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