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.
5 // Garbage collector: marking and scanning
12 "internal/goexperiment"
13 "runtime/internal/atomic"
14 "runtime/internal/sys"
19 fixedRootFinalizers = iota
23 // rootBlockBytes is the number of bytes to scan per data or
25 rootBlockBytes = 256 << 10
27 // maxObletBytes is the maximum bytes of an object to scan at
28 // once. Larger objects will be split up into "oblets" of at
29 // most this size. Since we can scan 1–2 MB/ms, 128 KB bounds
30 // scan preemption at ~100 µs.
32 // This must be > _MaxSmallSize so that the object base is the
34 maxObletBytes = 128 << 10
36 // drainCheckThreshold specifies how many units of work to do
37 // between self-preemption checks in gcDrain. Assuming a scan
38 // rate of 1 MB/ms, this is ~100 µs. Lower values have higher
39 // overhead in the scan loop (the scheduler check may perform
40 // a syscall, so its overhead is nontrivial). Higher values
41 // make the system less responsive to incoming work.
42 drainCheckThreshold = 100000
44 // pagesPerSpanRoot indicates how many pages to scan from a span root
45 // at a time. Used by special root marking.
47 // Higher values improve throughput by increasing locality, but
48 // increase the minimum latency of a marking operation.
50 // Must be a multiple of the pageInUse bitmap element size and
51 // must also evenly divide pagesPerArena.
52 pagesPerSpanRoot = 512
55 // gcMarkRootPrepare queues root scanning jobs (stacks, globals, and
56 // some miscellany) and initializes scanning-related state.
58 // The world must be stopped.
59 func gcMarkRootPrepare() {
62 // Compute how many data and BSS root blocks there are.
63 nBlocks := func(bytes uintptr) int {
64 return int(divRoundUp(bytes, rootBlockBytes))
71 for _, datap := range activeModules() {
72 nDataRoots := nBlocks(datap.edata - datap.data)
73 if nDataRoots > work.nDataRoots {
74 work.nDataRoots = nDataRoots
78 for _, datap := range activeModules() {
79 nBSSRoots := nBlocks(datap.ebss - datap.bss)
80 if nBSSRoots > work.nBSSRoots {
81 work.nBSSRoots = nBSSRoots
85 // Scan span roots for finalizer specials.
87 // We depend on addfinalizer to mark objects that get
88 // finalizers after root marking.
90 // We're going to scan the whole heap (that was available at the time the
91 // mark phase started, i.e. markArenas) for in-use spans which have specials.
93 // Break up the work into arenas, and further into chunks.
95 // Snapshot allArenas as markArenas. This snapshot is safe because allArenas
97 mheap_.markArenas = mheap_.allArenas[:len(mheap_.allArenas):len(mheap_.allArenas)]
98 work.nSpanRoots = len(mheap_.markArenas) * (pagesPerArena / pagesPerSpanRoot)
102 // Gs may be created after this point, but it's okay that we
103 // ignore them because they begin life without any roots, so
104 // there's nothing to scan, and any roots they create during
105 // the concurrent phase will be caught by the write barrier.
106 work.stackRoots = allGsSnapshot()
107 work.nStackRoots = len(work.stackRoots)
109 work.markrootNext = 0
110 work.markrootJobs = uint32(fixedRootCount + work.nDataRoots + work.nBSSRoots + work.nSpanRoots + work.nStackRoots)
112 // Calculate base indexes of each root type
113 work.baseData = uint32(fixedRootCount)
114 work.baseBSS = work.baseData + uint32(work.nDataRoots)
115 work.baseSpans = work.baseBSS + uint32(work.nBSSRoots)
116 work.baseStacks = work.baseSpans + uint32(work.nSpanRoots)
117 work.baseEnd = work.baseStacks + uint32(work.nStackRoots)
120 // gcMarkRootCheck checks that all roots have been scanned. It is
121 // purely for debugging.
122 func gcMarkRootCheck() {
123 if work.markrootNext < work.markrootJobs {
124 print(work.markrootNext, " of ", work.markrootJobs, " markroot jobs done\n")
125 throw("left over markroot jobs")
128 // Check that stacks have been scanned.
130 // We only check the first nStackRoots Gs that we should have scanned.
131 // Since we don't care about newer Gs (see comment in
132 // gcMarkRootPrepare), no locking is required.
134 forEachGRace(func(gp *g) {
135 if i >= work.nStackRoots {
140 println("gp", gp, "goid", gp.goid,
141 "status", readgstatus(gp),
142 "gcscandone", gp.gcscandone)
143 throw("scan missed a g")
150 // ptrmask for an allocation containing a single pointer.
151 var oneptrmask = [...]uint8{1}
153 // markroot scans the i'th root.
155 // Preemption must be disabled (because this uses a gcWork).
157 // Returns the amount of GC work credit produced by the operation.
158 // If flushBgCredit is true, then that credit is also flushed
159 // to the background credit pool.
161 // nowritebarrier is only advisory here.
164 func markroot(gcw *gcWork, i uint32, flushBgCredit bool) int64 {
165 // Note: if you add a case here, please also update heapdump.go:dumproots.
167 var workCounter *atomic.Int64
169 case work.baseData <= i && i < work.baseBSS:
170 workCounter = &gcController.globalsScanWork
171 for _, datap := range activeModules() {
172 workDone += markrootBlock(datap.data, datap.edata-datap.data, datap.gcdatamask.bytedata, gcw, int(i-work.baseData))
175 case work.baseBSS <= i && i < work.baseSpans:
176 workCounter = &gcController.globalsScanWork
177 for _, datap := range activeModules() {
178 workDone += markrootBlock(datap.bss, datap.ebss-datap.bss, datap.gcbssmask.bytedata, gcw, int(i-work.baseBSS))
181 case i == fixedRootFinalizers:
182 for fb := allfin; fb != nil; fb = fb.alllink {
183 cnt := uintptr(atomic.Load(&fb.cnt))
184 scanblock(uintptr(unsafe.Pointer(&fb.fin[0])), cnt*unsafe.Sizeof(fb.fin[0]), &finptrmask[0], gcw, nil)
187 case i == fixedRootFreeGStacks:
188 // Switch to the system stack so we can call
190 systemstack(markrootFreeGStacks)
192 case work.baseSpans <= i && i < work.baseStacks:
193 // mark mspan.specials
194 markrootSpans(gcw, int(i-work.baseSpans))
197 // the rest is scanning goroutine stacks
198 workCounter = &gcController.stackScanWork
199 if i < work.baseStacks || work.baseEnd <= i {
201 print("runtime: markroot index ", i, " not in stack roots range [", work.baseStacks, ", ", work.baseEnd, ")\n")
202 throw("markroot: bad index")
204 gp := work.stackRoots[i-work.baseStacks]
206 // remember when we've first observed the G blocked
207 // needed only to output in traceback
208 status := readgstatus(gp) // We are not in a scan state
209 if (status == _Gwaiting || status == _Gsyscall) && gp.waitsince == 0 {
210 gp.waitsince = work.tstart
213 // scanstack must be done on the system stack in case
214 // we're trying to scan our own stack.
216 // If this is a self-scan, put the user G in
217 // _Gwaiting to prevent self-deadlock. It may
218 // already be in _Gwaiting if this is a mark
219 // worker or we're in mark termination.
220 userG := getg().m.curg
221 selfScan := gp == userG && readgstatus(userG) == _Grunning
223 casGToWaiting(userG, _Grunning, waitReasonGarbageCollectionScan)
226 // TODO: suspendG blocks (and spins) until gp
227 // stops, which may take a while for
228 // running goroutines. Consider doing this in
229 // two phases where the first is non-blocking:
230 // we scan the stacks we can and ask running
231 // goroutines to scan themselves; and the
233 stopped := suspendG(gp)
239 throw("g already scanned")
241 workDone += scanstack(gp, gcw)
246 casgstatus(userG, _Gwaiting, _Grunning)
250 if workCounter != nil && workDone != 0 {
251 workCounter.Add(workDone)
253 gcFlushBgCredit(workDone)
259 // markrootBlock scans the shard'th shard of the block of memory [b0,
260 // b0+n0), with the given pointer mask.
262 // Returns the amount of work done.
265 func markrootBlock(b0, n0 uintptr, ptrmask0 *uint8, gcw *gcWork, shard int) int64 {
266 if rootBlockBytes%(8*goarch.PtrSize) != 0 {
267 // This is necessary to pick byte offsets in ptrmask0.
268 throw("rootBlockBytes must be a multiple of 8*ptrSize")
271 // Note that if b0 is toward the end of the address space,
272 // then b0 + rootBlockBytes might wrap around.
273 // These tests are written to avoid any possible overflow.
274 off := uintptr(shard) * rootBlockBytes
279 ptrmask := (*uint8)(add(unsafe.Pointer(ptrmask0), uintptr(shard)*(rootBlockBytes/(8*goarch.PtrSize))))
280 n := uintptr(rootBlockBytes)
286 scanblock(b, n, ptrmask, gcw, nil)
290 // markrootFreeGStacks frees stacks of dead Gs.
292 // This does not free stacks of dead Gs cached on Ps, but having a few
293 // cached stacks around isn't a problem.
294 func markrootFreeGStacks() {
295 // Take list of dead Gs with stacks.
296 lock(&sched.gFree.lock)
297 list := sched.gFree.stack
298 sched.gFree.stack = gList{}
299 unlock(&sched.gFree.lock)
305 q := gQueue{list.head, list.head}
306 for gp := list.head.ptr(); gp != nil; gp = gp.schedlink.ptr() {
310 // Manipulate the queue directly since the Gs are
311 // already all linked the right way.
315 // Put Gs back on the free list.
316 lock(&sched.gFree.lock)
317 sched.gFree.noStack.pushAll(q)
318 unlock(&sched.gFree.lock)
321 // markrootSpans marks roots for one shard of markArenas.
324 func markrootSpans(gcw *gcWork, shard int) {
325 // Objects with finalizers have two GC-related invariants:
327 // 1) Everything reachable from the object must be marked.
328 // This ensures that when we pass the object to its finalizer,
329 // everything the finalizer can reach will be retained.
331 // 2) Finalizer specials (which are not in the garbage
332 // collected heap) are roots. In practice, this means the fn
333 // field must be scanned.
334 sg := mheap_.sweepgen
336 // Find the arena and page index into that arena for this shard.
337 ai := mheap_.markArenas[shard/(pagesPerArena/pagesPerSpanRoot)]
338 ha := mheap_.arenas[ai.l1()][ai.l2()]
339 arenaPage := uint(uintptr(shard) * pagesPerSpanRoot % pagesPerArena)
341 // Construct slice of bitmap which we'll iterate over.
342 specialsbits := ha.pageSpecials[arenaPage/8:]
343 specialsbits = specialsbits[:pagesPerSpanRoot/8]
344 for i := range specialsbits {
345 // Find set bits, which correspond to spans with specials.
346 specials := atomic.Load8(&specialsbits[i])
350 for j := uint(0); j < 8; j++ {
351 if specials&(1<<j) == 0 {
354 // Find the span for this bit.
356 // This value is guaranteed to be non-nil because having
357 // specials implies that the span is in-use, and since we're
358 // currently marking we can be sure that we don't have to worry
359 // about the span being freed and re-used.
360 s := ha.spans[arenaPage+uint(i)*8+j]
362 // The state must be mSpanInUse if the specials bit is set, so
363 // sanity check that.
364 if state := s.state.get(); state != mSpanInUse {
365 print("s.state = ", state, "\n")
366 throw("non in-use span found with specials bit set")
368 // Check that this span was swept (it may be cached or uncached).
369 if !useCheckmark && !(s.sweepgen == sg || s.sweepgen == sg+3) {
370 // sweepgen was updated (+2) during non-checkmark GC pass
371 print("sweep ", s.sweepgen, " ", sg, "\n")
372 throw("gc: unswept span")
375 // Lock the specials to prevent a special from being
376 // removed from the list while we're traversing it.
378 for sp := s.specials; sp != nil; sp = sp.next {
379 if sp.kind != _KindSpecialFinalizer {
382 // don't mark finalized object, but scan it so we
383 // retain everything it points to.
384 spf := (*specialfinalizer)(unsafe.Pointer(sp))
385 // A finalizer can be set for an inner byte of an object, find object beginning.
386 p := s.base() + uintptr(spf.special.offset)/s.elemsize*s.elemsize
388 // Mark everything that can be reached from
389 // the object (but *not* the object itself or
390 // we'll never collect it).
391 if !s.spanclass.noscan() {
395 // The special itself is a root.
396 scanblock(uintptr(unsafe.Pointer(&spf.fn)), goarch.PtrSize, &oneptrmask[0], gcw, nil)
398 unlock(&s.speciallock)
403 // gcAssistAlloc performs GC work to make gp's assist debt positive.
404 // gp must be the calling user goroutine.
406 // This must be called with preemption enabled.
407 func gcAssistAlloc(gp *g) {
408 // Don't assist in non-preemptible contexts. These are
409 // generally fragile and won't allow the assist to block.
410 if getg() == gp.m.g0 {
413 if mp := getg().m; mp.locks > 0 || mp.preemptoff != "" {
419 if gcCPULimiter.limiting() {
420 // If the CPU limiter is enabled, intentionally don't
421 // assist to reduce the amount of CPU time spent in the GC.
423 trace := traceAcquire()
425 trace.GCMarkAssistDone()
431 // Compute the amount of scan work we need to do to make the
432 // balance positive. When the required amount of work is low,
433 // we over-assist to build up credit for future allocations
434 // and amortize the cost of assisting.
435 assistWorkPerByte := gcController.assistWorkPerByte.Load()
436 assistBytesPerWork := gcController.assistBytesPerWork.Load()
437 debtBytes := -gp.gcAssistBytes
438 scanWork := int64(assistWorkPerByte * float64(debtBytes))
439 if scanWork < gcOverAssistWork {
440 scanWork = gcOverAssistWork
441 debtBytes = int64(assistBytesPerWork * float64(scanWork))
444 // Steal as much credit as we can from the background GC's
445 // scan credit. This is racy and may drop the background
446 // credit below 0 if two mutators steal at the same time. This
447 // will just cause steals to fail until credit is accumulated
448 // again, so in the long run it doesn't really matter, but we
449 // do have to handle the negative credit case.
450 bgScanCredit := gcController.bgScanCredit.Load()
452 if bgScanCredit > 0 {
453 if bgScanCredit < scanWork {
454 stolen = bgScanCredit
455 gp.gcAssistBytes += 1 + int64(assistBytesPerWork*float64(stolen))
458 gp.gcAssistBytes += debtBytes
460 gcController.bgScanCredit.Add(-stolen)
465 // We were able to steal all of the credit we
468 trace := traceAcquire()
470 trace.GCMarkAssistDone()
477 if traceEnabled() && !traced {
478 trace := traceAcquire()
481 trace.GCMarkAssistStart()
486 // Perform assist work
488 gcAssistAlloc1(gp, scanWork)
489 // The user stack may have moved, so this can't touch
490 // anything on it until it returns from systemstack.
493 completed := gp.param != nil
499 if gp.gcAssistBytes < 0 {
500 // We were unable steal enough credit or perform
501 // enough work to pay off the assist debt. We need to
502 // do one of these before letting the mutator allocate
503 // more to prevent over-allocation.
505 // If this is because we were preempted, reschedule
506 // and try some more.
512 // Add this G to an assist queue and park. When the GC
513 // has more background credit, it will satisfy queued
514 // assists before flushing to the global credit pool.
516 // Note that this does *not* get woken up when more
517 // work is added to the work list. The theory is that
518 // there wasn't enough work to do anyway, so we might
519 // as well let background marking take care of the
520 // work that is available.
525 // At this point either background GC has satisfied
526 // this G's assist debt, or the GC cycle is over.
529 trace := traceAcquire()
531 trace.GCMarkAssistDone()
537 // gcAssistAlloc1 is the part of gcAssistAlloc that runs on the system
538 // stack. This is a separate function to make it easier to see that
539 // we're not capturing anything from the user stack, since the user
540 // stack may move while we're in this function.
542 // gcAssistAlloc1 indicates whether this assist completed the mark
543 // phase by setting gp.param to non-nil. This can't be communicated on
544 // the stack since it may move.
547 func gcAssistAlloc1(gp *g, scanWork int64) {
548 // Clear the flag indicating that this assist completed the
552 if atomic.Load(&gcBlackenEnabled) == 0 {
553 // The gcBlackenEnabled check in malloc races with the
554 // store that clears it but an atomic check in every malloc
555 // would be a performance hit.
556 // Instead we recheck it here on the non-preemptible system
557 // stack to determine if we should perform an assist.
559 // GC is done, so ignore any remaining debt.
563 // Track time spent in this assist. Since we're on the
564 // system stack, this is non-preemptible, so we can
565 // just measure start and end time.
567 // Limiter event tracking might be disabled if we end up here
568 // while on a mark worker.
569 startTime := nanotime()
570 trackLimiterEvent := gp.m.p.ptr().limiterEvent.start(limiterEventMarkAssist, startTime)
572 decnwait := atomic.Xadd(&work.nwait, -1)
573 if decnwait == work.nproc {
574 println("runtime: work.nwait =", decnwait, "work.nproc=", work.nproc)
575 throw("nwait > work.nprocs")
578 // gcDrainN requires the caller to be preemptible.
579 casGToWaiting(gp, _Grunning, waitReasonGCAssistMarking)
581 // drain own cached work first in the hopes that it
582 // will be more cache friendly.
583 gcw := &getg().m.p.ptr().gcw
584 workDone := gcDrainN(gcw, scanWork)
586 casgstatus(gp, _Gwaiting, _Grunning)
588 // Record that we did this much scan work.
590 // Back out the number of bytes of assist credit that
591 // this scan work counts for. The "1+" is a poor man's
592 // round-up, to ensure this adds credit even if
593 // assistBytesPerWork is very low.
594 assistBytesPerWork := gcController.assistBytesPerWork.Load()
595 gp.gcAssistBytes += 1 + int64(assistBytesPerWork*float64(workDone))
597 // If this is the last worker and we ran out of work,
598 // signal a completion point.
599 incnwait := atomic.Xadd(&work.nwait, +1)
600 if incnwait > work.nproc {
601 println("runtime: work.nwait=", incnwait,
602 "work.nproc=", work.nproc)
603 throw("work.nwait > work.nproc")
606 if incnwait == work.nproc && !gcMarkWorkAvailable(nil) {
607 // This has reached a background completion point. Set
608 // gp.param to a non-nil value to indicate this. It
609 // doesn't matter what we set it to (it just has to be
611 gp.param = unsafe.Pointer(gp)
614 duration := now - startTime
616 pp.gcAssistTime += duration
617 if trackLimiterEvent {
618 pp.limiterEvent.stop(limiterEventMarkAssist, now)
620 if pp.gcAssistTime > gcAssistTimeSlack {
621 gcController.assistTime.Add(pp.gcAssistTime)
622 gcCPULimiter.update(now)
627 // gcWakeAllAssists wakes all currently blocked assists. This is used
628 // at the end of a GC cycle. gcBlackenEnabled must be false to prevent
629 // new assists from going to sleep after this point.
630 func gcWakeAllAssists() {
631 lock(&work.assistQueue.lock)
632 list := work.assistQueue.q.popList()
634 unlock(&work.assistQueue.lock)
637 // gcParkAssist puts the current goroutine on the assist queue and parks.
639 // gcParkAssist reports whether the assist is now satisfied. If it
640 // returns false, the caller must retry the assist.
641 func gcParkAssist() bool {
642 lock(&work.assistQueue.lock)
643 // If the GC cycle finished while we were getting the lock,
644 // exit the assist. The cycle can't finish while we hold the
646 if atomic.Load(&gcBlackenEnabled) == 0 {
647 unlock(&work.assistQueue.lock)
652 oldList := work.assistQueue.q
653 work.assistQueue.q.pushBack(gp)
655 // Recheck for background credit now that this G is in
656 // the queue, but can still back out. This avoids a
657 // race in case background marking has flushed more
658 // credit since we checked above.
659 if gcController.bgScanCredit.Load() > 0 {
660 work.assistQueue.q = oldList
661 if oldList.tail != 0 {
662 oldList.tail.ptr().schedlink.set(nil)
664 unlock(&work.assistQueue.lock)
668 goparkunlock(&work.assistQueue.lock, waitReasonGCAssistWait, traceBlockGCMarkAssist, 2)
672 // gcFlushBgCredit flushes scanWork units of background scan work
673 // credit. This first satisfies blocked assists on the
674 // work.assistQueue and then flushes any remaining credit to
675 // gcController.bgScanCredit.
677 // Write barriers are disallowed because this is used by gcDrain after
678 // it has ensured that all work is drained and this must preserve that
681 //go:nowritebarrierrec
682 func gcFlushBgCredit(scanWork int64) {
683 if work.assistQueue.q.empty() {
684 // Fast path; there are no blocked assists. There's a
685 // small window here where an assist may add itself to
686 // the blocked queue and park. If that happens, we'll
687 // just get it on the next flush.
688 gcController.bgScanCredit.Add(scanWork)
692 assistBytesPerWork := gcController.assistBytesPerWork.Load()
693 scanBytes := int64(float64(scanWork) * assistBytesPerWork)
695 lock(&work.assistQueue.lock)
696 for !work.assistQueue.q.empty() && scanBytes > 0 {
697 gp := work.assistQueue.q.pop()
698 // Note that gp.gcAssistBytes is negative because gp
699 // is in debt. Think carefully about the signs below.
700 if scanBytes+gp.gcAssistBytes >= 0 {
701 // Satisfy this entire assist debt.
702 scanBytes += gp.gcAssistBytes
704 // It's important that we *not* put gp in
705 // runnext. Otherwise, it's possible for user
706 // code to exploit the GC worker's high
707 // scheduler priority to get itself always run
708 // before other goroutines and always in the
709 // fresh quantum started by GC.
712 // Partially satisfy this assist.
713 gp.gcAssistBytes += scanBytes
715 // As a heuristic, we move this assist to the
716 // back of the queue so that large assists
717 // can't clog up the assist queue and
718 // substantially delay small assists.
719 work.assistQueue.q.pushBack(gp)
725 // Convert from scan bytes back to work.
726 assistWorkPerByte := gcController.assistWorkPerByte.Load()
727 scanWork = int64(float64(scanBytes) * assistWorkPerByte)
728 gcController.bgScanCredit.Add(scanWork)
730 unlock(&work.assistQueue.lock)
733 // scanstack scans gp's stack, greying all pointers found on the stack.
735 // Returns the amount of scan work performed, but doesn't update
736 // gcController.stackScanWork or flush any credit. Any background credit produced
737 // by this function should be flushed by its caller. scanstack itself can't
738 // safely flush because it may result in trying to wake up a goroutine that
739 // was just scanned, resulting in a self-deadlock.
741 // scanstack will also shrink the stack if it is safe to do so. If it
742 // is not, it schedules a stack shrink for the next synchronous safe
745 // scanstack is marked go:systemstack because it must not be preempted
746 // while using a workbuf.
750 func scanstack(gp *g, gcw *gcWork) int64 {
751 if readgstatus(gp)&_Gscan == 0 {
752 print("runtime:scanstack: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", hex(readgstatus(gp)), "\n")
753 throw("scanstack - bad status")
756 switch readgstatus(gp) &^ _Gscan {
758 print("runtime: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n")
759 throw("mark - bad status")
763 print("runtime: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n")
764 throw("scanstack: goroutine not stopped")
765 case _Grunnable, _Gsyscall, _Gwaiting:
770 throw("can't scan our own stack")
773 // scannedSize is the amount of work we'll be reporting.
775 // It is less than the allocated size (which is hi-lo).
777 if gp.syscallsp != 0 {
778 sp = gp.syscallsp // If in a system call this is the stack pointer (gp.sched.sp can be 0 in this case on Windows).
782 scannedSize := gp.stack.hi - sp
784 // Keep statistics for initial stack size calculation.
785 // Note that this accumulates the scanned size, not the allocated size.
786 p := getg().m.p.ptr()
787 p.scannedStackSize += uint64(scannedSize)
790 if isShrinkStackSafe(gp) {
791 // Shrink the stack if not much of it is being used.
794 // Otherwise, shrink the stack at the next sync safe point.
795 gp.preemptShrink = true
798 var state stackScanState
799 state.stack = gp.stack
802 println("stack trace goroutine", gp.goid)
805 if debugScanConservative && gp.asyncSafePoint {
806 print("scanning async preempted goroutine ", gp.goid, " stack [", hex(gp.stack.lo), ",", hex(gp.stack.hi), ")\n")
809 // Scan the saved context register. This is effectively a live
810 // register that gets moved back and forth between the
811 // register and sched.ctxt without a write barrier.
812 if gp.sched.ctxt != nil {
813 scanblock(uintptr(unsafe.Pointer(&gp.sched.ctxt)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
816 // Scan the stack. Accumulate a list of stack objects.
818 for u.init(gp, 0); u.valid(); u.next() {
819 scanframeworker(&u.frame, &state, gcw)
822 // Find additional pointers that point into the stack from the heap.
823 // Currently this includes defers and panics. See also function copystack.
825 // Find and trace other pointers in defer records.
826 for d := gp._defer; d != nil; d = d.link {
828 // Scan the func value, which could be a stack allocated closure.
830 scanblock(uintptr(unsafe.Pointer(&d.fn)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
833 // The link field of a stack-allocated defer record might point
834 // to a heap-allocated defer record. Keep that heap record live.
835 scanblock(uintptr(unsafe.Pointer(&d.link)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
837 // Retain defers records themselves.
838 // Defer records might not be reachable from the G through regular heap
839 // tracing because the defer linked list might weave between the stack and the heap.
841 scanblock(uintptr(unsafe.Pointer(&d)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
844 if gp._panic != nil {
845 // Panics are always stack allocated.
846 state.putPtr(uintptr(unsafe.Pointer(gp._panic)), false)
849 // Find and scan all reachable stack objects.
851 // The state's pointer queue prioritizes precise pointers over
852 // conservative pointers so that we'll prefer scanning stack
853 // objects precisely.
856 p, conservative := state.getPtr()
860 obj := state.findObject(p)
866 // We've already scanned this object.
869 obj.setRecord(nil) // Don't scan it again.
872 print(" live stkobj at", hex(state.stack.lo+uintptr(obj.off)), "of size", obj.size)
874 print(" (conservative)")
882 // This path is pretty unlikely, an object large enough
883 // to have a GC program allocated on the stack.
884 // We need some space to unpack the program into a straight
885 // bitmask, which we allocate/free here.
886 // TODO: it would be nice if there were a way to run a GC
887 // program without having to store all its bits. We'd have
888 // to change from a Lempel-Ziv style program to something else.
889 // Or we can forbid putting objects on stacks if they require
890 // a gc program (see issue 27447).
891 s = materializeGCProg(r.ptrdata(), gcdata)
892 gcdata = (*byte)(unsafe.Pointer(s.startAddr))
895 b := state.stack.lo + uintptr(obj.off)
897 scanConservative(b, r.ptrdata(), gcdata, gcw, &state)
899 scanblock(b, r.ptrdata(), gcdata, gcw, &state)
903 dematerializeGCProg(s)
907 // Deallocate object buffers.
908 // (Pointer buffers were all deallocated in the loop above.)
909 for state.head != nil {
913 for i := 0; i < x.nobj; i++ {
915 if obj.r == nil { // reachable
918 println(" dead stkobj at", hex(gp.stack.lo+uintptr(obj.off)), "of size", obj.r.size)
919 // Note: not necessarily really dead - only reachable-from-ptr dead.
923 putempty((*workbuf)(unsafe.Pointer(x)))
925 if state.buf != nil || state.cbuf != nil || state.freeBuf != nil {
926 throw("remaining pointer buffers")
928 return int64(scannedSize)
931 // Scan a stack frame: local variables and function arguments/results.
934 func scanframeworker(frame *stkframe, state *stackScanState, gcw *gcWork) {
935 if _DebugGC > 1 && frame.continpc != 0 {
936 print("scanframe ", funcname(frame.fn), "\n")
939 isAsyncPreempt := frame.fn.valid() && frame.fn.funcID == abi.FuncID_asyncPreempt
940 isDebugCall := frame.fn.valid() && frame.fn.funcID == abi.FuncID_debugCallV2
941 if state.conservative || isAsyncPreempt || isDebugCall {
942 if debugScanConservative {
943 println("conservatively scanning function", funcname(frame.fn), "at PC", hex(frame.continpc))
946 // Conservatively scan the frame. Unlike the precise
947 // case, this includes the outgoing argument space
948 // since we may have stopped while this function was
949 // setting up a call.
951 // TODO: We could narrow this down if the compiler
952 // produced a single map per function of stack slots
953 // and registers that ever contain a pointer.
955 size := frame.varp - frame.sp
957 scanConservative(frame.sp, size, nil, gcw, state)
961 // Scan arguments to this frame.
962 if n := frame.argBytes(); n != 0 {
963 // TODO: We could pass the entry argument map
964 // to narrow this down further.
965 scanConservative(frame.argp, n, nil, gcw, state)
968 if isAsyncPreempt || isDebugCall {
969 // This function's frame contained the
970 // registers for the asynchronously stopped
971 // parent frame. Scan the parent
973 state.conservative = true
975 // We only wanted to scan those two frames
976 // conservatively. Clear the flag for future
978 state.conservative = false
983 locals, args, objs := frame.getStackMap(false)
985 // Scan local variables if stack frame has been allocated.
987 size := uintptr(locals.n) * goarch.PtrSize
988 scanblock(frame.varp-size, size, locals.bytedata, gcw, state)
993 scanblock(frame.argp, uintptr(args.n)*goarch.PtrSize, args.bytedata, gcw, state)
996 // Add all stack objects to the stack object list.
998 // varp is 0 for defers, where there are no locals.
999 // In that case, there can't be a pointer to its args, either.
1000 // (And all args would be scanned above anyway.)
1001 for i := range objs {
1004 base := frame.varp // locals base pointer
1006 base = frame.argp // arguments and return values base pointer
1008 ptr := base + uintptr(off)
1010 // object hasn't been allocated in the frame yet.
1013 if stackTraceDebug {
1014 println("stkobj at", hex(ptr), "of size", obj.size)
1016 state.addObject(ptr, obj)
1021 type gcDrainFlags int
1024 gcDrainUntilPreempt gcDrainFlags = 1 << iota
1025 gcDrainFlushBgCredit
1030 // gcDrainMarkWorkerIdle is a wrapper for gcDrain that exists to better account
1031 // mark time in profiles.
1032 func gcDrainMarkWorkerIdle(gcw *gcWork) {
1033 gcDrain(gcw, gcDrainIdle|gcDrainUntilPreempt|gcDrainFlushBgCredit)
1036 // gcDrainMarkWorkerDedicated is a wrapper for gcDrain that exists to better account
1037 // mark time in profiles.
1038 func gcDrainMarkWorkerDedicated(gcw *gcWork, untilPreempt bool) {
1039 flags := gcDrainFlushBgCredit
1041 flags |= gcDrainUntilPreempt
1046 // gcDrainMarkWorkerFractional is a wrapper for gcDrain that exists to better account
1047 // mark time in profiles.
1048 func gcDrainMarkWorkerFractional(gcw *gcWork) {
1049 gcDrain(gcw, gcDrainFractional|gcDrainUntilPreempt|gcDrainFlushBgCredit)
1052 // gcDrain scans roots and objects in work buffers, blackening grey
1053 // objects until it is unable to get more work. It may return before
1054 // GC is done; it's the caller's responsibility to balance work from
1057 // If flags&gcDrainUntilPreempt != 0, gcDrain returns when g.preempt
1060 // If flags&gcDrainIdle != 0, gcDrain returns when there is other work
1063 // If flags&gcDrainFractional != 0, gcDrain self-preempts when
1064 // pollFractionalWorkerExit() returns true. This implies
1067 // If flags&gcDrainFlushBgCredit != 0, gcDrain flushes scan work
1068 // credit to gcController.bgScanCredit every gcCreditSlack units of
1071 // gcDrain will always return if there is a pending STW or forEachP.
1073 // Disabling write barriers is necessary to ensure that after we've
1074 // confirmed that we've drained gcw, that we don't accidentally end
1075 // up flipping that condition by immediately adding work in the form
1076 // of a write barrier buffer flush.
1078 // Don't set nowritebarrierrec because it's safe for some callees to
1079 // have write barriers enabled.
1082 func gcDrain(gcw *gcWork, flags gcDrainFlags) {
1083 if !writeBarrier.enabled {
1084 throw("gcDrain phase incorrect")
1087 // N.B. We must be running in a non-preemptible context, so it's
1088 // safe to hold a reference to our P here.
1091 preemptible := flags&gcDrainUntilPreempt != 0
1092 flushBgCredit := flags&gcDrainFlushBgCredit != 0
1093 idle := flags&gcDrainIdle != 0
1095 initScanWork := gcw.heapScanWork
1097 // checkWork is the scan work before performing the next
1098 // self-preempt check.
1099 checkWork := int64(1<<63 - 1)
1100 var check func() bool
1101 if flags&(gcDrainIdle|gcDrainFractional) != 0 {
1102 checkWork = initScanWork + drainCheckThreshold
1105 } else if flags&gcDrainFractional != 0 {
1106 check = pollFractionalWorkerExit
1110 // Drain root marking jobs.
1111 if work.markrootNext < work.markrootJobs {
1112 // Stop if we're preemptible, if someone wants to STW, or if
1113 // someone is calling forEachP.
1114 for !(gp.preempt && (preemptible || sched.gcwaiting.Load() || pp.runSafePointFn != 0)) {
1115 job := atomic.Xadd(&work.markrootNext, +1) - 1
1116 if job >= work.markrootJobs {
1119 markroot(gcw, job, flushBgCredit)
1120 if check != nil && check() {
1126 // Drain heap marking jobs.
1128 // Stop if we're preemptible, if someone wants to STW, or if
1129 // someone is calling forEachP.
1131 // TODO(mknyszek): Consider always checking gp.preempt instead
1132 // of having the preempt flag, and making an exception for certain
1133 // mark workers in retake. That might be simpler than trying to
1134 // enumerate all the reasons why we might want to preempt, even
1135 // if we're supposed to be mostly non-preemptible.
1136 for !(gp.preempt && (preemptible || sched.gcwaiting.Load() || pp.runSafePointFn != 0)) {
1137 // Try to keep work available on the global queue. We used to
1138 // check if there were waiting workers, but it's better to
1139 // just keep work available than to make workers wait. In the
1140 // worst case, we'll do O(log(_WorkbufSize)) unnecessary
1146 b := gcw.tryGetFast()
1150 // Flush the write barrier
1151 // buffer; this may create
1158 // Unable to get work.
1163 // Flush background scan work credit to the global
1164 // account if we've accumulated enough locally so
1165 // mutator assists can draw on it.
1166 if gcw.heapScanWork >= gcCreditSlack {
1167 gcController.heapScanWork.Add(gcw.heapScanWork)
1169 gcFlushBgCredit(gcw.heapScanWork - initScanWork)
1172 checkWork -= gcw.heapScanWork
1173 gcw.heapScanWork = 0
1176 checkWork += drainCheckThreshold
1177 if check != nil && check() {
1185 // Flush remaining scan work credit.
1186 if gcw.heapScanWork > 0 {
1187 gcController.heapScanWork.Add(gcw.heapScanWork)
1189 gcFlushBgCredit(gcw.heapScanWork - initScanWork)
1191 gcw.heapScanWork = 0
1195 // gcDrainN blackens grey objects until it has performed roughly
1196 // scanWork units of scan work or the G is preempted. This is
1197 // best-effort, so it may perform less work if it fails to get a work
1198 // buffer. Otherwise, it will perform at least n units of work, but
1199 // may perform more because scanning is always done in whole object
1200 // increments. It returns the amount of scan work performed.
1202 // The caller goroutine must be in a preemptible state (e.g.,
1203 // _Gwaiting) to prevent deadlocks during stack scanning. As a
1204 // consequence, this must be called on the system stack.
1208 func gcDrainN(gcw *gcWork, scanWork int64) int64 {
1209 if !writeBarrier.enabled {
1210 throw("gcDrainN phase incorrect")
1213 // There may already be scan work on the gcw, which we don't
1214 // want to claim was done by this call.
1215 workFlushed := -gcw.heapScanWork
1217 // In addition to backing out because of a preemption, back out
1218 // if the GC CPU limiter is enabled.
1220 for !gp.preempt && !gcCPULimiter.limiting() && workFlushed+gcw.heapScanWork < scanWork {
1221 // See gcDrain comment.
1226 b := gcw.tryGetFast()
1230 // Flush the write barrier buffer;
1231 // this may create more work.
1238 // Try to do a root job.
1239 if work.markrootNext < work.markrootJobs {
1240 job := atomic.Xadd(&work.markrootNext, +1) - 1
1241 if job < work.markrootJobs {
1242 workFlushed += markroot(gcw, job, false)
1246 // No heap or root jobs.
1252 // Flush background scan work credit.
1253 if gcw.heapScanWork >= gcCreditSlack {
1254 gcController.heapScanWork.Add(gcw.heapScanWork)
1255 workFlushed += gcw.heapScanWork
1256 gcw.heapScanWork = 0
1260 // Unlike gcDrain, there's no need to flush remaining work
1261 // here because this never flushes to bgScanCredit and
1262 // gcw.dispose will flush any remaining work to scanWork.
1264 return workFlushed + gcw.heapScanWork
1267 // scanblock scans b as scanobject would, but using an explicit
1268 // pointer bitmap instead of the heap bitmap.
1270 // This is used to scan non-heap roots, so it does not update
1271 // gcw.bytesMarked or gcw.heapScanWork.
1273 // If stk != nil, possible stack pointers are also reported to stk.putPtr.
1276 func scanblock(b0, n0 uintptr, ptrmask *uint8, gcw *gcWork, stk *stackScanState) {
1277 // Use local copies of original parameters, so that a stack trace
1278 // due to one of the throws below shows the original block
1283 for i := uintptr(0); i < n; {
1284 // Find bits for the next word.
1285 bits := uint32(*addb(ptrmask, i/(goarch.PtrSize*8)))
1287 i += goarch.PtrSize * 8
1290 for j := 0; j < 8 && i < n; j++ {
1292 // Same work as in scanobject; see comments there.
1293 p := *(*uintptr)(unsafe.Pointer(b + i))
1295 if obj, span, objIndex := findObject(p, b, i); obj != 0 {
1296 greyobject(obj, b, i, span, gcw, objIndex)
1297 } else if stk != nil && p >= stk.stack.lo && p < stk.stack.hi {
1298 stk.putPtr(p, false)
1308 // scanobject scans the object starting at b, adding pointers to gcw.
1309 // b must point to the beginning of a heap object or an oblet.
1310 // scanobject consults the GC bitmap for the pointer mask and the
1311 // spans for the size of the object.
1314 func scanobject(b uintptr, gcw *gcWork) {
1315 // Prefetch object before we scan it.
1317 // This will overlap fetching the beginning of the object with initial
1318 // setup before we start scanning the object.
1321 // Find the bits for b and the size of the object at b.
1323 // b is either the beginning of an object, in which case this
1324 // is the size of the object to scan, or it points to an
1325 // oblet, in which case we compute the size to scan below.
1326 s := spanOfUnchecked(b)
1329 throw("scanobject n == 0")
1331 if s.spanclass.noscan() {
1332 // Correctness-wise this is ok, but it's inefficient
1333 // if noscan objects reach here.
1334 throw("scanobject of a noscan object")
1338 if n > maxObletBytes {
1339 // Large object. Break into oblets for better
1340 // parallelism and lower latency.
1342 // Enqueue the other oblets to scan later.
1343 // Some oblets may be in b's scalar tail, but
1344 // these will be marked as "no more pointers",
1345 // so we'll drop out immediately when we go to
1347 for oblet := b + maxObletBytes; oblet < s.base()+s.elemsize; oblet += maxObletBytes {
1348 if !gcw.putFast(oblet) {
1354 // Compute the size of the oblet. Since this object
1355 // must be a large object, s.base() is the beginning
1357 n = s.base() + s.elemsize - b
1358 n = min(n, maxObletBytes)
1359 if goexperiment.AllocHeaders {
1360 tp = s.typePointersOfUnchecked(s.base())
1361 tp = tp.fastForward(b-tp.addr, b+n)
1364 if goexperiment.AllocHeaders {
1365 tp = s.typePointersOfUnchecked(b)
1370 if !goexperiment.AllocHeaders {
1371 hbits = heapBitsForAddr(b, n)
1373 var scanSize uintptr
1376 if goexperiment.AllocHeaders {
1377 if tp, addr = tp.nextFast(); addr == 0 {
1378 if tp, addr = tp.next(b + n); addr == 0 {
1383 if hbits, addr = hbits.nextFast(); addr == 0 {
1384 if hbits, addr = hbits.next(); addr == 0 {
1390 // Keep track of farthest pointer we found, so we can
1391 // update heapScanWork. TODO: is there a better metric,
1392 // now that we can skip scalar portions pretty efficiently?
1393 scanSize = addr - b + goarch.PtrSize
1395 // Work here is duplicated in scanblock and above.
1396 // If you make changes here, make changes there too.
1397 obj := *(*uintptr)(unsafe.Pointer(addr))
1399 // At this point we have extracted the next potential pointer.
1400 // Quickly filter out nil and pointers back to the current object.
1401 if obj != 0 && obj-b >= n {
1402 // Test if obj points into the Go heap and, if so,
1405 // Note that it's possible for findObject to
1406 // fail if obj points to a just-allocated heap
1407 // object because of a race with growing the
1408 // heap. In this case, we know the object was
1409 // just allocated and hence will be marked by
1410 // allocation itself.
1411 if obj, span, objIndex := findObject(obj, b, addr-b); obj != 0 {
1412 greyobject(obj, b, addr-b, span, gcw, objIndex)
1416 gcw.bytesMarked += uint64(n)
1417 gcw.heapScanWork += int64(scanSize)
1420 // scanConservative scans block [b, b+n) conservatively, treating any
1421 // pointer-like value in the block as a pointer.
1423 // If ptrmask != nil, only words that are marked in ptrmask are
1424 // considered as potential pointers.
1426 // If state != nil, it's assumed that [b, b+n) is a block in the stack
1427 // and may contain pointers to stack objects.
1428 func scanConservative(b, n uintptr, ptrmask *uint8, gcw *gcWork, state *stackScanState) {
1429 if debugScanConservative {
1431 print("conservatively scanning [", hex(b), ",", hex(b+n), ")\n")
1432 hexdumpWords(b, b+n, func(p uintptr) byte {
1434 word := (p - b) / goarch.PtrSize
1435 bits := *addb(ptrmask, word/8)
1436 if (bits>>(word%8))&1 == 0 {
1441 val := *(*uintptr)(unsafe.Pointer(p))
1442 if state != nil && state.stack.lo <= val && val < state.stack.hi {
1446 span := spanOfHeap(val)
1450 idx := span.objIndex(val)
1451 if span.isFree(idx) {
1459 for i := uintptr(0); i < n; i += goarch.PtrSize {
1461 word := i / goarch.PtrSize
1462 bits := *addb(ptrmask, word/8)
1464 // Skip 8 words (the loop increment will do the 8th)
1466 // This must be the first time we've
1467 // seen this word of ptrmask, so i
1468 // must be 8-word-aligned, but check
1469 // our reasoning just in case.
1470 if i%(goarch.PtrSize*8) != 0 {
1471 throw("misaligned mask")
1473 i += goarch.PtrSize*8 - goarch.PtrSize
1476 if (bits>>(word%8))&1 == 0 {
1481 val := *(*uintptr)(unsafe.Pointer(b + i))
1483 // Check if val points into the stack.
1484 if state != nil && state.stack.lo <= val && val < state.stack.hi {
1485 // val may point to a stack object. This
1486 // object may be dead from last cycle and
1487 // hence may contain pointers to unallocated
1488 // objects, but unlike heap objects we can't
1489 // tell if it's already dead. Hence, if all
1490 // pointers to this object are from
1491 // conservative scanning, we have to scan it
1492 // defensively, too.
1493 state.putPtr(val, true)
1497 // Check if val points to a heap span.
1498 span := spanOfHeap(val)
1503 // Check if val points to an allocated object.
1504 idx := span.objIndex(val)
1505 if span.isFree(idx) {
1509 // val points to an allocated object. Mark it.
1510 obj := span.base() + idx*span.elemsize
1511 greyobject(obj, b, i, span, gcw, idx)
1515 // Shade the object if it isn't already.
1516 // The object is not nil and known to be in the heap.
1517 // Preemption must be disabled.
1520 func shade(b uintptr) {
1521 if obj, span, objIndex := findObject(b, 0, 0); obj != 0 {
1522 gcw := &getg().m.p.ptr().gcw
1523 greyobject(obj, 0, 0, span, gcw, objIndex)
1527 // obj is the start of an object with mark mbits.
1528 // If it isn't already marked, mark it and enqueue into gcw.
1529 // base and off are for debugging only and could be removed.
1531 // See also wbBufFlush1, which partially duplicates this logic.
1533 //go:nowritebarrierrec
1534 func greyobject(obj, base, off uintptr, span *mspan, gcw *gcWork, objIndex uintptr) {
1535 // obj should be start of allocation, and so must be at least pointer-aligned.
1536 if obj&(goarch.PtrSize-1) != 0 {
1537 throw("greyobject: obj not pointer-aligned")
1539 mbits := span.markBitsForIndex(objIndex)
1542 if setCheckmark(obj, base, off, mbits) {
1547 if debug.gccheckmark > 0 && span.isFree(objIndex) {
1548 print("runtime: marking free object ", hex(obj), " found at *(", hex(base), "+", hex(off), ")\n")
1549 gcDumpObject("base", base, off)
1550 gcDumpObject("obj", obj, ^uintptr(0))
1551 getg().m.traceback = 2
1552 throw("marking free object")
1555 // If marked we have nothing to do.
1556 if mbits.isMarked() {
1562 arena, pageIdx, pageMask := pageIndexOf(span.base())
1563 if arena.pageMarks[pageIdx]&pageMask == 0 {
1564 atomic.Or8(&arena.pageMarks[pageIdx], pageMask)
1567 // If this is a noscan object, fast-track it to black
1568 // instead of greying it.
1569 if span.spanclass.noscan() {
1570 gcw.bytesMarked += uint64(span.elemsize)
1575 // We're adding obj to P's local workbuf, so it's likely
1576 // this object will be processed soon by the same P.
1577 // Even if the workbuf gets flushed, there will likely still be
1578 // some benefit on platforms with inclusive shared caches.
1580 // Queue the obj for scanning.
1581 if !gcw.putFast(obj) {
1586 // gcDumpObject dumps the contents of obj for debugging and marks the
1587 // field at byte offset off in obj.
1588 func gcDumpObject(label string, obj, off uintptr) {
1590 print(label, "=", hex(obj))
1595 print(" s.base()=", hex(s.base()), " s.limit=", hex(s.limit), " s.spanclass=", s.spanclass, " s.elemsize=", s.elemsize, " s.state=")
1596 if state := s.state.get(); 0 <= state && int(state) < len(mSpanStateNames) {
1597 print(mSpanStateNames[state], "\n")
1599 print("unknown(", state, ")\n")
1604 if s.state.get() == mSpanManual && size == 0 {
1605 // We're printing something from a stack frame. We
1606 // don't know how big it is, so just show up to an
1608 size = off + goarch.PtrSize
1610 for i := uintptr(0); i < size; i += goarch.PtrSize {
1611 // For big objects, just print the beginning (because
1612 // that usually hints at the object's type) and the
1613 // fields around off.
1614 if !(i < 128*goarch.PtrSize || off-16*goarch.PtrSize < i && i < off+16*goarch.PtrSize) {
1622 print(" *(", label, "+", i, ") = ", hex(*(*uintptr)(unsafe.Pointer(obj + i))))
1633 // gcmarknewobject marks a newly allocated object black. obj must
1634 // not contain any non-nil pointers.
1636 // This is nosplit so it can manipulate a gcWork without preemption.
1640 func gcmarknewobject(span *mspan, obj, size uintptr) {
1641 if useCheckmark { // The world should be stopped so this should not happen.
1642 throw("gcmarknewobject called while doing checkmark")
1646 objIndex := span.objIndex(obj)
1647 span.markBitsForIndex(objIndex).setMarked()
1650 arena, pageIdx, pageMask := pageIndexOf(span.base())
1651 if arena.pageMarks[pageIdx]&pageMask == 0 {
1652 atomic.Or8(&arena.pageMarks[pageIdx], pageMask)
1655 gcw := &getg().m.p.ptr().gcw
1656 gcw.bytesMarked += uint64(size)
1659 // gcMarkTinyAllocs greys all active tiny alloc blocks.
1661 // The world must be stopped.
1662 func gcMarkTinyAllocs() {
1663 assertWorldStopped()
1665 for _, p := range allp {
1667 if c == nil || c.tiny == 0 {
1670 _, span, objIndex := findObject(c.tiny, 0, 0)
1672 greyobject(c.tiny, 0, 0, span, gcw, objIndex)