Source file src/runtime/proc.go

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

View as plain text