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