Source file src/runtime/proc.go

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

View as plain text