Source file src/runtime/proc.go

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

View as plain text