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