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