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