[project @ 2005-04-05 12:19:54 by simonmar]
[ghc-hetmet.git] / ghc / rts / Storage.c
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 1998-2004
4  *
5  * Storage manager front end
6  *
7  * ---------------------------------------------------------------------------*/
8
9 #include "PosixSource.h"
10 #include "Rts.h"
11 #include "RtsUtils.h"
12 #include "RtsFlags.h"
13 #include "Stats.h"
14 #include "Hooks.h"
15 #include "BlockAlloc.h"
16 #include "MBlock.h"
17 #include "Weak.h"
18 #include "Sanity.h"
19 #include "Arena.h"
20 #include "OSThreads.h"
21 #include "Capability.h"
22 #include "Storage.h"
23 #include "Schedule.h"
24 #include "RetainerProfile.h"    // for counting memory blocks (memInventory)
25
26 #include <stdlib.h>
27 #include <string.h>
28
29 StgClosure    *caf_list         = NULL;
30 StgClosure    *revertible_caf_list = NULL;
31 rtsBool       keepCAFs;
32
33 bdescr *small_alloc_list;       /* allocate()d small objects */
34 bdescr *pinned_object_block;    /* allocate pinned objects into this block */
35 nat alloc_blocks;               /* number of allocate()d blocks since GC */
36 nat alloc_blocks_lim;           /* approximate limit on alloc_blocks */
37
38 StgPtr alloc_Hp    = NULL;      /* next free byte in small_alloc_list */
39 StgPtr alloc_HpLim = NULL;      /* end of block at small_alloc_list   */
40
41 generation *generations = NULL; /* all the generations */
42 generation *g0          = NULL; /* generation 0, for convenience */
43 generation *oldest_gen  = NULL; /* oldest generation, for convenience */
44 step *g0s0              = NULL; /* generation 0, step 0, for convenience */
45
46 ullong total_allocated = 0;     /* total memory allocated during run */
47
48 /*
49  * Storage manager mutex:  protects all the above state from
50  * simultaneous access by two STG threads.
51  */
52 #ifdef SMP
53 Mutex sm_mutex = INIT_MUTEX_VAR;
54 #endif
55
56 /*
57  * Forward references
58  */
59 static void *stgAllocForGMP   (size_t size_in_bytes);
60 static void *stgReallocForGMP (void *ptr, size_t old_size, size_t new_size);
61 static void  stgDeallocForGMP (void *ptr, size_t size);
62
63 /*
64  * Storage manager mutex
65  */
66 #if defined(SMP)
67 extern Mutex sm_mutex;
68 #define ACQUIRE_SM_LOCK   ACQUIRE_LOCK(&sm_mutex)
69 #define RELEASE_SM_LOCK   RELEASE_LOCK(&sm_mutex)
70 #else
71 #define ACQUIRE_SM_LOCK
72 #define RELEASE_SM_LOCK
73 #endif
74
75 void
76 initStorage( void )
77 {
78   nat g, s;
79   step *stp;
80   generation *gen;
81
82   if (generations != NULL) {
83       // multi-init protection
84       return;
85   }
86
87   /* Sanity check to make sure the LOOKS_LIKE_ macros appear to be
88    * doing something reasonable.
89    */
90   ASSERT(LOOKS_LIKE_INFO_PTR(&stg_BLACKHOLE_info));
91   ASSERT(LOOKS_LIKE_CLOSURE_PTR(&stg_dummy_ret_closure));
92   ASSERT(!HEAP_ALLOCED(&stg_dummy_ret_closure));
93   
94   if (RtsFlags.GcFlags.maxHeapSize != 0 &&
95       RtsFlags.GcFlags.heapSizeSuggestion > 
96       RtsFlags.GcFlags.maxHeapSize) {
97     RtsFlags.GcFlags.maxHeapSize = RtsFlags.GcFlags.heapSizeSuggestion;
98   }
99
100   if (RtsFlags.GcFlags.maxHeapSize != 0 &&
101       RtsFlags.GcFlags.minAllocAreaSize > 
102       RtsFlags.GcFlags.maxHeapSize) {
103       errorBelch("maximum heap size (-M) is smaller than minimum alloc area size (-A)");
104       exit(1);
105   }
106
107   initBlockAllocator();
108   
109 #if defined(SMP)
110   initMutex(&sm_mutex);
111 #endif
112
113   /* allocate generation info array */
114   generations = (generation *)stgMallocBytes(RtsFlags.GcFlags.generations 
115                                              * sizeof(struct _generation),
116                                              "initStorage: gens");
117
118   /* Initialise all generations */
119   for(g = 0; g < RtsFlags.GcFlags.generations; g++) {
120     gen = &generations[g];
121     gen->no = g;
122     gen->mut_list = allocBlock();
123     gen->collections = 0;
124     gen->failed_promotions = 0;
125     gen->max_blocks = 0;
126   }
127
128   /* A couple of convenience pointers */
129   g0 = &generations[0];
130   oldest_gen = &generations[RtsFlags.GcFlags.generations-1];
131
132   /* Allocate step structures in each generation */
133   if (RtsFlags.GcFlags.generations > 1) {
134     /* Only for multiple-generations */
135
136     /* Oldest generation: one step */
137     oldest_gen->n_steps = 1;
138     oldest_gen->steps = 
139       stgMallocBytes(1 * sizeof(struct _step), "initStorage: last step");
140
141     /* set up all except the oldest generation with 2 steps */
142     for(g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
143       generations[g].n_steps = RtsFlags.GcFlags.steps;
144       generations[g].steps  = 
145         stgMallocBytes (RtsFlags.GcFlags.steps * sizeof(struct _step),
146                         "initStorage: steps");
147     }
148     
149   } else {
150     /* single generation, i.e. a two-space collector */
151     g0->n_steps = 1;
152     g0->steps = stgMallocBytes (sizeof(struct _step), "initStorage: steps");
153   }
154
155   /* Initialise all steps */
156   for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
157     for (s = 0; s < generations[g].n_steps; s++) {
158       stp = &generations[g].steps[s];
159       stp->no = s;
160       stp->blocks = NULL;
161       stp->n_to_blocks = 0;
162       stp->n_blocks = 0;
163       stp->gen = &generations[g];
164       stp->gen_no = g;
165       stp->hp = NULL;
166       stp->hpLim = NULL;
167       stp->hp_bd = NULL;
168       stp->scan = NULL;
169       stp->scan_bd = NULL;
170       stp->large_objects = NULL;
171       stp->n_large_blocks = 0;
172       stp->new_large_objects = NULL;
173       stp->scavenged_large_objects = NULL;
174       stp->n_scavenged_large_blocks = 0;
175       stp->is_compacted = 0;
176       stp->bitmap = NULL;
177     }
178   }
179   
180   /* Set up the destination pointers in each younger gen. step */
181   for (g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
182     for (s = 0; s < generations[g].n_steps-1; s++) {
183       generations[g].steps[s].to = &generations[g].steps[s+1];
184     }
185     generations[g].steps[s].to = &generations[g+1].steps[0];
186   }
187   
188   /* The oldest generation has one step and it is compacted. */
189   if (RtsFlags.GcFlags.compact) {
190       if (RtsFlags.GcFlags.generations == 1) {
191           errorBelch("WARNING: compaction is incompatible with -G1; disabled");
192       } else {
193           oldest_gen->steps[0].is_compacted = 1;
194       }
195   }
196   oldest_gen->steps[0].to = &oldest_gen->steps[0];
197
198   /* generation 0 is special: that's the nursery */
199   generations[0].max_blocks = 0;
200
201   /* G0S0: the allocation area.  Policy: keep the allocation area
202    * small to begin with, even if we have a large suggested heap
203    * size.  Reason: we're going to do a major collection first, and we
204    * don't want it to be a big one.  This vague idea is borne out by 
205    * rigorous experimental evidence.
206    */
207   g0s0 = &generations[0].steps[0];
208
209   allocNurseries();
210
211   weak_ptr_list = NULL;
212   caf_list = NULL;
213   revertible_caf_list = NULL;
214    
215   /* initialise the allocate() interface */
216   small_alloc_list = NULL;
217   alloc_blocks = 0;
218   alloc_blocks_lim = RtsFlags.GcFlags.minAllocAreaSize;
219
220   /* Tell GNU multi-precision pkg about our custom alloc functions */
221   mp_set_memory_functions(stgAllocForGMP, stgReallocForGMP, stgDeallocForGMP);
222
223   IF_DEBUG(gc, statDescribeGens());
224 }
225
226 void
227 exitStorage (void)
228 {
229     stat_exit(calcAllocated());
230 }
231
232 /* -----------------------------------------------------------------------------
233    CAF management.
234
235    The entry code for every CAF does the following:
236      
237       - builds a CAF_BLACKHOLE in the heap
238       - pushes an update frame pointing to the CAF_BLACKHOLE
239       - invokes UPD_CAF(), which:
240           - calls newCaf, below
241           - updates the CAF with a static indirection to the CAF_BLACKHOLE
242       
243    Why do we build a BLACKHOLE in the heap rather than just updating
244    the thunk directly?  It's so that we only need one kind of update
245    frame - otherwise we'd need a static version of the update frame too.
246
247    newCaf() does the following:
248        
249       - it puts the CAF on the oldest generation's mut-once list.
250         This is so that we can treat the CAF as a root when collecting
251         younger generations.
252
253    For GHCI, we have additional requirements when dealing with CAFs:
254
255       - we must *retain* all dynamically-loaded CAFs ever entered,
256         just in case we need them again.
257       - we must be able to *revert* CAFs that have been evaluated, to
258         their pre-evaluated form.
259
260       To do this, we use an additional CAF list.  When newCaf() is
261       called on a dynamically-loaded CAF, we add it to the CAF list
262       instead of the old-generation mutable list, and save away its
263       old info pointer (in caf->saved_info) for later reversion.
264
265       To revert all the CAFs, we traverse the CAF list and reset the
266       info pointer to caf->saved_info, then throw away the CAF list.
267       (see GC.c:revertCAFs()).
268
269       -- SDM 29/1/01
270
271    -------------------------------------------------------------------------- */
272
273 void
274 newCAF(StgClosure* caf)
275 {
276   ACQUIRE_SM_LOCK;
277
278   if(keepCAFs)
279   {
280     // HACK:
281     // If we are in GHCi _and_ we are using dynamic libraries,
282     // then we can't redirect newCAF calls to newDynCAF (see below),
283     // so we make newCAF behave almost like newDynCAF.
284     // The dynamic libraries might be used by both the interpreted
285     // program and GHCi itself, so they must not be reverted.
286     // This also means that in GHCi with dynamic libraries, CAFs are not
287     // garbage collected. If this turns out to be a problem, we could
288     // do another hack here and do an address range test on caf to figure
289     // out whether it is from a dynamic library.
290     ((StgIndStatic *)caf)->saved_info  = (StgInfoTable *)caf->header.info;
291     ((StgIndStatic *)caf)->static_link = caf_list;
292     caf_list = caf;
293   }
294   else
295   {
296     /* Put this CAF on the mutable list for the old generation.
297     * This is a HACK - the IND_STATIC closure doesn't really have
298     * a mut_link field, but we pretend it has - in fact we re-use
299     * the STATIC_LINK field for the time being, because when we
300     * come to do a major GC we won't need the mut_link field
301     * any more and can use it as a STATIC_LINK.
302     */
303     ((StgIndStatic *)caf)->saved_info = NULL;
304     recordMutableGen(caf, oldest_gen);
305   }
306   
307   RELEASE_SM_LOCK;
308
309 #ifdef PAR
310   /* If we are PAR or DIST then  we never forget a CAF */
311   { globalAddr *newGA;
312     //debugBelch("<##> Globalising CAF %08x %s",caf,info_type(caf));
313     newGA=makeGlobal(caf,rtsTrue); /*given full weight*/
314     ASSERT(newGA);
315   } 
316 #endif /* PAR */
317 }
318
319 // An alternate version of newCaf which is used for dynamically loaded
320 // object code in GHCi.  In this case we want to retain *all* CAFs in
321 // the object code, because they might be demanded at any time from an
322 // expression evaluated on the command line.
323 // Also, GHCi might want to revert CAFs, so we add these to the
324 // revertible_caf_list.
325 //
326 // The linker hackily arranges that references to newCaf from dynamic
327 // code end up pointing to newDynCAF.
328 void
329 newDynCAF(StgClosure *caf)
330 {
331     ACQUIRE_SM_LOCK;
332
333     ((StgIndStatic *)caf)->saved_info  = (StgInfoTable *)caf->header.info;
334     ((StgIndStatic *)caf)->static_link = revertible_caf_list;
335     revertible_caf_list = caf;
336
337     RELEASE_SM_LOCK;
338 }
339
340 /* -----------------------------------------------------------------------------
341    Nursery management.
342    -------------------------------------------------------------------------- */
343
344 void
345 allocNurseries( void )
346
347 #ifdef SMP
348   Capability *cap;
349
350   g0s0->blocks = NULL;
351   g0s0->n_blocks = 0;
352   for (cap = free_capabilities; cap != NULL; cap = cap->link) {
353     cap->r.rNursery = allocNursery(NULL, RtsFlags.GcFlags.minAllocAreaSize);
354     cap->r.rCurrentNursery = cap->r.rNursery;
355   }
356 #else /* SMP */
357   g0s0->blocks      = allocNursery(NULL, RtsFlags.GcFlags.minAllocAreaSize);
358   g0s0->n_blocks    = RtsFlags.GcFlags.minAllocAreaSize;
359   g0s0->to_blocks   = NULL;
360   g0s0->n_to_blocks = 0;
361   MainCapability.r.rNursery        = g0s0->blocks;
362   MainCapability.r.rCurrentNursery = g0s0->blocks;
363   /* hp, hpLim, hp_bd, to_space etc. aren't used in G0S0 */
364 #endif
365 }
366       
367 void
368 resetNurseries( void )
369 {
370   bdescr *bd;
371 #ifdef SMP
372   Capability *cap;
373   
374   /* All tasks must be stopped */
375   ASSERT(rts_n_free_capabilities == RtsFlags.ParFlags.nNodes);
376
377   for (cap = free_capabilities; cap != NULL; cap = cap->link) {
378     for (bd = cap->r.rNursery; bd; bd = bd->link) {
379       bd->free = bd->start;
380       ASSERT(bd->gen_no == 0);
381       ASSERT(bd->step == g0s0);
382       IF_DEBUG(sanity,memset(bd->start, 0xaa, BLOCK_SIZE));
383     }
384     cap->r.rCurrentNursery = cap->r.rNursery;
385   }
386 #else
387   for (bd = g0s0->blocks; bd; bd = bd->link) {
388     bd->free = bd->start;
389     ASSERT(bd->gen_no == 0);
390     ASSERT(bd->step == g0s0);
391     IF_DEBUG(sanity,memset(bd->start, 0xaa, BLOCK_SIZE));
392   }
393   MainCapability.r.rNursery = g0s0->blocks;
394   MainCapability.r.rCurrentNursery = g0s0->blocks;
395 #endif
396 }
397
398 bdescr *
399 allocNursery (bdescr *tail, nat blocks)
400 {
401   bdescr *bd;
402   nat i;
403
404   // Allocate a nursery: we allocate fresh blocks one at a time and
405   // cons them on to the front of the list, not forgetting to update
406   // the back pointer on the tail of the list to point to the new block.
407   for (i=0; i < blocks; i++) {
408     // @LDV profiling
409     /*
410       processNursery() in LdvProfile.c assumes that every block group in
411       the nursery contains only a single block. So, if a block group is
412       given multiple blocks, change processNursery() accordingly.
413      */
414     bd = allocBlock();
415     bd->link = tail;
416     // double-link the nursery: we might need to insert blocks
417     if (tail != NULL) {
418         tail->u.back = bd;
419     }
420     bd->step = g0s0;
421     bd->gen_no = 0;
422     bd->flags = 0;
423     bd->free = bd->start;
424     tail = bd;
425   }
426   tail->u.back = NULL;
427   return tail;
428 }
429
430 void
431 resizeNursery ( nat blocks )
432 {
433   bdescr *bd;
434   nat nursery_blocks;
435
436 #ifdef SMP
437   barf("resizeNursery: can't resize in SMP mode");
438 #endif
439
440   nursery_blocks = g0s0->n_blocks;
441   if (nursery_blocks == blocks) {
442     return;
443   }
444
445   else if (nursery_blocks < blocks) {
446     IF_DEBUG(gc, debugBelch("Increasing size of nursery to %d blocks\n", 
447                          blocks));
448     g0s0->blocks = allocNursery(g0s0->blocks, blocks-nursery_blocks);
449   } 
450
451   else {
452     bdescr *next_bd;
453     
454     IF_DEBUG(gc, debugBelch("Decreasing size of nursery to %d blocks\n", 
455                          blocks));
456
457     bd = g0s0->blocks;
458     while (nursery_blocks > blocks) {
459         next_bd = bd->link;
460         next_bd->u.back = NULL;
461         nursery_blocks -= bd->blocks; // might be a large block
462         freeGroup(bd);
463         bd = next_bd;
464     }
465     g0s0->blocks = bd;
466     // might have gone just under, by freeing a large block, so make
467     // up the difference.
468     if (nursery_blocks < blocks) {
469         g0s0->blocks = allocNursery(g0s0->blocks, blocks-nursery_blocks);
470     }
471   }
472   
473   g0s0->n_blocks = blocks;
474   ASSERT(countBlocks(g0s0->blocks) == g0s0->n_blocks);
475 }
476
477 /* -----------------------------------------------------------------------------
478    The allocate() interface
479
480    allocate(n) always succeeds, and returns a chunk of memory n words
481    long.  n can be larger than the size of a block if necessary, in
482    which case a contiguous block group will be allocated.
483    -------------------------------------------------------------------------- */
484
485 StgPtr
486 allocate( nat n )
487 {
488   bdescr *bd;
489   StgPtr p;
490
491   ACQUIRE_SM_LOCK;
492
493   TICK_ALLOC_HEAP_NOCTR(n);
494   CCS_ALLOC(CCCS,n);
495
496   /* big allocation (>LARGE_OBJECT_THRESHOLD) */
497   /* ToDo: allocate directly into generation 1 */
498   if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
499     nat req_blocks =  (lnat)BLOCK_ROUND_UP(n*sizeof(W_)) / BLOCK_SIZE;
500     bd = allocGroup(req_blocks);
501     dbl_link_onto(bd, &g0s0->large_objects);
502     g0s0->n_large_blocks += req_blocks;
503     bd->gen_no  = 0;
504     bd->step = g0s0;
505     bd->flags = BF_LARGE;
506     bd->free = bd->start + n;
507     alloc_blocks += req_blocks;
508     RELEASE_SM_LOCK;
509     return bd->start;
510
511   /* small allocation (<LARGE_OBJECT_THRESHOLD) */
512   } else if (small_alloc_list == NULL || alloc_Hp + n > alloc_HpLim) {
513     if (small_alloc_list) {
514       small_alloc_list->free = alloc_Hp;
515     }
516     bd = allocBlock();
517     bd->link = small_alloc_list;
518     small_alloc_list = bd;
519     bd->gen_no = 0;
520     bd->step = g0s0;
521     bd->flags = 0;
522     alloc_Hp = bd->start;
523     alloc_HpLim = bd->start + BLOCK_SIZE_W;
524     alloc_blocks++;
525   }
526
527   p = alloc_Hp;
528   alloc_Hp += n;
529   RELEASE_SM_LOCK;
530   return p;
531 }
532
533 lnat
534 allocated_bytes( void )
535 {
536     lnat allocated;
537
538     allocated = alloc_blocks * BLOCK_SIZE_W - (alloc_HpLim - alloc_Hp);
539     if (pinned_object_block != NULL) {
540         allocated -= (pinned_object_block->start + BLOCK_SIZE_W) - 
541             pinned_object_block->free;
542     }
543         
544     return allocated;
545 }
546
547 void
548 tidyAllocateLists (void)
549 {
550     if (small_alloc_list != NULL) {
551         ASSERT(alloc_Hp >= small_alloc_list->start && 
552                alloc_Hp <= small_alloc_list->start + BLOCK_SIZE);
553         small_alloc_list->free = alloc_Hp;
554     }
555 }
556
557 /* ---------------------------------------------------------------------------
558    Allocate a fixed/pinned object.
559
560    We allocate small pinned objects into a single block, allocating a
561    new block when the current one overflows.  The block is chained
562    onto the large_object_list of generation 0 step 0.
563
564    NOTE: The GC can't in general handle pinned objects.  This
565    interface is only safe to use for ByteArrays, which have no
566    pointers and don't require scavenging.  It works because the
567    block's descriptor has the BF_LARGE flag set, so the block is
568    treated as a large object and chained onto various lists, rather
569    than the individual objects being copied.  However, when it comes
570    to scavenge the block, the GC will only scavenge the first object.
571    The reason is that the GC can't linearly scan a block of pinned
572    objects at the moment (doing so would require using the
573    mostly-copying techniques).  But since we're restricting ourselves
574    to pinned ByteArrays, not scavenging is ok.
575
576    This function is called by newPinnedByteArray# which immediately
577    fills the allocated memory with a MutableByteArray#.
578    ------------------------------------------------------------------------- */
579
580 StgPtr
581 allocatePinned( nat n )
582 {
583     StgPtr p;
584     bdescr *bd = pinned_object_block;
585
586     // If the request is for a large object, then allocate()
587     // will give us a pinned object anyway.
588     if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
589         return allocate(n);
590     }
591
592     ACQUIRE_SM_LOCK;
593     
594     TICK_ALLOC_HEAP_NOCTR(n);
595     CCS_ALLOC(CCCS,n);
596
597     // we always return 8-byte aligned memory.  bd->free must be
598     // 8-byte aligned to begin with, so we just round up n to
599     // the nearest multiple of 8 bytes.
600     if (sizeof(StgWord) == 4) {
601         n = (n+1) & ~1;
602     }
603
604     // If we don't have a block of pinned objects yet, or the current
605     // one isn't large enough to hold the new object, allocate a new one.
606     if (bd == NULL || (bd->free + n) > (bd->start + BLOCK_SIZE_W)) {
607         pinned_object_block = bd = allocBlock();
608         dbl_link_onto(bd, &g0s0->large_objects);
609         bd->gen_no = 0;
610         bd->step   = g0s0;
611         bd->flags  = BF_PINNED | BF_LARGE;
612         bd->free   = bd->start;
613         alloc_blocks++;
614     }
615
616     p = bd->free;
617     bd->free += n;
618     RELEASE_SM_LOCK;
619     return p;
620 }
621
622 /* -----------------------------------------------------------------------------
623    Allocation functions for GMP.
624
625    These all use the allocate() interface - we can't have any garbage
626    collection going on during a gmp operation, so we use allocate()
627    which always succeeds.  The gmp operations which might need to
628    allocate will ask the storage manager (via doYouWantToGC()) whether
629    a garbage collection is required, in case we get into a loop doing
630    only allocate() style allocation.
631    -------------------------------------------------------------------------- */
632
633 static void *
634 stgAllocForGMP (size_t size_in_bytes)
635 {
636   StgArrWords* arr;
637   nat data_size_in_words, total_size_in_words;
638   
639   /* round up to a whole number of words */
640   data_size_in_words  = (size_in_bytes + sizeof(W_) + 1) / sizeof(W_);
641   total_size_in_words = sizeofW(StgArrWords) + data_size_in_words;
642   
643   /* allocate and fill it in. */
644   arr = (StgArrWords *)allocate(total_size_in_words);
645   SET_ARR_HDR(arr, &stg_ARR_WORDS_info, CCCS, data_size_in_words);
646   
647   /* and return a ptr to the goods inside the array */
648   return arr->payload;
649 }
650
651 static void *
652 stgReallocForGMP (void *ptr, size_t old_size, size_t new_size)
653 {
654     void *new_stuff_ptr = stgAllocForGMP(new_size);
655     nat i = 0;
656     char *p = (char *) ptr;
657     char *q = (char *) new_stuff_ptr;
658
659     for (; i < old_size; i++, p++, q++) {
660         *q = *p;
661     }
662
663     return(new_stuff_ptr);
664 }
665
666 static void
667 stgDeallocForGMP (void *ptr STG_UNUSED, 
668                   size_t size STG_UNUSED)
669 {
670     /* easy for us: the garbage collector does the dealloc'n */
671 }
672
673 /* -----------------------------------------------------------------------------
674  * Stats and stuff
675  * -------------------------------------------------------------------------- */
676
677 /* -----------------------------------------------------------------------------
678  * calcAllocated()
679  *
680  * Approximate how much we've allocated: number of blocks in the
681  * nursery + blocks allocated via allocate() - unused nusery blocks.
682  * This leaves a little slop at the end of each block, and doesn't
683  * take into account large objects (ToDo).
684  * -------------------------------------------------------------------------- */
685
686 lnat
687 calcAllocated( void )
688 {
689   nat allocated;
690   bdescr *bd;
691
692 #ifdef SMP
693   Capability *cap;
694
695   /* All tasks must be stopped.  Can't assert that all the
696      capabilities are owned by the scheduler, though: one or more
697      tasks might have been stopped while they were running (non-main)
698      threads. */
699   /*  ASSERT(n_free_capabilities == RtsFlags.ParFlags.nNodes); */
700
701   allocated = 
702     rts_n_free_capabilities * RtsFlags.GcFlags.minAllocAreaSize * BLOCK_SIZE_W
703     + allocated_bytes();
704
705   for (cap = free_capabilities; cap != NULL; cap = cap->link) {
706     for ( bd = cap->r.rCurrentNursery->link; bd != NULL; bd = bd->link ) {
707       allocated -= BLOCK_SIZE_W;
708     }
709     if (cap->r.rCurrentNursery->free < cap->r.rCurrentNursery->start 
710         + BLOCK_SIZE_W) {
711       allocated -= (cap->r.rCurrentNursery->start + BLOCK_SIZE_W)
712         - cap->r.rCurrentNursery->free;
713     }
714   }
715
716 #else /* !SMP */
717   bdescr *current_nursery = MainCapability.r.rCurrentNursery;
718
719   allocated = (g0s0->n_blocks * BLOCK_SIZE_W) + allocated_bytes();
720   for ( bd = current_nursery->link; bd != NULL; bd = bd->link ) {
721     allocated -= BLOCK_SIZE_W;
722   }
723   if (current_nursery->free < current_nursery->start + BLOCK_SIZE_W) {
724     allocated -= (current_nursery->start + BLOCK_SIZE_W)
725       - current_nursery->free;
726   }
727 #endif
728
729   total_allocated += allocated;
730   return allocated;
731 }  
732
733 /* Approximate the amount of live data in the heap.  To be called just
734  * after garbage collection (see GarbageCollect()).
735  */
736 extern lnat 
737 calcLive(void)
738 {
739   nat g, s;
740   lnat live = 0;
741   step *stp;
742
743   if (RtsFlags.GcFlags.generations == 1) {
744     live = (g0s0->n_to_blocks - 1) * BLOCK_SIZE_W + 
745       ((lnat)g0s0->hp_bd->free - (lnat)g0s0->hp_bd->start) / sizeof(W_);
746     return live;
747   }
748
749   for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
750     for (s = 0; s < generations[g].n_steps; s++) {
751       /* approximate amount of live data (doesn't take into account slop
752        * at end of each block).
753        */
754       if (g == 0 && s == 0) { 
755           continue; 
756       }
757       stp = &generations[g].steps[s];
758       live += (stp->n_large_blocks + stp->n_blocks - 1) * BLOCK_SIZE_W;
759       if (stp->hp_bd != NULL) {
760           live += ((lnat)stp->hp_bd->free - (lnat)stp->hp_bd->start) 
761               / sizeof(W_);
762       }
763     }
764   }
765   return live;
766 }
767
768 /* Approximate the number of blocks that will be needed at the next
769  * garbage collection.
770  *
771  * Assume: all data currently live will remain live.  Steps that will
772  * be collected next time will therefore need twice as many blocks
773  * since all the data will be copied.
774  */
775 extern lnat 
776 calcNeeded(void)
777 {
778     lnat needed = 0;
779     nat g, s;
780     step *stp;
781     
782     for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
783         for (s = 0; s < generations[g].n_steps; s++) {
784             if (g == 0 && s == 0) { continue; }
785             stp = &generations[g].steps[s];
786             if (generations[g].steps[0].n_blocks +
787                 generations[g].steps[0].n_large_blocks 
788                 > generations[g].max_blocks
789                 && stp->is_compacted == 0) {
790                 needed += 2 * stp->n_blocks;
791             } else {
792                 needed += stp->n_blocks;
793             }
794         }
795     }
796     return needed;
797 }
798
799 /* -----------------------------------------------------------------------------
800    Debugging
801
802    memInventory() checks for memory leaks by counting up all the
803    blocks we know about and comparing that to the number of blocks
804    allegedly floating around in the system.
805    -------------------------------------------------------------------------- */
806
807 #ifdef DEBUG
808
809 void
810 memInventory(void)
811 {
812   nat g, s;
813   step *stp;
814   bdescr *bd;
815   lnat total_blocks = 0, free_blocks = 0;
816
817   /* count the blocks we current have */
818
819   for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
820       for (bd = generations[g].mut_list; bd != NULL; bd = bd->link) {
821           total_blocks += bd->blocks;
822       }
823       for (s = 0; s < generations[g].n_steps; s++) {
824           stp = &generations[g].steps[s];
825           total_blocks += stp->n_blocks;
826           if (RtsFlags.GcFlags.generations == 1) {
827               /* two-space collector has a to-space too :-) */
828               total_blocks += g0s0->n_to_blocks;
829           }
830           for (bd = stp->large_objects; bd; bd = bd->link) {
831               total_blocks += bd->blocks;
832               /* hack for megablock groups: they have an extra block or two in
833                  the second and subsequent megablocks where the block
834                  descriptors would normally go.
835               */
836               if (bd->blocks > BLOCKS_PER_MBLOCK) {
837                   total_blocks -= (MBLOCK_SIZE / BLOCK_SIZE - BLOCKS_PER_MBLOCK)
838                       * (bd->blocks/(MBLOCK_SIZE/BLOCK_SIZE));
839               }
840           }
841       }
842   }
843
844   /* any blocks held by allocate() */
845   for (bd = small_alloc_list; bd; bd = bd->link) {
846     total_blocks += bd->blocks;
847   }
848
849 #ifdef PROFILING
850   if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER) {
851       total_blocks += retainerStackBlocks();
852   }
853 #endif
854
855   // count the blocks allocated by the arena allocator
856   total_blocks += arenaBlocks();
857
858   /* count the blocks on the free list */
859   free_blocks = countFreeList();
860
861   if (total_blocks + free_blocks != mblocks_allocated *
862       BLOCKS_PER_MBLOCK) {
863     debugBelch("Blocks: %ld live + %ld free  = %ld total (%ld around)\n",
864             total_blocks, free_blocks, total_blocks + free_blocks,
865             mblocks_allocated * BLOCKS_PER_MBLOCK);
866   }
867
868   ASSERT(total_blocks + free_blocks == mblocks_allocated * BLOCKS_PER_MBLOCK);
869 }
870
871
872 nat
873 countBlocks(bdescr *bd)
874 {
875     nat n;
876     for (n=0; bd != NULL; bd=bd->link) {
877         n += bd->blocks;
878     }
879     return n;
880 }
881
882 /* Full heap sanity check. */
883 void
884 checkSanity( void )
885 {
886     nat g, s;
887
888     if (RtsFlags.GcFlags.generations == 1) {
889         checkHeap(g0s0->to_blocks);
890         checkChain(g0s0->large_objects);
891     } else {
892         
893         for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
894             for (s = 0; s < generations[g].n_steps; s++) {
895                 ASSERT(countBlocks(generations[g].steps[s].blocks)
896                        == generations[g].steps[s].n_blocks);
897                 ASSERT(countBlocks(generations[g].steps[s].large_objects)
898                        == generations[g].steps[s].n_large_blocks);
899                 if (g == 0 && s == 0) { continue; }
900                 checkHeap(generations[g].steps[s].blocks);
901                 checkChain(generations[g].steps[s].large_objects);
902                 if (g > 0) {
903                     checkMutableList(generations[g].mut_list, g);
904                 }
905             }
906         }
907         checkFreeListSanity();
908     }
909 }
910
911 // handy function for use in gdb, because Bdescr() is inlined.
912 extern bdescr *_bdescr( StgPtr p );
913
914 bdescr *
915 _bdescr( StgPtr p )
916 {
917     return Bdescr(p);
918 }
919
920 #endif