Source file src/runtime/proc.go

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

View as plain text