Source file src/runtime/mgc.go

Documentation: runtime

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

View as plain text