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