Source file src/runtime/proc.go

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

View as plain text