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