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

View as plain text