| 1 |
// Copyright 2009 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
// Garbage collector: marking and scanning |
| 6 |
|
| 7 |
package runtime |
| 8 |
|
| 9 |
import ( |
| 10 |
"internal/goarch" |
| 11 |
"internal/goexperiment" |
| 12 |
"runtime/internal/atomic" |
| 13 |
"runtime/internal/sys" |
| 14 |
"unsafe" |
| 15 |
) |
| 16 |
|
| 17 |
const ( |
| 18 |
fixedRootFinalizers = iota |
| 19 |
fixedRootFreeGStacks |
| 20 |
fixedRootCount |
| 21 |
|
| 22 |
// rootBlockBytes is the number of bytes to scan per data or |
| 23 |
// BSS root. |
| 24 |
rootBlockBytes = 256 << 10 |
| 25 |
|
| 26 |
// maxObletBytes is the maximum bytes of an object to scan at |
| 27 |
// once. Larger objects will be split up into "oblets" of at |
| 28 |
// most this size. Since we can scan 1–2 MB/ms, 128 KB bounds |
| 29 |
// scan preemption at ~100 µs. |
| 30 |
// |
| 31 |
// This must be > _MaxSmallSize so that the object base is the |
| 32 |
// span base. |
| 33 |
maxObletBytes = 128 << 10 |
| 34 |
|
| 35 |
// drainCheckThreshold specifies how many units of work to do |
| 36 |
// between self-preemption checks in gcDrain. Assuming a scan |
| 37 |
// rate of 1 MB/ms, this is ~100 µs. Lower values have higher |
| 38 |
// overhead in the scan loop (the scheduler check may perform |
| 39 |
// a syscall, so its overhead is nontrivial). Higher values |
| 40 |
// make the system less responsive to incoming work. |
| 41 |
drainCheckThreshold = 100000 |
| 42 |
|
| 43 |
// pagesPerSpanRoot indicates how many pages to scan from a span root |
| 44 |
// at a time. Used by special root marking. |
| 45 |
// |
| 46 |
// Higher values improve throughput by increasing locality, but |
| 47 |
// increase the minimum latency of a marking operation. |
| 48 |
// |
| 49 |
// Must be a multiple of the pageInUse bitmap element size and |
| 50 |
// must also evenly divide pagesPerArena. |
| 51 |
pagesPerSpanRoot = 512 |
| 52 |
) |
| 53 |
|
| 54 |
// gcMarkRootPrepare queues root scanning jobs (stacks, globals, and |
| 55 |
// some miscellany) and initializes scanning-related state. |
| 56 |
// |
| 57 |
// The world must be stopped. |
| 58 |
func gcMarkRootPrepare() { |
| 59 |
assertWorldStopped() |
| 60 |
|
| 61 |
work.nDataRoots = 0 |
| 62 |
|
| 63 |
// Only scan globals once per cycle; preferably concurrently. |
| 64 |
roots := gcRoots |
| 65 |
for roots != nil { |
| 66 |
work.nDataRoots++ |
| 67 |
roots = roots.next |
| 68 |
} |
| 69 |
|
| 70 |
// Scan span roots for finalizer specials. |
| 71 |
// |
| 72 |
// We depend on addfinalizer to mark objects that get |
| 73 |
// finalizers after root marking. |
| 74 |
// |
| 75 |
// We're going to scan the whole heap (that was available at the time the |
| 76 |
// mark phase started, i.e. markArenas) for in-use spans which have specials. |
| 77 |
// |
| 78 |
// Break up the work into arenas, and further into chunks. |
| 79 |
// |
| 80 |
// Snapshot allArenas as markArenas. This snapshot is safe because allArenas |
| 81 |
// is append-only. |
| 82 |
mheap_.markArenas = mheap_.allArenas[:len(mheap_.allArenas):len(mheap_.allArenas)] |
| 83 |
work.nSpanRoots = len(mheap_.markArenas) * (pagesPerArena / pagesPerSpanRoot) |
| 84 |
|
| 85 |
// Scan stacks. |
| 86 |
// |
| 87 |
// Gs may be created after this point, but it's okay that we |
| 88 |
// ignore them because they begin life without any roots, so |
| 89 |
// there's nothing to scan, and any roots they create during |
| 90 |
// the concurrent phase will be caught by the write barrier. |
| 91 |
work.stackRoots = allGsSnapshot() |
| 92 |
work.nStackRoots = len(work.stackRoots) |
| 93 |
|
| 94 |
work.markrootNext = 0 |
| 95 |
work.markrootJobs = uint32(fixedRootCount + work.nDataRoots + work.nSpanRoots + work.nStackRoots) |
| 96 |
|
| 97 |
// Calculate base indexes of each root type |
| 98 |
work.baseData = uint32(fixedRootCount) |
| 99 |
work.baseSpans = work.baseData + uint32(work.nDataRoots) |
| 100 |
work.baseStacks = work.baseSpans + uint32(work.nSpanRoots) |
| 101 |
work.baseEnd = work.baseStacks + uint32(work.nStackRoots) |
| 102 |
} |
| 103 |
|
| 104 |
// gcMarkRootCheck checks that all roots have been scanned. It is |
| 105 |
// purely for debugging. |
| 106 |
func gcMarkRootCheck() { |
| 107 |
if work.markrootNext < work.markrootJobs { |
| 108 |
print(work.markrootNext, " of ", work.markrootJobs, " markroot jobs done\n") |
| 109 |
throw("left over markroot jobs") |
| 110 |
} |
| 111 |
|
| 112 |
// Check that stacks have been scanned. |
| 113 |
// |
| 114 |
// We only check the first nStackRoots Gs that we should have scanned. |
| 115 |
// Since we don't care about newer Gs (see comment in |
| 116 |
// gcMarkRootPrepare), no locking is required. |
| 117 |
i := 0 |
| 118 |
forEachGRace(func(gp *g) { |
| 119 |
if i >= work.nStackRoots { |
| 120 |
return |
| 121 |
} |
| 122 |
|
| 123 |
if !gp.gcscandone { |
| 124 |
println("gp", gp, "goid", gp.goid, |
| 125 |
"status", readgstatus(gp), |
| 126 |
"gcscandone", gp.gcscandone) |
| 127 |
throw("scan missed a g") |
| 128 |
} |
| 129 |
|
| 130 |
i++ |
| 131 |
}) |
| 132 |
} |
| 133 |
|
| 134 |
// ptrmask for an allocation containing a single pointer. |
| 135 |
var oneptrmask = [...]uint8{1} |
| 136 |
|
| 137 |
// markroot scans the i'th root. |
| 138 |
// |
| 139 |
// Preemption must be disabled (because this uses a gcWork). |
| 140 |
// |
| 141 |
// Returns the amount of GC work credit produced by the operation. |
| 142 |
// If flushBgCredit is true, then that credit is also flushed |
| 143 |
// to the background credit pool. |
| 144 |
// |
| 145 |
// nowritebarrier is only advisory here. |
| 146 |
// |
| 147 |
//go:nowritebarrier |
| 148 |
func markroot(gcw *gcWork, i uint32, flushBgCredit bool) int64 { |
| 149 |
// Note: if you add a case here, please also update heapdump.go:dumproots. |
| 150 |
var workDone int64 |
| 151 |
var workCounter *atomic.Int64 |
| 152 |
switch { |
| 153 |
case work.baseData <= i && i < work.baseSpans: |
| 154 |
workCounter = &gcController.globalsScanWork |
| 155 |
roots := gcRoots |
| 156 |
c := work.baseData |
| 157 |
for roots != nil { |
| 158 |
if i == c { |
| 159 |
workDone += markrootBlock(roots, gcw) |
| 160 |
break |
| 161 |
} |
| 162 |
roots = roots.next |
| 163 |
c++ |
| 164 |
} |
| 165 |
|
| 166 |
case i == fixedRootFinalizers: |
| 167 |
for fb := allfin; fb != nil; fb = fb.alllink { |
| 168 |
cnt := uintptr(atomic.Load(&fb.cnt)) |
| 169 |
scanblock(uintptr(unsafe.Pointer(&fb.fin[0])), cnt*unsafe.Sizeof(fb.fin[0]), &finptrmask[0], gcw) |
| 170 |
} |
| 171 |
|
| 172 |
case i == fixedRootFreeGStacks: |
| 173 |
// FIXME: We don't do this for gccgo. |
| 174 |
|
| 175 |
case work.baseSpans <= i && i < work.baseStacks: |
| 176 |
// mark mspan.specials |
| 177 |
markrootSpans(gcw, int(i-work.baseSpans)) |
| 178 |
|
| 179 |
default: |
| 180 |
// the rest is scanning goroutine stacks |
| 181 |
workCounter = &gcController.stackScanWork |
| 182 |
if i < work.baseStacks || work.baseEnd <= i { |
| 183 |
printlock() |
| 184 |
print("runtime: markroot index ", i, " not in stack roots range [", work.baseStacks, ", ", work.baseEnd, ")\n") |
| 185 |
throw("markroot: bad index") |
| 186 |
} |
| 187 |
gp := work.stackRoots[i-work.baseStacks] |
| 188 |
|
| 189 |
// remember when we've first observed the G blocked |
| 190 |
// needed only to output in traceback |
| 191 |
status := readgstatus(gp) // We are not in a scan state |
| 192 |
if (status == _Gwaiting || status == _Gsyscall) && gp.waitsince == 0 { |
| 193 |
gp.waitsince = work.tstart |
| 194 |
} |
| 195 |
|
| 196 |
// scanstack must be done on the system stack in case |
| 197 |
// we're trying to scan our own stack. |
| 198 |
systemstack(func() { |
| 199 |
// If this is a self-scan, put the user G in |
| 200 |
// _Gwaiting to prevent self-deadlock. It may |
| 201 |
// already be in _Gwaiting if this is a mark |
| 202 |
// worker or we're in mark termination. |
| 203 |
userG := getg().m.curg |
| 204 |
selfScan := gp == userG && readgstatus(userG) == _Grunning |
| 205 |
if selfScan { |
| 206 |
casgstatus(userG, _Grunning, _Gwaiting) |
| 207 |
userG.waitreason = waitReasonGarbageCollectionScan |
| 208 |
} |
| 209 |
|
| 210 |
// TODO: suspendG blocks (and spins) until gp |
| 211 |
// stops, which may take a while for |
| 212 |
// running goroutines. Consider doing this in |
| 213 |
// two phases where the first is non-blocking: |
| 214 |
// we scan the stacks we can and ask running |
| 215 |
// goroutines to scan themselves; and the |
| 216 |
// second blocks. |
| 217 |
stopped := suspendG(gp) |
| 218 |
if stopped.dead { |
| 219 |
gp.gcscandone = true |
| 220 |
return |
| 221 |
} |
| 222 |
if gp.gcscandone { |
| 223 |
throw("g already scanned") |
| 224 |
} |
| 225 |
workDone += scanstack(gp, gcw) |
| 226 |
gp.gcscandone = true |
| 227 |
resumeG(stopped) |
| 228 |
|
| 229 |
if selfScan { |
| 230 |
casgstatus(userG, _Gwaiting, _Grunning) |
| 231 |
} |
| 232 |
}) |
| 233 |
} |
| 234 |
if goexperiment.PacerRedesign { |
| 235 |
if workCounter != nil && workDone != 0 { |
| 236 |
workCounter.Add(workDone) |
| 237 |
if flushBgCredit { |
| 238 |
gcFlushBgCredit(workDone) |
| 239 |
} |
| 240 |
} |
| 241 |
} |
| 242 |
return workDone |
| 243 |
} |
| 244 |
|
| 245 |
// markrootBlock scans one element of the list of GC roots. |
| 246 |
// |
| 247 |
// Returns the amount of work done. |
| 248 |
// |
| 249 |
//go:nowritebarrier |
| 250 |
func markrootBlock(roots *gcRootList, gcw *gcWork) int64 { |
| 251 |
var ret int64 |
| 252 |
for i := 0; i < roots.count; i++ { |
| 253 |
r := &roots.roots[i] |
| 254 |
scanblock(uintptr(r.decl), r.ptrdata, r.gcdata, gcw) |
| 255 |
ret += int64(r.ptrdata) |
| 256 |
} |
| 257 |
return ret |
| 258 |
} |
| 259 |
|
| 260 |
// markrootSpans marks roots for one shard of markArenas. |
| 261 |
// |
| 262 |
//go:nowritebarrier |
| 263 |
func markrootSpans(gcw *gcWork, shard int) { |
| 264 |
// Objects with finalizers have two GC-related invariants: |
| 265 |
// |
| 266 |
// 1) Everything reachable from the object must be marked. |
| 267 |
// This ensures that when we pass the object to its finalizer, |
| 268 |
// everything the finalizer can reach will be retained. |
| 269 |
// |
| 270 |
// 2) Finalizer specials (which are not in the garbage |
| 271 |
// collected heap) are roots. In practice, this means the fn |
| 272 |
// field must be scanned. |
| 273 |
sg := mheap_.sweepgen |
| 274 |
|
| 275 |
// Find the arena and page index into that arena for this shard. |
| 276 |
ai := mheap_.markArenas[shard/(pagesPerArena/pagesPerSpanRoot)] |
| 277 |
ha := mheap_.arenas[ai.l1()][ai.l2()] |
| 278 |
arenaPage := uint(uintptr(shard) * pagesPerSpanRoot % pagesPerArena) |
| 279 |
|
| 280 |
// Construct slice of bitmap which we'll iterate over. |
| 281 |
specialsbits := ha.pageSpecials[arenaPage/8:] |
| 282 |
specialsbits = specialsbits[:pagesPerSpanRoot/8] |
| 283 |
for i := range specialsbits { |
| 284 |
// Find set bits, which correspond to spans with specials. |
| 285 |
specials := atomic.Load8(&specialsbits[i]) |
| 286 |
if specials == 0 { |
| 287 |
continue |
| 288 |
} |
| 289 |
for j := uint(0); j < 8; j++ { |
| 290 |
if specials&(1<<j) == 0 { |
| 291 |
continue |
| 292 |
} |
| 293 |
// Find the span for this bit. |
| 294 |
// |
| 295 |
// This value is guaranteed to be non-nil because having |
| 296 |
// specials implies that the span is in-use, and since we're |
| 297 |
// currently marking we can be sure that we don't have to worry |
| 298 |
// about the span being freed and re-used. |
| 299 |
s := ha.spans[arenaPage+uint(i)*8+j] |
| 300 |
|
| 301 |
// The state must be mSpanInUse if the specials bit is set, so |
| 302 |
// sanity check that. |
| 303 |
if state := s.state.get(); state != mSpanInUse { |
| 304 |
print("s.state = ", state, "\n") |
| 305 |
throw("non in-use span found with specials bit set") |
| 306 |
} |
| 307 |
// Check that this span was swept (it may be cached or uncached). |
| 308 |
if !useCheckmark && !(s.sweepgen == sg || s.sweepgen == sg+3) { |
| 309 |
// sweepgen was updated (+2) during non-checkmark GC pass |
| 310 |
print("sweep ", s.sweepgen, " ", sg, "\n") |
| 311 |
throw("gc: unswept span") |
| 312 |
} |
| 313 |
|
| 314 |
// Lock the specials to prevent a special from being |
| 315 |
// removed from the list while we're traversing it. |
| 316 |
lock(&s.speciallock) |
| 317 |
for sp := s.specials; sp != nil; sp = sp.next { |
| 318 |
if sp.kind != _KindSpecialFinalizer { |
| 319 |
continue |
| 320 |
} |
| 321 |
// don't mark finalized object, but scan it so we |
| 322 |
// retain everything it points to. |
| 323 |
spf := (*specialfinalizer)(unsafe.Pointer(sp)) |
| 324 |
// A finalizer can be set for an inner byte of an object, find object beginning. |
| 325 |
p := s.base() + uintptr(spf.special.offset)/s.elemsize*s.elemsize |
| 326 |
|
| 327 |
// Mark everything that can be reached from |
| 328 |
// the object (but *not* the object itself or |
| 329 |
// we'll never collect it). |
| 330 |
scanobject(p, gcw) |
| 331 |
|
| 332 |
// The special itself is a root. |
| 333 |
scanblock(uintptr(unsafe.Pointer(&spf.fn)), goarch.PtrSize, &oneptrmask[0], gcw) |
| 334 |
} |
| 335 |
unlock(&s.speciallock) |
| 336 |
} |
| 337 |
} |
| 338 |
} |
| 339 |
|
| 340 |
// gcAssistAlloc performs GC work to make gp's assist debt positive. |
| 341 |
// gp must be the calling user goroutine. |
| 342 |
// |
| 343 |
// This must be called with preemption enabled. |
| 344 |
func gcAssistAlloc(gp *g) { |
| 345 |
// Don't assist in non-preemptible contexts. These are |
| 346 |
// generally fragile and won't allow the assist to block. |
| 347 |
if getg() == gp.m.g0 { |
| 348 |
return |
| 349 |
} |
| 350 |
if mp := getg().m; mp.locks > 0 || mp.preemptoff != "" { |
| 351 |
return |
| 352 |
} |
| 353 |
|
| 354 |
traced := false |
| 355 |
retry: |
| 356 |
// Compute the amount of scan work we need to do to make the |
| 357 |
// balance positive. When the required amount of work is low, |
| 358 |
// we over-assist to build up credit for future allocations |
| 359 |
// and amortize the cost of assisting. |
| 360 |
assistWorkPerByte := gcController.assistWorkPerByte.Load() |
| 361 |
assistBytesPerWork := gcController.assistBytesPerWork.Load() |
| 362 |
debtBytes := -gp.gcAssistBytes |
| 363 |
scanWork := int64(assistWorkPerByte * float64(debtBytes)) |
| 364 |
if scanWork < gcOverAssistWork { |
| 365 |
scanWork = gcOverAssistWork |
| 366 |
debtBytes = int64(assistBytesPerWork * float64(scanWork)) |
| 367 |
} |
| 368 |
|
| 369 |
// Steal as much credit as we can from the background GC's |
| 370 |
// scan credit. This is racy and may drop the background |
| 371 |
// credit below 0 if two mutators steal at the same time. This |
| 372 |
// will just cause steals to fail until credit is accumulated |
| 373 |
// again, so in the long run it doesn't really matter, but we |
| 374 |
// do have to handle the negative credit case. |
| 375 |
bgScanCredit := atomic.Loadint64(&gcController.bgScanCredit) |
| 376 |
stolen := int64(0) |
| 377 |
if bgScanCredit > 0 { |
| 378 |
if bgScanCredit < scanWork { |
| 379 |
stolen = bgScanCredit |
| 380 |
gp.gcAssistBytes += 1 + int64(assistBytesPerWork*float64(stolen)) |
| 381 |
} else { |
| 382 |
stolen = scanWork |
| 383 |
gp.gcAssistBytes += debtBytes |
| 384 |
} |
| 385 |
atomic.Xaddint64(&gcController.bgScanCredit, -stolen) |
| 386 |
|
| 387 |
scanWork -= stolen |
| 388 |
|
| 389 |
if scanWork == 0 { |
| 390 |
// We were able to steal all of the credit we |
| 391 |
// needed. |
| 392 |
if traced { |
| 393 |
traceGCMarkAssistDone() |
| 394 |
} |
| 395 |
return |
| 396 |
} |
| 397 |
} |
| 398 |
|
| 399 |
if trace.enabled && !traced { |
| 400 |
traced = true |
| 401 |
traceGCMarkAssistStart() |
| 402 |
} |
| 403 |
|
| 404 |
// Perform assist work |
| 405 |
systemstack(func() { |
| 406 |
gcAssistAlloc1(gp, scanWork) |
| 407 |
// The user stack may have moved, so this can't touch |
| 408 |
// anything on it until it returns from systemstack. |
| 409 |
}) |
| 410 |
|
| 411 |
completed := gp.param != nil |
| 412 |
gp.param = nil |
| 413 |
if completed { |
| 414 |
gcMarkDone() |
| 415 |
} |
| 416 |
|
| 417 |
if gp.gcAssistBytes < 0 { |
| 418 |
// We were unable steal enough credit or perform |
| 419 |
// enough work to pay off the assist debt. We need to |
| 420 |
// do one of these before letting the mutator allocate |
| 421 |
// more to prevent over-allocation. |
| 422 |
// |
| 423 |
// If this is because we were preempted, reschedule |
| 424 |
// and try some more. |
| 425 |
if gp.preempt { |
| 426 |
Gosched() |
| 427 |
goto retry |
| 428 |
} |
| 429 |
|
| 430 |
// Add this G to an assist queue and park. When the GC |
| 431 |
// has more background credit, it will satisfy queued |
| 432 |
// assists before flushing to the global credit pool. |
| 433 |
// |
| 434 |
// Note that this does *not* get woken up when more |
| 435 |
// work is added to the work list. The theory is that |
| 436 |
// there wasn't enough work to do anyway, so we might |
| 437 |
// as well let background marking take care of the |
| 438 |
// work that is available. |
| 439 |
if !gcParkAssist() { |
| 440 |
goto retry |
| 441 |
} |
| 442 |
|
| 443 |
// At this point either background GC has satisfied |
| 444 |
// this G's assist debt, or the GC cycle is over. |
| 445 |
} |
| 446 |
if traced { |
| 447 |
traceGCMarkAssistDone() |
| 448 |
} |
| 449 |
} |
| 450 |
|
| 451 |
// gcAssistAlloc1 is the part of gcAssistAlloc that runs on the system |
| 452 |
// stack. This is a separate function to make it easier to see that |
| 453 |
// we're not capturing anything from the user stack, since the user |
| 454 |
// stack may move while we're in this function. |
| 455 |
// |
| 456 |
// gcAssistAlloc1 indicates whether this assist completed the mark |
| 457 |
// phase by setting gp.param to non-nil. This can't be communicated on |
| 458 |
// the stack since it may move. |
| 459 |
// |
| 460 |
//go:systemstack |
| 461 |
func gcAssistAlloc1(gp *g, scanWork int64) { |
| 462 |
// Clear the flag indicating that this assist completed the |
| 463 |
// mark phase. |
| 464 |
gp.param = nil |
| 465 |
|
| 466 |
if atomic.Load(&gcBlackenEnabled) == 0 { |
| 467 |
// The gcBlackenEnabled check in malloc races with the |
| 468 |
// store that clears it but an atomic check in every malloc |
| 469 |
// would be a performance hit. |
| 470 |
// Instead we recheck it here on the non-preemptable system |
| 471 |
// stack to determine if we should perform an assist. |
| 472 |
|
| 473 |
// GC is done, so ignore any remaining debt. |
| 474 |
gp.gcAssistBytes = 0 |
| 475 |
return |
| 476 |
} |
| 477 |
// Track time spent in this assist. Since we're on the |
| 478 |
// system stack, this is non-preemptible, so we can |
| 479 |
// just measure start and end time. |
| 480 |
startTime := nanotime() |
| 481 |
|
| 482 |
decnwait := atomic.Xadd(&work.nwait, -1) |
| 483 |
if decnwait == work.nproc { |
| 484 |
println("runtime: work.nwait =", decnwait, "work.nproc=", work.nproc) |
| 485 |
throw("nwait > work.nprocs") |
| 486 |
} |
| 487 |
|
| 488 |
// gcDrainN requires the caller to be preemptible. |
| 489 |
casgstatus(gp, _Grunning, _Gwaiting) |
| 490 |
gp.waitreason = waitReasonGCAssistMarking |
| 491 |
|
| 492 |
// drain own cached work first in the hopes that it |
| 493 |
// will be more cache friendly. |
| 494 |
gcw := &getg().m.p.ptr().gcw |
| 495 |
workDone := gcDrainN(gcw, scanWork) |
| 496 |
|
| 497 |
casgstatus(gp, _Gwaiting, _Grunning) |
| 498 |
|
| 499 |
// Record that we did this much scan work. |
| 500 |
// |
| 501 |
// Back out the number of bytes of assist credit that |
| 502 |
// this scan work counts for. The "1+" is a poor man's |
| 503 |
// round-up, to ensure this adds credit even if |
| 504 |
// assistBytesPerWork is very low. |
| 505 |
assistBytesPerWork := gcController.assistBytesPerWork.Load() |
| 506 |
gp.gcAssistBytes += 1 + int64(assistBytesPerWork*float64(workDone)) |
| 507 |
|
| 508 |
// If this is the last worker and we ran out of work, |
| 509 |
// signal a completion point. |
| 510 |
incnwait := atomic.Xadd(&work.nwait, +1) |
| 511 |
if incnwait > work.nproc { |
| 512 |
println("runtime: work.nwait=", incnwait, |
| 513 |
"work.nproc=", work.nproc) |
| 514 |
throw("work.nwait > work.nproc") |
| 515 |
} |
| 516 |
|
| 517 |
if incnwait == work.nproc && !gcMarkWorkAvailable(nil) { |
| 518 |
// This has reached a background completion point. Set |
| 519 |
// gp.param to a non-nil value to indicate this. It |
| 520 |
// doesn't matter what we set it to (it just has to be |
| 521 |
// a valid pointer). |
| 522 |
gp.param = unsafe.Pointer(gp) |
| 523 |
} |
| 524 |
duration := nanotime() - startTime |
| 525 |
_p_ := gp.m.p.ptr() |
| 526 |
_p_.gcAssistTime += duration |
| 527 |
if _p_.gcAssistTime > gcAssistTimeSlack { |
| 528 |
atomic.Xaddint64(&gcController.assistTime, _p_.gcAssistTime) |
| 529 |
_p_.gcAssistTime = 0 |
| 530 |
} |
| 531 |
} |
| 532 |
|
| 533 |
// gcWakeAllAssists wakes all currently blocked assists. This is used |
| 534 |
// at the end of a GC cycle. gcBlackenEnabled must be false to prevent |
| 535 |
// new assists from going to sleep after this point. |
| 536 |
func gcWakeAllAssists() { |
| 537 |
lock(&work.assistQueue.lock) |
| 538 |
list := work.assistQueue.q.popList() |
| 539 |
injectglist(&list) |
| 540 |
unlock(&work.assistQueue.lock) |
| 541 |
} |
| 542 |
|
| 543 |
// gcParkAssist puts the current goroutine on the assist queue and parks. |
| 544 |
// |
| 545 |
// gcParkAssist reports whether the assist is now satisfied. If it |
| 546 |
// returns false, the caller must retry the assist. |
| 547 |
func gcParkAssist() bool { |
| 548 |
lock(&work.assistQueue.lock) |
| 549 |
// If the GC cycle finished while we were getting the lock, |
| 550 |
// exit the assist. The cycle can't finish while we hold the |
| 551 |
// lock. |
| 552 |
if atomic.Load(&gcBlackenEnabled) == 0 { |
| 553 |
unlock(&work.assistQueue.lock) |
| 554 |
return true |
| 555 |
} |
| 556 |
|
| 557 |
gp := getg() |
| 558 |
oldList := work.assistQueue.q |
| 559 |
work.assistQueue.q.pushBack(gp) |
| 560 |
|
| 561 |
// Recheck for background credit now that this G is in |
| 562 |
// the queue, but can still back out. This avoids a |
| 563 |
// race in case background marking has flushed more |
| 564 |
// credit since we checked above. |
| 565 |
if atomic.Loadint64(&gcController.bgScanCredit) > 0 { |
| 566 |
work.assistQueue.q = oldList |
| 567 |
if oldList.tail != 0 { |
| 568 |
oldList.tail.ptr().schedlink.set(nil) |
| 569 |
} |
| 570 |
unlock(&work.assistQueue.lock) |
| 571 |
return false |
| 572 |
} |
| 573 |
// Park. |
| 574 |
goparkunlock(&work.assistQueue.lock, waitReasonGCAssistWait, traceEvGoBlockGC, 2) |
| 575 |
return true |
| 576 |
} |
| 577 |
|
| 578 |
// gcFlushBgCredit flushes scanWork units of background scan work |
| 579 |
// credit. This first satisfies blocked assists on the |
| 580 |
// work.assistQueue and then flushes any remaining credit to |
| 581 |
// gcController.bgScanCredit. |
| 582 |
// |
| 583 |
// Write barriers are disallowed because this is used by gcDrain after |
| 584 |
// it has ensured that all work is drained and this must preserve that |
| 585 |
// condition. |
| 586 |
// |
| 587 |
//go:nowritebarrierrec |
| 588 |
func gcFlushBgCredit(scanWork int64) { |
| 589 |
if work.assistQueue.q.empty() { |
| 590 |
// Fast path; there are no blocked assists. There's a |
| 591 |
// small window here where an assist may add itself to |
| 592 |
// the blocked queue and park. If that happens, we'll |
| 593 |
// just get it on the next flush. |
| 594 |
atomic.Xaddint64(&gcController.bgScanCredit, scanWork) |
| 595 |
return |
| 596 |
} |
| 597 |
|
| 598 |
assistBytesPerWork := gcController.assistBytesPerWork.Load() |
| 599 |
scanBytes := int64(float64(scanWork) * assistBytesPerWork) |
| 600 |
|
| 601 |
lock(&work.assistQueue.lock) |
| 602 |
for !work.assistQueue.q.empty() && scanBytes > 0 { |
| 603 |
gp := work.assistQueue.q.pop() |
| 604 |
// Note that gp.gcAssistBytes is negative because gp |
| 605 |
// is in debt. Think carefully about the signs below. |
| 606 |
if scanBytes+gp.gcAssistBytes >= 0 { |
| 607 |
// Satisfy this entire assist debt. |
| 608 |
scanBytes += gp.gcAssistBytes |
| 609 |
gp.gcAssistBytes = 0 |
| 610 |
// It's important that we *not* put gp in |
| 611 |
// runnext. Otherwise, it's possible for user |
| 612 |
// code to exploit the GC worker's high |
| 613 |
// scheduler priority to get itself always run |
| 614 |
// before other goroutines and always in the |
| 615 |
// fresh quantum started by GC. |
| 616 |
ready(gp, 0, false) |
| 617 |
} else { |
| 618 |
// Partially satisfy this assist. |
| 619 |
gp.gcAssistBytes += scanBytes |
| 620 |
scanBytes = 0 |
| 621 |
// As a heuristic, we move this assist to the |
| 622 |
// back of the queue so that large assists |
| 623 |
// can't clog up the assist queue and |
| 624 |
// substantially delay small assists. |
| 625 |
work.assistQueue.q.pushBack(gp) |
| 626 |
break |
| 627 |
} |
| 628 |
} |
| 629 |
|
| 630 |
if scanBytes > 0 { |
| 631 |
// Convert from scan bytes back to work. |
| 632 |
assistWorkPerByte := gcController.assistWorkPerByte.Load() |
| 633 |
scanWork = int64(float64(scanBytes) * assistWorkPerByte) |
| 634 |
atomic.Xaddint64(&gcController.bgScanCredit, scanWork) |
| 635 |
} |
| 636 |
unlock(&work.assistQueue.lock) |
| 637 |
} |
| 638 |
|
| 639 |
// We use a C function to find the stack. |
| 640 |
// Returns whether we succesfully scanned the stack. |
| 641 |
func doscanstack(*g, *gcWork) bool |
| 642 |
|
| 643 |
func doscanstackswitch(*g, *g) |
| 644 |
|
| 645 |
// scanstack scans gp's stack, greying all pointers found on the stack. |
| 646 |
// |
| 647 |
// For goexperiment.PacerRedesign: |
| 648 |
// Returns the amount of scan work performed, but doesn't update |
| 649 |
// gcController.stackScanWork or flush any credit. Any background credit produced |
| 650 |
// by this function should be flushed by its caller. scanstack itself can't |
| 651 |
// safely flush because it may result in trying to wake up a goroutine that |
| 652 |
// was just scanned, resulting in a self-deadlock. |
| 653 |
// |
| 654 |
// scanstack will also shrink the stack if it is safe to do so. If it |
| 655 |
// is not, it schedules a stack shrink for the next synchronous safe |
| 656 |
// point. |
| 657 |
// |
| 658 |
// scanstack is marked go:systemstack because it must not be preempted |
| 659 |
// while using a workbuf. |
| 660 |
// |
| 661 |
//go:nowritebarrier |
| 662 |
//go:systemstack |
| 663 |
func scanstack(gp *g, gcw *gcWork) int64 { |
| 664 |
if readgstatus(gp)&_Gscan == 0 { |
| 665 |
print("runtime:scanstack: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", hex(readgstatus(gp)), "\n") |
| 666 |
throw("scanstack - bad status") |
| 667 |
} |
| 668 |
|
| 669 |
switch readgstatus(gp) &^ _Gscan { |
| 670 |
default: |
| 671 |
print("runtime: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n") |
| 672 |
throw("mark - bad status") |
| 673 |
case _Gdead: |
| 674 |
return 0 |
| 675 |
case _Grunning: |
| 676 |
print("runtime: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n") |
| 677 |
throw("scanstack: goroutine not stopped") |
| 678 |
case _Grunnable, _Gsyscall, _Gwaiting: |
| 679 |
// ok |
| 680 |
} |
| 681 |
|
| 682 |
// Scan the stack. |
| 683 |
if usestackmaps { |
| 684 |
g := getg() |
| 685 |
if g == gp { |
| 686 |
// Scan its own stack. |
| 687 |
doscanstack(gp, gcw) |
| 688 |
} else if gp.entry != nil { |
| 689 |
// This is a newly created g that hasn't run. No stack to scan. |
| 690 |
} else if readgstatus(gp)&^_Gscan == _Gsyscall { |
| 691 |
scanSyscallStack(gp, gcw) |
| 692 |
} else { |
| 693 |
// Scanning another g's stack. We need to switch to that g |
| 694 |
// to unwind its stack. And switch back after scan. |
| 695 |
scanstackswitch(gp, gcw) |
| 696 |
} |
| 697 |
} else { |
| 698 |
doscanstack(gp, gcw) |
| 699 |
|
| 700 |
// Conservatively scan the saved register values. |
| 701 |
scanstackblock(uintptr(unsafe.Pointer(&gp.gcregs)), unsafe.Sizeof(gp.gcregs), gcw) |
| 702 |
scanstackblock(uintptr(unsafe.Pointer(&gp.context)), unsafe.Sizeof(gp.context), gcw) |
| 703 |
} |
| 704 |
|
| 705 |
// Note: in the gc runtime scanstack also scans defer records. |
| 706 |
// This is necessary as it uses stack objects (a.k.a. stack tracing). |
| 707 |
// We don't (yet) do stack objects, and regular stack/heap scan |
| 708 |
// will take care of defer records just fine. |
| 709 |
|
| 710 |
return 0 |
| 711 |
} |
| 712 |
|
| 713 |
// scanstackswitch scans gp's stack by switching (gogo) to gp and |
| 714 |
// letting it scan its own stack, and switching back upon finish. |
| 715 |
// |
| 716 |
//go:nowritebarrier |
| 717 |
func scanstackswitch(gp *g, gcw *gcWork) { |
| 718 |
g := getg() |
| 719 |
|
| 720 |
// We are on the system stack which prevents preemption. But |
| 721 |
// we are going to switch to g stack. Lock m to block preemption. |
| 722 |
mp := acquirem() |
| 723 |
|
| 724 |
// The doscanstackswitch function will modify the current g's |
| 725 |
// context. Preserve it. |
| 726 |
// The stack scan code may call systemstack, which will modify |
| 727 |
// gp's context. Preserve it as well so we can resume gp. |
| 728 |
context := g.context |
| 729 |
stackcontext := g.stackcontext |
| 730 |
context2 := gp.context |
| 731 |
stackcontext2 := gp.stackcontext |
| 732 |
|
| 733 |
gp.scangcw = uintptr(unsafe.Pointer(gcw)) |
| 734 |
gp.scang = uintptr(unsafe.Pointer(g)) |
| 735 |
doscanstackswitch(g, gp) |
| 736 |
|
| 737 |
// Restore the contexts. |
| 738 |
g.context = context |
| 739 |
g.stackcontext = stackcontext |
| 740 |
gp.context = context2 |
| 741 |
gp.stackcontext = stackcontext2 |
| 742 |
gp.scangcw = 0 |
| 743 |
// gp.scang is already cleared in C code. |
| 744 |
|
| 745 |
releasem(mp) |
| 746 |
} |
| 747 |
|
| 748 |
// scanSyscallStack scans the stack of a goroutine blocked in a |
| 749 |
// syscall by waking it up and asking it to scan its own stack. |
| 750 |
func scanSyscallStack(gp *g, gcw *gcWork) { |
| 751 |
if gp.scanningself { |
| 752 |
// We've suspended the goroutine by setting the _Gscan bit, |
| 753 |
// so this shouldn't be possible. |
| 754 |
throw("scanSyscallStack: scanningself") |
| 755 |
} |
| 756 |
if gp.gcscandone { |
| 757 |
// We've suspended the goroutine by setting the _Gscan bit, |
| 758 |
// so this shouldn't be possible. |
| 759 |
|
| 760 |
throw("scanSyscallStack: gcscandone") |
| 761 |
} |
| 762 |
|
| 763 |
gp.gcScannedSyscallStack = false |
| 764 |
for { |
| 765 |
mp := gp.m |
| 766 |
noteclear(&mp.scannote) |
| 767 |
gp.scangcw = uintptr(unsafe.Pointer(gcw)) |
| 768 |
tgkill(getpid(), _pid_t(mp.procid), _SIGURG) |
| 769 |
// Wait for gp to scan its own stack. |
| 770 |
notesleep(&mp.scannote) |
| 771 |
if gp.gcScannedSyscallStack { |
| 772 |
return |
| 773 |
} |
| 774 |
|
| 775 |
// The signal was delivered at a bad time. Try again. |
| 776 |
osyield() |
| 777 |
} |
| 778 |
} |
| 779 |
|
| 780 |
type gcDrainFlags int |
| 781 |
|
| 782 |
const ( |
| 783 |
gcDrainUntilPreempt gcDrainFlags = 1 << iota |
| 784 |
gcDrainFlushBgCredit |
| 785 |
gcDrainIdle |
| 786 |
gcDrainFractional |
| 787 |
) |
| 788 |
|
| 789 |
// gcDrain scans roots and objects in work buffers, blackening grey |
| 790 |
// objects until it is unable to get more work. It may return before |
| 791 |
// GC is done; it's the caller's responsibility to balance work from |
| 792 |
// other Ps. |
| 793 |
// |
| 794 |
// If flags&gcDrainUntilPreempt != 0, gcDrain returns when g.preempt |
| 795 |
// is set. |
| 796 |
// |
| 797 |
// If flags&gcDrainIdle != 0, gcDrain returns when there is other work |
| 798 |
// to do. |
| 799 |
// |
| 800 |
// If flags&gcDrainFractional != 0, gcDrain self-preempts when |
| 801 |
// pollFractionalWorkerExit() returns true. This implies |
| 802 |
// gcDrainNoBlock. |
| 803 |
// |
| 804 |
// If flags&gcDrainFlushBgCredit != 0, gcDrain flushes scan work |
| 805 |
// credit to gcController.bgScanCredit every gcCreditSlack units of |
| 806 |
// scan work. |
| 807 |
// |
| 808 |
// gcDrain will always return if there is a pending STW. |
| 809 |
// |
| 810 |
//go:nowritebarrier |
| 811 |
func gcDrain(gcw *gcWork, flags gcDrainFlags) { |
| 812 |
if !writeBarrier.needed { |
| 813 |
throw("gcDrain phase incorrect") |
| 814 |
} |
| 815 |
|
| 816 |
gp := getg().m.curg |
| 817 |
preemptible := flags&gcDrainUntilPreempt != 0 |
| 818 |
flushBgCredit := flags&gcDrainFlushBgCredit != 0 |
| 819 |
idle := flags&gcDrainIdle != 0 |
| 820 |
|
| 821 |
initScanWork := gcw.heapScanWork |
| 822 |
|
| 823 |
// checkWork is the scan work before performing the next |
| 824 |
// self-preempt check. |
| 825 |
checkWork := int64(1<<63 - 1) |
| 826 |
var check func() bool |
| 827 |
if flags&(gcDrainIdle|gcDrainFractional) != 0 { |
| 828 |
checkWork = initScanWork + drainCheckThreshold |
| 829 |
if idle { |
| 830 |
check = pollWork |
| 831 |
} else if flags&gcDrainFractional != 0 { |
| 832 |
check = pollFractionalWorkerExit |
| 833 |
} |
| 834 |
} |
| 835 |
|
| 836 |
// Drain root marking jobs. |
| 837 |
if work.markrootNext < work.markrootJobs { |
| 838 |
// Stop if we're preemptible or if someone wants to STW. |
| 839 |
for !(gp.preempt && (preemptible || atomic.Load(&sched.gcwaiting) != 0)) { |
| 840 |
job := atomic.Xadd(&work.markrootNext, +1) - 1 |
| 841 |
if job >= work.markrootJobs { |
| 842 |
break |
| 843 |
} |
| 844 |
markroot(gcw, job, flushBgCredit) |
| 845 |
if check != nil && check() { |
| 846 |
goto done |
| 847 |
} |
| 848 |
} |
| 849 |
} |
| 850 |
|
| 851 |
// Drain heap marking jobs. |
| 852 |
// Stop if we're preemptible or if someone wants to STW. |
| 853 |
for !(gp.preempt && (preemptible || atomic.Load(&sched.gcwaiting) != 0)) { |
| 854 |
// Try to keep work available on the global queue. We used to |
| 855 |
// check if there were waiting workers, but it's better to |
| 856 |
// just keep work available than to make workers wait. In the |
| 857 |
// worst case, we'll do O(log(_WorkbufSize)) unnecessary |
| 858 |
// balances. |
| 859 |
if work.full == 0 { |
| 860 |
gcw.balance() |
| 861 |
} |
| 862 |
|
| 863 |
b := gcw.tryGetFast() |
| 864 |
if b == 0 { |
| 865 |
b = gcw.tryGet() |
| 866 |
if b == 0 { |
| 867 |
// Flush the write barrier |
| 868 |
// buffer; this may create |
| 869 |
// more work. |
| 870 |
wbBufFlush(nil, 0) |
| 871 |
b = gcw.tryGet() |
| 872 |
} |
| 873 |
} |
| 874 |
if b == 0 { |
| 875 |
// Unable to get work. |
| 876 |
break |
| 877 |
} |
| 878 |
scanobject(b, gcw) |
| 879 |
|
| 880 |
// Flush background scan work credit to the global |
| 881 |
// account if we've accumulated enough locally so |
| 882 |
// mutator assists can draw on it. |
| 883 |
if gcw.heapScanWork >= gcCreditSlack { |
| 884 |
gcController.heapScanWork.Add(gcw.heapScanWork) |
| 885 |
if flushBgCredit { |
| 886 |
gcFlushBgCredit(gcw.heapScanWork - initScanWork) |
| 887 |
initScanWork = 0 |
| 888 |
} |
| 889 |
checkWork -= gcw.heapScanWork |
| 890 |
gcw.heapScanWork = 0 |
| 891 |
|
| 892 |
if checkWork <= 0 { |
| 893 |
checkWork += drainCheckThreshold |
| 894 |
if check != nil && check() { |
| 895 |
break |
| 896 |
} |
| 897 |
} |
| 898 |
} |
| 899 |
} |
| 900 |
|
| 901 |
done: |
| 902 |
// Flush remaining scan work credit. |
| 903 |
if gcw.heapScanWork > 0 { |
| 904 |
gcController.heapScanWork.Add(gcw.heapScanWork) |
| 905 |
if flushBgCredit { |
| 906 |
gcFlushBgCredit(gcw.heapScanWork - initScanWork) |
| 907 |
} |
| 908 |
gcw.heapScanWork = 0 |
| 909 |
} |
| 910 |
} |
| 911 |
|
| 912 |
// gcDrainN blackens grey objects until it has performed roughly |
| 913 |
// scanWork units of scan work or the G is preempted. This is |
| 914 |
// best-effort, so it may perform less work if it fails to get a work |
| 915 |
// buffer. Otherwise, it will perform at least n units of work, but |
| 916 |
// may perform more because scanning is always done in whole object |
| 917 |
// increments. It returns the amount of scan work performed. |
| 918 |
// |
| 919 |
// The caller goroutine must be in a preemptible state (e.g., |
| 920 |
// _Gwaiting) to prevent deadlocks during stack scanning. As a |
| 921 |
// consequence, this must be called on the system stack. |
| 922 |
// |
| 923 |
//go:nowritebarrier |
| 924 |
//go:systemstack |
| 925 |
func gcDrainN(gcw *gcWork, scanWork int64) int64 { |
| 926 |
if !writeBarrier.needed { |
| 927 |
throw("gcDrainN phase incorrect") |
| 928 |
} |
| 929 |
|
| 930 |
// There may already be scan work on the gcw, which we don't |
| 931 |
// want to claim was done by this call. |
| 932 |
workFlushed := -gcw.heapScanWork |
| 933 |
|
| 934 |
gp := getg().m.curg |
| 935 |
for !gp.preempt && workFlushed+gcw.heapScanWork < scanWork { |
| 936 |
// See gcDrain comment. |
| 937 |
if work.full == 0 { |
| 938 |
gcw.balance() |
| 939 |
} |
| 940 |
|
| 941 |
b := gcw.tryGetFast() |
| 942 |
if b == 0 { |
| 943 |
b = gcw.tryGet() |
| 944 |
if b == 0 { |
| 945 |
// Flush the write barrier buffer; |
| 946 |
// this may create more work. |
| 947 |
wbBufFlush(nil, 0) |
| 948 |
b = gcw.tryGet() |
| 949 |
} |
| 950 |
} |
| 951 |
|
| 952 |
if b == 0 { |
| 953 |
// Try to do a root job. |
| 954 |
if work.markrootNext < work.markrootJobs { |
| 955 |
job := atomic.Xadd(&work.markrootNext, +1) - 1 |
| 956 |
if job < work.markrootJobs { |
| 957 |
work := markroot(gcw, job, false) |
| 958 |
if goexperiment.PacerRedesign { |
| 959 |
workFlushed += work |
| 960 |
} |
| 961 |
continue |
| 962 |
} |
| 963 |
} |
| 964 |
// No heap or root jobs. |
| 965 |
break |
| 966 |
} |
| 967 |
|
| 968 |
scanobject(b, gcw) |
| 969 |
|
| 970 |
// Flush background scan work credit. |
| 971 |
if gcw.heapScanWork >= gcCreditSlack { |
| 972 |
gcController.heapScanWork.Add(gcw.heapScanWork) |
| 973 |
workFlushed += gcw.heapScanWork |
| 974 |
gcw.heapScanWork = 0 |
| 975 |
} |
| 976 |
} |
| 977 |
|
| 978 |
// Unlike gcDrain, there's no need to flush remaining work |
| 979 |
// here because this never flushes to bgScanCredit and |
| 980 |
// gcw.dispose will flush any remaining work to scanWork. |
| 981 |
|
| 982 |
return workFlushed + gcw.heapScanWork |
| 983 |
} |
| 984 |
|
| 985 |
// scanblock scans b as scanobject would, but using an explicit |
| 986 |
// pointer bitmap instead of the heap bitmap. |
| 987 |
// |
| 988 |
// This is used to scan non-heap roots, so it does not update |
| 989 |
// gcw.bytesMarked or gcw.heapScanWork. |
| 990 |
// |
| 991 |
//go:nowritebarrier |
| 992 |
func scanblock(b0, n0 uintptr, ptrmask *uint8, gcw *gcWork) { |
| 993 |
// Use local copies of original parameters, so that a stack trace |
| 994 |
// due to one of the throws below shows the original block |
| 995 |
// base and extent. |
| 996 |
b := b0 |
| 997 |
n := n0 |
| 998 |
|
| 999 |
for i := uintptr(0); i < n; { |
| 1000 |
// Find bits for the next word. |
| 1001 |
bits := uint32(*addb(ptrmask, i/(goarch.PtrSize*8))) |
| 1002 |
if bits == 0 { |
| 1003 |
i += goarch.PtrSize * 8 |
| 1004 |
continue |
| 1005 |
} |
| 1006 |
for j := 0; j < 8 && i < n; j++ { |
| 1007 |
if bits&1 != 0 { |
| 1008 |
// Same work as in scanobject; see comments there. |
| 1009 |
p := *(*uintptr)(unsafe.Pointer(b + i)) |
| 1010 |
if p != 0 { |
| 1011 |
if obj, span, objIndex := findObject(p, b, i, false); obj != 0 { |
| 1012 |
greyobject(obj, b, i, span, gcw, objIndex, false) |
| 1013 |
} |
| 1014 |
} |
| 1015 |
} |
| 1016 |
bits >>= 1 |
| 1017 |
i += goarch.PtrSize |
| 1018 |
} |
| 1019 |
} |
| 1020 |
} |
| 1021 |
|
| 1022 |
// scanobject scans the object starting at b, adding pointers to gcw. |
| 1023 |
// b must point to the beginning of a heap object or an oblet. |
| 1024 |
// scanobject consults the GC bitmap for the pointer mask and the |
| 1025 |
// spans for the size of the object. |
| 1026 |
// |
| 1027 |
//go:nowritebarrier |
| 1028 |
func scanobject(b uintptr, gcw *gcWork) { |
| 1029 |
// Prefetch object before we scan it. |
| 1030 |
// |
| 1031 |
// This will overlap fetching the beginning of the object with initial |
| 1032 |
// setup before we start scanning the object. |
| 1033 |
sys.Prefetch(b) |
| 1034 |
|
| 1035 |
// Find the bits for b and the size of the object at b. |
| 1036 |
// |
| 1037 |
// b is either the beginning of an object, in which case this |
| 1038 |
// is the size of the object to scan, or it points to an |
| 1039 |
// oblet, in which case we compute the size to scan below. |
| 1040 |
hbits := heapBitsForAddr(b) |
| 1041 |
s := spanOfUnchecked(b) |
| 1042 |
n := s.elemsize |
| 1043 |
if n == 0 { |
| 1044 |
throw("scanobject n == 0") |
| 1045 |
} |
| 1046 |
|
| 1047 |
if n > maxObletBytes { |
| 1048 |
// Large object. Break into oblets for better |
| 1049 |
// parallelism and lower latency. |
| 1050 |
if b == s.base() { |
| 1051 |
// It's possible this is a noscan object (not |
| 1052 |
// from greyobject, but from other code |
| 1053 |
// paths), in which case we must *not* enqueue |
| 1054 |
// oblets since their bitmaps will be |
| 1055 |
// uninitialized. |
| 1056 |
if s.spanclass.noscan() { |
| 1057 |
// Bypass the whole scan. |
| 1058 |
gcw.bytesMarked += uint64(n) |
| 1059 |
return |
| 1060 |
} |
| 1061 |
|
| 1062 |
// Enqueue the other oblets to scan later. |
| 1063 |
// Some oblets may be in b's scalar tail, but |
| 1064 |
// these will be marked as "no more pointers", |
| 1065 |
// so we'll drop out immediately when we go to |
| 1066 |
// scan those. |
| 1067 |
for oblet := b + maxObletBytes; oblet < s.base()+s.elemsize; oblet += maxObletBytes { |
| 1068 |
if !gcw.putFast(oblet) { |
| 1069 |
gcw.put(oblet) |
| 1070 |
} |
| 1071 |
} |
| 1072 |
} |
| 1073 |
|
| 1074 |
// Compute the size of the oblet. Since this object |
| 1075 |
// must be a large object, s.base() is the beginning |
| 1076 |
// of the object. |
| 1077 |
n = s.base() + s.elemsize - b |
| 1078 |
if n > maxObletBytes { |
| 1079 |
n = maxObletBytes |
| 1080 |
} |
| 1081 |
} |
| 1082 |
|
| 1083 |
var i uintptr |
| 1084 |
for i = 0; i < n; i, hbits = i+goarch.PtrSize, hbits.next() { |
| 1085 |
// Load bits once. See CL 22712 and issue 16973 for discussion. |
| 1086 |
bits := hbits.bits() |
| 1087 |
if bits&bitScan == 0 { |
| 1088 |
break // no more pointers in this object |
| 1089 |
} |
| 1090 |
if bits&bitPointer == 0 { |
| 1091 |
continue // not a pointer |
| 1092 |
} |
| 1093 |
|
| 1094 |
// Work here is duplicated in scanblock and above. |
| 1095 |
// If you make changes here, make changes there too. |
| 1096 |
obj := *(*uintptr)(unsafe.Pointer(b + i)) |
| 1097 |
|
| 1098 |
// At this point we have extracted the next potential pointer. |
| 1099 |
// Quickly filter out nil and pointers back to the current object. |
| 1100 |
if obj != 0 && obj-b >= n { |
| 1101 |
// Test if obj points into the Go heap and, if so, |
| 1102 |
// mark the object. |
| 1103 |
// |
| 1104 |
// Note that it's possible for findObject to |
| 1105 |
// fail if obj points to a just-allocated heap |
| 1106 |
// object because of a race with growing the |
| 1107 |
// heap. In this case, we know the object was |
| 1108 |
// just allocated and hence will be marked by |
| 1109 |
// allocation itself. |
| 1110 |
if obj, span, objIndex := findObject(obj, b, i, false); obj != 0 { |
| 1111 |
greyobject(obj, b, i, span, gcw, objIndex, false) |
| 1112 |
} |
| 1113 |
} |
| 1114 |
} |
| 1115 |
gcw.bytesMarked += uint64(n) |
| 1116 |
gcw.heapScanWork += int64(i) |
| 1117 |
} |
| 1118 |
|
| 1119 |
//go:linkname scanstackblock |
| 1120 |
|
| 1121 |
// scanstackblock is called by the stack scanning code in C to |
| 1122 |
// actually find and mark pointers in the stack block. This is like |
| 1123 |
// scanblock, but we scan the stack conservatively, so there is no |
| 1124 |
// bitmask of pointers. |
| 1125 |
func scanstackblock(b, n uintptr, gcw *gcWork) { |
| 1126 |
if usestackmaps { |
| 1127 |
throw("scanstackblock: conservative scan but stack map is used") |
| 1128 |
} |
| 1129 |
|
| 1130 |
for i := uintptr(0); i < n; i += goarch.PtrSize { |
| 1131 |
// Same work as in scanobject; see comments there. |
| 1132 |
obj := *(*uintptr)(unsafe.Pointer(b + i)) |
| 1133 |
if obj, span, objIndex := findObject(obj, b, i, true); obj != 0 { |
| 1134 |
greyobject(obj, b, i, span, gcw, objIndex, true) |
| 1135 |
} |
| 1136 |
} |
| 1137 |
} |
| 1138 |
|
| 1139 |
// scanstackblockwithmap is like scanstackblock, but with an explicit |
| 1140 |
// pointer bitmap. This is used only when precise stack scan is enabled. |
| 1141 |
//go:linkname scanstackblockwithmap |
| 1142 |
//go:nowritebarrier |
| 1143 |
func scanstackblockwithmap(pc, b0, n0 uintptr, ptrmask *uint8, gcw *gcWork) { |
| 1144 |
// Use local copies of original parameters, so that a stack trace |
| 1145 |
// due to one of the throws below shows the original block |
| 1146 |
// base and extent. |
| 1147 |
b := b0 |
| 1148 |
n := n0 |
| 1149 |
|
| 1150 |
for i := uintptr(0); i < n; { |
| 1151 |
// Find bits for the next word. |
| 1152 |
bits := uint32(*addb(ptrmask, i/(goarch.PtrSize*8))) |
| 1153 |
if bits == 0 { |
| 1154 |
i += goarch.PtrSize * 8 |
| 1155 |
continue |
| 1156 |
} |
| 1157 |
for j := 0; j < 8 && i < n; j++ { |
| 1158 |
if bits&1 != 0 { |
| 1159 |
// Same work as in scanobject; see comments there. |
| 1160 |
obj := *(*uintptr)(unsafe.Pointer(b + i)) |
| 1161 |
if obj != 0 { |
| 1162 |
o, span, objIndex := findObject(obj, b, i, false) |
| 1163 |
if obj < minPhysPageSize || |
| 1164 |
span != nil && span.state.get() != mSpanManual && |
| 1165 |
(obj < span.base() || obj >= span.limit || span.state.get() != mSpanInUse) { |
| 1166 |
print("runtime: found in object at *(", hex(b), "+", hex(i), ") = ", hex(obj), ", pc=", hex(pc), "\n") |
| 1167 |
name, file, line, _ := funcfileline(pc, -1, false) |
| 1168 |
print(name, "\n", file, ":", line, "\n") |
| 1169 |
//gcDumpObject("object", b, i) |
| 1170 |
throw("found bad pointer in Go stack (incorrect use of unsafe or cgo?)") |
| 1171 |
} |
| 1172 |
if o != 0 { |
| 1173 |
greyobject(o, b, i, span, gcw, objIndex, false) |
| 1174 |
} |
| 1175 |
} |
| 1176 |
} |
| 1177 |
bits >>= 1 |
| 1178 |
i += goarch.PtrSize |
| 1179 |
} |
| 1180 |
} |
| 1181 |
} |
| 1182 |
|
| 1183 |
// Shade the object if it isn't already. |
| 1184 |
// The object is not nil and known to be in the heap. |
| 1185 |
// Preemption must be disabled. |
| 1186 |
//go:nowritebarrier |
| 1187 |
func shade(b uintptr) { |
| 1188 |
if obj, span, objIndex := findObject(b, 0, 0, !usestackmaps); obj != 0 { |
| 1189 |
gcw := &getg().m.p.ptr().gcw |
| 1190 |
greyobject(obj, 0, 0, span, gcw, objIndex, !usestackmaps) |
| 1191 |
} |
| 1192 |
} |
| 1193 |
|
| 1194 |
// obj is the start of an object with mark mbits. |
| 1195 |
// If it isn't already marked, mark it and enqueue into gcw. |
| 1196 |
// base and off are for debugging only and could be removed. |
| 1197 |
// |
| 1198 |
// See also wbBufFlush1, which partially duplicates this logic. |
| 1199 |
// |
| 1200 |
//go:nowritebarrierrec |
| 1201 |
func greyobject(obj, base, off uintptr, span *mspan, gcw *gcWork, objIndex uintptr, forStack bool) { |
| 1202 |
// obj should be start of allocation, and so must be at least pointer-aligned. |
| 1203 |
if obj&(goarch.PtrSize-1) != 0 { |
| 1204 |
throw("greyobject: obj not pointer-aligned") |
| 1205 |
} |
| 1206 |
mbits := span.markBitsForIndex(objIndex) |
| 1207 |
|
| 1208 |
if useCheckmark { |
| 1209 |
if setCheckmark(obj, base, off, mbits, forStack) { |
| 1210 |
// Already marked. |
| 1211 |
return |
| 1212 |
} |
| 1213 |
} else { |
| 1214 |
// Stack scanning is conservative, so we can see a |
| 1215 |
// pointer to a free object. Assume the object was |
| 1216 |
// correctly freed and we must ignore the pointer. |
| 1217 |
if forStack && span.isFree(objIndex) { |
| 1218 |
return |
| 1219 |
} |
| 1220 |
|
| 1221 |
if debug.gccheckmark > 0 && span.isFree(objIndex) { |
| 1222 |
print("runtime: marking free object ", hex(obj), " found at *(", hex(base), "+", hex(off), ")\n") |
| 1223 |
gcDumpObject("base", base, off) |
| 1224 |
gcDumpObject("obj", obj, ^uintptr(0)) |
| 1225 |
getg().m.traceback = 2 |
| 1226 |
throw("marking free object") |
| 1227 |
} |
| 1228 |
|
| 1229 |
// If marked we have nothing to do. |
| 1230 |
if mbits.isMarked() { |
| 1231 |
return |
| 1232 |
} |
| 1233 |
mbits.setMarked() |
| 1234 |
|
| 1235 |
// Mark span. |
| 1236 |
arena, pageIdx, pageMask := pageIndexOf(span.base()) |
| 1237 |
if arena.pageMarks[pageIdx]&pageMask == 0 { |
| 1238 |
atomic.Or8(&arena.pageMarks[pageIdx], pageMask) |
| 1239 |
} |
| 1240 |
|
| 1241 |
// If this is a noscan object, fast-track it to black |
| 1242 |
// instead of greying it. |
| 1243 |
if span.spanclass.noscan() { |
| 1244 |
gcw.bytesMarked += uint64(span.elemsize) |
| 1245 |
return |
| 1246 |
} |
| 1247 |
} |
| 1248 |
|
| 1249 |
// We're adding obj to P's local workbuf, so it's likely |
| 1250 |
// this object will be processed soon by the same P. |
| 1251 |
// Even if the workbuf gets flushed, there will likely still be |
| 1252 |
// some benefit on platforms with inclusive shared caches. |
| 1253 |
sys.Prefetch(obj) |
| 1254 |
// Queue the obj for scanning. |
| 1255 |
if !gcw.putFast(obj) { |
| 1256 |
gcw.put(obj) |
| 1257 |
} |
| 1258 |
} |
| 1259 |
|
| 1260 |
// gcDumpObject dumps the contents of obj for debugging and marks the |
| 1261 |
// field at byte offset off in obj. |
| 1262 |
func gcDumpObject(label string, obj, off uintptr) { |
| 1263 |
s := spanOf(obj) |
| 1264 |
print(label, "=", hex(obj)) |
| 1265 |
if s == nil { |
| 1266 |
print(" s=nil\n") |
| 1267 |
return |
| 1268 |
} |
| 1269 |
print(" s.base()=", hex(s.base()), " s.limit=", hex(s.limit), " s.spanclass=", s.spanclass, " s.elemsize=", s.elemsize, " s.state=") |
| 1270 |
if state := s.state.get(); 0 <= state && int(state) < len(mSpanStateNames) { |
| 1271 |
print(mSpanStateNames[state], "\n") |
| 1272 |
} else { |
| 1273 |
print("unknown(", state, ")\n") |
| 1274 |
} |
| 1275 |
|
| 1276 |
skipped := false |
| 1277 |
size := s.elemsize |
| 1278 |
if s.state.get() == mSpanManual && size == 0 { |
| 1279 |
// We're printing something from a stack frame. We |
| 1280 |
// don't know how big it is, so just show up to an |
| 1281 |
// including off. |
| 1282 |
size = off + goarch.PtrSize |
| 1283 |
} |
| 1284 |
for i := uintptr(0); i < size; i += goarch.PtrSize { |
| 1285 |
// For big objects, just print the beginning (because |
| 1286 |
// that usually hints at the object's type) and the |
| 1287 |
// fields around off. |
| 1288 |
if !(i < 128*goarch.PtrSize || off-16*goarch.PtrSize < i && i < off+16*goarch.PtrSize) { |
| 1289 |
skipped = true |
| 1290 |
continue |
| 1291 |
} |
| 1292 |
if skipped { |
| 1293 |
print(" ...\n") |
| 1294 |
skipped = false |
| 1295 |
} |
| 1296 |
print(" *(", label, "+", i, ") = ", hex(*(*uintptr)(unsafe.Pointer(obj + i)))) |
| 1297 |
if i == off { |
| 1298 |
print(" <==") |
| 1299 |
} |
| 1300 |
print("\n") |
| 1301 |
} |
| 1302 |
if skipped { |
| 1303 |
print(" ...\n") |
| 1304 |
} |
| 1305 |
} |
| 1306 |
|
| 1307 |
// gcmarknewobject marks a newly allocated object black. obj must |
| 1308 |
// not contain any non-nil pointers. |
| 1309 |
// |
| 1310 |
// This is nosplit so it can manipulate a gcWork without preemption. |
| 1311 |
// |
| 1312 |
//go:nowritebarrier |
| 1313 |
//go:nosplit |
| 1314 |
func gcmarknewobject(span *mspan, obj, size, scanSize uintptr) { |
| 1315 |
if useCheckmark { // The world should be stopped so this should not happen. |
| 1316 |
throw("gcmarknewobject called while doing checkmark") |
| 1317 |
} |
| 1318 |
|
| 1319 |
// Mark object. |
| 1320 |
objIndex := span.objIndex(obj) |
| 1321 |
span.markBitsForIndex(objIndex).setMarked() |
| 1322 |
|
| 1323 |
// Mark span. |
| 1324 |
arena, pageIdx, pageMask := pageIndexOf(span.base()) |
| 1325 |
if arena.pageMarks[pageIdx]&pageMask == 0 { |
| 1326 |
atomic.Or8(&arena.pageMarks[pageIdx], pageMask) |
| 1327 |
} |
| 1328 |
|
| 1329 |
gcw := &getg().m.p.ptr().gcw |
| 1330 |
gcw.bytesMarked += uint64(size) |
| 1331 |
if !goexperiment.PacerRedesign { |
| 1332 |
// The old pacer counts newly allocated memory toward |
| 1333 |
// heapScanWork because heapScan is continuously updated |
| 1334 |
// throughout the GC cycle with newly allocated memory. However, |
| 1335 |
// these objects are never actually scanned, so we need |
| 1336 |
// to account for them in heapScanWork here, "faking" their work. |
| 1337 |
// Otherwise the pacer will think it's always behind, potentially |
| 1338 |
// by a large margin. |
| 1339 |
// |
| 1340 |
// The new pacer doesn't care about this because it ceases to updated |
| 1341 |
// heapScan once a GC cycle starts, effectively snapshotting it. |
| 1342 |
gcw.heapScanWork += int64(scanSize) |
| 1343 |
} |
| 1344 |
} |
| 1345 |
|
| 1346 |
// gcMarkTinyAllocs greys all active tiny alloc blocks. |
| 1347 |
// |
| 1348 |
// The world must be stopped. |
| 1349 |
func gcMarkTinyAllocs() { |
| 1350 |
assertWorldStopped() |
| 1351 |
|
| 1352 |
for _, p := range allp { |
| 1353 |
c := p.mcache |
| 1354 |
if c == nil || c.tiny == 0 { |
| 1355 |
continue |
| 1356 |
} |
| 1357 |
_, span, objIndex := findObject(c.tiny, 0, 0, false) |
| 1358 |
gcw := &p.gcw |
| 1359 |
greyobject(c.tiny, 0, 0, span, gcw, objIndex, false) |
| 1360 |
} |
| 1361 |
} |