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