merge up to ghc HEAD 16-Apr-2011
[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 "GCThread.h"
19 #include "RtsUtils.h"
20 #include "Stats.h"
21 #include "BlockAlloc.h"
22 #include "Weak.h"
23 #include "Sanity.h"
24 #include "Arena.h"
25 #include "Capability.h"
26 #include "Schedule.h"
27 #include "RetainerProfile.h"    // for counting memory blocks (memInventory)
28 #include "OSMem.h"
29 #include "Trace.h"
30 #include "GC.h"
31 #include "Evac.h"
32
33 #include <string.h>
34
35 #include "ffi.h"
36
37 /* 
38  * All these globals require sm_mutex to access in THREADED_RTS mode.
39  */
40 StgClosure    *caf_list         = NULL;
41 StgClosure    *revertible_caf_list = NULL;
42 rtsBool       keepCAFs;
43
44 nat large_alloc_lim;    /* GC if n_large_blocks in any nursery
45                          * reaches this. */
46
47 bdescr *exec_block;
48
49 generation *generations = NULL; /* all the generations */
50 generation *g0          = NULL; /* generation 0, for convenience */
51 generation *oldest_gen  = NULL; /* oldest generation, for convenience */
52
53 nursery *nurseries = NULL;     /* array of nurseries, size == n_capabilities */
54
55 #ifdef THREADED_RTS
56 /*
57  * Storage manager mutex:  protects all the above state from
58  * simultaneous access by two STG threads.
59  */
60 Mutex sm_mutex;
61 #endif
62
63 static void allocNurseries ( void );
64
65 static void
66 initGeneration (generation *gen, int g)
67 {
68     gen->no = g;
69     gen->collections = 0;
70     gen->par_collections = 0;
71     gen->failed_promotions = 0;
72     gen->max_blocks = 0;
73     gen->blocks = NULL;
74     gen->n_blocks = 0;
75     gen->n_words = 0;
76     gen->live_estimate = 0;
77     gen->old_blocks = NULL;
78     gen->n_old_blocks = 0;
79     gen->large_objects = NULL;
80     gen->n_large_blocks = 0;
81     gen->n_new_large_words = 0;
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);
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   large_alloc_lim = RtsFlags.GcFlags.minAllocAreaSize * BLOCK_SIZE_W;
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(rtsTrue));
213 }
214
215 void
216 freeStorage (rtsBool free_heap)
217 {
218     stgFree(generations);
219     if (free_heap) 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 = NULL;
335     nat i, n;
336
337     // We allocate the nursery as a single contiguous block and then
338     // divide it into single blocks manually.  This way we guarantee
339     // that the nursery blocks are adjacent, so that the processor's
340     // automatic prefetching works across nursery blocks.  This is a
341     // tiny optimisation (~0.5%), but it's free.
342
343     while (blocks > 0) {
344         n = stg_min(blocks, BLOCKS_PER_MBLOCK);
345         blocks -= n;
346
347         bd = allocGroup(n);
348         for (i = 0; i < n; i++) {
349             initBdescr(&bd[i], g0, g0);
350
351             bd[i].blocks = 1;
352             bd[i].flags = 0;
353
354             if (i > 0) {
355                 bd[i].u.back = &bd[i-1];
356             } else {
357                 bd[i].u.back = NULL;
358             }
359
360             if (i+1 < n) {
361                 bd[i].link = &bd[i+1];
362             } else {
363                 bd[i].link = tail;
364                 if (tail != NULL) {
365                     tail->u.back = &bd[i];
366                 }
367             }
368
369             bd[i].free = bd[i].start;
370         }
371
372         tail = &bd[0];
373     }
374
375     return &bd[0];
376 }
377
378 static void
379 assignNurseriesToCapabilities (void)
380 {
381     nat i;
382
383     for (i = 0; i < n_capabilities; i++) {
384         capabilities[i].r.rNursery        = &nurseries[i];
385         capabilities[i].r.rCurrentNursery = nurseries[i].blocks;
386         capabilities[i].r.rCurrentAlloc   = NULL;
387     }
388 }
389
390 static void
391 allocNurseries( void )
392
393     nat i;
394
395     for (i = 0; i < n_capabilities; i++) {
396         nurseries[i].blocks = 
397             allocNursery(NULL, RtsFlags.GcFlags.minAllocAreaSize);
398         nurseries[i].n_blocks =
399             RtsFlags.GcFlags.minAllocAreaSize;
400     }
401     assignNurseriesToCapabilities();
402 }
403       
404 lnat // words allocated
405 clearNurseries (void)
406 {
407     lnat allocated = 0;
408     nat i;
409     bdescr *bd;
410
411     for (i = 0; i < n_capabilities; i++) {
412         for (bd = nurseries[i].blocks; bd; bd = bd->link) {
413             allocated += (lnat)(bd->free - bd->start);
414             bd->free = bd->start;
415             ASSERT(bd->gen_no == 0);
416             ASSERT(bd->gen == g0);
417             IF_DEBUG(sanity,memset(bd->start, 0xaa, BLOCK_SIZE));
418         }
419     }
420
421     return allocated;
422 }
423
424 void
425 resetNurseries (void)
426 {
427     assignNurseriesToCapabilities();
428
429 }
430
431 lnat
432 countNurseryBlocks (void)
433 {
434     nat i;
435     lnat blocks = 0;
436
437     for (i = 0; i < n_capabilities; i++) {
438         blocks += nurseries[i].n_blocks;
439     }
440     return blocks;
441 }
442
443 static void
444 resizeNursery ( nursery *nursery, nat blocks )
445 {
446   bdescr *bd;
447   nat nursery_blocks;
448
449   nursery_blocks = nursery->n_blocks;
450   if (nursery_blocks == blocks) return;
451
452   if (nursery_blocks < blocks) {
453       debugTrace(DEBUG_gc, "increasing size of nursery to %d blocks", 
454                  blocks);
455     nursery->blocks = allocNursery(nursery->blocks, blocks-nursery_blocks);
456   } 
457   else {
458     bdescr *next_bd;
459     
460     debugTrace(DEBUG_gc, "decreasing size of nursery to %d blocks", 
461                blocks);
462
463     bd = nursery->blocks;
464     while (nursery_blocks > blocks) {
465         next_bd = bd->link;
466         next_bd->u.back = NULL;
467         nursery_blocks -= bd->blocks; // might be a large block
468         freeGroup(bd);
469         bd = next_bd;
470     }
471     nursery->blocks = bd;
472     // might have gone just under, by freeing a large block, so make
473     // up the difference.
474     if (nursery_blocks < blocks) {
475         nursery->blocks = allocNursery(nursery->blocks, blocks-nursery_blocks);
476     }
477   }
478   
479   nursery->n_blocks = blocks;
480   ASSERT(countBlocks(nursery->blocks) == nursery->n_blocks);
481 }
482
483 // 
484 // Resize each of the nurseries to the specified size.
485 //
486 void
487 resizeNurseriesFixed (nat blocks)
488 {
489     nat i;
490     for (i = 0; i < n_capabilities; i++) {
491         resizeNursery(&nurseries[i], blocks);
492     }
493 }
494
495 // 
496 // Resize the nurseries to the total specified size.
497 //
498 void
499 resizeNurseries (nat blocks)
500 {
501     // If there are multiple nurseries, then we just divide the number
502     // of available blocks between them.
503     resizeNurseriesFixed(blocks / n_capabilities);
504 }
505
506
507 /* -----------------------------------------------------------------------------
508    move_STACK is called to update the TSO structure after it has been
509    moved from one place to another.
510    -------------------------------------------------------------------------- */
511
512 void
513 move_STACK (StgStack *src, StgStack *dest)
514 {
515     ptrdiff_t diff;
516
517     // relocate the stack pointer... 
518     diff = (StgPtr)dest - (StgPtr)src; // In *words* 
519     dest->sp = (StgPtr)dest->sp + diff;
520 }
521
522 /* -----------------------------------------------------------------------------
523    allocate()
524
525    This allocates memory in the current thread - it is intended for
526    use primarily from STG-land where we have a Capability.  It is
527    better than allocate() because it doesn't require taking the
528    sm_mutex lock in the common case.
529
530    Memory is allocated directly from the nursery if possible (but not
531    from the current nursery block, so as not to interfere with
532    Hp/HpLim).
533    -------------------------------------------------------------------------- */
534
535 StgPtr
536 allocate (Capability *cap, lnat n)
537 {
538     bdescr *bd;
539     StgPtr p;
540
541     if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
542         lnat req_blocks =  (lnat)BLOCK_ROUND_UP(n*sizeof(W_)) / BLOCK_SIZE;
543
544         // Attempting to allocate an object larger than maxHeapSize
545         // should definitely be disallowed.  (bug #1791)
546         if (RtsFlags.GcFlags.maxHeapSize > 0 && 
547             req_blocks >= RtsFlags.GcFlags.maxHeapSize) {
548             heapOverflow();
549             // heapOverflow() doesn't exit (see #2592), but we aren't
550             // in a position to do a clean shutdown here: we
551             // either have to allocate the memory or exit now.
552             // Allocating the memory would be bad, because the user
553             // has requested that we not exceed maxHeapSize, so we
554             // just exit.
555             stg_exit(EXIT_HEAPOVERFLOW);
556         }
557
558         ACQUIRE_SM_LOCK
559         bd = allocGroup(req_blocks);
560         dbl_link_onto(bd, &g0->large_objects);
561         g0->n_large_blocks += bd->blocks; // might be larger than req_blocks
562         g0->n_new_large_words += n;
563         RELEASE_SM_LOCK;
564         initBdescr(bd, g0, g0);
565         bd->flags = BF_LARGE;
566         bd->free = bd->start + n;
567         return bd->start;
568     }
569
570     /* small allocation (<LARGE_OBJECT_THRESHOLD) */
571
572     TICK_ALLOC_HEAP_NOCTR(n);
573     CCS_ALLOC(CCCS,n);
574     
575     bd = cap->r.rCurrentAlloc;
576     if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
577         
578         // The CurrentAlloc block is full, we need to find another
579         // one.  First, we try taking the next block from the
580         // nursery:
581         bd = cap->r.rCurrentNursery->link;
582         
583         if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
584             // The nursery is empty, or the next block is already
585             // full: allocate a fresh block (we can't fail here).
586             ACQUIRE_SM_LOCK;
587             bd = allocBlock();
588             cap->r.rNursery->n_blocks++;
589             RELEASE_SM_LOCK;
590             initBdescr(bd, g0, g0);
591             bd->flags = 0;
592             // If we had to allocate a new block, then we'll GC
593             // pretty quickly now, because MAYBE_GC() will
594             // notice that CurrentNursery->link is NULL.
595         } else {
596             // we have a block in the nursery: take it and put
597             // it at the *front* of the nursery list, and use it
598             // to allocate() from.
599             cap->r.rCurrentNursery->link = bd->link;
600             if (bd->link != NULL) {
601                 bd->link->u.back = cap->r.rCurrentNursery;
602             }
603         }
604         dbl_link_onto(bd, &cap->r.rNursery->blocks);
605         cap->r.rCurrentAlloc = bd;
606         IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
607     }
608     p = bd->free;
609     bd->free += n;
610
611     IF_DEBUG(sanity, ASSERT(*((StgWord8*)p) == 0xaa));
612     return p;
613 }
614
615 /* ---------------------------------------------------------------------------
616    Allocate a fixed/pinned object.
617
618    We allocate small pinned objects into a single block, allocating a
619    new block when the current one overflows.  The block is chained
620    onto the large_object_list of generation 0.
621
622    NOTE: The GC can't in general handle pinned objects.  This
623    interface is only safe to use for ByteArrays, which have no
624    pointers and don't require scavenging.  It works because the
625    block's descriptor has the BF_LARGE flag set, so the block is
626    treated as a large object and chained onto various lists, rather
627    than the individual objects being copied.  However, when it comes
628    to scavenge the block, the GC will only scavenge the first object.
629    The reason is that the GC can't linearly scan a block of pinned
630    objects at the moment (doing so would require using the
631    mostly-copying techniques).  But since we're restricting ourselves
632    to pinned ByteArrays, not scavenging is ok.
633
634    This function is called by newPinnedByteArray# which immediately
635    fills the allocated memory with a MutableByteArray#.
636    ------------------------------------------------------------------------- */
637
638 StgPtr
639 allocatePinned (Capability *cap, lnat n)
640 {
641     StgPtr p;
642     bdescr *bd;
643
644     // If the request is for a large object, then allocate()
645     // will give us a pinned object anyway.
646     if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
647         p = allocate(cap, n);
648         Bdescr(p)->flags |= BF_PINNED;
649         return p;
650     }
651
652     TICK_ALLOC_HEAP_NOCTR(n);
653     CCS_ALLOC(CCCS,n);
654
655     bd = cap->pinned_object_block;
656     
657     // If we don't have a block of pinned objects yet, or the current
658     // one isn't large enough to hold the new object, allocate a new one.
659     if (bd == NULL || (bd->free + n) > (bd->start + BLOCK_SIZE_W)) {
660         // The pinned_object_block remains attached to the capability
661         // until it is full, even if a GC occurs.  We want this
662         // behaviour because otherwise the unallocated portion of the
663         // block would be forever slop, and under certain workloads
664         // (allocating a few ByteStrings per GC) we accumulate a lot
665         // of slop.
666         //
667         // So, the pinned_object_block is initially marked
668         // BF_EVACUATED so the GC won't touch it.  When it is full,
669         // we place it on the large_objects list, and at the start of
670         // the next GC the BF_EVACUATED flag will be cleared, and the
671         // block will be promoted as usual (if anything in it is
672         // live).
673         ACQUIRE_SM_LOCK;
674         if (bd != NULL) {
675             dbl_link_onto(bd, &g0->large_objects);
676             g0->n_large_blocks++;
677             g0->n_new_large_words += bd->free - bd->start;
678         }
679         cap->pinned_object_block = bd = allocBlock();
680         RELEASE_SM_LOCK;
681         initBdescr(bd, g0, g0);
682         bd->flags  = BF_PINNED | BF_LARGE | BF_EVACUATED;
683         bd->free   = bd->start;
684     }
685
686     p = bd->free;
687     bd->free += n;
688     return p;
689 }
690
691 /* -----------------------------------------------------------------------------
692    Write Barriers
693    -------------------------------------------------------------------------- */
694
695 /*
696    This is the write barrier for MUT_VARs, a.k.a. IORefs.  A
697    MUT_VAR_CLEAN object is not on the mutable list; a MUT_VAR_DIRTY
698    is.  When written to, a MUT_VAR_CLEAN turns into a MUT_VAR_DIRTY
699    and is put on the mutable list.
700 */
701 void
702 dirty_MUT_VAR(StgRegTable *reg, StgClosure *p)
703 {
704     Capability *cap = regTableToCapability(reg);
705     if (p->header.info == &stg_MUT_VAR_CLEAN_info) {
706         p->header.info = &stg_MUT_VAR_DIRTY_info;
707         recordClosureMutated(cap,p);
708     }
709 }
710
711 // Setting a TSO's link field with a write barrier.
712 // It is *not* necessary to call this function when
713 //    * setting the link field to END_TSO_QUEUE
714 //    * putting a TSO on the blackhole_queue
715 //    * setting the link field of the currently running TSO, as it
716 //      will already be dirty.
717 void
718 setTSOLink (Capability *cap, StgTSO *tso, StgTSO *target)
719 {
720     if (tso->dirty == 0) {
721         tso->dirty = 1;
722         recordClosureMutated(cap,(StgClosure*)tso);
723     }
724     tso->_link = target;
725 }
726
727 void
728 setTSOPrev (Capability *cap, StgTSO *tso, StgTSO *target)
729 {
730     if (tso->dirty == 0) {
731         tso->dirty = 1;
732         recordClosureMutated(cap,(StgClosure*)tso);
733     }
734     tso->block_info.prev = target;
735 }
736
737 void
738 dirty_TSO (Capability *cap, StgTSO *tso)
739 {
740     if (tso->dirty == 0) {
741         tso->dirty = 1;
742         recordClosureMutated(cap,(StgClosure*)tso);
743     }
744 }
745
746 void
747 dirty_STACK (Capability *cap, StgStack *stack)
748 {
749     if (stack->dirty == 0) {
750         stack->dirty = 1;
751         recordClosureMutated(cap,(StgClosure*)stack);
752     }
753 }
754
755 /*
756    This is the write barrier for MVARs.  An MVAR_CLEAN objects is not
757    on the mutable list; a MVAR_DIRTY is.  When written to, a
758    MVAR_CLEAN turns into a MVAR_DIRTY and is put on the mutable list.
759    The check for MVAR_CLEAN is inlined at the call site for speed,
760    this really does make a difference on concurrency-heavy benchmarks
761    such as Chaneneos and cheap-concurrency.
762 */
763 void
764 dirty_MVAR(StgRegTable *reg, StgClosure *p)
765 {
766     recordClosureMutated(regTableToCapability(reg),p);
767 }
768
769 /* -----------------------------------------------------------------------------
770  * Stats and stuff
771  * -------------------------------------------------------------------------- */
772
773 /* -----------------------------------------------------------------------------
774  * calcAllocated()
775  *
776  * Approximate how much we've allocated: number of blocks in the
777  * nursery + blocks allocated via allocate() - unused nusery blocks.
778  * This leaves a little slop at the end of each block.
779  * -------------------------------------------------------------------------- */
780
781 lnat
782 calcAllocated (rtsBool include_nurseries)
783 {
784   nat allocated = 0;
785   nat i;
786
787   // When called from GC.c, we already have the allocation count for
788   // the nursery from resetNurseries(), so we don't need to walk
789   // through these block lists again.
790   if (include_nurseries)
791   {
792       for (i = 0; i < n_capabilities; i++) {
793           allocated += countOccupied(nurseries[i].blocks);
794       }
795   }
796
797   // add in sizes of new large and pinned objects
798   allocated += g0->n_new_large_words;
799
800   return allocated;
801 }  
802
803 lnat countOccupied (bdescr *bd)
804 {
805     lnat words;
806
807     words = 0;
808     for (; bd != NULL; bd = bd->link) {
809         ASSERT(bd->free <= bd->start + bd->blocks * BLOCK_SIZE_W);
810         words += bd->free - bd->start;
811     }
812     return words;
813 }
814
815 lnat genLiveWords (generation *gen)
816 {
817     return gen->n_words + countOccupied(gen->large_objects);
818 }
819
820 lnat genLiveBlocks (generation *gen)
821 {
822     return gen->n_blocks + gen->n_large_blocks;
823 }
824
825 lnat gcThreadLiveWords (nat i, nat g)
826 {
827     lnat words;
828
829     words   = countOccupied(gc_threads[i]->gens[g].todo_bd);
830     words  += countOccupied(gc_threads[i]->gens[g].part_list);
831     words  += countOccupied(gc_threads[i]->gens[g].scavd_list);
832
833     return words;
834 }
835
836 lnat gcThreadLiveBlocks (nat i, nat g)
837 {
838     lnat blocks;
839
840     blocks  = countBlocks(gc_threads[i]->gens[g].todo_bd);
841     blocks += gc_threads[i]->gens[g].n_part_blocks;
842     blocks += gc_threads[i]->gens[g].n_scavd_blocks;
843
844     return blocks;
845 }
846
847 // Return an accurate count of the live data in the heap, excluding
848 // generation 0.
849 lnat calcLiveWords (void)
850 {
851     nat g;
852     lnat live;
853
854     live = 0;
855     for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
856         live += genLiveWords(&generations[g]);
857     }
858     return live;
859 }
860
861 lnat calcLiveBlocks (void)
862 {
863     nat g;
864     lnat live;
865
866     live = 0;
867     for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
868         live += genLiveBlocks(&generations[g]);
869     }
870     return live;
871 }
872
873 /* Approximate the number of blocks that will be needed at the next
874  * garbage collection.
875  *
876  * Assume: all data currently live will remain live.  Generationss
877  * that will be collected next time will therefore need twice as many
878  * blocks since all the data will be copied.
879  */
880 extern lnat 
881 calcNeeded(void)
882 {
883     lnat needed = 0;
884     nat g;
885     generation *gen;
886     
887     for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
888         gen = &generations[g];
889
890         // we need at least this much space
891         needed += gen->n_blocks + gen->n_large_blocks;
892         
893         // any additional space needed to collect this gen next time?
894         if (g == 0 || // always collect gen 0
895             (gen->n_blocks + gen->n_large_blocks > gen->max_blocks)) {
896             // we will collect this gen next time
897             if (gen->mark) {
898                 //  bitmap:
899                 needed += gen->n_blocks / BITS_IN(W_);
900                 //  mark stack:
901                 needed += gen->n_blocks / 100;
902             }
903             if (gen->compact) {
904                 continue; // no additional space needed for compaction
905             } else {
906                 needed += gen->n_blocks;
907             }
908         }
909     }
910     return needed;
911 }
912
913 /* ----------------------------------------------------------------------------
914    Executable memory
915
916    Executable memory must be managed separately from non-executable
917    memory.  Most OSs these days require you to jump through hoops to
918    dynamically allocate executable memory, due to various security
919    measures.
920
921    Here we provide a small memory allocator for executable memory.
922    Memory is managed with a page granularity; we allocate linearly
923    in the page, and when the page is emptied (all objects on the page
924    are free) we free the page again, not forgetting to make it
925    non-executable.
926
927    TODO: The inability to handle objects bigger than BLOCK_SIZE_W means that
928          the linker cannot use allocateExec for loading object code files
929          on Windows. Once allocateExec can handle larger objects, the linker
930          should be modified to use allocateExec instead of VirtualAlloc.
931    ------------------------------------------------------------------------- */
932
933 #if defined(linux_HOST_OS)
934
935 // On Linux we need to use libffi for allocating executable memory,
936 // because it knows how to work around the restrictions put in place
937 // by SELinux.
938
939 void *allocateExec (nat bytes, void **exec_ret)
940 {
941     void **ret, **exec;
942     ACQUIRE_SM_LOCK;
943     ret = ffi_closure_alloc (sizeof(void *) + (size_t)bytes, (void**)&exec);
944     RELEASE_SM_LOCK;
945     if (ret == NULL) return ret;
946     *ret = ret; // save the address of the writable mapping, for freeExec().
947     *exec_ret = exec + 1;
948     return (ret + 1);
949 }
950
951 // freeExec gets passed the executable address, not the writable address. 
952 void freeExec (void *addr)
953 {
954     void *writable;
955     writable = *((void**)addr - 1);
956     ACQUIRE_SM_LOCK;
957     ffi_closure_free (writable);
958     RELEASE_SM_LOCK
959 }
960
961 #else
962
963 void *allocateExec (nat bytes, void **exec_ret)
964 {
965     void *ret;
966     nat n;
967
968     ACQUIRE_SM_LOCK;
969
970     // round up to words.
971     n  = (bytes + sizeof(W_) + 1) / sizeof(W_);
972
973     if (n+1 > BLOCK_SIZE_W) {
974         barf("allocateExec: can't handle large objects");
975     }
976
977     if (exec_block == NULL || 
978         exec_block->free + n + 1 > exec_block->start + BLOCK_SIZE_W) {
979         bdescr *bd;
980         lnat pagesize = getPageSize();
981         bd = allocGroup(stg_max(1, pagesize / BLOCK_SIZE));
982         debugTrace(DEBUG_gc, "allocate exec block %p", bd->start);
983         bd->gen_no = 0;
984         bd->flags = BF_EXEC;
985         bd->link = exec_block;
986         if (exec_block != NULL) {
987             exec_block->u.back = bd;
988         }
989         bd->u.back = NULL;
990         setExecutable(bd->start, bd->blocks * BLOCK_SIZE, rtsTrue);
991         exec_block = bd;
992     }
993     *(exec_block->free) = n;  // store the size of this chunk
994     exec_block->gen_no += n;  // gen_no stores the number of words allocated
995     ret = exec_block->free + 1;
996     exec_block->free += n + 1;
997
998     RELEASE_SM_LOCK
999     *exec_ret = ret;
1000     return ret;
1001 }
1002
1003 void freeExec (void *addr)
1004 {
1005     StgPtr p = (StgPtr)addr - 1;
1006     bdescr *bd = Bdescr((StgPtr)p);
1007
1008     if ((bd->flags & BF_EXEC) == 0) {
1009         barf("freeExec: not executable");
1010     }
1011
1012     if (*(StgPtr)p == 0) {
1013         barf("freeExec: already free?");
1014     }
1015
1016     ACQUIRE_SM_LOCK;
1017
1018     bd->gen_no -= *(StgPtr)p;
1019     *(StgPtr)p = 0;
1020
1021     if (bd->gen_no == 0) {
1022         // Free the block if it is empty, but not if it is the block at
1023         // the head of the queue.
1024         if (bd != exec_block) {
1025             debugTrace(DEBUG_gc, "free exec block %p", bd->start);
1026             dbl_link_remove(bd, &exec_block);
1027             setExecutable(bd->start, bd->blocks * BLOCK_SIZE, rtsFalse);
1028             freeGroup(bd);
1029         } else {
1030             bd->free = bd->start;
1031         }
1032     }
1033
1034     RELEASE_SM_LOCK
1035 }    
1036
1037 #endif /* mingw32_HOST_OS */
1038
1039 #ifdef DEBUG
1040
1041 // handy function for use in gdb, because Bdescr() is inlined.
1042 extern bdescr *_bdescr( StgPtr p );
1043
1044 bdescr *
1045 _bdescr( StgPtr p )
1046 {
1047     return Bdescr(p);
1048 }
1049
1050 #endif