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

View as plain text