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