Source file src/runtime/proc.go

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

View as plain text