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