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

View as plain text