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/strconv"
    13  	_ "unsafe"
    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.Store(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  func (c *gcControllerState) endCycle(now int64, procs int) {
   599  	// Record last heap goal for the scavenger.
   600  	// We'll be updating the heap goal soon.
   601  	gcController.lastHeapGoal = c.heapGoal()
   602  
   603  	// Compute the duration of time for which assists were turned on.
   604  	assistDuration := now - c.markStartTime
   605  
   606  	// Assume background mark hit its utilization goal.
   607  	utilization := gcBackgroundUtilization
   608  	// Add assist utilization; avoid divide by zero.
   609  	if assistDuration > 0 {
   610  		utilization += float64(c.assistTime.Load()) / float64(assistDuration*int64(procs))
   611  	}
   612  
   613  	if c.heapLive.Load() <= c.triggered {
   614  		// Shouldn't happen, but let's be very safe about this in case the
   615  		// GC is somehow extremely short.
   616  		//
   617  		// In this case though, the only reasonable value for c.heapLive-c.triggered
   618  		// would be 0, which isn't really all that useful, i.e. the GC was so short
   619  		// that it didn't matter.
   620  		//
   621  		// Ignore this case and don't update anything.
   622  		return
   623  	}
   624  	idleUtilization := 0.0
   625  	if assistDuration > 0 {
   626  		idleUtilization = float64(c.idleMarkTime.Load()) / float64(assistDuration*int64(procs))
   627  	}
   628  	// Determine the cons/mark ratio.
   629  	//
   630  	// The units we want for the numerator and denominator are both B / cpu-ns.
   631  	// We get this by taking the bytes allocated or scanned, and divide by the amount of
   632  	// CPU time it took for those operations. For allocations, that CPU time is
   633  	//
   634  	//    assistDuration * procs * (1 - utilization)
   635  	//
   636  	// Where utilization includes just background GC workers and assists. It does *not*
   637  	// include idle GC work time, because in theory the mutator is free to take that at
   638  	// any point.
   639  	//
   640  	// For scanning, that CPU time is
   641  	//
   642  	//    assistDuration * procs * (utilization + idleUtilization)
   643  	//
   644  	// In this case, we *include* idle utilization, because that is additional CPU time that
   645  	// the GC had available to it.
   646  	//
   647  	// In effect, idle GC time is sort of double-counted here, but it's very weird compared
   648  	// to other kinds of GC work, because of how fluid it is. Namely, because the mutator is
   649  	// *always* free to take it.
   650  	//
   651  	// So this calculation is really:
   652  	//     (heapLive-trigger) / (assistDuration * procs * (1-utilization)) /
   653  	//         (scanWork) / (assistDuration * procs * (utilization+idleUtilization))
   654  	//
   655  	// Note that because we only care about the ratio, assistDuration and procs cancel out.
   656  	scanWork := c.heapScanWork.Load() + c.stackScanWork.Load() + c.globalsScanWork.Load()
   657  	currentConsMark := (float64(c.heapLive.Load()-c.triggered) * (utilization + idleUtilization)) /
   658  		(float64(scanWork) * (1 - utilization))
   659  
   660  	// Update our cons/mark estimate. This is the maximum of the value we just computed and the last
   661  	// 4 cons/mark values we measured. The reason we take the maximum here is to bias a noisy
   662  	// cons/mark measurement toward fewer assists at the expense of additional GC cycles (starting
   663  	// earlier).
   664  	oldConsMark := c.consMark
   665  	c.consMark = currentConsMark
   666  	for i := range c.lastConsMark {
   667  		if c.lastConsMark[i] > c.consMark {
   668  			c.consMark = c.lastConsMark[i]
   669  		}
   670  	}
   671  	copy(c.lastConsMark[:], c.lastConsMark[1:])
   672  	c.lastConsMark[len(c.lastConsMark)-1] = currentConsMark
   673  
   674  	if debug.gcpacertrace > 0 {
   675  		printlock()
   676  		goal := gcGoalUtilization * 100
   677  		print("pacer: ", int(utilization*100), "% CPU (", int(goal), " exp.) for ")
   678  		print(c.heapScanWork.Load(), "+", c.stackScanWork.Load(), "+", c.globalsScanWork.Load(), " B work (", c.lastHeapScan+c.lastStackScan.Load()+c.globalsScan.Load(), " B exp.) ")
   679  		live := c.heapLive.Load()
   680  		print("in ", c.triggered, " B -> ", live, " B (∆goal ", int64(live)-int64(c.lastHeapGoal), ", cons/mark ", oldConsMark, ")")
   681  		println()
   682  		printunlock()
   683  	}
   684  }
   685  
   686  // enlistWorker encourages another dedicated mark worker to start on
   687  // another P if there are spare worker slots. It is used by putfull
   688  // when more work is made available.
   689  //
   690  // If goexperiment.GreenTeaGC, the caller must not hold a G's scan bit,
   691  // otherwise this could cause a deadlock. This is already enforced by
   692  // the static lock ranking.
   693  //
   694  //go:nowritebarrier
   695  func (c *gcControllerState) enlistWorker() {
   696  	needDedicated := c.dedicatedMarkWorkersNeeded.Load() > 0
   697  
   698  	// Create new workers from idle Ps with goexperiment.GreenTeaGC.
   699  	//
   700  	// Note: with Green Tea, this places a requirement on enlistWorker
   701  	// that it must not be called while a G's scan bit is held.
   702  	if goexperiment.GreenTeaGC {
   703  		needIdle := c.needIdleMarkWorker()
   704  
   705  		// If we're all full on dedicated and idle workers, nothing
   706  		// to do.
   707  		if !needDedicated && !needIdle {
   708  			return
   709  		}
   710  
   711  		// If there are idle Ps, wake one so it will run a worker
   712  		// (the scheduler will already prefer to spin up a new
   713  		// dedicated worker over an idle one).
   714  		if sched.npidle.Load() != 0 && sched.nmspinning.Load() == 0 {
   715  			wakep() // Likely to consume our worker request.
   716  			return
   717  		}
   718  	}
   719  
   720  	// If we still need more dedicated workers, try to preempt a running P
   721  	// so it will switch to a worker.
   722  	if !needDedicated {
   723  		return
   724  	}
   725  
   726  	// Pick a random other P to preempt.
   727  	if gomaxprocs <= 1 {
   728  		return
   729  	}
   730  	gp := getg()
   731  	if gp == nil || gp.m == nil || gp.m.p == 0 {
   732  		return
   733  	}
   734  	myID := gp.m.p.ptr().id
   735  	for tries := 0; tries < 5; tries++ {
   736  		id := int32(cheaprandn(uint32(gomaxprocs - 1)))
   737  		if id >= myID {
   738  			id++
   739  		}
   740  		p := allp[id]
   741  		if p.status != _Prunning {
   742  			continue
   743  		}
   744  		if preemptone(p) {
   745  			return
   746  		}
   747  	}
   748  }
   749  
   750  // assignWaitingGCWorker assigns a background mark worker to pp if one should
   751  // be run.
   752  //
   753  // If a worker is selected, it is assigned to pp.nextMarkGCWorker and the P is
   754  // wired as a GC mark worker. The G is still in _Gwaiting. If no worker is
   755  // selected, ok returns false.
   756  //
   757  // If assignedWaitingGCWorker returns true, this P must either:
   758  // - Mark the G as runnable and run it, clearing pp.nextMarkGCWorker.
   759  // - Or, call c.releaseNextGCMarkWorker.
   760  //
   761  // This must only be called when gcBlackenEnabled != 0.
   762  func (c *gcControllerState) assignWaitingGCWorker(pp *p, now int64) (bool, int64) {
   763  	if gcBlackenEnabled == 0 {
   764  		throw("gcControllerState.findRunnable: blackening not enabled")
   765  	}
   766  
   767  	if now == 0 {
   768  		now = nanotime()
   769  	}
   770  
   771  	if !gcShouldScheduleWorker(pp) {
   772  		// No good reason to schedule a worker. This can happen at
   773  		// the end of the mark phase when there are still
   774  		// assists tapering off. Don't bother running a worker
   775  		// now because it'll just return immediately.
   776  		return false, now
   777  	}
   778  
   779  	if c.dedicatedMarkWorkersNeeded.Load() <= 0 && c.fractionalUtilizationGoal == 0 {
   780  		// No current need for dedicated workers, and no need at all for
   781  		// fractional workers. Check before trying to acquire a worker; when
   782  		// GOMAXPROCS is large, that can be expensive and is often unnecessary.
   783  		//
   784  		// When a dedicated worker stops running, the gcBgMarkWorker loop notes
   785  		// the need for the worker before returning it to the pool. If we don't
   786  		// see the need now, we wouldn't have found it in the pool anyway.
   787  		return false, now
   788  	}
   789  
   790  	// Grab a worker before we commit to running below.
   791  	node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
   792  	if node == nil {
   793  		// There is at least one worker per P, so normally there are
   794  		// enough workers to run on all Ps, if necessary. However, once
   795  		// a worker enters gcMarkDone it may park without rejoining the
   796  		// pool, thus freeing a P with no corresponding worker.
   797  		// gcMarkDone never depends on another worker doing work, so it
   798  		// is safe to simply do nothing here.
   799  		//
   800  		// If gcMarkDone bails out without completing the mark phase,
   801  		// it will always do so with queued global work. Thus, that P
   802  		// will be immediately eligible to re-run the worker G it was
   803  		// just using, ensuring work can complete.
   804  		return false, now
   805  	}
   806  
   807  	decIfPositive := func(val *atomic.Int64) bool {
   808  		for {
   809  			v := val.Load()
   810  			if v <= 0 {
   811  				return false
   812  			}
   813  
   814  			if val.CompareAndSwap(v, v-1) {
   815  				return true
   816  			}
   817  		}
   818  	}
   819  
   820  	if decIfPositive(&c.dedicatedMarkWorkersNeeded) {
   821  		// This P is now dedicated to marking until the end of
   822  		// the concurrent mark phase.
   823  		pp.gcMarkWorkerMode = gcMarkWorkerDedicatedMode
   824  	} else if c.fractionalUtilizationGoal == 0 {
   825  		// No need for fractional workers.
   826  		gcBgMarkWorkerPool.push(&node.node)
   827  		return false, now
   828  	} else {
   829  		// Is this P behind on the fractional utilization
   830  		// goal?
   831  		//
   832  		// This should be kept in sync with pollFractionalWorkerExit.
   833  		delta := now - c.markStartTime
   834  		if delta > 0 && float64(pp.gcFractionalMarkTime.Load())/float64(delta) > c.fractionalUtilizationGoal {
   835  			// Nope. No need to run a fractional worker.
   836  			gcBgMarkWorkerPool.push(&node.node)
   837  			return false, now
   838  		}
   839  		// Run a fractional worker.
   840  		pp.gcMarkWorkerMode = gcMarkWorkerFractionalMode
   841  	}
   842  
   843  	pp.nextGCMarkWorker = node
   844  	return true, now
   845  }
   846  
   847  // findRunnableGCWorker returns a background mark worker for pp if it
   848  // should be run.
   849  //
   850  // If findRunnableGCWorker returns a G, this P is wired as a GC mark worker and
   851  // must run the G.
   852  //
   853  // This must only be called when gcBlackenEnabled != 0.
   854  //
   855  // This function is allowed to have write barriers because it is called from
   856  // the portion of findRunnable that always has a P.
   857  //
   858  //go:yeswritebarrierrec
   859  func (c *gcControllerState) findRunnableGCWorker(pp *p, now int64) (*g, int64) {
   860  	// Since we have the current time, check if the GC CPU limiter
   861  	// hasn't had an update in a while. This check is necessary in
   862  	// case the limiter is on but hasn't been checked in a while and
   863  	// so may have left sufficient headroom to turn off again.
   864  	if now == 0 {
   865  		now = nanotime()
   866  	}
   867  	if gcCPULimiter.needUpdate(now) {
   868  		gcCPULimiter.update(now)
   869  	}
   870  
   871  	// If a worker wasn't already assigned by procresize, assign one now.
   872  	if pp.nextGCMarkWorker == nil {
   873  		ok, now := c.assignWaitingGCWorker(pp, now)
   874  		if !ok {
   875  			return nil, now
   876  		}
   877  	}
   878  
   879  	node := pp.nextGCMarkWorker
   880  	pp.nextGCMarkWorker = nil
   881  
   882  	// Run the background mark worker.
   883  	gp := node.gp.ptr()
   884  	trace := traceAcquire()
   885  	casgstatus(gp, _Gwaiting, _Grunnable)
   886  	if trace.ok() {
   887  		trace.GoUnpark(gp, 0)
   888  		traceRelease(trace)
   889  	}
   890  	return gp, now
   891  }
   892  
   893  // Release an unused pp.nextGCMarkWorker, if any.
   894  //
   895  // This function is allowed to have write barriers because it is called from
   896  // the portion of schedule.
   897  //
   898  //go:yeswritebarrierrec
   899  func (c *gcControllerState) releaseNextGCMarkWorker(pp *p) {
   900  	node := pp.nextGCMarkWorker
   901  	if node == nil {
   902  		return
   903  	}
   904  
   905  	c.markWorkerStop(pp.gcMarkWorkerMode, 0)
   906  	gcBgMarkWorkerPool.push(&node.node)
   907  	pp.nextGCMarkWorker = nil
   908  }
   909  
   910  // resetLive sets up the controller state for the next mark phase after the end
   911  // of the previous one. Must be called after endCycle and before commit, before
   912  // the world is started.
   913  //
   914  // The world must be stopped.
   915  func (c *gcControllerState) resetLive(bytesMarked uint64) {
   916  	c.heapMarked = bytesMarked
   917  	c.heapLive.Store(bytesMarked)
   918  	c.heapScan.Store(uint64(c.heapScanWork.Load()))
   919  	c.lastHeapScan = uint64(c.heapScanWork.Load())
   920  	c.lastStackScan.Store(uint64(c.stackScanWork.Load()))
   921  	c.triggered = ^uint64(0) // Reset triggered.
   922  
   923  	// heapLive was updated, so emit a trace event.
   924  	trace := traceAcquire()
   925  	if trace.ok() {
   926  		trace.HeapAlloc(bytesMarked)
   927  		traceRelease(trace)
   928  	}
   929  }
   930  
   931  // markWorkerStop must be called whenever a mark worker stops executing.
   932  //
   933  // It updates mark work accounting in the controller by a duration of
   934  // work in nanoseconds and other bookkeeping.
   935  //
   936  // Safe to execute at any time.
   937  func (c *gcControllerState) markWorkerStop(mode gcMarkWorkerMode, duration int64) {
   938  	switch mode {
   939  	case gcMarkWorkerDedicatedMode:
   940  		c.dedicatedMarkTime.Add(duration)
   941  		c.dedicatedMarkWorkersNeeded.Add(1)
   942  	case gcMarkWorkerFractionalMode:
   943  		c.fractionalMarkTime.Add(duration)
   944  	case gcMarkWorkerIdleMode:
   945  		c.idleMarkTime.Add(duration)
   946  		c.removeIdleMarkWorker()
   947  	default:
   948  		throw("markWorkerStop: unknown mark worker mode")
   949  	}
   950  }
   951  
   952  func (c *gcControllerState) update(dHeapLive, dHeapScan int64) {
   953  	if dHeapLive != 0 {
   954  		trace := traceAcquire()
   955  		live := gcController.heapLive.Add(dHeapLive)
   956  		if trace.ok() {
   957  			// gcController.heapLive changed.
   958  			trace.HeapAlloc(live)
   959  			traceRelease(trace)
   960  		}
   961  	}
   962  	if gcBlackenEnabled == 0 {
   963  		// Update heapScan when we're not in a current GC. It is fixed
   964  		// at the beginning of a cycle.
   965  		if dHeapScan != 0 {
   966  			gcController.heapScan.Add(dHeapScan)
   967  		}
   968  	} else {
   969  		// gcController.heapLive changed.
   970  		c.revise()
   971  	}
   972  }
   973  
   974  func (c *gcControllerState) addScannableStack(pp *p, amount int64) {
   975  	if pp == nil {
   976  		c.maxStackScan.Add(amount)
   977  		return
   978  	}
   979  	pp.maxStackScanDelta += amount
   980  	if pp.maxStackScanDelta >= maxStackScanSlack || pp.maxStackScanDelta <= -maxStackScanSlack {
   981  		c.maxStackScan.Add(pp.maxStackScanDelta)
   982  		pp.maxStackScanDelta = 0
   983  	}
   984  }
   985  
   986  func (c *gcControllerState) addGlobals(amount int64) {
   987  	c.globalsScan.Add(amount)
   988  }
   989  
   990  // heapGoal returns the current heap goal.
   991  func (c *gcControllerState) heapGoal() uint64 {
   992  	goal, _ := c.heapGoalInternal()
   993  	return goal
   994  }
   995  
   996  // heapGoalInternal is the implementation of heapGoal which returns additional
   997  // information that is necessary for computing the trigger.
   998  //
   999  // The returned minTrigger is always <= goal.
  1000  func (c *gcControllerState) heapGoalInternal() (goal, minTrigger uint64) {
  1001  	// Start with the goal calculated for gcPercent.
  1002  	goal = c.gcPercentHeapGoal.Load()
  1003  
  1004  	// Check if the memory-limit-based goal is smaller, and if so, pick that.
  1005  	if newGoal := c.memoryLimitHeapGoal(); newGoal < goal {
  1006  		goal = newGoal
  1007  	} else {
  1008  		// We're not limited by the memory limit goal, so perform a series of
  1009  		// adjustments that might move the goal forward in a variety of circumstances.
  1010  
  1011  		sweepDistTrigger := c.sweepDistMinTrigger.Load()
  1012  		if sweepDistTrigger > goal {
  1013  			// Set the goal to maintain a minimum sweep distance since
  1014  			// the last call to commit. Note that we never want to do this
  1015  			// if we're in the memory limit regime, because it could push
  1016  			// the goal up.
  1017  			goal = sweepDistTrigger
  1018  		}
  1019  		// Since we ignore the sweep distance trigger in the memory
  1020  		// limit regime, we need to ensure we don't propagate it to
  1021  		// the trigger, because it could cause a violation of the
  1022  		// invariant that the trigger < goal.
  1023  		minTrigger = sweepDistTrigger
  1024  
  1025  		// Ensure that the heap goal is at least a little larger than
  1026  		// the point at which we triggered. This may not be the case if GC
  1027  		// start is delayed or if the allocation that pushed gcController.heapLive
  1028  		// over trigger is large or if the trigger is really close to
  1029  		// GOGC. Assist is proportional to this distance, so enforce a
  1030  		// minimum distance, even if it means going over the GOGC goal
  1031  		// by a tiny bit.
  1032  		//
  1033  		// Ignore this if we're in the memory limit regime: we'd prefer to
  1034  		// have the GC respond hard about how close we are to the goal than to
  1035  		// push the goal back in such a manner that it could cause us to exceed
  1036  		// the memory limit.
  1037  		const minRunway = 64 << 10
  1038  		if c.triggered != ^uint64(0) && goal < c.triggered+minRunway {
  1039  			goal = c.triggered + minRunway
  1040  		}
  1041  	}
  1042  	return
  1043  }
  1044  
  1045  // memoryLimitHeapGoal returns a heap goal derived from memoryLimit.
  1046  func (c *gcControllerState) memoryLimitHeapGoal() uint64 {
  1047  	// Start by pulling out some values we'll need. Be careful about overflow.
  1048  	var heapFree, heapAlloc, mappedReady uint64
  1049  	for {
  1050  		heapFree = c.heapFree.load()                         // Free and unscavenged memory.
  1051  		heapAlloc = c.totalAlloc.Load() - c.totalFree.Load() // Heap object bytes in use.
  1052  		mappedReady = c.mappedReady.Load()                   // Total unreleased mapped memory.
  1053  		if heapFree+heapAlloc <= mappedReady {
  1054  			break
  1055  		}
  1056  		// It is impossible for total unreleased mapped memory to exceed heap memory, but
  1057  		// because these stats are updated independently, we may observe a partial update
  1058  		// including only some values. Thus, we appear to break the invariant. However,
  1059  		// this condition is necessarily transient, so just try again. In the case of a
  1060  		// persistent accounting error, we'll deadlock here.
  1061  	}
  1062  
  1063  	// Below we compute a goal from memoryLimit. There are a few things to be aware of.
  1064  	// Firstly, the memoryLimit does not easily compare to the heap goal: the former
  1065  	// is total mapped memory by the runtime that hasn't been released, while the latter is
  1066  	// only heap object memory. Intuitively, the way we convert from one to the other is to
  1067  	// subtract everything from memoryLimit that both contributes to the memory limit (so,
  1068  	// ignore scavenged memory) and doesn't contain heap objects. This isn't quite what
  1069  	// lines up with reality, but it's a good starting point.
  1070  	//
  1071  	// In practice this computation looks like the following:
  1072  	//
  1073  	//    goal := memoryLimit - ((mappedReady - heapFree - heapAlloc) + max(mappedReady - memoryLimit, 0))
  1074  	//                    ^1                                    ^2
  1075  	//    goal -= goal / 100 * memoryLimitHeapGoalHeadroomPercent
  1076  	//    ^3
  1077  	//
  1078  	// Let's break this down.
  1079  	//
  1080  	// The first term (marker 1) is everything that contributes to the memory limit and isn't
  1081  	// or couldn't become heap objects. It represents, broadly speaking, non-heap overheads.
  1082  	// One oddity you may have noticed is that we also subtract out heapFree, i.e. unscavenged
  1083  	// memory that may contain heap objects in the future.
  1084  	//
  1085  	// Let's take a step back. In an ideal world, this term would look something like just
  1086  	// the heap goal. That is, we "reserve" enough space for the heap to grow to the heap
  1087  	// goal, and subtract out everything else. This is of course impossible; the definition
  1088  	// is circular! However, this impossible definition contains a key insight: the amount
  1089  	// we're *going* to use matters just as much as whatever we're currently using.
  1090  	//
  1091  	// Consider if the heap shrinks to 1/10th its size, leaving behind lots of free and
  1092  	// unscavenged memory. mappedReady - heapAlloc will be quite large, because of that free
  1093  	// and unscavenged memory, pushing the goal down significantly.
  1094  	//
  1095  	// heapFree is also safe to exclude from the memory limit because in the steady-state, it's
  1096  	// just a pool of memory for future heap allocations, and making new allocations from heapFree
  1097  	// memory doesn't increase overall memory use. In transient states, the scavenger and the
  1098  	// allocator actively manage the pool of heapFree memory to maintain the memory limit.
  1099  	//
  1100  	// The second term (marker 2) is the amount of memory we've exceeded the limit by, and is
  1101  	// intended to help recover from such a situation. By pushing the heap goal down, we also
  1102  	// push the trigger down, triggering and finishing a GC sooner in order to make room for
  1103  	// other memory sources. Note that since we're effectively reducing the heap goal by X bytes,
  1104  	// we're actually giving more than X bytes of headroom back, because the heap goal is in
  1105  	// terms of heap objects, but it takes more than X bytes (e.g. due to fragmentation) to store
  1106  	// X bytes worth of objects.
  1107  	//
  1108  	// The final adjustment (marker 3) reduces the maximum possible memory limit heap goal by
  1109  	// memoryLimitHeapGoalPercent. As the name implies, this is to provide additional headroom in
  1110  	// the face of pacing inaccuracies, and also to leave a buffer of unscavenged memory so the
  1111  	// allocator isn't constantly scavenging. The reduction amount also has a fixed minimum
  1112  	// (memoryLimitMinHeapGoalHeadroom, not pictured) because the aforementioned pacing inaccuracies
  1113  	// disproportionately affect small heaps: as heaps get smaller, the pacer's inputs get fuzzier.
  1114  	// Shorter GC cycles and less GC work means noisy external factors like the OS scheduler have a
  1115  	// greater impact.
  1116  
  1117  	memoryLimit := uint64(c.memoryLimit.Load())
  1118  
  1119  	// Compute term 1.
  1120  	nonHeapMemory := mappedReady - heapFree - heapAlloc
  1121  
  1122  	// Compute term 2.
  1123  	var overage uint64
  1124  	if mappedReady > memoryLimit {
  1125  		overage = mappedReady - memoryLimit
  1126  	}
  1127  
  1128  	if nonHeapMemory+overage >= memoryLimit {
  1129  		// We're at a point where non-heap memory exceeds the memory limit on its own.
  1130  		// There's honestly not much we can do here but just trigger GCs continuously
  1131  		// and let the CPU limiter reign that in. Something has to give at this point.
  1132  		// Set it to heapMarked, the lowest possible goal.
  1133  		return c.heapMarked
  1134  	}
  1135  
  1136  	// Compute the goal.
  1137  	goal := memoryLimit - (nonHeapMemory + overage)
  1138  
  1139  	// Apply some headroom to the goal to account for pacing inaccuracies and to reduce
  1140  	// the impact of scavenging at allocation time in response to a high allocation rate
  1141  	// when GOGC=off. See issue #57069. Also, be careful about small limits.
  1142  	headroom := goal / 100 * memoryLimitHeapGoalHeadroomPercent
  1143  	if headroom < memoryLimitMinHeapGoalHeadroom {
  1144  		// Set a fixed minimum to deal with the particularly large effect pacing inaccuracies
  1145  		// have for smaller heaps.
  1146  		headroom = memoryLimitMinHeapGoalHeadroom
  1147  	}
  1148  	if goal < headroom || goal-headroom < headroom {
  1149  		goal = headroom
  1150  	} else {
  1151  		goal = goal - headroom
  1152  	}
  1153  	// Don't let us go below the live heap. A heap goal below the live heap doesn't make sense.
  1154  	if goal < c.heapMarked {
  1155  		goal = c.heapMarked
  1156  	}
  1157  	return goal
  1158  }
  1159  
  1160  const (
  1161  	// These constants determine the bounds on the GC trigger as a fraction
  1162  	// of heap bytes allocated between the start of a GC (heapLive == heapMarked)
  1163  	// and the end of a GC (heapLive == heapGoal).
  1164  	//
  1165  	// The constants are obscured in this way for efficiency. The denominator
  1166  	// of the fraction is always a power-of-two for a quick division, so that
  1167  	// the numerator is a single constant integer multiplication.
  1168  	triggerRatioDen = 64
  1169  
  1170  	// The minimum trigger constant was chosen empirically: given a sufficiently
  1171  	// fast/scalable allocator with 48 Ps that could drive the trigger ratio
  1172  	// to <0.05, this constant causes applications to retain the same peak
  1173  	// RSS compared to not having this allocator.
  1174  	minTriggerRatioNum = 45 // ~0.7
  1175  
  1176  	// The maximum trigger constant is chosen somewhat arbitrarily, but the
  1177  	// current constant has served us well over the years.
  1178  	maxTriggerRatioNum = 61 // ~0.95
  1179  )
  1180  
  1181  // trigger returns the current point at which a GC should trigger along with
  1182  // the heap goal.
  1183  //
  1184  // The returned value may be compared against heapLive to determine whether
  1185  // the GC should trigger. Thus, the GC trigger condition should be (but may
  1186  // not be, in the case of small movements for efficiency) checked whenever
  1187  // the heap goal may change.
  1188  func (c *gcControllerState) trigger() (uint64, uint64) {
  1189  	goal, minTrigger := c.heapGoalInternal()
  1190  
  1191  	// Invariant: the trigger must always be less than the heap goal.
  1192  	//
  1193  	// Note that the memory limit sets a hard maximum on our heap goal,
  1194  	// but the live heap may grow beyond it.
  1195  
  1196  	if c.heapMarked >= goal {
  1197  		// The goal should never be smaller than heapMarked, but let's be
  1198  		// defensive about it. The only reasonable trigger here is one that
  1199  		// causes a continuous GC cycle at heapMarked, but respect the goal
  1200  		// if it came out as smaller than that.
  1201  		return goal, goal
  1202  	}
  1203  
  1204  	// Below this point, c.heapMarked < goal.
  1205  
  1206  	// heapMarked is our absolute minimum, and it's possible the trigger
  1207  	// bound we get from heapGoalinternal is less than that.
  1208  	if minTrigger < c.heapMarked {
  1209  		minTrigger = c.heapMarked
  1210  	}
  1211  
  1212  	// If we let the trigger go too low, then if the application
  1213  	// is allocating very rapidly we might end up in a situation
  1214  	// where we're allocating black during a nearly always-on GC.
  1215  	// The result of this is a growing heap and ultimately an
  1216  	// increase in RSS. By capping us at a point >0, we're essentially
  1217  	// saying that we're OK using more CPU during the GC to prevent
  1218  	// this growth in RSS.
  1219  	triggerLowerBound := ((goal-c.heapMarked)/triggerRatioDen)*minTriggerRatioNum + c.heapMarked
  1220  	if minTrigger < triggerLowerBound {
  1221  		minTrigger = triggerLowerBound
  1222  	}
  1223  
  1224  	// For small heaps, set the max trigger point at maxTriggerRatio of the way
  1225  	// from the live heap to the heap goal. This ensures we always have *some*
  1226  	// headroom when the GC actually starts. For larger heaps, set the max trigger
  1227  	// point at the goal, minus the minimum heap size.
  1228  	//
  1229  	// This choice follows from the fact that the minimum heap size is chosen
  1230  	// to reflect the costs of a GC with no work to do. With a large heap but
  1231  	// very little scan work to perform, this gives us exactly as much runway
  1232  	// as we would need, in the worst case.
  1233  	maxTrigger := ((goal-c.heapMarked)/triggerRatioDen)*maxTriggerRatioNum + c.heapMarked
  1234  	if goal > defaultHeapMinimum && goal-defaultHeapMinimum > maxTrigger {
  1235  		maxTrigger = goal - defaultHeapMinimum
  1236  	}
  1237  	maxTrigger = max(maxTrigger, minTrigger)
  1238  
  1239  	// Compute the trigger from our bounds and the runway stored by commit.
  1240  	var trigger uint64
  1241  	runway := c.runway.Load()
  1242  	if runway > goal {
  1243  		trigger = minTrigger
  1244  	} else {
  1245  		trigger = goal - runway
  1246  	}
  1247  	trigger = max(trigger, minTrigger)
  1248  	trigger = min(trigger, maxTrigger)
  1249  	if trigger > goal {
  1250  		print("trigger=", trigger, " heapGoal=", goal, "\n")
  1251  		print("minTrigger=", minTrigger, " maxTrigger=", maxTrigger, "\n")
  1252  		throw("produced a trigger greater than the heap goal")
  1253  	}
  1254  	return trigger, goal
  1255  }
  1256  
  1257  // commit recomputes all pacing parameters needed to derive the
  1258  // trigger and the heap goal. Namely, the gcPercent-based heap goal,
  1259  // and the amount of runway we want to give the GC this cycle.
  1260  //
  1261  // This can be called any time. If GC is the in the middle of a
  1262  // concurrent phase, it will adjust the pacing of that phase.
  1263  //
  1264  // isSweepDone should be the result of calling isSweepDone(),
  1265  // unless we're testing or we know we're executing during a GC cycle.
  1266  //
  1267  // This depends on gcPercent, gcController.heapMarked, and
  1268  // gcController.heapLive. These must be up to date.
  1269  //
  1270  // Callers must call gcControllerState.revise after calling this
  1271  // function if the GC is enabled.
  1272  //
  1273  // mheap_.lock must be held or the world must be stopped.
  1274  func (c *gcControllerState) commit(isSweepDone bool) {
  1275  	if !c.test {
  1276  		assertWorldStoppedOrLockHeld(&mheap_.lock)
  1277  	}
  1278  
  1279  	if isSweepDone {
  1280  		// The sweep is done, so there aren't any restrictions on the trigger
  1281  		// we need to think about.
  1282  		c.sweepDistMinTrigger.Store(0)
  1283  	} else {
  1284  		// Concurrent sweep happens in the heap growth
  1285  		// from gcController.heapLive to trigger. Make sure we
  1286  		// give the sweeper some runway if it doesn't have enough.
  1287  		c.sweepDistMinTrigger.Store(c.heapLive.Load() + sweepMinHeapDistance)
  1288  	}
  1289  
  1290  	// Compute the next GC goal, which is when the allocated heap
  1291  	// has grown by GOGC/100 over where it started the last cycle,
  1292  	// plus additional runway for non-heap sources of GC work.
  1293  	gcPercentHeapGoal := ^uint64(0)
  1294  	if gcPercent := c.gcPercent.Load(); gcPercent >= 0 {
  1295  		gcPercentHeapGoal = c.heapMarked + (c.heapMarked+c.lastStackScan.Load()+c.globalsScan.Load())*uint64(gcPercent)/100
  1296  	}
  1297  	// Apply the minimum heap size here. It's defined in terms of gcPercent
  1298  	// and is only updated by functions that call commit.
  1299  	if gcPercentHeapGoal < c.heapMinimum {
  1300  		gcPercentHeapGoal = c.heapMinimum
  1301  	}
  1302  	c.gcPercentHeapGoal.Store(gcPercentHeapGoal)
  1303  
  1304  	// Compute the amount of runway we want the GC to have by using our
  1305  	// estimate of the cons/mark ratio.
  1306  	//
  1307  	// The idea is to take our expected scan work, and multiply it by
  1308  	// the cons/mark ratio to determine how long it'll take to complete
  1309  	// that scan work in terms of bytes allocated. This gives us our GC's
  1310  	// runway.
  1311  	//
  1312  	// However, the cons/mark ratio is a ratio of rates per CPU-second, but
  1313  	// here we care about the relative rates for some division of CPU
  1314  	// resources among the mutator and the GC.
  1315  	//
  1316  	// To summarize, we have B / cpu-ns, and we want B / ns. We get that
  1317  	// by multiplying by our desired division of CPU resources. We choose
  1318  	// to express CPU resources as GOMAPROCS*fraction. Note that because
  1319  	// we're working with a ratio here, we can omit the number of CPU cores,
  1320  	// because they'll appear in the numerator and denominator and cancel out.
  1321  	// As a result, this is basically just "weighing" the cons/mark ratio by
  1322  	// our desired division of resources.
  1323  	//
  1324  	// Furthermore, by setting the runway so that CPU resources are divided
  1325  	// this way, assuming that the cons/mark ratio is correct, we make that
  1326  	// division a reality.
  1327  	c.runway.Store(uint64((c.consMark * (1 - gcGoalUtilization) / (gcGoalUtilization)) * float64(c.lastHeapScan+c.lastStackScan.Load()+c.globalsScan.Load())))
  1328  }
  1329  
  1330  // setGCPercent updates gcPercent. commit must be called after.
  1331  // Returns the old value of gcPercent.
  1332  //
  1333  // The world must be stopped, or mheap_.lock must be held.
  1334  func (c *gcControllerState) setGCPercent(in int32) int32 {
  1335  	if !c.test {
  1336  		assertWorldStoppedOrLockHeld(&mheap_.lock)
  1337  	}
  1338  
  1339  	out := c.gcPercent.Load()
  1340  	if in < 0 {
  1341  		in = -1
  1342  	}
  1343  	c.heapMinimum = defaultHeapMinimum * uint64(in) / 100
  1344  	c.gcPercent.Store(in)
  1345  
  1346  	return out
  1347  }
  1348  
  1349  //go:linkname setGCPercent runtime/debug.setGCPercent
  1350  func setGCPercent(in int32) (out int32) {
  1351  	// Run on the system stack since we grab the heap lock.
  1352  	systemstack(func() {
  1353  		lock(&mheap_.lock)
  1354  		out = gcController.setGCPercent(in)
  1355  		gcControllerCommit()
  1356  		unlock(&mheap_.lock)
  1357  	})
  1358  
  1359  	// If we just disabled GC, wait for any concurrent GC mark to
  1360  	// finish so we always return with no GC running.
  1361  	if in < 0 {
  1362  		gcWaitOnMark(work.cycles.Load())
  1363  	}
  1364  
  1365  	return out
  1366  }
  1367  
  1368  func readGOGC() int32 {
  1369  	p := gogetenv("GOGC")
  1370  	if p == "off" {
  1371  		return -1
  1372  	}
  1373  	if n, err := strconv.ParseInt(p, 10, 32); err == nil {
  1374  		return int32(n)
  1375  	}
  1376  	return 100
  1377  }
  1378  
  1379  // setMemoryLimit updates memoryLimit. commit must be called after
  1380  // Returns the old value of memoryLimit.
  1381  //
  1382  // The world must be stopped, or mheap_.lock must be held.
  1383  func (c *gcControllerState) setMemoryLimit(in int64) int64 {
  1384  	if !c.test {
  1385  		assertWorldStoppedOrLockHeld(&mheap_.lock)
  1386  	}
  1387  
  1388  	out := c.memoryLimit.Load()
  1389  	if in >= 0 {
  1390  		c.memoryLimit.Store(in)
  1391  	}
  1392  
  1393  	return out
  1394  }
  1395  
  1396  //go:linkname setMemoryLimit runtime/debug.setMemoryLimit
  1397  func setMemoryLimit(in int64) (out int64) {
  1398  	// Run on the system stack since we grab the heap lock.
  1399  	systemstack(func() {
  1400  		lock(&mheap_.lock)
  1401  		out = gcController.setMemoryLimit(in)
  1402  		if in < 0 || out == in {
  1403  			// If we're just checking the value or not changing
  1404  			// it, there's no point in doing the rest.
  1405  			unlock(&mheap_.lock)
  1406  			return
  1407  		}
  1408  		gcControllerCommit()
  1409  		unlock(&mheap_.lock)
  1410  	})
  1411  	return out
  1412  }
  1413  
  1414  func readGOMEMLIMIT() int64 {
  1415  	p := gogetenv("GOMEMLIMIT")
  1416  	if p == "" || p == "off" {
  1417  		return math.MaxInt64
  1418  	}
  1419  	n, ok := parseByteCount(p)
  1420  	if !ok {
  1421  		print("GOMEMLIMIT=", p, "\n")
  1422  		throw("malformed GOMEMLIMIT; see `go doc runtime/debug.SetMemoryLimit`")
  1423  	}
  1424  	return n
  1425  }
  1426  
  1427  // addIdleMarkWorker attempts to add a new idle mark worker.
  1428  //
  1429  // If this returns true, the caller must become an idle mark worker unless
  1430  // there's no background mark worker goroutines in the pool. This case is
  1431  // harmless because there are already background mark workers running.
  1432  // If this returns false, the caller must NOT become an idle mark worker.
  1433  //
  1434  // nosplit because it may be called without a P.
  1435  //
  1436  //go:nosplit
  1437  func (c *gcControllerState) addIdleMarkWorker() bool {
  1438  	for {
  1439  		old := c.idleMarkWorkers.Load()
  1440  		n, max := int32(old&uint64(^uint32(0))), int32(old>>32)
  1441  		if n >= max {
  1442  			// See the comment on idleMarkWorkers for why
  1443  			// n > max is tolerated.
  1444  			return false
  1445  		}
  1446  		if n < 0 {
  1447  			print("n=", n, " max=", max, "\n")
  1448  			throw("negative idle mark workers")
  1449  		}
  1450  		new := uint64(uint32(n+1)) | (uint64(max) << 32)
  1451  		if c.idleMarkWorkers.CompareAndSwap(old, new) {
  1452  			return true
  1453  		}
  1454  	}
  1455  }
  1456  
  1457  // needIdleMarkWorker is a hint as to whether another idle mark worker is needed.
  1458  //
  1459  // The caller must still call addIdleMarkWorker to become one. This is mainly
  1460  // useful for a quick check before an expensive operation.
  1461  //
  1462  // nosplit because it may be called without a P.
  1463  //
  1464  //go:nosplit
  1465  func (c *gcControllerState) needIdleMarkWorker() bool {
  1466  	p := c.idleMarkWorkers.Load()
  1467  	n, max := int32(p&uint64(^uint32(0))), int32(p>>32)
  1468  	return n < max
  1469  }
  1470  
  1471  // removeIdleMarkWorker must be called when a new idle mark worker stops executing.
  1472  func (c *gcControllerState) removeIdleMarkWorker() {
  1473  	for {
  1474  		old := c.idleMarkWorkers.Load()
  1475  		n, max := int32(old&uint64(^uint32(0))), int32(old>>32)
  1476  		if n-1 < 0 {
  1477  			print("n=", n, " max=", max, "\n")
  1478  			throw("negative idle mark workers")
  1479  		}
  1480  		new := uint64(uint32(n-1)) | (uint64(max) << 32)
  1481  		if c.idleMarkWorkers.CompareAndSwap(old, new) {
  1482  			return
  1483  		}
  1484  	}
  1485  }
  1486  
  1487  // setMaxIdleMarkWorkers sets the maximum number of idle mark workers allowed.
  1488  //
  1489  // This method is optimistic in that it does not wait for the number of
  1490  // idle mark workers to reduce to max before returning; it assumes the workers
  1491  // will deschedule themselves.
  1492  func (c *gcControllerState) setMaxIdleMarkWorkers(max int32) {
  1493  	for {
  1494  		old := c.idleMarkWorkers.Load()
  1495  		n := int32(old & uint64(^uint32(0)))
  1496  		if n < 0 {
  1497  			print("n=", n, " max=", max, "\n")
  1498  			throw("negative idle mark workers")
  1499  		}
  1500  		new := uint64(uint32(n)) | (uint64(max) << 32)
  1501  		if c.idleMarkWorkers.CompareAndSwap(old, new) {
  1502  			return
  1503  		}
  1504  	}
  1505  }
  1506  
  1507  // gcControllerCommit is gcController.commit, but passes arguments from live
  1508  // (non-test) data. It also updates any consumers of the GC pacing, such as
  1509  // sweep pacing and the background scavenger.
  1510  //
  1511  // Calls gcController.commit.
  1512  //
  1513  // The heap lock must be held, so this must be executed on the system stack.
  1514  //
  1515  //go:systemstack
  1516  func gcControllerCommit() {
  1517  	assertWorldStoppedOrLockHeld(&mheap_.lock)
  1518  
  1519  	gcController.commit(isSweepDone())
  1520  
  1521  	// Update mark pacing.
  1522  	if gcphase != _GCoff {
  1523  		gcController.revise()
  1524  	}
  1525  
  1526  	// TODO(mknyszek): This isn't really accurate any longer because the heap
  1527  	// goal is computed dynamically. Still useful to snapshot, but not as useful.
  1528  	trace := traceAcquire()
  1529  	if trace.ok() {
  1530  		trace.HeapGoal()
  1531  		traceRelease(trace)
  1532  	}
  1533  
  1534  	trigger, heapGoal := gcController.trigger()
  1535  	gcPaceSweeper(trigger)
  1536  	gcPaceScavenger(gcController.memoryLimit.Load(), heapGoal, gcController.lastHeapGoal)
  1537  }
  1538  

View as plain text