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

View as plain text