1 /* -----------------------------------------------------------------------------
2 * $Id: Storage.c,v 1.34 2001/01/29 17:23:41 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
71 #if defined(PROFILING) || defined(DEBUG)
72 if (RtsFlags.ProfFlags.doHeapProfile) {
73 RtsFlags.GcFlags.generations = 1;
74 RtsFlags.GcFlags.steps = 1;
75 RtsFlags.GcFlags.oldGenFactor = 0;
76 RtsFlags.GcFlags.heapSizeSuggestion = 0;
80 if (RtsFlags.GcFlags.heapSizeSuggestion >
81 RtsFlags.GcFlags.maxHeapSize) {
82 RtsFlags.GcFlags.maxHeapSize = RtsFlags.GcFlags.heapSizeSuggestion;
87 /* allocate generation info array */
88 generations = (generation *)stgMallocBytes(RtsFlags.GcFlags.generations
89 * sizeof(struct _generation),
92 /* Initialise all generations */
93 for(g = 0; g < RtsFlags.GcFlags.generations; g++) {
94 gen = &generations[g];
96 gen->mut_list = END_MUT_LIST;
97 gen->mut_once_list = END_MUT_LIST;
99 gen->failed_promotions = 0;
103 /* A couple of convenience pointers */
104 g0 = &generations[0];
105 oldest_gen = &generations[RtsFlags.GcFlags.generations-1];
107 /* Allocate step structures in each generation */
108 if (RtsFlags.GcFlags.generations > 1) {
109 /* Only for multiple-generations */
111 /* Oldest generation: one step */
112 oldest_gen->n_steps = 1;
114 stgMallocBytes(1 * sizeof(struct _step), "initStorage: last step");
116 /* set up all except the oldest generation with 2 steps */
117 for(g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
118 generations[g].n_steps = RtsFlags.GcFlags.steps;
119 generations[g].steps =
120 stgMallocBytes (RtsFlags.GcFlags.steps * sizeof(struct _step),
121 "initStorage: steps");
125 /* single generation, i.e. a two-space collector */
127 g0->steps = stgMallocBytes (sizeof(struct _step), "initStorage: steps");
130 /* Initialise all steps */
131 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
132 for (s = 0; s < generations[g].n_steps; s++) {
133 stp = &generations[g].steps[s];
137 stp->gen = &generations[g];
143 stp->large_objects = NULL;
144 stp->new_large_objects = NULL;
145 stp->scavenged_large_objects = NULL;
149 /* Set up the destination pointers in each younger gen. step */
150 for (g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
151 for (s = 0; s < generations[g].n_steps-1; s++) {
152 generations[g].steps[s].to = &generations[g].steps[s+1];
154 generations[g].steps[s].to = &generations[g+1].steps[0];
157 /* The oldest generation has one step and its destination is the
159 oldest_gen->steps[0].to = &oldest_gen->steps[0];
161 /* generation 0 is special: that's the nursery */
162 generations[0].max_blocks = 0;
164 /* G0S0: the allocation area. Policy: keep the allocation area
165 * small to begin with, even if we have a large suggested heap
166 * size. Reason: we're going to do a major collection first, and we
167 * don't want it to be a big one. This vague idea is borne out by
168 * rigorous experimental evidence.
170 g0s0 = &generations[0].steps[0];
174 weak_ptr_list = NULL;
177 /* initialise the allocate() interface */
178 small_alloc_list = NULL;
179 large_alloc_list = NULL;
181 alloc_blocks_lim = RtsFlags.GcFlags.minAllocAreaSize;
183 /* Tell GNU multi-precision pkg about our custom alloc functions */
184 mp_set_memory_functions(stgAllocForGMP, stgReallocForGMP, stgDeallocForGMP);
187 pthread_mutex_init(&sm_mutex, NULL);
190 IF_DEBUG(gc, stat_describe_gens());
196 stat_exit(calcAllocated());
199 /* -----------------------------------------------------------------------------
202 The entry code for every CAF does the following:
204 - builds a CAF_BLACKHOLE in the heap
205 - pushes an update frame pointing to the CAF_BLACKHOLE
206 - invokes UPD_CAF(), which:
207 - calls newCaf, below
208 - updates the CAF with a static indirection to the CAF_BLACKHOLE
210 Why do we build a BLACKHOLE in the heap rather than just updating
211 the thunk directly? It's so that we only need one kind of update
212 frame - otherwise we'd need a static version of the update frame too.
214 newCaf() does the following:
216 - it puts the CAF on the oldest generation's mut-once list.
217 This is so that we can treat the CAF as a root when collecting
220 For GHCI, we have additional requirements when dealing with CAFs:
222 - we must *retain* all dynamically-loaded CAFs ever entered,
223 just in case we need them again.
224 - we must be able to *revert* CAFs that have been evaluated, to
225 their pre-evaluated form.
227 To do this, we use an additional CAF list. When newCaf() is
228 called on a dynamically-loaded CAF, we add it to the CAF list
229 instead of the old-generation mutable list, and save away its
230 old info pointer (in caf->saved_info) for later reversion.
232 To revert all the CAFs, we traverse the CAF list and reset the
233 info pointer to caf->saved_info, then throw away the CAF list.
234 (see GC.c:revertCAFs()).
238 -------------------------------------------------------------------------- */
241 newCAF(StgClosure* caf)
243 /* Put this CAF on the mutable list for the old generation.
244 * This is a HACK - the IND_STATIC closure doesn't really have
245 * a mut_link field, but we pretend it has - in fact we re-use
246 * the STATIC_LINK field for the time being, because when we
247 * come to do a major GC we won't need the mut_link field
248 * any more and can use it as a STATIC_LINK.
250 ACQUIRE_LOCK(&sm_mutex);
253 if (is_dynamically_loaded_rwdata_ptr((StgPtr)caf)) {
254 ((StgIndStatic *)caf)->saved_info = (StgInfoTable *)caf->header.info;
255 ((StgIndStatic *)caf)->static_link = caf_list;
258 ((StgIndStatic *)caf)->saved_info = NULL;
259 ((StgMutClosure *)caf)->mut_link = oldest_gen->mut_once_list;
260 oldest_gen->mut_once_list = (StgMutClosure *)caf;
263 ASSERT( ((StgMutClosure*)caf)->mut_link == NULL );
264 ((StgMutClosure *)caf)->mut_link = oldest_gen->mut_once_list;
265 oldest_gen->mut_once_list = (StgMutClosure *)caf;
268 RELEASE_LOCK(&sm_mutex);
277 for (p = caf_list; p != NULL; p = STATIC_LINK2(get_itbl(p),p)) {
283 /* -----------------------------------------------------------------------------
285 -------------------------------------------------------------------------- */
288 allocNurseries( void )
297 for (cap = free_capabilities; cap != NULL; cap = cap->link) {
298 cap->rNursery = allocNursery(NULL, RtsFlags.GcFlags.minAllocAreaSize);
299 cap->rCurrentNursery = cap->rNursery;
300 for (bd = cap->rNursery; bd != NULL; bd = bd->link) {
301 bd->back = (bdescr *)cap;
304 /* Set the back links to be equal to the Capability,
305 * so we can do slightly better informed locking.
309 nursery_blocks = RtsFlags.GcFlags.minAllocAreaSize;
310 g0s0->blocks = allocNursery(NULL, nursery_blocks);
311 g0s0->n_blocks = nursery_blocks;
312 g0s0->to_space = NULL;
313 MainRegTable.rNursery = g0s0->blocks;
314 MainRegTable.rCurrentNursery = g0s0->blocks;
315 /* hp, hpLim, hp_bd, to_space etc. aren't used in G0S0 */
320 resetNurseries( void )
326 /* All tasks must be stopped */
327 ASSERT(n_free_capabilities == RtsFlags.ParFlags.nNodes);
329 for (cap = free_capabilities; cap != NULL; cap = cap->link) {
330 for (bd = cap->rNursery; bd; bd = bd->link) {
331 bd->free = bd->start;
332 ASSERT(bd->gen == g0);
333 ASSERT(bd->step == g0s0);
334 IF_DEBUG(sanity,memset(bd->start, 0xaa, BLOCK_SIZE));
336 cap->rCurrentNursery = cap->rNursery;
339 for (bd = g0s0->blocks; bd; bd = bd->link) {
340 bd->free = bd->start;
341 ASSERT(bd->gen == g0);
342 ASSERT(bd->step == g0s0);
343 IF_DEBUG(sanity,memset(bd->start, 0xaa, BLOCK_SIZE));
345 MainRegTable.rNursery = g0s0->blocks;
346 MainRegTable.rCurrentNursery = g0s0->blocks;
351 allocNursery (bdescr *last_bd, nat blocks)
356 /* Allocate a nursery */
357 for (i=0; i < blocks; i++) {
363 bd->free = bd->start;
370 resizeNursery ( nat blocks )
375 barf("resizeNursery: can't resize in SMP mode");
378 if (nursery_blocks == blocks) {
379 ASSERT(g0s0->n_blocks == blocks);
383 else if (nursery_blocks < blocks) {
384 IF_DEBUG(gc, fprintf(stderr, "Increasing size of nursery to %d blocks\n",
386 g0s0->blocks = allocNursery(g0s0->blocks, blocks-nursery_blocks);
392 IF_DEBUG(gc, fprintf(stderr, "Decreasing size of nursery to %d blocks\n",
394 for (bd = g0s0->blocks; nursery_blocks > blocks; nursery_blocks--) {
402 g0s0->n_blocks = nursery_blocks = blocks;
405 /* -----------------------------------------------------------------------------
406 The allocate() interface
408 allocate(n) always succeeds, and returns a chunk of memory n words
409 long. n can be larger than the size of a block if necessary, in
410 which case a contiguous block group will be allocated.
411 -------------------------------------------------------------------------- */
419 ACQUIRE_LOCK(&sm_mutex);
421 TICK_ALLOC_HEAP_NOCTR(n);
424 /* big allocation (>LARGE_OBJECT_THRESHOLD) */
425 /* ToDo: allocate directly into generation 1 */
426 if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
427 nat req_blocks = (lnat)BLOCK_ROUND_UP(n*sizeof(W_)) / BLOCK_SIZE;
428 bd = allocGroup(req_blocks);
429 dbl_link_onto(bd, &g0s0->large_objects);
433 bd->free = bd->start;
434 /* don't add these blocks to alloc_blocks, since we're assuming
435 * that large objects are likely to remain live for quite a while
436 * (eg. running threads), so garbage collecting early won't make
439 alloc_blocks += req_blocks;
440 RELEASE_LOCK(&sm_mutex);
443 /* small allocation (<LARGE_OBJECT_THRESHOLD) */
444 } else if (small_alloc_list == NULL || alloc_Hp + n > alloc_HpLim) {
445 if (small_alloc_list) {
446 small_alloc_list->free = alloc_Hp;
449 bd->link = small_alloc_list;
450 small_alloc_list = bd;
454 alloc_Hp = bd->start;
455 alloc_HpLim = bd->start + BLOCK_SIZE_W;
461 RELEASE_LOCK(&sm_mutex);
465 lnat allocated_bytes(void)
467 return (alloc_blocks * BLOCK_SIZE_W - (alloc_HpLim - alloc_Hp));
470 /* -----------------------------------------------------------------------------
471 Allocation functions for GMP.
473 These all use the allocate() interface - we can't have any garbage
474 collection going on during a gmp operation, so we use allocate()
475 which always succeeds. The gmp operations which might need to
476 allocate will ask the storage manager (via doYouWantToGC()) whether
477 a garbage collection is required, in case we get into a loop doing
478 only allocate() style allocation.
479 -------------------------------------------------------------------------- */
482 stgAllocForGMP (size_t size_in_bytes)
485 nat data_size_in_words, total_size_in_words;
487 /* should be a multiple of sizeof(StgWord) (whole no. of limbs) */
488 ASSERT(size_in_bytes % sizeof(W_) == 0);
490 data_size_in_words = size_in_bytes / sizeof(W_);
491 total_size_in_words = sizeofW(StgArrWords) + data_size_in_words;
493 /* allocate and fill it in. */
494 arr = (StgArrWords *)allocate(total_size_in_words);
495 SET_ARR_HDR(arr, &stg_ARR_WORDS_info, CCCS, data_size_in_words);
497 /* and return a ptr to the goods inside the array */
498 return(BYTE_ARR_CTS(arr));
502 stgReallocForGMP (void *ptr, size_t old_size, size_t new_size)
504 void *new_stuff_ptr = stgAllocForGMP(new_size);
506 char *p = (char *) ptr;
507 char *q = (char *) new_stuff_ptr;
509 for (; i < old_size; i++, p++, q++) {
513 return(new_stuff_ptr);
517 stgDeallocForGMP (void *ptr STG_UNUSED,
518 size_t size STG_UNUSED)
520 /* easy for us: the garbage collector does the dealloc'n */
523 /* -----------------------------------------------------------------------------
525 * -------------------------------------------------------------------------- */
527 /* -----------------------------------------------------------------------------
530 * Approximate how much we've allocated: number of blocks in the
531 * nursery + blocks allocated via allocate() - unused nusery blocks.
532 * This leaves a little slop at the end of each block, and doesn't
533 * take into account large objects (ToDo).
534 * -------------------------------------------------------------------------- */
537 calcAllocated( void )
545 /* All tasks must be stopped. Can't assert that all the
546 capabilities are owned by the scheduler, though: one or more
547 tasks might have been stopped while they were running (non-main)
549 /* ASSERT(n_free_capabilities == RtsFlags.ParFlags.nNodes); */
552 n_free_capabilities * RtsFlags.GcFlags.minAllocAreaSize * BLOCK_SIZE_W
555 for (cap = free_capabilities; cap != NULL; cap = cap->link) {
556 for ( bd = cap->rCurrentNursery->link; bd != NULL; bd = bd->link ) {
557 allocated -= BLOCK_SIZE_W;
559 if (cap->rCurrentNursery->free < cap->rCurrentNursery->start
561 allocated -= (cap->rCurrentNursery->start + BLOCK_SIZE_W)
562 - cap->rCurrentNursery->free;
567 bdescr *current_nursery = MainRegTable.rCurrentNursery;
569 allocated = (nursery_blocks * BLOCK_SIZE_W) + allocated_bytes();
570 for ( bd = current_nursery->link; bd != NULL; bd = bd->link ) {
571 allocated -= BLOCK_SIZE_W;
573 if (current_nursery->free < current_nursery->start + BLOCK_SIZE_W) {
574 allocated -= (current_nursery->start + BLOCK_SIZE_W)
575 - current_nursery->free;
579 total_allocated += allocated;
583 /* Approximate the amount of live data in the heap. To be called just
584 * after garbage collection (see GarbageCollect()).
593 if (RtsFlags.GcFlags.generations == 1) {
594 live = (g0s0->to_blocks - 1) * BLOCK_SIZE_W +
595 ((lnat)g0s0->hp_bd->free - (lnat)g0s0->hp_bd->start) / sizeof(W_);
599 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
600 for (s = 0; s < generations[g].n_steps; s++) {
601 /* approximate amount of live data (doesn't take into account slop
602 * at end of each block).
604 if (g == 0 && s == 0) {
607 stp = &generations[g].steps[s];
608 live += (stp->n_blocks - 1) * BLOCK_SIZE_W +
609 ((lnat)stp->hp_bd->free - (lnat)stp->hp_bd->start) / sizeof(W_);
615 /* Approximate the number of blocks that will be needed at the next
616 * garbage collection.
618 * Assume: all data currently live will remain live. Steps that will
619 * be collected next time will therefore need twice as many blocks
620 * since all the data will be copied.
629 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
630 for (s = 0; s < generations[g].n_steps; s++) {
631 if (g == 0 && s == 0) { continue; }
632 stp = &generations[g].steps[s];
633 if (generations[g].steps[0].n_blocks > generations[g].max_blocks) {
634 needed += 2 * stp->n_blocks;
636 needed += stp->n_blocks;
643 /* -----------------------------------------------------------------------------
646 memInventory() checks for memory leaks by counting up all the
647 blocks we know about and comparing that to the number of blocks
648 allegedly floating around in the system.
649 -------------------------------------------------------------------------- */
659 lnat total_blocks = 0, free_blocks = 0;
661 /* count the blocks we current have */
663 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
664 for (s = 0; s < generations[g].n_steps; s++) {
665 stp = &generations[g].steps[s];
666 total_blocks += stp->n_blocks;
667 if (RtsFlags.GcFlags.generations == 1) {
668 /* two-space collector has a to-space too :-) */
669 total_blocks += g0s0->to_blocks;
671 for (bd = stp->large_objects; bd; bd = bd->link) {
672 total_blocks += bd->blocks;
673 /* hack for megablock groups: they have an extra block or two in
674 the second and subsequent megablocks where the block
675 descriptors would normally go.
677 if (bd->blocks > BLOCKS_PER_MBLOCK) {
678 total_blocks -= (MBLOCK_SIZE / BLOCK_SIZE - BLOCKS_PER_MBLOCK)
679 * (bd->blocks/(MBLOCK_SIZE/BLOCK_SIZE));
685 /* any blocks held by allocate() */
686 for (bd = small_alloc_list; bd; bd = bd->link) {
687 total_blocks += bd->blocks;
689 for (bd = large_alloc_list; bd; bd = bd->link) {
690 total_blocks += bd->blocks;
693 /* count the blocks on the free list */
694 free_blocks = countFreeList();
696 ASSERT(total_blocks + free_blocks == mblocks_allocated * BLOCKS_PER_MBLOCK);
699 if (total_blocks + free_blocks != mblocks_allocated *
701 fprintf(stderr, "Blocks: %ld live + %ld free = %ld total (%ld around)\n",
702 total_blocks, free_blocks, total_blocks + free_blocks,
703 mblocks_allocated * BLOCKS_PER_MBLOCK);
708 /* Full heap sanity check. */
715 if (RtsFlags.GcFlags.generations == 1) {
716 checkHeap(g0s0->to_space, NULL);
717 checkChain(g0s0->large_objects);
720 for (g = 0; g <= N; g++) {
721 for (s = 0; s < generations[g].n_steps; s++) {
722 if (g == 0 && s == 0) { continue; }
723 checkHeap(generations[g].steps[s].blocks, NULL);
726 for (g = N+1; g < RtsFlags.GcFlags.generations; g++) {
727 for (s = 0; s < generations[g].n_steps; s++) {
728 checkHeap(generations[g].steps[s].blocks,
729 generations[g].steps[s].blocks->start);
730 checkChain(generations[g].steps[s].large_objects);
733 checkFreeListSanity();