1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team, 1998-2008
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 */
55 step *all_steps = NULL; /* single array of steps */
57 ullong total_allocated = 0; /* total memory allocated during run */
59 nat n_nurseries = 0; /* == RtsFlags.ParFlags.nNodes, convenience */
60 step *nurseries = NULL; /* array of nurseries, >1 only if THREADED_RTS */
64 * Storage manager mutex: protects all the above state from
65 * simultaneous access by two STG threads.
69 * This mutex is used by atomicModifyMutVar# only
71 Mutex atomic_modify_mutvar_mutex;
78 static void *stgAllocForGMP (size_t size_in_bytes);
79 static void *stgReallocForGMP (void *ptr, size_t old_size, size_t new_size);
80 static void stgDeallocForGMP (void *ptr, size_t size);
83 initStep (step *stp, int g, int s)
86 stp->abs_no = RtsFlags.GcFlags.steps * g + s;
90 stp->live_estimate = 0;
91 stp->old_blocks = NULL;
92 stp->n_old_blocks = 0;
93 stp->gen = &generations[g];
95 stp->large_objects = NULL;
96 stp->n_large_blocks = 0;
97 stp->scavenged_large_objects = NULL;
98 stp->n_scavenged_large_blocks = 0;
103 initSpinLock(&stp->sync_todo);
104 initSpinLock(&stp->sync_large_objects);
106 stp->threads = END_TSO_QUEUE;
107 stp->old_threads = END_TSO_QUEUE;
116 if (generations != NULL) {
117 // multi-init protection
123 /* Sanity check to make sure the LOOKS_LIKE_ macros appear to be
124 * doing something reasonable.
126 /* We use the NOT_NULL variant or gcc warns that the test is always true */
127 ASSERT(LOOKS_LIKE_INFO_PTR_NOT_NULL(&stg_BLACKHOLE_info));
128 ASSERT(LOOKS_LIKE_CLOSURE_PTR(&stg_dummy_ret_closure));
129 ASSERT(!HEAP_ALLOCED(&stg_dummy_ret_closure));
131 if (RtsFlags.GcFlags.maxHeapSize != 0 &&
132 RtsFlags.GcFlags.heapSizeSuggestion >
133 RtsFlags.GcFlags.maxHeapSize) {
134 RtsFlags.GcFlags.maxHeapSize = RtsFlags.GcFlags.heapSizeSuggestion;
137 if (RtsFlags.GcFlags.maxHeapSize != 0 &&
138 RtsFlags.GcFlags.minAllocAreaSize >
139 RtsFlags.GcFlags.maxHeapSize) {
140 errorBelch("maximum heap size (-M) is smaller than minimum alloc area size (-A)");
141 RtsFlags.GcFlags.minAllocAreaSize = RtsFlags.GcFlags.maxHeapSize;
144 initBlockAllocator();
146 #if defined(THREADED_RTS)
147 initMutex(&sm_mutex);
148 initMutex(&atomic_modify_mutvar_mutex);
153 /* allocate generation info array */
154 generations = (generation *)stgMallocBytes(RtsFlags.GcFlags.generations
155 * sizeof(struct generation_),
156 "initStorage: gens");
158 /* allocate all the steps into an array. It is important that we do
159 it this way, because we need the invariant that two step pointers
160 can be directly compared to see which is the oldest.
161 Remember that the last generation has only one step. */
162 total_steps = 1 + (RtsFlags.GcFlags.generations - 1) * RtsFlags.GcFlags.steps;
163 all_steps = stgMallocBytes(total_steps * sizeof(struct step_),
164 "initStorage: steps");
166 /* Initialise all generations */
167 for(g = 0; g < RtsFlags.GcFlags.generations; g++) {
168 gen = &generations[g];
170 gen->mut_list = allocBlock();
171 gen->collections = 0;
172 gen->par_collections = 0;
173 gen->failed_promotions = 0;
177 /* A couple of convenience pointers */
178 g0 = &generations[0];
179 oldest_gen = &generations[RtsFlags.GcFlags.generations-1];
181 /* Allocate step structures in each generation */
182 if (RtsFlags.GcFlags.generations > 1) {
183 /* Only for multiple-generations */
185 /* Oldest generation: one step */
186 oldest_gen->n_steps = 1;
187 oldest_gen->steps = all_steps + (RtsFlags.GcFlags.generations - 1)
188 * RtsFlags.GcFlags.steps;
190 /* set up all except the oldest generation with 2 steps */
191 for(g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
192 generations[g].n_steps = RtsFlags.GcFlags.steps;
193 generations[g].steps = all_steps + g * RtsFlags.GcFlags.steps;
197 /* single generation, i.e. a two-space collector */
199 g0->steps = all_steps;
203 n_nurseries = n_capabilities;
207 nurseries = stgMallocBytes (n_nurseries * sizeof(struct step_),
208 "initStorage: nurseries");
210 /* Initialise all steps */
211 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
212 for (s = 0; s < generations[g].n_steps; s++) {
213 initStep(&generations[g].steps[s], g, s);
217 for (s = 0; s < n_nurseries; s++) {
218 initStep(&nurseries[s], 0, s);
221 /* Set up the destination pointers in each younger gen. step */
222 for (g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
223 for (s = 0; s < generations[g].n_steps-1; s++) {
224 generations[g].steps[s].to = &generations[g].steps[s+1];
226 generations[g].steps[s].to = &generations[g+1].steps[0];
228 oldest_gen->steps[0].to = &oldest_gen->steps[0];
230 for (s = 0; s < n_nurseries; s++) {
231 nurseries[s].to = generations[0].steps[0].to;
234 /* The oldest generation has one step. */
235 if (RtsFlags.GcFlags.compact || RtsFlags.GcFlags.sweep) {
236 if (RtsFlags.GcFlags.generations == 1) {
237 errorBelch("WARNING: compact/sweep is incompatible with -G1; disabled");
239 oldest_gen->steps[0].mark = 1;
240 if (RtsFlags.GcFlags.compact)
241 oldest_gen->steps[0].compact = 1;
245 generations[0].max_blocks = 0;
246 g0s0 = &generations[0].steps[0];
248 /* The allocation area. Policy: keep the allocation area
249 * small to begin with, even if we have a large suggested heap
250 * size. Reason: we're going to do a major collection first, and we
251 * don't want it to be a big one. This vague idea is borne out by
252 * rigorous experimental evidence.
256 weak_ptr_list = NULL;
258 revertible_caf_list = NULL;
260 /* initialise the allocate() interface */
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);
268 initSpinLock(&gc_alloc_block_sync);
269 initSpinLock(&recordMutableGen_sync);
273 IF_DEBUG(gc, statDescribeGens());
281 stat_exit(calcAllocated());
287 stgFree(g0s0); // frees all the steps
288 stgFree(generations);
290 #if defined(THREADED_RTS)
291 closeMutex(&sm_mutex);
292 closeMutex(&atomic_modify_mutvar_mutex);
297 /* -----------------------------------------------------------------------------
300 The entry code for every CAF does the following:
302 - builds a CAF_BLACKHOLE in the heap
303 - pushes an update frame pointing to the CAF_BLACKHOLE
304 - invokes UPD_CAF(), which:
305 - calls newCaf, below
306 - updates the CAF with a static indirection to the CAF_BLACKHOLE
308 Why do we build a BLACKHOLE in the heap rather than just updating
309 the thunk directly? It's so that we only need one kind of update
310 frame - otherwise we'd need a static version of the update frame too.
312 newCaf() does the following:
314 - it puts the CAF on the oldest generation's mut-once list.
315 This is so that we can treat the CAF as a root when collecting
318 For GHCI, we have additional requirements when dealing with CAFs:
320 - we must *retain* all dynamically-loaded CAFs ever entered,
321 just in case we need them again.
322 - we must be able to *revert* CAFs that have been evaluated, to
323 their pre-evaluated form.
325 To do this, we use an additional CAF list. When newCaf() is
326 called on a dynamically-loaded CAF, we add it to the CAF list
327 instead of the old-generation mutable list, and save away its
328 old info pointer (in caf->saved_info) for later reversion.
330 To revert all the CAFs, we traverse the CAF list and reset the
331 info pointer to caf->saved_info, then throw away the CAF list.
332 (see GC.c:revertCAFs()).
336 -------------------------------------------------------------------------- */
339 newCAF(StgClosure* caf)
346 // If we are in GHCi _and_ we are using dynamic libraries,
347 // then we can't redirect newCAF calls to newDynCAF (see below),
348 // so we make newCAF behave almost like newDynCAF.
349 // The dynamic libraries might be used by both the interpreted
350 // program and GHCi itself, so they must not be reverted.
351 // This also means that in GHCi with dynamic libraries, CAFs are not
352 // garbage collected. If this turns out to be a problem, we could
353 // do another hack here and do an address range test on caf to figure
354 // out whether it is from a dynamic library.
355 ((StgIndStatic *)caf)->saved_info = (StgInfoTable *)caf->header.info;
356 ((StgIndStatic *)caf)->static_link = caf_list;
361 /* Put this CAF on the mutable list for the old generation.
362 * This is a HACK - the IND_STATIC closure doesn't really have
363 * a mut_link field, but we pretend it has - in fact we re-use
364 * the STATIC_LINK field for the time being, because when we
365 * come to do a major GC we won't need the mut_link field
366 * any more and can use it as a STATIC_LINK.
368 ((StgIndStatic *)caf)->saved_info = NULL;
369 recordMutableGen(caf, oldest_gen);
375 // An alternate version of newCaf which is used for dynamically loaded
376 // object code in GHCi. In this case we want to retain *all* CAFs in
377 // the object code, because they might be demanded at any time from an
378 // expression evaluated on the command line.
379 // Also, GHCi might want to revert CAFs, so we add these to the
380 // revertible_caf_list.
382 // The linker hackily arranges that references to newCaf from dynamic
383 // code end up pointing to newDynCAF.
385 newDynCAF(StgClosure *caf)
389 ((StgIndStatic *)caf)->saved_info = (StgInfoTable *)caf->header.info;
390 ((StgIndStatic *)caf)->static_link = revertible_caf_list;
391 revertible_caf_list = caf;
396 /* -----------------------------------------------------------------------------
398 -------------------------------------------------------------------------- */
401 allocNursery (step *stp, bdescr *tail, nat blocks)
406 // Allocate a nursery: we allocate fresh blocks one at a time and
407 // cons them on to the front of the list, not forgetting to update
408 // the back pointer on the tail of the list to point to the new block.
409 for (i=0; i < blocks; i++) {
412 processNursery() in LdvProfile.c assumes that every block group in
413 the nursery contains only a single block. So, if a block group is
414 given multiple blocks, change processNursery() accordingly.
418 // double-link the nursery: we might need to insert blocks
425 bd->free = bd->start;
433 assignNurseriesToCapabilities (void)
438 for (i = 0; i < n_nurseries; i++) {
439 capabilities[i].r.rNursery = &nurseries[i];
440 capabilities[i].r.rCurrentNursery = nurseries[i].blocks;
441 capabilities[i].r.rCurrentAlloc = NULL;
443 #else /* THREADED_RTS */
444 MainCapability.r.rNursery = &nurseries[0];
445 MainCapability.r.rCurrentNursery = nurseries[0].blocks;
446 MainCapability.r.rCurrentAlloc = NULL;
451 allocNurseries( void )
455 for (i = 0; i < n_nurseries; i++) {
456 nurseries[i].blocks =
457 allocNursery(&nurseries[i], NULL,
458 RtsFlags.GcFlags.minAllocAreaSize);
459 nurseries[i].n_blocks = RtsFlags.GcFlags.minAllocAreaSize;
460 nurseries[i].old_blocks = NULL;
461 nurseries[i].n_old_blocks = 0;
463 assignNurseriesToCapabilities();
467 resetNurseries( void )
473 for (i = 0; i < n_nurseries; i++) {
475 for (bd = stp->blocks; bd; bd = bd->link) {
476 bd->free = bd->start;
477 ASSERT(bd->gen_no == 0);
478 ASSERT(bd->step == stp);
479 IF_DEBUG(sanity,memset(bd->start, 0xaa, BLOCK_SIZE));
482 assignNurseriesToCapabilities();
486 countNurseryBlocks (void)
491 for (i = 0; i < n_nurseries; i++) {
492 blocks += nurseries[i].n_blocks;
498 resizeNursery ( step *stp, nat blocks )
503 nursery_blocks = stp->n_blocks;
504 if (nursery_blocks == blocks) return;
506 if (nursery_blocks < blocks) {
507 debugTrace(DEBUG_gc, "increasing size of nursery to %d blocks",
509 stp->blocks = allocNursery(stp, stp->blocks, blocks-nursery_blocks);
514 debugTrace(DEBUG_gc, "decreasing size of nursery to %d blocks",
518 while (nursery_blocks > blocks) {
520 next_bd->u.back = NULL;
521 nursery_blocks -= bd->blocks; // might be a large block
526 // might have gone just under, by freeing a large block, so make
527 // up the difference.
528 if (nursery_blocks < blocks) {
529 stp->blocks = allocNursery(stp, stp->blocks, blocks-nursery_blocks);
533 stp->n_blocks = blocks;
534 ASSERT(countBlocks(stp->blocks) == stp->n_blocks);
538 // Resize each of the nurseries to the specified size.
541 resizeNurseriesFixed (nat blocks)
544 for (i = 0; i < n_nurseries; i++) {
545 resizeNursery(&nurseries[i], blocks);
550 // Resize the nurseries to the total specified size.
553 resizeNurseries (nat blocks)
555 // If there are multiple nurseries, then we just divide the number
556 // of available blocks between them.
557 resizeNurseriesFixed(blocks / n_nurseries);
561 /* -----------------------------------------------------------------------------
562 move_TSO is called to update the TSO structure after it has been
563 moved from one place to another.
564 -------------------------------------------------------------------------- */
567 move_TSO (StgTSO *src, StgTSO *dest)
571 // relocate the stack pointer...
572 diff = (StgPtr)dest - (StgPtr)src; // In *words*
573 dest->sp = (StgPtr)dest->sp + diff;
576 /* -----------------------------------------------------------------------------
577 The allocate() interface
579 allocateInGen() function allocates memory directly into a specific
580 generation. It always succeeds, and returns a chunk of memory n
581 words long. n can be larger than the size of a block if necessary,
582 in which case a contiguous block group will be allocated.
584 allocate(n) is equivalent to allocateInGen(g0).
585 -------------------------------------------------------------------------- */
588 allocateInGen (generation *g, lnat n)
596 TICK_ALLOC_HEAP_NOCTR(n);
601 if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_))
603 lnat req_blocks = (lnat)BLOCK_ROUND_UP(n*sizeof(W_)) / BLOCK_SIZE;
605 // Attempting to allocate an object larger than maxHeapSize
606 // should definitely be disallowed. (bug #1791)
607 if (RtsFlags.GcFlags.maxHeapSize > 0 &&
608 req_blocks >= RtsFlags.GcFlags.maxHeapSize) {
612 bd = allocGroup(req_blocks);
613 dbl_link_onto(bd, &stp->large_objects);
614 stp->n_large_blocks += bd->blocks; // might be larger than req_blocks
617 bd->flags = BF_LARGE;
618 bd->free = bd->start + n;
623 // small allocation (<LARGE_OBJECT_THRESHOLD) */
625 if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
630 bd->link = stp->blocks;
647 return allocateInGen(g0,n);
651 allocatedBytes( void )
655 allocated = alloc_blocks * BLOCK_SIZE_W;
656 if (pinned_object_block != NULL) {
657 allocated -= (pinned_object_block->start + BLOCK_SIZE_W) -
658 pinned_object_block->free;
664 // split N blocks off the start of the given bdescr, returning the
665 // remainder as a new block group. We treat the remainder as if it
666 // had been freshly allocated in generation 0.
668 splitLargeBlock (bdescr *bd, nat blocks)
672 // subtract the original number of blocks from the counter first
673 bd->step->n_large_blocks -= bd->blocks;
675 new_bd = splitBlockGroup (bd, blocks);
677 dbl_link_onto(new_bd, &g0s0->large_objects);
678 g0s0->n_large_blocks += new_bd->blocks;
679 new_bd->gen_no = g0s0->no;
681 new_bd->flags = BF_LARGE;
682 new_bd->free = bd->free;
684 // add the new number of blocks to the counter. Due to the gaps
685 // for block descriptor, new_bd->blocks + bd->blocks might not be
686 // equal to the original bd->blocks, which is why we do it this way.
687 bd->step->n_large_blocks += bd->blocks;
692 /* -----------------------------------------------------------------------------
695 This allocates memory in the current thread - it is intended for
696 use primarily from STG-land where we have a Capability. It is
697 better than allocate() because it doesn't require taking the
698 sm_mutex lock in the common case.
700 Memory is allocated directly from the nursery if possible (but not
701 from the current nursery block, so as not to interfere with
703 -------------------------------------------------------------------------- */
706 allocateLocal (Capability *cap, lnat n)
711 if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
712 return allocateInGen(g0,n);
715 /* small allocation (<LARGE_OBJECT_THRESHOLD) */
717 TICK_ALLOC_HEAP_NOCTR(n);
720 bd = cap->r.rCurrentAlloc;
721 if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
723 // The CurrentAlloc block is full, we need to find another
724 // one. First, we try taking the next block from the
726 bd = cap->r.rCurrentNursery->link;
728 if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
729 // The nursery is empty, or the next block is already
730 // full: allocate a fresh block (we can't fail here).
733 cap->r.rNursery->n_blocks++;
736 bd->step = cap->r.rNursery;
738 // NO: alloc_blocks++;
739 // calcAllocated() uses the size of the nursery, and we've
740 // already bumpted nursery->n_blocks above.
742 // we have a block in the nursery: take it and put
743 // it at the *front* of the nursery list, and use it
744 // to allocate() from.
745 cap->r.rCurrentNursery->link = bd->link;
746 if (bd->link != NULL) {
747 bd->link->u.back = cap->r.rCurrentNursery;
750 dbl_link_onto(bd, &cap->r.rNursery->blocks);
751 cap->r.rCurrentAlloc = bd;
752 IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
759 /* ---------------------------------------------------------------------------
760 Allocate a fixed/pinned object.
762 We allocate small pinned objects into a single block, allocating a
763 new block when the current one overflows. The block is chained
764 onto the large_object_list of generation 0 step 0.
766 NOTE: The GC can't in general handle pinned objects. This
767 interface is only safe to use for ByteArrays, which have no
768 pointers and don't require scavenging. It works because the
769 block's descriptor has the BF_LARGE flag set, so the block is
770 treated as a large object and chained onto various lists, rather
771 than the individual objects being copied. However, when it comes
772 to scavenge the block, the GC will only scavenge the first object.
773 The reason is that the GC can't linearly scan a block of pinned
774 objects at the moment (doing so would require using the
775 mostly-copying techniques). But since we're restricting ourselves
776 to pinned ByteArrays, not scavenging is ok.
778 This function is called by newPinnedByteArray# which immediately
779 fills the allocated memory with a MutableByteArray#.
780 ------------------------------------------------------------------------- */
783 allocatePinned( lnat n )
786 bdescr *bd = pinned_object_block;
788 // If the request is for a large object, then allocate()
789 // will give us a pinned object anyway.
790 if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
796 TICK_ALLOC_HEAP_NOCTR(n);
799 // we always return 8-byte aligned memory. bd->free must be
800 // 8-byte aligned to begin with, so we just round up n to
801 // the nearest multiple of 8 bytes.
802 if (sizeof(StgWord) == 4) {
806 // If we don't have a block of pinned objects yet, or the current
807 // one isn't large enough to hold the new object, allocate a new one.
808 if (bd == NULL || (bd->free + n) > (bd->start + BLOCK_SIZE_W)) {
809 pinned_object_block = bd = allocBlock();
810 dbl_link_onto(bd, &g0s0->large_objects);
811 g0s0->n_large_blocks++;
814 bd->flags = BF_PINNED | BF_LARGE;
815 bd->free = bd->start;
825 /* -----------------------------------------------------------------------------
827 -------------------------------------------------------------------------- */
830 This is the write barrier for MUT_VARs, a.k.a. IORefs. A
831 MUT_VAR_CLEAN object is not on the mutable list; a MUT_VAR_DIRTY
832 is. When written to, a MUT_VAR_CLEAN turns into a MUT_VAR_DIRTY
833 and is put on the mutable list.
836 dirty_MUT_VAR(StgRegTable *reg, StgClosure *p)
838 Capability *cap = regTableToCapability(reg);
840 if (p->header.info == &stg_MUT_VAR_CLEAN_info) {
841 p->header.info = &stg_MUT_VAR_DIRTY_info;
842 bd = Bdescr((StgPtr)p);
843 if (bd->gen_no > 0) recordMutableCap(p,cap,bd->gen_no);
847 // Setting a TSO's link field with a write barrier.
848 // It is *not* necessary to call this function when
849 // * setting the link field to END_TSO_QUEUE
850 // * putting a TSO on the blackhole_queue
851 // * setting the link field of the currently running TSO, as it
852 // will already be dirty.
854 setTSOLink (Capability *cap, StgTSO *tso, StgTSO *target)
857 if ((tso->flags & (TSO_DIRTY|TSO_LINK_DIRTY)) == 0) {
858 tso->flags |= TSO_LINK_DIRTY;
859 bd = Bdescr((StgPtr)tso);
860 if (bd->gen_no > 0) recordMutableCap((StgClosure*)tso,cap,bd->gen_no);
866 dirty_TSO (Capability *cap, StgTSO *tso)
869 if ((tso->flags & (TSO_DIRTY|TSO_LINK_DIRTY)) == 0) {
870 bd = Bdescr((StgPtr)tso);
871 if (bd->gen_no > 0) recordMutableCap((StgClosure*)tso,cap,bd->gen_no);
873 tso->flags |= TSO_DIRTY;
877 This is the write barrier for MVARs. An MVAR_CLEAN objects is not
878 on the mutable list; a MVAR_DIRTY is. When written to, a
879 MVAR_CLEAN turns into a MVAR_DIRTY and is put on the mutable list.
880 The check for MVAR_CLEAN is inlined at the call site for speed,
881 this really does make a difference on concurrency-heavy benchmarks
882 such as Chaneneos and cheap-concurrency.
885 dirty_MVAR(StgRegTable *reg, StgClosure *p)
887 Capability *cap = regTableToCapability(reg);
889 bd = Bdescr((StgPtr)p);
890 if (bd->gen_no > 0) recordMutableCap(p,cap,bd->gen_no);
893 /* -----------------------------------------------------------------------------
894 Allocation functions for GMP.
896 These all use the allocate() interface - we can't have any garbage
897 collection going on during a gmp operation, so we use allocate()
898 which always succeeds. The gmp operations which might need to
899 allocate will ask the storage manager (via doYouWantToGC()) whether
900 a garbage collection is required, in case we get into a loop doing
901 only allocate() style allocation.
902 -------------------------------------------------------------------------- */
905 stgAllocForGMP (size_t size_in_bytes)
908 nat data_size_in_words, total_size_in_words;
910 /* round up to a whole number of words */
911 data_size_in_words = (size_in_bytes + sizeof(W_) + 1) / sizeof(W_);
912 total_size_in_words = sizeofW(StgArrWords) + data_size_in_words;
914 /* allocate and fill it in. */
915 #if defined(THREADED_RTS)
916 arr = (StgArrWords *)allocateLocal(myTask()->cap, total_size_in_words);
918 arr = (StgArrWords *)allocateLocal(&MainCapability, total_size_in_words);
920 SET_ARR_HDR(arr, &stg_ARR_WORDS_info, CCCS, data_size_in_words);
922 /* and return a ptr to the goods inside the array */
927 stgReallocForGMP (void *ptr, size_t old_size, size_t new_size)
929 void *new_stuff_ptr = stgAllocForGMP(new_size);
931 char *p = (char *) ptr;
932 char *q = (char *) new_stuff_ptr;
934 for (; i < old_size; i++, p++, q++) {
938 return(new_stuff_ptr);
942 stgDeallocForGMP (void *ptr STG_UNUSED,
943 size_t size STG_UNUSED)
945 /* easy for us: the garbage collector does the dealloc'n */
948 /* -----------------------------------------------------------------------------
950 * -------------------------------------------------------------------------- */
952 /* -----------------------------------------------------------------------------
955 * Approximate how much we've allocated: number of blocks in the
956 * nursery + blocks allocated via allocate() - unused nusery blocks.
957 * This leaves a little slop at the end of each block, and doesn't
958 * take into account large objects (ToDo).
959 * -------------------------------------------------------------------------- */
962 calcAllocated( void )
967 allocated = allocatedBytes();
968 allocated += countNurseryBlocks() * BLOCK_SIZE_W;
973 for (i = 0; i < n_nurseries; i++) {
975 for ( bd = capabilities[i].r.rCurrentNursery->link;
976 bd != NULL; bd = bd->link ) {
977 allocated -= BLOCK_SIZE_W;
979 cap = &capabilities[i];
980 if (cap->r.rCurrentNursery->free <
981 cap->r.rCurrentNursery->start + BLOCK_SIZE_W) {
982 allocated -= (cap->r.rCurrentNursery->start + BLOCK_SIZE_W)
983 - cap->r.rCurrentNursery->free;
987 bdescr *current_nursery = MainCapability.r.rCurrentNursery;
989 for ( bd = current_nursery->link; bd != NULL; bd = bd->link ) {
990 allocated -= BLOCK_SIZE_W;
992 if (current_nursery->free < current_nursery->start + BLOCK_SIZE_W) {
993 allocated -= (current_nursery->start + BLOCK_SIZE_W)
994 - current_nursery->free;
999 total_allocated += allocated;
1003 /* Approximate the amount of live data in the heap. To be called just
1004 * after garbage collection (see GarbageCollect()).
1007 calcLiveBlocks(void)
1013 if (RtsFlags.GcFlags.generations == 1) {
1014 return g0s0->n_large_blocks + g0s0->n_blocks;
1017 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1018 for (s = 0; s < generations[g].n_steps; s++) {
1019 /* approximate amount of live data (doesn't take into account slop
1020 * at end of each block).
1022 if (g == 0 && s == 0) {
1025 stp = &generations[g].steps[s];
1026 live += stp->n_large_blocks + stp->n_blocks;
1033 countOccupied(bdescr *bd)
1038 for (; bd != NULL; bd = bd->link) {
1039 ASSERT(bd->free <= bd->start + bd->blocks * BLOCK_SIZE_W);
1040 words += bd->free - bd->start;
1045 // Return an accurate count of the live data in the heap, excluding
1054 if (RtsFlags.GcFlags.generations == 1) {
1055 return g0s0->n_words + countOccupied(g0s0->large_objects);
1059 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1060 for (s = 0; s < generations[g].n_steps; s++) {
1061 if (g == 0 && s == 0) continue;
1062 stp = &generations[g].steps[s];
1063 live += stp->n_words + countOccupied(stp->large_objects);
1069 /* Approximate the number of blocks that will be needed at the next
1070 * garbage collection.
1072 * Assume: all data currently live will remain live. Steps that will
1073 * be collected next time will therefore need twice as many blocks
1074 * since all the data will be copied.
1083 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1084 for (s = 0; s < generations[g].n_steps; s++) {
1085 if (g == 0 && s == 0) { continue; }
1086 stp = &generations[g].steps[s];
1088 // we need at least this much space
1089 needed += stp->n_blocks + stp->n_large_blocks;
1091 // any additional space needed to collect this gen next time?
1092 if (g == 0 || // always collect gen 0
1093 (generations[g].steps[0].n_blocks +
1094 generations[g].steps[0].n_large_blocks
1095 > generations[g].max_blocks)) {
1096 // we will collect this gen next time
1099 needed += stp->n_blocks / BITS_IN(W_);
1101 needed += stp->n_blocks / 100;
1104 continue; // no additional space needed for compaction
1106 needed += stp->n_blocks;
1114 /* ----------------------------------------------------------------------------
1117 Executable memory must be managed separately from non-executable
1118 memory. Most OSs these days require you to jump through hoops to
1119 dynamically allocate executable memory, due to various security
1122 Here we provide a small memory allocator for executable memory.
1123 Memory is managed with a page granularity; we allocate linearly
1124 in the page, and when the page is emptied (all objects on the page
1125 are free) we free the page again, not forgetting to make it
1128 TODO: The inability to handle objects bigger than BLOCK_SIZE_W means that
1129 the linker cannot use allocateExec for loading object code files
1130 on Windows. Once allocateExec can handle larger objects, the linker
1131 should be modified to use allocateExec instead of VirtualAlloc.
1132 ------------------------------------------------------------------------- */
1134 static bdescr *exec_block;
1136 void *allocateExec (nat bytes)
1143 // round up to words.
1144 n = (bytes + sizeof(W_) + 1) / sizeof(W_);
1146 if (n+1 > BLOCK_SIZE_W) {
1147 barf("allocateExec: can't handle large objects");
1150 if (exec_block == NULL ||
1151 exec_block->free + n + 1 > exec_block->start + BLOCK_SIZE_W) {
1153 lnat pagesize = getPageSize();
1154 bd = allocGroup(stg_max(1, pagesize / BLOCK_SIZE));
1155 debugTrace(DEBUG_gc, "allocate exec block %p", bd->start);
1157 bd->flags = BF_EXEC;
1158 bd->link = exec_block;
1159 if (exec_block != NULL) {
1160 exec_block->u.back = bd;
1163 setExecutable(bd->start, bd->blocks * BLOCK_SIZE, rtsTrue);
1166 *(exec_block->free) = n; // store the size of this chunk
1167 exec_block->gen_no += n; // gen_no stores the number of words allocated
1168 ret = exec_block->free + 1;
1169 exec_block->free += n + 1;
1175 void freeExec (void *addr)
1177 StgPtr p = (StgPtr)addr - 1;
1178 bdescr *bd = Bdescr((StgPtr)p);
1180 if ((bd->flags & BF_EXEC) == 0) {
1181 barf("freeExec: not executable");
1184 if (*(StgPtr)p == 0) {
1185 barf("freeExec: already free?");
1190 bd->gen_no -= *(StgPtr)p;
1193 if (bd->gen_no == 0) {
1194 // Free the block if it is empty, but not if it is the block at
1195 // the head of the queue.
1196 if (bd != exec_block) {
1197 debugTrace(DEBUG_gc, "free exec block %p", bd->start);
1198 dbl_link_remove(bd, &exec_block);
1199 setExecutable(bd->start, bd->blocks * BLOCK_SIZE, rtsFalse);
1202 bd->free = bd->start;
1209 /* -----------------------------------------------------------------------------
1212 memInventory() checks for memory leaks by counting up all the
1213 blocks we know about and comparing that to the number of blocks
1214 allegedly floating around in the system.
1215 -------------------------------------------------------------------------- */
1219 // Useful for finding partially full blocks in gdb
1220 void findSlop(bdescr *bd);
1221 void findSlop(bdescr *bd)
1225 for (; bd != NULL; bd = bd->link) {
1226 slop = (bd->blocks * BLOCK_SIZE_W) - (bd->free - bd->start);
1227 if (slop > (1024/sizeof(W_))) {
1228 debugBelch("block at %p (bdescr %p) has %ldKB slop\n",
1229 bd->start, bd, slop / (1024/sizeof(W_)));
1235 countBlocks(bdescr *bd)
1238 for (n=0; bd != NULL; bd=bd->link) {
1244 // (*1) Just like countBlocks, except that we adjust the count for a
1245 // megablock group so that it doesn't include the extra few blocks
1246 // that would be taken up by block descriptors in the second and
1247 // subsequent megablock. This is so we can tally the count with the
1248 // number of blocks allocated in the system, for memInventory().
1250 countAllocdBlocks(bdescr *bd)
1253 for (n=0; bd != NULL; bd=bd->link) {
1255 // hack for megablock groups: see (*1) above
1256 if (bd->blocks > BLOCKS_PER_MBLOCK) {
1257 n -= (MBLOCK_SIZE / BLOCK_SIZE - BLOCKS_PER_MBLOCK)
1258 * (bd->blocks/(MBLOCK_SIZE/BLOCK_SIZE));
1265 stepBlocks (step *stp)
1267 ASSERT(countBlocks(stp->blocks) == stp->n_blocks);
1268 ASSERT(countBlocks(stp->large_objects) == stp->n_large_blocks);
1269 return stp->n_blocks + stp->n_old_blocks +
1270 countAllocdBlocks(stp->large_objects);
1274 memInventory (rtsBool show)
1278 lnat gen_blocks[RtsFlags.GcFlags.generations];
1279 lnat nursery_blocks, retainer_blocks,
1280 arena_blocks, exec_blocks;
1281 lnat live_blocks = 0, free_blocks = 0;
1284 // count the blocks we current have
1286 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1288 for (i = 0; i < n_capabilities; i++) {
1289 gen_blocks[g] += countBlocks(capabilities[i].mut_lists[g]);
1291 gen_blocks[g] += countAllocdBlocks(generations[g].mut_list);
1292 for (s = 0; s < generations[g].n_steps; s++) {
1293 stp = &generations[g].steps[s];
1294 gen_blocks[g] += stepBlocks(stp);
1299 for (i = 0; i < n_nurseries; i++) {
1300 nursery_blocks += stepBlocks(&nurseries[i]);
1303 retainer_blocks = 0;
1305 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER) {
1306 retainer_blocks = retainerStackBlocks();
1310 // count the blocks allocated by the arena allocator
1311 arena_blocks = arenaBlocks();
1313 // count the blocks containing executable memory
1314 exec_blocks = countAllocdBlocks(exec_block);
1316 /* count the blocks on the free list */
1317 free_blocks = countFreeList();
1320 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1321 live_blocks += gen_blocks[g];
1323 live_blocks += nursery_blocks +
1324 + retainer_blocks + arena_blocks + exec_blocks;
1326 #define MB(n) (((n) * BLOCK_SIZE_W) / ((1024*1024)/sizeof(W_)))
1328 leak = live_blocks + free_blocks != mblocks_allocated * BLOCKS_PER_MBLOCK;
1330 ASSERT(n_alloc_blocks == live_blocks);
1335 debugBelch("Memory leak detected:\n");
1337 debugBelch("Memory inventory:\n");
1339 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1340 debugBelch(" gen %d blocks : %5lu blocks (%lu MB)\n", g,
1341 gen_blocks[g], MB(gen_blocks[g]));
1343 debugBelch(" nursery : %5lu blocks (%lu MB)\n",
1344 nursery_blocks, MB(nursery_blocks));
1345 debugBelch(" retainer : %5lu blocks (%lu MB)\n",
1346 retainer_blocks, MB(retainer_blocks));
1347 debugBelch(" arena blocks : %5lu blocks (%lu MB)\n",
1348 arena_blocks, MB(arena_blocks));
1349 debugBelch(" exec : %5lu blocks (%lu MB)\n",
1350 exec_blocks, MB(exec_blocks));
1351 debugBelch(" free : %5lu blocks (%lu MB)\n",
1352 free_blocks, MB(free_blocks));
1353 debugBelch(" total : %5lu blocks (%lu MB)\n",
1354 live_blocks + free_blocks, MB(live_blocks+free_blocks));
1356 debugBelch("\n in system : %5lu blocks (%lu MB)\n",
1357 mblocks_allocated * BLOCKS_PER_MBLOCK, mblocks_allocated);
1363 /* Full heap sanity check. */
1369 if (RtsFlags.GcFlags.generations == 1) {
1370 checkHeap(g0s0->blocks);
1371 checkChain(g0s0->large_objects);
1374 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1375 for (s = 0; s < generations[g].n_steps; s++) {
1376 if (g == 0 && s == 0) { continue; }
1377 ASSERT(countBlocks(generations[g].steps[s].blocks)
1378 == generations[g].steps[s].n_blocks);
1379 ASSERT(countBlocks(generations[g].steps[s].large_objects)
1380 == generations[g].steps[s].n_large_blocks);
1381 checkHeap(generations[g].steps[s].blocks);
1382 checkChain(generations[g].steps[s].large_objects);
1384 checkMutableList(generations[g].mut_list, g);
1389 for (s = 0; s < n_nurseries; s++) {
1390 ASSERT(countBlocks(nurseries[s].blocks)
1391 == nurseries[s].n_blocks);
1392 ASSERT(countBlocks(nurseries[s].large_objects)
1393 == nurseries[s].n_large_blocks);
1396 checkFreeListSanity();
1400 /* Nursery sanity check */
1402 checkNurserySanity( step *stp )
1408 for (bd = stp->blocks; bd != NULL; bd = bd->link) {
1409 ASSERT(bd->u.back == prev);
1411 blocks += bd->blocks;
1413 ASSERT(blocks == stp->n_blocks);
1416 // handy function for use in gdb, because Bdescr() is inlined.
1417 extern bdescr *_bdescr( StgPtr p );