github.com/panjjo/go@v0.0.0-20161104043856-d62b31386338/src/runtime/proc.go (about)

     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  	"runtime/internal/atomic"
     9  	"runtime/internal/sys"
    10  	"unsafe"
    11  )
    12  
    13  var buildVersion = sys.TheVersion
    14  
    15  // Goroutine scheduler
    16  // The scheduler's job is to distribute ready-to-run goroutines over worker threads.
    17  //
    18  // The main concepts are:
    19  // G - goroutine.
    20  // M - worker thread, or machine.
    21  // P - processor, a resource that is required to execute Go code.
    22  //     M must have an associated P to execute Go code, however it can be
    23  //     blocked or in a syscall w/o an associated P.
    24  //
    25  // Design doc at https://golang.org/s/go11sched.
    26  
    27  // Worker thread parking/unparking.
    28  // We need to balance between keeping enough running worker threads to utilize
    29  // available hardware parallelism and parking excessive running worker threads
    30  // to conserve CPU resources and power. This is not simple for two reasons:
    31  // (1) scheduler state is intentionally distributed (in particular, per-P work
    32  // queues), so it is not possible to compute global predicates on fast paths;
    33  // (2) for optimal thread management we would need to know the future (don't park
    34  // a worker thread when a new goroutine will be readied in near future).
    35  //
    36  // Three rejected approaches that would work badly:
    37  // 1. Centralize all scheduler state (would inhibit scalability).
    38  // 2. Direct goroutine handoff. That is, when we ready a new goroutine and there
    39  //    is a spare P, unpark a thread and handoff it the thread and the goroutine.
    40  //    This would lead to thread state thrashing, as the thread that readied the
    41  //    goroutine can be out of work the very next moment, we will need to park it.
    42  //    Also, it would destroy locality of computation as we want to preserve
    43  //    dependent goroutines on the same thread; and introduce additional latency.
    44  // 3. Unpark an additional thread whenever we ready a goroutine and there is an
    45  //    idle P, but don't do handoff. This would lead to excessive thread parking/
    46  //    unparking as the additional threads will instantly park without discovering
    47  //    any work to do.
    48  //
    49  // The current approach:
    50  // We unpark an additional thread when we ready a goroutine if (1) there is an
    51  // idle P and there are no "spinning" worker threads. A worker thread is considered
    52  // spinning if it is out of local work and did not find work in global run queue/
    53  // netpoller; the spinning state is denoted in m.spinning and in sched.nmspinning.
    54  // Threads unparked this way are also considered spinning; we don't do goroutine
    55  // handoff so such threads are out of work initially. Spinning threads do some
    56  // spinning looking for work in per-P run queues before parking. If a spinning
    57  // thread finds work it takes itself out of the spinning state and proceeds to
    58  // execution. If it does not find work it takes itself out of the spinning state
    59  // and then parks.
    60  // If there is at least one spinning thread (sched.nmspinning>1), we don't unpark
    61  // new threads when readying goroutines. To compensate for that, if the last spinning
    62  // thread finds work and stops spinning, it must unpark a new spinning thread.
    63  // This approach smooths out unjustified spikes of thread unparking,
    64  // but at the same time guarantees eventual maximal CPU parallelism utilization.
    65  //
    66  // The main implementation complication is that we need to be very careful during
    67  // spinning->non-spinning thread transition. This transition can race with submission
    68  // of a new goroutine, and either one part or another needs to unpark another worker
    69  // thread. If they both fail to do that, we can end up with semi-persistent CPU
    70  // underutilization. The general pattern for goroutine readying is: submit a goroutine
    71  // to local work queue, #StoreLoad-style memory barrier, check sched.nmspinning.
    72  // The general pattern for spinning->non-spinning transition is: decrement nmspinning,
    73  // #StoreLoad-style memory barrier, check all per-P work queues for new work.
    74  // Note that all this complexity does not apply to global run queue as we are not
    75  // sloppy about thread unparking when submitting to global queue. Also see comments
    76  // for nmspinning manipulation.
    77  
    78  var (
    79  	m0           m
    80  	g0           g
    81  	raceprocctx0 uintptr
    82  )
    83  
    84  //go:linkname runtime_init runtime.init
    85  func runtime_init()
    86  
    87  //go:linkname main_init main.init
    88  func main_init()
    89  
    90  // main_init_done is a signal used by cgocallbackg that initialization
    91  // has been completed. It is made before _cgo_notify_runtime_init_done,
    92  // so all cgo calls can rely on it existing. When main_init is complete,
    93  // it is closed, meaning cgocallbackg can reliably receive from it.
    94  var main_init_done chan bool
    95  
    96  //go:linkname main_main main.main
    97  func main_main()
    98  
    99  // runtimeInitTime is the nanotime() at which the runtime started.
   100  var runtimeInitTime int64
   101  
   102  // Value to use for signal mask for newly created M's.
   103  var initSigmask sigset
   104  
   105  // The main goroutine.
   106  func main() {
   107  	g := getg()
   108  
   109  	// Racectx of m0->g0 is used only as the parent of the main goroutine.
   110  	// It must not be used for anything else.
   111  	g.m.g0.racectx = 0
   112  
   113  	// Max stack size is 1 GB on 64-bit, 250 MB on 32-bit.
   114  	// Using decimal instead of binary GB and MB because
   115  	// they look nicer in the stack overflow failure message.
   116  	if sys.PtrSize == 8 {
   117  		maxstacksize = 1000000000
   118  	} else {
   119  		maxstacksize = 250000000
   120  	}
   121  
   122  	// Record when the world started.
   123  	runtimeInitTime = nanotime()
   124  
   125  	systemstack(func() {
   126  		newm(sysmon, nil)
   127  	})
   128  
   129  	// Lock the main goroutine onto this, the main OS thread,
   130  	// during initialization. Most programs won't care, but a few
   131  	// do require certain calls to be made by the main thread.
   132  	// Those can arrange for main.main to run in the main thread
   133  	// by calling runtime.LockOSThread during initialization
   134  	// to preserve the lock.
   135  	lockOSThread()
   136  
   137  	if g.m != &m0 {
   138  		throw("runtime.main not on m0")
   139  	}
   140  
   141  	runtime_init() // must be before defer
   142  
   143  	// Defer unlock so that runtime.Goexit during init does the unlock too.
   144  	needUnlock := true
   145  	defer func() {
   146  		if needUnlock {
   147  			unlockOSThread()
   148  		}
   149  	}()
   150  
   151  	gcenable()
   152  
   153  	main_init_done = make(chan bool)
   154  	if iscgo {
   155  		if _cgo_thread_start == nil {
   156  			throw("_cgo_thread_start missing")
   157  		}
   158  		if GOOS != "windows" {
   159  			if _cgo_setenv == nil {
   160  				throw("_cgo_setenv missing")
   161  			}
   162  			if _cgo_unsetenv == nil {
   163  				throw("_cgo_unsetenv missing")
   164  			}
   165  		}
   166  		if _cgo_notify_runtime_init_done == nil {
   167  			throw("_cgo_notify_runtime_init_done missing")
   168  		}
   169  		cgocall(_cgo_notify_runtime_init_done, nil)
   170  	}
   171  
   172  	fn := main_init // make an indirect call, as the linker doesn't know the address of the main package when laying down the runtime
   173  	fn()
   174  	close(main_init_done)
   175  
   176  	needUnlock = false
   177  	unlockOSThread()
   178  
   179  	if isarchive || islibrary {
   180  		// A program compiled with -buildmode=c-archive or c-shared
   181  		// has a main, but it is not executed.
   182  		return
   183  	}
   184  	fn = main_main // make an indirect call, as the linker doesn't know the address of the main package when laying down the runtime
   185  	fn()
   186  	if raceenabled {
   187  		racefini()
   188  	}
   189  
   190  	// Make racy client program work: if panicking on
   191  	// another goroutine at the same time as main returns,
   192  	// let the other goroutine finish printing the panic trace.
   193  	// Once it does, it will exit. See issue 3934.
   194  	if panicking != 0 {
   195  		gopark(nil, nil, "panicwait", traceEvGoStop, 1)
   196  	}
   197  
   198  	exit(0)
   199  	for {
   200  		var x *int32
   201  		*x = 0
   202  	}
   203  }
   204  
   205  // os_beforeExit is called from os.Exit(0).
   206  //go:linkname os_beforeExit os.runtime_beforeExit
   207  func os_beforeExit() {
   208  	if raceenabled {
   209  		racefini()
   210  	}
   211  }
   212  
   213  // start forcegc helper goroutine
   214  func init() {
   215  	go forcegchelper()
   216  }
   217  
   218  func forcegchelper() {
   219  	forcegc.g = getg()
   220  	for {
   221  		lock(&forcegc.lock)
   222  		if forcegc.idle != 0 {
   223  			throw("forcegc: phase error")
   224  		}
   225  		atomic.Store(&forcegc.idle, 1)
   226  		goparkunlock(&forcegc.lock, "force gc (idle)", traceEvGoBlock, 1)
   227  		// this goroutine is explicitly resumed by sysmon
   228  		if debug.gctrace > 0 {
   229  			println("GC forced")
   230  		}
   231  		gcStart(gcBackgroundMode, true)
   232  	}
   233  }
   234  
   235  //go:nosplit
   236  
   237  // Gosched yields the processor, allowing other goroutines to run. It does not
   238  // suspend the current goroutine, so execution resumes automatically.
   239  func Gosched() {
   240  	mcall(gosched_m)
   241  }
   242  
   243  // Puts the current goroutine into a waiting state and calls unlockf.
   244  // If unlockf returns false, the goroutine is resumed.
   245  // unlockf must not access this G's stack, as it may be moved between
   246  // the call to gopark and the call to unlockf.
   247  func gopark(unlockf func(*g, unsafe.Pointer) bool, lock unsafe.Pointer, reason string, traceEv byte, traceskip int) {
   248  	mp := acquirem()
   249  	gp := mp.curg
   250  	status := readgstatus(gp)
   251  	if status != _Grunning && status != _Gscanrunning {
   252  		throw("gopark: bad g status")
   253  	}
   254  	mp.waitlock = lock
   255  	mp.waitunlockf = *(*unsafe.Pointer)(unsafe.Pointer(&unlockf))
   256  	gp.waitreason = reason
   257  	mp.waittraceev = traceEv
   258  	mp.waittraceskip = traceskip
   259  	releasem(mp)
   260  	// can't do anything that might move the G between Ms here.
   261  	mcall(park_m)
   262  }
   263  
   264  // Puts the current goroutine into a waiting state and unlocks the lock.
   265  // The goroutine can be made runnable again by calling goready(gp).
   266  func goparkunlock(lock *mutex, reason string, traceEv byte, traceskip int) {
   267  	gopark(parkunlock_c, unsafe.Pointer(lock), reason, traceEv, traceskip)
   268  }
   269  
   270  func goready(gp *g, traceskip int) {
   271  	systemstack(func() {
   272  		ready(gp, traceskip, true)
   273  	})
   274  }
   275  
   276  //go:nosplit
   277  func acquireSudog() *sudog {
   278  	// Delicate dance: the semaphore implementation calls
   279  	// acquireSudog, acquireSudog calls new(sudog),
   280  	// new calls malloc, malloc can call the garbage collector,
   281  	// and the garbage collector calls the semaphore implementation
   282  	// in stopTheWorld.
   283  	// Break the cycle by doing acquirem/releasem around new(sudog).
   284  	// The acquirem/releasem increments m.locks during new(sudog),
   285  	// which keeps the garbage collector from being invoked.
   286  	mp := acquirem()
   287  	pp := mp.p.ptr()
   288  	if len(pp.sudogcache) == 0 {
   289  		lock(&sched.sudoglock)
   290  		// First, try to grab a batch from central cache.
   291  		for len(pp.sudogcache) < cap(pp.sudogcache)/2 && sched.sudogcache != nil {
   292  			s := sched.sudogcache
   293  			sched.sudogcache = s.next
   294  			s.next = nil
   295  			pp.sudogcache = append(pp.sudogcache, s)
   296  		}
   297  		unlock(&sched.sudoglock)
   298  		// If the central cache is empty, allocate a new one.
   299  		if len(pp.sudogcache) == 0 {
   300  			pp.sudogcache = append(pp.sudogcache, new(sudog))
   301  		}
   302  	}
   303  	n := len(pp.sudogcache)
   304  	s := pp.sudogcache[n-1]
   305  	pp.sudogcache[n-1] = nil
   306  	pp.sudogcache = pp.sudogcache[:n-1]
   307  	if s.elem != nil {
   308  		throw("acquireSudog: found s.elem != nil in cache")
   309  	}
   310  	releasem(mp)
   311  	return s
   312  }
   313  
   314  //go:nosplit
   315  func releaseSudog(s *sudog) {
   316  	if s.elem != nil {
   317  		throw("runtime: sudog with non-nil elem")
   318  	}
   319  	if s.selectdone != nil {
   320  		throw("runtime: sudog with non-nil selectdone")
   321  	}
   322  	if s.next != nil {
   323  		throw("runtime: sudog with non-nil next")
   324  	}
   325  	if s.prev != nil {
   326  		throw("runtime: sudog with non-nil prev")
   327  	}
   328  	if s.waitlink != nil {
   329  		throw("runtime: sudog with non-nil waitlink")
   330  	}
   331  	if s.c != nil {
   332  		throw("runtime: sudog with non-nil c")
   333  	}
   334  	gp := getg()
   335  	if gp.param != nil {
   336  		throw("runtime: releaseSudog with non-nil gp.param")
   337  	}
   338  	mp := acquirem() // avoid rescheduling to another P
   339  	pp := mp.p.ptr()
   340  	if len(pp.sudogcache) == cap(pp.sudogcache) {
   341  		// Transfer half of local cache to the central cache.
   342  		var first, last *sudog
   343  		for len(pp.sudogcache) > cap(pp.sudogcache)/2 {
   344  			n := len(pp.sudogcache)
   345  			p := pp.sudogcache[n-1]
   346  			pp.sudogcache[n-1] = nil
   347  			pp.sudogcache = pp.sudogcache[:n-1]
   348  			if first == nil {
   349  				first = p
   350  			} else {
   351  				last.next = p
   352  			}
   353  			last = p
   354  		}
   355  		lock(&sched.sudoglock)
   356  		last.next = sched.sudogcache
   357  		sched.sudogcache = first
   358  		unlock(&sched.sudoglock)
   359  	}
   360  	pp.sudogcache = append(pp.sudogcache, s)
   361  	releasem(mp)
   362  }
   363  
   364  // funcPC returns the entry PC of the function f.
   365  // It assumes that f is a func value. Otherwise the behavior is undefined.
   366  //go:nosplit
   367  func funcPC(f interface{}) uintptr {
   368  	return **(**uintptr)(add(unsafe.Pointer(&f), sys.PtrSize))
   369  }
   370  
   371  // called from assembly
   372  func badmcall(fn func(*g)) {
   373  	throw("runtime: mcall called on m->g0 stack")
   374  }
   375  
   376  func badmcall2(fn func(*g)) {
   377  	throw("runtime: mcall function returned")
   378  }
   379  
   380  func badreflectcall() {
   381  	panic(plainError("arg size to reflect.call more than 1GB"))
   382  }
   383  
   384  var badmorestackg0Msg = "fatal: morestack on g0\n"
   385  
   386  //go:nosplit
   387  //go:nowritebarrierrec
   388  func badmorestackg0() {
   389  	sp := stringStructOf(&badmorestackg0Msg)
   390  	write(2, sp.str, int32(sp.len))
   391  }
   392  
   393  var badmorestackgsignalMsg = "fatal: morestack on gsignal\n"
   394  
   395  //go:nosplit
   396  //go:nowritebarrierrec
   397  func badmorestackgsignal() {
   398  	sp := stringStructOf(&badmorestackgsignalMsg)
   399  	write(2, sp.str, int32(sp.len))
   400  }
   401  
   402  //go:nosplit
   403  func badctxt() {
   404  	throw("ctxt != 0")
   405  }
   406  
   407  func lockedOSThread() bool {
   408  	gp := getg()
   409  	return gp.lockedm != nil && gp.m.lockedg != nil
   410  }
   411  
   412  var (
   413  	allgs    []*g
   414  	allglock mutex
   415  )
   416  
   417  func allgadd(gp *g) {
   418  	if readgstatus(gp) == _Gidle {
   419  		throw("allgadd: bad status Gidle")
   420  	}
   421  
   422  	lock(&allglock)
   423  	allgs = append(allgs, gp)
   424  	allglen = uintptr(len(allgs))
   425  
   426  	// Grow GC rescan list if necessary.
   427  	if len(allgs) > cap(work.rescan.list) {
   428  		lock(&work.rescan.lock)
   429  		l := work.rescan.list
   430  		// Let append do the heavy lifting, but keep the
   431  		// length the same.
   432  		work.rescan.list = append(l[:cap(l)], 0)[:len(l)]
   433  		unlock(&work.rescan.lock)
   434  	}
   435  	unlock(&allglock)
   436  }
   437  
   438  const (
   439  	// Number of goroutine ids to grab from sched.goidgen to local per-P cache at once.
   440  	// 16 seems to provide enough amortization, but other than that it's mostly arbitrary number.
   441  	_GoidCacheBatch = 16
   442  )
   443  
   444  // The bootstrap sequence is:
   445  //
   446  //	call osinit
   447  //	call schedinit
   448  //	make & queue new G
   449  //	call runtime·mstart
   450  //
   451  // The new G calls runtime·main.
   452  func schedinit() {
   453  	// raceinit must be the first call to race detector.
   454  	// In particular, it must be done before mallocinit below calls racemapshadow.
   455  	_g_ := getg()
   456  	if raceenabled {
   457  		_g_.racectx, raceprocctx0 = raceinit()
   458  	}
   459  
   460  	sched.maxmcount = 10000
   461  
   462  	tracebackinit()
   463  	moduledataverify()
   464  	stackinit()
   465  	mallocinit()
   466  	mcommoninit(_g_.m)
   467  	alginit()       // maps must not be used before this call
   468  	modulesinit()   // provides activeModules
   469  	typelinksinit() // uses maps, activeModules
   470  	itabsinit()     // uses activeModules
   471  
   472  	msigsave(_g_.m)
   473  	initSigmask = _g_.m.sigmask
   474  
   475  	goargs()
   476  	goenvs()
   477  	parsedebugvars()
   478  	gcinit()
   479  
   480  	sched.lastpoll = uint64(nanotime())
   481  	procs := ncpu
   482  	if n, ok := atoi32(gogetenv("GOMAXPROCS")); ok && n > 0 {
   483  		procs = n
   484  	}
   485  	if procs > _MaxGomaxprocs {
   486  		procs = _MaxGomaxprocs
   487  	}
   488  	if procresize(procs) != nil {
   489  		throw("unknown runnable goroutine during bootstrap")
   490  	}
   491  
   492  	if buildVersion == "" {
   493  		// Condition should never trigger. This code just serves
   494  		// to ensure runtime·buildVersion is kept in the resulting binary.
   495  		buildVersion = "unknown"
   496  	}
   497  }
   498  
   499  func dumpgstatus(gp *g) {
   500  	_g_ := getg()
   501  	print("runtime: gp: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n")
   502  	print("runtime:  g:  g=", _g_, ", goid=", _g_.goid, ",  g->atomicstatus=", readgstatus(_g_), "\n")
   503  }
   504  
   505  func checkmcount() {
   506  	// sched lock is held
   507  	if sched.mcount > sched.maxmcount {
   508  		print("runtime: program exceeds ", sched.maxmcount, "-thread limit\n")
   509  		throw("thread exhaustion")
   510  	}
   511  }
   512  
   513  func mcommoninit(mp *m) {
   514  	_g_ := getg()
   515  
   516  	// g0 stack won't make sense for user (and is not necessary unwindable).
   517  	if _g_ != _g_.m.g0 {
   518  		callers(1, mp.createstack[:])
   519  	}
   520  
   521  	mp.fastrand = 0x49f6428a + uint32(mp.id) + uint32(cputicks())
   522  	if mp.fastrand == 0 {
   523  		mp.fastrand = 0x49f6428a
   524  	}
   525  
   526  	lock(&sched.lock)
   527  	mp.id = sched.mcount
   528  	sched.mcount++
   529  	checkmcount()
   530  	mpreinit(mp)
   531  	if mp.gsignal != nil {
   532  		mp.gsignal.stackguard1 = mp.gsignal.stack.lo + _StackGuard
   533  	}
   534  
   535  	// Add to allm so garbage collector doesn't free g->m
   536  	// when it is just in a register or thread-local storage.
   537  	mp.alllink = allm
   538  
   539  	// NumCgoCall() iterates over allm w/o schedlock,
   540  	// so we need to publish it safely.
   541  	atomicstorep(unsafe.Pointer(&allm), unsafe.Pointer(mp))
   542  	unlock(&sched.lock)
   543  
   544  	// Allocate memory to hold a cgo traceback if the cgo call crashes.
   545  	if iscgo || GOOS == "solaris" || GOOS == "windows" {
   546  		mp.cgoCallers = new(cgoCallers)
   547  	}
   548  }
   549  
   550  // Mark gp ready to run.
   551  func ready(gp *g, traceskip int, next bool) {
   552  	if trace.enabled {
   553  		traceGoUnpark(gp, traceskip)
   554  	}
   555  
   556  	status := readgstatus(gp)
   557  
   558  	// Mark runnable.
   559  	_g_ := getg()
   560  	_g_.m.locks++ // disable preemption because it can be holding p in a local var
   561  	if status&^_Gscan != _Gwaiting {
   562  		dumpgstatus(gp)
   563  		throw("bad g->status in ready")
   564  	}
   565  
   566  	// status is Gwaiting or Gscanwaiting, make Grunnable and put on runq
   567  	casgstatus(gp, _Gwaiting, _Grunnable)
   568  	runqput(_g_.m.p.ptr(), gp, next)
   569  	if atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 {
   570  		wakep()
   571  	}
   572  	_g_.m.locks--
   573  	if _g_.m.locks == 0 && _g_.preempt { // restore the preemption request in Case we've cleared it in newstack
   574  		_g_.stackguard0 = stackPreempt
   575  	}
   576  }
   577  
   578  func gcprocs() int32 {
   579  	// Figure out how many CPUs to use during GC.
   580  	// Limited by gomaxprocs, number of actual CPUs, and MaxGcproc.
   581  	lock(&sched.lock)
   582  	n := gomaxprocs
   583  	if n > ncpu {
   584  		n = ncpu
   585  	}
   586  	if n > _MaxGcproc {
   587  		n = _MaxGcproc
   588  	}
   589  	if n > sched.nmidle+1 { // one M is currently running
   590  		n = sched.nmidle + 1
   591  	}
   592  	unlock(&sched.lock)
   593  	return n
   594  }
   595  
   596  func needaddgcproc() bool {
   597  	lock(&sched.lock)
   598  	n := gomaxprocs
   599  	if n > ncpu {
   600  		n = ncpu
   601  	}
   602  	if n > _MaxGcproc {
   603  		n = _MaxGcproc
   604  	}
   605  	n -= sched.nmidle + 1 // one M is currently running
   606  	unlock(&sched.lock)
   607  	return n > 0
   608  }
   609  
   610  func helpgc(nproc int32) {
   611  	_g_ := getg()
   612  	lock(&sched.lock)
   613  	pos := 0
   614  	for n := int32(1); n < nproc; n++ { // one M is currently running
   615  		if allp[pos].mcache == _g_.m.mcache {
   616  			pos++
   617  		}
   618  		mp := mget()
   619  		if mp == nil {
   620  			throw("gcprocs inconsistency")
   621  		}
   622  		mp.helpgc = n
   623  		mp.p.set(allp[pos])
   624  		mp.mcache = allp[pos].mcache
   625  		pos++
   626  		notewakeup(&mp.park)
   627  	}
   628  	unlock(&sched.lock)
   629  }
   630  
   631  // freezeStopWait is a large value that freezetheworld sets
   632  // sched.stopwait to in order to request that all Gs permanently stop.
   633  const freezeStopWait = 0x7fffffff
   634  
   635  // Similar to stopTheWorld but best-effort and can be called several times.
   636  // There is no reverse operation, used during crashing.
   637  // This function must not lock any mutexes.
   638  func freezetheworld() {
   639  	// stopwait and preemption requests can be lost
   640  	// due to races with concurrently executing threads,
   641  	// so try several times
   642  	for i := 0; i < 5; i++ {
   643  		// this should tell the scheduler to not start any new goroutines
   644  		sched.stopwait = freezeStopWait
   645  		atomic.Store(&sched.gcwaiting, 1)
   646  		// this should stop running goroutines
   647  		if !preemptall() {
   648  			break // no running goroutines
   649  		}
   650  		usleep(1000)
   651  	}
   652  	// to be sure
   653  	usleep(1000)
   654  	preemptall()
   655  	usleep(1000)
   656  }
   657  
   658  func isscanstatus(status uint32) bool {
   659  	if status == _Gscan {
   660  		throw("isscanstatus: Bad status Gscan")
   661  	}
   662  	return status&_Gscan == _Gscan
   663  }
   664  
   665  // All reads and writes of g's status go through readgstatus, casgstatus
   666  // castogscanstatus, casfrom_Gscanstatus.
   667  //go:nosplit
   668  func readgstatus(gp *g) uint32 {
   669  	return atomic.Load(&gp.atomicstatus)
   670  }
   671  
   672  // Ownership of gcscanvalid:
   673  //
   674  // If gp is running (meaning status == _Grunning or _Grunning|_Gscan),
   675  // then gp owns gp.gcscanvalid, and other goroutines must not modify it.
   676  //
   677  // Otherwise, a second goroutine can lock the scan state by setting _Gscan
   678  // in the status bit and then modify gcscanvalid, and then unlock the scan state.
   679  //
   680  // Note that the first condition implies an exception to the second:
   681  // if a second goroutine changes gp's status to _Grunning|_Gscan,
   682  // that second goroutine still does not have the right to modify gcscanvalid.
   683  
   684  // The Gscanstatuses are acting like locks and this releases them.
   685  // If it proves to be a performance hit we should be able to make these
   686  // simple atomic stores but for now we are going to throw if
   687  // we see an inconsistent state.
   688  func casfrom_Gscanstatus(gp *g, oldval, newval uint32) {
   689  	success := false
   690  
   691  	// Check that transition is valid.
   692  	switch oldval {
   693  	default:
   694  		print("runtime: casfrom_Gscanstatus bad oldval gp=", gp, ", oldval=", hex(oldval), ", newval=", hex(newval), "\n")
   695  		dumpgstatus(gp)
   696  		throw("casfrom_Gscanstatus:top gp->status is not in scan state")
   697  	case _Gscanrunnable,
   698  		_Gscanwaiting,
   699  		_Gscanrunning,
   700  		_Gscansyscall:
   701  		if newval == oldval&^_Gscan {
   702  			success = atomic.Cas(&gp.atomicstatus, oldval, newval)
   703  		}
   704  	}
   705  	if !success {
   706  		print("runtime: casfrom_Gscanstatus failed gp=", gp, ", oldval=", hex(oldval), ", newval=", hex(newval), "\n")
   707  		dumpgstatus(gp)
   708  		throw("casfrom_Gscanstatus: gp->status is not in scan state")
   709  	}
   710  }
   711  
   712  // This will return false if the gp is not in the expected status and the cas fails.
   713  // This acts like a lock acquire while the casfromgstatus acts like a lock release.
   714  func castogscanstatus(gp *g, oldval, newval uint32) bool {
   715  	switch oldval {
   716  	case _Grunnable,
   717  		_Grunning,
   718  		_Gwaiting,
   719  		_Gsyscall:
   720  		if newval == oldval|_Gscan {
   721  			return atomic.Cas(&gp.atomicstatus, oldval, newval)
   722  		}
   723  	}
   724  	print("runtime: castogscanstatus oldval=", hex(oldval), " newval=", hex(newval), "\n")
   725  	throw("castogscanstatus")
   726  	panic("not reached")
   727  }
   728  
   729  // If asked to move to or from a Gscanstatus this will throw. Use the castogscanstatus
   730  // and casfrom_Gscanstatus instead.
   731  // casgstatus will loop if the g->atomicstatus is in a Gscan status until the routine that
   732  // put it in the Gscan state is finished.
   733  //go:nosplit
   734  func casgstatus(gp *g, oldval, newval uint32) {
   735  	if (oldval&_Gscan != 0) || (newval&_Gscan != 0) || oldval == newval {
   736  		systemstack(func() {
   737  			print("runtime: casgstatus: oldval=", hex(oldval), " newval=", hex(newval), "\n")
   738  			throw("casgstatus: bad incoming values")
   739  		})
   740  	}
   741  
   742  	if oldval == _Grunning && gp.gcscanvalid {
   743  		// If oldvall == _Grunning, then the actual status must be
   744  		// _Grunning or _Grunning|_Gscan; either way,
   745  		// we own gp.gcscanvalid, so it's safe to read.
   746  		// gp.gcscanvalid must not be true when we are running.
   747  		print("runtime: casgstatus ", hex(oldval), "->", hex(newval), " gp.status=", hex(gp.atomicstatus), " gp.gcscanvalid=true\n")
   748  		throw("casgstatus")
   749  	}
   750  
   751  	// See http://golang.org/cl/21503 for justification of the yield delay.
   752  	const yieldDelay = 5 * 1000
   753  	var nextYield int64
   754  
   755  	// loop if gp->atomicstatus is in a scan state giving
   756  	// GC time to finish and change the state to oldval.
   757  	for i := 0; !atomic.Cas(&gp.atomicstatus, oldval, newval); i++ {
   758  		if oldval == _Gwaiting && gp.atomicstatus == _Grunnable {
   759  			systemstack(func() {
   760  				throw("casgstatus: waiting for Gwaiting but is Grunnable")
   761  			})
   762  		}
   763  		// Help GC if needed.
   764  		// if gp.preemptscan && !gp.gcworkdone && (oldval == _Grunning || oldval == _Gsyscall) {
   765  		// 	gp.preemptscan = false
   766  		// 	systemstack(func() {
   767  		// 		gcphasework(gp)
   768  		// 	})
   769  		// }
   770  		// But meanwhile just yield.
   771  		if i == 0 {
   772  			nextYield = nanotime() + yieldDelay
   773  		}
   774  		if nanotime() < nextYield {
   775  			for x := 0; x < 10 && gp.atomicstatus != oldval; x++ {
   776  				procyield(1)
   777  			}
   778  		} else {
   779  			osyield()
   780  			nextYield = nanotime() + yieldDelay/2
   781  		}
   782  	}
   783  	if newval == _Grunning && gp.gcscanvalid {
   784  		// Run queueRescan on the system stack so it has more space.
   785  		systemstack(func() { queueRescan(gp) })
   786  	}
   787  }
   788  
   789  // casgstatus(gp, oldstatus, Gcopystack), assuming oldstatus is Gwaiting or Grunnable.
   790  // Returns old status. Cannot call casgstatus directly, because we are racing with an
   791  // async wakeup that might come in from netpoll. If we see Gwaiting from the readgstatus,
   792  // it might have become Grunnable by the time we get to the cas. If we called casgstatus,
   793  // it would loop waiting for the status to go back to Gwaiting, which it never will.
   794  //go:nosplit
   795  func casgcopystack(gp *g) uint32 {
   796  	for {
   797  		oldstatus := readgstatus(gp) &^ _Gscan
   798  		if oldstatus != _Gwaiting && oldstatus != _Grunnable {
   799  			throw("copystack: bad status, not Gwaiting or Grunnable")
   800  		}
   801  		if atomic.Cas(&gp.atomicstatus, oldstatus, _Gcopystack) {
   802  			return oldstatus
   803  		}
   804  	}
   805  }
   806  
   807  // scang blocks until gp's stack has been scanned.
   808  // It might be scanned by scang or it might be scanned by the goroutine itself.
   809  // Either way, the stack scan has completed when scang returns.
   810  func scang(gp *g, gcw *gcWork) {
   811  	// Invariant; we (the caller, markroot for a specific goroutine) own gp.gcscandone.
   812  	// Nothing is racing with us now, but gcscandone might be set to true left over
   813  	// from an earlier round of stack scanning (we scan twice per GC).
   814  	// We use gcscandone to record whether the scan has been done during this round.
   815  	// It is important that the scan happens exactly once: if called twice,
   816  	// the installation of stack barriers will detect the double scan and die.
   817  
   818  	gp.gcscandone = false
   819  
   820  	// See http://golang.org/cl/21503 for justification of the yield delay.
   821  	const yieldDelay = 10 * 1000
   822  	var nextYield int64
   823  
   824  	// Endeavor to get gcscandone set to true,
   825  	// either by doing the stack scan ourselves or by coercing gp to scan itself.
   826  	// gp.gcscandone can transition from false to true when we're not looking
   827  	// (if we asked for preemption), so any time we lock the status using
   828  	// castogscanstatus we have to double-check that the scan is still not done.
   829  loop:
   830  	for i := 0; !gp.gcscandone; i++ {
   831  		switch s := readgstatus(gp); s {
   832  		default:
   833  			dumpgstatus(gp)
   834  			throw("stopg: invalid status")
   835  
   836  		case _Gdead:
   837  			// No stack.
   838  			gp.gcscandone = true
   839  			break loop
   840  
   841  		case _Gcopystack:
   842  		// Stack being switched. Go around again.
   843  
   844  		case _Grunnable, _Gsyscall, _Gwaiting:
   845  			// Claim goroutine by setting scan bit.
   846  			// Racing with execution or readying of gp.
   847  			// The scan bit keeps them from running
   848  			// the goroutine until we're done.
   849  			if castogscanstatus(gp, s, s|_Gscan) {
   850  				if !gp.gcscandone {
   851  					scanstack(gp, gcw)
   852  					gp.gcscandone = true
   853  				}
   854  				restartg(gp)
   855  				break loop
   856  			}
   857  
   858  		case _Gscanwaiting:
   859  		// newstack is doing a scan for us right now. Wait.
   860  
   861  		case _Grunning:
   862  			// Goroutine running. Try to preempt execution so it can scan itself.
   863  			// The preemption handler (in newstack) does the actual scan.
   864  
   865  			// Optimization: if there is already a pending preemption request
   866  			// (from the previous loop iteration), don't bother with the atomics.
   867  			if gp.preemptscan && gp.preempt && gp.stackguard0 == stackPreempt {
   868  				break
   869  			}
   870  
   871  			// Ask for preemption and self scan.
   872  			if castogscanstatus(gp, _Grunning, _Gscanrunning) {
   873  				if !gp.gcscandone {
   874  					gp.preemptscan = true
   875  					gp.preempt = true
   876  					gp.stackguard0 = stackPreempt
   877  				}
   878  				casfrom_Gscanstatus(gp, _Gscanrunning, _Grunning)
   879  			}
   880  		}
   881  
   882  		if i == 0 {
   883  			nextYield = nanotime() + yieldDelay
   884  		}
   885  		if nanotime() < nextYield {
   886  			procyield(10)
   887  		} else {
   888  			osyield()
   889  			nextYield = nanotime() + yieldDelay/2
   890  		}
   891  	}
   892  
   893  	gp.preemptscan = false // cancel scan request if no longer needed
   894  }
   895  
   896  // The GC requests that this routine be moved from a scanmumble state to a mumble state.
   897  func restartg(gp *g) {
   898  	s := readgstatus(gp)
   899  	switch s {
   900  	default:
   901  		dumpgstatus(gp)
   902  		throw("restartg: unexpected status")
   903  
   904  	case _Gdead:
   905  	// ok
   906  
   907  	case _Gscanrunnable,
   908  		_Gscanwaiting,
   909  		_Gscansyscall:
   910  		casfrom_Gscanstatus(gp, s, s&^_Gscan)
   911  	}
   912  }
   913  
   914  // stopTheWorld stops all P's from executing goroutines, interrupting
   915  // all goroutines at GC safe points and records reason as the reason
   916  // for the stop. On return, only the current goroutine's P is running.
   917  // stopTheWorld must not be called from a system stack and the caller
   918  // must not hold worldsema. The caller must call startTheWorld when
   919  // other P's should resume execution.
   920  //
   921  // stopTheWorld is safe for multiple goroutines to call at the
   922  // same time. Each will execute its own stop, and the stops will
   923  // be serialized.
   924  //
   925  // This is also used by routines that do stack dumps. If the system is
   926  // in panic or being exited, this may not reliably stop all
   927  // goroutines.
   928  func stopTheWorld(reason string) {
   929  	semacquire(&worldsema, 0)
   930  	getg().m.preemptoff = reason
   931  	systemstack(stopTheWorldWithSema)
   932  }
   933  
   934  // startTheWorld undoes the effects of stopTheWorld.
   935  func startTheWorld() {
   936  	systemstack(startTheWorldWithSema)
   937  	// worldsema must be held over startTheWorldWithSema to ensure
   938  	// gomaxprocs cannot change while worldsema is held.
   939  	semrelease(&worldsema)
   940  	getg().m.preemptoff = ""
   941  }
   942  
   943  // Holding worldsema grants an M the right to try to stop the world
   944  // and prevents gomaxprocs from changing concurrently.
   945  var worldsema uint32 = 1
   946  
   947  // stopTheWorldWithSema is the core implementation of stopTheWorld.
   948  // The caller is responsible for acquiring worldsema and disabling
   949  // preemption first and then should stopTheWorldWithSema on the system
   950  // stack:
   951  //
   952  //	semacquire(&worldsema, 0)
   953  //	m.preemptoff = "reason"
   954  //	systemstack(stopTheWorldWithSema)
   955  //
   956  // When finished, the caller must either call startTheWorld or undo
   957  // these three operations separately:
   958  //
   959  //	m.preemptoff = ""
   960  //	systemstack(startTheWorldWithSema)
   961  //	semrelease(&worldsema)
   962  //
   963  // It is allowed to acquire worldsema once and then execute multiple
   964  // startTheWorldWithSema/stopTheWorldWithSema pairs.
   965  // Other P's are able to execute between successive calls to
   966  // startTheWorldWithSema and stopTheWorldWithSema.
   967  // Holding worldsema causes any other goroutines invoking
   968  // stopTheWorld to block.
   969  func stopTheWorldWithSema() {
   970  	_g_ := getg()
   971  
   972  	// If we hold a lock, then we won't be able to stop another M
   973  	// that is blocked trying to acquire the lock.
   974  	if _g_.m.locks > 0 {
   975  		throw("stopTheWorld: holding locks")
   976  	}
   977  
   978  	lock(&sched.lock)
   979  	sched.stopwait = gomaxprocs
   980  	atomic.Store(&sched.gcwaiting, 1)
   981  	preemptall()
   982  	// stop current P
   983  	_g_.m.p.ptr().status = _Pgcstop // Pgcstop is only diagnostic.
   984  	sched.stopwait--
   985  	// try to retake all P's in Psyscall status
   986  	for i := 0; i < int(gomaxprocs); i++ {
   987  		p := allp[i]
   988  		s := p.status
   989  		if s == _Psyscall && atomic.Cas(&p.status, s, _Pgcstop) {
   990  			if trace.enabled {
   991  				traceGoSysBlock(p)
   992  				traceProcStop(p)
   993  			}
   994  			p.syscalltick++
   995  			sched.stopwait--
   996  		}
   997  	}
   998  	// stop idle P's
   999  	for {
  1000  		p := pidleget()
  1001  		if p == nil {
  1002  			break
  1003  		}
  1004  		p.status = _Pgcstop
  1005  		sched.stopwait--
  1006  	}
  1007  	wait := sched.stopwait > 0
  1008  	unlock(&sched.lock)
  1009  
  1010  	// wait for remaining P's to stop voluntarily
  1011  	if wait {
  1012  		for {
  1013  			// wait for 100us, then try to re-preempt in case of any races
  1014  			if notetsleep(&sched.stopnote, 100*1000) {
  1015  				noteclear(&sched.stopnote)
  1016  				break
  1017  			}
  1018  			preemptall()
  1019  		}
  1020  	}
  1021  	if sched.stopwait != 0 {
  1022  		throw("stopTheWorld: not stopped")
  1023  	}
  1024  	for i := 0; i < int(gomaxprocs); i++ {
  1025  		p := allp[i]
  1026  		if p.status != _Pgcstop {
  1027  			throw("stopTheWorld: not stopped")
  1028  		}
  1029  	}
  1030  }
  1031  
  1032  func mhelpgc() {
  1033  	_g_ := getg()
  1034  	_g_.m.helpgc = -1
  1035  }
  1036  
  1037  func startTheWorldWithSema() {
  1038  	_g_ := getg()
  1039  
  1040  	_g_.m.locks++        // disable preemption because it can be holding p in a local var
  1041  	gp := netpoll(false) // non-blocking
  1042  	injectglist(gp)
  1043  	add := needaddgcproc()
  1044  	lock(&sched.lock)
  1045  
  1046  	procs := gomaxprocs
  1047  	if newprocs != 0 {
  1048  		procs = newprocs
  1049  		newprocs = 0
  1050  	}
  1051  	p1 := procresize(procs)
  1052  	sched.gcwaiting = 0
  1053  	if sched.sysmonwait != 0 {
  1054  		sched.sysmonwait = 0
  1055  		notewakeup(&sched.sysmonnote)
  1056  	}
  1057  	unlock(&sched.lock)
  1058  
  1059  	for p1 != nil {
  1060  		p := p1
  1061  		p1 = p1.link.ptr()
  1062  		if p.m != 0 {
  1063  			mp := p.m.ptr()
  1064  			p.m = 0
  1065  			if mp.nextp != 0 {
  1066  				throw("startTheWorld: inconsistent mp->nextp")
  1067  			}
  1068  			mp.nextp.set(p)
  1069  			notewakeup(&mp.park)
  1070  		} else {
  1071  			// Start M to run P.  Do not start another M below.
  1072  			newm(nil, p)
  1073  			add = false
  1074  		}
  1075  	}
  1076  
  1077  	// Wakeup an additional proc in case we have excessive runnable goroutines
  1078  	// in local queues or in the global queue. If we don't, the proc will park itself.
  1079  	// If we have lots of excessive work, resetspinning will unpark additional procs as necessary.
  1080  	if atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 {
  1081  		wakep()
  1082  	}
  1083  
  1084  	if add {
  1085  		// If GC could have used another helper proc, start one now,
  1086  		// in the hope that it will be available next time.
  1087  		// It would have been even better to start it before the collection,
  1088  		// but doing so requires allocating memory, so it's tricky to
  1089  		// coordinate. This lazy approach works out in practice:
  1090  		// we don't mind if the first couple gc rounds don't have quite
  1091  		// the maximum number of procs.
  1092  		newm(mhelpgc, nil)
  1093  	}
  1094  	_g_.m.locks--
  1095  	if _g_.m.locks == 0 && _g_.preempt { // restore the preemption request in case we've cleared it in newstack
  1096  		_g_.stackguard0 = stackPreempt
  1097  	}
  1098  }
  1099  
  1100  // Called to start an M.
  1101  //go:nosplit
  1102  func mstart() {
  1103  	_g_ := getg()
  1104  
  1105  	if _g_.stack.lo == 0 {
  1106  		// Initialize stack bounds from system stack.
  1107  		// Cgo may have left stack size in stack.hi.
  1108  		size := _g_.stack.hi
  1109  		if size == 0 {
  1110  			size = 8192 * sys.StackGuardMultiplier
  1111  		}
  1112  		_g_.stack.hi = uintptr(noescape(unsafe.Pointer(&size)))
  1113  		_g_.stack.lo = _g_.stack.hi - size + 1024
  1114  	}
  1115  	// Initialize stack guards so that we can start calling
  1116  	// both Go and C functions with stack growth prologues.
  1117  	_g_.stackguard0 = _g_.stack.lo + _StackGuard
  1118  	_g_.stackguard1 = _g_.stackguard0
  1119  	mstart1()
  1120  }
  1121  
  1122  func mstart1() {
  1123  	_g_ := getg()
  1124  
  1125  	if _g_ != _g_.m.g0 {
  1126  		throw("bad runtime·mstart")
  1127  	}
  1128  
  1129  	// Record top of stack for use by mcall.
  1130  	// Once we call schedule we're never coming back,
  1131  	// so other calls can reuse this stack space.
  1132  	gosave(&_g_.m.g0.sched)
  1133  	_g_.m.g0.sched.pc = ^uintptr(0) // make sure it is never used
  1134  	asminit()
  1135  	minit()
  1136  
  1137  	// Install signal handlers; after minit so that minit can
  1138  	// prepare the thread to be able to handle the signals.
  1139  	if _g_.m == &m0 {
  1140  		// Create an extra M for callbacks on threads not created by Go.
  1141  		if iscgo && !cgoHasExtraM {
  1142  			cgoHasExtraM = true
  1143  			newextram()
  1144  		}
  1145  		initsig(false)
  1146  	}
  1147  
  1148  	if fn := _g_.m.mstartfn; fn != nil {
  1149  		fn()
  1150  	}
  1151  
  1152  	if _g_.m.helpgc != 0 {
  1153  		_g_.m.helpgc = 0
  1154  		stopm()
  1155  	} else if _g_.m != &m0 {
  1156  		acquirep(_g_.m.nextp.ptr())
  1157  		_g_.m.nextp = 0
  1158  	}
  1159  	schedule()
  1160  }
  1161  
  1162  // forEachP calls fn(p) for every P p when p reaches a GC safe point.
  1163  // If a P is currently executing code, this will bring the P to a GC
  1164  // safe point and execute fn on that P. If the P is not executing code
  1165  // (it is idle or in a syscall), this will call fn(p) directly while
  1166  // preventing the P from exiting its state. This does not ensure that
  1167  // fn will run on every CPU executing Go code, but it acts as a global
  1168  // memory barrier. GC uses this as a "ragged barrier."
  1169  //
  1170  // The caller must hold worldsema.
  1171  //
  1172  //go:systemstack
  1173  func forEachP(fn func(*p)) {
  1174  	mp := acquirem()
  1175  	_p_ := getg().m.p.ptr()
  1176  
  1177  	lock(&sched.lock)
  1178  	if sched.safePointWait != 0 {
  1179  		throw("forEachP: sched.safePointWait != 0")
  1180  	}
  1181  	sched.safePointWait = gomaxprocs - 1
  1182  	sched.safePointFn = fn
  1183  
  1184  	// Ask all Ps to run the safe point function.
  1185  	for _, p := range allp[:gomaxprocs] {
  1186  		if p != _p_ {
  1187  			atomic.Store(&p.runSafePointFn, 1)
  1188  		}
  1189  	}
  1190  	preemptall()
  1191  
  1192  	// Any P entering _Pidle or _Psyscall from now on will observe
  1193  	// p.runSafePointFn == 1 and will call runSafePointFn when
  1194  	// changing its status to _Pidle/_Psyscall.
  1195  
  1196  	// Run safe point function for all idle Ps. sched.pidle will
  1197  	// not change because we hold sched.lock.
  1198  	for p := sched.pidle.ptr(); p != nil; p = p.link.ptr() {
  1199  		if atomic.Cas(&p.runSafePointFn, 1, 0) {
  1200  			fn(p)
  1201  			sched.safePointWait--
  1202  		}
  1203  	}
  1204  
  1205  	wait := sched.safePointWait > 0
  1206  	unlock(&sched.lock)
  1207  
  1208  	// Run fn for the current P.
  1209  	fn(_p_)
  1210  
  1211  	// Force Ps currently in _Psyscall into _Pidle and hand them
  1212  	// off to induce safe point function execution.
  1213  	for i := 0; i < int(gomaxprocs); i++ {
  1214  		p := allp[i]
  1215  		s := p.status
  1216  		if s == _Psyscall && p.runSafePointFn == 1 && atomic.Cas(&p.status, s, _Pidle) {
  1217  			if trace.enabled {
  1218  				traceGoSysBlock(p)
  1219  				traceProcStop(p)
  1220  			}
  1221  			p.syscalltick++
  1222  			handoffp(p)
  1223  		}
  1224  	}
  1225  
  1226  	// Wait for remaining Ps to run fn.
  1227  	if wait {
  1228  		for {
  1229  			// Wait for 100us, then try to re-preempt in
  1230  			// case of any races.
  1231  			//
  1232  			// Requires system stack.
  1233  			if notetsleep(&sched.safePointNote, 100*1000) {
  1234  				noteclear(&sched.safePointNote)
  1235  				break
  1236  			}
  1237  			preemptall()
  1238  		}
  1239  	}
  1240  	if sched.safePointWait != 0 {
  1241  		throw("forEachP: not done")
  1242  	}
  1243  	for i := 0; i < int(gomaxprocs); i++ {
  1244  		p := allp[i]
  1245  		if p.runSafePointFn != 0 {
  1246  			throw("forEachP: P did not run fn")
  1247  		}
  1248  	}
  1249  
  1250  	lock(&sched.lock)
  1251  	sched.safePointFn = nil
  1252  	unlock(&sched.lock)
  1253  	releasem(mp)
  1254  }
  1255  
  1256  // runSafePointFn runs the safe point function, if any, for this P.
  1257  // This should be called like
  1258  //
  1259  //     if getg().m.p.runSafePointFn != 0 {
  1260  //         runSafePointFn()
  1261  //     }
  1262  //
  1263  // runSafePointFn must be checked on any transition in to _Pidle or
  1264  // _Psyscall to avoid a race where forEachP sees that the P is running
  1265  // just before the P goes into _Pidle/_Psyscall and neither forEachP
  1266  // nor the P run the safe-point function.
  1267  func runSafePointFn() {
  1268  	p := getg().m.p.ptr()
  1269  	// Resolve the race between forEachP running the safe-point
  1270  	// function on this P's behalf and this P running the
  1271  	// safe-point function directly.
  1272  	if !atomic.Cas(&p.runSafePointFn, 1, 0) {
  1273  		return
  1274  	}
  1275  	sched.safePointFn(p)
  1276  	lock(&sched.lock)
  1277  	sched.safePointWait--
  1278  	if sched.safePointWait == 0 {
  1279  		notewakeup(&sched.safePointNote)
  1280  	}
  1281  	unlock(&sched.lock)
  1282  }
  1283  
  1284  // When running with cgo, we call _cgo_thread_start
  1285  // to start threads for us so that we can play nicely with
  1286  // foreign code.
  1287  var cgoThreadStart unsafe.Pointer
  1288  
  1289  type cgothreadstart struct {
  1290  	g   guintptr
  1291  	tls *uint64
  1292  	fn  unsafe.Pointer
  1293  }
  1294  
  1295  // Allocate a new m unassociated with any thread.
  1296  // Can use p for allocation context if needed.
  1297  // fn is recorded as the new m's m.mstartfn.
  1298  //
  1299  // This function is allowed to have write barriers even if the caller
  1300  // isn't because it borrows _p_.
  1301  //
  1302  //go:yeswritebarrierrec
  1303  func allocm(_p_ *p, fn func()) *m {
  1304  	_g_ := getg()
  1305  	_g_.m.locks++ // disable GC because it can be called from sysmon
  1306  	if _g_.m.p == 0 {
  1307  		acquirep(_p_) // temporarily borrow p for mallocs in this function
  1308  	}
  1309  	mp := new(m)
  1310  	mp.mstartfn = fn
  1311  	mcommoninit(mp)
  1312  
  1313  	// In case of cgo or Solaris, pthread_create will make us a stack.
  1314  	// Windows and Plan 9 will layout sched stack on OS stack.
  1315  	if iscgo || GOOS == "solaris" || GOOS == "windows" || GOOS == "plan9" {
  1316  		mp.g0 = malg(-1)
  1317  	} else {
  1318  		mp.g0 = malg(8192 * sys.StackGuardMultiplier)
  1319  	}
  1320  	mp.g0.m = mp
  1321  
  1322  	if _p_ == _g_.m.p.ptr() {
  1323  		releasep()
  1324  	}
  1325  	_g_.m.locks--
  1326  	if _g_.m.locks == 0 && _g_.preempt { // restore the preemption request in case we've cleared it in newstack
  1327  		_g_.stackguard0 = stackPreempt
  1328  	}
  1329  
  1330  	return mp
  1331  }
  1332  
  1333  // needm is called when a cgo callback happens on a
  1334  // thread without an m (a thread not created by Go).
  1335  // In this case, needm is expected to find an m to use
  1336  // and return with m, g initialized correctly.
  1337  // Since m and g are not set now (likely nil, but see below)
  1338  // needm is limited in what routines it can call. In particular
  1339  // it can only call nosplit functions (textflag 7) and cannot
  1340  // do any scheduling that requires an m.
  1341  //
  1342  // In order to avoid needing heavy lifting here, we adopt
  1343  // the following strategy: there is a stack of available m's
  1344  // that can be stolen. Using compare-and-swap
  1345  // to pop from the stack has ABA races, so we simulate
  1346  // a lock by doing an exchange (via casp) to steal the stack
  1347  // head and replace the top pointer with MLOCKED (1).
  1348  // This serves as a simple spin lock that we can use even
  1349  // without an m. The thread that locks the stack in this way
  1350  // unlocks the stack by storing a valid stack head pointer.
  1351  //
  1352  // In order to make sure that there is always an m structure
  1353  // available to be stolen, we maintain the invariant that there
  1354  // is always one more than needed. At the beginning of the
  1355  // program (if cgo is in use) the list is seeded with a single m.
  1356  // If needm finds that it has taken the last m off the list, its job
  1357  // is - once it has installed its own m so that it can do things like
  1358  // allocate memory - to create a spare m and put it on the list.
  1359  //
  1360  // Each of these extra m's also has a g0 and a curg that are
  1361  // pressed into service as the scheduling stack and current
  1362  // goroutine for the duration of the cgo callback.
  1363  //
  1364  // When the callback is done with the m, it calls dropm to
  1365  // put the m back on the list.
  1366  //go:nosplit
  1367  func needm(x byte) {
  1368  	if iscgo && !cgoHasExtraM {
  1369  		// Can happen if C/C++ code calls Go from a global ctor.
  1370  		// Can not throw, because scheduler is not initialized yet.
  1371  		write(2, unsafe.Pointer(&earlycgocallback[0]), int32(len(earlycgocallback)))
  1372  		exit(1)
  1373  	}
  1374  
  1375  	// Lock extra list, take head, unlock popped list.
  1376  	// nilokay=false is safe here because of the invariant above,
  1377  	// that the extra list always contains or will soon contain
  1378  	// at least one m.
  1379  	mp := lockextra(false)
  1380  
  1381  	// Set needextram when we've just emptied the list,
  1382  	// so that the eventual call into cgocallbackg will
  1383  	// allocate a new m for the extra list. We delay the
  1384  	// allocation until then so that it can be done
  1385  	// after exitsyscall makes sure it is okay to be
  1386  	// running at all (that is, there's no garbage collection
  1387  	// running right now).
  1388  	mp.needextram = mp.schedlink == 0
  1389  	unlockextra(mp.schedlink.ptr())
  1390  
  1391  	// Save and block signals before installing g.
  1392  	// Once g is installed, any incoming signals will try to execute,
  1393  	// but we won't have the sigaltstack settings and other data
  1394  	// set up appropriately until the end of minit, which will
  1395  	// unblock the signals. This is the same dance as when
  1396  	// starting a new m to run Go code via newosproc.
  1397  	msigsave(mp)
  1398  	sigblock()
  1399  
  1400  	// Install g (= m->g0) and set the stack bounds
  1401  	// to match the current stack. We don't actually know
  1402  	// how big the stack is, like we don't know how big any
  1403  	// scheduling stack is, but we assume there's at least 32 kB,
  1404  	// which is more than enough for us.
  1405  	setg(mp.g0)
  1406  	_g_ := getg()
  1407  	_g_.stack.hi = uintptr(noescape(unsafe.Pointer(&x))) + 1024
  1408  	_g_.stack.lo = uintptr(noescape(unsafe.Pointer(&x))) - 32*1024
  1409  	_g_.stackguard0 = _g_.stack.lo + _StackGuard
  1410  
  1411  	// Initialize this thread to use the m.
  1412  	asminit()
  1413  	minit()
  1414  }
  1415  
  1416  var earlycgocallback = []byte("fatal error: cgo callback before cgo call\n")
  1417  
  1418  // newextram allocates m's and puts them on the extra list.
  1419  // It is called with a working local m, so that it can do things
  1420  // like call schedlock and allocate.
  1421  func newextram() {
  1422  	c := atomic.Xchg(&extraMWaiters, 0)
  1423  	if c > 0 {
  1424  		for i := uint32(0); i < c; i++ {
  1425  			oneNewExtraM()
  1426  		}
  1427  	} else {
  1428  		// Make sure there is at least one extra M.
  1429  		mp := lockextra(true)
  1430  		unlockextra(mp)
  1431  		if mp == nil {
  1432  			oneNewExtraM()
  1433  		}
  1434  	}
  1435  }
  1436  
  1437  // oneNewExtraM allocates an m and puts it on the extra list.
  1438  func oneNewExtraM() {
  1439  	// Create extra goroutine locked to extra m.
  1440  	// The goroutine is the context in which the cgo callback will run.
  1441  	// The sched.pc will never be returned to, but setting it to
  1442  	// goexit makes clear to the traceback routines where
  1443  	// the goroutine stack ends.
  1444  	mp := allocm(nil, nil)
  1445  	gp := malg(4096)
  1446  	gp.sched.pc = funcPC(goexit) + sys.PCQuantum
  1447  	gp.sched.sp = gp.stack.hi
  1448  	gp.sched.sp -= 4 * sys.RegSize // extra space in case of reads slightly beyond frame
  1449  	gp.sched.lr = 0
  1450  	gp.sched.g = guintptr(unsafe.Pointer(gp))
  1451  	gp.syscallpc = gp.sched.pc
  1452  	gp.syscallsp = gp.sched.sp
  1453  	gp.stktopsp = gp.sched.sp
  1454  	gp.gcscanvalid = true // fresh G, so no dequeueRescan necessary
  1455  	gp.gcscandone = true
  1456  	gp.gcRescan = -1
  1457  	// malg returns status as Gidle, change to Gsyscall before adding to allg
  1458  	// where GC will see it.
  1459  	casgstatus(gp, _Gidle, _Gsyscall)
  1460  	gp.m = mp
  1461  	mp.curg = gp
  1462  	mp.locked = _LockInternal
  1463  	mp.lockedg = gp
  1464  	gp.lockedm = mp
  1465  	gp.goid = int64(atomic.Xadd64(&sched.goidgen, 1))
  1466  	if raceenabled {
  1467  		gp.racectx = racegostart(funcPC(newextram) + sys.PCQuantum)
  1468  	}
  1469  	// put on allg for garbage collector
  1470  	allgadd(gp)
  1471  
  1472  	// Add m to the extra list.
  1473  	mnext := lockextra(true)
  1474  	mp.schedlink.set(mnext)
  1475  	unlockextra(mp)
  1476  }
  1477  
  1478  // dropm is called when a cgo callback has called needm but is now
  1479  // done with the callback and returning back into the non-Go thread.
  1480  // It puts the current m back onto the extra list.
  1481  //
  1482  // The main expense here is the call to signalstack to release the
  1483  // m's signal stack, and then the call to needm on the next callback
  1484  // from this thread. It is tempting to try to save the m for next time,
  1485  // which would eliminate both these costs, but there might not be
  1486  // a next time: the current thread (which Go does not control) might exit.
  1487  // If we saved the m for that thread, there would be an m leak each time
  1488  // such a thread exited. Instead, we acquire and release an m on each
  1489  // call. These should typically not be scheduling operations, just a few
  1490  // atomics, so the cost should be small.
  1491  //
  1492  // TODO(rsc): An alternative would be to allocate a dummy pthread per-thread
  1493  // variable using pthread_key_create. Unlike the pthread keys we already use
  1494  // on OS X, this dummy key would never be read by Go code. It would exist
  1495  // only so that we could register at thread-exit-time destructor.
  1496  // That destructor would put the m back onto the extra list.
  1497  // This is purely a performance optimization. The current version,
  1498  // in which dropm happens on each cgo call, is still correct too.
  1499  // We may have to keep the current version on systems with cgo
  1500  // but without pthreads, like Windows.
  1501  func dropm() {
  1502  	// Clear m and g, and return m to the extra list.
  1503  	// After the call to setg we can only call nosplit functions
  1504  	// with no pointer manipulation.
  1505  	mp := getg().m
  1506  
  1507  	// Block signals before unminit.
  1508  	// Unminit unregisters the signal handling stack (but needs g on some systems).
  1509  	// Setg(nil) clears g, which is the signal handler's cue not to run Go handlers.
  1510  	// It's important not to try to handle a signal between those two steps.
  1511  	sigmask := mp.sigmask
  1512  	sigblock()
  1513  	unminit()
  1514  
  1515  	mnext := lockextra(true)
  1516  	mp.schedlink.set(mnext)
  1517  
  1518  	setg(nil)
  1519  
  1520  	// Commit the release of mp.
  1521  	unlockextra(mp)
  1522  
  1523  	msigrestore(sigmask)
  1524  }
  1525  
  1526  // A helper function for EnsureDropM.
  1527  func getm() uintptr {
  1528  	return uintptr(unsafe.Pointer(getg().m))
  1529  }
  1530  
  1531  var extram uintptr
  1532  var extraMWaiters uint32
  1533  
  1534  // lockextra locks the extra list and returns the list head.
  1535  // The caller must unlock the list by storing a new list head
  1536  // to extram. If nilokay is true, then lockextra will
  1537  // return a nil list head if that's what it finds. If nilokay is false,
  1538  // lockextra will keep waiting until the list head is no longer nil.
  1539  //go:nosplit
  1540  func lockextra(nilokay bool) *m {
  1541  	const locked = 1
  1542  
  1543  	incr := false
  1544  	for {
  1545  		old := atomic.Loaduintptr(&extram)
  1546  		if old == locked {
  1547  			yield := osyield
  1548  			yield()
  1549  			continue
  1550  		}
  1551  		if old == 0 && !nilokay {
  1552  			if !incr {
  1553  				// Add 1 to the number of threads
  1554  				// waiting for an M.
  1555  				// This is cleared by newextram.
  1556  				atomic.Xadd(&extraMWaiters, 1)
  1557  				incr = true
  1558  			}
  1559  			usleep(1)
  1560  			continue
  1561  		}
  1562  		if atomic.Casuintptr(&extram, old, locked) {
  1563  			return (*m)(unsafe.Pointer(old))
  1564  		}
  1565  		yield := osyield
  1566  		yield()
  1567  		continue
  1568  	}
  1569  }
  1570  
  1571  //go:nosplit
  1572  func unlockextra(mp *m) {
  1573  	atomic.Storeuintptr(&extram, uintptr(unsafe.Pointer(mp)))
  1574  }
  1575  
  1576  // Create a new m. It will start off with a call to fn, or else the scheduler.
  1577  // fn needs to be static and not a heap allocated closure.
  1578  // May run with m.p==nil, so write barriers are not allowed.
  1579  //go:nowritebarrierrec
  1580  func newm(fn func(), _p_ *p) {
  1581  	mp := allocm(_p_, fn)
  1582  	mp.nextp.set(_p_)
  1583  	mp.sigmask = initSigmask
  1584  	if iscgo {
  1585  		var ts cgothreadstart
  1586  		if _cgo_thread_start == nil {
  1587  			throw("_cgo_thread_start missing")
  1588  		}
  1589  		ts.g.set(mp.g0)
  1590  		ts.tls = (*uint64)(unsafe.Pointer(&mp.tls[0]))
  1591  		ts.fn = unsafe.Pointer(funcPC(mstart))
  1592  		if msanenabled {
  1593  			msanwrite(unsafe.Pointer(&ts), unsafe.Sizeof(ts))
  1594  		}
  1595  		asmcgocall(_cgo_thread_start, unsafe.Pointer(&ts))
  1596  		return
  1597  	}
  1598  	newosproc(mp, unsafe.Pointer(mp.g0.stack.hi))
  1599  }
  1600  
  1601  // Stops execution of the current m until new work is available.
  1602  // Returns with acquired P.
  1603  func stopm() {
  1604  	_g_ := getg()
  1605  
  1606  	if _g_.m.locks != 0 {
  1607  		throw("stopm holding locks")
  1608  	}
  1609  	if _g_.m.p != 0 {
  1610  		throw("stopm holding p")
  1611  	}
  1612  	if _g_.m.spinning {
  1613  		throw("stopm spinning")
  1614  	}
  1615  
  1616  retry:
  1617  	lock(&sched.lock)
  1618  	mput(_g_.m)
  1619  	unlock(&sched.lock)
  1620  	notesleep(&_g_.m.park)
  1621  	noteclear(&_g_.m.park)
  1622  	if _g_.m.helpgc != 0 {
  1623  		gchelper()
  1624  		_g_.m.helpgc = 0
  1625  		_g_.m.mcache = nil
  1626  		_g_.m.p = 0
  1627  		goto retry
  1628  	}
  1629  	acquirep(_g_.m.nextp.ptr())
  1630  	_g_.m.nextp = 0
  1631  }
  1632  
  1633  func mspinning() {
  1634  	// startm's caller incremented nmspinning. Set the new M's spinning.
  1635  	getg().m.spinning = true
  1636  }
  1637  
  1638  // Schedules some M to run the p (creates an M if necessary).
  1639  // If p==nil, tries to get an idle P, if no idle P's does nothing.
  1640  // May run with m.p==nil, so write barriers are not allowed.
  1641  // If spinning is set, the caller has incremented nmspinning and startm will
  1642  // either decrement nmspinning or set m.spinning in the newly started M.
  1643  //go:nowritebarrierrec
  1644  func startm(_p_ *p, spinning bool) {
  1645  	lock(&sched.lock)
  1646  	if _p_ == nil {
  1647  		_p_ = pidleget()
  1648  		if _p_ == nil {
  1649  			unlock(&sched.lock)
  1650  			if spinning {
  1651  				// The caller incremented nmspinning, but there are no idle Ps,
  1652  				// so it's okay to just undo the increment and give up.
  1653  				if int32(atomic.Xadd(&sched.nmspinning, -1)) < 0 {
  1654  					throw("startm: negative nmspinning")
  1655  				}
  1656  			}
  1657  			return
  1658  		}
  1659  	}
  1660  	mp := mget()
  1661  	unlock(&sched.lock)
  1662  	if mp == nil {
  1663  		var fn func()
  1664  		if spinning {
  1665  			// The caller incremented nmspinning, so set m.spinning in the new M.
  1666  			fn = mspinning
  1667  		}
  1668  		newm(fn, _p_)
  1669  		return
  1670  	}
  1671  	if mp.spinning {
  1672  		throw("startm: m is spinning")
  1673  	}
  1674  	if mp.nextp != 0 {
  1675  		throw("startm: m has p")
  1676  	}
  1677  	if spinning && !runqempty(_p_) {
  1678  		throw("startm: p has runnable gs")
  1679  	}
  1680  	// The caller incremented nmspinning, so set m.spinning in the new M.
  1681  	mp.spinning = spinning
  1682  	mp.nextp.set(_p_)
  1683  	notewakeup(&mp.park)
  1684  }
  1685  
  1686  // Hands off P from syscall or locked M.
  1687  // Always runs without a P, so write barriers are not allowed.
  1688  //go:nowritebarrierrec
  1689  func handoffp(_p_ *p) {
  1690  	// handoffp must start an M in any situation where
  1691  	// findrunnable would return a G to run on _p_.
  1692  
  1693  	// if it has local work, start it straight away
  1694  	if !runqempty(_p_) || sched.runqsize != 0 {
  1695  		startm(_p_, false)
  1696  		return
  1697  	}
  1698  	// if it has GC work, start it straight away
  1699  	if gcBlackenEnabled != 0 && gcMarkWorkAvailable(_p_) {
  1700  		startm(_p_, false)
  1701  		return
  1702  	}
  1703  	// no local work, check that there are no spinning/idle M's,
  1704  	// otherwise our help is not required
  1705  	if atomic.Load(&sched.nmspinning)+atomic.Load(&sched.npidle) == 0 && atomic.Cas(&sched.nmspinning, 0, 1) { // TODO: fast atomic
  1706  		startm(_p_, true)
  1707  		return
  1708  	}
  1709  	lock(&sched.lock)
  1710  	if sched.gcwaiting != 0 {
  1711  		_p_.status = _Pgcstop
  1712  		sched.stopwait--
  1713  		if sched.stopwait == 0 {
  1714  			notewakeup(&sched.stopnote)
  1715  		}
  1716  		unlock(&sched.lock)
  1717  		return
  1718  	}
  1719  	if _p_.runSafePointFn != 0 && atomic.Cas(&_p_.runSafePointFn, 1, 0) {
  1720  		sched.safePointFn(_p_)
  1721  		sched.safePointWait--
  1722  		if sched.safePointWait == 0 {
  1723  			notewakeup(&sched.safePointNote)
  1724  		}
  1725  	}
  1726  	if sched.runqsize != 0 {
  1727  		unlock(&sched.lock)
  1728  		startm(_p_, false)
  1729  		return
  1730  	}
  1731  	// If this is the last running P and nobody is polling network,
  1732  	// need to wakeup another M to poll network.
  1733  	if sched.npidle == uint32(gomaxprocs-1) && atomic.Load64(&sched.lastpoll) != 0 {
  1734  		unlock(&sched.lock)
  1735  		startm(_p_, false)
  1736  		return
  1737  	}
  1738  	pidleput(_p_)
  1739  	unlock(&sched.lock)
  1740  }
  1741  
  1742  // Tries to add one more P to execute G's.
  1743  // Called when a G is made runnable (newproc, ready).
  1744  func wakep() {
  1745  	// be conservative about spinning threads
  1746  	if !atomic.Cas(&sched.nmspinning, 0, 1) {
  1747  		return
  1748  	}
  1749  	startm(nil, true)
  1750  }
  1751  
  1752  // Stops execution of the current m that is locked to a g until the g is runnable again.
  1753  // Returns with acquired P.
  1754  func stoplockedm() {
  1755  	_g_ := getg()
  1756  
  1757  	if _g_.m.lockedg == nil || _g_.m.lockedg.lockedm != _g_.m {
  1758  		throw("stoplockedm: inconsistent locking")
  1759  	}
  1760  	if _g_.m.p != 0 {
  1761  		// Schedule another M to run this p.
  1762  		_p_ := releasep()
  1763  		handoffp(_p_)
  1764  	}
  1765  	incidlelocked(1)
  1766  	// Wait until another thread schedules lockedg again.
  1767  	notesleep(&_g_.m.park)
  1768  	noteclear(&_g_.m.park)
  1769  	status := readgstatus(_g_.m.lockedg)
  1770  	if status&^_Gscan != _Grunnable {
  1771  		print("runtime:stoplockedm: g is not Grunnable or Gscanrunnable\n")
  1772  		dumpgstatus(_g_)
  1773  		throw("stoplockedm: not runnable")
  1774  	}
  1775  	acquirep(_g_.m.nextp.ptr())
  1776  	_g_.m.nextp = 0
  1777  }
  1778  
  1779  // Schedules the locked m to run the locked gp.
  1780  // May run during STW, so write barriers are not allowed.
  1781  //go:nowritebarrierrec
  1782  func startlockedm(gp *g) {
  1783  	_g_ := getg()
  1784  
  1785  	mp := gp.lockedm
  1786  	if mp == _g_.m {
  1787  		throw("startlockedm: locked to me")
  1788  	}
  1789  	if mp.nextp != 0 {
  1790  		throw("startlockedm: m has p")
  1791  	}
  1792  	// directly handoff current P to the locked m
  1793  	incidlelocked(-1)
  1794  	_p_ := releasep()
  1795  	mp.nextp.set(_p_)
  1796  	notewakeup(&mp.park)
  1797  	stopm()
  1798  }
  1799  
  1800  // Stops the current m for stopTheWorld.
  1801  // Returns when the world is restarted.
  1802  func gcstopm() {
  1803  	_g_ := getg()
  1804  
  1805  	if sched.gcwaiting == 0 {
  1806  		throw("gcstopm: not waiting for gc")
  1807  	}
  1808  	if _g_.m.spinning {
  1809  		_g_.m.spinning = false
  1810  		// OK to just drop nmspinning here,
  1811  		// startTheWorld will unpark threads as necessary.
  1812  		if int32(atomic.Xadd(&sched.nmspinning, -1)) < 0 {
  1813  			throw("gcstopm: negative nmspinning")
  1814  		}
  1815  	}
  1816  	_p_ := releasep()
  1817  	lock(&sched.lock)
  1818  	_p_.status = _Pgcstop
  1819  	sched.stopwait--
  1820  	if sched.stopwait == 0 {
  1821  		notewakeup(&sched.stopnote)
  1822  	}
  1823  	unlock(&sched.lock)
  1824  	stopm()
  1825  }
  1826  
  1827  // Schedules gp to run on the current M.
  1828  // If inheritTime is true, gp inherits the remaining time in the
  1829  // current time slice. Otherwise, it starts a new time slice.
  1830  // Never returns.
  1831  //
  1832  // Write barriers are allowed because this is called immediately after
  1833  // acquiring a P in several places.
  1834  //
  1835  //go:yeswritebarrierrec
  1836  func execute(gp *g, inheritTime bool) {
  1837  	_g_ := getg()
  1838  
  1839  	casgstatus(gp, _Grunnable, _Grunning)
  1840  	gp.waitsince = 0
  1841  	gp.preempt = false
  1842  	gp.stackguard0 = gp.stack.lo + _StackGuard
  1843  	if !inheritTime {
  1844  		_g_.m.p.ptr().schedtick++
  1845  	}
  1846  	_g_.m.curg = gp
  1847  	gp.m = _g_.m
  1848  
  1849  	// Check whether the profiler needs to be turned on or off.
  1850  	hz := sched.profilehz
  1851  	if _g_.m.profilehz != hz {
  1852  		resetcpuprofiler(hz)
  1853  	}
  1854  
  1855  	if trace.enabled {
  1856  		// GoSysExit has to happen when we have a P, but before GoStart.
  1857  		// So we emit it here.
  1858  		if gp.syscallsp != 0 && gp.sysblocktraced {
  1859  			traceGoSysExit(gp.sysexitticks)
  1860  		}
  1861  		traceGoStart()
  1862  	}
  1863  
  1864  	gogo(&gp.sched)
  1865  }
  1866  
  1867  // Finds a runnable goroutine to execute.
  1868  // Tries to steal from other P's, get g from global queue, poll network.
  1869  func findrunnable() (gp *g, inheritTime bool) {
  1870  	_g_ := getg()
  1871  
  1872  	// The conditions here and in handoffp must agree: if
  1873  	// findrunnable would return a G to run, handoffp must start
  1874  	// an M.
  1875  
  1876  top:
  1877  	_p_ := _g_.m.p.ptr()
  1878  	if sched.gcwaiting != 0 {
  1879  		gcstopm()
  1880  		goto top
  1881  	}
  1882  	if _p_.runSafePointFn != 0 {
  1883  		runSafePointFn()
  1884  	}
  1885  	if fingwait && fingwake {
  1886  		if gp := wakefing(); gp != nil {
  1887  			ready(gp, 0, true)
  1888  		}
  1889  	}
  1890  
  1891  	// local runq
  1892  	if gp, inheritTime := runqget(_p_); gp != nil {
  1893  		return gp, inheritTime
  1894  	}
  1895  
  1896  	// global runq
  1897  	if sched.runqsize != 0 {
  1898  		lock(&sched.lock)
  1899  		gp := globrunqget(_p_, 0)
  1900  		unlock(&sched.lock)
  1901  		if gp != nil {
  1902  			return gp, false
  1903  		}
  1904  	}
  1905  
  1906  	// Poll network.
  1907  	// This netpoll is only an optimization before we resort to stealing.
  1908  	// We can safely skip it if there a thread blocked in netpoll already.
  1909  	// If there is any kind of logical race with that blocked thread
  1910  	// (e.g. it has already returned from netpoll, but does not set lastpoll yet),
  1911  	// this thread will do blocking netpoll below anyway.
  1912  	if netpollinited() && sched.lastpoll != 0 {
  1913  		if gp := netpoll(false); gp != nil { // non-blocking
  1914  			// netpoll returns list of goroutines linked by schedlink.
  1915  			injectglist(gp.schedlink.ptr())
  1916  			casgstatus(gp, _Gwaiting, _Grunnable)
  1917  			if trace.enabled {
  1918  				traceGoUnpark(gp, 0)
  1919  			}
  1920  			return gp, false
  1921  		}
  1922  	}
  1923  
  1924  	// Steal work from other P's.
  1925  	procs := uint32(gomaxprocs)
  1926  	if atomic.Load(&sched.npidle) == procs-1 {
  1927  		// Either GOMAXPROCS=1 or everybody, except for us, is idle already.
  1928  		// New work can appear from returning syscall/cgocall, network or timers.
  1929  		// Neither of that submits to local run queues, so no point in stealing.
  1930  		goto stop
  1931  	}
  1932  	// If number of spinning M's >= number of busy P's, block.
  1933  	// This is necessary to prevent excessive CPU consumption
  1934  	// when GOMAXPROCS>>1 but the program parallelism is low.
  1935  	if !_g_.m.spinning && 2*atomic.Load(&sched.nmspinning) >= procs-atomic.Load(&sched.npidle) {
  1936  		goto stop
  1937  	}
  1938  	if !_g_.m.spinning {
  1939  		_g_.m.spinning = true
  1940  		atomic.Xadd(&sched.nmspinning, 1)
  1941  	}
  1942  	for i := 0; i < 4; i++ {
  1943  		for enum := stealOrder.start(fastrand()); !enum.done(); enum.next() {
  1944  			if sched.gcwaiting != 0 {
  1945  				goto top
  1946  			}
  1947  			stealRunNextG := i > 2 // first look for ready queues with more than 1 g
  1948  			if gp := runqsteal(_p_, allp[enum.position()], stealRunNextG); gp != nil {
  1949  				return gp, false
  1950  			}
  1951  		}
  1952  	}
  1953  
  1954  stop:
  1955  
  1956  	// We have nothing to do. If we're in the GC mark phase, can
  1957  	// safely scan and blacken objects, and have work to do, run
  1958  	// idle-time marking rather than give up the P.
  1959  	if gcBlackenEnabled != 0 && _p_.gcBgMarkWorker != 0 && gcMarkWorkAvailable(_p_) {
  1960  		_p_.gcMarkWorkerMode = gcMarkWorkerIdleMode
  1961  		gp := _p_.gcBgMarkWorker.ptr()
  1962  		casgstatus(gp, _Gwaiting, _Grunnable)
  1963  		if trace.enabled {
  1964  			traceGoUnpark(gp, 0)
  1965  		}
  1966  		return gp, false
  1967  	}
  1968  
  1969  	// return P and block
  1970  	lock(&sched.lock)
  1971  	if sched.gcwaiting != 0 || _p_.runSafePointFn != 0 {
  1972  		unlock(&sched.lock)
  1973  		goto top
  1974  	}
  1975  	if sched.runqsize != 0 {
  1976  		gp := globrunqget(_p_, 0)
  1977  		unlock(&sched.lock)
  1978  		return gp, false
  1979  	}
  1980  	if releasep() != _p_ {
  1981  		throw("findrunnable: wrong p")
  1982  	}
  1983  	pidleput(_p_)
  1984  	unlock(&sched.lock)
  1985  
  1986  	// Delicate dance: thread transitions from spinning to non-spinning state,
  1987  	// potentially concurrently with submission of new goroutines. We must
  1988  	// drop nmspinning first and then check all per-P queues again (with
  1989  	// #StoreLoad memory barrier in between). If we do it the other way around,
  1990  	// another thread can submit a goroutine after we've checked all run queues
  1991  	// but before we drop nmspinning; as the result nobody will unpark a thread
  1992  	// to run the goroutine.
  1993  	// If we discover new work below, we need to restore m.spinning as a signal
  1994  	// for resetspinning to unpark a new worker thread (because there can be more
  1995  	// than one starving goroutine). However, if after discovering new work
  1996  	// we also observe no idle Ps, it is OK to just park the current thread:
  1997  	// the system is fully loaded so no spinning threads are required.
  1998  	// Also see "Worker thread parking/unparking" comment at the top of the file.
  1999  	wasSpinning := _g_.m.spinning
  2000  	if _g_.m.spinning {
  2001  		_g_.m.spinning = false
  2002  		if int32(atomic.Xadd(&sched.nmspinning, -1)) < 0 {
  2003  			throw("findrunnable: negative nmspinning")
  2004  		}
  2005  	}
  2006  
  2007  	// check all runqueues once again
  2008  	for i := 0; i < int(gomaxprocs); i++ {
  2009  		_p_ := allp[i]
  2010  		if _p_ != nil && !runqempty(_p_) {
  2011  			lock(&sched.lock)
  2012  			_p_ = pidleget()
  2013  			unlock(&sched.lock)
  2014  			if _p_ != nil {
  2015  				acquirep(_p_)
  2016  				if wasSpinning {
  2017  					_g_.m.spinning = true
  2018  					atomic.Xadd(&sched.nmspinning, 1)
  2019  				}
  2020  				goto top
  2021  			}
  2022  			break
  2023  		}
  2024  	}
  2025  
  2026  	// poll network
  2027  	if netpollinited() && atomic.Xchg64(&sched.lastpoll, 0) != 0 {
  2028  		if _g_.m.p != 0 {
  2029  			throw("findrunnable: netpoll with p")
  2030  		}
  2031  		if _g_.m.spinning {
  2032  			throw("findrunnable: netpoll with spinning")
  2033  		}
  2034  		gp := netpoll(true) // block until new work is available
  2035  		atomic.Store64(&sched.lastpoll, uint64(nanotime()))
  2036  		if gp != nil {
  2037  			lock(&sched.lock)
  2038  			_p_ = pidleget()
  2039  			unlock(&sched.lock)
  2040  			if _p_ != nil {
  2041  				acquirep(_p_)
  2042  				injectglist(gp.schedlink.ptr())
  2043  				casgstatus(gp, _Gwaiting, _Grunnable)
  2044  				if trace.enabled {
  2045  					traceGoUnpark(gp, 0)
  2046  				}
  2047  				return gp, false
  2048  			}
  2049  			injectglist(gp)
  2050  		}
  2051  	}
  2052  	stopm()
  2053  	goto top
  2054  }
  2055  
  2056  func resetspinning() {
  2057  	_g_ := getg()
  2058  	if !_g_.m.spinning {
  2059  		throw("resetspinning: not a spinning m")
  2060  	}
  2061  	_g_.m.spinning = false
  2062  	nmspinning := atomic.Xadd(&sched.nmspinning, -1)
  2063  	if int32(nmspinning) < 0 {
  2064  		throw("findrunnable: negative nmspinning")
  2065  	}
  2066  	// M wakeup policy is deliberately somewhat conservative, so check if we
  2067  	// need to wakeup another P here. See "Worker thread parking/unparking"
  2068  	// comment at the top of the file for details.
  2069  	if nmspinning == 0 && atomic.Load(&sched.npidle) > 0 {
  2070  		wakep()
  2071  	}
  2072  }
  2073  
  2074  // Injects the list of runnable G's into the scheduler.
  2075  // Can run concurrently with GC.
  2076  func injectglist(glist *g) {
  2077  	if glist == nil {
  2078  		return
  2079  	}
  2080  	if trace.enabled {
  2081  		for gp := glist; gp != nil; gp = gp.schedlink.ptr() {
  2082  			traceGoUnpark(gp, 0)
  2083  		}
  2084  	}
  2085  	lock(&sched.lock)
  2086  	var n int
  2087  	for n = 0; glist != nil; n++ {
  2088  		gp := glist
  2089  		glist = gp.schedlink.ptr()
  2090  		casgstatus(gp, _Gwaiting, _Grunnable)
  2091  		globrunqput(gp)
  2092  	}
  2093  	unlock(&sched.lock)
  2094  	for ; n != 0 && sched.npidle != 0; n-- {
  2095  		startm(nil, false)
  2096  	}
  2097  }
  2098  
  2099  // One round of scheduler: find a runnable goroutine and execute it.
  2100  // Never returns.
  2101  func schedule() {
  2102  	_g_ := getg()
  2103  
  2104  	if _g_.m.locks != 0 {
  2105  		throw("schedule: holding locks")
  2106  	}
  2107  
  2108  	if _g_.m.lockedg != nil {
  2109  		stoplockedm()
  2110  		execute(_g_.m.lockedg, false) // Never returns.
  2111  	}
  2112  
  2113  top:
  2114  	if sched.gcwaiting != 0 {
  2115  		gcstopm()
  2116  		goto top
  2117  	}
  2118  	if _g_.m.p.ptr().runSafePointFn != 0 {
  2119  		runSafePointFn()
  2120  	}
  2121  
  2122  	var gp *g
  2123  	var inheritTime bool
  2124  	if trace.enabled || trace.shutdown {
  2125  		gp = traceReader()
  2126  		if gp != nil {
  2127  			casgstatus(gp, _Gwaiting, _Grunnable)
  2128  			traceGoUnpark(gp, 0)
  2129  		}
  2130  	}
  2131  	if gp == nil && gcBlackenEnabled != 0 {
  2132  		gp = gcController.findRunnableGCWorker(_g_.m.p.ptr())
  2133  	}
  2134  	if gp == nil {
  2135  		// Check the global runnable queue once in a while to ensure fairness.
  2136  		// Otherwise two goroutines can completely occupy the local runqueue
  2137  		// by constantly respawning each other.
  2138  		if _g_.m.p.ptr().schedtick%61 == 0 && sched.runqsize > 0 {
  2139  			lock(&sched.lock)
  2140  			gp = globrunqget(_g_.m.p.ptr(), 1)
  2141  			unlock(&sched.lock)
  2142  		}
  2143  	}
  2144  	if gp == nil {
  2145  		gp, inheritTime = runqget(_g_.m.p.ptr())
  2146  		if gp != nil && _g_.m.spinning {
  2147  			throw("schedule: spinning with local work")
  2148  		}
  2149  	}
  2150  	if gp == nil {
  2151  		gp, inheritTime = findrunnable() // blocks until work is available
  2152  	}
  2153  
  2154  	// This thread is going to run a goroutine and is not spinning anymore,
  2155  	// so if it was marked as spinning we need to reset it now and potentially
  2156  	// start a new spinning M.
  2157  	if _g_.m.spinning {
  2158  		resetspinning()
  2159  	}
  2160  
  2161  	if gp.lockedm != nil {
  2162  		// Hands off own p to the locked m,
  2163  		// then blocks waiting for a new p.
  2164  		startlockedm(gp)
  2165  		goto top
  2166  	}
  2167  
  2168  	execute(gp, inheritTime)
  2169  }
  2170  
  2171  // dropg removes the association between m and the current goroutine m->curg (gp for short).
  2172  // Typically a caller sets gp's status away from Grunning and then
  2173  // immediately calls dropg to finish the job. The caller is also responsible
  2174  // for arranging that gp will be restarted using ready at an
  2175  // appropriate time. After calling dropg and arranging for gp to be
  2176  // readied later, the caller can do other work but eventually should
  2177  // call schedule to restart the scheduling of goroutines on this m.
  2178  func dropg() {
  2179  	_g_ := getg()
  2180  
  2181  	setMNoWB(&_g_.m.curg.m, nil)
  2182  	setGNoWB(&_g_.m.curg, nil)
  2183  }
  2184  
  2185  func parkunlock_c(gp *g, lock unsafe.Pointer) bool {
  2186  	unlock((*mutex)(lock))
  2187  	return true
  2188  }
  2189  
  2190  // park continuation on g0.
  2191  func park_m(gp *g) {
  2192  	_g_ := getg()
  2193  
  2194  	if trace.enabled {
  2195  		traceGoPark(_g_.m.waittraceev, _g_.m.waittraceskip, gp)
  2196  	}
  2197  
  2198  	casgstatus(gp, _Grunning, _Gwaiting)
  2199  	dropg()
  2200  
  2201  	if _g_.m.waitunlockf != nil {
  2202  		fn := *(*func(*g, unsafe.Pointer) bool)(unsafe.Pointer(&_g_.m.waitunlockf))
  2203  		ok := fn(gp, _g_.m.waitlock)
  2204  		_g_.m.waitunlockf = nil
  2205  		_g_.m.waitlock = nil
  2206  		if !ok {
  2207  			if trace.enabled {
  2208  				traceGoUnpark(gp, 2)
  2209  			}
  2210  			casgstatus(gp, _Gwaiting, _Grunnable)
  2211  			execute(gp, true) // Schedule it back, never returns.
  2212  		}
  2213  	}
  2214  	schedule()
  2215  }
  2216  
  2217  func goschedImpl(gp *g) {
  2218  	status := readgstatus(gp)
  2219  	if status&^_Gscan != _Grunning {
  2220  		dumpgstatus(gp)
  2221  		throw("bad g status")
  2222  	}
  2223  	casgstatus(gp, _Grunning, _Grunnable)
  2224  	dropg()
  2225  	lock(&sched.lock)
  2226  	globrunqput(gp)
  2227  	unlock(&sched.lock)
  2228  
  2229  	schedule()
  2230  }
  2231  
  2232  // Gosched continuation on g0.
  2233  func gosched_m(gp *g) {
  2234  	if trace.enabled {
  2235  		traceGoSched()
  2236  	}
  2237  	goschedImpl(gp)
  2238  }
  2239  
  2240  func gopreempt_m(gp *g) {
  2241  	if trace.enabled {
  2242  		traceGoPreempt()
  2243  	}
  2244  	goschedImpl(gp)
  2245  }
  2246  
  2247  // Finishes execution of the current goroutine.
  2248  func goexit1() {
  2249  	if raceenabled {
  2250  		racegoend()
  2251  	}
  2252  	if trace.enabled {
  2253  		traceGoEnd()
  2254  	}
  2255  	mcall(goexit0)
  2256  }
  2257  
  2258  // goexit continuation on g0.
  2259  func goexit0(gp *g) {
  2260  	_g_ := getg()
  2261  
  2262  	casgstatus(gp, _Grunning, _Gdead)
  2263  	if isSystemGoroutine(gp) {
  2264  		atomic.Xadd(&sched.ngsys, -1)
  2265  	}
  2266  	gp.m = nil
  2267  	gp.lockedm = nil
  2268  	_g_.m.lockedg = nil
  2269  	gp.paniconfault = false
  2270  	gp._defer = nil // should be true already but just in case.
  2271  	gp._panic = nil // non-nil for Goexit during panic. points at stack-allocated data.
  2272  	gp.writebuf = nil
  2273  	gp.waitreason = ""
  2274  	gp.param = nil
  2275  
  2276  	// Note that gp's stack scan is now "valid" because it has no
  2277  	// stack. We could dequeueRescan, but that takes a lock and
  2278  	// isn't really necessary.
  2279  	gp.gcscanvalid = true
  2280  	dropg()
  2281  
  2282  	if _g_.m.locked&^_LockExternal != 0 {
  2283  		print("invalid m->locked = ", _g_.m.locked, "\n")
  2284  		throw("internal lockOSThread error")
  2285  	}
  2286  	_g_.m.locked = 0
  2287  	gfput(_g_.m.p.ptr(), gp)
  2288  	schedule()
  2289  }
  2290  
  2291  // save updates getg().sched to refer to pc and sp so that a following
  2292  // gogo will restore pc and sp.
  2293  //
  2294  // save must not have write barriers because invoking a write barrier
  2295  // can clobber getg().sched.
  2296  //
  2297  //go:nosplit
  2298  //go:nowritebarrierrec
  2299  func save(pc, sp uintptr) {
  2300  	_g_ := getg()
  2301  
  2302  	_g_.sched.pc = pc
  2303  	_g_.sched.sp = sp
  2304  	_g_.sched.lr = 0
  2305  	_g_.sched.ret = 0
  2306  	_g_.sched.g = guintptr(unsafe.Pointer(_g_))
  2307  	// We need to ensure ctxt is zero, but can't have a write
  2308  	// barrier here. However, it should always already be zero.
  2309  	// Assert that.
  2310  	if _g_.sched.ctxt != nil {
  2311  		badctxt()
  2312  	}
  2313  }
  2314  
  2315  // The goroutine g is about to enter a system call.
  2316  // Record that it's not using the cpu anymore.
  2317  // This is called only from the go syscall library and cgocall,
  2318  // not from the low-level system calls used by the runtime.
  2319  //
  2320  // Entersyscall cannot split the stack: the gosave must
  2321  // make g->sched refer to the caller's stack segment, because
  2322  // entersyscall is going to return immediately after.
  2323  //
  2324  // Nothing entersyscall calls can split the stack either.
  2325  // We cannot safely move the stack during an active call to syscall,
  2326  // because we do not know which of the uintptr arguments are
  2327  // really pointers (back into the stack).
  2328  // In practice, this means that we make the fast path run through
  2329  // entersyscall doing no-split things, and the slow path has to use systemstack
  2330  // to run bigger things on the system stack.
  2331  //
  2332  // reentersyscall is the entry point used by cgo callbacks, where explicitly
  2333  // saved SP and PC are restored. This is needed when exitsyscall will be called
  2334  // from a function further up in the call stack than the parent, as g->syscallsp
  2335  // must always point to a valid stack frame. entersyscall below is the normal
  2336  // entry point for syscalls, which obtains the SP and PC from the caller.
  2337  //
  2338  // Syscall tracing:
  2339  // At the start of a syscall we emit traceGoSysCall to capture the stack trace.
  2340  // If the syscall does not block, that is it, we do not emit any other events.
  2341  // If the syscall blocks (that is, P is retaken), retaker emits traceGoSysBlock;
  2342  // when syscall returns we emit traceGoSysExit and when the goroutine starts running
  2343  // (potentially instantly, if exitsyscallfast returns true) we emit traceGoStart.
  2344  // To ensure that traceGoSysExit is emitted strictly after traceGoSysBlock,
  2345  // we remember current value of syscalltick in m (_g_.m.syscalltick = _g_.m.p.ptr().syscalltick),
  2346  // whoever emits traceGoSysBlock increments p.syscalltick afterwards;
  2347  // and we wait for the increment before emitting traceGoSysExit.
  2348  // Note that the increment is done even if tracing is not enabled,
  2349  // because tracing can be enabled in the middle of syscall. We don't want the wait to hang.
  2350  //
  2351  //go:nosplit
  2352  func reentersyscall(pc, sp uintptr) {
  2353  	_g_ := getg()
  2354  
  2355  	// Disable preemption because during this function g is in Gsyscall status,
  2356  	// but can have inconsistent g->sched, do not let GC observe it.
  2357  	_g_.m.locks++
  2358  
  2359  	// Entersyscall must not call any function that might split/grow the stack.
  2360  	// (See details in comment above.)
  2361  	// Catch calls that might, by replacing the stack guard with something that
  2362  	// will trip any stack check and leaving a flag to tell newstack to die.
  2363  	_g_.stackguard0 = stackPreempt
  2364  	_g_.throwsplit = true
  2365  
  2366  	// Leave SP around for GC and traceback.
  2367  	save(pc, sp)
  2368  	_g_.syscallsp = sp
  2369  	_g_.syscallpc = pc
  2370  	casgstatus(_g_, _Grunning, _Gsyscall)
  2371  	if _g_.syscallsp < _g_.stack.lo || _g_.stack.hi < _g_.syscallsp {
  2372  		systemstack(func() {
  2373  			print("entersyscall inconsistent ", hex(_g_.syscallsp), " [", hex(_g_.stack.lo), ",", hex(_g_.stack.hi), "]\n")
  2374  			throw("entersyscall")
  2375  		})
  2376  	}
  2377  
  2378  	if trace.enabled {
  2379  		systemstack(traceGoSysCall)
  2380  		// systemstack itself clobbers g.sched.{pc,sp} and we might
  2381  		// need them later when the G is genuinely blocked in a
  2382  		// syscall
  2383  		save(pc, sp)
  2384  	}
  2385  
  2386  	if atomic.Load(&sched.sysmonwait) != 0 {
  2387  		systemstack(entersyscall_sysmon)
  2388  		save(pc, sp)
  2389  	}
  2390  
  2391  	if _g_.m.p.ptr().runSafePointFn != 0 {
  2392  		// runSafePointFn may stack split if run on this stack
  2393  		systemstack(runSafePointFn)
  2394  		save(pc, sp)
  2395  	}
  2396  
  2397  	_g_.m.syscalltick = _g_.m.p.ptr().syscalltick
  2398  	_g_.sysblocktraced = true
  2399  	_g_.m.mcache = nil
  2400  	_g_.m.p.ptr().m = 0
  2401  	atomic.Store(&_g_.m.p.ptr().status, _Psyscall)
  2402  	if sched.gcwaiting != 0 {
  2403  		systemstack(entersyscall_gcwait)
  2404  		save(pc, sp)
  2405  	}
  2406  
  2407  	// Goroutines must not split stacks in Gsyscall status (it would corrupt g->sched).
  2408  	// We set _StackGuard to StackPreempt so that first split stack check calls morestack.
  2409  	// Morestack detects this case and throws.
  2410  	_g_.stackguard0 = stackPreempt
  2411  	_g_.m.locks--
  2412  }
  2413  
  2414  // Standard syscall entry used by the go syscall library and normal cgo calls.
  2415  //go:nosplit
  2416  func entersyscall(dummy int32) {
  2417  	reentersyscall(getcallerpc(unsafe.Pointer(&dummy)), getcallersp(unsafe.Pointer(&dummy)))
  2418  }
  2419  
  2420  func entersyscall_sysmon() {
  2421  	lock(&sched.lock)
  2422  	if atomic.Load(&sched.sysmonwait) != 0 {
  2423  		atomic.Store(&sched.sysmonwait, 0)
  2424  		notewakeup(&sched.sysmonnote)
  2425  	}
  2426  	unlock(&sched.lock)
  2427  }
  2428  
  2429  func entersyscall_gcwait() {
  2430  	_g_ := getg()
  2431  	_p_ := _g_.m.p.ptr()
  2432  
  2433  	lock(&sched.lock)
  2434  	if sched.stopwait > 0 && atomic.Cas(&_p_.status, _Psyscall, _Pgcstop) {
  2435  		if trace.enabled {
  2436  			traceGoSysBlock(_p_)
  2437  			traceProcStop(_p_)
  2438  		}
  2439  		_p_.syscalltick++
  2440  		if sched.stopwait--; sched.stopwait == 0 {
  2441  			notewakeup(&sched.stopnote)
  2442  		}
  2443  	}
  2444  	unlock(&sched.lock)
  2445  }
  2446  
  2447  // The same as entersyscall(), but with a hint that the syscall is blocking.
  2448  //go:nosplit
  2449  func entersyscallblock(dummy int32) {
  2450  	_g_ := getg()
  2451  
  2452  	_g_.m.locks++ // see comment in entersyscall
  2453  	_g_.throwsplit = true
  2454  	_g_.stackguard0 = stackPreempt // see comment in entersyscall
  2455  	_g_.m.syscalltick = _g_.m.p.ptr().syscalltick
  2456  	_g_.sysblocktraced = true
  2457  	_g_.m.p.ptr().syscalltick++
  2458  
  2459  	// Leave SP around for GC and traceback.
  2460  	pc := getcallerpc(unsafe.Pointer(&dummy))
  2461  	sp := getcallersp(unsafe.Pointer(&dummy))
  2462  	save(pc, sp)
  2463  	_g_.syscallsp = _g_.sched.sp
  2464  	_g_.syscallpc = _g_.sched.pc
  2465  	if _g_.syscallsp < _g_.stack.lo || _g_.stack.hi < _g_.syscallsp {
  2466  		sp1 := sp
  2467  		sp2 := _g_.sched.sp
  2468  		sp3 := _g_.syscallsp
  2469  		systemstack(func() {
  2470  			print("entersyscallblock inconsistent ", hex(sp1), " ", hex(sp2), " ", hex(sp3), " [", hex(_g_.stack.lo), ",", hex(_g_.stack.hi), "]\n")
  2471  			throw("entersyscallblock")
  2472  		})
  2473  	}
  2474  	casgstatus(_g_, _Grunning, _Gsyscall)
  2475  	if _g_.syscallsp < _g_.stack.lo || _g_.stack.hi < _g_.syscallsp {
  2476  		systemstack(func() {
  2477  			print("entersyscallblock inconsistent ", hex(sp), " ", hex(_g_.sched.sp), " ", hex(_g_.syscallsp), " [", hex(_g_.stack.lo), ",", hex(_g_.stack.hi), "]\n")
  2478  			throw("entersyscallblock")
  2479  		})
  2480  	}
  2481  
  2482  	systemstack(entersyscallblock_handoff)
  2483  
  2484  	// Resave for traceback during blocked call.
  2485  	save(getcallerpc(unsafe.Pointer(&dummy)), getcallersp(unsafe.Pointer(&dummy)))
  2486  
  2487  	_g_.m.locks--
  2488  }
  2489  
  2490  func entersyscallblock_handoff() {
  2491  	if trace.enabled {
  2492  		traceGoSysCall()
  2493  		traceGoSysBlock(getg().m.p.ptr())
  2494  	}
  2495  	handoffp(releasep())
  2496  }
  2497  
  2498  // The goroutine g exited its system call.
  2499  // Arrange for it to run on a cpu again.
  2500  // This is called only from the go syscall library, not
  2501  // from the low-level system calls used by the runtime.
  2502  //
  2503  // Write barriers are not allowed because our P may have been stolen.
  2504  //
  2505  //go:nosplit
  2506  //go:nowritebarrierrec
  2507  func exitsyscall(dummy int32) {
  2508  	_g_ := getg()
  2509  
  2510  	_g_.m.locks++ // see comment in entersyscall
  2511  	if getcallersp(unsafe.Pointer(&dummy)) > _g_.syscallsp {
  2512  		// throw calls print which may try to grow the stack,
  2513  		// but throwsplit == true so the stack can not be grown;
  2514  		// use systemstack to avoid that possible problem.
  2515  		systemstack(func() {
  2516  			throw("exitsyscall: syscall frame is no longer valid")
  2517  		})
  2518  	}
  2519  
  2520  	_g_.waitsince = 0
  2521  	oldp := _g_.m.p.ptr()
  2522  	if exitsyscallfast() {
  2523  		if _g_.m.mcache == nil {
  2524  			throw("lost mcache")
  2525  		}
  2526  		if trace.enabled {
  2527  			if oldp != _g_.m.p.ptr() || _g_.m.syscalltick != _g_.m.p.ptr().syscalltick {
  2528  				systemstack(traceGoStart)
  2529  			}
  2530  		}
  2531  		// There's a cpu for us, so we can run.
  2532  		_g_.m.p.ptr().syscalltick++
  2533  		// We need to cas the status and scan before resuming...
  2534  		casgstatus(_g_, _Gsyscall, _Grunning)
  2535  
  2536  		// Garbage collector isn't running (since we are),
  2537  		// so okay to clear syscallsp.
  2538  		_g_.syscallsp = 0
  2539  		_g_.m.locks--
  2540  		if _g_.preempt {
  2541  			// restore the preemption request in case we've cleared it in newstack
  2542  			_g_.stackguard0 = stackPreempt
  2543  		} else {
  2544  			// otherwise restore the real _StackGuard, we've spoiled it in entersyscall/entersyscallblock
  2545  			_g_.stackguard0 = _g_.stack.lo + _StackGuard
  2546  		}
  2547  		_g_.throwsplit = false
  2548  		return
  2549  	}
  2550  
  2551  	_g_.sysexitticks = 0
  2552  	if trace.enabled {
  2553  		// Wait till traceGoSysBlock event is emitted.
  2554  		// This ensures consistency of the trace (the goroutine is started after it is blocked).
  2555  		for oldp != nil && oldp.syscalltick == _g_.m.syscalltick {
  2556  			osyield()
  2557  		}
  2558  		// We can't trace syscall exit right now because we don't have a P.
  2559  		// Tracing code can invoke write barriers that cannot run without a P.
  2560  		// So instead we remember the syscall exit time and emit the event
  2561  		// in execute when we have a P.
  2562  		_g_.sysexitticks = cputicks()
  2563  	}
  2564  
  2565  	_g_.m.locks--
  2566  
  2567  	// Call the scheduler.
  2568  	mcall(exitsyscall0)
  2569  
  2570  	if _g_.m.mcache == nil {
  2571  		throw("lost mcache")
  2572  	}
  2573  
  2574  	// Scheduler returned, so we're allowed to run now.
  2575  	// Delete the syscallsp information that we left for
  2576  	// the garbage collector during the system call.
  2577  	// Must wait until now because until gosched returns
  2578  	// we don't know for sure that the garbage collector
  2579  	// is not running.
  2580  	_g_.syscallsp = 0
  2581  	_g_.m.p.ptr().syscalltick++
  2582  	_g_.throwsplit = false
  2583  }
  2584  
  2585  //go:nosplit
  2586  func exitsyscallfast() bool {
  2587  	_g_ := getg()
  2588  
  2589  	// Freezetheworld sets stopwait but does not retake P's.
  2590  	if sched.stopwait == freezeStopWait {
  2591  		_g_.m.mcache = nil
  2592  		_g_.m.p = 0
  2593  		return false
  2594  	}
  2595  
  2596  	// Try to re-acquire the last P.
  2597  	if _g_.m.p != 0 && _g_.m.p.ptr().status == _Psyscall && atomic.Cas(&_g_.m.p.ptr().status, _Psyscall, _Prunning) {
  2598  		// There's a cpu for us, so we can run.
  2599  		exitsyscallfast_reacquired()
  2600  		return true
  2601  	}
  2602  
  2603  	// Try to get any other idle P.
  2604  	oldp := _g_.m.p.ptr()
  2605  	_g_.m.mcache = nil
  2606  	_g_.m.p = 0
  2607  	if sched.pidle != 0 {
  2608  		var ok bool
  2609  		systemstack(func() {
  2610  			ok = exitsyscallfast_pidle()
  2611  			if ok && trace.enabled {
  2612  				if oldp != nil {
  2613  					// Wait till traceGoSysBlock event is emitted.
  2614  					// This ensures consistency of the trace (the goroutine is started after it is blocked).
  2615  					for oldp.syscalltick == _g_.m.syscalltick {
  2616  						osyield()
  2617  					}
  2618  				}
  2619  				traceGoSysExit(0)
  2620  			}
  2621  		})
  2622  		if ok {
  2623  			return true
  2624  		}
  2625  	}
  2626  	return false
  2627  }
  2628  
  2629  // exitsyscallfast_reacquired is the exitsyscall path on which this G
  2630  // has successfully reacquired the P it was running on before the
  2631  // syscall.
  2632  //
  2633  // This function is allowed to have write barriers because exitsyscall
  2634  // has acquired a P at this point.
  2635  //
  2636  //go:yeswritebarrierrec
  2637  //go:nosplit
  2638  func exitsyscallfast_reacquired() {
  2639  	_g_ := getg()
  2640  	_g_.m.mcache = _g_.m.p.ptr().mcache
  2641  	_g_.m.p.ptr().m.set(_g_.m)
  2642  	if _g_.m.syscalltick != _g_.m.p.ptr().syscalltick {
  2643  		if trace.enabled {
  2644  			// The p was retaken and then enter into syscall again (since _g_.m.syscalltick has changed).
  2645  			// traceGoSysBlock for this syscall was already emitted,
  2646  			// but here we effectively retake the p from the new syscall running on the same p.
  2647  			systemstack(func() {
  2648  				// Denote blocking of the new syscall.
  2649  				traceGoSysBlock(_g_.m.p.ptr())
  2650  				// Denote completion of the current syscall.
  2651  				traceGoSysExit(0)
  2652  			})
  2653  		}
  2654  		_g_.m.p.ptr().syscalltick++
  2655  	}
  2656  }
  2657  
  2658  func exitsyscallfast_pidle() bool {
  2659  	lock(&sched.lock)
  2660  	_p_ := pidleget()
  2661  	if _p_ != nil && atomic.Load(&sched.sysmonwait) != 0 {
  2662  		atomic.Store(&sched.sysmonwait, 0)
  2663  		notewakeup(&sched.sysmonnote)
  2664  	}
  2665  	unlock(&sched.lock)
  2666  	if _p_ != nil {
  2667  		acquirep(_p_)
  2668  		return true
  2669  	}
  2670  	return false
  2671  }
  2672  
  2673  // exitsyscall slow path on g0.
  2674  // Failed to acquire P, enqueue gp as runnable.
  2675  //
  2676  //go:nowritebarrierrec
  2677  func exitsyscall0(gp *g) {
  2678  	_g_ := getg()
  2679  
  2680  	casgstatus(gp, _Gsyscall, _Grunnable)
  2681  	dropg()
  2682  	lock(&sched.lock)
  2683  	_p_ := pidleget()
  2684  	if _p_ == nil {
  2685  		globrunqput(gp)
  2686  	} else if atomic.Load(&sched.sysmonwait) != 0 {
  2687  		atomic.Store(&sched.sysmonwait, 0)
  2688  		notewakeup(&sched.sysmonnote)
  2689  	}
  2690  	unlock(&sched.lock)
  2691  	if _p_ != nil {
  2692  		acquirep(_p_)
  2693  		execute(gp, false) // Never returns.
  2694  	}
  2695  	if _g_.m.lockedg != nil {
  2696  		// Wait until another thread schedules gp and so m again.
  2697  		stoplockedm()
  2698  		execute(gp, false) // Never returns.
  2699  	}
  2700  	stopm()
  2701  	schedule() // Never returns.
  2702  }
  2703  
  2704  func beforefork() {
  2705  	gp := getg().m.curg
  2706  
  2707  	// Fork can hang if preempted with signals frequently enough (see issue 5517).
  2708  	// Ensure that we stay on the same M where we disable profiling.
  2709  	gp.m.locks++
  2710  	if gp.m.profilehz != 0 {
  2711  		resetcpuprofiler(0)
  2712  	}
  2713  
  2714  	// This function is called before fork in syscall package.
  2715  	// Code between fork and exec must not allocate memory nor even try to grow stack.
  2716  	// Here we spoil g->_StackGuard to reliably detect any attempts to grow stack.
  2717  	// runtime_AfterFork will undo this in parent process, but not in child.
  2718  	gp.stackguard0 = stackFork
  2719  }
  2720  
  2721  // Called from syscall package before fork.
  2722  //go:linkname syscall_runtime_BeforeFork syscall.runtime_BeforeFork
  2723  //go:nosplit
  2724  func syscall_runtime_BeforeFork() {
  2725  	systemstack(beforefork)
  2726  }
  2727  
  2728  func afterfork() {
  2729  	gp := getg().m.curg
  2730  
  2731  	// See the comment in beforefork.
  2732  	gp.stackguard0 = gp.stack.lo + _StackGuard
  2733  
  2734  	hz := sched.profilehz
  2735  	if hz != 0 {
  2736  		resetcpuprofiler(hz)
  2737  	}
  2738  	gp.m.locks--
  2739  }
  2740  
  2741  // Called from syscall package after fork in parent.
  2742  //go:linkname syscall_runtime_AfterFork syscall.runtime_AfterFork
  2743  //go:nosplit
  2744  func syscall_runtime_AfterFork() {
  2745  	systemstack(afterfork)
  2746  }
  2747  
  2748  // Allocate a new g, with a stack big enough for stacksize bytes.
  2749  func malg(stacksize int32) *g {
  2750  	newg := new(g)
  2751  	if stacksize >= 0 {
  2752  		stacksize = round2(_StackSystem + stacksize)
  2753  		systemstack(func() {
  2754  			newg.stack, newg.stkbar = stackalloc(uint32(stacksize))
  2755  		})
  2756  		newg.stackguard0 = newg.stack.lo + _StackGuard
  2757  		newg.stackguard1 = ^uintptr(0)
  2758  		newg.stackAlloc = uintptr(stacksize)
  2759  	}
  2760  	return newg
  2761  }
  2762  
  2763  // Create a new g running fn with siz bytes of arguments.
  2764  // Put it on the queue of g's waiting to run.
  2765  // The compiler turns a go statement into a call to this.
  2766  // Cannot split the stack because it assumes that the arguments
  2767  // are available sequentially after &fn; they would not be
  2768  // copied if a stack split occurred.
  2769  //go:nosplit
  2770  func newproc(siz int32, fn *funcval) {
  2771  	argp := add(unsafe.Pointer(&fn), sys.PtrSize)
  2772  	pc := getcallerpc(unsafe.Pointer(&siz))
  2773  	systemstack(func() {
  2774  		newproc1(fn, (*uint8)(argp), siz, 0, pc)
  2775  	})
  2776  }
  2777  
  2778  // Create a new g running fn with narg bytes of arguments starting
  2779  // at argp and returning nret bytes of results.  callerpc is the
  2780  // address of the go statement that created this. The new g is put
  2781  // on the queue of g's waiting to run.
  2782  func newproc1(fn *funcval, argp *uint8, narg int32, nret int32, callerpc uintptr) *g {
  2783  	_g_ := getg()
  2784  
  2785  	if fn == nil {
  2786  		_g_.m.throwing = -1 // do not dump full stacks
  2787  		throw("go of nil func value")
  2788  	}
  2789  	_g_.m.locks++ // disable preemption because it can be holding p in a local var
  2790  	siz := narg + nret
  2791  	siz = (siz + 7) &^ 7
  2792  
  2793  	// We could allocate a larger initial stack if necessary.
  2794  	// Not worth it: this is almost always an error.
  2795  	// 4*sizeof(uintreg): extra space added below
  2796  	// sizeof(uintreg): caller's LR (arm) or return address (x86, in gostartcall).
  2797  	if siz >= _StackMin-4*sys.RegSize-sys.RegSize {
  2798  		throw("newproc: function arguments too large for new goroutine")
  2799  	}
  2800  
  2801  	_p_ := _g_.m.p.ptr()
  2802  	newg := gfget(_p_)
  2803  	if newg == nil {
  2804  		newg = malg(_StackMin)
  2805  		casgstatus(newg, _Gidle, _Gdead)
  2806  		newg.gcRescan = -1
  2807  		allgadd(newg) // publishes with a g->status of Gdead so GC scanner doesn't look at uninitialized stack.
  2808  	}
  2809  	if newg.stack.hi == 0 {
  2810  		throw("newproc1: newg missing stack")
  2811  	}
  2812  
  2813  	if readgstatus(newg) != _Gdead {
  2814  		throw("newproc1: new g is not Gdead")
  2815  	}
  2816  
  2817  	totalSize := 4*sys.RegSize + uintptr(siz) + sys.MinFrameSize // extra space in case of reads slightly beyond frame
  2818  	totalSize += -totalSize & (sys.SpAlign - 1)                  // align to spAlign
  2819  	sp := newg.stack.hi - totalSize
  2820  	spArg := sp
  2821  	if usesLR {
  2822  		// caller's LR
  2823  		*(*uintptr)(unsafe.Pointer(sp)) = 0
  2824  		prepGoExitFrame(sp)
  2825  		spArg += sys.MinFrameSize
  2826  	}
  2827  	if narg > 0 {
  2828  		memmove(unsafe.Pointer(spArg), unsafe.Pointer(argp), uintptr(narg))
  2829  		// This is a stack-to-stack copy. If write barriers
  2830  		// are enabled and the source stack is grey (the
  2831  		// destination is always black), then perform a
  2832  		// barrier copy. We do this *after* the memmove
  2833  		// because the destination stack may have garbage on
  2834  		// it.
  2835  		if writeBarrier.needed && !_g_.m.curg.gcscandone {
  2836  			f := findfunc(fn.fn)
  2837  			stkmap := (*stackmap)(funcdata(f, _FUNCDATA_ArgsPointerMaps))
  2838  			// We're in the prologue, so it's always stack map index 0.
  2839  			bv := stackmapdata(stkmap, 0)
  2840  			bulkBarrierBitmap(spArg, spArg, uintptr(narg), 0, bv.bytedata)
  2841  		}
  2842  	}
  2843  
  2844  	memclrNoHeapPointers(unsafe.Pointer(&newg.sched), unsafe.Sizeof(newg.sched))
  2845  	newg.sched.sp = sp
  2846  	newg.stktopsp = sp
  2847  	newg.sched.pc = funcPC(goexit) + sys.PCQuantum // +PCQuantum so that previous instruction is in same function
  2848  	newg.sched.g = guintptr(unsafe.Pointer(newg))
  2849  	gostartcallfn(&newg.sched, fn)
  2850  	newg.gopc = callerpc
  2851  	newg.startpc = fn.fn
  2852  	if isSystemGoroutine(newg) {
  2853  		atomic.Xadd(&sched.ngsys, +1)
  2854  	}
  2855  	// The stack is dirty from the argument frame, so queue it for
  2856  	// scanning. Do this before setting it to runnable so we still
  2857  	// own the G. If we're recycling a G, it may already be on the
  2858  	// rescan list.
  2859  	if newg.gcRescan == -1 {
  2860  		queueRescan(newg)
  2861  	} else {
  2862  		// The recycled G is already on the rescan list. Just
  2863  		// mark the stack dirty.
  2864  		newg.gcscanvalid = false
  2865  	}
  2866  	casgstatus(newg, _Gdead, _Grunnable)
  2867  
  2868  	if _p_.goidcache == _p_.goidcacheend {
  2869  		// Sched.goidgen is the last allocated id,
  2870  		// this batch must be [sched.goidgen+1, sched.goidgen+GoidCacheBatch].
  2871  		// At startup sched.goidgen=0, so main goroutine receives goid=1.
  2872  		_p_.goidcache = atomic.Xadd64(&sched.goidgen, _GoidCacheBatch)
  2873  		_p_.goidcache -= _GoidCacheBatch - 1
  2874  		_p_.goidcacheend = _p_.goidcache + _GoidCacheBatch
  2875  	}
  2876  	newg.goid = int64(_p_.goidcache)
  2877  	_p_.goidcache++
  2878  	if raceenabled {
  2879  		newg.racectx = racegostart(callerpc)
  2880  	}
  2881  	if trace.enabled {
  2882  		traceGoCreate(newg, newg.startpc)
  2883  	}
  2884  	runqput(_p_, newg, true)
  2885  
  2886  	if atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 && runtimeInitTime != 0 {
  2887  		wakep()
  2888  	}
  2889  	_g_.m.locks--
  2890  	if _g_.m.locks == 0 && _g_.preempt { // restore the preemption request in case we've cleared it in newstack
  2891  		_g_.stackguard0 = stackPreempt
  2892  	}
  2893  	return newg
  2894  }
  2895  
  2896  // Put on gfree list.
  2897  // If local list is too long, transfer a batch to the global list.
  2898  func gfput(_p_ *p, gp *g) {
  2899  	if readgstatus(gp) != _Gdead {
  2900  		throw("gfput: bad status (not Gdead)")
  2901  	}
  2902  
  2903  	stksize := gp.stackAlloc
  2904  
  2905  	if stksize != _FixedStack {
  2906  		// non-standard stack size - free it.
  2907  		stackfree(gp.stack, gp.stackAlloc)
  2908  		gp.stack.lo = 0
  2909  		gp.stack.hi = 0
  2910  		gp.stackguard0 = 0
  2911  		gp.stkbar = nil
  2912  		gp.stkbarPos = 0
  2913  	} else {
  2914  		// Reset stack barriers.
  2915  		gp.stkbar = gp.stkbar[:0]
  2916  		gp.stkbarPos = 0
  2917  	}
  2918  
  2919  	gp.schedlink.set(_p_.gfree)
  2920  	_p_.gfree = gp
  2921  	_p_.gfreecnt++
  2922  	if _p_.gfreecnt >= 64 {
  2923  		lock(&sched.gflock)
  2924  		for _p_.gfreecnt >= 32 {
  2925  			_p_.gfreecnt--
  2926  			gp = _p_.gfree
  2927  			_p_.gfree = gp.schedlink.ptr()
  2928  			if gp.stack.lo == 0 {
  2929  				gp.schedlink.set(sched.gfreeNoStack)
  2930  				sched.gfreeNoStack = gp
  2931  			} else {
  2932  				gp.schedlink.set(sched.gfreeStack)
  2933  				sched.gfreeStack = gp
  2934  			}
  2935  			sched.ngfree++
  2936  		}
  2937  		unlock(&sched.gflock)
  2938  	}
  2939  }
  2940  
  2941  // Get from gfree list.
  2942  // If local list is empty, grab a batch from global list.
  2943  func gfget(_p_ *p) *g {
  2944  retry:
  2945  	gp := _p_.gfree
  2946  	if gp == nil && (sched.gfreeStack != nil || sched.gfreeNoStack != nil) {
  2947  		lock(&sched.gflock)
  2948  		for _p_.gfreecnt < 32 {
  2949  			if sched.gfreeStack != nil {
  2950  				// Prefer Gs with stacks.
  2951  				gp = sched.gfreeStack
  2952  				sched.gfreeStack = gp.schedlink.ptr()
  2953  			} else if sched.gfreeNoStack != nil {
  2954  				gp = sched.gfreeNoStack
  2955  				sched.gfreeNoStack = gp.schedlink.ptr()
  2956  			} else {
  2957  				break
  2958  			}
  2959  			_p_.gfreecnt++
  2960  			sched.ngfree--
  2961  			gp.schedlink.set(_p_.gfree)
  2962  			_p_.gfree = gp
  2963  		}
  2964  		unlock(&sched.gflock)
  2965  		goto retry
  2966  	}
  2967  	if gp != nil {
  2968  		_p_.gfree = gp.schedlink.ptr()
  2969  		_p_.gfreecnt--
  2970  		if gp.stack.lo == 0 {
  2971  			// Stack was deallocated in gfput. Allocate a new one.
  2972  			systemstack(func() {
  2973  				gp.stack, gp.stkbar = stackalloc(_FixedStack)
  2974  			})
  2975  			gp.stackguard0 = gp.stack.lo + _StackGuard
  2976  			gp.stackAlloc = _FixedStack
  2977  		} else {
  2978  			if raceenabled {
  2979  				racemalloc(unsafe.Pointer(gp.stack.lo), gp.stackAlloc)
  2980  			}
  2981  			if msanenabled {
  2982  				msanmalloc(unsafe.Pointer(gp.stack.lo), gp.stackAlloc)
  2983  			}
  2984  		}
  2985  	}
  2986  	return gp
  2987  }
  2988  
  2989  // Purge all cached G's from gfree list to the global list.
  2990  func gfpurge(_p_ *p) {
  2991  	lock(&sched.gflock)
  2992  	for _p_.gfreecnt != 0 {
  2993  		_p_.gfreecnt--
  2994  		gp := _p_.gfree
  2995  		_p_.gfree = gp.schedlink.ptr()
  2996  		if gp.stack.lo == 0 {
  2997  			gp.schedlink.set(sched.gfreeNoStack)
  2998  			sched.gfreeNoStack = gp
  2999  		} else {
  3000  			gp.schedlink.set(sched.gfreeStack)
  3001  			sched.gfreeStack = gp
  3002  		}
  3003  		sched.ngfree++
  3004  	}
  3005  	unlock(&sched.gflock)
  3006  }
  3007  
  3008  // Breakpoint executes a breakpoint trap.
  3009  func Breakpoint() {
  3010  	breakpoint()
  3011  }
  3012  
  3013  // dolockOSThread is called by LockOSThread and lockOSThread below
  3014  // after they modify m.locked. Do not allow preemption during this call,
  3015  // or else the m might be different in this function than in the caller.
  3016  //go:nosplit
  3017  func dolockOSThread() {
  3018  	_g_ := getg()
  3019  	_g_.m.lockedg = _g_
  3020  	_g_.lockedm = _g_.m
  3021  }
  3022  
  3023  //go:nosplit
  3024  
  3025  // LockOSThread wires the calling goroutine to its current operating system thread.
  3026  // Until the calling goroutine exits or calls UnlockOSThread, it will always
  3027  // execute in that thread, and no other goroutine can.
  3028  func LockOSThread() {
  3029  	getg().m.locked |= _LockExternal
  3030  	dolockOSThread()
  3031  }
  3032  
  3033  //go:nosplit
  3034  func lockOSThread() {
  3035  	getg().m.locked += _LockInternal
  3036  	dolockOSThread()
  3037  }
  3038  
  3039  // dounlockOSThread is called by UnlockOSThread and unlockOSThread below
  3040  // after they update m->locked. Do not allow preemption during this call,
  3041  // or else the m might be in different in this function than in the caller.
  3042  //go:nosplit
  3043  func dounlockOSThread() {
  3044  	_g_ := getg()
  3045  	if _g_.m.locked != 0 {
  3046  		return
  3047  	}
  3048  	_g_.m.lockedg = nil
  3049  	_g_.lockedm = nil
  3050  }
  3051  
  3052  //go:nosplit
  3053  
  3054  // UnlockOSThread unwires the calling goroutine from its fixed operating system thread.
  3055  // If the calling goroutine has not called LockOSThread, UnlockOSThread is a no-op.
  3056  func UnlockOSThread() {
  3057  	getg().m.locked &^= _LockExternal
  3058  	dounlockOSThread()
  3059  }
  3060  
  3061  //go:nosplit
  3062  func unlockOSThread() {
  3063  	_g_ := getg()
  3064  	if _g_.m.locked < _LockInternal {
  3065  		systemstack(badunlockosthread)
  3066  	}
  3067  	_g_.m.locked -= _LockInternal
  3068  	dounlockOSThread()
  3069  }
  3070  
  3071  func badunlockosthread() {
  3072  	throw("runtime: internal error: misuse of lockOSThread/unlockOSThread")
  3073  }
  3074  
  3075  func gcount() int32 {
  3076  	n := int32(allglen) - sched.ngfree - int32(atomic.Load(&sched.ngsys))
  3077  	for i := 0; ; i++ {
  3078  		_p_ := allp[i]
  3079  		if _p_ == nil {
  3080  			break
  3081  		}
  3082  		n -= _p_.gfreecnt
  3083  	}
  3084  
  3085  	// All these variables can be changed concurrently, so the result can be inconsistent.
  3086  	// But at least the current goroutine is running.
  3087  	if n < 1 {
  3088  		n = 1
  3089  	}
  3090  	return n
  3091  }
  3092  
  3093  func mcount() int32 {
  3094  	return sched.mcount
  3095  }
  3096  
  3097  var prof struct {
  3098  	lock uint32
  3099  	hz   int32
  3100  }
  3101  
  3102  func _System()       { _System() }
  3103  func _ExternalCode() { _ExternalCode() }
  3104  func _GC()           { _GC() }
  3105  
  3106  // Called if we receive a SIGPROF signal.
  3107  // Called by the signal handler, may run during STW.
  3108  //go:nowritebarrierrec
  3109  func sigprof(pc, sp, lr uintptr, gp *g, mp *m) {
  3110  	if prof.hz == 0 {
  3111  		return
  3112  	}
  3113  
  3114  	// Profiling runs concurrently with GC, so it must not allocate.
  3115  	mp.mallocing++
  3116  
  3117  	// Define that a "user g" is a user-created goroutine, and a "system g"
  3118  	// is one that is m->g0 or m->gsignal.
  3119  	//
  3120  	// We might be interrupted for profiling halfway through a
  3121  	// goroutine switch. The switch involves updating three (or four) values:
  3122  	// g, PC, SP, and (on arm) LR. The PC must be the last to be updated,
  3123  	// because once it gets updated the new g is running.
  3124  	//
  3125  	// When switching from a user g to a system g, LR is not considered live,
  3126  	// so the update only affects g, SP, and PC. Since PC must be last, there
  3127  	// the possible partial transitions in ordinary execution are (1) g alone is updated,
  3128  	// (2) both g and SP are updated, and (3) SP alone is updated.
  3129  	// If SP or g alone is updated, we can detect the partial transition by checking
  3130  	// whether the SP is within g's stack bounds. (We could also require that SP
  3131  	// be changed only after g, but the stack bounds check is needed by other
  3132  	// cases, so there is no need to impose an additional requirement.)
  3133  	//
  3134  	// There is one exceptional transition to a system g, not in ordinary execution.
  3135  	// When a signal arrives, the operating system starts the signal handler running
  3136  	// with an updated PC and SP. The g is updated last, at the beginning of the
  3137  	// handler. There are two reasons this is okay. First, until g is updated the
  3138  	// g and SP do not match, so the stack bounds check detects the partial transition.
  3139  	// Second, signal handlers currently run with signals disabled, so a profiling
  3140  	// signal cannot arrive during the handler.
  3141  	//
  3142  	// When switching from a system g to a user g, there are three possibilities.
  3143  	//
  3144  	// First, it may be that the g switch has no PC update, because the SP
  3145  	// either corresponds to a user g throughout (as in asmcgocall)
  3146  	// or because it has been arranged to look like a user g frame
  3147  	// (as in cgocallback_gofunc). In this case, since the entire
  3148  	// transition is a g+SP update, a partial transition updating just one of
  3149  	// those will be detected by the stack bounds check.
  3150  	//
  3151  	// Second, when returning from a signal handler, the PC and SP updates
  3152  	// are performed by the operating system in an atomic update, so the g
  3153  	// update must be done before them. The stack bounds check detects
  3154  	// the partial transition here, and (again) signal handlers run with signals
  3155  	// disabled, so a profiling signal cannot arrive then anyway.
  3156  	//
  3157  	// Third, the common case: it may be that the switch updates g, SP, and PC
  3158  	// separately. If the PC is within any of the functions that does this,
  3159  	// we don't ask for a traceback. C.F. the function setsSP for more about this.
  3160  	//
  3161  	// There is another apparently viable approach, recorded here in case
  3162  	// the "PC within setsSP function" check turns out not to be usable.
  3163  	// It would be possible to delay the update of either g or SP until immediately
  3164  	// before the PC update instruction. Then, because of the stack bounds check,
  3165  	// the only problematic interrupt point is just before that PC update instruction,
  3166  	// and the sigprof handler can detect that instruction and simulate stepping past
  3167  	// it in order to reach a consistent state. On ARM, the update of g must be made
  3168  	// in two places (in R10 and also in a TLS slot), so the delayed update would
  3169  	// need to be the SP update. The sigprof handler must read the instruction at
  3170  	// the current PC and if it was the known instruction (for example, JMP BX or
  3171  	// MOV R2, PC), use that other register in place of the PC value.
  3172  	// The biggest drawback to this solution is that it requires that we can tell
  3173  	// whether it's safe to read from the memory pointed at by PC.
  3174  	// In a correct program, we can test PC == nil and otherwise read,
  3175  	// but if a profiling signal happens at the instant that a program executes
  3176  	// a bad jump (before the program manages to handle the resulting fault)
  3177  	// the profiling handler could fault trying to read nonexistent memory.
  3178  	//
  3179  	// To recap, there are no constraints on the assembly being used for the
  3180  	// transition. We simply require that g and SP match and that the PC is not
  3181  	// in gogo.
  3182  	traceback := true
  3183  	if gp == nil || sp < gp.stack.lo || gp.stack.hi < sp || setsSP(pc) {
  3184  		traceback = false
  3185  	}
  3186  	var stk [maxCPUProfStack]uintptr
  3187  	var haveStackLock *g
  3188  	n := 0
  3189  	if mp.ncgo > 0 && mp.curg != nil && mp.curg.syscallpc != 0 && mp.curg.syscallsp != 0 {
  3190  		cgoOff := 0
  3191  		// Check cgoCallersUse to make sure that we are not
  3192  		// interrupting other code that is fiddling with
  3193  		// cgoCallers.  We are running in a signal handler
  3194  		// with all signals blocked, so we don't have to worry
  3195  		// about any other code interrupting us.
  3196  		if atomic.Load(&mp.cgoCallersUse) == 0 && mp.cgoCallers != nil && mp.cgoCallers[0] != 0 {
  3197  			for cgoOff < len(mp.cgoCallers) && mp.cgoCallers[cgoOff] != 0 {
  3198  				cgoOff++
  3199  			}
  3200  			copy(stk[:], mp.cgoCallers[:cgoOff])
  3201  			mp.cgoCallers[0] = 0
  3202  		}
  3203  
  3204  		// Collect Go stack that leads to the cgo call.
  3205  		if gcTryLockStackBarriers(mp.curg) {
  3206  			haveStackLock = mp.curg
  3207  			n = gentraceback(mp.curg.syscallpc, mp.curg.syscallsp, 0, mp.curg, 0, &stk[cgoOff], len(stk)-cgoOff, nil, nil, 0)
  3208  		}
  3209  	} else if traceback {
  3210  		var flags uint = _TraceTrap
  3211  		if gp.m.curg != nil && gcTryLockStackBarriers(gp.m.curg) {
  3212  			// It's safe to traceback the user stack.
  3213  			haveStackLock = gp.m.curg
  3214  			flags |= _TraceJumpStack
  3215  		}
  3216  		// Traceback is safe if we're on the system stack (if
  3217  		// necessary, flags will stop it before switching to
  3218  		// the user stack), or if we locked the user stack.
  3219  		if gp != gp.m.curg || haveStackLock != nil {
  3220  			n = gentraceback(pc, sp, lr, gp, 0, &stk[0], len(stk), nil, nil, flags)
  3221  		}
  3222  	}
  3223  	if haveStackLock != nil {
  3224  		gcUnlockStackBarriers(haveStackLock)
  3225  	}
  3226  
  3227  	if n <= 0 {
  3228  		// Normal traceback is impossible or has failed.
  3229  		// See if it falls into several common cases.
  3230  		n = 0
  3231  		if GOOS == "windows" && mp.libcallg != 0 && mp.libcallpc != 0 && mp.libcallsp != 0 {
  3232  			// Libcall, i.e. runtime syscall on windows.
  3233  			// Collect Go stack that leads to the call.
  3234  			if gcTryLockStackBarriers(mp.libcallg.ptr()) {
  3235  				n = gentraceback(mp.libcallpc, mp.libcallsp, 0, mp.libcallg.ptr(), 0, &stk[0], len(stk), nil, nil, 0)
  3236  				gcUnlockStackBarriers(mp.libcallg.ptr())
  3237  			}
  3238  		}
  3239  		if n == 0 {
  3240  			// If all of the above has failed, account it against abstract "System" or "GC".
  3241  			n = 2
  3242  			// "ExternalCode" is better than "etext".
  3243  			if pc > firstmoduledata.etext {
  3244  				pc = funcPC(_ExternalCode) + sys.PCQuantum
  3245  			}
  3246  			stk[0] = pc
  3247  			if mp.preemptoff != "" || mp.helpgc != 0 {
  3248  				stk[1] = funcPC(_GC) + sys.PCQuantum
  3249  			} else {
  3250  				stk[1] = funcPC(_System) + sys.PCQuantum
  3251  			}
  3252  		}
  3253  	}
  3254  
  3255  	if prof.hz != 0 {
  3256  		// Simple cas-lock to coordinate with setcpuprofilerate.
  3257  		for !atomic.Cas(&prof.lock, 0, 1) {
  3258  			osyield()
  3259  		}
  3260  		if prof.hz != 0 {
  3261  			cpuprof.add(stk[:n])
  3262  		}
  3263  		atomic.Store(&prof.lock, 0)
  3264  	}
  3265  	mp.mallocing--
  3266  }
  3267  
  3268  // If the signal handler receives a SIGPROF signal on a non-Go thread,
  3269  // it tries to collect a traceback into sigprofCallers.
  3270  // sigprofCallersUse is set to non-zero while sigprofCallers holds a traceback.
  3271  var sigprofCallers cgoCallers
  3272  var sigprofCallersUse uint32
  3273  
  3274  // sigprofNonGo is called if we receive a SIGPROF signal on a non-Go thread,
  3275  // and the signal handler collected a stack trace in sigprofCallers.
  3276  // When this is called, sigprofCallersUse will be non-zero.
  3277  // g is nil, and what we can do is very limited.
  3278  //go:nosplit
  3279  //go:nowritebarrierrec
  3280  func sigprofNonGo() {
  3281  	if prof.hz != 0 {
  3282  		n := 0
  3283  		for n < len(sigprofCallers) && sigprofCallers[n] != 0 {
  3284  			n++
  3285  		}
  3286  
  3287  		// Simple cas-lock to coordinate with setcpuprofilerate.
  3288  		for !atomic.Cas(&prof.lock, 0, 1) {
  3289  			osyield()
  3290  		}
  3291  		if prof.hz != 0 {
  3292  			cpuprof.addNonGo(sigprofCallers[:n])
  3293  		}
  3294  		atomic.Store(&prof.lock, 0)
  3295  	}
  3296  
  3297  	atomic.Store(&sigprofCallersUse, 0)
  3298  }
  3299  
  3300  // sigprofNonGoPC is called when a profiling signal arrived on a
  3301  // non-Go thread and we have a single PC value, not a stack trace.
  3302  // g is nil, and what we can do is very limited.
  3303  //go:nosplit
  3304  //go:nowritebarrierrec
  3305  func sigprofNonGoPC(pc uintptr) {
  3306  	if prof.hz != 0 {
  3307  		pc := []uintptr{
  3308  			pc,
  3309  			funcPC(_ExternalCode) + sys.PCQuantum,
  3310  		}
  3311  
  3312  		// Simple cas-lock to coordinate with setcpuprofilerate.
  3313  		for !atomic.Cas(&prof.lock, 0, 1) {
  3314  			osyield()
  3315  		}
  3316  		if prof.hz != 0 {
  3317  			cpuprof.addNonGo(pc)
  3318  		}
  3319  		atomic.Store(&prof.lock, 0)
  3320  	}
  3321  }
  3322  
  3323  // Reports whether a function will set the SP
  3324  // to an absolute value. Important that
  3325  // we don't traceback when these are at the bottom
  3326  // of the stack since we can't be sure that we will
  3327  // find the caller.
  3328  //
  3329  // If the function is not on the bottom of the stack
  3330  // we assume that it will have set it up so that traceback will be consistent,
  3331  // either by being a traceback terminating function
  3332  // or putting one on the stack at the right offset.
  3333  func setsSP(pc uintptr) bool {
  3334  	f := findfunc(pc)
  3335  	if f == nil {
  3336  		// couldn't find the function for this PC,
  3337  		// so assume the worst and stop traceback
  3338  		return true
  3339  	}
  3340  	switch f.entry {
  3341  	case gogoPC, systemstackPC, mcallPC, morestackPC:
  3342  		return true
  3343  	}
  3344  	return false
  3345  }
  3346  
  3347  // Arrange to call fn with a traceback hz times a second.
  3348  func setcpuprofilerate_m(hz int32) {
  3349  	// Force sane arguments.
  3350  	if hz < 0 {
  3351  		hz = 0
  3352  	}
  3353  
  3354  	// Disable preemption, otherwise we can be rescheduled to another thread
  3355  	// that has profiling enabled.
  3356  	_g_ := getg()
  3357  	_g_.m.locks++
  3358  
  3359  	// Stop profiler on this thread so that it is safe to lock prof.
  3360  	// if a profiling signal came in while we had prof locked,
  3361  	// it would deadlock.
  3362  	resetcpuprofiler(0)
  3363  
  3364  	for !atomic.Cas(&prof.lock, 0, 1) {
  3365  		osyield()
  3366  	}
  3367  	prof.hz = hz
  3368  	atomic.Store(&prof.lock, 0)
  3369  
  3370  	lock(&sched.lock)
  3371  	sched.profilehz = hz
  3372  	unlock(&sched.lock)
  3373  
  3374  	if hz != 0 {
  3375  		resetcpuprofiler(hz)
  3376  	}
  3377  
  3378  	_g_.m.locks--
  3379  }
  3380  
  3381  // Change number of processors. The world is stopped, sched is locked.
  3382  // gcworkbufs are not being modified by either the GC or
  3383  // the write barrier code.
  3384  // Returns list of Ps with local work, they need to be scheduled by the caller.
  3385  func procresize(nprocs int32) *p {
  3386  	old := gomaxprocs
  3387  	if old < 0 || old > _MaxGomaxprocs || nprocs <= 0 || nprocs > _MaxGomaxprocs {
  3388  		throw("procresize: invalid arg")
  3389  	}
  3390  	if trace.enabled {
  3391  		traceGomaxprocs(nprocs)
  3392  	}
  3393  
  3394  	// update statistics
  3395  	now := nanotime()
  3396  	if sched.procresizetime != 0 {
  3397  		sched.totaltime += int64(old) * (now - sched.procresizetime)
  3398  	}
  3399  	sched.procresizetime = now
  3400  
  3401  	// initialize new P's
  3402  	for i := int32(0); i < nprocs; i++ {
  3403  		pp := allp[i]
  3404  		if pp == nil {
  3405  			pp = new(p)
  3406  			pp.id = i
  3407  			pp.status = _Pgcstop
  3408  			pp.sudogcache = pp.sudogbuf[:0]
  3409  			for i := range pp.deferpool {
  3410  				pp.deferpool[i] = pp.deferpoolbuf[i][:0]
  3411  			}
  3412  			atomicstorep(unsafe.Pointer(&allp[i]), unsafe.Pointer(pp))
  3413  		}
  3414  		if pp.mcache == nil {
  3415  			if old == 0 && i == 0 {
  3416  				if getg().m.mcache == nil {
  3417  					throw("missing mcache?")
  3418  				}
  3419  				pp.mcache = getg().m.mcache // bootstrap
  3420  			} else {
  3421  				pp.mcache = allocmcache()
  3422  			}
  3423  		}
  3424  		if raceenabled && pp.racectx == 0 {
  3425  			if old == 0 && i == 0 {
  3426  				pp.racectx = raceprocctx0
  3427  				raceprocctx0 = 0 // bootstrap
  3428  			} else {
  3429  				pp.racectx = raceproccreate()
  3430  			}
  3431  		}
  3432  	}
  3433  
  3434  	// free unused P's
  3435  	for i := nprocs; i < old; i++ {
  3436  		p := allp[i]
  3437  		if trace.enabled {
  3438  			if p == getg().m.p.ptr() {
  3439  				// moving to p[0], pretend that we were descheduled
  3440  				// and then scheduled again to keep the trace sane.
  3441  				traceGoSched()
  3442  				traceProcStop(p)
  3443  			}
  3444  		}
  3445  		// move all runnable goroutines to the global queue
  3446  		for p.runqhead != p.runqtail {
  3447  			// pop from tail of local queue
  3448  			p.runqtail--
  3449  			gp := p.runq[p.runqtail%uint32(len(p.runq))].ptr()
  3450  			// push onto head of global queue
  3451  			globrunqputhead(gp)
  3452  		}
  3453  		if p.runnext != 0 {
  3454  			globrunqputhead(p.runnext.ptr())
  3455  			p.runnext = 0
  3456  		}
  3457  		// if there's a background worker, make it runnable and put
  3458  		// it on the global queue so it can clean itself up
  3459  		if gp := p.gcBgMarkWorker.ptr(); gp != nil {
  3460  			casgstatus(gp, _Gwaiting, _Grunnable)
  3461  			if trace.enabled {
  3462  				traceGoUnpark(gp, 0)
  3463  			}
  3464  			globrunqput(gp)
  3465  			// This assignment doesn't race because the
  3466  			// world is stopped.
  3467  			p.gcBgMarkWorker.set(nil)
  3468  		}
  3469  		for i := range p.sudogbuf {
  3470  			p.sudogbuf[i] = nil
  3471  		}
  3472  		p.sudogcache = p.sudogbuf[:0]
  3473  		for i := range p.deferpool {
  3474  			for j := range p.deferpoolbuf[i] {
  3475  				p.deferpoolbuf[i][j] = nil
  3476  			}
  3477  			p.deferpool[i] = p.deferpoolbuf[i][:0]
  3478  		}
  3479  		freemcache(p.mcache)
  3480  		p.mcache = nil
  3481  		gfpurge(p)
  3482  		traceProcFree(p)
  3483  		if raceenabled {
  3484  			raceprocdestroy(p.racectx)
  3485  			p.racectx = 0
  3486  		}
  3487  		p.status = _Pdead
  3488  		// can't free P itself because it can be referenced by an M in syscall
  3489  	}
  3490  
  3491  	_g_ := getg()
  3492  	if _g_.m.p != 0 && _g_.m.p.ptr().id < nprocs {
  3493  		// continue to use the current P
  3494  		_g_.m.p.ptr().status = _Prunning
  3495  	} else {
  3496  		// release the current P and acquire allp[0]
  3497  		if _g_.m.p != 0 {
  3498  			_g_.m.p.ptr().m = 0
  3499  		}
  3500  		_g_.m.p = 0
  3501  		_g_.m.mcache = nil
  3502  		p := allp[0]
  3503  		p.m = 0
  3504  		p.status = _Pidle
  3505  		acquirep(p)
  3506  		if trace.enabled {
  3507  			traceGoStart()
  3508  		}
  3509  	}
  3510  	var runnablePs *p
  3511  	for i := nprocs - 1; i >= 0; i-- {
  3512  		p := allp[i]
  3513  		if _g_.m.p.ptr() == p {
  3514  			continue
  3515  		}
  3516  		p.status = _Pidle
  3517  		if runqempty(p) {
  3518  			pidleput(p)
  3519  		} else {
  3520  			p.m.set(mget())
  3521  			p.link.set(runnablePs)
  3522  			runnablePs = p
  3523  		}
  3524  	}
  3525  	stealOrder.reset(uint32(nprocs))
  3526  	var int32p *int32 = &gomaxprocs // make compiler check that gomaxprocs is an int32
  3527  	atomic.Store((*uint32)(unsafe.Pointer(int32p)), uint32(nprocs))
  3528  	return runnablePs
  3529  }
  3530  
  3531  // Associate p and the current m.
  3532  //
  3533  // This function is allowed to have write barriers even if the caller
  3534  // isn't because it immediately acquires _p_.
  3535  //
  3536  //go:yeswritebarrierrec
  3537  func acquirep(_p_ *p) {
  3538  	// Do the part that isn't allowed to have write barriers.
  3539  	acquirep1(_p_)
  3540  
  3541  	// have p; write barriers now allowed
  3542  	_g_ := getg()
  3543  	_g_.m.mcache = _p_.mcache
  3544  
  3545  	if trace.enabled {
  3546  		traceProcStart()
  3547  	}
  3548  }
  3549  
  3550  // acquirep1 is the first step of acquirep, which actually acquires
  3551  // _p_. This is broken out so we can disallow write barriers for this
  3552  // part, since we don't yet have a P.
  3553  //
  3554  //go:nowritebarrierrec
  3555  func acquirep1(_p_ *p) {
  3556  	_g_ := getg()
  3557  
  3558  	if _g_.m.p != 0 || _g_.m.mcache != nil {
  3559  		throw("acquirep: already in go")
  3560  	}
  3561  	if _p_.m != 0 || _p_.status != _Pidle {
  3562  		id := int32(0)
  3563  		if _p_.m != 0 {
  3564  			id = _p_.m.ptr().id
  3565  		}
  3566  		print("acquirep: p->m=", _p_.m, "(", id, ") p->status=", _p_.status, "\n")
  3567  		throw("acquirep: invalid p state")
  3568  	}
  3569  	_g_.m.p.set(_p_)
  3570  	_p_.m.set(_g_.m)
  3571  	_p_.status = _Prunning
  3572  }
  3573  
  3574  // Disassociate p and the current m.
  3575  func releasep() *p {
  3576  	_g_ := getg()
  3577  
  3578  	if _g_.m.p == 0 || _g_.m.mcache == nil {
  3579  		throw("releasep: invalid arg")
  3580  	}
  3581  	_p_ := _g_.m.p.ptr()
  3582  	if _p_.m.ptr() != _g_.m || _p_.mcache != _g_.m.mcache || _p_.status != _Prunning {
  3583  		print("releasep: m=", _g_.m, " m->p=", _g_.m.p.ptr(), " p->m=", _p_.m, " m->mcache=", _g_.m.mcache, " p->mcache=", _p_.mcache, " p->status=", _p_.status, "\n")
  3584  		throw("releasep: invalid p state")
  3585  	}
  3586  	if trace.enabled {
  3587  		traceProcStop(_g_.m.p.ptr())
  3588  	}
  3589  	_g_.m.p = 0
  3590  	_g_.m.mcache = nil
  3591  	_p_.m = 0
  3592  	_p_.status = _Pidle
  3593  	return _p_
  3594  }
  3595  
  3596  func incidlelocked(v int32) {
  3597  	lock(&sched.lock)
  3598  	sched.nmidlelocked += v
  3599  	if v > 0 {
  3600  		checkdead()
  3601  	}
  3602  	unlock(&sched.lock)
  3603  }
  3604  
  3605  // Check for deadlock situation.
  3606  // The check is based on number of running M's, if 0 -> deadlock.
  3607  func checkdead() {
  3608  	// For -buildmode=c-shared or -buildmode=c-archive it's OK if
  3609  	// there are no running goroutines. The calling program is
  3610  	// assumed to be running.
  3611  	if islibrary || isarchive {
  3612  		return
  3613  	}
  3614  
  3615  	// If we are dying because of a signal caught on an already idle thread,
  3616  	// freezetheworld will cause all running threads to block.
  3617  	// And runtime will essentially enter into deadlock state,
  3618  	// except that there is a thread that will call exit soon.
  3619  	if panicking > 0 {
  3620  		return
  3621  	}
  3622  
  3623  	// -1 for sysmon
  3624  	run := sched.mcount - sched.nmidle - sched.nmidlelocked - 1
  3625  	if run > 0 {
  3626  		return
  3627  	}
  3628  	if run < 0 {
  3629  		print("runtime: checkdead: nmidle=", sched.nmidle, " nmidlelocked=", sched.nmidlelocked, " mcount=", sched.mcount, "\n")
  3630  		throw("checkdead: inconsistent counts")
  3631  	}
  3632  
  3633  	grunning := 0
  3634  	lock(&allglock)
  3635  	for i := 0; i < len(allgs); i++ {
  3636  		gp := allgs[i]
  3637  		if isSystemGoroutine(gp) {
  3638  			continue
  3639  		}
  3640  		s := readgstatus(gp)
  3641  		switch s &^ _Gscan {
  3642  		case _Gwaiting:
  3643  			grunning++
  3644  		case _Grunnable,
  3645  			_Grunning,
  3646  			_Gsyscall:
  3647  			unlock(&allglock)
  3648  			print("runtime: checkdead: find g ", gp.goid, " in status ", s, "\n")
  3649  			throw("checkdead: runnable g")
  3650  		}
  3651  	}
  3652  	unlock(&allglock)
  3653  	if grunning == 0 { // possible if main goroutine calls runtime·Goexit()
  3654  		throw("no goroutines (main called runtime.Goexit) - deadlock!")
  3655  	}
  3656  
  3657  	// Maybe jump time forward for playground.
  3658  	gp := timejump()
  3659  	if gp != nil {
  3660  		casgstatus(gp, _Gwaiting, _Grunnable)
  3661  		globrunqput(gp)
  3662  		_p_ := pidleget()
  3663  		if _p_ == nil {
  3664  			throw("checkdead: no p for timer")
  3665  		}
  3666  		mp := mget()
  3667  		if mp == nil {
  3668  			// There should always be a free M since
  3669  			// nothing is running.
  3670  			throw("checkdead: no m for timer")
  3671  		}
  3672  		mp.nextp.set(_p_)
  3673  		notewakeup(&mp.park)
  3674  		return
  3675  	}
  3676  
  3677  	getg().m.throwing = -1 // do not dump full stacks
  3678  	throw("all goroutines are asleep - deadlock!")
  3679  }
  3680  
  3681  // forcegcperiod is the maximum time in nanoseconds between garbage
  3682  // collections. If we go this long without a garbage collection, one
  3683  // is forced to run.
  3684  //
  3685  // This is a variable for testing purposes. It normally doesn't change.
  3686  var forcegcperiod int64 = 2 * 60 * 1e9
  3687  
  3688  // Always runs without a P, so write barriers are not allowed.
  3689  //
  3690  //go:nowritebarrierrec
  3691  func sysmon() {
  3692  	// If a heap span goes unused for 5 minutes after a garbage collection,
  3693  	// we hand it back to the operating system.
  3694  	scavengelimit := int64(5 * 60 * 1e9)
  3695  
  3696  	if debug.scavenge > 0 {
  3697  		// Scavenge-a-lot for testing.
  3698  		forcegcperiod = 10 * 1e6
  3699  		scavengelimit = 20 * 1e6
  3700  	}
  3701  
  3702  	lastscavenge := nanotime()
  3703  	nscavenge := 0
  3704  
  3705  	lasttrace := int64(0)
  3706  	idle := 0 // how many cycles in succession we had not wokeup somebody
  3707  	delay := uint32(0)
  3708  	for {
  3709  		if idle == 0 { // start with 20us sleep...
  3710  			delay = 20
  3711  		} else if idle > 50 { // start doubling the sleep after 1ms...
  3712  			delay *= 2
  3713  		}
  3714  		if delay > 10*1000 { // up to 10ms
  3715  			delay = 10 * 1000
  3716  		}
  3717  		usleep(delay)
  3718  		if debug.schedtrace <= 0 && (sched.gcwaiting != 0 || atomic.Load(&sched.npidle) == uint32(gomaxprocs)) {
  3719  			lock(&sched.lock)
  3720  			if atomic.Load(&sched.gcwaiting) != 0 || atomic.Load(&sched.npidle) == uint32(gomaxprocs) {
  3721  				atomic.Store(&sched.sysmonwait, 1)
  3722  				unlock(&sched.lock)
  3723  				// Make wake-up period small enough
  3724  				// for the sampling to be correct.
  3725  				maxsleep := forcegcperiod / 2
  3726  				if scavengelimit < forcegcperiod {
  3727  					maxsleep = scavengelimit / 2
  3728  				}
  3729  				notetsleep(&sched.sysmonnote, maxsleep)
  3730  				lock(&sched.lock)
  3731  				atomic.Store(&sched.sysmonwait, 0)
  3732  				noteclear(&sched.sysmonnote)
  3733  				idle = 0
  3734  				delay = 20
  3735  			}
  3736  			unlock(&sched.lock)
  3737  		}
  3738  		// poll network if not polled for more than 10ms
  3739  		lastpoll := int64(atomic.Load64(&sched.lastpoll))
  3740  		now := nanotime()
  3741  		unixnow := unixnanotime()
  3742  		if lastpoll != 0 && lastpoll+10*1000*1000 < now {
  3743  			atomic.Cas64(&sched.lastpoll, uint64(lastpoll), uint64(now))
  3744  			gp := netpoll(false) // non-blocking - returns list of goroutines
  3745  			if gp != nil {
  3746  				// Need to decrement number of idle locked M's
  3747  				// (pretending that one more is running) before injectglist.
  3748  				// Otherwise it can lead to the following situation:
  3749  				// injectglist grabs all P's but before it starts M's to run the P's,
  3750  				// another M returns from syscall, finishes running its G,
  3751  				// observes that there is no work to do and no other running M's
  3752  				// and reports deadlock.
  3753  				incidlelocked(-1)
  3754  				injectglist(gp)
  3755  				incidlelocked(1)
  3756  			}
  3757  		}
  3758  		// retake P's blocked in syscalls
  3759  		// and preempt long running G's
  3760  		if retake(now) != 0 {
  3761  			idle = 0
  3762  		} else {
  3763  			idle++
  3764  		}
  3765  		// check if we need to force a GC
  3766  		lastgc := int64(atomic.Load64(&memstats.last_gc))
  3767  		if gcphase == _GCoff && lastgc != 0 && unixnow-lastgc > forcegcperiod && atomic.Load(&forcegc.idle) != 0 {
  3768  			lock(&forcegc.lock)
  3769  			forcegc.idle = 0
  3770  			forcegc.g.schedlink = 0
  3771  			injectglist(forcegc.g)
  3772  			unlock(&forcegc.lock)
  3773  		}
  3774  		// scavenge heap once in a while
  3775  		if lastscavenge+scavengelimit/2 < now {
  3776  			mheap_.scavenge(int32(nscavenge), uint64(now), uint64(scavengelimit))
  3777  			lastscavenge = now
  3778  			nscavenge++
  3779  		}
  3780  		if debug.schedtrace > 0 && lasttrace+int64(debug.schedtrace)*1000000 <= now {
  3781  			lasttrace = now
  3782  			schedtrace(debug.scheddetail > 0)
  3783  		}
  3784  	}
  3785  }
  3786  
  3787  var pdesc [_MaxGomaxprocs]struct {
  3788  	schedtick   uint32
  3789  	schedwhen   int64
  3790  	syscalltick uint32
  3791  	syscallwhen int64
  3792  }
  3793  
  3794  // forcePreemptNS is the time slice given to a G before it is
  3795  // preempted.
  3796  const forcePreemptNS = 10 * 1000 * 1000 // 10ms
  3797  
  3798  func retake(now int64) uint32 {
  3799  	n := 0
  3800  	for i := int32(0); i < gomaxprocs; i++ {
  3801  		_p_ := allp[i]
  3802  		if _p_ == nil {
  3803  			continue
  3804  		}
  3805  		pd := &pdesc[i]
  3806  		s := _p_.status
  3807  		if s == _Psyscall {
  3808  			// Retake P from syscall if it's there for more than 1 sysmon tick (at least 20us).
  3809  			t := int64(_p_.syscalltick)
  3810  			if int64(pd.syscalltick) != t {
  3811  				pd.syscalltick = uint32(t)
  3812  				pd.syscallwhen = now
  3813  				continue
  3814  			}
  3815  			// On the one hand we don't want to retake Ps if there is no other work to do,
  3816  			// but on the other hand we want to retake them eventually
  3817  			// because they can prevent the sysmon thread from deep sleep.
  3818  			if runqempty(_p_) && atomic.Load(&sched.nmspinning)+atomic.Load(&sched.npidle) > 0 && pd.syscallwhen+10*1000*1000 > now {
  3819  				continue
  3820  			}
  3821  			// Need to decrement number of idle locked M's
  3822  			// (pretending that one more is running) before the CAS.
  3823  			// Otherwise the M from which we retake can exit the syscall,
  3824  			// increment nmidle and report deadlock.
  3825  			incidlelocked(-1)
  3826  			if atomic.Cas(&_p_.status, s, _Pidle) {
  3827  				if trace.enabled {
  3828  					traceGoSysBlock(_p_)
  3829  					traceProcStop(_p_)
  3830  				}
  3831  				n++
  3832  				_p_.syscalltick++
  3833  				handoffp(_p_)
  3834  			}
  3835  			incidlelocked(1)
  3836  		} else if s == _Prunning {
  3837  			// Preempt G if it's running for too long.
  3838  			t := int64(_p_.schedtick)
  3839  			if int64(pd.schedtick) != t {
  3840  				pd.schedtick = uint32(t)
  3841  				pd.schedwhen = now
  3842  				continue
  3843  			}
  3844  			if pd.schedwhen+forcePreemptNS > now {
  3845  				continue
  3846  			}
  3847  			preemptone(_p_)
  3848  		}
  3849  	}
  3850  	return uint32(n)
  3851  }
  3852  
  3853  // Tell all goroutines that they have been preempted and they should stop.
  3854  // This function is purely best-effort. It can fail to inform a goroutine if a
  3855  // processor just started running it.
  3856  // No locks need to be held.
  3857  // Returns true if preemption request was issued to at least one goroutine.
  3858  func preemptall() bool {
  3859  	res := false
  3860  	for i := int32(0); i < gomaxprocs; i++ {
  3861  		_p_ := allp[i]
  3862  		if _p_ == nil || _p_.status != _Prunning {
  3863  			continue
  3864  		}
  3865  		if preemptone(_p_) {
  3866  			res = true
  3867  		}
  3868  	}
  3869  	return res
  3870  }
  3871  
  3872  // Tell the goroutine running on processor P to stop.
  3873  // This function is purely best-effort. It can incorrectly fail to inform the
  3874  // goroutine. It can send inform the wrong goroutine. Even if it informs the
  3875  // correct goroutine, that goroutine might ignore the request if it is
  3876  // simultaneously executing newstack.
  3877  // No lock needs to be held.
  3878  // Returns true if preemption request was issued.
  3879  // The actual preemption will happen at some point in the future
  3880  // and will be indicated by the gp->status no longer being
  3881  // Grunning
  3882  func preemptone(_p_ *p) bool {
  3883  	mp := _p_.m.ptr()
  3884  	if mp == nil || mp == getg().m {
  3885  		return false
  3886  	}
  3887  	gp := mp.curg
  3888  	if gp == nil || gp == mp.g0 {
  3889  		return false
  3890  	}
  3891  
  3892  	gp.preempt = true
  3893  
  3894  	// Every call in a go routine checks for stack overflow by
  3895  	// comparing the current stack pointer to gp->stackguard0.
  3896  	// Setting gp->stackguard0 to StackPreempt folds
  3897  	// preemption into the normal stack overflow check.
  3898  	gp.stackguard0 = stackPreempt
  3899  	return true
  3900  }
  3901  
  3902  var starttime int64
  3903  
  3904  func schedtrace(detailed bool) {
  3905  	now := nanotime()
  3906  	if starttime == 0 {
  3907  		starttime = now
  3908  	}
  3909  
  3910  	lock(&sched.lock)
  3911  	print("SCHED ", (now-starttime)/1e6, "ms: gomaxprocs=", gomaxprocs, " idleprocs=", sched.npidle, " threads=", sched.mcount, " spinningthreads=", sched.nmspinning, " idlethreads=", sched.nmidle, " runqueue=", sched.runqsize)
  3912  	if detailed {
  3913  		print(" gcwaiting=", sched.gcwaiting, " nmidlelocked=", sched.nmidlelocked, " stopwait=", sched.stopwait, " sysmonwait=", sched.sysmonwait, "\n")
  3914  	}
  3915  	// We must be careful while reading data from P's, M's and G's.
  3916  	// Even if we hold schedlock, most data can be changed concurrently.
  3917  	// E.g. (p->m ? p->m->id : -1) can crash if p->m changes from non-nil to nil.
  3918  	for i := int32(0); i < gomaxprocs; i++ {
  3919  		_p_ := allp[i]
  3920  		if _p_ == nil {
  3921  			continue
  3922  		}
  3923  		mp := _p_.m.ptr()
  3924  		h := atomic.Load(&_p_.runqhead)
  3925  		t := atomic.Load(&_p_.runqtail)
  3926  		if detailed {
  3927  			id := int32(-1)
  3928  			if mp != nil {
  3929  				id = mp.id
  3930  			}
  3931  			print("  P", i, ": status=", _p_.status, " schedtick=", _p_.schedtick, " syscalltick=", _p_.syscalltick, " m=", id, " runqsize=", t-h, " gfreecnt=", _p_.gfreecnt, "\n")
  3932  		} else {
  3933  			// In non-detailed mode format lengths of per-P run queues as:
  3934  			// [len1 len2 len3 len4]
  3935  			print(" ")
  3936  			if i == 0 {
  3937  				print("[")
  3938  			}
  3939  			print(t - h)
  3940  			if i == gomaxprocs-1 {
  3941  				print("]\n")
  3942  			}
  3943  		}
  3944  	}
  3945  
  3946  	if !detailed {
  3947  		unlock(&sched.lock)
  3948  		return
  3949  	}
  3950  
  3951  	for mp := allm; mp != nil; mp = mp.alllink {
  3952  		_p_ := mp.p.ptr()
  3953  		gp := mp.curg
  3954  		lockedg := mp.lockedg
  3955  		id1 := int32(-1)
  3956  		if _p_ != nil {
  3957  			id1 = _p_.id
  3958  		}
  3959  		id2 := int64(-1)
  3960  		if gp != nil {
  3961  			id2 = gp.goid
  3962  		}
  3963  		id3 := int64(-1)
  3964  		if lockedg != nil {
  3965  			id3 = lockedg.goid
  3966  		}
  3967  		print("  M", mp.id, ": p=", id1, " curg=", id2, " mallocing=", mp.mallocing, " throwing=", mp.throwing, " preemptoff=", mp.preemptoff, ""+" locks=", mp.locks, " dying=", mp.dying, " helpgc=", mp.helpgc, " spinning=", mp.spinning, " blocked=", mp.blocked, " lockedg=", id3, "\n")
  3968  	}
  3969  
  3970  	lock(&allglock)
  3971  	for gi := 0; gi < len(allgs); gi++ {
  3972  		gp := allgs[gi]
  3973  		mp := gp.m
  3974  		lockedm := gp.lockedm
  3975  		id1 := int32(-1)
  3976  		if mp != nil {
  3977  			id1 = mp.id
  3978  		}
  3979  		id2 := int32(-1)
  3980  		if lockedm != nil {
  3981  			id2 = lockedm.id
  3982  		}
  3983  		print("  G", gp.goid, ": status=", readgstatus(gp), "(", gp.waitreason, ") m=", id1, " lockedm=", id2, "\n")
  3984  	}
  3985  	unlock(&allglock)
  3986  	unlock(&sched.lock)
  3987  }
  3988  
  3989  // Put mp on midle list.
  3990  // Sched must be locked.
  3991  // May run during STW, so write barriers are not allowed.
  3992  //go:nowritebarrierrec
  3993  func mput(mp *m) {
  3994  	mp.schedlink = sched.midle
  3995  	sched.midle.set(mp)
  3996  	sched.nmidle++
  3997  	checkdead()
  3998  }
  3999  
  4000  // Try to get an m from midle list.
  4001  // Sched must be locked.
  4002  // May run during STW, so write barriers are not allowed.
  4003  //go:nowritebarrierrec
  4004  func mget() *m {
  4005  	mp := sched.midle.ptr()
  4006  	if mp != nil {
  4007  		sched.midle = mp.schedlink
  4008  		sched.nmidle--
  4009  	}
  4010  	return mp
  4011  }
  4012  
  4013  // Put gp on the global runnable queue.
  4014  // Sched must be locked.
  4015  // May run during STW, so write barriers are not allowed.
  4016  //go:nowritebarrierrec
  4017  func globrunqput(gp *g) {
  4018  	gp.schedlink = 0
  4019  	if sched.runqtail != 0 {
  4020  		sched.runqtail.ptr().schedlink.set(gp)
  4021  	} else {
  4022  		sched.runqhead.set(gp)
  4023  	}
  4024  	sched.runqtail.set(gp)
  4025  	sched.runqsize++
  4026  }
  4027  
  4028  // Put gp at the head of the global runnable queue.
  4029  // Sched must be locked.
  4030  // May run during STW, so write barriers are not allowed.
  4031  //go:nowritebarrierrec
  4032  func globrunqputhead(gp *g) {
  4033  	gp.schedlink = sched.runqhead
  4034  	sched.runqhead.set(gp)
  4035  	if sched.runqtail == 0 {
  4036  		sched.runqtail.set(gp)
  4037  	}
  4038  	sched.runqsize++
  4039  }
  4040  
  4041  // Put a batch of runnable goroutines on the global runnable queue.
  4042  // Sched must be locked.
  4043  func globrunqputbatch(ghead *g, gtail *g, n int32) {
  4044  	gtail.schedlink = 0
  4045  	if sched.runqtail != 0 {
  4046  		sched.runqtail.ptr().schedlink.set(ghead)
  4047  	} else {
  4048  		sched.runqhead.set(ghead)
  4049  	}
  4050  	sched.runqtail.set(gtail)
  4051  	sched.runqsize += n
  4052  }
  4053  
  4054  // Try get a batch of G's from the global runnable queue.
  4055  // Sched must be locked.
  4056  func globrunqget(_p_ *p, max int32) *g {
  4057  	if sched.runqsize == 0 {
  4058  		return nil
  4059  	}
  4060  
  4061  	n := sched.runqsize/gomaxprocs + 1
  4062  	if n > sched.runqsize {
  4063  		n = sched.runqsize
  4064  	}
  4065  	if max > 0 && n > max {
  4066  		n = max
  4067  	}
  4068  	if n > int32(len(_p_.runq))/2 {
  4069  		n = int32(len(_p_.runq)) / 2
  4070  	}
  4071  
  4072  	sched.runqsize -= n
  4073  	if sched.runqsize == 0 {
  4074  		sched.runqtail = 0
  4075  	}
  4076  
  4077  	gp := sched.runqhead.ptr()
  4078  	sched.runqhead = gp.schedlink
  4079  	n--
  4080  	for ; n > 0; n-- {
  4081  		gp1 := sched.runqhead.ptr()
  4082  		sched.runqhead = gp1.schedlink
  4083  		runqput(_p_, gp1, false)
  4084  	}
  4085  	return gp
  4086  }
  4087  
  4088  // Put p to on _Pidle list.
  4089  // Sched must be locked.
  4090  // May run during STW, so write barriers are not allowed.
  4091  //go:nowritebarrierrec
  4092  func pidleput(_p_ *p) {
  4093  	if !runqempty(_p_) {
  4094  		throw("pidleput: P has non-empty run queue")
  4095  	}
  4096  	_p_.link = sched.pidle
  4097  	sched.pidle.set(_p_)
  4098  	atomic.Xadd(&sched.npidle, 1) // TODO: fast atomic
  4099  }
  4100  
  4101  // Try get a p from _Pidle list.
  4102  // Sched must be locked.
  4103  // May run during STW, so write barriers are not allowed.
  4104  //go:nowritebarrierrec
  4105  func pidleget() *p {
  4106  	_p_ := sched.pidle.ptr()
  4107  	if _p_ != nil {
  4108  		sched.pidle = _p_.link
  4109  		atomic.Xadd(&sched.npidle, -1) // TODO: fast atomic
  4110  	}
  4111  	return _p_
  4112  }
  4113  
  4114  // runqempty returns true if _p_ has no Gs on its local run queue.
  4115  // It never returns true spuriously.
  4116  func runqempty(_p_ *p) bool {
  4117  	// Defend against a race where 1) _p_ has G1 in runqnext but runqhead == runqtail,
  4118  	// 2) runqput on _p_ kicks G1 to the runq, 3) runqget on _p_ empties runqnext.
  4119  	// Simply observing that runqhead == runqtail and then observing that runqnext == nil
  4120  	// does not mean the queue is empty.
  4121  	for {
  4122  		head := atomic.Load(&_p_.runqhead)
  4123  		tail := atomic.Load(&_p_.runqtail)
  4124  		runnext := atomic.Loaduintptr((*uintptr)(unsafe.Pointer(&_p_.runnext)))
  4125  		if tail == atomic.Load(&_p_.runqtail) {
  4126  			return head == tail && runnext == 0
  4127  		}
  4128  	}
  4129  }
  4130  
  4131  // To shake out latent assumptions about scheduling order,
  4132  // we introduce some randomness into scheduling decisions
  4133  // when running with the race detector.
  4134  // The need for this was made obvious by changing the
  4135  // (deterministic) scheduling order in Go 1.5 and breaking
  4136  // many poorly-written tests.
  4137  // With the randomness here, as long as the tests pass
  4138  // consistently with -race, they shouldn't have latent scheduling
  4139  // assumptions.
  4140  const randomizeScheduler = raceenabled
  4141  
  4142  // runqput tries to put g on the local runnable queue.
  4143  // If next if false, runqput adds g to the tail of the runnable queue.
  4144  // If next is true, runqput puts g in the _p_.runnext slot.
  4145  // If the run queue is full, runnext puts g on the global queue.
  4146  // Executed only by the owner P.
  4147  func runqput(_p_ *p, gp *g, next bool) {
  4148  	if randomizeScheduler && next && fastrand()%2 == 0 {
  4149  		next = false
  4150  	}
  4151  
  4152  	if next {
  4153  	retryNext:
  4154  		oldnext := _p_.runnext
  4155  		if !_p_.runnext.cas(oldnext, guintptr(unsafe.Pointer(gp))) {
  4156  			goto retryNext
  4157  		}
  4158  		if oldnext == 0 {
  4159  			return
  4160  		}
  4161  		// Kick the old runnext out to the regular run queue.
  4162  		gp = oldnext.ptr()
  4163  	}
  4164  
  4165  retry:
  4166  	h := atomic.Load(&_p_.runqhead) // load-acquire, synchronize with consumers
  4167  	t := _p_.runqtail
  4168  	if t-h < uint32(len(_p_.runq)) {
  4169  		_p_.runq[t%uint32(len(_p_.runq))].set(gp)
  4170  		atomic.Store(&_p_.runqtail, t+1) // store-release, makes the item available for consumption
  4171  		return
  4172  	}
  4173  	if runqputslow(_p_, gp, h, t) {
  4174  		return
  4175  	}
  4176  	// the queue is not full, now the put above must succeed
  4177  	goto retry
  4178  }
  4179  
  4180  // Put g and a batch of work from local runnable queue on global queue.
  4181  // Executed only by the owner P.
  4182  func runqputslow(_p_ *p, gp *g, h, t uint32) bool {
  4183  	var batch [len(_p_.runq)/2 + 1]*g
  4184  
  4185  	// First, grab a batch from local queue.
  4186  	n := t - h
  4187  	n = n / 2
  4188  	if n != uint32(len(_p_.runq)/2) {
  4189  		throw("runqputslow: queue is not full")
  4190  	}
  4191  	for i := uint32(0); i < n; i++ {
  4192  		batch[i] = _p_.runq[(h+i)%uint32(len(_p_.runq))].ptr()
  4193  	}
  4194  	if !atomic.Cas(&_p_.runqhead, h, h+n) { // cas-release, commits consume
  4195  		return false
  4196  	}
  4197  	batch[n] = gp
  4198  
  4199  	if randomizeScheduler {
  4200  		for i := uint32(1); i <= n; i++ {
  4201  			j := fastrand() % (i + 1)
  4202  			batch[i], batch[j] = batch[j], batch[i]
  4203  		}
  4204  	}
  4205  
  4206  	// Link the goroutines.
  4207  	for i := uint32(0); i < n; i++ {
  4208  		batch[i].schedlink.set(batch[i+1])
  4209  	}
  4210  
  4211  	// Now put the batch on global queue.
  4212  	lock(&sched.lock)
  4213  	globrunqputbatch(batch[0], batch[n], int32(n+1))
  4214  	unlock(&sched.lock)
  4215  	return true
  4216  }
  4217  
  4218  // Get g from local runnable queue.
  4219  // If inheritTime is true, gp should inherit the remaining time in the
  4220  // current time slice. Otherwise, it should start a new time slice.
  4221  // Executed only by the owner P.
  4222  func runqget(_p_ *p) (gp *g, inheritTime bool) {
  4223  	// If there's a runnext, it's the next G to run.
  4224  	for {
  4225  		next := _p_.runnext
  4226  		if next == 0 {
  4227  			break
  4228  		}
  4229  		if _p_.runnext.cas(next, 0) {
  4230  			return next.ptr(), true
  4231  		}
  4232  	}
  4233  
  4234  	for {
  4235  		h := atomic.Load(&_p_.runqhead) // load-acquire, synchronize with other consumers
  4236  		t := _p_.runqtail
  4237  		if t == h {
  4238  			return nil, false
  4239  		}
  4240  		gp := _p_.runq[h%uint32(len(_p_.runq))].ptr()
  4241  		if atomic.Cas(&_p_.runqhead, h, h+1) { // cas-release, commits consume
  4242  			return gp, false
  4243  		}
  4244  	}
  4245  }
  4246  
  4247  // Grabs a batch of goroutines from _p_'s runnable queue into batch.
  4248  // Batch is a ring buffer starting at batchHead.
  4249  // Returns number of grabbed goroutines.
  4250  // Can be executed by any P.
  4251  func runqgrab(_p_ *p, batch *[256]guintptr, batchHead uint32, stealRunNextG bool) uint32 {
  4252  	for {
  4253  		h := atomic.Load(&_p_.runqhead) // load-acquire, synchronize with other consumers
  4254  		t := atomic.Load(&_p_.runqtail) // load-acquire, synchronize with the producer
  4255  		n := t - h
  4256  		n = n - n/2
  4257  		if n == 0 {
  4258  			if stealRunNextG {
  4259  				// Try to steal from _p_.runnext.
  4260  				if next := _p_.runnext; next != 0 {
  4261  					// Sleep to ensure that _p_ isn't about to run the g we
  4262  					// are about to steal.
  4263  					// The important use case here is when the g running on _p_
  4264  					// ready()s another g and then almost immediately blocks.
  4265  					// Instead of stealing runnext in this window, back off
  4266  					// to give _p_ a chance to schedule runnext. This will avoid
  4267  					// thrashing gs between different Ps.
  4268  					// A sync chan send/recv takes ~50ns as of time of writing,
  4269  					// so 3us gives ~50x overshoot.
  4270  					if GOOS != "windows" {
  4271  						usleep(3)
  4272  					} else {
  4273  						// On windows system timer granularity is 1-15ms,
  4274  						// which is way too much for this optimization.
  4275  						// So just yield.
  4276  						osyield()
  4277  					}
  4278  					if !_p_.runnext.cas(next, 0) {
  4279  						continue
  4280  					}
  4281  					batch[batchHead%uint32(len(batch))] = next
  4282  					return 1
  4283  				}
  4284  			}
  4285  			return 0
  4286  		}
  4287  		if n > uint32(len(_p_.runq)/2) { // read inconsistent h and t
  4288  			continue
  4289  		}
  4290  		for i := uint32(0); i < n; i++ {
  4291  			g := _p_.runq[(h+i)%uint32(len(_p_.runq))]
  4292  			batch[(batchHead+i)%uint32(len(batch))] = g
  4293  		}
  4294  		if atomic.Cas(&_p_.runqhead, h, h+n) { // cas-release, commits consume
  4295  			return n
  4296  		}
  4297  	}
  4298  }
  4299  
  4300  // Steal half of elements from local runnable queue of p2
  4301  // and put onto local runnable queue of p.
  4302  // Returns one of the stolen elements (or nil if failed).
  4303  func runqsteal(_p_, p2 *p, stealRunNextG bool) *g {
  4304  	t := _p_.runqtail
  4305  	n := runqgrab(p2, &_p_.runq, t, stealRunNextG)
  4306  	if n == 0 {
  4307  		return nil
  4308  	}
  4309  	n--
  4310  	gp := _p_.runq[(t+n)%uint32(len(_p_.runq))].ptr()
  4311  	if n == 0 {
  4312  		return gp
  4313  	}
  4314  	h := atomic.Load(&_p_.runqhead) // load-acquire, synchronize with consumers
  4315  	if t-h+n >= uint32(len(_p_.runq)) {
  4316  		throw("runqsteal: runq overflow")
  4317  	}
  4318  	atomic.Store(&_p_.runqtail, t+n) // store-release, makes the item available for consumption
  4319  	return gp
  4320  }
  4321  
  4322  //go:linkname setMaxThreads runtime/debug.setMaxThreads
  4323  func setMaxThreads(in int) (out int) {
  4324  	lock(&sched.lock)
  4325  	out = int(sched.maxmcount)
  4326  	if in > 0x7fffffff { // MaxInt32
  4327  		sched.maxmcount = 0x7fffffff
  4328  	} else {
  4329  		sched.maxmcount = int32(in)
  4330  	}
  4331  	checkmcount()
  4332  	unlock(&sched.lock)
  4333  	return
  4334  }
  4335  
  4336  func haveexperiment(name string) bool {
  4337  	if name == "framepointer" {
  4338  		return framepointer_enabled // set by linker
  4339  	}
  4340  	x := sys.Goexperiment
  4341  	for x != "" {
  4342  		xname := ""
  4343  		i := index(x, ",")
  4344  		if i < 0 {
  4345  			xname, x = x, ""
  4346  		} else {
  4347  			xname, x = x[:i], x[i+1:]
  4348  		}
  4349  		if xname == name {
  4350  			return true
  4351  		}
  4352  		if len(xname) > 2 && xname[:2] == "no" && xname[2:] == name {
  4353  			return false
  4354  		}
  4355  	}
  4356  	return false
  4357  }
  4358  
  4359  //go:nosplit
  4360  func procPin() int {
  4361  	_g_ := getg()
  4362  	mp := _g_.m
  4363  
  4364  	mp.locks++
  4365  	return int(mp.p.ptr().id)
  4366  }
  4367  
  4368  //go:nosplit
  4369  func procUnpin() {
  4370  	_g_ := getg()
  4371  	_g_.m.locks--
  4372  }
  4373  
  4374  //go:linkname sync_runtime_procPin sync.runtime_procPin
  4375  //go:nosplit
  4376  func sync_runtime_procPin() int {
  4377  	return procPin()
  4378  }
  4379  
  4380  //go:linkname sync_runtime_procUnpin sync.runtime_procUnpin
  4381  //go:nosplit
  4382  func sync_runtime_procUnpin() {
  4383  	procUnpin()
  4384  }
  4385  
  4386  //go:linkname sync_atomic_runtime_procPin sync/atomic.runtime_procPin
  4387  //go:nosplit
  4388  func sync_atomic_runtime_procPin() int {
  4389  	return procPin()
  4390  }
  4391  
  4392  //go:linkname sync_atomic_runtime_procUnpin sync/atomic.runtime_procUnpin
  4393  //go:nosplit
  4394  func sync_atomic_runtime_procUnpin() {
  4395  	procUnpin()
  4396  }
  4397  
  4398  // Active spinning for sync.Mutex.
  4399  //go:linkname sync_runtime_canSpin sync.runtime_canSpin
  4400  //go:nosplit
  4401  func sync_runtime_canSpin(i int) bool {
  4402  	// sync.Mutex is cooperative, so we are conservative with spinning.
  4403  	// Spin only few times and only if running on a multicore machine and
  4404  	// GOMAXPROCS>1 and there is at least one other running P and local runq is empty.
  4405  	// As opposed to runtime mutex we don't do passive spinning here,
  4406  	// because there can be work on global runq on on other Ps.
  4407  	if i >= active_spin || ncpu <= 1 || gomaxprocs <= int32(sched.npidle+sched.nmspinning)+1 {
  4408  		return false
  4409  	}
  4410  	if p := getg().m.p.ptr(); !runqempty(p) {
  4411  		return false
  4412  	}
  4413  	return true
  4414  }
  4415  
  4416  //go:linkname sync_runtime_doSpin sync.runtime_doSpin
  4417  //go:nosplit
  4418  func sync_runtime_doSpin() {
  4419  	procyield(active_spin_cnt)
  4420  }
  4421  
  4422  var stealOrder randomOrder
  4423  
  4424  // randomOrder/randomEnum are helper types for randomized work stealing.
  4425  // They allow to enumerate all Ps in different pseudo-random orders without repetitions.
  4426  // The algorithm is based on the fact that if we have X such that X and GOMAXPROCS
  4427  // are coprime, then a sequences of (i + X) % GOMAXPROCS gives the required enumeration.
  4428  type randomOrder struct {
  4429  	count    uint32
  4430  	coprimes []uint32
  4431  }
  4432  
  4433  type randomEnum struct {
  4434  	i     uint32
  4435  	count uint32
  4436  	pos   uint32
  4437  	inc   uint32
  4438  }
  4439  
  4440  func (ord *randomOrder) reset(count uint32) {
  4441  	ord.count = count
  4442  	ord.coprimes = ord.coprimes[:0]
  4443  	for i := uint32(1); i <= count; i++ {
  4444  		if gcd(i, count) == 1 {
  4445  			ord.coprimes = append(ord.coprimes, i)
  4446  		}
  4447  	}
  4448  }
  4449  
  4450  func (ord *randomOrder) start(i uint32) randomEnum {
  4451  	return randomEnum{
  4452  		count: ord.count,
  4453  		pos:   i % ord.count,
  4454  		inc:   ord.coprimes[i%uint32(len(ord.coprimes))],
  4455  	}
  4456  }
  4457  
  4458  func (enum *randomEnum) done() bool {
  4459  	return enum.i == enum.count
  4460  }
  4461  
  4462  func (enum *randomEnum) next() {
  4463  	enum.i++
  4464  	enum.pos = (enum.pos + enum.inc) % enum.count
  4465  }
  4466  
  4467  func (enum *randomEnum) position() uint32 {
  4468  	return enum.pos
  4469  }
  4470  
  4471  func gcd(a, b uint32) uint32 {
  4472  	for b != 0 {
  4473  		a, b = b, a%b
  4474  	}
  4475  	return a
  4476  }