Source file src/runtime/mgc.go

     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 gcController.heapGoal variable). This keeps the GC cost in
   117  // linear proportion to the allocation cost. Adjusting GOGC just changes the linear constant
   118  // (and also the amount of extra memory used).
   119  
   120  // Oblets
   121  //
   122  // In order to prevent long pauses while scanning large objects and to
   123  // improve parallelism, the garbage collector breaks up scan jobs for
   124  // objects larger than maxObletBytes into "oblets" of at most
   125  // maxObletBytes. When scanning encounters the beginning of a large
   126  // object, it scans only the first oblet and enqueues the remaining
   127  // oblets as new scan jobs.
   128  
   129  package runtime
   130  
   131  import (
   132  	"internal/cpu"
   133  	"runtime/internal/atomic"
   134  	"unsafe"
   135  )
   136  
   137  const (
   138  	_DebugGC         = 0
   139  	_ConcurrentSweep = true
   140  	_FinBlockSize    = 4 * 1024
   141  
   142  	// debugScanConservative enables debug logging for stack
   143  	// frames that are scanned conservatively.
   144  	debugScanConservative = false
   145  
   146  	// sweepMinHeapDistance is a lower bound on the heap distance
   147  	// (in bytes) reserved for concurrent sweeping between GC
   148  	// cycles.
   149  	sweepMinHeapDistance = 1024 * 1024
   150  )
   151  
   152  func gcinit() {
   153  	if unsafe.Sizeof(workbuf{}) != _WorkbufSize {
   154  		throw("size of Workbuf is suboptimal")
   155  	}
   156  	// No sweep on the first cycle.
   157  	sweep.active.state.Store(sweepDrainedMask)
   158  
   159  	// Initialize GC pacer state.
   160  	// Use the environment variable GOGC for the initial gcPercent value.
   161  	gcController.init(readGOGC())
   162  
   163  	work.startSema = 1
   164  	work.markDoneSema = 1
   165  	lockInit(&work.sweepWaiters.lock, lockRankSweepWaiters)
   166  	lockInit(&work.assistQueue.lock, lockRankAssistQueue)
   167  	lockInit(&work.wbufSpans.lock, lockRankWbufSpans)
   168  }
   169  
   170  // gcenable is called after the bulk of the runtime initialization,
   171  // just before we're about to start letting user code run.
   172  // It kicks off the background sweeper goroutine, the background
   173  // scavenger goroutine, and enables GC.
   174  func gcenable() {
   175  	// Kick off sweeping and scavenging.
   176  	c := make(chan int, 2)
   177  	go bgsweep(c)
   178  	go bgscavenge(c)
   179  	<-c
   180  	<-c
   181  	memstats.enablegc = true // now that runtime is initialized, GC is okay
   182  }
   183  
   184  // Garbage collector phase.
   185  // Indicates to write barrier and synchronization task to perform.
   186  var gcphase uint32
   187  
   188  // The compiler knows about this variable.
   189  // If you change it, you must change builtin/runtime.go, too.
   190  // If you change the first four bytes, you must also change the write
   191  // barrier insertion code.
   192  var writeBarrier struct {
   193  	enabled bool    // compiler emits a check of this before calling write barrier
   194  	pad     [3]byte // compiler uses 32-bit load for "enabled" field
   195  	needed  bool    // whether we need a write barrier for current GC phase
   196  	cgo     bool    // whether we need a write barrier for a cgo check
   197  	alignme uint64  // guarantee alignment so that compiler can use a 32 or 64-bit load
   198  }
   199  
   200  // gcBlackenEnabled is 1 if mutator assists and background mark
   201  // workers are allowed to blacken objects. This must only be set when
   202  // gcphase == _GCmark.
   203  var gcBlackenEnabled uint32
   204  
   205  const (
   206  	_GCoff             = iota // GC not running; sweeping in background, write barrier disabled
   207  	_GCmark                   // GC marking roots and workbufs: allocate black, write barrier ENABLED
   208  	_GCmarktermination        // GC mark termination: allocate black, P's help GC, write barrier ENABLED
   209  )
   210  
   211  //go:nosplit
   212  func setGCPhase(x uint32) {
   213  	atomic.Store(&gcphase, x)
   214  	writeBarrier.needed = gcphase == _GCmark || gcphase == _GCmarktermination
   215  	writeBarrier.enabled = writeBarrier.needed || writeBarrier.cgo
   216  }
   217  
   218  // gcMarkWorkerMode represents the mode that a concurrent mark worker
   219  // should operate in.
   220  //
   221  // Concurrent marking happens through four different mechanisms. One
   222  // is mutator assists, which happen in response to allocations and are
   223  // not scheduled. The other three are variations in the per-P mark
   224  // workers and are distinguished by gcMarkWorkerMode.
   225  type gcMarkWorkerMode int
   226  
   227  const (
   228  	// gcMarkWorkerNotWorker indicates that the next scheduled G is not
   229  	// starting work and the mode should be ignored.
   230  	gcMarkWorkerNotWorker gcMarkWorkerMode = iota
   231  
   232  	// gcMarkWorkerDedicatedMode indicates that the P of a mark
   233  	// worker is dedicated to running that mark worker. The mark
   234  	// worker should run without preemption.
   235  	gcMarkWorkerDedicatedMode
   236  
   237  	// gcMarkWorkerFractionalMode indicates that a P is currently
   238  	// running the "fractional" mark worker. The fractional worker
   239  	// is necessary when GOMAXPROCS*gcBackgroundUtilization is not
   240  	// an integer and using only dedicated workers would result in
   241  	// utilization too far from the target of gcBackgroundUtilization.
   242  	// The fractional worker should run until it is preempted and
   243  	// will be scheduled to pick up the fractional part of
   244  	// GOMAXPROCS*gcBackgroundUtilization.
   245  	gcMarkWorkerFractionalMode
   246  
   247  	// gcMarkWorkerIdleMode indicates that a P is running the mark
   248  	// worker because it has nothing else to do. The idle worker
   249  	// should run until it is preempted and account its time
   250  	// against gcController.idleMarkTime.
   251  	gcMarkWorkerIdleMode
   252  )
   253  
   254  // gcMarkWorkerModeStrings are the strings labels of gcMarkWorkerModes
   255  // to use in execution traces.
   256  var gcMarkWorkerModeStrings = [...]string{
   257  	"Not worker",
   258  	"GC (dedicated)",
   259  	"GC (fractional)",
   260  	"GC (idle)",
   261  }
   262  
   263  // pollFractionalWorkerExit reports whether a fractional mark worker
   264  // should self-preempt. It assumes it is called from the fractional
   265  // worker.
   266  func pollFractionalWorkerExit() bool {
   267  	// This should be kept in sync with the fractional worker
   268  	// scheduler logic in findRunnableGCWorker.
   269  	now := nanotime()
   270  	delta := now - gcController.markStartTime
   271  	if delta <= 0 {
   272  		return true
   273  	}
   274  	p := getg().m.p.ptr()
   275  	selfTime := p.gcFractionalMarkTime + (now - p.gcMarkWorkerStartTime)
   276  	// Add some slack to the utilization goal so that the
   277  	// fractional worker isn't behind again the instant it exits.
   278  	return float64(selfTime)/float64(delta) > 1.2*gcController.fractionalUtilizationGoal
   279  }
   280  
   281  var work struct {
   282  	full  lfstack          // lock-free list of full blocks workbuf
   283  	empty lfstack          // lock-free list of empty blocks workbuf
   284  	pad0  cpu.CacheLinePad // prevents false-sharing between full/empty and nproc/nwait
   285  
   286  	wbufSpans struct {
   287  		lock mutex
   288  		// free is a list of spans dedicated to workbufs, but
   289  		// that don't currently contain any workbufs.
   290  		free mSpanList
   291  		// busy is a list of all spans containing workbufs on
   292  		// one of the workbuf lists.
   293  		busy mSpanList
   294  	}
   295  
   296  	// Restore 64-bit alignment on 32-bit.
   297  	_ uint32
   298  
   299  	// bytesMarked is the number of bytes marked this cycle. This
   300  	// includes bytes blackened in scanned objects, noscan objects
   301  	// that go straight to black, and permagrey objects scanned by
   302  	// markroot during the concurrent scan phase. This is updated
   303  	// atomically during the cycle. Updates may be batched
   304  	// arbitrarily, since the value is only read at the end of the
   305  	// cycle.
   306  	//
   307  	// Because of benign races during marking, this number may not
   308  	// be the exact number of marked bytes, but it should be very
   309  	// close.
   310  	//
   311  	// Put this field here because it needs 64-bit atomic access
   312  	// (and thus 8-byte alignment even on 32-bit architectures).
   313  	bytesMarked uint64
   314  
   315  	markrootNext uint32 // next markroot job
   316  	markrootJobs uint32 // number of markroot jobs
   317  
   318  	nproc  uint32
   319  	tstart int64
   320  	nwait  uint32
   321  
   322  	// Number of roots of various root types. Set by gcMarkRootPrepare.
   323  	//
   324  	// nStackRoots == len(stackRoots), but we have nStackRoots for
   325  	// consistency.
   326  	nDataRoots, nBSSRoots, nSpanRoots, nStackRoots int
   327  
   328  	// Base indexes of each root type. Set by gcMarkRootPrepare.
   329  	baseData, baseBSS, baseSpans, baseStacks, baseEnd uint32
   330  
   331  	// stackRoots is a snapshot of all of the Gs that existed
   332  	// before the beginning of concurrent marking. The backing
   333  	// store of this must not be modified because it might be
   334  	// shared with allgs.
   335  	stackRoots []*g
   336  
   337  	// Each type of GC state transition is protected by a lock.
   338  	// Since multiple threads can simultaneously detect the state
   339  	// transition condition, any thread that detects a transition
   340  	// condition must acquire the appropriate transition lock,
   341  	// re-check the transition condition and return if it no
   342  	// longer holds or perform the transition if it does.
   343  	// Likewise, any transition must invalidate the transition
   344  	// condition before releasing the lock. This ensures that each
   345  	// transition is performed by exactly one thread and threads
   346  	// that need the transition to happen block until it has
   347  	// happened.
   348  	//
   349  	// startSema protects the transition from "off" to mark or
   350  	// mark termination.
   351  	startSema uint32
   352  	// markDoneSema protects transitions from mark to mark termination.
   353  	markDoneSema uint32
   354  
   355  	bgMarkReady note   // signal background mark worker has started
   356  	bgMarkDone  uint32 // cas to 1 when at a background mark completion point
   357  	// Background mark completion signaling
   358  
   359  	// mode is the concurrency mode of the current GC cycle.
   360  	mode gcMode
   361  
   362  	// userForced indicates the current GC cycle was forced by an
   363  	// explicit user call.
   364  	userForced bool
   365  
   366  	// totaltime is the CPU nanoseconds spent in GC since the
   367  	// program started if debug.gctrace > 0.
   368  	totaltime int64
   369  
   370  	// initialHeapLive is the value of gcController.heapLive at the
   371  	// beginning of this GC cycle.
   372  	initialHeapLive uint64
   373  
   374  	// assistQueue is a queue of assists that are blocked because
   375  	// there was neither enough credit to steal or enough work to
   376  	// do.
   377  	assistQueue struct {
   378  		lock mutex
   379  		q    gQueue
   380  	}
   381  
   382  	// sweepWaiters is a list of blocked goroutines to wake when
   383  	// we transition from mark termination to sweep.
   384  	sweepWaiters struct {
   385  		lock mutex
   386  		list gList
   387  	}
   388  
   389  	// cycles is the number of completed GC cycles, where a GC
   390  	// cycle is sweep termination, mark, mark termination, and
   391  	// sweep. This differs from memstats.numgc, which is
   392  	// incremented at mark termination.
   393  	cycles uint32
   394  
   395  	// Timing/utilization stats for this cycle.
   396  	stwprocs, maxprocs                 int32
   397  	tSweepTerm, tMark, tMarkTerm, tEnd int64 // nanotime() of phase start
   398  
   399  	pauseNS    int64 // total STW time this cycle
   400  	pauseStart int64 // nanotime() of last STW
   401  
   402  	// debug.gctrace heap sizes for this cycle.
   403  	heap0, heap1, heap2, heapGoal uint64
   404  }
   405  
   406  // GC runs a garbage collection and blocks the caller until the
   407  // garbage collection is complete. It may also block the entire
   408  // program.
   409  func GC() {
   410  	// We consider a cycle to be: sweep termination, mark, mark
   411  	// termination, and sweep. This function shouldn't return
   412  	// until a full cycle has been completed, from beginning to
   413  	// end. Hence, we always want to finish up the current cycle
   414  	// and start a new one. That means:
   415  	//
   416  	// 1. In sweep termination, mark, or mark termination of cycle
   417  	// N, wait until mark termination N completes and transitions
   418  	// to sweep N.
   419  	//
   420  	// 2. In sweep N, help with sweep N.
   421  	//
   422  	// At this point we can begin a full cycle N+1.
   423  	//
   424  	// 3. Trigger cycle N+1 by starting sweep termination N+1.
   425  	//
   426  	// 4. Wait for mark termination N+1 to complete.
   427  	//
   428  	// 5. Help with sweep N+1 until it's done.
   429  	//
   430  	// This all has to be written to deal with the fact that the
   431  	// GC may move ahead on its own. For example, when we block
   432  	// until mark termination N, we may wake up in cycle N+2.
   433  
   434  	// Wait until the current sweep termination, mark, and mark
   435  	// termination complete.
   436  	n := atomic.Load(&work.cycles)
   437  	gcWaitOnMark(n)
   438  
   439  	// We're now in sweep N or later. Trigger GC cycle N+1, which
   440  	// will first finish sweep N if necessary and then enter sweep
   441  	// termination N+1.
   442  	gcStart(gcTrigger{kind: gcTriggerCycle, n: n + 1})
   443  
   444  	// Wait for mark termination N+1 to complete.
   445  	gcWaitOnMark(n + 1)
   446  
   447  	// Finish sweep N+1 before returning. We do this both to
   448  	// complete the cycle and because runtime.GC() is often used
   449  	// as part of tests and benchmarks to get the system into a
   450  	// relatively stable and isolated state.
   451  	for atomic.Load(&work.cycles) == n+1 && sweepone() != ^uintptr(0) {
   452  		sweep.nbgsweep++
   453  		Gosched()
   454  	}
   455  
   456  	// Callers may assume that the heap profile reflects the
   457  	// just-completed cycle when this returns (historically this
   458  	// happened because this was a STW GC), but right now the
   459  	// profile still reflects mark termination N, not N+1.
   460  	//
   461  	// As soon as all of the sweep frees from cycle N+1 are done,
   462  	// we can go ahead and publish the heap profile.
   463  	//
   464  	// First, wait for sweeping to finish. (We know there are no
   465  	// more spans on the sweep queue, but we may be concurrently
   466  	// sweeping spans, so we have to wait.)
   467  	for atomic.Load(&work.cycles) == n+1 && !isSweepDone() {
   468  		Gosched()
   469  	}
   470  
   471  	// Now we're really done with sweeping, so we can publish the
   472  	// stable heap profile. Only do this if we haven't already hit
   473  	// another mark termination.
   474  	mp := acquirem()
   475  	cycle := atomic.Load(&work.cycles)
   476  	if cycle == n+1 || (gcphase == _GCmark && cycle == n+2) {
   477  		mProf_PostSweep()
   478  	}
   479  	releasem(mp)
   480  }
   481  
   482  // gcWaitOnMark blocks until GC finishes the Nth mark phase. If GC has
   483  // already completed this mark phase, it returns immediately.
   484  func gcWaitOnMark(n uint32) {
   485  	for {
   486  		// Disable phase transitions.
   487  		lock(&work.sweepWaiters.lock)
   488  		nMarks := atomic.Load(&work.cycles)
   489  		if gcphase != _GCmark {
   490  			// We've already completed this cycle's mark.
   491  			nMarks++
   492  		}
   493  		if nMarks > n {
   494  			// We're done.
   495  			unlock(&work.sweepWaiters.lock)
   496  			return
   497  		}
   498  
   499  		// Wait until sweep termination, mark, and mark
   500  		// termination of cycle N complete.
   501  		work.sweepWaiters.list.push(getg())
   502  		goparkunlock(&work.sweepWaiters.lock, waitReasonWaitForGCCycle, traceEvGoBlock, 1)
   503  	}
   504  }
   505  
   506  // gcMode indicates how concurrent a GC cycle should be.
   507  type gcMode int
   508  
   509  const (
   510  	gcBackgroundMode gcMode = iota // concurrent GC and sweep
   511  	gcForceMode                    // stop-the-world GC now, concurrent sweep
   512  	gcForceBlockMode               // stop-the-world GC now and STW sweep (forced by user)
   513  )
   514  
   515  // A gcTrigger is a predicate for starting a GC cycle. Specifically,
   516  // it is an exit condition for the _GCoff phase.
   517  type gcTrigger struct {
   518  	kind gcTriggerKind
   519  	now  int64  // gcTriggerTime: current time
   520  	n    uint32 // gcTriggerCycle: cycle number to start
   521  }
   522  
   523  type gcTriggerKind int
   524  
   525  const (
   526  	// gcTriggerHeap indicates that a cycle should be started when
   527  	// the heap size reaches the trigger heap size computed by the
   528  	// controller.
   529  	gcTriggerHeap gcTriggerKind = iota
   530  
   531  	// gcTriggerTime indicates that a cycle should be started when
   532  	// it's been more than forcegcperiod nanoseconds since the
   533  	// previous GC cycle.
   534  	gcTriggerTime
   535  
   536  	// gcTriggerCycle indicates that a cycle should be started if
   537  	// we have not yet started cycle number gcTrigger.n (relative
   538  	// to work.cycles).
   539  	gcTriggerCycle
   540  )
   541  
   542  // test reports whether the trigger condition is satisfied, meaning
   543  // that the exit condition for the _GCoff phase has been met. The exit
   544  // condition should be tested when allocating.
   545  func (t gcTrigger) test() bool {
   546  	if !memstats.enablegc || panicking != 0 || gcphase != _GCoff {
   547  		return false
   548  	}
   549  	switch t.kind {
   550  	case gcTriggerHeap:
   551  		// Non-atomic access to gcController.heapLive for performance. If
   552  		// we are going to trigger on this, this thread just
   553  		// atomically wrote gcController.heapLive anyway and we'll see our
   554  		// own write.
   555  		return gcController.heapLive >= gcController.trigger
   556  	case gcTriggerTime:
   557  		if gcController.gcPercent.Load() < 0 {
   558  			return false
   559  		}
   560  		lastgc := int64(atomic.Load64(&memstats.last_gc_nanotime))
   561  		return lastgc != 0 && t.now-lastgc > forcegcperiod
   562  	case gcTriggerCycle:
   563  		// t.n > work.cycles, but accounting for wraparound.
   564  		return int32(t.n-work.cycles) > 0
   565  	}
   566  	return true
   567  }
   568  
   569  // gcStart starts the GC. It transitions from _GCoff to _GCmark (if
   570  // debug.gcstoptheworld == 0) or performs all of GC (if
   571  // debug.gcstoptheworld != 0).
   572  //
   573  // This may return without performing this transition in some cases,
   574  // such as when called on a system stack or with locks held.
   575  func gcStart(trigger gcTrigger) {
   576  	// Since this is called from malloc and malloc is called in
   577  	// the guts of a number of libraries that might be holding
   578  	// locks, don't attempt to start GC in non-preemptible or
   579  	// potentially unstable situations.
   580  	mp := acquirem()
   581  	if gp := getg(); gp == mp.g0 || mp.locks > 1 || mp.preemptoff != "" {
   582  		releasem(mp)
   583  		return
   584  	}
   585  	releasem(mp)
   586  	mp = nil
   587  
   588  	// Pick up the remaining unswept/not being swept spans concurrently
   589  	//
   590  	// This shouldn't happen if we're being invoked in background
   591  	// mode since proportional sweep should have just finished
   592  	// sweeping everything, but rounding errors, etc, may leave a
   593  	// few spans unswept. In forced mode, this is necessary since
   594  	// GC can be forced at any point in the sweeping cycle.
   595  	//
   596  	// We check the transition condition continuously here in case
   597  	// this G gets delayed in to the next GC cycle.
   598  	for trigger.test() && sweepone() != ^uintptr(0) {
   599  		sweep.nbgsweep++
   600  	}
   601  
   602  	// Perform GC initialization and the sweep termination
   603  	// transition.
   604  	semacquire(&work.startSema)
   605  	// Re-check transition condition under transition lock.
   606  	if !trigger.test() {
   607  		semrelease(&work.startSema)
   608  		return
   609  	}
   610  
   611  	// For stats, check if this GC was forced by the user.
   612  	work.userForced = trigger.kind == gcTriggerCycle
   613  
   614  	// In gcstoptheworld debug mode, upgrade the mode accordingly.
   615  	// We do this after re-checking the transition condition so
   616  	// that multiple goroutines that detect the heap trigger don't
   617  	// start multiple STW GCs.
   618  	mode := gcBackgroundMode
   619  	if debug.gcstoptheworld == 1 {
   620  		mode = gcForceMode
   621  	} else if debug.gcstoptheworld == 2 {
   622  		mode = gcForceBlockMode
   623  	}
   624  
   625  	// Ok, we're doing it! Stop everybody else
   626  	semacquire(&gcsema)
   627  	semacquire(&worldsema)
   628  
   629  	if trace.enabled {
   630  		traceGCStart()
   631  	}
   632  
   633  	// Check that all Ps have finished deferred mcache flushes.
   634  	for _, p := range allp {
   635  		if fg := atomic.Load(&p.mcache.flushGen); fg != mheap_.sweepgen {
   636  			println("runtime: p", p.id, "flushGen", fg, "!= sweepgen", mheap_.sweepgen)
   637  			throw("p mcache not flushed")
   638  		}
   639  	}
   640  
   641  	gcBgMarkStartWorkers()
   642  
   643  	systemstack(gcResetMarkState)
   644  
   645  	work.stwprocs, work.maxprocs = gomaxprocs, gomaxprocs
   646  	if work.stwprocs > ncpu {
   647  		// This is used to compute CPU time of the STW phases,
   648  		// so it can't be more than ncpu, even if GOMAXPROCS is.
   649  		work.stwprocs = ncpu
   650  	}
   651  	work.heap0 = atomic.Load64(&gcController.heapLive)
   652  	work.pauseNS = 0
   653  	work.mode = mode
   654  
   655  	now := nanotime()
   656  	work.tSweepTerm = now
   657  	work.pauseStart = now
   658  	if trace.enabled {
   659  		traceGCSTWStart(1)
   660  	}
   661  	systemstack(stopTheWorldWithSema)
   662  	// Finish sweep before we start concurrent scan.
   663  	systemstack(func() {
   664  		finishsweep_m()
   665  	})
   666  
   667  	// clearpools before we start the GC. If we wait they memory will not be
   668  	// reclaimed until the next GC cycle.
   669  	clearpools()
   670  
   671  	work.cycles++
   672  
   673  	// Assists and workers can start the moment we start
   674  	// the world.
   675  	gcController.startCycle(now, int(gomaxprocs))
   676  	work.heapGoal = gcController.heapGoal
   677  
   678  	// In STW mode, disable scheduling of user Gs. This may also
   679  	// disable scheduling of this goroutine, so it may block as
   680  	// soon as we start the world again.
   681  	if mode != gcBackgroundMode {
   682  		schedEnableUser(false)
   683  	}
   684  
   685  	// Enter concurrent mark phase and enable
   686  	// write barriers.
   687  	//
   688  	// Because the world is stopped, all Ps will
   689  	// observe that write barriers are enabled by
   690  	// the time we start the world and begin
   691  	// scanning.
   692  	//
   693  	// Write barriers must be enabled before assists are
   694  	// enabled because they must be enabled before
   695  	// any non-leaf heap objects are marked. Since
   696  	// allocations are blocked until assists can
   697  	// happen, we want enable assists as early as
   698  	// possible.
   699  	setGCPhase(_GCmark)
   700  
   701  	gcBgMarkPrepare() // Must happen before assist enable.
   702  	gcMarkRootPrepare()
   703  
   704  	// Mark all active tinyalloc blocks. Since we're
   705  	// allocating from these, they need to be black like
   706  	// other allocations. The alternative is to blacken
   707  	// the tiny block on every allocation from it, which
   708  	// would slow down the tiny allocator.
   709  	gcMarkTinyAllocs()
   710  
   711  	// At this point all Ps have enabled the write
   712  	// barrier, thus maintaining the no white to
   713  	// black invariant. Enable mutator assists to
   714  	// put back-pressure on fast allocating
   715  	// mutators.
   716  	atomic.Store(&gcBlackenEnabled, 1)
   717  
   718  	// In STW mode, we could block the instant systemstack
   719  	// returns, so make sure we're not preemptible.
   720  	mp = acquirem()
   721  
   722  	// Concurrent mark.
   723  	systemstack(func() {
   724  		now = startTheWorldWithSema(trace.enabled)
   725  		work.pauseNS += now - work.pauseStart
   726  		work.tMark = now
   727  		memstats.gcPauseDist.record(now - work.pauseStart)
   728  	})
   729  
   730  	// Release the world sema before Gosched() in STW mode
   731  	// because we will need to reacquire it later but before
   732  	// this goroutine becomes runnable again, and we could
   733  	// self-deadlock otherwise.
   734  	semrelease(&worldsema)
   735  	releasem(mp)
   736  
   737  	// Make sure we block instead of returning to user code
   738  	// in STW mode.
   739  	if mode != gcBackgroundMode {
   740  		Gosched()
   741  	}
   742  
   743  	semrelease(&work.startSema)
   744  }
   745  
   746  // gcMarkDoneFlushed counts the number of P's with flushed work.
   747  //
   748  // Ideally this would be a captured local in gcMarkDone, but forEachP
   749  // escapes its callback closure, so it can't capture anything.
   750  //
   751  // This is protected by markDoneSema.
   752  var gcMarkDoneFlushed uint32
   753  
   754  // gcMarkDone transitions the GC from mark to mark termination if all
   755  // reachable objects have been marked (that is, there are no grey
   756  // objects and can be no more in the future). Otherwise, it flushes
   757  // all local work to the global queues where it can be discovered by
   758  // other workers.
   759  //
   760  // This should be called when all local mark work has been drained and
   761  // there are no remaining workers. Specifically, when
   762  //
   763  //   work.nwait == work.nproc && !gcMarkWorkAvailable(p)
   764  //
   765  // The calling context must be preemptible.
   766  //
   767  // Flushing local work is important because idle Ps may have local
   768  // work queued. This is the only way to make that work visible and
   769  // drive GC to completion.
   770  //
   771  // It is explicitly okay to have write barriers in this function. If
   772  // it does transition to mark termination, then all reachable objects
   773  // have been marked, so the write barrier cannot shade any more
   774  // objects.
   775  func gcMarkDone() {
   776  	// Ensure only one thread is running the ragged barrier at a
   777  	// time.
   778  	semacquire(&work.markDoneSema)
   779  
   780  top:
   781  	// Re-check transition condition under transition lock.
   782  	//
   783  	// It's critical that this checks the global work queues are
   784  	// empty before performing the ragged barrier. Otherwise,
   785  	// there could be global work that a P could take after the P
   786  	// has passed the ragged barrier.
   787  	if !(gcphase == _GCmark && work.nwait == work.nproc && !gcMarkWorkAvailable(nil)) {
   788  		semrelease(&work.markDoneSema)
   789  		return
   790  	}
   791  
   792  	// forEachP needs worldsema to execute, and we'll need it to
   793  	// stop the world later, so acquire worldsema now.
   794  	semacquire(&worldsema)
   795  
   796  	// Flush all local buffers and collect flushedWork flags.
   797  	gcMarkDoneFlushed = 0
   798  	systemstack(func() {
   799  		gp := getg().m.curg
   800  		// Mark the user stack as preemptible so that it may be scanned.
   801  		// Otherwise, our attempt to force all P's to a safepoint could
   802  		// result in a deadlock as we attempt to preempt a worker that's
   803  		// trying to preempt us (e.g. for a stack scan).
   804  		casgstatus(gp, _Grunning, _Gwaiting)
   805  		forEachP(func(_p_ *p) {
   806  			// Flush the write barrier buffer, since this may add
   807  			// work to the gcWork.
   808  			wbBufFlush1(_p_)
   809  
   810  			// Flush the gcWork, since this may create global work
   811  			// and set the flushedWork flag.
   812  			//
   813  			// TODO(austin): Break up these workbufs to
   814  			// better distribute work.
   815  			_p_.gcw.dispose()
   816  			// Collect the flushedWork flag.
   817  			if _p_.gcw.flushedWork {
   818  				atomic.Xadd(&gcMarkDoneFlushed, 1)
   819  				_p_.gcw.flushedWork = false
   820  			}
   821  		})
   822  		casgstatus(gp, _Gwaiting, _Grunning)
   823  	})
   824  
   825  	if gcMarkDoneFlushed != 0 {
   826  		// More grey objects were discovered since the
   827  		// previous termination check, so there may be more
   828  		// work to do. Keep going. It's possible the
   829  		// transition condition became true again during the
   830  		// ragged barrier, so re-check it.
   831  		semrelease(&worldsema)
   832  		goto top
   833  	}
   834  
   835  	// There was no global work, no local work, and no Ps
   836  	// communicated work since we took markDoneSema. Therefore
   837  	// there are no grey objects and no more objects can be
   838  	// shaded. Transition to mark termination.
   839  	now := nanotime()
   840  	work.tMarkTerm = now
   841  	work.pauseStart = now
   842  	getg().m.preemptoff = "gcing"
   843  	if trace.enabled {
   844  		traceGCSTWStart(0)
   845  	}
   846  	systemstack(stopTheWorldWithSema)
   847  	// The gcphase is _GCmark, it will transition to _GCmarktermination
   848  	// below. The important thing is that the wb remains active until
   849  	// all marking is complete. This includes writes made by the GC.
   850  
   851  	// There is sometimes work left over when we enter mark termination due
   852  	// to write barriers performed after the completion barrier above.
   853  	// Detect this and resume concurrent mark. This is obviously
   854  	// unfortunate.
   855  	//
   856  	// See issue #27993 for details.
   857  	//
   858  	// Switch to the system stack to call wbBufFlush1, though in this case
   859  	// it doesn't matter because we're non-preemptible anyway.
   860  	restart := false
   861  	systemstack(func() {
   862  		for _, p := range allp {
   863  			wbBufFlush1(p)
   864  			if !p.gcw.empty() {
   865  				restart = true
   866  				break
   867  			}
   868  		}
   869  	})
   870  	if restart {
   871  		getg().m.preemptoff = ""
   872  		systemstack(func() {
   873  			now := startTheWorldWithSema(true)
   874  			work.pauseNS += now - work.pauseStart
   875  			memstats.gcPauseDist.record(now - work.pauseStart)
   876  		})
   877  		semrelease(&worldsema)
   878  		goto top
   879  	}
   880  
   881  	// Disable assists and background workers. We must do
   882  	// this before waking blocked assists.
   883  	atomic.Store(&gcBlackenEnabled, 0)
   884  
   885  	// Wake all blocked assists. These will run when we
   886  	// start the world again.
   887  	gcWakeAllAssists()
   888  
   889  	// Likewise, release the transition lock. Blocked
   890  	// workers and assists will run when we start the
   891  	// world again.
   892  	semrelease(&work.markDoneSema)
   893  
   894  	// In STW mode, re-enable user goroutines. These will be
   895  	// queued to run after we start the world.
   896  	schedEnableUser(true)
   897  
   898  	// endCycle depends on all gcWork cache stats being flushed.
   899  	// The termination algorithm above ensured that up to
   900  	// allocations since the ragged barrier.
   901  	nextTriggerRatio := gcController.endCycle(now, int(gomaxprocs), work.userForced)
   902  
   903  	// Perform mark termination. This will restart the world.
   904  	gcMarkTermination(nextTriggerRatio)
   905  }
   906  
   907  // World must be stopped and mark assists and background workers must be
   908  // disabled.
   909  func gcMarkTermination(nextTriggerRatio float64) {
   910  	// Start marktermination (write barrier remains enabled for now).
   911  	setGCPhase(_GCmarktermination)
   912  
   913  	work.heap1 = gcController.heapLive
   914  	startTime := nanotime()
   915  
   916  	mp := acquirem()
   917  	mp.preemptoff = "gcing"
   918  	_g_ := getg()
   919  	_g_.m.traceback = 2
   920  	gp := _g_.m.curg
   921  	casgstatus(gp, _Grunning, _Gwaiting)
   922  	gp.waitreason = waitReasonGarbageCollection
   923  
   924  	// Run gc on the g0 stack. We do this so that the g stack
   925  	// we're currently running on will no longer change. Cuts
   926  	// the root set down a bit (g0 stacks are not scanned, and
   927  	// we don't need to scan gc's internal state).  We also
   928  	// need to switch to g0 so we can shrink the stack.
   929  	systemstack(func() {
   930  		gcMark(startTime)
   931  		// Must return immediately.
   932  		// The outer function's stack may have moved
   933  		// during gcMark (it shrinks stacks, including the
   934  		// outer function's stack), so we must not refer
   935  		// to any of its variables. Return back to the
   936  		// non-system stack to pick up the new addresses
   937  		// before continuing.
   938  	})
   939  
   940  	systemstack(func() {
   941  		work.heap2 = work.bytesMarked
   942  		if debug.gccheckmark > 0 {
   943  			// Run a full non-parallel, stop-the-world
   944  			// mark using checkmark bits, to check that we
   945  			// didn't forget to mark anything during the
   946  			// concurrent mark process.
   947  			startCheckmarks()
   948  			gcResetMarkState()
   949  			gcw := &getg().m.p.ptr().gcw
   950  			gcDrain(gcw, 0)
   951  			wbBufFlush1(getg().m.p.ptr())
   952  			gcw.dispose()
   953  			endCheckmarks()
   954  		}
   955  
   956  		// marking is complete so we can turn the write barrier off
   957  		setGCPhase(_GCoff)
   958  		gcSweep(work.mode)
   959  	})
   960  
   961  	_g_.m.traceback = 0
   962  	casgstatus(gp, _Gwaiting, _Grunning)
   963  
   964  	if trace.enabled {
   965  		traceGCDone()
   966  	}
   967  
   968  	// all done
   969  	mp.preemptoff = ""
   970  
   971  	if gcphase != _GCoff {
   972  		throw("gc done but gcphase != _GCoff")
   973  	}
   974  
   975  	// Record heap_inuse for scavenger.
   976  	memstats.last_heap_inuse = memstats.heap_inuse
   977  
   978  	// Update GC trigger and pacing for the next cycle.
   979  	gcController.commit(nextTriggerRatio)
   980  	gcPaceSweeper(gcController.trigger)
   981  	gcPaceScavenger(gcController.heapGoal, gcController.lastHeapGoal)
   982  
   983  	// Update timing memstats
   984  	now := nanotime()
   985  	sec, nsec, _ := time_now()
   986  	unixNow := sec*1e9 + int64(nsec)
   987  	work.pauseNS += now - work.pauseStart
   988  	work.tEnd = now
   989  	memstats.gcPauseDist.record(now - work.pauseStart)
   990  	atomic.Store64(&memstats.last_gc_unix, uint64(unixNow)) // must be Unix time to make sense to user
   991  	atomic.Store64(&memstats.last_gc_nanotime, uint64(now)) // monotonic time for us
   992  	memstats.pause_ns[memstats.numgc%uint32(len(memstats.pause_ns))] = uint64(work.pauseNS)
   993  	memstats.pause_end[memstats.numgc%uint32(len(memstats.pause_end))] = uint64(unixNow)
   994  	memstats.pause_total_ns += uint64(work.pauseNS)
   995  
   996  	// Update work.totaltime.
   997  	sweepTermCpu := int64(work.stwprocs) * (work.tMark - work.tSweepTerm)
   998  	// We report idle marking time below, but omit it from the
   999  	// overall utilization here since it's "free".
  1000  	markCpu := gcController.assistTime + gcController.dedicatedMarkTime + gcController.fractionalMarkTime
  1001  	markTermCpu := int64(work.stwprocs) * (work.tEnd - work.tMarkTerm)
  1002  	cycleCpu := sweepTermCpu + markCpu + markTermCpu
  1003  	work.totaltime += cycleCpu
  1004  
  1005  	// Compute overall GC CPU utilization.
  1006  	totalCpu := sched.totaltime + (now-sched.procresizetime)*int64(gomaxprocs)
  1007  	memstats.gc_cpu_fraction = float64(work.totaltime) / float64(totalCpu)
  1008  
  1009  	// Reset sweep state.
  1010  	sweep.nbgsweep = 0
  1011  	sweep.npausesweep = 0
  1012  
  1013  	if work.userForced {
  1014  		memstats.numforcedgc++
  1015  	}
  1016  
  1017  	// Bump GC cycle count and wake goroutines waiting on sweep.
  1018  	lock(&work.sweepWaiters.lock)
  1019  	memstats.numgc++
  1020  	injectglist(&work.sweepWaiters.list)
  1021  	unlock(&work.sweepWaiters.lock)
  1022  
  1023  	// Finish the current heap profiling cycle and start a new
  1024  	// heap profiling cycle. We do this before starting the world
  1025  	// so events don't leak into the wrong cycle.
  1026  	mProf_NextCycle()
  1027  
  1028  	// There may be stale spans in mcaches that need to be swept.
  1029  	// Those aren't tracked in any sweep lists, so we need to
  1030  	// count them against sweep completion until we ensure all
  1031  	// those spans have been forced out.
  1032  	sl := sweep.active.begin()
  1033  	if !sl.valid {
  1034  		throw("failed to set sweep barrier")
  1035  	}
  1036  
  1037  	systemstack(func() { startTheWorldWithSema(true) })
  1038  
  1039  	// Flush the heap profile so we can start a new cycle next GC.
  1040  	// This is relatively expensive, so we don't do it with the
  1041  	// world stopped.
  1042  	mProf_Flush()
  1043  
  1044  	// Prepare workbufs for freeing by the sweeper. We do this
  1045  	// asynchronously because it can take non-trivial time.
  1046  	prepareFreeWorkbufs()
  1047  
  1048  	// Free stack spans. This must be done between GC cycles.
  1049  	systemstack(freeStackSpans)
  1050  
  1051  	// Ensure all mcaches are flushed. Each P will flush its own
  1052  	// mcache before allocating, but idle Ps may not. Since this
  1053  	// is necessary to sweep all spans, we need to ensure all
  1054  	// mcaches are flushed before we start the next GC cycle.
  1055  	systemstack(func() {
  1056  		forEachP(func(_p_ *p) {
  1057  			_p_.mcache.prepareForSweep()
  1058  		})
  1059  	})
  1060  	// Now that we've swept stale spans in mcaches, they don't
  1061  	// count against unswept spans.
  1062  	sweep.active.end(sl)
  1063  
  1064  	// Print gctrace before dropping worldsema. As soon as we drop
  1065  	// worldsema another cycle could start and smash the stats
  1066  	// we're trying to print.
  1067  	if debug.gctrace > 0 {
  1068  		util := int(memstats.gc_cpu_fraction * 100)
  1069  
  1070  		var sbuf [24]byte
  1071  		printlock()
  1072  		print("gc ", memstats.numgc,
  1073  			" @", string(itoaDiv(sbuf[:], uint64(work.tSweepTerm-runtimeInitTime)/1e6, 3)), "s ",
  1074  			util, "%: ")
  1075  		prev := work.tSweepTerm
  1076  		for i, ns := range []int64{work.tMark, work.tMarkTerm, work.tEnd} {
  1077  			if i != 0 {
  1078  				print("+")
  1079  			}
  1080  			print(string(fmtNSAsMS(sbuf[:], uint64(ns-prev))))
  1081  			prev = ns
  1082  		}
  1083  		print(" ms clock, ")
  1084  		for i, ns := range []int64{sweepTermCpu, gcController.assistTime, gcController.dedicatedMarkTime + gcController.fractionalMarkTime, gcController.idleMarkTime, markTermCpu} {
  1085  			if i == 2 || i == 3 {
  1086  				// Separate mark time components with /.
  1087  				print("/")
  1088  			} else if i != 0 {
  1089  				print("+")
  1090  			}
  1091  			print(string(fmtNSAsMS(sbuf[:], uint64(ns))))
  1092  		}
  1093  		print(" ms cpu, ",
  1094  			work.heap0>>20, "->", work.heap1>>20, "->", work.heap2>>20, " MB, ",
  1095  			work.heapGoal>>20, " MB goal, ",
  1096  			gcController.stackScan>>20, " MB stacks, ",
  1097  			gcController.globalsScan>>20, " MB globals, ",
  1098  			work.maxprocs, " P")
  1099  		if work.userForced {
  1100  			print(" (forced)")
  1101  		}
  1102  		print("\n")
  1103  		printunlock()
  1104  	}
  1105  
  1106  	semrelease(&worldsema)
  1107  	semrelease(&gcsema)
  1108  	// Careful: another GC cycle may start now.
  1109  
  1110  	releasem(mp)
  1111  	mp = nil
  1112  
  1113  	// now that gc is done, kick off finalizer thread if needed
  1114  	if !concurrentSweep {
  1115  		// give the queued finalizers, if any, a chance to run
  1116  		Gosched()
  1117  	}
  1118  }
  1119  
  1120  // gcBgMarkStartWorkers prepares background mark worker goroutines. These
  1121  // goroutines will not run until the mark phase, but they must be started while
  1122  // the work is not stopped and from a regular G stack. The caller must hold
  1123  // worldsema.
  1124  func gcBgMarkStartWorkers() {
  1125  	// Background marking is performed by per-P G's. Ensure that each P has
  1126  	// a background GC G.
  1127  	//
  1128  	// Worker Gs don't exit if gomaxprocs is reduced. If it is raised
  1129  	// again, we can reuse the old workers; no need to create new workers.
  1130  	for gcBgMarkWorkerCount < gomaxprocs {
  1131  		go gcBgMarkWorker()
  1132  
  1133  		notetsleepg(&work.bgMarkReady, -1)
  1134  		noteclear(&work.bgMarkReady)
  1135  		// The worker is now guaranteed to be added to the pool before
  1136  		// its P's next findRunnableGCWorker.
  1137  
  1138  		gcBgMarkWorkerCount++
  1139  	}
  1140  }
  1141  
  1142  // gcBgMarkPrepare sets up state for background marking.
  1143  // Mutator assists must not yet be enabled.
  1144  func gcBgMarkPrepare() {
  1145  	// Background marking will stop when the work queues are empty
  1146  	// and there are no more workers (note that, since this is
  1147  	// concurrent, this may be a transient state, but mark
  1148  	// termination will clean it up). Between background workers
  1149  	// and assists, we don't really know how many workers there
  1150  	// will be, so we pretend to have an arbitrarily large number
  1151  	// of workers, almost all of which are "waiting". While a
  1152  	// worker is working it decrements nwait. If nproc == nwait,
  1153  	// there are no workers.
  1154  	work.nproc = ^uint32(0)
  1155  	work.nwait = ^uint32(0)
  1156  }
  1157  
  1158  // gcBgMarkWorker is an entry in the gcBgMarkWorkerPool. It points to a single
  1159  // gcBgMarkWorker goroutine.
  1160  type gcBgMarkWorkerNode struct {
  1161  	// Unused workers are managed in a lock-free stack. This field must be first.
  1162  	node lfnode
  1163  
  1164  	// The g of this worker.
  1165  	gp guintptr
  1166  
  1167  	// Release this m on park. This is used to communicate with the unlock
  1168  	// function, which cannot access the G's stack. It is unused outside of
  1169  	// gcBgMarkWorker().
  1170  	m muintptr
  1171  }
  1172  
  1173  func gcBgMarkWorker() {
  1174  	gp := getg()
  1175  
  1176  	// We pass node to a gopark unlock function, so it can't be on
  1177  	// the stack (see gopark). Prevent deadlock from recursively
  1178  	// starting GC by disabling preemption.
  1179  	gp.m.preemptoff = "GC worker init"
  1180  	node := new(gcBgMarkWorkerNode)
  1181  	gp.m.preemptoff = ""
  1182  
  1183  	node.gp.set(gp)
  1184  
  1185  	node.m.set(acquirem())
  1186  	notewakeup(&work.bgMarkReady)
  1187  	// After this point, the background mark worker is generally scheduled
  1188  	// cooperatively by gcController.findRunnableGCWorker. While performing
  1189  	// work on the P, preemption is disabled because we are working on
  1190  	// P-local work buffers. When the preempt flag is set, this puts itself
  1191  	// into _Gwaiting to be woken up by gcController.findRunnableGCWorker
  1192  	// at the appropriate time.
  1193  	//
  1194  	// When preemption is enabled (e.g., while in gcMarkDone), this worker
  1195  	// may be preempted and schedule as a _Grunnable G from a runq. That is
  1196  	// fine; it will eventually gopark again for further scheduling via
  1197  	// findRunnableGCWorker.
  1198  	//
  1199  	// Since we disable preemption before notifying bgMarkReady, we
  1200  	// guarantee that this G will be in the worker pool for the next
  1201  	// findRunnableGCWorker. This isn't strictly necessary, but it reduces
  1202  	// latency between _GCmark starting and the workers starting.
  1203  
  1204  	for {
  1205  		// Go to sleep until woken by
  1206  		// gcController.findRunnableGCWorker.
  1207  		gopark(func(g *g, nodep unsafe.Pointer) bool {
  1208  			node := (*gcBgMarkWorkerNode)(nodep)
  1209  
  1210  			if mp := node.m.ptr(); mp != nil {
  1211  				// The worker G is no longer running; release
  1212  				// the M.
  1213  				//
  1214  				// N.B. it is _safe_ to release the M as soon
  1215  				// as we are no longer performing P-local mark
  1216  				// work.
  1217  				//
  1218  				// However, since we cooperatively stop work
  1219  				// when gp.preempt is set, if we releasem in
  1220  				// the loop then the following call to gopark
  1221  				// would immediately preempt the G. This is
  1222  				// also safe, but inefficient: the G must
  1223  				// schedule again only to enter gopark and park
  1224  				// again. Thus, we defer the release until
  1225  				// after parking the G.
  1226  				releasem(mp)
  1227  			}
  1228  
  1229  			// Release this G to the pool.
  1230  			gcBgMarkWorkerPool.push(&node.node)
  1231  			// Note that at this point, the G may immediately be
  1232  			// rescheduled and may be running.
  1233  			return true
  1234  		}, unsafe.Pointer(node), waitReasonGCWorkerIdle, traceEvGoBlock, 0)
  1235  
  1236  		// Preemption must not occur here, or another G might see
  1237  		// p.gcMarkWorkerMode.
  1238  
  1239  		// Disable preemption so we can use the gcw. If the
  1240  		// scheduler wants to preempt us, we'll stop draining,
  1241  		// dispose the gcw, and then preempt.
  1242  		node.m.set(acquirem())
  1243  		pp := gp.m.p.ptr() // P can't change with preemption disabled.
  1244  
  1245  		if gcBlackenEnabled == 0 {
  1246  			println("worker mode", pp.gcMarkWorkerMode)
  1247  			throw("gcBgMarkWorker: blackening not enabled")
  1248  		}
  1249  
  1250  		if pp.gcMarkWorkerMode == gcMarkWorkerNotWorker {
  1251  			throw("gcBgMarkWorker: mode not set")
  1252  		}
  1253  
  1254  		startTime := nanotime()
  1255  		pp.gcMarkWorkerStartTime = startTime
  1256  
  1257  		decnwait := atomic.Xadd(&work.nwait, -1)
  1258  		if decnwait == work.nproc {
  1259  			println("runtime: work.nwait=", decnwait, "work.nproc=", work.nproc)
  1260  			throw("work.nwait was > work.nproc")
  1261  		}
  1262  
  1263  		systemstack(func() {
  1264  			// Mark our goroutine preemptible so its stack
  1265  			// can be scanned. This lets two mark workers
  1266  			// scan each other (otherwise, they would
  1267  			// deadlock). We must not modify anything on
  1268  			// the G stack. However, stack shrinking is
  1269  			// disabled for mark workers, so it is safe to
  1270  			// read from the G stack.
  1271  			casgstatus(gp, _Grunning, _Gwaiting)
  1272  			switch pp.gcMarkWorkerMode {
  1273  			default:
  1274  				throw("gcBgMarkWorker: unexpected gcMarkWorkerMode")
  1275  			case gcMarkWorkerDedicatedMode:
  1276  				gcDrain(&pp.gcw, gcDrainUntilPreempt|gcDrainFlushBgCredit)
  1277  				if gp.preempt {
  1278  					// We were preempted. This is
  1279  					// a useful signal to kick
  1280  					// everything out of the run
  1281  					// queue so it can run
  1282  					// somewhere else.
  1283  					if drainQ, n := runqdrain(pp); n > 0 {
  1284  						lock(&sched.lock)
  1285  						globrunqputbatch(&drainQ, int32(n))
  1286  						unlock(&sched.lock)
  1287  					}
  1288  				}
  1289  				// Go back to draining, this time
  1290  				// without preemption.
  1291  				gcDrain(&pp.gcw, gcDrainFlushBgCredit)
  1292  			case gcMarkWorkerFractionalMode:
  1293  				gcDrain(&pp.gcw, gcDrainFractional|gcDrainUntilPreempt|gcDrainFlushBgCredit)
  1294  			case gcMarkWorkerIdleMode:
  1295  				gcDrain(&pp.gcw, gcDrainIdle|gcDrainUntilPreempt|gcDrainFlushBgCredit)
  1296  			}
  1297  			casgstatus(gp, _Gwaiting, _Grunning)
  1298  		})
  1299  
  1300  		// Account for time.
  1301  		duration := nanotime() - startTime
  1302  		gcController.logWorkTime(pp.gcMarkWorkerMode, duration)
  1303  		if pp.gcMarkWorkerMode == gcMarkWorkerFractionalMode {
  1304  			atomic.Xaddint64(&pp.gcFractionalMarkTime, duration)
  1305  		}
  1306  
  1307  		// Was this the last worker and did we run out
  1308  		// of work?
  1309  		incnwait := atomic.Xadd(&work.nwait, +1)
  1310  		if incnwait > work.nproc {
  1311  			println("runtime: p.gcMarkWorkerMode=", pp.gcMarkWorkerMode,
  1312  				"work.nwait=", incnwait, "work.nproc=", work.nproc)
  1313  			throw("work.nwait > work.nproc")
  1314  		}
  1315  
  1316  		// We'll releasem after this point and thus this P may run
  1317  		// something else. We must clear the worker mode to avoid
  1318  		// attributing the mode to a different (non-worker) G in
  1319  		// traceGoStart.
  1320  		pp.gcMarkWorkerMode = gcMarkWorkerNotWorker
  1321  
  1322  		// If this worker reached a background mark completion
  1323  		// point, signal the main GC goroutine.
  1324  		if incnwait == work.nproc && !gcMarkWorkAvailable(nil) {
  1325  			// We don't need the P-local buffers here, allow
  1326  			// preemption because we may schedule like a regular
  1327  			// goroutine in gcMarkDone (block on locks, etc).
  1328  			releasem(node.m.ptr())
  1329  			node.m.set(nil)
  1330  
  1331  			gcMarkDone()
  1332  		}
  1333  	}
  1334  }
  1335  
  1336  // gcMarkWorkAvailable reports whether executing a mark worker
  1337  // on p is potentially useful. p may be nil, in which case it only
  1338  // checks the global sources of work.
  1339  func gcMarkWorkAvailable(p *p) bool {
  1340  	if p != nil && !p.gcw.empty() {
  1341  		return true
  1342  	}
  1343  	if !work.full.empty() {
  1344  		return true // global work available
  1345  	}
  1346  	if work.markrootNext < work.markrootJobs {
  1347  		return true // root scan work available
  1348  	}
  1349  	return false
  1350  }
  1351  
  1352  // gcMark runs the mark (or, for concurrent GC, mark termination)
  1353  // All gcWork caches must be empty.
  1354  // STW is in effect at this point.
  1355  func gcMark(startTime int64) {
  1356  	if debug.allocfreetrace > 0 {
  1357  		tracegc()
  1358  	}
  1359  
  1360  	if gcphase != _GCmarktermination {
  1361  		throw("in gcMark expecting to see gcphase as _GCmarktermination")
  1362  	}
  1363  	work.tstart = startTime
  1364  
  1365  	// Check that there's no marking work remaining.
  1366  	if work.full != 0 || work.markrootNext < work.markrootJobs {
  1367  		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")
  1368  		panic("non-empty mark queue after concurrent mark")
  1369  	}
  1370  
  1371  	if debug.gccheckmark > 0 {
  1372  		// This is expensive when there's a large number of
  1373  		// Gs, so only do it if checkmark is also enabled.
  1374  		gcMarkRootCheck()
  1375  	}
  1376  	if work.full != 0 {
  1377  		throw("work.full != 0")
  1378  	}
  1379  
  1380  	// Drop allg snapshot. allgs may have grown, in which case
  1381  	// this is the only reference to the old backing store and
  1382  	// there's no need to keep it around.
  1383  	work.stackRoots = nil
  1384  
  1385  	// Clear out buffers and double-check that all gcWork caches
  1386  	// are empty. This should be ensured by gcMarkDone before we
  1387  	// enter mark termination.
  1388  	//
  1389  	// TODO: We could clear out buffers just before mark if this
  1390  	// has a non-negligible impact on STW time.
  1391  	for _, p := range allp {
  1392  		// The write barrier may have buffered pointers since
  1393  		// the gcMarkDone barrier. However, since the barrier
  1394  		// ensured all reachable objects were marked, all of
  1395  		// these must be pointers to black objects. Hence we
  1396  		// can just discard the write barrier buffer.
  1397  		if debug.gccheckmark > 0 {
  1398  			// For debugging, flush the buffer and make
  1399  			// sure it really was all marked.
  1400  			wbBufFlush1(p)
  1401  		} else {
  1402  			p.wbBuf.reset()
  1403  		}
  1404  
  1405  		gcw := &p.gcw
  1406  		if !gcw.empty() {
  1407  			printlock()
  1408  			print("runtime: P ", p.id, " flushedWork ", gcw.flushedWork)
  1409  			if gcw.wbuf1 == nil {
  1410  				print(" wbuf1=<nil>")
  1411  			} else {
  1412  				print(" wbuf1.n=", gcw.wbuf1.nobj)
  1413  			}
  1414  			if gcw.wbuf2 == nil {
  1415  				print(" wbuf2=<nil>")
  1416  			} else {
  1417  				print(" wbuf2.n=", gcw.wbuf2.nobj)
  1418  			}
  1419  			print("\n")
  1420  			throw("P has cached GC work at end of mark termination")
  1421  		}
  1422  		// There may still be cached empty buffers, which we
  1423  		// need to flush since we're going to free them. Also,
  1424  		// there may be non-zero stats because we allocated
  1425  		// black after the gcMarkDone barrier.
  1426  		gcw.dispose()
  1427  	}
  1428  
  1429  	// Flush scanAlloc from each mcache since we're about to modify
  1430  	// heapScan directly. If we were to flush this later, then scanAlloc
  1431  	// might have incorrect information.
  1432  	//
  1433  	// Note that it's not important to retain this information; we know
  1434  	// exactly what heapScan is at this point via scanWork.
  1435  	for _, p := range allp {
  1436  		c := p.mcache
  1437  		if c == nil {
  1438  			continue
  1439  		}
  1440  		c.scanAlloc = 0
  1441  	}
  1442  
  1443  	// Reset controller state.
  1444  	gcController.resetLive(work.bytesMarked)
  1445  }
  1446  
  1447  // gcSweep must be called on the system stack because it acquires the heap
  1448  // lock. See mheap for details.
  1449  //
  1450  // The world must be stopped.
  1451  //
  1452  //go:systemstack
  1453  func gcSweep(mode gcMode) {
  1454  	assertWorldStopped()
  1455  
  1456  	if gcphase != _GCoff {
  1457  		throw("gcSweep being done but phase is not GCoff")
  1458  	}
  1459  
  1460  	lock(&mheap_.lock)
  1461  	mheap_.sweepgen += 2
  1462  	sweep.active.reset()
  1463  	mheap_.pagesSwept.Store(0)
  1464  	mheap_.sweepArenas = mheap_.allArenas
  1465  	mheap_.reclaimIndex.Store(0)
  1466  	mheap_.reclaimCredit.Store(0)
  1467  	unlock(&mheap_.lock)
  1468  
  1469  	sweep.centralIndex.clear()
  1470  
  1471  	if !_ConcurrentSweep || mode == gcForceBlockMode {
  1472  		// Special case synchronous sweep.
  1473  		// Record that no proportional sweeping has to happen.
  1474  		lock(&mheap_.lock)
  1475  		mheap_.sweepPagesPerByte = 0
  1476  		unlock(&mheap_.lock)
  1477  		// Sweep all spans eagerly.
  1478  		for sweepone() != ^uintptr(0) {
  1479  			sweep.npausesweep++
  1480  		}
  1481  		// Free workbufs eagerly.
  1482  		prepareFreeWorkbufs()
  1483  		for freeSomeWbufs(false) {
  1484  		}
  1485  		// All "free" events for this mark/sweep cycle have
  1486  		// now happened, so we can make this profile cycle
  1487  		// available immediately.
  1488  		mProf_NextCycle()
  1489  		mProf_Flush()
  1490  		return
  1491  	}
  1492  
  1493  	// Background sweep.
  1494  	lock(&sweep.lock)
  1495  	if sweep.parked {
  1496  		sweep.parked = false
  1497  		ready(sweep.g, 0, true)
  1498  	}
  1499  	unlock(&sweep.lock)
  1500  }
  1501  
  1502  // gcResetMarkState resets global state prior to marking (concurrent
  1503  // or STW) and resets the stack scan state of all Gs.
  1504  //
  1505  // This is safe to do without the world stopped because any Gs created
  1506  // during or after this will start out in the reset state.
  1507  //
  1508  // gcResetMarkState must be called on the system stack because it acquires
  1509  // the heap lock. See mheap for details.
  1510  //
  1511  //go:systemstack
  1512  func gcResetMarkState() {
  1513  	// This may be called during a concurrent phase, so lock to make sure
  1514  	// allgs doesn't change.
  1515  	forEachG(func(gp *g) {
  1516  		gp.gcscandone = false // set to true in gcphasework
  1517  		gp.gcAssistBytes = 0
  1518  	})
  1519  
  1520  	// Clear page marks. This is just 1MB per 64GB of heap, so the
  1521  	// time here is pretty trivial.
  1522  	lock(&mheap_.lock)
  1523  	arenas := mheap_.allArenas
  1524  	unlock(&mheap_.lock)
  1525  	for _, ai := range arenas {
  1526  		ha := mheap_.arenas[ai.l1()][ai.l2()]
  1527  		for i := range ha.pageMarks {
  1528  			ha.pageMarks[i] = 0
  1529  		}
  1530  	}
  1531  
  1532  	work.bytesMarked = 0
  1533  	work.initialHeapLive = atomic.Load64(&gcController.heapLive)
  1534  }
  1535  
  1536  // Hooks for other packages
  1537  
  1538  var poolcleanup func()
  1539  
  1540  //go:linkname sync_runtime_registerPoolCleanup sync.runtime_registerPoolCleanup
  1541  func sync_runtime_registerPoolCleanup(f func()) {
  1542  	poolcleanup = f
  1543  }
  1544  
  1545  func clearpools() {
  1546  	// clear sync.Pools
  1547  	if poolcleanup != nil {
  1548  		poolcleanup()
  1549  	}
  1550  
  1551  	// Clear central sudog cache.
  1552  	// Leave per-P caches alone, they have strictly bounded size.
  1553  	// Disconnect cached list before dropping it on the floor,
  1554  	// so that a dangling ref to one entry does not pin all of them.
  1555  	lock(&sched.sudoglock)
  1556  	var sg, sgnext *sudog
  1557  	for sg = sched.sudogcache; sg != nil; sg = sgnext {
  1558  		sgnext = sg.next
  1559  		sg.next = nil
  1560  	}
  1561  	sched.sudogcache = nil
  1562  	unlock(&sched.sudoglock)
  1563  
  1564  	// Clear central defer pool.
  1565  	// Leave per-P pools alone, they have strictly bounded size.
  1566  	lock(&sched.deferlock)
  1567  	// disconnect cached list before dropping it on the floor,
  1568  	// so that a dangling ref to one entry does not pin all of them.
  1569  	var d, dlink *_defer
  1570  	for d = sched.deferpool; d != nil; d = dlink {
  1571  		dlink = d.link
  1572  		d.link = nil
  1573  	}
  1574  	sched.deferpool = nil
  1575  	unlock(&sched.deferlock)
  1576  }
  1577  
  1578  // Timing
  1579  
  1580  // itoaDiv formats val/(10**dec) into buf.
  1581  func itoaDiv(buf []byte, val uint64, dec int) []byte {
  1582  	i := len(buf) - 1
  1583  	idec := i - dec
  1584  	for val >= 10 || i >= idec {
  1585  		buf[i] = byte(val%10 + '0')
  1586  		i--
  1587  		if i == idec {
  1588  			buf[i] = '.'
  1589  			i--
  1590  		}
  1591  		val /= 10
  1592  	}
  1593  	buf[i] = byte(val + '0')
  1594  	return buf[i:]
  1595  }
  1596  
  1597  // fmtNSAsMS nicely formats ns nanoseconds as milliseconds.
  1598  func fmtNSAsMS(buf []byte, ns uint64) []byte {
  1599  	if ns >= 10e6 {
  1600  		// Format as whole milliseconds.
  1601  		return itoaDiv(buf, ns/1e6, 0)
  1602  	}
  1603  	// Format two digits of precision, with at most three decimal places.
  1604  	x := ns / 1e3
  1605  	if x == 0 {
  1606  		buf[0] = '0'
  1607  		return buf[:1]
  1608  	}
  1609  	dec := 3
  1610  	for x >= 100 {
  1611  		x /= 10
  1612  		dec--
  1613  	}
  1614  	return itoaDiv(buf, x, dec)
  1615  }
  1616  
  1617  // Helpers for testing GC.
  1618  
  1619  // gcTestMoveStackOnNextCall causes the stack to be moved on a call
  1620  // immediately following the call to this. It may not work correctly
  1621  // if any other work appears after this call (such as returning).
  1622  // Typically the following call should be marked go:noinline so it
  1623  // performs a stack check.
  1624  //
  1625  // In rare cases this may not cause the stack to move, specifically if
  1626  // there's a preemption between this call and the next.
  1627  func gcTestMoveStackOnNextCall() {
  1628  	gp := getg()
  1629  	gp.stackguard0 = stackForceMove
  1630  }
  1631  
  1632  // gcTestIsReachable performs a GC and returns a bit set where bit i
  1633  // is set if ptrs[i] is reachable.
  1634  func gcTestIsReachable(ptrs ...unsafe.Pointer) (mask uint64) {
  1635  	// This takes the pointers as unsafe.Pointers in order to keep
  1636  	// them live long enough for us to attach specials. After
  1637  	// that, we drop our references to them.
  1638  
  1639  	if len(ptrs) > 64 {
  1640  		panic("too many pointers for uint64 mask")
  1641  	}
  1642  
  1643  	// Block GC while we attach specials and drop our references
  1644  	// to ptrs. Otherwise, if a GC is in progress, it could mark
  1645  	// them reachable via this function before we have a chance to
  1646  	// drop them.
  1647  	semacquire(&gcsema)
  1648  
  1649  	// Create reachability specials for ptrs.
  1650  	specials := make([]*specialReachable, len(ptrs))
  1651  	for i, p := range ptrs {
  1652  		lock(&mheap_.speciallock)
  1653  		s := (*specialReachable)(mheap_.specialReachableAlloc.alloc())
  1654  		unlock(&mheap_.speciallock)
  1655  		s.special.kind = _KindSpecialReachable
  1656  		if !addspecial(p, &s.special) {
  1657  			throw("already have a reachable special (duplicate pointer?)")
  1658  		}
  1659  		specials[i] = s
  1660  		// Make sure we don't retain ptrs.
  1661  		ptrs[i] = nil
  1662  	}
  1663  
  1664  	semrelease(&gcsema)
  1665  
  1666  	// Force a full GC and sweep.
  1667  	GC()
  1668  
  1669  	// Process specials.
  1670  	for i, s := range specials {
  1671  		if !s.done {
  1672  			printlock()
  1673  			println("runtime: object", i, "was not swept")
  1674  			throw("IsReachable failed")
  1675  		}
  1676  		if s.reachable {
  1677  			mask |= 1 << i
  1678  		}
  1679  		lock(&mheap_.speciallock)
  1680  		mheap_.specialReachableAlloc.free(unsafe.Pointer(s))
  1681  		unlock(&mheap_.speciallock)
  1682  	}
  1683  
  1684  	return mask
  1685  }
  1686  
  1687  // gcTestPointerClass returns the category of what p points to, one of:
  1688  // "heap", "stack", "data", "bss", "other". This is useful for checking
  1689  // that a test is doing what it's intended to do.
  1690  //
  1691  // This is nosplit simply to avoid extra pointer shuffling that may
  1692  // complicate a test.
  1693  //
  1694  //go:nosplit
  1695  func gcTestPointerClass(p unsafe.Pointer) string {
  1696  	p2 := uintptr(noescape(p))
  1697  	gp := getg()
  1698  	if gp.stack.lo <= p2 && p2 < gp.stack.hi {
  1699  		return "stack"
  1700  	}
  1701  	if base, _, _ := findObject(p2, 0, 0); base != 0 {
  1702  		return "heap"
  1703  	}
  1704  	for _, datap := range activeModules() {
  1705  		if datap.data <= p2 && p2 < datap.edata || datap.noptrdata <= p2 && p2 < datap.enoptrdata {
  1706  			return "data"
  1707  		}
  1708  		if datap.bss <= p2 && p2 < datap.ebss || datap.noptrbss <= p2 && p2 <= datap.enoptrbss {
  1709  			return "bss"
  1710  		}
  1711  	}
  1712  	KeepAlive(p)
  1713  	return "other"
  1714  }
  1715  

View as plain text