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