]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/mgcmark.go
runtime: make CPU limiter assist time much less error-prone
[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                                 scanobject(p, gcw)
391
392                                 // The special itself is a root.
393                                 scanblock(uintptr(unsafe.Pointer(&spf.fn)), goarch.PtrSize, &oneptrmask[0], gcw, nil)
394                         }
395                         unlock(&s.speciallock)
396                 }
397         }
398 }
399
400 // gcAssistAlloc performs GC work to make gp's assist debt positive.
401 // gp must be the calling user goroutine.
402 //
403 // This must be called with preemption enabled.
404 func gcAssistAlloc(gp *g) {
405         // Don't assist in non-preemptible contexts. These are
406         // generally fragile and won't allow the assist to block.
407         if getg() == gp.m.g0 {
408                 return
409         }
410         if mp := getg().m; mp.locks > 0 || mp.preemptoff != "" {
411                 return
412         }
413
414         traced := false
415 retry:
416         if go119MemoryLimitSupport && gcCPULimiter.limiting() {
417                 // If the CPU limiter is enabled, intentionally don't
418                 // assist to reduce the amount of CPU time spent in the GC.
419                 if traced {
420                         traceGCMarkAssistDone()
421                 }
422                 return
423         }
424         // Compute the amount of scan work we need to do to make the
425         // balance positive. When the required amount of work is low,
426         // we over-assist to build up credit for future allocations
427         // and amortize the cost of assisting.
428         assistWorkPerByte := gcController.assistWorkPerByte.Load()
429         assistBytesPerWork := gcController.assistBytesPerWork.Load()
430         debtBytes := -gp.gcAssistBytes
431         scanWork := int64(assistWorkPerByte * float64(debtBytes))
432         if scanWork < gcOverAssistWork {
433                 scanWork = gcOverAssistWork
434                 debtBytes = int64(assistBytesPerWork * float64(scanWork))
435         }
436
437         // Steal as much credit as we can from the background GC's
438         // scan credit. This is racy and may drop the background
439         // credit below 0 if two mutators steal at the same time. This
440         // will just cause steals to fail until credit is accumulated
441         // again, so in the long run it doesn't really matter, but we
442         // do have to handle the negative credit case.
443         bgScanCredit := atomic.Loadint64(&gcController.bgScanCredit)
444         stolen := int64(0)
445         if bgScanCredit > 0 {
446                 if bgScanCredit < scanWork {
447                         stolen = bgScanCredit
448                         gp.gcAssistBytes += 1 + int64(assistBytesPerWork*float64(stolen))
449                 } else {
450                         stolen = scanWork
451                         gp.gcAssistBytes += debtBytes
452                 }
453                 atomic.Xaddint64(&gcController.bgScanCredit, -stolen)
454
455                 scanWork -= stolen
456
457                 if scanWork == 0 {
458                         // We were able to steal all of the credit we
459                         // needed.
460                         if traced {
461                                 traceGCMarkAssistDone()
462                         }
463                         return
464                 }
465         }
466
467         if trace.enabled && !traced {
468                 traced = true
469                 traceGCMarkAssistStart()
470         }
471
472         // Perform assist work
473         systemstack(func() {
474                 gcAssistAlloc1(gp, scanWork)
475                 // The user stack may have moved, so this can't touch
476                 // anything on it until it returns from systemstack.
477         })
478
479         completed := gp.param != nil
480         gp.param = nil
481         if completed {
482                 gcMarkDone()
483         }
484
485         if gp.gcAssistBytes < 0 {
486                 // We were unable steal enough credit or perform
487                 // enough work to pay off the assist debt. We need to
488                 // do one of these before letting the mutator allocate
489                 // more to prevent over-allocation.
490                 //
491                 // If this is because we were preempted, reschedule
492                 // and try some more.
493                 if gp.preempt {
494                         Gosched()
495                         goto retry
496                 }
497
498                 // Add this G to an assist queue and park. When the GC
499                 // has more background credit, it will satisfy queued
500                 // assists before flushing to the global credit pool.
501                 //
502                 // Note that this does *not* get woken up when more
503                 // work is added to the work list. The theory is that
504                 // there wasn't enough work to do anyway, so we might
505                 // as well let background marking take care of the
506                 // work that is available.
507                 if !gcParkAssist() {
508                         goto retry
509                 }
510
511                 // At this point either background GC has satisfied
512                 // this G's assist debt, or the GC cycle is over.
513         }
514         if traced {
515                 traceGCMarkAssistDone()
516         }
517 }
518
519 // gcAssistAlloc1 is the part of gcAssistAlloc that runs on the system
520 // stack. This is a separate function to make it easier to see that
521 // we're not capturing anything from the user stack, since the user
522 // stack may move while we're in this function.
523 //
524 // gcAssistAlloc1 indicates whether this assist completed the mark
525 // phase by setting gp.param to non-nil. This can't be communicated on
526 // the stack since it may move.
527 //
528 //go:systemstack
529 func gcAssistAlloc1(gp *g, scanWork int64) {
530         // Clear the flag indicating that this assist completed the
531         // mark phase.
532         gp.param = nil
533
534         if atomic.Load(&gcBlackenEnabled) == 0 {
535                 // The gcBlackenEnabled check in malloc races with the
536                 // store that clears it but an atomic check in every malloc
537                 // would be a performance hit.
538                 // Instead we recheck it here on the non-preemptable system
539                 // stack to determine if we should perform an assist.
540
541                 // GC is done, so ignore any remaining debt.
542                 gp.gcAssistBytes = 0
543                 return
544         }
545         // Track time spent in this assist. Since we're on the
546         // system stack, this is non-preemptible, so we can
547         // just measure start and end time.
548         startTime := nanotime()
549
550         decnwait := atomic.Xadd(&work.nwait, -1)
551         if decnwait == work.nproc {
552                 println("runtime: work.nwait =", decnwait, "work.nproc=", work.nproc)
553                 throw("nwait > work.nprocs")
554         }
555
556         // gcDrainN requires the caller to be preemptible.
557         casgstatus(gp, _Grunning, _Gwaiting)
558         gp.waitreason = waitReasonGCAssistMarking
559
560         // drain own cached work first in the hopes that it
561         // will be more cache friendly.
562         gcw := &getg().m.p.ptr().gcw
563         workDone := gcDrainN(gcw, scanWork)
564
565         casgstatus(gp, _Gwaiting, _Grunning)
566
567         // Record that we did this much scan work.
568         //
569         // Back out the number of bytes of assist credit that
570         // this scan work counts for. The "1+" is a poor man's
571         // round-up, to ensure this adds credit even if
572         // assistBytesPerWork is very low.
573         assistBytesPerWork := gcController.assistBytesPerWork.Load()
574         gp.gcAssistBytes += 1 + int64(assistBytesPerWork*float64(workDone))
575
576         // If this is the last worker and we ran out of work,
577         // signal a completion point.
578         incnwait := atomic.Xadd(&work.nwait, +1)
579         if incnwait > work.nproc {
580                 println("runtime: work.nwait=", incnwait,
581                         "work.nproc=", work.nproc)
582                 throw("work.nwait > work.nproc")
583         }
584
585         if incnwait == work.nproc && !gcMarkWorkAvailable(nil) {
586                 // This has reached a background completion point. Set
587                 // gp.param to a non-nil value to indicate this. It
588                 // doesn't matter what we set it to (it just has to be
589                 // a valid pointer).
590                 gp.param = unsafe.Pointer(gp)
591         }
592         now := nanotime()
593         duration := now - startTime
594         _p_ := gp.m.p.ptr()
595         _p_.gcAssistTime += duration
596         if _p_.gcAssistTime > gcAssistTimeSlack {
597                 gcController.assistTime.Add(_p_.gcAssistTime)
598                 gcCPULimiter.addAssistTime(_p_.gcAssistTime)
599                 gcCPULimiter.update(now)
600                 _p_.gcAssistTime = 0
601         }
602 }
603
604 // gcWakeAllAssists wakes all currently blocked assists. This is used
605 // at the end of a GC cycle. gcBlackenEnabled must be false to prevent
606 // new assists from going to sleep after this point.
607 func gcWakeAllAssists() {
608         lock(&work.assistQueue.lock)
609         list := work.assistQueue.q.popList()
610         injectglist(&list)
611         unlock(&work.assistQueue.lock)
612 }
613
614 // gcParkAssist puts the current goroutine on the assist queue and parks.
615 //
616 // gcParkAssist reports whether the assist is now satisfied. If it
617 // returns false, the caller must retry the assist.
618 func gcParkAssist() bool {
619         lock(&work.assistQueue.lock)
620         // If the GC cycle finished while we were getting the lock,
621         // exit the assist. The cycle can't finish while we hold the
622         // lock.
623         if atomic.Load(&gcBlackenEnabled) == 0 {
624                 unlock(&work.assistQueue.lock)
625                 return true
626         }
627
628         gp := getg()
629         oldList := work.assistQueue.q
630         work.assistQueue.q.pushBack(gp)
631
632         // Recheck for background credit now that this G is in
633         // the queue, but can still back out. This avoids a
634         // race in case background marking has flushed more
635         // credit since we checked above.
636         if atomic.Loadint64(&gcController.bgScanCredit) > 0 {
637                 work.assistQueue.q = oldList
638                 if oldList.tail != 0 {
639                         oldList.tail.ptr().schedlink.set(nil)
640                 }
641                 unlock(&work.assistQueue.lock)
642                 return false
643         }
644         // Park.
645         goparkunlock(&work.assistQueue.lock, waitReasonGCAssistWait, traceEvGoBlockGC, 2)
646         return true
647 }
648
649 // gcFlushBgCredit flushes scanWork units of background scan work
650 // credit. This first satisfies blocked assists on the
651 // work.assistQueue and then flushes any remaining credit to
652 // gcController.bgScanCredit.
653 //
654 // Write barriers are disallowed because this is used by gcDrain after
655 // it has ensured that all work is drained and this must preserve that
656 // condition.
657 //
658 //go:nowritebarrierrec
659 func gcFlushBgCredit(scanWork int64) {
660         if work.assistQueue.q.empty() {
661                 // Fast path; there are no blocked assists. There's a
662                 // small window here where an assist may add itself to
663                 // the blocked queue and park. If that happens, we'll
664                 // just get it on the next flush.
665                 atomic.Xaddint64(&gcController.bgScanCredit, scanWork)
666                 return
667         }
668
669         assistBytesPerWork := gcController.assistBytesPerWork.Load()
670         scanBytes := int64(float64(scanWork) * assistBytesPerWork)
671
672         lock(&work.assistQueue.lock)
673         for !work.assistQueue.q.empty() && scanBytes > 0 {
674                 gp := work.assistQueue.q.pop()
675                 // Note that gp.gcAssistBytes is negative because gp
676                 // is in debt. Think carefully about the signs below.
677                 if scanBytes+gp.gcAssistBytes >= 0 {
678                         // Satisfy this entire assist debt.
679                         scanBytes += gp.gcAssistBytes
680                         gp.gcAssistBytes = 0
681                         // It's important that we *not* put gp in
682                         // runnext. Otherwise, it's possible for user
683                         // code to exploit the GC worker's high
684                         // scheduler priority to get itself always run
685                         // before other goroutines and always in the
686                         // fresh quantum started by GC.
687                         ready(gp, 0, false)
688                 } else {
689                         // Partially satisfy this assist.
690                         gp.gcAssistBytes += scanBytes
691                         scanBytes = 0
692                         // As a heuristic, we move this assist to the
693                         // back of the queue so that large assists
694                         // can't clog up the assist queue and
695                         // substantially delay small assists.
696                         work.assistQueue.q.pushBack(gp)
697                         break
698                 }
699         }
700
701         if scanBytes > 0 {
702                 // Convert from scan bytes back to work.
703                 assistWorkPerByte := gcController.assistWorkPerByte.Load()
704                 scanWork = int64(float64(scanBytes) * assistWorkPerByte)
705                 atomic.Xaddint64(&gcController.bgScanCredit, scanWork)
706         }
707         unlock(&work.assistQueue.lock)
708 }
709
710 // scanstack scans gp's stack, greying all pointers found on the stack.
711 //
712 // Returns the amount of scan work performed, but doesn't update
713 // gcController.stackScanWork or flush any credit. Any background credit produced
714 // by this function should be flushed by its caller. scanstack itself can't
715 // safely flush because it may result in trying to wake up a goroutine that
716 // was just scanned, resulting in a self-deadlock.
717 //
718 // scanstack will also shrink the stack if it is safe to do so. If it
719 // is not, it schedules a stack shrink for the next synchronous safe
720 // point.
721 //
722 // scanstack is marked go:systemstack because it must not be preempted
723 // while using a workbuf.
724 //
725 //go:nowritebarrier
726 //go:systemstack
727 func scanstack(gp *g, gcw *gcWork) int64 {
728         if readgstatus(gp)&_Gscan == 0 {
729                 print("runtime:scanstack: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", hex(readgstatus(gp)), "\n")
730                 throw("scanstack - bad status")
731         }
732
733         switch readgstatus(gp) &^ _Gscan {
734         default:
735                 print("runtime: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n")
736                 throw("mark - bad status")
737         case _Gdead:
738                 return 0
739         case _Grunning:
740                 print("runtime: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n")
741                 throw("scanstack: goroutine not stopped")
742         case _Grunnable, _Gsyscall, _Gwaiting:
743                 // ok
744         }
745
746         if gp == getg() {
747                 throw("can't scan our own stack")
748         }
749
750         // scannedSize is the amount of work we'll be reporting.
751         //
752         // It is less than the allocated size (which is hi-lo).
753         var sp uintptr
754         if gp.syscallsp != 0 {
755                 sp = gp.syscallsp // If in a system call this is the stack pointer (gp.sched.sp can be 0 in this case on Windows).
756         } else {
757                 sp = gp.sched.sp
758         }
759         scannedSize := gp.stack.hi - sp
760
761         // Keep statistics for initial stack size calculation.
762         // Note that this accumulates the scanned size, not the allocated size.
763         p := getg().m.p.ptr()
764         p.scannedStackSize += uint64(scannedSize)
765         p.scannedStacks++
766
767         if isShrinkStackSafe(gp) {
768                 // Shrink the stack if not much of it is being used.
769                 shrinkstack(gp)
770         } else {
771                 // Otherwise, shrink the stack at the next sync safe point.
772                 gp.preemptShrink = true
773         }
774
775         var state stackScanState
776         state.stack = gp.stack
777
778         if stackTraceDebug {
779                 println("stack trace goroutine", gp.goid)
780         }
781
782         if debugScanConservative && gp.asyncSafePoint {
783                 print("scanning async preempted goroutine ", gp.goid, " stack [", hex(gp.stack.lo), ",", hex(gp.stack.hi), ")\n")
784         }
785
786         // Scan the saved context register. This is effectively a live
787         // register that gets moved back and forth between the
788         // register and sched.ctxt without a write barrier.
789         if gp.sched.ctxt != nil {
790                 scanblock(uintptr(unsafe.Pointer(&gp.sched.ctxt)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
791         }
792
793         // Scan the stack. Accumulate a list of stack objects.
794         scanframe := func(frame *stkframe, unused unsafe.Pointer) bool {
795                 scanframeworker(frame, &state, gcw)
796                 return true
797         }
798         gentraceback(^uintptr(0), ^uintptr(0), 0, gp, 0, nil, 0x7fffffff, scanframe, nil, 0)
799
800         // Find additional pointers that point into the stack from the heap.
801         // Currently this includes defers and panics. See also function copystack.
802
803         // Find and trace other pointers in defer records.
804         for d := gp._defer; d != nil; d = d.link {
805                 if d.fn != nil {
806                         // Scan the func value, which could be a stack allocated closure.
807                         // See issue 30453.
808                         scanblock(uintptr(unsafe.Pointer(&d.fn)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
809                 }
810                 if d.link != nil {
811                         // The link field of a stack-allocated defer record might point
812                         // to a heap-allocated defer record. Keep that heap record live.
813                         scanblock(uintptr(unsafe.Pointer(&d.link)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
814                 }
815                 // Retain defers records themselves.
816                 // Defer records might not be reachable from the G through regular heap
817                 // tracing because the defer linked list might weave between the stack and the heap.
818                 if d.heap {
819                         scanblock(uintptr(unsafe.Pointer(&d)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
820                 }
821         }
822         if gp._panic != nil {
823                 // Panics are always stack allocated.
824                 state.putPtr(uintptr(unsafe.Pointer(gp._panic)), false)
825         }
826
827         // Find and scan all reachable stack objects.
828         //
829         // The state's pointer queue prioritizes precise pointers over
830         // conservative pointers so that we'll prefer scanning stack
831         // objects precisely.
832         state.buildIndex()
833         for {
834                 p, conservative := state.getPtr()
835                 if p == 0 {
836                         break
837                 }
838                 obj := state.findObject(p)
839                 if obj == nil {
840                         continue
841                 }
842                 r := obj.r
843                 if r == nil {
844                         // We've already scanned this object.
845                         continue
846                 }
847                 obj.setRecord(nil) // Don't scan it again.
848                 if stackTraceDebug {
849                         printlock()
850                         print("  live stkobj at", hex(state.stack.lo+uintptr(obj.off)), "of size", obj.size)
851                         if conservative {
852                                 print(" (conservative)")
853                         }
854                         println()
855                         printunlock()
856                 }
857                 gcdata := r.gcdata()
858                 var s *mspan
859                 if r.useGCProg() {
860                         // This path is pretty unlikely, an object large enough
861                         // to have a GC program allocated on the stack.
862                         // We need some space to unpack the program into a straight
863                         // bitmask, which we allocate/free here.
864                         // TODO: it would be nice if there were a way to run a GC
865                         // program without having to store all its bits. We'd have
866                         // to change from a Lempel-Ziv style program to something else.
867                         // Or we can forbid putting objects on stacks if they require
868                         // a gc program (see issue 27447).
869                         s = materializeGCProg(r.ptrdata(), gcdata)
870                         gcdata = (*byte)(unsafe.Pointer(s.startAddr))
871                 }
872
873                 b := state.stack.lo + uintptr(obj.off)
874                 if conservative {
875                         scanConservative(b, r.ptrdata(), gcdata, gcw, &state)
876                 } else {
877                         scanblock(b, r.ptrdata(), gcdata, gcw, &state)
878                 }
879
880                 if s != nil {
881                         dematerializeGCProg(s)
882                 }
883         }
884
885         // Deallocate object buffers.
886         // (Pointer buffers were all deallocated in the loop above.)
887         for state.head != nil {
888                 x := state.head
889                 state.head = x.next
890                 if stackTraceDebug {
891                         for i := 0; i < x.nobj; i++ {
892                                 obj := &x.obj[i]
893                                 if obj.r == nil { // reachable
894                                         continue
895                                 }
896                                 println("  dead stkobj at", hex(gp.stack.lo+uintptr(obj.off)), "of size", obj.r.size)
897                                 // Note: not necessarily really dead - only reachable-from-ptr dead.
898                         }
899                 }
900                 x.nobj = 0
901                 putempty((*workbuf)(unsafe.Pointer(x)))
902         }
903         if state.buf != nil || state.cbuf != nil || state.freeBuf != nil {
904                 throw("remaining pointer buffers")
905         }
906         return int64(scannedSize)
907 }
908
909 // Scan a stack frame: local variables and function arguments/results.
910 //
911 //go:nowritebarrier
912 func scanframeworker(frame *stkframe, state *stackScanState, gcw *gcWork) {
913         if _DebugGC > 1 && frame.continpc != 0 {
914                 print("scanframe ", funcname(frame.fn), "\n")
915         }
916
917         isAsyncPreempt := frame.fn.valid() && frame.fn.funcID == funcID_asyncPreempt
918         isDebugCall := frame.fn.valid() && frame.fn.funcID == funcID_debugCallV2
919         if state.conservative || isAsyncPreempt || isDebugCall {
920                 if debugScanConservative {
921                         println("conservatively scanning function", funcname(frame.fn), "at PC", hex(frame.continpc))
922                 }
923
924                 // Conservatively scan the frame. Unlike the precise
925                 // case, this includes the outgoing argument space
926                 // since we may have stopped while this function was
927                 // setting up a call.
928                 //
929                 // TODO: We could narrow this down if the compiler
930                 // produced a single map per function of stack slots
931                 // and registers that ever contain a pointer.
932                 if frame.varp != 0 {
933                         size := frame.varp - frame.sp
934                         if size > 0 {
935                                 scanConservative(frame.sp, size, nil, gcw, state)
936                         }
937                 }
938
939                 // Scan arguments to this frame.
940                 if frame.arglen != 0 {
941                         // TODO: We could pass the entry argument map
942                         // to narrow this down further.
943                         scanConservative(frame.argp, frame.arglen, nil, gcw, state)
944                 }
945
946                 if isAsyncPreempt || isDebugCall {
947                         // This function's frame contained the
948                         // registers for the asynchronously stopped
949                         // parent frame. Scan the parent
950                         // conservatively.
951                         state.conservative = true
952                 } else {
953                         // We only wanted to scan those two frames
954                         // conservatively. Clear the flag for future
955                         // frames.
956                         state.conservative = false
957                 }
958                 return
959         }
960
961         locals, args, objs := getStackMap(frame, &state.cache, false)
962
963         // Scan local variables if stack frame has been allocated.
964         if locals.n > 0 {
965                 size := uintptr(locals.n) * goarch.PtrSize
966                 scanblock(frame.varp-size, size, locals.bytedata, gcw, state)
967         }
968
969         // Scan arguments.
970         if args.n > 0 {
971                 scanblock(frame.argp, uintptr(args.n)*goarch.PtrSize, args.bytedata, gcw, state)
972         }
973
974         // Add all stack objects to the stack object list.
975         if frame.varp != 0 {
976                 // varp is 0 for defers, where there are no locals.
977                 // In that case, there can't be a pointer to its args, either.
978                 // (And all args would be scanned above anyway.)
979                 for i := range objs {
980                         obj := &objs[i]
981                         off := obj.off
982                         base := frame.varp // locals base pointer
983                         if off >= 0 {
984                                 base = frame.argp // arguments and return values base pointer
985                         }
986                         ptr := base + uintptr(off)
987                         if ptr < frame.sp {
988                                 // object hasn't been allocated in the frame yet.
989                                 continue
990                         }
991                         if stackTraceDebug {
992                                 println("stkobj at", hex(ptr), "of size", obj.size)
993                         }
994                         state.addObject(ptr, obj)
995                 }
996         }
997 }
998
999 type gcDrainFlags int
1000
1001 const (
1002         gcDrainUntilPreempt gcDrainFlags = 1 << iota
1003         gcDrainFlushBgCredit
1004         gcDrainIdle
1005         gcDrainFractional
1006 )
1007
1008 // gcDrain scans roots and objects in work buffers, blackening grey
1009 // objects until it is unable to get more work. It may return before
1010 // GC is done; it's the caller's responsibility to balance work from
1011 // other Ps.
1012 //
1013 // If flags&gcDrainUntilPreempt != 0, gcDrain returns when g.preempt
1014 // is set.
1015 //
1016 // If flags&gcDrainIdle != 0, gcDrain returns when there is other work
1017 // to do.
1018 //
1019 // If flags&gcDrainFractional != 0, gcDrain self-preempts when
1020 // pollFractionalWorkerExit() returns true. This implies
1021 // gcDrainNoBlock.
1022 //
1023 // If flags&gcDrainFlushBgCredit != 0, gcDrain flushes scan work
1024 // credit to gcController.bgScanCredit every gcCreditSlack units of
1025 // scan work.
1026 //
1027 // gcDrain will always return if there is a pending STW.
1028 //
1029 //go:nowritebarrier
1030 func gcDrain(gcw *gcWork, flags gcDrainFlags) {
1031         if !writeBarrier.needed {
1032                 throw("gcDrain phase incorrect")
1033         }
1034
1035         gp := getg().m.curg
1036         preemptible := flags&gcDrainUntilPreempt != 0
1037         flushBgCredit := flags&gcDrainFlushBgCredit != 0
1038         idle := flags&gcDrainIdle != 0
1039
1040         initScanWork := gcw.heapScanWork
1041
1042         // checkWork is the scan work before performing the next
1043         // self-preempt check.
1044         checkWork := int64(1<<63 - 1)
1045         var check func() bool
1046         if flags&(gcDrainIdle|gcDrainFractional) != 0 {
1047                 checkWork = initScanWork + drainCheckThreshold
1048                 if idle {
1049                         check = pollWork
1050                 } else if flags&gcDrainFractional != 0 {
1051                         check = pollFractionalWorkerExit
1052                 }
1053         }
1054
1055         // Drain root marking jobs.
1056         if work.markrootNext < work.markrootJobs {
1057                 // Stop if we're preemptible or if someone wants to STW.
1058                 for !(gp.preempt && (preemptible || atomic.Load(&sched.gcwaiting) != 0)) {
1059                         job := atomic.Xadd(&work.markrootNext, +1) - 1
1060                         if job >= work.markrootJobs {
1061                                 break
1062                         }
1063                         markroot(gcw, job, flushBgCredit)
1064                         if check != nil && check() {
1065                                 goto done
1066                         }
1067                 }
1068         }
1069
1070         // Drain heap marking jobs.
1071         // Stop if we're preemptible or if someone wants to STW.
1072         for !(gp.preempt && (preemptible || atomic.Load(&sched.gcwaiting) != 0)) {
1073                 // Try to keep work available on the global queue. We used to
1074                 // check if there were waiting workers, but it's better to
1075                 // just keep work available than to make workers wait. In the
1076                 // worst case, we'll do O(log(_WorkbufSize)) unnecessary
1077                 // balances.
1078                 if work.full == 0 {
1079                         gcw.balance()
1080                 }
1081
1082                 b := gcw.tryGetFast()
1083                 if b == 0 {
1084                         b = gcw.tryGet()
1085                         if b == 0 {
1086                                 // Flush the write barrier
1087                                 // buffer; this may create
1088                                 // more work.
1089                                 wbBufFlush(nil, 0)
1090                                 b = gcw.tryGet()
1091                         }
1092                 }
1093                 if b == 0 {
1094                         // Unable to get work.
1095                         break
1096                 }
1097                 scanobject(b, gcw)
1098
1099                 // Flush background scan work credit to the global
1100                 // account if we've accumulated enough locally so
1101                 // mutator assists can draw on it.
1102                 if gcw.heapScanWork >= gcCreditSlack {
1103                         gcController.heapScanWork.Add(gcw.heapScanWork)
1104                         if flushBgCredit {
1105                                 gcFlushBgCredit(gcw.heapScanWork - initScanWork)
1106                                 initScanWork = 0
1107                         }
1108                         checkWork -= gcw.heapScanWork
1109                         gcw.heapScanWork = 0
1110
1111                         if checkWork <= 0 {
1112                                 checkWork += drainCheckThreshold
1113                                 if check != nil && check() {
1114                                         break
1115                                 }
1116                         }
1117                 }
1118         }
1119
1120 done:
1121         // Flush remaining scan work credit.
1122         if gcw.heapScanWork > 0 {
1123                 gcController.heapScanWork.Add(gcw.heapScanWork)
1124                 if flushBgCredit {
1125                         gcFlushBgCredit(gcw.heapScanWork - initScanWork)
1126                 }
1127                 gcw.heapScanWork = 0
1128         }
1129 }
1130
1131 // gcDrainN blackens grey objects until it has performed roughly
1132 // scanWork units of scan work or the G is preempted. This is
1133 // best-effort, so it may perform less work if it fails to get a work
1134 // buffer. Otherwise, it will perform at least n units of work, but
1135 // may perform more because scanning is always done in whole object
1136 // increments. It returns the amount of scan work performed.
1137 //
1138 // The caller goroutine must be in a preemptible state (e.g.,
1139 // _Gwaiting) to prevent deadlocks during stack scanning. As a
1140 // consequence, this must be called on the system stack.
1141 //
1142 //go:nowritebarrier
1143 //go:systemstack
1144 func gcDrainN(gcw *gcWork, scanWork int64) int64 {
1145         if !writeBarrier.needed {
1146                 throw("gcDrainN phase incorrect")
1147         }
1148
1149         // There may already be scan work on the gcw, which we don't
1150         // want to claim was done by this call.
1151         workFlushed := -gcw.heapScanWork
1152
1153         gp := getg().m.curg
1154         for !gp.preempt && workFlushed+gcw.heapScanWork < scanWork {
1155                 // See gcDrain comment.
1156                 if work.full == 0 {
1157                         gcw.balance()
1158                 }
1159
1160                 b := gcw.tryGetFast()
1161                 if b == 0 {
1162                         b = gcw.tryGet()
1163                         if b == 0 {
1164                                 // Flush the write barrier buffer;
1165                                 // this may create more work.
1166                                 wbBufFlush(nil, 0)
1167                                 b = gcw.tryGet()
1168                         }
1169                 }
1170
1171                 if b == 0 {
1172                         // Try to do a root job.
1173                         if work.markrootNext < work.markrootJobs {
1174                                 job := atomic.Xadd(&work.markrootNext, +1) - 1
1175                                 if job < work.markrootJobs {
1176                                         workFlushed += markroot(gcw, job, false)
1177                                         continue
1178                                 }
1179                         }
1180                         // No heap or root jobs.
1181                         break
1182                 }
1183
1184                 scanobject(b, gcw)
1185
1186                 // Flush background scan work credit.
1187                 if gcw.heapScanWork >= gcCreditSlack {
1188                         gcController.heapScanWork.Add(gcw.heapScanWork)
1189                         workFlushed += gcw.heapScanWork
1190                         gcw.heapScanWork = 0
1191                 }
1192         }
1193
1194         // Unlike gcDrain, there's no need to flush remaining work
1195         // here because this never flushes to bgScanCredit and
1196         // gcw.dispose will flush any remaining work to scanWork.
1197
1198         return workFlushed + gcw.heapScanWork
1199 }
1200
1201 // scanblock scans b as scanobject would, but using an explicit
1202 // pointer bitmap instead of the heap bitmap.
1203 //
1204 // This is used to scan non-heap roots, so it does not update
1205 // gcw.bytesMarked or gcw.heapScanWork.
1206 //
1207 // If stk != nil, possible stack pointers are also reported to stk.putPtr.
1208 //
1209 //go:nowritebarrier
1210 func scanblock(b0, n0 uintptr, ptrmask *uint8, gcw *gcWork, stk *stackScanState) {
1211         // Use local copies of original parameters, so that a stack trace
1212         // due to one of the throws below shows the original block
1213         // base and extent.
1214         b := b0
1215         n := n0
1216
1217         for i := uintptr(0); i < n; {
1218                 // Find bits for the next word.
1219                 bits := uint32(*addb(ptrmask, i/(goarch.PtrSize*8)))
1220                 if bits == 0 {
1221                         i += goarch.PtrSize * 8
1222                         continue
1223                 }
1224                 for j := 0; j < 8 && i < n; j++ {
1225                         if bits&1 != 0 {
1226                                 // Same work as in scanobject; see comments there.
1227                                 p := *(*uintptr)(unsafe.Pointer(b + i))
1228                                 if p != 0 {
1229                                         if obj, span, objIndex := findObject(p, b, i); obj != 0 {
1230                                                 greyobject(obj, b, i, span, gcw, objIndex)
1231                                         } else if stk != nil && p >= stk.stack.lo && p < stk.stack.hi {
1232                                                 stk.putPtr(p, false)
1233                                         }
1234                                 }
1235                         }
1236                         bits >>= 1
1237                         i += goarch.PtrSize
1238                 }
1239         }
1240 }
1241
1242 // scanobject scans the object starting at b, adding pointers to gcw.
1243 // b must point to the beginning of a heap object or an oblet.
1244 // scanobject consults the GC bitmap for the pointer mask and the
1245 // spans for the size of the object.
1246 //
1247 //go:nowritebarrier
1248 func scanobject(b uintptr, gcw *gcWork) {
1249         // Prefetch object before we scan it.
1250         //
1251         // This will overlap fetching the beginning of the object with initial
1252         // setup before we start scanning the object.
1253         sys.Prefetch(b)
1254
1255         // Find the bits for b and the size of the object at b.
1256         //
1257         // b is either the beginning of an object, in which case this
1258         // is the size of the object to scan, or it points to an
1259         // oblet, in which case we compute the size to scan below.
1260         hbits := heapBitsForAddr(b)
1261         s := spanOfUnchecked(b)
1262         n := s.elemsize
1263         if n == 0 {
1264                 throw("scanobject n == 0")
1265         }
1266
1267         if n > maxObletBytes {
1268                 // Large object. Break into oblets for better
1269                 // parallelism and lower latency.
1270                 if b == s.base() {
1271                         // It's possible this is a noscan object (not
1272                         // from greyobject, but from other code
1273                         // paths), in which case we must *not* enqueue
1274                         // oblets since their bitmaps will be
1275                         // uninitialized.
1276                         if s.spanclass.noscan() {
1277                                 // Bypass the whole scan.
1278                                 gcw.bytesMarked += uint64(n)
1279                                 return
1280                         }
1281
1282                         // Enqueue the other oblets to scan later.
1283                         // Some oblets may be in b's scalar tail, but
1284                         // these will be marked as "no more pointers",
1285                         // so we'll drop out immediately when we go to
1286                         // scan those.
1287                         for oblet := b + maxObletBytes; oblet < s.base()+s.elemsize; oblet += maxObletBytes {
1288                                 if !gcw.putFast(oblet) {
1289                                         gcw.put(oblet)
1290                                 }
1291                         }
1292                 }
1293
1294                 // Compute the size of the oblet. Since this object
1295                 // must be a large object, s.base() is the beginning
1296                 // of the object.
1297                 n = s.base() + s.elemsize - b
1298                 if n > maxObletBytes {
1299                         n = maxObletBytes
1300                 }
1301         }
1302
1303         var i uintptr
1304         for i = 0; i < n; i, hbits = i+goarch.PtrSize, hbits.next() {
1305                 // Load bits once. See CL 22712 and issue 16973 for discussion.
1306                 bits := hbits.bits()
1307                 if bits&bitScan == 0 {
1308                         break // no more pointers in this object
1309                 }
1310                 if bits&bitPointer == 0 {
1311                         continue // not a pointer
1312                 }
1313
1314                 // Work here is duplicated in scanblock and above.
1315                 // If you make changes here, make changes there too.
1316                 obj := *(*uintptr)(unsafe.Pointer(b + i))
1317
1318                 // At this point we have extracted the next potential pointer.
1319                 // Quickly filter out nil and pointers back to the current object.
1320                 if obj != 0 && obj-b >= n {
1321                         // Test if obj points into the Go heap and, if so,
1322                         // mark the object.
1323                         //
1324                         // Note that it's possible for findObject to
1325                         // fail if obj points to a just-allocated heap
1326                         // object because of a race with growing the
1327                         // heap. In this case, we know the object was
1328                         // just allocated and hence will be marked by
1329                         // allocation itself.
1330                         if obj, span, objIndex := findObject(obj, b, i); obj != 0 {
1331                                 greyobject(obj, b, i, span, gcw, objIndex)
1332                         }
1333                 }
1334         }
1335         gcw.bytesMarked += uint64(n)
1336         gcw.heapScanWork += int64(i)
1337 }
1338
1339 // scanConservative scans block [b, b+n) conservatively, treating any
1340 // pointer-like value in the block as a pointer.
1341 //
1342 // If ptrmask != nil, only words that are marked in ptrmask are
1343 // considered as potential pointers.
1344 //
1345 // If state != nil, it's assumed that [b, b+n) is a block in the stack
1346 // and may contain pointers to stack objects.
1347 func scanConservative(b, n uintptr, ptrmask *uint8, gcw *gcWork, state *stackScanState) {
1348         if debugScanConservative {
1349                 printlock()
1350                 print("conservatively scanning [", hex(b), ",", hex(b+n), ")\n")
1351                 hexdumpWords(b, b+n, func(p uintptr) byte {
1352                         if ptrmask != nil {
1353                                 word := (p - b) / goarch.PtrSize
1354                                 bits := *addb(ptrmask, word/8)
1355                                 if (bits>>(word%8))&1 == 0 {
1356                                         return '$'
1357                                 }
1358                         }
1359
1360                         val := *(*uintptr)(unsafe.Pointer(p))
1361                         if state != nil && state.stack.lo <= val && val < state.stack.hi {
1362                                 return '@'
1363                         }
1364
1365                         span := spanOfHeap(val)
1366                         if span == nil {
1367                                 return ' '
1368                         }
1369                         idx := span.objIndex(val)
1370                         if span.isFree(idx) {
1371                                 return ' '
1372                         }
1373                         return '*'
1374                 })
1375                 printunlock()
1376         }
1377
1378         for i := uintptr(0); i < n; i += goarch.PtrSize {
1379                 if ptrmask != nil {
1380                         word := i / goarch.PtrSize
1381                         bits := *addb(ptrmask, word/8)
1382                         if bits == 0 {
1383                                 // Skip 8 words (the loop increment will do the 8th)
1384                                 //
1385                                 // This must be the first time we've
1386                                 // seen this word of ptrmask, so i
1387                                 // must be 8-word-aligned, but check
1388                                 // our reasoning just in case.
1389                                 if i%(goarch.PtrSize*8) != 0 {
1390                                         throw("misaligned mask")
1391                                 }
1392                                 i += goarch.PtrSize*8 - goarch.PtrSize
1393                                 continue
1394                         }
1395                         if (bits>>(word%8))&1 == 0 {
1396                                 continue
1397                         }
1398                 }
1399
1400                 val := *(*uintptr)(unsafe.Pointer(b + i))
1401
1402                 // Check if val points into the stack.
1403                 if state != nil && state.stack.lo <= val && val < state.stack.hi {
1404                         // val may point to a stack object. This
1405                         // object may be dead from last cycle and
1406                         // hence may contain pointers to unallocated
1407                         // objects, but unlike heap objects we can't
1408                         // tell if it's already dead. Hence, if all
1409                         // pointers to this object are from
1410                         // conservative scanning, we have to scan it
1411                         // defensively, too.
1412                         state.putPtr(val, true)
1413                         continue
1414                 }
1415
1416                 // Check if val points to a heap span.
1417                 span := spanOfHeap(val)
1418                 if span == nil {
1419                         continue
1420                 }
1421
1422                 // Check if val points to an allocated object.
1423                 idx := span.objIndex(val)
1424                 if span.isFree(idx) {
1425                         continue
1426                 }
1427
1428                 // val points to an allocated object. Mark it.
1429                 obj := span.base() + idx*span.elemsize
1430                 greyobject(obj, b, i, span, gcw, idx)
1431         }
1432 }
1433
1434 // Shade the object if it isn't already.
1435 // The object is not nil and known to be in the heap.
1436 // Preemption must be disabled.
1437 //
1438 //go:nowritebarrier
1439 func shade(b uintptr) {
1440         if obj, span, objIndex := findObject(b, 0, 0); obj != 0 {
1441                 gcw := &getg().m.p.ptr().gcw
1442                 greyobject(obj, 0, 0, span, gcw, objIndex)
1443         }
1444 }
1445
1446 // obj is the start of an object with mark mbits.
1447 // If it isn't already marked, mark it and enqueue into gcw.
1448 // base and off are for debugging only and could be removed.
1449 //
1450 // See also wbBufFlush1, which partially duplicates this logic.
1451 //
1452 //go:nowritebarrierrec
1453 func greyobject(obj, base, off uintptr, span *mspan, gcw *gcWork, objIndex uintptr) {
1454         // obj should be start of allocation, and so must be at least pointer-aligned.
1455         if obj&(goarch.PtrSize-1) != 0 {
1456                 throw("greyobject: obj not pointer-aligned")
1457         }
1458         mbits := span.markBitsForIndex(objIndex)
1459
1460         if useCheckmark {
1461                 if setCheckmark(obj, base, off, mbits) {
1462                         // Already marked.
1463                         return
1464                 }
1465         } else {
1466                 if debug.gccheckmark > 0 && span.isFree(objIndex) {
1467                         print("runtime: marking free object ", hex(obj), " found at *(", hex(base), "+", hex(off), ")\n")
1468                         gcDumpObject("base", base, off)
1469                         gcDumpObject("obj", obj, ^uintptr(0))
1470                         getg().m.traceback = 2
1471                         throw("marking free object")
1472                 }
1473
1474                 // If marked we have nothing to do.
1475                 if mbits.isMarked() {
1476                         return
1477                 }
1478                 mbits.setMarked()
1479
1480                 // Mark span.
1481                 arena, pageIdx, pageMask := pageIndexOf(span.base())
1482                 if arena.pageMarks[pageIdx]&pageMask == 0 {
1483                         atomic.Or8(&arena.pageMarks[pageIdx], pageMask)
1484                 }
1485
1486                 // If this is a noscan object, fast-track it to black
1487                 // instead of greying it.
1488                 if span.spanclass.noscan() {
1489                         gcw.bytesMarked += uint64(span.elemsize)
1490                         return
1491                 }
1492         }
1493
1494         // We're adding obj to P's local workbuf, so it's likely
1495         // this object will be processed soon by the same P.
1496         // Even if the workbuf gets flushed, there will likely still be
1497         // some benefit on platforms with inclusive shared caches.
1498         sys.Prefetch(obj)
1499         // Queue the obj for scanning.
1500         if !gcw.putFast(obj) {
1501                 gcw.put(obj)
1502         }
1503 }
1504
1505 // gcDumpObject dumps the contents of obj for debugging and marks the
1506 // field at byte offset off in obj.
1507 func gcDumpObject(label string, obj, off uintptr) {
1508         s := spanOf(obj)
1509         print(label, "=", hex(obj))
1510         if s == nil {
1511                 print(" s=nil\n")
1512                 return
1513         }
1514         print(" s.base()=", hex(s.base()), " s.limit=", hex(s.limit), " s.spanclass=", s.spanclass, " s.elemsize=", s.elemsize, " s.state=")
1515         if state := s.state.get(); 0 <= state && int(state) < len(mSpanStateNames) {
1516                 print(mSpanStateNames[state], "\n")
1517         } else {
1518                 print("unknown(", state, ")\n")
1519         }
1520
1521         skipped := false
1522         size := s.elemsize
1523         if s.state.get() == mSpanManual && size == 0 {
1524                 // We're printing something from a stack frame. We
1525                 // don't know how big it is, so just show up to an
1526                 // including off.
1527                 size = off + goarch.PtrSize
1528         }
1529         for i := uintptr(0); i < size; i += goarch.PtrSize {
1530                 // For big objects, just print the beginning (because
1531                 // that usually hints at the object's type) and the
1532                 // fields around off.
1533                 if !(i < 128*goarch.PtrSize || off-16*goarch.PtrSize < i && i < off+16*goarch.PtrSize) {
1534                         skipped = true
1535                         continue
1536                 }
1537                 if skipped {
1538                         print(" ...\n")
1539                         skipped = false
1540                 }
1541                 print(" *(", label, "+", i, ") = ", hex(*(*uintptr)(unsafe.Pointer(obj + i))))
1542                 if i == off {
1543                         print(" <==")
1544                 }
1545                 print("\n")
1546         }
1547         if skipped {
1548                 print(" ...\n")
1549         }
1550 }
1551
1552 // gcmarknewobject marks a newly allocated object black. obj must
1553 // not contain any non-nil pointers.
1554 //
1555 // This is nosplit so it can manipulate a gcWork without preemption.
1556 //
1557 //go:nowritebarrier
1558 //go:nosplit
1559 func gcmarknewobject(span *mspan, obj, size, scanSize uintptr) {
1560         if useCheckmark { // The world should be stopped so this should not happen.
1561                 throw("gcmarknewobject called while doing checkmark")
1562         }
1563
1564         // Mark object.
1565         objIndex := span.objIndex(obj)
1566         span.markBitsForIndex(objIndex).setMarked()
1567
1568         // Mark span.
1569         arena, pageIdx, pageMask := pageIndexOf(span.base())
1570         if arena.pageMarks[pageIdx]&pageMask == 0 {
1571                 atomic.Or8(&arena.pageMarks[pageIdx], pageMask)
1572         }
1573
1574         gcw := &getg().m.p.ptr().gcw
1575         gcw.bytesMarked += uint64(size)
1576 }
1577
1578 // gcMarkTinyAllocs greys all active tiny alloc blocks.
1579 //
1580 // The world must be stopped.
1581 func gcMarkTinyAllocs() {
1582         assertWorldStopped()
1583
1584         for _, p := range allp {
1585                 c := p.mcache
1586                 if c == nil || c.tiny == 0 {
1587                         continue
1588                 }
1589                 _, span, objIndex := findObject(c.tiny, 0, 0)
1590                 gcw := &p.gcw
1591                 greyobject(c.tiny, 0, 0, span, gcw, objIndex)
1592         }
1593 }