Source file 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  	"internal/goexperiment"
    10  	"internal/runtime/atomic"
    11  	"internal/runtime/math"
    12  	"internal/runtime/strconv"
    13  	_ "unsafe" // for go:linkname
    14  )
    15  
    16  const (
    17  	// gcGoalUtilization is the goal CPU utilization for
    18  	// marking as a fraction of GOMAXPROCS.
    19  	//
    20  	// Increasing the goal utilization will shorten GC cycles as the GC
    21  	// has more resources behind it, lessening costs from the write barrier,
    22  	// but comes at the cost of increasing mutator latency.
    23  	gcGoalUtilization = gcBackgroundUtilization
    24  
    25  	// gcBackgroundUtilization is the fixed CPU utilization for background
    26  	// marking. It must be <= gcGoalUtilization. The difference between
    27  	// gcGoalUtilization and gcBackgroundUtilization will be made up by
    28  	// mark assists. The scheduler will aim to use within 50% of this
    29  	// goal.
    30  	//
    31  	// As a general rule, there's little reason to set gcBackgroundUtilization
    32  	// < gcGoalUtilization. One reason might be in mostly idle applications,
    33  	// where goroutines are unlikely to assist at all, so the actual
    34  	// utilization will be lower than the goal. But this is moot point
    35  	// because the idle mark workers already soak up idle CPU resources.
    36  	// These two values are still kept separate however because they are
    37  	// distinct conceptually, and in previous iterations of the pacer the
    38  	// distinction was more important.
    39  	gcBackgroundUtilization = 0.25
    40  
    41  	// gcCreditSlack is the amount of scan work credit that can
    42  	// accumulate locally before updating gcController.heapScanWork and,
    43  	// optionally, gcController.bgScanCredit. Lower values give a more
    44  	// accurate assist ratio and make it more likely that assists will
    45  	// successfully steal background credit. Higher values reduce memory
    46  	// contention.
    47  	gcCreditSlack = 2000
    48  
    49  	// gcAssistTimeSlack is the nanoseconds of mutator assist time that
    50  	// can accumulate on a P before updating gcController.assistTime.
    51  	gcAssistTimeSlack = 5000
    52  
    53  	// gcOverAssistWork determines how many extra units of scan work a GC
    54  	// assist does when an assist happens. This amortizes the cost of an
    55  	// assist by pre-paying for this many bytes of future allocations.
    56  	gcOverAssistWork = 64 << 10
    57  
    58  	// defaultHeapMinimum is the value of heapMinimum for GOGC==100.
    59  	defaultHeapMinimum = (goexperiment.HeapMinimum512KiBInt)*(512<<10) +
    60  		(1-goexperiment.HeapMinimum512KiBInt)*(4<<20)
    61  
    62  	// maxStackScanSlack is the bytes of stack space allocated or freed
    63  	// that can accumulate on a P before updating gcController.stackSize.
    64  	maxStackScanSlack = 8 << 10
    65  
    66  	// memoryLimitMinHeapGoalHeadroom is the minimum amount of headroom the
    67  	// pacer gives to the heap goal when operating in the memory-limited regime.
    68  	// That is, it'll reduce the heap goal by this many extra bytes off of the
    69  	// base calculation, at minimum.
    70  	memoryLimitMinHeapGoalHeadroom = 1 << 20
    71  
    72  	// memoryLimitHeapGoalHeadroomPercent is how headroom the memory-limit-based
    73  	// heap goal should have as a percent of the maximum possible heap goal allowed
    74  	// to maintain the memory limit.
    75  	memoryLimitHeapGoalHeadroomPercent = 3
    76  )
    77  
    78  // gcController implements the GC pacing controller that determines
    79  // when to trigger concurrent garbage collection and how much marking
    80  // work to do in mutator assists and background marking.
    81  //
    82  // It calculates the ratio between the allocation rate (in terms of CPU
    83  // time) and the GC scan throughput to determine the heap size at which to
    84  // trigger a GC cycle such that no GC assists are required to finish on time.
    85  // This algorithm thus optimizes GC CPU utilization to the dedicated background
    86  // mark utilization of 25% of GOMAXPROCS by minimizing GC assists.
    87  // GOMAXPROCS. The high-level design of this algorithm is documented
    88  // at https://github.com/golang/proposal/blob/master/design/44167-gc-pacer-redesign.md.
    89  // See https://golang.org/s/go15gcpacing for additional historical context.
    90  var gcController gcControllerState
    91  
    92  type gcControllerState struct {
    93  	// Initialized from GOGC. GOGC=off means no GC.
    94  	gcPercent atomic.Int32
    95  
    96  	// memoryLimit is the soft memory limit in bytes.
    97  	//
    98  	// Initialized from GOMEMLIMIT. GOMEMLIMIT=off is equivalent to MaxInt64
    99  	// which means no soft memory limit in practice.
   100  	//
   101  	// This is an int64 instead of a uint64 to more easily maintain parity with
   102  	// the SetMemoryLimit API, which sets a maximum at MaxInt64. This value
   103  	// should never be negative.
   104  	memoryLimit atomic.Int64
   105  
   106  	// heapMinimum is the minimum heap size at which to trigger GC.
   107  	// For small heaps, this overrides the usual GOGC*live set rule.
   108  	//
   109  	// When there is a very small live set but a lot of allocation, simply
   110  	// collecting when the heap reaches GOGC*live results in many GC
   111  	// cycles and high total per-GC overhead. This minimum amortizes this
   112  	// per-GC overhead while keeping the heap reasonably small.
   113  	//
   114  	// During initialization this is set to 4MB*GOGC/100. In the case of
   115  	// GOGC==0, this will set heapMinimum to 0, resulting in constant
   116  	// collection even when the heap size is small, which is useful for
   117  	// debugging.
   118  	heapMinimum uint64
   119  
   120  	// runway is the amount of runway in heap bytes allocated by the
   121  	// application that we want to give the GC once it starts.
   122  	//
   123  	// This is computed from consMark during mark termination.
   124  	runway atomic.Uint64
   125  
   126  	// consMark is the estimated per-CPU consMark ratio for the application.
   127  	//
   128  	// It represents the ratio between the application's allocation
   129  	// rate, as bytes allocated per CPU-time, and the GC's scan rate,
   130  	// as bytes scanned per CPU-time.
   131  	// The units of this ratio are (B / cpu-ns) / (B / cpu-ns).
   132  	//
   133  	// At a high level, this value is computed as the bytes of memory
   134  	// allocated (cons) per unit of scan work completed (mark) in a GC
   135  	// cycle, divided by the CPU time spent on each activity.
   136  	//
   137  	// Updated at the end of each GC cycle, in endCycle.
   138  	consMark float64
   139  
   140  	// lastConsMark is the computed cons/mark value for the previous 4 GC
   141  	// cycles. Note that this is *not* the last value of consMark, but the
   142  	// measured cons/mark value in endCycle.
   143  	lastConsMark [4]float64
   144  
   145  	// gcPercentHeapGoal is the goal heapLive for when next GC ends derived
   146  	// from gcPercent.
   147  	//
   148  	// Set to ^uint64(0) if gcPercent is disabled.
   149  	gcPercentHeapGoal atomic.Uint64
   150  
   151  	// sweepDistMinTrigger is the minimum trigger to ensure a minimum
   152  	// sweep distance.
   153  	//
   154  	// This bound is also special because it applies to both the trigger
   155  	// *and* the goal (all other trigger bounds must be based *on* the goal).
   156  	//
   157  	// It is computed ahead of time, at commit time. The theory is that,
   158  	// absent a sudden change to a parameter like gcPercent, the trigger
   159  	// will be chosen to always give the sweeper enough headroom. However,
   160  	// such a change might dramatically and suddenly move up the trigger,
   161  	// in which case we need to ensure the sweeper still has enough headroom.
   162  	sweepDistMinTrigger atomic.Uint64
   163  
   164  	// triggered is the point at which the current GC cycle actually triggered.
   165  	// Only valid during the mark phase of a GC cycle, otherwise set to ^uint64(0).
   166  	//
   167  	// Updated while the world is stopped.
   168  	triggered uint64
   169  
   170  	// lastHeapGoal is the value of heapGoal at the moment the last GC
   171  	// ended. Note that this is distinct from the last value heapGoal had,
   172  	// because it could change if e.g. gcPercent changes.
   173  	//
   174  	// Read and written with the world stopped or with mheap_.lock held.
   175  	lastHeapGoal uint64
   176  
   177  	// heapLive is the number of bytes considered live by the GC.
   178  	// That is: retained by the most recent GC plus allocated
   179  	// since then. heapLive ≤ memstats.totalAlloc-memstats.totalFree, since
   180  	// heapAlloc includes unmarked objects that have not yet been swept (and
   181  	// hence goes up as we allocate and down as we sweep) while heapLive
   182  	// excludes these objects (and hence only goes up between GCs).
   183  	//
   184  	// To reduce contention, this is updated only when obtaining a span
   185  	// from an mcentral and at this point it counts all of the unallocated
   186  	// slots in that span (which will be allocated before that mcache
   187  	// obtains another span from that mcentral). Hence, it slightly
   188  	// overestimates the "true" live heap size. It's better to overestimate
   189  	// than to underestimate because 1) this triggers the GC earlier than
   190  	// necessary rather than potentially too late and 2) this leads to a
   191  	// conservative GC rate rather than a GC rate that is potentially too
   192  	// low.
   193  	//
   194  	// Whenever this is updated, call traceHeapAlloc() and
   195  	// this gcControllerState's revise() method.
   196  	heapLive atomic.Uint64
   197  
   198  	// heapScan is the number of bytes of "scannable" heap. This is the
   199  	// live heap (as counted by heapLive), but omitting no-scan objects and
   200  	// no-scan tails of objects.
   201  	//
   202  	// This value is fixed at the start of a GC cycle. It represents the
   203  	// maximum scannable heap.
   204  	heapScan atomic.Uint64
   205  
   206  	// lastHeapScan is the number of bytes of heap that were scanned
   207  	// last GC cycle. It is the same as heapMarked, but only
   208  	// includes the "scannable" parts of objects.
   209  	//
   210  	// Updated when the world is stopped.
   211  	lastHeapScan uint64
   212  
   213  	// lastStackScan is the number of bytes of stack that were scanned
   214  	// last GC cycle.
   215  	lastStackScan atomic.Uint64
   216  
   217  	// maxStackScan is the amount of allocated goroutine stack space in
   218  	// use by goroutines.
   219  	//
   220  	// This number tracks allocated goroutine stack space rather than used
   221  	// goroutine stack space (i.e. what is actually scanned) because used
   222  	// goroutine stack space is much harder to measure cheaply. By using
   223  	// allocated space, we make an overestimate; this is OK, it's better
   224  	// to conservatively overcount than undercount.
   225  	maxStackScan atomic.Uint64
   226  
   227  	// globalsScan is the total amount of global variable space
   228  	// that is scannable.
   229  	globalsScan atomic.Uint64
   230  
   231  	// heapMarked is the number of bytes marked by the previous
   232  	// GC. After mark termination, heapLive == heapMarked, but
   233  	// unlike heapLive, heapMarked does not change until the
   234  	// next mark termination.
   235  	heapMarked uint64
   236  
   237  	// heapScanWork is the total heap scan work performed this cycle.
   238  	// stackScanWork is the total stack scan work performed this cycle.
   239  	// globalsScanWork is the total globals scan work performed this cycle.
   240  	//
   241  	// These are updated atomically during the cycle. Updates occur in
   242  	// bounded batches, since they are both written and read
   243  	// throughout the cycle. At the end of the cycle, heapScanWork is how
   244  	// much of the retained heap is scannable.
   245  	//
   246  	// Currently these are measured in bytes. For most uses, this is an
   247  	// opaque unit of work, but for estimation the definition is important.
   248  	//
   249  	// Note that stackScanWork includes only stack space scanned, not all
   250  	// of the allocated stack.
   251  	heapScanWork    atomic.Int64
   252  	stackScanWork   atomic.Int64
   253  	globalsScanWork atomic.Int64
   254  
   255  	// bgScanCredit is the scan work credit accumulated by the concurrent
   256  	// background scan. This credit is accumulated by the background scan
   257  	// and stolen by mutator assists.  Updates occur in bounded batches,
   258  	// since it is both written and read throughout the cycle.
   259  	bgScanCredit atomic.Int64
   260  
   261  	// assistTime is the nanoseconds spent in mutator assists
   262  	// during this cycle. This is updated atomically, and must also
   263  	// be updated atomically even during a STW, because it is read
   264  	// by sysmon. Updates occur in bounded batches, since it is both
   265  	// written and read throughout the cycle.
   266  	assistTime atomic.Int64
   267  
   268  	// dedicatedMarkTime is the nanoseconds spent in dedicated mark workers
   269  	// during this cycle. This is updated at the end of the concurrent mark
   270  	// phase.
   271  	dedicatedMarkTime atomic.Int64
   272  
   273  	// fractionalMarkTime is the nanoseconds spent in the fractional mark
   274  	// worker during this cycle. This is updated throughout the cycle and
   275  	// will be up-to-date if the fractional mark worker is not currently
   276  	// running.
   277  	fractionalMarkTime atomic.Int64
   278  
   279  	// idleMarkTime is the nanoseconds spent in idle marking during this
   280  	// cycle. This is updated throughout the cycle.
   281  	idleMarkTime atomic.Int64
   282  
   283  	// markStartTime is the absolute start time in nanoseconds
   284  	// that assists and background mark workers started.
   285  	markStartTime int64
   286  
   287  	// dedicatedMarkWorkersNeeded is the number of dedicated mark workers
   288  	// that need to be started. This is computed at the beginning of each
   289  	// cycle and decremented as dedicated mark workers get started.
   290  	dedicatedMarkWorkersNeeded atomic.Int64
   291  
   292  	// idleMarkWorkers is two packed int32 values in a single uint64.
   293  	// These two values are always updated simultaneously.
   294  	//
   295  	// The bottom int32 is the current number of idle mark workers executing.
   296  	//
   297  	// The top int32 is the maximum number of idle mark workers allowed to
   298  	// execute concurrently. Normally, this number is just gomaxprocs. However,
   299  	// during periodic GC cycles it is set to 0 because the system is idle
   300  	// anyway; there's no need to go full blast on all of GOMAXPROCS.
   301  	//
   302  	// The maximum number of idle mark workers is used to prevent new workers
   303  	// from starting, but it is not a hard maximum. It is possible (but
   304  	// exceedingly rare) for the current number of idle mark workers to
   305  	// transiently exceed the maximum. This could happen if the maximum changes
   306  	// just after a GC ends, and an M with no P.
   307  	//
   308  	// Note that if we have no dedicated mark workers, we set this value to
   309  	// 1 in this case we only have fractional GC workers which aren't scheduled
   310  	// strictly enough to ensure GC progress. As a result, idle-priority mark
   311  	// workers are vital to GC progress in these situations.
   312  	//
   313  	// For example, consider a situation in which goroutines block on the GC
   314  	// (such as via runtime.GOMAXPROCS) and only fractional mark workers are
   315  	// scheduled (e.g. GOMAXPROCS=1). Without idle-priority mark workers, the
   316  	// last running M might skip scheduling a fractional mark worker if its
   317  	// utilization goal is met, such that once it goes to sleep (because there's
   318  	// nothing to do), there will be nothing else to spin up a new M for the
   319  	// fractional worker in the future, stalling GC progress and causing a
   320  	// deadlock. However, idle-priority workers will *always* run when there is
   321  	// nothing left to do, ensuring the GC makes progress.
   322  	//
   323  	// See github.com/golang/go/issues/44163 for more details.
   324  	idleMarkWorkers atomic.Uint64
   325  
   326  	// assistWorkPerByte is the ratio of scan work to allocated
   327  	// bytes that should be performed by mutator assists. This is
   328  	// computed at the beginning of each cycle and updated every
   329  	// time heapScan is updated.
   330  	assistWorkPerByte atomic.Float64
   331  
   332  	// assistBytesPerWork is 1/assistWorkPerByte.
   333  	//
   334  	// Note that because this is read and written independently
   335  	// from assistWorkPerByte users may notice a skew between
   336  	// the two values, and such a state should be safe.
   337  	assistBytesPerWork atomic.Float64
   338  
   339  	// fractionalUtilizationGoal is the fraction of wall clock
   340  	// time that should be spent in the fractional mark worker on
   341  	// each P that isn't running a dedicated worker.
   342  	//
   343  	// For example, if the utilization goal is 25% and there are
   344  	// no dedicated workers, this will be 0.25. If the goal is
   345  	// 25%, there is one dedicated worker, and GOMAXPROCS is 5,
   346  	// this will be 0.05 to make up the missing 5%.
   347  	//
   348  	// If this is zero, no fractional workers are needed.
   349  	fractionalUtilizationGoal float64
   350  
   351  	// These memory stats are effectively duplicates of fields from
   352  	// memstats.heapStats but are updated atomically or with the world
   353  	// stopped and don't provide the same consistency guarantees.
   354  	//
   355  	// Because the runtime is responsible for managing a memory limit, it's
   356  	// useful to couple these stats more tightly to the gcController, which
   357  	// is intimately connected to how that memory limit is maintained.
   358  	heapInUse    sysMemStat    // bytes in mSpanInUse spans
   359  	heapReleased sysMemStat    // bytes released to the OS
   360  	heapFree     sysMemStat    // bytes not in any span, but not released to the OS
   361  	totalAlloc   atomic.Uint64 // total bytes allocated
   362  	totalFree    atomic.Uint64 // total bytes freed
   363  	mappedReady  atomic.Uint64 // total virtual memory in the Ready state (see mem.go).
   364  
   365  	// test indicates that this is a test-only copy of gcControllerState.
   366  	test bool
   367  
   368  	_ cpu.CacheLinePad
   369  }
   370  
   371  func (c *gcControllerState) init(gcPercent int32, memoryLimit int64) {
   372  	c.heapMinimum = defaultHeapMinimum
   373  	c.triggered = ^uint64(0)
   374  	c.setGCPercent(gcPercent)
   375  	c.setMemoryLimit(memoryLimit)
   376  	c.commit(true) // No sweep phase in the first GC cycle.
   377  	// N.B. Don't bother calling traceHeapGoal. Tracing is never enabled at
   378  	// initialization time.
   379  	// N.B. No need to call revise; there's no GC enabled during
   380  	// initialization.
   381  }
   382  
   383  // startCycle resets the GC controller's state and computes estimates
   384  // for a new GC cycle. The caller must hold worldsema and the world
   385  // must be stopped.
   386  func (c *gcControllerState) startCycle(markStartTime int64, procs int, trigger gcTrigger) {
   387  	c.heapScanWork.Store(0)
   388  	c.stackScanWork.Store(0)
   389  	c.globalsScanWork.Store(0)
   390  	c.bgScanCredit.Store(0)
   391  	c.assistTime.Store(0)
   392  	c.dedicatedMarkTime.Store(0)
   393  	c.fractionalMarkTime.Store(0)
   394  	c.idleMarkTime.Store(0)
   395  	c.markStartTime = markStartTime
   396  	c.triggered = c.heapLive.Load()
   397  
   398  	// Compute the background mark utilization goal. In general,
   399  	// this may not come out exactly. We round the number of
   400  	// dedicated workers so that the utilization is closest to
   401  	// 25%. For small GOMAXPROCS, this would introduce too much
   402  	// error, so we add fractional workers in that case.
   403  	totalUtilizationGoal := float64(procs) * gcBackgroundUtilization
   404  	dedicatedMarkWorkersNeeded := int64(totalUtilizationGoal + 0.5)
   405  	utilError := float64(dedicatedMarkWorkersNeeded)/totalUtilizationGoal - 1
   406  	const maxUtilError = 0.3
   407  	if utilError < -maxUtilError || utilError > maxUtilError {
   408  		// Rounding put us more than 30% off our goal. With
   409  		// gcBackgroundUtilization of 25%, this happens for
   410  		// GOMAXPROCS<=3 or GOMAXPROCS=6. Enable fractional
   411  		// workers to compensate.
   412  		if float64(dedicatedMarkWorkersNeeded) > totalUtilizationGoal {
   413  			// Too many dedicated workers.
   414  			dedicatedMarkWorkersNeeded--
   415  		}
   416  		c.fractionalUtilizationGoal = (totalUtilizationGoal - float64(dedicatedMarkWorkersNeeded)) / float64(procs)
   417  	} else {
   418  		c.fractionalUtilizationGoal = 0
   419  	}
   420  
   421  	// In STW mode, we just want dedicated workers.
   422  	if debug.gcstoptheworld > 0 {
   423  		dedicatedMarkWorkersNeeded = int64(procs)
   424  		c.fractionalUtilizationGoal = 0
   425  	}
   426  
   427  	// Clear per-P state
   428  	for _, p := range allp {
   429  		p.gcAssistTime = 0
   430  		p.gcFractionalMarkTime = 0
   431  	}
   432  
   433  	if trigger.kind == gcTriggerTime {
   434  		// During a periodic GC cycle, reduce the number of idle mark workers
   435  		// required. However, we need at least one dedicated mark worker or
   436  		// idle GC worker to ensure GC progress in some scenarios (see comment
   437  		// on maxIdleMarkWorkers).
   438  		if dedicatedMarkWorkersNeeded > 0 {
   439  			c.setMaxIdleMarkWorkers(0)
   440  		} else {
   441  			// TODO(mknyszek): The fundamental reason why we need this is because
   442  			// we can't count on the fractional mark worker to get scheduled.
   443  			// Fix that by ensuring it gets scheduled according to its quota even
   444  			// if the rest of the application is idle.
   445  			c.setMaxIdleMarkWorkers(1)
   446  		}
   447  	} else {
   448  		// N.B. gomaxprocs and dedicatedMarkWorkersNeeded are guaranteed not to
   449  		// change during a GC cycle.
   450  		c.setMaxIdleMarkWorkers(int32(procs) - int32(dedicatedMarkWorkersNeeded))
   451  	}
   452  
   453  	// Compute initial values for controls that are updated
   454  	// throughout the cycle.
   455  	c.dedicatedMarkWorkersNeeded.Store(dedicatedMarkWorkersNeeded)
   456  	c.revise()
   457  
   458  	if debug.gcpacertrace > 0 {
   459  		heapGoal := c.heapGoal()
   460  		assistRatio := c.assistWorkPerByte.Load()
   461  		print("pacer: assist ratio=", assistRatio,
   462  			" (scan ", gcController.heapScan.Load()>>20, " MB in ",
   463  			work.initialHeapLive>>20, "->",
   464  			heapGoal>>20, " MB)",
   465  			" workers=", dedicatedMarkWorkersNeeded,
   466  			"+", c.fractionalUtilizationGoal, "\n")
   467  	}
   468  }
   469  
   470  // revise updates the assist ratio during the GC cycle to account for
   471  // improved estimates. This should be called whenever gcController.heapScan,
   472  // gcController.heapLive, or if any inputs to gcController.heapGoal are
   473  // updated. It is safe to call concurrently, but it may race with other
   474  // calls to revise.
   475  //
   476  // The result of this race is that the two assist ratio values may not line
   477  // up or may be stale. In practice this is OK because the assist ratio
   478  // moves slowly throughout a GC cycle, and the assist ratio is a best-effort
   479  // heuristic anyway. Furthermore, no part of the heuristic depends on
   480  // the two assist ratio values being exact reciprocals of one another, since
   481  // the two values are used to convert values from different sources.
   482  //
   483  // The worst case result of this raciness is that we may miss a larger shift
   484  // in the ratio (say, if we decide to pace more aggressively against the
   485  // hard heap goal) but even this "hard goal" is best-effort (see #40460).
   486  // The dedicated GC should ensure we don't exceed the hard goal by too much
   487  // in the rare case we do exceed it.
   488  //
   489  // It should only be called when gcBlackenEnabled != 0 (because this
   490  // is when assists are enabled and the necessary statistics are
   491  // available).
   492  func (c *gcControllerState) revise() {
   493  	gcPercent := c.gcPercent.Load()
   494  	if gcPercent < 0 {
   495  		// If GC is disabled but we're running a forced GC,
   496  		// act like GOGC is huge for the below calculations.
   497  		gcPercent = 100000
   498  	}
   499  	live := c.heapLive.Load()
   500  	scan := c.heapScan.Load()
   501  	work := c.heapScanWork.Load() + c.stackScanWork.Load() + c.globalsScanWork.Load()
   502  
   503  	// Assume we're under the soft goal. Pace GC to complete at
   504  	// heapGoal assuming the heap is in steady-state.
   505  	heapGoal := int64(c.heapGoal())
   506  
   507  	// The expected scan work is computed as the amount of bytes scanned last
   508  	// GC cycle (both heap and stack), plus our estimate of globals work for this cycle.
   509  	scanWorkExpected := int64(c.lastHeapScan + c.lastStackScan.Load() + c.globalsScan.Load())
   510  
   511  	// maxScanWork is a worst-case estimate of the amount of scan work that
   512  	// needs to be performed in this GC cycle. Specifically, it represents
   513  	// the case where *all* scannable memory turns out to be live, and
   514  	// *all* allocated stack space is scannable.
   515  	maxStackScan := c.maxStackScan.Load()
   516  	maxScanWork := int64(scan + maxStackScan + c.globalsScan.Load())
   517  	if work > scanWorkExpected {
   518  		// We've already done more scan work than expected. Because our expectation
   519  		// is based on a steady-state scannable heap size, we assume this means our
   520  		// heap is growing. Compute a new heap goal that takes our existing runway
   521  		// computed for scanWorkExpected and extrapolates it to maxScanWork, the worst-case
   522  		// scan work. This keeps our assist ratio stable if the heap continues to grow.
   523  		//
   524  		// The effect of this mechanism is that assists stay flat in the face of heap
   525  		// growths. It's OK to use more memory this cycle to scan all the live heap,
   526  		// because the next GC cycle is inevitably going to use *at least* that much
   527  		// memory anyway.
   528  		extHeapGoal := int64(float64(heapGoal-int64(c.triggered))/float64(scanWorkExpected)*float64(maxScanWork)) + int64(c.triggered)
   529  		scanWorkExpected = maxScanWork
   530  
   531  		// hardGoal is a hard limit on the amount that we're willing to push back the
   532  		// heap goal, and that's twice the heap goal (i.e. if GOGC=100 and the heap and/or
   533  		// stacks and/or globals grow to twice their size, this limits the current GC cycle's
   534  		// growth to 4x the original live heap's size).
   535  		//
   536  		// This maintains the invariant that we use no more memory than the next GC cycle
   537  		// will anyway.
   538  		hardGoal := int64((1.0 + float64(gcPercent)/100.0) * float64(heapGoal))
   539  		if extHeapGoal > hardGoal {
   540  			extHeapGoal = hardGoal
   541  		}
   542  		heapGoal = extHeapGoal
   543  	}
   544  	if int64(live) > heapGoal {
   545  		// We're already past our heap goal, even the extrapolated one.
   546  		// Leave ourselves some extra runway, so in the worst case we
   547  		// finish by that point.
   548  		const maxOvershoot = 1.1
   549  		heapGoal = int64(float64(heapGoal) * maxOvershoot)
   550  
   551  		// Compute the upper bound on the scan work remaining.
   552  		scanWorkExpected = maxScanWork
   553  	}
   554  
   555  	// Compute the remaining scan work estimate.
   556  	//
   557  	// Note that we currently count allocations during GC as both
   558  	// scannable heap (heapScan) and scan work completed
   559  	// (scanWork), so allocation will change this difference
   560  	// slowly in the soft regime and not at all in the hard
   561  	// regime.
   562  	scanWorkRemaining := scanWorkExpected - work
   563  	if scanWorkRemaining < 1000 {
   564  		// We set a somewhat arbitrary lower bound on
   565  		// remaining scan work since if we aim a little high,
   566  		// we can miss by a little.
   567  		//
   568  		// We *do* need to enforce that this is at least 1,
   569  		// since marking is racy and double-scanning objects
   570  		// may legitimately make the remaining scan work
   571  		// negative, even in the hard goal regime.
   572  		scanWorkRemaining = 1000
   573  	}
   574  
   575  	// Compute the heap distance remaining.
   576  	heapRemaining := heapGoal - int64(live)
   577  	if heapRemaining <= 0 {
   578  		// This shouldn't happen, but if it does, avoid
   579  		// dividing by zero or setting the assist negative.
   580  		heapRemaining = 1
   581  	}
   582  
   583  	// Compute the mutator assist ratio so by the time the mutator
   584  	// allocates the remaining heap bytes up to heapGoal, it will
   585  	// have done (or stolen) the remaining amount of scan work.
   586  	// Note that the assist ratio values are updated atomically
   587  	// but not together. This means there may be some degree of
   588  	// skew between the two values. This is generally OK as the
   589  	// values shift relatively slowly over the course of a GC
   590  	// cycle.
   591  	assistWorkPerByte := float64(scanWorkRemaining) / float64(heapRemaining)
   592  	assistBytesPerWork := float64(heapRemaining) / float64(scanWorkRemaining)
   593  	c.assistWorkPerByte.Store(assistWorkPerByte)
   594  	c.assistBytesPerWork.Store(assistBytesPerWork)
   595  }
   596  
   597  // endCycle computes the consMark estimate for the next cycle.
   598  // userForced indicates whether the current GC cycle was forced
   599  // by the application.
   600  func (c *gcControllerState) endCycle(now int64, procs int, userForced bool) {
   601  	// Record last heap goal for the scavenger.
   602  	// We'll be updating the heap goal soon.
   603  	gcController.lastHeapGoal = c.heapGoal()
   604  
   605  	// Compute the duration of time for which assists were turned on.
   606  	assistDuration := now - c.markStartTime
   607  
   608  	// Assume background mark hit its utilization goal.
   609  	utilization := gcBackgroundUtilization
   610  	// Add assist utilization; avoid divide by zero.
   611  	if assistDuration > 0 {
   612  		utilization += float64(c.assistTime.Load()) / float64(assistDuration*int64(procs))
   613  	}
   614  
   615  	if c.heapLive.Load() <= c.triggered {
   616  		// Shouldn't happen, but let's be very safe about this in case the
   617  		// GC is somehow extremely short.
   618  		//
   619  		// In this case though, the only reasonable value for c.heapLive-c.triggered
   620  		// would be 0, which isn't really all that useful, i.e. the GC was so short
   621  		// that it didn't matter.
   622  		//
   623  		// Ignore this case and don't update anything.
   624  		return
   625  	}
   626  	idleUtilization := 0.0
   627  	if assistDuration > 0 {
   628  		idleUtilization = float64(c.idleMarkTime.Load()) / float64(assistDuration*int64(procs))
   629  	}
   630  	// Determine the cons/mark ratio.
   631  	//
   632  	// The units we want for the numerator and denominator are both B / cpu-ns.
   633  	// We get this by taking the bytes allocated or scanned, and divide by the amount of
   634  	// CPU time it took for those operations. For allocations, that CPU time is
   635  	//
   636  	//    assistDuration * procs * (1 - utilization)
   637  	//
   638  	// Where utilization includes just background GC workers and assists. It does *not*
   639  	// include idle GC work time, because in theory the mutator is free to take that at
   640  	// any point.
   641  	//
   642  	// For scanning, that CPU time is
   643  	//
   644  	//    assistDuration * procs * (utilization + idleUtilization)
   645  	//
   646  	// In this case, we *include* idle utilization, because that is additional CPU time that
   647  	// the GC had available to it.
   648  	//
   649  	// In effect, idle GC time is sort of double-counted here, but it's very weird compared
   650  	// to other kinds of GC work, because of how fluid it is. Namely, because the mutator is
   651  	// *always* free to take it.
   652  	//
   653  	// So this calculation is really:
   654  	//     (heapLive-trigger) / (assistDuration * procs * (1-utilization)) /
   655  	//         (scanWork) / (assistDuration * procs * (utilization+idleUtilization))
   656  	//
   657  	// Note that because we only care about the ratio, assistDuration and procs cancel out.
   658  	scanWork := c.heapScanWork.Load() + c.stackScanWork.Load() + c.globalsScanWork.Load()
   659  	currentConsMark := (float64(c.heapLive.Load()-c.triggered) * (utilization + idleUtilization)) /
   660  		(float64(scanWork) * (1 - utilization))
   661  
   662  	// Update our cons/mark estimate. This is the maximum of the value we just computed and the last
   663  	// 4 cons/mark values we measured. The reason we take the maximum here is to bias a noisy
   664  	// cons/mark measurement toward fewer assists at the expense of additional GC cycles (starting
   665  	// earlier).
   666  	oldConsMark := c.consMark
   667  	c.consMark = currentConsMark
   668  	for i := range c.lastConsMark {
   669  		if c.lastConsMark[i] > c.consMark {
   670  			c.consMark = c.lastConsMark[i]
   671  		}
   672  	}
   673  	copy(c.lastConsMark[:], c.lastConsMark[1:])
   674  	c.lastConsMark[len(c.lastConsMark)-1] = currentConsMark
   675  
   676  	if debug.gcpacertrace > 0 {
   677  		printlock()
   678  		goal := gcGoalUtilization * 100
   679  		print("pacer: ", int(utilization*100), "% CPU (", int(goal), " exp.) for ")
   680  		print(c.heapScanWork.Load(), "+", c.stackScanWork.Load(), "+", c.globalsScanWork.Load(), " B work (", c.lastHeapScan+c.lastStackScan.Load()+c.globalsScan.Load(), " B exp.) ")
   681  		live := c.heapLive.Load()
   682  		print("in ", c.triggered, " B -> ", live, " B (∆goal ", int64(live)-int64(c.lastHeapGoal), ", cons/mark ", oldConsMark, ")")
   683  		println()
   684  		printunlock()
   685  	}
   686  }
   687  
   688  // enlistWorker encourages another dedicated mark worker to start on
   689  // another P if there are spare worker slots. It is used by putfull
   690  // when more work is made available.
   691  //
   692  // If goexperiment.GreenTeaGC, the caller must not hold a G's scan bit,
   693  // otherwise this could cause a deadlock. This is already enforced by
   694  // the static lock ranking.
   695  //
   696  //go:nowritebarrier
   697  func (c *gcControllerState) enlistWorker() {
   698  	needDedicated := c.dedicatedMarkWorkersNeeded.Load() > 0
   699  
   700  	// Create new workers from idle Ps with goexperiment.GreenTeaGC.
   701  	//
   702  	// Note: with Green Tea, this places a requirement on enlistWorker
   703  	// that it must not be called while a G's scan bit is held.
   704  	if goexperiment.GreenTeaGC {
   705  		needIdle := c.needIdleMarkWorker()
   706  
   707  		// If we're all full on dedicated and idle workers, nothing
   708  		// to do.
   709  		if !needDedicated && !needIdle {
   710  			return
   711  		}
   712  
   713  		// If there are idle Ps, wake one so it will run a worker
   714  		// (the scheduler will already prefer to spin up a new
   715  		// dedicated worker over an idle one).
   716  		if sched.npidle.Load() != 0 && sched.nmspinning.Load() == 0 {
   717  			wakep()
   718  			return
   719  		}
   720  	}
   721  
   722  	// If we still need more dedicated workers, try to preempt a running P
   723  	// so it will switch to a worker.
   724  	if !needDedicated {
   725  		return
   726  	}
   727  
   728  	// Pick a random other P to preempt.
   729  	if gomaxprocs <= 1 {
   730  		return
   731  	}
   732  	gp := getg()
   733  	if gp == nil || gp.m == nil || gp.m.p == 0 {
   734  		return
   735  	}
   736  	myID := gp.m.p.ptr().id
   737  	for tries := 0; tries < 5; tries++ {
   738  		id := int32(cheaprandn(uint32(gomaxprocs - 1)))
   739  		if id >= myID {
   740  			id++
   741  		}
   742  		p := allp[id]
   743  		if p.status != _Prunning {
   744  			continue
   745  		}
   746  		if preemptone(p) {
   747  			return
   748  		}
   749  	}
   750  }
   751  
   752  // findRunnableGCWorker returns a background mark worker for pp if it
   753  // should be run. This must only be called when gcBlackenEnabled != 0.
   754  func (c *gcControllerState) findRunnableGCWorker(pp *p, now int64) (*g, int64) {
   755  	if gcBlackenEnabled == 0 {
   756  		throw("gcControllerState.findRunnable: blackening not enabled")
   757  	}
   758  
   759  	// Since we have the current time, check if the GC CPU limiter
   760  	// hasn't had an update in a while. This check is necessary in
   761  	// case the limiter is on but hasn't been checked in a while and
   762  	// so may have left sufficient headroom to turn off again.
   763  	if now == 0 {
   764  		now = nanotime()
   765  	}
   766  	if gcCPULimiter.needUpdate(now) {
   767  		gcCPULimiter.update(now)
   768  	}
   769  
   770  	if !gcMarkWorkAvailable(pp) {
   771  		// No work to be done right now. This can happen at
   772  		// the end of the mark phase when there are still
   773  		// assists tapering off. Don't bother running a worker
   774  		// now because it'll just return immediately.
   775  		return nil, now
   776  	}
   777  
   778  	if c.dedicatedMarkWorkersNeeded.Load() <= 0 && c.fractionalUtilizationGoal == 0 {
   779  		// No current need for dedicated workers, and no need at all for
   780  		// fractional workers. Check before trying to acquire a worker; when
   781  		// GOMAXPROCS is large, that can be expensive and is often unnecessary.
   782  		//
   783  		// When a dedicated worker stops running, the gcBgMarkWorker loop notes
   784  		// the need for the worker before returning it to the pool. If we don't
   785  		// see the need now, we wouldn't have found it in the pool anyway.
   786  		return nil, now
   787  	}
   788  
   789  	// Grab a worker before we commit to running below.
   790  	node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
   791  	if node == nil {
   792  		// There is at least one worker per P, so normally there are
   793  		// enough workers to run on all Ps, if necessary. However, once
   794  		// a worker enters gcMarkDone it may park without rejoining the
   795  		// pool, thus freeing a P with no corresponding worker.
   796  		// gcMarkDone never depends on another worker doing work, so it
   797  		// is safe to simply do nothing here.
   798  		//
   799  		// If gcMarkDone bails out without completing the mark phase,
   800  		// it will always do so with queued global work. Thus, that P
   801  		// will be immediately eligible to re-run the worker G it was
   802  		// just using, ensuring work can complete.
   803  		return nil, now
   804  	}
   805  
   806  	decIfPositive := func(val *atomic.Int64) bool {
   807  		for {
   808  			v := val.Load()
   809  			if v <= 0 {
   810  				return false
   811  			}
   812  
   813  			if val.CompareAndSwap(v, v-1) {
   814  				return true
   815  			}
   816  		}
   817  	}
   818  
   819  	if decIfPositive(&c.dedicatedMarkWorkersNeeded) {
   820  		// This P is now dedicated to marking until the end of
   821  		// the concurrent mark phase.
   822  		pp.gcMarkWorkerMode = gcMarkWorkerDedicatedMode
   823  	} else if c.fractionalUtilizationGoal == 0 {
   824  		// No need for fractional workers.
   825  		gcBgMarkWorkerPool.push(&node.node)
   826  		return nil, now
   827  	} else {
   828  		// Is this P behind on the fractional utilization
   829  		// goal?
   830  		//
   831  		// This should be kept in sync with pollFractionalWorkerExit.
   832  		delta := now - c.markStartTime
   833  		if delta > 0 && float64(pp.gcFractionalMarkTime)/float64(delta) > c.fractionalUtilizationGoal {
   834  			// Nope. No need to run a fractional worker.
   835  			gcBgMarkWorkerPool.push(&node.node)
   836  			return nil, now
   837  		}
   838  		// Run a fractional worker.
   839  		pp.gcMarkWorkerMode = gcMarkWorkerFractionalMode
   840  	}
   841  
   842  	// Run the background mark worker.
   843  	gp := node.gp.ptr()
   844  	trace := traceAcquire()
   845  	casgstatus(gp, _Gwaiting, _Grunnable)
   846  	if trace.ok() {
   847  		trace.GoUnpark(gp, 0)
   848  		traceRelease(trace)
   849  	}
   850  	return gp, now
   851  }
   852  
   853  // resetLive sets up the controller state for the next mark phase after the end
   854  // of the previous one. Must be called after endCycle and before commit, before
   855  // the world is started.
   856  //
   857  // The world must be stopped.
   858  func (c *gcControllerState) resetLive(bytesMarked uint64) {
   859  	c.heapMarked = bytesMarked
   860  	c.heapLive.Store(bytesMarked)
   861  	c.heapScan.Store(uint64(c.heapScanWork.Load()))
   862  	c.lastHeapScan = uint64(c.heapScanWork.Load())
   863  	c.lastStackScan.Store(uint64(c.stackScanWork.Load()))
   864  	c.triggered = ^uint64(0) // Reset triggered.
   865  
   866  	// heapLive was updated, so emit a trace event.
   867  	trace := traceAcquire()
   868  	if trace.ok() {
   869  		trace.HeapAlloc(bytesMarked)
   870  		traceRelease(trace)
   871  	}
   872  }
   873  
   874  // markWorkerStop must be called whenever a mark worker stops executing.
   875  //
   876  // It updates mark work accounting in the controller by a duration of
   877  // work in nanoseconds and other bookkeeping.
   878  //
   879  // Safe to execute at any time.
   880  func (c *gcControllerState) markWorkerStop(mode gcMarkWorkerMode, duration int64) {
   881  	switch mode {
   882  	case gcMarkWorkerDedicatedMode:
   883  		c.dedicatedMarkTime.Add(duration)
   884  		c.dedicatedMarkWorkersNeeded.Add(1)
   885  	case gcMarkWorkerFractionalMode:
   886  		c.fractionalMarkTime.Add(duration)
   887  	case gcMarkWorkerIdleMode:
   888  		c.idleMarkTime.Add(duration)
   889  		c.removeIdleMarkWorker()
   890  	default:
   891  		throw("markWorkerStop: unknown mark worker mode")
   892  	}
   893  }
   894  
   895  func (c *gcControllerState) update(dHeapLive, dHeapScan int64) {
   896  	if dHeapLive != 0 {
   897  		trace := traceAcquire()
   898  		live := gcController.heapLive.Add(dHeapLive)
   899  		if trace.ok() {
   900  			// gcController.heapLive changed.
   901  			trace.HeapAlloc(live)
   902  			traceRelease(trace)
   903  		}
   904  	}
   905  	if gcBlackenEnabled == 0 {
   906  		// Update heapScan when we're not in a current GC. It is fixed
   907  		// at the beginning of a cycle.
   908  		if dHeapScan != 0 {
   909  			gcController.heapScan.Add(dHeapScan)
   910  		}
   911  	} else {
   912  		// gcController.heapLive changed.
   913  		c.revise()
   914  	}
   915  }
   916  
   917  func (c *gcControllerState) addScannableStack(pp *p, amount int64) {
   918  	if pp == nil {
   919  		c.maxStackScan.Add(amount)
   920  		return
   921  	}
   922  	pp.maxStackScanDelta += amount
   923  	if pp.maxStackScanDelta >= maxStackScanSlack || pp.maxStackScanDelta <= -maxStackScanSlack {
   924  		c.maxStackScan.Add(pp.maxStackScanDelta)
   925  		pp.maxStackScanDelta = 0
   926  	}
   927  }
   928  
   929  func (c *gcControllerState) addGlobals(amount int64) {
   930  	c.globalsScan.Add(amount)
   931  }
   932  
   933  // heapGoal returns the current heap goal.
   934  func (c *gcControllerState) heapGoal() uint64 {
   935  	goal, _ := c.heapGoalInternal()
   936  	return goal
   937  }
   938  
   939  // heapGoalInternal is the implementation of heapGoal which returns additional
   940  // information that is necessary for computing the trigger.
   941  //
   942  // The returned minTrigger is always <= goal.
   943  func (c *gcControllerState) heapGoalInternal() (goal, minTrigger uint64) {
   944  	// Start with the goal calculated for gcPercent.
   945  	goal = c.gcPercentHeapGoal.Load()
   946  
   947  	// Check if the memory-limit-based goal is smaller, and if so, pick that.
   948  	if newGoal := c.memoryLimitHeapGoal(); newGoal < goal {
   949  		goal = newGoal
   950  	} else {
   951  		// We're not limited by the memory limit goal, so perform a series of
   952  		// adjustments that might move the goal forward in a variety of circumstances.
   953  
   954  		sweepDistTrigger := c.sweepDistMinTrigger.Load()
   955  		if sweepDistTrigger > goal {
   956  			// Set the goal to maintain a minimum sweep distance since
   957  			// the last call to commit. Note that we never want to do this
   958  			// if we're in the memory limit regime, because it could push
   959  			// the goal up.
   960  			goal = sweepDistTrigger
   961  		}
   962  		// Since we ignore the sweep distance trigger in the memory
   963  		// limit regime, we need to ensure we don't propagate it to
   964  		// the trigger, because it could cause a violation of the
   965  		// invariant that the trigger < goal.
   966  		minTrigger = sweepDistTrigger
   967  
   968  		// Ensure that the heap goal is at least a little larger than
   969  		// the point at which we triggered. This may not be the case if GC
   970  		// start is delayed or if the allocation that pushed gcController.heapLive
   971  		// over trigger is large or if the trigger is really close to
   972  		// GOGC. Assist is proportional to this distance, so enforce a
   973  		// minimum distance, even if it means going over the GOGC goal
   974  		// by a tiny bit.
   975  		//
   976  		// Ignore this if we're in the memory limit regime: we'd prefer to
   977  		// have the GC respond hard about how close we are to the goal than to
   978  		// push the goal back in such a manner that it could cause us to exceed
   979  		// the memory limit.
   980  		const minRunway = 64 << 10
   981  		if c.triggered != ^uint64(0) && goal < c.triggered+minRunway {
   982  			goal = c.triggered + minRunway
   983  		}
   984  	}
   985  	return
   986  }
   987  
   988  // memoryLimitHeapGoal returns a heap goal derived from memoryLimit.
   989  func (c *gcControllerState) memoryLimitHeapGoal() uint64 {
   990  	// Start by pulling out some values we'll need. Be careful about overflow.
   991  	var heapFree, heapAlloc, mappedReady uint64
   992  	for {
   993  		heapFree = c.heapFree.load()                         // Free and unscavenged memory.
   994  		heapAlloc = c.totalAlloc.Load() - c.totalFree.Load() // Heap object bytes in use.
   995  		mappedReady = c.mappedReady.Load()                   // Total unreleased mapped memory.
   996  		if heapFree+heapAlloc <= mappedReady {
   997  			break
   998  		}
   999  		// It is impossible for total unreleased mapped memory to exceed heap memory, but
  1000  		// because these stats are updated independently, we may observe a partial update
  1001  		// including only some values. Thus, we appear to break the invariant. However,
  1002  		// this condition is necessarily transient, so just try again. In the case of a
  1003  		// persistent accounting error, we'll deadlock here.
  1004  	}
  1005  
  1006  	// Below we compute a goal from memoryLimit. There are a few things to be aware of.
  1007  	// Firstly, the memoryLimit does not easily compare to the heap goal: the former
  1008  	// is total mapped memory by the runtime that hasn't been released, while the latter is
  1009  	// only heap object memory. Intuitively, the way we convert from one to the other is to
  1010  	// subtract everything from memoryLimit that both contributes to the memory limit (so,
  1011  	// ignore scavenged memory) and doesn't contain heap objects. This isn't quite what
  1012  	// lines up with reality, but it's a good starting point.
  1013  	//
  1014  	// In practice this computation looks like the following:
  1015  	//
  1016  	//    goal := memoryLimit - ((mappedReady - heapFree - heapAlloc) + max(mappedReady - memoryLimit, 0))
  1017  	//                    ^1                                    ^2
  1018  	//    goal -= goal / 100 * memoryLimitHeapGoalHeadroomPercent
  1019  	//    ^3
  1020  	//
  1021  	// Let's break this down.
  1022  	//
  1023  	// The first term (marker 1) is everything that contributes to the memory limit and isn't
  1024  	// or couldn't become heap objects. It represents, broadly speaking, non-heap overheads.
  1025  	// One oddity you may have noticed is that we also subtract out heapFree, i.e. unscavenged
  1026  	// memory that may contain heap objects in the future.
  1027  	//
  1028  	// Let's take a step back. In an ideal world, this term would look something like just
  1029  	// the heap goal. That is, we "reserve" enough space for the heap to grow to the heap
  1030  	// goal, and subtract out everything else. This is of course impossible; the definition
  1031  	// is circular! However, this impossible definition contains a key insight: the amount
  1032  	// we're *going* to use matters just as much as whatever we're currently using.
  1033  	//
  1034  	// Consider if the heap shrinks to 1/10th its size, leaving behind lots of free and
  1035  	// unscavenged memory. mappedReady - heapAlloc will be quite large, because of that free
  1036  	// and unscavenged memory, pushing the goal down significantly.
  1037  	//
  1038  	// heapFree is also safe to exclude from the memory limit because in the steady-state, it's
  1039  	// just a pool of memory for future heap allocations, and making new allocations from heapFree
  1040  	// memory doesn't increase overall memory use. In transient states, the scavenger and the
  1041  	// allocator actively manage the pool of heapFree memory to maintain the memory limit.
  1042  	//
  1043  	// The second term (marker 2) is the amount of memory we've exceeded the limit by, and is
  1044  	// intended to help recover from such a situation. By pushing the heap goal down, we also
  1045  	// push the trigger down, triggering and finishing a GC sooner in order to make room for
  1046  	// other memory sources. Note that since we're effectively reducing the heap goal by X bytes,
  1047  	// we're actually giving more than X bytes of headroom back, because the heap goal is in
  1048  	// terms of heap objects, but it takes more than X bytes (e.g. due to fragmentation) to store
  1049  	// X bytes worth of objects.
  1050  	//
  1051  	// The final adjustment (marker 3) reduces the maximum possible memory limit heap goal by
  1052  	// memoryLimitHeapGoalPercent. As the name implies, this is to provide additional headroom in
  1053  	// the face of pacing inaccuracies, and also to leave a buffer of unscavenged memory so the
  1054  	// allocator isn't constantly scavenging. The reduction amount also has a fixed minimum
  1055  	// (memoryLimitMinHeapGoalHeadroom, not pictured) because the aforementioned pacing inaccuracies
  1056  	// disproportionately affect small heaps: as heaps get smaller, the pacer's inputs get fuzzier.
  1057  	// Shorter GC cycles and less GC work means noisy external factors like the OS scheduler have a
  1058  	// greater impact.
  1059  
  1060  	memoryLimit := uint64(c.memoryLimit.Load())
  1061  
  1062  	// Compute term 1.
  1063  	nonHeapMemory := mappedReady - heapFree - heapAlloc
  1064  
  1065  	// Compute term 2.
  1066  	var overage uint64
  1067  	if mappedReady > memoryLimit {
  1068  		overage = mappedReady - memoryLimit
  1069  	}
  1070  
  1071  	if nonHeapMemory+overage >= memoryLimit {
  1072  		// We're at a point where non-heap memory exceeds the memory limit on its own.
  1073  		// There's honestly not much we can do here but just trigger GCs continuously
  1074  		// and let the CPU limiter reign that in. Something has to give at this point.
  1075  		// Set it to heapMarked, the lowest possible goal.
  1076  		return c.heapMarked
  1077  	}
  1078  
  1079  	// Compute the goal.
  1080  	goal := memoryLimit - (nonHeapMemory + overage)
  1081  
  1082  	// Apply some headroom to the goal to account for pacing inaccuracies and to reduce
  1083  	// the impact of scavenging at allocation time in response to a high allocation rate
  1084  	// when GOGC=off. See issue #57069. Also, be careful about small limits.
  1085  	headroom := goal / 100 * memoryLimitHeapGoalHeadroomPercent
  1086  	if headroom < memoryLimitMinHeapGoalHeadroom {
  1087  		// Set a fixed minimum to deal with the particularly large effect pacing inaccuracies
  1088  		// have for smaller heaps.
  1089  		headroom = memoryLimitMinHeapGoalHeadroom
  1090  	}
  1091  	if goal < headroom || goal-headroom < headroom {
  1092  		goal = headroom
  1093  	} else {
  1094  		goal = goal - headroom
  1095  	}
  1096  	// Don't let us go below the live heap. A heap goal below the live heap doesn't make sense.
  1097  	if goal < c.heapMarked {
  1098  		goal = c.heapMarked
  1099  	}
  1100  	return goal
  1101  }
  1102  
  1103  const (
  1104  	// These constants determine the bounds on the GC trigger as a fraction
  1105  	// of heap bytes allocated between the start of a GC (heapLive == heapMarked)
  1106  	// and the end of a GC (heapLive == heapGoal).
  1107  	//
  1108  	// The constants are obscured in this way for efficiency. The denominator
  1109  	// of the fraction is always a power-of-two for a quick division, so that
  1110  	// the numerator is a single constant integer multiplication.
  1111  	triggerRatioDen = 64
  1112  
  1113  	// The minimum trigger constant was chosen empirically: given a sufficiently
  1114  	// fast/scalable allocator with 48 Ps that could drive the trigger ratio
  1115  	// to <0.05, this constant causes applications to retain the same peak
  1116  	// RSS compared to not having this allocator.
  1117  	minTriggerRatioNum = 45 // ~0.7
  1118  
  1119  	// The maximum trigger constant is chosen somewhat arbitrarily, but the
  1120  	// current constant has served us well over the years.
  1121  	maxTriggerRatioNum = 61 // ~0.95
  1122  )
  1123  
  1124  // trigger returns the current point at which a GC should trigger along with
  1125  // the heap goal.
  1126  //
  1127  // The returned value may be compared against heapLive to determine whether
  1128  // the GC should trigger. Thus, the GC trigger condition should be (but may
  1129  // not be, in the case of small movements for efficiency) checked whenever
  1130  // the heap goal may change.
  1131  func (c *gcControllerState) trigger() (uint64, uint64) {
  1132  	goal, minTrigger := c.heapGoalInternal()
  1133  
  1134  	// Invariant: the trigger must always be less than the heap goal.
  1135  	//
  1136  	// Note that the memory limit sets a hard maximum on our heap goal,
  1137  	// but the live heap may grow beyond it.
  1138  
  1139  	if c.heapMarked >= goal {
  1140  		// The goal should never be smaller than heapMarked, but let's be
  1141  		// defensive about it. The only reasonable trigger here is one that
  1142  		// causes a continuous GC cycle at heapMarked, but respect the goal
  1143  		// if it came out as smaller than that.
  1144  		return goal, goal
  1145  	}
  1146  
  1147  	// Below this point, c.heapMarked < goal.
  1148  
  1149  	// heapMarked is our absolute minimum, and it's possible the trigger
  1150  	// bound we get from heapGoalinternal is less than that.
  1151  	if minTrigger < c.heapMarked {
  1152  		minTrigger = c.heapMarked
  1153  	}
  1154  
  1155  	// If we let the trigger go too low, then if the application
  1156  	// is allocating very rapidly we might end up in a situation
  1157  	// where we're allocating black during a nearly always-on GC.
  1158  	// The result of this is a growing heap and ultimately an
  1159  	// increase in RSS. By capping us at a point >0, we're essentially
  1160  	// saying that we're OK using more CPU during the GC to prevent
  1161  	// this growth in RSS.
  1162  	triggerLowerBound := ((goal-c.heapMarked)/triggerRatioDen)*minTriggerRatioNum + c.heapMarked
  1163  	if minTrigger < triggerLowerBound {
  1164  		minTrigger = triggerLowerBound
  1165  	}
  1166  
  1167  	// For small heaps, set the max trigger point at maxTriggerRatio of the way
  1168  	// from the live heap to the heap goal. This ensures we always have *some*
  1169  	// headroom when the GC actually starts. For larger heaps, set the max trigger
  1170  	// point at the goal, minus the minimum heap size.
  1171  	//
  1172  	// This choice follows from the fact that the minimum heap size is chosen
  1173  	// to reflect the costs of a GC with no work to do. With a large heap but
  1174  	// very little scan work to perform, this gives us exactly as much runway
  1175  	// as we would need, in the worst case.
  1176  	maxTrigger := ((goal-c.heapMarked)/triggerRatioDen)*maxTriggerRatioNum + c.heapMarked
  1177  	if goal > defaultHeapMinimum && goal-defaultHeapMinimum > maxTrigger {
  1178  		maxTrigger = goal - defaultHeapMinimum
  1179  	}
  1180  	maxTrigger = max(maxTrigger, minTrigger)
  1181  
  1182  	// Compute the trigger from our bounds and the runway stored by commit.
  1183  	var trigger uint64
  1184  	runway := c.runway.Load()
  1185  	if runway > goal {
  1186  		trigger = minTrigger
  1187  	} else {
  1188  		trigger = goal - runway
  1189  	}
  1190  	trigger = max(trigger, minTrigger)
  1191  	trigger = min(trigger, maxTrigger)
  1192  	if trigger > goal {
  1193  		print("trigger=", trigger, " heapGoal=", goal, "\n")
  1194  		print("minTrigger=", minTrigger, " maxTrigger=", maxTrigger, "\n")
  1195  		throw("produced a trigger greater than the heap goal")
  1196  	}
  1197  	return trigger, goal
  1198  }
  1199  
  1200  // commit recomputes all pacing parameters needed to derive the
  1201  // trigger and the heap goal. Namely, the gcPercent-based heap goal,
  1202  // and the amount of runway we want to give the GC this cycle.
  1203  //
  1204  // This can be called any time. If GC is the in the middle of a
  1205  // concurrent phase, it will adjust the pacing of that phase.
  1206  //
  1207  // isSweepDone should be the result of calling isSweepDone(),
  1208  // unless we're testing or we know we're executing during a GC cycle.
  1209  //
  1210  // This depends on gcPercent, gcController.heapMarked, and
  1211  // gcController.heapLive. These must be up to date.
  1212  //
  1213  // Callers must call gcControllerState.revise after calling this
  1214  // function if the GC is enabled.
  1215  //
  1216  // mheap_.lock must be held or the world must be stopped.
  1217  func (c *gcControllerState) commit(isSweepDone bool) {
  1218  	if !c.test {
  1219  		assertWorldStoppedOrLockHeld(&mheap_.lock)
  1220  	}
  1221  
  1222  	if isSweepDone {
  1223  		// The sweep is done, so there aren't any restrictions on the trigger
  1224  		// we need to think about.
  1225  		c.sweepDistMinTrigger.Store(0)
  1226  	} else {
  1227  		// Concurrent sweep happens in the heap growth
  1228  		// from gcController.heapLive to trigger. Make sure we
  1229  		// give the sweeper some runway if it doesn't have enough.
  1230  		c.sweepDistMinTrigger.Store(c.heapLive.Load() + sweepMinHeapDistance)
  1231  	}
  1232  
  1233  	// Compute the next GC goal, which is when the allocated heap
  1234  	// has grown by GOGC/100 over where it started the last cycle,
  1235  	// plus additional runway for non-heap sources of GC work.
  1236  	gcPercentHeapGoal := ^uint64(0)
  1237  	if gcPercent := c.gcPercent.Load(); gcPercent >= 0 {
  1238  		gcPercentHeapGoal = c.heapMarked + (c.heapMarked+c.lastStackScan.Load()+c.globalsScan.Load())*uint64(gcPercent)/100
  1239  	}
  1240  	// Apply the minimum heap size here. It's defined in terms of gcPercent
  1241  	// and is only updated by functions that call commit.
  1242  	if gcPercentHeapGoal < c.heapMinimum {
  1243  		gcPercentHeapGoal = c.heapMinimum
  1244  	}
  1245  	c.gcPercentHeapGoal.Store(gcPercentHeapGoal)
  1246  
  1247  	// Compute the amount of runway we want the GC to have by using our
  1248  	// estimate of the cons/mark ratio.
  1249  	//
  1250  	// The idea is to take our expected scan work, and multiply it by
  1251  	// the cons/mark ratio to determine how long it'll take to complete
  1252  	// that scan work in terms of bytes allocated. This gives us our GC's
  1253  	// runway.
  1254  	//
  1255  	// However, the cons/mark ratio is a ratio of rates per CPU-second, but
  1256  	// here we care about the relative rates for some division of CPU
  1257  	// resources among the mutator and the GC.
  1258  	//
  1259  	// To summarize, we have B / cpu-ns, and we want B / ns. We get that
  1260  	// by multiplying by our desired division of CPU resources. We choose
  1261  	// to express CPU resources as GOMAPROCS*fraction. Note that because
  1262  	// we're working with a ratio here, we can omit the number of CPU cores,
  1263  	// because they'll appear in the numerator and denominator and cancel out.
  1264  	// As a result, this is basically just "weighing" the cons/mark ratio by
  1265  	// our desired division of resources.
  1266  	//
  1267  	// Furthermore, by setting the runway so that CPU resources are divided
  1268  	// this way, assuming that the cons/mark ratio is correct, we make that
  1269  	// division a reality.
  1270  	c.runway.Store(uint64((c.consMark * (1 - gcGoalUtilization) / (gcGoalUtilization)) * float64(c.lastHeapScan+c.lastStackScan.Load()+c.globalsScan.Load())))
  1271  }
  1272  
  1273  // setGCPercent updates gcPercent. commit must be called after.
  1274  // Returns the old value of gcPercent.
  1275  //
  1276  // The world must be stopped, or mheap_.lock must be held.
  1277  func (c *gcControllerState) setGCPercent(in int32) int32 {
  1278  	if !c.test {
  1279  		assertWorldStoppedOrLockHeld(&mheap_.lock)
  1280  	}
  1281  
  1282  	out := c.gcPercent.Load()
  1283  	if in < 0 {
  1284  		in = -1
  1285  	}
  1286  	c.heapMinimum = defaultHeapMinimum * uint64(in) / 100
  1287  	c.gcPercent.Store(in)
  1288  
  1289  	return out
  1290  }
  1291  
  1292  //go:linkname setGCPercent runtime/debug.setGCPercent
  1293  func setGCPercent(in int32) (out int32) {
  1294  	// Run on the system stack since we grab the heap lock.
  1295  	systemstack(func() {
  1296  		lock(&mheap_.lock)
  1297  		out = gcController.setGCPercent(in)
  1298  		gcControllerCommit()
  1299  		unlock(&mheap_.lock)
  1300  	})
  1301  
  1302  	// If we just disabled GC, wait for any concurrent GC mark to
  1303  	// finish so we always return with no GC running.
  1304  	if in < 0 {
  1305  		gcWaitOnMark(work.cycles.Load())
  1306  	}
  1307  
  1308  	return out
  1309  }
  1310  
  1311  func readGOGC() int32 {
  1312  	p := gogetenv("GOGC")
  1313  	if p == "off" {
  1314  		return -1
  1315  	}
  1316  	if n, ok := strconv.Atoi32(p); ok {
  1317  		return n
  1318  	}
  1319  	return 100
  1320  }
  1321  
  1322  // setMemoryLimit updates memoryLimit. commit must be called after
  1323  // Returns the old value of memoryLimit.
  1324  //
  1325  // The world must be stopped, or mheap_.lock must be held.
  1326  func (c *gcControllerState) setMemoryLimit(in int64) int64 {
  1327  	if !c.test {
  1328  		assertWorldStoppedOrLockHeld(&mheap_.lock)
  1329  	}
  1330  
  1331  	out := c.memoryLimit.Load()
  1332  	if in >= 0 {
  1333  		c.memoryLimit.Store(in)
  1334  	}
  1335  
  1336  	return out
  1337  }
  1338  
  1339  //go:linkname setMemoryLimit runtime/debug.setMemoryLimit
  1340  func setMemoryLimit(in int64) (out int64) {
  1341  	// Run on the system stack since we grab the heap lock.
  1342  	systemstack(func() {
  1343  		lock(&mheap_.lock)
  1344  		out = gcController.setMemoryLimit(in)
  1345  		if in < 0 || out == in {
  1346  			// If we're just checking the value or not changing
  1347  			// it, there's no point in doing the rest.
  1348  			unlock(&mheap_.lock)
  1349  			return
  1350  		}
  1351  		gcControllerCommit()
  1352  		unlock(&mheap_.lock)
  1353  	})
  1354  	return out
  1355  }
  1356  
  1357  func readGOMEMLIMIT() int64 {
  1358  	p := gogetenv("GOMEMLIMIT")
  1359  	if p == "" || p == "off" {
  1360  		return math.MaxInt64
  1361  	}
  1362  	n, ok := parseByteCount(p)
  1363  	if !ok {
  1364  		print("GOMEMLIMIT=", p, "\n")
  1365  		throw("malformed GOMEMLIMIT; see `go doc runtime/debug.SetMemoryLimit`")
  1366  	}
  1367  	return n
  1368  }
  1369  
  1370  // addIdleMarkWorker attempts to add a new idle mark worker.
  1371  //
  1372  // If this returns true, the caller must become an idle mark worker unless
  1373  // there's no background mark worker goroutines in the pool. This case is
  1374  // harmless because there are already background mark workers running.
  1375  // If this returns false, the caller must NOT become an idle mark worker.
  1376  //
  1377  // nosplit because it may be called without a P.
  1378  //
  1379  //go:nosplit
  1380  func (c *gcControllerState) addIdleMarkWorker() bool {
  1381  	for {
  1382  		old := c.idleMarkWorkers.Load()
  1383  		n, max := int32(old&uint64(^uint32(0))), int32(old>>32)
  1384  		if n >= max {
  1385  			// See the comment on idleMarkWorkers for why
  1386  			// n > max is tolerated.
  1387  			return false
  1388  		}
  1389  		if n < 0 {
  1390  			print("n=", n, " max=", max, "\n")
  1391  			throw("negative idle mark workers")
  1392  		}
  1393  		new := uint64(uint32(n+1)) | (uint64(max) << 32)
  1394  		if c.idleMarkWorkers.CompareAndSwap(old, new) {
  1395  			return true
  1396  		}
  1397  	}
  1398  }
  1399  
  1400  // needIdleMarkWorker is a hint as to whether another idle mark worker is needed.
  1401  //
  1402  // The caller must still call addIdleMarkWorker to become one. This is mainly
  1403  // useful for a quick check before an expensive operation.
  1404  //
  1405  // nosplit because it may be called without a P.
  1406  //
  1407  //go:nosplit
  1408  func (c *gcControllerState) needIdleMarkWorker() bool {
  1409  	p := c.idleMarkWorkers.Load()
  1410  	n, max := int32(p&uint64(^uint32(0))), int32(p>>32)
  1411  	return n < max
  1412  }
  1413  
  1414  // removeIdleMarkWorker must be called when a new idle mark worker stops executing.
  1415  func (c *gcControllerState) removeIdleMarkWorker() {
  1416  	for {
  1417  		old := c.idleMarkWorkers.Load()
  1418  		n, max := int32(old&uint64(^uint32(0))), int32(old>>32)
  1419  		if n-1 < 0 {
  1420  			print("n=", n, " max=", max, "\n")
  1421  			throw("negative idle mark workers")
  1422  		}
  1423  		new := uint64(uint32(n-1)) | (uint64(max) << 32)
  1424  		if c.idleMarkWorkers.CompareAndSwap(old, new) {
  1425  			return
  1426  		}
  1427  	}
  1428  }
  1429  
  1430  // setMaxIdleMarkWorkers sets the maximum number of idle mark workers allowed.
  1431  //
  1432  // This method is optimistic in that it does not wait for the number of
  1433  // idle mark workers to reduce to max before returning; it assumes the workers
  1434  // will deschedule themselves.
  1435  func (c *gcControllerState) setMaxIdleMarkWorkers(max int32) {
  1436  	for {
  1437  		old := c.idleMarkWorkers.Load()
  1438  		n := int32(old & uint64(^uint32(0)))
  1439  		if n < 0 {
  1440  			print("n=", n, " max=", max, "\n")
  1441  			throw("negative idle mark workers")
  1442  		}
  1443  		new := uint64(uint32(n)) | (uint64(max) << 32)
  1444  		if c.idleMarkWorkers.CompareAndSwap(old, new) {
  1445  			return
  1446  		}
  1447  	}
  1448  }
  1449  
  1450  // gcControllerCommit is gcController.commit, but passes arguments from live
  1451  // (non-test) data. It also updates any consumers of the GC pacing, such as
  1452  // sweep pacing and the background scavenger.
  1453  //
  1454  // Calls gcController.commit.
  1455  //
  1456  // The heap lock must be held, so this must be executed on the system stack.
  1457  //
  1458  //go:systemstack
  1459  func gcControllerCommit() {
  1460  	assertWorldStoppedOrLockHeld(&mheap_.lock)
  1461  
  1462  	gcController.commit(isSweepDone())
  1463  
  1464  	// Update mark pacing.
  1465  	if gcphase != _GCoff {
  1466  		gcController.revise()
  1467  	}
  1468  
  1469  	// TODO(mknyszek): This isn't really accurate any longer because the heap
  1470  	// goal is computed dynamically. Still useful to snapshot, but not as useful.
  1471  	trace := traceAcquire()
  1472  	if trace.ok() {
  1473  		trace.HeapGoal()
  1474  		traceRelease(trace)
  1475  	}
  1476  
  1477  	trigger, heapGoal := gcController.trigger()
  1478  	gcPaceSweeper(trigger)
  1479  	gcPaceScavenger(gcController.memoryLimit.Load(), heapGoal, gcController.lastHeapGoal)
  1480  }
  1481  

View as plain text