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