Source file src/runtime/proc.go

     1  // Copyright 2014 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package runtime
     6  
     7  import (
     8  	"internal/abi"
     9  	"internal/cpu"
    10  	"internal/goexperiment"
    11  	"runtime/internal/atomic"
    12  	"runtime/internal/sys"
    13  	"unsafe"
    14  )
    15  
    16  // set using cmd/go/internal/modload.ModInfoProg
    17  var modinfo string
    18  
    19  // Goroutine scheduler
    20  // The scheduler's job is to distribute ready-to-run goroutines over worker threads.
    21  //
    22  // The main concepts are:
    23  // G - goroutine.
    24  // M - worker thread, or machine.
    25  // P - processor, a resource that is required to execute Go code.
    26  //     M must have an associated P to execute Go code, however it can be
    27  //     blocked or in a syscall w/o an associated P.
    28  //
    29  // Design doc at https://golang.org/s/go11sched.
    30  
    31  // Worker thread parking/unparking.
    32  // We need to balance between keeping enough running worker threads to utilize
    33  // available hardware parallelism and parking excessive running worker threads
    34  // to conserve CPU resources and power. This is not simple for two reasons:
    35  // (1) scheduler state is intentionally distributed (in particular, per-P work
    36  // queues), so it is not possible to compute global predicates on fast paths;
    37  // (2) for optimal thread management we would need to know the future (don't park
    38  // a worker thread when a new goroutine will be readied in near future).
    39  //
    40  // Three rejected approaches that would work badly:
    41  // 1. Centralize all scheduler state (would inhibit scalability).
    42  // 2. Direct goroutine handoff. That is, when we ready a new goroutine and there
    43  //    is a spare P, unpark a thread and handoff it the thread and the goroutine.
    44  //    This would lead to thread state thrashing, as the thread that readied the
    45  //    goroutine can be out of work the very next moment, we will need to park it.
    46  //    Also, it would destroy locality of computation as we want to preserve
    47  //    dependent goroutines on the same thread; and introduce additional latency.
    48  // 3. Unpark an additional thread whenever we ready a goroutine and there is an
    49  //    idle P, but don't do handoff. This would lead to excessive thread parking/
    50  //    unparking as the additional threads will instantly park without discovering
    51  //    any work to do.
    52  //
    53  // The current approach:
    54  //
    55  // This approach applies to three primary sources of potential work: readying a
    56  // goroutine, new/modified-earlier timers, and idle-priority GC. See below for
    57  // additional details.
    58  //
    59  // We unpark an additional thread when we submit work if (this is wakep()):
    60  // 1. There is an idle P, and
    61  // 2. There are no "spinning" worker threads.
    62  //
    63  // A worker thread is considered spinning if it is out of local work and did
    64  // not find work in the global run queue or netpoller; the spinning state is
    65  // denoted in m.spinning and in sched.nmspinning. Threads unparked this way are
    66  // also considered spinning; we don't do goroutine handoff so such threads are
    67  // out of work initially. Spinning threads spin on looking for work in per-P
    68  // run queues and timer heaps or from the GC before parking. If a spinning
    69  // thread finds work it takes itself out of the spinning state and proceeds to
    70  // execution. If it does not find work it takes itself out of the spinning
    71  // state and then parks.
    72  //
    73  // If there is at least one spinning thread (sched.nmspinning>1), we don't
    74  // unpark new threads when submitting work. To compensate for that, if the last
    75  // spinning thread finds work and stops spinning, it must unpark a new spinning
    76  // thread.  This approach smooths out unjustified spikes of thread unparking,
    77  // but at the same time guarantees eventual maximal CPU parallelism
    78  // utilization.
    79  //
    80  // The main implementation complication is that we need to be very careful
    81  // during spinning->non-spinning thread transition. This transition can race
    82  // with submission of new work, and either one part or another needs to unpark
    83  // another worker thread. If they both fail to do that, we can end up with
    84  // semi-persistent CPU underutilization.
    85  //
    86  // The general pattern for submission is:
    87  // 1. Submit work to the local run queue, timer heap, or GC state.
    88  // 2. #StoreLoad-style memory barrier.
    89  // 3. Check sched.nmspinning.
    90  //
    91  // The general pattern for spinning->non-spinning transition is:
    92  // 1. Decrement nmspinning.
    93  // 2. #StoreLoad-style memory barrier.
    94  // 3. Check all per-P work queues and GC for new work.
    95  //
    96  // Note that all this complexity does not apply to global run queue as we are
    97  // not sloppy about thread unparking when submitting to global queue. Also see
    98  // comments for nmspinning manipulation.
    99  //
   100  // How these different sources of work behave varies, though it doesn't affect
   101  // the synchronization approach:
   102  // * Ready goroutine: this is an obvious source of work; the goroutine is
   103  //   immediately ready and must run on some thread eventually.
   104  // * New/modified-earlier timer: The current timer implementation (see time.go)
   105  //   uses netpoll in a thread with no work available to wait for the soonest
   106  //   timer. If there is no thread waiting, we want a new spinning thread to go
   107  //   wait.
   108  // * Idle-priority GC: The GC wakes a stopped idle thread to contribute to
   109  //   background GC work (note: currently disabled per golang.org/issue/19112).
   110  //   Also see golang.org/issue/44313, as this should be extended to all GC
   111  //   workers.
   112  
   113  var (
   114  	m0           m
   115  	g0           g
   116  	mcache0      *mcache
   117  	raceprocctx0 uintptr
   118  )
   119  
   120  //go:linkname runtime_inittask runtime..inittask
   121  var runtime_inittask initTask
   122  
   123  //go:linkname main_inittask main..inittask
   124  var main_inittask initTask
   125  
   126  // main_init_done is a signal used by cgocallbackg that initialization
   127  // has been completed. It is made before _cgo_notify_runtime_init_done,
   128  // so all cgo calls can rely on it existing. When main_init is complete,
   129  // it is closed, meaning cgocallbackg can reliably receive from it.
   130  var main_init_done chan bool
   131  
   132  //go:linkname main_main main.main
   133  func main_main()
   134  
   135  // mainStarted indicates that the main M has started.
   136  var mainStarted bool
   137  
   138  // runtimeInitTime is the nanotime() at which the runtime started.
   139  var runtimeInitTime int64
   140  
   141  // Value to use for signal mask for newly created M's.
   142  var initSigmask sigset
   143  
   144  // The main goroutine.
   145  func main() {
   146  	g := getg()
   147  
   148  	// Racectx of m0->g0 is used only as the parent of the main goroutine.
   149  	// It must not be used for anything else.
   150  	g.m.g0.racectx = 0
   151  
   152  	// Max stack size is 1 GB on 64-bit, 250 MB on 32-bit.
   153  	// Using decimal instead of binary GB and MB because
   154  	// they look nicer in the stack overflow failure message.
   155  	if sys.PtrSize == 8 {
   156  		maxstacksize = 1000000000
   157  	} else {
   158  		maxstacksize = 250000000
   159  	}
   160  
   161  	// An upper limit for max stack size. Used to avoid random crashes
   162  	// after calling SetMaxStack and trying to allocate a stack that is too big,
   163  	// since stackalloc works with 32-bit sizes.
   164  	maxstackceiling = 2 * maxstacksize
   165  
   166  	// Allow newproc to start new Ms.
   167  	mainStarted = true
   168  
   169  	if GOARCH != "wasm" { // no threads on wasm yet, so no sysmon
   170  		// For runtime_syscall_doAllThreadsSyscall, we
   171  		// register sysmon is not ready for the world to be
   172  		// stopped.
   173  		atomic.Store(&sched.sysmonStarting, 1)
   174  		systemstack(func() {
   175  			newm(sysmon, nil, -1)
   176  		})
   177  	}
   178  
   179  	// Lock the main goroutine onto this, the main OS thread,
   180  	// during initialization. Most programs won't care, but a few
   181  	// do require certain calls to be made by the main thread.
   182  	// Those can arrange for main.main to run in the main thread
   183  	// by calling runtime.LockOSThread during initialization
   184  	// to preserve the lock.
   185  	lockOSThread()
   186  
   187  	if g.m != &m0 {
   188  		throw("runtime.main not on m0")
   189  	}
   190  	m0.doesPark = true
   191  
   192  	// Record when the world started.
   193  	// Must be before doInit for tracing init.
   194  	runtimeInitTime = nanotime()
   195  	if runtimeInitTime == 0 {
   196  		throw("nanotime returning zero")
   197  	}
   198  
   199  	if debug.inittrace != 0 {
   200  		inittrace.id = getg().goid
   201  		inittrace.active = true
   202  	}
   203  
   204  	doInit(&runtime_inittask) // Must be before defer.
   205  
   206  	// Defer unlock so that runtime.Goexit during init does the unlock too.
   207  	needUnlock := true
   208  	defer func() {
   209  		if needUnlock {
   210  			unlockOSThread()
   211  		}
   212  	}()
   213  
   214  	gcenable()
   215  
   216  	main_init_done = make(chan bool)
   217  	if iscgo {
   218  		if _cgo_thread_start == nil {
   219  			throw("_cgo_thread_start missing")
   220  		}
   221  		if GOOS != "windows" {
   222  			if _cgo_setenv == nil {
   223  				throw("_cgo_setenv missing")
   224  			}
   225  			if _cgo_unsetenv == nil {
   226  				throw("_cgo_unsetenv missing")
   227  			}
   228  		}
   229  		if _cgo_notify_runtime_init_done == nil {
   230  			throw("_cgo_notify_runtime_init_done missing")
   231  		}
   232  		// Start the template thread in case we enter Go from
   233  		// a C-created thread and need to create a new thread.
   234  		startTemplateThread()
   235  		cgocall(_cgo_notify_runtime_init_done, nil)
   236  	}
   237  
   238  	doInit(&main_inittask)
   239  
   240  	// Disable init tracing after main init done to avoid overhead
   241  	// of collecting statistics in malloc and newproc
   242  	inittrace.active = false
   243  
   244  	close(main_init_done)
   245  
   246  	needUnlock = false
   247  	unlockOSThread()
   248  
   249  	if isarchive || islibrary {
   250  		// A program compiled with -buildmode=c-archive or c-shared
   251  		// has a main, but it is not executed.
   252  		return
   253  	}
   254  	fn := main_main // make an indirect call, as the linker doesn't know the address of the main package when laying down the runtime
   255  	fn()
   256  	if raceenabled {
   257  		racefini()
   258  	}
   259  
   260  	// Make racy client program work: if panicking on
   261  	// another goroutine at the same time as main returns,
   262  	// let the other goroutine finish printing the panic trace.
   263  	// Once it does, it will exit. See issues 3934 and 20018.
   264  	if atomic.Load(&runningPanicDefers) != 0 {
   265  		// Running deferred functions should not take long.
   266  		for c := 0; c < 1000; c++ {
   267  			if atomic.Load(&runningPanicDefers) == 0 {
   268  				break
   269  			}
   270  			Gosched()
   271  		}
   272  	}
   273  	if atomic.Load(&panicking) != 0 {
   274  		gopark(nil, nil, waitReasonPanicWait, traceEvGoStop, 1)
   275  	}
   276  
   277  	exit(0)
   278  	for {
   279  		var x *int32
   280  		*x = 0
   281  	}
   282  }
   283  
   284  // os_beforeExit is called from os.Exit(0).
   285  //go:linkname os_beforeExit os.runtime_beforeExit
   286  func os_beforeExit() {
   287  	if raceenabled {
   288  		racefini()
   289  	}
   290  }
   291  
   292  // start forcegc helper goroutine
   293  func init() {
   294  	go forcegchelper()
   295  }
   296  
   297  func forcegchelper() {
   298  	forcegc.g = getg()
   299  	lockInit(&forcegc.lock, lockRankForcegc)
   300  	for {
   301  		lock(&forcegc.lock)
   302  		if forcegc.idle != 0 {
   303  			throw("forcegc: phase error")
   304  		}
   305  		atomic.Store(&forcegc.idle, 1)
   306  		goparkunlock(&forcegc.lock, waitReasonForceGCIdle, traceEvGoBlock, 1)
   307  		// this goroutine is explicitly resumed by sysmon
   308  		if debug.gctrace > 0 {
   309  			println("GC forced")
   310  		}
   311  		// Time-triggered, fully concurrent.
   312  		gcStart(gcTrigger{kind: gcTriggerTime, now: nanotime()})
   313  	}
   314  }
   315  
   316  //go:nosplit
   317  
   318  // Gosched yields the processor, allowing other goroutines to run. It does not
   319  // suspend the current goroutine, so execution resumes automatically.
   320  func Gosched() {
   321  	checkTimeouts()
   322  	mcall(gosched_m)
   323  }
   324  
   325  // goschedguarded yields the processor like gosched, but also checks
   326  // for forbidden states and opts out of the yield in those cases.
   327  //go:nosplit
   328  func goschedguarded() {
   329  	mcall(goschedguarded_m)
   330  }
   331  
   332  // Puts the current goroutine into a waiting state and calls unlockf on the
   333  // system stack.
   334  //
   335  // If unlockf returns false, the goroutine is resumed.
   336  //
   337  // unlockf must not access this G's stack, as it may be moved between
   338  // the call to gopark and the call to unlockf.
   339  //
   340  // Note that because unlockf is called after putting the G into a waiting
   341  // state, the G may have already been readied by the time unlockf is called
   342  // unless there is external synchronization preventing the G from being
   343  // readied. If unlockf returns false, it must guarantee that the G cannot be
   344  // externally readied.
   345  //
   346  // Reason explains why the goroutine has been parked. It is displayed in stack
   347  // traces and heap dumps. Reasons should be unique and descriptive. Do not
   348  // re-use reasons, add new ones.
   349  func gopark(unlockf func(*g, unsafe.Pointer) bool, lock unsafe.Pointer, reason waitReason, traceEv byte, traceskip int) {
   350  	if reason != waitReasonSleep {
   351  		checkTimeouts() // timeouts may expire while two goroutines keep the scheduler busy
   352  	}
   353  	mp := acquirem()
   354  	gp := mp.curg
   355  	status := readgstatus(gp)
   356  	if status != _Grunning && status != _Gscanrunning {
   357  		throw("gopark: bad g status")
   358  	}
   359  	mp.waitlock = lock
   360  	mp.waitunlockf = unlockf
   361  	gp.waitreason = reason
   362  	mp.waittraceev = traceEv
   363  	mp.waittraceskip = traceskip
   364  	releasem(mp)
   365  	// can't do anything that might move the G between Ms here.
   366  	mcall(park_m)
   367  }
   368  
   369  // Puts the current goroutine into a waiting state and unlocks the lock.
   370  // The goroutine can be made runnable again by calling goready(gp).
   371  func goparkunlock(lock *mutex, reason waitReason, traceEv byte, traceskip int) {
   372  	gopark(parkunlock_c, unsafe.Pointer(lock), reason, traceEv, traceskip)
   373  }
   374  
   375  func goready(gp *g, traceskip int) {
   376  	systemstack(func() {
   377  		ready(gp, traceskip, true)
   378  	})
   379  }
   380  
   381  //go:nosplit
   382  func acquireSudog() *sudog {
   383  	// Delicate dance: the semaphore implementation calls
   384  	// acquireSudog, acquireSudog calls new(sudog),
   385  	// new calls malloc, malloc can call the garbage collector,
   386  	// and the garbage collector calls the semaphore implementation
   387  	// in stopTheWorld.
   388  	// Break the cycle by doing acquirem/releasem around new(sudog).
   389  	// The acquirem/releasem increments m.locks during new(sudog),
   390  	// which keeps the garbage collector from being invoked.
   391  	mp := acquirem()
   392  	pp := mp.p.ptr()
   393  	if len(pp.sudogcache) == 0 {
   394  		lock(&sched.sudoglock)
   395  		// First, try to grab a batch from central cache.
   396  		for len(pp.sudogcache) < cap(pp.sudogcache)/2 && sched.sudogcache != nil {
   397  			s := sched.sudogcache
   398  			sched.sudogcache = s.next
   399  			s.next = nil
   400  			pp.sudogcache = append(pp.sudogcache, s)
   401  		}
   402  		unlock(&sched.sudoglock)
   403  		// If the central cache is empty, allocate a new one.
   404  		if len(pp.sudogcache) == 0 {
   405  			pp.sudogcache = append(pp.sudogcache, new(sudog))
   406  		}
   407  	}
   408  	n := len(pp.sudogcache)
   409  	s := pp.sudogcache[n-1]
   410  	pp.sudogcache[n-1] = nil
   411  	pp.sudogcache = pp.sudogcache[:n-1]
   412  	if s.elem != nil {
   413  		throw("acquireSudog: found s.elem != nil in cache")
   414  	}
   415  	releasem(mp)
   416  	return s
   417  }
   418  
   419  //go:nosplit
   420  func releaseSudog(s *sudog) {
   421  	if s.elem != nil {
   422  		throw("runtime: sudog with non-nil elem")
   423  	}
   424  	if s.isSelect {
   425  		throw("runtime: sudog with non-false isSelect")
   426  	}
   427  	if s.next != nil {
   428  		throw("runtime: sudog with non-nil next")
   429  	}
   430  	if s.prev != nil {
   431  		throw("runtime: sudog with non-nil prev")
   432  	}
   433  	if s.waitlink != nil {
   434  		throw("runtime: sudog with non-nil waitlink")
   435  	}
   436  	if s.c != nil {
   437  		throw("runtime: sudog with non-nil c")
   438  	}
   439  	gp := getg()
   440  	if gp.param != nil {
   441  		throw("runtime: releaseSudog with non-nil gp.param")
   442  	}
   443  	mp := acquirem() // avoid rescheduling to another P
   444  	pp := mp.p.ptr()
   445  	if len(pp.sudogcache) == cap(pp.sudogcache) {
   446  		// Transfer half of local cache to the central cache.
   447  		var first, last *sudog
   448  		for len(pp.sudogcache) > cap(pp.sudogcache)/2 {
   449  			n := len(pp.sudogcache)
   450  			p := pp.sudogcache[n-1]
   451  			pp.sudogcache[n-1] = nil
   452  			pp.sudogcache = pp.sudogcache[:n-1]
   453  			if first == nil {
   454  				first = p
   455  			} else {
   456  				last.next = p
   457  			}
   458  			last = p
   459  		}
   460  		lock(&sched.sudoglock)
   461  		last.next = sched.sudogcache
   462  		sched.sudogcache = first
   463  		unlock(&sched.sudoglock)
   464  	}
   465  	pp.sudogcache = append(pp.sudogcache, s)
   466  	releasem(mp)
   467  }
   468  
   469  // funcPC returns the entry PC of the function f.
   470  // It assumes that f is a func value. Otherwise the behavior is undefined.
   471  // CAREFUL: In programs with plugins, funcPC can return different values
   472  // for the same function (because there are actually multiple copies of
   473  // the same function in the address space). To be safe, don't use the
   474  // results of this function in any == expression. It is only safe to
   475  // use the result as an address at which to start executing code.
   476  //go:nosplit
   477  func funcPC(f interface{}) uintptr {
   478  	return *(*uintptr)(efaceOf(&f).data)
   479  }
   480  
   481  // called from assembly
   482  func badmcall(fn func(*g)) {
   483  	throw("runtime: mcall called on m->g0 stack")
   484  }
   485  
   486  func badmcall2(fn func(*g)) {
   487  	throw("runtime: mcall function returned")
   488  }
   489  
   490  func badreflectcall() {
   491  	panic(plainError("arg size to reflect.call more than 1GB"))
   492  }
   493  
   494  var badmorestackg0Msg = "fatal: morestack on g0\n"
   495  
   496  //go:nosplit
   497  //go:nowritebarrierrec
   498  func badmorestackg0() {
   499  	sp := stringStructOf(&badmorestackg0Msg)
   500  	write(2, sp.str, int32(sp.len))
   501  }
   502  
   503  var badmorestackgsignalMsg = "fatal: morestack on gsignal\n"
   504  
   505  //go:nosplit
   506  //go:nowritebarrierrec
   507  func badmorestackgsignal() {
   508  	sp := stringStructOf(&badmorestackgsignalMsg)
   509  	write(2, sp.str, int32(sp.len))
   510  }
   511  
   512  //go:nosplit
   513  func badctxt() {
   514  	throw("ctxt != 0")
   515  }
   516  
   517  func lockedOSThread() bool {
   518  	gp := getg()
   519  	return gp.lockedm != 0 && gp.m.lockedg != 0
   520  }
   521  
   522  var (
   523  	// allgs contains all Gs ever created (including dead Gs), and thus
   524  	// never shrinks.
   525  	//
   526  	// Access via the slice is protected by allglock or stop-the-world.
   527  	// Readers that cannot take the lock may (carefully!) use the atomic
   528  	// variables below.
   529  	allglock mutex
   530  	allgs    []*g
   531  
   532  	// allglen and allgptr are atomic variables that contain len(allgs) and
   533  	// &allgs[0] respectively. Proper ordering depends on totally-ordered
   534  	// loads and stores. Writes are protected by allglock.
   535  	//
   536  	// allgptr is updated before allglen. Readers should read allglen
   537  	// before allgptr to ensure that allglen is always <= len(allgptr). New
   538  	// Gs appended during the race can be missed. For a consistent view of
   539  	// all Gs, allglock must be held.
   540  	//
   541  	// allgptr copies should always be stored as a concrete type or
   542  	// unsafe.Pointer, not uintptr, to ensure that GC can still reach it
   543  	// even if it points to a stale array.
   544  	allglen uintptr
   545  	allgptr **g
   546  )
   547  
   548  func allgadd(gp *g) {
   549  	if readgstatus(gp) == _Gidle {
   550  		throw("allgadd: bad status Gidle")
   551  	}
   552  
   553  	lock(&allglock)
   554  	allgs = append(allgs, gp)
   555  	if &allgs[0] != allgptr {
   556  		atomicstorep(unsafe.Pointer(&allgptr), unsafe.Pointer(&allgs[0]))
   557  	}
   558  	atomic.Storeuintptr(&allglen, uintptr(len(allgs)))
   559  	unlock(&allglock)
   560  }
   561  
   562  // atomicAllG returns &allgs[0] and len(allgs) for use with atomicAllGIndex.
   563  func atomicAllG() (**g, uintptr) {
   564  	length := atomic.Loaduintptr(&allglen)
   565  	ptr := (**g)(atomic.Loadp(unsafe.Pointer(&allgptr)))
   566  	return ptr, length
   567  }
   568  
   569  // atomicAllGIndex returns ptr[i] with the allgptr returned from atomicAllG.
   570  func atomicAllGIndex(ptr **g, i uintptr) *g {
   571  	return *(**g)(add(unsafe.Pointer(ptr), i*sys.PtrSize))
   572  }
   573  
   574  // forEachG calls fn on every G from allgs.
   575  //
   576  // forEachG takes a lock to exclude concurrent addition of new Gs.
   577  func forEachG(fn func(gp *g)) {
   578  	lock(&allglock)
   579  	for _, gp := range allgs {
   580  		fn(gp)
   581  	}
   582  	unlock(&allglock)
   583  }
   584  
   585  // forEachGRace calls fn on every G from allgs.
   586  //
   587  // forEachGRace avoids locking, but does not exclude addition of new Gs during
   588  // execution, which may be missed.
   589  func forEachGRace(fn func(gp *g)) {
   590  	ptr, length := atomicAllG()
   591  	for i := uintptr(0); i < length; i++ {
   592  		gp := atomicAllGIndex(ptr, i)
   593  		fn(gp)
   594  	}
   595  	return
   596  }
   597  
   598  const (
   599  	// Number of goroutine ids to grab from sched.goidgen to local per-P cache at once.
   600  	// 16 seems to provide enough amortization, but other than that it's mostly arbitrary number.
   601  	_GoidCacheBatch = 16
   602  )
   603  
   604  // cpuinit extracts the environment variable GODEBUG from the environment on
   605  // Unix-like operating systems and calls internal/cpu.Initialize.
   606  func cpuinit() {
   607  	const prefix = "GODEBUG="
   608  	var env string
   609  
   610  	switch GOOS {
   611  	case "aix", "darwin", "ios", "dragonfly", "freebsd", "netbsd", "openbsd", "illumos", "solaris", "linux":
   612  		cpu.DebugOptions = true
   613  
   614  		// Similar to goenv_unix but extracts the environment value for
   615  		// GODEBUG directly.
   616  		// TODO(moehrmann): remove when general goenvs() can be called before cpuinit()
   617  		n := int32(0)
   618  		for argv_index(argv, argc+1+n) != nil {
   619  			n++
   620  		}
   621  
   622  		for i := int32(0); i < n; i++ {
   623  			p := argv_index(argv, argc+1+i)
   624  			s := *(*string)(unsafe.Pointer(&stringStruct{unsafe.Pointer(p), findnull(p)}))
   625  
   626  			if hasPrefix(s, prefix) {
   627  				env = gostring(p)[len(prefix):]
   628  				break
   629  			}
   630  		}
   631  	}
   632  
   633  	cpu.Initialize(env)
   634  
   635  	// Support cpu feature variables are used in code generated by the compiler
   636  	// to guard execution of instructions that can not be assumed to be always supported.
   637  	x86HasPOPCNT = cpu.X86.HasPOPCNT
   638  	x86HasSSE41 = cpu.X86.HasSSE41
   639  	x86HasFMA = cpu.X86.HasFMA
   640  
   641  	armHasVFPv4 = cpu.ARM.HasVFPv4
   642  
   643  	arm64HasATOMICS = cpu.ARM64.HasATOMICS
   644  }
   645  
   646  // The bootstrap sequence is:
   647  //
   648  //	call osinit
   649  //	call schedinit
   650  //	make & queue new G
   651  //	call runtime·mstart
   652  //
   653  // The new G calls runtime·main.
   654  func schedinit() {
   655  	lockInit(&sched.lock, lockRankSched)
   656  	lockInit(&sched.sysmonlock, lockRankSysmon)
   657  	lockInit(&sched.deferlock, lockRankDefer)
   658  	lockInit(&sched.sudoglock, lockRankSudog)
   659  	lockInit(&deadlock, lockRankDeadlock)
   660  	lockInit(&paniclk, lockRankPanic)
   661  	lockInit(&allglock, lockRankAllg)
   662  	lockInit(&allpLock, lockRankAllp)
   663  	lockInit(&reflectOffs.lock, lockRankReflectOffs)
   664  	lockInit(&finlock, lockRankFin)
   665  	lockInit(&trace.bufLock, lockRankTraceBuf)
   666  	lockInit(&trace.stringsLock, lockRankTraceStrings)
   667  	lockInit(&trace.lock, lockRankTrace)
   668  	lockInit(&cpuprof.lock, lockRankCpuprof)
   669  	lockInit(&trace.stackTab.lock, lockRankTraceStackTab)
   670  	// Enforce that this lock is always a leaf lock.
   671  	// All of this lock's critical sections should be
   672  	// extremely short.
   673  	lockInit(&memstats.heapStats.noPLock, lockRankLeafRank)
   674  
   675  	// raceinit must be the first call to race detector.
   676  	// In particular, it must be done before mallocinit below calls racemapshadow.
   677  	_g_ := getg()
   678  	if raceenabled {
   679  		_g_.racectx, raceprocctx0 = raceinit()
   680  	}
   681  
   682  	sched.maxmcount = 10000
   683  
   684  	// The world starts stopped.
   685  	worldStopped()
   686  
   687  	moduledataverify()
   688  	stackinit()
   689  	mallocinit()
   690  	fastrandinit() // must run before mcommoninit
   691  	mcommoninit(_g_.m, -1)
   692  	cpuinit()       // must run before alginit
   693  	alginit()       // maps must not be used before this call
   694  	modulesinit()   // provides activeModules
   695  	typelinksinit() // uses maps, activeModules
   696  	itabsinit()     // uses activeModules
   697  
   698  	sigsave(&_g_.m.sigmask)
   699  	initSigmask = _g_.m.sigmask
   700  
   701  	if offset := unsafe.Offsetof(sched.timeToRun); offset%8 != 0 {
   702  		println(offset)
   703  		throw("sched.timeToRun not aligned to 8 bytes")
   704  	}
   705  
   706  	goargs()
   707  	goenvs()
   708  	parsedebugvars()
   709  	gcinit()
   710  
   711  	lock(&sched.lock)
   712  	sched.lastpoll = uint64(nanotime())
   713  	procs := ncpu
   714  	if n, ok := atoi32(gogetenv("GOMAXPROCS")); ok && n > 0 {
   715  		procs = n
   716  	}
   717  	if procresize(procs) != nil {
   718  		throw("unknown runnable goroutine during bootstrap")
   719  	}
   720  	unlock(&sched.lock)
   721  
   722  	// World is effectively started now, as P's can run.
   723  	worldStarted()
   724  
   725  	// For cgocheck > 1, we turn on the write barrier at all times
   726  	// and check all pointer writes. We can't do this until after
   727  	// procresize because the write barrier needs a P.
   728  	if debug.cgocheck > 1 {
   729  		writeBarrier.cgo = true
   730  		writeBarrier.enabled = true
   731  		for _, p := range allp {
   732  			p.wbBuf.reset()
   733  		}
   734  	}
   735  
   736  	if buildVersion == "" {
   737  		// Condition should never trigger. This code just serves
   738  		// to ensure runtime·buildVersion is kept in the resulting binary.
   739  		buildVersion = "unknown"
   740  	}
   741  	if len(modinfo) == 1 {
   742  		// Condition should never trigger. This code just serves
   743  		// to ensure runtime·modinfo is kept in the resulting binary.
   744  		modinfo = ""
   745  	}
   746  }
   747  
   748  func dumpgstatus(gp *g) {
   749  	_g_ := getg()
   750  	print("runtime: gp: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n")
   751  	print("runtime:  g:  g=", _g_, ", goid=", _g_.goid, ",  g->atomicstatus=", readgstatus(_g_), "\n")
   752  }
   753  
   754  // sched.lock must be held.
   755  func checkmcount() {
   756  	assertLockHeld(&sched.lock)
   757  
   758  	if mcount() > sched.maxmcount {
   759  		print("runtime: program exceeds ", sched.maxmcount, "-thread limit\n")
   760  		throw("thread exhaustion")
   761  	}
   762  }
   763  
   764  // mReserveID returns the next ID to use for a new m. This new m is immediately
   765  // considered 'running' by checkdead.
   766  //
   767  // sched.lock must be held.
   768  func mReserveID() int64 {
   769  	assertLockHeld(&sched.lock)
   770  
   771  	if sched.mnext+1 < sched.mnext {
   772  		throw("runtime: thread ID overflow")
   773  	}
   774  	id := sched.mnext
   775  	sched.mnext++
   776  	checkmcount()
   777  	return id
   778  }
   779  
   780  // Pre-allocated ID may be passed as 'id', or omitted by passing -1.
   781  func mcommoninit(mp *m, id int64) {
   782  	_g_ := getg()
   783  
   784  	// g0 stack won't make sense for user (and is not necessary unwindable).
   785  	if _g_ != _g_.m.g0 {
   786  		callers(1, mp.createstack[:])
   787  	}
   788  
   789  	lock(&sched.lock)
   790  
   791  	if id >= 0 {
   792  		mp.id = id
   793  	} else {
   794  		mp.id = mReserveID()
   795  	}
   796  
   797  	mp.fastrand[0] = uint32(int64Hash(uint64(mp.id), fastrandseed))
   798  	mp.fastrand[1] = uint32(int64Hash(uint64(cputicks()), ^fastrandseed))
   799  	if mp.fastrand[0]|mp.fastrand[1] == 0 {
   800  		mp.fastrand[1] = 1
   801  	}
   802  
   803  	mpreinit(mp)
   804  	if mp.gsignal != nil {
   805  		mp.gsignal.stackguard1 = mp.gsignal.stack.lo + _StackGuard
   806  	}
   807  
   808  	// Add to allm so garbage collector doesn't free g->m
   809  	// when it is just in a register or thread-local storage.
   810  	mp.alllink = allm
   811  
   812  	// NumCgoCall() iterates over allm w/o schedlock,
   813  	// so we need to publish it safely.
   814  	atomicstorep(unsafe.Pointer(&allm), unsafe.Pointer(mp))
   815  	unlock(&sched.lock)
   816  
   817  	// Allocate memory to hold a cgo traceback if the cgo call crashes.
   818  	if iscgo || GOOS == "solaris" || GOOS == "illumos" || GOOS == "windows" {
   819  		mp.cgoCallers = new(cgoCallers)
   820  	}
   821  }
   822  
   823  var fastrandseed uintptr
   824  
   825  func fastrandinit() {
   826  	s := (*[unsafe.Sizeof(fastrandseed)]byte)(unsafe.Pointer(&fastrandseed))[:]
   827  	getRandomData(s)
   828  }
   829  
   830  // Mark gp ready to run.
   831  func ready(gp *g, traceskip int, next bool) {
   832  	if trace.enabled {
   833  		traceGoUnpark(gp, traceskip)
   834  	}
   835  
   836  	status := readgstatus(gp)
   837  
   838  	// Mark runnable.
   839  	_g_ := getg()
   840  	mp := acquirem() // disable preemption because it can be holding p in a local var
   841  	if status&^_Gscan != _Gwaiting {
   842  		dumpgstatus(gp)
   843  		throw("bad g->status in ready")
   844  	}
   845  
   846  	// status is Gwaiting or Gscanwaiting, make Grunnable and put on runq
   847  	casgstatus(gp, _Gwaiting, _Grunnable)
   848  	runqput(_g_.m.p.ptr(), gp, next)
   849  	wakep()
   850  	releasem(mp)
   851  }
   852  
   853  // freezeStopWait is a large value that freezetheworld sets
   854  // sched.stopwait to in order to request that all Gs permanently stop.
   855  const freezeStopWait = 0x7fffffff
   856  
   857  // freezing is set to non-zero if the runtime is trying to freeze the
   858  // world.
   859  var freezing uint32
   860  
   861  // Similar to stopTheWorld but best-effort and can be called several times.
   862  // There is no reverse operation, used during crashing.
   863  // This function must not lock any mutexes.
   864  func freezetheworld() {
   865  	atomic.Store(&freezing, 1)
   866  	// stopwait and preemption requests can be lost
   867  	// due to races with concurrently executing threads,
   868  	// so try several times
   869  	for i := 0; i < 5; i++ {
   870  		// this should tell the scheduler to not start any new goroutines
   871  		sched.stopwait = freezeStopWait
   872  		atomic.Store(&sched.gcwaiting, 1)
   873  		// this should stop running goroutines
   874  		if !preemptall() {
   875  			break // no running goroutines
   876  		}
   877  		usleep(1000)
   878  	}
   879  	// to be sure
   880  	usleep(1000)
   881  	preemptall()
   882  	usleep(1000)
   883  }
   884  
   885  // All reads and writes of g's status go through readgstatus, casgstatus
   886  // castogscanstatus, casfrom_Gscanstatus.
   887  //go:nosplit
   888  func readgstatus(gp *g) uint32 {
   889  	return atomic.Load(&gp.atomicstatus)
   890  }
   891  
   892  // The Gscanstatuses are acting like locks and this releases them.
   893  // If it proves to be a performance hit we should be able to make these
   894  // simple atomic stores but for now we are going to throw if
   895  // we see an inconsistent state.
   896  func casfrom_Gscanstatus(gp *g, oldval, newval uint32) {
   897  	success := false
   898  
   899  	// Check that transition is valid.
   900  	switch oldval {
   901  	default:
   902  		print("runtime: casfrom_Gscanstatus bad oldval gp=", gp, ", oldval=", hex(oldval), ", newval=", hex(newval), "\n")
   903  		dumpgstatus(gp)
   904  		throw("casfrom_Gscanstatus:top gp->status is not in scan state")
   905  	case _Gscanrunnable,
   906  		_Gscanwaiting,
   907  		_Gscanrunning,
   908  		_Gscansyscall,
   909  		_Gscanpreempted:
   910  		if newval == oldval&^_Gscan {
   911  			success = atomic.Cas(&gp.atomicstatus, oldval, newval)
   912  		}
   913  	}
   914  	if !success {
   915  		print("runtime: casfrom_Gscanstatus failed gp=", gp, ", oldval=", hex(oldval), ", newval=", hex(newval), "\n")
   916  		dumpgstatus(gp)
   917  		throw("casfrom_Gscanstatus: gp->status is not in scan state")
   918  	}
   919  	releaseLockRank(lockRankGscan)
   920  }
   921  
   922  // This will return false if the gp is not in the expected status and the cas fails.
   923  // This acts like a lock acquire while the casfromgstatus acts like a lock release.
   924  func castogscanstatus(gp *g, oldval, newval uint32) bool {
   925  	switch oldval {
   926  	case _Grunnable,
   927  		_Grunning,
   928  		_Gwaiting,
   929  		_Gsyscall:
   930  		if newval == oldval|_Gscan {
   931  			r := atomic.Cas(&gp.atomicstatus, oldval, newval)
   932  			if r {
   933  				acquireLockRank(lockRankGscan)
   934  			}
   935  			return r
   936  
   937  		}
   938  	}
   939  	print("runtime: castogscanstatus oldval=", hex(oldval), " newval=", hex(newval), "\n")
   940  	throw("castogscanstatus")
   941  	panic("not reached")
   942  }
   943  
   944  // If asked to move to or from a Gscanstatus this will throw. Use the castogscanstatus
   945  // and casfrom_Gscanstatus instead.
   946  // casgstatus will loop if the g->atomicstatus is in a Gscan status until the routine that
   947  // put it in the Gscan state is finished.
   948  //go:nosplit
   949  func casgstatus(gp *g, oldval, newval uint32) {
   950  	if (oldval&_Gscan != 0) || (newval&_Gscan != 0) || oldval == newval {
   951  		systemstack(func() {
   952  			print("runtime: casgstatus: oldval=", hex(oldval), " newval=", hex(newval), "\n")
   953  			throw("casgstatus: bad incoming values")
   954  		})
   955  	}
   956  
   957  	acquireLockRank(lockRankGscan)
   958  	releaseLockRank(lockRankGscan)
   959  
   960  	// See https://golang.org/cl/21503 for justification of the yield delay.
   961  	const yieldDelay = 5 * 1000
   962  	var nextYield int64
   963  
   964  	// loop if gp->atomicstatus is in a scan state giving
   965  	// GC time to finish and change the state to oldval.
   966  	for i := 0; !atomic.Cas(&gp.atomicstatus, oldval, newval); i++ {
   967  		if oldval == _Gwaiting && gp.atomicstatus == _Grunnable {
   968  			throw("casgstatus: waiting for Gwaiting but is Grunnable")
   969  		}
   970  		if i == 0 {
   971  			nextYield = nanotime() + yieldDelay
   972  		}
   973  		if nanotime() < nextYield {
   974  			for x := 0; x < 10 && gp.atomicstatus != oldval; x++ {
   975  				procyield(1)
   976  			}
   977  		} else {
   978  			osyield()
   979  			nextYield = nanotime() + yieldDelay/2
   980  		}
   981  	}
   982  
   983  	// Handle tracking for scheduling latencies.
   984  	if oldval == _Grunning {
   985  		// Track every 8th time a goroutine transitions out of running.
   986  		if gp.trackingSeq%gTrackingPeriod == 0 {
   987  			gp.tracking = true
   988  		}
   989  		gp.trackingSeq++
   990  	}
   991  	if gp.tracking {
   992  		now := nanotime()
   993  		if oldval == _Grunnable {
   994  			// We transitioned out of runnable, so measure how much
   995  			// time we spent in this state and add it to
   996  			// runnableTime.
   997  			gp.runnableTime += now - gp.runnableStamp
   998  			gp.runnableStamp = 0
   999  		}
  1000  		if newval == _Grunnable {
  1001  			// We just transitioned into runnable, so record what
  1002  			// time that happened.
  1003  			gp.runnableStamp = now
  1004  		} else if newval == _Grunning {
  1005  			// We're transitioning into running, so turn off
  1006  			// tracking and record how much time we spent in
  1007  			// runnable.
  1008  			gp.tracking = false
  1009  			sched.timeToRun.record(gp.runnableTime)
  1010  			gp.runnableTime = 0
  1011  		}
  1012  	}
  1013  }
  1014  
  1015  // casgstatus(gp, oldstatus, Gcopystack), assuming oldstatus is Gwaiting or Grunnable.
  1016  // Returns old status. Cannot call casgstatus directly, because we are racing with an
  1017  // async wakeup that might come in from netpoll. If we see Gwaiting from the readgstatus,
  1018  // it might have become Grunnable by the time we get to the cas. If we called casgstatus,
  1019  // it would loop waiting for the status to go back to Gwaiting, which it never will.
  1020  //go:nosplit
  1021  func casgcopystack(gp *g) uint32 {
  1022  	for {
  1023  		oldstatus := readgstatus(gp) &^ _Gscan
  1024  		if oldstatus != _Gwaiting && oldstatus != _Grunnable {
  1025  			throw("copystack: bad status, not Gwaiting or Grunnable")
  1026  		}
  1027  		if atomic.Cas(&gp.atomicstatus, oldstatus, _Gcopystack) {
  1028  			return oldstatus
  1029  		}
  1030  	}
  1031  }
  1032  
  1033  // casGToPreemptScan transitions gp from _Grunning to _Gscan|_Gpreempted.
  1034  //
  1035  // TODO(austin): This is the only status operation that both changes
  1036  // the status and locks the _Gscan bit. Rethink this.
  1037  func casGToPreemptScan(gp *g, old, new uint32) {
  1038  	if old != _Grunning || new != _Gscan|_Gpreempted {
  1039  		throw("bad g transition")
  1040  	}
  1041  	acquireLockRank(lockRankGscan)
  1042  	for !atomic.Cas(&gp.atomicstatus, _Grunning, _Gscan|_Gpreempted) {
  1043  	}
  1044  }
  1045  
  1046  // casGFromPreempted attempts to transition gp from _Gpreempted to
  1047  // _Gwaiting. If successful, the caller is responsible for
  1048  // re-scheduling gp.
  1049  func casGFromPreempted(gp *g, old, new uint32) bool {
  1050  	if old != _Gpreempted || new != _Gwaiting {
  1051  		throw("bad g transition")
  1052  	}
  1053  	return atomic.Cas(&gp.atomicstatus, _Gpreempted, _Gwaiting)
  1054  }
  1055  
  1056  // stopTheWorld stops all P's from executing goroutines, interrupting
  1057  // all goroutines at GC safe points and records reason as the reason
  1058  // for the stop. On return, only the current goroutine's P is running.
  1059  // stopTheWorld must not be called from a system stack and the caller
  1060  // must not hold worldsema. The caller must call startTheWorld when
  1061  // other P's should resume execution.
  1062  //
  1063  // stopTheWorld is safe for multiple goroutines to call at the
  1064  // same time. Each will execute its own stop, and the stops will
  1065  // be serialized.
  1066  //
  1067  // This is also used by routines that do stack dumps. If the system is
  1068  // in panic or being exited, this may not reliably stop all
  1069  // goroutines.
  1070  func stopTheWorld(reason string) {
  1071  	semacquire(&worldsema)
  1072  	gp := getg()
  1073  	gp.m.preemptoff = reason
  1074  	systemstack(func() {
  1075  		// Mark the goroutine which called stopTheWorld preemptible so its
  1076  		// stack may be scanned.
  1077  		// This lets a mark worker scan us while we try to stop the world
  1078  		// since otherwise we could get in a mutual preemption deadlock.
  1079  		// We must not modify anything on the G stack because a stack shrink
  1080  		// may occur. A stack shrink is otherwise OK though because in order
  1081  		// to return from this function (and to leave the system stack) we
  1082  		// must have preempted all goroutines, including any attempting
  1083  		// to scan our stack, in which case, any stack shrinking will
  1084  		// have already completed by the time we exit.
  1085  		casgstatus(gp, _Grunning, _Gwaiting)
  1086  		stopTheWorldWithSema()
  1087  		casgstatus(gp, _Gwaiting, _Grunning)
  1088  	})
  1089  }
  1090  
  1091  // startTheWorld undoes the effects of stopTheWorld.
  1092  func startTheWorld() {
  1093  	systemstack(func() { startTheWorldWithSema(false) })
  1094  
  1095  	// worldsema must be held over startTheWorldWithSema to ensure
  1096  	// gomaxprocs cannot change while worldsema is held.
  1097  	//
  1098  	// Release worldsema with direct handoff to the next waiter, but
  1099  	// acquirem so that semrelease1 doesn't try to yield our time.
  1100  	//
  1101  	// Otherwise if e.g. ReadMemStats is being called in a loop,
  1102  	// it might stomp on other attempts to stop the world, such as
  1103  	// for starting or ending GC. The operation this blocks is
  1104  	// so heavy-weight that we should just try to be as fair as
  1105  	// possible here.
  1106  	//
  1107  	// We don't want to just allow us to get preempted between now
  1108  	// and releasing the semaphore because then we keep everyone
  1109  	// (including, for example, GCs) waiting longer.
  1110  	mp := acquirem()
  1111  	mp.preemptoff = ""
  1112  	semrelease1(&worldsema, true, 0)
  1113  	releasem(mp)
  1114  }
  1115  
  1116  // stopTheWorldGC has the same effect as stopTheWorld, but blocks
  1117  // until the GC is not running. It also blocks a GC from starting
  1118  // until startTheWorldGC is called.
  1119  func stopTheWorldGC(reason string) {
  1120  	semacquire(&gcsema)
  1121  	stopTheWorld(reason)
  1122  }
  1123  
  1124  // startTheWorldGC undoes the effects of stopTheWorldGC.
  1125  func startTheWorldGC() {
  1126  	startTheWorld()
  1127  	semrelease(&gcsema)
  1128  }
  1129  
  1130  // Holding worldsema grants an M the right to try to stop the world.
  1131  var worldsema uint32 = 1
  1132  
  1133  // Holding gcsema grants the M the right to block a GC, and blocks
  1134  // until the current GC is done. In particular, it prevents gomaxprocs
  1135  // from changing concurrently.
  1136  //
  1137  // TODO(mknyszek): Once gomaxprocs and the execution tracer can handle
  1138  // being changed/enabled during a GC, remove this.
  1139  var gcsema uint32 = 1
  1140  
  1141  // stopTheWorldWithSema is the core implementation of stopTheWorld.
  1142  // The caller is responsible for acquiring worldsema and disabling
  1143  // preemption first and then should stopTheWorldWithSema on the system
  1144  // stack:
  1145  //
  1146  //	semacquire(&worldsema, 0)
  1147  //	m.preemptoff = "reason"
  1148  //	systemstack(stopTheWorldWithSema)
  1149  //
  1150  // When finished, the caller must either call startTheWorld or undo
  1151  // these three operations separately:
  1152  //
  1153  //	m.preemptoff = ""
  1154  //	systemstack(startTheWorldWithSema)
  1155  //	semrelease(&worldsema)
  1156  //
  1157  // It is allowed to acquire worldsema once and then execute multiple
  1158  // startTheWorldWithSema/stopTheWorldWithSema pairs.
  1159  // Other P's are able to execute between successive calls to
  1160  // startTheWorldWithSema and stopTheWorldWithSema.
  1161  // Holding worldsema causes any other goroutines invoking
  1162  // stopTheWorld to block.
  1163  func stopTheWorldWithSema() {
  1164  	_g_ := getg()
  1165  
  1166  	// If we hold a lock, then we won't be able to stop another M
  1167  	// that is blocked trying to acquire the lock.
  1168  	if _g_.m.locks > 0 {
  1169  		throw("stopTheWorld: holding locks")
  1170  	}
  1171  
  1172  	lock(&sched.lock)
  1173  	sched.stopwait = gomaxprocs
  1174  	atomic.Store(&sched.gcwaiting, 1)
  1175  	preemptall()
  1176  	// stop current P
  1177  	_g_.m.p.ptr().status = _Pgcstop // Pgcstop is only diagnostic.
  1178  	sched.stopwait--
  1179  	// try to retake all P's in Psyscall status
  1180  	for _, p := range allp {
  1181  		s := p.status
  1182  		if s == _Psyscall && atomic.Cas(&p.status, s, _Pgcstop) {
  1183  			if trace.enabled {
  1184  				traceGoSysBlock(p)
  1185  				traceProcStop(p)
  1186  			}
  1187  			p.syscalltick++
  1188  			sched.stopwait--
  1189  		}
  1190  	}
  1191  	// stop idle P's
  1192  	for {
  1193  		p := pidleget()
  1194  		if p == nil {
  1195  			break
  1196  		}
  1197  		p.status = _Pgcstop
  1198  		sched.stopwait--
  1199  	}
  1200  	wait := sched.stopwait > 0
  1201  	unlock(&sched.lock)
  1202  
  1203  	// wait for remaining P's to stop voluntarily
  1204  	if wait {
  1205  		for {
  1206  			// wait for 100us, then try to re-preempt in case of any races
  1207  			if notetsleep(&sched.stopnote, 100*1000) {
  1208  				noteclear(&sched.stopnote)
  1209  				break
  1210  			}
  1211  			preemptall()
  1212  		}
  1213  	}
  1214  
  1215  	// sanity checks
  1216  	bad := ""
  1217  	if sched.stopwait != 0 {
  1218  		bad = "stopTheWorld: not stopped (stopwait != 0)"
  1219  	} else {
  1220  		for _, p := range allp {
  1221  			if p.status != _Pgcstop {
  1222  				bad = "stopTheWorld: not stopped (status != _Pgcstop)"
  1223  			}
  1224  		}
  1225  	}
  1226  	if atomic.Load(&freezing) != 0 {
  1227  		// Some other thread is panicking. This can cause the
  1228  		// sanity checks above to fail if the panic happens in
  1229  		// the signal handler on a stopped thread. Either way,
  1230  		// we should halt this thread.
  1231  		lock(&deadlock)
  1232  		lock(&deadlock)
  1233  	}
  1234  	if bad != "" {
  1235  		throw(bad)
  1236  	}
  1237  
  1238  	worldStopped()
  1239  }
  1240  
  1241  func startTheWorldWithSema(emitTraceEvent bool) int64 {
  1242  	assertWorldStopped()
  1243  
  1244  	mp := acquirem() // disable preemption because it can be holding p in a local var
  1245  	if netpollinited() {
  1246  		list := netpoll(0) // non-blocking
  1247  		injectglist(&list)
  1248  	}
  1249  	lock(&sched.lock)
  1250  
  1251  	procs := gomaxprocs
  1252  	if newprocs != 0 {
  1253  		procs = newprocs
  1254  		newprocs = 0
  1255  	}
  1256  	p1 := procresize(procs)
  1257  	sched.gcwaiting = 0
  1258  	if sched.sysmonwait != 0 {
  1259  		sched.sysmonwait = 0
  1260  		notewakeup(&sched.sysmonnote)
  1261  	}
  1262  	unlock(&sched.lock)
  1263  
  1264  	worldStarted()
  1265  
  1266  	for p1 != nil {
  1267  		p := p1
  1268  		p1 = p1.link.ptr()
  1269  		if p.m != 0 {
  1270  			mp := p.m.ptr()
  1271  			p.m = 0
  1272  			if mp.nextp != 0 {
  1273  				throw("startTheWorld: inconsistent mp->nextp")
  1274  			}
  1275  			mp.nextp.set(p)
  1276  			notewakeup(&mp.park)
  1277  		} else {
  1278  			// Start M to run P.  Do not start another M below.
  1279  			newm(nil, p, -1)
  1280  		}
  1281  	}
  1282  
  1283  	// Capture start-the-world time before doing clean-up tasks.
  1284  	startTime := nanotime()
  1285  	if emitTraceEvent {
  1286  		traceGCSTWDone()
  1287  	}
  1288  
  1289  	// Wakeup an additional proc in case we have excessive runnable goroutines
  1290  	// in local queues or in the global queue. If we don't, the proc will park itself.
  1291  	// If we have lots of excessive work, resetspinning will unpark additional procs as necessary.
  1292  	wakep()
  1293  
  1294  	releasem(mp)
  1295  
  1296  	return startTime
  1297  }
  1298  
  1299  // usesLibcall indicates whether this runtime performs system calls
  1300  // via libcall.
  1301  func usesLibcall() bool {
  1302  	switch GOOS {
  1303  	case "aix", "darwin", "illumos", "ios", "solaris", "windows":
  1304  		return true
  1305  	case "openbsd":
  1306  		return GOARCH == "386" || GOARCH == "amd64" || GOARCH == "arm" || GOARCH == "arm64"
  1307  	}
  1308  	return false
  1309  }
  1310  
  1311  // mStackIsSystemAllocated indicates whether this runtime starts on a
  1312  // system-allocated stack.
  1313  func mStackIsSystemAllocated() bool {
  1314  	switch GOOS {
  1315  	case "aix", "darwin", "plan9", "illumos", "ios", "solaris", "windows":
  1316  		return true
  1317  	case "openbsd":
  1318  		switch GOARCH {
  1319  		case "386", "amd64", "arm", "arm64":
  1320  			return true
  1321  		}
  1322  	}
  1323  	return false
  1324  }
  1325  
  1326  // mstart is the entry-point for new Ms.
  1327  // It is written in assembly, uses ABI0, is marked TOPFRAME, and calls mstart0.
  1328  func mstart()
  1329  
  1330  // mstart0 is the Go entry-point for new Ms.
  1331  // This must not split the stack because we may not even have stack
  1332  // bounds set up yet.
  1333  //
  1334  // May run during STW (because it doesn't have a P yet), so write
  1335  // barriers are not allowed.
  1336  //
  1337  //go:nosplit
  1338  //go:nowritebarrierrec
  1339  func mstart0() {
  1340  	_g_ := getg()
  1341  
  1342  	osStack := _g_.stack.lo == 0
  1343  	if osStack {
  1344  		// Initialize stack bounds from system stack.
  1345  		// Cgo may have left stack size in stack.hi.
  1346  		// minit may update the stack bounds.
  1347  		//
  1348  		// Note: these bounds may not be very accurate.
  1349  		// We set hi to &size, but there are things above
  1350  		// it. The 1024 is supposed to compensate this,
  1351  		// but is somewhat arbitrary.
  1352  		size := _g_.stack.hi
  1353  		if size == 0 {
  1354  			size = 8192 * sys.StackGuardMultiplier
  1355  		}
  1356  		_g_.stack.hi = uintptr(noescape(unsafe.Pointer(&size)))
  1357  		_g_.stack.lo = _g_.stack.hi - size + 1024
  1358  	}
  1359  	// Initialize stack guard so that we can start calling regular
  1360  	// Go code.
  1361  	_g_.stackguard0 = _g_.stack.lo + _StackGuard
  1362  	// This is the g0, so we can also call go:systemstack
  1363  	// functions, which check stackguard1.
  1364  	_g_.stackguard1 = _g_.stackguard0
  1365  	mstart1()
  1366  
  1367  	// Exit this thread.
  1368  	if mStackIsSystemAllocated() {
  1369  		// Windows, Solaris, illumos, Darwin, AIX and Plan 9 always system-allocate
  1370  		// the stack, but put it in _g_.stack before mstart,
  1371  		// so the logic above hasn't set osStack yet.
  1372  		osStack = true
  1373  	}
  1374  	mexit(osStack)
  1375  }
  1376  
  1377  // The go:noinline is to guarantee the getcallerpc/getcallersp below are safe,
  1378  // so that we can set up g0.sched to return to the call of mstart1 above.
  1379  //go:noinline
  1380  func mstart1() {
  1381  	_g_ := getg()
  1382  
  1383  	if _g_ != _g_.m.g0 {
  1384  		throw("bad runtime·mstart")
  1385  	}
  1386  
  1387  	// Set up m.g0.sched as a label returning to just
  1388  	// after the mstart1 call in mstart0 above, for use by goexit0 and mcall.
  1389  	// We're never coming back to mstart1 after we call schedule,
  1390  	// so other calls can reuse the current frame.
  1391  	// And goexit0 does a gogo that needs to return from mstart1
  1392  	// and let mstart0 exit the thread.
  1393  	_g_.sched.g = guintptr(unsafe.Pointer(_g_))
  1394  	_g_.sched.pc = getcallerpc()
  1395  	_g_.sched.sp = getcallersp()
  1396  
  1397  	asminit()
  1398  	minit()
  1399  
  1400  	// Install signal handlers; after minit so that minit can
  1401  	// prepare the thread to be able to handle the signals.
  1402  	if _g_.m == &m0 {
  1403  		mstartm0()
  1404  	}
  1405  
  1406  	if fn := _g_.m.mstartfn; fn != nil {
  1407  		fn()
  1408  	}
  1409  
  1410  	if _g_.m != &m0 {
  1411  		acquirep(_g_.m.nextp.ptr())
  1412  		_g_.m.nextp = 0
  1413  	}
  1414  	schedule()
  1415  }
  1416  
  1417  // mstartm0 implements part of mstart1 that only runs on the m0.
  1418  //
  1419  // Write barriers are allowed here because we know the GC can't be
  1420  // running yet, so they'll be no-ops.
  1421  //
  1422  //go:yeswritebarrierrec
  1423  func mstartm0() {
  1424  	// Create an extra M for callbacks on threads not created by Go.
  1425  	// An extra M is also needed on Windows for callbacks created by
  1426  	// syscall.NewCallback. See issue #6751 for details.
  1427  	if (iscgo || GOOS == "windows") && !cgoHasExtraM {
  1428  		cgoHasExtraM = true
  1429  		newextram()
  1430  	}
  1431  	initsig(false)
  1432  }
  1433  
  1434  // mPark causes a thread to park itself - temporarily waking for
  1435  // fixups but otherwise waiting to be fully woken. This is the
  1436  // only way that m's should park themselves.
  1437  //go:nosplit
  1438  func mPark() {
  1439  	g := getg()
  1440  	for {
  1441  		notesleep(&g.m.park)
  1442  		// Note, because of signal handling by this parked m,
  1443  		// a preemptive mDoFixup() may actually occur via
  1444  		// mDoFixupAndOSYield(). (See golang.org/issue/44193)
  1445  		noteclear(&g.m.park)
  1446  		if !mDoFixup() {
  1447  			return
  1448  		}
  1449  	}
  1450  }
  1451  
  1452  // mexit tears down and exits the current thread.
  1453  //
  1454  // Don't call this directly to exit the thread, since it must run at
  1455  // the top of the thread stack. Instead, use gogo(&_g_.m.g0.sched) to
  1456  // unwind the stack to the point that exits the thread.
  1457  //
  1458  // It is entered with m.p != nil, so write barriers are allowed. It
  1459  // will release the P before exiting.
  1460  //
  1461  //go:yeswritebarrierrec
  1462  func mexit(osStack bool) {
  1463  	g := getg()
  1464  	m := g.m
  1465  
  1466  	if m == &m0 {
  1467  		// This is the main thread. Just wedge it.
  1468  		//
  1469  		// On Linux, exiting the main thread puts the process
  1470  		// into a non-waitable zombie state. On Plan 9,
  1471  		// exiting the main thread unblocks wait even though
  1472  		// other threads are still running. On Solaris we can
  1473  		// neither exitThread nor return from mstart. Other
  1474  		// bad things probably happen on other platforms.
  1475  		//
  1476  		// We could try to clean up this M more before wedging
  1477  		// it, but that complicates signal handling.
  1478  		handoffp(releasep())
  1479  		lock(&sched.lock)
  1480  		sched.nmfreed++
  1481  		checkdead()
  1482  		unlock(&sched.lock)
  1483  		mPark()
  1484  		throw("locked m0 woke up")
  1485  	}
  1486  
  1487  	sigblock(true)
  1488  	unminit()
  1489  
  1490  	// Free the gsignal stack.
  1491  	if m.gsignal != nil {
  1492  		stackfree(m.gsignal.stack)
  1493  		// On some platforms, when calling into VDSO (e.g. nanotime)
  1494  		// we store our g on the gsignal stack, if there is one.
  1495  		// Now the stack is freed, unlink it from the m, so we
  1496  		// won't write to it when calling VDSO code.
  1497  		m.gsignal = nil
  1498  	}
  1499  
  1500  	// Remove m from allm.
  1501  	lock(&sched.lock)
  1502  	for pprev := &allm; *pprev != nil; pprev = &(*pprev).alllink {
  1503  		if *pprev == m {
  1504  			*pprev = m.alllink
  1505  			goto found
  1506  		}
  1507  	}
  1508  	throw("m not found in allm")
  1509  found:
  1510  	if !osStack {
  1511  		// Delay reaping m until it's done with the stack.
  1512  		//
  1513  		// If this is using an OS stack, the OS will free it
  1514  		// so there's no need for reaping.
  1515  		atomic.Store(&m.freeWait, 1)
  1516  		// Put m on the free list, though it will not be reaped until
  1517  		// freeWait is 0. Note that the free list must not be linked
  1518  		// through alllink because some functions walk allm without
  1519  		// locking, so may be using alllink.
  1520  		m.freelink = sched.freem
  1521  		sched.freem = m
  1522  	}
  1523  	unlock(&sched.lock)
  1524  
  1525  	atomic.Xadd64(&ncgocall, int64(m.ncgocall))
  1526  
  1527  	// Release the P.
  1528  	handoffp(releasep())
  1529  	// After this point we must not have write barriers.
  1530  
  1531  	// Invoke the deadlock detector. This must happen after
  1532  	// handoffp because it may have started a new M to take our
  1533  	// P's work.
  1534  	lock(&sched.lock)
  1535  	sched.nmfreed++
  1536  	checkdead()
  1537  	unlock(&sched.lock)
  1538  
  1539  	if GOOS == "darwin" || GOOS == "ios" {
  1540  		// Make sure pendingPreemptSignals is correct when an M exits.
  1541  		// For #41702.
  1542  		if atomic.Load(&m.signalPending) != 0 {
  1543  			atomic.Xadd(&pendingPreemptSignals, -1)
  1544  		}
  1545  	}
  1546  
  1547  	// Destroy all allocated resources. After this is called, we may no
  1548  	// longer take any locks.
  1549  	mdestroy(m)
  1550  
  1551  	if osStack {
  1552  		// Return from mstart and let the system thread
  1553  		// library free the g0 stack and terminate the thread.
  1554  		return
  1555  	}
  1556  
  1557  	// mstart is the thread's entry point, so there's nothing to
  1558  	// return to. Exit the thread directly. exitThread will clear
  1559  	// m.freeWait when it's done with the stack and the m can be
  1560  	// reaped.
  1561  	exitThread(&m.freeWait)
  1562  }
  1563  
  1564  // forEachP calls fn(p) for every P p when p reaches a GC safe point.
  1565  // If a P is currently executing code, this will bring the P to a GC
  1566  // safe point and execute fn on that P. If the P is not executing code
  1567  // (it is idle or in a syscall), this will call fn(p) directly while
  1568  // preventing the P from exiting its state. This does not ensure that
  1569  // fn will run on every CPU executing Go code, but it acts as a global
  1570  // memory barrier. GC uses this as a "ragged barrier."
  1571  //
  1572  // The caller must hold worldsema.
  1573  //
  1574  //go:systemstack
  1575  func forEachP(fn func(*p)) {
  1576  	mp := acquirem()
  1577  	_p_ := getg().m.p.ptr()
  1578  
  1579  	lock(&sched.lock)
  1580  	if sched.safePointWait != 0 {
  1581  		throw("forEachP: sched.safePointWait != 0")
  1582  	}
  1583  	sched.safePointWait = gomaxprocs - 1
  1584  	sched.safePointFn = fn
  1585  
  1586  	// Ask all Ps to run the safe point function.
  1587  	for _, p := range allp {
  1588  		if p != _p_ {
  1589  			atomic.Store(&p.runSafePointFn, 1)
  1590  		}
  1591  	}
  1592  	preemptall()
  1593  
  1594  	// Any P entering _Pidle or _Psyscall from now on will observe
  1595  	// p.runSafePointFn == 1 and will call runSafePointFn when
  1596  	// changing its status to _Pidle/_Psyscall.
  1597  
  1598  	// Run safe point function for all idle Ps. sched.pidle will
  1599  	// not change because we hold sched.lock.
  1600  	for p := sched.pidle.ptr(); p != nil; p = p.link.ptr() {
  1601  		if atomic.Cas(&p.runSafePointFn, 1, 0) {
  1602  			fn(p)
  1603  			sched.safePointWait--
  1604  		}
  1605  	}
  1606  
  1607  	wait := sched.safePointWait > 0
  1608  	unlock(&sched.lock)
  1609  
  1610  	// Run fn for the current P.
  1611  	fn(_p_)
  1612  
  1613  	// Force Ps currently in _Psyscall into _Pidle and hand them
  1614  	// off to induce safe point function execution.
  1615  	for _, p := range allp {
  1616  		s := p.status
  1617  		if s == _Psyscall && p.runSafePointFn == 1 && atomic.Cas(&p.status, s, _Pidle) {
  1618  			if trace.enabled {
  1619  				traceGoSysBlock(p)
  1620  				traceProcStop(p)
  1621  			}
  1622  			p.syscalltick++
  1623  			handoffp(p)
  1624  		}
  1625  	}
  1626  
  1627  	// Wait for remaining Ps to run fn.
  1628  	if wait {
  1629  		for {
  1630  			// Wait for 100us, then try to re-preempt in
  1631  			// case of any races.
  1632  			//
  1633  			// Requires system stack.
  1634  			if notetsleep(&sched.safePointNote, 100*1000) {
  1635  				noteclear(&sched.safePointNote)
  1636  				break
  1637  			}
  1638  			preemptall()
  1639  		}
  1640  	}
  1641  	if sched.safePointWait != 0 {
  1642  		throw("forEachP: not done")
  1643  	}
  1644  	for _, p := range allp {
  1645  		if p.runSafePointFn != 0 {
  1646  			throw("forEachP: P did not run fn")
  1647  		}
  1648  	}
  1649  
  1650  	lock(&sched.lock)
  1651  	sched.safePointFn = nil
  1652  	unlock(&sched.lock)
  1653  	releasem(mp)
  1654  }
  1655  
  1656  // syscall_runtime_doAllThreadsSyscall serializes Go execution and
  1657  // executes a specified fn() call on all m's.
  1658  //
  1659  // The boolean argument to fn() indicates whether the function's
  1660  // return value will be consulted or not. That is, fn(true) should
  1661  // return true if fn() succeeds, and fn(true) should return false if
  1662  // it failed. When fn(false) is called, its return status will be
  1663  // ignored.
  1664  //
  1665  // syscall_runtime_doAllThreadsSyscall first invokes fn(true) on a
  1666  // single, coordinating, m, and only if it returns true does it go on
  1667  // to invoke fn(false) on all of the other m's known to the process.
  1668  //
  1669  //go:linkname syscall_runtime_doAllThreadsSyscall syscall.runtime_doAllThreadsSyscall
  1670  func syscall_runtime_doAllThreadsSyscall(fn func(bool) bool) {
  1671  	if iscgo {
  1672  		panic("doAllThreadsSyscall not supported with cgo enabled")
  1673  	}
  1674  	if fn == nil {
  1675  		return
  1676  	}
  1677  	for atomic.Load(&sched.sysmonStarting) != 0 {
  1678  		osyield()
  1679  	}
  1680  
  1681  	// We don't want this thread to handle signals for the
  1682  	// duration of this critical section. The underlying issue
  1683  	// being that this locked coordinating m is the one monitoring
  1684  	// for fn() execution by all the other m's of the runtime,
  1685  	// while no regular go code execution is permitted (the world
  1686  	// is stopped). If this present m were to get distracted to
  1687  	// run signal handling code, and find itself waiting for a
  1688  	// second thread to execute go code before being able to
  1689  	// return from that signal handling, a deadlock will result.
  1690  	// (See golang.org/issue/44193.)
  1691  	lockOSThread()
  1692  	var sigmask sigset
  1693  	sigsave(&sigmask)
  1694  	sigblock(false)
  1695  
  1696  	stopTheWorldGC("doAllThreadsSyscall")
  1697  	if atomic.Load(&newmHandoff.haveTemplateThread) != 0 {
  1698  		// Ensure that there are no in-flight thread
  1699  		// creations: don't want to race with allm.
  1700  		lock(&newmHandoff.lock)
  1701  		for !newmHandoff.waiting {
  1702  			unlock(&newmHandoff.lock)
  1703  			osyield()
  1704  			lock(&newmHandoff.lock)
  1705  		}
  1706  		unlock(&newmHandoff.lock)
  1707  	}
  1708  	if netpollinited() {
  1709  		netpollBreak()
  1710  	}
  1711  	sigRecvPrepareForFixup()
  1712  	_g_ := getg()
  1713  	if raceenabled {
  1714  		// For m's running without racectx, we loan out the
  1715  		// racectx of this call.
  1716  		lock(&mFixupRace.lock)
  1717  		mFixupRace.ctx = _g_.racectx
  1718  		unlock(&mFixupRace.lock)
  1719  	}
  1720  	if ok := fn(true); ok {
  1721  		tid := _g_.m.procid
  1722  		for mp := allm; mp != nil; mp = mp.alllink {
  1723  			if mp.procid == tid {
  1724  				// This m has already completed fn()
  1725  				// call.
  1726  				continue
  1727  			}
  1728  			// Be wary of mp's without procid values if
  1729  			// they are known not to park. If they are
  1730  			// marked as parking with a zero procid, then
  1731  			// they will be racing with this code to be
  1732  			// allocated a procid and we will annotate
  1733  			// them with the need to execute the fn when
  1734  			// they acquire a procid to run it.
  1735  			if mp.procid == 0 && !mp.doesPark {
  1736  				// Reaching here, we are either
  1737  				// running Windows, or cgo linked
  1738  				// code. Neither of which are
  1739  				// currently supported by this API.
  1740  				throw("unsupported runtime environment")
  1741  			}
  1742  			// stopTheWorldGC() doesn't guarantee stopping
  1743  			// all the threads, so we lock here to avoid
  1744  			// the possibility of racing with mp.
  1745  			lock(&mp.mFixup.lock)
  1746  			mp.mFixup.fn = fn
  1747  			atomic.Store(&mp.mFixup.used, 1)
  1748  			if mp.doesPark {
  1749  				// For non-service threads this will
  1750  				// cause the wakeup to be short lived
  1751  				// (once the mutex is unlocked). The
  1752  				// next real wakeup will occur after
  1753  				// startTheWorldGC() is called.
  1754  				notewakeup(&mp.park)
  1755  			}
  1756  			unlock(&mp.mFixup.lock)
  1757  		}
  1758  		for {
  1759  			done := true
  1760  			for mp := allm; done && mp != nil; mp = mp.alllink {
  1761  				if mp.procid == tid {
  1762  					continue
  1763  				}
  1764  				done = atomic.Load(&mp.mFixup.used) == 0
  1765  			}
  1766  			if done {
  1767  				break
  1768  			}
  1769  			// if needed force sysmon and/or newmHandoff to wakeup.
  1770  			lock(&sched.lock)
  1771  			if atomic.Load(&sched.sysmonwait) != 0 {
  1772  				atomic.Store(&sched.sysmonwait, 0)
  1773  				notewakeup(&sched.sysmonnote)
  1774  			}
  1775  			unlock(&sched.lock)
  1776  			lock(&newmHandoff.lock)
  1777  			if newmHandoff.waiting {
  1778  				newmHandoff.waiting = false
  1779  				notewakeup(&newmHandoff.wake)
  1780  			}
  1781  			unlock(&newmHandoff.lock)
  1782  			osyield()
  1783  		}
  1784  	}
  1785  	if raceenabled {
  1786  		lock(&mFixupRace.lock)
  1787  		mFixupRace.ctx = 0
  1788  		unlock(&mFixupRace.lock)
  1789  	}
  1790  	startTheWorldGC()
  1791  	msigrestore(sigmask)
  1792  	unlockOSThread()
  1793  }
  1794  
  1795  // runSafePointFn runs the safe point function, if any, for this P.
  1796  // This should be called like
  1797  //
  1798  //     if getg().m.p.runSafePointFn != 0 {
  1799  //         runSafePointFn()
  1800  //     }
  1801  //
  1802  // runSafePointFn must be checked on any transition in to _Pidle or
  1803  // _Psyscall to avoid a race where forEachP sees that the P is running
  1804  // just before the P goes into _Pidle/_Psyscall and neither forEachP
  1805  // nor the P run the safe-point function.
  1806  func runSafePointFn() {
  1807  	p := getg().m.p.ptr()
  1808  	// Resolve the race between forEachP running the safe-point
  1809  	// function on this P's behalf and this P running the
  1810  	// safe-point function directly.
  1811  	if !atomic.Cas(&p.runSafePointFn, 1, 0) {
  1812  		return
  1813  	}
  1814  	sched.safePointFn(p)
  1815  	lock(&sched.lock)
  1816  	sched.safePointWait--
  1817  	if sched.safePointWait == 0 {
  1818  		notewakeup(&sched.safePointNote)
  1819  	}
  1820  	unlock(&sched.lock)
  1821  }
  1822  
  1823  // When running with cgo, we call _cgo_thread_start
  1824  // to start threads for us so that we can play nicely with
  1825  // foreign code.
  1826  var cgoThreadStart unsafe.Pointer
  1827  
  1828  type cgothreadstart struct {
  1829  	g   guintptr
  1830  	tls *uint64
  1831  	fn  unsafe.Pointer
  1832  }
  1833  
  1834  // Allocate a new m unassociated with any thread.
  1835  // Can use p for allocation context if needed.
  1836  // fn is recorded as the new m's m.mstartfn.
  1837  // id is optional pre-allocated m ID. Omit by passing -1.
  1838  //
  1839  // This function is allowed to have write barriers even if the caller
  1840  // isn't because it borrows _p_.
  1841  //
  1842  //go:yeswritebarrierrec
  1843  func allocm(_p_ *p, fn func(), id int64) *m {
  1844  	_g_ := getg()
  1845  	acquirem() // disable GC because it can be called from sysmon
  1846  	if _g_.m.p == 0 {
  1847  		acquirep(_p_) // temporarily borrow p for mallocs in this function
  1848  	}
  1849  
  1850  	// Release the free M list. We need to do this somewhere and
  1851  	// this may free up a stack we can use.
  1852  	if sched.freem != nil {
  1853  		lock(&sched.lock)
  1854  		var newList *m
  1855  		for freem := sched.freem; freem != nil; {
  1856  			if freem.freeWait != 0 {
  1857  				next := freem.freelink
  1858  				freem.freelink = newList
  1859  				newList = freem
  1860  				freem = next
  1861  				continue
  1862  			}
  1863  			// stackfree must be on the system stack, but allocm is
  1864  			// reachable off the system stack transitively from
  1865  			// startm.
  1866  			systemstack(func() {
  1867  				stackfree(freem.g0.stack)
  1868  			})
  1869  			freem = freem.freelink
  1870  		}
  1871  		sched.freem = newList
  1872  		unlock(&sched.lock)
  1873  	}
  1874  
  1875  	mp := new(m)
  1876  	mp.mstartfn = fn
  1877  	mcommoninit(mp, id)
  1878  
  1879  	// In case of cgo or Solaris or illumos or Darwin, pthread_create will make us a stack.
  1880  	// Windows and Plan 9 will layout sched stack on OS stack.
  1881  	if iscgo || mStackIsSystemAllocated() {
  1882  		mp.g0 = malg(-1)
  1883  	} else {
  1884  		mp.g0 = malg(8192 * sys.StackGuardMultiplier)
  1885  	}
  1886  	mp.g0.m = mp
  1887  
  1888  	if _p_ == _g_.m.p.ptr() {
  1889  		releasep()
  1890  	}
  1891  	releasem(_g_.m)
  1892  
  1893  	return mp
  1894  }
  1895  
  1896  // needm is called when a cgo callback happens on a
  1897  // thread without an m (a thread not created by Go).
  1898  // In this case, needm is expected to find an m to use
  1899  // and return with m, g initialized correctly.
  1900  // Since m and g are not set now (likely nil, but see below)
  1901  // needm is limited in what routines it can call. In particular
  1902  // it can only call nosplit functions (textflag 7) and cannot
  1903  // do any scheduling that requires an m.
  1904  //
  1905  // In order to avoid needing heavy lifting here, we adopt
  1906  // the following strategy: there is a stack of available m's
  1907  // that can be stolen. Using compare-and-swap
  1908  // to pop from the stack has ABA races, so we simulate
  1909  // a lock by doing an exchange (via Casuintptr) to steal the stack
  1910  // head and replace the top pointer with MLOCKED (1).
  1911  // This serves as a simple spin lock that we can use even
  1912  // without an m. The thread that locks the stack in this way
  1913  // unlocks the stack by storing a valid stack head pointer.
  1914  //
  1915  // In order to make sure that there is always an m structure
  1916  // available to be stolen, we maintain the invariant that there
  1917  // is always one more than needed. At the beginning of the
  1918  // program (if cgo is in use) the list is seeded with a single m.
  1919  // If needm finds that it has taken the last m off the list, its job
  1920  // is - once it has installed its own m so that it can do things like
  1921  // allocate memory - to create a spare m and put it on the list.
  1922  //
  1923  // Each of these extra m's also has a g0 and a curg that are
  1924  // pressed into service as the scheduling stack and current
  1925  // goroutine for the duration of the cgo callback.
  1926  //
  1927  // When the callback is done with the m, it calls dropm to
  1928  // put the m back on the list.
  1929  //go:nosplit
  1930  func needm() {
  1931  	if (iscgo || GOOS == "windows") && !cgoHasExtraM {
  1932  		// Can happen if C/C++ code calls Go from a global ctor.
  1933  		// Can also happen on Windows if a global ctor uses a
  1934  		// callback created by syscall.NewCallback. See issue #6751
  1935  		// for details.
  1936  		//
  1937  		// Can not throw, because scheduler is not initialized yet.
  1938  		write(2, unsafe.Pointer(&earlycgocallback[0]), int32(len(earlycgocallback)))
  1939  		exit(1)
  1940  	}
  1941  
  1942  	// Save and block signals before getting an M.
  1943  	// The signal handler may call needm itself,
  1944  	// and we must avoid a deadlock. Also, once g is installed,
  1945  	// any incoming signals will try to execute,
  1946  	// but we won't have the sigaltstack settings and other data
  1947  	// set up appropriately until the end of minit, which will
  1948  	// unblock the signals. This is the same dance as when
  1949  	// starting a new m to run Go code via newosproc.
  1950  	var sigmask sigset
  1951  	sigsave(&sigmask)
  1952  	sigblock(false)
  1953  
  1954  	// Lock extra list, take head, unlock popped list.
  1955  	// nilokay=false is safe here because of the invariant above,
  1956  	// that the extra list always contains or will soon contain
  1957  	// at least one m.
  1958  	mp := lockextra(false)
  1959  
  1960  	// Set needextram when we've just emptied the list,
  1961  	// so that the eventual call into cgocallbackg will
  1962  	// allocate a new m for the extra list. We delay the
  1963  	// allocation until then so that it can be done
  1964  	// after exitsyscall makes sure it is okay to be
  1965  	// running at all (that is, there's no garbage collection
  1966  	// running right now).
  1967  	mp.needextram = mp.schedlink == 0
  1968  	extraMCount--
  1969  	unlockextra(mp.schedlink.ptr())
  1970  
  1971  	// Store the original signal mask for use by minit.
  1972  	mp.sigmask = sigmask
  1973  
  1974  	// Install TLS on some platforms (previously setg
  1975  	// would do this if necessary).
  1976  	osSetupTLS(mp)
  1977  
  1978  	// Install g (= m->g0) and set the stack bounds
  1979  	// to match the current stack. We don't actually know
  1980  	// how big the stack is, like we don't know how big any
  1981  	// scheduling stack is, but we assume there's at least 32 kB,
  1982  	// which is more than enough for us.
  1983  	setg(mp.g0)
  1984  	_g_ := getg()
  1985  	_g_.stack.hi = getcallersp() + 1024
  1986  	_g_.stack.lo = getcallersp() - 32*1024
  1987  	_g_.stackguard0 = _g_.stack.lo + _StackGuard
  1988  
  1989  	// Initialize this thread to use the m.
  1990  	asminit()
  1991  	minit()
  1992  
  1993  	// mp.curg is now a real goroutine.
  1994  	casgstatus(mp.curg, _Gdead, _Gsyscall)
  1995  	atomic.Xadd(&sched.ngsys, -1)
  1996  }
  1997  
  1998  var earlycgocallback = []byte("fatal error: cgo callback before cgo call\n")
  1999  
  2000  // newextram allocates m's and puts them on the extra list.
  2001  // It is called with a working local m, so that it can do things
  2002  // like call schedlock and allocate.
  2003  func newextram() {
  2004  	c := atomic.Xchg(&extraMWaiters, 0)
  2005  	if c > 0 {
  2006  		for i := uint32(0); i < c; i++ {
  2007  			oneNewExtraM()
  2008  		}
  2009  	} else {
  2010  		// Make sure there is at least one extra M.
  2011  		mp := lockextra(true)
  2012  		unlockextra(mp)
  2013  		if mp == nil {
  2014  			oneNewExtraM()
  2015  		}
  2016  	}
  2017  }
  2018  
  2019  // oneNewExtraM allocates an m and puts it on the extra list.
  2020  func oneNewExtraM() {
  2021  	// Create extra goroutine locked to extra m.
  2022  	// The goroutine is the context in which the cgo callback will run.
  2023  	// The sched.pc will never be returned to, but setting it to
  2024  	// goexit makes clear to the traceback routines where
  2025  	// the goroutine stack ends.
  2026  	mp := allocm(nil, nil, -1)
  2027  	gp := malg(4096)
  2028  	gp.sched.pc = abi.FuncPCABI0(goexit) + sys.PCQuantum
  2029  	gp.sched.sp = gp.stack.hi
  2030  	gp.sched.sp -= 4 * sys.PtrSize // extra space in case of reads slightly beyond frame
  2031  	gp.sched.lr = 0
  2032  	gp.sched.g = guintptr(unsafe.Pointer(gp))
  2033  	gp.syscallpc = gp.sched.pc
  2034  	gp.syscallsp = gp.sched.sp
  2035  	gp.stktopsp = gp.sched.sp
  2036  	// malg returns status as _Gidle. Change to _Gdead before
  2037  	// adding to allg where GC can see it. We use _Gdead to hide
  2038  	// this from tracebacks and stack scans since it isn't a
  2039  	// "real" goroutine until needm grabs it.
  2040  	casgstatus(gp, _Gidle, _Gdead)
  2041  	gp.m = mp
  2042  	mp.curg = gp
  2043  	mp.lockedInt++
  2044  	mp.lockedg.set(gp)
  2045  	gp.lockedm.set(mp)
  2046  	gp.goid = int64(atomic.Xadd64(&sched.goidgen, 1))
  2047  	if raceenabled {
  2048  		gp.racectx = racegostart(funcPC(newextram) + sys.PCQuantum)
  2049  	}
  2050  	// put on allg for garbage collector
  2051  	allgadd(gp)
  2052  
  2053  	// gp is now on the allg list, but we don't want it to be
  2054  	// counted by gcount. It would be more "proper" to increment
  2055  	// sched.ngfree, but that requires locking. Incrementing ngsys
  2056  	// has the same effect.
  2057  	atomic.Xadd(&sched.ngsys, +1)
  2058  
  2059  	// Add m to the extra list.
  2060  	mnext := lockextra(true)
  2061  	mp.schedlink.set(mnext)
  2062  	extraMCount++
  2063  	unlockextra(mp)
  2064  }
  2065  
  2066  // dropm is called when a cgo callback has called needm but is now
  2067  // done with the callback and returning back into the non-Go thread.
  2068  // It puts the current m back onto the extra list.
  2069  //
  2070  // The main expense here is the call to signalstack to release the
  2071  // m's signal stack, and then the call to needm on the next callback
  2072  // from this thread. It is tempting to try to save the m for next time,
  2073  // which would eliminate both these costs, but there might not be
  2074  // a next time: the current thread (which Go does not control) might exit.
  2075  // If we saved the m for that thread, there would be an m leak each time
  2076  // such a thread exited. Instead, we acquire and release an m on each
  2077  // call. These should typically not be scheduling operations, just a few
  2078  // atomics, so the cost should be small.
  2079  //
  2080  // TODO(rsc): An alternative would be to allocate a dummy pthread per-thread
  2081  // variable using pthread_key_create. Unlike the pthread keys we already use
  2082  // on OS X, this dummy key would never be read by Go code. It would exist
  2083  // only so that we could register at thread-exit-time destructor.
  2084  // That destructor would put the m back onto the extra list.
  2085  // This is purely a performance optimization. The current version,
  2086  // in which dropm happens on each cgo call, is still correct too.
  2087  // We may have to keep the current version on systems with cgo
  2088  // but without pthreads, like Windows.
  2089  func dropm() {
  2090  	// Clear m and g, and return m to the extra list.
  2091  	// After the call to setg we can only call nosplit functions
  2092  	// with no pointer manipulation.
  2093  	mp := getg().m
  2094  
  2095  	// Return mp.curg to dead state.
  2096  	casgstatus(mp.curg, _Gsyscall, _Gdead)
  2097  	mp.curg.preemptStop = false
  2098  	atomic.Xadd(&sched.ngsys, +1)
  2099  
  2100  	// Block signals before unminit.
  2101  	// Unminit unregisters the signal handling stack (but needs g on some systems).
  2102  	// Setg(nil) clears g, which is the signal handler's cue not to run Go handlers.
  2103  	// It's important not to try to handle a signal between those two steps.
  2104  	sigmask := mp.sigmask
  2105  	sigblock(false)
  2106  	unminit()
  2107  
  2108  	mnext := lockextra(true)
  2109  	extraMCount++
  2110  	mp.schedlink.set(mnext)
  2111  
  2112  	setg(nil)
  2113  
  2114  	// Commit the release of mp.
  2115  	unlockextra(mp)
  2116  
  2117  	msigrestore(sigmask)
  2118  }
  2119  
  2120  // A helper function for EnsureDropM.
  2121  func getm() uintptr {
  2122  	return uintptr(unsafe.Pointer(getg().m))
  2123  }
  2124  
  2125  var extram uintptr
  2126  var extraMCount uint32 // Protected by lockextra
  2127  var extraMWaiters uint32
  2128  
  2129  // lockextra locks the extra list and returns the list head.
  2130  // The caller must unlock the list by storing a new list head
  2131  // to extram. If nilokay is true, then lockextra will
  2132  // return a nil list head if that's what it finds. If nilokay is false,
  2133  // lockextra will keep waiting until the list head is no longer nil.
  2134  //go:nosplit
  2135  func lockextra(nilokay bool) *m {
  2136  	const locked = 1
  2137  
  2138  	incr := false
  2139  	for {
  2140  		old := atomic.Loaduintptr(&extram)
  2141  		if old == locked {
  2142  			osyield_no_g()
  2143  			continue
  2144  		}
  2145  		if old == 0 && !nilokay {
  2146  			if !incr {
  2147  				// Add 1 to the number of threads
  2148  				// waiting for an M.
  2149  				// This is cleared by newextram.
  2150  				atomic.Xadd(&extraMWaiters, 1)
  2151  				incr = true
  2152  			}
  2153  			usleep_no_g(1)
  2154  			continue
  2155  		}
  2156  		if atomic.Casuintptr(&extram, old, locked) {
  2157  			return (*m)(unsafe.Pointer(old))
  2158  		}
  2159  		osyield_no_g()
  2160  		continue
  2161  	}
  2162  }
  2163  
  2164  //go:nosplit
  2165  func unlockextra(mp *m) {
  2166  	atomic.Storeuintptr(&extram, uintptr(unsafe.Pointer(mp)))
  2167  }
  2168  
  2169  // execLock serializes exec and clone to avoid bugs or unspecified behaviour
  2170  // around exec'ing while creating/destroying threads.  See issue #19546.
  2171  var execLock rwmutex
  2172  
  2173  // newmHandoff contains a list of m structures that need new OS threads.
  2174  // This is used by newm in situations where newm itself can't safely
  2175  // start an OS thread.
  2176  var newmHandoff struct {
  2177  	lock mutex
  2178  
  2179  	// newm points to a list of M structures that need new OS
  2180  	// threads. The list is linked through m.schedlink.
  2181  	newm muintptr
  2182  
  2183  	// waiting indicates that wake needs to be notified when an m
  2184  	// is put on the list.
  2185  	waiting bool
  2186  	wake    note
  2187  
  2188  	// haveTemplateThread indicates that the templateThread has
  2189  	// been started. This is not protected by lock. Use cas to set
  2190  	// to 1.
  2191  	haveTemplateThread uint32
  2192  }
  2193  
  2194  // Create a new m. It will start off with a call to fn, or else the scheduler.
  2195  // fn needs to be static and not a heap allocated closure.
  2196  // May run with m.p==nil, so write barriers are not allowed.
  2197  //
  2198  // id is optional pre-allocated m ID. Omit by passing -1.
  2199  //go:nowritebarrierrec
  2200  func newm(fn func(), _p_ *p, id int64) {
  2201  	mp := allocm(_p_, fn, id)
  2202  	mp.doesPark = (_p_ != nil)
  2203  	mp.nextp.set(_p_)
  2204  	mp.sigmask = initSigmask
  2205  	if gp := getg(); gp != nil && gp.m != nil && (gp.m.lockedExt != 0 || gp.m.incgo) && GOOS != "plan9" {
  2206  		// We're on a locked M or a thread that may have been
  2207  		// started by C. The kernel state of this thread may
  2208  		// be strange (the user may have locked it for that
  2209  		// purpose). We don't want to clone that into another
  2210  		// thread. Instead, ask a known-good thread to create
  2211  		// the thread for us.
  2212  		//
  2213  		// This is disabled on Plan 9. See golang.org/issue/22227.
  2214  		//
  2215  		// TODO: This may be unnecessary on Windows, which
  2216  		// doesn't model thread creation off fork.
  2217  		lock(&newmHandoff.lock)
  2218  		if newmHandoff.haveTemplateThread == 0 {
  2219  			throw("on a locked thread with no template thread")
  2220  		}
  2221  		mp.schedlink = newmHandoff.newm
  2222  		newmHandoff.newm.set(mp)
  2223  		if newmHandoff.waiting {
  2224  			newmHandoff.waiting = false
  2225  			notewakeup(&newmHandoff.wake)
  2226  		}
  2227  		unlock(&newmHandoff.lock)
  2228  		return
  2229  	}
  2230  	newm1(mp)
  2231  }
  2232  
  2233  func newm1(mp *m) {
  2234  	if iscgo {
  2235  		var ts cgothreadstart
  2236  		if _cgo_thread_start == nil {
  2237  			throw("_cgo_thread_start missing")
  2238  		}
  2239  		ts.g.set(mp.g0)
  2240  		ts.tls = (*uint64)(unsafe.Pointer(&mp.tls[0]))
  2241  		ts.fn = unsafe.Pointer(funcPC(mstart))
  2242  		if msanenabled {
  2243  			msanwrite(unsafe.Pointer(&ts), unsafe.Sizeof(ts))
  2244  		}
  2245  		execLock.rlock() // Prevent process clone.
  2246  		asmcgocall(_cgo_thread_start, unsafe.Pointer(&ts))
  2247  		execLock.runlock()
  2248  		return
  2249  	}
  2250  	execLock.rlock() // Prevent process clone.
  2251  	newosproc(mp)
  2252  	execLock.runlock()
  2253  }
  2254  
  2255  // startTemplateThread starts the template thread if it is not already
  2256  // running.
  2257  //
  2258  // The calling thread must itself be in a known-good state.
  2259  func startTemplateThread() {
  2260  	if GOARCH == "wasm" { // no threads on wasm yet
  2261  		return
  2262  	}
  2263  
  2264  	// Disable preemption to guarantee that the template thread will be
  2265  	// created before a park once haveTemplateThread is set.
  2266  	mp := acquirem()
  2267  	if !atomic.Cas(&newmHandoff.haveTemplateThread, 0, 1) {
  2268  		releasem(mp)
  2269  		return
  2270  	}
  2271  	newm(templateThread, nil, -1)
  2272  	releasem(mp)
  2273  }
  2274  
  2275  // mFixupRace is used to temporarily borrow the race context from the
  2276  // coordinating m during a syscall_runtime_doAllThreadsSyscall and
  2277  // loan it out to each of the m's of the runtime so they can execute a
  2278  // mFixup.fn in that context.
  2279  var mFixupRace struct {
  2280  	lock mutex
  2281  	ctx  uintptr
  2282  }
  2283  
  2284  // mDoFixup runs any outstanding fixup function for the running m.
  2285  // Returns true if a fixup was outstanding and actually executed.
  2286  //
  2287  // Note: to avoid deadlocks, and the need for the fixup function
  2288  // itself to be async safe, signals are blocked for the working m
  2289  // while it holds the mFixup lock. (See golang.org/issue/44193)
  2290  //
  2291  //go:nosplit
  2292  func mDoFixup() bool {
  2293  	_g_ := getg()
  2294  	if used := atomic.Load(&_g_.m.mFixup.used); used == 0 {
  2295  		return false
  2296  	}
  2297  
  2298  	// slow path - if fixup fn is used, block signals and lock.
  2299  	var sigmask sigset
  2300  	sigsave(&sigmask)
  2301  	sigblock(false)
  2302  	lock(&_g_.m.mFixup.lock)
  2303  	fn := _g_.m.mFixup.fn
  2304  	if fn != nil {
  2305  		if gcphase != _GCoff {
  2306  			// We can't have a write barrier in this
  2307  			// context since we may not have a P, but we
  2308  			// clear fn to signal that we've executed the
  2309  			// fixup. As long as fn is kept alive
  2310  			// elsewhere, technically we should have no
  2311  			// issues with the GC, but fn is likely
  2312  			// generated in a different package altogether
  2313  			// that may change independently. Just assert
  2314  			// the GC is off so this lack of write barrier
  2315  			// is more obviously safe.
  2316  			throw("GC must be disabled to protect validity of fn value")
  2317  		}
  2318  		if _g_.racectx != 0 || !raceenabled {
  2319  			fn(false)
  2320  		} else {
  2321  			// temporarily acquire the context of the
  2322  			// originator of the
  2323  			// syscall_runtime_doAllThreadsSyscall and
  2324  			// block others from using it for the duration
  2325  			// of the fixup call.
  2326  			lock(&mFixupRace.lock)
  2327  			_g_.racectx = mFixupRace.ctx
  2328  			fn(false)
  2329  			_g_.racectx = 0
  2330  			unlock(&mFixupRace.lock)
  2331  		}
  2332  		*(*uintptr)(unsafe.Pointer(&_g_.m.mFixup.fn)) = 0
  2333  		atomic.Store(&_g_.m.mFixup.used, 0)
  2334  	}
  2335  	unlock(&_g_.m.mFixup.lock)
  2336  	msigrestore(sigmask)
  2337  	return fn != nil
  2338  }
  2339  
  2340  // mDoFixupAndOSYield is called when an m is unable to send a signal
  2341  // because the allThreadsSyscall mechanism is in progress. That is, an
  2342  // mPark() has been interrupted with this signal handler so we need to
  2343  // ensure the fixup is executed from this context.
  2344  //go:nosplit
  2345  func mDoFixupAndOSYield() {
  2346  	mDoFixup()
  2347  	osyield()
  2348  }
  2349  
  2350  // templateThread is a thread in a known-good state that exists solely
  2351  // to start new threads in known-good states when the calling thread
  2352  // may not be in a good state.
  2353  //
  2354  // Many programs never need this, so templateThread is started lazily
  2355  // when we first enter a state that might lead to running on a thread
  2356  // in an unknown state.
  2357  //
  2358  // templateThread runs on an M without a P, so it must not have write
  2359  // barriers.
  2360  //
  2361  //go:nowritebarrierrec
  2362  func templateThread() {
  2363  	lock(&sched.lock)
  2364  	sched.nmsys++
  2365  	checkdead()
  2366  	unlock(&sched.lock)
  2367  
  2368  	for {
  2369  		lock(&newmHandoff.lock)
  2370  		for newmHandoff.newm != 0 {
  2371  			newm := newmHandoff.newm.ptr()
  2372  			newmHandoff.newm = 0
  2373  			unlock(&newmHandoff.lock)
  2374  			for newm != nil {
  2375  				next := newm.schedlink.ptr()
  2376  				newm.schedlink = 0
  2377  				newm1(newm)
  2378  				newm = next
  2379  			}
  2380  			lock(&newmHandoff.lock)
  2381  		}
  2382  		newmHandoff.waiting = true
  2383  		noteclear(&newmHandoff.wake)
  2384  		unlock(&newmHandoff.lock)
  2385  		notesleep(&newmHandoff.wake)
  2386  		mDoFixup()
  2387  	}
  2388  }
  2389  
  2390  // Stops execution of the current m until new work is available.
  2391  // Returns with acquired P.
  2392  func stopm() {
  2393  	_g_ := getg()
  2394  
  2395  	if _g_.m.locks != 0 {
  2396  		throw("stopm holding locks")
  2397  	}
  2398  	if _g_.m.p != 0 {
  2399  		throw("stopm holding p")
  2400  	}
  2401  	if _g_.m.spinning {
  2402  		throw("stopm spinning")
  2403  	}
  2404  
  2405  	lock(&sched.lock)
  2406  	mput(_g_.m)
  2407  	unlock(&sched.lock)
  2408  	mPark()
  2409  	acquirep(_g_.m.nextp.ptr())
  2410  	_g_.m.nextp = 0
  2411  }
  2412  
  2413  func mspinning() {
  2414  	// startm's caller incremented nmspinning. Set the new M's spinning.
  2415  	getg().m.spinning = true
  2416  }
  2417  
  2418  // Schedules some M to run the p (creates an M if necessary).
  2419  // If p==nil, tries to get an idle P, if no idle P's does nothing.
  2420  // May run with m.p==nil, so write barriers are not allowed.
  2421  // If spinning is set, the caller has incremented nmspinning and startm will
  2422  // either decrement nmspinning or set m.spinning in the newly started M.
  2423  //
  2424  // Callers passing a non-nil P must call from a non-preemptible context. See
  2425  // comment on acquirem below.
  2426  //
  2427  // Must not have write barriers because this may be called without a P.
  2428  //go:nowritebarrierrec
  2429  func startm(_p_ *p, spinning bool) {
  2430  	// Disable preemption.
  2431  	//
  2432  	// Every owned P must have an owner that will eventually stop it in the
  2433  	// event of a GC stop request. startm takes transient ownership of a P
  2434  	// (either from argument or pidleget below) and transfers ownership to
  2435  	// a started M, which will be responsible for performing the stop.
  2436  	//
  2437  	// Preemption must be disabled during this transient ownership,
  2438  	// otherwise the P this is running on may enter GC stop while still
  2439  	// holding the transient P, leaving that P in limbo and deadlocking the
  2440  	// STW.
  2441  	//
  2442  	// Callers passing a non-nil P must already be in non-preemptible
  2443  	// context, otherwise such preemption could occur on function entry to
  2444  	// startm. Callers passing a nil P may be preemptible, so we must
  2445  	// disable preemption before acquiring a P from pidleget below.
  2446  	mp := acquirem()
  2447  	lock(&sched.lock)
  2448  	if _p_ == nil {
  2449  		_p_ = pidleget()
  2450  		if _p_ == nil {
  2451  			unlock(&sched.lock)
  2452  			if spinning {
  2453  				// The caller incremented nmspinning, but there are no idle Ps,
  2454  				// so it's okay to just undo the increment and give up.
  2455  				if int32(atomic.Xadd(&sched.nmspinning, -1)) < 0 {
  2456  					throw("startm: negative nmspinning")
  2457  				}
  2458  			}
  2459  			releasem(mp)
  2460  			return
  2461  		}
  2462  	}
  2463  	nmp := mget()
  2464  	if nmp == nil {
  2465  		// No M is available, we must drop sched.lock and call newm.
  2466  		// However, we already own a P to assign to the M.
  2467  		//
  2468  		// Once sched.lock is released, another G (e.g., in a syscall),
  2469  		// could find no idle P while checkdead finds a runnable G but
  2470  		// no running M's because this new M hasn't started yet, thus
  2471  		// throwing in an apparent deadlock.
  2472  		//
  2473  		// Avoid this situation by pre-allocating the ID for the new M,
  2474  		// thus marking it as 'running' before we drop sched.lock. This
  2475  		// new M will eventually run the scheduler to execute any
  2476  		// queued G's.
  2477  		id := mReserveID()
  2478  		unlock(&sched.lock)
  2479  
  2480  		var fn func()
  2481  		if spinning {
  2482  			// The caller incremented nmspinning, so set m.spinning in the new M.
  2483  			fn = mspinning
  2484  		}
  2485  		newm(fn, _p_, id)
  2486  		// Ownership transfer of _p_ committed by start in newm.
  2487  		// Preemption is now safe.
  2488  		releasem(mp)
  2489  		return
  2490  	}
  2491  	unlock(&sched.lock)
  2492  	if nmp.spinning {
  2493  		throw("startm: m is spinning")
  2494  	}
  2495  	if nmp.nextp != 0 {
  2496  		throw("startm: m has p")
  2497  	}
  2498  	if spinning && !runqempty(_p_) {
  2499  		throw("startm: p has runnable gs")
  2500  	}
  2501  	// The caller incremented nmspinning, so set m.spinning in the new M.
  2502  	nmp.spinning = spinning
  2503  	nmp.nextp.set(_p_)
  2504  	notewakeup(&nmp.park)
  2505  	// Ownership transfer of _p_ committed by wakeup. Preemption is now
  2506  	// safe.
  2507  	releasem(mp)
  2508  }
  2509  
  2510  // Hands off P from syscall or locked M.
  2511  // Always runs without a P, so write barriers are not allowed.
  2512  //go:nowritebarrierrec
  2513  func handoffp(_p_ *p) {
  2514  	// handoffp must start an M in any situation where
  2515  	// findrunnable would return a G to run on _p_.
  2516  
  2517  	// if it has local work, start it straight away
  2518  	if !runqempty(_p_) || sched.runqsize != 0 {
  2519  		startm(_p_, false)
  2520  		return
  2521  	}
  2522  	// if it has GC work, start it straight away
  2523  	if gcBlackenEnabled != 0 && gcMarkWorkAvailable(_p_) {
  2524  		startm(_p_, false)
  2525  		return
  2526  	}
  2527  	// no local work, check that there are no spinning/idle M's,
  2528  	// otherwise our help is not required
  2529  	if atomic.Load(&sched.nmspinning)+atomic.Load(&sched.npidle) == 0 && atomic.Cas(&sched.nmspinning, 0, 1) { // TODO: fast atomic
  2530  		startm(_p_, true)
  2531  		return
  2532  	}
  2533  	lock(&sched.lock)
  2534  	if sched.gcwaiting != 0 {
  2535  		_p_.status = _Pgcstop
  2536  		sched.stopwait--
  2537  		if sched.stopwait == 0 {
  2538  			notewakeup(&sched.stopnote)
  2539  		}
  2540  		unlock(&sched.lock)
  2541  		return
  2542  	}
  2543  	if _p_.runSafePointFn != 0 && atomic.Cas(&_p_.runSafePointFn, 1, 0) {
  2544  		sched.safePointFn(_p_)
  2545  		sched.safePointWait--
  2546  		if sched.safePointWait == 0 {
  2547  			notewakeup(&sched.safePointNote)
  2548  		}
  2549  	}
  2550  	if sched.runqsize != 0 {
  2551  		unlock(&sched.lock)
  2552  		startm(_p_, false)
  2553  		return
  2554  	}
  2555  	// If this is the last running P and nobody is polling network,
  2556  	// need to wakeup another M to poll network.
  2557  	if sched.npidle == uint32(gomaxprocs-1) && atomic.Load64(&sched.lastpoll) != 0 {
  2558  		unlock(&sched.lock)
  2559  		startm(_p_, false)
  2560  		return
  2561  	}
  2562  
  2563  	// The scheduler lock cannot be held when calling wakeNetPoller below
  2564  	// because wakeNetPoller may call wakep which may call startm.
  2565  	when := nobarrierWakeTime(_p_)
  2566  	pidleput(_p_)
  2567  	unlock(&sched.lock)
  2568  
  2569  	if when != 0 {
  2570  		wakeNetPoller(when)
  2571  	}
  2572  }
  2573  
  2574  // Tries to add one more P to execute G's.
  2575  // Called when a G is made runnable (newproc, ready).
  2576  func wakep() {
  2577  	if atomic.Load(&sched.npidle) == 0 {
  2578  		return
  2579  	}
  2580  	// be conservative about spinning threads
  2581  	if atomic.Load(&sched.nmspinning) != 0 || !atomic.Cas(&sched.nmspinning, 0, 1) {
  2582  		return
  2583  	}
  2584  	startm(nil, true)
  2585  }
  2586  
  2587  // Stops execution of the current m that is locked to a g until the g is runnable again.
  2588  // Returns with acquired P.
  2589  func stoplockedm() {
  2590  	_g_ := getg()
  2591  
  2592  	if _g_.m.lockedg == 0 || _g_.m.lockedg.ptr().lockedm.ptr() != _g_.m {
  2593  		throw("stoplockedm: inconsistent locking")
  2594  	}
  2595  	if _g_.m.p != 0 {
  2596  		// Schedule another M to run this p.
  2597  		_p_ := releasep()
  2598  		handoffp(_p_)
  2599  	}
  2600  	incidlelocked(1)
  2601  	// Wait until another thread schedules lockedg again.
  2602  	mPark()
  2603  	status := readgstatus(_g_.m.lockedg.ptr())
  2604  	if status&^_Gscan != _Grunnable {
  2605  		print("runtime:stoplockedm: lockedg (atomicstatus=", status, ") is not Grunnable or Gscanrunnable\n")
  2606  		dumpgstatus(_g_.m.lockedg.ptr())
  2607  		throw("stoplockedm: not runnable")
  2608  	}
  2609  	acquirep(_g_.m.nextp.ptr())
  2610  	_g_.m.nextp = 0
  2611  }
  2612  
  2613  // Schedules the locked m to run the locked gp.
  2614  // May run during STW, so write barriers are not allowed.
  2615  //go:nowritebarrierrec
  2616  func startlockedm(gp *g) {
  2617  	_g_ := getg()
  2618  
  2619  	mp := gp.lockedm.ptr()
  2620  	if mp == _g_.m {
  2621  		throw("startlockedm: locked to me")
  2622  	}
  2623  	if mp.nextp != 0 {
  2624  		throw("startlockedm: m has p")
  2625  	}
  2626  	// directly handoff current P to the locked m
  2627  	incidlelocked(-1)
  2628  	_p_ := releasep()
  2629  	mp.nextp.set(_p_)
  2630  	notewakeup(&mp.park)
  2631  	stopm()
  2632  }
  2633  
  2634  // Stops the current m for stopTheWorld.
  2635  // Returns when the world is restarted.
  2636  func gcstopm() {
  2637  	_g_ := getg()
  2638  
  2639  	if sched.gcwaiting == 0 {
  2640  		throw("gcstopm: not waiting for gc")
  2641  	}
  2642  	if _g_.m.spinning {
  2643  		_g_.m.spinning = false
  2644  		// OK to just drop nmspinning here,
  2645  		// startTheWorld will unpark threads as necessary.
  2646  		if int32(atomic.Xadd(&sched.nmspinning, -1)) < 0 {
  2647  			throw("gcstopm: negative nmspinning")
  2648  		}
  2649  	}
  2650  	_p_ := releasep()
  2651  	lock(&sched.lock)
  2652  	_p_.status = _Pgcstop
  2653  	sched.stopwait--
  2654  	if sched.stopwait == 0 {
  2655  		notewakeup(&sched.stopnote)
  2656  	}
  2657  	unlock(&sched.lock)
  2658  	stopm()
  2659  }
  2660  
  2661  // Schedules gp to run on the current M.
  2662  // If inheritTime is true, gp inherits the remaining time in the
  2663  // current time slice. Otherwise, it starts a new time slice.
  2664  // Never returns.
  2665  //
  2666  // Write barriers are allowed because this is called immediately after
  2667  // acquiring a P in several places.
  2668  //
  2669  //go:yeswritebarrierrec
  2670  func execute(gp *g, inheritTime bool) {
  2671  	_g_ := getg()
  2672  
  2673  	// Assign gp.m before entering _Grunning so running Gs have an
  2674  	// M.
  2675  	_g_.m.curg = gp
  2676  	gp.m = _g_.m
  2677  	casgstatus(gp, _Grunnable, _Grunning)
  2678  	gp.waitsince = 0
  2679  	gp.preempt = false
  2680  	gp.stackguard0 = gp.stack.lo + _StackGuard
  2681  	if !inheritTime {
  2682  		_g_.m.p.ptr().schedtick++
  2683  	}
  2684  
  2685  	// Check whether the profiler needs to be turned on or off.
  2686  	hz := sched.profilehz
  2687  	if _g_.m.profilehz != hz {
  2688  		setThreadCPUProfiler(hz)
  2689  	}
  2690  
  2691  	if trace.enabled {
  2692  		// GoSysExit has to happen when we have a P, but before GoStart.
  2693  		// So we emit it here.
  2694  		if gp.syscallsp != 0 && gp.sysblocktraced {
  2695  			traceGoSysExit(gp.sysexitticks)
  2696  		}
  2697  		traceGoStart()
  2698  	}
  2699  
  2700  	gogo(&gp.sched)
  2701  }
  2702  
  2703  // Finds a runnable goroutine to execute.
  2704  // Tries to steal from other P's, get g from local or global queue, poll network.
  2705  func findrunnable() (gp *g, inheritTime bool) {
  2706  	_g_ := getg()
  2707  
  2708  	// The conditions here and in handoffp must agree: if
  2709  	// findrunnable would return a G to run, handoffp must start
  2710  	// an M.
  2711  
  2712  top:
  2713  	_p_ := _g_.m.p.ptr()
  2714  	if sched.gcwaiting != 0 {
  2715  		gcstopm()
  2716  		goto top
  2717  	}
  2718  	if _p_.runSafePointFn != 0 {
  2719  		runSafePointFn()
  2720  	}
  2721  
  2722  	now, pollUntil, _ := checkTimers(_p_, 0)
  2723  
  2724  	if fingwait && fingwake {
  2725  		if gp := wakefing(); gp != nil {
  2726  			ready(gp, 0, true)
  2727  		}
  2728  	}
  2729  	if *cgo_yield != nil {
  2730  		asmcgocall(*cgo_yield, nil)
  2731  	}
  2732  
  2733  	// local runq
  2734  	if gp, inheritTime := runqget(_p_); gp != nil {
  2735  		return gp, inheritTime
  2736  	}
  2737  
  2738  	// global runq
  2739  	if sched.runqsize != 0 {
  2740  		lock(&sched.lock)
  2741  		gp := globrunqget(_p_, 0)
  2742  		unlock(&sched.lock)
  2743  		if gp != nil {
  2744  			return gp, false
  2745  		}
  2746  	}
  2747  
  2748  	// Poll network.
  2749  	// This netpoll is only an optimization before we resort to stealing.
  2750  	// We can safely skip it if there are no waiters or a thread is blocked
  2751  	// in netpoll already. If there is any kind of logical race with that
  2752  	// blocked thread (e.g. it has already returned from netpoll, but does
  2753  	// not set lastpoll yet), this thread will do blocking netpoll below
  2754  	// anyway.
  2755  	if netpollinited() && atomic.Load(&netpollWaiters) > 0 && atomic.Load64(&sched.lastpoll) != 0 {
  2756  		if list := netpoll(0); !list.empty() { // non-blocking
  2757  			gp := list.pop()
  2758  			injectglist(&list)
  2759  			casgstatus(gp, _Gwaiting, _Grunnable)
  2760  			if trace.enabled {
  2761  				traceGoUnpark(gp, 0)
  2762  			}
  2763  			return gp, false
  2764  		}
  2765  	}
  2766  
  2767  	// Spinning Ms: steal work from other Ps.
  2768  	//
  2769  	// Limit the number of spinning Ms to half the number of busy Ps.
  2770  	// This is necessary to prevent excessive CPU consumption when
  2771  	// GOMAXPROCS>>1 but the program parallelism is low.
  2772  	procs := uint32(gomaxprocs)
  2773  	if _g_.m.spinning || 2*atomic.Load(&sched.nmspinning) < procs-atomic.Load(&sched.npidle) {
  2774  		if !_g_.m.spinning {
  2775  			_g_.m.spinning = true
  2776  			atomic.Xadd(&sched.nmspinning, 1)
  2777  		}
  2778  
  2779  		gp, inheritTime, tnow, w, newWork := stealWork(now)
  2780  		now = tnow
  2781  		if gp != nil {
  2782  			// Successfully stole.
  2783  			return gp, inheritTime
  2784  		}
  2785  		if newWork {
  2786  			// There may be new timer or GC work; restart to
  2787  			// discover.
  2788  			goto top
  2789  		}
  2790  		if w != 0 && (pollUntil == 0 || w < pollUntil) {
  2791  			// Earlier timer to wait for.
  2792  			pollUntil = w
  2793  		}
  2794  	}
  2795  
  2796  	// We have nothing to do.
  2797  	//
  2798  	// If we're in the GC mark phase, can safely scan and blacken objects,
  2799  	// and have work to do, run idle-time marking rather than give up the
  2800  	// P.
  2801  	if gcBlackenEnabled != 0 && gcMarkWorkAvailable(_p_) {
  2802  		node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
  2803  		if node != nil {
  2804  			_p_.gcMarkWorkerMode = gcMarkWorkerIdleMode
  2805  			gp := node.gp.ptr()
  2806  			casgstatus(gp, _Gwaiting, _Grunnable)
  2807  			if trace.enabled {
  2808  				traceGoUnpark(gp, 0)
  2809  			}
  2810  			return gp, false
  2811  		}
  2812  	}
  2813  
  2814  	// wasm only:
  2815  	// If a callback returned and no other goroutine is awake,
  2816  	// then wake event handler goroutine which pauses execution
  2817  	// until a callback was triggered.
  2818  	gp, otherReady := beforeIdle(now, pollUntil)
  2819  	if gp != nil {
  2820  		casgstatus(gp, _Gwaiting, _Grunnable)
  2821  		if trace.enabled {
  2822  			traceGoUnpark(gp, 0)
  2823  		}
  2824  		return gp, false
  2825  	}
  2826  	if otherReady {
  2827  		goto top
  2828  	}
  2829  
  2830  	// Before we drop our P, make a snapshot of the allp slice,
  2831  	// which can change underfoot once we no longer block
  2832  	// safe-points. We don't need to snapshot the contents because
  2833  	// everything up to cap(allp) is immutable.
  2834  	allpSnapshot := allp
  2835  	// Also snapshot masks. Value changes are OK, but we can't allow
  2836  	// len to change out from under us.
  2837  	idlepMaskSnapshot := idlepMask
  2838  	timerpMaskSnapshot := timerpMask
  2839  
  2840  	// return P and block
  2841  	lock(&sched.lock)
  2842  	if sched.gcwaiting != 0 || _p_.runSafePointFn != 0 {
  2843  		unlock(&sched.lock)
  2844  		goto top
  2845  	}
  2846  	if sched.runqsize != 0 {
  2847  		gp := globrunqget(_p_, 0)
  2848  		unlock(&sched.lock)
  2849  		return gp, false
  2850  	}
  2851  	if releasep() != _p_ {
  2852  		throw("findrunnable: wrong p")
  2853  	}
  2854  	pidleput(_p_)
  2855  	unlock(&sched.lock)
  2856  
  2857  	// Delicate dance: thread transitions from spinning to non-spinning
  2858  	// state, potentially concurrently with submission of new work. We must
  2859  	// drop nmspinning first and then check all sources again (with
  2860  	// #StoreLoad memory barrier in between). If we do it the other way
  2861  	// around, another thread can submit work after we've checked all
  2862  	// sources but before we drop nmspinning; as a result nobody will
  2863  	// unpark a thread to run the work.
  2864  	//
  2865  	// This applies to the following sources of work:
  2866  	//
  2867  	// * Goroutines added to a per-P run queue.
  2868  	// * New/modified-earlier timers on a per-P timer heap.
  2869  	// * Idle-priority GC work (barring golang.org/issue/19112).
  2870  	//
  2871  	// If we discover new work below, we need to restore m.spinning as a signal
  2872  	// for resetspinning to unpark a new worker thread (because there can be more
  2873  	// than one starving goroutine). However, if after discovering new work
  2874  	// we also observe no idle Ps it is OK to skip unparking a new worker
  2875  	// thread: the system is fully loaded so no spinning threads are required.
  2876  	// Also see "Worker thread parking/unparking" comment at the top of the file.
  2877  	wasSpinning := _g_.m.spinning
  2878  	if _g_.m.spinning {
  2879  		_g_.m.spinning = false
  2880  		if int32(atomic.Xadd(&sched.nmspinning, -1)) < 0 {
  2881  			throw("findrunnable: negative nmspinning")
  2882  		}
  2883  
  2884  		// Note the for correctness, only the last M transitioning from
  2885  		// spinning to non-spinning must perform these rechecks to
  2886  		// ensure no missed work. We are performing it on every M that
  2887  		// transitions as a conservative change to monitor effects on
  2888  		// latency. See golang.org/issue/43997.
  2889  
  2890  		// Check all runqueues once again.
  2891  		_p_ = checkRunqsNoP(allpSnapshot, idlepMaskSnapshot)
  2892  		if _p_ != nil {
  2893  			acquirep(_p_)
  2894  			_g_.m.spinning = true
  2895  			atomic.Xadd(&sched.nmspinning, 1)
  2896  			goto top
  2897  		}
  2898  
  2899  		// Check for idle-priority GC work again.
  2900  		_p_, gp = checkIdleGCNoP()
  2901  		if _p_ != nil {
  2902  			acquirep(_p_)
  2903  			_g_.m.spinning = true
  2904  			atomic.Xadd(&sched.nmspinning, 1)
  2905  
  2906  			// Run the idle worker.
  2907  			_p_.gcMarkWorkerMode = gcMarkWorkerIdleMode
  2908  			casgstatus(gp, _Gwaiting, _Grunnable)
  2909  			if trace.enabled {
  2910  				traceGoUnpark(gp, 0)
  2911  			}
  2912  			return gp, false
  2913  		}
  2914  
  2915  		// Finally, check for timer creation or expiry concurrently with
  2916  		// transitioning from spinning to non-spinning.
  2917  		//
  2918  		// Note that we cannot use checkTimers here because it calls
  2919  		// adjusttimers which may need to allocate memory, and that isn't
  2920  		// allowed when we don't have an active P.
  2921  		pollUntil = checkTimersNoP(allpSnapshot, timerpMaskSnapshot, pollUntil)
  2922  	}
  2923  
  2924  	// Poll network until next timer.
  2925  	if netpollinited() && (atomic.Load(&netpollWaiters) > 0 || pollUntil != 0) && atomic.Xchg64(&sched.lastpoll, 0) != 0 {
  2926  		atomic.Store64(&sched.pollUntil, uint64(pollUntil))
  2927  		if _g_.m.p != 0 {
  2928  			throw("findrunnable: netpoll with p")
  2929  		}
  2930  		if _g_.m.spinning {
  2931  			throw("findrunnable: netpoll with spinning")
  2932  		}
  2933  		delay := int64(-1)
  2934  		if pollUntil != 0 {
  2935  			if now == 0 {
  2936  				now = nanotime()
  2937  			}
  2938  			delay = pollUntil - now
  2939  			if delay < 0 {
  2940  				delay = 0
  2941  			}
  2942  		}
  2943  		if faketime != 0 {
  2944  			// When using fake time, just poll.
  2945  			delay = 0
  2946  		}
  2947  		list := netpoll(delay) // block until new work is available
  2948  		atomic.Store64(&sched.pollUntil, 0)
  2949  		atomic.Store64(&sched.lastpoll, uint64(nanotime()))
  2950  		if faketime != 0 && list.empty() {
  2951  			// Using fake time and nothing is ready; stop M.
  2952  			// When all M's stop, checkdead will call timejump.
  2953  			stopm()
  2954  			goto top
  2955  		}
  2956  		lock(&sched.lock)
  2957  		_p_ = pidleget()
  2958  		unlock(&sched.lock)
  2959  		if _p_ == nil {
  2960  			injectglist(&list)
  2961  		} else {
  2962  			acquirep(_p_)
  2963  			if !list.empty() {
  2964  				gp := list.pop()
  2965  				injectglist(&list)
  2966  				casgstatus(gp, _Gwaiting, _Grunnable)
  2967  				if trace.enabled {
  2968  					traceGoUnpark(gp, 0)
  2969  				}
  2970  				return gp, false
  2971  			}
  2972  			if wasSpinning {
  2973  				_g_.m.spinning = true
  2974  				atomic.Xadd(&sched.nmspinning, 1)
  2975  			}
  2976  			goto top
  2977  		}
  2978  	} else if pollUntil != 0 && netpollinited() {
  2979  		pollerPollUntil := int64(atomic.Load64(&sched.pollUntil))
  2980  		if pollerPollUntil == 0 || pollerPollUntil > pollUntil {
  2981  			netpollBreak()
  2982  		}
  2983  	}
  2984  	stopm()
  2985  	goto top
  2986  }
  2987  
  2988  // pollWork reports whether there is non-background work this P could
  2989  // be doing. This is a fairly lightweight check to be used for
  2990  // background work loops, like idle GC. It checks a subset of the
  2991  // conditions checked by the actual scheduler.
  2992  func pollWork() bool {
  2993  	if sched.runqsize != 0 {
  2994  		return true
  2995  	}
  2996  	p := getg().m.p.ptr()
  2997  	if !runqempty(p) {
  2998  		return true
  2999  	}
  3000  	if netpollinited() && atomic.Load(&netpollWaiters) > 0 && sched.lastpoll != 0 {
  3001  		if list := netpoll(0); !list.empty() {
  3002  			injectglist(&list)
  3003  			return true
  3004  		}
  3005  	}
  3006  	return false
  3007  }
  3008  
  3009  // stealWork attempts to steal a runnable goroutine or timer from any P.
  3010  //
  3011  // If newWork is true, new work may have been readied.
  3012  //
  3013  // If now is not 0 it is the current time. stealWork returns the passed time or
  3014  // the current time if now was passed as 0.
  3015  func stealWork(now int64) (gp *g, inheritTime bool, rnow, pollUntil int64, newWork bool) {
  3016  	pp := getg().m.p.ptr()
  3017  
  3018  	ranTimer := false
  3019  
  3020  	const stealTries = 4
  3021  	for i := 0; i < stealTries; i++ {
  3022  		stealTimersOrRunNextG := i == stealTries-1
  3023  
  3024  		for enum := stealOrder.start(fastrand()); !enum.done(); enum.next() {
  3025  			if sched.gcwaiting != 0 {
  3026  				// GC work may be available.
  3027  				return nil, false, now, pollUntil, true
  3028  			}
  3029  			p2 := allp[enum.position()]
  3030  			if pp == p2 {
  3031  				continue
  3032  			}
  3033  
  3034  			// Steal timers from p2. This call to checkTimers is the only place
  3035  			// where we might hold a lock on a different P's timers. We do this
  3036  			// once on the last pass before checking runnext because stealing
  3037  			// from the other P's runnext should be the last resort, so if there
  3038  			// are timers to steal do that first.
  3039  			//
  3040  			// We only check timers on one of the stealing iterations because
  3041  			// the time stored in now doesn't change in this loop and checking
  3042  			// the timers for each P more than once with the same value of now
  3043  			// is probably a waste of time.
  3044  			//
  3045  			// timerpMask tells us whether the P may have timers at all. If it
  3046  			// can't, no need to check at all.
  3047  			if stealTimersOrRunNextG && timerpMask.read(enum.position()) {
  3048  				tnow, w, ran := checkTimers(p2, now)
  3049  				now = tnow
  3050  				if w != 0 && (pollUntil == 0 || w < pollUntil) {
  3051  					pollUntil = w
  3052  				}
  3053  				if ran {
  3054  					// Running the timers may have
  3055  					// made an arbitrary number of G's
  3056  					// ready and added them to this P's
  3057  					// local run queue. That invalidates
  3058  					// the assumption of runqsteal
  3059  					// that it always has room to add
  3060  					// stolen G's. So check now if there
  3061  					// is a local G to run.
  3062  					if gp, inheritTime := runqget(pp); gp != nil {
  3063  						return gp, inheritTime, now, pollUntil, ranTimer
  3064  					}
  3065  					ranTimer = true
  3066  				}
  3067  			}
  3068  
  3069  			// Don't bother to attempt to steal if p2 is idle.
  3070  			if !idlepMask.read(enum.position()) {
  3071  				if gp := runqsteal(pp, p2, stealTimersOrRunNextG); gp != nil {
  3072  					return gp, false, now, pollUntil, ranTimer
  3073  				}
  3074  			}
  3075  		}
  3076  	}
  3077  
  3078  	// No goroutines found to steal. Regardless, running a timer may have
  3079  	// made some goroutine ready that we missed. Indicate the next timer to
  3080  	// wait for.
  3081  	return nil, false, now, pollUntil, ranTimer
  3082  }
  3083  
  3084  // Check all Ps for a runnable G to steal.
  3085  //
  3086  // On entry we have no P. If a G is available to steal and a P is available,
  3087  // the P is returned which the caller should acquire and attempt to steal the
  3088  // work to.
  3089  func checkRunqsNoP(allpSnapshot []*p, idlepMaskSnapshot pMask) *p {
  3090  	for id, p2 := range allpSnapshot {
  3091  		if !idlepMaskSnapshot.read(uint32(id)) && !runqempty(p2) {
  3092  			lock(&sched.lock)
  3093  			pp := pidleget()
  3094  			unlock(&sched.lock)
  3095  			if pp != nil {
  3096  				return pp
  3097  			}
  3098  
  3099  			// Can't get a P, don't bother checking remaining Ps.
  3100  			break
  3101  		}
  3102  	}
  3103  
  3104  	return nil
  3105  }
  3106  
  3107  // Check all Ps for a timer expiring sooner than pollUntil.
  3108  //
  3109  // Returns updated pollUntil value.
  3110  func checkTimersNoP(allpSnapshot []*p, timerpMaskSnapshot pMask, pollUntil int64) int64 {
  3111  	for id, p2 := range allpSnapshot {
  3112  		if timerpMaskSnapshot.read(uint32(id)) {
  3113  			w := nobarrierWakeTime(p2)
  3114  			if w != 0 && (pollUntil == 0 || w < pollUntil) {
  3115  				pollUntil = w
  3116  			}
  3117  		}
  3118  	}
  3119  
  3120  	return pollUntil
  3121  }
  3122  
  3123  // Check for idle-priority GC, without a P on entry.
  3124  //
  3125  // If some GC work, a P, and a worker G are all available, the P and G will be
  3126  // returned. The returned P has not been wired yet.
  3127  func checkIdleGCNoP() (*p, *g) {
  3128  	// N.B. Since we have no P, gcBlackenEnabled may change at any time; we
  3129  	// must check again after acquiring a P.
  3130  	if atomic.Load(&gcBlackenEnabled) == 0 {
  3131  		return nil, nil
  3132  	}
  3133  	if !gcMarkWorkAvailable(nil) {
  3134  		return nil, nil
  3135  	}
  3136  
  3137  	// Work is available; we can start an idle GC worker only if there is
  3138  	// an available P and available worker G.
  3139  	//
  3140  	// We can attempt to acquire these in either order, though both have
  3141  	// synchronization concerns (see below). Workers are almost always
  3142  	// available (see comment in findRunnableGCWorker for the one case
  3143  	// there may be none). Since we're slightly less likely to find a P,
  3144  	// check for that first.
  3145  	//
  3146  	// Synchronization: note that we must hold sched.lock until we are
  3147  	// committed to keeping it. Otherwise we cannot put the unnecessary P
  3148  	// back in sched.pidle without performing the full set of idle
  3149  	// transition checks.
  3150  	//
  3151  	// If we were to check gcBgMarkWorkerPool first, we must somehow handle
  3152  	// the assumption in gcControllerState.findRunnableGCWorker that an
  3153  	// empty gcBgMarkWorkerPool is only possible if gcMarkDone is running.
  3154  	lock(&sched.lock)
  3155  	pp := pidleget()
  3156  	if pp == nil {
  3157  		unlock(&sched.lock)
  3158  		return nil, nil
  3159  	}
  3160  
  3161  	// Now that we own a P, gcBlackenEnabled can't change (as it requires
  3162  	// STW).
  3163  	if gcBlackenEnabled == 0 {
  3164  		pidleput(pp)
  3165  		unlock(&sched.lock)
  3166  		return nil, nil
  3167  	}
  3168  
  3169  	node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
  3170  	if node == nil {
  3171  		pidleput(pp)
  3172  		unlock(&sched.lock)
  3173  		return nil, nil
  3174  	}
  3175  
  3176  	unlock(&sched.lock)
  3177  
  3178  	return pp, node.gp.ptr()
  3179  }
  3180  
  3181  // wakeNetPoller wakes up the thread sleeping in the network poller if it isn't
  3182  // going to wake up before the when argument; or it wakes an idle P to service
  3183  // timers and the network poller if there isn't one already.
  3184  func wakeNetPoller(when int64) {
  3185  	if atomic.Load64(&sched.lastpoll) == 0 {
  3186  		// In findrunnable we ensure that when polling the pollUntil
  3187  		// field is either zero or the time to which the current
  3188  		// poll is expected to run. This can have a spurious wakeup
  3189  		// but should never miss a wakeup.
  3190  		pollerPollUntil := int64(atomic.Load64(&sched.pollUntil))
  3191  		if pollerPollUntil == 0 || pollerPollUntil > when {
  3192  			netpollBreak()
  3193  		}
  3194  	} else {
  3195  		// There are no threads in the network poller, try to get
  3196  		// one there so it can handle new timers.
  3197  		if GOOS != "plan9" { // Temporary workaround - see issue #42303.
  3198  			wakep()
  3199  		}
  3200  	}
  3201  }
  3202  
  3203  func resetspinning() {
  3204  	_g_ := getg()
  3205  	if !_g_.m.spinning {
  3206  		throw("resetspinning: not a spinning m")
  3207  	}
  3208  	_g_.m.spinning = false
  3209  	nmspinning := atomic.Xadd(&sched.nmspinning, -1)
  3210  	if int32(nmspinning) < 0 {
  3211  		throw("findrunnable: negative nmspinning")
  3212  	}
  3213  	// M wakeup policy is deliberately somewhat conservative, so check if we
  3214  	// need to wakeup another P here. See "Worker thread parking/unparking"
  3215  	// comment at the top of the file for details.
  3216  	wakep()
  3217  }
  3218  
  3219  // injectglist adds each runnable G on the list to some run queue,
  3220  // and clears glist. If there is no current P, they are added to the
  3221  // global queue, and up to npidle M's are started to run them.
  3222  // Otherwise, for each idle P, this adds a G to the global queue
  3223  // and starts an M. Any remaining G's are added to the current P's
  3224  // local run queue.
  3225  // This may temporarily acquire sched.lock.
  3226  // Can run concurrently with GC.
  3227  func injectglist(glist *gList) {
  3228  	if glist.empty() {
  3229  		return
  3230  	}
  3231  	if trace.enabled {
  3232  		for gp := glist.head.ptr(); gp != nil; gp = gp.schedlink.ptr() {
  3233  			traceGoUnpark(gp, 0)
  3234  		}
  3235  	}
  3236  
  3237  	// Mark all the goroutines as runnable before we put them
  3238  	// on the run queues.
  3239  	head := glist.head.ptr()
  3240  	var tail *g
  3241  	qsize := 0
  3242  	for gp := head; gp != nil; gp = gp.schedlink.ptr() {
  3243  		tail = gp
  3244  		qsize++
  3245  		casgstatus(gp, _Gwaiting, _Grunnable)
  3246  	}
  3247  
  3248  	// Turn the gList into a gQueue.
  3249  	var q gQueue
  3250  	q.head.set(head)
  3251  	q.tail.set(tail)
  3252  	*glist = gList{}
  3253  
  3254  	startIdle := func(n int) {
  3255  		for ; n != 0 && sched.npidle != 0; n-- {
  3256  			startm(nil, false)
  3257  		}
  3258  	}
  3259  
  3260  	pp := getg().m.p.ptr()
  3261  	if pp == nil {
  3262  		lock(&sched.lock)
  3263  		globrunqputbatch(&q, int32(qsize))
  3264  		unlock(&sched.lock)
  3265  		startIdle(qsize)
  3266  		return
  3267  	}
  3268  
  3269  	npidle := int(atomic.Load(&sched.npidle))
  3270  	var globq gQueue
  3271  	var n int
  3272  	for n = 0; n < npidle && !q.empty(); n++ {
  3273  		g := q.pop()
  3274  		globq.pushBack(g)
  3275  	}
  3276  	if n > 0 {
  3277  		lock(&sched.lock)
  3278  		globrunqputbatch(&globq, int32(n))
  3279  		unlock(&sched.lock)
  3280  		startIdle(n)
  3281  		qsize -= n
  3282  	}
  3283  
  3284  	if !q.empty() {
  3285  		runqputbatch(pp, &q, qsize)
  3286  	}
  3287  }
  3288  
  3289  // One round of scheduler: find a runnable goroutine and execute it.
  3290  // Never returns.
  3291  func schedule() {
  3292  	_g_ := getg()
  3293  
  3294  	if _g_.m.locks != 0 {
  3295  		throw("schedule: holding locks")
  3296  	}
  3297  
  3298  	if _g_.m.lockedg != 0 {
  3299  		stoplockedm()
  3300  		execute(_g_.m.lockedg.ptr(), false) // Never returns.
  3301  	}
  3302  
  3303  	// We should not schedule away from a g that is executing a cgo call,
  3304  	// since the cgo call is using the m's g0 stack.
  3305  	if _g_.m.incgo {
  3306  		throw("schedule: in cgo")
  3307  	}
  3308  
  3309  top:
  3310  	pp := _g_.m.p.ptr()
  3311  	pp.preempt = false
  3312  
  3313  	if sched.gcwaiting != 0 {
  3314  		gcstopm()
  3315  		goto top
  3316  	}
  3317  	if pp.runSafePointFn != 0 {
  3318  		runSafePointFn()
  3319  	}
  3320  
  3321  	// Sanity check: if we are spinning, the run queue should be empty.
  3322  	// Check this before calling checkTimers, as that might call
  3323  	// goready to put a ready goroutine on the local run queue.
  3324  	if _g_.m.spinning && (pp.runnext != 0 || pp.runqhead != pp.runqtail) {
  3325  		throw("schedule: spinning with local work")
  3326  	}
  3327  
  3328  	checkTimers(pp, 0)
  3329  
  3330  	var gp *g
  3331  	var inheritTime bool
  3332  
  3333  	// Normal goroutines will check for need to wakeP in ready,
  3334  	// but GCworkers and tracereaders will not, so the check must
  3335  	// be done here instead.
  3336  	tryWakeP := false
  3337  	if trace.enabled || trace.shutdown {
  3338  		gp = traceReader()
  3339  		if gp != nil {
  3340  			casgstatus(gp, _Gwaiting, _Grunnable)
  3341  			traceGoUnpark(gp, 0)
  3342  			tryWakeP = true
  3343  		}
  3344  	}
  3345  	if gp == nil && gcBlackenEnabled != 0 {
  3346  		gp = gcController.findRunnableGCWorker(_g_.m.p.ptr())
  3347  		if gp != nil {
  3348  			tryWakeP = true
  3349  		}
  3350  	}
  3351  	if gp == nil {
  3352  		// Check the global runnable queue once in a while to ensure fairness.
  3353  		// Otherwise two goroutines can completely occupy the local runqueue
  3354  		// by constantly respawning each other.
  3355  		if _g_.m.p.ptr().schedtick%61 == 0 && sched.runqsize > 0 {
  3356  			lock(&sched.lock)
  3357  			gp = globrunqget(_g_.m.p.ptr(), 1)
  3358  			unlock(&sched.lock)
  3359  		}
  3360  	}
  3361  	if gp == nil {
  3362  		gp, inheritTime = runqget(_g_.m.p.ptr())
  3363  		// We can see gp != nil here even if the M is spinning,
  3364  		// if checkTimers added a local goroutine via goready.
  3365  	}
  3366  	if gp == nil {
  3367  		gp, inheritTime = findrunnable() // blocks until work is available
  3368  	}
  3369  
  3370  	// This thread is going to run a goroutine and is not spinning anymore,
  3371  	// so if it was marked as spinning we need to reset it now and potentially
  3372  	// start a new spinning M.
  3373  	if _g_.m.spinning {
  3374  		resetspinning()
  3375  	}
  3376  
  3377  	if sched.disable.user && !schedEnabled(gp) {
  3378  		// Scheduling of this goroutine is disabled. Put it on
  3379  		// the list of pending runnable goroutines for when we
  3380  		// re-enable user scheduling and look again.
  3381  		lock(&sched.lock)
  3382  		if schedEnabled(gp) {
  3383  			// Something re-enabled scheduling while we
  3384  			// were acquiring the lock.
  3385  			unlock(&sched.lock)
  3386  		} else {
  3387  			sched.disable.runnable.pushBack(gp)
  3388  			sched.disable.n++
  3389  			unlock(&sched.lock)
  3390  			goto top
  3391  		}
  3392  	}
  3393  
  3394  	// If about to schedule a not-normal goroutine (a GCworker or tracereader),
  3395  	// wake a P if there is one.
  3396  	if tryWakeP {
  3397  		wakep()
  3398  	}
  3399  	if gp.lockedm != 0 {
  3400  		// Hands off own p to the locked m,
  3401  		// then blocks waiting for a new p.
  3402  		startlockedm(gp)
  3403  		goto top
  3404  	}
  3405  
  3406  	execute(gp, inheritTime)
  3407  }
  3408  
  3409  // dropg removes the association between m and the current goroutine m->curg (gp for short).
  3410  // Typically a caller sets gp's status away from Grunning and then
  3411  // immediately calls dropg to finish the job. The caller is also responsible
  3412  // for arranging that gp will be restarted using ready at an
  3413  // appropriate time. After calling dropg and arranging for gp to be
  3414  // readied later, the caller can do other work but eventually should
  3415  // call schedule to restart the scheduling of goroutines on this m.
  3416  func dropg() {
  3417  	_g_ := getg()
  3418  
  3419  	setMNoWB(&_g_.m.curg.m, nil)
  3420  	setGNoWB(&_g_.m.curg, nil)
  3421  }
  3422  
  3423  // checkTimers runs any timers for the P that are ready.
  3424  // If now is not 0 it is the current time.
  3425  // It returns the passed time or the current time if now was passed as 0.
  3426  // and the time when the next timer should run or 0 if there is no next timer,
  3427  // and reports whether it ran any timers.
  3428  // If the time when the next timer should run is not 0,
  3429  // it is always larger than the returned time.
  3430  // We pass now in and out to avoid extra calls of nanotime.
  3431  //go:yeswritebarrierrec
  3432  func checkTimers(pp *p, now int64) (rnow, pollUntil int64, ran bool) {
  3433  	// If it's not yet time for the first timer, or the first adjusted
  3434  	// timer, then there is nothing to do.
  3435  	next := int64(atomic.Load64(&pp.timer0When))
  3436  	nextAdj := int64(atomic.Load64(&pp.timerModifiedEarliest))
  3437  	if next == 0 || (nextAdj != 0 && nextAdj < next) {
  3438  		next = nextAdj
  3439  	}
  3440  
  3441  	if next == 0 {
  3442  		// No timers to run or adjust.
  3443  		return now, 0, false
  3444  	}
  3445  
  3446  	if now == 0 {
  3447  		now = nanotime()
  3448  	}
  3449  	if now < next {
  3450  		// Next timer is not ready to run, but keep going
  3451  		// if we would clear deleted timers.
  3452  		// This corresponds to the condition below where
  3453  		// we decide whether to call clearDeletedTimers.
  3454  		if pp != getg().m.p.ptr() || int(atomic.Load(&pp.deletedTimers)) <= int(atomic.Load(&pp.numTimers)/4) {
  3455  			return now, next, false
  3456  		}
  3457  	}
  3458  
  3459  	lock(&pp.timersLock)
  3460  
  3461  	if len(pp.timers) > 0 {
  3462  		adjusttimers(pp, now)
  3463  		for len(pp.timers) > 0 {
  3464  			// Note that runtimer may temporarily unlock
  3465  			// pp.timersLock.
  3466  			if tw := runtimer(pp, now); tw != 0 {
  3467  				if tw > 0 {
  3468  					pollUntil = tw
  3469  				}
  3470  				break
  3471  			}
  3472  			ran = true
  3473  		}
  3474  	}
  3475  
  3476  	// If this is the local P, and there are a lot of deleted timers,
  3477  	// clear them out. We only do this for the local P to reduce
  3478  	// lock contention on timersLock.
  3479  	if pp == getg().m.p.ptr() && int(atomic.Load(&pp.deletedTimers)) > len(pp.timers)/4 {
  3480  		clearDeletedTimers(pp)
  3481  	}
  3482  
  3483  	unlock(&pp.timersLock)
  3484  
  3485  	return now, pollUntil, ran
  3486  }
  3487  
  3488  func parkunlock_c(gp *g, lock unsafe.Pointer) bool {
  3489  	unlock((*mutex)(lock))
  3490  	return true
  3491  }
  3492  
  3493  // park continuation on g0.
  3494  func park_m(gp *g) {
  3495  	_g_ := getg()
  3496  
  3497  	if trace.enabled {
  3498  		traceGoPark(_g_.m.waittraceev, _g_.m.waittraceskip)
  3499  	}
  3500  
  3501  	casgstatus(gp, _Grunning, _Gwaiting)
  3502  	dropg()
  3503  
  3504  	if fn := _g_.m.waitunlockf; fn != nil {
  3505  		ok := fn(gp, _g_.m.waitlock)
  3506  		_g_.m.waitunlockf = nil
  3507  		_g_.m.waitlock = nil
  3508  		if !ok {
  3509  			if trace.enabled {
  3510  				traceGoUnpark(gp, 2)
  3511  			}
  3512  			casgstatus(gp, _Gwaiting, _Grunnable)
  3513  			execute(gp, true) // Schedule it back, never returns.
  3514  		}
  3515  	}
  3516  	schedule()
  3517  }
  3518  
  3519  func goschedImpl(gp *g) {
  3520  	status := readgstatus(gp)
  3521  	if status&^_Gscan != _Grunning {
  3522  		dumpgstatus(gp)
  3523  		throw("bad g status")
  3524  	}
  3525  	casgstatus(gp, _Grunning, _Grunnable)
  3526  	dropg()
  3527  	lock(&sched.lock)
  3528  	globrunqput(gp)
  3529  	unlock(&sched.lock)
  3530  
  3531  	schedule()
  3532  }
  3533  
  3534  // Gosched continuation on g0.
  3535  func gosched_m(gp *g) {
  3536  	if trace.enabled {
  3537  		traceGoSched()
  3538  	}
  3539  	goschedImpl(gp)
  3540  }
  3541  
  3542  // goschedguarded is a forbidden-states-avoided version of gosched_m
  3543  func goschedguarded_m(gp *g) {
  3544  
  3545  	if !canPreemptM(gp.m) {
  3546  		gogo(&gp.sched) // never return
  3547  	}
  3548  
  3549  	if trace.enabled {
  3550  		traceGoSched()
  3551  	}
  3552  	goschedImpl(gp)
  3553  }
  3554  
  3555  func gopreempt_m(gp *g) {
  3556  	if trace.enabled {
  3557  		traceGoPreempt()
  3558  	}
  3559  	goschedImpl(gp)
  3560  }
  3561  
  3562  // preemptPark parks gp and puts it in _Gpreempted.
  3563  //
  3564  //go:systemstack
  3565  func preemptPark(gp *g) {
  3566  	if trace.enabled {
  3567  		traceGoPark(traceEvGoBlock, 0)
  3568  	}
  3569  	status := readgstatus(gp)
  3570  	if status&^_Gscan != _Grunning {
  3571  		dumpgstatus(gp)
  3572  		throw("bad g status")
  3573  	}
  3574  	gp.waitreason = waitReasonPreempted
  3575  
  3576  	if gp.asyncSafePoint {
  3577  		// Double-check that async preemption does not
  3578  		// happen in SPWRITE assembly functions.
  3579  		// isAsyncSafePoint must exclude this case.
  3580  		f := findfunc(gp.sched.pc)
  3581  		if !f.valid() {
  3582  			throw("preempt at unknown pc")
  3583  		}
  3584  		if f.flag&funcFlag_SPWRITE != 0 {
  3585  			println("runtime: unexpected SPWRITE function", funcname(f), "in async preempt")
  3586  			throw("preempt SPWRITE")
  3587  		}
  3588  	}
  3589  
  3590  	// Transition from _Grunning to _Gscan|_Gpreempted. We can't
  3591  	// be in _Grunning when we dropg because then we'd be running
  3592  	// without an M, but the moment we're in _Gpreempted,
  3593  	// something could claim this G before we've fully cleaned it
  3594  	// up. Hence, we set the scan bit to lock down further
  3595  	// transitions until we can dropg.
  3596  	casGToPreemptScan(gp, _Grunning, _Gscan|_Gpreempted)
  3597  	dropg()
  3598  	casfrom_Gscanstatus(gp, _Gscan|_Gpreempted, _Gpreempted)
  3599  	schedule()
  3600  }
  3601  
  3602  // goyield is like Gosched, but it:
  3603  // - emits a GoPreempt trace event instead of a GoSched trace event
  3604  // - puts the current G on the runq of the current P instead of the globrunq
  3605  func goyield() {
  3606  	checkTimeouts()
  3607  	mcall(goyield_m)
  3608  }
  3609  
  3610  func goyield_m(gp *g) {
  3611  	if trace.enabled {
  3612  		traceGoPreempt()
  3613  	}
  3614  	pp := gp.m.p.ptr()
  3615  	casgstatus(gp, _Grunning, _Grunnable)
  3616  	dropg()
  3617  	runqput(pp, gp, false)
  3618  	schedule()
  3619  }
  3620  
  3621  // Finishes execution of the current goroutine.
  3622  func goexit1() {
  3623  	if raceenabled {
  3624  		racegoend()
  3625  	}
  3626  	if trace.enabled {
  3627  		traceGoEnd()
  3628  	}
  3629  	mcall(goexit0)
  3630  }
  3631  
  3632  // goexit continuation on g0.
  3633  func goexit0(gp *g) {
  3634  	_g_ := getg()
  3635  
  3636  	casgstatus(gp, _Grunning, _Gdead)
  3637  	if isSystemGoroutine(gp, false) {
  3638  		atomic.Xadd(&sched.ngsys, -1)
  3639  	}
  3640  	gp.m = nil
  3641  	locked := gp.lockedm != 0
  3642  	gp.lockedm = 0
  3643  	_g_.m.lockedg = 0
  3644  	gp.preemptStop = false
  3645  	gp.paniconfault = false
  3646  	gp._defer = nil // should be true already but just in case.
  3647  	gp._panic = nil // non-nil for Goexit during panic. points at stack-allocated data.
  3648  	gp.writebuf = nil
  3649  	gp.waitreason = 0
  3650  	gp.param = nil
  3651  	gp.labels = nil
  3652  	gp.timer = nil
  3653  
  3654  	if gcBlackenEnabled != 0 && gp.gcAssistBytes > 0 {
  3655  		// Flush assist credit to the global pool. This gives
  3656  		// better information to pacing if the application is
  3657  		// rapidly creating an exiting goroutines.
  3658  		assistWorkPerByte := float64frombits(atomic.Load64(&gcController.assistWorkPerByte))
  3659  		scanCredit := int64(assistWorkPerByte * float64(gp.gcAssistBytes))
  3660  		atomic.Xaddint64(&gcController.bgScanCredit, scanCredit)
  3661  		gp.gcAssistBytes = 0
  3662  	}
  3663  
  3664  	dropg()
  3665  
  3666  	if GOARCH == "wasm" { // no threads yet on wasm
  3667  		gfput(_g_.m.p.ptr(), gp)
  3668  		schedule() // never returns
  3669  	}
  3670  
  3671  	if _g_.m.lockedInt != 0 {
  3672  		print("invalid m->lockedInt = ", _g_.m.lockedInt, "\n")
  3673  		throw("internal lockOSThread error")
  3674  	}
  3675  	gfput(_g_.m.p.ptr(), gp)
  3676  	if locked {
  3677  		// The goroutine may have locked this thread because
  3678  		// it put it in an unusual kernel state. Kill it
  3679  		// rather than returning it to the thread pool.
  3680  
  3681  		// Return to mstart, which will release the P and exit
  3682  		// the thread.
  3683  		if GOOS != "plan9" { // See golang.org/issue/22227.
  3684  			gogo(&_g_.m.g0.sched)
  3685  		} else {
  3686  			// Clear lockedExt on plan9 since we may end up re-using
  3687  			// this thread.
  3688  			_g_.m.lockedExt = 0
  3689  		}
  3690  	}
  3691  	schedule()
  3692  }
  3693  
  3694  // save updates getg().sched to refer to pc and sp so that a following
  3695  // gogo will restore pc and sp.
  3696  //
  3697  // save must not have write barriers because invoking a write barrier
  3698  // can clobber getg().sched.
  3699  //
  3700  //go:nosplit
  3701  //go:nowritebarrierrec
  3702  func save(pc, sp uintptr) {
  3703  	_g_ := getg()
  3704  
  3705  	if _g_ == _g_.m.g0 || _g_ == _g_.m.gsignal {
  3706  		// m.g0.sched is special and must describe the context
  3707  		// for exiting the thread. mstart1 writes to it directly.
  3708  		// m.gsignal.sched should not be used at all.
  3709  		// This check makes sure save calls do not accidentally
  3710  		// run in contexts where they'd write to system g's.
  3711  		throw("save on system g not allowed")
  3712  	}
  3713  
  3714  	_g_.sched.pc = pc
  3715  	_g_.sched.sp = sp
  3716  	_g_.sched.lr = 0
  3717  	_g_.sched.ret = 0
  3718  	// We need to ensure ctxt is zero, but can't have a write
  3719  	// barrier here. However, it should always already be zero.
  3720  	// Assert that.
  3721  	if _g_.sched.ctxt != nil {
  3722  		badctxt()
  3723  	}
  3724  }
  3725  
  3726  // The goroutine g is about to enter a system call.
  3727  // Record that it's not using the cpu anymore.
  3728  // This is called only from the go syscall library and cgocall,
  3729  // not from the low-level system calls used by the runtime.
  3730  //
  3731  // Entersyscall cannot split the stack: the save must
  3732  // make g->sched refer to the caller's stack segment, because
  3733  // entersyscall is going to return immediately after.
  3734  //
  3735  // Nothing entersyscall calls can split the stack either.
  3736  // We cannot safely move the stack during an active call to syscall,
  3737  // because we do not know which of the uintptr arguments are
  3738  // really pointers (back into the stack).
  3739  // In practice, this means that we make the fast path run through
  3740  // entersyscall doing no-split things, and the slow path has to use systemstack
  3741  // to run bigger things on the system stack.
  3742  //
  3743  // reentersyscall is the entry point used by cgo callbacks, where explicitly
  3744  // saved SP and PC are restored. This is needed when exitsyscall will be called
  3745  // from a function further up in the call stack than the parent, as g->syscallsp
  3746  // must always point to a valid stack frame. entersyscall below is the normal
  3747  // entry point for syscalls, which obtains the SP and PC from the caller.
  3748  //
  3749  // Syscall tracing:
  3750  // At the start of a syscall we emit traceGoSysCall to capture the stack trace.
  3751  // If the syscall does not block, that is it, we do not emit any other events.
  3752  // If the syscall blocks (that is, P is retaken), retaker emits traceGoSysBlock;
  3753  // when syscall returns we emit traceGoSysExit and when the goroutine starts running
  3754  // (potentially instantly, if exitsyscallfast returns true) we emit traceGoStart.
  3755  // To ensure that traceGoSysExit is emitted strictly after traceGoSysBlock,
  3756  // we remember current value of syscalltick in m (_g_.m.syscalltick = _g_.m.p.ptr().syscalltick),
  3757  // whoever emits traceGoSysBlock increments p.syscalltick afterwards;
  3758  // and we wait for the increment before emitting traceGoSysExit.
  3759  // Note that the increment is done even if tracing is not enabled,
  3760  // because tracing can be enabled in the middle of syscall. We don't want the wait to hang.
  3761  //
  3762  //go:nosplit
  3763  func reentersyscall(pc, sp uintptr) {
  3764  	_g_ := getg()
  3765  
  3766  	// Disable preemption because during this function g is in Gsyscall status,
  3767  	// but can have inconsistent g->sched, do not let GC observe it.
  3768  	_g_.m.locks++
  3769  
  3770  	// Entersyscall must not call any function that might split/grow the stack.
  3771  	// (See details in comment above.)
  3772  	// Catch calls that might, by replacing the stack guard with something that
  3773  	// will trip any stack check and leaving a flag to tell newstack to die.
  3774  	_g_.stackguard0 = stackPreempt
  3775  	_g_.throwsplit = true
  3776  
  3777  	// Leave SP around for GC and traceback.
  3778  	save(pc, sp)
  3779  	_g_.syscallsp = sp
  3780  	_g_.syscallpc = pc
  3781  	casgstatus(_g_, _Grunning, _Gsyscall)
  3782  	if _g_.syscallsp < _g_.stack.lo || _g_.stack.hi < _g_.syscallsp {
  3783  		systemstack(func() {
  3784  			print("entersyscall inconsistent ", hex(_g_.syscallsp), " [", hex(_g_.stack.lo), ",", hex(_g_.stack.hi), "]\n")
  3785  			throw("entersyscall")
  3786  		})
  3787  	}
  3788  
  3789  	if trace.enabled {
  3790  		systemstack(traceGoSysCall)
  3791  		// systemstack itself clobbers g.sched.{pc,sp} and we might
  3792  		// need them later when the G is genuinely blocked in a
  3793  		// syscall
  3794  		save(pc, sp)
  3795  	}
  3796  
  3797  	if atomic.Load(&sched.sysmonwait) != 0 {
  3798  		systemstack(entersyscall_sysmon)
  3799  		save(pc, sp)
  3800  	}
  3801  
  3802  	if _g_.m.p.ptr().runSafePointFn != 0 {
  3803  		// runSafePointFn may stack split if run on this stack
  3804  		systemstack(runSafePointFn)
  3805  		save(pc, sp)
  3806  	}
  3807  
  3808  	_g_.m.syscalltick = _g_.m.p.ptr().syscalltick
  3809  	_g_.sysblocktraced = true
  3810  	pp := _g_.m.p.ptr()
  3811  	pp.m = 0
  3812  	_g_.m.oldp.set(pp)
  3813  	_g_.m.p = 0
  3814  	atomic.Store(&pp.status, _Psyscall)
  3815  	if sched.gcwaiting != 0 {
  3816  		systemstack(entersyscall_gcwait)
  3817  		save(pc, sp)
  3818  	}
  3819  
  3820  	_g_.m.locks--
  3821  }
  3822  
  3823  // Standard syscall entry used by the go syscall library and normal cgo calls.
  3824  //
  3825  // This is exported via linkname to assembly in the syscall package.
  3826  //
  3827  //go:nosplit
  3828  //go:linkname entersyscall
  3829  func entersyscall() {
  3830  	reentersyscall(getcallerpc(), getcallersp())
  3831  }
  3832  
  3833  func entersyscall_sysmon() {
  3834  	lock(&sched.lock)
  3835  	if atomic.Load(&sched.sysmonwait) != 0 {
  3836  		atomic.Store(&sched.sysmonwait, 0)
  3837  		notewakeup(&sched.sysmonnote)
  3838  	}
  3839  	unlock(&sched.lock)
  3840  }
  3841  
  3842  func entersyscall_gcwait() {
  3843  	_g_ := getg()
  3844  	_p_ := _g_.m.oldp.ptr()
  3845  
  3846  	lock(&sched.lock)
  3847  	if sched.stopwait > 0 && atomic.Cas(&_p_.status, _Psyscall, _Pgcstop) {
  3848  		if trace.enabled {
  3849  			traceGoSysBlock(_p_)
  3850  			traceProcStop(_p_)
  3851  		}
  3852  		_p_.syscalltick++
  3853  		if sched.stopwait--; sched.stopwait == 0 {
  3854  			notewakeup(&sched.stopnote)
  3855  		}
  3856  	}
  3857  	unlock(&sched.lock)
  3858  }
  3859  
  3860  // The same as entersyscall(), but with a hint that the syscall is blocking.
  3861  //go:nosplit
  3862  func entersyscallblock() {
  3863  	_g_ := getg()
  3864  
  3865  	_g_.m.locks++ // see comment in entersyscall
  3866  	_g_.throwsplit = true
  3867  	_g_.stackguard0 = stackPreempt // see comment in entersyscall
  3868  	_g_.m.syscalltick = _g_.m.p.ptr().syscalltick
  3869  	_g_.sysblocktraced = true
  3870  	_g_.m.p.ptr().syscalltick++
  3871  
  3872  	// Leave SP around for GC and traceback.
  3873  	pc := getcallerpc()
  3874  	sp := getcallersp()
  3875  	save(pc, sp)
  3876  	_g_.syscallsp = _g_.sched.sp
  3877  	_g_.syscallpc = _g_.sched.pc
  3878  	if _g_.syscallsp < _g_.stack.lo || _g_.stack.hi < _g_.syscallsp {
  3879  		sp1 := sp
  3880  		sp2 := _g_.sched.sp
  3881  		sp3 := _g_.syscallsp
  3882  		systemstack(func() {
  3883  			print("entersyscallblock inconsistent ", hex(sp1), " ", hex(sp2), " ", hex(sp3), " [", hex(_g_.stack.lo), ",", hex(_g_.stack.hi), "]\n")
  3884  			throw("entersyscallblock")
  3885  		})
  3886  	}
  3887  	casgstatus(_g_, _Grunning, _Gsyscall)
  3888  	if _g_.syscallsp < _g_.stack.lo || _g_.stack.hi < _g_.syscallsp {
  3889  		systemstack(func() {
  3890  			print("entersyscallblock inconsistent ", hex(sp), " ", hex(_g_.sched.sp), " ", hex(_g_.syscallsp), " [", hex(_g_.stack.lo), ",", hex(_g_.stack.hi), "]\n")
  3891  			throw("entersyscallblock")
  3892  		})
  3893  	}
  3894  
  3895  	systemstack(entersyscallblock_handoff)
  3896  
  3897  	// Resave for traceback during blocked call.
  3898  	save(getcallerpc(), getcallersp())
  3899  
  3900  	_g_.m.locks--
  3901  }
  3902  
  3903  func entersyscallblock_handoff() {
  3904  	if trace.enabled {
  3905  		traceGoSysCall()
  3906  		traceGoSysBlock(getg().m.p.ptr())
  3907  	}
  3908  	handoffp(releasep())
  3909  }
  3910  
  3911  // The goroutine g exited its system call.
  3912  // Arrange for it to run on a cpu again.
  3913  // This is called only from the go syscall library, not
  3914  // from the low-level system calls used by the runtime.
  3915  //
  3916  // Write barriers are not allowed because our P may have been stolen.
  3917  //
  3918  // This is exported via linkname to assembly in the syscall package.
  3919  //
  3920  //go:nosplit
  3921  //go:nowritebarrierrec
  3922  //go:linkname exitsyscall
  3923  func exitsyscall() {
  3924  	_g_ := getg()
  3925  
  3926  	_g_.m.locks++ // see comment in entersyscall
  3927  	if getcallersp() > _g_.syscallsp {
  3928  		throw("exitsyscall: syscall frame is no longer valid")
  3929  	}
  3930  
  3931  	_g_.waitsince = 0
  3932  	oldp := _g_.m.oldp.ptr()
  3933  	_g_.m.oldp = 0
  3934  	if exitsyscallfast(oldp) {
  3935  		if trace.enabled {
  3936  			if oldp != _g_.m.p.ptr() || _g_.m.syscalltick != _g_.m.p.ptr().syscalltick {
  3937  				systemstack(traceGoStart)
  3938  			}
  3939  		}
  3940  		// There's a cpu for us, so we can run.
  3941  		_g_.m.p.ptr().syscalltick++
  3942  		// We need to cas the status and scan before resuming...
  3943  		casgstatus(_g_, _Gsyscall, _Grunning)
  3944  
  3945  		// Garbage collector isn't running (since we are),
  3946  		// so okay to clear syscallsp.
  3947  		_g_.syscallsp = 0
  3948  		_g_.m.locks--
  3949  		if _g_.preempt {
  3950  			// restore the preemption request in case we've cleared it in newstack
  3951  			_g_.stackguard0 = stackPreempt
  3952  		} else {
  3953  			// otherwise restore the real _StackGuard, we've spoiled it in entersyscall/entersyscallblock
  3954  			_g_.stackguard0 = _g_.stack.lo + _StackGuard
  3955  		}
  3956  		_g_.throwsplit = false
  3957  
  3958  		if sched.disable.user && !schedEnabled(_g_) {
  3959  			// Scheduling of this goroutine is disabled.
  3960  			Gosched()
  3961  		}
  3962  
  3963  		return
  3964  	}
  3965  
  3966  	_g_.sysexitticks = 0
  3967  	if trace.enabled {
  3968  		// Wait till traceGoSysBlock event is emitted.
  3969  		// This ensures consistency of the trace (the goroutine is started after it is blocked).
  3970  		for oldp != nil && oldp.syscalltick == _g_.m.syscalltick {
  3971  			osyield()
  3972  		}
  3973  		// We can't trace syscall exit right now because we don't have a P.
  3974  		// Tracing code can invoke write barriers that cannot run without a P.
  3975  		// So instead we remember the syscall exit time and emit the event
  3976  		// in execute when we have a P.
  3977  		_g_.sysexitticks = cputicks()
  3978  	}
  3979  
  3980  	_g_.m.locks--
  3981  
  3982  	// Call the scheduler.
  3983  	mcall(exitsyscall0)
  3984  
  3985  	// Scheduler returned, so we're allowed to run now.
  3986  	// Delete the syscallsp information that we left for
  3987  	// the garbage collector during the system call.
  3988  	// Must wait until now because until gosched returns
  3989  	// we don't know for sure that the garbage collector
  3990  	// is not running.
  3991  	_g_.syscallsp = 0
  3992  	_g_.m.p.ptr().syscalltick++
  3993  	_g_.throwsplit = false
  3994  }
  3995  
  3996  //go:nosplit
  3997  func exitsyscallfast(oldp *p) bool {
  3998  	_g_ := getg()
  3999  
  4000  	// Freezetheworld sets stopwait but does not retake P's.
  4001  	if sched.stopwait == freezeStopWait {
  4002  		return false
  4003  	}
  4004  
  4005  	// Try to re-acquire the last P.
  4006  	if oldp != nil && oldp.status == _Psyscall && atomic.Cas(&oldp.status, _Psyscall, _Pidle) {
  4007  		// There's a cpu for us, so we can run.
  4008  		wirep(oldp)
  4009  		exitsyscallfast_reacquired()
  4010  		return true
  4011  	}
  4012  
  4013  	// Try to get any other idle P.
  4014  	if sched.pidle != 0 {
  4015  		var ok bool
  4016  		systemstack(func() {
  4017  			ok = exitsyscallfast_pidle()
  4018  			if ok && trace.enabled {
  4019  				if oldp != nil {
  4020  					// Wait till traceGoSysBlock event is emitted.
  4021  					// This ensures consistency of the trace (the goroutine is started after it is blocked).
  4022  					for oldp.syscalltick == _g_.m.syscalltick {
  4023  						osyield()
  4024  					}
  4025  				}
  4026  				traceGoSysExit(0)
  4027  			}
  4028  		})
  4029  		if ok {
  4030  			return true
  4031  		}
  4032  	}
  4033  	return false
  4034  }
  4035  
  4036  // exitsyscallfast_reacquired is the exitsyscall path on which this G
  4037  // has successfully reacquired the P it was running on before the
  4038  // syscall.
  4039  //
  4040  //go:nosplit
  4041  func exitsyscallfast_reacquired() {
  4042  	_g_ := getg()
  4043  	if _g_.m.syscalltick != _g_.m.p.ptr().syscalltick {
  4044  		if trace.enabled {
  4045  			// The p was retaken and then enter into syscall again (since _g_.m.syscalltick has changed).
  4046  			// traceGoSysBlock for this syscall was already emitted,
  4047  			// but here we effectively retake the p from the new syscall running on the same p.
  4048  			systemstack(func() {
  4049  				// Denote blocking of the new syscall.
  4050  				traceGoSysBlock(_g_.m.p.ptr())
  4051  				// Denote completion of the current syscall.
  4052  				traceGoSysExit(0)
  4053  			})
  4054  		}
  4055  		_g_.m.p.ptr().syscalltick++
  4056  	}
  4057  }
  4058  
  4059  func exitsyscallfast_pidle() bool {
  4060  	lock(&sched.lock)
  4061  	_p_ := pidleget()
  4062  	if _p_ != nil && atomic.Load(&sched.sysmonwait) != 0 {
  4063  		atomic.Store(&sched.sysmonwait, 0)
  4064  		notewakeup(&sched.sysmonnote)
  4065  	}
  4066  	unlock(&sched.lock)
  4067  	if _p_ != nil {
  4068  		acquirep(_p_)
  4069  		return true
  4070  	}
  4071  	return false
  4072  }
  4073  
  4074  // exitsyscall slow path on g0.
  4075  // Failed to acquire P, enqueue gp as runnable.
  4076  //
  4077  // Called via mcall, so gp is the calling g from this M.
  4078  //
  4079  //go:nowritebarrierrec
  4080  func exitsyscall0(gp *g) {
  4081  	casgstatus(gp, _Gsyscall, _Grunnable)
  4082  	dropg()
  4083  	lock(&sched.lock)
  4084  	var _p_ *p
  4085  	if schedEnabled(gp) {
  4086  		_p_ = pidleget()
  4087  	}
  4088  	var locked bool
  4089  	if _p_ == nil {
  4090  		globrunqput(gp)
  4091  
  4092  		// Below, we stoplockedm if gp is locked. globrunqput releases
  4093  		// ownership of gp, so we must check if gp is locked prior to
  4094  		// committing the release by unlocking sched.lock, otherwise we
  4095  		// could race with another M transitioning gp from unlocked to
  4096  		// locked.
  4097  		locked = gp.lockedm != 0
  4098  	} else if atomic.Load(&sched.sysmonwait) != 0 {
  4099  		atomic.Store(&sched.sysmonwait, 0)
  4100  		notewakeup(&sched.sysmonnote)
  4101  	}
  4102  	unlock(&sched.lock)
  4103  	if _p_ != nil {
  4104  		acquirep(_p_)
  4105  		execute(gp, false) // Never returns.
  4106  	}
  4107  	if locked {
  4108  		// Wait until another thread schedules gp and so m again.
  4109  		//
  4110  		// N.B. lockedm must be this M, as this g was running on this M
  4111  		// before entersyscall.
  4112  		stoplockedm()
  4113  		execute(gp, false) // Never returns.
  4114  	}
  4115  	stopm()
  4116  	schedule() // Never returns.
  4117  }
  4118  
  4119  func beforefork() {
  4120  	gp := getg().m.curg
  4121  
  4122  	// Block signals during a fork, so that the child does not run
  4123  	// a signal handler before exec if a signal is sent to the process
  4124  	// group. See issue #18600.
  4125  	gp.m.locks++
  4126  	sigsave(&gp.m.sigmask)
  4127  	sigblock(false)
  4128  
  4129  	// This function is called before fork in syscall package.
  4130  	// Code between fork and exec must not allocate memory nor even try to grow stack.
  4131  	// Here we spoil g->_StackGuard to reliably detect any attempts to grow stack.
  4132  	// runtime_AfterFork will undo this in parent process, but not in child.
  4133  	gp.stackguard0 = stackFork
  4134  }
  4135  
  4136  // Called from syscall package before fork.
  4137  //go:linkname syscall_runtime_BeforeFork syscall.runtime_BeforeFork
  4138  //go:nosplit
  4139  func syscall_runtime_BeforeFork() {
  4140  	systemstack(beforefork)
  4141  }
  4142  
  4143  func afterfork() {
  4144  	gp := getg().m.curg
  4145  
  4146  	// See the comments in beforefork.
  4147  	gp.stackguard0 = gp.stack.lo + _StackGuard
  4148  
  4149  	msigrestore(gp.m.sigmask)
  4150  
  4151  	gp.m.locks--
  4152  }
  4153  
  4154  // Called from syscall package after fork in parent.
  4155  //go:linkname syscall_runtime_AfterFork syscall.runtime_AfterFork
  4156  //go:nosplit
  4157  func syscall_runtime_AfterFork() {
  4158  	systemstack(afterfork)
  4159  }
  4160  
  4161  // inForkedChild is true while manipulating signals in the child process.
  4162  // This is used to avoid calling libc functions in case we are using vfork.
  4163  var inForkedChild bool
  4164  
  4165  // Called from syscall package after fork in child.
  4166  // It resets non-sigignored signals to the default handler, and
  4167  // restores the signal mask in preparation for the exec.
  4168  //
  4169  // Because this might be called during a vfork, and therefore may be
  4170  // temporarily sharing address space with the parent process, this must
  4171  // not change any global variables or calling into C code that may do so.
  4172  //
  4173  //go:linkname syscall_runtime_AfterForkInChild syscall.runtime_AfterForkInChild
  4174  //go:nosplit
  4175  //go:nowritebarrierrec
  4176  func syscall_runtime_AfterForkInChild() {
  4177  	// It's OK to change the global variable inForkedChild here
  4178  	// because we are going to change it back. There is no race here,
  4179  	// because if we are sharing address space with the parent process,
  4180  	// then the parent process can not be running concurrently.
  4181  	inForkedChild = true
  4182  
  4183  	clearSignalHandlers()
  4184  
  4185  	// When we are the child we are the only thread running,
  4186  	// so we know that nothing else has changed gp.m.sigmask.
  4187  	msigrestore(getg().m.sigmask)
  4188  
  4189  	inForkedChild = false
  4190  }
  4191  
  4192  // pendingPreemptSignals is the number of preemption signals
  4193  // that have been sent but not received. This is only used on Darwin.
  4194  // For #41702.
  4195  var pendingPreemptSignals uint32
  4196  
  4197  // Called from syscall package before Exec.
  4198  //go:linkname syscall_runtime_BeforeExec syscall.runtime_BeforeExec
  4199  func syscall_runtime_BeforeExec() {
  4200  	// Prevent thread creation during exec.
  4201  	execLock.lock()
  4202  
  4203  	// On Darwin, wait for all pending preemption signals to
  4204  	// be received. See issue #41702.
  4205  	if GOOS == "darwin" || GOOS == "ios" {
  4206  		for int32(atomic.Load(&pendingPreemptSignals)) > 0 {
  4207  			osyield()
  4208  		}
  4209  	}
  4210  }
  4211  
  4212  // Called from syscall package after Exec.
  4213  //go:linkname syscall_runtime_AfterExec syscall.runtime_AfterExec
  4214  func syscall_runtime_AfterExec() {
  4215  	execLock.unlock()
  4216  }
  4217  
  4218  // Allocate a new g, with a stack big enough for stacksize bytes.
  4219  func malg(stacksize int32) *g {
  4220  	newg := new(g)
  4221  	if stacksize >= 0 {
  4222  		stacksize = round2(_StackSystem + stacksize)
  4223  		systemstack(func() {
  4224  			newg.stack = stackalloc(uint32(stacksize))
  4225  		})
  4226  		newg.stackguard0 = newg.stack.lo + _StackGuard
  4227  		newg.stackguard1 = ^uintptr(0)
  4228  		// Clear the bottom word of the stack. We record g
  4229  		// there on gsignal stack during VDSO on ARM and ARM64.
  4230  		*(*uintptr)(unsafe.Pointer(newg.stack.lo)) = 0
  4231  	}
  4232  	return newg
  4233  }
  4234  
  4235  // Create a new g running fn with siz bytes of arguments.
  4236  // Put it on the queue of g's waiting to run.
  4237  // The compiler turns a go statement into a call to this.
  4238  //
  4239  // The stack layout of this call is unusual: it assumes that the
  4240  // arguments to pass to fn are on the stack sequentially immediately
  4241  // after &fn. Hence, they are logically part of newproc's argument
  4242  // frame, even though they don't appear in its signature (and can't
  4243  // because their types differ between call sites).
  4244  //
  4245  // This must be nosplit because this stack layout means there are
  4246  // untyped arguments in newproc's argument frame. Stack copies won't
  4247  // be able to adjust them and stack splits won't be able to copy them.
  4248  //
  4249  //go:nosplit
  4250  func newproc(siz int32, fn *funcval) {
  4251  	argp := add(unsafe.Pointer(&fn), sys.PtrSize)
  4252  	gp := getg()
  4253  	pc := getcallerpc()
  4254  	systemstack(func() {
  4255  		newg := newproc1(fn, argp, siz, gp, pc)
  4256  
  4257  		_p_ := getg().m.p.ptr()
  4258  		runqput(_p_, newg, true)
  4259  
  4260  		if mainStarted {
  4261  			wakep()
  4262  		}
  4263  	})
  4264  }
  4265  
  4266  // Create a new g in state _Grunnable, starting at fn, with narg bytes
  4267  // of arguments starting at argp. callerpc is the address of the go
  4268  // statement that created this. The caller is responsible for adding
  4269  // the new g to the scheduler.
  4270  //
  4271  // This must run on the system stack because it's the continuation of
  4272  // newproc, which cannot split the stack.
  4273  //
  4274  //go:systemstack
  4275  func newproc1(fn *funcval, argp unsafe.Pointer, narg int32, callergp *g, callerpc uintptr) *g {
  4276  	if goexperiment.RegabiDefer && narg != 0 {
  4277  		// TODO: When we commit to GOEXPERIMENT=regabidefer,
  4278  		// rewrite the comments for newproc and newproc1.
  4279  		// newproc will no longer have a funny stack layout or
  4280  		// need to be nosplit.
  4281  		throw("go with non-empty frame")
  4282  	}
  4283  
  4284  	_g_ := getg()
  4285  
  4286  	if fn == nil {
  4287  		_g_.m.throwing = -1 // do not dump full stacks
  4288  		throw("go of nil func value")
  4289  	}
  4290  	acquirem() // disable preemption because it can be holding p in a local var
  4291  	siz := narg
  4292  	siz = (siz + 7) &^ 7
  4293  
  4294  	// We could allocate a larger initial stack if necessary.
  4295  	// Not worth it: this is almost always an error.
  4296  	// 4*PtrSize: extra space added below
  4297  	// PtrSize: caller's LR (arm) or return address (x86, in gostartcall).
  4298  	if siz >= _StackMin-4*sys.PtrSize-sys.PtrSize {
  4299  		throw("newproc: function arguments too large for new goroutine")
  4300  	}
  4301  
  4302  	_p_ := _g_.m.p.ptr()
  4303  	newg := gfget(_p_)
  4304  	if newg == nil {
  4305  		newg = malg(_StackMin)
  4306  		casgstatus(newg, _Gidle, _Gdead)
  4307  		allgadd(newg) // publishes with a g->status of Gdead so GC scanner doesn't look at uninitialized stack.
  4308  	}
  4309  	if newg.stack.hi == 0 {
  4310  		throw("newproc1: newg missing stack")
  4311  	}
  4312  
  4313  	if readgstatus(newg) != _Gdead {
  4314  		throw("newproc1: new g is not Gdead")
  4315  	}
  4316  
  4317  	totalSize := 4*sys.PtrSize + uintptr(siz) + sys.MinFrameSize // extra space in case of reads slightly beyond frame
  4318  	totalSize += -totalSize & (sys.StackAlign - 1)               // align to StackAlign
  4319  	sp := newg.stack.hi - totalSize
  4320  	spArg := sp
  4321  	if usesLR {
  4322  		// caller's LR
  4323  		*(*uintptr)(unsafe.Pointer(sp)) = 0
  4324  		prepGoExitFrame(sp)
  4325  		spArg += sys.MinFrameSize
  4326  	}
  4327  	if narg > 0 {
  4328  		memmove(unsafe.Pointer(spArg), argp, uintptr(narg))
  4329  		// This is a stack-to-stack copy. If write barriers
  4330  		// are enabled and the source stack is grey (the
  4331  		// destination is always black), then perform a
  4332  		// barrier copy. We do this *after* the memmove
  4333  		// because the destination stack may have garbage on
  4334  		// it.
  4335  		if writeBarrier.needed && !_g_.m.curg.gcscandone {
  4336  			f := findfunc(fn.fn)
  4337  			stkmap := (*stackmap)(funcdata(f, _FUNCDATA_ArgsPointerMaps))
  4338  			if stkmap.nbit > 0 {
  4339  				// We're in the prologue, so it's always stack map index 0.
  4340  				bv := stackmapdata(stkmap, 0)
  4341  				bulkBarrierBitmap(spArg, spArg, uintptr(bv.n)*sys.PtrSize, 0, bv.bytedata)
  4342  			}
  4343  		}
  4344  	}
  4345  
  4346  	memclrNoHeapPointers(unsafe.Pointer(&newg.sched), unsafe.Sizeof(newg.sched))
  4347  	newg.sched.sp = sp
  4348  	newg.stktopsp = sp
  4349  	newg.sched.pc = abi.FuncPCABI0(goexit) + sys.PCQuantum // +PCQuantum so that previous instruction is in same function
  4350  	newg.sched.g = guintptr(unsafe.Pointer(newg))
  4351  	gostartcallfn(&newg.sched, fn)
  4352  	newg.gopc = callerpc
  4353  	newg.ancestors = saveAncestors(callergp)
  4354  	newg.startpc = fn.fn
  4355  	if _g_.m.curg != nil {
  4356  		newg.labels = _g_.m.curg.labels
  4357  	}
  4358  	if isSystemGoroutine(newg, false) {
  4359  		atomic.Xadd(&sched.ngsys, +1)
  4360  	}
  4361  	// Track initial transition?
  4362  	newg.trackingSeq = uint8(fastrand())
  4363  	if newg.trackingSeq%gTrackingPeriod == 0 {
  4364  		newg.tracking = true
  4365  	}
  4366  	casgstatus(newg, _Gdead, _Grunnable)
  4367  
  4368  	if _p_.goidcache == _p_.goidcacheend {
  4369  		// Sched.goidgen is the last allocated id,
  4370  		// this batch must be [sched.goidgen+1, sched.goidgen+GoidCacheBatch].
  4371  		// At startup sched.goidgen=0, so main goroutine receives goid=1.
  4372  		_p_.goidcache = atomic.Xadd64(&sched.goidgen, _GoidCacheBatch)
  4373  		_p_.goidcache -= _GoidCacheBatch - 1
  4374  		_p_.goidcacheend = _p_.goidcache + _GoidCacheBatch
  4375  	}
  4376  	newg.goid = int64(_p_.goidcache)
  4377  	_p_.goidcache++
  4378  	if raceenabled {
  4379  		newg.racectx = racegostart(callerpc)
  4380  	}
  4381  	if trace.enabled {
  4382  		traceGoCreate(newg, newg.startpc)
  4383  	}
  4384  	releasem(_g_.m)
  4385  
  4386  	return newg
  4387  }
  4388  
  4389  // saveAncestors copies previous ancestors of the given caller g and
  4390  // includes infor for the current caller into a new set of tracebacks for
  4391  // a g being created.
  4392  func saveAncestors(callergp *g) *[]ancestorInfo {
  4393  	// Copy all prior info, except for the root goroutine (goid 0).
  4394  	if debug.tracebackancestors <= 0 || callergp.goid == 0 {
  4395  		return nil
  4396  	}
  4397  	var callerAncestors []ancestorInfo
  4398  	if callergp.ancestors != nil {
  4399  		callerAncestors = *callergp.ancestors
  4400  	}
  4401  	n := int32(len(callerAncestors)) + 1
  4402  	if n > debug.tracebackancestors {
  4403  		n = debug.tracebackancestors
  4404  	}
  4405  	ancestors := make([]ancestorInfo, n)
  4406  	copy(ancestors[1:], callerAncestors)
  4407  
  4408  	var pcs [_TracebackMaxFrames]uintptr
  4409  	npcs := gcallers(callergp, 0, pcs[:])
  4410  	ipcs := make([]uintptr, npcs)
  4411  	copy(ipcs, pcs[:])
  4412  	ancestors[0] = ancestorInfo{
  4413  		pcs:  ipcs,
  4414  		goid: callergp.goid,
  4415  		gopc: callergp.gopc,
  4416  	}
  4417  
  4418  	ancestorsp := new([]ancestorInfo)
  4419  	*ancestorsp = ancestors
  4420  	return ancestorsp
  4421  }
  4422  
  4423  // Put on gfree list.
  4424  // If local list is too long, transfer a batch to the global list.
  4425  func gfput(_p_ *p, gp *g) {
  4426  	if readgstatus(gp) != _Gdead {
  4427  		throw("gfput: bad status (not Gdead)")
  4428  	}
  4429  
  4430  	stksize := gp.stack.hi - gp.stack.lo
  4431  
  4432  	if stksize != _FixedStack {
  4433  		// non-standard stack size - free it.
  4434  		stackfree(gp.stack)
  4435  		gp.stack.lo = 0
  4436  		gp.stack.hi = 0
  4437  		gp.stackguard0 = 0
  4438  	}
  4439  
  4440  	_p_.gFree.push(gp)
  4441  	_p_.gFree.n++
  4442  	if _p_.gFree.n >= 64 {
  4443  		var (
  4444  			inc      int32
  4445  			stackQ   gQueue
  4446  			noStackQ gQueue
  4447  		)
  4448  		for _p_.gFree.n >= 32 {
  4449  			gp = _p_.gFree.pop()
  4450  			_p_.gFree.n--
  4451  			if gp.stack.lo == 0 {
  4452  				noStackQ.push(gp)
  4453  			} else {
  4454  				stackQ.push(gp)
  4455  			}
  4456  			inc++
  4457  		}
  4458  		lock(&sched.gFree.lock)
  4459  		sched.gFree.noStack.pushAll(noStackQ)
  4460  		sched.gFree.stack.pushAll(stackQ)
  4461  		sched.gFree.n += inc
  4462  		unlock(&sched.gFree.lock)
  4463  	}
  4464  }
  4465  
  4466  // Get from gfree list.
  4467  // If local list is empty, grab a batch from global list.
  4468  func gfget(_p_ *p) *g {
  4469  retry:
  4470  	if _p_.gFree.empty() && (!sched.gFree.stack.empty() || !sched.gFree.noStack.empty()) {
  4471  		lock(&sched.gFree.lock)
  4472  		// Move a batch of free Gs to the P.
  4473  		for _p_.gFree.n < 32 {
  4474  			// Prefer Gs with stacks.
  4475  			gp := sched.gFree.stack.pop()
  4476  			if gp == nil {
  4477  				gp = sched.gFree.noStack.pop()
  4478  				if gp == nil {
  4479  					break
  4480  				}
  4481  			}
  4482  			sched.gFree.n--
  4483  			_p_.gFree.push(gp)
  4484  			_p_.gFree.n++
  4485  		}
  4486  		unlock(&sched.gFree.lock)
  4487  		goto retry
  4488  	}
  4489  	gp := _p_.gFree.pop()
  4490  	if gp == nil {
  4491  		return nil
  4492  	}
  4493  	_p_.gFree.n--
  4494  	if gp.stack.lo == 0 {
  4495  		// Stack was deallocated in gfput. Allocate a new one.
  4496  		systemstack(func() {
  4497  			gp.stack = stackalloc(_FixedStack)
  4498  		})
  4499  		gp.stackguard0 = gp.stack.lo + _StackGuard
  4500  	} else {
  4501  		if raceenabled {
  4502  			racemalloc(unsafe.Pointer(gp.stack.lo), gp.stack.hi-gp.stack.lo)
  4503  		}
  4504  		if msanenabled {
  4505  			msanmalloc(unsafe.Pointer(gp.stack.lo), gp.stack.hi-gp.stack.lo)
  4506  		}
  4507  	}
  4508  	return gp
  4509  }
  4510  
  4511  // Purge all cached G's from gfree list to the global list.
  4512  func gfpurge(_p_ *p) {
  4513  	var (
  4514  		inc      int32
  4515  		stackQ   gQueue
  4516  		noStackQ gQueue
  4517  	)
  4518  	for !_p_.gFree.empty() {
  4519  		gp := _p_.gFree.pop()
  4520  		_p_.gFree.n--
  4521  		if gp.stack.lo == 0 {
  4522  			noStackQ.push(gp)
  4523  		} else {
  4524  			stackQ.push(gp)
  4525  		}
  4526  		inc++
  4527  	}
  4528  	lock(&sched.gFree.lock)
  4529  	sched.gFree.noStack.pushAll(noStackQ)
  4530  	sched.gFree.stack.pushAll(stackQ)
  4531  	sched.gFree.n += inc
  4532  	unlock(&sched.gFree.lock)
  4533  }
  4534  
  4535  // Breakpoint executes a breakpoint trap.
  4536  func Breakpoint() {
  4537  	breakpoint()
  4538  }
  4539  
  4540  // dolockOSThread is called by LockOSThread and lockOSThread below
  4541  // after they modify m.locked. Do not allow preemption during this call,
  4542  // or else the m might be different in this function than in the caller.
  4543  //go:nosplit
  4544  func dolockOSThread() {
  4545  	if GOARCH == "wasm" {
  4546  		return // no threads on wasm yet
  4547  	}
  4548  	_g_ := getg()
  4549  	_g_.m.lockedg.set(_g_)
  4550  	_g_.lockedm.set(_g_.m)
  4551  }
  4552  
  4553  //go:nosplit
  4554  
  4555  // LockOSThread wires the calling goroutine to its current operating system thread.
  4556  // The calling goroutine will always execute in that thread,
  4557  // and no other goroutine will execute in it,
  4558  // until the calling goroutine has made as many calls to
  4559  // UnlockOSThread as to LockOSThread.
  4560  // If the calling goroutine exits without unlocking the thread,
  4561  // the thread will be terminated.
  4562  //
  4563  // All init functions are run on the startup thread. Calling LockOSThread
  4564  // from an init function will cause the main function to be invoked on
  4565  // that thread.
  4566  //
  4567  // A goroutine should call LockOSThread before calling OS services or
  4568  // non-Go library functions that depend on per-thread state.
  4569  func LockOSThread() {
  4570  	if atomic.Load(&newmHandoff.haveTemplateThread) == 0 && GOOS != "plan9" {
  4571  		// If we need to start a new thread from the locked
  4572  		// thread, we need the template thread. Start it now
  4573  		// while we're in a known-good state.
  4574  		startTemplateThread()
  4575  	}
  4576  	_g_ := getg()
  4577  	_g_.m.lockedExt++
  4578  	if _g_.m.lockedExt == 0 {
  4579  		_g_.m.lockedExt--
  4580  		panic("LockOSThread nesting overflow")
  4581  	}
  4582  	dolockOSThread()
  4583  }
  4584  
  4585  //go:nosplit
  4586  func lockOSThread() {
  4587  	getg().m.lockedInt++
  4588  	dolockOSThread()
  4589  }
  4590  
  4591  // dounlockOSThread is called by UnlockOSThread and unlockOSThread below
  4592  // after they update m->locked. Do not allow preemption during this call,
  4593  // or else the m might be in different in this function than in the caller.
  4594  //go:nosplit
  4595  func dounlockOSThread() {
  4596  	if GOARCH == "wasm" {
  4597  		return // no threads on wasm yet
  4598  	}
  4599  	_g_ := getg()
  4600  	if _g_.m.lockedInt != 0 || _g_.m.lockedExt != 0 {
  4601  		return
  4602  	}
  4603  	_g_.m.lockedg = 0
  4604  	_g_.lockedm = 0
  4605  }
  4606  
  4607  //go:nosplit
  4608  
  4609  // UnlockOSThread undoes an earlier call to LockOSThread.
  4610  // If this drops the number of active LockOSThread calls on the
  4611  // calling goroutine to zero, it unwires the calling goroutine from
  4612  // its fixed operating system thread.
  4613  // If there are no active LockOSThread calls, this is a no-op.
  4614  //
  4615  // Before calling UnlockOSThread, the caller must ensure that the OS
  4616  // thread is suitable for running other goroutines. If the caller made
  4617  // any permanent changes to the state of the thread that would affect
  4618  // other goroutines, it should not call this function and thus leave
  4619  // the goroutine locked to the OS thread until the goroutine (and
  4620  // hence the thread) exits.
  4621  func UnlockOSThread() {
  4622  	_g_ := getg()
  4623  	if _g_.m.lockedExt == 0 {
  4624  		return
  4625  	}
  4626  	_g_.m.lockedExt--
  4627  	dounlockOSThread()
  4628  }
  4629  
  4630  //go:nosplit
  4631  func unlockOSThread() {
  4632  	_g_ := getg()
  4633  	if _g_.m.lockedInt == 0 {
  4634  		systemstack(badunlockosthread)
  4635  	}
  4636  	_g_.m.lockedInt--
  4637  	dounlockOSThread()
  4638  }
  4639  
  4640  func badunlockosthread() {
  4641  	throw("runtime: internal error: misuse of lockOSThread/unlockOSThread")
  4642  }
  4643  
  4644  func gcount() int32 {
  4645  	n := int32(atomic.Loaduintptr(&allglen)) - sched.gFree.n - int32(atomic.Load(&sched.ngsys))
  4646  	for _, _p_ := range allp {
  4647  		n -= _p_.gFree.n
  4648  	}
  4649  
  4650  	// All these variables can be changed concurrently, so the result can be inconsistent.
  4651  	// But at least the current goroutine is running.
  4652  	if n < 1 {
  4653  		n = 1
  4654  	}
  4655  	return n
  4656  }
  4657  
  4658  func mcount() int32 {
  4659  	return int32(sched.mnext - sched.nmfreed)
  4660  }
  4661  
  4662  var prof struct {
  4663  	signalLock uint32
  4664  	hz         int32
  4665  }
  4666  
  4667  func _System()                    { _System() }
  4668  func _ExternalCode()              { _ExternalCode() }
  4669  func _LostExternalCode()          { _LostExternalCode() }
  4670  func _GC()                        { _GC() }
  4671  func _LostSIGPROFDuringAtomic64() { _LostSIGPROFDuringAtomic64() }
  4672  func _VDSO()                      { _VDSO() }
  4673  
  4674  // Called if we receive a SIGPROF signal.
  4675  // Called by the signal handler, may run during STW.
  4676  //go:nowritebarrierrec
  4677  func sigprof(pc, sp, lr uintptr, gp *g, mp *m) {
  4678  	if prof.hz == 0 {
  4679  		return
  4680  	}
  4681  
  4682  	// If mp.profilehz is 0, then profiling is not enabled for this thread.
  4683  	// We must check this to avoid a deadlock between setcpuprofilerate
  4684  	// and the call to cpuprof.add, below.
  4685  	if mp != nil && mp.profilehz == 0 {
  4686  		return
  4687  	}
  4688  
  4689  	// On mips{,le}/arm, 64bit atomics are emulated with spinlocks, in
  4690  	// runtime/internal/atomic. If SIGPROF arrives while the program is inside
  4691  	// the critical section, it creates a deadlock (when writing the sample).
  4692  	// As a workaround, create a counter of SIGPROFs while in critical section
  4693  	// to store the count, and pass it to sigprof.add() later when SIGPROF is
  4694  	// received from somewhere else (with _LostSIGPROFDuringAtomic64 as pc).
  4695  	if GOARCH == "mips" || GOARCH == "mipsle" || GOARCH == "arm" {
  4696  		if f := findfunc(pc); f.valid() {
  4697  			if hasPrefix(funcname(f), "runtime/internal/atomic") {
  4698  				cpuprof.lostAtomic++
  4699  				return
  4700  			}
  4701  		}
  4702  		if GOARCH == "arm" && goarm < 7 && GOOS == "linux" && pc&0xffff0000 == 0xffff0000 {
  4703  			// runtime/internal/atomic functions call into kernel
  4704  			// helpers on arm < 7. See
  4705  			// runtime/internal/atomic/sys_linux_arm.s.
  4706  			cpuprof.lostAtomic++
  4707  			return
  4708  		}
  4709  	}
  4710  
  4711  	// Profiling runs concurrently with GC, so it must not allocate.
  4712  	// Set a trap in case the code does allocate.
  4713  	// Note that on windows, one thread takes profiles of all the
  4714  	// other threads, so mp is usually not getg().m.
  4715  	// In fact mp may not even be stopped.
  4716  	// See golang.org/issue/17165.
  4717  	getg().m.mallocing++
  4718  
  4719  	var stk [maxCPUProfStack]uintptr
  4720  	n := 0
  4721  	if mp.ncgo > 0 && mp.curg != nil && mp.curg.syscallpc != 0 && mp.curg.syscallsp != 0 {
  4722  		cgoOff := 0
  4723  		// Check cgoCallersUse to make sure that we are not
  4724  		// interrupting other code that is fiddling with
  4725  		// cgoCallers.  We are running in a signal handler
  4726  		// with all signals blocked, so we don't have to worry
  4727  		// about any other code interrupting us.
  4728  		if atomic.Load(&mp.cgoCallersUse) == 0 && mp.cgoCallers != nil && mp.cgoCallers[0] != 0 {
  4729  			for cgoOff < len(mp.cgoCallers) && mp.cgoCallers[cgoOff] != 0 {
  4730  				cgoOff++
  4731  			}
  4732  			copy(stk[:], mp.cgoCallers[:cgoOff])
  4733  			mp.cgoCallers[0] = 0
  4734  		}
  4735  
  4736  		// Collect Go stack that leads to the cgo call.
  4737  		n = gentraceback(mp.curg.syscallpc, mp.curg.syscallsp, 0, mp.curg, 0, &stk[cgoOff], len(stk)-cgoOff, nil, nil, 0)
  4738  		if n > 0 {
  4739  			n += cgoOff
  4740  		}
  4741  	} else {
  4742  		n = gentraceback(pc, sp, lr, gp, 0, &stk[0], len(stk), nil, nil, _TraceTrap|_TraceJumpStack)
  4743  	}
  4744  
  4745  	if n <= 0 {
  4746  		// Normal traceback is impossible or has failed.
  4747  		// See if it falls into several common cases.
  4748  		n = 0
  4749  		if usesLibcall() && mp.libcallg != 0 && mp.libcallpc != 0 && mp.libcallsp != 0 {
  4750  			// Libcall, i.e. runtime syscall on windows.
  4751  			// Collect Go stack that leads to the call.
  4752  			n = gentraceback(mp.libcallpc, mp.libcallsp, 0, mp.libcallg.ptr(), 0, &stk[0], len(stk), nil, nil, 0)
  4753  		}
  4754  		if n == 0 && mp != nil && mp.vdsoSP != 0 {
  4755  			n = gentraceback(mp.vdsoPC, mp.vdsoSP, 0, gp, 0, &stk[0], len(stk), nil, nil, _TraceTrap|_TraceJumpStack)
  4756  		}
  4757  		if n == 0 {
  4758  			// If all of the above has failed, account it against abstract "System" or "GC".
  4759  			n = 2
  4760  			if inVDSOPage(pc) {
  4761  				pc = funcPC(_VDSO) + sys.PCQuantum
  4762  			} else if pc > firstmoduledata.etext {
  4763  				// "ExternalCode" is better than "etext".
  4764  				pc = funcPC(_ExternalCode) + sys.PCQuantum
  4765  			}
  4766  			stk[0] = pc
  4767  			if mp.preemptoff != "" {
  4768  				stk[1] = funcPC(_GC) + sys.PCQuantum
  4769  			} else {
  4770  				stk[1] = funcPC(_System) + sys.PCQuantum
  4771  			}
  4772  		}
  4773  	}
  4774  
  4775  	if prof.hz != 0 {
  4776  		cpuprof.add(gp, stk[:n])
  4777  	}
  4778  	getg().m.mallocing--
  4779  }
  4780  
  4781  // If the signal handler receives a SIGPROF signal on a non-Go thread,
  4782  // it tries to collect a traceback into sigprofCallers.
  4783  // sigprofCallersUse is set to non-zero while sigprofCallers holds a traceback.
  4784  var sigprofCallers cgoCallers
  4785  var sigprofCallersUse uint32
  4786  
  4787  // sigprofNonGo is called if we receive a SIGPROF signal on a non-Go thread,
  4788  // and the signal handler collected a stack trace in sigprofCallers.
  4789  // When this is called, sigprofCallersUse will be non-zero.
  4790  // g is nil, and what we can do is very limited.
  4791  //go:nosplit
  4792  //go:nowritebarrierrec
  4793  func sigprofNonGo() {
  4794  	if prof.hz != 0 {
  4795  		n := 0
  4796  		for n < len(sigprofCallers) && sigprofCallers[n] != 0 {
  4797  			n++
  4798  		}
  4799  		cpuprof.addNonGo(sigprofCallers[:n])
  4800  	}
  4801  
  4802  	atomic.Store(&sigprofCallersUse, 0)
  4803  }
  4804  
  4805  // sigprofNonGoPC is called when a profiling signal arrived on a
  4806  // non-Go thread and we have a single PC value, not a stack trace.
  4807  // g is nil, and what we can do is very limited.
  4808  //go:nosplit
  4809  //go:nowritebarrierrec
  4810  func sigprofNonGoPC(pc uintptr) {
  4811  	if prof.hz != 0 {
  4812  		stk := []uintptr{
  4813  			pc,
  4814  			funcPC(_ExternalCode) + sys.PCQuantum,
  4815  		}
  4816  		cpuprof.addNonGo(stk)
  4817  	}
  4818  }
  4819  
  4820  // setcpuprofilerate sets the CPU profiling rate to hz times per second.
  4821  // If hz <= 0, setcpuprofilerate turns off CPU profiling.
  4822  func setcpuprofilerate(hz int32) {
  4823  	// Force sane arguments.
  4824  	if hz < 0 {
  4825  		hz = 0
  4826  	}
  4827  
  4828  	// Disable preemption, otherwise we can be rescheduled to another thread
  4829  	// that has profiling enabled.
  4830  	_g_ := getg()
  4831  	_g_.m.locks++
  4832  
  4833  	// Stop profiler on this thread so that it is safe to lock prof.
  4834  	// if a profiling signal came in while we had prof locked,
  4835  	// it would deadlock.
  4836  	setThreadCPUProfiler(0)
  4837  
  4838  	for !atomic.Cas(&prof.signalLock, 0, 1) {
  4839  		osyield()
  4840  	}
  4841  	if prof.hz != hz {
  4842  		setProcessCPUProfiler(hz)
  4843  		prof.hz = hz
  4844  	}
  4845  	atomic.Store(&prof.signalLock, 0)
  4846  
  4847  	lock(&sched.lock)
  4848  	sched.profilehz = hz
  4849  	unlock(&sched.lock)
  4850  
  4851  	if hz != 0 {
  4852  		setThreadCPUProfiler(hz)
  4853  	}
  4854  
  4855  	_g_.m.locks--
  4856  }
  4857  
  4858  // init initializes pp, which may be a freshly allocated p or a
  4859  // previously destroyed p, and transitions it to status _Pgcstop.
  4860  func (pp *p) init(id int32) {
  4861  	pp.id = id
  4862  	pp.status = _Pgcstop
  4863  	pp.sudogcache = pp.sudogbuf[:0]
  4864  	for i := range pp.deferpool {
  4865  		pp.deferpool[i] = pp.deferpoolbuf[i][:0]
  4866  	}
  4867  	pp.wbBuf.reset()
  4868  	if pp.mcache == nil {
  4869  		if id == 0 {
  4870  			if mcache0 == nil {
  4871  				throw("missing mcache?")
  4872  			}
  4873  			// Use the bootstrap mcache0. Only one P will get
  4874  			// mcache0: the one with ID 0.
  4875  			pp.mcache = mcache0
  4876  		} else {
  4877  			pp.mcache = allocmcache()
  4878  		}
  4879  	}
  4880  	if raceenabled && pp.raceprocctx == 0 {
  4881  		if id == 0 {
  4882  			pp.raceprocctx = raceprocctx0
  4883  			raceprocctx0 = 0 // bootstrap
  4884  		} else {
  4885  			pp.raceprocctx = raceproccreate()
  4886  		}
  4887  	}
  4888  	lockInit(&pp.timersLock, lockRankTimers)
  4889  
  4890  	// This P may get timers when it starts running. Set the mask here
  4891  	// since the P may not go through pidleget (notably P 0 on startup).
  4892  	timerpMask.set(id)
  4893  	// Similarly, we may not go through pidleget before this P starts
  4894  	// running if it is P 0 on startup.
  4895  	idlepMask.clear(id)
  4896  }
  4897  
  4898  // destroy releases all of the resources associated with pp and
  4899  // transitions it to status _Pdead.
  4900  //
  4901  // sched.lock must be held and the world must be stopped.
  4902  func (pp *p) destroy() {
  4903  	assertLockHeld(&sched.lock)
  4904  	assertWorldStopped()
  4905  
  4906  	// Move all runnable goroutines to the global queue
  4907  	for pp.runqhead != pp.runqtail {
  4908  		// Pop from tail of local queue
  4909  		pp.runqtail--
  4910  		gp := pp.runq[pp.runqtail%uint32(len(pp.runq))].ptr()
  4911  		// Push onto head of global queue
  4912  		globrunqputhead(gp)
  4913  	}
  4914  	if pp.runnext != 0 {
  4915  		globrunqputhead(pp.runnext.ptr())
  4916  		pp.runnext = 0
  4917  	}
  4918  	if len(pp.timers) > 0 {
  4919  		plocal := getg().m.p.ptr()
  4920  		// The world is stopped, but we acquire timersLock to
  4921  		// protect against sysmon calling timeSleepUntil.
  4922  		// This is the only case where we hold the timersLock of
  4923  		// more than one P, so there are no deadlock concerns.
  4924  		lock(&plocal.timersLock)
  4925  		lock(&pp.timersLock)
  4926  		moveTimers(plocal, pp.timers)
  4927  		pp.timers = nil
  4928  		pp.numTimers = 0
  4929  		pp.deletedTimers = 0
  4930  		atomic.Store64(&pp.timer0When, 0)
  4931  		unlock(&pp.timersLock)
  4932  		unlock(&plocal.timersLock)
  4933  	}
  4934  	// Flush p's write barrier buffer.
  4935  	if gcphase != _GCoff {
  4936  		wbBufFlush1(pp)
  4937  		pp.gcw.dispose()
  4938  	}
  4939  	for i := range pp.sudogbuf {
  4940  		pp.sudogbuf[i] = nil
  4941  	}
  4942  	pp.sudogcache = pp.sudogbuf[:0]
  4943  	for i := range pp.deferpool {
  4944  		for j := range pp.deferpoolbuf[i] {
  4945  			pp.deferpoolbuf[i][j] = nil
  4946  		}
  4947  		pp.deferpool[i] = pp.deferpoolbuf[i][:0]
  4948  	}
  4949  	systemstack(func() {
  4950  		for i := 0; i < pp.mspancache.len; i++ {
  4951  			// Safe to call since the world is stopped.
  4952  			mheap_.spanalloc.free(unsafe.Pointer(pp.mspancache.buf[i]))
  4953  		}
  4954  		pp.mspancache.len = 0
  4955  		lock(&mheap_.lock)
  4956  		pp.pcache.flush(&mheap_.pages)
  4957  		unlock(&mheap_.lock)
  4958  	})
  4959  	freemcache(pp.mcache)
  4960  	pp.mcache = nil
  4961  	gfpurge(pp)
  4962  	traceProcFree(pp)
  4963  	if raceenabled {
  4964  		if pp.timerRaceCtx != 0 {
  4965  			// The race detector code uses a callback to fetch
  4966  			// the proc context, so arrange for that callback
  4967  			// to see the right thing.
  4968  			// This hack only works because we are the only
  4969  			// thread running.
  4970  			mp := getg().m
  4971  			phold := mp.p.ptr()
  4972  			mp.p.set(pp)
  4973  
  4974  			racectxend(pp.timerRaceCtx)
  4975  			pp.timerRaceCtx = 0
  4976  
  4977  			mp.p.set(phold)
  4978  		}
  4979  		raceprocdestroy(pp.raceprocctx)
  4980  		pp.raceprocctx = 0
  4981  	}
  4982  	pp.gcAssistTime = 0
  4983  	pp.status = _Pdead
  4984  }
  4985  
  4986  // Change number of processors.
  4987  //
  4988  // sched.lock must be held, and the world must be stopped.
  4989  //
  4990  // gcworkbufs must not be being modified by either the GC or the write barrier
  4991  // code, so the GC must not be running if the number of Ps actually changes.
  4992  //
  4993  // Returns list of Ps with local work, they need to be scheduled by the caller.
  4994  func procresize(nprocs int32) *p {
  4995  	assertLockHeld(&sched.lock)
  4996  	assertWorldStopped()
  4997  
  4998  	old := gomaxprocs
  4999  	if old < 0 || nprocs <= 0 {
  5000  		throw("procresize: invalid arg")
  5001  	}
  5002  	if trace.enabled {
  5003  		traceGomaxprocs(nprocs)
  5004  	}
  5005  
  5006  	// update statistics
  5007  	now := nanotime()
  5008  	if sched.procresizetime != 0 {
  5009  		sched.totaltime += int64(old) * (now - sched.procresizetime)
  5010  	}
  5011  	sched.procresizetime = now
  5012  
  5013  	maskWords := (nprocs + 31) / 32
  5014  
  5015  	// Grow allp if necessary.
  5016  	if nprocs > int32(len(allp)) {
  5017  		// Synchronize with retake, which could be running
  5018  		// concurrently since it doesn't run on a P.
  5019  		lock(&allpLock)
  5020  		if nprocs <= int32(cap(allp)) {
  5021  			allp = allp[:nprocs]
  5022  		} else {
  5023  			nallp := make([]*p, nprocs)
  5024  			// Copy everything up to allp's cap so we
  5025  			// never lose old allocated Ps.
  5026  			copy(nallp, allp[:cap(allp)])
  5027  			allp = nallp
  5028  		}
  5029  
  5030  		if maskWords <= int32(cap(idlepMask)) {
  5031  			idlepMask = idlepMask[:maskWords]
  5032  			timerpMask = timerpMask[:maskWords]
  5033  		} else {
  5034  			nidlepMask := make([]uint32, maskWords)
  5035  			// No need to copy beyond len, old Ps are irrelevant.
  5036  			copy(nidlepMask, idlepMask)
  5037  			idlepMask = nidlepMask
  5038  
  5039  			ntimerpMask := make([]uint32, maskWords)
  5040  			copy(ntimerpMask, timerpMask)
  5041  			timerpMask = ntimerpMask
  5042  		}
  5043  		unlock(&allpLock)
  5044  	}
  5045  
  5046  	// initialize new P's
  5047  	for i := old; i < nprocs; i++ {
  5048  		pp := allp[i]
  5049  		if pp == nil {
  5050  			pp = new(p)
  5051  		}
  5052  		pp.init(i)
  5053  		atomicstorep(unsafe.Pointer(&allp[i]), unsafe.Pointer(pp))
  5054  	}
  5055  
  5056  	_g_ := getg()
  5057  	if _g_.m.p != 0 && _g_.m.p.ptr().id < nprocs {
  5058  		// continue to use the current P
  5059  		_g_.m.p.ptr().status = _Prunning
  5060  		_g_.m.p.ptr().mcache.prepareForSweep()
  5061  	} else {
  5062  		// release the current P and acquire allp[0].
  5063  		//
  5064  		// We must do this before destroying our current P
  5065  		// because p.destroy itself has write barriers, so we
  5066  		// need to do that from a valid P.
  5067  		if _g_.m.p != 0 {
  5068  			if trace.enabled {
  5069  				// Pretend that we were descheduled
  5070  				// and then scheduled again to keep
  5071  				// the trace sane.
  5072  				traceGoSched()
  5073  				traceProcStop(_g_.m.p.ptr())
  5074  			}
  5075  			_g_.m.p.ptr().m = 0
  5076  		}
  5077  		_g_.m.p = 0
  5078  		p := allp[0]
  5079  		p.m = 0
  5080  		p.status = _Pidle
  5081  		acquirep(p)
  5082  		if trace.enabled {
  5083  			traceGoStart()
  5084  		}
  5085  	}
  5086  
  5087  	// g.m.p is now set, so we no longer need mcache0 for bootstrapping.
  5088  	mcache0 = nil
  5089  
  5090  	// release resources from unused P's
  5091  	for i := nprocs; i < old; i++ {
  5092  		p := allp[i]
  5093  		p.destroy()
  5094  		// can't free P itself because it can be referenced by an M in syscall
  5095  	}
  5096  
  5097  	// Trim allp.
  5098  	if int32(len(allp)) != nprocs {
  5099  		lock(&allpLock)
  5100  		allp = allp[:nprocs]
  5101  		idlepMask = idlepMask[:maskWords]
  5102  		timerpMask = timerpMask[:maskWords]
  5103  		unlock(&allpLock)
  5104  	}
  5105  
  5106  	var runnablePs *p
  5107  	for i := nprocs - 1; i >= 0; i-- {
  5108  		p := allp[i]
  5109  		if _g_.m.p.ptr() == p {
  5110  			continue
  5111  		}
  5112  		p.status = _Pidle
  5113  		if runqempty(p) {
  5114  			pidleput(p)
  5115  		} else {
  5116  			p.m.set(mget())
  5117  			p.link.set(runnablePs)
  5118  			runnablePs = p
  5119  		}
  5120  	}
  5121  	stealOrder.reset(uint32(nprocs))
  5122  	var int32p *int32 = &gomaxprocs // make compiler check that gomaxprocs is an int32
  5123  	atomic.Store((*uint32)(unsafe.Pointer(int32p)), uint32(nprocs))
  5124  	return runnablePs
  5125  }
  5126  
  5127  // Associate p and the current m.
  5128  //
  5129  // This function is allowed to have write barriers even if the caller
  5130  // isn't because it immediately acquires _p_.
  5131  //
  5132  //go:yeswritebarrierrec
  5133  func acquirep(_p_ *p) {
  5134  	// Do the part that isn't allowed to have write barriers.
  5135  	wirep(_p_)
  5136  
  5137  	// Have p; write barriers now allowed.
  5138  
  5139  	// Perform deferred mcache flush before this P can allocate
  5140  	// from a potentially stale mcache.
  5141  	_p_.mcache.prepareForSweep()
  5142  
  5143  	if trace.enabled {
  5144  		traceProcStart()
  5145  	}
  5146  }
  5147  
  5148  // wirep is the first step of acquirep, which actually associates the
  5149  // current M to _p_. This is broken out so we can disallow write
  5150  // barriers for this part, since we don't yet have a P.
  5151  //
  5152  //go:nowritebarrierrec
  5153  //go:nosplit
  5154  func wirep(_p_ *p) {
  5155  	_g_ := getg()
  5156  
  5157  	if _g_.m.p != 0 {
  5158  		throw("wirep: already in go")
  5159  	}
  5160  	if _p_.m != 0 || _p_.status != _Pidle {
  5161  		id := int64(0)
  5162  		if _p_.m != 0 {
  5163  			id = _p_.m.ptr().id
  5164  		}
  5165  		print("wirep: p->m=", _p_.m, "(", id, ") p->status=", _p_.status, "\n")
  5166  		throw("wirep: invalid p state")
  5167  	}
  5168  	_g_.m.p.set(_p_)
  5169  	_p_.m.set(_g_.m)
  5170  	_p_.status = _Prunning
  5171  }
  5172  
  5173  // Disassociate p and the current m.
  5174  func releasep() *p {
  5175  	_g_ := getg()
  5176  
  5177  	if _g_.m.p == 0 {
  5178  		throw("releasep: invalid arg")
  5179  	}
  5180  	_p_ := _g_.m.p.ptr()
  5181  	if _p_.m.ptr() != _g_.m || _p_.status != _Prunning {
  5182  		print("releasep: m=", _g_.m, " m->p=", _g_.m.p.ptr(), " p->m=", hex(_p_.m), " p->status=", _p_.status, "\n")
  5183  		throw("releasep: invalid p state")
  5184  	}
  5185  	if trace.enabled {
  5186  		traceProcStop(_g_.m.p.ptr())
  5187  	}
  5188  	_g_.m.p = 0
  5189  	_p_.m = 0
  5190  	_p_.status = _Pidle
  5191  	return _p_
  5192  }
  5193  
  5194  func incidlelocked(v int32) {
  5195  	lock(&sched.lock)
  5196  	sched.nmidlelocked += v
  5197  	if v > 0 {
  5198  		checkdead()
  5199  	}
  5200  	unlock(&sched.lock)
  5201  }
  5202  
  5203  // Check for deadlock situation.
  5204  // The check is based on number of running M's, if 0 -> deadlock.
  5205  // sched.lock must be held.
  5206  func checkdead() {
  5207  	assertLockHeld(&sched.lock)
  5208  
  5209  	// For -buildmode=c-shared or -buildmode=c-archive it's OK if
  5210  	// there are no running goroutines. The calling program is
  5211  	// assumed to be running.
  5212  	if islibrary || isarchive {
  5213  		return
  5214  	}
  5215  
  5216  	// If we are dying because of a signal caught on an already idle thread,
  5217  	// freezetheworld will cause all running threads to block.
  5218  	// And runtime will essentially enter into deadlock state,
  5219  	// except that there is a thread that will call exit soon.
  5220  	if panicking > 0 {
  5221  		return
  5222  	}
  5223  
  5224  	// If we are not running under cgo, but we have an extra M then account
  5225  	// for it. (It is possible to have an extra M on Windows without cgo to
  5226  	// accommodate callbacks created by syscall.NewCallback. See issue #6751
  5227  	// for details.)
  5228  	var run0 int32
  5229  	if !iscgo && cgoHasExtraM {
  5230  		mp := lockextra(true)
  5231  		haveExtraM := extraMCount > 0
  5232  		unlockextra(mp)
  5233  		if haveExtraM {
  5234  			run0 = 1
  5235  		}
  5236  	}
  5237  
  5238  	run := mcount() - sched.nmidle - sched.nmidlelocked - sched.nmsys
  5239  	if run > run0 {
  5240  		return
  5241  	}
  5242  	if run < 0 {
  5243  		print("runtime: checkdead: nmidle=", sched.nmidle, " nmidlelocked=", sched.nmidlelocked, " mcount=", mcount(), " nmsys=", sched.nmsys, "\n")
  5244  		throw("checkdead: inconsistent counts")
  5245  	}
  5246  
  5247  	grunning := 0
  5248  	forEachG(func(gp *g) {
  5249  		if isSystemGoroutine(gp, false) {
  5250  			return
  5251  		}
  5252  		s := readgstatus(gp)
  5253  		switch s &^ _Gscan {
  5254  		case _Gwaiting,
  5255  			_Gpreempted:
  5256  			grunning++
  5257  		case _Grunnable,
  5258  			_Grunning,
  5259  			_Gsyscall:
  5260  			print("runtime: checkdead: find g ", gp.goid, " in status ", s, "\n")
  5261  			throw("checkdead: runnable g")
  5262  		}
  5263  	})
  5264  	if grunning == 0 { // possible if main goroutine calls runtime·Goexit()
  5265  		unlock(&sched.lock) // unlock so that GODEBUG=scheddetail=1 doesn't hang
  5266  		throw("no goroutines (main called runtime.Goexit) - deadlock!")
  5267  	}
  5268  
  5269  	// Maybe jump time forward for playground.
  5270  	if faketime != 0 {
  5271  		when, _p_ := timeSleepUntil()
  5272  		if _p_ != nil {
  5273  			faketime = when
  5274  			for pp := &sched.pidle; *pp != 0; pp = &(*pp).ptr().link {
  5275  				if (*pp).ptr() == _p_ {
  5276  					*pp = _p_.link
  5277  					break
  5278  				}
  5279  			}
  5280  			mp := mget()
  5281  			if mp == nil {
  5282  				// There should always be a free M since
  5283  				// nothing is running.
  5284  				throw("checkdead: no m for timer")
  5285  			}
  5286  			mp.nextp.set(_p_)
  5287  			notewakeup(&mp.park)
  5288  			return
  5289  		}
  5290  	}
  5291  
  5292  	// There are no goroutines running, so we can look at the P's.
  5293  	for _, _p_ := range allp {
  5294  		if len(_p_.timers) > 0 {
  5295  			return
  5296  		}
  5297  	}
  5298  
  5299  	getg().m.throwing = -1 // do not dump full stacks
  5300  	unlock(&sched.lock)    // unlock so that GODEBUG=scheddetail=1 doesn't hang
  5301  	throw("all goroutines are asleep - deadlock!")
  5302  }
  5303  
  5304  // forcegcperiod is the maximum time in nanoseconds between garbage
  5305  // collections. If we go this long without a garbage collection, one
  5306  // is forced to run.
  5307  //
  5308  // This is a variable for testing purposes. It normally doesn't change.
  5309  var forcegcperiod int64 = 2 * 60 * 1e9
  5310  
  5311  // Always runs without a P, so write barriers are not allowed.
  5312  //
  5313  //go:nowritebarrierrec
  5314  func sysmon() {
  5315  	lock(&sched.lock)
  5316  	sched.nmsys++
  5317  	checkdead()
  5318  	unlock(&sched.lock)
  5319  
  5320  	// For syscall_runtime_doAllThreadsSyscall, sysmon is
  5321  	// sufficiently up to participate in fixups.
  5322  	atomic.Store(&sched.sysmonStarting, 0)
  5323  
  5324  	lasttrace := int64(0)
  5325  	idle := 0 // how many cycles in succession we had not wokeup somebody
  5326  	delay := uint32(0)
  5327  
  5328  	for {
  5329  		if idle == 0 { // start with 20us sleep...
  5330  			delay = 20
  5331  		} else if idle > 50 { // start doubling the sleep after 1ms...
  5332  			delay *= 2
  5333  		}
  5334  		if delay > 10*1000 { // up to 10ms
  5335  			delay = 10 * 1000
  5336  		}
  5337  		usleep(delay)
  5338  		mDoFixup()
  5339  
  5340  		// sysmon should not enter deep sleep if schedtrace is enabled so that
  5341  		// it can print that information at the right time.
  5342  		//
  5343  		// It should also not enter deep sleep if there are any active P's so
  5344  		// that it can retake P's from syscalls, preempt long running G's, and
  5345  		// poll the network if all P's are busy for long stretches.
  5346  		//
  5347  		// It should wakeup from deep sleep if any P's become active either due
  5348  		// to exiting a syscall or waking up due to a timer expiring so that it
  5349  		// can resume performing those duties. If it wakes from a syscall it
  5350  		// resets idle and delay as a bet that since it had retaken a P from a
  5351  		// syscall before, it may need to do it again shortly after the
  5352  		// application starts work again. It does not reset idle when waking
  5353  		// from a timer to avoid adding system load to applications that spend
  5354  		// most of their time sleeping.
  5355  		now := nanotime()
  5356  		if debug.schedtrace <= 0 && (sched.gcwaiting != 0 || atomic.Load(&sched.npidle) == uint32(gomaxprocs)) {
  5357  			lock(&sched.lock)
  5358  			if atomic.Load(&sched.gcwaiting) != 0 || atomic.Load(&sched.npidle) == uint32(gomaxprocs) {
  5359  				syscallWake := false
  5360  				next, _ := timeSleepUntil()
  5361  				if next > now {
  5362  					atomic.Store(&sched.sysmonwait, 1)
  5363  					unlock(&sched.lock)
  5364  					// Make wake-up period small enough
  5365  					// for the sampling to be correct.
  5366  					sleep := forcegcperiod / 2
  5367  					if next-now < sleep {
  5368  						sleep = next - now
  5369  					}
  5370  					shouldRelax := sleep >= osRelaxMinNS
  5371  					if shouldRelax {
  5372  						osRelax(true)
  5373  					}
  5374  					syscallWake = notetsleep(&sched.sysmonnote, sleep)
  5375  					mDoFixup()
  5376  					if shouldRelax {
  5377  						osRelax(false)
  5378  					}
  5379  					lock(&sched.lock)
  5380  					atomic.Store(&sched.sysmonwait, 0)
  5381  					noteclear(&sched.sysmonnote)
  5382  				}
  5383  				if syscallWake {
  5384  					idle = 0
  5385  					delay = 20
  5386  				}
  5387  			}
  5388  			unlock(&sched.lock)
  5389  		}
  5390  
  5391  		lock(&sched.sysmonlock)
  5392  		// Update now in case we blocked on sysmonnote or spent a long time
  5393  		// blocked on schedlock or sysmonlock above.
  5394  		now = nanotime()
  5395  
  5396  		// trigger libc interceptors if needed
  5397  		if *cgo_yield != nil {
  5398  			asmcgocall(*cgo_yield, nil)
  5399  		}
  5400  		// poll network if not polled for more than 10ms
  5401  		lastpoll := int64(atomic.Load64(&sched.lastpoll))
  5402  		if netpollinited() && lastpoll != 0 && lastpoll+10*1000*1000 < now {
  5403  			atomic.Cas64(&sched.lastpoll, uint64(lastpoll), uint64(now))
  5404  			list := netpoll(0) // non-blocking - returns list of goroutines
  5405  			if !list.empty() {
  5406  				// Need to decrement number of idle locked M's
  5407  				// (pretending that one more is running) before injectglist.
  5408  				// Otherwise it can lead to the following situation:
  5409  				// injectglist grabs all P's but before it starts M's to run the P's,
  5410  				// another M returns from syscall, finishes running its G,
  5411  				// observes that there is no work to do and no other running M's
  5412  				// and reports deadlock.
  5413  				incidlelocked(-1)
  5414  				injectglist(&list)
  5415  				incidlelocked(1)
  5416  			}
  5417  		}
  5418  		mDoFixup()
  5419  		if GOOS == "netbsd" {
  5420  			// netpoll is responsible for waiting for timer
  5421  			// expiration, so we typically don't have to worry
  5422  			// about starting an M to service timers. (Note that
  5423  			// sleep for timeSleepUntil above simply ensures sysmon
  5424  			// starts running again when that timer expiration may
  5425  			// cause Go code to run again).
  5426  			//
  5427  			// However, netbsd has a kernel bug that sometimes
  5428  			// misses netpollBreak wake-ups, which can lead to
  5429  			// unbounded delays servicing timers. If we detect this
  5430  			// overrun, then startm to get something to handle the
  5431  			// timer.
  5432  			//
  5433  			// See issue 42515 and
  5434  			// https://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=50094.
  5435  			if next, _ := timeSleepUntil(); next < now {
  5436  				startm(nil, false)
  5437  			}
  5438  		}
  5439  		if atomic.Load(&scavenge.sysmonWake) != 0 {
  5440  			// Kick the scavenger awake if someone requested it.
  5441  			wakeScavenger()
  5442  		}
  5443  		// retake P's blocked in syscalls
  5444  		// and preempt long running G's
  5445  		if retake(now) != 0 {
  5446  			idle = 0
  5447  		} else {
  5448  			idle++
  5449  		}
  5450  		// check if we need to force a GC
  5451  		if t := (gcTrigger{kind: gcTriggerTime, now: now}); t.test() && atomic.Load(&forcegc.idle) != 0 {
  5452  			lock(&forcegc.lock)
  5453  			forcegc.idle = 0
  5454  			var list gList
  5455  			list.push(forcegc.g)
  5456  			injectglist(&list)
  5457  			unlock(&forcegc.lock)
  5458  		}
  5459  		if debug.schedtrace > 0 && lasttrace+int64(debug.schedtrace)*1000000 <= now {
  5460  			lasttrace = now
  5461  			schedtrace(debug.scheddetail > 0)
  5462  		}
  5463  		unlock(&sched.sysmonlock)
  5464  	}
  5465  }
  5466  
  5467  type sysmontick struct {
  5468  	schedtick   uint32
  5469  	schedwhen   int64
  5470  	syscalltick uint32
  5471  	syscallwhen int64
  5472  }
  5473  
  5474  // forcePreemptNS is the time slice given to a G before it is
  5475  // preempted.
  5476  const forcePreemptNS = 10 * 1000 * 1000 // 10ms
  5477  
  5478  func retake(now int64) uint32 {
  5479  	n := 0
  5480  	// Prevent allp slice changes. This lock will be completely
  5481  	// uncontended unless we're already stopping the world.
  5482  	lock(&allpLock)
  5483  	// We can't use a range loop over allp because we may
  5484  	// temporarily drop the allpLock. Hence, we need to re-fetch
  5485  	// allp each time around the loop.
  5486  	for i := 0; i < len(allp); i++ {
  5487  		_p_ := allp[i]
  5488  		if _p_ == nil {
  5489  			// This can happen if procresize has grown
  5490  			// allp but not yet created new Ps.
  5491  			continue
  5492  		}
  5493  		pd := &_p_.sysmontick
  5494  		s := _p_.status
  5495  		sysretake := false
  5496  		if s == _Prunning || s == _Psyscall {
  5497  			// Preempt G if it's running for too long.
  5498  			t := int64(_p_.schedtick)
  5499  			if int64(pd.schedtick) != t {
  5500  				pd.schedtick = uint32(t)
  5501  				pd.schedwhen = now
  5502  			} else if pd.schedwhen+forcePreemptNS <= now {
  5503  				preemptone(_p_)
  5504  				// In case of syscall, preemptone() doesn't
  5505  				// work, because there is no M wired to P.
  5506  				sysretake = true
  5507  			}
  5508  		}
  5509  		if s == _Psyscall {
  5510  			// Retake P from syscall if it's there for more than 1 sysmon tick (at least 20us).
  5511  			t := int64(_p_.syscalltick)
  5512  			if !sysretake && int64(pd.syscalltick) != t {
  5513  				pd.syscalltick = uint32(t)
  5514  				pd.syscallwhen = now
  5515  				continue
  5516  			}
  5517  			// On the one hand we don't want to retake Ps if there is no other work to do,
  5518  			// but on the other hand we want to retake them eventually
  5519  			// because they can prevent the sysmon thread from deep sleep.
  5520  			if runqempty(_p_) && atomic.Load(&sched.nmspinning)+atomic.Load(&sched.npidle) > 0 && pd.syscallwhen+10*1000*1000 > now {
  5521  				continue
  5522  			}
  5523  			// Drop allpLock so we can take sched.lock.
  5524  			unlock(&allpLock)
  5525  			// Need to decrement number of idle locked M's
  5526  			// (pretending that one more is running) before the CAS.
  5527  			// Otherwise the M from which we retake can exit the syscall,
  5528  			// increment nmidle and report deadlock.
  5529  			incidlelocked(-1)
  5530  			if atomic.Cas(&_p_.status, s, _Pidle) {
  5531  				if trace.enabled {
  5532  					traceGoSysBlock(_p_)
  5533  					traceProcStop(_p_)
  5534  				}
  5535  				n++
  5536  				_p_.syscalltick++
  5537  				handoffp(_p_)
  5538  			}
  5539  			incidlelocked(1)
  5540  			lock(&allpLock)
  5541  		}
  5542  	}
  5543  	unlock(&allpLock)
  5544  	return uint32(n)
  5545  }
  5546  
  5547  // Tell all goroutines that they have been preempted and they should stop.
  5548  // This function is purely best-effort. It can fail to inform a goroutine if a
  5549  // processor just started running it.
  5550  // No locks need to be held.
  5551  // Returns true if preemption request was issued to at least one goroutine.
  5552  func preemptall() bool {
  5553  	res := false
  5554  	for _, _p_ := range allp {
  5555  		if _p_.status != _Prunning {
  5556  			continue
  5557  		}
  5558  		if preemptone(_p_) {
  5559  			res = true
  5560  		}
  5561  	}
  5562  	return res
  5563  }
  5564  
  5565  // Tell the goroutine running on processor P to stop.
  5566  // This function is purely best-effort. It can incorrectly fail to inform the
  5567  // goroutine. It can inform the wrong goroutine. Even if it informs the
  5568  // correct goroutine, that goroutine might ignore the request if it is
  5569  // simultaneously executing newstack.
  5570  // No lock needs to be held.
  5571  // Returns true if preemption request was issued.
  5572  // The actual preemption will happen at some point in the future
  5573  // and will be indicated by the gp->status no longer being
  5574  // Grunning
  5575  func preemptone(_p_ *p) bool {
  5576  	mp := _p_.m.ptr()
  5577  	if mp == nil || mp == getg().m {
  5578  		return false
  5579  	}
  5580  	gp := mp.curg
  5581  	if gp == nil || gp == mp.g0 {
  5582  		return false
  5583  	}
  5584  
  5585  	gp.preempt = true
  5586  
  5587  	// Every call in a goroutine checks for stack overflow by
  5588  	// comparing the current stack pointer to gp->stackguard0.
  5589  	// Setting gp->stackguard0 to StackPreempt folds
  5590  	// preemption into the normal stack overflow check.
  5591  	gp.stackguard0 = stackPreempt
  5592  
  5593  	// Request an async preemption of this P.
  5594  	if preemptMSupported && debug.asyncpreemptoff == 0 {
  5595  		_p_.preempt = true
  5596  		preemptM(mp)
  5597  	}
  5598  
  5599  	return true
  5600  }
  5601  
  5602  var starttime int64
  5603  
  5604  func schedtrace(detailed bool) {
  5605  	now := nanotime()
  5606  	if starttime == 0 {
  5607  		starttime = now
  5608  	}
  5609  
  5610  	lock(&sched.lock)
  5611  	print("SCHED ", (now-starttime)/1e6, "ms: gomaxprocs=", gomaxprocs, " idleprocs=", sched.npidle, " threads=", mcount(), " spinningthreads=", sched.nmspinning, " idlethreads=", sched.nmidle, " runqueue=", sched.runqsize)
  5612  	if detailed {
  5613  		print(" gcwaiting=", sched.gcwaiting, " nmidlelocked=", sched.nmidlelocked, " stopwait=", sched.stopwait, " sysmonwait=", sched.sysmonwait, "\n")
  5614  	}
  5615  	// We must be careful while reading data from P's, M's and G's.
  5616  	// Even if we hold schedlock, most data can be changed concurrently.
  5617  	// E.g. (p->m ? p->m->id : -1) can crash if p->m changes from non-nil to nil.
  5618  	for i, _p_ := range allp {
  5619  		mp := _p_.m.ptr()
  5620  		h := atomic.Load(&_p_.runqhead)
  5621  		t := atomic.Load(&_p_.runqtail)
  5622  		if detailed {
  5623  			id := int64(-1)
  5624  			if mp != nil {
  5625  				id = mp.id
  5626  			}
  5627  			print("  P", i, ": status=", _p_.status, " schedtick=", _p_.schedtick, " syscalltick=", _p_.syscalltick, " m=", id, " runqsize=", t-h, " gfreecnt=", _p_.gFree.n, " timerslen=", len(_p_.timers), "\n")
  5628  		} else {
  5629  			// In non-detailed mode format lengths of per-P run queues as:
  5630  			// [len1 len2 len3 len4]
  5631  			print(" ")
  5632  			if i == 0 {
  5633  				print("[")
  5634  			}
  5635  			print(t - h)
  5636  			if i == len(allp)-1 {
  5637  				print("]\n")
  5638  			}
  5639  		}
  5640  	}
  5641  
  5642  	if !detailed {
  5643  		unlock(&sched.lock)
  5644  		return
  5645  	}
  5646  
  5647  	for mp := allm; mp != nil; mp = mp.alllink {
  5648  		_p_ := mp.p.ptr()
  5649  		gp := mp.curg
  5650  		lockedg := mp.lockedg.ptr()
  5651  		id1 := int32(-1)
  5652  		if _p_ != nil {
  5653  			id1 = _p_.id
  5654  		}
  5655  		id2 := int64(-1)
  5656  		if gp != nil {
  5657  			id2 = gp.goid
  5658  		}
  5659  		id3 := int64(-1)
  5660  		if lockedg != nil {
  5661  			id3 = lockedg.goid
  5662  		}
  5663  		print("  M", mp.id, ": p=", id1, " curg=", id2, " mallocing=", mp.mallocing, " throwing=", mp.throwing, " preemptoff=", mp.preemptoff, ""+" locks=", mp.locks, " dying=", mp.dying, " spinning=", mp.spinning, " blocked=", mp.blocked, " lockedg=", id3, "\n")
  5664  	}
  5665  
  5666  	forEachG(func(gp *g) {
  5667  		mp := gp.m
  5668  		lockedm := gp.lockedm.ptr()
  5669  		id1 := int64(-1)
  5670  		if mp != nil {
  5671  			id1 = mp.id
  5672  		}
  5673  		id2 := int64(-1)
  5674  		if lockedm != nil {
  5675  			id2 = lockedm.id
  5676  		}
  5677  		print("  G", gp.goid, ": status=", readgstatus(gp), "(", gp.waitreason.String(), ") m=", id1, " lockedm=", id2, "\n")
  5678  	})
  5679  	unlock(&sched.lock)
  5680  }
  5681  
  5682  // schedEnableUser enables or disables the scheduling of user
  5683  // goroutines.
  5684  //
  5685  // This does not stop already running user goroutines, so the caller
  5686  // should first stop the world when disabling user goroutines.
  5687  func schedEnableUser(enable bool) {
  5688  	lock(&sched.lock)
  5689  	if sched.disable.user == !enable {
  5690  		unlock(&sched.lock)
  5691  		return
  5692  	}
  5693  	sched.disable.user = !enable
  5694  	if enable {
  5695  		n := sched.disable.n
  5696  		sched.disable.n = 0
  5697  		globrunqputbatch(&sched.disable.runnable, n)
  5698  		unlock(&sched.lock)
  5699  		for ; n != 0 && sched.npidle != 0; n-- {
  5700  			startm(nil, false)
  5701  		}
  5702  	} else {
  5703  		unlock(&sched.lock)
  5704  	}
  5705  }
  5706  
  5707  // schedEnabled reports whether gp should be scheduled. It returns
  5708  // false is scheduling of gp is disabled.
  5709  //
  5710  // sched.lock must be held.
  5711  func schedEnabled(gp *g) bool {
  5712  	assertLockHeld(&sched.lock)
  5713  
  5714  	if sched.disable.user {
  5715  		return isSystemGoroutine(gp, true)
  5716  	}
  5717  	return true
  5718  }
  5719  
  5720  // Put mp on midle list.
  5721  // sched.lock must be held.
  5722  // May run during STW, so write barriers are not allowed.
  5723  //go:nowritebarrierrec
  5724  func mput(mp *m) {
  5725  	assertLockHeld(&sched.lock)
  5726  
  5727  	mp.schedlink = sched.midle
  5728  	sched.midle.set(mp)
  5729  	sched.nmidle++
  5730  	checkdead()
  5731  }
  5732  
  5733  // Try to get an m from midle list.
  5734  // sched.lock must be held.
  5735  // May run during STW, so write barriers are not allowed.
  5736  //go:nowritebarrierrec
  5737  func mget() *m {
  5738  	assertLockHeld(&sched.lock)
  5739  
  5740  	mp := sched.midle.ptr()
  5741  	if mp != nil {
  5742  		sched.midle = mp.schedlink
  5743  		sched.nmidle--
  5744  	}
  5745  	return mp
  5746  }
  5747  
  5748  // Put gp on the global runnable queue.
  5749  // sched.lock must be held.
  5750  // May run during STW, so write barriers are not allowed.
  5751  //go:nowritebarrierrec
  5752  func globrunqput(gp *g) {
  5753  	assertLockHeld(&sched.lock)
  5754  
  5755  	sched.runq.pushBack(gp)
  5756  	sched.runqsize++
  5757  }
  5758  
  5759  // Put gp at the head of the global runnable queue.
  5760  // sched.lock must be held.
  5761  // May run during STW, so write barriers are not allowed.
  5762  //go:nowritebarrierrec
  5763  func globrunqputhead(gp *g) {
  5764  	assertLockHeld(&sched.lock)
  5765  
  5766  	sched.runq.push(gp)
  5767  	sched.runqsize++
  5768  }
  5769  
  5770  // Put a batch of runnable goroutines on the global runnable queue.
  5771  // This clears *batch.
  5772  // sched.lock must be held.
  5773  // May run during STW, so write barriers are not allowed.
  5774  //go:nowritebarrierrec
  5775  func globrunqputbatch(batch *gQueue, n int32) {
  5776  	assertLockHeld(&sched.lock)
  5777  
  5778  	sched.runq.pushBackAll(*batch)
  5779  	sched.runqsize += n
  5780  	*batch = gQueue{}
  5781  }
  5782  
  5783  // Try get a batch of G's from the global runnable queue.
  5784  // sched.lock must be held.
  5785  func globrunqget(_p_ *p, max int32) *g {
  5786  	assertLockHeld(&sched.lock)
  5787  
  5788  	if sched.runqsize == 0 {
  5789  		return nil
  5790  	}
  5791  
  5792  	n := sched.runqsize/gomaxprocs + 1
  5793  	if n > sched.runqsize {
  5794  		n = sched.runqsize
  5795  	}
  5796  	if max > 0 && n > max {
  5797  		n = max
  5798  	}
  5799  	if n > int32(len(_p_.runq))/2 {
  5800  		n = int32(len(_p_.runq)) / 2
  5801  	}
  5802  
  5803  	sched.runqsize -= n
  5804  
  5805  	gp := sched.runq.pop()
  5806  	n--
  5807  	for ; n > 0; n-- {
  5808  		gp1 := sched.runq.pop()
  5809  		runqput(_p_, gp1, false)
  5810  	}
  5811  	return gp
  5812  }
  5813  
  5814  // pMask is an atomic bitstring with one bit per P.
  5815  type pMask []uint32
  5816  
  5817  // read returns true if P id's bit is set.
  5818  func (p pMask) read(id uint32) bool {
  5819  	word := id / 32
  5820  	mask := uint32(1) << (id % 32)
  5821  	return (atomic.Load(&p[word]) & mask) != 0
  5822  }
  5823  
  5824  // set sets P id's bit.
  5825  func (p pMask) set(id int32) {
  5826  	word := id / 32
  5827  	mask := uint32(1) << (id % 32)
  5828  	atomic.Or(&p[word], mask)
  5829  }
  5830  
  5831  // clear clears P id's bit.
  5832  func (p pMask) clear(id int32) {
  5833  	word := id / 32
  5834  	mask := uint32(1) << (id % 32)
  5835  	atomic.And(&p[word], ^mask)
  5836  }
  5837  
  5838  // updateTimerPMask clears pp's timer mask if it has no timers on its heap.
  5839  //
  5840  // Ideally, the timer mask would be kept immediately consistent on any timer
  5841  // operations. Unfortunately, updating a shared global data structure in the
  5842  // timer hot path adds too much overhead in applications frequently switching
  5843  // between no timers and some timers.
  5844  //
  5845  // As a compromise, the timer mask is updated only on pidleget / pidleput. A
  5846  // running P (returned by pidleget) may add a timer at any time, so its mask
  5847  // must be set. An idle P (passed to pidleput) cannot add new timers while
  5848  // idle, so if it has no timers at that time, its mask may be cleared.
  5849  //
  5850  // Thus, we get the following effects on timer-stealing in findrunnable:
  5851  //
  5852  // * Idle Ps with no timers when they go idle are never checked in findrunnable
  5853  //   (for work- or timer-stealing; this is the ideal case).
  5854  // * Running Ps must always be checked.
  5855  // * Idle Ps whose timers are stolen must continue to be checked until they run
  5856  //   again, even after timer expiration.
  5857  //
  5858  // When the P starts running again, the mask should be set, as a timer may be
  5859  // added at any time.
  5860  //
  5861  // TODO(prattmic): Additional targeted updates may improve the above cases.
  5862  // e.g., updating the mask when stealing a timer.
  5863  func updateTimerPMask(pp *p) {
  5864  	if atomic.Load(&pp.numTimers) > 0 {
  5865  		return
  5866  	}
  5867  
  5868  	// Looks like there are no timers, however another P may transiently
  5869  	// decrement numTimers when handling a timerModified timer in
  5870  	// checkTimers. We must take timersLock to serialize with these changes.
  5871  	lock(&pp.timersLock)
  5872  	if atomic.Load(&pp.numTimers) == 0 {
  5873  		timerpMask.clear(pp.id)
  5874  	}
  5875  	unlock(&pp.timersLock)
  5876  }
  5877  
  5878  // pidleput puts p to on the _Pidle list.
  5879  //
  5880  // This releases ownership of p. Once sched.lock is released it is no longer
  5881  // safe to use p.
  5882  //
  5883  // sched.lock must be held.
  5884  //
  5885  // May run during STW, so write barriers are not allowed.
  5886  //go:nowritebarrierrec
  5887  func pidleput(_p_ *p) {
  5888  	assertLockHeld(&sched.lock)
  5889  
  5890  	if !runqempty(_p_) {
  5891  		throw("pidleput: P has non-empty run queue")
  5892  	}
  5893  	updateTimerPMask(_p_) // clear if there are no timers.
  5894  	idlepMask.set(_p_.id)
  5895  	_p_.link = sched.pidle
  5896  	sched.pidle.set(_p_)
  5897  	atomic.Xadd(&sched.npidle, 1) // TODO: fast atomic
  5898  }
  5899  
  5900  // pidleget tries to get a p from the _Pidle list, acquiring ownership.
  5901  //
  5902  // sched.lock must be held.
  5903  //
  5904  // May run during STW, so write barriers are not allowed.
  5905  //go:nowritebarrierrec
  5906  func pidleget() *p {
  5907  	assertLockHeld(&sched.lock)
  5908  
  5909  	_p_ := sched.pidle.ptr()
  5910  	if _p_ != nil {
  5911  		// Timer may get added at any time now.
  5912  		timerpMask.set(_p_.id)
  5913  		idlepMask.clear(_p_.id)
  5914  		sched.pidle = _p_.link
  5915  		atomic.Xadd(&sched.npidle, -1) // TODO: fast atomic
  5916  	}
  5917  	return _p_
  5918  }
  5919  
  5920  // runqempty reports whether _p_ has no Gs on its local run queue.
  5921  // It never returns true spuriously.
  5922  func runqempty(_p_ *p) bool {
  5923  	// Defend against a race where 1) _p_ has G1 in runqnext but runqhead == runqtail,
  5924  	// 2) runqput on _p_ kicks G1 to the runq, 3) runqget on _p_ empties runqnext.
  5925  	// Simply observing that runqhead == runqtail and then observing that runqnext == nil
  5926  	// does not mean the queue is empty.
  5927  	for {
  5928  		head := atomic.Load(&_p_.runqhead)
  5929  		tail := atomic.Load(&_p_.runqtail)
  5930  		runnext := atomic.Loaduintptr((*uintptr)(unsafe.Pointer(&_p_.runnext)))
  5931  		if tail == atomic.Load(&_p_.runqtail) {
  5932  			return head == tail && runnext == 0
  5933  		}
  5934  	}
  5935  }
  5936  
  5937  // To shake out latent assumptions about scheduling order,
  5938  // we introduce some randomness into scheduling decisions
  5939  // when running with the race detector.
  5940  // The need for this was made obvious by changing the
  5941  // (deterministic) scheduling order in Go 1.5 and breaking
  5942  // many poorly-written tests.
  5943  // With the randomness here, as long as the tests pass
  5944  // consistently with -race, they shouldn't have latent scheduling
  5945  // assumptions.
  5946  const randomizeScheduler = raceenabled
  5947  
  5948  // runqput tries to put g on the local runnable queue.
  5949  // If next is false, runqput adds g to the tail of the runnable queue.
  5950  // If next is true, runqput puts g in the _p_.runnext slot.
  5951  // If the run queue is full, runnext puts g on the global queue.
  5952  // Executed only by the owner P.
  5953  func runqput(_p_ *p, gp *g, next bool) {
  5954  	if randomizeScheduler && next && fastrand()%2 == 0 {
  5955  		next = false
  5956  	}
  5957  
  5958  	if next {
  5959  	retryNext:
  5960  		oldnext := _p_.runnext
  5961  		if !_p_.runnext.cas(oldnext, guintptr(unsafe.Pointer(gp))) {
  5962  			goto retryNext
  5963  		}
  5964  		if oldnext == 0 {
  5965  			return
  5966  		}
  5967  		// Kick the old runnext out to the regular run queue.
  5968  		gp = oldnext.ptr()
  5969  	}
  5970  
  5971  retry:
  5972  	h := atomic.LoadAcq(&_p_.runqhead) // load-acquire, synchronize with consumers
  5973  	t := _p_.runqtail
  5974  	if t-h < uint32(len(_p_.runq)) {
  5975  		_p_.runq[t%uint32(len(_p_.runq))].set(gp)
  5976  		atomic.StoreRel(&_p_.runqtail, t+1) // store-release, makes the item available for consumption
  5977  		return
  5978  	}
  5979  	if runqputslow(_p_, gp, h, t) {
  5980  		return
  5981  	}
  5982  	// the queue is not full, now the put above must succeed
  5983  	goto retry
  5984  }
  5985  
  5986  // Put g and a batch of work from local runnable queue on global queue.
  5987  // Executed only by the owner P.
  5988  func runqputslow(_p_ *p, gp *g, h, t uint32) bool {
  5989  	var batch [len(_p_.runq)/2 + 1]*g
  5990  
  5991  	// First, grab a batch from local queue.
  5992  	n := t - h
  5993  	n = n / 2
  5994  	if n != uint32(len(_p_.runq)/2) {
  5995  		throw("runqputslow: queue is not full")
  5996  	}
  5997  	for i := uint32(0); i < n; i++ {
  5998  		batch[i] = _p_.runq[(h+i)%uint32(len(_p_.runq))].ptr()
  5999  	}
  6000  	if !atomic.CasRel(&_p_.runqhead, h, h+n) { // cas-release, commits consume
  6001  		return false
  6002  	}
  6003  	batch[n] = gp
  6004  
  6005  	if randomizeScheduler {
  6006  		for i := uint32(1); i <= n; i++ {
  6007  			j := fastrandn(i + 1)
  6008  			batch[i], batch[j] = batch[j], batch[i]
  6009  		}
  6010  	}
  6011  
  6012  	// Link the goroutines.
  6013  	for i := uint32(0); i < n; i++ {
  6014  		batch[i].schedlink.set(batch[i+1])
  6015  	}
  6016  	var q gQueue
  6017  	q.head.set(batch[0])
  6018  	q.tail.set(batch[n])
  6019  
  6020  	// Now put the batch on global queue.
  6021  	lock(&sched.lock)
  6022  	globrunqputbatch(&q, int32(n+1))
  6023  	unlock(&sched.lock)
  6024  	return true
  6025  }
  6026  
  6027  // runqputbatch tries to put all the G's on q on the local runnable queue.
  6028  // If the queue is full, they are put on the global queue; in that case
  6029  // this will temporarily acquire the scheduler lock.
  6030  // Executed only by the owner P.
  6031  func runqputbatch(pp *p, q *gQueue, qsize int) {
  6032  	h := atomic.LoadAcq(&pp.runqhead)
  6033  	t := pp.runqtail
  6034  	n := uint32(0)
  6035  	for !q.empty() && t-h < uint32(len(pp.runq)) {
  6036  		gp := q.pop()
  6037  		pp.runq[t%uint32(len(pp.runq))].set(gp)
  6038  		t++
  6039  		n++
  6040  	}
  6041  	qsize -= int(n)
  6042  
  6043  	if randomizeScheduler {
  6044  		off := func(o uint32) uint32 {
  6045  			return (pp.runqtail + o) % uint32(len(pp.runq))
  6046  		}
  6047  		for i := uint32(1); i < n; i++ {
  6048  			j := fastrandn(i + 1)
  6049  			pp.runq[off(i)], pp.runq[off(j)] = pp.runq[off(j)], pp.runq[off(i)]
  6050  		}
  6051  	}
  6052  
  6053  	atomic.StoreRel(&pp.runqtail, t)
  6054  	if !q.empty() {
  6055  		lock(&sched.lock)
  6056  		globrunqputbatch(q, int32(qsize))
  6057  		unlock(&sched.lock)
  6058  	}
  6059  }
  6060  
  6061  // Get g from local runnable queue.
  6062  // If inheritTime is true, gp should inherit the remaining time in the
  6063  // current time slice. Otherwise, it should start a new time slice.
  6064  // Executed only by the owner P.
  6065  func runqget(_p_ *p) (gp *g, inheritTime bool) {
  6066  	// If there's a runnext, it's the next G to run.
  6067  	for {
  6068  		next := _p_.runnext
  6069  		if next == 0 {
  6070  			break
  6071  		}
  6072  		if _p_.runnext.cas(next, 0) {
  6073  			return next.ptr(), true
  6074  		}
  6075  	}
  6076  
  6077  	for {
  6078  		h := atomic.LoadAcq(&_p_.runqhead) // load-acquire, synchronize with other consumers
  6079  		t := _p_.runqtail
  6080  		if t == h {
  6081  			return nil, false
  6082  		}
  6083  		gp := _p_.runq[h%uint32(len(_p_.runq))].ptr()
  6084  		if atomic.CasRel(&_p_.runqhead, h, h+1) { // cas-release, commits consume
  6085  			return gp, false
  6086  		}
  6087  	}
  6088  }
  6089  
  6090  // runqdrain drains the local runnable queue of _p_ and returns all goroutines in it.
  6091  // Executed only by the owner P.
  6092  func runqdrain(_p_ *p) (drainQ gQueue, n uint32) {
  6093  	oldNext := _p_.runnext
  6094  	if oldNext != 0 && _p_.runnext.cas(oldNext, 0) {
  6095  		drainQ.pushBack(oldNext.ptr())
  6096  		n++
  6097  	}
  6098  
  6099  retry:
  6100  	h := atomic.LoadAcq(&_p_.runqhead) // load-acquire, synchronize with other consumers
  6101  	t := _p_.runqtail
  6102  	qn := t - h
  6103  	if qn == 0 {
  6104  		return
  6105  	}
  6106  	if qn > uint32(len(_p_.runq)) { // read inconsistent h and t
  6107  		goto retry
  6108  	}
  6109  
  6110  	if !atomic.CasRel(&_p_.runqhead, h, h+qn) { // cas-release, commits consume
  6111  		goto retry
  6112  	}
  6113  
  6114  	// We've inverted the order in which it gets G's from the local P's runnable queue
  6115  	// and then advances the head pointer because we don't want to mess up the statuses of G's
  6116  	// while runqdrain() and runqsteal() are running in parallel.
  6117  	// Thus we should advance the head pointer before draining the local P into a gQueue,
  6118  	// so that we can update any gp.schedlink only after we take the full ownership of G,
  6119  	// meanwhile, other P's can't access to all G's in local P's runnable queue and steal them.
  6120  	// See https://groups.google.com/g/golang-dev/c/0pTKxEKhHSc/m/6Q85QjdVBQAJ for more details.
  6121  	for i := uint32(0); i < qn; i++ {
  6122  		gp := _p_.runq[(h+i)%uint32(len(_p_.runq))].ptr()
  6123  		drainQ.pushBack(gp)
  6124  		n++
  6125  	}
  6126  	return
  6127  }
  6128  
  6129  // Grabs a batch of goroutines from _p_'s runnable queue into batch.
  6130  // Batch is a ring buffer starting at batchHead.
  6131  // Returns number of grabbed goroutines.
  6132  // Can be executed by any P.
  6133  func runqgrab(_p_ *p, batch *[256]guintptr, batchHead uint32, stealRunNextG bool) uint32 {
  6134  	for {
  6135  		h := atomic.LoadAcq(&_p_.runqhead) // load-acquire, synchronize with other consumers
  6136  		t := atomic.LoadAcq(&_p_.runqtail) // load-acquire, synchronize with the producer
  6137  		n := t - h
  6138  		n = n - n/2
  6139  		if n == 0 {
  6140  			if stealRunNextG {
  6141  				// Try to steal from _p_.runnext.
  6142  				if next := _p_.runnext; next != 0 {
  6143  					if _p_.status == _Prunning {
  6144  						// Sleep to ensure that _p_ isn't about to run the g
  6145  						// we are about to steal.
  6146  						// The important use case here is when the g running
  6147  						// on _p_ ready()s another g and then almost
  6148  						// immediately blocks. Instead of stealing runnext
  6149  						// in this window, back off to give _p_ a chance to
  6150  						// schedule runnext. This will avoid thrashing gs
  6151  						// between different Ps.
  6152  						// A sync chan send/recv takes ~50ns as of time of
  6153  						// writing, so 3us gives ~50x overshoot.
  6154  						if GOOS != "windows" {
  6155  							usleep(3)
  6156  						} else {
  6157  							// On windows system timer granularity is
  6158  							// 1-15ms, which is way too much for this
  6159  							// optimization. So just yield.
  6160  							osyield()
  6161  						}
  6162  					}
  6163  					if !_p_.runnext.cas(next, 0) {
  6164  						continue
  6165  					}
  6166  					batch[batchHead%uint32(len(batch))] = next
  6167  					return 1
  6168  				}
  6169  			}
  6170  			return 0
  6171  		}
  6172  		if n > uint32(len(_p_.runq)/2) { // read inconsistent h and t
  6173  			continue
  6174  		}
  6175  		for i := uint32(0); i < n; i++ {
  6176  			g := _p_.runq[(h+i)%uint32(len(_p_.runq))]
  6177  			batch[(batchHead+i)%uint32(len(batch))] = g
  6178  		}
  6179  		if atomic.CasRel(&_p_.runqhead, h, h+n) { // cas-release, commits consume
  6180  			return n
  6181  		}
  6182  	}
  6183  }
  6184  
  6185  // Steal half of elements from local runnable queue of p2
  6186  // and put onto local runnable queue of p.
  6187  // Returns one of the stolen elements (or nil if failed).
  6188  func runqsteal(_p_, p2 *p, stealRunNextG bool) *g {
  6189  	t := _p_.runqtail
  6190  	n := runqgrab(p2, &_p_.runq, t, stealRunNextG)
  6191  	if n == 0 {
  6192  		return nil
  6193  	}
  6194  	n--
  6195  	gp := _p_.runq[(t+n)%uint32(len(_p_.runq))].ptr()
  6196  	if n == 0 {
  6197  		return gp
  6198  	}
  6199  	h := atomic.LoadAcq(&_p_.runqhead) // load-acquire, synchronize with consumers
  6200  	if t-h+n >= uint32(len(_p_.runq)) {
  6201  		throw("runqsteal: runq overflow")
  6202  	}
  6203  	atomic.StoreRel(&_p_.runqtail, t+n) // store-release, makes the item available for consumption
  6204  	return gp
  6205  }
  6206  
  6207  // A gQueue is a dequeue of Gs linked through g.schedlink. A G can only
  6208  // be on one gQueue or gList at a time.
  6209  type gQueue struct {
  6210  	head guintptr
  6211  	tail guintptr
  6212  }
  6213  
  6214  // empty reports whether q is empty.
  6215  func (q *gQueue) empty() bool {
  6216  	return q.head == 0
  6217  }
  6218  
  6219  // push adds gp to the head of q.
  6220  func (q *gQueue) push(gp *g) {
  6221  	gp.schedlink = q.head
  6222  	q.head.set(gp)
  6223  	if q.tail == 0 {
  6224  		q.tail.set(gp)
  6225  	}
  6226  }
  6227  
  6228  // pushBack adds gp to the tail of q.
  6229  func (q *gQueue) pushBack(gp *g) {
  6230  	gp.schedlink = 0
  6231  	if q.tail != 0 {
  6232  		q.tail.ptr().schedlink.set(gp)
  6233  	} else {
  6234  		q.head.set(gp)
  6235  	}
  6236  	q.tail.set(gp)
  6237  }
  6238  
  6239  // pushBackAll adds all Gs in l2 to the tail of q. After this q2 must
  6240  // not be used.
  6241  func (q *gQueue) pushBackAll(q2 gQueue) {
  6242  	if q2.tail == 0 {
  6243  		return
  6244  	}
  6245  	q2.tail.ptr().schedlink = 0
  6246  	if q.tail != 0 {
  6247  		q.tail.ptr().schedlink = q2.head
  6248  	} else {
  6249  		q.head = q2.head
  6250  	}
  6251  	q.tail = q2.tail
  6252  }
  6253  
  6254  // pop removes and returns the head of queue q. It returns nil if
  6255  // q is empty.
  6256  func (q *gQueue) pop() *g {
  6257  	gp := q.head.ptr()
  6258  	if gp != nil {
  6259  		q.head = gp.schedlink
  6260  		if q.head == 0 {
  6261  			q.tail = 0
  6262  		}
  6263  	}
  6264  	return gp
  6265  }
  6266  
  6267  // popList takes all Gs in q and returns them as a gList.
  6268  func (q *gQueue) popList() gList {
  6269  	stack := gList{q.head}
  6270  	*q = gQueue{}
  6271  	return stack
  6272  }
  6273  
  6274  // A gList is a list of Gs linked through g.schedlink. A G can only be
  6275  // on one gQueue or gList at a time.
  6276  type gList struct {
  6277  	head guintptr
  6278  }
  6279  
  6280  // empty reports whether l is empty.
  6281  func (l *gList) empty() bool {
  6282  	return l.head == 0
  6283  }
  6284  
  6285  // push adds gp to the head of l.
  6286  func (l *gList) push(gp *g) {
  6287  	gp.schedlink = l.head
  6288  	l.head.set(gp)
  6289  }
  6290  
  6291  // pushAll prepends all Gs in q to l.
  6292  func (l *gList) pushAll(q gQueue) {
  6293  	if !q.empty() {
  6294  		q.tail.ptr().schedlink = l.head
  6295  		l.head = q.head
  6296  	}
  6297  }
  6298  
  6299  // pop removes and returns the head of l. If l is empty, it returns nil.
  6300  func (l *gList) pop() *g {
  6301  	gp := l.head.ptr()
  6302  	if gp != nil {
  6303  		l.head = gp.schedlink
  6304  	}
  6305  	return gp
  6306  }
  6307  
  6308  //go:linkname setMaxThreads runtime/debug.setMaxThreads
  6309  func setMaxThreads(in int) (out int) {
  6310  	lock(&sched.lock)
  6311  	out = int(sched.maxmcount)
  6312  	if in > 0x7fffffff { // MaxInt32
  6313  		sched.maxmcount = 0x7fffffff
  6314  	} else {
  6315  		sched.maxmcount = int32(in)
  6316  	}
  6317  	checkmcount()
  6318  	unlock(&sched.lock)
  6319  	return
  6320  }
  6321  
  6322  //go:nosplit
  6323  func procPin() int {
  6324  	_g_ := getg()
  6325  	mp := _g_.m
  6326  
  6327  	mp.locks++
  6328  	return int(mp.p.ptr().id)
  6329  }
  6330  
  6331  //go:nosplit
  6332  func procUnpin() {
  6333  	_g_ := getg()
  6334  	_g_.m.locks--
  6335  }
  6336  
  6337  //go:linkname sync_runtime_procPin sync.runtime_procPin
  6338  //go:nosplit
  6339  func sync_runtime_procPin() int {
  6340  	return procPin()
  6341  }
  6342  
  6343  //go:linkname sync_runtime_procUnpin sync.runtime_procUnpin
  6344  //go:nosplit
  6345  func sync_runtime_procUnpin() {
  6346  	procUnpin()
  6347  }
  6348  
  6349  //go:linkname sync_atomic_runtime_procPin sync/atomic.runtime_procPin
  6350  //go:nosplit
  6351  func sync_atomic_runtime_procPin() int {
  6352  	return procPin()
  6353  }
  6354  
  6355  //go:linkname sync_atomic_runtime_procUnpin sync/atomic.runtime_procUnpin
  6356  //go:nosplit
  6357  func sync_atomic_runtime_procUnpin() {
  6358  	procUnpin()
  6359  }
  6360  
  6361  // Active spinning for sync.Mutex.
  6362  //go:linkname sync_runtime_canSpin sync.runtime_canSpin
  6363  //go:nosplit
  6364  func sync_runtime_canSpin(i int) bool {
  6365  	// sync.Mutex is cooperative, so we are conservative with spinning.
  6366  	// Spin only few times and only if running on a multicore machine and
  6367  	// GOMAXPROCS>1 and there is at least one other running P and local runq is empty.
  6368  	// As opposed to runtime mutex we don't do passive spinning here,
  6369  	// because there can be work on global runq or on other Ps.
  6370  	if i >= active_spin || ncpu <= 1 || gomaxprocs <= int32(sched.npidle+sched.nmspinning)+1 {
  6371  		return false
  6372  	}
  6373  	if p := getg().m.p.ptr(); !runqempty(p) {
  6374  		return false
  6375  	}
  6376  	return true
  6377  }
  6378  
  6379  //go:linkname sync_runtime_doSpin sync.runtime_doSpin
  6380  //go:nosplit
  6381  func sync_runtime_doSpin() {
  6382  	procyield(active_spin_cnt)
  6383  }
  6384  
  6385  var stealOrder randomOrder
  6386  
  6387  // randomOrder/randomEnum are helper types for randomized work stealing.
  6388  // They allow to enumerate all Ps in different pseudo-random orders without repetitions.
  6389  // The algorithm is based on the fact that if we have X such that X and GOMAXPROCS
  6390  // are coprime, then a sequences of (i + X) % GOMAXPROCS gives the required enumeration.
  6391  type randomOrder struct {
  6392  	count    uint32
  6393  	coprimes []uint32
  6394  }
  6395  
  6396  type randomEnum struct {
  6397  	i     uint32
  6398  	count uint32
  6399  	pos   uint32
  6400  	inc   uint32
  6401  }
  6402  
  6403  func (ord *randomOrder) reset(count uint32) {
  6404  	ord.count = count
  6405  	ord.coprimes = ord.coprimes[:0]
  6406  	for i := uint32(1); i <= count; i++ {
  6407  		if gcd(i, count) == 1 {
  6408  			ord.coprimes = append(ord.coprimes, i)
  6409  		}
  6410  	}
  6411  }
  6412  
  6413  func (ord *randomOrder) start(i uint32) randomEnum {
  6414  	return randomEnum{
  6415  		count: ord.count,
  6416  		pos:   i % ord.count,
  6417  		inc:   ord.coprimes[i%uint32(len(ord.coprimes))],
  6418  	}
  6419  }
  6420  
  6421  func (enum *randomEnum) done() bool {
  6422  	return enum.i == enum.count
  6423  }
  6424  
  6425  func (enum *randomEnum) next() {
  6426  	enum.i++
  6427  	enum.pos = (enum.pos + enum.inc) % enum.count
  6428  }
  6429  
  6430  func (enum *randomEnum) position() uint32 {
  6431  	return enum.pos
  6432  }
  6433  
  6434  func gcd(a, b uint32) uint32 {
  6435  	for b != 0 {
  6436  		a, b = b, a%b
  6437  	}
  6438  	return a
  6439  }
  6440  
  6441  // An initTask represents the set of initializations that need to be done for a package.
  6442  // Keep in sync with ../../test/initempty.go:initTask
  6443  type initTask struct {
  6444  	// TODO: pack the first 3 fields more tightly?
  6445  	state uintptr // 0 = uninitialized, 1 = in progress, 2 = done
  6446  	ndeps uintptr
  6447  	nfns  uintptr
  6448  	// followed by ndeps instances of an *initTask, one per package depended on
  6449  	// followed by nfns pcs, one per init function to run
  6450  }
  6451  
  6452  // inittrace stores statistics for init functions which are
  6453  // updated by malloc and newproc when active is true.
  6454  var inittrace tracestat
  6455  
  6456  type tracestat struct {
  6457  	active bool   // init tracing activation status
  6458  	id     int64  // init goroutine id
  6459  	allocs uint64 // heap allocations
  6460  	bytes  uint64 // heap allocated bytes
  6461  }
  6462  
  6463  func doInit(t *initTask) {
  6464  	switch t.state {
  6465  	case 2: // fully initialized
  6466  		return
  6467  	case 1: // initialization in progress
  6468  		throw("recursive call during initialization - linker skew")
  6469  	default: // not initialized yet
  6470  		t.state = 1 // initialization in progress
  6471  
  6472  		for i := uintptr(0); i < t.ndeps; i++ {
  6473  			p := add(unsafe.Pointer(t), (3+i)*sys.PtrSize)
  6474  			t2 := *(**initTask)(p)
  6475  			doInit(t2)
  6476  		}
  6477  
  6478  		if t.nfns == 0 {
  6479  			t.state = 2 // initialization done
  6480  			return
  6481  		}
  6482  
  6483  		var (
  6484  			start  int64
  6485  			before tracestat
  6486  		)
  6487  
  6488  		if inittrace.active {
  6489  			start = nanotime()
  6490  			// Load stats non-atomically since tracinit is updated only by this init goroutine.
  6491  			before = inittrace
  6492  		}
  6493  
  6494  		firstFunc := add(unsafe.Pointer(t), (3+t.ndeps)*sys.PtrSize)
  6495  		for i := uintptr(0); i < t.nfns; i++ {
  6496  			p := add(firstFunc, i*sys.PtrSize)
  6497  			f := *(*func())(unsafe.Pointer(&p))
  6498  			f()
  6499  		}
  6500  
  6501  		if inittrace.active {
  6502  			end := nanotime()
  6503  			// Load stats non-atomically since tracinit is updated only by this init goroutine.
  6504  			after := inittrace
  6505  
  6506  			pkg := funcpkgpath(findfunc(funcPC(firstFunc)))
  6507  
  6508  			var sbuf [24]byte
  6509  			print("init ", pkg, " @")
  6510  			print(string(fmtNSAsMS(sbuf[:], uint64(start-runtimeInitTime))), " ms, ")
  6511  			print(string(fmtNSAsMS(sbuf[:], uint64(end-start))), " ms clock, ")
  6512  			print(string(itoa(sbuf[:], after.bytes-before.bytes)), " bytes, ")
  6513  			print(string(itoa(sbuf[:], after.allocs-before.allocs)), " allocs")
  6514  			print("\n")
  6515  		}
  6516  
  6517  		t.state = 2 // initialization done
  6518  	}
  6519  }
  6520  

View as plain text