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