Black Lives Matter. Support the Equal Justice Initiative.

Source file src/runtime/proc.go

Documentation: runtime

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

View as plain text