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