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