Debian Codegraph @

libgo/go/runtime/runtime2.go

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