]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/mgcpacer.go
runtime: track the amount of scannable allocated stack for the GC pacer
[gostls13.git] / src / runtime / mgcpacer.go
1 // Copyright 2021 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package runtime
6
7 import (
8         "internal/cpu"
9         "runtime/internal/atomic"
10         "unsafe"
11 )
12
13 const (
14         // gcGoalUtilization is the goal CPU utilization for
15         // marking as a fraction of GOMAXPROCS.
16         gcGoalUtilization = 0.30
17
18         // gcBackgroundUtilization is the fixed CPU utilization for background
19         // marking. It must be <= gcGoalUtilization. The difference between
20         // gcGoalUtilization and gcBackgroundUtilization will be made up by
21         // mark assists. The scheduler will aim to use within 50% of this
22         // goal.
23         //
24         // Setting this to < gcGoalUtilization avoids saturating the trigger
25         // feedback controller when there are no assists, which allows it to
26         // better control CPU and heap growth. However, the larger the gap,
27         // the more mutator assists are expected to happen, which impact
28         // mutator latency.
29         gcBackgroundUtilization = 0.25
30
31         // gcCreditSlack is the amount of scan work credit that can
32         // accumulate locally before updating gcController.scanWork and,
33         // optionally, gcController.bgScanCredit. Lower values give a more
34         // accurate assist ratio and make it more likely that assists will
35         // successfully steal background credit. Higher values reduce memory
36         // contention.
37         gcCreditSlack = 2000
38
39         // gcAssistTimeSlack is the nanoseconds of mutator assist time that
40         // can accumulate on a P before updating gcController.assistTime.
41         gcAssistTimeSlack = 5000
42
43         // gcOverAssistWork determines how many extra units of scan work a GC
44         // assist does when an assist happens. This amortizes the cost of an
45         // assist by pre-paying for this many bytes of future allocations.
46         gcOverAssistWork = 64 << 10
47
48         // defaultHeapMinimum is the value of heapMinimum for GOGC==100.
49         defaultHeapMinimum = 4 << 20
50
51         // scannableStackSizeSlack is the bytes of stack space allocated or freed
52         // that can accumulate on a P before updating gcController.stackSize.
53         scannableStackSizeSlack = 8 << 10
54 )
55
56 func init() {
57         if offset := unsafe.Offsetof(gcController.heapLive); offset%8 != 0 {
58                 println(offset)
59                 throw("gcController.heapLive not aligned to 8 bytes")
60         }
61 }
62
63 // gcController implements the GC pacing controller that determines
64 // when to trigger concurrent garbage collection and how much marking
65 // work to do in mutator assists and background marking.
66 //
67 // It uses a feedback control algorithm to adjust the gcController.trigger
68 // trigger based on the heap growth and GC CPU utilization each cycle.
69 // This algorithm optimizes for heap growth to match GOGC and for CPU
70 // utilization between assist and background marking to be 25% of
71 // GOMAXPROCS. The high-level design of this algorithm is documented
72 // at https://golang.org/s/go15gcpacing.
73 //
74 // All fields of gcController are used only during a single mark
75 // cycle.
76 var gcController gcControllerState
77
78 type gcControllerState struct {
79         // Initialized from $GOGC. GOGC=off means no GC.
80         //
81         // Updated atomically with mheap_.lock held or during a STW.
82         // Safe to read atomically at any time, or non-atomically with
83         // mheap_.lock or STW.
84         gcPercent int32
85
86         _ uint32 // padding so following 64-bit values are 8-byte aligned
87
88         // heapMinimum is the minimum heap size at which to trigger GC.
89         // For small heaps, this overrides the usual GOGC*live set rule.
90         //
91         // When there is a very small live set but a lot of allocation, simply
92         // collecting when the heap reaches GOGC*live results in many GC
93         // cycles and high total per-GC overhead. This minimum amortizes this
94         // per-GC overhead while keeping the heap reasonably small.
95         //
96         // During initialization this is set to 4MB*GOGC/100. In the case of
97         // GOGC==0, this will set heapMinimum to 0, resulting in constant
98         // collection even when the heap size is small, which is useful for
99         // debugging.
100         heapMinimum uint64
101
102         // triggerRatio is the heap growth ratio that triggers marking.
103         //
104         // E.g., if this is 0.6, then GC should start when the live
105         // heap has reached 1.6 times the heap size marked by the
106         // previous cycle. This should be ≤ GOGC/100 so the trigger
107         // heap size is less than the goal heap size. This is set
108         // during mark termination for the next cycle's trigger.
109         //
110         // Protected by mheap_.lock or a STW.
111         triggerRatio float64
112
113         // trigger is the heap size that triggers marking.
114         //
115         // When heapLive ≥ trigger, the mark phase will start.
116         // This is also the heap size by which proportional sweeping
117         // must be complete.
118         //
119         // This is computed from triggerRatio during mark termination
120         // for the next cycle's trigger.
121         //
122         // Protected by mheap_.lock or a STW.
123         trigger uint64
124
125         // heapGoal is the goal heapLive for when next GC ends.
126         // Set to ^uint64(0) if disabled.
127         //
128         // Read and written atomically, unless the world is stopped.
129         heapGoal uint64
130
131         // lastHeapGoal is the value of heapGoal for the previous GC.
132         // Note that this is distinct from the last value heapGoal had,
133         // because it could change if e.g. gcPercent changes.
134         //
135         // Read and written with the world stopped or with mheap_.lock held.
136         lastHeapGoal uint64
137
138         // heapLive is the number of bytes considered live by the GC.
139         // That is: retained by the most recent GC plus allocated
140         // since then. heapLive ≤ memstats.heapAlloc, since heapAlloc includes
141         // unmarked objects that have not yet been swept (and hence goes up as we
142         // allocate and down as we sweep) while heapLive excludes these
143         // objects (and hence only goes up between GCs).
144         //
145         // This is updated atomically without locking. To reduce
146         // contention, this is updated only when obtaining a span from
147         // an mcentral and at this point it counts all of the
148         // unallocated slots in that span (which will be allocated
149         // before that mcache obtains another span from that
150         // mcentral). Hence, it slightly overestimates the "true" live
151         // heap size. It's better to overestimate than to
152         // underestimate because 1) this triggers the GC earlier than
153         // necessary rather than potentially too late and 2) this
154         // leads to a conservative GC rate rather than a GC rate that
155         // is potentially too low.
156         //
157         // Reads should likewise be atomic (or during STW).
158         //
159         // Whenever this is updated, call traceHeapAlloc() and
160         // this gcControllerState's revise() method.
161         heapLive uint64
162
163         // heapScan is the number of bytes of "scannable" heap. This
164         // is the live heap (as counted by heapLive), but omitting
165         // no-scan objects and no-scan tails of objects.
166         //
167         // Whenever this is updated, call this gcControllerState's
168         // revise() method.
169         //
170         // Read and written atomically or with the world stopped.
171         heapScan uint64
172
173         // stackScan is a snapshot of scannableStackSize taken at each GC
174         // STW pause and is used in pacing decisions.
175         //
176         // Updated only while the world is stopped.
177         stackScan uint64
178
179         // scannableStackSize is the amount of allocated goroutine stack space in
180         // use by goroutines.
181         //
182         // Read and updated atomically.
183         scannableStackSize uint64
184
185         // heapMarked is the number of bytes marked by the previous
186         // GC. After mark termination, heapLive == heapMarked, but
187         // unlike heapLive, heapMarked does not change until the
188         // next mark termination.
189         heapMarked uint64
190
191         // scanWork is the total scan work performed this cycle. This
192         // is updated atomically during the cycle. Updates occur in
193         // bounded batches, since it is both written and read
194         // throughout the cycle. At the end of the cycle, this is how
195         // much of the retained heap is scannable.
196         //
197         // Currently this is the bytes of heap scanned. For most uses,
198         // this is an opaque unit of work, but for estimation the
199         // definition is important.
200         scanWork int64
201
202         // bgScanCredit is the scan work credit accumulated by the
203         // concurrent background scan. This credit is accumulated by
204         // the background scan and stolen by mutator assists. This is
205         // updated atomically. Updates occur in bounded batches, since
206         // it is both written and read throughout the cycle.
207         bgScanCredit int64
208
209         // assistTime is the nanoseconds spent in mutator assists
210         // during this cycle. This is updated atomically. Updates
211         // occur in bounded batches, since it is both written and read
212         // throughout the cycle.
213         assistTime int64
214
215         // dedicatedMarkTime is the nanoseconds spent in dedicated
216         // mark workers during this cycle. This is updated atomically
217         // at the end of the concurrent mark phase.
218         dedicatedMarkTime int64
219
220         // fractionalMarkTime is the nanoseconds spent in the
221         // fractional mark worker during this cycle. This is updated
222         // atomically throughout the cycle and will be up-to-date if
223         // the fractional mark worker is not currently running.
224         fractionalMarkTime int64
225
226         // idleMarkTime is the nanoseconds spent in idle marking
227         // during this cycle. This is updated atomically throughout
228         // the cycle.
229         idleMarkTime int64
230
231         // markStartTime is the absolute start time in nanoseconds
232         // that assists and background mark workers started.
233         markStartTime int64
234
235         // dedicatedMarkWorkersNeeded is the number of dedicated mark
236         // workers that need to be started. This is computed at the
237         // beginning of each cycle and decremented atomically as
238         // dedicated mark workers get started.
239         dedicatedMarkWorkersNeeded int64
240
241         // assistWorkPerByte is the ratio of scan work to allocated
242         // bytes that should be performed by mutator assists. This is
243         // computed at the beginning of each cycle and updated every
244         // time heapScan is updated.
245         assistWorkPerByte atomic.Float64
246
247         // assistBytesPerWork is 1/assistWorkPerByte.
248         //
249         // Note that because this is read and written independently
250         // from assistWorkPerByte users may notice a skew between
251         // the two values, and such a state should be safe.
252         assistBytesPerWork atomic.Float64
253
254         // fractionalUtilizationGoal is the fraction of wall clock
255         // time that should be spent in the fractional mark worker on
256         // each P that isn't running a dedicated worker.
257         //
258         // For example, if the utilization goal is 25% and there are
259         // no dedicated workers, this will be 0.25. If the goal is
260         // 25%, there is one dedicated worker, and GOMAXPROCS is 5,
261         // this will be 0.05 to make up the missing 5%.
262         //
263         // If this is zero, no fractional workers are needed.
264         fractionalUtilizationGoal float64
265
266         _ cpu.CacheLinePad
267 }
268
269 func (c *gcControllerState) init(gcPercent int32) {
270         c.heapMinimum = defaultHeapMinimum
271
272         // Set a reasonable initial GC trigger.
273         c.triggerRatio = 7 / 8.0
274
275         // Fake a heapMarked value so it looks like a trigger at
276         // heapMinimum is the appropriate growth from heapMarked.
277         // This will go into computing the initial GC goal.
278         c.heapMarked = uint64(float64(c.heapMinimum) / (1 + c.triggerRatio))
279
280         // This will also compute and set the GC trigger and goal.
281         c.setGCPercent(gcPercent)
282 }
283
284 // startCycle resets the GC controller's state and computes estimates
285 // for a new GC cycle. The caller must hold worldsema and the world
286 // must be stopped.
287 func (c *gcControllerState) startCycle(markStartTime int64) {
288         c.scanWork = 0
289         c.bgScanCredit = 0
290         c.assistTime = 0
291         c.dedicatedMarkTime = 0
292         c.fractionalMarkTime = 0
293         c.idleMarkTime = 0
294         c.markStartTime = markStartTime
295         c.stackScan = atomic.Load64(&c.scannableStackSize)
296
297         // Ensure that the heap goal is at least a little larger than
298         // the current live heap size. This may not be the case if GC
299         // start is delayed or if the allocation that pushed gcController.heapLive
300         // over trigger is large or if the trigger is really close to
301         // GOGC. Assist is proportional to this distance, so enforce a
302         // minimum distance, even if it means going over the GOGC goal
303         // by a tiny bit.
304         if c.heapGoal < c.heapLive+1024*1024 {
305                 c.heapGoal = c.heapLive + 1024*1024
306         }
307
308         // Compute the background mark utilization goal. In general,
309         // this may not come out exactly. We round the number of
310         // dedicated workers so that the utilization is closest to
311         // 25%. For small GOMAXPROCS, this would introduce too much
312         // error, so we add fractional workers in that case.
313         totalUtilizationGoal := float64(gomaxprocs) * gcBackgroundUtilization
314         c.dedicatedMarkWorkersNeeded = int64(totalUtilizationGoal + 0.5)
315         utilError := float64(c.dedicatedMarkWorkersNeeded)/totalUtilizationGoal - 1
316         const maxUtilError = 0.3
317         if utilError < -maxUtilError || utilError > maxUtilError {
318                 // Rounding put us more than 30% off our goal. With
319                 // gcBackgroundUtilization of 25%, this happens for
320                 // GOMAXPROCS<=3 or GOMAXPROCS=6. Enable fractional
321                 // workers to compensate.
322                 if float64(c.dedicatedMarkWorkersNeeded) > totalUtilizationGoal {
323                         // Too many dedicated workers.
324                         c.dedicatedMarkWorkersNeeded--
325                 }
326                 c.fractionalUtilizationGoal = (totalUtilizationGoal - float64(c.dedicatedMarkWorkersNeeded)) / float64(gomaxprocs)
327         } else {
328                 c.fractionalUtilizationGoal = 0
329         }
330
331         // In STW mode, we just want dedicated workers.
332         if debug.gcstoptheworld > 0 {
333                 c.dedicatedMarkWorkersNeeded = int64(gomaxprocs)
334                 c.fractionalUtilizationGoal = 0
335         }
336
337         // Clear per-P state
338         for _, p := range allp {
339                 p.gcAssistTime = 0
340                 p.gcFractionalMarkTime = 0
341         }
342
343         // Compute initial values for controls that are updated
344         // throughout the cycle.
345         c.revise()
346
347         if debug.gcpacertrace > 0 {
348                 assistRatio := c.assistWorkPerByte.Load()
349                 print("pacer: assist ratio=", assistRatio,
350                         " (scan ", gcController.heapScan>>20, " MB in ",
351                         work.initialHeapLive>>20, "->",
352                         c.heapGoal>>20, " MB)",
353                         " workers=", c.dedicatedMarkWorkersNeeded,
354                         "+", c.fractionalUtilizationGoal, "\n")
355         }
356 }
357
358 // revise updates the assist ratio during the GC cycle to account for
359 // improved estimates. This should be called whenever gcController.heapScan,
360 // gcController.heapLive, or gcController.heapGoal is updated. It is safe to
361 // call concurrently, but it may race with other calls to revise.
362 //
363 // The result of this race is that the two assist ratio values may not line
364 // up or may be stale. In practice this is OK because the assist ratio
365 // moves slowly throughout a GC cycle, and the assist ratio is a best-effort
366 // heuristic anyway. Furthermore, no part of the heuristic depends on
367 // the two assist ratio values being exact reciprocals of one another, since
368 // the two values are used to convert values from different sources.
369 //
370 // The worst case result of this raciness is that we may miss a larger shift
371 // in the ratio (say, if we decide to pace more aggressively against the
372 // hard heap goal) but even this "hard goal" is best-effort (see #40460).
373 // The dedicated GC should ensure we don't exceed the hard goal by too much
374 // in the rare case we do exceed it.
375 //
376 // It should only be called when gcBlackenEnabled != 0 (because this
377 // is when assists are enabled and the necessary statistics are
378 // available).
379 func (c *gcControllerState) revise() {
380         gcPercent := atomic.Loadint32(&c.gcPercent)
381         if gcPercent < 0 {
382                 // If GC is disabled but we're running a forced GC,
383                 // act like GOGC is huge for the below calculations.
384                 gcPercent = 100000
385         }
386         live := atomic.Load64(&c.heapLive)
387         scan := atomic.Load64(&c.heapScan)
388         work := atomic.Loadint64(&c.scanWork)
389
390         // Assume we're under the soft goal. Pace GC to complete at
391         // heapGoal assuming the heap is in steady-state.
392         heapGoal := int64(atomic.Load64(&c.heapGoal))
393
394         // Compute the expected scan work remaining.
395         //
396         // This is estimated based on the expected
397         // steady-state scannable heap. For example, with
398         // GOGC=100, only half of the scannable heap is
399         // expected to be live, so that's what we target.
400         //
401         // (This is a float calculation to avoid overflowing on
402         // 100*heapScan.)
403         scanWorkExpected := int64(float64(scan) * 100 / float64(100+gcPercent))
404
405         if int64(live) > heapGoal || work > scanWorkExpected {
406                 // We're past the soft goal, or we've already done more scan
407                 // work than we expected. Pace GC so that in the worst case it
408                 // will complete by the hard goal.
409                 const maxOvershoot = 1.1
410                 heapGoal = int64(float64(heapGoal) * maxOvershoot)
411
412                 // Compute the upper bound on the scan work remaining.
413                 scanWorkExpected = int64(scan)
414         }
415
416         // Compute the remaining scan work estimate.
417         //
418         // Note that we currently count allocations during GC as both
419         // scannable heap (heapScan) and scan work completed
420         // (scanWork), so allocation will change this difference
421         // slowly in the soft regime and not at all in the hard
422         // regime.
423         scanWorkRemaining := scanWorkExpected - work
424         if scanWorkRemaining < 1000 {
425                 // We set a somewhat arbitrary lower bound on
426                 // remaining scan work since if we aim a little high,
427                 // we can miss by a little.
428                 //
429                 // We *do* need to enforce that this is at least 1,
430                 // since marking is racy and double-scanning objects
431                 // may legitimately make the remaining scan work
432                 // negative, even in the hard goal regime.
433                 scanWorkRemaining = 1000
434         }
435
436         // Compute the heap distance remaining.
437         heapRemaining := heapGoal - int64(live)
438         if heapRemaining <= 0 {
439                 // This shouldn't happen, but if it does, avoid
440                 // dividing by zero or setting the assist negative.
441                 heapRemaining = 1
442         }
443
444         // Compute the mutator assist ratio so by the time the mutator
445         // allocates the remaining heap bytes up to heapGoal, it will
446         // have done (or stolen) the remaining amount of scan work.
447         // Note that the assist ratio values are updated atomically
448         // but not together. This means there may be some degree of
449         // skew between the two values. This is generally OK as the
450         // values shift relatively slowly over the course of a GC
451         // cycle.
452         assistWorkPerByte := float64(scanWorkRemaining) / float64(heapRemaining)
453         assistBytesPerWork := float64(heapRemaining) / float64(scanWorkRemaining)
454         c.assistWorkPerByte.Store(assistWorkPerByte)
455         c.assistBytesPerWork.Store(assistBytesPerWork)
456 }
457
458 // endCycle computes the trigger ratio for the next cycle.
459 // userForced indicates whether the current GC cycle was forced
460 // by the application.
461 func (c *gcControllerState) endCycle(userForced bool) float64 {
462         // Record last heap goal for the scavenger.
463         // We'll be updating the heap goal soon.
464         gcController.lastHeapGoal = gcController.heapGoal
465
466         if userForced {
467                 // Forced GC means this cycle didn't start at the
468                 // trigger, so where it finished isn't good
469                 // information about how to adjust the trigger.
470                 // Just leave it where it is.
471                 return c.triggerRatio
472         }
473
474         // Proportional response gain for the trigger controller. Must
475         // be in [0, 1]. Lower values smooth out transient effects but
476         // take longer to respond to phase changes. Higher values
477         // react to phase changes quickly, but are more affected by
478         // transient changes. Values near 1 may be unstable.
479         const triggerGain = 0.5
480
481         // Compute next cycle trigger ratio. First, this computes the
482         // "error" for this cycle; that is, how far off the trigger
483         // was from what it should have been, accounting for both heap
484         // growth and GC CPU utilization. We compute the actual heap
485         // growth during this cycle and scale that by how far off from
486         // the goal CPU utilization we were (to estimate the heap
487         // growth if we had the desired CPU utilization). The
488         // difference between this estimate and the GOGC-based goal
489         // heap growth is the error.
490         goalGrowthRatio := c.effectiveGrowthRatio()
491         actualGrowthRatio := float64(c.heapLive)/float64(c.heapMarked) - 1
492         assistDuration := nanotime() - c.markStartTime
493
494         // Assume background mark hit its utilization goal.
495         utilization := gcBackgroundUtilization
496         // Add assist utilization; avoid divide by zero.
497         if assistDuration > 0 {
498                 utilization += float64(c.assistTime) / float64(assistDuration*int64(gomaxprocs))
499         }
500
501         triggerError := goalGrowthRatio - c.triggerRatio - utilization/gcGoalUtilization*(actualGrowthRatio-c.triggerRatio)
502
503         // Finally, we adjust the trigger for next time by this error,
504         // damped by the proportional gain.
505         triggerRatio := c.triggerRatio + triggerGain*triggerError
506
507         if debug.gcpacertrace > 0 {
508                 // Print controller state in terms of the design
509                 // document.
510                 H_m_prev := c.heapMarked
511                 h_t := c.triggerRatio
512                 H_T := c.trigger
513                 h_a := actualGrowthRatio
514                 H_a := c.heapLive
515                 h_g := goalGrowthRatio
516                 H_g := int64(float64(H_m_prev) * (1 + h_g))
517                 u_a := utilization
518                 u_g := gcGoalUtilization
519                 W_a := c.scanWork
520                 print("pacer: H_m_prev=", H_m_prev,
521                         " h_t=", h_t, " H_T=", H_T,
522                         " h_a=", h_a, " H_a=", H_a,
523                         " h_g=", h_g, " H_g=", H_g,
524                         " u_a=", u_a, " u_g=", u_g,
525                         " W_a=", W_a,
526                         " goalΔ=", goalGrowthRatio-h_t,
527                         " actualΔ=", h_a-h_t,
528                         " u_a/u_g=", u_a/u_g,
529                         "\n")
530         }
531
532         return triggerRatio
533 }
534
535 // enlistWorker encourages another dedicated mark worker to start on
536 // another P if there are spare worker slots. It is used by putfull
537 // when more work is made available.
538 //
539 //go:nowritebarrier
540 func (c *gcControllerState) enlistWorker() {
541         // If there are idle Ps, wake one so it will run an idle worker.
542         // NOTE: This is suspected of causing deadlocks. See golang.org/issue/19112.
543         //
544         //      if atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 {
545         //              wakep()
546         //              return
547         //      }
548
549         // There are no idle Ps. If we need more dedicated workers,
550         // try to preempt a running P so it will switch to a worker.
551         if c.dedicatedMarkWorkersNeeded <= 0 {
552                 return
553         }
554         // Pick a random other P to preempt.
555         if gomaxprocs <= 1 {
556                 return
557         }
558         gp := getg()
559         if gp == nil || gp.m == nil || gp.m.p == 0 {
560                 return
561         }
562         myID := gp.m.p.ptr().id
563         for tries := 0; tries < 5; tries++ {
564                 id := int32(fastrandn(uint32(gomaxprocs - 1)))
565                 if id >= myID {
566                         id++
567                 }
568                 p := allp[id]
569                 if p.status != _Prunning {
570                         continue
571                 }
572                 if preemptone(p) {
573                         return
574                 }
575         }
576 }
577
578 // findRunnableGCWorker returns a background mark worker for _p_ if it
579 // should be run. This must only be called when gcBlackenEnabled != 0.
580 func (c *gcControllerState) findRunnableGCWorker(_p_ *p) *g {
581         if gcBlackenEnabled == 0 {
582                 throw("gcControllerState.findRunnable: blackening not enabled")
583         }
584
585         if !gcMarkWorkAvailable(_p_) {
586                 // No work to be done right now. This can happen at
587                 // the end of the mark phase when there are still
588                 // assists tapering off. Don't bother running a worker
589                 // now because it'll just return immediately.
590                 return nil
591         }
592
593         // Grab a worker before we commit to running below.
594         node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
595         if node == nil {
596                 // There is at least one worker per P, so normally there are
597                 // enough workers to run on all Ps, if necessary. However, once
598                 // a worker enters gcMarkDone it may park without rejoining the
599                 // pool, thus freeing a P with no corresponding worker.
600                 // gcMarkDone never depends on another worker doing work, so it
601                 // is safe to simply do nothing here.
602                 //
603                 // If gcMarkDone bails out without completing the mark phase,
604                 // it will always do so with queued global work. Thus, that P
605                 // will be immediately eligible to re-run the worker G it was
606                 // just using, ensuring work can complete.
607                 return nil
608         }
609
610         decIfPositive := func(ptr *int64) bool {
611                 for {
612                         v := atomic.Loadint64(ptr)
613                         if v <= 0 {
614                                 return false
615                         }
616
617                         if atomic.Casint64(ptr, v, v-1) {
618                                 return true
619                         }
620                 }
621         }
622
623         if decIfPositive(&c.dedicatedMarkWorkersNeeded) {
624                 // This P is now dedicated to marking until the end of
625                 // the concurrent mark phase.
626                 _p_.gcMarkWorkerMode = gcMarkWorkerDedicatedMode
627         } else if c.fractionalUtilizationGoal == 0 {
628                 // No need for fractional workers.
629                 gcBgMarkWorkerPool.push(&node.node)
630                 return nil
631         } else {
632                 // Is this P behind on the fractional utilization
633                 // goal?
634                 //
635                 // This should be kept in sync with pollFractionalWorkerExit.
636                 delta := nanotime() - c.markStartTime
637                 if delta > 0 && float64(_p_.gcFractionalMarkTime)/float64(delta) > c.fractionalUtilizationGoal {
638                         // Nope. No need to run a fractional worker.
639                         gcBgMarkWorkerPool.push(&node.node)
640                         return nil
641                 }
642                 // Run a fractional worker.
643                 _p_.gcMarkWorkerMode = gcMarkWorkerFractionalMode
644         }
645
646         // Run the background mark worker.
647         gp := node.gp.ptr()
648         casgstatus(gp, _Gwaiting, _Grunnable)
649         if trace.enabled {
650                 traceGoUnpark(gp, 0)
651         }
652         return gp
653 }
654
655 // resetLive sets up the controller state for the next mark phase after the end
656 // of the previous one. Must be called after endCycle and before commit, before
657 // the world is started.
658 //
659 // The world must be stopped.
660 func (c *gcControllerState) resetLive(bytesMarked uint64) {
661         c.heapMarked = bytesMarked
662         c.heapLive = bytesMarked
663         c.heapScan = uint64(c.scanWork)
664
665         // heapLive was updated, so emit a trace event.
666         if trace.enabled {
667                 traceHeapAlloc()
668         }
669 }
670
671 // logWorkTime updates mark work accounting in the controller by a duration of
672 // work in nanoseconds.
673 //
674 // Safe to execute at any time.
675 func (c *gcControllerState) logWorkTime(mode gcMarkWorkerMode, duration int64) {
676         switch mode {
677         case gcMarkWorkerDedicatedMode:
678                 atomic.Xaddint64(&c.dedicatedMarkTime, duration)
679                 atomic.Xaddint64(&c.dedicatedMarkWorkersNeeded, 1)
680         case gcMarkWorkerFractionalMode:
681                 atomic.Xaddint64(&c.fractionalMarkTime, duration)
682         case gcMarkWorkerIdleMode:
683                 atomic.Xaddint64(&c.idleMarkTime, duration)
684         default:
685                 throw("logWorkTime: unknown mark worker mode")
686         }
687 }
688
689 func (c *gcControllerState) update(dHeapLive, dHeapScan int64) {
690         if dHeapLive != 0 {
691                 atomic.Xadd64(&gcController.heapLive, dHeapLive)
692                 if trace.enabled {
693                         // gcController.heapLive changed.
694                         traceHeapAlloc()
695                 }
696         }
697         if dHeapScan != 0 {
698                 atomic.Xadd64(&gcController.heapScan, dHeapScan)
699         }
700         if gcBlackenEnabled != 0 {
701                 // gcController.heapLive and heapScan changed.
702                 c.revise()
703         }
704 }
705
706 func (c *gcControllerState) addScannableStack(pp *p, amount int64) {
707         if pp == nil {
708                 atomic.Xadd64(&c.scannableStackSize, amount)
709                 return
710         }
711         pp.scannableStackSizeDelta += amount
712         if pp.scannableStackSizeDelta >= scannableStackSizeSlack || pp.scannableStackSizeDelta <= -scannableStackSizeSlack {
713                 atomic.Xadd64(&c.scannableStackSize, pp.scannableStackSizeDelta)
714                 pp.scannableStackSizeDelta = 0
715         }
716 }
717
718 // commit sets the trigger ratio and updates everything
719 // derived from it: the absolute trigger, the heap goal, mark pacing,
720 // and sweep pacing.
721 //
722 // This can be called any time. If GC is the in the middle of a
723 // concurrent phase, it will adjust the pacing of that phase.
724 //
725 // This depends on gcPercent, gcController.heapMarked, and
726 // gcController.heapLive. These must be up to date.
727 //
728 // mheap_.lock must be held or the world must be stopped.
729 func (c *gcControllerState) commit(triggerRatio float64) {
730         assertWorldStoppedOrLockHeld(&mheap_.lock)
731
732         // Compute the next GC goal, which is when the allocated heap
733         // has grown by GOGC/100 over the heap marked by the last
734         // cycle.
735         goal := ^uint64(0)
736         if c.gcPercent >= 0 {
737                 goal = c.heapMarked + c.heapMarked*uint64(c.gcPercent)/100
738         }
739
740         // Set the trigger ratio, capped to reasonable bounds.
741         if c.gcPercent >= 0 {
742                 scalingFactor := float64(c.gcPercent) / 100
743                 // Ensure there's always a little margin so that the
744                 // mutator assist ratio isn't infinity.
745                 maxTriggerRatio := 0.95 * scalingFactor
746                 if triggerRatio > maxTriggerRatio {
747                         triggerRatio = maxTriggerRatio
748                 }
749
750                 // If we let triggerRatio go too low, then if the application
751                 // is allocating very rapidly we might end up in a situation
752                 // where we're allocating black during a nearly always-on GC.
753                 // The result of this is a growing heap and ultimately an
754                 // increase in RSS. By capping us at a point >0, we're essentially
755                 // saying that we're OK using more CPU during the GC to prevent
756                 // this growth in RSS.
757                 //
758                 // The current constant was chosen empirically: given a sufficiently
759                 // fast/scalable allocator with 48 Ps that could drive the trigger ratio
760                 // to <0.05, this constant causes applications to retain the same peak
761                 // RSS compared to not having this allocator.
762                 minTriggerRatio := 0.6 * scalingFactor
763                 if triggerRatio < minTriggerRatio {
764                         triggerRatio = minTriggerRatio
765                 }
766         } else if triggerRatio < 0 {
767                 // gcPercent < 0, so just make sure we're not getting a negative
768                 // triggerRatio. This case isn't expected to happen in practice,
769                 // and doesn't really matter because if gcPercent < 0 then we won't
770                 // ever consume triggerRatio further on in this function, but let's
771                 // just be defensive here; the triggerRatio being negative is almost
772                 // certainly undesirable.
773                 triggerRatio = 0
774         }
775         c.triggerRatio = triggerRatio
776
777         // Compute the absolute GC trigger from the trigger ratio.
778         //
779         // We trigger the next GC cycle when the allocated heap has
780         // grown by the trigger ratio over the marked heap size.
781         trigger := ^uint64(0)
782         if c.gcPercent >= 0 {
783                 trigger = uint64(float64(c.heapMarked) * (1 + triggerRatio))
784                 // Don't trigger below the minimum heap size.
785                 minTrigger := c.heapMinimum
786                 if !isSweepDone() {
787                         // Concurrent sweep happens in the heap growth
788                         // from gcController.heapLive to trigger, so ensure
789                         // that concurrent sweep has some heap growth
790                         // in which to perform sweeping before we
791                         // start the next GC cycle.
792                         sweepMin := atomic.Load64(&c.heapLive) + sweepMinHeapDistance
793                         if sweepMin > minTrigger {
794                                 minTrigger = sweepMin
795                         }
796                 }
797                 if trigger < minTrigger {
798                         trigger = minTrigger
799                 }
800                 if int64(trigger) < 0 {
801                         print("runtime: heapGoal=", c.heapGoal, " heapMarked=", c.heapMarked, " gcController.heapLive=", c.heapLive, " initialHeapLive=", work.initialHeapLive, "triggerRatio=", triggerRatio, " minTrigger=", minTrigger, "\n")
802                         throw("trigger underflow")
803                 }
804                 if trigger > goal {
805                         // The trigger ratio is always less than GOGC/100, but
806                         // other bounds on the trigger may have raised it.
807                         // Push up the goal, too.
808                         goal = trigger
809                 }
810         }
811
812         // Commit to the trigger and goal.
813         c.trigger = trigger
814         atomic.Store64(&c.heapGoal, goal)
815         if trace.enabled {
816                 traceHeapGoal()
817         }
818
819         // Update mark pacing.
820         if gcphase != _GCoff {
821                 c.revise()
822         }
823 }
824
825 // effectiveGrowthRatio returns the current effective heap growth
826 // ratio (GOGC/100) based on heapMarked from the previous GC and
827 // heapGoal for the current GC.
828 //
829 // This may differ from gcPercent/100 because of various upper and
830 // lower bounds on gcPercent. For example, if the heap is smaller than
831 // heapMinimum, this can be higher than gcPercent/100.
832 //
833 // mheap_.lock must be held or the world must be stopped.
834 func (c *gcControllerState) effectiveGrowthRatio() float64 {
835         assertWorldStoppedOrLockHeld(&mheap_.lock)
836
837         egogc := float64(atomic.Load64(&c.heapGoal)-c.heapMarked) / float64(c.heapMarked)
838         if egogc < 0 {
839                 // Shouldn't happen, but just in case.
840                 egogc = 0
841         }
842         return egogc
843 }
844
845 // setGCPercent updates gcPercent and all related pacer state.
846 // Returns the old value of gcPercent.
847 //
848 // Calls gcControllerState.commit.
849 //
850 // The world must be stopped, or mheap_.lock must be held.
851 func (c *gcControllerState) setGCPercent(in int32) int32 {
852         assertWorldStoppedOrLockHeld(&mheap_.lock)
853
854         out := c.gcPercent
855         if in < 0 {
856                 in = -1
857         }
858         // Write it atomically so readers like revise() can read it safely.
859         atomic.Storeint32(&c.gcPercent, in)
860         c.heapMinimum = defaultHeapMinimum * uint64(c.gcPercent) / 100
861         // Update pacing in response to gcPercent change.
862         c.commit(c.triggerRatio)
863
864         return out
865 }
866
867 //go:linkname setGCPercent runtime/debug.setGCPercent
868 func setGCPercent(in int32) (out int32) {
869         // Run on the system stack since we grab the heap lock.
870         systemstack(func() {
871                 lock(&mheap_.lock)
872                 out = gcController.setGCPercent(in)
873                 gcPaceSweeper(gcController.trigger)
874                 gcPaceScavenger(gcController.heapGoal, gcController.lastHeapGoal)
875                 unlock(&mheap_.lock)
876         })
877
878         // If we just disabled GC, wait for any concurrent GC mark to
879         // finish so we always return with no GC running.
880         if in < 0 {
881                 gcWaitOnMark(atomic.Load(&work.cycles))
882         }
883
884         return out
885 }
886
887 func readGOGC() int32 {
888         p := gogetenv("GOGC")
889         if p == "off" {
890                 return -1
891         }
892         if n, ok := atoi32(p); ok {
893                 return n
894         }
895         return 100
896 }