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