Make allocatePinned use local storage, and other refactorings
[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 static 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 nat total_steps         = 0;
53 step *all_steps         = NULL; /* single array of steps */
54
55 ullong total_allocated = 0;     /* total memory allocated during run */
56
57 nat n_nurseries         = 0;    /* == RtsFlags.ParFlags.nNodes, convenience */
58 step *nurseries         = NULL; /* array of nurseries, >1 only if THREADED_RTS */
59
60 #ifdef THREADED_RTS
61 /*
62  * Storage manager mutex:  protects all the above state from
63  * simultaneous access by two STG threads.
64  */
65 Mutex sm_mutex;
66 #endif
67
68 static void allocNurseries ( void );
69
70 static void
71 initStep (step *stp, int g, int s)
72 {
73     stp->no = s;
74     stp->abs_no = RtsFlags.GcFlags.steps * g + s;
75     stp->blocks = NULL;
76     stp->n_blocks = 0;
77     stp->n_words = 0;
78     stp->live_estimate = 0;
79     stp->old_blocks = NULL;
80     stp->n_old_blocks = 0;
81     stp->gen = &generations[g];
82     stp->gen_no = g;
83     stp->large_objects = NULL;
84     stp->n_large_blocks = 0;
85     stp->scavenged_large_objects = NULL;
86     stp->n_scavenged_large_blocks = 0;
87     stp->mark = 0;
88     stp->compact = 0;
89     stp->bitmap = NULL;
90 #ifdef THREADED_RTS
91     initSpinLock(&stp->sync_large_objects);
92 #endif
93     stp->threads = END_TSO_QUEUE;
94     stp->old_threads = END_TSO_QUEUE;
95 }
96
97 void
98 initStorage( void )
99 {
100   nat g, s;
101   generation *gen;
102
103   if (generations != NULL) {
104       // multi-init protection
105       return;
106   }
107
108   initMBlocks();
109
110   /* Sanity check to make sure the LOOKS_LIKE_ macros appear to be
111    * doing something reasonable.
112    */
113   /* We use the NOT_NULL variant or gcc warns that the test is always true */
114   ASSERT(LOOKS_LIKE_INFO_PTR_NOT_NULL((StgWord)&stg_BLACKHOLE_info));
115   ASSERT(LOOKS_LIKE_CLOSURE_PTR(&stg_dummy_ret_closure));
116   ASSERT(!HEAP_ALLOCED(&stg_dummy_ret_closure));
117   
118   if (RtsFlags.GcFlags.maxHeapSize != 0 &&
119       RtsFlags.GcFlags.heapSizeSuggestion > 
120       RtsFlags.GcFlags.maxHeapSize) {
121     RtsFlags.GcFlags.maxHeapSize = RtsFlags.GcFlags.heapSizeSuggestion;
122   }
123
124   if (RtsFlags.GcFlags.maxHeapSize != 0 &&
125       RtsFlags.GcFlags.minAllocAreaSize > 
126       RtsFlags.GcFlags.maxHeapSize) {
127       errorBelch("maximum heap size (-M) is smaller than minimum alloc area size (-A)");
128       RtsFlags.GcFlags.minAllocAreaSize = RtsFlags.GcFlags.maxHeapSize;
129   }
130
131   initBlockAllocator();
132   
133 #if defined(THREADED_RTS)
134   initMutex(&sm_mutex);
135 #endif
136
137   ACQUIRE_SM_LOCK;
138
139   /* allocate generation info array */
140   generations = (generation *)stgMallocBytes(RtsFlags.GcFlags.generations 
141                                              * sizeof(struct generation_),
142                                              "initStorage: gens");
143
144   /* Initialise all generations */
145   for(g = 0; g < RtsFlags.GcFlags.generations; g++) {
146     gen = &generations[g];
147     gen->no = g;
148     gen->mut_list = allocBlock();
149     gen->collections = 0;
150     gen->par_collections = 0;
151     gen->failed_promotions = 0;
152     gen->max_blocks = 0;
153   }
154
155   /* A couple of convenience pointers */
156   g0 = &generations[0];
157   oldest_gen = &generations[RtsFlags.GcFlags.generations-1];
158
159   /* allocate all the steps into an array.  It is important that we do
160      it this way, because we need the invariant that two step pointers
161      can be directly compared to see which is the oldest.
162      Remember that the last generation has only one step. */
163   total_steps = 1 + (RtsFlags.GcFlags.generations - 1) * RtsFlags.GcFlags.steps;
164   all_steps   = stgMallocBytes(total_steps * sizeof(struct step_),
165                                "initStorage: steps");
166
167   /* Allocate step structures in each generation */
168   if (RtsFlags.GcFlags.generations > 1) {
169     /* Only for multiple-generations */
170
171     /* Oldest generation: one step */
172     oldest_gen->n_steps = 1;
173     oldest_gen->steps   = all_steps + (RtsFlags.GcFlags.generations - 1)
174                                       * RtsFlags.GcFlags.steps;
175
176     /* set up all except the oldest generation with 2 steps */
177     for(g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
178       generations[g].n_steps = RtsFlags.GcFlags.steps;
179       generations[g].steps   = all_steps + g * RtsFlags.GcFlags.steps;
180     }
181     
182   } else {
183     /* single generation, i.e. a two-space collector */
184     g0->n_steps = 1;
185     g0->steps   = all_steps;
186   }
187
188   n_nurseries = n_capabilities;
189   nurseries = stgMallocBytes (n_nurseries * sizeof(struct step_),
190                               "initStorage: nurseries");
191
192   /* Initialise all steps */
193   for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
194     for (s = 0; s < generations[g].n_steps; s++) {
195         initStep(&generations[g].steps[s], g, s);
196     }
197   }
198   
199   for (s = 0; s < n_nurseries; s++) {
200       initStep(&nurseries[s], 0, s);
201   }
202   
203   /* Set up the destination pointers in each younger gen. step */
204   for (g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
205     for (s = 0; s < generations[g].n_steps-1; s++) {
206       generations[g].steps[s].to = &generations[g].steps[s+1];
207     }
208     generations[g].steps[s].to = &generations[g+1].steps[0];
209   }
210   oldest_gen->steps[0].to = &oldest_gen->steps[0];
211   
212   for (s = 0; s < n_nurseries; s++) {
213       nurseries[s].to = generations[0].steps[0].to;
214   }
215   
216   /* The oldest generation has one step. */
217   if (RtsFlags.GcFlags.compact || RtsFlags.GcFlags.sweep) {
218       if (RtsFlags.GcFlags.generations == 1) {
219           errorBelch("WARNING: compact/sweep is incompatible with -G1; disabled");
220       } else {
221           oldest_gen->steps[0].mark = 1;
222           if (RtsFlags.GcFlags.compact)
223               oldest_gen->steps[0].compact = 1;
224       }
225   }
226
227   generations[0].max_blocks = 0;
228
229   /* The allocation area.  Policy: keep the allocation area
230    * small to begin with, even if we have a large suggested heap
231    * size.  Reason: we're going to do a major collection first, and we
232    * don't want it to be a big one.  This vague idea is borne out by 
233    * rigorous experimental evidence.
234    */
235   allocNurseries();
236
237   weak_ptr_list = NULL;
238   caf_list = NULL;
239   revertible_caf_list = NULL;
240    
241   /* initialise the allocate() interface */
242   alloc_blocks_lim = RtsFlags.GcFlags.minAllocAreaSize;
243
244   exec_block = NULL;
245
246 #ifdef THREADED_RTS
247   initSpinLock(&gc_alloc_block_sync);
248   whitehole_spin = 0;
249 #endif
250
251   N = 0;
252
253   initGcThreads();
254
255   IF_DEBUG(gc, statDescribeGens());
256
257   RELEASE_SM_LOCK;
258 }
259
260 void
261 exitStorage (void)
262 {
263     stat_exit(calcAllocated());
264 }
265
266 void
267 freeStorage (void)
268 {
269     stgFree(all_steps); // frees all the steps
270     stgFree(generations);
271     freeAllMBlocks();
272 #if defined(THREADED_RTS)
273     closeMutex(&sm_mutex);
274 #endif
275     stgFree(nurseries);
276     freeGcThreads();
277 }
278
279 /* -----------------------------------------------------------------------------
280    CAF management.
281
282    The entry code for every CAF does the following:
283      
284       - builds a CAF_BLACKHOLE in the heap
285       - pushes an update frame pointing to the CAF_BLACKHOLE
286       - invokes UPD_CAF(), which:
287           - calls newCaf, below
288           - updates the CAF with a static indirection to the CAF_BLACKHOLE
289       
290    Why do we build a BLACKHOLE in the heap rather than just updating
291    the thunk directly?  It's so that we only need one kind of update
292    frame - otherwise we'd need a static version of the update frame too.
293
294    newCaf() does the following:
295        
296       - it puts the CAF on the oldest generation's mut-once list.
297         This is so that we can treat the CAF as a root when collecting
298         younger generations.
299
300    For GHCI, we have additional requirements when dealing with CAFs:
301
302       - we must *retain* all dynamically-loaded CAFs ever entered,
303         just in case we need them again.
304       - we must be able to *revert* CAFs that have been evaluated, to
305         their pre-evaluated form.
306
307       To do this, we use an additional CAF list.  When newCaf() is
308       called on a dynamically-loaded CAF, we add it to the CAF list
309       instead of the old-generation mutable list, and save away its
310       old info pointer (in caf->saved_info) for later reversion.
311
312       To revert all the CAFs, we traverse the CAF list and reset the
313       info pointer to caf->saved_info, then throw away the CAF list.
314       (see GC.c:revertCAFs()).
315
316       -- SDM 29/1/01
317
318    -------------------------------------------------------------------------- */
319
320 void
321 newCAF(StgClosure* caf)
322 {
323   ACQUIRE_SM_LOCK;
324
325 #ifdef DYNAMIC
326   if(keepCAFs)
327   {
328     // HACK:
329     // If we are in GHCi _and_ we are using dynamic libraries,
330     // then we can't redirect newCAF calls to newDynCAF (see below),
331     // so we make newCAF behave almost like newDynCAF.
332     // The dynamic libraries might be used by both the interpreted
333     // program and GHCi itself, so they must not be reverted.
334     // This also means that in GHCi with dynamic libraries, CAFs are not
335     // garbage collected. If this turns out to be a problem, we could
336     // do another hack here and do an address range test on caf to figure
337     // out whether it is from a dynamic library.
338     ((StgIndStatic *)caf)->saved_info  = (StgInfoTable *)caf->header.info;
339     ((StgIndStatic *)caf)->static_link = caf_list;
340     caf_list = caf;
341   }
342   else
343 #endif
344   {
345     /* Put this CAF on the mutable list for the old generation.
346     * This is a HACK - the IND_STATIC closure doesn't really have
347     * a mut_link field, but we pretend it has - in fact we re-use
348     * the STATIC_LINK field for the time being, because when we
349     * come to do a major GC we won't need the mut_link field
350     * any more and can use it as a STATIC_LINK.
351     */
352     ((StgIndStatic *)caf)->saved_info = NULL;
353     recordMutableGen(caf, oldest_gen->no);
354   }
355   
356   RELEASE_SM_LOCK;
357 }
358
359 // An alternate version of newCaf which is used for dynamically loaded
360 // object code in GHCi.  In this case we want to retain *all* CAFs in
361 // the object code, because they might be demanded at any time from an
362 // expression evaluated on the command line.
363 // Also, GHCi might want to revert CAFs, so we add these to the
364 // revertible_caf_list.
365 //
366 // The linker hackily arranges that references to newCaf from dynamic
367 // code end up pointing to newDynCAF.
368 void
369 newDynCAF(StgClosure *caf)
370 {
371     ACQUIRE_SM_LOCK;
372
373     ((StgIndStatic *)caf)->saved_info  = (StgInfoTable *)caf->header.info;
374     ((StgIndStatic *)caf)->static_link = revertible_caf_list;
375     revertible_caf_list = caf;
376
377     RELEASE_SM_LOCK;
378 }
379
380 /* -----------------------------------------------------------------------------
381    Nursery management.
382    -------------------------------------------------------------------------- */
383
384 static bdescr *
385 allocNursery (step *stp, bdescr *tail, nat blocks)
386 {
387     bdescr *bd;
388     nat i;
389
390     // Allocate a nursery: we allocate fresh blocks one at a time and
391     // cons them on to the front of the list, not forgetting to update
392     // the back pointer on the tail of the list to point to the new block.
393     for (i=0; i < blocks; i++) {
394         // @LDV profiling
395         /*
396           processNursery() in LdvProfile.c assumes that every block group in
397           the nursery contains only a single block. So, if a block group is
398           given multiple blocks, change processNursery() accordingly.
399         */
400         bd = allocBlock();
401         bd->link = tail;
402         // double-link the nursery: we might need to insert blocks
403         if (tail != NULL) {
404             tail->u.back = bd;
405         }
406         initBdescr(bd, stp);
407         bd->flags = 0;
408         bd->free = bd->start;
409         tail = bd;
410     }
411     tail->u.back = NULL;
412     return tail;
413 }
414
415 static void
416 assignNurseriesToCapabilities (void)
417 {
418     nat i;
419
420     for (i = 0; i < n_nurseries; i++) {
421         capabilities[i].r.rNursery        = &nurseries[i];
422         capabilities[i].r.rCurrentNursery = nurseries[i].blocks;
423         capabilities[i].r.rCurrentAlloc   = NULL;
424     }
425 }
426
427 static void
428 allocNurseries( void )
429
430     nat i;
431
432     for (i = 0; i < n_nurseries; i++) {
433         nurseries[i].blocks = 
434             allocNursery(&nurseries[i], NULL, 
435                          RtsFlags.GcFlags.minAllocAreaSize);
436         nurseries[i].n_blocks    = RtsFlags.GcFlags.minAllocAreaSize;
437         nurseries[i].old_blocks   = NULL;
438         nurseries[i].n_old_blocks = 0;
439     }
440     assignNurseriesToCapabilities();
441 }
442       
443 void
444 resetNurseries( void )
445 {
446     nat i;
447     bdescr *bd;
448     step *stp;
449
450     for (i = 0; i < n_nurseries; i++) {
451         stp = &nurseries[i];
452         for (bd = stp->blocks; bd; bd = bd->link) {
453             bd->free = bd->start;
454             ASSERT(bd->gen_no == 0);
455             ASSERT(bd->step == stp);
456             IF_DEBUG(sanity,memset(bd->start, 0xaa, BLOCK_SIZE));
457         }
458         // these large objects are dead, since we have just GC'd
459         freeChain(stp->large_objects);
460         stp->large_objects = NULL;
461         stp->n_large_blocks = 0;
462     }
463     assignNurseriesToCapabilities();
464 }
465
466 lnat
467 countNurseryBlocks (void)
468 {
469     nat i;
470     lnat blocks = 0;
471
472     for (i = 0; i < n_nurseries; i++) {
473         blocks += nurseries[i].n_blocks;
474         blocks += nurseries[i].n_large_blocks;
475     }
476     return blocks;
477 }
478
479 static void
480 resizeNursery ( step *stp, nat blocks )
481 {
482   bdescr *bd;
483   nat nursery_blocks;
484
485   nursery_blocks = stp->n_blocks;
486   if (nursery_blocks == blocks) return;
487
488   if (nursery_blocks < blocks) {
489       debugTrace(DEBUG_gc, "increasing size of nursery to %d blocks", 
490                  blocks);
491     stp->blocks = allocNursery(stp, stp->blocks, blocks-nursery_blocks);
492   } 
493   else {
494     bdescr *next_bd;
495     
496     debugTrace(DEBUG_gc, "decreasing size of nursery to %d blocks", 
497                blocks);
498
499     bd = stp->blocks;
500     while (nursery_blocks > blocks) {
501         next_bd = bd->link;
502         next_bd->u.back = NULL;
503         nursery_blocks -= bd->blocks; // might be a large block
504         freeGroup(bd);
505         bd = next_bd;
506     }
507     stp->blocks = bd;
508     // might have gone just under, by freeing a large block, so make
509     // up the difference.
510     if (nursery_blocks < blocks) {
511         stp->blocks = allocNursery(stp, stp->blocks, blocks-nursery_blocks);
512     }
513   }
514   
515   stp->n_blocks = blocks;
516   ASSERT(countBlocks(stp->blocks) == stp->n_blocks);
517 }
518
519 // 
520 // Resize each of the nurseries to the specified size.
521 //
522 void
523 resizeNurseriesFixed (nat blocks)
524 {
525     nat i;
526     for (i = 0; i < n_nurseries; i++) {
527         resizeNursery(&nurseries[i], blocks);
528     }
529 }
530
531 // 
532 // Resize the nurseries to the total specified size.
533 //
534 void
535 resizeNurseries (nat blocks)
536 {
537     // If there are multiple nurseries, then we just divide the number
538     // of available blocks between them.
539     resizeNurseriesFixed(blocks / n_nurseries);
540 }
541
542
543 /* -----------------------------------------------------------------------------
544    move_TSO is called to update the TSO structure after it has been
545    moved from one place to another.
546    -------------------------------------------------------------------------- */
547
548 void
549 move_TSO (StgTSO *src, StgTSO *dest)
550 {
551     ptrdiff_t diff;
552
553     // relocate the stack pointer... 
554     diff = (StgPtr)dest - (StgPtr)src; // In *words* 
555     dest->sp = (StgPtr)dest->sp + diff;
556 }
557
558 /* -----------------------------------------------------------------------------
559    split N blocks off the front of the given bdescr, returning the
560    new block group.  We add the remainder to the large_blocks list
561    in the same step as the original block.
562    -------------------------------------------------------------------------- */
563
564 bdescr *
565 splitLargeBlock (bdescr *bd, nat blocks)
566 {
567     bdescr *new_bd;
568
569     ACQUIRE_SM_LOCK;
570
571     ASSERT(countBlocks(bd->step->large_objects) == bd->step->n_large_blocks);
572
573     // subtract the original number of blocks from the counter first
574     bd->step->n_large_blocks -= bd->blocks;
575
576     new_bd = splitBlockGroup (bd, blocks);
577     initBdescr(new_bd, bd->step);
578     new_bd->flags   = BF_LARGE | (bd->flags & BF_EVACUATED); 
579     // if new_bd is in an old generation, we have to set BF_EVACUATED
580     new_bd->free    = bd->free;
581     dbl_link_onto(new_bd, &bd->step->large_objects);
582
583     ASSERT(new_bd->free <= new_bd->start + new_bd->blocks * BLOCK_SIZE_W);
584
585     // add the new number of blocks to the counter.  Due to the gaps
586     // for block descriptors, new_bd->blocks + bd->blocks might not be
587     // equal to the original bd->blocks, which is why we do it this way.
588     bd->step->n_large_blocks += bd->blocks + new_bd->blocks;
589
590     ASSERT(countBlocks(bd->step->large_objects) == bd->step->n_large_blocks);
591
592     RELEASE_SM_LOCK;
593
594     return new_bd;
595 }
596
597 /* -----------------------------------------------------------------------------
598    allocate()
599
600    This allocates memory in the current thread - it is intended for
601    use primarily from STG-land where we have a Capability.  It is
602    better than allocate() because it doesn't require taking the
603    sm_mutex lock in the common case.
604
605    Memory is allocated directly from the nursery if possible (but not
606    from the current nursery block, so as not to interfere with
607    Hp/HpLim).
608    -------------------------------------------------------------------------- */
609
610 StgPtr
611 allocate (Capability *cap, lnat n)
612 {
613     bdescr *bd;
614     StgPtr p;
615     step *stp;
616
617     if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
618         lnat req_blocks =  (lnat)BLOCK_ROUND_UP(n*sizeof(W_)) / BLOCK_SIZE;
619
620         // Attempting to allocate an object larger than maxHeapSize
621         // should definitely be disallowed.  (bug #1791)
622         if (RtsFlags.GcFlags.maxHeapSize > 0 && 
623             req_blocks >= RtsFlags.GcFlags.maxHeapSize) {
624             heapOverflow();
625             // heapOverflow() doesn't exit (see #2592), but we aren't
626             // in a position to do a clean shutdown here: we
627             // either have to allocate the memory or exit now.
628             // Allocating the memory would be bad, because the user
629             // has requested that we not exceed maxHeapSize, so we
630             // just exit.
631             stg_exit(EXIT_HEAPOVERFLOW);
632         }
633
634         stp = &nurseries[cap->no];
635
636         bd = allocGroup(req_blocks);
637         dbl_link_onto(bd, &stp->large_objects);
638         stp->n_large_blocks += bd->blocks; // might be larger than req_blocks
639         initBdescr(bd, stp);
640         bd->flags = BF_LARGE;
641         bd->free = bd->start + n;
642         return bd->start;
643     }
644
645     /* small allocation (<LARGE_OBJECT_THRESHOLD) */
646
647     TICK_ALLOC_HEAP_NOCTR(n);
648     CCS_ALLOC(CCCS,n);
649     
650     bd = cap->r.rCurrentAlloc;
651     if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
652         
653         // The CurrentAlloc block is full, we need to find another
654         // one.  First, we try taking the next block from the
655         // nursery:
656         bd = cap->r.rCurrentNursery->link;
657         
658         if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
659             // The nursery is empty, or the next block is already
660             // full: allocate a fresh block (we can't fail here).
661             ACQUIRE_SM_LOCK;
662             bd = allocBlock();
663             cap->r.rNursery->n_blocks++;
664             RELEASE_SM_LOCK;
665             initBdescr(bd, cap->r.rNursery);
666             bd->flags = 0;
667             // If we had to allocate a new block, then we'll GC
668             // pretty quickly now, because MAYBE_GC() will
669             // notice that CurrentNursery->link is NULL.
670         } else {
671             // we have a block in the nursery: take it and put
672             // it at the *front* of the nursery list, and use it
673             // to allocate() from.
674             cap->r.rCurrentNursery->link = bd->link;
675             if (bd->link != NULL) {
676                 bd->link->u.back = cap->r.rCurrentNursery;
677             }
678         }
679         dbl_link_onto(bd, &cap->r.rNursery->blocks);
680         cap->r.rCurrentAlloc = bd;
681         IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
682     }
683     p = bd->free;
684     bd->free += n;
685     return p;
686 }
687
688 /* ---------------------------------------------------------------------------
689    Allocate a fixed/pinned object.
690
691    We allocate small pinned objects into a single block, allocating a
692    new block when the current one overflows.  The block is chained
693    onto the large_object_list of generation 0 step 0.
694
695    NOTE: The GC can't in general handle pinned objects.  This
696    interface is only safe to use for ByteArrays, which have no
697    pointers and don't require scavenging.  It works because the
698    block's descriptor has the BF_LARGE flag set, so the block is
699    treated as a large object and chained onto various lists, rather
700    than the individual objects being copied.  However, when it comes
701    to scavenge the block, the GC will only scavenge the first object.
702    The reason is that the GC can't linearly scan a block of pinned
703    objects at the moment (doing so would require using the
704    mostly-copying techniques).  But since we're restricting ourselves
705    to pinned ByteArrays, not scavenging is ok.
706
707    This function is called by newPinnedByteArray# which immediately
708    fills the allocated memory with a MutableByteArray#.
709    ------------------------------------------------------------------------- */
710
711 StgPtr
712 allocatePinned (Capability *cap, lnat n)
713 {
714     StgPtr p;
715     bdescr *bd;
716     step *stp;
717
718     // If the request is for a large object, then allocate()
719     // will give us a pinned object anyway.
720     if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
721         p = allocate(cap, n);
722         Bdescr(p)->flags |= BF_PINNED;
723         return p;
724     }
725
726     TICK_ALLOC_HEAP_NOCTR(n);
727     CCS_ALLOC(CCCS,n);
728
729     bd = cap->pinned_object_block;
730     
731     // If we don't have a block of pinned objects yet, or the current
732     // one isn't large enough to hold the new object, allocate a new one.
733     if (bd == NULL || (bd->free + n) > (bd->start + BLOCK_SIZE_W)) {
734         ACQUIRE_SM_LOCK
735         cap->pinned_object_block = bd = allocBlock();
736         RELEASE_SM_LOCK
737         stp = &nurseries[cap->no];
738         dbl_link_onto(bd, &stp->large_objects);
739         stp->n_large_blocks++;
740         initBdescr(bd, stp);
741         bd->flags  = BF_PINNED | BF_LARGE;
742         bd->free   = bd->start;
743     }
744
745     p = bd->free;
746     bd->free += n;
747     return p;
748 }
749
750 /* -----------------------------------------------------------------------------
751    Write Barriers
752    -------------------------------------------------------------------------- */
753
754 /*
755    This is the write barrier for MUT_VARs, a.k.a. IORefs.  A
756    MUT_VAR_CLEAN object is not on the mutable list; a MUT_VAR_DIRTY
757    is.  When written to, a MUT_VAR_CLEAN turns into a MUT_VAR_DIRTY
758    and is put on the mutable list.
759 */
760 void
761 dirty_MUT_VAR(StgRegTable *reg, StgClosure *p)
762 {
763     Capability *cap = regTableToCapability(reg);
764     bdescr *bd;
765     if (p->header.info == &stg_MUT_VAR_CLEAN_info) {
766         p->header.info = &stg_MUT_VAR_DIRTY_info;
767         bd = Bdescr((StgPtr)p);
768         if (bd->gen_no > 0) recordMutableCap(p,cap,bd->gen_no);
769     }
770 }
771
772 // Setting a TSO's link field with a write barrier.
773 // It is *not* necessary to call this function when
774 //    * setting the link field to END_TSO_QUEUE
775 //    * putting a TSO on the blackhole_queue
776 //    * setting the link field of the currently running TSO, as it
777 //      will already be dirty.
778 void
779 setTSOLink (Capability *cap, StgTSO *tso, StgTSO *target)
780 {
781     bdescr *bd;
782     if (tso->dirty == 0 && (tso->flags & TSO_LINK_DIRTY) == 0) {
783         tso->flags |= TSO_LINK_DIRTY;
784         bd = Bdescr((StgPtr)tso);
785         if (bd->gen_no > 0) recordMutableCap((StgClosure*)tso,cap,bd->gen_no);
786     }
787     tso->_link = target;
788 }
789
790 void
791 dirty_TSO (Capability *cap, StgTSO *tso)
792 {
793     bdescr *bd;
794     if (tso->dirty == 0 && (tso->flags & TSO_LINK_DIRTY) == 0) {
795         bd = Bdescr((StgPtr)tso);
796         if (bd->gen_no > 0) recordMutableCap((StgClosure*)tso,cap,bd->gen_no);
797     }
798     tso->dirty = 1;
799 }
800
801 /*
802    This is the write barrier for MVARs.  An MVAR_CLEAN objects is not
803    on the mutable list; a MVAR_DIRTY is.  When written to, a
804    MVAR_CLEAN turns into a MVAR_DIRTY and is put on the mutable list.
805    The check for MVAR_CLEAN is inlined at the call site for speed,
806    this really does make a difference on concurrency-heavy benchmarks
807    such as Chaneneos and cheap-concurrency.
808 */
809 void
810 dirty_MVAR(StgRegTable *reg, StgClosure *p)
811 {
812     Capability *cap = regTableToCapability(reg);
813     bdescr *bd;
814     bd = Bdescr((StgPtr)p);
815     if (bd->gen_no > 0) recordMutableCap(p,cap,bd->gen_no);
816 }
817
818 /* -----------------------------------------------------------------------------
819  * Stats and stuff
820  * -------------------------------------------------------------------------- */
821
822 /* -----------------------------------------------------------------------------
823  * calcAllocated()
824  *
825  * Approximate how much we've allocated: number of blocks in the
826  * nursery + blocks allocated via allocate() - unused nusery blocks.
827  * This leaves a little slop at the end of each block, and doesn't
828  * take into account large objects (ToDo).
829  * -------------------------------------------------------------------------- */
830
831 lnat
832 calcAllocated( void )
833 {
834   nat allocated;
835   bdescr *bd;
836   nat i;
837
838   allocated = countNurseryBlocks() * BLOCK_SIZE_W;
839   
840   for (i = 0; i < n_capabilities; i++) {
841       Capability *cap;
842       for ( bd = capabilities[i].r.rCurrentNursery->link; 
843             bd != NULL; bd = bd->link ) {
844           allocated -= BLOCK_SIZE_W;
845       }
846       cap = &capabilities[i];
847       if (cap->r.rCurrentNursery->free < 
848           cap->r.rCurrentNursery->start + BLOCK_SIZE_W) {
849           allocated -= (cap->r.rCurrentNursery->start + BLOCK_SIZE_W)
850               - cap->r.rCurrentNursery->free;
851       }
852       if (cap->pinned_object_block != NULL) {
853           allocated -= (cap->pinned_object_block->start + BLOCK_SIZE_W) - 
854               cap->pinned_object_block->free;
855       }
856   }
857
858   total_allocated += allocated;
859   return allocated;
860 }  
861
862 /* Approximate the amount of live data in the heap.  To be called just
863  * after garbage collection (see GarbageCollect()).
864  */
865 lnat 
866 calcLiveBlocks(void)
867 {
868   nat g, s;
869   lnat live = 0;
870   step *stp;
871
872   for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
873     for (s = 0; s < generations[g].n_steps; s++) {
874       /* approximate amount of live data (doesn't take into account slop
875        * at end of each block).
876        */
877       if (g == 0 && s == 0 && RtsFlags.GcFlags.generations > 1) { 
878           continue; 
879       }
880       stp = &generations[g].steps[s];
881       live += stp->n_large_blocks + stp->n_blocks;
882     }
883   }
884   return live;
885 }
886
887 lnat
888 countOccupied(bdescr *bd)
889 {
890     lnat words;
891
892     words = 0;
893     for (; bd != NULL; bd = bd->link) {
894         ASSERT(bd->free <= bd->start + bd->blocks * BLOCK_SIZE_W);
895         words += bd->free - bd->start;
896     }
897     return words;
898 }
899
900 // Return an accurate count of the live data in the heap, excluding
901 // generation 0.
902 lnat
903 calcLiveWords(void)
904 {
905     nat g, s;
906     lnat live;
907     step *stp;
908     
909     live = 0;
910     for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
911         for (s = 0; s < generations[g].n_steps; s++) {
912             if (g == 0 && s == 0 && RtsFlags.GcFlags.generations > 1) continue; 
913             stp = &generations[g].steps[s];
914             live += stp->n_words + countOccupied(stp->large_objects);
915         } 
916     }
917     return live;
918 }
919
920 /* Approximate the number of blocks that will be needed at the next
921  * garbage collection.
922  *
923  * Assume: all data currently live will remain live.  Steps that will
924  * be collected next time will therefore need twice as many blocks
925  * since all the data will be copied.
926  */
927 extern lnat 
928 calcNeeded(void)
929 {
930     lnat needed = 0;
931     nat g, s;
932     step *stp;
933     
934     for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
935         for (s = 0; s < generations[g].n_steps; s++) {
936             if (g == 0 && s == 0) { continue; }
937             stp = &generations[g].steps[s];
938
939             // we need at least this much space
940             needed += stp->n_blocks + stp->n_large_blocks;
941
942             // any additional space needed to collect this gen next time?
943             if (g == 0 || // always collect gen 0
944                 (generations[g].steps[0].n_blocks +
945                  generations[g].steps[0].n_large_blocks 
946                  > generations[g].max_blocks)) {
947                 // we will collect this gen next time
948                 if (stp->mark) {
949                     //  bitmap:
950                     needed += stp->n_blocks / BITS_IN(W_);
951                     //  mark stack:
952                     needed += stp->n_blocks / 100;
953                 }
954                 if (stp->compact) {
955                     continue; // no additional space needed for compaction
956                 } else {
957                     needed += stp->n_blocks;
958                 }
959             }
960         }
961     }
962     return needed;
963 }
964
965 /* ----------------------------------------------------------------------------
966    Executable memory
967
968    Executable memory must be managed separately from non-executable
969    memory.  Most OSs these days require you to jump through hoops to
970    dynamically allocate executable memory, due to various security
971    measures.
972
973    Here we provide a small memory allocator for executable memory.
974    Memory is managed with a page granularity; we allocate linearly
975    in the page, and when the page is emptied (all objects on the page
976    are free) we free the page again, not forgetting to make it
977    non-executable.
978
979    TODO: The inability to handle objects bigger than BLOCK_SIZE_W means that
980          the linker cannot use allocateExec for loading object code files
981          on Windows. Once allocateExec can handle larger objects, the linker
982          should be modified to use allocateExec instead of VirtualAlloc.
983    ------------------------------------------------------------------------- */
984
985 #if defined(linux_HOST_OS)
986
987 // On Linux we need to use libffi for allocating executable memory,
988 // because it knows how to work around the restrictions put in place
989 // by SELinux.
990
991 void *allocateExec (nat bytes, void **exec_ret)
992 {
993     void **ret, **exec;
994     ACQUIRE_SM_LOCK;
995     ret = ffi_closure_alloc (sizeof(void *) + (size_t)bytes, (void**)&exec);
996     RELEASE_SM_LOCK;
997     if (ret == NULL) return ret;
998     *ret = ret; // save the address of the writable mapping, for freeExec().
999     *exec_ret = exec + 1;
1000     return (ret + 1);
1001 }
1002
1003 // freeExec gets passed the executable address, not the writable address. 
1004 void freeExec (void *addr)
1005 {
1006     void *writable;
1007     writable = *((void**)addr - 1);
1008     ACQUIRE_SM_LOCK;
1009     ffi_closure_free (writable);
1010     RELEASE_SM_LOCK
1011 }
1012
1013 #else
1014
1015 void *allocateExec (nat bytes, void **exec_ret)
1016 {
1017     void *ret;
1018     nat n;
1019
1020     ACQUIRE_SM_LOCK;
1021
1022     // round up to words.
1023     n  = (bytes + sizeof(W_) + 1) / sizeof(W_);
1024
1025     if (n+1 > BLOCK_SIZE_W) {
1026         barf("allocateExec: can't handle large objects");
1027     }
1028
1029     if (exec_block == NULL || 
1030         exec_block->free + n + 1 > exec_block->start + BLOCK_SIZE_W) {
1031         bdescr *bd;
1032         lnat pagesize = getPageSize();
1033         bd = allocGroup(stg_max(1, pagesize / BLOCK_SIZE));
1034         debugTrace(DEBUG_gc, "allocate exec block %p", bd->start);
1035         bd->gen_no = 0;
1036         bd->flags = BF_EXEC;
1037         bd->link = exec_block;
1038         if (exec_block != NULL) {
1039             exec_block->u.back = bd;
1040         }
1041         bd->u.back = NULL;
1042         setExecutable(bd->start, bd->blocks * BLOCK_SIZE, rtsTrue);
1043         exec_block = bd;
1044     }
1045     *(exec_block->free) = n;  // store the size of this chunk
1046     exec_block->gen_no += n;  // gen_no stores the number of words allocated
1047     ret = exec_block->free + 1;
1048     exec_block->free += n + 1;
1049
1050     RELEASE_SM_LOCK
1051     *exec_ret = ret;
1052     return ret;
1053 }
1054
1055 void freeExec (void *addr)
1056 {
1057     StgPtr p = (StgPtr)addr - 1;
1058     bdescr *bd = Bdescr((StgPtr)p);
1059
1060     if ((bd->flags & BF_EXEC) == 0) {
1061         barf("freeExec: not executable");
1062     }
1063
1064     if (*(StgPtr)p == 0) {
1065         barf("freeExec: already free?");
1066     }
1067
1068     ACQUIRE_SM_LOCK;
1069
1070     bd->gen_no -= *(StgPtr)p;
1071     *(StgPtr)p = 0;
1072
1073     if (bd->gen_no == 0) {
1074         // Free the block if it is empty, but not if it is the block at
1075         // the head of the queue.
1076         if (bd != exec_block) {
1077             debugTrace(DEBUG_gc, "free exec block %p", bd->start);
1078             dbl_link_remove(bd, &exec_block);
1079             setExecutable(bd->start, bd->blocks * BLOCK_SIZE, rtsFalse);
1080             freeGroup(bd);
1081         } else {
1082             bd->free = bd->start;
1083         }
1084     }
1085
1086     RELEASE_SM_LOCK
1087 }    
1088
1089 #endif /* mingw32_HOST_OS */
1090
1091 /* -----------------------------------------------------------------------------
1092    Debugging
1093
1094    memInventory() checks for memory leaks by counting up all the
1095    blocks we know about and comparing that to the number of blocks
1096    allegedly floating around in the system.
1097    -------------------------------------------------------------------------- */
1098
1099 #ifdef DEBUG
1100
1101 // Useful for finding partially full blocks in gdb
1102 void findSlop(bdescr *bd);
1103 void findSlop(bdescr *bd)
1104 {
1105     lnat slop;
1106
1107     for (; bd != NULL; bd = bd->link) {
1108         slop = (bd->blocks * BLOCK_SIZE_W) - (bd->free - bd->start);
1109         if (slop > (1024/sizeof(W_))) {
1110             debugBelch("block at %p (bdescr %p) has %ldKB slop\n",
1111                        bd->start, bd, slop / (1024/sizeof(W_)));
1112         }
1113     }
1114 }
1115
1116 nat
1117 countBlocks(bdescr *bd)
1118 {
1119     nat n;
1120     for (n=0; bd != NULL; bd=bd->link) {
1121         n += bd->blocks;
1122     }
1123     return n;
1124 }
1125
1126 // (*1) Just like countBlocks, except that we adjust the count for a
1127 // megablock group so that it doesn't include the extra few blocks
1128 // that would be taken up by block descriptors in the second and
1129 // subsequent megablock.  This is so we can tally the count with the
1130 // number of blocks allocated in the system, for memInventory().
1131 static nat
1132 countAllocdBlocks(bdescr *bd)
1133 {
1134     nat n;
1135     for (n=0; bd != NULL; bd=bd->link) {
1136         n += bd->blocks;
1137         // hack for megablock groups: see (*1) above
1138         if (bd->blocks > BLOCKS_PER_MBLOCK) {
1139             n -= (MBLOCK_SIZE / BLOCK_SIZE - BLOCKS_PER_MBLOCK)
1140                 * (bd->blocks/(MBLOCK_SIZE/BLOCK_SIZE));
1141         }
1142     }
1143     return n;
1144 }
1145
1146 static lnat
1147 stepBlocks (step *stp)
1148 {
1149     ASSERT(countBlocks(stp->blocks) == stp->n_blocks);
1150     ASSERT(countBlocks(stp->large_objects) == stp->n_large_blocks);
1151     return stp->n_blocks + stp->n_old_blocks + 
1152             countAllocdBlocks(stp->large_objects);
1153 }
1154
1155 // If memInventory() calculates that we have a memory leak, this
1156 // function will try to find the block(s) that are leaking by marking
1157 // all the ones that we know about, and search through memory to find
1158 // blocks that are not marked.  In the debugger this can help to give
1159 // us a clue about what kind of block leaked.  In the future we might
1160 // annotate blocks with their allocation site to give more helpful
1161 // info.
1162 static void
1163 findMemoryLeak (void)
1164 {
1165   nat g, s, i;
1166   for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1167       for (i = 0; i < n_capabilities; i++) {
1168           markBlocks(capabilities[i].mut_lists[g]);
1169       }
1170       markBlocks(generations[g].mut_list);
1171       for (s = 0; s < generations[g].n_steps; s++) {
1172           markBlocks(generations[g].steps[s].blocks);
1173           markBlocks(generations[g].steps[s].large_objects);
1174       }
1175   }
1176
1177   for (i = 0; i < n_nurseries; i++) {
1178       markBlocks(nurseries[i].blocks);
1179       markBlocks(nurseries[i].large_objects);
1180   }
1181
1182 #ifdef PROFILING
1183   // TODO:
1184   // if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER) {
1185   //    markRetainerBlocks();
1186   // }
1187 #endif
1188
1189   // count the blocks allocated by the arena allocator
1190   // TODO:
1191   // markArenaBlocks();
1192
1193   // count the blocks containing executable memory
1194   markBlocks(exec_block);
1195
1196   reportUnmarkedBlocks();
1197 }
1198
1199
1200 void
1201 memInventory (rtsBool show)
1202 {
1203   nat g, s, i;
1204   step *stp;
1205   lnat gen_blocks[RtsFlags.GcFlags.generations];
1206   lnat nursery_blocks, retainer_blocks,
1207        arena_blocks, exec_blocks;
1208   lnat live_blocks = 0, free_blocks = 0;
1209   rtsBool leak;
1210
1211   // count the blocks we current have
1212
1213   for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1214       gen_blocks[g] = 0;
1215       for (i = 0; i < n_capabilities; i++) {
1216           gen_blocks[g] += countBlocks(capabilities[i].mut_lists[g]);
1217       }   
1218       gen_blocks[g] += countAllocdBlocks(generations[g].mut_list);
1219       for (s = 0; s < generations[g].n_steps; s++) {
1220           stp = &generations[g].steps[s];
1221           gen_blocks[g] += stepBlocks(stp);
1222       }
1223   }
1224
1225   nursery_blocks = 0;
1226   for (i = 0; i < n_nurseries; i++) {
1227       nursery_blocks += stepBlocks(&nurseries[i]);
1228   }
1229
1230   retainer_blocks = 0;
1231 #ifdef PROFILING
1232   if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER) {
1233       retainer_blocks = retainerStackBlocks();
1234   }
1235 #endif
1236
1237   // count the blocks allocated by the arena allocator
1238   arena_blocks = arenaBlocks();
1239
1240   // count the blocks containing executable memory
1241   exec_blocks = countAllocdBlocks(exec_block);
1242
1243   /* count the blocks on the free list */
1244   free_blocks = countFreeList();
1245
1246   live_blocks = 0;
1247   for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1248       live_blocks += gen_blocks[g];
1249   }
1250   live_blocks += nursery_blocks + 
1251                + retainer_blocks + arena_blocks + exec_blocks;
1252
1253 #define MB(n) (((n) * BLOCK_SIZE_W) / ((1024*1024)/sizeof(W_)))
1254
1255   leak = live_blocks + free_blocks != mblocks_allocated * BLOCKS_PER_MBLOCK;
1256
1257   if (show || leak)
1258   {
1259       if (leak) { 
1260           debugBelch("Memory leak detected:\n");
1261       } else {
1262           debugBelch("Memory inventory:\n");
1263       }
1264       for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1265           debugBelch("  gen %d blocks : %5lu blocks (%lu MB)\n", g, 
1266                      gen_blocks[g], MB(gen_blocks[g]));
1267       }
1268       debugBelch("  nursery      : %5lu blocks (%lu MB)\n", 
1269                  nursery_blocks, MB(nursery_blocks));
1270       debugBelch("  retainer     : %5lu blocks (%lu MB)\n", 
1271                  retainer_blocks, MB(retainer_blocks));
1272       debugBelch("  arena blocks : %5lu blocks (%lu MB)\n", 
1273                  arena_blocks, MB(arena_blocks));
1274       debugBelch("  exec         : %5lu blocks (%lu MB)\n", 
1275                  exec_blocks, MB(exec_blocks));
1276       debugBelch("  free         : %5lu blocks (%lu MB)\n", 
1277                  free_blocks, MB(free_blocks));
1278       debugBelch("  total        : %5lu blocks (%lu MB)\n",
1279                  live_blocks + free_blocks, MB(live_blocks+free_blocks));
1280       if (leak) {
1281           debugBelch("\n  in system    : %5lu blocks (%lu MB)\n", 
1282                      mblocks_allocated * BLOCKS_PER_MBLOCK, mblocks_allocated);
1283       }
1284   }
1285
1286   if (leak) {
1287       debugBelch("\n");
1288       findMemoryLeak();
1289   }
1290   ASSERT(n_alloc_blocks == live_blocks);
1291   ASSERT(!leak);
1292 }
1293
1294
1295 /* Full heap sanity check. */
1296 void
1297 checkSanity( void )
1298 {
1299     nat g, s;
1300
1301     for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1302         for (s = 0; s < generations[g].n_steps; s++) {
1303             if (g == 0 && s == 0 && RtsFlags.GcFlags.generations > 1) { 
1304                 continue;
1305             }
1306             ASSERT(countBlocks(generations[g].steps[s].blocks)
1307                    == generations[g].steps[s].n_blocks);
1308             ASSERT(countBlocks(generations[g].steps[s].large_objects)
1309                    == generations[g].steps[s].n_large_blocks);
1310             checkHeap(generations[g].steps[s].blocks);
1311             checkLargeObjects(generations[g].steps[s].large_objects);
1312         }
1313     }
1314     
1315     for (s = 0; s < n_nurseries; s++) {
1316         ASSERT(countBlocks(nurseries[s].blocks)
1317                == nurseries[s].n_blocks);
1318         ASSERT(countBlocks(nurseries[s].large_objects)
1319                == nurseries[s].n_large_blocks);
1320     }
1321     
1322     checkFreeListSanity();
1323
1324 #if defined(THREADED_RTS)
1325     // check the stacks too in threaded mode, because we don't do a
1326     // full heap sanity check in this case (see checkHeap())
1327     checkMutableLists(rtsTrue);
1328 #else
1329     checkMutableLists(rtsFalse);
1330 #endif
1331 }
1332
1333 /* Nursery sanity check */
1334 void
1335 checkNurserySanity( step *stp )
1336 {
1337     bdescr *bd, *prev;
1338     nat blocks = 0;
1339
1340     prev = NULL;
1341     for (bd = stp->blocks; bd != NULL; bd = bd->link) {
1342         ASSERT(bd->u.back == prev);
1343         prev = bd;
1344         blocks += bd->blocks;
1345     }
1346     ASSERT(blocks == stp->n_blocks);
1347 }
1348
1349 // handy function for use in gdb, because Bdescr() is inlined.
1350 extern bdescr *_bdescr( StgPtr p );
1351
1352 bdescr *
1353 _bdescr( StgPtr p )
1354 {
1355     return Bdescr(p);
1356 }
1357
1358 #endif