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