Source file src/runtime/proc.go

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

View as plain text