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