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