Source file src/runtime/mgcmark.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: marking and scanning
     6  
     7  package runtime
     8  
     9  import (
    10  	"internal/abi"
    11  	"internal/goarch"
    12  	"internal/runtime/atomic"
    13  	"internal/runtime/sys"
    14  	"unsafe"
    15  )
    16  
    17  const (
    18  	fixedRootFinalizers = iota
    19  	fixedRootFreeGStacks
    20  	fixedRootCount
    21  
    22  	// rootBlockBytes is the number of bytes to scan per data or
    23  	// BSS root.
    24  	rootBlockBytes = 256 << 10
    25  
    26  	// maxObletBytes is the maximum bytes of an object to scan at
    27  	// once. Larger objects will be split up into "oblets" of at
    28  	// most this size. Since we can scan 1–2 MB/ms, 128 KB bounds
    29  	// scan preemption at ~100 µs.
    30  	//
    31  	// This must be > _MaxSmallSize so that the object base is the
    32  	// span base.
    33  	maxObletBytes = 128 << 10
    34  
    35  	// drainCheckThreshold specifies how many units of work to do
    36  	// between self-preemption checks in gcDrain. Assuming a scan
    37  	// rate of 1 MB/ms, this is ~100 µs. Lower values have higher
    38  	// overhead in the scan loop (the scheduler check may perform
    39  	// a syscall, so its overhead is nontrivial). Higher values
    40  	// make the system less responsive to incoming work.
    41  	drainCheckThreshold = 100000
    42  
    43  	// pagesPerSpanRoot indicates how many pages to scan from a span root
    44  	// at a time. Used by special root marking.
    45  	//
    46  	// Higher values improve throughput by increasing locality, but
    47  	// increase the minimum latency of a marking operation.
    48  	//
    49  	// Must be a multiple of the pageInUse bitmap element size and
    50  	// must also evenly divide pagesPerArena.
    51  	pagesPerSpanRoot = 512
    52  )
    53  
    54  // gcMarkRootPrepare queues root scanning jobs (stacks, globals, and
    55  // some miscellany) and initializes scanning-related state.
    56  //
    57  // The world must be stopped.
    58  func gcMarkRootPrepare() {
    59  	assertWorldStopped()
    60  
    61  	// Compute how many data and BSS root blocks there are.
    62  	nBlocks := func(bytes uintptr) int {
    63  		return int(divRoundUp(bytes, rootBlockBytes))
    64  	}
    65  
    66  	work.nDataRoots = 0
    67  	work.nBSSRoots = 0
    68  
    69  	// Scan globals.
    70  	for _, datap := range activeModules() {
    71  		nDataRoots := nBlocks(datap.edata - datap.data)
    72  		if nDataRoots > work.nDataRoots {
    73  			work.nDataRoots = nDataRoots
    74  		}
    75  
    76  		nBSSRoots := nBlocks(datap.ebss - datap.bss)
    77  		if nBSSRoots > work.nBSSRoots {
    78  			work.nBSSRoots = nBSSRoots
    79  		}
    80  	}
    81  
    82  	// Scan span roots for finalizer specials.
    83  	//
    84  	// We depend on addfinalizer to mark objects that get
    85  	// finalizers after root marking.
    86  	//
    87  	// We're going to scan the whole heap (that was available at the time the
    88  	// mark phase started, i.e. markArenas) for in-use spans which have specials.
    89  	//
    90  	// Break up the work into arenas, and further into chunks.
    91  	//
    92  	// Snapshot allArenas as markArenas. This snapshot is safe because allArenas
    93  	// is append-only.
    94  	mheap_.markArenas = mheap_.allArenas[:len(mheap_.allArenas):len(mheap_.allArenas)]
    95  	work.nSpanRoots = len(mheap_.markArenas) * (pagesPerArena / pagesPerSpanRoot)
    96  
    97  	// Scan stacks.
    98  	//
    99  	// Gs may be created after this point, but it's okay that we
   100  	// ignore them because they begin life without any roots, so
   101  	// there's nothing to scan, and any roots they create during
   102  	// the concurrent phase will be caught by the write barrier.
   103  	work.stackRoots = allGsSnapshot()
   104  	work.nStackRoots = len(work.stackRoots)
   105  
   106  	work.markrootNext = 0
   107  	work.markrootJobs = uint32(fixedRootCount + work.nDataRoots + work.nBSSRoots + work.nSpanRoots + work.nStackRoots)
   108  
   109  	// Calculate base indexes of each root type
   110  	work.baseData = uint32(fixedRootCount)
   111  	work.baseBSS = work.baseData + uint32(work.nDataRoots)
   112  	work.baseSpans = work.baseBSS + uint32(work.nBSSRoots)
   113  	work.baseStacks = work.baseSpans + uint32(work.nSpanRoots)
   114  	work.baseEnd = work.baseStacks + uint32(work.nStackRoots)
   115  }
   116  
   117  // gcMarkRootCheck checks that all roots have been scanned. It is
   118  // purely for debugging.
   119  func gcMarkRootCheck() {
   120  	if work.markrootNext < work.markrootJobs {
   121  		print(work.markrootNext, " of ", work.markrootJobs, " markroot jobs done\n")
   122  		throw("left over markroot jobs")
   123  	}
   124  
   125  	// Check that stacks have been scanned.
   126  	//
   127  	// We only check the first nStackRoots Gs that we should have scanned.
   128  	// Since we don't care about newer Gs (see comment in
   129  	// gcMarkRootPrepare), no locking is required.
   130  	i := 0
   131  	forEachGRace(func(gp *g) {
   132  		if i >= work.nStackRoots {
   133  			return
   134  		}
   135  
   136  		if !gp.gcscandone {
   137  			println("gp", gp, "goid", gp.goid,
   138  				"status", readgstatus(gp),
   139  				"gcscandone", gp.gcscandone)
   140  			throw("scan missed a g")
   141  		}
   142  
   143  		i++
   144  	})
   145  }
   146  
   147  // ptrmask for an allocation containing a single pointer.
   148  var oneptrmask = [...]uint8{1}
   149  
   150  // markroot scans the i'th root.
   151  //
   152  // Preemption must be disabled (because this uses a gcWork).
   153  //
   154  // Returns the amount of GC work credit produced by the operation.
   155  // If flushBgCredit is true, then that credit is also flushed
   156  // to the background credit pool.
   157  //
   158  // nowritebarrier is only advisory here.
   159  //
   160  //go:nowritebarrier
   161  func markroot(gcw *gcWork, i uint32, flushBgCredit bool) int64 {
   162  	// Note: if you add a case here, please also update heapdump.go:dumproots.
   163  	var workDone int64
   164  	var workCounter *atomic.Int64
   165  	switch {
   166  	case work.baseData <= i && i < work.baseBSS:
   167  		workCounter = &gcController.globalsScanWork
   168  		for _, datap := range activeModules() {
   169  			workDone += markrootBlock(datap.data, datap.edata-datap.data, datap.gcdatamask.bytedata, gcw, int(i-work.baseData))
   170  		}
   171  
   172  	case work.baseBSS <= i && i < work.baseSpans:
   173  		workCounter = &gcController.globalsScanWork
   174  		for _, datap := range activeModules() {
   175  			workDone += markrootBlock(datap.bss, datap.ebss-datap.bss, datap.gcbssmask.bytedata, gcw, int(i-work.baseBSS))
   176  		}
   177  
   178  	case i == fixedRootFinalizers:
   179  		for fb := allfin; fb != nil; fb = fb.alllink {
   180  			cnt := uintptr(atomic.Load(&fb.cnt))
   181  			// Finalizers that contain cleanups only have fn set. None of the other
   182  			// fields are necessary.
   183  			scanblock(uintptr(unsafe.Pointer(&fb.fin[0])), cnt*unsafe.Sizeof(fb.fin[0]), &finptrmask[0], gcw, nil)
   184  		}
   185  
   186  	case i == fixedRootFreeGStacks:
   187  		// Switch to the system stack so we can call
   188  		// stackfree.
   189  		systemstack(markrootFreeGStacks)
   190  
   191  	case work.baseSpans <= i && i < work.baseStacks:
   192  		// mark mspan.specials
   193  		markrootSpans(gcw, int(i-work.baseSpans))
   194  
   195  	default:
   196  		// the rest is scanning goroutine stacks
   197  		workCounter = &gcController.stackScanWork
   198  		if i < work.baseStacks || work.baseEnd <= i {
   199  			printlock()
   200  			print("runtime: markroot index ", i, " not in stack roots range [", work.baseStacks, ", ", work.baseEnd, ")\n")
   201  			throw("markroot: bad index")
   202  		}
   203  		gp := work.stackRoots[i-work.baseStacks]
   204  
   205  		// remember when we've first observed the G blocked
   206  		// needed only to output in traceback
   207  		status := readgstatus(gp) // We are not in a scan state
   208  		if (status == _Gwaiting || status == _Gsyscall) && gp.waitsince == 0 {
   209  			gp.waitsince = work.tstart
   210  		}
   211  
   212  		// scanstack must be done on the system stack in case
   213  		// we're trying to scan our own stack.
   214  		systemstack(func() {
   215  			// If this is a self-scan, put the user G in
   216  			// _Gwaiting to prevent self-deadlock. It may
   217  			// already be in _Gwaiting if this is a mark
   218  			// worker or we're in mark termination.
   219  			userG := getg().m.curg
   220  			selfScan := gp == userG && readgstatus(userG) == _Grunning
   221  			if selfScan {
   222  				casGToWaitingForGC(userG, _Grunning, waitReasonGarbageCollectionScan)
   223  			}
   224  
   225  			// TODO: suspendG blocks (and spins) until gp
   226  			// stops, which may take a while for
   227  			// running goroutines. Consider doing this in
   228  			// two phases where the first is non-blocking:
   229  			// we scan the stacks we can and ask running
   230  			// goroutines to scan themselves; and the
   231  			// second blocks.
   232  			stopped := suspendG(gp)
   233  			if stopped.dead {
   234  				gp.gcscandone = true
   235  				return
   236  			}
   237  			if gp.gcscandone {
   238  				throw("g already scanned")
   239  			}
   240  			workDone += scanstack(gp, gcw)
   241  			gp.gcscandone = true
   242  			resumeG(stopped)
   243  
   244  			if selfScan {
   245  				casgstatus(userG, _Gwaiting, _Grunning)
   246  			}
   247  		})
   248  	}
   249  	if workCounter != nil && workDone != 0 {
   250  		workCounter.Add(workDone)
   251  		if flushBgCredit {
   252  			gcFlushBgCredit(workDone)
   253  		}
   254  	}
   255  	return workDone
   256  }
   257  
   258  // markrootBlock scans the shard'th shard of the block of memory [b0,
   259  // b0+n0), with the given pointer mask.
   260  //
   261  // Returns the amount of work done.
   262  //
   263  //go:nowritebarrier
   264  func markrootBlock(b0, n0 uintptr, ptrmask0 *uint8, gcw *gcWork, shard int) int64 {
   265  	if rootBlockBytes%(8*goarch.PtrSize) != 0 {
   266  		// This is necessary to pick byte offsets in ptrmask0.
   267  		throw("rootBlockBytes must be a multiple of 8*ptrSize")
   268  	}
   269  
   270  	// Note that if b0 is toward the end of the address space,
   271  	// then b0 + rootBlockBytes might wrap around.
   272  	// These tests are written to avoid any possible overflow.
   273  	off := uintptr(shard) * rootBlockBytes
   274  	if off >= n0 {
   275  		return 0
   276  	}
   277  	b := b0 + off
   278  	ptrmask := (*uint8)(add(unsafe.Pointer(ptrmask0), uintptr(shard)*(rootBlockBytes/(8*goarch.PtrSize))))
   279  	n := uintptr(rootBlockBytes)
   280  	if off+n > n0 {
   281  		n = n0 - off
   282  	}
   283  
   284  	// Scan this shard.
   285  	scanblock(b, n, ptrmask, gcw, nil)
   286  	return int64(n)
   287  }
   288  
   289  // markrootFreeGStacks frees stacks of dead Gs.
   290  //
   291  // This does not free stacks of dead Gs cached on Ps, but having a few
   292  // cached stacks around isn't a problem.
   293  func markrootFreeGStacks() {
   294  	// Take list of dead Gs with stacks.
   295  	lock(&sched.gFree.lock)
   296  	list := sched.gFree.stack
   297  	sched.gFree.stack = gList{}
   298  	unlock(&sched.gFree.lock)
   299  	if list.empty() {
   300  		return
   301  	}
   302  
   303  	// Free stacks.
   304  	q := gQueue{list.head, list.head}
   305  	for gp := list.head.ptr(); gp != nil; gp = gp.schedlink.ptr() {
   306  		stackfree(gp.stack)
   307  		gp.stack.lo = 0
   308  		gp.stack.hi = 0
   309  		// Manipulate the queue directly since the Gs are
   310  		// already all linked the right way.
   311  		q.tail.set(gp)
   312  	}
   313  
   314  	// Put Gs back on the free list.
   315  	lock(&sched.gFree.lock)
   316  	sched.gFree.noStack.pushAll(q)
   317  	unlock(&sched.gFree.lock)
   318  }
   319  
   320  // markrootSpans marks roots for one shard of markArenas.
   321  //
   322  //go:nowritebarrier
   323  func markrootSpans(gcw *gcWork, shard int) {
   324  	// Objects with finalizers have two GC-related invariants:
   325  	//
   326  	// 1) Everything reachable from the object must be marked.
   327  	// This ensures that when we pass the object to its finalizer,
   328  	// everything the finalizer can reach will be retained.
   329  	//
   330  	// 2) Finalizer specials (which are not in the garbage
   331  	// collected heap) are roots. In practice, this means the fn
   332  	// field must be scanned.
   333  	//
   334  	// Objects with weak handles have only one invariant related
   335  	// to this function: weak handle specials (which are not in the
   336  	// garbage collected heap) are roots. In practice, this means
   337  	// the handle field must be scanned. Note that the value the
   338  	// handle pointer referenced does *not* need to be scanned. See
   339  	// the definition of specialWeakHandle for details.
   340  	sg := mheap_.sweepgen
   341  
   342  	// Find the arena and page index into that arena for this shard.
   343  	ai := mheap_.markArenas[shard/(pagesPerArena/pagesPerSpanRoot)]
   344  	ha := mheap_.arenas[ai.l1()][ai.l2()]
   345  	arenaPage := uint(uintptr(shard) * pagesPerSpanRoot % pagesPerArena)
   346  
   347  	// Construct slice of bitmap which we'll iterate over.
   348  	specialsbits := ha.pageSpecials[arenaPage/8:]
   349  	specialsbits = specialsbits[:pagesPerSpanRoot/8]
   350  	for i := range specialsbits {
   351  		// Find set bits, which correspond to spans with specials.
   352  		specials := atomic.Load8(&specialsbits[i])
   353  		if specials == 0 {
   354  			continue
   355  		}
   356  		for j := uint(0); j < 8; j++ {
   357  			if specials&(1<<j) == 0 {
   358  				continue
   359  			}
   360  			// Find the span for this bit.
   361  			//
   362  			// This value is guaranteed to be non-nil because having
   363  			// specials implies that the span is in-use, and since we're
   364  			// currently marking we can be sure that we don't have to worry
   365  			// about the span being freed and re-used.
   366  			s := ha.spans[arenaPage+uint(i)*8+j]
   367  
   368  			// The state must be mSpanInUse if the specials bit is set, so
   369  			// sanity check that.
   370  			if state := s.state.get(); state != mSpanInUse {
   371  				print("s.state = ", state, "\n")
   372  				throw("non in-use span found with specials bit set")
   373  			}
   374  			// Check that this span was swept (it may be cached or uncached).
   375  			if !useCheckmark && !(s.sweepgen == sg || s.sweepgen == sg+3) {
   376  				// sweepgen was updated (+2) during non-checkmark GC pass
   377  				print("sweep ", s.sweepgen, " ", sg, "\n")
   378  				throw("gc: unswept span")
   379  			}
   380  
   381  			// Lock the specials to prevent a special from being
   382  			// removed from the list while we're traversing it.
   383  			lock(&s.speciallock)
   384  			for sp := s.specials; sp != nil; sp = sp.next {
   385  				switch sp.kind {
   386  				case _KindSpecialFinalizer:
   387  					// don't mark finalized object, but scan it so we
   388  					// retain everything it points to.
   389  					spf := (*specialfinalizer)(unsafe.Pointer(sp))
   390  					// A finalizer can be set for an inner byte of an object, find object beginning.
   391  					p := s.base() + uintptr(spf.special.offset)/s.elemsize*s.elemsize
   392  
   393  					// Mark everything that can be reached from
   394  					// the object (but *not* the object itself or
   395  					// we'll never collect it).
   396  					if !s.spanclass.noscan() {
   397  						scanobject(p, gcw)
   398  					}
   399  
   400  					// The special itself is a root.
   401  					scanblock(uintptr(unsafe.Pointer(&spf.fn)), goarch.PtrSize, &oneptrmask[0], gcw, nil)
   402  				case _KindSpecialWeakHandle:
   403  					// The special itself is a root.
   404  					spw := (*specialWeakHandle)(unsafe.Pointer(sp))
   405  					scanblock(uintptr(unsafe.Pointer(&spw.handle)), goarch.PtrSize, &oneptrmask[0], gcw, nil)
   406  				case _KindSpecialCleanup:
   407  					spc := (*specialCleanup)(unsafe.Pointer(sp))
   408  					// The special itself is a root.
   409  					scanblock(uintptr(unsafe.Pointer(&spc.fn)), goarch.PtrSize, &oneptrmask[0], gcw, nil)
   410  				}
   411  			}
   412  			unlock(&s.speciallock)
   413  		}
   414  	}
   415  }
   416  
   417  // gcAssistAlloc performs GC work to make gp's assist debt positive.
   418  // gp must be the calling user goroutine.
   419  //
   420  // This must be called with preemption enabled.
   421  func gcAssistAlloc(gp *g) {
   422  	// Don't assist in non-preemptible contexts. These are
   423  	// generally fragile and won't allow the assist to block.
   424  	if getg() == gp.m.g0 {
   425  		return
   426  	}
   427  	if mp := getg().m; mp.locks > 0 || mp.preemptoff != "" {
   428  		return
   429  	}
   430  
   431  	if gp := getg(); gp.syncGroup != nil {
   432  		// Disassociate the G from its synctest bubble while allocating.
   433  		// This is less elegant than incrementing the group's active count,
   434  		// but avoids any contamination between GC assist and synctest.
   435  		sg := gp.syncGroup
   436  		gp.syncGroup = nil
   437  		defer func() {
   438  			gp.syncGroup = sg
   439  		}()
   440  	}
   441  
   442  	// This extremely verbose boolean indicates whether we've
   443  	// entered mark assist from the perspective of the tracer.
   444  	//
   445  	// In the tracer, this is just before we call gcAssistAlloc1
   446  	// *regardless* of whether tracing is enabled. This is because
   447  	// the tracer allows for tracing to begin (and advance
   448  	// generations) in the middle of a GC mark phase, so we need to
   449  	// record some state so that the tracer can pick it up to ensure
   450  	// a consistent trace result.
   451  	//
   452  	// TODO(mknyszek): Hide the details of inMarkAssist in tracer
   453  	// functions and simplify all the state tracking. This is a lot.
   454  	enteredMarkAssistForTracing := false
   455  retry:
   456  	if gcCPULimiter.limiting() {
   457  		// If the CPU limiter is enabled, intentionally don't
   458  		// assist to reduce the amount of CPU time spent in the GC.
   459  		if enteredMarkAssistForTracing {
   460  			trace := traceAcquire()
   461  			if trace.ok() {
   462  				trace.GCMarkAssistDone()
   463  				// Set this *after* we trace the end to make sure
   464  				// that we emit an in-progress event if this is
   465  				// the first event for the goroutine in the trace
   466  				// or trace generation. Also, do this between
   467  				// acquire/release because this is part of the
   468  				// goroutine's trace state, and it must be atomic
   469  				// with respect to the tracer.
   470  				gp.inMarkAssist = false
   471  				traceRelease(trace)
   472  			} else {
   473  				// This state is tracked even if tracing isn't enabled.
   474  				// It's only used by the new tracer.
   475  				// See the comment on enteredMarkAssistForTracing.
   476  				gp.inMarkAssist = false
   477  			}
   478  		}
   479  		return
   480  	}
   481  	// Compute the amount of scan work we need to do to make the
   482  	// balance positive. When the required amount of work is low,
   483  	// we over-assist to build up credit for future allocations
   484  	// and amortize the cost of assisting.
   485  	assistWorkPerByte := gcController.assistWorkPerByte.Load()
   486  	assistBytesPerWork := gcController.assistBytesPerWork.Load()
   487  	debtBytes := -gp.gcAssistBytes
   488  	scanWork := int64(assistWorkPerByte * float64(debtBytes))
   489  	if scanWork < gcOverAssistWork {
   490  		scanWork = gcOverAssistWork
   491  		debtBytes = int64(assistBytesPerWork * float64(scanWork))
   492  	}
   493  
   494  	// Steal as much credit as we can from the background GC's
   495  	// scan credit. This is racy and may drop the background
   496  	// credit below 0 if two mutators steal at the same time. This
   497  	// will just cause steals to fail until credit is accumulated
   498  	// again, so in the long run it doesn't really matter, but we
   499  	// do have to handle the negative credit case.
   500  	bgScanCredit := gcController.bgScanCredit.Load()
   501  	stolen := int64(0)
   502  	if bgScanCredit > 0 {
   503  		if bgScanCredit < scanWork {
   504  			stolen = bgScanCredit
   505  			gp.gcAssistBytes += 1 + int64(assistBytesPerWork*float64(stolen))
   506  		} else {
   507  			stolen = scanWork
   508  			gp.gcAssistBytes += debtBytes
   509  		}
   510  		gcController.bgScanCredit.Add(-stolen)
   511  
   512  		scanWork -= stolen
   513  
   514  		if scanWork == 0 {
   515  			// We were able to steal all of the credit we
   516  			// needed.
   517  			if enteredMarkAssistForTracing {
   518  				trace := traceAcquire()
   519  				if trace.ok() {
   520  					trace.GCMarkAssistDone()
   521  					// Set this *after* we trace the end to make sure
   522  					// that we emit an in-progress event if this is
   523  					// the first event for the goroutine in the trace
   524  					// or trace generation. Also, do this between
   525  					// acquire/release because this is part of the
   526  					// goroutine's trace state, and it must be atomic
   527  					// with respect to the tracer.
   528  					gp.inMarkAssist = false
   529  					traceRelease(trace)
   530  				} else {
   531  					// This state is tracked even if tracing isn't enabled.
   532  					// It's only used by the new tracer.
   533  					// See the comment on enteredMarkAssistForTracing.
   534  					gp.inMarkAssist = false
   535  				}
   536  			}
   537  			return
   538  		}
   539  	}
   540  	if !enteredMarkAssistForTracing {
   541  		trace := traceAcquire()
   542  		if trace.ok() {
   543  			trace.GCMarkAssistStart()
   544  			// Set this *after* we trace the start, otherwise we may
   545  			// emit an in-progress event for an assist we're about to start.
   546  			gp.inMarkAssist = true
   547  			traceRelease(trace)
   548  		} else {
   549  			gp.inMarkAssist = true
   550  		}
   551  		// In the new tracer, set enter mark assist tracing if we
   552  		// ever pass this point, because we must manage inMarkAssist
   553  		// correctly.
   554  		//
   555  		// See the comment on enteredMarkAssistForTracing.
   556  		enteredMarkAssistForTracing = true
   557  	}
   558  
   559  	// Perform assist work
   560  	systemstack(func() {
   561  		gcAssistAlloc1(gp, scanWork)
   562  		// The user stack may have moved, so this can't touch
   563  		// anything on it until it returns from systemstack.
   564  	})
   565  
   566  	completed := gp.param != nil
   567  	gp.param = nil
   568  	if completed {
   569  		gcMarkDone()
   570  	}
   571  
   572  	if gp.gcAssistBytes < 0 {
   573  		// We were unable steal enough credit or perform
   574  		// enough work to pay off the assist debt. We need to
   575  		// do one of these before letting the mutator allocate
   576  		// more to prevent over-allocation.
   577  		//
   578  		// If this is because we were preempted, reschedule
   579  		// and try some more.
   580  		if gp.preempt {
   581  			Gosched()
   582  			goto retry
   583  		}
   584  
   585  		// Add this G to an assist queue and park. When the GC
   586  		// has more background credit, it will satisfy queued
   587  		// assists before flushing to the global credit pool.
   588  		//
   589  		// Note that this does *not* get woken up when more
   590  		// work is added to the work list. The theory is that
   591  		// there wasn't enough work to do anyway, so we might
   592  		// as well let background marking take care of the
   593  		// work that is available.
   594  		if !gcParkAssist() {
   595  			goto retry
   596  		}
   597  
   598  		// At this point either background GC has satisfied
   599  		// this G's assist debt, or the GC cycle is over.
   600  	}
   601  	if enteredMarkAssistForTracing {
   602  		trace := traceAcquire()
   603  		if trace.ok() {
   604  			trace.GCMarkAssistDone()
   605  			// Set this *after* we trace the end to make sure
   606  			// that we emit an in-progress event if this is
   607  			// the first event for the goroutine in the trace
   608  			// or trace generation. Also, do this between
   609  			// acquire/release because this is part of the
   610  			// goroutine's trace state, and it must be atomic
   611  			// with respect to the tracer.
   612  			gp.inMarkAssist = false
   613  			traceRelease(trace)
   614  		} else {
   615  			// This state is tracked even if tracing isn't enabled.
   616  			// It's only used by the new tracer.
   617  			// See the comment on enteredMarkAssistForTracing.
   618  			gp.inMarkAssist = false
   619  		}
   620  	}
   621  }
   622  
   623  // gcAssistAlloc1 is the part of gcAssistAlloc that runs on the system
   624  // stack. This is a separate function to make it easier to see that
   625  // we're not capturing anything from the user stack, since the user
   626  // stack may move while we're in this function.
   627  //
   628  // gcAssistAlloc1 indicates whether this assist completed the mark
   629  // phase by setting gp.param to non-nil. This can't be communicated on
   630  // the stack since it may move.
   631  //
   632  //go:systemstack
   633  func gcAssistAlloc1(gp *g, scanWork int64) {
   634  	// Clear the flag indicating that this assist completed the
   635  	// mark phase.
   636  	gp.param = nil
   637  
   638  	if atomic.Load(&gcBlackenEnabled) == 0 {
   639  		// The gcBlackenEnabled check in malloc races with the
   640  		// store that clears it but an atomic check in every malloc
   641  		// would be a performance hit.
   642  		// Instead we recheck it here on the non-preemptible system
   643  		// stack to determine if we should perform an assist.
   644  
   645  		// GC is done, so ignore any remaining debt.
   646  		gp.gcAssistBytes = 0
   647  		return
   648  	}
   649  	// Track time spent in this assist. Since we're on the
   650  	// system stack, this is non-preemptible, so we can
   651  	// just measure start and end time.
   652  	//
   653  	// Limiter event tracking might be disabled if we end up here
   654  	// while on a mark worker.
   655  	startTime := nanotime()
   656  	trackLimiterEvent := gp.m.p.ptr().limiterEvent.start(limiterEventMarkAssist, startTime)
   657  
   658  	decnwait := atomic.Xadd(&work.nwait, -1)
   659  	if decnwait == work.nproc {
   660  		println("runtime: work.nwait =", decnwait, "work.nproc=", work.nproc)
   661  		throw("nwait > work.nprocs")
   662  	}
   663  
   664  	// gcDrainN requires the caller to be preemptible.
   665  	casGToWaitingForGC(gp, _Grunning, waitReasonGCAssistMarking)
   666  
   667  	// drain own cached work first in the hopes that it
   668  	// will be more cache friendly.
   669  	gcw := &getg().m.p.ptr().gcw
   670  	workDone := gcDrainN(gcw, scanWork)
   671  
   672  	casgstatus(gp, _Gwaiting, _Grunning)
   673  
   674  	// Record that we did this much scan work.
   675  	//
   676  	// Back out the number of bytes of assist credit that
   677  	// this scan work counts for. The "1+" is a poor man's
   678  	// round-up, to ensure this adds credit even if
   679  	// assistBytesPerWork is very low.
   680  	assistBytesPerWork := gcController.assistBytesPerWork.Load()
   681  	gp.gcAssistBytes += 1 + int64(assistBytesPerWork*float64(workDone))
   682  
   683  	// If this is the last worker and we ran out of work,
   684  	// signal a completion point.
   685  	incnwait := atomic.Xadd(&work.nwait, +1)
   686  	if incnwait > work.nproc {
   687  		println("runtime: work.nwait=", incnwait,
   688  			"work.nproc=", work.nproc)
   689  		throw("work.nwait > work.nproc")
   690  	}
   691  
   692  	if incnwait == work.nproc && !gcMarkWorkAvailable(nil) {
   693  		// This has reached a background completion point. Set
   694  		// gp.param to a non-nil value to indicate this. It
   695  		// doesn't matter what we set it to (it just has to be
   696  		// a valid pointer).
   697  		gp.param = unsafe.Pointer(gp)
   698  	}
   699  	now := nanotime()
   700  	duration := now - startTime
   701  	pp := gp.m.p.ptr()
   702  	pp.gcAssistTime += duration
   703  	if trackLimiterEvent {
   704  		pp.limiterEvent.stop(limiterEventMarkAssist, now)
   705  	}
   706  	if pp.gcAssistTime > gcAssistTimeSlack {
   707  		gcController.assistTime.Add(pp.gcAssistTime)
   708  		gcCPULimiter.update(now)
   709  		pp.gcAssistTime = 0
   710  	}
   711  }
   712  
   713  // gcWakeAllAssists wakes all currently blocked assists. This is used
   714  // at the end of a GC cycle. gcBlackenEnabled must be false to prevent
   715  // new assists from going to sleep after this point.
   716  func gcWakeAllAssists() {
   717  	lock(&work.assistQueue.lock)
   718  	list := work.assistQueue.q.popList()
   719  	injectglist(&list)
   720  	unlock(&work.assistQueue.lock)
   721  }
   722  
   723  // gcParkAssist puts the current goroutine on the assist queue and parks.
   724  //
   725  // gcParkAssist reports whether the assist is now satisfied. If it
   726  // returns false, the caller must retry the assist.
   727  func gcParkAssist() bool {
   728  	lock(&work.assistQueue.lock)
   729  	// If the GC cycle finished while we were getting the lock,
   730  	// exit the assist. The cycle can't finish while we hold the
   731  	// lock.
   732  	if atomic.Load(&gcBlackenEnabled) == 0 {
   733  		unlock(&work.assistQueue.lock)
   734  		return true
   735  	}
   736  
   737  	gp := getg()
   738  	oldList := work.assistQueue.q
   739  	work.assistQueue.q.pushBack(gp)
   740  
   741  	// Recheck for background credit now that this G is in
   742  	// the queue, but can still back out. This avoids a
   743  	// race in case background marking has flushed more
   744  	// credit since we checked above.
   745  	if gcController.bgScanCredit.Load() > 0 {
   746  		work.assistQueue.q = oldList
   747  		if oldList.tail != 0 {
   748  			oldList.tail.ptr().schedlink.set(nil)
   749  		}
   750  		unlock(&work.assistQueue.lock)
   751  		return false
   752  	}
   753  	// Park.
   754  	goparkunlock(&work.assistQueue.lock, waitReasonGCAssistWait, traceBlockGCMarkAssist, 2)
   755  	return true
   756  }
   757  
   758  // gcFlushBgCredit flushes scanWork units of background scan work
   759  // credit. This first satisfies blocked assists on the
   760  // work.assistQueue and then flushes any remaining credit to
   761  // gcController.bgScanCredit.
   762  //
   763  // Write barriers are disallowed because this is used by gcDrain after
   764  // it has ensured that all work is drained and this must preserve that
   765  // condition.
   766  //
   767  //go:nowritebarrierrec
   768  func gcFlushBgCredit(scanWork int64) {
   769  	if work.assistQueue.q.empty() {
   770  		// Fast path; there are no blocked assists. There's a
   771  		// small window here where an assist may add itself to
   772  		// the blocked queue and park. If that happens, we'll
   773  		// just get it on the next flush.
   774  		gcController.bgScanCredit.Add(scanWork)
   775  		return
   776  	}
   777  
   778  	assistBytesPerWork := gcController.assistBytesPerWork.Load()
   779  	scanBytes := int64(float64(scanWork) * assistBytesPerWork)
   780  
   781  	lock(&work.assistQueue.lock)
   782  	for !work.assistQueue.q.empty() && scanBytes > 0 {
   783  		gp := work.assistQueue.q.pop()
   784  		// Note that gp.gcAssistBytes is negative because gp
   785  		// is in debt. Think carefully about the signs below.
   786  		if scanBytes+gp.gcAssistBytes >= 0 {
   787  			// Satisfy this entire assist debt.
   788  			scanBytes += gp.gcAssistBytes
   789  			gp.gcAssistBytes = 0
   790  			// It's important that we *not* put gp in
   791  			// runnext. Otherwise, it's possible for user
   792  			// code to exploit the GC worker's high
   793  			// scheduler priority to get itself always run
   794  			// before other goroutines and always in the
   795  			// fresh quantum started by GC.
   796  			ready(gp, 0, false)
   797  		} else {
   798  			// Partially satisfy this assist.
   799  			gp.gcAssistBytes += scanBytes
   800  			scanBytes = 0
   801  			// As a heuristic, we move this assist to the
   802  			// back of the queue so that large assists
   803  			// can't clog up the assist queue and
   804  			// substantially delay small assists.
   805  			work.assistQueue.q.pushBack(gp)
   806  			break
   807  		}
   808  	}
   809  
   810  	if scanBytes > 0 {
   811  		// Convert from scan bytes back to work.
   812  		assistWorkPerByte := gcController.assistWorkPerByte.Load()
   813  		scanWork = int64(float64(scanBytes) * assistWorkPerByte)
   814  		gcController.bgScanCredit.Add(scanWork)
   815  	}
   816  	unlock(&work.assistQueue.lock)
   817  }
   818  
   819  // scanstack scans gp's stack, greying all pointers found on the stack.
   820  //
   821  // Returns the amount of scan work performed, but doesn't update
   822  // gcController.stackScanWork or flush any credit. Any background credit produced
   823  // by this function should be flushed by its caller. scanstack itself can't
   824  // safely flush because it may result in trying to wake up a goroutine that
   825  // was just scanned, resulting in a self-deadlock.
   826  //
   827  // scanstack will also shrink the stack if it is safe to do so. If it
   828  // is not, it schedules a stack shrink for the next synchronous safe
   829  // point.
   830  //
   831  // scanstack is marked go:systemstack because it must not be preempted
   832  // while using a workbuf.
   833  //
   834  //go:nowritebarrier
   835  //go:systemstack
   836  func scanstack(gp *g, gcw *gcWork) int64 {
   837  	if readgstatus(gp)&_Gscan == 0 {
   838  		print("runtime:scanstack: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", hex(readgstatus(gp)), "\n")
   839  		throw("scanstack - bad status")
   840  	}
   841  
   842  	switch readgstatus(gp) &^ _Gscan {
   843  	default:
   844  		print("runtime: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n")
   845  		throw("mark - bad status")
   846  	case _Gdead:
   847  		return 0
   848  	case _Grunning:
   849  		print("runtime: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n")
   850  		throw("scanstack: goroutine not stopped")
   851  	case _Grunnable, _Gsyscall, _Gwaiting:
   852  		// ok
   853  	}
   854  
   855  	if gp == getg() {
   856  		throw("can't scan our own stack")
   857  	}
   858  
   859  	// scannedSize is the amount of work we'll be reporting.
   860  	//
   861  	// It is less than the allocated size (which is hi-lo).
   862  	var sp uintptr
   863  	if gp.syscallsp != 0 {
   864  		sp = gp.syscallsp // If in a system call this is the stack pointer (gp.sched.sp can be 0 in this case on Windows).
   865  	} else {
   866  		sp = gp.sched.sp
   867  	}
   868  	scannedSize := gp.stack.hi - sp
   869  
   870  	// Keep statistics for initial stack size calculation.
   871  	// Note that this accumulates the scanned size, not the allocated size.
   872  	p := getg().m.p.ptr()
   873  	p.scannedStackSize += uint64(scannedSize)
   874  	p.scannedStacks++
   875  
   876  	if isShrinkStackSafe(gp) {
   877  		// Shrink the stack if not much of it is being used.
   878  		shrinkstack(gp)
   879  	} else {
   880  		// Otherwise, shrink the stack at the next sync safe point.
   881  		gp.preemptShrink = true
   882  	}
   883  
   884  	var state stackScanState
   885  	state.stack = gp.stack
   886  
   887  	if stackTraceDebug {
   888  		println("stack trace goroutine", gp.goid)
   889  	}
   890  
   891  	if debugScanConservative && gp.asyncSafePoint {
   892  		print("scanning async preempted goroutine ", gp.goid, " stack [", hex(gp.stack.lo), ",", hex(gp.stack.hi), ")\n")
   893  	}
   894  
   895  	// Scan the saved context register. This is effectively a live
   896  	// register that gets moved back and forth between the
   897  	// register and sched.ctxt without a write barrier.
   898  	if gp.sched.ctxt != nil {
   899  		scanblock(uintptr(unsafe.Pointer(&gp.sched.ctxt)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
   900  	}
   901  
   902  	// Scan the stack. Accumulate a list of stack objects.
   903  	var u unwinder
   904  	for u.init(gp, 0); u.valid(); u.next() {
   905  		scanframeworker(&u.frame, &state, gcw)
   906  	}
   907  
   908  	// Find additional pointers that point into the stack from the heap.
   909  	// Currently this includes defers and panics. See also function copystack.
   910  
   911  	// Find and trace other pointers in defer records.
   912  	for d := gp._defer; d != nil; d = d.link {
   913  		if d.fn != nil {
   914  			// Scan the func value, which could be a stack allocated closure.
   915  			// See issue 30453.
   916  			scanblock(uintptr(unsafe.Pointer(&d.fn)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
   917  		}
   918  		if d.link != nil {
   919  			// The link field of a stack-allocated defer record might point
   920  			// to a heap-allocated defer record. Keep that heap record live.
   921  			scanblock(uintptr(unsafe.Pointer(&d.link)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
   922  		}
   923  		// Retain defers records themselves.
   924  		// Defer records might not be reachable from the G through regular heap
   925  		// tracing because the defer linked list might weave between the stack and the heap.
   926  		if d.heap {
   927  			scanblock(uintptr(unsafe.Pointer(&d)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
   928  		}
   929  	}
   930  	if gp._panic != nil {
   931  		// Panics are always stack allocated.
   932  		state.putPtr(uintptr(unsafe.Pointer(gp._panic)), false)
   933  	}
   934  
   935  	// Find and scan all reachable stack objects.
   936  	//
   937  	// The state's pointer queue prioritizes precise pointers over
   938  	// conservative pointers so that we'll prefer scanning stack
   939  	// objects precisely.
   940  	state.buildIndex()
   941  	for {
   942  		p, conservative := state.getPtr()
   943  		if p == 0 {
   944  			break
   945  		}
   946  		obj := state.findObject(p)
   947  		if obj == nil {
   948  			continue
   949  		}
   950  		r := obj.r
   951  		if r == nil {
   952  			// We've already scanned this object.
   953  			continue
   954  		}
   955  		obj.setRecord(nil) // Don't scan it again.
   956  		if stackTraceDebug {
   957  			printlock()
   958  			print("  live stkobj at", hex(state.stack.lo+uintptr(obj.off)), "of size", obj.size)
   959  			if conservative {
   960  				print(" (conservative)")
   961  			}
   962  			println()
   963  			printunlock()
   964  		}
   965  		ptrBytes, gcData := r.gcdata()
   966  		b := state.stack.lo + uintptr(obj.off)
   967  		if conservative {
   968  			scanConservative(b, ptrBytes, gcData, gcw, &state)
   969  		} else {
   970  			scanblock(b, ptrBytes, gcData, gcw, &state)
   971  		}
   972  	}
   973  
   974  	// Deallocate object buffers.
   975  	// (Pointer buffers were all deallocated in the loop above.)
   976  	for state.head != nil {
   977  		x := state.head
   978  		state.head = x.next
   979  		if stackTraceDebug {
   980  			for i := 0; i < x.nobj; i++ {
   981  				obj := &x.obj[i]
   982  				if obj.r == nil { // reachable
   983  					continue
   984  				}
   985  				println("  dead stkobj at", hex(gp.stack.lo+uintptr(obj.off)), "of size", obj.r.size)
   986  				// Note: not necessarily really dead - only reachable-from-ptr dead.
   987  			}
   988  		}
   989  		x.nobj = 0
   990  		putempty((*workbuf)(unsafe.Pointer(x)))
   991  	}
   992  	if state.buf != nil || state.cbuf != nil || state.freeBuf != nil {
   993  		throw("remaining pointer buffers")
   994  	}
   995  	return int64(scannedSize)
   996  }
   997  
   998  // Scan a stack frame: local variables and function arguments/results.
   999  //
  1000  //go:nowritebarrier
  1001  func scanframeworker(frame *stkframe, state *stackScanState, gcw *gcWork) {
  1002  	if _DebugGC > 1 && frame.continpc != 0 {
  1003  		print("scanframe ", funcname(frame.fn), "\n")
  1004  	}
  1005  
  1006  	isAsyncPreempt := frame.fn.valid() && frame.fn.funcID == abi.FuncID_asyncPreempt
  1007  	isDebugCall := frame.fn.valid() && frame.fn.funcID == abi.FuncID_debugCallV2
  1008  	if state.conservative || isAsyncPreempt || isDebugCall {
  1009  		if debugScanConservative {
  1010  			println("conservatively scanning function", funcname(frame.fn), "at PC", hex(frame.continpc))
  1011  		}
  1012  
  1013  		// Conservatively scan the frame. Unlike the precise
  1014  		// case, this includes the outgoing argument space
  1015  		// since we may have stopped while this function was
  1016  		// setting up a call.
  1017  		//
  1018  		// TODO: We could narrow this down if the compiler
  1019  		// produced a single map per function of stack slots
  1020  		// and registers that ever contain a pointer.
  1021  		if frame.varp != 0 {
  1022  			size := frame.varp - frame.sp
  1023  			if size > 0 {
  1024  				scanConservative(frame.sp, size, nil, gcw, state)
  1025  			}
  1026  		}
  1027  
  1028  		// Scan arguments to this frame.
  1029  		if n := frame.argBytes(); n != 0 {
  1030  			// TODO: We could pass the entry argument map
  1031  			// to narrow this down further.
  1032  			scanConservative(frame.argp, n, nil, gcw, state)
  1033  		}
  1034  
  1035  		if isAsyncPreempt || isDebugCall {
  1036  			// This function's frame contained the
  1037  			// registers for the asynchronously stopped
  1038  			// parent frame. Scan the parent
  1039  			// conservatively.
  1040  			state.conservative = true
  1041  		} else {
  1042  			// We only wanted to scan those two frames
  1043  			// conservatively. Clear the flag for future
  1044  			// frames.
  1045  			state.conservative = false
  1046  		}
  1047  		return
  1048  	}
  1049  
  1050  	locals, args, objs := frame.getStackMap(false)
  1051  
  1052  	// Scan local variables if stack frame has been allocated.
  1053  	if locals.n > 0 {
  1054  		size := uintptr(locals.n) * goarch.PtrSize
  1055  		scanblock(frame.varp-size, size, locals.bytedata, gcw, state)
  1056  	}
  1057  
  1058  	// Scan arguments.
  1059  	if args.n > 0 {
  1060  		scanblock(frame.argp, uintptr(args.n)*goarch.PtrSize, args.bytedata, gcw, state)
  1061  	}
  1062  
  1063  	// Add all stack objects to the stack object list.
  1064  	if frame.varp != 0 {
  1065  		// varp is 0 for defers, where there are no locals.
  1066  		// In that case, there can't be a pointer to its args, either.
  1067  		// (And all args would be scanned above anyway.)
  1068  		for i := range objs {
  1069  			obj := &objs[i]
  1070  			off := obj.off
  1071  			base := frame.varp // locals base pointer
  1072  			if off >= 0 {
  1073  				base = frame.argp // arguments and return values base pointer
  1074  			}
  1075  			ptr := base + uintptr(off)
  1076  			if ptr < frame.sp {
  1077  				// object hasn't been allocated in the frame yet.
  1078  				continue
  1079  			}
  1080  			if stackTraceDebug {
  1081  				println("stkobj at", hex(ptr), "of size", obj.size)
  1082  			}
  1083  			state.addObject(ptr, obj)
  1084  		}
  1085  	}
  1086  }
  1087  
  1088  type gcDrainFlags int
  1089  
  1090  const (
  1091  	gcDrainUntilPreempt gcDrainFlags = 1 << iota
  1092  	gcDrainFlushBgCredit
  1093  	gcDrainIdle
  1094  	gcDrainFractional
  1095  )
  1096  
  1097  // gcDrainMarkWorkerIdle is a wrapper for gcDrain that exists to better account
  1098  // mark time in profiles.
  1099  func gcDrainMarkWorkerIdle(gcw *gcWork) {
  1100  	gcDrain(gcw, gcDrainIdle|gcDrainUntilPreempt|gcDrainFlushBgCredit)
  1101  }
  1102  
  1103  // gcDrainMarkWorkerDedicated is a wrapper for gcDrain that exists to better account
  1104  // mark time in profiles.
  1105  func gcDrainMarkWorkerDedicated(gcw *gcWork, untilPreempt bool) {
  1106  	flags := gcDrainFlushBgCredit
  1107  	if untilPreempt {
  1108  		flags |= gcDrainUntilPreempt
  1109  	}
  1110  	gcDrain(gcw, flags)
  1111  }
  1112  
  1113  // gcDrainMarkWorkerFractional is a wrapper for gcDrain that exists to better account
  1114  // mark time in profiles.
  1115  func gcDrainMarkWorkerFractional(gcw *gcWork) {
  1116  	gcDrain(gcw, gcDrainFractional|gcDrainUntilPreempt|gcDrainFlushBgCredit)
  1117  }
  1118  
  1119  // gcDrain scans roots and objects in work buffers, blackening grey
  1120  // objects until it is unable to get more work. It may return before
  1121  // GC is done; it's the caller's responsibility to balance work from
  1122  // other Ps.
  1123  //
  1124  // If flags&gcDrainUntilPreempt != 0, gcDrain returns when g.preempt
  1125  // is set.
  1126  //
  1127  // If flags&gcDrainIdle != 0, gcDrain returns when there is other work
  1128  // to do.
  1129  //
  1130  // If flags&gcDrainFractional != 0, gcDrain self-preempts when
  1131  // pollFractionalWorkerExit() returns true. This implies
  1132  // gcDrainNoBlock.
  1133  //
  1134  // If flags&gcDrainFlushBgCredit != 0, gcDrain flushes scan work
  1135  // credit to gcController.bgScanCredit every gcCreditSlack units of
  1136  // scan work.
  1137  //
  1138  // gcDrain will always return if there is a pending STW or forEachP.
  1139  //
  1140  // Disabling write barriers is necessary to ensure that after we've
  1141  // confirmed that we've drained gcw, that we don't accidentally end
  1142  // up flipping that condition by immediately adding work in the form
  1143  // of a write barrier buffer flush.
  1144  //
  1145  // Don't set nowritebarrierrec because it's safe for some callees to
  1146  // have write barriers enabled.
  1147  //
  1148  //go:nowritebarrier
  1149  func gcDrain(gcw *gcWork, flags gcDrainFlags) {
  1150  	if !writeBarrier.enabled {
  1151  		throw("gcDrain phase incorrect")
  1152  	}
  1153  
  1154  	// N.B. We must be running in a non-preemptible context, so it's
  1155  	// safe to hold a reference to our P here.
  1156  	gp := getg().m.curg
  1157  	pp := gp.m.p.ptr()
  1158  	preemptible := flags&gcDrainUntilPreempt != 0
  1159  	flushBgCredit := flags&gcDrainFlushBgCredit != 0
  1160  	idle := flags&gcDrainIdle != 0
  1161  
  1162  	initScanWork := gcw.heapScanWork
  1163  
  1164  	// checkWork is the scan work before performing the next
  1165  	// self-preempt check.
  1166  	checkWork := int64(1<<63 - 1)
  1167  	var check func() bool
  1168  	if flags&(gcDrainIdle|gcDrainFractional) != 0 {
  1169  		checkWork = initScanWork + drainCheckThreshold
  1170  		if idle {
  1171  			check = pollWork
  1172  		} else if flags&gcDrainFractional != 0 {
  1173  			check = pollFractionalWorkerExit
  1174  		}
  1175  	}
  1176  
  1177  	// Drain root marking jobs.
  1178  	if work.markrootNext < work.markrootJobs {
  1179  		// Stop if we're preemptible, if someone wants to STW, or if
  1180  		// someone is calling forEachP.
  1181  		for !(gp.preempt && (preemptible || sched.gcwaiting.Load() || pp.runSafePointFn != 0)) {
  1182  			job := atomic.Xadd(&work.markrootNext, +1) - 1
  1183  			if job >= work.markrootJobs {
  1184  				break
  1185  			}
  1186  			markroot(gcw, job, flushBgCredit)
  1187  			if check != nil && check() {
  1188  				goto done
  1189  			}
  1190  		}
  1191  	}
  1192  
  1193  	// Drain heap marking jobs.
  1194  	//
  1195  	// Stop if we're preemptible, if someone wants to STW, or if
  1196  	// someone is calling forEachP.
  1197  	//
  1198  	// TODO(mknyszek): Consider always checking gp.preempt instead
  1199  	// of having the preempt flag, and making an exception for certain
  1200  	// mark workers in retake. That might be simpler than trying to
  1201  	// enumerate all the reasons why we might want to preempt, even
  1202  	// if we're supposed to be mostly non-preemptible.
  1203  	for !(gp.preempt && (preemptible || sched.gcwaiting.Load() || pp.runSafePointFn != 0)) {
  1204  		// Try to keep work available on the global queue. We used to
  1205  		// check if there were waiting workers, but it's better to
  1206  		// just keep work available than to make workers wait. In the
  1207  		// worst case, we'll do O(log(_WorkbufSize)) unnecessary
  1208  		// balances.
  1209  		if work.full == 0 {
  1210  			gcw.balance()
  1211  		}
  1212  
  1213  		b := gcw.tryGetFast()
  1214  		if b == 0 {
  1215  			b = gcw.tryGet()
  1216  			if b == 0 {
  1217  				// Flush the write barrier
  1218  				// buffer; this may create
  1219  				// more work.
  1220  				wbBufFlush()
  1221  				b = gcw.tryGet()
  1222  			}
  1223  		}
  1224  		if b == 0 {
  1225  			// Unable to get work.
  1226  			break
  1227  		}
  1228  		scanobject(b, gcw)
  1229  
  1230  		// Flush background scan work credit to the global
  1231  		// account if we've accumulated enough locally so
  1232  		// mutator assists can draw on it.
  1233  		if gcw.heapScanWork >= gcCreditSlack {
  1234  			gcController.heapScanWork.Add(gcw.heapScanWork)
  1235  			if flushBgCredit {
  1236  				gcFlushBgCredit(gcw.heapScanWork - initScanWork)
  1237  				initScanWork = 0
  1238  			}
  1239  			checkWork -= gcw.heapScanWork
  1240  			gcw.heapScanWork = 0
  1241  
  1242  			if checkWork <= 0 {
  1243  				checkWork += drainCheckThreshold
  1244  				if check != nil && check() {
  1245  					break
  1246  				}
  1247  			}
  1248  		}
  1249  	}
  1250  
  1251  done:
  1252  	// Flush remaining scan work credit.
  1253  	if gcw.heapScanWork > 0 {
  1254  		gcController.heapScanWork.Add(gcw.heapScanWork)
  1255  		if flushBgCredit {
  1256  			gcFlushBgCredit(gcw.heapScanWork - initScanWork)
  1257  		}
  1258  		gcw.heapScanWork = 0
  1259  	}
  1260  }
  1261  
  1262  // gcDrainN blackens grey objects until it has performed roughly
  1263  // scanWork units of scan work or the G is preempted. This is
  1264  // best-effort, so it may perform less work if it fails to get a work
  1265  // buffer. Otherwise, it will perform at least n units of work, but
  1266  // may perform more because scanning is always done in whole object
  1267  // increments. It returns the amount of scan work performed.
  1268  //
  1269  // The caller goroutine must be in a preemptible state (e.g.,
  1270  // _Gwaiting) to prevent deadlocks during stack scanning. As a
  1271  // consequence, this must be called on the system stack.
  1272  //
  1273  //go:nowritebarrier
  1274  //go:systemstack
  1275  func gcDrainN(gcw *gcWork, scanWork int64) int64 {
  1276  	if !writeBarrier.enabled {
  1277  		throw("gcDrainN phase incorrect")
  1278  	}
  1279  
  1280  	// There may already be scan work on the gcw, which we don't
  1281  	// want to claim was done by this call.
  1282  	workFlushed := -gcw.heapScanWork
  1283  
  1284  	// In addition to backing out because of a preemption, back out
  1285  	// if the GC CPU limiter is enabled.
  1286  	gp := getg().m.curg
  1287  	for !gp.preempt && !gcCPULimiter.limiting() && workFlushed+gcw.heapScanWork < scanWork {
  1288  		// See gcDrain comment.
  1289  		if work.full == 0 {
  1290  			gcw.balance()
  1291  		}
  1292  
  1293  		b := gcw.tryGetFast()
  1294  		if b == 0 {
  1295  			b = gcw.tryGet()
  1296  			if b == 0 {
  1297  				// Flush the write barrier buffer;
  1298  				// this may create more work.
  1299  				wbBufFlush()
  1300  				b = gcw.tryGet()
  1301  			}
  1302  		}
  1303  
  1304  		if b == 0 {
  1305  			// Try to do a root job.
  1306  			if work.markrootNext < work.markrootJobs {
  1307  				job := atomic.Xadd(&work.markrootNext, +1) - 1
  1308  				if job < work.markrootJobs {
  1309  					workFlushed += markroot(gcw, job, false)
  1310  					continue
  1311  				}
  1312  			}
  1313  			// No heap or root jobs.
  1314  			break
  1315  		}
  1316  
  1317  		scanobject(b, gcw)
  1318  
  1319  		// Flush background scan work credit.
  1320  		if gcw.heapScanWork >= gcCreditSlack {
  1321  			gcController.heapScanWork.Add(gcw.heapScanWork)
  1322  			workFlushed += gcw.heapScanWork
  1323  			gcw.heapScanWork = 0
  1324  		}
  1325  	}
  1326  
  1327  	// Unlike gcDrain, there's no need to flush remaining work
  1328  	// here because this never flushes to bgScanCredit and
  1329  	// gcw.dispose will flush any remaining work to scanWork.
  1330  
  1331  	return workFlushed + gcw.heapScanWork
  1332  }
  1333  
  1334  // scanblock scans b as scanobject would, but using an explicit
  1335  // pointer bitmap instead of the heap bitmap.
  1336  //
  1337  // This is used to scan non-heap roots, so it does not update
  1338  // gcw.bytesMarked or gcw.heapScanWork.
  1339  //
  1340  // If stk != nil, possible stack pointers are also reported to stk.putPtr.
  1341  //
  1342  //go:nowritebarrier
  1343  func scanblock(b0, n0 uintptr, ptrmask *uint8, gcw *gcWork, stk *stackScanState) {
  1344  	// Use local copies of original parameters, so that a stack trace
  1345  	// due to one of the throws below shows the original block
  1346  	// base and extent.
  1347  	b := b0
  1348  	n := n0
  1349  
  1350  	for i := uintptr(0); i < n; {
  1351  		// Find bits for the next word.
  1352  		bits := uint32(*addb(ptrmask, i/(goarch.PtrSize*8)))
  1353  		if bits == 0 {
  1354  			i += goarch.PtrSize * 8
  1355  			continue
  1356  		}
  1357  		for j := 0; j < 8 && i < n; j++ {
  1358  			if bits&1 != 0 {
  1359  				// Same work as in scanobject; see comments there.
  1360  				p := *(*uintptr)(unsafe.Pointer(b + i))
  1361  				if p != 0 {
  1362  					if obj, span, objIndex := findObject(p, b, i); obj != 0 {
  1363  						greyobject(obj, b, i, span, gcw, objIndex)
  1364  					} else if stk != nil && p >= stk.stack.lo && p < stk.stack.hi {
  1365  						stk.putPtr(p, false)
  1366  					}
  1367  				}
  1368  			}
  1369  			bits >>= 1
  1370  			i += goarch.PtrSize
  1371  		}
  1372  	}
  1373  }
  1374  
  1375  // scanobject scans the object starting at b, adding pointers to gcw.
  1376  // b must point to the beginning of a heap object or an oblet.
  1377  // scanobject consults the GC bitmap for the pointer mask and the
  1378  // spans for the size of the object.
  1379  //
  1380  //go:nowritebarrier
  1381  func scanobject(b uintptr, gcw *gcWork) {
  1382  	// Prefetch object before we scan it.
  1383  	//
  1384  	// This will overlap fetching the beginning of the object with initial
  1385  	// setup before we start scanning the object.
  1386  	sys.Prefetch(b)
  1387  
  1388  	// Find the bits for b and the size of the object at b.
  1389  	//
  1390  	// b is either the beginning of an object, in which case this
  1391  	// is the size of the object to scan, or it points to an
  1392  	// oblet, in which case we compute the size to scan below.
  1393  	s := spanOfUnchecked(b)
  1394  	n := s.elemsize
  1395  	if n == 0 {
  1396  		throw("scanobject n == 0")
  1397  	}
  1398  	if s.spanclass.noscan() {
  1399  		// Correctness-wise this is ok, but it's inefficient
  1400  		// if noscan objects reach here.
  1401  		throw("scanobject of a noscan object")
  1402  	}
  1403  
  1404  	var tp typePointers
  1405  	if n > maxObletBytes {
  1406  		// Large object. Break into oblets for better
  1407  		// parallelism and lower latency.
  1408  		if b == s.base() {
  1409  			// Enqueue the other oblets to scan later.
  1410  			// Some oblets may be in b's scalar tail, but
  1411  			// these will be marked as "no more pointers",
  1412  			// so we'll drop out immediately when we go to
  1413  			// scan those.
  1414  			for oblet := b + maxObletBytes; oblet < s.base()+s.elemsize; oblet += maxObletBytes {
  1415  				if !gcw.putFast(oblet) {
  1416  					gcw.put(oblet)
  1417  				}
  1418  			}
  1419  		}
  1420  
  1421  		// Compute the size of the oblet. Since this object
  1422  		// must be a large object, s.base() is the beginning
  1423  		// of the object.
  1424  		n = s.base() + s.elemsize - b
  1425  		n = min(n, maxObletBytes)
  1426  		tp = s.typePointersOfUnchecked(s.base())
  1427  		tp = tp.fastForward(b-tp.addr, b+n)
  1428  	} else {
  1429  		tp = s.typePointersOfUnchecked(b)
  1430  	}
  1431  
  1432  	var scanSize uintptr
  1433  	for {
  1434  		var addr uintptr
  1435  		if tp, addr = tp.nextFast(); addr == 0 {
  1436  			if tp, addr = tp.next(b + n); addr == 0 {
  1437  				break
  1438  			}
  1439  		}
  1440  
  1441  		// Keep track of farthest pointer we found, so we can
  1442  		// update heapScanWork. TODO: is there a better metric,
  1443  		// now that we can skip scalar portions pretty efficiently?
  1444  		scanSize = addr - b + goarch.PtrSize
  1445  
  1446  		// Work here is duplicated in scanblock and above.
  1447  		// If you make changes here, make changes there too.
  1448  		obj := *(*uintptr)(unsafe.Pointer(addr))
  1449  
  1450  		// At this point we have extracted the next potential pointer.
  1451  		// Quickly filter out nil and pointers back to the current object.
  1452  		if obj != 0 && obj-b >= n {
  1453  			// Test if obj points into the Go heap and, if so,
  1454  			// mark the object.
  1455  			//
  1456  			// Note that it's possible for findObject to
  1457  			// fail if obj points to a just-allocated heap
  1458  			// object because of a race with growing the
  1459  			// heap. In this case, we know the object was
  1460  			// just allocated and hence will be marked by
  1461  			// allocation itself.
  1462  			if obj, span, objIndex := findObject(obj, b, addr-b); obj != 0 {
  1463  				greyobject(obj, b, addr-b, span, gcw, objIndex)
  1464  			}
  1465  		}
  1466  	}
  1467  	gcw.bytesMarked += uint64(n)
  1468  	gcw.heapScanWork += int64(scanSize)
  1469  }
  1470  
  1471  // scanConservative scans block [b, b+n) conservatively, treating any
  1472  // pointer-like value in the block as a pointer.
  1473  //
  1474  // If ptrmask != nil, only words that are marked in ptrmask are
  1475  // considered as potential pointers.
  1476  //
  1477  // If state != nil, it's assumed that [b, b+n) is a block in the stack
  1478  // and may contain pointers to stack objects.
  1479  func scanConservative(b, n uintptr, ptrmask *uint8, gcw *gcWork, state *stackScanState) {
  1480  	if debugScanConservative {
  1481  		printlock()
  1482  		print("conservatively scanning [", hex(b), ",", hex(b+n), ")\n")
  1483  		hexdumpWords(b, b+n, func(p uintptr) byte {
  1484  			if ptrmask != nil {
  1485  				word := (p - b) / goarch.PtrSize
  1486  				bits := *addb(ptrmask, word/8)
  1487  				if (bits>>(word%8))&1 == 0 {
  1488  					return '$'
  1489  				}
  1490  			}
  1491  
  1492  			val := *(*uintptr)(unsafe.Pointer(p))
  1493  			if state != nil && state.stack.lo <= val && val < state.stack.hi {
  1494  				return '@'
  1495  			}
  1496  
  1497  			span := spanOfHeap(val)
  1498  			if span == nil {
  1499  				return ' '
  1500  			}
  1501  			idx := span.objIndex(val)
  1502  			if span.isFree(idx) {
  1503  				return ' '
  1504  			}
  1505  			return '*'
  1506  		})
  1507  		printunlock()
  1508  	}
  1509  
  1510  	for i := uintptr(0); i < n; i += goarch.PtrSize {
  1511  		if ptrmask != nil {
  1512  			word := i / goarch.PtrSize
  1513  			bits := *addb(ptrmask, word/8)
  1514  			if bits == 0 {
  1515  				// Skip 8 words (the loop increment will do the 8th)
  1516  				//
  1517  				// This must be the first time we've
  1518  				// seen this word of ptrmask, so i
  1519  				// must be 8-word-aligned, but check
  1520  				// our reasoning just in case.
  1521  				if i%(goarch.PtrSize*8) != 0 {
  1522  					throw("misaligned mask")
  1523  				}
  1524  				i += goarch.PtrSize*8 - goarch.PtrSize
  1525  				continue
  1526  			}
  1527  			if (bits>>(word%8))&1 == 0 {
  1528  				continue
  1529  			}
  1530  		}
  1531  
  1532  		val := *(*uintptr)(unsafe.Pointer(b + i))
  1533  
  1534  		// Check if val points into the stack.
  1535  		if state != nil && state.stack.lo <= val && val < state.stack.hi {
  1536  			// val may point to a stack object. This
  1537  			// object may be dead from last cycle and
  1538  			// hence may contain pointers to unallocated
  1539  			// objects, but unlike heap objects we can't
  1540  			// tell if it's already dead. Hence, if all
  1541  			// pointers to this object are from
  1542  			// conservative scanning, we have to scan it
  1543  			// defensively, too.
  1544  			state.putPtr(val, true)
  1545  			continue
  1546  		}
  1547  
  1548  		// Check if val points to a heap span.
  1549  		span := spanOfHeap(val)
  1550  		if span == nil {
  1551  			continue
  1552  		}
  1553  
  1554  		// Check if val points to an allocated object.
  1555  		idx := span.objIndex(val)
  1556  		if span.isFree(idx) {
  1557  			continue
  1558  		}
  1559  
  1560  		// val points to an allocated object. Mark it.
  1561  		obj := span.base() + idx*span.elemsize
  1562  		greyobject(obj, b, i, span, gcw, idx)
  1563  	}
  1564  }
  1565  
  1566  // Shade the object if it isn't already.
  1567  // The object is not nil and known to be in the heap.
  1568  // Preemption must be disabled.
  1569  //
  1570  //go:nowritebarrier
  1571  func shade(b uintptr) {
  1572  	if obj, span, objIndex := findObject(b, 0, 0); obj != 0 {
  1573  		gcw := &getg().m.p.ptr().gcw
  1574  		greyobject(obj, 0, 0, span, gcw, objIndex)
  1575  	}
  1576  }
  1577  
  1578  // obj is the start of an object with mark mbits.
  1579  // If it isn't already marked, mark it and enqueue into gcw.
  1580  // base and off are for debugging only and could be removed.
  1581  //
  1582  // See also wbBufFlush1, which partially duplicates this logic.
  1583  //
  1584  //go:nowritebarrierrec
  1585  func greyobject(obj, base, off uintptr, span *mspan, gcw *gcWork, objIndex uintptr) {
  1586  	// obj should be start of allocation, and so must be at least pointer-aligned.
  1587  	if obj&(goarch.PtrSize-1) != 0 {
  1588  		throw("greyobject: obj not pointer-aligned")
  1589  	}
  1590  	mbits := span.markBitsForIndex(objIndex)
  1591  
  1592  	if useCheckmark {
  1593  		if setCheckmark(obj, base, off, mbits) {
  1594  			// Already marked.
  1595  			return
  1596  		}
  1597  	} else {
  1598  		if debug.gccheckmark > 0 && span.isFree(objIndex) {
  1599  			print("runtime: marking free object ", hex(obj), " found at *(", hex(base), "+", hex(off), ")\n")
  1600  			gcDumpObject("base", base, off)
  1601  			gcDumpObject("obj", obj, ^uintptr(0))
  1602  			getg().m.traceback = 2
  1603  			throw("marking free object")
  1604  		}
  1605  
  1606  		// If marked we have nothing to do.
  1607  		if mbits.isMarked() {
  1608  			return
  1609  		}
  1610  		mbits.setMarked()
  1611  
  1612  		// Mark span.
  1613  		arena, pageIdx, pageMask := pageIndexOf(span.base())
  1614  		if arena.pageMarks[pageIdx]&pageMask == 0 {
  1615  			atomic.Or8(&arena.pageMarks[pageIdx], pageMask)
  1616  		}
  1617  
  1618  		// If this is a noscan object, fast-track it to black
  1619  		// instead of greying it.
  1620  		if span.spanclass.noscan() {
  1621  			gcw.bytesMarked += uint64(span.elemsize)
  1622  			return
  1623  		}
  1624  	}
  1625  
  1626  	// We're adding obj to P's local workbuf, so it's likely
  1627  	// this object will be processed soon by the same P.
  1628  	// Even if the workbuf gets flushed, there will likely still be
  1629  	// some benefit on platforms with inclusive shared caches.
  1630  	sys.Prefetch(obj)
  1631  	// Queue the obj for scanning.
  1632  	if !gcw.putFast(obj) {
  1633  		gcw.put(obj)
  1634  	}
  1635  }
  1636  
  1637  // gcDumpObject dumps the contents of obj for debugging and marks the
  1638  // field at byte offset off in obj.
  1639  func gcDumpObject(label string, obj, off uintptr) {
  1640  	s := spanOf(obj)
  1641  	print(label, "=", hex(obj))
  1642  	if s == nil {
  1643  		print(" s=nil\n")
  1644  		return
  1645  	}
  1646  	print(" s.base()=", hex(s.base()), " s.limit=", hex(s.limit), " s.spanclass=", s.spanclass, " s.elemsize=", s.elemsize, " s.state=")
  1647  	if state := s.state.get(); 0 <= state && int(state) < len(mSpanStateNames) {
  1648  		print(mSpanStateNames[state], "\n")
  1649  	} else {
  1650  		print("unknown(", state, ")\n")
  1651  	}
  1652  
  1653  	skipped := false
  1654  	size := s.elemsize
  1655  	if s.state.get() == mSpanManual && size == 0 {
  1656  		// We're printing something from a stack frame. We
  1657  		// don't know how big it is, so just show up to an
  1658  		// including off.
  1659  		size = off + goarch.PtrSize
  1660  	}
  1661  	for i := uintptr(0); i < size; i += goarch.PtrSize {
  1662  		// For big objects, just print the beginning (because
  1663  		// that usually hints at the object's type) and the
  1664  		// fields around off.
  1665  		if !(i < 128*goarch.PtrSize || off-16*goarch.PtrSize < i && i < off+16*goarch.PtrSize) {
  1666  			skipped = true
  1667  			continue
  1668  		}
  1669  		if skipped {
  1670  			print(" ...\n")
  1671  			skipped = false
  1672  		}
  1673  		print(" *(", label, "+", i, ") = ", hex(*(*uintptr)(unsafe.Pointer(obj + i))))
  1674  		if i == off {
  1675  			print(" <==")
  1676  		}
  1677  		print("\n")
  1678  	}
  1679  	if skipped {
  1680  		print(" ...\n")
  1681  	}
  1682  }
  1683  
  1684  // gcmarknewobject marks a newly allocated object black. obj must
  1685  // not contain any non-nil pointers.
  1686  //
  1687  // This is nosplit so it can manipulate a gcWork without preemption.
  1688  //
  1689  //go:nowritebarrier
  1690  //go:nosplit
  1691  func gcmarknewobject(span *mspan, obj uintptr) {
  1692  	if useCheckmark { // The world should be stopped so this should not happen.
  1693  		throw("gcmarknewobject called while doing checkmark")
  1694  	}
  1695  	if gcphase == _GCmarktermination {
  1696  		// Check this here instead of on the hot path.
  1697  		throw("mallocgc called with gcphase == _GCmarktermination")
  1698  	}
  1699  
  1700  	// Mark object.
  1701  	objIndex := span.objIndex(obj)
  1702  	span.markBitsForIndex(objIndex).setMarked()
  1703  
  1704  	// Mark span.
  1705  	arena, pageIdx, pageMask := pageIndexOf(span.base())
  1706  	if arena.pageMarks[pageIdx]&pageMask == 0 {
  1707  		atomic.Or8(&arena.pageMarks[pageIdx], pageMask)
  1708  	}
  1709  
  1710  	gcw := &getg().m.p.ptr().gcw
  1711  	gcw.bytesMarked += uint64(span.elemsize)
  1712  }
  1713  
  1714  // gcMarkTinyAllocs greys all active tiny alloc blocks.
  1715  //
  1716  // The world must be stopped.
  1717  func gcMarkTinyAllocs() {
  1718  	assertWorldStopped()
  1719  
  1720  	for _, p := range allp {
  1721  		c := p.mcache
  1722  		if c == nil || c.tiny == 0 {
  1723  			continue
  1724  		}
  1725  		_, span, objIndex := findObject(c.tiny, 0, 0)
  1726  		gcw := &p.gcw
  1727  		greyobject(c.tiny, 0, 0, span, gcw, objIndex)
  1728  	}
  1729  }
  1730  

View as plain text