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