Debian Codegraph @

src/runtime/mgcmark.go

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