]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/proc.go
runtime/trace: add missing events for the locked g in extra M.
[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.isextra = true
1980         mp.lockedInt++
1981         mp.lockedg.set(gp)
1982         gp.lockedm.set(mp)
1983         gp.goid = sched.goidgen.Add(1)
1984         gp.sysblocktraced = true
1985         if raceenabled {
1986                 gp.racectx = racegostart(abi.FuncPCABIInternal(newextram) + sys.PCQuantum)
1987         }
1988         if trace.enabled {
1989                 // Trigger two trace events for the locked g in the extra m,
1990                 // since the next event of the g will be traceEvGoSysExit in exitsyscall,
1991                 // while calling from C thread to Go.
1992                 traceGoCreate(gp, 0) // no start pc
1993                 gp.traceseq++
1994                 traceEvent(traceEvGoInSyscall, -1, gp.goid)
1995         }
1996         // put on allg for garbage collector
1997         allgadd(gp)
1998
1999         // gp is now on the allg list, but we don't want it to be
2000         // counted by gcount. It would be more "proper" to increment
2001         // sched.ngfree, but that requires locking. Incrementing ngsys
2002         // has the same effect.
2003         sched.ngsys.Add(1)
2004
2005         // Add m to the extra list.
2006         mnext := lockextra(true)
2007         mp.schedlink.set(mnext)
2008         extraMCount++
2009         unlockextra(mp)
2010 }
2011
2012 // dropm is called when a cgo callback has called needm but is now
2013 // done with the callback and returning back into the non-Go thread.
2014 // It puts the current m back onto the extra list.
2015 //
2016 // The main expense here is the call to signalstack to release the
2017 // m's signal stack, and then the call to needm on the next callback
2018 // from this thread. It is tempting to try to save the m for next time,
2019 // which would eliminate both these costs, but there might not be
2020 // a next time: the current thread (which Go does not control) might exit.
2021 // If we saved the m for that thread, there would be an m leak each time
2022 // such a thread exited. Instead, we acquire and release an m on each
2023 // call. These should typically not be scheduling operations, just a few
2024 // atomics, so the cost should be small.
2025 //
2026 // TODO(rsc): An alternative would be to allocate a dummy pthread per-thread
2027 // variable using pthread_key_create. Unlike the pthread keys we already use
2028 // on OS X, this dummy key would never be read by Go code. It would exist
2029 // only so that we could register at thread-exit-time destructor.
2030 // That destructor would put the m back onto the extra list.
2031 // This is purely a performance optimization. The current version,
2032 // in which dropm happens on each cgo call, is still correct too.
2033 // We may have to keep the current version on systems with cgo
2034 // but without pthreads, like Windows.
2035 func dropm() {
2036         // Clear m and g, and return m to the extra list.
2037         // After the call to setg we can only call nosplit functions
2038         // with no pointer manipulation.
2039         mp := getg().m
2040
2041         // Return mp.curg to dead state.
2042         casgstatus(mp.curg, _Gsyscall, _Gdead)
2043         mp.curg.preemptStop = false
2044         sched.ngsys.Add(1)
2045
2046         // Block signals before unminit.
2047         // Unminit unregisters the signal handling stack (but needs g on some systems).
2048         // Setg(nil) clears g, which is the signal handler's cue not to run Go handlers.
2049         // It's important not to try to handle a signal between those two steps.
2050         sigmask := mp.sigmask
2051         sigblock(false)
2052         unminit()
2053
2054         mnext := lockextra(true)
2055         extraMCount++
2056         mp.schedlink.set(mnext)
2057
2058         setg(nil)
2059
2060         // Commit the release of mp.
2061         unlockextra(mp)
2062
2063         msigrestore(sigmask)
2064 }
2065
2066 // A helper function for EnsureDropM.
2067 func getm() uintptr {
2068         return uintptr(unsafe.Pointer(getg().m))
2069 }
2070
2071 var extram atomic.Uintptr
2072 var extraMCount uint32 // Protected by lockextra
2073 var extraMWaiters atomic.Uint32
2074
2075 // lockextra locks the extra list and returns the list head.
2076 // The caller must unlock the list by storing a new list head
2077 // to extram. If nilokay is true, then lockextra will
2078 // return a nil list head if that's what it finds. If nilokay is false,
2079 // lockextra will keep waiting until the list head is no longer nil.
2080 //
2081 //go:nosplit
2082 func lockextra(nilokay bool) *m {
2083         const locked = 1
2084
2085         incr := false
2086         for {
2087                 old := extram.Load()
2088                 if old == locked {
2089                         osyield_no_g()
2090                         continue
2091                 }
2092                 if old == 0 && !nilokay {
2093                         if !incr {
2094                                 // Add 1 to the number of threads
2095                                 // waiting for an M.
2096                                 // This is cleared by newextram.
2097                                 extraMWaiters.Add(1)
2098                                 incr = true
2099                         }
2100                         usleep_no_g(1)
2101                         continue
2102                 }
2103                 if extram.CompareAndSwap(old, locked) {
2104                         return (*m)(unsafe.Pointer(old))
2105                 }
2106                 osyield_no_g()
2107                 continue
2108         }
2109 }
2110
2111 //go:nosplit
2112 func unlockextra(mp *m) {
2113         extram.Store(uintptr(unsafe.Pointer(mp)))
2114 }
2115
2116 var (
2117         // allocmLock is locked for read when creating new Ms in allocm and their
2118         // addition to allm. Thus acquiring this lock for write blocks the
2119         // creation of new Ms.
2120         allocmLock rwmutex
2121
2122         // execLock serializes exec and clone to avoid bugs or unspecified
2123         // behaviour around exec'ing while creating/destroying threads. See
2124         // issue #19546.
2125         execLock rwmutex
2126 )
2127
2128 // newmHandoff contains a list of m structures that need new OS threads.
2129 // This is used by newm in situations where newm itself can't safely
2130 // start an OS thread.
2131 var newmHandoff struct {
2132         lock mutex
2133
2134         // newm points to a list of M structures that need new OS
2135         // threads. The list is linked through m.schedlink.
2136         newm muintptr
2137
2138         // waiting indicates that wake needs to be notified when an m
2139         // is put on the list.
2140         waiting bool
2141         wake    note
2142
2143         // haveTemplateThread indicates that the templateThread has
2144         // been started. This is not protected by lock. Use cas to set
2145         // to 1.
2146         haveTemplateThread uint32
2147 }
2148
2149 // Create a new m. It will start off with a call to fn, or else the scheduler.
2150 // fn needs to be static and not a heap allocated closure.
2151 // May run with m.p==nil, so write barriers are not allowed.
2152 //
2153 // id is optional pre-allocated m ID. Omit by passing -1.
2154 //
2155 //go:nowritebarrierrec
2156 func newm(fn func(), pp *p, id int64) {
2157         // allocm adds a new M to allm, but they do not start until created by
2158         // the OS in newm1 or the template thread.
2159         //
2160         // doAllThreadsSyscall requires that every M in allm will eventually
2161         // start and be signal-able, even with a STW.
2162         //
2163         // Disable preemption here until we start the thread to ensure that
2164         // newm is not preempted between allocm and starting the new thread,
2165         // ensuring that anything added to allm is guaranteed to eventually
2166         // start.
2167         acquirem()
2168
2169         mp := allocm(pp, fn, id)
2170         mp.nextp.set(pp)
2171         mp.sigmask = initSigmask
2172         if gp := getg(); gp != nil && gp.m != nil && (gp.m.lockedExt != 0 || gp.m.incgo) && GOOS != "plan9" {
2173                 // We're on a locked M or a thread that may have been
2174                 // started by C. The kernel state of this thread may
2175                 // be strange (the user may have locked it for that
2176                 // purpose). We don't want to clone that into another
2177                 // thread. Instead, ask a known-good thread to create
2178                 // the thread for us.
2179                 //
2180                 // This is disabled on Plan 9. See golang.org/issue/22227.
2181                 //
2182                 // TODO: This may be unnecessary on Windows, which
2183                 // doesn't model thread creation off fork.
2184                 lock(&newmHandoff.lock)
2185                 if newmHandoff.haveTemplateThread == 0 {
2186                         throw("on a locked thread with no template thread")
2187                 }
2188                 mp.schedlink = newmHandoff.newm
2189                 newmHandoff.newm.set(mp)
2190                 if newmHandoff.waiting {
2191                         newmHandoff.waiting = false
2192                         notewakeup(&newmHandoff.wake)
2193                 }
2194                 unlock(&newmHandoff.lock)
2195                 // The M has not started yet, but the template thread does not
2196                 // participate in STW, so it will always process queued Ms and
2197                 // it is safe to releasem.
2198                 releasem(getg().m)
2199                 return
2200         }
2201         newm1(mp)
2202         releasem(getg().m)
2203 }
2204
2205 func newm1(mp *m) {
2206         if iscgo {
2207                 var ts cgothreadstart
2208                 if _cgo_thread_start == nil {
2209                         throw("_cgo_thread_start missing")
2210                 }
2211                 ts.g.set(mp.g0)
2212                 ts.tls = (*uint64)(unsafe.Pointer(&mp.tls[0]))
2213                 ts.fn = unsafe.Pointer(abi.FuncPCABI0(mstart))
2214                 if msanenabled {
2215                         msanwrite(unsafe.Pointer(&ts), unsafe.Sizeof(ts))
2216                 }
2217                 if asanenabled {
2218                         asanwrite(unsafe.Pointer(&ts), unsafe.Sizeof(ts))
2219                 }
2220                 execLock.rlock() // Prevent process clone.
2221                 asmcgocall(_cgo_thread_start, unsafe.Pointer(&ts))
2222                 execLock.runlock()
2223                 return
2224         }
2225         execLock.rlock() // Prevent process clone.
2226         newosproc(mp)
2227         execLock.runlock()
2228 }
2229
2230 // startTemplateThread starts the template thread if it is not already
2231 // running.
2232 //
2233 // The calling thread must itself be in a known-good state.
2234 func startTemplateThread() {
2235         if GOARCH == "wasm" { // no threads on wasm yet
2236                 return
2237         }
2238
2239         // Disable preemption to guarantee that the template thread will be
2240         // created before a park once haveTemplateThread is set.
2241         mp := acquirem()
2242         if !atomic.Cas(&newmHandoff.haveTemplateThread, 0, 1) {
2243                 releasem(mp)
2244                 return
2245         }
2246         newm(templateThread, nil, -1)
2247         releasem(mp)
2248 }
2249
2250 // templateThread is a thread in a known-good state that exists solely
2251 // to start new threads in known-good states when the calling thread
2252 // may not be in a good state.
2253 //
2254 // Many programs never need this, so templateThread is started lazily
2255 // when we first enter a state that might lead to running on a thread
2256 // in an unknown state.
2257 //
2258 // templateThread runs on an M without a P, so it must not have write
2259 // barriers.
2260 //
2261 //go:nowritebarrierrec
2262 func templateThread() {
2263         lock(&sched.lock)
2264         sched.nmsys++
2265         checkdead()
2266         unlock(&sched.lock)
2267
2268         for {
2269                 lock(&newmHandoff.lock)
2270                 for newmHandoff.newm != 0 {
2271                         newm := newmHandoff.newm.ptr()
2272                         newmHandoff.newm = 0
2273                         unlock(&newmHandoff.lock)
2274                         for newm != nil {
2275                                 next := newm.schedlink.ptr()
2276                                 newm.schedlink = 0
2277                                 newm1(newm)
2278                                 newm = next
2279                         }
2280                         lock(&newmHandoff.lock)
2281                 }
2282                 newmHandoff.waiting = true
2283                 noteclear(&newmHandoff.wake)
2284                 unlock(&newmHandoff.lock)
2285                 notesleep(&newmHandoff.wake)
2286         }
2287 }
2288
2289 // Stops execution of the current m until new work is available.
2290 // Returns with acquired P.
2291 func stopm() {
2292         gp := getg()
2293
2294         if gp.m.locks != 0 {
2295                 throw("stopm holding locks")
2296         }
2297         if gp.m.p != 0 {
2298                 throw("stopm holding p")
2299         }
2300         if gp.m.spinning {
2301                 throw("stopm spinning")
2302         }
2303
2304         lock(&sched.lock)
2305         mput(gp.m)
2306         unlock(&sched.lock)
2307         mPark()
2308         acquirep(gp.m.nextp.ptr())
2309         gp.m.nextp = 0
2310 }
2311
2312 func mspinning() {
2313         // startm's caller incremented nmspinning. Set the new M's spinning.
2314         getg().m.spinning = true
2315 }
2316
2317 // Schedules some M to run the p (creates an M if necessary).
2318 // If p==nil, tries to get an idle P, if no idle P's does nothing.
2319 // May run with m.p==nil, so write barriers are not allowed.
2320 // If spinning is set, the caller has incremented nmspinning and must provide a
2321 // P. startm will set m.spinning in the newly started M.
2322 //
2323 // Callers passing a non-nil P must call from a non-preemptible context. See
2324 // comment on acquirem below.
2325 //
2326 // Must not have write barriers because this may be called without a P.
2327 //
2328 //go:nowritebarrierrec
2329 func startm(pp *p, spinning bool) {
2330         // Disable preemption.
2331         //
2332         // Every owned P must have an owner that will eventually stop it in the
2333         // event of a GC stop request. startm takes transient ownership of a P
2334         // (either from argument or pidleget below) and transfers ownership to
2335         // a started M, which will be responsible for performing the stop.
2336         //
2337         // Preemption must be disabled during this transient ownership,
2338         // otherwise the P this is running on may enter GC stop while still
2339         // holding the transient P, leaving that P in limbo and deadlocking the
2340         // STW.
2341         //
2342         // Callers passing a non-nil P must already be in non-preemptible
2343         // context, otherwise such preemption could occur on function entry to
2344         // startm. Callers passing a nil P may be preemptible, so we must
2345         // disable preemption before acquiring a P from pidleget below.
2346         mp := acquirem()
2347         lock(&sched.lock)
2348         if pp == nil {
2349                 if spinning {
2350                         // TODO(prattmic): All remaining calls to this function
2351                         // with _p_ == nil could be cleaned up to find a P
2352                         // before calling startm.
2353                         throw("startm: P required for spinning=true")
2354                 }
2355                 pp, _ = pidleget(0)
2356                 if pp == nil {
2357                         unlock(&sched.lock)
2358                         releasem(mp)
2359                         return
2360                 }
2361         }
2362         nmp := mget()
2363         if nmp == nil {
2364                 // No M is available, we must drop sched.lock and call newm.
2365                 // However, we already own a P to assign to the M.
2366                 //
2367                 // Once sched.lock is released, another G (e.g., in a syscall),
2368                 // could find no idle P while checkdead finds a runnable G but
2369                 // no running M's because this new M hasn't started yet, thus
2370                 // throwing in an apparent deadlock.
2371                 //
2372                 // Avoid this situation by pre-allocating the ID for the new M,
2373                 // thus marking it as 'running' before we drop sched.lock. This
2374                 // new M will eventually run the scheduler to execute any
2375                 // queued G's.
2376                 id := mReserveID()
2377                 unlock(&sched.lock)
2378
2379                 var fn func()
2380                 if spinning {
2381                         // The caller incremented nmspinning, so set m.spinning in the new M.
2382                         fn = mspinning
2383                 }
2384                 newm(fn, pp, id)
2385                 // Ownership transfer of pp committed by start in newm.
2386                 // Preemption is now safe.
2387                 releasem(mp)
2388                 return
2389         }
2390         unlock(&sched.lock)
2391         if nmp.spinning {
2392                 throw("startm: m is spinning")
2393         }
2394         if nmp.nextp != 0 {
2395                 throw("startm: m has p")
2396         }
2397         if spinning && !runqempty(pp) {
2398                 throw("startm: p has runnable gs")
2399         }
2400         // The caller incremented nmspinning, so set m.spinning in the new M.
2401         nmp.spinning = spinning
2402         nmp.nextp.set(pp)
2403         notewakeup(&nmp.park)
2404         // Ownership transfer of pp committed by wakeup. Preemption is now
2405         // safe.
2406         releasem(mp)
2407 }
2408
2409 // Hands off P from syscall or locked M.
2410 // Always runs without a P, so write barriers are not allowed.
2411 //
2412 //go:nowritebarrierrec
2413 func handoffp(pp *p) {
2414         // handoffp must start an M in any situation where
2415         // findrunnable would return a G to run on pp.
2416
2417         // if it has local work, start it straight away
2418         if !runqempty(pp) || sched.runqsize != 0 {
2419                 startm(pp, false)
2420                 return
2421         }
2422         // if there's trace work to do, start it straight away
2423         if (trace.enabled || trace.shutdown) && traceReaderAvailable() != nil {
2424                 startm(pp, false)
2425                 return
2426         }
2427         // if it has GC work, start it straight away
2428         if gcBlackenEnabled != 0 && gcMarkWorkAvailable(pp) {
2429                 startm(pp, false)
2430                 return
2431         }
2432         // no local work, check that there are no spinning/idle M's,
2433         // otherwise our help is not required
2434         if sched.nmspinning.Load()+sched.npidle.Load() == 0 && sched.nmspinning.CompareAndSwap(0, 1) { // TODO: fast atomic
2435                 sched.needspinning.Store(0)
2436                 startm(pp, true)
2437                 return
2438         }
2439         lock(&sched.lock)
2440         if sched.gcwaiting.Load() {
2441                 pp.status = _Pgcstop
2442                 sched.stopwait--
2443                 if sched.stopwait == 0 {
2444                         notewakeup(&sched.stopnote)
2445                 }
2446                 unlock(&sched.lock)
2447                 return
2448         }
2449         if pp.runSafePointFn != 0 && atomic.Cas(&pp.runSafePointFn, 1, 0) {
2450                 sched.safePointFn(pp)
2451                 sched.safePointWait--
2452                 if sched.safePointWait == 0 {
2453                         notewakeup(&sched.safePointNote)
2454                 }
2455         }
2456         if sched.runqsize != 0 {
2457                 unlock(&sched.lock)
2458                 startm(pp, false)
2459                 return
2460         }
2461         // If this is the last running P and nobody is polling network,
2462         // need to wakeup another M to poll network.
2463         if sched.npidle.Load() == gomaxprocs-1 && sched.lastpoll.Load() != 0 {
2464                 unlock(&sched.lock)
2465                 startm(pp, false)
2466                 return
2467         }
2468
2469         // The scheduler lock cannot be held when calling wakeNetPoller below
2470         // because wakeNetPoller may call wakep which may call startm.
2471         when := nobarrierWakeTime(pp)
2472         pidleput(pp, 0)
2473         unlock(&sched.lock)
2474
2475         if when != 0 {
2476                 wakeNetPoller(when)
2477         }
2478 }
2479
2480 // Tries to add one more P to execute G's.
2481 // Called when a G is made runnable (newproc, ready).
2482 // Must be called with a P.
2483 func wakep() {
2484         // Be conservative about spinning threads, only start one if none exist
2485         // already.
2486         if sched.nmspinning.Load() != 0 || !sched.nmspinning.CompareAndSwap(0, 1) {
2487                 return
2488         }
2489
2490         // Disable preemption until ownership of pp transfers to the next M in
2491         // startm. Otherwise preemption here would leave pp stuck waiting to
2492         // enter _Pgcstop.
2493         //
2494         // See preemption comment on acquirem in startm for more details.
2495         mp := acquirem()
2496
2497         var pp *p
2498         lock(&sched.lock)
2499         pp, _ = pidlegetSpinning(0)
2500         if pp == nil {
2501                 if sched.nmspinning.Add(-1) < 0 {
2502                         throw("wakep: negative nmspinning")
2503                 }
2504                 unlock(&sched.lock)
2505                 releasem(mp)
2506                 return
2507         }
2508         // Since we always have a P, the race in the "No M is available"
2509         // comment in startm doesn't apply during the small window between the
2510         // unlock here and lock in startm. A checkdead in between will always
2511         // see at least one running M (ours).
2512         unlock(&sched.lock)
2513
2514         startm(pp, true)
2515
2516         releasem(mp)
2517 }
2518
2519 // Stops execution of the current m that is locked to a g until the g is runnable again.
2520 // Returns with acquired P.
2521 func stoplockedm() {
2522         gp := getg()
2523
2524         if gp.m.lockedg == 0 || gp.m.lockedg.ptr().lockedm.ptr() != gp.m {
2525                 throw("stoplockedm: inconsistent locking")
2526         }
2527         if gp.m.p != 0 {
2528                 // Schedule another M to run this p.
2529                 pp := releasep()
2530                 handoffp(pp)
2531         }
2532         incidlelocked(1)
2533         // Wait until another thread schedules lockedg again.
2534         mPark()
2535         status := readgstatus(gp.m.lockedg.ptr())
2536         if status&^_Gscan != _Grunnable {
2537                 print("runtime:stoplockedm: lockedg (atomicstatus=", status, ") is not Grunnable or Gscanrunnable\n")
2538                 dumpgstatus(gp.m.lockedg.ptr())
2539                 throw("stoplockedm: not runnable")
2540         }
2541         acquirep(gp.m.nextp.ptr())
2542         gp.m.nextp = 0
2543 }
2544
2545 // Schedules the locked m to run the locked gp.
2546 // May run during STW, so write barriers are not allowed.
2547 //
2548 //go:nowritebarrierrec
2549 func startlockedm(gp *g) {
2550         mp := gp.lockedm.ptr()
2551         if mp == getg().m {
2552                 throw("startlockedm: locked to me")
2553         }
2554         if mp.nextp != 0 {
2555                 throw("startlockedm: m has p")
2556         }
2557         // directly handoff current P to the locked m
2558         incidlelocked(-1)
2559         pp := releasep()
2560         mp.nextp.set(pp)
2561         notewakeup(&mp.park)
2562         stopm()
2563 }
2564
2565 // Stops the current m for stopTheWorld.
2566 // Returns when the world is restarted.
2567 func gcstopm() {
2568         gp := getg()
2569
2570         if !sched.gcwaiting.Load() {
2571                 throw("gcstopm: not waiting for gc")
2572         }
2573         if gp.m.spinning {
2574                 gp.m.spinning = false
2575                 // OK to just drop nmspinning here,
2576                 // startTheWorld will unpark threads as necessary.
2577                 if sched.nmspinning.Add(-1) < 0 {
2578                         throw("gcstopm: negative nmspinning")
2579                 }
2580         }
2581         pp := releasep()
2582         lock(&sched.lock)
2583         pp.status = _Pgcstop
2584         sched.stopwait--
2585         if sched.stopwait == 0 {
2586                 notewakeup(&sched.stopnote)
2587         }
2588         unlock(&sched.lock)
2589         stopm()
2590 }
2591
2592 // Schedules gp to run on the current M.
2593 // If inheritTime is true, gp inherits the remaining time in the
2594 // current time slice. Otherwise, it starts a new time slice.
2595 // Never returns.
2596 //
2597 // Write barriers are allowed because this is called immediately after
2598 // acquiring a P in several places.
2599 //
2600 //go:yeswritebarrierrec
2601 func execute(gp *g, inheritTime bool) {
2602         mp := getg().m
2603
2604         if goroutineProfile.active {
2605                 // Make sure that gp has had its stack written out to the goroutine
2606                 // profile, exactly as it was when the goroutine profiler first stopped
2607                 // the world.
2608                 tryRecordGoroutineProfile(gp, osyield)
2609         }
2610
2611         // Assign gp.m before entering _Grunning so running Gs have an
2612         // M.
2613         mp.curg = gp
2614         gp.m = mp
2615         casgstatus(gp, _Grunnable, _Grunning)
2616         gp.waitsince = 0
2617         gp.preempt = false
2618         gp.stackguard0 = gp.stack.lo + _StackGuard
2619         if !inheritTime {
2620                 mp.p.ptr().schedtick++
2621         }
2622
2623         // Check whether the profiler needs to be turned on or off.
2624         hz := sched.profilehz
2625         if mp.profilehz != hz {
2626                 setThreadCPUProfiler(hz)
2627         }
2628
2629         if trace.enabled {
2630                 // GoSysExit has to happen when we have a P, but before GoStart.
2631                 // So we emit it here.
2632                 if gp.syscallsp != 0 && gp.sysblocktraced {
2633                         traceGoSysExit(gp.sysexitticks)
2634                 }
2635                 traceGoStart()
2636         }
2637
2638         gogo(&gp.sched)
2639 }
2640
2641 // Finds a runnable goroutine to execute.
2642 // Tries to steal from other P's, get g from local or global queue, poll network.
2643 // tryWakeP indicates that the returned goroutine is not normal (GC worker, trace
2644 // reader) so the caller should try to wake a P.
2645 func findRunnable() (gp *g, inheritTime, tryWakeP bool) {
2646         mp := getg().m
2647
2648         // The conditions here and in handoffp must agree: if
2649         // findrunnable would return a G to run, handoffp must start
2650         // an M.
2651
2652 top:
2653         pp := mp.p.ptr()
2654         if sched.gcwaiting.Load() {
2655                 gcstopm()
2656                 goto top
2657         }
2658         if pp.runSafePointFn != 0 {
2659                 runSafePointFn()
2660         }
2661
2662         // now and pollUntil are saved for work stealing later,
2663         // which may steal timers. It's important that between now
2664         // and then, nothing blocks, so these numbers remain mostly
2665         // relevant.
2666         now, pollUntil, _ := checkTimers(pp, 0)
2667
2668         // Try to schedule the trace reader.
2669         if trace.enabled || trace.shutdown {
2670                 gp := traceReader()
2671                 if gp != nil {
2672                         casgstatus(gp, _Gwaiting, _Grunnable)
2673                         traceGoUnpark(gp, 0)
2674                         return gp, false, true
2675                 }
2676         }
2677
2678         // Try to schedule a GC worker.
2679         if gcBlackenEnabled != 0 {
2680                 gp, tnow := gcController.findRunnableGCWorker(pp, now)
2681                 if gp != nil {
2682                         return gp, false, true
2683                 }
2684                 now = tnow
2685         }
2686
2687         // Check the global runnable queue once in a while to ensure fairness.
2688         // Otherwise two goroutines can completely occupy the local runqueue
2689         // by constantly respawning each other.
2690         if pp.schedtick%61 == 0 && sched.runqsize > 0 {
2691                 lock(&sched.lock)
2692                 gp := globrunqget(pp, 1)
2693                 unlock(&sched.lock)
2694                 if gp != nil {
2695                         return gp, false, false
2696                 }
2697         }
2698
2699         // Wake up the finalizer G.
2700         if fingStatus.Load()&(fingWait|fingWake) == fingWait|fingWake {
2701                 if gp := wakefing(); gp != nil {
2702                         ready(gp, 0, true)
2703                 }
2704         }
2705         if *cgo_yield != nil {
2706                 asmcgocall(*cgo_yield, nil)
2707         }
2708
2709         // local runq
2710         if gp, inheritTime := runqget(pp); gp != nil {
2711                 return gp, inheritTime, false
2712         }
2713
2714         // global runq
2715         if sched.runqsize != 0 {
2716                 lock(&sched.lock)
2717                 gp := globrunqget(pp, 0)
2718                 unlock(&sched.lock)
2719                 if gp != nil {
2720                         return gp, false, false
2721                 }
2722         }
2723
2724         // Poll network.
2725         // This netpoll is only an optimization before we resort to stealing.
2726         // We can safely skip it if there are no waiters or a thread is blocked
2727         // in netpoll already. If there is any kind of logical race with that
2728         // blocked thread (e.g. it has already returned from netpoll, but does
2729         // not set lastpoll yet), this thread will do blocking netpoll below
2730         // anyway.
2731         if netpollinited() && netpollWaiters.Load() > 0 && sched.lastpoll.Load() != 0 {
2732                 if list := netpoll(0); !list.empty() { // non-blocking
2733                         gp := list.pop()
2734                         injectglist(&list)
2735                         casgstatus(gp, _Gwaiting, _Grunnable)
2736                         if trace.enabled {
2737                                 traceGoUnpark(gp, 0)
2738                         }
2739                         return gp, false, false
2740                 }
2741         }
2742
2743         // Spinning Ms: steal work from other Ps.
2744         //
2745         // Limit the number of spinning Ms to half the number of busy Ps.
2746         // This is necessary to prevent excessive CPU consumption when
2747         // GOMAXPROCS>>1 but the program parallelism is low.
2748         if mp.spinning || 2*sched.nmspinning.Load() < gomaxprocs-sched.npidle.Load() {
2749                 if !mp.spinning {
2750                         mp.becomeSpinning()
2751                 }
2752
2753                 gp, inheritTime, tnow, w, newWork := stealWork(now)
2754                 if gp != nil {
2755                         // Successfully stole.
2756                         return gp, inheritTime, false
2757                 }
2758                 if newWork {
2759                         // There may be new timer or GC work; restart to
2760                         // discover.
2761                         goto top
2762                 }
2763
2764                 now = tnow
2765                 if w != 0 && (pollUntil == 0 || w < pollUntil) {
2766                         // Earlier timer to wait for.
2767                         pollUntil = w
2768                 }
2769         }
2770
2771         // We have nothing to do.
2772         //
2773         // If we're in the GC mark phase, can safely scan and blacken objects,
2774         // and have work to do, run idle-time marking rather than give up the P.
2775         if gcBlackenEnabled != 0 && gcMarkWorkAvailable(pp) && gcController.addIdleMarkWorker() {
2776                 node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
2777                 if node != nil {
2778                         pp.gcMarkWorkerMode = gcMarkWorkerIdleMode
2779                         gp := node.gp.ptr()
2780                         casgstatus(gp, _Gwaiting, _Grunnable)
2781                         if trace.enabled {
2782                                 traceGoUnpark(gp, 0)
2783                         }
2784                         return gp, false, false
2785                 }
2786                 gcController.removeIdleMarkWorker()
2787         }
2788
2789         // wasm only:
2790         // If a callback returned and no other goroutine is awake,
2791         // then wake event handler goroutine which pauses execution
2792         // until a callback was triggered.
2793         gp, otherReady := beforeIdle(now, pollUntil)
2794         if gp != nil {
2795                 casgstatus(gp, _Gwaiting, _Grunnable)
2796                 if trace.enabled {
2797                         traceGoUnpark(gp, 0)
2798                 }
2799                 return gp, false, false
2800         }
2801         if otherReady {
2802                 goto top
2803         }
2804
2805         // Before we drop our P, make a snapshot of the allp slice,
2806         // which can change underfoot once we no longer block
2807         // safe-points. We don't need to snapshot the contents because
2808         // everything up to cap(allp) is immutable.
2809         allpSnapshot := allp
2810         // Also snapshot masks. Value changes are OK, but we can't allow
2811         // len to change out from under us.
2812         idlepMaskSnapshot := idlepMask
2813         timerpMaskSnapshot := timerpMask
2814
2815         // return P and block
2816         lock(&sched.lock)
2817         if sched.gcwaiting.Load() || pp.runSafePointFn != 0 {
2818                 unlock(&sched.lock)
2819                 goto top
2820         }
2821         if sched.runqsize != 0 {
2822                 gp := globrunqget(pp, 0)
2823                 unlock(&sched.lock)
2824                 return gp, false, false
2825         }
2826         if !mp.spinning && sched.needspinning.Load() == 1 {
2827                 // See "Delicate dance" comment below.
2828                 mp.becomeSpinning()
2829                 unlock(&sched.lock)
2830                 goto top
2831         }
2832         if releasep() != pp {
2833                 throw("findrunnable: wrong p")
2834         }
2835         now = pidleput(pp, now)
2836         unlock(&sched.lock)
2837
2838         // Delicate dance: thread transitions from spinning to non-spinning
2839         // state, potentially concurrently with submission of new work. We must
2840         // drop nmspinning first and then check all sources again (with
2841         // #StoreLoad memory barrier in between). If we do it the other way
2842         // around, another thread can submit work after we've checked all
2843         // sources but before we drop nmspinning; as a result nobody will
2844         // unpark a thread to run the work.
2845         //
2846         // This applies to the following sources of work:
2847         //
2848         // * Goroutines added to a per-P run queue.
2849         // * New/modified-earlier timers on a per-P timer heap.
2850         // * Idle-priority GC work (barring golang.org/issue/19112).
2851         //
2852         // If we discover new work below, we need to restore m.spinning as a
2853         // signal for resetspinning to unpark a new worker thread (because
2854         // there can be more than one starving goroutine).
2855         //
2856         // However, if after discovering new work we also observe no idle Ps
2857         // (either here or in resetspinning), we have a problem. We may be
2858         // racing with a non-spinning M in the block above, having found no
2859         // work and preparing to release its P and park. Allowing that P to go
2860         // idle will result in loss of work conservation (idle P while there is
2861         // runnable work). This could result in complete deadlock in the
2862         // unlikely event that we discover new work (from netpoll) right as we
2863         // are racing with _all_ other Ps going idle.
2864         //
2865         // We use sched.needspinning to synchronize with non-spinning Ms going
2866         // idle. If needspinning is set when they are about to drop their P,
2867         // they abort the drop and instead become a new spinning M on our
2868         // behalf. If we are not racing and the system is truly fully loaded
2869         // then no spinning threads are required, and the next thread to
2870         // naturally become spinning will clear the flag.
2871         //
2872         // Also see "Worker thread parking/unparking" comment at the top of the
2873         // file.
2874         wasSpinning := mp.spinning
2875         if mp.spinning {
2876                 mp.spinning = false
2877                 if sched.nmspinning.Add(-1) < 0 {
2878                         throw("findrunnable: negative nmspinning")
2879                 }
2880
2881                 // Note the for correctness, only the last M transitioning from
2882                 // spinning to non-spinning must perform these rechecks to
2883                 // ensure no missed work. However, the runtime has some cases
2884                 // of transient increments of nmspinning that are decremented
2885                 // without going through this path, so we must be conservative
2886                 // and perform the check on all spinning Ms.
2887                 //
2888                 // See https://go.dev/issue/43997.
2889
2890                 // Check all runqueues once again.
2891                 pp := checkRunqsNoP(allpSnapshot, idlepMaskSnapshot)
2892                 if pp != nil {
2893                         acquirep(pp)
2894                         mp.becomeSpinning()
2895                         goto top
2896                 }
2897
2898                 // Check for idle-priority GC work again.
2899                 pp, gp := checkIdleGCNoP()
2900                 if pp != nil {
2901                         acquirep(pp)
2902                         mp.becomeSpinning()
2903
2904                         // Run the idle worker.
2905                         pp.gcMarkWorkerMode = gcMarkWorkerIdleMode
2906                         casgstatus(gp, _Gwaiting, _Grunnable)
2907                         if trace.enabled {
2908                                 traceGoUnpark(gp, 0)
2909                         }
2910                         return gp, false, false
2911                 }
2912
2913                 // Finally, check for timer creation or expiry concurrently with
2914                 // transitioning from spinning to non-spinning.
2915                 //
2916                 // Note that we cannot use checkTimers here because it calls
2917                 // adjusttimers which may need to allocate memory, and that isn't
2918                 // allowed when we don't have an active P.
2919                 pollUntil = checkTimersNoP(allpSnapshot, timerpMaskSnapshot, pollUntil)
2920         }
2921
2922         // Poll network until next timer.
2923         if netpollinited() && (netpollWaiters.Load() > 0 || pollUntil != 0) && sched.lastpoll.Swap(0) != 0 {
2924                 sched.pollUntil.Store(pollUntil)
2925                 if mp.p != 0 {
2926                         throw("findrunnable: netpoll with p")
2927                 }
2928                 if mp.spinning {
2929                         throw("findrunnable: netpoll with spinning")
2930                 }
2931                 // Refresh now.
2932                 now = nanotime()
2933                 delay := int64(-1)
2934                 if pollUntil != 0 {
2935                         delay = pollUntil - now
2936                         if delay < 0 {
2937                                 delay = 0
2938                         }
2939                 }
2940                 if faketime != 0 {
2941                         // When using fake time, just poll.
2942                         delay = 0
2943                 }
2944                 list := netpoll(delay) // block until new work is available
2945                 sched.pollUntil.Store(0)
2946                 sched.lastpoll.Store(now)
2947                 if faketime != 0 && list.empty() {
2948                         // Using fake time and nothing is ready; stop M.
2949                         // When all M's stop, checkdead will call timejump.
2950                         stopm()
2951                         goto top
2952                 }
2953                 lock(&sched.lock)
2954                 pp, _ := pidleget(now)
2955                 unlock(&sched.lock)
2956                 if pp == nil {
2957                         injectglist(&list)
2958                 } else {
2959                         acquirep(pp)
2960                         if !list.empty() {
2961                                 gp := list.pop()
2962                                 injectglist(&list)
2963                                 casgstatus(gp, _Gwaiting, _Grunnable)
2964                                 if trace.enabled {
2965                                         traceGoUnpark(gp, 0)
2966                                 }
2967                                 return gp, false, false
2968                         }
2969                         if wasSpinning {
2970                                 mp.becomeSpinning()
2971                         }
2972                         goto top
2973                 }
2974         } else if pollUntil != 0 && netpollinited() {
2975                 pollerPollUntil := sched.pollUntil.Load()
2976                 if pollerPollUntil == 0 || pollerPollUntil > pollUntil {
2977                         netpollBreak()
2978                 }
2979         }
2980         stopm()
2981         goto top
2982 }
2983
2984 // pollWork reports whether there is non-background work this P could
2985 // be doing. This is a fairly lightweight check to be used for
2986 // background work loops, like idle GC. It checks a subset of the
2987 // conditions checked by the actual scheduler.
2988 func pollWork() bool {
2989         if sched.runqsize != 0 {
2990                 return true
2991         }
2992         p := getg().m.p.ptr()
2993         if !runqempty(p) {
2994                 return true
2995         }
2996         if netpollinited() && netpollWaiters.Load() > 0 && sched.lastpoll.Load() != 0 {
2997                 if list := netpoll(0); !list.empty() {
2998                         injectglist(&list)
2999                         return true
3000                 }
3001         }
3002         return false
3003 }
3004
3005 // stealWork attempts to steal a runnable goroutine or timer from any P.
3006 //
3007 // If newWork is true, new work may have been readied.
3008 //
3009 // If now is not 0 it is the current time. stealWork returns the passed time or
3010 // the current time if now was passed as 0.
3011 func stealWork(now int64) (gp *g, inheritTime bool, rnow, pollUntil int64, newWork bool) {
3012         pp := getg().m.p.ptr()
3013
3014         ranTimer := false
3015
3016         const stealTries = 4
3017         for i := 0; i < stealTries; i++ {
3018                 stealTimersOrRunNextG := i == stealTries-1
3019
3020                 for enum := stealOrder.start(fastrand()); !enum.done(); enum.next() {
3021                         if sched.gcwaiting.Load() {
3022                                 // GC work may be available.
3023                                 return nil, false, now, pollUntil, true
3024                         }
3025                         p2 := allp[enum.position()]
3026                         if pp == p2 {
3027                                 continue
3028                         }
3029
3030                         // Steal timers from p2. This call to checkTimers is the only place
3031                         // where we might hold a lock on a different P's timers. We do this
3032                         // once on the last pass before checking runnext because stealing
3033                         // from the other P's runnext should be the last resort, so if there
3034                         // are timers to steal do that first.
3035                         //
3036                         // We only check timers on one of the stealing iterations because
3037                         // the time stored in now doesn't change in this loop and checking
3038                         // the timers for each P more than once with the same value of now
3039                         // is probably a waste of time.
3040                         //
3041                         // timerpMask tells us whether the P may have timers at all. If it
3042                         // can't, no need to check at all.
3043                         if stealTimersOrRunNextG && timerpMask.read(enum.position()) {
3044                                 tnow, w, ran := checkTimers(p2, now)
3045                                 now = tnow
3046                                 if w != 0 && (pollUntil == 0 || w < pollUntil) {
3047                                         pollUntil = w
3048                                 }
3049                                 if ran {
3050                                         // Running the timers may have
3051                                         // made an arbitrary number of G's
3052                                         // ready and added them to this P's
3053                                         // local run queue. That invalidates
3054                                         // the assumption of runqsteal
3055                                         // that it always has room to add
3056                                         // stolen G's. So check now if there
3057                                         // is a local G to run.
3058                                         if gp, inheritTime := runqget(pp); gp != nil {
3059                                                 return gp, inheritTime, now, pollUntil, ranTimer
3060                                         }
3061                                         ranTimer = true
3062                                 }
3063                         }
3064
3065                         // Don't bother to attempt to steal if p2 is idle.
3066                         if !idlepMask.read(enum.position()) {
3067                                 if gp := runqsteal(pp, p2, stealTimersOrRunNextG); gp != nil {
3068                                         return gp, false, now, pollUntil, ranTimer
3069                                 }
3070                         }
3071                 }
3072         }
3073
3074         // No goroutines found to steal. Regardless, running a timer may have
3075         // made some goroutine ready that we missed. Indicate the next timer to
3076         // wait for.
3077         return nil, false, now, pollUntil, ranTimer
3078 }
3079
3080 // Check all Ps for a runnable G to steal.
3081 //
3082 // On entry we have no P. If a G is available to steal and a P is available,
3083 // the P is returned which the caller should acquire and attempt to steal the
3084 // work to.
3085 func checkRunqsNoP(allpSnapshot []*p, idlepMaskSnapshot pMask) *p {
3086         for id, p2 := range allpSnapshot {
3087                 if !idlepMaskSnapshot.read(uint32(id)) && !runqempty(p2) {
3088                         lock(&sched.lock)
3089                         pp, _ := pidlegetSpinning(0)
3090                         if pp == nil {
3091                                 // Can't get a P, don't bother checking remaining Ps.
3092                                 unlock(&sched.lock)
3093                                 return nil
3094                         }
3095                         unlock(&sched.lock)
3096                         return pp
3097                 }
3098         }
3099
3100         // No work available.
3101         return nil
3102 }
3103
3104 // Check all Ps for a timer expiring sooner than pollUntil.
3105 //
3106 // Returns updated pollUntil value.
3107 func checkTimersNoP(allpSnapshot []*p, timerpMaskSnapshot pMask, pollUntil int64) int64 {
3108         for id, p2 := range allpSnapshot {
3109                 if timerpMaskSnapshot.read(uint32(id)) {
3110                         w := nobarrierWakeTime(p2)
3111                         if w != 0 && (pollUntil == 0 || w < pollUntil) {
3112                                 pollUntil = w
3113                         }
3114                 }
3115         }
3116
3117         return pollUntil
3118 }
3119
3120 // Check for idle-priority GC, without a P on entry.
3121 //
3122 // If some GC work, a P, and a worker G are all available, the P and G will be
3123 // returned. The returned P has not been wired yet.
3124 func checkIdleGCNoP() (*p, *g) {
3125         // N.B. Since we have no P, gcBlackenEnabled may change at any time; we
3126         // must check again after acquiring a P. As an optimization, we also check
3127         // if an idle mark worker is needed at all. This is OK here, because if we
3128         // observe that one isn't needed, at least one is currently running. Even if
3129         // it stops running, its own journey into the scheduler should schedule it
3130         // again, if need be (at which point, this check will pass, if relevant).
3131         if atomic.Load(&gcBlackenEnabled) == 0 || !gcController.needIdleMarkWorker() {
3132                 return nil, nil
3133         }
3134         if !gcMarkWorkAvailable(nil) {
3135                 return nil, nil
3136         }
3137
3138         // Work is available; we can start an idle GC worker only if there is
3139         // an available P and available worker G.
3140         //
3141         // We can attempt to acquire these in either order, though both have
3142         // synchronization concerns (see below). Workers are almost always
3143         // available (see comment in findRunnableGCWorker for the one case
3144         // there may be none). Since we're slightly less likely to find a P,
3145         // check for that first.
3146         //
3147         // Synchronization: note that we must hold sched.lock until we are
3148         // committed to keeping it. Otherwise we cannot put the unnecessary P
3149         // back in sched.pidle without performing the full set of idle
3150         // transition checks.
3151         //
3152         // If we were to check gcBgMarkWorkerPool first, we must somehow handle
3153         // the assumption in gcControllerState.findRunnableGCWorker that an
3154         // empty gcBgMarkWorkerPool is only possible if gcMarkDone is running.
3155         lock(&sched.lock)
3156         pp, now := pidlegetSpinning(0)
3157         if pp == nil {
3158                 unlock(&sched.lock)
3159                 return nil, nil
3160         }
3161
3162         // Now that we own a P, gcBlackenEnabled can't change (as it requires STW).
3163         if gcBlackenEnabled == 0 || !gcController.addIdleMarkWorker() {
3164                 pidleput(pp, now)
3165                 unlock(&sched.lock)
3166                 return nil, nil
3167         }
3168
3169         node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
3170         if node == nil {
3171                 pidleput(pp, now)
3172                 unlock(&sched.lock)
3173                 gcController.removeIdleMarkWorker()
3174                 return nil, nil
3175         }
3176
3177         unlock(&sched.lock)
3178
3179         return pp, node.gp.ptr()
3180 }
3181
3182 // wakeNetPoller wakes up the thread sleeping in the network poller if it isn't
3183 // going to wake up before the when argument; or it wakes an idle P to service
3184 // timers and the network poller if there isn't one already.
3185 func wakeNetPoller(when int64) {
3186         if sched.lastpoll.Load() == 0 {
3187                 // In findrunnable we ensure that when polling the pollUntil
3188                 // field is either zero or the time to which the current
3189                 // poll is expected to run. This can have a spurious wakeup
3190                 // but should never miss a wakeup.
3191                 pollerPollUntil := sched.pollUntil.Load()
3192                 if pollerPollUntil == 0 || pollerPollUntil > when {
3193                         netpollBreak()
3194                 }
3195         } else {
3196                 // There are no threads in the network poller, try to get
3197                 // one there so it can handle new timers.
3198                 if GOOS != "plan9" { // Temporary workaround - see issue #42303.
3199                         wakep()
3200                 }
3201         }
3202 }
3203
3204 func resetspinning() {
3205         gp := getg()
3206         if !gp.m.spinning {
3207                 throw("resetspinning: not a spinning m")
3208         }
3209         gp.m.spinning = false
3210         nmspinning := sched.nmspinning.Add(-1)
3211         if nmspinning < 0 {
3212                 throw("findrunnable: negative nmspinning")
3213         }
3214         // M wakeup policy is deliberately somewhat conservative, so check if we
3215         // need to wakeup another P here. See "Worker thread parking/unparking"
3216         // comment at the top of the file for details.
3217         wakep()
3218 }
3219
3220 // injectglist adds each runnable G on the list to some run queue,
3221 // and clears glist. If there is no current P, they are added to the
3222 // global queue, and up to npidle M's are started to run them.
3223 // Otherwise, for each idle P, this adds a G to the global queue
3224 // and starts an M. Any remaining G's are added to the current P's
3225 // local run queue.
3226 // This may temporarily acquire sched.lock.
3227 // Can run concurrently with GC.
3228 func injectglist(glist *gList) {
3229         if glist.empty() {
3230                 return
3231         }
3232         if trace.enabled {
3233                 for gp := glist.head.ptr(); gp != nil; gp = gp.schedlink.ptr() {
3234                         traceGoUnpark(gp, 0)
3235                 }
3236         }
3237
3238         // Mark all the goroutines as runnable before we put them
3239         // on the run queues.
3240         head := glist.head.ptr()
3241         var tail *g
3242         qsize := 0
3243         for gp := head; gp != nil; gp = gp.schedlink.ptr() {
3244                 tail = gp
3245                 qsize++
3246                 casgstatus(gp, _Gwaiting, _Grunnable)
3247         }
3248
3249         // Turn the gList into a gQueue.
3250         var q gQueue
3251         q.head.set(head)
3252         q.tail.set(tail)
3253         *glist = gList{}
3254
3255         startIdle := func(n int) {
3256                 for i := 0; i < n; i++ {
3257                         mp := acquirem() // See comment in startm.
3258                         lock(&sched.lock)
3259
3260                         pp, _ := pidlegetSpinning(0)
3261                         if pp == nil {
3262                                 unlock(&sched.lock)
3263                                 releasem(mp)
3264                                 break
3265                         }
3266
3267                         unlock(&sched.lock)
3268                         startm(pp, false)
3269                         releasem(mp)
3270                 }
3271         }
3272
3273         pp := getg().m.p.ptr()
3274         if pp == nil {
3275                 lock(&sched.lock)
3276                 globrunqputbatch(&q, int32(qsize))
3277                 unlock(&sched.lock)
3278                 startIdle(qsize)
3279                 return
3280         }
3281
3282         npidle := int(sched.npidle.Load())
3283         var globq gQueue
3284         var n int
3285         for n = 0; n < npidle && !q.empty(); n++ {
3286                 g := q.pop()
3287                 globq.pushBack(g)
3288         }
3289         if n > 0 {
3290                 lock(&sched.lock)
3291                 globrunqputbatch(&globq, int32(n))
3292                 unlock(&sched.lock)
3293                 startIdle(n)
3294                 qsize -= n
3295         }
3296
3297         if !q.empty() {
3298                 runqputbatch(pp, &q, qsize)
3299         }
3300 }
3301
3302 // One round of scheduler: find a runnable goroutine and execute it.
3303 // Never returns.
3304 func schedule() {
3305         mp := getg().m
3306
3307         if mp.locks != 0 {
3308                 throw("schedule: holding locks")
3309         }
3310
3311         if mp.lockedg != 0 {
3312                 stoplockedm()
3313                 execute(mp.lockedg.ptr(), false) // Never returns.
3314         }
3315
3316         // We should not schedule away from a g that is executing a cgo call,
3317         // since the cgo call is using the m's g0 stack.
3318         if mp.incgo {
3319                 throw("schedule: in cgo")
3320         }
3321
3322 top:
3323         pp := mp.p.ptr()
3324         pp.preempt = false
3325
3326         // Safety check: if we are spinning, the run queue should be empty.
3327         // Check this before calling checkTimers, as that might call
3328         // goready to put a ready goroutine on the local run queue.
3329         if mp.spinning && (pp.runnext != 0 || pp.runqhead != pp.runqtail) {
3330                 throw("schedule: spinning with local work")
3331         }
3332
3333         gp, inheritTime, tryWakeP := findRunnable() // blocks until work is available
3334
3335         // This thread is going to run a goroutine and is not spinning anymore,
3336         // so if it was marked as spinning we need to reset it now and potentially
3337         // start a new spinning M.
3338         if mp.spinning {
3339                 resetspinning()
3340         }
3341
3342         if sched.disable.user && !schedEnabled(gp) {
3343                 // Scheduling of this goroutine is disabled. Put it on
3344                 // the list of pending runnable goroutines for when we
3345                 // re-enable user scheduling and look again.
3346                 lock(&sched.lock)
3347                 if schedEnabled(gp) {
3348                         // Something re-enabled scheduling while we
3349                         // were acquiring the lock.
3350                         unlock(&sched.lock)
3351                 } else {
3352                         sched.disable.runnable.pushBack(gp)
3353                         sched.disable.n++
3354                         unlock(&sched.lock)
3355                         goto top
3356                 }
3357         }
3358
3359         // If about to schedule a not-normal goroutine (a GCworker or tracereader),
3360         // wake a P if there is one.
3361         if tryWakeP {
3362                 wakep()
3363         }
3364         if gp.lockedm != 0 {
3365                 // Hands off own p to the locked m,
3366                 // then blocks waiting for a new p.
3367                 startlockedm(gp)
3368                 goto top
3369         }
3370
3371         execute(gp, inheritTime)
3372 }
3373
3374 // dropg removes the association between m and the current goroutine m->curg (gp for short).
3375 // Typically a caller sets gp's status away from Grunning and then
3376 // immediately calls dropg to finish the job. The caller is also responsible
3377 // for arranging that gp will be restarted using ready at an
3378 // appropriate time. After calling dropg and arranging for gp to be
3379 // readied later, the caller can do other work but eventually should
3380 // call schedule to restart the scheduling of goroutines on this m.
3381 func dropg() {
3382         gp := getg()
3383
3384         setMNoWB(&gp.m.curg.m, nil)
3385         setGNoWB(&gp.m.curg, nil)
3386 }
3387
3388 // checkTimers runs any timers for the P that are ready.
3389 // If now is not 0 it is the current time.
3390 // It returns the passed time or the current time if now was passed as 0.
3391 // and the time when the next timer should run or 0 if there is no next timer,
3392 // and reports whether it ran any timers.
3393 // If the time when the next timer should run is not 0,
3394 // it is always larger than the returned time.
3395 // We pass now in and out to avoid extra calls of nanotime.
3396 //
3397 //go:yeswritebarrierrec
3398 func checkTimers(pp *p, now int64) (rnow, pollUntil int64, ran bool) {
3399         // If it's not yet time for the first timer, or the first adjusted
3400         // timer, then there is nothing to do.
3401         next := pp.timer0When.Load()
3402         nextAdj := pp.timerModifiedEarliest.Load()
3403         if next == 0 || (nextAdj != 0 && nextAdj < next) {
3404                 next = nextAdj
3405         }
3406
3407         if next == 0 {
3408                 // No timers to run or adjust.
3409                 return now, 0, false
3410         }
3411
3412         if now == 0 {
3413                 now = nanotime()
3414         }
3415         if now < next {
3416                 // Next timer is not ready to run, but keep going
3417                 // if we would clear deleted timers.
3418                 // This corresponds to the condition below where
3419                 // we decide whether to call clearDeletedTimers.
3420                 if pp != getg().m.p.ptr() || int(pp.deletedTimers.Load()) <= int(pp.numTimers.Load()/4) {
3421                         return now, next, false
3422                 }
3423         }
3424
3425         lock(&pp.timersLock)
3426
3427         if len(pp.timers) > 0 {
3428                 adjusttimers(pp, now)
3429                 for len(pp.timers) > 0 {
3430                         // Note that runtimer may temporarily unlock
3431                         // pp.timersLock.
3432                         if tw := runtimer(pp, now); tw != 0 {
3433                                 if tw > 0 {
3434                                         pollUntil = tw
3435                                 }
3436                                 break
3437                         }
3438                         ran = true
3439                 }
3440         }
3441
3442         // If this is the local P, and there are a lot of deleted timers,
3443         // clear them out. We only do this for the local P to reduce
3444         // lock contention on timersLock.
3445         if pp == getg().m.p.ptr() && int(pp.deletedTimers.Load()) > len(pp.timers)/4 {
3446                 clearDeletedTimers(pp)
3447         }
3448
3449         unlock(&pp.timersLock)
3450
3451         return now, pollUntil, ran
3452 }
3453
3454 func parkunlock_c(gp *g, lock unsafe.Pointer) bool {
3455         unlock((*mutex)(lock))
3456         return true
3457 }
3458
3459 // park continuation on g0.
3460 func park_m(gp *g) {
3461         mp := getg().m
3462
3463         if trace.enabled {
3464                 traceGoPark(mp.waittraceev, mp.waittraceskip)
3465         }
3466
3467         // N.B. Not using casGToWaiting here because the waitreason is
3468         // set by park_m's caller.
3469         casgstatus(gp, _Grunning, _Gwaiting)
3470         dropg()
3471
3472         if fn := mp.waitunlockf; fn != nil {
3473                 ok := fn(gp, mp.waitlock)
3474                 mp.waitunlockf = nil
3475                 mp.waitlock = nil
3476                 if !ok {
3477                         if trace.enabled {
3478                                 traceGoUnpark(gp, 2)
3479                         }
3480                         casgstatus(gp, _Gwaiting, _Grunnable)
3481                         execute(gp, true) // Schedule it back, never returns.
3482                 }
3483         }
3484         schedule()
3485 }
3486
3487 func goschedImpl(gp *g) {
3488         status := readgstatus(gp)
3489         if status&^_Gscan != _Grunning {
3490                 dumpgstatus(gp)
3491                 throw("bad g status")
3492         }
3493         casgstatus(gp, _Grunning, _Grunnable)
3494         dropg()
3495         lock(&sched.lock)
3496         globrunqput(gp)
3497         unlock(&sched.lock)
3498
3499         schedule()
3500 }
3501
3502 // Gosched continuation on g0.
3503 func gosched_m(gp *g) {
3504         if trace.enabled {
3505                 traceGoSched()
3506         }
3507         goschedImpl(gp)
3508 }
3509
3510 // goschedguarded is a forbidden-states-avoided version of gosched_m
3511 func goschedguarded_m(gp *g) {
3512
3513         if !canPreemptM(gp.m) {
3514                 gogo(&gp.sched) // never return
3515         }
3516
3517         if trace.enabled {
3518                 traceGoSched()
3519         }
3520         goschedImpl(gp)
3521 }
3522
3523 func gopreempt_m(gp *g) {
3524         if trace.enabled {
3525                 traceGoPreempt()
3526         }
3527         goschedImpl(gp)
3528 }
3529
3530 // preemptPark parks gp and puts it in _Gpreempted.
3531 //
3532 //go:systemstack
3533 func preemptPark(gp *g) {
3534         if trace.enabled {
3535                 traceGoPark(traceEvGoBlock, 0)
3536         }
3537         status := readgstatus(gp)
3538         if status&^_Gscan != _Grunning {
3539                 dumpgstatus(gp)
3540                 throw("bad g status")
3541         }
3542
3543         if gp.asyncSafePoint {
3544                 // Double-check that async preemption does not
3545                 // happen in SPWRITE assembly functions.
3546                 // isAsyncSafePoint must exclude this case.
3547                 f := findfunc(gp.sched.pc)
3548                 if !f.valid() {
3549                         throw("preempt at unknown pc")
3550                 }
3551                 if f.flag&funcFlag_SPWRITE != 0 {
3552                         println("runtime: unexpected SPWRITE function", funcname(f), "in async preempt")
3553                         throw("preempt SPWRITE")
3554                 }
3555         }
3556
3557         // Transition from _Grunning to _Gscan|_Gpreempted. We can't
3558         // be in _Grunning when we dropg because then we'd be running
3559         // without an M, but the moment we're in _Gpreempted,
3560         // something could claim this G before we've fully cleaned it
3561         // up. Hence, we set the scan bit to lock down further
3562         // transitions until we can dropg.
3563         casGToPreemptScan(gp, _Grunning, _Gscan|_Gpreempted)
3564         dropg()
3565         casfrom_Gscanstatus(gp, _Gscan|_Gpreempted, _Gpreempted)
3566         schedule()
3567 }
3568
3569 // goyield is like Gosched, but it:
3570 // - emits a GoPreempt trace event instead of a GoSched trace event
3571 // - puts the current G on the runq of the current P instead of the globrunq
3572 func goyield() {
3573         checkTimeouts()
3574         mcall(goyield_m)
3575 }
3576
3577 func goyield_m(gp *g) {
3578         if trace.enabled {
3579                 traceGoPreempt()
3580         }
3581         pp := gp.m.p.ptr()
3582         casgstatus(gp, _Grunning, _Grunnable)
3583         dropg()
3584         runqput(pp, gp, false)
3585         schedule()
3586 }
3587
3588 // Finishes execution of the current goroutine.
3589 func goexit1() {
3590         if raceenabled {
3591                 racegoend()
3592         }
3593         if trace.enabled {
3594                 traceGoEnd()
3595         }
3596         mcall(goexit0)
3597 }
3598
3599 // goexit continuation on g0.
3600 func goexit0(gp *g) {
3601         mp := getg().m
3602         pp := mp.p.ptr()
3603
3604         casgstatus(gp, _Grunning, _Gdead)
3605         gcController.addScannableStack(pp, -int64(gp.stack.hi-gp.stack.lo))
3606         if isSystemGoroutine(gp, false) {
3607                 sched.ngsys.Add(-1)
3608         }
3609         gp.m = nil
3610         locked := gp.lockedm != 0
3611         gp.lockedm = 0
3612         mp.lockedg = 0
3613         gp.preemptStop = false
3614         gp.paniconfault = false
3615         gp._defer = nil // should be true already but just in case.
3616         gp._panic = nil // non-nil for Goexit during panic. points at stack-allocated data.
3617         gp.writebuf = nil
3618         gp.waitreason = waitReasonZero
3619         gp.param = nil
3620         gp.labels = nil
3621         gp.timer = nil
3622
3623         if gcBlackenEnabled != 0 && gp.gcAssistBytes > 0 {
3624                 // Flush assist credit to the global pool. This gives
3625                 // better information to pacing if the application is
3626                 // rapidly creating an exiting goroutines.
3627                 assistWorkPerByte := gcController.assistWorkPerByte.Load()
3628                 scanCredit := int64(assistWorkPerByte * float64(gp.gcAssistBytes))
3629                 gcController.bgScanCredit.Add(scanCredit)
3630                 gp.gcAssistBytes = 0
3631         }
3632
3633         dropg()
3634
3635         if GOARCH == "wasm" { // no threads yet on wasm
3636                 gfput(pp, gp)
3637                 schedule() // never returns
3638         }
3639
3640         if mp.lockedInt != 0 {
3641                 print("invalid m->lockedInt = ", mp.lockedInt, "\n")
3642                 throw("internal lockOSThread error")
3643         }
3644         gfput(pp, gp)
3645         if locked {
3646                 // The goroutine may have locked this thread because
3647                 // it put it in an unusual kernel state. Kill it
3648                 // rather than returning it to the thread pool.
3649
3650                 // Return to mstart, which will release the P and exit
3651                 // the thread.
3652                 if GOOS != "plan9" { // See golang.org/issue/22227.
3653                         gogo(&mp.g0.sched)
3654                 } else {
3655                         // Clear lockedExt on plan9 since we may end up re-using
3656                         // this thread.
3657                         mp.lockedExt = 0
3658                 }
3659         }
3660         schedule()
3661 }
3662
3663 // save updates getg().sched to refer to pc and sp so that a following
3664 // gogo will restore pc and sp.
3665 //
3666 // save must not have write barriers because invoking a write barrier
3667 // can clobber getg().sched.
3668 //
3669 //go:nosplit
3670 //go:nowritebarrierrec
3671 func save(pc, sp uintptr) {
3672         gp := getg()
3673
3674         if gp == gp.m.g0 || gp == gp.m.gsignal {
3675                 // m.g0.sched is special and must describe the context
3676                 // for exiting the thread. mstart1 writes to it directly.
3677                 // m.gsignal.sched should not be used at all.
3678                 // This check makes sure save calls do not accidentally
3679                 // run in contexts where they'd write to system g's.
3680                 throw("save on system g not allowed")
3681         }
3682
3683         gp.sched.pc = pc
3684         gp.sched.sp = sp
3685         gp.sched.lr = 0
3686         gp.sched.ret = 0
3687         // We need to ensure ctxt is zero, but can't have a write
3688         // barrier here. However, it should always already be zero.
3689         // Assert that.
3690         if gp.sched.ctxt != nil {
3691                 badctxt()
3692         }
3693 }
3694
3695 // The goroutine g is about to enter a system call.
3696 // Record that it's not using the cpu anymore.
3697 // This is called only from the go syscall library and cgocall,
3698 // not from the low-level system calls used by the runtime.
3699 //
3700 // Entersyscall cannot split the stack: the save must
3701 // make g->sched refer to the caller's stack segment, because
3702 // entersyscall is going to return immediately after.
3703 //
3704 // Nothing entersyscall calls can split the stack either.
3705 // We cannot safely move the stack during an active call to syscall,
3706 // because we do not know which of the uintptr arguments are
3707 // really pointers (back into the stack).
3708 // In practice, this means that we make the fast path run through
3709 // entersyscall doing no-split things, and the slow path has to use systemstack
3710 // to run bigger things on the system stack.
3711 //
3712 // reentersyscall is the entry point used by cgo callbacks, where explicitly
3713 // saved SP and PC are restored. This is needed when exitsyscall will be called
3714 // from a function further up in the call stack than the parent, as g->syscallsp
3715 // must always point to a valid stack frame. entersyscall below is the normal
3716 // entry point for syscalls, which obtains the SP and PC from the caller.
3717 //
3718 // Syscall tracing:
3719 // At the start of a syscall we emit traceGoSysCall to capture the stack trace.
3720 // If the syscall does not block, that is it, we do not emit any other events.
3721 // If the syscall blocks (that is, P is retaken), retaker emits traceGoSysBlock;
3722 // when syscall returns we emit traceGoSysExit and when the goroutine starts running
3723 // (potentially instantly, if exitsyscallfast returns true) we emit traceGoStart.
3724 // To ensure that traceGoSysExit is emitted strictly after traceGoSysBlock,
3725 // we remember current value of syscalltick in m (gp.m.syscalltick = gp.m.p.ptr().syscalltick),
3726 // whoever emits traceGoSysBlock increments p.syscalltick afterwards;
3727 // and we wait for the increment before emitting traceGoSysExit.
3728 // Note that the increment is done even if tracing is not enabled,
3729 // because tracing can be enabled in the middle of syscall. We don't want the wait to hang.
3730 //
3731 //go:nosplit
3732 func reentersyscall(pc, sp uintptr) {
3733         gp := getg()
3734
3735         // Disable preemption because during this function g is in Gsyscall status,
3736         // but can have inconsistent g->sched, do not let GC observe it.
3737         gp.m.locks++
3738
3739         // Entersyscall must not call any function that might split/grow the stack.
3740         // (See details in comment above.)
3741         // Catch calls that might, by replacing the stack guard with something that
3742         // will trip any stack check and leaving a flag to tell newstack to die.
3743         gp.stackguard0 = stackPreempt
3744         gp.throwsplit = true
3745
3746         // Leave SP around for GC and traceback.
3747         save(pc, sp)
3748         gp.syscallsp = sp
3749         gp.syscallpc = pc
3750         casgstatus(gp, _Grunning, _Gsyscall)
3751         if gp.syscallsp < gp.stack.lo || gp.stack.hi < gp.syscallsp {
3752                 systemstack(func() {
3753                         print("entersyscall inconsistent ", hex(gp.syscallsp), " [", hex(gp.stack.lo), ",", hex(gp.stack.hi), "]\n")
3754                         throw("entersyscall")
3755                 })
3756         }
3757
3758         if trace.enabled {
3759                 systemstack(traceGoSysCall)
3760                 // systemstack itself clobbers g.sched.{pc,sp} and we might
3761                 // need them later when the G is genuinely blocked in a
3762                 // syscall
3763                 save(pc, sp)
3764         }
3765
3766         if sched.sysmonwait.Load() {
3767                 systemstack(entersyscall_sysmon)
3768                 save(pc, sp)
3769         }
3770
3771         if gp.m.p.ptr().runSafePointFn != 0 {
3772                 // runSafePointFn may stack split if run on this stack
3773                 systemstack(runSafePointFn)
3774                 save(pc, sp)
3775         }
3776
3777         gp.m.syscalltick = gp.m.p.ptr().syscalltick
3778         gp.sysblocktraced = true
3779         pp := gp.m.p.ptr()
3780         pp.m = 0
3781         gp.m.oldp.set(pp)
3782         gp.m.p = 0
3783         atomic.Store(&pp.status, _Psyscall)
3784         if sched.gcwaiting.Load() {
3785                 systemstack(entersyscall_gcwait)
3786                 save(pc, sp)
3787         }
3788
3789         gp.m.locks--
3790 }
3791
3792 // Standard syscall entry used by the go syscall library and normal cgo calls.
3793 //
3794 // This is exported via linkname to assembly in the syscall package and x/sys.
3795 //
3796 //go:nosplit
3797 //go:linkname entersyscall
3798 func entersyscall() {
3799         reentersyscall(getcallerpc(), getcallersp())
3800 }
3801
3802 func entersyscall_sysmon() {
3803         lock(&sched.lock)
3804         if sched.sysmonwait.Load() {
3805                 sched.sysmonwait.Store(false)
3806                 notewakeup(&sched.sysmonnote)
3807         }
3808         unlock(&sched.lock)
3809 }
3810
3811 func entersyscall_gcwait() {
3812         gp := getg()
3813         pp := gp.m.oldp.ptr()
3814
3815         lock(&sched.lock)
3816         if sched.stopwait > 0 && atomic.Cas(&pp.status, _Psyscall, _Pgcstop) {
3817                 if trace.enabled {
3818                         traceGoSysBlock(pp)
3819                         traceProcStop(pp)
3820                 }
3821                 pp.syscalltick++
3822                 if sched.stopwait--; sched.stopwait == 0 {
3823                         notewakeup(&sched.stopnote)
3824                 }
3825         }
3826         unlock(&sched.lock)
3827 }
3828
3829 // The same as entersyscall(), but with a hint that the syscall is blocking.
3830 //
3831 //go:nosplit
3832 func entersyscallblock() {
3833         gp := getg()
3834
3835         gp.m.locks++ // see comment in entersyscall
3836         gp.throwsplit = true
3837         gp.stackguard0 = stackPreempt // see comment in entersyscall
3838         gp.m.syscalltick = gp.m.p.ptr().syscalltick
3839         gp.sysblocktraced = true
3840         gp.m.p.ptr().syscalltick++
3841
3842         // Leave SP around for GC and traceback.
3843         pc := getcallerpc()
3844         sp := getcallersp()
3845         save(pc, sp)
3846         gp.syscallsp = gp.sched.sp
3847         gp.syscallpc = gp.sched.pc
3848         if gp.syscallsp < gp.stack.lo || gp.stack.hi < gp.syscallsp {
3849                 sp1 := sp
3850                 sp2 := gp.sched.sp
3851                 sp3 := gp.syscallsp
3852                 systemstack(func() {
3853                         print("entersyscallblock inconsistent ", hex(sp1), " ", hex(sp2), " ", hex(sp3), " [", hex(gp.stack.lo), ",", hex(gp.stack.hi), "]\n")
3854                         throw("entersyscallblock")
3855                 })
3856         }
3857         casgstatus(gp, _Grunning, _Gsyscall)
3858         if gp.syscallsp < gp.stack.lo || gp.stack.hi < gp.syscallsp {
3859                 systemstack(func() {
3860                         print("entersyscallblock inconsistent ", hex(sp), " ", hex(gp.sched.sp), " ", hex(gp.syscallsp), " [", hex(gp.stack.lo), ",", hex(gp.stack.hi), "]\n")
3861                         throw("entersyscallblock")
3862                 })
3863         }
3864
3865         systemstack(entersyscallblock_handoff)
3866
3867         // Resave for traceback during blocked call.
3868         save(getcallerpc(), getcallersp())
3869
3870         gp.m.locks--
3871 }
3872
3873 func entersyscallblock_handoff() {
3874         if trace.enabled {
3875                 traceGoSysCall()
3876                 traceGoSysBlock(getg().m.p.ptr())
3877         }
3878         handoffp(releasep())
3879 }
3880
3881 // The goroutine g exited its system call.
3882 // Arrange for it to run on a cpu again.
3883 // This is called only from the go syscall library, not
3884 // from the low-level system calls used by the runtime.
3885 //
3886 // Write barriers are not allowed because our P may have been stolen.
3887 //
3888 // This is exported via linkname to assembly in the syscall package.
3889 //
3890 //go:nosplit
3891 //go:nowritebarrierrec
3892 //go:linkname exitsyscall
3893 func exitsyscall() {
3894         gp := getg()
3895
3896         gp.m.locks++ // see comment in entersyscall
3897         if getcallersp() > gp.syscallsp {
3898                 throw("exitsyscall: syscall frame is no longer valid")
3899         }
3900
3901         gp.waitsince = 0
3902         oldp := gp.m.oldp.ptr()
3903         gp.m.oldp = 0
3904         if exitsyscallfast(oldp) {
3905                 // When exitsyscallfast returns success, we have a P so can now use
3906                 // write barriers
3907                 if goroutineProfile.active {
3908                         // Make sure that gp has had its stack written out to the goroutine
3909                         // profile, exactly as it was when the goroutine profiler first
3910                         // stopped the world.
3911                         systemstack(func() {
3912                                 tryRecordGoroutineProfileWB(gp)
3913                         })
3914                 }
3915                 if trace.enabled {
3916                         if oldp != gp.m.p.ptr() || gp.m.syscalltick != gp.m.p.ptr().syscalltick {
3917                                 systemstack(traceGoStart)
3918                         }
3919                 }
3920                 // There's a cpu for us, so we can run.
3921                 gp.m.p.ptr().syscalltick++
3922                 // We need to cas the status and scan before resuming...
3923                 casgstatus(gp, _Gsyscall, _Grunning)
3924
3925                 // Garbage collector isn't running (since we are),
3926                 // so okay to clear syscallsp.
3927                 gp.syscallsp = 0
3928                 gp.m.locks--
3929                 if gp.preempt {
3930                         // restore the preemption request in case we've cleared it in newstack
3931                         gp.stackguard0 = stackPreempt
3932                 } else {
3933                         // otherwise restore the real _StackGuard, we've spoiled it in entersyscall/entersyscallblock
3934                         gp.stackguard0 = gp.stack.lo + _StackGuard
3935                 }
3936                 gp.throwsplit = false
3937
3938                 if sched.disable.user && !schedEnabled(gp) {
3939                         // Scheduling of this goroutine is disabled.
3940                         Gosched()
3941                 }
3942
3943                 return
3944         }
3945
3946         gp.sysexitticks = 0
3947         if trace.enabled {
3948                 // Wait till traceGoSysBlock event is emitted.
3949                 // This ensures consistency of the trace (the goroutine is started after it is blocked).
3950                 for oldp != nil && oldp.syscalltick == gp.m.syscalltick {
3951                         osyield()
3952                 }
3953                 // We can't trace syscall exit right now because we don't have a P.
3954                 // Tracing code can invoke write barriers that cannot run without a P.
3955                 // So instead we remember the syscall exit time and emit the event
3956                 // in execute when we have a P.
3957                 gp.sysexitticks = cputicks()
3958         }
3959
3960         gp.m.locks--
3961
3962         // Call the scheduler.
3963         mcall(exitsyscall0)
3964
3965         // Scheduler returned, so we're allowed to run now.
3966         // Delete the syscallsp information that we left for
3967         // the garbage collector during the system call.
3968         // Must wait until now because until gosched returns
3969         // we don't know for sure that the garbage collector
3970         // is not running.
3971         gp.syscallsp = 0
3972         gp.m.p.ptr().syscalltick++
3973         gp.throwsplit = false
3974 }
3975
3976 //go:nosplit
3977 func exitsyscallfast(oldp *p) bool {
3978         gp := getg()
3979
3980         // Freezetheworld sets stopwait but does not retake P's.
3981         if sched.stopwait == freezeStopWait {
3982                 return false
3983         }
3984
3985         // Try to re-acquire the last P.
3986         if oldp != nil && oldp.status == _Psyscall && atomic.Cas(&oldp.status, _Psyscall, _Pidle) {
3987                 // There's a cpu for us, so we can run.
3988                 wirep(oldp)
3989                 exitsyscallfast_reacquired()
3990                 return true
3991         }
3992
3993         // Try to get any other idle P.
3994         if sched.pidle != 0 {
3995                 var ok bool
3996                 systemstack(func() {
3997                         ok = exitsyscallfast_pidle()
3998                         if ok && trace.enabled {
3999                                 if oldp != nil {
4000                                         // Wait till traceGoSysBlock event is emitted.
4001                                         // This ensures consistency of the trace (the goroutine is started after it is blocked).
4002                                         for oldp.syscalltick == gp.m.syscalltick {
4003                                                 osyield()
4004                                         }
4005                                 }
4006                                 traceGoSysExit(0)
4007                         }
4008                 })
4009                 if ok {
4010                         return true
4011                 }
4012         }
4013         return false
4014 }
4015
4016 // exitsyscallfast_reacquired is the exitsyscall path on which this G
4017 // has successfully reacquired the P it was running on before the
4018 // syscall.
4019 //
4020 //go:nosplit
4021 func exitsyscallfast_reacquired() {
4022         gp := getg()
4023         if gp.m.syscalltick != gp.m.p.ptr().syscalltick {
4024                 if trace.enabled {
4025                         // The p was retaken and then enter into syscall again (since gp.m.syscalltick has changed).
4026                         // traceGoSysBlock for this syscall was already emitted,
4027                         // but here we effectively retake the p from the new syscall running on the same p.
4028                         systemstack(func() {
4029                                 // Denote blocking of the new syscall.
4030                                 traceGoSysBlock(gp.m.p.ptr())
4031                                 // Denote completion of the current syscall.
4032                                 traceGoSysExit(0)
4033                         })
4034                 }
4035                 gp.m.p.ptr().syscalltick++
4036         }
4037 }
4038
4039 func exitsyscallfast_pidle() bool {
4040         lock(&sched.lock)
4041         pp, _ := pidleget(0)
4042         if pp != nil && sched.sysmonwait.Load() {
4043                 sched.sysmonwait.Store(false)
4044                 notewakeup(&sched.sysmonnote)
4045         }
4046         unlock(&sched.lock)
4047         if pp != nil {
4048                 acquirep(pp)
4049                 return true
4050         }
4051         return false
4052 }
4053
4054 // exitsyscall slow path on g0.
4055 // Failed to acquire P, enqueue gp as runnable.
4056 //
4057 // Called via mcall, so gp is the calling g from this M.
4058 //
4059 //go:nowritebarrierrec
4060 func exitsyscall0(gp *g) {
4061         casgstatus(gp, _Gsyscall, _Grunnable)
4062         dropg()
4063         lock(&sched.lock)
4064         var pp *p
4065         if schedEnabled(gp) {
4066                 pp, _ = pidleget(0)
4067         }
4068         var locked bool
4069         if pp == nil {
4070                 globrunqput(gp)
4071
4072                 // Below, we stoplockedm if gp is locked. globrunqput releases
4073                 // ownership of gp, so we must check if gp is locked prior to
4074                 // committing the release by unlocking sched.lock, otherwise we
4075                 // could race with another M transitioning gp from unlocked to
4076                 // locked.
4077                 locked = gp.lockedm != 0
4078         } else if sched.sysmonwait.Load() {
4079                 sched.sysmonwait.Store(false)
4080                 notewakeup(&sched.sysmonnote)
4081         }
4082         unlock(&sched.lock)
4083         if pp != nil {
4084                 acquirep(pp)
4085                 execute(gp, false) // Never returns.
4086         }
4087         if locked {
4088                 // Wait until another thread schedules gp and so m again.
4089                 //
4090                 // N.B. lockedm must be this M, as this g was running on this M
4091                 // before entersyscall.
4092                 stoplockedm()
4093                 execute(gp, false) // Never returns.
4094         }
4095         stopm()
4096         schedule() // Never returns.
4097 }
4098
4099 // Called from syscall package before fork.
4100 //
4101 //go:linkname syscall_runtime_BeforeFork syscall.runtime_BeforeFork
4102 //go:nosplit
4103 func syscall_runtime_BeforeFork() {
4104         gp := getg().m.curg
4105
4106         // Block signals during a fork, so that the child does not run
4107         // a signal handler before exec if a signal is sent to the process
4108         // group. See issue #18600.
4109         gp.m.locks++
4110         sigsave(&gp.m.sigmask)
4111         sigblock(false)
4112
4113         // This function is called before fork in syscall package.
4114         // Code between fork and exec must not allocate memory nor even try to grow stack.
4115         // Here we spoil g->_StackGuard to reliably detect any attempts to grow stack.
4116         // runtime_AfterFork will undo this in parent process, but not in child.
4117         gp.stackguard0 = stackFork
4118 }
4119
4120 // Called from syscall package after fork in parent.
4121 //
4122 //go:linkname syscall_runtime_AfterFork syscall.runtime_AfterFork
4123 //go:nosplit
4124 func syscall_runtime_AfterFork() {
4125         gp := getg().m.curg
4126
4127         // See the comments in beforefork.
4128         gp.stackguard0 = gp.stack.lo + _StackGuard
4129
4130         msigrestore(gp.m.sigmask)
4131
4132         gp.m.locks--
4133 }
4134
4135 // inForkedChild is true while manipulating signals in the child process.
4136 // This is used to avoid calling libc functions in case we are using vfork.
4137 var inForkedChild bool
4138
4139 // Called from syscall package after fork in child.
4140 // It resets non-sigignored signals to the default handler, and
4141 // restores the signal mask in preparation for the exec.
4142 //
4143 // Because this might be called during a vfork, and therefore may be
4144 // temporarily sharing address space with the parent process, this must
4145 // not change any global variables or calling into C code that may do so.
4146 //
4147 //go:linkname syscall_runtime_AfterForkInChild syscall.runtime_AfterForkInChild
4148 //go:nosplit
4149 //go:nowritebarrierrec
4150 func syscall_runtime_AfterForkInChild() {
4151         // It's OK to change the global variable inForkedChild here
4152         // because we are going to change it back. There is no race here,
4153         // because if we are sharing address space with the parent process,
4154         // then the parent process can not be running concurrently.
4155         inForkedChild = true
4156
4157         clearSignalHandlers()
4158
4159         // When we are the child we are the only thread running,
4160         // so we know that nothing else has changed gp.m.sigmask.
4161         msigrestore(getg().m.sigmask)
4162
4163         inForkedChild = false
4164 }
4165
4166 // pendingPreemptSignals is the number of preemption signals
4167 // that have been sent but not received. This is only used on Darwin.
4168 // For #41702.
4169 var pendingPreemptSignals atomic.Int32
4170
4171 // Called from syscall package before Exec.
4172 //
4173 //go:linkname syscall_runtime_BeforeExec syscall.runtime_BeforeExec
4174 func syscall_runtime_BeforeExec() {
4175         // Prevent thread creation during exec.
4176         execLock.lock()
4177
4178         // On Darwin, wait for all pending preemption signals to
4179         // be received. See issue #41702.
4180         if GOOS == "darwin" || GOOS == "ios" {
4181                 for pendingPreemptSignals.Load() > 0 {
4182                         osyield()
4183                 }
4184         }
4185 }
4186
4187 // Called from syscall package after Exec.
4188 //
4189 //go:linkname syscall_runtime_AfterExec syscall.runtime_AfterExec
4190 func syscall_runtime_AfterExec() {
4191         execLock.unlock()
4192 }
4193
4194 // Allocate a new g, with a stack big enough for stacksize bytes.
4195 func malg(stacksize int32) *g {
4196         newg := new(g)
4197         if stacksize >= 0 {
4198                 stacksize = round2(_StackSystem + stacksize)
4199                 systemstack(func() {
4200                         newg.stack = stackalloc(uint32(stacksize))
4201                 })
4202                 newg.stackguard0 = newg.stack.lo + _StackGuard
4203                 newg.stackguard1 = ^uintptr(0)
4204                 // Clear the bottom word of the stack. We record g
4205                 // there on gsignal stack during VDSO on ARM and ARM64.
4206                 *(*uintptr)(unsafe.Pointer(newg.stack.lo)) = 0
4207         }
4208         return newg
4209 }
4210
4211 // Create a new g running fn.
4212 // Put it on the queue of g's waiting to run.
4213 // The compiler turns a go statement into a call to this.
4214 func newproc(fn *funcval) {
4215         gp := getg()
4216         pc := getcallerpc()
4217         systemstack(func() {
4218                 newg := newproc1(fn, gp, pc)
4219
4220                 pp := getg().m.p.ptr()
4221                 runqput(pp, newg, true)
4222
4223                 if mainStarted {
4224                         wakep()
4225                 }
4226         })
4227 }
4228
4229 // Create a new g in state _Grunnable, starting at fn. callerpc is the
4230 // address of the go statement that created this. The caller is responsible
4231 // for adding the new g to the scheduler.
4232 func newproc1(fn *funcval, callergp *g, callerpc uintptr) *g {
4233         if fn == nil {
4234                 fatal("go of nil func value")
4235         }
4236
4237         mp := acquirem() // disable preemption because we hold M and P in local vars.
4238         pp := mp.p.ptr()
4239         newg := gfget(pp)
4240         if newg == nil {
4241                 newg = malg(_StackMin)
4242                 casgstatus(newg, _Gidle, _Gdead)
4243                 allgadd(newg) // publishes with a g->status of Gdead so GC scanner doesn't look at uninitialized stack.
4244         }
4245         if newg.stack.hi == 0 {
4246                 throw("newproc1: newg missing stack")
4247         }
4248
4249         if readgstatus(newg) != _Gdead {
4250                 throw("newproc1: new g is not Gdead")
4251         }
4252
4253         totalSize := uintptr(4*goarch.PtrSize + sys.MinFrameSize) // extra space in case of reads slightly beyond frame
4254         totalSize = alignUp(totalSize, sys.StackAlign)
4255         sp := newg.stack.hi - totalSize
4256         spArg := sp
4257         if usesLR {
4258                 // caller's LR
4259                 *(*uintptr)(unsafe.Pointer(sp)) = 0
4260                 prepGoExitFrame(sp)
4261                 spArg += sys.MinFrameSize
4262         }
4263
4264         memclrNoHeapPointers(unsafe.Pointer(&newg.sched), unsafe.Sizeof(newg.sched))
4265         newg.sched.sp = sp
4266         newg.stktopsp = sp
4267         newg.sched.pc = abi.FuncPCABI0(goexit) + sys.PCQuantum // +PCQuantum so that previous instruction is in same function
4268         newg.sched.g = guintptr(unsafe.Pointer(newg))
4269         gostartcallfn(&newg.sched, fn)
4270         newg.gopc = callerpc
4271         newg.ancestors = saveAncestors(callergp)
4272         newg.startpc = fn.fn
4273         if isSystemGoroutine(newg, false) {
4274                 sched.ngsys.Add(1)
4275         } else {
4276                 // Only user goroutines inherit pprof labels.
4277                 if mp.curg != nil {
4278                         newg.labels = mp.curg.labels
4279                 }
4280                 if goroutineProfile.active {
4281                         // A concurrent goroutine profile is running. It should include
4282                         // exactly the set of goroutines that were alive when the goroutine
4283                         // profiler first stopped the world. That does not include newg, so
4284                         // mark it as not needing a profile before transitioning it from
4285                         // _Gdead.
4286                         newg.goroutineProfiled.Store(goroutineProfileSatisfied)
4287                 }
4288         }
4289         // Track initial transition?
4290         newg.trackingSeq = uint8(fastrand())
4291         if newg.trackingSeq%gTrackingPeriod == 0 {
4292                 newg.tracking = true
4293         }
4294         casgstatus(newg, _Gdead, _Grunnable)
4295         gcController.addScannableStack(pp, int64(newg.stack.hi-newg.stack.lo))
4296
4297         if pp.goidcache == pp.goidcacheend {
4298                 // Sched.goidgen is the last allocated id,
4299                 // this batch must be [sched.goidgen+1, sched.goidgen+GoidCacheBatch].
4300                 // At startup sched.goidgen=0, so main goroutine receives goid=1.
4301                 pp.goidcache = sched.goidgen.Add(_GoidCacheBatch)
4302                 pp.goidcache -= _GoidCacheBatch - 1
4303                 pp.goidcacheend = pp.goidcache + _GoidCacheBatch
4304         }
4305         newg.goid = pp.goidcache
4306         pp.goidcache++
4307         if raceenabled {
4308                 newg.racectx = racegostart(callerpc)
4309                 if newg.labels != nil {
4310                         // See note in proflabel.go on labelSync's role in synchronizing
4311                         // with the reads in the signal handler.
4312                         racereleasemergeg(newg, unsafe.Pointer(&labelSync))
4313                 }
4314         }
4315         if trace.enabled {
4316                 traceGoCreate(newg, newg.startpc)
4317         }
4318         releasem(mp)
4319
4320         return newg
4321 }
4322
4323 // saveAncestors copies previous ancestors of the given caller g and
4324 // includes infor for the current caller into a new set of tracebacks for
4325 // a g being created.
4326 func saveAncestors(callergp *g) *[]ancestorInfo {
4327         // Copy all prior info, except for the root goroutine (goid 0).
4328         if debug.tracebackancestors <= 0 || callergp.goid == 0 {
4329                 return nil
4330         }
4331         var callerAncestors []ancestorInfo
4332         if callergp.ancestors != nil {
4333                 callerAncestors = *callergp.ancestors
4334         }
4335         n := int32(len(callerAncestors)) + 1
4336         if n > debug.tracebackancestors {
4337                 n = debug.tracebackancestors
4338         }
4339         ancestors := make([]ancestorInfo, n)
4340         copy(ancestors[1:], callerAncestors)
4341
4342         var pcs [_TracebackMaxFrames]uintptr
4343         npcs := gcallers(callergp, 0, pcs[:])
4344         ipcs := make([]uintptr, npcs)
4345         copy(ipcs, pcs[:])
4346         ancestors[0] = ancestorInfo{
4347                 pcs:  ipcs,
4348                 goid: callergp.goid,
4349                 gopc: callergp.gopc,
4350         }
4351
4352         ancestorsp := new([]ancestorInfo)
4353         *ancestorsp = ancestors
4354         return ancestorsp
4355 }
4356
4357 // Put on gfree list.
4358 // If local list is too long, transfer a batch to the global list.
4359 func gfput(pp *p, gp *g) {
4360         if readgstatus(gp) != _Gdead {
4361                 throw("gfput: bad status (not Gdead)")
4362         }
4363
4364         stksize := gp.stack.hi - gp.stack.lo
4365
4366         if stksize != uintptr(startingStackSize) {
4367                 // non-standard stack size - free it.
4368                 stackfree(gp.stack)
4369                 gp.stack.lo = 0
4370                 gp.stack.hi = 0
4371                 gp.stackguard0 = 0
4372         }
4373
4374         pp.gFree.push(gp)
4375         pp.gFree.n++
4376         if pp.gFree.n >= 64 {
4377                 var (
4378                         inc      int32
4379                         stackQ   gQueue
4380                         noStackQ gQueue
4381                 )
4382                 for pp.gFree.n >= 32 {
4383                         gp := pp.gFree.pop()
4384                         pp.gFree.n--
4385                         if gp.stack.lo == 0 {
4386                                 noStackQ.push(gp)
4387                         } else {
4388                                 stackQ.push(gp)
4389                         }
4390                         inc++
4391                 }
4392                 lock(&sched.gFree.lock)
4393                 sched.gFree.noStack.pushAll(noStackQ)
4394                 sched.gFree.stack.pushAll(stackQ)
4395                 sched.gFree.n += inc
4396                 unlock(&sched.gFree.lock)
4397         }
4398 }
4399
4400 // Get from gfree list.
4401 // If local list is empty, grab a batch from global list.
4402 func gfget(pp *p) *g {
4403 retry:
4404         if pp.gFree.empty() && (!sched.gFree.stack.empty() || !sched.gFree.noStack.empty()) {
4405                 lock(&sched.gFree.lock)
4406                 // Move a batch of free Gs to the P.
4407                 for pp.gFree.n < 32 {
4408                         // Prefer Gs with stacks.
4409                         gp := sched.gFree.stack.pop()
4410                         if gp == nil {
4411                                 gp = sched.gFree.noStack.pop()
4412                                 if gp == nil {
4413                                         break
4414                                 }
4415                         }
4416                         sched.gFree.n--
4417                         pp.gFree.push(gp)
4418                         pp.gFree.n++
4419                 }
4420                 unlock(&sched.gFree.lock)
4421                 goto retry
4422         }
4423         gp := pp.gFree.pop()
4424         if gp == nil {
4425                 return nil
4426         }
4427         pp.gFree.n--
4428         if gp.stack.lo != 0 && gp.stack.hi-gp.stack.lo != uintptr(startingStackSize) {
4429                 // Deallocate old stack. We kept it in gfput because it was the
4430                 // right size when the goroutine was put on the free list, but
4431                 // the right size has changed since then.
4432                 systemstack(func() {
4433                         stackfree(gp.stack)
4434                         gp.stack.lo = 0
4435                         gp.stack.hi = 0
4436                         gp.stackguard0 = 0
4437                 })
4438         }
4439         if gp.stack.lo == 0 {
4440                 // Stack was deallocated in gfput or just above. Allocate a new one.
4441                 systemstack(func() {
4442                         gp.stack = stackalloc(startingStackSize)
4443                 })
4444                 gp.stackguard0 = gp.stack.lo + _StackGuard
4445         } else {
4446                 if raceenabled {
4447                         racemalloc(unsafe.Pointer(gp.stack.lo), gp.stack.hi-gp.stack.lo)
4448                 }
4449                 if msanenabled {
4450                         msanmalloc(unsafe.Pointer(gp.stack.lo), gp.stack.hi-gp.stack.lo)
4451                 }
4452                 if asanenabled {
4453                         asanunpoison(unsafe.Pointer(gp.stack.lo), gp.stack.hi-gp.stack.lo)
4454                 }
4455         }
4456         return gp
4457 }
4458
4459 // Purge all cached G's from gfree list to the global list.
4460 func gfpurge(pp *p) {
4461         var (
4462                 inc      int32
4463                 stackQ   gQueue
4464                 noStackQ gQueue
4465         )
4466         for !pp.gFree.empty() {
4467                 gp := pp.gFree.pop()
4468                 pp.gFree.n--
4469                 if gp.stack.lo == 0 {
4470                         noStackQ.push(gp)
4471                 } else {
4472                         stackQ.push(gp)
4473                 }
4474                 inc++
4475         }
4476         lock(&sched.gFree.lock)
4477         sched.gFree.noStack.pushAll(noStackQ)
4478         sched.gFree.stack.pushAll(stackQ)
4479         sched.gFree.n += inc
4480         unlock(&sched.gFree.lock)
4481 }
4482
4483 // Breakpoint executes a breakpoint trap.
4484 func Breakpoint() {
4485         breakpoint()
4486 }
4487
4488 // dolockOSThread is called by LockOSThread and lockOSThread below
4489 // after they modify m.locked. Do not allow preemption during this call,
4490 // or else the m might be different in this function than in the caller.
4491 //
4492 //go:nosplit
4493 func dolockOSThread() {
4494         if GOARCH == "wasm" {
4495                 return // no threads on wasm yet
4496         }
4497         gp := getg()
4498         gp.m.lockedg.set(gp)
4499         gp.lockedm.set(gp.m)
4500 }
4501
4502 //go:nosplit
4503
4504 // LockOSThread wires the calling goroutine to its current operating system thread.
4505 // The calling goroutine will always execute in that thread,
4506 // and no other goroutine will execute in it,
4507 // until the calling goroutine has made as many calls to
4508 // UnlockOSThread as to LockOSThread.
4509 // If the calling goroutine exits without unlocking the thread,
4510 // the thread will be terminated.
4511 //
4512 // All init functions are run on the startup thread. Calling LockOSThread
4513 // from an init function will cause the main function to be invoked on
4514 // that thread.
4515 //
4516 // A goroutine should call LockOSThread before calling OS services or
4517 // non-Go library functions that depend on per-thread state.
4518 func LockOSThread() {
4519         if atomic.Load(&newmHandoff.haveTemplateThread) == 0 && GOOS != "plan9" {
4520                 // If we need to start a new thread from the locked
4521                 // thread, we need the template thread. Start it now
4522                 // while we're in a known-good state.
4523                 startTemplateThread()
4524         }
4525         gp := getg()
4526         gp.m.lockedExt++
4527         if gp.m.lockedExt == 0 {
4528                 gp.m.lockedExt--
4529                 panic("LockOSThread nesting overflow")
4530         }
4531         dolockOSThread()
4532 }
4533
4534 //go:nosplit
4535 func lockOSThread() {
4536         getg().m.lockedInt++
4537         dolockOSThread()
4538 }
4539
4540 // dounlockOSThread is called by UnlockOSThread and unlockOSThread below
4541 // after they update m->locked. Do not allow preemption during this call,
4542 // or else the m might be in different in this function than in the caller.
4543 //
4544 //go:nosplit
4545 func dounlockOSThread() {
4546         if GOARCH == "wasm" {
4547                 return // no threads on wasm yet
4548         }
4549         gp := getg()
4550         if gp.m.lockedInt != 0 || gp.m.lockedExt != 0 {
4551                 return
4552         }
4553         gp.m.lockedg = 0
4554         gp.lockedm = 0
4555 }
4556
4557 //go:nosplit
4558
4559 // UnlockOSThread undoes an earlier call to LockOSThread.
4560 // If this drops the number of active LockOSThread calls on the
4561 // calling goroutine to zero, it unwires the calling goroutine from
4562 // its fixed operating system thread.
4563 // If there are no active LockOSThread calls, this is a no-op.
4564 //
4565 // Before calling UnlockOSThread, the caller must ensure that the OS
4566 // thread is suitable for running other goroutines. If the caller made
4567 // any permanent changes to the state of the thread that would affect
4568 // other goroutines, it should not call this function and thus leave
4569 // the goroutine locked to the OS thread until the goroutine (and
4570 // hence the thread) exits.
4571 func UnlockOSThread() {
4572         gp := getg()
4573         if gp.m.lockedExt == 0 {
4574                 return
4575         }
4576         gp.m.lockedExt--
4577         dounlockOSThread()
4578 }
4579
4580 //go:nosplit
4581 func unlockOSThread() {
4582         gp := getg()
4583         if gp.m.lockedInt == 0 {
4584                 systemstack(badunlockosthread)
4585         }
4586         gp.m.lockedInt--
4587         dounlockOSThread()
4588 }
4589
4590 func badunlockosthread() {
4591         throw("runtime: internal error: misuse of lockOSThread/unlockOSThread")
4592 }
4593
4594 func gcount() int32 {
4595         n := int32(atomic.Loaduintptr(&allglen)) - sched.gFree.n - sched.ngsys.Load()
4596         for _, pp := range allp {
4597                 n -= pp.gFree.n
4598         }
4599
4600         // All these variables can be changed concurrently, so the result can be inconsistent.
4601         // But at least the current goroutine is running.
4602         if n < 1 {
4603                 n = 1
4604         }
4605         return n
4606 }
4607
4608 func mcount() int32 {
4609         return int32(sched.mnext - sched.nmfreed)
4610 }
4611
4612 var prof struct {
4613         signalLock atomic.Uint32
4614
4615         // Must hold signalLock to write. Reads may be lock-free, but
4616         // signalLock should be taken to synchronize with changes.
4617         hz atomic.Int32
4618 }
4619
4620 func _System()                    { _System() }
4621 func _ExternalCode()              { _ExternalCode() }
4622 func _LostExternalCode()          { _LostExternalCode() }
4623 func _GC()                        { _GC() }
4624 func _LostSIGPROFDuringAtomic64() { _LostSIGPROFDuringAtomic64() }
4625 func _VDSO()                      { _VDSO() }
4626
4627 // Called if we receive a SIGPROF signal.
4628 // Called by the signal handler, may run during STW.
4629 //
4630 //go:nowritebarrierrec
4631 func sigprof(pc, sp, lr uintptr, gp *g, mp *m) {
4632         if prof.hz.Load() == 0 {
4633                 return
4634         }
4635
4636         // If mp.profilehz is 0, then profiling is not enabled for this thread.
4637         // We must check this to avoid a deadlock between setcpuprofilerate
4638         // and the call to cpuprof.add, below.
4639         if mp != nil && mp.profilehz == 0 {
4640                 return
4641         }
4642
4643         // On mips{,le}/arm, 64bit atomics are emulated with spinlocks, in
4644         // runtime/internal/atomic. If SIGPROF arrives while the program is inside
4645         // the critical section, it creates a deadlock (when writing the sample).
4646         // As a workaround, create a counter of SIGPROFs while in critical section
4647         // to store the count, and pass it to sigprof.add() later when SIGPROF is
4648         // received from somewhere else (with _LostSIGPROFDuringAtomic64 as pc).
4649         if GOARCH == "mips" || GOARCH == "mipsle" || GOARCH == "arm" {
4650                 if f := findfunc(pc); f.valid() {
4651                         if hasPrefix(funcname(f), "runtime/internal/atomic") {
4652                                 cpuprof.lostAtomic++
4653                                 return
4654                         }
4655                 }
4656                 if GOARCH == "arm" && goarm < 7 && GOOS == "linux" && pc&0xffff0000 == 0xffff0000 {
4657                         // runtime/internal/atomic functions call into kernel
4658                         // helpers on arm < 7. See
4659                         // runtime/internal/atomic/sys_linux_arm.s.
4660                         cpuprof.lostAtomic++
4661                         return
4662                 }
4663         }
4664
4665         // Profiling runs concurrently with GC, so it must not allocate.
4666         // Set a trap in case the code does allocate.
4667         // Note that on windows, one thread takes profiles of all the
4668         // other threads, so mp is usually not getg().m.
4669         // In fact mp may not even be stopped.
4670         // See golang.org/issue/17165.
4671         getg().m.mallocing++
4672
4673         var stk [maxCPUProfStack]uintptr
4674         n := 0
4675         if mp.ncgo > 0 && mp.curg != nil && mp.curg.syscallpc != 0 && mp.curg.syscallsp != 0 {
4676                 cgoOff := 0
4677                 // Check cgoCallersUse to make sure that we are not
4678                 // interrupting other code that is fiddling with
4679                 // cgoCallers.  We are running in a signal handler
4680                 // with all signals blocked, so we don't have to worry
4681                 // about any other code interrupting us.
4682                 if mp.cgoCallersUse.Load() == 0 && mp.cgoCallers != nil && mp.cgoCallers[0] != 0 {
4683                         for cgoOff < len(mp.cgoCallers) && mp.cgoCallers[cgoOff] != 0 {
4684                                 cgoOff++
4685                         }
4686                         copy(stk[:], mp.cgoCallers[:cgoOff])
4687                         mp.cgoCallers[0] = 0
4688                 }
4689
4690                 // Collect Go stack that leads to the cgo call.
4691                 n = gentraceback(mp.curg.syscallpc, mp.curg.syscallsp, 0, mp.curg, 0, &stk[cgoOff], len(stk)-cgoOff, nil, nil, 0)
4692                 if n > 0 {
4693                         n += cgoOff
4694                 }
4695         } else {
4696                 n = gentraceback(pc, sp, lr, gp, 0, &stk[0], len(stk), nil, nil, _TraceTrap|_TraceJumpStack)
4697         }
4698
4699         if n <= 0 {
4700                 // Normal traceback is impossible or has failed.
4701                 // See if it falls into several common cases.
4702                 n = 0
4703                 if usesLibcall() && mp.libcallg != 0 && mp.libcallpc != 0 && mp.libcallsp != 0 {
4704                         // Libcall, i.e. runtime syscall on windows.
4705                         // Collect Go stack that leads to the call.
4706                         n = gentraceback(mp.libcallpc, mp.libcallsp, 0, mp.libcallg.ptr(), 0, &stk[0], len(stk), nil, nil, 0)
4707                 }
4708                 if n == 0 && mp != nil && mp.vdsoSP != 0 {
4709                         n = gentraceback(mp.vdsoPC, mp.vdsoSP, 0, gp, 0, &stk[0], len(stk), nil, nil, _TraceTrap|_TraceJumpStack)
4710                 }
4711                 if n == 0 {
4712                         // If all of the above has failed, account it against abstract "System" or "GC".
4713                         n = 2
4714                         if inVDSOPage(pc) {
4715                                 pc = abi.FuncPCABIInternal(_VDSO) + sys.PCQuantum
4716                         } else if pc > firstmoduledata.etext {
4717                                 // "ExternalCode" is better than "etext".
4718                                 pc = abi.FuncPCABIInternal(_ExternalCode) + sys.PCQuantum
4719                         }
4720                         stk[0] = pc
4721                         if mp.preemptoff != "" {
4722                                 stk[1] = abi.FuncPCABIInternal(_GC) + sys.PCQuantum
4723                         } else {
4724                                 stk[1] = abi.FuncPCABIInternal(_System) + sys.PCQuantum
4725                         }
4726                 }
4727         }
4728
4729         if prof.hz.Load() != 0 {
4730                 // Note: it can happen on Windows that we interrupted a system thread
4731                 // with no g, so gp could nil. The other nil checks are done out of
4732                 // caution, but not expected to be nil in practice.
4733                 var tagPtr *unsafe.Pointer
4734                 if gp != nil && gp.m != nil && gp.m.curg != nil {
4735                         tagPtr = &gp.m.curg.labels
4736                 }
4737                 cpuprof.add(tagPtr, stk[:n])
4738
4739                 gprof := gp
4740                 var pp *p
4741                 if gp != nil && gp.m != nil {
4742                         if gp.m.curg != nil {
4743                                 gprof = gp.m.curg
4744                         }
4745                         pp = gp.m.p.ptr()
4746                 }
4747                 traceCPUSample(gprof, pp, stk[:n])
4748         }
4749         getg().m.mallocing--
4750 }
4751
4752 // setcpuprofilerate sets the CPU profiling rate to hz times per second.
4753 // If hz <= 0, setcpuprofilerate turns off CPU profiling.
4754 func setcpuprofilerate(hz int32) {
4755         // Force sane arguments.
4756         if hz < 0 {
4757                 hz = 0
4758         }
4759
4760         // Disable preemption, otherwise we can be rescheduled to another thread
4761         // that has profiling enabled.
4762         gp := getg()
4763         gp.m.locks++
4764
4765         // Stop profiler on this thread so that it is safe to lock prof.
4766         // if a profiling signal came in while we had prof locked,
4767         // it would deadlock.
4768         setThreadCPUProfiler(0)
4769
4770         for !prof.signalLock.CompareAndSwap(0, 1) {
4771                 osyield()
4772         }
4773         if prof.hz.Load() != hz {
4774                 setProcessCPUProfiler(hz)
4775                 prof.hz.Store(hz)
4776         }
4777         prof.signalLock.Store(0)
4778
4779         lock(&sched.lock)
4780         sched.profilehz = hz
4781         unlock(&sched.lock)
4782
4783         if hz != 0 {
4784                 setThreadCPUProfiler(hz)
4785         }
4786
4787         gp.m.locks--
4788 }
4789
4790 // init initializes pp, which may be a freshly allocated p or a
4791 // previously destroyed p, and transitions it to status _Pgcstop.
4792 func (pp *p) init(id int32) {
4793         pp.id = id
4794         pp.status = _Pgcstop
4795         pp.sudogcache = pp.sudogbuf[:0]
4796         pp.deferpool = pp.deferpoolbuf[:0]
4797         pp.wbBuf.reset()
4798         if pp.mcache == nil {
4799                 if id == 0 {
4800                         if mcache0 == nil {
4801                                 throw("missing mcache?")
4802                         }
4803                         // Use the bootstrap mcache0. Only one P will get
4804                         // mcache0: the one with ID 0.
4805                         pp.mcache = mcache0
4806                 } else {
4807                         pp.mcache = allocmcache()
4808                 }
4809         }
4810         if raceenabled && pp.raceprocctx == 0 {
4811                 if id == 0 {
4812                         pp.raceprocctx = raceprocctx0
4813                         raceprocctx0 = 0 // bootstrap
4814                 } else {
4815                         pp.raceprocctx = raceproccreate()
4816                 }
4817         }
4818         lockInit(&pp.timersLock, lockRankTimers)
4819
4820         // This P may get timers when it starts running. Set the mask here
4821         // since the P may not go through pidleget (notably P 0 on startup).
4822         timerpMask.set(id)
4823         // Similarly, we may not go through pidleget before this P starts
4824         // running if it is P 0 on startup.
4825         idlepMask.clear(id)
4826 }
4827
4828 // destroy releases all of the resources associated with pp and
4829 // transitions it to status _Pdead.
4830 //
4831 // sched.lock must be held and the world must be stopped.
4832 func (pp *p) destroy() {
4833         assertLockHeld(&sched.lock)
4834         assertWorldStopped()
4835
4836         // Move all runnable goroutines to the global queue
4837         for pp.runqhead != pp.runqtail {
4838                 // Pop from tail of local queue
4839                 pp.runqtail--
4840                 gp := pp.runq[pp.runqtail%uint32(len(pp.runq))].ptr()
4841                 // Push onto head of global queue
4842                 globrunqputhead(gp)
4843         }
4844         if pp.runnext != 0 {
4845                 globrunqputhead(pp.runnext.ptr())
4846                 pp.runnext = 0
4847         }
4848         if len(pp.timers) > 0 {
4849                 plocal := getg().m.p.ptr()
4850                 // The world is stopped, but we acquire timersLock to
4851                 // protect against sysmon calling timeSleepUntil.
4852                 // This is the only case where we hold the timersLock of
4853                 // more than one P, so there are no deadlock concerns.
4854                 lock(&plocal.timersLock)
4855                 lock(&pp.timersLock)
4856                 moveTimers(plocal, pp.timers)
4857                 pp.timers = nil
4858                 pp.numTimers.Store(0)
4859                 pp.deletedTimers.Store(0)
4860                 pp.timer0When.Store(0)
4861                 unlock(&pp.timersLock)
4862                 unlock(&plocal.timersLock)
4863         }
4864         // Flush p's write barrier buffer.
4865         if gcphase != _GCoff {
4866                 wbBufFlush1(pp)
4867                 pp.gcw.dispose()
4868         }
4869         for i := range pp.sudogbuf {
4870                 pp.sudogbuf[i] = nil
4871         }
4872         pp.sudogcache = pp.sudogbuf[:0]
4873         for j := range pp.deferpoolbuf {
4874                 pp.deferpoolbuf[j] = nil
4875         }
4876         pp.deferpool = pp.deferpoolbuf[:0]
4877         systemstack(func() {
4878                 for i := 0; i < pp.mspancache.len; i++ {
4879                         // Safe to call since the world is stopped.
4880                         mheap_.spanalloc.free(unsafe.Pointer(pp.mspancache.buf[i]))
4881                 }
4882                 pp.mspancache.len = 0
4883                 lock(&mheap_.lock)
4884                 pp.pcache.flush(&mheap_.pages)
4885                 unlock(&mheap_.lock)
4886         })
4887         freemcache(pp.mcache)
4888         pp.mcache = nil
4889         gfpurge(pp)
4890         traceProcFree(pp)
4891         if raceenabled {
4892                 if pp.timerRaceCtx != 0 {
4893                         // The race detector code uses a callback to fetch
4894                         // the proc context, so arrange for that callback
4895                         // to see the right thing.
4896                         // This hack only works because we are the only
4897                         // thread running.
4898                         mp := getg().m
4899                         phold := mp.p.ptr()
4900                         mp.p.set(pp)
4901
4902                         racectxend(pp.timerRaceCtx)
4903                         pp.timerRaceCtx = 0
4904
4905                         mp.p.set(phold)
4906                 }
4907                 raceprocdestroy(pp.raceprocctx)
4908                 pp.raceprocctx = 0
4909         }
4910         pp.gcAssistTime = 0
4911         pp.status = _Pdead
4912 }
4913
4914 // Change number of processors.
4915 //
4916 // sched.lock must be held, and the world must be stopped.
4917 //
4918 // gcworkbufs must not be being modified by either the GC or the write barrier
4919 // code, so the GC must not be running if the number of Ps actually changes.
4920 //
4921 // Returns list of Ps with local work, they need to be scheduled by the caller.
4922 func procresize(nprocs int32) *p {
4923         assertLockHeld(&sched.lock)
4924         assertWorldStopped()
4925
4926         old := gomaxprocs
4927         if old < 0 || nprocs <= 0 {
4928                 throw("procresize: invalid arg")
4929         }
4930         if trace.enabled {
4931                 traceGomaxprocs(nprocs)
4932         }
4933
4934         // update statistics
4935         now := nanotime()
4936         if sched.procresizetime != 0 {
4937                 sched.totaltime += int64(old) * (now - sched.procresizetime)
4938         }
4939         sched.procresizetime = now
4940
4941         maskWords := (nprocs + 31) / 32
4942
4943         // Grow allp if necessary.
4944         if nprocs > int32(len(allp)) {
4945                 // Synchronize with retake, which could be running
4946                 // concurrently since it doesn't run on a P.
4947                 lock(&allpLock)
4948                 if nprocs <= int32(cap(allp)) {
4949                         allp = allp[:nprocs]
4950                 } else {
4951                         nallp := make([]*p, nprocs)
4952                         // Copy everything up to allp's cap so we
4953                         // never lose old allocated Ps.
4954                         copy(nallp, allp[:cap(allp)])
4955                         allp = nallp
4956                 }
4957
4958                 if maskWords <= int32(cap(idlepMask)) {
4959                         idlepMask = idlepMask[:maskWords]
4960                         timerpMask = timerpMask[:maskWords]
4961                 } else {
4962                         nidlepMask := make([]uint32, maskWords)
4963                         // No need to copy beyond len, old Ps are irrelevant.
4964                         copy(nidlepMask, idlepMask)
4965                         idlepMask = nidlepMask
4966
4967                         ntimerpMask := make([]uint32, maskWords)
4968                         copy(ntimerpMask, timerpMask)
4969                         timerpMask = ntimerpMask
4970                 }
4971                 unlock(&allpLock)
4972         }
4973
4974         // initialize new P's
4975         for i := old; i < nprocs; i++ {
4976                 pp := allp[i]
4977                 if pp == nil {
4978                         pp = new(p)
4979                 }
4980                 pp.init(i)
4981                 atomicstorep(unsafe.Pointer(&allp[i]), unsafe.Pointer(pp))
4982         }
4983
4984         gp := getg()
4985         if gp.m.p != 0 && gp.m.p.ptr().id < nprocs {
4986                 // continue to use the current P
4987                 gp.m.p.ptr().status = _Prunning
4988                 gp.m.p.ptr().mcache.prepareForSweep()
4989         } else {
4990                 // release the current P and acquire allp[0].
4991                 //
4992                 // We must do this before destroying our current P
4993                 // because p.destroy itself has write barriers, so we
4994                 // need to do that from a valid P.
4995                 if gp.m.p != 0 {
4996                         if trace.enabled {
4997                                 // Pretend that we were descheduled
4998                                 // and then scheduled again to keep
4999                                 // the trace sane.
5000                                 traceGoSched()
5001                                 traceProcStop(gp.m.p.ptr())
5002                         }
5003                         gp.m.p.ptr().m = 0
5004                 }
5005                 gp.m.p = 0
5006                 pp := allp[0]
5007                 pp.m = 0
5008                 pp.status = _Pidle
5009                 acquirep(pp)
5010                 if trace.enabled {
5011                         traceGoStart()
5012                 }
5013         }
5014
5015         // g.m.p is now set, so we no longer need mcache0 for bootstrapping.
5016         mcache0 = nil
5017
5018         // release resources from unused P's
5019         for i := nprocs; i < old; i++ {
5020                 pp := allp[i]
5021                 pp.destroy()
5022                 // can't free P itself because it can be referenced by an M in syscall
5023         }
5024
5025         // Trim allp.
5026         if int32(len(allp)) != nprocs {
5027                 lock(&allpLock)
5028                 allp = allp[:nprocs]
5029                 idlepMask = idlepMask[:maskWords]
5030                 timerpMask = timerpMask[:maskWords]
5031                 unlock(&allpLock)
5032         }
5033
5034         var runnablePs *p
5035         for i := nprocs - 1; i >= 0; i-- {
5036                 pp := allp[i]
5037                 if gp.m.p.ptr() == pp {
5038                         continue
5039                 }
5040                 pp.status = _Pidle
5041                 if runqempty(pp) {
5042                         pidleput(pp, now)
5043                 } else {
5044                         pp.m.set(mget())
5045                         pp.link.set(runnablePs)
5046                         runnablePs = pp
5047                 }
5048         }
5049         stealOrder.reset(uint32(nprocs))
5050         var int32p *int32 = &gomaxprocs // make compiler check that gomaxprocs is an int32
5051         atomic.Store((*uint32)(unsafe.Pointer(int32p)), uint32(nprocs))
5052         if old != nprocs {
5053                 // Notify the limiter that the amount of procs has changed.
5054                 gcCPULimiter.resetCapacity(now, nprocs)
5055         }
5056         return runnablePs
5057 }
5058
5059 // Associate p and the current m.
5060 //
5061 // This function is allowed to have write barriers even if the caller
5062 // isn't because it immediately acquires pp.
5063 //
5064 //go:yeswritebarrierrec
5065 func acquirep(pp *p) {
5066         // Do the part that isn't allowed to have write barriers.
5067         wirep(pp)
5068
5069         // Have p; write barriers now allowed.
5070
5071         // Perform deferred mcache flush before this P can allocate
5072         // from a potentially stale mcache.
5073         pp.mcache.prepareForSweep()
5074
5075         if trace.enabled {
5076                 traceProcStart()
5077         }
5078 }
5079
5080 // wirep is the first step of acquirep, which actually associates the
5081 // current M to pp. This is broken out so we can disallow write
5082 // barriers for this part, since we don't yet have a P.
5083 //
5084 //go:nowritebarrierrec
5085 //go:nosplit
5086 func wirep(pp *p) {
5087         gp := getg()
5088
5089         if gp.m.p != 0 {
5090                 throw("wirep: already in go")
5091         }
5092         if pp.m != 0 || pp.status != _Pidle {
5093                 id := int64(0)
5094                 if pp.m != 0 {
5095                         id = pp.m.ptr().id
5096                 }
5097                 print("wirep: p->m=", pp.m, "(", id, ") p->status=", pp.status, "\n")
5098                 throw("wirep: invalid p state")
5099         }
5100         gp.m.p.set(pp)
5101         pp.m.set(gp.m)
5102         pp.status = _Prunning
5103 }
5104
5105 // Disassociate p and the current m.
5106 func releasep() *p {
5107         gp := getg()
5108
5109         if gp.m.p == 0 {
5110                 throw("releasep: invalid arg")
5111         }
5112         pp := gp.m.p.ptr()
5113         if pp.m.ptr() != gp.m || pp.status != _Prunning {
5114                 print("releasep: m=", gp.m, " m->p=", gp.m.p.ptr(), " p->m=", hex(pp.m), " p->status=", pp.status, "\n")
5115                 throw("releasep: invalid p state")
5116         }
5117         if trace.enabled {
5118                 traceProcStop(gp.m.p.ptr())
5119         }
5120         gp.m.p = 0
5121         pp.m = 0
5122         pp.status = _Pidle
5123         return pp
5124 }
5125
5126 func incidlelocked(v int32) {
5127         lock(&sched.lock)
5128         sched.nmidlelocked += v
5129         if v > 0 {
5130                 checkdead()
5131         }
5132         unlock(&sched.lock)
5133 }
5134
5135 // Check for deadlock situation.
5136 // The check is based on number of running M's, if 0 -> deadlock.
5137 // sched.lock must be held.
5138 func checkdead() {
5139         assertLockHeld(&sched.lock)
5140
5141         // For -buildmode=c-shared or -buildmode=c-archive it's OK if
5142         // there are no running goroutines. The calling program is
5143         // assumed to be running.
5144         if islibrary || isarchive {
5145                 return
5146         }
5147
5148         // If we are dying because of a signal caught on an already idle thread,
5149         // freezetheworld will cause all running threads to block.
5150         // And runtime will essentially enter into deadlock state,
5151         // except that there is a thread that will call exit soon.
5152         if panicking.Load() > 0 {
5153                 return
5154         }
5155
5156         // If we are not running under cgo, but we have an extra M then account
5157         // for it. (It is possible to have an extra M on Windows without cgo to
5158         // accommodate callbacks created by syscall.NewCallback. See issue #6751
5159         // for details.)
5160         var run0 int32
5161         if !iscgo && cgoHasExtraM {
5162                 mp := lockextra(true)
5163                 haveExtraM := extraMCount > 0
5164                 unlockextra(mp)
5165                 if haveExtraM {
5166                         run0 = 1
5167                 }
5168         }
5169
5170         run := mcount() - sched.nmidle - sched.nmidlelocked - sched.nmsys
5171         if run > run0 {
5172                 return
5173         }
5174         if run < 0 {
5175                 print("runtime: checkdead: nmidle=", sched.nmidle, " nmidlelocked=", sched.nmidlelocked, " mcount=", mcount(), " nmsys=", sched.nmsys, "\n")
5176                 throw("checkdead: inconsistent counts")
5177         }
5178
5179         grunning := 0
5180         forEachG(func(gp *g) {
5181                 if isSystemGoroutine(gp, false) {
5182                         return
5183                 }
5184                 s := readgstatus(gp)
5185                 switch s &^ _Gscan {
5186                 case _Gwaiting,
5187                         _Gpreempted:
5188                         grunning++
5189                 case _Grunnable,
5190                         _Grunning,
5191                         _Gsyscall:
5192                         print("runtime: checkdead: find g ", gp.goid, " in status ", s, "\n")
5193                         throw("checkdead: runnable g")
5194                 }
5195         })
5196         if grunning == 0 { // possible if main goroutine calls runtime·Goexit()
5197                 unlock(&sched.lock) // unlock so that GODEBUG=scheddetail=1 doesn't hang
5198                 fatal("no goroutines (main called runtime.Goexit) - deadlock!")
5199         }
5200
5201         // Maybe jump time forward for playground.
5202         if faketime != 0 {
5203                 if when := timeSleepUntil(); when < maxWhen {
5204                         faketime = when
5205
5206                         // Start an M to steal the timer.
5207                         pp, _ := pidleget(faketime)
5208                         if pp == nil {
5209                                 // There should always be a free P since
5210                                 // nothing is running.
5211                                 throw("checkdead: no p for timer")
5212                         }
5213                         mp := mget()
5214                         if mp == nil {
5215                                 // There should always be a free M since
5216                                 // nothing is running.
5217                                 throw("checkdead: no m for timer")
5218                         }
5219                         // M must be spinning to steal. We set this to be
5220                         // explicit, but since this is the only M it would
5221                         // become spinning on its own anyways.
5222                         sched.nmspinning.Add(1)
5223                         mp.spinning = true
5224                         mp.nextp.set(pp)
5225                         notewakeup(&mp.park)
5226                         return
5227                 }
5228         }
5229
5230         // There are no goroutines running, so we can look at the P's.
5231         for _, pp := range allp {
5232                 if len(pp.timers) > 0 {
5233                         return
5234                 }
5235         }
5236
5237         unlock(&sched.lock) // unlock so that GODEBUG=scheddetail=1 doesn't hang
5238         fatal("all goroutines are asleep - deadlock!")
5239 }
5240
5241 // forcegcperiod is the maximum time in nanoseconds between garbage
5242 // collections. If we go this long without a garbage collection, one
5243 // is forced to run.
5244 //
5245 // This is a variable for testing purposes. It normally doesn't change.
5246 var forcegcperiod int64 = 2 * 60 * 1e9
5247
5248 // needSysmonWorkaround is true if the workaround for
5249 // golang.org/issue/42515 is needed on NetBSD.
5250 var needSysmonWorkaround bool = false
5251
5252 // Always runs without a P, so write barriers are not allowed.
5253 //
5254 //go:nowritebarrierrec
5255 func sysmon() {
5256         lock(&sched.lock)
5257         sched.nmsys++
5258         checkdead()
5259         unlock(&sched.lock)
5260
5261         lasttrace := int64(0)
5262         idle := 0 // how many cycles in succession we had not wokeup somebody
5263         delay := uint32(0)
5264
5265         for {
5266                 if idle == 0 { // start with 20us sleep...
5267                         delay = 20
5268                 } else if idle > 50 { // start doubling the sleep after 1ms...
5269                         delay *= 2
5270                 }
5271                 if delay > 10*1000 { // up to 10ms
5272                         delay = 10 * 1000
5273                 }
5274                 usleep(delay)
5275
5276                 // sysmon should not enter deep sleep if schedtrace is enabled so that
5277                 // it can print that information at the right time.
5278                 //
5279                 // It should also not enter deep sleep if there are any active P's so
5280                 // that it can retake P's from syscalls, preempt long running G's, and
5281                 // poll the network if all P's are busy for long stretches.
5282                 //
5283                 // It should wakeup from deep sleep if any P's become active either due
5284                 // to exiting a syscall or waking up due to a timer expiring so that it
5285                 // can resume performing those duties. If it wakes from a syscall it
5286                 // resets idle and delay as a bet that since it had retaken a P from a
5287                 // syscall before, it may need to do it again shortly after the
5288                 // application starts work again. It does not reset idle when waking
5289                 // from a timer to avoid adding system load to applications that spend
5290                 // most of their time sleeping.
5291                 now := nanotime()
5292                 if debug.schedtrace <= 0 && (sched.gcwaiting.Load() || sched.npidle.Load() == gomaxprocs) {
5293                         lock(&sched.lock)
5294                         if sched.gcwaiting.Load() || sched.npidle.Load() == gomaxprocs {
5295                                 syscallWake := false
5296                                 next := timeSleepUntil()
5297                                 if next > now {
5298                                         sched.sysmonwait.Store(true)
5299                                         unlock(&sched.lock)
5300                                         // Make wake-up period small enough
5301                                         // for the sampling to be correct.
5302                                         sleep := forcegcperiod / 2
5303                                         if next-now < sleep {
5304                                                 sleep = next - now
5305                                         }
5306                                         shouldRelax := sleep >= osRelaxMinNS
5307                                         if shouldRelax {
5308                                                 osRelax(true)
5309                                         }
5310                                         syscallWake = notetsleep(&sched.sysmonnote, sleep)
5311                                         if shouldRelax {
5312                                                 osRelax(false)
5313                                         }
5314                                         lock(&sched.lock)
5315                                         sched.sysmonwait.Store(false)
5316                                         noteclear(&sched.sysmonnote)
5317                                 }
5318                                 if syscallWake {
5319                                         idle = 0
5320                                         delay = 20
5321                                 }
5322                         }
5323                         unlock(&sched.lock)
5324                 }
5325
5326                 lock(&sched.sysmonlock)
5327                 // Update now in case we blocked on sysmonnote or spent a long time
5328                 // blocked on schedlock or sysmonlock above.
5329                 now = nanotime()
5330
5331                 // trigger libc interceptors if needed
5332                 if *cgo_yield != nil {
5333                         asmcgocall(*cgo_yield, nil)
5334                 }
5335                 // poll network if not polled for more than 10ms
5336                 lastpoll := sched.lastpoll.Load()
5337                 if netpollinited() && lastpoll != 0 && lastpoll+10*1000*1000 < now {
5338                         sched.lastpoll.CompareAndSwap(lastpoll, now)
5339                         list := netpoll(0) // non-blocking - returns list of goroutines
5340                         if !list.empty() {
5341                                 // Need to decrement number of idle locked M's
5342                                 // (pretending that one more is running) before injectglist.
5343                                 // Otherwise it can lead to the following situation:
5344                                 // injectglist grabs all P's but before it starts M's to run the P's,
5345                                 // another M returns from syscall, finishes running its G,
5346                                 // observes that there is no work to do and no other running M's
5347                                 // and reports deadlock.
5348                                 incidlelocked(-1)
5349                                 injectglist(&list)
5350                                 incidlelocked(1)
5351                         }
5352                 }
5353                 if GOOS == "netbsd" && needSysmonWorkaround {
5354                         // netpoll is responsible for waiting for timer
5355                         // expiration, so we typically don't have to worry
5356                         // about starting an M to service timers. (Note that
5357                         // sleep for timeSleepUntil above simply ensures sysmon
5358                         // starts running again when that timer expiration may
5359                         // cause Go code to run again).
5360                         //
5361                         // However, netbsd has a kernel bug that sometimes
5362                         // misses netpollBreak wake-ups, which can lead to
5363                         // unbounded delays servicing timers. If we detect this
5364                         // overrun, then startm to get something to handle the
5365                         // timer.
5366                         //
5367                         // See issue 42515 and
5368                         // https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=50094.
5369                         if next := timeSleepUntil(); next < now {
5370                                 startm(nil, false)
5371                         }
5372                 }
5373                 if scavenger.sysmonWake.Load() != 0 {
5374                         // Kick the scavenger awake if someone requested it.
5375                         scavenger.wake()
5376                 }
5377                 // retake P's blocked in syscalls
5378                 // and preempt long running G's
5379                 if retake(now) != 0 {
5380                         idle = 0
5381                 } else {
5382                         idle++
5383                 }
5384                 // check if we need to force a GC
5385                 if t := (gcTrigger{kind: gcTriggerTime, now: now}); t.test() && forcegc.idle.Load() {
5386                         lock(&forcegc.lock)
5387                         forcegc.idle.Store(false)
5388                         var list gList
5389                         list.push(forcegc.g)
5390                         injectglist(&list)
5391                         unlock(&forcegc.lock)
5392                 }
5393                 if debug.schedtrace > 0 && lasttrace+int64(debug.schedtrace)*1000000 <= now {
5394                         lasttrace = now
5395                         schedtrace(debug.scheddetail > 0)
5396                 }
5397                 unlock(&sched.sysmonlock)
5398         }
5399 }
5400
5401 type sysmontick struct {
5402         schedtick   uint32
5403         schedwhen   int64
5404         syscalltick uint32
5405         syscallwhen int64
5406 }
5407
5408 // forcePreemptNS is the time slice given to a G before it is
5409 // preempted.
5410 const forcePreemptNS = 10 * 1000 * 1000 // 10ms
5411
5412 func retake(now int64) uint32 {
5413         n := 0
5414         // Prevent allp slice changes. This lock will be completely
5415         // uncontended unless we're already stopping the world.
5416         lock(&allpLock)
5417         // We can't use a range loop over allp because we may
5418         // temporarily drop the allpLock. Hence, we need to re-fetch
5419         // allp each time around the loop.
5420         for i := 0; i < len(allp); i++ {
5421                 pp := allp[i]
5422                 if pp == nil {
5423                         // This can happen if procresize has grown
5424                         // allp but not yet created new Ps.
5425                         continue
5426                 }
5427                 pd := &pp.sysmontick
5428                 s := pp.status
5429                 sysretake := false
5430                 if s == _Prunning || s == _Psyscall {
5431                         // Preempt G if it's running for too long.
5432                         t := int64(pp.schedtick)
5433                         if int64(pd.schedtick) != t {
5434                                 pd.schedtick = uint32(t)
5435                                 pd.schedwhen = now
5436                         } else if pd.schedwhen+forcePreemptNS <= now {
5437                                 preemptone(pp)
5438                                 // In case of syscall, preemptone() doesn't
5439                                 // work, because there is no M wired to P.
5440                                 sysretake = true
5441                         }
5442                 }
5443                 if s == _Psyscall {
5444                         // Retake P from syscall if it's there for more than 1 sysmon tick (at least 20us).
5445                         t := int64(pp.syscalltick)
5446                         if !sysretake && int64(pd.syscalltick) != t {
5447                                 pd.syscalltick = uint32(t)
5448                                 pd.syscallwhen = now
5449                                 continue
5450                         }
5451                         // On the one hand we don't want to retake Ps if there is no other work to do,
5452                         // but on the other hand we want to retake them eventually
5453                         // because they can prevent the sysmon thread from deep sleep.
5454                         if runqempty(pp) && sched.nmspinning.Load()+sched.npidle.Load() > 0 && pd.syscallwhen+10*1000*1000 > now {
5455                                 continue
5456                         }
5457                         // Drop allpLock so we can take sched.lock.
5458                         unlock(&allpLock)
5459                         // Need to decrement number of idle locked M's
5460                         // (pretending that one more is running) before the CAS.
5461                         // Otherwise the M from which we retake can exit the syscall,
5462                         // increment nmidle and report deadlock.
5463                         incidlelocked(-1)
5464                         if atomic.Cas(&pp.status, s, _Pidle) {
5465                                 if trace.enabled {
5466                                         traceGoSysBlock(pp)
5467                                         traceProcStop(pp)
5468                                 }
5469                                 n++
5470                                 pp.syscalltick++
5471                                 handoffp(pp)
5472                         }
5473                         incidlelocked(1)
5474                         lock(&allpLock)
5475                 }
5476         }
5477         unlock(&allpLock)
5478         return uint32(n)
5479 }
5480
5481 // Tell all goroutines that they have been preempted and they should stop.
5482 // This function is purely best-effort. It can fail to inform a goroutine if a
5483 // processor just started running it.
5484 // No locks need to be held.
5485 // Returns true if preemption request was issued to at least one goroutine.
5486 func preemptall() bool {
5487         res := false
5488         for _, pp := range allp {
5489                 if pp.status != _Prunning {
5490                         continue
5491                 }
5492                 if preemptone(pp) {
5493                         res = true
5494                 }
5495         }
5496         return res
5497 }
5498
5499 // Tell the goroutine running on processor P to stop.
5500 // This function is purely best-effort. It can incorrectly fail to inform the
5501 // goroutine. It can inform the wrong goroutine. Even if it informs the
5502 // correct goroutine, that goroutine might ignore the request if it is
5503 // simultaneously executing newstack.
5504 // No lock needs to be held.
5505 // Returns true if preemption request was issued.
5506 // The actual preemption will happen at some point in the future
5507 // and will be indicated by the gp->status no longer being
5508 // Grunning
5509 func preemptone(pp *p) bool {
5510         mp := pp.m.ptr()
5511         if mp == nil || mp == getg().m {
5512                 return false
5513         }
5514         gp := mp.curg
5515         if gp == nil || gp == mp.g0 {
5516                 return false
5517         }
5518
5519         gp.preempt = true
5520
5521         // Every call in a goroutine checks for stack overflow by
5522         // comparing the current stack pointer to gp->stackguard0.
5523         // Setting gp->stackguard0 to StackPreempt folds
5524         // preemption into the normal stack overflow check.
5525         gp.stackguard0 = stackPreempt
5526
5527         // Request an async preemption of this P.
5528         if preemptMSupported && debug.asyncpreemptoff == 0 {
5529                 pp.preempt = true
5530                 preemptM(mp)
5531         }
5532
5533         return true
5534 }
5535
5536 var starttime int64
5537
5538 func schedtrace(detailed bool) {
5539         now := nanotime()
5540         if starttime == 0 {
5541                 starttime = now
5542         }
5543
5544         lock(&sched.lock)
5545         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)
5546         if detailed {
5547                 print(" gcwaiting=", sched.gcwaiting.Load(), " nmidlelocked=", sched.nmidlelocked, " stopwait=", sched.stopwait, " sysmonwait=", sched.sysmonwait.Load(), "\n")
5548         }
5549         // We must be careful while reading data from P's, M's and G's.
5550         // Even if we hold schedlock, most data can be changed concurrently.
5551         // E.g. (p->m ? p->m->id : -1) can crash if p->m changes from non-nil to nil.
5552         for i, pp := range allp {
5553                 mp := pp.m.ptr()
5554                 h := atomic.Load(&pp.runqhead)
5555                 t := atomic.Load(&pp.runqtail)
5556                 if detailed {
5557                         print("  P", i, ": status=", pp.status, " schedtick=", pp.schedtick, " syscalltick=", pp.syscalltick, " m=")
5558                         if mp != nil {
5559                                 print(mp.id)
5560                         } else {
5561                                 print("nil")
5562                         }
5563                         print(" runqsize=", t-h, " gfreecnt=", pp.gFree.n, " timerslen=", len(pp.timers), "\n")
5564                 } else {
5565                         // In non-detailed mode format lengths of per-P run queues as:
5566                         // [len1 len2 len3 len4]
5567                         print(" ")
5568                         if i == 0 {
5569                                 print("[")
5570                         }
5571                         print(t - h)
5572                         if i == len(allp)-1 {
5573                                 print("]\n")
5574                         }
5575                 }
5576         }
5577
5578         if !detailed {
5579                 unlock(&sched.lock)
5580                 return
5581         }
5582
5583         for mp := allm; mp != nil; mp = mp.alllink {
5584                 pp := mp.p.ptr()
5585                 print("  M", mp.id, ": p=")
5586                 if pp != nil {
5587                         print(pp.id)
5588                 } else {
5589                         print("nil")
5590                 }
5591                 print(" curg=")
5592                 if mp.curg != nil {
5593                         print(mp.curg.goid)
5594                 } else {
5595                         print("nil")
5596                 }
5597                 print(" mallocing=", mp.mallocing, " throwing=", mp.throwing, " preemptoff=", mp.preemptoff, " locks=", mp.locks, " dying=", mp.dying, " spinning=", mp.spinning, " blocked=", mp.blocked, " lockedg=")
5598                 if lockedg := mp.lockedg.ptr(); lockedg != nil {
5599                         print(lockedg.goid)
5600                 } else {
5601                         print("nil")
5602                 }
5603                 print("\n")
5604         }
5605
5606         forEachG(func(gp *g) {
5607                 print("  G", gp.goid, ": status=", readgstatus(gp), "(", gp.waitreason.String(), ") m=")
5608                 if gp.m != nil {
5609                         print(gp.m.id)
5610                 } else {
5611                         print("nil")
5612                 }
5613                 print(" lockedm=")
5614                 if lockedm := gp.lockedm.ptr(); lockedm != nil {
5615                         print(lockedm.id)
5616                 } else {
5617                         print("nil")
5618                 }
5619                 print("\n")
5620         })
5621         unlock(&sched.lock)
5622 }
5623
5624 // schedEnableUser enables or disables the scheduling of user
5625 // goroutines.
5626 //
5627 // This does not stop already running user goroutines, so the caller
5628 // should first stop the world when disabling user goroutines.
5629 func schedEnableUser(enable bool) {
5630         lock(&sched.lock)
5631         if sched.disable.user == !enable {
5632                 unlock(&sched.lock)
5633                 return
5634         }
5635         sched.disable.user = !enable
5636         if enable {
5637                 n := sched.disable.n
5638                 sched.disable.n = 0
5639                 globrunqputbatch(&sched.disable.runnable, n)
5640                 unlock(&sched.lock)
5641                 for ; n != 0 && sched.npidle.Load() != 0; n-- {
5642                         startm(nil, false)
5643                 }
5644         } else {
5645                 unlock(&sched.lock)
5646         }
5647 }
5648
5649 // schedEnabled reports whether gp should be scheduled. It returns
5650 // false is scheduling of gp is disabled.
5651 //
5652 // sched.lock must be held.
5653 func schedEnabled(gp *g) bool {
5654         assertLockHeld(&sched.lock)
5655
5656         if sched.disable.user {
5657                 return isSystemGoroutine(gp, true)
5658         }
5659         return true
5660 }
5661
5662 // Put mp on midle list.
5663 // sched.lock must be held.
5664 // May run during STW, so write barriers are not allowed.
5665 //
5666 //go:nowritebarrierrec
5667 func mput(mp *m) {
5668         assertLockHeld(&sched.lock)
5669
5670         mp.schedlink = sched.midle
5671         sched.midle.set(mp)
5672         sched.nmidle++
5673         checkdead()
5674 }
5675
5676 // Try to get an m from midle list.
5677 // sched.lock must be held.
5678 // May run during STW, so write barriers are not allowed.
5679 //
5680 //go:nowritebarrierrec
5681 func mget() *m {
5682         assertLockHeld(&sched.lock)
5683
5684         mp := sched.midle.ptr()
5685         if mp != nil {
5686                 sched.midle = mp.schedlink
5687                 sched.nmidle--
5688         }
5689         return mp
5690 }
5691
5692 // Put gp on the global runnable queue.
5693 // sched.lock must be held.
5694 // May run during STW, so write barriers are not allowed.
5695 //
5696 //go:nowritebarrierrec
5697 func globrunqput(gp *g) {
5698         assertLockHeld(&sched.lock)
5699
5700         sched.runq.pushBack(gp)
5701         sched.runqsize++
5702 }
5703
5704 // Put gp at the head of the global runnable queue.
5705 // sched.lock must be held.
5706 // May run during STW, so write barriers are not allowed.
5707 //
5708 //go:nowritebarrierrec
5709 func globrunqputhead(gp *g) {
5710         assertLockHeld(&sched.lock)
5711
5712         sched.runq.push(gp)
5713         sched.runqsize++
5714 }
5715
5716 // Put a batch of runnable goroutines on the global runnable queue.
5717 // This clears *batch.
5718 // sched.lock must be held.
5719 // May run during STW, so write barriers are not allowed.
5720 //
5721 //go:nowritebarrierrec
5722 func globrunqputbatch(batch *gQueue, n int32) {
5723         assertLockHeld(&sched.lock)
5724
5725         sched.runq.pushBackAll(*batch)
5726         sched.runqsize += n
5727         *batch = gQueue{}
5728 }
5729
5730 // Try get a batch of G's from the global runnable queue.
5731 // sched.lock must be held.
5732 func globrunqget(pp *p, max int32) *g {
5733         assertLockHeld(&sched.lock)
5734
5735         if sched.runqsize == 0 {
5736                 return nil
5737         }
5738
5739         n := sched.runqsize/gomaxprocs + 1
5740         if n > sched.runqsize {
5741                 n = sched.runqsize
5742         }
5743         if max > 0 && n > max {
5744                 n = max
5745         }
5746         if n > int32(len(pp.runq))/2 {
5747                 n = int32(len(pp.runq)) / 2
5748         }
5749
5750         sched.runqsize -= n
5751
5752         gp := sched.runq.pop()
5753         n--
5754         for ; n > 0; n-- {
5755                 gp1 := sched.runq.pop()
5756                 runqput(pp, gp1, false)
5757         }
5758         return gp
5759 }
5760
5761 // pMask is an atomic bitstring with one bit per P.
5762 type pMask []uint32
5763
5764 // read returns true if P id's bit is set.
5765 func (p pMask) read(id uint32) bool {
5766         word := id / 32
5767         mask := uint32(1) << (id % 32)
5768         return (atomic.Load(&p[word]) & mask) != 0
5769 }
5770
5771 // set sets P id's bit.
5772 func (p pMask) set(id int32) {
5773         word := id / 32
5774         mask := uint32(1) << (id % 32)
5775         atomic.Or(&p[word], mask)
5776 }
5777
5778 // clear clears P id's bit.
5779 func (p pMask) clear(id int32) {
5780         word := id / 32
5781         mask := uint32(1) << (id % 32)
5782         atomic.And(&p[word], ^mask)
5783 }
5784
5785 // updateTimerPMask clears pp's timer mask if it has no timers on its heap.
5786 //
5787 // Ideally, the timer mask would be kept immediately consistent on any timer
5788 // operations. Unfortunately, updating a shared global data structure in the
5789 // timer hot path adds too much overhead in applications frequently switching
5790 // between no timers and some timers.
5791 //
5792 // As a compromise, the timer mask is updated only on pidleget / pidleput. A
5793 // running P (returned by pidleget) may add a timer at any time, so its mask
5794 // must be set. An idle P (passed to pidleput) cannot add new timers while
5795 // idle, so if it has no timers at that time, its mask may be cleared.
5796 //
5797 // Thus, we get the following effects on timer-stealing in findrunnable:
5798 //
5799 //   - Idle Ps with no timers when they go idle are never checked in findrunnable
5800 //     (for work- or timer-stealing; this is the ideal case).
5801 //   - Running Ps must always be checked.
5802 //   - Idle Ps whose timers are stolen must continue to be checked until they run
5803 //     again, even after timer expiration.
5804 //
5805 // When the P starts running again, the mask should be set, as a timer may be
5806 // added at any time.
5807 //
5808 // TODO(prattmic): Additional targeted updates may improve the above cases.
5809 // e.g., updating the mask when stealing a timer.
5810 func updateTimerPMask(pp *p) {
5811         if pp.numTimers.Load() > 0 {
5812                 return
5813         }
5814
5815         // Looks like there are no timers, however another P may transiently
5816         // decrement numTimers when handling a timerModified timer in
5817         // checkTimers. We must take timersLock to serialize with these changes.
5818         lock(&pp.timersLock)
5819         if pp.numTimers.Load() == 0 {
5820                 timerpMask.clear(pp.id)
5821         }
5822         unlock(&pp.timersLock)
5823 }
5824
5825 // pidleput puts p on the _Pidle list. now must be a relatively recent call
5826 // to nanotime or zero. Returns now or the current time if now was zero.
5827 //
5828 // This releases ownership of p. Once sched.lock is released it is no longer
5829 // safe to use p.
5830 //
5831 // sched.lock must be held.
5832 //
5833 // May run during STW, so write barriers are not allowed.
5834 //
5835 //go:nowritebarrierrec
5836 func pidleput(pp *p, now int64) int64 {
5837         assertLockHeld(&sched.lock)
5838
5839         if !runqempty(pp) {
5840                 throw("pidleput: P has non-empty run queue")
5841         }
5842         if now == 0 {
5843                 now = nanotime()
5844         }
5845         updateTimerPMask(pp) // clear if there are no timers.
5846         idlepMask.set(pp.id)
5847         pp.link = sched.pidle
5848         sched.pidle.set(pp)
5849         sched.npidle.Add(1)
5850         if !pp.limiterEvent.start(limiterEventIdle, now) {
5851                 throw("must be able to track idle limiter event")
5852         }
5853         return now
5854 }
5855
5856 // pidleget tries to get a p from the _Pidle list, acquiring ownership.
5857 //
5858 // sched.lock must be held.
5859 //
5860 // May run during STW, so write barriers are not allowed.
5861 //
5862 //go:nowritebarrierrec
5863 func pidleget(now int64) (*p, int64) {
5864         assertLockHeld(&sched.lock)
5865
5866         pp := sched.pidle.ptr()
5867         if pp != nil {
5868                 // Timer may get added at any time now.
5869                 if now == 0 {
5870                         now = nanotime()
5871                 }
5872                 timerpMask.set(pp.id)
5873                 idlepMask.clear(pp.id)
5874                 sched.pidle = pp.link
5875                 sched.npidle.Add(-1)
5876                 pp.limiterEvent.stop(limiterEventIdle, now)
5877         }
5878         return pp, now
5879 }
5880
5881 // pidlegetSpinning tries to get a p from the _Pidle list, acquiring ownership.
5882 // This is called by spinning Ms (or callers than need a spinning M) that have
5883 // found work. If no P is available, this must synchronized with non-spinning
5884 // Ms that may be preparing to drop their P without discovering this work.
5885 //
5886 // sched.lock must be held.
5887 //
5888 // May run during STW, so write barriers are not allowed.
5889 //
5890 //go:nowritebarrierrec
5891 func pidlegetSpinning(now int64) (*p, int64) {
5892         assertLockHeld(&sched.lock)
5893
5894         pp, now := pidleget(now)
5895         if pp == nil {
5896                 // See "Delicate dance" comment in findrunnable. We found work
5897                 // that we cannot take, we must synchronize with non-spinning
5898                 // Ms that may be preparing to drop their P.
5899                 sched.needspinning.Store(1)
5900                 return nil, now
5901         }
5902
5903         return pp, now
5904 }
5905
5906 // runqempty reports whether pp has no Gs on its local run queue.
5907 // It never returns true spuriously.
5908 func runqempty(pp *p) bool {
5909         // Defend against a race where 1) pp has G1 in runqnext but runqhead == runqtail,
5910         // 2) runqput on pp kicks G1 to the runq, 3) runqget on pp empties runqnext.
5911         // Simply observing that runqhead == runqtail and then observing that runqnext == nil
5912         // does not mean the queue is empty.
5913         for {
5914                 head := atomic.Load(&pp.runqhead)
5915                 tail := atomic.Load(&pp.runqtail)
5916                 runnext := atomic.Loaduintptr((*uintptr)(unsafe.Pointer(&pp.runnext)))
5917                 if tail == atomic.Load(&pp.runqtail) {
5918                         return head == tail && runnext == 0
5919                 }
5920         }
5921 }
5922
5923 // To shake out latent assumptions about scheduling order,
5924 // we introduce some randomness into scheduling decisions
5925 // when running with the race detector.
5926 // The need for this was made obvious by changing the
5927 // (deterministic) scheduling order in Go 1.5 and breaking
5928 // many poorly-written tests.
5929 // With the randomness here, as long as the tests pass
5930 // consistently with -race, they shouldn't have latent scheduling
5931 // assumptions.
5932 const randomizeScheduler = raceenabled
5933
5934 // runqput tries to put g on the local runnable queue.
5935 // If next is false, runqput adds g to the tail of the runnable queue.
5936 // If next is true, runqput puts g in the pp.runnext slot.
5937 // If the run queue is full, runnext puts g on the global queue.
5938 // Executed only by the owner P.
5939 func runqput(pp *p, gp *g, next bool) {
5940         if randomizeScheduler && next && fastrandn(2) == 0 {
5941                 next = false
5942         }
5943
5944         if next {
5945         retryNext:
5946                 oldnext := pp.runnext
5947                 if !pp.runnext.cas(oldnext, guintptr(unsafe.Pointer(gp))) {
5948                         goto retryNext
5949                 }
5950                 if oldnext == 0 {
5951                         return
5952                 }
5953                 // Kick the old runnext out to the regular run queue.
5954                 gp = oldnext.ptr()
5955         }
5956
5957 retry:
5958         h := atomic.LoadAcq(&pp.runqhead) // load-acquire, synchronize with consumers
5959         t := pp.runqtail
5960         if t-h < uint32(len(pp.runq)) {
5961                 pp.runq[t%uint32(len(pp.runq))].set(gp)
5962                 atomic.StoreRel(&pp.runqtail, t+1) // store-release, makes the item available for consumption
5963                 return
5964         }
5965         if runqputslow(pp, gp, h, t) {
5966                 return
5967         }
5968         // the queue is not full, now the put above must succeed
5969         goto retry
5970 }
5971
5972 // Put g and a batch of work from local runnable queue on global queue.
5973 // Executed only by the owner P.
5974 func runqputslow(pp *p, gp *g, h, t uint32) bool {
5975         var batch [len(pp.runq)/2 + 1]*g
5976
5977         // First, grab a batch from local queue.
5978         n := t - h
5979         n = n / 2
5980         if n != uint32(len(pp.runq)/2) {
5981                 throw("runqputslow: queue is not full")
5982         }
5983         for i := uint32(0); i < n; i++ {
5984                 batch[i] = pp.runq[(h+i)%uint32(len(pp.runq))].ptr()
5985         }
5986         if !atomic.CasRel(&pp.runqhead, h, h+n) { // cas-release, commits consume
5987                 return false
5988         }
5989         batch[n] = gp
5990
5991         if randomizeScheduler {
5992                 for i := uint32(1); i <= n; i++ {
5993                         j := fastrandn(i + 1)
5994                         batch[i], batch[j] = batch[j], batch[i]
5995                 }
5996         }
5997
5998         // Link the goroutines.
5999         for i := uint32(0); i < n; i++ {
6000                 batch[i].schedlink.set(batch[i+1])
6001         }
6002         var q gQueue
6003         q.head.set(batch[0])
6004         q.tail.set(batch[n])
6005
6006         // Now put the batch on global queue.
6007         lock(&sched.lock)
6008         globrunqputbatch(&q, int32(n+1))
6009         unlock(&sched.lock)
6010         return true
6011 }
6012
6013 // runqputbatch tries to put all the G's on q on the local runnable queue.
6014 // If the queue is full, they are put on the global queue; in that case
6015 // this will temporarily acquire the scheduler lock.
6016 // Executed only by the owner P.
6017 func runqputbatch(pp *p, q *gQueue, qsize int) {
6018         h := atomic.LoadAcq(&pp.runqhead)
6019         t := pp.runqtail
6020         n := uint32(0)
6021         for !q.empty() && t-h < uint32(len(pp.runq)) {
6022                 gp := q.pop()
6023                 pp.runq[t%uint32(len(pp.runq))].set(gp)
6024                 t++
6025                 n++
6026         }
6027         qsize -= int(n)
6028
6029         if randomizeScheduler {
6030                 off := func(o uint32) uint32 {
6031                         return (pp.runqtail + o) % uint32(len(pp.runq))
6032                 }
6033                 for i := uint32(1); i < n; i++ {
6034                         j := fastrandn(i + 1)
6035                         pp.runq[off(i)], pp.runq[off(j)] = pp.runq[off(j)], pp.runq[off(i)]
6036                 }
6037         }
6038
6039         atomic.StoreRel(&pp.runqtail, t)
6040         if !q.empty() {
6041                 lock(&sched.lock)
6042                 globrunqputbatch(q, int32(qsize))
6043                 unlock(&sched.lock)
6044         }
6045 }
6046
6047 // Get g from local runnable queue.
6048 // If inheritTime is true, gp should inherit the remaining time in the
6049 // current time slice. Otherwise, it should start a new time slice.
6050 // Executed only by the owner P.
6051 func runqget(pp *p) (gp *g, inheritTime bool) {
6052         // If there's a runnext, it's the next G to run.
6053         next := pp.runnext
6054         // If the runnext is non-0 and the CAS fails, it could only have been stolen by another P,
6055         // because other Ps can race to set runnext to 0, but only the current P can set it to non-0.
6056         // Hence, there's no need to retry this CAS if it fails.
6057         if next != 0 && pp.runnext.cas(next, 0) {
6058                 return next.ptr(), true
6059         }
6060
6061         for {
6062                 h := atomic.LoadAcq(&pp.runqhead) // load-acquire, synchronize with other consumers
6063                 t := pp.runqtail
6064                 if t == h {
6065                         return nil, false
6066                 }
6067                 gp := pp.runq[h%uint32(len(pp.runq))].ptr()
6068                 if atomic.CasRel(&pp.runqhead, h, h+1) { // cas-release, commits consume
6069                         return gp, false
6070                 }
6071         }
6072 }
6073
6074 // runqdrain drains the local runnable queue of pp and returns all goroutines in it.
6075 // Executed only by the owner P.
6076 func runqdrain(pp *p) (drainQ gQueue, n uint32) {
6077         oldNext := pp.runnext
6078         if oldNext != 0 && pp.runnext.cas(oldNext, 0) {
6079                 drainQ.pushBack(oldNext.ptr())
6080                 n++
6081         }
6082
6083 retry:
6084         h := atomic.LoadAcq(&pp.runqhead) // load-acquire, synchronize with other consumers
6085         t := pp.runqtail
6086         qn := t - h
6087         if qn == 0 {
6088                 return
6089         }
6090         if qn > uint32(len(pp.runq)) { // read inconsistent h and t
6091                 goto retry
6092         }
6093
6094         if !atomic.CasRel(&pp.runqhead, h, h+qn) { // cas-release, commits consume
6095                 goto retry
6096         }
6097
6098         // We've inverted the order in which it gets G's from the local P's runnable queue
6099         // and then advances the head pointer because we don't want to mess up the statuses of G's
6100         // while runqdrain() and runqsteal() are running in parallel.
6101         // Thus we should advance the head pointer before draining the local P into a gQueue,
6102         // so that we can update any gp.schedlink only after we take the full ownership of G,
6103         // meanwhile, other P's can't access to all G's in local P's runnable queue and steal them.
6104         // See https://groups.google.com/g/golang-dev/c/0pTKxEKhHSc/m/6Q85QjdVBQAJ for more details.
6105         for i := uint32(0); i < qn; i++ {
6106                 gp := pp.runq[(h+i)%uint32(len(pp.runq))].ptr()
6107                 drainQ.pushBack(gp)
6108                 n++
6109         }
6110         return
6111 }
6112
6113 // Grabs a batch of goroutines from pp's runnable queue into batch.
6114 // Batch is a ring buffer starting at batchHead.
6115 // Returns number of grabbed goroutines.
6116 // Can be executed by any P.
6117 func runqgrab(pp *p, batch *[256]guintptr, batchHead uint32, stealRunNextG bool) uint32 {
6118         for {
6119                 h := atomic.LoadAcq(&pp.runqhead) // load-acquire, synchronize with other consumers
6120                 t := atomic.LoadAcq(&pp.runqtail) // load-acquire, synchronize with the producer
6121                 n := t - h
6122                 n = n - n/2
6123                 if n == 0 {
6124                         if stealRunNextG {
6125                                 // Try to steal from pp.runnext.
6126                                 if next := pp.runnext; next != 0 {
6127                                         if pp.status == _Prunning {
6128                                                 // Sleep to ensure that pp isn't about to run the g
6129                                                 // we are about to steal.
6130                                                 // The important use case here is when the g running
6131                                                 // on pp ready()s another g and then almost
6132                                                 // immediately blocks. Instead of stealing runnext
6133                                                 // in this window, back off to give pp a chance to
6134                                                 // schedule runnext. This will avoid thrashing gs
6135                                                 // between different Ps.
6136                                                 // A sync chan send/recv takes ~50ns as of time of
6137                                                 // writing, so 3us gives ~50x overshoot.
6138                                                 if GOOS != "windows" && GOOS != "openbsd" && GOOS != "netbsd" {
6139                                                         usleep(3)
6140                                                 } else {
6141                                                         // On some platforms system timer granularity is
6142                                                         // 1-15ms, which is way too much for this
6143                                                         // optimization. So just yield.
6144                                                         osyield()
6145                                                 }
6146                                         }
6147                                         if !pp.runnext.cas(next, 0) {
6148                                                 continue
6149                                         }
6150                                         batch[batchHead%uint32(len(batch))] = next
6151                                         return 1
6152                                 }
6153                         }
6154                         return 0
6155                 }
6156                 if n > uint32(len(pp.runq)/2) { // read inconsistent h and t
6157                         continue
6158                 }
6159                 for i := uint32(0); i < n; i++ {
6160                         g := pp.runq[(h+i)%uint32(len(pp.runq))]
6161                         batch[(batchHead+i)%uint32(len(batch))] = g
6162                 }
6163                 if atomic.CasRel(&pp.runqhead, h, h+n) { // cas-release, commits consume
6164                         return n
6165                 }
6166         }
6167 }
6168
6169 // Steal half of elements from local runnable queue of p2
6170 // and put onto local runnable queue of p.
6171 // Returns one of the stolen elements (or nil if failed).
6172 func runqsteal(pp, p2 *p, stealRunNextG bool) *g {
6173         t := pp.runqtail
6174         n := runqgrab(p2, &pp.runq, t, stealRunNextG)
6175         if n == 0 {
6176                 return nil
6177         }
6178         n--
6179         gp := pp.runq[(t+n)%uint32(len(pp.runq))].ptr()
6180         if n == 0 {
6181                 return gp
6182         }
6183         h := atomic.LoadAcq(&pp.runqhead) // load-acquire, synchronize with consumers
6184         if t-h+n >= uint32(len(pp.runq)) {
6185                 throw("runqsteal: runq overflow")
6186         }
6187         atomic.StoreRel(&pp.runqtail, t+n) // store-release, makes the item available for consumption
6188         return gp
6189 }
6190
6191 // A gQueue is a dequeue of Gs linked through g.schedlink. A G can only
6192 // be on one gQueue or gList at a time.
6193 type gQueue struct {
6194         head guintptr
6195         tail guintptr
6196 }
6197
6198 // empty reports whether q is empty.
6199 func (q *gQueue) empty() bool {
6200         return q.head == 0
6201 }
6202
6203 // push adds gp to the head of q.
6204 func (q *gQueue) push(gp *g) {
6205         gp.schedlink = q.head
6206         q.head.set(gp)
6207         if q.tail == 0 {
6208                 q.tail.set(gp)
6209         }
6210 }
6211
6212 // pushBack adds gp to the tail of q.
6213 func (q *gQueue) pushBack(gp *g) {
6214         gp.schedlink = 0
6215         if q.tail != 0 {
6216                 q.tail.ptr().schedlink.set(gp)
6217         } else {
6218                 q.head.set(gp)
6219         }
6220         q.tail.set(gp)
6221 }
6222
6223 // pushBackAll adds all Gs in q2 to the tail of q. After this q2 must
6224 // not be used.
6225 func (q *gQueue) pushBackAll(q2 gQueue) {
6226         if q2.tail == 0 {
6227                 return
6228         }
6229         q2.tail.ptr().schedlink = 0
6230         if q.tail != 0 {
6231                 q.tail.ptr().schedlink = q2.head
6232         } else {
6233                 q.head = q2.head
6234         }
6235         q.tail = q2.tail
6236 }
6237
6238 // pop removes and returns the head of queue q. It returns nil if
6239 // q is empty.
6240 func (q *gQueue) pop() *g {
6241         gp := q.head.ptr()
6242         if gp != nil {
6243                 q.head = gp.schedlink
6244                 if q.head == 0 {
6245                         q.tail = 0
6246                 }
6247         }
6248         return gp
6249 }
6250
6251 // popList takes all Gs in q and returns them as a gList.
6252 func (q *gQueue) popList() gList {
6253         stack := gList{q.head}
6254         *q = gQueue{}
6255         return stack
6256 }
6257
6258 // A gList is a list of Gs linked through g.schedlink. A G can only be
6259 // on one gQueue or gList at a time.
6260 type gList struct {
6261         head guintptr
6262 }
6263
6264 // empty reports whether l is empty.
6265 func (l *gList) empty() bool {
6266         return l.head == 0
6267 }
6268
6269 // push adds gp to the head of l.
6270 func (l *gList) push(gp *g) {
6271         gp.schedlink = l.head
6272         l.head.set(gp)
6273 }
6274
6275 // pushAll prepends all Gs in q to l.
6276 func (l *gList) pushAll(q gQueue) {
6277         if !q.empty() {
6278                 q.tail.ptr().schedlink = l.head
6279                 l.head = q.head
6280         }
6281 }
6282
6283 // pop removes and returns the head of l. If l is empty, it returns nil.
6284 func (l *gList) pop() *g {
6285         gp := l.head.ptr()
6286         if gp != nil {
6287                 l.head = gp.schedlink
6288         }
6289         return gp
6290 }
6291
6292 //go:linkname setMaxThreads runtime/debug.setMaxThreads
6293 func setMaxThreads(in int) (out int) {
6294         lock(&sched.lock)
6295         out = int(sched.maxmcount)
6296         if in > 0x7fffffff { // MaxInt32
6297                 sched.maxmcount = 0x7fffffff
6298         } else {
6299                 sched.maxmcount = int32(in)
6300         }
6301         checkmcount()
6302         unlock(&sched.lock)
6303         return
6304 }
6305
6306 //go:nosplit
6307 func procPin() int {
6308         gp := getg()
6309         mp := gp.m
6310
6311         mp.locks++
6312         return int(mp.p.ptr().id)
6313 }
6314
6315 //go:nosplit
6316 func procUnpin() {
6317         gp := getg()
6318         gp.m.locks--
6319 }
6320
6321 //go:linkname sync_runtime_procPin sync.runtime_procPin
6322 //go:nosplit
6323 func sync_runtime_procPin() int {
6324         return procPin()
6325 }
6326
6327 //go:linkname sync_runtime_procUnpin sync.runtime_procUnpin
6328 //go:nosplit
6329 func sync_runtime_procUnpin() {
6330         procUnpin()
6331 }
6332
6333 //go:linkname sync_atomic_runtime_procPin sync/atomic.runtime_procPin
6334 //go:nosplit
6335 func sync_atomic_runtime_procPin() int {
6336         return procPin()
6337 }
6338
6339 //go:linkname sync_atomic_runtime_procUnpin sync/atomic.runtime_procUnpin
6340 //go:nosplit
6341 func sync_atomic_runtime_procUnpin() {
6342         procUnpin()
6343 }
6344
6345 // Active spinning for sync.Mutex.
6346 //
6347 //go:linkname sync_runtime_canSpin sync.runtime_canSpin
6348 //go:nosplit
6349 func sync_runtime_canSpin(i int) bool {
6350         // sync.Mutex is cooperative, so we are conservative with spinning.
6351         // Spin only few times and only if running on a multicore machine and
6352         // GOMAXPROCS>1 and there is at least one other running P and local runq is empty.
6353         // As opposed to runtime mutex we don't do passive spinning here,
6354         // because there can be work on global runq or on other Ps.
6355         if i >= active_spin || ncpu <= 1 || gomaxprocs <= sched.npidle.Load()+sched.nmspinning.Load()+1 {
6356                 return false
6357         }
6358         if p := getg().m.p.ptr(); !runqempty(p) {
6359                 return false
6360         }
6361         return true
6362 }
6363
6364 //go:linkname sync_runtime_doSpin sync.runtime_doSpin
6365 //go:nosplit
6366 func sync_runtime_doSpin() {
6367         procyield(active_spin_cnt)
6368 }
6369
6370 var stealOrder randomOrder
6371
6372 // randomOrder/randomEnum are helper types for randomized work stealing.
6373 // They allow to enumerate all Ps in different pseudo-random orders without repetitions.
6374 // The algorithm is based on the fact that if we have X such that X and GOMAXPROCS
6375 // are coprime, then a sequences of (i + X) % GOMAXPROCS gives the required enumeration.
6376 type randomOrder struct {
6377         count    uint32
6378         coprimes []uint32
6379 }
6380
6381 type randomEnum struct {
6382         i     uint32
6383         count uint32
6384         pos   uint32
6385         inc   uint32
6386 }
6387
6388 func (ord *randomOrder) reset(count uint32) {
6389         ord.count = count
6390         ord.coprimes = ord.coprimes[:0]
6391         for i := uint32(1); i <= count; i++ {
6392                 if gcd(i, count) == 1 {
6393                         ord.coprimes = append(ord.coprimes, i)
6394                 }
6395         }
6396 }
6397
6398 func (ord *randomOrder) start(i uint32) randomEnum {
6399         return randomEnum{
6400                 count: ord.count,
6401                 pos:   i % ord.count,
6402                 inc:   ord.coprimes[i/ord.count%uint32(len(ord.coprimes))],
6403         }
6404 }
6405
6406 func (enum *randomEnum) done() bool {
6407         return enum.i == enum.count
6408 }
6409
6410 func (enum *randomEnum) next() {
6411         enum.i++
6412         enum.pos = (enum.pos + enum.inc) % enum.count
6413 }
6414
6415 func (enum *randomEnum) position() uint32 {
6416         return enum.pos
6417 }
6418
6419 func gcd(a, b uint32) uint32 {
6420         for b != 0 {
6421                 a, b = b, a%b
6422         }
6423         return a
6424 }
6425
6426 // An initTask represents the set of initializations that need to be done for a package.
6427 // Keep in sync with ../../test/initempty.go:initTask
6428 type initTask struct {
6429         // TODO: pack the first 3 fields more tightly?
6430         state uintptr // 0 = uninitialized, 1 = in progress, 2 = done
6431         ndeps uintptr
6432         nfns  uintptr
6433         // followed by ndeps instances of an *initTask, one per package depended on
6434         // followed by nfns pcs, one per init function to run
6435 }
6436
6437 // inittrace stores statistics for init functions which are
6438 // updated by malloc and newproc when active is true.
6439 var inittrace tracestat
6440
6441 type tracestat struct {
6442         active bool   // init tracing activation status
6443         id     uint64 // init goroutine id
6444         allocs uint64 // heap allocations
6445         bytes  uint64 // heap allocated bytes
6446 }
6447
6448 func doInit(t *initTask) {
6449         switch t.state {
6450         case 2: // fully initialized
6451                 return
6452         case 1: // initialization in progress
6453                 throw("recursive call during initialization - linker skew")
6454         default: // not initialized yet
6455                 t.state = 1 // initialization in progress
6456
6457                 for i := uintptr(0); i < t.ndeps; i++ {
6458                         p := add(unsafe.Pointer(t), (3+i)*goarch.PtrSize)
6459                         t2 := *(**initTask)(p)
6460                         doInit(t2)
6461                 }
6462
6463                 if t.nfns == 0 {
6464                         t.state = 2 // initialization done
6465                         return
6466                 }
6467
6468                 var (
6469                         start  int64
6470                         before tracestat
6471                 )
6472
6473                 if inittrace.active {
6474                         start = nanotime()
6475                         // Load stats non-atomically since tracinit is updated only by this init goroutine.
6476                         before = inittrace
6477                 }
6478
6479                 firstFunc := add(unsafe.Pointer(t), (3+t.ndeps)*goarch.PtrSize)
6480                 for i := uintptr(0); i < t.nfns; i++ {
6481                         p := add(firstFunc, i*goarch.PtrSize)
6482                         f := *(*func())(unsafe.Pointer(&p))
6483                         f()
6484                 }
6485
6486                 if inittrace.active {
6487                         end := nanotime()
6488                         // Load stats non-atomically since tracinit is updated only by this init goroutine.
6489                         after := inittrace
6490
6491                         f := *(*func())(unsafe.Pointer(&firstFunc))
6492                         pkg := funcpkgpath(findfunc(abi.FuncPCABIInternal(f)))
6493
6494                         var sbuf [24]byte
6495                         print("init ", pkg, " @")
6496                         print(string(fmtNSAsMS(sbuf[:], uint64(start-runtimeInitTime))), " ms, ")
6497                         print(string(fmtNSAsMS(sbuf[:], uint64(end-start))), " ms clock, ")
6498                         print(string(itoa(sbuf[:], after.bytes-before.bytes)), " bytes, ")
6499                         print(string(itoa(sbuf[:], after.allocs-before.allocs)), " allocs")
6500                         print("\n")
6501                 }
6502
6503                 t.state = 2 // initialization done
6504         }
6505 }