Debian Codegraph @

src/runtime/mgc.go

raw
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Garbage collector (GC).
6 //
7 // The GC runs concurrently with mutator threads, is type accurate (aka precise), allows multiple
8 // GC threads to run in parallel. It is a concurrent mark and sweep that uses a write barrier. It is
9 // non-generational and non-compacting. Allocation is done using size segregated per P allocation
10 // areas to minimize fragmentation while eliminating locks in the common case.
11 //
12 // The algorithm decomposes into several steps.
13 // This is a high level description of the algorithm being used. For an overview of GC a good
14 // place to start is Richard Jones' gchandbook.org.
15 //
16 // The algorithm's intellectual heritage includes Dijkstra's on-the-fly algorithm, see
17 // Edsger W. Dijkstra, Leslie Lamport, A. J. Martin, C. S. Scholten, and E. F. M. Steffens. 1978.
18 // On-the-fly garbage collection: an exercise in cooperation. Commun. ACM 21, 11 (November 1978),
19 // 966-975.
20 // For journal quality proofs that these steps are complete, correct, and terminate see
21 // Hudson, R., and Moss, J.E.B. Copying Garbage Collection without stopping the world.
22 // Concurrency and Computation: Practice and Experience 15(3-5), 2003.
23 //
24 // 1. GC performs sweep termination.
25 //
26 // a. Stop the world. This causes all Ps to reach a GC safe-point.
27 //
28 // b. Sweep any unswept spans. There will only be unswept spans if
29 // this GC cycle was forced before the expected time.
30 //
31 // 2. GC performs the mark phase.
32 //
33 // a. Prepare for the mark phase by setting gcphase to _GCmark
34 // (from _GCoff), enabling the write barrier, enabling mutator
35 // assists, and enqueueing root mark jobs. No objects may be
36 // scanned until all Ps have enabled the write barrier, which is
37 // accomplished using STW.
38 //
39 // b. Start the world. From this point, GC work is done by mark
40 // workers started by the scheduler and by assists performed as
41 // part of allocation. The write barrier shades both the
42 // overwritten pointer and the new pointer value for any pointer
43 // writes (see mbarrier.go for details). Newly allocated objects
44 // are immediately marked black.
45 //
46 // c. GC performs root marking jobs. This includes scanning all
47 // stacks, shading all globals, and shading any heap pointers in
48 // off-heap runtime data structures. Scanning a stack stops a
49 // goroutine, shades any pointers found on its stack, and then
50 // resumes the goroutine.
51 //
52 // d. GC drains the work queue of grey objects, scanning each grey
53 // object to black and shading all pointers found in the object
54 // (which in turn may add those pointers to the work queue).
55 //
56 // e. Because GC work is spread across local caches, GC uses a
57 // distributed termination algorithm to detect when there are no
58 // more root marking jobs or grey objects (see gcMarkDone). At this
59 // point, GC transitions to mark termination.
60 //
61 // 3. GC performs mark termination.
62 //
63 // a. Stop the world.
64 //
65 // b. Set gcphase to _GCmarktermination, and disable workers and
66 // assists.
67 //
68 // c. Perform housekeeping like flushing mcaches.
69 //
70 // 4. GC performs the sweep phase.
71 //
72 // a. Prepare for the sweep phase by setting gcphase to _GCoff,
73 // setting up sweep state and disabling the write barrier.
74 //
75 // b. Start the world. From this point on, newly allocated objects
76 // are white, and allocating sweeps spans before use if necessary.
77 //
78 // c. GC does concurrent sweeping in the background and in response
79 // to allocation. See description below.
80 //
81 // 5. When sufficient allocation has taken place, replay the sequence
82 // starting with 1 above. See discussion of GC rate below.
83
84 // Concurrent sweep.
85 //
86 // The sweep phase proceeds concurrently with normal program execution.
87 // The heap is swept span-by-span both lazily (when a goroutine needs another span)
88 // and concurrently in a background goroutine (this helps programs that are not CPU bound).
89 // At the end of STW mark termination all spans are marked as "needs sweeping".
90 //
91 // The background sweeper goroutine simply sweeps spans one-by-one.
92 //
93 // To avoid requesting more OS memory while there are unswept spans, when a
94 // goroutine needs another span, it first attempts to reclaim that much memory
95 // by sweeping. When a goroutine needs to allocate a new small-object span, it
96 // sweeps small-object spans for the same object size until it frees at least
97 // one object. When a goroutine needs to allocate large-object span from heap,
98 // it sweeps spans until it frees at least that many pages into heap. There is
99 // one case where this may not suffice: if a goroutine sweeps and frees two
100 // nonadjacent one-page spans to the heap, it will allocate a new two-page
101 // span, but there can still be other one-page unswept spans which could be
102 // combined into a two-page span.
103 //
104 // It's critical to ensure that no operations proceed on unswept spans (that would corrupt
105 // mark bits in GC bitmap). During GC all mcaches are flushed into the central cache,
106 // so they are empty. When a goroutine grabs a new span into mcache, it sweeps it.
107 // When a goroutine explicitly frees an object or sets a finalizer, it ensures that
108 // the span is swept (either by sweeping it, or by waiting for the concurrent sweep to finish).
109 // The finalizer goroutine is kicked off only when all spans are swept.
110 // When the next GC starts, it sweeps all not-yet-swept spans (if any).
111
112 // GC rate.
113 // Next GC is after we've allocated an extra amount of memory proportional to
114 // the amount already in use. The proportion is controlled by GOGC environment variable
115 // (100 by default). If GOGC=100 and we're using 4M, we'll GC again when we get to 8M
116 // (this mark is computed by the gcController.heapGoal method). This keeps the GC cost in
117 // linear proportion to the allocation cost. Adjusting GOGC just changes the linear constant
118 // (and also the amount of extra memory used).
119
120 // Oblets
121 //
122 // In order to prevent long pauses while scanning large objects and to
123 // improve parallelism, the garbage collector breaks up scan jobs for
124 // objects larger than maxObletBytes into "oblets" of at most
125 // maxObletBytes. When scanning encounters the beginning of a large
126 // object, it scans only the first oblet and enqueues the remaining
127 // oblets as new scan jobs.
128
129 package runtime
130
131 import (
132 "internal/cpu"
133 "internal/goarch"
134 "internal/goexperiment"
135 "internal/runtime/atomic"
136 "internal/runtime/gc"
137 "unsafe"
138 )
139
140 const (
141 _DebugGC = 0
142
143 // concurrentSweep is a debug flag. Disabling this flag
144 // ensures all spans are swept while the world is stopped.
145 concurrentSweep = true
146
147 // debugScanConservative enables debug logging for stack
148 // frames that are scanned conservatively.
149 debugScanConservative = false
150
151 // sweepMinHeapDistance is a lower bound on the heap distance
152 // (in bytes) reserved for concurrent sweeping between GC
153 // cycles.
154 sweepMinHeapDistance = 1024 * 1024
155 )
156
157 // heapObjectsCanMove always returns false in the current garbage collector.
158 // It exists for go4.org/unsafe/assume-no-moving-gc, which is an
159 // unfortunate idea that had an even more unfortunate implementation.
160 // Every time a new Go release happened, the package stopped building,
161 // and the authors had to add a new file with a new //go:build line, and
162 // then the entire ecosystem of packages with that as a dependency had to
163 // explicitly update to the new version. Many packages depend on
164 // assume-no-moving-gc transitively, through paths like
165 // inet.af/netaddr -> go4.org/intern -> assume-no-moving-gc.
166 // This was causing a significant amount of friction around each new
167 // release, so we added this bool for the package to //go:linkname
168 // instead. The bool is still unfortunate, but it's not as bad as
169 // breaking the ecosystem on every new release.
170 //
171 // If the Go garbage collector ever does move heap objects, we can set
172 // this to true to break all the programs using assume-no-moving-gc.
173 //
174 //go:linkname heapObjectsCanMove
175 func heapObjectsCanMove() bool {
176 return false
177 }
178
179 func gcinit() {
180 if unsafe.Sizeof(workbuf{}) != _WorkbufSize {
181 throw("size of Workbuf is suboptimal")
182 }
183 // No sweep on the first cycle.
184 sweep.active.state.Store(sweepDrainedMask)
185
186 // Initialize GC pacer state.
187 // Use the environment variable GOGC for the initial gcPercent value.
188 // Use the environment variable GOMEMLIMIT for the initial memoryLimit value.
189 gcController.init(readGOGC(), readGOMEMLIMIT())
190
191 // Set up the cleanup block ptr mask.
192 for i := range cleanupBlockPtrMask {
193 cleanupBlockPtrMask[i] = 0xff
194 }
195
196 work.startSema = 1
197 work.markDoneSema = 1
198 work.spanSPMCs.list.init(unsafe.Offsetof(spanSPMC{}.allnode))
199 lockInit(&work.sweepWaiters.lock, lockRankSweepWaiters)
200 lockInit(&work.assistQueue.lock, lockRankAssistQueue)
201 lockInit(&work.strongFromWeak.lock, lockRankStrongFromWeakQueue)
202 lockInit(&work.wbufSpans.lock, lockRankWbufSpans)
203 lockInit(&work.spanSPMCs.lock, lockRankSpanSPMCs)
204 lockInit(&gcCleanups.lock, lockRankCleanupQueue)
205 }
206
207 // gcenable is called after the bulk of the runtime initialization,
208 // just before we're about to start letting user code run.
209 // It kicks off the background sweeper goroutine, the background
210 // scavenger goroutine, and enables GC.
211 func gcenable() {
212 // Kick off sweeping and scavenging.
213 c := make(chan int, 2)
214 go bgsweep(c)
215 go bgscavenge(c)
216 <-c
217 <-c
218 memstats.enablegc = true // now that runtime is initialized, GC is okay
219 }
220
221 // Garbage collector phase.
222 // Indicates to write barrier and synchronization task to perform.
223 var gcphase uint32
224
225 // The compiler knows about this variable.
226 // If you change it, you must change builtin/runtime.go, too.
227 // If you change the first four bytes, you must also change the write
228 // barrier insertion code.
229 //
230 // writeBarrier should be an internal detail,
231 // but widely used packages access it using linkname.
232 // Notable members of the hall of shame include:
233 // - github.com/bytedance/sonic
234 //
235 // Do not remove or change the type signature.
236 // See go.dev/issue/67401.
237 //
238 //go:linkname writeBarrier
239 var writeBarrier struct {
240 enabled bool // compiler emits a check of this before calling write barrier
241 pad [3]byte // compiler uses 32-bit load for "enabled" field
242 alignme uint64 // guarantee alignment so that compiler can use a 32 or 64-bit load
243 }
244
245 // gcBlackenEnabled is 1 if mutator assists and background mark
246 // workers are allowed to blacken objects. This must only be set when
247 // gcphase == _GCmark.
248 var gcBlackenEnabled uint32
249
250 const (
251 _GCoff = iota // GC not running; sweeping in background, write barrier disabled
252 _GCmark // GC marking roots and workbufs: allocate black, write barrier ENABLED
253 _GCmarktermination // GC mark termination: allocate black, P's help GC, write barrier ENABLED
254 )
255
256 //go:nosplit
257 func setGCPhase(x uint32) {
258 atomic.Store(&gcphase, x)
259 writeBarrier.enabled = gcphase == _GCmark || gcphase == _GCmarktermination
260 }
261
262 // gcMarkWorkerMode represents the mode that a concurrent mark worker
263 // should operate in.
264 //
265 // Concurrent marking happens through four different mechanisms. One
266 // is mutator assists, which happen in response to allocations and are
267 // not scheduled. The other three are variations in the per-P mark
268 // workers and are distinguished by gcMarkWorkerMode.
269 type gcMarkWorkerMode int
270
271 const (
272 // gcMarkWorkerNotWorker indicates that the next scheduled G is not
273 // starting work and the mode should be ignored.
274 gcMarkWorkerNotWorker gcMarkWorkerMode = iota
275
276 // gcMarkWorkerDedicatedMode indicates that the P of a mark
277 // worker is dedicated to running that mark worker. The mark
278 // worker should run without preemption.
279 gcMarkWorkerDedicatedMode
280
281 // gcMarkWorkerFractionalMode indicates that a P is currently
282 // running the "fractional" mark worker. The fractional worker
283 // is necessary when GOMAXPROCS*gcBackgroundUtilization is not
284 // an integer and using only dedicated workers would result in
285 // utilization too far from the target of gcBackgroundUtilization.
286 // The fractional worker should run until it is preempted and
287 // will be scheduled to pick up the fractional part of
288 // GOMAXPROCS*gcBackgroundUtilization.
289 gcMarkWorkerFractionalMode
290
291 // gcMarkWorkerIdleMode indicates that a P is running the mark
292 // worker because it has nothing else to do. The idle worker
293 // should run until it is preempted and account its time
294 // against gcController.idleMarkTime.
295 gcMarkWorkerIdleMode
296 )
297
298 // gcMarkWorkerModeStrings are the strings labels of gcMarkWorkerModes
299 // to use in execution traces.
300 var gcMarkWorkerModeStrings = [...]string{
301 "Not worker",
302 "GC (dedicated)",
303 "GC (fractional)",
304 "GC (idle)",
305 }
306
307 // pollFractionalWorkerExit reports whether a fractional mark worker
308 // should self-preempt. It assumes it is called from the fractional
309 // worker.
310 func pollFractionalWorkerExit() bool {
311 // This should be kept in sync with the fractional worker
312 // scheduler logic in findRunnableGCWorker.
313 now := nanotime()
314 delta := now - gcController.markStartTime
315 if delta <= 0 {
316 return true
317 }
318 p := getg().m.p.ptr()
319 selfTime := p.gcFractionalMarkTime.Load() + (now - p.gcMarkWorkerStartTime)
320 // Add some slack to the utilization goal so that the
321 // fractional worker isn't behind again the instant it exits.
322 return float64(selfTime)/float64(delta) > 1.2*gcController.fractionalUtilizationGoal
323 }
324
325 var work workType
326
327 type workType struct {
328 full lfstack // lock-free list of full blocks workbuf
329 _ cpu.CacheLinePad // prevents false-sharing between full and empty
330 empty lfstack // lock-free list of empty blocks workbuf
331 _ cpu.CacheLinePad // prevents false-sharing between empty and wbufSpans
332
333 wbufSpans struct {
334 lock mutex
335 // free is a list of spans dedicated to workbufs, but
336 // that don't currently contain any workbufs.
337 free mSpanList
338 // busy is a list of all spans containing workbufs on
339 // one of the workbuf lists.
340 busy mSpanList
341 }
342 _ cpu.CacheLinePad // prevents false-sharing between wbufSpans and spanWorkMask
343
344 // spanqMask is a bitmap indicating which Ps have local work worth stealing.
345 // Set or cleared by the owning P, cleared by stealing Ps.
346 //
347 // spanqMask is like a proxy for a global queue. An important invariant is that
348 // forced flushing like gcw.dispose must set this bit on any P that has local
349 // span work.
350 spanqMask pMask
351 _ cpu.CacheLinePad // prevents false-sharing between spanqMask and everything else
352
353 // List of all spanSPMCs.
354 //
355 // Only used if goexperiment.GreenTeaGC.
356 spanSPMCs struct {
357 lock mutex
358 list listHeadManual // *spanSPMC
359 }
360
361 // Restore 64-bit alignment on 32-bit.
362 // _ uint32
363
364 // bytesMarked is the number of bytes marked this cycle. This
365 // includes bytes blackened in scanned objects, noscan objects
366 // that go straight to black, objects allocated as black during
367 // the cycle, and permagrey objects scanned by markroot during
368 // the concurrent scan phase.
369 //
370 // This is updated atomically during the cycle. Updates may be batched
371 // arbitrarily, since the value is only read at the end of the cycle.
372 //
373 // Because of benign races during marking, this number may not
374 // be the exact number of marked bytes, but it should be very
375 // close.
376 //
377 // Put this field here because it needs 64-bit atomic access
378 // (and thus 8-byte alignment even on 32-bit architectures).
379 bytesMarked uint64
380
381 markrootNext atomic.Uint32 // next markroot job
382 markrootJobs atomic.Uint32 // number of markroot jobs
383
384 nproc uint32
385 tstart int64
386 nwait uint32
387
388 // Number of roots of various root types. Set by gcPrepareMarkRoots.
389 //
390 // During normal GC cycle, nStackRoots == nMaybeRunnableStackRoots == len(stackRoots);
391 // during goroutine leak detection, nMaybeRunnableStackRoots is the number of stackRoots
392 // scheduled for marking.
393 // In both variants, nStackRoots == len(stackRoots).
394 nDataRoots, nBSSRoots, nSpanRoots, nStackRoots, nMaybeRunnableStackRoots int
395
396 // The following fields monitor the GC phase of the current cycle during
397 // goroutine leak detection.
398 goroutineLeak struct {
399 // Once set, it indicates that the GC will perform goroutine leak detection during
400 // the next GC cycle; it is set by goroutineLeakGC and unset during gcStart.
401 pending atomic.Bool
402 // Once set, it indicates that the GC has started a goroutine leak detection run;
403 // it is set during gcStart and unset during gcMarkTermination;
404 //
405 // Protected by STW.
406 enabled bool
407 // Once set, it indicates that the GC has performed goroutine leak detection during
408 // the current GC cycle; it is set during gcMarkDone, right after goroutine leak detection,
409 // and unset during gcMarkTermination;
410 //
411 // Protected by STW.
412 done bool
413 // The number of leaked goroutines during the last leak detection GC cycle.
414 //
415 // Write-protected by STW in findGoroutineLeaks.
416 count int
417 }
418
419 // Base indexes of each root type. Set by gcPrepareMarkRoots.
420 baseData, baseBSS, baseSpans, baseStacks, baseEnd uint32
421
422 // stackRoots is a snapshot of all of the Gs that existed before the
423 // beginning of concurrent marking. During goroutine leak detection, stackRoots
424 // is partitioned into two sets; to the left of nMaybeRunnableStackRoots are stackRoots
425 // of running / runnable goroutines and to the right of nMaybeRunnableStackRoots are
426 // stackRoots of unmarked / not runnable goroutines
427 // The stackRoots array is re-partitioned after each marking phase iteration.
428 stackRoots []*g
429
430 // Each type of GC state transition is protected by a lock.
431 // Since multiple threads can simultaneously detect the state
432 // transition condition, any thread that detects a transition
433 // condition must acquire the appropriate transition lock,
434 // re-check the transition condition and return if it no
435 // longer holds or perform the transition if it does.
436 // Likewise, any transition must invalidate the transition
437 // condition before releasing the lock. This ensures that each
438 // transition is performed by exactly one thread and threads
439 // that need the transition to happen block until it has
440 // happened.
441 //
442 // startSema protects the transition from "off" to mark or
443 // mark termination.
444 startSema uint32
445 // markDoneSema protects transitions from mark to mark termination.
446 markDoneSema uint32
447
448 bgMarkDone uint32 // cas to 1 when at a background mark completion point
449 // Background mark completion signaling
450
451 // mode is the concurrency mode of the current GC cycle.
452 mode gcMode
453
454 // userForced indicates the current GC cycle was forced by an
455 // explicit user call.
456 userForced bool
457
458 // initialHeapLive is the value of gcController.heapLive at the
459 // beginning of this GC cycle.
460 initialHeapLive uint64
461
462 // assistQueue is a queue of assists that are blocked because
463 // there was neither enough credit to steal or enough work to
464 // do.
465 assistQueue struct {
466 lock mutex
467 q gQueue
468 }
469
470 // sweepWaiters is a list of blocked goroutines to wake when
471 // we transition from mark termination to sweep.
472 sweepWaiters struct {
473 lock mutex
474 list gList
475 }
476
477 // strongFromWeak controls how the GC interacts with weak->strong
478 // pointer conversions.
479 strongFromWeak struct {
480 // block is a flag set during mark termination that prevents
481 // new weak->strong conversions from executing by blocking the
482 // goroutine and enqueuing it onto q.
483 //
484 // Mutated only by one goroutine at a time in gcMarkDone,
485 // with globally-synchronizing events like forEachP and
486 // stopTheWorld.
487 block bool
488
489 // q is a queue of goroutines that attempted to perform a
490 // weak->strong conversion during mark termination.
491 //
492 // Protected by lock.
493 lock mutex
494 q gQueue
495 }
496
497 // cycles is the number of completed GC cycles, where a GC
498 // cycle is sweep termination, mark, mark termination, and
499 // sweep. This differs from memstats.numgc, which is
500 // incremented at mark termination.
501 cycles atomic.Uint32
502
503 // Timing/utilization stats for this cycle.
504 stwprocs, maxprocs int32
505 tSweepTerm, tMark, tMarkTerm, tEnd int64 // nanotime() of phase start
506
507 // pauseNS is the total STW time this cycle, measured as the time between
508 // when stopping began (just before trying to stop Ps) and just after the
509 // world started again.
510 pauseNS int64
511
512 // debug.gctrace heap sizes for this cycle.
513 heap0, heap1, heap2 uint64
514
515 // Cumulative estimated CPU usage.
516 cpuStats
517 }
518
519 // GC runs a garbage collection and blocks the caller until the
520 // garbage collection is complete. It may also block the entire
521 // program.
522 func GC() {
523 // We consider a cycle to be: sweep termination, mark, mark
524 // termination, and sweep. This function shouldn't return
525 // until a full cycle has been completed, from beginning to
526 // end. Hence, we always want to finish up the current cycle
527 // and start a new one. That means:
528 //
529 // 1. In sweep termination, mark, or mark termination of cycle
530 // N, wait until mark termination N completes and transitions
531 // to sweep N.
532 //
533 // 2. In sweep N, help with sweep N.
534 //
535 // At this point we can begin a full cycle N+1.
536 //
537 // 3. Trigger cycle N+1 by starting sweep termination N+1.
538 //
539 // 4. Wait for mark termination N+1 to complete.
540 //
541 // 5. Help with sweep N+1 until it's done.
542 //
543 // This all has to be written to deal with the fact that the
544 // GC may move ahead on its own. For example, when we block
545 // until mark termination N, we may wake up in cycle N+2.
546
547 // Wait until the current sweep termination, mark, and mark
548 // termination complete.
549 n := work.cycles.Load()
550 gcWaitOnMark(n)
551
552 // We're now in sweep N or later. Trigger GC cycle N+1, which
553 // will first finish sweep N if necessary and then enter sweep
554 // termination N+1.
555 gcStart(gcTrigger{kind: gcTriggerCycle, n: n + 1})
556
557 // Wait for mark termination N+1 to complete.
558 gcWaitOnMark(n + 1)
559
560 // Finish sweep N+1 before returning. We do this both to
561 // complete the cycle and because runtime.GC() is often used
562 // as part of tests and benchmarks to get the system into a
563 // relatively stable and isolated state.
564 for work.cycles.Load() == n+1 && sweepone() != ^uintptr(0) {
565 Gosched()
566 }
567
568 // Callers may assume that the heap profile reflects the
569 // just-completed cycle when this returns (historically this
570 // happened because this was a STW GC), but right now the
571 // profile still reflects mark termination N, not N+1.
572 //
573 // As soon as all of the sweep frees from cycle N+1 are done,
574 // we can go ahead and publish the heap profile.
575 //
576 // First, wait for sweeping to finish. (We know there are no
577 // more spans on the sweep queue, but we may be concurrently
578 // sweeping spans, so we have to wait.)
579 for work.cycles.Load() == n+1 && !isSweepDone() {
580 Gosched()
581 }
582
583 // Now we're really done with sweeping, so we can publish the
584 // stable heap profile. Only do this if we haven't already hit
585 // another mark termination.
586 mp := acquirem()
587 cycle := work.cycles.Load()
588 if cycle == n+1 || (gcphase == _GCmark && cycle == n+2) {
589 mProf_PostSweep()
590 }
591 releasem(mp)
592 }
593
594 // goroutineLeakGC runs a GC cycle that performs goroutine leak detection.
595 //
596 //go:linkname goroutineLeakGC runtime/pprof.runtime_goroutineLeakGC
597 func goroutineLeakGC() {
598 // Set the pending flag to true, instructing the next GC cycle to
599 // perform goroutine leak detection.
600 work.goroutineLeak.pending.Store(true)
601
602 // Spin GC cycles until the pending flag is unset.
603 // This ensures that goroutineLeakGC waits for a GC cycle that
604 // actually performs goroutine leak detection.
605 //
606 // This is needed in case multiple concurrent calls to GC
607 // are simultaneously fired by the system, wherein some
608 // of them are dropped.
609 //
610 // In the vast majority of cases, only one loop iteration is needed;
611 // however, multiple concurrent calls to goroutineLeakGC could lead to
612 // the execution of additional GC cycles.
613 //
614 // Examples:
615 //
616 // pending? | G1 | G2
617 // ---------|-------------------------|-----------------------
618 // - | goroutineLeakGC() | goroutineLeakGC()
619 // - | pending.Store(true) | .
620 // X | for pending.Load() | .
621 // X | GC() | .
622 // X | > gcStart() | .
623 // X | pending.Store(false) | .
624 // ...
625 // - | > gcMarkDone() | .
626 // - | . | pending.Store(true)
627 // ...
628 // X | > gcMarkTermination() | .
629 // X | ...
630 // X | < GC returns | .
631 // X | for pending.Load | .
632 // X | GC() | .
633 // X | . | for pending.Load()
634 // X | . | GC()
635 // ...
636 // The first to pick up the pending flag will start a
637 // leak detection cycle.
638 for work.goroutineLeak.pending.Load() {
639 GC()
640 }
641 }
642
643 // gcWaitOnMark blocks until GC finishes the Nth mark phase. If GC has
644 // already completed this mark phase, it returns immediately.
645 func gcWaitOnMark(n uint32) {
646 for {
647 // Disable phase transitions.
648 lock(&work.sweepWaiters.lock)
649 nMarks := work.cycles.Load()
650 if gcphase != _GCmark {
651 // We've already completed this cycle's mark.
652 nMarks++
653 }
654 if nMarks > n {
655 // We're done.
656 unlock(&work.sweepWaiters.lock)
657 return
658 }
659
660 // Wait until sweep termination, mark, and mark
661 // termination of cycle N complete.
662 work.sweepWaiters.list.push(getg())
663 goparkunlock(&work.sweepWaiters.lock, waitReasonWaitForGCCycle, traceBlockUntilGCEnds, 1)
664 }
665 }
666
667 // gcMode indicates how concurrent a GC cycle should be.
668 type gcMode int
669
670 const (
671 gcBackgroundMode gcMode = iota // concurrent GC and sweep
672 gcForceMode // stop-the-world GC now, concurrent sweep
673 gcForceBlockMode // stop-the-world GC now and STW sweep (forced by user)
674 )
675
676 // A gcTrigger is a predicate for starting a GC cycle. Specifically,
677 // it is an exit condition for the _GCoff phase.
678 type gcTrigger struct {
679 kind gcTriggerKind
680 now int64 // gcTriggerTime: current time
681 n uint32 // gcTriggerCycle: cycle number to start
682 }
683
684 type gcTriggerKind int
685
686 const (
687 // gcTriggerHeap indicates that a cycle should be started when
688 // the heap size reaches the trigger heap size computed by the
689 // controller.
690 gcTriggerHeap gcTriggerKind = iota
691
692 // gcTriggerTime indicates that a cycle should be started when
693 // it's been more than forcegcperiod nanoseconds since the
694 // previous GC cycle.
695 gcTriggerTime
696
697 // gcTriggerCycle indicates that a cycle should be started if
698 // we have not yet started cycle number gcTrigger.n (relative
699 // to work.cycles).
700 gcTriggerCycle
701 )
702
703 // test reports whether the trigger condition is satisfied, meaning
704 // that the exit condition for the _GCoff phase has been met. The exit
705 // condition should be tested when allocating.
706 func (t gcTrigger) test() bool {
707 if !memstats.enablegc || panicking.Load() != 0 || gcphase != _GCoff {
708 return false
709 }
710 switch t.kind {
711 case gcTriggerHeap:
712 trigger, _ := gcController.trigger()
713 return gcController.heapLive.Load() >= trigger
714 case gcTriggerTime:
715 if gcController.gcPercent.Load() < 0 {
716 return false
717 }
718 lastgc := int64(atomic.Load64(&memstats.last_gc_nanotime))
719 return lastgc != 0 && t.now-lastgc > forcegcperiod
720 case gcTriggerCycle:
721 // t.n > work.cycles, but accounting for wraparound.
722 return int32(t.n-work.cycles.Load()) > 0
723 }
724 return true
725 }
726
727 // gcStart starts the GC. It transitions from _GCoff to _GCmark (if
728 // debug.gcstoptheworld == 0) or performs all of GC (if
729 // debug.gcstoptheworld != 0).
730 //
731 // This may return without performing this transition in some cases,
732 // such as when called on a system stack or with locks held.
733 func gcStart(trigger gcTrigger) {
734 // Since this is called from malloc and malloc is called in
735 // the guts of a number of libraries that might be holding
736 // locks, don't attempt to start GC in non-preemptible or
737 // potentially unstable situations.
738 mp := acquirem()
739 if gp := getg(); gp == mp.g0 || mp.locks > 1 || mp.preemptoff != "" {
740 releasem(mp)
741 return
742 }
743 releasem(mp)
744 mp = nil
745
746 if gp := getg(); gp.bubble != nil {
747 // Disassociate the G from its synctest bubble while allocating.
748 // This is less elegant than incrementing the group's active count,
749 // but avoids any contamination between GC and synctest.
750 bubble := gp.bubble
751 gp.bubble = nil
752 defer func() {
753 gp.bubble = bubble
754 }()
755 }
756
757 // Pick up the remaining unswept/not being swept spans concurrently
758 //
759 // This shouldn't happen if we're being invoked in background
760 // mode since proportional sweep should have just finished
761 // sweeping everything, but rounding errors, etc, may leave a
762 // few spans unswept. In forced mode, this is necessary since
763 // GC can be forced at any point in the sweeping cycle.
764 //
765 // We check the transition condition continuously here in case
766 // this G gets delayed in to the next GC cycle.
767 for trigger.test() && sweepone() != ^uintptr(0) {
768 }
769
770 // Perform GC initialization and the sweep termination
771 // transition.
772 semacquire(&work.startSema)
773 // Re-check transition condition under transition lock.
774 if !trigger.test() {
775 semrelease(&work.startSema)
776 return
777 }
778
779 // In gcstoptheworld debug mode, upgrade the mode accordingly.
780 // We do this after re-checking the transition condition so
781 // that multiple goroutines that detect the heap trigger don't
782 // start multiple STW GCs.
783 mode := gcBackgroundMode
784 if debug.gcstoptheworld == 1 {
785 mode = gcForceMode
786 } else if debug.gcstoptheworld == 2 {
787 mode = gcForceBlockMode
788 }
789
790 // Ok, we're doing it! Stop everybody else
791 semacquire(&gcsema)
792 semacquire(&worldsema)
793
794 // For stats, check if this GC was forced by the user.
795 // Update it under gcsema to avoid gctrace getting wrong values.
796 work.userForced = trigger.kind == gcTriggerCycle
797
798 trace := traceAcquire()
799 if trace.ok() {
800 trace.GCStart()
801 traceRelease(trace)
802 }
803
804 // Check and setup per-P state.
805 for _, p := range allp {
806 // Check that all Ps have finished deferred mcache flushes.
807 if fg := p.mcache.flushGen.Load(); fg != mheap_.sweepgen {
808 println("runtime: p", p.id, "flushGen", fg, "!= sweepgen", mheap_.sweepgen)
809 throw("p mcache not flushed")
810 }
811 // Initialize ptrBuf if necessary.
812 if goexperiment.GreenTeaGC && p.gcw.ptrBuf == nil {
813 p.gcw.ptrBuf = (*[gc.PageSize / goarch.PtrSize]uintptr)(persistentalloc(gc.PageSize, goarch.PtrSize, &memstats.gcMiscSys))
814 }
815 }
816
817 gcBgMarkStartWorkers()
818
819 systemstack(gcResetMarkState)
820
821 work.stwprocs, work.maxprocs = gomaxprocs, gomaxprocs
822 if work.stwprocs > numCPUStartup {
823 // This is used to compute CPU time of the STW phases, so it
824 // can't be more than the CPU count, even if GOMAXPROCS is.
825 work.stwprocs = numCPUStartup
826 }
827 work.heap0 = gcController.heapLive.Load()
828 work.pauseNS = 0
829 work.mode = mode
830
831 now := nanotime()
832 work.tSweepTerm = now
833 var stw worldStop
834 systemstack(func() {
835 stw = stopTheWorldWithSema(stwGCSweepTerm)
836 })
837
838 // Accumulate fine-grained stopping time.
839 work.cpuStats.accumulateGCPauseTime(stw.stoppingCPUTime, 1)
840
841 if goexperiment.RuntimeSecret {
842 // The world is stopped. Every M is either parked
843 // or in a syscall, or running some non-go code which can't run in secret mode.
844 // To get to a parked or a syscall state
845 // they have to transition through a point where we erase any
846 // confidential information in the registers. Making them
847 // handle a signal now would clobber the signal stack
848 // with non-confidential information.
849 //
850 // TODO(dmo): this is linear with respect to the number of Ms.
851 // Investigate just how long this takes and whether we can somehow
852 // loop over just the Ms that have secret info on their signal stack,
853 // or cooperatively have the Ms send signals to themselves just
854 // after they erase their registers, but before they enter a syscall
855 for mp := allm; mp != nil; mp = mp.alllink {
856 // even through the world is stopped, the kernel can still
857 // invoke our signal handlers. No confidential information can be spilled
858 // (because it's been erased by this time), but we can avoid
859 // sending additional signals by atomically inspecting this variable
860 if atomic.Xchg(&mp.signalSecret, 0) != 0 {
861 noopSignal(mp)
862 }
863 // TODO: syncronize with the signal handler to ensure that the signal
864 // was actually delivered.
865 }
866 }
867
868 // Finish sweep before we start concurrent scan.
869 systemstack(func() {
870 finishsweep_m()
871 })
872
873 // clearpools before we start the GC. If we wait the memory will not be
874 // reclaimed until the next GC cycle.
875 clearpools()
876
877 work.cycles.Add(1)
878
879 // Assists and workers can start the moment we start
880 // the world.
881 gcController.startCycle(now, int(gomaxprocs), trigger)
882
883 // Notify the CPU limiter that assists may begin.
884 gcCPULimiter.startGCTransition(true, now)
885
886 // In STW mode, disable scheduling of user Gs. This may also
887 // disable scheduling of this goroutine, so it may block as
888 // soon as we start the world again.
889 if mode != gcBackgroundMode {
890 schedEnableUser(false)
891 }
892
893 // If goroutine leak detection is pending, enable it for this GC cycle.
894 if work.goroutineLeak.pending.Load() {
895 work.goroutineLeak.enabled = true
896 work.goroutineLeak.pending.Store(false)
897 // Set all sync objects of blocked goroutines as untraceable
898 // by the GC. Only set as traceable at the end of the GC cycle.
899 setSyncObjectsUntraceable()
900 }
901
902 // Enter concurrent mark phase and enable
903 // write barriers.
904 //
905 // Because the world is stopped, all Ps will
906 // observe that write barriers are enabled by
907 // the time we start the world and begin
908 // scanning.
909 //
910 // Write barriers must be enabled before assists are
911 // enabled because they must be enabled before
912 // any non-leaf heap objects are marked. Since
913 // allocations are blocked until assists can
914 // happen, we want to enable assists as early as
915 // possible.
916 setGCPhase(_GCmark)
917
918 gcBgMarkPrepare() // Must happen before assists are enabled.
919 gcPrepareMarkRoots()
920
921 // Mark all active tinyalloc blocks. Since we're
922 // allocating from these, they need to be black like
923 // other allocations. The alternative is to blacken
924 // the tiny block on every allocation from it, which
925 // would slow down the tiny allocator.
926 gcMarkTinyAllocs()
927
928 // At this point all Ps have enabled the write
929 // barrier, thus maintaining the no white to
930 // black invariant. Enable mutator assists to
931 // put back-pressure on fast allocating
932 // mutators.
933 atomic.Store(&gcBlackenEnabled, 1)
934
935 // In STW mode, we could block the instant systemstack
936 // returns, so make sure we're not preemptible.
937 mp = acquirem()
938
939 // Update the CPU stats pause time.
940 //
941 // Use maxprocs instead of stwprocs here because the total time
942 // computed in the CPU stats is based on maxprocs, and we want them
943 // to be comparable.
944 work.cpuStats.accumulateGCPauseTime(nanotime()-stw.finishedStopping, work.maxprocs)
945
946 // Concurrent mark.
947 systemstack(func() {
948 now = startTheWorldWithSema(0, stw)
949 work.pauseNS += now - stw.startedStopping
950 work.tMark = now
951
952 // Release the CPU limiter.
953 gcCPULimiter.finishGCTransition(now)
954 })
955
956 // Release the world sema before Gosched() in STW mode
957 // because we will need to reacquire it later but before
958 // this goroutine becomes runnable again, and we could
959 // self-deadlock otherwise.
960 semrelease(&worldsema)
961 releasem(mp)
962
963 // Make sure we block instead of returning to user code
964 // in STW mode.
965 if mode != gcBackgroundMode {
966 Gosched()
967 }
968
969 semrelease(&work.startSema)
970 }
971
972 // gcMarkDoneFlushed counts the number of P's with flushed work.
973 //
974 // Ideally this would be a captured local in gcMarkDone, but forEachP
975 // escapes its callback closure, so it can't capture anything.
976 //
977 // This is protected by markDoneSema.
978 var gcMarkDoneFlushed uint32
979
980 // gcDebugMarkDone contains fields used to debug/test mark termination.
981 var gcDebugMarkDone struct {
982 // spinAfterRaggedBarrier forces gcMarkDone to spin after it executes
983 // the ragged barrier.
984 spinAfterRaggedBarrier atomic.Bool
985
986 // restartedDueTo27993 indicates that we restarted mark termination
987 // due to the bug described in issue #27993.
988 //
989 // Protected by worldsema.
990 restartedDueTo27993 bool
991 }
992
993 // gcMarkDone transitions the GC from mark to mark termination if all
994 // reachable objects have been marked (that is, there are no grey
995 // objects and can be no more in the future). Otherwise, it flushes
996 // all local work to the global queues where it can be discovered by
997 // other workers.
998 //
999 // All goroutines performing GC work must call gcBeginWork to signal
1000 // that they're executing GC work. They must call gcEndWork when done.
1001 // This should be called when all local mark work has been drained and
1002 // there are no remaining workers. Specifically, when gcEndWork returns
1003 // true.
1004 //
1005 // The calling context must be preemptible.
1006 //
1007 // Flushing local work is important because idle Ps may have local
1008 // work queued. This is the only way to make that work visible and
1009 // drive GC to completion.
1010 //
1011 // It is explicitly okay to have write barriers in this function. If
1012 // it does transition to mark termination, then all reachable objects
1013 // have been marked, so the write barrier cannot shade any more
1014 // objects.
1015 func gcMarkDone() {
1016 // Ensure only one thread is running the ragged barrier at a
1017 // time.
1018 semacquire(&work.markDoneSema)
1019
1020 top:
1021 // Re-check transition condition under transition lock.
1022 //
1023 // It's critical that this checks the global work queues are
1024 // empty before performing the ragged barrier. Otherwise,
1025 // there could be global work that a P could take after the P
1026 // has passed the ragged barrier.
1027 if !(gcphase == _GCmark && gcIsMarkDone()) {
1028 semrelease(&work.markDoneSema)
1029 return
1030 }
1031
1032 // forEachP needs worldsema to execute, and we'll need it to
1033 // stop the world later, so acquire worldsema now.
1034 semacquire(&worldsema)
1035
1036 // Prevent weak->strong conversions from generating additional
1037 // GC work. forEachP will guarantee that it is observed globally.
1038 work.strongFromWeak.block = true
1039
1040 // Flush all local buffers and collect flushedWork flags.
1041 gcMarkDoneFlushed = 0
1042 forEachP(waitReasonGCMarkTermination, func(pp *p) {
1043 // Flush the write barrier buffer, since this may add
1044 // work to the gcWork.
1045 wbBufFlush1(pp)
1046
1047 // Flush the gcWork, since this may create global work
1048 // and set the flushedWork flag.
1049 //
1050 // TODO(austin): Break up these workbufs to
1051 // better distribute work.
1052 pp.gcw.dispose()
1053
1054 // Collect the flushedWork flag.
1055 if pp.gcw.flushedWork {
1056 atomic.Xadd(&gcMarkDoneFlushed, 1)
1057 pp.gcw.flushedWork = false
1058 }
1059 })
1060
1061 if gcMarkDoneFlushed != 0 {
1062 // More grey objects were discovered since the
1063 // previous termination check, so there may be more
1064 // work to do. Keep going. It's possible the
1065 // transition condition became true again during the
1066 // ragged barrier, so re-check it.
1067 semrelease(&worldsema)
1068 goto top
1069 }
1070
1071 // For debugging/testing.
1072 for gcDebugMarkDone.spinAfterRaggedBarrier.Load() {
1073 }
1074
1075 // There was no global work, no local work, and no Ps
1076 // communicated work since we took markDoneSema. Therefore
1077 // there are no grey objects and no more objects can be
1078 // shaded. Transition to mark termination.
1079 now := nanotime()
1080 work.tMarkTerm = now
1081 getg().m.preemptoff = "gcing"
1082 var stw worldStop
1083 systemstack(func() {
1084 stw = stopTheWorldWithSema(stwGCMarkTerm)
1085 })
1086 // The gcphase is _GCmark, it will transition to _GCmarktermination
1087 // below. The important thing is that the wb remains active until
1088 // all marking is complete. This includes writes made by the GC.
1089
1090 // Accumulate fine-grained stopping time.
1091 work.cpuStats.accumulateGCPauseTime(stw.stoppingCPUTime, 1)
1092
1093 // There is sometimes work left over when we enter mark termination due
1094 // to write barriers performed after the completion barrier above.
1095 // Detect this and resume concurrent mark. This is obviously
1096 // unfortunate.
1097 //
1098 // See issue #27993 for details.
1099 //
1100 // Switch to the system stack to call wbBufFlush1, though in this case
1101 // it doesn't matter because we're non-preemptible anyway.
1102 restart := false
1103 systemstack(func() {
1104 for _, p := range allp {
1105 wbBufFlush1(p)
1106 if !p.gcw.empty() {
1107 restart = true
1108 break
1109 }
1110 }
1111 })
1112
1113 // Check whether we need to resume the marking phase because of issue #27993
1114 // or because of goroutine leak detection.
1115 if restart || (work.goroutineLeak.enabled && !work.goroutineLeak.done) {
1116 if restart {
1117 // Restart because of issue #27993.
1118 gcDebugMarkDone.restartedDueTo27993 = true
1119 } else {
1120 // Marking has reached a fixed-point. Attempt to detect goroutine leaks.
1121 //
1122 // If the returned value is true, then detection already concluded for this cycle.
1123 // Otherwise, more runnable goroutines were discovered, requiring additional mark work.
1124 work.goroutineLeak.done = findGoroutineLeaks()
1125 }
1126
1127 getg().m.preemptoff = ""
1128 systemstack(func() {
1129 // Accumulate the time we were stopped before we had to start again.
1130 work.cpuStats.accumulateGCPauseTime(nanotime()-stw.finishedStopping, work.maxprocs)
1131
1132 // Start the world again.
1133 now := startTheWorldWithSema(0, stw)
1134 work.pauseNS += now - stw.startedStopping
1135 })
1136 semrelease(&worldsema)
1137 goto top
1138 }
1139
1140 gcComputeStartingStackSize()
1141
1142 // Disable assists and background workers. We must do
1143 // this before waking blocked assists.
1144 atomic.Store(&gcBlackenEnabled, 0)
1145
1146 // Notify the CPU limiter that GC assists will now cease.
1147 gcCPULimiter.startGCTransition(false, now)
1148
1149 // Wake all blocked assists. These will run when we
1150 // start the world again.
1151 gcWakeAllAssists()
1152
1153 // Wake all blocked weak->strong conversions. These will run
1154 // when we start the world again.
1155 work.strongFromWeak.block = false
1156 gcWakeAllStrongFromWeak()
1157
1158 // Likewise, release the transition lock. Blocked
1159 // workers and assists will run when we start the
1160 // world again.
1161 semrelease(&work.markDoneSema)
1162
1163 // In STW mode, re-enable user goroutines. These will be
1164 // queued to run after we start the world.
1165 schedEnableUser(true)
1166
1167 // endCycle depends on all gcWork cache stats being flushed.
1168 // The termination algorithm above ensured that up to
1169 // allocations since the ragged barrier.
1170 gcController.endCycle(now, int(gomaxprocs), work.userForced)
1171
1172 // Perform mark termination. This will restart the world.
1173 gcMarkTermination(stw)
1174 }
1175
1176 // isMaybeRunnable checks whether a goroutine may still be semantically runnable.
1177 // For goroutines which are semantically runnable, this will eventually return true
1178 // as the GC marking phase progresses. It returns false for leaked goroutines, or for
1179 // goroutines which are not yet computed as possibly runnable by the GC.
1180 func (gp *g) isMaybeRunnable() bool {
1181 // Check whether the goroutine is actually in a waiting state first.
1182 if readgstatus(gp) != _Gwaiting {
1183 // If the goroutine is not waiting, then clearly it is maybe runnable.
1184 return true
1185 }
1186
1187 switch gp.waitreason {
1188 case waitReasonSelectNoCases,
1189 waitReasonChanSendNilChan,
1190 waitReasonChanReceiveNilChan:
1191 // Select with no cases or communicating on nil channels
1192 // make goroutines unrunnable by definition.
1193 return false
1194 case waitReasonChanReceive,
1195 waitReasonSelect,
1196 waitReasonChanSend:
1197 // Cycle all through all *sudog to check whether
1198 // the goroutine is waiting on a marked channel.
1199 for sg := gp.waiting; sg != nil; sg = sg.waitlink {
1200 if isMarkedOrNotInHeap(unsafe.Pointer(sg.c.get())) {
1201 return true
1202 }
1203 }
1204 return false
1205 case waitReasonSyncCondWait,
1206 waitReasonSyncWaitGroupWait,
1207 waitReasonSyncMutexLock,
1208 waitReasonSyncRWMutexLock,
1209 waitReasonSyncRWMutexRLock:
1210 // If waiting on mutexes, wait groups, or condition variables,
1211 // check if the synchronization primitive attached to the sudog is marked.
1212 if gp.waiting != nil {
1213 return isMarkedOrNotInHeap(gp.waiting.elem.get())
1214 }
1215 }
1216 return true
1217 }
1218
1219 // findMaybeRunnableGoroutines checks to see if more blocked but maybe-runnable goroutines exist.
1220 // If so, it adds them into root set and increments work.markrootJobs accordingly.
1221 // Returns true if we need to run another phase of markroots; returns false otherwise.
1222 func findMaybeRunnableGoroutines() (moreWork bool) {
1223 oldRootJobs := work.markrootJobs.Load()
1224
1225 // To begin with we have a set of unchecked stackRoots between
1226 // vIndex and ivIndex. During the loop, anything < vIndex should be
1227 // valid stackRoots and anything >= ivIndex should be invalid stackRoots.
1228 // The loop terminates when the two indices meet.
1229 var vIndex, ivIndex int = work.nMaybeRunnableStackRoots, work.nStackRoots
1230 // Reorder goroutine list
1231 for vIndex < ivIndex {
1232 if work.stackRoots[vIndex].isMaybeRunnable() {
1233 vIndex = vIndex + 1
1234 continue
1235 }
1236 for ivIndex = ivIndex - 1; ivIndex != vIndex; ivIndex = ivIndex - 1 {
1237 if gp := work.stackRoots[ivIndex]; gp.isMaybeRunnable() {
1238 work.stackRoots[ivIndex] = work.stackRoots[vIndex]
1239 work.stackRoots[vIndex] = gp
1240 vIndex = vIndex + 1
1241 break
1242 }
1243 }
1244 }
1245
1246 newRootJobs := work.baseStacks + uint32(vIndex)
1247 if newRootJobs > oldRootJobs {
1248 work.nMaybeRunnableStackRoots = vIndex
1249 work.markrootJobs.Store(newRootJobs)
1250 }
1251 return newRootJobs > oldRootJobs
1252 }
1253
1254 // setSyncObjectsUntraceable scans allgs and sets the elem and c fields of all sudogs to
1255 // an untrackable pointer. This prevents the GC from marking these objects as live in memory
1256 // by following these pointers when runnning deadlock detection.
1257 func setSyncObjectsUntraceable() {
1258 assertWorldStopped()
1259
1260 forEachGRace(func(gp *g) {
1261 // Set as untraceable all synchronization objects of goroutines
1262 // blocked at concurrency operations that could leak.
1263 switch {
1264 case gp.waitreason.isSyncWait():
1265 // Synchronization primitives are reachable from the *sudog via
1266 // via the elem field.
1267 for sg := gp.waiting; sg != nil; sg = sg.waitlink {
1268 sg.elem.setUntraceable()
1269 }
1270 case gp.waitreason.isChanWait():
1271 // Channels and select statements are reachable from the *sudog via the c field.
1272 for sg := gp.waiting; sg != nil; sg = sg.waitlink {
1273 sg.c.setUntraceable()
1274 }
1275 }
1276 })
1277 }
1278
1279 // gcRestoreSyncObjects restores the elem and c fields of all sudogs to their original values.
1280 // Should be invoked after the goroutine leak detection phase.
1281 func gcRestoreSyncObjects() {
1282 assertWorldStopped()
1283
1284 forEachGRace(func(gp *g) {
1285 for sg := gp.waiting; sg != nil; sg = sg.waitlink {
1286 sg.elem.setTraceable()
1287 sg.c.setTraceable()
1288 }
1289 })
1290 }
1291
1292 // findGoroutineLeaks scans the remaining stackRoots and marks any which are
1293 // blocked over exclusively unreachable concurrency primitives as leaked (deadlocked).
1294 // Returns true if the goroutine leak check was performed (or unnecessary).
1295 // Returns false if the GC cycle has not yet computed all maybe-runnable goroutines.
1296 func findGoroutineLeaks() bool {
1297 assertWorldStopped()
1298
1299 // Report goroutine leaks and mark them unreachable, and resume marking
1300 // we still need to mark these unreachable *g structs as they
1301 // get reused, but their stack won't get scanned
1302 if work.nMaybeRunnableStackRoots == work.nStackRoots {
1303 // nMaybeRunnableStackRoots == nStackRoots means that all goroutines are marked.
1304 return true
1305 }
1306
1307 // Check whether any more maybe-runnable goroutines can be found by the GC.
1308 if findMaybeRunnableGoroutines() {
1309 // We found more work, so we need to resume the marking phase.
1310 return false
1311 }
1312
1313 // For the remaining goroutines, mark them as unreachable and leaked.
1314 work.goroutineLeak.count = work.nStackRoots - work.nMaybeRunnableStackRoots
1315
1316 for i := work.nMaybeRunnableStackRoots; i < work.nStackRoots; i++ {
1317 gp := work.stackRoots[i]
1318 casgstatus(gp, _Gwaiting, _Gleaked)
1319
1320 // Add the primitives causing the goroutine leaks
1321 // to the GC work queue, to ensure they are marked.
1322 //
1323 // NOTE(vsaioc): these primitives should also be reachable
1324 // from the goroutine's stack, but let's play it safe.
1325 switch {
1326 case gp.waitreason.isChanWait():
1327 for sg := gp.waiting; sg != nil; sg = sg.waitlink {
1328 shade(sg.c.uintptr())
1329 }
1330 case gp.waitreason.isSyncWait():
1331 for sg := gp.waiting; sg != nil; sg = sg.waitlink {
1332 shade(sg.elem.uintptr())
1333 }
1334 }
1335 }
1336 // Put the remaining roots as ready for marking and drain them.
1337 work.markrootJobs.Add(int32(work.nStackRoots - work.nMaybeRunnableStackRoots))
1338 work.nMaybeRunnableStackRoots = work.nStackRoots
1339 return true
1340 }
1341
1342 // World must be stopped and mark assists and background workers must be
1343 // disabled.
1344 func gcMarkTermination(stw worldStop) {
1345 // Start marktermination (write barrier remains enabled for now).
1346 setGCPhase(_GCmarktermination)
1347
1348 work.heap1 = gcController.heapLive.Load()
1349 startTime := nanotime()
1350
1351 mp := acquirem()
1352 mp.preemptoff = "gcing"
1353 mp.traceback = 2
1354 curgp := mp.curg
1355 // N.B. The execution tracer is not aware of this status
1356 // transition and handles it specially based on the
1357 // wait reason.
1358 casGToWaitingForSuspendG(curgp, _Grunning, waitReasonGarbageCollection)
1359
1360 // Run gc on the g0 stack. We do this so that the g stack
1361 // we're currently running on will no longer change. Cuts
1362 // the root set down a bit (g0 stacks are not scanned, and
1363 // we don't need to scan gc's internal state). We also
1364 // need to switch to g0 so we can shrink the stack.
1365 systemstack(func() {
1366 gcMark(startTime)
1367 // Must return immediately.
1368 // The outer function's stack may have moved
1369 // during gcMark (it shrinks stacks, including the
1370 // outer function's stack), so we must not refer
1371 // to any of its variables. Return back to the
1372 // non-system stack to pick up the new addresses
1373 // before continuing.
1374 })
1375
1376 var stwSwept bool
1377 systemstack(func() {
1378 work.heap2 = work.bytesMarked
1379 if debug.gccheckmark > 0 {
1380 runCheckmark(func(_ *gcWork) { gcPrepareMarkRoots() })
1381 }
1382 if debug.checkfinalizers > 0 {
1383 checkFinalizersAndCleanups()
1384 }
1385
1386 // marking is complete so we can turn the write barrier off
1387 setGCPhase(_GCoff)
1388 stwSwept = gcSweep(work.mode)
1389 })
1390
1391 mp.traceback = 0
1392 casgstatus(curgp, _Gwaiting, _Grunning)
1393
1394 trace := traceAcquire()
1395 if trace.ok() {
1396 trace.GCDone()
1397 traceRelease(trace)
1398 }
1399
1400 // all done
1401 mp.preemptoff = ""
1402
1403 if gcphase != _GCoff {
1404 throw("gc done but gcphase != _GCoff")
1405 }
1406
1407 // Record heapInUse for scavenger.
1408 memstats.lastHeapInUse = gcController.heapInUse.load()
1409
1410 // Update GC trigger and pacing, as well as downstream consumers
1411 // of this pacing information, for the next cycle.
1412 systemstack(gcControllerCommit)
1413
1414 // Update timing memstats
1415 now := nanotime()
1416 sec, nsec, _ := time_now()
1417 unixNow := sec*1e9 + int64(nsec)
1418 work.pauseNS += now - stw.startedStopping
1419 work.tEnd = now
1420 atomic.Store64(&memstats.last_gc_unix, uint64(unixNow)) // must be Unix time to make sense to user
1421 atomic.Store64(&memstats.last_gc_nanotime, uint64(now)) // monotonic time for us
1422 memstats.pause_ns[memstats.numgc%uint32(len(memstats.pause_ns))] = uint64(work.pauseNS)
1423 memstats.pause_end[memstats.numgc%uint32(len(memstats.pause_end))] = uint64(unixNow)
1424 memstats.pause_total_ns += uint64(work.pauseNS)
1425
1426 // Accumulate CPU stats.
1427 //
1428 // Use maxprocs instead of stwprocs for GC pause time because the total time
1429 // computed in the CPU stats is based on maxprocs, and we want them to be
1430 // comparable.
1431 //
1432 // Pass gcMarkPhase=true to accumulate so we can get all the latest GC CPU stats
1433 // in there too.
1434 work.cpuStats.accumulateGCPauseTime(now-stw.finishedStopping, work.maxprocs)
1435 work.cpuStats.accumulate(now, true)
1436
1437 // Compute overall GC CPU utilization.
1438 // Omit idle marking time from the overall utilization here since it's "free".
1439 memstats.gc_cpu_fraction = float64(work.cpuStats.GCTotalTime-work.cpuStats.GCIdleTime) / float64(work.cpuStats.TotalTime)
1440
1441 // Reset assist time and background time stats.
1442 //
1443 // Do this now, instead of at the start of the next GC cycle, because
1444 // these two may keep accumulating even if the GC is not active.
1445 scavenge.assistTime.Store(0)
1446 scavenge.backgroundTime.Store(0)
1447
1448 // Reset idle time stat.
1449 sched.idleTime.Store(0)
1450
1451 if work.userForced {
1452 memstats.numforcedgc++
1453 }
1454
1455 // Bump GC cycle count and wake goroutines waiting on sweep.
1456 lock(&work.sweepWaiters.lock)
1457 memstats.numgc++
1458 injectglist(&work.sweepWaiters.list)
1459 unlock(&work.sweepWaiters.lock)
1460
1461 // Increment the scavenge generation now.
1462 //
1463 // This moment represents peak heap in use because we're
1464 // about to start sweeping.
1465 mheap_.pages.scav.index.nextGen()
1466
1467 // Release the CPU limiter.
1468 gcCPULimiter.finishGCTransition(now)
1469
1470 // Finish the current heap profiling cycle and start a new
1471 // heap profiling cycle. We do this before starting the world
1472 // so events don't leak into the wrong cycle.
1473 mProf_NextCycle()
1474
1475 // There may be stale spans in mcaches that need to be swept.
1476 // Those aren't tracked in any sweep lists, so we need to
1477 // count them against sweep completion until we ensure all
1478 // those spans have been forced out.
1479 //
1480 // If gcSweep fully swept the heap (for example if the sweep
1481 // is not concurrent due to a GODEBUG setting), then we expect
1482 // the sweepLocker to be invalid, since sweeping is done.
1483 //
1484 // N.B. Below we might duplicate some work from gcSweep; this is
1485 // fine as all that work is idempotent within a GC cycle, and
1486 // we're still holding worldsema so a new cycle can't start.
1487 sl := sweep.active.begin()
1488 if !stwSwept && !sl.valid {
1489 throw("failed to set sweep barrier")
1490 } else if stwSwept && sl.valid {
1491 throw("non-concurrent sweep failed to drain all sweep queues")
1492 }
1493
1494 if work.goroutineLeak.enabled {
1495 // Restore the elem and c fields of all sudogs to their original values.
1496 gcRestoreSyncObjects()
1497 }
1498
1499 var goroutineLeakDone bool
1500 systemstack(func() {
1501 // Pull the GC out of goroutine leak detection mode.
1502 work.goroutineLeak.enabled = false
1503 goroutineLeakDone = work.goroutineLeak.done
1504 work.goroutineLeak.done = false
1505
1506 // The memstats updated above must be updated with the world
1507 // stopped to ensure consistency of some values, such as
1508 // sched.idleTime and sched.totaltime. memstats also include
1509 // the pause time (work,pauseNS), forcing computation of the
1510 // total pause time before the pause actually ends.
1511 //
1512 // Here we reuse the same now for start the world so that the
1513 // time added to /sched/pauses/total/gc:seconds will be
1514 // consistent with the value in memstats.
1515 startTheWorldWithSema(now, stw)
1516 })
1517
1518 // Flush the heap profile so we can start a new cycle next GC.
1519 // This is relatively expensive, so we don't do it with the
1520 // world stopped.
1521 mProf_Flush()
1522
1523 // Prepare workbufs for freeing by the sweeper. We do this
1524 // asynchronously because it can take non-trivial time.
1525 prepareFreeWorkbufs()
1526
1527 // Free stack spans. This must be done between GC cycles.
1528 systemstack(freeStackSpans)
1529
1530 // Ensure all mcaches are flushed. Each P will flush its own
1531 // mcache before allocating, but idle Ps may not. Since this
1532 // is necessary to sweep all spans, we need to ensure all
1533 // mcaches are flushed before we start the next GC cycle.
1534 //
1535 // While we're here, flush the page cache for idle Ps to avoid
1536 // having pages get stuck on them. These pages are hidden from
1537 // the scavenger, so in small idle heaps a significant amount
1538 // of additional memory might be held onto.
1539 //
1540 // Also, flush the pinner cache, to avoid leaking that memory
1541 // indefinitely.
1542 if debug.gctrace > 1 {
1543 clear(memstats.lastScanStats[:])
1544 }
1545 forEachP(waitReasonFlushProcCaches, func(pp *p) {
1546 pp.mcache.prepareForSweep()
1547 if pp.status == _Pidle {
1548 systemstack(func() {
1549 lock(&mheap_.lock)
1550 pp.pcache.flush(&mheap_.pages)
1551 unlock(&mheap_.lock)
1552 })
1553 }
1554 if debug.gctrace > 1 {
1555 pp.gcw.flushScanStats(&memstats.lastScanStats)
1556 }
1557 pp.pinnerCache = nil
1558 })
1559 if sl.valid {
1560 // Now that we've swept stale spans in mcaches, they don't
1561 // count against unswept spans.
1562 //
1563 // Note: this sweepLocker may not be valid if sweeping had
1564 // already completed during the STW. See the corresponding
1565 // begin() call that produced sl.
1566 sweep.active.end(sl)
1567 }
1568
1569 // Print gctrace before dropping worldsema. As soon as we drop
1570 // worldsema another cycle could start and smash the stats
1571 // we're trying to print.
1572 if debug.gctrace > 0 {
1573 util := int(memstats.gc_cpu_fraction * 100)
1574
1575 var sbuf [24]byte
1576 printlock()
1577 print("gc ", memstats.numgc,
1578 " @", string(itoaDiv(sbuf[:], uint64(work.tSweepTerm-runtimeInitTime)/1e6, 3)), "s ",
1579 util, "%")
1580 if goroutineLeakDone {
1581 print(" (checking for goroutine leaks)")
1582 }
1583 print(": ")
1584 prev := work.tSweepTerm
1585 for i, ns := range []int64{work.tMark, work.tMarkTerm, work.tEnd} {
1586 if i != 0 {
1587 print("+")
1588 }
1589 print(string(fmtNSAsMS(sbuf[:], uint64(ns-prev))))
1590 prev = ns
1591 }
1592 print(" ms clock, ")
1593 for i, ns := range []int64{
1594 int64(work.stwprocs) * (work.tMark - work.tSweepTerm),
1595 gcController.assistTime.Load(),
1596 gcController.dedicatedMarkTime.Load() + gcController.fractionalMarkTime.Load(),
1597 gcController.idleMarkTime.Load(),
1598 int64(work.stwprocs) * (work.tEnd - work.tMarkTerm),
1599 } {
1600 if i == 2 || i == 3 {
1601 // Separate mark time components with /.
1602 print("/")
1603 } else if i != 0 {
1604 print("+")
1605 }
1606 print(string(fmtNSAsMS(sbuf[:], uint64(ns))))
1607 }
1608 print(" ms cpu, ",
1609 work.heap0>>20, "->", work.heap1>>20, "->", work.heap2>>20, " MB, ",
1610 gcController.lastHeapGoal>>20, " MB goal, ",
1611 gcController.lastStackScan.Load()>>20, " MB stacks, ",
1612 gcController.globalsScan.Load()>>20, " MB globals, ",
1613 work.maxprocs, " P")
1614 if work.userForced {
1615 print(" (forced)")
1616 }
1617 print("\n")
1618
1619 if debug.gctrace > 1 {
1620 dumpScanStats()
1621 }
1622 printunlock()
1623 }
1624
1625 // Print finalizer/cleanup queue length. Like gctrace, do this before the next GC starts.
1626 // The fact that the next GC might start is not that problematic here, but acts as a convenient
1627 // lock on printing this information (so it cannot overlap with itself from the next GC cycle).
1628 if debug.checkfinalizers > 0 {
1629 fq, fe := finReadQueueStats()
1630 fn := max(int64(fq)-int64(fe), 0)
1631
1632 cq, ce := gcCleanups.readQueueStats()
1633 cn := max(int64(cq)-int64(ce), 0)
1634
1635 println("checkfinalizers: queue:", fn, "finalizers +", cn, "cleanups")
1636 }
1637
1638 // Set any arena chunks that were deferred to fault.
1639 lock(&userArenaState.lock)
1640 faultList := userArenaState.fault
1641 userArenaState.fault = nil
1642 unlock(&userArenaState.lock)
1643 for _, lc := range faultList {
1644 lc.mspan.setUserArenaChunkToFault()
1645 }
1646
1647 // Enable huge pages on some metadata if we cross a heap threshold.
1648 if gcController.heapGoal() > minHeapForMetadataHugePages {
1649 systemstack(func() {
1650 mheap_.enableMetadataHugePages()
1651 })
1652 }
1653
1654 semrelease(&worldsema)
1655 semrelease(&gcsema)
1656 // Careful: another GC cycle may start now.
1657
1658 releasem(mp)
1659 mp = nil
1660
1661 // now that gc is done, kick off finalizer thread if needed
1662 if !concurrentSweep {
1663 // give the queued finalizers, if any, a chance to run
1664 Gosched()
1665 }
1666 }
1667
1668 // gcBgMarkStartWorkers prepares background mark worker goroutines. These
1669 // goroutines will not run until the mark phase, but they must be started while
1670 // the work is not stopped and from a regular G stack. The caller must hold
1671 // worldsema.
1672 func gcBgMarkStartWorkers() {
1673 // Background marking is performed by per-P G's. Ensure that each P has
1674 // a background GC G.
1675 //
1676 // Worker Gs don't exit if gomaxprocs is reduced. If it is raised
1677 // again, we can reuse the old workers; no need to create new workers.
1678 if gcBgMarkWorkerCount >= gomaxprocs {
1679 return
1680 }
1681
1682 // Increment mp.locks when allocating. We are called within gcStart,
1683 // and thus must not trigger another gcStart via an allocation. gcStart
1684 // bails when allocating with locks held, so simulate that for these
1685 // allocations.
1686 //
1687 // TODO(prattmic): cleanup gcStart to use a more explicit "in gcStart"
1688 // check for bailing.
1689 mp := acquirem()
1690 ready := make(chan struct{}, 1)
1691 releasem(mp)
1692
1693 for gcBgMarkWorkerCount < gomaxprocs {
1694 mp := acquirem() // See above, we allocate a closure here.
1695 go gcBgMarkWorker(ready)
1696 releasem(mp)
1697
1698 // N.B. we intentionally wait on each goroutine individually
1699 // rather than starting all in a batch and then waiting once
1700 // afterwards. By running one goroutine at a time, we can take
1701 // advantage of runnext to bounce back and forth between
1702 // workers and this goroutine. In an overloaded application,
1703 // this can reduce GC start latency by prioritizing these
1704 // goroutines rather than waiting on the end of the run queue.
1705 <-ready
1706 // The worker is now guaranteed to be added to the pool before
1707 // its P's next findRunnableGCWorker.
1708
1709 gcBgMarkWorkerCount++
1710 }
1711 }
1712
1713 // gcBgMarkPrepare sets up state for background marking.
1714 // Mutator assists must not yet be enabled.
1715 func gcBgMarkPrepare() {
1716 // Background marking will stop when the work queues are empty
1717 // and there are no more workers (note that, since this is
1718 // concurrent, this may be a transient state, but mark
1719 // termination will clean it up). Between background workers
1720 // and assists, we don't really know how many workers there
1721 // will be, so we pretend to have an arbitrarily large number
1722 // of workers, almost all of which are "waiting". While a
1723 // worker is working it decrements nwait. If nproc == nwait,
1724 // there are no workers.
1725 work.nproc = ^uint32(0)
1726 work.nwait = ^uint32(0)
1727 }
1728
1729 // gcBgMarkWorkerNode is an entry in the gcBgMarkWorkerPool. It points to a single
1730 // gcBgMarkWorker goroutine.
1731 type gcBgMarkWorkerNode struct {
1732 // Unused workers are managed in a lock-free stack. This field must be first.
1733 node lfnode
1734
1735 // The g of this worker.
1736 gp guintptr
1737
1738 // Release this m on park. This is used to communicate with the unlock
1739 // function, which cannot access the G's stack. It is unused outside of
1740 // gcBgMarkWorker().
1741 m muintptr
1742 }
1743 type gcBgMarkWorkerNodePadded struct {
1744 gcBgMarkWorkerNode
1745 pad [tagAlign - unsafe.Sizeof(gcBgMarkWorkerNode{}) - gcBgMarkWorkerNodeRedZoneSize]byte
1746 }
1747
1748 const gcBgMarkWorkerNodeRedZoneSize = (16 << 2) * asanenabledBit // redZoneSize(512)
1749
1750 func gcBgMarkWorker(ready chan struct{}) {
1751 gp := getg()
1752
1753 // We pass node to a gopark unlock function, so it can't be on
1754 // the stack (see gopark). Prevent deadlock from recursively
1755 // starting GC by disabling preemption.
1756 gp.m.preemptoff = "GC worker init"
1757 // TODO: This is technically not allowed in the heap. See comment in tagptr.go.
1758 //
1759 // It is kept alive simply by virtue of being used in the infinite loop
1760 // below. gcBgMarkWorkerPool keeps pointers to nodes that are not
1761 // GC-visible, so this must be kept alive indefinitely (even if
1762 // GOMAXPROCS decreases).
1763 node := &new(gcBgMarkWorkerNodePadded).gcBgMarkWorkerNode
1764 gp.m.preemptoff = ""
1765
1766 node.gp.set(gp)
1767
1768 node.m.set(acquirem())
1769
1770 ready <- struct{}{}
1771 // After this point, the background mark worker is generally scheduled
1772 // cooperatively by gcController.findRunnableGCWorker. While performing
1773 // work on the P, preemption is disabled because we are working on
1774 // P-local work buffers. When the preempt flag is set, this puts itself
1775 // into _Gwaiting to be woken up by gcController.findRunnableGCWorker
1776 // at the appropriate time.
1777 //
1778 // When preemption is enabled (e.g., while in gcMarkDone), this worker
1779 // may be preempted and schedule as a _Grunnable G from a runq. That is
1780 // fine; it will eventually gopark again for further scheduling via
1781 // findRunnableGCWorker.
1782 //
1783 // Since we disable preemption before notifying ready, we guarantee that
1784 // this G will be in the worker pool for the next findRunnableGCWorker.
1785 // This isn't strictly necessary, but it reduces latency between
1786 // _GCmark starting and the workers starting.
1787
1788 for {
1789 // Go to sleep until woken by
1790 // gcController.findRunnableGCWorker.
1791 gopark(func(g *g, nodep unsafe.Pointer) bool {
1792 node := (*gcBgMarkWorkerNode)(nodep)
1793
1794 if mp := node.m.ptr(); mp != nil {
1795 // The worker G is no longer running; release
1796 // the M.
1797 //
1798 // N.B. it is _safe_ to release the M as soon
1799 // as we are no longer performing P-local mark
1800 // work.
1801 //
1802 // However, since we cooperatively stop work
1803 // when gp.preempt is set, if we releasem in
1804 // the loop then the following call to gopark
1805 // would immediately preempt the G. This is
1806 // also safe, but inefficient: the G must
1807 // schedule again only to enter gopark and park
1808 // again. Thus, we defer the release until
1809 // after parking the G.
1810 releasem(mp)
1811 }
1812
1813 // Release this G to the pool.
1814 gcBgMarkWorkerPool.push(&node.node)
1815 // Note that at this point, the G may immediately be
1816 // rescheduled and may be running.
1817 return true
1818 }, unsafe.Pointer(node), waitReasonGCWorkerIdle, traceBlockSystemGoroutine, 0)
1819
1820 // Preemption must not occur here, or another G might see
1821 // p.gcMarkWorkerMode.
1822
1823 // Disable preemption so we can use the gcw. If the
1824 // scheduler wants to preempt us, we'll stop draining,
1825 // dispose the gcw, and then preempt.
1826 node.m.set(acquirem())
1827 pp := gp.m.p.ptr() // P can't change with preemption disabled.
1828
1829 if gcBlackenEnabled == 0 {
1830 println("worker mode", pp.gcMarkWorkerMode)
1831 throw("gcBgMarkWorker: blackening not enabled")
1832 }
1833
1834 if pp.gcMarkWorkerMode == gcMarkWorkerNotWorker {
1835 throw("gcBgMarkWorker: mode not set")
1836 }
1837
1838 startTime := nanotime()
1839 pp.gcMarkWorkerStartTime = startTime
1840 var trackLimiterEvent bool
1841 if pp.gcMarkWorkerMode == gcMarkWorkerIdleMode {
1842 trackLimiterEvent = pp.limiterEvent.start(limiterEventIdleMarkWork, startTime)
1843 }
1844
1845 gcBeginWork()
1846
1847 systemstack(func() {
1848 // Mark our goroutine preemptible so its stack can be scanned or observed
1849 // by the execution tracer. This, for example, lets two mark workers scan
1850 // each other (otherwise, they would deadlock).
1851 //
1852 // casGToWaitingForSuspendG marks the goroutine as ineligible for a
1853 // stack shrink, effectively pinning the stack in memory for the duration.
1854 //
1855 // N.B. The execution tracer is not aware of this status transition and
1856 // handles it specially based on the wait reason.
1857 casGToWaitingForSuspendG(gp, _Grunning, waitReasonGCWorkerActive)
1858 switch pp.gcMarkWorkerMode {
1859 default:
1860 throw("gcBgMarkWorker: unexpected gcMarkWorkerMode")
1861 case gcMarkWorkerDedicatedMode:
1862 gcDrainMarkWorkerDedicated(&pp.gcw, true)
1863 if gp.preempt {
1864 // We were preempted. This is
1865 // a useful signal to kick
1866 // everything out of the run
1867 // queue so it can run
1868 // somewhere else.
1869 if drainQ := runqdrain(pp); !drainQ.empty() {
1870 lock(&sched.lock)
1871 globrunqputbatch(&drainQ)
1872 unlock(&sched.lock)
1873 }
1874 }
1875 // Go back to draining, this time
1876 // without preemption.
1877 gcDrainMarkWorkerDedicated(&pp.gcw, false)
1878 case gcMarkWorkerFractionalMode:
1879 gcDrainMarkWorkerFractional(&pp.gcw)
1880 case gcMarkWorkerIdleMode:
1881 gcDrainMarkWorkerIdle(&pp.gcw)
1882 }
1883 casgstatus(gp, _Gwaiting, _Grunning)
1884 })
1885
1886 // Account for time and mark us as stopped.
1887 now := nanotime()
1888 duration := now - startTime
1889 gcController.markWorkerStop(pp.gcMarkWorkerMode, duration)
1890 if trackLimiterEvent {
1891 pp.limiterEvent.stop(limiterEventIdleMarkWork, now)
1892 }
1893 if pp.gcMarkWorkerMode == gcMarkWorkerFractionalMode {
1894 pp.gcFractionalMarkTime.Add(duration)
1895 }
1896
1897 // We'll releasem after this point and thus this P may run
1898 // something else. We must clear the worker mode to avoid
1899 // attributing the mode to a different (non-worker) G in
1900 // tracev2.GoStart.
1901 pp.gcMarkWorkerMode = gcMarkWorkerNotWorker
1902
1903 // If this worker reached a background mark completion
1904 // point, signal the main GC goroutine.
1905 if gcEndWork() {
1906 // We don't need the P-local buffers here, allow
1907 // preemption because we may schedule like a regular
1908 // goroutine in gcMarkDone (block on locks, etc).
1909 releasem(node.m.ptr())
1910 node.m.set(nil)
1911
1912 gcMarkDone()
1913 }
1914 }
1915 }
1916
1917 // gcShouldScheduleWorker reports whether executing a mark worker
1918 // on p is potentially useful. p may be nil.
1919 func gcShouldScheduleWorker(p *p) bool {
1920 if p != nil && !p.gcw.empty() {
1921 return true
1922 }
1923 return gcMarkWorkAvailable()
1924 }
1925
1926 // gcIsMarkDone reports whether the mark phase is (probably) done.
1927 func gcIsMarkDone() bool {
1928 return work.nwait == work.nproc && !gcMarkWorkAvailable()
1929 }
1930
1931 // gcBeginWork signals to the garbage collector that a new worker is
1932 // about to process GC work.
1933 func gcBeginWork() {
1934 decnwait := atomic.Xadd(&work.nwait, -1)
1935 if decnwait == work.nproc {
1936 println("runtime: work.nwait=", decnwait, "work.nproc=", work.nproc)
1937 throw("work.nwait was > work.nproc")
1938 }
1939 }
1940
1941 // gcEndWork signals to the garbage collector that a new worker has just finished
1942 // its work. It reports whether it was the last worker and there's no more work
1943 // to do. If it returns true, the caller must call gcMarkDone.
1944 func gcEndWork() (last bool) {
1945 incnwait := atomic.Xadd(&work.nwait, +1)
1946 if incnwait > work.nproc {
1947 println("runtime: work.nwait=", incnwait, "work.nproc=", work.nproc)
1948 throw("work.nwait > work.nproc")
1949 }
1950 return incnwait == work.nproc && !gcMarkWorkAvailable()
1951 }
1952
1953 // gcMark runs the mark (or, for concurrent GC, mark termination)
1954 // All gcWork caches must be empty.
1955 // STW is in effect at this point.
1956 func gcMark(startTime int64) {
1957 if gcphase != _GCmarktermination {
1958 throw("in gcMark expecting to see gcphase as _GCmarktermination")
1959 }
1960 work.tstart = startTime
1961
1962 // Check that there's no marking work remaining.
1963 if next, jobs := work.markrootNext.Load(), work.markrootJobs.Load(); work.full != 0 || next < jobs {
1964 print("runtime: full=", hex(work.full), " next=", next, " jobs=", jobs, " nDataRoots=", work.nDataRoots, " nBSSRoots=", work.nBSSRoots, " nSpanRoots=", work.nSpanRoots, " nStackRoots=", work.nStackRoots, "\n")
1965 panic("non-empty mark queue after concurrent mark")
1966 }
1967
1968 if debug.gccheckmark > 0 {
1969 // This is expensive when there's a large number of
1970 // Gs, so only do it if checkmark is also enabled.
1971 gcMarkRootCheck()
1972 }
1973
1974 // Drop allg snapshot. allgs may have grown, in which case
1975 // this is the only reference to the old backing store and
1976 // there's no need to keep it around.
1977 work.stackRoots = nil
1978
1979 // Clear out buffers and double-check that all gcWork caches
1980 // are empty. This should be ensured by gcMarkDone before we
1981 // enter mark termination.
1982 //
1983 // TODO: We could clear out buffers just before mark if this
1984 // has a non-negligible impact on STW time.
1985 for _, p := range allp {
1986 // The write barrier may have buffered pointers since
1987 // the gcMarkDone barrier. However, since the barrier
1988 // ensured all reachable objects were marked, all of
1989 // these must be pointers to black objects. Hence we
1990 // can just discard the write barrier buffer.
1991 if debug.gccheckmark > 0 {
1992 // For debugging, flush the buffer and make
1993 // sure it really was all marked.
1994 wbBufFlush1(p)
1995 } else {
1996 p.wbBuf.reset()
1997 }
1998
1999 gcw := &p.gcw
2000 if !gcw.empty() {
2001 printlock()
2002 print("runtime: P ", p.id, " flushedWork ", gcw.flushedWork)
2003 if gcw.wbuf1 == nil {
2004 print(" wbuf1=<nil>")
2005 } else {
2006 print(" wbuf1.n=", gcw.wbuf1.nobj)
2007 }
2008 if gcw.wbuf2 == nil {
2009 print(" wbuf2=<nil>")
2010 } else {
2011 print(" wbuf2.n=", gcw.wbuf2.nobj)
2012 }
2013 print("\n")
2014 throw("P has cached GC work at end of mark termination")
2015 }
2016 // There may still be cached empty buffers, which we
2017 // need to flush since we're going to free them. Also,
2018 // there may be non-zero stats because we allocated
2019 // black after the gcMarkDone barrier.
2020 gcw.dispose()
2021 }
2022
2023 // Flush scanAlloc from each mcache since we're about to modify
2024 // heapScan directly. If we were to flush this later, then scanAlloc
2025 // might have incorrect information.
2026 //
2027 // Note that it's not important to retain this information; we know
2028 // exactly what heapScan is at this point via scanWork.
2029 for _, p := range allp {
2030 c := p.mcache
2031 if c == nil {
2032 continue
2033 }
2034 c.scanAlloc = 0
2035 }
2036
2037 // Reset controller state.
2038 gcController.resetLive(work.bytesMarked)
2039 }
2040
2041 // gcSweep must be called on the system stack because it acquires the heap
2042 // lock. See mheap for details.
2043 //
2044 // Returns true if the heap was fully swept by this function.
2045 //
2046 // The world must be stopped.
2047 //
2048 //go:systemstack
2049 func gcSweep(mode gcMode) bool {
2050 assertWorldStopped()
2051
2052 if gcphase != _GCoff {
2053 throw("gcSweep being done but phase is not GCoff")
2054 }
2055
2056 lock(&mheap_.lock)
2057 mheap_.sweepgen += 2
2058 sweep.active.reset()
2059 mheap_.pagesSwept.Store(0)
2060 mheap_.sweepArenas = mheap_.heapArenas
2061 mheap_.reclaimIndex.Store(0)
2062 mheap_.reclaimCredit.Store(0)
2063 unlock(&mheap_.lock)
2064
2065 sweep.centralIndex.clear()
2066
2067 if !concurrentSweep || mode == gcForceBlockMode {
2068 // Special case synchronous sweep.
2069 // Record that no proportional sweeping has to happen.
2070 lock(&mheap_.lock)
2071 mheap_.sweepPagesPerByte = 0
2072 unlock(&mheap_.lock)
2073 // Flush all mcaches.
2074 for _, pp := range allp {
2075 pp.mcache.prepareForSweep()
2076 }
2077 // Sweep all spans eagerly.
2078 for sweepone() != ^uintptr(0) {
2079 }
2080 // Free workbufs and span rings eagerly.
2081 prepareFreeWorkbufs()
2082 for freeSomeWbufs(false) {
2083 }
2084 freeDeadSpanSPMCs()
2085 // All "free" events for this mark/sweep cycle have
2086 // now happened, so we can make this profile cycle
2087 // available immediately.
2088 mProf_NextCycle()
2089 mProf_Flush()
2090 return true
2091 }
2092
2093 // Background sweep.
2094 lock(&sweep.lock)
2095 if sweep.parked {
2096 sweep.parked = false
2097 ready(sweep.g, 0, true)
2098 }
2099 unlock(&sweep.lock)
2100 return false
2101 }
2102
2103 // gcResetMarkState resets global state prior to marking (concurrent
2104 // or STW) and resets the stack scan state of all Gs.
2105 //
2106 // This is safe to do without the world stopped because any Gs created
2107 // during or after this will start out in the reset state.
2108 //
2109 // gcResetMarkState must be called on the system stack because it acquires
2110 // the heap lock. See mheap for details.
2111 //
2112 //go:systemstack
2113 func gcResetMarkState() {
2114 // This may be called during a concurrent phase, so lock to make sure
2115 // allgs doesn't change.
2116 forEachG(func(gp *g) {
2117 gp.gcscandone = false // set to true in gcphasework
2118 gp.gcAssistBytes = 0
2119 })
2120
2121 // Clear page marks. This is just 1MB per 64GB of heap, so the
2122 // time here is pretty trivial.
2123 lock(&mheap_.lock)
2124 arenas := mheap_.heapArenas
2125 unlock(&mheap_.lock)
2126 for _, ai := range arenas {
2127 ha := mheap_.arenas[ai.l1()][ai.l2()]
2128 clear(ha.pageMarks[:])
2129 }
2130
2131 work.bytesMarked = 0
2132 work.initialHeapLive = gcController.heapLive.Load()
2133 }
2134
2135 // Hooks for other packages
2136
2137 var poolcleanup func()
2138 var boringCaches []unsafe.Pointer // for crypto/internal/boring
2139
2140 // sync_runtime_registerPoolCleanup should be an internal detail,
2141 // but widely used packages access it using linkname.
2142 // Notable members of the hall of shame include:
2143 // - github.com/bytedance/gopkg
2144 // - github.com/songzhibin97/gkit
2145 //
2146 // Do not remove or change the type signature.
2147 // See go.dev/issue/67401.
2148 //
2149 //go:linkname sync_runtime_registerPoolCleanup sync.runtime_registerPoolCleanup
2150 func sync_runtime_registerPoolCleanup(f func()) {
2151 poolcleanup = f
2152 }
2153
2154 //go:linkname boring_registerCache crypto/internal/boring/bcache.registerCache
2155 func boring_registerCache(p unsafe.Pointer) {
2156 boringCaches = append(boringCaches, p)
2157 }
2158
2159 func clearpools() {
2160 // clear sync.Pools
2161 if poolcleanup != nil {
2162 poolcleanup()
2163 }
2164
2165 // clear boringcrypto caches
2166 for _, p := range boringCaches {
2167 atomicstorep(p, nil)
2168 }
2169
2170 // Clear central sudog cache.
2171 // Leave per-P caches alone, they have strictly bounded size.
2172 // Disconnect cached list before dropping it on the floor,
2173 // so that a dangling ref to one entry does not pin all of them.
2174 lock(&sched.sudoglock)
2175 var sg, sgnext *sudog
2176 for sg = sched.sudogcache; sg != nil; sg = sgnext {
2177 sgnext = sg.next
2178 sg.next = nil
2179 }
2180 sched.sudogcache = nil
2181 unlock(&sched.sudoglock)
2182
2183 // Clear central defer pool.
2184 // Leave per-P pools alone, they have strictly bounded size.
2185 lock(&sched.deferlock)
2186 // disconnect cached list before dropping it on the floor,
2187 // so that a dangling ref to one entry does not pin all of them.
2188 var d, dlink *_defer
2189 for d = sched.deferpool; d != nil; d = dlink {
2190 dlink = d.link
2191 d.link = nil
2192 }
2193 sched.deferpool = nil
2194 unlock(&sched.deferlock)
2195 }
2196
2197 // Timing
2198
2199 // itoaDiv formats val/(10**dec) into buf.
2200 func itoaDiv(buf []byte, val uint64, dec int) []byte {
2201 i := len(buf) - 1
2202 idec := i - dec
2203 for val >= 10 || i >= idec {
2204 buf[i] = byte(val%10 + '0')
2205 i--
2206 if i == idec {
2207 buf[i] = '.'
2208 i--
2209 }
2210 val /= 10
2211 }
2212 buf[i] = byte(val + '0')
2213 return buf[i:]
2214 }
2215
2216 // fmtNSAsMS nicely formats ns nanoseconds as milliseconds.
2217 func fmtNSAsMS(buf []byte, ns uint64) []byte {
2218 if ns >= 10e6 {
2219 // Format as whole milliseconds.
2220 return itoaDiv(buf, ns/1e6, 0)
2221 }
2222 // Format two digits of precision, with at most three decimal places.
2223 x := ns / 1e3
2224 if x == 0 {
2225 buf[0] = '0'
2226 return buf[:1]
2227 }
2228 dec := 3
2229 for x >= 100 {
2230 x /= 10
2231 dec--
2232 }
2233 return itoaDiv(buf, x, dec)
2234 }
2235
2236 // Helpers for testing GC.
2237
2238 // gcTestMoveStackOnNextCall causes the stack to be moved on a call
2239 // immediately following the call to this. It may not work correctly
2240 // if any other work appears after this call (such as returning).
2241 // Typically the following call should be marked go:noinline so it
2242 // performs a stack check.
2243 //
2244 // In rare cases this may not cause the stack to move, specifically if
2245 // there's a preemption between this call and the next.
2246 func gcTestMoveStackOnNextCall() {
2247 gp := getg()
2248 gp.stackguard0 = stackForceMove
2249 }
2250
2251 // gcTestIsReachable performs a GC and returns a bit set where bit i
2252 // is set if ptrs[i] is reachable.
2253 func gcTestIsReachable(ptrs ...unsafe.Pointer) (mask uint64) {
2254 // This takes the pointers as unsafe.Pointers in order to keep
2255 // them live long enough for us to attach specials. After
2256 // that, we drop our references to them.
2257
2258 if len(ptrs) > 64 {
2259 panic("too many pointers for uint64 mask")
2260 }
2261
2262 // Block GC while we attach specials and drop our references
2263 // to ptrs. Otherwise, if a GC is in progress, it could mark
2264 // them reachable via this function before we have a chance to
2265 // drop them.
2266 semacquire(&gcsema)
2267
2268 // Create reachability specials for ptrs.
2269 specials := make([]*specialReachable, len(ptrs))
2270 for i, p := range ptrs {
2271 lock(&mheap_.speciallock)
2272 s := (*specialReachable)(mheap_.specialReachableAlloc.alloc())
2273 unlock(&mheap_.speciallock)
2274 s.special.kind = _KindSpecialReachable
2275 if !addspecial(p, &s.special, false) {
2276 throw("already have a reachable special (duplicate pointer?)")
2277 }
2278 specials[i] = s
2279 // Make sure we don't retain ptrs.
2280 ptrs[i] = nil
2281 }
2282
2283 semrelease(&gcsema)
2284
2285 // Force a full GC and sweep.
2286 GC()
2287
2288 // Process specials.
2289 for i, s := range specials {
2290 if !s.done {
2291 printlock()
2292 println("runtime: object", i, "was not swept")
2293 throw("IsReachable failed")
2294 }
2295 if s.reachable {
2296 mask |= 1 << i
2297 }
2298 lock(&mheap_.speciallock)
2299 mheap_.specialReachableAlloc.free(unsafe.Pointer(s))
2300 unlock(&mheap_.speciallock)
2301 }
2302
2303 return mask
2304 }
2305
2306 // gcTestPointerClass returns the category of what p points to, one of:
2307 // "heap", "stack", "data", "bss", "other". This is useful for checking
2308 // that a test is doing what it's intended to do.
2309 //
2310 // This is nosplit simply to avoid extra pointer shuffling that may
2311 // complicate a test.
2312 //
2313 //go:nosplit
2314 func gcTestPointerClass(p unsafe.Pointer) string {
2315 p2 := uintptr(noescape(p))
2316 gp := getg()
2317 if gp.stack.lo <= p2 && p2 < gp.stack.hi {
2318 return "stack"
2319 }
2320 if base, _, _ := findObject(p2, 0, 0); base != 0 {
2321 return "heap"
2322 }
2323 for _, datap := range activeModules() {
2324 if datap.data <= p2 && p2 < datap.edata || datap.noptrdata <= p2 && p2 < datap.enoptrdata {
2325 return "data"
2326 }
2327 if datap.bss <= p2 && p2 < datap.ebss || datap.noptrbss <= p2 && p2 <= datap.enoptrbss {
2328 return "bss"
2329 }
2330 }
2331 KeepAlive(p)
2332 return "other"
2333 }