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

View as plain text