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

View as plain text