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 1 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 the maximum may not be zero because idle-priority mark workers
300 // are vital to GC progress. Consider a situation in which goroutines
301 // block on the GC (such as via runtime.GOMAXPROCS) and only fractional
302 // mark workers are scheduled (e.g. GOMAXPROCS=1). Without idle-priority
303 // mark workers, the last running M might skip scheduling a fractional
304 // mark worker if its utilization goal is met, such that once it goes to
305 // sleep (because there's nothing to do), there will be nothing else to
306 // spin up a new M for the fractional worker in the future, stalling GC
307 // progress and causing a deadlock. However, idle-priority workers will
308 // *always* run when there is nothing left to do, ensuring the GC makes
310 idleMarkWorkers atomic.Uint64
312 // assistWorkPerByte is the ratio of scan work to allocated
313 // bytes that should be performed by mutator assists. This is
314 // computed at the beginning of each cycle and updated every
315 // time heapScan is updated.
316 assistWorkPerByte atomic.Float64
318 // assistBytesPerWork is 1/assistWorkPerByte.
320 // Note that because this is read and written independently
321 // from assistWorkPerByte users may notice a skew between
322 // the two values, and such a state should be safe.
323 assistBytesPerWork atomic.Float64
325 // fractionalUtilizationGoal is the fraction of wall clock
326 // time that should be spent in the fractional mark worker on
327 // each P that isn't running a dedicated worker.
329 // For example, if the utilization goal is 25% and there are
330 // no dedicated workers, this will be 0.25. If the goal is
331 // 25%, there is one dedicated worker, and GOMAXPROCS is 5,
332 // this will be 0.05 to make up the missing 5%.
334 // If this is zero, no fractional workers are needed.
335 fractionalUtilizationGoal float64
337 // test indicates that this is a test-only copy of gcControllerState.
343 func (c *gcControllerState) init(gcPercent int32) {
344 c.heapMinimum = defaultHeapMinimum
346 c.consMarkController = piController{
347 // Tuned first via the Ziegler-Nichols process in simulation,
348 // then the integral time was manually tuned against real-world
349 // applications to deal with noisiness in the measured cons/mark
354 // Set a high reset time in GC cycles.
355 // This is inversely proportional to the rate at which we
356 // accumulate error from clipping. By making this very high
357 // we make the accumulation slow. In general, clipping is
358 // OK in our situation, hence the choice.
360 // Tune this if we get unintended effects from clipping for
367 // This will also compute and set the GC trigger and goal.
368 c.setGCPercent(gcPercent)
371 // startCycle resets the GC controller's state and computes estimates
372 // for a new GC cycle. The caller must hold worldsema and the world
374 func (c *gcControllerState) startCycle(markStartTime int64, procs int, trigger gcTrigger) {
375 c.heapScanWork.Store(0)
376 c.stackScanWork.Store(0)
377 c.globalsScanWork.Store(0)
380 c.dedicatedMarkTime = 0
381 c.fractionalMarkTime = 0
383 c.markStartTime = markStartTime
384 c.stackScan = atomic.Load64(&c.scannableStackSize)
386 // Ensure that the heap goal is at least a little larger than
387 // the current live heap size. This may not be the case if GC
388 // start is delayed or if the allocation that pushed gcController.heapLive
389 // over trigger is large or if the trigger is really close to
390 // GOGC. Assist is proportional to this distance, so enforce a
391 // minimum distance, even if it means going over the GOGC goal
393 if c.heapGoal < c.heapLive+64<<10 {
394 c.heapGoal = c.heapLive + 64<<10
397 // Compute the background mark utilization goal. In general,
398 // this may not come out exactly. We round the number of
399 // dedicated workers so that the utilization is closest to
400 // 25%. For small GOMAXPROCS, this would introduce too much
401 // error, so we add fractional workers in that case.
402 totalUtilizationGoal := float64(procs) * gcBackgroundUtilization
403 c.dedicatedMarkWorkersNeeded = int64(totalUtilizationGoal + 0.5)
404 utilError := float64(c.dedicatedMarkWorkersNeeded)/totalUtilizationGoal - 1
405 const maxUtilError = 0.3
406 if utilError < -maxUtilError || utilError > maxUtilError {
407 // Rounding put us more than 30% off our goal. With
408 // gcBackgroundUtilization of 25%, this happens for
409 // GOMAXPROCS<=3 or GOMAXPROCS=6. Enable fractional
410 // workers to compensate.
411 if float64(c.dedicatedMarkWorkersNeeded) > totalUtilizationGoal {
412 // Too many dedicated workers.
413 c.dedicatedMarkWorkersNeeded--
415 c.fractionalUtilizationGoal = (totalUtilizationGoal - float64(c.dedicatedMarkWorkersNeeded)) / float64(procs)
417 c.fractionalUtilizationGoal = 0
420 // In STW mode, we just want dedicated workers.
421 if debug.gcstoptheworld > 0 {
422 c.dedicatedMarkWorkersNeeded = int64(procs)
423 c.fractionalUtilizationGoal = 0
427 for _, p := range allp {
429 p.gcFractionalMarkTime = 0
432 if trigger.kind == gcTriggerTime {
433 // During a periodic GC cycle, avoid having more than
434 // one idle mark worker running at a time. We need to have
435 // at least one to ensure the GC makes progress, but more than
436 // one is unnecessary.
437 c.setMaxIdleMarkWorkers(1)
439 // N.B. gomaxprocs and dedicatedMarkWorkersNeeded is guaranteed not to
440 // change during a GC cycle.
441 c.setMaxIdleMarkWorkers(int32(procs) - int32(c.dedicatedMarkWorkersNeeded))
444 // Compute initial values for controls that are updated
445 // throughout the cycle.
448 if debug.gcpacertrace > 0 {
449 assistRatio := c.assistWorkPerByte.Load()
450 print("pacer: assist ratio=", assistRatio,
451 " (scan ", gcController.heapScan>>20, " MB in ",
452 work.initialHeapLive>>20, "->",
453 c.heapGoal>>20, " MB)",
454 " workers=", c.dedicatedMarkWorkersNeeded,
455 "+", c.fractionalUtilizationGoal, "\n")
459 // revise updates the assist ratio during the GC cycle to account for
460 // improved estimates. This should be called whenever gcController.heapScan,
461 // gcController.heapLive, or gcController.heapGoal is updated. It is safe to
462 // call concurrently, but it may race with other calls to revise.
464 // The result of this race is that the two assist ratio values may not line
465 // up or may be stale. In practice this is OK because the assist ratio
466 // moves slowly throughout a GC cycle, and the assist ratio is a best-effort
467 // heuristic anyway. Furthermore, no part of the heuristic depends on
468 // the two assist ratio values being exact reciprocals of one another, since
469 // the two values are used to convert values from different sources.
471 // The worst case result of this raciness is that we may miss a larger shift
472 // in the ratio (say, if we decide to pace more aggressively against the
473 // hard heap goal) but even this "hard goal" is best-effort (see #40460).
474 // The dedicated GC should ensure we don't exceed the hard goal by too much
475 // in the rare case we do exceed it.
477 // It should only be called when gcBlackenEnabled != 0 (because this
478 // is when assists are enabled and the necessary statistics are
480 func (c *gcControllerState) revise() {
481 gcPercent := c.gcPercent.Load()
483 // If GC is disabled but we're running a forced GC,
484 // act like GOGC is huge for the below calculations.
487 live := atomic.Load64(&c.heapLive)
488 scan := atomic.Load64(&c.heapScan)
489 work := c.heapScanWork.Load() + c.stackScanWork.Load() + c.globalsScanWork.Load()
491 // Assume we're under the soft goal. Pace GC to complete at
492 // heapGoal assuming the heap is in steady-state.
493 heapGoal := int64(atomic.Load64(&c.heapGoal))
495 // The expected scan work is computed as the amount of bytes scanned last
496 // GC cycle, plus our estimate of stacks and globals work for this cycle.
497 scanWorkExpected := int64(c.lastHeapScan + c.stackScan + c.globalsScan)
499 // maxScanWork is a worst-case estimate of the amount of scan work that
500 // needs to be performed in this GC cycle. Specifically, it represents
501 // the case where *all* scannable memory turns out to be live.
502 maxScanWork := int64(scan + c.stackScan + c.globalsScan)
503 if work > scanWorkExpected {
504 // We've already done more scan work than expected. Because our expectation
505 // is based on a steady-state scannable heap size, we assume this means our
506 // heap is growing. Compute a new heap goal that takes our existing runway
507 // computed for scanWorkExpected and extrapolates it to maxScanWork, the worst-case
508 // scan work. This keeps our assist ratio stable if the heap continues to grow.
510 // The effect of this mechanism is that assists stay flat in the face of heap
511 // growths. It's OK to use more memory this cycle to scan all the live heap,
512 // because the next GC cycle is inevitably going to use *at least* that much
514 extHeapGoal := int64(float64(heapGoal-int64(c.trigger))/float64(scanWorkExpected)*float64(maxScanWork)) + int64(c.trigger)
515 scanWorkExpected = maxScanWork
517 // hardGoal is a hard limit on the amount that we're willing to push back the
518 // heap goal, and that's twice the heap goal (i.e. if GOGC=100 and the heap and/or
519 // stacks and/or globals grow to twice their size, this limits the current GC cycle's
520 // growth to 4x the original live heap's size).
522 // This maintains the invariant that we use no more memory than the next GC cycle
524 hardGoal := int64((1.0 + float64(gcPercent)/100.0) * float64(heapGoal))
525 if extHeapGoal > hardGoal {
526 extHeapGoal = hardGoal
528 heapGoal = extHeapGoal
530 if int64(live) > heapGoal {
531 // We're already past our heap goal, even the extrapolated one.
532 // Leave ourselves some extra runway, so in the worst case we
533 // finish by that point.
534 const maxOvershoot = 1.1
535 heapGoal = int64(float64(heapGoal) * maxOvershoot)
537 // Compute the upper bound on the scan work remaining.
538 scanWorkExpected = maxScanWork
541 // Compute the remaining scan work estimate.
543 // Note that we currently count allocations during GC as both
544 // scannable heap (heapScan) and scan work completed
545 // (scanWork), so allocation will change this difference
546 // slowly in the soft regime and not at all in the hard
548 scanWorkRemaining := scanWorkExpected - work
549 if scanWorkRemaining < 1000 {
550 // We set a somewhat arbitrary lower bound on
551 // remaining scan work since if we aim a little high,
552 // we can miss by a little.
554 // We *do* need to enforce that this is at least 1,
555 // since marking is racy and double-scanning objects
556 // may legitimately make the remaining scan work
557 // negative, even in the hard goal regime.
558 scanWorkRemaining = 1000
561 // Compute the heap distance remaining.
562 heapRemaining := heapGoal - int64(live)
563 if heapRemaining <= 0 {
564 // This shouldn't happen, but if it does, avoid
565 // dividing by zero or setting the assist negative.
569 // Compute the mutator assist ratio so by the time the mutator
570 // allocates the remaining heap bytes up to heapGoal, it will
571 // have done (or stolen) the remaining amount of scan work.
572 // Note that the assist ratio values are updated atomically
573 // but not together. This means there may be some degree of
574 // skew between the two values. This is generally OK as the
575 // values shift relatively slowly over the course of a GC
577 assistWorkPerByte := float64(scanWorkRemaining) / float64(heapRemaining)
578 assistBytesPerWork := float64(heapRemaining) / float64(scanWorkRemaining)
579 c.assistWorkPerByte.Store(assistWorkPerByte)
580 c.assistBytesPerWork.Store(assistBytesPerWork)
583 // endCycle computes the consMark estimate for the next cycle.
584 // userForced indicates whether the current GC cycle was forced
585 // by the application.
586 func (c *gcControllerState) endCycle(now int64, procs int, userForced bool) {
587 // Record last heap goal for the scavenger.
588 // We'll be updating the heap goal soon.
589 gcController.lastHeapGoal = gcController.heapGoal
591 // Compute the duration of time for which assists were turned on.
592 assistDuration := now - c.markStartTime
594 // Assume background mark hit its utilization goal.
595 utilization := gcBackgroundUtilization
596 // Add assist utilization; avoid divide by zero.
597 if assistDuration > 0 {
598 utilization += float64(c.assistTime) / float64(assistDuration*int64(procs))
601 if c.heapLive <= c.trigger {
602 // Shouldn't happen, but let's be very safe about this in case the
603 // GC is somehow extremely short.
605 // In this case though, the only reasonable value for c.heapLive-c.trigger
606 // would be 0, which isn't really all that useful, i.e. the GC was so short
607 // that it didn't matter.
609 // Ignore this case and don't update anything.
612 idleUtilization := 0.0
613 if assistDuration > 0 {
614 idleUtilization = float64(c.idleMarkTime) / float64(assistDuration*int64(procs))
616 // Determine the cons/mark ratio.
618 // The units we want for the numerator and denominator are both B / cpu-ns.
619 // We get this by taking the bytes allocated or scanned, and divide by the amount of
620 // CPU time it took for those operations. For allocations, that CPU time is
622 // assistDuration * procs * (1 - utilization)
624 // Where utilization includes just background GC workers and assists. It does *not*
625 // include idle GC work time, because in theory the mutator is free to take that at
628 // For scanning, that CPU time is
630 // assistDuration * procs * (utilization + idleUtilization)
632 // In this case, we *include* idle utilization, because that is additional CPU time that the
633 // the GC had available to it.
635 // In effect, idle GC time is sort of double-counted here, but it's very weird compared
636 // to other kinds of GC work, because of how fluid it is. Namely, because the mutator is
637 // *always* free to take it.
639 // So this calculation is really:
640 // (heapLive-trigger) / (assistDuration * procs * (1-utilization)) /
641 // (scanWork) / (assistDuration * procs * (utilization+idleUtilization)
643 // Note that because we only care about the ratio, assistDuration and procs cancel out.
644 scanWork := c.heapScanWork.Load() + c.stackScanWork.Load() + c.globalsScanWork.Load()
645 currentConsMark := (float64(c.heapLive-c.trigger) * (utilization + idleUtilization)) /
646 (float64(scanWork) * (1 - utilization))
648 // Update cons/mark controller. The time period for this is 1 GC cycle.
650 // This use of a PI controller might seem strange. So, here's an explanation:
652 // currentConsMark represents the consMark we *should've* had to be perfectly
653 // on-target for this cycle. Given that we assume the next GC will be like this
654 // one in the steady-state, it stands to reason that we should just pick that
655 // as our next consMark. In practice, however, currentConsMark is too noisy:
656 // we're going to be wildly off-target in each GC cycle if we do that.
658 // What we do instead is make a long-term assumption: there is some steady-state
659 // consMark value, but it's obscured by noise. By constantly shooting for this
660 // noisy-but-perfect consMark value, the controller will bounce around a bit,
661 // but its average behavior, in aggregate, should be less noisy and closer to
662 // the true long-term consMark value, provided its tuned to be slightly overdamped.
664 oldConsMark := c.consMark
665 c.consMark, ok = c.consMarkController.next(c.consMark, currentConsMark, 1.0)
667 // The error spiraled out of control. This is incredibly unlikely seeing
668 // as this controller is essentially just a smoothing function, but it might
669 // mean that something went very wrong with how currentConsMark was calculated.
670 // Just reset consMark and keep going.
674 if debug.gcpacertrace > 0 {
676 goal := gcGoalUtilization * 100
677 print("pacer: ", int(utilization*100), "% CPU (", int(goal), " exp.) for ")
678 print(c.heapScanWork.Load(), "+", c.stackScanWork.Load(), "+", c.globalsScanWork.Load(), " B work (", c.lastHeapScan+c.stackScan+c.globalsScan, " B exp.) ")
679 print("in ", c.trigger, " B -> ", c.heapLive, " B (∆goal ", int64(c.heapLive)-int64(c.heapGoal), ", cons/mark ", oldConsMark, ")")
681 print("[controller reset]")
688 // enlistWorker encourages another dedicated mark worker to start on
689 // another P if there are spare worker slots. It is used by putfull
690 // when more work is made available.
693 func (c *gcControllerState) enlistWorker() {
694 // If there are idle Ps, wake one so it will run an idle worker.
695 // NOTE: This is suspected of causing deadlocks. See golang.org/issue/19112.
697 // if atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 {
702 // There are no idle Ps. If we need more dedicated workers,
703 // try to preempt a running P so it will switch to a worker.
704 if c.dedicatedMarkWorkersNeeded <= 0 {
707 // Pick a random other P to preempt.
712 if gp == nil || gp.m == nil || gp.m.p == 0 {
715 myID := gp.m.p.ptr().id
716 for tries := 0; tries < 5; tries++ {
717 id := int32(fastrandn(uint32(gomaxprocs - 1)))
722 if p.status != _Prunning {
731 // findRunnableGCWorker returns a background mark worker for _p_ if it
732 // should be run. This must only be called when gcBlackenEnabled != 0.
733 func (c *gcControllerState) findRunnableGCWorker(_p_ *p) *g {
734 if gcBlackenEnabled == 0 {
735 throw("gcControllerState.findRunnable: blackening not enabled")
738 if !gcMarkWorkAvailable(_p_) {
739 // No work to be done right now. This can happen at
740 // the end of the mark phase when there are still
741 // assists tapering off. Don't bother running a worker
742 // now because it'll just return immediately.
746 // Grab a worker before we commit to running below.
747 node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
749 // There is at least one worker per P, so normally there are
750 // enough workers to run on all Ps, if necessary. However, once
751 // a worker enters gcMarkDone it may park without rejoining the
752 // pool, thus freeing a P with no corresponding worker.
753 // gcMarkDone never depends on another worker doing work, so it
754 // is safe to simply do nothing here.
756 // If gcMarkDone bails out without completing the mark phase,
757 // it will always do so with queued global work. Thus, that P
758 // will be immediately eligible to re-run the worker G it was
759 // just using, ensuring work can complete.
763 decIfPositive := func(ptr *int64) bool {
765 v := atomic.Loadint64(ptr)
770 if atomic.Casint64(ptr, v, v-1) {
776 if decIfPositive(&c.dedicatedMarkWorkersNeeded) {
777 // This P is now dedicated to marking until the end of
778 // the concurrent mark phase.
779 _p_.gcMarkWorkerMode = gcMarkWorkerDedicatedMode
780 } else if c.fractionalUtilizationGoal == 0 {
781 // No need for fractional workers.
782 gcBgMarkWorkerPool.push(&node.node)
785 // Is this P behind on the fractional utilization
788 // This should be kept in sync with pollFractionalWorkerExit.
789 delta := nanotime() - c.markStartTime
790 if delta > 0 && float64(_p_.gcFractionalMarkTime)/float64(delta) > c.fractionalUtilizationGoal {
791 // Nope. No need to run a fractional worker.
792 gcBgMarkWorkerPool.push(&node.node)
795 // Run a fractional worker.
796 _p_.gcMarkWorkerMode = gcMarkWorkerFractionalMode
799 // Run the background mark worker.
801 casgstatus(gp, _Gwaiting, _Grunnable)
808 // resetLive sets up the controller state for the next mark phase after the end
809 // of the previous one. Must be called after endCycle and before commit, before
810 // the world is started.
812 // The world must be stopped.
813 func (c *gcControllerState) resetLive(bytesMarked uint64) {
814 c.heapMarked = bytesMarked
815 c.heapLive = bytesMarked
816 c.heapScan = uint64(c.heapScanWork.Load())
817 c.lastHeapScan = uint64(c.heapScanWork.Load())
819 // heapLive was updated, so emit a trace event.
825 // markWorkerStop must be called whenever a mark worker stops executing.
827 // It updates mark work accounting in the controller by a duration of
828 // work in nanoseconds and other bookkeeping.
830 // Safe to execute at any time.
831 func (c *gcControllerState) markWorkerStop(mode gcMarkWorkerMode, duration int64) {
833 case gcMarkWorkerDedicatedMode:
834 atomic.Xaddint64(&c.dedicatedMarkTime, duration)
835 atomic.Xaddint64(&c.dedicatedMarkWorkersNeeded, 1)
836 case gcMarkWorkerFractionalMode:
837 atomic.Xaddint64(&c.fractionalMarkTime, duration)
838 case gcMarkWorkerIdleMode:
839 atomic.Xaddint64(&c.idleMarkTime, duration)
840 c.removeIdleMarkWorker()
842 throw("markWorkerStop: unknown mark worker mode")
846 func (c *gcControllerState) update(dHeapLive, dHeapScan int64) {
848 atomic.Xadd64(&gcController.heapLive, dHeapLive)
850 // gcController.heapLive changed.
854 if gcBlackenEnabled == 0 {
855 // Update heapScan when we're not in a current GC. It is fixed
856 // at the beginning of a cycle.
858 atomic.Xadd64(&gcController.heapScan, dHeapScan)
861 // gcController.heapLive changed.
866 func (c *gcControllerState) addScannableStack(pp *p, amount int64) {
868 atomic.Xadd64(&c.scannableStackSize, amount)
871 pp.scannableStackSizeDelta += amount
872 if pp.scannableStackSizeDelta >= scannableStackSizeSlack || pp.scannableStackSizeDelta <= -scannableStackSizeSlack {
873 atomic.Xadd64(&c.scannableStackSize, pp.scannableStackSizeDelta)
874 pp.scannableStackSizeDelta = 0
878 func (c *gcControllerState) addGlobals(amount int64) {
879 atomic.Xadd64(&c.globalsScan, amount)
882 // commit recomputes all pacing parameters from scratch, namely
883 // absolute trigger, the heap goal, mark pacing, and sweep pacing.
885 // This can be called any time. If GC is the in the middle of a
886 // concurrent phase, it will adjust the pacing of that phase.
888 // This depends on gcPercent, gcController.heapMarked, and
889 // gcController.heapLive. These must be up to date.
891 // mheap_.lock must be held or the world must be stopped.
892 func (c *gcControllerState) commit() {
894 assertWorldStoppedOrLockHeld(&mheap_.lock)
897 // Compute the next GC goal, which is when the allocated heap
898 // has grown by GOGC/100 over where it started the last cycle,
899 // plus additional runway for non-heap sources of GC work.
901 if gcPercent := c.gcPercent.Load(); gcPercent >= 0 {
902 goal = c.heapMarked + (c.heapMarked+atomic.Load64(&c.stackScan)+atomic.Load64(&c.globalsScan))*uint64(gcPercent)/100
905 // Don't trigger below the minimum heap size.
906 minTrigger := c.heapMinimum
908 // Concurrent sweep happens in the heap growth
909 // from gcController.heapLive to trigger, so ensure
910 // that concurrent sweep has some heap growth
911 // in which to perform sweeping before we
912 // start the next GC cycle.
913 sweepMin := atomic.Load64(&c.heapLive) + sweepMinHeapDistance
914 if sweepMin > minTrigger {
915 minTrigger = sweepMin
919 // If we let the trigger go too low, then if the application
920 // is allocating very rapidly we might end up in a situation
921 // where we're allocating black during a nearly always-on GC.
922 // The result of this is a growing heap and ultimately an
923 // increase in RSS. By capping us at a point >0, we're essentially
924 // saying that we're OK using more CPU during the GC to prevent
925 // this growth in RSS.
927 // The current constant was chosen empirically: given a sufficiently
928 // fast/scalable allocator with 48 Ps that could drive the trigger ratio
929 // to <0.05, this constant causes applications to retain the same peak
930 // RSS compared to not having this allocator.
931 if triggerBound := uint64(0.7*float64(goal-c.heapMarked)) + c.heapMarked; minTrigger < triggerBound {
932 minTrigger = triggerBound
935 // For small heaps, set the max trigger point at 95% of the heap goal.
936 // This ensures we always have *some* headroom when the GC actually starts.
937 // For larger heaps, set the max trigger point at the goal, minus the
938 // minimum heap size.
939 // This choice follows from the fact that the minimum heap size is chosen
940 // to reflect the costs of a GC with no work to do. With a large heap but
941 // very little scan work to perform, this gives us exactly as much runway
942 // as we would need, in the worst case.
943 maxRunway := uint64(0.95 * float64(goal-c.heapMarked))
944 if largeHeapMaxRunway := goal - c.heapMinimum; goal > c.heapMinimum && maxRunway < largeHeapMaxRunway {
945 maxRunway = largeHeapMaxRunway
947 maxTrigger := maxRunway + c.heapMarked
948 if maxTrigger < minTrigger {
949 maxTrigger = minTrigger
952 // Compute the trigger by using our estimate of the cons/mark ratio.
954 // The idea is to take our expected scan work, and multiply it by
955 // the cons/mark ratio to determine how long it'll take to complete
956 // that scan work in terms of bytes allocated. This gives us our GC's
959 // However, the cons/mark ratio is a ratio of rates per CPU-second, but
960 // here we care about the relative rates for some division of CPU
961 // resources among the mutator and the GC.
963 // To summarize, we have B / cpu-ns, and we want B / ns. We get that
964 // by multiplying by our desired division of CPU resources. We choose
965 // to express CPU resources as GOMAPROCS*fraction. Note that because
966 // we're working with a ratio here, we can omit the number of CPU cores,
967 // because they'll appear in the numerator and denominator and cancel out.
968 // As a result, this is basically just "weighing" the cons/mark ratio by
969 // our desired division of resources.
971 // Furthermore, by setting the trigger so that CPU resources are divided
972 // this way, assuming that the cons/mark ratio is correct, we make that
973 // division a reality.
975 runway := uint64((c.consMark * (1 - gcGoalUtilization) / (gcGoalUtilization)) * float64(c.lastHeapScan+c.stackScan+c.globalsScan))
979 trigger = goal - runway
981 if trigger < minTrigger {
984 if trigger > maxTrigger {
991 // Commit to the trigger and goal.
993 atomic.Store64(&c.heapGoal, goal)
998 // Update mark pacing.
999 if gcphase != _GCoff {
1004 // effectiveGrowthRatio returns the current effective heap growth
1005 // ratio (GOGC/100) based on heapMarked from the previous GC and
1006 // heapGoal for the current GC.
1008 // This may differ from gcPercent/100 because of various upper and
1009 // lower bounds on gcPercent. For example, if the heap is smaller than
1010 // heapMinimum, this can be higher than gcPercent/100.
1012 // mheap_.lock must be held or the world must be stopped.
1013 func (c *gcControllerState) effectiveGrowthRatio() float64 {
1015 assertWorldStoppedOrLockHeld(&mheap_.lock)
1018 egogc := float64(atomic.Load64(&c.heapGoal)-c.heapMarked) / float64(c.heapMarked)
1020 // Shouldn't happen, but just in case.
1026 // setGCPercent updates gcPercent and all related pacer state.
1027 // Returns the old value of gcPercent.
1029 // Calls gcControllerState.commit.
1031 // The world must be stopped, or mheap_.lock must be held.
1032 func (c *gcControllerState) setGCPercent(in int32) int32 {
1034 assertWorldStoppedOrLockHeld(&mheap_.lock)
1037 out := c.gcPercent.Load()
1041 c.heapMinimum = defaultHeapMinimum * uint64(in) / 100
1042 c.gcPercent.Store(in)
1043 // Update pacing in response to gcPercent change.
1049 //go:linkname setGCPercent runtime/debug.setGCPercent
1050 func setGCPercent(in int32) (out int32) {
1051 // Run on the system stack since we grab the heap lock.
1052 systemstack(func() {
1054 out = gcController.setGCPercent(in)
1055 gcPaceSweeper(gcController.trigger)
1056 gcPaceScavenger(gcController.heapGoal, gcController.lastHeapGoal)
1057 unlock(&mheap_.lock)
1060 // If we just disabled GC, wait for any concurrent GC mark to
1061 // finish so we always return with no GC running.
1063 gcWaitOnMark(atomic.Load(&work.cycles))
1069 func readGOGC() int32 {
1070 p := gogetenv("GOGC")
1074 if n, ok := atoi32(p); ok {
1080 type piController struct {
1081 kp float64 // Proportional constant.
1082 ti float64 // Integral time constant.
1083 tt float64 // Reset time.
1085 min, max float64 // Output boundaries.
1087 // PI controller state.
1089 errIntegral float64 // Integral of the error from t=0 to now.
1092 errOverflow bool // Set if errIntegral ever overflowed.
1093 inputOverflow bool // Set if an operation with the input overflowed.
1096 // next provides a new sample to the controller.
1098 // input is the sample, setpoint is the desired point, and period is how much
1099 // time (in whatever unit makes the most sense) has passed since the last sample.
1101 // Returns a new value for the variable it's controlling, and whether the operation
1102 // completed successfully. One reason this might fail is if error has been growing
1103 // in an unbounded manner, to the point of overflow.
1105 // In the specific case of an error overflow occurs, the errOverflow field will be
1106 // set and the rest of the controller's internal state will be fully reset.
1107 func (c *piController) next(input, setpoint, period float64) (float64, bool) {
1108 // Compute the raw output value.
1109 prop := c.kp * (setpoint - input)
1110 rawOutput := prop + c.errIntegral
1112 // Clamp rawOutput into output.
1114 if isInf(output) || isNaN(output) {
1115 // The input had a large enough magnitude that either it was already
1116 // overflowed, or some operation with it overflowed.
1117 // Set a flag and reset. That's the safest thing to do.
1119 c.inputOverflow = true
1124 } else if output > c.max {
1128 // Update the controller's state.
1129 if c.ti != 0 && c.tt != 0 {
1130 c.errIntegral += (c.kp*period/c.ti)*(setpoint-input) + (period/c.tt)*(output-rawOutput)
1131 if isInf(c.errIntegral) || isNaN(c.errIntegral) {
1132 // So much error has accumulated that we managed to overflow.
1133 // The assumptions around the controller have likely broken down.
1134 // Set a flag and reset. That's the safest thing to do.
1136 c.errOverflow = true
1143 // reset resets the controller state, except for controller error flags.
1144 func (c *piController) reset() {
1148 // addIdleMarkWorker attempts to add a new idle mark worker.
1150 // If this returns true, the caller must become an idle mark worker unless
1151 // there's no background mark worker goroutines in the pool. This case is
1152 // harmless because there are already background mark workers running.
1153 // If this returns false, the caller must NOT become an idle mark worker.
1155 // nosplit because it may be called without a P.
1157 func (c *gcControllerState) addIdleMarkWorker() bool {
1159 old := c.idleMarkWorkers.Load()
1160 n, max := int32(old&uint64(^uint32(0))), int32(old>>32)
1162 // See the comment on idleMarkWorkers for why
1163 // n > max is tolerated.
1167 print("n=", n, " max=", max, "\n")
1168 throw("negative idle mark workers")
1170 new := uint64(uint32(n+1)) | (uint64(max) << 32)
1171 if c.idleMarkWorkers.CompareAndSwap(old, new) {
1177 // needIdleMarkWorker is a hint as to whether another idle mark worker is needed.
1179 // The caller must still call addIdleMarkWorker to become one. This is mainly
1180 // useful for a quick check before an expensive operation.
1182 // nosplit because it may be called without a P.
1184 func (c *gcControllerState) needIdleMarkWorker() bool {
1185 p := c.idleMarkWorkers.Load()
1186 n, max := int32(p&uint64(^uint32(0))), int32(p>>32)
1190 // removeIdleMarkWorker must be called when an new idle mark worker stops executing.
1191 func (c *gcControllerState) removeIdleMarkWorker() {
1193 old := c.idleMarkWorkers.Load()
1194 n, max := int32(old&uint64(^uint32(0))), int32(old>>32)
1196 print("n=", n, " max=", max, "\n")
1197 throw("negative idle mark workers")
1199 new := uint64(uint32(n-1)) | (uint64(max) << 32)
1200 if c.idleMarkWorkers.CompareAndSwap(old, new) {
1206 // setMaxIdleMarkWorkers sets the maximum number of idle mark workers allowed.
1208 // This method is optimistic in that it does not wait for the number of
1209 // idle mark workers to reduce to max before returning; it assumes the workers
1210 // will deschedule themselves.
1211 func (c *gcControllerState) setMaxIdleMarkWorkers(max int32) {
1213 old := c.idleMarkWorkers.Load()
1214 n := int32(old & uint64(^uint32(0)))
1216 print("n=", n, " max=", max, "\n")
1217 throw("negative idle mark workers")
1219 new := uint64(uint32(n)) | (uint64(max) << 32)
1220 if c.idleMarkWorkers.CompareAndSwap(old, new) {