Black Lives Matter. Support the Equal Justice Initiative.

Source file src/runtime/proc.go

Documentation: runtime

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

View as plain text