]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/mgcpacer.go
runtime: rename gcpercent, readgogc, and heapminimum to match Go style
[gostls13.git] / src / runtime / mgcpacer.go
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.
4
5 package runtime
6
7 import (
8         "internal/cpu"
9         "runtime/internal/atomic"
10         _ "unsafe" // for linkname
11 )
12
13 const (
14         // gcGoalUtilization is the goal CPU utilization for
15         // marking as a fraction of GOMAXPROCS.
16         gcGoalUtilization = 0.30
17
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
22         // goal.
23         //
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
28         // mutator latency.
29         gcBackgroundUtilization = 0.25
30
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
36         // contention.
37         gcCreditSlack = 2000
38
39         // gcAssistTimeSlack is the nanoseconds of mutator assist time that
40         // can accumulate on a P before updating gcController.assistTime.
41         gcAssistTimeSlack = 5000
42
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
47
48         // defaultHeapMinimum is the value of heapMinimum for GOGC==100.
49         defaultHeapMinimum = 4 << 20
50 )
51
52 var (
53         // heapMinimum is the minimum heap size at which to trigger GC.
54         // For small heaps, this overrides the usual GOGC*live set rule.
55         //
56         // When there is a very small live set but a lot of allocation, simply
57         // collecting when the heap reaches GOGC*live results in many GC
58         // cycles and high total per-GC overhead. This minimum amortizes this
59         // per-GC overhead while keeping the heap reasonably small.
60         //
61         // During initialization this is set to 4MB*GOGC/100. In the case of
62         // GOGC==0, this will set heapMinimum to 0, resulting in constant
63         // collection even when the heap size is small, which is useful for
64         // debugging.
65         heapMinimum uint64 = defaultHeapMinimum
66
67         // Initialized from $GOGC.  GOGC=off means no GC.
68         gcPercent int32
69 )
70
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.
74 //
75 // It uses a feedback control algorithm to adjust the memstats.gc_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.
81 //
82 // All fields of gcController are used only during a single mark
83 // cycle.
84 var gcController gcControllerState
85
86 type gcControllerState struct {
87         // scanWork is the total scan work performed this cycle. This
88         // is updated atomically during the cycle. Updates occur in
89         // bounded batches, since it is both written and read
90         // throughout the cycle. At the end of the cycle, this is how
91         // much of the retained heap is scannable.
92         //
93         // Currently this is the bytes of heap scanned. For most uses,
94         // this is an opaque unit of work, but for estimation the
95         // definition is important.
96         scanWork int64
97
98         // bgScanCredit is the scan work credit accumulated by the
99         // concurrent background scan. This credit is accumulated by
100         // the background scan and stolen by mutator assists. This is
101         // updated atomically. Updates occur in bounded batches, since
102         // it is both written and read throughout the cycle.
103         bgScanCredit int64
104
105         // assistTime is the nanoseconds spent in mutator assists
106         // during this cycle. This is updated atomically. Updates
107         // occur in bounded batches, since it is both written and read
108         // throughout the cycle.
109         assistTime int64
110
111         // dedicatedMarkTime is the nanoseconds spent in dedicated
112         // mark workers during this cycle. This is updated atomically
113         // at the end of the concurrent mark phase.
114         dedicatedMarkTime int64
115
116         // fractionalMarkTime is the nanoseconds spent in the
117         // fractional mark worker during this cycle. This is updated
118         // atomically throughout the cycle and will be up-to-date if
119         // the fractional mark worker is not currently running.
120         fractionalMarkTime int64
121
122         // idleMarkTime is the nanoseconds spent in idle marking
123         // during this cycle. This is updated atomically throughout
124         // the cycle.
125         idleMarkTime int64
126
127         // markStartTime is the absolute start time in nanoseconds
128         // that assists and background mark workers started.
129         markStartTime int64
130
131         // dedicatedMarkWorkersNeeded is the number of dedicated mark
132         // workers that need to be started. This is computed at the
133         // beginning of each cycle and decremented atomically as
134         // dedicated mark workers get started.
135         dedicatedMarkWorkersNeeded int64
136
137         // assistWorkPerByte is the ratio of scan work to allocated
138         // bytes that should be performed by mutator assists. This is
139         // computed at the beginning of each cycle and updated every
140         // time heap_scan is updated.
141         //
142         // Stored as a uint64, but it's actually a float64. Use
143         // float64frombits to get the value.
144         //
145         // Read and written atomically.
146         assistWorkPerByte uint64
147
148         // assistBytesPerWork is 1/assistWorkPerByte.
149         //
150         // Stored as a uint64, but it's actually a float64. Use
151         // float64frombits to get the value.
152         //
153         // Read and written atomically.
154         //
155         // Note that because this is read and written independently
156         // from assistWorkPerByte users may notice a skew between
157         // the two values, and such a state should be safe.
158         assistBytesPerWork uint64
159
160         // fractionalUtilizationGoal is the fraction of wall clock
161         // time that should be spent in the fractional mark worker on
162         // each P that isn't running a dedicated worker.
163         //
164         // For example, if the utilization goal is 25% and there are
165         // no dedicated workers, this will be 0.25. If the goal is
166         // 25%, there is one dedicated worker, and GOMAXPROCS is 5,
167         // this will be 0.05 to make up the missing 5%.
168         //
169         // If this is zero, no fractional workers are needed.
170         fractionalUtilizationGoal float64
171
172         _ cpu.CacheLinePad
173 }
174
175 // startCycle resets the GC controller's state and computes estimates
176 // for a new GC cycle. The caller must hold worldsema and the world
177 // must be stopped.
178 func (c *gcControllerState) startCycle() {
179         c.scanWork = 0
180         c.bgScanCredit = 0
181         c.assistTime = 0
182         c.dedicatedMarkTime = 0
183         c.fractionalMarkTime = 0
184         c.idleMarkTime = 0
185
186         // Ensure that the heap goal is at least a little larger than
187         // the current live heap size. This may not be the case if GC
188         // start is delayed or if the allocation that pushed heap_live
189         // over gc_trigger is large or if the trigger is really close to
190         // GOGC. Assist is proportional to this distance, so enforce a
191         // minimum distance, even if it means going over the GOGC goal
192         // by a tiny bit.
193         if memstats.next_gc < memstats.heap_live+1024*1024 {
194                 memstats.next_gc = memstats.heap_live + 1024*1024
195         }
196
197         // Compute the background mark utilization goal. In general,
198         // this may not come out exactly. We round the number of
199         // dedicated workers so that the utilization is closest to
200         // 25%. For small GOMAXPROCS, this would introduce too much
201         // error, so we add fractional workers in that case.
202         totalUtilizationGoal := float64(gomaxprocs) * gcBackgroundUtilization
203         c.dedicatedMarkWorkersNeeded = int64(totalUtilizationGoal + 0.5)
204         utilError := float64(c.dedicatedMarkWorkersNeeded)/totalUtilizationGoal - 1
205         const maxUtilError = 0.3
206         if utilError < -maxUtilError || utilError > maxUtilError {
207                 // Rounding put us more than 30% off our goal. With
208                 // gcBackgroundUtilization of 25%, this happens for
209                 // GOMAXPROCS<=3 or GOMAXPROCS=6. Enable fractional
210                 // workers to compensate.
211                 if float64(c.dedicatedMarkWorkersNeeded) > totalUtilizationGoal {
212                         // Too many dedicated workers.
213                         c.dedicatedMarkWorkersNeeded--
214                 }
215                 c.fractionalUtilizationGoal = (totalUtilizationGoal - float64(c.dedicatedMarkWorkersNeeded)) / float64(gomaxprocs)
216         } else {
217                 c.fractionalUtilizationGoal = 0
218         }
219
220         // In STW mode, we just want dedicated workers.
221         if debug.gcstoptheworld > 0 {
222                 c.dedicatedMarkWorkersNeeded = int64(gomaxprocs)
223                 c.fractionalUtilizationGoal = 0
224         }
225
226         // Clear per-P state
227         for _, p := range allp {
228                 p.gcAssistTime = 0
229                 p.gcFractionalMarkTime = 0
230         }
231
232         // Compute initial values for controls that are updated
233         // throughout the cycle.
234         c.revise()
235
236         if debug.gcpacertrace > 0 {
237                 assistRatio := float64frombits(atomic.Load64(&c.assistWorkPerByte))
238                 print("pacer: assist ratio=", assistRatio,
239                         " (scan ", memstats.heap_scan>>20, " MB in ",
240                         work.initialHeapLive>>20, "->",
241                         memstats.next_gc>>20, " MB)",
242                         " workers=", c.dedicatedMarkWorkersNeeded,
243                         "+", c.fractionalUtilizationGoal, "\n")
244         }
245 }
246
247 // revise updates the assist ratio during the GC cycle to account for
248 // improved estimates. This should be called whenever memstats.heap_scan,
249 // memstats.heap_live, or memstats.next_gc is updated. It is safe to
250 // call concurrently, but it may race with other calls to revise.
251 //
252 // The result of this race is that the two assist ratio values may not line
253 // up or may be stale. In practice this is OK because the assist ratio
254 // moves slowly throughout a GC cycle, and the assist ratio is a best-effort
255 // heuristic anyway. Furthermore, no part of the heuristic depends on
256 // the two assist ratio values being exact reciprocals of one another, since
257 // the two values are used to convert values from different sources.
258 //
259 // The worst case result of this raciness is that we may miss a larger shift
260 // in the ratio (say, if we decide to pace more aggressively against the
261 // hard heap goal) but even this "hard goal" is best-effort (see #40460).
262 // The dedicated GC should ensure we don't exceed the hard goal by too much
263 // in the rare case we do exceed it.
264 //
265 // It should only be called when gcBlackenEnabled != 0 (because this
266 // is when assists are enabled and the necessary statistics are
267 // available).
268 func (c *gcControllerState) revise() {
269         gcPercent := gcPercent
270         if gcPercent < 0 {
271                 // If GC is disabled but we're running a forced GC,
272                 // act like GOGC is huge for the below calculations.
273                 gcPercent = 100000
274         }
275         live := atomic.Load64(&memstats.heap_live)
276         scan := atomic.Load64(&memstats.heap_scan)
277         work := atomic.Loadint64(&c.scanWork)
278
279         // Assume we're under the soft goal. Pace GC to complete at
280         // next_gc assuming the heap is in steady-state.
281         heapGoal := int64(atomic.Load64(&memstats.next_gc))
282
283         // Compute the expected scan work remaining.
284         //
285         // This is estimated based on the expected
286         // steady-state scannable heap. For example, with
287         // GOGC=100, only half of the scannable heap is
288         // expected to be live, so that's what we target.
289         //
290         // (This is a float calculation to avoid overflowing on
291         // 100*heap_scan.)
292         scanWorkExpected := int64(float64(scan) * 100 / float64(100+gcPercent))
293
294         if int64(live) > heapGoal || work > scanWorkExpected {
295                 // We're past the soft goal, or we've already done more scan
296                 // work than we expected. Pace GC so that in the worst case it
297                 // will complete by the hard goal.
298                 const maxOvershoot = 1.1
299                 heapGoal = int64(float64(heapGoal) * maxOvershoot)
300
301                 // Compute the upper bound on the scan work remaining.
302                 scanWorkExpected = int64(scan)
303         }
304
305         // Compute the remaining scan work estimate.
306         //
307         // Note that we currently count allocations during GC as both
308         // scannable heap (heap_scan) and scan work completed
309         // (scanWork), so allocation will change this difference
310         // slowly in the soft regime and not at all in the hard
311         // regime.
312         scanWorkRemaining := scanWorkExpected - work
313         if scanWorkRemaining < 1000 {
314                 // We set a somewhat arbitrary lower bound on
315                 // remaining scan work since if we aim a little high,
316                 // we can miss by a little.
317                 //
318                 // We *do* need to enforce that this is at least 1,
319                 // since marking is racy and double-scanning objects
320                 // may legitimately make the remaining scan work
321                 // negative, even in the hard goal regime.
322                 scanWorkRemaining = 1000
323         }
324
325         // Compute the heap distance remaining.
326         heapRemaining := heapGoal - int64(live)
327         if heapRemaining <= 0 {
328                 // This shouldn't happen, but if it does, avoid
329                 // dividing by zero or setting the assist negative.
330                 heapRemaining = 1
331         }
332
333         // Compute the mutator assist ratio so by the time the mutator
334         // allocates the remaining heap bytes up to next_gc, it will
335         // have done (or stolen) the remaining amount of scan work.
336         // Note that the assist ratio values are updated atomically
337         // but not together. This means there may be some degree of
338         // skew between the two values. This is generally OK as the
339         // values shift relatively slowly over the course of a GC
340         // cycle.
341         assistWorkPerByte := float64(scanWorkRemaining) / float64(heapRemaining)
342         assistBytesPerWork := float64(heapRemaining) / float64(scanWorkRemaining)
343         atomic.Store64(&c.assistWorkPerByte, float64bits(assistWorkPerByte))
344         atomic.Store64(&c.assistBytesPerWork, float64bits(assistBytesPerWork))
345 }
346
347 // endCycle computes the trigger ratio for the next cycle.
348 func (c *gcControllerState) endCycle() float64 {
349         if work.userForced {
350                 // Forced GC means this cycle didn't start at the
351                 // trigger, so where it finished isn't good
352                 // information about how to adjust the trigger.
353                 // Just leave it where it is.
354                 return memstats.triggerRatio
355         }
356
357         // Proportional response gain for the trigger controller. Must
358         // be in [0, 1]. Lower values smooth out transient effects but
359         // take longer to respond to phase changes. Higher values
360         // react to phase changes quickly, but are more affected by
361         // transient changes. Values near 1 may be unstable.
362         const triggerGain = 0.5
363
364         // Compute next cycle trigger ratio. First, this computes the
365         // "error" for this cycle; that is, how far off the trigger
366         // was from what it should have been, accounting for both heap
367         // growth and GC CPU utilization. We compute the actual heap
368         // growth during this cycle and scale that by how far off from
369         // the goal CPU utilization we were (to estimate the heap
370         // growth if we had the desired CPU utilization). The
371         // difference between this estimate and the GOGC-based goal
372         // heap growth is the error.
373         goalGrowthRatio := gcEffectiveGrowthRatio()
374         actualGrowthRatio := float64(memstats.heap_live)/float64(memstats.heap_marked) - 1
375         assistDuration := nanotime() - c.markStartTime
376
377         // Assume background mark hit its utilization goal.
378         utilization := gcBackgroundUtilization
379         // Add assist utilization; avoid divide by zero.
380         if assistDuration > 0 {
381                 utilization += float64(c.assistTime) / float64(assistDuration*int64(gomaxprocs))
382         }
383
384         triggerError := goalGrowthRatio - memstats.triggerRatio - utilization/gcGoalUtilization*(actualGrowthRatio-memstats.triggerRatio)
385
386         // Finally, we adjust the trigger for next time by this error,
387         // damped by the proportional gain.
388         triggerRatio := memstats.triggerRatio + triggerGain*triggerError
389
390         if debug.gcpacertrace > 0 {
391                 // Print controller state in terms of the design
392                 // document.
393                 H_m_prev := memstats.heap_marked
394                 h_t := memstats.triggerRatio
395                 H_T := memstats.gc_trigger
396                 h_a := actualGrowthRatio
397                 H_a := memstats.heap_live
398                 h_g := goalGrowthRatio
399                 H_g := int64(float64(H_m_prev) * (1 + h_g))
400                 u_a := utilization
401                 u_g := gcGoalUtilization
402                 W_a := c.scanWork
403                 print("pacer: H_m_prev=", H_m_prev,
404                         " h_t=", h_t, " H_T=", H_T,
405                         " h_a=", h_a, " H_a=", H_a,
406                         " h_g=", h_g, " H_g=", H_g,
407                         " u_a=", u_a, " u_g=", u_g,
408                         " W_a=", W_a,
409                         " goalΔ=", goalGrowthRatio-h_t,
410                         " actualΔ=", h_a-h_t,
411                         " u_a/u_g=", u_a/u_g,
412                         "\n")
413         }
414
415         return triggerRatio
416 }
417
418 // enlistWorker encourages another dedicated mark worker to start on
419 // another P if there are spare worker slots. It is used by putfull
420 // when more work is made available.
421 //
422 //go:nowritebarrier
423 func (c *gcControllerState) enlistWorker() {
424         // If there are idle Ps, wake one so it will run an idle worker.
425         // NOTE: This is suspected of causing deadlocks. See golang.org/issue/19112.
426         //
427         //      if atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 {
428         //              wakep()
429         //              return
430         //      }
431
432         // There are no idle Ps. If we need more dedicated workers,
433         // try to preempt a running P so it will switch to a worker.
434         if c.dedicatedMarkWorkersNeeded <= 0 {
435                 return
436         }
437         // Pick a random other P to preempt.
438         if gomaxprocs <= 1 {
439                 return
440         }
441         gp := getg()
442         if gp == nil || gp.m == nil || gp.m.p == 0 {
443                 return
444         }
445         myID := gp.m.p.ptr().id
446         for tries := 0; tries < 5; tries++ {
447                 id := int32(fastrandn(uint32(gomaxprocs - 1)))
448                 if id >= myID {
449                         id++
450                 }
451                 p := allp[id]
452                 if p.status != _Prunning {
453                         continue
454                 }
455                 if preemptone(p) {
456                         return
457                 }
458         }
459 }
460
461 // findRunnableGCWorker returns a background mark worker for _p_ if it
462 // should be run. This must only be called when gcBlackenEnabled != 0.
463 func (c *gcControllerState) findRunnableGCWorker(_p_ *p) *g {
464         if gcBlackenEnabled == 0 {
465                 throw("gcControllerState.findRunnable: blackening not enabled")
466         }
467
468         if !gcMarkWorkAvailable(_p_) {
469                 // No work to be done right now. This can happen at
470                 // the end of the mark phase when there are still
471                 // assists tapering off. Don't bother running a worker
472                 // now because it'll just return immediately.
473                 return nil
474         }
475
476         // Grab a worker before we commit to running below.
477         node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
478         if node == nil {
479                 // There is at least one worker per P, so normally there are
480                 // enough workers to run on all Ps, if necessary. However, once
481                 // a worker enters gcMarkDone it may park without rejoining the
482                 // pool, thus freeing a P with no corresponding worker.
483                 // gcMarkDone never depends on another worker doing work, so it
484                 // is safe to simply do nothing here.
485                 //
486                 // If gcMarkDone bails out without completing the mark phase,
487                 // it will always do so with queued global work. Thus, that P
488                 // will be immediately eligible to re-run the worker G it was
489                 // just using, ensuring work can complete.
490                 return nil
491         }
492
493         decIfPositive := func(ptr *int64) bool {
494                 for {
495                         v := atomic.Loadint64(ptr)
496                         if v <= 0 {
497                                 return false
498                         }
499
500                         if atomic.Casint64(ptr, v, v-1) {
501                                 return true
502                         }
503                 }
504         }
505
506         if decIfPositive(&c.dedicatedMarkWorkersNeeded) {
507                 // This P is now dedicated to marking until the end of
508                 // the concurrent mark phase.
509                 _p_.gcMarkWorkerMode = gcMarkWorkerDedicatedMode
510         } else if c.fractionalUtilizationGoal == 0 {
511                 // No need for fractional workers.
512                 gcBgMarkWorkerPool.push(&node.node)
513                 return nil
514         } else {
515                 // Is this P behind on the fractional utilization
516                 // goal?
517                 //
518                 // This should be kept in sync with pollFractionalWorkerExit.
519                 delta := nanotime() - gcController.markStartTime
520                 if delta > 0 && float64(_p_.gcFractionalMarkTime)/float64(delta) > c.fractionalUtilizationGoal {
521                         // Nope. No need to run a fractional worker.
522                         gcBgMarkWorkerPool.push(&node.node)
523                         return nil
524                 }
525                 // Run a fractional worker.
526                 _p_.gcMarkWorkerMode = gcMarkWorkerFractionalMode
527         }
528
529         // Run the background mark worker.
530         gp := node.gp.ptr()
531         casgstatus(gp, _Gwaiting, _Grunnable)
532         if trace.enabled {
533                 traceGoUnpark(gp, 0)
534         }
535         return gp
536 }
537
538 // gcSetTriggerRatio sets the trigger ratio and updates everything
539 // derived from it: the absolute trigger, the heap goal, mark pacing,
540 // and sweep pacing.
541 //
542 // This can be called any time. If GC is the in the middle of a
543 // concurrent phase, it will adjust the pacing of that phase.
544 //
545 // This depends on gcPercent, memstats.heap_marked, and
546 // memstats.heap_live. These must be up to date.
547 //
548 // mheap_.lock must be held or the world must be stopped.
549 func gcSetTriggerRatio(triggerRatio float64) {
550         assertWorldStoppedOrLockHeld(&mheap_.lock)
551
552         // Compute the next GC goal, which is when the allocated heap
553         // has grown by GOGC/100 over the heap marked by the last
554         // cycle.
555         goal := ^uint64(0)
556         if gcPercent >= 0 {
557                 goal = memstats.heap_marked + memstats.heap_marked*uint64(gcPercent)/100
558         }
559
560         // Set the trigger ratio, capped to reasonable bounds.
561         if gcPercent >= 0 {
562                 scalingFactor := float64(gcPercent) / 100
563                 // Ensure there's always a little margin so that the
564                 // mutator assist ratio isn't infinity.
565                 maxTriggerRatio := 0.95 * scalingFactor
566                 if triggerRatio > maxTriggerRatio {
567                         triggerRatio = maxTriggerRatio
568                 }
569
570                 // If we let triggerRatio go too low, then if the application
571                 // is allocating very rapidly we might end up in a situation
572                 // where we're allocating black during a nearly always-on GC.
573                 // The result of this is a growing heap and ultimately an
574                 // increase in RSS. By capping us at a point >0, we're essentially
575                 // saying that we're OK using more CPU during the GC to prevent
576                 // this growth in RSS.
577                 //
578                 // The current constant was chosen empirically: given a sufficiently
579                 // fast/scalable allocator with 48 Ps that could drive the trigger ratio
580                 // to <0.05, this constant causes applications to retain the same peak
581                 // RSS compared to not having this allocator.
582                 minTriggerRatio := 0.6 * scalingFactor
583                 if triggerRatio < minTriggerRatio {
584                         triggerRatio = minTriggerRatio
585                 }
586         } else if triggerRatio < 0 {
587                 // gcPercent < 0, so just make sure we're not getting a negative
588                 // triggerRatio. This case isn't expected to happen in practice,
589                 // and doesn't really matter because if gcPercent < 0 then we won't
590                 // ever consume triggerRatio further on in this function, but let's
591                 // just be defensive here; the triggerRatio being negative is almost
592                 // certainly undesirable.
593                 triggerRatio = 0
594         }
595         memstats.triggerRatio = triggerRatio
596
597         // Compute the absolute GC trigger from the trigger ratio.
598         //
599         // We trigger the next GC cycle when the allocated heap has
600         // grown by the trigger ratio over the marked heap size.
601         trigger := ^uint64(0)
602         if gcPercent >= 0 {
603                 trigger = uint64(float64(memstats.heap_marked) * (1 + triggerRatio))
604                 // Don't trigger below the minimum heap size.
605                 minTrigger := heapMinimum
606                 if !isSweepDone() {
607                         // Concurrent sweep happens in the heap growth
608                         // from heap_live to gc_trigger, so ensure
609                         // that concurrent sweep has some heap growth
610                         // in which to perform sweeping before we
611                         // start the next GC cycle.
612                         sweepMin := atomic.Load64(&memstats.heap_live) + sweepMinHeapDistance
613                         if sweepMin > minTrigger {
614                                 minTrigger = sweepMin
615                         }
616                 }
617                 if trigger < minTrigger {
618                         trigger = minTrigger
619                 }
620                 if int64(trigger) < 0 {
621                         print("runtime: next_gc=", memstats.next_gc, " heap_marked=", memstats.heap_marked, " heap_live=", memstats.heap_live, " initialHeapLive=", work.initialHeapLive, "triggerRatio=", triggerRatio, " minTrigger=", minTrigger, "\n")
622                         throw("gc_trigger underflow")
623                 }
624                 if trigger > goal {
625                         // The trigger ratio is always less than GOGC/100, but
626                         // other bounds on the trigger may have raised it.
627                         // Push up the goal, too.
628                         goal = trigger
629                 }
630         }
631
632         // Commit to the trigger and goal.
633         memstats.gc_trigger = trigger
634         atomic.Store64(&memstats.next_gc, goal)
635         if trace.enabled {
636                 traceNextGC()
637         }
638
639         // Update mark pacing.
640         if gcphase != _GCoff {
641                 gcController.revise()
642         }
643
644         // Update sweep pacing.
645         if isSweepDone() {
646                 mheap_.sweepPagesPerByte = 0
647         } else {
648                 // Concurrent sweep needs to sweep all of the in-use
649                 // pages by the time the allocated heap reaches the GC
650                 // trigger. Compute the ratio of in-use pages to sweep
651                 // per byte allocated, accounting for the fact that
652                 // some might already be swept.
653                 heapLiveBasis := atomic.Load64(&memstats.heap_live)
654                 heapDistance := int64(trigger) - int64(heapLiveBasis)
655                 // Add a little margin so rounding errors and
656                 // concurrent sweep are less likely to leave pages
657                 // unswept when GC starts.
658                 heapDistance -= 1024 * 1024
659                 if heapDistance < _PageSize {
660                         // Avoid setting the sweep ratio extremely high
661                         heapDistance = _PageSize
662                 }
663                 pagesSwept := atomic.Load64(&mheap_.pagesSwept)
664                 pagesInUse := atomic.Load64(&mheap_.pagesInUse)
665                 sweepDistancePages := int64(pagesInUse) - int64(pagesSwept)
666                 if sweepDistancePages <= 0 {
667                         mheap_.sweepPagesPerByte = 0
668                 } else {
669                         mheap_.sweepPagesPerByte = float64(sweepDistancePages) / float64(heapDistance)
670                         mheap_.sweepHeapLiveBasis = heapLiveBasis
671                         // Write pagesSweptBasis last, since this
672                         // signals concurrent sweeps to recompute
673                         // their debt.
674                         atomic.Store64(&mheap_.pagesSweptBasis, pagesSwept)
675                 }
676         }
677
678         gcPaceScavenger()
679 }
680
681 // gcEffectiveGrowthRatio returns the current effective heap growth
682 // ratio (GOGC/100) based on heap_marked from the previous GC and
683 // next_gc for the current GC.
684 //
685 // This may differ from gcPercent/100 because of various upper and
686 // lower bounds on gcPercent. For example, if the heap is smaller than
687 // heapMinimum, this can be higher than gcPercent/100.
688 //
689 // mheap_.lock must be held or the world must be stopped.
690 func gcEffectiveGrowthRatio() float64 {
691         assertWorldStoppedOrLockHeld(&mheap_.lock)
692
693         egogc := float64(atomic.Load64(&memstats.next_gc)-memstats.heap_marked) / float64(memstats.heap_marked)
694         if egogc < 0 {
695                 // Shouldn't happen, but just in case.
696                 egogc = 0
697         }
698         return egogc
699 }
700
701 //go:linkname setGCPercent runtime/debug.setGCPercent
702 func setGCPercent(in int32) (out int32) {
703         // Run on the system stack since we grab the heap lock.
704         systemstack(func() {
705                 lock(&mheap_.lock)
706                 out = gcPercent
707                 if in < 0 {
708                         in = -1
709                 }
710                 gcPercent = in
711                 heapMinimum = defaultHeapMinimum * uint64(gcPercent) / 100
712                 // Update pacing in response to gcPercent change.
713                 gcSetTriggerRatio(memstats.triggerRatio)
714                 unlock(&mheap_.lock)
715         })
716
717         // If we just disabled GC, wait for any concurrent GC mark to
718         // finish so we always return with no GC running.
719         if in < 0 {
720                 gcWaitOnMark(atomic.Load(&work.cycles))
721         }
722
723         return out
724 }
725
726 func readGOGC() int32 {
727         p := gogetenv("GOGC")
728         if p == "off" {
729                 return -1
730         }
731         if n, ok := atoi32(p); ok {
732                 return n
733         }
734         return 100
735 }