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