34cdab16ca6309ac9f6bfe016e7bfb670ec24b26
[ghc-hetmet.git] / rts / sm / Storage.c
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 1998-2008
4  *
5  * Storage manager front end
6  *
7  * Documentation on the architecture of the Storage Manager can be
8  * found in the online commentary:
9  * 
10  *   http://hackage.haskell.org/trac/ghc/wiki/Commentary/Rts/Storage
11  *
12  * ---------------------------------------------------------------------------*/
13
14 #include "PosixSource.h"
15 #include "Rts.h"
16
17 #include "Storage.h"
18 #include "RtsUtils.h"
19 #include "Stats.h"
20 #include "BlockAlloc.h"
21 #include "Weak.h"
22 #include "Sanity.h"
23 #include "Arena.h"
24 #include "Capability.h"
25 #include "Schedule.h"
26 #include "RetainerProfile.h"    // for counting memory blocks (memInventory)
27 #include "OSMem.h"
28 #include "Trace.h"
29 #include "GC.h"
30 #include "Evac.h"
31
32 #include <string.h>
33
34 #include "ffi.h"
35
36 /* 
37  * All these globals require sm_mutex to access in THREADED_RTS mode.
38  */
39 StgClosure    *caf_list         = NULL;
40 StgClosure    *revertible_caf_list = NULL;
41 rtsBool       keepCAFs;
42
43 nat alloc_blocks_lim;    /* GC if n_large_blocks in any nursery
44                           * reaches this. */
45
46 bdescr *exec_block;
47
48 generation *generations = NULL; /* all the generations */
49 generation *g0          = NULL; /* generation 0, for convenience */
50 generation *oldest_gen  = NULL; /* oldest generation, for convenience */
51
52 nursery *nurseries = NULL;     /* array of nurseries, size == n_capabilities */
53
54 #ifdef THREADED_RTS
55 /*
56  * Storage manager mutex:  protects all the above state from
57  * simultaneous access by two STG threads.
58  */
59 Mutex sm_mutex;
60 #endif
61
62 static void allocNurseries ( void );
63
64 static void
65 initGeneration (generation *gen, int g)
66 {
67     gen->no = g;
68     gen->collections = 0;
69     gen->par_collections = 0;
70     gen->failed_promotions = 0;
71     gen->max_blocks = 0;
72     gen->blocks = NULL;
73     gen->n_blocks = 0;
74     gen->n_words = 0;
75     gen->live_estimate = 0;
76     gen->old_blocks = NULL;
77     gen->n_old_blocks = 0;
78     gen->large_objects = NULL;
79     gen->n_large_blocks = 0;
80     gen->n_new_large_blocks = 0;
81     gen->mut_list = allocBlock();
82     gen->scavenged_large_objects = NULL;
83     gen->n_scavenged_large_blocks = 0;
84     gen->mark = 0;
85     gen->compact = 0;
86     gen->bitmap = NULL;
87 #ifdef THREADED_RTS
88     initSpinLock(&gen->sync_large_objects);
89 #endif
90     gen->threads = END_TSO_QUEUE;
91     gen->old_threads = END_TSO_QUEUE;
92 }
93
94 void
95 initStorage( void )
96 {
97     nat g, n;
98
99   if (generations != NULL) {
100       // multi-init protection
101       return;
102   }
103
104   initMBlocks();
105
106   /* Sanity check to make sure the LOOKS_LIKE_ macros appear to be
107    * doing something reasonable.
108    */
109   /* We use the NOT_NULL variant or gcc warns that the test is always true */
110   ASSERT(LOOKS_LIKE_INFO_PTR_NOT_NULL((StgWord)&stg_BLOCKING_QUEUE_CLEAN_info));
111   ASSERT(LOOKS_LIKE_CLOSURE_PTR(&stg_dummy_ret_closure));
112   ASSERT(!HEAP_ALLOCED(&stg_dummy_ret_closure));
113   
114   if (RtsFlags.GcFlags.maxHeapSize != 0 &&
115       RtsFlags.GcFlags.heapSizeSuggestion > 
116       RtsFlags.GcFlags.maxHeapSize) {
117     RtsFlags.GcFlags.maxHeapSize = RtsFlags.GcFlags.heapSizeSuggestion;
118   }
119
120   if (RtsFlags.GcFlags.maxHeapSize != 0 &&
121       RtsFlags.GcFlags.minAllocAreaSize > 
122       RtsFlags.GcFlags.maxHeapSize) {
123       errorBelch("maximum heap size (-M) is smaller than minimum alloc area size (-A)");
124       RtsFlags.GcFlags.minAllocAreaSize = RtsFlags.GcFlags.maxHeapSize;
125   }
126
127   initBlockAllocator();
128   
129 #if defined(THREADED_RTS)
130   initMutex(&sm_mutex);
131 #endif
132
133   ACQUIRE_SM_LOCK;
134
135   /* allocate generation info array */
136   generations = (generation *)stgMallocBytes(RtsFlags.GcFlags.generations 
137                                              * sizeof(struct generation_),
138                                              "initStorage: gens");
139
140   /* Initialise all generations */
141   for(g = 0; g < RtsFlags.GcFlags.generations; g++) {
142       initGeneration(&generations[g], g);
143   }
144
145   /* A couple of convenience pointers */
146   g0 = &generations[0];
147   oldest_gen = &generations[RtsFlags.GcFlags.generations-1];
148
149   nurseries = stgMallocBytes(n_capabilities * sizeof(struct nursery_),
150                              "initStorage: nurseries");
151   
152   /* Set up the destination pointers in each younger gen. step */
153   for (g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
154       generations[g].to = &generations[g+1];
155   }
156   oldest_gen->to = oldest_gen;
157   
158   /* The oldest generation has one step. */
159   if (RtsFlags.GcFlags.compact || RtsFlags.GcFlags.sweep) {
160       if (RtsFlags.GcFlags.generations == 1) {
161           errorBelch("WARNING: compact/sweep is incompatible with -G1; disabled");
162       } else {
163           oldest_gen->mark = 1;
164           if (RtsFlags.GcFlags.compact)
165               oldest_gen->compact = 1;
166       }
167   }
168
169   generations[0].max_blocks = 0;
170
171   /* The allocation area.  Policy: keep the allocation area
172    * small to begin with, even if we have a large suggested heap
173    * size.  Reason: we're going to do a major collection first, and we
174    * don't want it to be a big one.  This vague idea is borne out by 
175    * rigorous experimental evidence.
176    */
177   allocNurseries();
178
179   weak_ptr_list = NULL;
180   caf_list = END_OF_STATIC_LIST;
181   revertible_caf_list = END_OF_STATIC_LIST;
182    
183   /* initialise the allocate() interface */
184   alloc_blocks_lim = RtsFlags.GcFlags.minAllocAreaSize;
185
186   exec_block = NULL;
187
188 #ifdef THREADED_RTS
189   initSpinLock(&gc_alloc_block_sync);
190   whitehole_spin = 0;
191 #endif
192
193   N = 0;
194
195   // allocate a block for each mut list
196   for (n = 0; n < n_capabilities; n++) {
197       for (g = 1; g < RtsFlags.GcFlags.generations; g++) {
198           capabilities[n].mut_lists[g] = allocBlock();
199       }
200   }
201
202   initGcThreads();
203
204   IF_DEBUG(gc, statDescribeGens());
205
206   RELEASE_SM_LOCK;
207 }
208
209 void
210 exitStorage (void)
211 {
212     stat_exit(calcAllocated());
213 }
214
215 void
216 freeStorage (void)
217 {
218     stgFree(generations);
219     freeAllMBlocks();
220 #if defined(THREADED_RTS)
221     closeMutex(&sm_mutex);
222 #endif
223     stgFree(nurseries);
224     freeGcThreads();
225 }
226
227 /* -----------------------------------------------------------------------------
228    CAF management.
229
230    The entry code for every CAF does the following:
231      
232       - builds a BLACKHOLE in the heap
233       - pushes an update frame pointing to the BLACKHOLE
234       - calls newCaf, below
235       - updates the CAF with a static indirection to the BLACKHOLE
236       
237    Why do we build an BLACKHOLE in the heap rather than just updating
238    the thunk directly?  It's so that we only need one kind of update
239    frame - otherwise we'd need a static version of the update frame too.
240
241    newCaf() does the following:
242        
243       - it puts the CAF on the oldest generation's mutable list.
244         This is so that we treat the CAF as a root when collecting
245         younger generations.
246
247    For GHCI, we have additional requirements when dealing with CAFs:
248
249       - we must *retain* all dynamically-loaded CAFs ever entered,
250         just in case we need them again.
251       - we must be able to *revert* CAFs that have been evaluated, to
252         their pre-evaluated form.
253
254       To do this, we use an additional CAF list.  When newCaf() is
255       called on a dynamically-loaded CAF, we add it to the CAF list
256       instead of the old-generation mutable list, and save away its
257       old info pointer (in caf->saved_info) for later reversion.
258
259       To revert all the CAFs, we traverse the CAF list and reset the
260       info pointer to caf->saved_info, then throw away the CAF list.
261       (see GC.c:revertCAFs()).
262
263       -- SDM 29/1/01
264
265    -------------------------------------------------------------------------- */
266
267 void
268 newCAF(StgRegTable *reg, StgClosure* caf)
269 {
270   if(keepCAFs)
271   {
272     // HACK:
273     // If we are in GHCi _and_ we are using dynamic libraries,
274     // then we can't redirect newCAF calls to newDynCAF (see below),
275     // so we make newCAF behave almost like newDynCAF.
276     // The dynamic libraries might be used by both the interpreted
277     // program and GHCi itself, so they must not be reverted.
278     // This also means that in GHCi with dynamic libraries, CAFs are not
279     // garbage collected. If this turns out to be a problem, we could
280     // do another hack here and do an address range test on caf to figure
281     // out whether it is from a dynamic library.
282     ((StgIndStatic *)caf)->saved_info  = (StgInfoTable *)caf->header.info;
283
284     ACQUIRE_SM_LOCK; // caf_list is global, locked by sm_mutex
285     ((StgIndStatic *)caf)->static_link = caf_list;
286     caf_list = caf;
287     RELEASE_SM_LOCK;
288   }
289   else
290   {
291     // Put this CAF on the mutable list for the old generation.
292     ((StgIndStatic *)caf)->saved_info = NULL;
293     if (oldest_gen->no != 0) {
294         recordMutableCap(caf, regTableToCapability(reg), oldest_gen->no);
295     }
296   }
297 }
298
299 // External API for setting the keepCAFs flag. see #3900.
300 void
301 setKeepCAFs (void)
302 {
303     keepCAFs = 1;
304 }
305
306 // An alternate version of newCaf which is used for dynamically loaded
307 // object code in GHCi.  In this case we want to retain *all* CAFs in
308 // the object code, because they might be demanded at any time from an
309 // expression evaluated on the command line.
310 // Also, GHCi might want to revert CAFs, so we add these to the
311 // revertible_caf_list.
312 //
313 // The linker hackily arranges that references to newCaf from dynamic
314 // code end up pointing to newDynCAF.
315 void
316 newDynCAF (StgRegTable *reg STG_UNUSED, StgClosure *caf)
317 {
318     ACQUIRE_SM_LOCK;
319
320     ((StgIndStatic *)caf)->saved_info  = (StgInfoTable *)caf->header.info;
321     ((StgIndStatic *)caf)->static_link = revertible_caf_list;
322     revertible_caf_list = caf;
323
324     RELEASE_SM_LOCK;
325 }
326
327 /* -----------------------------------------------------------------------------
328    Nursery management.
329    -------------------------------------------------------------------------- */
330
331 static bdescr *
332 allocNursery (bdescr *tail, nat blocks)
333 {
334     bdescr *bd;
335     nat i;
336
337     // Allocate a nursery: we allocate fresh blocks one at a time and
338     // cons them on to the front of the list, not forgetting to update
339     // the back pointer on the tail of the list to point to the new block.
340     for (i=0; i < blocks; i++) {
341         // @LDV profiling
342         /*
343           processNursery() in LdvProfile.c assumes that every block group in
344           the nursery contains only a single block. So, if a block group is
345           given multiple blocks, change processNursery() accordingly.
346         */
347         bd = allocBlock();
348         bd->link = tail;
349         // double-link the nursery: we might need to insert blocks
350         if (tail != NULL) {
351             tail->u.back = bd;
352         }
353         initBdescr(bd, g0, g0);
354         bd->flags = 0;
355         bd->free = bd->start;
356         tail = bd;
357     }
358     tail->u.back = NULL;
359     return tail;
360 }
361
362 static void
363 assignNurseriesToCapabilities (void)
364 {
365     nat i;
366
367     for (i = 0; i < n_capabilities; i++) {
368         capabilities[i].r.rNursery        = &nurseries[i];
369         capabilities[i].r.rCurrentNursery = nurseries[i].blocks;
370         capabilities[i].r.rCurrentAlloc   = NULL;
371     }
372 }
373
374 static void
375 allocNurseries( void )
376
377     nat i;
378
379     for (i = 0; i < n_capabilities; i++) {
380         nurseries[i].blocks = 
381             allocNursery(NULL, RtsFlags.GcFlags.minAllocAreaSize);
382         nurseries[i].n_blocks =
383             RtsFlags.GcFlags.minAllocAreaSize;
384     }
385     assignNurseriesToCapabilities();
386 }
387       
388 void
389 resetNurseries( void )
390 {
391     nat i;
392     bdescr *bd;
393
394     for (i = 0; i < n_capabilities; i++) {
395         for (bd = nurseries[i].blocks; bd; bd = bd->link) {
396             bd->free = bd->start;
397             ASSERT(bd->gen_no == 0);
398             ASSERT(bd->gen == g0);
399             IF_DEBUG(sanity,memset(bd->start, 0xaa, BLOCK_SIZE));
400         }
401     }
402     assignNurseriesToCapabilities();
403 }
404
405 lnat
406 countNurseryBlocks (void)
407 {
408     nat i;
409     lnat blocks = 0;
410
411     for (i = 0; i < n_capabilities; i++) {
412         blocks += nurseries[i].n_blocks;
413     }
414     return blocks;
415 }
416
417 static void
418 resizeNursery ( nursery *nursery, nat blocks )
419 {
420   bdescr *bd;
421   nat nursery_blocks;
422
423   nursery_blocks = nursery->n_blocks;
424   if (nursery_blocks == blocks) return;
425
426   if (nursery_blocks < blocks) {
427       debugTrace(DEBUG_gc, "increasing size of nursery to %d blocks", 
428                  blocks);
429     nursery->blocks = allocNursery(nursery->blocks, blocks-nursery_blocks);
430   } 
431   else {
432     bdescr *next_bd;
433     
434     debugTrace(DEBUG_gc, "decreasing size of nursery to %d blocks", 
435                blocks);
436
437     bd = nursery->blocks;
438     while (nursery_blocks > blocks) {
439         next_bd = bd->link;
440         next_bd->u.back = NULL;
441         nursery_blocks -= bd->blocks; // might be a large block
442         freeGroup(bd);
443         bd = next_bd;
444     }
445     nursery->blocks = bd;
446     // might have gone just under, by freeing a large block, so make
447     // up the difference.
448     if (nursery_blocks < blocks) {
449         nursery->blocks = allocNursery(nursery->blocks, blocks-nursery_blocks);
450     }
451   }
452   
453   nursery->n_blocks = blocks;
454   ASSERT(countBlocks(nursery->blocks) == nursery->n_blocks);
455 }
456
457 // 
458 // Resize each of the nurseries to the specified size.
459 //
460 void
461 resizeNurseriesFixed (nat blocks)
462 {
463     nat i;
464     for (i = 0; i < n_capabilities; i++) {
465         resizeNursery(&nurseries[i], blocks);
466     }
467 }
468
469 // 
470 // Resize the nurseries to the total specified size.
471 //
472 void
473 resizeNurseries (nat blocks)
474 {
475     // If there are multiple nurseries, then we just divide the number
476     // of available blocks between them.
477     resizeNurseriesFixed(blocks / n_capabilities);
478 }
479
480
481 /* -----------------------------------------------------------------------------
482    move_TSO is called to update the TSO structure after it has been
483    moved from one place to another.
484    -------------------------------------------------------------------------- */
485
486 void
487 move_TSO (StgTSO *src, StgTSO *dest)
488 {
489     ptrdiff_t diff;
490
491     // relocate the stack pointer... 
492     diff = (StgPtr)dest - (StgPtr)src; // In *words* 
493     dest->sp = (StgPtr)dest->sp + diff;
494 }
495
496 /* -----------------------------------------------------------------------------
497    split N blocks off the front of the given bdescr, returning the
498    new block group.  We add the remainder to the large_blocks list
499    in the same step as the original block.
500    -------------------------------------------------------------------------- */
501
502 bdescr *
503 splitLargeBlock (bdescr *bd, nat blocks)
504 {
505     bdescr *new_bd;
506
507     ACQUIRE_SM_LOCK;
508
509     ASSERT(countBlocks(bd->gen->large_objects) == bd->gen->n_large_blocks);
510
511     // subtract the original number of blocks from the counter first
512     bd->gen->n_large_blocks -= bd->blocks;
513
514     new_bd = splitBlockGroup (bd, blocks);
515     initBdescr(new_bd, bd->gen, bd->gen->to);
516     new_bd->flags   = BF_LARGE | (bd->flags & BF_EVACUATED); 
517     // if new_bd is in an old generation, we have to set BF_EVACUATED
518     new_bd->free    = bd->free;
519     dbl_link_onto(new_bd, &bd->gen->large_objects);
520
521     ASSERT(new_bd->free <= new_bd->start + new_bd->blocks * BLOCK_SIZE_W);
522
523     // add the new number of blocks to the counter.  Due to the gaps
524     // for block descriptors, new_bd->blocks + bd->blocks might not be
525     // equal to the original bd->blocks, which is why we do it this way.
526     bd->gen->n_large_blocks += bd->blocks + new_bd->blocks;
527
528     ASSERT(countBlocks(bd->gen->large_objects) == bd->gen->n_large_blocks);
529
530     RELEASE_SM_LOCK;
531
532     return new_bd;
533 }
534
535 /* -----------------------------------------------------------------------------
536    allocate()
537
538    This allocates memory in the current thread - it is intended for
539    use primarily from STG-land where we have a Capability.  It is
540    better than allocate() because it doesn't require taking the
541    sm_mutex lock in the common case.
542
543    Memory is allocated directly from the nursery if possible (but not
544    from the current nursery block, so as not to interfere with
545    Hp/HpLim).
546    -------------------------------------------------------------------------- */
547
548 StgPtr
549 allocate (Capability *cap, lnat n)
550 {
551     bdescr *bd;
552     StgPtr p;
553
554     if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
555         lnat req_blocks =  (lnat)BLOCK_ROUND_UP(n*sizeof(W_)) / BLOCK_SIZE;
556
557         // Attempting to allocate an object larger than maxHeapSize
558         // should definitely be disallowed.  (bug #1791)
559         if (RtsFlags.GcFlags.maxHeapSize > 0 && 
560             req_blocks >= RtsFlags.GcFlags.maxHeapSize) {
561             heapOverflow();
562             // heapOverflow() doesn't exit (see #2592), but we aren't
563             // in a position to do a clean shutdown here: we
564             // either have to allocate the memory or exit now.
565             // Allocating the memory would be bad, because the user
566             // has requested that we not exceed maxHeapSize, so we
567             // just exit.
568             stg_exit(EXIT_HEAPOVERFLOW);
569         }
570
571         ACQUIRE_SM_LOCK
572         bd = allocGroup(req_blocks);
573         dbl_link_onto(bd, &g0->large_objects);
574         g0->n_large_blocks += bd->blocks; // might be larger than req_blocks
575         g0->n_new_large_blocks += bd->blocks;
576         RELEASE_SM_LOCK;
577         initBdescr(bd, g0, g0);
578         bd->flags = BF_LARGE;
579         bd->free = bd->start + n;
580         return bd->start;
581     }
582
583     /* small allocation (<LARGE_OBJECT_THRESHOLD) */
584
585     TICK_ALLOC_HEAP_NOCTR(n);
586     CCS_ALLOC(CCCS,n);
587     
588     bd = cap->r.rCurrentAlloc;
589     if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
590         
591         // The CurrentAlloc block is full, we need to find another
592         // one.  First, we try taking the next block from the
593         // nursery:
594         bd = cap->r.rCurrentNursery->link;
595         
596         if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
597             // The nursery is empty, or the next block is already
598             // full: allocate a fresh block (we can't fail here).
599             ACQUIRE_SM_LOCK;
600             bd = allocBlock();
601             cap->r.rNursery->n_blocks++;
602             RELEASE_SM_LOCK;
603             initBdescr(bd, g0, g0);
604             bd->flags = 0;
605             // If we had to allocate a new block, then we'll GC
606             // pretty quickly now, because MAYBE_GC() will
607             // notice that CurrentNursery->link is NULL.
608         } else {
609             // we have a block in the nursery: take it and put
610             // it at the *front* of the nursery list, and use it
611             // to allocate() from.
612             cap->r.rCurrentNursery->link = bd->link;
613             if (bd->link != NULL) {
614                 bd->link->u.back = cap->r.rCurrentNursery;
615             }
616         }
617         dbl_link_onto(bd, &cap->r.rNursery->blocks);
618         cap->r.rCurrentAlloc = bd;
619         IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
620     }
621     p = bd->free;
622     bd->free += n;
623
624     IF_DEBUG(sanity, ASSERT(*((StgWord8*)p) == 0xaa));
625     return p;
626 }
627
628 /* ---------------------------------------------------------------------------
629    Allocate a fixed/pinned object.
630
631    We allocate small pinned objects into a single block, allocating a
632    new block when the current one overflows.  The block is chained
633    onto the large_object_list of generation 0.
634
635    NOTE: The GC can't in general handle pinned objects.  This
636    interface is only safe to use for ByteArrays, which have no
637    pointers and don't require scavenging.  It works because the
638    block's descriptor has the BF_LARGE flag set, so the block is
639    treated as a large object and chained onto various lists, rather
640    than the individual objects being copied.  However, when it comes
641    to scavenge the block, the GC will only scavenge the first object.
642    The reason is that the GC can't linearly scan a block of pinned
643    objects at the moment (doing so would require using the
644    mostly-copying techniques).  But since we're restricting ourselves
645    to pinned ByteArrays, not scavenging is ok.
646
647    This function is called by newPinnedByteArray# which immediately
648    fills the allocated memory with a MutableByteArray#.
649    ------------------------------------------------------------------------- */
650
651 StgPtr
652 allocatePinned (Capability *cap, lnat n)
653 {
654     StgPtr p;
655     bdescr *bd;
656
657     // If the request is for a large object, then allocate()
658     // will give us a pinned object anyway.
659     if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
660         p = allocate(cap, n);
661         Bdescr(p)->flags |= BF_PINNED;
662         return p;
663     }
664
665     TICK_ALLOC_HEAP_NOCTR(n);
666     CCS_ALLOC(CCCS,n);
667
668     bd = cap->pinned_object_block;
669     
670     // If we don't have a block of pinned objects yet, or the current
671     // one isn't large enough to hold the new object, allocate a new one.
672     if (bd == NULL || (bd->free + n) > (bd->start + BLOCK_SIZE_W)) {
673         ACQUIRE_SM_LOCK;
674         cap->pinned_object_block = bd = allocBlock();
675         dbl_link_onto(bd, &g0->large_objects);
676         g0->n_large_blocks++;
677         g0->n_new_large_blocks++;
678         RELEASE_SM_LOCK;
679         initBdescr(bd, g0, g0);
680         bd->flags  = BF_PINNED | BF_LARGE;
681         bd->free   = bd->start;
682     }
683
684     p = bd->free;
685     bd->free += n;
686     return p;
687 }
688
689 /* -----------------------------------------------------------------------------
690    Write Barriers
691    -------------------------------------------------------------------------- */
692
693 /*
694    This is the write barrier for MUT_VARs, a.k.a. IORefs.  A
695    MUT_VAR_CLEAN object is not on the mutable list; a MUT_VAR_DIRTY
696    is.  When written to, a MUT_VAR_CLEAN turns into a MUT_VAR_DIRTY
697    and is put on the mutable list.
698 */
699 void
700 dirty_MUT_VAR(StgRegTable *reg, StgClosure *p)
701 {
702     Capability *cap = regTableToCapability(reg);
703     if (p->header.info == &stg_MUT_VAR_CLEAN_info) {
704         p->header.info = &stg_MUT_VAR_DIRTY_info;
705         recordClosureMutated(cap,p);
706     }
707 }
708
709 // Setting a TSO's link field with a write barrier.
710 // It is *not* necessary to call this function when
711 //    * setting the link field to END_TSO_QUEUE
712 //    * putting a TSO on the blackhole_queue
713 //    * setting the link field of the currently running TSO, as it
714 //      will already be dirty.
715 void
716 setTSOLink (Capability *cap, StgTSO *tso, StgTSO *target)
717 {
718     if (tso->dirty == 0 && (tso->flags & TSO_LINK_DIRTY) == 0) {
719         tso->flags |= TSO_LINK_DIRTY;
720         recordClosureMutated(cap,(StgClosure*)tso);
721     }
722     tso->_link = target;
723 }
724
725 void
726 setTSOPrev (Capability *cap, StgTSO *tso, StgTSO *target)
727 {
728     if (tso->dirty == 0 && (tso->flags & TSO_LINK_DIRTY) == 0) {
729         tso->flags |= TSO_LINK_DIRTY;
730         recordClosureMutated(cap,(StgClosure*)tso);
731     }
732     tso->block_info.prev = target;
733 }
734
735 void
736 dirty_TSO (Capability *cap, StgTSO *tso)
737 {
738     if (tso->dirty == 0 && (tso->flags & TSO_LINK_DIRTY) == 0) {
739         recordClosureMutated(cap,(StgClosure*)tso);
740     }
741     tso->dirty = 1;
742 }
743
744 /*
745    This is the write barrier for MVARs.  An MVAR_CLEAN objects is not
746    on the mutable list; a MVAR_DIRTY is.  When written to, a
747    MVAR_CLEAN turns into a MVAR_DIRTY and is put on the mutable list.
748    The check for MVAR_CLEAN is inlined at the call site for speed,
749    this really does make a difference on concurrency-heavy benchmarks
750    such as Chaneneos and cheap-concurrency.
751 */
752 void
753 dirty_MVAR(StgRegTable *reg, StgClosure *p)
754 {
755     recordClosureMutated(regTableToCapability(reg),p);
756 }
757
758 /* -----------------------------------------------------------------------------
759  * Stats and stuff
760  * -------------------------------------------------------------------------- */
761
762 /* -----------------------------------------------------------------------------
763  * calcAllocated()
764  *
765  * Approximate how much we've allocated: number of blocks in the
766  * nursery + blocks allocated via allocate() - unused nusery blocks.
767  * This leaves a little slop at the end of each block.
768  * -------------------------------------------------------------------------- */
769
770 lnat
771 calcAllocated( void )
772 {
773   nat allocated;
774   bdescr *bd;
775   nat i;
776
777   allocated = countNurseryBlocks() * BLOCK_SIZE_W;
778   
779   for (i = 0; i < n_capabilities; i++) {
780       Capability *cap;
781       for ( bd = capabilities[i].r.rCurrentNursery->link; 
782             bd != NULL; bd = bd->link ) {
783           allocated -= BLOCK_SIZE_W;
784       }
785       cap = &capabilities[i];
786       if (cap->r.rCurrentNursery->free < 
787           cap->r.rCurrentNursery->start + BLOCK_SIZE_W) {
788           allocated -= (cap->r.rCurrentNursery->start + BLOCK_SIZE_W)
789               - cap->r.rCurrentNursery->free;
790       }
791       if (cap->pinned_object_block != NULL) {
792           allocated -= (cap->pinned_object_block->start + BLOCK_SIZE_W) - 
793               cap->pinned_object_block->free;
794       }
795   }
796
797   allocated += g0->n_new_large_blocks * BLOCK_SIZE_W;
798
799   return allocated;
800 }  
801
802 /* Approximate the amount of live data in the heap.  To be called just
803  * after garbage collection (see GarbageCollect()).
804  */
805 lnat calcLiveBlocks (void)
806 {
807   nat g;
808   lnat live = 0;
809   generation *gen;
810
811   for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
812       /* approximate amount of live data (doesn't take into account slop
813        * at end of each block).
814        */
815       gen = &generations[g];
816       live += gen->n_large_blocks + gen->n_blocks;
817   }
818   return live;
819 }
820
821 lnat countOccupied (bdescr *bd)
822 {
823     lnat words;
824
825     words = 0;
826     for (; bd != NULL; bd = bd->link) {
827         ASSERT(bd->free <= bd->start + bd->blocks * BLOCK_SIZE_W);
828         words += bd->free - bd->start;
829     }
830     return words;
831 }
832
833 // Return an accurate count of the live data in the heap, excluding
834 // generation 0.
835 lnat calcLiveWords (void)
836 {
837     nat g;
838     lnat live;
839     generation *gen;
840     
841     live = 0;
842     for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
843         gen = &generations[g];
844         live += gen->n_words + countOccupied(gen->large_objects);
845     }
846     return live;
847 }
848
849 /* Approximate the number of blocks that will be needed at the next
850  * garbage collection.
851  *
852  * Assume: all data currently live will remain live.  Generationss
853  * that will be collected next time will therefore need twice as many
854  * blocks since all the data will be copied.
855  */
856 extern lnat 
857 calcNeeded(void)
858 {
859     lnat needed = 0;
860     nat g;
861     generation *gen;
862     
863     for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
864         gen = &generations[g];
865
866         // we need at least this much space
867         needed += gen->n_blocks + gen->n_large_blocks;
868         
869         // any additional space needed to collect this gen next time?
870         if (g == 0 || // always collect gen 0
871             (gen->n_blocks + gen->n_large_blocks > gen->max_blocks)) {
872             // we will collect this gen next time
873             if (gen->mark) {
874                 //  bitmap:
875                 needed += gen->n_blocks / BITS_IN(W_);
876                 //  mark stack:
877                 needed += gen->n_blocks / 100;
878             }
879             if (gen->compact) {
880                 continue; // no additional space needed for compaction
881             } else {
882                 needed += gen->n_blocks;
883             }
884         }
885     }
886     return needed;
887 }
888
889 /* ----------------------------------------------------------------------------
890    Executable memory
891
892    Executable memory must be managed separately from non-executable
893    memory.  Most OSs these days require you to jump through hoops to
894    dynamically allocate executable memory, due to various security
895    measures.
896
897    Here we provide a small memory allocator for executable memory.
898    Memory is managed with a page granularity; we allocate linearly
899    in the page, and when the page is emptied (all objects on the page
900    are free) we free the page again, not forgetting to make it
901    non-executable.
902
903    TODO: The inability to handle objects bigger than BLOCK_SIZE_W means that
904          the linker cannot use allocateExec for loading object code files
905          on Windows. Once allocateExec can handle larger objects, the linker
906          should be modified to use allocateExec instead of VirtualAlloc.
907    ------------------------------------------------------------------------- */
908
909 #if defined(linux_HOST_OS)
910
911 // On Linux we need to use libffi for allocating executable memory,
912 // because it knows how to work around the restrictions put in place
913 // by SELinux.
914
915 void *allocateExec (nat bytes, void **exec_ret)
916 {
917     void **ret, **exec;
918     ACQUIRE_SM_LOCK;
919     ret = ffi_closure_alloc (sizeof(void *) + (size_t)bytes, (void**)&exec);
920     RELEASE_SM_LOCK;
921     if (ret == NULL) return ret;
922     *ret = ret; // save the address of the writable mapping, for freeExec().
923     *exec_ret = exec + 1;
924     return (ret + 1);
925 }
926
927 // freeExec gets passed the executable address, not the writable address. 
928 void freeExec (void *addr)
929 {
930     void *writable;
931     writable = *((void**)addr - 1);
932     ACQUIRE_SM_LOCK;
933     ffi_closure_free (writable);
934     RELEASE_SM_LOCK
935 }
936
937 #else
938
939 void *allocateExec (nat bytes, void **exec_ret)
940 {
941     void *ret;
942     nat n;
943
944     ACQUIRE_SM_LOCK;
945
946     // round up to words.
947     n  = (bytes + sizeof(W_) + 1) / sizeof(W_);
948
949     if (n+1 > BLOCK_SIZE_W) {
950         barf("allocateExec: can't handle large objects");
951     }
952
953     if (exec_block == NULL || 
954         exec_block->free + n + 1 > exec_block->start + BLOCK_SIZE_W) {
955         bdescr *bd;
956         lnat pagesize = getPageSize();
957         bd = allocGroup(stg_max(1, pagesize / BLOCK_SIZE));
958         debugTrace(DEBUG_gc, "allocate exec block %p", bd->start);
959         bd->gen_no = 0;
960         bd->flags = BF_EXEC;
961         bd->link = exec_block;
962         if (exec_block != NULL) {
963             exec_block->u.back = bd;
964         }
965         bd->u.back = NULL;
966         setExecutable(bd->start, bd->blocks * BLOCK_SIZE, rtsTrue);
967         exec_block = bd;
968     }
969     *(exec_block->free) = n;  // store the size of this chunk
970     exec_block->gen_no += n;  // gen_no stores the number of words allocated
971     ret = exec_block->free + 1;
972     exec_block->free += n + 1;
973
974     RELEASE_SM_LOCK
975     *exec_ret = ret;
976     return ret;
977 }
978
979 void freeExec (void *addr)
980 {
981     StgPtr p = (StgPtr)addr - 1;
982     bdescr *bd = Bdescr((StgPtr)p);
983
984     if ((bd->flags & BF_EXEC) == 0) {
985         barf("freeExec: not executable");
986     }
987
988     if (*(StgPtr)p == 0) {
989         barf("freeExec: already free?");
990     }
991
992     ACQUIRE_SM_LOCK;
993
994     bd->gen_no -= *(StgPtr)p;
995     *(StgPtr)p = 0;
996
997     if (bd->gen_no == 0) {
998         // Free the block if it is empty, but not if it is the block at
999         // the head of the queue.
1000         if (bd != exec_block) {
1001             debugTrace(DEBUG_gc, "free exec block %p", bd->start);
1002             dbl_link_remove(bd, &exec_block);
1003             setExecutable(bd->start, bd->blocks * BLOCK_SIZE, rtsFalse);
1004             freeGroup(bd);
1005         } else {
1006             bd->free = bd->start;
1007         }
1008     }
1009
1010     RELEASE_SM_LOCK
1011 }    
1012
1013 #endif /* mingw32_HOST_OS */
1014
1015 #ifdef DEBUG
1016
1017 // handy function for use in gdb, because Bdescr() is inlined.
1018 extern bdescr *_bdescr( StgPtr p );
1019
1020 bdescr *
1021 _bdescr( StgPtr p )
1022 {
1023     return Bdescr(p);
1024 }
1025
1026 #endif