github.com/ActiveState/go@v0.0.0-20170614201249-0b81c023a722/src/runtime/proc.go (about) 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 "runtime/internal/atomic" 9 "runtime/internal/sys" 10 "unsafe" 11 ) 12 13 var buildVersion = sys.TheVersion 14 15 // Goroutine scheduler 16 // The scheduler's job is to distribute ready-to-run goroutines over worker threads. 17 // 18 // The main concepts are: 19 // G - goroutine. 20 // M - worker thread, or machine. 21 // P - processor, a resource that is required to execute Go code. 22 // M must have an associated P to execute Go code, however it can be 23 // blocked or in a syscall w/o an associated P. 24 // 25 // Design doc at https://golang.org/s/go11sched. 26 27 // Worker thread parking/unparking. 28 // We need to balance between keeping enough running worker threads to utilize 29 // available hardware parallelism and parking excessive running worker threads 30 // to conserve CPU resources and power. This is not simple for two reasons: 31 // (1) scheduler state is intentionally distributed (in particular, per-P work 32 // queues), so it is not possible to compute global predicates on fast paths; 33 // (2) for optimal thread management we would need to know the future (don't park 34 // a worker thread when a new goroutine will be readied in near future). 35 // 36 // Three rejected approaches that would work badly: 37 // 1. Centralize all scheduler state (would inhibit scalability). 38 // 2. Direct goroutine handoff. That is, when we ready a new goroutine and there 39 // is a spare P, unpark a thread and handoff it the thread and the goroutine. 40 // This would lead to thread state thrashing, as the thread that readied the 41 // goroutine can be out of work the very next moment, we will need to park it. 42 // Also, it would destroy locality of computation as we want to preserve 43 // dependent goroutines on the same thread; and introduce additional latency. 44 // 3. Unpark an additional thread whenever we ready a goroutine and there is an 45 // idle P, but don't do handoff. This would lead to excessive thread parking/ 46 // unparking as the additional threads will instantly park without discovering 47 // any work to do. 48 // 49 // The current approach: 50 // We unpark an additional thread when we ready a goroutine if (1) there is an 51 // idle P and there are no "spinning" worker threads. A worker thread is considered 52 // spinning if it is out of local work and did not find work in global run queue/ 53 // netpoller; the spinning state is denoted in m.spinning and in sched.nmspinning. 54 // Threads unparked this way are also considered spinning; we don't do goroutine 55 // handoff so such threads are out of work initially. Spinning threads do some 56 // spinning looking for work in per-P run queues before parking. If a spinning 57 // thread finds work it takes itself out of the spinning state and proceeds to 58 // execution. If it does not find work it takes itself out of the spinning state 59 // and then parks. 60 // If there is at least one spinning thread (sched.nmspinning>1), we don't unpark 61 // new threads when readying goroutines. To compensate for that, if the last spinning 62 // thread finds work and stops spinning, it must unpark a new spinning thread. 63 // This approach smooths out unjustified spikes of thread unparking, 64 // but at the same time guarantees eventual maximal CPU parallelism utilization. 65 // 66 // The main implementation complication is that we need to be very careful during 67 // spinning->non-spinning thread transition. This transition can race with submission 68 // of a new goroutine, and either one part or another needs to unpark another worker 69 // thread. If they both fail to do that, we can end up with semi-persistent CPU 70 // underutilization. The general pattern for goroutine readying is: submit a goroutine 71 // to local work queue, #StoreLoad-style memory barrier, check sched.nmspinning. 72 // The general pattern for spinning->non-spinning transition is: decrement nmspinning, 73 // #StoreLoad-style memory barrier, check all per-P work queues for new work. 74 // Note that all this complexity does not apply to global run queue as we are not 75 // sloppy about thread unparking when submitting to global queue. Also see comments 76 // for nmspinning manipulation. 77 78 var ( 79 m0 m 80 g0 g 81 raceprocctx0 uintptr 82 ) 83 84 //go:linkname runtime_init runtime.init 85 func runtime_init() 86 87 //go:linkname main_init main.init 88 func main_init() 89 90 // main_init_done is a signal used by cgocallbackg that initialization 91 // has been completed. It is made before _cgo_notify_runtime_init_done, 92 // so all cgo calls can rely on it existing. When main_init is complete, 93 // it is closed, meaning cgocallbackg can reliably receive from it. 94 var main_init_done chan bool 95 96 //go:linkname main_main main.main 97 func main_main() 98 99 // runtimeInitTime is the nanotime() at which the runtime started. 100 var runtimeInitTime int64 101 102 // Value to use for signal mask for newly created M's. 103 var initSigmask sigset 104 105 // The main goroutine. 106 func main() { 107 g := getg() 108 109 // Racectx of m0->g0 is used only as the parent of the main goroutine. 110 // It must not be used for anything else. 111 g.m.g0.racectx = 0 112 113 // Max stack size is 1 GB on 64-bit, 250 MB on 32-bit. 114 // Using decimal instead of binary GB and MB because 115 // they look nicer in the stack overflow failure message. 116 if sys.PtrSize == 8 { 117 maxstacksize = 1000000000 118 } else { 119 maxstacksize = 250000000 120 } 121 122 // Record when the world started. 123 runtimeInitTime = nanotime() 124 125 systemstack(func() { 126 newm(sysmon, nil) 127 }) 128 129 // Lock the main goroutine onto this, the main OS thread, 130 // during initialization. Most programs won't care, but a few 131 // do require certain calls to be made by the main thread. 132 // Those can arrange for main.main to run in the main thread 133 // by calling runtime.LockOSThread during initialization 134 // to preserve the lock. 135 lockOSThread() 136 137 if g.m != &m0 { 138 throw("runtime.main not on m0") 139 } 140 141 runtime_init() // must be before defer 142 143 // Defer unlock so that runtime.Goexit during init does the unlock too. 144 needUnlock := true 145 defer func() { 146 if needUnlock { 147 unlockOSThread() 148 } 149 }() 150 151 gcenable() 152 153 main_init_done = make(chan bool) 154 if iscgo { 155 if _cgo_thread_start == nil { 156 throw("_cgo_thread_start missing") 157 } 158 if GOOS != "windows" { 159 if _cgo_setenv == nil { 160 throw("_cgo_setenv missing") 161 } 162 if _cgo_unsetenv == nil { 163 throw("_cgo_unsetenv missing") 164 } 165 } 166 if _cgo_notify_runtime_init_done == nil { 167 throw("_cgo_notify_runtime_init_done missing") 168 } 169 cgocall(_cgo_notify_runtime_init_done, nil) 170 } 171 172 fn := main_init // make an indirect call, as the linker doesn't know the address of the main package when laying down the runtime 173 fn() 174 close(main_init_done) 175 176 needUnlock = false 177 unlockOSThread() 178 179 if isarchive || islibrary { 180 // A program compiled with -buildmode=c-archive or c-shared 181 // has a main, but it is not executed. 182 return 183 } 184 fn = main_main // make an indirect call, as the linker doesn't know the address of the main package when laying down the runtime 185 fn() 186 if raceenabled { 187 racefini() 188 } 189 190 // Make racy client program work: if panicking on 191 // another goroutine at the same time as main returns, 192 // let the other goroutine finish printing the panic trace. 193 // Once it does, it will exit. See issues 3934 and 20018. 194 if atomic.Load(&runningPanicDefers) != 0 { 195 // Running deferred functions should not take long. 196 for c := 0; c < 1000; c++ { 197 if atomic.Load(&runningPanicDefers) == 0 { 198 break 199 } 200 Gosched() 201 } 202 } 203 if atomic.Load(&panicking) != 0 { 204 gopark(nil, nil, "panicwait", traceEvGoStop, 1) 205 } 206 207 exit(0) 208 for { 209 var x *int32 210 *x = 0 211 } 212 } 213 214 // os_beforeExit is called from os.Exit(0). 215 //go:linkname os_beforeExit os.runtime_beforeExit 216 func os_beforeExit() { 217 if raceenabled { 218 racefini() 219 } 220 } 221 222 // start forcegc helper goroutine 223 func init() { 224 go forcegchelper() 225 } 226 227 func forcegchelper() { 228 forcegc.g = getg() 229 for { 230 lock(&forcegc.lock) 231 if forcegc.idle != 0 { 232 throw("forcegc: phase error") 233 } 234 atomic.Store(&forcegc.idle, 1) 235 goparkunlock(&forcegc.lock, "force gc (idle)", traceEvGoBlock, 1) 236 // this goroutine is explicitly resumed by sysmon 237 if debug.gctrace > 0 { 238 println("GC forced") 239 } 240 // Time-triggered, fully concurrent. 241 gcStart(gcBackgroundMode, gcTrigger{kind: gcTriggerTime, now: nanotime()}) 242 } 243 } 244 245 // Gosched yields the processor, allowing other goroutines to run. It does not 246 // suspend the current goroutine, so execution resumes automatically. 247 //go:nosplit 248 func Gosched() { 249 mcall(gosched_m) 250 } 251 252 // goschedguarded yields the processor like gosched, but also checks 253 // for forbidden states and opts out of the yield in those cases. 254 //go:nosplit 255 func goschedguarded() { 256 mcall(goschedguarded_m) 257 } 258 259 // Puts the current goroutine into a waiting state and calls unlockf. 260 // If unlockf returns false, the goroutine is resumed. 261 // unlockf must not access this G's stack, as it may be moved between 262 // the call to gopark and the call to unlockf. 263 func gopark(unlockf func(*g, unsafe.Pointer) bool, lock unsafe.Pointer, reason string, traceEv byte, traceskip int) { 264 mp := acquirem() 265 gp := mp.curg 266 status := readgstatus(gp) 267 if status != _Grunning && status != _Gscanrunning { 268 throw("gopark: bad g status") 269 } 270 mp.waitlock = lock 271 mp.waitunlockf = *(*unsafe.Pointer)(unsafe.Pointer(&unlockf)) 272 gp.waitreason = reason 273 mp.waittraceev = traceEv 274 mp.waittraceskip = traceskip 275 releasem(mp) 276 // can't do anything that might move the G between Ms here. 277 mcall(park_m) 278 } 279 280 // Puts the current goroutine into a waiting state and unlocks the lock. 281 // The goroutine can be made runnable again by calling goready(gp). 282 func goparkunlock(lock *mutex, reason string, traceEv byte, traceskip int) { 283 gopark(parkunlock_c, unsafe.Pointer(lock), reason, traceEv, traceskip) 284 } 285 286 func goready(gp *g, traceskip int) { 287 systemstack(func() { 288 ready(gp, traceskip, true) 289 }) 290 } 291 292 //go:nosplit 293 func acquireSudog() *sudog { 294 // Delicate dance: the semaphore implementation calls 295 // acquireSudog, acquireSudog calls new(sudog), 296 // new calls malloc, malloc can call the garbage collector, 297 // and the garbage collector calls the semaphore implementation 298 // in stopTheWorld. 299 // Break the cycle by doing acquirem/releasem around new(sudog). 300 // The acquirem/releasem increments m.locks during new(sudog), 301 // which keeps the garbage collector from being invoked. 302 mp := acquirem() 303 pp := mp.p.ptr() 304 if len(pp.sudogcache) == 0 { 305 lock(&sched.sudoglock) 306 // First, try to grab a batch from central cache. 307 for len(pp.sudogcache) < cap(pp.sudogcache)/2 && sched.sudogcache != nil { 308 s := sched.sudogcache 309 sched.sudogcache = s.next 310 s.next = nil 311 pp.sudogcache = append(pp.sudogcache, s) 312 } 313 unlock(&sched.sudoglock) 314 // If the central cache is empty, allocate a new one. 315 if len(pp.sudogcache) == 0 { 316 pp.sudogcache = append(pp.sudogcache, new(sudog)) 317 } 318 } 319 n := len(pp.sudogcache) 320 s := pp.sudogcache[n-1] 321 pp.sudogcache[n-1] = nil 322 pp.sudogcache = pp.sudogcache[:n-1] 323 if s.elem != nil { 324 throw("acquireSudog: found s.elem != nil in cache") 325 } 326 releasem(mp) 327 return s 328 } 329 330 //go:nosplit 331 func releaseSudog(s *sudog) { 332 if s.elem != nil { 333 throw("runtime: sudog with non-nil elem") 334 } 335 if s.selectdone != nil { 336 throw("runtime: sudog with non-nil selectdone") 337 } 338 if s.next != nil { 339 throw("runtime: sudog with non-nil next") 340 } 341 if s.prev != nil { 342 throw("runtime: sudog with non-nil prev") 343 } 344 if s.waitlink != nil { 345 throw("runtime: sudog with non-nil waitlink") 346 } 347 if s.c != nil { 348 throw("runtime: sudog with non-nil c") 349 } 350 gp := getg() 351 if gp.param != nil { 352 throw("runtime: releaseSudog with non-nil gp.param") 353 } 354 mp := acquirem() // avoid rescheduling to another P 355 pp := mp.p.ptr() 356 if len(pp.sudogcache) == cap(pp.sudogcache) { 357 // Transfer half of local cache to the central cache. 358 var first, last *sudog 359 for len(pp.sudogcache) > cap(pp.sudogcache)/2 { 360 n := len(pp.sudogcache) 361 p := pp.sudogcache[n-1] 362 pp.sudogcache[n-1] = nil 363 pp.sudogcache = pp.sudogcache[:n-1] 364 if first == nil { 365 first = p 366 } else { 367 last.next = p 368 } 369 last = p 370 } 371 lock(&sched.sudoglock) 372 last.next = sched.sudogcache 373 sched.sudogcache = first 374 unlock(&sched.sudoglock) 375 } 376 pp.sudogcache = append(pp.sudogcache, s) 377 releasem(mp) 378 } 379 380 // funcPC returns the entry PC of the function f. 381 // It assumes that f is a func value. Otherwise the behavior is undefined. 382 //go:nosplit 383 func funcPC(f interface{}) uintptr { 384 return **(**uintptr)(add(unsafe.Pointer(&f), sys.PtrSize)) 385 } 386 387 // called from assembly 388 func badmcall(fn func(*g)) { 389 throw("runtime: mcall called on m->g0 stack") 390 } 391 392 func badmcall2(fn func(*g)) { 393 throw("runtime: mcall function returned") 394 } 395 396 func badreflectcall() { 397 panic(plainError("arg size to reflect.call more than 1GB")) 398 } 399 400 var badmorestackg0Msg = "fatal: morestack on g0\n" 401 402 //go:nosplit 403 //go:nowritebarrierrec 404 func badmorestackg0() { 405 sp := stringStructOf(&badmorestackg0Msg) 406 write(2, sp.str, int32(sp.len)) 407 } 408 409 var badmorestackgsignalMsg = "fatal: morestack on gsignal\n" 410 411 //go:nosplit 412 //go:nowritebarrierrec 413 func badmorestackgsignal() { 414 sp := stringStructOf(&badmorestackgsignalMsg) 415 write(2, sp.str, int32(sp.len)) 416 } 417 418 //go:nosplit 419 func badctxt() { 420 throw("ctxt != 0") 421 } 422 423 func lockedOSThread() bool { 424 gp := getg() 425 return gp.lockedm != nil && gp.m.lockedg != nil 426 } 427 428 var ( 429 allgs []*g 430 allglock mutex 431 ) 432 433 func allgadd(gp *g) { 434 if readgstatus(gp) == _Gidle { 435 throw("allgadd: bad status Gidle") 436 } 437 438 lock(&allglock) 439 allgs = append(allgs, gp) 440 allglen = uintptr(len(allgs)) 441 unlock(&allglock) 442 } 443 444 const ( 445 // Number of goroutine ids to grab from sched.goidgen to local per-P cache at once. 446 // 16 seems to provide enough amortization, but other than that it's mostly arbitrary number. 447 _GoidCacheBatch = 16 448 ) 449 450 // The bootstrap sequence is: 451 // 452 // call osinit 453 // call schedinit 454 // make & queue new G 455 // call runtime·mstart 456 // 457 // The new G calls runtime·main. 458 func schedinit() { 459 // raceinit must be the first call to race detector. 460 // In particular, it must be done before mallocinit below calls racemapshadow. 461 _g_ := getg() 462 if raceenabled { 463 _g_.racectx, raceprocctx0 = raceinit() 464 } 465 466 sched.maxmcount = 10000 467 468 tracebackinit() 469 moduledataverify() 470 stackinit() 471 mallocinit() 472 mcommoninit(_g_.m) 473 alginit() // maps must not be used before this call 474 modulesinit() // provides activeModules 475 typelinksinit() // uses maps, activeModules 476 itabsinit() // uses activeModules 477 478 msigsave(_g_.m) 479 initSigmask = _g_.m.sigmask 480 481 goargs() 482 goenvs() 483 parsedebugvars() 484 gcinit() 485 486 sched.lastpoll = uint64(nanotime()) 487 procs := ncpu 488 if n, ok := atoi32(gogetenv("GOMAXPROCS")); ok && n > 0 { 489 procs = n 490 } 491 if procs > _MaxGomaxprocs { 492 procs = _MaxGomaxprocs 493 } 494 if procresize(procs) != nil { 495 throw("unknown runnable goroutine during bootstrap") 496 } 497 498 if buildVersion == "" { 499 // Condition should never trigger. This code just serves 500 // to ensure runtime·buildVersion is kept in the resulting binary. 501 buildVersion = "unknown" 502 } 503 } 504 505 func dumpgstatus(gp *g) { 506 _g_ := getg() 507 print("runtime: gp: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n") 508 print("runtime: g: g=", _g_, ", goid=", _g_.goid, ", g->atomicstatus=", readgstatus(_g_), "\n") 509 } 510 511 func checkmcount() { 512 // sched lock is held 513 if sched.mcount > sched.maxmcount { 514 print("runtime: program exceeds ", sched.maxmcount, "-thread limit\n") 515 throw("thread exhaustion") 516 } 517 } 518 519 func mcommoninit(mp *m) { 520 _g_ := getg() 521 522 // g0 stack won't make sense for user (and is not necessary unwindable). 523 if _g_ != _g_.m.g0 { 524 callers(1, mp.createstack[:]) 525 } 526 527 mp.fastrand = 0x49f6428a + uint32(mp.id) + uint32(cputicks()) 528 if mp.fastrand == 0 { 529 mp.fastrand = 0x49f6428a 530 } 531 532 lock(&sched.lock) 533 mp.id = sched.mcount 534 sched.mcount++ 535 checkmcount() 536 mpreinit(mp) 537 if mp.gsignal != nil { 538 mp.gsignal.stackguard1 = mp.gsignal.stack.lo + _StackGuard 539 } 540 541 // Add to allm so garbage collector doesn't free g->m 542 // when it is just in a register or thread-local storage. 543 mp.alllink = allm 544 545 // NumCgoCall() iterates over allm w/o schedlock, 546 // so we need to publish it safely. 547 atomicstorep(unsafe.Pointer(&allm), unsafe.Pointer(mp)) 548 unlock(&sched.lock) 549 550 // Allocate memory to hold a cgo traceback if the cgo call crashes. 551 if iscgo || GOOS == "solaris" || GOOS == "windows" { 552 mp.cgoCallers = new(cgoCallers) 553 } 554 } 555 556 // Mark gp ready to run. 557 func ready(gp *g, traceskip int, next bool) { 558 if trace.enabled { 559 traceGoUnpark(gp, traceskip) 560 } 561 562 status := readgstatus(gp) 563 564 // Mark runnable. 565 _g_ := getg() 566 _g_.m.locks++ // disable preemption because it can be holding p in a local var 567 if status&^_Gscan != _Gwaiting { 568 dumpgstatus(gp) 569 throw("bad g->status in ready") 570 } 571 572 // status is Gwaiting or Gscanwaiting, make Grunnable and put on runq 573 casgstatus(gp, _Gwaiting, _Grunnable) 574 runqput(_g_.m.p.ptr(), gp, next) 575 if atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 { 576 wakep() 577 } 578 _g_.m.locks-- 579 if _g_.m.locks == 0 && _g_.preempt { // restore the preemption request in Case we've cleared it in newstack 580 _g_.stackguard0 = stackPreempt 581 } 582 } 583 584 func gcprocs() int32 { 585 // Figure out how many CPUs to use during GC. 586 // Limited by gomaxprocs, number of actual CPUs, and MaxGcproc. 587 lock(&sched.lock) 588 n := gomaxprocs 589 if n > ncpu { 590 n = ncpu 591 } 592 if n > _MaxGcproc { 593 n = _MaxGcproc 594 } 595 if n > sched.nmidle+1 { // one M is currently running 596 n = sched.nmidle + 1 597 } 598 unlock(&sched.lock) 599 return n 600 } 601 602 func needaddgcproc() bool { 603 lock(&sched.lock) 604 n := gomaxprocs 605 if n > ncpu { 606 n = ncpu 607 } 608 if n > _MaxGcproc { 609 n = _MaxGcproc 610 } 611 n -= sched.nmidle + 1 // one M is currently running 612 unlock(&sched.lock) 613 return n > 0 614 } 615 616 func helpgc(nproc int32) { 617 _g_ := getg() 618 lock(&sched.lock) 619 pos := 0 620 for n := int32(1); n < nproc; n++ { // one M is currently running 621 if allp[pos].mcache == _g_.m.mcache { 622 pos++ 623 } 624 mp := mget() 625 if mp == nil { 626 throw("gcprocs inconsistency") 627 } 628 mp.helpgc = n 629 mp.p.set(allp[pos]) 630 mp.mcache = allp[pos].mcache 631 pos++ 632 notewakeup(&mp.park) 633 } 634 unlock(&sched.lock) 635 } 636 637 // freezeStopWait is a large value that freezetheworld sets 638 // sched.stopwait to in order to request that all Gs permanently stop. 639 const freezeStopWait = 0x7fffffff 640 641 // freezing is set to non-zero if the runtime is trying to freeze the 642 // world. 643 var freezing uint32 644 645 // Similar to stopTheWorld but best-effort and can be called several times. 646 // There is no reverse operation, used during crashing. 647 // This function must not lock any mutexes. 648 func freezetheworld() { 649 atomic.Store(&freezing, 1) 650 // stopwait and preemption requests can be lost 651 // due to races with concurrently executing threads, 652 // so try several times 653 for i := 0; i < 5; i++ { 654 // this should tell the scheduler to not start any new goroutines 655 sched.stopwait = freezeStopWait 656 atomic.Store(&sched.gcwaiting, 1) 657 // this should stop running goroutines 658 if !preemptall() { 659 break // no running goroutines 660 } 661 usleep(1000) 662 } 663 // to be sure 664 usleep(1000) 665 preemptall() 666 usleep(1000) 667 } 668 669 func isscanstatus(status uint32) bool { 670 if status == _Gscan { 671 throw("isscanstatus: Bad status Gscan") 672 } 673 return status&_Gscan == _Gscan 674 } 675 676 // All reads and writes of g's status go through readgstatus, casgstatus 677 // castogscanstatus, casfrom_Gscanstatus. 678 //go:nosplit 679 func readgstatus(gp *g) uint32 { 680 return atomic.Load(&gp.atomicstatus) 681 } 682 683 // Ownership of gcscanvalid: 684 // 685 // If gp is running (meaning status == _Grunning or _Grunning|_Gscan), 686 // then gp owns gp.gcscanvalid, and other goroutines must not modify it. 687 // 688 // Otherwise, a second goroutine can lock the scan state by setting _Gscan 689 // in the status bit and then modify gcscanvalid, and then unlock the scan state. 690 // 691 // Note that the first condition implies an exception to the second: 692 // if a second goroutine changes gp's status to _Grunning|_Gscan, 693 // that second goroutine still does not have the right to modify gcscanvalid. 694 695 // The Gscanstatuses are acting like locks and this releases them. 696 // If it proves to be a performance hit we should be able to make these 697 // simple atomic stores but for now we are going to throw if 698 // we see an inconsistent state. 699 func casfrom_Gscanstatus(gp *g, oldval, newval uint32) { 700 success := false 701 702 // Check that transition is valid. 703 switch oldval { 704 default: 705 print("runtime: casfrom_Gscanstatus bad oldval gp=", gp, ", oldval=", hex(oldval), ", newval=", hex(newval), "\n") 706 dumpgstatus(gp) 707 throw("casfrom_Gscanstatus:top gp->status is not in scan state") 708 case _Gscanrunnable, 709 _Gscanwaiting, 710 _Gscanrunning, 711 _Gscansyscall: 712 if newval == oldval&^_Gscan { 713 success = atomic.Cas(&gp.atomicstatus, oldval, newval) 714 } 715 } 716 if !success { 717 print("runtime: casfrom_Gscanstatus failed gp=", gp, ", oldval=", hex(oldval), ", newval=", hex(newval), "\n") 718 dumpgstatus(gp) 719 throw("casfrom_Gscanstatus: gp->status is not in scan state") 720 } 721 } 722 723 // This will return false if the gp is not in the expected status and the cas fails. 724 // This acts like a lock acquire while the casfromgstatus acts like a lock release. 725 func castogscanstatus(gp *g, oldval, newval uint32) bool { 726 switch oldval { 727 case _Grunnable, 728 _Grunning, 729 _Gwaiting, 730 _Gsyscall: 731 if newval == oldval|_Gscan { 732 return atomic.Cas(&gp.atomicstatus, oldval, newval) 733 } 734 } 735 print("runtime: castogscanstatus oldval=", hex(oldval), " newval=", hex(newval), "\n") 736 throw("castogscanstatus") 737 panic("not reached") 738 } 739 740 // If asked to move to or from a Gscanstatus this will throw. Use the castogscanstatus 741 // and casfrom_Gscanstatus instead. 742 // casgstatus will loop if the g->atomicstatus is in a Gscan status until the routine that 743 // put it in the Gscan state is finished. 744 //go:nosplit 745 func casgstatus(gp *g, oldval, newval uint32) { 746 if (oldval&_Gscan != 0) || (newval&_Gscan != 0) || oldval == newval { 747 systemstack(func() { 748 print("runtime: casgstatus: oldval=", hex(oldval), " newval=", hex(newval), "\n") 749 throw("casgstatus: bad incoming values") 750 }) 751 } 752 753 if oldval == _Grunning && gp.gcscanvalid { 754 // If oldvall == _Grunning, then the actual status must be 755 // _Grunning or _Grunning|_Gscan; either way, 756 // we own gp.gcscanvalid, so it's safe to read. 757 // gp.gcscanvalid must not be true when we are running. 758 print("runtime: casgstatus ", hex(oldval), "->", hex(newval), " gp.status=", hex(gp.atomicstatus), " gp.gcscanvalid=true\n") 759 throw("casgstatus") 760 } 761 762 // See http://golang.org/cl/21503 for justification of the yield delay. 763 const yieldDelay = 5 * 1000 764 var nextYield int64 765 766 // loop if gp->atomicstatus is in a scan state giving 767 // GC time to finish and change the state to oldval. 768 for i := 0; !atomic.Cas(&gp.atomicstatus, oldval, newval); i++ { 769 if oldval == _Gwaiting && gp.atomicstatus == _Grunnable { 770 systemstack(func() { 771 throw("casgstatus: waiting for Gwaiting but is Grunnable") 772 }) 773 } 774 // Help GC if needed. 775 // if gp.preemptscan && !gp.gcworkdone && (oldval == _Grunning || oldval == _Gsyscall) { 776 // gp.preemptscan = false 777 // systemstack(func() { 778 // gcphasework(gp) 779 // }) 780 // } 781 // But meanwhile just yield. 782 if i == 0 { 783 nextYield = nanotime() + yieldDelay 784 } 785 if nanotime() < nextYield { 786 for x := 0; x < 10 && gp.atomicstatus != oldval; x++ { 787 procyield(1) 788 } 789 } else { 790 osyield() 791 nextYield = nanotime() + yieldDelay/2 792 } 793 } 794 if newval == _Grunning { 795 gp.gcscanvalid = false 796 } 797 } 798 799 // casgstatus(gp, oldstatus, Gcopystack), assuming oldstatus is Gwaiting or Grunnable. 800 // Returns old status. Cannot call casgstatus directly, because we are racing with an 801 // async wakeup that might come in from netpoll. If we see Gwaiting from the readgstatus, 802 // it might have become Grunnable by the time we get to the cas. If we called casgstatus, 803 // it would loop waiting for the status to go back to Gwaiting, which it never will. 804 //go:nosplit 805 func casgcopystack(gp *g) uint32 { 806 for { 807 oldstatus := readgstatus(gp) &^ _Gscan 808 if oldstatus != _Gwaiting && oldstatus != _Grunnable { 809 throw("copystack: bad status, not Gwaiting or Grunnable") 810 } 811 if atomic.Cas(&gp.atomicstatus, oldstatus, _Gcopystack) { 812 return oldstatus 813 } 814 } 815 } 816 817 // scang blocks until gp's stack has been scanned. 818 // It might be scanned by scang or it might be scanned by the goroutine itself. 819 // Either way, the stack scan has completed when scang returns. 820 func scang(gp *g, gcw *gcWork) { 821 // Invariant; we (the caller, markroot for a specific goroutine) own gp.gcscandone. 822 // Nothing is racing with us now, but gcscandone might be set to true left over 823 // from an earlier round of stack scanning (we scan twice per GC). 824 // We use gcscandone to record whether the scan has been done during this round. 825 826 gp.gcscandone = false 827 828 // See http://golang.org/cl/21503 for justification of the yield delay. 829 const yieldDelay = 10 * 1000 830 var nextYield int64 831 832 // Endeavor to get gcscandone set to true, 833 // either by doing the stack scan ourselves or by coercing gp to scan itself. 834 // gp.gcscandone can transition from false to true when we're not looking 835 // (if we asked for preemption), so any time we lock the status using 836 // castogscanstatus we have to double-check that the scan is still not done. 837 loop: 838 for i := 0; !gp.gcscandone; i++ { 839 switch s := readgstatus(gp); s { 840 default: 841 dumpgstatus(gp) 842 throw("stopg: invalid status") 843 844 case _Gdead: 845 // No stack. 846 gp.gcscandone = true 847 break loop 848 849 case _Gcopystack: 850 // Stack being switched. Go around again. 851 852 case _Grunnable, _Gsyscall, _Gwaiting: 853 // Claim goroutine by setting scan bit. 854 // Racing with execution or readying of gp. 855 // The scan bit keeps them from running 856 // the goroutine until we're done. 857 if castogscanstatus(gp, s, s|_Gscan) { 858 if !gp.gcscandone { 859 scanstack(gp, gcw) 860 gp.gcscandone = true 861 } 862 restartg(gp) 863 break loop 864 } 865 866 case _Gscanwaiting: 867 // newstack is doing a scan for us right now. Wait. 868 869 case _Grunning: 870 // Goroutine running. Try to preempt execution so it can scan itself. 871 // The preemption handler (in newstack) does the actual scan. 872 873 // Optimization: if there is already a pending preemption request 874 // (from the previous loop iteration), don't bother with the atomics. 875 if gp.preemptscan && gp.preempt && gp.stackguard0 == stackPreempt { 876 break 877 } 878 879 // Ask for preemption and self scan. 880 if castogscanstatus(gp, _Grunning, _Gscanrunning) { 881 if !gp.gcscandone { 882 gp.preemptscan = true 883 gp.preempt = true 884 gp.stackguard0 = stackPreempt 885 } 886 casfrom_Gscanstatus(gp, _Gscanrunning, _Grunning) 887 } 888 } 889 890 if i == 0 { 891 nextYield = nanotime() + yieldDelay 892 } 893 if nanotime() < nextYield { 894 procyield(10) 895 } else { 896 osyield() 897 nextYield = nanotime() + yieldDelay/2 898 } 899 } 900 901 gp.preemptscan = false // cancel scan request if no longer needed 902 } 903 904 // The GC requests that this routine be moved from a scanmumble state to a mumble state. 905 func restartg(gp *g) { 906 s := readgstatus(gp) 907 switch s { 908 default: 909 dumpgstatus(gp) 910 throw("restartg: unexpected status") 911 912 case _Gdead: 913 // ok 914 915 case _Gscanrunnable, 916 _Gscanwaiting, 917 _Gscansyscall: 918 casfrom_Gscanstatus(gp, s, s&^_Gscan) 919 } 920 } 921 922 // stopTheWorld stops all P's from executing goroutines, interrupting 923 // all goroutines at GC safe points and records reason as the reason 924 // for the stop. On return, only the current goroutine's P is running. 925 // stopTheWorld must not be called from a system stack and the caller 926 // must not hold worldsema. The caller must call startTheWorld when 927 // other P's should resume execution. 928 // 929 // stopTheWorld is safe for multiple goroutines to call at the 930 // same time. Each will execute its own stop, and the stops will 931 // be serialized. 932 // 933 // This is also used by routines that do stack dumps. If the system is 934 // in panic or being exited, this may not reliably stop all 935 // goroutines. 936 func stopTheWorld(reason string) { 937 semacquire(&worldsema) 938 getg().m.preemptoff = reason 939 systemstack(stopTheWorldWithSema) 940 } 941 942 // startTheWorld undoes the effects of stopTheWorld. 943 func startTheWorld() { 944 systemstack(startTheWorldWithSema) 945 // worldsema must be held over startTheWorldWithSema to ensure 946 // gomaxprocs cannot change while worldsema is held. 947 semrelease(&worldsema) 948 getg().m.preemptoff = "" 949 } 950 951 // Holding worldsema grants an M the right to try to stop the world 952 // and prevents gomaxprocs from changing concurrently. 953 var worldsema uint32 = 1 954 955 // stopTheWorldWithSema is the core implementation of stopTheWorld. 956 // The caller is responsible for acquiring worldsema and disabling 957 // preemption first and then should stopTheWorldWithSema on the system 958 // stack: 959 // 960 // semacquire(&worldsema, 0) 961 // m.preemptoff = "reason" 962 // systemstack(stopTheWorldWithSema) 963 // 964 // When finished, the caller must either call startTheWorld or undo 965 // these three operations separately: 966 // 967 // m.preemptoff = "" 968 // systemstack(startTheWorldWithSema) 969 // semrelease(&worldsema) 970 // 971 // It is allowed to acquire worldsema once and then execute multiple 972 // startTheWorldWithSema/stopTheWorldWithSema pairs. 973 // Other P's are able to execute between successive calls to 974 // startTheWorldWithSema and stopTheWorldWithSema. 975 // Holding worldsema causes any other goroutines invoking 976 // stopTheWorld to block. 977 func stopTheWorldWithSema() { 978 _g_ := getg() 979 980 // If we hold a lock, then we won't be able to stop another M 981 // that is blocked trying to acquire the lock. 982 if _g_.m.locks > 0 { 983 throw("stopTheWorld: holding locks") 984 } 985 986 lock(&sched.lock) 987 sched.stopwait = gomaxprocs 988 atomic.Store(&sched.gcwaiting, 1) 989 preemptall() 990 // stop current P 991 _g_.m.p.ptr().status = _Pgcstop // Pgcstop is only diagnostic. 992 sched.stopwait-- 993 // try to retake all P's in Psyscall status 994 for i := 0; i < int(gomaxprocs); i++ { 995 p := allp[i] 996 s := p.status 997 if s == _Psyscall && atomic.Cas(&p.status, s, _Pgcstop) { 998 if trace.enabled { 999 traceGoSysBlock(p) 1000 traceProcStop(p) 1001 } 1002 p.syscalltick++ 1003 sched.stopwait-- 1004 } 1005 } 1006 // stop idle P's 1007 for { 1008 p := pidleget() 1009 if p == nil { 1010 break 1011 } 1012 p.status = _Pgcstop 1013 sched.stopwait-- 1014 } 1015 wait := sched.stopwait > 0 1016 unlock(&sched.lock) 1017 1018 // wait for remaining P's to stop voluntarily 1019 if wait { 1020 for { 1021 // wait for 100us, then try to re-preempt in case of any races 1022 if notetsleep(&sched.stopnote, 100*1000) { 1023 noteclear(&sched.stopnote) 1024 break 1025 } 1026 preemptall() 1027 } 1028 } 1029 1030 // sanity checks 1031 bad := "" 1032 if sched.stopwait != 0 { 1033 bad = "stopTheWorld: not stopped (stopwait != 0)" 1034 } else { 1035 for i := 0; i < int(gomaxprocs); i++ { 1036 p := allp[i] 1037 if p.status != _Pgcstop { 1038 bad = "stopTheWorld: not stopped (status != _Pgcstop)" 1039 } 1040 } 1041 } 1042 if atomic.Load(&freezing) != 0 { 1043 // Some other thread is panicking. This can cause the 1044 // sanity checks above to fail if the panic happens in 1045 // the signal handler on a stopped thread. Either way, 1046 // we should halt this thread. 1047 lock(&deadlock) 1048 lock(&deadlock) 1049 } 1050 if bad != "" { 1051 throw(bad) 1052 } 1053 } 1054 1055 func mhelpgc() { 1056 _g_ := getg() 1057 _g_.m.helpgc = -1 1058 } 1059 1060 func startTheWorldWithSema() { 1061 _g_ := getg() 1062 1063 _g_.m.locks++ // disable preemption because it can be holding p in a local var 1064 gp := netpoll(false) // non-blocking 1065 injectglist(gp) 1066 add := needaddgcproc() 1067 lock(&sched.lock) 1068 1069 procs := gomaxprocs 1070 if newprocs != 0 { 1071 procs = newprocs 1072 newprocs = 0 1073 } 1074 p1 := procresize(procs) 1075 sched.gcwaiting = 0 1076 if sched.sysmonwait != 0 { 1077 sched.sysmonwait = 0 1078 notewakeup(&sched.sysmonnote) 1079 } 1080 unlock(&sched.lock) 1081 1082 for p1 != nil { 1083 p := p1 1084 p1 = p1.link.ptr() 1085 if p.m != 0 { 1086 mp := p.m.ptr() 1087 p.m = 0 1088 if mp.nextp != 0 { 1089 throw("startTheWorld: inconsistent mp->nextp") 1090 } 1091 mp.nextp.set(p) 1092 notewakeup(&mp.park) 1093 } else { 1094 // Start M to run P. Do not start another M below. 1095 newm(nil, p) 1096 add = false 1097 } 1098 } 1099 1100 // Wakeup an additional proc in case we have excessive runnable goroutines 1101 // in local queues or in the global queue. If we don't, the proc will park itself. 1102 // If we have lots of excessive work, resetspinning will unpark additional procs as necessary. 1103 if atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 { 1104 wakep() 1105 } 1106 1107 if add { 1108 // If GC could have used another helper proc, start one now, 1109 // in the hope that it will be available next time. 1110 // It would have been even better to start it before the collection, 1111 // but doing so requires allocating memory, so it's tricky to 1112 // coordinate. This lazy approach works out in practice: 1113 // we don't mind if the first couple gc rounds don't have quite 1114 // the maximum number of procs. 1115 newm(mhelpgc, nil) 1116 } 1117 _g_.m.locks-- 1118 if _g_.m.locks == 0 && _g_.preempt { // restore the preemption request in case we've cleared it in newstack 1119 _g_.stackguard0 = stackPreempt 1120 } 1121 } 1122 1123 // Called to start an M. 1124 //go:nosplit 1125 func mstart() { 1126 _g_ := getg() 1127 1128 if _g_.stack.lo == 0 { 1129 // Initialize stack bounds from system stack. 1130 // Cgo may have left stack size in stack.hi. 1131 size := _g_.stack.hi 1132 if size == 0 { 1133 size = 8192 * sys.StackGuardMultiplier 1134 } 1135 _g_.stack.hi = uintptr(noescape(unsafe.Pointer(&size))) 1136 _g_.stack.lo = _g_.stack.hi - size + 1024 1137 } 1138 // Initialize stack guards so that we can start calling 1139 // both Go and C functions with stack growth prologues. 1140 _g_.stackguard0 = _g_.stack.lo + _StackGuard 1141 _g_.stackguard1 = _g_.stackguard0 1142 mstart1() 1143 } 1144 1145 func mstart1() { 1146 _g_ := getg() 1147 1148 if _g_ != _g_.m.g0 { 1149 throw("bad runtime·mstart") 1150 } 1151 1152 // Record top of stack for use by mcall. 1153 // Once we call schedule we're never coming back, 1154 // so other calls can reuse this stack space. 1155 gosave(&_g_.m.g0.sched) 1156 _g_.m.g0.sched.pc = ^uintptr(0) // make sure it is never used 1157 asminit() 1158 minit() 1159 1160 // Install signal handlers; after minit so that minit can 1161 // prepare the thread to be able to handle the signals. 1162 if _g_.m == &m0 { 1163 // Create an extra M for callbacks on threads not created by Go. 1164 if iscgo && !cgoHasExtraM { 1165 cgoHasExtraM = true 1166 newextram() 1167 } 1168 initsig(false) 1169 } 1170 1171 if fn := _g_.m.mstartfn; fn != nil { 1172 fn() 1173 } 1174 1175 if _g_.m.helpgc != 0 { 1176 _g_.m.helpgc = 0 1177 stopm() 1178 } else if _g_.m != &m0 { 1179 acquirep(_g_.m.nextp.ptr()) 1180 _g_.m.nextp = 0 1181 } 1182 schedule() 1183 } 1184 1185 // forEachP calls fn(p) for every P p when p reaches a GC safe point. 1186 // If a P is currently executing code, this will bring the P to a GC 1187 // safe point and execute fn on that P. If the P is not executing code 1188 // (it is idle or in a syscall), this will call fn(p) directly while 1189 // preventing the P from exiting its state. This does not ensure that 1190 // fn will run on every CPU executing Go code, but it acts as a global 1191 // memory barrier. GC uses this as a "ragged barrier." 1192 // 1193 // The caller must hold worldsema. 1194 // 1195 //go:systemstack 1196 func forEachP(fn func(*p)) { 1197 mp := acquirem() 1198 _p_ := getg().m.p.ptr() 1199 1200 lock(&sched.lock) 1201 if sched.safePointWait != 0 { 1202 throw("forEachP: sched.safePointWait != 0") 1203 } 1204 sched.safePointWait = gomaxprocs - 1 1205 sched.safePointFn = fn 1206 1207 // Ask all Ps to run the safe point function. 1208 for _, p := range allp[:gomaxprocs] { 1209 if p != _p_ { 1210 atomic.Store(&p.runSafePointFn, 1) 1211 } 1212 } 1213 preemptall() 1214 1215 // Any P entering _Pidle or _Psyscall from now on will observe 1216 // p.runSafePointFn == 1 and will call runSafePointFn when 1217 // changing its status to _Pidle/_Psyscall. 1218 1219 // Run safe point function for all idle Ps. sched.pidle will 1220 // not change because we hold sched.lock. 1221 for p := sched.pidle.ptr(); p != nil; p = p.link.ptr() { 1222 if atomic.Cas(&p.runSafePointFn, 1, 0) { 1223 fn(p) 1224 sched.safePointWait-- 1225 } 1226 } 1227 1228 wait := sched.safePointWait > 0 1229 unlock(&sched.lock) 1230 1231 // Run fn for the current P. 1232 fn(_p_) 1233 1234 // Force Ps currently in _Psyscall into _Pidle and hand them 1235 // off to induce safe point function execution. 1236 for i := 0; i < int(gomaxprocs); i++ { 1237 p := allp[i] 1238 s := p.status 1239 if s == _Psyscall && p.runSafePointFn == 1 && atomic.Cas(&p.status, s, _Pidle) { 1240 if trace.enabled { 1241 traceGoSysBlock(p) 1242 traceProcStop(p) 1243 } 1244 p.syscalltick++ 1245 handoffp(p) 1246 } 1247 } 1248 1249 // Wait for remaining Ps to run fn. 1250 if wait { 1251 for { 1252 // Wait for 100us, then try to re-preempt in 1253 // case of any races. 1254 // 1255 // Requires system stack. 1256 if notetsleep(&sched.safePointNote, 100*1000) { 1257 noteclear(&sched.safePointNote) 1258 break 1259 } 1260 preemptall() 1261 } 1262 } 1263 if sched.safePointWait != 0 { 1264 throw("forEachP: not done") 1265 } 1266 for i := 0; i < int(gomaxprocs); i++ { 1267 p := allp[i] 1268 if p.runSafePointFn != 0 { 1269 throw("forEachP: P did not run fn") 1270 } 1271 } 1272 1273 lock(&sched.lock) 1274 sched.safePointFn = nil 1275 unlock(&sched.lock) 1276 releasem(mp) 1277 } 1278 1279 // runSafePointFn runs the safe point function, if any, for this P. 1280 // This should be called like 1281 // 1282 // if getg().m.p.runSafePointFn != 0 { 1283 // runSafePointFn() 1284 // } 1285 // 1286 // runSafePointFn must be checked on any transition in to _Pidle or 1287 // _Psyscall to avoid a race where forEachP sees that the P is running 1288 // just before the P goes into _Pidle/_Psyscall and neither forEachP 1289 // nor the P run the safe-point function. 1290 func runSafePointFn() { 1291 p := getg().m.p.ptr() 1292 // Resolve the race between forEachP running the safe-point 1293 // function on this P's behalf and this P running the 1294 // safe-point function directly. 1295 if !atomic.Cas(&p.runSafePointFn, 1, 0) { 1296 return 1297 } 1298 sched.safePointFn(p) 1299 lock(&sched.lock) 1300 sched.safePointWait-- 1301 if sched.safePointWait == 0 { 1302 notewakeup(&sched.safePointNote) 1303 } 1304 unlock(&sched.lock) 1305 } 1306 1307 // When running with cgo, we call _cgo_thread_start 1308 // to start threads for us so that we can play nicely with 1309 // foreign code. 1310 var cgoThreadStart unsafe.Pointer 1311 1312 type cgothreadstart struct { 1313 g guintptr 1314 tls *uint64 1315 fn unsafe.Pointer 1316 } 1317 1318 // Allocate a new m unassociated with any thread. 1319 // Can use p for allocation context if needed. 1320 // fn is recorded as the new m's m.mstartfn. 1321 // 1322 // This function is allowed to have write barriers even if the caller 1323 // isn't because it borrows _p_. 1324 // 1325 //go:yeswritebarrierrec 1326 func allocm(_p_ *p, fn func()) *m { 1327 _g_ := getg() 1328 _g_.m.locks++ // disable GC because it can be called from sysmon 1329 if _g_.m.p == 0 { 1330 acquirep(_p_) // temporarily borrow p for mallocs in this function 1331 } 1332 mp := new(m) 1333 mp.mstartfn = fn 1334 mcommoninit(mp) 1335 1336 // In case of cgo or Solaris, pthread_create will make us a stack. 1337 // Windows and Plan 9 will layout sched stack on OS stack. 1338 if iscgo || GOOS == "solaris" || GOOS == "windows" || GOOS == "plan9" { 1339 mp.g0 = malg(-1) 1340 } else { 1341 mp.g0 = malg(8192 * sys.StackGuardMultiplier) 1342 } 1343 mp.g0.m = mp 1344 1345 if _p_ == _g_.m.p.ptr() { 1346 releasep() 1347 } 1348 _g_.m.locks-- 1349 if _g_.m.locks == 0 && _g_.preempt { // restore the preemption request in case we've cleared it in newstack 1350 _g_.stackguard0 = stackPreempt 1351 } 1352 1353 return mp 1354 } 1355 1356 // needm is called when a cgo callback happens on a 1357 // thread without an m (a thread not created by Go). 1358 // In this case, needm is expected to find an m to use 1359 // and return with m, g initialized correctly. 1360 // Since m and g are not set now (likely nil, but see below) 1361 // needm is limited in what routines it can call. In particular 1362 // it can only call nosplit functions (textflag 7) and cannot 1363 // do any scheduling that requires an m. 1364 // 1365 // In order to avoid needing heavy lifting here, we adopt 1366 // the following strategy: there is a stack of available m's 1367 // that can be stolen. Using compare-and-swap 1368 // to pop from the stack has ABA races, so we simulate 1369 // a lock by doing an exchange (via casp) to steal the stack 1370 // head and replace the top pointer with MLOCKED (1). 1371 // This serves as a simple spin lock that we can use even 1372 // without an m. The thread that locks the stack in this way 1373 // unlocks the stack by storing a valid stack head pointer. 1374 // 1375 // In order to make sure that there is always an m structure 1376 // available to be stolen, we maintain the invariant that there 1377 // is always one more than needed. At the beginning of the 1378 // program (if cgo is in use) the list is seeded with a single m. 1379 // If needm finds that it has taken the last m off the list, its job 1380 // is - once it has installed its own m so that it can do things like 1381 // allocate memory - to create a spare m and put it on the list. 1382 // 1383 // Each of these extra m's also has a g0 and a curg that are 1384 // pressed into service as the scheduling stack and current 1385 // goroutine for the duration of the cgo callback. 1386 // 1387 // When the callback is done with the m, it calls dropm to 1388 // put the m back on the list. 1389 //go:nosplit 1390 func needm(x byte) { 1391 if iscgo && !cgoHasExtraM { 1392 // Can happen if C/C++ code calls Go from a global ctor. 1393 // Can not throw, because scheduler is not initialized yet. 1394 write(2, unsafe.Pointer(&earlycgocallback[0]), int32(len(earlycgocallback))) 1395 exit(1) 1396 } 1397 1398 // Lock extra list, take head, unlock popped list. 1399 // nilokay=false is safe here because of the invariant above, 1400 // that the extra list always contains or will soon contain 1401 // at least one m. 1402 mp := lockextra(false) 1403 1404 // Set needextram when we've just emptied the list, 1405 // so that the eventual call into cgocallbackg will 1406 // allocate a new m for the extra list. We delay the 1407 // allocation until then so that it can be done 1408 // after exitsyscall makes sure it is okay to be 1409 // running at all (that is, there's no garbage collection 1410 // running right now). 1411 mp.needextram = mp.schedlink == 0 1412 extraMCount-- 1413 unlockextra(mp.schedlink.ptr()) 1414 1415 // Save and block signals before installing g. 1416 // Once g is installed, any incoming signals will try to execute, 1417 // but we won't have the sigaltstack settings and other data 1418 // set up appropriately until the end of minit, which will 1419 // unblock the signals. This is the same dance as when 1420 // starting a new m to run Go code via newosproc. 1421 msigsave(mp) 1422 sigblock() 1423 1424 // Install g (= m->g0) and set the stack bounds 1425 // to match the current stack. We don't actually know 1426 // how big the stack is, like we don't know how big any 1427 // scheduling stack is, but we assume there's at least 32 kB, 1428 // which is more than enough for us. 1429 setg(mp.g0) 1430 _g_ := getg() 1431 _g_.stack.hi = uintptr(noescape(unsafe.Pointer(&x))) + 1024 1432 _g_.stack.lo = uintptr(noescape(unsafe.Pointer(&x))) - 32*1024 1433 _g_.stackguard0 = _g_.stack.lo + _StackGuard 1434 1435 // Initialize this thread to use the m. 1436 asminit() 1437 minit() 1438 1439 // mp.curg is now a real goroutine. 1440 casgstatus(mp.curg, _Gdead, _Gsyscall) 1441 atomic.Xadd(&sched.ngsys, -1) 1442 } 1443 1444 var earlycgocallback = []byte("fatal error: cgo callback before cgo call\n") 1445 1446 // newextram allocates m's and puts them on the extra list. 1447 // It is called with a working local m, so that it can do things 1448 // like call schedlock and allocate. 1449 func newextram() { 1450 c := atomic.Xchg(&extraMWaiters, 0) 1451 if c > 0 { 1452 for i := uint32(0); i < c; i++ { 1453 oneNewExtraM() 1454 } 1455 } else { 1456 // Make sure there is at least one extra M. 1457 mp := lockextra(true) 1458 unlockextra(mp) 1459 if mp == nil { 1460 oneNewExtraM() 1461 } 1462 } 1463 } 1464 1465 // oneNewExtraM allocates an m and puts it on the extra list. 1466 func oneNewExtraM() { 1467 // Create extra goroutine locked to extra m. 1468 // The goroutine is the context in which the cgo callback will run. 1469 // The sched.pc will never be returned to, but setting it to 1470 // goexit makes clear to the traceback routines where 1471 // the goroutine stack ends. 1472 mp := allocm(nil, nil) 1473 gp := malg(4096) 1474 gp.sched.pc = funcPC(goexit) + sys.PCQuantum 1475 gp.sched.sp = gp.stack.hi 1476 gp.sched.sp -= 4 * sys.RegSize // extra space in case of reads slightly beyond frame 1477 gp.sched.lr = 0 1478 gp.sched.g = guintptr(unsafe.Pointer(gp)) 1479 gp.syscallpc = gp.sched.pc 1480 gp.syscallsp = gp.sched.sp 1481 gp.stktopsp = gp.sched.sp 1482 gp.gcscanvalid = true 1483 gp.gcscandone = true 1484 // malg returns status as _Gidle. Change to _Gdead before 1485 // adding to allg where GC can see it. We use _Gdead to hide 1486 // this from tracebacks and stack scans since it isn't a 1487 // "real" goroutine until needm grabs it. 1488 casgstatus(gp, _Gidle, _Gdead) 1489 gp.m = mp 1490 mp.curg = gp 1491 mp.locked = _LockInternal 1492 mp.lockedg = gp 1493 gp.lockedm = mp 1494 gp.goid = int64(atomic.Xadd64(&sched.goidgen, 1)) 1495 if raceenabled { 1496 gp.racectx = racegostart(funcPC(newextram) + sys.PCQuantum) 1497 } 1498 // put on allg for garbage collector 1499 allgadd(gp) 1500 1501 // gp is now on the allg list, but we don't want it to be 1502 // counted by gcount. It would be more "proper" to increment 1503 // sched.ngfree, but that requires locking. Incrementing ngsys 1504 // has the same effect. 1505 atomic.Xadd(&sched.ngsys, +1) 1506 1507 // Add m to the extra list. 1508 mnext := lockextra(true) 1509 mp.schedlink.set(mnext) 1510 extraMCount++ 1511 unlockextra(mp) 1512 } 1513 1514 // dropm is called when a cgo callback has called needm but is now 1515 // done with the callback and returning back into the non-Go thread. 1516 // It puts the current m back onto the extra list. 1517 // 1518 // The main expense here is the call to signalstack to release the 1519 // m's signal stack, and then the call to needm on the next callback 1520 // from this thread. It is tempting to try to save the m for next time, 1521 // which would eliminate both these costs, but there might not be 1522 // a next time: the current thread (which Go does not control) might exit. 1523 // If we saved the m for that thread, there would be an m leak each time 1524 // such a thread exited. Instead, we acquire and release an m on each 1525 // call. These should typically not be scheduling operations, just a few 1526 // atomics, so the cost should be small. 1527 // 1528 // TODO(rsc): An alternative would be to allocate a dummy pthread per-thread 1529 // variable using pthread_key_create. Unlike the pthread keys we already use 1530 // on OS X, this dummy key would never be read by Go code. It would exist 1531 // only so that we could register at thread-exit-time destructor. 1532 // That destructor would put the m back onto the extra list. 1533 // This is purely a performance optimization. The current version, 1534 // in which dropm happens on each cgo call, is still correct too. 1535 // We may have to keep the current version on systems with cgo 1536 // but without pthreads, like Windows. 1537 func dropm() { 1538 // Clear m and g, and return m to the extra list. 1539 // After the call to setg we can only call nosplit functions 1540 // with no pointer manipulation. 1541 mp := getg().m 1542 1543 // Return mp.curg to dead state. 1544 casgstatus(mp.curg, _Gsyscall, _Gdead) 1545 atomic.Xadd(&sched.ngsys, +1) 1546 1547 // Block signals before unminit. 1548 // Unminit unregisters the signal handling stack (but needs g on some systems). 1549 // Setg(nil) clears g, which is the signal handler's cue not to run Go handlers. 1550 // It's important not to try to handle a signal between those two steps. 1551 sigmask := mp.sigmask 1552 sigblock() 1553 unminit() 1554 1555 mnext := lockextra(true) 1556 extraMCount++ 1557 mp.schedlink.set(mnext) 1558 1559 setg(nil) 1560 1561 // Commit the release of mp. 1562 unlockextra(mp) 1563 1564 msigrestore(sigmask) 1565 } 1566 1567 // A helper function for EnsureDropM. 1568 func getm() uintptr { 1569 return uintptr(unsafe.Pointer(getg().m)) 1570 } 1571 1572 var extram uintptr 1573 var extraMCount uint32 // Protected by lockextra 1574 var extraMWaiters uint32 1575 1576 // lockextra locks the extra list and returns the list head. 1577 // The caller must unlock the list by storing a new list head 1578 // to extram. If nilokay is true, then lockextra will 1579 // return a nil list head if that's what it finds. If nilokay is false, 1580 // lockextra will keep waiting until the list head is no longer nil. 1581 //go:nosplit 1582 func lockextra(nilokay bool) *m { 1583 const locked = 1 1584 1585 incr := false 1586 for { 1587 old := atomic.Loaduintptr(&extram) 1588 if old == locked { 1589 yield := osyield 1590 yield() 1591 continue 1592 } 1593 if old == 0 && !nilokay { 1594 if !incr { 1595 // Add 1 to the number of threads 1596 // waiting for an M. 1597 // This is cleared by newextram. 1598 atomic.Xadd(&extraMWaiters, 1) 1599 incr = true 1600 } 1601 usleep(1) 1602 continue 1603 } 1604 if atomic.Casuintptr(&extram, old, locked) { 1605 return (*m)(unsafe.Pointer(old)) 1606 } 1607 yield := osyield 1608 yield() 1609 continue 1610 } 1611 } 1612 1613 //go:nosplit 1614 func unlockextra(mp *m) { 1615 atomic.Storeuintptr(&extram, uintptr(unsafe.Pointer(mp))) 1616 } 1617 1618 // Create a new m. It will start off with a call to fn, or else the scheduler. 1619 // fn needs to be static and not a heap allocated closure. 1620 // May run with m.p==nil, so write barriers are not allowed. 1621 //go:nowritebarrierrec 1622 func newm(fn func(), _p_ *p) { 1623 mp := allocm(_p_, fn) 1624 mp.nextp.set(_p_) 1625 mp.sigmask = initSigmask 1626 if iscgo { 1627 var ts cgothreadstart 1628 if _cgo_thread_start == nil { 1629 throw("_cgo_thread_start missing") 1630 } 1631 ts.g.set(mp.g0) 1632 ts.tls = (*uint64)(unsafe.Pointer(&mp.tls[0])) 1633 ts.fn = unsafe.Pointer(funcPC(mstart)) 1634 if msanenabled { 1635 msanwrite(unsafe.Pointer(&ts), unsafe.Sizeof(ts)) 1636 } 1637 asmcgocall(_cgo_thread_start, unsafe.Pointer(&ts)) 1638 return 1639 } 1640 newosproc(mp, unsafe.Pointer(mp.g0.stack.hi)) 1641 } 1642 1643 // Stops execution of the current m until new work is available. 1644 // Returns with acquired P. 1645 func stopm() { 1646 _g_ := getg() 1647 1648 if _g_.m.locks != 0 { 1649 throw("stopm holding locks") 1650 } 1651 if _g_.m.p != 0 { 1652 throw("stopm holding p") 1653 } 1654 if _g_.m.spinning { 1655 throw("stopm spinning") 1656 } 1657 1658 retry: 1659 lock(&sched.lock) 1660 mput(_g_.m) 1661 unlock(&sched.lock) 1662 notesleep(&_g_.m.park) 1663 noteclear(&_g_.m.park) 1664 if _g_.m.helpgc != 0 { 1665 gchelper() 1666 _g_.m.helpgc = 0 1667 _g_.m.mcache = nil 1668 _g_.m.p = 0 1669 goto retry 1670 } 1671 acquirep(_g_.m.nextp.ptr()) 1672 _g_.m.nextp = 0 1673 } 1674 1675 func mspinning() { 1676 // startm's caller incremented nmspinning. Set the new M's spinning. 1677 getg().m.spinning = true 1678 } 1679 1680 // Schedules some M to run the p (creates an M if necessary). 1681 // If p==nil, tries to get an idle P, if no idle P's does nothing. 1682 // May run with m.p==nil, so write barriers are not allowed. 1683 // If spinning is set, the caller has incremented nmspinning and startm will 1684 // either decrement nmspinning or set m.spinning in the newly started M. 1685 //go:nowritebarrierrec 1686 func startm(_p_ *p, spinning bool) { 1687 lock(&sched.lock) 1688 if _p_ == nil { 1689 _p_ = pidleget() 1690 if _p_ == nil { 1691 unlock(&sched.lock) 1692 if spinning { 1693 // The caller incremented nmspinning, but there are no idle Ps, 1694 // so it's okay to just undo the increment and give up. 1695 if int32(atomic.Xadd(&sched.nmspinning, -1)) < 0 { 1696 throw("startm: negative nmspinning") 1697 } 1698 } 1699 return 1700 } 1701 } 1702 mp := mget() 1703 unlock(&sched.lock) 1704 if mp == nil { 1705 var fn func() 1706 if spinning { 1707 // The caller incremented nmspinning, so set m.spinning in the new M. 1708 fn = mspinning 1709 } 1710 newm(fn, _p_) 1711 return 1712 } 1713 if mp.spinning { 1714 throw("startm: m is spinning") 1715 } 1716 if mp.nextp != 0 { 1717 throw("startm: m has p") 1718 } 1719 if spinning && !runqempty(_p_) { 1720 throw("startm: p has runnable gs") 1721 } 1722 // The caller incremented nmspinning, so set m.spinning in the new M. 1723 mp.spinning = spinning 1724 mp.nextp.set(_p_) 1725 notewakeup(&mp.park) 1726 } 1727 1728 // Hands off P from syscall or locked M. 1729 // Always runs without a P, so write barriers are not allowed. 1730 //go:nowritebarrierrec 1731 func handoffp(_p_ *p) { 1732 // handoffp must start an M in any situation where 1733 // findrunnable would return a G to run on _p_. 1734 1735 // if it has local work, start it straight away 1736 if !runqempty(_p_) || sched.runqsize != 0 { 1737 startm(_p_, false) 1738 return 1739 } 1740 // if it has GC work, start it straight away 1741 if gcBlackenEnabled != 0 && gcMarkWorkAvailable(_p_) { 1742 startm(_p_, false) 1743 return 1744 } 1745 // no local work, check that there are no spinning/idle M's, 1746 // otherwise our help is not required 1747 if atomic.Load(&sched.nmspinning)+atomic.Load(&sched.npidle) == 0 && atomic.Cas(&sched.nmspinning, 0, 1) { // TODO: fast atomic 1748 startm(_p_, true) 1749 return 1750 } 1751 lock(&sched.lock) 1752 if sched.gcwaiting != 0 { 1753 _p_.status = _Pgcstop 1754 sched.stopwait-- 1755 if sched.stopwait == 0 { 1756 notewakeup(&sched.stopnote) 1757 } 1758 unlock(&sched.lock) 1759 return 1760 } 1761 if _p_.runSafePointFn != 0 && atomic.Cas(&_p_.runSafePointFn, 1, 0) { 1762 sched.safePointFn(_p_) 1763 sched.safePointWait-- 1764 if sched.safePointWait == 0 { 1765 notewakeup(&sched.safePointNote) 1766 } 1767 } 1768 if sched.runqsize != 0 { 1769 unlock(&sched.lock) 1770 startm(_p_, false) 1771 return 1772 } 1773 // If this is the last running P and nobody is polling network, 1774 // need to wakeup another M to poll network. 1775 if sched.npidle == uint32(gomaxprocs-1) && atomic.Load64(&sched.lastpoll) != 0 { 1776 unlock(&sched.lock) 1777 startm(_p_, false) 1778 return 1779 } 1780 pidleput(_p_) 1781 unlock(&sched.lock) 1782 } 1783 1784 // Tries to add one more P to execute G's. 1785 // Called when a G is made runnable (newproc, ready). 1786 func wakep() { 1787 // be conservative about spinning threads 1788 if !atomic.Cas(&sched.nmspinning, 0, 1) { 1789 return 1790 } 1791 startm(nil, true) 1792 } 1793 1794 // Stops execution of the current m that is locked to a g until the g is runnable again. 1795 // Returns with acquired P. 1796 func stoplockedm() { 1797 _g_ := getg() 1798 1799 if _g_.m.lockedg == nil || _g_.m.lockedg.lockedm != _g_.m { 1800 throw("stoplockedm: inconsistent locking") 1801 } 1802 if _g_.m.p != 0 { 1803 // Schedule another M to run this p. 1804 _p_ := releasep() 1805 handoffp(_p_) 1806 } 1807 incidlelocked(1) 1808 // Wait until another thread schedules lockedg again. 1809 notesleep(&_g_.m.park) 1810 noteclear(&_g_.m.park) 1811 status := readgstatus(_g_.m.lockedg) 1812 if status&^_Gscan != _Grunnable { 1813 print("runtime:stoplockedm: g is not Grunnable or Gscanrunnable\n") 1814 dumpgstatus(_g_) 1815 throw("stoplockedm: not runnable") 1816 } 1817 acquirep(_g_.m.nextp.ptr()) 1818 _g_.m.nextp = 0 1819 } 1820 1821 // Schedules the locked m to run the locked gp. 1822 // May run during STW, so write barriers are not allowed. 1823 //go:nowritebarrierrec 1824 func startlockedm(gp *g) { 1825 _g_ := getg() 1826 1827 mp := gp.lockedm 1828 if mp == _g_.m { 1829 throw("startlockedm: locked to me") 1830 } 1831 if mp.nextp != 0 { 1832 throw("startlockedm: m has p") 1833 } 1834 // directly handoff current P to the locked m 1835 incidlelocked(-1) 1836 _p_ := releasep() 1837 mp.nextp.set(_p_) 1838 notewakeup(&mp.park) 1839 stopm() 1840 } 1841 1842 // Stops the current m for stopTheWorld. 1843 // Returns when the world is restarted. 1844 func gcstopm() { 1845 _g_ := getg() 1846 1847 if sched.gcwaiting == 0 { 1848 throw("gcstopm: not waiting for gc") 1849 } 1850 if _g_.m.spinning { 1851 _g_.m.spinning = false 1852 // OK to just drop nmspinning here, 1853 // startTheWorld will unpark threads as necessary. 1854 if int32(atomic.Xadd(&sched.nmspinning, -1)) < 0 { 1855 throw("gcstopm: negative nmspinning") 1856 } 1857 } 1858 _p_ := releasep() 1859 lock(&sched.lock) 1860 _p_.status = _Pgcstop 1861 sched.stopwait-- 1862 if sched.stopwait == 0 { 1863 notewakeup(&sched.stopnote) 1864 } 1865 unlock(&sched.lock) 1866 stopm() 1867 } 1868 1869 // Schedules gp to run on the current M. 1870 // If inheritTime is true, gp inherits the remaining time in the 1871 // current time slice. Otherwise, it starts a new time slice. 1872 // Never returns. 1873 // 1874 // Write barriers are allowed because this is called immediately after 1875 // acquiring a P in several places. 1876 // 1877 //go:yeswritebarrierrec 1878 func execute(gp *g, inheritTime bool) { 1879 _g_ := getg() 1880 1881 casgstatus(gp, _Grunnable, _Grunning) 1882 gp.waitsince = 0 1883 gp.preempt = false 1884 gp.stackguard0 = gp.stack.lo + _StackGuard 1885 if !inheritTime { 1886 _g_.m.p.ptr().schedtick++ 1887 } 1888 _g_.m.curg = gp 1889 gp.m = _g_.m 1890 1891 // Check whether the profiler needs to be turned on or off. 1892 hz := sched.profilehz 1893 if _g_.m.profilehz != hz { 1894 setThreadCPUProfiler(hz) 1895 } 1896 1897 if trace.enabled { 1898 // GoSysExit has to happen when we have a P, but before GoStart. 1899 // So we emit it here. 1900 if gp.syscallsp != 0 && gp.sysblocktraced { 1901 traceGoSysExit(gp.sysexitticks) 1902 } 1903 traceGoStart() 1904 } 1905 1906 gogo(&gp.sched) 1907 } 1908 1909 // Finds a runnable goroutine to execute. 1910 // Tries to steal from other P's, get g from global queue, poll network. 1911 func findrunnable() (gp *g, inheritTime bool) { 1912 _g_ := getg() 1913 1914 // The conditions here and in handoffp must agree: if 1915 // findrunnable would return a G to run, handoffp must start 1916 // an M. 1917 1918 top: 1919 _p_ := _g_.m.p.ptr() 1920 if sched.gcwaiting != 0 { 1921 gcstopm() 1922 goto top 1923 } 1924 if _p_.runSafePointFn != 0 { 1925 runSafePointFn() 1926 } 1927 if fingwait && fingwake { 1928 if gp := wakefing(); gp != nil { 1929 ready(gp, 0, true) 1930 } 1931 } 1932 if *cgo_yield != nil { 1933 asmcgocall(*cgo_yield, nil) 1934 } 1935 1936 // local runq 1937 if gp, inheritTime := runqget(_p_); gp != nil { 1938 return gp, inheritTime 1939 } 1940 1941 // global runq 1942 if sched.runqsize != 0 { 1943 lock(&sched.lock) 1944 gp := globrunqget(_p_, 0) 1945 unlock(&sched.lock) 1946 if gp != nil { 1947 return gp, false 1948 } 1949 } 1950 1951 // Poll network. 1952 // This netpoll is only an optimization before we resort to stealing. 1953 // We can safely skip it if there a thread blocked in netpoll already. 1954 // If there is any kind of logical race with that blocked thread 1955 // (e.g. it has already returned from netpoll, but does not set lastpoll yet), 1956 // this thread will do blocking netpoll below anyway. 1957 if netpollinited() && sched.lastpoll != 0 { 1958 if gp := netpoll(false); gp != nil { // non-blocking 1959 // netpoll returns list of goroutines linked by schedlink. 1960 injectglist(gp.schedlink.ptr()) 1961 casgstatus(gp, _Gwaiting, _Grunnable) 1962 if trace.enabled { 1963 traceGoUnpark(gp, 0) 1964 } 1965 return gp, false 1966 } 1967 } 1968 1969 // Steal work from other P's. 1970 procs := uint32(gomaxprocs) 1971 if atomic.Load(&sched.npidle) == procs-1 { 1972 // Either GOMAXPROCS=1 or everybody, except for us, is idle already. 1973 // New work can appear from returning syscall/cgocall, network or timers. 1974 // Neither of that submits to local run queues, so no point in stealing. 1975 goto stop 1976 } 1977 // If number of spinning M's >= number of busy P's, block. 1978 // This is necessary to prevent excessive CPU consumption 1979 // when GOMAXPROCS>>1 but the program parallelism is low. 1980 if !_g_.m.spinning && 2*atomic.Load(&sched.nmspinning) >= procs-atomic.Load(&sched.npidle) { 1981 goto stop 1982 } 1983 if !_g_.m.spinning { 1984 _g_.m.spinning = true 1985 atomic.Xadd(&sched.nmspinning, 1) 1986 } 1987 for i := 0; i < 4; i++ { 1988 for enum := stealOrder.start(fastrand()); !enum.done(); enum.next() { 1989 if sched.gcwaiting != 0 { 1990 goto top 1991 } 1992 stealRunNextG := i > 2 // first look for ready queues with more than 1 g 1993 if gp := runqsteal(_p_, allp[enum.position()], stealRunNextG); gp != nil { 1994 return gp, false 1995 } 1996 } 1997 } 1998 1999 stop: 2000 2001 // We have nothing to do. If we're in the GC mark phase, can 2002 // safely scan and blacken objects, and have work to do, run 2003 // idle-time marking rather than give up the P. 2004 if gcBlackenEnabled != 0 && _p_.gcBgMarkWorker != 0 && gcMarkWorkAvailable(_p_) { 2005 _p_.gcMarkWorkerMode = gcMarkWorkerIdleMode 2006 gp := _p_.gcBgMarkWorker.ptr() 2007 casgstatus(gp, _Gwaiting, _Grunnable) 2008 if trace.enabled { 2009 traceGoUnpark(gp, 0) 2010 } 2011 return gp, false 2012 } 2013 2014 // return P and block 2015 lock(&sched.lock) 2016 if sched.gcwaiting != 0 || _p_.runSafePointFn != 0 { 2017 unlock(&sched.lock) 2018 goto top 2019 } 2020 if sched.runqsize != 0 { 2021 gp := globrunqget(_p_, 0) 2022 unlock(&sched.lock) 2023 return gp, false 2024 } 2025 if releasep() != _p_ { 2026 throw("findrunnable: wrong p") 2027 } 2028 pidleput(_p_) 2029 unlock(&sched.lock) 2030 2031 // Delicate dance: thread transitions from spinning to non-spinning state, 2032 // potentially concurrently with submission of new goroutines. We must 2033 // drop nmspinning first and then check all per-P queues again (with 2034 // #StoreLoad memory barrier in between). If we do it the other way around, 2035 // another thread can submit a goroutine after we've checked all run queues 2036 // but before we drop nmspinning; as the result nobody will unpark a thread 2037 // to run the goroutine. 2038 // If we discover new work below, we need to restore m.spinning as a signal 2039 // for resetspinning to unpark a new worker thread (because there can be more 2040 // than one starving goroutine). However, if after discovering new work 2041 // we also observe no idle Ps, it is OK to just park the current thread: 2042 // the system is fully loaded so no spinning threads are required. 2043 // Also see "Worker thread parking/unparking" comment at the top of the file. 2044 wasSpinning := _g_.m.spinning 2045 if _g_.m.spinning { 2046 _g_.m.spinning = false 2047 if int32(atomic.Xadd(&sched.nmspinning, -1)) < 0 { 2048 throw("findrunnable: negative nmspinning") 2049 } 2050 } 2051 2052 // check all runqueues once again 2053 for i := 0; i < int(gomaxprocs); i++ { 2054 _p_ := allp[i] 2055 if _p_ != nil && !runqempty(_p_) { 2056 lock(&sched.lock) 2057 _p_ = pidleget() 2058 unlock(&sched.lock) 2059 if _p_ != nil { 2060 acquirep(_p_) 2061 if wasSpinning { 2062 _g_.m.spinning = true 2063 atomic.Xadd(&sched.nmspinning, 1) 2064 } 2065 goto top 2066 } 2067 break 2068 } 2069 } 2070 2071 // Check for idle-priority GC work again. 2072 if gcBlackenEnabled != 0 && gcMarkWorkAvailable(nil) { 2073 lock(&sched.lock) 2074 _p_ = pidleget() 2075 if _p_ != nil && _p_.gcBgMarkWorker == 0 { 2076 pidleput(_p_) 2077 _p_ = nil 2078 } 2079 unlock(&sched.lock) 2080 if _p_ != nil { 2081 acquirep(_p_) 2082 if wasSpinning { 2083 _g_.m.spinning = true 2084 atomic.Xadd(&sched.nmspinning, 1) 2085 } 2086 // Go back to idle GC check. 2087 goto stop 2088 } 2089 } 2090 2091 // poll network 2092 if netpollinited() && atomic.Load(&netpollWaiters) > 0 && atomic.Xchg64(&sched.lastpoll, 0) != 0 { 2093 if _g_.m.p != 0 { 2094 throw("findrunnable: netpoll with p") 2095 } 2096 if _g_.m.spinning { 2097 throw("findrunnable: netpoll with spinning") 2098 } 2099 gp := netpoll(true) // block until new work is available 2100 atomic.Store64(&sched.lastpoll, uint64(nanotime())) 2101 if gp != nil { 2102 lock(&sched.lock) 2103 _p_ = pidleget() 2104 unlock(&sched.lock) 2105 if _p_ != nil { 2106 acquirep(_p_) 2107 injectglist(gp.schedlink.ptr()) 2108 casgstatus(gp, _Gwaiting, _Grunnable) 2109 if trace.enabled { 2110 traceGoUnpark(gp, 0) 2111 } 2112 return gp, false 2113 } 2114 injectglist(gp) 2115 } 2116 } 2117 stopm() 2118 goto top 2119 } 2120 2121 // pollWork returns true if there is non-background work this P could 2122 // be doing. This is a fairly lightweight check to be used for 2123 // background work loops, like idle GC. It checks a subset of the 2124 // conditions checked by the actual scheduler. 2125 func pollWork() bool { 2126 if sched.runqsize != 0 { 2127 return true 2128 } 2129 p := getg().m.p.ptr() 2130 if !runqempty(p) { 2131 return true 2132 } 2133 if netpollinited() && atomic.Load(&netpollWaiters) > 0 && sched.lastpoll != 0 { 2134 if gp := netpoll(false); gp != nil { 2135 injectglist(gp) 2136 return true 2137 } 2138 } 2139 return false 2140 } 2141 2142 func resetspinning() { 2143 _g_ := getg() 2144 if !_g_.m.spinning { 2145 throw("resetspinning: not a spinning m") 2146 } 2147 _g_.m.spinning = false 2148 nmspinning := atomic.Xadd(&sched.nmspinning, -1) 2149 if int32(nmspinning) < 0 { 2150 throw("findrunnable: negative nmspinning") 2151 } 2152 // M wakeup policy is deliberately somewhat conservative, so check if we 2153 // need to wakeup another P here. See "Worker thread parking/unparking" 2154 // comment at the top of the file for details. 2155 if nmspinning == 0 && atomic.Load(&sched.npidle) > 0 { 2156 wakep() 2157 } 2158 } 2159 2160 // Injects the list of runnable G's into the scheduler. 2161 // Can run concurrently with GC. 2162 func injectglist(glist *g) { 2163 if glist == nil { 2164 return 2165 } 2166 if trace.enabled { 2167 for gp := glist; gp != nil; gp = gp.schedlink.ptr() { 2168 traceGoUnpark(gp, 0) 2169 } 2170 } 2171 lock(&sched.lock) 2172 var n int 2173 for n = 0; glist != nil; n++ { 2174 gp := glist 2175 glist = gp.schedlink.ptr() 2176 casgstatus(gp, _Gwaiting, _Grunnable) 2177 globrunqput(gp) 2178 } 2179 unlock(&sched.lock) 2180 for ; n != 0 && sched.npidle != 0; n-- { 2181 startm(nil, false) 2182 } 2183 } 2184 2185 // One round of scheduler: find a runnable goroutine and execute it. 2186 // Never returns. 2187 func schedule() { 2188 _g_ := getg() 2189 2190 if _g_.m.locks != 0 { 2191 throw("schedule: holding locks") 2192 } 2193 2194 if _g_.m.lockedg != nil { 2195 stoplockedm() 2196 execute(_g_.m.lockedg, false) // Never returns. 2197 } 2198 2199 top: 2200 if sched.gcwaiting != 0 { 2201 gcstopm() 2202 goto top 2203 } 2204 if _g_.m.p.ptr().runSafePointFn != 0 { 2205 runSafePointFn() 2206 } 2207 2208 var gp *g 2209 var inheritTime bool 2210 if trace.enabled || trace.shutdown { 2211 gp = traceReader() 2212 if gp != nil { 2213 casgstatus(gp, _Gwaiting, _Grunnable) 2214 traceGoUnpark(gp, 0) 2215 } 2216 } 2217 if gp == nil && gcBlackenEnabled != 0 { 2218 gp = gcController.findRunnableGCWorker(_g_.m.p.ptr()) 2219 } 2220 if gp == nil { 2221 // Check the global runnable queue once in a while to ensure fairness. 2222 // Otherwise two goroutines can completely occupy the local runqueue 2223 // by constantly respawning each other. 2224 if _g_.m.p.ptr().schedtick%61 == 0 && sched.runqsize > 0 { 2225 lock(&sched.lock) 2226 gp = globrunqget(_g_.m.p.ptr(), 1) 2227 unlock(&sched.lock) 2228 } 2229 } 2230 if gp == nil { 2231 gp, inheritTime = runqget(_g_.m.p.ptr()) 2232 if gp != nil && _g_.m.spinning { 2233 throw("schedule: spinning with local work") 2234 } 2235 } 2236 if gp == nil { 2237 gp, inheritTime = findrunnable() // blocks until work is available 2238 } 2239 2240 // This thread is going to run a goroutine and is not spinning anymore, 2241 // so if it was marked as spinning we need to reset it now and potentially 2242 // start a new spinning M. 2243 if _g_.m.spinning { 2244 resetspinning() 2245 } 2246 2247 if gp.lockedm != nil { 2248 // Hands off own p to the locked m, 2249 // then blocks waiting for a new p. 2250 startlockedm(gp) 2251 goto top 2252 } 2253 2254 execute(gp, inheritTime) 2255 } 2256 2257 // dropg removes the association between m and the current goroutine m->curg (gp for short). 2258 // Typically a caller sets gp's status away from Grunning and then 2259 // immediately calls dropg to finish the job. The caller is also responsible 2260 // for arranging that gp will be restarted using ready at an 2261 // appropriate time. After calling dropg and arranging for gp to be 2262 // readied later, the caller can do other work but eventually should 2263 // call schedule to restart the scheduling of goroutines on this m. 2264 func dropg() { 2265 _g_ := getg() 2266 2267 setMNoWB(&_g_.m.curg.m, nil) 2268 setGNoWB(&_g_.m.curg, nil) 2269 } 2270 2271 func parkunlock_c(gp *g, lock unsafe.Pointer) bool { 2272 unlock((*mutex)(lock)) 2273 return true 2274 } 2275 2276 // park continuation on g0. 2277 func park_m(gp *g) { 2278 _g_ := getg() 2279 2280 if trace.enabled { 2281 traceGoPark(_g_.m.waittraceev, _g_.m.waittraceskip) 2282 } 2283 2284 casgstatus(gp, _Grunning, _Gwaiting) 2285 dropg() 2286 2287 if _g_.m.waitunlockf != nil { 2288 fn := *(*func(*g, unsafe.Pointer) bool)(unsafe.Pointer(&_g_.m.waitunlockf)) 2289 ok := fn(gp, _g_.m.waitlock) 2290 _g_.m.waitunlockf = nil 2291 _g_.m.waitlock = nil 2292 if !ok { 2293 if trace.enabled { 2294 traceGoUnpark(gp, 2) 2295 } 2296 casgstatus(gp, _Gwaiting, _Grunnable) 2297 execute(gp, true) // Schedule it back, never returns. 2298 } 2299 } 2300 schedule() 2301 } 2302 2303 func goschedImpl(gp *g) { 2304 status := readgstatus(gp) 2305 if status&^_Gscan != _Grunning { 2306 dumpgstatus(gp) 2307 throw("bad g status") 2308 } 2309 casgstatus(gp, _Grunning, _Grunnable) 2310 dropg() 2311 lock(&sched.lock) 2312 globrunqput(gp) 2313 unlock(&sched.lock) 2314 2315 schedule() 2316 } 2317 2318 // Gosched continuation on g0. 2319 func gosched_m(gp *g) { 2320 if trace.enabled { 2321 traceGoSched() 2322 } 2323 goschedImpl(gp) 2324 } 2325 2326 // goschedguarded is a forbidden-states-avoided version of gosched_m 2327 func goschedguarded_m(gp *g) { 2328 2329 if gp.m.locks != 0 || gp.m.mallocing != 0 || gp.m.preemptoff != "" || gp.m.p.ptr().status != _Prunning { 2330 gogo(&gp.sched) // never return 2331 } 2332 2333 if trace.enabled { 2334 traceGoSched() 2335 } 2336 goschedImpl(gp) 2337 } 2338 2339 func gopreempt_m(gp *g) { 2340 if trace.enabled { 2341 traceGoPreempt() 2342 } 2343 goschedImpl(gp) 2344 } 2345 2346 // Finishes execution of the current goroutine. 2347 func goexit1() { 2348 if raceenabled { 2349 racegoend() 2350 } 2351 if trace.enabled { 2352 traceGoEnd() 2353 } 2354 mcall(goexit0) 2355 } 2356 2357 // goexit continuation on g0. 2358 func goexit0(gp *g) { 2359 _g_ := getg() 2360 2361 casgstatus(gp, _Grunning, _Gdead) 2362 if isSystemGoroutine(gp) { 2363 atomic.Xadd(&sched.ngsys, -1) 2364 } 2365 gp.m = nil 2366 gp.lockedm = nil 2367 _g_.m.lockedg = nil 2368 gp.paniconfault = false 2369 gp._defer = nil // should be true already but just in case. 2370 gp._panic = nil // non-nil for Goexit during panic. points at stack-allocated data. 2371 gp.writebuf = nil 2372 gp.waitreason = "" 2373 gp.param = nil 2374 gp.labels = nil 2375 gp.timer = nil 2376 2377 // Note that gp's stack scan is now "valid" because it has no 2378 // stack. 2379 gp.gcscanvalid = true 2380 dropg() 2381 2382 if _g_.m.locked&^_LockExternal != 0 { 2383 print("invalid m->locked = ", _g_.m.locked, "\n") 2384 throw("internal lockOSThread error") 2385 } 2386 _g_.m.locked = 0 2387 gfput(_g_.m.p.ptr(), gp) 2388 schedule() 2389 } 2390 2391 // save updates getg().sched to refer to pc and sp so that a following 2392 // gogo will restore pc and sp. 2393 // 2394 // save must not have write barriers because invoking a write barrier 2395 // can clobber getg().sched. 2396 // 2397 //go:nosplit 2398 //go:nowritebarrierrec 2399 func save(pc, sp uintptr) { 2400 _g_ := getg() 2401 2402 _g_.sched.pc = pc 2403 _g_.sched.sp = sp 2404 _g_.sched.lr = 0 2405 _g_.sched.ret = 0 2406 _g_.sched.g = guintptr(unsafe.Pointer(_g_)) 2407 // We need to ensure ctxt is zero, but can't have a write 2408 // barrier here. However, it should always already be zero. 2409 // Assert that. 2410 if _g_.sched.ctxt != nil { 2411 badctxt() 2412 } 2413 } 2414 2415 // The goroutine g is about to enter a system call. 2416 // Record that it's not using the cpu anymore. 2417 // This is called only from the go syscall library and cgocall, 2418 // not from the low-level system calls used by the runtime. 2419 // 2420 // Entersyscall cannot split the stack: the gosave must 2421 // make g->sched refer to the caller's stack segment, because 2422 // entersyscall is going to return immediately after. 2423 // 2424 // Nothing entersyscall calls can split the stack either. 2425 // We cannot safely move the stack during an active call to syscall, 2426 // because we do not know which of the uintptr arguments are 2427 // really pointers (back into the stack). 2428 // In practice, this means that we make the fast path run through 2429 // entersyscall doing no-split things, and the slow path has to use systemstack 2430 // to run bigger things on the system stack. 2431 // 2432 // reentersyscall is the entry point used by cgo callbacks, where explicitly 2433 // saved SP and PC are restored. This is needed when exitsyscall will be called 2434 // from a function further up in the call stack than the parent, as g->syscallsp 2435 // must always point to a valid stack frame. entersyscall below is the normal 2436 // entry point for syscalls, which obtains the SP and PC from the caller. 2437 // 2438 // Syscall tracing: 2439 // At the start of a syscall we emit traceGoSysCall to capture the stack trace. 2440 // If the syscall does not block, that is it, we do not emit any other events. 2441 // If the syscall blocks (that is, P is retaken), retaker emits traceGoSysBlock; 2442 // when syscall returns we emit traceGoSysExit and when the goroutine starts running 2443 // (potentially instantly, if exitsyscallfast returns true) we emit traceGoStart. 2444 // To ensure that traceGoSysExit is emitted strictly after traceGoSysBlock, 2445 // we remember current value of syscalltick in m (_g_.m.syscalltick = _g_.m.p.ptr().syscalltick), 2446 // whoever emits traceGoSysBlock increments p.syscalltick afterwards; 2447 // and we wait for the increment before emitting traceGoSysExit. 2448 // Note that the increment is done even if tracing is not enabled, 2449 // because tracing can be enabled in the middle of syscall. We don't want the wait to hang. 2450 // 2451 //go:nosplit 2452 func reentersyscall(pc, sp uintptr) { 2453 _g_ := getg() 2454 2455 // Disable preemption because during this function g is in Gsyscall status, 2456 // but can have inconsistent g->sched, do not let GC observe it. 2457 _g_.m.locks++ 2458 2459 // Entersyscall must not call any function that might split/grow the stack. 2460 // (See details in comment above.) 2461 // Catch calls that might, by replacing the stack guard with something that 2462 // will trip any stack check and leaving a flag to tell newstack to die. 2463 _g_.stackguard0 = stackPreempt 2464 _g_.throwsplit = true 2465 2466 // Leave SP around for GC and traceback. 2467 save(pc, sp) 2468 _g_.syscallsp = sp 2469 _g_.syscallpc = pc 2470 casgstatus(_g_, _Grunning, _Gsyscall) 2471 if _g_.syscallsp < _g_.stack.lo || _g_.stack.hi < _g_.syscallsp { 2472 systemstack(func() { 2473 print("entersyscall inconsistent ", hex(_g_.syscallsp), " [", hex(_g_.stack.lo), ",", hex(_g_.stack.hi), "]\n") 2474 throw("entersyscall") 2475 }) 2476 } 2477 2478 if trace.enabled { 2479 systemstack(traceGoSysCall) 2480 // systemstack itself clobbers g.sched.{pc,sp} and we might 2481 // need them later when the G is genuinely blocked in a 2482 // syscall 2483 save(pc, sp) 2484 } 2485 2486 if atomic.Load(&sched.sysmonwait) != 0 { 2487 systemstack(entersyscall_sysmon) 2488 save(pc, sp) 2489 } 2490 2491 if _g_.m.p.ptr().runSafePointFn != 0 { 2492 // runSafePointFn may stack split if run on this stack 2493 systemstack(runSafePointFn) 2494 save(pc, sp) 2495 } 2496 2497 _g_.m.syscalltick = _g_.m.p.ptr().syscalltick 2498 _g_.sysblocktraced = true 2499 _g_.m.mcache = nil 2500 _g_.m.p.ptr().m = 0 2501 atomic.Store(&_g_.m.p.ptr().status, _Psyscall) 2502 if sched.gcwaiting != 0 { 2503 systemstack(entersyscall_gcwait) 2504 save(pc, sp) 2505 } 2506 2507 // Goroutines must not split stacks in Gsyscall status (it would corrupt g->sched). 2508 // We set _StackGuard to StackPreempt so that first split stack check calls morestack. 2509 // Morestack detects this case and throws. 2510 _g_.stackguard0 = stackPreempt 2511 _g_.m.locks-- 2512 } 2513 2514 // Standard syscall entry used by the go syscall library and normal cgo calls. 2515 //go:nosplit 2516 func entersyscall(dummy int32) { 2517 reentersyscall(getcallerpc(unsafe.Pointer(&dummy)), getcallersp(unsafe.Pointer(&dummy))) 2518 } 2519 2520 func entersyscall_sysmon() { 2521 lock(&sched.lock) 2522 if atomic.Load(&sched.sysmonwait) != 0 { 2523 atomic.Store(&sched.sysmonwait, 0) 2524 notewakeup(&sched.sysmonnote) 2525 } 2526 unlock(&sched.lock) 2527 } 2528 2529 func entersyscall_gcwait() { 2530 _g_ := getg() 2531 _p_ := _g_.m.p.ptr() 2532 2533 lock(&sched.lock) 2534 if sched.stopwait > 0 && atomic.Cas(&_p_.status, _Psyscall, _Pgcstop) { 2535 if trace.enabled { 2536 traceGoSysBlock(_p_) 2537 traceProcStop(_p_) 2538 } 2539 _p_.syscalltick++ 2540 if sched.stopwait--; sched.stopwait == 0 { 2541 notewakeup(&sched.stopnote) 2542 } 2543 } 2544 unlock(&sched.lock) 2545 } 2546 2547 // The same as entersyscall(), but with a hint that the syscall is blocking. 2548 //go:nosplit 2549 func entersyscallblock(dummy int32) { 2550 _g_ := getg() 2551 2552 _g_.m.locks++ // see comment in entersyscall 2553 _g_.throwsplit = true 2554 _g_.stackguard0 = stackPreempt // see comment in entersyscall 2555 _g_.m.syscalltick = _g_.m.p.ptr().syscalltick 2556 _g_.sysblocktraced = true 2557 _g_.m.p.ptr().syscalltick++ 2558 2559 // Leave SP around for GC and traceback. 2560 pc := getcallerpc(unsafe.Pointer(&dummy)) 2561 sp := getcallersp(unsafe.Pointer(&dummy)) 2562 save(pc, sp) 2563 _g_.syscallsp = _g_.sched.sp 2564 _g_.syscallpc = _g_.sched.pc 2565 if _g_.syscallsp < _g_.stack.lo || _g_.stack.hi < _g_.syscallsp { 2566 sp1 := sp 2567 sp2 := _g_.sched.sp 2568 sp3 := _g_.syscallsp 2569 systemstack(func() { 2570 print("entersyscallblock inconsistent ", hex(sp1), " ", hex(sp2), " ", hex(sp3), " [", hex(_g_.stack.lo), ",", hex(_g_.stack.hi), "]\n") 2571 throw("entersyscallblock") 2572 }) 2573 } 2574 casgstatus(_g_, _Grunning, _Gsyscall) 2575 if _g_.syscallsp < _g_.stack.lo || _g_.stack.hi < _g_.syscallsp { 2576 systemstack(func() { 2577 print("entersyscallblock inconsistent ", hex(sp), " ", hex(_g_.sched.sp), " ", hex(_g_.syscallsp), " [", hex(_g_.stack.lo), ",", hex(_g_.stack.hi), "]\n") 2578 throw("entersyscallblock") 2579 }) 2580 } 2581 2582 systemstack(entersyscallblock_handoff) 2583 2584 // Resave for traceback during blocked call. 2585 save(getcallerpc(unsafe.Pointer(&dummy)), getcallersp(unsafe.Pointer(&dummy))) 2586 2587 _g_.m.locks-- 2588 } 2589 2590 func entersyscallblock_handoff() { 2591 if trace.enabled { 2592 traceGoSysCall() 2593 traceGoSysBlock(getg().m.p.ptr()) 2594 } 2595 handoffp(releasep()) 2596 } 2597 2598 // The goroutine g exited its system call. 2599 // Arrange for it to run on a cpu again. 2600 // This is called only from the go syscall library, not 2601 // from the low-level system calls used by the runtime. 2602 // 2603 // Write barriers are not allowed because our P may have been stolen. 2604 // 2605 //go:nosplit 2606 //go:nowritebarrierrec 2607 func exitsyscall(dummy int32) { 2608 _g_ := getg() 2609 2610 _g_.m.locks++ // see comment in entersyscall 2611 if getcallersp(unsafe.Pointer(&dummy)) > _g_.syscallsp { 2612 // throw calls print which may try to grow the stack, 2613 // but throwsplit == true so the stack can not be grown; 2614 // use systemstack to avoid that possible problem. 2615 systemstack(func() { 2616 throw("exitsyscall: syscall frame is no longer valid") 2617 }) 2618 } 2619 2620 _g_.waitsince = 0 2621 oldp := _g_.m.p.ptr() 2622 if exitsyscallfast() { 2623 if _g_.m.mcache == nil { 2624 throw("lost mcache") 2625 } 2626 if trace.enabled { 2627 if oldp != _g_.m.p.ptr() || _g_.m.syscalltick != _g_.m.p.ptr().syscalltick { 2628 systemstack(traceGoStart) 2629 } 2630 } 2631 // There's a cpu for us, so we can run. 2632 _g_.m.p.ptr().syscalltick++ 2633 // We need to cas the status and scan before resuming... 2634 casgstatus(_g_, _Gsyscall, _Grunning) 2635 2636 // Garbage collector isn't running (since we are), 2637 // so okay to clear syscallsp. 2638 _g_.syscallsp = 0 2639 _g_.m.locks-- 2640 if _g_.preempt { 2641 // restore the preemption request in case we've cleared it in newstack 2642 _g_.stackguard0 = stackPreempt 2643 } else { 2644 // otherwise restore the real _StackGuard, we've spoiled it in entersyscall/entersyscallblock 2645 _g_.stackguard0 = _g_.stack.lo + _StackGuard 2646 } 2647 _g_.throwsplit = false 2648 return 2649 } 2650 2651 _g_.sysexitticks = 0 2652 if trace.enabled { 2653 // Wait till traceGoSysBlock event is emitted. 2654 // This ensures consistency of the trace (the goroutine is started after it is blocked). 2655 for oldp != nil && oldp.syscalltick == _g_.m.syscalltick { 2656 osyield() 2657 } 2658 // We can't trace syscall exit right now because we don't have a P. 2659 // Tracing code can invoke write barriers that cannot run without a P. 2660 // So instead we remember the syscall exit time and emit the event 2661 // in execute when we have a P. 2662 _g_.sysexitticks = cputicks() 2663 } 2664 2665 _g_.m.locks-- 2666 2667 // Call the scheduler. 2668 mcall(exitsyscall0) 2669 2670 if _g_.m.mcache == nil { 2671 throw("lost mcache") 2672 } 2673 2674 // Scheduler returned, so we're allowed to run now. 2675 // Delete the syscallsp information that we left for 2676 // the garbage collector during the system call. 2677 // Must wait until now because until gosched returns 2678 // we don't know for sure that the garbage collector 2679 // is not running. 2680 _g_.syscallsp = 0 2681 _g_.m.p.ptr().syscalltick++ 2682 _g_.throwsplit = false 2683 } 2684 2685 //go:nosplit 2686 func exitsyscallfast() bool { 2687 _g_ := getg() 2688 2689 // Freezetheworld sets stopwait but does not retake P's. 2690 if sched.stopwait == freezeStopWait { 2691 _g_.m.mcache = nil 2692 _g_.m.p = 0 2693 return false 2694 } 2695 2696 // Try to re-acquire the last P. 2697 if _g_.m.p != 0 && _g_.m.p.ptr().status == _Psyscall && atomic.Cas(&_g_.m.p.ptr().status, _Psyscall, _Prunning) { 2698 // There's a cpu for us, so we can run. 2699 exitsyscallfast_reacquired() 2700 return true 2701 } 2702 2703 // Try to get any other idle P. 2704 oldp := _g_.m.p.ptr() 2705 _g_.m.mcache = nil 2706 _g_.m.p = 0 2707 if sched.pidle != 0 { 2708 var ok bool 2709 systemstack(func() { 2710 ok = exitsyscallfast_pidle() 2711 if ok && trace.enabled { 2712 if oldp != nil { 2713 // Wait till traceGoSysBlock event is emitted. 2714 // This ensures consistency of the trace (the goroutine is started after it is blocked). 2715 for oldp.syscalltick == _g_.m.syscalltick { 2716 osyield() 2717 } 2718 } 2719 traceGoSysExit(0) 2720 } 2721 }) 2722 if ok { 2723 return true 2724 } 2725 } 2726 return false 2727 } 2728 2729 // exitsyscallfast_reacquired is the exitsyscall path on which this G 2730 // has successfully reacquired the P it was running on before the 2731 // syscall. 2732 // 2733 // This function is allowed to have write barriers because exitsyscall 2734 // has acquired a P at this point. 2735 // 2736 //go:yeswritebarrierrec 2737 //go:nosplit 2738 func exitsyscallfast_reacquired() { 2739 _g_ := getg() 2740 _g_.m.mcache = _g_.m.p.ptr().mcache 2741 _g_.m.p.ptr().m.set(_g_.m) 2742 if _g_.m.syscalltick != _g_.m.p.ptr().syscalltick { 2743 if trace.enabled { 2744 // The p was retaken and then enter into syscall again (since _g_.m.syscalltick has changed). 2745 // traceGoSysBlock for this syscall was already emitted, 2746 // but here we effectively retake the p from the new syscall running on the same p. 2747 systemstack(func() { 2748 // Denote blocking of the new syscall. 2749 traceGoSysBlock(_g_.m.p.ptr()) 2750 // Denote completion of the current syscall. 2751 traceGoSysExit(0) 2752 }) 2753 } 2754 _g_.m.p.ptr().syscalltick++ 2755 } 2756 } 2757 2758 func exitsyscallfast_pidle() bool { 2759 lock(&sched.lock) 2760 _p_ := pidleget() 2761 if _p_ != nil && atomic.Load(&sched.sysmonwait) != 0 { 2762 atomic.Store(&sched.sysmonwait, 0) 2763 notewakeup(&sched.sysmonnote) 2764 } 2765 unlock(&sched.lock) 2766 if _p_ != nil { 2767 acquirep(_p_) 2768 return true 2769 } 2770 return false 2771 } 2772 2773 // exitsyscall slow path on g0. 2774 // Failed to acquire P, enqueue gp as runnable. 2775 // 2776 //go:nowritebarrierrec 2777 func exitsyscall0(gp *g) { 2778 _g_ := getg() 2779 2780 casgstatus(gp, _Gsyscall, _Grunnable) 2781 dropg() 2782 lock(&sched.lock) 2783 _p_ := pidleget() 2784 if _p_ == nil { 2785 globrunqput(gp) 2786 } else if atomic.Load(&sched.sysmonwait) != 0 { 2787 atomic.Store(&sched.sysmonwait, 0) 2788 notewakeup(&sched.sysmonnote) 2789 } 2790 unlock(&sched.lock) 2791 if _p_ != nil { 2792 acquirep(_p_) 2793 execute(gp, false) // Never returns. 2794 } 2795 if _g_.m.lockedg != nil { 2796 // Wait until another thread schedules gp and so m again. 2797 stoplockedm() 2798 execute(gp, false) // Never returns. 2799 } 2800 stopm() 2801 schedule() // Never returns. 2802 } 2803 2804 func beforefork() { 2805 gp := getg().m.curg 2806 2807 // Block signals during a fork, so that the child does not run 2808 // a signal handler before exec if a signal is sent to the process 2809 // group. See issue #18600. 2810 gp.m.locks++ 2811 msigsave(gp.m) 2812 sigblock() 2813 2814 // This function is called before fork in syscall package. 2815 // Code between fork and exec must not allocate memory nor even try to grow stack. 2816 // Here we spoil g->_StackGuard to reliably detect any attempts to grow stack. 2817 // runtime_AfterFork will undo this in parent process, but not in child. 2818 gp.stackguard0 = stackFork 2819 } 2820 2821 // Called from syscall package before fork. 2822 //go:linkname syscall_runtime_BeforeFork syscall.runtime_BeforeFork 2823 //go:nosplit 2824 func syscall_runtime_BeforeFork() { 2825 systemstack(beforefork) 2826 } 2827 2828 func afterfork() { 2829 gp := getg().m.curg 2830 2831 // See the comments in beforefork. 2832 gp.stackguard0 = gp.stack.lo + _StackGuard 2833 2834 msigrestore(gp.m.sigmask) 2835 2836 gp.m.locks-- 2837 } 2838 2839 // Called from syscall package after fork in parent. 2840 //go:linkname syscall_runtime_AfterFork syscall.runtime_AfterFork 2841 //go:nosplit 2842 func syscall_runtime_AfterFork() { 2843 systemstack(afterfork) 2844 } 2845 2846 // Called from syscall package after fork in child. 2847 // It resets non-sigignored signals to the default handler, and 2848 // restores the signal mask in preparation for the exec. 2849 //go:linkname syscall_runtime_AfterForkInChild syscall.runtime_AfterForkInChild 2850 //go:nosplit 2851 //go:nowritebarrierrec 2852 func syscall_runtime_AfterForkInChild() { 2853 clearSignalHandlers() 2854 2855 // When we are the child we are the only thread running, 2856 // so we know that nothing else has changed gp.m.sigmask. 2857 msigrestore(getg().m.sigmask) 2858 } 2859 2860 // Allocate a new g, with a stack big enough for stacksize bytes. 2861 func malg(stacksize int32) *g { 2862 newg := new(g) 2863 if stacksize >= 0 { 2864 stacksize = round2(_StackSystem + stacksize) 2865 systemstack(func() { 2866 newg.stack = stackalloc(uint32(stacksize)) 2867 }) 2868 newg.stackguard0 = newg.stack.lo + _StackGuard 2869 newg.stackguard1 = ^uintptr(0) 2870 } 2871 return newg 2872 } 2873 2874 // Create a new g running fn with siz bytes of arguments. 2875 // Put it on the queue of g's waiting to run. 2876 // The compiler turns a go statement into a call to this. 2877 // Cannot split the stack because it assumes that the arguments 2878 // are available sequentially after &fn; they would not be 2879 // copied if a stack split occurred. 2880 //go:nosplit 2881 func newproc(siz int32, fn *funcval) { 2882 argp := add(unsafe.Pointer(&fn), sys.PtrSize) 2883 pc := getcallerpc(unsafe.Pointer(&siz)) 2884 systemstack(func() { 2885 newproc1(fn, (*uint8)(argp), siz, 0, pc) 2886 }) 2887 } 2888 2889 // Create a new g running fn with narg bytes of arguments starting 2890 // at argp and returning nret bytes of results. callerpc is the 2891 // address of the go statement that created this. The new g is put 2892 // on the queue of g's waiting to run. 2893 func newproc1(fn *funcval, argp *uint8, narg int32, nret int32, callerpc uintptr) *g { 2894 _g_ := getg() 2895 2896 if fn == nil { 2897 _g_.m.throwing = -1 // do not dump full stacks 2898 throw("go of nil func value") 2899 } 2900 _g_.m.locks++ // disable preemption because it can be holding p in a local var 2901 siz := narg + nret 2902 siz = (siz + 7) &^ 7 2903 2904 // We could allocate a larger initial stack if necessary. 2905 // Not worth it: this is almost always an error. 2906 // 4*sizeof(uintreg): extra space added below 2907 // sizeof(uintreg): caller's LR (arm) or return address (x86, in gostartcall). 2908 if siz >= _StackMin-4*sys.RegSize-sys.RegSize { 2909 throw("newproc: function arguments too large for new goroutine") 2910 } 2911 2912 _p_ := _g_.m.p.ptr() 2913 newg := gfget(_p_) 2914 if newg == nil { 2915 newg = malg(_StackMin) 2916 casgstatus(newg, _Gidle, _Gdead) 2917 allgadd(newg) // publishes with a g->status of Gdead so GC scanner doesn't look at uninitialized stack. 2918 } 2919 if newg.stack.hi == 0 { 2920 throw("newproc1: newg missing stack") 2921 } 2922 2923 if readgstatus(newg) != _Gdead { 2924 throw("newproc1: new g is not Gdead") 2925 } 2926 2927 totalSize := 4*sys.RegSize + uintptr(siz) + sys.MinFrameSize // extra space in case of reads slightly beyond frame 2928 totalSize += -totalSize & (sys.SpAlign - 1) // align to spAlign 2929 sp := newg.stack.hi - totalSize 2930 spArg := sp 2931 if usesLR { 2932 // caller's LR 2933 *(*uintptr)(unsafe.Pointer(sp)) = 0 2934 prepGoExitFrame(sp) 2935 spArg += sys.MinFrameSize 2936 } 2937 if narg > 0 { 2938 memmove(unsafe.Pointer(spArg), unsafe.Pointer(argp), uintptr(narg)) 2939 // This is a stack-to-stack copy. If write barriers 2940 // are enabled and the source stack is grey (the 2941 // destination is always black), then perform a 2942 // barrier copy. We do this *after* the memmove 2943 // because the destination stack may have garbage on 2944 // it. 2945 if writeBarrier.needed && !_g_.m.curg.gcscandone { 2946 f := findfunc(fn.fn) 2947 stkmap := (*stackmap)(funcdata(f, _FUNCDATA_ArgsPointerMaps)) 2948 // We're in the prologue, so it's always stack map index 0. 2949 bv := stackmapdata(stkmap, 0) 2950 bulkBarrierBitmap(spArg, spArg, uintptr(narg), 0, bv.bytedata) 2951 } 2952 } 2953 2954 memclrNoHeapPointers(unsafe.Pointer(&newg.sched), unsafe.Sizeof(newg.sched)) 2955 newg.sched.sp = sp 2956 newg.stktopsp = sp 2957 newg.sched.pc = funcPC(goexit) + sys.PCQuantum // +PCQuantum so that previous instruction is in same function 2958 newg.sched.g = guintptr(unsafe.Pointer(newg)) 2959 gostartcallfn(&newg.sched, fn) 2960 newg.gopc = callerpc 2961 newg.startpc = fn.fn 2962 if _g_.m.curg != nil { 2963 newg.labels = _g_.m.curg.labels 2964 } 2965 if isSystemGoroutine(newg) { 2966 atomic.Xadd(&sched.ngsys, +1) 2967 } 2968 newg.gcscanvalid = false 2969 casgstatus(newg, _Gdead, _Grunnable) 2970 2971 if _p_.goidcache == _p_.goidcacheend { 2972 // Sched.goidgen is the last allocated id, 2973 // this batch must be [sched.goidgen+1, sched.goidgen+GoidCacheBatch]. 2974 // At startup sched.goidgen=0, so main goroutine receives goid=1. 2975 _p_.goidcache = atomic.Xadd64(&sched.goidgen, _GoidCacheBatch) 2976 _p_.goidcache -= _GoidCacheBatch - 1 2977 _p_.goidcacheend = _p_.goidcache + _GoidCacheBatch 2978 } 2979 newg.goid = int64(_p_.goidcache) 2980 _p_.goidcache++ 2981 if raceenabled { 2982 newg.racectx = racegostart(callerpc) 2983 } 2984 if trace.enabled { 2985 traceGoCreate(newg, newg.startpc) 2986 } 2987 runqput(_p_, newg, true) 2988 2989 if atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 && runtimeInitTime != 0 { 2990 wakep() 2991 } 2992 _g_.m.locks-- 2993 if _g_.m.locks == 0 && _g_.preempt { // restore the preemption request in case we've cleared it in newstack 2994 _g_.stackguard0 = stackPreempt 2995 } 2996 return newg 2997 } 2998 2999 // Put on gfree list. 3000 // If local list is too long, transfer a batch to the global list. 3001 func gfput(_p_ *p, gp *g) { 3002 if readgstatus(gp) != _Gdead { 3003 throw("gfput: bad status (not Gdead)") 3004 } 3005 3006 stksize := gp.stack.hi - gp.stack.lo 3007 3008 if stksize != _FixedStack { 3009 // non-standard stack size - free it. 3010 stackfree(gp.stack) 3011 gp.stack.lo = 0 3012 gp.stack.hi = 0 3013 gp.stackguard0 = 0 3014 } 3015 3016 gp.schedlink.set(_p_.gfree) 3017 _p_.gfree = gp 3018 _p_.gfreecnt++ 3019 if _p_.gfreecnt >= 64 { 3020 lock(&sched.gflock) 3021 for _p_.gfreecnt >= 32 { 3022 _p_.gfreecnt-- 3023 gp = _p_.gfree 3024 _p_.gfree = gp.schedlink.ptr() 3025 if gp.stack.lo == 0 { 3026 gp.schedlink.set(sched.gfreeNoStack) 3027 sched.gfreeNoStack = gp 3028 } else { 3029 gp.schedlink.set(sched.gfreeStack) 3030 sched.gfreeStack = gp 3031 } 3032 sched.ngfree++ 3033 } 3034 unlock(&sched.gflock) 3035 } 3036 } 3037 3038 // Get from gfree list. 3039 // If local list is empty, grab a batch from global list. 3040 func gfget(_p_ *p) *g { 3041 retry: 3042 gp := _p_.gfree 3043 if gp == nil && (sched.gfreeStack != nil || sched.gfreeNoStack != nil) { 3044 lock(&sched.gflock) 3045 for _p_.gfreecnt < 32 { 3046 if sched.gfreeStack != nil { 3047 // Prefer Gs with stacks. 3048 gp = sched.gfreeStack 3049 sched.gfreeStack = gp.schedlink.ptr() 3050 } else if sched.gfreeNoStack != nil { 3051 gp = sched.gfreeNoStack 3052 sched.gfreeNoStack = gp.schedlink.ptr() 3053 } else { 3054 break 3055 } 3056 _p_.gfreecnt++ 3057 sched.ngfree-- 3058 gp.schedlink.set(_p_.gfree) 3059 _p_.gfree = gp 3060 } 3061 unlock(&sched.gflock) 3062 goto retry 3063 } 3064 if gp != nil { 3065 _p_.gfree = gp.schedlink.ptr() 3066 _p_.gfreecnt-- 3067 if gp.stack.lo == 0 { 3068 // Stack was deallocated in gfput. Allocate a new one. 3069 systemstack(func() { 3070 gp.stack = stackalloc(_FixedStack) 3071 }) 3072 gp.stackguard0 = gp.stack.lo + _StackGuard 3073 } else { 3074 if raceenabled { 3075 racemalloc(unsafe.Pointer(gp.stack.lo), gp.stack.hi-gp.stack.lo) 3076 } 3077 if msanenabled { 3078 msanmalloc(unsafe.Pointer(gp.stack.lo), gp.stack.hi-gp.stack.lo) 3079 } 3080 } 3081 } 3082 return gp 3083 } 3084 3085 // Purge all cached G's from gfree list to the global list. 3086 func gfpurge(_p_ *p) { 3087 lock(&sched.gflock) 3088 for _p_.gfreecnt != 0 { 3089 _p_.gfreecnt-- 3090 gp := _p_.gfree 3091 _p_.gfree = gp.schedlink.ptr() 3092 if gp.stack.lo == 0 { 3093 gp.schedlink.set(sched.gfreeNoStack) 3094 sched.gfreeNoStack = gp 3095 } else { 3096 gp.schedlink.set(sched.gfreeStack) 3097 sched.gfreeStack = gp 3098 } 3099 sched.ngfree++ 3100 } 3101 unlock(&sched.gflock) 3102 } 3103 3104 // Breakpoint executes a breakpoint trap. 3105 func Breakpoint() { 3106 breakpoint() 3107 } 3108 3109 // dolockOSThread is called by LockOSThread and lockOSThread below 3110 // after they modify m.locked. Do not allow preemption during this call, 3111 // or else the m might be different in this function than in the caller. 3112 //go:nosplit 3113 func dolockOSThread() { 3114 _g_ := getg() 3115 _g_.m.lockedg = _g_ 3116 _g_.lockedm = _g_.m 3117 } 3118 3119 //go:nosplit 3120 3121 // LockOSThread wires the calling goroutine to its current operating system thread. 3122 // Until the calling goroutine exits or calls UnlockOSThread, it will always 3123 // execute in that thread, and no other goroutine can. 3124 func LockOSThread() { 3125 getg().m.locked |= _LockExternal 3126 dolockOSThread() 3127 } 3128 3129 //go:nosplit 3130 func lockOSThread() { 3131 getg().m.locked += _LockInternal 3132 dolockOSThread() 3133 } 3134 3135 // dounlockOSThread is called by UnlockOSThread and unlockOSThread below 3136 // after they update m->locked. Do not allow preemption during this call, 3137 // or else the m might be in different in this function than in the caller. 3138 //go:nosplit 3139 func dounlockOSThread() { 3140 _g_ := getg() 3141 if _g_.m.locked != 0 { 3142 return 3143 } 3144 _g_.m.lockedg = nil 3145 _g_.lockedm = nil 3146 } 3147 3148 //go:nosplit 3149 3150 // UnlockOSThread unwires the calling goroutine from its fixed operating system thread. 3151 // If the calling goroutine has not called LockOSThread, UnlockOSThread is a no-op. 3152 func UnlockOSThread() { 3153 getg().m.locked &^= _LockExternal 3154 dounlockOSThread() 3155 } 3156 3157 //go:nosplit 3158 func unlockOSThread() { 3159 _g_ := getg() 3160 if _g_.m.locked < _LockInternal { 3161 systemstack(badunlockosthread) 3162 } 3163 _g_.m.locked -= _LockInternal 3164 dounlockOSThread() 3165 } 3166 3167 func badunlockosthread() { 3168 throw("runtime: internal error: misuse of lockOSThread/unlockOSThread") 3169 } 3170 3171 func gcount() int32 { 3172 n := int32(allglen) - sched.ngfree - int32(atomic.Load(&sched.ngsys)) 3173 for _, _p_ := range &allp { 3174 if _p_ == nil { 3175 break 3176 } 3177 n -= _p_.gfreecnt 3178 } 3179 3180 // All these variables can be changed concurrently, so the result can be inconsistent. 3181 // But at least the current goroutine is running. 3182 if n < 1 { 3183 n = 1 3184 } 3185 return n 3186 } 3187 3188 func mcount() int32 { 3189 return sched.mcount 3190 } 3191 3192 var prof struct { 3193 signalLock uint32 3194 hz int32 3195 } 3196 3197 func _System() { _System() } 3198 func _ExternalCode() { _ExternalCode() } 3199 func _LostExternalCode() { _LostExternalCode() } 3200 func _GC() { _GC() } 3201 3202 // Called if we receive a SIGPROF signal. 3203 // Called by the signal handler, may run during STW. 3204 //go:nowritebarrierrec 3205 func sigprof(pc, sp, lr uintptr, gp *g, mp *m) { 3206 if prof.hz == 0 { 3207 return 3208 } 3209 3210 // Profiling runs concurrently with GC, so it must not allocate. 3211 // Set a trap in case the code does allocate. 3212 // Note that on windows, one thread takes profiles of all the 3213 // other threads, so mp is usually not getg().m. 3214 // In fact mp may not even be stopped. 3215 // See golang.org/issue/17165. 3216 getg().m.mallocing++ 3217 3218 // Define that a "user g" is a user-created goroutine, and a "system g" 3219 // is one that is m->g0 or m->gsignal. 3220 // 3221 // We might be interrupted for profiling halfway through a 3222 // goroutine switch. The switch involves updating three (or four) values: 3223 // g, PC, SP, and (on arm) LR. The PC must be the last to be updated, 3224 // because once it gets updated the new g is running. 3225 // 3226 // When switching from a user g to a system g, LR is not considered live, 3227 // so the update only affects g, SP, and PC. Since PC must be last, there 3228 // the possible partial transitions in ordinary execution are (1) g alone is updated, 3229 // (2) both g and SP are updated, and (3) SP alone is updated. 3230 // If SP or g alone is updated, we can detect the partial transition by checking 3231 // whether the SP is within g's stack bounds. (We could also require that SP 3232 // be changed only after g, but the stack bounds check is needed by other 3233 // cases, so there is no need to impose an additional requirement.) 3234 // 3235 // There is one exceptional transition to a system g, not in ordinary execution. 3236 // When a signal arrives, the operating system starts the signal handler running 3237 // with an updated PC and SP. The g is updated last, at the beginning of the 3238 // handler. There are two reasons this is okay. First, until g is updated the 3239 // g and SP do not match, so the stack bounds check detects the partial transition. 3240 // Second, signal handlers currently run with signals disabled, so a profiling 3241 // signal cannot arrive during the handler. 3242 // 3243 // When switching from a system g to a user g, there are three possibilities. 3244 // 3245 // First, it may be that the g switch has no PC update, because the SP 3246 // either corresponds to a user g throughout (as in asmcgocall) 3247 // or because it has been arranged to look like a user g frame 3248 // (as in cgocallback_gofunc). In this case, since the entire 3249 // transition is a g+SP update, a partial transition updating just one of 3250 // those will be detected by the stack bounds check. 3251 // 3252 // Second, when returning from a signal handler, the PC and SP updates 3253 // are performed by the operating system in an atomic update, so the g 3254 // update must be done before them. The stack bounds check detects 3255 // the partial transition here, and (again) signal handlers run with signals 3256 // disabled, so a profiling signal cannot arrive then anyway. 3257 // 3258 // Third, the common case: it may be that the switch updates g, SP, and PC 3259 // separately. If the PC is within any of the functions that does this, 3260 // we don't ask for a traceback. C.F. the function setsSP for more about this. 3261 // 3262 // There is another apparently viable approach, recorded here in case 3263 // the "PC within setsSP function" check turns out not to be usable. 3264 // It would be possible to delay the update of either g or SP until immediately 3265 // before the PC update instruction. Then, because of the stack bounds check, 3266 // the only problematic interrupt point is just before that PC update instruction, 3267 // and the sigprof handler can detect that instruction and simulate stepping past 3268 // it in order to reach a consistent state. On ARM, the update of g must be made 3269 // in two places (in R10 and also in a TLS slot), so the delayed update would 3270 // need to be the SP update. The sigprof handler must read the instruction at 3271 // the current PC and if it was the known instruction (for example, JMP BX or 3272 // MOV R2, PC), use that other register in place of the PC value. 3273 // The biggest drawback to this solution is that it requires that we can tell 3274 // whether it's safe to read from the memory pointed at by PC. 3275 // In a correct program, we can test PC == nil and otherwise read, 3276 // but if a profiling signal happens at the instant that a program executes 3277 // a bad jump (before the program manages to handle the resulting fault) 3278 // the profiling handler could fault trying to read nonexistent memory. 3279 // 3280 // To recap, there are no constraints on the assembly being used for the 3281 // transition. We simply require that g and SP match and that the PC is not 3282 // in gogo. 3283 traceback := true 3284 if gp == nil || sp < gp.stack.lo || gp.stack.hi < sp || setsSP(pc) { 3285 traceback = false 3286 } 3287 var stk [maxCPUProfStack]uintptr 3288 n := 0 3289 if mp.ncgo > 0 && mp.curg != nil && mp.curg.syscallpc != 0 && mp.curg.syscallsp != 0 { 3290 cgoOff := 0 3291 // Check cgoCallersUse to make sure that we are not 3292 // interrupting other code that is fiddling with 3293 // cgoCallers. We are running in a signal handler 3294 // with all signals blocked, so we don't have to worry 3295 // about any other code interrupting us. 3296 if atomic.Load(&mp.cgoCallersUse) == 0 && mp.cgoCallers != nil && mp.cgoCallers[0] != 0 { 3297 for cgoOff < len(mp.cgoCallers) && mp.cgoCallers[cgoOff] != 0 { 3298 cgoOff++ 3299 } 3300 copy(stk[:], mp.cgoCallers[:cgoOff]) 3301 mp.cgoCallers[0] = 0 3302 } 3303 3304 // Collect Go stack that leads to the cgo call. 3305 n = gentraceback(mp.curg.syscallpc, mp.curg.syscallsp, 0, mp.curg, 0, &stk[cgoOff], len(stk)-cgoOff, nil, nil, 0) 3306 } else if traceback { 3307 n = gentraceback(pc, sp, lr, gp, 0, &stk[0], len(stk), nil, nil, _TraceTrap|_TraceJumpStack) 3308 } 3309 3310 if n <= 0 { 3311 // Normal traceback is impossible or has failed. 3312 // See if it falls into several common cases. 3313 n = 0 3314 if GOOS == "windows" && mp.libcallg != 0 && mp.libcallpc != 0 && mp.libcallsp != 0 { 3315 // Libcall, i.e. runtime syscall on windows. 3316 // Collect Go stack that leads to the call. 3317 n = gentraceback(mp.libcallpc, mp.libcallsp, 0, mp.libcallg.ptr(), 0, &stk[0], len(stk), nil, nil, 0) 3318 } 3319 if n == 0 { 3320 // If all of the above has failed, account it against abstract "System" or "GC". 3321 n = 2 3322 // "ExternalCode" is better than "etext". 3323 if pc > firstmoduledata.etext { 3324 pc = funcPC(_ExternalCode) + sys.PCQuantum 3325 } 3326 stk[0] = pc 3327 if mp.preemptoff != "" || mp.helpgc != 0 { 3328 stk[1] = funcPC(_GC) + sys.PCQuantum 3329 } else { 3330 stk[1] = funcPC(_System) + sys.PCQuantum 3331 } 3332 } 3333 } 3334 3335 if prof.hz != 0 { 3336 cpuprof.add(gp, stk[:n]) 3337 } 3338 getg().m.mallocing-- 3339 } 3340 3341 // If the signal handler receives a SIGPROF signal on a non-Go thread, 3342 // it tries to collect a traceback into sigprofCallers. 3343 // sigprofCallersUse is set to non-zero while sigprofCallers holds a traceback. 3344 var sigprofCallers cgoCallers 3345 var sigprofCallersUse uint32 3346 3347 // sigprofNonGo is called if we receive a SIGPROF signal on a non-Go thread, 3348 // and the signal handler collected a stack trace in sigprofCallers. 3349 // When this is called, sigprofCallersUse will be non-zero. 3350 // g is nil, and what we can do is very limited. 3351 //go:nosplit 3352 //go:nowritebarrierrec 3353 func sigprofNonGo() { 3354 if prof.hz != 0 { 3355 n := 0 3356 for n < len(sigprofCallers) && sigprofCallers[n] != 0 { 3357 n++ 3358 } 3359 cpuprof.addNonGo(sigprofCallers[:n]) 3360 } 3361 3362 atomic.Store(&sigprofCallersUse, 0) 3363 } 3364 3365 // sigprofNonGoPC is called when a profiling signal arrived on a 3366 // non-Go thread and we have a single PC value, not a stack trace. 3367 // g is nil, and what we can do is very limited. 3368 //go:nosplit 3369 //go:nowritebarrierrec 3370 func sigprofNonGoPC(pc uintptr) { 3371 if prof.hz != 0 { 3372 stk := []uintptr{ 3373 pc, 3374 funcPC(_ExternalCode) + sys.PCQuantum, 3375 } 3376 cpuprof.addNonGo(stk) 3377 } 3378 } 3379 3380 // Reports whether a function will set the SP 3381 // to an absolute value. Important that 3382 // we don't traceback when these are at the bottom 3383 // of the stack since we can't be sure that we will 3384 // find the caller. 3385 // 3386 // If the function is not on the bottom of the stack 3387 // we assume that it will have set it up so that traceback will be consistent, 3388 // either by being a traceback terminating function 3389 // or putting one on the stack at the right offset. 3390 func setsSP(pc uintptr) bool { 3391 f := findfunc(pc) 3392 if !f.valid() { 3393 // couldn't find the function for this PC, 3394 // so assume the worst and stop traceback 3395 return true 3396 } 3397 switch f.entry { 3398 case gogoPC, systemstackPC, mcallPC, morestackPC: 3399 return true 3400 } 3401 return false 3402 } 3403 3404 // setcpuprofilerate sets the CPU profiling rate to hz times per second. 3405 // If hz <= 0, setcpuprofilerate turns off CPU profiling. 3406 func setcpuprofilerate(hz int32) { 3407 // Force sane arguments. 3408 if hz < 0 { 3409 hz = 0 3410 } 3411 3412 // Disable preemption, otherwise we can be rescheduled to another thread 3413 // that has profiling enabled. 3414 _g_ := getg() 3415 _g_.m.locks++ 3416 3417 // Stop profiler on this thread so that it is safe to lock prof. 3418 // if a profiling signal came in while we had prof locked, 3419 // it would deadlock. 3420 setThreadCPUProfiler(0) 3421 3422 for !atomic.Cas(&prof.signalLock, 0, 1) { 3423 osyield() 3424 } 3425 if prof.hz != hz { 3426 setProcessCPUProfiler(hz) 3427 prof.hz = hz 3428 } 3429 atomic.Store(&prof.signalLock, 0) 3430 3431 lock(&sched.lock) 3432 sched.profilehz = hz 3433 unlock(&sched.lock) 3434 3435 if hz != 0 { 3436 setThreadCPUProfiler(hz) 3437 } 3438 3439 _g_.m.locks-- 3440 } 3441 3442 // Change number of processors. The world is stopped, sched is locked. 3443 // gcworkbufs are not being modified by either the GC or 3444 // the write barrier code. 3445 // Returns list of Ps with local work, they need to be scheduled by the caller. 3446 func procresize(nprocs int32) *p { 3447 old := gomaxprocs 3448 if old < 0 || old > _MaxGomaxprocs || nprocs <= 0 || nprocs > _MaxGomaxprocs { 3449 throw("procresize: invalid arg") 3450 } 3451 if trace.enabled { 3452 traceGomaxprocs(nprocs) 3453 } 3454 3455 // update statistics 3456 now := nanotime() 3457 if sched.procresizetime != 0 { 3458 sched.totaltime += int64(old) * (now - sched.procresizetime) 3459 } 3460 sched.procresizetime = now 3461 3462 // initialize new P's 3463 for i := int32(0); i < nprocs; i++ { 3464 pp := allp[i] 3465 if pp == nil { 3466 pp = new(p) 3467 pp.id = i 3468 pp.status = _Pgcstop 3469 pp.sudogcache = pp.sudogbuf[:0] 3470 for i := range pp.deferpool { 3471 pp.deferpool[i] = pp.deferpoolbuf[i][:0] 3472 } 3473 atomicstorep(unsafe.Pointer(&allp[i]), unsafe.Pointer(pp)) 3474 } 3475 if pp.mcache == nil { 3476 if old == 0 && i == 0 { 3477 if getg().m.mcache == nil { 3478 throw("missing mcache?") 3479 } 3480 pp.mcache = getg().m.mcache // bootstrap 3481 } else { 3482 pp.mcache = allocmcache() 3483 } 3484 } 3485 if raceenabled && pp.racectx == 0 { 3486 if old == 0 && i == 0 { 3487 pp.racectx = raceprocctx0 3488 raceprocctx0 = 0 // bootstrap 3489 } else { 3490 pp.racectx = raceproccreate() 3491 } 3492 } 3493 } 3494 3495 // free unused P's 3496 for i := nprocs; i < old; i++ { 3497 p := allp[i] 3498 if trace.enabled { 3499 if p == getg().m.p.ptr() { 3500 // moving to p[0], pretend that we were descheduled 3501 // and then scheduled again to keep the trace sane. 3502 traceGoSched() 3503 traceProcStop(p) 3504 } 3505 } 3506 // move all runnable goroutines to the global queue 3507 for p.runqhead != p.runqtail { 3508 // pop from tail of local queue 3509 p.runqtail-- 3510 gp := p.runq[p.runqtail%uint32(len(p.runq))].ptr() 3511 // push onto head of global queue 3512 globrunqputhead(gp) 3513 } 3514 if p.runnext != 0 { 3515 globrunqputhead(p.runnext.ptr()) 3516 p.runnext = 0 3517 } 3518 // if there's a background worker, make it runnable and put 3519 // it on the global queue so it can clean itself up 3520 if gp := p.gcBgMarkWorker.ptr(); gp != nil { 3521 casgstatus(gp, _Gwaiting, _Grunnable) 3522 if trace.enabled { 3523 traceGoUnpark(gp, 0) 3524 } 3525 globrunqput(gp) 3526 // This assignment doesn't race because the 3527 // world is stopped. 3528 p.gcBgMarkWorker.set(nil) 3529 } 3530 for i := range p.sudogbuf { 3531 p.sudogbuf[i] = nil 3532 } 3533 p.sudogcache = p.sudogbuf[:0] 3534 for i := range p.deferpool { 3535 for j := range p.deferpoolbuf[i] { 3536 p.deferpoolbuf[i][j] = nil 3537 } 3538 p.deferpool[i] = p.deferpoolbuf[i][:0] 3539 } 3540 freemcache(p.mcache) 3541 p.mcache = nil 3542 gfpurge(p) 3543 traceProcFree(p) 3544 if raceenabled { 3545 raceprocdestroy(p.racectx) 3546 p.racectx = 0 3547 } 3548 p.status = _Pdead 3549 // can't free P itself because it can be referenced by an M in syscall 3550 } 3551 3552 _g_ := getg() 3553 if _g_.m.p != 0 && _g_.m.p.ptr().id < nprocs { 3554 // continue to use the current P 3555 _g_.m.p.ptr().status = _Prunning 3556 } else { 3557 // release the current P and acquire allp[0] 3558 if _g_.m.p != 0 { 3559 _g_.m.p.ptr().m = 0 3560 } 3561 _g_.m.p = 0 3562 _g_.m.mcache = nil 3563 p := allp[0] 3564 p.m = 0 3565 p.status = _Pidle 3566 acquirep(p) 3567 if trace.enabled { 3568 traceGoStart() 3569 } 3570 } 3571 var runnablePs *p 3572 for i := nprocs - 1; i >= 0; i-- { 3573 p := allp[i] 3574 if _g_.m.p.ptr() == p { 3575 continue 3576 } 3577 p.status = _Pidle 3578 if runqempty(p) { 3579 pidleput(p) 3580 } else { 3581 p.m.set(mget()) 3582 p.link.set(runnablePs) 3583 runnablePs = p 3584 } 3585 } 3586 stealOrder.reset(uint32(nprocs)) 3587 var int32p *int32 = &gomaxprocs // make compiler check that gomaxprocs is an int32 3588 atomic.Store((*uint32)(unsafe.Pointer(int32p)), uint32(nprocs)) 3589 return runnablePs 3590 } 3591 3592 // Associate p and the current m. 3593 // 3594 // This function is allowed to have write barriers even if the caller 3595 // isn't because it immediately acquires _p_. 3596 // 3597 //go:yeswritebarrierrec 3598 func acquirep(_p_ *p) { 3599 // Do the part that isn't allowed to have write barriers. 3600 acquirep1(_p_) 3601 3602 // have p; write barriers now allowed 3603 _g_ := getg() 3604 _g_.m.mcache = _p_.mcache 3605 3606 if trace.enabled { 3607 traceProcStart() 3608 } 3609 } 3610 3611 // acquirep1 is the first step of acquirep, which actually acquires 3612 // _p_. This is broken out so we can disallow write barriers for this 3613 // part, since we don't yet have a P. 3614 // 3615 //go:nowritebarrierrec 3616 func acquirep1(_p_ *p) { 3617 _g_ := getg() 3618 3619 if _g_.m.p != 0 || _g_.m.mcache != nil { 3620 throw("acquirep: already in go") 3621 } 3622 if _p_.m != 0 || _p_.status != _Pidle { 3623 id := int32(0) 3624 if _p_.m != 0 { 3625 id = _p_.m.ptr().id 3626 } 3627 print("acquirep: p->m=", _p_.m, "(", id, ") p->status=", _p_.status, "\n") 3628 throw("acquirep: invalid p state") 3629 } 3630 _g_.m.p.set(_p_) 3631 _p_.m.set(_g_.m) 3632 _p_.status = _Prunning 3633 } 3634 3635 // Disassociate p and the current m. 3636 func releasep() *p { 3637 _g_ := getg() 3638 3639 if _g_.m.p == 0 || _g_.m.mcache == nil { 3640 throw("releasep: invalid arg") 3641 } 3642 _p_ := _g_.m.p.ptr() 3643 if _p_.m.ptr() != _g_.m || _p_.mcache != _g_.m.mcache || _p_.status != _Prunning { 3644 print("releasep: m=", _g_.m, " m->p=", _g_.m.p.ptr(), " p->m=", _p_.m, " m->mcache=", _g_.m.mcache, " p->mcache=", _p_.mcache, " p->status=", _p_.status, "\n") 3645 throw("releasep: invalid p state") 3646 } 3647 if trace.enabled { 3648 traceProcStop(_g_.m.p.ptr()) 3649 } 3650 _g_.m.p = 0 3651 _g_.m.mcache = nil 3652 _p_.m = 0 3653 _p_.status = _Pidle 3654 return _p_ 3655 } 3656 3657 func incidlelocked(v int32) { 3658 lock(&sched.lock) 3659 sched.nmidlelocked += v 3660 if v > 0 { 3661 checkdead() 3662 } 3663 unlock(&sched.lock) 3664 } 3665 3666 // Check for deadlock situation. 3667 // The check is based on number of running M's, if 0 -> deadlock. 3668 func checkdead() { 3669 // For -buildmode=c-shared or -buildmode=c-archive it's OK if 3670 // there are no running goroutines. The calling program is 3671 // assumed to be running. 3672 if islibrary || isarchive { 3673 return 3674 } 3675 3676 // If we are dying because of a signal caught on an already idle thread, 3677 // freezetheworld will cause all running threads to block. 3678 // And runtime will essentially enter into deadlock state, 3679 // except that there is a thread that will call exit soon. 3680 if panicking > 0 { 3681 return 3682 } 3683 3684 // -1 for sysmon 3685 run := sched.mcount - sched.nmidle - sched.nmidlelocked - 1 3686 if run > 0 { 3687 return 3688 } 3689 if run < 0 { 3690 print("runtime: checkdead: nmidle=", sched.nmidle, " nmidlelocked=", sched.nmidlelocked, " mcount=", sched.mcount, "\n") 3691 throw("checkdead: inconsistent counts") 3692 } 3693 3694 grunning := 0 3695 lock(&allglock) 3696 for i := 0; i < len(allgs); i++ { 3697 gp := allgs[i] 3698 if isSystemGoroutine(gp) { 3699 continue 3700 } 3701 s := readgstatus(gp) 3702 switch s &^ _Gscan { 3703 case _Gwaiting: 3704 grunning++ 3705 case _Grunnable, 3706 _Grunning, 3707 _Gsyscall: 3708 unlock(&allglock) 3709 print("runtime: checkdead: find g ", gp.goid, " in status ", s, "\n") 3710 throw("checkdead: runnable g") 3711 } 3712 } 3713 unlock(&allglock) 3714 if grunning == 0 { // possible if main goroutine calls runtime·Goexit() 3715 throw("no goroutines (main called runtime.Goexit) - deadlock!") 3716 } 3717 3718 // Maybe jump time forward for playground. 3719 gp := timejump() 3720 if gp != nil { 3721 casgstatus(gp, _Gwaiting, _Grunnable) 3722 globrunqput(gp) 3723 _p_ := pidleget() 3724 if _p_ == nil { 3725 throw("checkdead: no p for timer") 3726 } 3727 mp := mget() 3728 if mp == nil { 3729 // There should always be a free M since 3730 // nothing is running. 3731 throw("checkdead: no m for timer") 3732 } 3733 mp.nextp.set(_p_) 3734 notewakeup(&mp.park) 3735 return 3736 } 3737 3738 getg().m.throwing = -1 // do not dump full stacks 3739 throw("all goroutines are asleep - deadlock!") 3740 } 3741 3742 // forcegcperiod is the maximum time in nanoseconds between garbage 3743 // collections. If we go this long without a garbage collection, one 3744 // is forced to run. 3745 // 3746 // This is a variable for testing purposes. It normally doesn't change. 3747 var forcegcperiod int64 = 2 * 60 * 1e9 3748 3749 // Always runs without a P, so write barriers are not allowed. 3750 // 3751 //go:nowritebarrierrec 3752 func sysmon() { 3753 // If a heap span goes unused for 5 minutes after a garbage collection, 3754 // we hand it back to the operating system. 3755 scavengelimit := int64(5 * 60 * 1e9) 3756 3757 if debug.scavenge > 0 { 3758 // Scavenge-a-lot for testing. 3759 forcegcperiod = 10 * 1e6 3760 scavengelimit = 20 * 1e6 3761 } 3762 3763 lastscavenge := nanotime() 3764 nscavenge := 0 3765 3766 lasttrace := int64(0) 3767 idle := 0 // how many cycles in succession we had not wokeup somebody 3768 delay := uint32(0) 3769 for { 3770 if idle == 0 { // start with 20us sleep... 3771 delay = 20 3772 } else if idle > 50 { // start doubling the sleep after 1ms... 3773 delay *= 2 3774 } 3775 if delay > 10*1000 { // up to 10ms 3776 delay = 10 * 1000 3777 } 3778 usleep(delay) 3779 if debug.schedtrace <= 0 && (sched.gcwaiting != 0 || atomic.Load(&sched.npidle) == uint32(gomaxprocs)) { 3780 lock(&sched.lock) 3781 if atomic.Load(&sched.gcwaiting) != 0 || atomic.Load(&sched.npidle) == uint32(gomaxprocs) { 3782 atomic.Store(&sched.sysmonwait, 1) 3783 unlock(&sched.lock) 3784 // Make wake-up period small enough 3785 // for the sampling to be correct. 3786 maxsleep := forcegcperiod / 2 3787 if scavengelimit < forcegcperiod { 3788 maxsleep = scavengelimit / 2 3789 } 3790 osRelax(true) 3791 notetsleep(&sched.sysmonnote, maxsleep) 3792 osRelax(false) 3793 lock(&sched.lock) 3794 atomic.Store(&sched.sysmonwait, 0) 3795 noteclear(&sched.sysmonnote) 3796 idle = 0 3797 delay = 20 3798 } 3799 unlock(&sched.lock) 3800 } 3801 // trigger libc interceptors if needed 3802 if *cgo_yield != nil { 3803 asmcgocall(*cgo_yield, nil) 3804 } 3805 // poll network if not polled for more than 10ms 3806 lastpoll := int64(atomic.Load64(&sched.lastpoll)) 3807 now := nanotime() 3808 if lastpoll != 0 && lastpoll+10*1000*1000 < now { 3809 atomic.Cas64(&sched.lastpoll, uint64(lastpoll), uint64(now)) 3810 gp := netpoll(false) // non-blocking - returns list of goroutines 3811 if gp != nil { 3812 // Need to decrement number of idle locked M's 3813 // (pretending that one more is running) before injectglist. 3814 // Otherwise it can lead to the following situation: 3815 // injectglist grabs all P's but before it starts M's to run the P's, 3816 // another M returns from syscall, finishes running its G, 3817 // observes that there is no work to do and no other running M's 3818 // and reports deadlock. 3819 incidlelocked(-1) 3820 injectglist(gp) 3821 incidlelocked(1) 3822 } 3823 } 3824 // retake P's blocked in syscalls 3825 // and preempt long running G's 3826 if retake(now) != 0 { 3827 idle = 0 3828 } else { 3829 idle++ 3830 } 3831 // check if we need to force a GC 3832 if t := (gcTrigger{kind: gcTriggerTime, now: now}); t.test() && atomic.Load(&forcegc.idle) != 0 { 3833 lock(&forcegc.lock) 3834 forcegc.idle = 0 3835 forcegc.g.schedlink = 0 3836 injectglist(forcegc.g) 3837 unlock(&forcegc.lock) 3838 } 3839 // scavenge heap once in a while 3840 if lastscavenge+scavengelimit/2 < now { 3841 mheap_.scavenge(int32(nscavenge), uint64(now), uint64(scavengelimit)) 3842 lastscavenge = now 3843 nscavenge++ 3844 } 3845 if debug.schedtrace > 0 && lasttrace+int64(debug.schedtrace)*1000000 <= now { 3846 lasttrace = now 3847 schedtrace(debug.scheddetail > 0) 3848 } 3849 } 3850 } 3851 3852 type sysmontick struct { 3853 schedtick uint32 3854 schedwhen int64 3855 syscalltick uint32 3856 syscallwhen int64 3857 } 3858 3859 // forcePreemptNS is the time slice given to a G before it is 3860 // preempted. 3861 const forcePreemptNS = 10 * 1000 * 1000 // 10ms 3862 3863 func retake(now int64) uint32 { 3864 n := 0 3865 for i := int32(0); i < gomaxprocs; i++ { 3866 _p_ := allp[i] 3867 if _p_ == nil { 3868 continue 3869 } 3870 pd := &_p_.sysmontick 3871 s := _p_.status 3872 if s == _Psyscall { 3873 // Retake P from syscall if it's there for more than 1 sysmon tick (at least 20us). 3874 t := int64(_p_.syscalltick) 3875 if int64(pd.syscalltick) != t { 3876 pd.syscalltick = uint32(t) 3877 pd.syscallwhen = now 3878 continue 3879 } 3880 // On the one hand we don't want to retake Ps if there is no other work to do, 3881 // but on the other hand we want to retake them eventually 3882 // because they can prevent the sysmon thread from deep sleep. 3883 if runqempty(_p_) && atomic.Load(&sched.nmspinning)+atomic.Load(&sched.npidle) > 0 && pd.syscallwhen+10*1000*1000 > now { 3884 continue 3885 } 3886 // Need to decrement number of idle locked M's 3887 // (pretending that one more is running) before the CAS. 3888 // Otherwise the M from which we retake can exit the syscall, 3889 // increment nmidle and report deadlock. 3890 incidlelocked(-1) 3891 if atomic.Cas(&_p_.status, s, _Pidle) { 3892 if trace.enabled { 3893 traceGoSysBlock(_p_) 3894 traceProcStop(_p_) 3895 } 3896 n++ 3897 _p_.syscalltick++ 3898 handoffp(_p_) 3899 } 3900 incidlelocked(1) 3901 } else if s == _Prunning { 3902 // Preempt G if it's running for too long. 3903 t := int64(_p_.schedtick) 3904 if int64(pd.schedtick) != t { 3905 pd.schedtick = uint32(t) 3906 pd.schedwhen = now 3907 continue 3908 } 3909 if pd.schedwhen+forcePreemptNS > now { 3910 continue 3911 } 3912 preemptone(_p_) 3913 } 3914 } 3915 return uint32(n) 3916 } 3917 3918 // Tell all goroutines that they have been preempted and they should stop. 3919 // This function is purely best-effort. It can fail to inform a goroutine if a 3920 // processor just started running it. 3921 // No locks need to be held. 3922 // Returns true if preemption request was issued to at least one goroutine. 3923 func preemptall() bool { 3924 res := false 3925 for i := int32(0); i < gomaxprocs; i++ { 3926 _p_ := allp[i] 3927 if _p_ == nil || _p_.status != _Prunning { 3928 continue 3929 } 3930 if preemptone(_p_) { 3931 res = true 3932 } 3933 } 3934 return res 3935 } 3936 3937 // Tell the goroutine running on processor P to stop. 3938 // This function is purely best-effort. It can incorrectly fail to inform the 3939 // goroutine. It can send inform the wrong goroutine. Even if it informs the 3940 // correct goroutine, that goroutine might ignore the request if it is 3941 // simultaneously executing newstack. 3942 // No lock needs to be held. 3943 // Returns true if preemption request was issued. 3944 // The actual preemption will happen at some point in the future 3945 // and will be indicated by the gp->status no longer being 3946 // Grunning 3947 func preemptone(_p_ *p) bool { 3948 mp := _p_.m.ptr() 3949 if mp == nil || mp == getg().m { 3950 return false 3951 } 3952 gp := mp.curg 3953 if gp == nil || gp == mp.g0 { 3954 return false 3955 } 3956 3957 gp.preempt = true 3958 3959 // Every call in a go routine checks for stack overflow by 3960 // comparing the current stack pointer to gp->stackguard0. 3961 // Setting gp->stackguard0 to StackPreempt folds 3962 // preemption into the normal stack overflow check. 3963 gp.stackguard0 = stackPreempt 3964 return true 3965 } 3966 3967 var starttime int64 3968 3969 func schedtrace(detailed bool) { 3970 now := nanotime() 3971 if starttime == 0 { 3972 starttime = now 3973 } 3974 3975 lock(&sched.lock) 3976 print("SCHED ", (now-starttime)/1e6, "ms: gomaxprocs=", gomaxprocs, " idleprocs=", sched.npidle, " threads=", sched.mcount, " spinningthreads=", sched.nmspinning, " idlethreads=", sched.nmidle, " runqueue=", sched.runqsize) 3977 if detailed { 3978 print(" gcwaiting=", sched.gcwaiting, " nmidlelocked=", sched.nmidlelocked, " stopwait=", sched.stopwait, " sysmonwait=", sched.sysmonwait, "\n") 3979 } 3980 // We must be careful while reading data from P's, M's and G's. 3981 // Even if we hold schedlock, most data can be changed concurrently. 3982 // E.g. (p->m ? p->m->id : -1) can crash if p->m changes from non-nil to nil. 3983 for i := int32(0); i < gomaxprocs; i++ { 3984 _p_ := allp[i] 3985 if _p_ == nil { 3986 continue 3987 } 3988 mp := _p_.m.ptr() 3989 h := atomic.Load(&_p_.runqhead) 3990 t := atomic.Load(&_p_.runqtail) 3991 if detailed { 3992 id := int32(-1) 3993 if mp != nil { 3994 id = mp.id 3995 } 3996 print(" P", i, ": status=", _p_.status, " schedtick=", _p_.schedtick, " syscalltick=", _p_.syscalltick, " m=", id, " runqsize=", t-h, " gfreecnt=", _p_.gfreecnt, "\n") 3997 } else { 3998 // In non-detailed mode format lengths of per-P run queues as: 3999 // [len1 len2 len3 len4] 4000 print(" ") 4001 if i == 0 { 4002 print("[") 4003 } 4004 print(t - h) 4005 if i == gomaxprocs-1 { 4006 print("]\n") 4007 } 4008 } 4009 } 4010 4011 if !detailed { 4012 unlock(&sched.lock) 4013 return 4014 } 4015 4016 for mp := allm; mp != nil; mp = mp.alllink { 4017 _p_ := mp.p.ptr() 4018 gp := mp.curg 4019 lockedg := mp.lockedg 4020 id1 := int32(-1) 4021 if _p_ != nil { 4022 id1 = _p_.id 4023 } 4024 id2 := int64(-1) 4025 if gp != nil { 4026 id2 = gp.goid 4027 } 4028 id3 := int64(-1) 4029 if lockedg != nil { 4030 id3 = lockedg.goid 4031 } 4032 print(" M", mp.id, ": p=", id1, " curg=", id2, " mallocing=", mp.mallocing, " throwing=", mp.throwing, " preemptoff=", mp.preemptoff, ""+" locks=", mp.locks, " dying=", mp.dying, " helpgc=", mp.helpgc, " spinning=", mp.spinning, " blocked=", mp.blocked, " lockedg=", id3, "\n") 4033 } 4034 4035 lock(&allglock) 4036 for gi := 0; gi < len(allgs); gi++ { 4037 gp := allgs[gi] 4038 mp := gp.m 4039 lockedm := gp.lockedm 4040 id1 := int32(-1) 4041 if mp != nil { 4042 id1 = mp.id 4043 } 4044 id2 := int32(-1) 4045 if lockedm != nil { 4046 id2 = lockedm.id 4047 } 4048 print(" G", gp.goid, ": status=", readgstatus(gp), "(", gp.waitreason, ") m=", id1, " lockedm=", id2, "\n") 4049 } 4050 unlock(&allglock) 4051 unlock(&sched.lock) 4052 } 4053 4054 // Put mp on midle list. 4055 // Sched must be locked. 4056 // May run during STW, so write barriers are not allowed. 4057 //go:nowritebarrierrec 4058 func mput(mp *m) { 4059 mp.schedlink = sched.midle 4060 sched.midle.set(mp) 4061 sched.nmidle++ 4062 checkdead() 4063 } 4064 4065 // Try to get an m from midle list. 4066 // Sched must be locked. 4067 // May run during STW, so write barriers are not allowed. 4068 //go:nowritebarrierrec 4069 func mget() *m { 4070 mp := sched.midle.ptr() 4071 if mp != nil { 4072 sched.midle = mp.schedlink 4073 sched.nmidle-- 4074 } 4075 return mp 4076 } 4077 4078 // Put gp on the global runnable queue. 4079 // Sched must be locked. 4080 // May run during STW, so write barriers are not allowed. 4081 //go:nowritebarrierrec 4082 func globrunqput(gp *g) { 4083 gp.schedlink = 0 4084 if sched.runqtail != 0 { 4085 sched.runqtail.ptr().schedlink.set(gp) 4086 } else { 4087 sched.runqhead.set(gp) 4088 } 4089 sched.runqtail.set(gp) 4090 sched.runqsize++ 4091 } 4092 4093 // Put gp at the head of the global runnable queue. 4094 // Sched must be locked. 4095 // May run during STW, so write barriers are not allowed. 4096 //go:nowritebarrierrec 4097 func globrunqputhead(gp *g) { 4098 gp.schedlink = sched.runqhead 4099 sched.runqhead.set(gp) 4100 if sched.runqtail == 0 { 4101 sched.runqtail.set(gp) 4102 } 4103 sched.runqsize++ 4104 } 4105 4106 // Put a batch of runnable goroutines on the global runnable queue. 4107 // Sched must be locked. 4108 func globrunqputbatch(ghead *g, gtail *g, n int32) { 4109 gtail.schedlink = 0 4110 if sched.runqtail != 0 { 4111 sched.runqtail.ptr().schedlink.set(ghead) 4112 } else { 4113 sched.runqhead.set(ghead) 4114 } 4115 sched.runqtail.set(gtail) 4116 sched.runqsize += n 4117 } 4118 4119 // Try get a batch of G's from the global runnable queue. 4120 // Sched must be locked. 4121 func globrunqget(_p_ *p, max int32) *g { 4122 if sched.runqsize == 0 { 4123 return nil 4124 } 4125 4126 n := sched.runqsize/gomaxprocs + 1 4127 if n > sched.runqsize { 4128 n = sched.runqsize 4129 } 4130 if max > 0 && n > max { 4131 n = max 4132 } 4133 if n > int32(len(_p_.runq))/2 { 4134 n = int32(len(_p_.runq)) / 2 4135 } 4136 4137 sched.runqsize -= n 4138 if sched.runqsize == 0 { 4139 sched.runqtail = 0 4140 } 4141 4142 gp := sched.runqhead.ptr() 4143 sched.runqhead = gp.schedlink 4144 n-- 4145 for ; n > 0; n-- { 4146 gp1 := sched.runqhead.ptr() 4147 sched.runqhead = gp1.schedlink 4148 runqput(_p_, gp1, false) 4149 } 4150 return gp 4151 } 4152 4153 // Put p to on _Pidle list. 4154 // Sched must be locked. 4155 // May run during STW, so write barriers are not allowed. 4156 //go:nowritebarrierrec 4157 func pidleput(_p_ *p) { 4158 if !runqempty(_p_) { 4159 throw("pidleput: P has non-empty run queue") 4160 } 4161 _p_.link = sched.pidle 4162 sched.pidle.set(_p_) 4163 atomic.Xadd(&sched.npidle, 1) // TODO: fast atomic 4164 } 4165 4166 // Try get a p from _Pidle list. 4167 // Sched must be locked. 4168 // May run during STW, so write barriers are not allowed. 4169 //go:nowritebarrierrec 4170 func pidleget() *p { 4171 _p_ := sched.pidle.ptr() 4172 if _p_ != nil { 4173 sched.pidle = _p_.link 4174 atomic.Xadd(&sched.npidle, -1) // TODO: fast atomic 4175 } 4176 return _p_ 4177 } 4178 4179 // runqempty returns true if _p_ has no Gs on its local run queue. 4180 // It never returns true spuriously. 4181 func runqempty(_p_ *p) bool { 4182 // Defend against a race where 1) _p_ has G1 in runqnext but runqhead == runqtail, 4183 // 2) runqput on _p_ kicks G1 to the runq, 3) runqget on _p_ empties runqnext. 4184 // Simply observing that runqhead == runqtail and then observing that runqnext == nil 4185 // does not mean the queue is empty. 4186 for { 4187 head := atomic.Load(&_p_.runqhead) 4188 tail := atomic.Load(&_p_.runqtail) 4189 runnext := atomic.Loaduintptr((*uintptr)(unsafe.Pointer(&_p_.runnext))) 4190 if tail == atomic.Load(&_p_.runqtail) { 4191 return head == tail && runnext == 0 4192 } 4193 } 4194 } 4195 4196 // To shake out latent assumptions about scheduling order, 4197 // we introduce some randomness into scheduling decisions 4198 // when running with the race detector. 4199 // The need for this was made obvious by changing the 4200 // (deterministic) scheduling order in Go 1.5 and breaking 4201 // many poorly-written tests. 4202 // With the randomness here, as long as the tests pass 4203 // consistently with -race, they shouldn't have latent scheduling 4204 // assumptions. 4205 const randomizeScheduler = raceenabled 4206 4207 // runqput tries to put g on the local runnable queue. 4208 // If next if false, runqput adds g to the tail of the runnable queue. 4209 // If next is true, runqput puts g in the _p_.runnext slot. 4210 // If the run queue is full, runnext puts g on the global queue. 4211 // Executed only by the owner P. 4212 func runqput(_p_ *p, gp *g, next bool) { 4213 if randomizeScheduler && next && fastrand()%2 == 0 { 4214 next = false 4215 } 4216 4217 if next { 4218 retryNext: 4219 oldnext := _p_.runnext 4220 if !_p_.runnext.cas(oldnext, guintptr(unsafe.Pointer(gp))) { 4221 goto retryNext 4222 } 4223 if oldnext == 0 { 4224 return 4225 } 4226 // Kick the old runnext out to the regular run queue. 4227 gp = oldnext.ptr() 4228 } 4229 4230 retry: 4231 h := atomic.Load(&_p_.runqhead) // load-acquire, synchronize with consumers 4232 t := _p_.runqtail 4233 if t-h < uint32(len(_p_.runq)) { 4234 _p_.runq[t%uint32(len(_p_.runq))].set(gp) 4235 atomic.Store(&_p_.runqtail, t+1) // store-release, makes the item available for consumption 4236 return 4237 } 4238 if runqputslow(_p_, gp, h, t) { 4239 return 4240 } 4241 // the queue is not full, now the put above must succeed 4242 goto retry 4243 } 4244 4245 // Put g and a batch of work from local runnable queue on global queue. 4246 // Executed only by the owner P. 4247 func runqputslow(_p_ *p, gp *g, h, t uint32) bool { 4248 var batch [len(_p_.runq)/2 + 1]*g 4249 4250 // First, grab a batch from local queue. 4251 n := t - h 4252 n = n / 2 4253 if n != uint32(len(_p_.runq)/2) { 4254 throw("runqputslow: queue is not full") 4255 } 4256 for i := uint32(0); i < n; i++ { 4257 batch[i] = _p_.runq[(h+i)%uint32(len(_p_.runq))].ptr() 4258 } 4259 if !atomic.Cas(&_p_.runqhead, h, h+n) { // cas-release, commits consume 4260 return false 4261 } 4262 batch[n] = gp 4263 4264 if randomizeScheduler { 4265 for i := uint32(1); i <= n; i++ { 4266 j := fastrandn(i + 1) 4267 batch[i], batch[j] = batch[j], batch[i] 4268 } 4269 } 4270 4271 // Link the goroutines. 4272 for i := uint32(0); i < n; i++ { 4273 batch[i].schedlink.set(batch[i+1]) 4274 } 4275 4276 // Now put the batch on global queue. 4277 lock(&sched.lock) 4278 globrunqputbatch(batch[0], batch[n], int32(n+1)) 4279 unlock(&sched.lock) 4280 return true 4281 } 4282 4283 // Get g from local runnable queue. 4284 // If inheritTime is true, gp should inherit the remaining time in the 4285 // current time slice. Otherwise, it should start a new time slice. 4286 // Executed only by the owner P. 4287 func runqget(_p_ *p) (gp *g, inheritTime bool) { 4288 // If there's a runnext, it's the next G to run. 4289 for { 4290 next := _p_.runnext 4291 if next == 0 { 4292 break 4293 } 4294 if _p_.runnext.cas(next, 0) { 4295 return next.ptr(), true 4296 } 4297 } 4298 4299 for { 4300 h := atomic.Load(&_p_.runqhead) // load-acquire, synchronize with other consumers 4301 t := _p_.runqtail 4302 if t == h { 4303 return nil, false 4304 } 4305 gp := _p_.runq[h%uint32(len(_p_.runq))].ptr() 4306 if atomic.Cas(&_p_.runqhead, h, h+1) { // cas-release, commits consume 4307 return gp, false 4308 } 4309 } 4310 } 4311 4312 // Grabs a batch of goroutines from _p_'s runnable queue into batch. 4313 // Batch is a ring buffer starting at batchHead. 4314 // Returns number of grabbed goroutines. 4315 // Can be executed by any P. 4316 func runqgrab(_p_ *p, batch *[256]guintptr, batchHead uint32, stealRunNextG bool) uint32 { 4317 for { 4318 h := atomic.Load(&_p_.runqhead) // load-acquire, synchronize with other consumers 4319 t := atomic.Load(&_p_.runqtail) // load-acquire, synchronize with the producer 4320 n := t - h 4321 n = n - n/2 4322 if n == 0 { 4323 if stealRunNextG { 4324 // Try to steal from _p_.runnext. 4325 if next := _p_.runnext; next != 0 { 4326 // Sleep to ensure that _p_ isn't about to run the g we 4327 // are about to steal. 4328 // The important use case here is when the g running on _p_ 4329 // ready()s another g and then almost immediately blocks. 4330 // Instead of stealing runnext in this window, back off 4331 // to give _p_ a chance to schedule runnext. This will avoid 4332 // thrashing gs between different Ps. 4333 // A sync chan send/recv takes ~50ns as of time of writing, 4334 // so 3us gives ~50x overshoot. 4335 if GOOS != "windows" { 4336 usleep(3) 4337 } else { 4338 // On windows system timer granularity is 1-15ms, 4339 // which is way too much for this optimization. 4340 // So just yield. 4341 osyield() 4342 } 4343 if !_p_.runnext.cas(next, 0) { 4344 continue 4345 } 4346 batch[batchHead%uint32(len(batch))] = next 4347 return 1 4348 } 4349 } 4350 return 0 4351 } 4352 if n > uint32(len(_p_.runq)/2) { // read inconsistent h and t 4353 continue 4354 } 4355 for i := uint32(0); i < n; i++ { 4356 g := _p_.runq[(h+i)%uint32(len(_p_.runq))] 4357 batch[(batchHead+i)%uint32(len(batch))] = g 4358 } 4359 if atomic.Cas(&_p_.runqhead, h, h+n) { // cas-release, commits consume 4360 return n 4361 } 4362 } 4363 } 4364 4365 // Steal half of elements from local runnable queue of p2 4366 // and put onto local runnable queue of p. 4367 // Returns one of the stolen elements (or nil if failed). 4368 func runqsteal(_p_, p2 *p, stealRunNextG bool) *g { 4369 t := _p_.runqtail 4370 n := runqgrab(p2, &_p_.runq, t, stealRunNextG) 4371 if n == 0 { 4372 return nil 4373 } 4374 n-- 4375 gp := _p_.runq[(t+n)%uint32(len(_p_.runq))].ptr() 4376 if n == 0 { 4377 return gp 4378 } 4379 h := atomic.Load(&_p_.runqhead) // load-acquire, synchronize with consumers 4380 if t-h+n >= uint32(len(_p_.runq)) { 4381 throw("runqsteal: runq overflow") 4382 } 4383 atomic.Store(&_p_.runqtail, t+n) // store-release, makes the item available for consumption 4384 return gp 4385 } 4386 4387 //go:linkname setMaxThreads runtime/debug.setMaxThreads 4388 func setMaxThreads(in int) (out int) { 4389 lock(&sched.lock) 4390 out = int(sched.maxmcount) 4391 if in > 0x7fffffff { // MaxInt32 4392 sched.maxmcount = 0x7fffffff 4393 } else { 4394 sched.maxmcount = int32(in) 4395 } 4396 checkmcount() 4397 unlock(&sched.lock) 4398 return 4399 } 4400 4401 func haveexperiment(name string) bool { 4402 if name == "framepointer" { 4403 return framepointer_enabled // set by linker 4404 } 4405 x := sys.Goexperiment 4406 for x != "" { 4407 xname := "" 4408 i := index(x, ",") 4409 if i < 0 { 4410 xname, x = x, "" 4411 } else { 4412 xname, x = x[:i], x[i+1:] 4413 } 4414 if xname == name { 4415 return true 4416 } 4417 if len(xname) > 2 && xname[:2] == "no" && xname[2:] == name { 4418 return false 4419 } 4420 } 4421 return false 4422 } 4423 4424 //go:nosplit 4425 func procPin() int { 4426 _g_ := getg() 4427 mp := _g_.m 4428 4429 mp.locks++ 4430 return int(mp.p.ptr().id) 4431 } 4432 4433 //go:nosplit 4434 func procUnpin() { 4435 _g_ := getg() 4436 _g_.m.locks-- 4437 } 4438 4439 //go:linkname sync_runtime_procPin sync.runtime_procPin 4440 //go:nosplit 4441 func sync_runtime_procPin() int { 4442 return procPin() 4443 } 4444 4445 //go:linkname sync_runtime_procUnpin sync.runtime_procUnpin 4446 //go:nosplit 4447 func sync_runtime_procUnpin() { 4448 procUnpin() 4449 } 4450 4451 //go:linkname sync_atomic_runtime_procPin sync/atomic.runtime_procPin 4452 //go:nosplit 4453 func sync_atomic_runtime_procPin() int { 4454 return procPin() 4455 } 4456 4457 //go:linkname sync_atomic_runtime_procUnpin sync/atomic.runtime_procUnpin 4458 //go:nosplit 4459 func sync_atomic_runtime_procUnpin() { 4460 procUnpin() 4461 } 4462 4463 // Active spinning for sync.Mutex. 4464 //go:linkname sync_runtime_canSpin sync.runtime_canSpin 4465 //go:nosplit 4466 func sync_runtime_canSpin(i int) bool { 4467 // sync.Mutex is cooperative, so we are conservative with spinning. 4468 // Spin only few times and only if running on a multicore machine and 4469 // GOMAXPROCS>1 and there is at least one other running P and local runq is empty. 4470 // As opposed to runtime mutex we don't do passive spinning here, 4471 // because there can be work on global runq on on other Ps. 4472 if i >= active_spin || ncpu <= 1 || gomaxprocs <= int32(sched.npidle+sched.nmspinning)+1 { 4473 return false 4474 } 4475 if p := getg().m.p.ptr(); !runqempty(p) { 4476 return false 4477 } 4478 return true 4479 } 4480 4481 //go:linkname sync_runtime_doSpin sync.runtime_doSpin 4482 //go:nosplit 4483 func sync_runtime_doSpin() { 4484 procyield(active_spin_cnt) 4485 } 4486 4487 var stealOrder randomOrder 4488 4489 // randomOrder/randomEnum are helper types for randomized work stealing. 4490 // They allow to enumerate all Ps in different pseudo-random orders without repetitions. 4491 // The algorithm is based on the fact that if we have X such that X and GOMAXPROCS 4492 // are coprime, then a sequences of (i + X) % GOMAXPROCS gives the required enumeration. 4493 type randomOrder struct { 4494 count uint32 4495 coprimes []uint32 4496 } 4497 4498 type randomEnum struct { 4499 i uint32 4500 count uint32 4501 pos uint32 4502 inc uint32 4503 } 4504 4505 func (ord *randomOrder) reset(count uint32) { 4506 ord.count = count 4507 ord.coprimes = ord.coprimes[:0] 4508 for i := uint32(1); i <= count; i++ { 4509 if gcd(i, count) == 1 { 4510 ord.coprimes = append(ord.coprimes, i) 4511 } 4512 } 4513 } 4514 4515 func (ord *randomOrder) start(i uint32) randomEnum { 4516 return randomEnum{ 4517 count: ord.count, 4518 pos: i % ord.count, 4519 inc: ord.coprimes[i%uint32(len(ord.coprimes))], 4520 } 4521 } 4522 4523 func (enum *randomEnum) done() bool { 4524 return enum.i == enum.count 4525 } 4526 4527 func (enum *randomEnum) next() { 4528 enum.i++ 4529 enum.pos = (enum.pos + enum.inc) % enum.count 4530 } 4531 4532 func (enum *randomEnum) position() uint32 { 4533 return enum.pos 4534 } 4535 4536 func gcd(a, b uint32) uint32 { 4537 for b != 0 { 4538 a, b = b, a%b 4539 } 4540 return a 4541 }