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"
52 #include <string.h> // for memset()
54 /* -----------------------------------------------------------------------------
56 -------------------------------------------------------------------------- */
58 /* STATIC OBJECT LIST.
61 * We maintain a linked list of static objects that are still live.
62 * The requirements for this list are:
64 * - we need to scan the list while adding to it, in order to
65 * scavenge all the static objects (in the same way that
66 * breadth-first scavenging works for dynamic objects).
68 * - we need to be able to tell whether an object is already on
69 * the list, to break loops.
71 * Each static object has a "static link field", which we use for
72 * linking objects on to the list. We use a stack-type list, consing
73 * objects on the front as they are added (this means that the
74 * scavenge phase is depth-first, not breadth-first, but that
77 * A separate list is kept for objects that have been scavenged
78 * already - this is so that we can zero all the marks afterwards.
80 * An object is on the list if its static link field is non-zero; this
81 * means that we have to mark the end of the list with '1', not NULL.
83 * Extra notes for generational GC:
85 * Each generation has a static object list associated with it. When
86 * collecting generations up to N, we treat the static object lists
87 * from generations > N as roots.
89 * We build up a static object list while collecting generations 0..N,
90 * which is then appended to the static object list of generation N+1.
92 StgClosure* static_objects; // live static objects
93 StgClosure* scavenged_static_objects; // static objects scavenged so far
95 SpinLock static_objects_sync;
98 /* N is the oldest generation being collected, where the generations
99 * are numbered starting at 0. A major GC (indicated by the major_gc
100 * flag) is when we're collecting all generations. We only attempt to
101 * deal with static objects and GC CAFs when doing a major GC.
106 /* Data used for allocation area sizing.
108 static lnat g0s0_pcnt_kept = 30; // percentage of g0s0 live at last minor GC
118 /* Thread-local data for each GC thread
120 gc_thread *gc_threads = NULL;
121 // gc_thread *gct = NULL; // this thread's gct TODO: make thread-local
124 long copied; // *words* copied & scavenged during this GC
127 SpinLock recordMutableGen_sync;
130 /* -----------------------------------------------------------------------------
131 Static function declarations
132 -------------------------------------------------------------------------- */
134 static void mark_root (StgClosure **root);
135 static void zero_static_object_list (StgClosure* first_static);
136 static void initialise_N (rtsBool force_major_gc);
137 static void alloc_gc_threads (void);
138 static void init_collected_gen (nat g, nat threads);
139 static void init_uncollected_gen (nat g, nat threads);
140 static void init_gc_thread (gc_thread *t);
141 static void update_task_list (void);
142 static void resize_generations (void);
143 static void resize_nursery (void);
144 static void start_gc_threads (void);
145 static void gc_thread_work (void);
146 static nat inc_running (void);
147 static nat dec_running (void);
148 static void wakeup_gc_threads (nat n_threads);
150 #if 0 && defined(DEBUG)
151 static void gcCAFs (void);
154 /* -----------------------------------------------------------------------------
155 The mark bitmap & stack.
156 -------------------------------------------------------------------------- */
158 #define MARK_STACK_BLOCKS 4
160 bdescr *mark_stack_bdescr;
165 // Flag and pointers used for falling back to a linear scan when the
166 // mark stack overflows.
167 rtsBool mark_stack_overflowed;
168 bdescr *oldgen_scan_bd;
171 /* -----------------------------------------------------------------------------
172 GarbageCollect: the main entry point to the garbage collector.
174 Locks held: all capabilities are held throughout GarbageCollect().
175 -------------------------------------------------------------------------- */
178 GarbageCollect ( rtsBool force_major_gc )
182 lnat live, allocated;
183 lnat oldgen_saved_blocks = 0;
184 nat n_threads; // number of threads participating in GC
185 gc_thread *saved_gct;
188 // necessary if we stole a callee-saves register for gct:
192 CostCentreStack *prev_CCS;
197 debugTrace(DEBUG_gc, "starting GC");
199 #if defined(RTS_USER_SIGNALS)
200 if (RtsFlags.MiscFlags.install_signal_handlers) {
206 // tell the STM to discard any cached closures it's hoping to re-use
209 // tell the stats department that we've started a GC
213 // check for memory leaks if DEBUG is on
223 // attribute any costs to CCS_GC
229 /* Approximate how much we allocated.
230 * Todo: only when generating stats?
232 allocated = calcAllocated();
234 /* Figure out which generation to collect
236 initialise_N(force_major_gc);
238 /* Allocate + initialise the gc_thread structures.
242 /* Start threads, so they can be spinning up while we finish initialisation.
246 /* How many threads will be participating in this GC?
247 * We don't try to parallelise minor GC.
249 #if defined(THREADED_RTS)
253 n_threads = RtsFlags.ParFlags.gcThreads;
259 #ifdef RTS_GTK_FRONTPANEL
260 if (RtsFlags.GcFlags.frontpanel) {
261 updateFrontPanelBeforeGC(N);
265 // check stack sanity *before* GC (ToDo: check all threads)
266 IF_DEBUG(sanity, checkFreeListSanity());
268 /* Initialise the static object lists
270 static_objects = END_OF_STATIC_LIST;
271 scavenged_static_objects = END_OF_STATIC_LIST;
274 initSpinLock(&static_objects_sync);
275 initSpinLock(&recordMutableGen_sync);
276 initSpinLock(&gc_alloc_block_sync);
279 // Initialise all the generations/steps that we're collecting.
280 for (g = 0; g <= N; g++) {
281 init_collected_gen(g,n_threads);
284 // Initialise all the generations/steps that we're *not* collecting.
285 for (g = N+1; g < RtsFlags.GcFlags.generations; g++) {
286 init_uncollected_gen(g,n_threads);
289 /* Allocate a mark stack if we're doing a major collection.
292 mark_stack_bdescr = allocGroup(MARK_STACK_BLOCKS);
293 mark_stack = (StgPtr *)mark_stack_bdescr->start;
294 mark_sp = mark_stack;
295 mark_splim = mark_stack + (MARK_STACK_BLOCKS * BLOCK_SIZE_W);
297 mark_stack_bdescr = NULL;
300 // Initialise all our gc_thread structures
301 for (t = 0; t < n_threads; t++) {
302 init_gc_thread(&gc_threads[t]);
305 // the main thread is running: this prevents any other threads from
306 // exiting prematurely, so we can start them now.
308 wakeup_gc_threads(n_threads);
313 // this is the main thread
314 gct = &gc_threads[0];
316 /* -----------------------------------------------------------------------
317 * follow all the roots that we know about:
318 * - mutable lists from each generation > N
319 * we want to *scavenge* these roots, not evacuate them: they're not
320 * going to move in this GC.
321 * Also do them in reverse generation order, for the usual reason:
322 * namely to reduce the likelihood of spurious old->new pointers.
325 for (g = RtsFlags.GcFlags.generations-1; g > N; g--) {
326 generations[g].saved_mut_list = generations[g].mut_list;
327 generations[g].mut_list = allocBlock();
328 // mut_list always has at least one block.
330 for (g = RtsFlags.GcFlags.generations-1; g > N; g--) {
331 scavenge_mutable_list(&generations[g]);
335 // follow roots from the CAF list (used by GHCi)
339 // follow all the roots that the application knows about.
343 // Mark the weak pointer list, and prepare to detect dead weak pointers.
347 // Mark the stable pointer table.
348 markStablePtrTable(mark_root);
350 /* -------------------------------------------------------------------------
351 * Repeatedly scavenge all the areas we know about until there's no
352 * more scavenging to be done.
357 // The other threads are now stopped. We might recurse back to
358 // here, but from now on this is the only thread.
360 // if any blackholes are alive, make the threads that wait on
362 if (traverseBlackholeQueue()) {
367 // must be last... invariant is that everything is fully
368 // scavenged at this point.
369 if (traverseWeakPtrList()) { // returns rtsTrue if evaced something
374 // If we get to here, there's really nothing left to do.
378 // Update pointers from the Task list
381 // Now see which stable names are still alive.
385 // We call processHeapClosureForDead() on every closure destroyed during
386 // the current garbage collection, so we invoke LdvCensusForDead().
387 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV
388 || RtsFlags.ProfFlags.bioSelector != NULL)
392 // NO MORE EVACUATION AFTER THIS POINT!
393 // Finally: compaction of the oldest generation.
394 if (major_gc && oldest_gen->steps[0].is_compacted) {
395 // save number of blocks for stats
396 oldgen_saved_blocks = oldest_gen->steps[0].n_old_blocks;
400 IF_DEBUG(sanity, checkGlobalTSOList(rtsFalse));
402 // Two-space collector: free the old to-space.
403 // g0s0->old_blocks is the old nursery
404 // g0s0->blocks is to-space from the previous GC
405 if (RtsFlags.GcFlags.generations == 1) {
406 if (g0s0->blocks != NULL) {
407 freeChain(g0s0->blocks);
412 // For each workspace, in each thread:
413 // * clear the BF_EVACUATED flag from each copied block
414 // * move the copied blocks to the step
420 for (t = 0; t < n_threads; t++) {
421 thr = &gc_threads[t];
423 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
424 for (s = 0; s < generations[g].n_steps; s++) {
425 ws = &thr->steps[g][s];
426 if (g==0 && s==0) continue;
429 // ASSERT( ws->scan_bd == ws->todo_bd );
430 ASSERT( ws->scan_bd ? ws->scan == ws->scan_bd->free : 1 );
432 // Push the final block
433 if (ws->scan_bd) { push_scan_block(ws->scan_bd, ws); }
435 ASSERT(countBlocks(ws->scavd_list) == ws->n_scavd_blocks);
437 prev = ws->scavd_list;
438 for (bd = ws->scavd_list; bd != NULL; bd = bd->link) {
439 bd->flags &= ~BF_EVACUATED; // now from-space
442 prev->link = ws->stp->blocks;
443 ws->stp->blocks = ws->scavd_list;
444 ws->stp->n_blocks += ws->n_scavd_blocks;
445 ASSERT(countBlocks(ws->stp->blocks) == ws->stp->n_blocks);
451 // Two-space collector: swap the semi-spaces around.
452 // Currently: g0s0->old_blocks is the old nursery
453 // g0s0->blocks is to-space from this GC
454 // We want these the other way around.
455 if (RtsFlags.GcFlags.generations == 1) {
456 bdescr *nursery_blocks = g0s0->old_blocks;
457 nat n_nursery_blocks = g0s0->n_old_blocks;
458 g0s0->old_blocks = g0s0->blocks;
459 g0s0->n_old_blocks = g0s0->n_blocks;
460 g0s0->blocks = nursery_blocks;
461 g0s0->n_blocks = n_nursery_blocks;
464 /* run through all the generations/steps and tidy up
466 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
469 generations[g].collections++; // for stats
472 // Count the mutable list as bytes "copied" for the purposes of
473 // stats. Every mutable list is copied during every GC.
475 nat mut_list_size = 0;
476 for (bd = generations[g].mut_list; bd != NULL; bd = bd->link) {
477 mut_list_size += bd->free - bd->start;
479 copied += mut_list_size;
482 "mut_list_size: %lu (%d vars, %d arrays, %d MVARs, %d others)",
483 (unsigned long)(mut_list_size * sizeof(W_)),
484 mutlist_MUTVARS, mutlist_MUTARRS, mutlist_MVARS, mutlist_OTHERS);
487 for (s = 0; s < generations[g].n_steps; s++) {
489 stp = &generations[g].steps[s];
491 // for generations we collected...
494 /* free old memory and shift to-space into from-space for all
495 * the collected steps (except the allocation area). These
496 * freed blocks will probaby be quickly recycled.
498 if (!(g == 0 && s == 0 && RtsFlags.GcFlags.generations > 1)) {
499 if (stp->is_compacted)
501 // for a compacted step, just shift the new to-space
502 // onto the front of the now-compacted existing blocks.
503 for (bd = stp->blocks; bd != NULL; bd = bd->link) {
504 bd->flags &= ~BF_EVACUATED; // now from-space
506 // tack the new blocks on the end of the existing blocks
507 if (stp->old_blocks != NULL) {
508 for (bd = stp->old_blocks; bd != NULL; bd = next) {
509 // NB. this step might not be compacted next
510 // time, so reset the BF_COMPACTED flags.
511 // They are set before GC if we're going to
512 // compact. (search for BF_COMPACTED above).
513 bd->flags &= ~BF_COMPACTED;
516 bd->link = stp->blocks;
519 stp->blocks = stp->old_blocks;
521 // add the new blocks to the block tally
522 stp->n_blocks += stp->n_old_blocks;
523 ASSERT(countBlocks(stp->blocks) == stp->n_blocks);
527 freeChain(stp->old_blocks);
529 stp->old_blocks = NULL;
530 stp->n_old_blocks = 0;
533 /* LARGE OBJECTS. The current live large objects are chained on
534 * scavenged_large, having been moved during garbage
535 * collection from large_objects. Any objects left on
536 * large_objects list are therefore dead, so we free them here.
538 for (bd = stp->large_objects; bd != NULL; bd = next) {
544 // update the count of blocks used by large objects
545 for (bd = stp->scavenged_large_objects; bd != NULL; bd = bd->link) {
546 bd->flags &= ~BF_EVACUATED;
548 stp->large_objects = stp->scavenged_large_objects;
549 stp->n_large_blocks = stp->n_scavenged_large_blocks;
552 else // for older generations...
554 /* For older generations, we need to append the
555 * scavenged_large_object list (i.e. large objects that have been
556 * promoted during this GC) to the large_object list for that step.
558 for (bd = stp->scavenged_large_objects; bd; bd = next) {
560 bd->flags &= ~BF_EVACUATED;
561 dbl_link_onto(bd, &stp->large_objects);
564 // add the new blocks we promoted during this GC
565 stp->n_large_blocks += stp->n_scavenged_large_blocks;
570 // update the max size of older generations after a major GC
571 resize_generations();
573 // Guess the amount of live data for stats.
576 // Free the small objects allocated via allocate(), since this will
577 // all have been copied into G0S1 now.
578 if (RtsFlags.GcFlags.generations > 1) {
579 if (g0s0->blocks != NULL) {
580 freeChain(g0s0->blocks);
586 alloc_blocks_lim = RtsFlags.GcFlags.minAllocAreaSize;
588 // Start a new pinned_object_block
589 pinned_object_block = NULL;
591 // Free the mark stack.
592 if (mark_stack_bdescr != NULL) {
593 freeGroup(mark_stack_bdescr);
597 for (g = 0; g <= N; g++) {
598 for (s = 0; s < generations[g].n_steps; s++) {
599 stp = &generations[g].steps[s];
600 if (stp->bitmap != NULL) {
601 freeGroup(stp->bitmap);
609 // mark the garbage collected CAFs as dead
610 #if 0 && defined(DEBUG) // doesn't work at the moment
611 if (major_gc) { gcCAFs(); }
615 // resetStaticObjectForRetainerProfiling() must be called before
617 resetStaticObjectForRetainerProfiling();
620 // zero the scavenged static object list
622 zero_static_object_list(scavenged_static_objects);
628 // start any pending finalizers
630 scheduleFinalizers(last_free_capability, old_weak_ptr_list);
633 // send exceptions to any threads which were about to die
635 resurrectThreads(resurrected_threads);
638 // Update the stable pointer hash table.
639 updateStablePtrTable(major_gc);
641 // check sanity after GC
642 IF_DEBUG(sanity, checkSanity());
644 // extra GC trace info
645 IF_DEBUG(gc, statDescribeGens());
648 // symbol-table based profiling
649 /* heapCensus(to_blocks); */ /* ToDo */
652 // restore enclosing cost centre
658 // check for memory leaks if DEBUG is on
662 #ifdef RTS_GTK_FRONTPANEL
663 if (RtsFlags.GcFlags.frontpanel) {
664 updateFrontPanelAfterGC( N, live );
668 // ok, GC over: tell the stats department what happened.
669 stat_endGC(allocated, live, copied, N);
671 #if defined(RTS_USER_SIGNALS)
672 if (RtsFlags.MiscFlags.install_signal_handlers) {
673 // unblock signals again
674 unblockUserSignals();
683 /* ---------------------------------------------------------------------------
684 Where are the roots that we know about?
686 - all the threads on the runnable queue
687 - all the threads on the blocked queue
688 - all the threads on the sleeping queue
689 - all the thread currently executing a _ccall_GC
690 - all the "main threads"
692 ------------------------------------------------------------------------ */
694 /* This has to be protected either by the scheduler monitor, or by the
695 garbage collection monitor (probably the latter).
700 GetRoots( evac_fn evac )
706 for (i = 0; i < n_capabilities; i++) {
707 cap = &capabilities[i];
708 evac((StgClosure **)(void *)&cap->run_queue_hd);
709 evac((StgClosure **)(void *)&cap->run_queue_tl);
710 #if defined(THREADED_RTS)
711 evac((StgClosure **)(void *)&cap->wakeup_queue_hd);
712 evac((StgClosure **)(void *)&cap->wakeup_queue_tl);
714 for (task = cap->suspended_ccalling_tasks; task != NULL;
716 debugTrace(DEBUG_sched,
717 "evac'ing suspended TSO %lu", (unsigned long)task->suspended_tso->id);
718 evac((StgClosure **)(void *)&task->suspended_tso);
723 #if !defined(THREADED_RTS)
724 evac((StgClosure **)(void *)&blocked_queue_hd);
725 evac((StgClosure **)(void *)&blocked_queue_tl);
726 evac((StgClosure **)(void *)&sleeping_queue);
729 // evac((StgClosure **)&blackhole_queue);
731 #if defined(THREADED_RTS)
732 markSparkQueue(evac);
735 #if defined(RTS_USER_SIGNALS)
736 // mark the signal handlers (signals should be already blocked)
737 markSignalHandlers(evac);
741 /* -----------------------------------------------------------------------------
742 isAlive determines whether the given closure is still alive (after
743 a garbage collection) or not. It returns the new address of the
744 closure if it is alive, or NULL otherwise.
746 NOTE: Use it before compaction only!
747 It untags and (if needed) retags pointers to closures.
748 -------------------------------------------------------------------------- */
752 isAlive(StgClosure *p)
754 const StgInfoTable *info;
760 /* The tag and the pointer are split, to be merged later when needed. */
761 tag = GET_CLOSURE_TAG(p);
762 q = UNTAG_CLOSURE(p);
764 ASSERT(LOOKS_LIKE_CLOSURE_PTR(q));
767 // ignore static closures
769 // ToDo: for static closures, check the static link field.
770 // Problem here is that we sometimes don't set the link field, eg.
771 // for static closures with an empty SRT or CONSTR_STATIC_NOCAFs.
773 if (!HEAP_ALLOCED(q)) {
777 // ignore closures in generations that we're not collecting.
779 if (bd->gen_no > N) {
783 // if it's a pointer into to-space, then we're done
784 if (bd->flags & BF_EVACUATED) {
788 // large objects use the evacuated flag
789 if (bd->flags & BF_LARGE) {
793 // check the mark bit for compacted steps
794 if ((bd->flags & BF_COMPACTED) && is_marked((P_)q,bd)) {
798 switch (info->type) {
803 case IND_OLDGEN: // rely on compatible layout with StgInd
804 case IND_OLDGEN_PERM:
805 // follow indirections
806 p = ((StgInd *)q)->indirectee;
811 return ((StgEvacuated *)q)->evacuee;
814 if (((StgTSO *)q)->what_next == ThreadRelocated) {
815 p = (StgClosure *)((StgTSO *)q)->link;
827 /* -----------------------------------------------------------------------------
828 Figure out which generation to collect, initialise N and major_gc.
829 -------------------------------------------------------------------------- */
832 initialise_N (rtsBool force_major_gc)
836 if (force_major_gc) {
837 N = RtsFlags.GcFlags.generations - 1;
841 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
842 if (generations[g].steps[0].n_blocks +
843 generations[g].steps[0].n_large_blocks
844 >= generations[g].max_blocks) {
848 major_gc = (N == RtsFlags.GcFlags.generations-1);
852 /* -----------------------------------------------------------------------------
853 Initialise the gc_thread structures.
854 -------------------------------------------------------------------------- */
857 alloc_gc_thread (gc_thread *t, int n)
864 initCondition(&t->wake_cond);
865 initMutex(&t->wake_mutex);
866 t->wakeup = rtsFalse;
871 t->free_blocks = NULL;
876 t->steps = stgMallocBytes(RtsFlags.GcFlags.generations *
877 sizeof(step_workspace *),
878 "initialise_gc_thread");
880 for (g = 0; g < RtsFlags.GcFlags.generations; g++)
882 t->steps[g] = stgMallocBytes(generations[g].n_steps *
883 sizeof(step_workspace),
884 "initialise_gc_thread/2");
886 for (s = 0; s < generations[g].n_steps; s++)
888 ws = &t->steps[g][s];
889 ws->stp = &generations[g].steps[s];
896 ws->buffer_todo_bd = NULL;
898 ws->scavd_list = NULL;
899 ws->n_scavd_blocks = 0;
906 alloc_gc_threads (void)
908 if (gc_threads == NULL) {
909 #if defined(THREADED_RTS)
911 gc_threads = stgMallocBytes (RtsFlags.ParFlags.gcThreads *
915 for (i = 0; i < RtsFlags.ParFlags.gcThreads; i++) {
916 alloc_gc_thread(&gc_threads[i], i);
919 gc_threads = stgMallocBytes (sizeof(gc_thread),
922 alloc_gc_thread(gc_threads, 0);
927 /* ----------------------------------------------------------------------------
929 ------------------------------------------------------------------------- */
931 static nat gc_running_threads;
933 #if defined(THREADED_RTS)
934 static Mutex gc_running_mutex;
941 ACQUIRE_LOCK(&gc_running_mutex);
942 n_running = ++gc_running_threads;
943 RELEASE_LOCK(&gc_running_mutex);
951 ACQUIRE_LOCK(&gc_running_mutex);
952 n_running = --gc_running_threads;
953 RELEASE_LOCK(&gc_running_mutex);
958 // gc_thread_work(): Scavenge until there's no work left to do and all
959 // the running threads are idle.
962 gc_thread_work (void)
966 debugTrace(DEBUG_gc, "GC thread %d working", gct->thread_index);
968 // gc_running_threads has already been incremented for us; either
969 // this is the main thread and we incremented it inside
970 // GarbageCollect(), or this is a worker thread and the main
971 // thread bumped gc_running_threads before waking us up.
975 // scavenge_loop() only exits when there's no work to do
978 debugTrace(DEBUG_gc, "GC thread %d idle (%d still running)",
979 gct->thread_index, r);
981 while (gc_running_threads != 0) {
986 // any_work() does not remove the work from the queue, it
987 // just checks for the presence of work. If we find any,
988 // then we increment gc_running_threads and go back to
989 // scavenge_loop() to perform any pending work.
992 // All threads are now stopped
993 debugTrace(DEBUG_gc, "GC thread %d finished.", gct->thread_index);
997 #if defined(THREADED_RTS)
999 gc_thread_mainloop (void)
1001 while (!gct->exit) {
1003 // Wait until we're told to wake up
1004 ACQUIRE_LOCK(&gct->wake_mutex);
1005 while (!gct->wakeup) {
1006 debugTrace(DEBUG_gc, "GC thread %d standing by...",
1008 waitCondition(&gct->wake_cond, &gct->wake_mutex);
1010 RELEASE_LOCK(&gct->wake_mutex);
1011 gct->wakeup = rtsFalse;
1012 if (gct->exit) break;
1019 #if defined(THREADED_RTS)
1021 gc_thread_entry (gc_thread *my_gct)
1024 debugTrace(DEBUG_gc, "GC thread %d starting...", gct->thread_index);
1025 gct->id = osThreadId();
1026 gc_thread_mainloop();
1031 start_gc_threads (void)
1033 #if defined(THREADED_RTS)
1036 static rtsBool done = rtsFalse;
1038 gc_running_threads = 0;
1039 initMutex(&gc_running_mutex);
1042 // Start from 1: the main thread is 0
1043 for (i = 1; i < RtsFlags.ParFlags.gcThreads; i++) {
1044 createOSThread(&id, (OSThreadProc*)&gc_thread_entry,
1053 wakeup_gc_threads (nat n_threads USED_IF_THREADS)
1055 #if defined(THREADED_RTS)
1057 for (i=1; i < n_threads; i++) {
1059 ACQUIRE_LOCK(&gc_threads[i].wake_mutex);
1060 gc_threads[i].wakeup = rtsTrue;
1061 signalCondition(&gc_threads[i].wake_cond);
1062 RELEASE_LOCK(&gc_threads[i].wake_mutex);
1067 /* ----------------------------------------------------------------------------
1068 Initialise a generation that is to be collected
1069 ------------------------------------------------------------------------- */
1072 init_collected_gen (nat g, nat n_threads)
1079 // Throw away the current mutable list. Invariant: the mutable
1080 // list always has at least one block; this means we can avoid a
1081 // check for NULL in recordMutable().
1083 freeChain(generations[g].mut_list);
1084 generations[g].mut_list = allocBlock();
1085 for (i = 0; i < n_capabilities; i++) {
1086 freeChain(capabilities[i].mut_lists[g]);
1087 capabilities[i].mut_lists[g] = allocBlock();
1091 for (s = 0; s < generations[g].n_steps; s++) {
1093 // generation 0, step 0 doesn't need to-space
1094 if (g == 0 && s == 0 && RtsFlags.GcFlags.generations > 1) {
1098 stp = &generations[g].steps[s];
1099 ASSERT(stp->gen_no == g);
1101 // deprecate the existing blocks
1102 stp->old_blocks = stp->blocks;
1103 stp->n_old_blocks = stp->n_blocks;
1107 // we don't have any to-be-scavenged blocks yet
1111 // initialise the large object queues.
1112 stp->scavenged_large_objects = NULL;
1113 stp->n_scavenged_large_blocks = 0;
1115 // mark the large objects as not evacuated yet
1116 for (bd = stp->large_objects; bd; bd = bd->link) {
1117 bd->flags &= ~BF_EVACUATED;
1120 // for a compacted step, we need to allocate the bitmap
1121 if (stp->is_compacted) {
1122 nat bitmap_size; // in bytes
1123 bdescr *bitmap_bdescr;
1126 bitmap_size = stp->n_old_blocks * BLOCK_SIZE / (sizeof(W_)*BITS_PER_BYTE);
1128 if (bitmap_size > 0) {
1129 bitmap_bdescr = allocGroup((lnat)BLOCK_ROUND_UP(bitmap_size)
1131 stp->bitmap = bitmap_bdescr;
1132 bitmap = bitmap_bdescr->start;
1134 debugTrace(DEBUG_gc, "bitmap_size: %d, bitmap: %p",
1135 bitmap_size, bitmap);
1137 // don't forget to fill it with zeros!
1138 memset(bitmap, 0, bitmap_size);
1140 // For each block in this step, point to its bitmap from the
1141 // block descriptor.
1142 for (bd=stp->old_blocks; bd != NULL; bd = bd->link) {
1143 bd->u.bitmap = bitmap;
1144 bitmap += BLOCK_SIZE_W / (sizeof(W_)*BITS_PER_BYTE);
1146 // Also at this point we set the BF_COMPACTED flag
1147 // for this block. The invariant is that
1148 // BF_COMPACTED is always unset, except during GC
1149 // when it is set on those blocks which will be
1151 bd->flags |= BF_COMPACTED;
1157 // For each GC thread, for each step, allocate a "todo" block to
1158 // store evacuated objects to be scavenged, and a block to store
1159 // evacuated objects that do not need to be scavenged.
1160 for (t = 0; t < n_threads; t++) {
1161 for (s = 0; s < generations[g].n_steps; s++) {
1163 // we don't copy objects into g0s0, unless -G0
1164 if (g==0 && s==0 && RtsFlags.GcFlags.generations > 1) continue;
1166 ws = &gc_threads[t].steps[g][s];
1171 ws->todo_large_objects = NULL;
1173 // allocate the first to-space block; extra blocks will be
1174 // chained on as necessary.
1176 ws->buffer_todo_bd = NULL;
1177 gc_alloc_todo_block(ws);
1179 ws->scavd_list = NULL;
1180 ws->n_scavd_blocks = 0;
1186 /* ----------------------------------------------------------------------------
1187 Initialise a generation that is *not* to be collected
1188 ------------------------------------------------------------------------- */
1191 init_uncollected_gen (nat g, nat threads)
1198 for (s = 0; s < generations[g].n_steps; s++) {
1199 stp = &generations[g].steps[s];
1200 stp->scavenged_large_objects = NULL;
1201 stp->n_scavenged_large_blocks = 0;
1204 for (t = 0; t < threads; t++) {
1205 for (s = 0; s < generations[g].n_steps; s++) {
1207 ws = &gc_threads[t].steps[g][s];
1210 ws->buffer_todo_bd = NULL;
1211 ws->todo_large_objects = NULL;
1213 ws->scavd_list = NULL;
1214 ws->n_scavd_blocks = 0;
1216 // If the block at the head of the list in this generation
1217 // is less than 3/4 full, then use it as a todo block.
1218 if (isPartiallyFull(stp->blocks))
1220 ws->todo_bd = stp->blocks;
1221 stp->blocks = stp->blocks->link;
1223 ws->todo_bd->link = NULL;
1225 // this block is also the scan block; we must scan
1226 // from the current end point.
1227 ws->scan_bd = ws->todo_bd;
1228 ws->scan = ws->scan_bd->free;
1230 // subtract the contents of this block from the stats,
1231 // because we'll count the whole block later.
1232 copied -= ws->scan_bd->free - ws->scan_bd->start;
1239 gc_alloc_todo_block(ws);
1244 // Move the private mutable lists from each capability onto the
1245 // main mutable list for the generation.
1246 for (i = 0; i < n_capabilities; i++) {
1247 for (bd = capabilities[i].mut_lists[g];
1248 bd->link != NULL; bd = bd->link) {
1251 bd->link = generations[g].mut_list;
1252 generations[g].mut_list = capabilities[i].mut_lists[g];
1253 capabilities[i].mut_lists[g] = allocBlock();
1257 /* -----------------------------------------------------------------------------
1258 Initialise a gc_thread before GC
1259 -------------------------------------------------------------------------- */
1262 init_gc_thread (gc_thread *t)
1265 t->failed_to_evac = rtsFalse;
1266 t->eager_promotion = rtsTrue;
1267 t->thunk_selector_depth = 0;
1270 /* -----------------------------------------------------------------------------
1271 Function we pass to GetRoots to evacuate roots.
1272 -------------------------------------------------------------------------- */
1275 mark_root(StgClosure **root)
1280 /* -----------------------------------------------------------------------------
1281 Initialising the static object & mutable lists
1282 -------------------------------------------------------------------------- */
1285 zero_static_object_list(StgClosure* first_static)
1289 const StgInfoTable *info;
1291 for (p = first_static; p != END_OF_STATIC_LIST; p = link) {
1293 link = *STATIC_LINK(info, p);
1294 *STATIC_LINK(info,p) = NULL;
1298 /* -----------------------------------------------------------------------------
1300 -------------------------------------------------------------------------- */
1307 for (c = (StgIndStatic *)revertible_caf_list; c != NULL;
1308 c = (StgIndStatic *)c->static_link)
1310 SET_INFO(c, c->saved_info);
1311 c->saved_info = NULL;
1312 // could, but not necessary: c->static_link = NULL;
1314 revertible_caf_list = NULL;
1318 markCAFs( evac_fn evac )
1322 for (c = (StgIndStatic *)caf_list; c != NULL;
1323 c = (StgIndStatic *)c->static_link)
1325 evac(&c->indirectee);
1327 for (c = (StgIndStatic *)revertible_caf_list; c != NULL;
1328 c = (StgIndStatic *)c->static_link)
1330 evac(&c->indirectee);
1334 /* ----------------------------------------------------------------------------
1335 Update the pointers from the task list
1337 These are treated as weak pointers because we want to allow a main
1338 thread to get a BlockedOnDeadMVar exception in the same way as any
1339 other thread. Note that the threads should all have been retained
1340 by GC by virtue of being on the all_threads list, we're just
1341 updating pointers here.
1342 ------------------------------------------------------------------------- */
1345 update_task_list (void)
1349 for (task = all_tasks; task != NULL; task = task->all_link) {
1350 if (!task->stopped && task->tso) {
1351 ASSERT(task->tso->bound == task);
1352 tso = (StgTSO *) isAlive((StgClosure *)task->tso);
1354 barf("task %p: main thread %d has been GC'd",
1367 /* ----------------------------------------------------------------------------
1368 Reset the sizes of the older generations when we do a major
1371 CURRENT STRATEGY: make all generations except zero the same size.
1372 We have to stay within the maximum heap size, and leave a certain
1373 percentage of the maximum heap size available to allocate into.
1374 ------------------------------------------------------------------------- */
1377 resize_generations (void)
1381 if (major_gc && RtsFlags.GcFlags.generations > 1) {
1382 nat live, size, min_alloc;
1383 nat max = RtsFlags.GcFlags.maxHeapSize;
1384 nat gens = RtsFlags.GcFlags.generations;
1386 // live in the oldest generations
1387 live = oldest_gen->steps[0].n_blocks +
1388 oldest_gen->steps[0].n_large_blocks;
1390 // default max size for all generations except zero
1391 size = stg_max(live * RtsFlags.GcFlags.oldGenFactor,
1392 RtsFlags.GcFlags.minOldGenSize);
1394 // minimum size for generation zero
1395 min_alloc = stg_max((RtsFlags.GcFlags.pcFreeHeap * max) / 200,
1396 RtsFlags.GcFlags.minAllocAreaSize);
1398 // Auto-enable compaction when the residency reaches a
1399 // certain percentage of the maximum heap size (default: 30%).
1400 if (RtsFlags.GcFlags.generations > 1 &&
1401 (RtsFlags.GcFlags.compact ||
1403 oldest_gen->steps[0].n_blocks >
1404 (RtsFlags.GcFlags.compactThreshold * max) / 100))) {
1405 oldest_gen->steps[0].is_compacted = 1;
1406 // debugBelch("compaction: on\n", live);
1408 oldest_gen->steps[0].is_compacted = 0;
1409 // debugBelch("compaction: off\n", live);
1412 // if we're going to go over the maximum heap size, reduce the
1413 // size of the generations accordingly. The calculation is
1414 // different if compaction is turned on, because we don't need
1415 // to double the space required to collect the old generation.
1418 // this test is necessary to ensure that the calculations
1419 // below don't have any negative results - we're working
1420 // with unsigned values here.
1421 if (max < min_alloc) {
1425 if (oldest_gen->steps[0].is_compacted) {
1426 if ( (size + (size - 1) * (gens - 2) * 2) + min_alloc > max ) {
1427 size = (max - min_alloc) / ((gens - 1) * 2 - 1);
1430 if ( (size * (gens - 1) * 2) + min_alloc > max ) {
1431 size = (max - min_alloc) / ((gens - 1) * 2);
1441 debugBelch("live: %d, min_alloc: %d, size : %d, max = %d\n", live,
1442 min_alloc, size, max);
1445 for (g = 0; g < gens; g++) {
1446 generations[g].max_blocks = size;
1451 /* -----------------------------------------------------------------------------
1452 Calculate the new size of the nursery, and resize it.
1453 -------------------------------------------------------------------------- */
1456 resize_nursery (void)
1458 if (RtsFlags.GcFlags.generations == 1)
1459 { // Two-space collector:
1462 /* set up a new nursery. Allocate a nursery size based on a
1463 * function of the amount of live data (by default a factor of 2)
1464 * Use the blocks from the old nursery if possible, freeing up any
1467 * If we get near the maximum heap size, then adjust our nursery
1468 * size accordingly. If the nursery is the same size as the live
1469 * data (L), then we need 3L bytes. We can reduce the size of the
1470 * nursery to bring the required memory down near 2L bytes.
1472 * A normal 2-space collector would need 4L bytes to give the same
1473 * performance we get from 3L bytes, reducing to the same
1474 * performance at 2L bytes.
1476 blocks = g0s0->n_old_blocks;
1478 if ( RtsFlags.GcFlags.maxHeapSize != 0 &&
1479 blocks * RtsFlags.GcFlags.oldGenFactor * 2 >
1480 RtsFlags.GcFlags.maxHeapSize )
1482 long adjusted_blocks; // signed on purpose
1485 adjusted_blocks = (RtsFlags.GcFlags.maxHeapSize - 2 * blocks);
1487 debugTrace(DEBUG_gc, "near maximum heap size of 0x%x blocks, blocks = %d, adjusted to %ld",
1488 RtsFlags.GcFlags.maxHeapSize, blocks, adjusted_blocks);
1490 pc_free = adjusted_blocks * 100 / RtsFlags.GcFlags.maxHeapSize;
1491 if (pc_free < RtsFlags.GcFlags.pcFreeHeap) /* might even * be < 0 */
1495 blocks = adjusted_blocks;
1499 blocks *= RtsFlags.GcFlags.oldGenFactor;
1500 if (blocks < RtsFlags.GcFlags.minAllocAreaSize)
1502 blocks = RtsFlags.GcFlags.minAllocAreaSize;
1505 resizeNurseries(blocks);
1507 else // Generational collector
1510 * If the user has given us a suggested heap size, adjust our
1511 * allocation area to make best use of the memory available.
1513 if (RtsFlags.GcFlags.heapSizeSuggestion)
1516 nat needed = calcNeeded(); // approx blocks needed at next GC
1518 /* Guess how much will be live in generation 0 step 0 next time.
1519 * A good approximation is obtained by finding the
1520 * percentage of g0s0 that was live at the last minor GC.
1522 * We have an accurate figure for the amount of copied data in
1523 * 'copied', but we must convert this to a number of blocks, with
1524 * a small adjustment for estimated slop at the end of a block
1529 g0s0_pcnt_kept = ((copied / (BLOCK_SIZE_W - 10)) * 100)
1530 / countNurseryBlocks();
1533 /* Estimate a size for the allocation area based on the
1534 * information available. We might end up going slightly under
1535 * or over the suggested heap size, but we should be pretty
1538 * Formula: suggested - needed
1539 * ----------------------------
1540 * 1 + g0s0_pcnt_kept/100
1542 * where 'needed' is the amount of memory needed at the next
1543 * collection for collecting all steps except g0s0.
1546 (((long)RtsFlags.GcFlags.heapSizeSuggestion - (long)needed) * 100) /
1547 (100 + (long)g0s0_pcnt_kept);
1549 if (blocks < (long)RtsFlags.GcFlags.minAllocAreaSize) {
1550 blocks = RtsFlags.GcFlags.minAllocAreaSize;
1553 resizeNurseries((nat)blocks);
1557 // we might have added extra large blocks to the nursery, so
1558 // resize back to minAllocAreaSize again.
1559 resizeNurseriesFixed(RtsFlags.GcFlags.minAllocAreaSize);
1564 /* -----------------------------------------------------------------------------
1565 Sanity code for CAF garbage collection.
1567 With DEBUG turned on, we manage a CAF list in addition to the SRT
1568 mechanism. After GC, we run down the CAF list and blackhole any
1569 CAFs which have been garbage collected. This means we get an error
1570 whenever the program tries to enter a garbage collected CAF.
1572 Any garbage collected CAFs are taken off the CAF list at the same
1574 -------------------------------------------------------------------------- */
1576 #if 0 && defined(DEBUG)
1583 const StgInfoTable *info;
1594 ASSERT(info->type == IND_STATIC);
1596 if (STATIC_LINK(info,p) == NULL) {
1597 debugTrace(DEBUG_gccafs, "CAF gc'd at 0x%04lx", (long)p);
1599 SET_INFO(p,&stg_BLACKHOLE_info);
1600 p = STATIC_LINK2(info,p);
1604 pp = &STATIC_LINK2(info,p);
1611 debugTrace(DEBUG_gccafs, "%d CAFs live", i);