Refactor PAPI support, and add profiling of multithreaded GC
[ghc-hetmet.git] / rts / sm / GC.c
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team 1998-2006
4  *
5  * Generational garbage collector
6  *
7  * Documentation on the architecture of the Garbage Collector can be
8  * found in the online commentary:
9  * 
10  *   http://hackage.haskell.org/trac/ghc/wiki/Commentary/Rts/Storage/GC
11  *
12  * ---------------------------------------------------------------------------*/
13
14 #include "PosixSource.h"
15 #include "Rts.h"
16 #include "RtsFlags.h"
17 #include "RtsUtils.h"
18 #include "Apply.h"
19 #include "OSThreads.h"
20 #include "LdvProfile.h"
21 #include "Updates.h"
22 #include "Stats.h"
23 #include "Schedule.h"
24 #include "Sanity.h"
25 #include "BlockAlloc.h"
26 #include "MBlock.h"
27 #include "ProfHeap.h"
28 #include "SchedAPI.h"
29 #include "Weak.h"
30 #include "Prelude.h"
31 #include "ParTicky.h"           // ToDo: move into Rts.h
32 #include "RtsSignals.h"
33 #include "STM.h"
34 #include "HsFFI.h"
35 #include "Linker.h"
36 #if defined(RTS_GTK_FRONTPANEL)
37 #include "FrontPanel.h"
38 #endif
39 #include "Trace.h"
40 #include "RetainerProfile.h"
41 #include "RaiseAsync.h"
42 #include "Sparks.h"
43 #include "Papi.h"
44
45 #include "GC.h"
46 #include "Compact.h"
47 #include "Evac.h"
48 #include "Scav.h"
49 #include "GCUtils.h"
50 #include "MarkWeak.h"
51 #include "Sparks.h"
52
53 #include <string.h> // for memset()
54
55 /* -----------------------------------------------------------------------------
56    Global variables
57    -------------------------------------------------------------------------- */
58
59 /* STATIC OBJECT LIST.
60  *
61  * During GC:
62  * We maintain a linked list of static objects that are still live.
63  * The requirements for this list are:
64  *
65  *  - we need to scan the list while adding to it, in order to
66  *    scavenge all the static objects (in the same way that
67  *    breadth-first scavenging works for dynamic objects).
68  *
69  *  - we need to be able to tell whether an object is already on
70  *    the list, to break loops.
71  *
72  * Each static object has a "static link field", which we use for
73  * linking objects on to the list.  We use a stack-type list, consing
74  * objects on the front as they are added (this means that the
75  * scavenge phase is depth-first, not breadth-first, but that
76  * shouldn't matter).  
77  *
78  * A separate list is kept for objects that have been scavenged
79  * already - this is so that we can zero all the marks afterwards.
80  *
81  * An object is on the list if its static link field is non-zero; this
82  * means that we have to mark the end of the list with '1', not NULL.  
83  *
84  * Extra notes for generational GC:
85  *
86  * Each generation has a static object list associated with it.  When
87  * collecting generations up to N, we treat the static object lists
88  * from generations > N as roots.
89  *
90  * We build up a static object list while collecting generations 0..N,
91  * which is then appended to the static object list of generation N+1.
92  */
93 StgClosure* static_objects;      // live static objects
94 StgClosure* scavenged_static_objects;   // static objects scavenged so far
95 #ifdef THREADED_RTS
96 SpinLock static_objects_sync;
97 #endif
98
99 /* N is the oldest generation being collected, where the generations
100  * are numbered starting at 0.  A major GC (indicated by the major_gc
101  * flag) is when we're collecting all generations.  We only attempt to
102  * deal with static objects and GC CAFs when doing a major GC.
103  */
104 nat N;
105 rtsBool major_gc;
106
107 /* Data used for allocation area sizing.
108  */
109 static lnat g0s0_pcnt_kept = 30; // percentage of g0s0 live at last minor GC 
110
111 /* Mut-list stats */
112 #ifdef DEBUG
113 nat mutlist_MUTVARS,
114     mutlist_MUTARRS,
115     mutlist_MVARS,
116     mutlist_OTHERS;
117 #endif
118
119 /* Thread-local data for each GC thread
120  */
121 gc_thread *gc_threads = NULL;
122 // gc_thread *gct = NULL;  // this thread's gct TODO: make thread-local
123
124 // For stats:
125 long copied;        // *words* copied & scavenged during this GC
126
127 #ifdef THREADED_RTS
128 SpinLock recordMutableGen_sync;
129 #endif
130
131 /* -----------------------------------------------------------------------------
132    Static function declarations
133    -------------------------------------------------------------------------- */
134
135 static void mark_root               (StgClosure **root);
136 static void zero_static_object_list (StgClosure* first_static);
137 static void initialise_N            (rtsBool force_major_gc);
138 static void alloc_gc_threads        (void);
139 static void init_collected_gen      (nat g, nat threads);
140 static void init_uncollected_gen    (nat g, nat threads);
141 static void init_gc_thread          (gc_thread *t);
142 static void update_task_list        (void);
143 static void resize_generations      (void);
144 static void resize_nursery          (void);
145 static void start_gc_threads        (void);
146 static void gc_thread_work          (void);
147 static nat  inc_running             (void);
148 static nat  dec_running             (void);
149 static void wakeup_gc_threads       (nat n_threads);
150
151 #if 0 && defined(DEBUG)
152 static void gcCAFs                  (void);
153 #endif
154
155 /* -----------------------------------------------------------------------------
156    The mark bitmap & stack.
157    -------------------------------------------------------------------------- */
158
159 #define MARK_STACK_BLOCKS 4
160
161 bdescr *mark_stack_bdescr;
162 StgPtr *mark_stack;
163 StgPtr *mark_sp;
164 StgPtr *mark_splim;
165
166 // Flag and pointers used for falling back to a linear scan when the
167 // mark stack overflows.
168 rtsBool mark_stack_overflowed;
169 bdescr *oldgen_scan_bd;
170 StgPtr  oldgen_scan;
171
172 /* -----------------------------------------------------------------------------
173    GarbageCollect: the main entry point to the garbage collector.
174
175    Locks held: all capabilities are held throughout GarbageCollect().
176    -------------------------------------------------------------------------- */
177
178 void
179 GarbageCollect ( rtsBool force_major_gc )
180 {
181   bdescr *bd;
182   step *stp;
183   lnat live, allocated;
184   lnat oldgen_saved_blocks = 0;
185   nat n_threads; // number of threads participating in GC
186   gc_thread *saved_gct;
187   nat g, s, t;
188
189   // necessary if we stole a callee-saves register for gct:
190   saved_gct = gct;
191
192 #ifdef PROFILING
193   CostCentreStack *prev_CCS;
194 #endif
195
196   ACQUIRE_SM_LOCK;
197
198   debugTrace(DEBUG_gc, "starting GC");
199
200 #if defined(RTS_USER_SIGNALS)
201   if (RtsFlags.MiscFlags.install_signal_handlers) {
202     // block signals
203     blockUserSignals();
204   }
205 #endif
206
207   // tell the STM to discard any cached closures it's hoping to re-use
208   stmPreGCHook();
209
210   // tell the stats department that we've started a GC 
211   stat_startGC();
212
213 #ifdef DEBUG
214   // check for memory leaks if DEBUG is on 
215   memInventory();
216 #endif
217
218 #ifdef DEBUG
219   mutlist_MUTVARS = 0;
220   mutlist_MUTARRS = 0;
221   mutlist_OTHERS = 0;
222 #endif
223
224   // attribute any costs to CCS_GC 
225 #ifdef PROFILING
226   prev_CCS = CCCS;
227   CCCS = CCS_GC;
228 #endif
229
230   /* Approximate how much we allocated.  
231    * Todo: only when generating stats? 
232    */
233   allocated = calcAllocated();
234
235   /* Figure out which generation to collect
236    */
237   initialise_N(force_major_gc);
238
239   /* Allocate + initialise the gc_thread structures.
240    */
241   alloc_gc_threads();
242
243   /* Start threads, so they can be spinning up while we finish initialisation.
244    */
245   start_gc_threads();
246
247   /* How many threads will be participating in this GC?
248    * We don't try to parallelise minor GC.
249    */
250 #if defined(THREADED_RTS)
251   if (N == 0) {
252       n_threads = 1;
253   } else {
254       n_threads = RtsFlags.ParFlags.gcThreads;
255   }
256 #else
257   n_threads = 1;
258 #endif
259
260 #ifdef RTS_GTK_FRONTPANEL
261   if (RtsFlags.GcFlags.frontpanel) {
262       updateFrontPanelBeforeGC(N);
263   }
264 #endif
265
266   // check stack sanity *before* GC (ToDo: check all threads) 
267   IF_DEBUG(sanity, checkFreeListSanity());
268
269   /* Initialise the static object lists
270    */
271   static_objects = END_OF_STATIC_LIST;
272   scavenged_static_objects = END_OF_STATIC_LIST;
273
274 #ifdef THREADED_RTS
275   initSpinLock(&static_objects_sync);
276   initSpinLock(&recordMutableGen_sync);
277   initSpinLock(&gc_alloc_block_sync);
278 #endif
279
280   // Initialise all the generations/steps that we're collecting.
281   for (g = 0; g <= N; g++) {
282       init_collected_gen(g,n_threads);
283   }
284   
285   // Initialise all the generations/steps that we're *not* collecting.
286   for (g = N+1; g < RtsFlags.GcFlags.generations; g++) {
287       init_uncollected_gen(g,n_threads);
288   }
289
290   /* Allocate a mark stack if we're doing a major collection.
291    */
292   if (major_gc) {
293       mark_stack_bdescr = allocGroup(MARK_STACK_BLOCKS);
294       mark_stack = (StgPtr *)mark_stack_bdescr->start;
295       mark_sp    = mark_stack;
296       mark_splim = mark_stack + (MARK_STACK_BLOCKS * BLOCK_SIZE_W);
297   } else {
298       mark_stack_bdescr = NULL;
299   }
300
301   // Initialise all our gc_thread structures
302   for (t = 0; t < n_threads; t++) {
303       init_gc_thread(&gc_threads[t]);
304   }
305
306   // the main thread is running: this prevents any other threads from
307   // exiting prematurely, so we can start them now.
308   inc_running();
309   wakeup_gc_threads(n_threads);
310
311   // Initialise stats
312   copied = 0;
313
314   // this is the main thread
315   gct = &gc_threads[0];
316
317   /* -----------------------------------------------------------------------
318    * follow all the roots that we know about:
319    *   - mutable lists from each generation > N
320    * we want to *scavenge* these roots, not evacuate them: they're not
321    * going to move in this GC.
322    * Also do them in reverse generation order, for the usual reason:
323    * namely to reduce the likelihood of spurious old->new pointers.
324    */
325   { 
326     for (g = RtsFlags.GcFlags.generations-1; g > N; g--) {
327       generations[g].saved_mut_list = generations[g].mut_list;
328       generations[g].mut_list = allocBlock(); 
329         // mut_list always has at least one block.
330     }
331     for (g = RtsFlags.GcFlags.generations-1; g > N; g--) {
332       scavenge_mutable_list(&generations[g]);
333     }
334   }
335
336   // follow roots from the CAF list (used by GHCi)
337   gct->evac_step = 0;
338   markCAFs(mark_root);
339
340   // follow all the roots that the application knows about.
341   gct->evac_step = 0;
342   GetRoots(mark_root);
343
344   // Mark the weak pointer list, and prepare to detect dead weak pointers.
345   markWeakPtrList();
346   initWeakForGC();
347
348   // Mark the stable pointer table.
349   markStablePtrTable(mark_root);
350
351   /* -------------------------------------------------------------------------
352    * Repeatedly scavenge all the areas we know about until there's no
353    * more scavenging to be done.
354    */
355   for (;;)
356   {
357       gc_thread_work();
358       // The other threads are now stopped.  We might recurse back to
359       // here, but from now on this is the only thread.
360       
361       // if any blackholes are alive, make the threads that wait on
362       // them alive too.
363       if (traverseBlackholeQueue()) {
364           inc_running(); 
365           continue;
366       }
367   
368       // must be last...  invariant is that everything is fully
369       // scavenged at this point.
370       if (traverseWeakPtrList()) { // returns rtsTrue if evaced something 
371           inc_running();
372           continue;
373       }
374
375       // If we get to here, there's really nothing left to do.
376       break;
377   }
378
379   // Update pointers from the Task list
380   update_task_list();
381
382   // Now see which stable names are still alive.
383   gcStablePtrTable();
384
385 #ifdef PROFILING
386   // We call processHeapClosureForDead() on every closure destroyed during
387   // the current garbage collection, so we invoke LdvCensusForDead().
388   if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV
389       || RtsFlags.ProfFlags.bioSelector != NULL)
390     LdvCensusForDead(N);
391 #endif
392
393   // NO MORE EVACUATION AFTER THIS POINT!
394   // Finally: compaction of the oldest generation.
395   if (major_gc && oldest_gen->steps[0].is_compacted) {
396       // save number of blocks for stats
397       oldgen_saved_blocks = oldest_gen->steps[0].n_old_blocks;
398       compact();
399   }
400
401   IF_DEBUG(sanity, checkGlobalTSOList(rtsFalse));
402
403   // Two-space collector: free the old to-space.
404   // g0s0->old_blocks is the old nursery
405   // g0s0->blocks is to-space from the previous GC
406   if (RtsFlags.GcFlags.generations == 1) {
407       if (g0s0->blocks != NULL) {
408           freeChain(g0s0->blocks);
409           g0s0->blocks = NULL;
410       }
411   }
412
413   // For each workspace, in each thread:
414   //    * clear the BF_EVACUATED flag from each copied block
415   //    * move the copied blocks to the step
416   {
417       gc_thread *thr;
418       step_workspace *ws;
419       bdescr *prev;
420
421       for (t = 0; t < n_threads; t++) {
422           thr = &gc_threads[t];
423
424           for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
425               for (s = 0; s < generations[g].n_steps; s++) {
426                   ws = &thr->steps[g][s];
427                   if (g==0 && s==0) continue;
428
429                   // Not true?
430                   // ASSERT( ws->scan_bd == ws->todo_bd );
431                   ASSERT( ws->scan_bd ? ws->scan == ws->scan_bd->free : 1 );
432
433                   // Push the final block
434                   if (ws->scan_bd) { push_scan_block(ws->scan_bd, ws); }
435
436                   ASSERT(countBlocks(ws->scavd_list) == ws->n_scavd_blocks);
437
438                   prev = ws->scavd_list;
439                   for (bd = ws->scavd_list; bd != NULL; bd = bd->link) {
440                       bd->flags &= ~BF_EVACUATED;        // now from-space 
441                       prev = bd;
442                   }
443                   prev->link = ws->stp->blocks;
444                   ws->stp->blocks = ws->scavd_list;
445                   ws->stp->n_blocks += ws->n_scavd_blocks;
446                   ASSERT(countBlocks(ws->stp->blocks) == ws->stp->n_blocks);
447               }
448           }
449       }
450   }
451
452   // Two-space collector: swap the semi-spaces around.
453   // Currently: g0s0->old_blocks is the old nursery
454   //            g0s0->blocks is to-space from this GC
455   // We want these the other way around.
456   if (RtsFlags.GcFlags.generations == 1) {
457       bdescr *nursery_blocks = g0s0->old_blocks;
458       nat n_nursery_blocks = g0s0->n_old_blocks;
459       g0s0->old_blocks = g0s0->blocks;
460       g0s0->n_old_blocks = g0s0->n_blocks;
461       g0s0->blocks = nursery_blocks;
462       g0s0->n_blocks = n_nursery_blocks;
463   }
464
465   /* run through all the generations/steps and tidy up 
466    */
467   for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
468
469     if (g <= N) {
470       generations[g].collections++; // for stats 
471     }
472
473     // Count the mutable list as bytes "copied" for the purposes of
474     // stats.  Every mutable list is copied during every GC.
475     if (g > 0) {
476         nat mut_list_size = 0;
477         for (bd = generations[g].mut_list; bd != NULL; bd = bd->link) {
478             mut_list_size += bd->free - bd->start;
479         }
480         copied +=  mut_list_size;
481
482         debugTrace(DEBUG_gc,
483                    "mut_list_size: %lu (%d vars, %d arrays, %d MVARs, %d others)",
484                    (unsigned long)(mut_list_size * sizeof(W_)),
485                    mutlist_MUTVARS, mutlist_MUTARRS, mutlist_MVARS, mutlist_OTHERS);
486     }
487
488     for (s = 0; s < generations[g].n_steps; s++) {
489       bdescr *next;
490       stp = &generations[g].steps[s];
491
492       // for generations we collected... 
493       if (g <= N) {
494
495         /* free old memory and shift to-space into from-space for all
496          * the collected steps (except the allocation area).  These
497          * freed blocks will probaby be quickly recycled.
498          */
499         if (!(g == 0 && s == 0 && RtsFlags.GcFlags.generations > 1)) {
500             if (stp->is_compacted)
501             {
502                 // for a compacted step, just shift the new to-space
503                 // onto the front of the now-compacted existing blocks.
504                 for (bd = stp->blocks; bd != NULL; bd = bd->link) {
505                     bd->flags &= ~BF_EVACUATED;  // now from-space 
506                 }
507                 // tack the new blocks on the end of the existing blocks
508                 if (stp->old_blocks != NULL) {
509                     for (bd = stp->old_blocks; bd != NULL; bd = next) {
510                         // NB. this step might not be compacted next
511                         // time, so reset the BF_COMPACTED flags.
512                         // They are set before GC if we're going to
513                         // compact.  (search for BF_COMPACTED above).
514                         bd->flags &= ~BF_COMPACTED;
515                         next = bd->link;
516                         if (next == NULL) {
517                             bd->link = stp->blocks;
518                         }
519                     }
520                     stp->blocks = stp->old_blocks;
521                 }
522                 // add the new blocks to the block tally
523                 stp->n_blocks += stp->n_old_blocks;
524                 ASSERT(countBlocks(stp->blocks) == stp->n_blocks);
525             }
526             else // not copacted
527             {
528                 freeChain(stp->old_blocks);
529             }
530             stp->old_blocks = NULL;
531             stp->n_old_blocks = 0;
532         }
533
534         /* LARGE OBJECTS.  The current live large objects are chained on
535          * scavenged_large, having been moved during garbage
536          * collection from large_objects.  Any objects left on
537          * large_objects list are therefore dead, so we free them here.
538          */
539         for (bd = stp->large_objects; bd != NULL; bd = next) {
540           next = bd->link;
541           freeGroup(bd);
542           bd = next;
543         }
544
545         // update the count of blocks used by large objects
546         for (bd = stp->scavenged_large_objects; bd != NULL; bd = bd->link) {
547           bd->flags &= ~BF_EVACUATED;
548         }
549         stp->large_objects  = stp->scavenged_large_objects;
550         stp->n_large_blocks = stp->n_scavenged_large_blocks;
551
552       }
553       else // for older generations... 
554       {
555         /* For older generations, we need to append the
556          * scavenged_large_object list (i.e. large objects that have been
557          * promoted during this GC) to the large_object list for that step.
558          */
559         for (bd = stp->scavenged_large_objects; bd; bd = next) {
560           next = bd->link;
561           bd->flags &= ~BF_EVACUATED;
562           dbl_link_onto(bd, &stp->large_objects);
563         }
564
565         // add the new blocks we promoted during this GC 
566         stp->n_large_blocks += stp->n_scavenged_large_blocks;
567       }
568     }
569   }
570
571   // update the max size of older generations after a major GC
572   resize_generations();
573   
574   // Guess the amount of live data for stats.
575   live = calcLive();
576
577   // Free the small objects allocated via allocate(), since this will
578   // all have been copied into G0S1 now.  
579   if (RtsFlags.GcFlags.generations > 1) {
580       if (g0s0->blocks != NULL) {
581           freeChain(g0s0->blocks);
582           g0s0->blocks = NULL;
583       }
584       g0s0->n_blocks = 0;
585   }
586   alloc_blocks = 0;
587   alloc_blocks_lim = RtsFlags.GcFlags.minAllocAreaSize;
588
589   // Start a new pinned_object_block
590   pinned_object_block = NULL;
591
592   // Free the mark stack.
593   if (mark_stack_bdescr != NULL) {
594       freeGroup(mark_stack_bdescr);
595   }
596
597   // Free any bitmaps.
598   for (g = 0; g <= N; g++) {
599       for (s = 0; s < generations[g].n_steps; s++) {
600           stp = &generations[g].steps[s];
601           if (stp->bitmap != NULL) {
602               freeGroup(stp->bitmap);
603               stp->bitmap = NULL;
604           }
605       }
606   }
607
608   resize_nursery();
609
610  // mark the garbage collected CAFs as dead 
611 #if 0 && defined(DEBUG) // doesn't work at the moment 
612   if (major_gc) { gcCAFs(); }
613 #endif
614   
615 #ifdef PROFILING
616   // resetStaticObjectForRetainerProfiling() must be called before
617   // zeroing below.
618   resetStaticObjectForRetainerProfiling();
619 #endif
620
621   // zero the scavenged static object list 
622   if (major_gc) {
623     zero_static_object_list(scavenged_static_objects);
624   }
625
626   // Reset the nursery
627   resetNurseries();
628
629   // start any pending finalizers 
630   RELEASE_SM_LOCK;
631   scheduleFinalizers(last_free_capability, old_weak_ptr_list);
632   ACQUIRE_SM_LOCK;
633   
634   // send exceptions to any threads which were about to die 
635   RELEASE_SM_LOCK;
636   resurrectThreads(resurrected_threads);
637   ACQUIRE_SM_LOCK;
638
639   // Update the stable pointer hash table.
640   updateStablePtrTable(major_gc);
641
642   // check sanity after GC 
643   IF_DEBUG(sanity, checkSanity());
644
645   // extra GC trace info 
646   IF_DEBUG(gc, statDescribeGens());
647
648 #ifdef DEBUG
649   // symbol-table based profiling 
650   /*  heapCensus(to_blocks); */ /* ToDo */
651 #endif
652
653   // restore enclosing cost centre 
654 #ifdef PROFILING
655   CCCS = prev_CCS;
656 #endif
657
658 #ifdef DEBUG
659   // check for memory leaks if DEBUG is on 
660   memInventory();
661 #endif
662
663 #ifdef RTS_GTK_FRONTPANEL
664   if (RtsFlags.GcFlags.frontpanel) {
665       updateFrontPanelAfterGC( N, live );
666   }
667 #endif
668
669   // ok, GC over: tell the stats department what happened. 
670   stat_endGC(allocated, live, copied, N);
671
672 #if defined(RTS_USER_SIGNALS)
673   if (RtsFlags.MiscFlags.install_signal_handlers) {
674     // unblock signals again
675     unblockUserSignals();
676   }
677 #endif
678
679   RELEASE_SM_LOCK;
680
681   gct = saved_gct;
682 }
683
684 /* ---------------------------------------------------------------------------
685    Where are the roots that we know about?
686
687         - all the threads on the runnable queue
688         - all the threads on the blocked queue
689         - all the threads on the sleeping queue
690         - all the thread currently executing a _ccall_GC
691         - all the "main threads"
692      
693    ------------------------------------------------------------------------ */
694
695 /* This has to be protected either by the scheduler monitor, or by the
696         garbage collection monitor (probably the latter).
697         KH @ 25/10/99
698 */
699
700 void
701 GetRoots( evac_fn evac )
702 {
703     nat i;
704     Capability *cap;
705     Task *task;
706
707     for (i = 0; i < n_capabilities; i++) {
708         cap = &capabilities[i];
709         evac((StgClosure **)(void *)&cap->run_queue_hd);
710         evac((StgClosure **)(void *)&cap->run_queue_tl);
711 #if defined(THREADED_RTS)
712         evac((StgClosure **)(void *)&cap->wakeup_queue_hd);
713         evac((StgClosure **)(void *)&cap->wakeup_queue_tl);
714 #endif
715         for (task = cap->suspended_ccalling_tasks; task != NULL; 
716              task=task->next) {
717             debugTrace(DEBUG_sched,
718                        "evac'ing suspended TSO %lu", (unsigned long)task->suspended_tso->id);
719             evac((StgClosure **)(void *)&task->suspended_tso);
720         }
721
722     }
723     
724 #if !defined(THREADED_RTS)
725     evac((StgClosure **)(void *)&blocked_queue_hd);
726     evac((StgClosure **)(void *)&blocked_queue_tl);
727     evac((StgClosure **)(void *)&sleeping_queue);
728 #endif 
729
730     // evac((StgClosure **)&blackhole_queue);
731
732 #if defined(THREADED_RTS)
733     markSparkQueue(evac);
734 #endif
735     
736 #if defined(RTS_USER_SIGNALS)
737     // mark the signal handlers (signals should be already blocked)
738     markSignalHandlers(evac);
739 #endif
740 }
741
742 /* -----------------------------------------------------------------------------
743    isAlive determines whether the given closure is still alive (after
744    a garbage collection) or not.  It returns the new address of the
745    closure if it is alive, or NULL otherwise.
746
747    NOTE: Use it before compaction only!
748          It untags and (if needed) retags pointers to closures.
749    -------------------------------------------------------------------------- */
750
751
752 StgClosure *
753 isAlive(StgClosure *p)
754 {
755   const StgInfoTable *info;
756   bdescr *bd;
757   StgWord tag;
758   StgClosure *q;
759
760   while (1) {
761     /* The tag and the pointer are split, to be merged later when needed. */
762     tag = GET_CLOSURE_TAG(p);
763     q = UNTAG_CLOSURE(p);
764
765     ASSERT(LOOKS_LIKE_CLOSURE_PTR(q));
766     info = get_itbl(q);
767
768     // ignore static closures 
769     //
770     // ToDo: for static closures, check the static link field.
771     // Problem here is that we sometimes don't set the link field, eg.
772     // for static closures with an empty SRT or CONSTR_STATIC_NOCAFs.
773     //
774     if (!HEAP_ALLOCED(q)) {
775         return p;
776     }
777
778     // ignore closures in generations that we're not collecting. 
779     bd = Bdescr((P_)q);
780     if (bd->gen_no > N) {
781         return p;
782     }
783
784     // if it's a pointer into to-space, then we're done
785     if (bd->flags & BF_EVACUATED) {
786         return p;
787     }
788
789     // large objects use the evacuated flag
790     if (bd->flags & BF_LARGE) {
791         return NULL;
792     }
793
794     // check the mark bit for compacted steps
795     if ((bd->flags & BF_COMPACTED) && is_marked((P_)q,bd)) {
796         return p;
797     }
798
799     switch (info->type) {
800
801     case IND:
802     case IND_STATIC:
803     case IND_PERM:
804     case IND_OLDGEN:            // rely on compatible layout with StgInd 
805     case IND_OLDGEN_PERM:
806       // follow indirections 
807       p = ((StgInd *)q)->indirectee;
808       continue;
809
810     case EVACUATED:
811       // alive! 
812       return ((StgEvacuated *)q)->evacuee;
813
814     case TSO:
815       if (((StgTSO *)q)->what_next == ThreadRelocated) {
816         p = (StgClosure *)((StgTSO *)q)->link;
817         continue;
818       } 
819       return NULL;
820
821     default:
822       // dead. 
823       return NULL;
824     }
825   }
826 }
827
828 /* -----------------------------------------------------------------------------
829    Figure out which generation to collect, initialise N and major_gc.
830    -------------------------------------------------------------------------- */
831
832 static void
833 initialise_N (rtsBool force_major_gc)
834 {
835     nat g;
836
837     if (force_major_gc) {
838         N = RtsFlags.GcFlags.generations - 1;
839         major_gc = rtsTrue;
840     } else {
841         N = 0;
842         for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
843             if (generations[g].steps[0].n_blocks +
844                 generations[g].steps[0].n_large_blocks
845                 >= generations[g].max_blocks) {
846                 N = g;
847             }
848         }
849         major_gc = (N == RtsFlags.GcFlags.generations-1);
850     }
851 }
852
853 /* -----------------------------------------------------------------------------
854    Initialise the gc_thread structures.
855    -------------------------------------------------------------------------- */
856
857 static void
858 alloc_gc_thread (gc_thread *t, int n)
859 {
860     nat g, s;
861     step_workspace *ws;
862
863 #ifdef THREADED_RTS
864     t->id = 0;
865     initCondition(&t->wake_cond);
866     initMutex(&t->wake_mutex);
867     t->wakeup = rtsFalse;
868     t->exit   = rtsFalse;
869 #endif
870
871     t->thread_index = n;
872     t->free_blocks = NULL;
873     t->gc_count = 0;
874
875     init_gc_thread(t);
876     
877 #ifdef USE_PAPI
878     t->papi_events = -1;
879 #endif
880
881     t->steps = stgMallocBytes(RtsFlags.GcFlags.generations * 
882                                 sizeof(step_workspace *), 
883                                 "initialise_gc_thread");
884
885     for (g = 0; g < RtsFlags.GcFlags.generations; g++)
886     {
887         t->steps[g] = stgMallocBytes(generations[g].n_steps * 
888                                        sizeof(step_workspace),
889                                        "initialise_gc_thread/2");
890
891         for (s = 0; s < generations[g].n_steps; s++)
892         {
893             ws = &t->steps[g][s];
894             ws->stp = &generations[g].steps[s];
895             ws->gct = t;
896
897             ws->scan_bd = NULL;
898             ws->scan = NULL;
899
900             ws->todo_bd = NULL;
901             ws->buffer_todo_bd = NULL;
902
903             ws->scavd_list = NULL;
904             ws->n_scavd_blocks = 0;
905         }
906     }
907 }
908
909
910 static void
911 alloc_gc_threads (void)
912 {
913     if (gc_threads == NULL) {
914 #if defined(THREADED_RTS)
915         nat i;
916         gc_threads = stgMallocBytes (RtsFlags.ParFlags.gcThreads * 
917                                      sizeof(gc_thread), 
918                                      "alloc_gc_threads");
919
920         for (i = 0; i < RtsFlags.ParFlags.gcThreads; i++) {
921             alloc_gc_thread(&gc_threads[i], i);
922         }
923 #else
924         gc_threads = stgMallocBytes (sizeof(gc_thread), 
925                                      "alloc_gc_threads");
926
927         alloc_gc_thread(gc_threads, 0);
928 #endif
929     }
930 }
931
932 /* ----------------------------------------------------------------------------
933    Start GC threads
934    ------------------------------------------------------------------------- */
935
936 static nat gc_running_threads;
937
938 #if defined(THREADED_RTS)
939 static Mutex gc_running_mutex;
940 #endif
941
942 static nat
943 inc_running (void)
944 {
945     nat n_running;
946     ACQUIRE_LOCK(&gc_running_mutex);
947     n_running = ++gc_running_threads;
948     RELEASE_LOCK(&gc_running_mutex);
949     return n_running;
950 }
951
952 static nat
953 dec_running (void)
954 {
955     nat n_running;
956     ACQUIRE_LOCK(&gc_running_mutex);
957     n_running = --gc_running_threads;
958     RELEASE_LOCK(&gc_running_mutex);
959     return n_running;
960 }
961
962 //
963 // gc_thread_work(): Scavenge until there's no work left to do and all
964 // the running threads are idle.
965 //
966 static void
967 gc_thread_work (void)
968 {
969     nat r;
970         
971     debugTrace(DEBUG_gc, "GC thread %d working", gct->thread_index);
972
973     // gc_running_threads has already been incremented for us; either
974     // this is the main thread and we incremented it inside
975     // GarbageCollect(), or this is a worker thread and the main
976     // thread bumped gc_running_threads before waking us up.
977
978 loop:
979     scavenge_loop();
980     // scavenge_loop() only exits when there's no work to do
981     r = dec_running();
982     
983     debugTrace(DEBUG_gc, "GC thread %d idle (%d still running)", 
984                gct->thread_index, r);
985
986     while (gc_running_threads != 0) {
987         if (any_work()) {
988             inc_running();
989             goto loop;
990         }
991         // any_work() does not remove the work from the queue, it
992         // just checks for the presence of work.  If we find any,
993         // then we increment gc_running_threads and go back to 
994         // scavenge_loop() to perform any pending work.
995     }
996     
997     // All threads are now stopped
998     debugTrace(DEBUG_gc, "GC thread %d finished.", gct->thread_index);
999 }
1000
1001
1002 #if defined(THREADED_RTS)
1003 static void
1004 gc_thread_mainloop (void)
1005 {
1006     while (!gct->exit) {
1007
1008         // Wait until we're told to wake up
1009         ACQUIRE_LOCK(&gct->wake_mutex);
1010         while (!gct->wakeup) {
1011             debugTrace(DEBUG_gc, "GC thread %d standing by...", 
1012                        gct->thread_index);
1013             waitCondition(&gct->wake_cond, &gct->wake_mutex);
1014         }
1015         RELEASE_LOCK(&gct->wake_mutex);
1016         gct->wakeup = rtsFalse;
1017         if (gct->exit) break;
1018
1019 #ifdef USE_PAPI
1020         // start performance counters in this thread...
1021         if (gct->papi_events == -1) {
1022             papi_init_eventset(&gct->papi_events);
1023         }
1024         papi_thread_start_gc_count(gct->papi_events);
1025 #endif
1026
1027         gc_thread_work();
1028
1029 #ifdef USE_PAPI
1030         // count events in this thread towards the GC totals
1031         papi_thread_stop_gc_count(gct->papi_events);
1032 #endif
1033     }
1034 }       
1035 #endif
1036
1037 #if defined(THREADED_RTS)
1038 static void
1039 gc_thread_entry (gc_thread *my_gct)
1040 {
1041     gct = my_gct;
1042     debugTrace(DEBUG_gc, "GC thread %d starting...", gct->thread_index);
1043     gct->id = osThreadId();
1044     gc_thread_mainloop();
1045 }
1046 #endif
1047
1048 static void
1049 start_gc_threads (void)
1050 {
1051 #if defined(THREADED_RTS)
1052     nat i;
1053     OSThreadId id;
1054     static rtsBool done = rtsFalse;
1055
1056     gc_running_threads = 0;
1057     initMutex(&gc_running_mutex);
1058
1059     if (!done) {
1060         // Start from 1: the main thread is 0
1061         for (i = 1; i < RtsFlags.ParFlags.gcThreads; i++) {
1062             createOSThread(&id, (OSThreadProc*)&gc_thread_entry, 
1063                            &gc_threads[i]);
1064         }
1065         done = rtsTrue;
1066     }
1067 #endif
1068 }
1069
1070 static void
1071 wakeup_gc_threads (nat n_threads USED_IF_THREADS)
1072 {
1073 #if defined(THREADED_RTS)
1074     nat i;
1075     for (i=1; i < n_threads; i++) {
1076         inc_running();
1077         ACQUIRE_LOCK(&gc_threads[i].wake_mutex);
1078         gc_threads[i].wakeup = rtsTrue;
1079         signalCondition(&gc_threads[i].wake_cond);
1080         RELEASE_LOCK(&gc_threads[i].wake_mutex);
1081     }
1082 #endif
1083 }
1084
1085 /* ----------------------------------------------------------------------------
1086    Initialise a generation that is to be collected 
1087    ------------------------------------------------------------------------- */
1088
1089 static void
1090 init_collected_gen (nat g, nat n_threads)
1091 {
1092     nat s, t, i;
1093     step_workspace *ws;
1094     step *stp;
1095     bdescr *bd;
1096
1097     // Throw away the current mutable list.  Invariant: the mutable
1098     // list always has at least one block; this means we can avoid a
1099     // check for NULL in recordMutable().
1100     if (g != 0) {
1101         freeChain(generations[g].mut_list);
1102         generations[g].mut_list = allocBlock();
1103         for (i = 0; i < n_capabilities; i++) {
1104             freeChain(capabilities[i].mut_lists[g]);
1105             capabilities[i].mut_lists[g] = allocBlock();
1106         }
1107     }
1108
1109     for (s = 0; s < generations[g].n_steps; s++) {
1110
1111         // generation 0, step 0 doesn't need to-space 
1112         if (g == 0 && s == 0 && RtsFlags.GcFlags.generations > 1) { 
1113             continue; 
1114         }
1115         
1116         stp = &generations[g].steps[s];
1117         ASSERT(stp->gen_no == g);
1118
1119         // deprecate the existing blocks
1120         stp->old_blocks   = stp->blocks;
1121         stp->n_old_blocks = stp->n_blocks;
1122         stp->blocks       = NULL;
1123         stp->n_blocks     = 0;
1124
1125         // we don't have any to-be-scavenged blocks yet
1126         stp->todos = NULL;
1127         stp->n_todos = 0;
1128
1129         // initialise the large object queues.
1130         stp->scavenged_large_objects = NULL;
1131         stp->n_scavenged_large_blocks = 0;
1132
1133         // mark the large objects as not evacuated yet 
1134         for (bd = stp->large_objects; bd; bd = bd->link) {
1135             bd->flags &= ~BF_EVACUATED;
1136         }
1137
1138         // for a compacted step, we need to allocate the bitmap
1139         if (stp->is_compacted) {
1140             nat bitmap_size; // in bytes
1141             bdescr *bitmap_bdescr;
1142             StgWord *bitmap;
1143             
1144             bitmap_size = stp->n_old_blocks * BLOCK_SIZE / (sizeof(W_)*BITS_PER_BYTE);
1145             
1146             if (bitmap_size > 0) {
1147                 bitmap_bdescr = allocGroup((lnat)BLOCK_ROUND_UP(bitmap_size) 
1148                                            / BLOCK_SIZE);
1149                 stp->bitmap = bitmap_bdescr;
1150                 bitmap = bitmap_bdescr->start;
1151                 
1152                 debugTrace(DEBUG_gc, "bitmap_size: %d, bitmap: %p",
1153                            bitmap_size, bitmap);
1154                 
1155                 // don't forget to fill it with zeros!
1156                 memset(bitmap, 0, bitmap_size);
1157                 
1158                 // For each block in this step, point to its bitmap from the
1159                 // block descriptor.
1160                 for (bd=stp->old_blocks; bd != NULL; bd = bd->link) {
1161                     bd->u.bitmap = bitmap;
1162                     bitmap += BLOCK_SIZE_W / (sizeof(W_)*BITS_PER_BYTE);
1163                     
1164                     // Also at this point we set the BF_COMPACTED flag
1165                     // for this block.  The invariant is that
1166                     // BF_COMPACTED is always unset, except during GC
1167                     // when it is set on those blocks which will be
1168                     // compacted.
1169                     bd->flags |= BF_COMPACTED;
1170                 }
1171             }
1172         }
1173     }
1174
1175     // For each GC thread, for each step, allocate a "todo" block to
1176     // store evacuated objects to be scavenged, and a block to store
1177     // evacuated objects that do not need to be scavenged.
1178     for (t = 0; t < n_threads; t++) {
1179         for (s = 0; s < generations[g].n_steps; s++) {
1180
1181             // we don't copy objects into g0s0, unless -G0
1182             if (g==0 && s==0 && RtsFlags.GcFlags.generations > 1) continue;
1183
1184             ws = &gc_threads[t].steps[g][s];
1185
1186             ws->scan_bd = NULL;
1187             ws->scan = NULL;
1188
1189             ws->todo_large_objects = NULL;
1190
1191             // allocate the first to-space block; extra blocks will be
1192             // chained on as necessary.
1193             ws->todo_bd = NULL;
1194             ws->buffer_todo_bd = NULL;
1195             gc_alloc_todo_block(ws);
1196
1197             ws->scavd_list = NULL;
1198             ws->n_scavd_blocks = 0;
1199         }
1200     }
1201 }
1202
1203
1204 /* ----------------------------------------------------------------------------
1205    Initialise a generation that is *not* to be collected 
1206    ------------------------------------------------------------------------- */
1207
1208 static void
1209 init_uncollected_gen (nat g, nat threads)
1210 {
1211     nat s, t, i;
1212     step_workspace *ws;
1213     step *stp;
1214     bdescr *bd;
1215
1216     for (s = 0; s < generations[g].n_steps; s++) {
1217         stp = &generations[g].steps[s];
1218         stp->scavenged_large_objects = NULL;
1219         stp->n_scavenged_large_blocks = 0;
1220     }
1221     
1222     for (t = 0; t < threads; t++) {
1223         for (s = 0; s < generations[g].n_steps; s++) {
1224             
1225             ws = &gc_threads[t].steps[g][s];
1226             stp = ws->stp;
1227             
1228             ws->buffer_todo_bd = NULL;
1229             ws->todo_large_objects = NULL;
1230
1231             ws->scavd_list = NULL;
1232             ws->n_scavd_blocks = 0;
1233
1234             // If the block at the head of the list in this generation
1235             // is less than 3/4 full, then use it as a todo block.
1236             if (isPartiallyFull(stp->blocks))
1237             {
1238                 ws->todo_bd = stp->blocks;
1239                 stp->blocks = stp->blocks->link;
1240                 stp->n_blocks -= 1;
1241                 ws->todo_bd->link = NULL;
1242
1243                 // this block is also the scan block; we must scan
1244                 // from the current end point.
1245                 ws->scan_bd = ws->todo_bd;
1246                 ws->scan = ws->scan_bd->free;
1247
1248                 // subtract the contents of this block from the stats,
1249                 // because we'll count the whole block later.
1250                 copied -= ws->scan_bd->free - ws->scan_bd->start;
1251             } 
1252             else
1253             {
1254                 ws->scan_bd = NULL;
1255                 ws->scan = NULL;
1256                 ws->todo_bd = NULL;
1257                 gc_alloc_todo_block(ws);
1258             }
1259         }
1260     }
1261
1262     // Move the private mutable lists from each capability onto the
1263     // main mutable list for the generation.
1264     for (i = 0; i < n_capabilities; i++) {
1265         for (bd = capabilities[i].mut_lists[g]; 
1266              bd->link != NULL; bd = bd->link) {
1267             /* nothing */
1268         }
1269         bd->link = generations[g].mut_list;
1270         generations[g].mut_list = capabilities[i].mut_lists[g];
1271         capabilities[i].mut_lists[g] = allocBlock();
1272     }
1273 }
1274
1275 /* -----------------------------------------------------------------------------
1276    Initialise a gc_thread before GC
1277    -------------------------------------------------------------------------- */
1278
1279 static void
1280 init_gc_thread (gc_thread *t)
1281 {
1282     t->evac_step = 0;
1283     t->failed_to_evac = rtsFalse;
1284     t->eager_promotion = rtsTrue;
1285     t->thunk_selector_depth = 0;
1286 }
1287
1288 /* -----------------------------------------------------------------------------
1289    Function we pass to GetRoots to evacuate roots.
1290    -------------------------------------------------------------------------- */
1291
1292 static void
1293 mark_root(StgClosure **root)
1294 {
1295   evacuate(root);
1296 }
1297
1298 /* -----------------------------------------------------------------------------
1299    Initialising the static object & mutable lists
1300    -------------------------------------------------------------------------- */
1301
1302 static void
1303 zero_static_object_list(StgClosure* first_static)
1304 {
1305   StgClosure* p;
1306   StgClosure* link;
1307   const StgInfoTable *info;
1308
1309   for (p = first_static; p != END_OF_STATIC_LIST; p = link) {
1310     info = get_itbl(p);
1311     link = *STATIC_LINK(info, p);
1312     *STATIC_LINK(info,p) = NULL;
1313   }
1314 }
1315
1316 /* -----------------------------------------------------------------------------
1317    Reverting CAFs
1318    -------------------------------------------------------------------------- */
1319
1320 void
1321 revertCAFs( void )
1322 {
1323     StgIndStatic *c;
1324
1325     for (c = (StgIndStatic *)revertible_caf_list; c != NULL; 
1326          c = (StgIndStatic *)c->static_link) 
1327     {
1328         SET_INFO(c, c->saved_info);
1329         c->saved_info = NULL;
1330         // could, but not necessary: c->static_link = NULL; 
1331     }
1332     revertible_caf_list = NULL;
1333 }
1334
1335 void
1336 markCAFs( evac_fn evac )
1337 {
1338     StgIndStatic *c;
1339
1340     for (c = (StgIndStatic *)caf_list; c != NULL; 
1341          c = (StgIndStatic *)c->static_link) 
1342     {
1343         evac(&c->indirectee);
1344     }
1345     for (c = (StgIndStatic *)revertible_caf_list; c != NULL; 
1346          c = (StgIndStatic *)c->static_link) 
1347     {
1348         evac(&c->indirectee);
1349     }
1350 }
1351
1352 /* ----------------------------------------------------------------------------
1353    Update the pointers from the task list
1354
1355    These are treated as weak pointers because we want to allow a main
1356    thread to get a BlockedOnDeadMVar exception in the same way as any
1357    other thread.  Note that the threads should all have been retained
1358    by GC by virtue of being on the all_threads list, we're just
1359    updating pointers here.
1360    ------------------------------------------------------------------------- */
1361
1362 static void
1363 update_task_list (void)
1364 {
1365     Task *task;
1366     StgTSO *tso;
1367     for (task = all_tasks; task != NULL; task = task->all_link) {
1368         if (!task->stopped && task->tso) {
1369             ASSERT(task->tso->bound == task);
1370             tso = (StgTSO *) isAlive((StgClosure *)task->tso);
1371             if (tso == NULL) {
1372                 barf("task %p: main thread %d has been GC'd", 
1373 #ifdef THREADED_RTS
1374                      (void *)task->id, 
1375 #else
1376                      (void *)task,
1377 #endif
1378                      task->tso->id);
1379             }
1380             task->tso = tso;
1381         }
1382     }
1383 }
1384
1385 /* ----------------------------------------------------------------------------
1386    Reset the sizes of the older generations when we do a major
1387    collection.
1388   
1389    CURRENT STRATEGY: make all generations except zero the same size.
1390    We have to stay within the maximum heap size, and leave a certain
1391    percentage of the maximum heap size available to allocate into.
1392    ------------------------------------------------------------------------- */
1393
1394 static void
1395 resize_generations (void)
1396 {
1397     nat g;
1398
1399     if (major_gc && RtsFlags.GcFlags.generations > 1) {
1400         nat live, size, min_alloc;
1401         nat max  = RtsFlags.GcFlags.maxHeapSize;
1402         nat gens = RtsFlags.GcFlags.generations;
1403         
1404         // live in the oldest generations
1405         live = oldest_gen->steps[0].n_blocks +
1406             oldest_gen->steps[0].n_large_blocks;
1407         
1408         // default max size for all generations except zero
1409         size = stg_max(live * RtsFlags.GcFlags.oldGenFactor,
1410                        RtsFlags.GcFlags.minOldGenSize);
1411         
1412         // minimum size for generation zero
1413         min_alloc = stg_max((RtsFlags.GcFlags.pcFreeHeap * max) / 200,
1414                             RtsFlags.GcFlags.minAllocAreaSize);
1415
1416         // Auto-enable compaction when the residency reaches a
1417         // certain percentage of the maximum heap size (default: 30%).
1418         if (RtsFlags.GcFlags.generations > 1 &&
1419             (RtsFlags.GcFlags.compact ||
1420              (max > 0 &&
1421               oldest_gen->steps[0].n_blocks > 
1422               (RtsFlags.GcFlags.compactThreshold * max) / 100))) {
1423             oldest_gen->steps[0].is_compacted = 1;
1424 //        debugBelch("compaction: on\n", live);
1425         } else {
1426             oldest_gen->steps[0].is_compacted = 0;
1427 //        debugBelch("compaction: off\n", live);
1428         }
1429
1430         // if we're going to go over the maximum heap size, reduce the
1431         // size of the generations accordingly.  The calculation is
1432         // different if compaction is turned on, because we don't need
1433         // to double the space required to collect the old generation.
1434         if (max != 0) {
1435             
1436             // this test is necessary to ensure that the calculations
1437             // below don't have any negative results - we're working
1438             // with unsigned values here.
1439             if (max < min_alloc) {
1440                 heapOverflow();
1441             }
1442             
1443             if (oldest_gen->steps[0].is_compacted) {
1444                 if ( (size + (size - 1) * (gens - 2) * 2) + min_alloc > max ) {
1445                     size = (max - min_alloc) / ((gens - 1) * 2 - 1);
1446                 }
1447             } else {
1448                 if ( (size * (gens - 1) * 2) + min_alloc > max ) {
1449                     size = (max - min_alloc) / ((gens - 1) * 2);
1450                 }
1451             }
1452             
1453             if (size < live) {
1454                 heapOverflow();
1455             }
1456         }
1457         
1458 #if 0
1459         debugBelch("live: %d, min_alloc: %d, size : %d, max = %d\n", live,
1460                    min_alloc, size, max);
1461 #endif
1462         
1463         for (g = 0; g < gens; g++) {
1464             generations[g].max_blocks = size;
1465         }
1466     }
1467 }
1468
1469 /* -----------------------------------------------------------------------------
1470    Calculate the new size of the nursery, and resize it.
1471    -------------------------------------------------------------------------- */
1472
1473 static void
1474 resize_nursery (void)
1475 {
1476     if (RtsFlags.GcFlags.generations == 1)
1477     {   // Two-space collector:
1478         nat blocks;
1479     
1480         /* set up a new nursery.  Allocate a nursery size based on a
1481          * function of the amount of live data (by default a factor of 2)
1482          * Use the blocks from the old nursery if possible, freeing up any
1483          * left over blocks.
1484          *
1485          * If we get near the maximum heap size, then adjust our nursery
1486          * size accordingly.  If the nursery is the same size as the live
1487          * data (L), then we need 3L bytes.  We can reduce the size of the
1488          * nursery to bring the required memory down near 2L bytes.
1489          * 
1490          * A normal 2-space collector would need 4L bytes to give the same
1491          * performance we get from 3L bytes, reducing to the same
1492          * performance at 2L bytes.
1493          */
1494         blocks = g0s0->n_old_blocks;
1495         
1496         if ( RtsFlags.GcFlags.maxHeapSize != 0 &&
1497              blocks * RtsFlags.GcFlags.oldGenFactor * 2 > 
1498              RtsFlags.GcFlags.maxHeapSize )
1499         {
1500             long adjusted_blocks;  // signed on purpose 
1501             int pc_free; 
1502             
1503             adjusted_blocks = (RtsFlags.GcFlags.maxHeapSize - 2 * blocks);
1504             
1505             debugTrace(DEBUG_gc, "near maximum heap size of 0x%x blocks, blocks = %d, adjusted to %ld", 
1506                        RtsFlags.GcFlags.maxHeapSize, blocks, adjusted_blocks);
1507             
1508             pc_free = adjusted_blocks * 100 / RtsFlags.GcFlags.maxHeapSize;
1509             if (pc_free < RtsFlags.GcFlags.pcFreeHeap) /* might even * be < 0 */
1510             {
1511                 heapOverflow();
1512             }
1513             blocks = adjusted_blocks;
1514         }
1515         else
1516         {
1517             blocks *= RtsFlags.GcFlags.oldGenFactor;
1518             if (blocks < RtsFlags.GcFlags.minAllocAreaSize)
1519             {
1520                 blocks = RtsFlags.GcFlags.minAllocAreaSize;
1521             }
1522         }
1523         resizeNurseries(blocks);
1524     }
1525     else  // Generational collector
1526     {
1527         /* 
1528          * If the user has given us a suggested heap size, adjust our
1529          * allocation area to make best use of the memory available.
1530          */
1531         if (RtsFlags.GcFlags.heapSizeSuggestion)
1532         {
1533             long blocks;
1534             nat needed = calcNeeded();  // approx blocks needed at next GC 
1535             
1536             /* Guess how much will be live in generation 0 step 0 next time.
1537              * A good approximation is obtained by finding the
1538              * percentage of g0s0 that was live at the last minor GC.
1539              *
1540              * We have an accurate figure for the amount of copied data in
1541              * 'copied', but we must convert this to a number of blocks, with
1542              * a small adjustment for estimated slop at the end of a block
1543              * (- 10 words).
1544              */
1545             if (N == 0)
1546             {
1547                 g0s0_pcnt_kept = ((copied / (BLOCK_SIZE_W - 10)) * 100)
1548                     / countNurseryBlocks();
1549             }
1550             
1551             /* Estimate a size for the allocation area based on the
1552              * information available.  We might end up going slightly under
1553              * or over the suggested heap size, but we should be pretty
1554              * close on average.
1555              *
1556              * Formula:            suggested - needed
1557              *                ----------------------------
1558              *                    1 + g0s0_pcnt_kept/100
1559              *
1560              * where 'needed' is the amount of memory needed at the next
1561              * collection for collecting all steps except g0s0.
1562              */
1563             blocks = 
1564                 (((long)RtsFlags.GcFlags.heapSizeSuggestion - (long)needed) * 100) /
1565                 (100 + (long)g0s0_pcnt_kept);
1566             
1567             if (blocks < (long)RtsFlags.GcFlags.minAllocAreaSize) {
1568                 blocks = RtsFlags.GcFlags.minAllocAreaSize;
1569             }
1570             
1571             resizeNurseries((nat)blocks);
1572         }
1573         else
1574         {
1575             // we might have added extra large blocks to the nursery, so
1576             // resize back to minAllocAreaSize again.
1577             resizeNurseriesFixed(RtsFlags.GcFlags.minAllocAreaSize);
1578         }
1579     }
1580 }
1581
1582 /* -----------------------------------------------------------------------------
1583    Sanity code for CAF garbage collection.
1584
1585    With DEBUG turned on, we manage a CAF list in addition to the SRT
1586    mechanism.  After GC, we run down the CAF list and blackhole any
1587    CAFs which have been garbage collected.  This means we get an error
1588    whenever the program tries to enter a garbage collected CAF.
1589
1590    Any garbage collected CAFs are taken off the CAF list at the same
1591    time. 
1592    -------------------------------------------------------------------------- */
1593
1594 #if 0 && defined(DEBUG)
1595
1596 static void
1597 gcCAFs(void)
1598 {
1599   StgClosure*  p;
1600   StgClosure** pp;
1601   const StgInfoTable *info;
1602   nat i;
1603
1604   i = 0;
1605   p = caf_list;
1606   pp = &caf_list;
1607
1608   while (p != NULL) {
1609     
1610     info = get_itbl(p);
1611
1612     ASSERT(info->type == IND_STATIC);
1613
1614     if (STATIC_LINK(info,p) == NULL) {
1615         debugTrace(DEBUG_gccafs, "CAF gc'd at 0x%04lx", (long)p);
1616         // black hole it 
1617         SET_INFO(p,&stg_BLACKHOLE_info);
1618         p = STATIC_LINK2(info,p);
1619         *pp = p;
1620     }
1621     else {
1622       pp = &STATIC_LINK2(info,p);
1623       p = *pp;
1624       i++;
1625     }
1626
1627   }
1628
1629   debugTrace(DEBUG_gccafs, "%d CAFs live", i); 
1630 }
1631 #endif