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 GOOS == "darwin" {
  1285  		// Make sure pendingPreemptSignals is correct when an M exits.
  1286  		// For #41702.
  1287  		if atomic.Load(&m.signalPending) != 0 {
  1288  			atomic.Xadd(&pendingPreemptSignals, -1)
  1289  		}
  1290  	}
  1291  
  1292  	if osStack {
  1293  		// Return from mstart and let the system thread
  1294  		// library free the g0 stack and terminate the thread.
  1295  		return
  1296  	}
  1297  
  1298  	// mstart is the thread's entry point, so there's nothing to
  1299  	// return to. Exit the thread directly. exitThread will clear
  1300  	// m.freeWait when it's done with the stack and the m can be
  1301  	// reaped.
  1302  	exitThread(&m.freeWait)
  1303  }
  1304  
  1305  // forEachP calls fn(p) for every P p when p reaches a GC safe point.
  1306  // If a P is currently executing code, this will bring the P to a GC
  1307  // safe point and execute fn on that P. If the P is not executing code
  1308  // (it is idle or in a syscall), this will call fn(p) directly while
  1309  // preventing the P from exiting its state. This does not ensure that
  1310  // fn will run on every CPU executing Go code, but it acts as a global
  1311  // memory barrier. GC uses this as a "ragged barrier."
  1312  //
  1313  // The caller must hold worldsema.
  1314  //
  1315  //go:systemstack
  1316  func forEachP(fn func(*p)) {
  1317  	mp := acquirem()
  1318  	_p_ := getg().m.p.ptr()
  1319  
  1320  	lock(&sched.lock)
  1321  	if sched.safePointWait != 0 {
  1322  		throw("forEachP: sched.safePointWait != 0")
  1323  	}
  1324  	sched.safePointWait = gomaxprocs - 1
  1325  	sched.safePointFn = fn
  1326  
  1327  	// Ask all Ps to run the safe point function.
  1328  	for _, p := range allp {
  1329  		if p != _p_ {
  1330  			atomic.Store(&p.runSafePointFn, 1)
  1331  		}
  1332  	}
  1333  	preemptall()
  1334  
  1335  	// Any P entering _Pidle or _Psyscall from now on will observe
  1336  	// p.runSafePointFn == 1 and will call runSafePointFn when
  1337  	// changing its status to _Pidle/_Psyscall.
  1338  
  1339  	// Run safe point function for all idle Ps. sched.pidle will
  1340  	// not change because we hold sched.lock.
  1341  	for p := sched.pidle.ptr(); p != nil; p = p.link.ptr() {
  1342  		if atomic.Cas(&p.runSafePointFn, 1, 0) {
  1343  			fn(p)
  1344  			sched.safePointWait--
  1345  		}
  1346  	}
  1347  
  1348  	wait := sched.safePointWait > 0
  1349  	unlock(&sched.lock)
  1350  
  1351  	// Run fn for the current P.
  1352  	fn(_p_)
  1353  
  1354  	// Force Ps currently in _Psyscall into _Pidle and hand them
  1355  	// off to induce safe point function execution.
  1356  	for _, p := range allp {
  1357  		s := p.status
  1358  		if s == _Psyscall && p.runSafePointFn == 1 && atomic.Cas(&p.status, s, _Pidle) {
  1359  			if trace.enabled {
  1360  				traceGoSysBlock(p)
  1361  				traceProcStop(p)
  1362  			}
  1363  			p.syscalltick++
  1364  			handoffp(p)
  1365  		}
  1366  	}
  1367  
  1368  	// Wait for remaining Ps to run fn.
  1369  	if wait {
  1370  		for {
  1371  			// Wait for 100us, then try to re-preempt in
  1372  			// case of any races.
  1373  			//
  1374  			// Requires system stack.
  1375  			if notetsleep(&sched.safePointNote, 100*1000) {
  1376  				noteclear(&sched.safePointNote)
  1377  				break
  1378  			}
  1379  			preemptall()
  1380  		}
  1381  	}
  1382  	if sched.safePointWait != 0 {
  1383  		throw("forEachP: not done")
  1384  	}
  1385  	for _, p := range allp {
  1386  		if p.runSafePointFn != 0 {
  1387  			throw("forEachP: P did not run fn")
  1388  		}
  1389  	}
  1390  
  1391  	lock(&sched.lock)
  1392  	sched.safePointFn = nil
  1393  	unlock(&sched.lock)
  1394  	releasem(mp)
  1395  }
  1396  
  1397  // runSafePointFn runs the safe point function, if any, for this P.
  1398  // This should be called like
  1399  //
  1400  //     if getg().m.p.runSafePointFn != 0 {
  1401  //         runSafePointFn()
  1402  //     }
  1403  //
  1404  // runSafePointFn must be checked on any transition in to _Pidle or
  1405  // _Psyscall to avoid a race where forEachP sees that the P is running
  1406  // just before the P goes into _Pidle/_Psyscall and neither forEachP
  1407  // nor the P run the safe-point function.
  1408  func runSafePointFn() {
  1409  	p := getg().m.p.ptr()
  1410  	// Resolve the race between forEachP running the safe-point
  1411  	// function on this P's behalf and this P running the
  1412  	// safe-point function directly.
  1413  	if !atomic.Cas(&p.runSafePointFn, 1, 0) {
  1414  		return
  1415  	}
  1416  	sched.safePointFn(p)
  1417  	lock(&sched.lock)
  1418  	sched.safePointWait--
  1419  	if sched.safePointWait == 0 {
  1420  		notewakeup(&sched.safePointNote)
  1421  	}
  1422  	unlock(&sched.lock)
  1423  }
  1424  
  1425  // When running with cgo, we call _cgo_thread_start
  1426  // to start threads for us so that we can play nicely with
  1427  // foreign code.
  1428  var cgoThreadStart unsafe.Pointer
  1429  
  1430  type cgothreadstart struct {
  1431  	g   guintptr
  1432  	tls *uint64
  1433  	fn  unsafe.Pointer
  1434  }
  1435  
  1436  // Allocate a new m unassociated with any thread.
  1437  // Can use p for allocation context if needed.
  1438  // fn is recorded as the new m's m.mstartfn.
  1439  // id is optional pre-allocated m ID. Omit by passing -1.
  1440  //
  1441  // This function is allowed to have write barriers even if the caller
  1442  // isn't because it borrows _p_.
  1443  //
  1444  //go:yeswritebarrierrec
  1445  func allocm(_p_ *p, fn func(), id int64) *m {
  1446  	_g_ := getg()
  1447  	acquirem() // disable GC because it can be called from sysmon
  1448  	if _g_.m.p == 0 {
  1449  		acquirep(_p_) // temporarily borrow p for mallocs in this function
  1450  	}
  1451  
  1452  	// Release the free M list. We need to do this somewhere and
  1453  	// this may free up a stack we can use.
  1454  	if sched.freem != nil {
  1455  		lock(&sched.lock)
  1456  		var newList *m
  1457  		for freem := sched.freem; freem != nil; {
  1458  			if freem.freeWait != 0 {
  1459  				next := freem.freelink
  1460  				freem.freelink = newList
  1461  				newList = freem
  1462  				freem = next
  1463  				continue
  1464  			}
  1465  			stackfree(freem.g0.stack)
  1466  			freem = freem.freelink
  1467  		}
  1468  		sched.freem = newList
  1469  		unlock(&sched.lock)
  1470  	}
  1471  
  1472  	mp := new(m)
  1473  	mp.mstartfn = fn
  1474  	mcommoninit(mp, id)
  1475  
  1476  	// In case of cgo or Solaris or illumos or Darwin, pthread_create will make us a stack.
  1477  	// Windows and Plan 9 will layout sched stack on OS stack.
  1478  	if iscgo || GOOS == "solaris" || GOOS == "illumos" || GOOS == "windows" || GOOS == "plan9" || GOOS == "darwin" {
  1479  		mp.g0 = malg(-1)
  1480  	} else {
  1481  		mp.g0 = malg(8192 * sys.StackGuardMultiplier)
  1482  	}
  1483  	mp.g0.m = mp
  1484  
  1485  	if _p_ == _g_.m.p.ptr() {
  1486  		releasep()
  1487  	}
  1488  	releasem(_g_.m)
  1489  
  1490  	return mp
  1491  }
  1492  
  1493  // needm is called when a cgo callback happens on a
  1494  // thread without an m (a thread not created by Go).
  1495  // In this case, needm is expected to find an m to use
  1496  // and return with m, g initialized correctly.
  1497  // Since m and g are not set now (likely nil, but see below)
  1498  // needm is limited in what routines it can call. In particular
  1499  // it can only call nosplit functions (textflag 7) and cannot
  1500  // do any scheduling that requires an m.
  1501  //
  1502  // In order to avoid needing heavy lifting here, we adopt
  1503  // the following strategy: there is a stack of available m's
  1504  // that can be stolen. Using compare-and-swap
  1505  // to pop from the stack has ABA races, so we simulate
  1506  // a lock by doing an exchange (via Casuintptr) to steal the stack
  1507  // head and replace the top pointer with MLOCKED (1).
  1508  // This serves as a simple spin lock that we can use even
  1509  // without an m. The thread that locks the stack in this way
  1510  // unlocks the stack by storing a valid stack head pointer.
  1511  //
  1512  // In order to make sure that there is always an m structure
  1513  // available to be stolen, we maintain the invariant that there
  1514  // is always one more than needed. At the beginning of the
  1515  // program (if cgo is in use) the list is seeded with a single m.
  1516  // If needm finds that it has taken the last m off the list, its job
  1517  // is - once it has installed its own m so that it can do things like
  1518  // allocate memory - to create a spare m and put it on the list.
  1519  //
  1520  // Each of these extra m's also has a g0 and a curg that are
  1521  // pressed into service as the scheduling stack and current
  1522  // goroutine for the duration of the cgo callback.
  1523  //
  1524  // When the callback is done with the m, it calls dropm to
  1525  // put the m back on the list.
  1526  //go:nosplit
  1527  func needm(x byte) {
  1528  	if (iscgo || GOOS == "windows") && !cgoHasExtraM {
  1529  		// Can happen if C/C++ code calls Go from a global ctor.
  1530  		// Can also happen on Windows if a global ctor uses a
  1531  		// callback created by syscall.NewCallback. See issue #6751
  1532  		// for details.
  1533  		//
  1534  		// Can not throw, because scheduler is not initialized yet.
  1535  		write(2, unsafe.Pointer(&earlycgocallback[0]), int32(len(earlycgocallback)))
  1536  		exit(1)
  1537  	}
  1538  
  1539  	// Lock extra list, take head, unlock popped list.
  1540  	// nilokay=false is safe here because of the invariant above,
  1541  	// that the extra list always contains or will soon contain
  1542  	// at least one m.
  1543  	mp := lockextra(false)
  1544  
  1545  	// Set needextram when we've just emptied the list,
  1546  	// so that the eventual call into cgocallbackg will
  1547  	// allocate a new m for the extra list. We delay the
  1548  	// allocation until then so that it can be done
  1549  	// after exitsyscall makes sure it is okay to be
  1550  	// running at all (that is, there's no garbage collection
  1551  	// running right now).
  1552  	mp.needextram = mp.schedlink == 0
  1553  	extraMCount--
  1554  	unlockextra(mp.schedlink.ptr())
  1555  
  1556  	// Save and block signals before installing g.
  1557  	// Once g is installed, any incoming signals will try to execute,
  1558  	// but we won't have the sigaltstack settings and other data
  1559  	// set up appropriately until the end of minit, which will
  1560  	// unblock the signals. This is the same dance as when
  1561  	// starting a new m to run Go code via newosproc.
  1562  	msigsave(mp)
  1563  	sigblock()
  1564  
  1565  	// Install g (= m->g0) and set the stack bounds
  1566  	// to match the current stack. We don't actually know
  1567  	// how big the stack is, like we don't know how big any
  1568  	// scheduling stack is, but we assume there's at least 32 kB,
  1569  	// which is more than enough for us.
  1570  	setg(mp.g0)
  1571  	_g_ := getg()
  1572  	_g_.stack.hi = uintptr(noescape(unsafe.Pointer(&x))) + 1024
  1573  	_g_.stack.lo = uintptr(noescape(unsafe.Pointer(&x))) - 32*1024
  1574  	_g_.stackguard0 = _g_.stack.lo + _StackGuard
  1575  
  1576  	// Initialize this thread to use the m.
  1577  	asminit()
  1578  	minit()
  1579  
  1580  	// mp.curg is now a real goroutine.
  1581  	casgstatus(mp.curg, _Gdead, _Gsyscall)
  1582  	atomic.Xadd(&sched.ngsys, -1)
  1583  }
  1584  
  1585  var earlycgocallback = []byte("fatal error: cgo callback before cgo call\n")
  1586  
  1587  // newextram allocates m's and puts them on the extra list.
  1588  // It is called with a working local m, so that it can do things
  1589  // like call schedlock and allocate.
  1590  func newextram() {
  1591  	c := atomic.Xchg(&extraMWaiters, 0)
  1592  	if c > 0 {
  1593  		for i := uint32(0); i < c; i++ {
  1594  			oneNewExtraM()
  1595  		}
  1596  	} else {
  1597  		// Make sure there is at least one extra M.
  1598  		mp := lockextra(true)
  1599  		unlockextra(mp)
  1600  		if mp == nil {
  1601  			oneNewExtraM()
  1602  		}
  1603  	}
  1604  }
  1605  
  1606  // oneNewExtraM allocates an m and puts it on the extra list.
  1607  func oneNewExtraM() {
  1608  	// Create extra goroutine locked to extra m.
  1609  	// The goroutine is the context in which the cgo callback will run.
  1610  	// The sched.pc will never be returned to, but setting it to
  1611  	// goexit makes clear to the traceback routines where
  1612  	// the goroutine stack ends.
  1613  	mp := allocm(nil, nil, -1)
  1614  	gp := malg(4096)
  1615  	gp.sched.pc = funcPC(goexit) + sys.PCQuantum
  1616  	gp.sched.sp = gp.stack.hi
  1617  	gp.sched.sp -= 4 * sys.RegSize // extra space in case of reads slightly beyond frame
  1618  	gp.sched.lr = 0
  1619  	gp.sched.g = guintptr(unsafe.Pointer(gp))
  1620  	gp.syscallpc = gp.sched.pc
  1621  	gp.syscallsp = gp.sched.sp
  1622  	gp.stktopsp = gp.sched.sp
  1623  	// malg returns status as _Gidle. Change to _Gdead before
  1624  	// adding to allg where GC can see it. We use _Gdead to hide
  1625  	// this from tracebacks and stack scans since it isn't a
  1626  	// "real" goroutine until needm grabs it.
  1627  	casgstatus(gp, _Gidle, _Gdead)
  1628  	gp.m = mp
  1629  	mp.curg = gp
  1630  	mp.lockedInt++
  1631  	mp.lockedg.set(gp)
  1632  	gp.lockedm.set(mp)
  1633  	gp.goid = int64(atomic.Xadd64(&sched.goidgen, 1))
  1634  	if raceenabled {
  1635  		gp.racectx = racegostart(funcPC(newextram) + sys.PCQuantum)
  1636  	}
  1637  	// put on allg for garbage collector
  1638  	allgadd(gp)
  1639  
  1640  	// gp is now on the allg list, but we don't want it to be
  1641  	// counted by gcount. It would be more "proper" to increment
  1642  	// sched.ngfree, but that requires locking. Incrementing ngsys
  1643  	// has the same effect.
  1644  	atomic.Xadd(&sched.ngsys, +1)
  1645  
  1646  	// Add m to the extra list.
  1647  	mnext := lockextra(true)
  1648  	mp.schedlink.set(mnext)
  1649  	extraMCount++
  1650  	unlockextra(mp)
  1651  }
  1652  
  1653  // dropm is called when a cgo callback has called needm but is now
  1654  // done with the callback and returning back into the non-Go thread.
  1655  // It puts the current m back onto the extra list.
  1656  //
  1657  // The main expense here is the call to signalstack to release the
  1658  // m's signal stack, and then the call to needm on the next callback
  1659  // from this thread. It is tempting to try to save the m for next time,
  1660  // which would eliminate both these costs, but there might not be
  1661  // a next time: the current thread (which Go does not control) might exit.
  1662  // If we saved the m for that thread, there would be an m leak each time
  1663  // such a thread exited. Instead, we acquire and release an m on each
  1664  // call. These should typically not be scheduling operations, just a few
  1665  // atomics, so the cost should be small.
  1666  //
  1667  // TODO(rsc): An alternative would be to allocate a dummy pthread per-thread
  1668  // variable using pthread_key_create. Unlike the pthread keys we already use
  1669  // on OS X, this dummy key would never be read by Go code. It would exist
  1670  // only so that we could register at thread-exit-time destructor.
  1671  // That destructor would put the m back onto the extra list.
  1672  // This is purely a performance optimization. The current version,
  1673  // in which dropm happens on each cgo call, is still correct too.
  1674  // We may have to keep the current version on systems with cgo
  1675  // but without pthreads, like Windows.
  1676  func dropm() {
  1677  	// Clear m and g, and return m to the extra list.
  1678  	// After the call to setg we can only call nosplit functions
  1679  	// with no pointer manipulation.
  1680  	mp := getg().m
  1681  
  1682  	// Return mp.curg to dead state.
  1683  	casgstatus(mp.curg, _Gsyscall, _Gdead)
  1684  	mp.curg.preemptStop = false
  1685  	atomic.Xadd(&sched.ngsys, +1)
  1686  
  1687  	// Block signals before unminit.
  1688  	// Unminit unregisters the signal handling stack (but needs g on some systems).
  1689  	// Setg(nil) clears g, which is the signal handler's cue not to run Go handlers.
  1690  	// It's important not to try to handle a signal between those two steps.
  1691  	sigmask := mp.sigmask
  1692  	sigblock()
  1693  	unminit()
  1694  
  1695  	mnext := lockextra(true)
  1696  	extraMCount++
  1697  	mp.schedlink.set(mnext)
  1698  
  1699  	setg(nil)
  1700  
  1701  	// Commit the release of mp.
  1702  	unlockextra(mp)
  1703  
  1704  	msigrestore(sigmask)
  1705  }
  1706  
  1707  // A helper function for EnsureDropM.
  1708  func getm() uintptr {
  1709  	return uintptr(unsafe.Pointer(getg().m))
  1710  }
  1711  
  1712  var extram uintptr
  1713  var extraMCount uint32 // Protected by lockextra
  1714  var extraMWaiters uint32
  1715  
  1716  // lockextra locks the extra list and returns the list head.
  1717  // The caller must unlock the list by storing a new list head
  1718  // to extram. If nilokay is true, then lockextra will
  1719  // return a nil list head if that's what it finds. If nilokay is false,
  1720  // lockextra will keep waiting until the list head is no longer nil.
  1721  //go:nosplit
  1722  func lockextra(nilokay bool) *m {
  1723  	const locked = 1
  1724  
  1725  	incr := false
  1726  	for {
  1727  		old := atomic.Loaduintptr(&extram)
  1728  		if old == locked {
  1729  			osyield()
  1730  			continue
  1731  		}
  1732  		if old == 0 && !nilokay {
  1733  			if !incr {
  1734  				// Add 1 to the number of threads
  1735  				// waiting for an M.
  1736  				// This is cleared by newextram.
  1737  				atomic.Xadd(&extraMWaiters, 1)
  1738  				incr = true
  1739  			}
  1740  			usleep(1)
  1741  			continue
  1742  		}
  1743  		if atomic.Casuintptr(&extram, old, locked) {
  1744  			return (*m)(unsafe.Pointer(old))
  1745  		}
  1746  		osyield()
  1747  		continue
  1748  	}
  1749  }
  1750  
  1751  //go:nosplit
  1752  func unlockextra(mp *m) {
  1753  	atomic.Storeuintptr(&extram, uintptr(unsafe.Pointer(mp)))
  1754  }
  1755  
  1756  // execLock serializes exec and clone to avoid bugs or unspecified behaviour
  1757  // around exec'ing while creating/destroying threads.  See issue #19546.
  1758  var execLock rwmutex
  1759  
  1760  // newmHandoff contains a list of m structures that need new OS threads.
  1761  // This is used by newm in situations where newm itself can't safely
  1762  // start an OS thread.
  1763  var newmHandoff struct {
  1764  	lock mutex
  1765  
  1766  	// newm points to a list of M structures that need new OS
  1767  	// threads. The list is linked through m.schedlink.
  1768  	newm muintptr
  1769  
  1770  	// waiting indicates that wake needs to be notified when an m
  1771  	// is put on the list.
  1772  	waiting bool
  1773  	wake    note
  1774  
  1775  	// haveTemplateThread indicates that the templateThread has
  1776  	// been started. This is not protected by lock. Use cas to set
  1777  	// to 1.
  1778  	haveTemplateThread uint32
  1779  }
  1780  
  1781  // Create a new m. It will start off with a call to fn, or else the scheduler.
  1782  // fn needs to be static and not a heap allocated closure.
  1783  // May run with m.p==nil, so write barriers are not allowed.
  1784  //
  1785  // id is optional pre-allocated m ID. Omit by passing -1.
  1786  //go:nowritebarrierrec
  1787  func newm(fn func(), _p_ *p, id int64) {
  1788  	mp := allocm(_p_, fn, id)
  1789  	mp.nextp.set(_p_)
  1790  	mp.sigmask = initSigmask
  1791  	if gp := getg(); gp != nil && gp.m != nil && (gp.m.lockedExt != 0 || gp.m.incgo) && GOOS != "plan9" {
  1792  		// We're on a locked M or a thread that may have been
  1793  		// started by C. The kernel state of this thread may
  1794  		// be strange (the user may have locked it for that
  1795  		// purpose). We don't want to clone that into another
  1796  		// thread. Instead, ask a known-good thread to create
  1797  		// the thread for us.
  1798  		//
  1799  		// This is disabled on Plan 9. See golang.org/issue/22227.
  1800  		//
  1801  		// TODO: This may be unnecessary on Windows, which
  1802  		// doesn't model thread creation off fork.
  1803  		lock(&newmHandoff.lock)
  1804  		if newmHandoff.haveTemplateThread == 0 {
  1805  			throw("on a locked thread with no template thread")
  1806  		}
  1807  		mp.schedlink = newmHandoff.newm
  1808  		newmHandoff.newm.set(mp)
  1809  		if newmHandoff.waiting {
  1810  			newmHandoff.waiting = false
  1811  			notewakeup(&newmHandoff.wake)
  1812  		}
  1813  		unlock(&newmHandoff.lock)
  1814  		return
  1815  	}
  1816  	newm1(mp)
  1817  }
  1818  
  1819  func newm1(mp *m) {
  1820  	if iscgo {
  1821  		var ts cgothreadstart
  1822  		if _cgo_thread_start == nil {
  1823  			throw("_cgo_thread_start missing")
  1824  		}
  1825  		ts.g.set(mp.g0)
  1826  		ts.tls = (*uint64)(unsafe.Pointer(&mp.tls[0]))
  1827  		ts.fn = unsafe.Pointer(funcPC(mstart))
  1828  		if msanenabled {
  1829  			msanwrite(unsafe.Pointer(&ts), unsafe.Sizeof(ts))
  1830  		}
  1831  		execLock.rlock() // Prevent process clone.
  1832  		asmcgocall(_cgo_thread_start, unsafe.Pointer(&ts))
  1833  		execLock.runlock()
  1834  		return
  1835  	}
  1836  	execLock.rlock() // Prevent process clone.
  1837  	newosproc(mp)
  1838  	execLock.runlock()
  1839  }
  1840  
  1841  // startTemplateThread starts the template thread if it is not already
  1842  // running.
  1843  //
  1844  // The calling thread must itself be in a known-good state.
  1845  func startTemplateThread() {
  1846  	if GOARCH == "wasm" { // no threads on wasm yet
  1847  		return
  1848  	}
  1849  
  1850  	// Disable preemption to guarantee that the template thread will be
  1851  	// created before a park once haveTemplateThread is set.
  1852  	mp := acquirem()
  1853  	if !atomic.Cas(&newmHandoff.haveTemplateThread, 0, 1) {
  1854  		releasem(mp)
  1855  		return
  1856  	}
  1857  	newm(templateThread, nil, -1)
  1858  	releasem(mp)
  1859  }
  1860  
  1861  // templateThread is a thread in a known-good state that exists solely
  1862  // to start new threads in known-good states when the calling thread
  1863  // may not be in a good state.
  1864  //
  1865  // Many programs never need this, so templateThread is started lazily
  1866  // when we first enter a state that might lead to running on a thread
  1867  // in an unknown state.
  1868  //
  1869  // templateThread runs on an M without a P, so it must not have write
  1870  // barriers.
  1871  //
  1872  //go:nowritebarrierrec
  1873  func templateThread() {
  1874  	lock(&sched.lock)
  1875  	sched.nmsys++
  1876  	checkdead()
  1877  	unlock(&sched.lock)
  1878  
  1879  	for {
  1880  		lock(&newmHandoff.lock)
  1881  		for newmHandoff.newm != 0 {
  1882  			newm := newmHandoff.newm.ptr()
  1883  			newmHandoff.newm = 0
  1884  			unlock(&newmHandoff.lock)
  1885  			for newm != nil {
  1886  				next := newm.schedlink.ptr()
  1887  				newm.schedlink = 0
  1888  				newm1(newm)
  1889  				newm = next
  1890  			}
  1891  			lock(&newmHandoff.lock)
  1892  		}
  1893  		newmHandoff.waiting = true
  1894  		noteclear(&newmHandoff.wake)
  1895  		unlock(&newmHandoff.lock)
  1896  		notesleep(&newmHandoff.wake)
  1897  	}
  1898  }
  1899  
  1900  // Stops execution of the current m until new work is available.
  1901  // Returns with acquired P.
  1902  func stopm() {
  1903  	_g_ := getg()
  1904  
  1905  	if _g_.m.locks != 0 {
  1906  		throw("stopm holding locks")
  1907  	}
  1908  	if _g_.m.p != 0 {
  1909  		throw("stopm holding p")
  1910  	}
  1911  	if _g_.m.spinning {
  1912  		throw("stopm spinning")
  1913  	}
  1914  
  1915  	lock(&sched.lock)
  1916  	mput(_g_.m)
  1917  	unlock(&sched.lock)
  1918  	notesleep(&_g_.m.park)
  1919  	noteclear(&_g_.m.park)
  1920  	acquirep(_g_.m.nextp.ptr())
  1921  	_g_.m.nextp = 0
  1922  }
  1923  
  1924  func mspinning() {
  1925  	// startm's caller incremented nmspinning. Set the new M's spinning.
  1926  	getg().m.spinning = true
  1927  }
  1928  
  1929  // Schedules some M to run the p (creates an M if necessary).
  1930  // If p==nil, tries to get an idle P, if no idle P's does nothing.
  1931  // May run with m.p==nil, so write barriers are not allowed.
  1932  // If spinning is set, the caller has incremented nmspinning and startm will
  1933  // either decrement nmspinning or set m.spinning in the newly started M.
  1934  //go:nowritebarrierrec
  1935  func startm(_p_ *p, spinning bool) {
  1936  	lock(&sched.lock)
  1937  	if _p_ == nil {
  1938  		_p_ = pidleget()
  1939  		if _p_ == nil {
  1940  			unlock(&sched.lock)
  1941  			if spinning {
  1942  				// The caller incremented nmspinning, but there are no idle Ps,
  1943  				// so it's okay to just undo the increment and give up.
  1944  				if int32(atomic.Xadd(&sched.nmspinning, -1)) < 0 {
  1945  					throw("startm: negative nmspinning")
  1946  				}
  1947  			}
  1948  			return
  1949  		}
  1950  	}
  1951  	mp := mget()
  1952  	if mp == nil {
  1953  		// No M is available, we must drop sched.lock and call newm.
  1954  		// However, we already own a P to assign to the M.
  1955  		//
  1956  		// Once sched.lock is released, another G (e.g., in a syscall),
  1957  		// could find no idle P while checkdead finds a runnable G but
  1958  		// no running M's because this new M hasn't started yet, thus
  1959  		// throwing in an apparent deadlock.
  1960  		//
  1961  		// Avoid this situation by pre-allocating the ID for the new M,
  1962  		// thus marking it as 'running' before we drop sched.lock. This
  1963  		// new M will eventually run the scheduler to execute any
  1964  		// queued G's.
  1965  		id := mReserveID()
  1966  		unlock(&sched.lock)
  1967  
  1968  		var fn func()
  1969  		if spinning {
  1970  			// The caller incremented nmspinning, so set m.spinning in the new M.
  1971  			fn = mspinning
  1972  		}
  1973  		newm(fn, _p_, id)
  1974  		return
  1975  	}
  1976  	unlock(&sched.lock)
  1977  	if mp.spinning {
  1978  		throw("startm: m is spinning")
  1979  	}
  1980  	if mp.nextp != 0 {
  1981  		throw("startm: m has p")
  1982  	}
  1983  	if spinning && !runqempty(_p_) {
  1984  		throw("startm: p has runnable gs")
  1985  	}
  1986  	// The caller incremented nmspinning, so set m.spinning in the new M.
  1987  	mp.spinning = spinning
  1988  	mp.nextp.set(_p_)
  1989  	notewakeup(&mp.park)
  1990  }
  1991  
  1992  // Hands off P from syscall or locked M.
  1993  // Always runs without a P, so write barriers are not allowed.
  1994  //go:nowritebarrierrec
  1995  func handoffp(_p_ *p) {
  1996  	// handoffp must start an M in any situation where
  1997  	// findrunnable would return a G to run on _p_.
  1998  
  1999  	// if it has local work, start it straight away
  2000  	if !runqempty(_p_) || sched.runqsize != 0 {
  2001  		startm(_p_, false)
  2002  		return
  2003  	}
  2004  	// if it has GC work, start it straight away
  2005  	if gcBlackenEnabled != 0 && gcMarkWorkAvailable(_p_) {
  2006  		startm(_p_, false)
  2007  		return
  2008  	}
  2009  	// no local work, check that there are no spinning/idle M's,
  2010  	// otherwise our help is not required
  2011  	if atomic.Load(&sched.nmspinning)+atomic.Load(&sched.npidle) == 0 && atomic.Cas(&sched.nmspinning, 0, 1) { // TODO: fast atomic
  2012  		startm(_p_, true)
  2013  		return
  2014  	}
  2015  	lock(&sched.lock)
  2016  	if sched.gcwaiting != 0 {
  2017  		_p_.status = _Pgcstop
  2018  		sched.stopwait--
  2019  		if sched.stopwait == 0 {
  2020  			notewakeup(&sched.stopnote)
  2021  		}
  2022  		unlock(&sched.lock)
  2023  		return
  2024  	}
  2025  	if _p_.runSafePointFn != 0 && atomic.Cas(&_p_.runSafePointFn, 1, 0) {
  2026  		sched.safePointFn(_p_)
  2027  		sched.safePointWait--
  2028  		if sched.safePointWait == 0 {
  2029  			notewakeup(&sched.safePointNote)
  2030  		}
  2031  	}
  2032  	if sched.runqsize != 0 {
  2033  		unlock(&sched.lock)
  2034  		startm(_p_, false)
  2035  		return
  2036  	}
  2037  	// If this is the last running P and nobody is polling network,
  2038  	// need to wakeup another M to poll network.
  2039  	if sched.npidle == uint32(gomaxprocs-1) && atomic.Load64(&sched.lastpoll) != 0 {
  2040  		unlock(&sched.lock)
  2041  		startm(_p_, false)
  2042  		return
  2043  	}
  2044  	if when := nobarrierWakeTime(_p_); when != 0 {
  2045  		wakeNetPoller(when)
  2046  	}
  2047  	pidleput(_p_)
  2048  	unlock(&sched.lock)
  2049  }
  2050  
  2051  // Tries to add one more P to execute G's.
  2052  // Called when a G is made runnable (newproc, ready).
  2053  func wakep() {
  2054  	if atomic.Load(&sched.npidle) == 0 {
  2055  		return
  2056  	}
  2057  	// be conservative about spinning threads
  2058  	if atomic.Load(&sched.nmspinning) != 0 || !atomic.Cas(&sched.nmspinning, 0, 1) {
  2059  		return
  2060  	}
  2061  	startm(nil, true)
  2062  }
  2063  
  2064  // Stops execution of the current m that is locked to a g until the g is runnable again.
  2065  // Returns with acquired P.
  2066  func stoplockedm() {
  2067  	_g_ := getg()
  2068  
  2069  	if _g_.m.lockedg == 0 || _g_.m.lockedg.ptr().lockedm.ptr() != _g_.m {
  2070  		throw("stoplockedm: inconsistent locking")
  2071  	}
  2072  	if _g_.m.p != 0 {
  2073  		// Schedule another M to run this p.
  2074  		_p_ := releasep()
  2075  		handoffp(_p_)
  2076  	}
  2077  	incidlelocked(1)
  2078  	// Wait until another thread schedules lockedg again.
  2079  	notesleep(&_g_.m.park)
  2080  	noteclear(&_g_.m.park)
  2081  	status := readgstatus(_g_.m.lockedg.ptr())
  2082  	if status&^_Gscan != _Grunnable {
  2083  		print("runtime:stoplockedm: g is not Grunnable or Gscanrunnable\n")
  2084  		dumpgstatus(_g_)
  2085  		throw("stoplockedm: not runnable")
  2086  	}
  2087  	acquirep(_g_.m.nextp.ptr())
  2088  	_g_.m.nextp = 0
  2089  }
  2090  
  2091  // Schedules the locked m to run the locked gp.
  2092  // May run during STW, so write barriers are not allowed.
  2093  //go:nowritebarrierrec
  2094  func startlockedm(gp *g) {
  2095  	_g_ := getg()
  2096  
  2097  	mp := gp.lockedm.ptr()
  2098  	if mp == _g_.m {
  2099  		throw("startlockedm: locked to me")
  2100  	}
  2101  	if mp.nextp != 0 {
  2102  		throw("startlockedm: m has p")
  2103  	}
  2104  	// directly handoff current P to the locked m
  2105  	incidlelocked(-1)
  2106  	_p_ := releasep()
  2107  	mp.nextp.set(_p_)
  2108  	notewakeup(&mp.park)
  2109  	stopm()
  2110  }
  2111  
  2112  // Stops the current m for stopTheWorld.
  2113  // Returns when the world is restarted.
  2114  func gcstopm() {
  2115  	_g_ := getg()
  2116  
  2117  	if sched.gcwaiting == 0 {
  2118  		throw("gcstopm: not waiting for gc")
  2119  	}
  2120  	if _g_.m.spinning {
  2121  		_g_.m.spinning = false
  2122  		// OK to just drop nmspinning here,
  2123  		// startTheWorld will unpark threads as necessary.
  2124  		if int32(atomic.Xadd(&sched.nmspinning, -1)) < 0 {
  2125  			throw("gcstopm: negative nmspinning")
  2126  		}
  2127  	}
  2128  	_p_ := releasep()
  2129  	lock(&sched.lock)
  2130  	_p_.status = _Pgcstop
  2131  	sched.stopwait--
  2132  	if sched.stopwait == 0 {
  2133  		notewakeup(&sched.stopnote)
  2134  	}
  2135  	unlock(&sched.lock)
  2136  	stopm()
  2137  }
  2138  
  2139  // Schedules gp to run on the current M.
  2140  // If inheritTime is true, gp inherits the remaining time in the
  2141  // current time slice. Otherwise, it starts a new time slice.
  2142  // Never returns.
  2143  //
  2144  // Write barriers are allowed because this is called immediately after
  2145  // acquiring a P in several places.
  2146  //
  2147  //go:yeswritebarrierrec
  2148  func execute(gp *g, inheritTime bool) {
  2149  	_g_ := getg()
  2150  
  2151  	// Assign gp.m before entering _Grunning so running Gs have an
  2152  	// M.
  2153  	_g_.m.curg = gp
  2154  	gp.m = _g_.m
  2155  	casgstatus(gp, _Grunnable, _Grunning)
  2156  	gp.waitsince = 0
  2157  	gp.preempt = false
  2158  	gp.stackguard0 = gp.stack.lo + _StackGuard
  2159  	if !inheritTime {
  2160  		_g_.m.p.ptr().schedtick++
  2161  	}
  2162  
  2163  	// Check whether the profiler needs to be turned on or off.
  2164  	hz := sched.profilehz
  2165  	if _g_.m.profilehz != hz {
  2166  		setThreadCPUProfiler(hz)
  2167  	}
  2168  
  2169  	if trace.enabled {
  2170  		// GoSysExit has to happen when we have a P, but before GoStart.
  2171  		// So we emit it here.
  2172  		if gp.syscallsp != 0 && gp.sysblocktraced {
  2173  			traceGoSysExit(gp.sysexitticks)
  2174  		}
  2175  		traceGoStart()
  2176  	}
  2177  
  2178  	gogo(&gp.sched)
  2179  }
  2180  
  2181  // Finds a runnable goroutine to execute.
  2182  // Tries to steal from other P's, get g from local or global queue, poll network.
  2183  func findrunnable() (gp *g, inheritTime bool) {
  2184  	_g_ := getg()
  2185  
  2186  	// The conditions here and in handoffp must agree: if
  2187  	// findrunnable would return a G to run, handoffp must start
  2188  	// an M.
  2189  
  2190  top:
  2191  	_p_ := _g_.m.p.ptr()
  2192  	if sched.gcwaiting != 0 {
  2193  		gcstopm()
  2194  		goto top
  2195  	}
  2196  	if _p_.runSafePointFn != 0 {
  2197  		runSafePointFn()
  2198  	}
  2199  
  2200  	now, pollUntil, _ := checkTimers(_p_, 0)
  2201  
  2202  	if fingwait && fingwake {
  2203  		if gp := wakefing(); gp != nil {
  2204  			ready(gp, 0, true)
  2205  		}
  2206  	}
  2207  	if *cgo_yield != nil {
  2208  		asmcgocall(*cgo_yield, nil)
  2209  	}
  2210  
  2211  	// local runq
  2212  	if gp, inheritTime := runqget(_p_); gp != nil {
  2213  		return gp, inheritTime
  2214  	}
  2215  
  2216  	// global runq
  2217  	if sched.runqsize != 0 {
  2218  		lock(&sched.lock)
  2219  		gp := globrunqget(_p_, 0)
  2220  		unlock(&sched.lock)
  2221  		if gp != nil {
  2222  			return gp, false
  2223  		}
  2224  	}
  2225  
  2226  	// Poll network.
  2227  	// This netpoll is only an optimization before we resort to stealing.
  2228  	// We can safely skip it if there are no waiters or a thread is blocked
  2229  	// in netpoll already. If there is any kind of logical race with that
  2230  	// blocked thread (e.g. it has already returned from netpoll, but does
  2231  	// not set lastpoll yet), this thread will do blocking netpoll below
  2232  	// anyway.
  2233  	if netpollinited() && atomic.Load(&netpollWaiters) > 0 && atomic.Load64(&sched.lastpoll) != 0 {
  2234  		if list := netpoll(0); !list.empty() { // non-blocking
  2235  			gp := list.pop()
  2236  			injectglist(&list)
  2237  			casgstatus(gp, _Gwaiting, _Grunnable)
  2238  			if trace.enabled {
  2239  				traceGoUnpark(gp, 0)
  2240  			}
  2241  			return gp, false
  2242  		}
  2243  	}
  2244  
  2245  	// Steal work from other P's.
  2246  	procs := uint32(gomaxprocs)
  2247  	ranTimer := false
  2248  	// If number of spinning M's >= number of busy P's, block.
  2249  	// This is necessary to prevent excessive CPU consumption
  2250  	// when GOMAXPROCS>>1 but the program parallelism is low.
  2251  	if !_g_.m.spinning && 2*atomic.Load(&sched.nmspinning) >= procs-atomic.Load(&sched.npidle) {
  2252  		goto stop
  2253  	}
  2254  	if !_g_.m.spinning {
  2255  		_g_.m.spinning = true
  2256  		atomic.Xadd(&sched.nmspinning, 1)
  2257  	}
  2258  	for i := 0; i < 4; i++ {
  2259  		for enum := stealOrder.start(fastrand()); !enum.done(); enum.next() {
  2260  			if sched.gcwaiting != 0 {
  2261  				goto top
  2262  			}
  2263  			stealRunNextG := i > 2 // first look for ready queues with more than 1 g
  2264  			p2 := allp[enum.position()]
  2265  			if _p_ == p2 {
  2266  				continue
  2267  			}
  2268  			if gp := runqsteal(_p_, p2, stealRunNextG); gp != nil {
  2269  				return gp, false
  2270  			}
  2271  
  2272  			// Consider stealing timers from p2.
  2273  			// This call to checkTimers is the only place where
  2274  			// we hold a lock on a different P's timers.
  2275  			// Lock contention can be a problem here, so
  2276  			// initially avoid grabbing the lock if p2 is running
  2277  			// and is not marked for preemption. If p2 is running
  2278  			// and not being preempted we assume it will handle its
  2279  			// own timers.
  2280  			// If we're still looking for work after checking all
  2281  			// the P's, then go ahead and steal from an active P.
  2282  			if i > 2 || (i > 1 && shouldStealTimers(p2)) {
  2283  				tnow, w, ran := checkTimers(p2, now)
  2284  				now = tnow
  2285  				if w != 0 && (pollUntil == 0 || w < pollUntil) {
  2286  					pollUntil = w
  2287  				}
  2288  				if ran {
  2289  					// Running the timers may have
  2290  					// made an arbitrary number of G's
  2291  					// ready and added them to this P's
  2292  					// local run queue. That invalidates
  2293  					// the assumption of runqsteal
  2294  					// that is always has room to add
  2295  					// stolen G's. So check now if there
  2296  					// is a local G to run.
  2297  					if gp, inheritTime := runqget(_p_); gp != nil {
  2298  						return gp, inheritTime
  2299  					}
  2300  					ranTimer = true
  2301  				}
  2302  			}
  2303  		}
  2304  	}
  2305  	if ranTimer {
  2306  		// Running a timer may have made some goroutine ready.
  2307  		goto top
  2308  	}
  2309  
  2310  stop:
  2311  
  2312  	// We have nothing to do. If we're in the GC mark phase, can
  2313  	// safely scan and blacken objects, and have work to do, run
  2314  	// idle-time marking rather than give up the P.
  2315  	if gcBlackenEnabled != 0 && _p_.gcBgMarkWorker != 0 && gcMarkWorkAvailable(_p_) {
  2316  		_p_.gcMarkWorkerMode = gcMarkWorkerIdleMode
  2317  		gp := _p_.gcBgMarkWorker.ptr()
  2318  		casgstatus(gp, _Gwaiting, _Grunnable)
  2319  		if trace.enabled {
  2320  			traceGoUnpark(gp, 0)
  2321  		}
  2322  		return gp, false
  2323  	}
  2324  
  2325  	delta := int64(-1)
  2326  	if pollUntil != 0 {
  2327  		// checkTimers ensures that polluntil > now.
  2328  		delta = pollUntil - now
  2329  	}
  2330  
  2331  	// wasm only:
  2332  	// If a callback returned and no other goroutine is awake,
  2333  	// then wake event handler goroutine which pauses execution
  2334  	// until a callback was triggered.
  2335  	gp, otherReady := beforeIdle(delta)
  2336  	if gp != nil {
  2337  		casgstatus(gp, _Gwaiting, _Grunnable)
  2338  		if trace.enabled {
  2339  			traceGoUnpark(gp, 0)
  2340  		}
  2341  		return gp, false
  2342  	}
  2343  	if otherReady {
  2344  		goto top
  2345  	}
  2346  
  2347  	// Before we drop our P, make a snapshot of the allp slice,
  2348  	// which can change underfoot once we no longer block
  2349  	// safe-points. We don't need to snapshot the contents because
  2350  	// everything up to cap(allp) is immutable.
  2351  	allpSnapshot := allp
  2352  
  2353  	// return P and block
  2354  	lock(&sched.lock)
  2355  	if sched.gcwaiting != 0 || _p_.runSafePointFn != 0 {
  2356  		unlock(&sched.lock)
  2357  		goto top
  2358  	}
  2359  	if sched.runqsize != 0 {
  2360  		gp := globrunqget(_p_, 0)
  2361  		unlock(&sched.lock)
  2362  		return gp, false
  2363  	}
  2364  	if releasep() != _p_ {
  2365  		throw("findrunnable: wrong p")
  2366  	}
  2367  	pidleput(_p_)
  2368  	unlock(&sched.lock)
  2369  
  2370  	// Delicate dance: thread transitions from spinning to non-spinning state,
  2371  	// potentially concurrently with submission of new goroutines. We must
  2372  	// drop nmspinning first and then check all per-P queues again (with
  2373  	// #StoreLoad memory barrier in between). If we do it the other way around,
  2374  	// another thread can submit a goroutine after we've checked all run queues
  2375  	// but before we drop nmspinning; as the result nobody will unpark a thread
  2376  	// to run the goroutine.
  2377  	// If we discover new work below, we need to restore m.spinning as a signal
  2378  	// for resetspinning to unpark a new worker thread (because there can be more
  2379  	// than one starving goroutine). However, if after discovering new work
  2380  	// we also observe no idle Ps, it is OK to just park the current thread:
  2381  	// the system is fully loaded so no spinning threads are required.
  2382  	// Also see "Worker thread parking/unparking" comment at the top of the file.
  2383  	wasSpinning := _g_.m.spinning
  2384  	if _g_.m.spinning {
  2385  		_g_.m.spinning = false
  2386  		if int32(atomic.Xadd(&sched.nmspinning, -1)) < 0 {
  2387  			throw("findrunnable: negative nmspinning")
  2388  		}
  2389  	}
  2390  
  2391  	// check all runqueues once again
  2392  	for _, _p_ := range allpSnapshot {
  2393  		if !runqempty(_p_) {
  2394  			lock(&sched.lock)
  2395  			_p_ = pidleget()
  2396  			unlock(&sched.lock)
  2397  			if _p_ != nil {
  2398  				acquirep(_p_)
  2399  				if wasSpinning {
  2400  					_g_.m.spinning = true
  2401  					atomic.Xadd(&sched.nmspinning, 1)
  2402  				}
  2403  				goto top
  2404  			}
  2405  			break
  2406  		}
  2407  	}
  2408  
  2409  	// Check for idle-priority GC work again.
  2410  	if gcBlackenEnabled != 0 && gcMarkWorkAvailable(nil) {
  2411  		lock(&sched.lock)
  2412  		_p_ = pidleget()
  2413  		if _p_ != nil && _p_.gcBgMarkWorker == 0 {
  2414  			pidleput(_p_)
  2415  			_p_ = nil
  2416  		}
  2417  		unlock(&sched.lock)
  2418  		if _p_ != nil {
  2419  			acquirep(_p_)
  2420  			if wasSpinning {
  2421  				_g_.m.spinning = true
  2422  				atomic.Xadd(&sched.nmspinning, 1)
  2423  			}
  2424  			// Go back to idle GC check.
  2425  			goto stop
  2426  		}
  2427  	}
  2428  
  2429  	// poll network
  2430  	if netpollinited() && (atomic.Load(&netpollWaiters) > 0 || pollUntil != 0) && atomic.Xchg64(&sched.lastpoll, 0) != 0 {
  2431  		atomic.Store64(&sched.pollUntil, uint64(pollUntil))
  2432  		if _g_.m.p != 0 {
  2433  			throw("findrunnable: netpoll with p")
  2434  		}
  2435  		if _g_.m.spinning {
  2436  			throw("findrunnable: netpoll with spinning")
  2437  		}
  2438  		if faketime != 0 {
  2439  			// When using fake time, just poll.
  2440  			delta = 0
  2441  		}
  2442  		list := netpoll(delta) // block until new work is available
  2443  		atomic.Store64(&sched.pollUntil, 0)
  2444  		atomic.Store64(&sched.lastpoll, uint64(nanotime()))
  2445  		if faketime != 0 && list.empty() {
  2446  			// Using fake time and nothing is ready; stop M.
  2447  			// When all M's stop, checkdead will call timejump.
  2448  			stopm()
  2449  			goto top
  2450  		}
  2451  		lock(&sched.lock)
  2452  		_p_ = pidleget()
  2453  		unlock(&sched.lock)
  2454  		if _p_ == nil {
  2455  			injectglist(&list)
  2456  		} else {
  2457  			acquirep(_p_)
  2458  			if !list.empty() {
  2459  				gp := list.pop()
  2460  				injectglist(&list)
  2461  				casgstatus(gp, _Gwaiting, _Grunnable)
  2462  				if trace.enabled {
  2463  					traceGoUnpark(gp, 0)
  2464  				}
  2465  				return gp, false
  2466  			}
  2467  			if wasSpinning {
  2468  				_g_.m.spinning = true
  2469  				atomic.Xadd(&sched.nmspinning, 1)
  2470  			}
  2471  			goto top
  2472  		}
  2473  	} else if pollUntil != 0 && netpollinited() {
  2474  		pollerPollUntil := int64(atomic.Load64(&sched.pollUntil))
  2475  		if pollerPollUntil == 0 || pollerPollUntil > pollUntil {
  2476  			netpollBreak()
  2477  		}
  2478  	}
  2479  	stopm()
  2480  	goto top
  2481  }
  2482  
  2483  // pollWork reports whether there is non-background work this P could
  2484  // be doing. This is a fairly lightweight check to be used for
  2485  // background work loops, like idle GC. It checks a subset of the
  2486  // conditions checked by the actual scheduler.
  2487  func pollWork() bool {
  2488  	if sched.runqsize != 0 {
  2489  		return true
  2490  	}
  2491  	p := getg().m.p.ptr()
  2492  	if !runqempty(p) {
  2493  		return true
  2494  	}
  2495  	if netpollinited() && atomic.Load(&netpollWaiters) > 0 && sched.lastpoll != 0 {
  2496  		if list := netpoll(0); !list.empty() {
  2497  			injectglist(&list)
  2498  			return true
  2499  		}
  2500  	}
  2501  	return false
  2502  }
  2503  
  2504  // wakeNetPoller wakes up the thread sleeping in the network poller,
  2505  // if there is one, and if it isn't going to wake up anyhow before
  2506  // the when argument.
  2507  func wakeNetPoller(when int64) {
  2508  	if atomic.Load64(&sched.lastpoll) == 0 {
  2509  		// In findrunnable we ensure that when polling the pollUntil
  2510  		// field is either zero or the time to which the current
  2511  		// poll is expected to run. This can have a spurious wakeup
  2512  		// but should never miss a wakeup.
  2513  		pollerPollUntil := int64(atomic.Load64(&sched.pollUntil))
  2514  		if pollerPollUntil == 0 || pollerPollUntil > when {
  2515  			netpollBreak()
  2516  		}
  2517  	}
  2518  }
  2519  
  2520  func resetspinning() {
  2521  	_g_ := getg()
  2522  	if !_g_.m.spinning {
  2523  		throw("resetspinning: not a spinning m")
  2524  	}
  2525  	_g_.m.spinning = false
  2526  	nmspinning := atomic.Xadd(&sched.nmspinning, -1)
  2527  	if int32(nmspinning) < 0 {
  2528  		throw("findrunnable: negative nmspinning")
  2529  	}
  2530  	// M wakeup policy is deliberately somewhat conservative, so check if we
  2531  	// need to wakeup another P here. See "Worker thread parking/unparking"
  2532  	// comment at the top of the file for details.
  2533  	wakep()
  2534  }
  2535  
  2536  // injectglist adds each runnable G on the list to some run queue,
  2537  // and clears glist. If there is no current P, they are added to the
  2538  // global queue, and up to npidle M's are started to run them.
  2539  // Otherwise, for each idle P, this adds a G to the global queue
  2540  // and starts an M. Any remaining G's are added to the current P's
  2541  // local run queue.
  2542  // This may temporarily acquire the scheduler lock.
  2543  // Can run concurrently with GC.
  2544  func injectglist(glist *gList) {
  2545  	if glist.empty() {
  2546  		return
  2547  	}
  2548  	if trace.enabled {
  2549  		for gp := glist.head.ptr(); gp != nil; gp = gp.schedlink.ptr() {
  2550  			traceGoUnpark(gp, 0)
  2551  		}
  2552  	}
  2553  
  2554  	// Mark all the goroutines as runnable before we put them
  2555  	// on the run queues.
  2556  	head := glist.head.ptr()
  2557  	var tail *g
  2558  	qsize := 0
  2559  	for gp := head; gp != nil; gp = gp.schedlink.ptr() {
  2560  		tail = gp
  2561  		qsize++
  2562  		casgstatus(gp, _Gwaiting, _Grunnable)
  2563  	}
  2564  
  2565  	// Turn the gList into a gQueue.
  2566  	var q gQueue
  2567  	q.head.set(head)
  2568  	q.tail.set(tail)
  2569  	*glist = gList{}
  2570  
  2571  	startIdle := func(n int) {
  2572  		for ; n != 0 && sched.npidle != 0; n-- {
  2573  			startm(nil, false)
  2574  		}
  2575  	}
  2576  
  2577  	pp := getg().m.p.ptr()
  2578  	if pp == nil {
  2579  		lock(&sched.lock)
  2580  		globrunqputbatch(&q, int32(qsize))
  2581  		unlock(&sched.lock)
  2582  		startIdle(qsize)
  2583  		return
  2584  	}
  2585  
  2586  	lock(&sched.lock)
  2587  	npidle := int(sched.npidle)
  2588  	var n int
  2589  	for n = 0; n < npidle && !q.empty(); n++ {
  2590  		globrunqput(q.pop())
  2591  	}
  2592  	unlock(&sched.lock)
  2593  	startIdle(n)
  2594  	qsize -= n
  2595  
  2596  	if !q.empty() {
  2597  		runqputbatch(pp, &q, qsize)
  2598  	}
  2599  }
  2600  
  2601  // One round of scheduler: find a runnable goroutine and execute it.
  2602  // Never returns.
  2603  func schedule() {
  2604  	_g_ := getg()
  2605  
  2606  	if _g_.m.locks != 0 {
  2607  		throw("schedule: holding locks")
  2608  	}
  2609  
  2610  	if _g_.m.lockedg != 0 {
  2611  		stoplockedm()
  2612  		execute(_g_.m.lockedg.ptr(), false) // Never returns.
  2613  	}
  2614  
  2615  	// We should not schedule away from a g that is executing a cgo call,
  2616  	// since the cgo call is using the m's g0 stack.
  2617  	if _g_.m.incgo {
  2618  		throw("schedule: in cgo")
  2619  	}
  2620  
  2621  top:
  2622  	pp := _g_.m.p.ptr()
  2623  	pp.preempt = false
  2624  
  2625  	if sched.gcwaiting != 0 {
  2626  		gcstopm()
  2627  		goto top
  2628  	}
  2629  	if pp.runSafePointFn != 0 {
  2630  		runSafePointFn()
  2631  	}
  2632  
  2633  	// Sanity check: if we are spinning, the run queue should be empty.
  2634  	// Check this before calling checkTimers, as that might call
  2635  	// goready to put a ready goroutine on the local run queue.
  2636  	if _g_.m.spinning && (pp.runnext != 0 || pp.runqhead != pp.runqtail) {
  2637  		throw("schedule: spinning with local work")
  2638  	}
  2639  
  2640  	checkTimers(pp, 0)
  2641  
  2642  	var gp *g
  2643  	var inheritTime bool
  2644  
  2645  	// Normal goroutines will check for need to wakeP in ready,
  2646  	// but GCworkers and tracereaders will not, so the check must
  2647  	// be done here instead.
  2648  	tryWakeP := false
  2649  	if trace.enabled || trace.shutdown {
  2650  		gp = traceReader()
  2651  		if gp != nil {
  2652  			casgstatus(gp, _Gwaiting, _Grunnable)
  2653  			traceGoUnpark(gp, 0)
  2654  			tryWakeP = true
  2655  		}
  2656  	}
  2657  	if gp == nil && gcBlackenEnabled != 0 {
  2658  		gp = gcController.findRunnableGCWorker(_g_.m.p.ptr())
  2659  		tryWakeP = tryWakeP || gp != nil
  2660  	}
  2661  	if gp == nil {
  2662  		// Check the global runnable queue once in a while to ensure fairness.
  2663  		// Otherwise two goroutines can completely occupy the local runqueue
  2664  		// by constantly respawning each other.
  2665  		if _g_.m.p.ptr().schedtick%61 == 0 && sched.runqsize > 0 {
  2666  			lock(&sched.lock)
  2667  			gp = globrunqget(_g_.m.p.ptr(), 1)
  2668  			unlock(&sched.lock)
  2669  		}
  2670  	}
  2671  	if gp == nil {
  2672  		gp, inheritTime = runqget(_g_.m.p.ptr())
  2673  		// We can see gp != nil here even if the M is spinning,
  2674  		// if checkTimers added a local goroutine via goready.
  2675  	}
  2676  	if gp == nil {
  2677  		gp, inheritTime = findrunnable() // blocks until work is available
  2678  	}
  2679  
  2680  	// This thread is going to run a goroutine and is not spinning anymore,
  2681  	// so if it was marked as spinning we need to reset it now and potentially
  2682  	// start a new spinning M.
  2683  	if _g_.m.spinning {
  2684  		resetspinning()
  2685  	}
  2686  
  2687  	if sched.disable.user && !schedEnabled(gp) {
  2688  		// Scheduling of this goroutine is disabled. Put it on
  2689  		// the list of pending runnable goroutines for when we
  2690  		// re-enable user scheduling and look again.
  2691  		lock(&sched.lock)
  2692  		if schedEnabled(gp) {
  2693  			// Something re-enabled scheduling while we
  2694  			// were acquiring the lock.
  2695  			unlock(&sched.lock)
  2696  		} else {
  2697  			sched.disable.runnable.pushBack(gp)
  2698  			sched.disable.n++
  2699  			unlock(&sched.lock)
  2700  			goto top
  2701  		}
  2702  	}
  2703  
  2704  	// If about to schedule a not-normal goroutine (a GCworker or tracereader),
  2705  	// wake a P if there is one.
  2706  	if tryWakeP {
  2707  		wakep()
  2708  	}
  2709  	if gp.lockedm != 0 {
  2710  		// Hands off own p to the locked m,
  2711  		// then blocks waiting for a new p.
  2712  		startlockedm(gp)
  2713  		goto top
  2714  	}
  2715  
  2716  	execute(gp, inheritTime)
  2717  }
  2718  
  2719  // dropg removes the association between m and the current goroutine m->curg (gp for short).
  2720  // Typically a caller sets gp's status away from Grunning and then
  2721  // immediately calls dropg to finish the job. The caller is also responsible
  2722  // for arranging that gp will be restarted using ready at an
  2723  // appropriate time. After calling dropg and arranging for gp to be
  2724  // readied later, the caller can do other work but eventually should
  2725  // call schedule to restart the scheduling of goroutines on this m.
  2726  func dropg() {
  2727  	_g_ := getg()
  2728  
  2729  	setMNoWB(&_g_.m.curg.m, nil)
  2730  	setGNoWB(&_g_.m.curg, nil)
  2731  }
  2732  
  2733  // checkTimers runs any timers for the P that are ready.
  2734  // If now is not 0 it is the current time.
  2735  // It returns the current time or 0 if it is not known,
  2736  // and the time when the next timer should run or 0 if there is no next timer,
  2737  // and reports whether it ran any timers.
  2738  // If the time when the next timer should run is not 0,
  2739  // it is always larger than the returned time.
  2740  // We pass now in and out to avoid extra calls of nanotime.
  2741  //go:yeswritebarrierrec
  2742  func checkTimers(pp *p, now int64) (rnow, pollUntil int64, ran bool) {
  2743  	// If there are no timers to adjust, and the first timer on
  2744  	// the heap is not yet ready to run, then there is nothing to do.
  2745  	if atomic.Load(&pp.adjustTimers) == 0 {
  2746  		next := int64(atomic.Load64(&pp.timer0When))
  2747  		if next == 0 {
  2748  			return now, 0, false
  2749  		}
  2750  		if now == 0 {
  2751  			now = nanotime()
  2752  		}
  2753  		if now < next {
  2754  			// Next timer is not ready to run.
  2755  			// But keep going if we would clear deleted timers.
  2756  			// This corresponds to the condition below where
  2757  			// we decide whether to call clearDeletedTimers.
  2758  			if pp != getg().m.p.ptr() || int(atomic.Load(&pp.deletedTimers)) <= int(atomic.Load(&pp.numTimers)/4) {
  2759  				return now, next, false
  2760  			}
  2761  		}
  2762  	}
  2763  
  2764  	lock(&pp.timersLock)
  2765  
  2766  	adjusttimers(pp)
  2767  
  2768  	rnow = now
  2769  	if len(pp.timers) > 0 {
  2770  		if rnow == 0 {
  2771  			rnow = nanotime()
  2772  		}
  2773  		for len(pp.timers) > 0 {
  2774  			// Note that runtimer may temporarily unlock
  2775  			// pp.timersLock.
  2776  			if tw := runtimer(pp, rnow); tw != 0 {
  2777  				if tw > 0 {
  2778  					pollUntil = tw
  2779  				}
  2780  				break
  2781  			}
  2782  			ran = true
  2783  		}
  2784  	}
  2785  
  2786  	// If this is the local P, and there are a lot of deleted timers,
  2787  	// clear them out. We only do this for the local P to reduce
  2788  	// lock contention on timersLock.
  2789  	if pp == getg().m.p.ptr() && int(atomic.Load(&pp.deletedTimers)) > len(pp.timers)/4 {
  2790  		clearDeletedTimers(pp)
  2791  	}
  2792  
  2793  	unlock(&pp.timersLock)
  2794  
  2795  	return rnow, pollUntil, ran
  2796  }
  2797  
  2798  // shouldStealTimers reports whether we should try stealing the timers from p2.
  2799  // We don't steal timers from a running P that is not marked for preemption,
  2800  // on the assumption that it will run its own timers. This reduces
  2801  // contention on the timers lock.
  2802  func shouldStealTimers(p2 *p) bool {
  2803  	if p2.status != _Prunning {
  2804  		return true
  2805  	}
  2806  	mp := p2.m.ptr()
  2807  	if mp == nil || mp.locks > 0 {
  2808  		return false
  2809  	}
  2810  	gp := mp.curg
  2811  	if gp == nil || gp.atomicstatus != _Grunning || !gp.preempt {
  2812  		return false
  2813  	}
  2814  	return true
  2815  }
  2816  
  2817  func parkunlock_c(gp *g, lock unsafe.Pointer) bool {
  2818  	unlock((*mutex)(lock))
  2819  	return true
  2820  }
  2821  
  2822  // park continuation on g0.
  2823  func park_m(gp *g) {
  2824  	_g_ := getg()
  2825  
  2826  	if trace.enabled {
  2827  		traceGoPark(_g_.m.waittraceev, _g_.m.waittraceskip)
  2828  	}
  2829  
  2830  	casgstatus(gp, _Grunning, _Gwaiting)
  2831  	dropg()
  2832  
  2833  	if fn := _g_.m.waitunlockf; fn != nil {
  2834  		ok := fn(gp, _g_.m.waitlock)
  2835  		_g_.m.waitunlockf = nil
  2836  		_g_.m.waitlock = nil
  2837  		if !ok {
  2838  			if trace.enabled {
  2839  				traceGoUnpark(gp, 2)
  2840  			}
  2841  			casgstatus(gp, _Gwaiting, _Grunnable)
  2842  			execute(gp, true) // Schedule it back, never returns.
  2843  		}
  2844  	}
  2845  	schedule()
  2846  }
  2847  
  2848  func goschedImpl(gp *g) {
  2849  	status := readgstatus(gp)
  2850  	if status&^_Gscan != _Grunning {
  2851  		dumpgstatus(gp)
  2852  		throw("bad g status")
  2853  	}
  2854  	casgstatus(gp, _Grunning, _Grunnable)
  2855  	dropg()
  2856  	lock(&sched.lock)
  2857  	globrunqput(gp)
  2858  	unlock(&sched.lock)
  2859  
  2860  	schedule()
  2861  }
  2862  
  2863  // Gosched continuation on g0.
  2864  func gosched_m(gp *g) {
  2865  	if trace.enabled {
  2866  		traceGoSched()
  2867  	}
  2868  	goschedImpl(gp)
  2869  }
  2870  
  2871  // goschedguarded is a forbidden-states-avoided version of gosched_m
  2872  func goschedguarded_m(gp *g) {
  2873  
  2874  	if !canPreemptM(gp.m) {
  2875  		gogo(&gp.sched) // never return
  2876  	}
  2877  
  2878  	if trace.enabled {
  2879  		traceGoSched()
  2880  	}
  2881  	goschedImpl(gp)
  2882  }
  2883  
  2884  func gopreempt_m(gp *g) {
  2885  	if trace.enabled {
  2886  		traceGoPreempt()
  2887  	}
  2888  	goschedImpl(gp)
  2889  }
  2890  
  2891  // preemptPark parks gp and puts it in _Gpreempted.
  2892  //
  2893  //go:systemstack
  2894  func preemptPark(gp *g) {
  2895  	if trace.enabled {
  2896  		traceGoPark(traceEvGoBlock, 0)
  2897  	}
  2898  	status := readgstatus(gp)
  2899  	if status&^_Gscan != _Grunning {
  2900  		dumpgstatus(gp)
  2901  		throw("bad g status")
  2902  	}
  2903  	gp.waitreason = waitReasonPreempted
  2904  	// Transition from _Grunning to _Gscan|_Gpreempted. We can't
  2905  	// be in _Grunning when we dropg because then we'd be running
  2906  	// without an M, but the moment we're in _Gpreempted,
  2907  	// something could claim this G before we've fully cleaned it
  2908  	// up. Hence, we set the scan bit to lock down further
  2909  	// transitions until we can dropg.
  2910  	casGToPreemptScan(gp, _Grunning, _Gscan|_Gpreempted)
  2911  	dropg()
  2912  	casfrom_Gscanstatus(gp, _Gscan|_Gpreempted, _Gpreempted)
  2913  	schedule()
  2914  }
  2915  
  2916  // goyield is like Gosched, but it:
  2917  // - emits a GoPreempt trace event instead of a GoSched trace event
  2918  // - puts the current G on the runq of the current P instead of the globrunq
  2919  func goyield() {
  2920  	checkTimeouts()
  2921  	mcall(goyield_m)
  2922  }
  2923  
  2924  func goyield_m(gp *g) {
  2925  	if trace.enabled {
  2926  		traceGoPreempt()
  2927  	}
  2928  	pp := gp.m.p.ptr()
  2929  	casgstatus(gp, _Grunning, _Grunnable)
  2930  	dropg()
  2931  	runqput(pp, gp, false)
  2932  	schedule()
  2933  }
  2934  
  2935  // Finishes execution of the current goroutine.
  2936  func goexit1() {
  2937  	if raceenabled {
  2938  		racegoend()
  2939  	}
  2940  	if trace.enabled {
  2941  		traceGoEnd()
  2942  	}
  2943  	mcall(goexit0)
  2944  }
  2945  
  2946  // goexit continuation on g0.
  2947  func goexit0(gp *g) {
  2948  	_g_ := getg()
  2949  
  2950  	casgstatus(gp, _Grunning, _Gdead)
  2951  	if isSystemGoroutine(gp, false) {
  2952  		atomic.Xadd(&sched.ngsys, -1)
  2953  	}
  2954  	gp.m = nil
  2955  	locked := gp.lockedm != 0
  2956  	gp.lockedm = 0
  2957  	_g_.m.lockedg = 0
  2958  	gp.preemptStop = false
  2959  	gp.paniconfault = false
  2960  	gp._defer = nil // should be true already but just in case.
  2961  	gp._panic = nil // non-nil for Goexit during panic. points at stack-allocated data.
  2962  	gp.writebuf = nil
  2963  	gp.waitreason = 0
  2964  	gp.param = nil
  2965  	gp.labels = nil
  2966  	gp.timer = nil
  2967  
  2968  	if gcBlackenEnabled != 0 && gp.gcAssistBytes > 0 {
  2969  		// Flush assist credit to the global pool. This gives
  2970  		// better information to pacing if the application is
  2971  		// rapidly creating an exiting goroutines.
  2972  		scanCredit := int64(gcController.assistWorkPerByte * float64(gp.gcAssistBytes))
  2973  		atomic.Xaddint64(&gcController.bgScanCredit, scanCredit)
  2974  		gp.gcAssistBytes = 0
  2975  	}
  2976  
  2977  	dropg()
  2978  
  2979  	if GOARCH == "wasm" { // no threads yet on wasm
  2980  		gfput(_g_.m.p.ptr(), gp)
  2981  		schedule() // never returns
  2982  	}
  2983  
  2984  	if _g_.m.lockedInt != 0 {
  2985  		print("invalid m->lockedInt = ", _g_.m.lockedInt, "\n")
  2986  		throw("internal lockOSThread error")
  2987  	}
  2988  	gfput(_g_.m.p.ptr(), gp)
  2989  	if locked {
  2990  		// The goroutine may have locked this thread because
  2991  		// it put it in an unusual kernel state. Kill it
  2992  		// rather than returning it to the thread pool.
  2993  
  2994  		// Return to mstart, which will release the P and exit
  2995  		// the thread.
  2996  		if GOOS != "plan9" { // See golang.org/issue/22227.
  2997  			gogo(&_g_.m.g0.sched)
  2998  		} else {
  2999  			// Clear lockedExt on plan9 since we may end up re-using
  3000  			// this thread.
  3001  			_g_.m.lockedExt = 0
  3002  		}
  3003  	}
  3004  	schedule()
  3005  }
  3006  
  3007  // save updates getg().sched to refer to pc and sp so that a following
  3008  // gogo will restore pc and sp.
  3009  //
  3010  // save must not have write barriers because invoking a write barrier
  3011  // can clobber getg().sched.
  3012  //
  3013  //go:nosplit
  3014  //go:nowritebarrierrec
  3015  func save(pc, sp uintptr) {
  3016  	_g_ := getg()
  3017  
  3018  	_g_.sched.pc = pc
  3019  	_g_.sched.sp = sp
  3020  	_g_.sched.lr = 0
  3021  	_g_.sched.ret = 0
  3022  	_g_.sched.g = guintptr(unsafe.Pointer(_g_))
  3023  	// We need to ensure ctxt is zero, but can't have a write
  3024  	// barrier here. However, it should always already be zero.
  3025  	// Assert that.
  3026  	if _g_.sched.ctxt != nil {
  3027  		badctxt()
  3028  	}
  3029  }
  3030  
  3031  // The goroutine g is about to enter a system call.
  3032  // Record that it's not using the cpu anymore.
  3033  // This is called only from the go syscall library and cgocall,
  3034  // not from the low-level system calls used by the runtime.
  3035  //
  3036  // Entersyscall cannot split the stack: the gosave must
  3037  // make g->sched refer to the caller's stack segment, because
  3038  // entersyscall is going to return immediately after.
  3039  //
  3040  // Nothing entersyscall calls can split the stack either.
  3041  // We cannot safely move the stack during an active call to syscall,
  3042  // because we do not know which of the uintptr arguments are
  3043  // really pointers (back into the stack).
  3044  // In practice, this means that we make the fast path run through
  3045  // entersyscall doing no-split things, and the slow path has to use systemstack
  3046  // to run bigger things on the system stack.
  3047  //
  3048  // reentersyscall is the entry point used by cgo callbacks, where explicitly
  3049  // saved SP and PC are restored. This is needed when exitsyscall will be called
  3050  // from a function further up in the call stack than the parent, as g->syscallsp
  3051  // must always point to a valid stack frame. entersyscall below is the normal
  3052  // entry point for syscalls, which obtains the SP and PC from the caller.
  3053  //
  3054  // Syscall tracing:
  3055  // At the start of a syscall we emit traceGoSysCall to capture the stack trace.
  3056  // If the syscall does not block, that is it, we do not emit any other events.
  3057  // If the syscall blocks (that is, P is retaken), retaker emits traceGoSysBlock;
  3058  // when syscall returns we emit traceGoSysExit and when the goroutine starts running
  3059  // (potentially instantly, if exitsyscallfast returns true) we emit traceGoStart.
  3060  // To ensure that traceGoSysExit is emitted strictly after traceGoSysBlock,
  3061  // we remember current value of syscalltick in m (_g_.m.syscalltick = _g_.m.p.ptr().syscalltick),
  3062  // whoever emits traceGoSysBlock increments p.syscalltick afterwards;
  3063  // and we wait for the increment before emitting traceGoSysExit.
  3064  // Note that the increment is done even if tracing is not enabled,
  3065  // because tracing can be enabled in the middle of syscall. We don't want the wait to hang.
  3066  //
  3067  //go:nosplit
  3068  func reentersyscall(pc, sp uintptr) {
  3069  	_g_ := getg()
  3070  
  3071  	// Disable preemption because during this function g is in Gsyscall status,
  3072  	// but can have inconsistent g->sched, do not let GC observe it.
  3073  	_g_.m.locks++
  3074  
  3075  	// Entersyscall must not call any function that might split/grow the stack.
  3076  	// (See details in comment above.)
  3077  	// Catch calls that might, by replacing the stack guard with something that
  3078  	// will trip any stack check and leaving a flag to tell newstack to die.
  3079  	_g_.stackguard0 = stackPreempt
  3080  	_g_.throwsplit = true
  3081  
  3082  	// Leave SP around for GC and traceback.
  3083  	save(pc, sp)
  3084  	_g_.syscallsp = sp
  3085  	_g_.syscallpc = pc
  3086  	casgstatus(_g_, _Grunning, _Gsyscall)
  3087  	if _g_.syscallsp < _g_.stack.lo || _g_.stack.hi < _g_.syscallsp {
  3088  		systemstack(func() {
  3089  			print("entersyscall inconsistent ", hex(_g_.syscallsp), " [", hex(_g_.stack.lo), ",", hex(_g_.stack.hi), "]\n")
  3090  			throw("entersyscall")
  3091  		})
  3092  	}
  3093  
  3094  	if trace.enabled {
  3095  		systemstack(traceGoSysCall)
  3096  		// systemstack itself clobbers g.sched.{pc,sp} and we might
  3097  		// need them later when the G is genuinely blocked in a
  3098  		// syscall
  3099  		save(pc, sp)
  3100  	}
  3101  
  3102  	if atomic.Load(&sched.sysmonwait) != 0 {
  3103  		systemstack(entersyscall_sysmon)
  3104  		save(pc, sp)
  3105  	}
  3106  
  3107  	if _g_.m.p.ptr().runSafePointFn != 0 {
  3108  		// runSafePointFn may stack split if run on this stack
  3109  		systemstack(runSafePointFn)
  3110  		save(pc, sp)
  3111  	}
  3112  
  3113  	_g_.m.syscalltick = _g_.m.p.ptr().syscalltick
  3114  	_g_.sysblocktraced = true
  3115  	pp := _g_.m.p.ptr()
  3116  	pp.m = 0
  3117  	_g_.m.oldp.set(pp)
  3118  	_g_.m.p = 0
  3119  	atomic.Store(&pp.status, _Psyscall)
  3120  	if sched.gcwaiting != 0 {
  3121  		systemstack(entersyscall_gcwait)
  3122  		save(pc, sp)
  3123  	}
  3124  
  3125  	_g_.m.locks--
  3126  }
  3127  
  3128  // Standard syscall entry used by the go syscall library and normal cgo calls.
  3129  //
  3130  // This is exported via linkname to assembly in the syscall package.
  3131  //
  3132  //go:nosplit
  3133  //go:linkname entersyscall
  3134  func entersyscall() {
  3135  	reentersyscall(getcallerpc(), getcallersp())
  3136  }
  3137  
  3138  func entersyscall_sysmon() {
  3139  	lock(&sched.lock)
  3140  	if atomic.Load(&sched.sysmonwait) != 0 {
  3141  		atomic.Store(&sched.sysmonwait, 0)
  3142  		notewakeup(&sched.sysmonnote)
  3143  	}
  3144  	unlock(&sched.lock)
  3145  }
  3146  
  3147  func entersyscall_gcwait() {
  3148  	_g_ := getg()
  3149  	_p_ := _g_.m.oldp.ptr()
  3150  
  3151  	lock(&sched.lock)
  3152  	if sched.stopwait > 0 && atomic.Cas(&_p_.status, _Psyscall, _Pgcstop) {
  3153  		if trace.enabled {
  3154  			traceGoSysBlock(_p_)
  3155  			traceProcStop(_p_)
  3156  		}
  3157  		_p_.syscalltick++
  3158  		if sched.stopwait--; sched.stopwait == 0 {
  3159  			notewakeup(&sched.stopnote)
  3160  		}
  3161  	}
  3162  	unlock(&sched.lock)
  3163  }
  3164  
  3165  // The same as entersyscall(), but with a hint that the syscall is blocking.
  3166  //go:nosplit
  3167  func entersyscallblock() {
  3168  	_g_ := getg()
  3169  
  3170  	_g_.m.locks++ // see comment in entersyscall
  3171  	_g_.throwsplit = true
  3172  	_g_.stackguard0 = stackPreempt // see comment in entersyscall
  3173  	_g_.m.syscalltick = _g_.m.p.ptr().syscalltick
  3174  	_g_.sysblocktraced = true
  3175  	_g_.m.p.ptr().syscalltick++
  3176  
  3177  	// Leave SP around for GC and traceback.
  3178  	pc := getcallerpc()
  3179  	sp := getcallersp()
  3180  	save(pc, sp)
  3181  	_g_.syscallsp = _g_.sched.sp
  3182  	_g_.syscallpc = _g_.sched.pc
  3183  	if _g_.syscallsp < _g_.stack.lo || _g_.stack.hi < _g_.syscallsp {
  3184  		sp1 := sp
  3185  		sp2 := _g_.sched.sp
  3186  		sp3 := _g_.syscallsp
  3187  		systemstack(func() {
  3188  			print("entersyscallblock inconsistent ", hex(sp1), " ", hex(sp2), " ", hex(sp3), " [", hex(_g_.stack.lo), ",", hex(_g_.stack.hi), "]\n")
  3189  			throw("entersyscallblock")
  3190  		})
  3191  	}
  3192  	casgstatus(_g_, _Grunning, _Gsyscall)
  3193  	if _g_.syscallsp < _g_.stack.lo || _g_.stack.hi < _g_.syscallsp {
  3194  		systemstack(func() {
  3195  			print("entersyscallblock inconsistent ", hex(sp), " ", hex(_g_.sched.sp), " ", hex(_g_.syscallsp), " [", hex(_g_.stack.lo), ",", hex(_g_.stack.hi), "]\n")
  3196  			throw("entersyscallblock")
  3197  		})
  3198  	}
  3199  
  3200  	systemstack(entersyscallblock_handoff)
  3201  
  3202  	// Resave for traceback during blocked call.
  3203  	save(getcallerpc(), getcallersp())
  3204  
  3205  	_g_.m.locks--
  3206  }
  3207  
  3208  func entersyscallblock_handoff() {
  3209  	if trace.enabled {
  3210  		traceGoSysCall()
  3211  		traceGoSysBlock(getg().m.p.ptr())
  3212  	}
  3213  	handoffp(releasep())
  3214  }
  3215  
  3216  // The goroutine g exited its system call.
  3217  // Arrange for it to run on a cpu again.
  3218  // This is called only from the go syscall library, not
  3219  // from the low-level system calls used by the runtime.
  3220  //
  3221  // Write barriers are not allowed because our P may have been stolen.
  3222  //
  3223  // This is exported via linkname to assembly in the syscall package.
  3224  //
  3225  //go:nosplit
  3226  //go:nowritebarrierrec
  3227  //go:linkname exitsyscall
  3228  func exitsyscall() {
  3229  	_g_ := getg()
  3230  
  3231  	_g_.m.locks++ // see comment in entersyscall
  3232  	if getcallersp() > _g_.syscallsp {
  3233  		throw("exitsyscall: syscall frame is no longer valid")
  3234  	}
  3235  
  3236  	_g_.waitsince = 0
  3237  	oldp := _g_.m.oldp.ptr()
  3238  	_g_.m.oldp = 0
  3239  	if exitsyscallfast(oldp) {
  3240  		if trace.enabled {
  3241  			if oldp != _g_.m.p.ptr() || _g_.m.syscalltick != _g_.m.p.ptr().syscalltick {
  3242  				systemstack(traceGoStart)
  3243  			}
  3244  		}
  3245  		// There's a cpu for us, so we can run.
  3246  		_g_.m.p.ptr().syscalltick++
  3247  		// We need to cas the status and scan before resuming...
  3248  		casgstatus(_g_, _Gsyscall, _Grunning)
  3249  
  3250  		// Garbage collector isn't running (since we are),
  3251  		// so okay to clear syscallsp.
  3252  		_g_.syscallsp = 0
  3253  		_g_.m.locks--
  3254  		if _g_.preempt {
  3255  			// restore the preemption request in case we've cleared it in newstack
  3256  			_g_.stackguard0 = stackPreempt
  3257  		} else {
  3258  			// otherwise restore the real _StackGuard, we've spoiled it in entersyscall/entersyscallblock
  3259  			_g_.stackguard0 = _g_.stack.lo + _StackGuard
  3260  		}
  3261  		_g_.throwsplit = false
  3262  
  3263  		if sched.disable.user && !schedEnabled(_g_) {
  3264  			// Scheduling of this goroutine is disabled.
  3265  			Gosched()
  3266  		}
  3267  
  3268  		return
  3269  	}
  3270  
  3271  	_g_.sysexitticks = 0
  3272  	if trace.enabled {
  3273  		// Wait till traceGoSysBlock event is emitted.
  3274  		// This ensures consistency of the trace (the goroutine is started after it is blocked).
  3275  		for oldp != nil && oldp.syscalltick == _g_.m.syscalltick {
  3276  			osyield()
  3277  		}
  3278  		// We can't trace syscall exit right now because we don't have a P.
  3279  		// Tracing code can invoke write barriers that cannot run without a P.
  3280  		// So instead we remember the syscall exit time and emit the event
  3281  		// in execute when we have a P.
  3282  		_g_.sysexitticks = cputicks()
  3283  	}
  3284  
  3285  	_g_.m.locks--
  3286  
  3287  	// Call the scheduler.
  3288  	mcall(exitsyscall0)
  3289  
  3290  	// Scheduler returned, so we're allowed to run now.
  3291  	// Delete the syscallsp information that we left for
  3292  	// the garbage collector during the system call.
  3293  	// Must wait until now because until gosched returns
  3294  	// we don't know for sure that the garbage collector
  3295  	// is not running.
  3296  	_g_.syscallsp = 0
  3297  	_g_.m.p.ptr().syscalltick++
  3298  	_g_.throwsplit = false
  3299  }
  3300  
  3301  //go:nosplit
  3302  func exitsyscallfast(oldp *p) bool {
  3303  	_g_ := getg()
  3304  
  3305  	// Freezetheworld sets stopwait but does not retake P's.
  3306  	if sched.stopwait == freezeStopWait {
  3307  		return false
  3308  	}
  3309  
  3310  	// Try to re-acquire the last P.
  3311  	if oldp != nil && oldp.status == _Psyscall && atomic.Cas(&oldp.status, _Psyscall, _Pidle) {
  3312  		// There's a cpu for us, so we can run.
  3313  		wirep(oldp)
  3314  		exitsyscallfast_reacquired()
  3315  		return true
  3316  	}
  3317  
  3318  	// Try to get any other idle P.
  3319  	if sched.pidle != 0 {
  3320  		var ok bool
  3321  		systemstack(func() {
  3322  			ok = exitsyscallfast_pidle()
  3323  			if ok && trace.enabled {
  3324  				if oldp != nil {
  3325  					// Wait till traceGoSysBlock event is emitted.
  3326  					// This ensures consistency of the trace (the goroutine is started after it is blocked).
  3327  					for oldp.syscalltick == _g_.m.syscalltick {
  3328  						osyield()
  3329  					}
  3330  				}
  3331  				traceGoSysExit(0)
  3332  			}
  3333  		})
  3334  		if ok {
  3335  			return true
  3336  		}
  3337  	}
  3338  	return false
  3339  }
  3340  
  3341  // exitsyscallfast_reacquired is the exitsyscall path on which this G
  3342  // has successfully reacquired the P it was running on before the
  3343  // syscall.
  3344  //
  3345  //go:nosplit
  3346  func exitsyscallfast_reacquired() {
  3347  	_g_ := getg()
  3348  	if _g_.m.syscalltick != _g_.m.p.ptr().syscalltick {
  3349  		if trace.enabled {
  3350  			// The p was retaken and then enter into syscall again (since _g_.m.syscalltick has changed).
  3351  			// traceGoSysBlock for this syscall was already emitted,
  3352  			// but here we effectively retake the p from the new syscall running on the same p.
  3353  			systemstack(func() {
  3354  				// Denote blocking of the new syscall.
  3355  				traceGoSysBlock(_g_.m.p.ptr())
  3356  				// Denote completion of the current syscall.
  3357  				traceGoSysExit(0)
  3358  			})
  3359  		}
  3360  		_g_.m.p.ptr().syscalltick++
  3361  	}
  3362  }
  3363  
  3364  func exitsyscallfast_pidle() bool {
  3365  	lock(&sched.lock)
  3366  	_p_ := pidleget()
  3367  	if _p_ != nil && atomic.Load(&sched.sysmonwait) != 0 {
  3368  		atomic.Store(&sched.sysmonwait, 0)
  3369  		notewakeup(&sched.sysmonnote)
  3370  	}
  3371  	unlock(&sched.lock)
  3372  	if _p_ != nil {
  3373  		acquirep(_p_)
  3374  		return true
  3375  	}
  3376  	return false
  3377  }
  3378  
  3379  // exitsyscall slow path on g0.
  3380  // Failed to acquire P, enqueue gp as runnable.
  3381  //
  3382  //go:nowritebarrierrec
  3383  func exitsyscall0(gp *g) {
  3384  	_g_ := getg()
  3385  
  3386  	casgstatus(gp, _Gsyscall, _Grunnable)
  3387  	dropg()
  3388  	lock(&sched.lock)
  3389  	var _p_ *p
  3390  	if schedEnabled(_g_) {
  3391  		_p_ = pidleget()
  3392  	}
  3393  	if _p_ == nil {
  3394  		globrunqput(gp)
  3395  	} else if atomic.Load(&sched.sysmonwait) != 0 {
  3396  		atomic.Store(&sched.sysmonwait, 0)
  3397  		notewakeup(&sched.sysmonnote)
  3398  	}
  3399  	unlock(&sched.lock)
  3400  	if _p_ != nil {
  3401  		acquirep(_p_)
  3402  		execute(gp, false) // Never returns.
  3403  	}
  3404  	if _g_.m.lockedg != 0 {
  3405  		// Wait until another thread schedules gp and so m again.
  3406  		stoplockedm()
  3407  		execute(gp, false) // Never returns.
  3408  	}
  3409  	stopm()
  3410  	schedule() // Never returns.
  3411  }
  3412  
  3413  func beforefork() {
  3414  	gp := getg().m.curg
  3415  
  3416  	// Block signals during a fork, so that the child does not run
  3417  	// a signal handler before exec if a signal is sent to the process
  3418  	// group. See issue #18600.
  3419  	gp.m.locks++
  3420  	msigsave(gp.m)
  3421  	sigblock()
  3422  
  3423  	// This function is called before fork in syscall package.
  3424  	// Code between fork and exec must not allocate memory nor even try to grow stack.
  3425  	// Here we spoil g->_StackGuard to reliably detect any attempts to grow stack.
  3426  	// runtime_AfterFork will undo this in parent process, but not in child.
  3427  	gp.stackguard0 = stackFork
  3428  }
  3429  
  3430  // Called from syscall package before fork.
  3431  //go:linkname syscall_runtime_BeforeFork syscall.runtime_BeforeFork
  3432  //go:nosplit
  3433  func syscall_runtime_BeforeFork() {
  3434  	systemstack(beforefork)
  3435  }
  3436  
  3437  func afterfork() {
  3438  	gp := getg().m.curg
  3439  
  3440  	// See the comments in beforefork.
  3441  	gp.stackguard0 = gp.stack.lo + _StackGuard
  3442  
  3443  	msigrestore(gp.m.sigmask)
  3444  
  3445  	gp.m.locks--
  3446  }
  3447  
  3448  // Called from syscall package after fork in parent.
  3449  //go:linkname syscall_runtime_AfterFork syscall.runtime_AfterFork
  3450  //go:nosplit
  3451  func syscall_runtime_AfterFork() {
  3452  	systemstack(afterfork)
  3453  }
  3454  
  3455  // inForkedChild is true while manipulating signals in the child process.
  3456  // This is used to avoid calling libc functions in case we are using vfork.
  3457  var inForkedChild bool
  3458  
  3459  // Called from syscall package after fork in child.
  3460  // It resets non-sigignored signals to the default handler, and
  3461  // restores the signal mask in preparation for the exec.
  3462  //
  3463  // Because this might be called during a vfork, and therefore may be
  3464  // temporarily sharing address space with the parent process, this must
  3465  // not change any global variables or calling into C code that may do so.
  3466  //
  3467  //go:linkname syscall_runtime_AfterForkInChild syscall.runtime_AfterForkInChild
  3468  //go:nosplit
  3469  //go:nowritebarrierrec
  3470  func syscall_runtime_AfterForkInChild() {
  3471  	// It's OK to change the global variable inForkedChild here
  3472  	// because we are going to change it back. There is no race here,
  3473  	// because if we are sharing address space with the parent process,
  3474  	// then the parent process can not be running concurrently.
  3475  	inForkedChild = true
  3476  
  3477  	clearSignalHandlers()
  3478  
  3479  	// When we are the child we are the only thread running,
  3480  	// so we know that nothing else has changed gp.m.sigmask.
  3481  	msigrestore(getg().m.sigmask)
  3482  
  3483  	inForkedChild = false
  3484  }
  3485  
  3486  // pendingPreemptSignals is the number of preemption signals
  3487  // that have been sent but not received. This is only used on Darwin.
  3488  // For #41702.
  3489  var pendingPreemptSignals uint32
  3490  
  3491  // Called from syscall package before Exec.
  3492  //go:linkname syscall_runtime_BeforeExec syscall.runtime_BeforeExec
  3493  func syscall_runtime_BeforeExec() {
  3494  	// Prevent thread creation during exec.
  3495  	execLock.lock()
  3496  
  3497  	// On Darwin, wait for all pending preemption signals to
  3498  	// be received. See issue #41702.
  3499  	if GOOS == "darwin" {
  3500  		for int32(atomic.Load(&pendingPreemptSignals)) > 0 {
  3501  			osyield()
  3502  		}
  3503  	}
  3504  }
  3505  
  3506  // Called from syscall package after Exec.
  3507  //go:linkname syscall_runtime_AfterExec syscall.runtime_AfterExec
  3508  func syscall_runtime_AfterExec() {
  3509  	execLock.unlock()
  3510  }
  3511  
  3512  // Allocate a new g, with a stack big enough for stacksize bytes.
  3513  func malg(stacksize int32) *g {
  3514  	newg := new(g)
  3515  	if stacksize >= 0 {
  3516  		stacksize = round2(_StackSystem + stacksize)
  3517  		systemstack(func() {
  3518  			newg.stack = stackalloc(uint32(stacksize))
  3519  		})
  3520  		newg.stackguard0 = newg.stack.lo + _StackGuard
  3521  		newg.stackguard1 = ^uintptr(0)
  3522  		// Clear the bottom word of the stack. We record g
  3523  		// there on gsignal stack during VDSO on ARM and ARM64.
  3524  		*(*uintptr)(unsafe.Pointer(newg.stack.lo)) = 0
  3525  	}
  3526  	return newg
  3527  }
  3528  
  3529  // Create a new g running fn with siz bytes of arguments.
  3530  // Put it on the queue of g's waiting to run.
  3531  // The compiler turns a go statement into a call to this.
  3532  //
  3533  // The stack layout of this call is unusual: it assumes that the
  3534  // arguments to pass to fn are on the stack sequentially immediately
  3535  // after &fn. Hence, they are logically part of newproc's argument
  3536  // frame, even though they don't appear in its signature (and can't
  3537  // because their types differ between call sites).
  3538  //
  3539  // This must be nosplit because this stack layout means there are
  3540  // untyped arguments in newproc's argument frame. Stack copies won't
  3541  // be able to adjust them and stack splits won't be able to copy them.
  3542  //
  3543  //go:nosplit
  3544  func newproc(siz int32, fn *funcval) {
  3545  	argp := add(unsafe.Pointer(&fn), sys.PtrSize)
  3546  	gp := getg()
  3547  	pc := getcallerpc()
  3548  	systemstack(func() {
  3549  		newg := newproc1(fn, argp, siz, gp, pc)
  3550  
  3551  		_p_ := getg().m.p.ptr()
  3552  		runqput(_p_, newg, true)
  3553  
  3554  		if mainStarted {
  3555  			wakep()
  3556  		}
  3557  	})
  3558  }
  3559  
  3560  // Create a new g in state _Grunnable, starting at fn, with narg bytes
  3561  // of arguments starting at argp. callerpc is the address of the go
  3562  // statement that created this. The caller is responsible for adding
  3563  // the new g to the scheduler.
  3564  //
  3565  // This must run on the system stack because it's the continuation of
  3566  // newproc, which cannot split the stack.
  3567  //
  3568  //go:systemstack
  3569  func newproc1(fn *funcval, argp unsafe.Pointer, narg int32, callergp *g, callerpc uintptr) *g {
  3570  	_g_ := getg()
  3571  
  3572  	if fn == nil {
  3573  		_g_.m.throwing = -1 // do not dump full stacks
  3574  		throw("go of nil func value")
  3575  	}
  3576  	acquirem() // disable preemption because it can be holding p in a local var
  3577  	siz := narg
  3578  	siz = (siz + 7) &^ 7
  3579  
  3580  	// We could allocate a larger initial stack if necessary.
  3581  	// Not worth it: this is almost always an error.
  3582  	// 4*sizeof(uintreg): extra space added below
  3583  	// sizeof(uintreg): caller's LR (arm) or return address (x86, in gostartcall).
  3584  	if siz >= _StackMin-4*sys.RegSize-sys.RegSize {
  3585  		throw("newproc: function arguments too large for new goroutine")
  3586  	}
  3587  
  3588  	_p_ := _g_.m.p.ptr()
  3589  	newg := gfget(_p_)
  3590  	if newg == nil {
  3591  		newg = malg(_StackMin)
  3592  		casgstatus(newg, _Gidle, _Gdead)
  3593  		allgadd(newg) // publishes with a g->status of Gdead so GC scanner doesn't look at uninitialized stack.
  3594  	}
  3595  	if newg.stack.hi == 0 {
  3596  		throw("newproc1: newg missing stack")
  3597  	}
  3598  
  3599  	if readgstatus(newg) != _Gdead {
  3600  		throw("newproc1: new g is not Gdead")
  3601  	}
  3602  
  3603  	totalSize := 4*sys.RegSize + uintptr(siz) + sys.MinFrameSize // extra space in case of reads slightly beyond frame
  3604  	totalSize += -totalSize & (sys.SpAlign - 1)                  // align to spAlign
  3605  	sp := newg.stack.hi - totalSize
  3606  	spArg := sp
  3607  	if usesLR {
  3608  		// caller's LR
  3609  		*(*uintptr)(unsafe.Pointer(sp)) = 0
  3610  		prepGoExitFrame(sp)
  3611  		spArg += sys.MinFrameSize
  3612  	}
  3613  	if narg > 0 {
  3614  		memmove(unsafe.Pointer(spArg), argp, uintptr(narg))
  3615  		// This is a stack-to-stack copy. If write barriers
  3616  		// are enabled and the source stack is grey (the
  3617  		// destination is always black), then perform a
  3618  		// barrier copy. We do this *after* the memmove
  3619  		// because the destination stack may have garbage on
  3620  		// it.
  3621  		if writeBarrier.needed && !_g_.m.curg.gcscandone {
  3622  			f := findfunc(fn.fn)
  3623  			stkmap := (*stackmap)(funcdata(f, _FUNCDATA_ArgsPointerMaps))
  3624  			if stkmap.nbit > 0 {
  3625  				// We're in the prologue, so it's always stack map index 0.
  3626  				bv := stackmapdata(stkmap, 0)
  3627  				bulkBarrierBitmap(spArg, spArg, uintptr(bv.n)*sys.PtrSize, 0, bv.bytedata)
  3628  			}
  3629  		}
  3630  	}
  3631  
  3632  	memclrNoHeapPointers(unsafe.Pointer(&newg.sched), unsafe.Sizeof(newg.sched))
  3633  	newg.sched.sp = sp
  3634  	newg.stktopsp = sp
  3635  	newg.sched.pc = funcPC(goexit) + sys.PCQuantum // +PCQuantum so that previous instruction is in same function
  3636  	newg.sched.g = guintptr(unsafe.Pointer(newg))
  3637  	gostartcallfn(&newg.sched, fn)
  3638  	newg.gopc = callerpc
  3639  	newg.ancestors = saveAncestors(callergp)
  3640  	newg.startpc = fn.fn
  3641  	if _g_.m.curg != nil {
  3642  		newg.labels = _g_.m.curg.labels
  3643  	}
  3644  	if isSystemGoroutine(newg, false) {
  3645  		atomic.Xadd(&sched.ngsys, +1)
  3646  	}
  3647  	casgstatus(newg, _Gdead, _Grunnable)
  3648  
  3649  	if _p_.goidcache == _p_.goidcacheend {
  3650  		// Sched.goidgen is the last allocated id,
  3651  		// this batch must be [sched.goidgen+1, sched.goidgen+GoidCacheBatch].
  3652  		// At startup sched.goidgen=0, so main goroutine receives goid=1.
  3653  		_p_.goidcache = atomic.Xadd64(&sched.goidgen, _GoidCacheBatch)
  3654  		_p_.goidcache -= _GoidCacheBatch - 1
  3655  		_p_.goidcacheend = _p_.goidcache + _GoidCacheBatch
  3656  	}
  3657  	newg.goid = int64(_p_.goidcache)
  3658  	_p_.goidcache++
  3659  	if raceenabled {
  3660  		newg.racectx = racegostart(callerpc)
  3661  	}
  3662  	if trace.enabled {
  3663  		traceGoCreate(newg, newg.startpc)
  3664  	}
  3665  	releasem(_g_.m)
  3666  
  3667  	return newg
  3668  }
  3669  
  3670  // saveAncestors copies previous ancestors of the given caller g and
  3671  // includes infor for the current caller into a new set of tracebacks for
  3672  // a g being created.
  3673  func saveAncestors(callergp *g) *[]ancestorInfo {
  3674  	// Copy all prior info, except for the root goroutine (goid 0).
  3675  	if debug.tracebackancestors <= 0 || callergp.goid == 0 {
  3676  		return nil
  3677  	}
  3678  	var callerAncestors []ancestorInfo
  3679  	if callergp.ancestors != nil {
  3680  		callerAncestors = *callergp.ancestors
  3681  	}
  3682  	n := int32(len(callerAncestors)) + 1
  3683  	if n > debug.tracebackancestors {
  3684  		n = debug.tracebackancestors
  3685  	}
  3686  	ancestors := make([]ancestorInfo, n)
  3687  	copy(ancestors[1:], callerAncestors)
  3688  
  3689  	var pcs [_TracebackMaxFrames]uintptr
  3690  	npcs := gcallers(callergp, 0, pcs[:])
  3691  	ipcs := make([]uintptr, npcs)
  3692  	copy(ipcs, pcs[:])
  3693  	ancestors[0] = ancestorInfo{
  3694  		pcs:  ipcs,
  3695  		goid: callergp.goid,
  3696  		gopc: callergp.gopc,
  3697  	}
  3698  
  3699  	ancestorsp := new([]ancestorInfo)
  3700  	*ancestorsp = ancestors
  3701  	return ancestorsp
  3702  }
  3703  
  3704  // Put on gfree list.
  3705  // If local list is too long, transfer a batch to the global list.
  3706  func gfput(_p_ *p, gp *g) {
  3707  	if readgstatus(gp) != _Gdead {
  3708  		throw("gfput: bad status (not Gdead)")
  3709  	}
  3710  
  3711  	stksize := gp.stack.hi - gp.stack.lo
  3712  
  3713  	if stksize != _FixedStack {
  3714  		// non-standard stack size - free it.
  3715  		stackfree(gp.stack)
  3716  		gp.stack.lo = 0
  3717  		gp.stack.hi = 0
  3718  		gp.stackguard0 = 0
  3719  	}
  3720  
  3721  	_p_.gFree.push(gp)
  3722  	_p_.gFree.n++
  3723  	if _p_.gFree.n >= 64 {
  3724  		lock(&sched.gFree.lock)
  3725  		for _p_.gFree.n >= 32 {
  3726  			_p_.gFree.n--
  3727  			gp = _p_.gFree.pop()
  3728  			if gp.stack.lo == 0 {
  3729  				sched.gFree.noStack.push(gp)
  3730  			} else {
  3731  				sched.gFree.stack.push(gp)
  3732  			}
  3733  			sched.gFree.n++
  3734  		}
  3735  		unlock(&sched.gFree.lock)
  3736  	}
  3737  }
  3738  
  3739  // Get from gfree list.
  3740  // If local list is empty, grab a batch from global list.
  3741  func gfget(_p_ *p) *g {
  3742  retry:
  3743  	if _p_.gFree.empty() && (!sched.gFree.stack.empty() || !sched.gFree.noStack.empty()) {
  3744  		lock(&sched.gFree.lock)
  3745  		// Move a batch of free Gs to the P.
  3746  		for _p_.gFree.n < 32 {
  3747  			// Prefer Gs with stacks.
  3748  			gp := sched.gFree.stack.pop()
  3749  			if gp == nil {
  3750  				gp = sched.gFree.noStack.pop()
  3751  				if gp == nil {
  3752  					break
  3753  				}
  3754  			}
  3755  			sched.gFree.n--
  3756  			_p_.gFree.push(gp)
  3757  			_p_.gFree.n++
  3758  		}
  3759  		unlock(&sched.gFree.lock)
  3760  		goto retry
  3761  	}
  3762  	gp := _p_.gFree.pop()
  3763  	if gp == nil {
  3764  		return nil
  3765  	}
  3766  	_p_.gFree.n--
  3767  	if gp.stack.lo == 0 {
  3768  		// Stack was deallocated in gfput. Allocate a new one.
  3769  		systemstack(func() {
  3770  			gp.stack = stackalloc(_FixedStack)
  3771  		})
  3772  		gp.stackguard0 = gp.stack.lo + _StackGuard
  3773  	} else {
  3774  		if raceenabled {
  3775  			racemalloc(unsafe.Pointer(gp.stack.lo), gp.stack.hi-gp.stack.lo)
  3776  		}
  3777  		if msanenabled {
  3778  			msanmalloc(unsafe.Pointer(gp.stack.lo), gp.stack.hi-gp.stack.lo)
  3779  		}
  3780  	}
  3781  	return gp
  3782  }
  3783  
  3784  // Purge all cached G's from gfree list to the global list.
  3785  func gfpurge(_p_ *p) {
  3786  	lock(&sched.gFree.lock)
  3787  	for !_p_.gFree.empty() {
  3788  		gp := _p_.gFree.pop()
  3789  		_p_.gFree.n--
  3790  		if gp.stack.lo == 0 {
  3791  			sched.gFree.noStack.push(gp)
  3792  		} else {
  3793  			sched.gFree.stack.push(gp)
  3794  		}
  3795  		sched.gFree.n++
  3796  	}
  3797  	unlock(&sched.gFree.lock)
  3798  }
  3799  
  3800  // Breakpoint executes a breakpoint trap.
  3801  func Breakpoint() {
  3802  	breakpoint()
  3803  }
  3804  
  3805  // dolockOSThread is called by LockOSThread and lockOSThread below
  3806  // after they modify m.locked. Do not allow preemption during this call,
  3807  // or else the m might be different in this function than in the caller.
  3808  //go:nosplit
  3809  func dolockOSThread() {
  3810  	if GOARCH == "wasm" {
  3811  		return // no threads on wasm yet
  3812  	}
  3813  	_g_ := getg()
  3814  	_g_.m.lockedg.set(_g_)
  3815  	_g_.lockedm.set(_g_.m)
  3816  }
  3817  
  3818  //go:nosplit
  3819  
  3820  // LockOSThread wires the calling goroutine to its current operating system thread.
  3821  // The calling goroutine will always execute in that thread,
  3822  // and no other goroutine will execute in it,
  3823  // until the calling goroutine has made as many calls to
  3824  // UnlockOSThread as to LockOSThread.
  3825  // If the calling goroutine exits without unlocking the thread,
  3826  // the thread will be terminated.
  3827  //
  3828  // All init functions are run on the startup thread. Calling LockOSThread
  3829  // from an init function will cause the main function to be invoked on
  3830  // that thread.
  3831  //
  3832  // A goroutine should call LockOSThread before calling OS services or
  3833  // non-Go library functions that depend on per-thread state.
  3834  func LockOSThread() {
  3835  	if atomic.Load(&newmHandoff.haveTemplateThread) == 0 && GOOS != "plan9" {
  3836  		// If we need to start a new thread from the locked
  3837  		// thread, we need the template thread. Start it now
  3838  		// while we're in a known-good state.
  3839  		startTemplateThread()
  3840  	}
  3841  	_g_ := getg()
  3842  	_g_.m.lockedExt++
  3843  	if _g_.m.lockedExt == 0 {
  3844  		_g_.m.lockedExt--
  3845  		panic("LockOSThread nesting overflow")
  3846  	}
  3847  	dolockOSThread()
  3848  }
  3849  
  3850  //go:nosplit
  3851  func lockOSThread() {
  3852  	getg().m.lockedInt++
  3853  	dolockOSThread()
  3854  }
  3855  
  3856  // dounlockOSThread is called by UnlockOSThread and unlockOSThread below
  3857  // after they update m->locked. Do not allow preemption during this call,
  3858  // or else the m might be in different in this function than in the caller.
  3859  //go:nosplit
  3860  func dounlockOSThread() {
  3861  	if GOARCH == "wasm" {
  3862  		return // no threads on wasm yet
  3863  	}
  3864  	_g_ := getg()
  3865  	if _g_.m.lockedInt != 0 || _g_.m.lockedExt != 0 {
  3866  		return
  3867  	}
  3868  	_g_.m.lockedg = 0
  3869  	_g_.lockedm = 0
  3870  }
  3871  
  3872  //go:nosplit
  3873  
  3874  // UnlockOSThread undoes an earlier call to LockOSThread.
  3875  // If this drops the number of active LockOSThread calls on the
  3876  // calling goroutine to zero, it unwires the calling goroutine from
  3877  // its fixed operating system thread.
  3878  // If there are no active LockOSThread calls, this is a no-op.
  3879  //
  3880  // Before calling UnlockOSThread, the caller must ensure that the OS
  3881  // thread is suitable for running other goroutines. If the caller made
  3882  // any permanent changes to the state of the thread that would affect
  3883  // other goroutines, it should not call this function and thus leave
  3884  // the goroutine locked to the OS thread until the goroutine (and
  3885  // hence the thread) exits.
  3886  func UnlockOSThread() {
  3887  	_g_ := getg()
  3888  	if _g_.m.lockedExt == 0 {
  3889  		return
  3890  	}
  3891  	_g_.m.lockedExt--
  3892  	dounlockOSThread()
  3893  }
  3894  
  3895  //go:nosplit
  3896  func unlockOSThread() {
  3897  	_g_ := getg()
  3898  	if _g_.m.lockedInt == 0 {
  3899  		systemstack(badunlockosthread)
  3900  	}
  3901  	_g_.m.lockedInt--
  3902  	dounlockOSThread()
  3903  }
  3904  
  3905  func badunlockosthread() {
  3906  	throw("runtime: internal error: misuse of lockOSThread/unlockOSThread")
  3907  }
  3908  
  3909  func gcount() int32 {
  3910  	n := int32(allglen) - sched.gFree.n - int32(atomic.Load(&sched.ngsys))
  3911  	for _, _p_ := range allp {
  3912  		n -= _p_.gFree.n
  3913  	}
  3914  
  3915  	// All these variables can be changed concurrently, so the result can be inconsistent.
  3916  	// But at least the current goroutine is running.
  3917  	if n < 1 {
  3918  		n = 1
  3919  	}
  3920  	return n
  3921  }
  3922  
  3923  func mcount() int32 {
  3924  	return int32(sched.mnext - sched.nmfreed)
  3925  }
  3926  
  3927  var prof struct {
  3928  	signalLock uint32
  3929  	hz         int32
  3930  }
  3931  
  3932  func _System()                    { _System() }
  3933  func _ExternalCode()              { _ExternalCode() }
  3934  func _LostExternalCode()          { _LostExternalCode() }
  3935  func _GC()                        { _GC() }
  3936  func _LostSIGPROFDuringAtomic64() { _LostSIGPROFDuringAtomic64() }
  3937  func _VDSO()                      { _VDSO() }
  3938  
  3939  // Called if we receive a SIGPROF signal.
  3940  // Called by the signal handler, may run during STW.
  3941  //go:nowritebarrierrec
  3942  func sigprof(pc, sp, lr uintptr, gp *g, mp *m) {
  3943  	if prof.hz == 0 {
  3944  		return
  3945  	}
  3946  
  3947  	// On mips{,le}, 64bit atomics are emulated with spinlocks, in
  3948  	// runtime/internal/atomic. If SIGPROF arrives while the program is inside
  3949  	// the critical section, it creates a deadlock (when writing the sample).
  3950  	// As a workaround, create a counter of SIGPROFs while in critical section
  3951  	// to store the count, and pass it to sigprof.add() later when SIGPROF is
  3952  	// received from somewhere else (with _LostSIGPROFDuringAtomic64 as pc).
  3953  	if GOARCH == "mips" || GOARCH == "mipsle" || GOARCH == "arm" {
  3954  		if f := findfunc(pc); f.valid() {
  3955  			if hasPrefix(funcname(f), "runtime/internal/atomic") {
  3956  				cpuprof.lostAtomic++
  3957  				return
  3958  			}
  3959  		}
  3960  	}
  3961  
  3962  	// Profiling runs concurrently with GC, so it must not allocate.
  3963  	// Set a trap in case the code does allocate.
  3964  	// Note that on windows, one thread takes profiles of all the
  3965  	// other threads, so mp is usually not getg().m.
  3966  	// In fact mp may not even be stopped.
  3967  	// See golang.org/issue/17165.
  3968  	getg().m.mallocing++
  3969  
  3970  	// Define that a "user g" is a user-created goroutine, and a "system g"
  3971  	// is one that is m->g0 or m->gsignal.
  3972  	//
  3973  	// We might be interrupted for profiling halfway through a
  3974  	// goroutine switch. The switch involves updating three (or four) values:
  3975  	// g, PC, SP, and (on arm) LR. The PC must be the last to be updated,
  3976  	// because once it gets updated the new g is running.
  3977  	//
  3978  	// When switching from a user g to a system g, LR is not considered live,
  3979  	// so the update only affects g, SP, and PC. Since PC must be last, there
  3980  	// the possible partial transitions in ordinary execution are (1) g alone is updated,
  3981  	// (2) both g and SP are updated, and (3) SP alone is updated.
  3982  	// If SP or g alone is updated, we can detect the partial transition by checking
  3983  	// whether the SP is within g's stack bounds. (We could also require that SP
  3984  	// be changed only after g, but the stack bounds check is needed by other
  3985  	// cases, so there is no need to impose an additional requirement.)
  3986  	//
  3987  	// There is one exceptional transition to a system g, not in ordinary execution.
  3988  	// When a signal arrives, the operating system starts the signal handler running
  3989  	// with an updated PC and SP. The g is updated last, at the beginning of the
  3990  	// handler. There are two reasons this is okay. First, until g is updated the
  3991  	// g and SP do not match, so the stack bounds check detects the partial transition.
  3992  	// Second, signal handlers currently run with signals disabled, so a profiling
  3993  	// signal cannot arrive during the handler.
  3994  	//
  3995  	// When switching from a system g to a user g, there are three possibilities.
  3996  	//
  3997  	// First, it may be that the g switch has no PC update, because the SP
  3998  	// either corresponds to a user g throughout (as in asmcgocall)
  3999  	// or because it has been arranged to look like a user g frame
  4000  	// (as in cgocallback_gofunc). In this case, since the entire
  4001  	// transition is a g+SP update, a partial transition updating just one of
  4002  	// those will be detected by the stack bounds check.
  4003  	//
  4004  	// Second, when returning from a signal handler, the PC and SP updates
  4005  	// are performed by the operating system in an atomic update, so the g
  4006  	// update must be done before them. The stack bounds check detects
  4007  	// the partial transition here, and (again) signal handlers run with signals
  4008  	// disabled, so a profiling signal cannot arrive then anyway.
  4009  	//
  4010  	// Third, the common case: it may be that the switch updates g, SP, and PC
  4011  	// separately. If the PC is within any of the functions that does this,
  4012  	// we don't ask for a traceback. C.F. the function setsSP for more about this.
  4013  	//
  4014  	// There is another apparently viable approach, recorded here in case
  4015  	// the "PC within setsSP function" check turns out not to be usable.
  4016  	// It would be possible to delay the update of either g or SP until immediately
  4017  	// before the PC update instruction. Then, because of the stack bounds check,
  4018  	// the only problematic interrupt point is just before that PC update instruction,
  4019  	// and the sigprof handler can detect that instruction and simulate stepping past
  4020  	// it in order to reach a consistent state. On ARM, the update of g must be made
  4021  	// in two places (in R10 and also in a TLS slot), so the delayed update would
  4022  	// need to be the SP update. The sigprof handler must read the instruction at
  4023  	// the current PC and if it was the known instruction (for example, JMP BX or
  4024  	// MOV R2, PC), use that other register in place of the PC value.
  4025  	// The biggest drawback to this solution is that it requires that we can tell
  4026  	// whether it's safe to read from the memory pointed at by PC.
  4027  	// In a correct program, we can test PC == nil and otherwise read,
  4028  	// but if a profiling signal happens at the instant that a program executes
  4029  	// a bad jump (before the program manages to handle the resulting fault)
  4030  	// the profiling handler could fault trying to read nonexistent memory.
  4031  	//
  4032  	// To recap, there are no constraints on the assembly being used for the
  4033  	// transition. We simply require that g and SP match and that the PC is not
  4034  	// in gogo.
  4035  	traceback := true
  4036  	if gp == nil || sp < gp.stack.lo || gp.stack.hi < sp || setsSP(pc) || (mp != nil && mp.vdsoSP != 0) {
  4037  		traceback = false
  4038  	}
  4039  	var stk [maxCPUProfStack]uintptr
  4040  	n := 0
  4041  	if mp.ncgo > 0 && mp.curg != nil && mp.curg.syscallpc != 0 && mp.curg.syscallsp != 0 {
  4042  		cgoOff := 0
  4043  		// Check cgoCallersUse to make sure that we are not
  4044  		// interrupting other code that is fiddling with
  4045  		// cgoCallers.  We are running in a signal handler
  4046  		// with all signals blocked, so we don't have to worry
  4047  		// about any other code interrupting us.
  4048  		if atomic.Load(&mp.cgoCallersUse) == 0 && mp.cgoCallers != nil && mp.cgoCallers[0] != 0 {
  4049  			for cgoOff < len(mp.cgoCallers) && mp.cgoCallers[cgoOff] != 0 {
  4050  				cgoOff++
  4051  			}
  4052  			copy(stk[:], mp.cgoCallers[:cgoOff])
  4053  			mp.cgoCallers[0] = 0
  4054  		}
  4055  
  4056  		// Collect Go stack that leads to the cgo call.
  4057  		n = gentraceback(mp.curg.syscallpc, mp.curg.syscallsp, 0, mp.curg, 0, &stk[cgoOff], len(stk)-cgoOff, nil, nil, 0)
  4058  		if n > 0 {
  4059  			n += cgoOff
  4060  		}
  4061  	} else if traceback {
  4062  		n = gentraceback(pc, sp, lr, gp, 0, &stk[0], len(stk), nil, nil, _TraceTrap|_TraceJumpStack)
  4063  	}
  4064  
  4065  	if n <= 0 {
  4066  		// Normal traceback is impossible or has failed.
  4067  		// See if it falls into several common cases.
  4068  		n = 0
  4069  		if (GOOS == "windows" || GOOS == "solaris" || GOOS == "illumos" || GOOS == "darwin" || GOOS == "aix") && mp.libcallg != 0 && mp.libcallpc != 0 && mp.libcallsp != 0 {
  4070  			// Libcall, i.e. runtime syscall on windows.
  4071  			// Collect Go stack that leads to the call.
  4072  			n = gentraceback(mp.libcallpc, mp.libcallsp, 0, mp.libcallg.ptr(), 0, &stk[0], len(stk), nil, nil, 0)
  4073  		}
  4074  		if n == 0 && mp != nil && mp.vdsoSP != 0 {
  4075  			n = gentraceback(mp.vdsoPC, mp.vdsoSP, 0, gp, 0, &stk[0], len(stk), nil, nil, _TraceTrap|_TraceJumpStack)
  4076  		}
  4077  		if n == 0 {
  4078  			// If all of the above has failed, account it against abstract "System" or "GC".
  4079  			n = 2
  4080  			if inVDSOPage(pc) {
  4081  				pc = funcPC(_VDSO) + sys.PCQuantum
  4082  			} else if pc > firstmoduledata.etext {
  4083  				// "ExternalCode" is better than "etext".
  4084  				pc = funcPC(_ExternalCode) + sys.PCQuantum
  4085  			}
  4086  			stk[0] = pc
  4087  			if mp.preemptoff != "" {
  4088  				stk[1] = funcPC(_GC) + sys.PCQuantum
  4089  			} else {
  4090  				stk[1] = funcPC(_System) + sys.PCQuantum
  4091  			}
  4092  		}
  4093  	}
  4094  
  4095  	if prof.hz != 0 {
  4096  		cpuprof.add(gp, stk[:n])
  4097  	}
  4098  	getg().m.mallocing--
  4099  }
  4100  
  4101  // If the signal handler receives a SIGPROF signal on a non-Go thread,
  4102  // it tries to collect a traceback into sigprofCallers.
  4103  // sigprofCallersUse is set to non-zero while sigprofCallers holds a traceback.
  4104  var sigprofCallers cgoCallers
  4105  var sigprofCallersUse uint32
  4106  
  4107  // sigprofNonGo is called if we receive a SIGPROF signal on a non-Go thread,
  4108  // and the signal handler collected a stack trace in sigprofCallers.
  4109  // When this is called, sigprofCallersUse will be non-zero.
  4110  // g is nil, and what we can do is very limited.
  4111  //go:nosplit
  4112  //go:nowritebarrierrec
  4113  func sigprofNonGo() {
  4114  	if prof.hz != 0 {
  4115  		n := 0
  4116  		for n < len(sigprofCallers) && sigprofCallers[n] != 0 {
  4117  			n++
  4118  		}
  4119  		cpuprof.addNonGo(sigprofCallers[:n])
  4120  	}
  4121  
  4122  	atomic.Store(&sigprofCallersUse, 0)
  4123  }
  4124  
  4125  // sigprofNonGoPC is called when a profiling signal arrived on a
  4126  // non-Go thread and we have a single PC value, not a stack trace.
  4127  // g is nil, and what we can do is very limited.
  4128  //go:nosplit
  4129  //go:nowritebarrierrec
  4130  func sigprofNonGoPC(pc uintptr) {
  4131  	if prof.hz != 0 {
  4132  		stk := []uintptr{
  4133  			pc,
  4134  			funcPC(_ExternalCode) + sys.PCQuantum,
  4135  		}
  4136  		cpuprof.addNonGo(stk)
  4137  	}
  4138  }
  4139  
  4140  // Reports whether a function will set the SP
  4141  // to an absolute value. Important that
  4142  // we don't traceback when these are at the bottom
  4143  // of the stack since we can't be sure that we will
  4144  // find the caller.
  4145  //
  4146  // If the function is not on the bottom of the stack
  4147  // we assume that it will have set it up so that traceback will be consistent,
  4148  // either by being a traceback terminating function
  4149  // or putting one on the stack at the right offset.
  4150  func setsSP(pc uintptr) bool {
  4151  	f := findfunc(pc)
  4152  	if !f.valid() {
  4153  		// couldn't find the function for this PC,
  4154  		// so assume the worst and stop traceback
  4155  		return true
  4156  	}
  4157  	switch f.funcID {
  4158  	case funcID_gogo, funcID_systemstack, funcID_mcall, funcID_morestack:
  4159  		return true
  4160  	}
  4161  	return false
  4162  }
  4163  
  4164  // setcpuprofilerate sets the CPU profiling rate to hz times per second.
  4165  // If hz <= 0, setcpuprofilerate turns off CPU profiling.
  4166  func setcpuprofilerate(hz int32) {
  4167  	// Force sane arguments.
  4168  	if hz < 0 {
  4169  		hz = 0
  4170  	}
  4171  
  4172  	// Disable preemption, otherwise we can be rescheduled to another thread
  4173  	// that has profiling enabled.
  4174  	_g_ := getg()
  4175  	_g_.m.locks++
  4176  
  4177  	// Stop profiler on this thread so that it is safe to lock prof.
  4178  	// if a profiling signal came in while we had prof locked,
  4179  	// it would deadlock.
  4180  	setThreadCPUProfiler(0)
  4181  
  4182  	for !atomic.Cas(&prof.signalLock, 0, 1) {
  4183  		osyield()
  4184  	}
  4185  	if prof.hz != hz {
  4186  		setProcessCPUProfiler(hz)
  4187  		prof.hz = hz
  4188  	}
  4189  	atomic.Store(&prof.signalLock, 0)
  4190  
  4191  	lock(&sched.lock)
  4192  	sched.profilehz = hz
  4193  	unlock(&sched.lock)
  4194  
  4195  	if hz != 0 {
  4196  		setThreadCPUProfiler(hz)
  4197  	}
  4198  
  4199  	_g_.m.locks--
  4200  }
  4201  
  4202  // init initializes pp, which may be a freshly allocated p or a
  4203  // previously destroyed p, and transitions it to status _Pgcstop.
  4204  func (pp *p) init(id int32) {
  4205  	pp.id = id
  4206  	pp.status = _Pgcstop
  4207  	pp.sudogcache = pp.sudogbuf[:0]
  4208  	for i := range pp.deferpool {
  4209  		pp.deferpool[i] = pp.deferpoolbuf[i][:0]
  4210  	}
  4211  	pp.wbBuf.reset()
  4212  	if pp.mcache == nil {
  4213  		if id == 0 {
  4214  			if mcache0 == nil {
  4215  				throw("missing mcache?")
  4216  			}
  4217  			// Use the bootstrap mcache0. Only one P will get
  4218  			// mcache0: the one with ID 0.
  4219  			pp.mcache = mcache0
  4220  		} else {
  4221  			pp.mcache = allocmcache()
  4222  		}
  4223  	}
  4224  	if raceenabled && pp.raceprocctx == 0 {
  4225  		if id == 0 {
  4226  			pp.raceprocctx = raceprocctx0
  4227  			raceprocctx0 = 0 // bootstrap
  4228  		} else {
  4229  			pp.raceprocctx = raceproccreate()
  4230  		}
  4231  	}
  4232  	lockInit(&pp.timersLock, lockRankTimers)
  4233  }
  4234  
  4235  // destroy releases all of the resources associated with pp and
  4236  // transitions it to status _Pdead.
  4237  //
  4238  // sched.lock must be held and the world must be stopped.
  4239  func (pp *p) destroy() {
  4240  	// Move all runnable goroutines to the global queue
  4241  	for pp.runqhead != pp.runqtail {
  4242  		// Pop from tail of local queue
  4243  		pp.runqtail--
  4244  		gp := pp.runq[pp.runqtail%uint32(len(pp.runq))].ptr()
  4245  		// Push onto head of global queue
  4246  		globrunqputhead(gp)
  4247  	}
  4248  	if pp.runnext != 0 {
  4249  		globrunqputhead(pp.runnext.ptr())
  4250  		pp.runnext = 0
  4251  	}
  4252  	if len(pp.timers) > 0 {
  4253  		plocal := getg().m.p.ptr()
  4254  		// The world is stopped, but we acquire timersLock to
  4255  		// protect against sysmon calling timeSleepUntil.
  4256  		// This is the only case where we hold the timersLock of
  4257  		// more than one P, so there are no deadlock concerns.
  4258  		lock(&plocal.timersLock)
  4259  		lock(&pp.timersLock)
  4260  		moveTimers(plocal, pp.timers)
  4261  		pp.timers = nil
  4262  		pp.numTimers = 0
  4263  		pp.adjustTimers = 0
  4264  		pp.deletedTimers = 0
  4265  		atomic.Store64(&pp.timer0When, 0)
  4266  		unlock(&pp.timersLock)
  4267  		unlock(&plocal.timersLock)
  4268  	}
  4269  	// If there's a background worker, make it runnable and put
  4270  	// it on the global queue so it can clean itself up.
  4271  	if gp := pp.gcBgMarkWorker.ptr(); gp != nil {
  4272  		casgstatus(gp, _Gwaiting, _Grunnable)
  4273  		if trace.enabled {
  4274  			traceGoUnpark(gp, 0)
  4275  		}
  4276  		globrunqput(gp)
  4277  		// This assignment doesn't race because the
  4278  		// world is stopped.
  4279  		pp.gcBgMarkWorker.set(nil)
  4280  	}
  4281  	// Flush p's write barrier buffer.
  4282  	if gcphase != _GCoff {
  4283  		wbBufFlush1(pp)
  4284  		pp.gcw.dispose()
  4285  	}
  4286  	for i := range pp.sudogbuf {
  4287  		pp.sudogbuf[i] = nil
  4288  	}
  4289  	pp.sudogcache = pp.sudogbuf[:0]
  4290  	for i := range pp.deferpool {
  4291  		for j := range pp.deferpoolbuf[i] {
  4292  			pp.deferpoolbuf[i][j] = nil
  4293  		}
  4294  		pp.deferpool[i] = pp.deferpoolbuf[i][:0]
  4295  	}
  4296  	systemstack(func() {
  4297  		for i := 0; i < pp.mspancache.len; i++ {
  4298  			// Safe to call since the world is stopped.
  4299  			mheap_.spanalloc.free(unsafe.Pointer(pp.mspancache.buf[i]))
  4300  		}
  4301  		pp.mspancache.len = 0
  4302  		pp.pcache.flush(&mheap_.pages)
  4303  	})
  4304  	freemcache(pp.mcache)
  4305  	pp.mcache = nil
  4306  	gfpurge(pp)
  4307  	traceProcFree(pp)
  4308  	if raceenabled {
  4309  		if pp.timerRaceCtx != 0 {
  4310  			// The race detector code uses a callback to fetch
  4311  			// the proc context, so arrange for that callback
  4312  			// to see the right thing.
  4313  			// This hack only works because we are the only
  4314  			// thread running.
  4315  			mp := getg().m
  4316  			phold := mp.p.ptr()
  4317  			mp.p.set(pp)
  4318  
  4319  			racectxend(pp.timerRaceCtx)
  4320  			pp.timerRaceCtx = 0
  4321  
  4322  			mp.p.set(phold)
  4323  		}
  4324  		raceprocdestroy(pp.raceprocctx)
  4325  		pp.raceprocctx = 0
  4326  	}
  4327  	pp.gcAssistTime = 0
  4328  	pp.status = _Pdead
  4329  }
  4330  
  4331  // Change number of processors. The world is stopped, sched is locked.
  4332  // gcworkbufs are not being modified by either the GC or
  4333  // the write barrier code.
  4334  // Returns list of Ps with local work, they need to be scheduled by the caller.
  4335  func procresize(nprocs int32) *p {
  4336  	old := gomaxprocs
  4337  	if old < 0 || nprocs <= 0 {
  4338  		throw("procresize: invalid arg")
  4339  	}
  4340  	if trace.enabled {
  4341  		traceGomaxprocs(nprocs)
  4342  	}
  4343  
  4344  	// update statistics
  4345  	now := nanotime()
  4346  	if sched.procresizetime != 0 {
  4347  		sched.totaltime += int64(old) * (now - sched.procresizetime)
  4348  	}
  4349  	sched.procresizetime = now
  4350  
  4351  	// Grow allp if necessary.
  4352  	if nprocs > int32(len(allp)) {
  4353  		// Synchronize with retake, which could be running
  4354  		// concurrently since it doesn't run on a P.
  4355  		lock(&allpLock)
  4356  		if nprocs <= int32(cap(allp)) {
  4357  			allp = allp[:nprocs]
  4358  		} else {
  4359  			nallp := make([]*p, nprocs)
  4360  			// Copy everything up to allp's cap so we
  4361  			// never lose old allocated Ps.
  4362  			copy(nallp, allp[:cap(allp)])
  4363  			allp = nallp
  4364  		}
  4365  		unlock(&allpLock)
  4366  	}
  4367  
  4368  	// initialize new P's
  4369  	for i := old; i < nprocs; i++ {
  4370  		pp := allp[i]
  4371  		if pp == nil {
  4372  			pp = new(p)
  4373  		}
  4374  		pp.init(i)
  4375  		atomicstorep(unsafe.Pointer(&allp[i]), unsafe.Pointer(pp))
  4376  	}
  4377  
  4378  	_g_ := getg()
  4379  	if _g_.m.p != 0 && _g_.m.p.ptr().id < nprocs {
  4380  		// continue to use the current P
  4381  		_g_.m.p.ptr().status = _Prunning
  4382  		_g_.m.p.ptr().mcache.prepareForSweep()
  4383  	} else {
  4384  		// release the current P and acquire allp[0].
  4385  		//
  4386  		// We must do this before destroying our current P
  4387  		// because p.destroy itself has write barriers, so we
  4388  		// need to do that from a valid P.
  4389  		if _g_.m.p != 0 {
  4390  			if trace.enabled {
  4391  				// Pretend that we were descheduled
  4392  				// and then scheduled again to keep
  4393  				// the trace sane.
  4394  				traceGoSched()
  4395  				traceProcStop(_g_.m.p.ptr())
  4396  			}
  4397  			_g_.m.p.ptr().m = 0
  4398  		}
  4399  		_g_.m.p = 0
  4400  		p := allp[0]
  4401  		p.m = 0
  4402  		p.status = _Pidle
  4403  		acquirep(p)
  4404  		if trace.enabled {
  4405  			traceGoStart()
  4406  		}
  4407  	}
  4408  
  4409  	// g.m.p is now set, so we no longer need mcache0 for bootstrapping.
  4410  	mcache0 = nil
  4411  
  4412  	// release resources from unused P's
  4413  	for i := nprocs; i < old; i++ {
  4414  		p := allp[i]
  4415  		p.destroy()
  4416  		// can't free P itself because it can be referenced by an M in syscall
  4417  	}
  4418  
  4419  	// Trim allp.
  4420  	if int32(len(allp)) != nprocs {
  4421  		lock(&allpLock)
  4422  		allp = allp[:nprocs]
  4423  		unlock(&allpLock)
  4424  	}
  4425  
  4426  	var runnablePs *p
  4427  	for i := nprocs - 1; i >= 0; i-- {
  4428  		p := allp[i]
  4429  		if _g_.m.p.ptr() == p {
  4430  			continue
  4431  		}
  4432  		p.status = _Pidle
  4433  		if runqempty(p) {
  4434  			pidleput(p)
  4435  		} else {
  4436  			p.m.set(mget())
  4437  			p.link.set(runnablePs)
  4438  			runnablePs = p
  4439  		}
  4440  	}
  4441  	stealOrder.reset(uint32(nprocs))
  4442  	var int32p *int32 = &gomaxprocs // make compiler check that gomaxprocs is an int32
  4443  	atomic.Store((*uint32)(unsafe.Pointer(int32p)), uint32(nprocs))
  4444  	return runnablePs
  4445  }
  4446  
  4447  // Associate p and the current m.
  4448  //
  4449  // This function is allowed to have write barriers even if the caller
  4450  // isn't because it immediately acquires _p_.
  4451  //
  4452  //go:yeswritebarrierrec
  4453  func acquirep(_p_ *p) {
  4454  	// Do the part that isn't allowed to have write barriers.
  4455  	wirep(_p_)
  4456  
  4457  	// Have p; write barriers now allowed.
  4458  
  4459  	// Perform deferred mcache flush before this P can allocate
  4460  	// from a potentially stale mcache.
  4461  	_p_.mcache.prepareForSweep()
  4462  
  4463  	if trace.enabled {
  4464  		traceProcStart()
  4465  	}
  4466  }
  4467  
  4468  // wirep is the first step of acquirep, which actually associates the
  4469  // current M to _p_. This is broken out so we can disallow write
  4470  // barriers for this part, since we don't yet have a P.
  4471  //
  4472  //go:nowritebarrierrec
  4473  //go:nosplit
  4474  func wirep(_p_ *p) {
  4475  	_g_ := getg()
  4476  
  4477  	if _g_.m.p != 0 {
  4478  		throw("wirep: already in go")
  4479  	}
  4480  	if _p_.m != 0 || _p_.status != _Pidle {
  4481  		id := int64(0)
  4482  		if _p_.m != 0 {
  4483  			id = _p_.m.ptr().id
  4484  		}
  4485  		print("wirep: p->m=", _p_.m, "(", id, ") p->status=", _p_.status, "\n")
  4486  		throw("wirep: invalid p state")
  4487  	}
  4488  	_g_.m.p.set(_p_)
  4489  	_p_.m.set(_g_.m)
  4490  	_p_.status = _Prunning
  4491  }
  4492  
  4493  // Disassociate p and the current m.
  4494  func releasep() *p {
  4495  	_g_ := getg()
  4496  
  4497  	if _g_.m.p == 0 {
  4498  		throw("releasep: invalid arg")
  4499  	}
  4500  	_p_ := _g_.m.p.ptr()
  4501  	if _p_.m.ptr() != _g_.m || _p_.status != _Prunning {
  4502  		print("releasep: m=", _g_.m, " m->p=", _g_.m.p.ptr(), " p->m=", hex(_p_.m), " p->status=", _p_.status, "\n")
  4503  		throw("releasep: invalid p state")
  4504  	}
  4505  	if trace.enabled {
  4506  		traceProcStop(_g_.m.p.ptr())
  4507  	}
  4508  	_g_.m.p = 0
  4509  	_p_.m = 0
  4510  	_p_.status = _Pidle
  4511  	return _p_
  4512  }
  4513  
  4514  func incidlelocked(v int32) {
  4515  	lock(&sched.lock)
  4516  	sched.nmidlelocked += v
  4517  	if v > 0 {
  4518  		checkdead()
  4519  	}
  4520  	unlock(&sched.lock)
  4521  }
  4522  
  4523  // Check for deadlock situation.
  4524  // The check is based on number of running M's, if 0 -> deadlock.
  4525  // sched.lock must be held.
  4526  func checkdead() {
  4527  	// For -buildmode=c-shared or -buildmode=c-archive it's OK if
  4528  	// there are no running goroutines. The calling program is
  4529  	// assumed to be running.
  4530  	if islibrary || isarchive {
  4531  		return
  4532  	}
  4533  
  4534  	// If we are dying because of a signal caught on an already idle thread,
  4535  	// freezetheworld will cause all running threads to block.
  4536  	// And runtime will essentially enter into deadlock state,
  4537  	// except that there is a thread that will call exit soon.
  4538  	if panicking > 0 {
  4539  		return
  4540  	}
  4541  
  4542  	// If we are not running under cgo, but we have an extra M then account
  4543  	// for it. (It is possible to have an extra M on Windows without cgo to
  4544  	// accommodate callbacks created by syscall.NewCallback. See issue #6751
  4545  	// for details.)
  4546  	var run0 int32
  4547  	if !iscgo && cgoHasExtraM {
  4548  		mp := lockextra(true)
  4549  		haveExtraM := extraMCount > 0
  4550  		unlockextra(mp)
  4551  		if haveExtraM {
  4552  			run0 = 1
  4553  		}
  4554  	}
  4555  
  4556  	run := mcount() - sched.nmidle - sched.nmidlelocked - sched.nmsys
  4557  	if run > run0 {
  4558  		return
  4559  	}
  4560  	if run < 0 {
  4561  		print("runtime: checkdead: nmidle=", sched.nmidle, " nmidlelocked=", sched.nmidlelocked, " mcount=", mcount(), " nmsys=", sched.nmsys, "\n")
  4562  		throw("checkdead: inconsistent counts")
  4563  	}
  4564  
  4565  	grunning := 0
  4566  	lock(&allglock)
  4567  	for i := 0; i < len(allgs); i++ {
  4568  		gp := allgs[i]
  4569  		if isSystemGoroutine(gp, false) {
  4570  			continue
  4571  		}
  4572  		s := readgstatus(gp)
  4573  		switch s &^ _Gscan {
  4574  		case _Gwaiting,
  4575  			_Gpreempted:
  4576  			grunning++
  4577  		case _Grunnable,
  4578  			_Grunning,
  4579  			_Gsyscall:
  4580  			unlock(&allglock)
  4581  			print("runtime: checkdead: find g ", gp.goid, " in status ", s, "\n")
  4582  			throw("checkdead: runnable g")
  4583  		}
  4584  	}
  4585  	unlock(&allglock)
  4586  	if grunning == 0 { // possible if main goroutine calls runtime·Goexit()
  4587  		unlock(&sched.lock) // unlock so that GODEBUG=scheddetail=1 doesn't hang
  4588  		throw("no goroutines (main called runtime.Goexit) - deadlock!")
  4589  	}
  4590  
  4591  	// Maybe jump time forward for playground.
  4592  	if faketime != 0 {
  4593  		when, _p_ := timeSleepUntil()
  4594  		if _p_ != nil {
  4595  			faketime = when
  4596  			for pp := &sched.pidle; *pp != 0; pp = &(*pp).ptr().link {
  4597  				if (*pp).ptr() == _p_ {
  4598  					*pp = _p_.link
  4599  					break
  4600  				}
  4601  			}
  4602  			mp := mget()
  4603  			if mp == nil {
  4604  				// There should always be a free M since
  4605  				// nothing is running.
  4606  				throw("checkdead: no m for timer")
  4607  			}
  4608  			mp.nextp.set(_p_)
  4609  			notewakeup(&mp.park)
  4610  			return
  4611  		}
  4612  	}
  4613  
  4614  	// There are no goroutines running, so we can look at the P's.
  4615  	for _, _p_ := range allp {
  4616  		if len(_p_.timers) > 0 {
  4617  			return
  4618  		}
  4619  	}
  4620  
  4621  	getg().m.throwing = -1 // do not dump full stacks
  4622  	unlock(&sched.lock)    // unlock so that GODEBUG=scheddetail=1 doesn't hang
  4623  	throw("all goroutines are asleep - deadlock!")
  4624  }
  4625  
  4626  // forcegcperiod is the maximum time in nanoseconds between garbage
  4627  // collections. If we go this long without a garbage collection, one
  4628  // is forced to run.
  4629  //
  4630  // This is a variable for testing purposes. It normally doesn't change.
  4631  var forcegcperiod int64 = 2 * 60 * 1e9
  4632  
  4633  // Always runs without a P, so write barriers are not allowed.
  4634  //
  4635  //go:nowritebarrierrec
  4636  func sysmon() {
  4637  	lock(&sched.lock)
  4638  	sched.nmsys++
  4639  	checkdead()
  4640  	unlock(&sched.lock)
  4641  
  4642  	lasttrace := int64(0)
  4643  	idle := 0 // how many cycles in succession we had not wokeup somebody
  4644  	delay := uint32(0)
  4645  	for {
  4646  		if idle == 0 { // start with 20us sleep...
  4647  			delay = 20
  4648  		} else if idle > 50 { // start doubling the sleep after 1ms...
  4649  			delay *= 2
  4650  		}
  4651  		if delay > 10*1000 { // up to 10ms
  4652  			delay = 10 * 1000
  4653  		}
  4654  		usleep(delay)
  4655  		now := nanotime()
  4656  		next, _ := timeSleepUntil()
  4657  		if debug.schedtrace <= 0 && (sched.gcwaiting != 0 || atomic.Load(&sched.npidle) == uint32(gomaxprocs)) {
  4658  			lock(&sched.lock)
  4659  			if atomic.Load(&sched.gcwaiting) != 0 || atomic.Load(&sched.npidle) == uint32(gomaxprocs) {
  4660  				if next > now {
  4661  					atomic.Store(&sched.sysmonwait, 1)
  4662  					unlock(&sched.lock)
  4663  					// Make wake-up period small enough
  4664  					// for the sampling to be correct.
  4665  					sleep := forcegcperiod / 2
  4666  					if next-now < sleep {
  4667  						sleep = next - now
  4668  					}
  4669  					shouldRelax := sleep >= osRelaxMinNS
  4670  					if shouldRelax {
  4671  						osRelax(true)
  4672  					}
  4673  					notetsleep(&sched.sysmonnote, sleep)
  4674  					if shouldRelax {
  4675  						osRelax(false)
  4676  					}
  4677  					now = nanotime()
  4678  					next, _ = timeSleepUntil()
  4679  					lock(&sched.lock)
  4680  					atomic.Store(&sched.sysmonwait, 0)
  4681  					noteclear(&sched.sysmonnote)
  4682  				}
  4683  				idle = 0
  4684  				delay = 20
  4685  			}
  4686  			unlock(&sched.lock)
  4687  		}
  4688  		lock(&sched.sysmonlock)
  4689  		{
  4690  			// If we spent a long time blocked on sysmonlock
  4691  			// then we want to update now and next since it's
  4692  			// likely stale.
  4693  			now1 := nanotime()
  4694  			if now1-now > 50*1000 /* 50µs */ {
  4695  				next, _ = timeSleepUntil()
  4696  			}
  4697  			now = now1
  4698  		}
  4699  
  4700  		// trigger libc interceptors if needed
  4701  		if *cgo_yield != nil {
  4702  			asmcgocall(*cgo_yield, nil)
  4703  		}
  4704  		// poll network if not polled for more than 10ms
  4705  		lastpoll := int64(atomic.Load64(&sched.lastpoll))
  4706  		if netpollinited() && lastpoll != 0 && lastpoll+10*1000*1000 < now {
  4707  			atomic.Cas64(&sched.lastpoll, uint64(lastpoll), uint64(now))
  4708  			list := netpoll(0) // non-blocking - returns list of goroutines
  4709  			if !list.empty() {
  4710  				// Need to decrement number of idle locked M's
  4711  				// (pretending that one more is running) before injectglist.
  4712  				// Otherwise it can lead to the following situation:
  4713  				// injectglist grabs all P's but before it starts M's to run the P's,
  4714  				// another M returns from syscall, finishes running its G,
  4715  				// observes that there is no work to do and no other running M's
  4716  				// and reports deadlock.
  4717  				incidlelocked(-1)
  4718  				injectglist(&list)
  4719  				incidlelocked(1)
  4720  			}
  4721  		}
  4722  		if next < now {
  4723  			// There are timers that should have already run,
  4724  			// perhaps because there is an unpreemptible P.
  4725  			// Try to start an M to run them.
  4726  			startm(nil, false)
  4727  		}
  4728  		if atomic.Load(&scavenge.sysmonWake) != 0 {
  4729  			// Kick the scavenger awake if someone requested it.
  4730  			wakeScavenger()
  4731  		}
  4732  		// retake P's blocked in syscalls
  4733  		// and preempt long running G's
  4734  		if retake(now) != 0 {
  4735  			idle = 0
  4736  		} else {
  4737  			idle++
  4738  		}
  4739  		// check if we need to force a GC
  4740  		if t := (gcTrigger{kind: gcTriggerTime, now: now}); t.test() && atomic.Load(&forcegc.idle) != 0 {
  4741  			lock(&forcegc.lock)
  4742  			forcegc.idle = 0
  4743  			var list gList
  4744  			list.push(forcegc.g)
  4745  			injectglist(&list)
  4746  			unlock(&forcegc.lock)
  4747  		}
  4748  		if debug.schedtrace > 0 && lasttrace+int64(debug.schedtrace)*1000000 <= now {
  4749  			lasttrace = now
  4750  			schedtrace(debug.scheddetail > 0)
  4751  		}
  4752  		unlock(&sched.sysmonlock)
  4753  	}
  4754  }
  4755  
  4756  type sysmontick struct {
  4757  	schedtick   uint32
  4758  	schedwhen   int64
  4759  	syscalltick uint32
  4760  	syscallwhen int64
  4761  }
  4762  
  4763  // forcePreemptNS is the time slice given to a G before it is
  4764  // preempted.
  4765  const forcePreemptNS = 10 * 1000 * 1000 // 10ms
  4766  
  4767  func retake(now int64) uint32 {
  4768  	n := 0
  4769  	// Prevent allp slice changes. This lock will be completely
  4770  	// uncontended unless we're already stopping the world.
  4771  	lock(&allpLock)
  4772  	// We can't use a range loop over allp because we may
  4773  	// temporarily drop the allpLock. Hence, we need to re-fetch
  4774  	// allp each time around the loop.
  4775  	for i := 0; i < len(allp); i++ {
  4776  		_p_ := allp[i]
  4777  		if _p_ == nil {
  4778  			// This can happen if procresize has grown
  4779  			// allp but not yet created new Ps.
  4780  			continue
  4781  		}
  4782  		pd := &_p_.sysmontick
  4783  		s := _p_.status
  4784  		sysretake := false
  4785  		if s == _Prunning || s == _Psyscall {
  4786  			// Preempt G if it's running for too long.
  4787  			t := int64(_p_.schedtick)
  4788  			if int64(pd.schedtick) != t {
  4789  				pd.schedtick = uint32(t)
  4790  				pd.schedwhen = now
  4791  			} else if pd.schedwhen+forcePreemptNS <= now {
  4792  				preemptone(_p_)
  4793  				// In case of syscall, preemptone() doesn't
  4794  				// work, because there is no M wired to P.
  4795  				sysretake = true
  4796  			}
  4797  		}
  4798  		if s == _Psyscall {
  4799  			// Retake P from syscall if it's there for more than 1 sysmon tick (at least 20us).
  4800  			t := int64(_p_.syscalltick)
  4801  			if !sysretake && int64(pd.syscalltick) != t {
  4802  				pd.syscalltick = uint32(t)
  4803  				pd.syscallwhen = now
  4804  				continue
  4805  			}
  4806  			// On the one hand we don't want to retake Ps if there is no other work to do,
  4807  			// but on the other hand we want to retake them eventually
  4808  			// because they can prevent the sysmon thread from deep sleep.
  4809  			if runqempty(_p_) && atomic.Load(&sched.nmspinning)+atomic.Load(&sched.npidle) > 0 && pd.syscallwhen+10*1000*1000 > now {
  4810  				continue
  4811  			}
  4812  			// Drop allpLock so we can take sched.lock.
  4813  			unlock(&allpLock)
  4814  			// Need to decrement number of idle locked M's
  4815  			// (pretending that one more is running) before the CAS.
  4816  			// Otherwise the M from which we retake can exit the syscall,
  4817  			// increment nmidle and report deadlock.
  4818  			incidlelocked(-1)
  4819  			if atomic.Cas(&_p_.status, s, _Pidle) {
  4820  				if trace.enabled {
  4821  					traceGoSysBlock(_p_)
  4822  					traceProcStop(_p_)
  4823  				}
  4824  				n++
  4825  				_p_.syscalltick++
  4826  				handoffp(_p_)
  4827  			}
  4828  			incidlelocked(1)
  4829  			lock(&allpLock)
  4830  		}
  4831  	}
  4832  	unlock(&allpLock)
  4833  	return uint32(n)
  4834  }
  4835  
  4836  // Tell all goroutines that they have been preempted and they should stop.
  4837  // This function is purely best-effort. It can fail to inform a goroutine if a
  4838  // processor just started running it.
  4839  // No locks need to be held.
  4840  // Returns true if preemption request was issued to at least one goroutine.
  4841  func preemptall() bool {
  4842  	res := false
  4843  	for _, _p_ := range allp {
  4844  		if _p_.status != _Prunning {
  4845  			continue
  4846  		}
  4847  		if preemptone(_p_) {
  4848  			res = true
  4849  		}
  4850  	}
  4851  	return res
  4852  }
  4853  
  4854  // Tell the goroutine running on processor P to stop.
  4855  // This function is purely best-effort. It can incorrectly fail to inform the
  4856  // goroutine. It can send inform the wrong goroutine. Even if it informs the
  4857  // correct goroutine, that goroutine might ignore the request if it is
  4858  // simultaneously executing newstack.
  4859  // No lock needs to be held.
  4860  // Returns true if preemption request was issued.
  4861  // The actual preemption will happen at some point in the future
  4862  // and will be indicated by the gp->status no longer being
  4863  // Grunning
  4864  func preemptone(_p_ *p) bool {
  4865  	mp := _p_.m.ptr()
  4866  	if mp == nil || mp == getg().m {
  4867  		return false
  4868  	}
  4869  	gp := mp.curg
  4870  	if gp == nil || gp == mp.g0 {
  4871  		return false
  4872  	}
  4873  
  4874  	gp.preempt = true
  4875  
  4876  	// Every call in a go routine checks for stack overflow by
  4877  	// comparing the current stack pointer to gp->stackguard0.
  4878  	// Setting gp->stackguard0 to StackPreempt folds
  4879  	// preemption into the normal stack overflow check.
  4880  	gp.stackguard0 = stackPreempt
  4881  
  4882  	// Request an async preemption of this P.
  4883  	if preemptMSupported && debug.asyncpreemptoff == 0 {
  4884  		_p_.preempt = true
  4885  		preemptM(mp)
  4886  	}
  4887  
  4888  	return true
  4889  }
  4890  
  4891  var starttime int64
  4892  
  4893  func schedtrace(detailed bool) {
  4894  	now := nanotime()
  4895  	if starttime == 0 {
  4896  		starttime = now
  4897  	}
  4898  
  4899  	lock(&sched.lock)
  4900  	print("SCHED ", (now-starttime)/1e6, "ms: gomaxprocs=", gomaxprocs, " idleprocs=", sched.npidle, " threads=", mcount(), " spinningthreads=", sched.nmspinning, " idlethreads=", sched.nmidle, " runqueue=", sched.runqsize)
  4901  	if detailed {
  4902  		print(" gcwaiting=", sched.gcwaiting, " nmidlelocked=", sched.nmidlelocked, " stopwait=", sched.stopwait, " sysmonwait=", sched.sysmonwait, "\n")
  4903  	}
  4904  	// We must be careful while reading data from P's, M's and G's.
  4905  	// Even if we hold schedlock, most data can be changed concurrently.
  4906  	// E.g. (p->m ? p->m->id : -1) can crash if p->m changes from non-nil to nil.
  4907  	for i, _p_ := range allp {
  4908  		mp := _p_.m.ptr()
  4909  		h := atomic.Load(&_p_.runqhead)
  4910  		t := atomic.Load(&_p_.runqtail)
  4911  		if detailed {
  4912  			id := int64(-1)
  4913  			if mp != nil {
  4914  				id = mp.id
  4915  			}
  4916  			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")
  4917  		} else {
  4918  			// In non-detailed mode format lengths of per-P run queues as:
  4919  			// [len1 len2 len3 len4]
  4920  			print(" ")
  4921  			if i == 0 {
  4922  				print("[")
  4923  			}
  4924  			print(t - h)
  4925  			if i == len(allp)-1 {
  4926  				print("]\n")
  4927  			}
  4928  		}
  4929  	}
  4930  
  4931  	if !detailed {
  4932  		unlock(&sched.lock)
  4933  		return
  4934  	}
  4935  
  4936  	for mp := allm; mp != nil; mp = mp.alllink {
  4937  		_p_ := mp.p.ptr()
  4938  		gp := mp.curg
  4939  		lockedg := mp.lockedg.ptr()
  4940  		id1 := int32(-1)
  4941  		if _p_ != nil {
  4942  			id1 = _p_.id
  4943  		}
  4944  		id2 := int64(-1)
  4945  		if gp != nil {
  4946  			id2 = gp.goid
  4947  		}
  4948  		id3 := int64(-1)
  4949  		if lockedg != nil {
  4950  			id3 = lockedg.goid
  4951  		}
  4952  		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")
  4953  	}
  4954  
  4955  	lock(&allglock)
  4956  	for gi := 0; gi < len(allgs); gi++ {
  4957  		gp := allgs[gi]
  4958  		mp := gp.m
  4959  		lockedm := gp.lockedm.ptr()
  4960  		id1 := int64(-1)
  4961  		if mp != nil {
  4962  			id1 = mp.id
  4963  		}
  4964  		id2 := int64(-1)
  4965  		if lockedm != nil {
  4966  			id2 = lockedm.id
  4967  		}
  4968  		print("  G", gp.goid, ": status=", readgstatus(gp), "(", gp.waitreason.String(), ") m=", id1, " lockedm=", id2, "\n")
  4969  	}
  4970  	unlock(&allglock)
  4971  	unlock(&sched.lock)
  4972  }
  4973  
  4974  // schedEnableUser enables or disables the scheduling of user
  4975  // goroutines.
  4976  //
  4977  // This does not stop already running user goroutines, so the caller
  4978  // should first stop the world when disabling user goroutines.
  4979  func schedEnableUser(enable bool) {
  4980  	lock(&sched.lock)
  4981  	if sched.disable.user == !enable {
  4982  		unlock(&sched.lock)
  4983  		return
  4984  	}
  4985  	sched.disable.user = !enable
  4986  	if enable {
  4987  		n := sched.disable.n
  4988  		sched.disable.n = 0
  4989  		globrunqputbatch(&sched.disable.runnable, n)
  4990  		unlock(&sched.lock)
  4991  		for ; n != 0 && sched.npidle != 0; n-- {
  4992  			startm(nil, false)
  4993  		}
  4994  	} else {
  4995  		unlock(&sched.lock)
  4996  	}
  4997  }
  4998  
  4999  // schedEnabled reports whether gp should be scheduled. It returns
  5000  // false is scheduling of gp is disabled.
  5001  func schedEnabled(gp *g) bool {
  5002  	if sched.disable.user {
  5003  		return isSystemGoroutine(gp, true)
  5004  	}
  5005  	return true
  5006  }
  5007  
  5008  // Put mp on midle list.
  5009  // Sched must be locked.
  5010  // May run during STW, so write barriers are not allowed.
  5011  //go:nowritebarrierrec
  5012  func mput(mp *m) {
  5013  	mp.schedlink = sched.midle
  5014  	sched.midle.set(mp)
  5015  	sched.nmidle++
  5016  	checkdead()
  5017  }
  5018  
  5019  // Try to get an m from midle list.
  5020  // Sched must be locked.
  5021  // May run during STW, so write barriers are not allowed.
  5022  //go:nowritebarrierrec
  5023  func mget() *m {
  5024  	mp := sched.midle.ptr()
  5025  	if mp != nil {
  5026  		sched.midle = mp.schedlink
  5027  		sched.nmidle--
  5028  	}
  5029  	return mp
  5030  }
  5031  
  5032  // Put gp on the global runnable queue.
  5033  // Sched must be locked.
  5034  // May run during STW, so write barriers are not allowed.
  5035  //go:nowritebarrierrec
  5036  func globrunqput(gp *g) {
  5037  	sched.runq.pushBack(gp)
  5038  	sched.runqsize++
  5039  }
  5040  
  5041  // Put gp at the head of the global runnable queue.
  5042  // Sched must be locked.
  5043  // May run during STW, so write barriers are not allowed.
  5044  //go:nowritebarrierrec
  5045  func globrunqputhead(gp *g) {
  5046  	sched.runq.push(gp)
  5047  	sched.runqsize++
  5048  }
  5049  
  5050  // Put a batch of runnable goroutines on the global runnable queue.
  5051  // This clears *batch.
  5052  // Sched must be locked.
  5053  func globrunqputbatch(batch *gQueue, n int32) {
  5054  	sched.runq.pushBackAll(*batch)
  5055  	sched.runqsize += n
  5056  	*batch = gQueue{}
  5057  }
  5058  
  5059  // Try get a batch of G's from the global runnable queue.
  5060  // Sched must be locked.
  5061  func globrunqget(_p_ *p, max int32) *g {
  5062  	if sched.runqsize == 0 {
  5063  		return nil
  5064  	}
  5065  
  5066  	n := sched.runqsize/gomaxprocs + 1
  5067  	if n > sched.runqsize {
  5068  		n = sched.runqsize
  5069  	}
  5070  	if max > 0 && n > max {
  5071  		n = max
  5072  	}
  5073  	if n > int32(len(_p_.runq))/2 {
  5074  		n = int32(len(_p_.runq)) / 2
  5075  	}
  5076  
  5077  	sched.runqsize -= n
  5078  
  5079  	gp := sched.runq.pop()
  5080  	n--
  5081  	for ; n > 0; n-- {
  5082  		gp1 := sched.runq.pop()
  5083  		runqput(_p_, gp1, false)
  5084  	}
  5085  	return gp
  5086  }
  5087  
  5088  // Put p to on _Pidle list.
  5089  // Sched must be locked.
  5090  // May run during STW, so write barriers are not allowed.
  5091  //go:nowritebarrierrec
  5092  func pidleput(_p_ *p) {
  5093  	if !runqempty(_p_) {
  5094  		throw("pidleput: P has non-empty run queue")
  5095  	}
  5096  	_p_.link = sched.pidle
  5097  	sched.pidle.set(_p_)
  5098  	atomic.Xadd(&sched.npidle, 1) // TODO: fast atomic
  5099  }
  5100  
  5101  // Try get a p from _Pidle list.
  5102  // Sched must be locked.
  5103  // May run during STW, so write barriers are not allowed.
  5104  //go:nowritebarrierrec
  5105  func pidleget() *p {
  5106  	_p_ := sched.pidle.ptr()
  5107  	if _p_ != nil {
  5108  		sched.pidle = _p_.link
  5109  		atomic.Xadd(&sched.npidle, -1) // TODO: fast atomic
  5110  	}
  5111  	return _p_
  5112  }
  5113  
  5114  // runqempty reports whether _p_ has no Gs on its local run queue.
  5115  // It never returns true spuriously.
  5116  func runqempty(_p_ *p) bool {
  5117  	// Defend against a race where 1) _p_ has G1 in runqnext but runqhead == runqtail,
  5118  	// 2) runqput on _p_ kicks G1 to the runq, 3) runqget on _p_ empties runqnext.
  5119  	// Simply observing that runqhead == runqtail and then observing that runqnext == nil
  5120  	// does not mean the queue is empty.
  5121  	for {
  5122  		head := atomic.Load(&_p_.runqhead)
  5123  		tail := atomic.Load(&_p_.runqtail)
  5124  		runnext := atomic.Loaduintptr((*uintptr)(unsafe.Pointer(&_p_.runnext)))
  5125  		if tail == atomic.Load(&_p_.runqtail) {
  5126  			return head == tail && runnext == 0
  5127  		}
  5128  	}
  5129  }
  5130  
  5131  // To shake out latent assumptions about scheduling order,
  5132  // we introduce some randomness into scheduling decisions
  5133  // when running with the race detector.
  5134  // The need for this was made obvious by changing the
  5135  // (deterministic) scheduling order in Go 1.5 and breaking
  5136  // many poorly-written tests.
  5137  // With the randomness here, as long as the tests pass
  5138  // consistently with -race, they shouldn't have latent scheduling
  5139  // assumptions.
  5140  const randomizeScheduler = raceenabled
  5141  
  5142  // runqput tries to put g on the local runnable queue.
  5143  // If next is false, runqput adds g to the tail of the runnable queue.
  5144  // If next is true, runqput puts g in the _p_.runnext slot.
  5145  // If the run queue is full, runnext puts g on the global queue.
  5146  // Executed only by the owner P.
  5147  func runqput(_p_ *p, gp *g, next bool) {
  5148  	if randomizeScheduler && next && fastrand()%2 == 0 {
  5149  		next = false
  5150  	}
  5151  
  5152  	if next {
  5153  	retryNext:
  5154  		oldnext := _p_.runnext
  5155  		if !_p_.runnext.cas(oldnext, guintptr(unsafe.Pointer(gp))) {
  5156  			goto retryNext
  5157  		}
  5158  		if oldnext == 0 {
  5159  			return
  5160  		}
  5161  		// Kick the old runnext out to the regular run queue.
  5162  		gp = oldnext.ptr()
  5163  	}
  5164  
  5165  retry:
  5166  	h := atomic.LoadAcq(&_p_.runqhead) // load-acquire, synchronize with consumers
  5167  	t := _p_.runqtail
  5168  	if t-h < uint32(len(_p_.runq)) {
  5169  		_p_.runq[t%uint32(len(_p_.runq))].set(gp)
  5170  		atomic.StoreRel(&_p_.runqtail, t+1) // store-release, makes the item available for consumption
  5171  		return
  5172  	}
  5173  	if runqputslow(_p_, gp, h, t) {
  5174  		return
  5175  	}
  5176  	// the queue is not full, now the put above must succeed
  5177  	goto retry
  5178  }
  5179  
  5180  // Put g and a batch of work from local runnable queue on global queue.
  5181  // Executed only by the owner P.
  5182  func runqputslow(_p_ *p, gp *g, h, t uint32) bool {
  5183  	var batch [len(_p_.runq)/2 + 1]*g
  5184  
  5185  	// First, grab a batch from local queue.
  5186  	n := t - h
  5187  	n = n / 2
  5188  	if n != uint32(len(_p_.runq)/2) {
  5189  		throw("runqputslow: queue is not full")
  5190  	}
  5191  	for i := uint32(0); i < n; i++ {
  5192  		batch[i] = _p_.runq[(h+i)%uint32(len(_p_.runq))].ptr()
  5193  	}
  5194  	if !atomic.CasRel(&_p_.runqhead, h, h+n) { // cas-release, commits consume
  5195  		return false
  5196  	}
  5197  	batch[n] = gp
  5198  
  5199  	if randomizeScheduler {
  5200  		for i := uint32(1); i <= n; i++ {
  5201  			j := fastrandn(i + 1)
  5202  			batch[i], batch[j] = batch[j], batch[i]
  5203  		}
  5204  	}
  5205  
  5206  	// Link the goroutines.
  5207  	for i := uint32(0); i < n; i++ {
  5208  		batch[i].schedlink.set(batch[i+1])
  5209  	}
  5210  	var q gQueue
  5211  	q.head.set(batch[0])
  5212  	q.tail.set(batch[n])
  5213  
  5214  	// Now put the batch on global queue.
  5215  	lock(&sched.lock)
  5216  	globrunqputbatch(&q, int32(n+1))
  5217  	unlock(&sched.lock)
  5218  	return true
  5219  }
  5220  
  5221  // runqputbatch tries to put all the G's on q on the local runnable queue.
  5222  // If the queue is full, they are put on the global queue; in that case
  5223  // this will temporarily acquire the scheduler lock.
  5224  // Executed only by the owner P.
  5225  func runqputbatch(pp *p, q *gQueue, qsize int) {
  5226  	h := atomic.LoadAcq(&pp.runqhead)
  5227  	t := pp.runqtail
  5228  	n := uint32(0)
  5229  	for !q.empty() && t-h < uint32(len(pp.runq)) {
  5230  		gp := q.pop()
  5231  		pp.runq[t%uint32(len(pp.runq))].set(gp)
  5232  		t++
  5233  		n++
  5234  	}
  5235  	qsize -= int(n)
  5236  
  5237  	if randomizeScheduler {
  5238  		off := func(o uint32) uint32 {
  5239  			return (pp.runqtail + o) % uint32(len(pp.runq))
  5240  		}
  5241  		for i := uint32(1); i < n; i++ {
  5242  			j := fastrandn(i + 1)
  5243  			pp.runq[off(i)], pp.runq[off(j)] = pp.runq[off(j)], pp.runq[off(i)]
  5244  		}
  5245  	}
  5246  
  5247  	atomic.StoreRel(&pp.runqtail, t)
  5248  	if !q.empty() {
  5249  		lock(&sched.lock)
  5250  		globrunqputbatch(q, int32(qsize))
  5251  		unlock(&sched.lock)
  5252  	}
  5253  }
  5254  
  5255  // Get g from local runnable queue.
  5256  // If inheritTime is true, gp should inherit the remaining time in the
  5257  // current time slice. Otherwise, it should start a new time slice.
  5258  // Executed only by the owner P.
  5259  func runqget(_p_ *p) (gp *g, inheritTime bool) {
  5260  	// If there's a runnext, it's the next G to run.
  5261  	for {
  5262  		next := _p_.runnext
  5263  		if next == 0 {
  5264  			break
  5265  		}
  5266  		if _p_.runnext.cas(next, 0) {
  5267  			return next.ptr(), true
  5268  		}
  5269  	}
  5270  
  5271  	for {
  5272  		h := atomic.LoadAcq(&_p_.runqhead) // load-acquire, synchronize with other consumers
  5273  		t := _p_.runqtail
  5274  		if t == h {
  5275  			return nil, false
  5276  		}
  5277  		gp := _p_.runq[h%uint32(len(_p_.runq))].ptr()
  5278  		if atomic.CasRel(&_p_.runqhead, h, h+1) { // cas-release, commits consume
  5279  			return gp, false
  5280  		}
  5281  	}
  5282  }
  5283  
  5284  // Grabs a batch of goroutines from _p_'s runnable queue into batch.
  5285  // Batch is a ring buffer starting at batchHead.
  5286  // Returns number of grabbed goroutines.
  5287  // Can be executed by any P.
  5288  func runqgrab(_p_ *p, batch *[256]guintptr, batchHead uint32, stealRunNextG bool) uint32 {
  5289  	for {
  5290  		h := atomic.LoadAcq(&_p_.runqhead) // load-acquire, synchronize with other consumers
  5291  		t := atomic.LoadAcq(&_p_.runqtail) // load-acquire, synchronize with the producer
  5292  		n := t - h
  5293  		n = n - n/2
  5294  		if n == 0 {
  5295  			if stealRunNextG {
  5296  				// Try to steal from _p_.runnext.
  5297  				if next := _p_.runnext; next != 0 {
  5298  					if _p_.status == _Prunning {
  5299  						// Sleep to ensure that _p_ isn't about to run the g
  5300  						// we are about to steal.
  5301  						// The important use case here is when the g running
  5302  						// on _p_ ready()s another g and then almost
  5303  						// immediately blocks. Instead of stealing runnext
  5304  						// in this window, back off to give _p_ a chance to
  5305  						// schedule runnext. This will avoid thrashing gs
  5306  						// between different Ps.
  5307  						// A sync chan send/recv takes ~50ns as of time of
  5308  						// writing, so 3us gives ~50x overshoot.
  5309  						if GOOS != "windows" {
  5310  							usleep(3)
  5311  						} else {
  5312  							// On windows system timer granularity is
  5313  							// 1-15ms, which is way too much for this
  5314  							// optimization. So just yield.
  5315  							osyield()
  5316  						}
  5317  					}
  5318  					if !_p_.runnext.cas(next, 0) {
  5319  						continue
  5320  					}
  5321  					batch[batchHead%uint32(len(batch))] = next
  5322  					return 1
  5323  				}
  5324  			}
  5325  			return 0
  5326  		}
  5327  		if n > uint32(len(_p_.runq)/2) { // read inconsistent h and t
  5328  			continue
  5329  		}
  5330  		for i := uint32(0); i < n; i++ {
  5331  			g := _p_.runq[(h+i)%uint32(len(_p_.runq))]
  5332  			batch[(batchHead+i)%uint32(len(batch))] = g
  5333  		}
  5334  		if atomic.CasRel(&_p_.runqhead, h, h+n) { // cas-release, commits consume
  5335  			return n
  5336  		}
  5337  	}
  5338  }
  5339  
  5340  // Steal half of elements from local runnable queue of p2
  5341  // and put onto local runnable queue of p.
  5342  // Returns one of the stolen elements (or nil if failed).
  5343  func runqsteal(_p_, p2 *p, stealRunNextG bool) *g {
  5344  	t := _p_.runqtail
  5345  	n := runqgrab(p2, &_p_.runq, t, stealRunNextG)
  5346  	if n == 0 {
  5347  		return nil
  5348  	}
  5349  	n--
  5350  	gp := _p_.runq[(t+n)%uint32(len(_p_.runq))].ptr()
  5351  	if n == 0 {
  5352  		return gp
  5353  	}
  5354  	h := atomic.LoadAcq(&_p_.runqhead) // load-acquire, synchronize with consumers
  5355  	if t-h+n >= uint32(len(_p_.runq)) {
  5356  		throw("runqsteal: runq overflow")
  5357  	}
  5358  	atomic.StoreRel(&_p_.runqtail, t+n) // store-release, makes the item available for consumption
  5359  	return gp
  5360  }
  5361  
  5362  // A gQueue is a dequeue of Gs linked through g.schedlink. A G can only
  5363  // be on one gQueue or gList at a time.
  5364  type gQueue struct {
  5365  	head guintptr
  5366  	tail guintptr
  5367  }
  5368  
  5369  // empty reports whether q is empty.
  5370  func (q *gQueue) empty() bool {
  5371  	return q.head == 0
  5372  }
  5373  
  5374  // push adds gp to the head of q.
  5375  func (q *gQueue) push(gp *g) {
  5376  	gp.schedlink = q.head
  5377  	q.head.set(gp)
  5378  	if q.tail == 0 {
  5379  		q.tail.set(gp)
  5380  	}
  5381  }
  5382  
  5383  // pushBack adds gp to the tail of q.
  5384  func (q *gQueue) pushBack(gp *g) {
  5385  	gp.schedlink = 0
  5386  	if q.tail != 0 {
  5387  		q.tail.ptr().schedlink.set(gp)
  5388  	} else {
  5389  		q.head.set(gp)
  5390  	}
  5391  	q.tail.set(gp)
  5392  }
  5393  
  5394  // pushBackAll adds all Gs in l2 to the tail of q. After this q2 must
  5395  // not be used.
  5396  func (q *gQueue) pushBackAll(q2 gQueue) {
  5397  	if q2.tail == 0 {
  5398  		return
  5399  	}
  5400  	q2.tail.ptr().schedlink = 0
  5401  	if q.tail != 0 {
  5402  		q.tail.ptr().schedlink = q2.head
  5403  	} else {
  5404  		q.head = q2.head
  5405  	}
  5406  	q.tail = q2.tail
  5407  }
  5408  
  5409  // pop removes and returns the head of queue q. It returns nil if
  5410  // q is empty.
  5411  func (q *gQueue) pop() *g {
  5412  	gp := q.head.ptr()
  5413  	if gp != nil {
  5414  		q.head = gp.schedlink
  5415  		if q.head == 0 {
  5416  			q.tail = 0
  5417  		}
  5418  	}
  5419  	return gp
  5420  }
  5421  
  5422  // popList takes all Gs in q and returns them as a gList.
  5423  func (q *gQueue) popList() gList {
  5424  	stack := gList{q.head}
  5425  	*q = gQueue{}
  5426  	return stack
  5427  }
  5428  
  5429  // A gList is a list of Gs linked through g.schedlink. A G can only be
  5430  // on one gQueue or gList at a time.
  5431  type gList struct {
  5432  	head guintptr
  5433  }
  5434  
  5435  // empty reports whether l is empty.
  5436  func (l *gList) empty() bool {
  5437  	return l.head == 0
  5438  }
  5439  
  5440  // push adds gp to the head of l.
  5441  func (l *gList) push(gp *g) {
  5442  	gp.schedlink = l.head
  5443  	l.head.set(gp)
  5444  }
  5445  
  5446  // pushAll prepends all Gs in q to l.
  5447  func (l *gList) pushAll(q gQueue) {
  5448  	if !q.empty() {
  5449  		q.tail.ptr().schedlink = l.head
  5450  		l.head = q.head
  5451  	}
  5452  }
  5453  
  5454  // pop removes and returns the head of l. If l is empty, it returns nil.
  5455  func (l *gList) pop() *g {
  5456  	gp := l.head.ptr()
  5457  	if gp != nil {
  5458  		l.head = gp.schedlink
  5459  	}
  5460  	return gp
  5461  }
  5462  
  5463  //go:linkname setMaxThreads runtime/debug.setMaxThreads
  5464  func setMaxThreads(in int) (out int) {
  5465  	lock(&sched.lock)
  5466  	out = int(sched.maxmcount)
  5467  	if in > 0x7fffffff { // MaxInt32
  5468  		sched.maxmcount = 0x7fffffff
  5469  	} else {
  5470  		sched.maxmcount = int32(in)
  5471  	}
  5472  	checkmcount()
  5473  	unlock(&sched.lock)
  5474  	return
  5475  }
  5476  
  5477  func haveexperiment(name string) bool {
  5478  	if name == "framepointer" {
  5479  		return framepointer_enabled // set by linker
  5480  	}
  5481  	x := sys.Goexperiment
  5482  	for x != "" {
  5483  		xname := ""
  5484  		i := index(x, ",")
  5485  		if i < 0 {
  5486  			xname, x = x, ""
  5487  		} else {
  5488  			xname, x = x[:i], x[i+1:]
  5489  		}
  5490  		if xname == name {
  5491  			return true
  5492  		}
  5493  		if len(xname) > 2 && xname[:2] == "no" && xname[2:] == name {
  5494  			return false
  5495  		}
  5496  	}
  5497  	return false
  5498  }
  5499  
  5500  //go:nosplit
  5501  func procPin() int {
  5502  	_g_ := getg()
  5503  	mp := _g_.m
  5504  
  5505  	mp.locks++
  5506  	return int(mp.p.ptr().id)
  5507  }
  5508  
  5509  //go:nosplit
  5510  func procUnpin() {
  5511  	_g_ := getg()
  5512  	_g_.m.locks--
  5513  }
  5514  
  5515  //go:linkname sync_runtime_procPin sync.runtime_procPin
  5516  //go:nosplit
  5517  func sync_runtime_procPin() int {
  5518  	return procPin()
  5519  }
  5520  
  5521  //go:linkname sync_runtime_procUnpin sync.runtime_procUnpin
  5522  //go:nosplit
  5523  func sync_runtime_procUnpin() {
  5524  	procUnpin()
  5525  }
  5526  
  5527  //go:linkname sync_atomic_runtime_procPin sync/atomic.runtime_procPin
  5528  //go:nosplit
  5529  func sync_atomic_runtime_procPin() int {
  5530  	return procPin()
  5531  }
  5532  
  5533  //go:linkname sync_atomic_runtime_procUnpin sync/atomic.runtime_procUnpin
  5534  //go:nosplit
  5535  func sync_atomic_runtime_procUnpin() {
  5536  	procUnpin()
  5537  }
  5538  
  5539  // Active spinning for sync.Mutex.
  5540  //go:linkname sync_runtime_canSpin sync.runtime_canSpin
  5541  //go:nosplit
  5542  func sync_runtime_canSpin(i int) bool {
  5543  	// sync.Mutex is cooperative, so we are conservative with spinning.
  5544  	// Spin only few times and only if running on a multicore machine and
  5545  	// GOMAXPROCS>1 and there is at least one other running P and local runq is empty.
  5546  	// As opposed to runtime mutex we don't do passive spinning here,
  5547  	// because there can be work on global runq or on other Ps.
  5548  	if i >= active_spin || ncpu <= 1 || gomaxprocs <= int32(sched.npidle+sched.nmspinning)+1 {
  5549  		return false
  5550  	}
  5551  	if p := getg().m.p.ptr(); !runqempty(p) {
  5552  		return false
  5553  	}
  5554  	return true
  5555  }
  5556  
  5557  //go:linkname sync_runtime_doSpin sync.runtime_doSpin
  5558  //go:nosplit
  5559  func sync_runtime_doSpin() {
  5560  	procyield(active_spin_cnt)
  5561  }
  5562  
  5563  var stealOrder randomOrder
  5564  
  5565  // randomOrder/randomEnum are helper types for randomized work stealing.
  5566  // They allow to enumerate all Ps in different pseudo-random orders without repetitions.
  5567  // The algorithm is based on the fact that if we have X such that X and GOMAXPROCS
  5568  // are coprime, then a sequences of (i + X) % GOMAXPROCS gives the required enumeration.
  5569  type randomOrder struct {
  5570  	count    uint32
  5571  	coprimes []uint32
  5572  }
  5573  
  5574  type randomEnum struct {
  5575  	i     uint32
  5576  	count uint32
  5577  	pos   uint32
  5578  	inc   uint32
  5579  }
  5580  
  5581  func (ord *randomOrder) reset(count uint32) {
  5582  	ord.count = count
  5583  	ord.coprimes = ord.coprimes[:0]
  5584  	for i := uint32(1); i <= count; i++ {
  5585  		if gcd(i, count) == 1 {
  5586  			ord.coprimes = append(ord.coprimes, i)
  5587  		}
  5588  	}
  5589  }
  5590  
  5591  func (ord *randomOrder) start(i uint32) randomEnum {
  5592  	return randomEnum{
  5593  		count: ord.count,
  5594  		pos:   i % ord.count,
  5595  		inc:   ord.coprimes[i%uint32(len(ord.coprimes))],
  5596  	}
  5597  }
  5598  
  5599  func (enum *randomEnum) done() bool {
  5600  	return enum.i == enum.count
  5601  }
  5602  
  5603  func (enum *randomEnum) next() {
  5604  	enum.i++
  5605  	enum.pos = (enum.pos + enum.inc) % enum.count
  5606  }
  5607  
  5608  func (enum *randomEnum) position() uint32 {
  5609  	return enum.pos
  5610  }
  5611  
  5612  func gcd(a, b uint32) uint32 {
  5613  	for b != 0 {
  5614  		a, b = b, a%b
  5615  	}
  5616  	return a
  5617  }
  5618  
  5619  // An initTask represents the set of initializations that need to be done for a package.
  5620  // Keep in sync with ../../test/initempty.go:initTask
  5621  type initTask struct {
  5622  	// TODO: pack the first 3 fields more tightly?
  5623  	state uintptr // 0 = uninitialized, 1 = in progress, 2 = done
  5624  	ndeps uintptr
  5625  	nfns  uintptr
  5626  	// followed by ndeps instances of an *initTask, one per package depended on
  5627  	// followed by nfns pcs, one per init function to run
  5628  }
  5629  
  5630  func doInit(t *initTask) {
  5631  	switch t.state {
  5632  	case 2: // fully initialized
  5633  		return
  5634  	case 1: // initialization in progress
  5635  		throw("recursive call during initialization - linker skew")
  5636  	default: // not initialized yet
  5637  		t.state = 1 // initialization in progress
  5638  		for i := uintptr(0); i < t.ndeps; i++ {
  5639  			p := add(unsafe.Pointer(t), (3+i)*sys.PtrSize)
  5640  			t2 := *(**initTask)(p)
  5641  			doInit(t2)
  5642  		}
  5643  		for i := uintptr(0); i < t.nfns; i++ {
  5644  			p := add(unsafe.Pointer(t), (3+t.ndeps+i)*sys.PtrSize)
  5645  			f := *(*func())(unsafe.Pointer(&p))
  5646  			f()
  5647  		}
  5648  		t.state = 2 // initialization done
  5649  	}
  5650  }
  5651  

View as plain text