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