Source file src/runtime/runtime2.go
1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package runtime 6 7 import ( 8 "internal/abi" 9 "internal/chacha8rand" 10 "internal/goarch" 11 "internal/runtime/atomic" 12 "internal/runtime/sys" 13 "unsafe" 14 ) 15 16 // defined constants 17 const ( 18 // G status 19 // 20 // Beyond indicating the general state of a G, the G status 21 // acts like a lock on the goroutine's stack (and hence its 22 // ability to execute user code). 23 // 24 // If you add to this list, add to the list 25 // of "okay during garbage collection" status 26 // in mgcmark.go too. 27 // 28 // TODO(austin): The _Gscan bit could be much lighter-weight. 29 // For example, we could choose not to run _Gscanrunnable 30 // goroutines found in the run queue, rather than CAS-looping 31 // until they become _Grunnable. And transitions like 32 // _Gscanwaiting -> _Gscanrunnable are actually okay because 33 // they don't affect stack ownership. 34 35 // _Gidle means this goroutine was just allocated and has not 36 // yet been initialized. 37 _Gidle = iota // 0 38 39 // _Grunnable means this goroutine is on a run queue. It is 40 // not currently executing user code. The stack is not owned. 41 _Grunnable // 1 42 43 // _Grunning means this goroutine may execute user code. The 44 // stack is owned by this goroutine. It is not on a run queue. 45 // It is assigned an M (g.m is valid) and it usually has a P 46 // (g.m.p is valid), but there are small windows of time where 47 // it might not, namely upon entering and exiting _Gsyscall. 48 _Grunning // 2 49 50 // _Gsyscall means this goroutine is executing a system call. 51 // It is not executing user code. The stack is owned by this 52 // goroutine. It is not on a run queue. It is assigned an M. 53 // It may have a P attached, but it does not own it. Code 54 // executing in this state must not touch g.m.p. 55 _Gsyscall // 3 56 57 // _Gwaiting means this goroutine is blocked in the runtime. 58 // It is not executing user code. It is not on a run queue, 59 // but should be recorded somewhere (e.g., a channel wait 60 // queue) so it can be ready()d when necessary. The stack is 61 // not owned *except* that a channel operation may read or 62 // write parts of the stack under the appropriate channel 63 // lock. Otherwise, it is not safe to access the stack after a 64 // goroutine enters _Gwaiting (e.g., it may get moved). 65 _Gwaiting // 4 66 67 // _Gmoribund_unused is currently unused, but hardcoded in gdb 68 // scripts. 69 _Gmoribund_unused // 5 70 71 // _Gdead means this goroutine is currently unused. It may be 72 // just exited, on a free list, or just being initialized. It 73 // is not executing user code. It may or may not have a stack 74 // allocated. The G and its stack (if any) are owned by the M 75 // that is exiting the G or that obtained the G from the free 76 // list. 77 _Gdead // 6 78 79 // _Genqueue_unused is currently unused. 80 _Genqueue_unused // 7 81 82 // _Gcopystack means this goroutine's stack is being moved. It 83 // is not executing user code and is not on a run queue. The 84 // stack is owned by the goroutine that put it in _Gcopystack. 85 _Gcopystack // 8 86 87 // _Gpreempted means this goroutine stopped itself for a 88 // suspendG preemption. It is like _Gwaiting, but nothing is 89 // yet responsible for ready()ing it. Some suspendG must CAS 90 // the status to _Gwaiting to take responsibility for 91 // ready()ing this G. 92 _Gpreempted // 9 93 94 // _Gleaked represents a leaked goroutine caught by the GC. 95 _Gleaked // 10 96 97 // _Gdeadextra is a _Gdead goroutine that's attached to an extra M 98 // used for cgo callbacks. 99 _Gdeadextra // 11 100 101 // _Gscan combined with one of the above states other than 102 // _Grunning indicates that GC is scanning the stack. The 103 // goroutine is not executing user code and the stack is owned 104 // by the goroutine that set the _Gscan bit. 105 // 106 // _Gscanrunning is different: it is used to briefly block 107 // state transitions while GC signals the G to scan its own 108 // stack. This is otherwise like _Grunning. 109 // 110 // atomicstatus&~Gscan gives the state the goroutine will 111 // return to when the scan completes. 112 _Gscan = 0x1000 113 _Gscanrunnable = _Gscan + _Grunnable // 0x1001 114 _Gscanrunning = _Gscan + _Grunning // 0x1002 115 _Gscansyscall = _Gscan + _Gsyscall // 0x1003 116 _Gscanwaiting = _Gscan + _Gwaiting // 0x1004 117 _Gscanpreempted = _Gscan + _Gpreempted // 0x1009 118 _Gscanleaked = _Gscan + _Gleaked // 0x100a 119 _Gscandeadextra = _Gscan + _Gdeadextra // 0x100b 120 ) 121 122 const ( 123 // P status 124 125 // _Pidle means a P is not being used to run user code or the 126 // scheduler. Typically, it's on the idle P list and available 127 // to the scheduler, but it may just be transitioning between 128 // other states. 129 // 130 // The P is owned by the idle list or by whatever is 131 // transitioning its state. Its run queue is empty. 132 _Pidle = iota 133 134 // _Prunning means a P is owned by an M and is being used to 135 // run user code or the scheduler. Only the M that owns this P 136 // is allowed to change the P's status from _Prunning. The M 137 // may transition the P to _Pidle (if it has no more work to 138 // do), or _Pgcstop (to halt for the GC). The M may also hand 139 // ownership of the P off directly to another M (for example, 140 // to schedule a locked G). 141 _Prunning 142 143 // _Psyscall_unused is a now-defunct state for a P. A P is 144 // identified as "in a system call" by looking at the goroutine's 145 // state. 146 _Psyscall_unused 147 148 // _Pgcstop means a P is halted for STW and owned by the M 149 // that stopped the world. The M that stopped the world 150 // continues to use its P, even in _Pgcstop. Transitioning 151 // from _Prunning to _Pgcstop causes an M to release its P and 152 // park. 153 // 154 // The P retains its run queue and startTheWorld will restart 155 // the scheduler on Ps with non-empty run queues. 156 _Pgcstop 157 158 // _Pdead means a P is no longer used (GOMAXPROCS shrank). We 159 // reuse Ps if GOMAXPROCS increases. A dead P is mostly 160 // stripped of its resources, though a few things remain 161 // (e.g., trace buffers). 162 _Pdead 163 ) 164 165 // Mutual exclusion locks. In the uncontended case, 166 // as fast as spin locks (just a few user-level instructions), 167 // but on the contention path they sleep in the kernel. 168 // A zeroed Mutex is unlocked (no need to initialize each lock). 169 // Initialization is helpful for static lock ranking, but not required. 170 type mutex struct { 171 // Empty struct if lock ranking is disabled, otherwise includes the lock rank 172 lockRankStruct 173 // Futex-based impl treats it as uint32 key, 174 // while sema-based impl as M* waitm. 175 // Used to be a union, but unions break precise GC. 176 key uintptr 177 } 178 179 type funcval struct { 180 fn uintptr 181 // variable-size, fn-specific data here 182 } 183 184 type iface struct { 185 tab *itab 186 data unsafe.Pointer 187 } 188 189 type eface struct { 190 _type *_type 191 data unsafe.Pointer 192 } 193 194 func efaceOf(ep *any) *eface { 195 return (*eface)(unsafe.Pointer(ep)) 196 } 197 198 // The guintptr, muintptr, and puintptr are all used to bypass write barriers. 199 // It is particularly important to avoid write barriers when the current P has 200 // been released, because the GC thinks the world is stopped, and an 201 // unexpected write barrier would not be synchronized with the GC, 202 // which can lead to a half-executed write barrier that has marked the object 203 // but not queued it. If the GC skips the object and completes before the 204 // queuing can occur, it will incorrectly free the object. 205 // 206 // We tried using special assignment functions invoked only when not 207 // holding a running P, but then some updates to a particular memory 208 // word went through write barriers and some did not. This breaks the 209 // write barrier shadow checking mode, and it is also scary: better to have 210 // a word that is completely ignored by the GC than to have one for which 211 // only a few updates are ignored. 212 // 213 // Gs and Ps are always reachable via true pointers in the 214 // allgs and allp lists or (during allocation before they reach those lists) 215 // from stack variables. 216 // 217 // Ms are always reachable via true pointers either from allm or 218 // freem. Unlike Gs and Ps we do free Ms, so it's important that 219 // nothing ever hold an muintptr across a safe point. 220 221 // A guintptr holds a goroutine pointer, but typed as a uintptr 222 // to bypass write barriers. It is used in the Gobuf goroutine state 223 // and in scheduling lists that are manipulated without a P. 224 // 225 // The Gobuf.g goroutine pointer is almost always updated by assembly code. 226 // In one of the few places it is updated by Go code - func save - it must be 227 // treated as a uintptr to avoid a write barrier being emitted at a bad time. 228 // Instead of figuring out how to emit the write barriers missing in the 229 // assembly manipulation, we change the type of the field to uintptr, 230 // so that it does not require write barriers at all. 231 // 232 // Goroutine structs are published in the allg list and never freed. 233 // That will keep the goroutine structs from being collected. 234 // There is never a time that Gobuf.g's contain the only references 235 // to a goroutine: the publishing of the goroutine in allg comes first. 236 // Goroutine pointers are also kept in non-GC-visible places like TLS, 237 // so I can't see them ever moving. If we did want to start moving data 238 // in the GC, we'd need to allocate the goroutine structs from an 239 // alternate arena. Using guintptr doesn't make that problem any worse. 240 // Note that pollDesc.rg, pollDesc.wg also store g in uintptr form, 241 // so they would need to be updated too if g's start moving. 242 type guintptr uintptr 243 244 //go:nosplit 245 func (gp guintptr) ptr() *g { return (*g)(unsafe.Pointer(gp)) } 246 247 //go:nosplit 248 func (gp *guintptr) set(g *g) { *gp = guintptr(unsafe.Pointer(g)) } 249 250 //go:nosplit 251 func (gp *guintptr) cas(old, new guintptr) bool { 252 return atomic.Casuintptr((*uintptr)(unsafe.Pointer(gp)), uintptr(old), uintptr(new)) 253 } 254 255 //go:nosplit 256 func (gp *g) guintptr() guintptr { 257 return guintptr(unsafe.Pointer(gp)) 258 } 259 260 // setGNoWB performs *gp = new without a write barrier. 261 // For times when it's impractical to use a guintptr. 262 // 263 //go:nosplit 264 //go:nowritebarrier 265 func setGNoWB(gp **g, new *g) { 266 (*guintptr)(unsafe.Pointer(gp)).set(new) 267 } 268 269 type puintptr uintptr 270 271 //go:nosplit 272 func (pp puintptr) ptr() *p { return (*p)(unsafe.Pointer(pp)) } 273 274 //go:nosplit 275 func (pp *puintptr) set(p *p) { *pp = puintptr(unsafe.Pointer(p)) } 276 277 // muintptr is a *m that is not tracked by the garbage collector. 278 // 279 // Because we do free Ms, there are some additional constrains on 280 // muintptrs: 281 // 282 // 1. Never hold an muintptr locally across a safe point. 283 // 284 // 2. Any muintptr in the heap must be owned by the M itself so it can 285 // ensure it is not in use when the last true *m is released. 286 type muintptr uintptr 287 288 //go:nosplit 289 func (mp muintptr) ptr() *m { return (*m)(unsafe.Pointer(mp)) } 290 291 //go:nosplit 292 func (mp *muintptr) set(m *m) { *mp = muintptr(unsafe.Pointer(m)) } 293 294 // setMNoWB performs *mp = new without a write barrier. 295 // For times when it's impractical to use an muintptr. 296 // 297 //go:nosplit 298 //go:nowritebarrier 299 func setMNoWB(mp **m, new *m) { 300 (*muintptr)(unsafe.Pointer(mp)).set(new) 301 } 302 303 type gobuf struct { 304 // ctxt is unusual with respect to GC: it may be a 305 // heap-allocated funcval, so GC needs to track it, but it 306 // needs to be set and cleared from assembly, where it's 307 // difficult to have write barriers. However, ctxt is really a 308 // saved, live register, and we only ever exchange it between 309 // the real register and the gobuf. Hence, we treat it as a 310 // root during stack scanning, which means assembly that saves 311 // and restores it doesn't need write barriers. It's still 312 // typed as a pointer so that any other writes from Go get 313 // write barriers. 314 sp uintptr 315 pc uintptr 316 g guintptr 317 ctxt unsafe.Pointer 318 lr uintptr 319 bp uintptr // for framepointer-enabled architectures 320 } 321 322 // maybeTraceablePtr is a special pointer that is conditionally trackable 323 // by the GC. It consists of an address as a uintptr (vu) and a pointer 324 // to a data element (vp). 325 // 326 // maybeTraceablePtr values can be in one of three states: 327 // 1. Unset: vu == 0 && vp == nil 328 // 2. Untracked: vu != 0 && vp == nil 329 // 3. Tracked: vu != 0 && vp != nil 330 // 331 // Do not set fields manually. Use methods instead. 332 // Extend this type with additional methods if needed. 333 type maybeTraceablePtr struct { 334 vp unsafe.Pointer // For liveness only. 335 vu uintptr // Source of truth. 336 } 337 338 // untrack unsets the pointer but preserves the address. 339 // This is used to hide the pointer from the GC. 340 // 341 //go:nosplit 342 func (p *maybeTraceablePtr) setUntraceable() { 343 p.vp = nil 344 } 345 346 // setTraceable resets the pointer to the stored address. 347 // This is used to make the pointer visible to the GC. 348 // 349 //go:nosplit 350 func (p *maybeTraceablePtr) setTraceable() { 351 p.vp = unsafe.Pointer(p.vu) 352 } 353 354 // set sets the pointer to the data element and updates the address. 355 // 356 //go:nosplit 357 func (p *maybeTraceablePtr) set(v unsafe.Pointer) { 358 p.vp = v 359 p.vu = uintptr(v) 360 } 361 362 // get retrieves the pointer to the data element. 363 // 364 //go:nosplit 365 func (p *maybeTraceablePtr) get() unsafe.Pointer { 366 return unsafe.Pointer(p.vu) 367 } 368 369 // uintptr returns the uintptr address of the pointer. 370 // 371 //go:nosplit 372 func (p *maybeTraceablePtr) uintptr() uintptr { 373 return p.vu 374 } 375 376 // maybeTraceableChan extends conditionally trackable pointers (maybeTraceablePtr) 377 // to track hchan pointers. 378 // 379 // Do not set fields manually. Use methods instead. 380 type maybeTraceableChan struct { 381 maybeTraceablePtr 382 } 383 384 //go:nosplit 385 func (p *maybeTraceableChan) set(c *hchan) { 386 p.maybeTraceablePtr.set(unsafe.Pointer(c)) 387 } 388 389 //go:nosplit 390 func (p *maybeTraceableChan) get() *hchan { 391 return (*hchan)(p.maybeTraceablePtr.get()) 392 } 393 394 // sudog (pseudo-g) represents a g in a wait list, such as for sending/receiving 395 // on a channel. 396 // 397 // sudog is necessary because the g ↔ synchronization object relation 398 // is many-to-many. A g can be on many wait lists, so there may be 399 // many sudogs for one g; and many gs may be waiting on the same 400 // synchronization object, so there may be many sudogs for one object. 401 // 402 // sudogs are allocated from a special pool. Use acquireSudog and 403 // releaseSudog to allocate and free them. 404 type sudog struct { 405 // The following fields are protected by the hchan.lock of the 406 // channel this sudog is blocking on. shrinkstack depends on 407 // this for sudogs involved in channel ops. 408 409 g *g 410 411 next *sudog 412 prev *sudog 413 414 elem maybeTraceablePtr // data element (may point to stack) 415 416 // The following fields are never accessed concurrently. 417 // For channels, waitlink is only accessed by g. 418 // For semaphores, all fields (including the ones above) 419 // are only accessed when holding a semaRoot lock. 420 421 acquiretime int64 422 releasetime int64 423 ticket uint32 424 425 // isSelect indicates g is participating in a select, so 426 // g.selectDone must be CAS'd to win the wake-up race. 427 isSelect bool 428 429 // success indicates whether communication over channel c 430 // succeeded. It is true if the goroutine was awoken because a 431 // value was delivered over channel c, and false if awoken 432 // because c was closed. 433 success bool 434 435 // waiters is a count of semaRoot waiting list other than head of list, 436 // clamped to a uint16 to fit in unused space. 437 // Only meaningful at the head of the list. 438 // (If we wanted to be overly clever, we could store a high 16 bits 439 // in the second entry in the list.) 440 waiters uint16 441 442 parent *sudog // semaRoot binary tree 443 waitlink *sudog // g.waiting list or semaRoot 444 waittail *sudog // semaRoot 445 c maybeTraceableChan // channel 446 } 447 448 type libcall struct { 449 fn uintptr 450 n uintptr // number of parameters 451 args uintptr // parameters 452 r1 uintptr // return values 453 r2 uintptr 454 err uintptr // error number 455 } 456 457 // Stack describes a Go execution stack. 458 // The bounds of the stack are exactly [lo, hi), 459 // with no implicit data structures on either side. 460 type stack struct { 461 lo uintptr 462 hi uintptr 463 } 464 465 // heldLockInfo gives info on a held lock and the rank of that lock 466 type heldLockInfo struct { 467 lockAddr uintptr 468 rank lockRank 469 } 470 471 type g struct { 472 // Stack parameters. 473 // stack describes the actual stack memory: [stack.lo, stack.hi). 474 // stackguard0 is the stack pointer compared in the Go stack growth prologue. 475 // It is stack.lo+StackGuard normally, but can be StackPreempt to trigger a preemption. 476 // stackguard1 is the stack pointer compared in the //go:systemstack stack growth prologue. 477 // It is stack.lo+StackGuard on g0 and gsignal stacks. 478 // It is ~0 on other goroutine stacks, to trigger a call to morestackc (and crash). 479 stack stack // offset known to runtime/cgo 480 stackguard0 uintptr // offset known to cmd/internal/obj/* 481 stackguard1 uintptr // offset known to cmd/internal/obj/* 482 483 _panic *_panic // innermost panic 484 _defer *_defer // innermost defer 485 m *m // current m 486 sched gobuf 487 syscallsp uintptr // if status==Gsyscall, syscallsp = sched.sp to use during gc 488 syscallpc uintptr // if status==Gsyscall, syscallpc = sched.pc to use during gc 489 syscallbp uintptr // if status==Gsyscall, syscallbp = sched.bp to use in fpTraceback 490 stktopsp uintptr // expected sp at top of stack, to check in traceback 491 // param is a generic pointer parameter field used to pass 492 // values in particular contexts where other storage for the 493 // parameter would be difficult to find. It is currently used 494 // in four ways: 495 // 1. When a channel operation wakes up a blocked goroutine, it sets param to 496 // point to the sudog of the completed blocking operation. 497 // 2. By gcAssistAlloc1 to signal back to its caller that the goroutine completed 498 // the GC cycle. It is unsafe to do so in any other way, because the goroutine's 499 // stack may have moved in the meantime. 500 // 3. By debugCallWrap to pass parameters to a new goroutine because allocating a 501 // closure in the runtime is forbidden. 502 // 4. When a panic is recovered and control returns to the respective frame, 503 // param may point to a savedOpenDeferState. 504 param unsafe.Pointer 505 atomicstatus atomic.Uint32 506 stackLock uint32 // sigprof/scang lock; TODO: fold in to atomicstatus 507 goid uint64 508 schedlink guintptr 509 waitsince int64 // approx time when the g become blocked 510 waitreason waitReason // if status==Gwaiting 511 512 preempt bool // preemption signal, duplicates stackguard0 = stackpreempt 513 preemptStop bool // transition to _Gpreempted on preemption; otherwise, just deschedule 514 preemptShrink bool // shrink stack at synchronous safe point 515 516 // asyncSafePoint is set if g is stopped at an asynchronous 517 // safe point. This means there are frames on the stack 518 // without precise pointer information. 519 asyncSafePoint bool 520 521 paniconfault bool // panic (instead of crash) on unexpected fault address 522 gcscandone bool // g has scanned stack; protected by _Gscan bit in status 523 throwsplit bool // must not split stack 524 // activeStackChans indicates that there are unlocked channels 525 // pointing into this goroutine's stack. If true, stack 526 // copying needs to acquire channel locks to protect these 527 // areas of the stack. 528 activeStackChans bool 529 // parkingOnChan indicates that the goroutine is about to 530 // park on a chansend or chanrecv. Used to signal an unsafe point 531 // for stack shrinking. 532 parkingOnChan atomic.Bool 533 // inMarkAssist indicates whether the goroutine is in mark assist. 534 // Used by the execution tracer. 535 inMarkAssist bool 536 coroexit bool // argument to coroswitch_m 537 538 raceignore int8 // ignore race detection events 539 nocgocallback bool // whether disable callback from C 540 tracking bool // whether we're tracking this G for sched latency statistics 541 trackingSeq uint8 // used to decide whether to track this G 542 trackingStamp int64 // timestamp of when the G last started being tracked 543 runnableTime int64 // the amount of time spent runnable, cleared when running, only used when tracking 544 lockedm muintptr 545 fipsIndicator uint8 546 fipsOnlyBypass bool 547 ditWanted bool // set if g wants to be executed with DIT enabled 548 syncSafePoint bool // set if g is stopped at a synchronous safe point. 549 runningCleanups atomic.Bool 550 sig uint32 551 secret int32 // current nesting of runtime/secret.Do calls. 552 writebuf []byte 553 sigcode0 uintptr 554 sigcode1 uintptr 555 sigpc uintptr 556 parentGoid uint64 // goid of goroutine that created this goroutine 557 gopc uintptr // pc of go statement that created this goroutine 558 ancestors *[]ancestorInfo // ancestor information goroutine(s) that created this goroutine (only used if debug.tracebackancestors) 559 startpc uintptr // pc of goroutine function 560 racectx uintptr 561 waiting *sudog // sudog structures this g is waiting on (that have a valid elem ptr); in lock order 562 cgoCtxt []uintptr // cgo traceback context 563 labels unsafe.Pointer // profiler labels 564 timer *timer // cached timer for time.Sleep 565 sleepWhen int64 // when to sleep until 566 selectDone atomic.Uint32 // are we participating in a select and did someone win the race? 567 568 // goroutineProfiled indicates the status of this goroutine's stack for the 569 // current in-progress goroutine profile 570 goroutineProfiled goroutineProfileStateHolder 571 572 coroarg *coro // argument during coroutine transfers 573 bubble *synctestBubble 574 575 // xRegs stores the extended register state if this G has been 576 // asynchronously preempted. 577 xRegs xRegPerG 578 579 // Per-G tracer state. 580 trace gTraceState 581 582 // Per-G GC state 583 584 // gcAssistBytes is this G's GC assist credit in terms of 585 // bytes allocated. If this is positive, then the G has credit 586 // to allocate gcAssistBytes bytes without assisting. If this 587 // is negative, then the G must correct this by performing 588 // scan work. We track this in bytes to make it fast to update 589 // and check for debt in the malloc hot path. The assist ratio 590 // determines how this corresponds to scan work debt. 591 gcAssistBytes int64 592 593 // valgrindStackID is used to track what memory is used for stacks when a program is 594 // built with the "valgrind" build tag, otherwise it is unused. 595 valgrindStackID uintptr 596 } 597 598 // gTrackingPeriod is the number of transitions out of _Grunning between 599 // latency tracking runs. 600 const gTrackingPeriod = 8 601 602 const ( 603 // tlsSlots is the number of pointer-sized slots reserved for TLS on some platforms, 604 // like Windows. 605 tlsSlots = 6 606 tlsSize = tlsSlots * goarch.PtrSize 607 ) 608 609 // Values for m.freeWait. 610 const ( 611 freeMStack = 0 // M done, free stack and reference. 612 freeMRef = 1 // M done, free reference. 613 freeMWait = 2 // M still in use. 614 ) 615 616 type m struct { 617 g0 *g // goroutine with scheduling stack 618 morebuf gobuf // gobuf arg to morestack 619 divmod uint32 // div/mod denominator for arm - known to liblink (cmd/internal/obj/arm/obj5.go) 620 621 // Fields whose offsets are not known to debuggers. 622 623 procid uint64 // for debuggers, but offset not hard-coded 624 gsignal *g // signal-handling g 625 goSigStack gsignalStack // Go-allocated signal handling stack 626 sigmask sigset // storage for saved signal mask 627 tls [tlsSlots]uintptr // thread-local storage (for x86 extern register) 628 mstartfn func() 629 curg *g // current running goroutine 630 caughtsig guintptr // goroutine running during fatal signal 631 signalSecret uint32 // whether we have secret information in our signal stack 632 633 // p is the currently attached P for executing Go code, nil if not executing user Go code. 634 // 635 // A non-nil p implies exclusive ownership of the P, unless curg is in _Gsyscall. 636 // In _Gsyscall the scheduler may mutate this instead. The point of synchronization 637 // is the _Gscan bit on curg's status. The scheduler must arrange to prevent curg 638 // from transitioning out of _Gsyscall if it intends to mutate p. 639 p puintptr 640 641 nextp puintptr // The next P to install before executing. Implies exclusive ownership of this P. 642 oldp puintptr // The P that was attached before executing a syscall. 643 id int64 644 mallocing int32 645 throwing throwType 646 preemptoff string // if != "", keep curg running on this m 647 locks int32 648 dying int32 649 profilehz int32 650 spinning bool // m is out of work and is actively looking for work 651 blocked bool // m is blocked on a note 652 newSigstack bool // minit on C thread called sigaltstack 653 printlock int8 654 incgo bool // m is executing a cgo call 655 isextra bool // m is an extra m 656 isExtraInC bool // m is an extra m that does not have any Go frames 657 isExtraInSig bool // m is an extra m in a signal handler 658 freeWait atomic.Uint32 // Whether it is safe to free g0 and delete m (one of freeMRef, freeMStack, freeMWait) 659 needextram bool 660 g0StackAccurate bool // whether the g0 stack has accurate bounds 661 traceback uint8 662 allpSnapshot []*p // Snapshot of allp for use after dropping P in findRunnable, nil otherwise. 663 ncgocall uint64 // number of cgo calls in total 664 ncgo int32 // number of cgo calls currently in progress 665 cgoCallersUse atomic.Uint32 // if non-zero, cgoCallers in use temporarily 666 cgoCallers *cgoCallers // cgo traceback if crashing in cgo call 667 park note 668 alllink *m // on allm 669 schedlink muintptr 670 idleNode listNodeManual 671 lockedg guintptr 672 createstack [32]uintptr // stack that created this thread, it's used for StackRecord.Stack0, so it must align with it. 673 lockedExt uint32 // tracking for external LockOSThread 674 lockedInt uint32 // tracking for internal lockOSThread 675 mWaitList mWaitList // list of runtime lock waiters 676 ditEnabled bool // set if DIT is currently enabled on this M 677 678 mLockProfile mLockProfile // fields relating to runtime.lock contention 679 profStack []uintptr // used for memory/block/mutex stack traces 680 681 // wait* are used to carry arguments from gopark into park_m, because 682 // there's no stack to put them on. That is their sole purpose. 683 waitunlockf func(*g, unsafe.Pointer) bool 684 waitlock unsafe.Pointer 685 waitTraceSkip int 686 waitTraceBlockReason traceBlockReason 687 688 syscalltick uint32 689 freelink *m // on sched.freem 690 trace mTraceState 691 692 // These are here to avoid using the G stack so the stack can move during the call. 693 libcallpc uintptr // for cpu profiler 694 libcallsp uintptr 695 libcallg guintptr 696 winsyscall winlibcall // stores syscall parameters on windows 697 698 vdsoSP uintptr // SP for traceback while in VDSO call (0 if not in call) 699 vdsoPC uintptr // PC for traceback while in VDSO call 700 701 // preemptGen counts the number of completed preemption 702 // signals. This is used to detect when a preemption is 703 // requested, but fails. 704 preemptGen atomic.Uint32 705 706 // Whether this is a pending preemption signal on this M. 707 signalPending atomic.Uint32 708 709 // pcvalue lookup cache 710 pcvalueCache pcvalueCache 711 712 dlogPerM 713 714 mOS 715 716 chacha8 chacha8rand.State 717 cheaprand uint32 718 cheaprand64 uint64 719 720 // Up to 10 locks held by this m, maintained by the lock ranking code. 721 locksHeldLen int 722 locksHeld [10]heldLockInfo 723 724 // self points this M until mexit clears it to return nil. 725 self mWeakPointer 726 } 727 728 const mRedZoneSize = (16 << 3) * asanenabledBit // redZoneSize(2048) 729 730 type mPadded struct { 731 m 732 733 // Size the runtime.m structure so it fits in the 2048-byte size class, and 734 // not in the next-smallest (1792-byte) size class. That leaves the 11 low 735 // bits of muintptr values available for flags, as required by 736 // lock_spinbit.go. 737 _ [(1 - goarch.IsWasm) * (2048 - mallocHeaderSize - mRedZoneSize - unsafe.Sizeof(m{}))]byte 738 } 739 740 // mWeakPointer is a "weak" pointer to an M. A weak pointer for each M is 741 // available as m.self. Users may copy mWeakPointer arbitrarily, and get will 742 // return the M if it is still live, or nil after mexit. 743 // 744 // The zero value is treated as a nil pointer. 745 // 746 // Note that get may race with M exit. A successful get will keep the m object 747 // alive, but the M itself may be exited and thus not actually usable. 748 type mWeakPointer struct { 749 m *atomic.Pointer[m] 750 } 751 752 func newMWeakPointer(mp *m) mWeakPointer { 753 w := mWeakPointer{m: new(atomic.Pointer[m])} 754 w.m.Store(mp) 755 return w 756 } 757 758 func (w mWeakPointer) get() *m { 759 if w.m == nil { 760 return nil 761 } 762 return w.m.Load() 763 } 764 765 // clear sets the weak pointer to nil. It cannot be used on zero value 766 // mWeakPointers. 767 func (w mWeakPointer) clear() { 768 w.m.Store(nil) 769 } 770 771 type p struct { 772 id int32 773 status uint32 // one of pidle/prunning/... 774 link puintptr 775 schedtick uint32 // incremented on every scheduler call 776 syscalltick uint32 // incremented on every system call 777 sysmontick sysmontick // last tick observed by sysmon 778 m muintptr // back-link to associated m (nil if idle) 779 mcache *mcache 780 pcache pageCache 781 raceprocctx uintptr 782 783 // oldm is the previous m this p ran on. 784 // 785 // We are not assosciated with this m, so we have no control over its 786 // lifecycle. This value is an m.self object which points to the m 787 // until the m exits. 788 // 789 // Note that this m may be idle, running, or exiting. It should only be 790 // used with mgetSpecific, which will take ownership of the m only if 791 // it is idle. 792 oldm mWeakPointer 793 794 deferpool []*_defer // pool of available defer structs (see panic.go) 795 deferpoolbuf [32]*_defer 796 797 // Cache of goroutine ids, amortizes accesses to runtime·sched.goidgen. 798 goidcache uint64 799 goidcacheend uint64 800 801 // Queue of runnable goroutines. Accessed without lock. 802 runqhead uint32 803 runqtail uint32 804 runq [256]guintptr 805 // runnext, if non-nil, is a runnable G that was ready'd by 806 // the current G and should be run next instead of what's in 807 // runq if there's time remaining in the running G's time 808 // slice. It will inherit the time left in the current time 809 // slice. If a set of goroutines is locked in a 810 // communicate-and-wait pattern, this schedules that set as a 811 // unit and eliminates the (potentially large) scheduling 812 // latency that otherwise arises from adding the ready'd 813 // goroutines to the end of the run queue. 814 // 815 // Note that while other P's may atomically CAS this to zero, 816 // only the owner P can CAS it to a valid G. 817 runnext guintptr 818 819 // Available G's (status == Gdead) 820 gFree gList 821 822 sudogcache []*sudog 823 sudogbuf [128]*sudog 824 825 // Cache of mspan objects from the heap. 826 mspancache struct { 827 // We need an explicit length here because this field is used 828 // in allocation codepaths where write barriers are not allowed, 829 // and eliminating the write barrier/keeping it eliminated from 830 // slice updates is tricky, more so than just managing the length 831 // ourselves. 832 len int 833 buf [128]*mspan 834 } 835 836 // Cache of a single pinner object to reduce allocations from repeated 837 // pinner creation. 838 pinnerCache *pinner 839 840 trace pTraceState 841 842 palloc persistentAlloc // per-P to avoid mutex 843 844 // Per-P GC state 845 gcAssistTime int64 // Nanoseconds in assistAlloc 846 gcFractionalMarkTime atomic.Int64 // Nanoseconds in fractional mark worker 847 848 // limiterEvent tracks events for the GC CPU limiter. 849 limiterEvent limiterEvent 850 851 // gcMarkWorkerMode is the mode for the next mark worker to run in. 852 // That is, this is used to communicate with the worker goroutine 853 // selected for immediate execution by 854 // gcController.findRunnableGCWorker. When scheduling other goroutines, 855 // this field must be set to gcMarkWorkerNotWorker. 856 gcMarkWorkerMode gcMarkWorkerMode 857 // gcMarkWorkerStartTime is the nanotime() at which the most recent 858 // mark worker started. 859 gcMarkWorkerStartTime int64 860 861 // nextGCMarkWorker is the next mark worker to run. This may be set 862 // during start-the-world to assign a worker to this P. The P runs this 863 // worker on the next call to gcController.findRunnableGCWorker. If the 864 // P runs something else or stops, it must release this worker via 865 // gcController.releaseNextGCMarkWorker. 866 // 867 // See comment in gcBgMarkWorker about the lifetime of 868 // gcBgMarkWorkerNode. 869 // 870 // Only accessed by this P or during STW. 871 nextGCMarkWorker *gcBgMarkWorkerNode 872 873 // gcw is this P's GC work buffer cache. The work buffer is 874 // filled by write barriers, drained by mutator assists, and 875 // disposed on certain GC state transitions. 876 gcw gcWork 877 878 // wbBuf is this P's GC write barrier buffer. 879 // 880 // TODO: Consider caching this in the running G. 881 wbBuf wbBuf 882 883 runSafePointFn uint32 // if 1, run sched.safePointFn at next safe point 884 885 // statsSeq is a counter indicating whether this P is currently 886 // writing any stats. Its value is even when not, odd when it is. 887 statsSeq atomic.Uint32 888 889 // Timer heap. 890 timers timers 891 892 // Cleanups. 893 cleanups *cleanupBlock 894 cleanupsQueued uint64 // monotonic count of cleanups queued by this P 895 896 // maxStackScanDelta accumulates the amount of stack space held by 897 // live goroutines (i.e. those eligible for stack scanning). 898 // Flushed to gcController.maxStackScan once maxStackScanSlack 899 // or -maxStackScanSlack is reached. 900 maxStackScanDelta int64 901 902 // gc-time statistics about current goroutines 903 // Note that this differs from maxStackScan in that this 904 // accumulates the actual stack observed to be used at GC time (hi - sp), 905 // not an instantaneous measure of the total stack size that might need 906 // to be scanned (hi - lo). 907 scannedStackSize uint64 // stack size of goroutines scanned by this P 908 scannedStacks uint64 // number of goroutines scanned by this P 909 910 // preempt is set to indicate that this P should be enter the 911 // scheduler ASAP (regardless of what G is running on it). 912 preempt bool 913 914 // gcStopTime is the nanotime timestamp that this P last entered _Pgcstop. 915 gcStopTime int64 916 917 // goroutinesCreated is the total count of goroutines created by this P. 918 goroutinesCreated uint64 919 920 // xRegs is the per-P extended register state used by asynchronous 921 // preemption. This is an empty struct on platforms that don't use extended 922 // register state. 923 xRegs xRegPerP 924 925 // Padding is no longer needed. False sharing is now not a worry because p is large enough 926 // that its size class is an integer multiple of the cache line size (for any of our architectures). 927 } 928 929 type schedt struct { 930 goidgen atomic.Uint64 931 lastpoll atomic.Int64 // time of last network poll, 0 if currently polling 932 pollUntil atomic.Int64 // time to which current poll is sleeping 933 pollingNet atomic.Int32 // 1 if some P doing non-blocking network poll 934 935 lock mutex 936 937 // When increasing nmidle, nmidlelocked, nmsys, or nmfreed, be 938 // sure to call checkdead(). 939 940 midle listHeadManual // idle m's waiting for work 941 nmidle int32 // number of idle m's waiting for work 942 nmidlelocked int32 // number of locked m's waiting for work 943 mnext int64 // number of m's that have been created and next M ID 944 maxmcount int32 // maximum number of m's allowed (or die) 945 nmsys int32 // number of system m's not counted for deadlock 946 nmfreed int64 // cumulative number of freed m's 947 948 ngsys atomic.Int32 // number of system goroutines 949 nGsyscallNoP atomic.Int32 // number of goroutines in syscalls without a P but whose M is not isExtraInC 950 951 pidle puintptr // idle p's 952 npidle atomic.Int32 953 nmspinning atomic.Int32 // See "Worker thread parking/unparking" comment in proc.go. 954 needspinning atomic.Uint32 // See "Delicate dance" comment in proc.go. Boolean. Must hold sched.lock to set to 1. 955 956 // Global runnable queue. 957 runq gQueue 958 959 // disable controls selective disabling of the scheduler. 960 // 961 // Use schedEnableUser to control this. 962 // 963 // disable is protected by sched.lock. 964 disable struct { 965 // user disables scheduling of user goroutines. 966 user bool 967 runnable gQueue // pending runnable Gs 968 } 969 970 // Global cache of dead G's. 971 gFree struct { 972 lock mutex 973 stack gList // Gs with stacks 974 noStack gList // Gs without stacks 975 } 976 977 // Central cache of sudog structs. 978 sudoglock mutex 979 sudogcache *sudog 980 981 // Central pool of available defer structs. 982 deferlock mutex 983 deferpool *_defer 984 985 // freem is the list of m's waiting to be freed when their 986 // m.exited is set. Linked through m.freelink. 987 freem *m 988 989 gcwaiting atomic.Bool // gc is waiting to run 990 stopwait int32 991 stopnote note 992 sysmonwait atomic.Bool 993 sysmonnote note 994 995 // safePointFn should be called on each P at the next GC 996 // safepoint if p.runSafePointFn is set. 997 safePointFn func(*p) 998 safePointWait int32 999 safePointNote note 1000 1001 profilehz int32 // cpu profiling rate 1002 1003 procresizetime int64 // nanotime() of last change to gomaxprocs 1004 totaltime int64 // ∫gomaxprocs dt up to procresizetime 1005 1006 customGOMAXPROCS bool // GOMAXPROCS was manually set from the environment or runtime.GOMAXPROCS 1007 1008 // sysmonlock protects sysmon's actions on the runtime. 1009 // 1010 // Acquire and hold this mutex to block sysmon from interacting 1011 // with the rest of the runtime. 1012 sysmonlock mutex 1013 1014 // timeToRun is a distribution of scheduling latencies, defined 1015 // as the sum of time a G spends in the _Grunnable state before 1016 // it transitions to _Grunning. 1017 timeToRun timeHistogram 1018 1019 // idleTime is the total CPU time Ps have "spent" idle. 1020 // 1021 // Reset on each GC cycle. 1022 idleTime atomic.Int64 1023 1024 // totalMutexWaitTime is the sum of time goroutines have spent in _Gwaiting 1025 // with a waitreason of the form waitReasonSync{RW,}Mutex{R,}Lock. 1026 totalMutexWaitTime atomic.Int64 1027 1028 // stwStoppingTimeGC/Other are distributions of stop-the-world stopping 1029 // latencies, defined as the time taken by stopTheWorldWithSema to get 1030 // all Ps to stop. stwStoppingTimeGC covers all GC-related STWs, 1031 // stwStoppingTimeOther covers the others. 1032 stwStoppingTimeGC timeHistogram 1033 stwStoppingTimeOther timeHistogram 1034 1035 // stwTotalTimeGC/Other are distributions of stop-the-world total 1036 // latencies, defined as the total time from stopTheWorldWithSema to 1037 // startTheWorldWithSema. This is a superset of 1038 // stwStoppingTimeGC/Other. stwTotalTimeGC covers all GC-related STWs, 1039 // stwTotalTimeOther covers the others. 1040 stwTotalTimeGC timeHistogram 1041 stwTotalTimeOther timeHistogram 1042 1043 // totalRuntimeLockWaitTime (plus the value of lockWaitTime on each M in 1044 // allm) is the sum of time goroutines have spent in _Grunnable and with an 1045 // M, but waiting for locks within the runtime. This field stores the value 1046 // for Ms that have exited. 1047 totalRuntimeLockWaitTime atomic.Int64 1048 1049 // goroutinesCreated (plus the value of goroutinesCreated on each P in allp) 1050 // is the sum of all goroutines created by the program. 1051 goroutinesCreated atomic.Uint64 1052 } 1053 1054 // Values for the flags field of a sigTabT. 1055 const ( 1056 _SigNotify = 1 << iota // let signal.Notify have signal, even if from kernel 1057 _SigKill // if signal.Notify doesn't take it, exit quietly 1058 _SigThrow // if signal.Notify doesn't take it, exit loudly 1059 _SigPanic // if the signal is from the kernel, panic 1060 _SigDefault // if the signal isn't explicitly requested, don't monitor it 1061 _SigGoExit // cause all runtime procs to exit (only used on Plan 9). 1062 _SigSetStack // Don't explicitly install handler, but add SA_ONSTACK to existing libc handler 1063 _SigUnblock // always unblock; see blockableSig 1064 _SigIgn // _SIG_DFL action is to ignore the signal 1065 ) 1066 1067 // Layout of in-memory per-function information prepared by linker 1068 // See https://golang.org/s/go12symtab. 1069 // Keep in sync with linker (../cmd/link/internal/ld/pcln.go:/pclntab) 1070 // and with package debug/gosym and with symtab.go in package runtime. 1071 type _func struct { 1072 sys.NotInHeap // Only in static data 1073 1074 entryOff uint32 // start pc, as offset from moduledata.text 1075 nameOff int32 // function name, as index into moduledata.funcnametab. 1076 1077 args int32 // in/out args size 1078 deferreturn uint32 // offset of start of a deferreturn call instruction from entry, if any. 1079 1080 pcsp uint32 1081 pcfile uint32 1082 pcln uint32 1083 npcdata uint32 1084 cuOffset uint32 // runtime.cutab offset of this function's CU 1085 startLine int32 // line number of start of function (func keyword/TEXT directive) 1086 funcID abi.FuncID // set for certain special runtime functions 1087 flag abi.FuncFlag 1088 _ [1]byte // pad 1089 nfuncdata uint8 // must be last, must end on a uint32-aligned boundary 1090 1091 // The end of the struct is followed immediately by two variable-length 1092 // arrays that reference the pcdata and funcdata locations for this 1093 // function. 1094 1095 // pcdata contains the offset into moduledata.pctab for the start of 1096 // that index's table. e.g., 1097 // &moduledata.pctab[_func.pcdata[_PCDATA_UnsafePoint]] is the start of 1098 // the unsafe point table. 1099 // 1100 // An offset of 0 indicates that there is no table. 1101 // 1102 // pcdata [npcdata]uint32 1103 1104 // funcdata contains the offset past moduledata.gofunc which contains a 1105 // pointer to that index's funcdata. e.g., 1106 // *(moduledata.gofunc + _func.funcdata[_FUNCDATA_ArgsPointerMaps]) is 1107 // the argument pointer map. 1108 // 1109 // An offset of ^uint32(0) indicates that there is no entry. 1110 // 1111 // funcdata [nfuncdata]uint32 1112 } 1113 1114 // Pseudo-Func that is returned for PCs that occur in inlined code. 1115 // A *Func can be either a *_func or a *funcinl, and they are distinguished 1116 // by the first uintptr. 1117 // 1118 // TODO(austin): Can we merge this with inlinedCall? 1119 type funcinl struct { 1120 ones uint32 // set to ^0 to distinguish from _func 1121 entry uintptr // entry of the real (the "outermost") frame 1122 name string 1123 file string 1124 line int32 1125 startLine int32 1126 } 1127 1128 type itab = abi.ITab 1129 1130 // Lock-free stack node. 1131 // Also known to export_test.go. 1132 type lfnode struct { 1133 next uint64 1134 pushcnt uintptr 1135 } 1136 1137 type forcegcstate struct { 1138 lock mutex 1139 g *g 1140 idle atomic.Bool 1141 } 1142 1143 // A _defer holds an entry on the list of deferred calls. 1144 // If you add a field here, add code to clear it in deferProcStack. 1145 // This struct must match the code in cmd/compile/internal/ssagen/ssa.go:deferstruct 1146 // and cmd/compile/internal/ssagen/ssa.go:(*state).call. 1147 // Some defers will be allocated on the stack and some on the heap. 1148 // All defers are logically part of the stack, so write barriers to 1149 // initialize them are not required. All defers must be manually scanned, 1150 // and for heap defers, marked. 1151 type _defer struct { 1152 heap bool 1153 rangefunc bool // true for rangefunc list 1154 sp uintptr // sp at time of defer 1155 pc uintptr // pc at time of defer 1156 fn func() // can be nil for open-coded defers 1157 link *_defer // next defer on G; can point to either heap or stack! 1158 1159 // If rangefunc is true, *head is the head of the atomic linked list 1160 // during a range-over-func execution. 1161 head *atomic.Pointer[_defer] 1162 } 1163 1164 // A _panic holds information about an active panic. 1165 // 1166 // A _panic value must only ever live on the stack. 1167 // 1168 // The gopanicFP and link fields are stack pointers, but don't need special 1169 // handling during stack growth: because they are pointer-typed and 1170 // _panic values only live on the stack, regular stack pointer 1171 // adjustment takes care of them. 1172 type _panic struct { 1173 arg any // argument to panic 1174 link *_panic // link to earlier panic 1175 1176 // startPC and startSP track where _panic.start was called. 1177 startPC uintptr 1178 startSP unsafe.Pointer 1179 1180 // The current stack frame that we're running deferred calls for. 1181 sp unsafe.Pointer 1182 lr uintptr 1183 fp unsafe.Pointer 1184 1185 // retpc stores the PC where the panic should jump back to, if the 1186 // function last returned by _panic.next() recovers the panic. 1187 retpc uintptr 1188 1189 // Extra state for handling open-coded defers. 1190 deferBitsPtr *uint8 1191 slotsPtr unsafe.Pointer 1192 1193 recovered bool // whether this panic has been recovered 1194 repanicked bool // whether this panic repanicked 1195 goexit bool 1196 deferreturn bool 1197 1198 gopanicFP unsafe.Pointer // frame pointer of the gopanic frame 1199 } 1200 1201 // savedOpenDeferState tracks the extra state from _panic that's 1202 // necessary for deferreturn to pick up where gopanic left off, 1203 // without needing to unwind the stack. 1204 type savedOpenDeferState struct { 1205 retpc uintptr 1206 deferBitsOffset uintptr 1207 slotsOffset uintptr 1208 } 1209 1210 // ancestorInfo records details of where a goroutine was started. 1211 type ancestorInfo struct { 1212 pcs []uintptr // pcs from the stack of this goroutine 1213 goid uint64 // goroutine id of this goroutine; original goroutine possibly dead 1214 gopc uintptr // pc of go statement that created this goroutine 1215 } 1216 1217 // A waitReason explains why a goroutine has been stopped. 1218 // See gopark. Do not re-use waitReasons, add new ones. 1219 type waitReason uint8 1220 1221 const ( 1222 waitReasonZero waitReason = iota // "" 1223 waitReasonGCAssistMarking // "GC assist marking" 1224 waitReasonIOWait // "IO wait" 1225 waitReasonDumpingHeap // "dumping heap" 1226 waitReasonGarbageCollection // "garbage collection" 1227 waitReasonGarbageCollectionScan // "garbage collection scan" 1228 waitReasonPanicWait // "panicwait" 1229 waitReasonGCAssistWait // "GC assist wait" 1230 waitReasonGCSweepWait // "GC sweep wait" 1231 waitReasonGCScavengeWait // "GC scavenge wait" 1232 waitReasonFinalizerWait // "finalizer wait" 1233 waitReasonForceGCIdle // "force gc (idle)" 1234 waitReasonUpdateGOMAXPROCSIdle // "GOMAXPROCS updater (idle)" 1235 waitReasonSemacquire // "semacquire" 1236 waitReasonSleep // "sleep" 1237 waitReasonChanReceiveNilChan // "chan receive (nil chan)" 1238 waitReasonChanSendNilChan // "chan send (nil chan)" 1239 waitReasonSelectNoCases // "select (no cases)" 1240 waitReasonSelect // "select" 1241 waitReasonChanReceive // "chan receive" 1242 waitReasonChanSend // "chan send" 1243 waitReasonSyncCondWait // "sync.Cond.Wait" 1244 waitReasonSyncMutexLock // "sync.Mutex.Lock" 1245 waitReasonSyncRWMutexRLock // "sync.RWMutex.RLock" 1246 waitReasonSyncRWMutexLock // "sync.RWMutex.Lock" 1247 waitReasonSyncWaitGroupWait // "sync.WaitGroup.Wait" 1248 waitReasonTraceReaderBlocked // "trace reader (blocked)" 1249 waitReasonWaitForGCCycle // "wait for GC cycle" 1250 waitReasonGCWorkerIdle // "GC worker (idle)" 1251 waitReasonGCWorkerActive // "GC worker (active)" 1252 waitReasonPreempted // "preempted" 1253 waitReasonDebugCall // "debug call" 1254 waitReasonGCMarkTermination // "GC mark termination" 1255 waitReasonStoppingTheWorld // "stopping the world" 1256 waitReasonFlushProcCaches // "flushing proc caches" 1257 waitReasonTraceGoroutineStatus // "trace goroutine status" 1258 waitReasonTraceProcStatus // "trace proc status" 1259 waitReasonPageTraceFlush // "page trace flush" 1260 waitReasonCoroutine // "coroutine" 1261 waitReasonGCWeakToStrongWait // "GC weak to strong wait" 1262 waitReasonSynctestRun // "synctest.Run" 1263 waitReasonSynctestWait // "synctest.Wait" 1264 waitReasonSynctestChanReceive // "chan receive (durable)" 1265 waitReasonSynctestChanSend // "chan send (durable)" 1266 waitReasonSynctestSelect // "select (durable)" 1267 waitReasonSynctestWaitGroupWait // "sync.WaitGroup.Wait (durable)" 1268 waitReasonCleanupWait // "cleanup wait" 1269 ) 1270 1271 var waitReasonStrings = [...]string{ 1272 waitReasonZero: "", 1273 waitReasonGCAssistMarking: "GC assist marking", 1274 waitReasonIOWait: "IO wait", 1275 waitReasonChanReceiveNilChan: "chan receive (nil chan)", 1276 waitReasonChanSendNilChan: "chan send (nil chan)", 1277 waitReasonDumpingHeap: "dumping heap", 1278 waitReasonGarbageCollection: "garbage collection", 1279 waitReasonGarbageCollectionScan: "garbage collection scan", 1280 waitReasonPanicWait: "panicwait", 1281 waitReasonSelect: "select", 1282 waitReasonSelectNoCases: "select (no cases)", 1283 waitReasonGCAssistWait: "GC assist wait", 1284 waitReasonGCSweepWait: "GC sweep wait", 1285 waitReasonGCScavengeWait: "GC scavenge wait", 1286 waitReasonChanReceive: "chan receive", 1287 waitReasonChanSend: "chan send", 1288 waitReasonFinalizerWait: "finalizer wait", 1289 waitReasonForceGCIdle: "force gc (idle)", 1290 waitReasonUpdateGOMAXPROCSIdle: "GOMAXPROCS updater (idle)", 1291 waitReasonSemacquire: "semacquire", 1292 waitReasonSleep: "sleep", 1293 waitReasonSyncCondWait: "sync.Cond.Wait", 1294 waitReasonSyncMutexLock: "sync.Mutex.Lock", 1295 waitReasonSyncRWMutexRLock: "sync.RWMutex.RLock", 1296 waitReasonSyncRWMutexLock: "sync.RWMutex.Lock", 1297 waitReasonSyncWaitGroupWait: "sync.WaitGroup.Wait", 1298 waitReasonTraceReaderBlocked: "trace reader (blocked)", 1299 waitReasonWaitForGCCycle: "wait for GC cycle", 1300 waitReasonGCWorkerIdle: "GC worker (idle)", 1301 waitReasonGCWorkerActive: "GC worker (active)", 1302 waitReasonPreempted: "preempted", 1303 waitReasonDebugCall: "debug call", 1304 waitReasonGCMarkTermination: "GC mark termination", 1305 waitReasonStoppingTheWorld: "stopping the world", 1306 waitReasonFlushProcCaches: "flushing proc caches", 1307 waitReasonTraceGoroutineStatus: "trace goroutine status", 1308 waitReasonTraceProcStatus: "trace proc status", 1309 waitReasonPageTraceFlush: "page trace flush", 1310 waitReasonCoroutine: "coroutine", 1311 waitReasonGCWeakToStrongWait: "GC weak to strong wait", 1312 waitReasonSynctestRun: "synctest.Run", 1313 waitReasonSynctestWait: "synctest.Wait", 1314 waitReasonSynctestChanReceive: "chan receive (durable)", 1315 waitReasonSynctestChanSend: "chan send (durable)", 1316 waitReasonSynctestSelect: "select (durable)", 1317 waitReasonSynctestWaitGroupWait: "sync.WaitGroup.Wait (durable)", 1318 waitReasonCleanupWait: "cleanup wait", 1319 } 1320 1321 func (w waitReason) String() string { 1322 if w < 0 || w >= waitReason(len(waitReasonStrings)) { 1323 return "unknown wait reason" 1324 } 1325 return waitReasonStrings[w] 1326 } 1327 1328 // isMutexWait returns true if the goroutine is blocked because of 1329 // sync.Mutex.Lock or sync.RWMutex.[R]Lock. 1330 // 1331 //go:nosplit 1332 func (w waitReason) isMutexWait() bool { 1333 return w == waitReasonSyncMutexLock || 1334 w == waitReasonSyncRWMutexRLock || 1335 w == waitReasonSyncRWMutexLock 1336 } 1337 1338 // isSyncWait returns true if the goroutine is blocked because of 1339 // sync library primitive operations. 1340 // 1341 //go:nosplit 1342 func (w waitReason) isSyncWait() bool { 1343 return waitReasonSyncCondWait <= w && w <= waitReasonSyncWaitGroupWait 1344 } 1345 1346 // isChanWait is true if the goroutine is blocked because of non-nil 1347 // channel operations or a select statement with at least one case. 1348 // 1349 //go:nosplit 1350 func (w waitReason) isChanWait() bool { 1351 return w == waitReasonSelect || 1352 w == waitReasonChanReceive || 1353 w == waitReasonChanSend 1354 } 1355 1356 func (w waitReason) isWaitingForSuspendG() bool { 1357 return isWaitingForSuspendG[w] 1358 } 1359 1360 // isWaitingForSuspendG indicates that a goroutine is only entering _Gwaiting and 1361 // setting a waitReason because it needs to be able to let the suspendG 1362 // (used by the GC and the execution tracer) take ownership of its stack. 1363 // The G is always actually executing on the system stack in these cases. 1364 // 1365 // TODO(mknyszek): Consider replacing this with a new dedicated G status. 1366 var isWaitingForSuspendG = [len(waitReasonStrings)]bool{ 1367 waitReasonStoppingTheWorld: true, 1368 waitReasonGCMarkTermination: true, 1369 waitReasonGarbageCollection: true, 1370 waitReasonGarbageCollectionScan: true, 1371 waitReasonTraceGoroutineStatus: true, 1372 waitReasonTraceProcStatus: true, 1373 waitReasonPageTraceFlush: true, 1374 waitReasonGCAssistMarking: true, 1375 waitReasonGCWorkerActive: true, 1376 waitReasonFlushProcCaches: true, 1377 } 1378 1379 func (w waitReason) isIdleInSynctest() bool { 1380 return isIdleInSynctest[w] 1381 } 1382 1383 // isIdleInSynctest indicates that a goroutine is considered idle by synctest.Wait. 1384 var isIdleInSynctest = [len(waitReasonStrings)]bool{ 1385 waitReasonChanReceiveNilChan: true, 1386 waitReasonChanSendNilChan: true, 1387 waitReasonSelectNoCases: true, 1388 waitReasonSleep: true, 1389 waitReasonSyncCondWait: true, 1390 waitReasonSynctestWaitGroupWait: true, 1391 waitReasonCoroutine: true, 1392 waitReasonSynctestRun: true, 1393 waitReasonSynctestWait: true, 1394 waitReasonSynctestChanReceive: true, 1395 waitReasonSynctestChanSend: true, 1396 waitReasonSynctestSelect: true, 1397 } 1398 1399 var ( 1400 // Linked-list of all Ms. Written under sched.lock, read atomically. 1401 allm *m 1402 1403 gomaxprocs int32 1404 numCPUStartup int32 1405 forcegc forcegcstate 1406 sched schedt 1407 newprocs int32 1408 ) 1409 1410 var ( 1411 // allpLock protects P-less reads and size changes of allp, idlepMask, 1412 // and timerpMask, and all writes to allp. 1413 allpLock mutex 1414 1415 // len(allp) == gomaxprocs; may change at safe points, otherwise 1416 // immutable. 1417 allp []*p 1418 1419 // Bitmask of Ps in _Pidle list, one bit per P. Reads and writes must 1420 // be atomic. Length may change at safe points. 1421 // 1422 // Each P must update only its own bit. In order to maintain 1423 // consistency, a P going idle must set the idle mask simultaneously with 1424 // updates to the idle P list under the sched.lock, otherwise a racing 1425 // pidleget may clear the mask before pidleput sets the mask, 1426 // corrupting the bitmap. 1427 // 1428 // N.B., procresize takes ownership of all Ps in stopTheWorldWithSema. 1429 idlepMask pMask 1430 1431 // Bitmask of Ps that may have a timer, one bit per P. Reads and writes 1432 // must be atomic. Length may change at safe points. 1433 // 1434 // Ideally, the timer mask would be kept immediately consistent on any timer 1435 // operations. Unfortunately, updating a shared global data structure in the 1436 // timer hot path adds too much overhead in applications frequently switching 1437 // between no timers and some timers. 1438 // 1439 // As a compromise, the timer mask is updated only on pidleget / pidleput. A 1440 // running P (returned by pidleget) may add a timer at any time, so its mask 1441 // must be set. An idle P (passed to pidleput) cannot add new timers while 1442 // idle, so if it has no timers at that time, its mask may be cleared. 1443 // 1444 // Thus, we get the following effects on timer-stealing in findRunnable: 1445 // 1446 // - Idle Ps with no timers when they go idle are never checked in findRunnable 1447 // (for work- or timer-stealing; this is the ideal case). 1448 // - Running Ps must always be checked. 1449 // - Idle Ps whose timers are stolen must continue to be checked until they run 1450 // again, even after timer expiration. 1451 // 1452 // When the P starts running again, the mask should be set, as a timer may be 1453 // added at any time. 1454 // 1455 // TODO(prattmic): Additional targeted updates may improve the above cases. 1456 // e.g., updating the mask when stealing a timer. 1457 timerpMask pMask 1458 ) 1459 1460 // goarmsoftfp is used by runtime/cgo assembly. 1461 // 1462 //go:linkname goarmsoftfp 1463 1464 var ( 1465 // Pool of GC parked background workers. Entries are type 1466 // *gcBgMarkWorkerNode. 1467 gcBgMarkWorkerPool lfstack 1468 1469 // Total number of gcBgMarkWorker goroutines. Protected by worldsema. 1470 gcBgMarkWorkerCount int32 1471 1472 // Information about what cpu features are available. 1473 // Packages outside the runtime should not use these 1474 // as they are not an external api. 1475 // Set on startup in asm_{386,amd64}.s 1476 processorVersionInfo uint32 1477 isIntel bool 1478 ) 1479 1480 // set by cmd/link on arm systems 1481 // accessed using linkname by internal/runtime/atomic. 1482 // 1483 // goarm should be an internal detail, 1484 // but widely used packages access it using linkname. 1485 // Notable members of the hall of shame include: 1486 // - github.com/creativeprojects/go-selfupdate 1487 // 1488 // Do not remove or change the type signature. 1489 // See go.dev/issue/67401. 1490 // 1491 //go:linkname goarm 1492 var ( 1493 goarm uint8 1494 goarmsoftfp uint8 1495 ) 1496 1497 // Set by the linker so the runtime can determine the buildmode. 1498 var ( 1499 islibrary bool // -buildmode=c-shared 1500 isarchive bool // -buildmode=c-archive 1501 ) 1502 1503 // Must agree with internal/buildcfg.FramePointerEnabled. 1504 const framepointer_enabled = GOARCH == "amd64" || GOARCH == "arm64" 1505 1506 // getcallerfp returns the frame pointer of the caller of the caller 1507 // of this function. 1508 // 1509 //go:nosplit 1510 //go:noinline 1511 func getcallerfp() uintptr { 1512 fp := getfp() // This frame's FP. 1513 if fp != 0 { 1514 fp = *(*uintptr)(unsafe.Pointer(fp)) // The caller's FP. 1515 fp = *(*uintptr)(unsafe.Pointer(fp)) // The caller's caller's FP. 1516 } 1517 return fp 1518 } 1519