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 *pinned_object_block; /* allocate pinned objects into this block */
44 nat alloc_blocks; /* number of allocate()d blocks since GC */
45 nat alloc_blocks_lim; /* approximate limit on alloc_blocks */
47 generation *generations = NULL; /* all the generations */
48 generation *g0 = NULL; /* generation 0, for convenience */
49 generation *oldest_gen = NULL; /* oldest generation, for convenience */
50 step *g0s0 = NULL; /* generation 0, step 0, for convenience */
52 ullong total_allocated = 0; /* total memory allocated during run */
54 nat n_nurseries = 0; /* == RtsFlags.ParFlags.nNodes, convenience */
55 step *nurseries = NULL; /* array of nurseries, >1 only if THREADED_RTS */
59 * Storage manager mutex: protects all the above state from
60 * simultaneous access by two STG threads.
64 * This mutex is used by atomicModifyMutVar# only
66 Mutex atomic_modify_mutvar_mutex;
73 static void *stgAllocForGMP (size_t size_in_bytes);
74 static void *stgReallocForGMP (void *ptr, size_t old_size, size_t new_size);
75 static void stgDeallocForGMP (void *ptr, size_t size);
78 initStep (step *stp, int g, int s)
83 stp->old_blocks = NULL;
84 stp->n_old_blocks = 0;
85 stp->gen = &generations[g];
91 stp->scavd_hpLim = NULL;
94 stp->large_objects = NULL;
95 stp->n_large_blocks = 0;
96 stp->new_large_objects = NULL;
97 stp->scavenged_large_objects = NULL;
98 stp->n_scavenged_large_blocks = 0;
99 stp->is_compacted = 0;
109 if (generations != NULL) {
110 // multi-init protection
116 /* Sanity check to make sure the LOOKS_LIKE_ macros appear to be
117 * doing something reasonable.
119 /* We use the NOT_NULL variant or gcc warns that the test is always true */
120 ASSERT(LOOKS_LIKE_INFO_PTR_NOT_NULL(&stg_BLACKHOLE_info));
121 ASSERT(LOOKS_LIKE_CLOSURE_PTR(&stg_dummy_ret_closure));
122 ASSERT(!HEAP_ALLOCED(&stg_dummy_ret_closure));
124 if (RtsFlags.GcFlags.maxHeapSize != 0 &&
125 RtsFlags.GcFlags.heapSizeSuggestion >
126 RtsFlags.GcFlags.maxHeapSize) {
127 RtsFlags.GcFlags.maxHeapSize = RtsFlags.GcFlags.heapSizeSuggestion;
130 if (RtsFlags.GcFlags.maxHeapSize != 0 &&
131 RtsFlags.GcFlags.minAllocAreaSize >
132 RtsFlags.GcFlags.maxHeapSize) {
133 errorBelch("maximum heap size (-M) is smaller than minimum alloc area size (-A)");
134 RtsFlags.GcFlags.minAllocAreaSize = RtsFlags.GcFlags.maxHeapSize;
137 initBlockAllocator();
139 #if defined(THREADED_RTS)
140 initMutex(&sm_mutex);
141 initMutex(&atomic_modify_mutvar_mutex);
146 /* allocate generation info array */
147 generations = (generation *)stgMallocBytes(RtsFlags.GcFlags.generations
148 * sizeof(struct generation_),
149 "initStorage: gens");
151 /* Initialise all generations */
152 for(g = 0; g < RtsFlags.GcFlags.generations; g++) {
153 gen = &generations[g];
155 gen->mut_list = allocBlock();
156 gen->collections = 0;
157 gen->failed_promotions = 0;
161 /* A couple of convenience pointers */
162 g0 = &generations[0];
163 oldest_gen = &generations[RtsFlags.GcFlags.generations-1];
165 /* Allocate step structures in each generation */
166 if (RtsFlags.GcFlags.generations > 1) {
167 /* Only for multiple-generations */
169 /* Oldest generation: one step */
170 oldest_gen->n_steps = 1;
172 stgMallocBytes(1 * sizeof(struct step_), "initStorage: last step");
174 /* set up all except the oldest generation with 2 steps */
175 for(g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
176 generations[g].n_steps = RtsFlags.GcFlags.steps;
177 generations[g].steps =
178 stgMallocBytes (RtsFlags.GcFlags.steps * sizeof(struct step_),
179 "initStorage: steps");
183 /* single generation, i.e. a two-space collector */
185 g0->steps = stgMallocBytes (sizeof(struct step_), "initStorage: steps");
189 n_nurseries = n_capabilities;
193 nurseries = stgMallocBytes (n_nurseries * sizeof(struct step_),
194 "initStorage: nurseries");
196 /* Initialise all steps */
197 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
198 for (s = 0; s < generations[g].n_steps; s++) {
199 initStep(&generations[g].steps[s], g, s);
203 for (s = 0; s < n_nurseries; s++) {
204 initStep(&nurseries[s], 0, s);
207 /* Set up the destination pointers in each younger gen. step */
208 for (g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
209 for (s = 0; s < generations[g].n_steps-1; s++) {
210 generations[g].steps[s].to = &generations[g].steps[s+1];
212 generations[g].steps[s].to = &generations[g+1].steps[0];
214 oldest_gen->steps[0].to = &oldest_gen->steps[0];
216 for (s = 0; s < n_nurseries; s++) {
217 nurseries[s].to = generations[0].steps[0].to;
220 /* The oldest generation has one step. */
221 if (RtsFlags.GcFlags.compact) {
222 if (RtsFlags.GcFlags.generations == 1) {
223 errorBelch("WARNING: compaction is incompatible with -G1; disabled");
225 oldest_gen->steps[0].is_compacted = 1;
229 generations[0].max_blocks = 0;
230 g0s0 = &generations[0].steps[0];
232 /* The allocation area. Policy: keep the allocation area
233 * small to begin with, even if we have a large suggested heap
234 * size. Reason: we're going to do a major collection first, and we
235 * don't want it to be a big one. This vague idea is borne out by
236 * rigorous experimental evidence.
240 weak_ptr_list = NULL;
242 revertible_caf_list = NULL;
244 /* initialise the allocate() interface */
246 alloc_blocks_lim = RtsFlags.GcFlags.minAllocAreaSize;
248 /* Tell GNU multi-precision pkg about our custom alloc functions */
249 mp_set_memory_functions(stgAllocForGMP, stgReallocForGMP, stgDeallocForGMP);
251 IF_DEBUG(gc, statDescribeGens());
259 stat_exit(calcAllocated());
267 for(g = 0; g < RtsFlags.GcFlags.generations; g++)
268 stgFree(generations[g].steps);
269 stgFree(generations);
271 #if defined(THREADED_RTS)
272 closeMutex(&sm_mutex);
273 closeMutex(&atomic_modify_mutvar_mutex);
278 /* -----------------------------------------------------------------------------
281 The entry code for every CAF does the following:
283 - builds a CAF_BLACKHOLE in the heap
284 - pushes an update frame pointing to the CAF_BLACKHOLE
285 - invokes UPD_CAF(), which:
286 - calls newCaf, below
287 - updates the CAF with a static indirection to the CAF_BLACKHOLE
289 Why do we build a BLACKHOLE in the heap rather than just updating
290 the thunk directly? It's so that we only need one kind of update
291 frame - otherwise we'd need a static version of the update frame too.
293 newCaf() does the following:
295 - it puts the CAF on the oldest generation's mut-once list.
296 This is so that we can treat the CAF as a root when collecting
299 For GHCI, we have additional requirements when dealing with CAFs:
301 - we must *retain* all dynamically-loaded CAFs ever entered,
302 just in case we need them again.
303 - we must be able to *revert* CAFs that have been evaluated, to
304 their pre-evaluated form.
306 To do this, we use an additional CAF list. When newCaf() is
307 called on a dynamically-loaded CAF, we add it to the CAF list
308 instead of the old-generation mutable list, and save away its
309 old info pointer (in caf->saved_info) for later reversion.
311 To revert all the CAFs, we traverse the CAF list and reset the
312 info pointer to caf->saved_info, then throw away the CAF list.
313 (see GC.c:revertCAFs()).
317 -------------------------------------------------------------------------- */
320 newCAF(StgClosure* caf)
327 // If we are in GHCi _and_ we are using dynamic libraries,
328 // then we can't redirect newCAF calls to newDynCAF (see below),
329 // so we make newCAF behave almost like newDynCAF.
330 // The dynamic libraries might be used by both the interpreted
331 // program and GHCi itself, so they must not be reverted.
332 // This also means that in GHCi with dynamic libraries, CAFs are not
333 // garbage collected. If this turns out to be a problem, we could
334 // do another hack here and do an address range test on caf to figure
335 // out whether it is from a dynamic library.
336 ((StgIndStatic *)caf)->saved_info = (StgInfoTable *)caf->header.info;
337 ((StgIndStatic *)caf)->static_link = caf_list;
342 /* Put this CAF on the mutable list for the old generation.
343 * This is a HACK - the IND_STATIC closure doesn't really have
344 * a mut_link field, but we pretend it has - in fact we re-use
345 * the STATIC_LINK field for the time being, because when we
346 * come to do a major GC we won't need the mut_link field
347 * any more and can use it as a STATIC_LINK.
349 ((StgIndStatic *)caf)->saved_info = NULL;
350 recordMutableGen(caf, oldest_gen);
356 // An alternate version of newCaf which is used for dynamically loaded
357 // object code in GHCi. In this case we want to retain *all* CAFs in
358 // the object code, because they might be demanded at any time from an
359 // expression evaluated on the command line.
360 // Also, GHCi might want to revert CAFs, so we add these to the
361 // revertible_caf_list.
363 // The linker hackily arranges that references to newCaf from dynamic
364 // code end up pointing to newDynCAF.
366 newDynCAF(StgClosure *caf)
370 ((StgIndStatic *)caf)->saved_info = (StgInfoTable *)caf->header.info;
371 ((StgIndStatic *)caf)->static_link = revertible_caf_list;
372 revertible_caf_list = caf;
377 /* -----------------------------------------------------------------------------
379 -------------------------------------------------------------------------- */
382 allocNursery (step *stp, bdescr *tail, nat blocks)
387 // Allocate a nursery: we allocate fresh blocks one at a time and
388 // cons them on to the front of the list, not forgetting to update
389 // the back pointer on the tail of the list to point to the new block.
390 for (i=0; i < blocks; i++) {
393 processNursery() in LdvProfile.c assumes that every block group in
394 the nursery contains only a single block. So, if a block group is
395 given multiple blocks, change processNursery() accordingly.
399 // double-link the nursery: we might need to insert blocks
406 bd->free = bd->start;
414 assignNurseriesToCapabilities (void)
419 for (i = 0; i < n_nurseries; i++) {
420 capabilities[i].r.rNursery = &nurseries[i];
421 capabilities[i].r.rCurrentNursery = nurseries[i].blocks;
422 capabilities[i].r.rCurrentAlloc = NULL;
424 #else /* THREADED_RTS */
425 MainCapability.r.rNursery = &nurseries[0];
426 MainCapability.r.rCurrentNursery = nurseries[0].blocks;
427 MainCapability.r.rCurrentAlloc = NULL;
432 allocNurseries( void )
436 for (i = 0; i < n_nurseries; i++) {
437 nurseries[i].blocks =
438 allocNursery(&nurseries[i], NULL,
439 RtsFlags.GcFlags.minAllocAreaSize);
440 nurseries[i].n_blocks = RtsFlags.GcFlags.minAllocAreaSize;
441 nurseries[i].old_blocks = NULL;
442 nurseries[i].n_old_blocks = 0;
444 assignNurseriesToCapabilities();
448 resetNurseries( void )
454 for (i = 0; i < n_nurseries; i++) {
456 for (bd = stp->blocks; bd; bd = bd->link) {
457 bd->free = bd->start;
458 ASSERT(bd->gen_no == 0);
459 ASSERT(bd->step == stp);
460 IF_DEBUG(sanity,memset(bd->start, 0xaa, BLOCK_SIZE));
463 assignNurseriesToCapabilities();
467 countNurseryBlocks (void)
472 for (i = 0; i < n_nurseries; i++) {
473 blocks += nurseries[i].n_blocks;
479 resizeNursery ( step *stp, nat blocks )
484 nursery_blocks = stp->n_blocks;
485 if (nursery_blocks == blocks) return;
487 if (nursery_blocks < blocks) {
488 debugTrace(DEBUG_gc, "increasing size of nursery to %d blocks",
490 stp->blocks = allocNursery(stp, stp->blocks, blocks-nursery_blocks);
495 debugTrace(DEBUG_gc, "decreasing size of nursery to %d blocks",
499 while (nursery_blocks > blocks) {
501 next_bd->u.back = NULL;
502 nursery_blocks -= bd->blocks; // might be a large block
507 // might have gone just under, by freeing a large block, so make
508 // up the difference.
509 if (nursery_blocks < blocks) {
510 stp->blocks = allocNursery(stp, stp->blocks, blocks-nursery_blocks);
514 stp->n_blocks = blocks;
515 ASSERT(countBlocks(stp->blocks) == stp->n_blocks);
519 // Resize each of the nurseries to the specified size.
522 resizeNurseriesFixed (nat blocks)
525 for (i = 0; i < n_nurseries; i++) {
526 resizeNursery(&nurseries[i], blocks);
531 // Resize the nurseries to the total specified size.
534 resizeNurseries (nat blocks)
536 // If there are multiple nurseries, then we just divide the number
537 // of available blocks between them.
538 resizeNurseriesFixed(blocks / n_nurseries);
541 /* -----------------------------------------------------------------------------
542 The allocate() interface
544 allocateInGen() function allocates memory directly into a specific
545 generation. It always succeeds, and returns a chunk of memory n
546 words long. n can be larger than the size of a block if necessary,
547 in which case a contiguous block group will be allocated.
549 allocate(n) is equivalent to allocateInGen(g0).
550 -------------------------------------------------------------------------- */
553 allocateInGen (generation *g, nat n)
561 TICK_ALLOC_HEAP_NOCTR(n);
566 if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_))
568 nat req_blocks = (lnat)BLOCK_ROUND_UP(n*sizeof(W_)) / BLOCK_SIZE;
570 // Attempting to allocate an object larger than maxHeapSize
571 // should definitely be disallowed. (bug #1791)
572 if (RtsFlags.GcFlags.maxHeapSize > 0 &&
573 req_blocks >= RtsFlags.GcFlags.maxHeapSize) {
577 bd = allocGroup(req_blocks);
578 dbl_link_onto(bd, &stp->large_objects);
579 stp->n_large_blocks += bd->blocks; // might be larger than req_blocks
582 bd->flags = BF_LARGE;
583 bd->free = bd->start + n;
588 // small allocation (<LARGE_OBJECT_THRESHOLD) */
590 if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
595 bd->link = stp->blocks;
612 return allocateInGen(g0,n);
616 allocatedBytes( void )
620 allocated = alloc_blocks * BLOCK_SIZE_W;
621 if (pinned_object_block != NULL) {
622 allocated -= (pinned_object_block->start + BLOCK_SIZE_W) -
623 pinned_object_block->free;
629 /* -----------------------------------------------------------------------------
632 This allocates memory in the current thread - it is intended for
633 use primarily from STG-land where we have a Capability. It is
634 better than allocate() because it doesn't require taking the
635 sm_mutex lock in the common case.
637 Memory is allocated directly from the nursery if possible (but not
638 from the current nursery block, so as not to interfere with
640 -------------------------------------------------------------------------- */
643 allocateLocal (Capability *cap, nat n)
648 if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
649 return allocateInGen(g0,n);
652 /* small allocation (<LARGE_OBJECT_THRESHOLD) */
654 TICK_ALLOC_HEAP_NOCTR(n);
657 bd = cap->r.rCurrentAlloc;
658 if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
660 // The CurrentAlloc block is full, we need to find another
661 // one. First, we try taking the next block from the
663 bd = cap->r.rCurrentNursery->link;
665 if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
666 // The nursery is empty, or the next block is already
667 // full: allocate a fresh block (we can't fail here).
670 cap->r.rNursery->n_blocks++;
673 bd->step = cap->r.rNursery;
675 // NO: alloc_blocks++;
676 // calcAllocated() uses the size of the nursery, and we've
677 // already bumpted nursery->n_blocks above.
679 // we have a block in the nursery: take it and put
680 // it at the *front* of the nursery list, and use it
681 // to allocate() from.
682 cap->r.rCurrentNursery->link = bd->link;
683 if (bd->link != NULL) {
684 bd->link->u.back = cap->r.rCurrentNursery;
687 dbl_link_onto(bd, &cap->r.rNursery->blocks);
688 cap->r.rCurrentAlloc = bd;
689 IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
696 /* ---------------------------------------------------------------------------
697 Allocate a fixed/pinned object.
699 We allocate small pinned objects into a single block, allocating a
700 new block when the current one overflows. The block is chained
701 onto the large_object_list of generation 0 step 0.
703 NOTE: The GC can't in general handle pinned objects. This
704 interface is only safe to use for ByteArrays, which have no
705 pointers and don't require scavenging. It works because the
706 block's descriptor has the BF_LARGE flag set, so the block is
707 treated as a large object and chained onto various lists, rather
708 than the individual objects being copied. However, when it comes
709 to scavenge the block, the GC will only scavenge the first object.
710 The reason is that the GC can't linearly scan a block of pinned
711 objects at the moment (doing so would require using the
712 mostly-copying techniques). But since we're restricting ourselves
713 to pinned ByteArrays, not scavenging is ok.
715 This function is called by newPinnedByteArray# which immediately
716 fills the allocated memory with a MutableByteArray#.
717 ------------------------------------------------------------------------- */
720 allocatePinned( nat n )
723 bdescr *bd = pinned_object_block;
725 // If the request is for a large object, then allocate()
726 // will give us a pinned object anyway.
727 if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
733 TICK_ALLOC_HEAP_NOCTR(n);
736 // we always return 8-byte aligned memory. bd->free must be
737 // 8-byte aligned to begin with, so we just round up n to
738 // the nearest multiple of 8 bytes.
739 if (sizeof(StgWord) == 4) {
743 // If we don't have a block of pinned objects yet, or the current
744 // one isn't large enough to hold the new object, allocate a new one.
745 if (bd == NULL || (bd->free + n) > (bd->start + BLOCK_SIZE_W)) {
746 pinned_object_block = bd = allocBlock();
747 dbl_link_onto(bd, &g0s0->large_objects);
748 g0s0->n_large_blocks++;
751 bd->flags = BF_PINNED | BF_LARGE;
752 bd->free = bd->start;
762 /* -----------------------------------------------------------------------------
764 -------------------------------------------------------------------------- */
767 This is the write barrier for MUT_VARs, a.k.a. IORefs. A
768 MUT_VAR_CLEAN object is not on the mutable list; a MUT_VAR_DIRTY
769 is. When written to, a MUT_VAR_CLEAN turns into a MUT_VAR_DIRTY
770 and is put on the mutable list.
773 dirty_MUT_VAR(StgRegTable *reg, StgClosure *p)
775 Capability *cap = regTableToCapability(reg);
777 if (p->header.info == &stg_MUT_VAR_CLEAN_info) {
778 p->header.info = &stg_MUT_VAR_DIRTY_info;
779 bd = Bdescr((StgPtr)p);
780 if (bd->gen_no > 0) recordMutableCap(p,cap,bd->gen_no);
785 This is the write barrier for MVARs. An MVAR_CLEAN objects is not
786 on the mutable list; a MVAR_DIRTY is. When written to, a
787 MVAR_CLEAN turns into a MVAR_DIRTY and is put on the mutable list.
788 The check for MVAR_CLEAN is inlined at the call site for speed,
789 this really does make a difference on concurrency-heavy benchmarks
790 such as Chaneneos and cheap-concurrency.
793 dirty_MVAR(StgRegTable *reg, StgClosure *p)
795 Capability *cap = regTableToCapability(reg);
797 bd = Bdescr((StgPtr)p);
798 if (bd->gen_no > 0) recordMutableCap(p,cap,bd->gen_no);
801 /* -----------------------------------------------------------------------------
802 Allocation functions for GMP.
804 These all use the allocate() interface - we can't have any garbage
805 collection going on during a gmp operation, so we use allocate()
806 which always succeeds. The gmp operations which might need to
807 allocate will ask the storage manager (via doYouWantToGC()) whether
808 a garbage collection is required, in case we get into a loop doing
809 only allocate() style allocation.
810 -------------------------------------------------------------------------- */
813 stgAllocForGMP (size_t size_in_bytes)
816 nat data_size_in_words, total_size_in_words;
818 /* round up to a whole number of words */
819 data_size_in_words = (size_in_bytes + sizeof(W_) + 1) / sizeof(W_);
820 total_size_in_words = sizeofW(StgArrWords) + data_size_in_words;
822 /* allocate and fill it in. */
823 #if defined(THREADED_RTS)
824 arr = (StgArrWords *)allocateLocal(myTask()->cap, total_size_in_words);
826 arr = (StgArrWords *)allocateLocal(&MainCapability, total_size_in_words);
828 SET_ARR_HDR(arr, &stg_ARR_WORDS_info, CCCS, data_size_in_words);
830 /* and return a ptr to the goods inside the array */
835 stgReallocForGMP (void *ptr, size_t old_size, size_t new_size)
837 void *new_stuff_ptr = stgAllocForGMP(new_size);
839 char *p = (char *) ptr;
840 char *q = (char *) new_stuff_ptr;
842 for (; i < old_size; i++, p++, q++) {
846 return(new_stuff_ptr);
850 stgDeallocForGMP (void *ptr STG_UNUSED,
851 size_t size STG_UNUSED)
853 /* easy for us: the garbage collector does the dealloc'n */
856 /* -----------------------------------------------------------------------------
858 * -------------------------------------------------------------------------- */
860 /* -----------------------------------------------------------------------------
863 * Approximate how much we've allocated: number of blocks in the
864 * nursery + blocks allocated via allocate() - unused nusery blocks.
865 * This leaves a little slop at the end of each block, and doesn't
866 * take into account large objects (ToDo).
867 * -------------------------------------------------------------------------- */
870 calcAllocated( void )
875 allocated = allocatedBytes();
876 allocated += countNurseryBlocks() * BLOCK_SIZE_W;
881 for (i = 0; i < n_nurseries; i++) {
883 for ( bd = capabilities[i].r.rCurrentNursery->link;
884 bd != NULL; bd = bd->link ) {
885 allocated -= BLOCK_SIZE_W;
887 cap = &capabilities[i];
888 if (cap->r.rCurrentNursery->free <
889 cap->r.rCurrentNursery->start + BLOCK_SIZE_W) {
890 allocated -= (cap->r.rCurrentNursery->start + BLOCK_SIZE_W)
891 - cap->r.rCurrentNursery->free;
895 bdescr *current_nursery = MainCapability.r.rCurrentNursery;
897 for ( bd = current_nursery->link; bd != NULL; bd = bd->link ) {
898 allocated -= BLOCK_SIZE_W;
900 if (current_nursery->free < current_nursery->start + BLOCK_SIZE_W) {
901 allocated -= (current_nursery->start + BLOCK_SIZE_W)
902 - current_nursery->free;
907 total_allocated += allocated;
911 /* Approximate the amount of live data in the heap. To be called just
912 * after garbage collection (see GarbageCollect()).
921 if (RtsFlags.GcFlags.generations == 1) {
922 return (g0s0->n_large_blocks + g0s0->n_blocks) * BLOCK_SIZE_W;
925 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
926 for (s = 0; s < generations[g].n_steps; s++) {
927 /* approximate amount of live data (doesn't take into account slop
928 * at end of each block).
930 if (g == 0 && s == 0) {
933 stp = &generations[g].steps[s];
934 live += (stp->n_large_blocks + stp->n_blocks) * BLOCK_SIZE_W;
940 /* Approximate the number of blocks that will be needed at the next
941 * garbage collection.
943 * Assume: all data currently live will remain live. Steps that will
944 * be collected next time will therefore need twice as many blocks
945 * since all the data will be copied.
954 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
955 for (s = 0; s < generations[g].n_steps; s++) {
956 if (g == 0 && s == 0) { continue; }
957 stp = &generations[g].steps[s];
958 if (generations[g].steps[0].n_blocks +
959 generations[g].steps[0].n_large_blocks
960 > generations[g].max_blocks
961 && stp->is_compacted == 0) {
962 needed += 2 * stp->n_blocks;
964 needed += stp->n_blocks;
971 /* ----------------------------------------------------------------------------
974 Executable memory must be managed separately from non-executable
975 memory. Most OSs these days require you to jump through hoops to
976 dynamically allocate executable memory, due to various security
979 Here we provide a small memory allocator for executable memory.
980 Memory is managed with a page granularity; we allocate linearly
981 in the page, and when the page is emptied (all objects on the page
982 are free) we free the page again, not forgetting to make it
985 TODO: The inability to handle objects bigger than BLOCK_SIZE_W means that
986 the linker cannot use allocateExec for loading object code files
987 on Windows. Once allocateExec can handle larger objects, the linker
988 should be modified to use allocateExec instead of VirtualAlloc.
989 ------------------------------------------------------------------------- */
991 static bdescr *exec_block;
993 void *allocateExec (nat bytes)
1000 // round up to words.
1001 n = (bytes + sizeof(W_) + 1) / sizeof(W_);
1003 if (n+1 > BLOCK_SIZE_W) {
1004 barf("allocateExec: can't handle large objects");
1007 if (exec_block == NULL ||
1008 exec_block->free + n + 1 > exec_block->start + BLOCK_SIZE_W) {
1010 lnat pagesize = getPageSize();
1011 bd = allocGroup(stg_max(1, pagesize / BLOCK_SIZE));
1012 debugTrace(DEBUG_gc, "allocate exec block %p", bd->start);
1014 bd->flags = BF_EXEC;
1015 bd->link = exec_block;
1016 if (exec_block != NULL) {
1017 exec_block->u.back = bd;
1020 setExecutable(bd->start, bd->blocks * BLOCK_SIZE, rtsTrue);
1023 *(exec_block->free) = n; // store the size of this chunk
1024 exec_block->gen_no += n; // gen_no stores the number of words allocated
1025 ret = exec_block->free + 1;
1026 exec_block->free += n + 1;
1032 void freeExec (void *addr)
1034 StgPtr p = (StgPtr)addr - 1;
1035 bdescr *bd = Bdescr((StgPtr)p);
1037 if ((bd->flags & BF_EXEC) == 0) {
1038 barf("freeExec: not executable");
1041 if (*(StgPtr)p == 0) {
1042 barf("freeExec: already free?");
1047 bd->gen_no -= *(StgPtr)p;
1050 if (bd->gen_no == 0) {
1051 // Free the block if it is empty, but not if it is the block at
1052 // the head of the queue.
1053 if (bd != exec_block) {
1054 debugTrace(DEBUG_gc, "free exec block %p", bd->start);
1055 dbl_link_remove(bd, &exec_block);
1056 setExecutable(bd->start, bd->blocks * BLOCK_SIZE, rtsFalse);
1059 bd->free = bd->start;
1066 /* -----------------------------------------------------------------------------
1069 memInventory() checks for memory leaks by counting up all the
1070 blocks we know about and comparing that to the number of blocks
1071 allegedly floating around in the system.
1072 -------------------------------------------------------------------------- */
1077 countBlocks(bdescr *bd)
1080 for (n=0; bd != NULL; bd=bd->link) {
1086 // (*1) Just like countBlocks, except that we adjust the count for a
1087 // megablock group so that it doesn't include the extra few blocks
1088 // that would be taken up by block descriptors in the second and
1089 // subsequent megablock. This is so we can tally the count with the
1090 // number of blocks allocated in the system, for memInventory().
1092 countAllocdBlocks(bdescr *bd)
1095 for (n=0; bd != NULL; bd=bd->link) {
1097 // hack for megablock groups: see (*1) above
1098 if (bd->blocks > BLOCKS_PER_MBLOCK) {
1099 n -= (MBLOCK_SIZE / BLOCK_SIZE - BLOCKS_PER_MBLOCK)
1100 * (bd->blocks/(MBLOCK_SIZE/BLOCK_SIZE));
1107 stepBlocks (step *stp)
1109 ASSERT(countBlocks(stp->blocks) == stp->n_blocks);
1110 ASSERT(countBlocks(stp->large_objects) == stp->n_large_blocks);
1111 return stp->n_blocks + stp->n_old_blocks +
1112 countAllocdBlocks(stp->large_objects);
1120 lnat gen_blocks[RtsFlags.GcFlags.generations];
1121 lnat nursery_blocks, retainer_blocks,
1122 arena_blocks, exec_blocks;
1123 lnat live_blocks = 0, free_blocks = 0;
1125 // count the blocks we current have
1127 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1129 for (i = 0; i < n_capabilities; i++) {
1130 gen_blocks[g] += countBlocks(capabilities[i].mut_lists[g]);
1132 gen_blocks[g] += countAllocdBlocks(generations[g].mut_list);
1133 for (s = 0; s < generations[g].n_steps; s++) {
1134 stp = &generations[g].steps[s];
1135 gen_blocks[g] += stepBlocks(stp);
1140 for (i = 0; i < n_nurseries; i++) {
1141 nursery_blocks += stepBlocks(&nurseries[i]);
1144 retainer_blocks = 0;
1146 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER) {
1147 retainer_blocks = retainerStackBlocks();
1151 // count the blocks allocated by the arena allocator
1152 arena_blocks = arenaBlocks();
1154 // count the blocks containing executable memory
1155 exec_blocks = countAllocdBlocks(exec_block);
1157 /* count the blocks on the free list */
1158 free_blocks = countFreeList();
1161 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1162 live_blocks += gen_blocks[g];
1164 live_blocks += nursery_blocks +
1165 + retainer_blocks + arena_blocks + exec_blocks;
1167 if (live_blocks + free_blocks != mblocks_allocated * BLOCKS_PER_MBLOCK)
1169 debugBelch("Memory leak detected\n");
1170 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1171 debugBelch(" gen %d blocks : %4lu\n", g, gen_blocks[g]);
1173 debugBelch(" nursery : %4lu\n", nursery_blocks);
1174 debugBelch(" retainer : %4lu\n", retainer_blocks);
1175 debugBelch(" arena blocks : %4lu\n", arena_blocks);
1176 debugBelch(" exec : %4lu\n", exec_blocks);
1177 debugBelch(" free : %4lu\n", free_blocks);
1178 debugBelch(" total : %4lu\n\n", live_blocks + free_blocks);
1179 debugBelch(" in system : %4lu\n", mblocks_allocated * BLOCKS_PER_MBLOCK);
1185 /* Full heap sanity check. */
1191 if (RtsFlags.GcFlags.generations == 1) {
1192 checkHeap(g0s0->blocks);
1193 checkChain(g0s0->large_objects);
1196 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1197 for (s = 0; s < generations[g].n_steps; s++) {
1198 if (g == 0 && s == 0) { continue; }
1199 ASSERT(countBlocks(generations[g].steps[s].blocks)
1200 == generations[g].steps[s].n_blocks);
1201 ASSERT(countBlocks(generations[g].steps[s].large_objects)
1202 == generations[g].steps[s].n_large_blocks);
1203 checkHeap(generations[g].steps[s].blocks);
1204 checkChain(generations[g].steps[s].large_objects);
1206 checkMutableList(generations[g].mut_list, g);
1211 for (s = 0; s < n_nurseries; s++) {
1212 ASSERT(countBlocks(nurseries[s].blocks)
1213 == nurseries[s].n_blocks);
1214 ASSERT(countBlocks(nurseries[s].large_objects)
1215 == nurseries[s].n_large_blocks);
1218 checkFreeListSanity();
1222 /* Nursery sanity check */
1224 checkNurserySanity( step *stp )
1230 for (bd = stp->blocks; bd != NULL; bd = bd->link) {
1231 ASSERT(bd->u.back == prev);
1233 blocks += bd->blocks;
1235 ASSERT(blocks == stp->n_blocks);
1238 // handy function for use in gdb, because Bdescr() is inlined.
1239 extern bdescr *_bdescr( StgPtr p );