]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/mgcmark.go
runtime: implement experiment to replace heap bitmap with alloc headers
[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                         traceGCMarkAssistDone()
424                 }
425                 return
426         }
427         // Compute the amount of scan work we need to do to make the
428         // balance positive. When the required amount of work is low,
429         // we over-assist to build up credit for future allocations
430         // and amortize the cost of assisting.
431         assistWorkPerByte := gcController.assistWorkPerByte.Load()
432         assistBytesPerWork := gcController.assistBytesPerWork.Load()
433         debtBytes := -gp.gcAssistBytes
434         scanWork := int64(assistWorkPerByte * float64(debtBytes))
435         if scanWork < gcOverAssistWork {
436                 scanWork = gcOverAssistWork
437                 debtBytes = int64(assistBytesPerWork * float64(scanWork))
438         }
439
440         // Steal as much credit as we can from the background GC's
441         // scan credit. This is racy and may drop the background
442         // credit below 0 if two mutators steal at the same time. This
443         // will just cause steals to fail until credit is accumulated
444         // again, so in the long run it doesn't really matter, but we
445         // do have to handle the negative credit case.
446         bgScanCredit := gcController.bgScanCredit.Load()
447         stolen := int64(0)
448         if bgScanCredit > 0 {
449                 if bgScanCredit < scanWork {
450                         stolen = bgScanCredit
451                         gp.gcAssistBytes += 1 + int64(assistBytesPerWork*float64(stolen))
452                 } else {
453                         stolen = scanWork
454                         gp.gcAssistBytes += debtBytes
455                 }
456                 gcController.bgScanCredit.Add(-stolen)
457
458                 scanWork -= stolen
459
460                 if scanWork == 0 {
461                         // We were able to steal all of the credit we
462                         // needed.
463                         if traced {
464                                 traceGCMarkAssistDone()
465                         }
466                         return
467                 }
468         }
469
470         if traceEnabled() && !traced {
471                 traced = true
472                 traceGCMarkAssistStart()
473         }
474
475         // Perform assist work
476         systemstack(func() {
477                 gcAssistAlloc1(gp, scanWork)
478                 // The user stack may have moved, so this can't touch
479                 // anything on it until it returns from systemstack.
480         })
481
482         completed := gp.param != nil
483         gp.param = nil
484         if completed {
485                 gcMarkDone()
486         }
487
488         if gp.gcAssistBytes < 0 {
489                 // We were unable steal enough credit or perform
490                 // enough work to pay off the assist debt. We need to
491                 // do one of these before letting the mutator allocate
492                 // more to prevent over-allocation.
493                 //
494                 // If this is because we were preempted, reschedule
495                 // and try some more.
496                 if gp.preempt {
497                         Gosched()
498                         goto retry
499                 }
500
501                 // Add this G to an assist queue and park. When the GC
502                 // has more background credit, it will satisfy queued
503                 // assists before flushing to the global credit pool.
504                 //
505                 // Note that this does *not* get woken up when more
506                 // work is added to the work list. The theory is that
507                 // there wasn't enough work to do anyway, so we might
508                 // as well let background marking take care of the
509                 // work that is available.
510                 if !gcParkAssist() {
511                         goto retry
512                 }
513
514                 // At this point either background GC has satisfied
515                 // this G's assist debt, or the GC cycle is over.
516         }
517         if traced {
518                 traceGCMarkAssistDone()
519         }
520 }
521
522 // gcAssistAlloc1 is the part of gcAssistAlloc that runs on the system
523 // stack. This is a separate function to make it easier to see that
524 // we're not capturing anything from the user stack, since the user
525 // stack may move while we're in this function.
526 //
527 // gcAssistAlloc1 indicates whether this assist completed the mark
528 // phase by setting gp.param to non-nil. This can't be communicated on
529 // the stack since it may move.
530 //
531 //go:systemstack
532 func gcAssistAlloc1(gp *g, scanWork int64) {
533         // Clear the flag indicating that this assist completed the
534         // mark phase.
535         gp.param = nil
536
537         if atomic.Load(&gcBlackenEnabled) == 0 {
538                 // The gcBlackenEnabled check in malloc races with the
539                 // store that clears it but an atomic check in every malloc
540                 // would be a performance hit.
541                 // Instead we recheck it here on the non-preemptible system
542                 // stack to determine if we should perform an assist.
543
544                 // GC is done, so ignore any remaining debt.
545                 gp.gcAssistBytes = 0
546                 return
547         }
548         // Track time spent in this assist. Since we're on the
549         // system stack, this is non-preemptible, so we can
550         // just measure start and end time.
551         //
552         // Limiter event tracking might be disabled if we end up here
553         // while on a mark worker.
554         startTime := nanotime()
555         trackLimiterEvent := gp.m.p.ptr().limiterEvent.start(limiterEventMarkAssist, startTime)
556
557         decnwait := atomic.Xadd(&work.nwait, -1)
558         if decnwait == work.nproc {
559                 println("runtime: work.nwait =", decnwait, "work.nproc=", work.nproc)
560                 throw("nwait > work.nprocs")
561         }
562
563         // gcDrainN requires the caller to be preemptible.
564         casGToWaiting(gp, _Grunning, waitReasonGCAssistMarking)
565
566         // drain own cached work first in the hopes that it
567         // will be more cache friendly.
568         gcw := &getg().m.p.ptr().gcw
569         workDone := gcDrainN(gcw, scanWork)
570
571         casgstatus(gp, _Gwaiting, _Grunning)
572
573         // Record that we did this much scan work.
574         //
575         // Back out the number of bytes of assist credit that
576         // this scan work counts for. The "1+" is a poor man's
577         // round-up, to ensure this adds credit even if
578         // assistBytesPerWork is very low.
579         assistBytesPerWork := gcController.assistBytesPerWork.Load()
580         gp.gcAssistBytes += 1 + int64(assistBytesPerWork*float64(workDone))
581
582         // If this is the last worker and we ran out of work,
583         // signal a completion point.
584         incnwait := atomic.Xadd(&work.nwait, +1)
585         if incnwait > work.nproc {
586                 println("runtime: work.nwait=", incnwait,
587                         "work.nproc=", work.nproc)
588                 throw("work.nwait > work.nproc")
589         }
590
591         if incnwait == work.nproc && !gcMarkWorkAvailable(nil) {
592                 // This has reached a background completion point. Set
593                 // gp.param to a non-nil value to indicate this. It
594                 // doesn't matter what we set it to (it just has to be
595                 // a valid pointer).
596                 gp.param = unsafe.Pointer(gp)
597         }
598         now := nanotime()
599         duration := now - startTime
600         pp := gp.m.p.ptr()
601         pp.gcAssistTime += duration
602         if trackLimiterEvent {
603                 pp.limiterEvent.stop(limiterEventMarkAssist, now)
604         }
605         if pp.gcAssistTime > gcAssistTimeSlack {
606                 gcController.assistTime.Add(pp.gcAssistTime)
607                 gcCPULimiter.update(now)
608                 pp.gcAssistTime = 0
609         }
610 }
611
612 // gcWakeAllAssists wakes all currently blocked assists. This is used
613 // at the end of a GC cycle. gcBlackenEnabled must be false to prevent
614 // new assists from going to sleep after this point.
615 func gcWakeAllAssists() {
616         lock(&work.assistQueue.lock)
617         list := work.assistQueue.q.popList()
618         injectglist(&list)
619         unlock(&work.assistQueue.lock)
620 }
621
622 // gcParkAssist puts the current goroutine on the assist queue and parks.
623 //
624 // gcParkAssist reports whether the assist is now satisfied. If it
625 // returns false, the caller must retry the assist.
626 func gcParkAssist() bool {
627         lock(&work.assistQueue.lock)
628         // If the GC cycle finished while we were getting the lock,
629         // exit the assist. The cycle can't finish while we hold the
630         // lock.
631         if atomic.Load(&gcBlackenEnabled) == 0 {
632                 unlock(&work.assistQueue.lock)
633                 return true
634         }
635
636         gp := getg()
637         oldList := work.assistQueue.q
638         work.assistQueue.q.pushBack(gp)
639
640         // Recheck for background credit now that this G is in
641         // the queue, but can still back out. This avoids a
642         // race in case background marking has flushed more
643         // credit since we checked above.
644         if gcController.bgScanCredit.Load() > 0 {
645                 work.assistQueue.q = oldList
646                 if oldList.tail != 0 {
647                         oldList.tail.ptr().schedlink.set(nil)
648                 }
649                 unlock(&work.assistQueue.lock)
650                 return false
651         }
652         // Park.
653         goparkunlock(&work.assistQueue.lock, waitReasonGCAssistWait, traceBlockGCMarkAssist, 2)
654         return true
655 }
656
657 // gcFlushBgCredit flushes scanWork units of background scan work
658 // credit. This first satisfies blocked assists on the
659 // work.assistQueue and then flushes any remaining credit to
660 // gcController.bgScanCredit.
661 //
662 // Write barriers are disallowed because this is used by gcDrain after
663 // it has ensured that all work is drained and this must preserve that
664 // condition.
665 //
666 //go:nowritebarrierrec
667 func gcFlushBgCredit(scanWork int64) {
668         if work.assistQueue.q.empty() {
669                 // Fast path; there are no blocked assists. There's a
670                 // small window here where an assist may add itself to
671                 // the blocked queue and park. If that happens, we'll
672                 // just get it on the next flush.
673                 gcController.bgScanCredit.Add(scanWork)
674                 return
675         }
676
677         assistBytesPerWork := gcController.assistBytesPerWork.Load()
678         scanBytes := int64(float64(scanWork) * assistBytesPerWork)
679
680         lock(&work.assistQueue.lock)
681         for !work.assistQueue.q.empty() && scanBytes > 0 {
682                 gp := work.assistQueue.q.pop()
683                 // Note that gp.gcAssistBytes is negative because gp
684                 // is in debt. Think carefully about the signs below.
685                 if scanBytes+gp.gcAssistBytes >= 0 {
686                         // Satisfy this entire assist debt.
687                         scanBytes += gp.gcAssistBytes
688                         gp.gcAssistBytes = 0
689                         // It's important that we *not* put gp in
690                         // runnext. Otherwise, it's possible for user
691                         // code to exploit the GC worker's high
692                         // scheduler priority to get itself always run
693                         // before other goroutines and always in the
694                         // fresh quantum started by GC.
695                         ready(gp, 0, false)
696                 } else {
697                         // Partially satisfy this assist.
698                         gp.gcAssistBytes += scanBytes
699                         scanBytes = 0
700                         // As a heuristic, we move this assist to the
701                         // back of the queue so that large assists
702                         // can't clog up the assist queue and
703                         // substantially delay small assists.
704                         work.assistQueue.q.pushBack(gp)
705                         break
706                 }
707         }
708
709         if scanBytes > 0 {
710                 // Convert from scan bytes back to work.
711                 assistWorkPerByte := gcController.assistWorkPerByte.Load()
712                 scanWork = int64(float64(scanBytes) * assistWorkPerByte)
713                 gcController.bgScanCredit.Add(scanWork)
714         }
715         unlock(&work.assistQueue.lock)
716 }
717
718 // scanstack scans gp's stack, greying all pointers found on the stack.
719 //
720 // Returns the amount of scan work performed, but doesn't update
721 // gcController.stackScanWork or flush any credit. Any background credit produced
722 // by this function should be flushed by its caller. scanstack itself can't
723 // safely flush because it may result in trying to wake up a goroutine that
724 // was just scanned, resulting in a self-deadlock.
725 //
726 // scanstack will also shrink the stack if it is safe to do so. If it
727 // is not, it schedules a stack shrink for the next synchronous safe
728 // point.
729 //
730 // scanstack is marked go:systemstack because it must not be preempted
731 // while using a workbuf.
732 //
733 //go:nowritebarrier
734 //go:systemstack
735 func scanstack(gp *g, gcw *gcWork) int64 {
736         if readgstatus(gp)&_Gscan == 0 {
737                 print("runtime:scanstack: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", hex(readgstatus(gp)), "\n")
738                 throw("scanstack - bad status")
739         }
740
741         switch readgstatus(gp) &^ _Gscan {
742         default:
743                 print("runtime: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n")
744                 throw("mark - bad status")
745         case _Gdead:
746                 return 0
747         case _Grunning:
748                 print("runtime: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n")
749                 throw("scanstack: goroutine not stopped")
750         case _Grunnable, _Gsyscall, _Gwaiting:
751                 // ok
752         }
753
754         if gp == getg() {
755                 throw("can't scan our own stack")
756         }
757
758         // scannedSize is the amount of work we'll be reporting.
759         //
760         // It is less than the allocated size (which is hi-lo).
761         var sp uintptr
762         if gp.syscallsp != 0 {
763                 sp = gp.syscallsp // If in a system call this is the stack pointer (gp.sched.sp can be 0 in this case on Windows).
764         } else {
765                 sp = gp.sched.sp
766         }
767         scannedSize := gp.stack.hi - sp
768
769         // Keep statistics for initial stack size calculation.
770         // Note that this accumulates the scanned size, not the allocated size.
771         p := getg().m.p.ptr()
772         p.scannedStackSize += uint64(scannedSize)
773         p.scannedStacks++
774
775         if isShrinkStackSafe(gp) {
776                 // Shrink the stack if not much of it is being used.
777                 shrinkstack(gp)
778         } else {
779                 // Otherwise, shrink the stack at the next sync safe point.
780                 gp.preemptShrink = true
781         }
782
783         var state stackScanState
784         state.stack = gp.stack
785
786         if stackTraceDebug {
787                 println("stack trace goroutine", gp.goid)
788         }
789
790         if debugScanConservative && gp.asyncSafePoint {
791                 print("scanning async preempted goroutine ", gp.goid, " stack [", hex(gp.stack.lo), ",", hex(gp.stack.hi), ")\n")
792         }
793
794         // Scan the saved context register. This is effectively a live
795         // register that gets moved back and forth between the
796         // register and sched.ctxt without a write barrier.
797         if gp.sched.ctxt != nil {
798                 scanblock(uintptr(unsafe.Pointer(&gp.sched.ctxt)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
799         }
800
801         // Scan the stack. Accumulate a list of stack objects.
802         var u unwinder
803         for u.init(gp, 0); u.valid(); u.next() {
804                 scanframeworker(&u.frame, &state, gcw)
805         }
806
807         // Find additional pointers that point into the stack from the heap.
808         // Currently this includes defers and panics. See also function copystack.
809
810         // Find and trace other pointers in defer records.
811         for d := gp._defer; d != nil; d = d.link {
812                 if d.fn != nil {
813                         // Scan the func value, which could be a stack allocated closure.
814                         // See issue 30453.
815                         scanblock(uintptr(unsafe.Pointer(&d.fn)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
816                 }
817                 if d.link != nil {
818                         // The link field of a stack-allocated defer record might point
819                         // to a heap-allocated defer record. Keep that heap record live.
820                         scanblock(uintptr(unsafe.Pointer(&d.link)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
821                 }
822                 // Retain defers records themselves.
823                 // Defer records might not be reachable from the G through regular heap
824                 // tracing because the defer linked list might weave between the stack and the heap.
825                 if d.heap {
826                         scanblock(uintptr(unsafe.Pointer(&d)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
827                 }
828         }
829         if gp._panic != nil {
830                 // Panics are always stack allocated.
831                 state.putPtr(uintptr(unsafe.Pointer(gp._panic)), false)
832         }
833
834         // Find and scan all reachable stack objects.
835         //
836         // The state's pointer queue prioritizes precise pointers over
837         // conservative pointers so that we'll prefer scanning stack
838         // objects precisely.
839         state.buildIndex()
840         for {
841                 p, conservative := state.getPtr()
842                 if p == 0 {
843                         break
844                 }
845                 obj := state.findObject(p)
846                 if obj == nil {
847                         continue
848                 }
849                 r := obj.r
850                 if r == nil {
851                         // We've already scanned this object.
852                         continue
853                 }
854                 obj.setRecord(nil) // Don't scan it again.
855                 if stackTraceDebug {
856                         printlock()
857                         print("  live stkobj at", hex(state.stack.lo+uintptr(obj.off)), "of size", obj.size)
858                         if conservative {
859                                 print(" (conservative)")
860                         }
861                         println()
862                         printunlock()
863                 }
864                 gcdata := r.gcdata()
865                 var s *mspan
866                 if r.useGCProg() {
867                         // This path is pretty unlikely, an object large enough
868                         // to have a GC program allocated on the stack.
869                         // We need some space to unpack the program into a straight
870                         // bitmask, which we allocate/free here.
871                         // TODO: it would be nice if there were a way to run a GC
872                         // program without having to store all its bits. We'd have
873                         // to change from a Lempel-Ziv style program to something else.
874                         // Or we can forbid putting objects on stacks if they require
875                         // a gc program (see issue 27447).
876                         s = materializeGCProg(r.ptrdata(), gcdata)
877                         gcdata = (*byte)(unsafe.Pointer(s.startAddr))
878                 }
879
880                 b := state.stack.lo + uintptr(obj.off)
881                 if conservative {
882                         scanConservative(b, r.ptrdata(), gcdata, gcw, &state)
883                 } else {
884                         scanblock(b, r.ptrdata(), gcdata, gcw, &state)
885                 }
886
887                 if s != nil {
888                         dematerializeGCProg(s)
889                 }
890         }
891
892         // Deallocate object buffers.
893         // (Pointer buffers were all deallocated in the loop above.)
894         for state.head != nil {
895                 x := state.head
896                 state.head = x.next
897                 if stackTraceDebug {
898                         for i := 0; i < x.nobj; i++ {
899                                 obj := &x.obj[i]
900                                 if obj.r == nil { // reachable
901                                         continue
902                                 }
903                                 println("  dead stkobj at", hex(gp.stack.lo+uintptr(obj.off)), "of size", obj.r.size)
904                                 // Note: not necessarily really dead - only reachable-from-ptr dead.
905                         }
906                 }
907                 x.nobj = 0
908                 putempty((*workbuf)(unsafe.Pointer(x)))
909         }
910         if state.buf != nil || state.cbuf != nil || state.freeBuf != nil {
911                 throw("remaining pointer buffers")
912         }
913         return int64(scannedSize)
914 }
915
916 // Scan a stack frame: local variables and function arguments/results.
917 //
918 //go:nowritebarrier
919 func scanframeworker(frame *stkframe, state *stackScanState, gcw *gcWork) {
920         if _DebugGC > 1 && frame.continpc != 0 {
921                 print("scanframe ", funcname(frame.fn), "\n")
922         }
923
924         isAsyncPreempt := frame.fn.valid() && frame.fn.funcID == abi.FuncID_asyncPreempt
925         isDebugCall := frame.fn.valid() && frame.fn.funcID == abi.FuncID_debugCallV2
926         if state.conservative || isAsyncPreempt || isDebugCall {
927                 if debugScanConservative {
928                         println("conservatively scanning function", funcname(frame.fn), "at PC", hex(frame.continpc))
929                 }
930
931                 // Conservatively scan the frame. Unlike the precise
932                 // case, this includes the outgoing argument space
933                 // since we may have stopped while this function was
934                 // setting up a call.
935                 //
936                 // TODO: We could narrow this down if the compiler
937                 // produced a single map per function of stack slots
938                 // and registers that ever contain a pointer.
939                 if frame.varp != 0 {
940                         size := frame.varp - frame.sp
941                         if size > 0 {
942                                 scanConservative(frame.sp, size, nil, gcw, state)
943                         }
944                 }
945
946                 // Scan arguments to this frame.
947                 if n := frame.argBytes(); n != 0 {
948                         // TODO: We could pass the entry argument map
949                         // to narrow this down further.
950                         scanConservative(frame.argp, n, nil, gcw, state)
951                 }
952
953                 if isAsyncPreempt || isDebugCall {
954                         // This function's frame contained the
955                         // registers for the asynchronously stopped
956                         // parent frame. Scan the parent
957                         // conservatively.
958                         state.conservative = true
959                 } else {
960                         // We only wanted to scan those two frames
961                         // conservatively. Clear the flag for future
962                         // frames.
963                         state.conservative = false
964                 }
965                 return
966         }
967
968         locals, args, objs := frame.getStackMap(false)
969
970         // Scan local variables if stack frame has been allocated.
971         if locals.n > 0 {
972                 size := uintptr(locals.n) * goarch.PtrSize
973                 scanblock(frame.varp-size, size, locals.bytedata, gcw, state)
974         }
975
976         // Scan arguments.
977         if args.n > 0 {
978                 scanblock(frame.argp, uintptr(args.n)*goarch.PtrSize, args.bytedata, gcw, state)
979         }
980
981         // Add all stack objects to the stack object list.
982         if frame.varp != 0 {
983                 // varp is 0 for defers, where there are no locals.
984                 // In that case, there can't be a pointer to its args, either.
985                 // (And all args would be scanned above anyway.)
986                 for i := range objs {
987                         obj := &objs[i]
988                         off := obj.off
989                         base := frame.varp // locals base pointer
990                         if off >= 0 {
991                                 base = frame.argp // arguments and return values base pointer
992                         }
993                         ptr := base + uintptr(off)
994                         if ptr < frame.sp {
995                                 // object hasn't been allocated in the frame yet.
996                                 continue
997                         }
998                         if stackTraceDebug {
999                                 println("stkobj at", hex(ptr), "of size", obj.size)
1000                         }
1001                         state.addObject(ptr, obj)
1002                 }
1003         }
1004 }
1005
1006 type gcDrainFlags int
1007
1008 const (
1009         gcDrainUntilPreempt gcDrainFlags = 1 << iota
1010         gcDrainFlushBgCredit
1011         gcDrainIdle
1012         gcDrainFractional
1013 )
1014
1015 // gcDrainMarkWorkerIdle is a wrapper for gcDrain that exists to better account
1016 // mark time in profiles.
1017 func gcDrainMarkWorkerIdle(gcw *gcWork) {
1018         gcDrain(gcw, gcDrainIdle|gcDrainUntilPreempt|gcDrainFlushBgCredit)
1019 }
1020
1021 // gcDrainMarkWorkerDedicated is a wrapper for gcDrain that exists to better account
1022 // mark time in profiles.
1023 func gcDrainMarkWorkerDedicated(gcw *gcWork, untilPreempt bool) {
1024         flags := gcDrainFlushBgCredit
1025         if untilPreempt {
1026                 flags |= gcDrainUntilPreempt
1027         }
1028         gcDrain(gcw, flags)
1029 }
1030
1031 // gcDrainMarkWorkerFractional is a wrapper for gcDrain that exists to better account
1032 // mark time in profiles.
1033 func gcDrainMarkWorkerFractional(gcw *gcWork) {
1034         gcDrain(gcw, gcDrainFractional|gcDrainUntilPreempt|gcDrainFlushBgCredit)
1035 }
1036
1037 // gcDrain scans roots and objects in work buffers, blackening grey
1038 // objects until it is unable to get more work. It may return before
1039 // GC is done; it's the caller's responsibility to balance work from
1040 // other Ps.
1041 //
1042 // If flags&gcDrainUntilPreempt != 0, gcDrain returns when g.preempt
1043 // is set.
1044 //
1045 // If flags&gcDrainIdle != 0, gcDrain returns when there is other work
1046 // to do.
1047 //
1048 // If flags&gcDrainFractional != 0, gcDrain self-preempts when
1049 // pollFractionalWorkerExit() returns true. This implies
1050 // gcDrainNoBlock.
1051 //
1052 // If flags&gcDrainFlushBgCredit != 0, gcDrain flushes scan work
1053 // credit to gcController.bgScanCredit every gcCreditSlack units of
1054 // scan work.
1055 //
1056 // gcDrain will always return if there is a pending STW.
1057 //
1058 // Disabling write barriers is necessary to ensure that after we've
1059 // confirmed that we've drained gcw, that we don't accidentally end
1060 // up flipping that condition by immediately adding work in the form
1061 // of a write barrier buffer flush.
1062 //
1063 // Don't set nowritebarrierrec because it's safe for some callees to
1064 // have write barriers enabled.
1065 //
1066 //go:nowritebarrier
1067 func gcDrain(gcw *gcWork, flags gcDrainFlags) {
1068         if !writeBarrier.enabled {
1069                 throw("gcDrain phase incorrect")
1070         }
1071
1072         gp := getg().m.curg
1073         preemptible := flags&gcDrainUntilPreempt != 0
1074         flushBgCredit := flags&gcDrainFlushBgCredit != 0
1075         idle := flags&gcDrainIdle != 0
1076
1077         initScanWork := gcw.heapScanWork
1078
1079         // checkWork is the scan work before performing the next
1080         // self-preempt check.
1081         checkWork := int64(1<<63 - 1)
1082         var check func() bool
1083         if flags&(gcDrainIdle|gcDrainFractional) != 0 {
1084                 checkWork = initScanWork + drainCheckThreshold
1085                 if idle {
1086                         check = pollWork
1087                 } else if flags&gcDrainFractional != 0 {
1088                         check = pollFractionalWorkerExit
1089                 }
1090         }
1091
1092         // Drain root marking jobs.
1093         if work.markrootNext < work.markrootJobs {
1094                 // Stop if we're preemptible or if someone wants to STW.
1095                 for !(gp.preempt && (preemptible || sched.gcwaiting.Load())) {
1096                         job := atomic.Xadd(&work.markrootNext, +1) - 1
1097                         if job >= work.markrootJobs {
1098                                 break
1099                         }
1100                         markroot(gcw, job, flushBgCredit)
1101                         if check != nil && check() {
1102                                 goto done
1103                         }
1104                 }
1105         }
1106
1107         // Drain heap marking jobs.
1108         // Stop if we're preemptible or if someone wants to STW.
1109         for !(gp.preempt && (preemptible || sched.gcwaiting.Load())) {
1110                 // Try to keep work available on the global queue. We used to
1111                 // check if there were waiting workers, but it's better to
1112                 // just keep work available than to make workers wait. In the
1113                 // worst case, we'll do O(log(_WorkbufSize)) unnecessary
1114                 // balances.
1115                 if work.full == 0 {
1116                         gcw.balance()
1117                 }
1118
1119                 b := gcw.tryGetFast()
1120                 if b == 0 {
1121                         b = gcw.tryGet()
1122                         if b == 0 {
1123                                 // Flush the write barrier
1124                                 // buffer; this may create
1125                                 // more work.
1126                                 wbBufFlush()
1127                                 b = gcw.tryGet()
1128                         }
1129                 }
1130                 if b == 0 {
1131                         // Unable to get work.
1132                         break
1133                 }
1134                 scanobject(b, gcw)
1135
1136                 // Flush background scan work credit to the global
1137                 // account if we've accumulated enough locally so
1138                 // mutator assists can draw on it.
1139                 if gcw.heapScanWork >= gcCreditSlack {
1140                         gcController.heapScanWork.Add(gcw.heapScanWork)
1141                         if flushBgCredit {
1142                                 gcFlushBgCredit(gcw.heapScanWork - initScanWork)
1143                                 initScanWork = 0
1144                         }
1145                         checkWork -= gcw.heapScanWork
1146                         gcw.heapScanWork = 0
1147
1148                         if checkWork <= 0 {
1149                                 checkWork += drainCheckThreshold
1150                                 if check != nil && check() {
1151                                         break
1152                                 }
1153                         }
1154                 }
1155         }
1156
1157 done:
1158         // Flush remaining scan work credit.
1159         if gcw.heapScanWork > 0 {
1160                 gcController.heapScanWork.Add(gcw.heapScanWork)
1161                 if flushBgCredit {
1162                         gcFlushBgCredit(gcw.heapScanWork - initScanWork)
1163                 }
1164                 gcw.heapScanWork = 0
1165         }
1166 }
1167
1168 // gcDrainN blackens grey objects until it has performed roughly
1169 // scanWork units of scan work or the G is preempted. This is
1170 // best-effort, so it may perform less work if it fails to get a work
1171 // buffer. Otherwise, it will perform at least n units of work, but
1172 // may perform more because scanning is always done in whole object
1173 // increments. It returns the amount of scan work performed.
1174 //
1175 // The caller goroutine must be in a preemptible state (e.g.,
1176 // _Gwaiting) to prevent deadlocks during stack scanning. As a
1177 // consequence, this must be called on the system stack.
1178 //
1179 //go:nowritebarrier
1180 //go:systemstack
1181 func gcDrainN(gcw *gcWork, scanWork int64) int64 {
1182         if !writeBarrier.enabled {
1183                 throw("gcDrainN phase incorrect")
1184         }
1185
1186         // There may already be scan work on the gcw, which we don't
1187         // want to claim was done by this call.
1188         workFlushed := -gcw.heapScanWork
1189
1190         // In addition to backing out because of a preemption, back out
1191         // if the GC CPU limiter is enabled.
1192         gp := getg().m.curg
1193         for !gp.preempt && !gcCPULimiter.limiting() && workFlushed+gcw.heapScanWork < scanWork {
1194                 // See gcDrain comment.
1195                 if work.full == 0 {
1196                         gcw.balance()
1197                 }
1198
1199                 b := gcw.tryGetFast()
1200                 if b == 0 {
1201                         b = gcw.tryGet()
1202                         if b == 0 {
1203                                 // Flush the write barrier buffer;
1204                                 // this may create more work.
1205                                 wbBufFlush()
1206                                 b = gcw.tryGet()
1207                         }
1208                 }
1209
1210                 if b == 0 {
1211                         // Try to do a root job.
1212                         if work.markrootNext < work.markrootJobs {
1213                                 job := atomic.Xadd(&work.markrootNext, +1) - 1
1214                                 if job < work.markrootJobs {
1215                                         workFlushed += markroot(gcw, job, false)
1216                                         continue
1217                                 }
1218                         }
1219                         // No heap or root jobs.
1220                         break
1221                 }
1222
1223                 scanobject(b, gcw)
1224
1225                 // Flush background scan work credit.
1226                 if gcw.heapScanWork >= gcCreditSlack {
1227                         gcController.heapScanWork.Add(gcw.heapScanWork)
1228                         workFlushed += gcw.heapScanWork
1229                         gcw.heapScanWork = 0
1230                 }
1231         }
1232
1233         // Unlike gcDrain, there's no need to flush remaining work
1234         // here because this never flushes to bgScanCredit and
1235         // gcw.dispose will flush any remaining work to scanWork.
1236
1237         return workFlushed + gcw.heapScanWork
1238 }
1239
1240 // scanblock scans b as scanobject would, but using an explicit
1241 // pointer bitmap instead of the heap bitmap.
1242 //
1243 // This is used to scan non-heap roots, so it does not update
1244 // gcw.bytesMarked or gcw.heapScanWork.
1245 //
1246 // If stk != nil, possible stack pointers are also reported to stk.putPtr.
1247 //
1248 //go:nowritebarrier
1249 func scanblock(b0, n0 uintptr, ptrmask *uint8, gcw *gcWork, stk *stackScanState) {
1250         // Use local copies of original parameters, so that a stack trace
1251         // due to one of the throws below shows the original block
1252         // base and extent.
1253         b := b0
1254         n := n0
1255
1256         for i := uintptr(0); i < n; {
1257                 // Find bits for the next word.
1258                 bits := uint32(*addb(ptrmask, i/(goarch.PtrSize*8)))
1259                 if bits == 0 {
1260                         i += goarch.PtrSize * 8
1261                         continue
1262                 }
1263                 for j := 0; j < 8 && i < n; j++ {
1264                         if bits&1 != 0 {
1265                                 // Same work as in scanobject; see comments there.
1266                                 p := *(*uintptr)(unsafe.Pointer(b + i))
1267                                 if p != 0 {
1268                                         if obj, span, objIndex := findObject(p, b, i); obj != 0 {
1269                                                 greyobject(obj, b, i, span, gcw, objIndex)
1270                                         } else if stk != nil && p >= stk.stack.lo && p < stk.stack.hi {
1271                                                 stk.putPtr(p, false)
1272                                         }
1273                                 }
1274                         }
1275                         bits >>= 1
1276                         i += goarch.PtrSize
1277                 }
1278         }
1279 }
1280
1281 // scanobject scans the object starting at b, adding pointers to gcw.
1282 // b must point to the beginning of a heap object or an oblet.
1283 // scanobject consults the GC bitmap for the pointer mask and the
1284 // spans for the size of the object.
1285 //
1286 //go:nowritebarrier
1287 func scanobject(b uintptr, gcw *gcWork) {
1288         // Prefetch object before we scan it.
1289         //
1290         // This will overlap fetching the beginning of the object with initial
1291         // setup before we start scanning the object.
1292         sys.Prefetch(b)
1293
1294         // Find the bits for b and the size of the object at b.
1295         //
1296         // b is either the beginning of an object, in which case this
1297         // is the size of the object to scan, or it points to an
1298         // oblet, in which case we compute the size to scan below.
1299         s := spanOfUnchecked(b)
1300         n := s.elemsize
1301         if n == 0 {
1302                 throw("scanobject n == 0")
1303         }
1304         if s.spanclass.noscan() {
1305                 // Correctness-wise this is ok, but it's inefficient
1306                 // if noscan objects reach here.
1307                 throw("scanobject of a noscan object")
1308         }
1309
1310         var tp typePointers
1311         if n > maxObletBytes {
1312                 // Large object. Break into oblets for better
1313                 // parallelism and lower latency.
1314                 if b == s.base() {
1315                         // Enqueue the other oblets to scan later.
1316                         // Some oblets may be in b's scalar tail, but
1317                         // these will be marked as "no more pointers",
1318                         // so we'll drop out immediately when we go to
1319                         // scan those.
1320                         for oblet := b + maxObletBytes; oblet < s.base()+s.elemsize; oblet += maxObletBytes {
1321                                 if !gcw.putFast(oblet) {
1322                                         gcw.put(oblet)
1323                                 }
1324                         }
1325                 }
1326
1327                 // Compute the size of the oblet. Since this object
1328                 // must be a large object, s.base() is the beginning
1329                 // of the object.
1330                 n = s.base() + s.elemsize - b
1331                 n = min(n, maxObletBytes)
1332                 if goexperiment.AllocHeaders {
1333                         tp = s.typePointersOfUnchecked(s.base())
1334                         tp = tp.fastForward(b-tp.addr, b+n)
1335                 }
1336         } else {
1337                 if goexperiment.AllocHeaders {
1338                         tp = s.typePointersOfUnchecked(b)
1339                 }
1340         }
1341
1342         var hbits heapBits
1343         if !goexperiment.AllocHeaders {
1344                 hbits = heapBitsForAddr(b, n)
1345         }
1346         var scanSize uintptr
1347         for {
1348                 var addr uintptr
1349                 if goexperiment.AllocHeaders {
1350                         if tp, addr = tp.nextFast(); addr == 0 {
1351                                 if tp, addr = tp.next(b + n); addr == 0 {
1352                                         break
1353                                 }
1354                         }
1355                 } else {
1356                         if hbits, addr = hbits.nextFast(); addr == 0 {
1357                                 if hbits, addr = hbits.next(); addr == 0 {
1358                                         break
1359                                 }
1360                         }
1361                 }
1362
1363                 // Keep track of farthest pointer we found, so we can
1364                 // update heapScanWork. TODO: is there a better metric,
1365                 // now that we can skip scalar portions pretty efficiently?
1366                 scanSize = addr - b + goarch.PtrSize
1367
1368                 // Work here is duplicated in scanblock and above.
1369                 // If you make changes here, make changes there too.
1370                 obj := *(*uintptr)(unsafe.Pointer(addr))
1371
1372                 // At this point we have extracted the next potential pointer.
1373                 // Quickly filter out nil and pointers back to the current object.
1374                 if obj != 0 && obj-b >= n {
1375                         // Test if obj points into the Go heap and, if so,
1376                         // mark the object.
1377                         //
1378                         // Note that it's possible for findObject to
1379                         // fail if obj points to a just-allocated heap
1380                         // object because of a race with growing the
1381                         // heap. In this case, we know the object was
1382                         // just allocated and hence will be marked by
1383                         // allocation itself.
1384                         if obj, span, objIndex := findObject(obj, b, addr-b); obj != 0 {
1385                                 greyobject(obj, b, addr-b, span, gcw, objIndex)
1386                         }
1387                 }
1388         }
1389         gcw.bytesMarked += uint64(n)
1390         gcw.heapScanWork += int64(scanSize)
1391 }
1392
1393 // scanConservative scans block [b, b+n) conservatively, treating any
1394 // pointer-like value in the block as a pointer.
1395 //
1396 // If ptrmask != nil, only words that are marked in ptrmask are
1397 // considered as potential pointers.
1398 //
1399 // If state != nil, it's assumed that [b, b+n) is a block in the stack
1400 // and may contain pointers to stack objects.
1401 func scanConservative(b, n uintptr, ptrmask *uint8, gcw *gcWork, state *stackScanState) {
1402         if debugScanConservative {
1403                 printlock()
1404                 print("conservatively scanning [", hex(b), ",", hex(b+n), ")\n")
1405                 hexdumpWords(b, b+n, func(p uintptr) byte {
1406                         if ptrmask != nil {
1407                                 word := (p - b) / goarch.PtrSize
1408                                 bits := *addb(ptrmask, word/8)
1409                                 if (bits>>(word%8))&1 == 0 {
1410                                         return '$'
1411                                 }
1412                         }
1413
1414                         val := *(*uintptr)(unsafe.Pointer(p))
1415                         if state != nil && state.stack.lo <= val && val < state.stack.hi {
1416                                 return '@'
1417                         }
1418
1419                         span := spanOfHeap(val)
1420                         if span == nil {
1421                                 return ' '
1422                         }
1423                         idx := span.objIndex(val)
1424                         if span.isFree(idx) {
1425                                 return ' '
1426                         }
1427                         return '*'
1428                 })
1429                 printunlock()
1430         }
1431
1432         for i := uintptr(0); i < n; i += goarch.PtrSize {
1433                 if ptrmask != nil {
1434                         word := i / goarch.PtrSize
1435                         bits := *addb(ptrmask, word/8)
1436                         if bits == 0 {
1437                                 // Skip 8 words (the loop increment will do the 8th)
1438                                 //
1439                                 // This must be the first time we've
1440                                 // seen this word of ptrmask, so i
1441                                 // must be 8-word-aligned, but check
1442                                 // our reasoning just in case.
1443                                 if i%(goarch.PtrSize*8) != 0 {
1444                                         throw("misaligned mask")
1445                                 }
1446                                 i += goarch.PtrSize*8 - goarch.PtrSize
1447                                 continue
1448                         }
1449                         if (bits>>(word%8))&1 == 0 {
1450                                 continue
1451                         }
1452                 }
1453
1454                 val := *(*uintptr)(unsafe.Pointer(b + i))
1455
1456                 // Check if val points into the stack.
1457                 if state != nil && state.stack.lo <= val && val < state.stack.hi {
1458                         // val may point to a stack object. This
1459                         // object may be dead from last cycle and
1460                         // hence may contain pointers to unallocated
1461                         // objects, but unlike heap objects we can't
1462                         // tell if it's already dead. Hence, if all
1463                         // pointers to this object are from
1464                         // conservative scanning, we have to scan it
1465                         // defensively, too.
1466                         state.putPtr(val, true)
1467                         continue
1468                 }
1469
1470                 // Check if val points to a heap span.
1471                 span := spanOfHeap(val)
1472                 if span == nil {
1473                         continue
1474                 }
1475
1476                 // Check if val points to an allocated object.
1477                 idx := span.objIndex(val)
1478                 if span.isFree(idx) {
1479                         continue
1480                 }
1481
1482                 // val points to an allocated object. Mark it.
1483                 obj := span.base() + idx*span.elemsize
1484                 greyobject(obj, b, i, span, gcw, idx)
1485         }
1486 }
1487
1488 // Shade the object if it isn't already.
1489 // The object is not nil and known to be in the heap.
1490 // Preemption must be disabled.
1491 //
1492 //go:nowritebarrier
1493 func shade(b uintptr) {
1494         if obj, span, objIndex := findObject(b, 0, 0); obj != 0 {
1495                 gcw := &getg().m.p.ptr().gcw
1496                 greyobject(obj, 0, 0, span, gcw, objIndex)
1497         }
1498 }
1499
1500 // obj is the start of an object with mark mbits.
1501 // If it isn't already marked, mark it and enqueue into gcw.
1502 // base and off are for debugging only and could be removed.
1503 //
1504 // See also wbBufFlush1, which partially duplicates this logic.
1505 //
1506 //go:nowritebarrierrec
1507 func greyobject(obj, base, off uintptr, span *mspan, gcw *gcWork, objIndex uintptr) {
1508         // obj should be start of allocation, and so must be at least pointer-aligned.
1509         if obj&(goarch.PtrSize-1) != 0 {
1510                 throw("greyobject: obj not pointer-aligned")
1511         }
1512         mbits := span.markBitsForIndex(objIndex)
1513
1514         if useCheckmark {
1515                 if setCheckmark(obj, base, off, mbits) {
1516                         // Already marked.
1517                         return
1518                 }
1519         } else {
1520                 if debug.gccheckmark > 0 && span.isFree(objIndex) {
1521                         print("runtime: marking free object ", hex(obj), " found at *(", hex(base), "+", hex(off), ")\n")
1522                         gcDumpObject("base", base, off)
1523                         gcDumpObject("obj", obj, ^uintptr(0))
1524                         getg().m.traceback = 2
1525                         throw("marking free object")
1526                 }
1527
1528                 // If marked we have nothing to do.
1529                 if mbits.isMarked() {
1530                         return
1531                 }
1532                 mbits.setMarked()
1533
1534                 // Mark span.
1535                 arena, pageIdx, pageMask := pageIndexOf(span.base())
1536                 if arena.pageMarks[pageIdx]&pageMask == 0 {
1537                         atomic.Or8(&arena.pageMarks[pageIdx], pageMask)
1538                 }
1539
1540                 // If this is a noscan object, fast-track it to black
1541                 // instead of greying it.
1542                 if span.spanclass.noscan() {
1543                         gcw.bytesMarked += uint64(span.elemsize)
1544                         return
1545                 }
1546         }
1547
1548         // We're adding obj to P's local workbuf, so it's likely
1549         // this object will be processed soon by the same P.
1550         // Even if the workbuf gets flushed, there will likely still be
1551         // some benefit on platforms with inclusive shared caches.
1552         sys.Prefetch(obj)
1553         // Queue the obj for scanning.
1554         if !gcw.putFast(obj) {
1555                 gcw.put(obj)
1556         }
1557 }
1558
1559 // gcDumpObject dumps the contents of obj for debugging and marks the
1560 // field at byte offset off in obj.
1561 func gcDumpObject(label string, obj, off uintptr) {
1562         s := spanOf(obj)
1563         print(label, "=", hex(obj))
1564         if s == nil {
1565                 print(" s=nil\n")
1566                 return
1567         }
1568         print(" s.base()=", hex(s.base()), " s.limit=", hex(s.limit), " s.spanclass=", s.spanclass, " s.elemsize=", s.elemsize, " s.state=")
1569         if state := s.state.get(); 0 <= state && int(state) < len(mSpanStateNames) {
1570                 print(mSpanStateNames[state], "\n")
1571         } else {
1572                 print("unknown(", state, ")\n")
1573         }
1574
1575         skipped := false
1576         size := s.elemsize
1577         if s.state.get() == mSpanManual && size == 0 {
1578                 // We're printing something from a stack frame. We
1579                 // don't know how big it is, so just show up to an
1580                 // including off.
1581                 size = off + goarch.PtrSize
1582         }
1583         for i := uintptr(0); i < size; i += goarch.PtrSize {
1584                 // For big objects, just print the beginning (because
1585                 // that usually hints at the object's type) and the
1586                 // fields around off.
1587                 if !(i < 128*goarch.PtrSize || off-16*goarch.PtrSize < i && i < off+16*goarch.PtrSize) {
1588                         skipped = true
1589                         continue
1590                 }
1591                 if skipped {
1592                         print(" ...\n")
1593                         skipped = false
1594                 }
1595                 print(" *(", label, "+", i, ") = ", hex(*(*uintptr)(unsafe.Pointer(obj + i))))
1596                 if i == off {
1597                         print(" <==")
1598                 }
1599                 print("\n")
1600         }
1601         if skipped {
1602                 print(" ...\n")
1603         }
1604 }
1605
1606 // gcmarknewobject marks a newly allocated object black. obj must
1607 // not contain any non-nil pointers.
1608 //
1609 // This is nosplit so it can manipulate a gcWork without preemption.
1610 //
1611 //go:nowritebarrier
1612 //go:nosplit
1613 func gcmarknewobject(span *mspan, obj, size uintptr) {
1614         if useCheckmark { // The world should be stopped so this should not happen.
1615                 throw("gcmarknewobject called while doing checkmark")
1616         }
1617
1618         // Mark object.
1619         objIndex := span.objIndex(obj)
1620         span.markBitsForIndex(objIndex).setMarked()
1621
1622         // Mark span.
1623         arena, pageIdx, pageMask := pageIndexOf(span.base())
1624         if arena.pageMarks[pageIdx]&pageMask == 0 {
1625                 atomic.Or8(&arena.pageMarks[pageIdx], pageMask)
1626         }
1627
1628         gcw := &getg().m.p.ptr().gcw
1629         gcw.bytesMarked += uint64(size)
1630 }
1631
1632 // gcMarkTinyAllocs greys all active tiny alloc blocks.
1633 //
1634 // The world must be stopped.
1635 func gcMarkTinyAllocs() {
1636         assertWorldStopped()
1637
1638         for _, p := range allp {
1639                 c := p.mcache
1640                 if c == nil || c.tiny == 0 {
1641                         continue
1642                 }
1643                 _, span, objIndex := findObject(c.tiny, 0, 0)
1644                 gcw := &p.gcw
1645                 greyobject(c.tiny, 0, 0, span, gcw, objIndex)
1646         }
1647 }