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
10 "runtime/internal/atomic"
11 "runtime/internal/sys"
16 fixedRootFinalizers = iota
20 // rootBlockBytes is the number of bytes to scan per data or
22 rootBlockBytes = 256 << 10
24 // maxObletBytes is the maximum bytes of an object to scan at
25 // once. Larger objects will be split up into "oblets" of at
26 // most this size. Since we can scan 1–2 MB/ms, 128 KB bounds
27 // scan preemption at ~100 µs.
29 // This must be > _MaxSmallSize so that the object base is the
31 maxObletBytes = 128 << 10
33 // drainCheckThreshold specifies how many units of work to do
34 // between self-preemption checks in gcDrain. Assuming a scan
35 // rate of 1 MB/ms, this is ~100 µs. Lower values have higher
36 // overhead in the scan loop (the scheduler check may perform
37 // a syscall, so its overhead is nontrivial). Higher values
38 // make the system less responsive to incoming work.
39 drainCheckThreshold = 100000
41 // pagesPerSpanRoot indicates how many pages to scan from a span root
42 // at a time. Used by special root marking.
44 // Higher values improve throughput by increasing locality, but
45 // increase the minimum latency of a marking operation.
47 // Must be a multiple of the pageInUse bitmap element size and
48 // must also evenly divide pagesPerArena.
49 pagesPerSpanRoot = 512
52 // gcMarkRootPrepare queues root scanning jobs (stacks, globals, and
53 // some miscellany) and initializes scanning-related state.
55 // The world must be stopped.
56 func gcMarkRootPrepare() {
59 work.nFlushCacheRoots = 0
61 // Compute how many data and BSS root blocks there are.
62 nBlocks := func(bytes uintptr) int {
63 return int(divRoundUp(bytes, rootBlockBytes))
70 for _, datap := range activeModules() {
71 nDataRoots := nBlocks(datap.edata - datap.data)
72 if nDataRoots > work.nDataRoots {
73 work.nDataRoots = nDataRoots
77 for _, datap := range activeModules() {
78 nBSSRoots := nBlocks(datap.ebss - datap.bss)
79 if nBSSRoots > work.nBSSRoots {
80 work.nBSSRoots = nBSSRoots
84 // Scan span roots for finalizer specials.
86 // We depend on addfinalizer to mark objects that get
87 // finalizers after root marking.
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.
92 // Break up the work into arenas, and further into chunks.
94 // Snapshot allArenas as markArenas. This snapshot is safe because allArenas
96 mheap_.markArenas = mheap_.allArenas[:len(mheap_.allArenas):len(mheap_.allArenas)]
97 work.nSpanRoots = len(mheap_.markArenas) * (pagesPerArena / pagesPerSpanRoot)
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 scanned during mark
106 work.nStackRoots = int(atomic.Loaduintptr(&allglen))
108 work.markrootNext = 0
109 work.markrootJobs = uint32(fixedRootCount + work.nFlushCacheRoots + work.nDataRoots + work.nBSSRoots + work.nSpanRoots + work.nStackRoots)
112 // gcMarkRootCheck checks that all roots have been scanned. It is
113 // purely for debugging.
114 func gcMarkRootCheck() {
115 if work.markrootNext < work.markrootJobs {
116 print(work.markrootNext, " of ", work.markrootJobs, " markroot jobs done\n")
117 throw("left over markroot jobs")
121 // Check that stacks have been scanned.
123 for i := 0; i < work.nStackRoots; i++ {
133 println("gp", gp, "goid", gp.goid,
134 "status", readgstatus(gp),
135 "gcscandone", gp.gcscandone)
136 unlock(&allglock) // Avoid self-deadlock with traceback.
137 throw("scan missed a g")
140 // ptrmask for an allocation containing a single pointer.
141 var oneptrmask = [...]uint8{1}
143 // markroot scans the i'th root.
145 // Preemption must be disabled (because this uses a gcWork).
147 // nowritebarrier is only advisory here.
150 func markroot(gcw *gcWork, i uint32) {
151 // TODO(austin): This is a bit ridiculous. Compute and store
152 // the bases in gcMarkRootPrepare instead of the counts.
153 baseFlushCache := uint32(fixedRootCount)
154 baseData := baseFlushCache + uint32(work.nFlushCacheRoots)
155 baseBSS := baseData + uint32(work.nDataRoots)
156 baseSpans := baseBSS + uint32(work.nBSSRoots)
157 baseStacks := baseSpans + uint32(work.nSpanRoots)
158 end := baseStacks + uint32(work.nStackRoots)
160 // Note: if you add a case here, please also update heapdump.go:dumproots.
162 case baseFlushCache <= i && i < baseData:
163 flushmcache(int(i - baseFlushCache))
165 case baseData <= i && i < baseBSS:
166 for _, datap := range activeModules() {
167 markrootBlock(datap.data, datap.edata-datap.data, datap.gcdatamask.bytedata, gcw, int(i-baseData))
170 case baseBSS <= i && i < baseSpans:
171 for _, datap := range activeModules() {
172 markrootBlock(datap.bss, datap.ebss-datap.bss, datap.gcbssmask.bytedata, gcw, int(i-baseBSS))
175 case i == fixedRootFinalizers:
176 for fb := allfin; fb != nil; fb = fb.alllink {
177 cnt := uintptr(atomic.Load(&fb.cnt))
178 scanblock(uintptr(unsafe.Pointer(&fb.fin[0])), cnt*unsafe.Sizeof(fb.fin[0]), &finptrmask[0], gcw, nil)
181 case i == fixedRootFreeGStacks:
182 // Switch to the system stack so we can call
184 systemstack(markrootFreeGStacks)
186 case baseSpans <= i && i < baseStacks:
187 // mark mspan.specials
188 markrootSpans(gcw, int(i-baseSpans))
191 // the rest is scanning goroutine stacks
193 if baseStacks <= i && i < end {
194 gp = allgs[i-baseStacks]
196 throw("markroot: bad index")
199 // remember when we've first observed the G blocked
200 // needed only to output in traceback
201 status := readgstatus(gp) // We are not in a scan state
202 if (status == _Gwaiting || status == _Gsyscall) && gp.waitsince == 0 {
203 gp.waitsince = work.tstart
206 // scanstack must be done on the system stack in case
207 // we're trying to scan our own stack.
209 // If this is a self-scan, put the user G in
210 // _Gwaiting to prevent self-deadlock. It may
211 // already be in _Gwaiting if this is a mark
212 // worker or we're in mark termination.
213 userG := getg().m.curg
214 selfScan := gp == userG && readgstatus(userG) == _Grunning
216 casgstatus(userG, _Grunning, _Gwaiting)
217 userG.waitreason = waitReasonGarbageCollectionScan
220 // TODO: suspendG blocks (and spins) until gp
221 // stops, which may take a while for
222 // running goroutines. Consider doing this in
223 // two phases where the first is non-blocking:
224 // we scan the stacks we can and ask running
225 // goroutines to scan themselves; and the
227 stopped := suspendG(gp)
233 throw("g already scanned")
240 casgstatus(userG, _Gwaiting, _Grunning)
246 // markrootBlock scans the shard'th shard of the block of memory [b0,
247 // b0+n0), with the given pointer mask.
250 func markrootBlock(b0, n0 uintptr, ptrmask0 *uint8, gcw *gcWork, shard int) {
251 if rootBlockBytes%(8*sys.PtrSize) != 0 {
252 // This is necessary to pick byte offsets in ptrmask0.
253 throw("rootBlockBytes must be a multiple of 8*ptrSize")
256 // Note that if b0 is toward the end of the address space,
257 // then b0 + rootBlockBytes might wrap around.
258 // These tests are written to avoid any possible overflow.
259 off := uintptr(shard) * rootBlockBytes
264 ptrmask := (*uint8)(add(unsafe.Pointer(ptrmask0), uintptr(shard)*(rootBlockBytes/(8*sys.PtrSize))))
265 n := uintptr(rootBlockBytes)
271 scanblock(b, n, ptrmask, gcw, nil)
274 // markrootFreeGStacks frees stacks of dead Gs.
276 // This does not free stacks of dead Gs cached on Ps, but having a few
277 // cached stacks around isn't a problem.
278 func markrootFreeGStacks() {
279 // Take list of dead Gs with stacks.
280 lock(&sched.gFree.lock)
281 list := sched.gFree.stack
282 sched.gFree.stack = gList{}
283 unlock(&sched.gFree.lock)
289 q := gQueue{list.head, list.head}
290 for gp := list.head.ptr(); gp != nil; gp = gp.schedlink.ptr() {
294 // Manipulate the queue directly since the Gs are
295 // already all linked the right way.
299 // Put Gs back on the free list.
300 lock(&sched.gFree.lock)
301 sched.gFree.noStack.pushAll(q)
302 unlock(&sched.gFree.lock)
305 // markrootSpans marks roots for one shard of markArenas.
308 func markrootSpans(gcw *gcWork, shard int) {
309 // Objects with finalizers have two GC-related invariants:
311 // 1) Everything reachable from the object must be marked.
312 // This ensures that when we pass the object to its finalizer,
313 // everything the finalizer can reach will be retained.
315 // 2) Finalizer specials (which are not in the garbage
316 // collected heap) are roots. In practice, this means the fn
317 // field must be scanned.
318 sg := mheap_.sweepgen
320 // Find the arena and page index into that arena for this shard.
321 ai := mheap_.markArenas[shard/(pagesPerArena/pagesPerSpanRoot)]
322 ha := mheap_.arenas[ai.l1()][ai.l2()]
323 arenaPage := uint(uintptr(shard) * pagesPerSpanRoot % pagesPerArena)
325 // Construct slice of bitmap which we'll iterate over.
326 specialsbits := ha.pageSpecials[arenaPage/8:]
327 specialsbits = specialsbits[:pagesPerSpanRoot/8]
328 for i := range specialsbits {
329 // Find set bits, which correspond to spans with specials.
330 specials := atomic.Load8(&specialsbits[i])
334 for j := uint(0); j < 8; j++ {
335 if specials&(1<<j) == 0 {
338 // Find the span for this bit.
340 // This value is guaranteed to be non-nil because having
341 // specials implies that the span is in-use, and since we're
342 // currently marking we can be sure that we don't have to worry
343 // about the span being freed and re-used.
344 s := ha.spans[arenaPage+uint(i)*8+j]
346 // The state must be mSpanInUse if the specials bit is set, so
347 // sanity check that.
348 if state := s.state.get(); state != mSpanInUse {
349 print("s.state = ", state, "\n")
350 throw("non in-use span found with specials bit set")
352 // Check that this span was swept (it may be cached or uncached).
353 if !useCheckmark && !(s.sweepgen == sg || s.sweepgen == sg+3) {
354 // sweepgen was updated (+2) during non-checkmark GC pass
355 print("sweep ", s.sweepgen, " ", sg, "\n")
356 throw("gc: unswept span")
359 // Lock the specials to prevent a special from being
360 // removed from the list while we're traversing it.
362 for sp := s.specials; sp != nil; sp = sp.next {
363 if sp.kind != _KindSpecialFinalizer {
366 // don't mark finalized object, but scan it so we
367 // retain everything it points to.
368 spf := (*specialfinalizer)(unsafe.Pointer(sp))
369 // A finalizer can be set for an inner byte of an object, find object beginning.
370 p := s.base() + uintptr(spf.special.offset)/s.elemsize*s.elemsize
372 // Mark everything that can be reached from
373 // the object (but *not* the object itself or
374 // we'll never collect it).
377 // The special itself is a root.
378 scanblock(uintptr(unsafe.Pointer(&spf.fn)), sys.PtrSize, &oneptrmask[0], gcw, nil)
380 unlock(&s.speciallock)
385 // gcAssistAlloc performs GC work to make gp's assist debt positive.
386 // gp must be the calling user gorountine.
388 // This must be called with preemption enabled.
389 func gcAssistAlloc(gp *g) {
390 // Don't assist in non-preemptible contexts. These are
391 // generally fragile and won't allow the assist to block.
392 if getg() == gp.m.g0 {
395 if mp := getg().m; mp.locks > 0 || mp.preemptoff != "" {
401 // Compute the amount of scan work we need to do to make the
402 // balance positive. When the required amount of work is low,
403 // we over-assist to build up credit for future allocations
404 // and amortize the cost of assisting.
405 assistWorkPerByte := float64frombits(atomic.Load64(&gcController.assistWorkPerByte))
406 assistBytesPerWork := float64frombits(atomic.Load64(&gcController.assistBytesPerWork))
407 debtBytes := -gp.gcAssistBytes
408 scanWork := int64(assistWorkPerByte * float64(debtBytes))
409 if scanWork < gcOverAssistWork {
410 scanWork = gcOverAssistWork
411 debtBytes = int64(assistBytesPerWork * float64(scanWork))
414 // Steal as much credit as we can from the background GC's
415 // scan credit. This is racy and may drop the background
416 // credit below 0 if two mutators steal at the same time. This
417 // will just cause steals to fail until credit is accumulated
418 // again, so in the long run it doesn't really matter, but we
419 // do have to handle the negative credit case.
420 bgScanCredit := atomic.Loadint64(&gcController.bgScanCredit)
422 if bgScanCredit > 0 {
423 if bgScanCredit < scanWork {
424 stolen = bgScanCredit
425 gp.gcAssistBytes += 1 + int64(assistBytesPerWork*float64(stolen))
428 gp.gcAssistBytes += debtBytes
430 atomic.Xaddint64(&gcController.bgScanCredit, -stolen)
435 // We were able to steal all of the credit we
438 traceGCMarkAssistDone()
444 if trace.enabled && !traced {
446 traceGCMarkAssistStart()
449 // Perform assist work
451 gcAssistAlloc1(gp, scanWork)
452 // The user stack may have moved, so this can't touch
453 // anything on it until it returns from systemstack.
456 completed := gp.param != nil
462 if gp.gcAssistBytes < 0 {
463 // We were unable steal enough credit or perform
464 // enough work to pay off the assist debt. We need to
465 // do one of these before letting the mutator allocate
466 // more to prevent over-allocation.
468 // If this is because we were preempted, reschedule
469 // and try some more.
475 // Add this G to an assist queue and park. When the GC
476 // has more background credit, it will satisfy queued
477 // assists before flushing to the global credit pool.
479 // Note that this does *not* get woken up when more
480 // work is added to the work list. The theory is that
481 // there wasn't enough work to do anyway, so we might
482 // as well let background marking take care of the
483 // work that is available.
488 // At this point either background GC has satisfied
489 // this G's assist debt, or the GC cycle is over.
492 traceGCMarkAssistDone()
496 // gcAssistAlloc1 is the part of gcAssistAlloc that runs on the system
497 // stack. This is a separate function to make it easier to see that
498 // we're not capturing anything from the user stack, since the user
499 // stack may move while we're in this function.
501 // gcAssistAlloc1 indicates whether this assist completed the mark
502 // phase by setting gp.param to non-nil. This can't be communicated on
503 // the stack since it may move.
506 func gcAssistAlloc1(gp *g, scanWork int64) {
507 // Clear the flag indicating that this assist completed the
511 if atomic.Load(&gcBlackenEnabled) == 0 {
512 // The gcBlackenEnabled check in malloc races with the
513 // store that clears it but an atomic check in every malloc
514 // would be a performance hit.
515 // Instead we recheck it here on the non-preemptable system
516 // stack to determine if we should perform an assist.
518 // GC is done, so ignore any remaining debt.
522 // Track time spent in this assist. Since we're on the
523 // system stack, this is non-preemptible, so we can
524 // just measure start and end time.
525 startTime := nanotime()
527 decnwait := atomic.Xadd(&work.nwait, -1)
528 if decnwait == work.nproc {
529 println("runtime: work.nwait =", decnwait, "work.nproc=", work.nproc)
530 throw("nwait > work.nprocs")
533 // gcDrainN requires the caller to be preemptible.
534 casgstatus(gp, _Grunning, _Gwaiting)
535 gp.waitreason = waitReasonGCAssistMarking
537 // drain own cached work first in the hopes that it
538 // will be more cache friendly.
539 gcw := &getg().m.p.ptr().gcw
540 workDone := gcDrainN(gcw, scanWork)
542 casgstatus(gp, _Gwaiting, _Grunning)
544 // Record that we did this much scan work.
546 // Back out the number of bytes of assist credit that
547 // this scan work counts for. The "1+" is a poor man's
548 // round-up, to ensure this adds credit even if
549 // assistBytesPerWork is very low.
550 assistBytesPerWork := float64frombits(atomic.Load64(&gcController.assistBytesPerWork))
551 gp.gcAssistBytes += 1 + int64(assistBytesPerWork*float64(workDone))
553 // If this is the last worker and we ran out of work,
554 // signal a completion point.
555 incnwait := atomic.Xadd(&work.nwait, +1)
556 if incnwait > work.nproc {
557 println("runtime: work.nwait=", incnwait,
558 "work.nproc=", work.nproc)
559 throw("work.nwait > work.nproc")
562 if incnwait == work.nproc && !gcMarkWorkAvailable(nil) {
563 // This has reached a background completion point. Set
564 // gp.param to a non-nil value to indicate this. It
565 // doesn't matter what we set it to (it just has to be
567 gp.param = unsafe.Pointer(gp)
569 duration := nanotime() - startTime
571 _p_.gcAssistTime += duration
572 if _p_.gcAssistTime > gcAssistTimeSlack {
573 atomic.Xaddint64(&gcController.assistTime, _p_.gcAssistTime)
578 // gcWakeAllAssists wakes all currently blocked assists. This is used
579 // at the end of a GC cycle. gcBlackenEnabled must be false to prevent
580 // new assists from going to sleep after this point.
581 func gcWakeAllAssists() {
582 lock(&work.assistQueue.lock)
583 list := work.assistQueue.q.popList()
585 unlock(&work.assistQueue.lock)
588 // gcParkAssist puts the current goroutine on the assist queue and parks.
590 // gcParkAssist reports whether the assist is now satisfied. If it
591 // returns false, the caller must retry the assist.
594 func gcParkAssist() bool {
595 lock(&work.assistQueue.lock)
596 // If the GC cycle finished while we were getting the lock,
597 // exit the assist. The cycle can't finish while we hold the
599 if atomic.Load(&gcBlackenEnabled) == 0 {
600 unlock(&work.assistQueue.lock)
605 oldList := work.assistQueue.q
606 work.assistQueue.q.pushBack(gp)
608 // Recheck for background credit now that this G is in
609 // the queue, but can still back out. This avoids a
610 // race in case background marking has flushed more
611 // credit since we checked above.
612 if atomic.Loadint64(&gcController.bgScanCredit) > 0 {
613 work.assistQueue.q = oldList
614 if oldList.tail != 0 {
615 oldList.tail.ptr().schedlink.set(nil)
617 unlock(&work.assistQueue.lock)
621 goparkunlock(&work.assistQueue.lock, waitReasonGCAssistWait, traceEvGoBlockGC, 2)
625 // gcFlushBgCredit flushes scanWork units of background scan work
626 // credit. This first satisfies blocked assists on the
627 // work.assistQueue and then flushes any remaining credit to
628 // gcController.bgScanCredit.
630 // Write barriers are disallowed because this is used by gcDrain after
631 // it has ensured that all work is drained and this must preserve that
634 //go:nowritebarrierrec
635 func gcFlushBgCredit(scanWork int64) {
636 if work.assistQueue.q.empty() {
637 // Fast path; there are no blocked assists. There's a
638 // small window here where an assist may add itself to
639 // the blocked queue and park. If that happens, we'll
640 // just get it on the next flush.
641 atomic.Xaddint64(&gcController.bgScanCredit, scanWork)
645 assistBytesPerWork := float64frombits(atomic.Load64(&gcController.assistBytesPerWork))
646 scanBytes := int64(float64(scanWork) * assistBytesPerWork)
648 lock(&work.assistQueue.lock)
649 for !work.assistQueue.q.empty() && scanBytes > 0 {
650 gp := work.assistQueue.q.pop()
651 // Note that gp.gcAssistBytes is negative because gp
652 // is in debt. Think carefully about the signs below.
653 if scanBytes+gp.gcAssistBytes >= 0 {
654 // Satisfy this entire assist debt.
655 scanBytes += gp.gcAssistBytes
657 // It's important that we *not* put gp in
658 // runnext. Otherwise, it's possible for user
659 // code to exploit the GC worker's high
660 // scheduler priority to get itself always run
661 // before other goroutines and always in the
662 // fresh quantum started by GC.
665 // Partially satisfy this assist.
666 gp.gcAssistBytes += scanBytes
668 // As a heuristic, we move this assist to the
669 // back of the queue so that large assists
670 // can't clog up the assist queue and
671 // substantially delay small assists.
672 work.assistQueue.q.pushBack(gp)
678 // Convert from scan bytes back to work.
679 assistWorkPerByte := float64frombits(atomic.Load64(&gcController.assistWorkPerByte))
680 scanWork = int64(float64(scanBytes) * assistWorkPerByte)
681 atomic.Xaddint64(&gcController.bgScanCredit, scanWork)
683 unlock(&work.assistQueue.lock)
686 // scanstack scans gp's stack, greying all pointers found on the stack.
688 // scanstack will also shrink the stack if it is safe to do so. If it
689 // is not, it schedules a stack shrink for the next synchronous safe
692 // scanstack is marked go:systemstack because it must not be preempted
693 // while using a workbuf.
697 func scanstack(gp *g, gcw *gcWork) {
698 if readgstatus(gp)&_Gscan == 0 {
699 print("runtime:scanstack: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", hex(readgstatus(gp)), "\n")
700 throw("scanstack - bad status")
703 switch readgstatus(gp) &^ _Gscan {
705 print("runtime: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n")
706 throw("mark - bad status")
710 print("runtime: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n")
711 throw("scanstack: goroutine not stopped")
712 case _Grunnable, _Gsyscall, _Gwaiting:
717 throw("can't scan our own stack")
720 if isShrinkStackSafe(gp) {
721 // Shrink the stack if not much of it is being used.
724 // Otherwise, shrink the stack at the next sync safe point.
725 gp.preemptShrink = true
728 var state stackScanState
729 state.stack = gp.stack
732 println("stack trace goroutine", gp.goid)
735 if debugScanConservative && gp.asyncSafePoint {
736 print("scanning async preempted goroutine ", gp.goid, " stack [", hex(gp.stack.lo), ",", hex(gp.stack.hi), ")\n")
739 // Scan the saved context register. This is effectively a live
740 // register that gets moved back and forth between the
741 // register and sched.ctxt without a write barrier.
742 if gp.sched.ctxt != nil {
743 scanblock(uintptr(unsafe.Pointer(&gp.sched.ctxt)), sys.PtrSize, &oneptrmask[0], gcw, &state)
746 // Scan the stack. Accumulate a list of stack objects.
747 scanframe := func(frame *stkframe, unused unsafe.Pointer) bool {
748 scanframeworker(frame, &state, gcw)
751 gentraceback(^uintptr(0), ^uintptr(0), 0, gp, 0, nil, 0x7fffffff, scanframe, nil, 0)
753 // Find additional pointers that point into the stack from the heap.
754 // Currently this includes defers and panics. See also function copystack.
756 // Find and trace all defer arguments.
757 tracebackdefers(gp, scanframe, nil)
759 // Find and trace other pointers in defer records.
760 for d := gp._defer; d != nil; d = d.link {
762 // tracebackdefers above does not scan the func value, which could
763 // be a stack allocated closure. See issue 30453.
764 scanblock(uintptr(unsafe.Pointer(&d.fn)), sys.PtrSize, &oneptrmask[0], gcw, &state)
767 // The link field of a stack-allocated defer record might point
768 // to a heap-allocated defer record. Keep that heap record live.
769 scanblock(uintptr(unsafe.Pointer(&d.link)), sys.PtrSize, &oneptrmask[0], gcw, &state)
771 // Retain defers records themselves.
772 // Defer records might not be reachable from the G through regular heap
773 // tracing because the defer linked list might weave between the stack and the heap.
775 scanblock(uintptr(unsafe.Pointer(&d)), sys.PtrSize, &oneptrmask[0], gcw, &state)
778 if gp._panic != nil {
779 // Panics are always stack allocated.
780 state.putPtr(uintptr(unsafe.Pointer(gp._panic)), false)
783 // Find and scan all reachable stack objects.
785 // The state's pointer queue prioritizes precise pointers over
786 // conservative pointers so that we'll prefer scanning stack
787 // objects precisely.
790 p, conservative := state.getPtr()
794 obj := state.findObject(p)
800 // We've already scanned this object.
803 obj.setType(nil) // Don't scan it again.
806 print(" live stkobj at", hex(state.stack.lo+uintptr(obj.off)), "of type", t.string())
808 print(" (conservative)")
815 if t.kind&kindGCProg != 0 {
816 // This path is pretty unlikely, an object large enough
817 // to have a GC program allocated on the stack.
818 // We need some space to unpack the program into a straight
819 // bitmask, which we allocate/free here.
820 // TODO: it would be nice if there were a way to run a GC
821 // program without having to store all its bits. We'd have
822 // to change from a Lempel-Ziv style program to something else.
823 // Or we can forbid putting objects on stacks if they require
824 // a gc program (see issue 27447).
825 s = materializeGCProg(t.ptrdata, gcdata)
826 gcdata = (*byte)(unsafe.Pointer(s.startAddr))
829 b := state.stack.lo + uintptr(obj.off)
831 scanConservative(b, t.ptrdata, gcdata, gcw, &state)
833 scanblock(b, t.ptrdata, gcdata, gcw, &state)
837 dematerializeGCProg(s)
841 // Deallocate object buffers.
842 // (Pointer buffers were all deallocated in the loop above.)
843 for state.head != nil {
847 for i := 0; i < x.nobj; i++ {
849 if obj.typ == nil { // reachable
852 println(" dead stkobj at", hex(gp.stack.lo+uintptr(obj.off)), "of type", obj.typ.string())
853 // Note: not necessarily really dead - only reachable-from-ptr dead.
857 putempty((*workbuf)(unsafe.Pointer(x)))
859 if state.buf != nil || state.cbuf != nil || state.freeBuf != nil {
860 throw("remaining pointer buffers")
864 // Scan a stack frame: local variables and function arguments/results.
866 func scanframeworker(frame *stkframe, state *stackScanState, gcw *gcWork) {
867 if _DebugGC > 1 && frame.continpc != 0 {
868 print("scanframe ", funcname(frame.fn), "\n")
871 isAsyncPreempt := frame.fn.valid() && frame.fn.funcID == funcID_asyncPreempt
872 isDebugCall := frame.fn.valid() && frame.fn.funcID == funcID_debugCallV1
873 if state.conservative || isAsyncPreempt || isDebugCall {
874 if debugScanConservative {
875 println("conservatively scanning function", funcname(frame.fn), "at PC", hex(frame.continpc))
878 // Conservatively scan the frame. Unlike the precise
879 // case, this includes the outgoing argument space
880 // since we may have stopped while this function was
881 // setting up a call.
883 // TODO: We could narrow this down if the compiler
884 // produced a single map per function of stack slots
885 // and registers that ever contain a pointer.
887 size := frame.varp - frame.sp
889 scanConservative(frame.sp, size, nil, gcw, state)
893 // Scan arguments to this frame.
894 if frame.arglen != 0 {
895 // TODO: We could pass the entry argument map
896 // to narrow this down further.
897 scanConservative(frame.argp, frame.arglen, nil, gcw, state)
900 if isAsyncPreempt || isDebugCall {
901 // This function's frame contained the
902 // registers for the asynchronously stopped
903 // parent frame. Scan the parent
905 state.conservative = true
907 // We only wanted to scan those two frames
908 // conservatively. Clear the flag for future
910 state.conservative = false
915 locals, args, objs := getStackMap(frame, &state.cache, false)
917 // Scan local variables if stack frame has been allocated.
919 size := uintptr(locals.n) * sys.PtrSize
920 scanblock(frame.varp-size, size, locals.bytedata, gcw, state)
925 scanblock(frame.argp, uintptr(args.n)*sys.PtrSize, args.bytedata, gcw, state)
928 // Add all stack objects to the stack object list.
930 // varp is 0 for defers, where there are no locals.
931 // In that case, there can't be a pointer to its args, either.
932 // (And all args would be scanned above anyway.)
933 for _, obj := range objs {
935 base := frame.varp // locals base pointer
937 base = frame.argp // arguments and return values base pointer
939 ptr := base + uintptr(off)
941 // object hasn't been allocated in the frame yet.
945 println("stkobj at", hex(ptr), "of type", obj.typ.string())
947 state.addObject(ptr, obj.typ)
952 type gcDrainFlags int
955 gcDrainUntilPreempt gcDrainFlags = 1 << iota
961 // gcDrain scans roots and objects in work buffers, blackening grey
962 // objects until it is unable to get more work. It may return before
963 // GC is done; it's the caller's responsibility to balance work from
966 // If flags&gcDrainUntilPreempt != 0, gcDrain returns when g.preempt
969 // If flags&gcDrainIdle != 0, gcDrain returns when there is other work
972 // If flags&gcDrainFractional != 0, gcDrain self-preempts when
973 // pollFractionalWorkerExit() returns true. This implies
976 // If flags&gcDrainFlushBgCredit != 0, gcDrain flushes scan work
977 // credit to gcController.bgScanCredit every gcCreditSlack units of
980 // gcDrain will always return if there is a pending STW.
983 func gcDrain(gcw *gcWork, flags gcDrainFlags) {
984 if !writeBarrier.needed {
985 throw("gcDrain phase incorrect")
989 preemptible := flags&gcDrainUntilPreempt != 0
990 flushBgCredit := flags&gcDrainFlushBgCredit != 0
991 idle := flags&gcDrainIdle != 0
993 initScanWork := gcw.scanWork
995 // checkWork is the scan work before performing the next
996 // self-preempt check.
997 checkWork := int64(1<<63 - 1)
998 var check func() bool
999 if flags&(gcDrainIdle|gcDrainFractional) != 0 {
1000 checkWork = initScanWork + drainCheckThreshold
1003 } else if flags&gcDrainFractional != 0 {
1004 check = pollFractionalWorkerExit
1008 // Drain root marking jobs.
1009 if work.markrootNext < work.markrootJobs {
1010 // Stop if we're preemptible or if someone wants to STW.
1011 for !(gp.preempt && (preemptible || atomic.Load(&sched.gcwaiting) != 0)) {
1012 job := atomic.Xadd(&work.markrootNext, +1) - 1
1013 if job >= work.markrootJobs {
1017 if check != nil && check() {
1023 // Drain heap marking jobs.
1024 // Stop if we're preemptible or if someone wants to STW.
1025 for !(gp.preempt && (preemptible || atomic.Load(&sched.gcwaiting) != 0)) {
1026 // Try to keep work available on the global queue. We used to
1027 // check if there were waiting workers, but it's better to
1028 // just keep work available than to make workers wait. In the
1029 // worst case, we'll do O(log(_WorkbufSize)) unnecessary
1035 b := gcw.tryGetFast()
1039 // Flush the write barrier
1040 // buffer; this may create
1047 // Unable to get work.
1052 // Flush background scan work credit to the global
1053 // account if we've accumulated enough locally so
1054 // mutator assists can draw on it.
1055 if gcw.scanWork >= gcCreditSlack {
1056 atomic.Xaddint64(&gcController.scanWork, gcw.scanWork)
1058 gcFlushBgCredit(gcw.scanWork - initScanWork)
1061 checkWork -= gcw.scanWork
1065 checkWork += drainCheckThreshold
1066 if check != nil && check() {
1074 // Flush remaining scan work credit.
1075 if gcw.scanWork > 0 {
1076 atomic.Xaddint64(&gcController.scanWork, gcw.scanWork)
1078 gcFlushBgCredit(gcw.scanWork - initScanWork)
1084 // gcDrainN blackens grey objects until it has performed roughly
1085 // scanWork units of scan work or the G is preempted. This is
1086 // best-effort, so it may perform less work if it fails to get a work
1087 // buffer. Otherwise, it will perform at least n units of work, but
1088 // may perform more because scanning is always done in whole object
1089 // increments. It returns the amount of scan work performed.
1091 // The caller goroutine must be in a preemptible state (e.g.,
1092 // _Gwaiting) to prevent deadlocks during stack scanning. As a
1093 // consequence, this must be called on the system stack.
1097 func gcDrainN(gcw *gcWork, scanWork int64) int64 {
1098 if !writeBarrier.needed {
1099 throw("gcDrainN phase incorrect")
1102 // There may already be scan work on the gcw, which we don't
1103 // want to claim was done by this call.
1104 workFlushed := -gcw.scanWork
1107 for !gp.preempt && workFlushed+gcw.scanWork < scanWork {
1108 // See gcDrain comment.
1113 // This might be a good place to add prefetch code...
1114 // if(wbuf.nobj > 4) {
1115 // PREFETCH(wbuf->obj[wbuf.nobj - 3];
1118 b := gcw.tryGetFast()
1122 // Flush the write barrier buffer;
1123 // this may create more work.
1130 // Try to do a root job.
1132 // TODO: Assists should get credit for this
1134 if work.markrootNext < work.markrootJobs {
1135 job := atomic.Xadd(&work.markrootNext, +1) - 1
1136 if job < work.markrootJobs {
1141 // No heap or root jobs.
1146 // Flush background scan work credit.
1147 if gcw.scanWork >= gcCreditSlack {
1148 atomic.Xaddint64(&gcController.scanWork, gcw.scanWork)
1149 workFlushed += gcw.scanWork
1154 // Unlike gcDrain, there's no need to flush remaining work
1155 // here because this never flushes to bgScanCredit and
1156 // gcw.dispose will flush any remaining work to scanWork.
1158 return workFlushed + gcw.scanWork
1161 // scanblock scans b as scanobject would, but using an explicit
1162 // pointer bitmap instead of the heap bitmap.
1164 // This is used to scan non-heap roots, so it does not update
1165 // gcw.bytesMarked or gcw.scanWork.
1167 // If stk != nil, possible stack pointers are also reported to stk.putPtr.
1169 func scanblock(b0, n0 uintptr, ptrmask *uint8, gcw *gcWork, stk *stackScanState) {
1170 // Use local copies of original parameters, so that a stack trace
1171 // due to one of the throws below shows the original block
1176 for i := uintptr(0); i < n; {
1177 // Find bits for the next word.
1178 bits := uint32(*addb(ptrmask, i/(sys.PtrSize*8)))
1180 i += sys.PtrSize * 8
1183 for j := 0; j < 8 && i < n; j++ {
1185 // Same work as in scanobject; see comments there.
1186 p := *(*uintptr)(unsafe.Pointer(b + i))
1188 if obj, span, objIndex := findObject(p, b, i); obj != 0 {
1189 greyobject(obj, b, i, span, gcw, objIndex)
1190 } else if stk != nil && p >= stk.stack.lo && p < stk.stack.hi {
1191 stk.putPtr(p, false)
1201 // scanobject scans the object starting at b, adding pointers to gcw.
1202 // b must point to the beginning of a heap object or an oblet.
1203 // scanobject consults the GC bitmap for the pointer mask and the
1204 // spans for the size of the object.
1207 func scanobject(b uintptr, gcw *gcWork) {
1208 // Find the bits for b and the size of the object at b.
1210 // b is either the beginning of an object, in which case this
1211 // is the size of the object to scan, or it points to an
1212 // oblet, in which case we compute the size to scan below.
1213 hbits := heapBitsForAddr(b)
1214 s := spanOfUnchecked(b)
1217 throw("scanobject n == 0")
1220 if n > maxObletBytes {
1221 // Large object. Break into oblets for better
1222 // parallelism and lower latency.
1224 // It's possible this is a noscan object (not
1225 // from greyobject, but from other code
1226 // paths), in which case we must *not* enqueue
1227 // oblets since their bitmaps will be
1229 if s.spanclass.noscan() {
1230 // Bypass the whole scan.
1231 gcw.bytesMarked += uint64(n)
1235 // Enqueue the other oblets to scan later.
1236 // Some oblets may be in b's scalar tail, but
1237 // these will be marked as "no more pointers",
1238 // so we'll drop out immediately when we go to
1240 for oblet := b + maxObletBytes; oblet < s.base()+s.elemsize; oblet += maxObletBytes {
1241 if !gcw.putFast(oblet) {
1247 // Compute the size of the oblet. Since this object
1248 // must be a large object, s.base() is the beginning
1250 n = s.base() + s.elemsize - b
1251 if n > maxObletBytes {
1257 for i = 0; i < n; i += sys.PtrSize {
1258 // Find bits for this word.
1260 // Avoid needless hbits.next() on last iteration.
1261 hbits = hbits.next()
1263 // Load bits once. See CL 22712 and issue 16973 for discussion.
1264 bits := hbits.bits()
1265 if bits&bitScan == 0 {
1266 break // no more pointers in this object
1268 if bits&bitPointer == 0 {
1269 continue // not a pointer
1272 // Work here is duplicated in scanblock and above.
1273 // If you make changes here, make changes there too.
1274 obj := *(*uintptr)(unsafe.Pointer(b + i))
1276 // At this point we have extracted the next potential pointer.
1277 // Quickly filter out nil and pointers back to the current object.
1278 if obj != 0 && obj-b >= n {
1279 // Test if obj points into the Go heap and, if so,
1282 // Note that it's possible for findObject to
1283 // fail if obj points to a just-allocated heap
1284 // object because of a race with growing the
1285 // heap. In this case, we know the object was
1286 // just allocated and hence will be marked by
1287 // allocation itself.
1288 if obj, span, objIndex := findObject(obj, b, i); obj != 0 {
1289 greyobject(obj, b, i, span, gcw, objIndex)
1293 gcw.bytesMarked += uint64(n)
1294 gcw.scanWork += int64(i)
1297 // scanConservative scans block [b, b+n) conservatively, treating any
1298 // pointer-like value in the block as a pointer.
1300 // If ptrmask != nil, only words that are marked in ptrmask are
1301 // considered as potential pointers.
1303 // If state != nil, it's assumed that [b, b+n) is a block in the stack
1304 // and may contain pointers to stack objects.
1305 func scanConservative(b, n uintptr, ptrmask *uint8, gcw *gcWork, state *stackScanState) {
1306 if debugScanConservative {
1308 print("conservatively scanning [", hex(b), ",", hex(b+n), ")\n")
1309 hexdumpWords(b, b+n, func(p uintptr) byte {
1311 word := (p - b) / sys.PtrSize
1312 bits := *addb(ptrmask, word/8)
1313 if (bits>>(word%8))&1 == 0 {
1318 val := *(*uintptr)(unsafe.Pointer(p))
1319 if state != nil && state.stack.lo <= val && val < state.stack.hi {
1323 span := spanOfHeap(val)
1327 idx := span.objIndex(val)
1328 if span.isFree(idx) {
1336 for i := uintptr(0); i < n; i += sys.PtrSize {
1338 word := i / sys.PtrSize
1339 bits := *addb(ptrmask, word/8)
1341 // Skip 8 words (the loop increment will do the 8th)
1343 // This must be the first time we've
1344 // seen this word of ptrmask, so i
1345 // must be 8-word-aligned, but check
1346 // our reasoning just in case.
1347 if i%(sys.PtrSize*8) != 0 {
1348 throw("misaligned mask")
1350 i += sys.PtrSize*8 - sys.PtrSize
1353 if (bits>>(word%8))&1 == 0 {
1358 val := *(*uintptr)(unsafe.Pointer(b + i))
1360 // Check if val points into the stack.
1361 if state != nil && state.stack.lo <= val && val < state.stack.hi {
1362 // val may point to a stack object. This
1363 // object may be dead from last cycle and
1364 // hence may contain pointers to unallocated
1365 // objects, but unlike heap objects we can't
1366 // tell if it's already dead. Hence, if all
1367 // pointers to this object are from
1368 // conservative scanning, we have to scan it
1369 // defensively, too.
1370 state.putPtr(val, true)
1374 // Check if val points to a heap span.
1375 span := spanOfHeap(val)
1380 // Check if val points to an allocated object.
1381 idx := span.objIndex(val)
1382 if span.isFree(idx) {
1386 // val points to an allocated object. Mark it.
1387 obj := span.base() + idx*span.elemsize
1388 greyobject(obj, b, i, span, gcw, idx)
1392 // Shade the object if it isn't already.
1393 // The object is not nil and known to be in the heap.
1394 // Preemption must be disabled.
1396 func shade(b uintptr) {
1397 if obj, span, objIndex := findObject(b, 0, 0); obj != 0 {
1398 gcw := &getg().m.p.ptr().gcw
1399 greyobject(obj, 0, 0, span, gcw, objIndex)
1403 // obj is the start of an object with mark mbits.
1404 // If it isn't already marked, mark it and enqueue into gcw.
1405 // base and off are for debugging only and could be removed.
1407 // See also wbBufFlush1, which partially duplicates this logic.
1409 //go:nowritebarrierrec
1410 func greyobject(obj, base, off uintptr, span *mspan, gcw *gcWork, objIndex uintptr) {
1411 // obj should be start of allocation, and so must be at least pointer-aligned.
1412 if obj&(sys.PtrSize-1) != 0 {
1413 throw("greyobject: obj not pointer-aligned")
1415 mbits := span.markBitsForIndex(objIndex)
1418 if setCheckmark(obj, base, off, mbits) {
1423 if debug.gccheckmark > 0 && span.isFree(objIndex) {
1424 print("runtime: marking free object ", hex(obj), " found at *(", hex(base), "+", hex(off), ")\n")
1425 gcDumpObject("base", base, off)
1426 gcDumpObject("obj", obj, ^uintptr(0))
1427 getg().m.traceback = 2
1428 throw("marking free object")
1431 // If marked we have nothing to do.
1432 if mbits.isMarked() {
1438 arena, pageIdx, pageMask := pageIndexOf(span.base())
1439 if arena.pageMarks[pageIdx]&pageMask == 0 {
1440 atomic.Or8(&arena.pageMarks[pageIdx], pageMask)
1443 // If this is a noscan object, fast-track it to black
1444 // instead of greying it.
1445 if span.spanclass.noscan() {
1446 gcw.bytesMarked += uint64(span.elemsize)
1451 // Queue the obj for scanning. The PREFETCH(obj) logic has been removed but
1452 // seems like a nice optimization that can be added back in.
1453 // There needs to be time between the PREFETCH and the use.
1454 // Previously we put the obj in an 8 element buffer that is drained at a rate
1455 // to give the PREFETCH time to do its work.
1456 // Use of PREFETCHNTA might be more appropriate than PREFETCH
1457 if !gcw.putFast(obj) {
1462 // gcDumpObject dumps the contents of obj for debugging and marks the
1463 // field at byte offset off in obj.
1464 func gcDumpObject(label string, obj, off uintptr) {
1466 print(label, "=", hex(obj))
1471 print(" s.base()=", hex(s.base()), " s.limit=", hex(s.limit), " s.spanclass=", s.spanclass, " s.elemsize=", s.elemsize, " s.state=")
1472 if state := s.state.get(); 0 <= state && int(state) < len(mSpanStateNames) {
1473 print(mSpanStateNames[state], "\n")
1475 print("unknown(", state, ")\n")
1480 if s.state.get() == mSpanManual && size == 0 {
1481 // We're printing something from a stack frame. We
1482 // don't know how big it is, so just show up to an
1484 size = off + sys.PtrSize
1486 for i := uintptr(0); i < size; i += sys.PtrSize {
1487 // For big objects, just print the beginning (because
1488 // that usually hints at the object's type) and the
1489 // fields around off.
1490 if !(i < 128*sys.PtrSize || off-16*sys.PtrSize < i && i < off+16*sys.PtrSize) {
1498 print(" *(", label, "+", i, ") = ", hex(*(*uintptr)(unsafe.Pointer(obj + i))))
1509 // gcmarknewobject marks a newly allocated object black. obj must
1510 // not contain any non-nil pointers.
1512 // This is nosplit so it can manipulate a gcWork without preemption.
1516 func gcmarknewobject(span *mspan, obj, size, scanSize uintptr) {
1517 if useCheckmark { // The world should be stopped so this should not happen.
1518 throw("gcmarknewobject called while doing checkmark")
1522 objIndex := span.objIndex(obj)
1523 span.markBitsForIndex(objIndex).setMarked()
1526 arena, pageIdx, pageMask := pageIndexOf(span.base())
1527 if arena.pageMarks[pageIdx]&pageMask == 0 {
1528 atomic.Or8(&arena.pageMarks[pageIdx], pageMask)
1531 gcw := &getg().m.p.ptr().gcw
1532 gcw.bytesMarked += uint64(size)
1533 gcw.scanWork += int64(scanSize)
1536 // gcMarkTinyAllocs greys all active tiny alloc blocks.
1538 // The world must be stopped.
1539 func gcMarkTinyAllocs() {
1540 assertWorldStopped()
1542 for _, p := range allp {
1544 if c == nil || c.tiny == 0 {
1547 _, span, objIndex := findObject(c.tiny, 0, 0)
1549 greyobject(c.tiny, 0, 0, span, gcw, objIndex)