1 /* -----------------------------------------------------------------------------
2 * $Id: Storage.c,v 1.40 2001/07/23 10:47:16 simonmar Exp $
4 * (c) The GHC Team, 1998-1999
6 * Storage manager front end
8 * ---------------------------------------------------------------------------*/
15 #include "BlockAlloc.h"
22 #include "StoragePriv.h"
25 nat nursery_blocks; /* number of blocks in the nursery */
28 StgClosure *caf_list = NULL;
30 bdescr *small_alloc_list; /* allocate()d small objects */
31 bdescr *large_alloc_list; /* allocate()d large objects */
32 nat alloc_blocks; /* number of allocate()d blocks since GC */
33 nat alloc_blocks_lim; /* approximate limit on alloc_blocks */
35 StgPtr alloc_Hp = NULL; /* next free byte in small_alloc_list */
36 StgPtr alloc_HpLim = NULL; /* end of block at small_alloc_list */
38 generation *generations; /* all the generations */
39 generation *g0; /* generation 0, for convenience */
40 generation *oldest_gen; /* oldest generation, for convenience */
41 step *g0s0; /* generation 0, step 0, for convenience */
43 lnat total_allocated = 0; /* total memory allocated during run */
46 * Storage manager mutex: protects all the above state from
47 * simultaneous access by two STG threads.
50 pthread_mutex_t sm_mutex = PTHREAD_MUTEX_INITIALIZER;
56 static void *stgAllocForGMP (size_t size_in_bytes);
57 static void *stgReallocForGMP (void *ptr, size_t old_size, size_t new_size);
58 static void stgDeallocForGMP (void *ptr, size_t size);
67 /* If we're doing heap profiling, we want a two-space heap with a
68 * fixed-size allocation area so that we get roughly even-spaced
72 /* As an experiment, try a 2 generation collector
75 #if defined(PROFILING) || defined(DEBUG)
76 if (RtsFlags.ProfFlags.doHeapProfile) {
77 RtsFlags.GcFlags.generations = 1;
78 RtsFlags.GcFlags.steps = 1;
79 RtsFlags.GcFlags.oldGenFactor = 0;
80 RtsFlags.GcFlags.heapSizeSuggestion = 0;
84 if (RtsFlags.GcFlags.heapSizeSuggestion >
85 RtsFlags.GcFlags.maxHeapSize) {
86 RtsFlags.GcFlags.maxHeapSize = RtsFlags.GcFlags.heapSizeSuggestion;
91 /* allocate generation info array */
92 generations = (generation *)stgMallocBytes(RtsFlags.GcFlags.generations
93 * sizeof(struct _generation),
96 /* Initialise all generations */
97 for(g = 0; g < RtsFlags.GcFlags.generations; g++) {
98 gen = &generations[g];
100 gen->mut_list = END_MUT_LIST;
101 gen->mut_once_list = END_MUT_LIST;
102 gen->collections = 0;
103 gen->failed_promotions = 0;
107 /* A couple of convenience pointers */
108 g0 = &generations[0];
109 oldest_gen = &generations[RtsFlags.GcFlags.generations-1];
111 /* Allocate step structures in each generation */
112 if (RtsFlags.GcFlags.generations > 1) {
113 /* Only for multiple-generations */
115 /* Oldest generation: one step */
116 oldest_gen->n_steps = 1;
118 stgMallocBytes(1 * sizeof(struct _step), "initStorage: last step");
120 /* set up all except the oldest generation with 2 steps */
121 for(g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
122 generations[g].n_steps = RtsFlags.GcFlags.steps;
123 generations[g].steps =
124 stgMallocBytes (RtsFlags.GcFlags.steps * sizeof(struct _step),
125 "initStorage: steps");
129 /* single generation, i.e. a two-space collector */
131 g0->steps = stgMallocBytes (sizeof(struct _step), "initStorage: steps");
134 /* Initialise all steps */
135 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
136 for (s = 0; s < generations[g].n_steps; s++) {
137 stp = &generations[g].steps[s];
141 stp->gen = &generations[g];
148 stp->large_objects = NULL;
149 stp->new_large_objects = NULL;
150 stp->scavenged_large_objects = NULL;
154 /* Set up the destination pointers in each younger gen. step */
155 for (g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
156 for (s = 0; s < generations[g].n_steps-1; s++) {
157 generations[g].steps[s].to = &generations[g].steps[s+1];
159 generations[g].steps[s].to = &generations[g+1].steps[0];
162 /* The oldest generation has one step and its destination is the
164 oldest_gen->steps[0].to = &oldest_gen->steps[0];
166 /* generation 0 is special: that's the nursery */
167 generations[0].max_blocks = 0;
169 /* G0S0: the allocation area. Policy: keep the allocation area
170 * small to begin with, even if we have a large suggested heap
171 * size. Reason: we're going to do a major collection first, and we
172 * don't want it to be a big one. This vague idea is borne out by
173 * rigorous experimental evidence.
175 g0s0 = &generations[0].steps[0];
179 weak_ptr_list = NULL;
182 /* initialise the allocate() interface */
183 small_alloc_list = NULL;
184 large_alloc_list = NULL;
186 alloc_blocks_lim = RtsFlags.GcFlags.minAllocAreaSize;
188 /* Tell GNU multi-precision pkg about our custom alloc functions */
189 mp_set_memory_functions(stgAllocForGMP, stgReallocForGMP, stgDeallocForGMP);
192 pthread_mutex_init(&sm_mutex, NULL);
195 IF_DEBUG(gc, stat_describe_gens());
201 stat_exit(calcAllocated());
204 /* -----------------------------------------------------------------------------
207 The entry code for every CAF does the following:
209 - builds a CAF_BLACKHOLE in the heap
210 - pushes an update frame pointing to the CAF_BLACKHOLE
211 - invokes UPD_CAF(), which:
212 - calls newCaf, below
213 - updates the CAF with a static indirection to the CAF_BLACKHOLE
215 Why do we build a BLACKHOLE in the heap rather than just updating
216 the thunk directly? It's so that we only need one kind of update
217 frame - otherwise we'd need a static version of the update frame too.
219 newCaf() does the following:
221 - it puts the CAF on the oldest generation's mut-once list.
222 This is so that we can treat the CAF as a root when collecting
225 For GHCI, we have additional requirements when dealing with CAFs:
227 - we must *retain* all dynamically-loaded CAFs ever entered,
228 just in case we need them again.
229 - we must be able to *revert* CAFs that have been evaluated, to
230 their pre-evaluated form.
232 To do this, we use an additional CAF list. When newCaf() is
233 called on a dynamically-loaded CAF, we add it to the CAF list
234 instead of the old-generation mutable list, and save away its
235 old info pointer (in caf->saved_info) for later reversion.
237 To revert all the CAFs, we traverse the CAF list and reset the
238 info pointer to caf->saved_info, then throw away the CAF list.
239 (see GC.c:revertCAFs()).
243 -------------------------------------------------------------------------- */
246 newCAF(StgClosure* caf)
248 /* Put this CAF on the mutable list for the old generation.
249 * This is a HACK - the IND_STATIC closure doesn't really have
250 * a mut_link field, but we pretend it has - in fact we re-use
251 * the STATIC_LINK field for the time being, because when we
252 * come to do a major GC we won't need the mut_link field
253 * any more and can use it as a STATIC_LINK.
255 ACQUIRE_LOCK(&sm_mutex);
257 if (is_dynamically_loaded_rwdata_ptr((StgPtr)caf)) {
258 ((StgIndStatic *)caf)->saved_info = (StgInfoTable *)caf->header.info;
259 ((StgIndStatic *)caf)->static_link = caf_list;
262 ((StgIndStatic *)caf)->saved_info = NULL;
263 ((StgMutClosure *)caf)->mut_link = oldest_gen->mut_once_list;
264 oldest_gen->mut_once_list = (StgMutClosure *)caf;
267 RELEASE_LOCK(&sm_mutex);
270 /* If we are PAR or DIST then we never forget a CAF */
272 //belch("<##> Globalising CAF %08x %s",caf,info_type(caf));
273 newGA=makeGlobal(caf,rtsTrue); /*given full weight*/
279 /* -----------------------------------------------------------------------------
281 -------------------------------------------------------------------------- */
284 allocNurseries( void )
293 for (cap = free_capabilities; cap != NULL; cap = cap->link) {
294 cap->rNursery = allocNursery(NULL, RtsFlags.GcFlags.minAllocAreaSize);
295 cap->rCurrentNursery = cap->rNursery;
296 for (bd = cap->rNursery; bd != NULL; bd = bd->link) {
297 bd->back = (bdescr *)cap;
300 /* Set the back links to be equal to the Capability,
301 * so we can do slightly better informed locking.
305 nursery_blocks = RtsFlags.GcFlags.minAllocAreaSize;
306 g0s0->blocks = allocNursery(NULL, nursery_blocks);
307 g0s0->n_blocks = nursery_blocks;
308 g0s0->to_space = NULL;
309 MainRegTable.rNursery = g0s0->blocks;
310 MainRegTable.rCurrentNursery = g0s0->blocks;
311 /* hp, hpLim, hp_bd, to_space etc. aren't used in G0S0 */
316 resetNurseries( void )
322 /* All tasks must be stopped */
323 ASSERT(n_free_capabilities == RtsFlags.ParFlags.nNodes);
325 for (cap = free_capabilities; cap != NULL; cap = cap->link) {
326 for (bd = cap->rNursery; bd; bd = bd->link) {
327 bd->free = bd->start;
328 ASSERT(bd->gen_no == 0);
329 ASSERT(bd->step == g0s0);
330 IF_DEBUG(sanity,memset(bd->start, 0xaa, BLOCK_SIZE));
332 cap->rCurrentNursery = cap->rNursery;
335 for (bd = g0s0->blocks; bd; bd = bd->link) {
336 bd->free = bd->start;
337 ASSERT(bd->gen_no == 0);
338 ASSERT(bd->step == g0s0);
339 IF_DEBUG(sanity,memset(bd->start, 0xaa, BLOCK_SIZE));
341 MainRegTable.rNursery = g0s0->blocks;
342 MainRegTable.rCurrentNursery = g0s0->blocks;
347 allocNursery (bdescr *last_bd, nat blocks)
352 /* Allocate a nursery */
353 for (i=0; i < blocks; i++) {
359 bd->free = bd->start;
366 resizeNursery ( nat blocks )
371 barf("resizeNursery: can't resize in SMP mode");
374 if (nursery_blocks == blocks) {
375 ASSERT(g0s0->n_blocks == blocks);
379 else if (nursery_blocks < blocks) {
380 IF_DEBUG(gc, fprintf(stderr, "Increasing size of nursery to %d blocks\n",
382 g0s0->blocks = allocNursery(g0s0->blocks, blocks-nursery_blocks);
388 IF_DEBUG(gc, fprintf(stderr, "Decreasing size of nursery to %d blocks\n",
390 for (bd = g0s0->blocks; nursery_blocks > blocks; nursery_blocks--) {
398 g0s0->n_blocks = nursery_blocks = blocks;
401 /* -----------------------------------------------------------------------------
402 The allocate() interface
404 allocate(n) always succeeds, and returns a chunk of memory n words
405 long. n can be larger than the size of a block if necessary, in
406 which case a contiguous block group will be allocated.
407 -------------------------------------------------------------------------- */
415 ACQUIRE_LOCK(&sm_mutex);
417 TICK_ALLOC_HEAP_NOCTR(n);
420 /* big allocation (>LARGE_OBJECT_THRESHOLD) */
421 /* ToDo: allocate directly into generation 1 */
422 if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
423 nat req_blocks = (lnat)BLOCK_ROUND_UP(n*sizeof(W_)) / BLOCK_SIZE;
424 bd = allocGroup(req_blocks);
425 dbl_link_onto(bd, &g0s0->large_objects);
429 bd->free = bd->start;
430 /* don't add these blocks to alloc_blocks, since we're assuming
431 * that large objects are likely to remain live for quite a while
432 * (eg. running threads), so garbage collecting early won't make
435 alloc_blocks += req_blocks;
436 RELEASE_LOCK(&sm_mutex);
439 /* small allocation (<LARGE_OBJECT_THRESHOLD) */
440 } else if (small_alloc_list == NULL || alloc_Hp + n > alloc_HpLim) {
441 if (small_alloc_list) {
442 small_alloc_list->free = alloc_Hp;
445 bd->link = small_alloc_list;
446 small_alloc_list = bd;
450 alloc_Hp = bd->start;
451 alloc_HpLim = bd->start + BLOCK_SIZE_W;
457 RELEASE_LOCK(&sm_mutex);
461 lnat allocated_bytes(void)
463 return (alloc_blocks * BLOCK_SIZE_W - (alloc_HpLim - alloc_Hp));
466 /* -----------------------------------------------------------------------------
467 Allocation functions for GMP.
469 These all use the allocate() interface - we can't have any garbage
470 collection going on during a gmp operation, so we use allocate()
471 which always succeeds. The gmp operations which might need to
472 allocate will ask the storage manager (via doYouWantToGC()) whether
473 a garbage collection is required, in case we get into a loop doing
474 only allocate() style allocation.
475 -------------------------------------------------------------------------- */
478 stgAllocForGMP (size_t size_in_bytes)
481 nat data_size_in_words, total_size_in_words;
483 /* should be a multiple of sizeof(StgWord) (whole no. of limbs) */
484 ASSERT(size_in_bytes % sizeof(W_) == 0);
486 data_size_in_words = size_in_bytes / sizeof(W_);
487 total_size_in_words = sizeofW(StgArrWords) + data_size_in_words;
489 /* allocate and fill it in. */
490 arr = (StgArrWords *)allocate(total_size_in_words);
491 SET_ARR_HDR(arr, &stg_ARR_WORDS_info, CCCS, data_size_in_words);
493 /* and return a ptr to the goods inside the array */
494 return(BYTE_ARR_CTS(arr));
498 stgReallocForGMP (void *ptr, size_t old_size, size_t new_size)
500 void *new_stuff_ptr = stgAllocForGMP(new_size);
502 char *p = (char *) ptr;
503 char *q = (char *) new_stuff_ptr;
505 for (; i < old_size; i++, p++, q++) {
509 return(new_stuff_ptr);
513 stgDeallocForGMP (void *ptr STG_UNUSED,
514 size_t size STG_UNUSED)
516 /* easy for us: the garbage collector does the dealloc'n */
519 /* -----------------------------------------------------------------------------
521 * -------------------------------------------------------------------------- */
523 /* -----------------------------------------------------------------------------
526 * Approximate how much we've allocated: number of blocks in the
527 * nursery + blocks allocated via allocate() - unused nusery blocks.
528 * This leaves a little slop at the end of each block, and doesn't
529 * take into account large objects (ToDo).
530 * -------------------------------------------------------------------------- */
533 calcAllocated( void )
541 /* All tasks must be stopped. Can't assert that all the
542 capabilities are owned by the scheduler, though: one or more
543 tasks might have been stopped while they were running (non-main)
545 /* ASSERT(n_free_capabilities == RtsFlags.ParFlags.nNodes); */
548 n_free_capabilities * RtsFlags.GcFlags.minAllocAreaSize * BLOCK_SIZE_W
551 for (cap = free_capabilities; cap != NULL; cap = cap->link) {
552 for ( bd = cap->rCurrentNursery->link; bd != NULL; bd = bd->link ) {
553 allocated -= BLOCK_SIZE_W;
555 if (cap->rCurrentNursery->free < cap->rCurrentNursery->start
557 allocated -= (cap->rCurrentNursery->start + BLOCK_SIZE_W)
558 - cap->rCurrentNursery->free;
563 bdescr *current_nursery = MainRegTable.rCurrentNursery;
565 allocated = (nursery_blocks * BLOCK_SIZE_W) + allocated_bytes();
566 for ( bd = current_nursery->link; bd != NULL; bd = bd->link ) {
567 allocated -= BLOCK_SIZE_W;
569 if (current_nursery->free < current_nursery->start + BLOCK_SIZE_W) {
570 allocated -= (current_nursery->start + BLOCK_SIZE_W)
571 - current_nursery->free;
575 total_allocated += allocated;
579 /* Approximate the amount of live data in the heap. To be called just
580 * after garbage collection (see GarbageCollect()).
589 if (RtsFlags.GcFlags.generations == 1) {
590 live = (g0s0->to_blocks - 1) * BLOCK_SIZE_W +
591 ((lnat)g0s0->hp_bd->free - (lnat)g0s0->hp_bd->start) / sizeof(W_);
595 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
596 for (s = 0; s < generations[g].n_steps; s++) {
597 /* approximate amount of live data (doesn't take into account slop
598 * at end of each block).
600 if (g == 0 && s == 0) {
603 stp = &generations[g].steps[s];
604 live += (stp->n_blocks - 1) * BLOCK_SIZE_W +
605 ((lnat)stp->hp_bd->free - (lnat)stp->hp_bd->start) / sizeof(W_);
611 /* Approximate the number of blocks that will be needed at the next
612 * garbage collection.
614 * Assume: all data currently live will remain live. Steps that will
615 * be collected next time will therefore need twice as many blocks
616 * since all the data will be copied.
625 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
626 for (s = 0; s < generations[g].n_steps; s++) {
627 if (g == 0 && s == 0) { continue; }
628 stp = &generations[g].steps[s];
629 if (generations[g].steps[0].n_blocks > generations[g].max_blocks) {
630 needed += 2 * stp->n_blocks;
632 needed += stp->n_blocks;
639 /* -----------------------------------------------------------------------------
642 memInventory() checks for memory leaks by counting up all the
643 blocks we know about and comparing that to the number of blocks
644 allegedly floating around in the system.
645 -------------------------------------------------------------------------- */
655 lnat total_blocks = 0, free_blocks = 0;
657 /* count the blocks we current have */
659 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
660 for (s = 0; s < generations[g].n_steps; s++) {
661 stp = &generations[g].steps[s];
662 total_blocks += stp->n_blocks;
663 if (RtsFlags.GcFlags.generations == 1) {
664 /* two-space collector has a to-space too :-) */
665 total_blocks += g0s0->to_blocks;
667 for (bd = stp->large_objects; bd; bd = bd->link) {
668 total_blocks += bd->blocks;
669 /* hack for megablock groups: they have an extra block or two in
670 the second and subsequent megablocks where the block
671 descriptors would normally go.
673 if (bd->blocks > BLOCKS_PER_MBLOCK) {
674 total_blocks -= (MBLOCK_SIZE / BLOCK_SIZE - BLOCKS_PER_MBLOCK)
675 * (bd->blocks/(MBLOCK_SIZE/BLOCK_SIZE));
681 /* any blocks held by allocate() */
682 for (bd = small_alloc_list; bd; bd = bd->link) {
683 total_blocks += bd->blocks;
685 for (bd = large_alloc_list; bd; bd = bd->link) {
686 total_blocks += bd->blocks;
689 /* count the blocks on the free list */
690 free_blocks = countFreeList();
692 ASSERT(total_blocks + free_blocks == mblocks_allocated * BLOCKS_PER_MBLOCK);
695 if (total_blocks + free_blocks != mblocks_allocated *
697 fprintf(stderr, "Blocks: %ld live + %ld free = %ld total (%ld around)\n",
698 total_blocks, free_blocks, total_blocks + free_blocks,
699 mblocks_allocated * BLOCKS_PER_MBLOCK);
704 /* Full heap sanity check. */
711 if (RtsFlags.GcFlags.generations == 1) {
712 checkHeap(g0s0->to_space, NULL);
713 checkChain(g0s0->large_objects);
716 for (g = 0; g <= N; g++) {
717 for (s = 0; s < generations[g].n_steps; s++) {
718 if (g == 0 && s == 0) { continue; }
719 checkHeap(generations[g].steps[s].blocks, NULL);
722 for (g = N+1; g < RtsFlags.GcFlags.generations; g++) {
723 for (s = 0; s < generations[g].n_steps; s++) {
724 checkHeap(generations[g].steps[s].blocks,
725 generations[g].steps[s].blocks->start);
726 checkChain(generations[g].steps[s].large_objects);
729 checkFreeListSanity();