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.
17 gcGoalUtilization = goexperiment.PacerRedesignInt*gcBackgroundUtilization +
18 (1-goexperiment.PacerRedesignInt)*(gcBackgroundUtilization+0.05)
20 // gcBackgroundUtilization is the fixed CPU utilization for background
21 // marking. It must be <= gcGoalUtilization. The difference between
22 // gcGoalUtilization and gcBackgroundUtilization will be made up by
23 // mark assists. The scheduler will aim to use within 50% of this
26 // Setting this to < gcGoalUtilization avoids saturating the trigger
27 // feedback controller when there are no assists, which allows it to
28 // better control CPU and heap growth. However, the larger the gap,
29 // the more mutator assists are expected to happen, which impact
32 // If goexperiment.PacerRedesign, the trigger feedback controller
33 // is replaced with an estimate of the mark/cons ratio that doesn't
34 // have the same saturation issues, so this is set equal to
36 gcBackgroundUtilization = 0.25
38 // gcCreditSlack is the amount of scan work credit that can
39 // accumulate locally before updating gcController.heapScanWork and,
40 // optionally, gcController.bgScanCredit. Lower values give a more
41 // accurate assist ratio and make it more likely that assists will
42 // successfully steal background credit. Higher values reduce memory
46 // gcAssistTimeSlack is the nanoseconds of mutator assist time that
47 // can accumulate on a P before updating gcController.assistTime.
48 gcAssistTimeSlack = 5000
50 // gcOverAssistWork determines how many extra units of scan work a GC
51 // assist does when an assist happens. This amortizes the cost of an
52 // assist by pre-paying for this many bytes of future allocations.
53 gcOverAssistWork = 64 << 10
55 // defaultHeapMinimum is the value of heapMinimum for GOGC==100.
56 defaultHeapMinimum = goexperiment.PacerRedesignInt*(512<<10) +
57 (1-goexperiment.PacerRedesignInt)*(4<<20)
59 // scannableStackSizeSlack is the bytes of stack space allocated or freed
60 // that can accumulate on a P before updating gcController.stackSize.
61 scannableStackSizeSlack = 8 << 10
65 if offset := unsafe.Offsetof(gcController.heapLive); offset%8 != 0 {
67 throw("gcController.heapLive not aligned to 8 bytes")
71 // gcController implements the GC pacing controller that determines
72 // when to trigger concurrent garbage collection and how much marking
73 // work to do in mutator assists and background marking.
75 // It uses a feedback control algorithm to adjust the gcController.trigger
76 // trigger based on the heap growth and GC CPU utilization each cycle.
77 // This algorithm optimizes for heap growth to match GOGC and for CPU
78 // utilization between assist and background marking to be 25% of
79 // GOMAXPROCS. The high-level design of this algorithm is documented
80 // at https://golang.org/s/go15gcpacing.
82 // All fields of gcController are used only during a single mark
84 var gcController gcControllerState
86 type gcControllerState struct {
87 // Initialized from $GOGC. GOGC=off means no GC.
89 // Updated atomically with mheap_.lock held or during a STW.
90 // Safe to read atomically at any time, or non-atomically with
91 // mheap_.lock or STW.
94 _ uint32 // padding so following 64-bit values are 8-byte aligned
96 // heapMinimum is the minimum heap size at which to trigger GC.
97 // For small heaps, this overrides the usual GOGC*live set rule.
99 // When there is a very small live set but a lot of allocation, simply
100 // collecting when the heap reaches GOGC*live results in many GC
101 // cycles and high total per-GC overhead. This minimum amortizes this
102 // per-GC overhead while keeping the heap reasonably small.
104 // During initialization this is set to 4MB*GOGC/100. In the case of
105 // GOGC==0, this will set heapMinimum to 0, resulting in constant
106 // collection even when the heap size is small, which is useful for
110 // triggerRatio is the heap growth ratio that triggers marking.
112 // E.g., if this is 0.6, then GC should start when the live
113 // heap has reached 1.6 times the heap size marked by the
114 // previous cycle. This should be ≤ GOGC/100 so the trigger
115 // heap size is less than the goal heap size. This is set
116 // during mark termination for the next cycle's trigger.
118 // Protected by mheap_.lock or a STW.
120 // Used if !goexperiment.PacerRedesign.
123 // trigger is the heap size that triggers marking.
125 // When heapLive ≥ trigger, the mark phase will start.
126 // This is also the heap size by which proportional sweeping
129 // This is computed from triggerRatio during mark termination
130 // for the next cycle's trigger.
132 // Protected by mheap_.lock or a STW.
135 // consMark is the estimated per-CPU consMark ratio for the application.
137 // It represents the ratio between the application's allocation
138 // rate, as bytes allocated per CPU-time, and the GC's scan rate,
139 // as bytes scanned per CPU-time.
140 // The units of this ratio are (B / cpu-ns) / (B / cpu-ns).
142 // At a high level, this value is computed as the bytes of memory
143 // allocated (cons) per unit of scan work completed (mark) in a GC
144 // cycle, divided by the CPU time spent on each activity.
146 // Updated at the end of each GC cycle, in endCycle.
148 // For goexperiment.PacerRedesign.
151 // consMarkController holds the state for the mark-cons ratio
152 // estimation over time.
154 // Its purpose is to smooth out noisiness in the computation of
155 // consMark; see consMark for details.
157 // For goexperiment.PacerRedesign.
158 consMarkController piController
160 // heapGoal is the goal heapLive for when next GC ends.
161 // Set to ^uint64(0) if disabled.
163 // Read and written atomically, unless the world is stopped.
166 // lastHeapGoal is the value of heapGoal for the previous GC.
167 // Note that this is distinct from the last value heapGoal had,
168 // because it could change if e.g. gcPercent changes.
170 // Read and written with the world stopped or with mheap_.lock held.
173 // heapLive is the number of bytes considered live by the GC.
174 // That is: retained by the most recent GC plus allocated
175 // since then. heapLive ≤ memstats.heapAlloc, since heapAlloc includes
176 // unmarked objects that have not yet been swept (and hence goes up as we
177 // allocate and down as we sweep) while heapLive excludes these
178 // objects (and hence only goes up between GCs).
180 // This is updated atomically without locking. To reduce
181 // contention, this is updated only when obtaining a span from
182 // an mcentral and at this point it counts all of the
183 // unallocated slots in that span (which will be allocated
184 // before that mcache obtains another span from that
185 // mcentral). Hence, it slightly overestimates the "true" live
186 // heap size. It's better to overestimate than to
187 // underestimate because 1) this triggers the GC earlier than
188 // necessary rather than potentially too late and 2) this
189 // leads to a conservative GC rate rather than a GC rate that
190 // is potentially too low.
192 // Reads should likewise be atomic (or during STW).
194 // Whenever this is updated, call traceHeapAlloc() and
195 // this gcControllerState's revise() method.
198 // heapScan is the number of bytes of "scannable" heap. This
199 // is the live heap (as counted by heapLive), but omitting
200 // no-scan objects and no-scan tails of objects.
202 // For !goexperiment.PacerRedesign: Whenever this is updated,
203 // call this gcControllerState's revise() method. It is read
204 // and written atomically or with the world stopped.
206 // For goexperiment.PacerRedesign: This value is fixed at the
207 // start of a GC cycle, so during a GC cycle it is safe to
208 // read without atomics, and it represents the maximum scannable
212 // lastHeapScan is the number of bytes of heap that were scanned
213 // last GC cycle. It is the same as heapMarked, but only
214 // includes the "scannable" parts of objects.
216 // Updated when the world is stopped.
219 // stackScan is a snapshot of scannableStackSize taken at each GC
220 // STW pause and is used in pacing decisions.
222 // Updated only while the world is stopped.
225 // scannableStackSize is the amount of allocated goroutine stack space in
226 // use by goroutines.
228 // This number tracks allocated goroutine stack space rather than used
229 // goroutine stack space (i.e. what is actually scanned) because used
230 // goroutine stack space is much harder to measure cheaply. By using
231 // allocated space, we make an overestimate; this is OK, it's better
232 // to conservatively overcount than undercount.
234 // Read and updated atomically.
235 scannableStackSize uint64
237 // globalsScan is the total amount of global variable space
238 // that is scannable.
240 // Read and updated atomically.
243 // heapMarked is the number of bytes marked by the previous
244 // GC. After mark termination, heapLive == heapMarked, but
245 // unlike heapLive, heapMarked does not change until the
246 // next mark termination.
249 // heapScanWork is the total heap scan work performed this cycle.
250 // stackScanWork is the total stack scan work performed this cycle.
251 // globalsScanWork is the total globals scan work performed this cycle.
253 // These are updated atomically during the cycle. Updates occur in
254 // bounded batches, since they are both written and read
255 // throughout the cycle. At the end of the cycle, heapScanWork is how
256 // much of the retained heap is scannable.
258 // Currently these are measured in bytes. For most uses, this is an
259 // opaque unit of work, but for estimation the definition is important.
261 // Note that stackScanWork includes all allocated space, not just the
262 // size of the stack itself, mirroring stackSize.
264 // For !goexperiment.PacerRedesign, stackScanWork and globalsScanWork
266 heapScanWork atomic.Int64
267 stackScanWork atomic.Int64
268 globalsScanWork atomic.Int64
270 // bgScanCredit is the scan work credit accumulated by the
271 // concurrent background scan. This credit is accumulated by
272 // the background scan and stolen by mutator assists. This is
273 // updated atomically. Updates occur in bounded batches, since
274 // it is both written and read throughout the cycle.
277 // assistTime is the nanoseconds spent in mutator assists
278 // during this cycle. This is updated atomically. Updates
279 // occur in bounded batches, since it is both written and read
280 // throughout the cycle.
283 // dedicatedMarkTime is the nanoseconds spent in dedicated
284 // mark workers during this cycle. This is updated atomically
285 // at the end of the concurrent mark phase.
286 dedicatedMarkTime int64
288 // fractionalMarkTime is the nanoseconds spent in the
289 // fractional mark worker during this cycle. This is updated
290 // atomically throughout the cycle and will be up-to-date if
291 // the fractional mark worker is not currently running.
292 fractionalMarkTime int64
294 // idleMarkTime is the nanoseconds spent in idle marking
295 // during this cycle. This is updated atomically throughout
299 // markStartTime is the absolute start time in nanoseconds
300 // that assists and background mark workers started.
303 // dedicatedMarkWorkersNeeded is the number of dedicated mark
304 // workers that need to be started. This is computed at the
305 // beginning of each cycle and decremented atomically as
306 // dedicated mark workers get started.
307 dedicatedMarkWorkersNeeded int64
309 // assistWorkPerByte is the ratio of scan work to allocated
310 // bytes that should be performed by mutator assists. This is
311 // computed at the beginning of each cycle and updated every
312 // time heapScan is updated.
313 assistWorkPerByte atomic.Float64
315 // assistBytesPerWork is 1/assistWorkPerByte.
317 // Note that because this is read and written independently
318 // from assistWorkPerByte users may notice a skew between
319 // the two values, and such a state should be safe.
320 assistBytesPerWork atomic.Float64
322 // fractionalUtilizationGoal is the fraction of wall clock
323 // time that should be spent in the fractional mark worker on
324 // each P that isn't running a dedicated worker.
326 // For example, if the utilization goal is 25% and there are
327 // no dedicated workers, this will be 0.25. If the goal is
328 // 25%, there is one dedicated worker, and GOMAXPROCS is 5,
329 // this will be 0.05 to make up the missing 5%.
331 // If this is zero, no fractional workers are needed.
332 fractionalUtilizationGoal float64
334 // test indicates that this is a test-only copy of gcControllerState.
340 func (c *gcControllerState) init(gcPercent int32) {
341 c.heapMinimum = defaultHeapMinimum
343 if goexperiment.PacerRedesign {
344 c.consMarkController = piController{
345 // Tuned first via the Ziegler-Nichols process in simulation,
346 // then the integral time was manually tuned against real-world
347 // applications to deal with noisiness in the measured cons/mark
352 // An update is done once per GC cycle.
355 // Set a high reset time in GC cycles.
356 // This is inversely proportional to the rate at which we
357 // accumulate error from clipping. By making this very high
358 // we make the accumulation slow. In general, clipping is
359 // OK in our situation, hence the choice.
361 // Tune this if we get unintended effects from clipping for
368 // Set a reasonable initial GC trigger.
369 c.triggerRatio = 7 / 8.0
371 // Fake a heapMarked value so it looks like a trigger at
372 // heapMinimum is the appropriate growth from heapMarked.
373 // This will go into computing the initial GC goal.
374 c.heapMarked = uint64(float64(c.heapMinimum) / (1 + c.triggerRatio))
377 // This will also compute and set the GC trigger and goal.
378 c.setGCPercent(gcPercent)
381 // startCycle resets the GC controller's state and computes estimates
382 // for a new GC cycle. The caller must hold worldsema and the world
384 func (c *gcControllerState) startCycle(markStartTime int64, procs int) {
385 c.heapScanWork.Store(0)
386 c.stackScanWork.Store(0)
387 c.globalsScanWork.Store(0)
390 c.dedicatedMarkTime = 0
391 c.fractionalMarkTime = 0
393 c.markStartTime = markStartTime
394 c.stackScan = atomic.Load64(&c.scannableStackSize)
396 // Ensure that the heap goal is at least a little larger than
397 // the current live heap size. This may not be the case if GC
398 // start is delayed or if the allocation that pushed gcController.heapLive
399 // over trigger is large or if the trigger is really close to
400 // GOGC. Assist is proportional to this distance, so enforce a
401 // minimum distance, even if it means going over the GOGC goal
403 if goexperiment.PacerRedesign {
404 if c.heapGoal < c.heapLive+64<<10 {
405 c.heapGoal = c.heapLive + 64<<10
408 if c.heapGoal < c.heapLive+1<<20 {
409 c.heapGoal = c.heapLive + 1<<20
413 // Compute the background mark utilization goal. In general,
414 // this may not come out exactly. We round the number of
415 // dedicated workers so that the utilization is closest to
416 // 25%. For small GOMAXPROCS, this would introduce too much
417 // error, so we add fractional workers in that case.
418 totalUtilizationGoal := float64(procs) * gcBackgroundUtilization
419 c.dedicatedMarkWorkersNeeded = int64(totalUtilizationGoal + 0.5)
420 utilError := float64(c.dedicatedMarkWorkersNeeded)/totalUtilizationGoal - 1
421 const maxUtilError = 0.3
422 if utilError < -maxUtilError || utilError > maxUtilError {
423 // Rounding put us more than 30% off our goal. With
424 // gcBackgroundUtilization of 25%, this happens for
425 // GOMAXPROCS<=3 or GOMAXPROCS=6. Enable fractional
426 // workers to compensate.
427 if float64(c.dedicatedMarkWorkersNeeded) > totalUtilizationGoal {
428 // Too many dedicated workers.
429 c.dedicatedMarkWorkersNeeded--
431 c.fractionalUtilizationGoal = (totalUtilizationGoal - float64(c.dedicatedMarkWorkersNeeded)) / float64(procs)
433 c.fractionalUtilizationGoal = 0
436 // In STW mode, we just want dedicated workers.
437 if debug.gcstoptheworld > 0 {
438 c.dedicatedMarkWorkersNeeded = int64(procs)
439 c.fractionalUtilizationGoal = 0
443 for _, p := range allp {
445 p.gcFractionalMarkTime = 0
448 // Compute initial values for controls that are updated
449 // throughout the cycle.
452 if debug.gcpacertrace > 0 {
453 assistRatio := c.assistWorkPerByte.Load()
454 print("pacer: assist ratio=", assistRatio,
455 " (scan ", gcController.heapScan>>20, " MB in ",
456 work.initialHeapLive>>20, "->",
457 c.heapGoal>>20, " MB)",
458 " workers=", c.dedicatedMarkWorkersNeeded,
459 "+", c.fractionalUtilizationGoal, "\n")
463 // revise updates the assist ratio during the GC cycle to account for
464 // improved estimates. This should be called whenever gcController.heapScan,
465 // gcController.heapLive, or gcController.heapGoal is updated. It is safe to
466 // call concurrently, but it may race with other calls to revise.
468 // The result of this race is that the two assist ratio values may not line
469 // up or may be stale. In practice this is OK because the assist ratio
470 // moves slowly throughout a GC cycle, and the assist ratio is a best-effort
471 // heuristic anyway. Furthermore, no part of the heuristic depends on
472 // the two assist ratio values being exact reciprocals of one another, since
473 // the two values are used to convert values from different sources.
475 // The worst case result of this raciness is that we may miss a larger shift
476 // in the ratio (say, if we decide to pace more aggressively against the
477 // hard heap goal) but even this "hard goal" is best-effort (see #40460).
478 // The dedicated GC should ensure we don't exceed the hard goal by too much
479 // in the rare case we do exceed it.
481 // It should only be called when gcBlackenEnabled != 0 (because this
482 // is when assists are enabled and the necessary statistics are
484 func (c *gcControllerState) revise() {
485 gcPercent := atomic.Loadint32(&c.gcPercent)
487 // If GC is disabled but we're running a forced GC,
488 // act like GOGC is huge for the below calculations.
491 live := atomic.Load64(&c.heapLive)
492 scan := atomic.Load64(&c.heapScan)
493 work := c.heapScanWork.Load() + c.stackScanWork.Load() + c.globalsScanWork.Load()
495 // Assume we're under the soft goal. Pace GC to complete at
496 // heapGoal assuming the heap is in steady-state.
497 heapGoal := int64(atomic.Load64(&c.heapGoal))
499 var scanWorkExpected int64
500 if goexperiment.PacerRedesign {
501 // The expected scan work is computed as the amount of bytes scanned last
502 // GC cycle, plus our estimate of stacks and globals work for this cycle.
503 scanWorkExpected = int64(c.lastHeapScan + c.stackScan + c.globalsScan)
505 // maxScanWork is a worst-case estimate of the amount of scan work that
506 // needs to be performed in this GC cycle. Specifically, it represents
507 // the case where *all* scannable memory turns out to be live.
508 maxScanWork := int64(scan + c.stackScan + c.globalsScan)
509 if work > scanWorkExpected {
510 // We've already done more scan work than expected. Because our expectation
511 // is based on a steady-state scannable heap size, we assume this means our
512 // heap is growing. Compute a new heap goal that takes our existing runway
513 // computed for scanWorkExpected and extrapolates it to maxScanWork, the worst-case
514 // scan work. This keeps our assist ratio stable if the heap continues to grow.
516 // The effect of this mechanism is that assists stay flat in the face of heap
517 // growths. It's OK to use more memory this cycle to scan all the live heap,
518 // because the next GC cycle is inevitably going to use *at least* that much
520 extHeapGoal := int64(float64(heapGoal-int64(c.trigger))/float64(scanWorkExpected)*float64(maxScanWork)) + int64(c.trigger)
521 scanWorkExpected = maxScanWork
523 // hardGoal is a hard limit on the amount that we're willing to push back the
524 // heap goal, and that's twice the heap goal (i.e. if GOGC=100 and the heap and/or
525 // stacks and/or globals grow to twice their size, this limits the current GC cycle's
526 // growth to 4x the original live heap's size).
528 // This maintains the invariant that we use no more memory than the next GC cycle
530 hardGoal := int64((1.0 + float64(gcPercent)/100.0) * float64(heapGoal))
531 if extHeapGoal > hardGoal {
532 extHeapGoal = hardGoal
534 heapGoal = extHeapGoal
536 if int64(live) > heapGoal {
537 // We're already past our heap goal, even the extrapolated one.
538 // Leave ourselves some extra runway, so in the worst case we
539 // finish by that point.
540 const maxOvershoot = 1.1
541 heapGoal = int64(float64(heapGoal) * maxOvershoot)
543 // Compute the upper bound on the scan work remaining.
544 scanWorkExpected = maxScanWork
547 // Compute the expected scan work remaining.
549 // This is estimated based on the expected
550 // steady-state scannable heap. For example, with
551 // GOGC=100, only half of the scannable heap is
552 // expected to be live, so that's what we target.
554 // (This is a float calculation to avoid overflowing on
556 scanWorkExpected = int64(float64(scan) * 100 / float64(100+gcPercent))
557 if int64(live) > heapGoal || work > scanWorkExpected {
558 // We're past the soft goal, or we've already done more scan
559 // work than we expected. Pace GC so that in the worst case it
560 // will complete by the hard goal.
561 const maxOvershoot = 1.1
562 heapGoal = int64(float64(heapGoal) * maxOvershoot)
564 // Compute the upper bound on the scan work remaining.
565 scanWorkExpected = int64(scan)
569 // Compute the remaining scan work estimate.
571 // Note that we currently count allocations during GC as both
572 // scannable heap (heapScan) and scan work completed
573 // (scanWork), so allocation will change this difference
574 // slowly in the soft regime and not at all in the hard
576 scanWorkRemaining := scanWorkExpected - work
577 if scanWorkRemaining < 1000 {
578 // We set a somewhat arbitrary lower bound on
579 // remaining scan work since if we aim a little high,
580 // we can miss by a little.
582 // We *do* need to enforce that this is at least 1,
583 // since marking is racy and double-scanning objects
584 // may legitimately make the remaining scan work
585 // negative, even in the hard goal regime.
586 scanWorkRemaining = 1000
589 // Compute the heap distance remaining.
590 heapRemaining := heapGoal - int64(live)
591 if heapRemaining <= 0 {
592 // This shouldn't happen, but if it does, avoid
593 // dividing by zero or setting the assist negative.
597 // Compute the mutator assist ratio so by the time the mutator
598 // allocates the remaining heap bytes up to heapGoal, it will
599 // have done (or stolen) the remaining amount of scan work.
600 // Note that the assist ratio values are updated atomically
601 // but not together. This means there may be some degree of
602 // skew between the two values. This is generally OK as the
603 // values shift relatively slowly over the course of a GC
605 assistWorkPerByte := float64(scanWorkRemaining) / float64(heapRemaining)
606 assistBytesPerWork := float64(heapRemaining) / float64(scanWorkRemaining)
607 c.assistWorkPerByte.Store(assistWorkPerByte)
608 c.assistBytesPerWork.Store(assistBytesPerWork)
611 // endCycle computes the trigger ratio (!goexperiment.PacerRedesign)
612 // or the consMark estimate (goexperiment.PacerRedesign) for the next cycle.
613 // Returns the trigger ratio if application, or 0 (goexperiment.PacerRedesign).
614 // userForced indicates whether the current GC cycle was forced
615 // by the application.
616 func (c *gcControllerState) endCycle(now int64, procs int, userForced bool) float64 {
617 // Record last heap goal for the scavenger.
618 // We'll be updating the heap goal soon.
619 gcController.lastHeapGoal = gcController.heapGoal
621 // Compute the duration of time for which assists were turned on.
622 assistDuration := now - c.markStartTime
624 // Assume background mark hit its utilization goal.
625 utilization := gcBackgroundUtilization
626 // Add assist utilization; avoid divide by zero.
627 if assistDuration > 0 {
628 utilization += float64(c.assistTime) / float64(assistDuration*int64(procs))
631 if goexperiment.PacerRedesign {
632 if c.heapLive <= c.trigger {
633 // Shouldn't happen, but let's be very safe about this in case the
634 // GC is somehow extremely short.
636 // In this case though, the only reasonable value for c.heapLive-c.trigger
637 // would be 0, which isn't really all that useful, i.e. the GC was so short
638 // that it didn't matter.
640 // Ignore this case and don't update anything.
643 idleUtilization := 0.0
644 if assistDuration > 0 {
645 idleUtilization = float64(c.idleMarkTime) / float64(assistDuration*int64(procs))
647 // Determine the cons/mark ratio.
649 // The units we want for the numerator and denominator are both B / cpu-ns.
650 // We get this by taking the bytes allocated or scanned, and divide by the amount of
651 // CPU time it took for those operations. For allocations, that CPU time is
653 // assistDuration * procs * (1 - utilization)
655 // Where utilization includes just background GC workers and assists. It does *not*
656 // include idle GC work time, because in theory the mutator is free to take that at
659 // For scanning, that CPU time is
661 // assistDuration * procs * (utilization + idleUtilization)
663 // In this case, we *include* idle utilization, because that is additional CPU time that the
664 // the GC had available to it.
666 // In effect, idle GC time is sort of double-counted here, but it's very weird compared
667 // to other kinds of GC work, because of how fluid it is. Namely, because the mutator is
668 // *always* free to take it.
670 // So this calculation is really:
671 // (heapLive-trigger) / (assistDuration * procs * (1-utilization)) /
672 // (scanWork) / (assistDuration * procs * (utilization+idleUtilization)
674 // Note that because we only care about the ratio, assistDuration and procs cancel out.
675 scanWork := c.heapScanWork.Load() + c.stackScanWork.Load() + c.globalsScanWork.Load()
676 currentConsMark := (float64(c.heapLive-c.trigger) * (utilization + idleUtilization)) /
677 (float64(scanWork) * (1 - utilization))
679 // Update cons/mark controller.
680 oldConsMark := c.consMark
681 c.consMark = c.consMarkController.next(c.consMark, currentConsMark)
683 if debug.gcpacertrace > 0 {
685 print("pacer: ", int(utilization*100), "% CPU (", int(gcGoalUtilization*100), " exp.) for ")
686 print(c.heapScanWork.Load(), "+", c.stackScanWork.Load(), "+", c.globalsScanWork.Load(), " B work (", c.lastHeapScan+c.stackScan+c.globalsScan, " B exp.) ")
687 print("in ", c.trigger, " B -> ", c.heapLive, " B (∆goal ", int64(c.heapLive)-int64(c.heapGoal), ", cons/mark ", oldConsMark, ")")
694 // !goexperiment.PacerRedesign below.
697 // Forced GC means this cycle didn't start at the
698 // trigger, so where it finished isn't good
699 // information about how to adjust the trigger.
700 // Just leave it where it is.
701 return c.triggerRatio
704 // Proportional response gain for the trigger controller. Must
705 // be in [0, 1]. Lower values smooth out transient effects but
706 // take longer to respond to phase changes. Higher values
707 // react to phase changes quickly, but are more affected by
708 // transient changes. Values near 1 may be unstable.
709 const triggerGain = 0.5
711 // Compute next cycle trigger ratio. First, this computes the
712 // "error" for this cycle; that is, how far off the trigger
713 // was from what it should have been, accounting for both heap
714 // growth and GC CPU utilization. We compute the actual heap
715 // growth during this cycle and scale that by how far off from
716 // the goal CPU utilization we were (to estimate the heap
717 // growth if we had the desired CPU utilization). The
718 // difference between this estimate and the GOGC-based goal
719 // heap growth is the error.
720 goalGrowthRatio := c.effectiveGrowthRatio()
721 actualGrowthRatio := float64(c.heapLive)/float64(c.heapMarked) - 1
722 triggerError := goalGrowthRatio - c.triggerRatio - utilization/gcGoalUtilization*(actualGrowthRatio-c.triggerRatio)
724 // Finally, we adjust the trigger for next time by this error,
725 // damped by the proportional gain.
726 triggerRatio := c.triggerRatio + triggerGain*triggerError
728 if debug.gcpacertrace > 0 {
729 // Print controller state in terms of the design
731 H_m_prev := c.heapMarked
732 h_t := c.triggerRatio
734 h_a := actualGrowthRatio
736 h_g := goalGrowthRatio
737 H_g := int64(float64(H_m_prev) * (1 + h_g))
739 u_g := gcGoalUtilization
740 W_a := c.heapScanWork.Load()
741 print("pacer: H_m_prev=", H_m_prev,
742 " h_t=", h_t, " H_T=", H_T,
743 " h_a=", h_a, " H_a=", H_a,
744 " h_g=", h_g, " H_g=", H_g,
745 " u_a=", u_a, " u_g=", u_g,
747 " goalΔ=", goalGrowthRatio-h_t,
748 " actualΔ=", h_a-h_t,
749 " u_a/u_g=", u_a/u_g,
756 // enlistWorker encourages another dedicated mark worker to start on
757 // another P if there are spare worker slots. It is used by putfull
758 // when more work is made available.
761 func (c *gcControllerState) enlistWorker() {
762 // If there are idle Ps, wake one so it will run an idle worker.
763 // NOTE: This is suspected of causing deadlocks. See golang.org/issue/19112.
765 // if atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 {
770 // There are no idle Ps. If we need more dedicated workers,
771 // try to preempt a running P so it will switch to a worker.
772 if c.dedicatedMarkWorkersNeeded <= 0 {
775 // Pick a random other P to preempt.
780 if gp == nil || gp.m == nil || gp.m.p == 0 {
783 myID := gp.m.p.ptr().id
784 for tries := 0; tries < 5; tries++ {
785 id := int32(fastrandn(uint32(gomaxprocs - 1)))
790 if p.status != _Prunning {
799 // findRunnableGCWorker returns a background mark worker for _p_ if it
800 // should be run. This must only be called when gcBlackenEnabled != 0.
801 func (c *gcControllerState) findRunnableGCWorker(_p_ *p) *g {
802 if gcBlackenEnabled == 0 {
803 throw("gcControllerState.findRunnable: blackening not enabled")
806 if !gcMarkWorkAvailable(_p_) {
807 // No work to be done right now. This can happen at
808 // the end of the mark phase when there are still
809 // assists tapering off. Don't bother running a worker
810 // now because it'll just return immediately.
814 // Grab a worker before we commit to running below.
815 node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
817 // There is at least one worker per P, so normally there are
818 // enough workers to run on all Ps, if necessary. However, once
819 // a worker enters gcMarkDone it may park without rejoining the
820 // pool, thus freeing a P with no corresponding worker.
821 // gcMarkDone never depends on another worker doing work, so it
822 // is safe to simply do nothing here.
824 // If gcMarkDone bails out without completing the mark phase,
825 // it will always do so with queued global work. Thus, that P
826 // will be immediately eligible to re-run the worker G it was
827 // just using, ensuring work can complete.
831 decIfPositive := func(ptr *int64) bool {
833 v := atomic.Loadint64(ptr)
838 if atomic.Casint64(ptr, v, v-1) {
844 if decIfPositive(&c.dedicatedMarkWorkersNeeded) {
845 // This P is now dedicated to marking until the end of
846 // the concurrent mark phase.
847 _p_.gcMarkWorkerMode = gcMarkWorkerDedicatedMode
848 } else if c.fractionalUtilizationGoal == 0 {
849 // No need for fractional workers.
850 gcBgMarkWorkerPool.push(&node.node)
853 // Is this P behind on the fractional utilization
856 // This should be kept in sync with pollFractionalWorkerExit.
857 delta := nanotime() - c.markStartTime
858 if delta > 0 && float64(_p_.gcFractionalMarkTime)/float64(delta) > c.fractionalUtilizationGoal {
859 // Nope. No need to run a fractional worker.
860 gcBgMarkWorkerPool.push(&node.node)
863 // Run a fractional worker.
864 _p_.gcMarkWorkerMode = gcMarkWorkerFractionalMode
867 // Run the background mark worker.
869 casgstatus(gp, _Gwaiting, _Grunnable)
876 // resetLive sets up the controller state for the next mark phase after the end
877 // of the previous one. Must be called after endCycle and before commit, before
878 // the world is started.
880 // The world must be stopped.
881 func (c *gcControllerState) resetLive(bytesMarked uint64) {
882 c.heapMarked = bytesMarked
883 c.heapLive = bytesMarked
884 c.heapScan = uint64(c.heapScanWork.Load())
885 c.lastHeapScan = uint64(c.heapScanWork.Load())
887 // heapLive was updated, so emit a trace event.
893 // logWorkTime updates mark work accounting in the controller by a duration of
894 // work in nanoseconds.
896 // Safe to execute at any time.
897 func (c *gcControllerState) logWorkTime(mode gcMarkWorkerMode, duration int64) {
899 case gcMarkWorkerDedicatedMode:
900 atomic.Xaddint64(&c.dedicatedMarkTime, duration)
901 atomic.Xaddint64(&c.dedicatedMarkWorkersNeeded, 1)
902 case gcMarkWorkerFractionalMode:
903 atomic.Xaddint64(&c.fractionalMarkTime, duration)
904 case gcMarkWorkerIdleMode:
905 atomic.Xaddint64(&c.idleMarkTime, duration)
907 throw("logWorkTime: unknown mark worker mode")
911 func (c *gcControllerState) update(dHeapLive, dHeapScan int64) {
913 atomic.Xadd64(&gcController.heapLive, dHeapLive)
915 // gcController.heapLive changed.
919 // Only update heapScan in the new pacer redesign if we're not
920 // currently in a GC.
921 if !goexperiment.PacerRedesign || gcBlackenEnabled == 0 {
923 atomic.Xadd64(&gcController.heapScan, dHeapScan)
926 if gcBlackenEnabled != 0 {
927 // gcController.heapLive and heapScan changed.
932 func (c *gcControllerState) addScannableStack(pp *p, amount int64) {
934 atomic.Xadd64(&c.scannableStackSize, amount)
937 pp.scannableStackSizeDelta += amount
938 if pp.scannableStackSizeDelta >= scannableStackSizeSlack || pp.scannableStackSizeDelta <= -scannableStackSizeSlack {
939 atomic.Xadd64(&c.scannableStackSize, pp.scannableStackSizeDelta)
940 pp.scannableStackSizeDelta = 0
944 func (c *gcControllerState) addGlobals(amount int64) {
945 atomic.Xadd64(&c.globalsScan, amount)
948 // commit recomputes all pacing parameters from scratch, namely
949 // absolute trigger, the heap goal, mark pacing, and sweep pacing.
951 // If goexperiment.PacerRedesign is true, triggerRatio is ignored.
953 // This can be called any time. If GC is the in the middle of a
954 // concurrent phase, it will adjust the pacing of that phase.
956 // This depends on gcPercent, gcController.heapMarked, and
957 // gcController.heapLive. These must be up to date.
959 // mheap_.lock must be held or the world must be stopped.
960 func (c *gcControllerState) commit(triggerRatio float64) {
962 assertWorldStoppedOrLockHeld(&mheap_.lock)
965 if !goexperiment.PacerRedesign {
966 c.oldCommit(triggerRatio)
970 // Compute the next GC goal, which is when the allocated heap
971 // has grown by GOGC/100 over where it started the last cycle,
972 // plus additional runway for non-heap sources of GC work.
974 if c.gcPercent >= 0 {
975 goal = c.heapMarked + (c.heapMarked+atomic.Load64(&c.stackScan)+atomic.Load64(&c.globalsScan))*uint64(c.gcPercent)/100
978 // Don't trigger below the minimum heap size.
979 minTrigger := c.heapMinimum
981 // Concurrent sweep happens in the heap growth
982 // from gcController.heapLive to trigger, so ensure
983 // that concurrent sweep has some heap growth
984 // in which to perform sweeping before we
985 // start the next GC cycle.
986 sweepMin := atomic.Load64(&c.heapLive) + sweepMinHeapDistance
987 if sweepMin > minTrigger {
988 minTrigger = sweepMin
992 // If we let the trigger go too low, then if the application
993 // is allocating very rapidly we might end up in a situation
994 // where we're allocating black during a nearly always-on GC.
995 // The result of this is a growing heap and ultimately an
996 // increase in RSS. By capping us at a point >0, we're essentially
997 // saying that we're OK using more CPU during the GC to prevent
998 // this growth in RSS.
1000 // The current constant was chosen empirically: given a sufficiently
1001 // fast/scalable allocator with 48 Ps that could drive the trigger ratio
1002 // to <0.05, this constant causes applications to retain the same peak
1003 // RSS compared to not having this allocator.
1004 if triggerBound := uint64(0.7*float64(goal-c.heapMarked)) + c.heapMarked; minTrigger < triggerBound {
1005 minTrigger = triggerBound
1008 // For small heaps, set the max trigger point at 95% of the heap goal.
1009 // This ensures we always have *some* headroom when the GC actually starts.
1010 // For larger heaps, set the max trigger point at the goal, minus the
1011 // minimum heap size.
1012 // This choice follows from the fact that the minimum heap size is chosen
1013 // to reflect the costs of a GC with no work to do. With a large heap but
1014 // very little scan work to perform, this gives us exactly as much runway
1015 // as we would need, in the worst case.
1016 maxRunway := uint64(0.95 * float64(goal-c.heapMarked))
1017 if largeHeapMaxRunway := goal - c.heapMinimum; goal > c.heapMinimum && maxRunway < largeHeapMaxRunway {
1018 maxRunway = largeHeapMaxRunway
1020 maxTrigger := maxRunway + c.heapMarked
1021 if maxTrigger < minTrigger {
1022 maxTrigger = minTrigger
1025 // Compute the trigger by using our estimate of the cons/mark ratio.
1027 // The idea is to take our expected scan work, and multiply it by
1028 // the cons/mark ratio to determine how long it'll take to complete
1029 // that scan work in terms of bytes allocated. This gives us our GC's
1032 // However, the cons/mark ratio is a ratio of rates per CPU-second, but
1033 // here we care about the relative rates for some division of CPU
1034 // resources among the mutator and the GC.
1036 // To summarize, we have B / cpu-ns, and we want B / ns. We get that
1037 // by multiplying by our desired division of CPU resources. We choose
1038 // to express CPU resources as GOMAPROCS*fraction. Note that because
1039 // we're working with a ratio here, we can omit the number of CPU cores,
1040 // because they'll appear in the numerator and denominator and cancel out.
1041 // As a result, this is basically just "weighing" the cons/mark ratio by
1042 // our desired division of resources.
1044 // Furthermore, by setting the trigger so that CPU resources are divided
1045 // this way, assuming that the cons/mark ratio is correct, we make that
1046 // division a reality.
1048 runway := uint64((c.consMark * (1 - gcGoalUtilization) / (gcGoalUtilization)) * float64(c.lastHeapScan+c.stackScan+c.globalsScan))
1050 trigger = minTrigger
1052 trigger = goal - runway
1054 if trigger < minTrigger {
1055 trigger = minTrigger
1057 if trigger > maxTrigger {
1058 trigger = maxTrigger
1064 // Commit to the trigger and goal.
1066 atomic.Store64(&c.heapGoal, goal)
1071 // Update mark pacing.
1072 if gcphase != _GCoff {
1077 // oldCommit sets the trigger ratio and updates everything
1078 // derived from it: the absolute trigger, the heap goal, mark pacing,
1079 // and sweep pacing.
1081 // This can be called any time. If GC is the in the middle of a
1082 // concurrent phase, it will adjust the pacing of that phase.
1084 // This depends on gcPercent, gcController.heapMarked, and
1085 // gcController.heapLive. These must be up to date.
1087 // For !goexperiment.PacerRedesign.
1088 func (c *gcControllerState) oldCommit(triggerRatio float64) {
1089 // Compute the next GC goal, which is when the allocated heap
1090 // has grown by GOGC/100 over the heap marked by the last
1093 if c.gcPercent >= 0 {
1094 goal = c.heapMarked + c.heapMarked*uint64(c.gcPercent)/100
1097 // Set the trigger ratio, capped to reasonable bounds.
1098 if c.gcPercent >= 0 {
1099 scalingFactor := float64(c.gcPercent) / 100
1100 // Ensure there's always a little margin so that the
1101 // mutator assist ratio isn't infinity.
1102 maxTriggerRatio := 0.95 * scalingFactor
1103 if triggerRatio > maxTriggerRatio {
1104 triggerRatio = maxTriggerRatio
1107 // If we let triggerRatio go too low, then if the application
1108 // is allocating very rapidly we might end up in a situation
1109 // where we're allocating black during a nearly always-on GC.
1110 // The result of this is a growing heap and ultimately an
1111 // increase in RSS. By capping us at a point >0, we're essentially
1112 // saying that we're OK using more CPU during the GC to prevent
1113 // this growth in RSS.
1115 // The current constant was chosen empirically: given a sufficiently
1116 // fast/scalable allocator with 48 Ps that could drive the trigger ratio
1117 // to <0.05, this constant causes applications to retain the same peak
1118 // RSS compared to not having this allocator.
1119 minTriggerRatio := 0.6 * scalingFactor
1120 if triggerRatio < minTriggerRatio {
1121 triggerRatio = minTriggerRatio
1123 } else if triggerRatio < 0 {
1124 // gcPercent < 0, so just make sure we're not getting a negative
1125 // triggerRatio. This case isn't expected to happen in practice,
1126 // and doesn't really matter because if gcPercent < 0 then we won't
1127 // ever consume triggerRatio further on in this function, but let's
1128 // just be defensive here; the triggerRatio being negative is almost
1129 // certainly undesirable.
1132 c.triggerRatio = triggerRatio
1134 // Compute the absolute GC trigger from the trigger ratio.
1136 // We trigger the next GC cycle when the allocated heap has
1137 // grown by the trigger ratio over the marked heap size.
1138 trigger := ^uint64(0)
1139 if c.gcPercent >= 0 {
1140 trigger = uint64(float64(c.heapMarked) * (1 + triggerRatio))
1141 // Don't trigger below the minimum heap size.
1142 minTrigger := c.heapMinimum
1144 // Concurrent sweep happens in the heap growth
1145 // from gcController.heapLive to trigger, so ensure
1146 // that concurrent sweep has some heap growth
1147 // in which to perform sweeping before we
1148 // start the next GC cycle.
1149 sweepMin := atomic.Load64(&c.heapLive) + sweepMinHeapDistance
1150 if sweepMin > minTrigger {
1151 minTrigger = sweepMin
1154 if trigger < minTrigger {
1155 trigger = minTrigger
1157 if int64(trigger) < 0 {
1158 print("runtime: heapGoal=", c.heapGoal, " heapMarked=", c.heapMarked, " gcController.heapLive=", c.heapLive, " initialHeapLive=", work.initialHeapLive, "triggerRatio=", triggerRatio, " minTrigger=", minTrigger, "\n")
1159 throw("trigger underflow")
1162 // The trigger ratio is always less than GOGC/100, but
1163 // other bounds on the trigger may have raised it.
1164 // Push up the goal, too.
1169 // Commit to the trigger and goal.
1171 atomic.Store64(&c.heapGoal, goal)
1176 // Update mark pacing.
1177 if gcphase != _GCoff {
1182 // effectiveGrowthRatio returns the current effective heap growth
1183 // ratio (GOGC/100) based on heapMarked from the previous GC and
1184 // heapGoal for the current GC.
1186 // This may differ from gcPercent/100 because of various upper and
1187 // lower bounds on gcPercent. For example, if the heap is smaller than
1188 // heapMinimum, this can be higher than gcPercent/100.
1190 // mheap_.lock must be held or the world must be stopped.
1191 func (c *gcControllerState) effectiveGrowthRatio() float64 {
1193 assertWorldStoppedOrLockHeld(&mheap_.lock)
1196 egogc := float64(atomic.Load64(&c.heapGoal)-c.heapMarked) / float64(c.heapMarked)
1198 // Shouldn't happen, but just in case.
1204 // setGCPercent updates gcPercent and all related pacer state.
1205 // Returns the old value of gcPercent.
1207 // Calls gcControllerState.commit.
1209 // The world must be stopped, or mheap_.lock must be held.
1210 func (c *gcControllerState) setGCPercent(in int32) int32 {
1212 assertWorldStoppedOrLockHeld(&mheap_.lock)
1219 // Write it atomically so readers like revise() can read it safely.
1220 atomic.Storeint32(&c.gcPercent, in)
1221 c.heapMinimum = defaultHeapMinimum * uint64(c.gcPercent) / 100
1222 // Update pacing in response to gcPercent change.
1223 c.commit(c.triggerRatio)
1228 //go:linkname setGCPercent runtime/debug.setGCPercent
1229 func setGCPercent(in int32) (out int32) {
1230 // Run on the system stack since we grab the heap lock.
1231 systemstack(func() {
1233 out = gcController.setGCPercent(in)
1234 gcPaceSweeper(gcController.trigger)
1235 gcPaceScavenger(gcController.heapGoal, gcController.lastHeapGoal)
1236 unlock(&mheap_.lock)
1239 // If we just disabled GC, wait for any concurrent GC mark to
1240 // finish so we always return with no GC running.
1242 gcWaitOnMark(atomic.Load(&work.cycles))
1248 func readGOGC() int32 {
1249 p := gogetenv("GOGC")
1253 if n, ok := atoi32(p); ok {
1259 type piController struct {
1260 kp float64 // Proportional constant.
1261 ti float64 // Integral time constant.
1262 tt float64 // Reset time in GC cyles.
1264 // Period in GC cycles between updates.
1267 min, max float64 // Output boundaries.
1269 // PI controller state.
1271 errIntegral float64 // Integral of the error from t=0 to now.
1274 func (c *piController) next(input, setpoint float64) float64 {
1275 // Compute the raw output value.
1276 prop := c.kp * (setpoint - input)
1277 rawOutput := prop + c.errIntegral
1279 // Clamp rawOutput into output.
1283 } else if output > c.max {
1287 // Update the controller's state.
1288 if c.ti != 0 && c.tt != 0 {
1289 c.errIntegral += (c.kp*c.period/c.ti)*(setpoint-input) + (c.period/c.tt)*(output-rawOutput)