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  
  2459  	// This is technically inaccurate, but we set isExtraInC to false above,
  2460  	// and so we need to update addGSyscallNoP to keep the two pieces of state
  2461  	// consistent (it's only updated when isExtraInC is false). More specifically,
  2462  	// When we get to cgocallbackg and exitsyscall, we'll be looking for a P, and
  2463  	// since isExtraInC is false, we will decrement this metric.
  2464  	//
  2465  	// The inaccuracy is thankfully transient: only until this thread can get a P.
  2466  	// We're going into Go anyway, so it's okay to pretend we're a real goroutine now.
  2467  	addGSyscallNoP(mp)
  2468  
  2469  	if !signal {
  2470  		if trace.ok() {
  2471  			trace.GoCreateSyscall(mp.curg)
  2472  			traceRelease(trace)
  2473  		}
  2474  	}
  2475  	mp.isExtraInSig = signal
  2476  }
  2477  
  2478  // Acquire an extra m and bind it to the C thread when a pthread key has been created.
  2479  //
  2480  //go:nosplit
  2481  func needAndBindM() {
  2482  	needm(false)
  2483  
  2484  	if _cgo_pthread_key_created != nil && *(*uintptr)(_cgo_pthread_key_created) != 0 {
  2485  		cgoBindM()
  2486  	}
  2487  }
  2488  
  2489  // newextram allocates m's and puts them on the extra list.
  2490  // It is called with a working local m, so that it can do things
  2491  // like call schedlock and allocate.
  2492  func newextram() {
  2493  	c := extraMWaiters.Swap(0)
  2494  	if c > 0 {
  2495  		for i := uint32(0); i < c; i++ {
  2496  			oneNewExtraM()
  2497  		}
  2498  	} else if extraMLength.Load() == 0 {
  2499  		// Make sure there is at least one extra M.
  2500  		oneNewExtraM()
  2501  	}
  2502  }
  2503  
  2504  // oneNewExtraM allocates an m and puts it on the extra list.
  2505  func oneNewExtraM() {
  2506  	// Create extra goroutine locked to extra m.
  2507  	// The goroutine is the context in which the cgo callback will run.
  2508  	// The sched.pc will never be returned to, but setting it to
  2509  	// goexit makes clear to the traceback routines where
  2510  	// the goroutine stack ends.
  2511  	mp := allocm(nil, nil, -1)
  2512  	gp := malg(4096)
  2513  	gp.sched.pc = abi.FuncPCABI0(goexit) + sys.PCQuantum
  2514  	gp.sched.sp = gp.stack.hi
  2515  	gp.sched.sp -= 4 * goarch.PtrSize // extra space in case of reads slightly beyond frame
  2516  	gp.sched.lr = 0
  2517  	gp.sched.g = guintptr(unsafe.Pointer(gp))
  2518  	gp.syscallpc = gp.sched.pc
  2519  	gp.syscallsp = gp.sched.sp
  2520  	gp.stktopsp = gp.sched.sp
  2521  	// malg returns status as _Gidle. Change to _Gdeadextra before
  2522  	// adding to allg where GC can see it. _Gdeadextra hides this
  2523  	// from traceback and stack scans.
  2524  	casgstatus(gp, _Gidle, _Gdeadextra)
  2525  	gp.m = mp
  2526  	mp.curg = gp
  2527  	mp.isextra = true
  2528  	// mark we are in C by default.
  2529  	mp.isExtraInC = true
  2530  	mp.lockedInt++
  2531  	mp.lockedg.set(gp)
  2532  	gp.lockedm.set(mp)
  2533  	gp.goid = sched.goidgen.Add(1)
  2534  	if raceenabled {
  2535  		gp.racectx = racegostart(abi.FuncPCABIInternal(newextram) + sys.PCQuantum)
  2536  	}
  2537  	// put on allg for garbage collector
  2538  	allgadd(gp)
  2539  
  2540  	// gp is now on the allg list, but we don't want it to be
  2541  	// counted by gcount. It would be more "proper" to increment
  2542  	// sched.ngfree, but that requires locking. Incrementing ngsys
  2543  	// has the same effect.
  2544  	sched.ngsys.Add(1)
  2545  
  2546  	// Add m to the extra list.
  2547  	addExtraM(mp)
  2548  }
  2549  
  2550  // dropm puts the current m back onto the extra list.
  2551  //
  2552  // 1. On systems without pthreads, like Windows
  2553  // dropm is called when a cgo callback has called needm but is now
  2554  // done with the callback and returning back into the non-Go thread.
  2555  //
  2556  // The main expense here is the call to signalstack to release the
  2557  // m's signal stack, and then the call to needm on the next callback
  2558  // from this thread. It is tempting to try to save the m for next time,
  2559  // which would eliminate both these costs, but there might not be
  2560  // a next time: the current thread (which Go does not control) might exit.
  2561  // If we saved the m for that thread, there would be an m leak each time
  2562  // such a thread exited. Instead, we acquire and release an m on each
  2563  // call. These should typically not be scheduling operations, just a few
  2564  // atomics, so the cost should be small.
  2565  //
  2566  // 2. On systems with pthreads
  2567  // dropm is called while a non-Go thread is exiting.
  2568  // We allocate a pthread per-thread variable using pthread_key_create,
  2569  // to register a thread-exit-time destructor.
  2570  // And store the g into a thread-specific value associated with the pthread key,
  2571  // when first return back to C.
  2572  // So that the destructor would invoke dropm while the non-Go thread is exiting.
  2573  // This is much faster since it avoids expensive signal-related syscalls.
  2574  //
  2575  // This may run without a P, so //go:nowritebarrierrec is required.
  2576  //
  2577  // This may run with a different stack than was recorded in g0 (there is no
  2578  // call to callbackUpdateSystemStack prior to dropm), so this must be
  2579  // //go:nosplit to avoid the stack bounds check.
  2580  //
  2581  //go:nowritebarrierrec
  2582  //go:nosplit
  2583  func dropm() {
  2584  	// Clear m and g, and return m to the extra list.
  2585  	// After the call to setg we can only call nosplit functions
  2586  	// with no pointer manipulation.
  2587  	mp := getg().m
  2588  
  2589  	// Emit a trace event for this syscall -> dead transition.
  2590  	//
  2591  	// N.B. the tracer can run on a bare M just fine, we just have
  2592  	// to make sure to do this before setg(nil) and unminit.
  2593  	var trace traceLocker
  2594  	if !mp.isExtraInSig {
  2595  		trace = traceAcquire()
  2596  	}
  2597  
  2598  	// Return mp.curg to _Gdeadextra state.
  2599  	casgstatus(mp.curg, _Gsyscall, _Gdeadextra)
  2600  	mp.curg.preemptStop = false
  2601  	sched.ngsys.Add(1)
  2602  	decGSyscallNoP(mp)
  2603  
  2604  	if !mp.isExtraInSig {
  2605  		if trace.ok() {
  2606  			trace.GoDestroySyscall()
  2607  			traceRelease(trace)
  2608  		}
  2609  	}
  2610  
  2611  	// Trash syscalltick so that it doesn't line up with mp.old.syscalltick anymore.
  2612  	//
  2613  	// In the new tracer, we model needm and dropm and a goroutine being created and
  2614  	// destroyed respectively. The m then might get reused with a different procid but
  2615  	// still with a reference to oldp, and still with the same syscalltick. The next
  2616  	// time a G is "created" in needm, it'll return and quietly reacquire its P from a
  2617  	// different m with a different procid, which will confuse the trace parser. By
  2618  	// trashing syscalltick, we ensure that it'll appear as if we lost the P to the
  2619  	// tracer parser and that we just reacquired it.
  2620  	//
  2621  	// Trash the value by decrementing because that gets us as far away from the value
  2622  	// the syscall exit code expects as possible. Setting to zero is risky because
  2623  	// syscalltick could already be zero (and in fact, is initialized to zero).
  2624  	mp.syscalltick--
  2625  
  2626  	// Reset trace state unconditionally. This goroutine is being 'destroyed'
  2627  	// from the perspective of the tracer.
  2628  	mp.curg.trace.reset()
  2629  
  2630  	// Flush all the M's buffers. This is necessary because the M might
  2631  	// be used on a different thread with a different procid, so we have
  2632  	// to make sure we don't write into the same buffer.
  2633  	if traceEnabled() || traceShuttingDown() {
  2634  		// Acquire sched.lock across thread destruction. One of the invariants of the tracer
  2635  		// is that a thread cannot disappear from the tracer's view (allm or freem) without
  2636  		// it noticing, so it requires that sched.lock be held over traceThreadDestroy.
  2637  		//
  2638  		// This isn't strictly necessary in this case, because this thread never leaves allm,
  2639  		// but the critical section is short and dropm is rare on pthread platforms, so just
  2640  		// take the lock and play it safe. traceThreadDestroy also asserts that the lock is held.
  2641  		lock(&sched.lock)
  2642  		traceThreadDestroy(mp)
  2643  		unlock(&sched.lock)
  2644  	}
  2645  	mp.isExtraInSig = false
  2646  
  2647  	// Block signals before unminit.
  2648  	// Unminit unregisters the signal handling stack (but needs g on some systems).
  2649  	// Setg(nil) clears g, which is the signal handler's cue not to run Go handlers.
  2650  	// It's important not to try to handle a signal between those two steps.
  2651  	sigmask := mp.sigmask
  2652  	sigblock(false)
  2653  	unminit()
  2654  
  2655  	setg(nil)
  2656  
  2657  	// Clear g0 stack bounds to ensure that needm always refreshes the
  2658  	// bounds when reusing this M.
  2659  	g0 := mp.g0
  2660  	g0.stack.hi = 0
  2661  	g0.stack.lo = 0
  2662  	g0.stackguard0 = 0
  2663  	g0.stackguard1 = 0
  2664  	mp.g0StackAccurate = false
  2665  
  2666  	putExtraM(mp)
  2667  
  2668  	msigrestore(sigmask)
  2669  }
  2670  
  2671  // bindm store the g0 of the current m into a thread-specific value.
  2672  //
  2673  // We allocate a pthread per-thread variable using pthread_key_create,
  2674  // to register a thread-exit-time destructor.
  2675  // We are here setting the thread-specific value of the pthread key, to enable the destructor.
  2676  // So that the pthread_key_destructor would dropm while the C thread is exiting.
  2677  //
  2678  // And the saved g will be used in pthread_key_destructor,
  2679  // since the g stored in the TLS by Go might be cleared in some platforms,
  2680  // before the destructor invoked, so, we restore g by the stored g, before dropm.
  2681  //
  2682  // We store g0 instead of m, to make the assembly code simpler,
  2683  // since we need to restore g0 in runtime.cgocallback.
  2684  //
  2685  // On systems without pthreads, like Windows, bindm shouldn't be used.
  2686  //
  2687  // NOTE: this always runs without a P, so, nowritebarrierrec required.
  2688  //
  2689  //go:nosplit
  2690  //go:nowritebarrierrec
  2691  func cgoBindM() {
  2692  	if GOOS == "windows" || GOOS == "plan9" {
  2693  		fatal("bindm in unexpected GOOS")
  2694  	}
  2695  	g := getg()
  2696  	if g.m.g0 != g {
  2697  		fatal("the current g is not g0")
  2698  	}
  2699  	if _cgo_bindm != nil {
  2700  		asmcgocall(_cgo_bindm, unsafe.Pointer(g))
  2701  	}
  2702  }
  2703  
  2704  // A helper function for EnsureDropM.
  2705  //
  2706  // getm should be an internal detail,
  2707  // but widely used packages access it using linkname.
  2708  // Notable members of the hall of shame include:
  2709  //   - fortio.org/log
  2710  //
  2711  // Do not remove or change the type signature.
  2712  // See go.dev/issue/67401.
  2713  //
  2714  //go:linkname getm
  2715  func getm() uintptr {
  2716  	return uintptr(unsafe.Pointer(getg().m))
  2717  }
  2718  
  2719  var (
  2720  	// Locking linked list of extra M's, via mp.schedlink. Must be accessed
  2721  	// only via lockextra/unlockextra.
  2722  	//
  2723  	// Can't be atomic.Pointer[m] because we use an invalid pointer as a
  2724  	// "locked" sentinel value. M's on this list remain visible to the GC
  2725  	// because their mp.curg is on allgs.
  2726  	extraM atomic.Uintptr
  2727  	// Number of M's in the extraM list.
  2728  	extraMLength atomic.Uint32
  2729  	// Number of waiters in lockextra.
  2730  	extraMWaiters atomic.Uint32
  2731  
  2732  	// Number of extra M's in use by threads.
  2733  	extraMInUse atomic.Uint32
  2734  )
  2735  
  2736  // lockextra locks the extra list and returns the list head.
  2737  // The caller must unlock the list by storing a new list head
  2738  // to extram. If nilokay is true, then lockextra will
  2739  // return a nil list head if that's what it finds. If nilokay is false,
  2740  // lockextra will keep waiting until the list head is no longer nil.
  2741  //
  2742  //go:nosplit
  2743  func lockextra(nilokay bool) *m {
  2744  	const locked = 1
  2745  
  2746  	incr := false
  2747  	for {
  2748  		old := extraM.Load()
  2749  		if old == locked {
  2750  			osyield_no_g()
  2751  			continue
  2752  		}
  2753  		if old == 0 && !nilokay {
  2754  			if !incr {
  2755  				// Add 1 to the number of threads
  2756  				// waiting for an M.
  2757  				// This is cleared by newextram.
  2758  				extraMWaiters.Add(1)
  2759  				incr = true
  2760  			}
  2761  			usleep_no_g(1)
  2762  			continue
  2763  		}
  2764  		if extraM.CompareAndSwap(old, locked) {
  2765  			return (*m)(unsafe.Pointer(old))
  2766  		}
  2767  		osyield_no_g()
  2768  		continue
  2769  	}
  2770  }
  2771  
  2772  //go:nosplit
  2773  func unlockextra(mp *m, delta int32) {
  2774  	extraMLength.Add(delta)
  2775  	extraM.Store(uintptr(unsafe.Pointer(mp)))
  2776  }
  2777  
  2778  // Return an M from the extra M list. Returns last == true if the list becomes
  2779  // empty because of this call.
  2780  //
  2781  // Spins waiting for an extra M, so caller must ensure that the list always
  2782  // contains or will soon contain at least one M.
  2783  //
  2784  //go:nosplit
  2785  func getExtraM() (mp *m, last bool) {
  2786  	mp = lockextra(false)
  2787  	extraMInUse.Add(1)
  2788  	unlockextra(mp.schedlink.ptr(), -1)
  2789  	return mp, mp.schedlink.ptr() == nil
  2790  }
  2791  
  2792  // Returns an extra M back to the list. mp must be from getExtraM. Newly
  2793  // allocated M's should use addExtraM.
  2794  //
  2795  //go:nosplit
  2796  func putExtraM(mp *m) {
  2797  	extraMInUse.Add(-1)
  2798  	addExtraM(mp)
  2799  }
  2800  
  2801  // Adds a newly allocated M to the extra M list.
  2802  //
  2803  //go:nosplit
  2804  func addExtraM(mp *m) {
  2805  	mnext := lockextra(true)
  2806  	mp.schedlink.set(mnext)
  2807  	unlockextra(mp, 1)
  2808  }
  2809  
  2810  var (
  2811  	// allocmLock is locked for read when creating new Ms in allocm and their
  2812  	// addition to allm. Thus acquiring this lock for write blocks the
  2813  	// creation of new Ms.
  2814  	allocmLock rwmutex
  2815  
  2816  	// execLock serializes exec and clone to avoid bugs or unspecified
  2817  	// behaviour around exec'ing while creating/destroying threads. See
  2818  	// issue #19546.
  2819  	execLock rwmutex
  2820  )
  2821  
  2822  // These errors are reported (via writeErrStr) by some OS-specific
  2823  // versions of newosproc and newosproc0.
  2824  const (
  2825  	failthreadcreate  = "runtime: failed to create new OS thread\n"
  2826  	failallocatestack = "runtime: failed to allocate stack for the new OS thread\n"
  2827  )
  2828  
  2829  // newmHandoff contains a list of m structures that need new OS threads.
  2830  // This is used by newm in situations where newm itself can't safely
  2831  // start an OS thread.
  2832  var newmHandoff struct {
  2833  	lock mutex
  2834  
  2835  	// newm points to a list of M structures that need new OS
  2836  	// threads. The list is linked through m.schedlink.
  2837  	newm muintptr
  2838  
  2839  	// waiting indicates that wake needs to be notified when an m
  2840  	// is put on the list.
  2841  	waiting bool
  2842  	wake    note
  2843  
  2844  	// haveTemplateThread indicates that the templateThread has
  2845  	// been started. This is not protected by lock. Use cas to set
  2846  	// to 1.
  2847  	haveTemplateThread uint32
  2848  }
  2849  
  2850  // Create a new m. It will start off with a call to fn, or else the scheduler.
  2851  // fn needs to be static and not a heap allocated closure.
  2852  // May run with m.p==nil, so write barriers are not allowed.
  2853  //
  2854  // id is optional pre-allocated m ID. Omit by passing -1.
  2855  //
  2856  //go:nowritebarrierrec
  2857  func newm(fn func(), pp *p, id int64) {
  2858  	// allocm adds a new M to allm, but they do not start until created by
  2859  	// the OS in newm1 or the template thread.
  2860  	//
  2861  	// doAllThreadsSyscall requires that every M in allm will eventually
  2862  	// start and be signal-able, even with a STW.
  2863  	//
  2864  	// Disable preemption here until we start the thread to ensure that
  2865  	// newm is not preempted between allocm and starting the new thread,
  2866  	// ensuring that anything added to allm is guaranteed to eventually
  2867  	// start.
  2868  	acquirem()
  2869  
  2870  	mp := allocm(pp, fn, id)
  2871  	mp.nextp.set(pp)
  2872  	mp.sigmask = initSigmask
  2873  	if gp := getg(); gp != nil && gp.m != nil && (gp.m.lockedExt != 0 || gp.m.incgo) && GOOS != "plan9" {
  2874  		// We're on a locked M or a thread that may have been
  2875  		// started by C. The kernel state of this thread may
  2876  		// be strange (the user may have locked it for that
  2877  		// purpose). We don't want to clone that into another
  2878  		// thread. Instead, ask a known-good thread to create
  2879  		// the thread for us.
  2880  		//
  2881  		// This is disabled on Plan 9. See golang.org/issue/22227.
  2882  		//
  2883  		// TODO: This may be unnecessary on Windows, which
  2884  		// doesn't model thread creation off fork.
  2885  		lock(&newmHandoff.lock)
  2886  		if newmHandoff.haveTemplateThread == 0 {
  2887  			throw("on a locked thread with no template thread")
  2888  		}
  2889  		mp.schedlink = newmHandoff.newm
  2890  		newmHandoff.newm.set(mp)
  2891  		if newmHandoff.waiting {
  2892  			newmHandoff.waiting = false
  2893  			notewakeup(&newmHandoff.wake)
  2894  		}
  2895  		unlock(&newmHandoff.lock)
  2896  		// The M has not started yet, but the template thread does not
  2897  		// participate in STW, so it will always process queued Ms and
  2898  		// it is safe to releasem.
  2899  		releasem(getg().m)
  2900  		return
  2901  	}
  2902  	newm1(mp)
  2903  	releasem(getg().m)
  2904  }
  2905  
  2906  func newm1(mp *m) {
  2907  	if iscgo {
  2908  		var ts cgothreadstart
  2909  		if _cgo_thread_start == nil {
  2910  			throw("_cgo_thread_start missing")
  2911  		}
  2912  		ts.g.set(mp.g0)
  2913  		ts.tls = (*uint64)(unsafe.Pointer(&mp.tls[0]))
  2914  		ts.fn = unsafe.Pointer(abi.FuncPCABI0(mstart))
  2915  		if msanenabled {
  2916  			msanwrite(unsafe.Pointer(&ts), unsafe.Sizeof(ts))
  2917  		}
  2918  		if asanenabled {
  2919  			asanwrite(unsafe.Pointer(&ts), unsafe.Sizeof(ts))
  2920  		}
  2921  		execLock.rlock() // Prevent process clone.
  2922  		asmcgocall(_cgo_thread_start, unsafe.Pointer(&ts))
  2923  		execLock.runlock()
  2924  		return
  2925  	}
  2926  	execLock.rlock() // Prevent process clone.
  2927  	newosproc(mp)
  2928  	execLock.runlock()
  2929  }
  2930  
  2931  // startTemplateThread starts the template thread if it is not already
  2932  // running.
  2933  //
  2934  // The calling thread must itself be in a known-good state.
  2935  func startTemplateThread() {
  2936  	if GOARCH == "wasm" { // no threads on wasm yet
  2937  		return
  2938  	}
  2939  
  2940  	// Disable preemption to guarantee that the template thread will be
  2941  	// created before a park once haveTemplateThread is set.
  2942  	mp := acquirem()
  2943  	if !atomic.Cas(&newmHandoff.haveTemplateThread, 0, 1) {
  2944  		releasem(mp)
  2945  		return
  2946  	}
  2947  	newm(templateThread, nil, -1)
  2948  	releasem(mp)
  2949  }
  2950  
  2951  // templateThread is a thread in a known-good state that exists solely
  2952  // to start new threads in known-good states when the calling thread
  2953  // may not be in a good state.
  2954  //
  2955  // Many programs never need this, so templateThread is started lazily
  2956  // when we first enter a state that might lead to running on a thread
  2957  // in an unknown state.
  2958  //
  2959  // templateThread runs on an M without a P, so it must not have write
  2960  // barriers.
  2961  //
  2962  //go:nowritebarrierrec
  2963  func templateThread() {
  2964  	lock(&sched.lock)
  2965  	sched.nmsys++
  2966  	checkdead()
  2967  	unlock(&sched.lock)
  2968  
  2969  	for {
  2970  		lock(&newmHandoff.lock)
  2971  		for newmHandoff.newm != 0 {
  2972  			newm := newmHandoff.newm.ptr()
  2973  			newmHandoff.newm = 0
  2974  			unlock(&newmHandoff.lock)
  2975  			for newm != nil {
  2976  				next := newm.schedlink.ptr()
  2977  				newm.schedlink = 0
  2978  				newm1(newm)
  2979  				newm = next
  2980  			}
  2981  			lock(&newmHandoff.lock)
  2982  		}
  2983  		newmHandoff.waiting = true
  2984  		noteclear(&newmHandoff.wake)
  2985  		unlock(&newmHandoff.lock)
  2986  		notesleep(&newmHandoff.wake)
  2987  	}
  2988  }
  2989  
  2990  // Stops execution of the current m until new work is available.
  2991  // Returns with acquired P.
  2992  func stopm() {
  2993  	gp := getg()
  2994  
  2995  	if gp.m.locks != 0 {
  2996  		throw("stopm holding locks")
  2997  	}
  2998  	if gp.m.p != 0 {
  2999  		throw("stopm holding p")
  3000  	}
  3001  	if gp.m.spinning {
  3002  		throw("stopm spinning")
  3003  	}
  3004  
  3005  	lock(&sched.lock)
  3006  	mput(gp.m)
  3007  	unlock(&sched.lock)
  3008  	mPark()
  3009  	acquirep(gp.m.nextp.ptr())
  3010  	gp.m.nextp = 0
  3011  }
  3012  
  3013  func mspinning() {
  3014  	// startm's caller incremented nmspinning. Set the new M's spinning.
  3015  	getg().m.spinning = true
  3016  }
  3017  
  3018  // Schedules some M to run the p (creates an M if necessary).
  3019  // If p==nil, tries to get an idle P, if no idle P's does nothing.
  3020  // May run with m.p==nil, so write barriers are not allowed.
  3021  // If spinning is set, the caller has incremented nmspinning and must provide a
  3022  // P. startm will set m.spinning in the newly started M.
  3023  //
  3024  // Callers passing a non-nil P must call from a non-preemptible context. See
  3025  // comment on acquirem below.
  3026  //
  3027  // Argument lockheld indicates whether the caller already acquired the
  3028  // scheduler lock. Callers holding the lock when making the call must pass
  3029  // true. The lock might be temporarily dropped, but will be reacquired before
  3030  // returning.
  3031  //
  3032  // Must not have write barriers because this may be called without a P.
  3033  //
  3034  //go:nowritebarrierrec
  3035  func startm(pp *p, spinning, lockheld bool) {
  3036  	// Disable preemption.
  3037  	//
  3038  	// Every owned P must have an owner that will eventually stop it in the
  3039  	// event of a GC stop request. startm takes transient ownership of a P
  3040  	// (either from argument or pidleget below) and transfers ownership to
  3041  	// a started M, which will be responsible for performing the stop.
  3042  	//
  3043  	// Preemption must be disabled during this transient ownership,
  3044  	// otherwise the P this is running on may enter GC stop while still
  3045  	// holding the transient P, leaving that P in limbo and deadlocking the
  3046  	// STW.
  3047  	//
  3048  	// Callers passing a non-nil P must already be in non-preemptible
  3049  	// context, otherwise such preemption could occur on function entry to
  3050  	// startm. Callers passing a nil P may be preemptible, so we must
  3051  	// disable preemption before acquiring a P from pidleget below.
  3052  	mp := acquirem()
  3053  	if !lockheld {
  3054  		lock(&sched.lock)
  3055  	}
  3056  	if pp == nil {
  3057  		if spinning {
  3058  			// TODO(prattmic): All remaining calls to this function
  3059  			// with _p_ == nil could be cleaned up to find a P
  3060  			// before calling startm.
  3061  			throw("startm: P required for spinning=true")
  3062  		}
  3063  		pp, _ = pidleget(0)
  3064  		if pp == nil {
  3065  			if !lockheld {
  3066  				unlock(&sched.lock)
  3067  			}
  3068  			releasem(mp)
  3069  			return
  3070  		}
  3071  	}
  3072  	nmp := mget()
  3073  	if nmp == nil {
  3074  		// No M is available, we must drop sched.lock and call newm.
  3075  		// However, we already own a P to assign to the M.
  3076  		//
  3077  		// Once sched.lock is released, another G (e.g., in a syscall),
  3078  		// could find no idle P while checkdead finds a runnable G but
  3079  		// no running M's because this new M hasn't started yet, thus
  3080  		// throwing in an apparent deadlock.
  3081  		// This apparent deadlock is possible when startm is called
  3082  		// from sysmon, which doesn't count as a running M.
  3083  		//
  3084  		// Avoid this situation by pre-allocating the ID for the new M,
  3085  		// thus marking it as 'running' before we drop sched.lock. This
  3086  		// new M will eventually run the scheduler to execute any
  3087  		// queued G's.
  3088  		id := mReserveID()
  3089  		unlock(&sched.lock)
  3090  
  3091  		var fn func()
  3092  		if spinning {
  3093  			// The caller incremented nmspinning, so set m.spinning in the new M.
  3094  			fn = mspinning
  3095  		}
  3096  		newm(fn, pp, id)
  3097  
  3098  		if lockheld {
  3099  			lock(&sched.lock)
  3100  		}
  3101  		// Ownership transfer of pp committed by start in newm.
  3102  		// Preemption is now safe.
  3103  		releasem(mp)
  3104  		return
  3105  	}
  3106  	if !lockheld {
  3107  		unlock(&sched.lock)
  3108  	}
  3109  	if nmp.spinning {
  3110  		throw("startm: m is spinning")
  3111  	}
  3112  	if nmp.nextp != 0 {
  3113  		throw("startm: m has p")
  3114  	}
  3115  	if spinning && !runqempty(pp) {
  3116  		throw("startm: p has runnable gs")
  3117  	}
  3118  	// The caller incremented nmspinning, so set m.spinning in the new M.
  3119  	nmp.spinning = spinning
  3120  	nmp.nextp.set(pp)
  3121  	notewakeup(&nmp.park)
  3122  	// Ownership transfer of pp committed by wakeup. Preemption is now
  3123  	// safe.
  3124  	releasem(mp)
  3125  }
  3126  
  3127  // Hands off P from syscall or locked M.
  3128  // Always runs without a P, so write barriers are not allowed.
  3129  //
  3130  //go:nowritebarrierrec
  3131  func handoffp(pp *p) {
  3132  	// handoffp must start an M in any situation where
  3133  	// findRunnable would return a G to run on pp.
  3134  
  3135  	// if it has local work, start it straight away
  3136  	if !runqempty(pp) || !sched.runq.empty() {
  3137  		startm(pp, false, false)
  3138  		return
  3139  	}
  3140  	// if there's trace work to do, start it straight away
  3141  	if (traceEnabled() || traceShuttingDown()) && traceReaderAvailable() != nil {
  3142  		startm(pp, false, false)
  3143  		return
  3144  	}
  3145  	// if it has GC work, start it straight away
  3146  	if gcBlackenEnabled != 0 && gcShouldScheduleWorker(pp) {
  3147  		startm(pp, false, false)
  3148  		return
  3149  	}
  3150  	// no local work, check that there are no spinning/idle M's,
  3151  	// otherwise our help is not required
  3152  	if sched.nmspinning.Load()+sched.npidle.Load() == 0 && sched.nmspinning.CompareAndSwap(0, 1) { // TODO: fast atomic
  3153  		sched.needspinning.Store(0)
  3154  		startm(pp, true, false)
  3155  		return
  3156  	}
  3157  	lock(&sched.lock)
  3158  	if sched.gcwaiting.Load() {
  3159  		pp.status = _Pgcstop
  3160  		pp.gcStopTime = nanotime()
  3161  		sched.stopwait--
  3162  		if sched.stopwait == 0 {
  3163  			notewakeup(&sched.stopnote)
  3164  		}
  3165  		unlock(&sched.lock)
  3166  		return
  3167  	}
  3168  	if pp.runSafePointFn != 0 && atomic.Cas(&pp.runSafePointFn, 1, 0) {
  3169  		sched.safePointFn(pp)
  3170  		sched.safePointWait--
  3171  		if sched.safePointWait == 0 {
  3172  			notewakeup(&sched.safePointNote)
  3173  		}
  3174  	}
  3175  	if !sched.runq.empty() {
  3176  		unlock(&sched.lock)
  3177  		startm(pp, false, false)
  3178  		return
  3179  	}
  3180  	// If this is the last running P and nobody is polling network,
  3181  	// need to wakeup another M to poll network.
  3182  	if sched.npidle.Load() == gomaxprocs-1 && sched.lastpoll.Load() != 0 {
  3183  		unlock(&sched.lock)
  3184  		startm(pp, false, false)
  3185  		return
  3186  	}
  3187  
  3188  	// The scheduler lock cannot be held when calling wakeNetPoller below
  3189  	// because wakeNetPoller may call wakep which may call startm.
  3190  	when := pp.timers.wakeTime()
  3191  	pidleput(pp, 0)
  3192  	unlock(&sched.lock)
  3193  
  3194  	if when != 0 {
  3195  		wakeNetPoller(when)
  3196  	}
  3197  }
  3198  
  3199  // Tries to add one more P to execute G's.
  3200  // Called when a G is made runnable (newproc, ready).
  3201  // Must be called with a P.
  3202  //
  3203  // wakep should be an internal detail,
  3204  // but widely used packages access it using linkname.
  3205  // Notable members of the hall of shame include:
  3206  //   - gvisor.dev/gvisor
  3207  //
  3208  // Do not remove or change the type signature.
  3209  // See go.dev/issue/67401.
  3210  //
  3211  //go:linkname wakep
  3212  func wakep() {
  3213  	// Be conservative about spinning threads, only start one if none exist
  3214  	// already.
  3215  	if sched.nmspinning.Load() != 0 || !sched.nmspinning.CompareAndSwap(0, 1) {
  3216  		return
  3217  	}
  3218  
  3219  	// Disable preemption until ownership of pp transfers to the next M in
  3220  	// startm. Otherwise preemption here would leave pp stuck waiting to
  3221  	// enter _Pgcstop.
  3222  	//
  3223  	// See preemption comment on acquirem in startm for more details.
  3224  	mp := acquirem()
  3225  
  3226  	var pp *p
  3227  	lock(&sched.lock)
  3228  	pp, _ = pidlegetSpinning(0)
  3229  	if pp == nil {
  3230  		if sched.nmspinning.Add(-1) < 0 {
  3231  			throw("wakep: negative nmspinning")
  3232  		}
  3233  		unlock(&sched.lock)
  3234  		releasem(mp)
  3235  		return
  3236  	}
  3237  	// Since we always have a P, the race in the "No M is available"
  3238  	// comment in startm doesn't apply during the small window between the
  3239  	// unlock here and lock in startm. A checkdead in between will always
  3240  	// see at least one running M (ours).
  3241  	unlock(&sched.lock)
  3242  
  3243  	startm(pp, true, false)
  3244  
  3245  	releasem(mp)
  3246  }
  3247  
  3248  // Stops execution of the current m that is locked to a g until the g is runnable again.
  3249  // Returns with acquired P.
  3250  func stoplockedm() {
  3251  	gp := getg()
  3252  
  3253  	if gp.m.lockedg == 0 || gp.m.lockedg.ptr().lockedm.ptr() != gp.m {
  3254  		throw("stoplockedm: inconsistent locking")
  3255  	}
  3256  	if gp.m.p != 0 {
  3257  		// Schedule another M to run this p.
  3258  		pp := releasep()
  3259  		handoffp(pp)
  3260  	}
  3261  	incidlelocked(1)
  3262  	// Wait until another thread schedules lockedg again.
  3263  	mPark()
  3264  	status := readgstatus(gp.m.lockedg.ptr())
  3265  	if status&^_Gscan != _Grunnable {
  3266  		print("runtime:stoplockedm: lockedg (atomicstatus=", status, ") is not Grunnable or Gscanrunnable\n")
  3267  		dumpgstatus(gp.m.lockedg.ptr())
  3268  		throw("stoplockedm: not runnable")
  3269  	}
  3270  	acquirep(gp.m.nextp.ptr())
  3271  	gp.m.nextp = 0
  3272  }
  3273  
  3274  // Schedules the locked m to run the locked gp.
  3275  // May run during STW, so write barriers are not allowed.
  3276  //
  3277  //go:nowritebarrierrec
  3278  func startlockedm(gp *g) {
  3279  	mp := gp.lockedm.ptr()
  3280  	if mp == getg().m {
  3281  		throw("startlockedm: locked to me")
  3282  	}
  3283  	if mp.nextp != 0 {
  3284  		throw("startlockedm: m has p")
  3285  	}
  3286  	// directly handoff current P to the locked m
  3287  	incidlelocked(-1)
  3288  	pp := releasep()
  3289  	mp.nextp.set(pp)
  3290  	notewakeup(&mp.park)
  3291  	stopm()
  3292  }
  3293  
  3294  // Stops the current m for stopTheWorld.
  3295  // Returns when the world is restarted.
  3296  func gcstopm() {
  3297  	gp := getg()
  3298  
  3299  	if !sched.gcwaiting.Load() {
  3300  		throw("gcstopm: not waiting for gc")
  3301  	}
  3302  	if gp.m.spinning {
  3303  		gp.m.spinning = false
  3304  		// OK to just drop nmspinning here,
  3305  		// startTheWorld will unpark threads as necessary.
  3306  		if sched.nmspinning.Add(-1) < 0 {
  3307  			throw("gcstopm: negative nmspinning")
  3308  		}
  3309  	}
  3310  	pp := releasep()
  3311  	lock(&sched.lock)
  3312  	pp.status = _Pgcstop
  3313  	pp.gcStopTime = nanotime()
  3314  	sched.stopwait--
  3315  	if sched.stopwait == 0 {
  3316  		notewakeup(&sched.stopnote)
  3317  	}
  3318  	unlock(&sched.lock)
  3319  	stopm()
  3320  }
  3321  
  3322  // Schedules gp to run on the current M.
  3323  // If inheritTime is true, gp inherits the remaining time in the
  3324  // current time slice. Otherwise, it starts a new time slice.
  3325  // Never returns.
  3326  //
  3327  // Write barriers are allowed because this is called immediately after
  3328  // acquiring a P in several places.
  3329  //
  3330  //go:yeswritebarrierrec
  3331  func execute(gp *g, inheritTime bool) {
  3332  	mp := getg().m
  3333  
  3334  	if goroutineProfile.active {
  3335  		// Make sure that gp has had its stack written out to the goroutine
  3336  		// profile, exactly as it was when the goroutine profiler first stopped
  3337  		// the world.
  3338  		tryRecordGoroutineProfile(gp, nil, osyield)
  3339  	}
  3340  
  3341  	// Assign gp.m before entering _Grunning so running Gs have an M.
  3342  	mp.curg = gp
  3343  	gp.m = mp
  3344  	gp.syncSafePoint = false // Clear the flag, which may have been set by morestack.
  3345  	casgstatus(gp, _Grunnable, _Grunning)
  3346  	gp.waitsince = 0
  3347  	gp.preempt = false
  3348  	gp.stackguard0 = gp.stack.lo + stackGuard
  3349  	if !inheritTime {
  3350  		mp.p.ptr().schedtick++
  3351  	}
  3352  
  3353  	if sys.DITSupported && debug.dataindependenttiming != 1 {
  3354  		if gp.ditWanted && !mp.ditEnabled {
  3355  			// The current M doesn't have DIT enabled, but the goroutine we're
  3356  			// executing does need it, so turn it on.
  3357  			sys.EnableDIT()
  3358  			mp.ditEnabled = true
  3359  		} else if !gp.ditWanted && mp.ditEnabled {
  3360  			// The current M has DIT enabled, but the goroutine we're executing does
  3361  			// not need it, so turn it off.
  3362  			// NOTE: turning off DIT here means that the scheduler will have DIT enabled
  3363  			// when it runs after this goroutine yields or is preempted. This may have
  3364  			// a minor performance impact on the scheduler.
  3365  			sys.DisableDIT()
  3366  			mp.ditEnabled = false
  3367  		}
  3368  	}
  3369  
  3370  	// Check whether the profiler needs to be turned on or off.
  3371  	hz := sched.profilehz
  3372  	if mp.profilehz != hz {
  3373  		setThreadCPUProfiler(hz)
  3374  	}
  3375  
  3376  	trace := traceAcquire()
  3377  	if trace.ok() {
  3378  		trace.GoStart()
  3379  		traceRelease(trace)
  3380  	}
  3381  
  3382  	gogo(&gp.sched)
  3383  }
  3384  
  3385  // Finds a runnable goroutine to execute.
  3386  // Tries to steal from other P's, get g from local or global queue, poll network.
  3387  // tryWakeP indicates that the returned goroutine is not normal (GC worker, trace
  3388  // reader) so the caller should try to wake a P.
  3389  func findRunnable() (gp *g, inheritTime, tryWakeP bool) {
  3390  	mp := getg().m
  3391  
  3392  	// The conditions here and in handoffp must agree: if
  3393  	// findRunnable would return a G to run, handoffp must start
  3394  	// an M.
  3395  
  3396  top:
  3397  	// We may have collected an allp snapshot below. The snapshot is only
  3398  	// required in each loop iteration. Clear it to all GC to collect the
  3399  	// slice.
  3400  	mp.clearAllpSnapshot()
  3401  
  3402  	pp := mp.p.ptr()
  3403  	if sched.gcwaiting.Load() {
  3404  		gcstopm()
  3405  		goto top
  3406  	}
  3407  	if pp.runSafePointFn != 0 {
  3408  		runSafePointFn()
  3409  	}
  3410  
  3411  	// now and pollUntil are saved for work stealing later,
  3412  	// which may steal timers. It's important that between now
  3413  	// and then, nothing blocks, so these numbers remain mostly
  3414  	// relevant.
  3415  	now, pollUntil, _ := pp.timers.check(0, nil)
  3416  
  3417  	// Try to schedule the trace reader.
  3418  	if traceEnabled() || traceShuttingDown() {
  3419  		gp := traceReader()
  3420  		if gp != nil {
  3421  			trace := traceAcquire()
  3422  			casgstatus(gp, _Gwaiting, _Grunnable)
  3423  			if trace.ok() {
  3424  				trace.GoUnpark(gp, 0)
  3425  				traceRelease(trace)
  3426  			}
  3427  			return gp, false, true
  3428  		}
  3429  	}
  3430  
  3431  	// Try to schedule a GC worker.
  3432  	if gcBlackenEnabled != 0 {
  3433  		gp, tnow := gcController.findRunnableGCWorker(pp, now)
  3434  		if gp != nil {
  3435  			return gp, false, true
  3436  		}
  3437  		now = tnow
  3438  	}
  3439  
  3440  	// Check the global runnable queue once in a while to ensure fairness.
  3441  	// Otherwise two goroutines can completely occupy the local runqueue
  3442  	// by constantly respawning each other.
  3443  	if pp.schedtick%61 == 0 && !sched.runq.empty() {
  3444  		lock(&sched.lock)
  3445  		gp := globrunqget()
  3446  		unlock(&sched.lock)
  3447  		if gp != nil {
  3448  			return gp, false, false
  3449  		}
  3450  	}
  3451  
  3452  	// Wake up the finalizer G.
  3453  	if fingStatus.Load()&(fingWait|fingWake) == fingWait|fingWake {
  3454  		if gp := wakefing(); gp != nil {
  3455  			ready(gp, 0, true)
  3456  		}
  3457  	}
  3458  
  3459  	// Wake up one or more cleanup Gs.
  3460  	if gcCleanups.needsWake() {
  3461  		gcCleanups.wake()
  3462  	}
  3463  
  3464  	if *cgo_yield != nil {
  3465  		asmcgocall(*cgo_yield, nil)
  3466  	}
  3467  
  3468  	// local runq
  3469  	if gp, inheritTime := runqget(pp); gp != nil {
  3470  		return gp, inheritTime, false
  3471  	}
  3472  
  3473  	// global runq
  3474  	if !sched.runq.empty() {
  3475  		lock(&sched.lock)
  3476  		gp, q := globrunqgetbatch(int32(len(pp.runq)) / 2)
  3477  		unlock(&sched.lock)
  3478  		if gp != nil {
  3479  			if runqputbatch(pp, &q); !q.empty() {
  3480  				throw("Couldn't put Gs into empty local runq")
  3481  			}
  3482  			return gp, false, false
  3483  		}
  3484  	}
  3485  
  3486  	// Poll network.
  3487  	// This netpoll is only an optimization before we resort to stealing.
  3488  	// We can safely skip it if there are no waiters or a thread is blocked
  3489  	// in netpoll already. If there is any kind of logical race with that
  3490  	// blocked thread (e.g. it has already returned from netpoll, but does
  3491  	// not set lastpoll yet), this thread will do blocking netpoll below
  3492  	// anyway.
  3493  	// We only poll from one thread at a time to avoid kernel contention
  3494  	// on machines with many cores.
  3495  	if netpollinited() && netpollAnyWaiters() && sched.lastpoll.Load() != 0 && sched.pollingNet.Swap(1) == 0 {
  3496  		list, delta := netpoll(0)
  3497  		sched.pollingNet.Store(0)
  3498  		if !list.empty() { // non-blocking
  3499  			gp := list.pop()
  3500  			injectglist(&list)
  3501  			netpollAdjustWaiters(delta)
  3502  			trace := traceAcquire()
  3503  			casgstatus(gp, _Gwaiting, _Grunnable)
  3504  			if trace.ok() {
  3505  				trace.GoUnpark(gp, 0)
  3506  				traceRelease(trace)
  3507  			}
  3508  			return gp, false, false
  3509  		}
  3510  	}
  3511  
  3512  	// Spinning Ms: steal work from other Ps.
  3513  	//
  3514  	// Limit the number of spinning Ms to half the number of busy Ps.
  3515  	// This is necessary to prevent excessive CPU consumption when
  3516  	// GOMAXPROCS>>1 but the program parallelism is low.
  3517  	if mp.spinning || 2*sched.nmspinning.Load() < gomaxprocs-sched.npidle.Load() {
  3518  		if !mp.spinning {
  3519  			mp.becomeSpinning()
  3520  		}
  3521  
  3522  		gp, inheritTime, tnow, w, newWork := stealWork(now)
  3523  		if gp != nil {
  3524  			// Successfully stole.
  3525  			return gp, inheritTime, false
  3526  		}
  3527  		if newWork {
  3528  			// There may be new timer or GC work; restart to
  3529  			// discover.
  3530  			goto top
  3531  		}
  3532  
  3533  		now = tnow
  3534  		if w != 0 && (pollUntil == 0 || w < pollUntil) {
  3535  			// Earlier timer to wait for.
  3536  			pollUntil = w
  3537  		}
  3538  	}
  3539  
  3540  	// We have nothing to do.
  3541  	//
  3542  	// If we're in the GC mark phase, can safely scan and blacken objects,
  3543  	// and have work to do, run idle-time marking rather than give up the P.
  3544  	if gcBlackenEnabled != 0 && gcShouldScheduleWorker(pp) && gcController.addIdleMarkWorker() {
  3545  		node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
  3546  		if node != nil {
  3547  			pp.gcMarkWorkerMode = gcMarkWorkerIdleMode
  3548  			gp := node.gp.ptr()
  3549  
  3550  			trace := traceAcquire()
  3551  			casgstatus(gp, _Gwaiting, _Grunnable)
  3552  			if trace.ok() {
  3553  				trace.GoUnpark(gp, 0)
  3554  				traceRelease(trace)
  3555  			}
  3556  			return gp, false, false
  3557  		}
  3558  		gcController.removeIdleMarkWorker()
  3559  	}
  3560  
  3561  	// wasm only:
  3562  	// If a callback returned and no other goroutine is awake,
  3563  	// then wake event handler goroutine which pauses execution
  3564  	// until a callback was triggered.
  3565  	gp, otherReady := beforeIdle(now, pollUntil)
  3566  	if gp != nil {
  3567  		trace := traceAcquire()
  3568  		casgstatus(gp, _Gwaiting, _Grunnable)
  3569  		if trace.ok() {
  3570  			trace.GoUnpark(gp, 0)
  3571  			traceRelease(trace)
  3572  		}
  3573  		return gp, false, false
  3574  	}
  3575  	if otherReady {
  3576  		goto top
  3577  	}
  3578  
  3579  	// Before we drop our P, make a snapshot of the allp slice,
  3580  	// which can change underfoot once we no longer block
  3581  	// safe-points. We don't need to snapshot the contents because
  3582  	// everything up to cap(allp) is immutable.
  3583  	//
  3584  	// We clear the snapshot from the M after return via
  3585  	// mp.clearAllpSnapshop (in schedule) and on each iteration of the top
  3586  	// loop.
  3587  	allpSnapshot := mp.snapshotAllp()
  3588  	// Also snapshot masks. Value changes are OK, but we can't allow
  3589  	// len to change out from under us.
  3590  	idlepMaskSnapshot := idlepMask
  3591  	timerpMaskSnapshot := timerpMask
  3592  
  3593  	// return P and block
  3594  	lock(&sched.lock)
  3595  	if sched.gcwaiting.Load() || pp.runSafePointFn != 0 {
  3596  		unlock(&sched.lock)
  3597  		goto top
  3598  	}
  3599  	if !sched.runq.empty() {
  3600  		gp, q := globrunqgetbatch(int32(len(pp.runq)) / 2)
  3601  		unlock(&sched.lock)
  3602  		if gp == nil {
  3603  			throw("global runq empty with non-zero runqsize")
  3604  		}
  3605  		if runqputbatch(pp, &q); !q.empty() {
  3606  			throw("Couldn't put Gs into empty local runq")
  3607  		}
  3608  		return gp, false, false
  3609  	}
  3610  	if !mp.spinning && sched.needspinning.Load() == 1 {
  3611  		// See "Delicate dance" comment below.
  3612  		mp.becomeSpinning()
  3613  		unlock(&sched.lock)
  3614  		goto top
  3615  	}
  3616  	if releasep() != pp {
  3617  		throw("findRunnable: wrong p")
  3618  	}
  3619  	now = pidleput(pp, now)
  3620  	unlock(&sched.lock)
  3621  
  3622  	// Delicate dance: thread transitions from spinning to non-spinning
  3623  	// state, potentially concurrently with submission of new work. We must
  3624  	// drop nmspinning first and then check all sources again (with
  3625  	// #StoreLoad memory barrier in between). If we do it the other way
  3626  	// around, another thread can submit work after we've checked all
  3627  	// sources but before we drop nmspinning; as a result nobody will
  3628  	// unpark a thread to run the work.
  3629  	//
  3630  	// This applies to the following sources of work:
  3631  	//
  3632  	// * Goroutines added to the global or a per-P run queue.
  3633  	// * New/modified-earlier timers on a per-P timer heap.
  3634  	// * Idle-priority GC work (barring golang.org/issue/19112).
  3635  	//
  3636  	// If we discover new work below, we need to restore m.spinning as a
  3637  	// signal for resetspinning to unpark a new worker thread (because
  3638  	// there can be more than one starving goroutine).
  3639  	//
  3640  	// However, if after discovering new work we also observe no idle Ps
  3641  	// (either here or in resetspinning), we have a problem. We may be
  3642  	// racing with a non-spinning M in the block above, having found no
  3643  	// work and preparing to release its P and park. Allowing that P to go
  3644  	// idle will result in loss of work conservation (idle P while there is
  3645  	// runnable work). This could result in complete deadlock in the
  3646  	// unlikely event that we discover new work (from netpoll) right as we
  3647  	// are racing with _all_ other Ps going idle.
  3648  	//
  3649  	// We use sched.needspinning to synchronize with non-spinning Ms going
  3650  	// idle. If needspinning is set when they are about to drop their P,
  3651  	// they abort the drop and instead become a new spinning M on our
  3652  	// behalf. If we are not racing and the system is truly fully loaded
  3653  	// then no spinning threads are required, and the next thread to
  3654  	// naturally become spinning will clear the flag.
  3655  	//
  3656  	// Also see "Worker thread parking/unparking" comment at the top of the
  3657  	// file.
  3658  	wasSpinning := mp.spinning
  3659  	if mp.spinning {
  3660  		mp.spinning = false
  3661  		if sched.nmspinning.Add(-1) < 0 {
  3662  			throw("findRunnable: negative nmspinning")
  3663  		}
  3664  
  3665  		// Note the for correctness, only the last M transitioning from
  3666  		// spinning to non-spinning must perform these rechecks to
  3667  		// ensure no missed work. However, the runtime has some cases
  3668  		// of transient increments of nmspinning that are decremented
  3669  		// without going through this path, so we must be conservative
  3670  		// and perform the check on all spinning Ms.
  3671  		//
  3672  		// See https://go.dev/issue/43997.
  3673  
  3674  		// Check global and P runqueues again.
  3675  
  3676  		lock(&sched.lock)
  3677  		if !sched.runq.empty() {
  3678  			pp, _ := pidlegetSpinning(0)
  3679  			if pp != nil {
  3680  				gp, q := globrunqgetbatch(int32(len(pp.runq)) / 2)
  3681  				unlock(&sched.lock)
  3682  				if gp == nil {
  3683  					throw("global runq empty with non-zero runqsize")
  3684  				}
  3685  				if runqputbatch(pp, &q); !q.empty() {
  3686  					throw("Couldn't put Gs into empty local runq")
  3687  				}
  3688  				acquirep(pp)
  3689  				mp.becomeSpinning()
  3690  				return gp, false, false
  3691  			}
  3692  		}
  3693  		unlock(&sched.lock)
  3694  
  3695  		pp := checkRunqsNoP(allpSnapshot, idlepMaskSnapshot)
  3696  		if pp != nil {
  3697  			acquirep(pp)
  3698  			mp.becomeSpinning()
  3699  			goto top
  3700  		}
  3701  
  3702  		// Check for idle-priority GC work again.
  3703  		pp, gp := checkIdleGCNoP()
  3704  		if pp != nil {
  3705  			acquirep(pp)
  3706  			mp.becomeSpinning()
  3707  
  3708  			// Run the idle worker.
  3709  			pp.gcMarkWorkerMode = gcMarkWorkerIdleMode
  3710  			trace := traceAcquire()
  3711  			casgstatus(gp, _Gwaiting, _Grunnable)
  3712  			if trace.ok() {
  3713  				trace.GoUnpark(gp, 0)
  3714  				traceRelease(trace)
  3715  			}
  3716  			return gp, false, false
  3717  		}
  3718  
  3719  		// Finally, check for timer creation or expiry concurrently with
  3720  		// transitioning from spinning to non-spinning.
  3721  		//
  3722  		// Note that we cannot use checkTimers here because it calls
  3723  		// adjusttimers which may need to allocate memory, and that isn't
  3724  		// allowed when we don't have an active P.
  3725  		pollUntil = checkTimersNoP(allpSnapshot, timerpMaskSnapshot, pollUntil)
  3726  	}
  3727  
  3728  	// We don't need allp anymore at this pointer, but can't clear the
  3729  	// snapshot without a P for the write barrier..
  3730  
  3731  	// Poll network until next timer.
  3732  	if netpollinited() && (netpollAnyWaiters() || pollUntil != 0) && sched.lastpoll.Swap(0) != 0 {
  3733  		sched.pollUntil.Store(pollUntil)
  3734  		if mp.p != 0 {
  3735  			throw("findRunnable: netpoll with p")
  3736  		}
  3737  		if mp.spinning {
  3738  			throw("findRunnable: netpoll with spinning")
  3739  		}
  3740  		delay := int64(-1)
  3741  		if pollUntil != 0 {
  3742  			if now == 0 {
  3743  				now = nanotime()
  3744  			}
  3745  			delay = pollUntil - now
  3746  			if delay < 0 {
  3747  				delay = 0
  3748  			}
  3749  		}
  3750  		if faketime != 0 {
  3751  			// When using fake time, just poll.
  3752  			delay = 0
  3753  		}
  3754  		list, delta := netpoll(delay) // block until new work is available
  3755  		// Refresh now again, after potentially blocking.
  3756  		now = nanotime()
  3757  		sched.pollUntil.Store(0)
  3758  		sched.lastpoll.Store(now)
  3759  		if faketime != 0 && list.empty() {
  3760  			// Using fake time and nothing is ready; stop M.
  3761  			// When all M's stop, checkdead will call timejump.
  3762  			stopm()
  3763  			goto top
  3764  		}
  3765  		lock(&sched.lock)
  3766  		pp, _ := pidleget(now)
  3767  		unlock(&sched.lock)
  3768  		if pp == nil {
  3769  			injectglist(&list)
  3770  			netpollAdjustWaiters(delta)
  3771  		} else {
  3772  			acquirep(pp)
  3773  			if !list.empty() {
  3774  				gp := list.pop()
  3775  				injectglist(&list)
  3776  				netpollAdjustWaiters(delta)
  3777  				trace := traceAcquire()
  3778  				casgstatus(gp, _Gwaiting, _Grunnable)
  3779  				if trace.ok() {
  3780  					trace.GoUnpark(gp, 0)
  3781  					traceRelease(trace)
  3782  				}
  3783  				return gp, false, false
  3784  			}
  3785  			if wasSpinning {
  3786  				mp.becomeSpinning()
  3787  			}
  3788  			goto top
  3789  		}
  3790  	} else if pollUntil != 0 && netpollinited() {
  3791  		pollerPollUntil := sched.pollUntil.Load()
  3792  		if pollerPollUntil == 0 || pollerPollUntil > pollUntil {
  3793  			netpollBreak()
  3794  		}
  3795  	}
  3796  	stopm()
  3797  	goto top
  3798  }
  3799  
  3800  // pollWork reports whether there is non-background work this P could
  3801  // be doing. This is a fairly lightweight check to be used for
  3802  // background work loops, like idle GC. It checks a subset of the
  3803  // conditions checked by the actual scheduler.
  3804  func pollWork() bool {
  3805  	if !sched.runq.empty() {
  3806  		return true
  3807  	}
  3808  	p := getg().m.p.ptr()
  3809  	if !runqempty(p) {
  3810  		return true
  3811  	}
  3812  	if netpollinited() && netpollAnyWaiters() && sched.lastpoll.Load() != 0 {
  3813  		if list, delta := netpoll(0); !list.empty() {
  3814  			injectglist(&list)
  3815  			netpollAdjustWaiters(delta)
  3816  			return true
  3817  		}
  3818  	}
  3819  	return false
  3820  }
  3821  
  3822  // stealWork attempts to steal a runnable goroutine or timer from any P.
  3823  //
  3824  // If newWork is true, new work may have been readied.
  3825  //
  3826  // If now is not 0 it is the current time. stealWork returns the passed time or
  3827  // the current time if now was passed as 0.
  3828  func stealWork(now int64) (gp *g, inheritTime bool, rnow, pollUntil int64, newWork bool) {
  3829  	pp := getg().m.p.ptr()
  3830  
  3831  	ranTimer := false
  3832  
  3833  	const stealTries = 4
  3834  	for i := 0; i < stealTries; i++ {
  3835  		stealTimersOrRunNextG := i == stealTries-1
  3836  
  3837  		for enum := stealOrder.start(cheaprand()); !enum.done(); enum.next() {
  3838  			if sched.gcwaiting.Load() {
  3839  				// GC work may be available.
  3840  				return nil, false, now, pollUntil, true
  3841  			}
  3842  			p2 := allp[enum.position()]
  3843  			if pp == p2 {
  3844  				continue
  3845  			}
  3846  
  3847  			// Steal timers from p2. This call to checkTimers is the only place
  3848  			// where we might hold a lock on a different P's timers. We do this
  3849  			// once on the last pass before checking runnext because stealing
  3850  			// from the other P's runnext should be the last resort, so if there
  3851  			// are timers to steal do that first.
  3852  			//
  3853  			// We only check timers on one of the stealing iterations because
  3854  			// the time stored in now doesn't change in this loop and checking
  3855  			// the timers for each P more than once with the same value of now
  3856  			// is probably a waste of time.
  3857  			//
  3858  			// timerpMask tells us whether the P may have timers at all. If it
  3859  			// can't, no need to check at all.
  3860  			if stealTimersOrRunNextG && timerpMask.read(enum.position()) {
  3861  				tnow, w, ran := p2.timers.check(now, nil)
  3862  				now = tnow
  3863  				if w != 0 && (pollUntil == 0 || w < pollUntil) {
  3864  					pollUntil = w
  3865  				}
  3866  				if ran {
  3867  					// Running the timers may have
  3868  					// made an arbitrary number of G's
  3869  					// ready and added them to this P's
  3870  					// local run queue. That invalidates
  3871  					// the assumption of runqsteal
  3872  					// that it always has room to add
  3873  					// stolen G's. So check now if there
  3874  					// is a local G to run.
  3875  					if gp, inheritTime := runqget(pp); gp != nil {
  3876  						return gp, inheritTime, now, pollUntil, ranTimer
  3877  					}
  3878  					ranTimer = true
  3879  				}
  3880  			}
  3881  
  3882  			// Don't bother to attempt to steal if p2 is idle.
  3883  			if !idlepMask.read(enum.position()) {
  3884  				if gp := runqsteal(pp, p2, stealTimersOrRunNextG); gp != nil {
  3885  					return gp, false, now, pollUntil, ranTimer
  3886  				}
  3887  			}
  3888  		}
  3889  	}
  3890  
  3891  	// No goroutines found to steal. Regardless, running a timer may have
  3892  	// made some goroutine ready that we missed. Indicate the next timer to
  3893  	// wait for.
  3894  	return nil, false, now, pollUntil, ranTimer
  3895  }
  3896  
  3897  // Check all Ps for a runnable G to steal.
  3898  //
  3899  // On entry we have no P. If a G is available to steal and a P is available,
  3900  // the P is returned which the caller should acquire and attempt to steal the
  3901  // work to.
  3902  func checkRunqsNoP(allpSnapshot []*p, idlepMaskSnapshot pMask) *p {
  3903  	for id, p2 := range allpSnapshot {
  3904  		if !idlepMaskSnapshot.read(uint32(id)) && !runqempty(p2) {
  3905  			lock(&sched.lock)
  3906  			pp, _ := pidlegetSpinning(0)
  3907  			if pp == nil {
  3908  				// Can't get a P, don't bother checking remaining Ps.
  3909  				unlock(&sched.lock)
  3910  				return nil
  3911  			}
  3912  			unlock(&sched.lock)
  3913  			return pp
  3914  		}
  3915  	}
  3916  
  3917  	// No work available.
  3918  	return nil
  3919  }
  3920  
  3921  // Check all Ps for a timer expiring sooner than pollUntil.
  3922  //
  3923  // Returns updated pollUntil value.
  3924  func checkTimersNoP(allpSnapshot []*p, timerpMaskSnapshot pMask, pollUntil int64) int64 {
  3925  	for id, p2 := range allpSnapshot {
  3926  		if timerpMaskSnapshot.read(uint32(id)) {
  3927  			w := p2.timers.wakeTime()
  3928  			if w != 0 && (pollUntil == 0 || w < pollUntil) {
  3929  				pollUntil = w
  3930  			}
  3931  		}
  3932  	}
  3933  
  3934  	return pollUntil
  3935  }
  3936  
  3937  // Check for idle-priority GC, without a P on entry.
  3938  //
  3939  // If some GC work, a P, and a worker G are all available, the P and G will be
  3940  // returned. The returned P has not been wired yet.
  3941  func checkIdleGCNoP() (*p, *g) {
  3942  	// N.B. Since we have no P, gcBlackenEnabled may change at any time; we
  3943  	// must check again after acquiring a P. As an optimization, we also check
  3944  	// if an idle mark worker is needed at all. This is OK here, because if we
  3945  	// observe that one isn't needed, at least one is currently running. Even if
  3946  	// it stops running, its own journey into the scheduler should schedule it
  3947  	// again, if need be (at which point, this check will pass, if relevant).
  3948  	if atomic.Load(&gcBlackenEnabled) == 0 || !gcController.needIdleMarkWorker() {
  3949  		return nil, nil
  3950  	}
  3951  	if !gcShouldScheduleWorker(nil) {
  3952  		return nil, nil
  3953  	}
  3954  
  3955  	// Work is available; we can start an idle GC worker only if there is
  3956  	// an available P and available worker G.
  3957  	//
  3958  	// We can attempt to acquire these in either order, though both have
  3959  	// synchronization concerns (see below). Workers are almost always
  3960  	// available (see comment in findRunnableGCWorker for the one case
  3961  	// there may be none). Since we're slightly less likely to find a P,
  3962  	// check for that first.
  3963  	//
  3964  	// Synchronization: note that we must hold sched.lock until we are
  3965  	// committed to keeping it. Otherwise we cannot put the unnecessary P
  3966  	// back in sched.pidle without performing the full set of idle
  3967  	// transition checks.
  3968  	//
  3969  	// If we were to check gcBgMarkWorkerPool first, we must somehow handle
  3970  	// the assumption in gcControllerState.findRunnableGCWorker that an
  3971  	// empty gcBgMarkWorkerPool is only possible if gcMarkDone is running.
  3972  	lock(&sched.lock)
  3973  	pp, now := pidlegetSpinning(0)
  3974  	if pp == nil {
  3975  		unlock(&sched.lock)
  3976  		return nil, nil
  3977  	}
  3978  
  3979  	// Now that we own a P, gcBlackenEnabled can't change (as it requires STW).
  3980  	if gcBlackenEnabled == 0 || !gcController.addIdleMarkWorker() {
  3981  		pidleput(pp, now)
  3982  		unlock(&sched.lock)
  3983  		return nil, nil
  3984  	}
  3985  
  3986  	node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
  3987  	if node == nil {
  3988  		pidleput(pp, now)
  3989  		unlock(&sched.lock)
  3990  		gcController.removeIdleMarkWorker()
  3991  		return nil, nil
  3992  	}
  3993  
  3994  	unlock(&sched.lock)
  3995  
  3996  	return pp, node.gp.ptr()
  3997  }
  3998  
  3999  // wakeNetPoller wakes up the thread sleeping in the network poller if it isn't
  4000  // going to wake up before the when argument; or it wakes an idle P to service
  4001  // timers and the network poller if there isn't one already.
  4002  func wakeNetPoller(when int64) {
  4003  	if sched.lastpoll.Load() == 0 {
  4004  		// In findRunnable we ensure that when polling the pollUntil
  4005  		// field is either zero or the time to which the current
  4006  		// poll is expected to run. This can have a spurious wakeup
  4007  		// but should never miss a wakeup.
  4008  		pollerPollUntil := sched.pollUntil.Load()
  4009  		if pollerPollUntil == 0 || pollerPollUntil > when {
  4010  			netpollBreak()
  4011  		}
  4012  	} else {
  4013  		// There are no threads in the network poller, try to get
  4014  		// one there so it can handle new timers.
  4015  		if GOOS != "plan9" { // Temporary workaround - see issue #42303.
  4016  			wakep()
  4017  		}
  4018  	}
  4019  }
  4020  
  4021  func resetspinning() {
  4022  	gp := getg()
  4023  	if !gp.m.spinning {
  4024  		throw("resetspinning: not a spinning m")
  4025  	}
  4026  	gp.m.spinning = false
  4027  	nmspinning := sched.nmspinning.Add(-1)
  4028  	if nmspinning < 0 {
  4029  		throw("findRunnable: negative nmspinning")
  4030  	}
  4031  	// M wakeup policy is deliberately somewhat conservative, so check if we
  4032  	// need to wakeup another P here. See "Worker thread parking/unparking"
  4033  	// comment at the top of the file for details.
  4034  	wakep()
  4035  }
  4036  
  4037  // injectglist adds each runnable G on the list to some run queue,
  4038  // and clears glist. If there is no current P, they are added to the
  4039  // global queue, and up to npidle M's are started to run them.
  4040  // Otherwise, for each idle P, this adds a G to the global queue
  4041  // and starts an M. Any remaining G's are added to the current P's
  4042  // local run queue.
  4043  // This may temporarily acquire sched.lock.
  4044  // Can run concurrently with GC.
  4045  func injectglist(glist *gList) {
  4046  	if glist.empty() {
  4047  		return
  4048  	}
  4049  
  4050  	// Mark all the goroutines as runnable before we put them
  4051  	// on the run queues.
  4052  	var tail *g
  4053  	trace := traceAcquire()
  4054  	for gp := glist.head.ptr(); gp != nil; gp = gp.schedlink.ptr() {
  4055  		tail = gp
  4056  		casgstatus(gp, _Gwaiting, _Grunnable)
  4057  		if trace.ok() {
  4058  			trace.GoUnpark(gp, 0)
  4059  		}
  4060  	}
  4061  	if trace.ok() {
  4062  		traceRelease(trace)
  4063  	}
  4064  
  4065  	// Turn the gList into a gQueue.
  4066  	q := gQueue{glist.head, tail.guintptr(), glist.size}
  4067  	*glist = gList{}
  4068  
  4069  	startIdle := func(n int32) {
  4070  		for ; n > 0; n-- {
  4071  			mp := acquirem() // See comment in startm.
  4072  			lock(&sched.lock)
  4073  
  4074  			pp, _ := pidlegetSpinning(0)
  4075  			if pp == nil {
  4076  				unlock(&sched.lock)
  4077  				releasem(mp)
  4078  				break
  4079  			}
  4080  
  4081  			startm(pp, false, true)
  4082  			unlock(&sched.lock)
  4083  			releasem(mp)
  4084  		}
  4085  	}
  4086  
  4087  	pp := getg().m.p.ptr()
  4088  	if pp == nil {
  4089  		n := q.size
  4090  		lock(&sched.lock)
  4091  		globrunqputbatch(&q)
  4092  		unlock(&sched.lock)
  4093  		startIdle(n)
  4094  		return
  4095  	}
  4096  
  4097  	var globq gQueue
  4098  	npidle := sched.npidle.Load()
  4099  	for ; npidle > 0 && !q.empty(); npidle-- {
  4100  		g := q.pop()
  4101  		globq.pushBack(g)
  4102  	}
  4103  	if !globq.empty() {
  4104  		n := globq.size
  4105  		lock(&sched.lock)
  4106  		globrunqputbatch(&globq)
  4107  		unlock(&sched.lock)
  4108  		startIdle(n)
  4109  	}
  4110  
  4111  	if runqputbatch(pp, &q); !q.empty() {
  4112  		lock(&sched.lock)
  4113  		globrunqputbatch(&q)
  4114  		unlock(&sched.lock)
  4115  	}
  4116  
  4117  	// Some P's might have become idle after we loaded `sched.npidle`
  4118  	// but before any goroutines were added to the queue, which could
  4119  	// lead to idle P's when there is work available in the global queue.
  4120  	// That could potentially last until other goroutines become ready
  4121  	// to run. That said, we need to find a way to hedge
  4122  	//
  4123  	// Calling wakep() here is the best bet, it will do nothing in the
  4124  	// common case (no racing on `sched.npidle`), while it could wake one
  4125  	// more P to execute G's, which might end up with >1 P's: the first one
  4126  	// wakes another P and so forth until there is no more work, but this
  4127  	// ought to be an extremely rare case.
  4128  	//
  4129  	// Also see "Worker thread parking/unparking" comment at the top of the file for details.
  4130  	wakep()
  4131  }
  4132  
  4133  // One round of scheduler: find a runnable goroutine and execute it.
  4134  // Never returns.
  4135  func schedule() {
  4136  	mp := getg().m
  4137  
  4138  	if mp.locks != 0 {
  4139  		throw("schedule: holding locks")
  4140  	}
  4141  
  4142  	if mp.lockedg != 0 {
  4143  		stoplockedm()
  4144  		execute(mp.lockedg.ptr(), false) // Never returns.
  4145  	}
  4146  
  4147  	// We should not schedule away from a g that is executing a cgo call,
  4148  	// since the cgo call is using the m's g0 stack.
  4149  	if mp.incgo {
  4150  		throw("schedule: in cgo")
  4151  	}
  4152  
  4153  top:
  4154  	pp := mp.p.ptr()
  4155  	pp.preempt = false
  4156  
  4157  	// Safety check: if we are spinning, the run queue should be empty.
  4158  	// Check this before calling checkTimers, as that might call
  4159  	// goready to put a ready goroutine on the local run queue.
  4160  	if mp.spinning && (pp.runnext != 0 || pp.runqhead != pp.runqtail) {
  4161  		throw("schedule: spinning with local work")
  4162  	}
  4163  
  4164  	gp, inheritTime, tryWakeP := findRunnable() // blocks until work is available
  4165  
  4166  	// May be on a new P.
  4167  	pp = mp.p.ptr()
  4168  
  4169  	// findRunnable may have collected an allp snapshot. The snapshot is
  4170  	// only required within findRunnable. Clear it to all GC to collect the
  4171  	// slice.
  4172  	mp.clearAllpSnapshot()
  4173  
  4174  	// If the P was assigned a next GC mark worker but findRunnable
  4175  	// selected anything else, release the worker so another P may run it.
  4176  	//
  4177  	// N.B. If this occurs because a higher-priority goroutine was selected
  4178  	// (trace reader), then tryWakeP is set, which will wake another P to
  4179  	// run the worker. If this occurs because the GC is no longer active,
  4180  	// there is no need to wakep.
  4181  	gcController.releaseNextGCMarkWorker(pp)
  4182  
  4183  	if debug.dontfreezetheworld > 0 && freezing.Load() {
  4184  		// See comment in freezetheworld. We don't want to perturb
  4185  		// scheduler state, so we didn't gcstopm in findRunnable, but
  4186  		// also don't want to allow new goroutines to run.
  4187  		//
  4188  		// Deadlock here rather than in the findRunnable loop so if
  4189  		// findRunnable is stuck in a loop we don't perturb that
  4190  		// either.
  4191  		lock(&deadlock)
  4192  		lock(&deadlock)
  4193  	}
  4194  
  4195  	// This thread is going to run a goroutine and is not spinning anymore,
  4196  	// so if it was marked as spinning we need to reset it now and potentially
  4197  	// start a new spinning M.
  4198  	if mp.spinning {
  4199  		resetspinning()
  4200  	}
  4201  
  4202  	if sched.disable.user && !schedEnabled(gp) {
  4203  		// Scheduling of this goroutine is disabled. Put it on
  4204  		// the list of pending runnable goroutines for when we
  4205  		// re-enable user scheduling and look again.
  4206  		lock(&sched.lock)
  4207  		if schedEnabled(gp) {
  4208  			// Something re-enabled scheduling while we
  4209  			// were acquiring the lock.
  4210  			unlock(&sched.lock)
  4211  		} else {
  4212  			sched.disable.runnable.pushBack(gp)
  4213  			unlock(&sched.lock)
  4214  			goto top
  4215  		}
  4216  	}
  4217  
  4218  	// If about to schedule a not-normal goroutine (a GCworker or tracereader),
  4219  	// wake a P if there is one.
  4220  	if tryWakeP {
  4221  		wakep()
  4222  	}
  4223  	if gp.lockedm != 0 {
  4224  		// Hands off own p to the locked m,
  4225  		// then blocks waiting for a new p.
  4226  		startlockedm(gp)
  4227  		goto top
  4228  	}
  4229  
  4230  	execute(gp, inheritTime)
  4231  }
  4232  
  4233  // dropg removes the association between m and the current goroutine m->curg (gp for short).
  4234  // Typically a caller sets gp's status away from Grunning and then
  4235  // immediately calls dropg to finish the job. The caller is also responsible
  4236  // for arranging that gp will be restarted using ready at an
  4237  // appropriate time. After calling dropg and arranging for gp to be
  4238  // readied later, the caller can do other work but eventually should
  4239  // call schedule to restart the scheduling of goroutines on this m.
  4240  func dropg() {
  4241  	gp := getg()
  4242  
  4243  	setMNoWB(&gp.m.curg.m, nil)
  4244  	setGNoWB(&gp.m.curg, nil)
  4245  }
  4246  
  4247  func parkunlock_c(gp *g, lock unsafe.Pointer) bool {
  4248  	unlock((*mutex)(lock))
  4249  	return true
  4250  }
  4251  
  4252  // park continuation on g0.
  4253  func park_m(gp *g) {
  4254  	mp := getg().m
  4255  
  4256  	trace := traceAcquire()
  4257  
  4258  	// If g is in a synctest group, we don't want to let the group
  4259  	// become idle until after the waitunlockf (if any) has confirmed
  4260  	// that the park is happening.
  4261  	// We need to record gp.bubble here, since waitunlockf can change it.
  4262  	bubble := gp.bubble
  4263  	if bubble != nil {
  4264  		bubble.incActive()
  4265  	}
  4266  
  4267  	if trace.ok() {
  4268  		// Trace the event before the transition. It may take a
  4269  		// stack trace, but we won't own the stack after the
  4270  		// transition anymore.
  4271  		trace.GoPark(mp.waitTraceBlockReason, mp.waitTraceSkip)
  4272  	}
  4273  	// N.B. Not using casGToWaiting here because the waitreason is
  4274  	// set by park_m's caller.
  4275  	casgstatus(gp, _Grunning, _Gwaiting)
  4276  	if trace.ok() {
  4277  		traceRelease(trace)
  4278  	}
  4279  
  4280  	dropg()
  4281  
  4282  	if fn := mp.waitunlockf; fn != nil {
  4283  		ok := fn(gp, mp.waitlock)
  4284  		mp.waitunlockf = nil
  4285  		mp.waitlock = nil
  4286  		if !ok {
  4287  			trace := traceAcquire()
  4288  			casgstatus(gp, _Gwaiting, _Grunnable)
  4289  			if bubble != nil {
  4290  				bubble.decActive()
  4291  			}
  4292  			if trace.ok() {
  4293  				trace.GoUnpark(gp, 2)
  4294  				traceRelease(trace)
  4295  			}
  4296  			execute(gp, true) // Schedule it back, never returns.
  4297  		}
  4298  	}
  4299  
  4300  	if bubble != nil {
  4301  		bubble.decActive()
  4302  	}
  4303  
  4304  	schedule()
  4305  }
  4306  
  4307  func goschedImpl(gp *g, preempted bool) {
  4308  	pp := gp.m.p.ptr()
  4309  	trace := traceAcquire()
  4310  	status := readgstatus(gp)
  4311  	if status&^_Gscan != _Grunning {
  4312  		dumpgstatus(gp)
  4313  		throw("bad g status")
  4314  	}
  4315  	if trace.ok() {
  4316  		// Trace the event before the transition. It may take a
  4317  		// stack trace, but we won't own the stack after the
  4318  		// transition anymore.
  4319  		if preempted {
  4320  			trace.GoPreempt()
  4321  		} else {
  4322  			trace.GoSched()
  4323  		}
  4324  	}
  4325  	casgstatus(gp, _Grunning, _Grunnable)
  4326  	if trace.ok() {
  4327  		traceRelease(trace)
  4328  	}
  4329  
  4330  	dropg()
  4331  	if preempted && sched.gcwaiting.Load() {
  4332  		// If preempted for STW, keep the G on the local P in runnext
  4333  		// so it can keep running immediately after the STW.
  4334  		runqput(pp, gp, true)
  4335  	} else {
  4336  		lock(&sched.lock)
  4337  		globrunqput(gp)
  4338  		unlock(&sched.lock)
  4339  	}
  4340  
  4341  	if mainStarted {
  4342  		wakep()
  4343  	}
  4344  
  4345  	schedule()
  4346  }
  4347  
  4348  // Gosched continuation on g0.
  4349  func gosched_m(gp *g) {
  4350  	goschedImpl(gp, false)
  4351  }
  4352  
  4353  // goschedguarded is a forbidden-states-avoided version of gosched_m.
  4354  func goschedguarded_m(gp *g) {
  4355  	if !canPreemptM(gp.m) {
  4356  		gogo(&gp.sched) // never return
  4357  	}
  4358  	goschedImpl(gp, false)
  4359  }
  4360  
  4361  func gopreempt_m(gp *g) {
  4362  	goschedImpl(gp, true)
  4363  }
  4364  
  4365  // preemptPark parks gp and puts it in _Gpreempted.
  4366  //
  4367  //go:systemstack
  4368  func preemptPark(gp *g) {
  4369  	status := readgstatus(gp)
  4370  	if status&^_Gscan != _Grunning {
  4371  		dumpgstatus(gp)
  4372  		throw("bad g status")
  4373  	}
  4374  
  4375  	if gp.asyncSafePoint {
  4376  		// Double-check that async preemption does not
  4377  		// happen in SPWRITE assembly functions.
  4378  		// isAsyncSafePoint must exclude this case.
  4379  		f := findfunc(gp.sched.pc)
  4380  		if !f.valid() {
  4381  			throw("preempt at unknown pc")
  4382  		}
  4383  		if f.flag&abi.FuncFlagSPWrite != 0 {
  4384  			println("runtime: unexpected SPWRITE function", funcname(f), "in async preempt")
  4385  			throw("preempt SPWRITE")
  4386  		}
  4387  	}
  4388  
  4389  	// Transition from _Grunning to _Gscan|_Gpreempted. We can't
  4390  	// be in _Grunning when we dropg because then we'd be running
  4391  	// without an M, but the moment we're in _Gpreempted,
  4392  	// something could claim this G before we've fully cleaned it
  4393  	// up. Hence, we set the scan bit to lock down further
  4394  	// transitions until we can dropg.
  4395  	casGToPreemptScan(gp, _Grunning, _Gscan|_Gpreempted)
  4396  
  4397  	// Be careful about ownership as we trace this next event.
  4398  	//
  4399  	// According to the tracer invariants (trace.go) it's unsafe
  4400  	// for us to emit an event for a goroutine we do not own.
  4401  	// The moment we CAS into _Gpreempted, suspendG could CAS the
  4402  	// goroutine to _Gwaiting, effectively taking ownership. All of
  4403  	// this could happen before we even get the chance to emit
  4404  	// an event. The end result is that the events could appear
  4405  	// out of order, and the tracer generally assumes the scheduler
  4406  	// takes care of the ordering between GoPark and GoUnpark.
  4407  	//
  4408  	// The answer here is simple: emit the event while we still hold
  4409  	// the _Gscan bit on the goroutine, since the _Gscan bit means
  4410  	// ownership over transitions.
  4411  	//
  4412  	// We still need to traceAcquire and traceRelease across the CAS
  4413  	// because the tracer could be what's calling suspendG in the first
  4414  	// place. This also upholds the tracer invariant that we must hold
  4415  	// traceAcquire/traceRelease across the transition. However, we
  4416  	// specifically *only* emit the event while we still have ownership.
  4417  	trace := traceAcquire()
  4418  	if trace.ok() {
  4419  		trace.GoPark(traceBlockPreempted, 0)
  4420  	}
  4421  
  4422  	// Drop the goroutine from the M. Only do this after the tracer has
  4423  	// emitted an event, because it needs the association for GoPark to
  4424  	// work correctly.
  4425  	dropg()
  4426  
  4427  	// Drop the scan bit and release the trace locker if necessary.
  4428  	casfrom_Gscanstatus(gp, _Gscan|_Gpreempted, _Gpreempted)
  4429  	if trace.ok() {
  4430  		traceRelease(trace)
  4431  	}
  4432  
  4433  	// All done.
  4434  	schedule()
  4435  }
  4436  
  4437  // goyield is like Gosched, but it:
  4438  // - emits a GoPreempt trace event instead of a GoSched trace event
  4439  // - puts the current G on the runq of the current P instead of the globrunq
  4440  //
  4441  // goyield should be an internal detail,
  4442  // but widely used packages access it using linkname.
  4443  // Notable members of the hall of shame include:
  4444  //   - gvisor.dev/gvisor
  4445  //   - github.com/sagernet/gvisor
  4446  //
  4447  // Do not remove or change the type signature.
  4448  // See go.dev/issue/67401.
  4449  //
  4450  //go:linkname goyield
  4451  func goyield() {
  4452  	checkTimeouts()
  4453  	mcall(goyield_m)
  4454  }
  4455  
  4456  func goyield_m(gp *g) {
  4457  	trace := traceAcquire()
  4458  	pp := gp.m.p.ptr()
  4459  	if trace.ok() {
  4460  		// Trace the event before the transition. It may take a
  4461  		// stack trace, but we won't own the stack after the
  4462  		// transition anymore.
  4463  		trace.GoPreempt()
  4464  	}
  4465  	casgstatus(gp, _Grunning, _Grunnable)
  4466  	if trace.ok() {
  4467  		traceRelease(trace)
  4468  	}
  4469  	dropg()
  4470  	runqput(pp, gp, false)
  4471  	schedule()
  4472  }
  4473  
  4474  // Finishes execution of the current goroutine.
  4475  func goexit1() {
  4476  	if raceenabled {
  4477  		if gp := getg(); gp.bubble != nil {
  4478  			racereleasemergeg(gp, gp.bubble.raceaddr())
  4479  		}
  4480  		racegoend()
  4481  	}
  4482  	trace := traceAcquire()
  4483  	if trace.ok() {
  4484  		trace.GoEnd()
  4485  		traceRelease(trace)
  4486  	}
  4487  	mcall(goexit0)
  4488  }
  4489  
  4490  // goexit continuation on g0.
  4491  func goexit0(gp *g) {
  4492  	if goexperiment.RuntimeSecret && gp.secret > 0 {
  4493  		// Erase the whole stack. This path only occurs when
  4494  		// runtime.Goexit is called from within a runtime/secret.Do call.
  4495  		memclrNoHeapPointers(unsafe.Pointer(gp.stack.lo), gp.stack.hi-gp.stack.lo)
  4496  		// Since this is running on g0, our registers are already zeroed from going through
  4497  		// mcall in secret mode.
  4498  	}
  4499  	gdestroy(gp)
  4500  	schedule()
  4501  }
  4502  
  4503  func gdestroy(gp *g) {
  4504  	mp := getg().m
  4505  	pp := mp.p.ptr()
  4506  
  4507  	casgstatus(gp, _Grunning, _Gdead)
  4508  	gcController.addScannableStack(pp, -int64(gp.stack.hi-gp.stack.lo))
  4509  	if isSystemGoroutine(gp, false) {
  4510  		sched.ngsys.Add(-1)
  4511  	}
  4512  	gp.m = nil
  4513  	locked := gp.lockedm != 0
  4514  	gp.lockedm = 0
  4515  	mp.lockedg = 0
  4516  	gp.preemptStop = false
  4517  	gp.paniconfault = false
  4518  	gp._defer = nil // should be true already but just in case.
  4519  	gp._panic = nil // non-nil for Goexit during panic. points at stack-allocated data.
  4520  	gp.writebuf = nil
  4521  	gp.waitreason = waitReasonZero
  4522  	gp.param = nil
  4523  	gp.labels = nil
  4524  	gp.timer = nil
  4525  	gp.bubble = nil
  4526  	gp.fipsOnlyBypass = false
  4527  	gp.secret = 0
  4528  
  4529  	if gcBlackenEnabled != 0 && gp.gcAssistBytes > 0 {
  4530  		// Flush assist credit to the global pool. This gives
  4531  		// better information to pacing if the application is
  4532  		// rapidly creating an exiting goroutines.
  4533  		assistWorkPerByte := gcController.assistWorkPerByte.Load()
  4534  		scanCredit := int64(assistWorkPerByte * float64(gp.gcAssistBytes))
  4535  		gcController.bgScanCredit.Add(scanCredit)
  4536  		gp.gcAssistBytes = 0
  4537  	}
  4538  
  4539  	dropg()
  4540  
  4541  	if GOARCH == "wasm" { // no threads yet on wasm
  4542  		gfput(pp, gp)
  4543  		return
  4544  	}
  4545  
  4546  	if locked && mp.lockedInt != 0 {
  4547  		print("runtime: mp.lockedInt = ", mp.lockedInt, "\n")
  4548  		if mp.isextra {
  4549  			throw("runtime.Goexit called in a thread that was not created by the Go runtime")
  4550  		}
  4551  		throw("exited a goroutine internally locked to the OS thread")
  4552  	}
  4553  	gfput(pp, gp)
  4554  	if locked {
  4555  		// The goroutine may have locked this thread because
  4556  		// it put it in an unusual kernel state. Kill it
  4557  		// rather than returning it to the thread pool.
  4558  
  4559  		// Return to mstart, which will release the P and exit
  4560  		// the thread.
  4561  		if GOOS != "plan9" { // See golang.org/issue/22227.
  4562  			gogo(&mp.g0.sched)
  4563  		} else {
  4564  			// Clear lockedExt on plan9 since we may end up re-using
  4565  			// this thread.
  4566  			mp.lockedExt = 0
  4567  		}
  4568  	}
  4569  }
  4570  
  4571  // save updates getg().sched to refer to pc and sp so that a following
  4572  // gogo will restore pc and sp.
  4573  //
  4574  // save must not have write barriers because invoking a write barrier
  4575  // can clobber getg().sched.
  4576  //
  4577  //go:nosplit
  4578  //go:nowritebarrierrec
  4579  func save(pc, sp, bp uintptr) {
  4580  	gp := getg()
  4581  
  4582  	if gp == gp.m.g0 || gp == gp.m.gsignal {
  4583  		// m.g0.sched is special and must describe the context
  4584  		// for exiting the thread. mstart1 writes to it directly.
  4585  		// m.gsignal.sched should not be used at all.
  4586  		// This check makes sure save calls do not accidentally
  4587  		// run in contexts where they'd write to system g's.
  4588  		throw("save on system g not allowed")
  4589  	}
  4590  
  4591  	gp.sched.pc = pc
  4592  	gp.sched.sp = sp
  4593  	gp.sched.lr = 0
  4594  	gp.sched.bp = bp
  4595  	// We need to ensure ctxt is zero, but can't have a write
  4596  	// barrier here. However, it should always already be zero.
  4597  	// Assert that.
  4598  	if gp.sched.ctxt != nil {
  4599  		badctxt()
  4600  	}
  4601  }
  4602  
  4603  // The goroutine g is about to enter a system call.
  4604  // Record that it's not using the cpu anymore.
  4605  // This is called only from the go syscall library and cgocall,
  4606  // not from the low-level system calls used by the runtime.
  4607  //
  4608  // Entersyscall cannot split the stack: the save must
  4609  // make g->sched refer to the caller's stack segment, because
  4610  // entersyscall is going to return immediately after.
  4611  //
  4612  // Nothing entersyscall calls can split the stack either.
  4613  // We cannot safely move the stack during an active call to syscall,
  4614  // because we do not know which of the uintptr arguments are
  4615  // really pointers (back into the stack).
  4616  // In practice, this means that we make the fast path run through
  4617  // entersyscall doing no-split things, and the slow path has to use systemstack
  4618  // to run bigger things on the system stack.
  4619  //
  4620  // reentersyscall is the entry point used by cgo callbacks, where explicitly
  4621  // saved SP and PC are restored. This is needed when exitsyscall will be called
  4622  // from a function further up in the call stack than the parent, as g->syscallsp
  4623  // must always point to a valid stack frame. entersyscall below is the normal
  4624  // entry point for syscalls, which obtains the SP and PC from the caller.
  4625  //
  4626  //go:nosplit
  4627  func reentersyscall(pc, sp, bp uintptr) {
  4628  	gp := getg()
  4629  
  4630  	// Disable preemption because during this function g is in Gsyscall status,
  4631  	// but can have inconsistent g->sched, do not let GC observe it.
  4632  	gp.m.locks++
  4633  
  4634  	// Entersyscall must not call any function that might split/grow the stack.
  4635  	// (See details in comment above.)
  4636  	// Catch calls that might, by replacing the stack guard with something that
  4637  	// will trip any stack check and leaving a flag to tell newstack to die.
  4638  	gp.stackguard0 = stackPreempt
  4639  	gp.throwsplit = true
  4640  
  4641  	// Copy the syscalltick over so we can identify if the P got stolen later.
  4642  	gp.m.syscalltick = gp.m.p.ptr().syscalltick
  4643  
  4644  	pp := gp.m.p.ptr()
  4645  	if pp.runSafePointFn != 0 {
  4646  		// runSafePointFn may stack split if run on this stack
  4647  		systemstack(runSafePointFn)
  4648  	}
  4649  	gp.m.oldp.set(pp)
  4650  
  4651  	// Leave SP around for GC and traceback.
  4652  	save(pc, sp, bp)
  4653  	gp.syscallsp = sp
  4654  	gp.syscallpc = pc
  4655  	gp.syscallbp = bp
  4656  
  4657  	// Double-check sp and bp.
  4658  	if gp.syscallsp < gp.stack.lo || gp.stack.hi < gp.syscallsp {
  4659  		systemstack(func() {
  4660  			print("entersyscall inconsistent sp ", hex(gp.syscallsp), " [", hex(gp.stack.lo), ",", hex(gp.stack.hi), "]\n")
  4661  			throw("entersyscall")
  4662  		})
  4663  	}
  4664  	if gp.syscallbp != 0 && gp.syscallbp < gp.stack.lo || gp.stack.hi < gp.syscallbp {
  4665  		systemstack(func() {
  4666  			print("entersyscall inconsistent bp ", hex(gp.syscallbp), " [", hex(gp.stack.lo), ",", hex(gp.stack.hi), "]\n")
  4667  			throw("entersyscall")
  4668  		})
  4669  	}
  4670  	trace := traceAcquire()
  4671  	if trace.ok() {
  4672  		// Emit a trace event. Notably, actually emitting the event must happen before
  4673  		// the casgstatus because it mutates the P, but the traceLocker must be held
  4674  		// across the casgstatus since we're transitioning out of _Grunning
  4675  		// (see trace.go invariants).
  4676  		systemstack(func() {
  4677  			trace.GoSysCall()
  4678  		})
  4679  		// systemstack clobbered gp.sched, so restore it.
  4680  		save(pc, sp, bp)
  4681  	}
  4682  	if sched.gcwaiting.Load() {
  4683  		// Optimization: If there's a pending STW, do the equivalent of
  4684  		// entersyscallblock here at the last minute and immediately give
  4685  		// away our P.
  4686  		systemstack(func() {
  4687  			entersyscallHandleGCWait(trace)
  4688  		})
  4689  		// systemstack clobbered gp.sched, so restore it.
  4690  		save(pc, sp, bp)
  4691  	}
  4692  	// As soon as we switch to _Gsyscall, we are in danger of losing our P.
  4693  	// We must not touch it after this point.
  4694  	//
  4695  	// Try to do a quick CAS to avoid calling into casgstatus in the common case.
  4696  	// If we have a bubble, we need to fall into casgstatus.
  4697  	if gp.bubble != nil || !gp.atomicstatus.CompareAndSwap(_Grunning, _Gsyscall) {
  4698  		casgstatus(gp, _Grunning, _Gsyscall)
  4699  	}
  4700  	if staticLockRanking {
  4701  		// casgstatus clobbers gp.sched via systemstack under staticLockRanking. Restore it.
  4702  		save(pc, sp, bp)
  4703  	}
  4704  	if trace.ok() {
  4705  		// N.B. We don't need to go on the systemstack because traceRelease is very
  4706  		// carefully recursively nosplit. This also means we don't need to worry
  4707  		// about clobbering gp.sched.
  4708  		traceRelease(trace)
  4709  	}
  4710  	if sched.sysmonwait.Load() {
  4711  		systemstack(entersyscallWakeSysmon)
  4712  		// systemstack clobbered gp.sched, so restore it.
  4713  		save(pc, sp, bp)
  4714  	}
  4715  	gp.m.locks--
  4716  }
  4717  
  4718  // debugExtendGrunningNoP is a debug mode that extends the windows in which
  4719  // we're _Grunning without a P in order to try to shake out bugs with code
  4720  // assuming this state is impossible.
  4721  const debugExtendGrunningNoP = false
  4722  
  4723  // Standard syscall entry used by the go syscall library and normal cgo calls.
  4724  //
  4725  // This is exported via linkname to assembly in the syscall package and x/sys.
  4726  //
  4727  // Other packages should not be accessing entersyscall directly,
  4728  // but widely used packages access it using linkname.
  4729  // Notable members of the hall of shame include:
  4730  //   - gvisor.dev/gvisor
  4731  //
  4732  // Do not remove or change the type signature.
  4733  // See go.dev/issue/67401.
  4734  //
  4735  //go:nosplit
  4736  //go:linkname entersyscall
  4737  func entersyscall() {
  4738  	// N.B. getcallerfp cannot be written directly as argument in the call
  4739  	// to reentersyscall because it forces spilling the other arguments to
  4740  	// the stack. This results in exceeding the nosplit stack requirements
  4741  	// on some platforms.
  4742  	fp := getcallerfp()
  4743  	reentersyscall(sys.GetCallerPC(), sys.GetCallerSP(), fp)
  4744  }
  4745  
  4746  func entersyscallWakeSysmon() {
  4747  	lock(&sched.lock)
  4748  	if sched.sysmonwait.Load() {
  4749  		sched.sysmonwait.Store(false)
  4750  		notewakeup(&sched.sysmonnote)
  4751  	}
  4752  	unlock(&sched.lock)
  4753  }
  4754  
  4755  func entersyscallHandleGCWait(trace traceLocker) {
  4756  	gp := getg()
  4757  
  4758  	lock(&sched.lock)
  4759  	if sched.stopwait > 0 {
  4760  		// Set our P to _Pgcstop so the STW can take it.
  4761  		pp := gp.m.p.ptr()
  4762  		pp.m = 0
  4763  		gp.m.p = 0
  4764  		atomic.Store(&pp.status, _Pgcstop)
  4765  
  4766  		if trace.ok() {
  4767  			trace.ProcStop(pp)
  4768  		}
  4769  		addGSyscallNoP(gp.m) // We gave up our P voluntarily.
  4770  		pp.gcStopTime = nanotime()
  4771  		pp.syscalltick++
  4772  		if sched.stopwait--; sched.stopwait == 0 {
  4773  			notewakeup(&sched.stopnote)
  4774  		}
  4775  	}
  4776  	unlock(&sched.lock)
  4777  }
  4778  
  4779  // The same as entersyscall(), but with a hint that the syscall is blocking.
  4780  
  4781  // entersyscallblock should be an internal detail,
  4782  // but widely used packages access it using linkname.
  4783  // Notable members of the hall of shame include:
  4784  //   - gvisor.dev/gvisor
  4785  //
  4786  // Do not remove or change the type signature.
  4787  // See go.dev/issue/67401.
  4788  //
  4789  //go:linkname entersyscallblock
  4790  //go:nosplit
  4791  func entersyscallblock() {
  4792  	gp := getg()
  4793  
  4794  	gp.m.locks++ // see comment in entersyscall
  4795  	gp.throwsplit = true
  4796  	gp.stackguard0 = stackPreempt // see comment in entersyscall
  4797  	gp.m.syscalltick = gp.m.p.ptr().syscalltick
  4798  	gp.m.p.ptr().syscalltick++
  4799  
  4800  	addGSyscallNoP(gp.m) // We're going to give up our P.
  4801  
  4802  	// Leave SP around for GC and traceback.
  4803  	pc := sys.GetCallerPC()
  4804  	sp := sys.GetCallerSP()
  4805  	bp := getcallerfp()
  4806  	save(pc, sp, bp)
  4807  	gp.syscallsp = gp.sched.sp
  4808  	gp.syscallpc = gp.sched.pc
  4809  	gp.syscallbp = gp.sched.bp
  4810  	if gp.syscallsp < gp.stack.lo || gp.stack.hi < gp.syscallsp {
  4811  		sp1 := sp
  4812  		sp2 := gp.sched.sp
  4813  		sp3 := gp.syscallsp
  4814  		systemstack(func() {
  4815  			print("entersyscallblock inconsistent sp ", hex(sp1), " ", hex(sp2), " ", hex(sp3), " [", hex(gp.stack.lo), ",", hex(gp.stack.hi), "]\n")
  4816  			throw("entersyscallblock")
  4817  		})
  4818  	}
  4819  
  4820  	// Once we switch to _Gsyscall, we can't safely touch
  4821  	// our P anymore, so we need to hand it off beforehand.
  4822  	// The tracer also needs to see the syscall before the P
  4823  	// handoff, so the order here must be (1) trace,
  4824  	// (2) handoff, (3) _Gsyscall switch.
  4825  	trace := traceAcquire()
  4826  	systemstack(func() {
  4827  		if trace.ok() {
  4828  			trace.GoSysCall()
  4829  		}
  4830  		handoffp(releasep())
  4831  	})
  4832  	// <--
  4833  	// Caution: we're in a small window where we are in _Grunning without a P.
  4834  	// -->
  4835  	if debugExtendGrunningNoP {
  4836  		usleep(10)
  4837  	}
  4838  	casgstatus(gp, _Grunning, _Gsyscall)
  4839  	if gp.syscallsp < gp.stack.lo || gp.stack.hi < gp.syscallsp {
  4840  		systemstack(func() {
  4841  			print("entersyscallblock inconsistent sp ", hex(sp), " ", hex(gp.sched.sp), " ", hex(gp.syscallsp), " [", hex(gp.stack.lo), ",", hex(gp.stack.hi), "]\n")
  4842  			throw("entersyscallblock")
  4843  		})
  4844  	}
  4845  	if gp.syscallbp != 0 && gp.syscallbp < gp.stack.lo || gp.stack.hi < gp.syscallbp {
  4846  		systemstack(func() {
  4847  			print("entersyscallblock inconsistent bp ", hex(bp), " ", hex(gp.sched.bp), " ", hex(gp.syscallbp), " [", hex(gp.stack.lo), ",", hex(gp.stack.hi), "]\n")
  4848  			throw("entersyscallblock")
  4849  		})
  4850  	}
  4851  	if trace.ok() {
  4852  		systemstack(func() {
  4853  			traceRelease(trace)
  4854  		})
  4855  	}
  4856  
  4857  	// Resave for traceback during blocked call.
  4858  	save(sys.GetCallerPC(), sys.GetCallerSP(), getcallerfp())
  4859  
  4860  	gp.m.locks--
  4861  }
  4862  
  4863  // The goroutine g exited its system call.
  4864  // Arrange for it to run on a cpu again.
  4865  // This is called only from the go syscall library, not
  4866  // from the low-level system calls used by the runtime.
  4867  //
  4868  // Write barriers are not allowed because our P may have been stolen.
  4869  //
  4870  // This is exported via linkname to assembly in the syscall package.
  4871  //
  4872  // exitsyscall should be an internal detail,
  4873  // but widely used packages access it using linkname.
  4874  // Notable members of the hall of shame include:
  4875  //   - gvisor.dev/gvisor
  4876  //
  4877  // Do not remove or change the type signature.
  4878  // See go.dev/issue/67401.
  4879  //
  4880  //go:nosplit
  4881  //go:nowritebarrierrec
  4882  //go:linkname exitsyscall
  4883  func exitsyscall() {
  4884  	gp := getg()
  4885  
  4886  	gp.m.locks++ // see comment in entersyscall
  4887  	if sys.GetCallerSP() > gp.syscallsp {
  4888  		throw("exitsyscall: syscall frame is no longer valid")
  4889  	}
  4890  	gp.waitsince = 0
  4891  
  4892  	if sched.stopwait == freezeStopWait {
  4893  		// Wedge ourselves if there's an outstanding freezetheworld.
  4894  		// If we transition to running, we might end up with our traceback
  4895  		// being taken twice.
  4896  		systemstack(func() {
  4897  			lock(&deadlock)
  4898  			lock(&deadlock)
  4899  		})
  4900  	}
  4901  
  4902  	// Optimistically assume we're going to keep running, and switch to running.
  4903  	// Before this point, our P wiring is not ours. Once we get past this point,
  4904  	// we can access our P if we have it, otherwise we lost it.
  4905  	//
  4906  	// N.B. Because we're transitioning to _Grunning here, traceAcquire doesn't
  4907  	// need to be held ahead of time. We're effectively atomic with respect to
  4908  	// the tracer because we're non-preemptible and in the runtime. It can't stop
  4909  	// us to read a bad status.
  4910  	//
  4911  	// Try to do a quick CAS to avoid calling into casgstatus in the common case.
  4912  	// If we have a bubble, we need to fall into casgstatus.
  4913  	if gp.bubble != nil || !gp.atomicstatus.CompareAndSwap(_Gsyscall, _Grunning) {
  4914  		casgstatus(gp, _Gsyscall, _Grunning)
  4915  	}
  4916  
  4917  	// Caution: we're in a window where we may be in _Grunning without a P.
  4918  	// Either we will grab a P or call exitsyscall0, where we'll switch to
  4919  	// _Grunnable.
  4920  	if debugExtendGrunningNoP {
  4921  		usleep(10)
  4922  	}
  4923  
  4924  	// Grab and clear our old P.
  4925  	oldp := gp.m.oldp.ptr()
  4926  	gp.m.oldp.set(nil)
  4927  
  4928  	// Check if we still have a P, and if not, try to acquire an idle P.
  4929  	pp := gp.m.p.ptr()
  4930  	if pp != nil {
  4931  		// Fast path: we still have our P. Just emit a syscall exit event.
  4932  		if trace := traceAcquire(); trace.ok() {
  4933  			systemstack(func() {
  4934  				// The truth is we truly never lost the P, but syscalltick
  4935  				// is used to indicate whether the P should be treated as
  4936  				// lost anyway. For example, when syscalltick is trashed by
  4937  				// dropm.
  4938  				//
  4939  				// TODO(mknyszek): Consider a more explicit mechanism for this.
  4940  				// Then syscalltick doesn't need to be trashed, and can be used
  4941  				// exclusively by sysmon for deciding when it's time to retake.
  4942  				if pp.syscalltick == gp.m.syscalltick {
  4943  					trace.GoSysExit(false)
  4944  				} else {
  4945  					// Since we need to pretend we lost the P, but nobody ever
  4946  					// took it, we need a ProcSteal event to model the loss.
  4947  					// Then, continue with everything else we'd do if we lost
  4948  					// the P.
  4949  					trace.ProcSteal(pp)
  4950  					trace.ProcStart()
  4951  					trace.GoSysExit(true)
  4952  					trace.GoStart()
  4953  				}
  4954  				traceRelease(trace)
  4955  			})
  4956  		}
  4957  	} else {
  4958  		// Slow path: we lost our P. Try to get another one.
  4959  		systemstack(func() {
  4960  			// Try to get some other P.
  4961  			if pp := exitsyscallTryGetP(oldp); pp != nil {
  4962  				// Install the P.
  4963  				acquirepNoTrace(pp)
  4964  
  4965  				// We're going to start running again, so emit all the relevant events.
  4966  				if trace := traceAcquire(); trace.ok() {
  4967  					trace.ProcStart()
  4968  					trace.GoSysExit(true)
  4969  					trace.GoStart()
  4970  					traceRelease(trace)
  4971  				}
  4972  			}
  4973  		})
  4974  		pp = gp.m.p.ptr()
  4975  	}
  4976  
  4977  	// If we have a P, clean up and exit.
  4978  	if pp != nil {
  4979  		if goroutineProfile.active {
  4980  			// Make sure that gp has had its stack written out to the goroutine
  4981  			// profile, exactly as it was when the goroutine profiler first
  4982  			// stopped the world.
  4983  			systemstack(func() {
  4984  				tryRecordGoroutineProfileWB(gp)
  4985  			})
  4986  		}
  4987  
  4988  		// Increment the syscalltick for P, since we're exiting a syscall.
  4989  		pp.syscalltick++
  4990  
  4991  		// Garbage collector isn't running (since we are),
  4992  		// so okay to clear syscallsp.
  4993  		gp.syscallsp = 0
  4994  		gp.m.locks--
  4995  		if gp.preempt {
  4996  			// Restore the preemption request in case we cleared it in newstack.
  4997  			gp.stackguard0 = stackPreempt
  4998  		} else {
  4999  			// Otherwise restore the real stackGuard, we clobbered it in entersyscall/entersyscallblock.
  5000  			gp.stackguard0 = gp.stack.lo + stackGuard
  5001  		}
  5002  		gp.throwsplit = false
  5003  
  5004  		if sched.disable.user && !schedEnabled(gp) {
  5005  			// Scheduling of this goroutine is disabled.
  5006  			Gosched()
  5007  		}
  5008  		return
  5009  	}
  5010  	// Slowest path: We couldn't get a P, so call into the scheduler.
  5011  	gp.m.locks--
  5012  
  5013  	// Call the scheduler.
  5014  	mcall(exitsyscallNoP)
  5015  
  5016  	// Scheduler returned, so we're allowed to run now.
  5017  	// Delete the syscallsp information that we left for
  5018  	// the garbage collector during the system call.
  5019  	// Must wait until now because until gosched returns
  5020  	// we don't know for sure that the garbage collector
  5021  	// is not running.
  5022  	gp.syscallsp = 0
  5023  	gp.m.p.ptr().syscalltick++
  5024  	gp.throwsplit = false
  5025  }
  5026  
  5027  // exitsyscall's attempt to try to get any P, if it's missing one.
  5028  // Returns true on success.
  5029  //
  5030  // Must execute on the systemstack because exitsyscall is nosplit.
  5031  //
  5032  //go:systemstack
  5033  func exitsyscallTryGetP(oldp *p) *p {
  5034  	// Try to steal our old P back.
  5035  	if oldp != nil {
  5036  		if thread, ok := setBlockOnExitSyscall(oldp); ok {
  5037  			thread.takeP()
  5038  			decGSyscallNoP(getg().m) // We got a P for ourselves.
  5039  			thread.resume()
  5040  			return oldp
  5041  		}
  5042  	}
  5043  
  5044  	// Try to get an idle P.
  5045  	if sched.pidle != 0 {
  5046  		lock(&sched.lock)
  5047  		pp, _ := pidleget(0)
  5048  		if pp != nil && sched.sysmonwait.Load() {
  5049  			sched.sysmonwait.Store(false)
  5050  			notewakeup(&sched.sysmonnote)
  5051  		}
  5052  		unlock(&sched.lock)
  5053  		if pp != nil {
  5054  			decGSyscallNoP(getg().m) // We got a P for ourselves.
  5055  			return pp
  5056  		}
  5057  	}
  5058  	return nil
  5059  }
  5060  
  5061  // exitsyscall slow path on g0.
  5062  // Failed to acquire P, enqueue gp as runnable.
  5063  //
  5064  // Called via mcall, so gp is the calling g from this M.
  5065  //
  5066  //go:nowritebarrierrec
  5067  func exitsyscallNoP(gp *g) {
  5068  	traceExitingSyscall()
  5069  	trace := traceAcquire()
  5070  	casgstatus(gp, _Grunning, _Grunnable)
  5071  	traceExitedSyscall()
  5072  	if trace.ok() {
  5073  		// Write out syscall exit eagerly.
  5074  		//
  5075  		// It's important that we write this *after* we know whether we
  5076  		// lost our P or not (determined by exitsyscallfast).
  5077  		trace.GoSysExit(true)
  5078  		traceRelease(trace)
  5079  	}
  5080  	decGSyscallNoP(getg().m)
  5081  	dropg()
  5082  	lock(&sched.lock)
  5083  	var pp *p
  5084  	if schedEnabled(gp) {
  5085  		pp, _ = pidleget(0)
  5086  	}
  5087  	var locked bool
  5088  	if pp == nil {
  5089  		globrunqput(gp)
  5090  
  5091  		// Below, we stoplockedm if gp is locked. globrunqput releases
  5092  		// ownership of gp, so we must check if gp is locked prior to
  5093  		// committing the release by unlocking sched.lock, otherwise we
  5094  		// could race with another M transitioning gp from unlocked to
  5095  		// locked.
  5096  		locked = gp.lockedm != 0
  5097  	} else if sched.sysmonwait.Load() {
  5098  		sched.sysmonwait.Store(false)
  5099  		notewakeup(&sched.sysmonnote)
  5100  	}
  5101  	unlock(&sched.lock)
  5102  	if pp != nil {
  5103  		acquirep(pp)
  5104  		execute(gp, false) // Never returns.
  5105  	}
  5106  	if locked {
  5107  		// Wait until another thread schedules gp and so m again.
  5108  		//
  5109  		// N.B. lockedm must be this M, as this g was running on this M
  5110  		// before entersyscall.
  5111  		stoplockedm()
  5112  		execute(gp, false) // Never returns.
  5113  	}
  5114  	stopm()
  5115  	schedule() // Never returns.
  5116  }
  5117  
  5118  // addGSyscallNoP must be called when a goroutine in a syscall loses its P.
  5119  // This function updates all relevant accounting.
  5120  //
  5121  // nosplit because it's called on the syscall paths.
  5122  //
  5123  //go:nosplit
  5124  func addGSyscallNoP(mp *m) {
  5125  	// It's safe to read isExtraInC here because it's only mutated
  5126  	// outside of _Gsyscall, and we know this thread is attached
  5127  	// to a goroutine in _Gsyscall and blocked from exiting.
  5128  	if !mp.isExtraInC {
  5129  		// Increment nGsyscallNoP since we're taking away a P
  5130  		// from a _Gsyscall goroutine, but only if isExtraInC
  5131  		// is not set on the M. If it is, then this thread is
  5132  		// back to being a full C thread, and will just inflate
  5133  		// the count of not-in-go goroutines. See go.dev/issue/76435.
  5134  		sched.nGsyscallNoP.Add(1)
  5135  	}
  5136  }
  5137  
  5138  // decGSsyscallNoP must be called whenever a goroutine in a syscall without
  5139  // a P exits the system call. This function updates all relevant accounting.
  5140  //
  5141  // nosplit because it's called from dropm.
  5142  //
  5143  //go:nosplit
  5144  func decGSyscallNoP(mp *m) {
  5145  	// Update nGsyscallNoP, but only if this is not a thread coming
  5146  	// out of C. See the comment in addGSyscallNoP. This logic must match,
  5147  	// to avoid unmatched increments and decrements.
  5148  	if !mp.isExtraInC {
  5149  		sched.nGsyscallNoP.Add(-1)
  5150  	}
  5151  }
  5152  
  5153  // Called from syscall package before fork.
  5154  //
  5155  // syscall_runtime_BeforeFork is for package syscall,
  5156  // but widely used packages access it using linkname.
  5157  // Notable members of the hall of shame include:
  5158  //   - gvisor.dev/gvisor
  5159  //
  5160  // Do not remove or change the type signature.
  5161  // See go.dev/issue/67401.
  5162  //
  5163  //go:linkname syscall_runtime_BeforeFork syscall.runtime_BeforeFork
  5164  //go:nosplit
  5165  func syscall_runtime_BeforeFork() {
  5166  	gp := getg().m.curg
  5167  
  5168  	// Block signals during a fork, so that the child does not run
  5169  	// a signal handler before exec if a signal is sent to the process
  5170  	// group. See issue #18600.
  5171  	gp.m.locks++
  5172  	sigsave(&gp.m.sigmask)
  5173  	sigblock(false)
  5174  
  5175  	// This function is called before fork in syscall package.
  5176  	// Code between fork and exec must not allocate memory nor even try to grow stack.
  5177  	// Here we spoil g.stackguard0 to reliably detect any attempts to grow stack.
  5178  	// runtime_AfterFork will undo this in parent process, but not in child.
  5179  	gp.stackguard0 = stackFork
  5180  }
  5181  
  5182  // Called from syscall package after fork in parent.
  5183  //
  5184  // syscall_runtime_AfterFork is for package syscall,
  5185  // but widely used packages access it using linkname.
  5186  // Notable members of the hall of shame include:
  5187  //   - gvisor.dev/gvisor
  5188  //
  5189  // Do not remove or change the type signature.
  5190  // See go.dev/issue/67401.
  5191  //
  5192  //go:linkname syscall_runtime_AfterFork syscall.runtime_AfterFork
  5193  //go:nosplit
  5194  func syscall_runtime_AfterFork() {
  5195  	gp := getg().m.curg
  5196  
  5197  	// See the comments in beforefork.
  5198  	gp.stackguard0 = gp.stack.lo + stackGuard
  5199  
  5200  	msigrestore(gp.m.sigmask)
  5201  
  5202  	gp.m.locks--
  5203  }
  5204  
  5205  // inForkedChild is true while manipulating signals in the child process.
  5206  // This is used to avoid calling libc functions in case we are using vfork.
  5207  var inForkedChild bool
  5208  
  5209  // Called from syscall package after fork in child.
  5210  // It resets non-sigignored signals to the default handler, and
  5211  // restores the signal mask in preparation for the exec.
  5212  //
  5213  // Because this might be called during a vfork, and therefore may be
  5214  // temporarily sharing address space with the parent process, this must
  5215  // not change any global variables or calling into C code that may do so.
  5216  //
  5217  // syscall_runtime_AfterForkInChild is for package syscall,
  5218  // but widely used packages access it using linkname.
  5219  // Notable members of the hall of shame include:
  5220  //   - gvisor.dev/gvisor
  5221  //
  5222  // Do not remove or change the type signature.
  5223  // See go.dev/issue/67401.
  5224  //
  5225  //go:linkname syscall_runtime_AfterForkInChild syscall.runtime_AfterForkInChild
  5226  //go:nosplit
  5227  //go:nowritebarrierrec
  5228  func syscall_runtime_AfterForkInChild() {
  5229  	// It's OK to change the global variable inForkedChild here
  5230  	// because we are going to change it back. There is no race here,
  5231  	// because if we are sharing address space with the parent process,
  5232  	// then the parent process can not be running concurrently.
  5233  	inForkedChild = true
  5234  
  5235  	clearSignalHandlers()
  5236  
  5237  	// When we are the child we are the only thread running,
  5238  	// so we know that nothing else has changed gp.m.sigmask.
  5239  	msigrestore(getg().m.sigmask)
  5240  
  5241  	inForkedChild = false
  5242  }
  5243  
  5244  // pendingPreemptSignals is the number of preemption signals
  5245  // that have been sent but not received. This is only used on Darwin.
  5246  // For #41702.
  5247  var pendingPreemptSignals atomic.Int32
  5248  
  5249  // Called from syscall package before Exec.
  5250  //
  5251  //go:linkname syscall_runtime_BeforeExec syscall.runtime_BeforeExec
  5252  func syscall_runtime_BeforeExec() {
  5253  	// Prevent thread creation during exec.
  5254  	execLock.lock()
  5255  
  5256  	// On Darwin, wait for all pending preemption signals to
  5257  	// be received. See issue #41702.
  5258  	if GOOS == "darwin" || GOOS == "ios" {
  5259  		for pendingPreemptSignals.Load() > 0 {
  5260  			osyield()
  5261  		}
  5262  	}
  5263  }
  5264  
  5265  // Called from syscall package after Exec.
  5266  //
  5267  //go:linkname syscall_runtime_AfterExec syscall.runtime_AfterExec
  5268  func syscall_runtime_AfterExec() {
  5269  	execLock.unlock()
  5270  }
  5271  
  5272  // Allocate a new g, with a stack big enough for stacksize bytes.
  5273  func malg(stacksize int32) *g {
  5274  	newg := new(g)
  5275  	if stacksize >= 0 {
  5276  		stacksize = round2(stackSystem + stacksize)
  5277  		systemstack(func() {
  5278  			newg.stack = stackalloc(uint32(stacksize))
  5279  			if valgrindenabled {
  5280  				newg.valgrindStackID = valgrindRegisterStack(unsafe.Pointer(newg.stack.lo), unsafe.Pointer(newg.stack.hi))
  5281  			}
  5282  		})
  5283  		newg.stackguard0 = newg.stack.lo + stackGuard
  5284  		newg.stackguard1 = ^uintptr(0)
  5285  		// Clear the bottom word of the stack. We record g
  5286  		// there on gsignal stack during VDSO on ARM and ARM64.
  5287  		*(*uintptr)(unsafe.Pointer(newg.stack.lo)) = 0
  5288  	}
  5289  	return newg
  5290  }
  5291  
  5292  // Create a new g running fn.
  5293  // Put it on the queue of g's waiting to run.
  5294  // The compiler turns a go statement into a call to this.
  5295  func newproc(fn *funcval) {
  5296  	gp := getg()
  5297  	pc := sys.GetCallerPC()
  5298  	systemstack(func() {
  5299  		newg := newproc1(fn, gp, pc, false, waitReasonZero)
  5300  
  5301  		pp := getg().m.p.ptr()
  5302  		runqput(pp, newg, true)
  5303  
  5304  		if mainStarted {
  5305  			wakep()
  5306  		}
  5307  	})
  5308  }
  5309  
  5310  // Create a new g in state _Grunnable (or _Gwaiting if parked is true), starting at fn.
  5311  // callerpc is the address of the go statement that created this. The caller is responsible
  5312  // for adding the new g to the scheduler. If parked is true, waitreason must be non-zero.
  5313  func newproc1(fn *funcval, callergp *g, callerpc uintptr, parked bool, waitreason waitReason) *g {
  5314  	if fn == nil {
  5315  		fatal("go of nil func value")
  5316  	}
  5317  
  5318  	mp := acquirem() // disable preemption because we hold M and P in local vars.
  5319  	pp := mp.p.ptr()
  5320  	newg := gfget(pp)
  5321  	if newg == nil {
  5322  		newg = malg(stackMin)
  5323  		casgstatus(newg, _Gidle, _Gdead)
  5324  		allgadd(newg) // publishes with a g->status of Gdead so GC scanner doesn't look at uninitialized stack.
  5325  	}
  5326  	if newg.stack.hi == 0 {
  5327  		throw("newproc1: newg missing stack")
  5328  	}
  5329  
  5330  	if readgstatus(newg) != _Gdead {
  5331  		throw("newproc1: new g is not Gdead")
  5332  	}
  5333  
  5334  	totalSize := uintptr(4*goarch.PtrSize + sys.MinFrameSize) // extra space in case of reads slightly beyond frame
  5335  	totalSize = alignUp(totalSize, sys.StackAlign)
  5336  	sp := newg.stack.hi - totalSize
  5337  	if usesLR {
  5338  		// caller's LR
  5339  		*(*uintptr)(unsafe.Pointer(sp)) = 0
  5340  		prepGoExitFrame(sp)
  5341  	}
  5342  	if GOARCH == "arm64" {
  5343  		// caller's FP
  5344  		*(*uintptr)(unsafe.Pointer(sp - goarch.PtrSize)) = 0
  5345  	}
  5346  
  5347  	memclrNoHeapPointers(unsafe.Pointer(&newg.sched), unsafe.Sizeof(newg.sched))
  5348  	newg.sched.sp = sp
  5349  	newg.stktopsp = sp
  5350  	newg.sched.pc = abi.FuncPCABI0(goexit) + sys.PCQuantum // +PCQuantum so that previous instruction is in same function
  5351  	newg.sched.g = guintptr(unsafe.Pointer(newg))
  5352  	gostartcallfn(&newg.sched, fn)
  5353  	newg.parentGoid = callergp.goid
  5354  	newg.gopc = callerpc
  5355  	newg.ancestors = saveAncestors(callergp)
  5356  	newg.startpc = fn.fn
  5357  	newg.runningCleanups.Store(false)
  5358  	if isSystemGoroutine(newg, false) {
  5359  		sched.ngsys.Add(1)
  5360  	} else {
  5361  		// Only user goroutines inherit synctest groups and pprof labels.
  5362  		newg.bubble = callergp.bubble
  5363  		if mp.curg != nil {
  5364  			newg.labels = mp.curg.labels
  5365  		}
  5366  		if goroutineProfile.active {
  5367  			// A concurrent goroutine profile is running. It should include
  5368  			// exactly the set of goroutines that were alive when the goroutine
  5369  			// profiler first stopped the world. That does not include newg, so
  5370  			// mark it as not needing a profile before transitioning it from
  5371  			// _Gdead.
  5372  			newg.goroutineProfiled.Store(goroutineProfileSatisfied)
  5373  		}
  5374  	}
  5375  	// Track initial transition?
  5376  	newg.trackingSeq = uint8(cheaprand())
  5377  	if newg.trackingSeq%gTrackingPeriod == 0 {
  5378  		newg.tracking = true
  5379  	}
  5380  	gcController.addScannableStack(pp, int64(newg.stack.hi-newg.stack.lo))
  5381  
  5382  	// Get a goid and switch to runnable. This needs to happen under traceAcquire
  5383  	// since it's a goroutine transition. See tracer invariants in trace.go.
  5384  	trace := traceAcquire()
  5385  	var status uint32 = _Grunnable
  5386  	if parked {
  5387  		status = _Gwaiting
  5388  		newg.waitreason = waitreason
  5389  	}
  5390  	if pp.goidcache == pp.goidcacheend {
  5391  		// Sched.goidgen is the last allocated id,
  5392  		// this batch must be [sched.goidgen+1, sched.goidgen+GoidCacheBatch].
  5393  		// At startup sched.goidgen=0, so main goroutine receives goid=1.
  5394  		pp.goidcache = sched.goidgen.Add(_GoidCacheBatch)
  5395  		pp.goidcache -= _GoidCacheBatch - 1
  5396  		pp.goidcacheend = pp.goidcache + _GoidCacheBatch
  5397  	}
  5398  	newg.goid = pp.goidcache
  5399  	casgstatus(newg, _Gdead, status)
  5400  	pp.goidcache++
  5401  	newg.trace.reset()
  5402  	if trace.ok() {
  5403  		trace.GoCreate(newg, newg.startpc, parked)
  5404  		traceRelease(trace)
  5405  	}
  5406  
  5407  	// fips140 bubble
  5408  	newg.fipsOnlyBypass = callergp.fipsOnlyBypass
  5409  
  5410  	// dit bubble
  5411  	newg.ditWanted = callergp.ditWanted
  5412  
  5413  	// Set up race context.
  5414  	if raceenabled {
  5415  		newg.racectx = racegostart(callerpc)
  5416  		newg.raceignore = 0
  5417  		if newg.labels != nil {
  5418  			// See note in proflabel.go on labelSync's role in synchronizing
  5419  			// with the reads in the signal handler.
  5420  			racereleasemergeg(newg, unsafe.Pointer(&labelSync))
  5421  		}
  5422  	}
  5423  	pp.goroutinesCreated++
  5424  	releasem(mp)
  5425  
  5426  	return newg
  5427  }
  5428  
  5429  // saveAncestors copies previous ancestors of the given caller g and
  5430  // includes info for the current caller into a new set of tracebacks for
  5431  // a g being created.
  5432  func saveAncestors(callergp *g) *[]ancestorInfo {
  5433  	// Copy all prior info, except for the root goroutine (goid 0).
  5434  	if debug.tracebackancestors <= 0 || callergp.goid == 0 {
  5435  		return nil
  5436  	}
  5437  	var callerAncestors []ancestorInfo
  5438  	if callergp.ancestors != nil {
  5439  		callerAncestors = *callergp.ancestors
  5440  	}
  5441  	n := int32(len(callerAncestors)) + 1
  5442  	if n > debug.tracebackancestors {
  5443  		n = debug.tracebackancestors
  5444  	}
  5445  	ancestors := make([]ancestorInfo, n)
  5446  	copy(ancestors[1:], callerAncestors)
  5447  
  5448  	var pcs [tracebackInnerFrames]uintptr
  5449  	npcs := gcallers(callergp, 0, pcs[:])
  5450  	ipcs := make([]uintptr, npcs)
  5451  	copy(ipcs, pcs[:])
  5452  	ancestors[0] = ancestorInfo{
  5453  		pcs:  ipcs,
  5454  		goid: callergp.goid,
  5455  		gopc: callergp.gopc,
  5456  	}
  5457  
  5458  	ancestorsp := new([]ancestorInfo)
  5459  	*ancestorsp = ancestors
  5460  	return ancestorsp
  5461  }
  5462  
  5463  // Put on gfree list.
  5464  // If local list is too long, transfer a batch to the global list.
  5465  func gfput(pp *p, gp *g) {
  5466  	if readgstatus(gp) != _Gdead {
  5467  		throw("gfput: bad status (not Gdead)")
  5468  	}
  5469  
  5470  	stksize := gp.stack.hi - gp.stack.lo
  5471  
  5472  	if stksize != uintptr(startingStackSize) {
  5473  		// non-standard stack size - free it.
  5474  		stackfree(gp.stack)
  5475  		gp.stack.lo = 0
  5476  		gp.stack.hi = 0
  5477  		gp.stackguard0 = 0
  5478  		if valgrindenabled {
  5479  			valgrindDeregisterStack(gp.valgrindStackID)
  5480  			gp.valgrindStackID = 0
  5481  		}
  5482  	}
  5483  
  5484  	pp.gFree.push(gp)
  5485  	if pp.gFree.size >= 64 {
  5486  		var (
  5487  			stackQ   gQueue
  5488  			noStackQ gQueue
  5489  		)
  5490  		for pp.gFree.size >= 32 {
  5491  			gp := pp.gFree.pop()
  5492  			if gp.stack.lo == 0 {
  5493  				noStackQ.push(gp)
  5494  			} else {
  5495  				stackQ.push(gp)
  5496  			}
  5497  		}
  5498  		lock(&sched.gFree.lock)
  5499  		sched.gFree.noStack.pushAll(noStackQ)
  5500  		sched.gFree.stack.pushAll(stackQ)
  5501  		unlock(&sched.gFree.lock)
  5502  	}
  5503  }
  5504  
  5505  // Get from gfree list.
  5506  // If local list is empty, grab a batch from global list.
  5507  func gfget(pp *p) *g {
  5508  retry:
  5509  	if pp.gFree.empty() && (!sched.gFree.stack.empty() || !sched.gFree.noStack.empty()) {
  5510  		lock(&sched.gFree.lock)
  5511  		// Move a batch of free Gs to the P.
  5512  		for pp.gFree.size < 32 {
  5513  			// Prefer Gs with stacks.
  5514  			gp := sched.gFree.stack.pop()
  5515  			if gp == nil {
  5516  				gp = sched.gFree.noStack.pop()
  5517  				if gp == nil {
  5518  					break
  5519  				}
  5520  			}
  5521  			pp.gFree.push(gp)
  5522  		}
  5523  		unlock(&sched.gFree.lock)
  5524  		goto retry
  5525  	}
  5526  	gp := pp.gFree.pop()
  5527  	if gp == nil {
  5528  		return nil
  5529  	}
  5530  	if gp.stack.lo != 0 && gp.stack.hi-gp.stack.lo != uintptr(startingStackSize) {
  5531  		// Deallocate old stack. We kept it in gfput because it was the
  5532  		// right size when the goroutine was put on the free list, but
  5533  		// the right size has changed since then.
  5534  		systemstack(func() {
  5535  			stackfree(gp.stack)
  5536  			gp.stack.lo = 0
  5537  			gp.stack.hi = 0
  5538  			gp.stackguard0 = 0
  5539  			if valgrindenabled {
  5540  				valgrindDeregisterStack(gp.valgrindStackID)
  5541  				gp.valgrindStackID = 0
  5542  			}
  5543  		})
  5544  	}
  5545  	if gp.stack.lo == 0 {
  5546  		// Stack was deallocated in gfput or just above. Allocate a new one.
  5547  		systemstack(func() {
  5548  			gp.stack = stackalloc(startingStackSize)
  5549  			if valgrindenabled {
  5550  				gp.valgrindStackID = valgrindRegisterStack(unsafe.Pointer(gp.stack.lo), unsafe.Pointer(gp.stack.hi))
  5551  			}
  5552  		})
  5553  		gp.stackguard0 = gp.stack.lo + stackGuard
  5554  	} else {
  5555  		if raceenabled {
  5556  			racemalloc(unsafe.Pointer(gp.stack.lo), gp.stack.hi-gp.stack.lo)
  5557  		}
  5558  		if msanenabled {
  5559  			msanmalloc(unsafe.Pointer(gp.stack.lo), gp.stack.hi-gp.stack.lo)
  5560  		}
  5561  		if asanenabled {
  5562  			asanunpoison(unsafe.Pointer(gp.stack.lo), gp.stack.hi-gp.stack.lo)
  5563  		}
  5564  	}
  5565  	return gp
  5566  }
  5567  
  5568  // Purge all cached G's from gfree list to the global list.
  5569  func gfpurge(pp *p) {
  5570  	var (
  5571  		stackQ   gQueue
  5572  		noStackQ gQueue
  5573  	)
  5574  	for !pp.gFree.empty() {
  5575  		gp := pp.gFree.pop()
  5576  		if gp.stack.lo == 0 {
  5577  			noStackQ.push(gp)
  5578  		} else {
  5579  			stackQ.push(gp)
  5580  		}
  5581  	}
  5582  	lock(&sched.gFree.lock)
  5583  	sched.gFree.noStack.pushAll(noStackQ)
  5584  	sched.gFree.stack.pushAll(stackQ)
  5585  	unlock(&sched.gFree.lock)
  5586  }
  5587  
  5588  // Breakpoint executes a breakpoint trap.
  5589  func Breakpoint() {
  5590  	breakpoint()
  5591  }
  5592  
  5593  // dolockOSThread is called by LockOSThread and lockOSThread below
  5594  // after they modify m.locked. Do not allow preemption during this call,
  5595  // or else the m might be different in this function than in the caller.
  5596  //
  5597  //go:nosplit
  5598  func dolockOSThread() {
  5599  	if GOARCH == "wasm" {
  5600  		return // no threads on wasm yet
  5601  	}
  5602  	gp := getg()
  5603  	gp.m.lockedg.set(gp)
  5604  	gp.lockedm.set(gp.m)
  5605  }
  5606  
  5607  // LockOSThread wires the calling goroutine to its current operating system thread.
  5608  // The calling goroutine will always execute in that thread,
  5609  // and no other goroutine will execute in it,
  5610  // until the calling goroutine has made as many calls to
  5611  // [UnlockOSThread] as to LockOSThread.
  5612  // If the calling goroutine exits without unlocking the thread,
  5613  // the thread will be terminated.
  5614  //
  5615  // All init functions are run on the startup thread. Calling LockOSThread
  5616  // from an init function will cause the main function to be invoked on
  5617  // that thread.
  5618  //
  5619  // A goroutine should call LockOSThread before calling OS services or
  5620  // non-Go library functions that depend on per-thread state.
  5621  //
  5622  //go:nosplit
  5623  func LockOSThread() {
  5624  	if atomic.Load(&newmHandoff.haveTemplateThread) == 0 && GOOS != "plan9" {
  5625  		// If we need to start a new thread from the locked
  5626  		// thread, we need the template thread. Start it now
  5627  		// while we're in a known-good state.
  5628  		startTemplateThread()
  5629  	}
  5630  	gp := getg()
  5631  	gp.m.lockedExt++
  5632  	if gp.m.lockedExt == 0 {
  5633  		gp.m.lockedExt--
  5634  		panic("LockOSThread nesting overflow")
  5635  	}
  5636  	dolockOSThread()
  5637  }
  5638  
  5639  //go:nosplit
  5640  func lockOSThread() {
  5641  	getg().m.lockedInt++
  5642  	dolockOSThread()
  5643  }
  5644  
  5645  // dounlockOSThread is called by UnlockOSThread and unlockOSThread below
  5646  // after they update m->locked. Do not allow preemption during this call,
  5647  // or else the m might be in different in this function than in the caller.
  5648  //
  5649  //go:nosplit
  5650  func dounlockOSThread() {
  5651  	if GOARCH == "wasm" {
  5652  		return // no threads on wasm yet
  5653  	}
  5654  	gp := getg()
  5655  	if gp.m.lockedInt != 0 || gp.m.lockedExt != 0 {
  5656  		return
  5657  	}
  5658  	gp.m.lockedg = 0
  5659  	gp.lockedm = 0
  5660  }
  5661  
  5662  // UnlockOSThread undoes an earlier call to LockOSThread.
  5663  // If this drops the number of active LockOSThread calls on the
  5664  // calling goroutine to zero, it unwires the calling goroutine from
  5665  // its fixed operating system thread.
  5666  // If there are no active LockOSThread calls, this is a no-op.
  5667  //
  5668  // Before calling UnlockOSThread, the caller must ensure that the OS
  5669  // thread is suitable for running other goroutines. If the caller made
  5670  // any permanent changes to the state of the thread that would affect
  5671  // other goroutines, it should not call this function and thus leave
  5672  // the goroutine locked to the OS thread until the goroutine (and
  5673  // hence the thread) exits.
  5674  //
  5675  //go:nosplit
  5676  func UnlockOSThread() {
  5677  	gp := getg()
  5678  	if gp.m.lockedExt == 0 {
  5679  		return
  5680  	}
  5681  	gp.m.lockedExt--
  5682  	dounlockOSThread()
  5683  }
  5684  
  5685  //go:nosplit
  5686  func unlockOSThread() {
  5687  	gp := getg()
  5688  	if gp.m.lockedInt == 0 {
  5689  		systemstack(badunlockosthread)
  5690  	}
  5691  	gp.m.lockedInt--
  5692  	dounlockOSThread()
  5693  }
  5694  
  5695  func badunlockosthread() {
  5696  	throw("runtime: internal error: misuse of lockOSThread/unlockOSThread")
  5697  }
  5698  
  5699  func gcount(includeSys bool) int32 {
  5700  	n := int32(atomic.Loaduintptr(&allglen)) - sched.gFree.stack.size - sched.gFree.noStack.size
  5701  	if !includeSys {
  5702  		n -= sched.ngsys.Load()
  5703  	}
  5704  	for _, pp := range allp {
  5705  		n -= pp.gFree.size
  5706  	}
  5707  
  5708  	// All these variables can be changed concurrently, so the result can be inconsistent.
  5709  	// But at least the current goroutine is running.
  5710  	if n < 1 {
  5711  		n = 1
  5712  	}
  5713  	return n
  5714  }
  5715  
  5716  // goroutineleakcount returns the number of leaked goroutines last reported by
  5717  // the runtime.
  5718  //
  5719  //go:linkname goroutineleakcount runtime/pprof.runtime_goroutineleakcount
  5720  func goroutineleakcount() int {
  5721  	return work.goroutineLeak.count
  5722  }
  5723  
  5724  func mcount() int32 {
  5725  	return int32(sched.mnext - sched.nmfreed)
  5726  }
  5727  
  5728  var prof struct {
  5729  	signalLock atomic.Uint32
  5730  
  5731  	// Must hold signalLock to write. Reads may be lock-free, but
  5732  	// signalLock should be taken to synchronize with changes.
  5733  	hz atomic.Int32
  5734  }
  5735  
  5736  func _System()                    { _System() }
  5737  func _ExternalCode()              { _ExternalCode() }
  5738  func _LostExternalCode()          { _LostExternalCode() }
  5739  func _GC()                        { _GC() }
  5740  func _LostSIGPROFDuringAtomic64() { _LostSIGPROFDuringAtomic64() }
  5741  func _LostContendedRuntimeLock()  { _LostContendedRuntimeLock() }
  5742  func _VDSO()                      { _VDSO() }
  5743  
  5744  // Called if we receive a SIGPROF signal.
  5745  // Called by the signal handler, may run during STW.
  5746  //
  5747  //go:nowritebarrierrec
  5748  func sigprof(pc, sp, lr uintptr, gp *g, mp *m) {
  5749  	if prof.hz.Load() == 0 {
  5750  		return
  5751  	}
  5752  
  5753  	// If mp.profilehz is 0, then profiling is not enabled for this thread.
  5754  	// We must check this to avoid a deadlock between setcpuprofilerate
  5755  	// and the call to cpuprof.add, below.
  5756  	if mp != nil && mp.profilehz == 0 {
  5757  		return
  5758  	}
  5759  
  5760  	// On mips{,le}/arm, 64bit atomics are emulated with spinlocks, in
  5761  	// internal/runtime/atomic. If SIGPROF arrives while the program is inside
  5762  	// the critical section, it creates a deadlock (when writing the sample).
  5763  	// As a workaround, create a counter of SIGPROFs while in critical section
  5764  	// to store the count, and pass it to sigprof.add() later when SIGPROF is
  5765  	// received from somewhere else (with _LostSIGPROFDuringAtomic64 as pc).
  5766  	if GOARCH == "mips" || GOARCH == "mipsle" || GOARCH == "arm" {
  5767  		if f := findfunc(pc); f.valid() {
  5768  			if stringslite.HasPrefix(funcname(f), "internal/runtime/atomic") {
  5769  				cpuprof.lostAtomic++
  5770  				return
  5771  			}
  5772  		}
  5773  		if GOARCH == "arm" && goarm < 7 && GOOS == "linux" && pc&0xffff0000 == 0xffff0000 {
  5774  			// internal/runtime/atomic functions call into kernel
  5775  			// helpers on arm < 7. See
  5776  			// internal/runtime/atomic/sys_linux_arm.s.
  5777  			cpuprof.lostAtomic++
  5778  			return
  5779  		}
  5780  	}
  5781  
  5782  	// Profiling runs concurrently with GC, so it must not allocate.
  5783  	// Set a trap in case the code does allocate.
  5784  	// Note that on windows, one thread takes profiles of all the
  5785  	// other threads, so mp is usually not getg().m.
  5786  	// In fact mp may not even be stopped.
  5787  	// See golang.org/issue/17165.
  5788  	getg().m.mallocing++
  5789  
  5790  	var u unwinder
  5791  	var stk [maxCPUProfStack]uintptr
  5792  	n := 0
  5793  	if mp.ncgo > 0 && mp.curg != nil && mp.curg.syscallpc != 0 && mp.curg.syscallsp != 0 {
  5794  		cgoOff := 0
  5795  		// Check cgoCallersUse to make sure that we are not
  5796  		// interrupting other code that is fiddling with
  5797  		// cgoCallers.  We are running in a signal handler
  5798  		// with all signals blocked, so we don't have to worry
  5799  		// about any other code interrupting us.
  5800  		if mp.cgoCallersUse.Load() == 0 && mp.cgoCallers != nil && mp.cgoCallers[0] != 0 {
  5801  			for cgoOff < len(mp.cgoCallers) && mp.cgoCallers[cgoOff] != 0 {
  5802  				cgoOff++
  5803  			}
  5804  			n += copy(stk[:], mp.cgoCallers[:cgoOff])
  5805  			mp.cgoCallers[0] = 0
  5806  		}
  5807  
  5808  		// Collect Go stack that leads to the cgo call.
  5809  		u.initAt(mp.curg.syscallpc, mp.curg.syscallsp, 0, mp.curg, unwindSilentErrors)
  5810  	} else if usesLibcall() && mp.libcallg != 0 && mp.libcallpc != 0 && mp.libcallsp != 0 {
  5811  		// Libcall, i.e. runtime syscall on windows.
  5812  		// Collect Go stack that leads to the call.
  5813  		u.initAt(mp.libcallpc, mp.libcallsp, 0, mp.libcallg.ptr(), unwindSilentErrors)
  5814  	} else if mp != nil && mp.vdsoSP != 0 {
  5815  		// VDSO call, e.g. nanotime1 on Linux.
  5816  		// Collect Go stack that leads to the call.
  5817  		u.initAt(mp.vdsoPC, mp.vdsoSP, 0, gp, unwindSilentErrors|unwindJumpStack)
  5818  	} else {
  5819  		u.initAt(pc, sp, lr, gp, unwindSilentErrors|unwindTrap|unwindJumpStack)
  5820  	}
  5821  	n += tracebackPCs(&u, 0, stk[n:])
  5822  
  5823  	if n <= 0 {
  5824  		// Normal traceback is impossible or has failed.
  5825  		// Account it against abstract "System" or "GC".
  5826  		n = 2
  5827  		if inVDSOPage(pc) {
  5828  			pc = abi.FuncPCABIInternal(_VDSO) + sys.PCQuantum
  5829  		} else if pc > firstmoduledata.etext {
  5830  			// "ExternalCode" is better than "etext".
  5831  			pc = abi.FuncPCABIInternal(_ExternalCode) + sys.PCQuantum
  5832  		}
  5833  		stk[0] = pc
  5834  		if mp.preemptoff != "" {
  5835  			stk[1] = abi.FuncPCABIInternal(_GC) + sys.PCQuantum
  5836  		} else {
  5837  			stk[1] = abi.FuncPCABIInternal(_System) + sys.PCQuantum
  5838  		}
  5839  	}
  5840  
  5841  	if prof.hz.Load() != 0 {
  5842  		// Note: it can happen on Windows that we interrupted a system thread
  5843  		// with no g, so gp could nil. The other nil checks are done out of
  5844  		// caution, but not expected to be nil in practice.
  5845  		var tagPtr *unsafe.Pointer
  5846  		if gp != nil && gp.m != nil && gp.m.curg != nil {
  5847  			tagPtr = &gp.m.curg.labels
  5848  		}
  5849  		cpuprof.add(tagPtr, stk[:n])
  5850  
  5851  		gprof := gp
  5852  		var mp *m
  5853  		var pp *p
  5854  		if gp != nil && gp.m != nil {
  5855  			if gp.m.curg != nil {
  5856  				gprof = gp.m.curg
  5857  			}
  5858  			mp = gp.m
  5859  			pp = gp.m.p.ptr()
  5860  		}
  5861  		traceCPUSample(gprof, mp, pp, stk[:n])
  5862  	}
  5863  	getg().m.mallocing--
  5864  }
  5865  
  5866  // setcpuprofilerate sets the CPU profiling rate to hz times per second.
  5867  // If hz <= 0, setcpuprofilerate turns off CPU profiling.
  5868  func setcpuprofilerate(hz int32) {
  5869  	// Force sane arguments.
  5870  	if hz < 0 {
  5871  		hz = 0
  5872  	}
  5873  
  5874  	// Disable preemption, otherwise we can be rescheduled to another thread
  5875  	// that has profiling enabled.
  5876  	gp := getg()
  5877  	gp.m.locks++
  5878  
  5879  	// Stop profiler on this thread so that it is safe to lock prof.
  5880  	// if a profiling signal came in while we had prof locked,
  5881  	// it would deadlock.
  5882  	setThreadCPUProfiler(0)
  5883  
  5884  	for !prof.signalLock.CompareAndSwap(0, 1) {
  5885  		osyield()
  5886  	}
  5887  	if prof.hz.Load() != hz {
  5888  		setProcessCPUProfiler(hz)
  5889  		prof.hz.Store(hz)
  5890  	}
  5891  	prof.signalLock.Store(0)
  5892  
  5893  	lock(&sched.lock)
  5894  	sched.profilehz = hz
  5895  	unlock(&sched.lock)
  5896  
  5897  	if hz != 0 {
  5898  		setThreadCPUProfiler(hz)
  5899  	}
  5900  
  5901  	gp.m.locks--
  5902  }
  5903  
  5904  // init initializes pp, which may be a freshly allocated p or a
  5905  // previously destroyed p, and transitions it to status _Pgcstop.
  5906  func (pp *p) init(id int32) {
  5907  	pp.id = id
  5908  	pp.gcw.id = id
  5909  	pp.status = _Pgcstop
  5910  	pp.sudogcache = pp.sudogbuf[:0]
  5911  	pp.deferpool = pp.deferpoolbuf[:0]
  5912  	pp.wbBuf.reset()
  5913  	if pp.mcache == nil {
  5914  		if id == 0 {
  5915  			if mcache0 == nil {
  5916  				throw("missing mcache?")
  5917  			}
  5918  			// Use the bootstrap mcache0. Only one P will get
  5919  			// mcache0: the one with ID 0.
  5920  			pp.mcache = mcache0
  5921  		} else {
  5922  			pp.mcache = allocmcache()
  5923  		}
  5924  	}
  5925  	if raceenabled && pp.raceprocctx == 0 {
  5926  		if id == 0 {
  5927  			pp.raceprocctx = raceprocctx0
  5928  			raceprocctx0 = 0 // bootstrap
  5929  		} else {
  5930  			pp.raceprocctx = raceproccreate()
  5931  		}
  5932  	}
  5933  	lockInit(&pp.timers.mu, lockRankTimers)
  5934  
  5935  	// This P may get timers when it starts running. Set the mask here
  5936  	// since the P may not go through pidleget (notably P 0 on startup).
  5937  	timerpMask.set(id)
  5938  	// Similarly, we may not go through pidleget before this P starts
  5939  	// running if it is P 0 on startup.
  5940  	idlepMask.clear(id)
  5941  }
  5942  
  5943  // destroy releases all of the resources associated with pp and
  5944  // transitions it to status _Pdead.
  5945  //
  5946  // sched.lock must be held and the world must be stopped.
  5947  func (pp *p) destroy() {
  5948  	assertLockHeld(&sched.lock)
  5949  	assertWorldStopped()
  5950  
  5951  	// Move all runnable goroutines to the global queue
  5952  	for pp.runqhead != pp.runqtail {
  5953  		// Pop from tail of local queue
  5954  		pp.runqtail--
  5955  		gp := pp.runq[pp.runqtail%uint32(len(pp.runq))].ptr()
  5956  		// Push onto head of global queue
  5957  		globrunqputhead(gp)
  5958  	}
  5959  	if pp.runnext != 0 {
  5960  		globrunqputhead(pp.runnext.ptr())
  5961  		pp.runnext = 0
  5962  	}
  5963  
  5964  	// Move all timers to the local P.
  5965  	getg().m.p.ptr().timers.take(&pp.timers)
  5966  
  5967  	// No need to flush p's write barrier buffer or span queue, as Ps
  5968  	// cannot be destroyed during the mark phase.
  5969  	if phase := gcphase; phase != _GCoff {
  5970  		println("runtime: p id", pp.id, "destroyed during GC phase", phase)
  5971  		throw("P destroyed while GC is running")
  5972  	}
  5973  	// We should free the queues though.
  5974  	pp.gcw.spanq.destroy()
  5975  
  5976  	clear(pp.sudogbuf[:])
  5977  	pp.sudogcache = pp.sudogbuf[:0]
  5978  	pp.pinnerCache = nil
  5979  	clear(pp.deferpoolbuf[:])
  5980  	pp.deferpool = pp.deferpoolbuf[:0]
  5981  	systemstack(func() {
  5982  		for i := 0; i < pp.mspancache.len; i++ {
  5983  			// Safe to call since the world is stopped.
  5984  			mheap_.spanalloc.free(unsafe.Pointer(pp.mspancache.buf[i]))
  5985  		}
  5986  		pp.mspancache.len = 0
  5987  		lock(&mheap_.lock)
  5988  		pp.pcache.flush(&mheap_.pages)
  5989  		unlock(&mheap_.lock)
  5990  	})
  5991  	freemcache(pp.mcache)
  5992  	pp.mcache = nil
  5993  	gfpurge(pp)
  5994  	if raceenabled {
  5995  		if pp.timers.raceCtx != 0 {
  5996  			// The race detector code uses a callback to fetch
  5997  			// the proc context, so arrange for that callback
  5998  			// to see the right thing.
  5999  			// This hack only works because we are the only
  6000  			// thread running.
  6001  			mp := getg().m
  6002  			phold := mp.p.ptr()
  6003  			mp.p.set(pp)
  6004  
  6005  			racectxend(pp.timers.raceCtx)
  6006  			pp.timers.raceCtx = 0
  6007  
  6008  			mp.p.set(phold)
  6009  		}
  6010  		raceprocdestroy(pp.raceprocctx)
  6011  		pp.raceprocctx = 0
  6012  	}
  6013  	pp.gcAssistTime = 0
  6014  	gcCleanups.queued += pp.cleanupsQueued
  6015  	pp.cleanupsQueued = 0
  6016  	sched.goroutinesCreated.Add(int64(pp.goroutinesCreated))
  6017  	pp.goroutinesCreated = 0
  6018  	pp.xRegs.free()
  6019  	pp.status = _Pdead
  6020  }
  6021  
  6022  // Change number of processors.
  6023  //
  6024  // sched.lock must be held, and the world must be stopped.
  6025  //
  6026  // gcworkbufs must not be being modified by either the GC or the write barrier
  6027  // code, so the GC must not be running if the number of Ps actually changes.
  6028  //
  6029  // Returns list of Ps with local work, they need to be scheduled by the caller.
  6030  func procresize(nprocs int32) *p {
  6031  	assertLockHeld(&sched.lock)
  6032  	assertWorldStopped()
  6033  
  6034  	old := gomaxprocs
  6035  	if old < 0 || nprocs <= 0 {
  6036  		throw("procresize: invalid arg")
  6037  	}
  6038  	trace := traceAcquire()
  6039  	if trace.ok() {
  6040  		trace.Gomaxprocs(nprocs)
  6041  		traceRelease(trace)
  6042  	}
  6043  
  6044  	// update statistics
  6045  	now := nanotime()
  6046  	if sched.procresizetime != 0 {
  6047  		sched.totaltime += int64(old) * (now - sched.procresizetime)
  6048  	}
  6049  	sched.procresizetime = now
  6050  
  6051  	// Grow allp if necessary.
  6052  	if nprocs > int32(len(allp)) {
  6053  		// Synchronize with retake, which could be running
  6054  		// concurrently since it doesn't run on a P.
  6055  		lock(&allpLock)
  6056  		if nprocs <= int32(cap(allp)) {
  6057  			allp = allp[:nprocs]
  6058  		} else {
  6059  			nallp := make([]*p, nprocs)
  6060  			// Copy everything up to allp's cap so we
  6061  			// never lose old allocated Ps.
  6062  			copy(nallp, allp[:cap(allp)])
  6063  			allp = nallp
  6064  		}
  6065  
  6066  		idlepMask = idlepMask.resize(nprocs)
  6067  		timerpMask = timerpMask.resize(nprocs)
  6068  		work.spanqMask = work.spanqMask.resize(nprocs)
  6069  		unlock(&allpLock)
  6070  	}
  6071  
  6072  	// initialize new P's
  6073  	for i := old; i < nprocs; i++ {
  6074  		pp := allp[i]
  6075  		if pp == nil {
  6076  			pp = new(p)
  6077  		}
  6078  		pp.init(i)
  6079  		atomicstorep(unsafe.Pointer(&allp[i]), unsafe.Pointer(pp))
  6080  	}
  6081  
  6082  	gp := getg()
  6083  	if gp.m.p != 0 && gp.m.p.ptr().id < nprocs {
  6084  		// continue to use the current P
  6085  		gp.m.p.ptr().status = _Prunning
  6086  		gp.m.p.ptr().mcache.prepareForSweep()
  6087  	} else {
  6088  		// release the current P and acquire allp[0].
  6089  		//
  6090  		// We must do this before destroying our current P
  6091  		// because p.destroy itself has write barriers, so we
  6092  		// need to do that from a valid P.
  6093  		if gp.m.p != 0 {
  6094  			trace := traceAcquire()
  6095  			if trace.ok() {
  6096  				// Pretend that we were descheduled
  6097  				// and then scheduled again to keep
  6098  				// the trace consistent.
  6099  				trace.GoSched()
  6100  				trace.ProcStop(gp.m.p.ptr())
  6101  				traceRelease(trace)
  6102  			}
  6103  			gp.m.p.ptr().m = 0
  6104  		}
  6105  		gp.m.p = 0
  6106  		pp := allp[0]
  6107  		pp.m = 0
  6108  		pp.status = _Pidle
  6109  		acquirep(pp)
  6110  		trace := traceAcquire()
  6111  		if trace.ok() {
  6112  			trace.GoStart()
  6113  			traceRelease(trace)
  6114  		}
  6115  	}
  6116  
  6117  	// g.m.p is now set, so we no longer need mcache0 for bootstrapping.
  6118  	mcache0 = nil
  6119  
  6120  	// release resources from unused P's
  6121  	for i := nprocs; i < old; i++ {
  6122  		pp := allp[i]
  6123  		pp.destroy()
  6124  		// can't free P itself because it can be referenced by an M in syscall
  6125  	}
  6126  
  6127  	// Trim allp.
  6128  	if int32(len(allp)) != nprocs {
  6129  		lock(&allpLock)
  6130  		allp = allp[:nprocs]
  6131  		idlepMask = idlepMask.resize(nprocs)
  6132  		timerpMask = timerpMask.resize(nprocs)
  6133  		work.spanqMask = work.spanqMask.resize(nprocs)
  6134  		unlock(&allpLock)
  6135  	}
  6136  
  6137  	// Assign Ms to Ps with runnable goroutines.
  6138  	var runnablePs *p
  6139  	var runnablePsNeedM *p
  6140  	var idlePs *p
  6141  	for i := nprocs - 1; i >= 0; i-- {
  6142  		pp := allp[i]
  6143  		if gp.m.p.ptr() == pp {
  6144  			continue
  6145  		}
  6146  		pp.status = _Pidle
  6147  		if runqempty(pp) {
  6148  			pp.link.set(idlePs)
  6149  			idlePs = pp
  6150  			continue
  6151  		}
  6152  
  6153  		// Prefer to run on the most recent M if it is
  6154  		// available.
  6155  		//
  6156  		// Ps with no oldm (or for which oldm is already taken
  6157  		// by an earlier P), we delay until all oldm Ps are
  6158  		// handled. Otherwise, mget may return an M that a
  6159  		// later P has in oldm.
  6160  		var mp *m
  6161  		if oldm := pp.oldm.get(); oldm != nil {
  6162  			// Returns nil if oldm is not idle.
  6163  			mp = mgetSpecific(oldm)
  6164  		}
  6165  		if mp == nil {
  6166  			// Call mget later.
  6167  			pp.link.set(runnablePsNeedM)
  6168  			runnablePsNeedM = pp
  6169  			continue
  6170  		}
  6171  		pp.m.set(mp)
  6172  		pp.link.set(runnablePs)
  6173  		runnablePs = pp
  6174  	}
  6175  	// Assign Ms to remaining runnable Ps without usable oldm. See comment
  6176  	// above.
  6177  	for runnablePsNeedM != nil {
  6178  		pp := runnablePsNeedM
  6179  		runnablePsNeedM = pp.link.ptr()
  6180  
  6181  		mp := mget()
  6182  		pp.m.set(mp)
  6183  		pp.link.set(runnablePs)
  6184  		runnablePs = pp
  6185  	}
  6186  
  6187  	// Now that we've assigned Ms to Ps with runnable goroutines, assign GC
  6188  	// mark workers to remaining idle Ps, if needed.
  6189  	//
  6190  	// By assigning GC workers to Ps here, we slightly speed up starting
  6191  	// the world, as we will start enough Ps to run all of the user
  6192  	// goroutines and GC mark workers all at once, rather than using a
  6193  	// sequence of wakep calls as each P's findRunnable realizes it needs
  6194  	// to run a mark worker instead of a user goroutine.
  6195  	//
  6196  	// By assigning GC workers to Ps only _after_ previously-running Ps are
  6197  	// assigned Ms, we ensure that goroutines previously running on a P
  6198  	// continue to run on the same P, with GC mark workers preferring
  6199  	// previously-idle Ps. This helps prevent goroutines from shuffling
  6200  	// around too much across STW.
  6201  	//
  6202  	// N.B., if there aren't enough Ps left in idlePs for all of the GC
  6203  	// mark workers, then findRunnable will still choose to run mark
  6204  	// workers on Ps assigned above.
  6205  	//
  6206  	// N.B., we do this during any STW in the mark phase, not just the
  6207  	// sweep termination STW that starts the mark phase. gcBgMarkWorker
  6208  	// always preempts by removing itself from the P, so even unrelated
  6209  	// STWs during the mark require that Ps reselect mark workers upon
  6210  	// restart.
  6211  	if gcBlackenEnabled != 0 {
  6212  		for idlePs != nil {
  6213  			pp := idlePs
  6214  
  6215  			ok, _ := gcController.assignWaitingGCWorker(pp, now)
  6216  			if !ok {
  6217  				// No more mark workers needed.
  6218  				break
  6219  			}
  6220  
  6221  			// Got a worker, P is now runnable.
  6222  			//
  6223  			// mget may return nil if there aren't enough Ms, in
  6224  			// which case startTheWorldWithSema will start one.
  6225  			//
  6226  			// N.B. findRunnableGCWorker will make the worker G
  6227  			// itself runnable.
  6228  			idlePs = pp.link.ptr()
  6229  			mp := mget()
  6230  			pp.m.set(mp)
  6231  			pp.link.set(runnablePs)
  6232  			runnablePs = pp
  6233  		}
  6234  	}
  6235  
  6236  	// Finally, any remaining Ps are truly idle.
  6237  	for idlePs != nil {
  6238  		pp := idlePs
  6239  		idlePs = pp.link.ptr()
  6240  		pidleput(pp, now)
  6241  	}
  6242  
  6243  	stealOrder.reset(uint32(nprocs))
  6244  	var int32p *int32 = &gomaxprocs // make compiler check that gomaxprocs is an int32
  6245  	atomic.Store((*uint32)(unsafe.Pointer(int32p)), uint32(nprocs))
  6246  	if old != nprocs {
  6247  		// Notify the limiter that the amount of procs has changed.
  6248  		gcCPULimiter.resetCapacity(now, nprocs)
  6249  	}
  6250  	return runnablePs
  6251  }
  6252  
  6253  // Associate p and the current m.
  6254  //
  6255  // This function is allowed to have write barriers even if the caller
  6256  // isn't because it immediately acquires pp.
  6257  //
  6258  //go:yeswritebarrierrec
  6259  func acquirep(pp *p) {
  6260  	// Do the work.
  6261  	acquirepNoTrace(pp)
  6262  
  6263  	// Emit the event.
  6264  	trace := traceAcquire()
  6265  	if trace.ok() {
  6266  		trace.ProcStart()
  6267  		traceRelease(trace)
  6268  	}
  6269  }
  6270  
  6271  // Internals of acquirep, just skipping the trace events.
  6272  //
  6273  //go:yeswritebarrierrec
  6274  func acquirepNoTrace(pp *p) {
  6275  	// Do the part that isn't allowed to have write barriers.
  6276  	wirep(pp)
  6277  
  6278  	// Have p; write barriers now allowed.
  6279  
  6280  	// The M we're associating with will be the old M after the next
  6281  	// releasep. We must set this here because write barriers are not
  6282  	// allowed in releasep.
  6283  	pp.oldm = pp.m.ptr().self
  6284  
  6285  	// Perform deferred mcache flush before this P can allocate
  6286  	// from a potentially stale mcache.
  6287  	pp.mcache.prepareForSweep()
  6288  }
  6289  
  6290  // wirep is the first step of acquirep, which actually associates the
  6291  // current M to pp. This is broken out so we can disallow write
  6292  // barriers for this part, since we don't yet have a P.
  6293  //
  6294  //go:nowritebarrierrec
  6295  //go:nosplit
  6296  func wirep(pp *p) {
  6297  	gp := getg()
  6298  
  6299  	if gp.m.p != 0 {
  6300  		// Call on the systemstack to avoid a nosplit overflow build failure
  6301  		// on some platforms when built with -N -l. See #64113.
  6302  		systemstack(func() {
  6303  			throw("wirep: already in go")
  6304  		})
  6305  	}
  6306  	if pp.m != 0 || pp.status != _Pidle {
  6307  		// Call on the systemstack to avoid a nosplit overflow build failure
  6308  		// on some platforms when built with -N -l. See #64113.
  6309  		systemstack(func() {
  6310  			id := int64(0)
  6311  			if pp.m != 0 {
  6312  				id = pp.m.ptr().id
  6313  			}
  6314  			print("wirep: p->m=", pp.m, "(", id, ") p->status=", pp.status, "\n")
  6315  			throw("wirep: invalid p state")
  6316  		})
  6317  	}
  6318  	gp.m.p.set(pp)
  6319  	pp.m.set(gp.m)
  6320  	pp.status = _Prunning
  6321  }
  6322  
  6323  // Disassociate p and the current m.
  6324  func releasep() *p {
  6325  	trace := traceAcquire()
  6326  	if trace.ok() {
  6327  		trace.ProcStop(getg().m.p.ptr())
  6328  		traceRelease(trace)
  6329  	}
  6330  	return releasepNoTrace()
  6331  }
  6332  
  6333  // Disassociate p and the current m without tracing an event.
  6334  func releasepNoTrace() *p {
  6335  	gp := getg()
  6336  
  6337  	if gp.m.p == 0 {
  6338  		throw("releasep: invalid arg")
  6339  	}
  6340  	pp := gp.m.p.ptr()
  6341  	if pp.m.ptr() != gp.m || pp.status != _Prunning {
  6342  		print("releasep: m=", gp.m, " m->p=", gp.m.p.ptr(), " p->m=", hex(pp.m), " p->status=", pp.status, "\n")
  6343  		throw("releasep: invalid p state")
  6344  	}
  6345  
  6346  	// P must clear if nextGCMarkWorker if it stops.
  6347  	gcController.releaseNextGCMarkWorker(pp)
  6348  
  6349  	gp.m.p = 0
  6350  	pp.m = 0
  6351  	pp.status = _Pidle
  6352  	return pp
  6353  }
  6354  
  6355  func incidlelocked(v int32) {
  6356  	lock(&sched.lock)
  6357  	sched.nmidlelocked += v
  6358  	if v > 0 {
  6359  		checkdead()
  6360  	}
  6361  	unlock(&sched.lock)
  6362  }
  6363  
  6364  // Check for deadlock situation.
  6365  // The check is based on number of running M's, if 0 -> deadlock.
  6366  // sched.lock must be held.
  6367  func checkdead() {
  6368  	assertLockHeld(&sched.lock)
  6369  
  6370  	// For -buildmode=c-shared or -buildmode=c-archive it's OK if
  6371  	// there are no running goroutines. The calling program is
  6372  	// assumed to be running.
  6373  	// One exception is Wasm, which is single-threaded. If we are
  6374  	// in Go and all goroutines are blocked, it deadlocks.
  6375  	if (islibrary || isarchive) && GOARCH != "wasm" {
  6376  		return
  6377  	}
  6378  
  6379  	// If we are dying because of a signal caught on an already idle thread,
  6380  	// freezetheworld will cause all running threads to block.
  6381  	// And runtime will essentially enter into deadlock state,
  6382  	// except that there is a thread that will call exit soon.
  6383  	if panicking.Load() > 0 {
  6384  		return
  6385  	}
  6386  
  6387  	// If we are not running under cgo, but we have an extra M then account
  6388  	// for it. (It is possible to have an extra M on Windows without cgo to
  6389  	// accommodate callbacks created by syscall.NewCallback. See issue #6751
  6390  	// for details.)
  6391  	var run0 int32
  6392  	if !iscgo && cgoHasExtraM && extraMLength.Load() > 0 {
  6393  		run0 = 1
  6394  	}
  6395  
  6396  	run := mcount() - sched.nmidle - sched.nmidlelocked - sched.nmsys
  6397  	if run > run0 {
  6398  		return
  6399  	}
  6400  	if run < 0 {
  6401  		print("runtime: checkdead: nmidle=", sched.nmidle, " nmidlelocked=", sched.nmidlelocked, " mcount=", mcount(), " nmsys=", sched.nmsys, "\n")
  6402  		unlock(&sched.lock)
  6403  		throw("checkdead: inconsistent counts")
  6404  	}
  6405  
  6406  	grunning := 0
  6407  	forEachG(func(gp *g) {
  6408  		if isSystemGoroutine(gp, false) {
  6409  			return
  6410  		}
  6411  		s := readgstatus(gp)
  6412  		switch s &^ _Gscan {
  6413  		case _Gwaiting,
  6414  			_Gpreempted:
  6415  			grunning++
  6416  		case _Grunnable,
  6417  			_Grunning,
  6418  			_Gsyscall:
  6419  			print("runtime: checkdead: find g ", gp.goid, " in status ", s, "\n")
  6420  			unlock(&sched.lock)
  6421  			throw("checkdead: runnable g")
  6422  		}
  6423  	})
  6424  	if grunning == 0 { // possible if main goroutine calls runtime·Goexit()
  6425  		unlock(&sched.lock) // unlock so that GODEBUG=scheddetail=1 doesn't hang
  6426  		fatal("no goroutines (main called runtime.Goexit) - deadlock!")
  6427  	}
  6428  
  6429  	// Maybe jump time forward for playground.
  6430  	if faketime != 0 {
  6431  		if when := timeSleepUntil(); when < maxWhen {
  6432  			faketime = when
  6433  
  6434  			// Start an M to steal the timer.
  6435  			pp, _ := pidleget(faketime)
  6436  			if pp == nil {
  6437  				// There should always be a free P since
  6438  				// nothing is running.
  6439  				unlock(&sched.lock)
  6440  				throw("checkdead: no p for timer")
  6441  			}
  6442  			mp := mget()
  6443  			if mp == nil {
  6444  				// There should always be a free M since
  6445  				// nothing is running.
  6446  				unlock(&sched.lock)
  6447  				throw("checkdead: no m for timer")
  6448  			}
  6449  			// M must be spinning to steal. We set this to be
  6450  			// explicit, but since this is the only M it would
  6451  			// become spinning on its own anyways.
  6452  			sched.nmspinning.Add(1)
  6453  			mp.spinning = true
  6454  			mp.nextp.set(pp)
  6455  			notewakeup(&mp.park)
  6456  			return
  6457  		}
  6458  	}
  6459  
  6460  	// There are no goroutines running, so we can look at the P's.
  6461  	for _, pp := range allp {
  6462  		if len(pp.timers.heap) > 0 {
  6463  			return
  6464  		}
  6465  	}
  6466  
  6467  	unlock(&sched.lock) // unlock so that GODEBUG=scheddetail=1 doesn't hang
  6468  	fatal("all goroutines are asleep - deadlock!")
  6469  }
  6470  
  6471  // forcegcperiod is the maximum time in nanoseconds between garbage
  6472  // collections. If we go this long without a garbage collection, one
  6473  // is forced to run.
  6474  //
  6475  // This is a variable for testing purposes. It normally doesn't change.
  6476  var forcegcperiod int64 = 2 * 60 * 1e9
  6477  
  6478  // haveSysmon indicates whether there is sysmon thread support.
  6479  //
  6480  // No threads on wasm yet, so no sysmon.
  6481  const haveSysmon = GOARCH != "wasm"
  6482  
  6483  // Always runs without a P, so write barriers are not allowed.
  6484  //
  6485  //go:nowritebarrierrec
  6486  func sysmon() {
  6487  	lock(&sched.lock)
  6488  	sched.nmsys++
  6489  	checkdead()
  6490  	unlock(&sched.lock)
  6491  
  6492  	lastgomaxprocs := int64(0)
  6493  	lasttrace := int64(0)
  6494  	idle := 0 // how many cycles in succession we had not wokeup somebody
  6495  	delay := uint32(0)
  6496  
  6497  	for {
  6498  		if idle == 0 { // start with 20us sleep...
  6499  			delay = 20
  6500  		} else if idle > 50 { // start doubling the sleep after 1ms...
  6501  			delay *= 2
  6502  		}
  6503  		if delay > 10*1000 { // up to 10ms
  6504  			delay = 10 * 1000
  6505  		}
  6506  		usleep(delay)
  6507  
  6508  		// sysmon should not enter deep sleep if schedtrace is enabled so that
  6509  		// it can print that information at the right time.
  6510  		//
  6511  		// It should also not enter deep sleep if there are any active P's so
  6512  		// that it can retake P's from syscalls, preempt long running G's, and
  6513  		// poll the network if all P's are busy for long stretches.
  6514  		//
  6515  		// It should wakeup from deep sleep if any P's become active either due
  6516  		// to exiting a syscall or waking up due to a timer expiring so that it
  6517  		// can resume performing those duties. If it wakes from a syscall it
  6518  		// resets idle and delay as a bet that since it had retaken a P from a
  6519  		// syscall before, it may need to do it again shortly after the
  6520  		// application starts work again. It does not reset idle when waking
  6521  		// from a timer to avoid adding system load to applications that spend
  6522  		// most of their time sleeping.
  6523  		now := nanotime()
  6524  		if debug.schedtrace <= 0 && (sched.gcwaiting.Load() || sched.npidle.Load() == gomaxprocs) {
  6525  			lock(&sched.lock)
  6526  			if sched.gcwaiting.Load() || sched.npidle.Load() == gomaxprocs {
  6527  				syscallWake := false
  6528  				next := timeSleepUntil()
  6529  				if next > now {
  6530  					sched.sysmonwait.Store(true)
  6531  					unlock(&sched.lock)
  6532  					// Make wake-up period small enough
  6533  					// for the sampling to be correct.
  6534  					sleep := forcegcperiod / 2
  6535  					if next-now < sleep {
  6536  						sleep = next - now
  6537  					}
  6538  					shouldRelax := sleep >= osRelaxMinNS
  6539  					if shouldRelax {
  6540  						osRelax(true)
  6541  					}
  6542  					syscallWake = notetsleep(&sched.sysmonnote, sleep)
  6543  					if shouldRelax {
  6544  						osRelax(false)
  6545  					}
  6546  					lock(&sched.lock)
  6547  					sched.sysmonwait.Store(false)
  6548  					noteclear(&sched.sysmonnote)
  6549  				}
  6550  				if syscallWake {
  6551  					idle = 0
  6552  					delay = 20
  6553  				}
  6554  			}
  6555  			unlock(&sched.lock)
  6556  		}
  6557  
  6558  		lock(&sched.sysmonlock)
  6559  		// Update now in case we blocked on sysmonnote or spent a long time
  6560  		// blocked on schedlock or sysmonlock above.
  6561  		now = nanotime()
  6562  
  6563  		// trigger libc interceptors if needed
  6564  		if *cgo_yield != nil {
  6565  			asmcgocall(*cgo_yield, nil)
  6566  		}
  6567  		// poll network if not polled for more than 10ms
  6568  		lastpoll := sched.lastpoll.Load()
  6569  		if netpollinited() && lastpoll != 0 && lastpoll+10*1000*1000 < now {
  6570  			sched.lastpoll.CompareAndSwap(lastpoll, now)
  6571  			list, delta := netpoll(0) // non-blocking - returns list of goroutines
  6572  			if !list.empty() {
  6573  				// Need to decrement number of idle locked M's
  6574  				// (pretending that one more is running) before injectglist.
  6575  				// Otherwise it can lead to the following situation:
  6576  				// injectglist grabs all P's but before it starts M's to run the P's,
  6577  				// another M returns from syscall, finishes running its G,
  6578  				// observes that there is no work to do and no other running M's
  6579  				// and reports deadlock.
  6580  				incidlelocked(-1)
  6581  				injectglist(&list)
  6582  				incidlelocked(1)
  6583  				netpollAdjustWaiters(delta)
  6584  			}
  6585  		}
  6586  		// Check if we need to update GOMAXPROCS at most once per second.
  6587  		if debug.updatemaxprocs != 0 && lastgomaxprocs+1e9 <= now {
  6588  			sysmonUpdateGOMAXPROCS()
  6589  			lastgomaxprocs = now
  6590  		}
  6591  		if scavenger.sysmonWake.Load() != 0 {
  6592  			// Kick the scavenger awake if someone requested it.
  6593  			scavenger.wake()
  6594  		}
  6595  		// retake P's blocked in syscalls
  6596  		// and preempt long running G's
  6597  		if retake(now) != 0 {
  6598  			idle = 0
  6599  		} else {
  6600  			idle++
  6601  		}
  6602  		// check if we need to force a GC
  6603  		if t := (gcTrigger{kind: gcTriggerTime, now: now}); t.test() && forcegc.idle.Load() {
  6604  			lock(&forcegc.lock)
  6605  			forcegc.idle.Store(false)
  6606  			var list gList
  6607  			list.push(forcegc.g)
  6608  			injectglist(&list)
  6609  			unlock(&forcegc.lock)
  6610  		}
  6611  		if debug.schedtrace > 0 && lasttrace+int64(debug.schedtrace)*1000000 <= now {
  6612  			lasttrace = now
  6613  			schedtrace(debug.scheddetail > 0)
  6614  		}
  6615  		unlock(&sched.sysmonlock)
  6616  	}
  6617  }
  6618  
  6619  type sysmontick struct {
  6620  	schedtick   uint32
  6621  	syscalltick uint32
  6622  	schedwhen   int64
  6623  	syscallwhen int64
  6624  }
  6625  
  6626  // forcePreemptNS is the time slice given to a G before it is
  6627  // preempted.
  6628  const forcePreemptNS = 10 * 1000 * 1000 // 10ms
  6629  
  6630  func retake(now int64) uint32 {
  6631  	n := 0
  6632  	// Prevent allp slice changes. This lock will be completely
  6633  	// uncontended unless we're already stopping the world.
  6634  	lock(&allpLock)
  6635  	// We can't use a range loop over allp because we may
  6636  	// temporarily drop the allpLock. Hence, we need to re-fetch
  6637  	// allp each time around the loop.
  6638  	for i := 0; i < len(allp); i++ {
  6639  		// Quickly filter out non-running Ps. Running Ps are either
  6640  		// in a syscall or are actually executing. Idle Ps don't
  6641  		// need to be retaken.
  6642  		//
  6643  		// This is best-effort, so it's OK that it's racy. Our target
  6644  		// is to retake Ps that have been running or in a syscall for
  6645  		// a long time (milliseconds), so the state has plenty of time
  6646  		// to stabilize.
  6647  		pp := allp[i]
  6648  		if pp == nil || atomic.Load(&pp.status) != _Prunning {
  6649  			// pp can be nil if procresize has grown
  6650  			// allp but not yet created new Ps.
  6651  			continue
  6652  		}
  6653  		pd := &pp.sysmontick
  6654  		sysretake := false
  6655  
  6656  		// Preempt G if it's running on the same schedtick for
  6657  		// too long. This could be from a single long-running
  6658  		// goroutine or a sequence of goroutines run via
  6659  		// runnext, which share a single schedtick time slice.
  6660  		schedt := int64(pp.schedtick)
  6661  		if int64(pd.schedtick) != schedt {
  6662  			pd.schedtick = uint32(schedt)
  6663  			pd.schedwhen = now
  6664  		} else if pd.schedwhen+forcePreemptNS <= now {
  6665  			preemptone(pp)
  6666  			// If pp is in a syscall, preemptone doesn't work.
  6667  			// The goroutine nor the thread can respond to a
  6668  			// preemption request because they're not in Go code,
  6669  			// so we need to take the P ourselves.
  6670  			sysretake = true
  6671  		}
  6672  
  6673  		// Drop allpLock so we can take sched.lock.
  6674  		unlock(&allpLock)
  6675  
  6676  		// Need to decrement number of idle locked M's (pretending that
  6677  		// one more is running) before we take the P and resume.
  6678  		// Otherwise the M from which we retake can exit the syscall,
  6679  		// increment nmidle and report deadlock.
  6680  		//
  6681  		// Can't call incidlelocked once we setBlockOnExitSyscall, due
  6682  		// to a lock ordering violation between sched.lock and _Gscan.
  6683  		incidlelocked(-1)
  6684  
  6685  		// Try to prevent the P from continuing in the syscall, if it's in one at all.
  6686  		thread, ok := setBlockOnExitSyscall(pp)
  6687  		if !ok {
  6688  			// Not in a syscall, or something changed out from under us.
  6689  			goto done
  6690  		}
  6691  
  6692  		// Retake the P if it's there for more than 1 sysmon tick (at least 20us).
  6693  		if syst := int64(pp.syscalltick); !sysretake && int64(pd.syscalltick) != syst {
  6694  			pd.syscalltick = uint32(syst)
  6695  			pd.syscallwhen = now
  6696  			thread.resume()
  6697  			goto done
  6698  		}
  6699  
  6700  		// On the one hand we don't want to retake Ps if there is no other work to do,
  6701  		// but on the other hand we want to retake them eventually
  6702  		// because they can prevent the sysmon thread from deep sleep.
  6703  		if runqempty(pp) && sched.nmspinning.Load()+sched.npidle.Load() > 0 && pd.syscallwhen+10*1000*1000 > now {
  6704  			thread.resume()
  6705  			goto done
  6706  		}
  6707  
  6708  		// Take the P. Note: because we have the scan bit, the goroutine
  6709  		// is at worst stuck spinning in exitsyscall.
  6710  		thread.takeP()
  6711  		thread.resume()
  6712  		n++
  6713  
  6714  		// Handoff the P for some other thread to run it.
  6715  		handoffp(pp)
  6716  
  6717  		// The P has been handed off to another thread, so risk of a false
  6718  		// deadlock report while we hold onto it is gone.
  6719  	done:
  6720  		incidlelocked(1)
  6721  		lock(&allpLock)
  6722  	}
  6723  	unlock(&allpLock)
  6724  	return uint32(n)
  6725  }
  6726  
  6727  // syscallingThread represents a thread in a system call that temporarily
  6728  // cannot advance out of the system call.
  6729  type syscallingThread struct {
  6730  	gp     *g
  6731  	mp     *m
  6732  	pp     *p
  6733  	status uint32
  6734  }
  6735  
  6736  // setBlockOnExitSyscall prevents pp's thread from advancing out of
  6737  // exitsyscall. On success, returns the g/m/p state of the thread
  6738  // and true. At that point, the caller owns the g/m/p links referenced,
  6739  // the goroutine is in _Gsyscall, and prevented from transitioning out
  6740  // of it. On failure, it returns false, and none of these guarantees are
  6741  // made.
  6742  //
  6743  // Callers must call resume on the resulting thread state once
  6744  // they're done with thread, otherwise it will remain blocked forever.
  6745  //
  6746  // This function races with state changes on pp, and thus may fail
  6747  // if pp is not in a system call, or exits a system call concurrently
  6748  // with this function. However, this function is safe to call without
  6749  // any additional synchronization.
  6750  func setBlockOnExitSyscall(pp *p) (syscallingThread, bool) {
  6751  	if pp.status != _Prunning {
  6752  		return syscallingThread{}, false
  6753  	}
  6754  	// Be very careful here, these reads are intentionally racy.
  6755  	// Once we notice the G is in _Gsyscall, acquire its scan bit,
  6756  	// and validate that it's still connected to the *same* M and P,
  6757  	// we can actually get to work. Holding the scan bit will prevent
  6758  	// the G from exiting the syscall.
  6759  	//
  6760  	// Our goal here is to interrupt long syscalls. If it turns out
  6761  	// that we're wrong and the G switched to another syscall while
  6762  	// we were trying to do this, that's completely fine. It's
  6763  	// probably making more frequent syscalls and the typical
  6764  	// preemption paths should be effective.
  6765  	mp := pp.m.ptr()
  6766  	if mp == nil {
  6767  		// Nothing to do.
  6768  		return syscallingThread{}, false
  6769  	}
  6770  	gp := mp.curg
  6771  	if gp == nil {
  6772  		// Nothing to do.
  6773  		return syscallingThread{}, false
  6774  	}
  6775  	status := readgstatus(gp) &^ _Gscan
  6776  
  6777  	// A goroutine is considered in a syscall, and may have a corresponding
  6778  	// P, if it's in _Gsyscall *or* _Gdeadextra. In the latter case, it's an
  6779  	// extra M goroutine.
  6780  	if status != _Gsyscall && status != _Gdeadextra {
  6781  		// Not in a syscall, nothing to do.
  6782  		return syscallingThread{}, false
  6783  	}
  6784  	if !castogscanstatus(gp, status, status|_Gscan) {
  6785  		// Not in _Gsyscall or _Gdeadextra anymore. Nothing to do.
  6786  		return syscallingThread{}, false
  6787  	}
  6788  	if gp.m != mp || gp.m.p.ptr() != pp {
  6789  		// This is not what we originally observed. Nothing to do.
  6790  		casfrom_Gscanstatus(gp, status|_Gscan, status)
  6791  		return syscallingThread{}, false
  6792  	}
  6793  	return syscallingThread{gp, mp, pp, status}, true
  6794  }
  6795  
  6796  // gcstopP unwires the P attached to the syscalling thread
  6797  // and moves it into the _Pgcstop state.
  6798  //
  6799  // The caller must be stopping the world.
  6800  func (s syscallingThread) gcstopP() {
  6801  	assertLockHeld(&sched.lock)
  6802  
  6803  	s.releaseP(_Pgcstop)
  6804  	s.pp.gcStopTime = nanotime()
  6805  	sched.stopwait--
  6806  }
  6807  
  6808  // takeP unwires the P attached to the syscalling thread
  6809  // and moves it into the _Pidle state.
  6810  func (s syscallingThread) takeP() {
  6811  	s.releaseP(_Pidle)
  6812  }
  6813  
  6814  // releaseP unwires the P from the syscalling thread, moving
  6815  // it to the provided state. Callers should prefer to use
  6816  // takeP and gcstopP.
  6817  func (s syscallingThread) releaseP(state uint32) {
  6818  	if state != _Pidle && state != _Pgcstop {
  6819  		throw("attempted to release P into a bad state")
  6820  	}
  6821  	trace := traceAcquire()
  6822  	s.pp.m = 0
  6823  	s.mp.p = 0
  6824  	atomic.Store(&s.pp.status, state)
  6825  	if trace.ok() {
  6826  		trace.ProcSteal(s.pp)
  6827  		traceRelease(trace)
  6828  	}
  6829  	addGSyscallNoP(s.mp)
  6830  	s.pp.syscalltick++
  6831  }
  6832  
  6833  // resume allows a syscalling thread to advance beyond exitsyscall.
  6834  func (s syscallingThread) resume() {
  6835  	casfrom_Gscanstatus(s.gp, s.status|_Gscan, s.status)
  6836  }
  6837  
  6838  // Tell all goroutines that they have been preempted and they should stop.
  6839  // This function is purely best-effort. It can fail to inform a goroutine if a
  6840  // processor just started running it.
  6841  // No locks need to be held.
  6842  // Returns true if preemption request was issued to at least one goroutine.
  6843  func preemptall() bool {
  6844  	res := false
  6845  	for _, pp := range allp {
  6846  		if pp.status != _Prunning {
  6847  			continue
  6848  		}
  6849  		if preemptone(pp) {
  6850  			res = true
  6851  		}
  6852  	}
  6853  	return res
  6854  }
  6855  
  6856  // Tell the goroutine running on processor P to stop.
  6857  // This function is purely best-effort. It can incorrectly fail to inform the
  6858  // goroutine. It can inform the wrong goroutine. Even if it informs the
  6859  // correct goroutine, that goroutine might ignore the request if it is
  6860  // simultaneously executing newstack.
  6861  // No lock needs to be held.
  6862  // Returns true if preemption request was issued.
  6863  // The actual preemption will happen at some point in the future
  6864  // and will be indicated by the gp->status no longer being
  6865  // Grunning
  6866  func preemptone(pp *p) bool {
  6867  	mp := pp.m.ptr()
  6868  	if mp == nil || mp == getg().m {
  6869  		return false
  6870  	}
  6871  	gp := mp.curg
  6872  	if gp == nil || gp == mp.g0 {
  6873  		return false
  6874  	}
  6875  	if readgstatus(gp)&^_Gscan == _Gsyscall {
  6876  		// Don't bother trying to preempt a goroutine in a syscall.
  6877  		return false
  6878  	}
  6879  
  6880  	gp.preempt = true
  6881  
  6882  	// Every call in a goroutine checks for stack overflow by
  6883  	// comparing the current stack pointer to gp->stackguard0.
  6884  	// Setting gp->stackguard0 to StackPreempt folds
  6885  	// preemption into the normal stack overflow check.
  6886  	gp.stackguard0 = stackPreempt
  6887  
  6888  	// Request an async preemption of this P.
  6889  	if preemptMSupported && debug.asyncpreemptoff == 0 {
  6890  		pp.preempt = true
  6891  		preemptM(mp)
  6892  	}
  6893  
  6894  	return true
  6895  }
  6896  
  6897  var starttime int64
  6898  
  6899  func schedtrace(detailed bool) {
  6900  	now := nanotime()
  6901  	if starttime == 0 {
  6902  		starttime = now
  6903  	}
  6904  
  6905  	lock(&sched.lock)
  6906  	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)
  6907  	if detailed {
  6908  		print(" gcwaiting=", sched.gcwaiting.Load(), " nmidlelocked=", sched.nmidlelocked, " stopwait=", sched.stopwait, " sysmonwait=", sched.sysmonwait.Load(), "\n")
  6909  	}
  6910  	// We must be careful while reading data from P's, M's and G's.
  6911  	// Even if we hold schedlock, most data can be changed concurrently.
  6912  	// E.g. (p->m ? p->m->id : -1) can crash if p->m changes from non-nil to nil.
  6913  	for i, pp := range allp {
  6914  		h := atomic.Load(&pp.runqhead)
  6915  		t := atomic.Load(&pp.runqtail)
  6916  		if detailed {
  6917  			print("  P", i, ": status=", pp.status, " schedtick=", pp.schedtick, " syscalltick=", pp.syscalltick, " m=")
  6918  			mp := pp.m.ptr()
  6919  			if mp != nil {
  6920  				print(mp.id)
  6921  			} else {
  6922  				print("nil")
  6923  			}
  6924  			print(" runqsize=", t-h, " gfreecnt=", pp.gFree.size, " timerslen=", len(pp.timers.heap), "\n")
  6925  		} else {
  6926  			// In non-detailed mode format lengths of per-P run queues as:
  6927  			// [ len1 len2 len3 len4 ]
  6928  			print(" ")
  6929  			if i == 0 {
  6930  				print("[ ")
  6931  			}
  6932  			print(t - h)
  6933  			if i == len(allp)-1 {
  6934  				print(" ]")
  6935  			}
  6936  		}
  6937  	}
  6938  
  6939  	if !detailed {
  6940  		// Format per-P schedticks as: schedticks=[ tick1 tick2 tick3 tick4 ].
  6941  		print(" schedticks=[ ")
  6942  		for _, pp := range allp {
  6943  			print(pp.schedtick)
  6944  			print(" ")
  6945  		}
  6946  		print("]\n")
  6947  	}
  6948  
  6949  	if !detailed {
  6950  		unlock(&sched.lock)
  6951  		return
  6952  	}
  6953  
  6954  	for mp := allm; mp != nil; mp = mp.alllink {
  6955  		pp := mp.p.ptr()
  6956  		print("  M", mp.id, ": p=")
  6957  		if pp != nil {
  6958  			print(pp.id)
  6959  		} else {
  6960  			print("nil")
  6961  		}
  6962  		print(" curg=")
  6963  		if mp.curg != nil {
  6964  			print(mp.curg.goid)
  6965  		} else {
  6966  			print("nil")
  6967  		}
  6968  		print(" mallocing=", mp.mallocing, " throwing=", mp.throwing, " preemptoff=", mp.preemptoff, " locks=", mp.locks, " dying=", mp.dying, " spinning=", mp.spinning, " blocked=", mp.blocked, " lockedg=")
  6969  		if lockedg := mp.lockedg.ptr(); lockedg != nil {
  6970  			print(lockedg.goid)
  6971  		} else {
  6972  			print("nil")
  6973  		}
  6974  		print("\n")
  6975  	}
  6976  
  6977  	forEachG(func(gp *g) {
  6978  		print("  G", gp.goid, ": status=", readgstatus(gp), "(", gp.waitreason.String(), ") m=")
  6979  		if gp.m != nil {
  6980  			print(gp.m.id)
  6981  		} else {
  6982  			print("nil")
  6983  		}
  6984  		print(" lockedm=")
  6985  		if lockedm := gp.lockedm.ptr(); lockedm != nil {
  6986  			print(lockedm.id)
  6987  		} else {
  6988  			print("nil")
  6989  		}
  6990  		print("\n")
  6991  	})
  6992  	unlock(&sched.lock)
  6993  }
  6994  
  6995  type updateMaxProcsGState struct {
  6996  	lock mutex
  6997  	g    *g
  6998  	idle atomic.Bool
  6999  
  7000  	// Readable when idle == false, writable when idle == true.
  7001  	procs int32 // new GOMAXPROCS value
  7002  }
  7003  
  7004  var (
  7005  	// GOMAXPROCS update godebug metric. Incremented if automatic
  7006  	// GOMAXPROCS updates actually change the value of GOMAXPROCS.
  7007  	updatemaxprocs = &godebugInc{name: "updatemaxprocs"}
  7008  
  7009  	// Synchronization and state between updateMaxProcsGoroutine and
  7010  	// sysmon.
  7011  	updateMaxProcsG updateMaxProcsGState
  7012  
  7013  	// Synchronization between GOMAXPROCS and sysmon.
  7014  	//
  7015  	// Setting GOMAXPROCS via a call to GOMAXPROCS disables automatic
  7016  	// GOMAXPROCS updates.
  7017  	//
  7018  	// We want to make two guarantees to callers of GOMAXPROCS. After
  7019  	// GOMAXPROCS returns:
  7020  	//
  7021  	// 1. The runtime will not make any automatic changes to GOMAXPROCS.
  7022  	//
  7023  	// 2. The runtime will not perform any of the system calls used to
  7024  	//    determine the appropriate value of GOMAXPROCS (i.e., it won't
  7025  	//    call defaultGOMAXPROCS).
  7026  	//
  7027  	// (1) is the baseline guarantee that everyone needs. The GOMAXPROCS
  7028  	// API isn't useful to anyone if automatic updates may occur after it
  7029  	// returns. This is easily achieved by double-checking the state under
  7030  	// STW before committing an automatic GOMAXPROCS update.
  7031  	//
  7032  	// (2) doesn't matter to most users, as it is isn't observable as long
  7033  	// as (1) holds. However, it can be important to users sandboxing Go.
  7034  	// They want disable these system calls and need some way to know when
  7035  	// they are guaranteed the calls will stop.
  7036  	//
  7037  	// This would be simple to achieve if we simply called
  7038  	// defaultGOMAXPROCS under STW in updateMaxProcsGoroutine below.
  7039  	// However, we would like to avoid scheduling this goroutine every
  7040  	// second when it will almost never do anything. Instead, sysmon calls
  7041  	// defaultGOMAXPROCS to decide whether to schedule
  7042  	// updateMaxProcsGoroutine. Thus we need to synchronize between sysmon
  7043  	// and GOMAXPROCS calls.
  7044  	//
  7045  	// GOMAXPROCS can't hold a runtime mutex across STW. It could hold a
  7046  	// semaphore, but sysmon cannot take semaphores. Instead, we have a
  7047  	// more complex scheme:
  7048  	//
  7049  	// * sysmon holds computeMaxProcsLock while calling defaultGOMAXPROCS.
  7050  	// * sysmon skips the current update if sched.customGOMAXPROCS is
  7051  	//   set.
  7052  	// * GOMAXPROCS sets sched.customGOMAXPROCS once it is committed to
  7053  	//   changing GOMAXPROCS.
  7054  	// * GOMAXPROCS takes computeMaxProcsLock to wait for outstanding
  7055  	//   defaultGOMAXPROCS calls to complete.
  7056  	//
  7057  	// N.B. computeMaxProcsLock could simply be sched.lock, but we want to
  7058  	// avoid holding that lock during the potentially slow
  7059  	// defaultGOMAXPROCS.
  7060  	computeMaxProcsLock mutex
  7061  )
  7062  
  7063  // Start GOMAXPROCS update helper goroutine.
  7064  //
  7065  // This is based on forcegchelper.
  7066  func defaultGOMAXPROCSUpdateEnable() {
  7067  	if debug.updatemaxprocs == 0 {
  7068  		// Unconditionally increment the metric when updates are disabled.
  7069  		//
  7070  		// It would be more descriptive if we did a dry run of the
  7071  		// complete update, determining the appropriate value of
  7072  		// GOMAXPROCS and the bailing out and just incrementing the
  7073  		// metric if a change would occur.
  7074  		//
  7075  		// Not only is that a lot of ongoing work for a disabled
  7076  		// feature, but some users need to be able to completely
  7077  		// disable the update system calls (such as sandboxes).
  7078  		// Currently, updatemaxprocs=0 serves that purpose.
  7079  		updatemaxprocs.IncNonDefault()
  7080  		return
  7081  	}
  7082  
  7083  	go updateMaxProcsGoroutine()
  7084  }
  7085  
  7086  func updateMaxProcsGoroutine() {
  7087  	updateMaxProcsG.g = getg()
  7088  	lockInit(&updateMaxProcsG.lock, lockRankUpdateMaxProcsG)
  7089  	for {
  7090  		lock(&updateMaxProcsG.lock)
  7091  		if updateMaxProcsG.idle.Load() {
  7092  			throw("updateMaxProcsGoroutine: phase error")
  7093  		}
  7094  		updateMaxProcsG.idle.Store(true)
  7095  		goparkunlock(&updateMaxProcsG.lock, waitReasonUpdateGOMAXPROCSIdle, traceBlockSystemGoroutine, 1)
  7096  		// This goroutine is explicitly resumed by sysmon.
  7097  
  7098  		stw := stopTheWorldGC(stwGOMAXPROCS)
  7099  
  7100  		// Still OK to update?
  7101  		lock(&sched.lock)
  7102  		custom := sched.customGOMAXPROCS
  7103  		unlock(&sched.lock)
  7104  		if custom {
  7105  			startTheWorldGC(stw)
  7106  			return
  7107  		}
  7108  
  7109  		// newprocs will be processed by startTheWorld
  7110  		//
  7111  		// TODO(prattmic): this could use a nicer API. Perhaps add it to the
  7112  		// stw parameter?
  7113  		newprocs = updateMaxProcsG.procs
  7114  		lock(&sched.lock)
  7115  		sched.customGOMAXPROCS = false
  7116  		unlock(&sched.lock)
  7117  
  7118  		startTheWorldGC(stw)
  7119  	}
  7120  }
  7121  
  7122  func sysmonUpdateGOMAXPROCS() {
  7123  	// Synchronize with GOMAXPROCS. See comment on computeMaxProcsLock.
  7124  	lock(&computeMaxProcsLock)
  7125  
  7126  	// No update if GOMAXPROCS was set manually.
  7127  	lock(&sched.lock)
  7128  	custom := sched.customGOMAXPROCS
  7129  	curr := gomaxprocs
  7130  	unlock(&sched.lock)
  7131  	if custom {
  7132  		unlock(&computeMaxProcsLock)
  7133  		return
  7134  	}
  7135  
  7136  	// Don't hold sched.lock while we read the filesystem.
  7137  	procs := defaultGOMAXPROCS(0)
  7138  	unlock(&computeMaxProcsLock)
  7139  	if procs == curr {
  7140  		// Nothing to do.
  7141  		return
  7142  	}
  7143  
  7144  	// Sysmon can't directly stop the world. Run the helper to do so on our
  7145  	// behalf. If updateGOMAXPROCS.idle is false, then a previous update is
  7146  	// still pending.
  7147  	if updateMaxProcsG.idle.Load() {
  7148  		lock(&updateMaxProcsG.lock)
  7149  		updateMaxProcsG.procs = procs
  7150  		updateMaxProcsG.idle.Store(false)
  7151  		var list gList
  7152  		list.push(updateMaxProcsG.g)
  7153  		injectglist(&list)
  7154  		unlock(&updateMaxProcsG.lock)
  7155  	}
  7156  }
  7157  
  7158  // schedEnableUser enables or disables the scheduling of user
  7159  // goroutines.
  7160  //
  7161  // This does not stop already running user goroutines, so the caller
  7162  // should first stop the world when disabling user goroutines.
  7163  func schedEnableUser(enable bool) {
  7164  	lock(&sched.lock)
  7165  	if sched.disable.user == !enable {
  7166  		unlock(&sched.lock)
  7167  		return
  7168  	}
  7169  	sched.disable.user = !enable
  7170  	if enable {
  7171  		n := sched.disable.runnable.size
  7172  		globrunqputbatch(&sched.disable.runnable)
  7173  		unlock(&sched.lock)
  7174  		for ; n != 0 && sched.npidle.Load() != 0; n-- {
  7175  			startm(nil, false, false)
  7176  		}
  7177  	} else {
  7178  		unlock(&sched.lock)
  7179  	}
  7180  }
  7181  
  7182  // schedEnabled reports whether gp should be scheduled. It returns
  7183  // false is scheduling of gp is disabled.
  7184  //
  7185  // sched.lock must be held.
  7186  func schedEnabled(gp *g) bool {
  7187  	assertLockHeld(&sched.lock)
  7188  
  7189  	if sched.disable.user {
  7190  		return isSystemGoroutine(gp, true)
  7191  	}
  7192  	return true
  7193  }
  7194  
  7195  // Put mp on midle list.
  7196  // sched.lock must be held.
  7197  // May run during STW, so write barriers are not allowed.
  7198  //
  7199  //go:nowritebarrierrec
  7200  func mput(mp *m) {
  7201  	assertLockHeld(&sched.lock)
  7202  
  7203  	sched.midle.push(unsafe.Pointer(mp))
  7204  	sched.nmidle++
  7205  	checkdead()
  7206  }
  7207  
  7208  // Try to get an m from midle list.
  7209  // sched.lock must be held.
  7210  // May run during STW, so write barriers are not allowed.
  7211  //
  7212  //go:nowritebarrierrec
  7213  func mget() *m {
  7214  	assertLockHeld(&sched.lock)
  7215  
  7216  	mp := (*m)(sched.midle.pop())
  7217  	if mp != nil {
  7218  		sched.nmidle--
  7219  	}
  7220  	return mp
  7221  }
  7222  
  7223  // Try to get a specific m from midle list. Returns nil if it isn't on the
  7224  // midle list.
  7225  //
  7226  // sched.lock must be held.
  7227  // May run during STW, so write barriers are not allowed.
  7228  //
  7229  //go:nowritebarrierrec
  7230  func mgetSpecific(mp *m) *m {
  7231  	assertLockHeld(&sched.lock)
  7232  
  7233  	if mp.idleNode.prev == 0 && mp.idleNode.next == 0 {
  7234  		// Not on the list.
  7235  		return nil
  7236  	}
  7237  
  7238  	sched.midle.remove(unsafe.Pointer(mp))
  7239  	sched.nmidle--
  7240  
  7241  	return mp
  7242  }
  7243  
  7244  // Put gp on the global runnable queue.
  7245  // sched.lock must be held.
  7246  // May run during STW, so write barriers are not allowed.
  7247  //
  7248  //go:nowritebarrierrec
  7249  func globrunqput(gp *g) {
  7250  	assertLockHeld(&sched.lock)
  7251  
  7252  	sched.runq.pushBack(gp)
  7253  }
  7254  
  7255  // Put gp at the head of the global runnable queue.
  7256  // sched.lock must be held.
  7257  // May run during STW, so write barriers are not allowed.
  7258  //
  7259  //go:nowritebarrierrec
  7260  func globrunqputhead(gp *g) {
  7261  	assertLockHeld(&sched.lock)
  7262  
  7263  	sched.runq.push(gp)
  7264  }
  7265  
  7266  // Put a batch of runnable goroutines on the global runnable queue.
  7267  // This clears *batch.
  7268  // sched.lock must be held.
  7269  // May run during STW, so write barriers are not allowed.
  7270  //
  7271  //go:nowritebarrierrec
  7272  func globrunqputbatch(batch *gQueue) {
  7273  	assertLockHeld(&sched.lock)
  7274  
  7275  	sched.runq.pushBackAll(*batch)
  7276  	*batch = gQueue{}
  7277  }
  7278  
  7279  // Try get a single G from the global runnable queue.
  7280  // sched.lock must be held.
  7281  func globrunqget() *g {
  7282  	assertLockHeld(&sched.lock)
  7283  
  7284  	if sched.runq.size == 0 {
  7285  		return nil
  7286  	}
  7287  
  7288  	return sched.runq.pop()
  7289  }
  7290  
  7291  // Try get a batch of G's from the global runnable queue.
  7292  // sched.lock must be held.
  7293  func globrunqgetbatch(n int32) (gp *g, q gQueue) {
  7294  	assertLockHeld(&sched.lock)
  7295  
  7296  	if sched.runq.size == 0 {
  7297  		return
  7298  	}
  7299  
  7300  	n = min(n, sched.runq.size, sched.runq.size/gomaxprocs+1)
  7301  
  7302  	gp = sched.runq.pop()
  7303  	n--
  7304  
  7305  	for ; n > 0; n-- {
  7306  		gp1 := sched.runq.pop()
  7307  		q.pushBack(gp1)
  7308  	}
  7309  	return
  7310  }
  7311  
  7312  // pMask is an atomic bitstring with one bit per P.
  7313  type pMask []uint32
  7314  
  7315  // read returns true if P id's bit is set.
  7316  func (p pMask) read(id uint32) bool {
  7317  	word := id / 32
  7318  	mask := uint32(1) << (id % 32)
  7319  	return (atomic.Load(&p[word]) & mask) != 0
  7320  }
  7321  
  7322  // set sets P id's bit.
  7323  func (p pMask) set(id int32) {
  7324  	word := id / 32
  7325  	mask := uint32(1) << (id % 32)
  7326  	atomic.Or(&p[word], mask)
  7327  }
  7328  
  7329  // clear clears P id's bit.
  7330  func (p pMask) clear(id int32) {
  7331  	word := id / 32
  7332  	mask := uint32(1) << (id % 32)
  7333  	atomic.And(&p[word], ^mask)
  7334  }
  7335  
  7336  // any returns true if any bit in p is set.
  7337  func (p pMask) any() bool {
  7338  	for i := range p {
  7339  		if atomic.Load(&p[i]) != 0 {
  7340  			return true
  7341  		}
  7342  	}
  7343  	return false
  7344  }
  7345  
  7346  // resize resizes the pMask and returns a new one.
  7347  //
  7348  // The result may alias p, so callers are encouraged to
  7349  // discard p. Not safe for concurrent use.
  7350  func (p pMask) resize(nprocs int32) pMask {
  7351  	maskWords := (nprocs + 31) / 32
  7352  
  7353  	if maskWords <= int32(cap(p)) {
  7354  		return p[:maskWords]
  7355  	}
  7356  	newMask := make([]uint32, maskWords)
  7357  	// No need to copy beyond len, old Ps are irrelevant.
  7358  	copy(newMask, p)
  7359  	return newMask
  7360  }
  7361  
  7362  // pidleput puts p on the _Pidle list. now must be a relatively recent call
  7363  // to nanotime or zero. Returns now or the current time if now was zero.
  7364  //
  7365  // This releases ownership of p. Once sched.lock is released it is no longer
  7366  // safe to use p.
  7367  //
  7368  // sched.lock must be held.
  7369  //
  7370  // May run during STW, so write barriers are not allowed.
  7371  //
  7372  //go:nowritebarrierrec
  7373  func pidleput(pp *p, now int64) int64 {
  7374  	assertLockHeld(&sched.lock)
  7375  
  7376  	if !runqempty(pp) {
  7377  		throw("pidleput: P has non-empty run queue")
  7378  	}
  7379  	if now == 0 {
  7380  		now = nanotime()
  7381  	}
  7382  	if pp.timers.len.Load() == 0 {
  7383  		timerpMask.clear(pp.id)
  7384  	}
  7385  	idlepMask.set(pp.id)
  7386  	pp.link = sched.pidle
  7387  	sched.pidle.set(pp)
  7388  	sched.npidle.Add(1)
  7389  	if !pp.limiterEvent.start(limiterEventIdle, now) {
  7390  		throw("must be able to track idle limiter event")
  7391  	}
  7392  	return now
  7393  }
  7394  
  7395  // pidleget tries to get a p from the _Pidle list, acquiring ownership.
  7396  //
  7397  // sched.lock must be held.
  7398  //
  7399  // May run during STW, so write barriers are not allowed.
  7400  //
  7401  //go:nowritebarrierrec
  7402  func pidleget(now int64) (*p, int64) {
  7403  	assertLockHeld(&sched.lock)
  7404  
  7405  	pp := sched.pidle.ptr()
  7406  	if pp != nil {
  7407  		// Timer may get added at any time now.
  7408  		if now == 0 {
  7409  			now = nanotime()
  7410  		}
  7411  		timerpMask.set(pp.id)
  7412  		idlepMask.clear(pp.id)
  7413  		sched.pidle = pp.link
  7414  		sched.npidle.Add(-1)
  7415  		pp.limiterEvent.stop(limiterEventIdle, now)
  7416  	}
  7417  	return pp, now
  7418  }
  7419  
  7420  // pidlegetSpinning tries to get a p from the _Pidle list, acquiring ownership.
  7421  // This is called by spinning Ms (or callers than need a spinning M) that have
  7422  // found work. If no P is available, this must synchronized with non-spinning
  7423  // Ms that may be preparing to drop their P without discovering this work.
  7424  //
  7425  // sched.lock must be held.
  7426  //
  7427  // May run during STW, so write barriers are not allowed.
  7428  //
  7429  //go:nowritebarrierrec
  7430  func pidlegetSpinning(now int64) (*p, int64) {
  7431  	assertLockHeld(&sched.lock)
  7432  
  7433  	pp, now := pidleget(now)
  7434  	if pp == nil {
  7435  		// See "Delicate dance" comment in findRunnable. We found work
  7436  		// that we cannot take, we must synchronize with non-spinning
  7437  		// Ms that may be preparing to drop their P.
  7438  		sched.needspinning.Store(1)
  7439  		return nil, now
  7440  	}
  7441  
  7442  	return pp, now
  7443  }
  7444  
  7445  // runqempty reports whether pp has no Gs on its local run queue.
  7446  // It never returns true spuriously.
  7447  func runqempty(pp *p) bool {
  7448  	// Defend against a race where 1) pp has G1 in runqnext but runqhead == runqtail,
  7449  	// 2) runqput on pp kicks G1 to the runq, 3) runqget on pp empties runqnext.
  7450  	// Simply observing that runqhead == runqtail and then observing that runqnext == nil
  7451  	// does not mean the queue is empty.
  7452  	for {
  7453  		head := atomic.Load(&pp.runqhead)
  7454  		tail := atomic.Load(&pp.runqtail)
  7455  		runnext := atomic.Loaduintptr((*uintptr)(unsafe.Pointer(&pp.runnext)))
  7456  		if tail == atomic.Load(&pp.runqtail) {
  7457  			return head == tail && runnext == 0
  7458  		}
  7459  	}
  7460  }
  7461  
  7462  // To shake out latent assumptions about scheduling order,
  7463  // we introduce some randomness into scheduling decisions
  7464  // when running with the race detector.
  7465  // The need for this was made obvious by changing the
  7466  // (deterministic) scheduling order in Go 1.5 and breaking
  7467  // many poorly-written tests.
  7468  // With the randomness here, as long as the tests pass
  7469  // consistently with -race, they shouldn't have latent scheduling
  7470  // assumptions.
  7471  const randomizeScheduler = raceenabled
  7472  
  7473  // runqput tries to put g on the local runnable queue.
  7474  // If next is false, runqput adds g to the tail of the runnable queue.
  7475  // If next is true, runqput puts g in the pp.runnext slot.
  7476  // If the run queue is full, runnext puts g on the global queue.
  7477  // Executed only by the owner P.
  7478  func runqput(pp *p, gp *g, next bool) {
  7479  	if !haveSysmon && next {
  7480  		// A runnext goroutine shares the same time slice as the
  7481  		// current goroutine (inheritTime from runqget). To prevent a
  7482  		// ping-pong pair of goroutines from starving all others, we
  7483  		// depend on sysmon to preempt "long-running goroutines". That
  7484  		// is, any set of goroutines sharing the same time slice.
  7485  		//
  7486  		// If there is no sysmon, we must avoid runnext entirely or
  7487  		// risk starvation.
  7488  		next = false
  7489  	}
  7490  	if randomizeScheduler && next && randn(2) == 0 {
  7491  		next = false
  7492  	}
  7493  
  7494  	if next {
  7495  	retryNext:
  7496  		oldnext := pp.runnext
  7497  		if !pp.runnext.cas(oldnext, guintptr(unsafe.Pointer(gp))) {
  7498  			goto retryNext
  7499  		}
  7500  		if oldnext == 0 {
  7501  			return
  7502  		}
  7503  		// Kick the old runnext out to the regular run queue.
  7504  		gp = oldnext.ptr()
  7505  	}
  7506  
  7507  retry:
  7508  	h := atomic.LoadAcq(&pp.runqhead) // load-acquire, synchronize with consumers
  7509  	t := pp.runqtail
  7510  	if t-h < uint32(len(pp.runq)) {
  7511  		pp.runq[t%uint32(len(pp.runq))].set(gp)
  7512  		atomic.StoreRel(&pp.runqtail, t+1) // store-release, makes the item available for consumption
  7513  		return
  7514  	}
  7515  	if runqputslow(pp, gp, h, t) {
  7516  		return
  7517  	}
  7518  	// the queue is not full, now the put above must succeed
  7519  	goto retry
  7520  }
  7521  
  7522  // Put g and a batch of work from local runnable queue on global queue.
  7523  // Executed only by the owner P.
  7524  func runqputslow(pp *p, gp *g, h, t uint32) bool {
  7525  	var batch [len(pp.runq)/2 + 1]*g
  7526  
  7527  	// First, grab a batch from local queue.
  7528  	n := t - h
  7529  	n = n / 2
  7530  	if n != uint32(len(pp.runq)/2) {
  7531  		throw("runqputslow: queue is not full")
  7532  	}
  7533  	for i := uint32(0); i < n; i++ {
  7534  		batch[i] = pp.runq[(h+i)%uint32(len(pp.runq))].ptr()
  7535  	}
  7536  	if !atomic.CasRel(&pp.runqhead, h, h+n) { // cas-release, commits consume
  7537  		return false
  7538  	}
  7539  	batch[n] = gp
  7540  
  7541  	if randomizeScheduler {
  7542  		for i := uint32(1); i <= n; i++ {
  7543  			j := cheaprandn(i + 1)
  7544  			batch[i], batch[j] = batch[j], batch[i]
  7545  		}
  7546  	}
  7547  
  7548  	// Link the goroutines.
  7549  	for i := uint32(0); i < n; i++ {
  7550  		batch[i].schedlink.set(batch[i+1])
  7551  	}
  7552  
  7553  	q := gQueue{batch[0].guintptr(), batch[n].guintptr(), int32(n + 1)}
  7554  
  7555  	// Now put the batch on global queue.
  7556  	lock(&sched.lock)
  7557  	globrunqputbatch(&q)
  7558  	unlock(&sched.lock)
  7559  	return true
  7560  }
  7561  
  7562  // runqputbatch tries to put all the G's on q on the local runnable queue.
  7563  // If the local runq is full the input queue still contains unqueued Gs.
  7564  // Executed only by the owner P.
  7565  func runqputbatch(pp *p, q *gQueue) {
  7566  	if q.empty() {
  7567  		return
  7568  	}
  7569  	h := atomic.LoadAcq(&pp.runqhead)
  7570  	t := pp.runqtail
  7571  	n := uint32(0)
  7572  	for !q.empty() && t-h < uint32(len(pp.runq)) {
  7573  		gp := q.pop()
  7574  		pp.runq[t%uint32(len(pp.runq))].set(gp)
  7575  		t++
  7576  		n++
  7577  	}
  7578  
  7579  	if randomizeScheduler {
  7580  		off := func(o uint32) uint32 {
  7581  			return (pp.runqtail + o) % uint32(len(pp.runq))
  7582  		}
  7583  		for i := uint32(1); i < n; i++ {
  7584  			j := cheaprandn(i + 1)
  7585  			pp.runq[off(i)], pp.runq[off(j)] = pp.runq[off(j)], pp.runq[off(i)]
  7586  		}
  7587  	}
  7588  
  7589  	atomic.StoreRel(&pp.runqtail, t)
  7590  
  7591  	return
  7592  }
  7593  
  7594  // Get g from local runnable queue.
  7595  // If inheritTime is true, gp should inherit the remaining time in the
  7596  // current time slice. Otherwise, it should start a new time slice.
  7597  // Executed only by the owner P.
  7598  func runqget(pp *p) (gp *g, inheritTime bool) {
  7599  	// If there's a runnext, it's the next G to run.
  7600  	next := pp.runnext
  7601  	// If the runnext is non-0 and the CAS fails, it could only have been stolen by another P,
  7602  	// because other Ps can race to set runnext to 0, but only the current P can set it to non-0.
  7603  	// Hence, there's no need to retry this CAS if it fails.
  7604  	if next != 0 && pp.runnext.cas(next, 0) {
  7605  		return next.ptr(), true
  7606  	}
  7607  
  7608  	for {
  7609  		h := atomic.LoadAcq(&pp.runqhead) // load-acquire, synchronize with other consumers
  7610  		t := pp.runqtail
  7611  		if t == h {
  7612  			return nil, false
  7613  		}
  7614  		gp := pp.runq[h%uint32(len(pp.runq))].ptr()
  7615  		if atomic.CasRel(&pp.runqhead, h, h+1) { // cas-release, commits consume
  7616  			return gp, false
  7617  		}
  7618  	}
  7619  }
  7620  
  7621  // runqdrain drains the local runnable queue of pp and returns all goroutines in it.
  7622  // Executed only by the owner P.
  7623  func runqdrain(pp *p) (drainQ gQueue) {
  7624  	oldNext := pp.runnext
  7625  	if oldNext != 0 && pp.runnext.cas(oldNext, 0) {
  7626  		drainQ.pushBack(oldNext.ptr())
  7627  	}
  7628  
  7629  retry:
  7630  	h := atomic.LoadAcq(&pp.runqhead) // load-acquire, synchronize with other consumers
  7631  	t := pp.runqtail
  7632  	qn := t - h
  7633  	if qn == 0 {
  7634  		return
  7635  	}
  7636  	if qn > uint32(len(pp.runq)) { // read inconsistent h and t
  7637  		goto retry
  7638  	}
  7639  
  7640  	if !atomic.CasRel(&pp.runqhead, h, h+qn) { // cas-release, commits consume
  7641  		goto retry
  7642  	}
  7643  
  7644  	// We've inverted the order in which it gets G's from the local P's runnable queue
  7645  	// and then advances the head pointer because we don't want to mess up the statuses of G's
  7646  	// while runqdrain() and runqsteal() are running in parallel.
  7647  	// Thus we should advance the head pointer before draining the local P into a gQueue,
  7648  	// so that we can update any gp.schedlink only after we take the full ownership of G,
  7649  	// meanwhile, other P's can't access to all G's in local P's runnable queue and steal them.
  7650  	// See https://groups.google.com/g/golang-dev/c/0pTKxEKhHSc/m/6Q85QjdVBQAJ for more details.
  7651  	for i := uint32(0); i < qn; i++ {
  7652  		gp := pp.runq[(h+i)%uint32(len(pp.runq))].ptr()
  7653  		drainQ.pushBack(gp)
  7654  	}
  7655  	return
  7656  }
  7657  
  7658  // Grabs a batch of goroutines from pp's runnable queue into batch.
  7659  // Batch is a ring buffer starting at batchHead.
  7660  // Returns number of grabbed goroutines.
  7661  // Can be executed by any P.
  7662  func runqgrab(pp *p, batch *[256]guintptr, batchHead uint32, stealRunNextG bool) uint32 {
  7663  	for {
  7664  		h := atomic.LoadAcq(&pp.runqhead) // load-acquire, synchronize with other consumers
  7665  		t := atomic.LoadAcq(&pp.runqtail) // load-acquire, synchronize with the producer
  7666  		n := t - h
  7667  		n = n - n/2
  7668  		if n == 0 {
  7669  			if stealRunNextG {
  7670  				// Try to steal from pp.runnext.
  7671  				if next := pp.runnext; next != 0 {
  7672  					if pp.status == _Prunning {
  7673  						if mp := pp.m.ptr(); mp != nil {
  7674  							if gp := mp.curg; gp == nil || readgstatus(gp)&^_Gscan != _Gsyscall {
  7675  								// Sleep to ensure that pp isn't about to run the g
  7676  								// we are about to steal.
  7677  								// The important use case here is when the g running
  7678  								// on pp ready()s another g and then almost
  7679  								// immediately blocks. Instead of stealing runnext
  7680  								// in this window, back off to give pp a chance to
  7681  								// schedule runnext. This will avoid thrashing gs
  7682  								// between different Ps.
  7683  								// A sync chan send/recv takes ~50ns as of time of
  7684  								// writing, so 3us gives ~50x overshoot.
  7685  								// If curg is nil, we assume that the P is likely
  7686  								// to be in the scheduler. If curg isn't nil and isn't
  7687  								// in a syscall, then it's either running, waiting, or
  7688  								// runnable. In this case we want to sleep because the
  7689  								// P might either call into the scheduler soon (running),
  7690  								// or already is (since we found a waiting or runnable
  7691  								// goroutine hanging off of a running P, suggesting it
  7692  								// either recently transitioned out of running, or will
  7693  								// transition to running shortly).
  7694  								if !osHasLowResTimer {
  7695  									usleep(3)
  7696  								} else {
  7697  									// On some platforms system timer granularity is
  7698  									// 1-15ms, which is way too much for this
  7699  									// optimization. So just yield.
  7700  									osyield()
  7701  								}
  7702  							}
  7703  						}
  7704  					}
  7705  					if !pp.runnext.cas(next, 0) {
  7706  						continue
  7707  					}
  7708  					batch[batchHead%uint32(len(batch))] = next
  7709  					return 1
  7710  				}
  7711  			}
  7712  			return 0
  7713  		}
  7714  		if n > uint32(len(pp.runq)/2) { // read inconsistent h and t
  7715  			continue
  7716  		}
  7717  		for i := uint32(0); i < n; i++ {
  7718  			g := pp.runq[(h+i)%uint32(len(pp.runq))]
  7719  			batch[(batchHead+i)%uint32(len(batch))] = g
  7720  		}
  7721  		if atomic.CasRel(&pp.runqhead, h, h+n) { // cas-release, commits consume
  7722  			return n
  7723  		}
  7724  	}
  7725  }
  7726  
  7727  // Steal half of elements from local runnable queue of p2
  7728  // and put onto local runnable queue of p.
  7729  // Returns one of the stolen elements (or nil if failed).
  7730  func runqsteal(pp, p2 *p, stealRunNextG bool) *g {
  7731  	t := pp.runqtail
  7732  	n := runqgrab(p2, &pp.runq, t, stealRunNextG)
  7733  	if n == 0 {
  7734  		return nil
  7735  	}
  7736  	n--
  7737  	gp := pp.runq[(t+n)%uint32(len(pp.runq))].ptr()
  7738  	if n == 0 {
  7739  		return gp
  7740  	}
  7741  	h := atomic.LoadAcq(&pp.runqhead) // load-acquire, synchronize with consumers
  7742  	if t-h+n >= uint32(len(pp.runq)) {
  7743  		throw("runqsteal: runq overflow")
  7744  	}
  7745  	atomic.StoreRel(&pp.runqtail, t+n) // store-release, makes the item available for consumption
  7746  	return gp
  7747  }
  7748  
  7749  // A gQueue is a dequeue of Gs linked through g.schedlink. A G can only
  7750  // be on one gQueue or gList at a time.
  7751  type gQueue struct {
  7752  	head guintptr
  7753  	tail guintptr
  7754  	size int32
  7755  }
  7756  
  7757  // empty reports whether q is empty.
  7758  func (q *gQueue) empty() bool {
  7759  	return q.head == 0
  7760  }
  7761  
  7762  // push adds gp to the head of q.
  7763  func (q *gQueue) push(gp *g) {
  7764  	gp.schedlink = q.head
  7765  	q.head.set(gp)
  7766  	if q.tail == 0 {
  7767  		q.tail.set(gp)
  7768  	}
  7769  	q.size++
  7770  }
  7771  
  7772  // pushBack adds gp to the tail of q.
  7773  func (q *gQueue) pushBack(gp *g) {
  7774  	gp.schedlink = 0
  7775  	if q.tail != 0 {
  7776  		q.tail.ptr().schedlink.set(gp)
  7777  	} else {
  7778  		q.head.set(gp)
  7779  	}
  7780  	q.tail.set(gp)
  7781  	q.size++
  7782  }
  7783  
  7784  // pushBackAll adds all Gs in q2 to the tail of q. After this q2 must
  7785  // not be used.
  7786  func (q *gQueue) pushBackAll(q2 gQueue) {
  7787  	if q2.tail == 0 {
  7788  		return
  7789  	}
  7790  	q2.tail.ptr().schedlink = 0
  7791  	if q.tail != 0 {
  7792  		q.tail.ptr().schedlink = q2.head
  7793  	} else {
  7794  		q.head = q2.head
  7795  	}
  7796  	q.tail = q2.tail
  7797  	q.size += q2.size
  7798  }
  7799  
  7800  // pop removes and returns the head of queue q. It returns nil if
  7801  // q is empty.
  7802  func (q *gQueue) pop() *g {
  7803  	gp := q.head.ptr()
  7804  	if gp != nil {
  7805  		q.head = gp.schedlink
  7806  		if q.head == 0 {
  7807  			q.tail = 0
  7808  		}
  7809  		q.size--
  7810  	}
  7811  	return gp
  7812  }
  7813  
  7814  // popList takes all Gs in q and returns them as a gList.
  7815  func (q *gQueue) popList() gList {
  7816  	stack := gList{q.head, q.size}
  7817  	*q = gQueue{}
  7818  	return stack
  7819  }
  7820  
  7821  // A gList is a list of Gs linked through g.schedlink. A G can only be
  7822  // on one gQueue or gList at a time.
  7823  type gList struct {
  7824  	head guintptr
  7825  	size int32
  7826  }
  7827  
  7828  // empty reports whether l is empty.
  7829  func (l *gList) empty() bool {
  7830  	return l.head == 0
  7831  }
  7832  
  7833  // push adds gp to the head of l.
  7834  func (l *gList) push(gp *g) {
  7835  	gp.schedlink = l.head
  7836  	l.head.set(gp)
  7837  	l.size++
  7838  }
  7839  
  7840  // pushAll prepends all Gs in q to l. After this q must not be used.
  7841  func (l *gList) pushAll(q gQueue) {
  7842  	if !q.empty() {
  7843  		q.tail.ptr().schedlink = l.head
  7844  		l.head = q.head
  7845  		l.size += q.size
  7846  	}
  7847  }
  7848  
  7849  // pop removes and returns the head of l. If l is empty, it returns nil.
  7850  func (l *gList) pop() *g {
  7851  	gp := l.head.ptr()
  7852  	if gp != nil {
  7853  		l.head = gp.schedlink
  7854  		l.size--
  7855  	}
  7856  	return gp
  7857  }
  7858  
  7859  //go:linkname setMaxThreads runtime/debug.setMaxThreads
  7860  func setMaxThreads(in int) (out int) {
  7861  	lock(&sched.lock)
  7862  	out = int(sched.maxmcount)
  7863  	if in > 0x7fffffff { // MaxInt32
  7864  		sched.maxmcount = 0x7fffffff
  7865  	} else {
  7866  		sched.maxmcount = int32(in)
  7867  	}
  7868  	checkmcount()
  7869  	unlock(&sched.lock)
  7870  	return
  7871  }
  7872  
  7873  // procPin should be an internal detail,
  7874  // but widely used packages access it using linkname.
  7875  // Notable members of the hall of shame include:
  7876  //   - github.com/bytedance/gopkg
  7877  //   - github.com/choleraehyq/pid
  7878  //   - github.com/songzhibin97/gkit
  7879  //
  7880  // Do not remove or change the type signature.
  7881  // See go.dev/issue/67401.
  7882  //
  7883  //go:linkname procPin
  7884  //go:nosplit
  7885  func procPin() int {
  7886  	gp := getg()
  7887  	mp := gp.m
  7888  
  7889  	mp.locks++
  7890  	return int(mp.p.ptr().id)
  7891  }
  7892  
  7893  // procUnpin should be an internal detail,
  7894  // but widely used packages access it using linkname.
  7895  // Notable members of the hall of shame include:
  7896  //   - github.com/bytedance/gopkg
  7897  //   - github.com/choleraehyq/pid
  7898  //   - github.com/songzhibin97/gkit
  7899  //
  7900  // Do not remove or change the type signature.
  7901  // See go.dev/issue/67401.
  7902  //
  7903  //go:linkname procUnpin
  7904  //go:nosplit
  7905  func procUnpin() {
  7906  	gp := getg()
  7907  	gp.m.locks--
  7908  }
  7909  
  7910  //go:linkname sync_runtime_procPin sync.runtime_procPin
  7911  //go:nosplit
  7912  func sync_runtime_procPin() int {
  7913  	return procPin()
  7914  }
  7915  
  7916  //go:linkname sync_runtime_procUnpin sync.runtime_procUnpin
  7917  //go:nosplit
  7918  func sync_runtime_procUnpin() {
  7919  	procUnpin()
  7920  }
  7921  
  7922  //go:linkname sync_atomic_runtime_procPin sync/atomic.runtime_procPin
  7923  //go:nosplit
  7924  func sync_atomic_runtime_procPin() int {
  7925  	return procPin()
  7926  }
  7927  
  7928  //go:linkname sync_atomic_runtime_procUnpin sync/atomic.runtime_procUnpin
  7929  //go:nosplit
  7930  func sync_atomic_runtime_procUnpin() {
  7931  	procUnpin()
  7932  }
  7933  
  7934  // Active spinning for sync.Mutex.
  7935  //
  7936  //go:linkname internal_sync_runtime_canSpin internal/sync.runtime_canSpin
  7937  //go:nosplit
  7938  func internal_sync_runtime_canSpin(i int) bool {
  7939  	// sync.Mutex is cooperative, so we are conservative with spinning.
  7940  	// Spin only few times and only if running on a multicore machine and
  7941  	// GOMAXPROCS>1 and there is at least one other running P and local runq is empty.
  7942  	// As opposed to runtime mutex we don't do passive spinning here,
  7943  	// because there can be work on global runq or on other Ps.
  7944  	if i >= active_spin || numCPUStartup <= 1 || gomaxprocs <= sched.npidle.Load()+sched.nmspinning.Load()+1 {
  7945  		return false
  7946  	}
  7947  	if p := getg().m.p.ptr(); !runqempty(p) {
  7948  		return false
  7949  	}
  7950  	return true
  7951  }
  7952  
  7953  //go:linkname internal_sync_runtime_doSpin internal/sync.runtime_doSpin
  7954  //go:nosplit
  7955  func internal_sync_runtime_doSpin() {
  7956  	procyield(active_spin_cnt)
  7957  }
  7958  
  7959  // Active spinning for sync.Mutex.
  7960  //
  7961  // sync_runtime_canSpin should be an internal detail,
  7962  // but widely used packages access it using linkname.
  7963  // Notable members of the hall of shame include:
  7964  //   - github.com/livekit/protocol
  7965  //   - github.com/sagernet/gvisor
  7966  //   - gvisor.dev/gvisor
  7967  //
  7968  // Do not remove or change the type signature.
  7969  // See go.dev/issue/67401.
  7970  //
  7971  //go:linkname sync_runtime_canSpin sync.runtime_canSpin
  7972  //go:nosplit
  7973  func sync_runtime_canSpin(i int) bool {
  7974  	return internal_sync_runtime_canSpin(i)
  7975  }
  7976  
  7977  // sync_runtime_doSpin should be an internal detail,
  7978  // but widely used packages access it using linkname.
  7979  // Notable members of the hall of shame include:
  7980  //   - github.com/livekit/protocol
  7981  //   - github.com/sagernet/gvisor
  7982  //   - gvisor.dev/gvisor
  7983  //
  7984  // Do not remove or change the type signature.
  7985  // See go.dev/issue/67401.
  7986  //
  7987  //go:linkname sync_runtime_doSpin sync.runtime_doSpin
  7988  //go:nosplit
  7989  func sync_runtime_doSpin() {
  7990  	internal_sync_runtime_doSpin()
  7991  }
  7992  
  7993  var stealOrder randomOrder
  7994  
  7995  // randomOrder/randomEnum are helper types for randomized work stealing.
  7996  // They allow to enumerate all Ps in different pseudo-random orders without repetitions.
  7997  // The algorithm is based on the fact that if we have X such that X and GOMAXPROCS
  7998  // are coprime, then a sequences of (i + X) % GOMAXPROCS gives the required enumeration.
  7999  type randomOrder struct {
  8000  	count    uint32
  8001  	coprimes []uint32
  8002  }
  8003  
  8004  type randomEnum struct {
  8005  	i     uint32
  8006  	count uint32
  8007  	pos   uint32
  8008  	inc   uint32
  8009  }
  8010  
  8011  func (ord *randomOrder) reset(count uint32) {
  8012  	ord.count = count
  8013  	ord.coprimes = ord.coprimes[:0]
  8014  	for i := uint32(1); i <= count; i++ {
  8015  		if gcd(i, count) == 1 {
  8016  			ord.coprimes = append(ord.coprimes, i)
  8017  		}
  8018  	}
  8019  }
  8020  
  8021  func (ord *randomOrder) start(i uint32) randomEnum {
  8022  	return randomEnum{
  8023  		count: ord.count,
  8024  		pos:   i % ord.count,
  8025  		inc:   ord.coprimes[i/ord.count%uint32(len(ord.coprimes))],
  8026  	}
  8027  }
  8028  
  8029  func (enum *randomEnum) done() bool {
  8030  	return enum.i == enum.count
  8031  }
  8032  
  8033  func (enum *randomEnum) next() {
  8034  	enum.i++
  8035  	enum.pos = (enum.pos + enum.inc) % enum.count
  8036  }
  8037  
  8038  func (enum *randomEnum) position() uint32 {
  8039  	return enum.pos
  8040  }
  8041  
  8042  func gcd(a, b uint32) uint32 {
  8043  	for b != 0 {
  8044  		a, b = b, a%b
  8045  	}
  8046  	return a
  8047  }
  8048  
  8049  // An initTask represents the set of initializations that need to be done for a package.
  8050  // Keep in sync with ../../test/noinit.go:initTask
  8051  type initTask struct {
  8052  	state uint32 // 0 = uninitialized, 1 = in progress, 2 = done
  8053  	nfns  uint32
  8054  	// followed by nfns pcs, uintptr sized, one per init function to run
  8055  }
  8056  
  8057  // inittrace stores statistics for init functions which are
  8058  // updated by malloc and newproc when active is true.
  8059  var inittrace tracestat
  8060  
  8061  type tracestat struct {
  8062  	active bool   // init tracing activation status
  8063  	id     uint64 // init goroutine id
  8064  	allocs uint64 // heap allocations
  8065  	bytes  uint64 // heap allocated bytes
  8066  }
  8067  
  8068  func doInit(ts []*initTask) {
  8069  	for _, t := range ts {
  8070  		doInit1(t)
  8071  	}
  8072  }
  8073  
  8074  func doInit1(t *initTask) {
  8075  	switch t.state {
  8076  	case 2: // fully initialized
  8077  		return
  8078  	case 1: // initialization in progress
  8079  		throw("recursive call during initialization - linker skew")
  8080  	default: // not initialized yet
  8081  		t.state = 1 // initialization in progress
  8082  
  8083  		var (
  8084  			start  int64
  8085  			before tracestat
  8086  		)
  8087  
  8088  		if inittrace.active {
  8089  			start = nanotime()
  8090  			// Load stats non-atomically since tracinit is updated only by this init goroutine.
  8091  			before = inittrace
  8092  		}
  8093  
  8094  		if t.nfns == 0 {
  8095  			// We should have pruned all of these in the linker.
  8096  			throw("inittask with no functions")
  8097  		}
  8098  
  8099  		firstFunc := add(unsafe.Pointer(t), 8)
  8100  		for i := uint32(0); i < t.nfns; i++ {
  8101  			p := add(firstFunc, uintptr(i)*goarch.PtrSize)
  8102  			f := *(*func())(unsafe.Pointer(&p))
  8103  			f()
  8104  		}
  8105  
  8106  		if inittrace.active {
  8107  			end := nanotime()
  8108  			// Load stats non-atomically since tracinit is updated only by this init goroutine.
  8109  			after := inittrace
  8110  
  8111  			f := *(*func())(unsafe.Pointer(&firstFunc))
  8112  			pkg := funcpkgpath(findfunc(abi.FuncPCABIInternal(f)))
  8113  
  8114  			var sbuf [24]byte
  8115  			print("init ", pkg, " @")
  8116  			print(string(fmtNSAsMS(sbuf[:], uint64(start-runtimeInitTime))), " ms, ")
  8117  			print(string(fmtNSAsMS(sbuf[:], uint64(end-start))), " ms clock, ")
  8118  			print(string(itoa(sbuf[:], after.bytes-before.bytes)), " bytes, ")
  8119  			print(string(itoa(sbuf[:], after.allocs-before.allocs)), " allocs")
  8120  			print("\n")
  8121  		}
  8122  
  8123  		t.state = 2 // initialization done
  8124  	}
  8125  }
  8126  

View as plain text