Source file src/runtime/proc.go

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

View as plain text