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"
14 // go119MemoryLimitSupport is a feature flag for a number of changes
15 // related to the memory limit feature (#48409). Disabling this flag
16 // disables those features, as well as the memory limit mechanism,
17 // which becomes a no-op.
18 const go119MemoryLimitSupport = true
21 // gcGoalUtilization is the goal CPU utilization for
22 // marking as a fraction of GOMAXPROCS.
24 // Increasing the goal utilization will shorten GC cycles as the GC
25 // has more resources behind it, lessening costs from the write barrier,
26 // but comes at the cost of increasing mutator latency.
27 gcGoalUtilization = gcBackgroundUtilization
29 // gcBackgroundUtilization is the fixed CPU utilization for background
30 // marking. It must be <= gcGoalUtilization. The difference between
31 // gcGoalUtilization and gcBackgroundUtilization will be made up by
32 // mark assists. The scheduler will aim to use within 50% of this
35 // As a general rule, there's little reason to set gcBackgroundUtilization
36 // < gcGoalUtilization. One reason might be in mostly idle applications,
37 // where goroutines are unlikely to assist at all, so the actual
38 // utilization will be lower than the goal. But this is moot point
39 // because the idle mark workers already soak up idle CPU resources.
40 // These two values are still kept separate however because they are
41 // distinct conceptually, and in previous iterations of the pacer the
42 // distinction was more important.
43 gcBackgroundUtilization = 0.25
45 // gcCreditSlack is the amount of scan work credit that can
46 // accumulate locally before updating gcController.heapScanWork and,
47 // optionally, gcController.bgScanCredit. Lower values give a more
48 // accurate assist ratio and make it more likely that assists will
49 // successfully steal background credit. Higher values reduce memory
53 // gcAssistTimeSlack is the nanoseconds of mutator assist time that
54 // can accumulate on a P before updating gcController.assistTime.
55 gcAssistTimeSlack = 5000
57 // gcOverAssistWork determines how many extra units of scan work a GC
58 // assist does when an assist happens. This amortizes the cost of an
59 // assist by pre-paying for this many bytes of future allocations.
60 gcOverAssistWork = 64 << 10
62 // defaultHeapMinimum is the value of heapMinimum for GOGC==100.
63 defaultHeapMinimum = (goexperiment.HeapMinimum512KiBInt)*(512<<10) +
64 (1-goexperiment.HeapMinimum512KiBInt)*(4<<20)
66 // scannableStackSizeSlack is the bytes of stack space allocated or freed
67 // that can accumulate on a P before updating gcController.stackSize.
68 scannableStackSizeSlack = 8 << 10
72 if offset := unsafe.Offsetof(gcController.heapLive); offset%8 != 0 {
74 throw("gcController.heapLive not aligned to 8 bytes")
78 // gcController implements the GC pacing controller that determines
79 // when to trigger concurrent garbage collection and how much marking
80 // work to do in mutator assists and background marking.
82 // It calculates the ratio between the allocation rate (in terms of CPU
83 // time) and the GC scan throughput to determine the heap size at which to
84 // trigger a GC cycle such that no GC assists are required to finish on time.
85 // This algorithm thus optimizes GC CPU utilization to the dedicated background
86 // mark utilization of 25% of GOMAXPROCS by minimizing GC assists.
87 // GOMAXPROCS. The high-level design of this algorithm is documented
88 // at https://github.com/golang/proposal/blob/master/design/44167-gc-pacer-redesign.md.
89 // See https://golang.org/s/go15gcpacing for additional historical context.
90 var gcController gcControllerState
92 type gcControllerState struct {
94 // Initialized from GOGC. GOGC=off means no GC.
95 gcPercent atomic.Int32
97 _ uint32 // padding so following 64-bit values are 8-byte aligned
99 // heapMinimum is the minimum heap size at which to trigger GC.
100 // For small heaps, this overrides the usual GOGC*live set rule.
102 // When there is a very small live set but a lot of allocation, simply
103 // collecting when the heap reaches GOGC*live results in many GC
104 // cycles and high total per-GC overhead. This minimum amortizes this
105 // per-GC overhead while keeping the heap reasonably small.
107 // During initialization this is set to 4MB*GOGC/100. In the case of
108 // GOGC==0, this will set heapMinimum to 0, resulting in constant
109 // collection even when the heap size is small, which is useful for
113 // trigger is the heap size that triggers marking.
115 // When heapLive ≥ trigger, the mark phase will start.
116 // This is also the heap size by which proportional sweeping
119 // This is computed from consMark during mark termination for
120 // the next cycle's trigger.
122 // Protected by mheap_.lock or a STW.
125 // consMark is the estimated per-CPU consMark ratio for the application.
127 // It represents the ratio between the application's allocation
128 // rate, as bytes allocated per CPU-time, and the GC's scan rate,
129 // as bytes scanned per CPU-time.
130 // The units of this ratio are (B / cpu-ns) / (B / cpu-ns).
132 // At a high level, this value is computed as the bytes of memory
133 // allocated (cons) per unit of scan work completed (mark) in a GC
134 // cycle, divided by the CPU time spent on each activity.
136 // Updated at the end of each GC cycle, in endCycle.
139 // consMarkController holds the state for the mark-cons ratio
140 // estimation over time.
142 // Its purpose is to smooth out noisiness in the computation of
143 // consMark; see consMark for details.
144 consMarkController piController
146 _ uint32 // Padding for atomics on 32-bit platforms.
148 // heapGoal is the goal heapLive for when next GC ends.
149 // Set to ^uint64(0) if disabled.
151 // Read and written atomically, unless the world is stopped.
154 // lastHeapGoal is the value of heapGoal for the previous GC.
155 // Note that this is distinct from the last value heapGoal had,
156 // because it could change if e.g. gcPercent changes.
158 // Read and written with the world stopped or with mheap_.lock held.
161 // heapLive is the number of bytes considered live by the GC.
162 // That is: retained by the most recent GC plus allocated
163 // since then. heapLive ≤ memstats.heapAlloc, since heapAlloc includes
164 // unmarked objects that have not yet been swept (and hence goes up as we
165 // allocate and down as we sweep) while heapLive excludes these
166 // objects (and hence only goes up between GCs).
168 // This is updated atomically without locking. To reduce
169 // contention, this is updated only when obtaining a span from
170 // an mcentral and at this point it counts all of the
171 // unallocated slots in that span (which will be allocated
172 // before that mcache obtains another span from that
173 // mcentral). Hence, it slightly overestimates the "true" live
174 // heap size. It's better to overestimate than to
175 // underestimate because 1) this triggers the GC earlier than
176 // necessary rather than potentially too late and 2) this
177 // leads to a conservative GC rate rather than a GC rate that
178 // is potentially too low.
180 // Reads should likewise be atomic (or during STW).
182 // Whenever this is updated, call traceHeapAlloc() and
183 // this gcControllerState's revise() method.
186 // heapScan is the number of bytes of "scannable" heap. This
187 // is the live heap (as counted by heapLive), but omitting
188 // no-scan objects and no-scan tails of objects.
190 // This value is fixed at the start of a GC cycle, so during a
191 // GC cycle it is safe to read without atomics, and it represents
192 // the maximum scannable heap.
195 // lastHeapScan is the number of bytes of heap that were scanned
196 // last GC cycle. It is the same as heapMarked, but only
197 // includes the "scannable" parts of objects.
199 // Updated when the world is stopped.
202 // stackScan is a snapshot of scannableStackSize taken at each GC
203 // STW pause and is used in pacing decisions.
205 // Updated only while the world is stopped.
208 // scannableStackSize is the amount of allocated goroutine stack space in
209 // use by goroutines.
211 // This number tracks allocated goroutine stack space rather than used
212 // goroutine stack space (i.e. what is actually scanned) because used
213 // goroutine stack space is much harder to measure cheaply. By using
214 // allocated space, we make an overestimate; this is OK, it's better
215 // to conservatively overcount than undercount.
217 // Read and updated atomically.
218 scannableStackSize uint64
220 // globalsScan is the total amount of global variable space
221 // that is scannable.
223 // Read and updated atomically.
226 // heapMarked is the number of bytes marked by the previous
227 // GC. After mark termination, heapLive == heapMarked, but
228 // unlike heapLive, heapMarked does not change until the
229 // next mark termination.
232 // heapScanWork is the total heap scan work performed this cycle.
233 // stackScanWork is the total stack scan work performed this cycle.
234 // globalsScanWork is the total globals scan work performed this cycle.
236 // These are updated atomically during the cycle. Updates occur in
237 // bounded batches, since they are both written and read
238 // throughout the cycle. At the end of the cycle, heapScanWork is how
239 // much of the retained heap is scannable.
241 // Currently these are measured in bytes. For most uses, this is an
242 // opaque unit of work, but for estimation the definition is important.
244 // Note that stackScanWork includes all allocated space, not just the
245 // size of the stack itself, mirroring stackSize.
246 heapScanWork atomic.Int64
247 stackScanWork atomic.Int64
248 globalsScanWork atomic.Int64
250 // bgScanCredit is the scan work credit accumulated by the
251 // concurrent background scan. This credit is accumulated by
252 // the background scan and stolen by mutator assists. This is
253 // updated atomically. Updates occur in bounded batches, since
254 // it is both written and read throughout the cycle.
257 // assistTime is the nanoseconds spent in mutator assists
258 // during this cycle. This is updated atomically, and must also
259 // be updated atomically even during a STW, because it is read
260 // by sysmon. Updates occur in bounded batches, since it is both
261 // written and read throughout the cycle.
262 assistTime atomic.Int64
264 // dedicatedMarkTime is the nanoseconds spent in dedicated
265 // mark workers during this cycle. This is updated atomically
266 // at the end of the concurrent mark phase.
267 dedicatedMarkTime int64
269 // fractionalMarkTime is the nanoseconds spent in the
270 // fractional mark worker during this cycle. This is updated
271 // atomically throughout the cycle and will be up-to-date if
272 // the fractional mark worker is not currently running.
273 fractionalMarkTime int64
275 // idleMarkTime is the nanoseconds spent in idle marking
276 // during this cycle. This is updated atomically throughout
280 // markStartTime is the absolute start time in nanoseconds
281 // that assists and background mark workers started.
284 // dedicatedMarkWorkersNeeded is the number of dedicated mark
285 // workers that need to be started. This is computed at the
286 // beginning of each cycle and decremented atomically as
287 // dedicated mark workers get started.
288 dedicatedMarkWorkersNeeded int64
290 // idleMarkWorkers is two packed int32 values in a single uint64.
291 // These two values are always updated simultaneously.
293 // The bottom int32 is the current number of idle mark workers executing.
295 // The top int32 is the maximum number of idle mark workers allowed to
296 // execute concurrently. Normally, this number is just gomaxprocs. However,
297 // during periodic GC cycles it is set to 0 because the system is idle
298 // anyway; there's no need to go full blast on all of GOMAXPROCS.
300 // The maximum number of idle mark workers is used to prevent new workers
301 // from starting, but it is not a hard maximum. It is possible (but
302 // exceedingly rare) for the current number of idle mark workers to
303 // transiently exceed the maximum. This could happen if the maximum changes
304 // just after a GC ends, and an M with no P.
306 // Note that if we have no dedicated mark workers, we set this value to
307 // 1 in this case we only have fractional GC workers which aren't scheduled
308 // strictly enough to ensure GC progress. As a result, idle-priority mark
309 // workers are vital to GC progress in these situations.
311 // For example, consider a situation in which goroutines block on the GC
312 // (such as via runtime.GOMAXPROCS) and only fractional mark workers are
313 // scheduled (e.g. GOMAXPROCS=1). Without idle-priority mark workers, the
314 // last running M might skip scheduling a fractional mark worker if its
315 // utilization goal is met, such that once it goes to sleep (because there's
316 // nothing to do), there will be nothing else to spin up a new M for the
317 // fractional worker in the future, stalling GC progress and causing a
318 // deadlock. However, idle-priority workers will *always* run when there is
319 // nothing left to do, ensuring the GC makes progress.
321 // See github.com/golang/go/issues/44163 for more details.
322 idleMarkWorkers atomic.Uint64
324 // assistWorkPerByte is the ratio of scan work to allocated
325 // bytes that should be performed by mutator assists. This is
326 // computed at the beginning of each cycle and updated every
327 // time heapScan is updated.
328 assistWorkPerByte atomic.Float64
330 // assistBytesPerWork is 1/assistWorkPerByte.
332 // Note that because this is read and written independently
333 // from assistWorkPerByte users may notice a skew between
334 // the two values, and such a state should be safe.
335 assistBytesPerWork atomic.Float64
337 // fractionalUtilizationGoal is the fraction of wall clock
338 // time that should be spent in the fractional mark worker on
339 // each P that isn't running a dedicated worker.
341 // For example, if the utilization goal is 25% and there are
342 // no dedicated workers, this will be 0.25. If the goal is
343 // 25%, there is one dedicated worker, and GOMAXPROCS is 5,
344 // this will be 0.05 to make up the missing 5%.
346 // If this is zero, no fractional workers are needed.
347 fractionalUtilizationGoal float64
349 // test indicates that this is a test-only copy of gcControllerState.
355 func (c *gcControllerState) init(gcPercent int32) {
356 c.heapMinimum = defaultHeapMinimum
358 c.consMarkController = piController{
359 // Tuned first via the Ziegler-Nichols process in simulation,
360 // then the integral time was manually tuned against real-world
361 // applications to deal with noisiness in the measured cons/mark
366 // Set a high reset time in GC cycles.
367 // This is inversely proportional to the rate at which we
368 // accumulate error from clipping. By making this very high
369 // we make the accumulation slow. In general, clipping is
370 // OK in our situation, hence the choice.
372 // Tune this if we get unintended effects from clipping for
379 // This will also compute and set the GC trigger and goal.
380 c.setGCPercent(gcPercent)
383 // startCycle resets the GC controller's state and computes estimates
384 // for a new GC cycle. The caller must hold worldsema and the world
386 func (c *gcControllerState) startCycle(markStartTime int64, procs int, trigger gcTrigger) {
387 c.heapScanWork.Store(0)
388 c.stackScanWork.Store(0)
389 c.globalsScanWork.Store(0)
391 c.assistTime.Store(0)
392 c.dedicatedMarkTime = 0
393 c.fractionalMarkTime = 0
395 c.markStartTime = markStartTime
396 c.stackScan = atomic.Load64(&c.scannableStackSize)
398 // Ensure that the heap goal is at least a little larger than
399 // the current live heap size. This may not be the case if GC
400 // start is delayed or if the allocation that pushed gcController.heapLive
401 // over trigger is large or if the trigger is really close to
402 // GOGC. Assist is proportional to this distance, so enforce a
403 // minimum distance, even if it means going over the GOGC goal
405 if c.heapGoal < c.heapLive+64<<10 {
406 c.heapGoal = c.heapLive + 64<<10
409 // Compute the background mark utilization goal. In general,
410 // this may not come out exactly. We round the number of
411 // dedicated workers so that the utilization is closest to
412 // 25%. For small GOMAXPROCS, this would introduce too much
413 // error, so we add fractional workers in that case.
414 totalUtilizationGoal := float64(procs) * gcBackgroundUtilization
415 c.dedicatedMarkWorkersNeeded = int64(totalUtilizationGoal + 0.5)
416 utilError := float64(c.dedicatedMarkWorkersNeeded)/totalUtilizationGoal - 1
417 const maxUtilError = 0.3
418 if utilError < -maxUtilError || utilError > maxUtilError {
419 // Rounding put us more than 30% off our goal. With
420 // gcBackgroundUtilization of 25%, this happens for
421 // GOMAXPROCS<=3 or GOMAXPROCS=6. Enable fractional
422 // workers to compensate.
423 if float64(c.dedicatedMarkWorkersNeeded) > totalUtilizationGoal {
424 // Too many dedicated workers.
425 c.dedicatedMarkWorkersNeeded--
427 c.fractionalUtilizationGoal = (totalUtilizationGoal - float64(c.dedicatedMarkWorkersNeeded)) / float64(procs)
429 c.fractionalUtilizationGoal = 0
432 // In STW mode, we just want dedicated workers.
433 if debug.gcstoptheworld > 0 {
434 c.dedicatedMarkWorkersNeeded = int64(procs)
435 c.fractionalUtilizationGoal = 0
439 for _, p := range allp {
441 p.gcFractionalMarkTime = 0
444 if trigger.kind == gcTriggerTime {
445 // During a periodic GC cycle, reduce the number of idle mark workers
446 // required. However, we need at least one dedicated mark worker or
447 // idle GC worker to ensure GC progress in some scenarios (see comment
448 // on maxIdleMarkWorkers).
449 if c.dedicatedMarkWorkersNeeded > 0 {
450 c.setMaxIdleMarkWorkers(0)
452 // TODO(mknyszek): The fundamental reason why we need this is because
453 // we can't count on the fractional mark worker to get scheduled.
454 // Fix that by ensuring it gets scheduled according to its quota even
455 // if the rest of the application is idle.
456 c.setMaxIdleMarkWorkers(1)
459 // N.B. gomaxprocs and dedicatedMarkWorkersNeeded is guaranteed not to
460 // change during a GC cycle.
461 c.setMaxIdleMarkWorkers(int32(procs) - int32(c.dedicatedMarkWorkersNeeded))
464 // Compute initial values for controls that are updated
465 // throughout the cycle.
468 if debug.gcpacertrace > 0 {
469 assistRatio := c.assistWorkPerByte.Load()
470 print("pacer: assist ratio=", assistRatio,
471 " (scan ", gcController.heapScan>>20, " MB in ",
472 work.initialHeapLive>>20, "->",
473 c.heapGoal>>20, " MB)",
474 " workers=", c.dedicatedMarkWorkersNeeded,
475 "+", c.fractionalUtilizationGoal, "\n")
479 // revise updates the assist ratio during the GC cycle to account for
480 // improved estimates. This should be called whenever gcController.heapScan,
481 // gcController.heapLive, or gcController.heapGoal is updated. It is safe to
482 // call concurrently, but it may race with other calls to revise.
484 // The result of this race is that the two assist ratio values may not line
485 // up or may be stale. In practice this is OK because the assist ratio
486 // moves slowly throughout a GC cycle, and the assist ratio is a best-effort
487 // heuristic anyway. Furthermore, no part of the heuristic depends on
488 // the two assist ratio values being exact reciprocals of one another, since
489 // the two values are used to convert values from different sources.
491 // The worst case result of this raciness is that we may miss a larger shift
492 // in the ratio (say, if we decide to pace more aggressively against the
493 // hard heap goal) but even this "hard goal" is best-effort (see #40460).
494 // The dedicated GC should ensure we don't exceed the hard goal by too much
495 // in the rare case we do exceed it.
497 // It should only be called when gcBlackenEnabled != 0 (because this
498 // is when assists are enabled and the necessary statistics are
500 func (c *gcControllerState) revise() {
501 gcPercent := c.gcPercent.Load()
503 // If GC is disabled but we're running a forced GC,
504 // act like GOGC is huge for the below calculations.
507 live := atomic.Load64(&c.heapLive)
508 scan := atomic.Load64(&c.heapScan)
509 work := c.heapScanWork.Load() + c.stackScanWork.Load() + c.globalsScanWork.Load()
511 // Assume we're under the soft goal. Pace GC to complete at
512 // heapGoal assuming the heap is in steady-state.
513 heapGoal := int64(atomic.Load64(&c.heapGoal))
515 // The expected scan work is computed as the amount of bytes scanned last
516 // GC cycle, plus our estimate of stacks and globals work for this cycle.
517 scanWorkExpected := int64(c.lastHeapScan + c.stackScan + c.globalsScan)
519 // maxScanWork is a worst-case estimate of the amount of scan work that
520 // needs to be performed in this GC cycle. Specifically, it represents
521 // the case where *all* scannable memory turns out to be live.
522 maxScanWork := int64(scan + c.stackScan + c.globalsScan)
523 if work > scanWorkExpected {
524 // We've already done more scan work than expected. Because our expectation
525 // is based on a steady-state scannable heap size, we assume this means our
526 // heap is growing. Compute a new heap goal that takes our existing runway
527 // computed for scanWorkExpected and extrapolates it to maxScanWork, the worst-case
528 // scan work. This keeps our assist ratio stable if the heap continues to grow.
530 // The effect of this mechanism is that assists stay flat in the face of heap
531 // growths. It's OK to use more memory this cycle to scan all the live heap,
532 // because the next GC cycle is inevitably going to use *at least* that much
534 extHeapGoal := int64(float64(heapGoal-int64(c.trigger))/float64(scanWorkExpected)*float64(maxScanWork)) + int64(c.trigger)
535 scanWorkExpected = maxScanWork
537 // hardGoal is a hard limit on the amount that we're willing to push back the
538 // heap goal, and that's twice the heap goal (i.e. if GOGC=100 and the heap and/or
539 // stacks and/or globals grow to twice their size, this limits the current GC cycle's
540 // growth to 4x the original live heap's size).
542 // This maintains the invariant that we use no more memory than the next GC cycle
544 hardGoal := int64((1.0 + float64(gcPercent)/100.0) * float64(heapGoal))
545 if extHeapGoal > hardGoal {
546 extHeapGoal = hardGoal
548 heapGoal = extHeapGoal
550 if int64(live) > heapGoal {
551 // We're already past our heap goal, even the extrapolated one.
552 // Leave ourselves some extra runway, so in the worst case we
553 // finish by that point.
554 const maxOvershoot = 1.1
555 heapGoal = int64(float64(heapGoal) * maxOvershoot)
557 // Compute the upper bound on the scan work remaining.
558 scanWorkExpected = maxScanWork
561 // Compute the remaining scan work estimate.
563 // Note that we currently count allocations during GC as both
564 // scannable heap (heapScan) and scan work completed
565 // (scanWork), so allocation will change this difference
566 // slowly in the soft regime and not at all in the hard
568 scanWorkRemaining := scanWorkExpected - work
569 if scanWorkRemaining < 1000 {
570 // We set a somewhat arbitrary lower bound on
571 // remaining scan work since if we aim a little high,
572 // we can miss by a little.
574 // We *do* need to enforce that this is at least 1,
575 // since marking is racy and double-scanning objects
576 // may legitimately make the remaining scan work
577 // negative, even in the hard goal regime.
578 scanWorkRemaining = 1000
581 // Compute the heap distance remaining.
582 heapRemaining := heapGoal - int64(live)
583 if heapRemaining <= 0 {
584 // This shouldn't happen, but if it does, avoid
585 // dividing by zero or setting the assist negative.
589 // Compute the mutator assist ratio so by the time the mutator
590 // allocates the remaining heap bytes up to heapGoal, it will
591 // have done (or stolen) the remaining amount of scan work.
592 // Note that the assist ratio values are updated atomically
593 // but not together. This means there may be some degree of
594 // skew between the two values. This is generally OK as the
595 // values shift relatively slowly over the course of a GC
597 assistWorkPerByte := float64(scanWorkRemaining) / float64(heapRemaining)
598 assistBytesPerWork := float64(heapRemaining) / float64(scanWorkRemaining)
599 c.assistWorkPerByte.Store(assistWorkPerByte)
600 c.assistBytesPerWork.Store(assistBytesPerWork)
603 // endCycle computes the consMark estimate for the next cycle.
604 // userForced indicates whether the current GC cycle was forced
605 // by the application.
606 func (c *gcControllerState) endCycle(now int64, procs int, userForced bool) {
607 // Record last heap goal for the scavenger.
608 // We'll be updating the heap goal soon.
609 gcController.lastHeapGoal = gcController.heapGoal
611 // Compute the duration of time for which assists were turned on.
612 assistDuration := now - c.markStartTime
614 // Assume background mark hit its utilization goal.
615 utilization := gcBackgroundUtilization
616 // Add assist utilization; avoid divide by zero.
617 if assistDuration > 0 {
618 utilization += float64(c.assistTime.Load()) / float64(assistDuration*int64(procs))
621 if c.heapLive <= c.trigger {
622 // Shouldn't happen, but let's be very safe about this in case the
623 // GC is somehow extremely short.
625 // In this case though, the only reasonable value for c.heapLive-c.trigger
626 // would be 0, which isn't really all that useful, i.e. the GC was so short
627 // that it didn't matter.
629 // Ignore this case and don't update anything.
632 idleUtilization := 0.0
633 if assistDuration > 0 {
634 idleUtilization = float64(c.idleMarkTime) / float64(assistDuration*int64(procs))
636 // Determine the cons/mark ratio.
638 // The units we want for the numerator and denominator are both B / cpu-ns.
639 // We get this by taking the bytes allocated or scanned, and divide by the amount of
640 // CPU time it took for those operations. For allocations, that CPU time is
642 // assistDuration * procs * (1 - utilization)
644 // Where utilization includes just background GC workers and assists. It does *not*
645 // include idle GC work time, because in theory the mutator is free to take that at
648 // For scanning, that CPU time is
650 // assistDuration * procs * (utilization + idleUtilization)
652 // In this case, we *include* idle utilization, because that is additional CPU time that the
653 // the GC had available to it.
655 // In effect, idle GC time is sort of double-counted here, but it's very weird compared
656 // to other kinds of GC work, because of how fluid it is. Namely, because the mutator is
657 // *always* free to take it.
659 // So this calculation is really:
660 // (heapLive-trigger) / (assistDuration * procs * (1-utilization)) /
661 // (scanWork) / (assistDuration * procs * (utilization+idleUtilization)
663 // Note that because we only care about the ratio, assistDuration and procs cancel out.
664 scanWork := c.heapScanWork.Load() + c.stackScanWork.Load() + c.globalsScanWork.Load()
665 currentConsMark := (float64(c.heapLive-c.trigger) * (utilization + idleUtilization)) /
666 (float64(scanWork) * (1 - utilization))
668 // Update cons/mark controller. The time period for this is 1 GC cycle.
670 // This use of a PI controller might seem strange. So, here's an explanation:
672 // currentConsMark represents the consMark we *should've* had to be perfectly
673 // on-target for this cycle. Given that we assume the next GC will be like this
674 // one in the steady-state, it stands to reason that we should just pick that
675 // as our next consMark. In practice, however, currentConsMark is too noisy:
676 // we're going to be wildly off-target in each GC cycle if we do that.
678 // What we do instead is make a long-term assumption: there is some steady-state
679 // consMark value, but it's obscured by noise. By constantly shooting for this
680 // noisy-but-perfect consMark value, the controller will bounce around a bit,
681 // but its average behavior, in aggregate, should be less noisy and closer to
682 // the true long-term consMark value, provided its tuned to be slightly overdamped.
684 oldConsMark := c.consMark
685 c.consMark, ok = c.consMarkController.next(c.consMark, currentConsMark, 1.0)
687 // The error spiraled out of control. This is incredibly unlikely seeing
688 // as this controller is essentially just a smoothing function, but it might
689 // mean that something went very wrong with how currentConsMark was calculated.
690 // Just reset consMark and keep going.
694 if debug.gcpacertrace > 0 {
696 goal := gcGoalUtilization * 100
697 print("pacer: ", int(utilization*100), "% CPU (", int(goal), " exp.) for ")
698 print(c.heapScanWork.Load(), "+", c.stackScanWork.Load(), "+", c.globalsScanWork.Load(), " B work (", c.lastHeapScan+c.stackScan+c.globalsScan, " B exp.) ")
699 print("in ", c.trigger, " B -> ", c.heapLive, " B (∆goal ", int64(c.heapLive)-int64(c.heapGoal), ", cons/mark ", oldConsMark, ")")
701 print("[controller reset]")
708 // enlistWorker encourages another dedicated mark worker to start on
709 // another P if there are spare worker slots. It is used by putfull
710 // when more work is made available.
713 func (c *gcControllerState) enlistWorker() {
714 // If there are idle Ps, wake one so it will run an idle worker.
715 // NOTE: This is suspected of causing deadlocks. See golang.org/issue/19112.
717 // if atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 {
722 // There are no idle Ps. If we need more dedicated workers,
723 // try to preempt a running P so it will switch to a worker.
724 if c.dedicatedMarkWorkersNeeded <= 0 {
727 // Pick a random other P to preempt.
732 if gp == nil || gp.m == nil || gp.m.p == 0 {
735 myID := gp.m.p.ptr().id
736 for tries := 0; tries < 5; tries++ {
737 id := int32(fastrandn(uint32(gomaxprocs - 1)))
742 if p.status != _Prunning {
751 // findRunnableGCWorker returns a background mark worker for _p_ if it
752 // should be run. This must only be called when gcBlackenEnabled != 0.
753 func (c *gcControllerState) findRunnableGCWorker(_p_ *p, now int64) *g {
754 if gcBlackenEnabled == 0 {
755 throw("gcControllerState.findRunnable: blackening not enabled")
758 // Since we have the current time, check if the GC CPU limiter
759 // hasn't had an update in a while. This check is necessary in
760 // case the limiter is on but hasn't been checked in a while and
761 // so may have left sufficient headroom to turn off again.
762 if gcCPULimiter.needUpdate(now) {
763 gcCPULimiter.update(gcController.assistTime.Load(), now)
766 if !gcMarkWorkAvailable(_p_) {
767 // No work to be done right now. This can happen at
768 // the end of the mark phase when there are still
769 // assists tapering off. Don't bother running a worker
770 // now because it'll just return immediately.
774 // Grab a worker before we commit to running below.
775 node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
777 // There is at least one worker per P, so normally there are
778 // enough workers to run on all Ps, if necessary. However, once
779 // a worker enters gcMarkDone it may park without rejoining the
780 // pool, thus freeing a P with no corresponding worker.
781 // gcMarkDone never depends on another worker doing work, so it
782 // is safe to simply do nothing here.
784 // If gcMarkDone bails out without completing the mark phase,
785 // it will always do so with queued global work. Thus, that P
786 // will be immediately eligible to re-run the worker G it was
787 // just using, ensuring work can complete.
791 decIfPositive := func(ptr *int64) bool {
793 v := atomic.Loadint64(ptr)
798 if atomic.Casint64(ptr, v, v-1) {
804 if decIfPositive(&c.dedicatedMarkWorkersNeeded) {
805 // This P is now dedicated to marking until the end of
806 // the concurrent mark phase.
807 _p_.gcMarkWorkerMode = gcMarkWorkerDedicatedMode
808 } else if c.fractionalUtilizationGoal == 0 {
809 // No need for fractional workers.
810 gcBgMarkWorkerPool.push(&node.node)
813 // Is this P behind on the fractional utilization
816 // This should be kept in sync with pollFractionalWorkerExit.
817 delta := now - c.markStartTime
818 if delta > 0 && float64(_p_.gcFractionalMarkTime)/float64(delta) > c.fractionalUtilizationGoal {
819 // Nope. No need to run a fractional worker.
820 gcBgMarkWorkerPool.push(&node.node)
823 // Run a fractional worker.
824 _p_.gcMarkWorkerMode = gcMarkWorkerFractionalMode
827 // Run the background mark worker.
829 casgstatus(gp, _Gwaiting, _Grunnable)
836 // resetLive sets up the controller state for the next mark phase after the end
837 // of the previous one. Must be called after endCycle and before commit, before
838 // the world is started.
840 // The world must be stopped.
841 func (c *gcControllerState) resetLive(bytesMarked uint64) {
842 c.heapMarked = bytesMarked
843 c.heapLive = bytesMarked
844 c.heapScan = uint64(c.heapScanWork.Load())
845 c.lastHeapScan = uint64(c.heapScanWork.Load())
847 // heapLive was updated, so emit a trace event.
853 // markWorkerStop must be called whenever a mark worker stops executing.
855 // It updates mark work accounting in the controller by a duration of
856 // work in nanoseconds and other bookkeeping.
858 // Safe to execute at any time.
859 func (c *gcControllerState) markWorkerStop(mode gcMarkWorkerMode, duration int64) {
861 case gcMarkWorkerDedicatedMode:
862 atomic.Xaddint64(&c.dedicatedMarkTime, duration)
863 atomic.Xaddint64(&c.dedicatedMarkWorkersNeeded, 1)
864 case gcMarkWorkerFractionalMode:
865 atomic.Xaddint64(&c.fractionalMarkTime, duration)
866 case gcMarkWorkerIdleMode:
867 atomic.Xaddint64(&c.idleMarkTime, duration)
868 c.removeIdleMarkWorker()
870 throw("markWorkerStop: unknown mark worker mode")
874 func (c *gcControllerState) update(dHeapLive, dHeapScan int64) {
876 atomic.Xadd64(&gcController.heapLive, dHeapLive)
878 // gcController.heapLive changed.
882 if gcBlackenEnabled == 0 {
883 // Update heapScan when we're not in a current GC. It is fixed
884 // at the beginning of a cycle.
886 atomic.Xadd64(&gcController.heapScan, dHeapScan)
889 // gcController.heapLive changed.
894 func (c *gcControllerState) addScannableStack(pp *p, amount int64) {
896 atomic.Xadd64(&c.scannableStackSize, amount)
899 pp.scannableStackSizeDelta += amount
900 if pp.scannableStackSizeDelta >= scannableStackSizeSlack || pp.scannableStackSizeDelta <= -scannableStackSizeSlack {
901 atomic.Xadd64(&c.scannableStackSize, pp.scannableStackSizeDelta)
902 pp.scannableStackSizeDelta = 0
906 func (c *gcControllerState) addGlobals(amount int64) {
907 atomic.Xadd64(&c.globalsScan, amount)
910 // commit recomputes all pacing parameters from scratch, namely
911 // absolute trigger, the heap goal, mark pacing, and sweep pacing.
913 // This can be called any time. If GC is the in the middle of a
914 // concurrent phase, it will adjust the pacing of that phase.
916 // This depends on gcPercent, gcController.heapMarked, and
917 // gcController.heapLive. These must be up to date.
919 // mheap_.lock must be held or the world must be stopped.
920 func (c *gcControllerState) commit() {
922 assertWorldStoppedOrLockHeld(&mheap_.lock)
925 // Compute the next GC goal, which is when the allocated heap
926 // has grown by GOGC/100 over where it started the last cycle,
927 // plus additional runway for non-heap sources of GC work.
929 if gcPercent := c.gcPercent.Load(); gcPercent >= 0 {
930 goal = c.heapMarked + (c.heapMarked+atomic.Load64(&c.stackScan)+atomic.Load64(&c.globalsScan))*uint64(gcPercent)/100
933 // Don't trigger below the minimum heap size.
934 minTrigger := c.heapMinimum
936 // Concurrent sweep happens in the heap growth
937 // from gcController.heapLive to trigger, so ensure
938 // that concurrent sweep has some heap growth
939 // in which to perform sweeping before we
940 // start the next GC cycle.
941 sweepMin := atomic.Load64(&c.heapLive) + sweepMinHeapDistance
942 if sweepMin > minTrigger {
943 minTrigger = sweepMin
947 // If we let the trigger go too low, then if the application
948 // is allocating very rapidly we might end up in a situation
949 // where we're allocating black during a nearly always-on GC.
950 // The result of this is a growing heap and ultimately an
951 // increase in RSS. By capping us at a point >0, we're essentially
952 // saying that we're OK using more CPU during the GC to prevent
953 // this growth in RSS.
955 // The current constant was chosen empirically: given a sufficiently
956 // fast/scalable allocator with 48 Ps that could drive the trigger ratio
957 // to <0.05, this constant causes applications to retain the same peak
958 // RSS compared to not having this allocator.
959 if triggerBound := uint64(0.7*float64(goal-c.heapMarked)) + c.heapMarked; minTrigger < triggerBound {
960 minTrigger = triggerBound
963 // For small heaps, set the max trigger point at 95% of the heap goal.
964 // This ensures we always have *some* headroom when the GC actually starts.
965 // For larger heaps, set the max trigger point at the goal, minus the
966 // minimum heap size.
967 // This choice follows from the fact that the minimum heap size is chosen
968 // to reflect the costs of a GC with no work to do. With a large heap but
969 // very little scan work to perform, this gives us exactly as much runway
970 // as we would need, in the worst case.
971 maxRunway := uint64(0.95 * float64(goal-c.heapMarked))
972 if largeHeapMaxRunway := goal - c.heapMinimum; goal > c.heapMinimum && maxRunway < largeHeapMaxRunway {
973 maxRunway = largeHeapMaxRunway
975 maxTrigger := maxRunway + c.heapMarked
976 if maxTrigger < minTrigger {
977 maxTrigger = minTrigger
980 // Compute the trigger by using our estimate of the cons/mark ratio.
982 // The idea is to take our expected scan work, and multiply it by
983 // the cons/mark ratio to determine how long it'll take to complete
984 // that scan work in terms of bytes allocated. This gives us our GC's
987 // However, the cons/mark ratio is a ratio of rates per CPU-second, but
988 // here we care about the relative rates for some division of CPU
989 // resources among the mutator and the GC.
991 // To summarize, we have B / cpu-ns, and we want B / ns. We get that
992 // by multiplying by our desired division of CPU resources. We choose
993 // to express CPU resources as GOMAPROCS*fraction. Note that because
994 // we're working with a ratio here, we can omit the number of CPU cores,
995 // because they'll appear in the numerator and denominator and cancel out.
996 // As a result, this is basically just "weighing" the cons/mark ratio by
997 // our desired division of resources.
999 // Furthermore, by setting the trigger so that CPU resources are divided
1000 // this way, assuming that the cons/mark ratio is correct, we make that
1001 // division a reality.
1003 runway := uint64((c.consMark * (1 - gcGoalUtilization) / (gcGoalUtilization)) * float64(c.lastHeapScan+c.stackScan+c.globalsScan))
1005 trigger = minTrigger
1007 trigger = goal - runway
1009 if trigger < minTrigger {
1010 trigger = minTrigger
1012 if trigger > maxTrigger {
1013 trigger = maxTrigger
1019 // Commit to the trigger and goal.
1021 atomic.Store64(&c.heapGoal, goal)
1026 // Update mark pacing.
1027 if gcphase != _GCoff {
1032 // effectiveGrowthRatio returns the current effective heap growth
1033 // ratio (GOGC/100) based on heapMarked from the previous GC and
1034 // heapGoal for the current GC.
1036 // This may differ from gcPercent/100 because of various upper and
1037 // lower bounds on gcPercent. For example, if the heap is smaller than
1038 // heapMinimum, this can be higher than gcPercent/100.
1040 // mheap_.lock must be held or the world must be stopped.
1041 func (c *gcControllerState) effectiveGrowthRatio() float64 {
1043 assertWorldStoppedOrLockHeld(&mheap_.lock)
1046 egogc := float64(atomic.Load64(&c.heapGoal)-c.heapMarked) / float64(c.heapMarked)
1048 // Shouldn't happen, but just in case.
1054 // setGCPercent updates gcPercent and all related pacer state.
1055 // Returns the old value of gcPercent.
1057 // Calls gcControllerState.commit.
1059 // The world must be stopped, or mheap_.lock must be held.
1060 func (c *gcControllerState) setGCPercent(in int32) int32 {
1062 assertWorldStoppedOrLockHeld(&mheap_.lock)
1065 out := c.gcPercent.Load()
1069 c.heapMinimum = defaultHeapMinimum * uint64(in) / 100
1070 c.gcPercent.Store(in)
1071 // Update pacing in response to gcPercent change.
1077 //go:linkname setGCPercent runtime/debug.setGCPercent
1078 func setGCPercent(in int32) (out int32) {
1079 // Run on the system stack since we grab the heap lock.
1080 systemstack(func() {
1082 out = gcController.setGCPercent(in)
1083 gcPaceSweeper(gcController.trigger)
1084 gcPaceScavenger(gcController.heapGoal, gcController.lastHeapGoal)
1085 unlock(&mheap_.lock)
1088 // If we just disabled GC, wait for any concurrent GC mark to
1089 // finish so we always return with no GC running.
1091 gcWaitOnMark(atomic.Load(&work.cycles))
1097 func readGOGC() int32 {
1098 p := gogetenv("GOGC")
1102 if n, ok := atoi32(p); ok {
1108 type piController struct {
1109 kp float64 // Proportional constant.
1110 ti float64 // Integral time constant.
1111 tt float64 // Reset time.
1113 min, max float64 // Output boundaries.
1115 // PI controller state.
1117 errIntegral float64 // Integral of the error from t=0 to now.
1120 errOverflow bool // Set if errIntegral ever overflowed.
1121 inputOverflow bool // Set if an operation with the input overflowed.
1124 // next provides a new sample to the controller.
1126 // input is the sample, setpoint is the desired point, and period is how much
1127 // time (in whatever unit makes the most sense) has passed since the last sample.
1129 // Returns a new value for the variable it's controlling, and whether the operation
1130 // completed successfully. One reason this might fail is if error has been growing
1131 // in an unbounded manner, to the point of overflow.
1133 // In the specific case of an error overflow occurs, the errOverflow field will be
1134 // set and the rest of the controller's internal state will be fully reset.
1135 func (c *piController) next(input, setpoint, period float64) (float64, bool) {
1136 // Compute the raw output value.
1137 prop := c.kp * (setpoint - input)
1138 rawOutput := prop + c.errIntegral
1140 // Clamp rawOutput into output.
1142 if isInf(output) || isNaN(output) {
1143 // The input had a large enough magnitude that either it was already
1144 // overflowed, or some operation with it overflowed.
1145 // Set a flag and reset. That's the safest thing to do.
1147 c.inputOverflow = true
1152 } else if output > c.max {
1156 // Update the controller's state.
1157 if c.ti != 0 && c.tt != 0 {
1158 c.errIntegral += (c.kp*period/c.ti)*(setpoint-input) + (period/c.tt)*(output-rawOutput)
1159 if isInf(c.errIntegral) || isNaN(c.errIntegral) {
1160 // So much error has accumulated that we managed to overflow.
1161 // The assumptions around the controller have likely broken down.
1162 // Set a flag and reset. That's the safest thing to do.
1164 c.errOverflow = true
1171 // reset resets the controller state, except for controller error flags.
1172 func (c *piController) reset() {
1176 // addIdleMarkWorker attempts to add a new idle mark worker.
1178 // If this returns true, the caller must become an idle mark worker unless
1179 // there's no background mark worker goroutines in the pool. This case is
1180 // harmless because there are already background mark workers running.
1181 // If this returns false, the caller must NOT become an idle mark worker.
1183 // nosplit because it may be called without a P.
1185 func (c *gcControllerState) addIdleMarkWorker() bool {
1187 old := c.idleMarkWorkers.Load()
1188 n, max := int32(old&uint64(^uint32(0))), int32(old>>32)
1190 // See the comment on idleMarkWorkers for why
1191 // n > max is tolerated.
1195 print("n=", n, " max=", max, "\n")
1196 throw("negative idle mark workers")
1198 new := uint64(uint32(n+1)) | (uint64(max) << 32)
1199 if c.idleMarkWorkers.CompareAndSwap(old, new) {
1205 // needIdleMarkWorker is a hint as to whether another idle mark worker is needed.
1207 // The caller must still call addIdleMarkWorker to become one. This is mainly
1208 // useful for a quick check before an expensive operation.
1210 // nosplit because it may be called without a P.
1212 func (c *gcControllerState) needIdleMarkWorker() bool {
1213 p := c.idleMarkWorkers.Load()
1214 n, max := int32(p&uint64(^uint32(0))), int32(p>>32)
1218 // removeIdleMarkWorker must be called when an new idle mark worker stops executing.
1219 func (c *gcControllerState) removeIdleMarkWorker() {
1221 old := c.idleMarkWorkers.Load()
1222 n, max := int32(old&uint64(^uint32(0))), int32(old>>32)
1224 print("n=", n, " max=", max, "\n")
1225 throw("negative idle mark workers")
1227 new := uint64(uint32(n-1)) | (uint64(max) << 32)
1228 if c.idleMarkWorkers.CompareAndSwap(old, new) {
1234 // setMaxIdleMarkWorkers sets the maximum number of idle mark workers allowed.
1236 // This method is optimistic in that it does not wait for the number of
1237 // idle mark workers to reduce to max before returning; it assumes the workers
1238 // will deschedule themselves.
1239 func (c *gcControllerState) setMaxIdleMarkWorkers(max int32) {
1241 old := c.idleMarkWorkers.Load()
1242 n := int32(old & uint64(^uint32(0)))
1244 print("n=", n, " max=", max, "\n")
1245 throw("negative idle mark workers")
1247 new := uint64(uint32(n)) | (uint64(max) << 32)
1248 if c.idleMarkWorkers.CompareAndSwap(old, new) {