1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team, 1998-2006
5 * Storage manager front end
7 * Documentation on the architecture of the Storage Manager can be
8 * found in the online commentary:
10 * http://hackage.haskell.org/trac/ghc/wiki/Commentary/Rts/Storage
12 * ---------------------------------------------------------------------------*/
14 #include "PosixSource.h"
20 #include "BlockAlloc.h"
25 #include "OSThreads.h"
26 #include "Capability.h"
29 #include "RetainerProfile.h" // for counting memory blocks (memInventory)
39 * All these globals require sm_mutex to access in THREADED_RTS mode.
41 StgClosure *caf_list = NULL;
42 StgClosure *revertible_caf_list = NULL;
45 bdescr *pinned_object_block; /* allocate pinned objects into this block */
46 nat alloc_blocks; /* number of allocate()d blocks since GC */
47 nat alloc_blocks_lim; /* approximate limit on alloc_blocks */
49 generation *generations = NULL; /* all the generations */
50 generation *g0 = NULL; /* generation 0, for convenience */
51 generation *oldest_gen = NULL; /* oldest generation, for convenience */
52 step *g0s0 = NULL; /* generation 0, step 0, for convenience */
54 ullong total_allocated = 0; /* total memory allocated during run */
56 nat n_nurseries = 0; /* == RtsFlags.ParFlags.nNodes, convenience */
57 step *nurseries = NULL; /* array of nurseries, >1 only if THREADED_RTS */
61 * Storage manager mutex: protects all the above state from
62 * simultaneous access by two STG threads.
66 * This mutex is used by atomicModifyMutVar# only
68 Mutex atomic_modify_mutvar_mutex;
75 static void *stgAllocForGMP (size_t size_in_bytes);
76 static void *stgReallocForGMP (void *ptr, size_t old_size, size_t new_size);
77 static void stgDeallocForGMP (void *ptr, size_t size);
80 initStep (step *stp, int g, int s)
85 stp->old_blocks = NULL;
86 stp->n_old_blocks = 0;
87 stp->gen = &generations[g];
89 stp->large_objects = NULL;
90 stp->n_large_blocks = 0;
91 stp->scavenged_large_objects = NULL;
92 stp->n_scavenged_large_blocks = 0;
93 stp->is_compacted = 0;
96 initSpinLock(&stp->sync_todo);
97 initSpinLock(&stp->sync_large_objects);
108 if (generations != NULL) {
109 // multi-init protection
115 /* Sanity check to make sure the LOOKS_LIKE_ macros appear to be
116 * doing something reasonable.
118 /* We use the NOT_NULL variant or gcc warns that the test is always true */
119 ASSERT(LOOKS_LIKE_INFO_PTR_NOT_NULL(&stg_BLACKHOLE_info));
120 ASSERT(LOOKS_LIKE_CLOSURE_PTR(&stg_dummy_ret_closure));
121 ASSERT(!HEAP_ALLOCED(&stg_dummy_ret_closure));
123 if (RtsFlags.GcFlags.maxHeapSize != 0 &&
124 RtsFlags.GcFlags.heapSizeSuggestion >
125 RtsFlags.GcFlags.maxHeapSize) {
126 RtsFlags.GcFlags.maxHeapSize = RtsFlags.GcFlags.heapSizeSuggestion;
129 if (RtsFlags.GcFlags.maxHeapSize != 0 &&
130 RtsFlags.GcFlags.minAllocAreaSize >
131 RtsFlags.GcFlags.maxHeapSize) {
132 errorBelch("maximum heap size (-M) is smaller than minimum alloc area size (-A)");
133 RtsFlags.GcFlags.minAllocAreaSize = RtsFlags.GcFlags.maxHeapSize;
136 initBlockAllocator();
138 #if defined(THREADED_RTS)
139 initMutex(&sm_mutex);
140 initMutex(&atomic_modify_mutvar_mutex);
145 /* allocate generation info array */
146 generations = (generation *)stgMallocBytes(RtsFlags.GcFlags.generations
147 * sizeof(struct generation_),
148 "initStorage: gens");
150 /* allocate all the steps into an array. It is important that we do
151 it this way, because we need the invariant that two step pointers
152 can be directly compared to see which is the oldest.
153 Remember that the last generation has only one step. */
154 step_arr = stgMallocBytes(sizeof(struct step_)
155 * (1 + ((RtsFlags.GcFlags.generations - 1)
156 * RtsFlags.GcFlags.steps)),
157 "initStorage: steps");
159 /* Initialise all generations */
160 for(g = 0; g < RtsFlags.GcFlags.generations; g++) {
161 gen = &generations[g];
163 gen->mut_list = allocBlock();
164 gen->collections = 0;
165 gen->failed_promotions = 0;
169 /* A couple of convenience pointers */
170 g0 = &generations[0];
171 oldest_gen = &generations[RtsFlags.GcFlags.generations-1];
173 /* Allocate step structures in each generation */
174 if (RtsFlags.GcFlags.generations > 1) {
175 /* Only for multiple-generations */
177 /* Oldest generation: one step */
178 oldest_gen->n_steps = 1;
179 oldest_gen->steps = step_arr + (RtsFlags.GcFlags.generations - 1)
180 * RtsFlags.GcFlags.steps;
182 /* set up all except the oldest generation with 2 steps */
183 for(g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
184 generations[g].n_steps = RtsFlags.GcFlags.steps;
185 generations[g].steps = step_arr + g * RtsFlags.GcFlags.steps;
189 /* single generation, i.e. a two-space collector */
191 g0->steps = step_arr;
195 n_nurseries = n_capabilities;
199 nurseries = stgMallocBytes (n_nurseries * sizeof(struct step_),
200 "initStorage: nurseries");
202 /* Initialise all steps */
203 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
204 for (s = 0; s < generations[g].n_steps; s++) {
205 initStep(&generations[g].steps[s], g, s);
209 for (s = 0; s < n_nurseries; s++) {
210 initStep(&nurseries[s], 0, s);
213 /* Set up the destination pointers in each younger gen. step */
214 for (g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
215 for (s = 0; s < generations[g].n_steps-1; s++) {
216 generations[g].steps[s].to = &generations[g].steps[s+1];
218 generations[g].steps[s].to = &generations[g+1].steps[0];
220 oldest_gen->steps[0].to = &oldest_gen->steps[0];
222 for (s = 0; s < n_nurseries; s++) {
223 nurseries[s].to = generations[0].steps[0].to;
226 /* The oldest generation has one step. */
227 if (RtsFlags.GcFlags.compact) {
228 if (RtsFlags.GcFlags.generations == 1) {
229 errorBelch("WARNING: compaction is incompatible with -G1; disabled");
231 oldest_gen->steps[0].is_compacted = 1;
235 generations[0].max_blocks = 0;
236 g0s0 = &generations[0].steps[0];
238 /* The allocation area. Policy: keep the allocation area
239 * small to begin with, even if we have a large suggested heap
240 * size. Reason: we're going to do a major collection first, and we
241 * don't want it to be a big one. This vague idea is borne out by
242 * rigorous experimental evidence.
246 weak_ptr_list = NULL;
248 revertible_caf_list = NULL;
250 /* initialise the allocate() interface */
252 alloc_blocks_lim = RtsFlags.GcFlags.minAllocAreaSize;
254 /* Tell GNU multi-precision pkg about our custom alloc functions */
255 mp_set_memory_functions(stgAllocForGMP, stgReallocForGMP, stgDeallocForGMP);
258 initSpinLock(&gc_alloc_block_sync);
261 IF_DEBUG(gc, statDescribeGens());
269 stat_exit(calcAllocated());
275 stgFree(g0s0); // frees all the steps
276 stgFree(generations);
278 #if defined(THREADED_RTS)
279 closeMutex(&sm_mutex);
280 closeMutex(&atomic_modify_mutvar_mutex);
285 /* -----------------------------------------------------------------------------
288 The entry code for every CAF does the following:
290 - builds a CAF_BLACKHOLE in the heap
291 - pushes an update frame pointing to the CAF_BLACKHOLE
292 - invokes UPD_CAF(), which:
293 - calls newCaf, below
294 - updates the CAF with a static indirection to the CAF_BLACKHOLE
296 Why do we build a BLACKHOLE in the heap rather than just updating
297 the thunk directly? It's so that we only need one kind of update
298 frame - otherwise we'd need a static version of the update frame too.
300 newCaf() does the following:
302 - it puts the CAF on the oldest generation's mut-once list.
303 This is so that we can treat the CAF as a root when collecting
306 For GHCI, we have additional requirements when dealing with CAFs:
308 - we must *retain* all dynamically-loaded CAFs ever entered,
309 just in case we need them again.
310 - we must be able to *revert* CAFs that have been evaluated, to
311 their pre-evaluated form.
313 To do this, we use an additional CAF list. When newCaf() is
314 called on a dynamically-loaded CAF, we add it to the CAF list
315 instead of the old-generation mutable list, and save away its
316 old info pointer (in caf->saved_info) for later reversion.
318 To revert all the CAFs, we traverse the CAF list and reset the
319 info pointer to caf->saved_info, then throw away the CAF list.
320 (see GC.c:revertCAFs()).
324 -------------------------------------------------------------------------- */
327 newCAF(StgClosure* caf)
334 // If we are in GHCi _and_ we are using dynamic libraries,
335 // then we can't redirect newCAF calls to newDynCAF (see below),
336 // so we make newCAF behave almost like newDynCAF.
337 // The dynamic libraries might be used by both the interpreted
338 // program and GHCi itself, so they must not be reverted.
339 // This also means that in GHCi with dynamic libraries, CAFs are not
340 // garbage collected. If this turns out to be a problem, we could
341 // do another hack here and do an address range test on caf to figure
342 // out whether it is from a dynamic library.
343 ((StgIndStatic *)caf)->saved_info = (StgInfoTable *)caf->header.info;
344 ((StgIndStatic *)caf)->static_link = caf_list;
349 /* Put this CAF on the mutable list for the old generation.
350 * This is a HACK - the IND_STATIC closure doesn't really have
351 * a mut_link field, but we pretend it has - in fact we re-use
352 * the STATIC_LINK field for the time being, because when we
353 * come to do a major GC we won't need the mut_link field
354 * any more and can use it as a STATIC_LINK.
356 ((StgIndStatic *)caf)->saved_info = NULL;
357 recordMutableGen(caf, oldest_gen);
363 // An alternate version of newCaf which is used for dynamically loaded
364 // object code in GHCi. In this case we want to retain *all* CAFs in
365 // the object code, because they might be demanded at any time from an
366 // expression evaluated on the command line.
367 // Also, GHCi might want to revert CAFs, so we add these to the
368 // revertible_caf_list.
370 // The linker hackily arranges that references to newCaf from dynamic
371 // code end up pointing to newDynCAF.
373 newDynCAF(StgClosure *caf)
377 ((StgIndStatic *)caf)->saved_info = (StgInfoTable *)caf->header.info;
378 ((StgIndStatic *)caf)->static_link = revertible_caf_list;
379 revertible_caf_list = caf;
384 /* -----------------------------------------------------------------------------
386 -------------------------------------------------------------------------- */
389 allocNursery (step *stp, bdescr *tail, nat blocks)
394 // Allocate a nursery: we allocate fresh blocks one at a time and
395 // cons them on to the front of the list, not forgetting to update
396 // the back pointer on the tail of the list to point to the new block.
397 for (i=0; i < blocks; i++) {
400 processNursery() in LdvProfile.c assumes that every block group in
401 the nursery contains only a single block. So, if a block group is
402 given multiple blocks, change processNursery() accordingly.
406 // double-link the nursery: we might need to insert blocks
413 bd->free = bd->start;
421 assignNurseriesToCapabilities (void)
426 for (i = 0; i < n_nurseries; i++) {
427 capabilities[i].r.rNursery = &nurseries[i];
428 capabilities[i].r.rCurrentNursery = nurseries[i].blocks;
429 capabilities[i].r.rCurrentAlloc = NULL;
431 #else /* THREADED_RTS */
432 MainCapability.r.rNursery = &nurseries[0];
433 MainCapability.r.rCurrentNursery = nurseries[0].blocks;
434 MainCapability.r.rCurrentAlloc = NULL;
439 allocNurseries( void )
443 for (i = 0; i < n_nurseries; i++) {
444 nurseries[i].blocks =
445 allocNursery(&nurseries[i], NULL,
446 RtsFlags.GcFlags.minAllocAreaSize);
447 nurseries[i].n_blocks = RtsFlags.GcFlags.minAllocAreaSize;
448 nurseries[i].old_blocks = NULL;
449 nurseries[i].n_old_blocks = 0;
451 assignNurseriesToCapabilities();
455 resetNurseries( void )
461 for (i = 0; i < n_nurseries; i++) {
463 for (bd = stp->blocks; bd; bd = bd->link) {
464 bd->free = bd->start;
465 ASSERT(bd->gen_no == 0);
466 ASSERT(bd->step == stp);
467 IF_DEBUG(sanity,memset(bd->start, 0xaa, BLOCK_SIZE));
470 assignNurseriesToCapabilities();
474 countNurseryBlocks (void)
479 for (i = 0; i < n_nurseries; i++) {
480 blocks += nurseries[i].n_blocks;
486 resizeNursery ( step *stp, nat blocks )
491 nursery_blocks = stp->n_blocks;
492 if (nursery_blocks == blocks) return;
494 if (nursery_blocks < blocks) {
495 debugTrace(DEBUG_gc, "increasing size of nursery to %d blocks",
497 stp->blocks = allocNursery(stp, stp->blocks, blocks-nursery_blocks);
502 debugTrace(DEBUG_gc, "decreasing size of nursery to %d blocks",
506 while (nursery_blocks > blocks) {
508 next_bd->u.back = NULL;
509 nursery_blocks -= bd->blocks; // might be a large block
514 // might have gone just under, by freeing a large block, so make
515 // up the difference.
516 if (nursery_blocks < blocks) {
517 stp->blocks = allocNursery(stp, stp->blocks, blocks-nursery_blocks);
521 stp->n_blocks = blocks;
522 ASSERT(countBlocks(stp->blocks) == stp->n_blocks);
526 // Resize each of the nurseries to the specified size.
529 resizeNurseriesFixed (nat blocks)
532 for (i = 0; i < n_nurseries; i++) {
533 resizeNursery(&nurseries[i], blocks);
538 // Resize the nurseries to the total specified size.
541 resizeNurseries (nat blocks)
543 // If there are multiple nurseries, then we just divide the number
544 // of available blocks between them.
545 resizeNurseriesFixed(blocks / n_nurseries);
548 /* -----------------------------------------------------------------------------
549 The allocate() interface
551 allocateInGen() function allocates memory directly into a specific
552 generation. It always succeeds, and returns a chunk of memory n
553 words long. n can be larger than the size of a block if necessary,
554 in which case a contiguous block group will be allocated.
556 allocate(n) is equivalent to allocateInGen(g0).
557 -------------------------------------------------------------------------- */
560 allocateInGen (generation *g, nat n)
568 TICK_ALLOC_HEAP_NOCTR(n);
573 if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_))
575 nat req_blocks = (lnat)BLOCK_ROUND_UP(n*sizeof(W_)) / BLOCK_SIZE;
577 // Attempting to allocate an object larger than maxHeapSize
578 // should definitely be disallowed. (bug #1791)
579 if (RtsFlags.GcFlags.maxHeapSize > 0 &&
580 req_blocks >= RtsFlags.GcFlags.maxHeapSize) {
584 bd = allocGroup(req_blocks);
585 dbl_link_onto(bd, &stp->large_objects);
586 stp->n_large_blocks += bd->blocks; // might be larger than req_blocks
589 bd->flags = BF_LARGE;
590 bd->free = bd->start + n;
595 // small allocation (<LARGE_OBJECT_THRESHOLD) */
597 if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
602 bd->link = stp->blocks;
619 return allocateInGen(g0,n);
623 allocatedBytes( void )
627 allocated = alloc_blocks * BLOCK_SIZE_W;
628 if (pinned_object_block != NULL) {
629 allocated -= (pinned_object_block->start + BLOCK_SIZE_W) -
630 pinned_object_block->free;
636 /* -----------------------------------------------------------------------------
639 This allocates memory in the current thread - it is intended for
640 use primarily from STG-land where we have a Capability. It is
641 better than allocate() because it doesn't require taking the
642 sm_mutex lock in the common case.
644 Memory is allocated directly from the nursery if possible (but not
645 from the current nursery block, so as not to interfere with
647 -------------------------------------------------------------------------- */
650 allocateLocal (Capability *cap, nat n)
655 if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
656 return allocateInGen(g0,n);
659 /* small allocation (<LARGE_OBJECT_THRESHOLD) */
661 TICK_ALLOC_HEAP_NOCTR(n);
664 bd = cap->r.rCurrentAlloc;
665 if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
667 // The CurrentAlloc block is full, we need to find another
668 // one. First, we try taking the next block from the
670 bd = cap->r.rCurrentNursery->link;
672 if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
673 // The nursery is empty, or the next block is already
674 // full: allocate a fresh block (we can't fail here).
677 cap->r.rNursery->n_blocks++;
680 bd->step = cap->r.rNursery;
682 // NO: alloc_blocks++;
683 // calcAllocated() uses the size of the nursery, and we've
684 // already bumpted nursery->n_blocks above.
686 // we have a block in the nursery: take it and put
687 // it at the *front* of the nursery list, and use it
688 // to allocate() from.
689 cap->r.rCurrentNursery->link = bd->link;
690 if (bd->link != NULL) {
691 bd->link->u.back = cap->r.rCurrentNursery;
694 dbl_link_onto(bd, &cap->r.rNursery->blocks);
695 cap->r.rCurrentAlloc = bd;
696 IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
703 /* ---------------------------------------------------------------------------
704 Allocate a fixed/pinned object.
706 We allocate small pinned objects into a single block, allocating a
707 new block when the current one overflows. The block is chained
708 onto the large_object_list of generation 0 step 0.
710 NOTE: The GC can't in general handle pinned objects. This
711 interface is only safe to use for ByteArrays, which have no
712 pointers and don't require scavenging. It works because the
713 block's descriptor has the BF_LARGE flag set, so the block is
714 treated as a large object and chained onto various lists, rather
715 than the individual objects being copied. However, when it comes
716 to scavenge the block, the GC will only scavenge the first object.
717 The reason is that the GC can't linearly scan a block of pinned
718 objects at the moment (doing so would require using the
719 mostly-copying techniques). But since we're restricting ourselves
720 to pinned ByteArrays, not scavenging is ok.
722 This function is called by newPinnedByteArray# which immediately
723 fills the allocated memory with a MutableByteArray#.
724 ------------------------------------------------------------------------- */
727 allocatePinned( nat n )
730 bdescr *bd = pinned_object_block;
732 // If the request is for a large object, then allocate()
733 // will give us a pinned object anyway.
734 if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
740 TICK_ALLOC_HEAP_NOCTR(n);
743 // we always return 8-byte aligned memory. bd->free must be
744 // 8-byte aligned to begin with, so we just round up n to
745 // the nearest multiple of 8 bytes.
746 if (sizeof(StgWord) == 4) {
750 // If we don't have a block of pinned objects yet, or the current
751 // one isn't large enough to hold the new object, allocate a new one.
752 if (bd == NULL || (bd->free + n) > (bd->start + BLOCK_SIZE_W)) {
753 pinned_object_block = bd = allocBlock();
754 dbl_link_onto(bd, &g0s0->large_objects);
755 g0s0->n_large_blocks++;
758 bd->flags = BF_PINNED | BF_LARGE;
759 bd->free = bd->start;
769 /* -----------------------------------------------------------------------------
771 -------------------------------------------------------------------------- */
774 This is the write barrier for MUT_VARs, a.k.a. IORefs. A
775 MUT_VAR_CLEAN object is not on the mutable list; a MUT_VAR_DIRTY
776 is. When written to, a MUT_VAR_CLEAN turns into a MUT_VAR_DIRTY
777 and is put on the mutable list.
780 dirty_MUT_VAR(StgRegTable *reg, StgClosure *p)
782 Capability *cap = regTableToCapability(reg);
784 if (p->header.info == &stg_MUT_VAR_CLEAN_info) {
785 p->header.info = &stg_MUT_VAR_DIRTY_info;
786 bd = Bdescr((StgPtr)p);
787 if (bd->gen_no > 0) recordMutableCap(p,cap,bd->gen_no);
792 This is the write barrier for MVARs. An MVAR_CLEAN objects is not
793 on the mutable list; a MVAR_DIRTY is. When written to, a
794 MVAR_CLEAN turns into a MVAR_DIRTY and is put on the mutable list.
795 The check for MVAR_CLEAN is inlined at the call site for speed,
796 this really does make a difference on concurrency-heavy benchmarks
797 such as Chaneneos and cheap-concurrency.
800 dirty_MVAR(StgRegTable *reg, StgClosure *p)
802 Capability *cap = regTableToCapability(reg);
804 bd = Bdescr((StgPtr)p);
805 if (bd->gen_no > 0) recordMutableCap(p,cap,bd->gen_no);
808 /* -----------------------------------------------------------------------------
809 Allocation functions for GMP.
811 These all use the allocate() interface - we can't have any garbage
812 collection going on during a gmp operation, so we use allocate()
813 which always succeeds. The gmp operations which might need to
814 allocate will ask the storage manager (via doYouWantToGC()) whether
815 a garbage collection is required, in case we get into a loop doing
816 only allocate() style allocation.
817 -------------------------------------------------------------------------- */
820 stgAllocForGMP (size_t size_in_bytes)
823 nat data_size_in_words, total_size_in_words;
825 /* round up to a whole number of words */
826 data_size_in_words = (size_in_bytes + sizeof(W_) + 1) / sizeof(W_);
827 total_size_in_words = sizeofW(StgArrWords) + data_size_in_words;
829 /* allocate and fill it in. */
830 #if defined(THREADED_RTS)
831 arr = (StgArrWords *)allocateLocal(myTask()->cap, total_size_in_words);
833 arr = (StgArrWords *)allocateLocal(&MainCapability, total_size_in_words);
835 SET_ARR_HDR(arr, &stg_ARR_WORDS_info, CCCS, data_size_in_words);
837 /* and return a ptr to the goods inside the array */
842 stgReallocForGMP (void *ptr, size_t old_size, size_t new_size)
844 void *new_stuff_ptr = stgAllocForGMP(new_size);
846 char *p = (char *) ptr;
847 char *q = (char *) new_stuff_ptr;
849 for (; i < old_size; i++, p++, q++) {
853 return(new_stuff_ptr);
857 stgDeallocForGMP (void *ptr STG_UNUSED,
858 size_t size STG_UNUSED)
860 /* easy for us: the garbage collector does the dealloc'n */
863 /* -----------------------------------------------------------------------------
865 * -------------------------------------------------------------------------- */
867 /* -----------------------------------------------------------------------------
870 * Approximate how much we've allocated: number of blocks in the
871 * nursery + blocks allocated via allocate() - unused nusery blocks.
872 * This leaves a little slop at the end of each block, and doesn't
873 * take into account large objects (ToDo).
874 * -------------------------------------------------------------------------- */
877 calcAllocated( void )
882 allocated = allocatedBytes();
883 allocated += countNurseryBlocks() * BLOCK_SIZE_W;
888 for (i = 0; i < n_nurseries; i++) {
890 for ( bd = capabilities[i].r.rCurrentNursery->link;
891 bd != NULL; bd = bd->link ) {
892 allocated -= BLOCK_SIZE_W;
894 cap = &capabilities[i];
895 if (cap->r.rCurrentNursery->free <
896 cap->r.rCurrentNursery->start + BLOCK_SIZE_W) {
897 allocated -= (cap->r.rCurrentNursery->start + BLOCK_SIZE_W)
898 - cap->r.rCurrentNursery->free;
902 bdescr *current_nursery = MainCapability.r.rCurrentNursery;
904 for ( bd = current_nursery->link; bd != NULL; bd = bd->link ) {
905 allocated -= BLOCK_SIZE_W;
907 if (current_nursery->free < current_nursery->start + BLOCK_SIZE_W) {
908 allocated -= (current_nursery->start + BLOCK_SIZE_W)
909 - current_nursery->free;
914 total_allocated += allocated;
918 /* Approximate the amount of live data in the heap. To be called just
919 * after garbage collection (see GarbageCollect()).
928 if (RtsFlags.GcFlags.generations == 1) {
929 return g0s0->n_large_blocks + g0s0->n_blocks;
932 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
933 for (s = 0; s < generations[g].n_steps; s++) {
934 /* approximate amount of live data (doesn't take into account slop
935 * at end of each block).
937 if (g == 0 && s == 0) {
940 stp = &generations[g].steps[s];
941 live += stp->n_large_blocks + stp->n_blocks;
948 countOccupied(bdescr *bd)
953 for (; bd != NULL; bd = bd->link) {
954 words += bd->free - bd->start;
959 // Return an accurate count of the live data in the heap, excluding
968 if (RtsFlags.GcFlags.generations == 1) {
969 return countOccupied(g0s0->blocks) + countOccupied(g0s0->large_objects);
973 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
974 for (s = 0; s < generations[g].n_steps; s++) {
975 if (g == 0 && s == 0) continue;
976 stp = &generations[g].steps[s];
977 live += countOccupied(stp->blocks) +
978 countOccupied(stp->large_objects);
984 /* Approximate the number of blocks that will be needed at the next
985 * garbage collection.
987 * Assume: all data currently live will remain live. Steps that will
988 * be collected next time will therefore need twice as many blocks
989 * since all the data will be copied.
998 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
999 for (s = 0; s < generations[g].n_steps; s++) {
1000 if (g == 0 && s == 0) { continue; }
1001 stp = &generations[g].steps[s];
1002 if (g == 0 || // always collect gen 0
1003 (generations[g].steps[0].n_blocks +
1004 generations[g].steps[0].n_large_blocks
1005 > generations[g].max_blocks
1006 && stp->is_compacted == 0)) {
1007 needed += 2 * stp->n_blocks + stp->n_large_blocks;
1009 needed += stp->n_blocks + stp->n_large_blocks;
1016 /* ----------------------------------------------------------------------------
1019 Executable memory must be managed separately from non-executable
1020 memory. Most OSs these days require you to jump through hoops to
1021 dynamically allocate executable memory, due to various security
1024 Here we provide a small memory allocator for executable memory.
1025 Memory is managed with a page granularity; we allocate linearly
1026 in the page, and when the page is emptied (all objects on the page
1027 are free) we free the page again, not forgetting to make it
1030 TODO: The inability to handle objects bigger than BLOCK_SIZE_W means that
1031 the linker cannot use allocateExec for loading object code files
1032 on Windows. Once allocateExec can handle larger objects, the linker
1033 should be modified to use allocateExec instead of VirtualAlloc.
1034 ------------------------------------------------------------------------- */
1036 static bdescr *exec_block;
1038 void *allocateExec (nat bytes)
1045 // round up to words.
1046 n = (bytes + sizeof(W_) + 1) / sizeof(W_);
1048 if (n+1 > BLOCK_SIZE_W) {
1049 barf("allocateExec: can't handle large objects");
1052 if (exec_block == NULL ||
1053 exec_block->free + n + 1 > exec_block->start + BLOCK_SIZE_W) {
1055 lnat pagesize = getPageSize();
1056 bd = allocGroup(stg_max(1, pagesize / BLOCK_SIZE));
1057 debugTrace(DEBUG_gc, "allocate exec block %p", bd->start);
1059 bd->flags = BF_EXEC;
1060 bd->link = exec_block;
1061 if (exec_block != NULL) {
1062 exec_block->u.back = bd;
1065 setExecutable(bd->start, bd->blocks * BLOCK_SIZE, rtsTrue);
1068 *(exec_block->free) = n; // store the size of this chunk
1069 exec_block->gen_no += n; // gen_no stores the number of words allocated
1070 ret = exec_block->free + 1;
1071 exec_block->free += n + 1;
1077 void freeExec (void *addr)
1079 StgPtr p = (StgPtr)addr - 1;
1080 bdescr *bd = Bdescr((StgPtr)p);
1082 if ((bd->flags & BF_EXEC) == 0) {
1083 barf("freeExec: not executable");
1086 if (*(StgPtr)p == 0) {
1087 barf("freeExec: already free?");
1092 bd->gen_no -= *(StgPtr)p;
1095 if (bd->gen_no == 0) {
1096 // Free the block if it is empty, but not if it is the block at
1097 // the head of the queue.
1098 if (bd != exec_block) {
1099 debugTrace(DEBUG_gc, "free exec block %p", bd->start);
1100 dbl_link_remove(bd, &exec_block);
1101 setExecutable(bd->start, bd->blocks * BLOCK_SIZE, rtsFalse);
1104 bd->free = bd->start;
1111 /* -----------------------------------------------------------------------------
1114 memInventory() checks for memory leaks by counting up all the
1115 blocks we know about and comparing that to the number of blocks
1116 allegedly floating around in the system.
1117 -------------------------------------------------------------------------- */
1121 // Useful for finding partially full blocks in gdb
1122 void findSlop(bdescr *bd);
1123 void findSlop(bdescr *bd)
1127 for (; bd != NULL; bd = bd->link) {
1128 slop = (bd->blocks * BLOCK_SIZE_W) - (bd->free - bd->start);
1129 if (slop > (1024/sizeof(W_))) {
1130 debugBelch("block at %p (bdescr %p) has %ldKB slop\n",
1131 bd->start, bd, slop / (1024/sizeof(W_)));
1137 countBlocks(bdescr *bd)
1140 for (n=0; bd != NULL; bd=bd->link) {
1146 // (*1) Just like countBlocks, except that we adjust the count for a
1147 // megablock group so that it doesn't include the extra few blocks
1148 // that would be taken up by block descriptors in the second and
1149 // subsequent megablock. This is so we can tally the count with the
1150 // number of blocks allocated in the system, for memInventory().
1152 countAllocdBlocks(bdescr *bd)
1155 for (n=0; bd != NULL; bd=bd->link) {
1157 // hack for megablock groups: see (*1) above
1158 if (bd->blocks > BLOCKS_PER_MBLOCK) {
1159 n -= (MBLOCK_SIZE / BLOCK_SIZE - BLOCKS_PER_MBLOCK)
1160 * (bd->blocks/(MBLOCK_SIZE/BLOCK_SIZE));
1167 stepBlocks (step *stp)
1169 ASSERT(countBlocks(stp->blocks) == stp->n_blocks);
1170 ASSERT(countBlocks(stp->large_objects) == stp->n_large_blocks);
1171 return stp->n_blocks + stp->n_old_blocks +
1172 countAllocdBlocks(stp->large_objects);
1176 memInventory (rtsBool show)
1180 lnat gen_blocks[RtsFlags.GcFlags.generations];
1181 lnat nursery_blocks, retainer_blocks,
1182 arena_blocks, exec_blocks;
1183 lnat live_blocks = 0, free_blocks = 0;
1186 // count the blocks we current have
1188 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1190 for (i = 0; i < n_capabilities; i++) {
1191 gen_blocks[g] += countBlocks(capabilities[i].mut_lists[g]);
1193 gen_blocks[g] += countAllocdBlocks(generations[g].mut_list);
1194 for (s = 0; s < generations[g].n_steps; s++) {
1195 stp = &generations[g].steps[s];
1196 gen_blocks[g] += stepBlocks(stp);
1201 for (i = 0; i < n_nurseries; i++) {
1202 nursery_blocks += stepBlocks(&nurseries[i]);
1205 retainer_blocks = 0;
1207 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER) {
1208 retainer_blocks = retainerStackBlocks();
1212 // count the blocks allocated by the arena allocator
1213 arena_blocks = arenaBlocks();
1215 // count the blocks containing executable memory
1216 exec_blocks = countAllocdBlocks(exec_block);
1218 /* count the blocks on the free list */
1219 free_blocks = countFreeList();
1222 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1223 live_blocks += gen_blocks[g];
1225 live_blocks += nursery_blocks +
1226 + retainer_blocks + arena_blocks + exec_blocks;
1228 #define MB(n) (((n) * BLOCK_SIZE_W) / ((1024*1024)/sizeof(W_)))
1230 leak = live_blocks + free_blocks != mblocks_allocated * BLOCKS_PER_MBLOCK;
1234 debugBelch("Memory leak detected:\n");
1236 debugBelch("Memory inventory:\n");
1238 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1239 debugBelch(" gen %d blocks : %5lu blocks (%lu MB)\n", g,
1240 gen_blocks[g], MB(gen_blocks[g]));
1242 debugBelch(" nursery : %5lu blocks (%lu MB)\n",
1243 nursery_blocks, MB(nursery_blocks));
1244 debugBelch(" retainer : %5lu blocks (%lu MB)\n",
1245 retainer_blocks, MB(retainer_blocks));
1246 debugBelch(" arena blocks : %5lu blocks (%lu MB)\n",
1247 arena_blocks, MB(arena_blocks));
1248 debugBelch(" exec : %5lu blocks (%lu MB)\n",
1249 exec_blocks, MB(exec_blocks));
1250 debugBelch(" free : %5lu blocks (%lu MB)\n",
1251 free_blocks, MB(free_blocks));
1252 debugBelch(" total : %5lu blocks (%lu MB)\n",
1253 live_blocks + free_blocks, MB(live_blocks+free_blocks));
1255 debugBelch("\n in system : %5lu blocks (%lu MB)\n",
1256 mblocks_allocated * BLOCKS_PER_MBLOCK, mblocks_allocated);
1262 /* Full heap sanity check. */
1268 if (RtsFlags.GcFlags.generations == 1) {
1269 checkHeap(g0s0->blocks);
1270 checkChain(g0s0->large_objects);
1273 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1274 for (s = 0; s < generations[g].n_steps; s++) {
1275 if (g == 0 && s == 0) { continue; }
1276 ASSERT(countBlocks(generations[g].steps[s].blocks)
1277 == generations[g].steps[s].n_blocks);
1278 ASSERT(countBlocks(generations[g].steps[s].large_objects)
1279 == generations[g].steps[s].n_large_blocks);
1280 checkHeap(generations[g].steps[s].blocks);
1281 checkChain(generations[g].steps[s].large_objects);
1283 checkMutableList(generations[g].mut_list, g);
1288 for (s = 0; s < n_nurseries; s++) {
1289 ASSERT(countBlocks(nurseries[s].blocks)
1290 == nurseries[s].n_blocks);
1291 ASSERT(countBlocks(nurseries[s].large_objects)
1292 == nurseries[s].n_large_blocks);
1295 checkFreeListSanity();
1299 /* Nursery sanity check */
1301 checkNurserySanity( step *stp )
1307 for (bd = stp->blocks; bd != NULL; bd = bd->link) {
1308 ASSERT(bd->u.back == prev);
1310 blocks += bd->blocks;
1312 ASSERT(blocks == stp->n_blocks);
1315 // handy function for use in gdb, because Bdescr() is inlined.
1316 extern bdescr *_bdescr( StgPtr p );