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

View as plain text