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