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