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 "runtime/internal/atomic"
14 // gcGoalUtilization is the goal CPU utilization for
15 // marking as a fraction of GOMAXPROCS.
16 gcGoalUtilization = 0.30
18 // gcBackgroundUtilization is the fixed CPU utilization for background
19 // marking. It must be <= gcGoalUtilization. The difference between
20 // gcGoalUtilization and gcBackgroundUtilization will be made up by
21 // mark assists. The scheduler will aim to use within 50% of this
24 // Setting this to < gcGoalUtilization avoids saturating the trigger
25 // feedback controller when there are no assists, which allows it to
26 // better control CPU and heap growth. However, the larger the gap,
27 // the more mutator assists are expected to happen, which impact
29 gcBackgroundUtilization = 0.25
31 // gcCreditSlack is the amount of scan work credit that can
32 // accumulate locally before updating gcController.scanWork and,
33 // optionally, gcController.bgScanCredit. Lower values give a more
34 // accurate assist ratio and make it more likely that assists will
35 // successfully steal background credit. Higher values reduce memory
39 // gcAssistTimeSlack is the nanoseconds of mutator assist time that
40 // can accumulate on a P before updating gcController.assistTime.
41 gcAssistTimeSlack = 5000
43 // gcOverAssistWork determines how many extra units of scan work a GC
44 // assist does when an assist happens. This amortizes the cost of an
45 // assist by pre-paying for this many bytes of future allocations.
46 gcOverAssistWork = 64 << 10
48 // defaultHeapMinimum is the value of heapMinimum for GOGC==100.
49 defaultHeapMinimum = 4 << 20
51 // scannableStackSizeSlack is the bytes of stack space allocated or freed
52 // that can accumulate on a P before updating gcController.stackSize.
53 scannableStackSizeSlack = 8 << 10
57 if offset := unsafe.Offsetof(gcController.heapLive); offset%8 != 0 {
59 throw("gcController.heapLive not aligned to 8 bytes")
63 // gcController implements the GC pacing controller that determines
64 // when to trigger concurrent garbage collection and how much marking
65 // work to do in mutator assists and background marking.
67 // It uses a feedback control algorithm to adjust the gcController.trigger
68 // trigger based on the heap growth and GC CPU utilization each cycle.
69 // This algorithm optimizes for heap growth to match GOGC and for CPU
70 // utilization between assist and background marking to be 25% of
71 // GOMAXPROCS. The high-level design of this algorithm is documented
72 // at https://golang.org/s/go15gcpacing.
74 // All fields of gcController are used only during a single mark
76 var gcController gcControllerState
78 type gcControllerState struct {
79 // Initialized from $GOGC. GOGC=off means no GC.
81 // Updated atomically with mheap_.lock held or during a STW.
82 // Safe to read atomically at any time, or non-atomically with
83 // mheap_.lock or STW.
86 _ uint32 // padding so following 64-bit values are 8-byte aligned
88 // heapMinimum is the minimum heap size at which to trigger GC.
89 // For small heaps, this overrides the usual GOGC*live set rule.
91 // When there is a very small live set but a lot of allocation, simply
92 // collecting when the heap reaches GOGC*live results in many GC
93 // cycles and high total per-GC overhead. This minimum amortizes this
94 // per-GC overhead while keeping the heap reasonably small.
96 // During initialization this is set to 4MB*GOGC/100. In the case of
97 // GOGC==0, this will set heapMinimum to 0, resulting in constant
98 // collection even when the heap size is small, which is useful for
102 // triggerRatio is the heap growth ratio that triggers marking.
104 // E.g., if this is 0.6, then GC should start when the live
105 // heap has reached 1.6 times the heap size marked by the
106 // previous cycle. This should be ≤ GOGC/100 so the trigger
107 // heap size is less than the goal heap size. This is set
108 // during mark termination for the next cycle's trigger.
110 // Protected by mheap_.lock or a STW.
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 triggerRatio during mark termination
120 // for the next cycle's trigger.
122 // Protected by mheap_.lock or a STW.
125 // heapGoal is the goal heapLive for when next GC ends.
126 // Set to ^uint64(0) if disabled.
128 // Read and written atomically, unless the world is stopped.
131 // lastHeapGoal is the value of heapGoal for the previous GC.
132 // Note that this is distinct from the last value heapGoal had,
133 // because it could change if e.g. gcPercent changes.
135 // Read and written with the world stopped or with mheap_.lock held.
138 // heapLive is the number of bytes considered live by the GC.
139 // That is: retained by the most recent GC plus allocated
140 // since then. heapLive ≤ memstats.heapAlloc, since heapAlloc includes
141 // unmarked objects that have not yet been swept (and hence goes up as we
142 // allocate and down as we sweep) while heapLive excludes these
143 // objects (and hence only goes up between GCs).
145 // This is updated atomically without locking. To reduce
146 // contention, this is updated only when obtaining a span from
147 // an mcentral and at this point it counts all of the
148 // unallocated slots in that span (which will be allocated
149 // before that mcache obtains another span from that
150 // mcentral). Hence, it slightly overestimates the "true" live
151 // heap size. It's better to overestimate than to
152 // underestimate because 1) this triggers the GC earlier than
153 // necessary rather than potentially too late and 2) this
154 // leads to a conservative GC rate rather than a GC rate that
155 // is potentially too low.
157 // Reads should likewise be atomic (or during STW).
159 // Whenever this is updated, call traceHeapAlloc() and
160 // this gcControllerState's revise() method.
163 // heapScan is the number of bytes of "scannable" heap. This
164 // is the live heap (as counted by heapLive), but omitting
165 // no-scan objects and no-scan tails of objects.
167 // Whenever this is updated, call this gcControllerState's
170 // Read and written atomically or with the world stopped.
173 // stackScan is a snapshot of scannableStackSize taken at each GC
174 // STW pause and is used in pacing decisions.
176 // Updated only while the world is stopped.
179 // scannableStackSize is the amount of allocated goroutine stack space in
180 // use by goroutines.
182 // Read and updated atomically.
183 scannableStackSize uint64
185 // heapMarked is the number of bytes marked by the previous
186 // GC. After mark termination, heapLive == heapMarked, but
187 // unlike heapLive, heapMarked does not change until the
188 // next mark termination.
191 // scanWork is the total scan work performed this cycle. This
192 // is updated atomically during the cycle. Updates occur in
193 // bounded batches, since it is both written and read
194 // throughout the cycle. At the end of the cycle, this is how
195 // much of the retained heap is scannable.
197 // Currently this is the bytes of heap scanned. For most uses,
198 // this is an opaque unit of work, but for estimation the
199 // definition is important.
202 // bgScanCredit is the scan work credit accumulated by the
203 // concurrent background scan. This credit is accumulated by
204 // the background scan and stolen by mutator assists. This is
205 // updated atomically. Updates occur in bounded batches, since
206 // it is both written and read throughout the cycle.
209 // assistTime is the nanoseconds spent in mutator assists
210 // during this cycle. This is updated atomically. Updates
211 // occur in bounded batches, since it is both written and read
212 // throughout the cycle.
215 // dedicatedMarkTime is the nanoseconds spent in dedicated
216 // mark workers during this cycle. This is updated atomically
217 // at the end of the concurrent mark phase.
218 dedicatedMarkTime int64
220 // fractionalMarkTime is the nanoseconds spent in the
221 // fractional mark worker during this cycle. This is updated
222 // atomically throughout the cycle and will be up-to-date if
223 // the fractional mark worker is not currently running.
224 fractionalMarkTime int64
226 // idleMarkTime is the nanoseconds spent in idle marking
227 // during this cycle. This is updated atomically throughout
231 // markStartTime is the absolute start time in nanoseconds
232 // that assists and background mark workers started.
235 // dedicatedMarkWorkersNeeded is the number of dedicated mark
236 // workers that need to be started. This is computed at the
237 // beginning of each cycle and decremented atomically as
238 // dedicated mark workers get started.
239 dedicatedMarkWorkersNeeded int64
241 // assistWorkPerByte is the ratio of scan work to allocated
242 // bytes that should be performed by mutator assists. This is
243 // computed at the beginning of each cycle and updated every
244 // time heapScan is updated.
245 assistWorkPerByte atomic.Float64
247 // assistBytesPerWork is 1/assistWorkPerByte.
249 // Note that because this is read and written independently
250 // from assistWorkPerByte users may notice a skew between
251 // the two values, and such a state should be safe.
252 assistBytesPerWork atomic.Float64
254 // fractionalUtilizationGoal is the fraction of wall clock
255 // time that should be spent in the fractional mark worker on
256 // each P that isn't running a dedicated worker.
258 // For example, if the utilization goal is 25% and there are
259 // no dedicated workers, this will be 0.25. If the goal is
260 // 25%, there is one dedicated worker, and GOMAXPROCS is 5,
261 // this will be 0.05 to make up the missing 5%.
263 // If this is zero, no fractional workers are needed.
264 fractionalUtilizationGoal float64
269 func (c *gcControllerState) init(gcPercent int32) {
270 c.heapMinimum = defaultHeapMinimum
272 // Set a reasonable initial GC trigger.
273 c.triggerRatio = 7 / 8.0
275 // Fake a heapMarked value so it looks like a trigger at
276 // heapMinimum is the appropriate growth from heapMarked.
277 // This will go into computing the initial GC goal.
278 c.heapMarked = uint64(float64(c.heapMinimum) / (1 + c.triggerRatio))
280 // This will also compute and set the GC trigger and goal.
281 c.setGCPercent(gcPercent)
284 // startCycle resets the GC controller's state and computes estimates
285 // for a new GC cycle. The caller must hold worldsema and the world
287 func (c *gcControllerState) startCycle(markStartTime int64) {
291 c.dedicatedMarkTime = 0
292 c.fractionalMarkTime = 0
294 c.markStartTime = markStartTime
295 c.stackScan = atomic.Load64(&c.scannableStackSize)
297 // Ensure that the heap goal is at least a little larger than
298 // the current live heap size. This may not be the case if GC
299 // start is delayed or if the allocation that pushed gcController.heapLive
300 // over trigger is large or if the trigger is really close to
301 // GOGC. Assist is proportional to this distance, so enforce a
302 // minimum distance, even if it means going over the GOGC goal
304 if c.heapGoal < c.heapLive+1024*1024 {
305 c.heapGoal = c.heapLive + 1024*1024
308 // Compute the background mark utilization goal. In general,
309 // this may not come out exactly. We round the number of
310 // dedicated workers so that the utilization is closest to
311 // 25%. For small GOMAXPROCS, this would introduce too much
312 // error, so we add fractional workers in that case.
313 totalUtilizationGoal := float64(gomaxprocs) * gcBackgroundUtilization
314 c.dedicatedMarkWorkersNeeded = int64(totalUtilizationGoal + 0.5)
315 utilError := float64(c.dedicatedMarkWorkersNeeded)/totalUtilizationGoal - 1
316 const maxUtilError = 0.3
317 if utilError < -maxUtilError || utilError > maxUtilError {
318 // Rounding put us more than 30% off our goal. With
319 // gcBackgroundUtilization of 25%, this happens for
320 // GOMAXPROCS<=3 or GOMAXPROCS=6. Enable fractional
321 // workers to compensate.
322 if float64(c.dedicatedMarkWorkersNeeded) > totalUtilizationGoal {
323 // Too many dedicated workers.
324 c.dedicatedMarkWorkersNeeded--
326 c.fractionalUtilizationGoal = (totalUtilizationGoal - float64(c.dedicatedMarkWorkersNeeded)) / float64(gomaxprocs)
328 c.fractionalUtilizationGoal = 0
331 // In STW mode, we just want dedicated workers.
332 if debug.gcstoptheworld > 0 {
333 c.dedicatedMarkWorkersNeeded = int64(gomaxprocs)
334 c.fractionalUtilizationGoal = 0
338 for _, p := range allp {
340 p.gcFractionalMarkTime = 0
343 // Compute initial values for controls that are updated
344 // throughout the cycle.
347 if debug.gcpacertrace > 0 {
348 assistRatio := c.assistWorkPerByte.Load()
349 print("pacer: assist ratio=", assistRatio,
350 " (scan ", gcController.heapScan>>20, " MB in ",
351 work.initialHeapLive>>20, "->",
352 c.heapGoal>>20, " MB)",
353 " workers=", c.dedicatedMarkWorkersNeeded,
354 "+", c.fractionalUtilizationGoal, "\n")
358 // revise updates the assist ratio during the GC cycle to account for
359 // improved estimates. This should be called whenever gcController.heapScan,
360 // gcController.heapLive, or gcController.heapGoal is updated. It is safe to
361 // call concurrently, but it may race with other calls to revise.
363 // The result of this race is that the two assist ratio values may not line
364 // up or may be stale. In practice this is OK because the assist ratio
365 // moves slowly throughout a GC cycle, and the assist ratio is a best-effort
366 // heuristic anyway. Furthermore, no part of the heuristic depends on
367 // the two assist ratio values being exact reciprocals of one another, since
368 // the two values are used to convert values from different sources.
370 // The worst case result of this raciness is that we may miss a larger shift
371 // in the ratio (say, if we decide to pace more aggressively against the
372 // hard heap goal) but even this "hard goal" is best-effort (see #40460).
373 // The dedicated GC should ensure we don't exceed the hard goal by too much
374 // in the rare case we do exceed it.
376 // It should only be called when gcBlackenEnabled != 0 (because this
377 // is when assists are enabled and the necessary statistics are
379 func (c *gcControllerState) revise() {
380 gcPercent := atomic.Loadint32(&c.gcPercent)
382 // If GC is disabled but we're running a forced GC,
383 // act like GOGC is huge for the below calculations.
386 live := atomic.Load64(&c.heapLive)
387 scan := atomic.Load64(&c.heapScan)
388 work := atomic.Loadint64(&c.scanWork)
390 // Assume we're under the soft goal. Pace GC to complete at
391 // heapGoal assuming the heap is in steady-state.
392 heapGoal := int64(atomic.Load64(&c.heapGoal))
394 // Compute the expected scan work remaining.
396 // This is estimated based on the expected
397 // steady-state scannable heap. For example, with
398 // GOGC=100, only half of the scannable heap is
399 // expected to be live, so that's what we target.
401 // (This is a float calculation to avoid overflowing on
403 scanWorkExpected := int64(float64(scan) * 100 / float64(100+gcPercent))
405 if int64(live) > heapGoal || work > scanWorkExpected {
406 // We're past the soft goal, or we've already done more scan
407 // work than we expected. Pace GC so that in the worst case it
408 // will complete by the hard goal.
409 const maxOvershoot = 1.1
410 heapGoal = int64(float64(heapGoal) * maxOvershoot)
412 // Compute the upper bound on the scan work remaining.
413 scanWorkExpected = int64(scan)
416 // Compute the remaining scan work estimate.
418 // Note that we currently count allocations during GC as both
419 // scannable heap (heapScan) and scan work completed
420 // (scanWork), so allocation will change this difference
421 // slowly in the soft regime and not at all in the hard
423 scanWorkRemaining := scanWorkExpected - work
424 if scanWorkRemaining < 1000 {
425 // We set a somewhat arbitrary lower bound on
426 // remaining scan work since if we aim a little high,
427 // we can miss by a little.
429 // We *do* need to enforce that this is at least 1,
430 // since marking is racy and double-scanning objects
431 // may legitimately make the remaining scan work
432 // negative, even in the hard goal regime.
433 scanWorkRemaining = 1000
436 // Compute the heap distance remaining.
437 heapRemaining := heapGoal - int64(live)
438 if heapRemaining <= 0 {
439 // This shouldn't happen, but if it does, avoid
440 // dividing by zero or setting the assist negative.
444 // Compute the mutator assist ratio so by the time the mutator
445 // allocates the remaining heap bytes up to heapGoal, it will
446 // have done (or stolen) the remaining amount of scan work.
447 // Note that the assist ratio values are updated atomically
448 // but not together. This means there may be some degree of
449 // skew between the two values. This is generally OK as the
450 // values shift relatively slowly over the course of a GC
452 assistWorkPerByte := float64(scanWorkRemaining) / float64(heapRemaining)
453 assistBytesPerWork := float64(heapRemaining) / float64(scanWorkRemaining)
454 c.assistWorkPerByte.Store(assistWorkPerByte)
455 c.assistBytesPerWork.Store(assistBytesPerWork)
458 // endCycle computes the trigger ratio for the next cycle.
459 // userForced indicates whether the current GC cycle was forced
460 // by the application.
461 func (c *gcControllerState) endCycle(userForced bool) float64 {
462 // Record last heap goal for the scavenger.
463 // We'll be updating the heap goal soon.
464 gcController.lastHeapGoal = gcController.heapGoal
467 // Forced GC means this cycle didn't start at the
468 // trigger, so where it finished isn't good
469 // information about how to adjust the trigger.
470 // Just leave it where it is.
471 return c.triggerRatio
474 // Proportional response gain for the trigger controller. Must
475 // be in [0, 1]. Lower values smooth out transient effects but
476 // take longer to respond to phase changes. Higher values
477 // react to phase changes quickly, but are more affected by
478 // transient changes. Values near 1 may be unstable.
479 const triggerGain = 0.5
481 // Compute next cycle trigger ratio. First, this computes the
482 // "error" for this cycle; that is, how far off the trigger
483 // was from what it should have been, accounting for both heap
484 // growth and GC CPU utilization. We compute the actual heap
485 // growth during this cycle and scale that by how far off from
486 // the goal CPU utilization we were (to estimate the heap
487 // growth if we had the desired CPU utilization). The
488 // difference between this estimate and the GOGC-based goal
489 // heap growth is the error.
490 goalGrowthRatio := c.effectiveGrowthRatio()
491 actualGrowthRatio := float64(c.heapLive)/float64(c.heapMarked) - 1
492 assistDuration := nanotime() - c.markStartTime
494 // Assume background mark hit its utilization goal.
495 utilization := gcBackgroundUtilization
496 // Add assist utilization; avoid divide by zero.
497 if assistDuration > 0 {
498 utilization += float64(c.assistTime) / float64(assistDuration*int64(gomaxprocs))
501 triggerError := goalGrowthRatio - c.triggerRatio - utilization/gcGoalUtilization*(actualGrowthRatio-c.triggerRatio)
503 // Finally, we adjust the trigger for next time by this error,
504 // damped by the proportional gain.
505 triggerRatio := c.triggerRatio + triggerGain*triggerError
507 if debug.gcpacertrace > 0 {
508 // Print controller state in terms of the design
510 H_m_prev := c.heapMarked
511 h_t := c.triggerRatio
513 h_a := actualGrowthRatio
515 h_g := goalGrowthRatio
516 H_g := int64(float64(H_m_prev) * (1 + h_g))
518 u_g := gcGoalUtilization
520 print("pacer: H_m_prev=", H_m_prev,
521 " h_t=", h_t, " H_T=", H_T,
522 " h_a=", h_a, " H_a=", H_a,
523 " h_g=", h_g, " H_g=", H_g,
524 " u_a=", u_a, " u_g=", u_g,
526 " goalΔ=", goalGrowthRatio-h_t,
527 " actualΔ=", h_a-h_t,
528 " u_a/u_g=", u_a/u_g,
535 // enlistWorker encourages another dedicated mark worker to start on
536 // another P if there are spare worker slots. It is used by putfull
537 // when more work is made available.
540 func (c *gcControllerState) enlistWorker() {
541 // If there are idle Ps, wake one so it will run an idle worker.
542 // NOTE: This is suspected of causing deadlocks. See golang.org/issue/19112.
544 // if atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 {
549 // There are no idle Ps. If we need more dedicated workers,
550 // try to preempt a running P so it will switch to a worker.
551 if c.dedicatedMarkWorkersNeeded <= 0 {
554 // Pick a random other P to preempt.
559 if gp == nil || gp.m == nil || gp.m.p == 0 {
562 myID := gp.m.p.ptr().id
563 for tries := 0; tries < 5; tries++ {
564 id := int32(fastrandn(uint32(gomaxprocs - 1)))
569 if p.status != _Prunning {
578 // findRunnableGCWorker returns a background mark worker for _p_ if it
579 // should be run. This must only be called when gcBlackenEnabled != 0.
580 func (c *gcControllerState) findRunnableGCWorker(_p_ *p) *g {
581 if gcBlackenEnabled == 0 {
582 throw("gcControllerState.findRunnable: blackening not enabled")
585 if !gcMarkWorkAvailable(_p_) {
586 // No work to be done right now. This can happen at
587 // the end of the mark phase when there are still
588 // assists tapering off. Don't bother running a worker
589 // now because it'll just return immediately.
593 // Grab a worker before we commit to running below.
594 node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
596 // There is at least one worker per P, so normally there are
597 // enough workers to run on all Ps, if necessary. However, once
598 // a worker enters gcMarkDone it may park without rejoining the
599 // pool, thus freeing a P with no corresponding worker.
600 // gcMarkDone never depends on another worker doing work, so it
601 // is safe to simply do nothing here.
603 // If gcMarkDone bails out without completing the mark phase,
604 // it will always do so with queued global work. Thus, that P
605 // will be immediately eligible to re-run the worker G it was
606 // just using, ensuring work can complete.
610 decIfPositive := func(ptr *int64) bool {
612 v := atomic.Loadint64(ptr)
617 if atomic.Casint64(ptr, v, v-1) {
623 if decIfPositive(&c.dedicatedMarkWorkersNeeded) {
624 // This P is now dedicated to marking until the end of
625 // the concurrent mark phase.
626 _p_.gcMarkWorkerMode = gcMarkWorkerDedicatedMode
627 } else if c.fractionalUtilizationGoal == 0 {
628 // No need for fractional workers.
629 gcBgMarkWorkerPool.push(&node.node)
632 // Is this P behind on the fractional utilization
635 // This should be kept in sync with pollFractionalWorkerExit.
636 delta := nanotime() - c.markStartTime
637 if delta > 0 && float64(_p_.gcFractionalMarkTime)/float64(delta) > c.fractionalUtilizationGoal {
638 // Nope. No need to run a fractional worker.
639 gcBgMarkWorkerPool.push(&node.node)
642 // Run a fractional worker.
643 _p_.gcMarkWorkerMode = gcMarkWorkerFractionalMode
646 // Run the background mark worker.
648 casgstatus(gp, _Gwaiting, _Grunnable)
655 // resetLive sets up the controller state for the next mark phase after the end
656 // of the previous one. Must be called after endCycle and before commit, before
657 // the world is started.
659 // The world must be stopped.
660 func (c *gcControllerState) resetLive(bytesMarked uint64) {
661 c.heapMarked = bytesMarked
662 c.heapLive = bytesMarked
663 c.heapScan = uint64(c.scanWork)
665 // heapLive was updated, so emit a trace event.
671 // logWorkTime updates mark work accounting in the controller by a duration of
672 // work in nanoseconds.
674 // Safe to execute at any time.
675 func (c *gcControllerState) logWorkTime(mode gcMarkWorkerMode, duration int64) {
677 case gcMarkWorkerDedicatedMode:
678 atomic.Xaddint64(&c.dedicatedMarkTime, duration)
679 atomic.Xaddint64(&c.dedicatedMarkWorkersNeeded, 1)
680 case gcMarkWorkerFractionalMode:
681 atomic.Xaddint64(&c.fractionalMarkTime, duration)
682 case gcMarkWorkerIdleMode:
683 atomic.Xaddint64(&c.idleMarkTime, duration)
685 throw("logWorkTime: unknown mark worker mode")
689 func (c *gcControllerState) update(dHeapLive, dHeapScan int64) {
691 atomic.Xadd64(&gcController.heapLive, dHeapLive)
693 // gcController.heapLive changed.
698 atomic.Xadd64(&gcController.heapScan, dHeapScan)
700 if gcBlackenEnabled != 0 {
701 // gcController.heapLive and heapScan changed.
706 func (c *gcControllerState) addScannableStack(pp *p, amount int64) {
708 atomic.Xadd64(&c.scannableStackSize, amount)
711 pp.scannableStackSizeDelta += amount
712 if pp.scannableStackSizeDelta >= scannableStackSizeSlack || pp.scannableStackSizeDelta <= -scannableStackSizeSlack {
713 atomic.Xadd64(&c.scannableStackSize, pp.scannableStackSizeDelta)
714 pp.scannableStackSizeDelta = 0
718 // commit sets the trigger ratio and updates everything
719 // derived from it: the absolute trigger, the heap goal, mark pacing,
722 // This can be called any time. If GC is the in the middle of a
723 // concurrent phase, it will adjust the pacing of that phase.
725 // This depends on gcPercent, gcController.heapMarked, and
726 // gcController.heapLive. These must be up to date.
728 // mheap_.lock must be held or the world must be stopped.
729 func (c *gcControllerState) commit(triggerRatio float64) {
730 assertWorldStoppedOrLockHeld(&mheap_.lock)
732 // Compute the next GC goal, which is when the allocated heap
733 // has grown by GOGC/100 over the heap marked by the last
736 if c.gcPercent >= 0 {
737 goal = c.heapMarked + c.heapMarked*uint64(c.gcPercent)/100
740 // Set the trigger ratio, capped to reasonable bounds.
741 if c.gcPercent >= 0 {
742 scalingFactor := float64(c.gcPercent) / 100
743 // Ensure there's always a little margin so that the
744 // mutator assist ratio isn't infinity.
745 maxTriggerRatio := 0.95 * scalingFactor
746 if triggerRatio > maxTriggerRatio {
747 triggerRatio = maxTriggerRatio
750 // If we let triggerRatio go too low, then if the application
751 // is allocating very rapidly we might end up in a situation
752 // where we're allocating black during a nearly always-on GC.
753 // The result of this is a growing heap and ultimately an
754 // increase in RSS. By capping us at a point >0, we're essentially
755 // saying that we're OK using more CPU during the GC to prevent
756 // this growth in RSS.
758 // The current constant was chosen empirically: given a sufficiently
759 // fast/scalable allocator with 48 Ps that could drive the trigger ratio
760 // to <0.05, this constant causes applications to retain the same peak
761 // RSS compared to not having this allocator.
762 minTriggerRatio := 0.6 * scalingFactor
763 if triggerRatio < minTriggerRatio {
764 triggerRatio = minTriggerRatio
766 } else if triggerRatio < 0 {
767 // gcPercent < 0, so just make sure we're not getting a negative
768 // triggerRatio. This case isn't expected to happen in practice,
769 // and doesn't really matter because if gcPercent < 0 then we won't
770 // ever consume triggerRatio further on in this function, but let's
771 // just be defensive here; the triggerRatio being negative is almost
772 // certainly undesirable.
775 c.triggerRatio = triggerRatio
777 // Compute the absolute GC trigger from the trigger ratio.
779 // We trigger the next GC cycle when the allocated heap has
780 // grown by the trigger ratio over the marked heap size.
781 trigger := ^uint64(0)
782 if c.gcPercent >= 0 {
783 trigger = uint64(float64(c.heapMarked) * (1 + triggerRatio))
784 // Don't trigger below the minimum heap size.
785 minTrigger := c.heapMinimum
787 // Concurrent sweep happens in the heap growth
788 // from gcController.heapLive to trigger, so ensure
789 // that concurrent sweep has some heap growth
790 // in which to perform sweeping before we
791 // start the next GC cycle.
792 sweepMin := atomic.Load64(&c.heapLive) + sweepMinHeapDistance
793 if sweepMin > minTrigger {
794 minTrigger = sweepMin
797 if trigger < minTrigger {
800 if int64(trigger) < 0 {
801 print("runtime: heapGoal=", c.heapGoal, " heapMarked=", c.heapMarked, " gcController.heapLive=", c.heapLive, " initialHeapLive=", work.initialHeapLive, "triggerRatio=", triggerRatio, " minTrigger=", minTrigger, "\n")
802 throw("trigger underflow")
805 // The trigger ratio is always less than GOGC/100, but
806 // other bounds on the trigger may have raised it.
807 // Push up the goal, too.
812 // Commit to the trigger and goal.
814 atomic.Store64(&c.heapGoal, goal)
819 // Update mark pacing.
820 if gcphase != _GCoff {
825 // effectiveGrowthRatio returns the current effective heap growth
826 // ratio (GOGC/100) based on heapMarked from the previous GC and
827 // heapGoal for the current GC.
829 // This may differ from gcPercent/100 because of various upper and
830 // lower bounds on gcPercent. For example, if the heap is smaller than
831 // heapMinimum, this can be higher than gcPercent/100.
833 // mheap_.lock must be held or the world must be stopped.
834 func (c *gcControllerState) effectiveGrowthRatio() float64 {
835 assertWorldStoppedOrLockHeld(&mheap_.lock)
837 egogc := float64(atomic.Load64(&c.heapGoal)-c.heapMarked) / float64(c.heapMarked)
839 // Shouldn't happen, but just in case.
845 // setGCPercent updates gcPercent and all related pacer state.
846 // Returns the old value of gcPercent.
848 // Calls gcControllerState.commit.
850 // The world must be stopped, or mheap_.lock must be held.
851 func (c *gcControllerState) setGCPercent(in int32) int32 {
852 assertWorldStoppedOrLockHeld(&mheap_.lock)
858 // Write it atomically so readers like revise() can read it safely.
859 atomic.Storeint32(&c.gcPercent, in)
860 c.heapMinimum = defaultHeapMinimum * uint64(c.gcPercent) / 100
861 // Update pacing in response to gcPercent change.
862 c.commit(c.triggerRatio)
867 //go:linkname setGCPercent runtime/debug.setGCPercent
868 func setGCPercent(in int32) (out int32) {
869 // Run on the system stack since we grab the heap lock.
872 out = gcController.setGCPercent(in)
873 gcPaceSweeper(gcController.trigger)
874 gcPaceScavenger(gcController.heapGoal, gcController.lastHeapGoal)
878 // If we just disabled GC, wait for any concurrent GC mark to
879 // finish so we always return with no GC running.
881 gcWaitOnMark(atomic.Load(&work.cycles))
887 func readGOGC() int32 {
888 p := gogetenv("GOGC")
892 if n, ok := atoi32(p); ok {