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