...

Source file src/runtime/proc.go

Documentation: runtime

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

View as plain text