github.com/jonasi/go@v0.0.0-20150930005915-e78e654c1de0/src/runtime/mgc.go (about)

     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  // TODO(rsc): The code having to do with the heap bitmap needs very serious cleanup.
     6  // It has gotten completely out of control.
     7  
     8  // Garbage collector (GC).
     9  //
    10  // The GC runs concurrently with mutator threads, is type accurate (aka precise), allows multiple
    11  // GC thread to run in parallel. It is a concurrent mark and sweep that uses a write barrier. It is
    12  // non-generational and non-compacting. Allocation is done using size segregated per P allocation
    13  // areas to minimize fragmentation while eliminating locks in the common case.
    14  //
    15  // The algorithm decomposes into several steps.
    16  // This is a high level description of the algorithm being used. For an overview of GC a good
    17  // place to start is Richard Jones' gchandbook.org.
    18  //
    19  // The algorithm's intellectual heritage includes Dijkstra's on-the-fly algorithm, see
    20  // Edsger W. Dijkstra, Leslie Lamport, A. J. Martin, C. S. Scholten, and E. F. M. Steffens. 1978.
    21  // On-the-fly garbage collection: an exercise in cooperation. Commun. ACM 21, 11 (November 1978),
    22  // 966-975.
    23  // For journal quality proofs that these steps are complete, correct, and terminate see
    24  // Hudson, R., and Moss, J.E.B. Copying Garbage Collection without stopping the world.
    25  // Concurrency and Computation: Practice and Experience 15(3-5), 2003.
    26  //
    27  //  0. Set phase = GCscan from GCoff.
    28  //  1. Wait for all P's to acknowledge phase change.
    29  //         At this point all goroutines have passed through a GC safepoint and
    30  //         know we are in the GCscan phase.
    31  //  2. GC scans all goroutine stacks, mark and enqueues all encountered pointers
    32  //       (marking avoids most duplicate enqueuing but races may produce benign duplication).
    33  //       Preempted goroutines are scanned before P schedules next goroutine.
    34  //  3. Set phase = GCmark.
    35  //  4. Wait for all P's to acknowledge phase change.
    36  //  5. Now write barrier marks and enqueues black, grey, or white to white pointers.
    37  //       Malloc still allocates white (non-marked) objects.
    38  //  6. Meanwhile GC transitively walks the heap marking reachable objects.
    39  //  7. When GC finishes marking heap, it preempts P's one-by-one and
    40  //       retakes partial wbufs (filled by write barrier or during a stack scan of the goroutine
    41  //       currently scheduled on the P).
    42  //  8. Once the GC has exhausted all available marking work it sets phase = marktermination.
    43  //  9. Wait for all P's to acknowledge phase change.
    44  // 10. Malloc now allocates black objects, so number of unmarked reachable objects
    45  //        monotonically decreases.
    46  // 11. GC preempts P's one-by-one taking partial wbufs and marks all unmarked yet
    47  //        reachable objects.
    48  // 12. When GC completes a full cycle over P's and discovers no new grey
    49  //         objects, (which means all reachable objects are marked) set phase = GCoff.
    50  // 13. Wait for all P's to acknowledge phase change.
    51  // 14. Now malloc allocates white (but sweeps spans before use).
    52  //         Write barrier becomes nop.
    53  // 15. GC does background sweeping, see description below.
    54  // 16. When sufficient allocation has taken place replay the sequence starting at 0 above,
    55  //         see discussion of GC rate below.
    56  
    57  // Changing phases.
    58  // Phases are changed by setting the gcphase to the next phase and possibly calling ackgcphase.
    59  // All phase action must be benign in the presence of a change.
    60  // Starting with GCoff
    61  // GCoff to GCscan
    62  //     GSscan scans stacks and globals greying them and never marks an object black.
    63  //     Once all the P's are aware of the new phase they will scan gs on preemption.
    64  //     This means that the scanning of preempted gs can't start until all the Ps
    65  //     have acknowledged.
    66  //     When a stack is scanned, this phase also installs stack barriers to
    67  //     track how much of the stack has been active.
    68  //     This transition enables write barriers because stack barriers
    69  //     assume that writes to higher frames will be tracked by write
    70  //     barriers. Technically this only needs write barriers for writes
    71  //     to stack slots, but we enable write barriers in general.
    72  // GCscan to GCmark
    73  //     In GCmark, work buffers are drained until there are no more
    74  //     pointers to scan.
    75  //     No scanning of objects (making them black) can happen until all
    76  //     Ps have enabled the write barrier, but that already happened in
    77  //     the transition to GCscan.
    78  // GCmark to GCmarktermination
    79  //     The only change here is that we start allocating black so the Ps must acknowledge
    80  //     the change before we begin the termination algorithm
    81  // GCmarktermination to GSsweep
    82  //     Object currently on the freelist must be marked black for this to work.
    83  //     Are things on the free lists black or white? How does the sweep phase work?
    84  
    85  // Concurrent sweep.
    86  //
    87  // The sweep phase proceeds concurrently with normal program execution.
    88  // The heap is swept span-by-span both lazily (when a goroutine needs another span)
    89  // and concurrently in a background goroutine (this helps programs that are not CPU bound).
    90  // At the end of STW mark termination all spans are marked as "needs sweeping".
    91  //
    92  // The background sweeper goroutine simply sweeps spans one-by-one.
    93  //
    94  // To avoid requesting more OS memory while there are unswept spans, when a
    95  // goroutine needs another span, it first attempts to reclaim that much memory
    96  // by sweeping. When a goroutine needs to allocate a new small-object span, it
    97  // sweeps small-object spans for the same object size until it frees at least
    98  // one object. When a goroutine needs to allocate large-object span from heap,
    99  // it sweeps spans until it frees at least that many pages into heap. There is
   100  // one case where this may not suffice: if a goroutine sweeps and frees two
   101  // nonadjacent one-page spans to the heap, it will allocate a new two-page
   102  // span, but there can still be other one-page unswept spans which could be
   103  // combined into a two-page span.
   104  //
   105  // It's critical to ensure that no operations proceed on unswept spans (that would corrupt
   106  // mark bits in GC bitmap). During GC all mcaches are flushed into the central cache,
   107  // so they are empty. When a goroutine grabs a new span into mcache, it sweeps it.
   108  // When a goroutine explicitly frees an object or sets a finalizer, it ensures that
   109  // the span is swept (either by sweeping it, or by waiting for the concurrent sweep to finish).
   110  // The finalizer goroutine is kicked off only when all spans are swept.
   111  // When the next GC starts, it sweeps all not-yet-swept spans (if any).
   112  
   113  // GC rate.
   114  // Next GC is after we've allocated an extra amount of memory proportional to
   115  // the amount already in use. The proportion is controlled by GOGC environment variable
   116  // (100 by default). If GOGC=100 and we're using 4M, we'll GC again when we get to 8M
   117  // (this mark is tracked in next_gc variable). This keeps the GC cost in linear
   118  // proportion to the allocation cost. Adjusting GOGC just changes the linear constant
   119  // (and also the amount of extra memory used).
   120  
   121  package runtime
   122  
   123  import "unsafe"
   124  
   125  const (
   126  	_DebugGC         = 0
   127  	_ConcurrentSweep = true
   128  	_FinBlockSize    = 4 * 1024
   129  
   130  	_RootData        = 0
   131  	_RootBss         = 1
   132  	_RootFinalizers  = 2
   133  	_RootFlushCaches = 3
   134  	_RootSpans0      = 4
   135  	_RootSpansShards = 128
   136  	_RootCount       = _RootSpans0 + _RootSpansShards
   137  
   138  	// sweepMinHeapDistance is a lower bound on the heap distance
   139  	// (in bytes) reserved for concurrent sweeping between GC
   140  	// cycles. This will be scaled by gcpercent/100.
   141  	sweepMinHeapDistance = 1024 * 1024
   142  )
   143  
   144  // heapminimum is the minimum heap size at which to trigger GC.
   145  // For small heaps, this overrides the usual GOGC*live set rule.
   146  //
   147  // When there is a very small live set but a lot of allocation, simply
   148  // collecting when the heap reaches GOGC*live results in many GC
   149  // cycles and high total per-GC overhead. This minimum amortizes this
   150  // per-GC overhead while keeping the heap reasonably small.
   151  //
   152  // During initialization this is set to 4MB*GOGC/100. In the case of
   153  // GOGC==0, this will set heapminimum to 0, resulting in constant
   154  // collection even when the heap size is small, which is useful for
   155  // debugging.
   156  var heapminimum uint64 = defaultHeapMinimum
   157  
   158  // defaultHeapMinimum is the value of heapminimum for GOGC==100.
   159  const defaultHeapMinimum = 4 << 20
   160  
   161  // Initialized from $GOGC.  GOGC=off means no GC.
   162  var gcpercent int32
   163  
   164  func gcinit() {
   165  	if unsafe.Sizeof(workbuf{}) != _WorkbufSize {
   166  		throw("size of Workbuf is suboptimal")
   167  	}
   168  
   169  	work.markfor = parforalloc(_MaxGcproc)
   170  	_ = setGCPercent(readgogc())
   171  	for datap := &firstmoduledata; datap != nil; datap = datap.next {
   172  		datap.gcdatamask = progToPointerMask((*byte)(unsafe.Pointer(datap.gcdata)), datap.edata-datap.data)
   173  		datap.gcbssmask = progToPointerMask((*byte)(unsafe.Pointer(datap.gcbss)), datap.ebss-datap.bss)
   174  	}
   175  	memstats.next_gc = heapminimum
   176  }
   177  
   178  func readgogc() int32 {
   179  	p := gogetenv("GOGC")
   180  	if p == "" {
   181  		return 100
   182  	}
   183  	if p == "off" {
   184  		return -1
   185  	}
   186  	return int32(atoi(p))
   187  }
   188  
   189  // gcenable is called after the bulk of the runtime initialization,
   190  // just before we're about to start letting user code run.
   191  // It kicks off the background sweeper goroutine and enables GC.
   192  func gcenable() {
   193  	c := make(chan int, 1)
   194  	go bgsweep(c)
   195  	<-c
   196  	memstats.enablegc = true // now that runtime is initialized, GC is okay
   197  }
   198  
   199  func setGCPercent(in int32) (out int32) {
   200  	lock(&mheap_.lock)
   201  	out = gcpercent
   202  	if in < 0 {
   203  		in = -1
   204  	}
   205  	gcpercent = in
   206  	heapminimum = defaultHeapMinimum * uint64(gcpercent) / 100
   207  	unlock(&mheap_.lock)
   208  	return out
   209  }
   210  
   211  // Garbage collector phase.
   212  // Indicates to write barrier and sychronization task to preform.
   213  var gcphase uint32
   214  var writeBarrierEnabled bool // compiler emits references to this in write barriers
   215  
   216  // gcBlackenEnabled is 1 if mutator assists and background mark
   217  // workers are allowed to blacken objects. This must only be set when
   218  // gcphase == _GCmark.
   219  var gcBlackenEnabled uint32
   220  
   221  // gcBlackenPromptly indicates that optimizations that may
   222  // hide work from the global work queue should be disabled.
   223  //
   224  // If gcBlackenPromptly is true, per-P gcWork caches should
   225  // be flushed immediately and new objects should be allocated black.
   226  //
   227  // There is a tension between allocating objects white and
   228  // allocating them black. If white and the objects die before being
   229  // marked they can be collected during this GC cycle. On the other
   230  // hand allocating them black will reduce _GCmarktermination latency
   231  // since more work is done in the mark phase. This tension is resolved
   232  // by allocating white until the mark phase is approaching its end and
   233  // then allocating black for the remainder of the mark phase.
   234  var gcBlackenPromptly bool
   235  
   236  const (
   237  	_GCoff             = iota // GC not running; sweeping in background, write barrier disabled
   238  	_GCstw                    // unused state
   239  	_GCscan                   // GC collecting roots into workbufs, write barrier ENABLED
   240  	_GCmark                   // GC marking from workbufs, write barrier ENABLED
   241  	_GCmarktermination        // GC mark termination: allocate black, P's help GC, write barrier ENABLED
   242  )
   243  
   244  //go:nosplit
   245  func setGCPhase(x uint32) {
   246  	atomicstore(&gcphase, x)
   247  	writeBarrierEnabled = gcphase == _GCmark || gcphase == _GCmarktermination || gcphase == _GCscan
   248  }
   249  
   250  // gcMarkWorkerMode represents the mode that a concurrent mark worker
   251  // should operate in.
   252  //
   253  // Concurrent marking happens through four different mechanisms. One
   254  // is mutator assists, which happen in response to allocations and are
   255  // not scheduled. The other three are variations in the per-P mark
   256  // workers and are distinguished by gcMarkWorkerMode.
   257  type gcMarkWorkerMode int
   258  
   259  const (
   260  	// gcMarkWorkerDedicatedMode indicates that the P of a mark
   261  	// worker is dedicated to running that mark worker. The mark
   262  	// worker should run without preemption until concurrent mark
   263  	// is done.
   264  	gcMarkWorkerDedicatedMode gcMarkWorkerMode = iota
   265  
   266  	// gcMarkWorkerFractionalMode indicates that a P is currently
   267  	// running the "fractional" mark worker. The fractional worker
   268  	// is necessary when GOMAXPROCS*gcGoalUtilization is not an
   269  	// integer. The fractional worker should run until it is
   270  	// preempted and will be scheduled to pick up the fractional
   271  	// part of GOMAXPROCS*gcGoalUtilization.
   272  	gcMarkWorkerFractionalMode
   273  
   274  	// gcMarkWorkerIdleMode indicates that a P is running the mark
   275  	// worker because it has nothing else to do. The idle worker
   276  	// should run until it is preempted and account its time
   277  	// against gcController.idleMarkTime.
   278  	gcMarkWorkerIdleMode
   279  )
   280  
   281  // gcController implements the GC pacing controller that determines
   282  // when to trigger concurrent garbage collection and how much marking
   283  // work to do in mutator assists and background marking.
   284  //
   285  // It uses a feedback control algorithm to adjust the memstats.next_gc
   286  // trigger based on the heap growth and GC CPU utilization each cycle.
   287  // This algorithm optimizes for heap growth to match GOGC and for CPU
   288  // utilization between assist and background marking to be 25% of
   289  // GOMAXPROCS. The high-level design of this algorithm is documented
   290  // at https://golang.org/s/go15gcpacing.
   291  var gcController = gcControllerState{
   292  	// Initial trigger ratio guess.
   293  	triggerRatio: 7 / 8.0,
   294  }
   295  
   296  type gcControllerState struct {
   297  	// scanWork is the total scan work performed this cycle. This
   298  	// is updated atomically during the cycle. Updates may be
   299  	// batched arbitrarily, since the value is only read at the
   300  	// end of the cycle.
   301  	//
   302  	// Currently this is the bytes of heap scanned. For most uses,
   303  	// this is an opaque unit of work, but for estimation the
   304  	// definition is important.
   305  	scanWork int64
   306  
   307  	// bgScanCredit is the scan work credit accumulated by the
   308  	// concurrent background scan. This credit is accumulated by
   309  	// the background scan and stolen by mutator assists. This is
   310  	// updated atomically. Updates occur in bounded batches, since
   311  	// it is both written and read throughout the cycle.
   312  	bgScanCredit int64
   313  
   314  	// assistTime is the nanoseconds spent in mutator assists
   315  	// during this cycle. This is updated atomically. Updates
   316  	// occur in bounded batches, since it is both written and read
   317  	// throughout the cycle.
   318  	assistTime int64
   319  
   320  	// dedicatedMarkTime is the nanoseconds spent in dedicated
   321  	// mark workers during this cycle. This is updated atomically
   322  	// at the end of the concurrent mark phase.
   323  	dedicatedMarkTime int64
   324  
   325  	// fractionalMarkTime is the nanoseconds spent in the
   326  	// fractional mark worker during this cycle. This is updated
   327  	// atomically throughout the cycle and will be up-to-date if
   328  	// the fractional mark worker is not currently running.
   329  	fractionalMarkTime int64
   330  
   331  	// idleMarkTime is the nanoseconds spent in idle marking
   332  	// during this cycle. This is updated atomically throughout
   333  	// the cycle.
   334  	idleMarkTime int64
   335  
   336  	// bgMarkStartTime is the absolute start time in nanoseconds
   337  	// that the background mark phase started.
   338  	bgMarkStartTime int64
   339  
   340  	// assistTime is the absolute start time in nanoseconds that
   341  	// mutator assists were enabled.
   342  	assistStartTime int64
   343  
   344  	// heapGoal is the goal memstats.heap_live for when this cycle
   345  	// ends. This is computed at the beginning of each cycle.
   346  	heapGoal uint64
   347  
   348  	// dedicatedMarkWorkersNeeded is the number of dedicated mark
   349  	// workers that need to be started. This is computed at the
   350  	// beginning of each cycle and decremented atomically as
   351  	// dedicated mark workers get started.
   352  	dedicatedMarkWorkersNeeded int64
   353  
   354  	// assistRatio is the ratio of allocated bytes to scan work
   355  	// that should be performed by mutator assists. This is
   356  	// computed at the beginning of each cycle and updated every
   357  	// time heap_scan is updated.
   358  	assistRatio float64
   359  
   360  	// fractionalUtilizationGoal is the fraction of wall clock
   361  	// time that should be spent in the fractional mark worker.
   362  	// For example, if the overall mark utilization goal is 25%
   363  	// and GOMAXPROCS is 6, one P will be a dedicated mark worker
   364  	// and this will be set to 0.5 so that 50% of the time some P
   365  	// is in a fractional mark worker. This is computed at the
   366  	// beginning of each cycle.
   367  	fractionalUtilizationGoal float64
   368  
   369  	// triggerRatio is the heap growth ratio at which the garbage
   370  	// collection cycle should start. E.g., if this is 0.6, then
   371  	// GC should start when the live heap has reached 1.6 times
   372  	// the heap size marked by the previous cycle. This is updated
   373  	// at the end of of each cycle.
   374  	triggerRatio float64
   375  
   376  	_ [_CacheLineSize]byte
   377  
   378  	// fractionalMarkWorkersNeeded is the number of fractional
   379  	// mark workers that need to be started. This is either 0 or
   380  	// 1. This is potentially updated atomically at every
   381  	// scheduling point (hence it gets its own cache line).
   382  	fractionalMarkWorkersNeeded int64
   383  
   384  	_ [_CacheLineSize]byte
   385  }
   386  
   387  // startCycle resets the GC controller's state and computes estimates
   388  // for a new GC cycle. The caller must hold worldsema.
   389  func (c *gcControllerState) startCycle() {
   390  	c.scanWork = 0
   391  	c.bgScanCredit = 0
   392  	c.assistTime = 0
   393  	c.dedicatedMarkTime = 0
   394  	c.fractionalMarkTime = 0
   395  	c.idleMarkTime = 0
   396  
   397  	// If this is the first GC cycle or we're operating on a very
   398  	// small heap, fake heap_marked so it looks like next_gc is
   399  	// the appropriate growth from heap_marked, even though the
   400  	// real heap_marked may not have a meaningful value (on the
   401  	// first cycle) or may be much smaller (resulting in a large
   402  	// error response).
   403  	if memstats.next_gc <= heapminimum {
   404  		memstats.heap_marked = uint64(float64(memstats.next_gc) / (1 + c.triggerRatio))
   405  		memstats.heap_reachable = memstats.heap_marked
   406  	}
   407  
   408  	// Compute the heap goal for this cycle
   409  	c.heapGoal = memstats.heap_reachable + memstats.heap_reachable*uint64(gcpercent)/100
   410  
   411  	// Compute the total mark utilization goal and divide it among
   412  	// dedicated and fractional workers.
   413  	totalUtilizationGoal := float64(gomaxprocs) * gcGoalUtilization
   414  	c.dedicatedMarkWorkersNeeded = int64(totalUtilizationGoal)
   415  	c.fractionalUtilizationGoal = totalUtilizationGoal - float64(c.dedicatedMarkWorkersNeeded)
   416  	if c.fractionalUtilizationGoal > 0 {
   417  		c.fractionalMarkWorkersNeeded = 1
   418  	} else {
   419  		c.fractionalMarkWorkersNeeded = 0
   420  	}
   421  
   422  	// Clear per-P state
   423  	for _, p := range &allp {
   424  		if p == nil {
   425  			break
   426  		}
   427  		p.gcAssistTime = 0
   428  	}
   429  
   430  	// Compute initial values for controls that are updated
   431  	// throughout the cycle.
   432  	c.revise()
   433  
   434  	if debug.gcpacertrace > 0 {
   435  		print("pacer: assist ratio=", c.assistRatio,
   436  			" (scan ", memstats.heap_scan>>20, " MB in ",
   437  			work.initialHeapLive>>20, "->",
   438  			c.heapGoal>>20, " MB)",
   439  			" workers=", c.dedicatedMarkWorkersNeeded,
   440  			"+", c.fractionalMarkWorkersNeeded, "\n")
   441  	}
   442  }
   443  
   444  // revise updates the assist ratio during the GC cycle to account for
   445  // improved estimates. This should be called either under STW or
   446  // whenever memstats.heap_scan is updated (with mheap_.lock held).
   447  func (c *gcControllerState) revise() {
   448  	// Compute the expected scan work. This is a strict upper
   449  	// bound on the possible scan work in the current heap.
   450  	//
   451  	// You might consider dividing this by 2 (or by
   452  	// (100+GOGC)/100) to counter this over-estimation, but
   453  	// benchmarks show that this has almost no effect on mean
   454  	// mutator utilization, heap size, or assist time and it
   455  	// introduces the danger of under-estimating and letting the
   456  	// mutator outpace the garbage collector.
   457  	scanWorkExpected := memstats.heap_scan
   458  
   459  	// Compute the mutator assist ratio so by the time the mutator
   460  	// allocates the remaining heap bytes up to next_gc, it will
   461  	// have done (or stolen) the estimated amount of scan work.
   462  	heapDistance := int64(c.heapGoal) - int64(work.initialHeapLive)
   463  	if heapDistance <= 1024*1024 {
   464  		// heapDistance can be negative if GC start is delayed
   465  		// or if the allocation that pushed heap_live over
   466  		// next_gc is large or if the trigger is really close
   467  		// to GOGC. We don't want to set the assist negative
   468  		// (or divide by zero, or set it really high), so
   469  		// enforce a minimum on the distance.
   470  		heapDistance = 1024 * 1024
   471  	}
   472  	c.assistRatio = float64(scanWorkExpected) / float64(heapDistance)
   473  }
   474  
   475  // endCycle updates the GC controller state at the end of the
   476  // concurrent part of the GC cycle.
   477  func (c *gcControllerState) endCycle() {
   478  	h_t := c.triggerRatio // For debugging
   479  
   480  	// Proportional response gain for the trigger controller. Must
   481  	// be in [0, 1]. Lower values smooth out transient effects but
   482  	// take longer to respond to phase changes. Higher values
   483  	// react to phase changes quickly, but are more affected by
   484  	// transient changes. Values near 1 may be unstable.
   485  	const triggerGain = 0.5
   486  
   487  	// Compute next cycle trigger ratio. First, this computes the
   488  	// "error" for this cycle; that is, how far off the trigger
   489  	// was from what it should have been, accounting for both heap
   490  	// growth and GC CPU utilization. We compute the actual heap
   491  	// growth during this cycle and scale that by how far off from
   492  	// the goal CPU utilization we were (to estimate the heap
   493  	// growth if we had the desired CPU utilization). The
   494  	// difference between this estimate and the GOGC-based goal
   495  	// heap growth is the error.
   496  	//
   497  	// TODO(austin): next_gc is based on heap_reachable, not
   498  	// heap_marked, which means the actual growth ratio
   499  	// technically isn't comparable to the trigger ratio.
   500  	goalGrowthRatio := float64(gcpercent) / 100
   501  	actualGrowthRatio := float64(memstats.heap_live)/float64(memstats.heap_marked) - 1
   502  	assistDuration := nanotime() - c.assistStartTime
   503  
   504  	// Assume background mark hit its utilization goal.
   505  	utilization := gcGoalUtilization
   506  	// Add assist utilization; avoid divide by zero.
   507  	if assistDuration > 0 {
   508  		utilization += float64(c.assistTime) / float64(assistDuration*int64(gomaxprocs))
   509  	}
   510  
   511  	triggerError := goalGrowthRatio - c.triggerRatio - utilization/gcGoalUtilization*(actualGrowthRatio-c.triggerRatio)
   512  
   513  	// Finally, we adjust the trigger for next time by this error,
   514  	// damped by the proportional gain.
   515  	c.triggerRatio += triggerGain * triggerError
   516  	if c.triggerRatio < 0 {
   517  		// This can happen if the mutator is allocating very
   518  		// quickly or the GC is scanning very slowly.
   519  		c.triggerRatio = 0
   520  	} else if c.triggerRatio > goalGrowthRatio*0.95 {
   521  		// Ensure there's always a little margin so that the
   522  		// mutator assist ratio isn't infinity.
   523  		c.triggerRatio = goalGrowthRatio * 0.95
   524  	}
   525  
   526  	if debug.gcpacertrace > 0 {
   527  		// Print controller state in terms of the design
   528  		// document.
   529  		H_m_prev := memstats.heap_marked
   530  		H_T := memstats.next_gc
   531  		h_a := actualGrowthRatio
   532  		H_a := memstats.heap_live
   533  		h_g := goalGrowthRatio
   534  		H_g := int64(float64(H_m_prev) * (1 + h_g))
   535  		u_a := utilization
   536  		u_g := gcGoalUtilization
   537  		W_a := c.scanWork
   538  		print("pacer: H_m_prev=", H_m_prev,
   539  			" h_t=", h_t, " H_T=", H_T,
   540  			" h_a=", h_a, " H_a=", H_a,
   541  			" h_g=", h_g, " H_g=", H_g,
   542  			" u_a=", u_a, " u_g=", u_g,
   543  			" W_a=", W_a,
   544  			" goalΔ=", goalGrowthRatio-h_t,
   545  			" actualΔ=", h_a-h_t,
   546  			" u_a/u_g=", u_a/u_g,
   547  			"\n")
   548  	}
   549  }
   550  
   551  // findRunnableGCWorker returns the background mark worker for _p_ if it
   552  // should be run. This must only be called when gcBlackenEnabled != 0.
   553  func (c *gcControllerState) findRunnableGCWorker(_p_ *p) *g {
   554  	if gcBlackenEnabled == 0 {
   555  		throw("gcControllerState.findRunnable: blackening not enabled")
   556  	}
   557  	if _p_.gcBgMarkWorker == nil {
   558  		throw("gcControllerState.findRunnable: no background mark worker")
   559  	}
   560  	if work.bgMark1.done != 0 && work.bgMark2.done != 0 {
   561  		// Background mark is done. Don't schedule background
   562  		// mark worker any more. (This is not just an
   563  		// optimization. Without this we can spin scheduling
   564  		// the background worker and having it return
   565  		// immediately with no work to do.)
   566  		return nil
   567  	}
   568  
   569  	decIfPositive := func(ptr *int64) bool {
   570  		if *ptr > 0 {
   571  			if xaddint64(ptr, -1) >= 0 {
   572  				return true
   573  			}
   574  			// We lost a race
   575  			xaddint64(ptr, +1)
   576  		}
   577  		return false
   578  	}
   579  
   580  	if decIfPositive(&c.dedicatedMarkWorkersNeeded) {
   581  		// This P is now dedicated to marking until the end of
   582  		// the concurrent mark phase.
   583  		_p_.gcMarkWorkerMode = gcMarkWorkerDedicatedMode
   584  		// TODO(austin): This P isn't going to run anything
   585  		// else for a while, so kick everything out of its run
   586  		// queue.
   587  	} else {
   588  		if _p_.gcw.wbuf == 0 && work.full == 0 && work.partial == 0 {
   589  			// No work to be done right now. This can
   590  			// happen at the end of the mark phase when
   591  			// there are still assists tapering off. Don't
   592  			// bother running background mark because
   593  			// it'll just return immediately.
   594  			if work.nwait == work.nproc {
   595  				// There are also no workers, which
   596  				// means we've reached a completion point.
   597  				// There may not be any workers to
   598  				// signal it, so signal it here.
   599  				readied := false
   600  				if gcBlackenPromptly {
   601  					if work.bgMark1.done == 0 {
   602  						throw("completing mark 2, but bgMark1.done == 0")
   603  					}
   604  					readied = work.bgMark2.complete()
   605  				} else {
   606  					readied = work.bgMark1.complete()
   607  				}
   608  				if readied {
   609  					// complete just called ready,
   610  					// but we're inside the
   611  					// scheduler. Let it know that
   612  					// that's okay.
   613  					resetspinning()
   614  				}
   615  			}
   616  			return nil
   617  		}
   618  		if !decIfPositive(&c.fractionalMarkWorkersNeeded) {
   619  			// No more workers are need right now.
   620  			return nil
   621  		}
   622  
   623  		// This P has picked the token for the fractional worker.
   624  		// Is the GC currently under or at the utilization goal?
   625  		// If so, do more work.
   626  		//
   627  		// We used to check whether doing one time slice of work
   628  		// would remain under the utilization goal, but that has the
   629  		// effect of delaying work until the mutator has run for
   630  		// enough time slices to pay for the work. During those time
   631  		// slices, write barriers are enabled, so the mutator is running slower.
   632  		// Now instead we do the work whenever we're under or at the
   633  		// utilization work and pay for it by letting the mutator run later.
   634  		// This doesn't change the overall utilization averages, but it
   635  		// front loads the GC work so that the GC finishes earlier and
   636  		// write barriers can be turned off sooner, effectively giving
   637  		// the mutator a faster machine.
   638  		//
   639  		// The old, slower behavior can be restored by setting
   640  		//	gcForcePreemptNS = forcePreemptNS.
   641  		const gcForcePreemptNS = 0
   642  
   643  		// TODO(austin): We could fast path this and basically
   644  		// eliminate contention on c.fractionalMarkWorkersNeeded by
   645  		// precomputing the minimum time at which it's worth
   646  		// next scheduling the fractional worker. Then Ps
   647  		// don't have to fight in the window where we've
   648  		// passed that deadline and no one has started the
   649  		// worker yet.
   650  		//
   651  		// TODO(austin): Shorter preemption interval for mark
   652  		// worker to improve fairness and give this
   653  		// finer-grained control over schedule?
   654  		now := nanotime() - gcController.bgMarkStartTime
   655  		then := now + gcForcePreemptNS
   656  		timeUsed := c.fractionalMarkTime + gcForcePreemptNS
   657  		if then > 0 && float64(timeUsed)/float64(then) > c.fractionalUtilizationGoal {
   658  			// Nope, we'd overshoot the utilization goal
   659  			xaddint64(&c.fractionalMarkWorkersNeeded, +1)
   660  			return nil
   661  		}
   662  		_p_.gcMarkWorkerMode = gcMarkWorkerFractionalMode
   663  	}
   664  
   665  	// Run the background mark worker
   666  	gp := _p_.gcBgMarkWorker
   667  	casgstatus(gp, _Gwaiting, _Grunnable)
   668  	if trace.enabled {
   669  		traceGoUnpark(gp, 0)
   670  	}
   671  	return gp
   672  }
   673  
   674  // gcGoalUtilization is the goal CPU utilization for background
   675  // marking as a fraction of GOMAXPROCS.
   676  const gcGoalUtilization = 0.25
   677  
   678  // gcBgCreditSlack is the amount of scan work credit background
   679  // scanning can accumulate locally before updating
   680  // gcController.bgScanCredit. Lower values give mutator assists more
   681  // accurate accounting of background scanning. Higher values reduce
   682  // memory contention.
   683  const gcBgCreditSlack = 2000
   684  
   685  // gcAssistTimeSlack is the nanoseconds of mutator assist time that
   686  // can accumulate on a P before updating gcController.assistTime.
   687  const gcAssistTimeSlack = 5000
   688  
   689  // Determine whether to initiate a GC.
   690  // If the GC is already working no need to trigger another one.
   691  // This should establish a feedback loop where if the GC does not
   692  // have sufficient time to complete then more memory will be
   693  // requested from the OS increasing heap size thus allow future
   694  // GCs more time to complete.
   695  // memstat.heap_live read has a benign race.
   696  // A false negative simple does not start a GC, a false positive
   697  // will start a GC needlessly. Neither have correctness issues.
   698  func shouldtriggergc() bool {
   699  	return memstats.heap_live >= memstats.next_gc && atomicloaduint(&bggc.working) == 0
   700  }
   701  
   702  // bgMarkSignal synchronizes the GC coordinator and background mark workers.
   703  type bgMarkSignal struct {
   704  	// Workers race to cas to 1. Winner signals coordinator.
   705  	done uint32
   706  	// Coordinator to wake up.
   707  	lock mutex
   708  	g    *g
   709  	wake bool
   710  }
   711  
   712  func (s *bgMarkSignal) wait() {
   713  	lock(&s.lock)
   714  	if s.wake {
   715  		// Wakeup already happened
   716  		unlock(&s.lock)
   717  	} else {
   718  		s.g = getg()
   719  		goparkunlock(&s.lock, "mark wait (idle)", traceEvGoBlock, 1)
   720  	}
   721  	s.wake = false
   722  	s.g = nil
   723  }
   724  
   725  // complete signals the completion of this phase of marking. This can
   726  // be called multiple times during a cycle; only the first call has
   727  // any effect.
   728  //
   729  // The caller should arrange to deschedule itself as soon as possible
   730  // after calling complete in order to let the coordinator goroutine
   731  // run.
   732  func (s *bgMarkSignal) complete() bool {
   733  	if cas(&s.done, 0, 1) {
   734  		// This is the first worker to reach this completion point.
   735  		// Signal the main GC goroutine.
   736  		lock(&s.lock)
   737  		if s.g == nil {
   738  			// It hasn't parked yet.
   739  			s.wake = true
   740  		} else {
   741  			ready(s.g, 0)
   742  		}
   743  		unlock(&s.lock)
   744  		return true
   745  	}
   746  	return false
   747  }
   748  
   749  func (s *bgMarkSignal) clear() {
   750  	s.done = 0
   751  }
   752  
   753  var work struct {
   754  	full  uint64 // lock-free list of full blocks workbuf
   755  	empty uint64 // lock-free list of empty blocks workbuf
   756  	// TODO(rlh): partial no longer used, remove. (issue #11922)
   757  	partial uint64                // lock-free list of partially filled blocks workbuf
   758  	pad0    [_CacheLineSize]uint8 // prevents false-sharing between full/empty and nproc/nwait
   759  	nproc   uint32
   760  	tstart  int64
   761  	nwait   uint32
   762  	ndone   uint32
   763  	alldone note
   764  	markfor *parfor
   765  
   766  	bgMarkReady note   // signal background mark worker has started
   767  	bgMarkDone  uint32 // cas to 1 when at a background mark completion point
   768  	// Background mark completion signaling
   769  
   770  	// Coordination for the 2 parts of the mark phase.
   771  	bgMark1 bgMarkSignal
   772  	bgMark2 bgMarkSignal
   773  
   774  	// Copy of mheap.allspans for marker or sweeper.
   775  	spans []*mspan
   776  
   777  	// totaltime is the CPU nanoseconds spent in GC since the
   778  	// program started if debug.gctrace > 0.
   779  	totaltime int64
   780  
   781  	// bytesMarked is the number of bytes marked this cycle. This
   782  	// includes bytes blackened in scanned objects, noscan objects
   783  	// that go straight to black, and permagrey objects scanned by
   784  	// markroot during the concurrent scan phase. This is updated
   785  	// atomically during the cycle. Updates may be batched
   786  	// arbitrarily, since the value is only read at the end of the
   787  	// cycle.
   788  	//
   789  	// Because of benign races during marking, this number may not
   790  	// be the exact number of marked bytes, but it should be very
   791  	// close.
   792  	bytesMarked uint64
   793  
   794  	// initialHeapLive is the value of memstats.heap_live at the
   795  	// beginning of this GC cycle.
   796  	initialHeapLive uint64
   797  }
   798  
   799  // GC runs a garbage collection and blocks the caller until the
   800  // garbage collection is complete. It may also block the entire
   801  // program.
   802  func GC() {
   803  	startGC(gcForceBlockMode, false)
   804  }
   805  
   806  const (
   807  	gcBackgroundMode = iota // concurrent GC
   808  	gcForceMode             // stop-the-world GC now
   809  	gcForceBlockMode        // stop-the-world GC now and wait for sweep
   810  )
   811  
   812  // startGC starts a GC cycle. If mode is gcBackgroundMode, this will
   813  // start GC in the background and return. Otherwise, this will block
   814  // until the new GC cycle is started and finishes. If forceTrigger is
   815  // true, it indicates that GC should be started regardless of the
   816  // current heap size.
   817  func startGC(mode int, forceTrigger bool) {
   818  	// The gc is turned off (via enablegc) until the bootstrap has completed.
   819  	// Also, malloc gets called in the guts of a number of libraries that might be
   820  	// holding locks. To avoid deadlocks during stop-the-world, don't bother
   821  	// trying to run gc while holding a lock. The next mallocgc without a lock
   822  	// will do the gc instead.
   823  	mp := acquirem()
   824  	if gp := getg(); gp == mp.g0 || mp.locks > 1 || mp.preemptoff != "" || !memstats.enablegc || panicking != 0 || gcpercent < 0 {
   825  		releasem(mp)
   826  		return
   827  	}
   828  	releasem(mp)
   829  	mp = nil
   830  
   831  	if debug.gcstoptheworld == 1 {
   832  		mode = gcForceMode
   833  	} else if debug.gcstoptheworld == 2 {
   834  		mode = gcForceBlockMode
   835  	}
   836  
   837  	if mode != gcBackgroundMode {
   838  		// special synchronous cases
   839  		gc(mode)
   840  		return
   841  	}
   842  
   843  	// trigger concurrent GC
   844  	readied := false
   845  	lock(&bggc.lock)
   846  	// The trigger was originally checked speculatively, so
   847  	// recheck that this really should trigger GC. (For example,
   848  	// we may have gone through a whole GC cycle since the
   849  	// speculative check.)
   850  	if !(forceTrigger || shouldtriggergc()) {
   851  		unlock(&bggc.lock)
   852  		return
   853  	}
   854  	if !bggc.started {
   855  		bggc.working = 1
   856  		bggc.started = true
   857  		readied = true
   858  		go backgroundgc()
   859  	} else if bggc.working == 0 {
   860  		bggc.working = 1
   861  		readied = true
   862  		ready(bggc.g, 0)
   863  	}
   864  	unlock(&bggc.lock)
   865  	if readied {
   866  		// This G just started or ready()d the GC goroutine.
   867  		// Switch directly to it by yielding.
   868  		Gosched()
   869  	}
   870  }
   871  
   872  // State of the background concurrent GC goroutine.
   873  var bggc struct {
   874  	lock    mutex
   875  	g       *g
   876  	working uint
   877  	started bool
   878  }
   879  
   880  // backgroundgc is running in a goroutine and does the concurrent GC work.
   881  // bggc holds the state of the backgroundgc.
   882  func backgroundgc() {
   883  	bggc.g = getg()
   884  	for {
   885  		gc(gcBackgroundMode)
   886  		lock(&bggc.lock)
   887  		bggc.working = 0
   888  		goparkunlock(&bggc.lock, "Concurrent GC wait", traceEvGoBlock, 1)
   889  	}
   890  }
   891  
   892  func gc(mode int) {
   893  	// Timing/utilization tracking
   894  	var stwprocs, maxprocs int32
   895  	var tSweepTerm, tScan, tInstallWB, tMark, tMarkTerm int64
   896  
   897  	// debug.gctrace variables
   898  	var heap0, heap1, heap2, heapGoal uint64
   899  
   900  	// memstats statistics
   901  	var now, pauseStart, pauseNS int64
   902  
   903  	// Ok, we're doing it!  Stop everybody else
   904  	semacquire(&worldsema, false)
   905  
   906  	// Pick up the remaining unswept/not being swept spans concurrently
   907  	//
   908  	// This shouldn't happen if we're being invoked in background
   909  	// mode since proportional sweep should have just finished
   910  	// sweeping everything, but rounding errors, etc, may leave a
   911  	// few spans unswept. In forced mode, this is necessary since
   912  	// GC can be forced at any point in the sweeping cycle.
   913  	for gosweepone() != ^uintptr(0) {
   914  		sweep.nbgsweep++
   915  	}
   916  
   917  	if trace.enabled {
   918  		traceGCStart()
   919  	}
   920  
   921  	if mode == gcBackgroundMode {
   922  		gcBgMarkStartWorkers()
   923  	}
   924  	now = nanotime()
   925  	stwprocs, maxprocs = gcprocs(), gomaxprocs
   926  	tSweepTerm = now
   927  	heap0 = memstats.heap_live
   928  
   929  	pauseStart = now
   930  	systemstack(stopTheWorldWithSema)
   931  	systemstack(finishsweep_m) // finish sweep before we start concurrent scan.
   932  	// clearpools before we start the GC. If we wait they memory will not be
   933  	// reclaimed until the next GC cycle.
   934  	clearpools()
   935  
   936  	gcResetMarkState()
   937  
   938  	if mode == gcBackgroundMode { // Do as much work concurrently as possible
   939  		gcController.startCycle()
   940  		heapGoal = gcController.heapGoal
   941  
   942  		systemstack(func() {
   943  			// Enter scan phase. This enables write
   944  			// barriers to track changes to stack frames
   945  			// above the stack barrier.
   946  			//
   947  			// TODO: This has evolved to the point where
   948  			// we carefully ensure invariants we no longer
   949  			// depend on. Either:
   950  			//
   951  			// 1) Enable full write barriers for the scan,
   952  			// but eliminate the ragged barrier below
   953  			// (since the start the world ensures all Ps
   954  			// have observed the write barrier enable) and
   955  			// consider draining during the scan.
   956  			//
   957  			// 2) Only enable write barriers for writes to
   958  			// the stack at this point, and then enable
   959  			// write barriers for heap writes when we
   960  			// enter the mark phase. This means we cannot
   961  			// drain in the scan phase and must perform a
   962  			// ragged barrier to ensure all Ps have
   963  			// enabled heap write barriers before we drain
   964  			// or enable assists.
   965  			//
   966  			// 3) Don't install stack barriers over frame
   967  			// boundaries where there are up-pointers.
   968  			setGCPhase(_GCscan)
   969  
   970  			gcBgMarkPrepare() // Must happen before assist enable.
   971  
   972  			// At this point all Ps have enabled the write
   973  			// barrier, thus maintaining the no white to
   974  			// black invariant. Enable mutator assists to
   975  			// put back-pressure on fast allocating
   976  			// mutators.
   977  			atomicstore(&gcBlackenEnabled, 1)
   978  
   979  			// Concurrent scan.
   980  			startTheWorldWithSema()
   981  			now = nanotime()
   982  			pauseNS += now - pauseStart
   983  			tScan = now
   984  			gcController.assistStartTime = now
   985  			gcscan_m()
   986  
   987  			// Enter mark phase.
   988  			tInstallWB = nanotime()
   989  			setGCPhase(_GCmark)
   990  			// Ensure all Ps have observed the phase
   991  			// change and have write barriers enabled
   992  			// before any blackening occurs.
   993  			forEachP(func(*p) {})
   994  		})
   995  		// Concurrent mark.
   996  		tMark = nanotime()
   997  
   998  		// Enable background mark workers and wait for
   999  		// background mark completion.
  1000  		gcController.bgMarkStartTime = nanotime()
  1001  		work.bgMark1.clear()
  1002  		work.bgMark1.wait()
  1003  
  1004  		// The global work list is empty, but there can still be work
  1005  		// sitting in the per-P work caches and there can be more
  1006  		// objects reachable from global roots since they don't have write
  1007  		// barriers. Rescan some roots and flush work caches.
  1008  		systemstack(func() {
  1009  			// rescan global data and bss.
  1010  			markroot(nil, _RootData)
  1011  			markroot(nil, _RootBss)
  1012  
  1013  			// Disallow caching workbufs.
  1014  			gcBlackenPromptly = true
  1015  
  1016  			// Flush all currently cached workbufs. This
  1017  			// also forces any remaining background
  1018  			// workers out of their loop.
  1019  			forEachP(func(_p_ *p) {
  1020  				_p_.gcw.dispose()
  1021  			})
  1022  		})
  1023  
  1024  		// Wait for this more aggressive background mark to complete.
  1025  		work.bgMark2.clear()
  1026  		work.bgMark2.wait()
  1027  
  1028  		// Begin mark termination.
  1029  		now = nanotime()
  1030  		tMarkTerm = now
  1031  		pauseStart = now
  1032  		systemstack(stopTheWorldWithSema)
  1033  		// The gcphase is _GCmark, it will transition to _GCmarktermination
  1034  		// below. The important thing is that the wb remains active until
  1035  		// all marking is complete. This includes writes made by the GC.
  1036  
  1037  		// Flush the gcWork caches. This must be done before
  1038  		// endCycle since endCycle depends on statistics kept
  1039  		// in these caches.
  1040  		gcFlushGCWork()
  1041  
  1042  		gcController.endCycle()
  1043  	} else {
  1044  		// For non-concurrent GC (mode != gcBackgroundMode)
  1045  		// The g stacks have not been scanned so clear g state
  1046  		// such that mark termination scans all stacks.
  1047  		gcResetGState()
  1048  
  1049  		t := nanotime()
  1050  		tScan, tInstallWB, tMark, tMarkTerm = t, t, t, t
  1051  		heapGoal = heap0
  1052  	}
  1053  
  1054  	// World is stopped.
  1055  	// Start marktermination which includes enabling the write barrier.
  1056  	atomicstore(&gcBlackenEnabled, 0)
  1057  	gcBlackenPromptly = false
  1058  	setGCPhase(_GCmarktermination)
  1059  
  1060  	heap1 = memstats.heap_live
  1061  	startTime := nanotime()
  1062  
  1063  	mp := acquirem()
  1064  	mp.preemptoff = "gcing"
  1065  	_g_ := getg()
  1066  	_g_.m.traceback = 2
  1067  	gp := _g_.m.curg
  1068  	casgstatus(gp, _Grunning, _Gwaiting)
  1069  	gp.waitreason = "garbage collection"
  1070  
  1071  	// Run gc on the g0 stack.  We do this so that the g stack
  1072  	// we're currently running on will no longer change.  Cuts
  1073  	// the root set down a bit (g0 stacks are not scanned, and
  1074  	// we don't need to scan gc's internal state).  We also
  1075  	// need to switch to g0 so we can shrink the stack.
  1076  	systemstack(func() {
  1077  		gcMark(startTime)
  1078  		// Must return immediately.
  1079  		// The outer function's stack may have moved
  1080  		// during gcMark (it shrinks stacks, including the
  1081  		// outer function's stack), so we must not refer
  1082  		// to any of its variables. Return back to the
  1083  		// non-system stack to pick up the new addresses
  1084  		// before continuing.
  1085  	})
  1086  
  1087  	systemstack(func() {
  1088  		heap2 = work.bytesMarked
  1089  		if debug.gccheckmark > 0 {
  1090  			// Run a full stop-the-world mark using checkmark bits,
  1091  			// to check that we didn't forget to mark anything during
  1092  			// the concurrent mark process.
  1093  			gcResetGState() // Rescan stacks
  1094  			gcResetMarkState()
  1095  			initCheckmarks()
  1096  			gcMark(startTime)
  1097  			clearCheckmarks()
  1098  		}
  1099  
  1100  		// marking is complete so we can turn the write barrier off
  1101  		setGCPhase(_GCoff)
  1102  		gcSweep(mode)
  1103  
  1104  		if debug.gctrace > 1 {
  1105  			startTime = nanotime()
  1106  			// The g stacks have been scanned so
  1107  			// they have gcscanvalid==true and gcworkdone==true.
  1108  			// Reset these so that all stacks will be rescanned.
  1109  			gcResetGState()
  1110  			gcResetMarkState()
  1111  			finishsweep_m()
  1112  
  1113  			// Still in STW but gcphase is _GCoff, reset to _GCmarktermination
  1114  			// At this point all objects will be found during the gcMark which
  1115  			// does a complete STW mark and object scan.
  1116  			setGCPhase(_GCmarktermination)
  1117  			gcMark(startTime)
  1118  			setGCPhase(_GCoff) // marking is done, turn off wb.
  1119  			gcSweep(mode)
  1120  		}
  1121  	})
  1122  
  1123  	_g_.m.traceback = 0
  1124  	casgstatus(gp, _Gwaiting, _Grunning)
  1125  
  1126  	if trace.enabled {
  1127  		traceGCDone()
  1128  	}
  1129  
  1130  	// all done
  1131  	mp.preemptoff = ""
  1132  
  1133  	if gcphase != _GCoff {
  1134  		throw("gc done but gcphase != _GCoff")
  1135  	}
  1136  
  1137  	// Update timing memstats
  1138  	now, unixNow := nanotime(), unixnanotime()
  1139  	pauseNS += now - pauseStart
  1140  	atomicstore64(&memstats.last_gc, uint64(unixNow)) // must be Unix time to make sense to user
  1141  	memstats.pause_ns[memstats.numgc%uint32(len(memstats.pause_ns))] = uint64(pauseNS)
  1142  	memstats.pause_end[memstats.numgc%uint32(len(memstats.pause_end))] = uint64(unixNow)
  1143  	memstats.pause_total_ns += uint64(pauseNS)
  1144  
  1145  	// Update work.totaltime.
  1146  	sweepTermCpu := int64(stwprocs) * (tScan - tSweepTerm)
  1147  	scanCpu := tInstallWB - tScan
  1148  	installWBCpu := int64(0)
  1149  	// We report idle marking time below, but omit it from the
  1150  	// overall utilization here since it's "free".
  1151  	markCpu := gcController.assistTime + gcController.dedicatedMarkTime + gcController.fractionalMarkTime
  1152  	markTermCpu := int64(stwprocs) * (now - tMarkTerm)
  1153  	cycleCpu := sweepTermCpu + scanCpu + installWBCpu + markCpu + markTermCpu
  1154  	work.totaltime += cycleCpu
  1155  
  1156  	// Compute overall GC CPU utilization.
  1157  	totalCpu := sched.totaltime + (now-sched.procresizetime)*int64(gomaxprocs)
  1158  	memstats.gc_cpu_fraction = float64(work.totaltime) / float64(totalCpu)
  1159  
  1160  	memstats.numgc++
  1161  
  1162  	systemstack(startTheWorldWithSema)
  1163  	semrelease(&worldsema)
  1164  
  1165  	releasem(mp)
  1166  	mp = nil
  1167  
  1168  	if debug.gctrace > 0 {
  1169  		tEnd := now
  1170  		util := int(memstats.gc_cpu_fraction * 100)
  1171  
  1172  		var sbuf [24]byte
  1173  		printlock()
  1174  		print("gc ", memstats.numgc,
  1175  			" @", string(itoaDiv(sbuf[:], uint64(tSweepTerm-runtimeInitTime)/1e6, 3)), "s ",
  1176  			util, "%: ")
  1177  		prev := tSweepTerm
  1178  		for i, ns := range []int64{tScan, tInstallWB, tMark, tMarkTerm, tEnd} {
  1179  			if i != 0 {
  1180  				print("+")
  1181  			}
  1182  			print(string(fmtNSAsMS(sbuf[:], uint64(ns-prev))))
  1183  			prev = ns
  1184  		}
  1185  		print(" ms clock, ")
  1186  		for i, ns := range []int64{sweepTermCpu, scanCpu, installWBCpu, gcController.assistTime, gcController.dedicatedMarkTime + gcController.fractionalMarkTime, gcController.idleMarkTime, markTermCpu} {
  1187  			if i == 4 || i == 5 {
  1188  				// Separate mark time components with /.
  1189  				print("/")
  1190  			} else if i != 0 {
  1191  				print("+")
  1192  			}
  1193  			print(string(fmtNSAsMS(sbuf[:], uint64(ns))))
  1194  		}
  1195  		print(" ms cpu, ",
  1196  			heap0>>20, "->", heap1>>20, "->", heap2>>20, " MB, ",
  1197  			heapGoal>>20, " MB goal, ",
  1198  			maxprocs, " P")
  1199  		if mode != gcBackgroundMode {
  1200  			print(" (forced)")
  1201  		}
  1202  		print("\n")
  1203  		printunlock()
  1204  	}
  1205  	sweep.nbgsweep = 0
  1206  	sweep.npausesweep = 0
  1207  
  1208  	// now that gc is done, kick off finalizer thread if needed
  1209  	if !concurrentSweep {
  1210  		// give the queued finalizers, if any, a chance to run
  1211  		Gosched()
  1212  	}
  1213  }
  1214  
  1215  // gcBgMarkStartWorkers prepares background mark worker goroutines.
  1216  // These goroutines will not run until the mark phase, but they must
  1217  // be started while the work is not stopped and from a regular G
  1218  // stack. The caller must hold worldsema.
  1219  func gcBgMarkStartWorkers() {
  1220  	// Background marking is performed by per-P G's. Ensure that
  1221  	// each P has a background GC G.
  1222  	for _, p := range &allp {
  1223  		if p == nil || p.status == _Pdead {
  1224  			break
  1225  		}
  1226  		if p.gcBgMarkWorker == nil {
  1227  			go gcBgMarkWorker(p)
  1228  			notetsleepg(&work.bgMarkReady, -1)
  1229  			noteclear(&work.bgMarkReady)
  1230  		}
  1231  	}
  1232  }
  1233  
  1234  // gcBgMarkPrepare sets up state for background marking.
  1235  // Mutator assists must not yet be enabled.
  1236  func gcBgMarkPrepare() {
  1237  	// Background marking will stop when the work queues are empty
  1238  	// and there are no more workers (note that, since this is
  1239  	// concurrent, this may be a transient state, but mark
  1240  	// termination will clean it up). Between background workers
  1241  	// and assists, we don't really know how many workers there
  1242  	// will be, so we pretend to have an arbitrarily large number
  1243  	// of workers, almost all of which are "waiting". While a
  1244  	// worker is working it decrements nwait. If nproc == nwait,
  1245  	// there are no workers.
  1246  	work.nproc = ^uint32(0)
  1247  	work.nwait = ^uint32(0)
  1248  
  1249  	// Reset background mark completion points.
  1250  	work.bgMark1.done = 1
  1251  	work.bgMark2.done = 1
  1252  }
  1253  
  1254  func gcBgMarkWorker(p *p) {
  1255  	// Register this G as the background mark worker for p.
  1256  	if p.gcBgMarkWorker != nil {
  1257  		throw("P already has a background mark worker")
  1258  	}
  1259  	gp := getg()
  1260  
  1261  	mp := acquirem()
  1262  	p.gcBgMarkWorker = gp
  1263  	// After this point, the background mark worker is scheduled
  1264  	// cooperatively by gcController.findRunnable. Hence, it must
  1265  	// never be preempted, as this would put it into _Grunnable
  1266  	// and put it on a run queue. Instead, when the preempt flag
  1267  	// is set, this puts itself into _Gwaiting to be woken up by
  1268  	// gcController.findRunnable at the appropriate time.
  1269  	notewakeup(&work.bgMarkReady)
  1270  	for {
  1271  		// Go to sleep until woken by gcContoller.findRunnable.
  1272  		// We can't releasem yet since even the call to gopark
  1273  		// may be preempted.
  1274  		gopark(func(g *g, mp unsafe.Pointer) bool {
  1275  			releasem((*m)(mp))
  1276  			return true
  1277  		}, unsafe.Pointer(mp), "mark worker (idle)", traceEvGoBlock, 0)
  1278  
  1279  		// Loop until the P dies and disassociates this
  1280  		// worker. (The P may later be reused, in which case
  1281  		// it will get a new worker.)
  1282  		if p.gcBgMarkWorker != gp {
  1283  			break
  1284  		}
  1285  
  1286  		// Disable preemption so we can use the gcw. If the
  1287  		// scheduler wants to preempt us, we'll stop draining,
  1288  		// dispose the gcw, and then preempt.
  1289  		mp = acquirem()
  1290  
  1291  		if gcBlackenEnabled == 0 {
  1292  			throw("gcBgMarkWorker: blackening not enabled")
  1293  		}
  1294  
  1295  		startTime := nanotime()
  1296  
  1297  		decnwait := xadd(&work.nwait, -1)
  1298  		if decnwait == work.nproc {
  1299  			println("runtime: work.nwait=", decnwait, "work.nproc=", work.nproc)
  1300  			throw("work.nwait was > work.nproc")
  1301  		}
  1302  
  1303  		done := false
  1304  		switch p.gcMarkWorkerMode {
  1305  		default:
  1306  			throw("gcBgMarkWorker: unexpected gcMarkWorkerMode")
  1307  		case gcMarkWorkerDedicatedMode:
  1308  			gcDrain(&p.gcw, gcBgCreditSlack)
  1309  			// gcDrain did the xadd(&work.nwait +1) to
  1310  			// match the decrement above. It only returns
  1311  			// at a mark completion point.
  1312  			done = true
  1313  			if !p.gcw.empty() {
  1314  				throw("gcDrain returned with buffer")
  1315  			}
  1316  		case gcMarkWorkerFractionalMode, gcMarkWorkerIdleMode:
  1317  			gcDrainUntilPreempt(&p.gcw, gcBgCreditSlack)
  1318  
  1319  			// If we are nearing the end of mark, dispose
  1320  			// of the cache promptly. We must do this
  1321  			// before signaling that we're no longer
  1322  			// working so that other workers can't observe
  1323  			// no workers and no work while we have this
  1324  			// cached, and before we compute done.
  1325  			if gcBlackenPromptly {
  1326  				p.gcw.dispose()
  1327  			}
  1328  
  1329  			// Was this the last worker and did we run out
  1330  			// of work?
  1331  			incnwait := xadd(&work.nwait, +1)
  1332  			if incnwait > work.nproc {
  1333  				println("runtime: p.gcMarkWorkerMode=", p.gcMarkWorkerMode,
  1334  					"work.nwait=", incnwait, "work.nproc=", work.nproc)
  1335  				throw("work.nwait > work.nproc")
  1336  			}
  1337  			done = incnwait == work.nproc && work.full == 0 && work.partial == 0
  1338  		}
  1339  
  1340  		// If this worker reached a background mark completion
  1341  		// point, signal the main GC goroutine.
  1342  		if done {
  1343  			if gcBlackenPromptly {
  1344  				if work.bgMark1.done == 0 {
  1345  					throw("completing mark 2, but bgMark1.done == 0")
  1346  				}
  1347  				work.bgMark2.complete()
  1348  			} else {
  1349  				work.bgMark1.complete()
  1350  			}
  1351  		}
  1352  
  1353  		duration := nanotime() - startTime
  1354  		switch p.gcMarkWorkerMode {
  1355  		case gcMarkWorkerDedicatedMode:
  1356  			xaddint64(&gcController.dedicatedMarkTime, duration)
  1357  			xaddint64(&gcController.dedicatedMarkWorkersNeeded, 1)
  1358  		case gcMarkWorkerFractionalMode:
  1359  			xaddint64(&gcController.fractionalMarkTime, duration)
  1360  			xaddint64(&gcController.fractionalMarkWorkersNeeded, 1)
  1361  		case gcMarkWorkerIdleMode:
  1362  			xaddint64(&gcController.idleMarkTime, duration)
  1363  		}
  1364  	}
  1365  }
  1366  
  1367  // gcMarkWorkAvailable returns true if executing a mark worker
  1368  // on p is potentially useful.
  1369  func gcMarkWorkAvailable(p *p) bool {
  1370  	if !p.gcw.empty() {
  1371  		return true
  1372  	}
  1373  	if atomicload64(&work.full) != 0 || atomicload64(&work.partial) != 0 {
  1374  		return true // global work available
  1375  	}
  1376  	return false
  1377  }
  1378  
  1379  // gcFlushGCWork disposes the gcWork caches of all Ps. The world must
  1380  // be stopped.
  1381  //go:nowritebarrier
  1382  func gcFlushGCWork() {
  1383  	// Gather all cached GC work. All other Ps are stopped, so
  1384  	// it's safe to manipulate their GC work caches.
  1385  	for i := 0; i < int(gomaxprocs); i++ {
  1386  		allp[i].gcw.dispose()
  1387  	}
  1388  }
  1389  
  1390  // gcMark runs the mark (or, for concurrent GC, mark termination)
  1391  // STW is in effect at this point.
  1392  //TODO go:nowritebarrier
  1393  func gcMark(start_time int64) {
  1394  	if debug.allocfreetrace > 0 {
  1395  		tracegc()
  1396  	}
  1397  
  1398  	if gcphase != _GCmarktermination {
  1399  		throw("in gcMark expecting to see gcphase as _GCmarktermination")
  1400  	}
  1401  	work.tstart = start_time
  1402  
  1403  	gcCopySpans() // TODO(rlh): should this be hoisted and done only once? Right now it is done for normal marking and also for checkmarking.
  1404  
  1405  	// Make sure the per-P gcWork caches are empty. During mark
  1406  	// termination, these caches can still be used temporarily,
  1407  	// but must be disposed to the global lists immediately.
  1408  	gcFlushGCWork()
  1409  
  1410  	work.nwait = 0
  1411  	work.ndone = 0
  1412  	work.nproc = uint32(gcprocs())
  1413  
  1414  	if trace.enabled {
  1415  		traceGCScanStart()
  1416  	}
  1417  
  1418  	parforsetup(work.markfor, work.nproc, uint32(_RootCount+allglen), false, markroot)
  1419  	if work.nproc > 1 {
  1420  		noteclear(&work.alldone)
  1421  		helpgc(int32(work.nproc))
  1422  	}
  1423  
  1424  	gchelperstart()
  1425  	parfordo(work.markfor)
  1426  
  1427  	var gcw gcWork
  1428  	gcDrain(&gcw, -1)
  1429  	gcw.dispose()
  1430  
  1431  	if work.full != 0 {
  1432  		throw("work.full != 0")
  1433  	}
  1434  	if work.partial != 0 {
  1435  		throw("work.partial != 0")
  1436  	}
  1437  
  1438  	if work.nproc > 1 {
  1439  		notesleep(&work.alldone)
  1440  	}
  1441  
  1442  	for i := 0; i < int(gomaxprocs); i++ {
  1443  		if allp[i].gcw.wbuf != 0 {
  1444  			throw("P has cached GC work at end of mark termination")
  1445  		}
  1446  	}
  1447  
  1448  	if trace.enabled {
  1449  		traceGCScanDone()
  1450  	}
  1451  
  1452  	// TODO(austin): This doesn't have to be done during STW, as
  1453  	// long as we block the next GC cycle until this is done. Move
  1454  	// it after we start the world, but before dropping worldsema.
  1455  	// (See issue #11465.)
  1456  	freeStackSpans()
  1457  
  1458  	cachestats()
  1459  
  1460  	// Compute the reachable heap size at the beginning of the
  1461  	// cycle. This is approximately the marked heap size at the
  1462  	// end (which we know) minus the amount of marked heap that
  1463  	// was allocated after marking began (which we don't know, but
  1464  	// is approximately the amount of heap that was allocated
  1465  	// since marking began).
  1466  	allocatedDuringCycle := memstats.heap_live - work.initialHeapLive
  1467  	if work.bytesMarked >= allocatedDuringCycle {
  1468  		memstats.heap_reachable = work.bytesMarked - allocatedDuringCycle
  1469  	} else {
  1470  		// This can happen if most of the allocation during
  1471  		// the cycle never became reachable from the heap.
  1472  		// Just set the reachable heap approximation to 0 and
  1473  		// let the heapminimum kick in below.
  1474  		memstats.heap_reachable = 0
  1475  	}
  1476  
  1477  	// Trigger the next GC cycle when the allocated heap has grown
  1478  	// by triggerRatio over the reachable heap size. Assume that
  1479  	// we're in steady state, so the reachable heap size is the
  1480  	// same now as it was at the beginning of the GC cycle.
  1481  	memstats.next_gc = uint64(float64(memstats.heap_reachable) * (1 + gcController.triggerRatio))
  1482  	if memstats.next_gc < heapminimum {
  1483  		memstats.next_gc = heapminimum
  1484  	}
  1485  	if int64(memstats.next_gc) < 0 {
  1486  		print("next_gc=", memstats.next_gc, " bytesMarked=", work.bytesMarked, " heap_live=", memstats.heap_live, " initialHeapLive=", work.initialHeapLive, "\n")
  1487  		throw("next_gc underflow")
  1488  	}
  1489  
  1490  	// Update other GC heap size stats.
  1491  	memstats.heap_live = work.bytesMarked
  1492  	memstats.heap_marked = work.bytesMarked
  1493  	memstats.heap_scan = uint64(gcController.scanWork)
  1494  
  1495  	minNextGC := memstats.heap_live + sweepMinHeapDistance*uint64(gcpercent)/100
  1496  	if memstats.next_gc < minNextGC {
  1497  		// The allocated heap is already past the trigger.
  1498  		// This can happen if the triggerRatio is very low and
  1499  		// the reachable heap estimate is less than the live
  1500  		// heap size.
  1501  		//
  1502  		// Concurrent sweep happens in the heap growth from
  1503  		// heap_live to next_gc, so bump next_gc up to ensure
  1504  		// that concurrent sweep has some heap growth in which
  1505  		// to perform sweeping before we start the next GC
  1506  		// cycle.
  1507  		memstats.next_gc = minNextGC
  1508  	}
  1509  
  1510  	if trace.enabled {
  1511  		traceHeapAlloc()
  1512  		traceNextGC()
  1513  	}
  1514  }
  1515  
  1516  func gcSweep(mode int) {
  1517  	if gcphase != _GCoff {
  1518  		throw("gcSweep being done but phase is not GCoff")
  1519  	}
  1520  	gcCopySpans()
  1521  
  1522  	lock(&mheap_.lock)
  1523  	mheap_.sweepgen += 2
  1524  	mheap_.sweepdone = 0
  1525  	sweep.spanidx = 0
  1526  	unlock(&mheap_.lock)
  1527  
  1528  	if !_ConcurrentSweep || mode == gcForceBlockMode {
  1529  		// Special case synchronous sweep.
  1530  		// Record that no proportional sweeping has to happen.
  1531  		lock(&mheap_.lock)
  1532  		mheap_.sweepPagesPerByte = 0
  1533  		mheap_.pagesSwept = 0
  1534  		unlock(&mheap_.lock)
  1535  		// Sweep all spans eagerly.
  1536  		for sweepone() != ^uintptr(0) {
  1537  			sweep.npausesweep++
  1538  		}
  1539  		// Do an additional mProf_GC, because all 'free' events are now real as well.
  1540  		mProf_GC()
  1541  		mProf_GC()
  1542  		return
  1543  	}
  1544  
  1545  	// Account how much sweeping needs to be done before the next
  1546  	// GC cycle and set up proportional sweep statistics.
  1547  	var pagesToSweep uintptr
  1548  	for _, s := range work.spans {
  1549  		if s.state == mSpanInUse {
  1550  			pagesToSweep += s.npages
  1551  		}
  1552  	}
  1553  	heapDistance := int64(memstats.next_gc) - int64(memstats.heap_live)
  1554  	// Add a little margin so rounding errors and concurrent
  1555  	// sweep are less likely to leave pages unswept when GC starts.
  1556  	heapDistance -= 1024 * 1024
  1557  	if heapDistance < _PageSize {
  1558  		// Avoid setting the sweep ratio extremely high
  1559  		heapDistance = _PageSize
  1560  	}
  1561  	lock(&mheap_.lock)
  1562  	mheap_.sweepPagesPerByte = float64(pagesToSweep) / float64(heapDistance)
  1563  	mheap_.pagesSwept = 0
  1564  	mheap_.spanBytesAlloc = 0
  1565  	unlock(&mheap_.lock)
  1566  
  1567  	// Background sweep.
  1568  	lock(&sweep.lock)
  1569  	if sweep.parked {
  1570  		sweep.parked = false
  1571  		ready(sweep.g, 0)
  1572  	}
  1573  	unlock(&sweep.lock)
  1574  	mProf_GC()
  1575  }
  1576  
  1577  func gcCopySpans() {
  1578  	// Cache runtime.mheap_.allspans in work.spans to avoid conflicts with
  1579  	// resizing/freeing allspans.
  1580  	// New spans can be created while GC progresses, but they are not garbage for
  1581  	// this round:
  1582  	//  - new stack spans can be created even while the world is stopped.
  1583  	//  - new malloc spans can be created during the concurrent sweep
  1584  	// Even if this is stop-the-world, a concurrent exitsyscall can allocate a stack from heap.
  1585  	lock(&mheap_.lock)
  1586  	// Free the old cached mark array if necessary.
  1587  	if work.spans != nil && &work.spans[0] != &h_allspans[0] {
  1588  		sysFree(unsafe.Pointer(&work.spans[0]), uintptr(len(work.spans))*unsafe.Sizeof(work.spans[0]), &memstats.other_sys)
  1589  	}
  1590  	// Cache the current array for sweeping.
  1591  	mheap_.gcspans = mheap_.allspans
  1592  	work.spans = h_allspans
  1593  	unlock(&mheap_.lock)
  1594  }
  1595  
  1596  // gcResetGState resets the GC state of all G's and returns the length
  1597  // of allgs.
  1598  func gcResetGState() (numgs int) {
  1599  	// This may be called during a concurrent phase, so make sure
  1600  	// allgs doesn't change.
  1601  	lock(&allglock)
  1602  	for _, gp := range allgs {
  1603  		gp.gcscandone = false  // set to true in gcphasework
  1604  		gp.gcscanvalid = false // stack has not been scanned
  1605  		gp.gcalloc = 0
  1606  		gp.gcscanwork = 0
  1607  	}
  1608  	numgs = len(allgs)
  1609  	unlock(&allglock)
  1610  	return
  1611  }
  1612  
  1613  // gcResetMarkState resets state prior to marking (concurrent or STW).
  1614  //
  1615  // TODO(austin): Merge with gcResetGState. See issue #11427.
  1616  func gcResetMarkState() {
  1617  	work.bytesMarked = 0
  1618  	work.initialHeapLive = memstats.heap_live
  1619  }
  1620  
  1621  // Hooks for other packages
  1622  
  1623  var poolcleanup func()
  1624  
  1625  //go:linkname sync_runtime_registerPoolCleanup sync.runtime_registerPoolCleanup
  1626  func sync_runtime_registerPoolCleanup(f func()) {
  1627  	poolcleanup = f
  1628  }
  1629  
  1630  func clearpools() {
  1631  	// clear sync.Pools
  1632  	if poolcleanup != nil {
  1633  		poolcleanup()
  1634  	}
  1635  
  1636  	// Clear central sudog cache.
  1637  	// Leave per-P caches alone, they have strictly bounded size.
  1638  	// Disconnect cached list before dropping it on the floor,
  1639  	// so that a dangling ref to one entry does not pin all of them.
  1640  	lock(&sched.sudoglock)
  1641  	var sg, sgnext *sudog
  1642  	for sg = sched.sudogcache; sg != nil; sg = sgnext {
  1643  		sgnext = sg.next
  1644  		sg.next = nil
  1645  	}
  1646  	sched.sudogcache = nil
  1647  	unlock(&sched.sudoglock)
  1648  
  1649  	// Clear central defer pools.
  1650  	// Leave per-P pools alone, they have strictly bounded size.
  1651  	lock(&sched.deferlock)
  1652  	for i := range sched.deferpool {
  1653  		// disconnect cached list before dropping it on the floor,
  1654  		// so that a dangling ref to one entry does not pin all of them.
  1655  		var d, dlink *_defer
  1656  		for d = sched.deferpool[i]; d != nil; d = dlink {
  1657  			dlink = d.link
  1658  			d.link = nil
  1659  		}
  1660  		sched.deferpool[i] = nil
  1661  	}
  1662  	unlock(&sched.deferlock)
  1663  
  1664  	for _, p := range &allp {
  1665  		if p == nil {
  1666  			break
  1667  		}
  1668  		// clear tinyalloc pool
  1669  		if c := p.mcache; c != nil {
  1670  			c.tiny = nil
  1671  			c.tinyoffset = 0
  1672  		}
  1673  	}
  1674  }
  1675  
  1676  // Timing
  1677  
  1678  //go:nowritebarrier
  1679  func gchelper() {
  1680  	_g_ := getg()
  1681  	_g_.m.traceback = 2
  1682  	gchelperstart()
  1683  
  1684  	if trace.enabled {
  1685  		traceGCScanStart()
  1686  	}
  1687  
  1688  	// parallel mark for over GC roots
  1689  	parfordo(work.markfor)
  1690  	if gcphase != _GCscan {
  1691  		var gcw gcWork
  1692  		gcDrain(&gcw, -1) // blocks in getfull
  1693  		gcw.dispose()
  1694  	}
  1695  
  1696  	if trace.enabled {
  1697  		traceGCScanDone()
  1698  	}
  1699  
  1700  	nproc := work.nproc // work.nproc can change right after we increment work.ndone
  1701  	if xadd(&work.ndone, +1) == nproc-1 {
  1702  		notewakeup(&work.alldone)
  1703  	}
  1704  	_g_.m.traceback = 0
  1705  }
  1706  
  1707  func gchelperstart() {
  1708  	_g_ := getg()
  1709  
  1710  	if _g_.m.helpgc < 0 || _g_.m.helpgc >= _MaxGcproc {
  1711  		throw("gchelperstart: bad m->helpgc")
  1712  	}
  1713  	if _g_ != _g_.m.g0 {
  1714  		throw("gchelper not running on g0 stack")
  1715  	}
  1716  }
  1717  
  1718  // itoaDiv formats val/(10**dec) into buf.
  1719  func itoaDiv(buf []byte, val uint64, dec int) []byte {
  1720  	i := len(buf) - 1
  1721  	idec := i - dec
  1722  	for val >= 10 || i >= idec {
  1723  		buf[i] = byte(val%10 + '0')
  1724  		i--
  1725  		if i == idec {
  1726  			buf[i] = '.'
  1727  			i--
  1728  		}
  1729  		val /= 10
  1730  	}
  1731  	buf[i] = byte(val + '0')
  1732  	return buf[i:]
  1733  }
  1734  
  1735  // fmtNSAsMS nicely formats ns nanoseconds as milliseconds.
  1736  func fmtNSAsMS(buf []byte, ns uint64) []byte {
  1737  	if ns >= 10e6 {
  1738  		// Format as whole milliseconds.
  1739  		return itoaDiv(buf, ns/1e6, 0)
  1740  	}
  1741  	// Format two digits of precision, with at most three decimal places.
  1742  	x := ns / 1e3
  1743  	if x == 0 {
  1744  		buf[0] = '0'
  1745  		return buf[:1]
  1746  	}
  1747  	dec := 3
  1748  	for x >= 100 {
  1749  		x /= 10
  1750  		dec--
  1751  	}
  1752  	return itoaDiv(buf, x, dec)
  1753  }