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

View as plain text