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