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"
24 #include "Capability.h"
26 #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 nat alloc_blocks_lim; /* GC if n_large_blocks in any nursery
48 generation *generations = NULL; /* all the generations */
49 generation *g0 = NULL; /* generation 0, for convenience */
50 generation *oldest_gen = NULL; /* oldest generation, for convenience */
53 step *all_steps = NULL; /* single array of steps */
55 ullong total_allocated = 0; /* total memory allocated during run */
57 step *nurseries = NULL; /* array of nurseries, size == n_capabilities */
61 * Storage manager mutex: protects all the above state from
62 * simultaneous access by two STG threads.
67 static void allocNurseries ( void );
70 initStep (step *stp, int g, int s)
73 stp->abs_no = RtsFlags.GcFlags.steps * g + s;
77 stp->live_estimate = 0;
78 stp->old_blocks = NULL;
79 stp->n_old_blocks = 0;
80 stp->gen = &generations[g];
82 stp->large_objects = NULL;
83 stp->n_large_blocks = 0;
84 stp->scavenged_large_objects = NULL;
85 stp->n_scavenged_large_blocks = 0;
90 initSpinLock(&stp->sync_large_objects);
92 stp->threads = END_TSO_QUEUE;
93 stp->old_threads = END_TSO_QUEUE;
102 if (generations != NULL) {
103 // multi-init protection
109 /* Sanity check to make sure the LOOKS_LIKE_ macros appear to be
110 * doing something reasonable.
112 /* We use the NOT_NULL variant or gcc warns that the test is always true */
113 ASSERT(LOOKS_LIKE_INFO_PTR_NOT_NULL((StgWord)&stg_BLACKHOLE_info));
114 ASSERT(LOOKS_LIKE_CLOSURE_PTR(&stg_dummy_ret_closure));
115 ASSERT(!HEAP_ALLOCED(&stg_dummy_ret_closure));
117 if (RtsFlags.GcFlags.maxHeapSize != 0 &&
118 RtsFlags.GcFlags.heapSizeSuggestion >
119 RtsFlags.GcFlags.maxHeapSize) {
120 RtsFlags.GcFlags.maxHeapSize = RtsFlags.GcFlags.heapSizeSuggestion;
123 if (RtsFlags.GcFlags.maxHeapSize != 0 &&
124 RtsFlags.GcFlags.minAllocAreaSize >
125 RtsFlags.GcFlags.maxHeapSize) {
126 errorBelch("maximum heap size (-M) is smaller than minimum alloc area size (-A)");
127 RtsFlags.GcFlags.minAllocAreaSize = RtsFlags.GcFlags.maxHeapSize;
130 initBlockAllocator();
132 #if defined(THREADED_RTS)
133 initMutex(&sm_mutex);
138 /* allocate generation info array */
139 generations = (generation *)stgMallocBytes(RtsFlags.GcFlags.generations
140 * sizeof(struct generation_),
141 "initStorage: gens");
143 /* Initialise all generations */
144 for(g = 0; g < RtsFlags.GcFlags.generations; g++) {
145 gen = &generations[g];
147 gen->mut_list = allocBlock();
148 gen->collections = 0;
149 gen->par_collections = 0;
150 gen->failed_promotions = 0;
154 /* A couple of convenience pointers */
155 g0 = &generations[0];
156 oldest_gen = &generations[RtsFlags.GcFlags.generations-1];
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 /* Allocate step structures in each generation */
167 if (RtsFlags.GcFlags.generations > 1) {
168 /* Only for multiple-generations */
170 /* Oldest generation: one step */
171 oldest_gen->n_steps = 1;
172 oldest_gen->steps = all_steps + (RtsFlags.GcFlags.generations - 1)
173 * RtsFlags.GcFlags.steps;
175 /* set up all except the oldest generation with 2 steps */
176 for(g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
177 generations[g].n_steps = RtsFlags.GcFlags.steps;
178 generations[g].steps = all_steps + g * RtsFlags.GcFlags.steps;
182 /* single generation, i.e. a two-space collector */
184 g0->steps = all_steps;
187 nurseries = stgMallocBytes (n_capabilities * sizeof(struct step_),
188 "initStorage: nurseries");
190 /* Initialise all steps */
191 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
192 for (s = 0; s < generations[g].n_steps; s++) {
193 initStep(&generations[g].steps[s], g, s);
197 for (s = 0; s < n_capabilities; s++) {
198 initStep(&nurseries[s], 0, s);
201 /* Set up the destination pointers in each younger gen. step */
202 for (g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
203 for (s = 0; s < generations[g].n_steps-1; s++) {
204 generations[g].steps[s].to = &generations[g].steps[s+1];
206 generations[g].steps[s].to = &generations[g+1].steps[0];
208 oldest_gen->steps[0].to = &oldest_gen->steps[0];
210 for (s = 0; s < n_capabilities; s++) {
211 nurseries[s].to = generations[0].steps[0].to;
214 /* The oldest generation has one step. */
215 if (RtsFlags.GcFlags.compact || RtsFlags.GcFlags.sweep) {
216 if (RtsFlags.GcFlags.generations == 1) {
217 errorBelch("WARNING: compact/sweep is incompatible with -G1; disabled");
219 oldest_gen->steps[0].mark = 1;
220 if (RtsFlags.GcFlags.compact)
221 oldest_gen->steps[0].compact = 1;
225 generations[0].max_blocks = 0;
227 /* The allocation area. Policy: keep the allocation area
228 * small to begin with, even if we have a large suggested heap
229 * size. Reason: we're going to do a major collection first, and we
230 * don't want it to be a big one. This vague idea is borne out by
231 * rigorous experimental evidence.
235 weak_ptr_list = NULL;
237 revertible_caf_list = NULL;
239 /* initialise the allocate() interface */
240 alloc_blocks_lim = RtsFlags.GcFlags.minAllocAreaSize;
245 initSpinLock(&gc_alloc_block_sync);
253 IF_DEBUG(gc, statDescribeGens());
261 stat_exit(calcAllocated());
267 stgFree(all_steps); // frees all the steps
268 stgFree(generations);
270 #if defined(THREADED_RTS)
271 closeMutex(&sm_mutex);
277 /* -----------------------------------------------------------------------------
280 The entry code for every CAF does the following:
282 - builds a CAF_BLACKHOLE in the heap
283 - pushes an update frame pointing to the CAF_BLACKHOLE
284 - invokes UPD_CAF(), which:
285 - calls newCaf, below
286 - updates the CAF with a static indirection to the CAF_BLACKHOLE
288 Why do we build a BLACKHOLE in the heap rather than just updating
289 the thunk directly? It's so that we only need one kind of update
290 frame - otherwise we'd need a static version of the update frame too.
292 newCaf() does the following:
294 - it puts the CAF on the oldest generation's mut-once list.
295 This is so that we can treat the CAF as a root when collecting
298 For GHCI, we have additional requirements when dealing with CAFs:
300 - we must *retain* all dynamically-loaded CAFs ever entered,
301 just in case we need them again.
302 - we must be able to *revert* CAFs that have been evaluated, to
303 their pre-evaluated form.
305 To do this, we use an additional CAF list. When newCaf() is
306 called on a dynamically-loaded CAF, we add it to the CAF list
307 instead of the old-generation mutable list, and save away its
308 old info pointer (in caf->saved_info) for later reversion.
310 To revert all the CAFs, we traverse the CAF list and reset the
311 info pointer to caf->saved_info, then throw away the CAF list.
312 (see GC.c:revertCAFs()).
316 -------------------------------------------------------------------------- */
319 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;
343 /* Put this CAF on the mutable list for the old generation.
344 * This is a HACK - the IND_STATIC closure doesn't really have
345 * a mut_link field, but we pretend it has - in fact we re-use
346 * the STATIC_LINK field for the time being, because when we
347 * come to do a major GC we won't need the mut_link field
348 * any more and can use it as a STATIC_LINK.
350 ((StgIndStatic *)caf)->saved_info = NULL;
351 recordMutableGen(caf, oldest_gen->no);
357 // An alternate version of newCaf which is used for dynamically loaded
358 // object code in GHCi. In this case we want to retain *all* CAFs in
359 // the object code, because they might be demanded at any time from an
360 // expression evaluated on the command line.
361 // Also, GHCi might want to revert CAFs, so we add these to the
362 // revertible_caf_list.
364 // The linker hackily arranges that references to newCaf from dynamic
365 // code end up pointing to newDynCAF.
367 newDynCAF(StgClosure *caf)
371 ((StgIndStatic *)caf)->saved_info = (StgInfoTable *)caf->header.info;
372 ((StgIndStatic *)caf)->static_link = revertible_caf_list;
373 revertible_caf_list = caf;
378 /* -----------------------------------------------------------------------------
380 -------------------------------------------------------------------------- */
383 allocNursery (step *stp, bdescr *tail, nat blocks)
388 // Allocate a nursery: we allocate fresh blocks one at a time and
389 // cons them on to the front of the list, not forgetting to update
390 // the back pointer on the tail of the list to point to the new block.
391 for (i=0; i < blocks; i++) {
394 processNursery() in LdvProfile.c assumes that every block group in
395 the nursery contains only a single block. So, if a block group is
396 given multiple blocks, change processNursery() accordingly.
400 // double-link the nursery: we might need to insert blocks
406 bd->free = bd->start;
414 assignNurseriesToCapabilities (void)
418 for (i = 0; i < n_capabilities; i++) {
419 capabilities[i].r.rNursery = &nurseries[i];
420 capabilities[i].r.rCurrentNursery = nurseries[i].blocks;
421 capabilities[i].r.rCurrentAlloc = NULL;
426 allocNurseries( void )
430 for (i = 0; i < n_capabilities; i++) {
431 nurseries[i].blocks =
432 allocNursery(&nurseries[i], NULL,
433 RtsFlags.GcFlags.minAllocAreaSize);
434 nurseries[i].n_blocks = RtsFlags.GcFlags.minAllocAreaSize;
435 nurseries[i].old_blocks = NULL;
436 nurseries[i].n_old_blocks = 0;
438 assignNurseriesToCapabilities();
442 resetNurseries( void )
448 for (i = 0; i < n_capabilities; i++) {
450 for (bd = stp->blocks; bd; bd = bd->link) {
451 bd->free = bd->start;
452 ASSERT(bd->gen_no == 0);
453 ASSERT(bd->step == stp);
454 IF_DEBUG(sanity,memset(bd->start, 0xaa, BLOCK_SIZE));
456 // these large objects are dead, since we have just GC'd
457 freeChain(stp->large_objects);
458 stp->large_objects = NULL;
459 stp->n_large_blocks = 0;
461 assignNurseriesToCapabilities();
465 countNurseryBlocks (void)
470 for (i = 0; i < n_capabilities; i++) {
471 blocks += nurseries[i].n_blocks;
472 blocks += nurseries[i].n_large_blocks;
478 resizeNursery ( step *stp, nat blocks )
483 nursery_blocks = stp->n_blocks;
484 if (nursery_blocks == blocks) return;
486 if (nursery_blocks < blocks) {
487 debugTrace(DEBUG_gc, "increasing size of nursery to %d blocks",
489 stp->blocks = allocNursery(stp, stp->blocks, blocks-nursery_blocks);
494 debugTrace(DEBUG_gc, "decreasing size of nursery to %d blocks",
498 while (nursery_blocks > blocks) {
500 next_bd->u.back = NULL;
501 nursery_blocks -= bd->blocks; // might be a large block
506 // might have gone just under, by freeing a large block, so make
507 // up the difference.
508 if (nursery_blocks < blocks) {
509 stp->blocks = allocNursery(stp, stp->blocks, blocks-nursery_blocks);
513 stp->n_blocks = blocks;
514 ASSERT(countBlocks(stp->blocks) == stp->n_blocks);
518 // Resize each of the nurseries to the specified size.
521 resizeNurseriesFixed (nat blocks)
524 for (i = 0; i < n_capabilities; i++) {
525 resizeNursery(&nurseries[i], blocks);
530 // Resize the nurseries to the total specified size.
533 resizeNurseries (nat blocks)
535 // If there are multiple nurseries, then we just divide the number
536 // of available blocks between them.
537 resizeNurseriesFixed(blocks / n_capabilities);
541 /* -----------------------------------------------------------------------------
542 move_TSO is called to update the TSO structure after it has been
543 moved from one place to another.
544 -------------------------------------------------------------------------- */
547 move_TSO (StgTSO *src, StgTSO *dest)
551 // relocate the stack pointer...
552 diff = (StgPtr)dest - (StgPtr)src; // In *words*
553 dest->sp = (StgPtr)dest->sp + diff;
556 /* -----------------------------------------------------------------------------
557 split N blocks off the front of the given bdescr, returning the
558 new block group. We add the remainder to the large_blocks list
559 in the same step as the original block.
560 -------------------------------------------------------------------------- */
563 splitLargeBlock (bdescr *bd, nat blocks)
569 ASSERT(countBlocks(bd->step->large_objects) == bd->step->n_large_blocks);
571 // subtract the original number of blocks from the counter first
572 bd->step->n_large_blocks -= bd->blocks;
574 new_bd = splitBlockGroup (bd, blocks);
575 initBdescr(new_bd, bd->step);
576 new_bd->flags = BF_LARGE | (bd->flags & BF_EVACUATED);
577 // if new_bd is in an old generation, we have to set BF_EVACUATED
578 new_bd->free = bd->free;
579 dbl_link_onto(new_bd, &bd->step->large_objects);
581 ASSERT(new_bd->free <= new_bd->start + new_bd->blocks * BLOCK_SIZE_W);
583 // add the new number of blocks to the counter. Due to the gaps
584 // for block descriptors, new_bd->blocks + bd->blocks might not be
585 // equal to the original bd->blocks, which is why we do it this way.
586 bd->step->n_large_blocks += bd->blocks + new_bd->blocks;
588 ASSERT(countBlocks(bd->step->large_objects) == bd->step->n_large_blocks);
595 /* -----------------------------------------------------------------------------
598 This allocates memory in the current thread - it is intended for
599 use primarily from STG-land where we have a Capability. It is
600 better than allocate() because it doesn't require taking the
601 sm_mutex lock in the common case.
603 Memory is allocated directly from the nursery if possible (but not
604 from the current nursery block, so as not to interfere with
606 -------------------------------------------------------------------------- */
609 allocate (Capability *cap, lnat n)
615 if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
616 lnat req_blocks = (lnat)BLOCK_ROUND_UP(n*sizeof(W_)) / BLOCK_SIZE;
618 // Attempting to allocate an object larger than maxHeapSize
619 // should definitely be disallowed. (bug #1791)
620 if (RtsFlags.GcFlags.maxHeapSize > 0 &&
621 req_blocks >= RtsFlags.GcFlags.maxHeapSize) {
623 // heapOverflow() doesn't exit (see #2592), but we aren't
624 // in a position to do a clean shutdown here: we
625 // either have to allocate the memory or exit now.
626 // Allocating the memory would be bad, because the user
627 // has requested that we not exceed maxHeapSize, so we
629 stg_exit(EXIT_HEAPOVERFLOW);
632 stp = &nurseries[cap->no];
634 bd = allocGroup(req_blocks);
635 dbl_link_onto(bd, &stp->large_objects);
636 stp->n_large_blocks += bd->blocks; // might be larger than req_blocks
638 bd->flags = BF_LARGE;
639 bd->free = bd->start + n;
643 /* small allocation (<LARGE_OBJECT_THRESHOLD) */
645 TICK_ALLOC_HEAP_NOCTR(n);
648 bd = cap->r.rCurrentAlloc;
649 if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
651 // The CurrentAlloc block is full, we need to find another
652 // one. First, we try taking the next block from the
654 bd = cap->r.rCurrentNursery->link;
656 if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
657 // The nursery is empty, or the next block is already
658 // full: allocate a fresh block (we can't fail here).
661 cap->r.rNursery->n_blocks++;
663 initBdescr(bd, cap->r.rNursery);
665 // If we had to allocate a new block, then we'll GC
666 // pretty quickly now, because MAYBE_GC() will
667 // notice that CurrentNursery->link is NULL.
669 // we have a block in the nursery: take it and put
670 // it at the *front* of the nursery list, and use it
671 // to allocate() from.
672 cap->r.rCurrentNursery->link = bd->link;
673 if (bd->link != NULL) {
674 bd->link->u.back = cap->r.rCurrentNursery;
677 dbl_link_onto(bd, &cap->r.rNursery->blocks);
678 cap->r.rCurrentAlloc = bd;
679 IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
686 /* ---------------------------------------------------------------------------
687 Allocate a fixed/pinned object.
689 We allocate small pinned objects into a single block, allocating a
690 new block when the current one overflows. The block is chained
691 onto the large_object_list of generation 0 step 0.
693 NOTE: The GC can't in general handle pinned objects. This
694 interface is only safe to use for ByteArrays, which have no
695 pointers and don't require scavenging. It works because the
696 block's descriptor has the BF_LARGE flag set, so the block is
697 treated as a large object and chained onto various lists, rather
698 than the individual objects being copied. However, when it comes
699 to scavenge the block, the GC will only scavenge the first object.
700 The reason is that the GC can't linearly scan a block of pinned
701 objects at the moment (doing so would require using the
702 mostly-copying techniques). But since we're restricting ourselves
703 to pinned ByteArrays, not scavenging is ok.
705 This function is called by newPinnedByteArray# which immediately
706 fills the allocated memory with a MutableByteArray#.
707 ------------------------------------------------------------------------- */
710 allocatePinned (Capability *cap, lnat n)
716 // If the request is for a large object, then allocate()
717 // will give us a pinned object anyway.
718 if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
719 p = allocate(cap, n);
720 Bdescr(p)->flags |= BF_PINNED;
724 TICK_ALLOC_HEAP_NOCTR(n);
727 bd = cap->pinned_object_block;
729 // If we don't have a block of pinned objects yet, or the current
730 // one isn't large enough to hold the new object, allocate a new one.
731 if (bd == NULL || (bd->free + n) > (bd->start + BLOCK_SIZE_W)) {
733 cap->pinned_object_block = bd = allocBlock();
735 stp = &nurseries[cap->no];
736 dbl_link_onto(bd, &stp->large_objects);
737 stp->n_large_blocks++;
739 bd->flags = BF_PINNED | BF_LARGE;
740 bd->free = bd->start;
748 /* -----------------------------------------------------------------------------
750 -------------------------------------------------------------------------- */
753 This is the write barrier for MUT_VARs, a.k.a. IORefs. A
754 MUT_VAR_CLEAN object is not on the mutable list; a MUT_VAR_DIRTY
755 is. When written to, a MUT_VAR_CLEAN turns into a MUT_VAR_DIRTY
756 and is put on the mutable list.
759 dirty_MUT_VAR(StgRegTable *reg, StgClosure *p)
761 Capability *cap = regTableToCapability(reg);
763 if (p->header.info == &stg_MUT_VAR_CLEAN_info) {
764 p->header.info = &stg_MUT_VAR_DIRTY_info;
765 bd = Bdescr((StgPtr)p);
766 if (bd->gen_no > 0) recordMutableCap(p,cap,bd->gen_no);
770 // Setting a TSO's link field with a write barrier.
771 // It is *not* necessary to call this function when
772 // * setting the link field to END_TSO_QUEUE
773 // * putting a TSO on the blackhole_queue
774 // * setting the link field of the currently running TSO, as it
775 // will already be dirty.
777 setTSOLink (Capability *cap, StgTSO *tso, StgTSO *target)
780 if (tso->dirty == 0 && (tso->flags & TSO_LINK_DIRTY) == 0) {
781 tso->flags |= TSO_LINK_DIRTY;
782 bd = Bdescr((StgPtr)tso);
783 if (bd->gen_no > 0) recordMutableCap((StgClosure*)tso,cap,bd->gen_no);
789 dirty_TSO (Capability *cap, StgTSO *tso)
792 if (tso->dirty == 0 && (tso->flags & TSO_LINK_DIRTY) == 0) {
793 bd = Bdescr((StgPtr)tso);
794 if (bd->gen_no > 0) recordMutableCap((StgClosure*)tso,cap,bd->gen_no);
800 This is the write barrier for MVARs. An MVAR_CLEAN objects is not
801 on the mutable list; a MVAR_DIRTY is. When written to, a
802 MVAR_CLEAN turns into a MVAR_DIRTY and is put on the mutable list.
803 The check for MVAR_CLEAN is inlined at the call site for speed,
804 this really does make a difference on concurrency-heavy benchmarks
805 such as Chaneneos and cheap-concurrency.
808 dirty_MVAR(StgRegTable *reg, StgClosure *p)
810 Capability *cap = regTableToCapability(reg);
812 bd = Bdescr((StgPtr)p);
813 if (bd->gen_no > 0) recordMutableCap(p,cap,bd->gen_no);
816 /* -----------------------------------------------------------------------------
818 * -------------------------------------------------------------------------- */
820 /* -----------------------------------------------------------------------------
823 * Approximate how much we've allocated: number of blocks in the
824 * nursery + blocks allocated via allocate() - unused nusery blocks.
825 * This leaves a little slop at the end of each block.
826 * -------------------------------------------------------------------------- */
829 calcAllocated( void )
835 allocated = countNurseryBlocks() * BLOCK_SIZE_W;
837 for (i = 0; i < n_capabilities; i++) {
839 for ( bd = capabilities[i].r.rCurrentNursery->link;
840 bd != NULL; bd = bd->link ) {
841 allocated -= BLOCK_SIZE_W;
843 cap = &capabilities[i];
844 if (cap->r.rCurrentNursery->free <
845 cap->r.rCurrentNursery->start + BLOCK_SIZE_W) {
846 allocated -= (cap->r.rCurrentNursery->start + BLOCK_SIZE_W)
847 - cap->r.rCurrentNursery->free;
849 if (cap->pinned_object_block != NULL) {
850 allocated -= (cap->pinned_object_block->start + BLOCK_SIZE_W) -
851 cap->pinned_object_block->free;
855 total_allocated += allocated;
859 /* Approximate the amount of live data in the heap. To be called just
860 * after garbage collection (see GarbageCollect()).
869 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
870 for (s = 0; s < generations[g].n_steps; s++) {
871 /* approximate amount of live data (doesn't take into account slop
872 * at end of each block).
874 if (g == 0 && s == 0 && RtsFlags.GcFlags.generations > 1) {
877 stp = &generations[g].steps[s];
878 live += stp->n_large_blocks + stp->n_blocks;
885 countOccupied(bdescr *bd)
890 for (; bd != NULL; bd = bd->link) {
891 ASSERT(bd->free <= bd->start + bd->blocks * BLOCK_SIZE_W);
892 words += bd->free - bd->start;
897 // Return an accurate count of the live data in the heap, excluding
907 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
908 for (s = 0; s < generations[g].n_steps; s++) {
909 if (g == 0 && s == 0 && RtsFlags.GcFlags.generations > 1) continue;
910 stp = &generations[g].steps[s];
911 live += stp->n_words + countOccupied(stp->large_objects);
917 /* Approximate the number of blocks that will be needed at the next
918 * garbage collection.
920 * Assume: all data currently live will remain live. Steps that will
921 * be collected next time will therefore need twice as many blocks
922 * since all the data will be copied.
931 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
932 for (s = 0; s < generations[g].n_steps; s++) {
933 if (g == 0 && s == 0) { continue; }
934 stp = &generations[g].steps[s];
936 // we need at least this much space
937 needed += stp->n_blocks + stp->n_large_blocks;
939 // any additional space needed to collect this gen next time?
940 if (g == 0 || // always collect gen 0
941 (generations[g].steps[0].n_blocks +
942 generations[g].steps[0].n_large_blocks
943 > generations[g].max_blocks)) {
944 // we will collect this gen next time
947 needed += stp->n_blocks / BITS_IN(W_);
949 needed += stp->n_blocks / 100;
952 continue; // no additional space needed for compaction
954 needed += stp->n_blocks;
962 /* ----------------------------------------------------------------------------
965 Executable memory must be managed separately from non-executable
966 memory. Most OSs these days require you to jump through hoops to
967 dynamically allocate executable memory, due to various security
970 Here we provide a small memory allocator for executable memory.
971 Memory is managed with a page granularity; we allocate linearly
972 in the page, and when the page is emptied (all objects on the page
973 are free) we free the page again, not forgetting to make it
976 TODO: The inability to handle objects bigger than BLOCK_SIZE_W means that
977 the linker cannot use allocateExec for loading object code files
978 on Windows. Once allocateExec can handle larger objects, the linker
979 should be modified to use allocateExec instead of VirtualAlloc.
980 ------------------------------------------------------------------------- */
982 #if defined(linux_HOST_OS)
984 // On Linux we need to use libffi for allocating executable memory,
985 // because it knows how to work around the restrictions put in place
988 void *allocateExec (nat bytes, void **exec_ret)
992 ret = ffi_closure_alloc (sizeof(void *) + (size_t)bytes, (void**)&exec);
994 if (ret == NULL) return ret;
995 *ret = ret; // save the address of the writable mapping, for freeExec().
996 *exec_ret = exec + 1;
1000 // freeExec gets passed the executable address, not the writable address.
1001 void freeExec (void *addr)
1004 writable = *((void**)addr - 1);
1006 ffi_closure_free (writable);
1012 void *allocateExec (nat bytes, void **exec_ret)
1019 // round up to words.
1020 n = (bytes + sizeof(W_) + 1) / sizeof(W_);
1022 if (n+1 > BLOCK_SIZE_W) {
1023 barf("allocateExec: can't handle large objects");
1026 if (exec_block == NULL ||
1027 exec_block->free + n + 1 > exec_block->start + BLOCK_SIZE_W) {
1029 lnat pagesize = getPageSize();
1030 bd = allocGroup(stg_max(1, pagesize / BLOCK_SIZE));
1031 debugTrace(DEBUG_gc, "allocate exec block %p", bd->start);
1033 bd->flags = BF_EXEC;
1034 bd->link = exec_block;
1035 if (exec_block != NULL) {
1036 exec_block->u.back = bd;
1039 setExecutable(bd->start, bd->blocks * BLOCK_SIZE, rtsTrue);
1042 *(exec_block->free) = n; // store the size of this chunk
1043 exec_block->gen_no += n; // gen_no stores the number of words allocated
1044 ret = exec_block->free + 1;
1045 exec_block->free += n + 1;
1052 void freeExec (void *addr)
1054 StgPtr p = (StgPtr)addr - 1;
1055 bdescr *bd = Bdescr((StgPtr)p);
1057 if ((bd->flags & BF_EXEC) == 0) {
1058 barf("freeExec: not executable");
1061 if (*(StgPtr)p == 0) {
1062 barf("freeExec: already free?");
1067 bd->gen_no -= *(StgPtr)p;
1070 if (bd->gen_no == 0) {
1071 // Free the block if it is empty, but not if it is the block at
1072 // the head of the queue.
1073 if (bd != exec_block) {
1074 debugTrace(DEBUG_gc, "free exec block %p", bd->start);
1075 dbl_link_remove(bd, &exec_block);
1076 setExecutable(bd->start, bd->blocks * BLOCK_SIZE, rtsFalse);
1079 bd->free = bd->start;
1086 #endif /* mingw32_HOST_OS */
1090 // handy function for use in gdb, because Bdescr() is inlined.
1091 extern bdescr *_bdescr( StgPtr p );