]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/mgcpacer.go
runtime: formalize and fix gcPercent synchronization
[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() {
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
279         // Ensure that the heap goal is at least a little larger than
280         // the current live heap size. This may not be the case if GC
281         // start is delayed or if the allocation that pushed gcController.heapLive
282         // over trigger is large or if the trigger is really close to
283         // GOGC. Assist is proportional to this distance, so enforce a
284         // minimum distance, even if it means going over the GOGC goal
285         // by a tiny bit.
286         if c.heapGoal < c.heapLive+1024*1024 {
287                 c.heapGoal = c.heapLive + 1024*1024
288         }
289
290         // Compute the background mark utilization goal. In general,
291         // this may not come out exactly. We round the number of
292         // dedicated workers so that the utilization is closest to
293         // 25%. For small GOMAXPROCS, this would introduce too much
294         // error, so we add fractional workers in that case.
295         totalUtilizationGoal := float64(gomaxprocs) * gcBackgroundUtilization
296         c.dedicatedMarkWorkersNeeded = int64(totalUtilizationGoal + 0.5)
297         utilError := float64(c.dedicatedMarkWorkersNeeded)/totalUtilizationGoal - 1
298         const maxUtilError = 0.3
299         if utilError < -maxUtilError || utilError > maxUtilError {
300                 // Rounding put us more than 30% off our goal. With
301                 // gcBackgroundUtilization of 25%, this happens for
302                 // GOMAXPROCS<=3 or GOMAXPROCS=6. Enable fractional
303                 // workers to compensate.
304                 if float64(c.dedicatedMarkWorkersNeeded) > totalUtilizationGoal {
305                         // Too many dedicated workers.
306                         c.dedicatedMarkWorkersNeeded--
307                 }
308                 c.fractionalUtilizationGoal = (totalUtilizationGoal - float64(c.dedicatedMarkWorkersNeeded)) / float64(gomaxprocs)
309         } else {
310                 c.fractionalUtilizationGoal = 0
311         }
312
313         // In STW mode, we just want dedicated workers.
314         if debug.gcstoptheworld > 0 {
315                 c.dedicatedMarkWorkersNeeded = int64(gomaxprocs)
316                 c.fractionalUtilizationGoal = 0
317         }
318
319         // Clear per-P state
320         for _, p := range allp {
321                 p.gcAssistTime = 0
322                 p.gcFractionalMarkTime = 0
323         }
324
325         // Compute initial values for controls that are updated
326         // throughout the cycle.
327         c.revise()
328
329         if debug.gcpacertrace > 0 {
330                 assistRatio := c.assistWorkPerByte.Load()
331                 print("pacer: assist ratio=", assistRatio,
332                         " (scan ", gcController.heapScan>>20, " MB in ",
333                         work.initialHeapLive>>20, "->",
334                         c.heapGoal>>20, " MB)",
335                         " workers=", c.dedicatedMarkWorkersNeeded,
336                         "+", c.fractionalUtilizationGoal, "\n")
337         }
338 }
339
340 // revise updates the assist ratio during the GC cycle to account for
341 // improved estimates. This should be called whenever gcController.heapScan,
342 // gcController.heapLive, or gcController.heapGoal is updated. It is safe to
343 // call concurrently, but it may race with other calls to revise.
344 //
345 // The result of this race is that the two assist ratio values may not line
346 // up or may be stale. In practice this is OK because the assist ratio
347 // moves slowly throughout a GC cycle, and the assist ratio is a best-effort
348 // heuristic anyway. Furthermore, no part of the heuristic depends on
349 // the two assist ratio values being exact reciprocals of one another, since
350 // the two values are used to convert values from different sources.
351 //
352 // The worst case result of this raciness is that we may miss a larger shift
353 // in the ratio (say, if we decide to pace more aggressively against the
354 // hard heap goal) but even this "hard goal" is best-effort (see #40460).
355 // The dedicated GC should ensure we don't exceed the hard goal by too much
356 // in the rare case we do exceed it.
357 //
358 // It should only be called when gcBlackenEnabled != 0 (because this
359 // is when assists are enabled and the necessary statistics are
360 // available).
361 func (c *gcControllerState) revise() {
362         gcPercent := atomic.Loadint32(&c.gcPercent)
363         if gcPercent < 0 {
364                 // If GC is disabled but we're running a forced GC,
365                 // act like GOGC is huge for the below calculations.
366                 gcPercent = 100000
367         }
368         live := atomic.Load64(&c.heapLive)
369         scan := atomic.Load64(&c.heapScan)
370         work := atomic.Loadint64(&c.scanWork)
371
372         // Assume we're under the soft goal. Pace GC to complete at
373         // heapGoal assuming the heap is in steady-state.
374         heapGoal := int64(atomic.Load64(&c.heapGoal))
375
376         // Compute the expected scan work remaining.
377         //
378         // This is estimated based on the expected
379         // steady-state scannable heap. For example, with
380         // GOGC=100, only half of the scannable heap is
381         // expected to be live, so that's what we target.
382         //
383         // (This is a float calculation to avoid overflowing on
384         // 100*heapScan.)
385         scanWorkExpected := int64(float64(scan) * 100 / float64(100+gcPercent))
386
387         if int64(live) > heapGoal || work > scanWorkExpected {
388                 // We're past the soft goal, or we've already done more scan
389                 // work than we expected. Pace GC so that in the worst case it
390                 // will complete by the hard goal.
391                 const maxOvershoot = 1.1
392                 heapGoal = int64(float64(heapGoal) * maxOvershoot)
393
394                 // Compute the upper bound on the scan work remaining.
395                 scanWorkExpected = int64(scan)
396         }
397
398         // Compute the remaining scan work estimate.
399         //
400         // Note that we currently count allocations during GC as both
401         // scannable heap (heapScan) and scan work completed
402         // (scanWork), so allocation will change this difference
403         // slowly in the soft regime and not at all in the hard
404         // regime.
405         scanWorkRemaining := scanWorkExpected - work
406         if scanWorkRemaining < 1000 {
407                 // We set a somewhat arbitrary lower bound on
408                 // remaining scan work since if we aim a little high,
409                 // we can miss by a little.
410                 //
411                 // We *do* need to enforce that this is at least 1,
412                 // since marking is racy and double-scanning objects
413                 // may legitimately make the remaining scan work
414                 // negative, even in the hard goal regime.
415                 scanWorkRemaining = 1000
416         }
417
418         // Compute the heap distance remaining.
419         heapRemaining := heapGoal - int64(live)
420         if heapRemaining <= 0 {
421                 // This shouldn't happen, but if it does, avoid
422                 // dividing by zero or setting the assist negative.
423                 heapRemaining = 1
424         }
425
426         // Compute the mutator assist ratio so by the time the mutator
427         // allocates the remaining heap bytes up to heapGoal, it will
428         // have done (or stolen) the remaining amount of scan work.
429         // Note that the assist ratio values are updated atomically
430         // but not together. This means there may be some degree of
431         // skew between the two values. This is generally OK as the
432         // values shift relatively slowly over the course of a GC
433         // cycle.
434         assistWorkPerByte := float64(scanWorkRemaining) / float64(heapRemaining)
435         assistBytesPerWork := float64(heapRemaining) / float64(scanWorkRemaining)
436         c.assistWorkPerByte.Store(assistWorkPerByte)
437         c.assistBytesPerWork.Store(assistBytesPerWork)
438 }
439
440 // endCycle computes the trigger ratio for the next cycle.
441 // userForced indicates whether the current GC cycle was forced
442 // by the application.
443 func (c *gcControllerState) endCycle(userForced bool) float64 {
444         if userForced {
445                 // Forced GC means this cycle didn't start at the
446                 // trigger, so where it finished isn't good
447                 // information about how to adjust the trigger.
448                 // Just leave it where it is.
449                 return c.triggerRatio
450         }
451
452         // Proportional response gain for the trigger controller. Must
453         // be in [0, 1]. Lower values smooth out transient effects but
454         // take longer to respond to phase changes. Higher values
455         // react to phase changes quickly, but are more affected by
456         // transient changes. Values near 1 may be unstable.
457         const triggerGain = 0.5
458
459         // Compute next cycle trigger ratio. First, this computes the
460         // "error" for this cycle; that is, how far off the trigger
461         // was from what it should have been, accounting for both heap
462         // growth and GC CPU utilization. We compute the actual heap
463         // growth during this cycle and scale that by how far off from
464         // the goal CPU utilization we were (to estimate the heap
465         // growth if we had the desired CPU utilization). The
466         // difference between this estimate and the GOGC-based goal
467         // heap growth is the error.
468         goalGrowthRatio := c.effectiveGrowthRatio()
469         actualGrowthRatio := float64(c.heapLive)/float64(c.heapMarked) - 1
470         assistDuration := nanotime() - c.markStartTime
471
472         // Assume background mark hit its utilization goal.
473         utilization := gcBackgroundUtilization
474         // Add assist utilization; avoid divide by zero.
475         if assistDuration > 0 {
476                 utilization += float64(c.assistTime) / float64(assistDuration*int64(gomaxprocs))
477         }
478
479         triggerError := goalGrowthRatio - c.triggerRatio - utilization/gcGoalUtilization*(actualGrowthRatio-c.triggerRatio)
480
481         // Finally, we adjust the trigger for next time by this error,
482         // damped by the proportional gain.
483         triggerRatio := c.triggerRatio + triggerGain*triggerError
484
485         if debug.gcpacertrace > 0 {
486                 // Print controller state in terms of the design
487                 // document.
488                 H_m_prev := c.heapMarked
489                 h_t := c.triggerRatio
490                 H_T := c.trigger
491                 h_a := actualGrowthRatio
492                 H_a := c.heapLive
493                 h_g := goalGrowthRatio
494                 H_g := int64(float64(H_m_prev) * (1 + h_g))
495                 u_a := utilization
496                 u_g := gcGoalUtilization
497                 W_a := c.scanWork
498                 print("pacer: H_m_prev=", H_m_prev,
499                         " h_t=", h_t, " H_T=", H_T,
500                         " h_a=", h_a, " H_a=", H_a,
501                         " h_g=", h_g, " H_g=", H_g,
502                         " u_a=", u_a, " u_g=", u_g,
503                         " W_a=", W_a,
504                         " goalΔ=", goalGrowthRatio-h_t,
505                         " actualΔ=", h_a-h_t,
506                         " u_a/u_g=", u_a/u_g,
507                         "\n")
508         }
509
510         return triggerRatio
511 }
512
513 // enlistWorker encourages another dedicated mark worker to start on
514 // another P if there are spare worker slots. It is used by putfull
515 // when more work is made available.
516 //
517 //go:nowritebarrier
518 func (c *gcControllerState) enlistWorker() {
519         // If there are idle Ps, wake one so it will run an idle worker.
520         // NOTE: This is suspected of causing deadlocks. See golang.org/issue/19112.
521         //
522         //      if atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 {
523         //              wakep()
524         //              return
525         //      }
526
527         // There are no idle Ps. If we need more dedicated workers,
528         // try to preempt a running P so it will switch to a worker.
529         if c.dedicatedMarkWorkersNeeded <= 0 {
530                 return
531         }
532         // Pick a random other P to preempt.
533         if gomaxprocs <= 1 {
534                 return
535         }
536         gp := getg()
537         if gp == nil || gp.m == nil || gp.m.p == 0 {
538                 return
539         }
540         myID := gp.m.p.ptr().id
541         for tries := 0; tries < 5; tries++ {
542                 id := int32(fastrandn(uint32(gomaxprocs - 1)))
543                 if id >= myID {
544                         id++
545                 }
546                 p := allp[id]
547                 if p.status != _Prunning {
548                         continue
549                 }
550                 if preemptone(p) {
551                         return
552                 }
553         }
554 }
555
556 // findRunnableGCWorker returns a background mark worker for _p_ if it
557 // should be run. This must only be called when gcBlackenEnabled != 0.
558 func (c *gcControllerState) findRunnableGCWorker(_p_ *p) *g {
559         if gcBlackenEnabled == 0 {
560                 throw("gcControllerState.findRunnable: blackening not enabled")
561         }
562
563         if !gcMarkWorkAvailable(_p_) {
564                 // No work to be done right now. This can happen at
565                 // the end of the mark phase when there are still
566                 // assists tapering off. Don't bother running a worker
567                 // now because it'll just return immediately.
568                 return nil
569         }
570
571         // Grab a worker before we commit to running below.
572         node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
573         if node == nil {
574                 // There is at least one worker per P, so normally there are
575                 // enough workers to run on all Ps, if necessary. However, once
576                 // a worker enters gcMarkDone it may park without rejoining the
577                 // pool, thus freeing a P with no corresponding worker.
578                 // gcMarkDone never depends on another worker doing work, so it
579                 // is safe to simply do nothing here.
580                 //
581                 // If gcMarkDone bails out without completing the mark phase,
582                 // it will always do so with queued global work. Thus, that P
583                 // will be immediately eligible to re-run the worker G it was
584                 // just using, ensuring work can complete.
585                 return nil
586         }
587
588         decIfPositive := func(ptr *int64) bool {
589                 for {
590                         v := atomic.Loadint64(ptr)
591                         if v <= 0 {
592                                 return false
593                         }
594
595                         if atomic.Casint64(ptr, v, v-1) {
596                                 return true
597                         }
598                 }
599         }
600
601         if decIfPositive(&c.dedicatedMarkWorkersNeeded) {
602                 // This P is now dedicated to marking until the end of
603                 // the concurrent mark phase.
604                 _p_.gcMarkWorkerMode = gcMarkWorkerDedicatedMode
605         } else if c.fractionalUtilizationGoal == 0 {
606                 // No need for fractional workers.
607                 gcBgMarkWorkerPool.push(&node.node)
608                 return nil
609         } else {
610                 // Is this P behind on the fractional utilization
611                 // goal?
612                 //
613                 // This should be kept in sync with pollFractionalWorkerExit.
614                 delta := nanotime() - c.markStartTime
615                 if delta > 0 && float64(_p_.gcFractionalMarkTime)/float64(delta) > c.fractionalUtilizationGoal {
616                         // Nope. No need to run a fractional worker.
617                         gcBgMarkWorkerPool.push(&node.node)
618                         return nil
619                 }
620                 // Run a fractional worker.
621                 _p_.gcMarkWorkerMode = gcMarkWorkerFractionalMode
622         }
623
624         // Run the background mark worker.
625         gp := node.gp.ptr()
626         casgstatus(gp, _Gwaiting, _Grunnable)
627         if trace.enabled {
628                 traceGoUnpark(gp, 0)
629         }
630         return gp
631 }
632
633 // commit sets the trigger ratio and updates everything
634 // derived from it: the absolute trigger, the heap goal, mark pacing,
635 // and sweep pacing.
636 //
637 // This can be called any time. If GC is the in the middle of a
638 // concurrent phase, it will adjust the pacing of that phase.
639 //
640 // This depends on gcPercent, gcController.heapMarked, and
641 // gcController.heapLive. These must be up to date.
642 //
643 // mheap_.lock must be held or the world must be stopped.
644 func (c *gcControllerState) commit(triggerRatio float64) {
645         assertWorldStoppedOrLockHeld(&mheap_.lock)
646
647         // Compute the next GC goal, which is when the allocated heap
648         // has grown by GOGC/100 over the heap marked by the last
649         // cycle.
650         goal := ^uint64(0)
651         if c.gcPercent >= 0 {
652                 goal = c.heapMarked + c.heapMarked*uint64(c.gcPercent)/100
653         }
654
655         // Set the trigger ratio, capped to reasonable bounds.
656         if c.gcPercent >= 0 {
657                 scalingFactor := float64(c.gcPercent) / 100
658                 // Ensure there's always a little margin so that the
659                 // mutator assist ratio isn't infinity.
660                 maxTriggerRatio := 0.95 * scalingFactor
661                 if triggerRatio > maxTriggerRatio {
662                         triggerRatio = maxTriggerRatio
663                 }
664
665                 // If we let triggerRatio go too low, then if the application
666                 // is allocating very rapidly we might end up in a situation
667                 // where we're allocating black during a nearly always-on GC.
668                 // The result of this is a growing heap and ultimately an
669                 // increase in RSS. By capping us at a point >0, we're essentially
670                 // saying that we're OK using more CPU during the GC to prevent
671                 // this growth in RSS.
672                 //
673                 // The current constant was chosen empirically: given a sufficiently
674                 // fast/scalable allocator with 48 Ps that could drive the trigger ratio
675                 // to <0.05, this constant causes applications to retain the same peak
676                 // RSS compared to not having this allocator.
677                 minTriggerRatio := 0.6 * scalingFactor
678                 if triggerRatio < minTriggerRatio {
679                         triggerRatio = minTriggerRatio
680                 }
681         } else if triggerRatio < 0 {
682                 // gcPercent < 0, so just make sure we're not getting a negative
683                 // triggerRatio. This case isn't expected to happen in practice,
684                 // and doesn't really matter because if gcPercent < 0 then we won't
685                 // ever consume triggerRatio further on in this function, but let's
686                 // just be defensive here; the triggerRatio being negative is almost
687                 // certainly undesirable.
688                 triggerRatio = 0
689         }
690         c.triggerRatio = triggerRatio
691
692         // Compute the absolute GC trigger from the trigger ratio.
693         //
694         // We trigger the next GC cycle when the allocated heap has
695         // grown by the trigger ratio over the marked heap size.
696         trigger := ^uint64(0)
697         if c.gcPercent >= 0 {
698                 trigger = uint64(float64(c.heapMarked) * (1 + triggerRatio))
699                 // Don't trigger below the minimum heap size.
700                 minTrigger := c.heapMinimum
701                 if !isSweepDone() {
702                         // Concurrent sweep happens in the heap growth
703                         // from gcController.heapLive to trigger, so ensure
704                         // that concurrent sweep has some heap growth
705                         // in which to perform sweeping before we
706                         // start the next GC cycle.
707                         sweepMin := atomic.Load64(&c.heapLive) + sweepMinHeapDistance
708                         if sweepMin > minTrigger {
709                                 minTrigger = sweepMin
710                         }
711                 }
712                 if trigger < minTrigger {
713                         trigger = minTrigger
714                 }
715                 if int64(trigger) < 0 {
716                         print("runtime: heapGoal=", c.heapGoal, " heapMarked=", c.heapMarked, " gcController.heapLive=", c.heapLive, " initialHeapLive=", work.initialHeapLive, "triggerRatio=", triggerRatio, " minTrigger=", minTrigger, "\n")
717                         throw("trigger underflow")
718                 }
719                 if trigger > goal {
720                         // The trigger ratio is always less than GOGC/100, but
721                         // other bounds on the trigger may have raised it.
722                         // Push up the goal, too.
723                         goal = trigger
724                 }
725         }
726
727         // Commit to the trigger and goal.
728         c.trigger = trigger
729         atomic.Store64(&c.heapGoal, goal)
730         if trace.enabled {
731                 traceHeapGoal()
732         }
733
734         // Update mark pacing.
735         if gcphase != _GCoff {
736                 c.revise()
737         }
738
739         // Update sweep pacing.
740         if isSweepDone() {
741                 mheap_.sweepPagesPerByte = 0
742         } else {
743                 // Concurrent sweep needs to sweep all of the in-use
744                 // pages by the time the allocated heap reaches the GC
745                 // trigger. Compute the ratio of in-use pages to sweep
746                 // per byte allocated, accounting for the fact that
747                 // some might already be swept.
748                 heapLiveBasis := atomic.Load64(&c.heapLive)
749                 heapDistance := int64(trigger) - int64(heapLiveBasis)
750                 // Add a little margin so rounding errors and
751                 // concurrent sweep are less likely to leave pages
752                 // unswept when GC starts.
753                 heapDistance -= 1024 * 1024
754                 if heapDistance < _PageSize {
755                         // Avoid setting the sweep ratio extremely high
756                         heapDistance = _PageSize
757                 }
758                 pagesSwept := mheap_.pagesSwept.Load()
759                 pagesInUse := mheap_.pagesInUse.Load()
760                 sweepDistancePages := int64(pagesInUse) - int64(pagesSwept)
761                 if sweepDistancePages <= 0 {
762                         mheap_.sweepPagesPerByte = 0
763                 } else {
764                         mheap_.sweepPagesPerByte = float64(sweepDistancePages) / float64(heapDistance)
765                         mheap_.sweepHeapLiveBasis = heapLiveBasis
766                         // Write pagesSweptBasis last, since this
767                         // signals concurrent sweeps to recompute
768                         // their debt.
769                         mheap_.pagesSweptBasis.Store(pagesSwept)
770                 }
771         }
772
773         gcPaceScavenger()
774 }
775
776 // effectiveGrowthRatio returns the current effective heap growth
777 // ratio (GOGC/100) based on heapMarked from the previous GC and
778 // heapGoal for the current GC.
779 //
780 // This may differ from gcPercent/100 because of various upper and
781 // lower bounds on gcPercent. For example, if the heap is smaller than
782 // heapMinimum, this can be higher than gcPercent/100.
783 //
784 // mheap_.lock must be held or the world must be stopped.
785 func (c *gcControllerState) effectiveGrowthRatio() float64 {
786         assertWorldStoppedOrLockHeld(&mheap_.lock)
787
788         egogc := float64(atomic.Load64(&c.heapGoal)-c.heapMarked) / float64(c.heapMarked)
789         if egogc < 0 {
790                 // Shouldn't happen, but just in case.
791                 egogc = 0
792         }
793         return egogc
794 }
795
796 // setGCPercent updates gcPercent and all related pacer state.
797 // Returns the old value of gcPercent.
798 //
799 // The world must be stopped, or mheap_.lock must be held.
800 func (c *gcControllerState) setGCPercent(in int32) int32 {
801         assertWorldStoppedOrLockHeld(&mheap_.lock)
802
803         out := c.gcPercent
804         if in < 0 {
805                 in = -1
806         }
807         // Write it atomically so readers like revise() can read it safely.
808         atomic.Storeint32(&c.gcPercent, in)
809         c.heapMinimum = defaultHeapMinimum * uint64(c.gcPercent) / 100
810         // Update pacing in response to gcPercent change.
811         c.commit(c.triggerRatio)
812
813         return out
814 }
815
816 //go:linkname setGCPercent runtime/debug.setGCPercent
817 func setGCPercent(in int32) (out int32) {
818         // Run on the system stack since we grab the heap lock.
819         systemstack(func() {
820                 lock(&mheap_.lock)
821                 out = gcController.setGCPercent(in)
822                 unlock(&mheap_.lock)
823         })
824
825         // If we just disabled GC, wait for any concurrent GC mark to
826         // finish so we always return with no GC running.
827         if in < 0 {
828                 gcWaitOnMark(atomic.Load(&work.cycles))
829         }
830
831         return out
832 }
833
834 func readGOGC() int32 {
835         p := gogetenv("GOGC")
836         if p == "off" {
837                 return -1
838         }
839         if n, ok := atoi32(p); ok {
840                 return n
841         }
842         return 100
843 }