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

View as plain text