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

View as plain text