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)
41 * All these globals require sm_mutex to access in THREADED_RTS mode.
43 StgClosure *caf_list = NULL;
44 StgClosure *revertible_caf_list = NULL;
47 bdescr *pinned_object_block; /* allocate pinned objects into this block */
48 nat alloc_blocks; /* number of allocate()d blocks since GC */
49 nat alloc_blocks_lim; /* approximate limit on alloc_blocks */
51 static bdescr *exec_block;
53 generation *generations = NULL; /* all the generations */
54 generation *g0 = NULL; /* generation 0, for convenience */
55 generation *oldest_gen = NULL; /* oldest generation, for convenience */
56 step *g0s0 = NULL; /* generation 0, step 0, for convenience */
59 step *all_steps = NULL; /* single array of steps */
61 ullong total_allocated = 0; /* total memory allocated during run */
63 nat n_nurseries = 0; /* == RtsFlags.ParFlags.nNodes, convenience */
64 step *nurseries = NULL; /* array of nurseries, >1 only if THREADED_RTS */
68 * Storage manager mutex: protects all the above state from
69 * simultaneous access by two STG threads.
73 * This mutex is used by atomicModifyMutVar# only
75 Mutex atomic_modify_mutvar_mutex;
82 static void *stgAllocForGMP (size_t size_in_bytes);
83 static void *stgReallocForGMP (void *ptr, size_t old_size, size_t new_size);
84 static void stgDeallocForGMP (void *ptr, size_t size);
87 initStep (step *stp, int g, int s)
90 stp->abs_no = RtsFlags.GcFlags.steps * g + s;
94 stp->live_estimate = 0;
95 stp->old_blocks = NULL;
96 stp->n_old_blocks = 0;
97 stp->gen = &generations[g];
99 stp->large_objects = NULL;
100 stp->n_large_blocks = 0;
101 stp->scavenged_large_objects = NULL;
102 stp->n_scavenged_large_blocks = 0;
107 initSpinLock(&stp->sync_todo);
108 initSpinLock(&stp->sync_large_objects);
110 stp->threads = END_TSO_QUEUE;
111 stp->old_threads = END_TSO_QUEUE;
120 if (generations != NULL) {
121 // multi-init protection
127 /* Sanity check to make sure the LOOKS_LIKE_ macros appear to be
128 * doing something reasonable.
130 /* We use the NOT_NULL variant or gcc warns that the test is always true */
131 ASSERT(LOOKS_LIKE_INFO_PTR_NOT_NULL((StgWord)&stg_BLACKHOLE_info));
132 ASSERT(LOOKS_LIKE_CLOSURE_PTR(&stg_dummy_ret_closure));
133 ASSERT(!HEAP_ALLOCED(&stg_dummy_ret_closure));
135 if (RtsFlags.GcFlags.maxHeapSize != 0 &&
136 RtsFlags.GcFlags.heapSizeSuggestion >
137 RtsFlags.GcFlags.maxHeapSize) {
138 RtsFlags.GcFlags.maxHeapSize = RtsFlags.GcFlags.heapSizeSuggestion;
141 if (RtsFlags.GcFlags.maxHeapSize != 0 &&
142 RtsFlags.GcFlags.minAllocAreaSize >
143 RtsFlags.GcFlags.maxHeapSize) {
144 errorBelch("maximum heap size (-M) is smaller than minimum alloc area size (-A)");
145 RtsFlags.GcFlags.minAllocAreaSize = RtsFlags.GcFlags.maxHeapSize;
148 initBlockAllocator();
150 #if defined(THREADED_RTS)
151 initMutex(&sm_mutex);
152 initMutex(&atomic_modify_mutvar_mutex);
157 /* allocate generation info array */
158 generations = (generation *)stgMallocBytes(RtsFlags.GcFlags.generations
159 * sizeof(struct generation_),
160 "initStorage: gens");
162 /* allocate all the steps into an array. It is important that we do
163 it this way, because we need the invariant that two step pointers
164 can be directly compared to see which is the oldest.
165 Remember that the last generation has only one step. */
166 total_steps = 1 + (RtsFlags.GcFlags.generations - 1) * RtsFlags.GcFlags.steps;
167 all_steps = stgMallocBytes(total_steps * sizeof(struct step_),
168 "initStorage: steps");
170 /* Initialise all generations */
171 for(g = 0; g < RtsFlags.GcFlags.generations; g++) {
172 gen = &generations[g];
174 gen->mut_list = allocBlock();
175 gen->collections = 0;
176 gen->par_collections = 0;
177 gen->failed_promotions = 0;
181 /* A couple of convenience pointers */
182 g0 = &generations[0];
183 oldest_gen = &generations[RtsFlags.GcFlags.generations-1];
185 /* Allocate step structures in each generation */
186 if (RtsFlags.GcFlags.generations > 1) {
187 /* Only for multiple-generations */
189 /* Oldest generation: one step */
190 oldest_gen->n_steps = 1;
191 oldest_gen->steps = all_steps + (RtsFlags.GcFlags.generations - 1)
192 * RtsFlags.GcFlags.steps;
194 /* set up all except the oldest generation with 2 steps */
195 for(g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
196 generations[g].n_steps = RtsFlags.GcFlags.steps;
197 generations[g].steps = all_steps + g * RtsFlags.GcFlags.steps;
201 /* single generation, i.e. a two-space collector */
203 g0->steps = all_steps;
207 n_nurseries = n_capabilities;
211 nurseries = stgMallocBytes (n_nurseries * sizeof(struct step_),
212 "initStorage: nurseries");
214 /* Initialise all steps */
215 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
216 for (s = 0; s < generations[g].n_steps; s++) {
217 initStep(&generations[g].steps[s], g, s);
221 for (s = 0; s < n_nurseries; s++) {
222 initStep(&nurseries[s], 0, s);
225 /* Set up the destination pointers in each younger gen. step */
226 for (g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
227 for (s = 0; s < generations[g].n_steps-1; s++) {
228 generations[g].steps[s].to = &generations[g].steps[s+1];
230 generations[g].steps[s].to = &generations[g+1].steps[0];
232 oldest_gen->steps[0].to = &oldest_gen->steps[0];
234 for (s = 0; s < n_nurseries; s++) {
235 nurseries[s].to = generations[0].steps[0].to;
238 /* The oldest generation has one step. */
239 if (RtsFlags.GcFlags.compact || RtsFlags.GcFlags.sweep) {
240 if (RtsFlags.GcFlags.generations == 1) {
241 errorBelch("WARNING: compact/sweep is incompatible with -G1; disabled");
243 oldest_gen->steps[0].mark = 1;
244 if (RtsFlags.GcFlags.compact)
245 oldest_gen->steps[0].compact = 1;
249 generations[0].max_blocks = 0;
250 g0s0 = &generations[0].steps[0];
252 /* The allocation area. Policy: keep the allocation area
253 * small to begin with, even if we have a large suggested heap
254 * size. Reason: we're going to do a major collection first, and we
255 * don't want it to be a big one. This vague idea is borne out by
256 * rigorous experimental evidence.
260 weak_ptr_list = NULL;
262 revertible_caf_list = NULL;
264 /* initialise the allocate() interface */
266 alloc_blocks_lim = RtsFlags.GcFlags.minAllocAreaSize;
270 /* Tell GNU multi-precision pkg about our custom alloc functions */
271 mp_set_memory_functions(stgAllocForGMP, stgReallocForGMP, stgDeallocForGMP);
274 initSpinLock(&gc_alloc_block_sync);
275 initSpinLock(&recordMutableGen_sync);
283 IF_DEBUG(gc, statDescribeGens());
291 stat_exit(calcAllocated());
297 stgFree(g0s0); // frees all the steps
298 stgFree(generations);
300 #if defined(THREADED_RTS)
301 closeMutex(&sm_mutex);
302 closeMutex(&atomic_modify_mutvar_mutex);
307 /* -----------------------------------------------------------------------------
310 The entry code for every CAF does the following:
312 - builds a CAF_BLACKHOLE in the heap
313 - pushes an update frame pointing to the CAF_BLACKHOLE
314 - invokes UPD_CAF(), which:
315 - calls newCaf, below
316 - updates the CAF with a static indirection to the CAF_BLACKHOLE
318 Why do we build a BLACKHOLE in the heap rather than just updating
319 the thunk directly? It's so that we only need one kind of update
320 frame - otherwise we'd need a static version of the update frame too.
322 newCaf() does the following:
324 - it puts the CAF on the oldest generation's mut-once list.
325 This is so that we can treat the CAF as a root when collecting
328 For GHCI, we have additional requirements when dealing with CAFs:
330 - we must *retain* all dynamically-loaded CAFs ever entered,
331 just in case we need them again.
332 - we must be able to *revert* CAFs that have been evaluated, to
333 their pre-evaluated form.
335 To do this, we use an additional CAF list. When newCaf() is
336 called on a dynamically-loaded CAF, we add it to the CAF list
337 instead of the old-generation mutable list, and save away its
338 old info pointer (in caf->saved_info) for later reversion.
340 To revert all the CAFs, we traverse the CAF list and reset the
341 info pointer to caf->saved_info, then throw away the CAF list.
342 (see GC.c:revertCAFs()).
346 -------------------------------------------------------------------------- */
349 newCAF(StgClosure* caf)
356 // If we are in GHCi _and_ we are using dynamic libraries,
357 // then we can't redirect newCAF calls to newDynCAF (see below),
358 // so we make newCAF behave almost like newDynCAF.
359 // The dynamic libraries might be used by both the interpreted
360 // program and GHCi itself, so they must not be reverted.
361 // This also means that in GHCi with dynamic libraries, CAFs are not
362 // garbage collected. If this turns out to be a problem, we could
363 // do another hack here and do an address range test on caf to figure
364 // out whether it is from a dynamic library.
365 ((StgIndStatic *)caf)->saved_info = (StgInfoTable *)caf->header.info;
366 ((StgIndStatic *)caf)->static_link = caf_list;
371 /* Put this CAF on the mutable list for the old generation.
372 * This is a HACK - the IND_STATIC closure doesn't really have
373 * a mut_link field, but we pretend it has - in fact we re-use
374 * the STATIC_LINK field for the time being, because when we
375 * come to do a major GC we won't need the mut_link field
376 * any more and can use it as a STATIC_LINK.
378 ((StgIndStatic *)caf)->saved_info = NULL;
379 recordMutableGen(caf, oldest_gen);
385 // An alternate version of newCaf which is used for dynamically loaded
386 // object code in GHCi. In this case we want to retain *all* CAFs in
387 // the object code, because they might be demanded at any time from an
388 // expression evaluated on the command line.
389 // Also, GHCi might want to revert CAFs, so we add these to the
390 // revertible_caf_list.
392 // The linker hackily arranges that references to newCaf from dynamic
393 // code end up pointing to newDynCAF.
395 newDynCAF(StgClosure *caf)
399 ((StgIndStatic *)caf)->saved_info = (StgInfoTable *)caf->header.info;
400 ((StgIndStatic *)caf)->static_link = revertible_caf_list;
401 revertible_caf_list = caf;
406 /* -----------------------------------------------------------------------------
408 -------------------------------------------------------------------------- */
411 allocNursery (step *stp, bdescr *tail, nat blocks)
416 // Allocate a nursery: we allocate fresh blocks one at a time and
417 // cons them on to the front of the list, not forgetting to update
418 // the back pointer on the tail of the list to point to the new block.
419 for (i=0; i < blocks; i++) {
422 processNursery() in LdvProfile.c assumes that every block group in
423 the nursery contains only a single block. So, if a block group is
424 given multiple blocks, change processNursery() accordingly.
428 // double-link the nursery: we might need to insert blocks
435 bd->free = bd->start;
443 assignNurseriesToCapabilities (void)
448 for (i = 0; i < n_nurseries; i++) {
449 capabilities[i].r.rNursery = &nurseries[i];
450 capabilities[i].r.rCurrentNursery = nurseries[i].blocks;
451 capabilities[i].r.rCurrentAlloc = NULL;
453 #else /* THREADED_RTS */
454 MainCapability.r.rNursery = &nurseries[0];
455 MainCapability.r.rCurrentNursery = nurseries[0].blocks;
456 MainCapability.r.rCurrentAlloc = NULL;
461 allocNurseries( void )
465 for (i = 0; i < n_nurseries; i++) {
466 nurseries[i].blocks =
467 allocNursery(&nurseries[i], NULL,
468 RtsFlags.GcFlags.minAllocAreaSize);
469 nurseries[i].n_blocks = RtsFlags.GcFlags.minAllocAreaSize;
470 nurseries[i].old_blocks = NULL;
471 nurseries[i].n_old_blocks = 0;
473 assignNurseriesToCapabilities();
477 resetNurseries( void )
483 for (i = 0; i < n_nurseries; i++) {
485 for (bd = stp->blocks; bd; bd = bd->link) {
486 bd->free = bd->start;
487 ASSERT(bd->gen_no == 0);
488 ASSERT(bd->step == stp);
489 IF_DEBUG(sanity,memset(bd->start, 0xaa, BLOCK_SIZE));
492 assignNurseriesToCapabilities();
496 countNurseryBlocks (void)
501 for (i = 0; i < n_nurseries; i++) {
502 blocks += nurseries[i].n_blocks;
508 resizeNursery ( step *stp, nat blocks )
513 nursery_blocks = stp->n_blocks;
514 if (nursery_blocks == blocks) return;
516 if (nursery_blocks < blocks) {
517 debugTrace(DEBUG_gc, "increasing size of nursery to %d blocks",
519 stp->blocks = allocNursery(stp, stp->blocks, blocks-nursery_blocks);
524 debugTrace(DEBUG_gc, "decreasing size of nursery to %d blocks",
528 while (nursery_blocks > blocks) {
530 next_bd->u.back = NULL;
531 nursery_blocks -= bd->blocks; // might be a large block
536 // might have gone just under, by freeing a large block, so make
537 // up the difference.
538 if (nursery_blocks < blocks) {
539 stp->blocks = allocNursery(stp, stp->blocks, blocks-nursery_blocks);
543 stp->n_blocks = blocks;
544 ASSERT(countBlocks(stp->blocks) == stp->n_blocks);
548 // Resize each of the nurseries to the specified size.
551 resizeNurseriesFixed (nat blocks)
554 for (i = 0; i < n_nurseries; i++) {
555 resizeNursery(&nurseries[i], blocks);
560 // Resize the nurseries to the total specified size.
563 resizeNurseries (nat blocks)
565 // If there are multiple nurseries, then we just divide the number
566 // of available blocks between them.
567 resizeNurseriesFixed(blocks / n_nurseries);
571 /* -----------------------------------------------------------------------------
572 move_TSO is called to update the TSO structure after it has been
573 moved from one place to another.
574 -------------------------------------------------------------------------- */
577 move_TSO (StgTSO *src, StgTSO *dest)
581 // relocate the stack pointer...
582 diff = (StgPtr)dest - (StgPtr)src; // In *words*
583 dest->sp = (StgPtr)dest->sp + diff;
586 /* -----------------------------------------------------------------------------
587 The allocate() interface
589 allocateInGen() function allocates memory directly into a specific
590 generation. It always succeeds, and returns a chunk of memory n
591 words long. n can be larger than the size of a block if necessary,
592 in which case a contiguous block group will be allocated.
594 allocate(n) is equivalent to allocateInGen(g0).
595 -------------------------------------------------------------------------- */
598 allocateInGen (generation *g, lnat n)
606 TICK_ALLOC_HEAP_NOCTR(n);
611 if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_))
613 lnat req_blocks = (lnat)BLOCK_ROUND_UP(n*sizeof(W_)) / BLOCK_SIZE;
615 // Attempting to allocate an object larger than maxHeapSize
616 // should definitely be disallowed. (bug #1791)
617 if (RtsFlags.GcFlags.maxHeapSize > 0 &&
618 req_blocks >= RtsFlags.GcFlags.maxHeapSize) {
620 // heapOverflow() doesn't exit (see #2592), but we aren't
621 // in a position to do a clean shutdown here: we
622 // either have to allocate the memory or exit now.
623 // Allocating the memory would be bad, because the user
624 // has requested that we not exceed maxHeapSize, so we
626 stg_exit(EXIT_HEAPOVERFLOW);
629 bd = allocGroup(req_blocks);
630 dbl_link_onto(bd, &stp->large_objects);
631 stp->n_large_blocks += bd->blocks; // might be larger than req_blocks
632 alloc_blocks += bd->blocks;
635 bd->flags = BF_LARGE;
636 bd->free = bd->start + n;
641 // small allocation (<LARGE_OBJECT_THRESHOLD) */
643 if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
648 bd->link = stp->blocks;
665 return allocateInGen(g0,n);
669 allocatedBytes( void )
673 allocated = alloc_blocks * BLOCK_SIZE_W;
674 if (pinned_object_block != NULL) {
675 allocated -= (pinned_object_block->start + BLOCK_SIZE_W) -
676 pinned_object_block->free;
682 // split N blocks off the front of the given bdescr, returning the
683 // new block group. We treat the remainder as if it
684 // had been freshly allocated in generation 0.
686 splitLargeBlock (bdescr *bd, nat blocks)
690 // subtract the original number of blocks from the counter first
691 bd->step->n_large_blocks -= bd->blocks;
693 new_bd = splitBlockGroup (bd, blocks);
695 dbl_link_onto(new_bd, &g0s0->large_objects);
696 g0s0->n_large_blocks += new_bd->blocks;
697 new_bd->gen_no = g0s0->no;
699 new_bd->flags = BF_LARGE;
700 new_bd->free = bd->free;
701 ASSERT(new_bd->free <= new_bd->start + new_bd->blocks * BLOCK_SIZE_W);
703 // add the new number of blocks to the counter. Due to the gaps
704 // for block descriptor, new_bd->blocks + bd->blocks might not be
705 // equal to the original bd->blocks, which is why we do it this way.
706 bd->step->n_large_blocks += bd->blocks;
711 /* -----------------------------------------------------------------------------
714 This allocates memory in the current thread - it is intended for
715 use primarily from STG-land where we have a Capability. It is
716 better than allocate() because it doesn't require taking the
717 sm_mutex lock in the common case.
719 Memory is allocated directly from the nursery if possible (but not
720 from the current nursery block, so as not to interfere with
722 -------------------------------------------------------------------------- */
725 allocateLocal (Capability *cap, lnat n)
730 if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
731 return allocateInGen(g0,n);
734 /* small allocation (<LARGE_OBJECT_THRESHOLD) */
736 TICK_ALLOC_HEAP_NOCTR(n);
739 bd = cap->r.rCurrentAlloc;
740 if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
742 // The CurrentAlloc block is full, we need to find another
743 // one. First, we try taking the next block from the
745 bd = cap->r.rCurrentNursery->link;
747 if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
748 // The nursery is empty, or the next block is already
749 // full: allocate a fresh block (we can't fail here).
752 cap->r.rNursery->n_blocks++;
755 bd->step = cap->r.rNursery;
757 // NO: alloc_blocks++;
758 // calcAllocated() uses the size of the nursery, and we've
759 // already bumpted nursery->n_blocks above. We'll GC
760 // pretty quickly now anyway, because MAYBE_GC() will
761 // notice that CurrentNursery->link is NULL.
763 // we have a block in the nursery: take it and put
764 // it at the *front* of the nursery list, and use it
765 // to allocate() from.
766 cap->r.rCurrentNursery->link = bd->link;
767 if (bd->link != NULL) {
768 bd->link->u.back = cap->r.rCurrentNursery;
771 dbl_link_onto(bd, &cap->r.rNursery->blocks);
772 cap->r.rCurrentAlloc = bd;
773 IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
780 /* ---------------------------------------------------------------------------
781 Allocate a fixed/pinned object.
783 We allocate small pinned objects into a single block, allocating a
784 new block when the current one overflows. The block is chained
785 onto the large_object_list of generation 0 step 0.
787 NOTE: The GC can't in general handle pinned objects. This
788 interface is only safe to use for ByteArrays, which have no
789 pointers and don't require scavenging. It works because the
790 block's descriptor has the BF_LARGE flag set, so the block is
791 treated as a large object and chained onto various lists, rather
792 than the individual objects being copied. However, when it comes
793 to scavenge the block, the GC will only scavenge the first object.
794 The reason is that the GC can't linearly scan a block of pinned
795 objects at the moment (doing so would require using the
796 mostly-copying techniques). But since we're restricting ourselves
797 to pinned ByteArrays, not scavenging is ok.
799 This function is called by newPinnedByteArray# which immediately
800 fills the allocated memory with a MutableByteArray#.
801 ------------------------------------------------------------------------- */
804 allocatePinned( lnat n )
807 bdescr *bd = pinned_object_block;
809 // If the request is for a large object, then allocate()
810 // will give us a pinned object anyway.
811 if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
817 TICK_ALLOC_HEAP_NOCTR(n);
820 // we always return 8-byte aligned memory. bd->free must be
821 // 8-byte aligned to begin with, so we just round up n to
822 // the nearest multiple of 8 bytes.
823 if (sizeof(StgWord) == 4) {
827 // If we don't have a block of pinned objects yet, or the current
828 // one isn't large enough to hold the new object, allocate a new one.
829 if (bd == NULL || (bd->free + n) > (bd->start + BLOCK_SIZE_W)) {
830 pinned_object_block = bd = allocBlock();
831 dbl_link_onto(bd, &g0s0->large_objects);
832 g0s0->n_large_blocks++;
835 bd->flags = BF_PINNED | BF_LARGE;
836 bd->free = bd->start;
846 /* -----------------------------------------------------------------------------
848 -------------------------------------------------------------------------- */
851 This is the write barrier for MUT_VARs, a.k.a. IORefs. A
852 MUT_VAR_CLEAN object is not on the mutable list; a MUT_VAR_DIRTY
853 is. When written to, a MUT_VAR_CLEAN turns into a MUT_VAR_DIRTY
854 and is put on the mutable list.
857 dirty_MUT_VAR(StgRegTable *reg, StgClosure *p)
859 Capability *cap = regTableToCapability(reg);
861 if (p->header.info == &stg_MUT_VAR_CLEAN_info) {
862 p->header.info = &stg_MUT_VAR_DIRTY_info;
863 bd = Bdescr((StgPtr)p);
864 if (bd->gen_no > 0) recordMutableCap(p,cap,bd->gen_no);
868 // Setting a TSO's link field with a write barrier.
869 // It is *not* necessary to call this function when
870 // * setting the link field to END_TSO_QUEUE
871 // * putting a TSO on the blackhole_queue
872 // * setting the link field of the currently running TSO, as it
873 // will already be dirty.
875 setTSOLink (Capability *cap, StgTSO *tso, StgTSO *target)
878 if ((tso->flags & (TSO_DIRTY|TSO_LINK_DIRTY)) == 0) {
879 tso->flags |= TSO_LINK_DIRTY;
880 bd = Bdescr((StgPtr)tso);
881 if (bd->gen_no > 0) recordMutableCap((StgClosure*)tso,cap,bd->gen_no);
887 dirty_TSO (Capability *cap, StgTSO *tso)
890 if ((tso->flags & (TSO_DIRTY|TSO_LINK_DIRTY)) == 0) {
891 bd = Bdescr((StgPtr)tso);
892 if (bd->gen_no > 0) recordMutableCap((StgClosure*)tso,cap,bd->gen_no);
894 tso->flags |= TSO_DIRTY;
898 This is the write barrier for MVARs. An MVAR_CLEAN objects is not
899 on the mutable list; a MVAR_DIRTY is. When written to, a
900 MVAR_CLEAN turns into a MVAR_DIRTY and is put on the mutable list.
901 The check for MVAR_CLEAN is inlined at the call site for speed,
902 this really does make a difference on concurrency-heavy benchmarks
903 such as Chaneneos and cheap-concurrency.
906 dirty_MVAR(StgRegTable *reg, StgClosure *p)
908 Capability *cap = regTableToCapability(reg);
910 bd = Bdescr((StgPtr)p);
911 if (bd->gen_no > 0) recordMutableCap(p,cap,bd->gen_no);
914 /* -----------------------------------------------------------------------------
915 Allocation functions for GMP.
917 These all use the allocate() interface - we can't have any garbage
918 collection going on during a gmp operation, so we use allocate()
919 which always succeeds. The gmp operations which might need to
920 allocate will ask the storage manager (via doYouWantToGC()) whether
921 a garbage collection is required, in case we get into a loop doing
922 only allocate() style allocation.
923 -------------------------------------------------------------------------- */
926 stgAllocForGMP (size_t size_in_bytes)
929 nat data_size_in_words, total_size_in_words;
931 /* round up to a whole number of words */
932 data_size_in_words = (size_in_bytes + sizeof(W_) + 1) / sizeof(W_);
933 total_size_in_words = sizeofW(StgArrWords) + data_size_in_words;
935 /* allocate and fill it in. */
936 #if defined(THREADED_RTS)
937 arr = (StgArrWords *)allocateLocal(myTask()->cap, total_size_in_words);
939 arr = (StgArrWords *)allocateLocal(&MainCapability, total_size_in_words);
941 SET_ARR_HDR(arr, &stg_ARR_WORDS_info, CCCS, data_size_in_words);
943 /* and return a ptr to the goods inside the array */
948 stgReallocForGMP (void *ptr, size_t old_size, size_t new_size)
951 void *new_stuff_ptr = stgAllocForGMP(new_size);
953 char *p = (char *) ptr;
954 char *q = (char *) new_stuff_ptr;
956 min_size = old_size < new_size ? old_size : new_size;
957 for (; i < min_size; i++, p++, q++) {
961 return(new_stuff_ptr);
965 stgDeallocForGMP (void *ptr STG_UNUSED,
966 size_t size STG_UNUSED)
968 /* easy for us: the garbage collector does the dealloc'n */
971 /* -----------------------------------------------------------------------------
973 * -------------------------------------------------------------------------- */
975 /* -----------------------------------------------------------------------------
978 * Approximate how much we've allocated: number of blocks in the
979 * nursery + blocks allocated via allocate() - unused nusery blocks.
980 * This leaves a little slop at the end of each block, and doesn't
981 * take into account large objects (ToDo).
982 * -------------------------------------------------------------------------- */
985 calcAllocated( void )
990 allocated = allocatedBytes();
991 allocated += countNurseryBlocks() * BLOCK_SIZE_W;
996 for (i = 0; i < n_nurseries; i++) {
998 for ( bd = capabilities[i].r.rCurrentNursery->link;
999 bd != NULL; bd = bd->link ) {
1000 allocated -= BLOCK_SIZE_W;
1002 cap = &capabilities[i];
1003 if (cap->r.rCurrentNursery->free <
1004 cap->r.rCurrentNursery->start + BLOCK_SIZE_W) {
1005 allocated -= (cap->r.rCurrentNursery->start + BLOCK_SIZE_W)
1006 - cap->r.rCurrentNursery->free;
1010 bdescr *current_nursery = MainCapability.r.rCurrentNursery;
1012 for ( bd = current_nursery->link; bd != NULL; bd = bd->link ) {
1013 allocated -= BLOCK_SIZE_W;
1015 if (current_nursery->free < current_nursery->start + BLOCK_SIZE_W) {
1016 allocated -= (current_nursery->start + BLOCK_SIZE_W)
1017 - current_nursery->free;
1022 total_allocated += allocated;
1026 /* Approximate the amount of live data in the heap. To be called just
1027 * after garbage collection (see GarbageCollect()).
1030 calcLiveBlocks(void)
1036 if (RtsFlags.GcFlags.generations == 1) {
1037 return g0s0->n_large_blocks + g0s0->n_blocks;
1040 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1041 for (s = 0; s < generations[g].n_steps; s++) {
1042 /* approximate amount of live data (doesn't take into account slop
1043 * at end of each block).
1045 if (g == 0 && s == 0) {
1048 stp = &generations[g].steps[s];
1049 live += stp->n_large_blocks + stp->n_blocks;
1056 countOccupied(bdescr *bd)
1061 for (; bd != NULL; bd = bd->link) {
1062 ASSERT(bd->free <= bd->start + bd->blocks * BLOCK_SIZE_W);
1063 words += bd->free - bd->start;
1068 // Return an accurate count of the live data in the heap, excluding
1077 if (RtsFlags.GcFlags.generations == 1) {
1078 return g0s0->n_words + countOccupied(g0s0->large_objects);
1082 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1083 for (s = 0; s < generations[g].n_steps; s++) {
1084 if (g == 0 && s == 0) continue;
1085 stp = &generations[g].steps[s];
1086 live += stp->n_words + countOccupied(stp->large_objects);
1092 /* Approximate the number of blocks that will be needed at the next
1093 * garbage collection.
1095 * Assume: all data currently live will remain live. Steps that will
1096 * be collected next time will therefore need twice as many blocks
1097 * since all the data will be copied.
1106 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1107 for (s = 0; s < generations[g].n_steps; s++) {
1108 if (g == 0 && s == 0) { continue; }
1109 stp = &generations[g].steps[s];
1111 // we need at least this much space
1112 needed += stp->n_blocks + stp->n_large_blocks;
1114 // any additional space needed to collect this gen next time?
1115 if (g == 0 || // always collect gen 0
1116 (generations[g].steps[0].n_blocks +
1117 generations[g].steps[0].n_large_blocks
1118 > generations[g].max_blocks)) {
1119 // we will collect this gen next time
1122 needed += stp->n_blocks / BITS_IN(W_);
1124 needed += stp->n_blocks / 100;
1127 continue; // no additional space needed for compaction
1129 needed += stp->n_blocks;
1137 /* ----------------------------------------------------------------------------
1140 Executable memory must be managed separately from non-executable
1141 memory. Most OSs these days require you to jump through hoops to
1142 dynamically allocate executable memory, due to various security
1145 Here we provide a small memory allocator for executable memory.
1146 Memory is managed with a page granularity; we allocate linearly
1147 in the page, and when the page is emptied (all objects on the page
1148 are free) we free the page again, not forgetting to make it
1151 TODO: The inability to handle objects bigger than BLOCK_SIZE_W means that
1152 the linker cannot use allocateExec for loading object code files
1153 on Windows. Once allocateExec can handle larger objects, the linker
1154 should be modified to use allocateExec instead of VirtualAlloc.
1155 ------------------------------------------------------------------------- */
1157 #if defined(linux_HOST_OS)
1159 // On Linux we need to use libffi for allocating executable memory,
1160 // because it knows how to work around the restrictions put in place
1163 void *allocateExec (nat bytes, void **exec_ret)
1167 ret = ffi_closure_alloc (sizeof(void *) + (size_t)bytes, (void**)&exec);
1169 if (ret == NULL) return ret;
1170 *ret = ret; // save the address of the writable mapping, for freeExec().
1171 *exec_ret = exec + 1;
1175 // freeExec gets passed the executable address, not the writable address.
1176 void freeExec (void *addr)
1179 writable = *((void**)addr - 1);
1181 ffi_closure_free (writable);
1187 void *allocateExec (nat bytes, void **exec_ret)
1194 // round up to words.
1195 n = (bytes + sizeof(W_) + 1) / sizeof(W_);
1197 if (n+1 > BLOCK_SIZE_W) {
1198 barf("allocateExec: can't handle large objects");
1201 if (exec_block == NULL ||
1202 exec_block->free + n + 1 > exec_block->start + BLOCK_SIZE_W) {
1204 lnat pagesize = getPageSize();
1205 bd = allocGroup(stg_max(1, pagesize / BLOCK_SIZE));
1206 debugTrace(DEBUG_gc, "allocate exec block %p", bd->start);
1208 bd->flags = BF_EXEC;
1209 bd->link = exec_block;
1210 if (exec_block != NULL) {
1211 exec_block->u.back = bd;
1214 setExecutable(bd->start, bd->blocks * BLOCK_SIZE, rtsTrue);
1217 *(exec_block->free) = n; // store the size of this chunk
1218 exec_block->gen_no += n; // gen_no stores the number of words allocated
1219 ret = exec_block->free + 1;
1220 exec_block->free += n + 1;
1227 void freeExec (void *addr)
1229 StgPtr p = (StgPtr)addr - 1;
1230 bdescr *bd = Bdescr((StgPtr)p);
1232 if ((bd->flags & BF_EXEC) == 0) {
1233 barf("freeExec: not executable");
1236 if (*(StgPtr)p == 0) {
1237 barf("freeExec: already free?");
1242 bd->gen_no -= *(StgPtr)p;
1245 if (bd->gen_no == 0) {
1246 // Free the block if it is empty, but not if it is the block at
1247 // the head of the queue.
1248 if (bd != exec_block) {
1249 debugTrace(DEBUG_gc, "free exec block %p", bd->start);
1250 dbl_link_remove(bd, &exec_block);
1251 setExecutable(bd->start, bd->blocks * BLOCK_SIZE, rtsFalse);
1254 bd->free = bd->start;
1261 #endif /* mingw32_HOST_OS */
1263 /* -----------------------------------------------------------------------------
1266 memInventory() checks for memory leaks by counting up all the
1267 blocks we know about and comparing that to the number of blocks
1268 allegedly floating around in the system.
1269 -------------------------------------------------------------------------- */
1273 // Useful for finding partially full blocks in gdb
1274 void findSlop(bdescr *bd);
1275 void findSlop(bdescr *bd)
1279 for (; bd != NULL; bd = bd->link) {
1280 slop = (bd->blocks * BLOCK_SIZE_W) - (bd->free - bd->start);
1281 if (slop > (1024/sizeof(W_))) {
1282 debugBelch("block at %p (bdescr %p) has %ldKB slop\n",
1283 bd->start, bd, slop / (1024/sizeof(W_)));
1289 countBlocks(bdescr *bd)
1292 for (n=0; bd != NULL; bd=bd->link) {
1298 // (*1) Just like countBlocks, except that we adjust the count for a
1299 // megablock group so that it doesn't include the extra few blocks
1300 // that would be taken up by block descriptors in the second and
1301 // subsequent megablock. This is so we can tally the count with the
1302 // number of blocks allocated in the system, for memInventory().
1304 countAllocdBlocks(bdescr *bd)
1307 for (n=0; bd != NULL; bd=bd->link) {
1309 // hack for megablock groups: see (*1) above
1310 if (bd->blocks > BLOCKS_PER_MBLOCK) {
1311 n -= (MBLOCK_SIZE / BLOCK_SIZE - BLOCKS_PER_MBLOCK)
1312 * (bd->blocks/(MBLOCK_SIZE/BLOCK_SIZE));
1319 stepBlocks (step *stp)
1321 ASSERT(countBlocks(stp->blocks) == stp->n_blocks);
1322 ASSERT(countBlocks(stp->large_objects) == stp->n_large_blocks);
1323 return stp->n_blocks + stp->n_old_blocks +
1324 countAllocdBlocks(stp->large_objects);
1327 // If memInventory() calculates that we have a memory leak, this
1328 // function will try to find the block(s) that are leaking by marking
1329 // all the ones that we know about, and search through memory to find
1330 // blocks that are not marked. In the debugger this can help to give
1331 // us a clue about what kind of block leaked. In the future we might
1332 // annotate blocks with their allocation site to give more helpful
1335 findMemoryLeak (void)
1338 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1339 for (i = 0; i < n_capabilities; i++) {
1340 markBlocks(capabilities[i].mut_lists[g]);
1342 markBlocks(generations[g].mut_list);
1343 for (s = 0; s < generations[g].n_steps; s++) {
1344 markBlocks(generations[g].steps[s].blocks);
1345 markBlocks(generations[g].steps[s].large_objects);
1349 for (i = 0; i < n_nurseries; i++) {
1350 markBlocks(nurseries[i].blocks);
1351 markBlocks(nurseries[i].large_objects);
1356 // if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER) {
1357 // markRetainerBlocks();
1361 // count the blocks allocated by the arena allocator
1363 // markArenaBlocks();
1365 // count the blocks containing executable memory
1366 markBlocks(exec_block);
1368 reportUnmarkedBlocks();
1373 memInventory (rtsBool show)
1377 lnat gen_blocks[RtsFlags.GcFlags.generations];
1378 lnat nursery_blocks, retainer_blocks,
1379 arena_blocks, exec_blocks;
1380 lnat live_blocks = 0, free_blocks = 0;
1383 // count the blocks we current have
1385 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1387 for (i = 0; i < n_capabilities; i++) {
1388 gen_blocks[g] += countBlocks(capabilities[i].mut_lists[g]);
1390 gen_blocks[g] += countAllocdBlocks(generations[g].mut_list);
1391 for (s = 0; s < generations[g].n_steps; s++) {
1392 stp = &generations[g].steps[s];
1393 gen_blocks[g] += stepBlocks(stp);
1398 for (i = 0; i < n_nurseries; i++) {
1399 nursery_blocks += stepBlocks(&nurseries[i]);
1402 retainer_blocks = 0;
1404 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER) {
1405 retainer_blocks = retainerStackBlocks();
1409 // count the blocks allocated by the arena allocator
1410 arena_blocks = arenaBlocks();
1412 // count the blocks containing executable memory
1413 exec_blocks = countAllocdBlocks(exec_block);
1415 /* count the blocks on the free list */
1416 free_blocks = countFreeList();
1419 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1420 live_blocks += gen_blocks[g];
1422 live_blocks += nursery_blocks +
1423 + retainer_blocks + arena_blocks + exec_blocks;
1425 #define MB(n) (((n) * BLOCK_SIZE_W) / ((1024*1024)/sizeof(W_)))
1427 leak = live_blocks + free_blocks != mblocks_allocated * BLOCKS_PER_MBLOCK;
1432 debugBelch("Memory leak detected:\n");
1434 debugBelch("Memory inventory:\n");
1436 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1437 debugBelch(" gen %d blocks : %5lu blocks (%lu MB)\n", g,
1438 gen_blocks[g], MB(gen_blocks[g]));
1440 debugBelch(" nursery : %5lu blocks (%lu MB)\n",
1441 nursery_blocks, MB(nursery_blocks));
1442 debugBelch(" retainer : %5lu blocks (%lu MB)\n",
1443 retainer_blocks, MB(retainer_blocks));
1444 debugBelch(" arena blocks : %5lu blocks (%lu MB)\n",
1445 arena_blocks, MB(arena_blocks));
1446 debugBelch(" exec : %5lu blocks (%lu MB)\n",
1447 exec_blocks, MB(exec_blocks));
1448 debugBelch(" free : %5lu blocks (%lu MB)\n",
1449 free_blocks, MB(free_blocks));
1450 debugBelch(" total : %5lu blocks (%lu MB)\n",
1451 live_blocks + free_blocks, MB(live_blocks+free_blocks));
1453 debugBelch("\n in system : %5lu blocks (%lu MB)\n",
1454 mblocks_allocated * BLOCKS_PER_MBLOCK, mblocks_allocated);
1462 ASSERT(n_alloc_blocks == live_blocks);
1467 /* Full heap sanity check. */
1473 if (RtsFlags.GcFlags.generations == 1) {
1474 checkHeap(g0s0->blocks);
1475 checkChain(g0s0->large_objects);
1478 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1479 for (s = 0; s < generations[g].n_steps; s++) {
1480 if (g == 0 && s == 0) { continue; }
1481 ASSERT(countBlocks(generations[g].steps[s].blocks)
1482 == generations[g].steps[s].n_blocks);
1483 ASSERT(countBlocks(generations[g].steps[s].large_objects)
1484 == generations[g].steps[s].n_large_blocks);
1485 checkHeap(generations[g].steps[s].blocks);
1486 checkChain(generations[g].steps[s].large_objects);
1488 checkMutableList(generations[g].mut_list, g);
1493 for (s = 0; s < n_nurseries; s++) {
1494 ASSERT(countBlocks(nurseries[s].blocks)
1495 == nurseries[s].n_blocks);
1496 ASSERT(countBlocks(nurseries[s].large_objects)
1497 == nurseries[s].n_large_blocks);
1500 checkFreeListSanity();
1503 #if defined(THREADED_RTS)
1504 // check the stacks too in threaded mode, because we don't do a
1505 // full heap sanity check in this case (see checkHeap())
1506 checkGlobalTSOList(rtsTrue);
1508 checkGlobalTSOList(rtsFalse);
1512 /* Nursery sanity check */
1514 checkNurserySanity( step *stp )
1520 for (bd = stp->blocks; bd != NULL; bd = bd->link) {
1521 ASSERT(bd->u.back == prev);
1523 blocks += bd->blocks;
1525 ASSERT(blocks == stp->n_blocks);
1528 // handy function for use in gdb, because Bdescr() is inlined.
1529 extern bdescr *_bdescr( StgPtr p );