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

View as plain text