Source file src/runtime/proc.go

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

View as plain text