748dc0d6de2ffac6806e406013c0d28b6de308ab
[ghc.git] / rts / sm / GC.c
1 /* -----------------------------------------------------------------------------
2 *
3 * (c) The GHC Team 1998-2008
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://ghc.haskell.org/trac/ghc/wiki/Commentary/Rts/Storage/GC
11 *
12 * ---------------------------------------------------------------------------*/
13
14 #include "PosixSource.h"
15 #include "Rts.h"
16 #include "HsFFI.h"
17
18 #include "GC.h"
19 #include "GCThread.h"
20 #include "GCTDecl.h" // NB. before RtsSignals.h which
21 // clobbers REG_R1 on arm/Linux
22 #include "Compact.h"
23 #include "Evac.h"
24 #include "Scav.h"
25 #include "GCUtils.h"
26 #include "MarkStack.h"
27 #include "MarkWeak.h"
28 #include "Sparks.h"
29 #include "Sweep.h"
30
31 #include "Storage.h"
32 #include "RtsUtils.h"
33 #include "Apply.h"
34 #include "Updates.h"
35 #include "Stats.h"
36 #include "Schedule.h"
37 #include "Sanity.h"
38 #include "BlockAlloc.h"
39 #include "ProfHeap.h"
40 #include "Weak.h"
41 #include "Prelude.h"
42 #include "RtsSignals.h"
43 #include "STM.h"
44 #include "Trace.h"
45 #include "RetainerProfile.h"
46 #include "LdvProfile.h"
47 #include "RaiseAsync.h"
48 #include "Papi.h"
49 #include "Stable.h"
50 #include "CheckUnload.h"
51
52 #include <string.h> // for memset()
53 #include <unistd.h>
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
94 /* N is the oldest generation being collected, where the generations
95 * are numbered starting at 0. A major GC (indicated by the major_gc
96 * flag) is when we're collecting all generations. We only attempt to
97 * deal with static objects and GC CAFs when doing a major GC.
98 */
99 nat N;
100 rtsBool major_gc;
101
102 /* Data used for allocation area sizing.
103 */
104 static W_ g0_pcnt_kept = 30; // percentage of g0 live at last minor GC
105
106 /* Mut-list stats */
107 #ifdef DEBUG
108 nat mutlist_MUTVARS,
109 mutlist_MUTARRS,
110 mutlist_MVARS,
111 mutlist_TVAR,
112 mutlist_TVAR_WATCH_QUEUE,
113 mutlist_TREC_CHUNK,
114 mutlist_TREC_HEADER,
115 mutlist_ATOMIC_INVARIANT,
116 mutlist_INVARIANT_CHECK_QUEUE,
117 mutlist_OTHERS;
118 #endif
119
120 /* Thread-local data for each GC thread
121 */
122 gc_thread **gc_threads = NULL;
123
124 #if !defined(THREADED_RTS)
125 StgWord8 the_gc_thread[sizeof(gc_thread) + 64 * sizeof(gen_workspace)];
126 #endif
127
128 // Number of threads running in *this* GC. Affects how many
129 // step->todos[] lists we have to look in to find work.
130 nat n_gc_threads;
131
132 // For stats:
133 long copied; // *words* copied & scavenged during this GC
134
135 rtsBool work_stealing;
136
137 DECLARE_GCT
138
139 /* -----------------------------------------------------------------------------
140 Static function declarations
141 -------------------------------------------------------------------------- */
142
143 static void mark_root (void *user, StgClosure **root);
144 static void zero_static_object_list (StgClosure* first_static);
145 static void prepare_collected_gen (generation *gen);
146 static void prepare_uncollected_gen (generation *gen);
147 static void init_gc_thread (gc_thread *t);
148 static void resize_generations (void);
149 static void resize_nursery (void);
150 static void start_gc_threads (void);
151 static void scavenge_until_all_done (void);
152 static StgWord inc_running (void);
153 static StgWord dec_running (void);
154 static void wakeup_gc_threads (nat me);
155 static void shutdown_gc_threads (nat me);
156 static void collect_gct_blocks (void);
157 static void collect_pinned_object_blocks (void);
158
159 #if defined(DEBUG)
160 static void gcCAFs (void);
161 #endif
162
163 /* -----------------------------------------------------------------------------
164 The mark stack.
165 -------------------------------------------------------------------------- */
166
167 bdescr *mark_stack_top_bd; // topmost block in the mark stack
168 bdescr *mark_stack_bd; // current block in the mark stack
169 StgPtr mark_sp; // pointer to the next unallocated mark stack entry
170
171 /* -----------------------------------------------------------------------------
172 GarbageCollect: the main entry point to the garbage collector.
173
174 The collect_gen parameter is gotten by calling calcNeeded().
175
176 Locks held: all capabilities are held throughout GarbageCollect().
177 -------------------------------------------------------------------------- */
178
179 void
180 GarbageCollect (nat collect_gen,
181 rtsBool do_heap_census,
182 nat gc_type USED_IF_THREADS,
183 Capability *cap)
184 {
185 bdescr *bd;
186 generation *gen;
187 StgWord live_blocks, live_words, par_max_copied, par_tot_copied;
188 #if defined(THREADED_RTS)
189 gc_thread *saved_gct;
190 #endif
191 nat g, n;
192
193 // necessary if we stole a callee-saves register for gct:
194 #if defined(THREADED_RTS)
195 saved_gct = gct;
196 #endif
197
198 #ifdef PROFILING
199 CostCentreStack *save_CCS[n_capabilities];
200 #endif
201
202 ACQUIRE_SM_LOCK;
203
204 #if defined(RTS_USER_SIGNALS)
205 if (RtsFlags.MiscFlags.install_signal_handlers) {
206 // block signals
207 blockUserSignals();
208 }
209 #endif
210
211 ASSERT(sizeof(gen_workspace) == 16 * sizeof(StgWord));
212 // otherwise adjust the padding in gen_workspace.
213
214 // this is the main thread
215 SET_GCT(gc_threads[cap->no]);
216
217 // tell the stats department that we've started a GC
218 stat_startGC(cap, gct);
219
220 // lock the StablePtr table
221 stableLock();
222
223 #ifdef DEBUG
224 mutlist_MUTVARS = 0;
225 mutlist_MUTARRS = 0;
226 mutlist_MVARS = 0;
227 mutlist_TVAR = 0;
228 mutlist_TVAR_WATCH_QUEUE = 0;
229 mutlist_TREC_CHUNK = 0;
230 mutlist_TREC_HEADER = 0;
231 mutlist_ATOMIC_INVARIANT = 0;
232 mutlist_INVARIANT_CHECK_QUEUE = 0;
233 mutlist_OTHERS = 0;
234 #endif
235
236 // attribute any costs to CCS_GC
237 #ifdef PROFILING
238 for (n = 0; n < n_capabilities; n++) {
239 save_CCS[n] = capabilities[n]->r.rCCCS;
240 capabilities[n]->r.rCCCS = CCS_GC;
241 }
242 #endif
243
244 /* Figure out which generation to collect
245 */
246 N = collect_gen;
247 major_gc = (N == RtsFlags.GcFlags.generations-1);
248
249 #if defined(THREADED_RTS)
250 work_stealing = RtsFlags.ParFlags.parGcLoadBalancingEnabled &&
251 N >= RtsFlags.ParFlags.parGcLoadBalancingGen;
252 // It's not always a good idea to do load balancing in parallel
253 // GC. In particular, for a parallel program we don't want to
254 // lose locality by moving cached data into another CPU's cache
255 // (this effect can be quite significant).
256 //
257 // We could have a more complex way to deterimine whether to do
258 // work stealing or not, e.g. it might be a good idea to do it
259 // if the heap is big. For now, we just turn it on or off with
260 // a flag.
261 #endif
262
263 /* Start threads, so they can be spinning up while we finish initialisation.
264 */
265 start_gc_threads();
266
267 #if defined(THREADED_RTS)
268 /* How many threads will be participating in this GC?
269 * We don't try to parallelise minor GCs (unless the user asks for
270 * it with +RTS -gn0), or mark/compact/sweep GC.
271 */
272 if (gc_type == SYNC_GC_PAR) {
273 n_gc_threads = n_capabilities;
274 } else {
275 n_gc_threads = 1;
276 }
277 #else
278 n_gc_threads = 1;
279 #endif
280
281 debugTrace(DEBUG_gc, "GC (gen %d, using %d thread(s))",
282 N, n_gc_threads);
283
284 #ifdef DEBUG
285 // check for memory leaks if DEBUG is on
286 memInventory(DEBUG_gc);
287 #endif
288
289 // do this *before* we start scavenging
290 collectFreshWeakPtrs();
291
292 // check sanity *before* GC
293 IF_DEBUG(sanity, checkSanity(rtsFalse /* before GC */, major_gc));
294
295 // gather blocks allocated using allocatePinned() from each capability
296 // and put them on the g0->large_object list.
297 collect_pinned_object_blocks();
298
299 // Initialise all the generations/steps that we're collecting.
300 for (g = 0; g <= N; g++) {
301 prepare_collected_gen(&generations[g]);
302 }
303 // Initialise all the generations/steps that we're *not* collecting.
304 for (g = N+1; g < RtsFlags.GcFlags.generations; g++) {
305 prepare_uncollected_gen(&generations[g]);
306 }
307
308 // Prepare this gc_thread
309 init_gc_thread(gct);
310
311 /* Allocate a mark stack if we're doing a major collection.
312 */
313 if (major_gc && oldest_gen->mark) {
314 mark_stack_bd = allocBlock();
315 mark_stack_top_bd = mark_stack_bd;
316 mark_stack_bd->link = NULL;
317 mark_stack_bd->u.back = NULL;
318 mark_sp = mark_stack_bd->start;
319 } else {
320 mark_stack_bd = NULL;
321 mark_stack_top_bd = NULL;
322 mark_sp = NULL;
323 }
324
325 /* -----------------------------------------------------------------------
326 * follow all the roots that we know about:
327 */
328
329 // the main thread is running: this prevents any other threads from
330 // exiting prematurely, so we can start them now.
331 // NB. do this after the mutable lists have been saved above, otherwise
332 // the other GC threads will be writing into the old mutable lists.
333 inc_running();
334 wakeup_gc_threads(gct->thread_index);
335
336 traceEventGcWork(gct->cap);
337
338 // scavenge the capability-private mutable lists. This isn't part
339 // of markSomeCapabilities() because markSomeCapabilities() can only
340 // call back into the GC via mark_root() (due to the gct register
341 // variable).
342 if (n_gc_threads == 1) {
343 for (n = 0; n < n_capabilities; n++) {
344 #if defined(THREADED_RTS)
345 scavenge_capability_mut_Lists1(capabilities[n]);
346 #else
347 scavenge_capability_mut_lists(capabilities[n]);
348 #endif
349 }
350 } else {
351 scavenge_capability_mut_lists(gct->cap);
352 for (n = 0; n < n_capabilities; n++) {
353 if (gc_threads[n]->idle) {
354 markCapability(mark_root, gct, capabilities[n],
355 rtsTrue/*don't mark sparks*/);
356 scavenge_capability_mut_lists(capabilities[n]);
357 }
358 }
359 }
360
361 // follow roots from the CAF list (used by GHCi)
362 gct->evac_gen_no = 0;
363 markCAFs(mark_root, gct);
364
365 // follow all the roots that the application knows about.
366 gct->evac_gen_no = 0;
367 if (n_gc_threads == 1) {
368 for (n = 0; n < n_capabilities; n++) {
369 markCapability(mark_root, gct, capabilities[n],
370 rtsTrue/*don't mark sparks*/);
371 }
372 } else {
373 markCapability(mark_root, gct, cap, rtsTrue/*don't mark sparks*/);
374 }
375
376 markScheduler(mark_root, gct);
377
378 #if defined(RTS_USER_SIGNALS)
379 // mark the signal handlers (signals should be already blocked)
380 markSignalHandlers(mark_root, gct);
381 #endif
382
383 // Mark the weak pointer list, and prepare to detect dead weak pointers.
384 markWeakPtrList();
385 initWeakForGC();
386
387 // Mark the stable pointer table.
388 markStableTables(mark_root, gct);
389
390 /* -------------------------------------------------------------------------
391 * Repeatedly scavenge all the areas we know about until there's no
392 * more scavenging to be done.
393 */
394 for (;;)
395 {
396 scavenge_until_all_done();
397 // The other threads are now stopped. We might recurse back to
398 // here, but from now on this is the only thread.
399
400 // must be last... invariant is that everything is fully
401 // scavenged at this point.
402 if (traverseWeakPtrList()) { // returns rtsTrue if evaced something
403 inc_running();
404 continue;
405 }
406
407 // If we get to here, there's really nothing left to do.
408 break;
409 }
410
411 if (!DEBUG_IS_ON && n_gc_threads != 1) {
412 clearNursery(cap);
413 }
414
415 shutdown_gc_threads(gct->thread_index);
416
417 // Now see which stable names are still alive.
418 gcStableTables();
419
420 #ifdef THREADED_RTS
421 if (n_gc_threads == 1) {
422 for (n = 0; n < n_capabilities; n++) {
423 pruneSparkQueue(capabilities[n]);
424 }
425 } else {
426 for (n = 0; n < n_capabilities; n++) {
427 if (n == cap->no || gc_threads[n]->idle) {
428 pruneSparkQueue(capabilities[n]);
429 }
430 }
431 }
432 #endif
433
434 #ifdef PROFILING
435 // We call processHeapClosureForDead() on every closure destroyed during
436 // the current garbage collection, so we invoke LdvCensusForDead().
437 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV
438 || RtsFlags.ProfFlags.bioSelector != NULL) {
439 RELEASE_SM_LOCK; // LdvCensusForDead may need to take the lock
440 LdvCensusForDead(N);
441 ACQUIRE_SM_LOCK;
442 }
443 #endif
444
445 // NO MORE EVACUATION AFTER THIS POINT!
446
447 // Finally: compact or sweep the oldest generation.
448 if (major_gc && oldest_gen->mark) {
449 if (oldest_gen->compact)
450 compact(gct->scavenged_static_objects);
451 else
452 sweep(oldest_gen);
453 }
454
455 copied = 0;
456 par_max_copied = 0;
457 par_tot_copied = 0;
458 {
459 nat i;
460 for (i=0; i < n_gc_threads; i++) {
461 if (n_gc_threads > 1) {
462 debugTrace(DEBUG_gc,"thread %d:", i);
463 debugTrace(DEBUG_gc," copied %ld", gc_threads[i]->copied * sizeof(W_));
464 debugTrace(DEBUG_gc," scanned %ld", gc_threads[i]->scanned * sizeof(W_));
465 debugTrace(DEBUG_gc," any_work %ld", gc_threads[i]->any_work);
466 debugTrace(DEBUG_gc," no_work %ld", gc_threads[i]->no_work);
467 debugTrace(DEBUG_gc," scav_find_work %ld", gc_threads[i]->scav_find_work);
468 }
469 copied += gc_threads[i]->copied;
470 par_max_copied = stg_max(gc_threads[i]->copied, par_max_copied);
471 }
472 par_tot_copied = copied;
473 if (n_gc_threads == 1) {
474 par_max_copied = 0;
475 par_tot_copied = 0;
476 }
477 }
478
479 // Run through all the generations/steps and tidy up.
480 // We're going to:
481 // - count the amount of "live" data (live_words, live_blocks)
482 // - count the amount of "copied" data in this GC (copied)
483 // - free from-space
484 // - make to-space the new from-space (set BF_EVACUATED on all blocks)
485 //
486 live_words = 0;
487 live_blocks = 0;
488
489 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
490
491 if (g == N) {
492 generations[g].collections++; // for stats
493 if (n_gc_threads > 1) generations[g].par_collections++;
494 }
495
496 // Count the mutable list as bytes "copied" for the purposes of
497 // stats. Every mutable list is copied during every GC.
498 if (g > 0) {
499 W_ mut_list_size = 0;
500 for (n = 0; n < n_capabilities; n++) {
501 mut_list_size += countOccupied(capabilities[n]->mut_lists[g]);
502 }
503 copied += mut_list_size;
504
505 debugTrace(DEBUG_gc,
506 "mut_list_size: %lu (%d vars, %d arrays, %d MVARs, %d TVARs, %d TVAR_WATCH_QUEUEs, %d TREC_CHUNKs, %d TREC_HEADERs, %d ATOMIC_INVARIANTs, %d INVARIANT_CHECK_QUEUEs, %d others)",
507 (unsigned long)(mut_list_size * sizeof(W_)),
508 mutlist_MUTVARS, mutlist_MUTARRS, mutlist_MVARS,
509 mutlist_TVAR, mutlist_TVAR_WATCH_QUEUE,
510 mutlist_TREC_CHUNK, mutlist_TREC_HEADER,
511 mutlist_ATOMIC_INVARIANT,
512 mutlist_INVARIANT_CHECK_QUEUE,
513 mutlist_OTHERS);
514 }
515
516 bdescr *next, *prev;
517 gen = &generations[g];
518
519 // for generations we collected...
520 if (g <= N) {
521
522 /* free old memory and shift to-space into from-space for all
523 * the collected steps (except the allocation area). These
524 * freed blocks will probaby be quickly recycled.
525 */
526 if (gen->mark)
527 {
528 // tack the new blocks on the end of the existing blocks
529 if (gen->old_blocks != NULL) {
530
531 prev = NULL;
532 for (bd = gen->old_blocks; bd != NULL; bd = next) {
533
534 next = bd->link;
535
536 if (!(bd->flags & BF_MARKED))
537 {
538 if (prev == NULL) {
539 gen->old_blocks = next;
540 } else {
541 prev->link = next;
542 }
543 freeGroup(bd);
544 gen->n_old_blocks--;
545 }
546 else
547 {
548 gen->n_words += bd->free - bd->start;
549
550 // NB. this step might not be compacted next
551 // time, so reset the BF_MARKED flags.
552 // They are set before GC if we're going to
553 // compact. (search for BF_MARKED above).
554 bd->flags &= ~BF_MARKED;
555
556 // between GCs, all blocks in the heap except
557 // for the nursery have the BF_EVACUATED flag set.
558 bd->flags |= BF_EVACUATED;
559
560 prev = bd;
561 }
562 }
563
564 if (prev != NULL) {
565 prev->link = gen->blocks;
566 gen->blocks = gen->old_blocks;
567 }
568 }
569 // add the new blocks to the block tally
570 gen->n_blocks += gen->n_old_blocks;
571 ASSERT(countBlocks(gen->blocks) == gen->n_blocks);
572 ASSERT(countOccupied(gen->blocks) == gen->n_words);
573 }
574 else // not copacted
575 {
576 freeChain(gen->old_blocks);
577 }
578
579 gen->old_blocks = NULL;
580 gen->n_old_blocks = 0;
581
582 /* LARGE OBJECTS. The current live large objects are chained on
583 * scavenged_large, having been moved during garbage
584 * collection from large_objects. Any objects left on the
585 * large_objects list are therefore dead, so we free them here.
586 */
587 freeChain(gen->large_objects);
588 gen->large_objects = gen->scavenged_large_objects;
589 gen->n_large_blocks = gen->n_scavenged_large_blocks;
590 gen->n_large_words = countOccupied(gen->large_objects);
591 gen->n_new_large_words = 0;
592 }
593 else // for generations > N
594 {
595 /* For older generations, we need to append the
596 * scavenged_large_object list (i.e. large objects that have been
597 * promoted during this GC) to the large_object list for that step.
598 */
599 for (bd = gen->scavenged_large_objects; bd; bd = next) {
600 next = bd->link;
601 dbl_link_onto(bd, &gen->large_objects);
602 gen->n_large_words += bd->free - bd->start;
603 }
604
605 // add the new blocks we promoted during this GC
606 gen->n_large_blocks += gen->n_scavenged_large_blocks;
607 }
608
609 ASSERT(countBlocks(gen->large_objects) == gen->n_large_blocks);
610 ASSERT(countOccupied(gen->large_objects) == gen->n_large_words);
611
612 gen->scavenged_large_objects = NULL;
613 gen->n_scavenged_large_blocks = 0;
614
615 // Count "live" data
616 live_words += genLiveWords(gen);
617 live_blocks += genLiveBlocks(gen);
618
619 // add in the partial blocks in the gen_workspaces, but ignore gen 0
620 // if this is a local GC (we can't count another capability's part_list)
621 {
622 nat i;
623 for (i = 0; i < n_capabilities; i++) {
624 live_words += gcThreadLiveWords(i, gen->no);
625 live_blocks += gcThreadLiveBlocks(i, gen->no);
626 }
627 }
628 } // for all generations
629
630 // update the max size of older generations after a major GC
631 resize_generations();
632
633 // Free the mark stack.
634 if (mark_stack_top_bd != NULL) {
635 debugTrace(DEBUG_gc, "mark stack: %d blocks",
636 countBlocks(mark_stack_top_bd));
637 freeChain(mark_stack_top_bd);
638 }
639
640 // Free any bitmaps.
641 for (g = 0; g <= N; g++) {
642 gen = &generations[g];
643 if (gen->bitmap != NULL) {
644 freeGroup(gen->bitmap);
645 gen->bitmap = NULL;
646 }
647 }
648
649 // Reset the nursery: make the blocks empty
650 if (DEBUG_IS_ON || n_gc_threads == 1) {
651 for (n = 0; n < n_capabilities; n++) {
652 clearNursery(capabilities[n]);
653 }
654 } else {
655 // When doing parallel GC, clearNursery() is called by the
656 // worker threads
657 for (n = 0; n < n_capabilities; n++) {
658 if (gc_threads[n]->idle) {
659 clearNursery(capabilities[n]);
660 }
661 }
662 }
663
664 resize_nursery();
665
666 resetNurseries();
667
668 // mark the garbage collected CAFs as dead
669 #if defined(DEBUG)
670 if (major_gc) { gcCAFs(); }
671 #endif
672
673 // Update the stable pointer hash table.
674 updateStableTables(major_gc);
675
676 // unlock the StablePtr table. Must be before scheduleFinalizers(),
677 // because a finalizer may call hs_free_fun_ptr() or
678 // hs_free_stable_ptr(), both of which access the StablePtr table.
679 stableUnlock();
680
681 // Must be after stableUnlock(), because it might free stable ptrs.
682 if (major_gc) {
683 checkUnload (gct->scavenged_static_objects);
684 }
685
686 #ifdef PROFILING
687 // resetStaticObjectForRetainerProfiling() must be called before
688 // zeroing below.
689
690 // ToDo: fix the gct->scavenged_static_objects below
691 resetStaticObjectForRetainerProfiling(gct->scavenged_static_objects);
692 #endif
693
694 // zero the scavenged static object list
695 if (major_gc) {
696 nat i;
697 if (n_gc_threads == 1) {
698 zero_static_object_list(gct->scavenged_static_objects);
699 } else {
700 for (i = 0; i < n_gc_threads; i++) {
701 if (!gc_threads[i]->idle) {
702 zero_static_object_list(gc_threads[i]->scavenged_static_objects);
703 }
704 }
705 }
706 }
707
708 // Start any pending finalizers. Must be after
709 // updateStableTables() and stableUnlock() (see #4221).
710 RELEASE_SM_LOCK;
711 scheduleFinalizers(cap, dead_weak_ptr_list);
712 ACQUIRE_SM_LOCK;
713
714 // check sanity after GC
715 // before resurrectThreads(), because that might overwrite some
716 // closures, which will cause problems with THREADED where we don't
717 // fill slop.
718 IF_DEBUG(sanity, checkSanity(rtsTrue /* after GC */, major_gc));
719
720 // If a heap census is due, we need to do it before
721 // resurrectThreads(), for the same reason as checkSanity above:
722 // resurrectThreads() will overwrite some closures and leave slop
723 // behind.
724 if (do_heap_census) {
725 debugTrace(DEBUG_sched, "performing heap census");
726 RELEASE_SM_LOCK;
727 heapCensus(gct->gc_start_cpu);
728 ACQUIRE_SM_LOCK;
729 }
730
731 // send exceptions to any threads which were about to die
732 RELEASE_SM_LOCK;
733 resurrectThreads(resurrected_threads);
734 ACQUIRE_SM_LOCK;
735
736 if (major_gc) {
737 W_ need, got;
738 need = BLOCKS_TO_MBLOCKS(n_alloc_blocks);
739 got = mblocks_allocated;
740 /* If the amount of data remains constant, next major GC we'll
741 require (F+1)*need. We leave (F+2)*need in order to reduce
742 repeated deallocation and reallocation. */
743 need = (RtsFlags.GcFlags.oldGenFactor + 2) * need;
744 if (got > need) {
745 returnMemoryToOS(got - need);
746 }
747 }
748
749 // extra GC trace info
750 IF_DEBUG(gc, statDescribeGens());
751
752 #ifdef DEBUG
753 // symbol-table based profiling
754 /* heapCensus(to_blocks); */ /* ToDo */
755 #endif
756
757 // restore enclosing cost centre
758 #ifdef PROFILING
759 for (n = 0; n < n_capabilities; n++) {
760 capabilities[n]->r.rCCCS = save_CCS[n];
761 }
762 #endif
763
764 #ifdef DEBUG
765 // check for memory leaks if DEBUG is on
766 memInventory(DEBUG_gc);
767 #endif
768
769 // ok, GC over: tell the stats department what happened.
770 stat_endGC(cap, gct, live_words, copied,
771 live_blocks * BLOCK_SIZE_W - live_words /* slop */,
772 N, n_gc_threads, par_max_copied, par_tot_copied);
773
774 #if defined(RTS_USER_SIGNALS)
775 if (RtsFlags.MiscFlags.install_signal_handlers) {
776 // unblock signals again
777 unblockUserSignals();
778 }
779 #endif
780
781 RELEASE_SM_LOCK;
782
783 SET_GCT(saved_gct);
784 }
785
786 /* -----------------------------------------------------------------------------
787 Initialise the gc_thread structures.
788 -------------------------------------------------------------------------- */
789
790 #define GC_THREAD_INACTIVE 0
791 #define GC_THREAD_STANDING_BY 1
792 #define GC_THREAD_RUNNING 2
793 #define GC_THREAD_WAITING_TO_CONTINUE 3
794
795 static void
796 new_gc_thread (nat n, gc_thread *t)
797 {
798 nat g;
799 gen_workspace *ws;
800
801 t->cap = capabilities[n];
802
803 #ifdef THREADED_RTS
804 t->id = 0;
805 initSpinLock(&t->gc_spin);
806 initSpinLock(&t->mut_spin);
807 ACQUIRE_SPIN_LOCK(&t->gc_spin);
808 ACQUIRE_SPIN_LOCK(&t->mut_spin);
809 t->wakeup = GC_THREAD_INACTIVE; // starts true, so we can wait for the
810 // thread to start up, see wakeup_gc_threads
811 #endif
812
813 t->thread_index = n;
814 t->idle = rtsFalse;
815 t->free_blocks = NULL;
816 t->gc_count = 0;
817
818 init_gc_thread(t);
819
820 #ifdef USE_PAPI
821 t->papi_events = -1;
822 #endif
823
824 for (g = 0; g < RtsFlags.GcFlags.generations; g++)
825 {
826 ws = &t->gens[g];
827 ws->gen = &generations[g];
828 ASSERT(g == ws->gen->no);
829 ws->my_gct = t;
830
831 // We want to call
832 // alloc_todo_block(ws,0);
833 // but can't, because it uses gct which isn't set up at this point.
834 // Hence, allocate a block for todo_bd manually:
835 {
836 bdescr *bd = allocBlock(); // no lock, locks aren't initialised yet
837 initBdescr(bd, ws->gen, ws->gen->to);
838 bd->flags = BF_EVACUATED;
839 bd->u.scan = bd->free = bd->start;
840
841 ws->todo_bd = bd;
842 ws->todo_free = bd->free;
843 ws->todo_lim = bd->start + BLOCK_SIZE_W;
844 }
845
846 ws->todo_q = newWSDeque(128);
847 ws->todo_overflow = NULL;
848 ws->n_todo_overflow = 0;
849 ws->todo_large_objects = NULL;
850
851 ws->part_list = NULL;
852 ws->n_part_blocks = 0;
853
854 ws->scavd_list = NULL;
855 ws->n_scavd_blocks = 0;
856 }
857 }
858
859
860 void
861 initGcThreads (nat from USED_IF_THREADS, nat to USED_IF_THREADS)
862 {
863 #if defined(THREADED_RTS)
864 nat i;
865
866 if (from > 0) {
867 gc_threads = stgReallocBytes (gc_threads, to * sizeof(gc_thread*),
868 "initGcThreads");
869 } else {
870 gc_threads = stgMallocBytes (to * sizeof(gc_thread*),
871 "initGcThreads");
872 }
873
874 for (i = from; i < to; i++) {
875 gc_threads[i] =
876 stgMallocBytes(sizeof(gc_thread) +
877 RtsFlags.GcFlags.generations * sizeof(gen_workspace),
878 "alloc_gc_threads");
879
880 new_gc_thread(i, gc_threads[i]);
881 }
882 #else
883 ASSERT(from == 0 && to == 1);
884 gc_threads = stgMallocBytes (sizeof(gc_thread*),"alloc_gc_threads");
885 gc_threads[0] = gct;
886 new_gc_thread(0,gc_threads[0]);
887 #endif
888 }
889
890 void
891 freeGcThreads (void)
892 {
893 nat g;
894 if (gc_threads != NULL) {
895 #if defined(THREADED_RTS)
896 nat i;
897 for (i = 0; i < n_capabilities; i++) {
898 for (g = 0; g < RtsFlags.GcFlags.generations; g++)
899 {
900 freeWSDeque(gc_threads[i]->gens[g].todo_q);
901 }
902 stgFree (gc_threads[i]);
903 }
904 stgFree (gc_threads);
905 #else
906 for (g = 0; g < RtsFlags.GcFlags.generations; g++)
907 {
908 freeWSDeque(gc_threads[0]->gens[g].todo_q);
909 }
910 stgFree (gc_threads);
911 #endif
912 gc_threads = NULL;
913 }
914 }
915
916 /* ----------------------------------------------------------------------------
917 Start GC threads
918 ------------------------------------------------------------------------- */
919
920 static volatile StgWord gc_running_threads;
921
922 static StgWord
923 inc_running (void)
924 {
925 StgWord new;
926 new = atomic_inc(&gc_running_threads, 1);
927 ASSERT(new <= n_gc_threads);
928 return new;
929 }
930
931 static StgWord
932 dec_running (void)
933 {
934 ASSERT(gc_running_threads != 0);
935 return atomic_dec(&gc_running_threads);
936 }
937
938 static rtsBool
939 any_work (void)
940 {
941 int g;
942 gen_workspace *ws;
943
944 gct->any_work++;
945
946 write_barrier();
947
948 // scavenge objects in compacted generation
949 if (mark_stack_bd != NULL && !mark_stack_empty()) {
950 return rtsTrue;
951 }
952
953 // Check for global work in any step. We don't need to check for
954 // local work, because we have already exited scavenge_loop(),
955 // which means there is no local work for this thread.
956 for (g = 0; g < (int)RtsFlags.GcFlags.generations; g++) {
957 ws = &gct->gens[g];
958 if (ws->todo_large_objects) return rtsTrue;
959 if (!looksEmptyWSDeque(ws->todo_q)) return rtsTrue;
960 if (ws->todo_overflow) return rtsTrue;
961 }
962
963 #if defined(THREADED_RTS)
964 if (work_stealing) {
965 nat n;
966 // look for work to steal
967 for (n = 0; n < n_gc_threads; n++) {
968 if (n == gct->thread_index) continue;
969 for (g = RtsFlags.GcFlags.generations-1; g >= 0; g--) {
970 ws = &gc_threads[n]->gens[g];
971 if (!looksEmptyWSDeque(ws->todo_q)) return rtsTrue;
972 }
973 }
974 }
975 #endif
976
977 gct->no_work++;
978 #if defined(THREADED_RTS)
979 yieldThread();
980 #endif
981
982 return rtsFalse;
983 }
984
985 static void
986 scavenge_until_all_done (void)
987 {
988 DEBUG_ONLY( nat r );
989
990
991 loop:
992 #if defined(THREADED_RTS)
993 if (n_gc_threads > 1) {
994 scavenge_loop();
995 } else {
996 scavenge_loop1();
997 }
998 #else
999 scavenge_loop();
1000 #endif
1001
1002 collect_gct_blocks();
1003
1004 // scavenge_loop() only exits when there's no work to do
1005
1006 #ifdef DEBUG
1007 r = dec_running();
1008 #else
1009 dec_running();
1010 #endif
1011
1012 traceEventGcIdle(gct->cap);
1013
1014 debugTrace(DEBUG_gc, "%d GC threads still running", r);
1015
1016 while (gc_running_threads != 0) {
1017 // usleep(1);
1018 if (any_work()) {
1019 inc_running();
1020 traceEventGcWork(gct->cap);
1021 goto loop;
1022 }
1023 // any_work() does not remove the work from the queue, it
1024 // just checks for the presence of work. If we find any,
1025 // then we increment gc_running_threads and go back to
1026 // scavenge_loop() to perform any pending work.
1027 }
1028
1029 traceEventGcDone(gct->cap);
1030 }
1031
1032 #if defined(THREADED_RTS)
1033
1034 void
1035 gcWorkerThread (Capability *cap)
1036 {
1037 gc_thread *saved_gct;
1038
1039 // necessary if we stole a callee-saves register for gct:
1040 saved_gct = gct;
1041
1042 SET_GCT(gc_threads[cap->no]);
1043 gct->id = osThreadId();
1044
1045 // Wait until we're told to wake up
1046 RELEASE_SPIN_LOCK(&gct->mut_spin);
1047 // yieldThread();
1048 // Strangely, adding a yieldThread() here makes the CPU time
1049 // measurements more accurate on Linux, perhaps because it syncs
1050 // the CPU time across the multiple cores. Without this, CPU time
1051 // is heavily skewed towards GC rather than MUT.
1052 gct->wakeup = GC_THREAD_STANDING_BY;
1053 debugTrace(DEBUG_gc, "GC thread %d standing by...", gct->thread_index);
1054 ACQUIRE_SPIN_LOCK(&gct->gc_spin);
1055
1056 #ifdef USE_PAPI
1057 // start performance counters in this thread...
1058 if (gct->papi_events == -1) {
1059 papi_init_eventset(&gct->papi_events);
1060 }
1061 papi_thread_start_gc1_count(gct->papi_events);
1062 #endif
1063
1064 init_gc_thread(gct);
1065
1066 traceEventGcWork(gct->cap);
1067
1068 // Every thread evacuates some roots.
1069 gct->evac_gen_no = 0;
1070 markCapability(mark_root, gct, cap, rtsTrue/*prune sparks*/);
1071 scavenge_capability_mut_lists(cap);
1072
1073 scavenge_until_all_done();
1074
1075 if (!DEBUG_IS_ON) {
1076 clearNursery(cap);
1077 }
1078
1079 #ifdef THREADED_RTS
1080 // Now that the whole heap is marked, we discard any sparks that
1081 // were found to be unreachable. The main GC thread is currently
1082 // marking heap reachable via weak pointers, so it is
1083 // non-deterministic whether a spark will be retained if it is
1084 // only reachable via weak pointers. To fix this problem would
1085 // require another GC barrier, which is too high a price.
1086 pruneSparkQueue(cap);
1087 #endif
1088
1089 #ifdef USE_PAPI
1090 // count events in this thread towards the GC totals
1091 papi_thread_stop_gc1_count(gct->papi_events);
1092 #endif
1093
1094 // Wait until we're told to continue
1095 RELEASE_SPIN_LOCK(&gct->gc_spin);
1096 gct->wakeup = GC_THREAD_WAITING_TO_CONTINUE;
1097 debugTrace(DEBUG_gc, "GC thread %d waiting to continue...",
1098 gct->thread_index);
1099 ACQUIRE_SPIN_LOCK(&gct->mut_spin);
1100 debugTrace(DEBUG_gc, "GC thread %d on my way...", gct->thread_index);
1101
1102 SET_GCT(saved_gct);
1103 }
1104
1105 #endif
1106
1107 #if defined(THREADED_RTS)
1108
1109 void
1110 waitForGcThreads (Capability *cap USED_IF_THREADS)
1111 {
1112 const nat n_threads = n_capabilities;
1113 const nat me = cap->no;
1114 nat i, j;
1115 rtsBool retry = rtsTrue;
1116
1117 while(retry) {
1118 for (i=0; i < n_threads; i++) {
1119 if (i == me || gc_threads[i]->idle) continue;
1120 if (gc_threads[i]->wakeup != GC_THREAD_STANDING_BY) {
1121 prodCapability(capabilities[i], cap->running_task);
1122 }
1123 }
1124 for (j=0; j < 10; j++) {
1125 retry = rtsFalse;
1126 for (i=0; i < n_threads; i++) {
1127 if (i == me || gc_threads[i]->idle) continue;
1128 write_barrier();
1129 interruptCapability(capabilities[i]);
1130 if (gc_threads[i]->wakeup != GC_THREAD_STANDING_BY) {
1131 retry = rtsTrue;
1132 }
1133 }
1134 if (!retry) break;
1135 yieldThread();
1136 }
1137 }
1138 }
1139
1140 #endif // THREADED_RTS
1141
1142 static void
1143 start_gc_threads (void)
1144 {
1145 #if defined(THREADED_RTS)
1146 gc_running_threads = 0;
1147 #endif
1148 }
1149
1150 static void
1151 wakeup_gc_threads (nat me USED_IF_THREADS)
1152 {
1153 #if defined(THREADED_RTS)
1154 nat i;
1155
1156 if (n_gc_threads == 1) return;
1157
1158 for (i=0; i < n_gc_threads; i++) {
1159 if (i == me || gc_threads[i]->idle) continue;
1160 inc_running();
1161 debugTrace(DEBUG_gc, "waking up gc thread %d", i);
1162 if (gc_threads[i]->wakeup != GC_THREAD_STANDING_BY) barf("wakeup_gc_threads");
1163
1164 gc_threads[i]->wakeup = GC_THREAD_RUNNING;
1165 ACQUIRE_SPIN_LOCK(&gc_threads[i]->mut_spin);
1166 RELEASE_SPIN_LOCK(&gc_threads[i]->gc_spin);
1167 }
1168 #endif
1169 }
1170
1171 // After GC is complete, we must wait for all GC threads to enter the
1172 // standby state, otherwise they may still be executing inside
1173 // any_work(), and may even remain awake until the next GC starts.
1174 static void
1175 shutdown_gc_threads (nat me USED_IF_THREADS)
1176 {
1177 #if defined(THREADED_RTS)
1178 nat i;
1179
1180 if (n_gc_threads == 1) return;
1181
1182 for (i=0; i < n_gc_threads; i++) {
1183 if (i == me || gc_threads[i]->idle) continue;
1184 while (gc_threads[i]->wakeup != GC_THREAD_WAITING_TO_CONTINUE) {
1185 busy_wait_nop();
1186 write_barrier();
1187 }
1188 }
1189 #endif
1190 }
1191
1192 #if defined(THREADED_RTS)
1193 void
1194 releaseGCThreads (Capability *cap USED_IF_THREADS)
1195 {
1196 const nat n_threads = n_capabilities;
1197 const nat me = cap->no;
1198 nat i;
1199 for (i=0; i < n_threads; i++) {
1200 if (i == me || gc_threads[i]->idle) continue;
1201 if (gc_threads[i]->wakeup != GC_THREAD_WAITING_TO_CONTINUE)
1202 barf("releaseGCThreads");
1203
1204 gc_threads[i]->wakeup = GC_THREAD_INACTIVE;
1205 ACQUIRE_SPIN_LOCK(&gc_threads[i]->gc_spin);
1206 RELEASE_SPIN_LOCK(&gc_threads[i]->mut_spin);
1207 }
1208 }
1209 #endif
1210
1211 /* ----------------------------------------------------------------------------
1212 Initialise a generation that is to be collected
1213 ------------------------------------------------------------------------- */
1214
1215 static void
1216 prepare_collected_gen (generation *gen)
1217 {
1218 nat i, g, n;
1219 gen_workspace *ws;
1220 bdescr *bd, *next;
1221
1222 // Throw away the current mutable list. Invariant: the mutable
1223 // list always has at least one block; this means we can avoid a
1224 // check for NULL in recordMutable().
1225 g = gen->no;
1226 if (g != 0) {
1227 for (i = 0; i < n_capabilities; i++) {
1228 freeChain(capabilities[i]->mut_lists[g]);
1229 capabilities[i]->mut_lists[g] = allocBlock();
1230 }
1231 }
1232
1233 gen = &generations[g];
1234 ASSERT(gen->no == g);
1235
1236 // we'll construct a new list of threads in this step
1237 // during GC, throw away the current list.
1238 gen->old_threads = gen->threads;
1239 gen->threads = END_TSO_QUEUE;
1240
1241 // deprecate the existing blocks
1242 gen->old_blocks = gen->blocks;
1243 gen->n_old_blocks = gen->n_blocks;
1244 gen->blocks = NULL;
1245 gen->n_blocks = 0;
1246 gen->n_words = 0;
1247 gen->live_estimate = 0;
1248
1249 // initialise the large object queues.
1250 ASSERT(gen->scavenged_large_objects == NULL);
1251 ASSERT(gen->n_scavenged_large_blocks == 0);
1252
1253 // grab all the partial blocks stashed in the gc_thread workspaces and
1254 // move them to the old_blocks list of this gen.
1255 for (n = 0; n < n_capabilities; n++) {
1256 ws = &gc_threads[n]->gens[gen->no];
1257
1258 for (bd = ws->part_list; bd != NULL; bd = next) {
1259 next = bd->link;
1260 bd->link = gen->old_blocks;
1261 gen->old_blocks = bd;
1262 gen->n_old_blocks += bd->blocks;
1263 }
1264 ws->part_list = NULL;
1265 ws->n_part_blocks = 0;
1266
1267 ASSERT(ws->scavd_list == NULL);
1268 ASSERT(ws->n_scavd_blocks == 0);
1269
1270 if (ws->todo_free != ws->todo_bd->start) {
1271 ws->todo_bd->free = ws->todo_free;
1272 ws->todo_bd->link = gen->old_blocks;
1273 gen->old_blocks = ws->todo_bd;
1274 gen->n_old_blocks += ws->todo_bd->blocks;
1275 alloc_todo_block(ws,0); // always has one block.
1276 }
1277 }
1278
1279 // mark the small objects as from-space
1280 for (bd = gen->old_blocks; bd; bd = bd->link) {
1281 bd->flags &= ~BF_EVACUATED;
1282 }
1283
1284 // mark the large objects as from-space
1285 for (bd = gen->large_objects; bd; bd = bd->link) {
1286 bd->flags &= ~BF_EVACUATED;
1287 }
1288
1289 // for a compacted generation, we need to allocate the bitmap
1290 if (gen->mark) {
1291 StgWord bitmap_size; // in bytes
1292 bdescr *bitmap_bdescr;
1293 StgWord *bitmap;
1294
1295 bitmap_size = gen->n_old_blocks * BLOCK_SIZE / (sizeof(W_)*BITS_PER_BYTE);
1296
1297 if (bitmap_size > 0) {
1298 bitmap_bdescr = allocGroup((StgWord)BLOCK_ROUND_UP(bitmap_size)
1299 / BLOCK_SIZE);
1300 gen->bitmap = bitmap_bdescr;
1301 bitmap = bitmap_bdescr->start;
1302
1303 debugTrace(DEBUG_gc, "bitmap_size: %d, bitmap: %p",
1304 bitmap_size, bitmap);
1305
1306 // don't forget to fill it with zeros!
1307 memset(bitmap, 0, bitmap_size);
1308
1309 // For each block in this step, point to its bitmap from the
1310 // block descriptor.
1311 for (bd=gen->old_blocks; bd != NULL; bd = bd->link) {
1312 bd->u.bitmap = bitmap;
1313 bitmap += BLOCK_SIZE_W / (sizeof(W_)*BITS_PER_BYTE);
1314
1315 // Also at this point we set the BF_MARKED flag
1316 // for this block. The invariant is that
1317 // BF_MARKED is always unset, except during GC
1318 // when it is set on those blocks which will be
1319 // compacted.
1320 if (!(bd->flags & BF_FRAGMENTED)) {
1321 bd->flags |= BF_MARKED;
1322 }
1323
1324 // BF_SWEPT should be marked only for blocks that are being
1325 // collected in sweep()
1326 bd->flags &= ~BF_SWEPT;
1327 }
1328 }
1329 }
1330 }
1331
1332
1333 /* ----------------------------------------------------------------------------
1334 Save the mutable lists in saved_mut_lists
1335 ------------------------------------------------------------------------- */
1336
1337 static void
1338 stash_mut_list (Capability *cap, nat gen_no)
1339 {
1340 cap->saved_mut_lists[gen_no] = cap->mut_lists[gen_no];
1341 cap->mut_lists[gen_no] = allocBlock_sync();
1342 }
1343
1344 /* ----------------------------------------------------------------------------
1345 Initialise a generation that is *not* to be collected
1346 ------------------------------------------------------------------------- */
1347
1348 static void
1349 prepare_uncollected_gen (generation *gen)
1350 {
1351 nat i;
1352
1353
1354 ASSERT(gen->no > 0);
1355
1356 // save the current mutable lists for this generation, and
1357 // allocate a fresh block for each one. We'll traverse these
1358 // mutable lists as roots early on in the GC.
1359 for (i = 0; i < n_capabilities; i++) {
1360 stash_mut_list(capabilities[i], gen->no);
1361 }
1362
1363 ASSERT(gen->scavenged_large_objects == NULL);
1364 ASSERT(gen->n_scavenged_large_blocks == 0);
1365 }
1366
1367 /* -----------------------------------------------------------------------------
1368 Collect the completed blocks from a GC thread and attach them to
1369 the generation.
1370 -------------------------------------------------------------------------- */
1371
1372 static void
1373 collect_gct_blocks (void)
1374 {
1375 nat g;
1376 gen_workspace *ws;
1377 bdescr *bd, *prev;
1378
1379 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1380 ws = &gct->gens[g];
1381
1382 // there may still be a block attached to ws->todo_bd;
1383 // leave it there to use next time.
1384
1385 if (ws->scavd_list != NULL) {
1386 ACQUIRE_SPIN_LOCK(&ws->gen->sync);
1387
1388 ASSERT(gct->scan_bd == NULL);
1389 ASSERT(countBlocks(ws->scavd_list) == ws->n_scavd_blocks);
1390
1391 prev = NULL;
1392 for (bd = ws->scavd_list; bd != NULL; bd = bd->link) {
1393 ws->gen->n_words += bd->free - bd->start;
1394 prev = bd;
1395 }
1396 if (prev != NULL) {
1397 prev->link = ws->gen->blocks;
1398 ws->gen->blocks = ws->scavd_list;
1399 }
1400 ws->gen->n_blocks += ws->n_scavd_blocks;
1401
1402 ws->scavd_list = NULL;
1403 ws->n_scavd_blocks = 0;
1404
1405 RELEASE_SPIN_LOCK(&ws->gen->sync);
1406 }
1407 }
1408 }
1409
1410 /* -----------------------------------------------------------------------------
1411 During mutation, any blocks that are filled by allocatePinned() are
1412 stashed on the local pinned_object_blocks list, to avoid needing to
1413 take a global lock. Here we collect those blocks from the
1414 cap->pinned_object_blocks lists and put them on the
1415 main g0->large_object list.
1416
1417 Returns: the number of words allocated this way, for stats
1418 purposes.
1419 -------------------------------------------------------------------------- */
1420
1421 static void
1422 collect_pinned_object_blocks (void)
1423 {
1424 nat n;
1425 bdescr *bd, *prev;
1426
1427 for (n = 0; n < n_capabilities; n++) {
1428 prev = NULL;
1429 for (bd = capabilities[n]->pinned_object_blocks; bd != NULL; bd = bd->link) {
1430 prev = bd;
1431 }
1432 if (prev != NULL) {
1433 prev->link = g0->large_objects;
1434 if (g0->large_objects != NULL) {
1435 g0->large_objects->u.back = prev;
1436 }
1437 g0->large_objects = capabilities[n]->pinned_object_blocks;
1438 capabilities[n]->pinned_object_blocks = 0;
1439 }
1440 }
1441 }
1442
1443 /* -----------------------------------------------------------------------------
1444 Initialise a gc_thread before GC
1445 -------------------------------------------------------------------------- */
1446
1447 static void
1448 init_gc_thread (gc_thread *t)
1449 {
1450 t->static_objects = END_OF_STATIC_LIST;
1451 t->scavenged_static_objects = END_OF_STATIC_LIST;
1452 t->scan_bd = NULL;
1453 t->mut_lists = t->cap->mut_lists;
1454 t->evac_gen_no = 0;
1455 t->failed_to_evac = rtsFalse;
1456 t->eager_promotion = rtsTrue;
1457 t->thunk_selector_depth = 0;
1458 t->copied = 0;
1459 t->scanned = 0;
1460 t->any_work = 0;
1461 t->no_work = 0;
1462 t->scav_find_work = 0;
1463 }
1464
1465 /* -----------------------------------------------------------------------------
1466 Function we pass to evacuate roots.
1467 -------------------------------------------------------------------------- */
1468
1469 static void
1470 mark_root(void *user USED_IF_THREADS, StgClosure **root)
1471 {
1472 // we stole a register for gct, but this function is called from
1473 // *outside* the GC where the register variable is not in effect,
1474 // so we need to save and restore it here. NB. only call
1475 // mark_root() from the main GC thread, otherwise gct will be
1476 // incorrect.
1477 #if defined(THREADED_RTS)
1478 gc_thread *saved_gct;
1479 saved_gct = gct;
1480 #endif
1481 SET_GCT(user);
1482
1483 evacuate(root);
1484
1485 SET_GCT(saved_gct);
1486 }
1487
1488 /* -----------------------------------------------------------------------------
1489 Initialising the static object & mutable lists
1490 -------------------------------------------------------------------------- */
1491
1492 static void
1493 zero_static_object_list(StgClosure* first_static)
1494 {
1495 StgClosure* p;
1496 StgClosure* link;
1497 const StgInfoTable *info;
1498
1499 for (p = first_static; p != END_OF_STATIC_LIST; p = link) {
1500 info = get_itbl(p);
1501 link = *STATIC_LINK(info, p);
1502 *STATIC_LINK(info,p) = NULL;
1503 }
1504 }
1505
1506 /* ----------------------------------------------------------------------------
1507 Reset the sizes of the older generations when we do a major
1508 collection.
1509
1510 CURRENT STRATEGY: make all generations except zero the same size.
1511 We have to stay within the maximum heap size, and leave a certain
1512 percentage of the maximum heap size available to allocate into.
1513 ------------------------------------------------------------------------- */
1514
1515 static void
1516 resize_generations (void)
1517 {
1518 nat g;
1519
1520 if (major_gc && RtsFlags.GcFlags.generations > 1) {
1521 W_ live, size, min_alloc, words;
1522 const W_ max = RtsFlags.GcFlags.maxHeapSize;
1523 const W_ gens = RtsFlags.GcFlags.generations;
1524
1525 // live in the oldest generations
1526 if (oldest_gen->live_estimate != 0) {
1527 words = oldest_gen->live_estimate;
1528 } else {
1529 words = oldest_gen->n_words;
1530 }
1531 live = (words + BLOCK_SIZE_W - 1) / BLOCK_SIZE_W +
1532 oldest_gen->n_large_blocks;
1533
1534 // default max size for all generations except zero
1535 size = stg_max(live * RtsFlags.GcFlags.oldGenFactor,
1536 RtsFlags.GcFlags.minOldGenSize);
1537
1538 if (RtsFlags.GcFlags.heapSizeSuggestionAuto) {
1539 if (max > 0) {
1540 RtsFlags.GcFlags.heapSizeSuggestion = stg_min(max, size);
1541 } else {
1542 RtsFlags.GcFlags.heapSizeSuggestion = size;
1543 }
1544 }
1545
1546 // minimum size for generation zero
1547 min_alloc = stg_max((RtsFlags.GcFlags.pcFreeHeap * max) / 200,
1548 RtsFlags.GcFlags.minAllocAreaSize);
1549
1550 // Auto-enable compaction when the residency reaches a
1551 // certain percentage of the maximum heap size (default: 30%).
1552 if (RtsFlags.GcFlags.compact ||
1553 (max > 0 &&
1554 oldest_gen->n_blocks >
1555 (RtsFlags.GcFlags.compactThreshold * max) / 100)) {
1556 oldest_gen->mark = 1;
1557 oldest_gen->compact = 1;
1558 // debugBelch("compaction: on\n", live);
1559 } else {
1560 oldest_gen->mark = 0;
1561 oldest_gen->compact = 0;
1562 // debugBelch("compaction: off\n", live);
1563 }
1564
1565 if (RtsFlags.GcFlags.sweep) {
1566 oldest_gen->mark = 1;
1567 }
1568
1569 // if we're going to go over the maximum heap size, reduce the
1570 // size of the generations accordingly. The calculation is
1571 // different if compaction is turned on, because we don't need
1572 // to double the space required to collect the old generation.
1573 if (max != 0) {
1574
1575 // this test is necessary to ensure that the calculations
1576 // below don't have any negative results - we're working
1577 // with unsigned values here.
1578 if (max < min_alloc) {
1579 heapOverflow();
1580 }
1581
1582 if (oldest_gen->compact) {
1583 if ( (size + (size - 1) * (gens - 2) * 2) + min_alloc > max ) {
1584 size = (max - min_alloc) / ((gens - 1) * 2 - 1);
1585 }
1586 } else {
1587 if ( (size * (gens - 1) * 2) + min_alloc > max ) {
1588 size = (max - min_alloc) / ((gens - 1) * 2);
1589 }
1590 }
1591
1592 if (size < live) {
1593 heapOverflow();
1594 }
1595 }
1596
1597 #if 0
1598 debugBelch("live: %d, min_alloc: %d, size : %d, max = %d\n", live,
1599 min_alloc, size, max);
1600 #endif
1601
1602 for (g = 0; g < gens; g++) {
1603 generations[g].max_blocks = size;
1604 }
1605 }
1606 }
1607
1608 /* -----------------------------------------------------------------------------
1609 Calculate the new size of the nursery, and resize it.
1610 -------------------------------------------------------------------------- */
1611
1612 static void
1613 resize_nursery (void)
1614 {
1615 const StgWord min_nursery =
1616 RtsFlags.GcFlags.minAllocAreaSize * (StgWord)n_capabilities;
1617
1618 if (RtsFlags.GcFlags.generations == 1)
1619 { // Two-space collector:
1620 W_ blocks;
1621
1622 /* set up a new nursery. Allocate a nursery size based on a
1623 * function of the amount of live data (by default a factor of 2)
1624 * Use the blocks from the old nursery if possible, freeing up any
1625 * left over blocks.
1626 *
1627 * If we get near the maximum heap size, then adjust our nursery
1628 * size accordingly. If the nursery is the same size as the live
1629 * data (L), then we need 3L bytes. We can reduce the size of the
1630 * nursery to bring the required memory down near 2L bytes.
1631 *
1632 * A normal 2-space collector would need 4L bytes to give the same
1633 * performance we get from 3L bytes, reducing to the same
1634 * performance at 2L bytes.
1635 */
1636 blocks = generations[0].n_blocks;
1637
1638 if ( RtsFlags.GcFlags.maxHeapSize != 0 &&
1639 blocks * RtsFlags.GcFlags.oldGenFactor * 2 >
1640 RtsFlags.GcFlags.maxHeapSize )
1641 {
1642 long adjusted_blocks; // signed on purpose
1643 int pc_free;
1644
1645 adjusted_blocks = (RtsFlags.GcFlags.maxHeapSize - 2 * blocks);
1646
1647 debugTrace(DEBUG_gc, "near maximum heap size of 0x%x blocks, blocks = %d, adjusted to %ld",
1648 RtsFlags.GcFlags.maxHeapSize, blocks, adjusted_blocks);
1649
1650 pc_free = adjusted_blocks * 100 / RtsFlags.GcFlags.maxHeapSize;
1651 if (pc_free < RtsFlags.GcFlags.pcFreeHeap) /* might even * be < 0 */
1652 {
1653 heapOverflow();
1654 }
1655 blocks = adjusted_blocks;
1656 }
1657 else
1658 {
1659 blocks *= RtsFlags.GcFlags.oldGenFactor;
1660 if (blocks < min_nursery)
1661 {
1662 blocks = min_nursery;
1663 }
1664 }
1665 resizeNurseries(blocks);
1666 }
1667 else // Generational collector
1668 {
1669 /*
1670 * If the user has given us a suggested heap size, adjust our
1671 * allocation area to make best use of the memory available.
1672 */
1673 if (RtsFlags.GcFlags.heapSizeSuggestion)
1674 {
1675 long blocks;
1676 StgWord needed;
1677
1678 calcNeeded(rtsFalse, &needed); // approx blocks needed at next GC
1679
1680 /* Guess how much will be live in generation 0 step 0 next time.
1681 * A good approximation is obtained by finding the
1682 * percentage of g0 that was live at the last minor GC.
1683 *
1684 * We have an accurate figure for the amount of copied data in
1685 * 'copied', but we must convert this to a number of blocks, with
1686 * a small adjustment for estimated slop at the end of a block
1687 * (- 10 words).
1688 */
1689 if (N == 0)
1690 {
1691 g0_pcnt_kept = ((copied / (BLOCK_SIZE_W - 10)) * 100)
1692 / countNurseryBlocks();
1693 }
1694
1695 /* Estimate a size for the allocation area based on the
1696 * information available. We might end up going slightly under
1697 * or over the suggested heap size, but we should be pretty
1698 * close on average.
1699 *
1700 * Formula: suggested - needed
1701 * ----------------------------
1702 * 1 + g0_pcnt_kept/100
1703 *
1704 * where 'needed' is the amount of memory needed at the next
1705 * collection for collecting all gens except g0.
1706 */
1707 blocks =
1708 (((long)RtsFlags.GcFlags.heapSizeSuggestion - (long)needed) * 100) /
1709 (100 + (long)g0_pcnt_kept);
1710
1711 if (blocks < (long)min_nursery) {
1712 blocks = min_nursery;
1713 }
1714
1715 resizeNurseries((W_)blocks);
1716 }
1717 else
1718 {
1719 // we might have added extra large blocks to the nursery, so
1720 // resize back to minAllocAreaSize again.
1721 resizeNurseriesFixed(RtsFlags.GcFlags.minAllocAreaSize);
1722 }
1723 }
1724 }
1725
1726 /* -----------------------------------------------------------------------------
1727 Sanity code for CAF garbage collection.
1728
1729 With DEBUG turned on, we manage a CAF list in addition to the SRT
1730 mechanism. After GC, we run down the CAF list and blackhole any
1731 CAFs which have been garbage collected. This means we get an error
1732 whenever the program tries to enter a garbage collected CAF.
1733
1734 Any garbage collected CAFs are taken off the CAF list at the same
1735 time.
1736 -------------------------------------------------------------------------- */
1737
1738 #if defined(DEBUG)
1739
1740 static void gcCAFs(void)
1741 {
1742 StgIndStatic *p, *prev;
1743
1744 const StgInfoTable *info;
1745 nat i;
1746
1747 i = 0;
1748 p = debug_caf_list;
1749 prev = NULL;
1750
1751 for (p = debug_caf_list; p != (StgIndStatic*)END_OF_STATIC_LIST;
1752 p = (StgIndStatic*)p->saved_info) {
1753
1754 info = get_itbl((StgClosure*)p);
1755 ASSERT(info->type == IND_STATIC);
1756
1757 if (p->static_link == NULL) {
1758 debugTrace(DEBUG_gccafs, "CAF gc'd at 0x%p", p);
1759 SET_INFO((StgClosure*)p,&stg_GCD_CAF_info); // stub it
1760 if (prev == NULL) {
1761 debug_caf_list = (StgIndStatic*)p->saved_info;
1762 } else {
1763 prev->saved_info = p->saved_info;
1764 }
1765 } else {
1766 prev = p;
1767 i++;
1768 }
1769 }
1770
1771 debugTrace(DEBUG_gccafs, "%d CAFs live", i);
1772 }
1773 #endif