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