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