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