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