]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/mgcpacer.go
runtime: eliminate rendundant loads gcPercent
[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         "internal/goexperiment"
10         "runtime/internal/atomic"
11         "unsafe"
12 )
13
14 const (
15         // gcGoalUtilization is the goal CPU utilization for
16         // marking as a fraction of GOMAXPROCS.
17         gcGoalUtilization = goexperiment.PacerRedesignInt*gcBackgroundUtilization +
18                 (1-goexperiment.PacerRedesignInt)*(gcBackgroundUtilization+0.05)
19
20         // gcBackgroundUtilization is the fixed CPU utilization for background
21         // marking. It must be <= gcGoalUtilization. The difference between
22         // gcGoalUtilization and gcBackgroundUtilization will be made up by
23         // mark assists. The scheduler will aim to use within 50% of this
24         // goal.
25         //
26         // Setting this to < gcGoalUtilization avoids saturating the trigger
27         // feedback controller when there are no assists, which allows it to
28         // better control CPU and heap growth. However, the larger the gap,
29         // the more mutator assists are expected to happen, which impact
30         // mutator latency.
31         //
32         // If goexperiment.PacerRedesign, the trigger feedback controller
33         // is replaced with an estimate of the mark/cons ratio that doesn't
34         // have the same saturation issues, so this is set equal to
35         // gcGoalUtilization.
36         gcBackgroundUtilization = 0.25
37
38         // gcCreditSlack is the amount of scan work credit that can
39         // accumulate locally before updating gcController.heapScanWork and,
40         // optionally, gcController.bgScanCredit. Lower values give a more
41         // accurate assist ratio and make it more likely that assists will
42         // successfully steal background credit. Higher values reduce memory
43         // contention.
44         gcCreditSlack = 2000
45
46         // gcAssistTimeSlack is the nanoseconds of mutator assist time that
47         // can accumulate on a P before updating gcController.assistTime.
48         gcAssistTimeSlack = 5000
49
50         // gcOverAssistWork determines how many extra units of scan work a GC
51         // assist does when an assist happens. This amortizes the cost of an
52         // assist by pre-paying for this many bytes of future allocations.
53         gcOverAssistWork = 64 << 10
54
55         // defaultHeapMinimum is the value of heapMinimum for GOGC==100.
56         defaultHeapMinimum = goexperiment.PacerRedesignInt*(512<<10) +
57                 (1-goexperiment.PacerRedesignInt)*(4<<20)
58
59         // scannableStackSizeSlack is the bytes of stack space allocated or freed
60         // that can accumulate on a P before updating gcController.stackSize.
61         scannableStackSizeSlack = 8 << 10
62 )
63
64 func init() {
65         if offset := unsafe.Offsetof(gcController.heapLive); offset%8 != 0 {
66                 println(offset)
67                 throw("gcController.heapLive not aligned to 8 bytes")
68         }
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 gcController.trigger
76 // trigger based on the heap growth and GC CPU utilization each cycle.
77 // This algorithm optimizes for heap growth to match GOGC and for CPU
78 // utilization between assist and background marking to be 25% of
79 // GOMAXPROCS. The high-level design of this algorithm is documented
80 // at https://golang.org/s/go15gcpacing.
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
88         // Initialized from GOGC. GOGC=off means no GC.
89         gcPercent atomic.Int32
90
91         _ uint32 // padding so following 64-bit values are 8-byte aligned
92
93         // heapMinimum is the minimum heap size at which to trigger GC.
94         // For small heaps, this overrides the usual GOGC*live set rule.
95         //
96         // When there is a very small live set but a lot of allocation, simply
97         // collecting when the heap reaches GOGC*live results in many GC
98         // cycles and high total per-GC overhead. This minimum amortizes this
99         // per-GC overhead while keeping the heap reasonably small.
100         //
101         // During initialization this is set to 4MB*GOGC/100. In the case of
102         // GOGC==0, this will set heapMinimum to 0, resulting in constant
103         // collection even when the heap size is small, which is useful for
104         // debugging.
105         heapMinimum uint64
106
107         // triggerRatio is the heap growth ratio that triggers marking.
108         //
109         // E.g., if this is 0.6, then GC should start when the live
110         // heap has reached 1.6 times the heap size marked by the
111         // previous cycle. This should be ≤ GOGC/100 so the trigger
112         // heap size is less than the goal heap size. This is set
113         // during mark termination for the next cycle's trigger.
114         //
115         // Protected by mheap_.lock or a STW.
116         //
117         // Used if !goexperiment.PacerRedesign.
118         triggerRatio float64
119
120         // trigger is the heap size that triggers marking.
121         //
122         // When heapLive ≥ trigger, the mark phase will start.
123         // This is also the heap size by which proportional sweeping
124         // must be complete.
125         //
126         // This is computed from triggerRatio during mark termination
127         // for the next cycle's trigger.
128         //
129         // Protected by mheap_.lock or a STW.
130         trigger uint64
131
132         // consMark is the estimated per-CPU consMark ratio for the application.
133         //
134         // It represents the ratio between the application's allocation
135         // rate, as bytes allocated per CPU-time, and the GC's scan rate,
136         // as bytes scanned per CPU-time.
137         // The units of this ratio are (B / cpu-ns) / (B / cpu-ns).
138         //
139         // At a high level, this value is computed as the bytes of memory
140         // allocated (cons) per unit of scan work completed (mark) in a GC
141         // cycle, divided by the CPU time spent on each activity.
142         //
143         // Updated at the end of each GC cycle, in endCycle.
144         //
145         // For goexperiment.PacerRedesign.
146         consMark float64
147
148         // consMarkController holds the state for the mark-cons ratio
149         // estimation over time.
150         //
151         // Its purpose is to smooth out noisiness in the computation of
152         // consMark; see consMark for details.
153         //
154         // For goexperiment.PacerRedesign.
155         consMarkController piController
156
157         // heapGoal is the goal heapLive for when next GC ends.
158         // Set to ^uint64(0) if disabled.
159         //
160         // Read and written atomically, unless the world is stopped.
161         heapGoal uint64
162
163         // lastHeapGoal is the value of heapGoal for the previous GC.
164         // Note that this is distinct from the last value heapGoal had,
165         // because it could change if e.g. gcPercent changes.
166         //
167         // Read and written with the world stopped or with mheap_.lock held.
168         lastHeapGoal uint64
169
170         // heapLive is the number of bytes considered live by the GC.
171         // That is: retained by the most recent GC plus allocated
172         // since then. heapLive ≤ memstats.heapAlloc, since heapAlloc includes
173         // unmarked objects that have not yet been swept (and hence goes up as we
174         // allocate and down as we sweep) while heapLive excludes these
175         // objects (and hence only goes up between GCs).
176         //
177         // This is updated atomically without locking. To reduce
178         // contention, this is updated only when obtaining a span from
179         // an mcentral and at this point it counts all of the
180         // unallocated slots in that span (which will be allocated
181         // before that mcache obtains another span from that
182         // mcentral). Hence, it slightly overestimates the "true" live
183         // heap size. It's better to overestimate than to
184         // underestimate because 1) this triggers the GC earlier than
185         // necessary rather than potentially too late and 2) this
186         // leads to a conservative GC rate rather than a GC rate that
187         // is potentially too low.
188         //
189         // Reads should likewise be atomic (or during STW).
190         //
191         // Whenever this is updated, call traceHeapAlloc() and
192         // this gcControllerState's revise() method.
193         heapLive uint64
194
195         // heapScan is the number of bytes of "scannable" heap. This
196         // is the live heap (as counted by heapLive), but omitting
197         // no-scan objects and no-scan tails of objects.
198         //
199         // For !goexperiment.PacerRedesign: Whenever this is updated,
200         // call this gcControllerState's revise() method. It is read
201         // and written atomically or with the world stopped.
202         //
203         // For goexperiment.PacerRedesign: This value is fixed at the
204         // start of a GC cycle, so during a GC cycle it is safe to
205         // read without atomics, and it represents the maximum scannable
206         // heap.
207         heapScan uint64
208
209         // lastHeapScan is the number of bytes of heap that were scanned
210         // last GC cycle. It is the same as heapMarked, but only
211         // includes the "scannable" parts of objects.
212         //
213         // Updated when the world is stopped.
214         lastHeapScan uint64
215
216         // stackScan is a snapshot of scannableStackSize taken at each GC
217         // STW pause and is used in pacing decisions.
218         //
219         // Updated only while the world is stopped.
220         stackScan uint64
221
222         // scannableStackSize is the amount of allocated goroutine stack space in
223         // use by goroutines.
224         //
225         // This number tracks allocated goroutine stack space rather than used
226         // goroutine stack space (i.e. what is actually scanned) because used
227         // goroutine stack space is much harder to measure cheaply. By using
228         // allocated space, we make an overestimate; this is OK, it's better
229         // to conservatively overcount than undercount.
230         //
231         // Read and updated atomically.
232         scannableStackSize uint64
233
234         // globalsScan is the total amount of global variable space
235         // that is scannable.
236         //
237         // Read and updated atomically.
238         globalsScan uint64
239
240         // heapMarked is the number of bytes marked by the previous
241         // GC. After mark termination, heapLive == heapMarked, but
242         // unlike heapLive, heapMarked does not change until the
243         // next mark termination.
244         heapMarked uint64
245
246         // heapScanWork is the total heap scan work performed this cycle.
247         // stackScanWork is the total stack scan work performed this cycle.
248         // globalsScanWork is the total globals scan work performed this cycle.
249         //
250         // These are updated atomically during the cycle. Updates occur in
251         // bounded batches, since they are both written and read
252         // throughout the cycle. At the end of the cycle, heapScanWork is how
253         // much of the retained heap is scannable.
254         //
255         // Currently these are measured in bytes. For most uses, this is an
256         // opaque unit of work, but for estimation the definition is important.
257         //
258         // Note that stackScanWork includes all allocated space, not just the
259         // size of the stack itself, mirroring stackSize.
260         //
261         // For !goexperiment.PacerRedesign, stackScanWork and globalsScanWork
262         // are always zero.
263         heapScanWork    atomic.Int64
264         stackScanWork   atomic.Int64
265         globalsScanWork atomic.Int64
266
267         // bgScanCredit is the scan work credit accumulated by the
268         // concurrent background scan. This credit is accumulated by
269         // the background scan and stolen by mutator assists. This is
270         // updated atomically. Updates occur in bounded batches, since
271         // it is both written and read throughout the cycle.
272         bgScanCredit int64
273
274         // assistTime is the nanoseconds spent in mutator assists
275         // during this cycle. This is updated atomically. Updates
276         // occur in bounded batches, since it is both written and read
277         // throughout the cycle.
278         assistTime int64
279
280         // dedicatedMarkTime is the nanoseconds spent in dedicated
281         // mark workers during this cycle. This is updated atomically
282         // at the end of the concurrent mark phase.
283         dedicatedMarkTime int64
284
285         // fractionalMarkTime is the nanoseconds spent in the
286         // fractional mark worker during this cycle. This is updated
287         // atomically throughout the cycle and will be up-to-date if
288         // the fractional mark worker is not currently running.
289         fractionalMarkTime int64
290
291         // idleMarkTime is the nanoseconds spent in idle marking
292         // during this cycle. This is updated atomically throughout
293         // the cycle.
294         idleMarkTime int64
295
296         // markStartTime is the absolute start time in nanoseconds
297         // that assists and background mark workers started.
298         markStartTime int64
299
300         // dedicatedMarkWorkersNeeded is the number of dedicated mark
301         // workers that need to be started. This is computed at the
302         // beginning of each cycle and decremented atomically as
303         // dedicated mark workers get started.
304         dedicatedMarkWorkersNeeded int64
305
306         // assistWorkPerByte is the ratio of scan work to allocated
307         // bytes that should be performed by mutator assists. This is
308         // computed at the beginning of each cycle and updated every
309         // time heapScan is updated.
310         assistWorkPerByte atomic.Float64
311
312         // assistBytesPerWork is 1/assistWorkPerByte.
313         //
314         // Note that because this is read and written independently
315         // from assistWorkPerByte users may notice a skew between
316         // the two values, and such a state should be safe.
317         assistBytesPerWork atomic.Float64
318
319         // fractionalUtilizationGoal is the fraction of wall clock
320         // time that should be spent in the fractional mark worker on
321         // each P that isn't running a dedicated worker.
322         //
323         // For example, if the utilization goal is 25% and there are
324         // no dedicated workers, this will be 0.25. If the goal is
325         // 25%, there is one dedicated worker, and GOMAXPROCS is 5,
326         // this will be 0.05 to make up the missing 5%.
327         //
328         // If this is zero, no fractional workers are needed.
329         fractionalUtilizationGoal float64
330
331         // test indicates that this is a test-only copy of gcControllerState.
332         test bool
333
334         _ cpu.CacheLinePad
335 }
336
337 func (c *gcControllerState) init(gcPercent int32) {
338         c.heapMinimum = defaultHeapMinimum
339
340         if goexperiment.PacerRedesign {
341                 c.consMarkController = piController{
342                         // Tuned first via the Ziegler-Nichols process in simulation,
343                         // then the integral time was manually tuned against real-world
344                         // applications to deal with noisiness in the measured cons/mark
345                         // ratio.
346                         kp: 0.9,
347                         ti: 4.0,
348
349                         // Set a high reset time in GC cycles.
350                         // This is inversely proportional to the rate at which we
351                         // accumulate error from clipping. By making this very high
352                         // we make the accumulation slow. In general, clipping is
353                         // OK in our situation, hence the choice.
354                         //
355                         // Tune this if we get unintended effects from clipping for
356                         // a long time.
357                         tt:  1000,
358                         min: -1000,
359                         max: 1000,
360                 }
361         } else {
362                 // Set a reasonable initial GC trigger.
363                 c.triggerRatio = 7 / 8.0
364
365                 // Fake a heapMarked value so it looks like a trigger at
366                 // heapMinimum is the appropriate growth from heapMarked.
367                 // This will go into computing the initial GC goal.
368                 c.heapMarked = uint64(float64(c.heapMinimum) / (1 + c.triggerRatio))
369         }
370
371         // This will also compute and set the GC trigger and goal.
372         c.setGCPercent(gcPercent)
373 }
374
375 // startCycle resets the GC controller's state and computes estimates
376 // for a new GC cycle. The caller must hold worldsema and the world
377 // must be stopped.
378 func (c *gcControllerState) startCycle(markStartTime int64, procs int) {
379         c.heapScanWork.Store(0)
380         c.stackScanWork.Store(0)
381         c.globalsScanWork.Store(0)
382         c.bgScanCredit = 0
383         c.assistTime = 0
384         c.dedicatedMarkTime = 0
385         c.fractionalMarkTime = 0
386         c.idleMarkTime = 0
387         c.markStartTime = markStartTime
388         c.stackScan = atomic.Load64(&c.scannableStackSize)
389
390         // Ensure that the heap goal is at least a little larger than
391         // the current live heap size. This may not be the case if GC
392         // start is delayed or if the allocation that pushed gcController.heapLive
393         // over trigger is large or if the trigger is really close to
394         // GOGC. Assist is proportional to this distance, so enforce a
395         // minimum distance, even if it means going over the GOGC goal
396         // by a tiny bit.
397         if goexperiment.PacerRedesign {
398                 if c.heapGoal < c.heapLive+64<<10 {
399                         c.heapGoal = c.heapLive + 64<<10
400                 }
401         } else {
402                 if c.heapGoal < c.heapLive+1<<20 {
403                         c.heapGoal = c.heapLive + 1<<20
404                 }
405         }
406
407         // Compute the background mark utilization goal. In general,
408         // this may not come out exactly. We round the number of
409         // dedicated workers so that the utilization is closest to
410         // 25%. For small GOMAXPROCS, this would introduce too much
411         // error, so we add fractional workers in that case.
412         totalUtilizationGoal := float64(procs) * gcBackgroundUtilization
413         c.dedicatedMarkWorkersNeeded = int64(totalUtilizationGoal + 0.5)
414         utilError := float64(c.dedicatedMarkWorkersNeeded)/totalUtilizationGoal - 1
415         const maxUtilError = 0.3
416         if utilError < -maxUtilError || utilError > maxUtilError {
417                 // Rounding put us more than 30% off our goal. With
418                 // gcBackgroundUtilization of 25%, this happens for
419                 // GOMAXPROCS<=3 or GOMAXPROCS=6. Enable fractional
420                 // workers to compensate.
421                 if float64(c.dedicatedMarkWorkersNeeded) > totalUtilizationGoal {
422                         // Too many dedicated workers.
423                         c.dedicatedMarkWorkersNeeded--
424                 }
425                 c.fractionalUtilizationGoal = (totalUtilizationGoal - float64(c.dedicatedMarkWorkersNeeded)) / float64(procs)
426         } else {
427                 c.fractionalUtilizationGoal = 0
428         }
429
430         // In STW mode, we just want dedicated workers.
431         if debug.gcstoptheworld > 0 {
432                 c.dedicatedMarkWorkersNeeded = int64(procs)
433                 c.fractionalUtilizationGoal = 0
434         }
435
436         // Clear per-P state
437         for _, p := range allp {
438                 p.gcAssistTime = 0
439                 p.gcFractionalMarkTime = 0
440         }
441
442         // Compute initial values for controls that are updated
443         // throughout the cycle.
444         c.revise()
445
446         if debug.gcpacertrace > 0 {
447                 assistRatio := c.assistWorkPerByte.Load()
448                 print("pacer: assist ratio=", assistRatio,
449                         " (scan ", gcController.heapScan>>20, " MB in ",
450                         work.initialHeapLive>>20, "->",
451                         c.heapGoal>>20, " MB)",
452                         " workers=", c.dedicatedMarkWorkersNeeded,
453                         "+", c.fractionalUtilizationGoal, "\n")
454         }
455 }
456
457 // revise updates the assist ratio during the GC cycle to account for
458 // improved estimates. This should be called whenever gcController.heapScan,
459 // gcController.heapLive, or gcController.heapGoal is updated. It is safe to
460 // call concurrently, but it may race with other calls to revise.
461 //
462 // The result of this race is that the two assist ratio values may not line
463 // up or may be stale. In practice this is OK because the assist ratio
464 // moves slowly throughout a GC cycle, and the assist ratio is a best-effort
465 // heuristic anyway. Furthermore, no part of the heuristic depends on
466 // the two assist ratio values being exact reciprocals of one another, since
467 // the two values are used to convert values from different sources.
468 //
469 // The worst case result of this raciness is that we may miss a larger shift
470 // in the ratio (say, if we decide to pace more aggressively against the
471 // hard heap goal) but even this "hard goal" is best-effort (see #40460).
472 // The dedicated GC should ensure we don't exceed the hard goal by too much
473 // in the rare case we do exceed it.
474 //
475 // It should only be called when gcBlackenEnabled != 0 (because this
476 // is when assists are enabled and the necessary statistics are
477 // available).
478 func (c *gcControllerState) revise() {
479         gcPercent := c.gcPercent.Load()
480         if gcPercent < 0 {
481                 // If GC is disabled but we're running a forced GC,
482                 // act like GOGC is huge for the below calculations.
483                 gcPercent = 100000
484         }
485         live := atomic.Load64(&c.heapLive)
486         scan := atomic.Load64(&c.heapScan)
487         work := c.heapScanWork.Load() + c.stackScanWork.Load() + c.globalsScanWork.Load()
488
489         // Assume we're under the soft goal. Pace GC to complete at
490         // heapGoal assuming the heap is in steady-state.
491         heapGoal := int64(atomic.Load64(&c.heapGoal))
492
493         var scanWorkExpected int64
494         if goexperiment.PacerRedesign {
495                 // The expected scan work is computed as the amount of bytes scanned last
496                 // GC cycle, plus our estimate of stacks and globals work for this cycle.
497                 scanWorkExpected = int64(c.lastHeapScan + c.stackScan + c.globalsScan)
498
499                 // maxScanWork is a worst-case estimate of the amount of scan work that
500                 // needs to be performed in this GC cycle. Specifically, it represents
501                 // the case where *all* scannable memory turns out to be live.
502                 maxScanWork := int64(scan + c.stackScan + c.globalsScan)
503                 if work > scanWorkExpected {
504                         // We've already done more scan work than expected. Because our expectation
505                         // is based on a steady-state scannable heap size, we assume this means our
506                         // heap is growing. Compute a new heap goal that takes our existing runway
507                         // computed for scanWorkExpected and extrapolates it to maxScanWork, the worst-case
508                         // scan work. This keeps our assist ratio stable if the heap continues to grow.
509                         //
510                         // The effect of this mechanism is that assists stay flat in the face of heap
511                         // growths. It's OK to use more memory this cycle to scan all the live heap,
512                         // because the next GC cycle is inevitably going to use *at least* that much
513                         // memory anyway.
514                         extHeapGoal := int64(float64(heapGoal-int64(c.trigger))/float64(scanWorkExpected)*float64(maxScanWork)) + int64(c.trigger)
515                         scanWorkExpected = maxScanWork
516
517                         // hardGoal is a hard limit on the amount that we're willing to push back the
518                         // heap goal, and that's twice the heap goal (i.e. if GOGC=100 and the heap and/or
519                         // stacks and/or globals grow to twice their size, this limits the current GC cycle's
520                         // growth to 4x the original live heap's size).
521                         //
522                         // This maintains the invariant that we use no more memory than the next GC cycle
523                         // will anyway.
524                         hardGoal := int64((1.0 + float64(gcPercent)/100.0) * float64(heapGoal))
525                         if extHeapGoal > hardGoal {
526                                 extHeapGoal = hardGoal
527                         }
528                         heapGoal = extHeapGoal
529                 }
530                 if int64(live) > heapGoal {
531                         // We're already past our heap goal, even the extrapolated one.
532                         // Leave ourselves some extra runway, so in the worst case we
533                         // finish by that point.
534                         const maxOvershoot = 1.1
535                         heapGoal = int64(float64(heapGoal) * maxOvershoot)
536
537                         // Compute the upper bound on the scan work remaining.
538                         scanWorkExpected = maxScanWork
539                 }
540         } else {
541                 // Compute the expected scan work remaining.
542                 //
543                 // This is estimated based on the expected
544                 // steady-state scannable heap. For example, with
545                 // GOGC=100, only half of the scannable heap is
546                 // expected to be live, so that's what we target.
547                 //
548                 // (This is a float calculation to avoid overflowing on
549                 // 100*heapScan.)
550                 scanWorkExpected = int64(float64(scan) * 100 / float64(100+gcPercent))
551                 if int64(live) > heapGoal || work > scanWorkExpected {
552                         // We're past the soft goal, or we've already done more scan
553                         // work than we expected. Pace GC so that in the worst case it
554                         // will complete by the hard goal.
555                         const maxOvershoot = 1.1
556                         heapGoal = int64(float64(heapGoal) * maxOvershoot)
557
558                         // Compute the upper bound on the scan work remaining.
559                         scanWorkExpected = int64(scan)
560                 }
561         }
562
563         // Compute the remaining scan work estimate.
564         //
565         // Note that we currently count allocations during GC as both
566         // scannable heap (heapScan) and scan work completed
567         // (scanWork), so allocation will change this difference
568         // slowly in the soft regime and not at all in the hard
569         // regime.
570         scanWorkRemaining := scanWorkExpected - work
571         if scanWorkRemaining < 1000 {
572                 // We set a somewhat arbitrary lower bound on
573                 // remaining scan work since if we aim a little high,
574                 // we can miss by a little.
575                 //
576                 // We *do* need to enforce that this is at least 1,
577                 // since marking is racy and double-scanning objects
578                 // may legitimately make the remaining scan work
579                 // negative, even in the hard goal regime.
580                 scanWorkRemaining = 1000
581         }
582
583         // Compute the heap distance remaining.
584         heapRemaining := heapGoal - int64(live)
585         if heapRemaining <= 0 {
586                 // This shouldn't happen, but if it does, avoid
587                 // dividing by zero or setting the assist negative.
588                 heapRemaining = 1
589         }
590
591         // Compute the mutator assist ratio so by the time the mutator
592         // allocates the remaining heap bytes up to heapGoal, it will
593         // have done (or stolen) the remaining amount of scan work.
594         // Note that the assist ratio values are updated atomically
595         // but not together. This means there may be some degree of
596         // skew between the two values. This is generally OK as the
597         // values shift relatively slowly over the course of a GC
598         // cycle.
599         assistWorkPerByte := float64(scanWorkRemaining) / float64(heapRemaining)
600         assistBytesPerWork := float64(heapRemaining) / float64(scanWorkRemaining)
601         c.assistWorkPerByte.Store(assistWorkPerByte)
602         c.assistBytesPerWork.Store(assistBytesPerWork)
603 }
604
605 // endCycle computes the trigger ratio (!goexperiment.PacerRedesign)
606 // or the consMark estimate (goexperiment.PacerRedesign) for the next cycle.
607 // Returns the trigger ratio if application, or 0 (goexperiment.PacerRedesign).
608 // userForced indicates whether the current GC cycle was forced
609 // by the application.
610 func (c *gcControllerState) endCycle(now int64, procs int, userForced bool) float64 {
611         // Record last heap goal for the scavenger.
612         // We'll be updating the heap goal soon.
613         gcController.lastHeapGoal = gcController.heapGoal
614
615         // Compute the duration of time for which assists were turned on.
616         assistDuration := now - c.markStartTime
617
618         // Assume background mark hit its utilization goal.
619         utilization := gcBackgroundUtilization
620         // Add assist utilization; avoid divide by zero.
621         if assistDuration > 0 {
622                 utilization += float64(c.assistTime) / float64(assistDuration*int64(procs))
623         }
624
625         if goexperiment.PacerRedesign {
626                 if c.heapLive <= c.trigger {
627                         // Shouldn't happen, but let's be very safe about this in case the
628                         // GC is somehow extremely short.
629                         //
630                         // In this case though, the only reasonable value for c.heapLive-c.trigger
631                         // would be 0, which isn't really all that useful, i.e. the GC was so short
632                         // that it didn't matter.
633                         //
634                         // Ignore this case and don't update anything.
635                         return 0
636                 }
637                 idleUtilization := 0.0
638                 if assistDuration > 0 {
639                         idleUtilization = float64(c.idleMarkTime) / float64(assistDuration*int64(procs))
640                 }
641                 // Determine the cons/mark ratio.
642                 //
643                 // The units we want for the numerator and denominator are both B / cpu-ns.
644                 // We get this by taking the bytes allocated or scanned, and divide by the amount of
645                 // CPU time it took for those operations. For allocations, that CPU time is
646                 //
647                 //    assistDuration * procs * (1 - utilization)
648                 //
649                 // Where utilization includes just background GC workers and assists. It does *not*
650                 // include idle GC work time, because in theory the mutator is free to take that at
651                 // any point.
652                 //
653                 // For scanning, that CPU time is
654                 //
655                 //    assistDuration * procs * (utilization + idleUtilization)
656                 //
657                 // In this case, we *include* idle utilization, because that is additional CPU time that the
658                 // the GC had available to it.
659                 //
660                 // In effect, idle GC time is sort of double-counted here, but it's very weird compared
661                 // to other kinds of GC work, because of how fluid it is. Namely, because the mutator is
662                 // *always* free to take it.
663                 //
664                 // So this calculation is really:
665                 //     (heapLive-trigger) / (assistDuration * procs * (1-utilization)) /
666                 //         (scanWork) / (assistDuration * procs * (utilization+idleUtilization)
667                 //
668                 // Note that because we only care about the ratio, assistDuration and procs cancel out.
669                 scanWork := c.heapScanWork.Load() + c.stackScanWork.Load() + c.globalsScanWork.Load()
670                 currentConsMark := (float64(c.heapLive-c.trigger) * (utilization + idleUtilization)) /
671                         (float64(scanWork) * (1 - utilization))
672
673                 // Update cons/mark controller.
674                 // Period for this is 1 GC cycle.
675                 oldConsMark := c.consMark
676                 c.consMark = c.consMarkController.next(c.consMark, currentConsMark, 1.0)
677
678                 if debug.gcpacertrace > 0 {
679                         printlock()
680                         print("pacer: ", int(utilization*100), "% CPU (", int(gcGoalUtilization*100), " exp.) for ")
681                         print(c.heapScanWork.Load(), "+", c.stackScanWork.Load(), "+", c.globalsScanWork.Load(), " B work (", c.lastHeapScan+c.stackScan+c.globalsScan, " B exp.) ")
682                         print("in ", c.trigger, " B -> ", c.heapLive, " B (∆goal ", int64(c.heapLive)-int64(c.heapGoal), ", cons/mark ", oldConsMark, ")")
683                         println()
684                         printunlock()
685                 }
686                 return 0
687         }
688
689         // !goexperiment.PacerRedesign below.
690
691         if userForced {
692                 // Forced GC means this cycle didn't start at the
693                 // trigger, so where it finished isn't good
694                 // information about how to adjust the trigger.
695                 // Just leave it where it is.
696                 return c.triggerRatio
697         }
698
699         // Proportional response gain for the trigger controller. Must
700         // be in [0, 1]. Lower values smooth out transient effects but
701         // take longer to respond to phase changes. Higher values
702         // react to phase changes quickly, but are more affected by
703         // transient changes. Values near 1 may be unstable.
704         const triggerGain = 0.5
705
706         // Compute next cycle trigger ratio. First, this computes the
707         // "error" for this cycle; that is, how far off the trigger
708         // was from what it should have been, accounting for both heap
709         // growth and GC CPU utilization. We compute the actual heap
710         // growth during this cycle and scale that by how far off from
711         // the goal CPU utilization we were (to estimate the heap
712         // growth if we had the desired CPU utilization). The
713         // difference between this estimate and the GOGC-based goal
714         // heap growth is the error.
715         goalGrowthRatio := c.effectiveGrowthRatio()
716         actualGrowthRatio := float64(c.heapLive)/float64(c.heapMarked) - 1
717         triggerError := goalGrowthRatio - c.triggerRatio - utilization/gcGoalUtilization*(actualGrowthRatio-c.triggerRatio)
718
719         // Finally, we adjust the trigger for next time by this error,
720         // damped by the proportional gain.
721         triggerRatio := c.triggerRatio + triggerGain*triggerError
722
723         if debug.gcpacertrace > 0 {
724                 // Print controller state in terms of the design
725                 // document.
726                 H_m_prev := c.heapMarked
727                 h_t := c.triggerRatio
728                 H_T := c.trigger
729                 h_a := actualGrowthRatio
730                 H_a := c.heapLive
731                 h_g := goalGrowthRatio
732                 H_g := int64(float64(H_m_prev) * (1 + h_g))
733                 u_a := utilization
734                 u_g := gcGoalUtilization
735                 W_a := c.heapScanWork.Load()
736                 print("pacer: H_m_prev=", H_m_prev,
737                         " h_t=", h_t, " H_T=", H_T,
738                         " h_a=", h_a, " H_a=", H_a,
739                         " h_g=", h_g, " H_g=", H_g,
740                         " u_a=", u_a, " u_g=", u_g,
741                         " W_a=", W_a,
742                         " goalΔ=", goalGrowthRatio-h_t,
743                         " actualΔ=", h_a-h_t,
744                         " u_a/u_g=", u_a/u_g,
745                         "\n")
746         }
747
748         return triggerRatio
749 }
750
751 // enlistWorker encourages another dedicated mark worker to start on
752 // another P if there are spare worker slots. It is used by putfull
753 // when more work is made available.
754 //
755 //go:nowritebarrier
756 func (c *gcControllerState) enlistWorker() {
757         // If there are idle Ps, wake one so it will run an idle worker.
758         // NOTE: This is suspected of causing deadlocks. See golang.org/issue/19112.
759         //
760         //      if atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 {
761         //              wakep()
762         //              return
763         //      }
764
765         // There are no idle Ps. If we need more dedicated workers,
766         // try to preempt a running P so it will switch to a worker.
767         if c.dedicatedMarkWorkersNeeded <= 0 {
768                 return
769         }
770         // Pick a random other P to preempt.
771         if gomaxprocs <= 1 {
772                 return
773         }
774         gp := getg()
775         if gp == nil || gp.m == nil || gp.m.p == 0 {
776                 return
777         }
778         myID := gp.m.p.ptr().id
779         for tries := 0; tries < 5; tries++ {
780                 id := int32(fastrandn(uint32(gomaxprocs - 1)))
781                 if id >= myID {
782                         id++
783                 }
784                 p := allp[id]
785                 if p.status != _Prunning {
786                         continue
787                 }
788                 if preemptone(p) {
789                         return
790                 }
791         }
792 }
793
794 // findRunnableGCWorker returns a background mark worker for _p_ if it
795 // should be run. This must only be called when gcBlackenEnabled != 0.
796 func (c *gcControllerState) findRunnableGCWorker(_p_ *p) *g {
797         if gcBlackenEnabled == 0 {
798                 throw("gcControllerState.findRunnable: blackening not enabled")
799         }
800
801         if !gcMarkWorkAvailable(_p_) {
802                 // No work to be done right now. This can happen at
803                 // the end of the mark phase when there are still
804                 // assists tapering off. Don't bother running a worker
805                 // now because it'll just return immediately.
806                 return nil
807         }
808
809         // Grab a worker before we commit to running below.
810         node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
811         if node == nil {
812                 // There is at least one worker per P, so normally there are
813                 // enough workers to run on all Ps, if necessary. However, once
814                 // a worker enters gcMarkDone it may park without rejoining the
815                 // pool, thus freeing a P with no corresponding worker.
816                 // gcMarkDone never depends on another worker doing work, so it
817                 // is safe to simply do nothing here.
818                 //
819                 // If gcMarkDone bails out without completing the mark phase,
820                 // it will always do so with queued global work. Thus, that P
821                 // will be immediately eligible to re-run the worker G it was
822                 // just using, ensuring work can complete.
823                 return nil
824         }
825
826         decIfPositive := func(ptr *int64) bool {
827                 for {
828                         v := atomic.Loadint64(ptr)
829                         if v <= 0 {
830                                 return false
831                         }
832
833                         if atomic.Casint64(ptr, v, v-1) {
834                                 return true
835                         }
836                 }
837         }
838
839         if decIfPositive(&c.dedicatedMarkWorkersNeeded) {
840                 // This P is now dedicated to marking until the end of
841                 // the concurrent mark phase.
842                 _p_.gcMarkWorkerMode = gcMarkWorkerDedicatedMode
843         } else if c.fractionalUtilizationGoal == 0 {
844                 // No need for fractional workers.
845                 gcBgMarkWorkerPool.push(&node.node)
846                 return nil
847         } else {
848                 // Is this P behind on the fractional utilization
849                 // goal?
850                 //
851                 // This should be kept in sync with pollFractionalWorkerExit.
852                 delta := nanotime() - c.markStartTime
853                 if delta > 0 && float64(_p_.gcFractionalMarkTime)/float64(delta) > c.fractionalUtilizationGoal {
854                         // Nope. No need to run a fractional worker.
855                         gcBgMarkWorkerPool.push(&node.node)
856                         return nil
857                 }
858                 // Run a fractional worker.
859                 _p_.gcMarkWorkerMode = gcMarkWorkerFractionalMode
860         }
861
862         // Run the background mark worker.
863         gp := node.gp.ptr()
864         casgstatus(gp, _Gwaiting, _Grunnable)
865         if trace.enabled {
866                 traceGoUnpark(gp, 0)
867         }
868         return gp
869 }
870
871 // resetLive sets up the controller state for the next mark phase after the end
872 // of the previous one. Must be called after endCycle and before commit, before
873 // the world is started.
874 //
875 // The world must be stopped.
876 func (c *gcControllerState) resetLive(bytesMarked uint64) {
877         c.heapMarked = bytesMarked
878         c.heapLive = bytesMarked
879         c.heapScan = uint64(c.heapScanWork.Load())
880         c.lastHeapScan = uint64(c.heapScanWork.Load())
881
882         // heapLive was updated, so emit a trace event.
883         if trace.enabled {
884                 traceHeapAlloc()
885         }
886 }
887
888 // logWorkTime updates mark work accounting in the controller by a duration of
889 // work in nanoseconds.
890 //
891 // Safe to execute at any time.
892 func (c *gcControllerState) logWorkTime(mode gcMarkWorkerMode, duration int64) {
893         switch mode {
894         case gcMarkWorkerDedicatedMode:
895                 atomic.Xaddint64(&c.dedicatedMarkTime, duration)
896                 atomic.Xaddint64(&c.dedicatedMarkWorkersNeeded, 1)
897         case gcMarkWorkerFractionalMode:
898                 atomic.Xaddint64(&c.fractionalMarkTime, duration)
899         case gcMarkWorkerIdleMode:
900                 atomic.Xaddint64(&c.idleMarkTime, duration)
901         default:
902                 throw("logWorkTime: unknown mark worker mode")
903         }
904 }
905
906 func (c *gcControllerState) update(dHeapLive, dHeapScan int64) {
907         if dHeapLive != 0 {
908                 atomic.Xadd64(&gcController.heapLive, dHeapLive)
909                 if trace.enabled {
910                         // gcController.heapLive changed.
911                         traceHeapAlloc()
912                 }
913         }
914         // Only update heapScan in the new pacer redesign if we're not
915         // currently in a GC.
916         if !goexperiment.PacerRedesign || gcBlackenEnabled == 0 {
917                 if dHeapScan != 0 {
918                         atomic.Xadd64(&gcController.heapScan, dHeapScan)
919                 }
920         }
921         if gcBlackenEnabled != 0 {
922                 // gcController.heapLive and heapScan changed.
923                 c.revise()
924         }
925 }
926
927 func (c *gcControllerState) addScannableStack(pp *p, amount int64) {
928         if pp == nil {
929                 atomic.Xadd64(&c.scannableStackSize, amount)
930                 return
931         }
932         pp.scannableStackSizeDelta += amount
933         if pp.scannableStackSizeDelta >= scannableStackSizeSlack || pp.scannableStackSizeDelta <= -scannableStackSizeSlack {
934                 atomic.Xadd64(&c.scannableStackSize, pp.scannableStackSizeDelta)
935                 pp.scannableStackSizeDelta = 0
936         }
937 }
938
939 func (c *gcControllerState) addGlobals(amount int64) {
940         atomic.Xadd64(&c.globalsScan, amount)
941 }
942
943 // commit recomputes all pacing parameters from scratch, namely
944 // absolute trigger, the heap goal, mark pacing, and sweep pacing.
945 //
946 // If goexperiment.PacerRedesign is true, triggerRatio is ignored.
947 //
948 // This can be called any time. If GC is the in the middle of a
949 // concurrent phase, it will adjust the pacing of that phase.
950 //
951 // This depends on gcPercent, gcController.heapMarked, and
952 // gcController.heapLive. These must be up to date.
953 //
954 // mheap_.lock must be held or the world must be stopped.
955 func (c *gcControllerState) commit(triggerRatio float64) {
956         if !c.test {
957                 assertWorldStoppedOrLockHeld(&mheap_.lock)
958         }
959
960         if !goexperiment.PacerRedesign {
961                 c.oldCommit(triggerRatio)
962                 return
963         }
964
965         // Compute the next GC goal, which is when the allocated heap
966         // has grown by GOGC/100 over where it started the last cycle,
967         // plus additional runway for non-heap sources of GC work.
968         goal := ^uint64(0)
969         if gcPercent := c.gcPercent.Load(); gcPercent >= 0 {
970                 goal = c.heapMarked + (c.heapMarked+atomic.Load64(&c.stackScan)+atomic.Load64(&c.globalsScan))*uint64(gcPercent)/100
971         }
972
973         // Don't trigger below the minimum heap size.
974         minTrigger := c.heapMinimum
975         if !isSweepDone() {
976                 // Concurrent sweep happens in the heap growth
977                 // from gcController.heapLive to trigger, so ensure
978                 // that concurrent sweep has some heap growth
979                 // in which to perform sweeping before we
980                 // start the next GC cycle.
981                 sweepMin := atomic.Load64(&c.heapLive) + sweepMinHeapDistance
982                 if sweepMin > minTrigger {
983                         minTrigger = sweepMin
984                 }
985         }
986
987         // If we let the trigger go too low, then if the application
988         // is allocating very rapidly we might end up in a situation
989         // where we're allocating black during a nearly always-on GC.
990         // The result of this is a growing heap and ultimately an
991         // increase in RSS. By capping us at a point >0, we're essentially
992         // saying that we're OK using more CPU during the GC to prevent
993         // this growth in RSS.
994         //
995         // The current constant was chosen empirically: given a sufficiently
996         // fast/scalable allocator with 48 Ps that could drive the trigger ratio
997         // to <0.05, this constant causes applications to retain the same peak
998         // RSS compared to not having this allocator.
999         if triggerBound := uint64(0.7*float64(goal-c.heapMarked)) + c.heapMarked; minTrigger < triggerBound {
1000                 minTrigger = triggerBound
1001         }
1002
1003         // For small heaps, set the max trigger point at 95% of the heap goal.
1004         // This ensures we always have *some* headroom when the GC actually starts.
1005         // For larger heaps, set the max trigger point at the goal, minus the
1006         // minimum heap size.
1007         // This choice follows from the fact that the minimum heap size is chosen
1008         // to reflect the costs of a GC with no work to do. With a large heap but
1009         // very little scan work to perform, this gives us exactly as much runway
1010         // as we would need, in the worst case.
1011         maxRunway := uint64(0.95 * float64(goal-c.heapMarked))
1012         if largeHeapMaxRunway := goal - c.heapMinimum; goal > c.heapMinimum && maxRunway < largeHeapMaxRunway {
1013                 maxRunway = largeHeapMaxRunway
1014         }
1015         maxTrigger := maxRunway + c.heapMarked
1016         if maxTrigger < minTrigger {
1017                 maxTrigger = minTrigger
1018         }
1019
1020         // Compute the trigger by using our estimate of the cons/mark ratio.
1021         //
1022         // The idea is to take our expected scan work, and multiply it by
1023         // the cons/mark ratio to determine how long it'll take to complete
1024         // that scan work in terms of bytes allocated. This gives us our GC's
1025         // runway.
1026         //
1027         // However, the cons/mark ratio is a ratio of rates per CPU-second, but
1028         // here we care about the relative rates for some division of CPU
1029         // resources among the mutator and the GC.
1030         //
1031         // To summarize, we have B / cpu-ns, and we want B / ns. We get that
1032         // by multiplying by our desired division of CPU resources. We choose
1033         // to express CPU resources as GOMAPROCS*fraction. Note that because
1034         // we're working with a ratio here, we can omit the number of CPU cores,
1035         // because they'll appear in the numerator and denominator and cancel out.
1036         // As a result, this is basically just "weighing" the cons/mark ratio by
1037         // our desired division of resources.
1038         //
1039         // Furthermore, by setting the trigger so that CPU resources are divided
1040         // this way, assuming that the cons/mark ratio is correct, we make that
1041         // division a reality.
1042         var trigger uint64
1043         runway := uint64((c.consMark * (1 - gcGoalUtilization) / (gcGoalUtilization)) * float64(c.lastHeapScan+c.stackScan+c.globalsScan))
1044         if runway > goal {
1045                 trigger = minTrigger
1046         } else {
1047                 trigger = goal - runway
1048         }
1049         if trigger < minTrigger {
1050                 trigger = minTrigger
1051         }
1052         if trigger > maxTrigger {
1053                 trigger = maxTrigger
1054         }
1055         if trigger > goal {
1056                 goal = trigger
1057         }
1058
1059         // Commit to the trigger and goal.
1060         c.trigger = trigger
1061         atomic.Store64(&c.heapGoal, goal)
1062         if trace.enabled {
1063                 traceHeapGoal()
1064         }
1065
1066         // Update mark pacing.
1067         if gcphase != _GCoff {
1068                 c.revise()
1069         }
1070 }
1071
1072 // oldCommit sets the trigger ratio and updates everything
1073 // derived from it: the absolute trigger, the heap goal, mark pacing,
1074 // and sweep pacing.
1075 //
1076 // This can be called any time. If GC is the in the middle of a
1077 // concurrent phase, it will adjust the pacing of that phase.
1078 //
1079 // This depends on gcPercent, gcController.heapMarked, and
1080 // gcController.heapLive. These must be up to date.
1081 //
1082 // For !goexperiment.PacerRedesign.
1083 func (c *gcControllerState) oldCommit(triggerRatio float64) {
1084         gcPercent := c.gcPercent.Load()
1085
1086         // Compute the next GC goal, which is when the allocated heap
1087         // has grown by GOGC/100 over the heap marked by the last
1088         // cycle.
1089         goal := ^uint64(0)
1090         if gcPercent >= 0 {
1091                 goal = c.heapMarked + c.heapMarked*uint64(gcPercent)/100
1092         }
1093
1094         // Set the trigger ratio, capped to reasonable bounds.
1095         if gcPercent >= 0 {
1096                 scalingFactor := float64(gcPercent) / 100
1097                 // Ensure there's always a little margin so that the
1098                 // mutator assist ratio isn't infinity.
1099                 maxTriggerRatio := 0.95 * scalingFactor
1100                 if triggerRatio > maxTriggerRatio {
1101                         triggerRatio = maxTriggerRatio
1102                 }
1103
1104                 // If we let triggerRatio go too low, then if the application
1105                 // is allocating very rapidly we might end up in a situation
1106                 // where we're allocating black during a nearly always-on GC.
1107                 // The result of this is a growing heap and ultimately an
1108                 // increase in RSS. By capping us at a point >0, we're essentially
1109                 // saying that we're OK using more CPU during the GC to prevent
1110                 // this growth in RSS.
1111                 //
1112                 // The current constant was chosen empirically: given a sufficiently
1113                 // fast/scalable allocator with 48 Ps that could drive the trigger ratio
1114                 // to <0.05, this constant causes applications to retain the same peak
1115                 // RSS compared to not having this allocator.
1116                 minTriggerRatio := 0.6 * scalingFactor
1117                 if triggerRatio < minTriggerRatio {
1118                         triggerRatio = minTriggerRatio
1119                 }
1120         } else if triggerRatio < 0 {
1121                 // gcPercent < 0, so just make sure we're not getting a negative
1122                 // triggerRatio. This case isn't expected to happen in practice,
1123                 // and doesn't really matter because if gcPercent < 0 then we won't
1124                 // ever consume triggerRatio further on in this function, but let's
1125                 // just be defensive here; the triggerRatio being negative is almost
1126                 // certainly undesirable.
1127                 triggerRatio = 0
1128         }
1129         c.triggerRatio = triggerRatio
1130
1131         // Compute the absolute GC trigger from the trigger ratio.
1132         //
1133         // We trigger the next GC cycle when the allocated heap has
1134         // grown by the trigger ratio over the marked heap size.
1135         trigger := ^uint64(0)
1136         if gcPercent >= 0 {
1137                 trigger = uint64(float64(c.heapMarked) * (1 + triggerRatio))
1138                 // Don't trigger below the minimum heap size.
1139                 minTrigger := c.heapMinimum
1140                 if !isSweepDone() {
1141                         // Concurrent sweep happens in the heap growth
1142                         // from gcController.heapLive to trigger, so ensure
1143                         // that concurrent sweep has some heap growth
1144                         // in which to perform sweeping before we
1145                         // start the next GC cycle.
1146                         sweepMin := atomic.Load64(&c.heapLive) + sweepMinHeapDistance
1147                         if sweepMin > minTrigger {
1148                                 minTrigger = sweepMin
1149                         }
1150                 }
1151                 if trigger < minTrigger {
1152                         trigger = minTrigger
1153                 }
1154                 if int64(trigger) < 0 {
1155                         print("runtime: heapGoal=", c.heapGoal, " heapMarked=", c.heapMarked, " gcController.heapLive=", c.heapLive, " initialHeapLive=", work.initialHeapLive, "triggerRatio=", triggerRatio, " minTrigger=", minTrigger, "\n")
1156                         throw("trigger underflow")
1157                 }
1158                 if trigger > goal {
1159                         // The trigger ratio is always less than GOGC/100, but
1160                         // other bounds on the trigger may have raised it.
1161                         // Push up the goal, too.
1162                         goal = trigger
1163                 }
1164         }
1165
1166         // Commit to the trigger and goal.
1167         c.trigger = trigger
1168         atomic.Store64(&c.heapGoal, goal)
1169         if trace.enabled {
1170                 traceHeapGoal()
1171         }
1172
1173         // Update mark pacing.
1174         if gcphase != _GCoff {
1175                 c.revise()
1176         }
1177 }
1178
1179 // effectiveGrowthRatio returns the current effective heap growth
1180 // ratio (GOGC/100) based on heapMarked from the previous GC and
1181 // heapGoal for the current GC.
1182 //
1183 // This may differ from gcPercent/100 because of various upper and
1184 // lower bounds on gcPercent. For example, if the heap is smaller than
1185 // heapMinimum, this can be higher than gcPercent/100.
1186 //
1187 // mheap_.lock must be held or the world must be stopped.
1188 func (c *gcControllerState) effectiveGrowthRatio() float64 {
1189         if !c.test {
1190                 assertWorldStoppedOrLockHeld(&mheap_.lock)
1191         }
1192
1193         egogc := float64(atomic.Load64(&c.heapGoal)-c.heapMarked) / float64(c.heapMarked)
1194         if egogc < 0 {
1195                 // Shouldn't happen, but just in case.
1196                 egogc = 0
1197         }
1198         return egogc
1199 }
1200
1201 // setGCPercent updates gcPercent and all related pacer state.
1202 // Returns the old value of gcPercent.
1203 //
1204 // Calls gcControllerState.commit.
1205 //
1206 // The world must be stopped, or mheap_.lock must be held.
1207 func (c *gcControllerState) setGCPercent(in int32) int32 {
1208         if !c.test {
1209                 assertWorldStoppedOrLockHeld(&mheap_.lock)
1210         }
1211
1212         out := c.gcPercent.Load()
1213         if in < 0 {
1214                 in = -1
1215         }
1216         c.heapMinimum = defaultHeapMinimum * uint64(in) / 100
1217         c.gcPercent.Store(in)
1218         // Update pacing in response to gcPercent change.
1219         c.commit(c.triggerRatio)
1220
1221         return out
1222 }
1223
1224 //go:linkname setGCPercent runtime/debug.setGCPercent
1225 func setGCPercent(in int32) (out int32) {
1226         // Run on the system stack since we grab the heap lock.
1227         systemstack(func() {
1228                 lock(&mheap_.lock)
1229                 out = gcController.setGCPercent(in)
1230                 gcPaceSweeper(gcController.trigger)
1231                 gcPaceScavenger(gcController.heapGoal, gcController.lastHeapGoal)
1232                 unlock(&mheap_.lock)
1233         })
1234
1235         // If we just disabled GC, wait for any concurrent GC mark to
1236         // finish so we always return with no GC running.
1237         if in < 0 {
1238                 gcWaitOnMark(atomic.Load(&work.cycles))
1239         }
1240
1241         return out
1242 }
1243
1244 func readGOGC() int32 {
1245         p := gogetenv("GOGC")
1246         if p == "off" {
1247                 return -1
1248         }
1249         if n, ok := atoi32(p); ok {
1250                 return n
1251         }
1252         return 100
1253 }
1254
1255 type piController struct {
1256         kp float64 // Proportional constant.
1257         ti float64 // Integral time constant.
1258         tt float64 // Reset time.
1259
1260         min, max float64 // Output boundaries.
1261
1262         // PI controller state.
1263
1264         errIntegral float64 // Integral of the error from t=0 to now.
1265 }
1266
1267 func (c *piController) next(input, setpoint, period float64) float64 {
1268         // Compute the raw output value.
1269         prop := c.kp * (setpoint - input)
1270         rawOutput := prop + c.errIntegral
1271
1272         // Clamp rawOutput into output.
1273         output := rawOutput
1274         if output < c.min {
1275                 output = c.min
1276         } else if output > c.max {
1277                 output = c.max
1278         }
1279
1280         // Update the controller's state.
1281         if c.ti != 0 && c.tt != 0 {
1282                 c.errIntegral += (c.kp*period/c.ti)*(setpoint-input) + (period/c.tt)*(output-rawOutput)
1283         }
1284         return output
1285 }