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

View as plain text