...
Run Format

Source file src/runtime/proc.go

Documentation: runtime

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

View as plain text