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  // ptrmask 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*goarch.PtrSize, &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.valgrindStackID)
   378  			gp.valgrindStackID = 0
   379  		}
   380  	}
   381  
   382  	q := gQueue{list.head, tail.guintptr(), list.size}
   383  
   384  	// Put Gs back on the free list.
   385  	lock(&sched.gFree.lock)
   386  	sched.gFree.noStack.pushAll(q)
   387  	unlock(&sched.gFree.lock)
   388  }
   389  
   390  // markrootSpans marks roots for one shard of markArenas.
   391  //
   392  //go:nowritebarrier
   393  func markrootSpans(gcw *gcWork, shard int) {
   394  	// Objects with finalizers have two GC-related invariants:
   395  	//
   396  	// 1) Everything reachable from the object must be marked.
   397  	// This ensures that when we pass the object to its finalizer,
   398  	// everything the finalizer can reach will be retained.
   399  	//
   400  	// 2) Finalizer specials (which are not in the garbage
   401  	// collected heap) are roots. In practice, this means the fn
   402  	// field must be scanned.
   403  	//
   404  	// Objects with weak handles have only one invariant related
   405  	// to this function: weak handle specials (which are not in the
   406  	// garbage collected heap) are roots. In practice, this means
   407  	// the handle field must be scanned. Note that the value the
   408  	// handle pointer referenced does *not* need to be scanned. See
   409  	// the definition of specialWeakHandle for details.
   410  	sg := mheap_.sweepgen
   411  
   412  	// Find the arena and page index into that arena for this shard.
   413  	ai := mheap_.markArenas[shard/(pagesPerArena/pagesPerSpanRoot)]
   414  	ha := mheap_.arenas[ai.l1()][ai.l2()]
   415  	arenaPage := uint(uintptr(shard) * pagesPerSpanRoot % pagesPerArena)
   416  
   417  	// Construct slice of bitmap which we'll iterate over.
   418  	specialsbits := ha.pageSpecials[arenaPage/8:]
   419  	specialsbits = specialsbits[:pagesPerSpanRoot/8]
   420  	for i := range specialsbits {
   421  		// Find set bits, which correspond to spans with specials.
   422  		specials := atomic.Load8(&specialsbits[i])
   423  		if specials == 0 {
   424  			continue
   425  		}
   426  		for j := uint(0); j < 8; j++ {
   427  			if specials&(1<<j) == 0 {
   428  				continue
   429  			}
   430  			// Find the span for this bit.
   431  			//
   432  			// This value is guaranteed to be non-nil because having
   433  			// specials implies that the span is in-use, and since we're
   434  			// currently marking we can be sure that we don't have to worry
   435  			// about the span being freed and re-used.
   436  			s := ha.spans[arenaPage+uint(i)*8+j]
   437  
   438  			// The state must be mSpanInUse if the specials bit is set, so
   439  			// sanity check that.
   440  			if state := s.state.get(); state != mSpanInUse {
   441  				print("s.state = ", state, "\n")
   442  				throw("non in-use span found with specials bit set")
   443  			}
   444  			// Check that this span was swept (it may be cached or uncached).
   445  			if !useCheckmark && !(s.sweepgen == sg || s.sweepgen == sg+3) {
   446  				// sweepgen was updated (+2) during non-checkmark GC pass
   447  				print("sweep ", s.sweepgen, " ", sg, "\n")
   448  				throw("gc: unswept span")
   449  			}
   450  
   451  			// Lock the specials to prevent a special from being
   452  			// removed from the list while we're traversing it.
   453  			lock(&s.speciallock)
   454  			for sp := s.specials; sp != nil; sp = sp.next {
   455  				switch sp.kind {
   456  				case _KindSpecialFinalizer:
   457  					gcScanFinalizer((*specialfinalizer)(unsafe.Pointer(sp)), s, gcw)
   458  				case _KindSpecialWeakHandle:
   459  					// The special itself is a root.
   460  					spw := (*specialWeakHandle)(unsafe.Pointer(sp))
   461  					scanblock(uintptr(unsafe.Pointer(&spw.handle)), goarch.PtrSize, &oneptrmask[0], gcw, nil)
   462  				case _KindSpecialCleanup:
   463  					gcScanCleanup((*specialCleanup)(unsafe.Pointer(sp)), gcw)
   464  				}
   465  			}
   466  			unlock(&s.speciallock)
   467  		}
   468  	}
   469  }
   470  
   471  // gcScanFinalizer scans the relevant parts of a finalizer special as a root.
   472  func gcScanFinalizer(spf *specialfinalizer, s *mspan, gcw *gcWork) {
   473  	// Don't mark finalized object, but scan it so we retain everything it points to.
   474  
   475  	// A finalizer can be set for an inner byte of an object, find object beginning.
   476  	p := s.base() + spf.special.offset/s.elemsize*s.elemsize
   477  
   478  	// Mark everything that can be reached from
   479  	// the object (but *not* the object itself or
   480  	// we'll never collect it).
   481  	if !s.spanclass.noscan() {
   482  		scanObject(p, gcw)
   483  	}
   484  
   485  	// The special itself is also a root.
   486  	scanblock(uintptr(unsafe.Pointer(&spf.fn)), goarch.PtrSize, &oneptrmask[0], gcw, nil)
   487  }
   488  
   489  // gcScanCleanup scans the relevant parts of a cleanup special as a root.
   490  func gcScanCleanup(spc *specialCleanup, gcw *gcWork) {
   491  	// The special itself is a root.
   492  	scanblock(uintptr(unsafe.Pointer(&spc.fn)), goarch.PtrSize, &oneptrmask[0], gcw, nil)
   493  }
   494  
   495  // gcAssistAlloc performs GC work to make gp's assist debt positive.
   496  // gp must be the calling user goroutine.
   497  //
   498  // This must be called with preemption enabled.
   499  func gcAssistAlloc(gp *g) {
   500  	// Don't assist in non-preemptible contexts. These are
   501  	// generally fragile and won't allow the assist to block.
   502  	if getg() == gp.m.g0 {
   503  		return
   504  	}
   505  	if mp := getg().m; mp.locks > 0 || mp.preemptoff != "" {
   506  		return
   507  	}
   508  
   509  	if gp := getg(); gp.bubble != nil {
   510  		// Disassociate the G from its synctest bubble while allocating.
   511  		// This is less elegant than incrementing the group's active count,
   512  		// but avoids any contamination between GC assist and synctest.
   513  		bubble := gp.bubble
   514  		gp.bubble = nil
   515  		defer func() {
   516  			gp.bubble = bubble
   517  		}()
   518  	}
   519  
   520  	// This extremely verbose boolean indicates whether we've
   521  	// entered mark assist from the perspective of the tracer.
   522  	//
   523  	// In the tracer, this is just before we call gcAssistAlloc1
   524  	// *regardless* of whether tracing is enabled. This is because
   525  	// the tracer allows for tracing to begin (and advance
   526  	// generations) in the middle of a GC mark phase, so we need to
   527  	// record some state so that the tracer can pick it up to ensure
   528  	// a consistent trace result.
   529  	//
   530  	// TODO(mknyszek): Hide the details of inMarkAssist in tracer
   531  	// functions and simplify all the state tracking. This is a lot.
   532  	enteredMarkAssistForTracing := false
   533  retry:
   534  	if gcCPULimiter.limiting() {
   535  		// If the CPU limiter is enabled, intentionally don't
   536  		// assist to reduce the amount of CPU time spent in the GC.
   537  		if enteredMarkAssistForTracing {
   538  			trace := traceAcquire()
   539  			if trace.ok() {
   540  				trace.GCMarkAssistDone()
   541  				// Set this *after* we trace the end to make sure
   542  				// that we emit an in-progress event if this is
   543  				// the first event for the goroutine in the trace
   544  				// or trace generation. Also, do this between
   545  				// acquire/release because this is part of the
   546  				// goroutine's trace state, and it must be atomic
   547  				// with respect to the tracer.
   548  				gp.inMarkAssist = false
   549  				traceRelease(trace)
   550  			} else {
   551  				// This state is tracked even if tracing isn't enabled.
   552  				// It's only used by the new tracer.
   553  				// See the comment on enteredMarkAssistForTracing.
   554  				gp.inMarkAssist = false
   555  			}
   556  		}
   557  		return
   558  	}
   559  	// Compute the amount of scan work we need to do to make the
   560  	// balance positive. When the required amount of work is low,
   561  	// we over-assist to build up credit for future allocations
   562  	// and amortize the cost of assisting.
   563  	assistWorkPerByte := gcController.assistWorkPerByte.Load()
   564  	assistBytesPerWork := gcController.assistBytesPerWork.Load()
   565  	debtBytes := -gp.gcAssistBytes
   566  	scanWork := int64(assistWorkPerByte * float64(debtBytes))
   567  	if scanWork < gcOverAssistWork {
   568  		scanWork = gcOverAssistWork
   569  		debtBytes = int64(assistBytesPerWork * float64(scanWork))
   570  	}
   571  
   572  	// Steal as much credit as we can from the background GC's
   573  	// scan credit. This is racy and may drop the background
   574  	// credit below 0 if two mutators steal at the same time. This
   575  	// will just cause steals to fail until credit is accumulated
   576  	// again, so in the long run it doesn't really matter, but we
   577  	// do have to handle the negative credit case.
   578  	bgScanCredit := gcController.bgScanCredit.Load()
   579  	stolen := int64(0)
   580  	if bgScanCredit > 0 {
   581  		if bgScanCredit < scanWork {
   582  			stolen = bgScanCredit
   583  			gp.gcAssistBytes += 1 + int64(assistBytesPerWork*float64(stolen))
   584  		} else {
   585  			stolen = scanWork
   586  			gp.gcAssistBytes += debtBytes
   587  		}
   588  		gcController.bgScanCredit.Add(-stolen)
   589  
   590  		scanWork -= stolen
   591  
   592  		if scanWork == 0 {
   593  			// We were able to steal all of the credit we
   594  			// needed.
   595  			if enteredMarkAssistForTracing {
   596  				trace := traceAcquire()
   597  				if trace.ok() {
   598  					trace.GCMarkAssistDone()
   599  					// Set this *after* we trace the end to make sure
   600  					// that we emit an in-progress event if this is
   601  					// the first event for the goroutine in the trace
   602  					// or trace generation. Also, do this between
   603  					// acquire/release because this is part of the
   604  					// goroutine's trace state, and it must be atomic
   605  					// with respect to the tracer.
   606  					gp.inMarkAssist = false
   607  					traceRelease(trace)
   608  				} else {
   609  					// This state is tracked even if tracing isn't enabled.
   610  					// It's only used by the new tracer.
   611  					// See the comment on enteredMarkAssistForTracing.
   612  					gp.inMarkAssist = false
   613  				}
   614  			}
   615  			return
   616  		}
   617  	}
   618  	if !enteredMarkAssistForTracing {
   619  		trace := traceAcquire()
   620  		if trace.ok() {
   621  			trace.GCMarkAssistStart()
   622  			// Set this *after* we trace the start, otherwise we may
   623  			// emit an in-progress event for an assist we're about to start.
   624  			gp.inMarkAssist = true
   625  			traceRelease(trace)
   626  		} else {
   627  			gp.inMarkAssist = true
   628  		}
   629  		// In the new tracer, set enter mark assist tracing if we
   630  		// ever pass this point, because we must manage inMarkAssist
   631  		// correctly.
   632  		//
   633  		// See the comment on enteredMarkAssistForTracing.
   634  		enteredMarkAssistForTracing = true
   635  	}
   636  
   637  	// Perform assist work
   638  	systemstack(func() {
   639  		gcAssistAlloc1(gp, scanWork)
   640  		// The user stack may have moved, so this can't touch
   641  		// anything on it until it returns from systemstack.
   642  	})
   643  
   644  	completed := gp.param != nil
   645  	gp.param = nil
   646  	if completed {
   647  		gcMarkDone()
   648  	}
   649  
   650  	if gp.gcAssistBytes < 0 {
   651  		// We were unable steal enough credit or perform
   652  		// enough work to pay off the assist debt. We need to
   653  		// do one of these before letting the mutator allocate
   654  		// more to prevent over-allocation.
   655  		//
   656  		// If this is because we were preempted, reschedule
   657  		// and try some more.
   658  		if gp.preempt {
   659  			Gosched()
   660  			goto retry
   661  		}
   662  
   663  		// Add this G to an assist queue and park. When the GC
   664  		// has more background credit, it will satisfy queued
   665  		// assists before flushing to the global credit pool.
   666  		//
   667  		// Note that this does *not* get woken up when more
   668  		// work is added to the work list. The theory is that
   669  		// there wasn't enough work to do anyway, so we might
   670  		// as well let background marking take care of the
   671  		// work that is available.
   672  		if !gcParkAssist() {
   673  			goto retry
   674  		}
   675  
   676  		// At this point either background GC has satisfied
   677  		// this G's assist debt, or the GC cycle is over.
   678  	}
   679  	if enteredMarkAssistForTracing {
   680  		trace := traceAcquire()
   681  		if trace.ok() {
   682  			trace.GCMarkAssistDone()
   683  			// Set this *after* we trace the end to make sure
   684  			// that we emit an in-progress event if this is
   685  			// the first event for the goroutine in the trace
   686  			// or trace generation. Also, do this between
   687  			// acquire/release because this is part of the
   688  			// goroutine's trace state, and it must be atomic
   689  			// with respect to the tracer.
   690  			gp.inMarkAssist = false
   691  			traceRelease(trace)
   692  		} else {
   693  			// This state is tracked even if tracing isn't enabled.
   694  			// It's only used by the new tracer.
   695  			// See the comment on enteredMarkAssistForTracing.
   696  			gp.inMarkAssist = false
   697  		}
   698  	}
   699  }
   700  
   701  // gcAssistAlloc1 is the part of gcAssistAlloc that runs on the system
   702  // stack. This is a separate function to make it easier to see that
   703  // we're not capturing anything from the user stack, since the user
   704  // stack may move while we're in this function.
   705  //
   706  // gcAssistAlloc1 indicates whether this assist completed the mark
   707  // phase by setting gp.param to non-nil. This can't be communicated on
   708  // the stack since it may move.
   709  //
   710  //go:systemstack
   711  func gcAssistAlloc1(gp *g, scanWork int64) {
   712  	// Clear the flag indicating that this assist completed the
   713  	// mark phase.
   714  	gp.param = nil
   715  
   716  	if atomic.Load(&gcBlackenEnabled) == 0 {
   717  		// The gcBlackenEnabled check in malloc races with the
   718  		// store that clears it but an atomic check in every malloc
   719  		// would be a performance hit.
   720  		// Instead we recheck it here on the non-preemptible system
   721  		// stack to determine if we should perform an assist.
   722  
   723  		// GC is done, so ignore any remaining debt.
   724  		gp.gcAssistBytes = 0
   725  		return
   726  	}
   727  
   728  	// Track time spent in this assist. Since we're on the
   729  	// system stack, this is non-preemptible, so we can
   730  	// just measure start and end time.
   731  	//
   732  	// Limiter event tracking might be disabled if we end up here
   733  	// while on a mark worker.
   734  	startTime := nanotime()
   735  	trackLimiterEvent := gp.m.p.ptr().limiterEvent.start(limiterEventMarkAssist, startTime)
   736  
   737  	gcBeginWork()
   738  
   739  	// gcDrainN requires the caller to be preemptible.
   740  	casGToWaitingForSuspendG(gp, _Grunning, waitReasonGCAssistMarking)
   741  
   742  	// drain own cached work first in the hopes that it
   743  	// will be more cache friendly.
   744  	gcw := &getg().m.p.ptr().gcw
   745  	workDone := gcDrainN(gcw, scanWork)
   746  
   747  	casgstatus(gp, _Gwaiting, _Grunning)
   748  
   749  	// Record that we did this much scan work.
   750  	//
   751  	// Back out the number of bytes of assist credit that
   752  	// this scan work counts for. The "1+" is a poor man's
   753  	// round-up, to ensure this adds credit even if
   754  	// assistBytesPerWork is very low.
   755  	assistBytesPerWork := gcController.assistBytesPerWork.Load()
   756  	gp.gcAssistBytes += 1 + int64(assistBytesPerWork*float64(workDone))
   757  
   758  	// If this is the last worker and we ran out of work,
   759  	// signal a completion point.
   760  	if gcEndWork() {
   761  		// This has reached a background completion point. Set
   762  		// gp.param to a non-nil value to indicate this. It
   763  		// doesn't matter what we set it to (it just has to be
   764  		// a valid pointer).
   765  		gp.param = unsafe.Pointer(gp)
   766  	}
   767  	now := nanotime()
   768  	duration := now - startTime
   769  	pp := gp.m.p.ptr()
   770  	pp.gcAssistTime += duration
   771  	if trackLimiterEvent {
   772  		pp.limiterEvent.stop(limiterEventMarkAssist, now)
   773  	}
   774  	if pp.gcAssistTime > gcAssistTimeSlack {
   775  		gcController.assistTime.Add(pp.gcAssistTime)
   776  		gcCPULimiter.update(now)
   777  		pp.gcAssistTime = 0
   778  	}
   779  }
   780  
   781  // gcWakeAllAssists wakes all currently blocked assists. This is used
   782  // at the end of a GC cycle. gcBlackenEnabled must be false to prevent
   783  // new assists from going to sleep after this point.
   784  func gcWakeAllAssists() {
   785  	lock(&work.assistQueue.lock)
   786  	list := work.assistQueue.q.popList()
   787  	injectglist(&list)
   788  	unlock(&work.assistQueue.lock)
   789  }
   790  
   791  // gcParkAssist puts the current goroutine on the assist queue and parks.
   792  //
   793  // gcParkAssist reports whether the assist is now satisfied. If it
   794  // returns false, the caller must retry the assist.
   795  func gcParkAssist() bool {
   796  	lock(&work.assistQueue.lock)
   797  	// If the GC cycle finished while we were getting the lock,
   798  	// exit the assist. The cycle can't finish while we hold the
   799  	// lock.
   800  	if atomic.Load(&gcBlackenEnabled) == 0 {
   801  		unlock(&work.assistQueue.lock)
   802  		return true
   803  	}
   804  
   805  	gp := getg()
   806  	oldList := work.assistQueue.q
   807  	work.assistQueue.q.pushBack(gp)
   808  
   809  	// Recheck for background credit now that this G is in
   810  	// the queue, but can still back out. This avoids a
   811  	// race in case background marking has flushed more
   812  	// credit since we checked above.
   813  	if gcController.bgScanCredit.Load() > 0 {
   814  		work.assistQueue.q = oldList
   815  		if oldList.tail != 0 {
   816  			oldList.tail.ptr().schedlink.set(nil)
   817  		}
   818  		unlock(&work.assistQueue.lock)
   819  		return false
   820  	}
   821  	// Park.
   822  	goparkunlock(&work.assistQueue.lock, waitReasonGCAssistWait, traceBlockGCMarkAssist, 2)
   823  	return true
   824  }
   825  
   826  // gcFlushBgCredit flushes scanWork units of background scan work
   827  // credit. This first satisfies blocked assists on the
   828  // work.assistQueue and then flushes any remaining credit to
   829  // gcController.bgScanCredit.
   830  //
   831  // Write barriers are disallowed because this is used by gcDrain after
   832  // it has ensured that all work is drained and this must preserve that
   833  // condition.
   834  //
   835  //go:nowritebarrierrec
   836  func gcFlushBgCredit(scanWork int64) {
   837  	if work.assistQueue.q.empty() {
   838  		// Fast path; there are no blocked assists. There's a
   839  		// small window here where an assist may add itself to
   840  		// the blocked queue and park. If that happens, we'll
   841  		// just get it on the next flush.
   842  		gcController.bgScanCredit.Add(scanWork)
   843  		return
   844  	}
   845  
   846  	assistBytesPerWork := gcController.assistBytesPerWork.Load()
   847  	scanBytes := int64(float64(scanWork) * assistBytesPerWork)
   848  
   849  	lock(&work.assistQueue.lock)
   850  	for !work.assistQueue.q.empty() && scanBytes > 0 {
   851  		gp := work.assistQueue.q.pop()
   852  		// Note that gp.gcAssistBytes is negative because gp
   853  		// is in debt. Think carefully about the signs below.
   854  		if scanBytes+gp.gcAssistBytes >= 0 {
   855  			// Satisfy this entire assist debt.
   856  			scanBytes += gp.gcAssistBytes
   857  			gp.gcAssistBytes = 0
   858  			// It's important that we *not* put gp in
   859  			// runnext. Otherwise, it's possible for user
   860  			// code to exploit the GC worker's high
   861  			// scheduler priority to get itself always run
   862  			// before other goroutines and always in the
   863  			// fresh quantum started by GC.
   864  			ready(gp, 0, false)
   865  		} else {
   866  			// Partially satisfy this assist.
   867  			gp.gcAssistBytes += scanBytes
   868  			scanBytes = 0
   869  			// As a heuristic, we move this assist to the
   870  			// back of the queue so that large assists
   871  			// can't clog up the assist queue and
   872  			// substantially delay small assists.
   873  			work.assistQueue.q.pushBack(gp)
   874  			break
   875  		}
   876  	}
   877  
   878  	if scanBytes > 0 {
   879  		// Convert from scan bytes back to work.
   880  		assistWorkPerByte := gcController.assistWorkPerByte.Load()
   881  		scanWork = int64(float64(scanBytes) * assistWorkPerByte)
   882  		gcController.bgScanCredit.Add(scanWork)
   883  	}
   884  	unlock(&work.assistQueue.lock)
   885  }
   886  
   887  // scanstack scans gp's stack, greying all pointers found on the stack.
   888  //
   889  // Returns the amount of scan work performed, but doesn't update
   890  // gcController.stackScanWork or flush any credit. Any background credit produced
   891  // by this function should be flushed by its caller. scanstack itself can't
   892  // safely flush because it may result in trying to wake up a goroutine that
   893  // was just scanned, resulting in a self-deadlock.
   894  //
   895  // scanstack will also shrink the stack if it is safe to do so. If it
   896  // is not, it schedules a stack shrink for the next synchronous safe
   897  // point.
   898  //
   899  // scanstack is marked go:systemstack because it must not be preempted
   900  // while using a workbuf.
   901  //
   902  //go:nowritebarrier
   903  //go:systemstack
   904  func scanstack(gp *g, gcw *gcWork) int64 {
   905  	if readgstatus(gp)&_Gscan == 0 {
   906  		print("runtime:scanstack: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", hex(readgstatus(gp)), "\n")
   907  		throw("scanstack - bad status")
   908  	}
   909  
   910  	switch readgstatus(gp) &^ _Gscan {
   911  	default:
   912  		print("runtime: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n")
   913  		throw("mark - bad status")
   914  	case _Gdead:
   915  		return 0
   916  	case _Grunning:
   917  		print("runtime: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n")
   918  		throw("scanstack: goroutine not stopped")
   919  	case _Grunnable, _Gsyscall, _Gwaiting, _Gleaked:
   920  		// ok
   921  	}
   922  
   923  	if gp == getg() {
   924  		throw("can't scan our own stack")
   925  	}
   926  
   927  	// scannedSize is the amount of work we'll be reporting.
   928  	//
   929  	// It is less than the allocated size (which is hi-lo).
   930  	var sp uintptr
   931  	if gp.syscallsp != 0 {
   932  		sp = gp.syscallsp // If in a system call this is the stack pointer (gp.sched.sp can be 0 in this case on Windows).
   933  	} else {
   934  		sp = gp.sched.sp
   935  	}
   936  	scannedSize := gp.stack.hi - sp
   937  
   938  	// Keep statistics for initial stack size calculation.
   939  	// Note that this accumulates the scanned size, not the allocated size.
   940  	p := getg().m.p.ptr()
   941  	p.scannedStackSize += uint64(scannedSize)
   942  	p.scannedStacks++
   943  
   944  	if isShrinkStackSafe(gp) {
   945  		// Shrink the stack if not much of it is being used.
   946  		shrinkstack(gp)
   947  	} else {
   948  		// Otherwise, shrink the stack at the next sync safe point.
   949  		gp.preemptShrink = true
   950  	}
   951  
   952  	var state stackScanState
   953  	state.stack = gp.stack
   954  
   955  	if stackTraceDebug {
   956  		println("stack trace goroutine", gp.goid)
   957  	}
   958  
   959  	if debugScanConservative && gp.asyncSafePoint {
   960  		print("scanning async preempted goroutine ", gp.goid, " stack [", hex(gp.stack.lo), ",", hex(gp.stack.hi), ")\n")
   961  	}
   962  
   963  	// Scan the saved context register. This is effectively a live
   964  	// register that gets moved back and forth between the
   965  	// register and sched.ctxt without a write barrier.
   966  	if gp.sched.ctxt != nil {
   967  		scanblock(uintptr(unsafe.Pointer(&gp.sched.ctxt)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
   968  	}
   969  
   970  	// Scan the stack. Accumulate a list of stack objects.
   971  	var u unwinder
   972  	for u.init(gp, 0); u.valid(); u.next() {
   973  		scanframeworker(&u.frame, &state, gcw)
   974  	}
   975  
   976  	// Find additional pointers that point into the stack from the heap.
   977  	// Currently this includes defers and panics. See also function copystack.
   978  
   979  	// Find and trace other pointers in defer records.
   980  	for d := gp._defer; d != nil; d = d.link {
   981  		if d.fn != nil {
   982  			// Scan the func value, which could be a stack allocated closure.
   983  			// See issue 30453.
   984  			scanblock(uintptr(unsafe.Pointer(&d.fn)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
   985  		}
   986  		if d.link != nil {
   987  			// The link field of a stack-allocated defer record might point
   988  			// to a heap-allocated defer record. Keep that heap record live.
   989  			scanblock(uintptr(unsafe.Pointer(&d.link)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
   990  		}
   991  		// Retain defers records themselves.
   992  		// Defer records might not be reachable from the G through regular heap
   993  		// tracing because the defer linked list might weave between the stack and the heap.
   994  		if d.heap {
   995  			scanblock(uintptr(unsafe.Pointer(&d)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
   996  		}
   997  	}
   998  	if gp._panic != nil {
   999  		// Panics are always stack allocated.
  1000  		state.putPtr(uintptr(unsafe.Pointer(gp._panic)), false)
  1001  	}
  1002  
  1003  	// Find and scan all reachable stack objects.
  1004  	//
  1005  	// The state's pointer queue prioritizes precise pointers over
  1006  	// conservative pointers so that we'll prefer scanning stack
  1007  	// objects precisely.
  1008  	state.buildIndex()
  1009  	for {
  1010  		p, conservative := state.getPtr()
  1011  		if p == 0 {
  1012  			break
  1013  		}
  1014  		obj := state.findObject(p)
  1015  		if obj == nil {
  1016  			continue
  1017  		}
  1018  		r := obj.r
  1019  		if r == nil {
  1020  			// We've already scanned this object.
  1021  			continue
  1022  		}
  1023  		obj.setRecord(nil) // Don't scan it again.
  1024  		if stackTraceDebug {
  1025  			printlock()
  1026  			print("  live stkobj at", hex(state.stack.lo+uintptr(obj.off)), "of size", obj.size)
  1027  			if conservative {
  1028  				print(" (conservative)")
  1029  			}
  1030  			println()
  1031  			printunlock()
  1032  		}
  1033  		ptrBytes, gcData := r.gcdata()
  1034  		b := state.stack.lo + uintptr(obj.off)
  1035  		if conservative {
  1036  			scanConservative(b, ptrBytes, gcData, gcw, &state)
  1037  		} else {
  1038  			scanblock(b, ptrBytes, gcData, gcw, &state)
  1039  		}
  1040  	}
  1041  
  1042  	// Deallocate object buffers.
  1043  	// (Pointer buffers were all deallocated in the loop above.)
  1044  	for state.head != nil {
  1045  		x := state.head
  1046  		state.head = x.next
  1047  		if stackTraceDebug {
  1048  			for i := 0; i < x.nobj; i++ {
  1049  				obj := &x.obj[i]
  1050  				if obj.r == nil { // reachable
  1051  					continue
  1052  				}
  1053  				println("  dead stkobj at", hex(gp.stack.lo+uintptr(obj.off)), "of size", obj.r.size)
  1054  				// Note: not necessarily really dead - only reachable-from-ptr dead.
  1055  			}
  1056  		}
  1057  		x.nobj = 0
  1058  		putempty((*workbuf)(unsafe.Pointer(x)))
  1059  	}
  1060  	if state.buf != nil || state.cbuf != nil || state.freeBuf != nil {
  1061  		throw("remaining pointer buffers")
  1062  	}
  1063  	return int64(scannedSize)
  1064  }
  1065  
  1066  // Scan a stack frame: local variables and function arguments/results.
  1067  //
  1068  //go:nowritebarrier
  1069  func scanframeworker(frame *stkframe, state *stackScanState, gcw *gcWork) {
  1070  	if _DebugGC > 1 && frame.continpc != 0 {
  1071  		print("scanframe ", funcname(frame.fn), "\n")
  1072  	}
  1073  
  1074  	isAsyncPreempt := frame.fn.valid() && frame.fn.funcID == abi.FuncID_asyncPreempt
  1075  	isDebugCall := frame.fn.valid() && frame.fn.funcID == abi.FuncID_debugCallV2
  1076  	if state.conservative || isAsyncPreempt || isDebugCall {
  1077  		if debugScanConservative {
  1078  			println("conservatively scanning function", funcname(frame.fn), "at PC", hex(frame.continpc))
  1079  		}
  1080  
  1081  		// Conservatively scan the frame. Unlike the precise
  1082  		// case, this includes the outgoing argument space
  1083  		// since we may have stopped while this function was
  1084  		// setting up a call.
  1085  		//
  1086  		// TODO: We could narrow this down if the compiler
  1087  		// produced a single map per function of stack slots
  1088  		// and registers that ever contain a pointer.
  1089  		if frame.varp != 0 {
  1090  			size := frame.varp - frame.sp
  1091  			if size > 0 {
  1092  				scanConservative(frame.sp, size, nil, gcw, state)
  1093  			}
  1094  		}
  1095  
  1096  		// Scan arguments to this frame.
  1097  		if n := frame.argBytes(); n != 0 {
  1098  			// TODO: We could pass the entry argument map
  1099  			// to narrow this down further.
  1100  			scanConservative(frame.argp, n, nil, gcw, state)
  1101  		}
  1102  
  1103  		if isAsyncPreempt || isDebugCall {
  1104  			// This function's frame contained the
  1105  			// registers for the asynchronously stopped
  1106  			// parent frame. Scan the parent
  1107  			// conservatively.
  1108  			state.conservative = true
  1109  		} else {
  1110  			// We only wanted to scan those two frames
  1111  			// conservatively. Clear the flag for future
  1112  			// frames.
  1113  			state.conservative = false
  1114  		}
  1115  		return
  1116  	}
  1117  
  1118  	locals, args, objs := frame.getStackMap(false)
  1119  
  1120  	// Scan local variables if stack frame has been allocated.
  1121  	if locals.n > 0 {
  1122  		size := uintptr(locals.n) * goarch.PtrSize
  1123  		scanblock(frame.varp-size, size, locals.bytedata, gcw, state)
  1124  	}
  1125  
  1126  	// Scan arguments.
  1127  	if args.n > 0 {
  1128  		scanblock(frame.argp, uintptr(args.n)*goarch.PtrSize, args.bytedata, gcw, state)
  1129  	}
  1130  
  1131  	// Add all stack objects to the stack object list.
  1132  	if frame.varp != 0 {
  1133  		// varp is 0 for defers, where there are no locals.
  1134  		// In that case, there can't be a pointer to its args, either.
  1135  		// (And all args would be scanned above anyway.)
  1136  		for i := range objs {
  1137  			obj := &objs[i]
  1138  			off := obj.off
  1139  			base := frame.varp // locals base pointer
  1140  			if off >= 0 {
  1141  				base = frame.argp // arguments and return values base pointer
  1142  			}
  1143  			ptr := base + uintptr(off)
  1144  			if ptr < frame.sp {
  1145  				// object hasn't been allocated in the frame yet.
  1146  				continue
  1147  			}
  1148  			if stackTraceDebug {
  1149  				println("stkobj at", hex(ptr), "of size", obj.size)
  1150  			}
  1151  			state.addObject(ptr, obj)
  1152  		}
  1153  	}
  1154  }
  1155  
  1156  type gcDrainFlags int
  1157  
  1158  const (
  1159  	gcDrainUntilPreempt gcDrainFlags = 1 << iota
  1160  	gcDrainFlushBgCredit
  1161  	gcDrainIdle
  1162  	gcDrainFractional
  1163  )
  1164  
  1165  // gcDrainMarkWorkerIdle is a wrapper for gcDrain that exists to better account
  1166  // mark time in profiles.
  1167  func gcDrainMarkWorkerIdle(gcw *gcWork) {
  1168  	gcDrain(gcw, gcDrainIdle|gcDrainUntilPreempt|gcDrainFlushBgCredit)
  1169  }
  1170  
  1171  // gcDrainMarkWorkerDedicated is a wrapper for gcDrain that exists to better account
  1172  // mark time in profiles.
  1173  func gcDrainMarkWorkerDedicated(gcw *gcWork, untilPreempt bool) {
  1174  	flags := gcDrainFlushBgCredit
  1175  	if untilPreempt {
  1176  		flags |= gcDrainUntilPreempt
  1177  	}
  1178  	gcDrain(gcw, flags)
  1179  }
  1180  
  1181  // gcDrainMarkWorkerFractional is a wrapper for gcDrain that exists to better account
  1182  // mark time in profiles.
  1183  func gcDrainMarkWorkerFractional(gcw *gcWork) {
  1184  	gcDrain(gcw, gcDrainFractional|gcDrainUntilPreempt|gcDrainFlushBgCredit)
  1185  }
  1186  
  1187  // gcNextMarkRoot safely increments work.markrootNext and returns the
  1188  // index of the next root job. The returned boolean is true if the root job
  1189  // is valid, and false if there are no more root jobs to be claimed,
  1190  // i.e. work.markrootNext >= work.markrootJobs.
  1191  func gcNextMarkRoot() (uint32, bool) {
  1192  	if !work.goroutineLeak.enabled {
  1193  		// If not running goroutine leak detection, assume regular GC behavior.
  1194  		job := work.markrootNext.Add(1) - 1
  1195  		return job, job < work.markrootJobs.Load()
  1196  	}
  1197  
  1198  	// Otherwise, use a CAS loop to increment markrootNext.
  1199  	for next, jobs := work.markrootNext.Load(), work.markrootJobs.Load(); next < jobs; next = work.markrootNext.Load() {
  1200  		// There is still work available at the moment.
  1201  		if work.markrootNext.CompareAndSwap(next, next+1) {
  1202  			// We manage to snatch a root job. Return the root index.
  1203  			return next, true
  1204  		}
  1205  	}
  1206  	return 0, false
  1207  }
  1208  
  1209  // gcDrain scans roots and objects in work buffers, blackening grey
  1210  // objects until it is unable to get more work. It may return before
  1211  // GC is done; it's the caller's responsibility to balance work from
  1212  // other Ps.
  1213  //
  1214  // If flags&gcDrainUntilPreempt != 0, gcDrain returns when g.preempt
  1215  // is set.
  1216  //
  1217  // If flags&gcDrainIdle != 0, gcDrain returns when there is other work
  1218  // to do.
  1219  //
  1220  // If flags&gcDrainFractional != 0, gcDrain self-preempts when
  1221  // pollFractionalWorkerExit() returns true. This implies
  1222  // gcDrainNoBlock.
  1223  //
  1224  // If flags&gcDrainFlushBgCredit != 0, gcDrain flushes scan work
  1225  // credit to gcController.bgScanCredit every gcCreditSlack units of
  1226  // scan work.
  1227  //
  1228  // gcDrain will always return if there is a pending STW or forEachP.
  1229  //
  1230  // Disabling write barriers is necessary to ensure that after we've
  1231  // confirmed that we've drained gcw, that we don't accidentally end
  1232  // up flipping that condition by immediately adding work in the form
  1233  // of a write barrier buffer flush.
  1234  //
  1235  // Don't set nowritebarrierrec because it's safe for some callees to
  1236  // have write barriers enabled.
  1237  //
  1238  //go:nowritebarrier
  1239  func gcDrain(gcw *gcWork, flags gcDrainFlags) {
  1240  	if !writeBarrier.enabled {
  1241  		throw("gcDrain phase incorrect")
  1242  	}
  1243  
  1244  	// N.B. We must be running in a non-preemptible context, so it's
  1245  	// safe to hold a reference to our P here.
  1246  	gp := getg().m.curg
  1247  	pp := gp.m.p.ptr()
  1248  	preemptible := flags&gcDrainUntilPreempt != 0
  1249  	flushBgCredit := flags&gcDrainFlushBgCredit != 0
  1250  	idle := flags&gcDrainIdle != 0
  1251  
  1252  	initScanWork := gcw.heapScanWork
  1253  
  1254  	// checkWork is the scan work before performing the next
  1255  	// self-preempt check.
  1256  	checkWork := int64(1<<63 - 1)
  1257  	var check func() bool
  1258  	if flags&(gcDrainIdle|gcDrainFractional) != 0 {
  1259  		checkWork = initScanWork + drainCheckThreshold
  1260  		if idle {
  1261  			check = pollWork
  1262  		} else if flags&gcDrainFractional != 0 {
  1263  			check = pollFractionalWorkerExit
  1264  		}
  1265  	}
  1266  
  1267  	if work.markrootNext.Load() < work.markrootJobs.Load() {
  1268  		// Stop if we're preemptible, if someone wants to STW, or if
  1269  		// someone is calling forEachP.
  1270  		for !(gp.preempt && (preemptible || sched.gcwaiting.Load() || pp.runSafePointFn != 0)) {
  1271  			job, ok := gcNextMarkRoot()
  1272  			if !ok {
  1273  				break
  1274  			}
  1275  			markroot(gcw, job, flushBgCredit)
  1276  			if check != nil && check() {
  1277  				goto done
  1278  			}
  1279  
  1280  			// Spin up a new worker if requested.
  1281  			if goexperiment.GreenTeaGC && gcw.mayNeedWorker {
  1282  				gcw.mayNeedWorker = false
  1283  				if gcphase == _GCmark {
  1284  					gcController.enlistWorker()
  1285  				}
  1286  			}
  1287  		}
  1288  	}
  1289  
  1290  	// Drain heap marking jobs.
  1291  	//
  1292  	// Stop if we're preemptible, if someone wants to STW, or if
  1293  	// someone is calling forEachP.
  1294  	//
  1295  	// TODO(mknyszek): Consider always checking gp.preempt instead
  1296  	// of having the preempt flag, and making an exception for certain
  1297  	// mark workers in retake. That might be simpler than trying to
  1298  	// enumerate all the reasons why we might want to preempt, even
  1299  	// if we're supposed to be mostly non-preemptible.
  1300  	for !(gp.preempt && (preemptible || sched.gcwaiting.Load() || pp.runSafePointFn != 0)) {
  1301  		// Try to keep work available on the global queue. We used to
  1302  		// check if there were waiting workers, but it's better to
  1303  		// just keep work available than to make workers wait. In the
  1304  		// worst case, we'll do O(log(_WorkbufSize)) unnecessary
  1305  		// balances.
  1306  		if work.full == 0 {
  1307  			gcw.balance()
  1308  		}
  1309  
  1310  		// See mgcwork.go for the rationale behind the order in which we check these queues.
  1311  		var b uintptr
  1312  		var s objptr
  1313  		if b = gcw.tryGetObjFast(); b == 0 {
  1314  			if s = gcw.tryGetSpanFast(); s == 0 {
  1315  				if b = gcw.tryGetObj(); b == 0 {
  1316  					if s = gcw.tryGetSpan(); s == 0 {
  1317  						// Flush the write barrier
  1318  						// buffer; this may create
  1319  						// more work.
  1320  						wbBufFlush()
  1321  						if b = gcw.tryGetObj(); b == 0 {
  1322  							if s = gcw.tryGetSpan(); s == 0 {
  1323  								s = gcw.tryStealSpan()
  1324  							}
  1325  						}
  1326  					}
  1327  				}
  1328  			}
  1329  		}
  1330  		if b != 0 {
  1331  			scanObject(b, gcw)
  1332  		} else if s != 0 {
  1333  			scanSpan(s, gcw)
  1334  		} else {
  1335  			// Unable to get work.
  1336  			break
  1337  		}
  1338  
  1339  		// Spin up a new worker if requested.
  1340  		if goexperiment.GreenTeaGC && gcw.mayNeedWorker {
  1341  			gcw.mayNeedWorker = false
  1342  			if gcphase == _GCmark {
  1343  				gcController.enlistWorker()
  1344  			}
  1345  		}
  1346  
  1347  		// Flush background scan work credit to the global
  1348  		// account if we've accumulated enough locally so
  1349  		// mutator assists can draw on it.
  1350  		if gcw.heapScanWork >= gcCreditSlack {
  1351  			gcController.heapScanWork.Add(gcw.heapScanWork)
  1352  			if flushBgCredit {
  1353  				gcFlushBgCredit(gcw.heapScanWork - initScanWork)
  1354  				initScanWork = 0
  1355  			}
  1356  			checkWork -= gcw.heapScanWork
  1357  			gcw.heapScanWork = 0
  1358  
  1359  			if checkWork <= 0 {
  1360  				checkWork += drainCheckThreshold
  1361  				if check != nil && check() {
  1362  					break
  1363  				}
  1364  			}
  1365  		}
  1366  	}
  1367  
  1368  done:
  1369  	// Flush remaining scan work credit.
  1370  	if gcw.heapScanWork > 0 {
  1371  		gcController.heapScanWork.Add(gcw.heapScanWork)
  1372  		if flushBgCredit {
  1373  			gcFlushBgCredit(gcw.heapScanWork - initScanWork)
  1374  		}
  1375  		gcw.heapScanWork = 0
  1376  	}
  1377  }
  1378  
  1379  // gcDrainN blackens grey objects until it has performed roughly
  1380  // scanWork units of scan work or the G is preempted. This is
  1381  // best-effort, so it may perform less work if it fails to get a work
  1382  // buffer. Otherwise, it will perform at least n units of work, but
  1383  // may perform more because scanning is always done in whole object
  1384  // increments. It returns the amount of scan work performed.
  1385  //
  1386  // The caller goroutine must be in a preemptible state (e.g.,
  1387  // _Gwaiting) to prevent deadlocks during stack scanning. As a
  1388  // consequence, this must be called on the system stack.
  1389  //
  1390  //go:nowritebarrier
  1391  //go:systemstack
  1392  func gcDrainN(gcw *gcWork, scanWork int64) int64 {
  1393  	if !writeBarrier.enabled {
  1394  		throw("gcDrainN phase incorrect")
  1395  	}
  1396  
  1397  	// There may already be scan work on the gcw, which we don't
  1398  	// want to claim was done by this call.
  1399  	workFlushed := -gcw.heapScanWork
  1400  
  1401  	// In addition to backing out because of a preemption, back out
  1402  	// if the GC CPU limiter is enabled.
  1403  	gp := getg().m.curg
  1404  	for !gp.preempt && !gcCPULimiter.limiting() && workFlushed+gcw.heapScanWork < scanWork {
  1405  		// See gcDrain comment.
  1406  		if work.full == 0 {
  1407  			gcw.balance()
  1408  		}
  1409  
  1410  		// See mgcwork.go for the rationale behind the order in which we check these queues.
  1411  		var b uintptr
  1412  		var s objptr
  1413  		if b = gcw.tryGetObjFast(); b == 0 {
  1414  			if s = gcw.tryGetSpanFast(); s == 0 {
  1415  				if b = gcw.tryGetObj(); b == 0 {
  1416  					if s = gcw.tryGetSpan(); s == 0 {
  1417  						// Flush the write barrier
  1418  						// buffer; this may create
  1419  						// more work.
  1420  						wbBufFlush()
  1421  						if b = gcw.tryGetObj(); b == 0 {
  1422  							if s = gcw.tryGetSpan(); s == 0 {
  1423  								// Try to do a root job.
  1424  								if work.markrootNext.Load() < work.markrootJobs.Load() {
  1425  									job, ok := gcNextMarkRoot()
  1426  									if ok {
  1427  										workFlushed += markroot(gcw, job, false)
  1428  										continue
  1429  									}
  1430  								}
  1431  								s = gcw.tryStealSpan()
  1432  							}
  1433  						}
  1434  					}
  1435  				}
  1436  			}
  1437  		}
  1438  		if b != 0 {
  1439  			scanObject(b, gcw)
  1440  		} else if s != 0 {
  1441  			scanSpan(s, gcw)
  1442  		} else {
  1443  			// Unable to get work.
  1444  			break
  1445  		}
  1446  
  1447  		// Flush background scan work credit.
  1448  		if gcw.heapScanWork >= gcCreditSlack {
  1449  			gcController.heapScanWork.Add(gcw.heapScanWork)
  1450  			workFlushed += gcw.heapScanWork
  1451  			gcw.heapScanWork = 0
  1452  		}
  1453  
  1454  		// Spin up a new worker if requested.
  1455  		if goexperiment.GreenTeaGC && gcw.mayNeedWorker {
  1456  			gcw.mayNeedWorker = false
  1457  			if gcphase == _GCmark {
  1458  				gcController.enlistWorker()
  1459  			}
  1460  		}
  1461  	}
  1462  
  1463  	// Unlike gcDrain, there's no need to flush remaining work
  1464  	// here because this never flushes to bgScanCredit and
  1465  	// gcw.dispose will flush any remaining work to scanWork.
  1466  
  1467  	return workFlushed + gcw.heapScanWork
  1468  }
  1469  
  1470  // scanblock scans b as scanObject would, but using an explicit
  1471  // pointer bitmap instead of the heap bitmap.
  1472  //
  1473  // This is used to scan non-heap roots, so it does not update
  1474  // gcw.bytesMarked or gcw.heapScanWork.
  1475  //
  1476  // If stk != nil, possible stack pointers are also reported to stk.putPtr.
  1477  //
  1478  //go:nowritebarrier
  1479  func scanblock(b0, n0 uintptr, ptrmask *uint8, gcw *gcWork, stk *stackScanState) {
  1480  	// Use local copies of original parameters, so that a stack trace
  1481  	// due to one of the throws below shows the original block
  1482  	// base and extent.
  1483  	b := b0
  1484  	n := n0
  1485  
  1486  	for i := uintptr(0); i < n; {
  1487  		// Find bits for the next word.
  1488  		bits := uint32(*addb(ptrmask, i/(goarch.PtrSize*8)))
  1489  		if bits == 0 {
  1490  			i += goarch.PtrSize * 8
  1491  			continue
  1492  		}
  1493  		for j := 0; j < 8 && i < n; j++ {
  1494  			if bits&1 != 0 {
  1495  				// Same work as in scanObject; see comments there.
  1496  				p := *(*uintptr)(unsafe.Pointer(b + i))
  1497  				if p != 0 {
  1498  					if stk != nil && p >= stk.stack.lo && p < stk.stack.hi {
  1499  						stk.putPtr(p, false)
  1500  					} else {
  1501  						if !tryDeferToSpanScan(p, gcw) {
  1502  							if obj, span, objIndex := findObject(p, b, i); obj != 0 {
  1503  								greyobject(obj, b, i, span, gcw, objIndex)
  1504  							}
  1505  						}
  1506  					}
  1507  				}
  1508  			}
  1509  			bits >>= 1
  1510  			i += goarch.PtrSize
  1511  		}
  1512  	}
  1513  }
  1514  
  1515  // scanConservative scans block [b, b+n) conservatively, treating any
  1516  // pointer-like value in the block as a pointer.
  1517  //
  1518  // If ptrmask != nil, only words that are marked in ptrmask are
  1519  // considered as potential pointers.
  1520  //
  1521  // If state != nil, it's assumed that [b, b+n) is a block in the stack
  1522  // and may contain pointers to stack objects.
  1523  func scanConservative(b, n uintptr, ptrmask *uint8, gcw *gcWork, state *stackScanState) {
  1524  	if debugScanConservative {
  1525  		printlock()
  1526  		print("conservatively scanning [", hex(b), ",", hex(b+n), ")\n")
  1527  		hexdumpWords(b, b+n, func(p uintptr) byte {
  1528  			if ptrmask != nil {
  1529  				word := (p - b) / goarch.PtrSize
  1530  				bits := *addb(ptrmask, word/8)
  1531  				if (bits>>(word%8))&1 == 0 {
  1532  					return '$'
  1533  				}
  1534  			}
  1535  
  1536  			val := *(*uintptr)(unsafe.Pointer(p))
  1537  			if state != nil && state.stack.lo <= val && val < state.stack.hi {
  1538  				return '@'
  1539  			}
  1540  
  1541  			span := spanOfHeap(val)
  1542  			if span == nil {
  1543  				return ' '
  1544  			}
  1545  			idx := span.objIndex(val)
  1546  			if span.isFreeOrNewlyAllocated(idx) {
  1547  				return ' '
  1548  			}
  1549  			return '*'
  1550  		})
  1551  		printunlock()
  1552  	}
  1553  
  1554  	for i := uintptr(0); i < n; i += goarch.PtrSize {
  1555  		if ptrmask != nil {
  1556  			word := i / goarch.PtrSize
  1557  			bits := *addb(ptrmask, word/8)
  1558  			if bits == 0 {
  1559  				// Skip 8 words (the loop increment will do the 8th)
  1560  				//
  1561  				// This must be the first time we've
  1562  				// seen this word of ptrmask, so i
  1563  				// must be 8-word-aligned, but check
  1564  				// our reasoning just in case.
  1565  				if i%(goarch.PtrSize*8) != 0 {
  1566  					throw("misaligned mask")
  1567  				}
  1568  				i += goarch.PtrSize*8 - goarch.PtrSize
  1569  				continue
  1570  			}
  1571  			if (bits>>(word%8))&1 == 0 {
  1572  				continue
  1573  			}
  1574  		}
  1575  
  1576  		val := *(*uintptr)(unsafe.Pointer(b + i))
  1577  
  1578  		// Check if val points into the stack.
  1579  		if state != nil && state.stack.lo <= val && val < state.stack.hi {
  1580  			// val may point to a stack object. This
  1581  			// object may be dead from last cycle and
  1582  			// hence may contain pointers to unallocated
  1583  			// objects, but unlike heap objects we can't
  1584  			// tell if it's already dead. Hence, if all
  1585  			// pointers to this object are from
  1586  			// conservative scanning, we have to scan it
  1587  			// defensively, too.
  1588  			state.putPtr(val, true)
  1589  			continue
  1590  		}
  1591  
  1592  		// Check if val points to a heap span.
  1593  		span := spanOfHeap(val)
  1594  		if span == nil {
  1595  			continue
  1596  		}
  1597  
  1598  		// Check if val points to an allocated object.
  1599  		//
  1600  		// Ignore objects allocated during the mark phase, they've
  1601  		// been allocated black.
  1602  		idx := span.objIndex(val)
  1603  		if span.isFreeOrNewlyAllocated(idx) {
  1604  			continue
  1605  		}
  1606  
  1607  		// val points to an allocated object. Mark it.
  1608  		obj := span.base() + idx*span.elemsize
  1609  		if !tryDeferToSpanScan(obj, gcw) {
  1610  			greyobject(obj, b, i, span, gcw, idx)
  1611  		}
  1612  	}
  1613  }
  1614  
  1615  // Shade the object if it isn't already.
  1616  // The object is not nil and known to be in the heap.
  1617  // Preemption must be disabled.
  1618  //
  1619  //go:nowritebarrier
  1620  func shade(b uintptr) {
  1621  	gcw := &getg().m.p.ptr().gcw
  1622  	if !tryDeferToSpanScan(b, gcw) {
  1623  		if obj, span, objIndex := findObject(b, 0, 0); obj != 0 {
  1624  			greyobject(obj, 0, 0, span, gcw, objIndex)
  1625  		}
  1626  	}
  1627  }
  1628  
  1629  // obj is the start of an object with mark mbits.
  1630  // If it isn't already marked, mark it and enqueue into gcw.
  1631  // base and off are for debugging only and could be removed.
  1632  //
  1633  // See also wbBufFlush1, which partially duplicates this logic.
  1634  //
  1635  //go:nowritebarrierrec
  1636  func greyobject(obj, base, off uintptr, span *mspan, gcw *gcWork, objIndex uintptr) {
  1637  	// obj should be start of allocation, and so must be at least pointer-aligned.
  1638  	if obj&(goarch.PtrSize-1) != 0 {
  1639  		throw("greyobject: obj not pointer-aligned")
  1640  	}
  1641  	mbits := span.markBitsForIndex(objIndex)
  1642  
  1643  	if useCheckmark {
  1644  		if setCheckmark(obj, base, off, mbits) {
  1645  			// Already marked.
  1646  			return
  1647  		}
  1648  		if debug.checkfinalizers > 1 {
  1649  			print("  mark ", hex(obj), " found at *(", hex(base), "+", hex(off), ")\n")
  1650  		}
  1651  	} else {
  1652  		if debug.gccheckmark > 0 && span.isFree(objIndex) {
  1653  			print("runtime: marking free object ", hex(obj), " found at *(", hex(base), "+", hex(off), ")\n")
  1654  			gcDumpObject("base", base, off)
  1655  			gcDumpObject("obj", obj, ^uintptr(0))
  1656  			getg().m.traceback = 2
  1657  			throw("marking free object")
  1658  		}
  1659  
  1660  		// If marked we have nothing to do.
  1661  		if mbits.isMarked() {
  1662  			return
  1663  		}
  1664  		mbits.setMarked()
  1665  
  1666  		// Mark span.
  1667  		arena, pageIdx, pageMask := pageIndexOf(span.base())
  1668  		if arena.pageMarks[pageIdx]&pageMask == 0 {
  1669  			atomic.Or8(&arena.pageMarks[pageIdx], pageMask)
  1670  		}
  1671  	}
  1672  
  1673  	// If this is a noscan object, fast-track it to black
  1674  	// instead of greying it.
  1675  	if span.spanclass.noscan() {
  1676  		gcw.bytesMarked += uint64(span.elemsize)
  1677  		return
  1678  	}
  1679  
  1680  	// We're adding obj to P's local workbuf, so it's likely
  1681  	// this object will be processed soon by the same P.
  1682  	// Even if the workbuf gets flushed, there will likely still be
  1683  	// some benefit on platforms with inclusive shared caches.
  1684  	sys.Prefetch(obj)
  1685  	// Queue the obj for scanning.
  1686  	if !gcw.putObjFast(obj) {
  1687  		gcw.putObj(obj)
  1688  	}
  1689  }
  1690  
  1691  // gcDumpObject dumps the contents of obj for debugging and marks the
  1692  // field at byte offset off in obj.
  1693  func gcDumpObject(label string, obj, off uintptr) {
  1694  	s := spanOf(obj)
  1695  	print(label, "=", hex(obj))
  1696  	if s == nil {
  1697  		print(" s=nil\n")
  1698  		return
  1699  	}
  1700  	print(" s.base()=", hex(s.base()), " s.limit=", hex(s.limit), " s.spanclass=", s.spanclass, " s.elemsize=", s.elemsize, " s.state=")
  1701  	if state := s.state.get(); 0 <= state && int(state) < len(mSpanStateNames) {
  1702  		print(mSpanStateNames[state], "\n")
  1703  	} else {
  1704  		print("unknown(", state, ")\n")
  1705  	}
  1706  
  1707  	skipped := false
  1708  	size := s.elemsize
  1709  	if s.state.get() == mSpanManual && size == 0 {
  1710  		// We're printing something from a stack frame. We
  1711  		// don't know how big it is, so just show up to an
  1712  		// including off.
  1713  		size = off + goarch.PtrSize
  1714  	}
  1715  	for i := uintptr(0); i < size; i += goarch.PtrSize {
  1716  		// For big objects, just print the beginning (because
  1717  		// that usually hints at the object's type) and the
  1718  		// fields around off.
  1719  		if !(i < 128*goarch.PtrSize || off-16*goarch.PtrSize < i && i < off+16*goarch.PtrSize) {
  1720  			skipped = true
  1721  			continue
  1722  		}
  1723  		if skipped {
  1724  			print(" ...\n")
  1725  			skipped = false
  1726  		}
  1727  		print(" *(", label, "+", i, ") = ", hex(*(*uintptr)(unsafe.Pointer(obj + i))))
  1728  		if i == off {
  1729  			print(" <==")
  1730  		}
  1731  		print("\n")
  1732  	}
  1733  	if skipped {
  1734  		print(" ...\n")
  1735  	}
  1736  }
  1737  
  1738  // gcmarknewobject marks a newly allocated object black. obj must
  1739  // not contain any non-nil pointers.
  1740  //
  1741  // This is nosplit so it can manipulate a gcWork without preemption.
  1742  //
  1743  //go:nowritebarrier
  1744  //go:nosplit
  1745  func gcmarknewobject(span *mspan, obj uintptr) {
  1746  	if useCheckmark { // The world should be stopped so this should not happen.
  1747  		throw("gcmarknewobject called while doing checkmark")
  1748  	}
  1749  	if gcphase == _GCmarktermination {
  1750  		// Check this here instead of on the hot path.
  1751  		throw("mallocgc called with gcphase == _GCmarktermination")
  1752  	}
  1753  
  1754  	// Mark object.
  1755  	objIndex := span.objIndex(obj)
  1756  	span.markBitsForIndex(objIndex).setMarked()
  1757  	if goexperiment.GreenTeaGC && gcUsesSpanInlineMarkBits(span.elemsize) {
  1758  		// No need to scan the new object.
  1759  		span.scannedBitsForIndex(objIndex).setMarked()
  1760  	}
  1761  
  1762  	// Mark span.
  1763  	arena, pageIdx, pageMask := pageIndexOf(span.base())
  1764  	if arena.pageMarks[pageIdx]&pageMask == 0 {
  1765  		atomic.Or8(&arena.pageMarks[pageIdx], pageMask)
  1766  	}
  1767  
  1768  	gcw := &getg().m.p.ptr().gcw
  1769  	gcw.bytesMarked += uint64(span.elemsize)
  1770  }
  1771  
  1772  // gcMarkTinyAllocs greys all active tiny alloc blocks.
  1773  //
  1774  // The world must be stopped.
  1775  func gcMarkTinyAllocs() {
  1776  	assertWorldStopped()
  1777  
  1778  	for _, p := range allp {
  1779  		c := p.mcache
  1780  		if c == nil || c.tiny == 0 {
  1781  			continue
  1782  		}
  1783  		gcw := &p.gcw
  1784  		if !tryDeferToSpanScan(c.tiny, gcw) {
  1785  			_, span, objIndex := findObject(c.tiny, 0, 0)
  1786  			greyobject(c.tiny, 0, 0, span, gcw, objIndex)
  1787  		}
  1788  	}
  1789  }
  1790  

View as plain text