Fix Haddock errors.
[ghc-hetmet.git] / includes / Storage.h
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 1998-2004
4  *
5  * External Storage Manger Interface
6  *
7  * ---------------------------------------------------------------------------*/
8
9 #ifndef STORAGE_H
10 #define STORAGE_H
11
12 #include <stddef.h>
13 #include "OSThreads.h"
14 #include "SMP.h"
15
16 /* -----------------------------------------------------------------------------
17  * Generational GC
18  *
19  * We support an arbitrary number of generations, with an arbitrary number
20  * of steps per generation.  Notes (in no particular order):
21  *
22  *       - all generations except the oldest should have two steps.  This gives
23  *         objects a decent chance to age before being promoted, and in
24  *         particular will ensure that we don't end up with too many
25  *         thunks being updated in older generations.
26  *
27  *       - the oldest generation has one step.  There's no point in aging
28  *         objects in the oldest generation.
29  *
30  *       - generation 0, step 0 (G0S0) is the allocation area.  It is given
31  *         a fixed set of blocks during initialisation, and these blocks
32  *         are never freed.
33  *
34  *       - during garbage collection, each step which is an evacuation
35  *         destination (i.e. all steps except G0S0) is allocated a to-space.
36  *         evacuated objects are allocated into the step's to-space until
37  *         GC is finished, when the original step's contents may be freed
38  *         and replaced by the to-space.
39  *
40  *       - the mutable-list is per-generation (not per-step).  G0 doesn't 
41  *         have one (since every garbage collection collects at least G0).
42  * 
43  *       - block descriptors contain pointers to both the step and the
44  *         generation that the block belongs to, for convenience.
45  *
46  *       - static objects are stored in per-generation lists.  See GC.c for
47  *         details of how we collect CAFs in the generational scheme.
48  *
49  *       - large objects are per-step, and are promoted in the same way
50  *         as small objects, except that we may allocate large objects into
51  *         generation 1 initially.
52  *
53  * ------------------------------------------------------------------------- */
54
55 typedef struct step_ {
56     unsigned int         no;            // step number in this generation
57     unsigned int         abs_no;        // absolute step number
58
59     struct generation_ * gen;           // generation this step belongs to
60     unsigned int         gen_no;        // generation number (cached)
61
62     bdescr *             blocks;        // blocks in this step
63     unsigned int         n_blocks;      // number of blocks
64     unsigned int         n_words;       // number of words
65
66     struct step_ *       to;            // destination step for live objects
67
68     bdescr *             large_objects;  // large objects (doubly linked)
69     unsigned int         n_large_blocks; // no. of blocks used by large objs
70
71     StgTSO *             threads;       // threads in this step
72                                         // linked via global_link
73
74     // ------------------------------------
75     // Fields below are used during GC only
76
77     // During GC, if we are collecting this step, blocks and n_blocks
78     // are copied into the following two fields.  After GC, these blocks
79     // are freed.
80
81 #if defined(THREADED_RTS)
82     char pad[128];                      // make sure the following is
83                                         // on a separate cache line.
84     SpinLock     sync_todo;             // lock for todos
85     SpinLock     sync_large_objects;    // lock for large_objects
86                                         //    and scavenged_large_objects
87 #endif
88
89     int          mark;                  // mark (not copy)? (old gen only)
90     int          compact;               // compact (not sweep)? (old gen only)
91
92     bdescr *     old_blocks;            // bdescr of first from-space block
93     unsigned int n_old_blocks;          // number of blocks in from-space
94     unsigned int live_estimate;         // for sweeping: estimate of live data
95     
96     bdescr *     todos;                 // blocks waiting to be scavenged
97     bdescr *     todos_last;
98     unsigned int n_todos;               // count of above
99
100     bdescr *     part_blocks;           // partially-full scanned blocks
101     unsigned int n_part_blocks;         // count of above
102
103     bdescr *     scavenged_large_objects;  // live large objs after GC (d-link)
104     unsigned int n_scavenged_large_blocks; // size (not count) of above
105
106     bdescr *     bitmap;                // bitmap for compacting collection
107
108     StgTSO *     old_threads;
109
110 } step;
111
112
113 typedef struct generation_ {
114     unsigned int   no;                  // generation number
115     step *         steps;               // steps
116     unsigned int   n_steps;             // number of steps
117     unsigned int   max_blocks;          // max blocks in step 0
118     bdescr        *mut_list;            // mut objects in this gen (not G0)
119     
120     // stats information
121     unsigned int collections;
122     unsigned int par_collections;
123     unsigned int failed_promotions;
124
125     // temporary use during GC:
126     bdescr        *saved_mut_list;
127 } generation;
128
129 extern generation * RTS_VAR(generations);
130
131 extern generation * RTS_VAR(g0);
132 extern step * RTS_VAR(g0s0);
133 extern generation * RTS_VAR(oldest_gen);
134 extern step * RTS_VAR(all_steps);
135 extern nat RTS_VAR(total_steps);
136
137 /* -----------------------------------------------------------------------------
138    Initialisation / De-initialisation
139    -------------------------------------------------------------------------- */
140
141 extern void initStorage(void);
142 extern void exitStorage(void);
143 extern void freeStorage(void);
144
145 /* -----------------------------------------------------------------------------
146    Generic allocation
147
148    StgPtr allocateInGen(generation *g, nat n)
149                                 Allocates a chunk of contiguous store
150                                 n words long in generation g,
151                                 returning a pointer to the first word.
152                                 Always succeeds.
153                                 
154    StgPtr allocate(nat n)       Equaivalent to allocateInGen(g0)
155                                 
156    StgPtr allocateLocal(Capability *cap, nat n)
157                                 Allocates memory from the nursery in
158                                 the current Capability.  This can be
159                                 done without taking a global lock,
160                                 unlike allocate().
161
162    StgPtr allocatePinned(nat n) Allocates a chunk of contiguous store
163                                 n words long, which is at a fixed
164                                 address (won't be moved by GC).  
165                                 Returns a pointer to the first word.
166                                 Always succeeds.
167                                 
168                                 NOTE: the GC can't in general handle
169                                 pinned objects, so allocatePinned()
170                                 can only be used for ByteArrays at the
171                                 moment.
172
173                                 Don't forget to TICK_ALLOC_XXX(...)
174                                 after calling allocate or
175                                 allocatePinned, for the
176                                 benefit of the ticky-ticky profiler.
177
178    rtsBool doYouWantToGC(void)  Returns True if the storage manager is
179                                 ready to perform a GC, False otherwise.
180
181    lnat  allocatedBytes(void)  Returns the number of bytes allocated
182                                 via allocate() since the last GC.
183                                 Used in the reporting of statistics.
184
185    -------------------------------------------------------------------------- */
186
187 extern StgPtr  allocate        ( nat n );
188 extern StgPtr  allocateInGen   ( generation *g, nat n );
189 extern StgPtr  allocateLocal   ( Capability *cap, nat n );
190 extern StgPtr  allocatePinned  ( nat n );
191 extern lnat    allocatedBytes  ( void );
192
193 extern bdescr * RTS_VAR(small_alloc_list);
194 extern bdescr * RTS_VAR(large_alloc_list);
195 extern bdescr * RTS_VAR(pinned_object_block);
196
197 extern nat RTS_VAR(alloc_blocks);
198 extern nat RTS_VAR(alloc_blocks_lim);
199
200 INLINE_HEADER rtsBool
201 doYouWantToGC( void )
202 {
203   return (alloc_blocks >= alloc_blocks_lim);
204 }
205
206 /* memory allocator for executable memory */
207 extern void *allocateExec (nat bytes);
208 extern void freeExec (void *p);
209
210 /* for splitting blocks groups in two */
211 extern bdescr * splitLargeBlock (bdescr *bd, nat blocks);
212
213 /* -----------------------------------------------------------------------------
214    Performing Garbage Collection
215
216    GarbageCollect(get_roots)    Performs a garbage collection.  
217                                 'get_roots' is called to find all the 
218                                 roots that the system knows about.
219
220
221    -------------------------------------------------------------------------- */
222
223 extern void GarbageCollect(rtsBool force_major_gc);
224
225 /* -----------------------------------------------------------------------------
226    Generational garbage collection support
227
228    recordMutable(StgPtr p)       Informs the garbage collector that a
229                                  previously immutable object has
230                                  become (permanently) mutable.  Used
231                                  by thawArray and similar.
232
233    updateWithIndirection(p1,p2)  Updates the object at p1 with an
234                                  indirection pointing to p2.  This is
235                                  normally called for objects in an old
236                                  generation (>0) when they are updated.
237
238    updateWithPermIndirection(p1,p2)  As above but uses a permanent indir.
239
240    -------------------------------------------------------------------------- */
241
242 /*
243  * Storage manager mutex
244  */
245 #if defined(THREADED_RTS)
246 extern Mutex sm_mutex;
247 extern Mutex atomic_modify_mutvar_mutex;
248 extern SpinLock recordMutableGen_sync;
249 #endif
250
251 #if defined(THREADED_RTS)
252 #define ACQUIRE_SM_LOCK   ACQUIRE_LOCK(&sm_mutex);
253 #define RELEASE_SM_LOCK   RELEASE_LOCK(&sm_mutex);
254 #define ASSERT_SM_LOCK()  ASSERT_LOCK_HELD(&sm_mutex);
255 #else
256 #define ACQUIRE_SM_LOCK
257 #define RELEASE_SM_LOCK
258 #define ASSERT_SM_LOCK()
259 #endif
260
261 INLINE_HEADER void
262 recordMutableGen(StgClosure *p, generation *gen)
263 {
264     bdescr *bd;
265
266     bd = gen->mut_list;
267     if (bd->free >= bd->start + BLOCK_SIZE_W) {
268         bdescr *new_bd;
269         new_bd = allocBlock();
270         new_bd->link = bd;
271         bd = new_bd;
272         gen->mut_list = bd;
273     }
274     *bd->free++ = (StgWord)p;
275
276 }
277
278 INLINE_HEADER void
279 recordMutableGenLock(StgClosure *p, generation *gen)
280 {
281     ACQUIRE_SM_LOCK;
282     recordMutableGen(p,gen);
283     RELEASE_SM_LOCK;
284 }
285
286 extern bdescr *allocBlock_sync(void);
287
288 // Version of recordMutableGen() for use in parallel GC.  The same as
289 // recordMutableGen(), except that we surround it with a spinlock and
290 // call the spinlock version of allocBlock().
291 INLINE_HEADER void
292 recordMutableGen_GC(StgClosure *p, generation *gen)
293 {
294     bdescr *bd;
295
296     ACQUIRE_SPIN_LOCK(&recordMutableGen_sync);
297
298     bd = gen->mut_list;
299     if (bd->free >= bd->start + BLOCK_SIZE_W) {
300         bdescr *new_bd;
301         new_bd = allocBlock_sync();
302         new_bd->link = bd;
303         bd = new_bd;
304         gen->mut_list = bd;
305     }
306     *bd->free++ = (StgWord)p;
307
308     RELEASE_SPIN_LOCK(&recordMutableGen_sync);
309 }
310
311 INLINE_HEADER void
312 recordMutable(StgClosure *p)
313 {
314     bdescr *bd;
315     ASSERT(closure_MUTABLE(p));
316     bd = Bdescr((P_)p);
317     if (bd->gen_no > 0) recordMutableGen(p, &RTS_DEREF(generations)[bd->gen_no]);
318 }
319
320 INLINE_HEADER void
321 recordMutableLock(StgClosure *p)
322 {
323     ACQUIRE_SM_LOCK;
324     recordMutable(p);
325     RELEASE_SM_LOCK;
326 }
327
328 /* -----------------------------------------------------------------------------
329    The CAF table - used to let us revert CAFs in GHCi
330    -------------------------------------------------------------------------- */
331
332 /* set to disable CAF garbage collection in GHCi. */
333 /* (needed when dynamic libraries are used). */
334 extern rtsBool keepCAFs;
335
336 /* -----------------------------------------------------------------------------
337    This is the write barrier for MUT_VARs, a.k.a. IORefs.  A
338    MUT_VAR_CLEAN object is not on the mutable list; a MUT_VAR_DIRTY
339    is.  When written to, a MUT_VAR_CLEAN turns into a MUT_VAR_DIRTY
340    and is put on the mutable list.
341    -------------------------------------------------------------------------- */
342
343 void dirty_MUT_VAR(StgRegTable *reg, StgClosure *p);
344
345 /* -----------------------------------------------------------------------------
346    DEBUGGING predicates for pointers
347
348    LOOKS_LIKE_INFO_PTR(p)    returns False if p is definitely not an info ptr
349    LOOKS_LIKE_CLOSURE_PTR(p) returns False if p is definitely not a closure ptr
350
351    These macros are complete but not sound.  That is, they might
352    return false positives.  Do not rely on them to distinguish info
353    pointers from closure pointers, for example.
354
355    We don't use address-space predicates these days, for portability
356    reasons, and the fact that code/data can be scattered about the
357    address space in a dynamically-linked environment.  Our best option
358    is to look at the alleged info table and see whether it seems to
359    make sense...
360    -------------------------------------------------------------------------- */
361
362 #define LOOKS_LIKE_INFO_PTR(p) \
363     (p && (IS_FORWARDING_PTR(p) || LOOKS_LIKE_INFO_PTR_NOT_NULL(p)))
364
365 #define LOOKS_LIKE_INFO_PTR_NOT_NULL(p) \
366    (((StgInfoTable *)(INFO_PTR_TO_STRUCT(p)))->type != INVALID_OBJECT && \
367     ((StgInfoTable *)(INFO_PTR_TO_STRUCT(p)))->type < N_CLOSURE_TYPES)
368
369 #define LOOKS_LIKE_CLOSURE_PTR(p) \
370   (LOOKS_LIKE_INFO_PTR((UNTAG_CLOSURE((StgClosure *)(p)))->header.info))
371
372 /* -----------------------------------------------------------------------------
373    Macros for calculating how big a closure will be (used during allocation)
374    -------------------------------------------------------------------------- */
375
376 INLINE_HEADER StgOffset PAP_sizeW   ( nat n_args )
377 { return sizeofW(StgPAP) + n_args; }
378
379 INLINE_HEADER StgOffset AP_sizeW   ( nat n_args )
380 { return sizeofW(StgAP) + n_args; }
381
382 INLINE_HEADER StgOffset AP_STACK_sizeW ( nat size )
383 { return sizeofW(StgAP_STACK) + size; }
384
385 INLINE_HEADER StgOffset CONSTR_sizeW( nat p, nat np )
386 { return sizeofW(StgHeader) + p + np; }
387
388 INLINE_HEADER StgOffset THUNK_SELECTOR_sizeW ( void )
389 { return sizeofW(StgSelector); }
390
391 INLINE_HEADER StgOffset BLACKHOLE_sizeW ( void )
392 { return sizeofW(StgHeader)+MIN_PAYLOAD_SIZE; }
393
394 /* --------------------------------------------------------------------------
395    Sizes of closures
396    ------------------------------------------------------------------------*/
397
398 INLINE_HEADER StgOffset sizeW_fromITBL( const StgInfoTable* itbl ) 
399 { return sizeofW(StgClosure) 
400        + sizeofW(StgPtr)  * itbl->layout.payload.ptrs 
401        + sizeofW(StgWord) * itbl->layout.payload.nptrs; }
402
403 INLINE_HEADER StgOffset thunk_sizeW_fromITBL( const StgInfoTable* itbl ) 
404 { return sizeofW(StgThunk) 
405        + sizeofW(StgPtr)  * itbl->layout.payload.ptrs 
406        + sizeofW(StgWord) * itbl->layout.payload.nptrs; }
407
408 INLINE_HEADER StgOffset ap_stack_sizeW( StgAP_STACK* x )
409 { return AP_STACK_sizeW(x->size); }
410
411 INLINE_HEADER StgOffset ap_sizeW( StgAP* x )
412 { return AP_sizeW(x->n_args); }
413
414 INLINE_HEADER StgOffset pap_sizeW( StgPAP* x )
415 { return PAP_sizeW(x->n_args); }
416
417 INLINE_HEADER StgOffset arr_words_sizeW( StgArrWords* x )
418 { return sizeofW(StgArrWords) + x->words; }
419
420 INLINE_HEADER StgOffset mut_arr_ptrs_sizeW( StgMutArrPtrs* x )
421 { return sizeofW(StgMutArrPtrs) + x->ptrs; }
422
423 INLINE_HEADER StgWord tso_sizeW ( StgTSO *tso )
424 { return TSO_STRUCT_SIZEW + tso->stack_size; }
425
426 INLINE_HEADER StgWord bco_sizeW ( StgBCO *bco )
427 { return bco->size; }
428
429 INLINE_HEADER nat
430 closure_sizeW_ (StgClosure *p, StgInfoTable *info)
431 {
432     switch (info->type) {
433     case THUNK_0_1:
434     case THUNK_1_0:
435         return sizeofW(StgThunk) + 1;
436     case FUN_0_1:
437     case CONSTR_0_1:
438     case FUN_1_0:
439     case CONSTR_1_0:
440         return sizeofW(StgHeader) + 1;
441     case THUNK_0_2:
442     case THUNK_1_1:
443     case THUNK_2_0:
444         return sizeofW(StgThunk) + 2;
445     case FUN_0_2:
446     case CONSTR_0_2:
447     case FUN_1_1:
448     case CONSTR_1_1:
449     case FUN_2_0:
450     case CONSTR_2_0:
451         return sizeofW(StgHeader) + 2;
452     case THUNK:
453         return thunk_sizeW_fromITBL(info);
454     case THUNK_SELECTOR:
455         return THUNK_SELECTOR_sizeW();
456     case AP_STACK:
457         return ap_stack_sizeW((StgAP_STACK *)p);
458     case AP:
459         return ap_sizeW((StgAP *)p);
460     case PAP:
461         return pap_sizeW((StgPAP *)p);
462     case IND:
463     case IND_PERM:
464     case IND_OLDGEN:
465     case IND_OLDGEN_PERM:
466         return sizeofW(StgInd);
467     case ARR_WORDS:
468         return arr_words_sizeW((StgArrWords *)p);
469     case MUT_ARR_PTRS_CLEAN:
470     case MUT_ARR_PTRS_DIRTY:
471     case MUT_ARR_PTRS_FROZEN:
472     case MUT_ARR_PTRS_FROZEN0:
473         return mut_arr_ptrs_sizeW((StgMutArrPtrs*)p);
474     case TSO:
475         return tso_sizeW((StgTSO *)p);
476     case BCO:
477         return bco_sizeW((StgBCO *)p);
478     case TVAR_WATCH_QUEUE:
479         return sizeofW(StgTVarWatchQueue);
480     case TVAR:
481         return sizeofW(StgTVar);
482     case TREC_CHUNK:
483         return sizeofW(StgTRecChunk);
484     case TREC_HEADER:
485         return sizeofW(StgTRecHeader);
486     case ATOMIC_INVARIANT:
487         return sizeofW(StgAtomicInvariant);
488     case INVARIANT_CHECK_QUEUE:
489         return sizeofW(StgInvariantCheckQueue);
490     default:
491         return sizeW_fromITBL(info);
492     }
493 }
494
495 // The definitive way to find the size, in words, of a heap-allocated closure
496 INLINE_HEADER nat
497 closure_sizeW (StgClosure *p)
498 {
499     return closure_sizeW_(p, get_itbl(p));
500 }
501
502 /* -----------------------------------------------------------------------------
503    Sizes of stack frames
504    -------------------------------------------------------------------------- */
505
506 INLINE_HEADER StgWord stack_frame_sizeW( StgClosure *frame )
507 {
508     StgRetInfoTable *info;
509
510     info = get_ret_itbl(frame);
511     switch (info->i.type) {
512
513     case RET_DYN:
514     {
515         StgRetDyn *dyn = (StgRetDyn *)frame;
516         return  sizeofW(StgRetDyn) + RET_DYN_BITMAP_SIZE + 
517             RET_DYN_NONPTR_REGS_SIZE +
518             RET_DYN_PTRS(dyn->liveness) + RET_DYN_NONPTRS(dyn->liveness);
519     }
520             
521     case RET_FUN:
522         return sizeofW(StgRetFun) + ((StgRetFun *)frame)->size;
523
524     case RET_BIG:
525         return 1 + GET_LARGE_BITMAP(&info->i)->size;
526
527     case RET_BCO:
528         return 2 + BCO_BITMAP_SIZE((StgBCO *)((P_)frame)[1]);
529
530     default:
531         return 1 + BITMAP_SIZE(info->i.layout.bitmap);
532     }
533 }
534
535 /* -----------------------------------------------------------------------------
536    Nursery manipulation
537    -------------------------------------------------------------------------- */
538
539 extern void     allocNurseries       ( void );
540 extern void     resetNurseries       ( void );
541 extern void     resizeNurseries      ( nat blocks );
542 extern void     resizeNurseriesFixed ( nat blocks );
543 extern lnat     countNurseryBlocks   ( void );
544
545
546 /* -----------------------------------------------------------------------------
547    Functions from GC.c 
548    -------------------------------------------------------------------------- */
549
550 typedef void (*evac_fn)(void *user, StgClosure **root);
551
552 extern void         threadPaused ( Capability *cap, StgTSO * );
553 extern StgClosure * isAlive      ( StgClosure *p );
554 extern void         markCAFs     ( evac_fn evac, void *user );
555 extern void         GetRoots     ( evac_fn evac, void *user );
556
557 /* -----------------------------------------------------------------------------
558    Stats 'n' DEBUG stuff
559    -------------------------------------------------------------------------- */
560
561 extern ullong RTS_VAR(total_allocated);
562
563 extern lnat calcAllocated  ( void );
564 extern lnat calcLiveBlocks ( void );
565 extern lnat calcLiveWords  ( void );
566 extern lnat countOccupied  ( bdescr *bd );
567 extern lnat calcNeeded     ( void );
568
569 #if defined(DEBUG)
570 extern void memInventory(rtsBool show);
571 extern void checkSanity(void);
572 extern nat  countBlocks(bdescr *);
573 extern void checkNurserySanity( step *stp );
574 #endif
575
576 #if defined(DEBUG)
577 void printMutOnceList(generation *gen);
578 void printMutableList(generation *gen);
579 #endif
580
581 /* ----------------------------------------------------------------------------
582    Storage manager internal APIs and globals
583    ------------------------------------------------------------------------- */
584
585 #define END_OF_STATIC_LIST stgCast(StgClosure*,1)
586
587 extern void newDynCAF(StgClosure *);
588
589 extern void move_TSO(StgTSO *src, StgTSO *dest);
590 extern StgTSO *relocate_stack(StgTSO *dest, ptrdiff_t diff);
591
592 extern StgWeak    * RTS_VAR(old_weak_ptr_list);
593 extern StgWeak    * RTS_VAR(weak_ptr_list);
594 extern StgClosure * RTS_VAR(caf_list);
595 extern StgClosure * RTS_VAR(revertible_caf_list);
596 extern StgTSO     * RTS_VAR(resurrected_threads);
597
598 #define IS_FORWARDING_PTR(p) ((((StgWord)p) & 1) != 0)
599 #define MK_FORWARDING_PTR(p) (((StgWord)p) | 1)
600 #define UN_FORWARDING_PTR(p) (((StgWord)p) - 1)
601
602 #endif /* STORAGE_H */