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)
37 * All these globals require sm_mutex to access in THREADED_RTS mode.
39 StgClosure *caf_list = NULL;
40 StgClosure *revertible_caf_list = NULL;
43 bdescr *small_alloc_list; /* allocate()d small objects */
44 bdescr *pinned_object_block; /* allocate pinned objects into this block */
45 nat alloc_blocks; /* number of allocate()d blocks since GC */
46 nat alloc_blocks_lim; /* approximate limit on alloc_blocks */
48 StgPtr alloc_Hp = NULL; /* next free byte in small_alloc_list */
49 StgPtr alloc_HpLim = NULL; /* end of block at small_alloc_list */
51 generation *generations = NULL; /* all the generations */
52 generation *g0 = NULL; /* generation 0, for convenience */
53 generation *oldest_gen = NULL; /* oldest generation, for convenience */
54 step *g0s0 = NULL; /* generation 0, step 0, for convenience */
56 ullong total_allocated = 0; /* total memory allocated during run */
58 nat n_nurseries = 0; /* == RtsFlags.ParFlags.nNodes, convenience */
59 step *nurseries = NULL; /* array of nurseries, >1 only if THREADED_RTS */
63 * Storage manager mutex: protects all the above state from
64 * simultaneous access by two STG threads.
68 * This mutex is used by atomicModifyMutVar# only
70 Mutex atomic_modify_mutvar_mutex;
77 static void *stgAllocForGMP (size_t size_in_bytes);
78 static void *stgReallocForGMP (void *ptr, size_t old_size, size_t new_size);
79 static void stgDeallocForGMP (void *ptr, size_t size);
82 initStep (step *stp, int g, int s)
87 stp->old_blocks = NULL;
88 stp->n_old_blocks = 0;
89 stp->gen = &generations[g];
95 stp->scavd_hpLim = NULL;
98 stp->large_objects = NULL;
99 stp->n_large_blocks = 0;
100 stp->new_large_objects = NULL;
101 stp->scavenged_large_objects = NULL;
102 stp->n_scavenged_large_blocks = 0;
103 stp->is_compacted = 0;
113 if (generations != NULL) {
114 // multi-init protection
118 /* Sanity check to make sure the LOOKS_LIKE_ macros appear to be
119 * doing something reasonable.
121 ASSERT(LOOKS_LIKE_INFO_PTR(&stg_BLACKHOLE_info));
122 ASSERT(LOOKS_LIKE_CLOSURE_PTR(&stg_dummy_ret_closure));
123 ASSERT(!HEAP_ALLOCED(&stg_dummy_ret_closure));
125 if (RtsFlags.GcFlags.maxHeapSize != 0 &&
126 RtsFlags.GcFlags.heapSizeSuggestion >
127 RtsFlags.GcFlags.maxHeapSize) {
128 RtsFlags.GcFlags.maxHeapSize = RtsFlags.GcFlags.heapSizeSuggestion;
131 if (RtsFlags.GcFlags.maxHeapSize != 0 &&
132 RtsFlags.GcFlags.minAllocAreaSize >
133 RtsFlags.GcFlags.maxHeapSize) {
134 errorBelch("maximum heap size (-M) is smaller than minimum alloc area size (-A)");
135 RtsFlags.GcFlags.minAllocAreaSize = RtsFlags.GcFlags.maxHeapSize;
138 initBlockAllocator();
140 #if defined(THREADED_RTS)
141 initMutex(&sm_mutex);
142 initMutex(&atomic_modify_mutvar_mutex);
147 /* allocate generation info array */
148 generations = (generation *)stgMallocBytes(RtsFlags.GcFlags.generations
149 * sizeof(struct generation_),
150 "initStorage: gens");
152 /* Initialise all generations */
153 for(g = 0; g < RtsFlags.GcFlags.generations; g++) {
154 gen = &generations[g];
156 gen->mut_list = allocBlock();
157 gen->collections = 0;
158 gen->failed_promotions = 0;
162 /* A couple of convenience pointers */
163 g0 = &generations[0];
164 oldest_gen = &generations[RtsFlags.GcFlags.generations-1];
166 /* Allocate step structures in each generation */
167 if (RtsFlags.GcFlags.generations > 1) {
168 /* Only for multiple-generations */
170 /* Oldest generation: one step */
171 oldest_gen->n_steps = 1;
173 stgMallocBytes(1 * sizeof(struct step_), "initStorage: last step");
175 /* set up all except the oldest generation with 2 steps */
176 for(g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
177 generations[g].n_steps = RtsFlags.GcFlags.steps;
178 generations[g].steps =
179 stgMallocBytes (RtsFlags.GcFlags.steps * sizeof(struct step_),
180 "initStorage: steps");
184 /* single generation, i.e. a two-space collector */
186 g0->steps = stgMallocBytes (sizeof(struct step_), "initStorage: steps");
190 n_nurseries = n_capabilities;
191 nurseries = stgMallocBytes (n_nurseries * sizeof(struct step_),
192 "initStorage: nurseries");
195 nurseries = g0->steps; // just share nurseries[0] with g0s0
198 /* Initialise all steps */
199 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
200 for (s = 0; s < generations[g].n_steps; s++) {
201 initStep(&generations[g].steps[s], g, s);
206 for (s = 0; s < n_nurseries; s++) {
207 initStep(&nurseries[s], 0, s);
211 /* Set up the destination pointers in each younger gen. step */
212 for (g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
213 for (s = 0; s < generations[g].n_steps-1; s++) {
214 generations[g].steps[s].to = &generations[g].steps[s+1];
216 generations[g].steps[s].to = &generations[g+1].steps[0];
218 oldest_gen->steps[0].to = &oldest_gen->steps[0];
221 for (s = 0; s < n_nurseries; s++) {
222 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;
236 if (RtsFlags.GcFlags.generations == 1) {
237 errorBelch("-G1 is incompatible with -threaded");
238 stg_exit(EXIT_FAILURE);
242 /* generation 0 is special: that's the nursery */
243 generations[0].max_blocks = 0;
245 /* G0S0: the allocation area. Policy: keep the allocation area
246 * small to begin with, even if we have a large suggested heap
247 * size. Reason: we're going to do a major collection first, and we
248 * don't want it to be a big one. This vague idea is borne out by
249 * rigorous experimental evidence.
251 g0s0 = &generations[0].steps[0];
255 weak_ptr_list = NULL;
257 revertible_caf_list = NULL;
259 /* initialise the allocate() interface */
260 small_alloc_list = NULL;
262 alloc_blocks_lim = RtsFlags.GcFlags.minAllocAreaSize;
264 /* Tell GNU multi-precision pkg about our custom alloc functions */
265 mp_set_memory_functions(stgAllocForGMP, stgReallocForGMP, stgDeallocForGMP);
267 IF_DEBUG(gc, statDescribeGens());
275 stat_exit(calcAllocated());
283 for(g = 0; g < RtsFlags.GcFlags.generations; g++)
284 stgFree(generations[g].steps);
285 stgFree(generations);
287 #if defined(THREADED_RTS)
288 closeMutex(&sm_mutex);
289 closeMutex(&atomic_modify_mutvar_mutex);
293 /* -----------------------------------------------------------------------------
296 The entry code for every CAF does the following:
298 - builds a CAF_BLACKHOLE in the heap
299 - pushes an update frame pointing to the CAF_BLACKHOLE
300 - invokes UPD_CAF(), which:
301 - calls newCaf, below
302 - updates the CAF with a static indirection to the CAF_BLACKHOLE
304 Why do we build a BLACKHOLE in the heap rather than just updating
305 the thunk directly? It's so that we only need one kind of update
306 frame - otherwise we'd need a static version of the update frame too.
308 newCaf() does the following:
310 - it puts the CAF on the oldest generation's mut-once list.
311 This is so that we can treat the CAF as a root when collecting
314 For GHCI, we have additional requirements when dealing with CAFs:
316 - we must *retain* all dynamically-loaded CAFs ever entered,
317 just in case we need them again.
318 - we must be able to *revert* CAFs that have been evaluated, to
319 their pre-evaluated form.
321 To do this, we use an additional CAF list. When newCaf() is
322 called on a dynamically-loaded CAF, we add it to the CAF list
323 instead of the old-generation mutable list, and save away its
324 old info pointer (in caf->saved_info) for later reversion.
326 To revert all the CAFs, we traverse the CAF list and reset the
327 info pointer to caf->saved_info, then throw away the CAF list.
328 (see GC.c:revertCAFs()).
332 -------------------------------------------------------------------------- */
335 newCAF(StgClosure* caf)
342 // If we are in GHCi _and_ we are using dynamic libraries,
343 // then we can't redirect newCAF calls to newDynCAF (see below),
344 // so we make newCAF behave almost like newDynCAF.
345 // The dynamic libraries might be used by both the interpreted
346 // program and GHCi itself, so they must not be reverted.
347 // This also means that in GHCi with dynamic libraries, CAFs are not
348 // garbage collected. If this turns out to be a problem, we could
349 // do another hack here and do an address range test on caf to figure
350 // out whether it is from a dynamic library.
351 ((StgIndStatic *)caf)->saved_info = (StgInfoTable *)caf->header.info;
352 ((StgIndStatic *)caf)->static_link = caf_list;
357 /* Put this CAF on the mutable list for the old generation.
358 * This is a HACK - the IND_STATIC closure doesn't really have
359 * a mut_link field, but we pretend it has - in fact we re-use
360 * the STATIC_LINK field for the time being, because when we
361 * come to do a major GC we won't need the mut_link field
362 * any more and can use it as a STATIC_LINK.
364 ((StgIndStatic *)caf)->saved_info = NULL;
365 recordMutableGen(caf, oldest_gen);
371 // An alternate version of newCaf which is used for dynamically loaded
372 // object code in GHCi. In this case we want to retain *all* CAFs in
373 // the object code, because they might be demanded at any time from an
374 // expression evaluated on the command line.
375 // Also, GHCi might want to revert CAFs, so we add these to the
376 // revertible_caf_list.
378 // The linker hackily arranges that references to newCaf from dynamic
379 // code end up pointing to newDynCAF.
381 newDynCAF(StgClosure *caf)
385 ((StgIndStatic *)caf)->saved_info = (StgInfoTable *)caf->header.info;
386 ((StgIndStatic *)caf)->static_link = revertible_caf_list;
387 revertible_caf_list = caf;
392 /* -----------------------------------------------------------------------------
394 -------------------------------------------------------------------------- */
397 allocNursery (step *stp, bdescr *tail, nat blocks)
402 // Allocate a nursery: we allocate fresh blocks one at a time and
403 // cons them on to the front of the list, not forgetting to update
404 // the back pointer on the tail of the list to point to the new block.
405 for (i=0; i < blocks; i++) {
408 processNursery() in LdvProfile.c assumes that every block group in
409 the nursery contains only a single block. So, if a block group is
410 given multiple blocks, change processNursery() accordingly.
414 // double-link the nursery: we might need to insert blocks
421 bd->free = bd->start;
429 assignNurseriesToCapabilities (void)
434 for (i = 0; i < n_nurseries; i++) {
435 capabilities[i].r.rNursery = &nurseries[i];
436 capabilities[i].r.rCurrentNursery = nurseries[i].blocks;
437 capabilities[i].r.rCurrentAlloc = NULL;
439 #else /* THREADED_RTS */
440 MainCapability.r.rNursery = &nurseries[0];
441 MainCapability.r.rCurrentNursery = nurseries[0].blocks;
442 MainCapability.r.rCurrentAlloc = NULL;
447 allocNurseries( void )
451 for (i = 0; i < n_nurseries; i++) {
452 nurseries[i].blocks =
453 allocNursery(&nurseries[i], NULL,
454 RtsFlags.GcFlags.minAllocAreaSize);
455 nurseries[i].n_blocks = RtsFlags.GcFlags.minAllocAreaSize;
456 nurseries[i].old_blocks = NULL;
457 nurseries[i].n_old_blocks = 0;
459 assignNurseriesToCapabilities();
463 resetNurseries( void )
469 for (i = 0; i < n_nurseries; i++) {
471 for (bd = stp->blocks; bd; bd = bd->link) {
472 bd->free = bd->start;
473 ASSERT(bd->gen_no == 0);
474 ASSERT(bd->step == stp);
475 IF_DEBUG(sanity,memset(bd->start, 0xaa, BLOCK_SIZE));
478 assignNurseriesToCapabilities();
482 countNurseryBlocks (void)
487 for (i = 0; i < n_nurseries; i++) {
488 blocks += nurseries[i].n_blocks;
494 resizeNursery ( step *stp, nat blocks )
499 nursery_blocks = stp->n_blocks;
500 if (nursery_blocks == blocks) return;
502 if (nursery_blocks < blocks) {
503 debugTrace(DEBUG_gc, "increasing size of nursery to %d blocks",
505 stp->blocks = allocNursery(stp, stp->blocks, blocks-nursery_blocks);
510 debugTrace(DEBUG_gc, "decreasing size of nursery to %d blocks",
514 while (nursery_blocks > blocks) {
516 next_bd->u.back = NULL;
517 nursery_blocks -= bd->blocks; // might be a large block
522 // might have gone just under, by freeing a large block, so make
523 // up the difference.
524 if (nursery_blocks < blocks) {
525 stp->blocks = allocNursery(stp, stp->blocks, blocks-nursery_blocks);
529 stp->n_blocks = blocks;
530 ASSERT(countBlocks(stp->blocks) == stp->n_blocks);
534 // Resize each of the nurseries to the specified size.
537 resizeNurseriesFixed (nat blocks)
540 for (i = 0; i < n_nurseries; i++) {
541 resizeNursery(&nurseries[i], blocks);
546 // Resize the nurseries to the total specified size.
549 resizeNurseries (nat blocks)
551 // If there are multiple nurseries, then we just divide the number
552 // of available blocks between them.
553 resizeNurseriesFixed(blocks / n_nurseries);
556 /* -----------------------------------------------------------------------------
557 The allocate() interface
559 allocate(n) always succeeds, and returns a chunk of memory n words
560 long. n can be larger than the size of a block if necessary, in
561 which case a contiguous block group will be allocated.
562 -------------------------------------------------------------------------- */
572 TICK_ALLOC_HEAP_NOCTR(n);
575 /* big allocation (>LARGE_OBJECT_THRESHOLD) */
576 /* ToDo: allocate directly into generation 1 */
577 if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
578 nat req_blocks = (lnat)BLOCK_ROUND_UP(n*sizeof(W_)) / BLOCK_SIZE;
579 bd = allocGroup(req_blocks);
580 dbl_link_onto(bd, &g0s0->large_objects);
581 g0s0->n_large_blocks += req_blocks;
584 bd->flags = BF_LARGE;
585 bd->free = bd->start + n;
586 alloc_blocks += req_blocks;
590 /* small allocation (<LARGE_OBJECT_THRESHOLD) */
591 } else if (small_alloc_list == NULL || alloc_Hp + n > alloc_HpLim) {
592 if (small_alloc_list) {
593 small_alloc_list->free = alloc_Hp;
596 bd->link = small_alloc_list;
597 small_alloc_list = bd;
601 alloc_Hp = bd->start;
602 alloc_HpLim = bd->start + BLOCK_SIZE_W;
613 allocatedBytes( void )
617 allocated = alloc_blocks * BLOCK_SIZE_W - (alloc_HpLim - alloc_Hp);
618 if (pinned_object_block != NULL) {
619 allocated -= (pinned_object_block->start + BLOCK_SIZE_W) -
620 pinned_object_block->free;
627 tidyAllocateLists (void)
629 if (small_alloc_list != NULL) {
630 ASSERT(alloc_Hp >= small_alloc_list->start &&
631 alloc_Hp <= small_alloc_list->start + BLOCK_SIZE);
632 small_alloc_list->free = alloc_Hp;
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 TICK_ALLOC_HEAP_NOCTR(n);
658 /* big allocation (>LARGE_OBJECT_THRESHOLD) */
659 /* ToDo: allocate directly into generation 1 */
660 if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
661 nat req_blocks = (lnat)BLOCK_ROUND_UP(n*sizeof(W_)) / BLOCK_SIZE;
663 bd = allocGroup(req_blocks);
664 dbl_link_onto(bd, &g0s0->large_objects);
665 g0s0->n_large_blocks += req_blocks;
668 bd->flags = BF_LARGE;
669 bd->free = bd->start + n;
670 alloc_blocks += req_blocks;
674 /* small allocation (<LARGE_OBJECT_THRESHOLD) */
677 bd = cap->r.rCurrentAlloc;
678 if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
680 // The CurrentAlloc block is full, we need to find another
681 // one. First, we try taking the next block from the
683 bd = cap->r.rCurrentNursery->link;
685 if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
686 // The nursery is empty, or the next block is already
687 // full: allocate a fresh block (we can't fail here).
690 cap->r.rNursery->n_blocks++;
693 bd->step = cap->r.rNursery;
696 // we have a block in the nursery: take it and put
697 // it at the *front* of the nursery list, and use it
698 // to allocate() from.
699 cap->r.rCurrentNursery->link = bd->link;
700 if (bd->link != NULL) {
701 bd->link->u.back = cap->r.rCurrentNursery;
704 dbl_link_onto(bd, &cap->r.rNursery->blocks);
705 cap->r.rCurrentAlloc = bd;
706 IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
714 /* ---------------------------------------------------------------------------
715 Allocate a fixed/pinned object.
717 We allocate small pinned objects into a single block, allocating a
718 new block when the current one overflows. The block is chained
719 onto the large_object_list of generation 0 step 0.
721 NOTE: The GC can't in general handle pinned objects. This
722 interface is only safe to use for ByteArrays, which have no
723 pointers and don't require scavenging. It works because the
724 block's descriptor has the BF_LARGE flag set, so the block is
725 treated as a large object and chained onto various lists, rather
726 than the individual objects being copied. However, when it comes
727 to scavenge the block, the GC will only scavenge the first object.
728 The reason is that the GC can't linearly scan a block of pinned
729 objects at the moment (doing so would require using the
730 mostly-copying techniques). But since we're restricting ourselves
731 to pinned ByteArrays, not scavenging is ok.
733 This function is called by newPinnedByteArray# which immediately
734 fills the allocated memory with a MutableByteArray#.
735 ------------------------------------------------------------------------- */
738 allocatePinned( nat n )
741 bdescr *bd = pinned_object_block;
743 // If the request is for a large object, then allocate()
744 // will give us a pinned object anyway.
745 if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
751 TICK_ALLOC_HEAP_NOCTR(n);
754 // we always return 8-byte aligned memory. bd->free must be
755 // 8-byte aligned to begin with, so we just round up n to
756 // the nearest multiple of 8 bytes.
757 if (sizeof(StgWord) == 4) {
761 // If we don't have a block of pinned objects yet, or the current
762 // one isn't large enough to hold the new object, allocate a new one.
763 if (bd == NULL || (bd->free + n) > (bd->start + BLOCK_SIZE_W)) {
764 pinned_object_block = bd = allocBlock();
765 dbl_link_onto(bd, &g0s0->large_objects);
768 bd->flags = BF_PINNED | BF_LARGE;
769 bd->free = bd->start;
779 /* -----------------------------------------------------------------------------
780 This is the write barrier for MUT_VARs, a.k.a. IORefs. A
781 MUT_VAR_CLEAN object is not on the mutable list; a MUT_VAR_DIRTY
782 is. When written to, a MUT_VAR_CLEAN turns into a MUT_VAR_DIRTY
783 and is put on the mutable list.
784 -------------------------------------------------------------------------- */
787 dirty_MUT_VAR(StgRegTable *reg, StgClosure *p)
789 Capability *cap = regTableToCapability(reg);
791 if (p->header.info == &stg_MUT_VAR_CLEAN_info) {
792 p->header.info = &stg_MUT_VAR_DIRTY_info;
793 bd = Bdescr((StgPtr)p);
794 if (bd->gen_no > 0) recordMutableCap(p,cap,bd->gen_no);
798 /* -----------------------------------------------------------------------------
799 Allocation functions for GMP.
801 These all use the allocate() interface - we can't have any garbage
802 collection going on during a gmp operation, so we use allocate()
803 which always succeeds. The gmp operations which might need to
804 allocate will ask the storage manager (via doYouWantToGC()) whether
805 a garbage collection is required, in case we get into a loop doing
806 only allocate() style allocation.
807 -------------------------------------------------------------------------- */
810 stgAllocForGMP (size_t size_in_bytes)
813 nat data_size_in_words, total_size_in_words;
815 /* round up to a whole number of words */
816 data_size_in_words = (size_in_bytes + sizeof(W_) + 1) / sizeof(W_);
817 total_size_in_words = sizeofW(StgArrWords) + data_size_in_words;
819 /* allocate and fill it in. */
820 #if defined(THREADED_RTS)
821 arr = (StgArrWords *)allocateLocal(myTask()->cap, total_size_in_words);
823 arr = (StgArrWords *)allocateLocal(&MainCapability, total_size_in_words);
825 SET_ARR_HDR(arr, &stg_ARR_WORDS_info, CCCS, data_size_in_words);
827 /* and return a ptr to the goods inside the array */
832 stgReallocForGMP (void *ptr, size_t old_size, size_t new_size)
834 void *new_stuff_ptr = stgAllocForGMP(new_size);
836 char *p = (char *) ptr;
837 char *q = (char *) new_stuff_ptr;
839 for (; i < old_size; i++, p++, q++) {
843 return(new_stuff_ptr);
847 stgDeallocForGMP (void *ptr STG_UNUSED,
848 size_t size STG_UNUSED)
850 /* easy for us: the garbage collector does the dealloc'n */
853 /* -----------------------------------------------------------------------------
855 * -------------------------------------------------------------------------- */
857 /* -----------------------------------------------------------------------------
860 * Approximate how much we've allocated: number of blocks in the
861 * nursery + blocks allocated via allocate() - unused nusery blocks.
862 * This leaves a little slop at the end of each block, and doesn't
863 * take into account large objects (ToDo).
864 * -------------------------------------------------------------------------- */
867 calcAllocated( void )
872 allocated = allocatedBytes();
873 allocated += countNurseryBlocks() * BLOCK_SIZE_W;
878 for (i = 0; i < n_nurseries; i++) {
880 for ( bd = capabilities[i].r.rCurrentNursery->link;
881 bd != NULL; bd = bd->link ) {
882 allocated -= BLOCK_SIZE_W;
884 cap = &capabilities[i];
885 if (cap->r.rCurrentNursery->free <
886 cap->r.rCurrentNursery->start + BLOCK_SIZE_W) {
887 allocated -= (cap->r.rCurrentNursery->start + BLOCK_SIZE_W)
888 - cap->r.rCurrentNursery->free;
892 bdescr *current_nursery = MainCapability.r.rCurrentNursery;
894 for ( bd = current_nursery->link; bd != NULL; bd = bd->link ) {
895 allocated -= BLOCK_SIZE_W;
897 if (current_nursery->free < current_nursery->start + BLOCK_SIZE_W) {
898 allocated -= (current_nursery->start + BLOCK_SIZE_W)
899 - current_nursery->free;
904 total_allocated += allocated;
908 /* Approximate the amount of live data in the heap. To be called just
909 * after garbage collection (see GarbageCollect()).
918 if (RtsFlags.GcFlags.generations == 1) {
919 return (g0s0->n_large_blocks + g0s0->n_blocks) * BLOCK_SIZE_W;
922 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
923 for (s = 0; s < generations[g].n_steps; s++) {
924 /* approximate amount of live data (doesn't take into account slop
925 * at end of each block).
927 if (g == 0 && s == 0) {
930 stp = &generations[g].steps[s];
931 live += (stp->n_large_blocks + stp->n_blocks) * BLOCK_SIZE_W;
937 /* Approximate the number of blocks that will be needed at the next
938 * garbage collection.
940 * Assume: all data currently live will remain live. Steps that will
941 * be collected next time will therefore need twice as many blocks
942 * since all the data will be copied.
951 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
952 for (s = 0; s < generations[g].n_steps; s++) {
953 if (g == 0 && s == 0) { continue; }
954 stp = &generations[g].steps[s];
955 if (generations[g].steps[0].n_blocks +
956 generations[g].steps[0].n_large_blocks
957 > generations[g].max_blocks
958 && stp->is_compacted == 0) {
959 needed += 2 * stp->n_blocks;
961 needed += stp->n_blocks;
968 /* ----------------------------------------------------------------------------
971 Executable memory must be managed separately from non-executable
972 memory. Most OSs these days require you to jump through hoops to
973 dynamically allocate executable memory, due to various security
976 Here we provide a small memory allocator for executable memory.
977 Memory is managed with a page granularity; we allocate linearly
978 in the page, and when the page is emptied (all objects on the page
979 are free) we free the page again, not forgetting to make it
981 ------------------------------------------------------------------------- */
983 static bdescr *exec_block;
985 void *allocateExec (nat bytes)
992 // round up to words.
993 n = (bytes + sizeof(W_) + 1) / sizeof(W_);
995 if (n+1 > BLOCK_SIZE_W) {
996 barf("allocateExec: can't handle large objects");
999 if (exec_block == NULL ||
1000 exec_block->free + n + 1 > exec_block->start + BLOCK_SIZE_W) {
1002 lnat pagesize = getPageSize();
1003 bd = allocGroup(stg_max(1, pagesize / BLOCK_SIZE));
1004 debugTrace(DEBUG_gc, "allocate exec block %p", bd->start);
1006 bd->flags = BF_EXEC;
1007 bd->link = exec_block;
1008 if (exec_block != NULL) {
1009 exec_block->u.back = bd;
1012 setExecutable(bd->start, bd->blocks * BLOCK_SIZE, rtsTrue);
1015 *(exec_block->free) = n; // store the size of this chunk
1016 exec_block->gen_no += n; // gen_no stores the number of words allocated
1017 ret = exec_block->free + 1;
1018 exec_block->free += n + 1;
1024 void freeExec (void *addr)
1026 StgPtr p = (StgPtr)addr - 1;
1027 bdescr *bd = Bdescr((StgPtr)p);
1029 if ((bd->flags & BF_EXEC) == 0) {
1030 barf("freeExec: not executable");
1033 if (*(StgPtr)p == 0) {
1034 barf("freeExec: already free?");
1039 bd->gen_no -= *(StgPtr)p;
1042 // Free the block if it is empty, but not if it is the block at
1043 // the head of the queue.
1044 if (bd->gen_no == 0 && bd != exec_block) {
1045 debugTrace(DEBUG_gc, "free exec block %p", bd->start);
1047 bd->u.back->link = bd->link;
1049 exec_block = bd->link;
1052 bd->link->u.back = bd->u.back;
1054 setExecutable(bd->start, bd->blocks * BLOCK_SIZE, rtsFalse);
1061 /* -----------------------------------------------------------------------------
1064 memInventory() checks for memory leaks by counting up all the
1065 blocks we know about and comparing that to the number of blocks
1066 allegedly floating around in the system.
1067 -------------------------------------------------------------------------- */
1072 stepBlocks (step *stp)
1077 total_blocks = stp->n_blocks;
1078 total_blocks += stp->n_old_blocks;
1079 for (bd = stp->large_objects; bd; bd = bd->link) {
1080 total_blocks += bd->blocks;
1081 /* hack for megablock groups: they have an extra block or two in
1082 the second and subsequent megablocks where the block
1083 descriptors would normally go.
1085 if (bd->blocks > BLOCKS_PER_MBLOCK) {
1086 total_blocks -= (MBLOCK_SIZE / BLOCK_SIZE - BLOCKS_PER_MBLOCK)
1087 * (bd->blocks/(MBLOCK_SIZE/BLOCK_SIZE));
1090 return total_blocks;
1099 lnat gen_blocks[RtsFlags.GcFlags.generations];
1100 lnat nursery_blocks, allocate_blocks, retainer_blocks,
1101 arena_blocks, exec_blocks;
1102 lnat live_blocks = 0, free_blocks = 0;
1104 // count the blocks we current have
1106 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1108 for (i = 0; i < n_capabilities; i++) {
1109 for (bd = capabilities[i].mut_lists[g]; bd != NULL; bd = bd->link) {
1110 gen_blocks[g] += bd->blocks;
1113 for (bd = generations[g].mut_list; bd != NULL; bd = bd->link) {
1114 gen_blocks[g] += bd->blocks;
1116 for (s = 0; s < generations[g].n_steps; s++) {
1117 if (g==0 && s==0) continue;
1118 stp = &generations[g].steps[s];
1119 gen_blocks[g] += stepBlocks(stp);
1124 for (i = 0; i < n_nurseries; i++) {
1125 nursery_blocks += stepBlocks(&nurseries[i]);
1128 // We put pinned object blocks in g0s0, so better count blocks there too.
1129 gen_blocks[0] += stepBlocks(g0s0);
1132 /* any blocks held by allocate() */
1133 allocate_blocks = 0;
1134 for (bd = small_alloc_list; bd; bd = bd->link) {
1135 allocate_blocks += bd->blocks;
1138 retainer_blocks = 0;
1140 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER) {
1141 retainer_blocks = retainerStackBlocks();
1145 // count the blocks allocated by the arena allocator
1146 arena_blocks = arenaBlocks();
1148 // count the blocks containing executable memory
1150 for (bd = exec_block; bd; bd = bd->link) {
1151 exec_blocks = bd->blocks;
1154 /* count the blocks on the free list */
1155 free_blocks = countFreeList();
1158 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1159 live_blocks += gen_blocks[g];
1161 live_blocks += nursery_blocks + allocate_blocks
1162 + retainer_blocks + arena_blocks + exec_blocks;
1164 if (live_blocks + free_blocks != mblocks_allocated * BLOCKS_PER_MBLOCK)
1166 debugBelch("Memory leak detected\n");
1167 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1168 debugBelch(" gen %d blocks : %4lu\n", g, gen_blocks[g]);
1170 debugBelch(" nursery : %4lu\n", nursery_blocks);
1171 debugBelch(" allocate() : %4lu\n", allocate_blocks);
1172 debugBelch(" retainer : %4lu\n", retainer_blocks);
1173 debugBelch(" arena blocks : %4lu\n", arena_blocks);
1174 debugBelch(" exec : %4lu\n", exec_blocks);
1175 debugBelch(" free : %4lu\n", free_blocks);
1176 debugBelch(" total : %4lu\n\n", live_blocks + free_blocks);
1177 debugBelch(" in system : %4lu\n", mblocks_allocated + BLOCKS_PER_MBLOCK);
1184 countBlocks(bdescr *bd)
1187 for (n=0; bd != NULL; bd=bd->link) {
1193 /* Full heap sanity check. */
1199 if (RtsFlags.GcFlags.generations == 1) {
1200 checkHeap(g0s0->blocks);
1201 checkChain(g0s0->large_objects);
1204 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1205 for (s = 0; s < generations[g].n_steps; s++) {
1206 if (g == 0 && s == 0) { continue; }
1207 ASSERT(countBlocks(generations[g].steps[s].blocks)
1208 == generations[g].steps[s].n_blocks);
1209 ASSERT(countBlocks(generations[g].steps[s].large_objects)
1210 == generations[g].steps[s].n_large_blocks);
1211 checkHeap(generations[g].steps[s].blocks);
1212 checkChain(generations[g].steps[s].large_objects);
1214 checkMutableList(generations[g].mut_list, g);
1219 for (s = 0; s < n_nurseries; s++) {
1220 ASSERT(countBlocks(nurseries[s].blocks)
1221 == nurseries[s].n_blocks);
1222 ASSERT(countBlocks(nurseries[s].large_objects)
1223 == nurseries[s].n_large_blocks);
1226 checkFreeListSanity();
1230 /* Nursery sanity check */
1232 checkNurserySanity( step *stp )
1238 for (bd = stp->blocks; bd != NULL; bd = bd->link) {
1239 ASSERT(bd->u.back == prev);
1241 blocks += bd->blocks;
1243 ASSERT(blocks == stp->n_blocks);
1246 // handy function for use in gdb, because Bdescr() is inlined.
1247 extern bdescr *_bdescr( StgPtr p );