Source file src/runtime/proc.go

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

View as plain text