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

View as plain text