Debian Codegraph @

src/runtime/proc.go

raw
1 // Copyright 2014 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package runtime
6
7 import (
8 "internal/abi"
9 "internal/cpu"
10 "internal/goarch"
11 "internal/goos"
12 "internal/runtime/atomic"
13 "internal/runtime/exithook"
14 "internal/runtime/strconv"
15 "internal/runtime/sys"
16 "internal/stringslite"
17 "unsafe"
18 )
19
20 // set using cmd/go/internal/modload.ModInfoProg
21 var modinfo string
22
23 // Goroutine scheduler
24 // The scheduler's job is to distribute ready-to-run goroutines over worker threads.
25 //
26 // The main concepts are:
27 // G - goroutine.
28 // M - worker thread, or machine.
29 // P - processor, a resource that is required to execute Go code.
30 // M must have an associated P to execute Go code, however it can be
31 // blocked or in a syscall w/o an associated P.
32 //
33 // Design doc at https://golang.org/s/go11sched.
34
35 // Worker thread parking/unparking.
36 // We need to balance between keeping enough running worker threads to utilize
37 // available hardware parallelism and parking excessive running worker threads
38 // to conserve CPU resources and power. This is not simple for two reasons:
39 // (1) scheduler state is intentionally distributed (in particular, per-P work
40 // queues), so it is not possible to compute global predicates on fast paths;
41 // (2) for optimal thread management we would need to know the future (don't park
42 // a worker thread when a new goroutine will be readied in near future).
43 //
44 // Three rejected approaches that would work badly:
45 // 1. Centralize all scheduler state (would inhibit scalability).
46 // 2. Direct goroutine handoff. That is, when we ready a new goroutine and there
47 // is a spare P, unpark a thread and handoff it the thread and the goroutine.
48 // This would lead to thread state thrashing, as the thread that readied the
49 // goroutine can be out of work the very next moment, we will need to park it.
50 // Also, it would destroy locality of computation as we want to preserve
51 // dependent goroutines on the same thread; and introduce additional latency.
52 // 3. Unpark an additional thread whenever we ready a goroutine and there is an
53 // idle P, but don't do handoff. This would lead to excessive thread parking/
54 // unparking as the additional threads will instantly park without discovering
55 // any work to do.
56 //
57 // The current approach:
58 //
59 // This approach applies to three primary sources of potential work: readying a
60 // goroutine, new/modified-earlier timers, and idle-priority GC. See below for
61 // additional details.
62 //
63 // We unpark an additional thread when we submit work if (this is wakep()):
64 // 1. There is an idle P, and
65 // 2. There are no "spinning" worker threads.
66 //
67 // A worker thread is considered spinning if it is out of local work and did
68 // not find work in the global run queue or netpoller; the spinning state is
69 // denoted in m.spinning and in sched.nmspinning. Threads unparked this way are
70 // also considered spinning; we don't do goroutine handoff so such threads are
71 // out of work initially. Spinning threads spin on looking for work in per-P
72 // run queues and timer heaps or from the GC before parking. If a spinning
73 // thread finds work it takes itself out of the spinning state and proceeds to
74 // execution. If it does not find work it takes itself out of the spinning
75 // state and then parks.
76 //
77 // If there is at least one spinning thread (sched.nmspinning>1), we don't
78 // unpark new threads when submitting work. To compensate for that, if the last
79 // spinning thread finds work and stops spinning, it must unpark a new spinning
80 // thread. This approach smooths out unjustified spikes of thread unparking,
81 // but at the same time guarantees eventual maximal CPU parallelism
82 // utilization.
83 //
84 // The main implementation complication is that we need to be very careful
85 // during spinning->non-spinning thread transition. This transition can race
86 // with submission of new work, and either one part or another needs to unpark
87 // another worker thread. If they both fail to do that, we can end up with
88 // semi-persistent CPU underutilization.
89 //
90 // The general pattern for submission is:
91 // 1. Submit work to the local or global run queue, timer heap, or GC state.
92 // 2. #StoreLoad-style memory barrier.
93 // 3. Check sched.nmspinning.
94 //
95 // The general pattern for spinning->non-spinning transition is:
96 // 1. Decrement nmspinning.
97 // 2. #StoreLoad-style memory barrier.
98 // 3. Check all per-P work queues and GC for new work.
99 //
100 // Note that all this complexity does not apply to global run queue as we are
101 // not sloppy about thread unparking when submitting to global queue. Also see
102 // comments for nmspinning manipulation.
103 //
104 // How these different sources of work behave varies, though it doesn't affect
105 // the synchronization approach:
106 // * Ready goroutine: this is an obvious source of work; the goroutine is
107 // immediately ready and must run on some thread eventually.
108 // * New/modified-earlier timer: The current timer implementation (see time.go)
109 // uses netpoll in a thread with no work available to wait for the soonest
110 // timer. If there is no thread waiting, we want a new spinning thread to go
111 // wait.
112 // * Idle-priority GC: The GC wakes a stopped idle thread to contribute to
113 // background GC work (note: currently disabled per golang.org/issue/19112).
114 // Also see golang.org/issue/44313, as this should be extended to all GC
115 // workers.
116
117 var (
118 m0 m
119 g0 g
120 mcache0 *mcache
121 raceprocctx0 uintptr
122 raceFiniLock mutex
123 )
124
125 // This slice records the initializing tasks that need to be
126 // done to start up the runtime. It is built by the linker.
127 var runtime_inittasks []*initTask
128
129 // main_init_done is a signal used by cgocallbackg that initialization
130 // has been completed. It is made before _cgo_notify_runtime_init_done,
131 // so all cgo calls can rely on it existing. When main_init is complete,
132 // it is closed, meaning cgocallbackg can reliably receive from it.
133 var main_init_done chan bool
134
135 //go:linkname main_main main.main
136 func main_main()
137
138 // mainStarted indicates that the main M has started.
139 var mainStarted bool
140
141 // runtimeInitTime is the nanotime() at which the runtime started.
142 var runtimeInitTime int64
143
144 // Value to use for signal mask for newly created M's.
145 var initSigmask sigset
146
147 // The main goroutine.
148 func main() {
149 mp := getg().m
150
151 // Racectx of m0->g0 is used only as the parent of the main goroutine.
152 // It must not be used for anything else.
153 mp.g0.racectx = 0
154
155 // Max stack size is 1 GB on 64-bit, 250 MB on 32-bit.
156 // Using decimal instead of binary GB and MB because
157 // they look nicer in the stack overflow failure message.
158 if goarch.PtrSize == 8 {
159 maxstacksize = 1000000000
160 } else {
161 maxstacksize = 250000000
162 }
163
164 // An upper limit for max stack size. Used to avoid random crashes
165 // after calling SetMaxStack and trying to allocate a stack that is too big,
166 // since stackalloc works with 32-bit sizes.
167 maxstackceiling = 2 * maxstacksize
168
169 // Allow newproc to start new Ms.
170 mainStarted = true
171
172 if haveSysmon {
173 systemstack(func() {
174 newm(sysmon, nil, -1)
175 })
176 }
177
178 // Lock the main goroutine onto this, the main OS thread,
179 // during initialization. Most programs won't care, but a few
180 // do require certain calls to be made by the main thread.
181 // Those can arrange for main.main to run in the main thread
182 // by calling runtime.LockOSThread during initialization
183 // to preserve the lock.
184 lockOSThread()
185
186 if mp != &m0 {
187 throw("runtime.main not on m0")
188 }
189
190 // Record when the world started.
191 // Must be before doInit for tracing init.
192 runtimeInitTime = nanotime()
193 if runtimeInitTime == 0 {
194 throw("nanotime returning zero")
195 }
196
197 if debug.inittrace != 0 {
198 inittrace.id = getg().goid
199 inittrace.active = true
200 }
201
202 doInit(runtime_inittasks) // Must be before defer.
203
204 // Defer unlock so that runtime.Goexit during init does the unlock too.
205 needUnlock := true
206 defer func() {
207 if needUnlock {
208 unlockOSThread()
209 }
210 }()
211
212 gcenable()
213 defaultGOMAXPROCSUpdateEnable() // don't STW before runtime initialized.
214
215 main_init_done = make(chan bool)
216 if iscgo {
217 if _cgo_pthread_key_created == nil {
218 throw("_cgo_pthread_key_created missing")
219 }
220
221 if _cgo_thread_start == nil {
222 throw("_cgo_thread_start missing")
223 }
224 if GOOS != "windows" {
225 if _cgo_setenv == nil {
226 throw("_cgo_setenv missing")
227 }
228 if _cgo_unsetenv == nil {
229 throw("_cgo_unsetenv missing")
230 }
231 }
232 if _cgo_notify_runtime_init_done == nil {
233 throw("_cgo_notify_runtime_init_done missing")
234 }
235
236 // Set the x_crosscall2_ptr C function pointer variable point to crosscall2.
237 if set_crosscall2 == nil {
238 throw("set_crosscall2 missing")
239 }
240 set_crosscall2()
241
242 // Start the template thread in case we enter Go from
243 // a C-created thread and need to create a new thread.
244 startTemplateThread()
245 cgocall(_cgo_notify_runtime_init_done, nil)
246 }
247
248 // Run the initializing tasks. Depending on build mode this
249 // list can arrive a few different ways, but it will always
250 // contain the init tasks computed by the linker for all the
251 // packages in the program (excluding those added at runtime
252 // by package plugin). Run through the modules in dependency
253 // order (the order they are initialized by the dynamic
254 // loader, i.e. they are added to the moduledata linked list).
255 for m := &firstmoduledata; m != nil; m = m.next {
256 doInit(m.inittasks)
257 }
258
259 // Disable init tracing after main init done to avoid overhead
260 // of collecting statistics in malloc and newproc
261 inittrace.active = false
262
263 close(main_init_done)
264
265 needUnlock = false
266 unlockOSThread()
267
268 if isarchive || islibrary {
269 // A program compiled with -buildmode=c-archive or c-shared
270 // has a main, but it is not executed.
271 if GOARCH == "wasm" {
272 // On Wasm, pause makes it return to the host.
273 // Unlike cgo callbacks where Ms are created on demand,
274 // on Wasm we have only one M. So we keep this M (and this
275 // G) for callbacks.
276 // Using the caller's SP unwinds this frame and backs to
277 // goexit. The -16 is: 8 for goexit's (fake) return PC,
278 // and pause's epilogue pops 8.
279 pause(sys.GetCallerSP() - 16) // should not return
280 panic("unreachable")
281 }
282 return
283 }
284 fn := main_main // make an indirect call, as the linker doesn't know the address of the main package when laying down the runtime
285 fn()
286
287 exitHooksRun := false
288 if raceenabled {
289 runExitHooks(0) // run hooks now, since racefini does not return
290 exitHooksRun = true
291 racefini()
292 }
293
294 // Check for C memory leaks if using ASAN and we've made cgo calls,
295 // or if we are running as a library in a C program.
296 // We always make one cgo call, above, to notify_runtime_init_done,
297 // so we ignore that one.
298 // No point in leak checking if no cgo calls, since leak checking
299 // just looks for objects allocated using malloc and friends.
300 // Just checking iscgo doesn't help because asan implies iscgo.
301 if asanenabled && (isarchive || islibrary || NumCgoCall() > 1) {
302 runExitHooks(0) // lsandoleakcheck may not return
303 exitHooksRun = true
304 lsandoleakcheck()
305 }
306
307 // Make racy client program work: if panicking on
308 // another goroutine at the same time as main returns,
309 // let the other goroutine finish printing the panic trace.
310 // Once it does, it will exit. See issues 3934 and 20018.
311 if runningPanicDefers.Load() != 0 {
312 // Running deferred functions should not take long.
313 for c := 0; c < 1000; c++ {
314 if runningPanicDefers.Load() == 0 {
315 break
316 }
317 Gosched()
318 }
319 }
320 if panicking.Load() != 0 {
321 gopark(nil, nil, waitReasonPanicWait, traceBlockForever, 1)
322 }
323 if !exitHooksRun {
324 runExitHooks(0)
325 }
326
327 exit(0)
328 for {
329 var x *int32
330 *x = 0
331 }
332 }
333
334 // os_beforeExit is called from os.Exit(0).
335 //
336 //go:linkname os_beforeExit os.runtime_beforeExit
337 func os_beforeExit(exitCode int) {
338 runExitHooks(exitCode)
339 if exitCode == 0 && raceenabled {
340 racefini()
341 }
342
343 // See comment in main, above.
344 if exitCode == 0 && asanenabled && (isarchive || islibrary || NumCgoCall() > 1) {
345 lsandoleakcheck()
346 }
347 }
348
349 func init() {
350 exithook.Gosched = Gosched
351 exithook.Goid = func() uint64 { return getg().goid }
352 exithook.Throw = throw
353 }
354
355 func runExitHooks(code int) {
356 exithook.Run(code)
357 }
358
359 // start forcegc helper goroutine
360 func init() {
361 go forcegchelper()
362 }
363
364 func forcegchelper() {
365 forcegc.g = getg()
366 lockInit(&forcegc.lock, lockRankForcegc)
367 for {
368 lock(&forcegc.lock)
369 if forcegc.idle.Load() {
370 throw("forcegc: phase error")
371 }
372 forcegc.idle.Store(true)
373 goparkunlock(&forcegc.lock, waitReasonForceGCIdle, traceBlockSystemGoroutine, 1)
374 // this goroutine is explicitly resumed by sysmon
375 if debug.gctrace > 0 {
376 println("GC forced")
377 }
378 // Time-triggered, fully concurrent.
379 gcStart(gcTrigger{kind: gcTriggerTime, now: nanotime()})
380 }
381 }
382
383 // Gosched yields the processor, allowing other goroutines to run. It does not
384 // suspend the current goroutine, so execution resumes automatically.
385 //
386 //go:nosplit
387 func Gosched() {
388 checkTimeouts()
389 mcall(gosched_m)
390 }
391
392 // goschedguarded yields the processor like gosched, but also checks
393 // for forbidden states and opts out of the yield in those cases.
394 //
395 //go:nosplit
396 func goschedguarded() {
397 mcall(goschedguarded_m)
398 }
399
400 // goschedIfBusy yields the processor like gosched, but only does so if
401 // there are no idle Ps or if we're on the only P and there's nothing in
402 // the run queue. In both cases, there is freely available idle time.
403 //
404 //go:nosplit
405 func goschedIfBusy() {
406 gp := getg()
407 // Call gosched if gp.preempt is set; we may be in a tight loop that
408 // doesn't otherwise yield.
409 if !gp.preempt && sched.npidle.Load() > 0 {
410 return
411 }
412 mcall(gosched_m)
413 }
414
415 // Puts the current goroutine into a waiting state and calls unlockf on the
416 // system stack.
417 //
418 // If unlockf returns false, the goroutine is resumed.
419 //
420 // unlockf must not access this G's stack, as it may be moved between
421 // the call to gopark and the call to unlockf.
422 //
423 // Note that because unlockf is called after putting the G into a waiting
424 // state, the G may have already been readied by the time unlockf is called
425 // unless there is external synchronization preventing the G from being
426 // readied. If unlockf returns false, it must guarantee that the G cannot be
427 // externally readied.
428 //
429 // Reason explains why the goroutine has been parked. It is displayed in stack
430 // traces and heap dumps. Reasons should be unique and descriptive. Do not
431 // re-use reasons, add new ones.
432 //
433 // gopark should be an internal detail,
434 // but widely used packages access it using linkname.
435 // Notable members of the hall of shame include:
436 // - gvisor.dev/gvisor
437 // - github.com/sagernet/gvisor
438 //
439 // Do not remove or change the type signature.
440 // See go.dev/issue/67401.
441 //
442 //go:linkname gopark
443 func gopark(unlockf func(*g, unsafe.Pointer) bool, lock unsafe.Pointer, reason waitReason, traceReason traceBlockReason, traceskip int) {
444 if reason != waitReasonSleep {
445 checkTimeouts() // timeouts may expire while two goroutines keep the scheduler busy
446 }
447 mp := acquirem()
448 gp := mp.curg
449 status := readgstatus(gp)
450 if status != _Grunning && status != _Gscanrunning {
451 throw("gopark: bad g status")
452 }
453 mp.waitlock = lock
454 mp.waitunlockf = unlockf
455 gp.waitreason = reason
456 mp.waitTraceBlockReason = traceReason
457 mp.waitTraceSkip = traceskip
458 releasem(mp)
459 // can't do anything that might move the G between Ms here.
460 mcall(park_m)
461 }
462
463 // Puts the current goroutine into a waiting state and unlocks the lock.
464 // The goroutine can be made runnable again by calling goready(gp).
465 func goparkunlock(lock *mutex, reason waitReason, traceReason traceBlockReason, traceskip int) {
466 gopark(parkunlock_c, unsafe.Pointer(lock), reason, traceReason, traceskip)
467 }
468
469 // goready should be an internal detail,
470 // but widely used packages access it using linkname.
471 // Notable members of the hall of shame include:
472 // - gvisor.dev/gvisor
473 // - github.com/sagernet/gvisor
474 //
475 // Do not remove or change the type signature.
476 // See go.dev/issue/67401.
477 //
478 //go:linkname goready
479 func goready(gp *g, traceskip int) {
480 systemstack(func() {
481 ready(gp, traceskip, true)
482 })
483 }
484
485 //go:nosplit
486 func acquireSudog() *sudog {
487 // Delicate dance: the semaphore implementation calls
488 // acquireSudog, acquireSudog calls new(sudog),
489 // new calls malloc, malloc can call the garbage collector,
490 // and the garbage collector calls the semaphore implementation
491 // in stopTheWorld.
492 // Break the cycle by doing acquirem/releasem around new(sudog).
493 // The acquirem/releasem increments m.locks during new(sudog),
494 // which keeps the garbage collector from being invoked.
495 mp := acquirem()
496 pp := mp.p.ptr()
497 if len(pp.sudogcache) == 0 {
498 lock(&sched.sudoglock)
499 // First, try to grab a batch from central cache.
500 for len(pp.sudogcache) < cap(pp.sudogcache)/2 && sched.sudogcache != nil {
501 s := sched.sudogcache
502 sched.sudogcache = s.next
503 s.next = nil
504 pp.sudogcache = append(pp.sudogcache, s)
505 }
506 unlock(&sched.sudoglock)
507 // If the central cache is empty, allocate a new one.
508 if len(pp.sudogcache) == 0 {
509 pp.sudogcache = append(pp.sudogcache, new(sudog))
510 }
511 }
512 n := len(pp.sudogcache)
513 s := pp.sudogcache[n-1]
514 pp.sudogcache[n-1] = nil
515 pp.sudogcache = pp.sudogcache[:n-1]
516 if s.elem != nil {
517 throw("acquireSudog: found s.elem != nil in cache")
518 }
519 releasem(mp)
520 return s
521 }
522
523 //go:nosplit
524 func releaseSudog(s *sudog) {
525 if s.elem != nil {
526 throw("runtime: sudog with non-nil elem")
527 }
528 if s.isSelect {
529 throw("runtime: sudog with non-false isSelect")
530 }
531 if s.next != nil {
532 throw("runtime: sudog with non-nil next")
533 }
534 if s.prev != nil {
535 throw("runtime: sudog with non-nil prev")
536 }
537 if s.waitlink != nil {
538 throw("runtime: sudog with non-nil waitlink")
539 }
540 if s.c != nil {
541 throw("runtime: sudog with non-nil c")
542 }
543 gp := getg()
544 if gp.param != nil {
545 throw("runtime: releaseSudog with non-nil gp.param")
546 }
547 mp := acquirem() // avoid rescheduling to another P
548 pp := mp.p.ptr()
549 if len(pp.sudogcache) == cap(pp.sudogcache) {
550 // Transfer half of local cache to the central cache.
551 var first, last *sudog
552 for len(pp.sudogcache) > cap(pp.sudogcache)/2 {
553 n := len(pp.sudogcache)
554 p := pp.sudogcache[n-1]
555 pp.sudogcache[n-1] = nil
556 pp.sudogcache = pp.sudogcache[:n-1]
557 if first == nil {
558 first = p
559 } else {
560 last.next = p
561 }
562 last = p
563 }
564 lock(&sched.sudoglock)
565 last.next = sched.sudogcache
566 sched.sudogcache = first
567 unlock(&sched.sudoglock)
568 }
569 pp.sudogcache = append(pp.sudogcache, s)
570 releasem(mp)
571 }
572
573 // called from assembly.
574 func badmcall(fn func(*g)) {
575 throw("runtime: mcall called on m->g0 stack")
576 }
577
578 func badmcall2(fn func(*g)) {
579 throw("runtime: mcall function returned")
580 }
581
582 func badreflectcall() {
583 panic(plainError("arg size to reflect.call more than 1GB"))
584 }
585
586 //go:nosplit
587 //go:nowritebarrierrec
588 func badmorestackg0() {
589 if !crashStackImplemented {
590 writeErrStr("fatal: morestack on g0\n")
591 return
592 }
593
594 g := getg()
595 switchToCrashStack(func() {
596 print("runtime: morestack on g0, stack [", hex(g.stack.lo), " ", hex(g.stack.hi), "], sp=", hex(g.sched.sp), ", called from\n")
597 g.m.traceback = 2 // include pc and sp in stack trace
598 traceback1(g.sched.pc, g.sched.sp, g.sched.lr, g, 0)
599 print("\n")
600
601 throw("morestack on g0")
602 })
603 }
604
605 //go:nosplit
606 //go:nowritebarrierrec
607 func badmorestackgsignal() {
608 writeErrStr("fatal: morestack on gsignal\n")
609 }
610
611 //go:nosplit
612 func badctxt() {
613 throw("ctxt != 0")
614 }
615
616 // gcrash is a fake g that can be used when crashing due to bad
617 // stack conditions.
618 var gcrash g
619
620 var crashingG atomic.Pointer[g]
621
622 // Switch to crashstack and call fn, with special handling of
623 // concurrent and recursive cases.
624 //
625 // Nosplit as it is called in a bad stack condition (we know
626 // morestack would fail).
627 //
628 //go:nosplit
629 //go:nowritebarrierrec
630 func switchToCrashStack(fn func()) {
631 me := getg()
632 if crashingG.CompareAndSwapNoWB(nil, me) {
633 switchToCrashStack0(fn) // should never return
634 abort()
635 }
636 if crashingG.Load() == me {
637 // recursive crashing. too bad.
638 writeErrStr("fatal: recursive switchToCrashStack\n")
639 abort()
640 }
641 // Another g is crashing. Give it some time, hopefully it will finish traceback.
642 usleep_no_g(100)
643 writeErrStr("fatal: concurrent switchToCrashStack\n")
644 abort()
645 }
646
647 // Disable crash stack on Windows for now. Apparently, throwing an exception
648 // on a non-system-allocated crash stack causes EXCEPTION_STACK_OVERFLOW and
649 // hangs the process (see issue 63938).
650 const crashStackImplemented = GOOS != "windows"
651
652 //go:noescape
653 func switchToCrashStack0(fn func()) // in assembly
654
655 func lockedOSThread() bool {
656 gp := getg()
657 return gp.lockedm != 0 && gp.m.lockedg != 0
658 }
659
660 var (
661 // allgs contains all Gs ever created (including dead Gs), and thus
662 // never shrinks.
663 //
664 // Access via the slice is protected by allglock or stop-the-world.
665 // Readers that cannot take the lock may (carefully!) use the atomic
666 // variables below.
667 allglock mutex
668 allgs []*g
669
670 // allglen and allgptr are atomic variables that contain len(allgs) and
671 // &allgs[0] respectively. Proper ordering depends on totally-ordered
672 // loads and stores. Writes are protected by allglock.
673 //
674 // allgptr is updated before allglen. Readers should read allglen
675 // before allgptr to ensure that allglen is always <= len(allgptr). New
676 // Gs appended during the race can be missed. For a consistent view of
677 // all Gs, allglock must be held.
678 //
679 // allgptr copies should always be stored as a concrete type or
680 // unsafe.Pointer, not uintptr, to ensure that GC can still reach it
681 // even if it points to a stale array.
682 allglen uintptr
683 allgptr **g
684 )
685
686 func allgadd(gp *g) {
687 if readgstatus(gp) == _Gidle {
688 throw("allgadd: bad status Gidle")
689 }
690
691 lock(&allglock)
692 allgs = append(allgs, gp)
693 if &allgs[0] != allgptr {
694 atomicstorep(unsafe.Pointer(&allgptr), unsafe.Pointer(&allgs[0]))
695 }
696 atomic.Storeuintptr(&allglen, uintptr(len(allgs)))
697 unlock(&allglock)
698 }
699
700 // allGsSnapshot returns a snapshot of the slice of all Gs.
701 //
702 // The world must be stopped or allglock must be held.
703 func allGsSnapshot() []*g {
704 assertWorldStoppedOrLockHeld(&allglock)
705
706 // Because the world is stopped or allglock is held, allgadd
707 // cannot happen concurrently with this. allgs grows
708 // monotonically and existing entries never change, so we can
709 // simply return a copy of the slice header. For added safety,
710 // we trim everything past len because that can still change.
711 return allgs[:len(allgs):len(allgs)]
712 }
713
714 // atomicAllG returns &allgs[0] and len(allgs) for use with atomicAllGIndex.
715 func atomicAllG() (**g, uintptr) {
716 length := atomic.Loaduintptr(&allglen)
717 ptr := (**g)(atomic.Loadp(unsafe.Pointer(&allgptr)))
718 return ptr, length
719 }
720
721 // atomicAllGIndex returns ptr[i] with the allgptr returned from atomicAllG.
722 func atomicAllGIndex(ptr **g, i uintptr) *g {
723 return *(**g)(add(unsafe.Pointer(ptr), i*goarch.PtrSize))
724 }
725
726 // forEachG calls fn on every G from allgs.
727 //
728 // forEachG takes a lock to exclude concurrent addition of new Gs.
729 func forEachG(fn func(gp *g)) {
730 lock(&allglock)
731 for _, gp := range allgs {
732 fn(gp)
733 }
734 unlock(&allglock)
735 }
736
737 // forEachGRace calls fn on every G from allgs.
738 //
739 // forEachGRace avoids locking, but does not exclude addition of new Gs during
740 // execution, which may be missed.
741 func forEachGRace(fn func(gp *g)) {
742 ptr, length := atomicAllG()
743 for i := uintptr(0); i < length; i++ {
744 gp := atomicAllGIndex(ptr, i)
745 fn(gp)
746 }
747 return
748 }
749
750 const (
751 // Number of goroutine ids to grab from sched.goidgen to local per-P cache at once.
752 // 16 seems to provide enough amortization, but other than that it's mostly arbitrary number.
753 _GoidCacheBatch = 16
754 )
755
756 // cpuinit sets up CPU feature flags and calls internal/cpu.Initialize. env should be the complete
757 // value of the GODEBUG environment variable.
758 func cpuinit(env string) {
759 switch GOOS {
760 case "aix", "darwin", "ios", "dragonfly", "freebsd", "netbsd", "openbsd", "illumos", "solaris", "linux":
761 cpu.DebugOptions = true
762 }
763 cpu.Initialize(env)
764
765 // Support cpu feature variables are used in code generated by the compiler
766 // to guard execution of instructions that can not be assumed to be always supported.
767 switch GOARCH {
768 case "386", "amd64":
769 x86HasPOPCNT = cpu.X86.HasPOPCNT
770 x86HasSSE41 = cpu.X86.HasSSE41
771 x86HasFMA = cpu.X86.HasFMA
772
773 case "arm":
774 armHasVFPv4 = cpu.ARM.HasVFPv4
775
776 case "arm64":
777 arm64HasATOMICS = cpu.ARM64.HasATOMICS
778
779 case "loong64":
780 loong64HasLAMCAS = cpu.Loong64.HasLAMCAS
781 loong64HasLAM_BH = cpu.Loong64.HasLAM_BH
782 loong64HasLSX = cpu.Loong64.HasLSX
783
784 case "riscv64":
785 riscv64HasZbb = cpu.RISCV64.HasZbb
786 }
787 }
788
789 // getGodebugEarly extracts the environment variable GODEBUG from the environment on
790 // Unix-like operating systems and returns it. This function exists to extract GODEBUG
791 // early before much of the runtime is initialized.
792 //
793 // Returns nil, false if OS doesn't provide env vars early in the init sequence.
794 func getGodebugEarly() (string, bool) {
795 const prefix = "GODEBUG="
796 var env string
797 switch GOOS {
798 case "aix", "darwin", "ios", "dragonfly", "freebsd", "netbsd", "openbsd", "illumos", "solaris", "linux":
799 // Similar to goenv_unix but extracts the environment value for
800 // GODEBUG directly.
801 // TODO(moehrmann): remove when general goenvs() can be called before cpuinit()
802 n := int32(0)
803 for argv_index(argv, argc+1+n) != nil {
804 n++
805 }
806
807 for i := int32(0); i < n; i++ {
808 p := argv_index(argv, argc+1+i)
809 s := unsafe.String(p, findnull(p))
810
811 if stringslite.HasPrefix(s, prefix) {
812 env = gostringnocopy(p)[len(prefix):]
813 break
814 }
815 }
816 break
817
818 default:
819 return "", false
820 }
821 return env, true
822 }
823
824 // The bootstrap sequence is:
825 //
826 // call osinit
827 // call schedinit
828 // make & queue new G
829 // call runtime·mstart
830 //
831 // The new G calls runtime·main.
832 func schedinit() {
833 lockInit(&sched.lock, lockRankSched)
834 lockInit(&sched.sysmonlock, lockRankSysmon)
835 lockInit(&sched.deferlock, lockRankDefer)
836 lockInit(&sched.sudoglock, lockRankSudog)
837 lockInit(&deadlock, lockRankDeadlock)
838 lockInit(&paniclk, lockRankPanic)
839 lockInit(&allglock, lockRankAllg)
840 lockInit(&allpLock, lockRankAllp)
841 lockInit(&reflectOffs.lock, lockRankReflectOffs)
842 lockInit(&finlock, lockRankFin)
843 lockInit(&cpuprof.lock, lockRankCpuprof)
844 lockInit(&computeMaxProcsLock, lockRankComputeMaxProcs)
845 allocmLock.init(lockRankAllocmR, lockRankAllocmRInternal, lockRankAllocmW)
846 execLock.init(lockRankExecR, lockRankExecRInternal, lockRankExecW)
847 traceLockInit()
848 // Enforce that this lock is always a leaf lock.
849 // All of this lock's critical sections should be
850 // extremely short.
851 lockInit(&memstats.heapStats.noPLock, lockRankLeafRank)
852
853 lockVerifyMSize()
854
855 // raceinit must be the first call to race detector.
856 // In particular, it must be done before mallocinit below calls racemapshadow.
857 gp := getg()
858 if raceenabled {
859 gp.racectx, raceprocctx0 = raceinit()
860 }
861
862 sched.maxmcount = 10000
863 crashFD.Store(^uintptr(0))
864
865 // The world starts stopped.
866 worldStopped()
867
868 godebug, parsedGodebug := getGodebugEarly()
869 if parsedGodebug {
870 parseRuntimeDebugVars(godebug)
871 }
872 ticks.init() // run as early as possible
873 moduledataverify()
874 stackinit()
875 mallocinit()
876 cpuinit(godebug) // must run before alginit
877 randinit() // must run before alginit, mcommoninit
878 alginit() // maps, hash, rand must not be used before this call
879 mcommoninit(gp.m, -1)
880 modulesinit() // provides activeModules
881 typelinksinit() // uses maps, activeModules
882 itabsinit() // uses activeModules
883 stkobjinit() // must run before GC starts
884
885 sigsave(&gp.m.sigmask)
886 initSigmask = gp.m.sigmask
887
888 goargs()
889 goenvs()
890 secure()
891 checkfds()
892 if !parsedGodebug {
893 // Some platforms, e.g., Windows, didn't make env vars available "early",
894 // so try again now.
895 parseRuntimeDebugVars(gogetenv("GODEBUG"))
896 }
897 finishDebugVarsSetup()
898 gcinit()
899
900 // Allocate stack space that can be used when crashing due to bad stack
901 // conditions, e.g. morestack on g0.
902 gcrash.stack = stackalloc(16384)
903 gcrash.stackguard0 = gcrash.stack.lo + 1000
904 gcrash.stackguard1 = gcrash.stack.lo + 1000
905
906 // if disableMemoryProfiling is set, update MemProfileRate to 0 to turn off memprofile.
907 // Note: parsedebugvars may update MemProfileRate, but when disableMemoryProfiling is
908 // set to true by the linker, it means that nothing is consuming the profile, it is
909 // safe to set MemProfileRate to 0.
910 if disableMemoryProfiling {
911 MemProfileRate = 0
912 }
913
914 // mcommoninit runs before parsedebugvars, so init profstacks again.
915 mProfStackInit(gp.m)
916 defaultGOMAXPROCSInit()
917
918 lock(&sched.lock)
919 sched.lastpoll.Store(nanotime())
920 var procs int32
921 if n, ok := strconv.Atoi32(gogetenv("GOMAXPROCS")); ok && n > 0 {
922 procs = n
923 sched.customGOMAXPROCS = true
924 } else {
925 // Use numCPUStartup for initial GOMAXPROCS for two reasons:
926 //
927 // 1. We just computed it in osinit, recomputing is (minorly) wasteful.
928 //
929 // 2. More importantly, if debug.containermaxprocs == 0 &&
930 // debug.updatemaxprocs == 0, we want to guarantee that
931 // runtime.GOMAXPROCS(0) always equals runtime.NumCPU (which is
932 // just numCPUStartup).
933 procs = defaultGOMAXPROCS(numCPUStartup)
934 }
935 if procresize(procs) != nil {
936 throw("unknown runnable goroutine during bootstrap")
937 }
938 unlock(&sched.lock)
939
940 // World is effectively started now, as P's can run.
941 worldStarted()
942
943 if buildVersion == "" {
944 // Condition should never trigger. This code just serves
945 // to ensure runtime·buildVersion is kept in the resulting binary.
946 buildVersion = "unknown"
947 }
948 if len(modinfo) == 1 {
949 // Condition should never trigger. This code just serves
950 // to ensure runtime·modinfo is kept in the resulting binary.
951 modinfo = ""
952 }
953 }
954
955 func dumpgstatus(gp *g) {
956 thisg := getg()
957 print("runtime: gp: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n")
958 print("runtime: getg: g=", thisg, ", goid=", thisg.goid, ", g->atomicstatus=", readgstatus(thisg), "\n")
959 }
960
961 // sched.lock must be held.
962 func checkmcount() {
963 assertLockHeld(&sched.lock)
964
965 // Exclude extra M's, which are used for cgocallback from threads
966 // created in C.
967 //
968 // The purpose of the SetMaxThreads limit is to avoid accidental fork
969 // bomb from something like millions of goroutines blocking on system
970 // calls, causing the runtime to create millions of threads. By
971 // definition, this isn't a problem for threads created in C, so we
972 // exclude them from the limit. See https://go.dev/issue/60004.
973 count := mcount() - int32(extraMInUse.Load()) - int32(extraMLength.Load())
974 if count > sched.maxmcount {
975 print("runtime: program exceeds ", sched.maxmcount, "-thread limit\n")
976 throw("thread exhaustion")
977 }
978 }
979
980 // mReserveID returns the next ID to use for a new m. This new m is immediately
981 // considered 'running' by checkdead.
982 //
983 // sched.lock must be held.
984 func mReserveID() int64 {
985 assertLockHeld(&sched.lock)
986
987 if sched.mnext+1 < sched.mnext {
988 throw("runtime: thread ID overflow")
989 }
990 id := sched.mnext
991 sched.mnext++
992 checkmcount()
993 return id
994 }
995
996 // Pre-allocated ID may be passed as 'id', or omitted by passing -1.
997 func mcommoninit(mp *m, id int64) {
998 gp := getg()
999
1000 // g0 stack won't make sense for user (and is not necessary unwindable).
1001 if gp != gp.m.g0 {
1002 callers(1, mp.createstack[:])
1003 }
1004
1005 lock(&sched.lock)
1006
1007 if id >= 0 {
1008 mp.id = id
1009 } else {
1010 mp.id = mReserveID()
1011 }
1012
1013 mrandinit(mp)
1014
1015 mpreinit(mp)
1016 if mp.gsignal != nil {
1017 mp.gsignal.stackguard1 = mp.gsignal.stack.lo + stackGuard
1018 }
1019
1020 // Add to allm so garbage collector doesn't free g->m
1021 // when it is just in a register or thread-local storage.
1022 mp.alllink = allm
1023
1024 // NumCgoCall() and others iterate over allm w/o schedlock,
1025 // so we need to publish it safely.
1026 atomicstorep(unsafe.Pointer(&allm), unsafe.Pointer(mp))
1027 unlock(&sched.lock)
1028
1029 // Allocate memory to hold a cgo traceback if the cgo call crashes.
1030 if iscgo || GOOS == "solaris" || GOOS == "illumos" || GOOS == "windows" {
1031 mp.cgoCallers = new(cgoCallers)
1032 }
1033 mProfStackInit(mp)
1034 }
1035
1036 // mProfStackInit is used to eagerly initialize stack trace buffers for
1037 // profiling. Lazy allocation would have to deal with reentrancy issues in
1038 // malloc and runtime locks for mLockProfile.
1039 // TODO(mknyszek): Implement lazy allocation if this becomes a problem.
1040 func mProfStackInit(mp *m) {
1041 if debug.profstackdepth == 0 {
1042 // debug.profstack is set to 0 by the user, or we're being called from
1043 // schedinit before parsedebugvars.
1044 return
1045 }
1046 mp.profStack = makeProfStackFP()
1047 mp.mLockProfile.stack = makeProfStackFP()
1048 }
1049
1050 // makeProfStackFP creates a buffer large enough to hold a maximum-sized stack
1051 // trace as well as any additional frames needed for frame pointer unwinding
1052 // with delayed inline expansion.
1053 func makeProfStackFP() []uintptr {
1054 // The "1" term is to account for the first stack entry being
1055 // taken up by a "skip" sentinel value for profilers which
1056 // defer inline frame expansion until the profile is reported.
1057 // The "maxSkip" term is for frame pointer unwinding, where we
1058 // want to end up with debug.profstackdebth frames but will discard
1059 // some "physical" frames to account for skipping.
1060 return make([]uintptr, 1+maxSkip+debug.profstackdepth)
1061 }
1062
1063 // makeProfStack returns a buffer large enough to hold a maximum-sized stack
1064 // trace.
1065 func makeProfStack() []uintptr { return make([]uintptr, debug.profstackdepth) }
1066
1067 //go:linkname pprof_makeProfStack
1068 func pprof_makeProfStack() []uintptr { return makeProfStack() }
1069
1070 func (mp *m) becomeSpinning() {
1071 mp.spinning = true
1072 sched.nmspinning.Add(1)
1073 sched.needspinning.Store(0)
1074 }
1075
1076 // Take a snapshot of allp, for use after dropping the P.
1077 //
1078 // Must be called with a P, but the returned slice may be used after dropping
1079 // the P. The M holds a reference on the snapshot to keep the backing array
1080 // alive.
1081 //
1082 //go:yeswritebarrierrec
1083 func (mp *m) snapshotAllp() []*p {
1084 mp.allpSnapshot = allp
1085 return mp.allpSnapshot
1086 }
1087
1088 // Clear the saved allp snapshot. Should be called as soon as the snapshot is
1089 // no longer required.
1090 //
1091 // Must be called after reacquiring a P, as it requires a write barrier.
1092 //
1093 //go:yeswritebarrierrec
1094 func (mp *m) clearAllpSnapshot() {
1095 mp.allpSnapshot = nil
1096 }
1097
1098 func (mp *m) hasCgoOnStack() bool {
1099 return mp.ncgo > 0 || mp.isextra
1100 }
1101
1102 const (
1103 // osHasLowResTimer indicates that the platform's internal timer system has a low resolution,
1104 // typically on the order of 1 ms or more.
1105 osHasLowResTimer = GOOS == "windows" || GOOS == "openbsd" || GOOS == "netbsd"
1106
1107 // osHasLowResClockInt is osHasLowResClock but in integer form, so it can be used to create
1108 // constants conditionally.
1109 osHasLowResClockInt = goos.IsWindows
1110
1111 // osHasLowResClock indicates that timestamps produced by nanotime on the platform have a
1112 // low resolution, typically on the order of 1 ms or more.
1113 osHasLowResClock = osHasLowResClockInt > 0
1114 )
1115
1116 // Mark gp ready to run.
1117 func ready(gp *g, traceskip int, next bool) {
1118 status := readgstatus(gp)
1119
1120 // Mark runnable.
1121 mp := acquirem() // disable preemption because it can be holding p in a local var
1122 if status&^_Gscan != _Gwaiting {
1123 dumpgstatus(gp)
1124 throw("bad g->status in ready")
1125 }
1126
1127 // status is Gwaiting or Gscanwaiting, make Grunnable and put on runq
1128 trace := traceAcquire()
1129 casgstatus(gp, _Gwaiting, _Grunnable)
1130 if trace.ok() {
1131 trace.GoUnpark(gp, traceskip)
1132 traceRelease(trace)
1133 }
1134 runqput(mp.p.ptr(), gp, next)
1135 wakep()
1136 releasem(mp)
1137 }
1138
1139 // freezeStopWait is a large value that freezetheworld sets
1140 // sched.stopwait to in order to request that all Gs permanently stop.
1141 const freezeStopWait = 0x7fffffff
1142
1143 // freezing is set to non-zero if the runtime is trying to freeze the
1144 // world.
1145 var freezing atomic.Bool
1146
1147 // Similar to stopTheWorld but best-effort and can be called several times.
1148 // There is no reverse operation, used during crashing.
1149 // This function must not lock any mutexes.
1150 func freezetheworld() {
1151 freezing.Store(true)
1152 if debug.dontfreezetheworld > 0 {
1153 // Don't prempt Ps to stop goroutines. That will perturb
1154 // scheduler state, making debugging more difficult. Instead,
1155 // allow goroutines to continue execution.
1156 //
1157 // fatalpanic will tracebackothers to trace all goroutines. It
1158 // is unsafe to trace a running goroutine, so tracebackothers
1159 // will skip running goroutines. That is OK and expected, we
1160 // expect users of dontfreezetheworld to use core files anyway.
1161 //
1162 // However, allowing the scheduler to continue running free
1163 // introduces a race: a goroutine may be stopped when
1164 // tracebackothers checks its status, and then start running
1165 // later when we are in the middle of traceback, potentially
1166 // causing a crash.
1167 //
1168 // To mitigate this, when an M naturally enters the scheduler,
1169 // schedule checks if freezing is set and if so stops
1170 // execution. This guarantees that while Gs can transition from
1171 // running to stopped, they can never transition from stopped
1172 // to running.
1173 //
1174 // The sleep here allows racing Ms that missed freezing and are
1175 // about to run a G to complete the transition to running
1176 // before we start traceback.
1177 usleep(1000)
1178 return
1179 }
1180
1181 // stopwait and preemption requests can be lost
1182 // due to races with concurrently executing threads,
1183 // so try several times
1184 for i := 0; i < 5; i++ {
1185 // this should tell the scheduler to not start any new goroutines
1186 sched.stopwait = freezeStopWait
1187 sched.gcwaiting.Store(true)
1188 // this should stop running goroutines
1189 if !preemptall() {
1190 break // no running goroutines
1191 }
1192 usleep(1000)
1193 }
1194 // to be sure
1195 usleep(1000)
1196 preemptall()
1197 usleep(1000)
1198 }
1199
1200 // All reads and writes of g's status go through readgstatus, casgstatus
1201 // castogscanstatus, casfrom_Gscanstatus.
1202 //
1203 //go:nosplit
1204 func readgstatus(gp *g) uint32 {
1205 return gp.atomicstatus.Load()
1206 }
1207
1208 // The Gscanstatuses are acting like locks and this releases them.
1209 // If it proves to be a performance hit we should be able to make these
1210 // simple atomic stores but for now we are going to throw if
1211 // we see an inconsistent state.
1212 func casfrom_Gscanstatus(gp *g, oldval, newval uint32) {
1213 success := false
1214
1215 // Check that transition is valid.
1216 switch oldval {
1217 default:
1218 print("runtime: casfrom_Gscanstatus bad oldval gp=", gp, ", oldval=", hex(oldval), ", newval=", hex(newval), "\n")
1219 dumpgstatus(gp)
1220 throw("casfrom_Gscanstatus:top gp->status is not in scan state")
1221 case _Gscanrunnable,
1222 _Gscanwaiting,
1223 _Gscanrunning,
1224 _Gscansyscall,
1225 _Gscanpreempted:
1226 if newval == oldval&^_Gscan {
1227 success = gp.atomicstatus.CompareAndSwap(oldval, newval)
1228 }
1229 }
1230 if !success {
1231 print("runtime: casfrom_Gscanstatus failed gp=", gp, ", oldval=", hex(oldval), ", newval=", hex(newval), "\n")
1232 dumpgstatus(gp)
1233 throw("casfrom_Gscanstatus: gp->status is not in scan state")
1234 }
1235 releaseLockRankAndM(lockRankGscan)
1236 }
1237
1238 // This will return false if the gp is not in the expected status and the cas fails.
1239 // This acts like a lock acquire while the casfromgstatus acts like a lock release.
1240 func castogscanstatus(gp *g, oldval, newval uint32) bool {
1241 switch oldval {
1242 case _Grunnable,
1243 _Grunning,
1244 _Gwaiting,
1245 _Gsyscall:
1246 if newval == oldval|_Gscan {
1247 r := gp.atomicstatus.CompareAndSwap(oldval, newval)
1248 if r {
1249 acquireLockRankAndM(lockRankGscan)
1250 }
1251 return r
1252
1253 }
1254 }
1255 print("runtime: castogscanstatus oldval=", hex(oldval), " newval=", hex(newval), "\n")
1256 throw("castogscanstatus")
1257 panic("not reached")
1258 }
1259
1260 // casgstatusAlwaysTrack is a debug flag that causes casgstatus to always track
1261 // various latencies on every transition instead of sampling them.
1262 var casgstatusAlwaysTrack = false
1263
1264 // If asked to move to or from a Gscanstatus this will throw. Use the castogscanstatus
1265 // and casfrom_Gscanstatus instead.
1266 // casgstatus will loop if the g->atomicstatus is in a Gscan status until the routine that
1267 // put it in the Gscan state is finished.
1268 //
1269 //go:nosplit
1270 func casgstatus(gp *g, oldval, newval uint32) {
1271 if (oldval&_Gscan != 0) || (newval&_Gscan != 0) || oldval == newval {
1272 systemstack(func() {
1273 // Call on the systemstack to prevent print and throw from counting
1274 // against the nosplit stack reservation.
1275 print("runtime: casgstatus: oldval=", hex(oldval), " newval=", hex(newval), "\n")
1276 throw("casgstatus: bad incoming values")
1277 })
1278 }
1279
1280 lockWithRankMayAcquire(nil, lockRankGscan)
1281
1282 // See https://golang.org/cl/21503 for justification of the yield delay.
1283 const yieldDelay = 5 * 1000
1284 var nextYield int64
1285
1286 // loop if gp->atomicstatus is in a scan state giving
1287 // GC time to finish and change the state to oldval.
1288 for i := 0; !gp.atomicstatus.CompareAndSwap(oldval, newval); i++ {
1289 if oldval == _Gwaiting && gp.atomicstatus.Load() == _Grunnable {
1290 systemstack(func() {
1291 // Call on the systemstack to prevent throw from counting
1292 // against the nosplit stack reservation.
1293 throw("casgstatus: waiting for Gwaiting but is Grunnable")
1294 })
1295 }
1296 if i == 0 {
1297 nextYield = nanotime() + yieldDelay
1298 }
1299 if nanotime() < nextYield {
1300 for x := 0; x < 10 && gp.atomicstatus.Load() != oldval; x++ {
1301 procyield(1)
1302 }
1303 } else {
1304 osyield()
1305 nextYield = nanotime() + yieldDelay/2
1306 }
1307 }
1308
1309 if gp.bubble != nil {
1310 systemstack(func() {
1311 gp.bubble.changegstatus(gp, oldval, newval)
1312 })
1313 }
1314
1315 if oldval == _Grunning {
1316 // Track every gTrackingPeriod time a goroutine transitions out of running.
1317 if casgstatusAlwaysTrack || gp.trackingSeq%gTrackingPeriod == 0 {
1318 gp.tracking = true
1319 }
1320 gp.trackingSeq++
1321 }
1322 if !gp.tracking {
1323 return
1324 }
1325
1326 // Handle various kinds of tracking.
1327 //
1328 // Currently:
1329 // - Time spent in runnable.
1330 // - Time spent blocked on a sync.Mutex or sync.RWMutex.
1331 switch oldval {
1332 case _Grunnable:
1333 // We transitioned out of runnable, so measure how much
1334 // time we spent in this state and add it to
1335 // runnableTime.
1336 now := nanotime()
1337 gp.runnableTime += now - gp.trackingStamp
1338 gp.trackingStamp = 0
1339 case _Gwaiting:
1340 if !gp.waitreason.isMutexWait() {
1341 // Not blocking on a lock.
1342 break
1343 }
1344 // Blocking on a lock, measure it. Note that because we're
1345 // sampling, we have to multiply by our sampling period to get
1346 // a more representative estimate of the absolute value.
1347 // gTrackingPeriod also represents an accurate sampling period
1348 // because we can only enter this state from _Grunning.
1349 now := nanotime()
1350 sched.totalMutexWaitTime.Add((now - gp.trackingStamp) * gTrackingPeriod)
1351 gp.trackingStamp = 0
1352 }
1353 switch newval {
1354 case _Gwaiting:
1355 if !gp.waitreason.isMutexWait() {
1356 // Not blocking on a lock.
1357 break
1358 }
1359 // Blocking on a lock. Write down the timestamp.
1360 now := nanotime()
1361 gp.trackingStamp = now
1362 case _Grunnable:
1363 // We just transitioned into runnable, so record what
1364 // time that happened.
1365 now := nanotime()
1366 gp.trackingStamp = now
1367 case _Grunning:
1368 // We're transitioning into running, so turn off
1369 // tracking and record how much time we spent in
1370 // runnable.
1371 gp.tracking = false
1372 sched.timeToRun.record(gp.runnableTime)
1373 gp.runnableTime = 0
1374 }
1375 }
1376
1377 // casGToWaiting transitions gp from old to _Gwaiting, and sets the wait reason.
1378 //
1379 // Use this over casgstatus when possible to ensure that a waitreason is set.
1380 func casGToWaiting(gp *g, old uint32, reason waitReason) {
1381 // Set the wait reason before calling casgstatus, because casgstatus will use it.
1382 gp.waitreason = reason
1383 casgstatus(gp, old, _Gwaiting)
1384 }
1385
1386 // casGToWaitingForSuspendG transitions gp from old to _Gwaiting, and sets the wait reason.
1387 // The wait reason must be a valid isWaitingForSuspendG wait reason.
1388 //
1389 // Use this over casgstatus when possible to ensure that a waitreason is set.
1390 func casGToWaitingForSuspendG(gp *g, old uint32, reason waitReason) {
1391 if !reason.isWaitingForSuspendG() {
1392 throw("casGToWaitingForSuspendG with non-isWaitingForSuspendG wait reason")
1393 }
1394 casGToWaiting(gp, old, reason)
1395 }
1396
1397 // casGToPreemptScan transitions gp from _Grunning to _Gscan|_Gpreempted.
1398 //
1399 // TODO(austin): This is the only status operation that both changes
1400 // the status and locks the _Gscan bit. Rethink this.
1401 func casGToPreemptScan(gp *g, old, new uint32) {
1402 if old != _Grunning || new != _Gscan|_Gpreempted {
1403 throw("bad g transition")
1404 }
1405 acquireLockRankAndM(lockRankGscan)
1406 for !gp.atomicstatus.CompareAndSwap(_Grunning, _Gscan|_Gpreempted) {
1407 }
1408 // We never notify gp.bubble that the goroutine state has moved
1409 // from _Grunning to _Gpreempted. We call bubble.changegstatus
1410 // after status changes happen, but doing so here would violate the
1411 // ordering between the gscan and synctest locks. The bubble doesn't
1412 // distinguish between _Grunning and _Gpreempted anyway, so not
1413 // notifying it is fine.
1414 }
1415
1416 // casGFromPreempted attempts to transition gp from _Gpreempted to
1417 // _Gwaiting. If successful, the caller is responsible for
1418 // re-scheduling gp.
1419 func casGFromPreempted(gp *g, old, new uint32) bool {
1420 if old != _Gpreempted || new != _Gwaiting {
1421 throw("bad g transition")
1422 }
1423 gp.waitreason = waitReasonPreempted
1424 if !gp.atomicstatus.CompareAndSwap(_Gpreempted, _Gwaiting) {
1425 return false
1426 }
1427 if bubble := gp.bubble; bubble != nil {
1428 bubble.changegstatus(gp, _Gpreempted, _Gwaiting)
1429 }
1430 return true
1431 }
1432
1433 // stwReason is an enumeration of reasons the world is stopping.
1434 type stwReason uint8
1435
1436 // Reasons to stop-the-world.
1437 //
1438 // Avoid reusing reasons and add new ones instead.
1439 const (
1440 stwUnknown stwReason = iota // "unknown"
1441 stwGCMarkTerm // "GC mark termination"
1442 stwGCSweepTerm // "GC sweep termination"
1443 stwWriteHeapDump // "write heap dump"
1444 stwGoroutineProfile // "goroutine profile"
1445 stwGoroutineProfileCleanup // "goroutine profile cleanup"
1446 stwAllGoroutinesStack // "all goroutines stack trace"
1447 stwReadMemStats // "read mem stats"
1448 stwAllThreadsSyscall // "AllThreadsSyscall"
1449 stwGOMAXPROCS // "GOMAXPROCS"
1450 stwStartTrace // "start trace"
1451 stwStopTrace // "stop trace"
1452 stwForTestCountPagesInUse // "CountPagesInUse (test)"
1453 stwForTestReadMetricsSlow // "ReadMetricsSlow (test)"
1454 stwForTestReadMemStatsSlow // "ReadMemStatsSlow (test)"
1455 stwForTestPageCachePagesLeaked // "PageCachePagesLeaked (test)"
1456 stwForTestResetDebugLog // "ResetDebugLog (test)"
1457 )
1458
1459 func (r stwReason) String() string {
1460 return stwReasonStrings[r]
1461 }
1462
1463 func (r stwReason) isGC() bool {
1464 return r == stwGCMarkTerm || r == stwGCSweepTerm
1465 }
1466
1467 // If you add to this list, also add it to src/internal/trace/parser.go.
1468 // If you change the values of any of the stw* constants, bump the trace
1469 // version number and make a copy of this.
1470 var stwReasonStrings = [...]string{
1471 stwUnknown: "unknown",
1472 stwGCMarkTerm: "GC mark termination",
1473 stwGCSweepTerm: "GC sweep termination",
1474 stwWriteHeapDump: "write heap dump",
1475 stwGoroutineProfile: "goroutine profile",
1476 stwGoroutineProfileCleanup: "goroutine profile cleanup",
1477 stwAllGoroutinesStack: "all goroutines stack trace",
1478 stwReadMemStats: "read mem stats",
1479 stwAllThreadsSyscall: "AllThreadsSyscall",
1480 stwGOMAXPROCS: "GOMAXPROCS",
1481 stwStartTrace: "start trace",
1482 stwStopTrace: "stop trace",
1483 stwForTestCountPagesInUse: "CountPagesInUse (test)",
1484 stwForTestReadMetricsSlow: "ReadMetricsSlow (test)",
1485 stwForTestReadMemStatsSlow: "ReadMemStatsSlow (test)",
1486 stwForTestPageCachePagesLeaked: "PageCachePagesLeaked (test)",
1487 stwForTestResetDebugLog: "ResetDebugLog (test)",
1488 }
1489
1490 // worldStop provides context from the stop-the-world required by the
1491 // start-the-world.
1492 type worldStop struct {
1493 reason stwReason
1494 startedStopping int64
1495 finishedStopping int64
1496 stoppingCPUTime int64
1497 }
1498
1499 // Temporary variable for stopTheWorld, when it can't write to the stack.
1500 //
1501 // Protected by worldsema.
1502 var stopTheWorldContext worldStop
1503
1504 // stopTheWorld stops all P's from executing goroutines, interrupting
1505 // all goroutines at GC safe points and records reason as the reason
1506 // for the stop. On return, only the current goroutine's P is running.
1507 // stopTheWorld must not be called from a system stack and the caller
1508 // must not hold worldsema. The caller must call startTheWorld when
1509 // other P's should resume execution.
1510 //
1511 // stopTheWorld is safe for multiple goroutines to call at the
1512 // same time. Each will execute its own stop, and the stops will
1513 // be serialized.
1514 //
1515 // This is also used by routines that do stack dumps. If the system is
1516 // in panic or being exited, this may not reliably stop all
1517 // goroutines.
1518 //
1519 // Returns the STW context. When starting the world, this context must be
1520 // passed to startTheWorld.
1521 func stopTheWorld(reason stwReason) worldStop {
1522 semacquire(&worldsema)
1523 gp := getg()
1524 gp.m.preemptoff = reason.String()
1525 systemstack(func() {
1526 stopTheWorldContext = stopTheWorldWithSema(reason) // avoid write to stack
1527 })
1528 return stopTheWorldContext
1529 }
1530
1531 // startTheWorld undoes the effects of stopTheWorld.
1532 //
1533 // w must be the worldStop returned by stopTheWorld.
1534 func startTheWorld(w worldStop) {
1535 systemstack(func() { startTheWorldWithSema(0, w) })
1536
1537 // worldsema must be held over startTheWorldWithSema to ensure
1538 // gomaxprocs cannot change while worldsema is held.
1539 //
1540 // Release worldsema with direct handoff to the next waiter, but
1541 // acquirem so that semrelease1 doesn't try to yield our time.
1542 //
1543 // Otherwise if e.g. ReadMemStats is being called in a loop,
1544 // it might stomp on other attempts to stop the world, such as
1545 // for starting or ending GC. The operation this blocks is
1546 // so heavy-weight that we should just try to be as fair as
1547 // possible here.
1548 //
1549 // We don't want to just allow us to get preempted between now
1550 // and releasing the semaphore because then we keep everyone
1551 // (including, for example, GCs) waiting longer.
1552 mp := acquirem()
1553 mp.preemptoff = ""
1554 semrelease1(&worldsema, true, 0)
1555 releasem(mp)
1556 }
1557
1558 // stopTheWorldGC has the same effect as stopTheWorld, but blocks
1559 // until the GC is not running. It also blocks a GC from starting
1560 // until startTheWorldGC is called.
1561 func stopTheWorldGC(reason stwReason) worldStop {
1562 semacquire(&gcsema)
1563 return stopTheWorld(reason)
1564 }
1565
1566 // startTheWorldGC undoes the effects of stopTheWorldGC.
1567 //
1568 // w must be the worldStop returned by stopTheWorld.
1569 func startTheWorldGC(w worldStop) {
1570 startTheWorld(w)
1571 semrelease(&gcsema)
1572 }
1573
1574 // Holding worldsema grants an M the right to try to stop the world.
1575 var worldsema uint32 = 1
1576
1577 // Holding gcsema grants the M the right to block a GC, and blocks
1578 // until the current GC is done. In particular, it prevents gomaxprocs
1579 // from changing concurrently.
1580 //
1581 // TODO(mknyszek): Once gomaxprocs and the execution tracer can handle
1582 // being changed/enabled during a GC, remove this.
1583 var gcsema uint32 = 1
1584
1585 // stopTheWorldWithSema is the core implementation of stopTheWorld.
1586 // The caller is responsible for acquiring worldsema and disabling
1587 // preemption first and then should stopTheWorldWithSema on the system
1588 // stack:
1589 //
1590 // semacquire(&worldsema, 0)
1591 // m.preemptoff = "reason"
1592 // var stw worldStop
1593 // systemstack(func() {
1594 // stw = stopTheWorldWithSema(reason)
1595 // })
1596 //
1597 // When finished, the caller must either call startTheWorld or undo
1598 // these three operations separately:
1599 //
1600 // m.preemptoff = ""
1601 // systemstack(func() {
1602 // now = startTheWorldWithSema(stw)
1603 // })
1604 // semrelease(&worldsema)
1605 //
1606 // It is allowed to acquire worldsema once and then execute multiple
1607 // startTheWorldWithSema/stopTheWorldWithSema pairs.
1608 // Other P's are able to execute between successive calls to
1609 // startTheWorldWithSema and stopTheWorldWithSema.
1610 // Holding worldsema causes any other goroutines invoking
1611 // stopTheWorld to block.
1612 //
1613 // Returns the STW context. When starting the world, this context must be
1614 // passed to startTheWorldWithSema.
1615 //
1616 //go:systemstack
1617 func stopTheWorldWithSema(reason stwReason) worldStop {
1618 // Mark the goroutine which called stopTheWorld preemptible so its
1619 // stack may be scanned by the GC or observed by the execution tracer.
1620 //
1621 // This lets a mark worker scan us or the execution tracer take our
1622 // stack while we try to stop the world since otherwise we could get
1623 // in a mutual preemption deadlock.
1624 //
1625 // We must not modify anything on the G stack because a stack shrink
1626 // may occur, now that we switched to _Gwaiting, specifically if we're
1627 // doing this during the mark phase (mark termination excepted, since
1628 // we know that stack scanning is done by that point). A stack shrink
1629 // is otherwise OK though because in order to return from this function
1630 // (and to leave the system stack) we must have preempted all
1631 // goroutines, including any attempting to scan our stack, in which
1632 // case, any stack shrinking will have already completed by the time we
1633 // exit.
1634 //
1635 // N.B. The execution tracer is not aware of this status transition and
1636 // andles it specially based on the wait reason.
1637 casGToWaitingForSuspendG(getg().m.curg, _Grunning, waitReasonStoppingTheWorld)
1638
1639 trace := traceAcquire()
1640 if trace.ok() {
1641 trace.STWStart(reason)
1642 traceRelease(trace)
1643 }
1644 gp := getg()
1645
1646 // If we hold a lock, then we won't be able to stop another M
1647 // that is blocked trying to acquire the lock.
1648 if gp.m.locks > 0 {
1649 throw("stopTheWorld: holding locks")
1650 }
1651
1652 lock(&sched.lock)
1653 start := nanotime() // exclude time waiting for sched.lock from start and total time metrics.
1654 sched.stopwait = gomaxprocs
1655 sched.gcwaiting.Store(true)
1656 preemptall()
1657 // stop current P
1658 gp.m.p.ptr().status = _Pgcstop // Pgcstop is only diagnostic.
1659 gp.m.p.ptr().gcStopTime = start
1660 sched.stopwait--
1661 // try to retake all P's in Psyscall status
1662 trace = traceAcquire()
1663 for _, pp := range allp {
1664 s := pp.status
1665 if s == _Psyscall && atomic.Cas(&pp.status, s, _Pgcstop) {
1666 if trace.ok() {
1667 trace.ProcSteal(pp, false)
1668 }
1669 pp.syscalltick++
1670 pp.gcStopTime = nanotime()
1671 sched.stopwait--
1672 }
1673 }
1674 if trace.ok() {
1675 traceRelease(trace)
1676 }
1677
1678 // stop idle P's
1679 now := nanotime()
1680 for {
1681 pp, _ := pidleget(now)
1682 if pp == nil {
1683 break
1684 }
1685 pp.status = _Pgcstop
1686 pp.gcStopTime = nanotime()
1687 sched.stopwait--
1688 }
1689 wait := sched.stopwait > 0
1690 unlock(&sched.lock)
1691
1692 // wait for remaining P's to stop voluntarily
1693 if wait {
1694 for {
1695 // wait for 100us, then try to re-preempt in case of any races
1696 if notetsleep(&sched.stopnote, 100*1000) {
1697 noteclear(&sched.stopnote)
1698 break
1699 }
1700 preemptall()
1701 }
1702 }
1703
1704 finish := nanotime()
1705 startTime := finish - start
1706 if reason.isGC() {
1707 sched.stwStoppingTimeGC.record(startTime)
1708 } else {
1709 sched.stwStoppingTimeOther.record(startTime)
1710 }
1711
1712 // Double-check we actually stopped everything, and all the invariants hold.
1713 // Also accumulate all the time spent by each P in _Pgcstop up to the point
1714 // where everything was stopped. This will be accumulated into the total pause
1715 // CPU time by the caller.
1716 stoppingCPUTime := int64(0)
1717 bad := ""
1718 if sched.stopwait != 0 {
1719 bad = "stopTheWorld: not stopped (stopwait != 0)"
1720 } else {
1721 for _, pp := range allp {
1722 if pp.status != _Pgcstop {
1723 bad = "stopTheWorld: not stopped (status != _Pgcstop)"
1724 }
1725 if pp.gcStopTime == 0 && bad == "" {
1726 bad = "stopTheWorld: broken CPU time accounting"
1727 }
1728 stoppingCPUTime += finish - pp.gcStopTime
1729 pp.gcStopTime = 0
1730 }
1731 }
1732 if freezing.Load() {
1733 // Some other thread is panicking. This can cause the
1734 // sanity checks above to fail if the panic happens in
1735 // the signal handler on a stopped thread. Either way,
1736 // we should halt this thread.
1737 lock(&deadlock)
1738 lock(&deadlock)
1739 }
1740 if bad != "" {
1741 throw(bad)
1742 }
1743
1744 worldStopped()
1745
1746 // Switch back to _Grunning, now that the world is stopped.
1747 casgstatus(getg().m.curg, _Gwaiting, _Grunning)
1748
1749 return worldStop{
1750 reason: reason,
1751 startedStopping: start,
1752 finishedStopping: finish,
1753 stoppingCPUTime: stoppingCPUTime,
1754 }
1755 }
1756
1757 // reason is the same STW reason passed to stopTheWorld. start is the start
1758 // time returned by stopTheWorld.
1759 //
1760 // now is the current time; prefer to pass 0 to capture a fresh timestamp.
1761 //
1762 // stattTheWorldWithSema returns now.
1763 func startTheWorldWithSema(now int64, w worldStop) int64 {
1764 assertWorldStopped()
1765
1766 mp := acquirem() // disable preemption because it can be holding p in a local var
1767 if netpollinited() {
1768 list, delta := netpoll(0) // non-blocking
1769 injectglist(&list)
1770 netpollAdjustWaiters(delta)
1771 }
1772 lock(&sched.lock)
1773
1774 procs := gomaxprocs
1775 if newprocs != 0 {
1776 procs = newprocs
1777 newprocs = 0
1778 }
1779 p1 := procresize(procs)
1780 sched.gcwaiting.Store(false)
1781 if sched.sysmonwait.Load() {
1782 sched.sysmonwait.Store(false)
1783 notewakeup(&sched.sysmonnote)
1784 }
1785 unlock(&sched.lock)
1786
1787 worldStarted()
1788
1789 for p1 != nil {
1790 p := p1
1791 p1 = p1.link.ptr()
1792 if p.m != 0 {
1793 mp := p.m.ptr()
1794 p.m = 0
1795 if mp.nextp != 0 {
1796 throw("startTheWorld: inconsistent mp->nextp")
1797 }
1798 mp.nextp.set(p)
1799 notewakeup(&mp.park)
1800 } else {
1801 // Start M to run P. Do not start another M below.
1802 newm(nil, p, -1)
1803 }
1804 }
1805
1806 // Capture start-the-world time before doing clean-up tasks.
1807 if now == 0 {
1808 now = nanotime()
1809 }
1810 totalTime := now - w.startedStopping
1811 if w.reason.isGC() {
1812 sched.stwTotalTimeGC.record(totalTime)
1813 } else {
1814 sched.stwTotalTimeOther.record(totalTime)
1815 }
1816 trace := traceAcquire()
1817 if trace.ok() {
1818 trace.STWDone()
1819 traceRelease(trace)
1820 }
1821
1822 // Wakeup an additional proc in case we have excessive runnable goroutines
1823 // in local queues or in the global queue. If we don't, the proc will park itself.
1824 // If we have lots of excessive work, resetspinning will unpark additional procs as necessary.
1825 wakep()
1826
1827 releasem(mp)
1828
1829 return now
1830 }
1831
1832 // usesLibcall indicates whether this runtime performs system calls
1833 // via libcall.
1834 func usesLibcall() bool {
1835 switch GOOS {
1836 case "aix", "darwin", "illumos", "ios", "solaris", "windows":
1837 return true
1838 case "openbsd":
1839 return GOARCH != "mips64"
1840 }
1841 return false
1842 }
1843
1844 // mStackIsSystemAllocated indicates whether this runtime starts on a
1845 // system-allocated stack.
1846 func mStackIsSystemAllocated() bool {
1847 switch GOOS {
1848 case "aix", "darwin", "plan9", "illumos", "ios", "solaris", "windows":
1849 return true
1850 case "openbsd":
1851 return GOARCH != "mips64"
1852 }
1853 return false
1854 }
1855
1856 // mstart is the entry-point for new Ms.
1857 // It is written in assembly, uses ABI0, is marked TOPFRAME, and calls mstart0.
1858 func mstart()
1859
1860 // mstart0 is the Go entry-point for new Ms.
1861 // This must not split the stack because we may not even have stack
1862 // bounds set up yet.
1863 //
1864 // May run during STW (because it doesn't have a P yet), so write
1865 // barriers are not allowed.
1866 //
1867 //go:nosplit
1868 //go:nowritebarrierrec
1869 func mstart0() {
1870 gp := getg()
1871
1872 osStack := gp.stack.lo == 0
1873 if osStack {
1874 // Initialize stack bounds from system stack.
1875 // Cgo may have left stack size in stack.hi.
1876 // minit may update the stack bounds.
1877 //
1878 // Note: these bounds may not be very accurate.
1879 // We set hi to &size, but there are things above
1880 // it. The 1024 is supposed to compensate this,
1881 // but is somewhat arbitrary.
1882 size := gp.stack.hi
1883 if size == 0 {
1884 size = 16384 * sys.StackGuardMultiplier
1885 }
1886 gp.stack.hi = uintptr(noescape(unsafe.Pointer(&size)))
1887 gp.stack.lo = gp.stack.hi - size + 1024
1888 }
1889 // Initialize stack guard so that we can start calling regular
1890 // Go code.
1891 gp.stackguard0 = gp.stack.lo + stackGuard
1892 // This is the g0, so we can also call go:systemstack
1893 // functions, which check stackguard1.
1894 gp.stackguard1 = gp.stackguard0
1895 mstart1()
1896
1897 // Exit this thread.
1898 if mStackIsSystemAllocated() {
1899 // Windows, Solaris, illumos, Darwin, AIX and Plan 9 always system-allocate
1900 // the stack, but put it in gp.stack before mstart,
1901 // so the logic above hasn't set osStack yet.
1902 osStack = true
1903 }
1904 mexit(osStack)
1905 }
1906
1907 // The go:noinline is to guarantee the sys.GetCallerPC/sys.GetCallerSP below are safe,
1908 // so that we can set up g0.sched to return to the call of mstart1 above.
1909 //
1910 //go:noinline
1911 func mstart1() {
1912 gp := getg()
1913
1914 if gp != gp.m.g0 {
1915 throw("bad runtime·mstart")
1916 }
1917
1918 // Set up m.g0.sched as a label returning to just
1919 // after the mstart1 call in mstart0 above, for use by goexit0 and mcall.
1920 // We're never coming back to mstart1 after we call schedule,
1921 // so other calls can reuse the current frame.
1922 // And goexit0 does a gogo that needs to return from mstart1
1923 // and let mstart0 exit the thread.
1924 gp.sched.g = guintptr(unsafe.Pointer(gp))
1925 gp.sched.pc = sys.GetCallerPC()
1926 gp.sched.sp = sys.GetCallerSP()
1927
1928 asminit()
1929 minit()
1930
1931 // Install signal handlers; after minit so that minit can
1932 // prepare the thread to be able to handle the signals.
1933 if gp.m == &m0 {
1934 mstartm0()
1935 }
1936
1937 if debug.dataindependenttiming == 1 {
1938 sys.EnableDIT()
1939 }
1940
1941 if fn := gp.m.mstartfn; fn != nil {
1942 fn()
1943 }
1944
1945 if gp.m != &m0 {
1946 acquirep(gp.m.nextp.ptr())
1947 gp.m.nextp = 0
1948 }
1949 schedule()
1950 }
1951
1952 // mstartm0 implements part of mstart1 that only runs on the m0.
1953 //
1954 // Write barriers are allowed here because we know the GC can't be
1955 // running yet, so they'll be no-ops.
1956 //
1957 //go:yeswritebarrierrec
1958 func mstartm0() {
1959 // Create an extra M for callbacks on threads not created by Go.
1960 // An extra M is also needed on Windows for callbacks created by
1961 // syscall.NewCallback. See issue #6751 for details.
1962 if (iscgo || GOOS == "windows") && !cgoHasExtraM {
1963 cgoHasExtraM = true
1964 newextram()
1965 }
1966 initsig(false)
1967 }
1968
1969 // mPark causes a thread to park itself, returning once woken.
1970 //
1971 //go:nosplit
1972 func mPark() {
1973 gp := getg()
1974 notesleep(&gp.m.park)
1975 noteclear(&gp.m.park)
1976 }
1977
1978 // mexit tears down and exits the current thread.
1979 //
1980 // Don't call this directly to exit the thread, since it must run at
1981 // the top of the thread stack. Instead, use gogo(&gp.m.g0.sched) to
1982 // unwind the stack to the point that exits the thread.
1983 //
1984 // It is entered with m.p != nil, so write barriers are allowed. It
1985 // will release the P before exiting.
1986 //
1987 //go:yeswritebarrierrec
1988 func mexit(osStack bool) {
1989 mp := getg().m
1990
1991 if mp == &m0 {
1992 // This is the main thread. Just wedge it.
1993 //
1994 // On Linux, exiting the main thread puts the process
1995 // into a non-waitable zombie state. On Plan 9,
1996 // exiting the main thread unblocks wait even though
1997 // other threads are still running. On Solaris we can
1998 // neither exitThread nor return from mstart. Other
1999 // bad things probably happen on other platforms.
2000 //
2001 // We could try to clean up this M more before wedging
2002 // it, but that complicates signal handling.
2003 handoffp(releasep())
2004 lock(&sched.lock)
2005 sched.nmfreed++
2006 checkdead()
2007 unlock(&sched.lock)
2008 mPark()
2009 throw("locked m0 woke up")
2010 }
2011
2012 sigblock(true)
2013 unminit()
2014
2015 // Free the gsignal stack.
2016 if mp.gsignal != nil {
2017 stackfree(mp.gsignal.stack)
2018 if valgrindenabled {
2019 valgrindDeregisterStack(mp.gsignal.valgrindStackID)
2020 mp.gsignal.valgrindStackID = 0
2021 }
2022 // On some platforms, when calling into VDSO (e.g. nanotime)
2023 // we store our g on the gsignal stack, if there is one.
2024 // Now the stack is freed, unlink it from the m, so we
2025 // won't write to it when calling VDSO code.
2026 mp.gsignal = nil
2027 }
2028
2029 // Free vgetrandom state.
2030 vgetrandomDestroy(mp)
2031
2032 // Remove m from allm.
2033 lock(&sched.lock)
2034 for pprev := &allm; *pprev != nil; pprev = &(*pprev).alllink {
2035 if *pprev == mp {
2036 *pprev = mp.alllink
2037 goto found
2038 }
2039 }
2040 throw("m not found in allm")
2041 found:
2042 // Events must not be traced after this point.
2043
2044 // Delay reaping m until it's done with the stack.
2045 //
2046 // Put mp on the free list, though it will not be reaped while freeWait
2047 // is freeMWait. mp is no longer reachable via allm, so even if it is
2048 // on an OS stack, we must keep a reference to mp alive so that the GC
2049 // doesn't free mp while we are still using it.
2050 //
2051 // Note that the free list must not be linked through alllink because
2052 // some functions walk allm without locking, so may be using alllink.
2053 //
2054 // N.B. It's important that the M appears on the free list simultaneously
2055 // with it being removed so that the tracer can find it.
2056 mp.freeWait.Store(freeMWait)
2057 mp.freelink = sched.freem
2058 sched.freem = mp
2059 unlock(&sched.lock)
2060
2061 atomic.Xadd64(&ncgocall, int64(mp.ncgocall))
2062 sched.totalRuntimeLockWaitTime.Add(mp.mLockProfile.waitTime.Load())
2063
2064 // Release the P.
2065 handoffp(releasep())
2066 // After this point we must not have write barriers.
2067
2068 // Invoke the deadlock detector. This must happen after
2069 // handoffp because it may have started a new M to take our
2070 // P's work.
2071 lock(&sched.lock)
2072 sched.nmfreed++
2073 checkdead()
2074 unlock(&sched.lock)
2075
2076 if GOOS == "darwin" || GOOS == "ios" {
2077 // Make sure pendingPreemptSignals is correct when an M exits.
2078 // For #41702.
2079 if mp.signalPending.Load() != 0 {
2080 pendingPreemptSignals.Add(-1)
2081 }
2082 }
2083
2084 // Destroy all allocated resources. After this is called, we may no
2085 // longer take any locks.
2086 mdestroy(mp)
2087
2088 if osStack {
2089 // No more uses of mp, so it is safe to drop the reference.
2090 mp.freeWait.Store(freeMRef)
2091
2092 // Return from mstart and let the system thread
2093 // library free the g0 stack and terminate the thread.
2094 return
2095 }
2096
2097 // mstart is the thread's entry point, so there's nothing to
2098 // return to. Exit the thread directly. exitThread will clear
2099 // m.freeWait when it's done with the stack and the m can be
2100 // reaped.
2101 exitThread(&mp.freeWait)
2102 }
2103
2104 // forEachP calls fn(p) for every P p when p reaches a GC safe point.
2105 // If a P is currently executing code, this will bring the P to a GC
2106 // safe point and execute fn on that P. If the P is not executing code
2107 // (it is idle or in a syscall), this will call fn(p) directly while
2108 // preventing the P from exiting its state. This does not ensure that
2109 // fn will run on every CPU executing Go code, but it acts as a global
2110 // memory barrier. GC uses this as a "ragged barrier."
2111 //
2112 // The caller must hold worldsema. fn must not refer to any
2113 // part of the current goroutine's stack, since the GC may move it.
2114 func forEachP(reason waitReason, fn func(*p)) {
2115 systemstack(func() {
2116 gp := getg().m.curg
2117 // Mark the user stack as preemptible so that it may be scanned
2118 // by the GC or observed by the execution tracer. Otherwise, our
2119 // attempt to force all P's to a safepoint could result in a
2120 // deadlock as we attempt to preempt a goroutine that's trying
2121 // to preempt us (e.g. for a stack scan).
2122 //
2123 // We must not modify anything on the G stack because a stack shrink
2124 // may occur. A stack shrink is otherwise OK though because in order
2125 // to return from this function (and to leave the system stack) we
2126 // must have preempted all goroutines, including any attempting
2127 // to scan our stack, in which case, any stack shrinking will
2128 // have already completed by the time we exit.
2129 //
2130 // N.B. The execution tracer is not aware of this status
2131 // transition and handles it specially based on the
2132 // wait reason.
2133 casGToWaitingForSuspendG(gp, _Grunning, reason)
2134 forEachPInternal(fn)
2135 casgstatus(gp, _Gwaiting, _Grunning)
2136 })
2137 }
2138
2139 // forEachPInternal calls fn(p) for every P p when p reaches a GC safe point.
2140 // It is the internal implementation of forEachP.
2141 //
2142 // The caller must hold worldsema and either must ensure that a GC is not
2143 // running (otherwise this may deadlock with the GC trying to preempt this P)
2144 // or it must leave its goroutine in a preemptible state before it switches
2145 // to the systemstack. Due to these restrictions, prefer forEachP when possible.
2146 //
2147 //go:systemstack
2148 func forEachPInternal(fn func(*p)) {
2149 mp := acquirem()
2150 pp := getg().m.p.ptr()
2151
2152 lock(&sched.lock)
2153 if sched.safePointWait != 0 {
2154 throw("forEachP: sched.safePointWait != 0")
2155 }
2156 sched.safePointWait = gomaxprocs - 1
2157 sched.safePointFn = fn
2158
2159 // Ask all Ps to run the safe point function.
2160 for _, p2 := range allp {
2161 if p2 != pp {
2162 atomic.Store(&p2.runSafePointFn, 1)
2163 }
2164 }
2165 preemptall()
2166
2167 // Any P entering _Pidle or _Psyscall from now on will observe
2168 // p.runSafePointFn == 1 and will call runSafePointFn when
2169 // changing its status to _Pidle/_Psyscall.
2170
2171 // Run safe point function for all idle Ps. sched.pidle will
2172 // not change because we hold sched.lock.
2173 for p := sched.pidle.ptr(); p != nil; p = p.link.ptr() {
2174 if atomic.Cas(&p.runSafePointFn, 1, 0) {
2175 fn(p)
2176 sched.safePointWait--
2177 }
2178 }
2179
2180 wait := sched.safePointWait > 0
2181 unlock(&sched.lock)
2182
2183 // Run fn for the current P.
2184 fn(pp)
2185
2186 // Force Ps currently in _Psyscall into _Pidle and hand them
2187 // off to induce safe point function execution.
2188 for _, p2 := range allp {
2189 s := p2.status
2190
2191 // We need to be fine-grained about tracing here, since handoffp
2192 // might call into the tracer, and the tracer is non-reentrant.
2193 trace := traceAcquire()
2194 if s == _Psyscall && p2.runSafePointFn == 1 && atomic.Cas(&p2.status, s, _Pidle) {
2195 if trace.ok() {
2196 // It's important that we traceRelease before we call handoffp, which may also traceAcquire.
2197 trace.ProcSteal(p2, false)
2198 traceRelease(trace)
2199 }
2200 p2.syscalltick++
2201 handoffp(p2)
2202 } else if trace.ok() {
2203 traceRelease(trace)
2204 }
2205 }
2206
2207 // Wait for remaining Ps to run fn.
2208 if wait {
2209 for {
2210 // Wait for 100us, then try to re-preempt in
2211 // case of any races.
2212 //
2213 // Requires system stack.
2214 if notetsleep(&sched.safePointNote, 100*1000) {
2215 noteclear(&sched.safePointNote)
2216 break
2217 }
2218 preemptall()
2219 }
2220 }
2221 if sched.safePointWait != 0 {
2222 throw("forEachP: not done")
2223 }
2224 for _, p2 := range allp {
2225 if p2.runSafePointFn != 0 {
2226 throw("forEachP: P did not run fn")
2227 }
2228 }
2229
2230 lock(&sched.lock)
2231 sched.safePointFn = nil
2232 unlock(&sched.lock)
2233 releasem(mp)
2234 }
2235
2236 // runSafePointFn runs the safe point function, if any, for this P.
2237 // This should be called like
2238 //
2239 // if getg().m.p.runSafePointFn != 0 {
2240 // runSafePointFn()
2241 // }
2242 //
2243 // runSafePointFn must be checked on any transition in to _Pidle or
2244 // _Psyscall to avoid a race where forEachP sees that the P is running
2245 // just before the P goes into _Pidle/_Psyscall and neither forEachP
2246 // nor the P run the safe-point function.
2247 func runSafePointFn() {
2248 p := getg().m.p.ptr()
2249 // Resolve the race between forEachP running the safe-point
2250 // function on this P's behalf and this P running the
2251 // safe-point function directly.
2252 if !atomic.Cas(&p.runSafePointFn, 1, 0) {
2253 return
2254 }
2255 sched.safePointFn(p)
2256 lock(&sched.lock)
2257 sched.safePointWait--
2258 if sched.safePointWait == 0 {
2259 notewakeup(&sched.safePointNote)
2260 }
2261 unlock(&sched.lock)
2262 }
2263
2264 // When running with cgo, we call _cgo_thread_start
2265 // to start threads for us so that we can play nicely with
2266 // foreign code.
2267 var cgoThreadStart unsafe.Pointer
2268
2269 type cgothreadstart struct {
2270 g guintptr
2271 tls *uint64
2272 fn unsafe.Pointer
2273 }
2274
2275 // Allocate a new m unassociated with any thread.
2276 // Can use p for allocation context if needed.
2277 // fn is recorded as the new m's m.mstartfn.
2278 // id is optional pre-allocated m ID. Omit by passing -1.
2279 //
2280 // This function is allowed to have write barriers even if the caller
2281 // isn't because it borrows pp.
2282 //
2283 //go:yeswritebarrierrec
2284 func allocm(pp *p, fn func(), id int64) *m {
2285 allocmLock.rlock()
2286
2287 // The caller owns pp, but we may borrow (i.e., acquirep) it. We must
2288 // disable preemption to ensure it is not stolen, which would make the
2289 // caller lose ownership.
2290 acquirem()
2291
2292 gp := getg()
2293 if gp.m.p == 0 {
2294 acquirep(pp) // temporarily borrow p for mallocs in this function
2295 }
2296
2297 // Release the free M list. We need to do this somewhere and
2298 // this may free up a stack we can use.
2299 if sched.freem != nil {
2300 lock(&sched.lock)
2301 var newList *m
2302 for freem := sched.freem; freem != nil; {
2303 // Wait for freeWait to indicate that freem's stack is unused.
2304 wait := freem.freeWait.Load()
2305 if wait == freeMWait {
2306 next := freem.freelink
2307 freem.freelink = newList
2308 newList = freem
2309 freem = next
2310 continue
2311 }
2312 // Drop any remaining trace resources.
2313 // Ms can continue to emit events all the way until wait != freeMWait,
2314 // so it's only safe to call traceThreadDestroy at this point.
2315 if traceEnabled() || traceShuttingDown() {
2316 traceThreadDestroy(freem)
2317 }
2318 // Free the stack if needed. For freeMRef, there is
2319 // nothing to do except drop freem from the sched.freem
2320 // list.
2321 if wait == freeMStack {
2322 // stackfree must be on the system stack, but allocm is
2323 // reachable off the system stack transitively from
2324 // startm.
2325 systemstack(func() {
2326 stackfree(freem.g0.stack)
2327 if valgrindenabled {
2328 valgrindDeregisterStack(freem.g0.valgrindStackID)
2329 freem.g0.valgrindStackID = 0
2330 }
2331 })
2332 }
2333 freem = freem.freelink
2334 }
2335 sched.freem = newList
2336 unlock(&sched.lock)
2337 }
2338
2339 mp := &new(mPadded).m
2340 mp.mstartfn = fn
2341 mcommoninit(mp, id)
2342
2343 // In case of cgo or Solaris or illumos or Darwin, pthread_create will make us a stack.
2344 // Windows and Plan 9 will layout sched stack on OS stack.
2345 if iscgo || mStackIsSystemAllocated() {
2346 mp.g0 = malg(-1)
2347 } else {
2348 mp.g0 = malg(16384 * sys.StackGuardMultiplier)
2349 }
2350 mp.g0.m = mp
2351
2352 if pp == gp.m.p.ptr() {
2353 releasep()
2354 }
2355
2356 releasem(gp.m)
2357 allocmLock.runlock()
2358 return mp
2359 }
2360
2361 // needm is called when a cgo callback happens on a
2362 // thread without an m (a thread not created by Go).
2363 // In this case, needm is expected to find an m to use
2364 // and return with m, g initialized correctly.
2365 // Since m and g are not set now (likely nil, but see below)
2366 // needm is limited in what routines it can call. In particular
2367 // it can only call nosplit functions (textflag 7) and cannot
2368 // do any scheduling that requires an m.
2369 //
2370 // In order to avoid needing heavy lifting here, we adopt
2371 // the following strategy: there is a stack of available m's
2372 // that can be stolen. Using compare-and-swap
2373 // to pop from the stack has ABA races, so we simulate
2374 // a lock by doing an exchange (via Casuintptr) to steal the stack
2375 // head and replace the top pointer with MLOCKED (1).
2376 // This serves as a simple spin lock that we can use even
2377 // without an m. The thread that locks the stack in this way
2378 // unlocks the stack by storing a valid stack head pointer.
2379 //
2380 // In order to make sure that there is always an m structure
2381 // available to be stolen, we maintain the invariant that there
2382 // is always one more than needed. At the beginning of the
2383 // program (if cgo is in use) the list is seeded with a single m.
2384 // If needm finds that it has taken the last m off the list, its job
2385 // is - once it has installed its own m so that it can do things like
2386 // allocate memory - to create a spare m and put it on the list.
2387 //
2388 // Each of these extra m's also has a g0 and a curg that are
2389 // pressed into service as the scheduling stack and current
2390 // goroutine for the duration of the cgo callback.
2391 //
2392 // It calls dropm to put the m back on the list,
2393 // 1. when the callback is done with the m in non-pthread platforms,
2394 // 2. or when the C thread exiting on pthread platforms.
2395 //
2396 // The signal argument indicates whether we're called from a signal
2397 // handler.
2398 //
2399 //go:nosplit
2400 func needm(signal bool) {
2401 if (iscgo || GOOS == "windows") && !cgoHasExtraM {
2402 // Can happen if C/C++ code calls Go from a global ctor.
2403 // Can also happen on Windows if a global ctor uses a
2404 // callback created by syscall.NewCallback. See issue #6751
2405 // for details.
2406 //
2407 // Can not throw, because scheduler is not initialized yet.
2408 writeErrStr("fatal error: cgo callback before cgo call\n")
2409 exit(1)
2410 }
2411
2412 // Save and block signals before getting an M.
2413 // The signal handler may call needm itself,
2414 // and we must avoid a deadlock. Also, once g is installed,
2415 // any incoming signals will try to execute,
2416 // but we won't have the sigaltstack settings and other data
2417 // set up appropriately until the end of minit, which will
2418 // unblock the signals. This is the same dance as when
2419 // starting a new m to run Go code via newosproc.
2420 var sigmask sigset
2421 sigsave(&sigmask)
2422 sigblock(false)
2423
2424 // getExtraM is safe here because of the invariant above,
2425 // that the extra list always contains or will soon contain
2426 // at least one m.
2427 mp, last := getExtraM()
2428
2429 // Set needextram when we've just emptied the list,
2430 // so that the eventual call into cgocallbackg will
2431 // allocate a new m for the extra list. We delay the
2432 // allocation until then so that it can be done
2433 // after exitsyscall makes sure it is okay to be
2434 // running at all (that is, there's no garbage collection
2435 // running right now).
2436 mp.needextram = last
2437
2438 // Store the original signal mask for use by minit.
2439 mp.sigmask = sigmask
2440
2441 // Install TLS on some platforms (previously setg
2442 // would do this if necessary).
2443 osSetupTLS(mp)
2444
2445 // Install g (= m->g0) and set the stack bounds
2446 // to match the current stack.
2447 setg(mp.g0)
2448 sp := sys.GetCallerSP()
2449 callbackUpdateSystemStack(mp, sp, signal)
2450
2451 // Should mark we are already in Go now.
2452 // Otherwise, we may call needm again when we get a signal, before cgocallbackg1,
2453 // which means the extram list may be empty, that will cause a deadlock.
2454 mp.isExtraInC = false
2455
2456 // Initialize this thread to use the m.
2457 asminit()
2458 minit()
2459
2460 // Emit a trace event for this dead -> syscall transition,
2461 // but only if we're not in a signal handler.
2462 //
2463 // N.B. the tracer can run on a bare M just fine, we just have
2464 // to make sure to do this before setg(nil) and unminit.
2465 var trace traceLocker
2466 if !signal {
2467 trace = traceAcquire()
2468 }
2469
2470 // mp.curg is now a real goroutine.
2471 casgstatus(mp.curg, _Gdead, _Gsyscall)
2472 sched.ngsys.Add(-1)
2473
2474 if !signal {
2475 if trace.ok() {
2476 trace.GoCreateSyscall(mp.curg)
2477 traceRelease(trace)
2478 }
2479 }
2480 mp.isExtraInSig = signal
2481 }
2482
2483 // Acquire an extra m and bind it to the C thread when a pthread key has been created.
2484 //
2485 //go:nosplit
2486 func needAndBindM() {
2487 needm(false)
2488
2489 if _cgo_pthread_key_created != nil && *(*uintptr)(_cgo_pthread_key_created) != 0 {
2490 cgoBindM()
2491 }
2492 }
2493
2494 // newextram allocates m's and puts them on the extra list.
2495 // It is called with a working local m, so that it can do things
2496 // like call schedlock and allocate.
2497 func newextram() {
2498 c := extraMWaiters.Swap(0)
2499 if c > 0 {
2500 for i := uint32(0); i < c; i++ {
2501 oneNewExtraM()
2502 }
2503 } else if extraMLength.Load() == 0 {
2504 // Make sure there is at least one extra M.
2505 oneNewExtraM()
2506 }
2507 }
2508
2509 // oneNewExtraM allocates an m and puts it on the extra list.
2510 func oneNewExtraM() {
2511 // Create extra goroutine locked to extra m.
2512 // The goroutine is the context in which the cgo callback will run.
2513 // The sched.pc will never be returned to, but setting it to
2514 // goexit makes clear to the traceback routines where
2515 // the goroutine stack ends.
2516 mp := allocm(nil, nil, -1)
2517 gp := malg(4096)
2518 gp.sched.pc = abi.FuncPCABI0(goexit) + sys.PCQuantum
2519 gp.sched.sp = gp.stack.hi
2520 gp.sched.sp -= 4 * goarch.PtrSize // extra space in case of reads slightly beyond frame
2521 gp.sched.lr = 0
2522 gp.sched.g = guintptr(unsafe.Pointer(gp))
2523 gp.syscallpc = gp.sched.pc
2524 gp.syscallsp = gp.sched.sp
2525 gp.stktopsp = gp.sched.sp
2526 // malg returns status as _Gidle. Change to _Gdead before
2527 // adding to allg where GC can see it. We use _Gdead to hide
2528 // this from tracebacks and stack scans since it isn't a
2529 // "real" goroutine until needm grabs it.
2530 casgstatus(gp, _Gidle, _Gdead)
2531 gp.m = mp
2532 mp.curg = gp
2533 mp.isextra = true
2534 // mark we are in C by default.
2535 mp.isExtraInC = true
2536 mp.lockedInt++
2537 mp.lockedg.set(gp)
2538 gp.lockedm.set(mp)
2539 gp.goid = sched.goidgen.Add(1)
2540 if raceenabled {
2541 gp.racectx = racegostart(abi.FuncPCABIInternal(newextram) + sys.PCQuantum)
2542 }
2543 // put on allg for garbage collector
2544 allgadd(gp)
2545
2546 // gp is now on the allg list, but we don't want it to be
2547 // counted by gcount. It would be more "proper" to increment
2548 // sched.ngfree, but that requires locking. Incrementing ngsys
2549 // has the same effect.
2550 sched.ngsys.Add(1)
2551
2552 // Add m to the extra list.
2553 addExtraM(mp)
2554 }
2555
2556 // dropm puts the current m back onto the extra list.
2557 //
2558 // 1. On systems without pthreads, like Windows
2559 // dropm is called when a cgo callback has called needm but is now
2560 // done with the callback and returning back into the non-Go thread.
2561 //
2562 // The main expense here is the call to signalstack to release the
2563 // m's signal stack, and then the call to needm on the next callback
2564 // from this thread. It is tempting to try to save the m for next time,
2565 // which would eliminate both these costs, but there might not be
2566 // a next time: the current thread (which Go does not control) might exit.
2567 // If we saved the m for that thread, there would be an m leak each time
2568 // such a thread exited. Instead, we acquire and release an m on each
2569 // call. These should typically not be scheduling operations, just a few
2570 // atomics, so the cost should be small.
2571 //
2572 // 2. On systems with pthreads
2573 // dropm is called while a non-Go thread is exiting.
2574 // We allocate a pthread per-thread variable using pthread_key_create,
2575 // to register a thread-exit-time destructor.
2576 // And store the g into a thread-specific value associated with the pthread key,
2577 // when first return back to C.
2578 // So that the destructor would invoke dropm while the non-Go thread is exiting.
2579 // This is much faster since it avoids expensive signal-related syscalls.
2580 //
2581 // This always runs without a P, so //go:nowritebarrierrec is required.
2582 //
2583 // This may run with a different stack than was recorded in g0 (there is no
2584 // call to callbackUpdateSystemStack prior to dropm), so this must be
2585 // //go:nosplit to avoid the stack bounds check.
2586 //
2587 //go:nowritebarrierrec
2588 //go:nosplit
2589 func dropm() {
2590 // Clear m and g, and return m to the extra list.
2591 // After the call to setg we can only call nosplit functions
2592 // with no pointer manipulation.
2593 mp := getg().m
2594
2595 // Emit a trace event for this syscall -> dead transition.
2596 //
2597 // N.B. the tracer can run on a bare M just fine, we just have
2598 // to make sure to do this before setg(nil) and unminit.
2599 var trace traceLocker
2600 if !mp.isExtraInSig {
2601 trace = traceAcquire()
2602 }
2603
2604 // Return mp.curg to dead state.
2605 casgstatus(mp.curg, _Gsyscall, _Gdead)
2606 mp.curg.preemptStop = false
2607 sched.ngsys.Add(1)
2608
2609 if !mp.isExtraInSig {
2610 if trace.ok() {
2611 trace.GoDestroySyscall()
2612 traceRelease(trace)
2613 }
2614 }
2615
2616 // Trash syscalltick so that it doesn't line up with mp.old.syscalltick anymore.
2617 //
2618 // In the new tracer, we model needm and dropm and a goroutine being created and
2619 // destroyed respectively. The m then might get reused with a different procid but
2620 // still with a reference to oldp, and still with the same syscalltick. The next
2621 // time a G is "created" in needm, it'll return and quietly reacquire its P from a
2622 // different m with a different procid, which will confuse the trace parser. By
2623 // trashing syscalltick, we ensure that it'll appear as if we lost the P to the
2624 // tracer parser and that we just reacquired it.
2625 //
2626 // Trash the value by decrementing because that gets us as far away from the value
2627 // the syscall exit code expects as possible. Setting to zero is risky because
2628 // syscalltick could already be zero (and in fact, is initialized to zero).
2629 mp.syscalltick--
2630
2631 // Reset trace state unconditionally. This goroutine is being 'destroyed'
2632 // from the perspective of the tracer.
2633 mp.curg.trace.reset()
2634
2635 // Flush all the M's buffers. This is necessary because the M might
2636 // be used on a different thread with a different procid, so we have
2637 // to make sure we don't write into the same buffer.
2638 if traceEnabled() || traceShuttingDown() {
2639 // Acquire sched.lock across thread destruction. One of the invariants of the tracer
2640 // is that a thread cannot disappear from the tracer's view (allm or freem) without
2641 // it noticing, so it requires that sched.lock be held over traceThreadDestroy.
2642 //
2643 // This isn't strictly necessary in this case, because this thread never leaves allm,
2644 // but the critical section is short and dropm is rare on pthread platforms, so just
2645 // take the lock and play it safe. traceThreadDestroy also asserts that the lock is held.
2646 lock(&sched.lock)
2647 traceThreadDestroy(mp)
2648 unlock(&sched.lock)
2649 }
2650 mp.isExtraInSig = false
2651
2652 // Block signals before unminit.
2653 // Unminit unregisters the signal handling stack (but needs g on some systems).
2654 // Setg(nil) clears g, which is the signal handler's cue not to run Go handlers.
2655 // It's important not to try to handle a signal between those two steps.
2656 sigmask := mp.sigmask
2657 sigblock(false)
2658 unminit()
2659
2660 setg(nil)
2661
2662 // Clear g0 stack bounds to ensure that needm always refreshes the
2663 // bounds when reusing this M.
2664 g0 := mp.g0
2665 g0.stack.hi = 0
2666 g0.stack.lo = 0
2667 g0.stackguard0 = 0
2668 g0.stackguard1 = 0
2669 mp.g0StackAccurate = false
2670
2671 putExtraM(mp)
2672
2673 msigrestore(sigmask)
2674 }
2675
2676 // bindm store the g0 of the current m into a thread-specific value.
2677 //
2678 // We allocate a pthread per-thread variable using pthread_key_create,
2679 // to register a thread-exit-time destructor.
2680 // We are here setting the thread-specific value of the pthread key, to enable the destructor.
2681 // So that the pthread_key_destructor would dropm while the C thread is exiting.
2682 //
2683 // And the saved g will be used in pthread_key_destructor,
2684 // since the g stored in the TLS by Go might be cleared in some platforms,
2685 // before the destructor invoked, so, we restore g by the stored g, before dropm.
2686 //
2687 // We store g0 instead of m, to make the assembly code simpler,
2688 // since we need to restore g0 in runtime.cgocallback.
2689 //
2690 // On systems without pthreads, like Windows, bindm shouldn't be used.
2691 //
2692 // NOTE: this always runs without a P, so, nowritebarrierrec required.
2693 //
2694 //go:nosplit
2695 //go:nowritebarrierrec
2696 func cgoBindM() {
2697 if GOOS == "windows" || GOOS == "plan9" {
2698 fatal("bindm in unexpected GOOS")
2699 }
2700 g := getg()
2701 if g.m.g0 != g {
2702 fatal("the current g is not g0")
2703 }
2704 if _cgo_bindm != nil {
2705 asmcgocall(_cgo_bindm, unsafe.Pointer(g))
2706 }
2707 }
2708
2709 // A helper function for EnsureDropM.
2710 //
2711 // getm should be an internal detail,
2712 // but widely used packages access it using linkname.
2713 // Notable members of the hall of shame include:
2714 // - fortio.org/log
2715 //
2716 // Do not remove or change the type signature.
2717 // See go.dev/issue/67401.
2718 //
2719 //go:linkname getm
2720 func getm() uintptr {
2721 return uintptr(unsafe.Pointer(getg().m))
2722 }
2723
2724 var (
2725 // Locking linked list of extra M's, via mp.schedlink. Must be accessed
2726 // only via lockextra/unlockextra.
2727 //
2728 // Can't be atomic.Pointer[m] because we use an invalid pointer as a
2729 // "locked" sentinel value. M's on this list remain visible to the GC
2730 // because their mp.curg is on allgs.
2731 extraM atomic.Uintptr
2732 // Number of M's in the extraM list.
2733 extraMLength atomic.Uint32
2734 // Number of waiters in lockextra.
2735 extraMWaiters atomic.Uint32
2736
2737 // Number of extra M's in use by threads.
2738 extraMInUse atomic.Uint32
2739 )
2740
2741 // lockextra locks the extra list and returns the list head.
2742 // The caller must unlock the list by storing a new list head
2743 // to extram. If nilokay is true, then lockextra will
2744 // return a nil list head if that's what it finds. If nilokay is false,
2745 // lockextra will keep waiting until the list head is no longer nil.
2746 //
2747 //go:nosplit
2748 func lockextra(nilokay bool) *m {
2749 const locked = 1
2750
2751 incr := false
2752 for {
2753 old := extraM.Load()
2754 if old == locked {
2755 osyield_no_g()
2756 continue
2757 }
2758 if old == 0 && !nilokay {
2759 if !incr {
2760 // Add 1 to the number of threads
2761 // waiting for an M.
2762 // This is cleared by newextram.
2763 extraMWaiters.Add(1)
2764 incr = true
2765 }
2766 usleep_no_g(1)
2767 continue
2768 }
2769 if extraM.CompareAndSwap(old, locked) {
2770 return (*m)(unsafe.Pointer(old))
2771 }
2772 osyield_no_g()
2773 continue
2774 }
2775 }
2776
2777 //go:nosplit
2778 func unlockextra(mp *m, delta int32) {
2779 extraMLength.Add(delta)
2780 extraM.Store(uintptr(unsafe.Pointer(mp)))
2781 }
2782
2783 // Return an M from the extra M list. Returns last == true if the list becomes
2784 // empty because of this call.
2785 //
2786 // Spins waiting for an extra M, so caller must ensure that the list always
2787 // contains or will soon contain at least one M.
2788 //
2789 //go:nosplit
2790 func getExtraM() (mp *m, last bool) {
2791 mp = lockextra(false)
2792 extraMInUse.Add(1)
2793 unlockextra(mp.schedlink.ptr(), -1)
2794 return mp, mp.schedlink.ptr() == nil
2795 }
2796
2797 // Returns an extra M back to the list. mp must be from getExtraM. Newly
2798 // allocated M's should use addExtraM.
2799 //
2800 //go:nosplit
2801 func putExtraM(mp *m) {
2802 extraMInUse.Add(-1)
2803 addExtraM(mp)
2804 }
2805
2806 // Adds a newly allocated M to the extra M list.
2807 //
2808 //go:nosplit
2809 func addExtraM(mp *m) {
2810 mnext := lockextra(true)
2811 mp.schedlink.set(mnext)
2812 unlockextra(mp, 1)
2813 }
2814
2815 var (
2816 // allocmLock is locked for read when creating new Ms in allocm and their
2817 // addition to allm. Thus acquiring this lock for write blocks the
2818 // creation of new Ms.
2819 allocmLock rwmutex
2820
2821 // execLock serializes exec and clone to avoid bugs or unspecified
2822 // behaviour around exec'ing while creating/destroying threads. See
2823 // issue #19546.
2824 execLock rwmutex
2825 )
2826
2827 // These errors are reported (via writeErrStr) by some OS-specific
2828 // versions of newosproc and newosproc0.
2829 const (
2830 failthreadcreate = "runtime: failed to create new OS thread\n"
2831 failallocatestack = "runtime: failed to allocate stack for the new OS thread\n"
2832 )
2833
2834 // newmHandoff contains a list of m structures that need new OS threads.
2835 // This is used by newm in situations where newm itself can't safely
2836 // start an OS thread.
2837 var newmHandoff struct {
2838 lock mutex
2839
2840 // newm points to a list of M structures that need new OS
2841 // threads. The list is linked through m.schedlink.
2842 newm muintptr
2843
2844 // waiting indicates that wake needs to be notified when an m
2845 // is put on the list.
2846 waiting bool
2847 wake note
2848
2849 // haveTemplateThread indicates that the templateThread has
2850 // been started. This is not protected by lock. Use cas to set
2851 // to 1.
2852 haveTemplateThread uint32
2853 }
2854
2855 // Create a new m. It will start off with a call to fn, or else the scheduler.
2856 // fn needs to be static and not a heap allocated closure.
2857 // May run with m.p==nil, so write barriers are not allowed.
2858 //
2859 // id is optional pre-allocated m ID. Omit by passing -1.
2860 //
2861 //go:nowritebarrierrec
2862 func newm(fn func(), pp *p, id int64) {
2863 // allocm adds a new M to allm, but they do not start until created by
2864 // the OS in newm1 or the template thread.
2865 //
2866 // doAllThreadsSyscall requires that every M in allm will eventually
2867 // start and be signal-able, even with a STW.
2868 //
2869 // Disable preemption here until we start the thread to ensure that
2870 // newm is not preempted between allocm and starting the new thread,
2871 // ensuring that anything added to allm is guaranteed to eventually
2872 // start.
2873 acquirem()
2874
2875 mp := allocm(pp, fn, id)
2876 mp.nextp.set(pp)
2877 mp.sigmask = initSigmask
2878 if gp := getg(); gp != nil && gp.m != nil && (gp.m.lockedExt != 0 || gp.m.incgo) && GOOS != "plan9" {
2879 // We're on a locked M or a thread that may have been
2880 // started by C. The kernel state of this thread may
2881 // be strange (the user may have locked it for that
2882 // purpose). We don't want to clone that into another
2883 // thread. Instead, ask a known-good thread to create
2884 // the thread for us.
2885 //
2886 // This is disabled on Plan 9. See golang.org/issue/22227.
2887 //
2888 // TODO: This may be unnecessary on Windows, which
2889 // doesn't model thread creation off fork.
2890 lock(&newmHandoff.lock)
2891 if newmHandoff.haveTemplateThread == 0 {
2892 throw("on a locked thread with no template thread")
2893 }
2894 mp.schedlink = newmHandoff.newm
2895 newmHandoff.newm.set(mp)
2896 if newmHandoff.waiting {
2897 newmHandoff.waiting = false
2898 notewakeup(&newmHandoff.wake)
2899 }
2900 unlock(&newmHandoff.lock)
2901 // The M has not started yet, but the template thread does not
2902 // participate in STW, so it will always process queued Ms and
2903 // it is safe to releasem.
2904 releasem(getg().m)
2905 return
2906 }
2907 newm1(mp)
2908 releasem(getg().m)
2909 }
2910
2911 func newm1(mp *m) {
2912 if iscgo {
2913 var ts cgothreadstart
2914 if _cgo_thread_start == nil {
2915 throw("_cgo_thread_start missing")
2916 }
2917 ts.g.set(mp.g0)
2918 ts.tls = (*uint64)(unsafe.Pointer(&mp.tls[0]))
2919 ts.fn = unsafe.Pointer(abi.FuncPCABI0(mstart))
2920 if msanenabled {
2921 msanwrite(unsafe.Pointer(&ts), unsafe.Sizeof(ts))
2922 }
2923 if asanenabled {
2924 asanwrite(unsafe.Pointer(&ts), unsafe.Sizeof(ts))
2925 }
2926 execLock.rlock() // Prevent process clone.
2927 asmcgocall(_cgo_thread_start, unsafe.Pointer(&ts))
2928 execLock.runlock()
2929 return
2930 }
2931 execLock.rlock() // Prevent process clone.
2932 newosproc(mp)
2933 execLock.runlock()
2934 }
2935
2936 // startTemplateThread starts the template thread if it is not already
2937 // running.
2938 //
2939 // The calling thread must itself be in a known-good state.
2940 func startTemplateThread() {
2941 if GOARCH == "wasm" { // no threads on wasm yet
2942 return
2943 }
2944
2945 // Disable preemption to guarantee that the template thread will be
2946 // created before a park once haveTemplateThread is set.
2947 mp := acquirem()
2948 if !atomic.Cas(&newmHandoff.haveTemplateThread, 0, 1) {
2949 releasem(mp)
2950 return
2951 }
2952 newm(templateThread, nil, -1)
2953 releasem(mp)
2954 }
2955
2956 // templateThread is a thread in a known-good state that exists solely
2957 // to start new threads in known-good states when the calling thread
2958 // may not be in a good state.
2959 //
2960 // Many programs never need this, so templateThread is started lazily
2961 // when we first enter a state that might lead to running on a thread
2962 // in an unknown state.
2963 //
2964 // templateThread runs on an M without a P, so it must not have write
2965 // barriers.
2966 //
2967 //go:nowritebarrierrec
2968 func templateThread() {
2969 lock(&sched.lock)
2970 sched.nmsys++
2971 checkdead()
2972 unlock(&sched.lock)
2973
2974 for {
2975 lock(&newmHandoff.lock)
2976 for newmHandoff.newm != 0 {
2977 newm := newmHandoff.newm.ptr()
2978 newmHandoff.newm = 0
2979 unlock(&newmHandoff.lock)
2980 for newm != nil {
2981 next := newm.schedlink.ptr()
2982 newm.schedlink = 0
2983 newm1(newm)
2984 newm = next
2985 }
2986 lock(&newmHandoff.lock)
2987 }
2988 newmHandoff.waiting = true
2989 noteclear(&newmHandoff.wake)
2990 unlock(&newmHandoff.lock)
2991 notesleep(&newmHandoff.wake)
2992 }
2993 }
2994
2995 // Stops execution of the current m until new work is available.
2996 // Returns with acquired P.
2997 func stopm() {
2998 gp := getg()
2999
3000 if gp.m.locks != 0 {
3001 throw("stopm holding locks")
3002 }
3003 if gp.m.p != 0 {
3004 throw("stopm holding p")
3005 }
3006 if gp.m.spinning {
3007 throw("stopm spinning")
3008 }
3009
3010 lock(&sched.lock)
3011 mput(gp.m)
3012 unlock(&sched.lock)
3013 mPark()
3014 acquirep(gp.m.nextp.ptr())
3015 gp.m.nextp = 0
3016 }
3017
3018 func mspinning() {
3019 // startm's caller incremented nmspinning. Set the new M's spinning.
3020 getg().m.spinning = true
3021 }
3022
3023 // Schedules some M to run the p (creates an M if necessary).
3024 // If p==nil, tries to get an idle P, if no idle P's does nothing.
3025 // May run with m.p==nil, so write barriers are not allowed.
3026 // If spinning is set, the caller has incremented nmspinning and must provide a
3027 // P. startm will set m.spinning in the newly started M.
3028 //
3029 // Callers passing a non-nil P must call from a non-preemptible context. See
3030 // comment on acquirem below.
3031 //
3032 // Argument lockheld indicates whether the caller already acquired the
3033 // scheduler lock. Callers holding the lock when making the call must pass
3034 // true. The lock might be temporarily dropped, but will be reacquired before
3035 // returning.
3036 //
3037 // Must not have write barriers because this may be called without a P.
3038 //
3039 //go:nowritebarrierrec
3040 func startm(pp *p, spinning, lockheld bool) {
3041 // Disable preemption.
3042 //
3043 // Every owned P must have an owner that will eventually stop it in the
3044 // event of a GC stop request. startm takes transient ownership of a P
3045 // (either from argument or pidleget below) and transfers ownership to
3046 // a started M, which will be responsible for performing the stop.
3047 //
3048 // Preemption must be disabled during this transient ownership,
3049 // otherwise the P this is running on may enter GC stop while still
3050 // holding the transient P, leaving that P in limbo and deadlocking the
3051 // STW.
3052 //
3053 // Callers passing a non-nil P must already be in non-preemptible
3054 // context, otherwise such preemption could occur on function entry to
3055 // startm. Callers passing a nil P may be preemptible, so we must
3056 // disable preemption before acquiring a P from pidleget below.
3057 mp := acquirem()
3058 if !lockheld {
3059 lock(&sched.lock)
3060 }
3061 if pp == nil {
3062 if spinning {
3063 // TODO(prattmic): All remaining calls to this function
3064 // with _p_ == nil could be cleaned up to find a P
3065 // before calling startm.
3066 throw("startm: P required for spinning=true")
3067 }
3068 pp, _ = pidleget(0)
3069 if pp == nil {
3070 if !lockheld {
3071 unlock(&sched.lock)
3072 }
3073 releasem(mp)
3074 return
3075 }
3076 }
3077 nmp := mget()
3078 if nmp == nil {
3079 // No M is available, we must drop sched.lock and call newm.
3080 // However, we already own a P to assign to the M.
3081 //
3082 // Once sched.lock is released, another G (e.g., in a syscall),
3083 // could find no idle P while checkdead finds a runnable G but
3084 // no running M's because this new M hasn't started yet, thus
3085 // throwing in an apparent deadlock.
3086 // This apparent deadlock is possible when startm is called
3087 // from sysmon, which doesn't count as a running M.
3088 //
3089 // Avoid this situation by pre-allocating the ID for the new M,
3090 // thus marking it as 'running' before we drop sched.lock. This
3091 // new M will eventually run the scheduler to execute any
3092 // queued G's.
3093 id := mReserveID()
3094 unlock(&sched.lock)
3095
3096 var fn func()
3097 if spinning {
3098 // The caller incremented nmspinning, so set m.spinning in the new M.
3099 fn = mspinning
3100 }
3101 newm(fn, pp, id)
3102
3103 if lockheld {
3104 lock(&sched.lock)
3105 }
3106 // Ownership transfer of pp committed by start in newm.
3107 // Preemption is now safe.
3108 releasem(mp)
3109 return
3110 }
3111 if !lockheld {
3112 unlock(&sched.lock)
3113 }
3114 if nmp.spinning {
3115 throw("startm: m is spinning")
3116 }
3117 if nmp.nextp != 0 {
3118 throw("startm: m has p")
3119 }
3120 if spinning && !runqempty(pp) {
3121 throw("startm: p has runnable gs")
3122 }
3123 // The caller incremented nmspinning, so set m.spinning in the new M.
3124 nmp.spinning = spinning
3125 nmp.nextp.set(pp)
3126 notewakeup(&nmp.park)
3127 // Ownership transfer of pp committed by wakeup. Preemption is now
3128 // safe.
3129 releasem(mp)
3130 }
3131
3132 // Hands off P from syscall or locked M.
3133 // Always runs without a P, so write barriers are not allowed.
3134 //
3135 //go:nowritebarrierrec
3136 func handoffp(pp *p) {
3137 // handoffp must start an M in any situation where
3138 // findrunnable would return a G to run on pp.
3139
3140 // if it has local work, start it straight away
3141 if !runqempty(pp) || !sched.runq.empty() {
3142 startm(pp, false, false)
3143 return
3144 }
3145 // if there's trace work to do, start it straight away
3146 if (traceEnabled() || traceShuttingDown()) && traceReaderAvailable() != nil {
3147 startm(pp, false, false)
3148 return
3149 }
3150 // if it has GC work, start it straight away
3151 if gcBlackenEnabled != 0 && gcMarkWorkAvailable(pp) {
3152 startm(pp, false, false)
3153 return
3154 }
3155 // no local work, check that there are no spinning/idle M's,
3156 // otherwise our help is not required
3157 if sched.nmspinning.Load()+sched.npidle.Load() == 0 && sched.nmspinning.CompareAndSwap(0, 1) { // TODO: fast atomic
3158 sched.needspinning.Store(0)
3159 startm(pp, true, false)
3160 return
3161 }
3162 lock(&sched.lock)
3163 if sched.gcwaiting.Load() {
3164 pp.status = _Pgcstop
3165 pp.gcStopTime = nanotime()
3166 sched.stopwait--
3167 if sched.stopwait == 0 {
3168 notewakeup(&sched.stopnote)
3169 }
3170 unlock(&sched.lock)
3171 return
3172 }
3173 if pp.runSafePointFn != 0 && atomic.Cas(&pp.runSafePointFn, 1, 0) {
3174 sched.safePointFn(pp)
3175 sched.safePointWait--
3176 if sched.safePointWait == 0 {
3177 notewakeup(&sched.safePointNote)
3178 }
3179 }
3180 if !sched.runq.empty() {
3181 unlock(&sched.lock)
3182 startm(pp, false, false)
3183 return
3184 }
3185 // If this is the last running P and nobody is polling network,
3186 // need to wakeup another M to poll network.
3187 if sched.npidle.Load() == gomaxprocs-1 && sched.lastpoll.Load() != 0 {
3188 unlock(&sched.lock)
3189 startm(pp, false, false)
3190 return
3191 }
3192
3193 // The scheduler lock cannot be held when calling wakeNetPoller below
3194 // because wakeNetPoller may call wakep which may call startm.
3195 when := pp.timers.wakeTime()
3196 pidleput(pp, 0)
3197 unlock(&sched.lock)
3198
3199 if when != 0 {
3200 wakeNetPoller(when)
3201 }
3202 }
3203
3204 // Tries to add one more P to execute G's.
3205 // Called when a G is made runnable (newproc, ready).
3206 // Must be called with a P.
3207 //
3208 // wakep should be an internal detail,
3209 // but widely used packages access it using linkname.
3210 // Notable members of the hall of shame include:
3211 // - gvisor.dev/gvisor
3212 //
3213 // Do not remove or change the type signature.
3214 // See go.dev/issue/67401.
3215 //
3216 //go:linkname wakep
3217 func wakep() {
3218 // Be conservative about spinning threads, only start one if none exist
3219 // already.
3220 if sched.nmspinning.Load() != 0 || !sched.nmspinning.CompareAndSwap(0, 1) {
3221 return
3222 }
3223
3224 // Disable preemption until ownership of pp transfers to the next M in
3225 // startm. Otherwise preemption here would leave pp stuck waiting to
3226 // enter _Pgcstop.
3227 //
3228 // See preemption comment on acquirem in startm for more details.
3229 mp := acquirem()
3230
3231 var pp *p
3232 lock(&sched.lock)
3233 pp, _ = pidlegetSpinning(0)
3234 if pp == nil {
3235 if sched.nmspinning.Add(-1) < 0 {
3236 throw("wakep: negative nmspinning")
3237 }
3238 unlock(&sched.lock)
3239 releasem(mp)
3240 return
3241 }
3242 // Since we always have a P, the race in the "No M is available"
3243 // comment in startm doesn't apply during the small window between the
3244 // unlock here and lock in startm. A checkdead in between will always
3245 // see at least one running M (ours).
3246 unlock(&sched.lock)
3247
3248 startm(pp, true, false)
3249
3250 releasem(mp)
3251 }
3252
3253 // Stops execution of the current m that is locked to a g until the g is runnable again.
3254 // Returns with acquired P.
3255 func stoplockedm() {
3256 gp := getg()
3257
3258 if gp.m.lockedg == 0 || gp.m.lockedg.ptr().lockedm.ptr() != gp.m {
3259 throw("stoplockedm: inconsistent locking")
3260 }
3261 if gp.m.p != 0 {
3262 // Schedule another M to run this p.
3263 pp := releasep()
3264 handoffp(pp)
3265 }
3266 incidlelocked(1)
3267 // Wait until another thread schedules lockedg again.
3268 mPark()
3269 status := readgstatus(gp.m.lockedg.ptr())
3270 if status&^_Gscan != _Grunnable {
3271 print("runtime:stoplockedm: lockedg (atomicstatus=", status, ") is not Grunnable or Gscanrunnable\n")
3272 dumpgstatus(gp.m.lockedg.ptr())
3273 throw("stoplockedm: not runnable")
3274 }
3275 acquirep(gp.m.nextp.ptr())
3276 gp.m.nextp = 0
3277 }
3278
3279 // Schedules the locked m to run the locked gp.
3280 // May run during STW, so write barriers are not allowed.
3281 //
3282 //go:nowritebarrierrec
3283 func startlockedm(gp *g) {
3284 mp := gp.lockedm.ptr()
3285 if mp == getg().m {
3286 throw("startlockedm: locked to me")
3287 }
3288 if mp.nextp != 0 {
3289 throw("startlockedm: m has p")
3290 }
3291 // directly handoff current P to the locked m
3292 incidlelocked(-1)
3293 pp := releasep()
3294 mp.nextp.set(pp)
3295 notewakeup(&mp.park)
3296 stopm()
3297 }
3298
3299 // Stops the current m for stopTheWorld.
3300 // Returns when the world is restarted.
3301 func gcstopm() {
3302 gp := getg()
3303
3304 if !sched.gcwaiting.Load() {
3305 throw("gcstopm: not waiting for gc")
3306 }
3307 if gp.m.spinning {
3308 gp.m.spinning = false
3309 // OK to just drop nmspinning here,
3310 // startTheWorld will unpark threads as necessary.
3311 if sched.nmspinning.Add(-1) < 0 {
3312 throw("gcstopm: negative nmspinning")
3313 }
3314 }
3315 pp := releasep()
3316 lock(&sched.lock)
3317 pp.status = _Pgcstop
3318 pp.gcStopTime = nanotime()
3319 sched.stopwait--
3320 if sched.stopwait == 0 {
3321 notewakeup(&sched.stopnote)
3322 }
3323 unlock(&sched.lock)
3324 stopm()
3325 }
3326
3327 // Schedules gp to run on the current M.
3328 // If inheritTime is true, gp inherits the remaining time in the
3329 // current time slice. Otherwise, it starts a new time slice.
3330 // Never returns.
3331 //
3332 // Write barriers are allowed because this is called immediately after
3333 // acquiring a P in several places.
3334 //
3335 //go:yeswritebarrierrec
3336 func execute(gp *g, inheritTime bool) {
3337 mp := getg().m
3338
3339 if goroutineProfile.active {
3340 // Make sure that gp has had its stack written out to the goroutine
3341 // profile, exactly as it was when the goroutine profiler first stopped
3342 // the world.
3343 tryRecordGoroutineProfile(gp, nil, osyield)
3344 }
3345
3346 // Assign gp.m before entering _Grunning so running Gs have an M.
3347 mp.curg = gp
3348 gp.m = mp
3349 gp.syncSafePoint = false // Clear the flag, which may have been set by morestack.
3350 casgstatus(gp, _Grunnable, _Grunning)
3351 gp.waitsince = 0
3352 gp.preempt = false
3353 gp.stackguard0 = gp.stack.lo + stackGuard
3354 if !inheritTime {
3355 mp.p.ptr().schedtick++
3356 }
3357
3358 // Check whether the profiler needs to be turned on or off.
3359 hz := sched.profilehz
3360 if mp.profilehz != hz {
3361 setThreadCPUProfiler(hz)
3362 }
3363
3364 trace := traceAcquire()
3365 if trace.ok() {
3366 trace.GoStart()
3367 traceRelease(trace)
3368 }
3369
3370 gogo(&gp.sched)
3371 }
3372
3373 // Finds a runnable goroutine to execute.
3374 // Tries to steal from other P's, get g from local or global queue, poll network.
3375 // tryWakeP indicates that the returned goroutine is not normal (GC worker, trace
3376 // reader) so the caller should try to wake a P.
3377 func findRunnable() (gp *g, inheritTime, tryWakeP bool) {
3378 mp := getg().m
3379
3380 // The conditions here and in handoffp must agree: if
3381 // findrunnable would return a G to run, handoffp must start
3382 // an M.
3383
3384 top:
3385 // We may have collected an allp snapshot below. The snapshot is only
3386 // required in each loop iteration. Clear it to all GC to collect the
3387 // slice.
3388 mp.clearAllpSnapshot()
3389
3390 pp := mp.p.ptr()
3391 if sched.gcwaiting.Load() {
3392 gcstopm()
3393 goto top
3394 }
3395 if pp.runSafePointFn != 0 {
3396 runSafePointFn()
3397 }
3398
3399 // now and pollUntil are saved for work stealing later,
3400 // which may steal timers. It's important that between now
3401 // and then, nothing blocks, so these numbers remain mostly
3402 // relevant.
3403 now, pollUntil, _ := pp.timers.check(0, nil)
3404
3405 // Try to schedule the trace reader.
3406 if traceEnabled() || traceShuttingDown() {
3407 gp := traceReader()
3408 if gp != nil {
3409 trace := traceAcquire()
3410 casgstatus(gp, _Gwaiting, _Grunnable)
3411 if trace.ok() {
3412 trace.GoUnpark(gp, 0)
3413 traceRelease(trace)
3414 }
3415 return gp, false, true
3416 }
3417 }
3418
3419 // Try to schedule a GC worker.
3420 if gcBlackenEnabled != 0 {
3421 gp, tnow := gcController.findRunnableGCWorker(pp, now)
3422 if gp != nil {
3423 return gp, false, true
3424 }
3425 now = tnow
3426 }
3427
3428 // Check the global runnable queue once in a while to ensure fairness.
3429 // Otherwise two goroutines can completely occupy the local runqueue
3430 // by constantly respawning each other.
3431 if pp.schedtick%61 == 0 && !sched.runq.empty() {
3432 lock(&sched.lock)
3433 gp := globrunqget()
3434 unlock(&sched.lock)
3435 if gp != nil {
3436 return gp, false, false
3437 }
3438 }
3439
3440 // Wake up the finalizer G.
3441 if fingStatus.Load()&(fingWait|fingWake) == fingWait|fingWake {
3442 if gp := wakefing(); gp != nil {
3443 ready(gp, 0, true)
3444 }
3445 }
3446
3447 // Wake up one or more cleanup Gs.
3448 if gcCleanups.needsWake() {
3449 gcCleanups.wake()
3450 }
3451
3452 if *cgo_yield != nil {
3453 asmcgocall(*cgo_yield, nil)
3454 }
3455
3456 // local runq
3457 if gp, inheritTime := runqget(pp); gp != nil {
3458 return gp, inheritTime, false
3459 }
3460
3461 // global runq
3462 if !sched.runq.empty() {
3463 lock(&sched.lock)
3464 gp, q := globrunqgetbatch(int32(len(pp.runq)) / 2)
3465 unlock(&sched.lock)
3466 if gp != nil {
3467 if runqputbatch(pp, &q); !q.empty() {
3468 throw("Couldn't put Gs into empty local runq")
3469 }
3470 return gp, false, false
3471 }
3472 }
3473
3474 // Poll network.
3475 // This netpoll is only an optimization before we resort to stealing.
3476 // We can safely skip it if there are no waiters or a thread is blocked
3477 // in netpoll already. If there is any kind of logical race with that
3478 // blocked thread (e.g. it has already returned from netpoll, but does
3479 // not set lastpoll yet), this thread will do blocking netpoll below
3480 // anyway.
3481 // We only poll from one thread at a time to avoid kernel contention
3482 // on machines with many cores.
3483 if netpollinited() && netpollAnyWaiters() && sched.lastpoll.Load() != 0 && sched.pollingNet.Swap(1) == 0 {
3484 list, delta := netpoll(0)
3485 sched.pollingNet.Store(0)
3486 if !list.empty() { // non-blocking
3487 gp := list.pop()
3488 injectglist(&list)
3489 netpollAdjustWaiters(delta)
3490 trace := traceAcquire()
3491 casgstatus(gp, _Gwaiting, _Grunnable)
3492 if trace.ok() {
3493 trace.GoUnpark(gp, 0)
3494 traceRelease(trace)
3495 }
3496 return gp, false, false
3497 }
3498 }
3499
3500 // Spinning Ms: steal work from other Ps.
3501 //
3502 // Limit the number of spinning Ms to half the number of busy Ps.
3503 // This is necessary to prevent excessive CPU consumption when
3504 // GOMAXPROCS>>1 but the program parallelism is low.
3505 if mp.spinning || 2*sched.nmspinning.Load() < gomaxprocs-sched.npidle.Load() {
3506 if !mp.spinning {
3507 mp.becomeSpinning()
3508 }
3509
3510 gp, inheritTime, tnow, w, newWork := stealWork(now)
3511 if gp != nil {
3512 // Successfully stole.
3513 return gp, inheritTime, false
3514 }
3515 if newWork {
3516 // There may be new timer or GC work; restart to
3517 // discover.
3518 goto top
3519 }
3520
3521 now = tnow
3522 if w != 0 && (pollUntil == 0 || w < pollUntil) {
3523 // Earlier timer to wait for.
3524 pollUntil = w
3525 }
3526 }
3527
3528 // We have nothing to do.
3529 //
3530 // If we're in the GC mark phase, can safely scan and blacken objects,
3531 // and have work to do, run idle-time marking rather than give up the P.
3532 if gcBlackenEnabled != 0 && gcMarkWorkAvailable(pp) && gcController.addIdleMarkWorker() {
3533 node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
3534 if node != nil {
3535 pp.gcMarkWorkerMode = gcMarkWorkerIdleMode
3536 gp := node.gp.ptr()
3537
3538 trace := traceAcquire()
3539 casgstatus(gp, _Gwaiting, _Grunnable)
3540 if trace.ok() {
3541 trace.GoUnpark(gp, 0)
3542 traceRelease(trace)
3543 }
3544 return gp, false, false
3545 }
3546 gcController.removeIdleMarkWorker()
3547 }
3548
3549 // wasm only:
3550 // If a callback returned and no other goroutine is awake,
3551 // then wake event handler goroutine which pauses execution
3552 // until a callback was triggered.
3553 gp, otherReady := beforeIdle(now, pollUntil)
3554 if gp != nil {
3555 trace := traceAcquire()
3556 casgstatus(gp, _Gwaiting, _Grunnable)
3557 if trace.ok() {
3558 trace.GoUnpark(gp, 0)
3559 traceRelease(trace)
3560 }
3561 return gp, false, false
3562 }
3563 if otherReady {
3564 goto top
3565 }
3566
3567 // Before we drop our P, make a snapshot of the allp slice,
3568 // which can change underfoot once we no longer block
3569 // safe-points. We don't need to snapshot the contents because
3570 // everything up to cap(allp) is immutable.
3571 //
3572 // We clear the snapshot from the M after return via
3573 // mp.clearAllpSnapshop (in schedule) and on each iteration of the top
3574 // loop.
3575 allpSnapshot := mp.snapshotAllp()
3576 // Also snapshot masks. Value changes are OK, but we can't allow
3577 // len to change out from under us.
3578 idlepMaskSnapshot := idlepMask
3579 timerpMaskSnapshot := timerpMask
3580
3581 // return P and block
3582 lock(&sched.lock)
3583 if sched.gcwaiting.Load() || pp.runSafePointFn != 0 {
3584 unlock(&sched.lock)
3585 goto top
3586 }
3587 if !sched.runq.empty() {
3588 gp, q := globrunqgetbatch(int32(len(pp.runq)) / 2)
3589 unlock(&sched.lock)
3590 if gp == nil {
3591 throw("global runq empty with non-zero runqsize")
3592 }
3593 if runqputbatch(pp, &q); !q.empty() {
3594 throw("Couldn't put Gs into empty local runq")
3595 }
3596 return gp, false, false
3597 }
3598 if !mp.spinning && sched.needspinning.Load() == 1 {
3599 // See "Delicate dance" comment below.
3600 mp.becomeSpinning()
3601 unlock(&sched.lock)
3602 goto top
3603 }
3604 if releasep() != pp {
3605 throw("findrunnable: wrong p")
3606 }
3607 now = pidleput(pp, now)
3608 unlock(&sched.lock)
3609
3610 // Delicate dance: thread transitions from spinning to non-spinning
3611 // state, potentially concurrently with submission of new work. We must
3612 // drop nmspinning first and then check all sources again (with
3613 // #StoreLoad memory barrier in between). If we do it the other way
3614 // around, another thread can submit work after we've checked all
3615 // sources but before we drop nmspinning; as a result nobody will
3616 // unpark a thread to run the work.
3617 //
3618 // This applies to the following sources of work:
3619 //
3620 // * Goroutines added to the global or a per-P run queue.
3621 // * New/modified-earlier timers on a per-P timer heap.
3622 // * Idle-priority GC work (barring golang.org/issue/19112).
3623 //
3624 // If we discover new work below, we need to restore m.spinning as a
3625 // signal for resetspinning to unpark a new worker thread (because
3626 // there can be more than one starving goroutine).
3627 //
3628 // However, if after discovering new work we also observe no idle Ps
3629 // (either here or in resetspinning), we have a problem. We may be
3630 // racing with a non-spinning M in the block above, having found no
3631 // work and preparing to release its P and park. Allowing that P to go
3632 // idle will result in loss of work conservation (idle P while there is
3633 // runnable work). This could result in complete deadlock in the
3634 // unlikely event that we discover new work (from netpoll) right as we
3635 // are racing with _all_ other Ps going idle.
3636 //
3637 // We use sched.needspinning to synchronize with non-spinning Ms going
3638 // idle. If needspinning is set when they are about to drop their P,
3639 // they abort the drop and instead become a new spinning M on our
3640 // behalf. If we are not racing and the system is truly fully loaded
3641 // then no spinning threads are required, and the next thread to
3642 // naturally become spinning will clear the flag.
3643 //
3644 // Also see "Worker thread parking/unparking" comment at the top of the
3645 // file.
3646 wasSpinning := mp.spinning
3647 if mp.spinning {
3648 mp.spinning = false
3649 if sched.nmspinning.Add(-1) < 0 {
3650 throw("findrunnable: negative nmspinning")
3651 }
3652
3653 // Note the for correctness, only the last M transitioning from
3654 // spinning to non-spinning must perform these rechecks to
3655 // ensure no missed work. However, the runtime has some cases
3656 // of transient increments of nmspinning that are decremented
3657 // without going through this path, so we must be conservative
3658 // and perform the check on all spinning Ms.
3659 //
3660 // See https://go.dev/issue/43997.
3661
3662 // Check global and P runqueues again.
3663
3664 lock(&sched.lock)
3665 if !sched.runq.empty() {
3666 pp, _ := pidlegetSpinning(0)
3667 if pp != nil {
3668 gp, q := globrunqgetbatch(int32(len(pp.runq)) / 2)
3669 unlock(&sched.lock)
3670 if gp == nil {
3671 throw("global runq empty with non-zero runqsize")
3672 }
3673 if runqputbatch(pp, &q); !q.empty() {
3674 throw("Couldn't put Gs into empty local runq")
3675 }
3676 acquirep(pp)
3677 mp.becomeSpinning()
3678 return gp, false, false
3679 }
3680 }
3681 unlock(&sched.lock)
3682
3683 pp := checkRunqsNoP(allpSnapshot, idlepMaskSnapshot)
3684 if pp != nil {
3685 acquirep(pp)
3686 mp.becomeSpinning()
3687 goto top
3688 }
3689
3690 // Check for idle-priority GC work again.
3691 pp, gp := checkIdleGCNoP()
3692 if pp != nil {
3693 acquirep(pp)
3694 mp.becomeSpinning()
3695
3696 // Run the idle worker.
3697 pp.gcMarkWorkerMode = gcMarkWorkerIdleMode
3698 trace := traceAcquire()
3699 casgstatus(gp, _Gwaiting, _Grunnable)
3700 if trace.ok() {
3701 trace.GoUnpark(gp, 0)
3702 traceRelease(trace)
3703 }
3704 return gp, false, false
3705 }
3706
3707 // Finally, check for timer creation or expiry concurrently with
3708 // transitioning from spinning to non-spinning.
3709 //
3710 // Note that we cannot use checkTimers here because it calls
3711 // adjusttimers which may need to allocate memory, and that isn't
3712 // allowed when we don't have an active P.
3713 pollUntil = checkTimersNoP(allpSnapshot, timerpMaskSnapshot, pollUntil)
3714 }
3715
3716 // We don't need allp anymore at this pointer, but can't clear the
3717 // snapshot without a P for the write barrier..
3718
3719 // Poll network until next timer.
3720 if netpollinited() && (netpollAnyWaiters() || pollUntil != 0) && sched.lastpoll.Swap(0) != 0 {
3721 sched.pollUntil.Store(pollUntil)
3722 if mp.p != 0 {
3723 throw("findrunnable: netpoll with p")
3724 }
3725 if mp.spinning {
3726 throw("findrunnable: netpoll with spinning")
3727 }
3728 delay := int64(-1)
3729 if pollUntil != 0 {
3730 if now == 0 {
3731 now = nanotime()
3732 }
3733 delay = pollUntil - now
3734 if delay < 0 {
3735 delay = 0
3736 }
3737 }
3738 if faketime != 0 {
3739 // When using fake time, just poll.
3740 delay = 0
3741 }
3742 list, delta := netpoll(delay) // block until new work is available
3743 // Refresh now again, after potentially blocking.
3744 now = nanotime()
3745 sched.pollUntil.Store(0)
3746 sched.lastpoll.Store(now)
3747 if faketime != 0 && list.empty() {
3748 // Using fake time and nothing is ready; stop M.
3749 // When all M's stop, checkdead will call timejump.
3750 stopm()
3751 goto top
3752 }
3753 lock(&sched.lock)
3754 pp, _ := pidleget(now)
3755 unlock(&sched.lock)
3756 if pp == nil {
3757 injectglist(&list)
3758 netpollAdjustWaiters(delta)
3759 } else {
3760 acquirep(pp)
3761 if !list.empty() {
3762 gp := list.pop()
3763 injectglist(&list)
3764 netpollAdjustWaiters(delta)
3765 trace := traceAcquire()
3766 casgstatus(gp, _Gwaiting, _Grunnable)
3767 if trace.ok() {
3768 trace.GoUnpark(gp, 0)
3769 traceRelease(trace)
3770 }
3771 return gp, false, false
3772 }
3773 if wasSpinning {
3774 mp.becomeSpinning()
3775 }
3776 goto top
3777 }
3778 } else if pollUntil != 0 && netpollinited() {
3779 pollerPollUntil := sched.pollUntil.Load()
3780 if pollerPollUntil == 0 || pollerPollUntil > pollUntil {
3781 netpollBreak()
3782 }
3783 }
3784 stopm()
3785 goto top
3786 }
3787
3788 // pollWork reports whether there is non-background work this P could
3789 // be doing. This is a fairly lightweight check to be used for
3790 // background work loops, like idle GC. It checks a subset of the
3791 // conditions checked by the actual scheduler.
3792 func pollWork() bool {
3793 if !sched.runq.empty() {
3794 return true
3795 }
3796 p := getg().m.p.ptr()
3797 if !runqempty(p) {
3798 return true
3799 }
3800 if netpollinited() && netpollAnyWaiters() && sched.lastpoll.Load() != 0 {
3801 if list, delta := netpoll(0); !list.empty() {
3802 injectglist(&list)
3803 netpollAdjustWaiters(delta)
3804 return true
3805 }
3806 }
3807 return false
3808 }
3809
3810 // stealWork attempts to steal a runnable goroutine or timer from any P.
3811 //
3812 // If newWork is true, new work may have been readied.
3813 //
3814 // If now is not 0 it is the current time. stealWork returns the passed time or
3815 // the current time if now was passed as 0.
3816 func stealWork(now int64) (gp *g, inheritTime bool, rnow, pollUntil int64, newWork bool) {
3817 pp := getg().m.p.ptr()
3818
3819 ranTimer := false
3820
3821 const stealTries = 4
3822 for i := 0; i < stealTries; i++ {
3823 stealTimersOrRunNextG := i == stealTries-1
3824
3825 for enum := stealOrder.start(cheaprand()); !enum.done(); enum.next() {
3826 if sched.gcwaiting.Load() {
3827 // GC work may be available.
3828 return nil, false, now, pollUntil, true
3829 }
3830 p2 := allp[enum.position()]
3831 if pp == p2 {
3832 continue
3833 }
3834
3835 // Steal timers from p2. This call to checkTimers is the only place
3836 // where we might hold a lock on a different P's timers. We do this
3837 // once on the last pass before checking runnext because stealing
3838 // from the other P's runnext should be the last resort, so if there
3839 // are timers to steal do that first.
3840 //
3841 // We only check timers on one of the stealing iterations because
3842 // the time stored in now doesn't change in this loop and checking
3843 // the timers for each P more than once with the same value of now
3844 // is probably a waste of time.
3845 //
3846 // timerpMask tells us whether the P may have timers at all. If it
3847 // can't, no need to check at all.
3848 if stealTimersOrRunNextG && timerpMask.read(enum.position()) {
3849 tnow, w, ran := p2.timers.check(now, nil)
3850 now = tnow
3851 if w != 0 && (pollUntil == 0 || w < pollUntil) {
3852 pollUntil = w
3853 }
3854 if ran {
3855 // Running the timers may have
3856 // made an arbitrary number of G's
3857 // ready and added them to this P's
3858 // local run queue. That invalidates
3859 // the assumption of runqsteal
3860 // that it always has room to add
3861 // stolen G's. So check now if there
3862 // is a local G to run.
3863 if gp, inheritTime := runqget(pp); gp != nil {
3864 return gp, inheritTime, now, pollUntil, ranTimer
3865 }
3866 ranTimer = true
3867 }
3868 }
3869
3870 // Don't bother to attempt to steal if p2 is idle.
3871 if !idlepMask.read(enum.position()) {
3872 if gp := runqsteal(pp, p2, stealTimersOrRunNextG); gp != nil {
3873 return gp, false, now, pollUntil, ranTimer
3874 }
3875 }
3876 }
3877 }
3878
3879 // No goroutines found to steal. Regardless, running a timer may have
3880 // made some goroutine ready that we missed. Indicate the next timer to
3881 // wait for.
3882 return nil, false, now, pollUntil, ranTimer
3883 }
3884
3885 // Check all Ps for a runnable G to steal.
3886 //
3887 // On entry we have no P. If a G is available to steal and a P is available,
3888 // the P is returned which the caller should acquire and attempt to steal the
3889 // work to.
3890 func checkRunqsNoP(allpSnapshot []*p, idlepMaskSnapshot pMask) *p {
3891 for id, p2 := range allpSnapshot {
3892 if !idlepMaskSnapshot.read(uint32(id)) && !runqempty(p2) {
3893 lock(&sched.lock)
3894 pp, _ := pidlegetSpinning(0)
3895 if pp == nil {
3896 // Can't get a P, don't bother checking remaining Ps.
3897 unlock(&sched.lock)
3898 return nil
3899 }
3900 unlock(&sched.lock)
3901 return pp
3902 }
3903 }
3904
3905 // No work available.
3906 return nil
3907 }
3908
3909 // Check all Ps for a timer expiring sooner than pollUntil.
3910 //
3911 // Returns updated pollUntil value.
3912 func checkTimersNoP(allpSnapshot []*p, timerpMaskSnapshot pMask, pollUntil int64) int64 {
3913 for id, p2 := range allpSnapshot {
3914 if timerpMaskSnapshot.read(uint32(id)) {
3915 w := p2.timers.wakeTime()
3916 if w != 0 && (pollUntil == 0 || w < pollUntil) {
3917 pollUntil = w
3918 }
3919 }
3920 }
3921
3922 return pollUntil
3923 }
3924
3925 // Check for idle-priority GC, without a P on entry.
3926 //
3927 // If some GC work, a P, and a worker G are all available, the P and G will be
3928 // returned. The returned P has not been wired yet.
3929 func checkIdleGCNoP() (*p, *g) {
3930 // N.B. Since we have no P, gcBlackenEnabled may change at any time; we
3931 // must check again after acquiring a P. As an optimization, we also check
3932 // if an idle mark worker is needed at all. This is OK here, because if we
3933 // observe that one isn't needed, at least one is currently running. Even if
3934 // it stops running, its own journey into the scheduler should schedule it
3935 // again, if need be (at which point, this check will pass, if relevant).
3936 if atomic.Load(&gcBlackenEnabled) == 0 || !gcController.needIdleMarkWorker() {
3937 return nil, nil
3938 }
3939 if !gcMarkWorkAvailable(nil) {
3940 return nil, nil
3941 }
3942
3943 // Work is available; we can start an idle GC worker only if there is
3944 // an available P and available worker G.
3945 //
3946 // We can attempt to acquire these in either order, though both have
3947 // synchronization concerns (see below). Workers are almost always
3948 // available (see comment in findRunnableGCWorker for the one case
3949 // there may be none). Since we're slightly less likely to find a P,
3950 // check for that first.
3951 //
3952 // Synchronization: note that we must hold sched.lock until we are
3953 // committed to keeping it. Otherwise we cannot put the unnecessary P
3954 // back in sched.pidle without performing the full set of idle
3955 // transition checks.
3956 //
3957 // If we were to check gcBgMarkWorkerPool first, we must somehow handle
3958 // the assumption in gcControllerState.findRunnableGCWorker that an
3959 // empty gcBgMarkWorkerPool is only possible if gcMarkDone is running.
3960 lock(&sched.lock)
3961 pp, now := pidlegetSpinning(0)
3962 if pp == nil {
3963 unlock(&sched.lock)
3964 return nil, nil
3965 }
3966
3967 // Now that we own a P, gcBlackenEnabled can't change (as it requires STW).
3968 if gcBlackenEnabled == 0 || !gcController.addIdleMarkWorker() {
3969 pidleput(pp, now)
3970 unlock(&sched.lock)
3971 return nil, nil
3972 }
3973
3974 node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
3975 if node == nil {
3976 pidleput(pp, now)
3977 unlock(&sched.lock)
3978 gcController.removeIdleMarkWorker()
3979 return nil, nil
3980 }
3981
3982 unlock(&sched.lock)
3983
3984 return pp, node.gp.ptr()
3985 }
3986
3987 // wakeNetPoller wakes up the thread sleeping in the network poller if it isn't
3988 // going to wake up before the when argument; or it wakes an idle P to service
3989 // timers and the network poller if there isn't one already.
3990 func wakeNetPoller(when int64) {
3991 if sched.lastpoll.Load() == 0 {
3992 // In findrunnable we ensure that when polling the pollUntil
3993 // field is either zero or the time to which the current
3994 // poll is expected to run. This can have a spurious wakeup
3995 // but should never miss a wakeup.
3996 pollerPollUntil := sched.pollUntil.Load()
3997 if pollerPollUntil == 0 || pollerPollUntil > when {
3998 netpollBreak()
3999 }
4000 } else {
4001 // There are no threads in the network poller, try to get
4002 // one there so it can handle new timers.
4003 if GOOS != "plan9" { // Temporary workaround - see issue #42303.
4004 wakep()
4005 }
4006 }
4007 }
4008
4009 func resetspinning() {
4010 gp := getg()
4011 if !gp.m.spinning {
4012 throw("resetspinning: not a spinning m")
4013 }
4014 gp.m.spinning = false
4015 nmspinning := sched.nmspinning.Add(-1)
4016 if nmspinning < 0 {
4017 throw("findrunnable: negative nmspinning")
4018 }
4019 // M wakeup policy is deliberately somewhat conservative, so check if we
4020 // need to wakeup another P here. See "Worker thread parking/unparking"
4021 // comment at the top of the file for details.
4022 wakep()
4023 }
4024
4025 // injectglist adds each runnable G on the list to some run queue,
4026 // and clears glist. If there is no current P, they are added to the
4027 // global queue, and up to npidle M's are started to run them.
4028 // Otherwise, for each idle P, this adds a G to the global queue
4029 // and starts an M. Any remaining G's are added to the current P's
4030 // local run queue.
4031 // This may temporarily acquire sched.lock.
4032 // Can run concurrently with GC.
4033 func injectglist(glist *gList) {
4034 if glist.empty() {
4035 return
4036 }
4037
4038 // Mark all the goroutines as runnable before we put them
4039 // on the run queues.
4040 var tail *g
4041 trace := traceAcquire()
4042 for gp := glist.head.ptr(); gp != nil; gp = gp.schedlink.ptr() {
4043 tail = gp
4044 casgstatus(gp, _Gwaiting, _Grunnable)
4045 if trace.ok() {
4046 trace.GoUnpark(gp, 0)
4047 }
4048 }
4049 if trace.ok() {
4050 traceRelease(trace)
4051 }
4052
4053 // Turn the gList into a gQueue.
4054 q := gQueue{glist.head, tail.guintptr(), glist.size}
4055 *glist = gList{}
4056
4057 startIdle := func(n int32) {
4058 for ; n > 0; n-- {
4059 mp := acquirem() // See comment in startm.
4060 lock(&sched.lock)
4061
4062 pp, _ := pidlegetSpinning(0)
4063 if pp == nil {
4064 unlock(&sched.lock)
4065 releasem(mp)
4066 break
4067 }
4068
4069 startm(pp, false, true)
4070 unlock(&sched.lock)
4071 releasem(mp)
4072 }
4073 }
4074
4075 pp := getg().m.p.ptr()
4076 if pp == nil {
4077 n := q.size
4078 lock(&sched.lock)
4079 globrunqputbatch(&q)
4080 unlock(&sched.lock)
4081 startIdle(n)
4082 return
4083 }
4084
4085 var globq gQueue
4086 npidle := sched.npidle.Load()
4087 for ; npidle > 0 && !q.empty(); npidle-- {
4088 g := q.pop()
4089 globq.pushBack(g)
4090 }
4091 if !globq.empty() {
4092 n := globq.size
4093 lock(&sched.lock)
4094 globrunqputbatch(&globq)
4095 unlock(&sched.lock)
4096 startIdle(n)
4097 }
4098
4099 if runqputbatch(pp, &q); !q.empty() {
4100 lock(&sched.lock)
4101 globrunqputbatch(&q)
4102 unlock(&sched.lock)
4103 }
4104
4105 // Some P's might have become idle after we loaded `sched.npidle`
4106 // but before any goroutines were added to the queue, which could
4107 // lead to idle P's when there is work available in the global queue.
4108 // That could potentially last until other goroutines become ready
4109 // to run. That said, we need to find a way to hedge
4110 //
4111 // Calling wakep() here is the best bet, it will do nothing in the
4112 // common case (no racing on `sched.npidle`), while it could wake one
4113 // more P to execute G's, which might end up with >1 P's: the first one
4114 // wakes another P and so forth until there is no more work, but this
4115 // ought to be an extremely rare case.
4116 //
4117 // Also see "Worker thread parking/unparking" comment at the top of the file for details.
4118 wakep()
4119 }
4120
4121 // One round of scheduler: find a runnable goroutine and execute it.
4122 // Never returns.
4123 func schedule() {
4124 mp := getg().m
4125
4126 if mp.locks != 0 {
4127 throw("schedule: holding locks")
4128 }
4129
4130 if mp.lockedg != 0 {
4131 stoplockedm()
4132 execute(mp.lockedg.ptr(), false) // Never returns.
4133 }
4134
4135 // We should not schedule away from a g that is executing a cgo call,
4136 // since the cgo call is using the m's g0 stack.
4137 if mp.incgo {
4138 throw("schedule: in cgo")
4139 }
4140
4141 top:
4142 pp := mp.p.ptr()
4143 pp.preempt = false
4144
4145 // Safety check: if we are spinning, the run queue should be empty.
4146 // Check this before calling checkTimers, as that might call
4147 // goready to put a ready goroutine on the local run queue.
4148 if mp.spinning && (pp.runnext != 0 || pp.runqhead != pp.runqtail) {
4149 throw("schedule: spinning with local work")
4150 }
4151
4152 gp, inheritTime, tryWakeP := findRunnable() // blocks until work is available
4153
4154 // findRunnable may have collected an allp snapshot. The snapshot is
4155 // only required within findRunnable. Clear it to all GC to collect the
4156 // slice.
4157 mp.clearAllpSnapshot()
4158
4159 if debug.dontfreezetheworld > 0 && freezing.Load() {
4160 // See comment in freezetheworld. We don't want to perturb
4161 // scheduler state, so we didn't gcstopm in findRunnable, but
4162 // also don't want to allow new goroutines to run.
4163 //
4164 // Deadlock here rather than in the findRunnable loop so if
4165 // findRunnable is stuck in a loop we don't perturb that
4166 // either.
4167 lock(&deadlock)
4168 lock(&deadlock)
4169 }
4170
4171 // This thread is going to run a goroutine and is not spinning anymore,
4172 // so if it was marked as spinning we need to reset it now and potentially
4173 // start a new spinning M.
4174 if mp.spinning {
4175 resetspinning()
4176 }
4177
4178 if sched.disable.user && !schedEnabled(gp) {
4179 // Scheduling of this goroutine is disabled. Put it on
4180 // the list of pending runnable goroutines for when we
4181 // re-enable user scheduling and look again.
4182 lock(&sched.lock)
4183 if schedEnabled(gp) {
4184 // Something re-enabled scheduling while we
4185 // were acquiring the lock.
4186 unlock(&sched.lock)
4187 } else {
4188 sched.disable.runnable.pushBack(gp)
4189 unlock(&sched.lock)
4190 goto top
4191 }
4192 }
4193
4194 // If about to schedule a not-normal goroutine (a GCworker or tracereader),
4195 // wake a P if there is one.
4196 if tryWakeP {
4197 wakep()
4198 }
4199 if gp.lockedm != 0 {
4200 // Hands off own p to the locked m,
4201 // then blocks waiting for a new p.
4202 startlockedm(gp)
4203 goto top
4204 }
4205
4206 execute(gp, inheritTime)
4207 }
4208
4209 // dropg removes the association between m and the current goroutine m->curg (gp for short).
4210 // Typically a caller sets gp's status away from Grunning and then
4211 // immediately calls dropg to finish the job. The caller is also responsible
4212 // for arranging that gp will be restarted using ready at an
4213 // appropriate time. After calling dropg and arranging for gp to be
4214 // readied later, the caller can do other work but eventually should
4215 // call schedule to restart the scheduling of goroutines on this m.
4216 func dropg() {
4217 gp := getg()
4218
4219 setMNoWB(&gp.m.curg.m, nil)
4220 setGNoWB(&gp.m.curg, nil)
4221 }
4222
4223 func parkunlock_c(gp *g, lock unsafe.Pointer) bool {
4224 unlock((*mutex)(lock))
4225 return true
4226 }
4227
4228 // park continuation on g0.
4229 func park_m(gp *g) {
4230 mp := getg().m
4231
4232 trace := traceAcquire()
4233
4234 // If g is in a synctest group, we don't want to let the group
4235 // become idle until after the waitunlockf (if any) has confirmed
4236 // that the park is happening.
4237 // We need to record gp.bubble here, since waitunlockf can change it.
4238 bubble := gp.bubble
4239 if bubble != nil {
4240 bubble.incActive()
4241 }
4242
4243 if trace.ok() {
4244 // Trace the event before the transition. It may take a
4245 // stack trace, but we won't own the stack after the
4246 // transition anymore.
4247 trace.GoPark(mp.waitTraceBlockReason, mp.waitTraceSkip)
4248 }
4249 // N.B. Not using casGToWaiting here because the waitreason is
4250 // set by park_m's caller.
4251 casgstatus(gp, _Grunning, _Gwaiting)
4252 if trace.ok() {
4253 traceRelease(trace)
4254 }
4255
4256 dropg()
4257
4258 if fn := mp.waitunlockf; fn != nil {
4259 ok := fn(gp, mp.waitlock)
4260 mp.waitunlockf = nil
4261 mp.waitlock = nil
4262 if !ok {
4263 trace := traceAcquire()
4264 casgstatus(gp, _Gwaiting, _Grunnable)
4265 if bubble != nil {
4266 bubble.decActive()
4267 }
4268 if trace.ok() {
4269 trace.GoUnpark(gp, 2)
4270 traceRelease(trace)
4271 }
4272 execute(gp, true) // Schedule it back, never returns.
4273 }
4274 }
4275
4276 if bubble != nil {
4277 bubble.decActive()
4278 }
4279
4280 schedule()
4281 }
4282
4283 func goschedImpl(gp *g, preempted bool) {
4284 trace := traceAcquire()
4285 status := readgstatus(gp)
4286 if status&^_Gscan != _Grunning {
4287 dumpgstatus(gp)
4288 throw("bad g status")
4289 }
4290 if trace.ok() {
4291 // Trace the event before the transition. It may take a
4292 // stack trace, but we won't own the stack after the
4293 // transition anymore.
4294 if preempted {
4295 trace.GoPreempt()
4296 } else {
4297 trace.GoSched()
4298 }
4299 }
4300 casgstatus(gp, _Grunning, _Grunnable)
4301 if trace.ok() {
4302 traceRelease(trace)
4303 }
4304
4305 dropg()
4306 lock(&sched.lock)
4307 globrunqput(gp)
4308 unlock(&sched.lock)
4309
4310 if mainStarted {
4311 wakep()
4312 }
4313
4314 schedule()
4315 }
4316
4317 // Gosched continuation on g0.
4318 func gosched_m(gp *g) {
4319 goschedImpl(gp, false)
4320 }
4321
4322 // goschedguarded is a forbidden-states-avoided version of gosched_m.
4323 func goschedguarded_m(gp *g) {
4324 if !canPreemptM(gp.m) {
4325 gogo(&gp.sched) // never return
4326 }
4327 goschedImpl(gp, false)
4328 }
4329
4330 func gopreempt_m(gp *g) {
4331 goschedImpl(gp, true)
4332 }
4333
4334 // preemptPark parks gp and puts it in _Gpreempted.
4335 //
4336 //go:systemstack
4337 func preemptPark(gp *g) {
4338 status := readgstatus(gp)
4339 if status&^_Gscan != _Grunning {
4340 dumpgstatus(gp)
4341 throw("bad g status")
4342 }
4343
4344 if gp.asyncSafePoint {
4345 // Double-check that async preemption does not
4346 // happen in SPWRITE assembly functions.
4347 // isAsyncSafePoint must exclude this case.
4348 f := findfunc(gp.sched.pc)
4349 if !f.valid() {
4350 throw("preempt at unknown pc")
4351 }
4352 if f.flag&abi.FuncFlagSPWrite != 0 {
4353 println("runtime: unexpected SPWRITE function", funcname(f), "in async preempt")
4354 throw("preempt SPWRITE")
4355 }
4356 }
4357
4358 // Transition from _Grunning to _Gscan|_Gpreempted. We can't
4359 // be in _Grunning when we dropg because then we'd be running
4360 // without an M, but the moment we're in _Gpreempted,
4361 // something could claim this G before we've fully cleaned it
4362 // up. Hence, we set the scan bit to lock down further
4363 // transitions until we can dropg.
4364 casGToPreemptScan(gp, _Grunning, _Gscan|_Gpreempted)
4365 dropg()
4366
4367 // Be careful about how we trace this next event. The ordering
4368 // is subtle.
4369 //
4370 // The moment we CAS into _Gpreempted, suspendG could CAS to
4371 // _Gwaiting, do its work, and ready the goroutine. All of
4372 // this could happen before we even get the chance to emit
4373 // an event. The end result is that the events could appear
4374 // out of order, and the tracer generally assumes the scheduler
4375 // takes care of the ordering between GoPark and GoUnpark.
4376 //
4377 // The answer here is simple: emit the event while we still hold
4378 // the _Gscan bit on the goroutine. We still need to traceAcquire
4379 // and traceRelease across the CAS because the tracer could be
4380 // what's calling suspendG in the first place, and we want the
4381 // CAS and event emission to appear atomic to the tracer.
4382 trace := traceAcquire()
4383 if trace.ok() {
4384 trace.GoPark(traceBlockPreempted, 0)
4385 }
4386 casfrom_Gscanstatus(gp, _Gscan|_Gpreempted, _Gpreempted)
4387 if trace.ok() {
4388 traceRelease(trace)
4389 }
4390 schedule()
4391 }
4392
4393 // goyield is like Gosched, but it:
4394 // - emits a GoPreempt trace event instead of a GoSched trace event
4395 // - puts the current G on the runq of the current P instead of the globrunq
4396 //
4397 // goyield should be an internal detail,
4398 // but widely used packages access it using linkname.
4399 // Notable members of the hall of shame include:
4400 // - gvisor.dev/gvisor
4401 // - github.com/sagernet/gvisor
4402 //
4403 // Do not remove or change the type signature.
4404 // See go.dev/issue/67401.
4405 //
4406 //go:linkname goyield
4407 func goyield() {
4408 checkTimeouts()
4409 mcall(goyield_m)
4410 }
4411
4412 func goyield_m(gp *g) {
4413 trace := traceAcquire()
4414 pp := gp.m.p.ptr()
4415 if trace.ok() {
4416 // Trace the event before the transition. It may take a
4417 // stack trace, but we won't own the stack after the
4418 // transition anymore.
4419 trace.GoPreempt()
4420 }
4421 casgstatus(gp, _Grunning, _Grunnable)
4422 if trace.ok() {
4423 traceRelease(trace)
4424 }
4425 dropg()
4426 runqput(pp, gp, false)
4427 schedule()
4428 }
4429
4430 // Finishes execution of the current goroutine.
4431 func goexit1() {
4432 if raceenabled {
4433 if gp := getg(); gp.bubble != nil {
4434 racereleasemergeg(gp, gp.bubble.raceaddr())
4435 }
4436 racegoend()
4437 }
4438 trace := traceAcquire()
4439 if trace.ok() {
4440 trace.GoEnd()
4441 traceRelease(trace)
4442 }
4443 mcall(goexit0)
4444 }
4445
4446 // goexit continuation on g0.
4447 func goexit0(gp *g) {
4448 gdestroy(gp)
4449 schedule()
4450 }
4451
4452 func gdestroy(gp *g) {
4453 mp := getg().m
4454 pp := mp.p.ptr()
4455
4456 casgstatus(gp, _Grunning, _Gdead)
4457 gcController.addScannableStack(pp, -int64(gp.stack.hi-gp.stack.lo))
4458 if isSystemGoroutine(gp, false) {
4459 sched.ngsys.Add(-1)
4460 }
4461 gp.m = nil
4462 locked := gp.lockedm != 0
4463 gp.lockedm = 0
4464 mp.lockedg = 0
4465 gp.preemptStop = false
4466 gp.paniconfault = false
4467 gp._defer = nil // should be true already but just in case.
4468 gp._panic = nil // non-nil for Goexit during panic. points at stack-allocated data.
4469 gp.writebuf = nil
4470 gp.waitreason = waitReasonZero
4471 gp.param = nil
4472 gp.labels = nil
4473 gp.timer = nil
4474 gp.bubble = nil
4475
4476 if gcBlackenEnabled != 0 && gp.gcAssistBytes > 0 {
4477 // Flush assist credit to the global pool. This gives
4478 // better information to pacing if the application is
4479 // rapidly creating an exiting goroutines.
4480 assistWorkPerByte := gcController.assistWorkPerByte.Load()
4481 scanCredit := int64(assistWorkPerByte * float64(gp.gcAssistBytes))
4482 gcController.bgScanCredit.Add(scanCredit)
4483 gp.gcAssistBytes = 0
4484 }
4485
4486 dropg()
4487
4488 if GOARCH == "wasm" { // no threads yet on wasm
4489 gfput(pp, gp)
4490 return
4491 }
4492
4493 if locked && mp.lockedInt != 0 {
4494 print("runtime: mp.lockedInt = ", mp.lockedInt, "\n")
4495 if mp.isextra {
4496 throw("runtime.Goexit called in a thread that was not created by the Go runtime")
4497 }
4498 throw("exited a goroutine internally locked to the OS thread")
4499 }
4500 gfput(pp, gp)
4501 if locked {
4502 // The goroutine may have locked this thread because
4503 // it put it in an unusual kernel state. Kill it
4504 // rather than returning it to the thread pool.
4505
4506 // Return to mstart, which will release the P and exit
4507 // the thread.
4508 if GOOS != "plan9" { // See golang.org/issue/22227.
4509 gogo(&mp.g0.sched)
4510 } else {
4511 // Clear lockedExt on plan9 since we may end up re-using
4512 // this thread.
4513 mp.lockedExt = 0
4514 }
4515 }
4516 }
4517
4518 // save updates getg().sched to refer to pc and sp so that a following
4519 // gogo will restore pc and sp.
4520 //
4521 // save must not have write barriers because invoking a write barrier
4522 // can clobber getg().sched.
4523 //
4524 //go:nosplit
4525 //go:nowritebarrierrec
4526 func save(pc, sp, bp uintptr) {
4527 gp := getg()
4528
4529 if gp == gp.m.g0 || gp == gp.m.gsignal {
4530 // m.g0.sched is special and must describe the context
4531 // for exiting the thread. mstart1 writes to it directly.
4532 // m.gsignal.sched should not be used at all.
4533 // This check makes sure save calls do not accidentally
4534 // run in contexts where they'd write to system g's.
4535 throw("save on system g not allowed")
4536 }
4537
4538 gp.sched.pc = pc
4539 gp.sched.sp = sp
4540 gp.sched.lr = 0
4541 gp.sched.bp = bp
4542 // We need to ensure ctxt is zero, but can't have a write
4543 // barrier here. However, it should always already be zero.
4544 // Assert that.
4545 if gp.sched.ctxt != nil {
4546 badctxt()
4547 }
4548 }
4549
4550 // The goroutine g is about to enter a system call.
4551 // Record that it's not using the cpu anymore.
4552 // This is called only from the go syscall library and cgocall,
4553 // not from the low-level system calls used by the runtime.
4554 //
4555 // Entersyscall cannot split the stack: the save must
4556 // make g->sched refer to the caller's stack segment, because
4557 // entersyscall is going to return immediately after.
4558 //
4559 // Nothing entersyscall calls can split the stack either.
4560 // We cannot safely move the stack during an active call to syscall,
4561 // because we do not know which of the uintptr arguments are
4562 // really pointers (back into the stack).
4563 // In practice, this means that we make the fast path run through
4564 // entersyscall doing no-split things, and the slow path has to use systemstack
4565 // to run bigger things on the system stack.
4566 //
4567 // reentersyscall is the entry point used by cgo callbacks, where explicitly
4568 // saved SP and PC are restored. This is needed when exitsyscall will be called
4569 // from a function further up in the call stack than the parent, as g->syscallsp
4570 // must always point to a valid stack frame. entersyscall below is the normal
4571 // entry point for syscalls, which obtains the SP and PC from the caller.
4572 //
4573 //go:nosplit
4574 func reentersyscall(pc, sp, bp uintptr) {
4575 trace := traceAcquire()
4576 gp := getg()
4577
4578 // Disable preemption because during this function g is in Gsyscall status,
4579 // but can have inconsistent g->sched, do not let GC observe it.
4580 gp.m.locks++
4581
4582 // Entersyscall must not call any function that might split/grow the stack.
4583 // (See details in comment above.)
4584 // Catch calls that might, by replacing the stack guard with something that
4585 // will trip any stack check and leaving a flag to tell newstack to die.
4586 gp.stackguard0 = stackPreempt
4587 gp.throwsplit = true
4588
4589 // Leave SP around for GC and traceback.
4590 save(pc, sp, bp)
4591 gp.syscallsp = sp
4592 gp.syscallpc = pc
4593 gp.syscallbp = bp
4594 casgstatus(gp, _Grunning, _Gsyscall)
4595 if staticLockRanking {
4596 // When doing static lock ranking casgstatus can call
4597 // systemstack which clobbers g.sched.
4598 save(pc, sp, bp)
4599 }
4600 if gp.syscallsp < gp.stack.lo || gp.stack.hi < gp.syscallsp {
4601 systemstack(func() {
4602 print("entersyscall inconsistent sp ", hex(gp.syscallsp), " [", hex(gp.stack.lo), ",", hex(gp.stack.hi), "]\n")
4603 throw("entersyscall")
4604 })
4605 }
4606 if gp.syscallbp != 0 && gp.syscallbp < gp.stack.lo || gp.stack.hi < gp.syscallbp {
4607 systemstack(func() {
4608 print("entersyscall inconsistent bp ", hex(gp.syscallbp), " [", hex(gp.stack.lo), ",", hex(gp.stack.hi), "]\n")
4609 throw("entersyscall")
4610 })
4611 }
4612
4613 if trace.ok() {
4614 systemstack(func() {
4615 trace.GoSysCall()
4616 traceRelease(trace)
4617 })
4618 // systemstack itself clobbers g.sched.{pc,sp} and we might
4619 // need them later when the G is genuinely blocked in a
4620 // syscall
4621 save(pc, sp, bp)
4622 }
4623
4624 if sched.sysmonwait.Load() {
4625 systemstack(entersyscall_sysmon)
4626 save(pc, sp, bp)
4627 }
4628
4629 if gp.m.p.ptr().runSafePointFn != 0 {
4630 // runSafePointFn may stack split if run on this stack
4631 systemstack(runSafePointFn)
4632 save(pc, sp, bp)
4633 }
4634
4635 gp.m.syscalltick = gp.m.p.ptr().syscalltick
4636 pp := gp.m.p.ptr()
4637 pp.m = 0
4638 gp.m.oldp.set(pp)
4639 gp.m.p = 0
4640 atomic.Store(&pp.status, _Psyscall)
4641 if sched.gcwaiting.Load() {
4642 systemstack(entersyscall_gcwait)
4643 save(pc, sp, bp)
4644 }
4645
4646 gp.m.locks--
4647 }
4648
4649 // Standard syscall entry used by the go syscall library and normal cgo calls.
4650 //
4651 // This is exported via linkname to assembly in the syscall package and x/sys.
4652 //
4653 // Other packages should not be accessing entersyscall directly,
4654 // but widely used packages access it using linkname.
4655 // Notable members of the hall of shame include:
4656 // - gvisor.dev/gvisor
4657 //
4658 // Do not remove or change the type signature.
4659 // See go.dev/issue/67401.
4660 //
4661 //go:nosplit
4662 //go:linkname entersyscall
4663 func entersyscall() {
4664 // N.B. getcallerfp cannot be written directly as argument in the call
4665 // to reentersyscall because it forces spilling the other arguments to
4666 // the stack. This results in exceeding the nosplit stack requirements
4667 // on some platforms.
4668 fp := getcallerfp()
4669 reentersyscall(sys.GetCallerPC(), sys.GetCallerSP(), fp)
4670 }
4671
4672 func entersyscall_sysmon() {
4673 lock(&sched.lock)
4674 if sched.sysmonwait.Load() {
4675 sched.sysmonwait.Store(false)
4676 notewakeup(&sched.sysmonnote)
4677 }
4678 unlock(&sched.lock)
4679 }
4680
4681 func entersyscall_gcwait() {
4682 gp := getg()
4683 pp := gp.m.oldp.ptr()
4684
4685 lock(&sched.lock)
4686 trace := traceAcquire()
4687 if sched.stopwait > 0 && atomic.Cas(&pp.status, _Psyscall, _Pgcstop) {
4688 if trace.ok() {
4689 // This is a steal in the new tracer. While it's very likely
4690 // that we were the ones to put this P into _Psyscall, between
4691 // then and now it's totally possible it had been stolen and
4692 // then put back into _Psyscall for us to acquire here. In such
4693 // case ProcStop would be incorrect.
4694 //
4695 // TODO(mknyszek): Consider emitting a ProcStop instead when
4696 // gp.m.syscalltick == pp.syscalltick, since then we know we never
4697 // lost the P.
4698 trace.ProcSteal(pp, true)
4699 traceRelease(trace)
4700 }
4701 pp.gcStopTime = nanotime()
4702 pp.syscalltick++
4703 if sched.stopwait--; sched.stopwait == 0 {
4704 notewakeup(&sched.stopnote)
4705 }
4706 } else if trace.ok() {
4707 traceRelease(trace)
4708 }
4709 unlock(&sched.lock)
4710 }
4711
4712 // The same as entersyscall(), but with a hint that the syscall is blocking.
4713
4714 // entersyscallblock should be an internal detail,
4715 // but widely used packages access it using linkname.
4716 // Notable members of the hall of shame include:
4717 // - gvisor.dev/gvisor
4718 //
4719 // Do not remove or change the type signature.
4720 // See go.dev/issue/67401.
4721 //
4722 //go:linkname entersyscallblock
4723 //go:nosplit
4724 func entersyscallblock() {
4725 gp := getg()
4726
4727 gp.m.locks++ // see comment in entersyscall
4728 gp.throwsplit = true
4729 gp.stackguard0 = stackPreempt // see comment in entersyscall
4730 gp.m.syscalltick = gp.m.p.ptr().syscalltick
4731 gp.m.p.ptr().syscalltick++
4732
4733 // Leave SP around for GC and traceback.
4734 pc := sys.GetCallerPC()
4735 sp := sys.GetCallerSP()
4736 bp := getcallerfp()
4737 save(pc, sp, bp)
4738 gp.syscallsp = gp.sched.sp
4739 gp.syscallpc = gp.sched.pc
4740 gp.syscallbp = gp.sched.bp
4741 if gp.syscallsp < gp.stack.lo || gp.stack.hi < gp.syscallsp {
4742 sp1 := sp
4743 sp2 := gp.sched.sp
4744 sp3 := gp.syscallsp
4745 systemstack(func() {
4746 print("entersyscallblock inconsistent sp ", hex(sp1), " ", hex(sp2), " ", hex(sp3), " [", hex(gp.stack.lo), ",", hex(gp.stack.hi), "]\n")
4747 throw("entersyscallblock")
4748 })
4749 }
4750 casgstatus(gp, _Grunning, _Gsyscall)
4751 if gp.syscallsp < gp.stack.lo || gp.stack.hi < gp.syscallsp {
4752 systemstack(func() {
4753 print("entersyscallblock inconsistent sp ", hex(sp), " ", hex(gp.sched.sp), " ", hex(gp.syscallsp), " [", hex(gp.stack.lo), ",", hex(gp.stack.hi), "]\n")
4754 throw("entersyscallblock")
4755 })
4756 }
4757 if gp.syscallbp != 0 && gp.syscallbp < gp.stack.lo || gp.stack.hi < gp.syscallbp {
4758 systemstack(func() {
4759 print("entersyscallblock inconsistent bp ", hex(bp), " ", hex(gp.sched.bp), " ", hex(gp.syscallbp), " [", hex(gp.stack.lo), ",", hex(gp.stack.hi), "]\n")
4760 throw("entersyscallblock")
4761 })
4762 }
4763
4764 systemstack(entersyscallblock_handoff)
4765
4766 // Resave for traceback during blocked call.
4767 save(sys.GetCallerPC(), sys.GetCallerSP(), getcallerfp())
4768
4769 gp.m.locks--
4770 }
4771
4772 func entersyscallblock_handoff() {
4773 trace := traceAcquire()
4774 if trace.ok() {
4775 trace.GoSysCall()
4776 traceRelease(trace)
4777 }
4778 handoffp(releasep())
4779 }
4780
4781 // The goroutine g exited its system call.
4782 // Arrange for it to run on a cpu again.
4783 // This is called only from the go syscall library, not
4784 // from the low-level system calls used by the runtime.
4785 //
4786 // Write barriers are not allowed because our P may have been stolen.
4787 //
4788 // This is exported via linkname to assembly in the syscall package.
4789 //
4790 // exitsyscall should be an internal detail,
4791 // but widely used packages access it using linkname.
4792 // Notable members of the hall of shame include:
4793 // - gvisor.dev/gvisor
4794 //
4795 // Do not remove or change the type signature.
4796 // See go.dev/issue/67401.
4797 //
4798 //go:nosplit
4799 //go:nowritebarrierrec
4800 //go:linkname exitsyscall
4801 func exitsyscall() {
4802 gp := getg()
4803
4804 gp.m.locks++ // see comment in entersyscall
4805 if sys.GetCallerSP() > gp.syscallsp {
4806 throw("exitsyscall: syscall frame is no longer valid")
4807 }
4808
4809 gp.waitsince = 0
4810 oldp := gp.m.oldp.ptr()
4811 gp.m.oldp = 0
4812 if exitsyscallfast(oldp) {
4813 // When exitsyscallfast returns success, we have a P so can now use
4814 // write barriers
4815 if goroutineProfile.active {
4816 // Make sure that gp has had its stack written out to the goroutine
4817 // profile, exactly as it was when the goroutine profiler first
4818 // stopped the world.
4819 systemstack(func() {
4820 tryRecordGoroutineProfileWB(gp)
4821 })
4822 }
4823 trace := traceAcquire()
4824 if trace.ok() {
4825 lostP := oldp != gp.m.p.ptr() || gp.m.syscalltick != gp.m.p.ptr().syscalltick
4826 systemstack(func() {
4827 // Write out syscall exit eagerly.
4828 //
4829 // It's important that we write this *after* we know whether we
4830 // lost our P or not (determined by exitsyscallfast).
4831 trace.GoSysExit(lostP)
4832 if lostP {
4833 // We lost the P at some point, even though we got it back here.
4834 // Trace that we're starting again, because there was a tracev2.GoSysBlock
4835 // call somewhere in exitsyscallfast (indicating that this goroutine
4836 // had blocked) and we're about to start running again.
4837 trace.GoStart()
4838 }
4839 })
4840 }
4841 // There's a cpu for us, so we can run.
4842 gp.m.p.ptr().syscalltick++
4843 // We need to cas the status and scan before resuming...
4844 casgstatus(gp, _Gsyscall, _Grunning)
4845 if trace.ok() {
4846 traceRelease(trace)
4847 }
4848
4849 // Garbage collector isn't running (since we are),
4850 // so okay to clear syscallsp.
4851 gp.syscallsp = 0
4852 gp.m.locks--
4853 if gp.preempt {
4854 // restore the preemption request in case we've cleared it in newstack
4855 gp.stackguard0 = stackPreempt
4856 } else {
4857 // otherwise restore the real stackGuard, we've spoiled it in entersyscall/entersyscallblock
4858 gp.stackguard0 = gp.stack.lo + stackGuard
4859 }
4860 gp.throwsplit = false
4861
4862 if sched.disable.user && !schedEnabled(gp) {
4863 // Scheduling of this goroutine is disabled.
4864 Gosched()
4865 }
4866
4867 return
4868 }
4869
4870 gp.m.locks--
4871
4872 // Call the scheduler.
4873 mcall(exitsyscall0)
4874
4875 // Scheduler returned, so we're allowed to run now.
4876 // Delete the syscallsp information that we left for
4877 // the garbage collector during the system call.
4878 // Must wait until now because until gosched returns
4879 // we don't know for sure that the garbage collector
4880 // is not running.
4881 gp.syscallsp = 0
4882 gp.m.p.ptr().syscalltick++
4883 gp.throwsplit = false
4884 }
4885
4886 //go:nosplit
4887 func exitsyscallfast(oldp *p) bool {
4888 // Freezetheworld sets stopwait but does not retake P's.
4889 if sched.stopwait == freezeStopWait {
4890 return false
4891 }
4892
4893 // Try to re-acquire the last P.
4894 trace := traceAcquire()
4895 if oldp != nil && oldp.status == _Psyscall && atomic.Cas(&oldp.status, _Psyscall, _Pidle) {
4896 // There's a cpu for us, so we can run.
4897 wirep(oldp)
4898 exitsyscallfast_reacquired(trace)
4899 if trace.ok() {
4900 traceRelease(trace)
4901 }
4902 return true
4903 }
4904 if trace.ok() {
4905 traceRelease(trace)
4906 }
4907
4908 // Try to get any other idle P.
4909 if sched.pidle != 0 {
4910 var ok bool
4911 systemstack(func() {
4912 ok = exitsyscallfast_pidle()
4913 })
4914 if ok {
4915 return true
4916 }
4917 }
4918 return false
4919 }
4920
4921 // exitsyscallfast_reacquired is the exitsyscall path on which this G
4922 // has successfully reacquired the P it was running on before the
4923 // syscall.
4924 //
4925 //go:nosplit
4926 func exitsyscallfast_reacquired(trace traceLocker) {
4927 gp := getg()
4928 if gp.m.syscalltick != gp.m.p.ptr().syscalltick {
4929 if trace.ok() {
4930 // The p was retaken and then enter into syscall again (since gp.m.syscalltick has changed).
4931 // tracev2.GoSysBlock for this syscall was already emitted,
4932 // but here we effectively retake the p from the new syscall running on the same p.
4933 systemstack(func() {
4934 // We're stealing the P. It's treated
4935 // as if it temporarily stopped running. Then, start running.
4936 trace.ProcSteal(gp.m.p.ptr(), true)
4937 trace.ProcStart()
4938 })
4939 }
4940 gp.m.p.ptr().syscalltick++
4941 }
4942 }
4943
4944 func exitsyscallfast_pidle() bool {
4945 lock(&sched.lock)
4946 pp, _ := pidleget(0)
4947 if pp != nil && sched.sysmonwait.Load() {
4948 sched.sysmonwait.Store(false)
4949 notewakeup(&sched.sysmonnote)
4950 }
4951 unlock(&sched.lock)
4952 if pp != nil {
4953 acquirep(pp)
4954 return true
4955 }
4956 return false
4957 }
4958
4959 // exitsyscall slow path on g0.
4960 // Failed to acquire P, enqueue gp as runnable.
4961 //
4962 // Called via mcall, so gp is the calling g from this M.
4963 //
4964 //go:nowritebarrierrec
4965 func exitsyscall0(gp *g) {
4966 var trace traceLocker
4967 traceExitingSyscall()
4968 trace = traceAcquire()
4969 casgstatus(gp, _Gsyscall, _Grunnable)
4970 traceExitedSyscall()
4971 if trace.ok() {
4972 // Write out syscall exit eagerly.
4973 //
4974 // It's important that we write this *after* we know whether we
4975 // lost our P or not (determined by exitsyscallfast).
4976 trace.GoSysExit(true)
4977 traceRelease(trace)
4978 }
4979 dropg()
4980 lock(&sched.lock)
4981 var pp *p
4982 if schedEnabled(gp) {
4983 pp, _ = pidleget(0)
4984 }
4985 var locked bool
4986 if pp == nil {
4987 globrunqput(gp)
4988
4989 // Below, we stoplockedm if gp is locked. globrunqput releases
4990 // ownership of gp, so we must check if gp is locked prior to
4991 // committing the release by unlocking sched.lock, otherwise we
4992 // could race with another M transitioning gp from unlocked to
4993 // locked.
4994 locked = gp.lockedm != 0
4995 } else if sched.sysmonwait.Load() {
4996 sched.sysmonwait.Store(false)
4997 notewakeup(&sched.sysmonnote)
4998 }
4999 unlock(&sched.lock)
5000 if pp != nil {
5001 acquirep(pp)
5002 execute(gp, false) // Never returns.
5003 }
5004 if locked {
5005 // Wait until another thread schedules gp and so m again.
5006 //
5007 // N.B. lockedm must be this M, as this g was running on this M
5008 // before entersyscall.
5009 stoplockedm()
5010 execute(gp, false) // Never returns.
5011 }
5012 stopm()
5013 schedule() // Never returns.
5014 }
5015
5016 // Called from syscall package before fork.
5017 //
5018 // syscall_runtime_BeforeFork is for package syscall,
5019 // but widely used packages access it using linkname.
5020 // Notable members of the hall of shame include:
5021 // - gvisor.dev/gvisor
5022 //
5023 // Do not remove or change the type signature.
5024 // See go.dev/issue/67401.
5025 //
5026 //go:linkname syscall_runtime_BeforeFork syscall.runtime_BeforeFork
5027 //go:nosplit
5028 func syscall_runtime_BeforeFork() {
5029 gp := getg().m.curg
5030
5031 // Block signals during a fork, so that the child does not run
5032 // a signal handler before exec if a signal is sent to the process
5033 // group. See issue #18600.
5034 gp.m.locks++
5035 sigsave(&gp.m.sigmask)
5036 sigblock(false)
5037
5038 // This function is called before fork in syscall package.
5039 // Code between fork and exec must not allocate memory nor even try to grow stack.
5040 // Here we spoil g.stackguard0 to reliably detect any attempts to grow stack.
5041 // runtime_AfterFork will undo this in parent process, but not in child.
5042 gp.stackguard0 = stackFork
5043 }
5044
5045 // Called from syscall package after fork in parent.
5046 //
5047 // syscall_runtime_AfterFork is for package syscall,
5048 // but widely used packages access it using linkname.
5049 // Notable members of the hall of shame include:
5050 // - gvisor.dev/gvisor
5051 //
5052 // Do not remove or change the type signature.
5053 // See go.dev/issue/67401.
5054 //
5055 //go:linkname syscall_runtime_AfterFork syscall.runtime_AfterFork
5056 //go:nosplit
5057 func syscall_runtime_AfterFork() {
5058 gp := getg().m.curg
5059
5060 // See the comments in beforefork.
5061 gp.stackguard0 = gp.stack.lo + stackGuard
5062
5063 msigrestore(gp.m.sigmask)
5064
5065 gp.m.locks--
5066 }
5067
5068 // inForkedChild is true while manipulating signals in the child process.
5069 // This is used to avoid calling libc functions in case we are using vfork.
5070 var inForkedChild bool
5071
5072 // Called from syscall package after fork in child.
5073 // It resets non-sigignored signals to the default handler, and
5074 // restores the signal mask in preparation for the exec.
5075 //
5076 // Because this might be called during a vfork, and therefore may be
5077 // temporarily sharing address space with the parent process, this must
5078 // not change any global variables or calling into C code that may do so.
5079 //
5080 // syscall_runtime_AfterForkInChild is for package syscall,
5081 // but widely used packages access it using linkname.
5082 // Notable members of the hall of shame include:
5083 // - gvisor.dev/gvisor
5084 //
5085 // Do not remove or change the type signature.
5086 // See go.dev/issue/67401.
5087 //
5088 //go:linkname syscall_runtime_AfterForkInChild syscall.runtime_AfterForkInChild
5089 //go:nosplit
5090 //go:nowritebarrierrec
5091 func syscall_runtime_AfterForkInChild() {
5092 // It's OK to change the global variable inForkedChild here
5093 // because we are going to change it back. There is no race here,
5094 // because if we are sharing address space with the parent process,
5095 // then the parent process can not be running concurrently.
5096 inForkedChild = true
5097
5098 clearSignalHandlers()
5099
5100 // When we are the child we are the only thread running,
5101 // so we know that nothing else has changed gp.m.sigmask.
5102 msigrestore(getg().m.sigmask)
5103
5104 inForkedChild = false
5105 }
5106
5107 // pendingPreemptSignals is the number of preemption signals
5108 // that have been sent but not received. This is only used on Darwin.
5109 // For #41702.
5110 var pendingPreemptSignals atomic.Int32
5111
5112 // Called from syscall package before Exec.
5113 //
5114 //go:linkname syscall_runtime_BeforeExec syscall.runtime_BeforeExec
5115 func syscall_runtime_BeforeExec() {
5116 // Prevent thread creation during exec.
5117 execLock.lock()
5118
5119 // On Darwin, wait for all pending preemption signals to
5120 // be received. See issue #41702.
5121 if GOOS == "darwin" || GOOS == "ios" {
5122 for pendingPreemptSignals.Load() > 0 {
5123 osyield()
5124 }
5125 }
5126 }
5127
5128 // Called from syscall package after Exec.
5129 //
5130 //go:linkname syscall_runtime_AfterExec syscall.runtime_AfterExec
5131 func syscall_runtime_AfterExec() {
5132 execLock.unlock()
5133 }
5134
5135 // Allocate a new g, with a stack big enough for stacksize bytes.
5136 func malg(stacksize int32) *g {
5137 newg := new(g)
5138 if stacksize >= 0 {
5139 stacksize = round2(stackSystem + stacksize)
5140 systemstack(func() {
5141 newg.stack = stackalloc(uint32(stacksize))
5142 if valgrindenabled {
5143 newg.valgrindStackID = valgrindRegisterStack(unsafe.Pointer(newg.stack.lo), unsafe.Pointer(newg.stack.hi))
5144 }
5145 })
5146 newg.stackguard0 = newg.stack.lo + stackGuard
5147 newg.stackguard1 = ^uintptr(0)
5148 // Clear the bottom word of the stack. We record g
5149 // there on gsignal stack during VDSO on ARM and ARM64.
5150 *(*uintptr)(unsafe.Pointer(newg.stack.lo)) = 0
5151 }
5152 return newg
5153 }
5154
5155 // Create a new g running fn.
5156 // Put it on the queue of g's waiting to run.
5157 // The compiler turns a go statement into a call to this.
5158 func newproc(fn *funcval) {
5159 gp := getg()
5160 pc := sys.GetCallerPC()
5161 systemstack(func() {
5162 newg := newproc1(fn, gp, pc, false, waitReasonZero)
5163
5164 pp := getg().m.p.ptr()
5165 runqput(pp, newg, true)
5166
5167 if mainStarted {
5168 wakep()
5169 }
5170 })
5171 }
5172
5173 // Create a new g in state _Grunnable (or _Gwaiting if parked is true), starting at fn.
5174 // callerpc is the address of the go statement that created this. The caller is responsible
5175 // for adding the new g to the scheduler. If parked is true, waitreason must be non-zero.
5176 func newproc1(fn *funcval, callergp *g, callerpc uintptr, parked bool, waitreason waitReason) *g {
5177 if fn == nil {
5178 fatal("go of nil func value")
5179 }
5180
5181 mp := acquirem() // disable preemption because we hold M and P in local vars.
5182 pp := mp.p.ptr()
5183 newg := gfget(pp)
5184 if newg == nil {
5185 newg = malg(stackMin)
5186 casgstatus(newg, _Gidle, _Gdead)
5187 allgadd(newg) // publishes with a g->status of Gdead so GC scanner doesn't look at uninitialized stack.
5188 }
5189 if newg.stack.hi == 0 {
5190 throw("newproc1: newg missing stack")
5191 }
5192
5193 if readgstatus(newg) != _Gdead {
5194 throw("newproc1: new g is not Gdead")
5195 }
5196
5197 totalSize := uintptr(4*goarch.PtrSize + sys.MinFrameSize) // extra space in case of reads slightly beyond frame
5198 totalSize = alignUp(totalSize, sys.StackAlign)
5199 sp := newg.stack.hi - totalSize
5200 if usesLR {
5201 // caller's LR
5202 *(*uintptr)(unsafe.Pointer(sp)) = 0
5203 prepGoExitFrame(sp)
5204 }
5205 if GOARCH == "arm64" {
5206 // caller's FP
5207 *(*uintptr)(unsafe.Pointer(sp - goarch.PtrSize)) = 0
5208 }
5209
5210 memclrNoHeapPointers(unsafe.Pointer(&newg.sched), unsafe.Sizeof(newg.sched))
5211 newg.sched.sp = sp
5212 newg.stktopsp = sp
5213 newg.sched.pc = abi.FuncPCABI0(goexit) + sys.PCQuantum // +PCQuantum so that previous instruction is in same function
5214 newg.sched.g = guintptr(unsafe.Pointer(newg))
5215 gostartcallfn(&newg.sched, fn)
5216 newg.parentGoid = callergp.goid
5217 newg.gopc = callerpc
5218 newg.ancestors = saveAncestors(callergp)
5219 newg.startpc = fn.fn
5220 newg.runningCleanups.Store(false)
5221 if isSystemGoroutine(newg, false) {
5222 sched.ngsys.Add(1)
5223 } else {
5224 // Only user goroutines inherit synctest groups and pprof labels.
5225 newg.bubble = callergp.bubble
5226 if mp.curg != nil {
5227 newg.labels = mp.curg.labels
5228 }
5229 if goroutineProfile.active {
5230 // A concurrent goroutine profile is running. It should include
5231 // exactly the set of goroutines that were alive when the goroutine
5232 // profiler first stopped the world. That does not include newg, so
5233 // mark it as not needing a profile before transitioning it from
5234 // _Gdead.
5235 newg.goroutineProfiled.Store(goroutineProfileSatisfied)
5236 }
5237 }
5238 // Track initial transition?
5239 newg.trackingSeq = uint8(cheaprand())
5240 if newg.trackingSeq%gTrackingPeriod == 0 {
5241 newg.tracking = true
5242 }
5243 gcController.addScannableStack(pp, int64(newg.stack.hi-newg.stack.lo))
5244
5245 // Get a goid and switch to runnable. Make all this atomic to the tracer.
5246 trace := traceAcquire()
5247 var status uint32 = _Grunnable
5248 if parked {
5249 status = _Gwaiting
5250 newg.waitreason = waitreason
5251 }
5252 if pp.goidcache == pp.goidcacheend {
5253 // Sched.goidgen is the last allocated id,
5254 // this batch must be [sched.goidgen+1, sched.goidgen+GoidCacheBatch].
5255 // At startup sched.goidgen=0, so main goroutine receives goid=1.
5256 pp.goidcache = sched.goidgen.Add(_GoidCacheBatch)
5257 pp.goidcache -= _GoidCacheBatch - 1
5258 pp.goidcacheend = pp.goidcache + _GoidCacheBatch
5259 }
5260 newg.goid = pp.goidcache
5261 casgstatus(newg, _Gdead, status)
5262 pp.goidcache++
5263 newg.trace.reset()
5264 if trace.ok() {
5265 trace.GoCreate(newg, newg.startpc, parked)
5266 traceRelease(trace)
5267 }
5268
5269 // Set up race context.
5270 if raceenabled {
5271 newg.racectx = racegostart(callerpc)
5272 newg.raceignore = 0
5273 if newg.labels != nil {
5274 // See note in proflabel.go on labelSync's role in synchronizing
5275 // with the reads in the signal handler.
5276 racereleasemergeg(newg, unsafe.Pointer(&labelSync))
5277 }
5278 }
5279 releasem(mp)
5280
5281 return newg
5282 }
5283
5284 // saveAncestors copies previous ancestors of the given caller g and
5285 // includes info for the current caller into a new set of tracebacks for
5286 // a g being created.
5287 func saveAncestors(callergp *g) *[]ancestorInfo {
5288 // Copy all prior info, except for the root goroutine (goid 0).
5289 if debug.tracebackancestors <= 0 || callergp.goid == 0 {
5290 return nil
5291 }
5292 var callerAncestors []ancestorInfo
5293 if callergp.ancestors != nil {
5294 callerAncestors = *callergp.ancestors
5295 }
5296 n := int32(len(callerAncestors)) + 1
5297 if n > debug.tracebackancestors {
5298 n = debug.tracebackancestors
5299 }
5300 ancestors := make([]ancestorInfo, n)
5301 copy(ancestors[1:], callerAncestors)
5302
5303 var pcs [tracebackInnerFrames]uintptr
5304 npcs := gcallers(callergp, 0, pcs[:])
5305 ipcs := make([]uintptr, npcs)
5306 copy(ipcs, pcs[:])
5307 ancestors[0] = ancestorInfo{
5308 pcs: ipcs,
5309 goid: callergp.goid,
5310 gopc: callergp.gopc,
5311 }
5312
5313 ancestorsp := new([]ancestorInfo)
5314 *ancestorsp = ancestors
5315 return ancestorsp
5316 }
5317
5318 // Put on gfree list.
5319 // If local list is too long, transfer a batch to the global list.
5320 func gfput(pp *p, gp *g) {
5321 if readgstatus(gp) != _Gdead {
5322 throw("gfput: bad status (not Gdead)")
5323 }
5324
5325 stksize := gp.stack.hi - gp.stack.lo
5326
5327 if stksize != uintptr(startingStackSize) {
5328 // non-standard stack size - free it.
5329 stackfree(gp.stack)
5330 gp.stack.lo = 0
5331 gp.stack.hi = 0
5332 gp.stackguard0 = 0
5333 if valgrindenabled {
5334 valgrindDeregisterStack(gp.valgrindStackID)
5335 gp.valgrindStackID = 0
5336 }
5337 }
5338
5339 pp.gFree.push(gp)
5340 if pp.gFree.size >= 64 {
5341 var (
5342 stackQ gQueue
5343 noStackQ gQueue
5344 )
5345 for pp.gFree.size >= 32 {
5346 gp := pp.gFree.pop()
5347 if gp.stack.lo == 0 {
5348 noStackQ.push(gp)
5349 } else {
5350 stackQ.push(gp)
5351 }
5352 }
5353 lock(&sched.gFree.lock)
5354 sched.gFree.noStack.pushAll(noStackQ)
5355 sched.gFree.stack.pushAll(stackQ)
5356 unlock(&sched.gFree.lock)
5357 }
5358 }
5359
5360 // Get from gfree list.
5361 // If local list is empty, grab a batch from global list.
5362 func gfget(pp *p) *g {
5363 retry:
5364 if pp.gFree.empty() && (!sched.gFree.stack.empty() || !sched.gFree.noStack.empty()) {
5365 lock(&sched.gFree.lock)
5366 // Move a batch of free Gs to the P.
5367 for pp.gFree.size < 32 {
5368 // Prefer Gs with stacks.
5369 gp := sched.gFree.stack.pop()
5370 if gp == nil {
5371 gp = sched.gFree.noStack.pop()
5372 if gp == nil {
5373 break
5374 }
5375 }
5376 pp.gFree.push(gp)
5377 }
5378 unlock(&sched.gFree.lock)
5379 goto retry
5380 }
5381 gp := pp.gFree.pop()
5382 if gp == nil {
5383 return nil
5384 }
5385 if gp.stack.lo != 0 && gp.stack.hi-gp.stack.lo != uintptr(startingStackSize) {
5386 // Deallocate old stack. We kept it in gfput because it was the
5387 // right size when the goroutine was put on the free list, but
5388 // the right size has changed since then.
5389 systemstack(func() {
5390 stackfree(gp.stack)
5391 gp.stack.lo = 0
5392 gp.stack.hi = 0
5393 gp.stackguard0 = 0
5394 if valgrindenabled {
5395 valgrindDeregisterStack(gp.valgrindStackID)
5396 gp.valgrindStackID = 0
5397 }
5398 })
5399 }
5400 if gp.stack.lo == 0 {
5401 // Stack was deallocated in gfput or just above. Allocate a new one.
5402 systemstack(func() {
5403 gp.stack = stackalloc(startingStackSize)
5404 if valgrindenabled {
5405 gp.valgrindStackID = valgrindRegisterStack(unsafe.Pointer(gp.stack.lo), unsafe.Pointer(gp.stack.hi))
5406 }
5407 })
5408 gp.stackguard0 = gp.stack.lo + stackGuard
5409 } else {
5410 if raceenabled {
5411 racemalloc(unsafe.Pointer(gp.stack.lo), gp.stack.hi-gp.stack.lo)
5412 }
5413 if msanenabled {
5414 msanmalloc(unsafe.Pointer(gp.stack.lo), gp.stack.hi-gp.stack.lo)
5415 }
5416 if asanenabled {
5417 asanunpoison(unsafe.Pointer(gp.stack.lo), gp.stack.hi-gp.stack.lo)
5418 }
5419 }
5420 return gp
5421 }
5422
5423 // Purge all cached G's from gfree list to the global list.
5424 func gfpurge(pp *p) {
5425 var (
5426 stackQ gQueue
5427 noStackQ gQueue
5428 )
5429 for !pp.gFree.empty() {
5430 gp := pp.gFree.pop()
5431 if gp.stack.lo == 0 {
5432 noStackQ.push(gp)
5433 } else {
5434 stackQ.push(gp)
5435 }
5436 }
5437 lock(&sched.gFree.lock)
5438 sched.gFree.noStack.pushAll(noStackQ)
5439 sched.gFree.stack.pushAll(stackQ)
5440 unlock(&sched.gFree.lock)
5441 }
5442
5443 // Breakpoint executes a breakpoint trap.
5444 func Breakpoint() {
5445 breakpoint()
5446 }
5447
5448 // dolockOSThread is called by LockOSThread and lockOSThread below
5449 // after they modify m.locked. Do not allow preemption during this call,
5450 // or else the m might be different in this function than in the caller.
5451 //
5452 //go:nosplit
5453 func dolockOSThread() {
5454 if GOARCH == "wasm" {
5455 return // no threads on wasm yet
5456 }
5457 gp := getg()
5458 gp.m.lockedg.set(gp)
5459 gp.lockedm.set(gp.m)
5460 }
5461
5462 // LockOSThread wires the calling goroutine to its current operating system thread.
5463 // The calling goroutine will always execute in that thread,
5464 // and no other goroutine will execute in it,
5465 // until the calling goroutine has made as many calls to
5466 // [UnlockOSThread] as to LockOSThread.
5467 // If the calling goroutine exits without unlocking the thread,
5468 // the thread will be terminated.
5469 //
5470 // All init functions are run on the startup thread. Calling LockOSThread
5471 // from an init function will cause the main function to be invoked on
5472 // that thread.
5473 //
5474 // A goroutine should call LockOSThread before calling OS services or
5475 // non-Go library functions that depend on per-thread state.
5476 //
5477 //go:nosplit
5478 func LockOSThread() {
5479 if atomic.Load(&newmHandoff.haveTemplateThread) == 0 && GOOS != "plan9" {
5480 // If we need to start a new thread from the locked
5481 // thread, we need the template thread. Start it now
5482 // while we're in a known-good state.
5483 startTemplateThread()
5484 }
5485 gp := getg()
5486 gp.m.lockedExt++
5487 if gp.m.lockedExt == 0 {
5488 gp.m.lockedExt--
5489 panic("LockOSThread nesting overflow")
5490 }
5491 dolockOSThread()
5492 }
5493
5494 //go:nosplit
5495 func lockOSThread() {
5496 getg().m.lockedInt++
5497 dolockOSThread()
5498 }
5499
5500 // dounlockOSThread is called by UnlockOSThread and unlockOSThread below
5501 // after they update m->locked. Do not allow preemption during this call,
5502 // or else the m might be in different in this function than in the caller.
5503 //
5504 //go:nosplit
5505 func dounlockOSThread() {
5506 if GOARCH == "wasm" {
5507 return // no threads on wasm yet
5508 }
5509 gp := getg()
5510 if gp.m.lockedInt != 0 || gp.m.lockedExt != 0 {
5511 return
5512 }
5513 gp.m.lockedg = 0
5514 gp.lockedm = 0
5515 }
5516
5517 // UnlockOSThread undoes an earlier call to LockOSThread.
5518 // If this drops the number of active LockOSThread calls on the
5519 // calling goroutine to zero, it unwires the calling goroutine from
5520 // its fixed operating system thread.
5521 // If there are no active LockOSThread calls, this is a no-op.
5522 //
5523 // Before calling UnlockOSThread, the caller must ensure that the OS
5524 // thread is suitable for running other goroutines. If the caller made
5525 // any permanent changes to the state of the thread that would affect
5526 // other goroutines, it should not call this function and thus leave
5527 // the goroutine locked to the OS thread until the goroutine (and
5528 // hence the thread) exits.
5529 //
5530 //go:nosplit
5531 func UnlockOSThread() {
5532 gp := getg()
5533 if gp.m.lockedExt == 0 {
5534 return
5535 }
5536 gp.m.lockedExt--
5537 dounlockOSThread()
5538 }
5539
5540 //go:nosplit
5541 func unlockOSThread() {
5542 gp := getg()
5543 if gp.m.lockedInt == 0 {
5544 systemstack(badunlockosthread)
5545 }
5546 gp.m.lockedInt--
5547 dounlockOSThread()
5548 }
5549
5550 func badunlockosthread() {
5551 throw("runtime: internal error: misuse of lockOSThread/unlockOSThread")
5552 }
5553
5554 func gcount() int32 {
5555 n := int32(atomic.Loaduintptr(&allglen)) - sched.gFree.stack.size - sched.gFree.noStack.size - sched.ngsys.Load()
5556 for _, pp := range allp {
5557 n -= pp.gFree.size
5558 }
5559
5560 // All these variables can be changed concurrently, so the result can be inconsistent.
5561 // But at least the current goroutine is running.
5562 if n < 1 {
5563 n = 1
5564 }
5565 return n
5566 }
5567
5568 func mcount() int32 {
5569 return int32(sched.mnext - sched.nmfreed)
5570 }
5571
5572 var prof struct {
5573 signalLock atomic.Uint32
5574
5575 // Must hold signalLock to write. Reads may be lock-free, but
5576 // signalLock should be taken to synchronize with changes.
5577 hz atomic.Int32
5578 }
5579
5580 func _System() { _System() }
5581 func _ExternalCode() { _ExternalCode() }
5582 func _LostExternalCode() { _LostExternalCode() }
5583 func _GC() { _GC() }
5584 func _LostSIGPROFDuringAtomic64() { _LostSIGPROFDuringAtomic64() }
5585 func _LostContendedRuntimeLock() { _LostContendedRuntimeLock() }
5586 func _VDSO() { _VDSO() }
5587
5588 // Called if we receive a SIGPROF signal.
5589 // Called by the signal handler, may run during STW.
5590 //
5591 //go:nowritebarrierrec
5592 func sigprof(pc, sp, lr uintptr, gp *g, mp *m) {
5593 if prof.hz.Load() == 0 {
5594 return
5595 }
5596
5597 // If mp.profilehz is 0, then profiling is not enabled for this thread.
5598 // We must check this to avoid a deadlock between setcpuprofilerate
5599 // and the call to cpuprof.add, below.
5600 if mp != nil && mp.profilehz == 0 {
5601 return
5602 }
5603
5604 // On mips{,le}/arm, 64bit atomics are emulated with spinlocks, in
5605 // internal/runtime/atomic. If SIGPROF arrives while the program is inside
5606 // the critical section, it creates a deadlock (when writing the sample).
5607 // As a workaround, create a counter of SIGPROFs while in critical section
5608 // to store the count, and pass it to sigprof.add() later when SIGPROF is
5609 // received from somewhere else (with _LostSIGPROFDuringAtomic64 as pc).
5610 if GOARCH == "mips" || GOARCH == "mipsle" || GOARCH == "arm" {
5611 if f := findfunc(pc); f.valid() {
5612 if stringslite.HasPrefix(funcname(f), "internal/runtime/atomic") {
5613 cpuprof.lostAtomic++
5614 return
5615 }
5616 }
5617 if GOARCH == "arm" && goarm < 7 && GOOS == "linux" && pc&0xffff0000 == 0xffff0000 {
5618 // internal/runtime/atomic functions call into kernel
5619 // helpers on arm < 7. See
5620 // internal/runtime/atomic/sys_linux_arm.s.
5621 cpuprof.lostAtomic++
5622 return
5623 }
5624 }
5625
5626 // Profiling runs concurrently with GC, so it must not allocate.
5627 // Set a trap in case the code does allocate.
5628 // Note that on windows, one thread takes profiles of all the
5629 // other threads, so mp is usually not getg().m.
5630 // In fact mp may not even be stopped.
5631 // See golang.org/issue/17165.
5632 getg().m.mallocing++
5633
5634 var u unwinder
5635 var stk [maxCPUProfStack]uintptr
5636 n := 0
5637 if mp.ncgo > 0 && mp.curg != nil && mp.curg.syscallpc != 0 && mp.curg.syscallsp != 0 {
5638 cgoOff := 0
5639 // Check cgoCallersUse to make sure that we are not
5640 // interrupting other code that is fiddling with
5641 // cgoCallers. We are running in a signal handler
5642 // with all signals blocked, so we don't have to worry
5643 // about any other code interrupting us.
5644 if mp.cgoCallersUse.Load() == 0 && mp.cgoCallers != nil && mp.cgoCallers[0] != 0 {
5645 for cgoOff < len(mp.cgoCallers) && mp.cgoCallers[cgoOff] != 0 {
5646 cgoOff++
5647 }
5648 n += copy(stk[:], mp.cgoCallers[:cgoOff])
5649 mp.cgoCallers[0] = 0
5650 }
5651
5652 // Collect Go stack that leads to the cgo call.
5653 u.initAt(mp.curg.syscallpc, mp.curg.syscallsp, 0, mp.curg, unwindSilentErrors)
5654 } else if usesLibcall() && mp.libcallg != 0 && mp.libcallpc != 0 && mp.libcallsp != 0 {
5655 // Libcall, i.e. runtime syscall on windows.
5656 // Collect Go stack that leads to the call.
5657 u.initAt(mp.libcallpc, mp.libcallsp, 0, mp.libcallg.ptr(), unwindSilentErrors)
5658 } else if mp != nil && mp.vdsoSP != 0 {
5659 // VDSO call, e.g. nanotime1 on Linux.
5660 // Collect Go stack that leads to the call.
5661 u.initAt(mp.vdsoPC, mp.vdsoSP, 0, gp, unwindSilentErrors|unwindJumpStack)
5662 } else {
5663 u.initAt(pc, sp, lr, gp, unwindSilentErrors|unwindTrap|unwindJumpStack)
5664 }
5665 n += tracebackPCs(&u, 0, stk[n:])
5666
5667 if n <= 0 {
5668 // Normal traceback is impossible or has failed.
5669 // Account it against abstract "System" or "GC".
5670 n = 2
5671 if inVDSOPage(pc) {
5672 pc = abi.FuncPCABIInternal(_VDSO) + sys.PCQuantum
5673 } else if pc > firstmoduledata.etext {
5674 // "ExternalCode" is better than "etext".
5675 pc = abi.FuncPCABIInternal(_ExternalCode) + sys.PCQuantum
5676 }
5677 stk[0] = pc
5678 if mp.preemptoff != "" {
5679 stk[1] = abi.FuncPCABIInternal(_GC) + sys.PCQuantum
5680 } else {
5681 stk[1] = abi.FuncPCABIInternal(_System) + sys.PCQuantum
5682 }
5683 }
5684
5685 if prof.hz.Load() != 0 {
5686 // Note: it can happen on Windows that we interrupted a system thread
5687 // with no g, so gp could nil. The other nil checks are done out of
5688 // caution, but not expected to be nil in practice.
5689 var tagPtr *unsafe.Pointer
5690 if gp != nil && gp.m != nil && gp.m.curg != nil {
5691 tagPtr = &gp.m.curg.labels
5692 }
5693 cpuprof.add(tagPtr, stk[:n])
5694
5695 gprof := gp
5696 var mp *m
5697 var pp *p
5698 if gp != nil && gp.m != nil {
5699 if gp.m.curg != nil {
5700 gprof = gp.m.curg
5701 }
5702 mp = gp.m
5703 pp = gp.m.p.ptr()
5704 }
5705 traceCPUSample(gprof, mp, pp, stk[:n])
5706 }
5707 getg().m.mallocing--
5708 }
5709
5710 // setcpuprofilerate sets the CPU profiling rate to hz times per second.
5711 // If hz <= 0, setcpuprofilerate turns off CPU profiling.
5712 func setcpuprofilerate(hz int32) {
5713 // Force sane arguments.
5714 if hz < 0 {
5715 hz = 0
5716 }
5717
5718 // Disable preemption, otherwise we can be rescheduled to another thread
5719 // that has profiling enabled.
5720 gp := getg()
5721 gp.m.locks++
5722
5723 // Stop profiler on this thread so that it is safe to lock prof.
5724 // if a profiling signal came in while we had prof locked,
5725 // it would deadlock.
5726 setThreadCPUProfiler(0)
5727
5728 for !prof.signalLock.CompareAndSwap(0, 1) {
5729 osyield()
5730 }
5731 if prof.hz.Load() != hz {
5732 setProcessCPUProfiler(hz)
5733 prof.hz.Store(hz)
5734 }
5735 prof.signalLock.Store(0)
5736
5737 lock(&sched.lock)
5738 sched.profilehz = hz
5739 unlock(&sched.lock)
5740
5741 if hz != 0 {
5742 setThreadCPUProfiler(hz)
5743 }
5744
5745 gp.m.locks--
5746 }
5747
5748 // init initializes pp, which may be a freshly allocated p or a
5749 // previously destroyed p, and transitions it to status _Pgcstop.
5750 func (pp *p) init(id int32) {
5751 pp.id = id
5752 pp.status = _Pgcstop
5753 pp.sudogcache = pp.sudogbuf[:0]
5754 pp.deferpool = pp.deferpoolbuf[:0]
5755 pp.wbBuf.reset()
5756 if pp.mcache == nil {
5757 if id == 0 {
5758 if mcache0 == nil {
5759 throw("missing mcache?")
5760 }
5761 // Use the bootstrap mcache0. Only one P will get
5762 // mcache0: the one with ID 0.
5763 pp.mcache = mcache0
5764 } else {
5765 pp.mcache = allocmcache()
5766 }
5767 }
5768 if raceenabled && pp.raceprocctx == 0 {
5769 if id == 0 {
5770 pp.raceprocctx = raceprocctx0
5771 raceprocctx0 = 0 // bootstrap
5772 } else {
5773 pp.raceprocctx = raceproccreate()
5774 }
5775 }
5776 lockInit(&pp.timers.mu, lockRankTimers)
5777
5778 // This P may get timers when it starts running. Set the mask here
5779 // since the P may not go through pidleget (notably P 0 on startup).
5780 timerpMask.set(id)
5781 // Similarly, we may not go through pidleget before this P starts
5782 // running if it is P 0 on startup.
5783 idlepMask.clear(id)
5784 }
5785
5786 // destroy releases all of the resources associated with pp and
5787 // transitions it to status _Pdead.
5788 //
5789 // sched.lock must be held and the world must be stopped.
5790 func (pp *p) destroy() {
5791 assertLockHeld(&sched.lock)
5792 assertWorldStopped()
5793
5794 // Move all runnable goroutines to the global queue
5795 for pp.runqhead != pp.runqtail {
5796 // Pop from tail of local queue
5797 pp.runqtail--
5798 gp := pp.runq[pp.runqtail%uint32(len(pp.runq))].ptr()
5799 // Push onto head of global queue
5800 globrunqputhead(gp)
5801 }
5802 if pp.runnext != 0 {
5803 globrunqputhead(pp.runnext.ptr())
5804 pp.runnext = 0
5805 }
5806
5807 // Move all timers to the local P.
5808 getg().m.p.ptr().timers.take(&pp.timers)
5809
5810 // Flush p's write barrier buffer.
5811 if gcphase != _GCoff {
5812 wbBufFlush1(pp)
5813 pp.gcw.dispose()
5814 }
5815 clear(pp.sudogbuf[:])
5816 pp.sudogcache = pp.sudogbuf[:0]
5817 pp.pinnerCache = nil
5818 clear(pp.deferpoolbuf[:])
5819 pp.deferpool = pp.deferpoolbuf[:0]
5820 systemstack(func() {
5821 for i := 0; i < pp.mspancache.len; i++ {
5822 // Safe to call since the world is stopped.
5823 mheap_.spanalloc.free(unsafe.Pointer(pp.mspancache.buf[i]))
5824 }
5825 pp.mspancache.len = 0
5826 lock(&mheap_.lock)
5827 pp.pcache.flush(&mheap_.pages)
5828 unlock(&mheap_.lock)
5829 })
5830 freemcache(pp.mcache)
5831 pp.mcache = nil
5832 gfpurge(pp)
5833 if raceenabled {
5834 if pp.timers.raceCtx != 0 {
5835 // The race detector code uses a callback to fetch
5836 // the proc context, so arrange for that callback
5837 // to see the right thing.
5838 // This hack only works because we are the only
5839 // thread running.
5840 mp := getg().m
5841 phold := mp.p.ptr()
5842 mp.p.set(pp)
5843
5844 racectxend(pp.timers.raceCtx)
5845 pp.timers.raceCtx = 0
5846
5847 mp.p.set(phold)
5848 }
5849 raceprocdestroy(pp.raceprocctx)
5850 pp.raceprocctx = 0
5851 }
5852 pp.gcAssistTime = 0
5853 gcCleanups.queued += pp.cleanupsQueued
5854 pp.cleanupsQueued = 0
5855 pp.status = _Pdead
5856 }
5857
5858 // Change number of processors.
5859 //
5860 // sched.lock must be held, and the world must be stopped.
5861 //
5862 // gcworkbufs must not be being modified by either the GC or the write barrier
5863 // code, so the GC must not be running if the number of Ps actually changes.
5864 //
5865 // Returns list of Ps with local work, they need to be scheduled by the caller.
5866 func procresize(nprocs int32) *p {
5867 assertLockHeld(&sched.lock)
5868 assertWorldStopped()
5869
5870 old := gomaxprocs
5871 if old < 0 || nprocs <= 0 {
5872 throw("procresize: invalid arg")
5873 }
5874 trace := traceAcquire()
5875 if trace.ok() {
5876 trace.Gomaxprocs(nprocs)
5877 traceRelease(trace)
5878 }
5879
5880 // update statistics
5881 now := nanotime()
5882 if sched.procresizetime != 0 {
5883 sched.totaltime += int64(old) * (now - sched.procresizetime)
5884 }
5885 sched.procresizetime = now
5886
5887 maskWords := (nprocs + 31) / 32
5888
5889 // Grow allp if necessary.
5890 if nprocs > int32(len(allp)) {
5891 // Synchronize with retake, which could be running
5892 // concurrently since it doesn't run on a P.
5893 lock(&allpLock)
5894 if nprocs <= int32(cap(allp)) {
5895 allp = allp[:nprocs]
5896 } else {
5897 nallp := make([]*p, nprocs)
5898 // Copy everything up to allp's cap so we
5899 // never lose old allocated Ps.
5900 copy(nallp, allp[:cap(allp)])
5901 allp = nallp
5902 }
5903
5904 if maskWords <= int32(cap(idlepMask)) {
5905 idlepMask = idlepMask[:maskWords]
5906 timerpMask = timerpMask[:maskWords]
5907 } else {
5908 nidlepMask := make([]uint32, maskWords)
5909 // No need to copy beyond len, old Ps are irrelevant.
5910 copy(nidlepMask, idlepMask)
5911 idlepMask = nidlepMask
5912
5913 ntimerpMask := make([]uint32, maskWords)
5914 copy(ntimerpMask, timerpMask)
5915 timerpMask = ntimerpMask
5916 }
5917 unlock(&allpLock)
5918 }
5919
5920 // initialize new P's
5921 for i := old; i < nprocs; i++ {
5922 pp := allp[i]
5923 if pp == nil {
5924 pp = new(p)
5925 }
5926 pp.init(i)
5927 atomicstorep(unsafe.Pointer(&allp[i]), unsafe.Pointer(pp))
5928 }
5929
5930 gp := getg()
5931 if gp.m.p != 0 && gp.m.p.ptr().id < nprocs {
5932 // continue to use the current P
5933 gp.m.p.ptr().status = _Prunning
5934 gp.m.p.ptr().mcache.prepareForSweep()
5935 } else {
5936 // release the current P and acquire allp[0].
5937 //
5938 // We must do this before destroying our current P
5939 // because p.destroy itself has write barriers, so we
5940 // need to do that from a valid P.
5941 if gp.m.p != 0 {
5942 trace := traceAcquire()
5943 if trace.ok() {
5944 // Pretend that we were descheduled
5945 // and then scheduled again to keep
5946 // the trace consistent.
5947 trace.GoSched()
5948 trace.ProcStop(gp.m.p.ptr())
5949 traceRelease(trace)
5950 }
5951 gp.m.p.ptr().m = 0
5952 }
5953 gp.m.p = 0
5954 pp := allp[0]
5955 pp.m = 0
5956 pp.status = _Pidle
5957 acquirep(pp)
5958 trace := traceAcquire()
5959 if trace.ok() {
5960 trace.GoStart()
5961 traceRelease(trace)
5962 }
5963 }
5964
5965 // g.m.p is now set, so we no longer need mcache0 for bootstrapping.
5966 mcache0 = nil
5967
5968 // release resources from unused P's
5969 for i := nprocs; i < old; i++ {
5970 pp := allp[i]
5971 pp.destroy()
5972 // can't free P itself because it can be referenced by an M in syscall
5973 }
5974
5975 // Trim allp.
5976 if int32(len(allp)) != nprocs {
5977 lock(&allpLock)
5978 allp = allp[:nprocs]
5979 idlepMask = idlepMask[:maskWords]
5980 timerpMask = timerpMask[:maskWords]
5981 unlock(&allpLock)
5982 }
5983
5984 var runnablePs *p
5985 for i := nprocs - 1; i >= 0; i-- {
5986 pp := allp[i]
5987 if gp.m.p.ptr() == pp {
5988 continue
5989 }
5990 pp.status = _Pidle
5991 if runqempty(pp) {
5992 pidleput(pp, now)
5993 } else {
5994 pp.m.set(mget())
5995 pp.link.set(runnablePs)
5996 runnablePs = pp
5997 }
5998 }
5999 stealOrder.reset(uint32(nprocs))
6000 var int32p *int32 = &gomaxprocs // make compiler check that gomaxprocs is an int32
6001 atomic.Store((*uint32)(unsafe.Pointer(int32p)), uint32(nprocs))
6002 if old != nprocs {
6003 // Notify the limiter that the amount of procs has changed.
6004 gcCPULimiter.resetCapacity(now, nprocs)
6005 }
6006 return runnablePs
6007 }
6008
6009 // Associate p and the current m.
6010 //
6011 // This function is allowed to have write barriers even if the caller
6012 // isn't because it immediately acquires pp.
6013 //
6014 //go:yeswritebarrierrec
6015 func acquirep(pp *p) {
6016 // Do the part that isn't allowed to have write barriers.
6017 wirep(pp)
6018
6019 // Have p; write barriers now allowed.
6020
6021 // Perform deferred mcache flush before this P can allocate
6022 // from a potentially stale mcache.
6023 pp.mcache.prepareForSweep()
6024
6025 trace := traceAcquire()
6026 if trace.ok() {
6027 trace.ProcStart()
6028 traceRelease(trace)
6029 }
6030 }
6031
6032 // wirep is the first step of acquirep, which actually associates the
6033 // current M to pp. This is broken out so we can disallow write
6034 // barriers for this part, since we don't yet have a P.
6035 //
6036 //go:nowritebarrierrec
6037 //go:nosplit
6038 func wirep(pp *p) {
6039 gp := getg()
6040
6041 if gp.m.p != 0 {
6042 // Call on the systemstack to avoid a nosplit overflow build failure
6043 // on some platforms when built with -N -l. See #64113.
6044 systemstack(func() {
6045 throw("wirep: already in go")
6046 })
6047 }
6048 if pp.m != 0 || pp.status != _Pidle {
6049 // Call on the systemstack to avoid a nosplit overflow build failure
6050 // on some platforms when built with -N -l. See #64113.
6051 systemstack(func() {
6052 id := int64(0)
6053 if pp.m != 0 {
6054 id = pp.m.ptr().id
6055 }
6056 print("wirep: p->m=", pp.m, "(", id, ") p->status=", pp.status, "\n")
6057 throw("wirep: invalid p state")
6058 })
6059 }
6060 gp.m.p.set(pp)
6061 pp.m.set(gp.m)
6062 pp.status = _Prunning
6063 }
6064
6065 // Disassociate p and the current m.
6066 func releasep() *p {
6067 trace := traceAcquire()
6068 if trace.ok() {
6069 trace.ProcStop(getg().m.p.ptr())
6070 traceRelease(trace)
6071 }
6072 return releasepNoTrace()
6073 }
6074
6075 // Disassociate p and the current m without tracing an event.
6076 func releasepNoTrace() *p {
6077 gp := getg()
6078
6079 if gp.m.p == 0 {
6080 throw("releasep: invalid arg")
6081 }
6082 pp := gp.m.p.ptr()
6083 if pp.m.ptr() != gp.m || pp.status != _Prunning {
6084 print("releasep: m=", gp.m, " m->p=", gp.m.p.ptr(), " p->m=", hex(pp.m), " p->status=", pp.status, "\n")
6085 throw("releasep: invalid p state")
6086 }
6087 gp.m.p = 0
6088 pp.m = 0
6089 pp.status = _Pidle
6090 return pp
6091 }
6092
6093 func incidlelocked(v int32) {
6094 lock(&sched.lock)
6095 sched.nmidlelocked += v
6096 if v > 0 {
6097 checkdead()
6098 }
6099 unlock(&sched.lock)
6100 }
6101
6102 // Check for deadlock situation.
6103 // The check is based on number of running M's, if 0 -> deadlock.
6104 // sched.lock must be held.
6105 func checkdead() {
6106 assertLockHeld(&sched.lock)
6107
6108 // For -buildmode=c-shared or -buildmode=c-archive it's OK if
6109 // there are no running goroutines. The calling program is
6110 // assumed to be running.
6111 // One exception is Wasm, which is single-threaded. If we are
6112 // in Go and all goroutines are blocked, it deadlocks.
6113 if (islibrary || isarchive) && GOARCH != "wasm" {
6114 return
6115 }
6116
6117 // If we are dying because of a signal caught on an already idle thread,
6118 // freezetheworld will cause all running threads to block.
6119 // And runtime will essentially enter into deadlock state,
6120 // except that there is a thread that will call exit soon.
6121 if panicking.Load() > 0 {
6122 return
6123 }
6124
6125 // If we are not running under cgo, but we have an extra M then account
6126 // for it. (It is possible to have an extra M on Windows without cgo to
6127 // accommodate callbacks created by syscall.NewCallback. See issue #6751
6128 // for details.)
6129 var run0 int32
6130 if !iscgo && cgoHasExtraM && extraMLength.Load() > 0 {
6131 run0 = 1
6132 }
6133
6134 run := mcount() - sched.nmidle - sched.nmidlelocked - sched.nmsys
6135 if run > run0 {
6136 return
6137 }
6138 if run < 0 {
6139 print("runtime: checkdead: nmidle=", sched.nmidle, " nmidlelocked=", sched.nmidlelocked, " mcount=", mcount(), " nmsys=", sched.nmsys, "\n")
6140 unlock(&sched.lock)
6141 throw("checkdead: inconsistent counts")
6142 }
6143
6144 grunning := 0
6145 forEachG(func(gp *g) {
6146 if isSystemGoroutine(gp, false) {
6147 return
6148 }
6149 s := readgstatus(gp)
6150 switch s &^ _Gscan {
6151 case _Gwaiting,
6152 _Gpreempted:
6153 grunning++
6154 case _Grunnable,
6155 _Grunning,
6156 _Gsyscall:
6157 print("runtime: checkdead: find g ", gp.goid, " in status ", s, "\n")
6158 unlock(&sched.lock)
6159 throw("checkdead: runnable g")
6160 }
6161 })
6162 if grunning == 0 { // possible if main goroutine calls runtime·Goexit()
6163 unlock(&sched.lock) // unlock so that GODEBUG=scheddetail=1 doesn't hang
6164 fatal("no goroutines (main called runtime.Goexit) - deadlock!")
6165 }
6166
6167 // Maybe jump time forward for playground.
6168 if faketime != 0 {
6169 if when := timeSleepUntil(); when < maxWhen {
6170 faketime = when
6171
6172 // Start an M to steal the timer.
6173 pp, _ := pidleget(faketime)
6174 if pp == nil {
6175 // There should always be a free P since
6176 // nothing is running.
6177 unlock(&sched.lock)
6178 throw("checkdead: no p for timer")
6179 }
6180 mp := mget()
6181 if mp == nil {
6182 // There should always be a free M since
6183 // nothing is running.
6184 unlock(&sched.lock)
6185 throw("checkdead: no m for timer")
6186 }
6187 // M must be spinning to steal. We set this to be
6188 // explicit, but since this is the only M it would
6189 // become spinning on its own anyways.
6190 sched.nmspinning.Add(1)
6191 mp.spinning = true
6192 mp.nextp.set(pp)
6193 notewakeup(&mp.park)
6194 return
6195 }
6196 }
6197
6198 // There are no goroutines running, so we can look at the P's.
6199 for _, pp := range allp {
6200 if len(pp.timers.heap) > 0 {
6201 return
6202 }
6203 }
6204
6205 unlock(&sched.lock) // unlock so that GODEBUG=scheddetail=1 doesn't hang
6206 fatal("all goroutines are asleep - deadlock!")
6207 }
6208
6209 // forcegcperiod is the maximum time in nanoseconds between garbage
6210 // collections. If we go this long without a garbage collection, one
6211 // is forced to run.
6212 //
6213 // This is a variable for testing purposes. It normally doesn't change.
6214 var forcegcperiod int64 = 2 * 60 * 1e9
6215
6216 // needSysmonWorkaround is true if the workaround for
6217 // golang.org/issue/42515 is needed on NetBSD.
6218 var needSysmonWorkaround bool = false
6219
6220 // haveSysmon indicates whether there is sysmon thread support.
6221 //
6222 // No threads on wasm yet, so no sysmon.
6223 const haveSysmon = GOARCH != "wasm"
6224
6225 // Always runs without a P, so write barriers are not allowed.
6226 //
6227 //go:nowritebarrierrec
6228 func sysmon() {
6229 lock(&sched.lock)
6230 sched.nmsys++
6231 checkdead()
6232 unlock(&sched.lock)
6233
6234 lastgomaxprocs := int64(0)
6235 lasttrace := int64(0)
6236 idle := 0 // how many cycles in succession we had not wokeup somebody
6237 delay := uint32(0)
6238
6239 for {
6240 if idle == 0 { // start with 20us sleep...
6241 delay = 20
6242 } else if idle > 50 { // start doubling the sleep after 1ms...
6243 delay *= 2
6244 }
6245 if delay > 10*1000 { // up to 10ms
6246 delay = 10 * 1000
6247 }
6248 usleep(delay)
6249
6250 // sysmon should not enter deep sleep if schedtrace is enabled so that
6251 // it can print that information at the right time.
6252 //
6253 // It should also not enter deep sleep if there are any active P's so
6254 // that it can retake P's from syscalls, preempt long running G's, and
6255 // poll the network if all P's are busy for long stretches.
6256 //
6257 // It should wakeup from deep sleep if any P's become active either due
6258 // to exiting a syscall or waking up due to a timer expiring so that it
6259 // can resume performing those duties. If it wakes from a syscall it
6260 // resets idle and delay as a bet that since it had retaken a P from a
6261 // syscall before, it may need to do it again shortly after the
6262 // application starts work again. It does not reset idle when waking
6263 // from a timer to avoid adding system load to applications that spend
6264 // most of their time sleeping.
6265 now := nanotime()
6266 if debug.schedtrace <= 0 && (sched.gcwaiting.Load() || sched.npidle.Load() == gomaxprocs) {
6267 lock(&sched.lock)
6268 if sched.gcwaiting.Load() || sched.npidle.Load() == gomaxprocs {
6269 syscallWake := false
6270 next := timeSleepUntil()
6271 if next > now {
6272 sched.sysmonwait.Store(true)
6273 unlock(&sched.lock)
6274 // Make wake-up period small enough
6275 // for the sampling to be correct.
6276 sleep := forcegcperiod / 2
6277 if next-now < sleep {
6278 sleep = next - now
6279 }
6280 shouldRelax := sleep >= osRelaxMinNS
6281 if shouldRelax {
6282 osRelax(true)
6283 }
6284 syscallWake = notetsleep(&sched.sysmonnote, sleep)
6285 if shouldRelax {
6286 osRelax(false)
6287 }
6288 lock(&sched.lock)
6289 sched.sysmonwait.Store(false)
6290 noteclear(&sched.sysmonnote)
6291 }
6292 if syscallWake {
6293 idle = 0
6294 delay = 20
6295 }
6296 }
6297 unlock(&sched.lock)
6298 }
6299
6300 lock(&sched.sysmonlock)
6301 // Update now in case we blocked on sysmonnote or spent a long time
6302 // blocked on schedlock or sysmonlock above.
6303 now = nanotime()
6304
6305 // trigger libc interceptors if needed
6306 if *cgo_yield != nil {
6307 asmcgocall(*cgo_yield, nil)
6308 }
6309 // poll network if not polled for more than 10ms
6310 lastpoll := sched.lastpoll.Load()
6311 if netpollinited() && lastpoll != 0 && lastpoll+10*1000*1000 < now {
6312 sched.lastpoll.CompareAndSwap(lastpoll, now)
6313 list, delta := netpoll(0) // non-blocking - returns list of goroutines
6314 if !list.empty() {
6315 // Need to decrement number of idle locked M's
6316 // (pretending that one more is running) before injectglist.
6317 // Otherwise it can lead to the following situation:
6318 // injectglist grabs all P's but before it starts M's to run the P's,
6319 // another M returns from syscall, finishes running its G,
6320 // observes that there is no work to do and no other running M's
6321 // and reports deadlock.
6322 incidlelocked(-1)
6323 injectglist(&list)
6324 incidlelocked(1)
6325 netpollAdjustWaiters(delta)
6326 }
6327 }
6328 if GOOS == "netbsd" && needSysmonWorkaround {
6329 // netpoll is responsible for waiting for timer
6330 // expiration, so we typically don't have to worry
6331 // about starting an M to service timers. (Note that
6332 // sleep for timeSleepUntil above simply ensures sysmon
6333 // starts running again when that timer expiration may
6334 // cause Go code to run again).
6335 //
6336 // However, netbsd has a kernel bug that sometimes
6337 // misses netpollBreak wake-ups, which can lead to
6338 // unbounded delays servicing timers. If we detect this
6339 // overrun, then startm to get something to handle the
6340 // timer.
6341 //
6342 // See issue 42515 and
6343 // https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=50094.
6344 if next := timeSleepUntil(); next < now {
6345 startm(nil, false, false)
6346 }
6347 }
6348 // Check if we need to update GOMAXPROCS at most once per second.
6349 if debug.updatemaxprocs != 0 && lastgomaxprocs+1e9 <= now {
6350 sysmonUpdateGOMAXPROCS()
6351 lastgomaxprocs = now
6352 }
6353 if scavenger.sysmonWake.Load() != 0 {
6354 // Kick the scavenger awake if someone requested it.
6355 scavenger.wake()
6356 }
6357 // retake P's blocked in syscalls
6358 // and preempt long running G's
6359 if retake(now) != 0 {
6360 idle = 0
6361 } else {
6362 idle++
6363 }
6364 // check if we need to force a GC
6365 if t := (gcTrigger{kind: gcTriggerTime, now: now}); t.test() && forcegc.idle.Load() {
6366 lock(&forcegc.lock)
6367 forcegc.idle.Store(false)
6368 var list gList
6369 list.push(forcegc.g)
6370 injectglist(&list)
6371 unlock(&forcegc.lock)
6372 }
6373 if debug.schedtrace > 0 && lasttrace+int64(debug.schedtrace)*1000000 <= now {
6374 lasttrace = now
6375 schedtrace(debug.scheddetail > 0)
6376 }
6377 unlock(&sched.sysmonlock)
6378 }
6379 }
6380
6381 type sysmontick struct {
6382 schedtick uint32
6383 syscalltick uint32
6384 schedwhen int64
6385 syscallwhen int64
6386 }
6387
6388 // forcePreemptNS is the time slice given to a G before it is
6389 // preempted.
6390 const forcePreemptNS = 10 * 1000 * 1000 // 10ms
6391
6392 func retake(now int64) uint32 {
6393 n := 0
6394 // Prevent allp slice changes. This lock will be completely
6395 // uncontended unless we're already stopping the world.
6396 lock(&allpLock)
6397 // We can't use a range loop over allp because we may
6398 // temporarily drop the allpLock. Hence, we need to re-fetch
6399 // allp each time around the loop.
6400 for i := 0; i < len(allp); i++ {
6401 pp := allp[i]
6402 if pp == nil {
6403 // This can happen if procresize has grown
6404 // allp but not yet created new Ps.
6405 continue
6406 }
6407 pd := &pp.sysmontick
6408 s := pp.status
6409 sysretake := false
6410 if s == _Prunning || s == _Psyscall {
6411 // Preempt G if it's running on the same schedtick for
6412 // too long. This could be from a single long-running
6413 // goroutine or a sequence of goroutines run via
6414 // runnext, which share a single schedtick time slice.
6415 t := int64(pp.schedtick)
6416 if int64(pd.schedtick) != t {
6417 pd.schedtick = uint32(t)
6418 pd.schedwhen = now
6419 } else if pd.schedwhen+forcePreemptNS <= now {
6420 preemptone(pp)
6421 // In case of syscall, preemptone() doesn't
6422 // work, because there is no M wired to P.
6423 sysretake = true
6424 }
6425 }
6426 if s == _Psyscall {
6427 // Retake P from syscall if it's there for more than 1 sysmon tick (at least 20us).
6428 t := int64(pp.syscalltick)
6429 if !sysretake && int64(pd.syscalltick) != t {
6430 pd.syscalltick = uint32(t)
6431 pd.syscallwhen = now
6432 continue
6433 }
6434 // On the one hand we don't want to retake Ps if there is no other work to do,
6435 // but on the other hand we want to retake them eventually
6436 // because they can prevent the sysmon thread from deep sleep.
6437 if runqempty(pp) && sched.nmspinning.Load()+sched.npidle.Load() > 0 && pd.syscallwhen+10*1000*1000 > now {
6438 continue
6439 }
6440 // Drop allpLock so we can take sched.lock.
6441 unlock(&allpLock)
6442 // Need to decrement number of idle locked M's
6443 // (pretending that one more is running) before the CAS.
6444 // Otherwise the M from which we retake can exit the syscall,
6445 // increment nmidle and report deadlock.
6446 incidlelocked(-1)
6447 trace := traceAcquire()
6448 if atomic.Cas(&pp.status, s, _Pidle) {
6449 if trace.ok() {
6450 trace.ProcSteal(pp, false)
6451 traceRelease(trace)
6452 }
6453 n++
6454 pp.syscalltick++
6455 handoffp(pp)
6456 } else if trace.ok() {
6457 traceRelease(trace)
6458 }
6459 incidlelocked(1)
6460 lock(&allpLock)
6461 }
6462 }
6463 unlock(&allpLock)
6464 return uint32(n)
6465 }
6466
6467 // Tell all goroutines that they have been preempted and they should stop.
6468 // This function is purely best-effort. It can fail to inform a goroutine if a
6469 // processor just started running it.
6470 // No locks need to be held.
6471 // Returns true if preemption request was issued to at least one goroutine.
6472 func preemptall() bool {
6473 res := false
6474 for _, pp := range allp {
6475 if pp.status != _Prunning {
6476 continue
6477 }
6478 if preemptone(pp) {
6479 res = true
6480 }
6481 }
6482 return res
6483 }
6484
6485 // Tell the goroutine running on processor P to stop.
6486 // This function is purely best-effort. It can incorrectly fail to inform the
6487 // goroutine. It can inform the wrong goroutine. Even if it informs the
6488 // correct goroutine, that goroutine might ignore the request if it is
6489 // simultaneously executing newstack.
6490 // No lock needs to be held.
6491 // Returns true if preemption request was issued.
6492 // The actual preemption will happen at some point in the future
6493 // and will be indicated by the gp->status no longer being
6494 // Grunning
6495 func preemptone(pp *p) bool {
6496 mp := pp.m.ptr()
6497 if mp == nil || mp == getg().m {
6498 return false
6499 }
6500 gp := mp.curg
6501 if gp == nil || gp == mp.g0 {
6502 return false
6503 }
6504
6505 gp.preempt = true
6506
6507 // Every call in a goroutine checks for stack overflow by
6508 // comparing the current stack pointer to gp->stackguard0.
6509 // Setting gp->stackguard0 to StackPreempt folds
6510 // preemption into the normal stack overflow check.
6511 gp.stackguard0 = stackPreempt
6512
6513 // Request an async preemption of this P.
6514 if preemptMSupported && debug.asyncpreemptoff == 0 {
6515 pp.preempt = true
6516 preemptM(mp)
6517 }
6518
6519 return true
6520 }
6521
6522 var starttime int64
6523
6524 func schedtrace(detailed bool) {
6525 now := nanotime()
6526 if starttime == 0 {
6527 starttime = now
6528 }
6529
6530 lock(&sched.lock)
6531 print("SCHED ", (now-starttime)/1e6, "ms: gomaxprocs=", gomaxprocs, " idleprocs=", sched.npidle.Load(), " threads=", mcount(), " spinningthreads=", sched.nmspinning.Load(), " needspinning=", sched.needspinning.Load(), " idlethreads=", sched.nmidle, " runqueue=", sched.runq.size)
6532 if detailed {
6533 print(" gcwaiting=", sched.gcwaiting.Load(), " nmidlelocked=", sched.nmidlelocked, " stopwait=", sched.stopwait, " sysmonwait=", sched.sysmonwait.Load(), "\n")
6534 }
6535 // We must be careful while reading data from P's, M's and G's.
6536 // Even if we hold schedlock, most data can be changed concurrently.
6537 // E.g. (p->m ? p->m->id : -1) can crash if p->m changes from non-nil to nil.
6538 for i, pp := range allp {
6539 h := atomic.Load(&pp.runqhead)
6540 t := atomic.Load(&pp.runqtail)
6541 if detailed {
6542 print(" P", i, ": status=", pp.status, " schedtick=", pp.schedtick, " syscalltick=", pp.syscalltick, " m=")
6543 mp := pp.m.ptr()
6544 if mp != nil {
6545 print(mp.id)
6546 } else {
6547 print("nil")
6548 }
6549 print(" runqsize=", t-h, " gfreecnt=", pp.gFree.size, " timerslen=", len(pp.timers.heap), "\n")
6550 } else {
6551 // In non-detailed mode format lengths of per-P run queues as:
6552 // [ len1 len2 len3 len4 ]
6553 print(" ")
6554 if i == 0 {
6555 print("[ ")
6556 }
6557 print(t - h)
6558 if i == len(allp)-1 {
6559 print(" ]")
6560 }
6561 }
6562 }
6563
6564 if !detailed {
6565 // Format per-P schedticks as: schedticks=[ tick1 tick2 tick3 tick4 ].
6566 print(" schedticks=[ ")
6567 for _, pp := range allp {
6568 print(pp.schedtick)
6569 print(" ")
6570 }
6571 print("]\n")
6572 }
6573
6574 if !detailed {
6575 unlock(&sched.lock)
6576 return
6577 }
6578
6579 for mp := allm; mp != nil; mp = mp.alllink {
6580 pp := mp.p.ptr()
6581 print(" M", mp.id, ": p=")
6582 if pp != nil {
6583 print(pp.id)
6584 } else {
6585 print("nil")
6586 }
6587 print(" curg=")
6588 if mp.curg != nil {
6589 print(mp.curg.goid)
6590 } else {
6591 print("nil")
6592 }
6593 print(" mallocing=", mp.mallocing, " throwing=", mp.throwing, " preemptoff=", mp.preemptoff, " locks=", mp.locks, " dying=", mp.dying, " spinning=", mp.spinning, " blocked=", mp.blocked, " lockedg=")
6594 if lockedg := mp.lockedg.ptr(); lockedg != nil {
6595 print(lockedg.goid)
6596 } else {
6597 print("nil")
6598 }
6599 print("\n")
6600 }
6601
6602 forEachG(func(gp *g) {
6603 print(" G", gp.goid, ": status=", readgstatus(gp), "(", gp.waitreason.String(), ") m=")
6604 if gp.m != nil {
6605 print(gp.m.id)
6606 } else {
6607 print("nil")
6608 }
6609 print(" lockedm=")
6610 if lockedm := gp.lockedm.ptr(); lockedm != nil {
6611 print(lockedm.id)
6612 } else {
6613 print("nil")
6614 }
6615 print("\n")
6616 })
6617 unlock(&sched.lock)
6618 }
6619
6620 type updateMaxProcsGState struct {
6621 lock mutex
6622 g *g
6623 idle atomic.Bool
6624
6625 // Readable when idle == false, writable when idle == true.
6626 procs int32 // new GOMAXPROCS value
6627 }
6628
6629 var (
6630 // GOMAXPROCS update godebug metric. Incremented if automatic
6631 // GOMAXPROCS updates actually change the value of GOMAXPROCS.
6632 updatemaxprocs = &godebugInc{name: "updatemaxprocs"}
6633
6634 // Synchronization and state between updateMaxProcsGoroutine and
6635 // sysmon.
6636 updateMaxProcsG updateMaxProcsGState
6637
6638 // Synchronization between GOMAXPROCS and sysmon.
6639 //
6640 // Setting GOMAXPROCS via a call to GOMAXPROCS disables automatic
6641 // GOMAXPROCS updates.
6642 //
6643 // We want to make two guarantees to callers of GOMAXPROCS. After
6644 // GOMAXPROCS returns:
6645 //
6646 // 1. The runtime will not make any automatic changes to GOMAXPROCS.
6647 //
6648 // 2. The runtime will not perform any of the system calls used to
6649 // determine the appropriate value of GOMAXPROCS (i.e., it won't
6650 // call defaultGOMAXPROCS).
6651 //
6652 // (1) is the baseline guarantee that everyone needs. The GOMAXPROCS
6653 // API isn't useful to anyone if automatic updates may occur after it
6654 // returns. This is easily achieved by double-checking the state under
6655 // STW before committing an automatic GOMAXPROCS update.
6656 //
6657 // (2) doesn't matter to most users, as it is isn't observable as long
6658 // as (1) holds. However, it can be important to users sandboxing Go.
6659 // They want disable these system calls and need some way to know when
6660 // they are guaranteed the calls will stop.
6661 //
6662 // This would be simple to achieve if we simply called
6663 // defaultGOMAXPROCS under STW in updateMaxProcsGoroutine below.
6664 // However, we would like to avoid scheduling this goroutine every
6665 // second when it will almost never do anything. Instead, sysmon calls
6666 // defaultGOMAXPROCS to decide whether to schedule
6667 // updateMaxProcsGoroutine. Thus we need to synchronize between sysmon
6668 // and GOMAXPROCS calls.
6669 //
6670 // GOMAXPROCS can't hold a runtime mutex across STW. It could hold a
6671 // semaphore, but sysmon cannot take semaphores. Instead, we have a
6672 // more complex scheme:
6673 //
6674 // * sysmon holds computeMaxProcsLock while calling defaultGOMAXPROCS.
6675 // * sysmon skips the current update if sched.customGOMAXPROCS is
6676 // set.
6677 // * GOMAXPROCS sets sched.customGOMAXPROCS once it is committed to
6678 // changing GOMAXPROCS.
6679 // * GOMAXPROCS takes computeMaxProcsLock to wait for outstanding
6680 // defaultGOMAXPROCS calls to complete.
6681 //
6682 // N.B. computeMaxProcsLock could simply be sched.lock, but we want to
6683 // avoid holding that lock during the potentially slow
6684 // defaultGOMAXPROCS.
6685 computeMaxProcsLock mutex
6686 )
6687
6688 // Start GOMAXPROCS update helper goroutine.
6689 //
6690 // This is based on forcegchelper.
6691 func defaultGOMAXPROCSUpdateEnable() {
6692 if debug.updatemaxprocs == 0 {
6693 // Unconditionally increment the metric when updates are disabled.
6694 //
6695 // It would be more descriptive if we did a dry run of the
6696 // complete update, determining the appropriate value of
6697 // GOMAXPROCS and the bailing out and just incrementing the
6698 // metric if a change would occur.
6699 //
6700 // Not only is that a lot of ongoing work for a disabled
6701 // feature, but some users need to be able to completely
6702 // disable the update system calls (such as sandboxes).
6703 // Currently, updatemaxprocs=0 serves that purpose.
6704 updatemaxprocs.IncNonDefault()
6705 return
6706 }
6707
6708 go updateMaxProcsGoroutine()
6709 }
6710
6711 func updateMaxProcsGoroutine() {
6712 updateMaxProcsG.g = getg()
6713 lockInit(&updateMaxProcsG.lock, lockRankUpdateMaxProcsG)
6714 for {
6715 lock(&updateMaxProcsG.lock)
6716 if updateMaxProcsG.idle.Load() {
6717 throw("updateMaxProcsGoroutine: phase error")
6718 }
6719 updateMaxProcsG.idle.Store(true)
6720 goparkunlock(&updateMaxProcsG.lock, waitReasonUpdateGOMAXPROCSIdle, traceBlockSystemGoroutine, 1)
6721 // This goroutine is explicitly resumed by sysmon.
6722
6723 stw := stopTheWorldGC(stwGOMAXPROCS)
6724
6725 // Still OK to update?
6726 lock(&sched.lock)
6727 custom := sched.customGOMAXPROCS
6728 unlock(&sched.lock)
6729 if custom {
6730 startTheWorldGC(stw)
6731 return
6732 }
6733
6734 // newprocs will be processed by startTheWorld
6735 //
6736 // TODO(prattmic): this could use a nicer API. Perhaps add it to the
6737 // stw parameter?
6738 newprocs = updateMaxProcsG.procs
6739 lock(&sched.lock)
6740 sched.customGOMAXPROCS = false
6741 unlock(&sched.lock)
6742
6743 startTheWorldGC(stw)
6744 }
6745 }
6746
6747 func sysmonUpdateGOMAXPROCS() {
6748 // Synchronize with GOMAXPROCS. See comment on computeMaxProcsLock.
6749 lock(&computeMaxProcsLock)
6750
6751 // No update if GOMAXPROCS was set manually.
6752 lock(&sched.lock)
6753 custom := sched.customGOMAXPROCS
6754 curr := gomaxprocs
6755 unlock(&sched.lock)
6756 if custom {
6757 unlock(&computeMaxProcsLock)
6758 return
6759 }
6760
6761 // Don't hold sched.lock while we read the filesystem.
6762 procs := defaultGOMAXPROCS(0)
6763 unlock(&computeMaxProcsLock)
6764 if procs == curr {
6765 // Nothing to do.
6766 return
6767 }
6768
6769 // Sysmon can't directly stop the world. Run the helper to do so on our
6770 // behalf. If updateGOMAXPROCS.idle is false, then a previous update is
6771 // still pending.
6772 if updateMaxProcsG.idle.Load() {
6773 lock(&updateMaxProcsG.lock)
6774 updateMaxProcsG.procs = procs
6775 updateMaxProcsG.idle.Store(false)
6776 var list gList
6777 list.push(updateMaxProcsG.g)
6778 injectglist(&list)
6779 unlock(&updateMaxProcsG.lock)
6780 }
6781 }
6782
6783 // schedEnableUser enables or disables the scheduling of user
6784 // goroutines.
6785 //
6786 // This does not stop already running user goroutines, so the caller
6787 // should first stop the world when disabling user goroutines.
6788 func schedEnableUser(enable bool) {
6789 lock(&sched.lock)
6790 if sched.disable.user == !enable {
6791 unlock(&sched.lock)
6792 return
6793 }
6794 sched.disable.user = !enable
6795 if enable {
6796 n := sched.disable.runnable.size
6797 globrunqputbatch(&sched.disable.runnable)
6798 unlock(&sched.lock)
6799 for ; n != 0 && sched.npidle.Load() != 0; n-- {
6800 startm(nil, false, false)
6801 }
6802 } else {
6803 unlock(&sched.lock)
6804 }
6805 }
6806
6807 // schedEnabled reports whether gp should be scheduled. It returns
6808 // false is scheduling of gp is disabled.
6809 //
6810 // sched.lock must be held.
6811 func schedEnabled(gp *g) bool {
6812 assertLockHeld(&sched.lock)
6813
6814 if sched.disable.user {
6815 return isSystemGoroutine(gp, true)
6816 }
6817 return true
6818 }
6819
6820 // Put mp on midle list.
6821 // sched.lock must be held.
6822 // May run during STW, so write barriers are not allowed.
6823 //
6824 //go:nowritebarrierrec
6825 func mput(mp *m) {
6826 assertLockHeld(&sched.lock)
6827
6828 mp.schedlink = sched.midle
6829 sched.midle.set(mp)
6830 sched.nmidle++
6831 checkdead()
6832 }
6833
6834 // Try to get an m from midle list.
6835 // sched.lock must be held.
6836 // May run during STW, so write barriers are not allowed.
6837 //
6838 //go:nowritebarrierrec
6839 func mget() *m {
6840 assertLockHeld(&sched.lock)
6841
6842 mp := sched.midle.ptr()
6843 if mp != nil {
6844 sched.midle = mp.schedlink
6845 sched.nmidle--
6846 }
6847 return mp
6848 }
6849
6850 // Put gp on the global runnable queue.
6851 // sched.lock must be held.
6852 // May run during STW, so write barriers are not allowed.
6853 //
6854 //go:nowritebarrierrec
6855 func globrunqput(gp *g) {
6856 assertLockHeld(&sched.lock)
6857
6858 sched.runq.pushBack(gp)
6859 }
6860
6861 // Put gp at the head of the global runnable queue.
6862 // sched.lock must be held.
6863 // May run during STW, so write barriers are not allowed.
6864 //
6865 //go:nowritebarrierrec
6866 func globrunqputhead(gp *g) {
6867 assertLockHeld(&sched.lock)
6868
6869 sched.runq.push(gp)
6870 }
6871
6872 // Put a batch of runnable goroutines on the global runnable queue.
6873 // This clears *batch.
6874 // sched.lock must be held.
6875 // May run during STW, so write barriers are not allowed.
6876 //
6877 //go:nowritebarrierrec
6878 func globrunqputbatch(batch *gQueue) {
6879 assertLockHeld(&sched.lock)
6880
6881 sched.runq.pushBackAll(*batch)
6882 *batch = gQueue{}
6883 }
6884
6885 // Try get a single G from the global runnable queue.
6886 // sched.lock must be held.
6887 func globrunqget() *g {
6888 assertLockHeld(&sched.lock)
6889
6890 if sched.runq.size == 0 {
6891 return nil
6892 }
6893
6894 return sched.runq.pop()
6895 }
6896
6897 // Try get a batch of G's from the global runnable queue.
6898 // sched.lock must be held.
6899 func globrunqgetbatch(n int32) (gp *g, q gQueue) {
6900 assertLockHeld(&sched.lock)
6901
6902 if sched.runq.size == 0 {
6903 return
6904 }
6905
6906 n = min(n, sched.runq.size, sched.runq.size/gomaxprocs+1)
6907
6908 gp = sched.runq.pop()
6909 n--
6910
6911 for ; n > 0; n-- {
6912 gp1 := sched.runq.pop()
6913 q.pushBack(gp1)
6914 }
6915 return
6916 }
6917
6918 // pMask is an atomic bitstring with one bit per P.
6919 type pMask []uint32
6920
6921 // read returns true if P id's bit is set.
6922 func (p pMask) read(id uint32) bool {
6923 word := id / 32
6924 mask := uint32(1) << (id % 32)
6925 return (atomic.Load(&p[word]) & mask) != 0
6926 }
6927
6928 // set sets P id's bit.
6929 func (p pMask) set(id int32) {
6930 word := id / 32
6931 mask := uint32(1) << (id % 32)
6932 atomic.Or(&p[word], mask)
6933 }
6934
6935 // clear clears P id's bit.
6936 func (p pMask) clear(id int32) {
6937 word := id / 32
6938 mask := uint32(1) << (id % 32)
6939 atomic.And(&p[word], ^mask)
6940 }
6941
6942 // pidleput puts p on the _Pidle list. now must be a relatively recent call
6943 // to nanotime or zero. Returns now or the current time if now was zero.
6944 //
6945 // This releases ownership of p. Once sched.lock is released it is no longer
6946 // safe to use p.
6947 //
6948 // sched.lock must be held.
6949 //
6950 // May run during STW, so write barriers are not allowed.
6951 //
6952 //go:nowritebarrierrec
6953 func pidleput(pp *p, now int64) int64 {
6954 assertLockHeld(&sched.lock)
6955
6956 if !runqempty(pp) {
6957 throw("pidleput: P has non-empty run queue")
6958 }
6959 if now == 0 {
6960 now = nanotime()
6961 }
6962 if pp.timers.len.Load() == 0 {
6963 timerpMask.clear(pp.id)
6964 }
6965 idlepMask.set(pp.id)
6966 pp.link = sched.pidle
6967 sched.pidle.set(pp)
6968 sched.npidle.Add(1)
6969 if !pp.limiterEvent.start(limiterEventIdle, now) {
6970 throw("must be able to track idle limiter event")
6971 }
6972 return now
6973 }
6974
6975 // pidleget tries to get a p from the _Pidle list, acquiring ownership.
6976 //
6977 // sched.lock must be held.
6978 //
6979 // May run during STW, so write barriers are not allowed.
6980 //
6981 //go:nowritebarrierrec
6982 func pidleget(now int64) (*p, int64) {
6983 assertLockHeld(&sched.lock)
6984
6985 pp := sched.pidle.ptr()
6986 if pp != nil {
6987 // Timer may get added at any time now.
6988 if now == 0 {
6989 now = nanotime()
6990 }
6991 timerpMask.set(pp.id)
6992 idlepMask.clear(pp.id)
6993 sched.pidle = pp.link
6994 sched.npidle.Add(-1)
6995 pp.limiterEvent.stop(limiterEventIdle, now)
6996 }
6997 return pp, now
6998 }
6999
7000 // pidlegetSpinning tries to get a p from the _Pidle list, acquiring ownership.
7001 // This is called by spinning Ms (or callers than need a spinning M) that have
7002 // found work. If no P is available, this must synchronized with non-spinning
7003 // Ms that may be preparing to drop their P without discovering this work.
7004 //
7005 // sched.lock must be held.
7006 //
7007 // May run during STW, so write barriers are not allowed.
7008 //
7009 //go:nowritebarrierrec
7010 func pidlegetSpinning(now int64) (*p, int64) {
7011 assertLockHeld(&sched.lock)
7012
7013 pp, now := pidleget(now)
7014 if pp == nil {
7015 // See "Delicate dance" comment in findrunnable. We found work
7016 // that we cannot take, we must synchronize with non-spinning
7017 // Ms that may be preparing to drop their P.
7018 sched.needspinning.Store(1)
7019 return nil, now
7020 }
7021
7022 return pp, now
7023 }
7024
7025 // runqempty reports whether pp has no Gs on its local run queue.
7026 // It never returns true spuriously.
7027 func runqempty(pp *p) bool {
7028 // Defend against a race where 1) pp has G1 in runqnext but runqhead == runqtail,
7029 // 2) runqput on pp kicks G1 to the runq, 3) runqget on pp empties runqnext.
7030 // Simply observing that runqhead == runqtail and then observing that runqnext == nil
7031 // does not mean the queue is empty.
7032 for {
7033 head := atomic.Load(&pp.runqhead)
7034 tail := atomic.Load(&pp.runqtail)
7035 runnext := atomic.Loaduintptr((*uintptr)(unsafe.Pointer(&pp.runnext)))
7036 if tail == atomic.Load(&pp.runqtail) {
7037 return head == tail && runnext == 0
7038 }
7039 }
7040 }
7041
7042 // To shake out latent assumptions about scheduling order,
7043 // we introduce some randomness into scheduling decisions
7044 // when running with the race detector.
7045 // The need for this was made obvious by changing the
7046 // (deterministic) scheduling order in Go 1.5 and breaking
7047 // many poorly-written tests.
7048 // With the randomness here, as long as the tests pass
7049 // consistently with -race, they shouldn't have latent scheduling
7050 // assumptions.
7051 const randomizeScheduler = raceenabled
7052
7053 // runqput tries to put g on the local runnable queue.
7054 // If next is false, runqput adds g to the tail of the runnable queue.
7055 // If next is true, runqput puts g in the pp.runnext slot.
7056 // If the run queue is full, runnext puts g on the global queue.
7057 // Executed only by the owner P.
7058 func runqput(pp *p, gp *g, next bool) {
7059 if !haveSysmon && next {
7060 // A runnext goroutine shares the same time slice as the
7061 // current goroutine (inheritTime from runqget). To prevent a
7062 // ping-pong pair of goroutines from starving all others, we
7063 // depend on sysmon to preempt "long-running goroutines". That
7064 // is, any set of goroutines sharing the same time slice.
7065 //
7066 // If there is no sysmon, we must avoid runnext entirely or
7067 // risk starvation.
7068 next = false
7069 }
7070 if randomizeScheduler && next && randn(2) == 0 {
7071 next = false
7072 }
7073
7074 if next {
7075 retryNext:
7076 oldnext := pp.runnext
7077 if !pp.runnext.cas(oldnext, guintptr(unsafe.Pointer(gp))) {
7078 goto retryNext
7079 }
7080 if oldnext == 0 {
7081 return
7082 }
7083 // Kick the old runnext out to the regular run queue.
7084 gp = oldnext.ptr()
7085 }
7086
7087 retry:
7088 h := atomic.LoadAcq(&pp.runqhead) // load-acquire, synchronize with consumers
7089 t := pp.runqtail
7090 if t-h < uint32(len(pp.runq)) {
7091 pp.runq[t%uint32(len(pp.runq))].set(gp)
7092 atomic.StoreRel(&pp.runqtail, t+1) // store-release, makes the item available for consumption
7093 return
7094 }
7095 if runqputslow(pp, gp, h, t) {
7096 return
7097 }
7098 // the queue is not full, now the put above must succeed
7099 goto retry
7100 }
7101
7102 // Put g and a batch of work from local runnable queue on global queue.
7103 // Executed only by the owner P.
7104 func runqputslow(pp *p, gp *g, h, t uint32) bool {
7105 var batch [len(pp.runq)/2 + 1]*g
7106
7107 // First, grab a batch from local queue.
7108 n := t - h
7109 n = n / 2
7110 if n != uint32(len(pp.runq)/2) {
7111 throw("runqputslow: queue is not full")
7112 }
7113 for i := uint32(0); i < n; i++ {
7114 batch[i] = pp.runq[(h+i)%uint32(len(pp.runq))].ptr()
7115 }
7116 if !atomic.CasRel(&pp.runqhead, h, h+n) { // cas-release, commits consume
7117 return false
7118 }
7119 batch[n] = gp
7120
7121 if randomizeScheduler {
7122 for i := uint32(1); i <= n; i++ {
7123 j := cheaprandn(i + 1)
7124 batch[i], batch[j] = batch[j], batch[i]
7125 }
7126 }
7127
7128 // Link the goroutines.
7129 for i := uint32(0); i < n; i++ {
7130 batch[i].schedlink.set(batch[i+1])
7131 }
7132
7133 q := gQueue{batch[0].guintptr(), batch[n].guintptr(), int32(n + 1)}
7134
7135 // Now put the batch on global queue.
7136 lock(&sched.lock)
7137 globrunqputbatch(&q)
7138 unlock(&sched.lock)
7139 return true
7140 }
7141
7142 // runqputbatch tries to put all the G's on q on the local runnable queue.
7143 // If the local runq is full the input queue still contains unqueued Gs.
7144 // Executed only by the owner P.
7145 func runqputbatch(pp *p, q *gQueue) {
7146 if q.empty() {
7147 return
7148 }
7149 h := atomic.LoadAcq(&pp.runqhead)
7150 t := pp.runqtail
7151 n := uint32(0)
7152 for !q.empty() && t-h < uint32(len(pp.runq)) {
7153 gp := q.pop()
7154 pp.runq[t%uint32(len(pp.runq))].set(gp)
7155 t++
7156 n++
7157 }
7158
7159 if randomizeScheduler {
7160 off := func(o uint32) uint32 {
7161 return (pp.runqtail + o) % uint32(len(pp.runq))
7162 }
7163 for i := uint32(1); i < n; i++ {
7164 j := cheaprandn(i + 1)
7165 pp.runq[off(i)], pp.runq[off(j)] = pp.runq[off(j)], pp.runq[off(i)]
7166 }
7167 }
7168
7169 atomic.StoreRel(&pp.runqtail, t)
7170
7171 return
7172 }
7173
7174 // Get g from local runnable queue.
7175 // If inheritTime is true, gp should inherit the remaining time in the
7176 // current time slice. Otherwise, it should start a new time slice.
7177 // Executed only by the owner P.
7178 func runqget(pp *p) (gp *g, inheritTime bool) {
7179 // If there's a runnext, it's the next G to run.
7180 next := pp.runnext
7181 // If the runnext is non-0 and the CAS fails, it could only have been stolen by another P,
7182 // because other Ps can race to set runnext to 0, but only the current P can set it to non-0.
7183 // Hence, there's no need to retry this CAS if it fails.
7184 if next != 0 && pp.runnext.cas(next, 0) {
7185 return next.ptr(), true
7186 }
7187
7188 for {
7189 h := atomic.LoadAcq(&pp.runqhead) // load-acquire, synchronize with other consumers
7190 t := pp.runqtail
7191 if t == h {
7192 return nil, false
7193 }
7194 gp := pp.runq[h%uint32(len(pp.runq))].ptr()
7195 if atomic.CasRel(&pp.runqhead, h, h+1) { // cas-release, commits consume
7196 return gp, false
7197 }
7198 }
7199 }
7200
7201 // runqdrain drains the local runnable queue of pp and returns all goroutines in it.
7202 // Executed only by the owner P.
7203 func runqdrain(pp *p) (drainQ gQueue) {
7204 oldNext := pp.runnext
7205 if oldNext != 0 && pp.runnext.cas(oldNext, 0) {
7206 drainQ.pushBack(oldNext.ptr())
7207 }
7208
7209 retry:
7210 h := atomic.LoadAcq(&pp.runqhead) // load-acquire, synchronize with other consumers
7211 t := pp.runqtail
7212 qn := t - h
7213 if qn == 0 {
7214 return
7215 }
7216 if qn > uint32(len(pp.runq)) { // read inconsistent h and t
7217 goto retry
7218 }
7219
7220 if !atomic.CasRel(&pp.runqhead, h, h+qn) { // cas-release, commits consume
7221 goto retry
7222 }
7223
7224 // We've inverted the order in which it gets G's from the local P's runnable queue
7225 // and then advances the head pointer because we don't want to mess up the statuses of G's
7226 // while runqdrain() and runqsteal() are running in parallel.
7227 // Thus we should advance the head pointer before draining the local P into a gQueue,
7228 // so that we can update any gp.schedlink only after we take the full ownership of G,
7229 // meanwhile, other P's can't access to all G's in local P's runnable queue and steal them.
7230 // See https://groups.google.com/g/golang-dev/c/0pTKxEKhHSc/m/6Q85QjdVBQAJ for more details.
7231 for i := uint32(0); i < qn; i++ {
7232 gp := pp.runq[(h+i)%uint32(len(pp.runq))].ptr()
7233 drainQ.pushBack(gp)
7234 }
7235 return
7236 }
7237
7238 // Grabs a batch of goroutines from pp's runnable queue into batch.
7239 // Batch is a ring buffer starting at batchHead.
7240 // Returns number of grabbed goroutines.
7241 // Can be executed by any P.
7242 func runqgrab(pp *p, batch *[256]guintptr, batchHead uint32, stealRunNextG bool) uint32 {
7243 for {
7244 h := atomic.LoadAcq(&pp.runqhead) // load-acquire, synchronize with other consumers
7245 t := atomic.LoadAcq(&pp.runqtail) // load-acquire, synchronize with the producer
7246 n := t - h
7247 n = n - n/2
7248 if n == 0 {
7249 if stealRunNextG {
7250 // Try to steal from pp.runnext.
7251 if next := pp.runnext; next != 0 {
7252 if pp.status == _Prunning {
7253 // Sleep to ensure that pp isn't about to run the g
7254 // we are about to steal.
7255 // The important use case here is when the g running
7256 // on pp ready()s another g and then almost
7257 // immediately blocks. Instead of stealing runnext
7258 // in this window, back off to give pp a chance to
7259 // schedule runnext. This will avoid thrashing gs
7260 // between different Ps.
7261 // A sync chan send/recv takes ~50ns as of time of
7262 // writing, so 3us gives ~50x overshoot.
7263 if !osHasLowResTimer {
7264 usleep(3)
7265 } else {
7266 // On some platforms system timer granularity is
7267 // 1-15ms, which is way too much for this
7268 // optimization. So just yield.
7269 osyield()
7270 }
7271 }
7272 if !pp.runnext.cas(next, 0) {
7273 continue
7274 }
7275 batch[batchHead%uint32(len(batch))] = next
7276 return 1
7277 }
7278 }
7279 return 0
7280 }
7281 if n > uint32(len(pp.runq)/2) { // read inconsistent h and t
7282 continue
7283 }
7284 for i := uint32(0); i < n; i++ {
7285 g := pp.runq[(h+i)%uint32(len(pp.runq))]
7286 batch[(batchHead+i)%uint32(len(batch))] = g
7287 }
7288 if atomic.CasRel(&pp.runqhead, h, h+n) { // cas-release, commits consume
7289 return n
7290 }
7291 }
7292 }
7293
7294 // Steal half of elements from local runnable queue of p2
7295 // and put onto local runnable queue of p.
7296 // Returns one of the stolen elements (or nil if failed).
7297 func runqsteal(pp, p2 *p, stealRunNextG bool) *g {
7298 t := pp.runqtail
7299 n := runqgrab(p2, &pp.runq, t, stealRunNextG)
7300 if n == 0 {
7301 return nil
7302 }
7303 n--
7304 gp := pp.runq[(t+n)%uint32(len(pp.runq))].ptr()
7305 if n == 0 {
7306 return gp
7307 }
7308 h := atomic.LoadAcq(&pp.runqhead) // load-acquire, synchronize with consumers
7309 if t-h+n >= uint32(len(pp.runq)) {
7310 throw("runqsteal: runq overflow")
7311 }
7312 atomic.StoreRel(&pp.runqtail, t+n) // store-release, makes the item available for consumption
7313 return gp
7314 }
7315
7316 // A gQueue is a dequeue of Gs linked through g.schedlink. A G can only
7317 // be on one gQueue or gList at a time.
7318 type gQueue struct {
7319 head guintptr
7320 tail guintptr
7321 size int32
7322 }
7323
7324 // empty reports whether q is empty.
7325 func (q *gQueue) empty() bool {
7326 return q.head == 0
7327 }
7328
7329 // push adds gp to the head of q.
7330 func (q *gQueue) push(gp *g) {
7331 gp.schedlink = q.head
7332 q.head.set(gp)
7333 if q.tail == 0 {
7334 q.tail.set(gp)
7335 }
7336 q.size++
7337 }
7338
7339 // pushBack adds gp to the tail of q.
7340 func (q *gQueue) pushBack(gp *g) {
7341 gp.schedlink = 0
7342 if q.tail != 0 {
7343 q.tail.ptr().schedlink.set(gp)
7344 } else {
7345 q.head.set(gp)
7346 }
7347 q.tail.set(gp)
7348 q.size++
7349 }
7350
7351 // pushBackAll adds all Gs in q2 to the tail of q. After this q2 must
7352 // not be used.
7353 func (q *gQueue) pushBackAll(q2 gQueue) {
7354 if q2.tail == 0 {
7355 return
7356 }
7357 q2.tail.ptr().schedlink = 0
7358 if q.tail != 0 {
7359 q.tail.ptr().schedlink = q2.head
7360 } else {
7361 q.head = q2.head
7362 }
7363 q.tail = q2.tail
7364 q.size += q2.size
7365 }
7366
7367 // pop removes and returns the head of queue q. It returns nil if
7368 // q is empty.
7369 func (q *gQueue) pop() *g {
7370 gp := q.head.ptr()
7371 if gp != nil {
7372 q.head = gp.schedlink
7373 if q.head == 0 {
7374 q.tail = 0
7375 }
7376 q.size--
7377 }
7378 return gp
7379 }
7380
7381 // popList takes all Gs in q and returns them as a gList.
7382 func (q *gQueue) popList() gList {
7383 stack := gList{q.head, q.size}
7384 *q = gQueue{}
7385 return stack
7386 }
7387
7388 // A gList is a list of Gs linked through g.schedlink. A G can only be
7389 // on one gQueue or gList at a time.
7390 type gList struct {
7391 head guintptr
7392 size int32
7393 }
7394
7395 // empty reports whether l is empty.
7396 func (l *gList) empty() bool {
7397 return l.head == 0
7398 }
7399
7400 // push adds gp to the head of l.
7401 func (l *gList) push(gp *g) {
7402 gp.schedlink = l.head
7403 l.head.set(gp)
7404 l.size++
7405 }
7406
7407 // pushAll prepends all Gs in q to l. After this q must not be used.
7408 func (l *gList) pushAll(q gQueue) {
7409 if !q.empty() {
7410 q.tail.ptr().schedlink = l.head
7411 l.head = q.head
7412 l.size += q.size
7413 }
7414 }
7415
7416 // pop removes and returns the head of l. If l is empty, it returns nil.
7417 func (l *gList) pop() *g {
7418 gp := l.head.ptr()
7419 if gp != nil {
7420 l.head = gp.schedlink
7421 l.size--
7422 }
7423 return gp
7424 }
7425
7426 //go:linkname setMaxThreads runtime/debug.setMaxThreads
7427 func setMaxThreads(in int) (out int) {
7428 lock(&sched.lock)
7429 out = int(sched.maxmcount)
7430 if in > 0x7fffffff { // MaxInt32
7431 sched.maxmcount = 0x7fffffff
7432 } else {
7433 sched.maxmcount = int32(in)
7434 }
7435 checkmcount()
7436 unlock(&sched.lock)
7437 return
7438 }
7439
7440 // procPin should be an internal detail,
7441 // but widely used packages access it using linkname.
7442 // Notable members of the hall of shame include:
7443 // - github.com/bytedance/gopkg
7444 // - github.com/choleraehyq/pid
7445 // - github.com/songzhibin97/gkit
7446 //
7447 // Do not remove or change the type signature.
7448 // See go.dev/issue/67401.
7449 //
7450 //go:linkname procPin
7451 //go:nosplit
7452 func procPin() int {
7453 gp := getg()
7454 mp := gp.m
7455
7456 mp.locks++
7457 return int(mp.p.ptr().id)
7458 }
7459
7460 // procUnpin should be an internal detail,
7461 // but widely used packages access it using linkname.
7462 // Notable members of the hall of shame include:
7463 // - github.com/bytedance/gopkg
7464 // - github.com/choleraehyq/pid
7465 // - github.com/songzhibin97/gkit
7466 //
7467 // Do not remove or change the type signature.
7468 // See go.dev/issue/67401.
7469 //
7470 //go:linkname procUnpin
7471 //go:nosplit
7472 func procUnpin() {
7473 gp := getg()
7474 gp.m.locks--
7475 }
7476
7477 //go:linkname sync_runtime_procPin sync.runtime_procPin
7478 //go:nosplit
7479 func sync_runtime_procPin() int {
7480 return procPin()
7481 }
7482
7483 //go:linkname sync_runtime_procUnpin sync.runtime_procUnpin
7484 //go:nosplit
7485 func sync_runtime_procUnpin() {
7486 procUnpin()
7487 }
7488
7489 //go:linkname sync_atomic_runtime_procPin sync/atomic.runtime_procPin
7490 //go:nosplit
7491 func sync_atomic_runtime_procPin() int {
7492 return procPin()
7493 }
7494
7495 //go:linkname sync_atomic_runtime_procUnpin sync/atomic.runtime_procUnpin
7496 //go:nosplit
7497 func sync_atomic_runtime_procUnpin() {
7498 procUnpin()
7499 }
7500
7501 // Active spinning for sync.Mutex.
7502 //
7503 //go:linkname internal_sync_runtime_canSpin internal/sync.runtime_canSpin
7504 //go:nosplit
7505 func internal_sync_runtime_canSpin(i int) bool {
7506 // sync.Mutex is cooperative, so we are conservative with spinning.
7507 // Spin only few times and only if running on a multicore machine and
7508 // GOMAXPROCS>1 and there is at least one other running P and local runq is empty.
7509 // As opposed to runtime mutex we don't do passive spinning here,
7510 // because there can be work on global runq or on other Ps.
7511 if i >= active_spin || numCPUStartup <= 1 || gomaxprocs <= sched.npidle.Load()+sched.nmspinning.Load()+1 {
7512 return false
7513 }
7514 if p := getg().m.p.ptr(); !runqempty(p) {
7515 return false
7516 }
7517 return true
7518 }
7519
7520 //go:linkname internal_sync_runtime_doSpin internal/sync.runtime_doSpin
7521 //go:nosplit
7522 func internal_sync_runtime_doSpin() {
7523 procyield(active_spin_cnt)
7524 }
7525
7526 // Active spinning for sync.Mutex.
7527 //
7528 // sync_runtime_canSpin should be an internal detail,
7529 // but widely used packages access it using linkname.
7530 // Notable members of the hall of shame include:
7531 // - github.com/livekit/protocol
7532 // - github.com/sagernet/gvisor
7533 // - gvisor.dev/gvisor
7534 //
7535 // Do not remove or change the type signature.
7536 // See go.dev/issue/67401.
7537 //
7538 //go:linkname sync_runtime_canSpin sync.runtime_canSpin
7539 //go:nosplit
7540 func sync_runtime_canSpin(i int) bool {
7541 return internal_sync_runtime_canSpin(i)
7542 }
7543
7544 // sync_runtime_doSpin should be an internal detail,
7545 // but widely used packages access it using linkname.
7546 // Notable members of the hall of shame include:
7547 // - github.com/livekit/protocol
7548 // - github.com/sagernet/gvisor
7549 // - gvisor.dev/gvisor
7550 //
7551 // Do not remove or change the type signature.
7552 // See go.dev/issue/67401.
7553 //
7554 //go:linkname sync_runtime_doSpin sync.runtime_doSpin
7555 //go:nosplit
7556 func sync_runtime_doSpin() {
7557 internal_sync_runtime_doSpin()
7558 }
7559
7560 var stealOrder randomOrder
7561
7562 // randomOrder/randomEnum are helper types for randomized work stealing.
7563 // They allow to enumerate all Ps in different pseudo-random orders without repetitions.
7564 // The algorithm is based on the fact that if we have X such that X and GOMAXPROCS
7565 // are coprime, then a sequences of (i + X) % GOMAXPROCS gives the required enumeration.
7566 type randomOrder struct {
7567 count uint32
7568 coprimes []uint32
7569 }
7570
7571 type randomEnum struct {
7572 i uint32
7573 count uint32
7574 pos uint32
7575 inc uint32
7576 }
7577
7578 func (ord *randomOrder) reset(count uint32) {
7579 ord.count = count
7580 ord.coprimes = ord.coprimes[:0]
7581 for i := uint32(1); i <= count; i++ {
7582 if gcd(i, count) == 1 {
7583 ord.coprimes = append(ord.coprimes, i)
7584 }
7585 }
7586 }
7587
7588 func (ord *randomOrder) start(i uint32) randomEnum {
7589 return randomEnum{
7590 count: ord.count,
7591 pos: i % ord.count,
7592 inc: ord.coprimes[i/ord.count%uint32(len(ord.coprimes))],
7593 }
7594 }
7595
7596 func (enum *randomEnum) done() bool {
7597 return enum.i == enum.count
7598 }
7599
7600 func (enum *randomEnum) next() {
7601 enum.i++
7602 enum.pos = (enum.pos + enum.inc) % enum.count
7603 }
7604
7605 func (enum *randomEnum) position() uint32 {
7606 return enum.pos
7607 }
7608
7609 func gcd(a, b uint32) uint32 {
7610 for b != 0 {
7611 a, b = b, a%b
7612 }
7613 return a
7614 }
7615
7616 // An initTask represents the set of initializations that need to be done for a package.
7617 // Keep in sync with ../../test/noinit.go:initTask
7618 type initTask struct {
7619 state uint32 // 0 = uninitialized, 1 = in progress, 2 = done
7620 nfns uint32
7621 // followed by nfns pcs, uintptr sized, one per init function to run
7622 }
7623
7624 // inittrace stores statistics for init functions which are
7625 // updated by malloc and newproc when active is true.
7626 var inittrace tracestat
7627
7628 type tracestat struct {
7629 active bool // init tracing activation status
7630 id uint64 // init goroutine id
7631 allocs uint64 // heap allocations
7632 bytes uint64 // heap allocated bytes
7633 }
7634
7635 func doInit(ts []*initTask) {
7636 for _, t := range ts {
7637 doInit1(t)
7638 }
7639 }
7640
7641 func doInit1(t *initTask) {
7642 switch t.state {
7643 case 2: // fully initialized
7644 return
7645 case 1: // initialization in progress
7646 throw("recursive call during initialization - linker skew")
7647 default: // not initialized yet
7648 t.state = 1 // initialization in progress
7649
7650 var (
7651 start int64
7652 before tracestat
7653 )
7654
7655 if inittrace.active {
7656 start = nanotime()
7657 // Load stats non-atomically since tracinit is updated only by this init goroutine.
7658 before = inittrace
7659 }
7660
7661 if t.nfns == 0 {
7662 // We should have pruned all of these in the linker.
7663 throw("inittask with no functions")
7664 }
7665
7666 firstFunc := add(unsafe.Pointer(t), 8)
7667 for i := uint32(0); i < t.nfns; i++ {
7668 p := add(firstFunc, uintptr(i)*goarch.PtrSize)
7669 f := *(*func())(unsafe.Pointer(&p))
7670 f()
7671 }
7672
7673 if inittrace.active {
7674 end := nanotime()
7675 // Load stats non-atomically since tracinit is updated only by this init goroutine.
7676 after := inittrace
7677
7678 f := *(*func())(unsafe.Pointer(&firstFunc))
7679 pkg := funcpkgpath(findfunc(abi.FuncPCABIInternal(f)))
7680
7681 var sbuf [24]byte
7682 print("init ", pkg, " @")
7683 print(string(fmtNSAsMS(sbuf[:], uint64(start-runtimeInitTime))), " ms, ")
7684 print(string(fmtNSAsMS(sbuf[:], uint64(end-start))), " ms clock, ")
7685 print(string(itoa(sbuf[:], after.bytes-before.bytes)), " bytes, ")
7686 print(string(itoa(sbuf[:], after.allocs-before.allocs)), " allocs")
7687 print("\n")
7688 }
7689
7690 t.state = 2 // initialization done
7691 }
7692 }