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

View as plain text