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