1 // Copyright 2021 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.
9 "internal/goexperiment"
10 "runtime/internal/atomic"
15 // gcGoalUtilization is the goal CPU utilization for
16 // marking as a fraction of GOMAXPROCS.
18 // Increasing the goal utilization will shorten GC cycles as the GC
19 // has more resources behind it, lessening costs from the write barrier,
20 // but comes at the cost of increasing mutator latency.
21 gcGoalUtilization = gcBackgroundUtilization
23 // gcBackgroundUtilization is the fixed CPU utilization for background
24 // marking. It must be <= gcGoalUtilization. The difference between
25 // gcGoalUtilization and gcBackgroundUtilization will be made up by
26 // mark assists. The scheduler will aim to use within 50% of this
29 // As a general rule, there's little reason to set gcBackgroundUtilization
30 // < gcGoalUtilization. One reason might be in mostly idle applications,
31 // where goroutines are unlikely to assist at all, so the actual
32 // utilization will be lower than the goal. But this is moot point
33 // because the idle mark workers already soak up idle CPU resources.
34 // These two values are still kept separate however because they are
35 // distinct conceptually, and in previous iterations of the pacer the
36 // distinction was more important.
37 gcBackgroundUtilization = 0.25
39 // gcCreditSlack is the amount of scan work credit that can
40 // accumulate locally before updating gcController.heapScanWork and,
41 // optionally, gcController.bgScanCredit. Lower values give a more
42 // accurate assist ratio and make it more likely that assists will
43 // successfully steal background credit. Higher values reduce memory
47 // gcAssistTimeSlack is the nanoseconds of mutator assist time that
48 // can accumulate on a P before updating gcController.assistTime.
49 gcAssistTimeSlack = 5000
51 // gcOverAssistWork determines how many extra units of scan work a GC
52 // assist does when an assist happens. This amortizes the cost of an
53 // assist by pre-paying for this many bytes of future allocations.
54 gcOverAssistWork = 64 << 10
56 // defaultHeapMinimum is the value of heapMinimum for GOGC==100.
57 defaultHeapMinimum = (goexperiment.HeapMinimum512KiBInt)*(512<<10) +
58 (1-goexperiment.HeapMinimum512KiBInt)*(4<<20)
60 // scannableStackSizeSlack is the bytes of stack space allocated or freed
61 // that can accumulate on a P before updating gcController.stackSize.
62 scannableStackSizeSlack = 8 << 10
66 if offset := unsafe.Offsetof(gcController.heapLive); offset%8 != 0 {
68 throw("gcController.heapLive not aligned to 8 bytes")
72 // gcController implements the GC pacing controller that determines
73 // when to trigger concurrent garbage collection and how much marking
74 // work to do in mutator assists and background marking.
76 // It calculates the ratio between the allocation rate (in terms of CPU
77 // time) and the GC scan throughput to determine the heap size at which to
78 // trigger a GC cycle such that no GC assists are required to finish on time.
79 // This algorithm thus optimizes GC CPU utilization to the dedicated background
80 // mark utilization of 25% of GOMAXPROCS by minimizing GC assists.
81 // GOMAXPROCS. The high-level design of this algorithm is documented
82 // at https://github.com/golang/proposal/blob/master/design/44167-gc-pacer-redesign.md.
83 // See https://golang.org/s/go15gcpacing for additional historical context.
84 var gcController gcControllerState
86 type gcControllerState struct {
88 // Initialized from GOGC. GOGC=off means no GC.
89 gcPercent atomic.Int32
91 _ uint32 // padding so following 64-bit values are 8-byte aligned
93 // heapMinimum is the minimum heap size at which to trigger GC.
94 // For small heaps, this overrides the usual GOGC*live set rule.
96 // When there is a very small live set but a lot of allocation, simply
97 // collecting when the heap reaches GOGC*live results in many GC
98 // cycles and high total per-GC overhead. This minimum amortizes this
99 // per-GC overhead while keeping the heap reasonably small.
101 // During initialization this is set to 4MB*GOGC/100. In the case of
102 // GOGC==0, this will set heapMinimum to 0, resulting in constant
103 // collection even when the heap size is small, which is useful for
107 // trigger is the heap size that triggers marking.
109 // When heapLive ≥ trigger, the mark phase will start.
110 // This is also the heap size by which proportional sweeping
113 // This is computed from consMark during mark termination for
114 // the next cycle's trigger.
116 // Protected by mheap_.lock or a STW.
119 // consMark is the estimated per-CPU consMark ratio for the application.
121 // It represents the ratio between the application's allocation
122 // rate, as bytes allocated per CPU-time, and the GC's scan rate,
123 // as bytes scanned per CPU-time.
124 // The units of this ratio are (B / cpu-ns) / (B / cpu-ns).
126 // At a high level, this value is computed as the bytes of memory
127 // allocated (cons) per unit of scan work completed (mark) in a GC
128 // cycle, divided by the CPU time spent on each activity.
130 // Updated at the end of each GC cycle, in endCycle.
133 // consMarkController holds the state for the mark-cons ratio
134 // estimation over time.
136 // Its purpose is to smooth out noisiness in the computation of
137 // consMark; see consMark for details.
138 consMarkController piController
140 _ uint32 // Padding for atomics on 32-bit platforms.
142 // heapGoal is the goal heapLive for when next GC ends.
143 // Set to ^uint64(0) if disabled.
145 // Read and written atomically, unless the world is stopped.
148 // lastHeapGoal is the value of heapGoal for the previous GC.
149 // Note that this is distinct from the last value heapGoal had,
150 // because it could change if e.g. gcPercent changes.
152 // Read and written with the world stopped or with mheap_.lock held.
155 // heapLive is the number of bytes considered live by the GC.
156 // That is: retained by the most recent GC plus allocated
157 // since then. heapLive ≤ memstats.heapAlloc, since heapAlloc includes
158 // unmarked objects that have not yet been swept (and hence goes up as we
159 // allocate and down as we sweep) while heapLive excludes these
160 // objects (and hence only goes up between GCs).
162 // This is updated atomically without locking. To reduce
163 // contention, this is updated only when obtaining a span from
164 // an mcentral and at this point it counts all of the
165 // unallocated slots in that span (which will be allocated
166 // before that mcache obtains another span from that
167 // mcentral). Hence, it slightly overestimates the "true" live
168 // heap size. It's better to overestimate than to
169 // underestimate because 1) this triggers the GC earlier than
170 // necessary rather than potentially too late and 2) this
171 // leads to a conservative GC rate rather than a GC rate that
172 // is potentially too low.
174 // Reads should likewise be atomic (or during STW).
176 // Whenever this is updated, call traceHeapAlloc() and
177 // this gcControllerState's revise() method.
180 // heapScan is the number of bytes of "scannable" heap. This
181 // is the live heap (as counted by heapLive), but omitting
182 // no-scan objects and no-scan tails of objects.
184 // This value is fixed at the start of a GC cycle, so during a
185 // GC cycle it is safe to read without atomics, and it represents
186 // the maximum scannable heap.
189 // lastHeapScan is the number of bytes of heap that were scanned
190 // last GC cycle. It is the same as heapMarked, but only
191 // includes the "scannable" parts of objects.
193 // Updated when the world is stopped.
196 // stackScan is a snapshot of scannableStackSize taken at each GC
197 // STW pause and is used in pacing decisions.
199 // Updated only while the world is stopped.
202 // scannableStackSize is the amount of allocated goroutine stack space in
203 // use by goroutines.
205 // This number tracks allocated goroutine stack space rather than used
206 // goroutine stack space (i.e. what is actually scanned) because used
207 // goroutine stack space is much harder to measure cheaply. By using
208 // allocated space, we make an overestimate; this is OK, it's better
209 // to conservatively overcount than undercount.
211 // Read and updated atomically.
212 scannableStackSize uint64
214 // globalsScan is the total amount of global variable space
215 // that is scannable.
217 // Read and updated atomically.
220 // heapMarked is the number of bytes marked by the previous
221 // GC. After mark termination, heapLive == heapMarked, but
222 // unlike heapLive, heapMarked does not change until the
223 // next mark termination.
226 // heapScanWork is the total heap scan work performed this cycle.
227 // stackScanWork is the total stack scan work performed this cycle.
228 // globalsScanWork is the total globals scan work performed this cycle.
230 // These are updated atomically during the cycle. Updates occur in
231 // bounded batches, since they are both written and read
232 // throughout the cycle. At the end of the cycle, heapScanWork is how
233 // much of the retained heap is scannable.
235 // Currently these are measured in bytes. For most uses, this is an
236 // opaque unit of work, but for estimation the definition is important.
238 // Note that stackScanWork includes all allocated space, not just the
239 // size of the stack itself, mirroring stackSize.
240 heapScanWork atomic.Int64
241 stackScanWork atomic.Int64
242 globalsScanWork atomic.Int64
244 // bgScanCredit is the scan work credit accumulated by the
245 // concurrent background scan. This credit is accumulated by
246 // the background scan and stolen by mutator assists. This is
247 // updated atomically. Updates occur in bounded batches, since
248 // it is both written and read throughout the cycle.
251 // assistTime is the nanoseconds spent in mutator assists
252 // during this cycle. This is updated atomically. Updates
253 // occur in bounded batches, since it is both written and read
254 // throughout the cycle.
257 // dedicatedMarkTime is the nanoseconds spent in dedicated
258 // mark workers during this cycle. This is updated atomically
259 // at the end of the concurrent mark phase.
260 dedicatedMarkTime int64
262 // fractionalMarkTime is the nanoseconds spent in the
263 // fractional mark worker during this cycle. This is updated
264 // atomically throughout the cycle and will be up-to-date if
265 // the fractional mark worker is not currently running.
266 fractionalMarkTime int64
268 // idleMarkTime is the nanoseconds spent in idle marking
269 // during this cycle. This is updated atomically throughout
273 // markStartTime is the absolute start time in nanoseconds
274 // that assists and background mark workers started.
277 // dedicatedMarkWorkersNeeded is the number of dedicated mark
278 // workers that need to be started. This is computed at the
279 // beginning of each cycle and decremented atomically as
280 // dedicated mark workers get started.
281 dedicatedMarkWorkersNeeded int64
283 // idleMarkWorkers is two packed int32 values in a single uint64.
284 // These two values are always updated simultaneously.
286 // The bottom int32 is the current number of idle mark workers executing.
288 // The top int32 is the maximum number of idle mark workers allowed to
289 // execute concurrently. Normally, this number is just gomaxprocs. However,
290 // during periodic GC cycles it is set to 0 because the system is idle
291 // anyway; there's no need to go full blast on all of GOMAXPROCS.
293 // The maximum number of idle mark workers is used to prevent new workers
294 // from starting, but it is not a hard maximum. It is possible (but
295 // exceedingly rare) for the current number of idle mark workers to
296 // transiently exceed the maximum. This could happen if the maximum changes
297 // just after a GC ends, and an M with no P.
299 // Note that if we have no dedicated mark workers, we set this value to
300 // 1 in this case we only have fractional GC workers which aren't scheduled
301 // strictly enough to ensure GC progress. As a result, idle-priority mark
302 // workers are vital to GC progress in these situations.
304 // For example, consider a situation in which goroutines block on the GC
305 // (such as via runtime.GOMAXPROCS) and only fractional mark workers are
306 // scheduled (e.g. GOMAXPROCS=1). Without idle-priority mark workers, the
307 // last running M might skip scheduling a fractional mark worker if its
308 // utilization goal is met, such that once it goes to sleep (because there's
309 // nothing to do), there will be nothing else to spin up a new M for the
310 // fractional worker in the future, stalling GC progress and causing a
311 // deadlock. However, idle-priority workers will *always* run when there is
312 // nothing left to do, ensuring the GC makes progress.
314 // See github.com/golang/go/issues/44163 for more details.
315 idleMarkWorkers atomic.Uint64
317 // assistWorkPerByte is the ratio of scan work to allocated
318 // bytes that should be performed by mutator assists. This is
319 // computed at the beginning of each cycle and updated every
320 // time heapScan is updated.
321 assistWorkPerByte atomic.Float64
323 // assistBytesPerWork is 1/assistWorkPerByte.
325 // Note that because this is read and written independently
326 // from assistWorkPerByte users may notice a skew between
327 // the two values, and such a state should be safe.
328 assistBytesPerWork atomic.Float64
330 // fractionalUtilizationGoal is the fraction of wall clock
331 // time that should be spent in the fractional mark worker on
332 // each P that isn't running a dedicated worker.
334 // For example, if the utilization goal is 25% and there are
335 // no dedicated workers, this will be 0.25. If the goal is
336 // 25%, there is one dedicated worker, and GOMAXPROCS is 5,
337 // this will be 0.05 to make up the missing 5%.
339 // If this is zero, no fractional workers are needed.
340 fractionalUtilizationGoal float64
342 // test indicates that this is a test-only copy of gcControllerState.
348 func (c *gcControllerState) init(gcPercent int32) {
349 c.heapMinimum = defaultHeapMinimum
351 c.consMarkController = piController{
352 // Tuned first via the Ziegler-Nichols process in simulation,
353 // then the integral time was manually tuned against real-world
354 // applications to deal with noisiness in the measured cons/mark
359 // Set a high reset time in GC cycles.
360 // This is inversely proportional to the rate at which we
361 // accumulate error from clipping. By making this very high
362 // we make the accumulation slow. In general, clipping is
363 // OK in our situation, hence the choice.
365 // Tune this if we get unintended effects from clipping for
372 // This will also compute and set the GC trigger and goal.
373 c.setGCPercent(gcPercent)
376 // startCycle resets the GC controller's state and computes estimates
377 // for a new GC cycle. The caller must hold worldsema and the world
379 func (c *gcControllerState) startCycle(markStartTime int64, procs int, trigger gcTrigger) {
380 c.heapScanWork.Store(0)
381 c.stackScanWork.Store(0)
382 c.globalsScanWork.Store(0)
385 c.dedicatedMarkTime = 0
386 c.fractionalMarkTime = 0
388 c.markStartTime = markStartTime
389 c.stackScan = atomic.Load64(&c.scannableStackSize)
391 // Ensure that the heap goal is at least a little larger than
392 // the current live heap size. This may not be the case if GC
393 // start is delayed or if the allocation that pushed gcController.heapLive
394 // over trigger is large or if the trigger is really close to
395 // GOGC. Assist is proportional to this distance, so enforce a
396 // minimum distance, even if it means going over the GOGC goal
398 if c.heapGoal < c.heapLive+64<<10 {
399 c.heapGoal = c.heapLive + 64<<10
402 // Compute the background mark utilization goal. In general,
403 // this may not come out exactly. We round the number of
404 // dedicated workers so that the utilization is closest to
405 // 25%. For small GOMAXPROCS, this would introduce too much
406 // error, so we add fractional workers in that case.
407 totalUtilizationGoal := float64(procs) * gcBackgroundUtilization
408 c.dedicatedMarkWorkersNeeded = int64(totalUtilizationGoal + 0.5)
409 utilError := float64(c.dedicatedMarkWorkersNeeded)/totalUtilizationGoal - 1
410 const maxUtilError = 0.3
411 if utilError < -maxUtilError || utilError > maxUtilError {
412 // Rounding put us more than 30% off our goal. With
413 // gcBackgroundUtilization of 25%, this happens for
414 // GOMAXPROCS<=3 or GOMAXPROCS=6. Enable fractional
415 // workers to compensate.
416 if float64(c.dedicatedMarkWorkersNeeded) > totalUtilizationGoal {
417 // Too many dedicated workers.
418 c.dedicatedMarkWorkersNeeded--
420 c.fractionalUtilizationGoal = (totalUtilizationGoal - float64(c.dedicatedMarkWorkersNeeded)) / float64(procs)
422 c.fractionalUtilizationGoal = 0
425 // In STW mode, we just want dedicated workers.
426 if debug.gcstoptheworld > 0 {
427 c.dedicatedMarkWorkersNeeded = int64(procs)
428 c.fractionalUtilizationGoal = 0
432 for _, p := range allp {
434 p.gcFractionalMarkTime = 0
437 if trigger.kind == gcTriggerTime {
438 // During a periodic GC cycle, reduce the number of idle mark workers
439 // required. However, we need at least one dedicated mark worker or
440 // idle GC worker to ensure GC progress in some scenarios (see comment
441 // on maxIdleMarkWorkers).
442 if c.dedicatedMarkWorkersNeeded > 0 {
443 c.setMaxIdleMarkWorkers(0)
445 // TODO(mknyszek): The fundamental reason why we need this is because
446 // we can't count on the fractional mark worker to get scheduled.
447 // Fix that by ensuring it gets scheduled according to its quota even
448 // if the rest of the application is idle.
449 c.setMaxIdleMarkWorkers(1)
452 // N.B. gomaxprocs and dedicatedMarkWorkersNeeded is guaranteed not to
453 // change during a GC cycle.
454 c.setMaxIdleMarkWorkers(int32(procs) - int32(c.dedicatedMarkWorkersNeeded))
457 // Compute initial values for controls that are updated
458 // throughout the cycle.
461 if debug.gcpacertrace > 0 {
462 assistRatio := c.assistWorkPerByte.Load()
463 print("pacer: assist ratio=", assistRatio,
464 " (scan ", gcController.heapScan>>20, " MB in ",
465 work.initialHeapLive>>20, "->",
466 c.heapGoal>>20, " MB)",
467 " workers=", c.dedicatedMarkWorkersNeeded,
468 "+", c.fractionalUtilizationGoal, "\n")
472 // revise updates the assist ratio during the GC cycle to account for
473 // improved estimates. This should be called whenever gcController.heapScan,
474 // gcController.heapLive, or gcController.heapGoal is updated. It is safe to
475 // call concurrently, but it may race with other calls to revise.
477 // The result of this race is that the two assist ratio values may not line
478 // up or may be stale. In practice this is OK because the assist ratio
479 // moves slowly throughout a GC cycle, and the assist ratio is a best-effort
480 // heuristic anyway. Furthermore, no part of the heuristic depends on
481 // the two assist ratio values being exact reciprocals of one another, since
482 // the two values are used to convert values from different sources.
484 // The worst case result of this raciness is that we may miss a larger shift
485 // in the ratio (say, if we decide to pace more aggressively against the
486 // hard heap goal) but even this "hard goal" is best-effort (see #40460).
487 // The dedicated GC should ensure we don't exceed the hard goal by too much
488 // in the rare case we do exceed it.
490 // It should only be called when gcBlackenEnabled != 0 (because this
491 // is when assists are enabled and the necessary statistics are
493 func (c *gcControllerState) revise() {
494 gcPercent := c.gcPercent.Load()
496 // If GC is disabled but we're running a forced GC,
497 // act like GOGC is huge for the below calculations.
500 live := atomic.Load64(&c.heapLive)
501 scan := atomic.Load64(&c.heapScan)
502 work := c.heapScanWork.Load() + c.stackScanWork.Load() + c.globalsScanWork.Load()
504 // Assume we're under the soft goal. Pace GC to complete at
505 // heapGoal assuming the heap is in steady-state.
506 heapGoal := int64(atomic.Load64(&c.heapGoal))
508 // The expected scan work is computed as the amount of bytes scanned last
509 // GC cycle, plus our estimate of stacks and globals work for this cycle.
510 scanWorkExpected := int64(c.lastHeapScan + c.stackScan + c.globalsScan)
512 // maxScanWork is a worst-case estimate of the amount of scan work that
513 // needs to be performed in this GC cycle. Specifically, it represents
514 // the case where *all* scannable memory turns out to be live.
515 maxScanWork := int64(scan + c.stackScan + c.globalsScan)
516 if work > scanWorkExpected {
517 // We've already done more scan work than expected. Because our expectation
518 // is based on a steady-state scannable heap size, we assume this means our
519 // heap is growing. Compute a new heap goal that takes our existing runway
520 // computed for scanWorkExpected and extrapolates it to maxScanWork, the worst-case
521 // scan work. This keeps our assist ratio stable if the heap continues to grow.
523 // The effect of this mechanism is that assists stay flat in the face of heap
524 // growths. It's OK to use more memory this cycle to scan all the live heap,
525 // because the next GC cycle is inevitably going to use *at least* that much
527 extHeapGoal := int64(float64(heapGoal-int64(c.trigger))/float64(scanWorkExpected)*float64(maxScanWork)) + int64(c.trigger)
528 scanWorkExpected = maxScanWork
530 // hardGoal is a hard limit on the amount that we're willing to push back the
531 // heap goal, and that's twice the heap goal (i.e. if GOGC=100 and the heap and/or
532 // stacks and/or globals grow to twice their size, this limits the current GC cycle's
533 // growth to 4x the original live heap's size).
535 // This maintains the invariant that we use no more memory than the next GC cycle
537 hardGoal := int64((1.0 + float64(gcPercent)/100.0) * float64(heapGoal))
538 if extHeapGoal > hardGoal {
539 extHeapGoal = hardGoal
541 heapGoal = extHeapGoal
543 if int64(live) > heapGoal {
544 // We're already past our heap goal, even the extrapolated one.
545 // Leave ourselves some extra runway, so in the worst case we
546 // finish by that point.
547 const maxOvershoot = 1.1
548 heapGoal = int64(float64(heapGoal) * maxOvershoot)
550 // Compute the upper bound on the scan work remaining.
551 scanWorkExpected = maxScanWork
554 // Compute the remaining scan work estimate.
556 // Note that we currently count allocations during GC as both
557 // scannable heap (heapScan) and scan work completed
558 // (scanWork), so allocation will change this difference
559 // slowly in the soft regime and not at all in the hard
561 scanWorkRemaining := scanWorkExpected - work
562 if scanWorkRemaining < 1000 {
563 // We set a somewhat arbitrary lower bound on
564 // remaining scan work since if we aim a little high,
565 // we can miss by a little.
567 // We *do* need to enforce that this is at least 1,
568 // since marking is racy and double-scanning objects
569 // may legitimately make the remaining scan work
570 // negative, even in the hard goal regime.
571 scanWorkRemaining = 1000
574 // Compute the heap distance remaining.
575 heapRemaining := heapGoal - int64(live)
576 if heapRemaining <= 0 {
577 // This shouldn't happen, but if it does, avoid
578 // dividing by zero or setting the assist negative.
582 // Compute the mutator assist ratio so by the time the mutator
583 // allocates the remaining heap bytes up to heapGoal, it will
584 // have done (or stolen) the remaining amount of scan work.
585 // Note that the assist ratio values are updated atomically
586 // but not together. This means there may be some degree of
587 // skew between the two values. This is generally OK as the
588 // values shift relatively slowly over the course of a GC
590 assistWorkPerByte := float64(scanWorkRemaining) / float64(heapRemaining)
591 assistBytesPerWork := float64(heapRemaining) / float64(scanWorkRemaining)
592 c.assistWorkPerByte.Store(assistWorkPerByte)
593 c.assistBytesPerWork.Store(assistBytesPerWork)
596 // endCycle computes the consMark estimate for the next cycle.
597 // userForced indicates whether the current GC cycle was forced
598 // by the application.
599 func (c *gcControllerState) endCycle(now int64, procs int, userForced bool) {
600 // Record last heap goal for the scavenger.
601 // We'll be updating the heap goal soon.
602 gcController.lastHeapGoal = gcController.heapGoal
604 // Compute the duration of time for which assists were turned on.
605 assistDuration := now - c.markStartTime
607 // Assume background mark hit its utilization goal.
608 utilization := gcBackgroundUtilization
609 // Add assist utilization; avoid divide by zero.
610 if assistDuration > 0 {
611 utilization += float64(c.assistTime) / float64(assistDuration*int64(procs))
614 if c.heapLive <= c.trigger {
615 // Shouldn't happen, but let's be very safe about this in case the
616 // GC is somehow extremely short.
618 // In this case though, the only reasonable value for c.heapLive-c.trigger
619 // would be 0, which isn't really all that useful, i.e. the GC was so short
620 // that it didn't matter.
622 // Ignore this case and don't update anything.
625 idleUtilization := 0.0
626 if assistDuration > 0 {
627 idleUtilization = float64(c.idleMarkTime) / float64(assistDuration*int64(procs))
629 // Determine the cons/mark ratio.
631 // The units we want for the numerator and denominator are both B / cpu-ns.
632 // We get this by taking the bytes allocated or scanned, and divide by the amount of
633 // CPU time it took for those operations. For allocations, that CPU time is
635 // assistDuration * procs * (1 - utilization)
637 // Where utilization includes just background GC workers and assists. It does *not*
638 // include idle GC work time, because in theory the mutator is free to take that at
641 // For scanning, that CPU time is
643 // assistDuration * procs * (utilization + idleUtilization)
645 // In this case, we *include* idle utilization, because that is additional CPU time that the
646 // the GC had available to it.
648 // In effect, idle GC time is sort of double-counted here, but it's very weird compared
649 // to other kinds of GC work, because of how fluid it is. Namely, because the mutator is
650 // *always* free to take it.
652 // So this calculation is really:
653 // (heapLive-trigger) / (assistDuration * procs * (1-utilization)) /
654 // (scanWork) / (assistDuration * procs * (utilization+idleUtilization)
656 // Note that because we only care about the ratio, assistDuration and procs cancel out.
657 scanWork := c.heapScanWork.Load() + c.stackScanWork.Load() + c.globalsScanWork.Load()
658 currentConsMark := (float64(c.heapLive-c.trigger) * (utilization + idleUtilization)) /
659 (float64(scanWork) * (1 - utilization))
661 // Update cons/mark controller. The time period for this is 1 GC cycle.
663 // This use of a PI controller might seem strange. So, here's an explanation:
665 // currentConsMark represents the consMark we *should've* had to be perfectly
666 // on-target for this cycle. Given that we assume the next GC will be like this
667 // one in the steady-state, it stands to reason that we should just pick that
668 // as our next consMark. In practice, however, currentConsMark is too noisy:
669 // we're going to be wildly off-target in each GC cycle if we do that.
671 // What we do instead is make a long-term assumption: there is some steady-state
672 // consMark value, but it's obscured by noise. By constantly shooting for this
673 // noisy-but-perfect consMark value, the controller will bounce around a bit,
674 // but its average behavior, in aggregate, should be less noisy and closer to
675 // the true long-term consMark value, provided its tuned to be slightly overdamped.
677 oldConsMark := c.consMark
678 c.consMark, ok = c.consMarkController.next(c.consMark, currentConsMark, 1.0)
680 // The error spiraled out of control. This is incredibly unlikely seeing
681 // as this controller is essentially just a smoothing function, but it might
682 // mean that something went very wrong with how currentConsMark was calculated.
683 // Just reset consMark and keep going.
687 if debug.gcpacertrace > 0 {
689 goal := gcGoalUtilization * 100
690 print("pacer: ", int(utilization*100), "% CPU (", int(goal), " exp.) for ")
691 print(c.heapScanWork.Load(), "+", c.stackScanWork.Load(), "+", c.globalsScanWork.Load(), " B work (", c.lastHeapScan+c.stackScan+c.globalsScan, " B exp.) ")
692 print("in ", c.trigger, " B -> ", c.heapLive, " B (∆goal ", int64(c.heapLive)-int64(c.heapGoal), ", cons/mark ", oldConsMark, ")")
694 print("[controller reset]")
701 // enlistWorker encourages another dedicated mark worker to start on
702 // another P if there are spare worker slots. It is used by putfull
703 // when more work is made available.
706 func (c *gcControllerState) enlistWorker() {
707 // If there are idle Ps, wake one so it will run an idle worker.
708 // NOTE: This is suspected of causing deadlocks. See golang.org/issue/19112.
710 // if atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 {
715 // There are no idle Ps. If we need more dedicated workers,
716 // try to preempt a running P so it will switch to a worker.
717 if c.dedicatedMarkWorkersNeeded <= 0 {
720 // Pick a random other P to preempt.
725 if gp == nil || gp.m == nil || gp.m.p == 0 {
728 myID := gp.m.p.ptr().id
729 for tries := 0; tries < 5; tries++ {
730 id := int32(fastrandn(uint32(gomaxprocs - 1)))
735 if p.status != _Prunning {
744 // findRunnableGCWorker returns a background mark worker for _p_ if it
745 // should be run. This must only be called when gcBlackenEnabled != 0.
746 func (c *gcControllerState) findRunnableGCWorker(_p_ *p) *g {
747 if gcBlackenEnabled == 0 {
748 throw("gcControllerState.findRunnable: blackening not enabled")
751 if !gcMarkWorkAvailable(_p_) {
752 // No work to be done right now. This can happen at
753 // the end of the mark phase when there are still
754 // assists tapering off. Don't bother running a worker
755 // now because it'll just return immediately.
759 // Grab a worker before we commit to running below.
760 node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
762 // There is at least one worker per P, so normally there are
763 // enough workers to run on all Ps, if necessary. However, once
764 // a worker enters gcMarkDone it may park without rejoining the
765 // pool, thus freeing a P with no corresponding worker.
766 // gcMarkDone never depends on another worker doing work, so it
767 // is safe to simply do nothing here.
769 // If gcMarkDone bails out without completing the mark phase,
770 // it will always do so with queued global work. Thus, that P
771 // will be immediately eligible to re-run the worker G it was
772 // just using, ensuring work can complete.
776 decIfPositive := func(ptr *int64) bool {
778 v := atomic.Loadint64(ptr)
783 if atomic.Casint64(ptr, v, v-1) {
789 if decIfPositive(&c.dedicatedMarkWorkersNeeded) {
790 // This P is now dedicated to marking until the end of
791 // the concurrent mark phase.
792 _p_.gcMarkWorkerMode = gcMarkWorkerDedicatedMode
793 } else if c.fractionalUtilizationGoal == 0 {
794 // No need for fractional workers.
795 gcBgMarkWorkerPool.push(&node.node)
798 // Is this P behind on the fractional utilization
801 // This should be kept in sync with pollFractionalWorkerExit.
802 delta := nanotime() - c.markStartTime
803 if delta > 0 && float64(_p_.gcFractionalMarkTime)/float64(delta) > c.fractionalUtilizationGoal {
804 // Nope. No need to run a fractional worker.
805 gcBgMarkWorkerPool.push(&node.node)
808 // Run a fractional worker.
809 _p_.gcMarkWorkerMode = gcMarkWorkerFractionalMode
812 // Run the background mark worker.
814 casgstatus(gp, _Gwaiting, _Grunnable)
821 // resetLive sets up the controller state for the next mark phase after the end
822 // of the previous one. Must be called after endCycle and before commit, before
823 // the world is started.
825 // The world must be stopped.
826 func (c *gcControllerState) resetLive(bytesMarked uint64) {
827 c.heapMarked = bytesMarked
828 c.heapLive = bytesMarked
829 c.heapScan = uint64(c.heapScanWork.Load())
830 c.lastHeapScan = uint64(c.heapScanWork.Load())
832 // heapLive was updated, so emit a trace event.
838 // markWorkerStop must be called whenever a mark worker stops executing.
840 // It updates mark work accounting in the controller by a duration of
841 // work in nanoseconds and other bookkeeping.
843 // Safe to execute at any time.
844 func (c *gcControllerState) markWorkerStop(mode gcMarkWorkerMode, duration int64) {
846 case gcMarkWorkerDedicatedMode:
847 atomic.Xaddint64(&c.dedicatedMarkTime, duration)
848 atomic.Xaddint64(&c.dedicatedMarkWorkersNeeded, 1)
849 case gcMarkWorkerFractionalMode:
850 atomic.Xaddint64(&c.fractionalMarkTime, duration)
851 case gcMarkWorkerIdleMode:
852 atomic.Xaddint64(&c.idleMarkTime, duration)
853 c.removeIdleMarkWorker()
855 throw("markWorkerStop: unknown mark worker mode")
859 func (c *gcControllerState) update(dHeapLive, dHeapScan int64) {
861 atomic.Xadd64(&gcController.heapLive, dHeapLive)
863 // gcController.heapLive changed.
867 if gcBlackenEnabled == 0 {
868 // Update heapScan when we're not in a current GC. It is fixed
869 // at the beginning of a cycle.
871 atomic.Xadd64(&gcController.heapScan, dHeapScan)
874 // gcController.heapLive changed.
879 func (c *gcControllerState) addScannableStack(pp *p, amount int64) {
881 atomic.Xadd64(&c.scannableStackSize, amount)
884 pp.scannableStackSizeDelta += amount
885 if pp.scannableStackSizeDelta >= scannableStackSizeSlack || pp.scannableStackSizeDelta <= -scannableStackSizeSlack {
886 atomic.Xadd64(&c.scannableStackSize, pp.scannableStackSizeDelta)
887 pp.scannableStackSizeDelta = 0
891 func (c *gcControllerState) addGlobals(amount int64) {
892 atomic.Xadd64(&c.globalsScan, amount)
895 // commit recomputes all pacing parameters from scratch, namely
896 // absolute trigger, the heap goal, mark pacing, and sweep pacing.
898 // This can be called any time. If GC is the in the middle of a
899 // concurrent phase, it will adjust the pacing of that phase.
901 // This depends on gcPercent, gcController.heapMarked, and
902 // gcController.heapLive. These must be up to date.
904 // mheap_.lock must be held or the world must be stopped.
905 func (c *gcControllerState) commit() {
907 assertWorldStoppedOrLockHeld(&mheap_.lock)
910 // Compute the next GC goal, which is when the allocated heap
911 // has grown by GOGC/100 over where it started the last cycle,
912 // plus additional runway for non-heap sources of GC work.
914 if gcPercent := c.gcPercent.Load(); gcPercent >= 0 {
915 goal = c.heapMarked + (c.heapMarked+atomic.Load64(&c.stackScan)+atomic.Load64(&c.globalsScan))*uint64(gcPercent)/100
918 // Don't trigger below the minimum heap size.
919 minTrigger := c.heapMinimum
921 // Concurrent sweep happens in the heap growth
922 // from gcController.heapLive to trigger, so ensure
923 // that concurrent sweep has some heap growth
924 // in which to perform sweeping before we
925 // start the next GC cycle.
926 sweepMin := atomic.Load64(&c.heapLive) + sweepMinHeapDistance
927 if sweepMin > minTrigger {
928 minTrigger = sweepMin
932 // If we let the trigger go too low, then if the application
933 // is allocating very rapidly we might end up in a situation
934 // where we're allocating black during a nearly always-on GC.
935 // The result of this is a growing heap and ultimately an
936 // increase in RSS. By capping us at a point >0, we're essentially
937 // saying that we're OK using more CPU during the GC to prevent
938 // this growth in RSS.
940 // The current constant was chosen empirically: given a sufficiently
941 // fast/scalable allocator with 48 Ps that could drive the trigger ratio
942 // to <0.05, this constant causes applications to retain the same peak
943 // RSS compared to not having this allocator.
944 if triggerBound := uint64(0.7*float64(goal-c.heapMarked)) + c.heapMarked; minTrigger < triggerBound {
945 minTrigger = triggerBound
948 // For small heaps, set the max trigger point at 95% of the heap goal.
949 // This ensures we always have *some* headroom when the GC actually starts.
950 // For larger heaps, set the max trigger point at the goal, minus the
951 // minimum heap size.
952 // This choice follows from the fact that the minimum heap size is chosen
953 // to reflect the costs of a GC with no work to do. With a large heap but
954 // very little scan work to perform, this gives us exactly as much runway
955 // as we would need, in the worst case.
956 maxRunway := uint64(0.95 * float64(goal-c.heapMarked))
957 if largeHeapMaxRunway := goal - c.heapMinimum; goal > c.heapMinimum && maxRunway < largeHeapMaxRunway {
958 maxRunway = largeHeapMaxRunway
960 maxTrigger := maxRunway + c.heapMarked
961 if maxTrigger < minTrigger {
962 maxTrigger = minTrigger
965 // Compute the trigger by using our estimate of the cons/mark ratio.
967 // The idea is to take our expected scan work, and multiply it by
968 // the cons/mark ratio to determine how long it'll take to complete
969 // that scan work in terms of bytes allocated. This gives us our GC's
972 // However, the cons/mark ratio is a ratio of rates per CPU-second, but
973 // here we care about the relative rates for some division of CPU
974 // resources among the mutator and the GC.
976 // To summarize, we have B / cpu-ns, and we want B / ns. We get that
977 // by multiplying by our desired division of CPU resources. We choose
978 // to express CPU resources as GOMAPROCS*fraction. Note that because
979 // we're working with a ratio here, we can omit the number of CPU cores,
980 // because they'll appear in the numerator and denominator and cancel out.
981 // As a result, this is basically just "weighing" the cons/mark ratio by
982 // our desired division of resources.
984 // Furthermore, by setting the trigger so that CPU resources are divided
985 // this way, assuming that the cons/mark ratio is correct, we make that
986 // division a reality.
988 runway := uint64((c.consMark * (1 - gcGoalUtilization) / (gcGoalUtilization)) * float64(c.lastHeapScan+c.stackScan+c.globalsScan))
992 trigger = goal - runway
994 if trigger < minTrigger {
997 if trigger > maxTrigger {
1004 // Commit to the trigger and goal.
1006 atomic.Store64(&c.heapGoal, goal)
1011 // Update mark pacing.
1012 if gcphase != _GCoff {
1017 // effectiveGrowthRatio returns the current effective heap growth
1018 // ratio (GOGC/100) based on heapMarked from the previous GC and
1019 // heapGoal for the current GC.
1021 // This may differ from gcPercent/100 because of various upper and
1022 // lower bounds on gcPercent. For example, if the heap is smaller than
1023 // heapMinimum, this can be higher than gcPercent/100.
1025 // mheap_.lock must be held or the world must be stopped.
1026 func (c *gcControllerState) effectiveGrowthRatio() float64 {
1028 assertWorldStoppedOrLockHeld(&mheap_.lock)
1031 egogc := float64(atomic.Load64(&c.heapGoal)-c.heapMarked) / float64(c.heapMarked)
1033 // Shouldn't happen, but just in case.
1039 // setGCPercent updates gcPercent and all related pacer state.
1040 // Returns the old value of gcPercent.
1042 // Calls gcControllerState.commit.
1044 // The world must be stopped, or mheap_.lock must be held.
1045 func (c *gcControllerState) setGCPercent(in int32) int32 {
1047 assertWorldStoppedOrLockHeld(&mheap_.lock)
1050 out := c.gcPercent.Load()
1054 c.heapMinimum = defaultHeapMinimum * uint64(in) / 100
1055 c.gcPercent.Store(in)
1056 // Update pacing in response to gcPercent change.
1062 //go:linkname setGCPercent runtime/debug.setGCPercent
1063 func setGCPercent(in int32) (out int32) {
1064 // Run on the system stack since we grab the heap lock.
1065 systemstack(func() {
1067 out = gcController.setGCPercent(in)
1068 gcPaceSweeper(gcController.trigger)
1069 gcPaceScavenger(gcController.heapGoal, gcController.lastHeapGoal)
1070 unlock(&mheap_.lock)
1073 // If we just disabled GC, wait for any concurrent GC mark to
1074 // finish so we always return with no GC running.
1076 gcWaitOnMark(atomic.Load(&work.cycles))
1082 func readGOGC() int32 {
1083 p := gogetenv("GOGC")
1087 if n, ok := atoi32(p); ok {
1093 type piController struct {
1094 kp float64 // Proportional constant.
1095 ti float64 // Integral time constant.
1096 tt float64 // Reset time.
1098 min, max float64 // Output boundaries.
1100 // PI controller state.
1102 errIntegral float64 // Integral of the error from t=0 to now.
1105 errOverflow bool // Set if errIntegral ever overflowed.
1106 inputOverflow bool // Set if an operation with the input overflowed.
1109 // next provides a new sample to the controller.
1111 // input is the sample, setpoint is the desired point, and period is how much
1112 // time (in whatever unit makes the most sense) has passed since the last sample.
1114 // Returns a new value for the variable it's controlling, and whether the operation
1115 // completed successfully. One reason this might fail is if error has been growing
1116 // in an unbounded manner, to the point of overflow.
1118 // In the specific case of an error overflow occurs, the errOverflow field will be
1119 // set and the rest of the controller's internal state will be fully reset.
1120 func (c *piController) next(input, setpoint, period float64) (float64, bool) {
1121 // Compute the raw output value.
1122 prop := c.kp * (setpoint - input)
1123 rawOutput := prop + c.errIntegral
1125 // Clamp rawOutput into output.
1127 if isInf(output) || isNaN(output) {
1128 // The input had a large enough magnitude that either it was already
1129 // overflowed, or some operation with it overflowed.
1130 // Set a flag and reset. That's the safest thing to do.
1132 c.inputOverflow = true
1137 } else if output > c.max {
1141 // Update the controller's state.
1142 if c.ti != 0 && c.tt != 0 {
1143 c.errIntegral += (c.kp*period/c.ti)*(setpoint-input) + (period/c.tt)*(output-rawOutput)
1144 if isInf(c.errIntegral) || isNaN(c.errIntegral) {
1145 // So much error has accumulated that we managed to overflow.
1146 // The assumptions around the controller have likely broken down.
1147 // Set a flag and reset. That's the safest thing to do.
1149 c.errOverflow = true
1156 // reset resets the controller state, except for controller error flags.
1157 func (c *piController) reset() {
1161 // addIdleMarkWorker attempts to add a new idle mark worker.
1163 // If this returns true, the caller must become an idle mark worker unless
1164 // there's no background mark worker goroutines in the pool. This case is
1165 // harmless because there are already background mark workers running.
1166 // If this returns false, the caller must NOT become an idle mark worker.
1168 // nosplit because it may be called without a P.
1170 func (c *gcControllerState) addIdleMarkWorker() bool {
1172 old := c.idleMarkWorkers.Load()
1173 n, max := int32(old&uint64(^uint32(0))), int32(old>>32)
1175 // See the comment on idleMarkWorkers for why
1176 // n > max is tolerated.
1180 print("n=", n, " max=", max, "\n")
1181 throw("negative idle mark workers")
1183 new := uint64(uint32(n+1)) | (uint64(max) << 32)
1184 if c.idleMarkWorkers.CompareAndSwap(old, new) {
1190 // needIdleMarkWorker is a hint as to whether another idle mark worker is needed.
1192 // The caller must still call addIdleMarkWorker to become one. This is mainly
1193 // useful for a quick check before an expensive operation.
1195 // nosplit because it may be called without a P.
1197 func (c *gcControllerState) needIdleMarkWorker() bool {
1198 p := c.idleMarkWorkers.Load()
1199 n, max := int32(p&uint64(^uint32(0))), int32(p>>32)
1203 // removeIdleMarkWorker must be called when an new idle mark worker stops executing.
1204 func (c *gcControllerState) removeIdleMarkWorker() {
1206 old := c.idleMarkWorkers.Load()
1207 n, max := int32(old&uint64(^uint32(0))), int32(old>>32)
1209 print("n=", n, " max=", max, "\n")
1210 throw("negative idle mark workers")
1212 new := uint64(uint32(n-1)) | (uint64(max) << 32)
1213 if c.idleMarkWorkers.CompareAndSwap(old, new) {
1219 // setMaxIdleMarkWorkers sets the maximum number of idle mark workers allowed.
1221 // This method is optimistic in that it does not wait for the number of
1222 // idle mark workers to reduce to max before returning; it assumes the workers
1223 // will deschedule themselves.
1224 func (c *gcControllerState) setMaxIdleMarkWorkers(max int32) {
1226 old := c.idleMarkWorkers.Load()
1227 n := int32(old & uint64(^uint32(0)))
1229 print("n=", n, " max=", max, "\n")
1230 throw("negative idle mark workers")
1232 new := uint64(uint32(n)) | (uint64(max) << 32)
1233 if c.idleMarkWorkers.CompareAndSwap(old, new) {