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