1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team 1998-2006
5 * Generational garbage collector
7 * Documentation on the architecture of the Garbage Collector can be
8 * found in the online commentary:
10 * http://hackage.haskell.org/trac/ghc/wiki/Commentary/Rts/Storage/GC
12 * ---------------------------------------------------------------------------*/
14 #include "PosixSource.h"
19 #include "OSThreads.h"
20 #include "LdvProfile.h"
25 #include "BlockAlloc.h"
31 #include "ParTicky.h" // ToDo: move into Rts.h
32 #include "RtsSignals.h"
36 #if defined(RTS_GTK_FRONTPANEL)
37 #include "FrontPanel.h"
40 #include "RetainerProfile.h"
41 #include "RaiseAsync.h"
53 #include <string.h> // for memset()
55 /* -----------------------------------------------------------------------------
57 -------------------------------------------------------------------------- */
59 /* STATIC OBJECT LIST.
62 * We maintain a linked list of static objects that are still live.
63 * The requirements for this list are:
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).
69 * - we need to be able to tell whether an object is already on
70 * the list, to break loops.
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
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.
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.
84 * Extra notes for generational GC:
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.
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.
93 StgClosure* static_objects; // live static objects
94 StgClosure* scavenged_static_objects; // static objects scavenged so far
96 SpinLock static_objects_sync;
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.
107 /* Data used for allocation area sizing.
109 static lnat g0s0_pcnt_kept = 30; // percentage of g0s0 live at last minor GC
119 /* Thread-local data for each GC thread
121 gc_thread *gc_threads = NULL;
122 // gc_thread *gct = NULL; // this thread's gct TODO: make thread-local
125 long copied; // *words* copied & scavenged during this GC
128 SpinLock recordMutableGen_sync;
131 /* -----------------------------------------------------------------------------
132 Static function declarations
133 -------------------------------------------------------------------------- */
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);
151 #if 0 && defined(DEBUG)
152 static void gcCAFs (void);
155 /* -----------------------------------------------------------------------------
156 The mark bitmap & stack.
157 -------------------------------------------------------------------------- */
159 #define MARK_STACK_BLOCKS 4
161 bdescr *mark_stack_bdescr;
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;
172 /* -----------------------------------------------------------------------------
173 GarbageCollect: the main entry point to the garbage collector.
175 Locks held: all capabilities are held throughout GarbageCollect().
176 -------------------------------------------------------------------------- */
179 GarbageCollect ( rtsBool force_major_gc )
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;
189 // necessary if we stole a callee-saves register for gct:
193 CostCentreStack *prev_CCS;
198 debugTrace(DEBUG_gc, "starting GC");
200 #if defined(RTS_USER_SIGNALS)
201 if (RtsFlags.MiscFlags.install_signal_handlers) {
207 // tell the STM to discard any cached closures it's hoping to re-use
210 // tell the stats department that we've started a GC
214 // check for memory leaks if DEBUG is on
224 // attribute any costs to CCS_GC
230 /* Approximate how much we allocated.
231 * Todo: only when generating stats?
233 allocated = calcAllocated();
235 /* Figure out which generation to collect
237 initialise_N(force_major_gc);
239 /* Allocate + initialise the gc_thread structures.
243 /* Start threads, so they can be spinning up while we finish initialisation.
247 /* How many threads will be participating in this GC?
248 * We don't try to parallelise minor GC.
250 #if defined(THREADED_RTS)
254 n_threads = RtsFlags.ParFlags.gcThreads;
260 #ifdef RTS_GTK_FRONTPANEL
261 if (RtsFlags.GcFlags.frontpanel) {
262 updateFrontPanelBeforeGC(N);
266 // check stack sanity *before* GC (ToDo: check all threads)
267 IF_DEBUG(sanity, checkFreeListSanity());
269 /* Initialise the static object lists
271 static_objects = END_OF_STATIC_LIST;
272 scavenged_static_objects = END_OF_STATIC_LIST;
275 initSpinLock(&static_objects_sync);
276 initSpinLock(&recordMutableGen_sync);
277 initSpinLock(&gc_alloc_block_sync);
280 // Initialise all the generations/steps that we're collecting.
281 for (g = 0; g <= N; g++) {
282 init_collected_gen(g,n_threads);
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);
290 /* Allocate a mark stack if we're doing a major collection.
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);
298 mark_stack_bdescr = NULL;
301 // Initialise all our gc_thread structures
302 for (t = 0; t < n_threads; t++) {
303 init_gc_thread(&gc_threads[t]);
306 // the main thread is running: this prevents any other threads from
307 // exiting prematurely, so we can start them now.
309 wakeup_gc_threads(n_threads);
314 // this is the main thread
315 gct = &gc_threads[0];
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.
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.
331 for (g = RtsFlags.GcFlags.generations-1; g > N; g--) {
332 scavenge_mutable_list(&generations[g]);
336 // follow roots from the CAF list (used by GHCi)
340 // follow all the roots that the application knows about.
344 // Mark the weak pointer list, and prepare to detect dead weak pointers.
348 // Mark the stable pointer table.
349 markStablePtrTable(mark_root);
351 /* -------------------------------------------------------------------------
352 * Repeatedly scavenge all the areas we know about until there's no
353 * more scavenging to be done.
358 // The other threads are now stopped. We might recurse back to
359 // here, but from now on this is the only thread.
361 // if any blackholes are alive, make the threads that wait on
363 if (traverseBlackholeQueue()) {
368 // must be last... invariant is that everything is fully
369 // scavenged at this point.
370 if (traverseWeakPtrList()) { // returns rtsTrue if evaced something
375 // If we get to here, there's really nothing left to do.
379 // Update pointers from the Task list
382 // Now see which stable names are still alive.
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)
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;
401 IF_DEBUG(sanity, checkGlobalTSOList(rtsFalse));
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);
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
421 for (t = 0; t < n_threads; t++) {
422 thr = &gc_threads[t];
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;
430 // ASSERT( ws->scan_bd == ws->todo_bd );
431 ASSERT( ws->scan_bd ? ws->scan == ws->scan_bd->free : 1 );
433 // Push the final block
434 if (ws->scan_bd) { push_scan_block(ws->scan_bd, ws); }
436 ASSERT(countBlocks(ws->scavd_list) == ws->n_scavd_blocks);
438 prev = ws->scavd_list;
439 for (bd = ws->scavd_list; bd != NULL; bd = bd->link) {
440 bd->flags &= ~BF_EVACUATED; // now from-space
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);
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;
465 /* run through all the generations/steps and tidy up
467 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
470 generations[g].collections++; // for stats
473 // Count the mutable list as bytes "copied" for the purposes of
474 // stats. Every mutable list is copied during every GC.
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;
480 copied += mut_list_size;
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);
488 for (s = 0; s < generations[g].n_steps; s++) {
490 stp = &generations[g].steps[s];
492 // for generations we collected...
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.
499 if (!(g == 0 && s == 0 && RtsFlags.GcFlags.generations > 1)) {
500 if (stp->is_compacted)
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
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;
517 bd->link = stp->blocks;
520 stp->blocks = stp->old_blocks;
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);
528 freeChain(stp->old_blocks);
530 stp->old_blocks = NULL;
531 stp->n_old_blocks = 0;
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.
539 for (bd = stp->large_objects; bd != NULL; bd = next) {
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;
549 stp->large_objects = stp->scavenged_large_objects;
550 stp->n_large_blocks = stp->n_scavenged_large_blocks;
553 else // for older generations...
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.
559 for (bd = stp->scavenged_large_objects; bd; bd = next) {
561 bd->flags &= ~BF_EVACUATED;
562 dbl_link_onto(bd, &stp->large_objects);
565 // add the new blocks we promoted during this GC
566 stp->n_large_blocks += stp->n_scavenged_large_blocks;
571 // update the max size of older generations after a major GC
572 resize_generations();
574 // Guess the amount of live data for stats.
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);
587 alloc_blocks_lim = RtsFlags.GcFlags.minAllocAreaSize;
589 // Start a new pinned_object_block
590 pinned_object_block = NULL;
592 // Free the mark stack.
593 if (mark_stack_bdescr != NULL) {
594 freeGroup(mark_stack_bdescr);
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);
610 // mark the garbage collected CAFs as dead
611 #if 0 && defined(DEBUG) // doesn't work at the moment
612 if (major_gc) { gcCAFs(); }
616 // resetStaticObjectForRetainerProfiling() must be called before
618 resetStaticObjectForRetainerProfiling();
621 // zero the scavenged static object list
623 zero_static_object_list(scavenged_static_objects);
629 // start any pending finalizers
631 scheduleFinalizers(last_free_capability, old_weak_ptr_list);
634 // send exceptions to any threads which were about to die
636 resurrectThreads(resurrected_threads);
639 // Update the stable pointer hash table.
640 updateStablePtrTable(major_gc);
642 // check sanity after GC
643 IF_DEBUG(sanity, checkSanity());
645 // extra GC trace info
646 IF_DEBUG(gc, statDescribeGens());
649 // symbol-table based profiling
650 /* heapCensus(to_blocks); */ /* ToDo */
653 // restore enclosing cost centre
659 // check for memory leaks if DEBUG is on
663 #ifdef RTS_GTK_FRONTPANEL
664 if (RtsFlags.GcFlags.frontpanel) {
665 updateFrontPanelAfterGC( N, live );
669 // ok, GC over: tell the stats department what happened.
670 stat_endGC(allocated, live, copied, N);
672 #if defined(RTS_USER_SIGNALS)
673 if (RtsFlags.MiscFlags.install_signal_handlers) {
674 // unblock signals again
675 unblockUserSignals();
684 /* ---------------------------------------------------------------------------
685 Where are the roots that we know about?
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"
693 ------------------------------------------------------------------------ */
695 /* This has to be protected either by the scheduler monitor, or by the
696 garbage collection monitor (probably the latter).
701 GetRoots( evac_fn evac )
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);
715 for (task = cap->suspended_ccalling_tasks; task != NULL;
717 debugTrace(DEBUG_sched,
718 "evac'ing suspended TSO %lu", (unsigned long)task->suspended_tso->id);
719 evac((StgClosure **)(void *)&task->suspended_tso);
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);
730 // evac((StgClosure **)&blackhole_queue);
732 #if defined(THREADED_RTS)
733 markSparkQueue(evac);
736 #if defined(RTS_USER_SIGNALS)
737 // mark the signal handlers (signals should be already blocked)
738 markSignalHandlers(evac);
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.
747 NOTE: Use it before compaction only!
748 It untags and (if needed) retags pointers to closures.
749 -------------------------------------------------------------------------- */
753 isAlive(StgClosure *p)
755 const StgInfoTable *info;
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);
765 ASSERT(LOOKS_LIKE_CLOSURE_PTR(q));
768 // ignore static closures
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.
774 if (!HEAP_ALLOCED(q)) {
778 // ignore closures in generations that we're not collecting.
780 if (bd->gen_no > N) {
784 // if it's a pointer into to-space, then we're done
785 if (bd->flags & BF_EVACUATED) {
789 // large objects use the evacuated flag
790 if (bd->flags & BF_LARGE) {
794 // check the mark bit for compacted steps
795 if ((bd->flags & BF_COMPACTED) && is_marked((P_)q,bd)) {
799 switch (info->type) {
804 case IND_OLDGEN: // rely on compatible layout with StgInd
805 case IND_OLDGEN_PERM:
806 // follow indirections
807 p = ((StgInd *)q)->indirectee;
812 return ((StgEvacuated *)q)->evacuee;
815 if (((StgTSO *)q)->what_next == ThreadRelocated) {
816 p = (StgClosure *)((StgTSO *)q)->link;
828 /* -----------------------------------------------------------------------------
829 Figure out which generation to collect, initialise N and major_gc.
830 -------------------------------------------------------------------------- */
833 initialise_N (rtsBool force_major_gc)
837 if (force_major_gc) {
838 N = RtsFlags.GcFlags.generations - 1;
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) {
849 major_gc = (N == RtsFlags.GcFlags.generations-1);
853 /* -----------------------------------------------------------------------------
854 Initialise the gc_thread structures.
855 -------------------------------------------------------------------------- */
858 alloc_gc_thread (gc_thread *t, int n)
865 initCondition(&t->wake_cond);
866 initMutex(&t->wake_mutex);
867 t->wakeup = rtsFalse;
872 t->free_blocks = NULL;
881 t->steps = stgMallocBytes(RtsFlags.GcFlags.generations *
882 sizeof(step_workspace *),
883 "initialise_gc_thread");
885 for (g = 0; g < RtsFlags.GcFlags.generations; g++)
887 t->steps[g] = stgMallocBytes(generations[g].n_steps *
888 sizeof(step_workspace),
889 "initialise_gc_thread/2");
891 for (s = 0; s < generations[g].n_steps; s++)
893 ws = &t->steps[g][s];
894 ws->stp = &generations[g].steps[s];
901 ws->buffer_todo_bd = NULL;
903 ws->scavd_list = NULL;
904 ws->n_scavd_blocks = 0;
911 alloc_gc_threads (void)
913 if (gc_threads == NULL) {
914 #if defined(THREADED_RTS)
916 gc_threads = stgMallocBytes (RtsFlags.ParFlags.gcThreads *
920 for (i = 0; i < RtsFlags.ParFlags.gcThreads; i++) {
921 alloc_gc_thread(&gc_threads[i], i);
924 gc_threads = stgMallocBytes (sizeof(gc_thread),
927 alloc_gc_thread(gc_threads, 0);
932 /* ----------------------------------------------------------------------------
934 ------------------------------------------------------------------------- */
936 static nat gc_running_threads;
938 #if defined(THREADED_RTS)
939 static Mutex gc_running_mutex;
946 ACQUIRE_LOCK(&gc_running_mutex);
947 n_running = ++gc_running_threads;
948 RELEASE_LOCK(&gc_running_mutex);
956 ACQUIRE_LOCK(&gc_running_mutex);
957 n_running = --gc_running_threads;
958 RELEASE_LOCK(&gc_running_mutex);
963 // gc_thread_work(): Scavenge until there's no work left to do and all
964 // the running threads are idle.
967 gc_thread_work (void)
971 debugTrace(DEBUG_gc, "GC thread %d working", gct->thread_index);
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.
980 // scavenge_loop() only exits when there's no work to do
983 debugTrace(DEBUG_gc, "GC thread %d idle (%d still running)",
984 gct->thread_index, r);
986 while (gc_running_threads != 0) {
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.
997 // All threads are now stopped
998 debugTrace(DEBUG_gc, "GC thread %d finished.", gct->thread_index);
1002 #if defined(THREADED_RTS)
1004 gc_thread_mainloop (void)
1006 while (!gct->exit) {
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...",
1013 waitCondition(&gct->wake_cond, &gct->wake_mutex);
1015 RELEASE_LOCK(&gct->wake_mutex);
1016 gct->wakeup = rtsFalse;
1017 if (gct->exit) break;
1020 // start performance counters in this thread...
1021 if (gct->papi_events == -1) {
1022 papi_init_eventset(&gct->papi_events);
1024 papi_thread_start_gc_count(gct->papi_events);
1030 // count events in this thread towards the GC totals
1031 papi_thread_stop_gc_count(gct->papi_events);
1037 #if defined(THREADED_RTS)
1039 gc_thread_entry (gc_thread *my_gct)
1042 debugTrace(DEBUG_gc, "GC thread %d starting...", gct->thread_index);
1043 gct->id = osThreadId();
1044 gc_thread_mainloop();
1049 start_gc_threads (void)
1051 #if defined(THREADED_RTS)
1054 static rtsBool done = rtsFalse;
1056 gc_running_threads = 0;
1057 initMutex(&gc_running_mutex);
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,
1071 wakeup_gc_threads (nat n_threads USED_IF_THREADS)
1073 #if defined(THREADED_RTS)
1075 for (i=1; i < n_threads; i++) {
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);
1085 /* ----------------------------------------------------------------------------
1086 Initialise a generation that is to be collected
1087 ------------------------------------------------------------------------- */
1090 init_collected_gen (nat g, nat n_threads)
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().
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();
1109 for (s = 0; s < generations[g].n_steps; s++) {
1111 // generation 0, step 0 doesn't need to-space
1112 if (g == 0 && s == 0 && RtsFlags.GcFlags.generations > 1) {
1116 stp = &generations[g].steps[s];
1117 ASSERT(stp->gen_no == g);
1119 // deprecate the existing blocks
1120 stp->old_blocks = stp->blocks;
1121 stp->n_old_blocks = stp->n_blocks;
1125 // we don't have any to-be-scavenged blocks yet
1129 // initialise the large object queues.
1130 stp->scavenged_large_objects = NULL;
1131 stp->n_scavenged_large_blocks = 0;
1133 // mark the large objects as not evacuated yet
1134 for (bd = stp->large_objects; bd; bd = bd->link) {
1135 bd->flags &= ~BF_EVACUATED;
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;
1144 bitmap_size = stp->n_old_blocks * BLOCK_SIZE / (sizeof(W_)*BITS_PER_BYTE);
1146 if (bitmap_size > 0) {
1147 bitmap_bdescr = allocGroup((lnat)BLOCK_ROUND_UP(bitmap_size)
1149 stp->bitmap = bitmap_bdescr;
1150 bitmap = bitmap_bdescr->start;
1152 debugTrace(DEBUG_gc, "bitmap_size: %d, bitmap: %p",
1153 bitmap_size, bitmap);
1155 // don't forget to fill it with zeros!
1156 memset(bitmap, 0, bitmap_size);
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);
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
1169 bd->flags |= BF_COMPACTED;
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++) {
1181 // we don't copy objects into g0s0, unless -G0
1182 if (g==0 && s==0 && RtsFlags.GcFlags.generations > 1) continue;
1184 ws = &gc_threads[t].steps[g][s];
1189 ws->todo_large_objects = NULL;
1191 // allocate the first to-space block; extra blocks will be
1192 // chained on as necessary.
1194 ws->buffer_todo_bd = NULL;
1195 gc_alloc_todo_block(ws);
1197 ws->scavd_list = NULL;
1198 ws->n_scavd_blocks = 0;
1204 /* ----------------------------------------------------------------------------
1205 Initialise a generation that is *not* to be collected
1206 ------------------------------------------------------------------------- */
1209 init_uncollected_gen (nat g, nat threads)
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;
1222 for (t = 0; t < threads; t++) {
1223 for (s = 0; s < generations[g].n_steps; s++) {
1225 ws = &gc_threads[t].steps[g][s];
1228 ws->buffer_todo_bd = NULL;
1229 ws->todo_large_objects = NULL;
1231 ws->scavd_list = NULL;
1232 ws->n_scavd_blocks = 0;
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))
1238 ws->todo_bd = stp->blocks;
1239 stp->blocks = stp->blocks->link;
1241 ws->todo_bd->link = NULL;
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;
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;
1257 gc_alloc_todo_block(ws);
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) {
1269 bd->link = generations[g].mut_list;
1270 generations[g].mut_list = capabilities[i].mut_lists[g];
1271 capabilities[i].mut_lists[g] = allocBlock();
1275 /* -----------------------------------------------------------------------------
1276 Initialise a gc_thread before GC
1277 -------------------------------------------------------------------------- */
1280 init_gc_thread (gc_thread *t)
1283 t->failed_to_evac = rtsFalse;
1284 t->eager_promotion = rtsTrue;
1285 t->thunk_selector_depth = 0;
1288 /* -----------------------------------------------------------------------------
1289 Function we pass to GetRoots to evacuate roots.
1290 -------------------------------------------------------------------------- */
1293 mark_root(StgClosure **root)
1298 /* -----------------------------------------------------------------------------
1299 Initialising the static object & mutable lists
1300 -------------------------------------------------------------------------- */
1303 zero_static_object_list(StgClosure* first_static)
1307 const StgInfoTable *info;
1309 for (p = first_static; p != END_OF_STATIC_LIST; p = link) {
1311 link = *STATIC_LINK(info, p);
1312 *STATIC_LINK(info,p) = NULL;
1316 /* -----------------------------------------------------------------------------
1318 -------------------------------------------------------------------------- */
1325 for (c = (StgIndStatic *)revertible_caf_list; c != NULL;
1326 c = (StgIndStatic *)c->static_link)
1328 SET_INFO(c, c->saved_info);
1329 c->saved_info = NULL;
1330 // could, but not necessary: c->static_link = NULL;
1332 revertible_caf_list = NULL;
1336 markCAFs( evac_fn evac )
1340 for (c = (StgIndStatic *)caf_list; c != NULL;
1341 c = (StgIndStatic *)c->static_link)
1343 evac(&c->indirectee);
1345 for (c = (StgIndStatic *)revertible_caf_list; c != NULL;
1346 c = (StgIndStatic *)c->static_link)
1348 evac(&c->indirectee);
1352 /* ----------------------------------------------------------------------------
1353 Update the pointers from the task list
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 ------------------------------------------------------------------------- */
1363 update_task_list (void)
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);
1372 barf("task %p: main thread %d has been GC'd",
1385 /* ----------------------------------------------------------------------------
1386 Reset the sizes of the older generations when we do a major
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 ------------------------------------------------------------------------- */
1395 resize_generations (void)
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;
1404 // live in the oldest generations
1405 live = oldest_gen->steps[0].n_blocks +
1406 oldest_gen->steps[0].n_large_blocks;
1408 // default max size for all generations except zero
1409 size = stg_max(live * RtsFlags.GcFlags.oldGenFactor,
1410 RtsFlags.GcFlags.minOldGenSize);
1412 // minimum size for generation zero
1413 min_alloc = stg_max((RtsFlags.GcFlags.pcFreeHeap * max) / 200,
1414 RtsFlags.GcFlags.minAllocAreaSize);
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 ||
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);
1426 oldest_gen->steps[0].is_compacted = 0;
1427 // debugBelch("compaction: off\n", live);
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.
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) {
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);
1448 if ( (size * (gens - 1) * 2) + min_alloc > max ) {
1449 size = (max - min_alloc) / ((gens - 1) * 2);
1459 debugBelch("live: %d, min_alloc: %d, size : %d, max = %d\n", live,
1460 min_alloc, size, max);
1463 for (g = 0; g < gens; g++) {
1464 generations[g].max_blocks = size;
1469 /* -----------------------------------------------------------------------------
1470 Calculate the new size of the nursery, and resize it.
1471 -------------------------------------------------------------------------- */
1474 resize_nursery (void)
1476 if (RtsFlags.GcFlags.generations == 1)
1477 { // Two-space collector:
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
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.
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.
1494 blocks = g0s0->n_old_blocks;
1496 if ( RtsFlags.GcFlags.maxHeapSize != 0 &&
1497 blocks * RtsFlags.GcFlags.oldGenFactor * 2 >
1498 RtsFlags.GcFlags.maxHeapSize )
1500 long adjusted_blocks; // signed on purpose
1503 adjusted_blocks = (RtsFlags.GcFlags.maxHeapSize - 2 * blocks);
1505 debugTrace(DEBUG_gc, "near maximum heap size of 0x%x blocks, blocks = %d, adjusted to %ld",
1506 RtsFlags.GcFlags.maxHeapSize, blocks, adjusted_blocks);
1508 pc_free = adjusted_blocks * 100 / RtsFlags.GcFlags.maxHeapSize;
1509 if (pc_free < RtsFlags.GcFlags.pcFreeHeap) /* might even * be < 0 */
1513 blocks = adjusted_blocks;
1517 blocks *= RtsFlags.GcFlags.oldGenFactor;
1518 if (blocks < RtsFlags.GcFlags.minAllocAreaSize)
1520 blocks = RtsFlags.GcFlags.minAllocAreaSize;
1523 resizeNurseries(blocks);
1525 else // Generational collector
1528 * If the user has given us a suggested heap size, adjust our
1529 * allocation area to make best use of the memory available.
1531 if (RtsFlags.GcFlags.heapSizeSuggestion)
1534 nat needed = calcNeeded(); // approx blocks needed at next GC
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.
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
1547 g0s0_pcnt_kept = ((copied / (BLOCK_SIZE_W - 10)) * 100)
1548 / countNurseryBlocks();
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
1556 * Formula: suggested - needed
1557 * ----------------------------
1558 * 1 + g0s0_pcnt_kept/100
1560 * where 'needed' is the amount of memory needed at the next
1561 * collection for collecting all steps except g0s0.
1564 (((long)RtsFlags.GcFlags.heapSizeSuggestion - (long)needed) * 100) /
1565 (100 + (long)g0s0_pcnt_kept);
1567 if (blocks < (long)RtsFlags.GcFlags.minAllocAreaSize) {
1568 blocks = RtsFlags.GcFlags.minAllocAreaSize;
1571 resizeNurseries((nat)blocks);
1575 // we might have added extra large blocks to the nursery, so
1576 // resize back to minAllocAreaSize again.
1577 resizeNurseriesFixed(RtsFlags.GcFlags.minAllocAreaSize);
1582 /* -----------------------------------------------------------------------------
1583 Sanity code for CAF garbage collection.
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.
1590 Any garbage collected CAFs are taken off the CAF list at the same
1592 -------------------------------------------------------------------------- */
1594 #if 0 && defined(DEBUG)
1601 const StgInfoTable *info;
1612 ASSERT(info->type == IND_STATIC);
1614 if (STATIC_LINK(info,p) == NULL) {
1615 debugTrace(DEBUG_gccafs, "CAF gc'd at 0x%04lx", (long)p);
1617 SET_INFO(p,&stg_BLACKHOLE_info);
1618 p = STATIC_LINK2(info,p);
1622 pp = &STATIC_LINK2(info,p);
1629 debugTrace(DEBUG_gccafs, "%d CAFs live", i);