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