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