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

View as plain text