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
53 if offset := unsafe.Offsetof(gcController.heapLive); offset%8 != 0 {
55 throw("gcController.heapLive not aligned to 8 bytes")
59 // gcController implements the GC pacing controller that determines
60 // when to trigger concurrent garbage collection and how much marking
61 // work to do in mutator assists and background marking.
63 // It uses a feedback control algorithm to adjust the gcController.trigger
64 // trigger based on the heap growth and GC CPU utilization each cycle.
65 // This algorithm optimizes for heap growth to match GOGC and for CPU
66 // utilization between assist and background marking to be 25% of
67 // GOMAXPROCS. The high-level design of this algorithm is documented
68 // at https://golang.org/s/go15gcpacing.
70 // All fields of gcController are used only during a single mark
72 var gcController gcControllerState
74 type gcControllerState struct {
75 // Initialized from $GOGC. GOGC=off means no GC.
77 // Updated atomically with mheap_.lock held or during a STW.
78 // Safe to read atomically at any time, or non-atomically with
79 // mheap_.lock or STW.
82 _ uint32 // padding so following 64-bit values are 8-byte aligned
84 // heapMinimum is the minimum heap size at which to trigger GC.
85 // For small heaps, this overrides the usual GOGC*live set rule.
87 // When there is a very small live set but a lot of allocation, simply
88 // collecting when the heap reaches GOGC*live results in many GC
89 // cycles and high total per-GC overhead. This minimum amortizes this
90 // per-GC overhead while keeping the heap reasonably small.
92 // During initialization this is set to 4MB*GOGC/100. In the case of
93 // GOGC==0, this will set heapMinimum to 0, resulting in constant
94 // collection even when the heap size is small, which is useful for
98 // triggerRatio is the heap growth ratio that triggers marking.
100 // E.g., if this is 0.6, then GC should start when the live
101 // heap has reached 1.6 times the heap size marked by the
102 // previous cycle. This should be ≤ GOGC/100 so the trigger
103 // heap size is less than the goal heap size. This is set
104 // during mark termination for the next cycle's trigger.
106 // Protected by mheap_.lock or a STW.
109 // trigger is the heap size that triggers marking.
111 // When heapLive ≥ trigger, the mark phase will start.
112 // This is also the heap size by which proportional sweeping
115 // This is computed from triggerRatio during mark termination
116 // for the next cycle's trigger.
118 // Protected by mheap_.lock or a STW.
121 // heapGoal is the goal heapLive for when next GC ends.
122 // Set to ^uint64(0) if disabled.
124 // Read and written atomically, unless the world is stopped.
127 // lastHeapGoal is the value of heapGoal for the previous GC.
128 // Note that this is distinct from the last value heapGoal had,
129 // because it could change if e.g. gcPercent changes.
131 // Read and written with the world stopped or with mheap_.lock held.
134 // heapLive is the number of bytes considered live by the GC.
135 // That is: retained by the most recent GC plus allocated
136 // since then. heapLive ≤ memstats.heapAlloc, since heapAlloc includes
137 // unmarked objects that have not yet been swept (and hence goes up as we
138 // allocate and down as we sweep) while heapLive excludes these
139 // objects (and hence only goes up between GCs).
141 // This is updated atomically without locking. To reduce
142 // contention, this is updated only when obtaining a span from
143 // an mcentral and at this point it counts all of the
144 // unallocated slots in that span (which will be allocated
145 // before that mcache obtains another span from that
146 // mcentral). Hence, it slightly overestimates the "true" live
147 // heap size. It's better to overestimate than to
148 // underestimate because 1) this triggers the GC earlier than
149 // necessary rather than potentially too late and 2) this
150 // leads to a conservative GC rate rather than a GC rate that
151 // is potentially too low.
153 // Reads should likewise be atomic (or during STW).
155 // Whenever this is updated, call traceHeapAlloc() and
156 // this gcControllerState's revise() method.
159 // heapScan is the number of bytes of "scannable" heap. This
160 // is the live heap (as counted by heapLive), but omitting
161 // no-scan objects and no-scan tails of objects.
163 // Whenever this is updated, call this gcControllerState's
166 // Read and written atomically or with the world stopped.
169 // heapMarked is the number of bytes marked by the previous
170 // GC. After mark termination, heapLive == heapMarked, but
171 // unlike heapLive, heapMarked does not change until the
172 // next mark termination.
175 // scanWork is the total scan work performed this cycle. This
176 // is updated atomically during the cycle. Updates occur in
177 // bounded batches, since it is both written and read
178 // throughout the cycle. At the end of the cycle, this is how
179 // much of the retained heap is scannable.
181 // Currently this is the bytes of heap scanned. For most uses,
182 // this is an opaque unit of work, but for estimation the
183 // definition is important.
186 // bgScanCredit is the scan work credit accumulated by the
187 // concurrent background scan. This credit is accumulated by
188 // the background scan and stolen by mutator assists. This is
189 // updated atomically. Updates occur in bounded batches, since
190 // it is both written and read throughout the cycle.
193 // assistTime is the nanoseconds spent in mutator assists
194 // during this cycle. This is updated atomically. Updates
195 // occur in bounded batches, since it is both written and read
196 // throughout the cycle.
199 // dedicatedMarkTime is the nanoseconds spent in dedicated
200 // mark workers during this cycle. This is updated atomically
201 // at the end of the concurrent mark phase.
202 dedicatedMarkTime int64
204 // fractionalMarkTime is the nanoseconds spent in the
205 // fractional mark worker during this cycle. This is updated
206 // atomically throughout the cycle and will be up-to-date if
207 // the fractional mark worker is not currently running.
208 fractionalMarkTime int64
210 // idleMarkTime is the nanoseconds spent in idle marking
211 // during this cycle. This is updated atomically throughout
215 // markStartTime is the absolute start time in nanoseconds
216 // that assists and background mark workers started.
219 // dedicatedMarkWorkersNeeded is the number of dedicated mark
220 // workers that need to be started. This is computed at the
221 // beginning of each cycle and decremented atomically as
222 // dedicated mark workers get started.
223 dedicatedMarkWorkersNeeded int64
225 // assistWorkPerByte is the ratio of scan work to allocated
226 // bytes that should be performed by mutator assists. This is
227 // computed at the beginning of each cycle and updated every
228 // time heapScan is updated.
229 assistWorkPerByte atomic.Float64
231 // assistBytesPerWork is 1/assistWorkPerByte.
233 // Note that because this is read and written independently
234 // from assistWorkPerByte users may notice a skew between
235 // the two values, and such a state should be safe.
236 assistBytesPerWork atomic.Float64
238 // fractionalUtilizationGoal is the fraction of wall clock
239 // time that should be spent in the fractional mark worker on
240 // each P that isn't running a dedicated worker.
242 // For example, if the utilization goal is 25% and there are
243 // no dedicated workers, this will be 0.25. If the goal is
244 // 25%, there is one dedicated worker, and GOMAXPROCS is 5,
245 // this will be 0.05 to make up the missing 5%.
247 // If this is zero, no fractional workers are needed.
248 fractionalUtilizationGoal float64
253 func (c *gcControllerState) init(gcPercent int32) {
254 c.heapMinimum = defaultHeapMinimum
256 // Set a reasonable initial GC trigger.
257 c.triggerRatio = 7 / 8.0
259 // Fake a heapMarked value so it looks like a trigger at
260 // heapMinimum is the appropriate growth from heapMarked.
261 // This will go into computing the initial GC goal.
262 c.heapMarked = uint64(float64(c.heapMinimum) / (1 + c.triggerRatio))
264 // This will also compute and set the GC trigger and goal.
265 c.setGCPercent(gcPercent)
268 // startCycle resets the GC controller's state and computes estimates
269 // for a new GC cycle. The caller must hold worldsema and the world
271 func (c *gcControllerState) startCycle(markStartTime int64) {
275 c.dedicatedMarkTime = 0
276 c.fractionalMarkTime = 0
278 c.markStartTime = markStartTime
280 // Ensure that the heap goal is at least a little larger than
281 // the current live heap size. This may not be the case if GC
282 // start is delayed or if the allocation that pushed gcController.heapLive
283 // over trigger is large or if the trigger is really close to
284 // GOGC. Assist is proportional to this distance, so enforce a
285 // minimum distance, even if it means going over the GOGC goal
287 if c.heapGoal < c.heapLive+1024*1024 {
288 c.heapGoal = c.heapLive + 1024*1024
291 // Compute the background mark utilization goal. In general,
292 // this may not come out exactly. We round the number of
293 // dedicated workers so that the utilization is closest to
294 // 25%. For small GOMAXPROCS, this would introduce too much
295 // error, so we add fractional workers in that case.
296 totalUtilizationGoal := float64(gomaxprocs) * gcBackgroundUtilization
297 c.dedicatedMarkWorkersNeeded = int64(totalUtilizationGoal + 0.5)
298 utilError := float64(c.dedicatedMarkWorkersNeeded)/totalUtilizationGoal - 1
299 const maxUtilError = 0.3
300 if utilError < -maxUtilError || utilError > maxUtilError {
301 // Rounding put us more than 30% off our goal. With
302 // gcBackgroundUtilization of 25%, this happens for
303 // GOMAXPROCS<=3 or GOMAXPROCS=6. Enable fractional
304 // workers to compensate.
305 if float64(c.dedicatedMarkWorkersNeeded) > totalUtilizationGoal {
306 // Too many dedicated workers.
307 c.dedicatedMarkWorkersNeeded--
309 c.fractionalUtilizationGoal = (totalUtilizationGoal - float64(c.dedicatedMarkWorkersNeeded)) / float64(gomaxprocs)
311 c.fractionalUtilizationGoal = 0
314 // In STW mode, we just want dedicated workers.
315 if debug.gcstoptheworld > 0 {
316 c.dedicatedMarkWorkersNeeded = int64(gomaxprocs)
317 c.fractionalUtilizationGoal = 0
321 for _, p := range allp {
323 p.gcFractionalMarkTime = 0
326 // Compute initial values for controls that are updated
327 // throughout the cycle.
330 if debug.gcpacertrace > 0 {
331 assistRatio := c.assistWorkPerByte.Load()
332 print("pacer: assist ratio=", assistRatio,
333 " (scan ", gcController.heapScan>>20, " MB in ",
334 work.initialHeapLive>>20, "->",
335 c.heapGoal>>20, " MB)",
336 " workers=", c.dedicatedMarkWorkersNeeded,
337 "+", c.fractionalUtilizationGoal, "\n")
341 // revise updates the assist ratio during the GC cycle to account for
342 // improved estimates. This should be called whenever gcController.heapScan,
343 // gcController.heapLive, or gcController.heapGoal is updated. It is safe to
344 // call concurrently, but it may race with other calls to revise.
346 // The result of this race is that the two assist ratio values may not line
347 // up or may be stale. In practice this is OK because the assist ratio
348 // moves slowly throughout a GC cycle, and the assist ratio is a best-effort
349 // heuristic anyway. Furthermore, no part of the heuristic depends on
350 // the two assist ratio values being exact reciprocals of one another, since
351 // the two values are used to convert values from different sources.
353 // The worst case result of this raciness is that we may miss a larger shift
354 // in the ratio (say, if we decide to pace more aggressively against the
355 // hard heap goal) but even this "hard goal" is best-effort (see #40460).
356 // The dedicated GC should ensure we don't exceed the hard goal by too much
357 // in the rare case we do exceed it.
359 // It should only be called when gcBlackenEnabled != 0 (because this
360 // is when assists are enabled and the necessary statistics are
362 func (c *gcControllerState) revise() {
363 gcPercent := atomic.Loadint32(&c.gcPercent)
365 // If GC is disabled but we're running a forced GC,
366 // act like GOGC is huge for the below calculations.
369 live := atomic.Load64(&c.heapLive)
370 scan := atomic.Load64(&c.heapScan)
371 work := atomic.Loadint64(&c.scanWork)
373 // Assume we're under the soft goal. Pace GC to complete at
374 // heapGoal assuming the heap is in steady-state.
375 heapGoal := int64(atomic.Load64(&c.heapGoal))
377 // Compute the expected scan work remaining.
379 // This is estimated based on the expected
380 // steady-state scannable heap. For example, with
381 // GOGC=100, only half of the scannable heap is
382 // expected to be live, so that's what we target.
384 // (This is a float calculation to avoid overflowing on
386 scanWorkExpected := int64(float64(scan) * 100 / float64(100+gcPercent))
388 if int64(live) > heapGoal || work > scanWorkExpected {
389 // We're past the soft goal, or we've already done more scan
390 // work than we expected. Pace GC so that in the worst case it
391 // will complete by the hard goal.
392 const maxOvershoot = 1.1
393 heapGoal = int64(float64(heapGoal) * maxOvershoot)
395 // Compute the upper bound on the scan work remaining.
396 scanWorkExpected = int64(scan)
399 // Compute the remaining scan work estimate.
401 // Note that we currently count allocations during GC as both
402 // scannable heap (heapScan) and scan work completed
403 // (scanWork), so allocation will change this difference
404 // slowly in the soft regime and not at all in the hard
406 scanWorkRemaining := scanWorkExpected - work
407 if scanWorkRemaining < 1000 {
408 // We set a somewhat arbitrary lower bound on
409 // remaining scan work since if we aim a little high,
410 // we can miss by a little.
412 // We *do* need to enforce that this is at least 1,
413 // since marking is racy and double-scanning objects
414 // may legitimately make the remaining scan work
415 // negative, even in the hard goal regime.
416 scanWorkRemaining = 1000
419 // Compute the heap distance remaining.
420 heapRemaining := heapGoal - int64(live)
421 if heapRemaining <= 0 {
422 // This shouldn't happen, but if it does, avoid
423 // dividing by zero or setting the assist negative.
427 // Compute the mutator assist ratio so by the time the mutator
428 // allocates the remaining heap bytes up to heapGoal, it will
429 // have done (or stolen) the remaining amount of scan work.
430 // Note that the assist ratio values are updated atomically
431 // but not together. This means there may be some degree of
432 // skew between the two values. This is generally OK as the
433 // values shift relatively slowly over the course of a GC
435 assistWorkPerByte := float64(scanWorkRemaining) / float64(heapRemaining)
436 assistBytesPerWork := float64(heapRemaining) / float64(scanWorkRemaining)
437 c.assistWorkPerByte.Store(assistWorkPerByte)
438 c.assistBytesPerWork.Store(assistBytesPerWork)
441 // endCycle computes the trigger ratio for the next cycle.
442 // userForced indicates whether the current GC cycle was forced
443 // by the application.
444 func (c *gcControllerState) endCycle(userForced bool) float64 {
445 // Record last heap goal for the scavenger.
446 // We'll be updating the heap goal soon.
447 gcController.lastHeapGoal = gcController.heapGoal
450 // Forced GC means this cycle didn't start at the
451 // trigger, so where it finished isn't good
452 // information about how to adjust the trigger.
453 // Just leave it where it is.
454 return c.triggerRatio
457 // Proportional response gain for the trigger controller. Must
458 // be in [0, 1]. Lower values smooth out transient effects but
459 // take longer to respond to phase changes. Higher values
460 // react to phase changes quickly, but are more affected by
461 // transient changes. Values near 1 may be unstable.
462 const triggerGain = 0.5
464 // Compute next cycle trigger ratio. First, this computes the
465 // "error" for this cycle; that is, how far off the trigger
466 // was from what it should have been, accounting for both heap
467 // growth and GC CPU utilization. We compute the actual heap
468 // growth during this cycle and scale that by how far off from
469 // the goal CPU utilization we were (to estimate the heap
470 // growth if we had the desired CPU utilization). The
471 // difference between this estimate and the GOGC-based goal
472 // heap growth is the error.
473 goalGrowthRatio := c.effectiveGrowthRatio()
474 actualGrowthRatio := float64(c.heapLive)/float64(c.heapMarked) - 1
475 assistDuration := nanotime() - c.markStartTime
477 // Assume background mark hit its utilization goal.
478 utilization := gcBackgroundUtilization
479 // Add assist utilization; avoid divide by zero.
480 if assistDuration > 0 {
481 utilization += float64(c.assistTime) / float64(assistDuration*int64(gomaxprocs))
484 triggerError := goalGrowthRatio - c.triggerRatio - utilization/gcGoalUtilization*(actualGrowthRatio-c.triggerRatio)
486 // Finally, we adjust the trigger for next time by this error,
487 // damped by the proportional gain.
488 triggerRatio := c.triggerRatio + triggerGain*triggerError
490 if debug.gcpacertrace > 0 {
491 // Print controller state in terms of the design
493 H_m_prev := c.heapMarked
494 h_t := c.triggerRatio
496 h_a := actualGrowthRatio
498 h_g := goalGrowthRatio
499 H_g := int64(float64(H_m_prev) * (1 + h_g))
501 u_g := gcGoalUtilization
503 print("pacer: H_m_prev=", H_m_prev,
504 " h_t=", h_t, " H_T=", H_T,
505 " h_a=", h_a, " H_a=", H_a,
506 " h_g=", h_g, " H_g=", H_g,
507 " u_a=", u_a, " u_g=", u_g,
509 " goalΔ=", goalGrowthRatio-h_t,
510 " actualΔ=", h_a-h_t,
511 " u_a/u_g=", u_a/u_g,
518 // enlistWorker encourages another dedicated mark worker to start on
519 // another P if there are spare worker slots. It is used by putfull
520 // when more work is made available.
523 func (c *gcControllerState) enlistWorker() {
524 // If there are idle Ps, wake one so it will run an idle worker.
525 // NOTE: This is suspected of causing deadlocks. See golang.org/issue/19112.
527 // if atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 {
532 // There are no idle Ps. If we need more dedicated workers,
533 // try to preempt a running P so it will switch to a worker.
534 if c.dedicatedMarkWorkersNeeded <= 0 {
537 // Pick a random other P to preempt.
542 if gp == nil || gp.m == nil || gp.m.p == 0 {
545 myID := gp.m.p.ptr().id
546 for tries := 0; tries < 5; tries++ {
547 id := int32(fastrandn(uint32(gomaxprocs - 1)))
552 if p.status != _Prunning {
561 // findRunnableGCWorker returns a background mark worker for _p_ if it
562 // should be run. This must only be called when gcBlackenEnabled != 0.
563 func (c *gcControllerState) findRunnableGCWorker(_p_ *p) *g {
564 if gcBlackenEnabled == 0 {
565 throw("gcControllerState.findRunnable: blackening not enabled")
568 if !gcMarkWorkAvailable(_p_) {
569 // No work to be done right now. This can happen at
570 // the end of the mark phase when there are still
571 // assists tapering off. Don't bother running a worker
572 // now because it'll just return immediately.
576 // Grab a worker before we commit to running below.
577 node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
579 // There is at least one worker per P, so normally there are
580 // enough workers to run on all Ps, if necessary. However, once
581 // a worker enters gcMarkDone it may park without rejoining the
582 // pool, thus freeing a P with no corresponding worker.
583 // gcMarkDone never depends on another worker doing work, so it
584 // is safe to simply do nothing here.
586 // If gcMarkDone bails out without completing the mark phase,
587 // it will always do so with queued global work. Thus, that P
588 // will be immediately eligible to re-run the worker G it was
589 // just using, ensuring work can complete.
593 decIfPositive := func(ptr *int64) bool {
595 v := atomic.Loadint64(ptr)
600 if atomic.Casint64(ptr, v, v-1) {
606 if decIfPositive(&c.dedicatedMarkWorkersNeeded) {
607 // This P is now dedicated to marking until the end of
608 // the concurrent mark phase.
609 _p_.gcMarkWorkerMode = gcMarkWorkerDedicatedMode
610 } else if c.fractionalUtilizationGoal == 0 {
611 // No need for fractional workers.
612 gcBgMarkWorkerPool.push(&node.node)
615 // Is this P behind on the fractional utilization
618 // This should be kept in sync with pollFractionalWorkerExit.
619 delta := nanotime() - c.markStartTime
620 if delta > 0 && float64(_p_.gcFractionalMarkTime)/float64(delta) > c.fractionalUtilizationGoal {
621 // Nope. No need to run a fractional worker.
622 gcBgMarkWorkerPool.push(&node.node)
625 // Run a fractional worker.
626 _p_.gcMarkWorkerMode = gcMarkWorkerFractionalMode
629 // Run the background mark worker.
631 casgstatus(gp, _Gwaiting, _Grunnable)
638 // resetLive sets up the controller state for the next mark phase after the end
639 // of the previous one. Must be called after endCycle and before commit, before
640 // the world is started.
642 // The world must be stopped.
643 func (c *gcControllerState) resetLive(bytesMarked uint64) {
644 c.heapMarked = bytesMarked
645 c.heapLive = bytesMarked
646 c.heapScan = uint64(c.scanWork)
648 // heapLive was updated, so emit a trace event.
654 // logWorkTime updates mark work accounting in the controller by a duration of
655 // work in nanoseconds.
657 // Safe to execute at any time.
658 func (c *gcControllerState) logWorkTime(mode gcMarkWorkerMode, duration int64) {
660 case gcMarkWorkerDedicatedMode:
661 atomic.Xaddint64(&c.dedicatedMarkTime, duration)
662 atomic.Xaddint64(&c.dedicatedMarkWorkersNeeded, 1)
663 case gcMarkWorkerFractionalMode:
664 atomic.Xaddint64(&c.fractionalMarkTime, duration)
665 case gcMarkWorkerIdleMode:
666 atomic.Xaddint64(&c.idleMarkTime, duration)
668 throw("logWorkTime: unknown mark worker mode")
672 // commit sets the trigger ratio and updates everything
673 // derived from it: the absolute trigger, the heap goal, mark pacing,
676 // This can be called any time. If GC is the in the middle of a
677 // concurrent phase, it will adjust the pacing of that phase.
679 // This depends on gcPercent, gcController.heapMarked, and
680 // gcController.heapLive. These must be up to date.
682 // mheap_.lock must be held or the world must be stopped.
683 func (c *gcControllerState) commit(triggerRatio float64) {
684 assertWorldStoppedOrLockHeld(&mheap_.lock)
686 // Compute the next GC goal, which is when the allocated heap
687 // has grown by GOGC/100 over the heap marked by the last
690 if c.gcPercent >= 0 {
691 goal = c.heapMarked + c.heapMarked*uint64(c.gcPercent)/100
694 // Set the trigger ratio, capped to reasonable bounds.
695 if c.gcPercent >= 0 {
696 scalingFactor := float64(c.gcPercent) / 100
697 // Ensure there's always a little margin so that the
698 // mutator assist ratio isn't infinity.
699 maxTriggerRatio := 0.95 * scalingFactor
700 if triggerRatio > maxTriggerRatio {
701 triggerRatio = maxTriggerRatio
704 // If we let triggerRatio go too low, then if the application
705 // is allocating very rapidly we might end up in a situation
706 // where we're allocating black during a nearly always-on GC.
707 // The result of this is a growing heap and ultimately an
708 // increase in RSS. By capping us at a point >0, we're essentially
709 // saying that we're OK using more CPU during the GC to prevent
710 // this growth in RSS.
712 // The current constant was chosen empirically: given a sufficiently
713 // fast/scalable allocator with 48 Ps that could drive the trigger ratio
714 // to <0.05, this constant causes applications to retain the same peak
715 // RSS compared to not having this allocator.
716 minTriggerRatio := 0.6 * scalingFactor
717 if triggerRatio < minTriggerRatio {
718 triggerRatio = minTriggerRatio
720 } else if triggerRatio < 0 {
721 // gcPercent < 0, so just make sure we're not getting a negative
722 // triggerRatio. This case isn't expected to happen in practice,
723 // and doesn't really matter because if gcPercent < 0 then we won't
724 // ever consume triggerRatio further on in this function, but let's
725 // just be defensive here; the triggerRatio being negative is almost
726 // certainly undesirable.
729 c.triggerRatio = triggerRatio
731 // Compute the absolute GC trigger from the trigger ratio.
733 // We trigger the next GC cycle when the allocated heap has
734 // grown by the trigger ratio over the marked heap size.
735 trigger := ^uint64(0)
736 if c.gcPercent >= 0 {
737 trigger = uint64(float64(c.heapMarked) * (1 + triggerRatio))
738 // Don't trigger below the minimum heap size.
739 minTrigger := c.heapMinimum
741 // Concurrent sweep happens in the heap growth
742 // from gcController.heapLive to trigger, so ensure
743 // that concurrent sweep has some heap growth
744 // in which to perform sweeping before we
745 // start the next GC cycle.
746 sweepMin := atomic.Load64(&c.heapLive) + sweepMinHeapDistance
747 if sweepMin > minTrigger {
748 minTrigger = sweepMin
751 if trigger < minTrigger {
754 if int64(trigger) < 0 {
755 print("runtime: heapGoal=", c.heapGoal, " heapMarked=", c.heapMarked, " gcController.heapLive=", c.heapLive, " initialHeapLive=", work.initialHeapLive, "triggerRatio=", triggerRatio, " minTrigger=", minTrigger, "\n")
756 throw("trigger underflow")
759 // The trigger ratio is always less than GOGC/100, but
760 // other bounds on the trigger may have raised it.
761 // Push up the goal, too.
766 // Commit to the trigger and goal.
768 atomic.Store64(&c.heapGoal, goal)
773 // Update mark pacing.
774 if gcphase != _GCoff {
779 // effectiveGrowthRatio returns the current effective heap growth
780 // ratio (GOGC/100) based on heapMarked from the previous GC and
781 // heapGoal for the current GC.
783 // This may differ from gcPercent/100 because of various upper and
784 // lower bounds on gcPercent. For example, if the heap is smaller than
785 // heapMinimum, this can be higher than gcPercent/100.
787 // mheap_.lock must be held or the world must be stopped.
788 func (c *gcControllerState) effectiveGrowthRatio() float64 {
789 assertWorldStoppedOrLockHeld(&mheap_.lock)
791 egogc := float64(atomic.Load64(&c.heapGoal)-c.heapMarked) / float64(c.heapMarked)
793 // Shouldn't happen, but just in case.
799 // setGCPercent updates gcPercent and all related pacer state.
800 // Returns the old value of gcPercent.
802 // Calls gcControllerState.commit.
804 // The world must be stopped, or mheap_.lock must be held.
805 func (c *gcControllerState) setGCPercent(in int32) int32 {
806 assertWorldStoppedOrLockHeld(&mheap_.lock)
812 // Write it atomically so readers like revise() can read it safely.
813 atomic.Storeint32(&c.gcPercent, in)
814 c.heapMinimum = defaultHeapMinimum * uint64(c.gcPercent) / 100
815 // Update pacing in response to gcPercent change.
816 c.commit(c.triggerRatio)
821 //go:linkname setGCPercent runtime/debug.setGCPercent
822 func setGCPercent(in int32) (out int32) {
823 // Run on the system stack since we grab the heap lock.
826 out = gcController.setGCPercent(in)
827 gcPaceSweeper(gcController.trigger)
828 gcPaceScavenger(gcController.heapGoal, gcController.lastHeapGoal)
832 // If we just disabled GC, wait for any concurrent GC mark to
833 // finish so we always return with no GC running.
835 gcWaitOnMark(atomic.Load(&work.cycles))
841 func readGOGC() int32 {
842 p := gogetenv("GOGC")
846 if n, ok := atoi32(p); ok {