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