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.
78 _ uint32 // padding so following 64-bit values are 8-byte aligned
80 // heapMinimum is the minimum heap size at which to trigger GC.
81 // For small heaps, this overrides the usual GOGC*live set rule.
83 // When there is a very small live set but a lot of allocation, simply
84 // collecting when the heap reaches GOGC*live results in many GC
85 // cycles and high total per-GC overhead. This minimum amortizes this
86 // per-GC overhead while keeping the heap reasonably small.
88 // During initialization this is set to 4MB*GOGC/100. In the case of
89 // GOGC==0, this will set heapMinimum to 0, resulting in constant
90 // collection even when the heap size is small, which is useful for
94 // triggerRatio is the heap growth ratio that triggers marking.
96 // E.g., if this is 0.6, then GC should start when the live
97 // heap has reached 1.6 times the heap size marked by the
98 // previous cycle. This should be ≤ GOGC/100 so the trigger
99 // heap size is less than the goal heap size. This is set
100 // during mark termination for the next cycle's trigger.
102 // Protected by mheap_.lock or a STW.
105 // trigger is the heap size that triggers marking.
107 // When heapLive ≥ trigger, the mark phase will start.
108 // This is also the heap size by which proportional sweeping
111 // This is computed from triggerRatio during mark termination
112 // for the next cycle's trigger.
114 // Protected by mheap_.lock or a STW.
117 // heapLive is the number of bytes considered live by the GC.
118 // That is: retained by the most recent GC plus allocated
119 // since then. heapLive ≤ memstats.heapAlloc, since heapAlloc includes
120 // unmarked objects that have not yet been swept (and hence goes up as we
121 // allocate and down as we sweep) while heapLive excludes these
122 // objects (and hence only goes up between GCs).
124 // This is updated atomically without locking. To reduce
125 // contention, this is updated only when obtaining a span from
126 // an mcentral and at this point it counts all of the
127 // unallocated slots in that span (which will be allocated
128 // before that mcache obtains another span from that
129 // mcentral). Hence, it slightly overestimates the "true" live
130 // heap size. It's better to overestimate than to
131 // underestimate because 1) this triggers the GC earlier than
132 // necessary rather than potentially too late and 2) this
133 // leads to a conservative GC rate rather than a GC rate that
134 // is potentially too low.
136 // Reads should likewise be atomic (or during STW).
138 // Whenever this is updated, call traceHeapAlloc() and
139 // this gcControllerState's revise() method.
142 // heapScan is the number of bytes of "scannable" heap. This
143 // is the live heap (as counted by heapLive), but omitting
144 // no-scan objects and no-scan tails of objects.
146 // Whenever this is updated, call this gcControllerState's
149 // Read and written atomically or with the world stopped.
152 // heapMarked is the number of bytes marked by the previous
153 // GC. After mark termination, heapLive == heapMarked, but
154 // unlike heapLive, heapMarked does not change until the
155 // next mark termination.
158 // scanWork is the total scan work performed this cycle. This
159 // is updated atomically during the cycle. Updates occur in
160 // bounded batches, since it is both written and read
161 // throughout the cycle. At the end of the cycle, this is how
162 // much of the retained heap is scannable.
164 // Currently this is the bytes of heap scanned. For most uses,
165 // this is an opaque unit of work, but for estimation the
166 // definition is important.
169 // bgScanCredit is the scan work credit accumulated by the
170 // concurrent background scan. This credit is accumulated by
171 // the background scan and stolen by mutator assists. This is
172 // updated atomically. Updates occur in bounded batches, since
173 // it is both written and read throughout the cycle.
176 // assistTime is the nanoseconds spent in mutator assists
177 // during this cycle. This is updated atomically. Updates
178 // occur in bounded batches, since it is both written and read
179 // throughout the cycle.
182 // dedicatedMarkTime is the nanoseconds spent in dedicated
183 // mark workers during this cycle. This is updated atomically
184 // at the end of the concurrent mark phase.
185 dedicatedMarkTime int64
187 // fractionalMarkTime is the nanoseconds spent in the
188 // fractional mark worker during this cycle. This is updated
189 // atomically throughout the cycle and will be up-to-date if
190 // the fractional mark worker is not currently running.
191 fractionalMarkTime int64
193 // idleMarkTime is the nanoseconds spent in idle marking
194 // during this cycle. This is updated atomically throughout
198 // markStartTime is the absolute start time in nanoseconds
199 // that assists and background mark workers started.
202 // dedicatedMarkWorkersNeeded is the number of dedicated mark
203 // workers that need to be started. This is computed at the
204 // beginning of each cycle and decremented atomically as
205 // dedicated mark workers get started.
206 dedicatedMarkWorkersNeeded int64
208 // assistWorkPerByte is the ratio of scan work to allocated
209 // bytes that should be performed by mutator assists. This is
210 // computed at the beginning of each cycle and updated every
211 // time heapScan is updated.
213 // Stored as a uint64, but it's actually a float64. Use
214 // float64frombits to get the value.
216 // Read and written atomically.
217 assistWorkPerByte uint64
219 // assistBytesPerWork is 1/assistWorkPerByte.
221 // Stored as a uint64, but it's actually a float64. Use
222 // float64frombits to get the value.
224 // Read and written atomically.
226 // Note that because this is read and written independently
227 // from assistWorkPerByte users may notice a skew between
228 // the two values, and such a state should be safe.
229 assistBytesPerWork uint64
231 // fractionalUtilizationGoal is the fraction of wall clock
232 // time that should be spent in the fractional mark worker on
233 // each P that isn't running a dedicated worker.
235 // For example, if the utilization goal is 25% and there are
236 // no dedicated workers, this will be 0.25. If the goal is
237 // 25%, there is one dedicated worker, and GOMAXPROCS is 5,
238 // this will be 0.05 to make up the missing 5%.
240 // If this is zero, no fractional workers are needed.
241 fractionalUtilizationGoal float64
246 func (c *gcControllerState) init(gcPercent int32) {
247 c.heapMinimum = defaultHeapMinimum
249 // Set a reasonable initial GC trigger.
250 c.triggerRatio = 7 / 8.0
252 // Fake a heapMarked value so it looks like a trigger at
253 // heapMinimum is the appropriate growth from heapMarked.
254 // This will go into computing the initial GC goal.
255 c.heapMarked = uint64(float64(c.heapMinimum) / (1 + c.triggerRatio))
257 // This will also compute and set the GC trigger and goal.
258 c.setGCPercent(gcPercent)
261 // startCycle resets the GC controller's state and computes estimates
262 // for a new GC cycle. The caller must hold worldsema and the world
264 func (c *gcControllerState) startCycle() {
268 c.dedicatedMarkTime = 0
269 c.fractionalMarkTime = 0
272 // Ensure that the heap goal is at least a little larger than
273 // the current live heap size. This may not be the case if GC
274 // start is delayed or if the allocation that pushed gcController.heapLive
275 // over trigger is large or if the trigger is really close to
276 // GOGC. Assist is proportional to this distance, so enforce a
277 // minimum distance, even if it means going over the GOGC goal
279 if memstats.next_gc < c.heapLive+1024*1024 {
280 memstats.next_gc = c.heapLive + 1024*1024
283 // Compute the background mark utilization goal. In general,
284 // this may not come out exactly. We round the number of
285 // dedicated workers so that the utilization is closest to
286 // 25%. For small GOMAXPROCS, this would introduce too much
287 // error, so we add fractional workers in that case.
288 totalUtilizationGoal := float64(gomaxprocs) * gcBackgroundUtilization
289 c.dedicatedMarkWorkersNeeded = int64(totalUtilizationGoal + 0.5)
290 utilError := float64(c.dedicatedMarkWorkersNeeded)/totalUtilizationGoal - 1
291 const maxUtilError = 0.3
292 if utilError < -maxUtilError || utilError > maxUtilError {
293 // Rounding put us more than 30% off our goal. With
294 // gcBackgroundUtilization of 25%, this happens for
295 // GOMAXPROCS<=3 or GOMAXPROCS=6. Enable fractional
296 // workers to compensate.
297 if float64(c.dedicatedMarkWorkersNeeded) > totalUtilizationGoal {
298 // Too many dedicated workers.
299 c.dedicatedMarkWorkersNeeded--
301 c.fractionalUtilizationGoal = (totalUtilizationGoal - float64(c.dedicatedMarkWorkersNeeded)) / float64(gomaxprocs)
303 c.fractionalUtilizationGoal = 0
306 // In STW mode, we just want dedicated workers.
307 if debug.gcstoptheworld > 0 {
308 c.dedicatedMarkWorkersNeeded = int64(gomaxprocs)
309 c.fractionalUtilizationGoal = 0
313 for _, p := range allp {
315 p.gcFractionalMarkTime = 0
318 // Compute initial values for controls that are updated
319 // throughout the cycle.
322 if debug.gcpacertrace > 0 {
323 assistRatio := float64frombits(atomic.Load64(&c.assistWorkPerByte))
324 print("pacer: assist ratio=", assistRatio,
325 " (scan ", gcController.heapScan>>20, " MB in ",
326 work.initialHeapLive>>20, "->",
327 memstats.next_gc>>20, " MB)",
328 " workers=", c.dedicatedMarkWorkersNeeded,
329 "+", c.fractionalUtilizationGoal, "\n")
333 // revise updates the assist ratio during the GC cycle to account for
334 // improved estimates. This should be called whenever gcController.heapScan,
335 // gcController.heapLive, or memstats.next_gc is updated. It is safe to
336 // call concurrently, but it may race with other calls to revise.
338 // The result of this race is that the two assist ratio values may not line
339 // up or may be stale. In practice this is OK because the assist ratio
340 // moves slowly throughout a GC cycle, and the assist ratio is a best-effort
341 // heuristic anyway. Furthermore, no part of the heuristic depends on
342 // the two assist ratio values being exact reciprocals of one another, since
343 // the two values are used to convert values from different sources.
345 // The worst case result of this raciness is that we may miss a larger shift
346 // in the ratio (say, if we decide to pace more aggressively against the
347 // hard heap goal) but even this "hard goal" is best-effort (see #40460).
348 // The dedicated GC should ensure we don't exceed the hard goal by too much
349 // in the rare case we do exceed it.
351 // It should only be called when gcBlackenEnabled != 0 (because this
352 // is when assists are enabled and the necessary statistics are
354 func (c *gcControllerState) revise() {
355 gcPercent := c.gcPercent
357 // If GC is disabled but we're running a forced GC,
358 // act like GOGC is huge for the below calculations.
361 live := atomic.Load64(&c.heapLive)
362 scan := atomic.Load64(&c.heapScan)
363 work := atomic.Loadint64(&c.scanWork)
365 // Assume we're under the soft goal. Pace GC to complete at
366 // next_gc assuming the heap is in steady-state.
367 heapGoal := int64(atomic.Load64(&memstats.next_gc))
369 // Compute the expected scan work remaining.
371 // This is estimated based on the expected
372 // steady-state scannable heap. For example, with
373 // GOGC=100, only half of the scannable heap is
374 // expected to be live, so that's what we target.
376 // (This is a float calculation to avoid overflowing on
378 scanWorkExpected := int64(float64(scan) * 100 / float64(100+gcPercent))
380 if int64(live) > heapGoal || work > scanWorkExpected {
381 // We're past the soft goal, or we've already done more scan
382 // work than we expected. Pace GC so that in the worst case it
383 // will complete by the hard goal.
384 const maxOvershoot = 1.1
385 heapGoal = int64(float64(heapGoal) * maxOvershoot)
387 // Compute the upper bound on the scan work remaining.
388 scanWorkExpected = int64(scan)
391 // Compute the remaining scan work estimate.
393 // Note that we currently count allocations during GC as both
394 // scannable heap (heapScan) and scan work completed
395 // (scanWork), so allocation will change this difference
396 // slowly in the soft regime and not at all in the hard
398 scanWorkRemaining := scanWorkExpected - work
399 if scanWorkRemaining < 1000 {
400 // We set a somewhat arbitrary lower bound on
401 // remaining scan work since if we aim a little high,
402 // we can miss by a little.
404 // We *do* need to enforce that this is at least 1,
405 // since marking is racy and double-scanning objects
406 // may legitimately make the remaining scan work
407 // negative, even in the hard goal regime.
408 scanWorkRemaining = 1000
411 // Compute the heap distance remaining.
412 heapRemaining := heapGoal - int64(live)
413 if heapRemaining <= 0 {
414 // This shouldn't happen, but if it does, avoid
415 // dividing by zero or setting the assist negative.
419 // Compute the mutator assist ratio so by the time the mutator
420 // allocates the remaining heap bytes up to next_gc, it will
421 // have done (or stolen) the remaining amount of scan work.
422 // Note that the assist ratio values are updated atomically
423 // but not together. This means there may be some degree of
424 // skew between the two values. This is generally OK as the
425 // values shift relatively slowly over the course of a GC
427 assistWorkPerByte := float64(scanWorkRemaining) / float64(heapRemaining)
428 assistBytesPerWork := float64(heapRemaining) / float64(scanWorkRemaining)
429 atomic.Store64(&c.assistWorkPerByte, float64bits(assistWorkPerByte))
430 atomic.Store64(&c.assistBytesPerWork, float64bits(assistBytesPerWork))
433 // endCycle computes the trigger ratio for the next cycle.
434 func (c *gcControllerState) endCycle() float64 {
436 // Forced GC means this cycle didn't start at the
437 // trigger, so where it finished isn't good
438 // information about how to adjust the trigger.
439 // Just leave it where it is.
440 return c.triggerRatio
443 // Proportional response gain for the trigger controller. Must
444 // be in [0, 1]. Lower values smooth out transient effects but
445 // take longer to respond to phase changes. Higher values
446 // react to phase changes quickly, but are more affected by
447 // transient changes. Values near 1 may be unstable.
448 const triggerGain = 0.5
450 // Compute next cycle trigger ratio. First, this computes the
451 // "error" for this cycle; that is, how far off the trigger
452 // was from what it should have been, accounting for both heap
453 // growth and GC CPU utilization. We compute the actual heap
454 // growth during this cycle and scale that by how far off from
455 // the goal CPU utilization we were (to estimate the heap
456 // growth if we had the desired CPU utilization). The
457 // difference between this estimate and the GOGC-based goal
458 // heap growth is the error.
459 goalGrowthRatio := gcEffectiveGrowthRatio()
460 actualGrowthRatio := float64(c.heapLive)/float64(c.heapMarked) - 1
461 assistDuration := nanotime() - c.markStartTime
463 // Assume background mark hit its utilization goal.
464 utilization := gcBackgroundUtilization
465 // Add assist utilization; avoid divide by zero.
466 if assistDuration > 0 {
467 utilization += float64(c.assistTime) / float64(assistDuration*int64(gomaxprocs))
470 triggerError := goalGrowthRatio - c.triggerRatio - utilization/gcGoalUtilization*(actualGrowthRatio-c.triggerRatio)
472 // Finally, we adjust the trigger for next time by this error,
473 // damped by the proportional gain.
474 triggerRatio := c.triggerRatio + triggerGain*triggerError
476 if debug.gcpacertrace > 0 {
477 // Print controller state in terms of the design
479 H_m_prev := c.heapMarked
480 h_t := c.triggerRatio
482 h_a := actualGrowthRatio
484 h_g := goalGrowthRatio
485 H_g := int64(float64(H_m_prev) * (1 + h_g))
487 u_g := gcGoalUtilization
489 print("pacer: H_m_prev=", H_m_prev,
490 " h_t=", h_t, " H_T=", H_T,
491 " h_a=", h_a, " H_a=", H_a,
492 " h_g=", h_g, " H_g=", H_g,
493 " u_a=", u_a, " u_g=", u_g,
495 " goalΔ=", goalGrowthRatio-h_t,
496 " actualΔ=", h_a-h_t,
497 " u_a/u_g=", u_a/u_g,
504 // enlistWorker encourages another dedicated mark worker to start on
505 // another P if there are spare worker slots. It is used by putfull
506 // when more work is made available.
509 func (c *gcControllerState) enlistWorker() {
510 // If there are idle Ps, wake one so it will run an idle worker.
511 // NOTE: This is suspected of causing deadlocks. See golang.org/issue/19112.
513 // if atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 {
518 // There are no idle Ps. If we need more dedicated workers,
519 // try to preempt a running P so it will switch to a worker.
520 if c.dedicatedMarkWorkersNeeded <= 0 {
523 // Pick a random other P to preempt.
528 if gp == nil || gp.m == nil || gp.m.p == 0 {
531 myID := gp.m.p.ptr().id
532 for tries := 0; tries < 5; tries++ {
533 id := int32(fastrandn(uint32(gomaxprocs - 1)))
538 if p.status != _Prunning {
547 // findRunnableGCWorker returns a background mark worker for _p_ if it
548 // should be run. This must only be called when gcBlackenEnabled != 0.
549 func (c *gcControllerState) findRunnableGCWorker(_p_ *p) *g {
550 if gcBlackenEnabled == 0 {
551 throw("gcControllerState.findRunnable: blackening not enabled")
554 if !gcMarkWorkAvailable(_p_) {
555 // No work to be done right now. This can happen at
556 // the end of the mark phase when there are still
557 // assists tapering off. Don't bother running a worker
558 // now because it'll just return immediately.
562 // Grab a worker before we commit to running below.
563 node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
565 // There is at least one worker per P, so normally there are
566 // enough workers to run on all Ps, if necessary. However, once
567 // a worker enters gcMarkDone it may park without rejoining the
568 // pool, thus freeing a P with no corresponding worker.
569 // gcMarkDone never depends on another worker doing work, so it
570 // is safe to simply do nothing here.
572 // If gcMarkDone bails out without completing the mark phase,
573 // it will always do so with queued global work. Thus, that P
574 // will be immediately eligible to re-run the worker G it was
575 // just using, ensuring work can complete.
579 decIfPositive := func(ptr *int64) bool {
581 v := atomic.Loadint64(ptr)
586 if atomic.Casint64(ptr, v, v-1) {
592 if decIfPositive(&c.dedicatedMarkWorkersNeeded) {
593 // This P is now dedicated to marking until the end of
594 // the concurrent mark phase.
595 _p_.gcMarkWorkerMode = gcMarkWorkerDedicatedMode
596 } else if c.fractionalUtilizationGoal == 0 {
597 // No need for fractional workers.
598 gcBgMarkWorkerPool.push(&node.node)
601 // Is this P behind on the fractional utilization
604 // This should be kept in sync with pollFractionalWorkerExit.
605 delta := nanotime() - c.markStartTime
606 if delta > 0 && float64(_p_.gcFractionalMarkTime)/float64(delta) > c.fractionalUtilizationGoal {
607 // Nope. No need to run a fractional worker.
608 gcBgMarkWorkerPool.push(&node.node)
611 // Run a fractional worker.
612 _p_.gcMarkWorkerMode = gcMarkWorkerFractionalMode
615 // Run the background mark worker.
617 casgstatus(gp, _Gwaiting, _Grunnable)
624 // commit sets the trigger ratio and updates everything
625 // derived from it: the absolute trigger, the heap goal, mark pacing,
628 // This can be called any time. If GC is the in the middle of a
629 // concurrent phase, it will adjust the pacing of that phase.
631 // This depends on gcPercent, gcController.heapMarked, and
632 // gcController.heapLive. These must be up to date.
634 // mheap_.lock must be held or the world must be stopped.
635 func (c *gcControllerState) commit(triggerRatio float64) {
636 assertWorldStoppedOrLockHeld(&mheap_.lock)
638 // Compute the next GC goal, which is when the allocated heap
639 // has grown by GOGC/100 over the heap marked by the last
642 if c.gcPercent >= 0 {
643 goal = c.heapMarked + c.heapMarked*uint64(c.gcPercent)/100
646 // Set the trigger ratio, capped to reasonable bounds.
647 if c.gcPercent >= 0 {
648 scalingFactor := float64(c.gcPercent) / 100
649 // Ensure there's always a little margin so that the
650 // mutator assist ratio isn't infinity.
651 maxTriggerRatio := 0.95 * scalingFactor
652 if triggerRatio > maxTriggerRatio {
653 triggerRatio = maxTriggerRatio
656 // If we let triggerRatio go too low, then if the application
657 // is allocating very rapidly we might end up in a situation
658 // where we're allocating black during a nearly always-on GC.
659 // The result of this is a growing heap and ultimately an
660 // increase in RSS. By capping us at a point >0, we're essentially
661 // saying that we're OK using more CPU during the GC to prevent
662 // this growth in RSS.
664 // The current constant was chosen empirically: given a sufficiently
665 // fast/scalable allocator with 48 Ps that could drive the trigger ratio
666 // to <0.05, this constant causes applications to retain the same peak
667 // RSS compared to not having this allocator.
668 minTriggerRatio := 0.6 * scalingFactor
669 if triggerRatio < minTriggerRatio {
670 triggerRatio = minTriggerRatio
672 } else if triggerRatio < 0 {
673 // gcPercent < 0, so just make sure we're not getting a negative
674 // triggerRatio. This case isn't expected to happen in practice,
675 // and doesn't really matter because if gcPercent < 0 then we won't
676 // ever consume triggerRatio further on in this function, but let's
677 // just be defensive here; the triggerRatio being negative is almost
678 // certainly undesirable.
681 c.triggerRatio = triggerRatio
683 // Compute the absolute GC trigger from the trigger ratio.
685 // We trigger the next GC cycle when the allocated heap has
686 // grown by the trigger ratio over the marked heap size.
687 trigger := ^uint64(0)
688 if c.gcPercent >= 0 {
689 trigger = uint64(float64(c.heapMarked) * (1 + triggerRatio))
690 // Don't trigger below the minimum heap size.
691 minTrigger := c.heapMinimum
693 // Concurrent sweep happens in the heap growth
694 // from gcController.heapLive to trigger, so ensure
695 // that concurrent sweep has some heap growth
696 // in which to perform sweeping before we
697 // start the next GC cycle.
698 sweepMin := atomic.Load64(&c.heapLive) + sweepMinHeapDistance
699 if sweepMin > minTrigger {
700 minTrigger = sweepMin
703 if trigger < minTrigger {
706 if int64(trigger) < 0 {
707 print("runtime: next_gc=", memstats.next_gc, " heapMarked=", c.heapMarked, " gcController.heapLive=", c.heapLive, " initialHeapLive=", work.initialHeapLive, "triggerRatio=", triggerRatio, " minTrigger=", minTrigger, "\n")
708 throw("trigger underflow")
711 // The trigger ratio is always less than GOGC/100, but
712 // other bounds on the trigger may have raised it.
713 // Push up the goal, too.
718 // Commit to the trigger and goal.
720 atomic.Store64(&memstats.next_gc, goal)
725 // Update mark pacing.
726 if gcphase != _GCoff {
730 // Update sweep pacing.
732 mheap_.sweepPagesPerByte = 0
734 // Concurrent sweep needs to sweep all of the in-use
735 // pages by the time the allocated heap reaches the GC
736 // trigger. Compute the ratio of in-use pages to sweep
737 // per byte allocated, accounting for the fact that
738 // some might already be swept.
739 heapLiveBasis := atomic.Load64(&c.heapLive)
740 heapDistance := int64(trigger) - int64(heapLiveBasis)
741 // Add a little margin so rounding errors and
742 // concurrent sweep are less likely to leave pages
743 // unswept when GC starts.
744 heapDistance -= 1024 * 1024
745 if heapDistance < _PageSize {
746 // Avoid setting the sweep ratio extremely high
747 heapDistance = _PageSize
749 pagesSwept := atomic.Load64(&mheap_.pagesSwept)
750 pagesInUse := atomic.Load64(&mheap_.pagesInUse)
751 sweepDistancePages := int64(pagesInUse) - int64(pagesSwept)
752 if sweepDistancePages <= 0 {
753 mheap_.sweepPagesPerByte = 0
755 mheap_.sweepPagesPerByte = float64(sweepDistancePages) / float64(heapDistance)
756 mheap_.sweepHeapLiveBasis = heapLiveBasis
757 // Write pagesSweptBasis last, since this
758 // signals concurrent sweeps to recompute
760 atomic.Store64(&mheap_.pagesSweptBasis, pagesSwept)
767 // gcEffectiveGrowthRatio returns the current effective heap growth
768 // ratio (GOGC/100) based on heapMarked from the previous GC and
769 // next_gc for the current GC.
771 // This may differ from gcPercent/100 because of various upper and
772 // lower bounds on gcPercent. For example, if the heap is smaller than
773 // heapMinimum, this can be higher than gcPercent/100.
775 // mheap_.lock must be held or the world must be stopped.
776 func gcEffectiveGrowthRatio() float64 {
777 assertWorldStoppedOrLockHeld(&mheap_.lock)
779 egogc := float64(atomic.Load64(&memstats.next_gc)-gcController.heapMarked) / float64(gcController.heapMarked)
781 // Shouldn't happen, but just in case.
787 // setGCPercent updates gcPercent and all related pacer state.
788 // Returns the old value of gcPercent.
790 // The world must be stopped, or mheap_.lock must be held.
791 func (c *gcControllerState) setGCPercent(in int32) int32 {
792 assertWorldStoppedOrLockHeld(&mheap_.lock)
799 c.heapMinimum = defaultHeapMinimum * uint64(c.gcPercent) / 100
800 // Update pacing in response to gcPercent change.
801 c.commit(c.triggerRatio)
806 //go:linkname setGCPercent runtime/debug.setGCPercent
807 func setGCPercent(in int32) (out int32) {
808 // Run on the system stack since we grab the heap lock.
811 out = gcController.setGCPercent(in)
815 // If we just disabled GC, wait for any concurrent GC mark to
816 // finish so we always return with no GC running.
818 gcWaitOnMark(atomic.Load(&work.cycles))
824 func readGOGC() int32 {
825 p := gogetenv("GOGC")
829 if n, ok := atoi32(p); ok {