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

View as plain text