]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/mgcpacer.go
runtime: convert gcController.dedicatedMarkTime to atomic type
[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" // for go:linkname
12 )
13
14 // go119MemoryLimitSupport is a feature flag for a number of changes
15 // related to the memory limit feature (#48409). Disabling this flag
16 // disables those features, as well as the memory limit mechanism,
17 // which becomes a no-op.
18 const go119MemoryLimitSupport = true
19
20 const (
21         // gcGoalUtilization is the goal CPU utilization for
22         // marking as a fraction of GOMAXPROCS.
23         //
24         // Increasing the goal utilization will shorten GC cycles as the GC
25         // has more resources behind it, lessening costs from the write barrier,
26         // but comes at the cost of increasing mutator latency.
27         gcGoalUtilization = gcBackgroundUtilization
28
29         // gcBackgroundUtilization is the fixed CPU utilization for background
30         // marking. It must be <= gcGoalUtilization. The difference between
31         // gcGoalUtilization and gcBackgroundUtilization will be made up by
32         // mark assists. The scheduler will aim to use within 50% of this
33         // goal.
34         //
35         // As a general rule, there's little reason to set gcBackgroundUtilization
36         // < gcGoalUtilization. One reason might be in mostly idle applications,
37         // where goroutines are unlikely to assist at all, so the actual
38         // utilization will be lower than the goal. But this is moot point
39         // because the idle mark workers already soak up idle CPU resources.
40         // These two values are still kept separate however because they are
41         // distinct conceptually, and in previous iterations of the pacer the
42         // distinction was more important.
43         gcBackgroundUtilization = 0.25
44
45         // gcCreditSlack is the amount of scan work credit that can
46         // accumulate locally before updating gcController.heapScanWork and,
47         // optionally, gcController.bgScanCredit. Lower values give a more
48         // accurate assist ratio and make it more likely that assists will
49         // successfully steal background credit. Higher values reduce memory
50         // contention.
51         gcCreditSlack = 2000
52
53         // gcAssistTimeSlack is the nanoseconds of mutator assist time that
54         // can accumulate on a P before updating gcController.assistTime.
55         gcAssistTimeSlack = 5000
56
57         // gcOverAssistWork determines how many extra units of scan work a GC
58         // assist does when an assist happens. This amortizes the cost of an
59         // assist by pre-paying for this many bytes of future allocations.
60         gcOverAssistWork = 64 << 10
61
62         // defaultHeapMinimum is the value of heapMinimum for GOGC==100.
63         defaultHeapMinimum = (goexperiment.HeapMinimum512KiBInt)*(512<<10) +
64                 (1-goexperiment.HeapMinimum512KiBInt)*(4<<20)
65
66         // maxStackScanSlack is the bytes of stack space allocated or freed
67         // that can accumulate on a P before updating gcController.stackSize.
68         maxStackScanSlack = 8 << 10
69
70         // memoryLimitHeapGoalHeadroom is the amount of headroom the pacer gives to
71         // the heap goal when operating in the memory-limited regime. That is,
72         // it'll reduce the heap goal by this many extra bytes off of the base
73         // calculation.
74         memoryLimitHeapGoalHeadroom = 1 << 20
75 )
76
77 // gcController implements the GC pacing controller that determines
78 // when to trigger concurrent garbage collection and how much marking
79 // work to do in mutator assists and background marking.
80 //
81 // It calculates the ratio between the allocation rate (in terms of CPU
82 // time) and the GC scan throughput to determine the heap size at which to
83 // trigger a GC cycle such that no GC assists are required to finish on time.
84 // This algorithm thus optimizes GC CPU utilization to the dedicated background
85 // mark utilization of 25% of GOMAXPROCS by minimizing GC assists.
86 // GOMAXPROCS. The high-level design of this algorithm is documented
87 // at https://github.com/golang/proposal/blob/master/design/44167-gc-pacer-redesign.md.
88 // See https://golang.org/s/go15gcpacing for additional historical context.
89 var gcController gcControllerState
90
91 type gcControllerState struct {
92         // Initialized from GOGC. GOGC=off means no GC.
93         gcPercent atomic.Int32
94
95         _ uint32 // padding so following 64-bit values are 8-byte aligned
96
97         // memoryLimit is the soft memory limit in bytes.
98         //
99         // Initialized from GOMEMLIMIT. GOMEMLIMIT=off is equivalent to MaxInt64
100         // which means no soft memory limit in practice.
101         //
102         // This is an int64 instead of a uint64 to more easily maintain parity with
103         // the SetMemoryLimit API, which sets a maximum at MaxInt64. This value
104         // should never be negative.
105         memoryLimit atomic.Int64
106
107         // heapMinimum is the minimum heap size at which to trigger GC.
108         // For small heaps, this overrides the usual GOGC*live set rule.
109         //
110         // When there is a very small live set but a lot of allocation, simply
111         // collecting when the heap reaches GOGC*live results in many GC
112         // cycles and high total per-GC overhead. This minimum amortizes this
113         // per-GC overhead while keeping the heap reasonably small.
114         //
115         // During initialization this is set to 4MB*GOGC/100. In the case of
116         // GOGC==0, this will set heapMinimum to 0, resulting in constant
117         // collection even when the heap size is small, which is useful for
118         // debugging.
119         heapMinimum uint64
120
121         // runway is the amount of runway in heap bytes allocated by the
122         // application that we want to give the GC once it starts.
123         //
124         // This is computed from consMark during mark termination.
125         runway atomic.Uint64
126
127         // consMark is the estimated per-CPU consMark ratio for the application.
128         //
129         // It represents the ratio between the application's allocation
130         // rate, as bytes allocated per CPU-time, and the GC's scan rate,
131         // as bytes scanned per CPU-time.
132         // The units of this ratio are (B / cpu-ns) / (B / cpu-ns).
133         //
134         // At a high level, this value is computed as the bytes of memory
135         // allocated (cons) per unit of scan work completed (mark) in a GC
136         // cycle, divided by the CPU time spent on each activity.
137         //
138         // Updated at the end of each GC cycle, in endCycle.
139         consMark float64
140
141         // consMarkController holds the state for the mark-cons ratio
142         // estimation over time.
143         //
144         // Its purpose is to smooth out noisiness in the computation of
145         // consMark; see consMark for details.
146         consMarkController piController
147
148         _ uint32 // Padding for atomics on 32-bit platforms.
149
150         // gcPercentHeapGoal is the goal heapLive for when next GC ends derived
151         // from gcPercent.
152         //
153         // Set to ^uint64(0) if gcPercent is disabled.
154         gcPercentHeapGoal atomic.Uint64
155
156         // sweepDistMinTrigger is the minimum trigger to ensure a minimum
157         // sweep distance.
158         //
159         // This bound is also special because it applies to both the trigger
160         // *and* the goal (all other trigger bounds must be based *on* the goal).
161         //
162         // It is computed ahead of time, at commit time. The theory is that,
163         // absent a sudden change to a parameter like gcPercent, the trigger
164         // will be chosen to always give the sweeper enough headroom. However,
165         // such a change might dramatically and suddenly move up the trigger,
166         // in which case we need to ensure the sweeper still has enough headroom.
167         sweepDistMinTrigger atomic.Uint64
168
169         // triggered is the point at which the current GC cycle actually triggered.
170         // Only valid during the mark phase of a GC cycle, otherwise set to ^uint64(0).
171         //
172         // Updated while the world is stopped.
173         triggered uint64
174
175         // lastHeapGoal is the value of heapGoal at the moment the last GC
176         // ended. Note that this is distinct from the last value heapGoal had,
177         // because it could change if e.g. gcPercent changes.
178         //
179         // Read and written with the world stopped or with mheap_.lock held.
180         lastHeapGoal uint64
181
182         // heapLive is the number of bytes considered live by the GC.
183         // That is: retained by the most recent GC plus allocated
184         // since then. heapLive ≤ memstats.totalAlloc-memstats.totalFree, since
185         // heapAlloc includes unmarked objects that have not yet been swept (and
186         // hence goes up as we allocate and down as we sweep) while heapLive
187         // excludes these objects (and hence only goes up between GCs).
188         //
189         // To reduce contention, this is updated only when obtaining a span
190         // from an mcentral and at this point it counts all of the unallocated
191         // slots in that span (which will be allocated before that mcache
192         // obtains another span from that mcentral). Hence, it slightly
193         // overestimates the "true" live heap size. It's better to overestimate
194         // than to underestimate because 1) this triggers the GC earlier than
195         // necessary rather than potentially too late and 2) this leads to a
196         // conservative GC rate rather than a GC rate that is potentially too
197         // low.
198         //
199         // Whenever this is updated, call traceHeapAlloc() and
200         // this gcControllerState's revise() method.
201         heapLive atomic.Uint64
202
203         // heapScan is the number of bytes of "scannable" heap. This is the
204         // live heap (as counted by heapLive), but omitting no-scan objects and
205         // no-scan tails of objects.
206         //
207         // This value is fixed at the start of a GC cycle. It represents the
208         // maximum scannable heap.
209         heapScan atomic.Uint64
210
211         // lastHeapScan is the number of bytes of heap that were scanned
212         // last GC cycle. It is the same as heapMarked, but only
213         // includes the "scannable" parts of objects.
214         //
215         // Updated when the world is stopped.
216         lastHeapScan uint64
217
218         // lastStackScan is the number of bytes of stack that were scanned
219         // last GC cycle.
220         lastStackScan atomic.Uint64
221
222         // maxStackScan 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         maxStackScan atomic.Uint64
231
232         // globalsScan is the total amount of global variable space
233         // that is scannable.
234         globalsScan atomic.Uint64
235
236         // heapMarked is the number of bytes marked by the previous
237         // GC. After mark termination, heapLive == heapMarked, but
238         // unlike heapLive, heapMarked does not change until the
239         // next mark termination.
240         heapMarked uint64
241
242         // heapScanWork is the total heap scan work performed this cycle.
243         // stackScanWork is the total stack scan work performed this cycle.
244         // globalsScanWork is the total globals scan work performed this cycle.
245         //
246         // These are updated atomically during the cycle. Updates occur in
247         // bounded batches, since they are both written and read
248         // throughout the cycle. At the end of the cycle, heapScanWork is how
249         // much of the retained heap is scannable.
250         //
251         // Currently these are measured in bytes. For most uses, this is an
252         // opaque unit of work, but for estimation the definition is important.
253         //
254         // Note that stackScanWork includes only stack space scanned, not all
255         // of the allocated stack.
256         heapScanWork    atomic.Int64
257         stackScanWork   atomic.Int64
258         globalsScanWork atomic.Int64
259
260         // bgScanCredit is the scan work credit accumulated by the concurrent
261         // background scan. This credit is accumulated by the background scan
262         // and stolen by mutator assists.  Updates occur in bounded batches,
263         // since it is both written and read throughout the cycle.
264         bgScanCredit atomic.Int64
265
266         // assistTime is the nanoseconds spent in mutator assists
267         // during this cycle. This is updated atomically, and must also
268         // be updated atomically even during a STW, because it is read
269         // by sysmon. Updates occur in bounded batches, since it is both
270         // written and read throughout the cycle.
271         assistTime atomic.Int64
272
273         // dedicatedMarkTime is the nanoseconds spent in dedicated mark workers
274         // during this cycle. This is updated at the end of the concurrent mark
275         // phase.
276         dedicatedMarkTime atomic.Int64
277
278         // fractionalMarkTime is the nanoseconds spent in the
279         // fractional mark worker during this cycle. This is updated
280         // atomically throughout the cycle and will be up-to-date if
281         // the fractional mark worker is not currently running.
282         fractionalMarkTime int64
283
284         // idleMarkTime is the nanoseconds spent in idle marking
285         // during this cycle. This is updated atomically throughout
286         // the cycle.
287         idleMarkTime int64
288
289         // markStartTime is the absolute start time in nanoseconds
290         // that assists and background mark workers started.
291         markStartTime int64
292
293         // dedicatedMarkWorkersNeeded is the number of dedicated mark
294         // workers that need to be started. This is computed at the
295         // beginning of each cycle and decremented atomically as
296         // dedicated mark workers get started.
297         dedicatedMarkWorkersNeeded int64
298
299         // idleMarkWorkers is two packed int32 values in a single uint64.
300         // These two values are always updated simultaneously.
301         //
302         // The bottom int32 is the current number of idle mark workers executing.
303         //
304         // The top int32 is the maximum number of idle mark workers allowed to
305         // execute concurrently. Normally, this number is just gomaxprocs. However,
306         // during periodic GC cycles it is set to 0 because the system is idle
307         // anyway; there's no need to go full blast on all of GOMAXPROCS.
308         //
309         // The maximum number of idle mark workers is used to prevent new workers
310         // from starting, but it is not a hard maximum. It is possible (but
311         // exceedingly rare) for the current number of idle mark workers to
312         // transiently exceed the maximum. This could happen if the maximum changes
313         // just after a GC ends, and an M with no P.
314         //
315         // Note that if we have no dedicated mark workers, we set this value to
316         // 1 in this case we only have fractional GC workers which aren't scheduled
317         // strictly enough to ensure GC progress. As a result, idle-priority mark
318         // workers are vital to GC progress in these situations.
319         //
320         // For example, consider a situation in which goroutines block on the GC
321         // (such as via runtime.GOMAXPROCS) and only fractional mark workers are
322         // scheduled (e.g. GOMAXPROCS=1). Without idle-priority mark workers, the
323         // last running M might skip scheduling a fractional mark worker if its
324         // utilization goal is met, such that once it goes to sleep (because there's
325         // nothing to do), there will be nothing else to spin up a new M for the
326         // fractional worker in the future, stalling GC progress and causing a
327         // deadlock. However, idle-priority workers will *always* run when there is
328         // nothing left to do, ensuring the GC makes progress.
329         //
330         // See github.com/golang/go/issues/44163 for more details.
331         idleMarkWorkers atomic.Uint64
332
333         // assistWorkPerByte is the ratio of scan work to allocated
334         // bytes that should be performed by mutator assists. This is
335         // computed at the beginning of each cycle and updated every
336         // time heapScan is updated.
337         assistWorkPerByte atomic.Float64
338
339         // assistBytesPerWork is 1/assistWorkPerByte.
340         //
341         // Note that because this is read and written independently
342         // from assistWorkPerByte users may notice a skew between
343         // the two values, and such a state should be safe.
344         assistBytesPerWork atomic.Float64
345
346         // fractionalUtilizationGoal is the fraction of wall clock
347         // time that should be spent in the fractional mark worker on
348         // each P that isn't running a dedicated worker.
349         //
350         // For example, if the utilization goal is 25% and there are
351         // no dedicated workers, this will be 0.25. If the goal is
352         // 25%, there is one dedicated worker, and GOMAXPROCS is 5,
353         // this will be 0.05 to make up the missing 5%.
354         //
355         // If this is zero, no fractional workers are needed.
356         fractionalUtilizationGoal float64
357
358         // These memory stats are effectively duplicates of fields from
359         // memstats.heapStats but are updated atomically or with the world
360         // stopped and don't provide the same consistency guarantees.
361         //
362         // Because the runtime is responsible for managing a memory limit, it's
363         // useful to couple these stats more tightly to the gcController, which
364         // is intimately connected to how that memory limit is maintained.
365         heapInUse    sysMemStat    // bytes in mSpanInUse spans
366         heapReleased sysMemStat    // bytes released to the OS
367         heapFree     sysMemStat    // bytes not in any span, but not released to the OS
368         totalAlloc   atomic.Uint64 // total bytes allocated
369         totalFree    atomic.Uint64 // total bytes freed
370         mappedReady  atomic.Uint64 // total virtual memory in the Ready state (see mem.go).
371
372         // test indicates that this is a test-only copy of gcControllerState.
373         test bool
374
375         _ cpu.CacheLinePad
376 }
377
378 func (c *gcControllerState) init(gcPercent int32, memoryLimit int64) {
379         c.heapMinimum = defaultHeapMinimum
380         c.triggered = ^uint64(0)
381
382         c.consMarkController = piController{
383                 // Tuned first via the Ziegler-Nichols process in simulation,
384                 // then the integral time was manually tuned against real-world
385                 // applications to deal with noisiness in the measured cons/mark
386                 // ratio.
387                 kp: 0.9,
388                 ti: 4.0,
389
390                 // Set a high reset time in GC cycles.
391                 // This is inversely proportional to the rate at which we
392                 // accumulate error from clipping. By making this very high
393                 // we make the accumulation slow. In general, clipping is
394                 // OK in our situation, hence the choice.
395                 //
396                 // Tune this if we get unintended effects from clipping for
397                 // a long time.
398                 tt:  1000,
399                 min: -1000,
400                 max: 1000,
401         }
402
403         c.setGCPercent(gcPercent)
404         c.setMemoryLimit(memoryLimit)
405         c.commit(true) // No sweep phase in the first GC cycle.
406         // N.B. Don't bother calling traceHeapGoal. Tracing is never enabled at
407         // initialization time.
408         // N.B. No need to call revise; there's no GC enabled during
409         // initialization.
410 }
411
412 // startCycle resets the GC controller's state and computes estimates
413 // for a new GC cycle. The caller must hold worldsema and the world
414 // must be stopped.
415 func (c *gcControllerState) startCycle(markStartTime int64, procs int, trigger gcTrigger) {
416         c.heapScanWork.Store(0)
417         c.stackScanWork.Store(0)
418         c.globalsScanWork.Store(0)
419         c.bgScanCredit.Store(0)
420         c.assistTime.Store(0)
421         c.dedicatedMarkTime.Store(0)
422         c.fractionalMarkTime = 0
423         c.idleMarkTime = 0
424         c.markStartTime = markStartTime
425
426         // TODO(mknyszek): This is supposed to be the actual trigger point for the heap, but
427         // causes regressions in memory use. The cause is that the PI controller used to smooth
428         // the cons/mark ratio measurements tends to flail when using the less accurate precomputed
429         // trigger for the cons/mark calculation, and this results in the controller being more
430         // conservative about steady-states it tries to find in the future.
431         //
432         // This conservatism is transient, but these transient states tend to matter for short-lived
433         // programs, especially because the PI controller is overdamped, partially because it is
434         // configured with a relatively large time constant.
435         //
436         // Ultimately, I think this is just two mistakes piled on one another: the choice of a swingy
437         // smoothing function that recalls a fairly long history (due to its overdamped time constant)
438         // coupled with an inaccurate cons/mark calculation. It just so happens this works better
439         // today, and it makes it harder to change things in the future.
440         //
441         // This is described in #53738. Fix this for #53892 by changing back to the actual trigger
442         // point and simplifying the smoothing function.
443         heapTrigger, heapGoal := c.trigger()
444         c.triggered = heapTrigger
445
446         // Compute the background mark utilization goal. In general,
447         // this may not come out exactly. We round the number of
448         // dedicated workers so that the utilization is closest to
449         // 25%. For small GOMAXPROCS, this would introduce too much
450         // error, so we add fractional workers in that case.
451         totalUtilizationGoal := float64(procs) * gcBackgroundUtilization
452         c.dedicatedMarkWorkersNeeded = int64(totalUtilizationGoal + 0.5)
453         utilError := float64(c.dedicatedMarkWorkersNeeded)/totalUtilizationGoal - 1
454         const maxUtilError = 0.3
455         if utilError < -maxUtilError || utilError > maxUtilError {
456                 // Rounding put us more than 30% off our goal. With
457                 // gcBackgroundUtilization of 25%, this happens for
458                 // GOMAXPROCS<=3 or GOMAXPROCS=6. Enable fractional
459                 // workers to compensate.
460                 if float64(c.dedicatedMarkWorkersNeeded) > totalUtilizationGoal {
461                         // Too many dedicated workers.
462                         c.dedicatedMarkWorkersNeeded--
463                 }
464                 c.fractionalUtilizationGoal = (totalUtilizationGoal - float64(c.dedicatedMarkWorkersNeeded)) / float64(procs)
465         } else {
466                 c.fractionalUtilizationGoal = 0
467         }
468
469         // In STW mode, we just want dedicated workers.
470         if debug.gcstoptheworld > 0 {
471                 c.dedicatedMarkWorkersNeeded = int64(procs)
472                 c.fractionalUtilizationGoal = 0
473         }
474
475         // Clear per-P state
476         for _, p := range allp {
477                 p.gcAssistTime = 0
478                 p.gcFractionalMarkTime = 0
479         }
480
481         if trigger.kind == gcTriggerTime {
482                 // During a periodic GC cycle, reduce the number of idle mark workers
483                 // required. However, we need at least one dedicated mark worker or
484                 // idle GC worker to ensure GC progress in some scenarios (see comment
485                 // on maxIdleMarkWorkers).
486                 if c.dedicatedMarkWorkersNeeded > 0 {
487                         c.setMaxIdleMarkWorkers(0)
488                 } else {
489                         // TODO(mknyszek): The fundamental reason why we need this is because
490                         // we can't count on the fractional mark worker to get scheduled.
491                         // Fix that by ensuring it gets scheduled according to its quota even
492                         // if the rest of the application is idle.
493                         c.setMaxIdleMarkWorkers(1)
494                 }
495         } else {
496                 // N.B. gomaxprocs and dedicatedMarkWorkersNeeded is guaranteed not to
497                 // change during a GC cycle.
498                 c.setMaxIdleMarkWorkers(int32(procs) - int32(c.dedicatedMarkWorkersNeeded))
499         }
500
501         // Compute initial values for controls that are updated
502         // throughout the cycle.
503         c.revise()
504
505         if debug.gcpacertrace > 0 {
506                 assistRatio := c.assistWorkPerByte.Load()
507                 print("pacer: assist ratio=", assistRatio,
508                         " (scan ", gcController.heapScan.Load()>>20, " MB in ",
509                         work.initialHeapLive>>20, "->",
510                         heapGoal>>20, " MB)",
511                         " workers=", c.dedicatedMarkWorkersNeeded,
512                         "+", c.fractionalUtilizationGoal, "\n")
513         }
514 }
515
516 // revise updates the assist ratio during the GC cycle to account for
517 // improved estimates. This should be called whenever gcController.heapScan,
518 // gcController.heapLive, or if any inputs to gcController.heapGoal are
519 // updated. It is safe to call concurrently, but it may race with other
520 // calls to revise.
521 //
522 // The result of this race is that the two assist ratio values may not line
523 // up or may be stale. In practice this is OK because the assist ratio
524 // moves slowly throughout a GC cycle, and the assist ratio is a best-effort
525 // heuristic anyway. Furthermore, no part of the heuristic depends on
526 // the two assist ratio values being exact reciprocals of one another, since
527 // the two values are used to convert values from different sources.
528 //
529 // The worst case result of this raciness is that we may miss a larger shift
530 // in the ratio (say, if we decide to pace more aggressively against the
531 // hard heap goal) but even this "hard goal" is best-effort (see #40460).
532 // The dedicated GC should ensure we don't exceed the hard goal by too much
533 // in the rare case we do exceed it.
534 //
535 // It should only be called when gcBlackenEnabled != 0 (because this
536 // is when assists are enabled and the necessary statistics are
537 // available).
538 func (c *gcControllerState) revise() {
539         gcPercent := c.gcPercent.Load()
540         if gcPercent < 0 {
541                 // If GC is disabled but we're running a forced GC,
542                 // act like GOGC is huge for the below calculations.
543                 gcPercent = 100000
544         }
545         live := c.heapLive.Load()
546         scan := c.heapScan.Load()
547         work := c.heapScanWork.Load() + c.stackScanWork.Load() + c.globalsScanWork.Load()
548
549         // Assume we're under the soft goal. Pace GC to complete at
550         // heapGoal assuming the heap is in steady-state.
551         heapGoal := int64(c.heapGoal())
552
553         // The expected scan work is computed as the amount of bytes scanned last
554         // GC cycle (both heap and stack), plus our estimate of globals work for this cycle.
555         scanWorkExpected := int64(c.lastHeapScan + c.lastStackScan.Load() + c.globalsScan.Load())
556
557         // maxScanWork is a worst-case estimate of the amount of scan work that
558         // needs to be performed in this GC cycle. Specifically, it represents
559         // the case where *all* scannable memory turns out to be live, and
560         // *all* allocated stack space is scannable.
561         maxStackScan := c.maxStackScan.Load()
562         maxScanWork := int64(scan + maxStackScan + c.globalsScan.Load())
563         if work > scanWorkExpected {
564                 // We've already done more scan work than expected. Because our expectation
565                 // is based on a steady-state scannable heap size, we assume this means our
566                 // heap is growing. Compute a new heap goal that takes our existing runway
567                 // computed for scanWorkExpected and extrapolates it to maxScanWork, the worst-case
568                 // scan work. This keeps our assist ratio stable if the heap continues to grow.
569                 //
570                 // The effect of this mechanism is that assists stay flat in the face of heap
571                 // growths. It's OK to use more memory this cycle to scan all the live heap,
572                 // because the next GC cycle is inevitably going to use *at least* that much
573                 // memory anyway.
574                 extHeapGoal := int64(float64(heapGoal-int64(c.triggered))/float64(scanWorkExpected)*float64(maxScanWork)) + int64(c.triggered)
575                 scanWorkExpected = maxScanWork
576
577                 // hardGoal is a hard limit on the amount that we're willing to push back the
578                 // heap goal, and that's twice the heap goal (i.e. if GOGC=100 and the heap and/or
579                 // stacks and/or globals grow to twice their size, this limits the current GC cycle's
580                 // growth to 4x the original live heap's size).
581                 //
582                 // This maintains the invariant that we use no more memory than the next GC cycle
583                 // will anyway.
584                 hardGoal := int64((1.0 + float64(gcPercent)/100.0) * float64(heapGoal))
585                 if extHeapGoal > hardGoal {
586                         extHeapGoal = hardGoal
587                 }
588                 heapGoal = extHeapGoal
589         }
590         if int64(live) > heapGoal {
591                 // We're already past our heap goal, even the extrapolated one.
592                 // Leave ourselves some extra runway, so in the worst case we
593                 // finish by that point.
594                 const maxOvershoot = 1.1
595                 heapGoal = int64(float64(heapGoal) * maxOvershoot)
596
597                 // Compute the upper bound on the scan work remaining.
598                 scanWorkExpected = maxScanWork
599         }
600
601         // Compute the remaining scan work estimate.
602         //
603         // Note that we currently count allocations during GC as both
604         // scannable heap (heapScan) and scan work completed
605         // (scanWork), so allocation will change this difference
606         // slowly in the soft regime and not at all in the hard
607         // regime.
608         scanWorkRemaining := scanWorkExpected - work
609         if scanWorkRemaining < 1000 {
610                 // We set a somewhat arbitrary lower bound on
611                 // remaining scan work since if we aim a little high,
612                 // we can miss by a little.
613                 //
614                 // We *do* need to enforce that this is at least 1,
615                 // since marking is racy and double-scanning objects
616                 // may legitimately make the remaining scan work
617                 // negative, even in the hard goal regime.
618                 scanWorkRemaining = 1000
619         }
620
621         // Compute the heap distance remaining.
622         heapRemaining := heapGoal - int64(live)
623         if heapRemaining <= 0 {
624                 // This shouldn't happen, but if it does, avoid
625                 // dividing by zero or setting the assist negative.
626                 heapRemaining = 1
627         }
628
629         // Compute the mutator assist ratio so by the time the mutator
630         // allocates the remaining heap bytes up to heapGoal, it will
631         // have done (or stolen) the remaining amount of scan work.
632         // Note that the assist ratio values are updated atomically
633         // but not together. This means there may be some degree of
634         // skew between the two values. This is generally OK as the
635         // values shift relatively slowly over the course of a GC
636         // cycle.
637         assistWorkPerByte := float64(scanWorkRemaining) / float64(heapRemaining)
638         assistBytesPerWork := float64(heapRemaining) / float64(scanWorkRemaining)
639         c.assistWorkPerByte.Store(assistWorkPerByte)
640         c.assistBytesPerWork.Store(assistBytesPerWork)
641 }
642
643 // endCycle computes the consMark estimate for the next cycle.
644 // userForced indicates whether the current GC cycle was forced
645 // by the application.
646 func (c *gcControllerState) endCycle(now int64, procs int, userForced bool) {
647         // Record last heap goal for the scavenger.
648         // We'll be updating the heap goal soon.
649         gcController.lastHeapGoal = c.heapGoal()
650
651         // Compute the duration of time for which assists were turned on.
652         assistDuration := now - c.markStartTime
653
654         // Assume background mark hit its utilization goal.
655         utilization := gcBackgroundUtilization
656         // Add assist utilization; avoid divide by zero.
657         if assistDuration > 0 {
658                 utilization += float64(c.assistTime.Load()) / float64(assistDuration*int64(procs))
659         }
660
661         if c.heapLive.Load() <= c.triggered {
662                 // Shouldn't happen, but let's be very safe about this in case the
663                 // GC is somehow extremely short.
664                 //
665                 // In this case though, the only reasonable value for c.heapLive-c.triggered
666                 // would be 0, which isn't really all that useful, i.e. the GC was so short
667                 // that it didn't matter.
668                 //
669                 // Ignore this case and don't update anything.
670                 return
671         }
672         idleUtilization := 0.0
673         if assistDuration > 0 {
674                 idleUtilization = float64(c.idleMarkTime) / float64(assistDuration*int64(procs))
675         }
676         // Determine the cons/mark ratio.
677         //
678         // The units we want for the numerator and denominator are both B / cpu-ns.
679         // We get this by taking the bytes allocated or scanned, and divide by the amount of
680         // CPU time it took for those operations. For allocations, that CPU time is
681         //
682         //    assistDuration * procs * (1 - utilization)
683         //
684         // Where utilization includes just background GC workers and assists. It does *not*
685         // include idle GC work time, because in theory the mutator is free to take that at
686         // any point.
687         //
688         // For scanning, that CPU time is
689         //
690         //    assistDuration * procs * (utilization + idleUtilization)
691         //
692         // In this case, we *include* idle utilization, because that is additional CPU time that the
693         // the GC had available to it.
694         //
695         // In effect, idle GC time is sort of double-counted here, but it's very weird compared
696         // to other kinds of GC work, because of how fluid it is. Namely, because the mutator is
697         // *always* free to take it.
698         //
699         // So this calculation is really:
700         //     (heapLive-trigger) / (assistDuration * procs * (1-utilization)) /
701         //         (scanWork) / (assistDuration * procs * (utilization+idleUtilization)
702         //
703         // Note that because we only care about the ratio, assistDuration and procs cancel out.
704         scanWork := c.heapScanWork.Load() + c.stackScanWork.Load() + c.globalsScanWork.Load()
705         currentConsMark := (float64(c.heapLive.Load()-c.triggered) * (utilization + idleUtilization)) /
706                 (float64(scanWork) * (1 - utilization))
707
708         // Update cons/mark controller. The time period for this is 1 GC cycle.
709         //
710         // This use of a PI controller might seem strange. So, here's an explanation:
711         //
712         // currentConsMark represents the consMark we *should've* had to be perfectly
713         // on-target for this cycle. Given that we assume the next GC will be like this
714         // one in the steady-state, it stands to reason that we should just pick that
715         // as our next consMark. In practice, however, currentConsMark is too noisy:
716         // we're going to be wildly off-target in each GC cycle if we do that.
717         //
718         // What we do instead is make a long-term assumption: there is some steady-state
719         // consMark value, but it's obscured by noise. By constantly shooting for this
720         // noisy-but-perfect consMark value, the controller will bounce around a bit,
721         // but its average behavior, in aggregate, should be less noisy and closer to
722         // the true long-term consMark value, provided its tuned to be slightly overdamped.
723         var ok bool
724         oldConsMark := c.consMark
725         c.consMark, ok = c.consMarkController.next(c.consMark, currentConsMark, 1.0)
726         if !ok {
727                 // The error spiraled out of control. This is incredibly unlikely seeing
728                 // as this controller is essentially just a smoothing function, but it might
729                 // mean that something went very wrong with how currentConsMark was calculated.
730                 // Just reset consMark and keep going.
731                 c.consMark = 0
732         }
733
734         if debug.gcpacertrace > 0 {
735                 printlock()
736                 goal := gcGoalUtilization * 100
737                 print("pacer: ", int(utilization*100), "% CPU (", int(goal), " exp.) for ")
738                 print(c.heapScanWork.Load(), "+", c.stackScanWork.Load(), "+", c.globalsScanWork.Load(), " B work (", c.lastHeapScan+c.lastStackScan.Load()+c.globalsScan.Load(), " B exp.) ")
739                 live := c.heapLive.Load()
740                 print("in ", c.triggered, " B -> ", live, " B (∆goal ", int64(live)-int64(c.lastHeapGoal), ", cons/mark ", oldConsMark, ")")
741                 if !ok {
742                         print("[controller reset]")
743                 }
744                 println()
745                 printunlock()
746         }
747 }
748
749 // enlistWorker encourages another dedicated mark worker to start on
750 // another P if there are spare worker slots. It is used by putfull
751 // when more work is made available.
752 //
753 //go:nowritebarrier
754 func (c *gcControllerState) enlistWorker() {
755         // If there are idle Ps, wake one so it will run an idle worker.
756         // NOTE: This is suspected of causing deadlocks. See golang.org/issue/19112.
757         //
758         //      if atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 {
759         //              wakep()
760         //              return
761         //      }
762
763         // There are no idle Ps. If we need more dedicated workers,
764         // try to preempt a running P so it will switch to a worker.
765         if c.dedicatedMarkWorkersNeeded <= 0 {
766                 return
767         }
768         // Pick a random other P to preempt.
769         if gomaxprocs <= 1 {
770                 return
771         }
772         gp := getg()
773         if gp == nil || gp.m == nil || gp.m.p == 0 {
774                 return
775         }
776         myID := gp.m.p.ptr().id
777         for tries := 0; tries < 5; tries++ {
778                 id := int32(fastrandn(uint32(gomaxprocs - 1)))
779                 if id >= myID {
780                         id++
781                 }
782                 p := allp[id]
783                 if p.status != _Prunning {
784                         continue
785                 }
786                 if preemptone(p) {
787                         return
788                 }
789         }
790 }
791
792 // findRunnableGCWorker returns a background mark worker for pp if it
793 // should be run. This must only be called when gcBlackenEnabled != 0.
794 func (c *gcControllerState) findRunnableGCWorker(pp *p, now int64) (*g, int64) {
795         if gcBlackenEnabled == 0 {
796                 throw("gcControllerState.findRunnable: blackening not enabled")
797         }
798
799         // Since we have the current time, check if the GC CPU limiter
800         // hasn't had an update in a while. This check is necessary in
801         // case the limiter is on but hasn't been checked in a while and
802         // so may have left sufficient headroom to turn off again.
803         if now == 0 {
804                 now = nanotime()
805         }
806         if gcCPULimiter.needUpdate(now) {
807                 gcCPULimiter.update(now)
808         }
809
810         if !gcMarkWorkAvailable(pp) {
811                 // No work to be done right now. This can happen at
812                 // the end of the mark phase when there are still
813                 // assists tapering off. Don't bother running a worker
814                 // now because it'll just return immediately.
815                 return nil, now
816         }
817
818         // Grab a worker before we commit to running below.
819         node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
820         if node == nil {
821                 // There is at least one worker per P, so normally there are
822                 // enough workers to run on all Ps, if necessary. However, once
823                 // a worker enters gcMarkDone it may park without rejoining the
824                 // pool, thus freeing a P with no corresponding worker.
825                 // gcMarkDone never depends on another worker doing work, so it
826                 // is safe to simply do nothing here.
827                 //
828                 // If gcMarkDone bails out without completing the mark phase,
829                 // it will always do so with queued global work. Thus, that P
830                 // will be immediately eligible to re-run the worker G it was
831                 // just using, ensuring work can complete.
832                 return nil, now
833         }
834
835         decIfPositive := func(ptr *int64) bool {
836                 for {
837                         v := atomic.Loadint64(ptr)
838                         if v <= 0 {
839                                 return false
840                         }
841
842                         if atomic.Casint64(ptr, v, v-1) {
843                                 return true
844                         }
845                 }
846         }
847
848         if decIfPositive(&c.dedicatedMarkWorkersNeeded) {
849                 // This P is now dedicated to marking until the end of
850                 // the concurrent mark phase.
851                 pp.gcMarkWorkerMode = gcMarkWorkerDedicatedMode
852         } else if c.fractionalUtilizationGoal == 0 {
853                 // No need for fractional workers.
854                 gcBgMarkWorkerPool.push(&node.node)
855                 return nil, now
856         } else {
857                 // Is this P behind on the fractional utilization
858                 // goal?
859                 //
860                 // This should be kept in sync with pollFractionalWorkerExit.
861                 delta := now - c.markStartTime
862                 if delta > 0 && float64(pp.gcFractionalMarkTime)/float64(delta) > c.fractionalUtilizationGoal {
863                         // Nope. No need to run a fractional worker.
864                         gcBgMarkWorkerPool.push(&node.node)
865                         return nil, now
866                 }
867                 // Run a fractional worker.
868                 pp.gcMarkWorkerMode = gcMarkWorkerFractionalMode
869         }
870
871         // Run the background mark worker.
872         gp := node.gp.ptr()
873         casgstatus(gp, _Gwaiting, _Grunnable)
874         if trace.enabled {
875                 traceGoUnpark(gp, 0)
876         }
877         return gp, now
878 }
879
880 // resetLive sets up the controller state for the next mark phase after the end
881 // of the previous one. Must be called after endCycle and before commit, before
882 // the world is started.
883 //
884 // The world must be stopped.
885 func (c *gcControllerState) resetLive(bytesMarked uint64) {
886         c.heapMarked = bytesMarked
887         c.heapLive.Store(bytesMarked)
888         c.heapScan.Store(uint64(c.heapScanWork.Load()))
889         c.lastHeapScan = uint64(c.heapScanWork.Load())
890         c.lastStackScan.Store(uint64(c.stackScanWork.Load()))
891         c.triggered = ^uint64(0) // Reset triggered.
892
893         // heapLive was updated, so emit a trace event.
894         if trace.enabled {
895                 traceHeapAlloc(bytesMarked)
896         }
897 }
898
899 // markWorkerStop must be called whenever a mark worker stops executing.
900 //
901 // It updates mark work accounting in the controller by a duration of
902 // work in nanoseconds and other bookkeeping.
903 //
904 // Safe to execute at any time.
905 func (c *gcControllerState) markWorkerStop(mode gcMarkWorkerMode, duration int64) {
906         switch mode {
907         case gcMarkWorkerDedicatedMode:
908                 c.dedicatedMarkTime.Add(duration)
909                 atomic.Xaddint64(&c.dedicatedMarkWorkersNeeded, 1)
910         case gcMarkWorkerFractionalMode:
911                 atomic.Xaddint64(&c.fractionalMarkTime, duration)
912         case gcMarkWorkerIdleMode:
913                 atomic.Xaddint64(&c.idleMarkTime, duration)
914                 c.removeIdleMarkWorker()
915         default:
916                 throw("markWorkerStop: unknown mark worker mode")
917         }
918 }
919
920 func (c *gcControllerState) update(dHeapLive, dHeapScan int64) {
921         if dHeapLive != 0 {
922                 live := gcController.heapLive.Add(dHeapLive)
923                 if trace.enabled {
924                         // gcController.heapLive changed.
925                         traceHeapAlloc(live)
926                 }
927         }
928         if gcBlackenEnabled == 0 {
929                 // Update heapScan when we're not in a current GC. It is fixed
930                 // at the beginning of a cycle.
931                 if dHeapScan != 0 {
932                         gcController.heapScan.Add(dHeapScan)
933                 }
934         } else {
935                 // gcController.heapLive changed.
936                 c.revise()
937         }
938 }
939
940 func (c *gcControllerState) addScannableStack(pp *p, amount int64) {
941         if pp == nil {
942                 c.maxStackScan.Add(amount)
943                 return
944         }
945         pp.maxStackScanDelta += amount
946         if pp.maxStackScanDelta >= maxStackScanSlack || pp.maxStackScanDelta <= -maxStackScanSlack {
947                 c.maxStackScan.Add(pp.maxStackScanDelta)
948                 pp.maxStackScanDelta = 0
949         }
950 }
951
952 func (c *gcControllerState) addGlobals(amount int64) {
953         c.globalsScan.Add(amount)
954 }
955
956 // heapGoal returns the current heap goal.
957 func (c *gcControllerState) heapGoal() uint64 {
958         goal, _ := c.heapGoalInternal()
959         return goal
960 }
961
962 // heapGoalInternal is the implementation of heapGoal which returns additional
963 // information that is necessary for computing the trigger.
964 //
965 // The returned minTrigger is always <= goal.
966 func (c *gcControllerState) heapGoalInternal() (goal, minTrigger uint64) {
967         // Start with the goal calculated for gcPercent.
968         goal = c.gcPercentHeapGoal.Load()
969
970         // Check if the memory-limit-based goal is smaller, and if so, pick that.
971         if newGoal := c.memoryLimitHeapGoal(); go119MemoryLimitSupport && newGoal < goal {
972                 goal = newGoal
973         } else {
974                 // We're not limited by the memory limit goal, so perform a series of
975                 // adjustments that might move the goal forward in a variety of circumstances.
976
977                 sweepDistTrigger := c.sweepDistMinTrigger.Load()
978                 if sweepDistTrigger > goal {
979                         // Set the goal to maintain a minimum sweep distance since
980                         // the last call to commit. Note that we never want to do this
981                         // if we're in the memory limit regime, because it could push
982                         // the goal up.
983                         goal = sweepDistTrigger
984                 }
985                 // Since we ignore the sweep distance trigger in the memory
986                 // limit regime, we need to ensure we don't propagate it to
987                 // the trigger, because it could cause a violation of the
988                 // invariant that the trigger < goal.
989                 minTrigger = sweepDistTrigger
990
991                 // Ensure that the heap goal is at least a little larger than
992                 // the point at which we triggered. This may not be the case if GC
993                 // start is delayed or if the allocation that pushed gcController.heapLive
994                 // over trigger is large or if the trigger is really close to
995                 // GOGC. Assist is proportional to this distance, so enforce a
996                 // minimum distance, even if it means going over the GOGC goal
997                 // by a tiny bit.
998                 //
999                 // Ignore this if we're in the memory limit regime: we'd prefer to
1000                 // have the GC respond hard about how close we are to the goal than to
1001                 // push the goal back in such a manner that it could cause us to exceed
1002                 // the memory limit.
1003                 const minRunway = 64 << 10
1004                 if c.triggered != ^uint64(0) && goal < c.triggered+minRunway {
1005                         goal = c.triggered + minRunway
1006                 }
1007         }
1008         return
1009 }
1010
1011 // memoryLimitHeapGoal returns a heap goal derived from memoryLimit.
1012 func (c *gcControllerState) memoryLimitHeapGoal() uint64 {
1013         // Start by pulling out some values we'll need. Be careful about overflow.
1014         var heapFree, heapAlloc, mappedReady uint64
1015         for {
1016                 heapFree = c.heapFree.load()                         // Free and unscavenged memory.
1017                 heapAlloc = c.totalAlloc.Load() - c.totalFree.Load() // Heap object bytes in use.
1018                 mappedReady = c.mappedReady.Load()                   // Total unreleased mapped memory.
1019                 if heapFree+heapAlloc <= mappedReady {
1020                         break
1021                 }
1022                 // It is impossible for total unreleased mapped memory to exceed heap memory, but
1023                 // because these stats are updated independently, we may observe a partial update
1024                 // including only some values. Thus, we appear to break the invariant. However,
1025                 // this condition is necessarily transient, so just try again. In the case of a
1026                 // persistent accounting error, we'll deadlock here.
1027         }
1028
1029         // Below we compute a goal from memoryLimit. There are a few things to be aware of.
1030         // Firstly, the memoryLimit does not easily compare to the heap goal: the former
1031         // is total mapped memory by the runtime that hasn't been released, while the latter is
1032         // only heap object memory. Intuitively, the way we convert from one to the other is to
1033         // subtract everything from memoryLimit that both contributes to the memory limit (so,
1034         // ignore scavenged memory) and doesn't contain heap objects. This isn't quite what
1035         // lines up with reality, but it's a good starting point.
1036         //
1037         // In practice this computation looks like the following:
1038         //
1039         //    memoryLimit - ((mappedReady - heapFree - heapAlloc) + max(mappedReady - memoryLimit, 0)) - memoryLimitHeapGoalHeadroom
1040         //                    ^1                                    ^2                                   ^3
1041         //
1042         // Let's break this down.
1043         //
1044         // The first term (marker 1) is everything that contributes to the memory limit and isn't
1045         // or couldn't become heap objects. It represents, broadly speaking, non-heap overheads.
1046         // One oddity you may have noticed is that we also subtract out heapFree, i.e. unscavenged
1047         // memory that may contain heap objects in the future.
1048         //
1049         // Let's take a step back. In an ideal world, this term would look something like just
1050         // the heap goal. That is, we "reserve" enough space for the heap to grow to the heap
1051         // goal, and subtract out everything else. This is of course impossible; the definition
1052         // is circular! However, this impossible definition contains a key insight: the amount
1053         // we're *going* to use matters just as much as whatever we're currently using.
1054         //
1055         // Consider if the heap shrinks to 1/10th its size, leaving behind lots of free and
1056         // unscavenged memory. mappedReady - heapAlloc will be quite large, because of that free
1057         // and unscavenged memory, pushing the goal down significantly.
1058         //
1059         // heapFree is also safe to exclude from the memory limit because in the steady-state, it's
1060         // just a pool of memory for future heap allocations, and making new allocations from heapFree
1061         // memory doesn't increase overall memory use. In transient states, the scavenger and the
1062         // allocator actively manage the pool of heapFree memory to maintain the memory limit.
1063         //
1064         // The second term (marker 2) is the amount of memory we've exceeded the limit by, and is
1065         // intended to help recover from such a situation. By pushing the heap goal down, we also
1066         // push the trigger down, triggering and finishing a GC sooner in order to make room for
1067         // other memory sources. Note that since we're effectively reducing the heap goal by X bytes,
1068         // we're actually giving more than X bytes of headroom back, because the heap goal is in
1069         // terms of heap objects, but it takes more than X bytes (e.g. due to fragmentation) to store
1070         // X bytes worth of objects.
1071         //
1072         // The third term (marker 3) subtracts an additional memoryLimitHeapGoalHeadroom bytes from the
1073         // heap goal. As the name implies, this is to provide additional headroom in the face of pacing
1074         // inaccuracies. This is a fixed number of bytes because these inaccuracies disproportionately
1075         // affect small heaps: as heaps get smaller, the pacer's inputs get fuzzier. Shorter GC cycles
1076         // and less GC work means noisy external factors like the OS scheduler have a greater impact.
1077
1078         memoryLimit := uint64(c.memoryLimit.Load())
1079
1080         // Compute term 1.
1081         nonHeapMemory := mappedReady - heapFree - heapAlloc
1082
1083         // Compute term 2.
1084         var overage uint64
1085         if mappedReady > memoryLimit {
1086                 overage = mappedReady - memoryLimit
1087         }
1088
1089         if nonHeapMemory+overage >= memoryLimit {
1090                 // We're at a point where non-heap memory exceeds the memory limit on its own.
1091                 // There's honestly not much we can do here but just trigger GCs continuously
1092                 // and let the CPU limiter reign that in. Something has to give at this point.
1093                 // Set it to heapMarked, the lowest possible goal.
1094                 return c.heapMarked
1095         }
1096
1097         // Compute the goal.
1098         goal := memoryLimit - (nonHeapMemory + overage)
1099
1100         // Apply some headroom to the goal to account for pacing inaccuracies.
1101         // Be careful about small limits.
1102         if goal < memoryLimitHeapGoalHeadroom || goal-memoryLimitHeapGoalHeadroom < memoryLimitHeapGoalHeadroom {
1103                 goal = memoryLimitHeapGoalHeadroom
1104         } else {
1105                 goal = goal - memoryLimitHeapGoalHeadroom
1106         }
1107         // Don't let us go below the live heap. A heap goal below the live heap doesn't make sense.
1108         if goal < c.heapMarked {
1109                 goal = c.heapMarked
1110         }
1111         return goal
1112 }
1113
1114 const (
1115         // These constants determine the bounds on the GC trigger as a fraction
1116         // of heap bytes allocated between the start of a GC (heapLive == heapMarked)
1117         // and the end of a GC (heapLive == heapGoal).
1118         //
1119         // The constants are obscured in this way for efficiency. The denominator
1120         // of the fraction is always a power-of-two for a quick division, so that
1121         // the numerator is a single constant integer multiplication.
1122         triggerRatioDen = 64
1123
1124         // The minimum trigger constant was chosen empirically: given a sufficiently
1125         // fast/scalable allocator with 48 Ps that could drive the trigger ratio
1126         // to <0.05, this constant causes applications to retain the same peak
1127         // RSS compared to not having this allocator.
1128         minTriggerRatioNum = 45 // ~0.7
1129
1130         // The maximum trigger constant is chosen somewhat arbitrarily, but the
1131         // current constant has served us well over the years.
1132         maxTriggerRatioNum = 61 // ~0.95
1133 )
1134
1135 // trigger returns the current point at which a GC should trigger along with
1136 // the heap goal.
1137 //
1138 // The returned value may be compared against heapLive to determine whether
1139 // the GC should trigger. Thus, the GC trigger condition should be (but may
1140 // not be, in the case of small movements for efficiency) checked whenever
1141 // the heap goal may change.
1142 func (c *gcControllerState) trigger() (uint64, uint64) {
1143         goal, minTrigger := c.heapGoalInternal()
1144
1145         // Invariant: the trigger must always be less than the heap goal.
1146         //
1147         // Note that the memory limit sets a hard maximum on our heap goal,
1148         // but the live heap may grow beyond it.
1149
1150         if c.heapMarked >= goal {
1151                 // The goal should never be smaller than heapMarked, but let's be
1152                 // defensive about it. The only reasonable trigger here is one that
1153                 // causes a continuous GC cycle at heapMarked, but respect the goal
1154                 // if it came out as smaller than that.
1155                 return goal, goal
1156         }
1157
1158         // Below this point, c.heapMarked < goal.
1159
1160         // heapMarked is our absolute minimum, and it's possible the trigger
1161         // bound we get from heapGoalinternal is less than that.
1162         if minTrigger < c.heapMarked {
1163                 minTrigger = c.heapMarked
1164         }
1165
1166         // If we let the trigger go too low, then if the application
1167         // is allocating very rapidly we might end up in a situation
1168         // where we're allocating black during a nearly always-on GC.
1169         // The result of this is a growing heap and ultimately an
1170         // increase in RSS. By capping us at a point >0, we're essentially
1171         // saying that we're OK using more CPU during the GC to prevent
1172         // this growth in RSS.
1173         triggerLowerBound := uint64(((goal-c.heapMarked)/triggerRatioDen)*minTriggerRatioNum) + c.heapMarked
1174         if minTrigger < triggerLowerBound {
1175                 minTrigger = triggerLowerBound
1176         }
1177
1178         // For small heaps, set the max trigger point at maxTriggerRatio of the way
1179         // from the live heap to the heap goal. This ensures we always have *some*
1180         // headroom when the GC actually starts. For larger heaps, set the max trigger
1181         // point at the goal, minus the minimum heap size.
1182         //
1183         // This choice follows from the fact that the minimum heap size is chosen
1184         // to reflect the costs of a GC with no work to do. With a large heap but
1185         // very little scan work to perform, this gives us exactly as much runway
1186         // as we would need, in the worst case.
1187         maxTrigger := uint64(((goal-c.heapMarked)/triggerRatioDen)*maxTriggerRatioNum) + c.heapMarked
1188         if goal > defaultHeapMinimum && goal-defaultHeapMinimum > maxTrigger {
1189                 maxTrigger = goal - defaultHeapMinimum
1190         }
1191         if maxTrigger < minTrigger {
1192                 maxTrigger = minTrigger
1193         }
1194
1195         // Compute the trigger from our bounds and the runway stored by commit.
1196         var trigger uint64
1197         runway := c.runway.Load()
1198         if runway > goal {
1199                 trigger = minTrigger
1200         } else {
1201                 trigger = goal - runway
1202         }
1203         if trigger < minTrigger {
1204                 trigger = minTrigger
1205         }
1206         if trigger > maxTrigger {
1207                 trigger = maxTrigger
1208         }
1209         if trigger > goal {
1210                 print("trigger=", trigger, " heapGoal=", goal, "\n")
1211                 print("minTrigger=", minTrigger, " maxTrigger=", maxTrigger, "\n")
1212                 throw("produced a trigger greater than the heap goal")
1213         }
1214         return trigger, goal
1215 }
1216
1217 // commit recomputes all pacing parameters needed to derive the
1218 // trigger and the heap goal. Namely, the gcPercent-based heap goal,
1219 // and the amount of runway we want to give the GC this cycle.
1220 //
1221 // This can be called any time. If GC is the in the middle of a
1222 // concurrent phase, it will adjust the pacing of that phase.
1223 //
1224 // isSweepDone should be the result of calling isSweepDone(),
1225 // unless we're testing or we know we're executing during a GC cycle.
1226 //
1227 // This depends on gcPercent, gcController.heapMarked, and
1228 // gcController.heapLive. These must be up to date.
1229 //
1230 // Callers must call gcControllerState.revise after calling this
1231 // function if the GC is enabled.
1232 //
1233 // mheap_.lock must be held or the world must be stopped.
1234 func (c *gcControllerState) commit(isSweepDone bool) {
1235         if !c.test {
1236                 assertWorldStoppedOrLockHeld(&mheap_.lock)
1237         }
1238
1239         if isSweepDone {
1240                 // The sweep is done, so there aren't any restrictions on the trigger
1241                 // we need to think about.
1242                 c.sweepDistMinTrigger.Store(0)
1243         } else {
1244                 // Concurrent sweep happens in the heap growth
1245                 // from gcController.heapLive to trigger. Make sure we
1246                 // give the sweeper some runway if it doesn't have enough.
1247                 c.sweepDistMinTrigger.Store(c.heapLive.Load() + sweepMinHeapDistance)
1248         }
1249
1250         // Compute the next GC goal, which is when the allocated heap
1251         // has grown by GOGC/100 over where it started the last cycle,
1252         // plus additional runway for non-heap sources of GC work.
1253         gcPercentHeapGoal := ^uint64(0)
1254         if gcPercent := c.gcPercent.Load(); gcPercent >= 0 {
1255                 gcPercentHeapGoal = c.heapMarked + (c.heapMarked+c.lastStackScan.Load()+c.globalsScan.Load())*uint64(gcPercent)/100
1256         }
1257         // Apply the minimum heap size here. It's defined in terms of gcPercent
1258         // and is only updated by functions that call commit.
1259         if gcPercentHeapGoal < c.heapMinimum {
1260                 gcPercentHeapGoal = c.heapMinimum
1261         }
1262         c.gcPercentHeapGoal.Store(gcPercentHeapGoal)
1263
1264         // Compute the amount of runway we want the GC to have by using our
1265         // estimate of the cons/mark ratio.
1266         //
1267         // The idea is to take our expected scan work, and multiply it by
1268         // the cons/mark ratio to determine how long it'll take to complete
1269         // that scan work in terms of bytes allocated. This gives us our GC's
1270         // runway.
1271         //
1272         // However, the cons/mark ratio is a ratio of rates per CPU-second, but
1273         // here we care about the relative rates for some division of CPU
1274         // resources among the mutator and the GC.
1275         //
1276         // To summarize, we have B / cpu-ns, and we want B / ns. We get that
1277         // by multiplying by our desired division of CPU resources. We choose
1278         // to express CPU resources as GOMAPROCS*fraction. Note that because
1279         // we're working with a ratio here, we can omit the number of CPU cores,
1280         // because they'll appear in the numerator and denominator and cancel out.
1281         // As a result, this is basically just "weighing" the cons/mark ratio by
1282         // our desired division of resources.
1283         //
1284         // Furthermore, by setting the runway so that CPU resources are divided
1285         // this way, assuming that the cons/mark ratio is correct, we make that
1286         // division a reality.
1287         c.runway.Store(uint64((c.consMark * (1 - gcGoalUtilization) / (gcGoalUtilization)) * float64(c.lastHeapScan+c.lastStackScan.Load()+c.globalsScan.Load())))
1288 }
1289
1290 // setGCPercent updates gcPercent. commit must be called after.
1291 // Returns the old value of gcPercent.
1292 //
1293 // The world must be stopped, or mheap_.lock must be held.
1294 func (c *gcControllerState) setGCPercent(in int32) int32 {
1295         if !c.test {
1296                 assertWorldStoppedOrLockHeld(&mheap_.lock)
1297         }
1298
1299         out := c.gcPercent.Load()
1300         if in < 0 {
1301                 in = -1
1302         }
1303         c.heapMinimum = defaultHeapMinimum * uint64(in) / 100
1304         c.gcPercent.Store(in)
1305
1306         return out
1307 }
1308
1309 //go:linkname setGCPercent runtime/debug.setGCPercent
1310 func setGCPercent(in int32) (out int32) {
1311         // Run on the system stack since we grab the heap lock.
1312         systemstack(func() {
1313                 lock(&mheap_.lock)
1314                 out = gcController.setGCPercent(in)
1315                 gcControllerCommit()
1316                 unlock(&mheap_.lock)
1317         })
1318
1319         // If we just disabled GC, wait for any concurrent GC mark to
1320         // finish so we always return with no GC running.
1321         if in < 0 {
1322                 gcWaitOnMark(atomic.Load(&work.cycles))
1323         }
1324
1325         return out
1326 }
1327
1328 func readGOGC() int32 {
1329         p := gogetenv("GOGC")
1330         if p == "off" {
1331                 return -1
1332         }
1333         if n, ok := atoi32(p); ok {
1334                 return n
1335         }
1336         return 100
1337 }
1338
1339 // setMemoryLimit updates memoryLimit. commit must be called after
1340 // Returns the old value of memoryLimit.
1341 //
1342 // The world must be stopped, or mheap_.lock must be held.
1343 func (c *gcControllerState) setMemoryLimit(in int64) int64 {
1344         if !c.test {
1345                 assertWorldStoppedOrLockHeld(&mheap_.lock)
1346         }
1347
1348         out := c.memoryLimit.Load()
1349         if in >= 0 {
1350                 c.memoryLimit.Store(in)
1351         }
1352
1353         return out
1354 }
1355
1356 //go:linkname setMemoryLimit runtime/debug.setMemoryLimit
1357 func setMemoryLimit(in int64) (out int64) {
1358         // Run on the system stack since we grab the heap lock.
1359         systemstack(func() {
1360                 lock(&mheap_.lock)
1361                 out = gcController.setMemoryLimit(in)
1362                 if in < 0 || out == in {
1363                         // If we're just checking the value or not changing
1364                         // it, there's no point in doing the rest.
1365                         unlock(&mheap_.lock)
1366                         return
1367                 }
1368                 gcControllerCommit()
1369                 unlock(&mheap_.lock)
1370         })
1371         return out
1372 }
1373
1374 func readGOMEMLIMIT() int64 {
1375         p := gogetenv("GOMEMLIMIT")
1376         if p == "" || p == "off" {
1377                 return maxInt64
1378         }
1379         n, ok := parseByteCount(p)
1380         if !ok {
1381                 print("GOMEMLIMIT=", p, "\n")
1382                 throw("malformed GOMEMLIMIT; see `go doc runtime/debug.SetMemoryLimit`")
1383         }
1384         return n
1385 }
1386
1387 type piController struct {
1388         kp float64 // Proportional constant.
1389         ti float64 // Integral time constant.
1390         tt float64 // Reset time.
1391
1392         min, max float64 // Output boundaries.
1393
1394         // PI controller state.
1395
1396         errIntegral float64 // Integral of the error from t=0 to now.
1397
1398         // Error flags.
1399         errOverflow   bool // Set if errIntegral ever overflowed.
1400         inputOverflow bool // Set if an operation with the input overflowed.
1401 }
1402
1403 // next provides a new sample to the controller.
1404 //
1405 // input is the sample, setpoint is the desired point, and period is how much
1406 // time (in whatever unit makes the most sense) has passed since the last sample.
1407 //
1408 // Returns a new value for the variable it's controlling, and whether the operation
1409 // completed successfully. One reason this might fail is if error has been growing
1410 // in an unbounded manner, to the point of overflow.
1411 //
1412 // In the specific case of an error overflow occurs, the errOverflow field will be
1413 // set and the rest of the controller's internal state will be fully reset.
1414 func (c *piController) next(input, setpoint, period float64) (float64, bool) {
1415         // Compute the raw output value.
1416         prop := c.kp * (setpoint - input)
1417         rawOutput := prop + c.errIntegral
1418
1419         // Clamp rawOutput into output.
1420         output := rawOutput
1421         if isInf(output) || isNaN(output) {
1422                 // The input had a large enough magnitude that either it was already
1423                 // overflowed, or some operation with it overflowed.
1424                 // Set a flag and reset. That's the safest thing to do.
1425                 c.reset()
1426                 c.inputOverflow = true
1427                 return c.min, false
1428         }
1429         if output < c.min {
1430                 output = c.min
1431         } else if output > c.max {
1432                 output = c.max
1433         }
1434
1435         // Update the controller's state.
1436         if c.ti != 0 && c.tt != 0 {
1437                 c.errIntegral += (c.kp*period/c.ti)*(setpoint-input) + (period/c.tt)*(output-rawOutput)
1438                 if isInf(c.errIntegral) || isNaN(c.errIntegral) {
1439                         // So much error has accumulated that we managed to overflow.
1440                         // The assumptions around the controller have likely broken down.
1441                         // Set a flag and reset. That's the safest thing to do.
1442                         c.reset()
1443                         c.errOverflow = true
1444                         return c.min, false
1445                 }
1446         }
1447         return output, true
1448 }
1449
1450 // reset resets the controller state, except for controller error flags.
1451 func (c *piController) reset() {
1452         c.errIntegral = 0
1453 }
1454
1455 // addIdleMarkWorker attempts to add a new idle mark worker.
1456 //
1457 // If this returns true, the caller must become an idle mark worker unless
1458 // there's no background mark worker goroutines in the pool. This case is
1459 // harmless because there are already background mark workers running.
1460 // If this returns false, the caller must NOT become an idle mark worker.
1461 //
1462 // nosplit because it may be called without a P.
1463 //
1464 //go:nosplit
1465 func (c *gcControllerState) addIdleMarkWorker() bool {
1466         for {
1467                 old := c.idleMarkWorkers.Load()
1468                 n, max := int32(old&uint64(^uint32(0))), int32(old>>32)
1469                 if n >= max {
1470                         // See the comment on idleMarkWorkers for why
1471                         // n > max is tolerated.
1472                         return false
1473                 }
1474                 if n < 0 {
1475                         print("n=", n, " max=", max, "\n")
1476                         throw("negative idle mark workers")
1477                 }
1478                 new := uint64(uint32(n+1)) | (uint64(max) << 32)
1479                 if c.idleMarkWorkers.CompareAndSwap(old, new) {
1480                         return true
1481                 }
1482         }
1483 }
1484
1485 // needIdleMarkWorker is a hint as to whether another idle mark worker is needed.
1486 //
1487 // The caller must still call addIdleMarkWorker to become one. This is mainly
1488 // useful for a quick check before an expensive operation.
1489 //
1490 // nosplit because it may be called without a P.
1491 //
1492 //go:nosplit
1493 func (c *gcControllerState) needIdleMarkWorker() bool {
1494         p := c.idleMarkWorkers.Load()
1495         n, max := int32(p&uint64(^uint32(0))), int32(p>>32)
1496         return n < max
1497 }
1498
1499 // removeIdleMarkWorker must be called when an new idle mark worker stops executing.
1500 func (c *gcControllerState) removeIdleMarkWorker() {
1501         for {
1502                 old := c.idleMarkWorkers.Load()
1503                 n, max := int32(old&uint64(^uint32(0))), int32(old>>32)
1504                 if n-1 < 0 {
1505                         print("n=", n, " max=", max, "\n")
1506                         throw("negative idle mark workers")
1507                 }
1508                 new := uint64(uint32(n-1)) | (uint64(max) << 32)
1509                 if c.idleMarkWorkers.CompareAndSwap(old, new) {
1510                         return
1511                 }
1512         }
1513 }
1514
1515 // setMaxIdleMarkWorkers sets the maximum number of idle mark workers allowed.
1516 //
1517 // This method is optimistic in that it does not wait for the number of
1518 // idle mark workers to reduce to max before returning; it assumes the workers
1519 // will deschedule themselves.
1520 func (c *gcControllerState) setMaxIdleMarkWorkers(max int32) {
1521         for {
1522                 old := c.idleMarkWorkers.Load()
1523                 n := int32(old & uint64(^uint32(0)))
1524                 if n < 0 {
1525                         print("n=", n, " max=", max, "\n")
1526                         throw("negative idle mark workers")
1527                 }
1528                 new := uint64(uint32(n)) | (uint64(max) << 32)
1529                 if c.idleMarkWorkers.CompareAndSwap(old, new) {
1530                         return
1531                 }
1532         }
1533 }
1534
1535 // gcControllerCommit is gcController.commit, but passes arguments from live
1536 // (non-test) data. It also updates any consumers of the GC pacing, such as
1537 // sweep pacing and the background scavenger.
1538 //
1539 // Calls gcController.commit.
1540 //
1541 // The heap lock must be held, so this must be executed on the system stack.
1542 //
1543 //go:systemstack
1544 func gcControllerCommit() {
1545         assertWorldStoppedOrLockHeld(&mheap_.lock)
1546
1547         gcController.commit(isSweepDone())
1548
1549         // Update mark pacing.
1550         if gcphase != _GCoff {
1551                 gcController.revise()
1552         }
1553
1554         // TODO(mknyszek): This isn't really accurate any longer because the heap
1555         // goal is computed dynamically. Still useful to snapshot, but not as useful.
1556         if trace.enabled {
1557                 traceHeapGoal()
1558         }
1559
1560         trigger, heapGoal := gcController.trigger()
1561         gcPaceSweeper(trigger)
1562         gcPaceScavenger(gcController.memoryLimit.Load(), heapGoal, gcController.lastHeapGoal)
1563 }