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

View as plain text