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

View as plain text