Black Lives Matter. Support the Equal Justice Initiative.

Source file src/runtime/mgc.go

Documentation: runtime

     1  // Copyright 2009 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  // Garbage collector (GC).
     6  //
     7  // The GC runs concurrently with mutator threads, is type accurate (aka precise), allows multiple
     8  // GC thread to run in parallel. It is a concurrent mark and sweep that uses a write barrier. It is
     9  // non-generational and non-compacting. Allocation is done using size segregated per P allocation
    10  // areas to minimize fragmentation while eliminating locks in the common case.
    11  //
    12  // The algorithm decomposes into several steps.
    13  // This is a high level description of the algorithm being used. For an overview of GC a good
    14  // place to start is Richard Jones' gchandbook.org.
    15  //
    16  // The algorithm's intellectual heritage includes Dijkstra's on-the-fly algorithm, see
    17  // Edsger W. Dijkstra, Leslie Lamport, A. J. Martin, C. S. Scholten, and E. F. M. Steffens. 1978.
    18  // On-the-fly garbage collection: an exercise in cooperation. Commun. ACM 21, 11 (November 1978),
    19  // 966-975.
    20  // For journal quality proofs that these steps are complete, correct, and terminate see
    21  // Hudson, R., and Moss, J.E.B. Copying Garbage Collection without stopping the world.
    22  // Concurrency and Computation: Practice and Experience 15(3-5), 2003.
    23  //
    24  // 1. GC performs sweep termination.
    25  //
    26  //    a. Stop the world. This causes all Ps to reach a GC safe-point.
    27  //
    28  //    b. Sweep any unswept spans. There will only be unswept spans if
    29  //    this GC cycle was forced before the expected time.
    30  //
    31  // 2. GC performs the mark phase.
    32  //
    33  //    a. Prepare for the mark phase by setting gcphase to _GCmark
    34  //    (from _GCoff), enabling the write barrier, enabling mutator
    35  //    assists, and enqueueing root mark jobs. No objects may be
    36  //    scanned until all Ps have enabled the write barrier, which is
    37  //    accomplished using STW.
    38  //
    39  //    b. Start the world. From this point, GC work is done by mark
    40  //    workers started by the scheduler and by assists performed as
    41  //    part of allocation. The write barrier shades both the
    42  //    overwritten pointer and the new pointer value for any pointer
    43  //    writes (see mbarrier.go for details). Newly allocated objects
    44  //    are immediately marked black.
    45  //
    46  //    c. GC performs root marking jobs. This includes scanning all
    47  //    stacks, shading all globals, and shading any heap pointers in
    48  //    off-heap runtime data structures. Scanning a stack stops a
    49  //    goroutine, shades any pointers found on its stack, and then
    50  //    resumes the goroutine.
    51  //
    52  //    d. GC drains the work queue of grey objects, scanning each grey
    53  //    object to black and shading all pointers found in the object
    54  //    (which in turn may add those pointers to the work queue).
    55  //
    56  //    e. Because GC work is spread across local caches, GC uses a
    57  //    distributed termination algorithm to detect when there are no
    58  //    more root marking jobs or grey objects (see gcMarkDone). At this
    59  //    point, GC transitions to mark termination.
    60  //
    61  // 3. GC performs mark termination.
    62  //
    63  //    a. Stop the world.
    64  //
    65  //    b. Set gcphase to _GCmarktermination, and disable workers and
    66  //    assists.
    67  //
    68  //    c. Perform housekeeping like flushing mcaches.
    69  //
    70  // 4. GC performs the sweep phase.
    71  //
    72  //    a. Prepare for the sweep phase by setting gcphase to _GCoff,
    73  //    setting up sweep state and disabling the write barrier.
    74  //
    75  //    b. Start the world. From this point on, newly allocated objects
    76  //    are white, and allocating sweeps spans before use if necessary.
    77  //
    78  //    c. GC does concurrent sweeping in the background and in response
    79  //    to allocation. See description below.
    80  //
    81  // 5. When sufficient allocation has taken place, replay the sequence
    82  // starting with 1 above. See discussion of GC rate below.
    83  
    84  // Concurrent sweep.
    85  //
    86  // The sweep phase proceeds concurrently with normal program execution.
    87  // The heap is swept span-by-span both lazily (when a goroutine needs another span)
    88  // and concurrently in a background goroutine (this helps programs that are not CPU bound).
    89  // At the end of STW mark termination all spans are marked as "needs sweeping".
    90  //
    91  // The background sweeper goroutine simply sweeps spans one-by-one.
    92  //
    93  // To avoid requesting more OS memory while there are unswept spans, when a
    94  // goroutine needs another span, it first attempts to reclaim that much memory
    95  // by sweeping. When a goroutine needs to allocate a new small-object span, it
    96  // sweeps small-object spans for the same object size until it frees at least
    97  // one object. When a goroutine needs to allocate large-object span from heap,
    98  // it sweeps spans until it frees at least that many pages into heap. There is
    99  // one case where this may not suffice: if a goroutine sweeps and frees two
   100  // nonadjacent one-page spans to the heap, it will allocate a new two-page
   101  // span, but there can still be other one-page unswept spans which could be
   102  // combined into a two-page span.
   103  //
   104  // It's critical to ensure that no operations proceed on unswept spans (that would corrupt
   105  // mark bits in GC bitmap). During GC all mcaches are flushed into the central cache,
   106  // so they are empty. When a goroutine grabs a new span into mcache, it sweeps it.
   107  // When a goroutine explicitly frees an object or sets a finalizer, it ensures that
   108  // the span is swept (either by sweeping it, or by waiting for the concurrent sweep to finish).
   109  // The finalizer goroutine is kicked off only when all spans are swept.
   110  // When the next GC starts, it sweeps all not-yet-swept spans (if any).
   111  
   112  // GC rate.
   113  // Next GC is after we've allocated an extra amount of memory proportional to
   114  // the amount already in use. The proportion is controlled by GOGC environment variable
   115  // (100 by default). If GOGC=100 and we're using 4M, we'll GC again when we get to 8M
   116  // (this mark is tracked in next_gc variable). This keeps the GC cost in linear
   117  // proportion to the allocation cost. Adjusting GOGC just changes the linear constant
   118  // (and also the amount of extra memory used).
   119  
   120  // Oblets
   121  //
   122  // In order to prevent long pauses while scanning large objects and to
   123  // improve parallelism, the garbage collector breaks up scan jobs for
   124  // objects larger than maxObletBytes into "oblets" of at most
   125  // maxObletBytes. When scanning encounters the beginning of a large
   126  // object, it scans only the first oblet and enqueues the remaining
   127  // oblets as new scan jobs.
   128  
   129  package runtime
   130  
   131  import (
   132  	"internal/cpu"
   133  	"runtime/internal/atomic"
   134  	"unsafe"
   135  )
   136  
   137  const (
   138  	_DebugGC         = 0
   139  	_ConcurrentSweep = true
   140  	_FinBlockSize    = 4 * 1024
   141  
   142  	// debugScanConservative enables debug logging for stack
   143  	// frames that are scanned conservatively.
   144  	debugScanConservative = false
   145  
   146  	// sweepMinHeapDistance is a lower bound on the heap distance
   147  	// (in bytes) reserved for concurrent sweeping between GC
   148  	// cycles.
   149  	sweepMinHeapDistance = 1024 * 1024
   150  )
   151  
   152  // heapminimum is the minimum heap size at which to trigger GC.
   153  // For small heaps, this overrides the usual GOGC*live set rule.
   154  //
   155  // When there is a very small live set but a lot of allocation, simply
   156  // collecting when the heap reaches GOGC*live results in many GC
   157  // cycles and high total per-GC overhead. This minimum amortizes this
   158  // per-GC overhead while keeping the heap reasonably small.
   159  //
   160  // During initialization this is set to 4MB*GOGC/100. In the case of
   161  // GOGC==0, this will set heapminimum to 0, resulting in constant
   162  // collection even when the heap size is small, which is useful for
   163  // debugging.
   164  var heapminimum uint64 = defaultHeapMinimum
   165  
   166  // defaultHeapMinimum is the value of heapminimum for GOGC==100.
   167  const defaultHeapMinimum = 4 << 20
   168  
   169  // Initialized from $GOGC.  GOGC=off means no GC.
   170  var gcpercent int32
   171  
   172  func gcinit() {
   173  	if unsafe.Sizeof(workbuf{}) != _WorkbufSize {
   174  		throw("size of Workbuf is suboptimal")
   175  	}
   176  
   177  	// No sweep on the first cycle.
   178  	mheap_.sweepdone = 1
   179  
   180  	// Set a reasonable initial GC trigger.
   181  	memstats.triggerRatio = 7 / 8.0
   182  
   183  	// Fake a heap_marked value so it looks like a trigger at
   184  	// heapminimum is the appropriate growth from heap_marked.
   185  	// This will go into computing the initial GC goal.
   186  	memstats.heap_marked = uint64(float64(heapminimum) / (1 + memstats.triggerRatio))
   187  
   188  	// Set gcpercent from the environment. This will also compute
   189  	// and set the GC trigger and goal.
   190  	_ = setGCPercent(readgogc())
   191  
   192  	work.startSema = 1
   193  	work.markDoneSema = 1
   194  }
   195  
   196  func readgogc() int32 {
   197  	p := gogetenv("GOGC")
   198  	if p == "off" {
   199  		return -1
   200  	}
   201  	if n, ok := atoi32(p); ok {
   202  		return n
   203  	}
   204  	return 100
   205  }
   206  
   207  // gcenable is called after the bulk of the runtime initialization,
   208  // just before we're about to start letting user code run.
   209  // It kicks off the background sweeper goroutine, the background
   210  // scavenger goroutine, and enables GC.
   211  func gcenable() {
   212  	// Kick off sweeping and scavenging.
   213  	c := make(chan int, 2)
   214  	go bgsweep(c)
   215  	go bgscavenge(c)
   216  	<-c
   217  	<-c
   218  	memstats.enablegc = true // now that runtime is initialized, GC is okay
   219  }
   220  
   221  //go:linkname setGCPercent runtime/debug.setGCPercent
   222  func setGCPercent(in int32) (out int32) {
   223  	// Run on the system stack since we grab the heap lock.
   224  	systemstack(func() {
   225  		lock(&mheap_.lock)
   226  		out = gcpercent
   227  		if in < 0 {
   228  			in = -1
   229  		}
   230  		gcpercent = in
   231  		heapminimum = defaultHeapMinimum * uint64(gcpercent) / 100
   232  		// Update pacing in response to gcpercent change.
   233  		gcSetTriggerRatio(memstats.triggerRatio)
   234  		unlock(&mheap_.lock)
   235  	})
   236  	// Pacing changed, so the scavenger should be awoken.
   237  	wakeScavenger()
   238  
   239  	// If we just disabled GC, wait for any concurrent GC mark to
   240  	// finish so we always return with no GC running.
   241  	if in < 0 {
   242  		gcWaitOnMark(atomic.Load(&work.cycles))
   243  	}
   244  
   245  	return out
   246  }
   247  
   248  // Garbage collector phase.
   249  // Indicates to write barrier and synchronization task to perform.
   250  var gcphase uint32
   251  
   252  // The compiler knows about this variable.
   253  // If you change it, you must change builtin/runtime.go, too.
   254  // If you change the first four bytes, you must also change the write
   255  // barrier insertion code.
   256  var writeBarrier struct {
   257  	enabled bool    // compiler emits a check of this before calling write barrier
   258  	pad     [3]byte // compiler uses 32-bit load for "enabled" field
   259  	needed  bool    // whether we need a write barrier for current GC phase
   260  	cgo     bool    // whether we need a write barrier for a cgo check
   261  	alignme uint64  // guarantee alignment so that compiler can use a 32 or 64-bit load
   262  }
   263  
   264  // gcBlackenEnabled is 1 if mutator assists and background mark
   265  // workers are allowed to blacken objects. This must only be set when
   266  // gcphase == _GCmark.
   267  var gcBlackenEnabled uint32
   268  
   269  const (
   270  	_GCoff             = iota // GC not running; sweeping in background, write barrier disabled
   271  	_GCmark                   // GC marking roots and workbufs: allocate black, write barrier ENABLED
   272  	_GCmarktermination        // GC mark termination: allocate black, P's help GC, write barrier ENABLED
   273  )
   274  
   275  //go:nosplit
   276  func setGCPhase(x uint32) {
   277  	atomic.Store(&gcphase, x)
   278  	writeBarrier.needed = gcphase == _GCmark || gcphase == _GCmarktermination
   279  	writeBarrier.enabled = writeBarrier.needed || writeBarrier.cgo
   280  }
   281  
   282  // gcMarkWorkerMode represents the mode that a concurrent mark worker
   283  // should operate in.
   284  //
   285  // Concurrent marking happens through four different mechanisms. One
   286  // is mutator assists, which happen in response to allocations and are
   287  // not scheduled. The other three are variations in the per-P mark
   288  // workers and are distinguished by gcMarkWorkerMode.
   289  type gcMarkWorkerMode int
   290  
   291  const (
   292  	// gcMarkWorkerDedicatedMode indicates that the P of a mark
   293  	// worker is dedicated to running that mark worker. The mark
   294  	// worker should run without preemption.
   295  	gcMarkWorkerDedicatedMode gcMarkWorkerMode = iota
   296  
   297  	// gcMarkWorkerFractionalMode indicates that a P is currently
   298  	// running the "fractional" mark worker. The fractional worker
   299  	// is necessary when GOMAXPROCS*gcBackgroundUtilization is not
   300  	// an integer. The fractional worker should run until it is
   301  	// preempted and will be scheduled to pick up the fractional
   302  	// part of GOMAXPROCS*gcBackgroundUtilization.
   303  	gcMarkWorkerFractionalMode
   304  
   305  	// gcMarkWorkerIdleMode indicates that a P is running the mark
   306  	// worker because it has nothing else to do. The idle worker
   307  	// should run until it is preempted and account its time
   308  	// against gcController.idleMarkTime.
   309  	gcMarkWorkerIdleMode
   310  )
   311  
   312  // gcMarkWorkerModeStrings are the strings labels of gcMarkWorkerModes
   313  // to use in execution traces.
   314  var gcMarkWorkerModeStrings = [...]string{
   315  	"GC (dedicated)",
   316  	"GC (fractional)",
   317  	"GC (idle)",
   318  }
   319  
   320  // gcController implements the GC pacing controller that determines
   321  // when to trigger concurrent garbage collection and how much marking
   322  // work to do in mutator assists and background marking.
   323  //
   324  // It uses a feedback control algorithm to adjust the memstats.gc_trigger
   325  // trigger based on the heap growth and GC CPU utilization each cycle.
   326  // This algorithm optimizes for heap growth to match GOGC and for CPU
   327  // utilization between assist and background marking to be 25% of
   328  // GOMAXPROCS. The high-level design of this algorithm is documented
   329  // at https://golang.org/s/go15gcpacing.
   330  //
   331  // All fields of gcController are used only during a single mark
   332  // cycle.
   333  var gcController gcControllerState
   334  
   335  type gcControllerState struct {
   336  	// scanWork is the total scan work performed this cycle. This
   337  	// is updated atomically during the cycle. Updates occur in
   338  	// bounded batches, since it is both written and read
   339  	// throughout the cycle. At the end of the cycle, this is how
   340  	// much of the retained heap is scannable.
   341  	//
   342  	// Currently this is the bytes of heap scanned. For most uses,
   343  	// this is an opaque unit of work, but for estimation the
   344  	// definition is important.
   345  	scanWork int64
   346  
   347  	// bgScanCredit is the scan work credit accumulated by the
   348  	// concurrent background scan. This credit is accumulated by
   349  	// the background scan and stolen by mutator assists. This is
   350  	// updated atomically. Updates occur in bounded batches, since
   351  	// it is both written and read throughout the cycle.
   352  	bgScanCredit int64
   353  
   354  	// assistTime is the nanoseconds spent in mutator assists
   355  	// during this cycle. This is updated atomically. Updates
   356  	// occur in bounded batches, since it is both written and read
   357  	// throughout the cycle.
   358  	assistTime int64
   359  
   360  	// dedicatedMarkTime is the nanoseconds spent in dedicated
   361  	// mark workers during this cycle. This is updated atomically
   362  	// at the end of the concurrent mark phase.
   363  	dedicatedMarkTime int64
   364  
   365  	// fractionalMarkTime is the nanoseconds spent in the
   366  	// fractional mark worker during this cycle. This is updated
   367  	// atomically throughout the cycle and will be up-to-date if
   368  	// the fractional mark worker is not currently running.
   369  	fractionalMarkTime int64
   370  
   371  	// idleMarkTime is the nanoseconds spent in idle marking
   372  	// during this cycle. This is updated atomically throughout
   373  	// the cycle.
   374  	idleMarkTime int64
   375  
   376  	// markStartTime is the absolute start time in nanoseconds
   377  	// that assists and background mark workers started.
   378  	markStartTime int64
   379  
   380  	// dedicatedMarkWorkersNeeded is the number of dedicated mark
   381  	// workers that need to be started. This is computed at the
   382  	// beginning of each cycle and decremented atomically as
   383  	// dedicated mark workers get started.
   384  	dedicatedMarkWorkersNeeded int64
   385  
   386  	// assistWorkPerByte is the ratio of scan work to allocated
   387  	// bytes that should be performed by mutator assists. This is
   388  	// computed at the beginning of each cycle and updated every
   389  	// time heap_scan is updated.
   390  	assistWorkPerByte float64
   391  
   392  	// assistBytesPerWork is 1/assistWorkPerByte.
   393  	assistBytesPerWork float64
   394  
   395  	// fractionalUtilizationGoal is the fraction of wall clock
   396  	// time that should be spent in the fractional mark worker on
   397  	// each P that isn't running a dedicated worker.
   398  	//
   399  	// For example, if the utilization goal is 25% and there are
   400  	// no dedicated workers, this will be 0.25. If the goal is
   401  	// 25%, there is one dedicated worker, and GOMAXPROCS is 5,
   402  	// this will be 0.05 to make up the missing 5%.
   403  	//
   404  	// If this is zero, no fractional workers are needed.
   405  	fractionalUtilizationGoal float64
   406  
   407  	_ cpu.CacheLinePad
   408  }
   409  
   410  // startCycle resets the GC controller's state and computes estimates
   411  // for a new GC cycle. The caller must hold worldsema.
   412  func (c *gcControllerState) startCycle() {
   413  	c.scanWork = 0
   414  	c.bgScanCredit = 0
   415  	c.assistTime = 0
   416  	c.dedicatedMarkTime = 0
   417  	c.fractionalMarkTime = 0
   418  	c.idleMarkTime = 0
   419  
   420  	// Ensure that the heap goal is at least a little larger than
   421  	// the current live heap size. This may not be the case if GC
   422  	// start is delayed or if the allocation that pushed heap_live
   423  	// over gc_trigger is large or if the trigger is really close to
   424  	// GOGC. Assist is proportional to this distance, so enforce a
   425  	// minimum distance, even if it means going over the GOGC goal
   426  	// by a tiny bit.
   427  	if memstats.next_gc < memstats.heap_live+1024*1024 {
   428  		memstats.next_gc = memstats.heap_live + 1024*1024
   429  	}
   430  
   431  	// Compute the background mark utilization goal. In general,
   432  	// this may not come out exactly. We round the number of
   433  	// dedicated workers so that the utilization is closest to
   434  	// 25%. For small GOMAXPROCS, this would introduce too much
   435  	// error, so we add fractional workers in that case.
   436  	totalUtilizationGoal := float64(gomaxprocs) * gcBackgroundUtilization
   437  	c.dedicatedMarkWorkersNeeded = int64(totalUtilizationGoal + 0.5)
   438  	utilError := float64(c.dedicatedMarkWorkersNeeded)/totalUtilizationGoal - 1
   439  	const maxUtilError = 0.3
   440  	if utilError < -maxUtilError || utilError > maxUtilError {
   441  		// Rounding put us more than 30% off our goal. With
   442  		// gcBackgroundUtilization of 25%, this happens for
   443  		// GOMAXPROCS<=3 or GOMAXPROCS=6. Enable fractional
   444  		// workers to compensate.
   445  		if float64(c.dedicatedMarkWorkersNeeded) > totalUtilizationGoal {
   446  			// Too many dedicated workers.
   447  			c.dedicatedMarkWorkersNeeded--
   448  		}
   449  		c.fractionalUtilizationGoal = (totalUtilizationGoal - float64(c.dedicatedMarkWorkersNeeded)) / float64(gomaxprocs)
   450  	} else {
   451  		c.fractionalUtilizationGoal = 0
   452  	}
   453  
   454  	// In STW mode, we just want dedicated workers.
   455  	if debug.gcstoptheworld > 0 {
   456  		c.dedicatedMarkWorkersNeeded = int64(gomaxprocs)
   457  		c.fractionalUtilizationGoal = 0
   458  	}
   459  
   460  	// Clear per-P state
   461  	for _, p := range allp {
   462  		p.gcAssistTime = 0
   463  		p.gcFractionalMarkTime = 0
   464  	}
   465  
   466  	// Compute initial values for controls that are updated
   467  	// throughout the cycle.
   468  	c.revise()
   469  
   470  	if debug.gcpacertrace > 0 {
   471  		print("pacer: assist ratio=", c.assistWorkPerByte,
   472  			" (scan ", memstats.heap_scan>>20, " MB in ",
   473  			work.initialHeapLive>>20, "->",
   474  			memstats.next_gc>>20, " MB)",
   475  			" workers=", c.dedicatedMarkWorkersNeeded,
   476  			"+", c.fractionalUtilizationGoal, "\n")
   477  	}
   478  }
   479  
   480  // revise updates the assist ratio during the GC cycle to account for
   481  // improved estimates. This should be called either under STW or
   482  // whenever memstats.heap_scan, memstats.heap_live, or
   483  // memstats.next_gc is updated (with mheap_.lock held).
   484  //
   485  // It should only be called when gcBlackenEnabled != 0 (because this
   486  // is when assists are enabled and the necessary statistics are
   487  // available).
   488  func (c *gcControllerState) revise() {
   489  	gcpercent := gcpercent
   490  	if gcpercent < 0 {
   491  		// If GC is disabled but we're running a forced GC,
   492  		// act like GOGC is huge for the below calculations.
   493  		gcpercent = 100000
   494  	}
   495  	live := atomic.Load64(&memstats.heap_live)
   496  
   497  	// Assume we're under the soft goal. Pace GC to complete at
   498  	// next_gc assuming the heap is in steady-state.
   499  	heapGoal := int64(memstats.next_gc)
   500  
   501  	// Compute the expected scan work remaining.
   502  	//
   503  	// This is estimated based on the expected
   504  	// steady-state scannable heap. For example, with
   505  	// GOGC=100, only half of the scannable heap is
   506  	// expected to be live, so that's what we target.
   507  	//
   508  	// (This is a float calculation to avoid overflowing on
   509  	// 100*heap_scan.)
   510  	scanWorkExpected := int64(float64(memstats.heap_scan) * 100 / float64(100+gcpercent))
   511  
   512  	if live > memstats.next_gc || c.scanWork > scanWorkExpected {
   513  		// We're past the soft goal, or we've already done more scan
   514  		// work than we expected. Pace GC so that in the worst case it
   515  		// will complete by the hard goal.
   516  		const maxOvershoot = 1.1
   517  		heapGoal = int64(float64(memstats.next_gc) * maxOvershoot)
   518  
   519  		// Compute the upper bound on the scan work remaining.
   520  		scanWorkExpected = int64(memstats.heap_scan)
   521  	}
   522  
   523  	// Compute the remaining scan work estimate.
   524  	//
   525  	// Note that we currently count allocations during GC as both
   526  	// scannable heap (heap_scan) and scan work completed
   527  	// (scanWork), so allocation will change this difference
   528  	// slowly in the soft regime and not at all in the hard
   529  	// regime.
   530  	scanWorkRemaining := scanWorkExpected - c.scanWork
   531  	if scanWorkRemaining < 1000 {
   532  		// We set a somewhat arbitrary lower bound on
   533  		// remaining scan work since if we aim a little high,
   534  		// we can miss by a little.
   535  		//
   536  		// We *do* need to enforce that this is at least 1,
   537  		// since marking is racy and double-scanning objects
   538  		// may legitimately make the remaining scan work
   539  		// negative, even in the hard goal regime.
   540  		scanWorkRemaining = 1000
   541  	}
   542  
   543  	// Compute the heap distance remaining.
   544  	heapRemaining := heapGoal - int64(live)
   545  	if heapRemaining <= 0 {
   546  		// This shouldn't happen, but if it does, avoid
   547  		// dividing by zero or setting the assist negative.
   548  		heapRemaining = 1
   549  	}
   550  
   551  	// Compute the mutator assist ratio so by the time the mutator
   552  	// allocates the remaining heap bytes up to next_gc, it will
   553  	// have done (or stolen) the remaining amount of scan work.
   554  	c.assistWorkPerByte = float64(scanWorkRemaining) / float64(heapRemaining)
   555  	c.assistBytesPerWork = float64(heapRemaining) / float64(scanWorkRemaining)
   556  }
   557  
   558  // endCycle computes the trigger ratio for the next cycle.
   559  func (c *gcControllerState) endCycle() float64 {
   560  	if work.userForced {
   561  		// Forced GC means this cycle didn't start at the
   562  		// trigger, so where it finished isn't good
   563  		// information about how to adjust the trigger.
   564  		// Just leave it where it is.
   565  		return memstats.triggerRatio
   566  	}
   567  
   568  	// Proportional response gain for the trigger controller. Must
   569  	// be in [0, 1]. Lower values smooth out transient effects but
   570  	// take longer to respond to phase changes. Higher values
   571  	// react to phase changes quickly, but are more affected by
   572  	// transient changes. Values near 1 may be unstable.
   573  	const triggerGain = 0.5
   574  
   575  	// Compute next cycle trigger ratio. First, this computes the
   576  	// "error" for this cycle; that is, how far off the trigger
   577  	// was from what it should have been, accounting for both heap
   578  	// growth and GC CPU utilization. We compute the actual heap
   579  	// growth during this cycle and scale that by how far off from
   580  	// the goal CPU utilization we were (to estimate the heap
   581  	// growth if we had the desired CPU utilization). The
   582  	// difference between this estimate and the GOGC-based goal
   583  	// heap growth is the error.
   584  	goalGrowthRatio := gcEffectiveGrowthRatio()
   585  	actualGrowthRatio := float64(memstats.heap_live)/float64(memstats.heap_marked) - 1
   586  	assistDuration := nanotime() - c.markStartTime
   587  
   588  	// Assume background mark hit its utilization goal.
   589  	utilization := gcBackgroundUtilization
   590  	// Add assist utilization; avoid divide by zero.
   591  	if assistDuration > 0 {
   592  		utilization += float64(c.assistTime) / float64(assistDuration*int64(gomaxprocs))
   593  	}
   594  
   595  	triggerError := goalGrowthRatio - memstats.triggerRatio - utilization/gcGoalUtilization*(actualGrowthRatio-memstats.triggerRatio)
   596  
   597  	// Finally, we adjust the trigger for next time by this error,
   598  	// damped by the proportional gain.
   599  	triggerRatio := memstats.triggerRatio + triggerGain*triggerError
   600  
   601  	if debug.gcpacertrace > 0 {
   602  		// Print controller state in terms of the design
   603  		// document.
   604  		H_m_prev := memstats.heap_marked
   605  		h_t := memstats.triggerRatio
   606  		H_T := memstats.gc_trigger
   607  		h_a := actualGrowthRatio
   608  		H_a := memstats.heap_live
   609  		h_g := goalGrowthRatio
   610  		H_g := int64(float64(H_m_prev) * (1 + h_g))
   611  		u_a := utilization
   612  		u_g := gcGoalUtilization
   613  		W_a := c.scanWork
   614  		print("pacer: H_m_prev=", H_m_prev,
   615  			" h_t=", h_t, " H_T=", H_T,
   616  			" h_a=", h_a, " H_a=", H_a,
   617  			" h_g=", h_g, " H_g=", H_g,
   618  			" u_a=", u_a, " u_g=", u_g,
   619  			" W_a=", W_a,
   620  			" goalΔ=", goalGrowthRatio-h_t,
   621  			" actualΔ=", h_a-h_t,
   622  			" u_a/u_g=", u_a/u_g,
   623  			"\n")
   624  	}
   625  
   626  	return triggerRatio
   627  }
   628  
   629  // enlistWorker encourages another dedicated mark worker to start on
   630  // another P if there are spare worker slots. It is used by putfull
   631  // when more work is made available.
   632  //
   633  //go:nowritebarrier
   634  func (c *gcControllerState) enlistWorker() {
   635  	// If there are idle Ps, wake one so it will run an idle worker.
   636  	// NOTE: This is suspected of causing deadlocks. See golang.org/issue/19112.
   637  	//
   638  	//	if atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 {
   639  	//		wakep()
   640  	//		return
   641  	//	}
   642  
   643  	// There are no idle Ps. If we need more dedicated workers,
   644  	// try to preempt a running P so it will switch to a worker.
   645  	if c.dedicatedMarkWorkersNeeded <= 0 {
   646  		return
   647  	}
   648  	// Pick a random other P to preempt.
   649  	if gomaxprocs <= 1 {
   650  		return
   651  	}
   652  	gp := getg()
   653  	if gp == nil || gp.m == nil || gp.m.p == 0 {
   654  		return
   655  	}
   656  	myID := gp.m.p.ptr().id
   657  	for tries := 0; tries < 5; tries++ {
   658  		id := int32(fastrandn(uint32(gomaxprocs - 1)))
   659  		if id >= myID {
   660  			id++
   661  		}
   662  		p := allp[id]
   663  		if p.status != _Prunning {
   664  			continue
   665  		}
   666  		if preemptone(p) {
   667  			return
   668  		}
   669  	}
   670  }
   671  
   672  // findRunnableGCWorker returns the background mark worker for _p_ if it
   673  // should be run. This must only be called when gcBlackenEnabled != 0.
   674  func (c *gcControllerState) findRunnableGCWorker(_p_ *p) *g {
   675  	if gcBlackenEnabled == 0 {
   676  		throw("gcControllerState.findRunnable: blackening not enabled")
   677  	}
   678  	if _p_.gcBgMarkWorker == 0 {
   679  		// The mark worker associated with this P is blocked
   680  		// performing a mark transition. We can't run it
   681  		// because it may be on some other run or wait queue.
   682  		return nil
   683  	}
   684  
   685  	if !gcMarkWorkAvailable(_p_) {
   686  		// No work to be done right now. This can happen at
   687  		// the end of the mark phase when there are still
   688  		// assists tapering off. Don't bother running a worker
   689  		// now because it'll just return immediately.
   690  		return nil
   691  	}
   692  
   693  	decIfPositive := func(ptr *int64) bool {
   694  		if *ptr > 0 {
   695  			if atomic.Xaddint64(ptr, -1) >= 0 {
   696  				return true
   697  			}
   698  			// We lost a race
   699  			atomic.Xaddint64(ptr, +1)
   700  		}
   701  		return false
   702  	}
   703  
   704  	if decIfPositive(&c.dedicatedMarkWorkersNeeded) {
   705  		// This P is now dedicated to marking until the end of
   706  		// the concurrent mark phase.
   707  		_p_.gcMarkWorkerMode = gcMarkWorkerDedicatedMode
   708  	} else if c.fractionalUtilizationGoal == 0 {
   709  		// No need for fractional workers.
   710  		return nil
   711  	} else {
   712  		// Is this P behind on the fractional utilization
   713  		// goal?
   714  		//
   715  		// This should be kept in sync with pollFractionalWorkerExit.
   716  		delta := nanotime() - gcController.markStartTime
   717  		if delta > 0 && float64(_p_.gcFractionalMarkTime)/float64(delta) > c.fractionalUtilizationGoal {
   718  			// Nope. No need to run a fractional worker.
   719  			return nil
   720  		}
   721  		// Run a fractional worker.
   722  		_p_.gcMarkWorkerMode = gcMarkWorkerFractionalMode
   723  	}
   724  
   725  	// Run the background mark worker
   726  	gp := _p_.gcBgMarkWorker.ptr()
   727  	casgstatus(gp, _Gwaiting, _Grunnable)
   728  	if trace.enabled {
   729  		traceGoUnpark(gp, 0)
   730  	}
   731  	return gp
   732  }
   733  
   734  // pollFractionalWorkerExit reports whether a fractional mark worker
   735  // should self-preempt. It assumes it is called from the fractional
   736  // worker.
   737  func pollFractionalWorkerExit() bool {
   738  	// This should be kept in sync with the fractional worker
   739  	// scheduler logic in findRunnableGCWorker.
   740  	now := nanotime()
   741  	delta := now - gcController.markStartTime
   742  	if delta <= 0 {
   743  		return true
   744  	}
   745  	p := getg().m.p.ptr()
   746  	selfTime := p.gcFractionalMarkTime + (now - p.gcMarkWorkerStartTime)
   747  	// Add some slack to the utilization goal so that the
   748  	// fractional worker isn't behind again the instant it exits.
   749  	return float64(selfTime)/float64(delta) > 1.2*gcController.fractionalUtilizationGoal
   750  }
   751  
   752  // gcSetTriggerRatio sets the trigger ratio and updates everything
   753  // derived from it: the absolute trigger, the heap goal, mark pacing,
   754  // and sweep pacing.
   755  //
   756  // This can be called any time. If GC is the in the middle of a
   757  // concurrent phase, it will adjust the pacing of that phase.
   758  //
   759  // This depends on gcpercent, memstats.heap_marked, and
   760  // memstats.heap_live. These must be up to date.
   761  //
   762  // mheap_.lock must be held or the world must be stopped.
   763  func gcSetTriggerRatio(triggerRatio float64) {
   764  	// Compute the next GC goal, which is when the allocated heap
   765  	// has grown by GOGC/100 over the heap marked by the last
   766  	// cycle.
   767  	goal := ^uint64(0)
   768  	if gcpercent >= 0 {
   769  		goal = memstats.heap_marked + memstats.heap_marked*uint64(gcpercent)/100
   770  	}
   771  
   772  	// Set the trigger ratio, capped to reasonable bounds.
   773  	if gcpercent >= 0 {
   774  		scalingFactor := float64(gcpercent) / 100
   775  		// Ensure there's always a little margin so that the
   776  		// mutator assist ratio isn't infinity.
   777  		maxTriggerRatio := 0.95 * scalingFactor
   778  		if triggerRatio > maxTriggerRatio {
   779  			triggerRatio = maxTriggerRatio
   780  		}
   781  
   782  		// If we let triggerRatio go too low, then if the application
   783  		// is allocating very rapidly we might end up in a situation
   784  		// where we're allocating black during a nearly always-on GC.
   785  		// The result of this is a growing heap and ultimately an
   786  		// increase in RSS. By capping us at a point >0, we're essentially
   787  		// saying that we're OK using more CPU during the GC to prevent
   788  		// this growth in RSS.
   789  		//
   790  		// The current constant was chosen empirically: given a sufficiently
   791  		// fast/scalable allocator with 48 Ps that could drive the trigger ratio
   792  		// to <0.05, this constant causes applications to retain the same peak
   793  		// RSS compared to not having this allocator.
   794  		minTriggerRatio := 0.6 * scalingFactor
   795  		if triggerRatio < minTriggerRatio {
   796  			triggerRatio = minTriggerRatio
   797  		}
   798  	} else if triggerRatio < 0 {
   799  		// gcpercent < 0, so just make sure we're not getting a negative
   800  		// triggerRatio. This case isn't expected to happen in practice,
   801  		// and doesn't really matter because if gcpercent < 0 then we won't
   802  		// ever consume triggerRatio further on in this function, but let's
   803  		// just be defensive here; the triggerRatio being negative is almost
   804  		// certainly undesirable.
   805  		triggerRatio = 0
   806  	}
   807  	memstats.triggerRatio = triggerRatio
   808  
   809  	// Compute the absolute GC trigger from the trigger ratio.
   810  	//
   811  	// We trigger the next GC cycle when the allocated heap has
   812  	// grown by the trigger ratio over the marked heap size.
   813  	trigger := ^uint64(0)
   814  	if gcpercent >= 0 {
   815  		trigger = uint64(float64(memstats.heap_marked) * (1 + triggerRatio))
   816  		// Don't trigger below the minimum heap size.
   817  		minTrigger := heapminimum
   818  		if !isSweepDone() {
   819  			// Concurrent sweep happens in the heap growth
   820  			// from heap_live to gc_trigger, so ensure
   821  			// that concurrent sweep has some heap growth
   822  			// in which to perform sweeping before we
   823  			// start the next GC cycle.
   824  			sweepMin := atomic.Load64(&memstats.heap_live) + sweepMinHeapDistance
   825  			if sweepMin > minTrigger {
   826  				minTrigger = sweepMin
   827  			}
   828  		}
   829  		if trigger < minTrigger {
   830  			trigger = minTrigger
   831  		}
   832  		if int64(trigger) < 0 {
   833  			print("runtime: next_gc=", memstats.next_gc, " heap_marked=", memstats.heap_marked, " heap_live=", memstats.heap_live, " initialHeapLive=", work.initialHeapLive, "triggerRatio=", triggerRatio, " minTrigger=", minTrigger, "\n")
   834  			throw("gc_trigger underflow")
   835  		}
   836  		if trigger > goal {
   837  			// The trigger ratio is always less than GOGC/100, but
   838  			// other bounds on the trigger may have raised it.
   839  			// Push up the goal, too.
   840  			goal = trigger
   841  		}
   842  	}
   843  
   844  	// Commit to the trigger and goal.
   845  	memstats.gc_trigger = trigger
   846  	memstats.next_gc = goal
   847  	if trace.enabled {
   848  		traceNextGC()
   849  	}
   850  
   851  	// Update mark pacing.
   852  	if gcphase != _GCoff {
   853  		gcController.revise()
   854  	}
   855  
   856  	// Update sweep pacing.
   857  	if isSweepDone() {
   858  		mheap_.sweepPagesPerByte = 0
   859  	} else {
   860  		// Concurrent sweep needs to sweep all of the in-use
   861  		// pages by the time the allocated heap reaches the GC
   862  		// trigger. Compute the ratio of in-use pages to sweep
   863  		// per byte allocated, accounting for the fact that
   864  		// some might already be swept.
   865  		heapLiveBasis := atomic.Load64(&memstats.heap_live)
   866  		heapDistance := int64(trigger) - int64(heapLiveBasis)
   867  		// Add a little margin so rounding errors and
   868  		// concurrent sweep are less likely to leave pages
   869  		// unswept when GC starts.
   870  		heapDistance -= 1024 * 1024
   871  		if heapDistance < _PageSize {
   872  			// Avoid setting the sweep ratio extremely high
   873  			heapDistance = _PageSize
   874  		}
   875  		pagesSwept := atomic.Load64(&mheap_.pagesSwept)
   876  		pagesInUse := atomic.Load64(&mheap_.pagesInUse)
   877  		sweepDistancePages := int64(pagesInUse) - int64(pagesSwept)
   878  		if sweepDistancePages <= 0 {
   879  			mheap_.sweepPagesPerByte = 0
   880  		} else {
   881  			mheap_.sweepPagesPerByte = float64(sweepDistancePages) / float64(heapDistance)
   882  			mheap_.sweepHeapLiveBasis = heapLiveBasis
   883  			// Write pagesSweptBasis last, since this
   884  			// signals concurrent sweeps to recompute
   885  			// their debt.
   886  			atomic.Store64(&mheap_.pagesSweptBasis, pagesSwept)
   887  		}
   888  	}
   889  
   890  	gcPaceScavenger()
   891  }
   892  
   893  // gcEffectiveGrowthRatio returns the current effective heap growth
   894  // ratio (GOGC/100) based on heap_marked from the previous GC and
   895  // next_gc for the current GC.
   896  //
   897  // This may differ from gcpercent/100 because of various upper and
   898  // lower bounds on gcpercent. For example, if the heap is smaller than
   899  // heapminimum, this can be higher than gcpercent/100.
   900  //
   901  // mheap_.lock must be held or the world must be stopped.
   902  func gcEffectiveGrowthRatio() float64 {
   903  	egogc := float64(memstats.next_gc-memstats.heap_marked) / float64(memstats.heap_marked)
   904  	if egogc < 0 {
   905  		// Shouldn't happen, but just in case.
   906  		egogc = 0
   907  	}
   908  	return egogc
   909  }
   910  
   911  // gcGoalUtilization is the goal CPU utilization for
   912  // marking as a fraction of GOMAXPROCS.
   913  const gcGoalUtilization = 0.30
   914  
   915  // gcBackgroundUtilization is the fixed CPU utilization for background
   916  // marking. It must be <= gcGoalUtilization. The difference between
   917  // gcGoalUtilization and gcBackgroundUtilization will be made up by
   918  // mark assists. The scheduler will aim to use within 50% of this
   919  // goal.
   920  //
   921  // Setting this to < gcGoalUtilization avoids saturating the trigger
   922  // feedback controller when there are no assists, which allows it to
   923  // better control CPU and heap growth. However, the larger the gap,
   924  // the more mutator assists are expected to happen, which impact
   925  // mutator latency.
   926  const gcBackgroundUtilization = 0.25
   927  
   928  // gcCreditSlack is the amount of scan work credit that can
   929  // accumulate locally before updating gcController.scanWork and,
   930  // optionally, gcController.bgScanCredit. Lower values give a more
   931  // accurate assist ratio and make it more likely that assists will
   932  // successfully steal background credit. Higher values reduce memory
   933  // contention.
   934  const gcCreditSlack = 2000
   935  
   936  // gcAssistTimeSlack is the nanoseconds of mutator assist time that
   937  // can accumulate on a P before updating gcController.assistTime.
   938  const gcAssistTimeSlack = 5000
   939  
   940  // gcOverAssistWork determines how many extra units of scan work a GC
   941  // assist does when an assist happens. This amortizes the cost of an
   942  // assist by pre-paying for this many bytes of future allocations.
   943  const gcOverAssistWork = 64 << 10
   944  
   945  var work struct {
   946  	full  lfstack          // lock-free list of full blocks workbuf
   947  	empty lfstack          // lock-free list of empty blocks workbuf
   948  	pad0  cpu.CacheLinePad // prevents false-sharing between full/empty and nproc/nwait
   949  
   950  	wbufSpans struct {
   951  		lock mutex
   952  		// free is a list of spans dedicated to workbufs, but
   953  		// that don't currently contain any workbufs.
   954  		free mSpanList
   955  		// busy is a list of all spans containing workbufs on
   956  		// one of the workbuf lists.
   957  		busy mSpanList
   958  	}
   959  
   960  	// Restore 64-bit alignment on 32-bit.
   961  	_ uint32
   962  
   963  	// bytesMarked is the number of bytes marked this cycle. This
   964  	// includes bytes blackened in scanned objects, noscan objects
   965  	// that go straight to black, and permagrey objects scanned by
   966  	// markroot during the concurrent scan phase. This is updated
   967  	// atomically during the cycle. Updates may be batched
   968  	// arbitrarily, since the value is only read at the end of the
   969  	// cycle.
   970  	//
   971  	// Because of benign races during marking, this number may not
   972  	// be the exact number of marked bytes, but it should be very
   973  	// close.
   974  	//
   975  	// Put this field here because it needs 64-bit atomic access
   976  	// (and thus 8-byte alignment even on 32-bit architectures).
   977  	bytesMarked uint64
   978  
   979  	markrootNext uint32 // next markroot job
   980  	markrootJobs uint32 // number of markroot jobs
   981  
   982  	nproc  uint32
   983  	tstart int64
   984  	nwait  uint32
   985  	ndone  uint32
   986  
   987  	// Number of roots of various root types. Set by gcMarkRootPrepare.
   988  	nFlushCacheRoots                               int
   989  	nDataRoots, nBSSRoots, nSpanRoots, nStackRoots int
   990  
   991  	// Each type of GC state transition is protected by a lock.
   992  	// Since multiple threads can simultaneously detect the state
   993  	// transition condition, any thread that detects a transition
   994  	// condition must acquire the appropriate transition lock,
   995  	// re-check the transition condition and return if it no
   996  	// longer holds or perform the transition if it does.
   997  	// Likewise, any transition must invalidate the transition
   998  	// condition before releasing the lock. This ensures that each
   999  	// transition is performed by exactly one thread and threads
  1000  	// that need the transition to happen block until it has
  1001  	// happened.
  1002  	//
  1003  	// startSema protects the transition from "off" to mark or
  1004  	// mark termination.
  1005  	startSema uint32
  1006  	// markDoneSema protects transitions from mark to mark termination.
  1007  	markDoneSema uint32
  1008  
  1009  	bgMarkReady note   // signal background mark worker has started
  1010  	bgMarkDone  uint32 // cas to 1 when at a background mark completion point
  1011  	// Background mark completion signaling
  1012  
  1013  	// mode is the concurrency mode of the current GC cycle.
  1014  	mode gcMode
  1015  
  1016  	// userForced indicates the current GC cycle was forced by an
  1017  	// explicit user call.
  1018  	userForced bool
  1019  
  1020  	// totaltime is the CPU nanoseconds spent in GC since the
  1021  	// program started if debug.gctrace > 0.
  1022  	totaltime int64
  1023  
  1024  	// initialHeapLive is the value of memstats.heap_live at the
  1025  	// beginning of this GC cycle.
  1026  	initialHeapLive uint64
  1027  
  1028  	// assistQueue is a queue of assists that are blocked because
  1029  	// there was neither enough credit to steal or enough work to
  1030  	// do.
  1031  	assistQueue struct {
  1032  		lock mutex
  1033  		q    gQueue
  1034  	}
  1035  
  1036  	// sweepWaiters is a list of blocked goroutines to wake when
  1037  	// we transition from mark termination to sweep.
  1038  	sweepWaiters struct {
  1039  		lock mutex
  1040  		list gList
  1041  	}
  1042  
  1043  	// cycles is the number of completed GC cycles, where a GC
  1044  	// cycle is sweep termination, mark, mark termination, and
  1045  	// sweep. This differs from memstats.numgc, which is
  1046  	// incremented at mark termination.
  1047  	cycles uint32
  1048  
  1049  	// Timing/utilization stats for this cycle.
  1050  	stwprocs, maxprocs                 int32
  1051  	tSweepTerm, tMark, tMarkTerm, tEnd int64 // nanotime() of phase start
  1052  
  1053  	pauseNS    int64 // total STW time this cycle
  1054  	pauseStart int64 // nanotime() of last STW
  1055  
  1056  	// debug.gctrace heap sizes for this cycle.
  1057  	heap0, heap1, heap2, heapGoal uint64
  1058  }
  1059  
  1060  // GC runs a garbage collection and blocks the caller until the
  1061  // garbage collection is complete. It may also block the entire
  1062  // program.
  1063  func GC() {
  1064  	// We consider a cycle to be: sweep termination, mark, mark
  1065  	// termination, and sweep. This function shouldn't return
  1066  	// until a full cycle has been completed, from beginning to
  1067  	// end. Hence, we always want to finish up the current cycle
  1068  	// and start a new one. That means:
  1069  	//
  1070  	// 1. In sweep termination, mark, or mark termination of cycle
  1071  	// N, wait until mark termination N completes and transitions
  1072  	// to sweep N.
  1073  	//
  1074  	// 2. In sweep N, help with sweep N.
  1075  	//
  1076  	// At this point we can begin a full cycle N+1.
  1077  	//
  1078  	// 3. Trigger cycle N+1 by starting sweep termination N+1.
  1079  	//
  1080  	// 4. Wait for mark termination N+1 to complete.
  1081  	//
  1082  	// 5. Help with sweep N+1 until it's done.
  1083  	//
  1084  	// This all has to be written to deal with the fact that the
  1085  	// GC may move ahead on its own. For example, when we block
  1086  	// until mark termination N, we may wake up in cycle N+2.
  1087  
  1088  	// Wait until the current sweep termination, mark, and mark
  1089  	// termination complete.
  1090  	n := atomic.Load(&work.cycles)
  1091  	gcWaitOnMark(n)
  1092  
  1093  	// We're now in sweep N or later. Trigger GC cycle N+1, which
  1094  	// will first finish sweep N if necessary and then enter sweep
  1095  	// termination N+1.
  1096  	gcStart(gcTrigger{kind: gcTriggerCycle, n: n + 1})
  1097  
  1098  	// Wait for mark termination N+1 to complete.
  1099  	gcWaitOnMark(n + 1)
  1100  
  1101  	// Finish sweep N+1 before returning. We do this both to
  1102  	// complete the cycle and because runtime.GC() is often used
  1103  	// as part of tests and benchmarks to get the system into a
  1104  	// relatively stable and isolated state.
  1105  	for atomic.Load(&work.cycles) == n+1 && sweepone() != ^uintptr(0) {
  1106  		sweep.nbgsweep++
  1107  		Gosched()
  1108  	}
  1109  
  1110  	// Callers may assume that the heap profile reflects the
  1111  	// just-completed cycle when this returns (historically this
  1112  	// happened because this was a STW GC), but right now the
  1113  	// profile still reflects mark termination N, not N+1.
  1114  	//
  1115  	// As soon as all of the sweep frees from cycle N+1 are done,
  1116  	// we can go ahead and publish the heap profile.
  1117  	//
  1118  	// First, wait for sweeping to finish. (We know there are no
  1119  	// more spans on the sweep queue, but we may be concurrently
  1120  	// sweeping spans, so we have to wait.)
  1121  	for atomic.Load(&work.cycles) == n+1 && atomic.Load(&mheap_.sweepers) != 0 {
  1122  		Gosched()
  1123  	}
  1124  
  1125  	// Now we're really done with sweeping, so we can publish the
  1126  	// stable heap profile. Only do this if we haven't already hit
  1127  	// another mark termination.
  1128  	mp := acquirem()
  1129  	cycle := atomic.Load(&work.cycles)
  1130  	if cycle == n+1 || (gcphase == _GCmark && cycle == n+2) {
  1131  		mProf_PostSweep()
  1132  	}
  1133  	releasem(mp)
  1134  }
  1135  
  1136  // gcWaitOnMark blocks until GC finishes the Nth mark phase. If GC has
  1137  // already completed this mark phase, it returns immediately.
  1138  func gcWaitOnMark(n uint32) {
  1139  	for {
  1140  		// Disable phase transitions.
  1141  		lock(&work.sweepWaiters.lock)
  1142  		nMarks := atomic.Load(&work.cycles)
  1143  		if gcphase != _GCmark {
  1144  			// We've already completed this cycle's mark.
  1145  			nMarks++
  1146  		}
  1147  		if nMarks > n {
  1148  			// We're done.
  1149  			unlock(&work.sweepWaiters.lock)
  1150  			return
  1151  		}
  1152  
  1153  		// Wait until sweep termination, mark, and mark
  1154  		// termination of cycle N complete.
  1155  		work.sweepWaiters.list.push(getg())
  1156  		goparkunlock(&work.sweepWaiters.lock, waitReasonWaitForGCCycle, traceEvGoBlock, 1)
  1157  	}
  1158  }
  1159  
  1160  // gcMode indicates how concurrent a GC cycle should be.
  1161  type gcMode int
  1162  
  1163  const (
  1164  	gcBackgroundMode gcMode = iota // concurrent GC and sweep
  1165  	gcForceMode                    // stop-the-world GC now, concurrent sweep
  1166  	gcForceBlockMode               // stop-the-world GC now and STW sweep (forced by user)
  1167  )
  1168  
  1169  // A gcTrigger is a predicate for starting a GC cycle. Specifically,
  1170  // it is an exit condition for the _GCoff phase.
  1171  type gcTrigger struct {
  1172  	kind gcTriggerKind
  1173  	now  int64  // gcTriggerTime: current time
  1174  	n    uint32 // gcTriggerCycle: cycle number to start
  1175  }
  1176  
  1177  type gcTriggerKind int
  1178  
  1179  const (
  1180  	// gcTriggerHeap indicates that a cycle should be started when
  1181  	// the heap size reaches the trigger heap size computed by the
  1182  	// controller.
  1183  	gcTriggerHeap gcTriggerKind = iota
  1184  
  1185  	// gcTriggerTime indicates that a cycle should be started when
  1186  	// it's been more than forcegcperiod nanoseconds since the
  1187  	// previous GC cycle.
  1188  	gcTriggerTime
  1189  
  1190  	// gcTriggerCycle indicates that a cycle should be started if
  1191  	// we have not yet started cycle number gcTrigger.n (relative
  1192  	// to work.cycles).
  1193  	gcTriggerCycle
  1194  )
  1195  
  1196  // test reports whether the trigger condition is satisfied, meaning
  1197  // that the exit condition for the _GCoff phase has been met. The exit
  1198  // condition should be tested when allocating.
  1199  func (t gcTrigger) test() bool {
  1200  	if !memstats.enablegc || panicking != 0 || gcphase != _GCoff {
  1201  		return false
  1202  	}
  1203  	switch t.kind {
  1204  	case gcTriggerHeap:
  1205  		// Non-atomic access to heap_live for performance. If
  1206  		// we are going to trigger on this, this thread just
  1207  		// atomically wrote heap_live anyway and we'll see our
  1208  		// own write.
  1209  		return memstats.heap_live >= memstats.gc_trigger
  1210  	case gcTriggerTime:
  1211  		if gcpercent < 0 {
  1212  			return false
  1213  		}
  1214  		lastgc := int64(atomic.Load64(&memstats.last_gc_nanotime))
  1215  		return lastgc != 0 && t.now-lastgc > forcegcperiod
  1216  	case gcTriggerCycle:
  1217  		// t.n > work.cycles, but accounting for wraparound.
  1218  		return int32(t.n-work.cycles) > 0
  1219  	}
  1220  	return true
  1221  }
  1222  
  1223  // gcStart starts the GC. It transitions from _GCoff to _GCmark (if
  1224  // debug.gcstoptheworld == 0) or performs all of GC (if
  1225  // debug.gcstoptheworld != 0).
  1226  //
  1227  // This may return without performing this transition in some cases,
  1228  // such as when called on a system stack or with locks held.
  1229  func gcStart(trigger gcTrigger) {
  1230  	// Since this is called from malloc and malloc is called in
  1231  	// the guts of a number of libraries that might be holding
  1232  	// locks, don't attempt to start GC in non-preemptible or
  1233  	// potentially unstable situations.
  1234  	mp := acquirem()
  1235  	if gp := getg(); gp == mp.g0 || mp.locks > 1 || mp.preemptoff != "" {
  1236  		releasem(mp)
  1237  		return
  1238  	}
  1239  	releasem(mp)
  1240  	mp = nil
  1241  
  1242  	// Pick up the remaining unswept/not being swept spans concurrently
  1243  	//
  1244  	// This shouldn't happen if we're being invoked in background
  1245  	// mode since proportional sweep should have just finished
  1246  	// sweeping everything, but rounding errors, etc, may leave a
  1247  	// few spans unswept. In forced mode, this is necessary since
  1248  	// GC can be forced at any point in the sweeping cycle.
  1249  	//
  1250  	// We check the transition condition continuously here in case
  1251  	// this G gets delayed in to the next GC cycle.
  1252  	for trigger.test() && sweepone() != ^uintptr(0) {
  1253  		sweep.nbgsweep++
  1254  	}
  1255  
  1256  	// Perform GC initialization and the sweep termination
  1257  	// transition.
  1258  	semacquire(&work.startSema)
  1259  	// Re-check transition condition under transition lock.
  1260  	if !trigger.test() {
  1261  		semrelease(&work.startSema)
  1262  		return
  1263  	}
  1264  
  1265  	// For stats, check if this GC was forced by the user.
  1266  	work.userForced = trigger.kind == gcTriggerCycle
  1267  
  1268  	// In gcstoptheworld debug mode, upgrade the mode accordingly.
  1269  	// We do this after re-checking the transition condition so
  1270  	// that multiple goroutines that detect the heap trigger don't
  1271  	// start multiple STW GCs.
  1272  	mode := gcBackgroundMode
  1273  	if debug.gcstoptheworld == 1 {
  1274  		mode = gcForceMode
  1275  	} else if debug.gcstoptheworld == 2 {
  1276  		mode = gcForceBlockMode
  1277  	}
  1278  
  1279  	// Ok, we're doing it! Stop everybody else
  1280  	semacquire(&worldsema)
  1281  
  1282  	if trace.enabled {
  1283  		traceGCStart()
  1284  	}
  1285  
  1286  	// Check that all Ps have finished deferred mcache flushes.
  1287  	for _, p := range allp {
  1288  		if fg := atomic.Load(&p.mcache.flushGen); fg != mheap_.sweepgen {
  1289  			println("runtime: p", p.id, "flushGen", fg, "!= sweepgen", mheap_.sweepgen)
  1290  			throw("p mcache not flushed")
  1291  		}
  1292  	}
  1293  
  1294  	gcBgMarkStartWorkers()
  1295  
  1296  	systemstack(gcResetMarkState)
  1297  
  1298  	work.stwprocs, work.maxprocs = gomaxprocs, gomaxprocs
  1299  	if work.stwprocs > ncpu {
  1300  		// This is used to compute CPU time of the STW phases,
  1301  		// so it can't be more than ncpu, even if GOMAXPROCS is.
  1302  		work.stwprocs = ncpu
  1303  	}
  1304  	work.heap0 = atomic.Load64(&memstats.heap_live)
  1305  	work.pauseNS = 0
  1306  	work.mode = mode
  1307  
  1308  	now := nanotime()
  1309  	work.tSweepTerm = now
  1310  	work.pauseStart = now
  1311  	if trace.enabled {
  1312  		traceGCSTWStart(1)
  1313  	}
  1314  	systemstack(stopTheWorldWithSema)
  1315  	// Finish sweep before we start concurrent scan.
  1316  	systemstack(func() {
  1317  		finishsweep_m()
  1318  	})
  1319  	// clearpools before we start the GC. If we wait they memory will not be
  1320  	// reclaimed until the next GC cycle.
  1321  	clearpools()
  1322  
  1323  	work.cycles++
  1324  
  1325  	gcController.startCycle()
  1326  	work.heapGoal = memstats.next_gc
  1327  
  1328  	// In STW mode, disable scheduling of user Gs. This may also
  1329  	// disable scheduling of this goroutine, so it may block as
  1330  	// soon as we start the world again.
  1331  	if mode != gcBackgroundMode {
  1332  		schedEnableUser(false)
  1333  	}
  1334  
  1335  	// Enter concurrent mark phase and enable
  1336  	// write barriers.
  1337  	//
  1338  	// Because the world is stopped, all Ps will
  1339  	// observe that write barriers are enabled by
  1340  	// the time we start the world and begin
  1341  	// scanning.
  1342  	//
  1343  	// Write barriers must be enabled before assists are
  1344  	// enabled because they must be enabled before
  1345  	// any non-leaf heap objects are marked. Since
  1346  	// allocations are blocked until assists can
  1347  	// happen, we want enable assists as early as
  1348  	// possible.
  1349  	setGCPhase(_GCmark)
  1350  
  1351  	gcBgMarkPrepare() // Must happen before assist enable.
  1352  	gcMarkRootPrepare()
  1353  
  1354  	// Mark all active tinyalloc blocks. Since we're
  1355  	// allocating from these, they need to be black like
  1356  	// other allocations. The alternative is to blacken
  1357  	// the tiny block on every allocation from it, which
  1358  	// would slow down the tiny allocator.
  1359  	gcMarkTinyAllocs()
  1360  
  1361  	// At this point all Ps have enabled the write
  1362  	// barrier, thus maintaining the no white to
  1363  	// black invariant. Enable mutator assists to
  1364  	// put back-pressure on fast allocating
  1365  	// mutators.
  1366  	atomic.Store(&gcBlackenEnabled, 1)
  1367  
  1368  	// Assists and workers can start the moment we start
  1369  	// the world.
  1370  	gcController.markStartTime = now
  1371  
  1372  	// Concurrent mark.
  1373  	systemstack(func() {
  1374  		now = startTheWorldWithSema(trace.enabled)
  1375  		work.pauseNS += now - work.pauseStart
  1376  		work.tMark = now
  1377  	})
  1378  	// In STW mode, we could block the instant systemstack
  1379  	// returns, so don't do anything important here. Make sure we
  1380  	// block rather than returning to user code.
  1381  	if mode != gcBackgroundMode {
  1382  		Gosched()
  1383  	}
  1384  
  1385  	semrelease(&work.startSema)
  1386  }
  1387  
  1388  // gcMarkDoneFlushed counts the number of P's with flushed work.
  1389  //
  1390  // Ideally this would be a captured local in gcMarkDone, but forEachP
  1391  // escapes its callback closure, so it can't capture anything.
  1392  //
  1393  // This is protected by markDoneSema.
  1394  var gcMarkDoneFlushed uint32
  1395  
  1396  // debugCachedWork enables extra checks for debugging premature mark
  1397  // termination.
  1398  //
  1399  // For debugging issue #27993.
  1400  const debugCachedWork = false
  1401  
  1402  // gcWorkPauseGen is for debugging the mark completion algorithm.
  1403  // gcWork put operations spin while gcWork.pauseGen == gcWorkPauseGen.
  1404  // Only used if debugCachedWork is true.
  1405  //
  1406  // For debugging issue #27993.
  1407  var gcWorkPauseGen uint32 = 1
  1408  
  1409  // gcMarkDone transitions the GC from mark to mark termination if all
  1410  // reachable objects have been marked (that is, there are no grey
  1411  // objects and can be no more in the future). Otherwise, it flushes
  1412  // all local work to the global queues where it can be discovered by
  1413  // other workers.
  1414  //
  1415  // This should be called when all local mark work has been drained and
  1416  // there are no remaining workers. Specifically, when
  1417  //
  1418  //   work.nwait == work.nproc && !gcMarkWorkAvailable(p)
  1419  //
  1420  // The calling context must be preemptible.
  1421  //
  1422  // Flushing local work is important because idle Ps may have local
  1423  // work queued. This is the only way to make that work visible and
  1424  // drive GC to completion.
  1425  //
  1426  // It is explicitly okay to have write barriers in this function. If
  1427  // it does transition to mark termination, then all reachable objects
  1428  // have been marked, so the write barrier cannot shade any more
  1429  // objects.
  1430  func gcMarkDone() {
  1431  	// Ensure only one thread is running the ragged barrier at a
  1432  	// time.
  1433  	semacquire(&work.markDoneSema)
  1434  
  1435  top:
  1436  	// Re-check transition condition under transition lock.
  1437  	//
  1438  	// It's critical that this checks the global work queues are
  1439  	// empty before performing the ragged barrier. Otherwise,
  1440  	// there could be global work that a P could take after the P
  1441  	// has passed the ragged barrier.
  1442  	if !(gcphase == _GCmark && work.nwait == work.nproc && !gcMarkWorkAvailable(nil)) {
  1443  		semrelease(&work.markDoneSema)
  1444  		return
  1445  	}
  1446  
  1447  	// Flush all local buffers and collect flushedWork flags.
  1448  	gcMarkDoneFlushed = 0
  1449  	systemstack(func() {
  1450  		gp := getg().m.curg
  1451  		// Mark the user stack as preemptible so that it may be scanned.
  1452  		// Otherwise, our attempt to force all P's to a safepoint could
  1453  		// result in a deadlock as we attempt to preempt a worker that's
  1454  		// trying to preempt us (e.g. for a stack scan).
  1455  		casgstatus(gp, _Grunning, _Gwaiting)
  1456  		forEachP(func(_p_ *p) {
  1457  			// Flush the write barrier buffer, since this may add
  1458  			// work to the gcWork.
  1459  			wbBufFlush1(_p_)
  1460  			// For debugging, shrink the write barrier
  1461  			// buffer so it flushes immediately.
  1462  			// wbBuf.reset will keep it at this size as
  1463  			// long as throwOnGCWork is set.
  1464  			if debugCachedWork {
  1465  				b := &_p_.wbBuf
  1466  				b.end = uintptr(unsafe.Pointer(&b.buf[wbBufEntryPointers]))
  1467  				b.debugGen = gcWorkPauseGen
  1468  			}
  1469  			// Flush the gcWork, since this may create global work
  1470  			// and set the flushedWork flag.
  1471  			//
  1472  			// TODO(austin): Break up these workbufs to
  1473  			// better distribute work.
  1474  			_p_.gcw.dispose()
  1475  			// Collect the flushedWork flag.
  1476  			if _p_.gcw.flushedWork {
  1477  				atomic.Xadd(&gcMarkDoneFlushed, 1)
  1478  				_p_.gcw.flushedWork = false
  1479  			} else if debugCachedWork {
  1480  				// For debugging, freeze the gcWork
  1481  				// until we know whether we've reached
  1482  				// completion or not. If we think
  1483  				// we've reached completion, but
  1484  				// there's a paused gcWork, then
  1485  				// that's a bug.
  1486  				_p_.gcw.pauseGen = gcWorkPauseGen
  1487  				// Capture the G's stack.
  1488  				for i := range _p_.gcw.pauseStack {
  1489  					_p_.gcw.pauseStack[i] = 0
  1490  				}
  1491  				callers(1, _p_.gcw.pauseStack[:])
  1492  			}
  1493  		})
  1494  		casgstatus(gp, _Gwaiting, _Grunning)
  1495  	})
  1496  
  1497  	if gcMarkDoneFlushed != 0 {
  1498  		if debugCachedWork {
  1499  			// Release paused gcWorks.
  1500  			atomic.Xadd(&gcWorkPauseGen, 1)
  1501  		}
  1502  		// More grey objects were discovered since the
  1503  		// previous termination check, so there may be more
  1504  		// work to do. Keep going. It's possible the
  1505  		// transition condition became true again during the
  1506  		// ragged barrier, so re-check it.
  1507  		goto top
  1508  	}
  1509  
  1510  	if debugCachedWork {
  1511  		throwOnGCWork = true
  1512  		// Release paused gcWorks. If there are any, they
  1513  		// should now observe throwOnGCWork and panic.
  1514  		atomic.Xadd(&gcWorkPauseGen, 1)
  1515  	}
  1516  
  1517  	// There was no global work, no local work, and no Ps
  1518  	// communicated work since we took markDoneSema. Therefore
  1519  	// there are no grey objects and no more objects can be
  1520  	// shaded. Transition to mark termination.
  1521  	now := nanotime()
  1522  	work.tMarkTerm = now
  1523  	work.pauseStart = now
  1524  	getg().m.preemptoff = "gcing"
  1525  	if trace.enabled {
  1526  		traceGCSTWStart(0)
  1527  	}
  1528  	systemstack(stopTheWorldWithSema)
  1529  	// The gcphase is _GCmark, it will transition to _GCmarktermination
  1530  	// below. The important thing is that the wb remains active until
  1531  	// all marking is complete. This includes writes made by the GC.
  1532  
  1533  	if debugCachedWork {
  1534  		// For debugging, double check that no work was added after we
  1535  		// went around above and disable write barrier buffering.
  1536  		for _, p := range allp {
  1537  			gcw := &p.gcw
  1538  			if !gcw.empty() {
  1539  				printlock()
  1540  				print("runtime: P ", p.id, " flushedWork ", gcw.flushedWork)
  1541  				if gcw.wbuf1 == nil {
  1542  					print(" wbuf1=<nil>")
  1543  				} else {
  1544  					print(" wbuf1.n=", gcw.wbuf1.nobj)
  1545  				}
  1546  				if gcw.wbuf2 == nil {
  1547  					print(" wbuf2=<nil>")
  1548  				} else {
  1549  					print(" wbuf2.n=", gcw.wbuf2.nobj)
  1550  				}
  1551  				print("\n")
  1552  				if gcw.pauseGen == gcw.putGen {
  1553  					println("runtime: checkPut already failed at this generation")
  1554  				}
  1555  				throw("throwOnGCWork")
  1556  			}
  1557  		}
  1558  	} else {
  1559  		// For unknown reasons (see issue #27993), there is
  1560  		// sometimes work left over when we enter mark
  1561  		// termination. Detect this and resume concurrent
  1562  		// mark. This is obviously unfortunate.
  1563  		//
  1564  		// Switch to the system stack to call wbBufFlush1,
  1565  		// though in this case it doesn't matter because we're
  1566  		// non-preemptible anyway.
  1567  		restart := false
  1568  		systemstack(func() {
  1569  			for _, p := range allp {
  1570  				wbBufFlush1(p)
  1571  				if !p.gcw.empty() {
  1572  					restart = true
  1573  					break
  1574  				}
  1575  			}
  1576  		})
  1577  		if restart {
  1578  			getg().m.preemptoff = ""
  1579  			systemstack(func() {
  1580  				now := startTheWorldWithSema(true)
  1581  				work.pauseNS += now - work.pauseStart
  1582  			})
  1583  			goto top
  1584  		}
  1585  	}
  1586  
  1587  	// Disable assists and background workers. We must do
  1588  	// this before waking blocked assists.
  1589  	atomic.Store(&gcBlackenEnabled, 0)
  1590  
  1591  	// Wake all blocked assists. These will run when we
  1592  	// start the world again.
  1593  	gcWakeAllAssists()
  1594  
  1595  	// Likewise, release the transition lock. Blocked
  1596  	// workers and assists will run when we start the
  1597  	// world again.
  1598  	semrelease(&work.markDoneSema)
  1599  
  1600  	// In STW mode, re-enable user goroutines. These will be
  1601  	// queued to run after we start the world.
  1602  	schedEnableUser(true)
  1603  
  1604  	// endCycle depends on all gcWork cache stats being flushed.
  1605  	// The termination algorithm above ensured that up to
  1606  	// allocations since the ragged barrier.
  1607  	nextTriggerRatio := gcController.endCycle()
  1608  
  1609  	// Perform mark termination. This will restart the world.
  1610  	gcMarkTermination(nextTriggerRatio)
  1611  }
  1612  
  1613  func gcMarkTermination(nextTriggerRatio float64) {
  1614  	// World is stopped.
  1615  	// Start marktermination which includes enabling the write barrier.
  1616  	atomic.Store(&gcBlackenEnabled, 0)
  1617  	setGCPhase(_GCmarktermination)
  1618  
  1619  	work.heap1 = memstats.heap_live
  1620  	startTime := nanotime()
  1621  
  1622  	mp := acquirem()
  1623  	mp.preemptoff = "gcing"
  1624  	_g_ := getg()
  1625  	_g_.m.traceback = 2
  1626  	gp := _g_.m.curg
  1627  	casgstatus(gp, _Grunning, _Gwaiting)
  1628  	gp.waitreason = waitReasonGarbageCollection
  1629  
  1630  	// Run gc on the g0 stack. We do this so that the g stack
  1631  	// we're currently running on will no longer change. Cuts
  1632  	// the root set down a bit (g0 stacks are not scanned, and
  1633  	// we don't need to scan gc's internal state).  We also
  1634  	// need to switch to g0 so we can shrink the stack.
  1635  	systemstack(func() {
  1636  		gcMark(startTime)
  1637  		// Must return immediately.
  1638  		// The outer function's stack may have moved
  1639  		// during gcMark (it shrinks stacks, including the
  1640  		// outer function's stack), so we must not refer
  1641  		// to any of its variables. Return back to the
  1642  		// non-system stack to pick up the new addresses
  1643  		// before continuing.
  1644  	})
  1645  
  1646  	systemstack(func() {
  1647  		work.heap2 = work.bytesMarked
  1648  		if debug.gccheckmark > 0 {
  1649  			// Run a full non-parallel, stop-the-world
  1650  			// mark using checkmark bits, to check that we
  1651  			// didn't forget to mark anything during the
  1652  			// concurrent mark process.
  1653  			gcResetMarkState()
  1654  			initCheckmarks()
  1655  			gcw := &getg().m.p.ptr().gcw
  1656  			gcDrain(gcw, 0)
  1657  			wbBufFlush1(getg().m.p.ptr())
  1658  			gcw.dispose()
  1659  			clearCheckmarks()
  1660  		}
  1661  
  1662  		// marking is complete so we can turn the write barrier off
  1663  		setGCPhase(_GCoff)
  1664  		gcSweep(work.mode)
  1665  	})
  1666  
  1667  	_g_.m.traceback = 0
  1668  	casgstatus(gp, _Gwaiting, _Grunning)
  1669  
  1670  	if trace.enabled {
  1671  		traceGCDone()
  1672  	}
  1673  
  1674  	// all done
  1675  	mp.preemptoff = ""
  1676  
  1677  	if gcphase != _GCoff {
  1678  		throw("gc done but gcphase != _GCoff")
  1679  	}
  1680  
  1681  	// Record next_gc and heap_inuse for scavenger.
  1682  	memstats.last_next_gc = memstats.next_gc
  1683  	memstats.last_heap_inuse = memstats.heap_inuse
  1684  
  1685  	// Update GC trigger and pacing for the next cycle.
  1686  	gcSetTriggerRatio(nextTriggerRatio)
  1687  
  1688  	// Pacing changed, so the scavenger should be awoken.
  1689  	wakeScavenger()
  1690  
  1691  	// Update timing memstats
  1692  	now := nanotime()
  1693  	sec, nsec, _ := time_now()
  1694  	unixNow := sec*1e9 + int64(nsec)
  1695  	work.pauseNS += now - work.pauseStart
  1696  	work.tEnd = now
  1697  	atomic.Store64(&memstats.last_gc_unix, uint64(unixNow)) // must be Unix time to make sense to user
  1698  	atomic.Store64(&memstats.last_gc_nanotime, uint64(now)) // monotonic time for us
  1699  	memstats.pause_ns[memstats.numgc%uint32(len(memstats.pause_ns))] = uint64(work.pauseNS)
  1700  	memstats.pause_end[memstats.numgc%uint32(len(memstats.pause_end))] = uint64(unixNow)
  1701  	memstats.pause_total_ns += uint64(work.pauseNS)
  1702  
  1703  	// Update work.totaltime.
  1704  	sweepTermCpu := int64(work.stwprocs) * (work.tMark - work.tSweepTerm)
  1705  	// We report idle marking time below, but omit it from the
  1706  	// overall utilization here since it's "free".
  1707  	markCpu := gcController.assistTime + gcController.dedicatedMarkTime + gcController.fractionalMarkTime
  1708  	markTermCpu := int64(work.stwprocs) * (work.tEnd - work.tMarkTerm)
  1709  	cycleCpu := sweepTermCpu + markCpu + markTermCpu
  1710  	work.totaltime += cycleCpu
  1711  
  1712  	// Compute overall GC CPU utilization.
  1713  	totalCpu := sched.totaltime + (now-sched.procresizetime)*int64(gomaxprocs)
  1714  	memstats.gc_cpu_fraction = float64(work.totaltime) / float64(totalCpu)
  1715  
  1716  	// Reset sweep state.
  1717  	sweep.nbgsweep = 0
  1718  	sweep.npausesweep = 0
  1719  
  1720  	if work.userForced {
  1721  		memstats.numforcedgc++
  1722  	}
  1723  
  1724  	// Bump GC cycle count and wake goroutines waiting on sweep.
  1725  	lock(&work.sweepWaiters.lock)
  1726  	memstats.numgc++
  1727  	injectglist(&work.sweepWaiters.list)
  1728  	unlock(&work.sweepWaiters.lock)
  1729  
  1730  	// Finish the current heap profiling cycle and start a new
  1731  	// heap profiling cycle. We do this before starting the world
  1732  	// so events don't leak into the wrong cycle.
  1733  	mProf_NextCycle()
  1734  
  1735  	systemstack(func() { startTheWorldWithSema(true) })
  1736  
  1737  	// Flush the heap profile so we can start a new cycle next GC.
  1738  	// This is relatively expensive, so we don't do it with the
  1739  	// world stopped.
  1740  	mProf_Flush()
  1741  
  1742  	// Prepare workbufs for freeing by the sweeper. We do this
  1743  	// asynchronously because it can take non-trivial time.
  1744  	prepareFreeWorkbufs()
  1745  
  1746  	// Free stack spans. This must be done between GC cycles.
  1747  	systemstack(freeStackSpans)
  1748  
  1749  	// Ensure all mcaches are flushed. Each P will flush its own
  1750  	// mcache before allocating, but idle Ps may not. Since this
  1751  	// is necessary to sweep all spans, we need to ensure all
  1752  	// mcaches are flushed before we start the next GC cycle.
  1753  	systemstack(func() {
  1754  		forEachP(func(_p_ *p) {
  1755  			_p_.mcache.prepareForSweep()
  1756  		})
  1757  	})
  1758  
  1759  	// Print gctrace before dropping worldsema. As soon as we drop
  1760  	// worldsema another cycle could start and smash the stats
  1761  	// we're trying to print.
  1762  	if debug.gctrace > 0 {
  1763  		util := int(memstats.gc_cpu_fraction * 100)
  1764  
  1765  		var sbuf [24]byte
  1766  		printlock()
  1767  		print("gc ", memstats.numgc,
  1768  			" @", string(itoaDiv(sbuf[:], uint64(work.tSweepTerm-runtimeInitTime)/1e6, 3)), "s ",
  1769  			util, "%: ")
  1770  		prev := work.tSweepTerm
  1771  		for i, ns := range []int64{work.tMark, work.tMarkTerm, work.tEnd} {
  1772  			if i != 0 {
  1773  				print("+")
  1774  			}
  1775  			print(string(fmtNSAsMS(sbuf[:], uint64(ns-prev))))
  1776  			prev = ns
  1777  		}
  1778  		print(" ms clock, ")
  1779  		for i, ns := range []int64{sweepTermCpu, gcController.assistTime, gcController.dedicatedMarkTime + gcController.fractionalMarkTime, gcController.idleMarkTime, markTermCpu} {
  1780  			if i == 2 || i == 3 {
  1781  				// Separate mark time components with /.
  1782  				print("/")
  1783  			} else if i != 0 {
  1784  				print("+")
  1785  			}
  1786  			print(string(fmtNSAsMS(sbuf[:], uint64(ns))))
  1787  		}
  1788  		print(" ms cpu, ",
  1789  			work.heap0>>20, "->", work.heap1>>20, "->", work.heap2>>20, " MB, ",
  1790  			work.heapGoal>>20, " MB goal, ",
  1791  			work.maxprocs, " P")
  1792  		if work.userForced {
  1793  			print(" (forced)")
  1794  		}
  1795  		print("\n")
  1796  		printunlock()
  1797  	}
  1798  
  1799  	semrelease(&worldsema)
  1800  	// Careful: another GC cycle may start now.
  1801  
  1802  	releasem(mp)
  1803  	mp = nil
  1804  
  1805  	// now that gc is done, kick off finalizer thread if needed
  1806  	if !concurrentSweep {
  1807  		// give the queued finalizers, if any, a chance to run
  1808  		Gosched()
  1809  	}
  1810  }
  1811  
  1812  // gcBgMarkStartWorkers prepares background mark worker goroutines.
  1813  // These goroutines will not run until the mark phase, but they must
  1814  // be started while the work is not stopped and from a regular G
  1815  // stack. The caller must hold worldsema.
  1816  func gcBgMarkStartWorkers() {
  1817  	// Background marking is performed by per-P G's. Ensure that
  1818  	// each P has a background GC G.
  1819  	for _, p := range allp {
  1820  		if p.gcBgMarkWorker == 0 {
  1821  			go gcBgMarkWorker(p)
  1822  			notetsleepg(&work.bgMarkReady, -1)
  1823  			noteclear(&work.bgMarkReady)
  1824  		}
  1825  	}
  1826  }
  1827  
  1828  // gcBgMarkPrepare sets up state for background marking.
  1829  // Mutator assists must not yet be enabled.
  1830  func gcBgMarkPrepare() {
  1831  	// Background marking will stop when the work queues are empty
  1832  	// and there are no more workers (note that, since this is
  1833  	// concurrent, this may be a transient state, but mark
  1834  	// termination will clean it up). Between background workers
  1835  	// and assists, we don't really know how many workers there
  1836  	// will be, so we pretend to have an arbitrarily large number
  1837  	// of workers, almost all of which are "waiting". While a
  1838  	// worker is working it decrements nwait. If nproc == nwait,
  1839  	// there are no workers.
  1840  	work.nproc = ^uint32(0)
  1841  	work.nwait = ^uint32(0)
  1842  }
  1843  
  1844  func gcBgMarkWorker(_p_ *p) {
  1845  	gp := getg()
  1846  
  1847  	type parkInfo struct {
  1848  		m      muintptr // Release this m on park.
  1849  		attach puintptr // If non-nil, attach to this p on park.
  1850  	}
  1851  	// We pass park to a gopark unlock function, so it can't be on
  1852  	// the stack (see gopark). Prevent deadlock from recursively
  1853  	// starting GC by disabling preemption.
  1854  	gp.m.preemptoff = "GC worker init"
  1855  	park := new(parkInfo)
  1856  	gp.m.preemptoff = ""
  1857  
  1858  	park.m.set(acquirem())
  1859  	park.attach.set(_p_)
  1860  	// Inform gcBgMarkStartWorkers that this worker is ready.
  1861  	// After this point, the background mark worker is scheduled
  1862  	// cooperatively by gcController.findRunnable. Hence, it must
  1863  	// never be preempted, as this would put it into _Grunnable
  1864  	// and put it on a run queue. Instead, when the preempt flag
  1865  	// is set, this puts itself into _Gwaiting to be woken up by
  1866  	// gcController.findRunnable at the appropriate time.
  1867  	notewakeup(&work.bgMarkReady)
  1868  
  1869  	for {
  1870  		// Go to sleep until woken by gcController.findRunnable.
  1871  		// We can't releasem yet since even the call to gopark
  1872  		// may be preempted.
  1873  		gopark(func(g *g, parkp unsafe.Pointer) bool {
  1874  			park := (*parkInfo)(parkp)
  1875  
  1876  			// The worker G is no longer running, so it's
  1877  			// now safe to allow preemption.
  1878  			releasem(park.m.ptr())
  1879  
  1880  			// If the worker isn't attached to its P,
  1881  			// attach now. During initialization and after
  1882  			// a phase change, the worker may have been
  1883  			// running on a different P. As soon as we
  1884  			// attach, the owner P may schedule the
  1885  			// worker, so this must be done after the G is
  1886  			// stopped.
  1887  			if park.attach != 0 {
  1888  				p := park.attach.ptr()
  1889  				park.attach.set(nil)
  1890  				// cas the worker because we may be
  1891  				// racing with a new worker starting
  1892  				// on this P.
  1893  				if !p.gcBgMarkWorker.cas(0, guintptr(unsafe.Pointer(g))) {
  1894  					// The P got a new worker.
  1895  					// Exit this worker.
  1896  					return false
  1897  				}
  1898  			}
  1899  			return true
  1900  		}, unsafe.Pointer(park), waitReasonGCWorkerIdle, traceEvGoBlock, 0)
  1901  
  1902  		// Loop until the P dies and disassociates this
  1903  		// worker (the P may later be reused, in which case
  1904  		// it will get a new worker) or we failed to associate.
  1905  		if _p_.gcBgMarkWorker.ptr() != gp {
  1906  			break
  1907  		}
  1908  
  1909  		// Disable preemption so we can use the gcw. If the
  1910  		// scheduler wants to preempt us, we'll stop draining,
  1911  		// dispose the gcw, and then preempt.
  1912  		park.m.set(acquirem())
  1913  
  1914  		if gcBlackenEnabled == 0 {
  1915  			throw("gcBgMarkWorker: blackening not enabled")
  1916  		}
  1917  
  1918  		startTime := nanotime()
  1919  		_p_.gcMarkWorkerStartTime = startTime
  1920  
  1921  		decnwait := atomic.Xadd(&work.nwait, -1)
  1922  		if decnwait == work.nproc {
  1923  			println("runtime: work.nwait=", decnwait, "work.nproc=", work.nproc)
  1924  			throw("work.nwait was > work.nproc")
  1925  		}
  1926  
  1927  		systemstack(func() {
  1928  			// Mark our goroutine preemptible so its stack
  1929  			// can be scanned. This lets two mark workers
  1930  			// scan each other (otherwise, they would
  1931  			// deadlock). We must not modify anything on
  1932  			// the G stack. However, stack shrinking is
  1933  			// disabled for mark workers, so it is safe to
  1934  			// read from the G stack.
  1935  			casgstatus(gp, _Grunning, _Gwaiting)
  1936  			switch _p_.gcMarkWorkerMode {
  1937  			default:
  1938  				throw("gcBgMarkWorker: unexpected gcMarkWorkerMode")
  1939  			case gcMarkWorkerDedicatedMode:
  1940  				gcDrain(&_p_.gcw, gcDrainUntilPreempt|gcDrainFlushBgCredit)
  1941  				if gp.preempt {
  1942  					// We were preempted. This is
  1943  					// a useful signal to kick
  1944  					// everything out of the run
  1945  					// queue so it can run
  1946  					// somewhere else.
  1947  					lock(&sched.lock)
  1948  					for {
  1949  						gp, _ := runqget(_p_)
  1950  						if gp == nil {
  1951  							break
  1952  						}
  1953  						globrunqput(gp)
  1954  					}
  1955  					unlock(&sched.lock)
  1956  				}
  1957  				// Go back to draining, this time
  1958  				// without preemption.
  1959  				gcDrain(&_p_.gcw, gcDrainFlushBgCredit)
  1960  			case gcMarkWorkerFractionalMode:
  1961  				gcDrain(&_p_.gcw, gcDrainFractional|gcDrainUntilPreempt|gcDrainFlushBgCredit)
  1962  			case gcMarkWorkerIdleMode:
  1963  				gcDrain(&_p_.gcw, gcDrainIdle|gcDrainUntilPreempt|gcDrainFlushBgCredit)
  1964  			}
  1965  			casgstatus(gp, _Gwaiting, _Grunning)
  1966  		})
  1967  
  1968  		// Account for time.
  1969  		duration := nanotime() - startTime
  1970  		switch _p_.gcMarkWorkerMode {
  1971  		case gcMarkWorkerDedicatedMode:
  1972  			atomic.Xaddint64(&gcController.dedicatedMarkTime, duration)
  1973  			atomic.Xaddint64(&gcController.dedicatedMarkWorkersNeeded, 1)
  1974  		case gcMarkWorkerFractionalMode:
  1975  			atomic.Xaddint64(&gcController.fractionalMarkTime, duration)
  1976  			atomic.Xaddint64(&_p_.gcFractionalMarkTime, duration)
  1977  		case gcMarkWorkerIdleMode:
  1978  			atomic.Xaddint64(&gcController.idleMarkTime, duration)
  1979  		}
  1980  
  1981  		// Was this the last worker and did we run out
  1982  		// of work?
  1983  		incnwait := atomic.Xadd(&work.nwait, +1)
  1984  		if incnwait > work.nproc {
  1985  			println("runtime: p.gcMarkWorkerMode=", _p_.gcMarkWorkerMode,
  1986  				"work.nwait=", incnwait, "work.nproc=", work.nproc)
  1987  			throw("work.nwait > work.nproc")
  1988  		}
  1989  
  1990  		// If this worker reached a background mark completion
  1991  		// point, signal the main GC goroutine.
  1992  		if incnwait == work.nproc && !gcMarkWorkAvailable(nil) {
  1993  			// Make this G preemptible and disassociate it
  1994  			// as the worker for this P so
  1995  			// findRunnableGCWorker doesn't try to
  1996  			// schedule it.
  1997  			_p_.gcBgMarkWorker.set(nil)
  1998  			releasem(park.m.ptr())
  1999  
  2000  			gcMarkDone()
  2001  
  2002  			// Disable preemption and prepare to reattach
  2003  			// to the P.
  2004  			//
  2005  			// We may be running on a different P at this
  2006  			// point, so we can't reattach until this G is
  2007  			// parked.
  2008  			park.m.set(acquirem())
  2009  			park.attach.set(_p_)
  2010  		}
  2011  	}
  2012  }
  2013  
  2014  // gcMarkWorkAvailable reports whether executing a mark worker
  2015  // on p is potentially useful. p may be nil, in which case it only
  2016  // checks the global sources of work.
  2017  func gcMarkWorkAvailable(p *p) bool {
  2018  	if p != nil && !p.gcw.empty() {
  2019  		return true
  2020  	}
  2021  	if !work.full.empty() {
  2022  		return true // global work available
  2023  	}
  2024  	if work.markrootNext < work.markrootJobs {
  2025  		return true // root scan work available
  2026  	}
  2027  	return false
  2028  }
  2029  
  2030  // gcMark runs the mark (or, for concurrent GC, mark termination)
  2031  // All gcWork caches must be empty.
  2032  // STW is in effect at this point.
  2033  func gcMark(start_time int64) {
  2034  	if debug.allocfreetrace > 0 {
  2035  		tracegc()
  2036  	}
  2037  
  2038  	if gcphase != _GCmarktermination {
  2039  		throw("in gcMark expecting to see gcphase as _GCmarktermination")
  2040  	}
  2041  	work.tstart = start_time
  2042  
  2043  	// Check that there's no marking work remaining.
  2044  	if work.full != 0 || work.markrootNext < work.markrootJobs {
  2045  		print("runtime: full=", hex(work.full), " next=", work.markrootNext, " jobs=", work.markrootJobs, " nDataRoots=", work.nDataRoots, " nBSSRoots=", work.nBSSRoots, " nSpanRoots=", work.nSpanRoots, " nStackRoots=", work.nStackRoots, "\n")
  2046  		panic("non-empty mark queue after concurrent mark")
  2047  	}
  2048  
  2049  	if debug.gccheckmark > 0 {
  2050  		// This is expensive when there's a large number of
  2051  		// Gs, so only do it if checkmark is also enabled.
  2052  		gcMarkRootCheck()
  2053  	}
  2054  	if work.full != 0 {
  2055  		throw("work.full != 0")
  2056  	}
  2057  
  2058  	// Clear out buffers and double-check that all gcWork caches
  2059  	// are empty. This should be ensured by gcMarkDone before we
  2060  	// enter mark termination.
  2061  	//
  2062  	// TODO: We could clear out buffers just before mark if this
  2063  	// has a non-negligible impact on STW time.
  2064  	for _, p := range allp {
  2065  		// The write barrier may have buffered pointers since
  2066  		// the gcMarkDone barrier. However, since the barrier
  2067  		// ensured all reachable objects were marked, all of
  2068  		// these must be pointers to black objects. Hence we
  2069  		// can just discard the write barrier buffer.
  2070  		if debug.gccheckmark > 0 || throwOnGCWork {
  2071  			// For debugging, flush the buffer and make
  2072  			// sure it really was all marked.
  2073  			wbBufFlush1(p)
  2074  		} else {
  2075  			p.wbBuf.reset()
  2076  		}
  2077  
  2078  		gcw := &p.gcw
  2079  		if !gcw.empty() {
  2080  			printlock()
  2081  			print("runtime: P ", p.id, " flushedWork ", gcw.flushedWork)
  2082  			if gcw.wbuf1 == nil {
  2083  				print(" wbuf1=<nil>")
  2084  			} else {
  2085  				print(" wbuf1.n=", gcw.wbuf1.nobj)
  2086  			}
  2087  			if gcw.wbuf2 == nil {
  2088  				print(" wbuf2=<nil>")
  2089  			} else {
  2090  				print(" wbuf2.n=", gcw.wbuf2.nobj)
  2091  			}
  2092  			print("\n")
  2093  			throw("P has cached GC work at end of mark termination")
  2094  		}
  2095  		// There may still be cached empty buffers, which we
  2096  		// need to flush since we're going to free them. Also,
  2097  		// there may be non-zero stats because we allocated
  2098  		// black after the gcMarkDone barrier.
  2099  		gcw.dispose()
  2100  	}
  2101  
  2102  	throwOnGCWork = false
  2103  
  2104  	cachestats()
  2105  
  2106  	// Update the marked heap stat.
  2107  	memstats.heap_marked = work.bytesMarked
  2108  
  2109  	// Update other GC heap size stats. This must happen after
  2110  	// cachestats (which flushes local statistics to these) and
  2111  	// flushallmcaches (which modifies heap_live).
  2112  	memstats.heap_live = work.bytesMarked
  2113  	memstats.heap_scan = uint64(gcController.scanWork)
  2114  
  2115  	if trace.enabled {
  2116  		traceHeapAlloc()
  2117  	}
  2118  }
  2119  
  2120  // gcSweep must be called on the system stack because it acquires the heap
  2121  // lock. See mheap for details.
  2122  //go:systemstack
  2123  func gcSweep(mode gcMode) {
  2124  	if gcphase != _GCoff {
  2125  		throw("gcSweep being done but phase is not GCoff")
  2126  	}
  2127  
  2128  	lock(&mheap_.lock)
  2129  	mheap_.sweepgen += 2
  2130  	mheap_.sweepdone = 0
  2131  	if mheap_.sweepSpans[mheap_.sweepgen/2%2].index != 0 {
  2132  		// We should have drained this list during the last
  2133  		// sweep phase. We certainly need to start this phase
  2134  		// with an empty swept list.
  2135  		throw("non-empty swept list")
  2136  	}
  2137  	mheap_.pagesSwept = 0
  2138  	mheap_.sweepArenas = mheap_.allArenas
  2139  	mheap_.reclaimIndex = 0
  2140  	mheap_.reclaimCredit = 0
  2141  	unlock(&mheap_.lock)
  2142  
  2143  	if !_ConcurrentSweep || mode == gcForceBlockMode {
  2144  		// Special case synchronous sweep.
  2145  		// Record that no proportional sweeping has to happen.
  2146  		lock(&mheap_.lock)
  2147  		mheap_.sweepPagesPerByte = 0
  2148  		unlock(&mheap_.lock)
  2149  		// Sweep all spans eagerly.
  2150  		for sweepone() != ^uintptr(0) {
  2151  			sweep.npausesweep++
  2152  		}
  2153  		// Free workbufs eagerly.
  2154  		prepareFreeWorkbufs()
  2155  		for freeSomeWbufs(false) {
  2156  		}
  2157  		// All "free" events for this mark/sweep cycle have
  2158  		// now happened, so we can make this profile cycle
  2159  		// available immediately.
  2160  		mProf_NextCycle()
  2161  		mProf_Flush()
  2162  		return
  2163  	}
  2164  
  2165  	// Background sweep.
  2166  	lock(&sweep.lock)
  2167  	if sweep.parked {
  2168  		sweep.parked = false
  2169  		ready(sweep.g, 0, true)
  2170  	}
  2171  	unlock(&sweep.lock)
  2172  }
  2173  
  2174  // gcResetMarkState resets global state prior to marking (concurrent
  2175  // or STW) and resets the stack scan state of all Gs.
  2176  //
  2177  // This is safe to do without the world stopped because any Gs created
  2178  // during or after this will start out in the reset state.
  2179  //
  2180  // gcResetMarkState must be called on the system stack because it acquires
  2181  // the heap lock. See mheap for details.
  2182  //
  2183  //go:systemstack
  2184  func gcResetMarkState() {
  2185  	// This may be called during a concurrent phase, so make sure
  2186  	// allgs doesn't change.
  2187  	lock(&allglock)
  2188  	for _, gp := range allgs {
  2189  		gp.gcscandone = false // set to true in gcphasework
  2190  		gp.gcAssistBytes = 0
  2191  	}
  2192  	unlock(&allglock)
  2193  
  2194  	// Clear page marks. This is just 1MB per 64GB of heap, so the
  2195  	// time here is pretty trivial.
  2196  	lock(&mheap_.lock)
  2197  	arenas := mheap_.allArenas
  2198  	unlock(&mheap_.lock)
  2199  	for _, ai := range arenas {
  2200  		ha := mheap_.arenas[ai.l1()][ai.l2()]
  2201  		for i := range ha.pageMarks {
  2202  			ha.pageMarks[i] = 0
  2203  		}
  2204  	}
  2205  
  2206  	work.bytesMarked = 0
  2207  	work.initialHeapLive = atomic.Load64(&memstats.heap_live)
  2208  }
  2209  
  2210  // Hooks for other packages
  2211  
  2212  var poolcleanup func()
  2213  
  2214  //go:linkname sync_runtime_registerPoolCleanup sync.runtime_registerPoolCleanup
  2215  func sync_runtime_registerPoolCleanup(f func()) {
  2216  	poolcleanup = f
  2217  }
  2218  
  2219  func clearpools() {
  2220  	// clear sync.Pools
  2221  	if poolcleanup != nil {
  2222  		poolcleanup()
  2223  	}
  2224  
  2225  	// Clear central sudog cache.
  2226  	// Leave per-P caches alone, they have strictly bounded size.
  2227  	// Disconnect cached list before dropping it on the floor,
  2228  	// so that a dangling ref to one entry does not pin all of them.
  2229  	lock(&sched.sudoglock)
  2230  	var sg, sgnext *sudog
  2231  	for sg = sched.sudogcache; sg != nil; sg = sgnext {
  2232  		sgnext = sg.next
  2233  		sg.next = nil
  2234  	}
  2235  	sched.sudogcache = nil
  2236  	unlock(&sched.sudoglock)
  2237  
  2238  	// Clear central defer pools.
  2239  	// Leave per-P pools alone, they have strictly bounded size.
  2240  	lock(&sched.deferlock)
  2241  	for i := range sched.deferpool {
  2242  		// disconnect cached list before dropping it on the floor,
  2243  		// so that a dangling ref to one entry does not pin all of them.
  2244  		var d, dlink *_defer
  2245  		for d = sched.deferpool[i]; d != nil; d = dlink {
  2246  			dlink = d.link
  2247  			d.link = nil
  2248  		}
  2249  		sched.deferpool[i] = nil
  2250  	}
  2251  	unlock(&sched.deferlock)
  2252  }
  2253  
  2254  // Timing
  2255  
  2256  // itoaDiv formats val/(10**dec) into buf.
  2257  func itoaDiv(buf []byte, val uint64, dec int) []byte {
  2258  	i := len(buf) - 1
  2259  	idec := i - dec
  2260  	for val >= 10 || i >= idec {
  2261  		buf[i] = byte(val%10 + '0')
  2262  		i--
  2263  		if i == idec {
  2264  			buf[i] = '.'
  2265  			i--
  2266  		}
  2267  		val /= 10
  2268  	}
  2269  	buf[i] = byte(val + '0')
  2270  	return buf[i:]
  2271  }
  2272  
  2273  // fmtNSAsMS nicely formats ns nanoseconds as milliseconds.
  2274  func fmtNSAsMS(buf []byte, ns uint64) []byte {
  2275  	if ns >= 10e6 {
  2276  		// Format as whole milliseconds.
  2277  		return itoaDiv(buf, ns/1e6, 0)
  2278  	}
  2279  	// Format two digits of precision, with at most three decimal places.
  2280  	x := ns / 1e3
  2281  	if x == 0 {
  2282  		buf[0] = '0'
  2283  		return buf[:1]
  2284  	}
  2285  	dec := 3
  2286  	for x >= 100 {
  2287  		x /= 10
  2288  		dec--
  2289  	}
  2290  	return itoaDiv(buf, x, dec)
  2291  }
  2292  

View as plain text