Fix #3461: protect the use of keepCAFs with #ifdef DYNAMIC
[ghc-hetmet.git] / rts / sm / Storage.c
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 1998-2008
4  *
5  * Storage manager front end
6  *
7  * Documentation on the architecture of the Storage Manager can be
8  * found in the online commentary:
9  * 
10  *   http://hackage.haskell.org/trac/ghc/wiki/Commentary/Rts/Storage
11  *
12  * ---------------------------------------------------------------------------*/
13
14 #include "PosixSource.h"
15 #include "Rts.h"
16
17 #include "Storage.h"
18 #include "RtsUtils.h"
19 #include "Stats.h"
20 #include "BlockAlloc.h"
21 #include "Weak.h"
22 #include "Sanity.h"
23 #include "Arena.h"
24 #include "Capability.h"
25 #include "Schedule.h"
26 #include "RetainerProfile.h"    // for counting memory blocks (memInventory)
27 #include "OSMem.h"
28 #include "Trace.h"
29 #include "GC.h"
30 #include "Evac.h"
31
32 #include <string.h>
33
34 #include "ffi.h"
35
36 /* 
37  * All these globals require sm_mutex to access in THREADED_RTS mode.
38  */
39 StgClosure    *caf_list         = NULL;
40 StgClosure    *revertible_caf_list = NULL;
41 rtsBool       keepCAFs;
42
43 bdescr *pinned_object_block;    /* allocate pinned objects into this block */
44 nat alloc_blocks;               /* number of allocate()d blocks since GC */
45 nat alloc_blocks_lim;           /* approximate limit on alloc_blocks */
46
47 static bdescr *exec_block;
48
49 generation *generations = NULL; /* all the generations */
50 generation *g0          = NULL; /* generation 0, for convenience */
51 generation *oldest_gen  = NULL; /* oldest generation, for convenience */
52 step *g0s0              = NULL; /* generation 0, step 0, for convenience */
53
54 nat total_steps         = 0;
55 step *all_steps         = NULL; /* single array of steps */
56
57 ullong total_allocated = 0;     /* total memory allocated during run */
58
59 nat n_nurseries         = 0;    /* == RtsFlags.ParFlags.nNodes, convenience */
60 step *nurseries         = NULL; /* array of nurseries, >1 only if THREADED_RTS */
61
62 #ifdef THREADED_RTS
63 /*
64  * Storage manager mutex:  protects all the above state from
65  * simultaneous access by two STG threads.
66  */
67 Mutex sm_mutex;
68 #endif
69
70 static void allocNurseries ( void );
71
72 static void
73 initStep (step *stp, int g, int s)
74 {
75     stp->no = s;
76     stp->abs_no = RtsFlags.GcFlags.steps * g + s;
77     stp->blocks = NULL;
78     stp->n_blocks = 0;
79     stp->n_words = 0;
80     stp->live_estimate = 0;
81     stp->old_blocks = NULL;
82     stp->n_old_blocks = 0;
83     stp->gen = &generations[g];
84     stp->gen_no = g;
85     stp->large_objects = NULL;
86     stp->n_large_blocks = 0;
87     stp->scavenged_large_objects = NULL;
88     stp->n_scavenged_large_blocks = 0;
89     stp->mark = 0;
90     stp->compact = 0;
91     stp->bitmap = NULL;
92 #ifdef THREADED_RTS
93     initSpinLock(&stp->sync_large_objects);
94 #endif
95     stp->threads = END_TSO_QUEUE;
96     stp->old_threads = END_TSO_QUEUE;
97 }
98
99 void
100 initStorage( void )
101 {
102   nat g, s;
103   generation *gen;
104
105   if (generations != NULL) {
106       // multi-init protection
107       return;
108   }
109
110   initMBlocks();
111
112   /* Sanity check to make sure the LOOKS_LIKE_ macros appear to be
113    * doing something reasonable.
114    */
115   /* We use the NOT_NULL variant or gcc warns that the test is always true */
116   ASSERT(LOOKS_LIKE_INFO_PTR_NOT_NULL((StgWord)&stg_BLACKHOLE_info));
117   ASSERT(LOOKS_LIKE_CLOSURE_PTR(&stg_dummy_ret_closure));
118   ASSERT(!HEAP_ALLOCED(&stg_dummy_ret_closure));
119   
120   if (RtsFlags.GcFlags.maxHeapSize != 0 &&
121       RtsFlags.GcFlags.heapSizeSuggestion > 
122       RtsFlags.GcFlags.maxHeapSize) {
123     RtsFlags.GcFlags.maxHeapSize = RtsFlags.GcFlags.heapSizeSuggestion;
124   }
125
126   if (RtsFlags.GcFlags.maxHeapSize != 0 &&
127       RtsFlags.GcFlags.minAllocAreaSize > 
128       RtsFlags.GcFlags.maxHeapSize) {
129       errorBelch("maximum heap size (-M) is smaller than minimum alloc area size (-A)");
130       RtsFlags.GcFlags.minAllocAreaSize = RtsFlags.GcFlags.maxHeapSize;
131   }
132
133   initBlockAllocator();
134   
135 #if defined(THREADED_RTS)
136   initMutex(&sm_mutex);
137 #endif
138
139   ACQUIRE_SM_LOCK;
140
141   /* allocate generation info array */
142   generations = (generation *)stgMallocBytes(RtsFlags.GcFlags.generations 
143                                              * sizeof(struct generation_),
144                                              "initStorage: gens");
145
146   /* allocate all the steps into an array.  It is important that we do
147      it this way, because we need the invariant that two step pointers
148      can be directly compared to see which is the oldest.
149      Remember that the last generation has only one step. */
150   total_steps = 1 + (RtsFlags.GcFlags.generations - 1) * RtsFlags.GcFlags.steps;
151   all_steps   = stgMallocBytes(total_steps * sizeof(struct step_),
152                                "initStorage: steps");
153
154   /* Initialise all generations */
155   for(g = 0; g < RtsFlags.GcFlags.generations; g++) {
156     gen = &generations[g];
157     gen->no = g;
158     gen->mut_list = allocBlock();
159     gen->collections = 0;
160     gen->par_collections = 0;
161     gen->failed_promotions = 0;
162     gen->max_blocks = 0;
163   }
164
165   /* A couple of convenience pointers */
166   g0 = &generations[0];
167   oldest_gen = &generations[RtsFlags.GcFlags.generations-1];
168
169   /* Allocate step structures in each generation */
170   if (RtsFlags.GcFlags.generations > 1) {
171     /* Only for multiple-generations */
172
173     /* Oldest generation: one step */
174     oldest_gen->n_steps = 1;
175     oldest_gen->steps   = all_steps + (RtsFlags.GcFlags.generations - 1)
176                                       * RtsFlags.GcFlags.steps;
177
178     /* set up all except the oldest generation with 2 steps */
179     for(g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
180       generations[g].n_steps = RtsFlags.GcFlags.steps;
181       generations[g].steps   = all_steps + g * RtsFlags.GcFlags.steps;
182     }
183     
184   } else {
185     /* single generation, i.e. a two-space collector */
186     g0->n_steps = 1;
187     g0->steps   = all_steps;
188   }
189
190 #ifdef THREADED_RTS
191   n_nurseries = n_capabilities;
192 #else
193   n_nurseries = 1;
194 #endif
195   nurseries = stgMallocBytes (n_nurseries * sizeof(struct step_),
196                               "initStorage: nurseries");
197
198   /* Initialise all steps */
199   for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
200     for (s = 0; s < generations[g].n_steps; s++) {
201         initStep(&generations[g].steps[s], g, s);
202     }
203   }
204   
205   for (s = 0; s < n_nurseries; s++) {
206       initStep(&nurseries[s], 0, s);
207   }
208   
209   /* Set up the destination pointers in each younger gen. step */
210   for (g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
211     for (s = 0; s < generations[g].n_steps-1; s++) {
212       generations[g].steps[s].to = &generations[g].steps[s+1];
213     }
214     generations[g].steps[s].to = &generations[g+1].steps[0];
215   }
216   oldest_gen->steps[0].to = &oldest_gen->steps[0];
217   
218   for (s = 0; s < n_nurseries; s++) {
219       nurseries[s].to = generations[0].steps[0].to;
220   }
221   
222   /* The oldest generation has one step. */
223   if (RtsFlags.GcFlags.compact || RtsFlags.GcFlags.sweep) {
224       if (RtsFlags.GcFlags.generations == 1) {
225           errorBelch("WARNING: compact/sweep is incompatible with -G1; disabled");
226       } else {
227           oldest_gen->steps[0].mark = 1;
228           if (RtsFlags.GcFlags.compact)
229               oldest_gen->steps[0].compact = 1;
230       }
231   }
232
233   generations[0].max_blocks = 0;
234   g0s0 = &generations[0].steps[0];
235
236   /* The allocation area.  Policy: keep the allocation area
237    * small to begin with, even if we have a large suggested heap
238    * size.  Reason: we're going to do a major collection first, and we
239    * don't want it to be a big one.  This vague idea is borne out by 
240    * rigorous experimental evidence.
241    */
242   allocNurseries();
243
244   weak_ptr_list = NULL;
245   caf_list = NULL;
246   revertible_caf_list = NULL;
247    
248   /* initialise the allocate() interface */
249   alloc_blocks = 0;
250   alloc_blocks_lim = RtsFlags.GcFlags.minAllocAreaSize;
251
252   exec_block = NULL;
253
254 #ifdef THREADED_RTS
255   initSpinLock(&gc_alloc_block_sync);
256   whitehole_spin = 0;
257 #endif
258
259   N = 0;
260
261   initGcThreads();
262
263   IF_DEBUG(gc, statDescribeGens());
264
265   RELEASE_SM_LOCK;
266 }
267
268 void
269 exitStorage (void)
270 {
271     stat_exit(calcAllocated());
272 }
273
274 void
275 freeStorage (void)
276 {
277     stgFree(g0s0); // frees all the steps
278     stgFree(generations);
279     freeAllMBlocks();
280 #if defined(THREADED_RTS)
281     closeMutex(&sm_mutex);
282 #endif
283     stgFree(nurseries);
284     freeGcThreads();
285 }
286
287 /* -----------------------------------------------------------------------------
288    CAF management.
289
290    The entry code for every CAF does the following:
291      
292       - builds a CAF_BLACKHOLE in the heap
293       - pushes an update frame pointing to the CAF_BLACKHOLE
294       - invokes UPD_CAF(), which:
295           - calls newCaf, below
296           - updates the CAF with a static indirection to the CAF_BLACKHOLE
297       
298    Why do we build a BLACKHOLE in the heap rather than just updating
299    the thunk directly?  It's so that we only need one kind of update
300    frame - otherwise we'd need a static version of the update frame too.
301
302    newCaf() does the following:
303        
304       - it puts the CAF on the oldest generation's mut-once list.
305         This is so that we can treat the CAF as a root when collecting
306         younger generations.
307
308    For GHCI, we have additional requirements when dealing with CAFs:
309
310       - we must *retain* all dynamically-loaded CAFs ever entered,
311         just in case we need them again.
312       - we must be able to *revert* CAFs that have been evaluated, to
313         their pre-evaluated form.
314
315       To do this, we use an additional CAF list.  When newCaf() is
316       called on a dynamically-loaded CAF, we add it to the CAF list
317       instead of the old-generation mutable list, and save away its
318       old info pointer (in caf->saved_info) for later reversion.
319
320       To revert all the CAFs, we traverse the CAF list and reset the
321       info pointer to caf->saved_info, then throw away the CAF list.
322       (see GC.c:revertCAFs()).
323
324       -- SDM 29/1/01
325
326    -------------------------------------------------------------------------- */
327
328 void
329 newCAF(StgClosure* caf)
330 {
331   ACQUIRE_SM_LOCK;
332
333 #ifdef DYNAMIC
334   if(keepCAFs)
335   {
336     // HACK:
337     // If we are in GHCi _and_ we are using dynamic libraries,
338     // then we can't redirect newCAF calls to newDynCAF (see below),
339     // so we make newCAF behave almost like newDynCAF.
340     // The dynamic libraries might be used by both the interpreted
341     // program and GHCi itself, so they must not be reverted.
342     // This also means that in GHCi with dynamic libraries, CAFs are not
343     // garbage collected. If this turns out to be a problem, we could
344     // do another hack here and do an address range test on caf to figure
345     // out whether it is from a dynamic library.
346     ((StgIndStatic *)caf)->saved_info  = (StgInfoTable *)caf->header.info;
347     ((StgIndStatic *)caf)->static_link = caf_list;
348     caf_list = caf;
349   }
350   else
351 #endif
352   {
353     /* Put this CAF on the mutable list for the old generation.
354     * This is a HACK - the IND_STATIC closure doesn't really have
355     * a mut_link field, but we pretend it has - in fact we re-use
356     * the STATIC_LINK field for the time being, because when we
357     * come to do a major GC we won't need the mut_link field
358     * any more and can use it as a STATIC_LINK.
359     */
360     ((StgIndStatic *)caf)->saved_info = NULL;
361     recordMutableGen(caf, oldest_gen->no);
362   }
363   
364   RELEASE_SM_LOCK;
365 }
366
367 // An alternate version of newCaf which is used for dynamically loaded
368 // object code in GHCi.  In this case we want to retain *all* CAFs in
369 // the object code, because they might be demanded at any time from an
370 // expression evaluated on the command line.
371 // Also, GHCi might want to revert CAFs, so we add these to the
372 // revertible_caf_list.
373 //
374 // The linker hackily arranges that references to newCaf from dynamic
375 // code end up pointing to newDynCAF.
376 void
377 newDynCAF(StgClosure *caf)
378 {
379     ACQUIRE_SM_LOCK;
380
381     ((StgIndStatic *)caf)->saved_info  = (StgInfoTable *)caf->header.info;
382     ((StgIndStatic *)caf)->static_link = revertible_caf_list;
383     revertible_caf_list = caf;
384
385     RELEASE_SM_LOCK;
386 }
387
388 /* -----------------------------------------------------------------------------
389    Nursery management.
390    -------------------------------------------------------------------------- */
391
392 static bdescr *
393 allocNursery (step *stp, bdescr *tail, nat blocks)
394 {
395     bdescr *bd;
396     nat i;
397
398     // Allocate a nursery: we allocate fresh blocks one at a time and
399     // cons them on to the front of the list, not forgetting to update
400     // the back pointer on the tail of the list to point to the new block.
401     for (i=0; i < blocks; i++) {
402         // @LDV profiling
403         /*
404           processNursery() in LdvProfile.c assumes that every block group in
405           the nursery contains only a single block. So, if a block group is
406           given multiple blocks, change processNursery() accordingly.
407         */
408         bd = allocBlock();
409         bd->link = tail;
410         // double-link the nursery: we might need to insert blocks
411         if (tail != NULL) {
412             tail->u.back = bd;
413         }
414         bd->step = stp;
415         bd->gen_no = 0;
416         bd->flags = 0;
417         bd->free = bd->start;
418         tail = bd;
419     }
420     tail->u.back = NULL;
421     return tail;
422 }
423
424 static void
425 assignNurseriesToCapabilities (void)
426 {
427 #ifdef THREADED_RTS
428     nat i;
429
430     for (i = 0; i < n_nurseries; i++) {
431         capabilities[i].r.rNursery        = &nurseries[i];
432         capabilities[i].r.rCurrentNursery = nurseries[i].blocks;
433         capabilities[i].r.rCurrentAlloc   = NULL;
434     }
435 #else /* THREADED_RTS */
436     MainCapability.r.rNursery        = &nurseries[0];
437     MainCapability.r.rCurrentNursery = nurseries[0].blocks;
438     MainCapability.r.rCurrentAlloc   = NULL;
439 #endif
440 }
441
442 static void
443 allocNurseries( void )
444
445     nat i;
446
447     for (i = 0; i < n_nurseries; i++) {
448         nurseries[i].blocks = 
449             allocNursery(&nurseries[i], NULL, 
450                          RtsFlags.GcFlags.minAllocAreaSize);
451         nurseries[i].n_blocks    = RtsFlags.GcFlags.minAllocAreaSize;
452         nurseries[i].old_blocks   = NULL;
453         nurseries[i].n_old_blocks = 0;
454     }
455     assignNurseriesToCapabilities();
456 }
457       
458 void
459 resetNurseries( void )
460 {
461     nat i;
462     bdescr *bd;
463     step *stp;
464
465     for (i = 0; i < n_nurseries; i++) {
466         stp = &nurseries[i];
467         for (bd = stp->blocks; bd; bd = bd->link) {
468             bd->free = bd->start;
469             ASSERT(bd->gen_no == 0);
470             ASSERT(bd->step == stp);
471             IF_DEBUG(sanity,memset(bd->start, 0xaa, BLOCK_SIZE));
472         }
473     }
474     assignNurseriesToCapabilities();
475 }
476
477 lnat
478 countNurseryBlocks (void)
479 {
480     nat i;
481     lnat blocks = 0;
482
483     for (i = 0; i < n_nurseries; i++) {
484         blocks += nurseries[i].n_blocks;
485     }
486     return blocks;
487 }
488
489 static void
490 resizeNursery ( step *stp, nat blocks )
491 {
492   bdescr *bd;
493   nat nursery_blocks;
494
495   nursery_blocks = stp->n_blocks;
496   if (nursery_blocks == blocks) return;
497
498   if (nursery_blocks < blocks) {
499       debugTrace(DEBUG_gc, "increasing size of nursery to %d blocks", 
500                  blocks);
501     stp->blocks = allocNursery(stp, stp->blocks, blocks-nursery_blocks);
502   } 
503   else {
504     bdescr *next_bd;
505     
506     debugTrace(DEBUG_gc, "decreasing size of nursery to %d blocks", 
507                blocks);
508
509     bd = stp->blocks;
510     while (nursery_blocks > blocks) {
511         next_bd = bd->link;
512         next_bd->u.back = NULL;
513         nursery_blocks -= bd->blocks; // might be a large block
514         freeGroup(bd);
515         bd = next_bd;
516     }
517     stp->blocks = bd;
518     // might have gone just under, by freeing a large block, so make
519     // up the difference.
520     if (nursery_blocks < blocks) {
521         stp->blocks = allocNursery(stp, stp->blocks, blocks-nursery_blocks);
522     }
523   }
524   
525   stp->n_blocks = blocks;
526   ASSERT(countBlocks(stp->blocks) == stp->n_blocks);
527 }
528
529 // 
530 // Resize each of the nurseries to the specified size.
531 //
532 void
533 resizeNurseriesFixed (nat blocks)
534 {
535     nat i;
536     for (i = 0; i < n_nurseries; i++) {
537         resizeNursery(&nurseries[i], blocks);
538     }
539 }
540
541 // 
542 // Resize the nurseries to the total specified size.
543 //
544 void
545 resizeNurseries (nat blocks)
546 {
547     // If there are multiple nurseries, then we just divide the number
548     // of available blocks between them.
549     resizeNurseriesFixed(blocks / n_nurseries);
550 }
551
552
553 /* -----------------------------------------------------------------------------
554    move_TSO is called to update the TSO structure after it has been
555    moved from one place to another.
556    -------------------------------------------------------------------------- */
557
558 void
559 move_TSO (StgTSO *src, StgTSO *dest)
560 {
561     ptrdiff_t diff;
562
563     // relocate the stack pointer... 
564     diff = (StgPtr)dest - (StgPtr)src; // In *words* 
565     dest->sp = (StgPtr)dest->sp + diff;
566 }
567
568 /* -----------------------------------------------------------------------------
569    The allocate() interface
570
571    allocateInGen() function allocates memory directly into a specific
572    generation.  It always succeeds, and returns a chunk of memory n
573    words long.  n can be larger than the size of a block if necessary,
574    in which case a contiguous block group will be allocated.
575
576    allocate(n) is equivalent to allocateInGen(g0).
577    -------------------------------------------------------------------------- */
578
579 StgPtr
580 allocateInGen (generation *g, lnat n)
581 {
582     step *stp;
583     bdescr *bd;
584     StgPtr ret;
585
586     ACQUIRE_SM_LOCK;
587     
588     TICK_ALLOC_HEAP_NOCTR(n);
589     CCS_ALLOC(CCCS,n);
590
591     stp = &g->steps[0];
592
593     if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_))
594     {
595         lnat req_blocks =  (lnat)BLOCK_ROUND_UP(n*sizeof(W_)) / BLOCK_SIZE;
596
597         // Attempting to allocate an object larger than maxHeapSize
598         // should definitely be disallowed.  (bug #1791)
599         if (RtsFlags.GcFlags.maxHeapSize > 0 && 
600             req_blocks >= RtsFlags.GcFlags.maxHeapSize) {
601             heapOverflow();
602             // heapOverflow() doesn't exit (see #2592), but we aren't
603             // in a position to do a clean shutdown here: we
604             // either have to allocate the memory or exit now.
605             // Allocating the memory would be bad, because the user
606             // has requested that we not exceed maxHeapSize, so we
607             // just exit.
608             stg_exit(EXIT_HEAPOVERFLOW);
609         }
610
611         bd = allocGroup(req_blocks);
612         dbl_link_onto(bd, &stp->large_objects);
613         stp->n_large_blocks += bd->blocks; // might be larger than req_blocks
614         alloc_blocks += bd->blocks;
615         bd->gen_no  = g->no;
616         bd->step = stp;
617         bd->flags = BF_LARGE;
618         bd->free = bd->start + n;
619         ret = bd->start;
620     }
621     else
622     {
623         // small allocation (<LARGE_OBJECT_THRESHOLD) */
624         bd = stp->blocks;
625         if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
626             bd = allocBlock();
627             bd->gen_no = g->no;
628             bd->step = stp;
629             bd->flags = 0;
630             bd->link = stp->blocks;
631             stp->blocks = bd;
632             stp->n_blocks++;
633             alloc_blocks++;
634         }
635         ret = bd->free;
636         bd->free += n;
637     }
638
639     RELEASE_SM_LOCK;
640
641     return ret;
642 }
643
644 StgPtr
645 allocate (lnat n)
646 {
647     return allocateInGen(g0,n);
648 }
649
650 lnat
651 allocatedBytes( void )
652 {
653     lnat allocated;
654
655     allocated = alloc_blocks * BLOCK_SIZE_W;
656     if (pinned_object_block != NULL) {
657         allocated -= (pinned_object_block->start + BLOCK_SIZE_W) - 
658             pinned_object_block->free;
659     }
660         
661     return allocated;
662 }
663
664 // split N blocks off the front of the given bdescr, returning the
665 // new block group.  We treat the remainder as if it
666 // had been freshly allocated in generation 0.
667 bdescr *
668 splitLargeBlock (bdescr *bd, nat blocks)
669 {
670     bdescr *new_bd;
671
672     // subtract the original number of blocks from the counter first
673     bd->step->n_large_blocks -= bd->blocks;
674
675     new_bd = splitBlockGroup (bd, blocks);
676
677     dbl_link_onto(new_bd, &g0s0->large_objects);
678     g0s0->n_large_blocks += new_bd->blocks;
679     new_bd->gen_no  = g0s0->no;
680     new_bd->step    = g0s0;
681     new_bd->flags   = BF_LARGE;
682     new_bd->free    = bd->free;
683     ASSERT(new_bd->free <= new_bd->start + new_bd->blocks * BLOCK_SIZE_W);
684
685     // add the new number of blocks to the counter.  Due to the gaps
686     // for block descriptor, new_bd->blocks + bd->blocks might not be
687     // equal to the original bd->blocks, which is why we do it this way.
688     bd->step->n_large_blocks += bd->blocks;
689
690     return new_bd;
691 }
692
693 /* -----------------------------------------------------------------------------
694    allocateLocal()
695
696    This allocates memory in the current thread - it is intended for
697    use primarily from STG-land where we have a Capability.  It is
698    better than allocate() because it doesn't require taking the
699    sm_mutex lock in the common case.
700
701    Memory is allocated directly from the nursery if possible (but not
702    from the current nursery block, so as not to interfere with
703    Hp/HpLim).
704    -------------------------------------------------------------------------- */
705
706 StgPtr
707 allocateLocal (Capability *cap, lnat n)
708 {
709     bdescr *bd;
710     StgPtr p;
711
712     if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
713         return allocateInGen(g0,n);
714     }
715
716     /* small allocation (<LARGE_OBJECT_THRESHOLD) */
717
718     TICK_ALLOC_HEAP_NOCTR(n);
719     CCS_ALLOC(CCCS,n);
720     
721     bd = cap->r.rCurrentAlloc;
722     if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
723         
724         // The CurrentAlloc block is full, we need to find another
725         // one.  First, we try taking the next block from the
726         // nursery:
727         bd = cap->r.rCurrentNursery->link;
728         
729         if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
730             // The nursery is empty, or the next block is already
731             // full: allocate a fresh block (we can't fail here).
732             ACQUIRE_SM_LOCK;
733             bd = allocBlock();
734             cap->r.rNursery->n_blocks++;
735             RELEASE_SM_LOCK;
736             bd->gen_no = 0;
737             bd->step = cap->r.rNursery;
738             bd->flags = 0;
739             // NO: alloc_blocks++;
740             // calcAllocated() uses the size of the nursery, and we've
741             // already bumpted nursery->n_blocks above.  We'll GC
742             // pretty quickly now anyway, because MAYBE_GC() will
743             // notice that CurrentNursery->link is NULL.
744         } else {
745             // we have a block in the nursery: take it and put
746             // it at the *front* of the nursery list, and use it
747             // to allocate() from.
748             cap->r.rCurrentNursery->link = bd->link;
749             if (bd->link != NULL) {
750                 bd->link->u.back = cap->r.rCurrentNursery;
751             }
752         }
753         dbl_link_onto(bd, &cap->r.rNursery->blocks);
754         cap->r.rCurrentAlloc = bd;
755         IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
756     }
757     p = bd->free;
758     bd->free += n;
759     return p;
760 }
761
762 /* ---------------------------------------------------------------------------
763    Allocate a fixed/pinned object.
764
765    We allocate small pinned objects into a single block, allocating a
766    new block when the current one overflows.  The block is chained
767    onto the large_object_list of generation 0 step 0.
768
769    NOTE: The GC can't in general handle pinned objects.  This
770    interface is only safe to use for ByteArrays, which have no
771    pointers and don't require scavenging.  It works because the
772    block's descriptor has the BF_LARGE flag set, so the block is
773    treated as a large object and chained onto various lists, rather
774    than the individual objects being copied.  However, when it comes
775    to scavenge the block, the GC will only scavenge the first object.
776    The reason is that the GC can't linearly scan a block of pinned
777    objects at the moment (doing so would require using the
778    mostly-copying techniques).  But since we're restricting ourselves
779    to pinned ByteArrays, not scavenging is ok.
780
781    This function is called by newPinnedByteArray# which immediately
782    fills the allocated memory with a MutableByteArray#.
783    ------------------------------------------------------------------------- */
784
785 StgPtr
786 allocatePinned( lnat n )
787 {
788     StgPtr p;
789     bdescr *bd = pinned_object_block;
790
791     // If the request is for a large object, then allocate()
792     // will give us a pinned object anyway.
793     if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
794         p = allocate(n);
795         Bdescr(p)->flags |= BF_PINNED;
796         return p;
797     }
798
799     ACQUIRE_SM_LOCK;
800     
801     TICK_ALLOC_HEAP_NOCTR(n);
802     CCS_ALLOC(CCCS,n);
803
804     // If we don't have a block of pinned objects yet, or the current
805     // one isn't large enough to hold the new object, allocate a new one.
806     if (bd == NULL || (bd->free + n) > (bd->start + BLOCK_SIZE_W)) {
807         pinned_object_block = bd = allocBlock();
808         dbl_link_onto(bd, &g0s0->large_objects);
809         g0s0->n_large_blocks++;
810         bd->gen_no = 0;
811         bd->step   = g0s0;
812         bd->flags  = BF_PINNED | BF_LARGE;
813         bd->free   = bd->start;
814         alloc_blocks++;
815     }
816
817     p = bd->free;
818     bd->free += n;
819     RELEASE_SM_LOCK;
820     return p;
821 }
822
823 /* -----------------------------------------------------------------------------
824    Write Barriers
825    -------------------------------------------------------------------------- */
826
827 /*
828    This is the write barrier for MUT_VARs, a.k.a. IORefs.  A
829    MUT_VAR_CLEAN object is not on the mutable list; a MUT_VAR_DIRTY
830    is.  When written to, a MUT_VAR_CLEAN turns into a MUT_VAR_DIRTY
831    and is put on the mutable list.
832 */
833 void
834 dirty_MUT_VAR(StgRegTable *reg, StgClosure *p)
835 {
836     Capability *cap = regTableToCapability(reg);
837     bdescr *bd;
838     if (p->header.info == &stg_MUT_VAR_CLEAN_info) {
839         p->header.info = &stg_MUT_VAR_DIRTY_info;
840         bd = Bdescr((StgPtr)p);
841         if (bd->gen_no > 0) recordMutableCap(p,cap,bd->gen_no);
842     }
843 }
844
845 // Setting a TSO's link field with a write barrier.
846 // It is *not* necessary to call this function when
847 //    * setting the link field to END_TSO_QUEUE
848 //    * putting a TSO on the blackhole_queue
849 //    * setting the link field of the currently running TSO, as it
850 //      will already be dirty.
851 void
852 setTSOLink (Capability *cap, StgTSO *tso, StgTSO *target)
853 {
854     bdescr *bd;
855     if (tso->dirty == 0 && (tso->flags & TSO_LINK_DIRTY) == 0) {
856         tso->flags |= TSO_LINK_DIRTY;
857         bd = Bdescr((StgPtr)tso);
858         if (bd->gen_no > 0) recordMutableCap((StgClosure*)tso,cap,bd->gen_no);
859     }
860     tso->_link = target;
861 }
862
863 void
864 dirty_TSO (Capability *cap, StgTSO *tso)
865 {
866     bdescr *bd;
867     if (tso->dirty == 0 && (tso->flags & TSO_LINK_DIRTY) == 0) {
868         bd = Bdescr((StgPtr)tso);
869         if (bd->gen_no > 0) recordMutableCap((StgClosure*)tso,cap,bd->gen_no);
870     }
871     tso->dirty = 1;
872 }
873
874 /*
875    This is the write barrier for MVARs.  An MVAR_CLEAN objects is not
876    on the mutable list; a MVAR_DIRTY is.  When written to, a
877    MVAR_CLEAN turns into a MVAR_DIRTY and is put on the mutable list.
878    The check for MVAR_CLEAN is inlined at the call site for speed,
879    this really does make a difference on concurrency-heavy benchmarks
880    such as Chaneneos and cheap-concurrency.
881 */
882 void
883 dirty_MVAR(StgRegTable *reg, StgClosure *p)
884 {
885     Capability *cap = regTableToCapability(reg);
886     bdescr *bd;
887     bd = Bdescr((StgPtr)p);
888     if (bd->gen_no > 0) recordMutableCap(p,cap,bd->gen_no);
889 }
890
891 /* -----------------------------------------------------------------------------
892  * Stats and stuff
893  * -------------------------------------------------------------------------- */
894
895 /* -----------------------------------------------------------------------------
896  * calcAllocated()
897  *
898  * Approximate how much we've allocated: number of blocks in the
899  * nursery + blocks allocated via allocate() - unused nusery blocks.
900  * This leaves a little slop at the end of each block, and doesn't
901  * take into account large objects (ToDo).
902  * -------------------------------------------------------------------------- */
903
904 lnat
905 calcAllocated( void )
906 {
907   nat allocated;
908   bdescr *bd;
909
910   allocated = allocatedBytes();
911   allocated += countNurseryBlocks() * BLOCK_SIZE_W;
912   
913   {
914 #ifdef THREADED_RTS
915   nat i;
916   for (i = 0; i < n_nurseries; i++) {
917       Capability *cap;
918       for ( bd = capabilities[i].r.rCurrentNursery->link; 
919             bd != NULL; bd = bd->link ) {
920           allocated -= BLOCK_SIZE_W;
921       }
922       cap = &capabilities[i];
923       if (cap->r.rCurrentNursery->free < 
924           cap->r.rCurrentNursery->start + BLOCK_SIZE_W) {
925           allocated -= (cap->r.rCurrentNursery->start + BLOCK_SIZE_W)
926               - cap->r.rCurrentNursery->free;
927       }
928   }
929 #else
930   bdescr *current_nursery = MainCapability.r.rCurrentNursery;
931
932   for ( bd = current_nursery->link; bd != NULL; bd = bd->link ) {
933       allocated -= BLOCK_SIZE_W;
934   }
935   if (current_nursery->free < current_nursery->start + BLOCK_SIZE_W) {
936       allocated -= (current_nursery->start + BLOCK_SIZE_W)
937           - current_nursery->free;
938   }
939 #endif
940   }
941
942   total_allocated += allocated;
943   return allocated;
944 }  
945
946 /* Approximate the amount of live data in the heap.  To be called just
947  * after garbage collection (see GarbageCollect()).
948  */
949 lnat 
950 calcLiveBlocks(void)
951 {
952   nat g, s;
953   lnat live = 0;
954   step *stp;
955
956   if (RtsFlags.GcFlags.generations == 1) {
957       return g0s0->n_large_blocks + g0s0->n_blocks;
958   }
959
960   for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
961     for (s = 0; s < generations[g].n_steps; s++) {
962       /* approximate amount of live data (doesn't take into account slop
963        * at end of each block).
964        */
965       if (g == 0 && s == 0) { 
966           continue; 
967       }
968       stp = &generations[g].steps[s];
969       live += stp->n_large_blocks + stp->n_blocks;
970     }
971   }
972   return live;
973 }
974
975 lnat
976 countOccupied(bdescr *bd)
977 {
978     lnat words;
979
980     words = 0;
981     for (; bd != NULL; bd = bd->link) {
982         ASSERT(bd->free <= bd->start + bd->blocks * BLOCK_SIZE_W);
983         words += bd->free - bd->start;
984     }
985     return words;
986 }
987
988 // Return an accurate count of the live data in the heap, excluding
989 // generation 0.
990 lnat
991 calcLiveWords(void)
992 {
993     nat g, s;
994     lnat live;
995     step *stp;
996     
997     if (RtsFlags.GcFlags.generations == 1) {
998         return g0s0->n_words + countOccupied(g0s0->large_objects);
999     }
1000     
1001     live = 0;
1002     for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1003         for (s = 0; s < generations[g].n_steps; s++) {
1004             if (g == 0 && s == 0) continue; 
1005             stp = &generations[g].steps[s];
1006             live += stp->n_words + countOccupied(stp->large_objects);
1007         } 
1008     }
1009     return live;
1010 }
1011
1012 /* Approximate the number of blocks that will be needed at the next
1013  * garbage collection.
1014  *
1015  * Assume: all data currently live will remain live.  Steps that will
1016  * be collected next time will therefore need twice as many blocks
1017  * since all the data will be copied.
1018  */
1019 extern lnat 
1020 calcNeeded(void)
1021 {
1022     lnat needed = 0;
1023     nat g, s;
1024     step *stp;
1025     
1026     for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1027         for (s = 0; s < generations[g].n_steps; s++) {
1028             if (g == 0 && s == 0) { continue; }
1029             stp = &generations[g].steps[s];
1030
1031             // we need at least this much space
1032             needed += stp->n_blocks + stp->n_large_blocks;
1033
1034             // any additional space needed to collect this gen next time?
1035             if (g == 0 || // always collect gen 0
1036                 (generations[g].steps[0].n_blocks +
1037                  generations[g].steps[0].n_large_blocks 
1038                  > generations[g].max_blocks)) {
1039                 // we will collect this gen next time
1040                 if (stp->mark) {
1041                     //  bitmap:
1042                     needed += stp->n_blocks / BITS_IN(W_);
1043                     //  mark stack:
1044                     needed += stp->n_blocks / 100;
1045                 }
1046                 if (stp->compact) {
1047                     continue; // no additional space needed for compaction
1048                 } else {
1049                     needed += stp->n_blocks;
1050                 }
1051             }
1052         }
1053     }
1054     return needed;
1055 }
1056
1057 /* ----------------------------------------------------------------------------
1058    Executable memory
1059
1060    Executable memory must be managed separately from non-executable
1061    memory.  Most OSs these days require you to jump through hoops to
1062    dynamically allocate executable memory, due to various security
1063    measures.
1064
1065    Here we provide a small memory allocator for executable memory.
1066    Memory is managed with a page granularity; we allocate linearly
1067    in the page, and when the page is emptied (all objects on the page
1068    are free) we free the page again, not forgetting to make it
1069    non-executable.
1070
1071    TODO: The inability to handle objects bigger than BLOCK_SIZE_W means that
1072          the linker cannot use allocateExec for loading object code files
1073          on Windows. Once allocateExec can handle larger objects, the linker
1074          should be modified to use allocateExec instead of VirtualAlloc.
1075    ------------------------------------------------------------------------- */
1076
1077 #if defined(linux_HOST_OS)
1078
1079 // On Linux we need to use libffi for allocating executable memory,
1080 // because it knows how to work around the restrictions put in place
1081 // by SELinux.
1082
1083 void *allocateExec (nat bytes, void **exec_ret)
1084 {
1085     void **ret, **exec;
1086     ACQUIRE_SM_LOCK;
1087     ret = ffi_closure_alloc (sizeof(void *) + (size_t)bytes, (void**)&exec);
1088     RELEASE_SM_LOCK;
1089     if (ret == NULL) return ret;
1090     *ret = ret; // save the address of the writable mapping, for freeExec().
1091     *exec_ret = exec + 1;
1092     return (ret + 1);
1093 }
1094
1095 // freeExec gets passed the executable address, not the writable address. 
1096 void freeExec (void *addr)
1097 {
1098     void *writable;
1099     writable = *((void**)addr - 1);
1100     ACQUIRE_SM_LOCK;
1101     ffi_closure_free (writable);
1102     RELEASE_SM_LOCK
1103 }
1104
1105 #else
1106
1107 void *allocateExec (nat bytes, void **exec_ret)
1108 {
1109     void *ret;
1110     nat n;
1111
1112     ACQUIRE_SM_LOCK;
1113
1114     // round up to words.
1115     n  = (bytes + sizeof(W_) + 1) / sizeof(W_);
1116
1117     if (n+1 > BLOCK_SIZE_W) {
1118         barf("allocateExec: can't handle large objects");
1119     }
1120
1121     if (exec_block == NULL || 
1122         exec_block->free + n + 1 > exec_block->start + BLOCK_SIZE_W) {
1123         bdescr *bd;
1124         lnat pagesize = getPageSize();
1125         bd = allocGroup(stg_max(1, pagesize / BLOCK_SIZE));
1126         debugTrace(DEBUG_gc, "allocate exec block %p", bd->start);
1127         bd->gen_no = 0;
1128         bd->flags = BF_EXEC;
1129         bd->link = exec_block;
1130         if (exec_block != NULL) {
1131             exec_block->u.back = bd;
1132         }
1133         bd->u.back = NULL;
1134         setExecutable(bd->start, bd->blocks * BLOCK_SIZE, rtsTrue);
1135         exec_block = bd;
1136     }
1137     *(exec_block->free) = n;  // store the size of this chunk
1138     exec_block->gen_no += n;  // gen_no stores the number of words allocated
1139     ret = exec_block->free + 1;
1140     exec_block->free += n + 1;
1141
1142     RELEASE_SM_LOCK
1143     *exec_ret = ret;
1144     return ret;
1145 }
1146
1147 void freeExec (void *addr)
1148 {
1149     StgPtr p = (StgPtr)addr - 1;
1150     bdescr *bd = Bdescr((StgPtr)p);
1151
1152     if ((bd->flags & BF_EXEC) == 0) {
1153         barf("freeExec: not executable");
1154     }
1155
1156     if (*(StgPtr)p == 0) {
1157         barf("freeExec: already free?");
1158     }
1159
1160     ACQUIRE_SM_LOCK;
1161
1162     bd->gen_no -= *(StgPtr)p;
1163     *(StgPtr)p = 0;
1164
1165     if (bd->gen_no == 0) {
1166         // Free the block if it is empty, but not if it is the block at
1167         // the head of the queue.
1168         if (bd != exec_block) {
1169             debugTrace(DEBUG_gc, "free exec block %p", bd->start);
1170             dbl_link_remove(bd, &exec_block);
1171             setExecutable(bd->start, bd->blocks * BLOCK_SIZE, rtsFalse);
1172             freeGroup(bd);
1173         } else {
1174             bd->free = bd->start;
1175         }
1176     }
1177
1178     RELEASE_SM_LOCK
1179 }    
1180
1181 #endif /* mingw32_HOST_OS */
1182
1183 /* -----------------------------------------------------------------------------
1184    Debugging
1185
1186    memInventory() checks for memory leaks by counting up all the
1187    blocks we know about and comparing that to the number of blocks
1188    allegedly floating around in the system.
1189    -------------------------------------------------------------------------- */
1190
1191 #ifdef DEBUG
1192
1193 // Useful for finding partially full blocks in gdb
1194 void findSlop(bdescr *bd);
1195 void findSlop(bdescr *bd)
1196 {
1197     lnat slop;
1198
1199     for (; bd != NULL; bd = bd->link) {
1200         slop = (bd->blocks * BLOCK_SIZE_W) - (bd->free - bd->start);
1201         if (slop > (1024/sizeof(W_))) {
1202             debugBelch("block at %p (bdescr %p) has %ldKB slop\n",
1203                        bd->start, bd, slop / (1024/sizeof(W_)));
1204         }
1205     }
1206 }
1207
1208 nat
1209 countBlocks(bdescr *bd)
1210 {
1211     nat n;
1212     for (n=0; bd != NULL; bd=bd->link) {
1213         n += bd->blocks;
1214     }
1215     return n;
1216 }
1217
1218 // (*1) Just like countBlocks, except that we adjust the count for a
1219 // megablock group so that it doesn't include the extra few blocks
1220 // that would be taken up by block descriptors in the second and
1221 // subsequent megablock.  This is so we can tally the count with the
1222 // number of blocks allocated in the system, for memInventory().
1223 static nat
1224 countAllocdBlocks(bdescr *bd)
1225 {
1226     nat n;
1227     for (n=0; bd != NULL; bd=bd->link) {
1228         n += bd->blocks;
1229         // hack for megablock groups: see (*1) above
1230         if (bd->blocks > BLOCKS_PER_MBLOCK) {
1231             n -= (MBLOCK_SIZE / BLOCK_SIZE - BLOCKS_PER_MBLOCK)
1232                 * (bd->blocks/(MBLOCK_SIZE/BLOCK_SIZE));
1233         }
1234     }
1235     return n;
1236 }
1237
1238 static lnat
1239 stepBlocks (step *stp)
1240 {
1241     ASSERT(countBlocks(stp->blocks) == stp->n_blocks);
1242     ASSERT(countBlocks(stp->large_objects) == stp->n_large_blocks);
1243     return stp->n_blocks + stp->n_old_blocks + 
1244             countAllocdBlocks(stp->large_objects);
1245 }
1246
1247 // If memInventory() calculates that we have a memory leak, this
1248 // function will try to find the block(s) that are leaking by marking
1249 // all the ones that we know about, and search through memory to find
1250 // blocks that are not marked.  In the debugger this can help to give
1251 // us a clue about what kind of block leaked.  In the future we might
1252 // annotate blocks with their allocation site to give more helpful
1253 // info.
1254 static void
1255 findMemoryLeak (void)
1256 {
1257   nat g, s, i;
1258   for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1259       for (i = 0; i < n_capabilities; i++) {
1260           markBlocks(capabilities[i].mut_lists[g]);
1261       }
1262       markBlocks(generations[g].mut_list);
1263       for (s = 0; s < generations[g].n_steps; s++) {
1264           markBlocks(generations[g].steps[s].blocks);
1265           markBlocks(generations[g].steps[s].large_objects);
1266       }
1267   }
1268
1269   for (i = 0; i < n_nurseries; i++) {
1270       markBlocks(nurseries[i].blocks);
1271       markBlocks(nurseries[i].large_objects);
1272   }
1273
1274 #ifdef PROFILING
1275   // TODO:
1276   // if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER) {
1277   //    markRetainerBlocks();
1278   // }
1279 #endif
1280
1281   // count the blocks allocated by the arena allocator
1282   // TODO:
1283   // markArenaBlocks();
1284
1285   // count the blocks containing executable memory
1286   markBlocks(exec_block);
1287
1288   reportUnmarkedBlocks();
1289 }
1290
1291
1292 void
1293 memInventory (rtsBool show)
1294 {
1295   nat g, s, i;
1296   step *stp;
1297   lnat gen_blocks[RtsFlags.GcFlags.generations];
1298   lnat nursery_blocks, retainer_blocks,
1299        arena_blocks, exec_blocks;
1300   lnat live_blocks = 0, free_blocks = 0;
1301   rtsBool leak;
1302
1303   // count the blocks we current have
1304
1305   for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1306       gen_blocks[g] = 0;
1307       for (i = 0; i < n_capabilities; i++) {
1308           gen_blocks[g] += countBlocks(capabilities[i].mut_lists[g]);
1309       }   
1310       gen_blocks[g] += countAllocdBlocks(generations[g].mut_list);
1311       for (s = 0; s < generations[g].n_steps; s++) {
1312           stp = &generations[g].steps[s];
1313           gen_blocks[g] += stepBlocks(stp);
1314       }
1315   }
1316
1317   nursery_blocks = 0;
1318   for (i = 0; i < n_nurseries; i++) {
1319       nursery_blocks += stepBlocks(&nurseries[i]);
1320   }
1321
1322   retainer_blocks = 0;
1323 #ifdef PROFILING
1324   if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER) {
1325       retainer_blocks = retainerStackBlocks();
1326   }
1327 #endif
1328
1329   // count the blocks allocated by the arena allocator
1330   arena_blocks = arenaBlocks();
1331
1332   // count the blocks containing executable memory
1333   exec_blocks = countAllocdBlocks(exec_block);
1334
1335   /* count the blocks on the free list */
1336   free_blocks = countFreeList();
1337
1338   live_blocks = 0;
1339   for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1340       live_blocks += gen_blocks[g];
1341   }
1342   live_blocks += nursery_blocks + 
1343                + retainer_blocks + arena_blocks + exec_blocks;
1344
1345 #define MB(n) (((n) * BLOCK_SIZE_W) / ((1024*1024)/sizeof(W_)))
1346
1347   leak = live_blocks + free_blocks != mblocks_allocated * BLOCKS_PER_MBLOCK;
1348
1349   if (show || leak)
1350   {
1351       if (leak) { 
1352           debugBelch("Memory leak detected:\n");
1353       } else {
1354           debugBelch("Memory inventory:\n");
1355       }
1356       for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1357           debugBelch("  gen %d blocks : %5lu blocks (%lu MB)\n", g, 
1358                      gen_blocks[g], MB(gen_blocks[g]));
1359       }
1360       debugBelch("  nursery      : %5lu blocks (%lu MB)\n", 
1361                  nursery_blocks, MB(nursery_blocks));
1362       debugBelch("  retainer     : %5lu blocks (%lu MB)\n", 
1363                  retainer_blocks, MB(retainer_blocks));
1364       debugBelch("  arena blocks : %5lu blocks (%lu MB)\n", 
1365                  arena_blocks, MB(arena_blocks));
1366       debugBelch("  exec         : %5lu blocks (%lu MB)\n", 
1367                  exec_blocks, MB(exec_blocks));
1368       debugBelch("  free         : %5lu blocks (%lu MB)\n", 
1369                  free_blocks, MB(free_blocks));
1370       debugBelch("  total        : %5lu blocks (%lu MB)\n",
1371                  live_blocks + free_blocks, MB(live_blocks+free_blocks));
1372       if (leak) {
1373           debugBelch("\n  in system    : %5lu blocks (%lu MB)\n", 
1374                      mblocks_allocated * BLOCKS_PER_MBLOCK, mblocks_allocated);
1375       }
1376   }
1377
1378   if (leak) {
1379       debugBelch("\n");
1380       findMemoryLeak();
1381   }
1382   ASSERT(n_alloc_blocks == live_blocks);
1383   ASSERT(!leak);
1384 }
1385
1386
1387 /* Full heap sanity check. */
1388 void
1389 checkSanity( void )
1390 {
1391     nat g, s;
1392
1393     if (RtsFlags.GcFlags.generations == 1) {
1394         checkHeap(g0s0->blocks);
1395         checkLargeObjects(g0s0->large_objects);
1396     } else {
1397         
1398         for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1399             for (s = 0; s < generations[g].n_steps; s++) {
1400                 if (g == 0 && s == 0) { continue; }
1401                 ASSERT(countBlocks(generations[g].steps[s].blocks)
1402                        == generations[g].steps[s].n_blocks);
1403                 ASSERT(countBlocks(generations[g].steps[s].large_objects)
1404                        == generations[g].steps[s].n_large_blocks);
1405                 checkHeap(generations[g].steps[s].blocks);
1406                 checkLargeObjects(generations[g].steps[s].large_objects);
1407             }
1408         }
1409
1410         for (s = 0; s < n_nurseries; s++) {
1411             ASSERT(countBlocks(nurseries[s].blocks)
1412                    == nurseries[s].n_blocks);
1413             ASSERT(countBlocks(nurseries[s].large_objects)
1414                    == nurseries[s].n_large_blocks);
1415         }
1416             
1417         checkFreeListSanity();
1418     }
1419
1420 #if defined(THREADED_RTS)
1421     // check the stacks too in threaded mode, because we don't do a
1422     // full heap sanity check in this case (see checkHeap())
1423     checkMutableLists(rtsTrue);
1424 #else
1425     checkMutableLists(rtsFalse);
1426 #endif
1427 }
1428
1429 /* Nursery sanity check */
1430 void
1431 checkNurserySanity( step *stp )
1432 {
1433     bdescr *bd, *prev;
1434     nat blocks = 0;
1435
1436     prev = NULL;
1437     for (bd = stp->blocks; bd != NULL; bd = bd->link) {
1438         ASSERT(bd->u.back == prev);
1439         prev = bd;
1440         blocks += bd->blocks;
1441     }
1442     ASSERT(blocks == stp->n_blocks);
1443 }
1444
1445 // handy function for use in gdb, because Bdescr() is inlined.
1446 extern bdescr *_bdescr( StgPtr p );
1447
1448 bdescr *
1449 _bdescr( StgPtr p )
1450 {
1451     return Bdescr(p);
1452 }
1453
1454 #endif