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

View as plain text