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

View as plain text