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