[project @ 1999-11-09 15:46:49 by simonmar]
[ghc-hetmet.git] / ghc / rts / Storage.c
1 /* -----------------------------------------------------------------------------
2  * $Id: Storage.c,v 1.21 1999/11/09 15:46:59 simonmar Exp $
3  *
4  * (c) The GHC Team, 1998-1999
5  *
6  * Storage manager front end
7  *
8  * ---------------------------------------------------------------------------*/
9
10 #include "Rts.h"
11 #include "RtsUtils.h"
12 #include "RtsFlags.h"
13 #include "Stats.h"
14 #include "Hooks.h"
15 #include "BlockAlloc.h"
16 #include "MBlock.h"
17 #include "gmp.h"
18 #include "Weak.h"
19 #include "Sanity.h"
20
21 #include "Storage.h"
22 #include "Schedule.h"
23 #include "StoragePriv.h"
24
25 #ifndef SMP
26 nat nursery_blocks;             /* number of blocks in the nursery */
27 #endif
28
29 StgClosure    *caf_list         = NULL;
30
31 bdescr *small_alloc_list;       /* allocate()d small objects */
32 bdescr *large_alloc_list;       /* allocate()d large objects */
33 nat alloc_blocks;               /* number of allocate()d blocks since GC */
34 nat alloc_blocks_lim;           /* approximate limit on alloc_blocks */
35
36 StgPtr alloc_Hp    = NULL;      /* next free byte in small_alloc_list */
37 StgPtr alloc_HpLim = NULL;      /* end of block at small_alloc_list   */
38
39 generation *generations;        /* all the generations */
40 generation *g0;                 /* generation 0, for convenience */
41 generation *oldest_gen;         /* oldest generation, for convenience */
42 step *g0s0;                     /* generation 0, step 0, for convenience */
43
44 /*
45  * Storage manager mutex:  protects all the above state from
46  * simultaneous access by two STG threads.
47  */
48 #ifdef SMP
49 pthread_mutex_t sm_mutex = PTHREAD_MUTEX_INITIALIZER;
50 #endif
51
52 /*
53  * Forward references
54  */
55 static void *stgAllocForGMP   (size_t size_in_bytes);
56 static void *stgReallocForGMP (void *ptr, size_t old_size, size_t new_size);
57 static void  stgDeallocForGMP (void *ptr, size_t size);
58
59 void
60 initStorage (void)
61 {
62   nat g, s;
63   step *step;
64   generation *gen;
65
66   /* If we're doing heap profiling, we want a two-space heap with a
67    * fixed-size allocation area so that we get roughly even-spaced
68    * samples.
69    */
70 #if defined(PROFILING) || defined(DEBUG)
71   if (RtsFlags.ProfFlags.doHeapProfile) {
72     RtsFlags.GcFlags.generations = 1;
73     RtsFlags.GcFlags.steps = 1;
74     RtsFlags.GcFlags.oldGenFactor = 0;
75     RtsFlags.GcFlags.heapSizeSuggestion = 0;
76   }
77 #endif
78
79   if (RtsFlags.GcFlags.heapSizeSuggestion > 
80       RtsFlags.GcFlags.maxHeapSize) {
81     RtsFlags.GcFlags.maxHeapSize = RtsFlags.GcFlags.heapSizeSuggestion;
82   }
83
84   initBlockAllocator();
85   
86   /* allocate generation info array */
87   generations = (generation *)stgMallocBytes(RtsFlags.GcFlags.generations 
88                                              * sizeof(struct _generation),
89                                              "initStorage: gens");
90
91   /* Initialise all generations */
92   for(g = 0; g < RtsFlags.GcFlags.generations; g++) {
93     gen = &generations[g];
94     gen->no = g;
95     gen->mut_list = END_MUT_LIST;
96     gen->mut_once_list = END_MUT_LIST;
97     gen->collections = 0;
98     gen->failed_promotions = 0;
99     gen->max_blocks = 0;
100   }
101
102   /* A couple of convenience pointers */
103   g0 = &generations[0];
104   oldest_gen = &generations[RtsFlags.GcFlags.generations-1];
105
106   /* Allocate step structures in each generation */
107   if (RtsFlags.GcFlags.generations > 1) {
108     /* Only for multiple-generations */
109
110     /* Oldest generation: one step */
111     oldest_gen->n_steps = 1;
112     oldest_gen->steps = 
113       stgMallocBytes(1 * sizeof(struct _step), "initStorage: last step");
114
115     /* set up all except the oldest generation with 2 steps */
116     for(g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
117       generations[g].n_steps = RtsFlags.GcFlags.steps;
118       generations[g].steps  = 
119         stgMallocBytes (RtsFlags.GcFlags.steps * sizeof(struct _step),
120                         "initStorage: steps");
121     }
122     
123   } else {
124     /* single generation, i.e. a two-space collector */
125     g0->n_steps = 1;
126     g0->steps = stgMallocBytes (sizeof(struct _step), "initStorage: steps");
127   }
128
129   /* Initialise all steps */
130   for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
131     for (s = 0; s < generations[g].n_steps; s++) {
132       step = &generations[g].steps[s];
133       step->no = s;
134       step->blocks = NULL;
135       step->n_blocks = 0;
136       step->gen = &generations[g];
137       step->hp = NULL;
138       step->hpLim = NULL;
139       step->hp_bd = NULL;
140       step->scan = NULL;
141       step->scan_bd = NULL;
142       step->large_objects = NULL;
143       step->new_large_objects = NULL;
144       step->scavenged_large_objects = NULL;
145     }
146   }
147   
148   /* Set up the destination pointers in each younger gen. step */
149   for (g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
150     for (s = 0; s < generations[g].n_steps-1; s++) {
151       generations[g].steps[s].to = &generations[g].steps[s+1];
152     }
153     generations[g].steps[s].to = &generations[g+1].steps[0];
154   }
155   
156   /* The oldest generation has one step and its destination is the
157    * same step. */
158   oldest_gen->steps[0].to = &oldest_gen->steps[0];
159
160   /* generation 0 is special: that's the nursery */
161   generations[0].max_blocks = 0;
162
163   /* G0S0: the allocation area.  Policy: keep the allocation area
164    * small to begin with, even if we have a large suggested heap
165    * size.  Reason: we're going to do a major collection first, and we
166    * don't want it to be a big one.  This vague idea is borne out by 
167    * rigorous experimental evidence.
168    */
169   g0s0 = &generations[0].steps[0];
170
171   allocNurseries();
172
173   weak_ptr_list = NULL;
174   caf_list = NULL;
175    
176   /* initialise the allocate() interface */
177   small_alloc_list = NULL;
178   large_alloc_list = NULL;
179   alloc_blocks = 0;
180   alloc_blocks_lim = RtsFlags.GcFlags.minAllocAreaSize;
181
182 #ifdef COMPILER
183   /* Tell GNU multi-precision pkg about our custom alloc functions */
184   mp_set_memory_functions(stgAllocForGMP, stgReallocForGMP, stgDeallocForGMP);
185 #endif
186
187 #ifdef SMP
188   pthread_mutex_init(&sm_mutex, NULL);
189 #endif
190
191   IF_DEBUG(gc, stat_describe_gens());
192 }
193
194 void
195 exitStorage (void)
196 {
197   stat_exit(calcAllocated());
198 }
199
200 void
201 newCAF(StgClosure* caf)
202 {
203   /* Put this CAF on the mutable list for the old generation.
204    * This is a HACK - the IND_STATIC closure doesn't really have
205    * a mut_link field, but we pretend it has - in fact we re-use
206    * the STATIC_LINK field for the time being, because when we
207    * come to do a major GC we won't need the mut_link field
208    * any more and can use it as a STATIC_LINK.
209    */
210   ACQUIRE_LOCK(&sm_mutex);
211   ((StgMutClosure *)caf)->mut_link = oldest_gen->mut_once_list;
212   oldest_gen->mut_once_list = (StgMutClosure *)caf;
213
214 #ifdef DEBUG
215   { 
216     const StgInfoTable *info;
217     
218     info = get_itbl(caf);
219     ASSERT(info->type == IND_STATIC);
220 #if 0
221     STATIC_LINK2(info,caf) = caf_list;
222     caf_list = caf;
223 #endif
224   }
225 #endif
226   RELEASE_LOCK(&sm_mutex);
227 }
228
229 /* -----------------------------------------------------------------------------
230    Nursery management.
231    -------------------------------------------------------------------------- */
232
233 void
234 allocNurseries( void )
235
236 #ifdef SMP
237   {
238     Capability *cap;
239     bdescr *bd;
240
241     g0s0->blocks = NULL;
242     g0s0->n_blocks = 0;
243     for (cap = free_capabilities; cap != NULL; cap = cap->link) {
244       cap->rNursery = allocNursery(NULL, RtsFlags.GcFlags.minAllocAreaSize);
245       cap->rCurrentNursery = cap->rNursery;
246       for (bd = cap->rNursery; bd != NULL; bd = bd->link) {
247         bd->back = (bdescr *)cap;
248       }
249     }
250     /* Set the back links to be equal to the Capability,
251      * so we can do slightly better informed locking.
252      */
253   }
254 #else /* SMP */
255   nursery_blocks  = RtsFlags.GcFlags.minAllocAreaSize;
256   g0s0->blocks    = allocNursery(NULL, nursery_blocks);
257   g0s0->n_blocks  = nursery_blocks;
258   g0s0->to_space  = NULL;
259   MainRegTable.rNursery        = g0s0->blocks;
260   MainRegTable.rCurrentNursery = g0s0->blocks;
261   /* hp, hpLim, hp_bd, to_space etc. aren't used in G0S0 */
262 #endif
263 }
264       
265 void
266 resetNurseries( void )
267 {
268   bdescr *bd;
269 #ifdef SMP
270   Capability *cap;
271   
272   /* All tasks must be stopped */
273   ASSERT(n_free_capabilities == RtsFlags.ConcFlags.nNodes);
274
275   for (cap = free_capabilities; cap != NULL; cap = cap->link) {
276     for (bd = cap->rNursery; bd; bd = bd->link) {
277       bd->free = bd->start;
278       ASSERT(bd->gen == g0);
279       ASSERT(bd->step == g0s0);
280       IF_DEBUG(sanity,memset(bd->start, 0xaa, BLOCK_SIZE));
281     }
282     cap->rCurrentNursery = cap->rNursery;
283   }
284 #else
285   for (bd = g0s0->blocks; bd; bd = bd->link) {
286     bd->free = bd->start;
287     ASSERT(bd->gen == g0);
288     ASSERT(bd->step == g0s0);
289     IF_DEBUG(sanity,memset(bd->start, 0xaa, BLOCK_SIZE));
290   }
291   MainRegTable.rNursery = g0s0->blocks;
292   MainRegTable.rCurrentNursery = g0s0->blocks;
293 #endif
294 }
295
296 bdescr *
297 allocNursery (bdescr *last_bd, nat blocks)
298 {
299   bdescr *bd;
300   nat i;
301
302   /* Allocate a nursery */
303   for (i=0; i < blocks; i++) {
304     bd = allocBlock();
305     bd->link = last_bd;
306     bd->step = g0s0;
307     bd->gen = g0;
308     bd->evacuated = 0;
309     bd->free = bd->start;
310     last_bd = bd;
311   }
312   return last_bd;
313 }
314
315 void
316 resizeNursery ( nat blocks )
317 {
318   bdescr *bd;
319
320 #ifdef SMP
321   barf("resizeNursery: can't resize in SMP mode");
322 #endif
323
324   if (nursery_blocks == blocks) {
325     ASSERT(g0s0->n_blocks == blocks);
326     return;
327   }
328
329   else if (nursery_blocks < blocks) {
330     IF_DEBUG(gc, fprintf(stderr, "Increasing size of nursery to %d blocks\n", 
331                          blocks));
332     g0s0->blocks = allocNursery(g0s0->blocks, blocks-nursery_blocks);
333   } 
334
335   else {
336     bdescr *next_bd;
337     
338     IF_DEBUG(gc, fprintf(stderr, "Decreasing size of nursery to %d blocks\n", 
339                          blocks));
340     for (bd = g0s0->blocks; nursery_blocks > blocks; nursery_blocks--) {
341       next_bd = bd->link;
342       freeGroup(bd);
343       bd = next_bd;
344     }
345     g0s0->blocks = bd;
346   }
347   
348   g0s0->n_blocks = nursery_blocks = blocks;
349 }
350
351 /* -----------------------------------------------------------------------------
352    The allocate() interface
353
354    allocate(n) always succeeds, and returns a chunk of memory n words
355    long.  n can be larger than the size of a block if necessary, in
356    which case a contiguous block group will be allocated.
357    -------------------------------------------------------------------------- */
358
359 StgPtr
360 allocate(nat n)
361 {
362   bdescr *bd;
363   StgPtr p;
364
365   ACQUIRE_LOCK(&sm_mutex);
366
367   TICK_ALLOC_HEAP_NOCTR(n);
368   CCS_ALLOC(CCCS,n);
369
370   /* big allocation (>LARGE_OBJECT_THRESHOLD) */
371   /* ToDo: allocate directly into generation 1 */
372   if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
373     nat req_blocks =  (lnat)BLOCK_ROUND_UP(n*sizeof(W_)) / BLOCK_SIZE;
374     bd = allocGroup(req_blocks);
375     dbl_link_onto(bd, &g0s0->large_objects);
376     bd->gen  = g0;
377     bd->step = g0s0;
378     bd->evacuated = 0;
379     bd->free = bd->start;
380     /* don't add these blocks to alloc_blocks, since we're assuming
381      * that large objects are likely to remain live for quite a while
382      * (eg. running threads), so garbage collecting early won't make
383      * much difference.
384      */
385     RELEASE_LOCK(&sm_mutex);
386     return bd->start;
387
388   /* small allocation (<LARGE_OBJECT_THRESHOLD) */
389   } else if (small_alloc_list == NULL || alloc_Hp + n > alloc_HpLim) {
390     if (small_alloc_list) {
391       small_alloc_list->free = alloc_Hp;
392     }
393     bd = allocBlock();
394     bd->link = small_alloc_list;
395     small_alloc_list = bd;
396     bd->gen = g0;
397     bd->step = g0s0;
398     bd->evacuated = 0;
399     alloc_Hp = bd->start;
400     alloc_HpLim = bd->start + BLOCK_SIZE_W;
401     alloc_blocks++;
402   }
403   
404   p = alloc_Hp;
405   alloc_Hp += n;
406   RELEASE_LOCK(&sm_mutex);
407   return p;
408 }
409
410 lnat allocated_bytes(void)
411 {
412   return (alloc_blocks * BLOCK_SIZE_W - (alloc_HpLim - alloc_Hp));
413 }
414
415 /* -----------------------------------------------------------------------------
416    Allocation functions for GMP.
417
418    These all use the allocate() interface - we can't have any garbage
419    collection going on during a gmp operation, so we use allocate()
420    which always succeeds.  The gmp operations which might need to
421    allocate will ask the storage manager (via doYouWantToGC()) whether
422    a garbage collection is required, in case we get into a loop doing
423    only allocate() style allocation.
424    -------------------------------------------------------------------------- */
425
426 static void *
427 stgAllocForGMP (size_t size_in_bytes)
428 {
429   StgArrWords* arr;
430   nat data_size_in_words, total_size_in_words;
431   
432   /* should be a multiple of sizeof(StgWord) (whole no. of limbs) */
433   ASSERT(size_in_bytes % sizeof(W_) == 0);
434   
435   data_size_in_words  = size_in_bytes / sizeof(W_);
436   total_size_in_words = sizeofW(StgArrWords) + data_size_in_words;
437   
438   /* allocate and fill it in. */
439   arr = (StgArrWords *)allocate(total_size_in_words);
440   SET_ARR_HDR(arr, &ARR_WORDS_info, CCCS, data_size_in_words);
441   
442   /* and return a ptr to the goods inside the array */
443   return(BYTE_ARR_CTS(arr));
444 }
445
446 static void *
447 stgReallocForGMP (void *ptr, size_t old_size, size_t new_size)
448 {
449     void *new_stuff_ptr = stgAllocForGMP(new_size);
450     nat i = 0;
451     char *p = (char *) ptr;
452     char *q = (char *) new_stuff_ptr;
453
454     for (; i < old_size; i++, p++, q++) {
455         *q = *p;
456     }
457
458     return(new_stuff_ptr);
459 }
460
461 static void
462 stgDeallocForGMP (void *ptr STG_UNUSED, 
463                   size_t size STG_UNUSED)
464 {
465     /* easy for us: the garbage collector does the dealloc'n */
466 }
467
468 /* -----------------------------------------------------------------------------
469  * Stats and stuff
470  * -------------------------------------------------------------------------- */
471
472 /* -----------------------------------------------------------------------------
473  * calcAllocated()
474  *
475  * Approximate how much we've allocated: number of blocks in the
476  * nursery + blocks allocated via allocate() - unused nusery blocks.
477  * This leaves a little slop at the end of each block, and doesn't
478  * take into account large objects (ToDo).
479  * -------------------------------------------------------------------------- */
480
481 lnat
482 calcAllocated( void )
483 {
484   nat allocated;
485   bdescr *bd;
486
487 #ifdef SMP
488   Capability *cap;
489
490   /* All tasks must be stopped.  Can't assert that all the
491      capabilities are owned by the scheduler, though: one or more
492      tasks might have been stopped while they were running (non-main)
493      threads. */
494   /*  ASSERT(n_free_capabilities == RtsFlags.ConcFlags.nNodes); */
495
496   allocated = 
497     n_free_capabilities * RtsFlags.GcFlags.minAllocAreaSize * BLOCK_SIZE_W
498     + allocated_bytes();
499
500   for (cap = free_capabilities; cap != NULL; cap = cap->link) {
501     for ( bd = cap->rCurrentNursery->link; bd != NULL; bd = bd->link ) {
502       allocated -= BLOCK_SIZE_W;
503     }
504     if (cap->rCurrentNursery->free < cap->rCurrentNursery->start 
505         + BLOCK_SIZE_W) {
506       allocated -= (cap->rCurrentNursery->start + BLOCK_SIZE_W)
507         - cap->rCurrentNursery->free;
508     }
509   }
510
511 #else /* !SMP */
512   bdescr *current_nursery = MainRegTable.rCurrentNursery;
513
514   allocated = (nursery_blocks * BLOCK_SIZE_W) + allocated_bytes();
515   for ( bd = current_nursery->link; bd != NULL; bd = bd->link ) {
516     allocated -= BLOCK_SIZE_W;
517   }
518   if (current_nursery->free < current_nursery->start + BLOCK_SIZE_W) {
519     allocated -= (current_nursery->start + BLOCK_SIZE_W)
520       - current_nursery->free;
521   }
522 #endif
523
524   return allocated;
525 }  
526
527 /* Approximate the amount of live data in the heap.  To be called just
528  * after garbage collection (see GarbageCollect()).
529  */
530 extern lnat 
531 calcLive(void)
532 {
533   nat g, s;
534   lnat live = 0;
535   step *step;
536
537   if (RtsFlags.GcFlags.generations == 1) {
538     live = (g0s0->to_blocks - 1) * BLOCK_SIZE_W + 
539       ((lnat)g0s0->hp_bd->free - (lnat)g0s0->hp_bd->start) / sizeof(W_);
540     return live;
541   }
542
543   for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
544     for (s = 0; s < generations[g].n_steps; s++) {
545       /* approximate amount of live data (doesn't take into account slop
546        * at end of each block).
547        */
548       if (g == 0 && s == 0) { 
549           continue; 
550       }
551       step = &generations[g].steps[s];
552       live += (step->n_blocks - 1) * BLOCK_SIZE_W +
553         ((lnat)step->hp_bd->free - (lnat)step->hp_bd->start) / sizeof(W_);
554     }
555   }
556   return live;
557 }
558
559 /* Approximate the number of blocks that will be needed at the next
560  * garbage collection.
561  *
562  * Assume: all data currently live will remain live.  Steps that will
563  * be collected next time will therefore need twice as many blocks
564  * since all the data will be copied.
565  */
566 extern lnat 
567 calcNeeded(void)
568 {
569   lnat needed = 0;
570   nat g, s;
571   step *step;
572
573   for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
574     for (s = 0; s < generations[g].n_steps; s++) {
575       if (g == 0 && s == 0) { continue; }
576       step = &generations[g].steps[s];
577       if (generations[g].steps[0].n_blocks > generations[g].max_blocks) {
578         needed += 2 * step->n_blocks;
579       } else {
580         needed += step->n_blocks;
581       }
582     }
583   }
584   return needed;
585 }
586
587 /* -----------------------------------------------------------------------------
588    Debugging
589
590    memInventory() checks for memory leaks by counting up all the
591    blocks we know about and comparing that to the number of blocks
592    allegedly floating around in the system.
593    -------------------------------------------------------------------------- */
594
595 #ifdef DEBUG
596
597 extern void
598 memInventory(void)
599 {
600   nat g, s;
601   step *step;
602   bdescr *bd;
603   lnat total_blocks = 0, free_blocks = 0;
604
605   /* count the blocks we current have */
606
607   for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
608     for (s = 0; s < generations[g].n_steps; s++) {
609       step = &generations[g].steps[s];
610       total_blocks += step->n_blocks;
611       if (RtsFlags.GcFlags.generations == 1) {
612         /* two-space collector has a to-space too :-) */
613         total_blocks += g0s0->to_blocks;
614       }
615       for (bd = step->large_objects; bd; bd = bd->link) {
616         total_blocks += bd->blocks;
617         /* hack for megablock groups: they have an extra block or two in
618            the second and subsequent megablocks where the block
619            descriptors would normally go.
620         */
621         if (bd->blocks > BLOCKS_PER_MBLOCK) {
622           total_blocks -= (MBLOCK_SIZE / BLOCK_SIZE - BLOCKS_PER_MBLOCK)
623                           * (bd->blocks/(MBLOCK_SIZE/BLOCK_SIZE));
624         }
625       }
626     }
627   }
628
629   /* any blocks held by allocate() */
630   for (bd = small_alloc_list; bd; bd = bd->link) {
631     total_blocks += bd->blocks;
632   }
633   for (bd = large_alloc_list; bd; bd = bd->link) {
634     total_blocks += bd->blocks;
635   }
636   
637   /* count the blocks on the free list */
638   free_blocks = countFreeList();
639
640   ASSERT(total_blocks + free_blocks == mblocks_allocated * BLOCKS_PER_MBLOCK);
641
642 #if 0
643   if (total_blocks + free_blocks != mblocks_allocated *
644       BLOCKS_PER_MBLOCK) {
645     fprintf(stderr, "Blocks: %ld live + %ld free  = %ld total (%ld around)\n",
646             total_blocks, free_blocks, total_blocks + free_blocks,
647             mblocks_allocated * BLOCKS_PER_MBLOCK);
648   }
649 #endif
650 }
651
652 /* Full heap sanity check. */
653
654 extern void
655 checkSanity(nat N)
656 {
657   nat g, s;
658
659   if (RtsFlags.GcFlags.generations == 1) {
660     checkHeap(g0s0->to_space, NULL);
661     checkChain(g0s0->large_objects);
662   } else {
663     
664     for (g = 0; g <= N; g++) {
665       for (s = 0; s < generations[g].n_steps; s++) {
666         if (g == 0 && s == 0) { continue; }
667         checkHeap(generations[g].steps[s].blocks, NULL);
668       }
669     }
670     for (g = N+1; g < RtsFlags.GcFlags.generations; g++) {
671       for (s = 0; s < generations[g].n_steps; s++) {
672         checkHeap(generations[g].steps[s].blocks,
673                   generations[g].steps[s].blocks->start);
674         checkChain(generations[g].steps[s].large_objects);
675       }
676     }
677     checkFreeListSanity();
678   }
679 }
680
681 #endif