Source file
src/runtime/proc.go
1
2
3
4
5 package runtime
6
7 import (
8 "internal/abi"
9 "internal/cpu"
10 "internal/goarch"
11 "internal/goexperiment"
12 "internal/runtime/atomic"
13 "internal/runtime/exithook"
14 "internal/runtime/maps"
15 "internal/runtime/sys"
16 "internal/strconv"
17 "internal/stringslite"
18 "unsafe"
19 )
20
21
22 var modinfo string
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118 var (
119 m0 m
120 g0 g
121 mcache0 *mcache
122 raceprocctx0 uintptr
123 raceFiniLock mutex
124 )
125
126
127
128 var runtime_inittasks []*initTask
129
130
131
132 var mainInitDone atomic.Bool
133
134
135
136
137 var mainInitDoneChan chan bool
138
139
140 func main_main()
141
142
143 var mainStarted bool
144
145
146 var runtimeInitTime int64
147
148
149 var initSigmask sigset
150
151
152 func main() {
153 mp := getg().m
154
155
156
157 mp.g0.racectx = 0
158
159
160
161
162 if goarch.PtrSize == 8 {
163 maxstacksize = 1000000000
164 } else {
165 maxstacksize = 250000000
166 }
167
168
169
170
171 maxstackceiling = 2 * maxstacksize
172
173
174 mainStarted = true
175
176 if haveSysmon {
177 systemstack(func() {
178 newm(sysmon, nil, -1)
179 })
180 }
181
182
183
184
185
186
187
188 lockOSThread()
189
190 if mp != &m0 {
191 throw("runtime.main not on m0")
192 }
193
194
195
196 runtimeInitTime = nanotime()
197 if runtimeInitTime == 0 {
198 throw("nanotime returning zero")
199 }
200
201 if debug.inittrace != 0 {
202 inittrace.id = getg().goid
203 inittrace.active = true
204 }
205
206 doInit(runtime_inittasks)
207
208
209 needUnlock := true
210 defer func() {
211 if needUnlock {
212 unlockOSThread()
213 }
214 }()
215
216 gcenable()
217 defaultGOMAXPROCSUpdateEnable()
218
219
220 if k := invalidGODEBUG.key; k != "" {
221 v := invalidGODEBUG.value
222 r := strconv.Itoa(invalidGODEBUG.removed)
223 fatal(`removed GODEBUG "` + k + `" set to old value "` + v + `" in environment (https://go.dev/doc/godebug#go-1` + r + `)`)
224 }
225
226 mainInitDoneChan = make(chan bool)
227 if iscgo {
228 if _cgo_pthread_key_created == nil {
229 throw("_cgo_pthread_key_created missing")
230 }
231
232 if GOOS != "windows" {
233 if _cgo_thread_start == nil && (!goexperiment.RuntimeCgoPurego || cgoThreadStart == nil) {
234 throw("_cgo_thread_start missing")
235 }
236 if _cgo_setenv == nil && (!goexperiment.RuntimeCgoPurego || cgoSetenv == nil) {
237 throw("_cgo_setenv missing")
238 }
239 if _cgo_unsetenv == nil && (!goexperiment.RuntimeCgoPurego || cgoUnsetenv == nil) {
240 throw("_cgo_unsetenv missing")
241 }
242 }
243 if _cgo_notify_runtime_init_done == nil && (!goexperiment.RuntimeCgoPurego || cgoNotifyRuntimeInitDone == nil) {
244 throw("_cgo_notify_runtime_init_done missing")
245 }
246
247
248 if set_crosscall2 == nil {
249 throw("set_crosscall2 missing")
250 }
251 set_crosscall2()
252
253
254
255 startTemplateThread()
256 if goexperiment.RuntimeCgoPurego && cgoNotifyRuntimeInitDone != nil {
257 cgoNotifyRuntimeInitDone()
258 } else {
259 cgocall(_cgo_notify_runtime_init_done, nil)
260 }
261 }
262
263
264
265
266
267
268
269
270 last := lastmoduledatap
271 for m := &firstmoduledata; true; m = m.next {
272 doInit(m.inittasks)
273 if m == last {
274 break
275 }
276 }
277
278
279
280 inittrace.active = false
281
282 mainInitDone.Store(true)
283 close(mainInitDoneChan)
284
285 needUnlock = false
286 unlockOSThread()
287
288 if isarchive || islibrary {
289
290
291 if GOARCH == "wasm" || GOARCH == "wasm32" {
292
293
294
295
296
297
298
299 pause(sys.GetCallerSP() - 16)
300 panic("unreachable")
301 }
302 return
303 }
304 fn := main_main
305 fn()
306
307
308
309
310
311
312
313
314 exitHooksRun := false
315 if asanenabled && (isarchive || islibrary || NumCgoCall() > 1) {
316 runExitHooks(0)
317 exitHooksRun = true
318 lsandoleakcheck()
319 }
320
321
322
323
324
325 if runningPanicDefers.Load() != 0 {
326
327 for c := 0; c < 1000; c++ {
328 if runningPanicDefers.Load() == 0 {
329 break
330 }
331 Gosched()
332 }
333 }
334 if panicking.Load() != 0 {
335 gopark(nil, nil, waitReasonPanicWait, traceBlockForever, 1)
336 }
337 if !exitHooksRun {
338 runExitHooks(0)
339 }
340 if raceenabled {
341 racefini()
342 }
343
344 exit(0)
345 for {
346 var x *int32
347 *x = 0
348 }
349 }
350
351
352
353
354 func os_beforeExit(exitCode int) {
355 runExitHooks(exitCode)
356 if exitCode == 0 && raceenabled {
357 racefini()
358 }
359
360
361 if exitCode == 0 && asanenabled && (isarchive || islibrary || NumCgoCall() > 1) {
362 lsandoleakcheck()
363 }
364 }
365
366 func init() {
367 exithook.Gosched = Gosched
368 exithook.Goid = func() uint64 { return getg().goid }
369 exithook.Throw = throw
370 }
371
372 func runExitHooks(code int) {
373 exithook.Run(code)
374 }
375
376
377 func init() {
378 go forcegchelper()
379 }
380
381 func forcegchelper() {
382 forcegc.g = getg()
383 lockInit(&forcegc.lock, lockRankForcegc)
384 for {
385 lock(&forcegc.lock)
386 if forcegc.idle.Load() {
387 throw("forcegc: phase error")
388 }
389 forcegc.idle.Store(true)
390 goparkunlock(&forcegc.lock, waitReasonForceGCIdle, traceBlockSystemGoroutine, 1)
391
392 if debug.gctrace > 0 {
393 println("GC forced")
394 }
395
396 gcStart(gcTrigger{kind: gcTriggerTime, now: nanotime()})
397 }
398 }
399
400
401
402
403
404 func Gosched() {
405 checkTimeouts()
406 mcall(gosched_m)
407 }
408
409
410
411
412
413 func goschedguarded() {
414 mcall(goschedguarded_m)
415 }
416
417
418
419
420
421
422 func goschedIfBusy() {
423 gp := getg()
424
425
426 if !gp.preempt && sched.npidle.Load() > 0 {
427 return
428 }
429 mcall(gosched_m)
430 }
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460 func gopark(unlockf func(*g, unsafe.Pointer) bool, lock unsafe.Pointer, reason waitReason, traceReason traceBlockReason, traceskip int) {
461 if reason != waitReasonSleep {
462 checkTimeouts()
463 }
464 mp := acquirem()
465 gp := mp.curg
466 status := readgstatus(gp)
467 if status != _Grunning && status != _Gscanrunning {
468 throw("gopark: bad g status")
469 }
470 mp.waitlock = lock
471 mp.waitunlockf = unlockf
472 gp.waitreason = reason
473 mp.waitTraceBlockReason = traceReason
474 mp.waitTraceSkip = traceskip
475 releasem(mp)
476
477 mcall(park_m)
478 }
479
480
481
482 func goparkunlock(lock *mutex, reason waitReason, traceReason traceBlockReason, traceskip int) {
483 gopark(parkunlock_c, unsafe.Pointer(lock), reason, traceReason, traceskip)
484 }
485
486
487
488
489
490
491
492
493
494
495
496 func goready(gp *g, traceskip int) {
497 systemstack(func() {
498 ready(gp, traceskip, true)
499 })
500 }
501
502
503 func acquireWaitingG(typ waitingGType) *waitingG {
504
505
506
507
508
509
510
511
512 mp := acquirem()
513 pp := mp.p.ptr()
514 if len(pp.waitingGCache) == 0 {
515 lock(&sched.waitingGLock)
516
517 for len(pp.waitingGCache) < cap(pp.waitingGCache)/2 && sched.waitingGCache != nil {
518 wg := sched.waitingGCache
519 sched.waitingGCache = wg.next
520 wg.next = nil
521 pp.waitingGCache = append(pp.waitingGCache, wg)
522 }
523 unlock(&sched.waitingGLock)
524
525 if len(pp.waitingGCache) == 0 {
526 pp.waitingGCache = append(pp.waitingGCache, new(waitingG))
527 }
528 }
529 n := len(pp.waitingGCache)
530 wg := pp.waitingGCache[n-1]
531 pp.waitingGCache[n-1] = nil
532 pp.waitingGCache = pp.waitingGCache[:n-1]
533 if wg.typ != waitingGTypeNone {
534 throw("acquireWaitingG: found wg.typ != waitingGTypeNone in cache")
535 }
536 if wg.elem.get() != nil {
537 throw("acquireWaitingG: found wg.elem != nil in cache")
538 }
539 wg.typ = typ
540 releasem(mp)
541 return wg
542 }
543
544
545 func releaseWaitingG(wg *waitingG) {
546 if wg.typ == waitingGTypeNone {
547 throw("runtime: waitingG without type")
548 }
549 if wg.elem.get() != nil {
550 throw("runtime: waitingG with non-nil elem")
551 }
552 if wg.isSelect {
553 throw("runtime: waitingG with non-false isSelect")
554 }
555 if wg.next != nil {
556 throw("runtime: waitingG with non-nil next")
557 }
558 if wg.prev != nil {
559 throw("runtime: waitingG with non-nil prev")
560 }
561 if wg.waitlink != nil {
562 throw("runtime: waitingG with non-nil waitlink")
563 }
564 if wg.c.get() != nil {
565 throw("runtime: waitingG with non-nil c")
566 }
567 wg.typ = waitingGTypeNone
568 gp := getg()
569 if gp.param != nil {
570 throw("runtime: releaseWaitingG with non-nil gp.param")
571 }
572 mp := acquirem()
573 pp := mp.p.ptr()
574 if len(pp.waitingGCache) == cap(pp.waitingGCache) {
575
576 var first, last *waitingG
577 for len(pp.waitingGCache) > cap(pp.waitingGCache)/2 {
578 n := len(pp.waitingGCache)
579 p := pp.waitingGCache[n-1]
580 pp.waitingGCache[n-1] = nil
581 pp.waitingGCache = pp.waitingGCache[:n-1]
582 if first == nil {
583 first = p
584 } else {
585 last.next = p
586 }
587 last = p
588 }
589 lock(&sched.waitingGLock)
590 last.next = sched.waitingGCache
591 sched.waitingGCache = first
592 unlock(&sched.waitingGLock)
593 }
594 pp.waitingGCache = append(pp.waitingGCache, wg)
595 releasem(mp)
596 }
597
598
599 func badmcall(fn func(*g)) {
600 throw("runtime: mcall called on m->g0 stack")
601 }
602
603 func badmcall2(fn func(*g)) {
604 throw("runtime: mcall function returned")
605 }
606
607 func badreflectcall() {
608 panic(plainError("arg size to reflect.call more than 1GB"))
609 }
610
611
612
613 func badmorestackg0() {
614 if !crashStackImplemented {
615 writeErrStr("fatal: morestack on g0\n")
616 return
617 }
618
619 g := getg()
620 switchToCrashStack(func() {
621 print("runtime: morestack on g0, stack [", hex(g.stack.lo), " ", hex(g.stack.hi), "], sp=", hex(g.sched.sp), ", called from\n")
622 g.m.traceback = 2
623 traceback1(g.sched.pc, g.sched.sp, g.sched.lr, g, 0)
624 print("\n")
625
626 throw("morestack on g0")
627 })
628 }
629
630
631
632 func badmorestackgsignal() {
633 writeErrStr("fatal: morestack on gsignal\n")
634 }
635
636
637 func badctxt() {
638 throw("ctxt != 0")
639 }
640
641
642
643 var gcrash g
644
645 var crashingG atomic.Pointer[g]
646
647
648
649
650
651
652
653
654
655 func switchToCrashStack(fn func()) {
656 me := getg()
657 if crashingG.CompareAndSwapNoWB(nil, me) {
658 switchToCrashStack0(fn)
659 abort()
660 }
661 if crashingG.Load() == me {
662
663 writeErrStr("fatal: recursive switchToCrashStack\n")
664 abort()
665 }
666
667 usleep_no_g(100)
668 writeErrStr("fatal: concurrent switchToCrashStack\n")
669 abort()
670 }
671
672
673
674
675 const crashStackImplemented = GOOS != "windows"
676
677
678 func switchToCrashStack0(fn func())
679
680 func lockedOSThread() bool {
681 gp := getg()
682 return gp.lockedm != 0 && gp.m.lockedg != 0
683 }
684
685 var (
686
687
688
689
690
691
692 allglock mutex
693 allgs []*g
694
695
696
697
698
699
700
701
702
703
704
705
706
707 allglen uintptr
708 allgptr **g
709 )
710
711 func allgadd(gp *g) {
712 if readgstatus(gp) == _Gidle {
713 throw("allgadd: bad status Gidle")
714 }
715
716 lock(&allglock)
717 allgs = append(allgs, gp)
718 if &allgs[0] != allgptr {
719 atomicstorep(unsafe.Pointer(&allgptr), unsafe.Pointer(&allgs[0]))
720 }
721 atomic.Storeuintptr(&allglen, uintptr(len(allgs)))
722 unlock(&allglock)
723 }
724
725
726
727
728 func allGsSnapshot() []*g {
729 assertWorldStoppedOrLockHeld(&allglock)
730
731
732
733
734
735
736 return allgs[:len(allgs):len(allgs)]
737 }
738
739
740 func atomicAllG() (**g, uintptr) {
741 length := atomic.Loaduintptr(&allglen)
742 ptr := (**g)(atomic.Loadp(unsafe.Pointer(&allgptr)))
743 return ptr, length
744 }
745
746
747 func atomicAllGIndex(ptr **g, i uintptr) *g {
748 return *(**g)(add(unsafe.Pointer(ptr), i*goarch.PtrSize))
749 }
750
751
752
753
754 func forEachG(fn func(gp *g)) {
755 lock(&allglock)
756 for _, gp := range allgs {
757 fn(gp)
758 }
759 unlock(&allglock)
760 }
761
762
763
764
765
766 func forEachGRace(fn func(gp *g)) {
767 ptr, length := atomicAllG()
768 for i := uintptr(0); i < length; i++ {
769 gp := atomicAllGIndex(ptr, i)
770 fn(gp)
771 }
772 return
773 }
774
775 const (
776
777
778 _GoidCacheBatch = 16
779 )
780
781
782
783 func cpuinit(env string) {
784 cpu.Initialize(env)
785
786
787
788 switch GOARCH {
789 case "386", "amd64":
790 x86HasAVX = cpu.X86.HasAVX
791 x86HasFMA = cpu.X86.HasFMA
792 x86HasPOPCNT = cpu.X86.HasPOPCNT
793 x86HasSSE41 = cpu.X86.HasSSE41
794
795 case "arm":
796 armHasVFPv4 = cpu.ARM.HasVFPv4
797
798 case "arm64":
799 arm64HasATOMICS = cpu.ARM64.HasATOMICS
800
801 case "loong64":
802 loong64HasLAMCAS = cpu.Loong64.HasLAMCAS
803 loong64HasLAM_BH = cpu.Loong64.HasLAM_BH
804 loong64HasDBAR_HINTS = cpu.Loong64.HasDBAR_HINTS
805 loong64HasLSX = cpu.Loong64.HasLSX
806 loong64HasLASX = cpu.Loong64.HasLASX
807
808 case "riscv64":
809 riscv64HasV = cpu.RISCV64.HasV
810 riscv64HasZbb = cpu.RISCV64.HasZbb
811 }
812
813 xRegInitCPU()
814 }
815
816
817
818
819
820
821 func getGodebugEarly() (string, bool) {
822 const prefix = "GODEBUG="
823 var env string
824 switch GOOS {
825 case "aix", "darwin", "ios", "dragonfly", "freebsd", "netbsd", "openbsd", "illumos", "solaris", "linux":
826
827
828
829 n := int32(0)
830 for argv_index(argv, argc+1+n) != nil {
831 n++
832 }
833
834 for i := int32(0); i < n; i++ {
835 p := argv_index(argv, argc+1+i)
836 s := unsafe.String(p, findnull(p))
837
838 if stringslite.HasPrefix(s, prefix) {
839 env = gostringnocopy(p)[len(prefix):]
840 break
841 }
842 }
843 break
844
845 default:
846 return "", false
847 }
848 return env, true
849 }
850
851
852
853
854
855
856
857
858
859 func schedinit() {
860 lockInit(&sched.lock, lockRankSched)
861 lockInit(&sched.sysmonlock, lockRankSysmon)
862 lockInit(&sched.deferlock, lockRankDefer)
863 lockInit(&sched.waitingGLock, lockRankWaitingG)
864 lockInit(&deadlock, lockRankDeadlock)
865 lockInit(&paniclk, lockRankPanic)
866 lockInit(&allglock, lockRankAllg)
867 lockInit(&allpLock, lockRankAllp)
868 lockInit(&reflectOffs.lock, lockRankReflectOffs)
869 lockInit(&finlock, lockRankFin)
870 lockInit(&cpuprof.lock, lockRankCpuprof)
871 lockInit(&computeMaxProcsLock, lockRankComputeMaxProcs)
872 allocmLock.init(lockRankAllocmR, lockRankAllocmRInternal, lockRankAllocmW)
873 execLock.init(lockRankExecR, lockRankExecRInternal, lockRankExecW)
874 traceLockInit()
875
876
877
878 lockInit(&memstats.heapStats.noPLock, lockRankLeafRank)
879
880 lockVerifyMSize()
881
882 sched.midle.init(unsafe.Offsetof(m{}.idleNode))
883
884
885
886 gp := getg()
887 if raceenabled {
888 gp.racectx, raceprocctx0 = raceinit()
889 }
890
891 sched.maxmcount = 10000
892 crashFD.Store(^uintptr(0))
893
894
895 worldStopped()
896
897 godebug, parsedGodebug := getGodebugEarly()
898 if parsedGodebug {
899 parseRuntimeDebugVars(godebug)
900 }
901 ticks.init()
902 moduledataverify()
903 stackinit()
904 randinit()
905 mallocinit()
906 cpuinit(godebug)
907 maps.AlgInit()
908 mcommoninit(gp.m, -1)
909 modulesinit()
910 typelinksinit()
911 itabsinit()
912 stkobjinit()
913
914 sigsave(&gp.m.sigmask)
915 initSigmask = gp.m.sigmask
916
917 goargs()
918 goenvs()
919 secure()
920 checkfds()
921 if !parsedGodebug {
922
923
924 parseRuntimeDebugVars(gogetenv("GODEBUG"))
925 }
926 finishDebugVarsSetup()
927 gcinit()
928
929
930
931 gcrash.stack = stackalloc(16384)
932 gcrash.stackguard0 = gcrash.stack.lo + 1000
933 gcrash.stackguard1 = gcrash.stack.lo + 1000
934
935
936
937
938
939 if disableMemoryProfiling {
940 MemProfileRate = 0
941 }
942
943
944 mProfStackInit(gp.m)
945 defaultGOMAXPROCSInit()
946 if memoryProfileEnabled() {
947 sysRSSInit()
948 }
949
950 lock(&sched.lock)
951 sched.lastpoll.Store(nanotime())
952 var procs int32
953 if n, err := strconv.ParseInt(gogetenv("GOMAXPROCS"), 10, 32); err == nil && n > 0 {
954 procs = int32(n)
955 sched.customGOMAXPROCS = true
956 } else {
957
958
959
960
961
962
963
964
965 procs = defaultGOMAXPROCS(numCPUStartup)
966 }
967 if procresize(procs) != nil {
968 throw("unknown runnable goroutine during bootstrap")
969 }
970 unlock(&sched.lock)
971
972
973 worldStarted()
974
975 if buildVersion == "" {
976
977
978 buildVersion = "unknown"
979 }
980 if len(modinfo) == 1 {
981
982
983 modinfo = ""
984 }
985 }
986
987 func dumpgstatus(gp *g) {
988 thisg := getg()
989 print("runtime: gp: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n")
990 print("runtime: getg: g=", thisg, ", goid=", thisg.goid, ", g->atomicstatus=", readgstatus(thisg), "\n")
991 }
992
993
994 func checkmcount() {
995 assertLockHeld(&sched.lock)
996
997
998
999
1000
1001
1002
1003
1004
1005 count := mcount() - int32(extraMInUse.Load()) - int32(extraMLength.Load())
1006 if count > sched.maxmcount {
1007 print("runtime: program exceeds ", sched.maxmcount, "-thread limit\n")
1008 throw("thread exhaustion")
1009 }
1010 }
1011
1012
1013
1014
1015
1016 func mReserveID() int64 {
1017 assertLockHeld(&sched.lock)
1018
1019 if sched.mnext+1 < sched.mnext {
1020 throw("runtime: thread ID overflow")
1021 }
1022 id := sched.mnext
1023 sched.mnext++
1024 checkmcount()
1025 return id
1026 }
1027
1028
1029 func mcommoninit(mp *m, id int64) {
1030 gp := getg()
1031
1032
1033 if gp != gp.m.g0 {
1034 callers(1, mp.createstack[:])
1035 }
1036
1037 lock(&sched.lock)
1038
1039 if id >= 0 {
1040 mp.id = id
1041 } else {
1042 mp.id = mReserveID()
1043 }
1044
1045 mp.self = newMWeakPointer(mp)
1046
1047 mrandinit(mp)
1048
1049 mpreinit(mp)
1050 if mp.gsignal != nil {
1051 mp.gsignal.stackguard1 = mp.gsignal.stack.lo + stackGuard
1052 }
1053
1054
1055
1056 mp.alllink = allm
1057
1058
1059
1060 atomicstorep(unsafe.Pointer(&allm), unsafe.Pointer(mp))
1061 unlock(&sched.lock)
1062
1063
1064 if iscgo || GOOS == "solaris" || GOOS == "illumos" || GOOS == "windows" {
1065 mp.cgoCallers = new(cgoCallers)
1066 }
1067 mProfStackInit(mp)
1068 }
1069
1070
1071
1072
1073
1074 func mProfStackInit(mp *m) {
1075 if debug.profstackdepth == 0 {
1076
1077
1078 return
1079 }
1080 mp.profStack = makeProfStackFP()
1081 mp.mLockProfile.stack = makeProfStackFP()
1082 }
1083
1084
1085
1086
1087 func makeProfStackFP() []uintptr {
1088
1089
1090
1091
1092
1093
1094 return make([]uintptr, 1+maxSkip+debug.profstackdepth)
1095 }
1096
1097
1098
1099 func makeProfStack() []uintptr { return make([]uintptr, debug.profstackdepth) }
1100
1101
1102 func pprof_makeProfStack() []uintptr { return makeProfStack() }
1103
1104 func (mp *m) becomeSpinning() {
1105 mp.spinning = true
1106 sched.nmspinning.Add(1)
1107 sched.needspinning.Store(0)
1108 }
1109
1110
1111
1112
1113
1114
1115
1116
1117 func (mp *m) snapshotAllp() []*p {
1118 mp.allpSnapshot = allp
1119 return mp.allpSnapshot
1120 }
1121
1122
1123
1124
1125
1126
1127
1128 func (mp *m) clearAllpSnapshot() {
1129 mp.allpSnapshot = nil
1130 }
1131
1132 func (mp *m) hasCgoOnStack() bool {
1133 return mp.ncgo > 0 || mp.isextra
1134 }
1135
1136
1137
1138 const osHasLowResTimer = GOOS == "windows" || GOOS == "openbsd" || GOOS == "netbsd" || GOOS == "plan9"
1139
1140
1141 func ready(gp *g, traceskip int, next bool) {
1142 status := readgstatus(gp)
1143
1144
1145 mp := acquirem()
1146 if status&^_Gscan != _Gwaiting {
1147 dumpgstatus(gp)
1148 throw("bad g->status in ready")
1149 }
1150
1151
1152 trace := traceAcquire()
1153 casgstatus(gp, _Gwaiting, _Grunnable)
1154 if trace.ok() {
1155 trace.GoUnpark(gp, traceskip)
1156 traceRelease(trace)
1157 }
1158 runqput(mp.p.ptr(), gp, next)
1159 wakep()
1160 releasem(mp)
1161 }
1162
1163
1164
1165 const freezeStopWait = 0x7fffffff
1166
1167
1168
1169 var freezing atomic.Bool
1170
1171
1172
1173
1174 func freezetheworld() {
1175 freezing.Store(true)
1176 if debug.dontfreezetheworld > 0 {
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201 usleep(1000)
1202 return
1203 }
1204
1205
1206
1207
1208 for i := 0; i < 5; i++ {
1209
1210 sched.stopwait = freezeStopWait
1211 sched.gcwaiting.Store(true)
1212
1213 if !preemptall() {
1214 break
1215 }
1216 usleep(1000)
1217 }
1218
1219 usleep(1000)
1220 preemptall()
1221 usleep(1000)
1222 }
1223
1224
1225
1226
1227
1228 func readgstatus(gp *g) uint32 {
1229 return gp.atomicstatus.Load()
1230 }
1231
1232
1233
1234
1235
1236 func casfrom_Gscanstatus(gp *g, oldval, newval uint32) {
1237 success := false
1238
1239
1240 switch oldval {
1241 default:
1242 print("runtime: casfrom_Gscanstatus bad oldval gp=", gp, ", oldval=", hex(oldval), ", newval=", hex(newval), "\n")
1243 dumpgstatus(gp)
1244 throw("casfrom_Gscanstatus:top gp->status is not in scan state")
1245 case _Gscanrunnable,
1246 _Gscanwaiting,
1247 _Gscanrunning,
1248 _Gscansyscall,
1249 _Gscanleaked,
1250 _Gscanpreempted,
1251 _Gscandeadextra:
1252 if newval == oldval&^_Gscan {
1253 success = gp.atomicstatus.CompareAndSwap(oldval, newval)
1254 }
1255 }
1256 if !success {
1257 print("runtime: casfrom_Gscanstatus failed gp=", gp, ", oldval=", hex(oldval), ", newval=", hex(newval), "\n")
1258 dumpgstatus(gp)
1259 throw("casfrom_Gscanstatus: gp->status is not in scan state")
1260 }
1261 releaseLockRankAndM(lockRankGscan)
1262 }
1263
1264
1265
1266 func castogscanstatus(gp *g, oldval, newval uint32) bool {
1267 switch oldval {
1268 case _Grunnable,
1269 _Grunning,
1270 _Gwaiting,
1271 _Gleaked,
1272 _Gsyscall,
1273 _Gdeadextra:
1274 if newval == oldval|_Gscan {
1275 r := gp.atomicstatus.CompareAndSwap(oldval, newval)
1276 if r {
1277 acquireLockRankAndM(lockRankGscan)
1278 }
1279 return r
1280
1281 }
1282 }
1283 print("runtime: castogscanstatus oldval=", hex(oldval), " newval=", hex(newval), "\n")
1284 throw("bad oldval passed to castogscanstatus")
1285 return false
1286 }
1287
1288
1289
1290 var casgstatusAlwaysTrack = false
1291
1292
1293
1294
1295
1296
1297
1298 func casgstatus(gp *g, oldval, newval uint32) {
1299 if (oldval&_Gscan != 0) || (newval&_Gscan != 0) || oldval == newval {
1300 systemstack(func() {
1301
1302
1303 print("runtime: casgstatus: oldval=", hex(oldval), " newval=", hex(newval), "\n")
1304 throw("casgstatus: bad incoming values")
1305 })
1306 }
1307
1308 lockWithRankMayAcquire(nil, lockRankGscan)
1309
1310
1311 const yieldDelay = 5 * 1000
1312 var nextYield int64
1313
1314
1315
1316 for i := 0; !gp.atomicstatus.CompareAndSwap(oldval, newval); i++ {
1317 if oldval == _Gwaiting && gp.atomicstatus.Load() == _Grunnable {
1318 systemstack(func() {
1319
1320
1321 throw("casgstatus: waiting for Gwaiting but is Grunnable")
1322 })
1323 }
1324 if i == 0 {
1325 nextYield = nanotime() + yieldDelay
1326 }
1327 if nanotime() < nextYield {
1328 for x := 0; x < 10 && gp.atomicstatus.Load() != oldval; x++ {
1329 procyield(1)
1330 }
1331 } else {
1332 osyield()
1333 nextYield = nanotime() + yieldDelay/2
1334 }
1335 }
1336
1337 if gp.bubble != nil {
1338 systemstack(func() {
1339 gp.bubble.changegstatus(gp, oldval, newval)
1340 })
1341 }
1342
1343 if (oldval == _Grunning || oldval == _Gsyscall) && (newval != _Grunning && newval != _Gsyscall) {
1344
1345
1346 if casgstatusAlwaysTrack || gp.trackingSeq%gTrackingPeriod == 0 {
1347 gp.tracking = true
1348 }
1349 gp.trackingSeq++
1350 }
1351 if !gp.tracking {
1352 return
1353 }
1354
1355
1356
1357
1358
1359
1360 switch oldval {
1361 case _Grunnable:
1362
1363
1364
1365 now := nanotime()
1366 gp.runnableTime += now - gp.trackingStamp
1367 gp.trackingStamp = 0
1368 case _Gwaiting:
1369 if !gp.waitreason.isMutexWait() {
1370
1371 break
1372 }
1373
1374
1375
1376
1377
1378 now := nanotime()
1379 sched.totalMutexWaitTime.Add((now - gp.trackingStamp) * gTrackingPeriod)
1380 gp.trackingStamp = 0
1381 }
1382 switch newval {
1383 case _Gwaiting:
1384 if !gp.waitreason.isMutexWait() {
1385
1386 break
1387 }
1388
1389 now := nanotime()
1390 gp.trackingStamp = now
1391 case _Grunnable:
1392
1393
1394 now := nanotime()
1395 gp.trackingStamp = now
1396 case _Grunning:
1397
1398
1399
1400 gp.tracking = false
1401 sched.timeToRun.record(gp.runnableTime)
1402 gp.runnableTime = 0
1403 }
1404 }
1405
1406
1407
1408
1409 func casGToWaiting(gp *g, old uint32, reason waitReason) {
1410
1411 gp.waitreason = reason
1412 casgstatus(gp, old, _Gwaiting)
1413 }
1414
1415
1416
1417
1418
1419
1420
1421
1422 func casGToWaitingForSuspendG(gp *g, old uint32, reason waitReason) {
1423 if !reason.isWaitingForSuspendG() {
1424 throw("casGToWaitingForSuspendG with non-isWaitingForSuspendG wait reason")
1425 }
1426 casGToWaiting(gp, old, reason)
1427 }
1428
1429
1430
1431
1432
1433 func casGToPreemptScan(gp *g, old, new uint32) {
1434 if old != _Grunning || new != _Gscan|_Gpreempted {
1435 throw("bad g transition")
1436 }
1437 acquireLockRankAndM(lockRankGscan)
1438 for !gp.atomicstatus.CompareAndSwap(_Grunning, _Gscan|_Gpreempted) {
1439 }
1440
1441
1442
1443
1444
1445
1446 }
1447
1448
1449
1450
1451 func casGFromPreempted(gp *g, old, new uint32) bool {
1452 if old != _Gpreempted || new != _Gwaiting {
1453 throw("bad g transition")
1454 }
1455 gp.waitreason = waitReasonPreempted
1456 if !gp.atomicstatus.CompareAndSwap(_Gpreempted, _Gwaiting) {
1457 return false
1458 }
1459 if bubble := gp.bubble; bubble != nil {
1460 bubble.changegstatus(gp, _Gpreempted, _Gwaiting)
1461 }
1462 return true
1463 }
1464
1465
1466 type stwReason uint8
1467
1468
1469
1470
1471 const (
1472 stwUnknown stwReason = iota
1473 stwGCMarkTerm
1474 stwGCSweepTerm
1475 stwWriteHeapDump
1476 stwGoroutineProfile
1477 stwGoroutineProfileCleanup
1478 stwAllGoroutinesStack
1479 stwReadMemStats
1480 stwAllThreadsSyscall
1481 stwGOMAXPROCS
1482 stwStartTrace
1483 stwStopTrace
1484 stwForTestCountPagesInUse
1485 stwForTestReadMetricsSlow
1486 stwForTestReadMemStatsSlow
1487 stwForTestPageCachePagesLeaked
1488 stwForTestResetDebugLog
1489 )
1490
1491 func (r stwReason) String() string {
1492 return stwReasonStrings[r]
1493 }
1494
1495 func (r stwReason) isGC() bool {
1496 return r == stwGCMarkTerm || r == stwGCSweepTerm
1497 }
1498
1499
1500
1501
1502 var stwReasonStrings = [...]string{
1503 stwUnknown: "unknown",
1504 stwGCMarkTerm: "GC mark termination",
1505 stwGCSweepTerm: "GC sweep termination",
1506 stwWriteHeapDump: "write heap dump",
1507 stwGoroutineProfile: "goroutine profile",
1508 stwGoroutineProfileCleanup: "goroutine profile cleanup",
1509 stwAllGoroutinesStack: "all goroutines stack trace",
1510 stwReadMemStats: "read mem stats",
1511 stwAllThreadsSyscall: "AllThreadsSyscall",
1512 stwGOMAXPROCS: "GOMAXPROCS",
1513 stwStartTrace: "start trace",
1514 stwStopTrace: "stop trace",
1515 stwForTestCountPagesInUse: "CountPagesInUse (test)",
1516 stwForTestReadMetricsSlow: "ReadMetricsSlow (test)",
1517 stwForTestReadMemStatsSlow: "ReadMemStatsSlow (test)",
1518 stwForTestPageCachePagesLeaked: "PageCachePagesLeaked (test)",
1519 stwForTestResetDebugLog: "ResetDebugLog (test)",
1520 }
1521
1522
1523
1524 type worldStop struct {
1525 reason stwReason
1526 startedStopping int64
1527 finishedStopping int64
1528 stoppingCPUTime int64
1529 }
1530
1531
1532
1533
1534 var stopTheWorldContext worldStop
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553 func stopTheWorld(reason stwReason) worldStop {
1554 semacquire(&worldsema)
1555 gp := getg()
1556 gp.m.preemptoff = reason.String()
1557 systemstack(func() {
1558 stopTheWorldContext = stopTheWorldWithSema(reason)
1559 })
1560 return stopTheWorldContext
1561 }
1562
1563
1564
1565
1566 func startTheWorld(w worldStop) {
1567 systemstack(func() { startTheWorldWithSema(0, w) })
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584 mp := acquirem()
1585 mp.preemptoff = ""
1586 semrelease1(&worldsema, true, 0)
1587 releasem(mp)
1588 }
1589
1590
1591
1592
1593 func stopTheWorldGC(reason stwReason) worldStop {
1594 semacquire(&gcsema)
1595 return stopTheWorld(reason)
1596 }
1597
1598
1599
1600
1601 func startTheWorldGC(w worldStop) {
1602 startTheWorld(w)
1603 semrelease(&gcsema)
1604 }
1605
1606
1607 var worldsema uint32 = 1
1608
1609
1610
1611
1612
1613
1614
1615 var gcsema uint32 = 1
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649 func stopTheWorldWithSema(reason stwReason) worldStop {
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662 casGToWaitingForSuspendG(getg().m.curg, _Grunning, waitReasonStoppingTheWorld)
1663
1664 trace := traceAcquire()
1665 if trace.ok() {
1666 trace.STWStart(reason)
1667 traceRelease(trace)
1668 }
1669 gp := getg()
1670
1671
1672
1673 if gp.m.locks > 0 {
1674 throw("stopTheWorld: holding locks")
1675 }
1676
1677 lock(&sched.lock)
1678 start := nanotime()
1679 sched.stopwait = gomaxprocs
1680 sched.gcwaiting.Store(true)
1681
1682
1683 gp.m.p.ptr().status = _Pgcstop
1684 gp.m.p.ptr().gcStopTime = start
1685 sched.stopwait--
1686
1687
1688 for _, pp := range allp {
1689 if thread, ok := setBlockOnExitSyscall(pp); ok {
1690 thread.gcstopP()
1691 thread.resume()
1692 }
1693 }
1694
1695
1696 now := nanotime()
1697 for {
1698 pp, _ := pidleget(now)
1699 if pp == nil {
1700 break
1701 }
1702 pp.status = _Pgcstop
1703 pp.gcStopTime = nanotime()
1704 sched.stopwait--
1705 }
1706 wait := sched.stopwait > 0
1707 unlock(&sched.lock)
1708
1709
1710 if wait {
1711 preemptall()
1712 stealRunnextWake()
1713 for {
1714
1715 if notetsleep(&sched.stopnote, 100*1000) {
1716 noteclear(&sched.stopnote)
1717 break
1718 }
1719 preemptall()
1720 }
1721 }
1722
1723 finish := nanotime()
1724 startTime := finish - start
1725 if reason.isGC() {
1726 sched.stwStoppingTimeGC.record(startTime)
1727 } else {
1728 sched.stwStoppingTimeOther.record(startTime)
1729 }
1730
1731
1732
1733
1734
1735 stoppingCPUTime := int64(0)
1736 bad := ""
1737 if sched.stopwait != 0 {
1738 bad = "stopTheWorld: not stopped (stopwait != 0)"
1739 } else {
1740 for _, pp := range allp {
1741 if pp.status != _Pgcstop {
1742 bad = "stopTheWorld: not stopped (status != _Pgcstop)"
1743 }
1744 if pp.gcStopTime == 0 && bad == "" {
1745 bad = "stopTheWorld: broken CPU time accounting"
1746 }
1747 stoppingCPUTime += finish - pp.gcStopTime
1748 pp.gcStopTime = 0
1749 }
1750 }
1751 if freezing.Load() {
1752
1753
1754
1755
1756 lock(&deadlock)
1757 lock(&deadlock)
1758 }
1759 if bad != "" {
1760 throw(bad)
1761 }
1762
1763 worldStopped()
1764
1765
1766 casgstatus(getg().m.curg, _Gwaiting, _Grunning)
1767
1768 return worldStop{
1769 reason: reason,
1770 startedStopping: start,
1771 finishedStopping: finish,
1772 stoppingCPUTime: stoppingCPUTime,
1773 }
1774 }
1775
1776
1777
1778
1779
1780
1781
1782 func startTheWorldWithSema(now int64, w worldStop) int64 {
1783 assertWorldStopped()
1784
1785 mp := acquirem()
1786 if netpollinited() {
1787 list, delta := netpoll(0)
1788 injectglist(&list)
1789 netpollAdjustWaiters(delta)
1790 }
1791 lock(&sched.lock)
1792
1793 procs := gomaxprocs
1794 if newprocs != 0 {
1795 procs = newprocs
1796 newprocs = 0
1797 }
1798 p1 := procresize(procs)
1799 sched.gcwaiting.Store(false)
1800 if sched.sysmonwait.Load() {
1801 sched.sysmonwait.Store(false)
1802 notewakeup(&sched.sysmonnote)
1803 }
1804 unlock(&sched.lock)
1805
1806 worldStarted()
1807
1808 for p1 != nil {
1809 p := p1
1810 p1 = p1.link.ptr()
1811 if p.m != 0 {
1812 mp := p.m.ptr()
1813 p.m = 0
1814 if mp.nextp != 0 {
1815 throw("startTheWorld: inconsistent mp->nextp")
1816 }
1817 mp.nextp.set(p)
1818 notewakeup(&mp.park)
1819 } else {
1820
1821 newm(nil, p, -1)
1822 }
1823 }
1824
1825
1826 if now == 0 {
1827 now = nanotime()
1828 }
1829 totalTime := now - w.startedStopping
1830 if w.reason.isGC() {
1831 sched.stwTotalTimeGC.record(totalTime)
1832 } else {
1833 sched.stwTotalTimeOther.record(totalTime)
1834 }
1835 trace := traceAcquire()
1836 if trace.ok() {
1837 trace.STWDone()
1838 traceRelease(trace)
1839 }
1840
1841
1842
1843
1844 wakep()
1845
1846 releasem(mp)
1847
1848 return now
1849 }
1850
1851
1852
1853 func usesLibcall() bool {
1854 switch GOOS {
1855 case "aix", "darwin", "illumos", "ios", "openbsd", "solaris", "windows":
1856 return true
1857 }
1858 return false
1859 }
1860
1861
1862
1863 func mStackIsSystemAllocated() bool {
1864 switch GOOS {
1865 case "aix", "darwin", "plan9", "illumos", "ios", "openbsd", "solaris", "windows":
1866 return true
1867 }
1868 return false
1869 }
1870
1871
1872
1873
1874
1875 func mstart()
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886 func mstart0() {
1887 gp := getg()
1888
1889 osStack := gp.stack.lo == 0
1890 if osStack {
1891
1892
1893
1894
1895
1896
1897
1898
1899 size := gp.stack.hi
1900 if size == 0 {
1901 size = 16384 * sys.StackGuardMultiplier
1902 }
1903 gp.stack.hi = uintptr(noescape(unsafe.Pointer(&size)))
1904 gp.stack.lo = gp.stack.hi - size + 1024
1905 }
1906
1907
1908 gp.stackguard0 = gp.stack.lo + stackGuard
1909
1910
1911 gp.stackguard1 = gp.stackguard0
1912 mstart1()
1913
1914
1915 if mStackIsSystemAllocated() {
1916
1917
1918
1919 osStack = true
1920 }
1921 mexit(osStack)
1922 }
1923
1924
1925
1926
1927
1928 func mstart1() {
1929 gp := getg()
1930
1931 if gp != gp.m.g0 {
1932 throw("bad runtime·mstart")
1933 }
1934
1935
1936
1937
1938
1939
1940
1941 gp.sched.g = guintptr(unsafe.Pointer(gp))
1942 pc := sys.GetCallerPC()
1943 if goarch.IsWasm32 != 0 {
1944 gobufSetPC(&gp.sched, pc)
1945 } else {
1946
1947 gp.sched.pc = pc
1948 }
1949 gp.sched.sp = sys.GetCallerSP()
1950 gp.sched.bp = getcallerfp()
1951
1952 asminit()
1953 minit()
1954
1955
1956
1957 if gp.m == &m0 {
1958 mstartm0()
1959 }
1960
1961 if debug.dataindependenttiming == 1 {
1962 sys.EnableDIT()
1963 }
1964
1965 if fn := gp.m.mstartfn; fn != nil {
1966 fn()
1967 }
1968
1969 if gp.m != &m0 {
1970 acquirep(gp.m.nextp.ptr())
1971 gp.m.nextp = 0
1972 }
1973 schedule()
1974 }
1975
1976
1977
1978
1979
1980
1981
1982 func mstartm0() {
1983
1984
1985
1986 if (iscgo || GOOS == "windows") && !cgoHasExtraM {
1987 cgoHasExtraM = true
1988 newextram()
1989 }
1990 initsig(false)
1991 }
1992
1993
1994
1995
1996 func mPark() {
1997 gp := getg()
1998
1999
2000 if goexperiment.RuntimeSecret {
2001 eraseSecretsSignalStk()
2002 }
2003 notesleep(&gp.m.park)
2004 noteclear(&gp.m.park)
2005 }
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017 func mexit(osStack bool) {
2018 mp := getg().m
2019
2020 if mp == &m0 {
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032 handoffp(releasep())
2033 lock(&sched.lock)
2034 sched.nmfreed++
2035 checkdead()
2036 unlock(&sched.lock)
2037 mPark()
2038 throw("locked m0 woke up")
2039 }
2040
2041 sigblock(true)
2042 unminit()
2043
2044
2045 if mp.gsignal != nil {
2046 stackfree(mp.gsignal.stack)
2047 if valgrindenabled {
2048 valgrindDeregisterStack(mp.gsignal)
2049 }
2050
2051
2052
2053
2054 mp.gsignal = nil
2055 }
2056
2057
2058 vgetrandomDestroy(mp)
2059
2060
2061
2062 mp.self.clear()
2063
2064
2065 lock(&sched.lock)
2066 for pprev := &allm; *pprev != nil; pprev = &(*pprev).alllink {
2067 if *pprev == mp {
2068 *pprev = mp.alllink
2069 goto found
2070 }
2071 }
2072 throw("m not found in allm")
2073 found:
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088 mp.freeWait.Store(freeMWait)
2089 mp.freelink = sched.freem
2090 sched.freem = mp
2091 unlock(&sched.lock)
2092
2093 atomic.Xadd64(&ncgocall, int64(mp.ncgocall))
2094 sched.totalRuntimeLockWaitTime.Add(mp.mLockProfile.waitTime.Load())
2095
2096
2097 handoffp(releasep())
2098
2099
2100
2101
2102
2103 lock(&sched.lock)
2104 sched.nmfreed++
2105 checkdead()
2106 unlock(&sched.lock)
2107
2108 if GOOS == "darwin" || GOOS == "ios" {
2109
2110
2111 if mp.signalPending.Load() != 0 {
2112 pendingPreemptSignals.Add(-1)
2113 }
2114 }
2115
2116
2117
2118 mdestroy(mp)
2119
2120 if osStack {
2121
2122 mp.freeWait.Store(freeMRef)
2123
2124
2125
2126 return
2127 }
2128
2129
2130
2131
2132
2133 exitThread(&mp.freeWait)
2134 }
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146 func forEachP(reason waitReason, fn func(*p)) {
2147 systemstack(func() {
2148 gp := getg().m.curg
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160 casGToWaitingForSuspendG(gp, _Grunning, reason)
2161 forEachPInternal(fn)
2162 casgstatus(gp, _Gwaiting, _Grunning)
2163 })
2164 }
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175 func forEachPInternal(fn func(*p)) {
2176 if atomic.Load(&worldsema) != 0 {
2177
2178 throw("worldsema not held")
2179 }
2180
2181 mp := acquirem()
2182 pp := getg().m.p.ptr()
2183
2184 lock(&sched.lock)
2185 if sched.safePointWait != 0 {
2186 throw("forEachP: sched.safePointWait != 0")
2187 }
2188 sched.safePointWait = gomaxprocs - 1
2189 sched.safePointFn = fn
2190
2191
2192 for _, p2 := range allp {
2193 if p2 != pp {
2194 atomic.Store(&p2.runSafePointFn, 1)
2195 }
2196 }
2197
2198
2199
2200
2201
2202
2203
2204 for p := sched.pidle.ptr(); p != nil; p = p.link.ptr() {
2205 if atomic.Cas(&p.runSafePointFn, 1, 0) {
2206 fn(p)
2207 sched.safePointWait--
2208 }
2209 }
2210
2211 wait := sched.safePointWait > 0
2212 unlock(&sched.lock)
2213
2214 if wait {
2215 preemptall()
2216 }
2217
2218
2219 fn(pp)
2220
2221
2222
2223 for _, p2 := range allp {
2224 if atomic.Load(&p2.runSafePointFn) != 1 {
2225
2226 continue
2227 }
2228 if thread, ok := setBlockOnExitSyscall(p2); ok {
2229 thread.takeP()
2230 thread.resume()
2231 handoffp(p2)
2232 }
2233 }
2234
2235
2236 if wait {
2237 for {
2238
2239
2240
2241
2242 if notetsleep(&sched.safePointNote, 100*1000) {
2243 noteclear(&sched.safePointNote)
2244 break
2245 }
2246 preemptall()
2247 }
2248 }
2249 if sched.safePointWait != 0 {
2250 throw("forEachP: not done")
2251 }
2252 for _, p2 := range allp {
2253 if p2.runSafePointFn != 0 {
2254 throw("forEachP: P did not run fn")
2255 }
2256 }
2257
2258 lock(&sched.lock)
2259 sched.safePointFn = nil
2260 unlock(&sched.lock)
2261 releasem(mp)
2262 }
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275 func runSafePointFn() {
2276 p := getg().m.p.ptr()
2277
2278
2279
2280 if !atomic.Cas(&p.runSafePointFn, 1, 0) {
2281 return
2282 }
2283 sched.safePointFn(p)
2284 lock(&sched.lock)
2285 sched.safePointWait--
2286 if sched.safePointWait == 0 {
2287 notewakeup(&sched.safePointNote)
2288 }
2289 unlock(&sched.lock)
2290 }
2291
2292
2293
2294
2295 type cgothreadstart struct {
2296 g guintptr
2297 tls *uint64
2298 fn unsafe.Pointer
2299 }
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310 func allocm(pp *p, fn func(), id int64) *m {
2311 allocmLock.rlock()
2312
2313
2314
2315
2316 acquirem()
2317
2318 gp := getg()
2319 if gp.m.p == 0 {
2320 acquirep(pp)
2321 }
2322
2323
2324
2325 if sched.freem != nil {
2326 lock(&sched.lock)
2327 var newList *m
2328 for freem := sched.freem; freem != nil; {
2329
2330 wait := freem.freeWait.Load()
2331 if wait == freeMWait {
2332 next := freem.freelink
2333 freem.freelink = newList
2334 newList = freem
2335 freem = next
2336 continue
2337 }
2338
2339
2340
2341 if traceEnabled() || traceShuttingDown() {
2342 traceThreadDestroy(freem)
2343 }
2344
2345
2346
2347 if wait == freeMStack {
2348
2349
2350
2351 systemstack(func() {
2352 stackfree(freem.g0.stack)
2353 if valgrindenabled {
2354 valgrindDeregisterStack(freem.g0)
2355 }
2356 })
2357 }
2358 freem = freem.freelink
2359 }
2360 sched.freem = newList
2361 unlock(&sched.lock)
2362 }
2363
2364 mp := &new(mPadded).m
2365 mp.mstartfn = fn
2366 mcommoninit(mp, id)
2367
2368
2369
2370 if iscgo || mStackIsSystemAllocated() {
2371 mp.g0 = malg(-1)
2372 } else {
2373 mp.g0 = malg(16384 * sys.StackGuardMultiplier)
2374 }
2375 mp.g0.m = mp
2376
2377 if pp == gp.m.p.ptr() {
2378 releasep()
2379 }
2380
2381 releasem(gp.m)
2382 allocmLock.runlock()
2383 return mp
2384 }
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425 func needm(signal bool) {
2426 if (iscgo || GOOS == "windows") && !cgoHasExtraM {
2427
2428
2429
2430
2431
2432
2433 writeErrStr("fatal error: cgo callback before cgo call\n")
2434 exit(1)
2435 }
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445 var sigmask sigset
2446 sigsave(&sigmask)
2447 sigblock(false)
2448
2449
2450
2451
2452 mp, last := getExtraM()
2453
2454
2455
2456
2457
2458
2459
2460
2461 mp.needextram = last
2462
2463
2464 mp.sigmask = sigmask
2465
2466
2467
2468 setg(mp.g0)
2469 sp := sys.GetCallerSP()
2470 callbackUpdateSystemStack(mp, sp, signal)
2471
2472
2473
2474
2475 mp.isExtraInC = false
2476
2477
2478 asminit()
2479 minit()
2480
2481
2482
2483
2484
2485
2486 var trace traceLocker
2487 if !signal {
2488 trace = traceAcquire()
2489 }
2490
2491
2492 casgstatus(mp.curg, _Gdeadextra, _Gsyscall)
2493 sched.ngsys.Add(-1)
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503 addGSyscallNoP(mp)
2504
2505 if !signal {
2506 if trace.ok() {
2507 trace.GoCreateSyscall(mp.curg)
2508 traceRelease(trace)
2509 }
2510 }
2511 mp.isExtraInSig = signal
2512 }
2513
2514
2515
2516
2517 func needAndBindM() {
2518 needm(false)
2519
2520 if _cgo_pthread_key_created != nil && *(*uintptr)(_cgo_pthread_key_created) != 0 {
2521 bindm()
2522 }
2523 }
2524
2525
2526
2527
2528 func newextram() {
2529 c := extraMWaiters.Swap(0)
2530 if c > 0 {
2531 for i := uint32(0); i < c; i++ {
2532 oneNewExtraM()
2533 }
2534 } else if extraMLength.Load() == 0 {
2535
2536 oneNewExtraM()
2537 }
2538 }
2539
2540
2541 func oneNewExtraM() {
2542
2543
2544
2545
2546
2547 mp := allocm(nil, nil, -1)
2548 gp := malg(4096)
2549 gp.sched.pc = abi.FuncPCABI0(goexit) + sys.PCQuantum
2550 gp.sched.sp = gp.stack.hi
2551 gp.sched.sp -= 4 * goarch.PtrSize
2552 gp.sched.lr = 0
2553 gp.sched.g = guintptr(unsafe.Pointer(gp))
2554 gp.syscallpc = gp.sched.pc
2555 gp.syscallsp = gp.sched.sp
2556 gp.stktopsp = gp.sched.sp
2557
2558
2559
2560 casgstatus(gp, _Gidle, _Gdeadextra)
2561 gp.m = mp
2562 mp.curg = gp
2563 mp.isextra = true
2564
2565 mp.isExtraInC = true
2566 mp.lockedInt++
2567 mp.lockedg.set(gp)
2568 gp.lockedm.set(mp)
2569 gp.goid = sched.goidgen.Add(1)
2570 if raceenabled {
2571 gp.racectx = racegostart(abi.FuncPCABIInternal(newextram) + sys.PCQuantum)
2572 }
2573
2574 allgadd(gp)
2575
2576
2577
2578
2579
2580 sched.ngsys.Add(1)
2581
2582
2583 addExtraM(mp)
2584 }
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619 func dropm() {
2620
2621
2622
2623 mp := getg().m
2624
2625
2626
2627
2628
2629 var trace traceLocker
2630 if !mp.isExtraInSig {
2631 trace = traceAcquire()
2632 }
2633
2634
2635 casgstatus(mp.curg, _Gsyscall, _Gdeadextra)
2636 mp.curg.preemptStop = false
2637 sched.ngsys.Add(1)
2638 decGSyscallNoP(mp)
2639
2640 if !mp.isExtraInSig {
2641 if trace.ok() {
2642 trace.GoDestroySyscall()
2643 traceRelease(trace)
2644 }
2645 }
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660 mp.syscalltick--
2661
2662
2663
2664 mp.curg.trace.reset()
2665
2666
2667
2668
2669 if traceEnabled() || traceShuttingDown() {
2670
2671
2672
2673
2674
2675
2676
2677 lock(&sched.lock)
2678 traceThreadDestroy(mp)
2679 unlock(&sched.lock)
2680 }
2681 mp.isExtraInSig = false
2682
2683
2684
2685
2686
2687 sigmask := mp.sigmask
2688 sigblock(false)
2689 unminit()
2690
2691 setg(nil)
2692
2693
2694
2695 g0 := mp.g0
2696 g0.stack.hi = 0
2697 g0.stack.lo = 0
2698 g0.stackguard0 = 0
2699 g0.stackguard1 = 0
2700 mp.g0StackAccurate = false
2701
2702 putExtraM(mp)
2703
2704 msigrestore(sigmask)
2705 }
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727 func bindm() {
2728 if GOOS == "windows" || GOOS == "plan9" {
2729 fatal("bindm in unexpected GOOS")
2730 }
2731 g := getg()
2732 if g.m.g0 != g {
2733 fatal("the current g is not g0")
2734 }
2735 if goexperiment.RuntimeCgoPurego && cgoBindM != nil {
2736 cgoBindM(uintptr(unsafe.Pointer(g)))
2737 } else if _cgo_bindm != nil {
2738 asmcgocall(_cgo_bindm, unsafe.Pointer(g))
2739 }
2740 }
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753 func getm() uintptr {
2754 return uintptr(unsafe.Pointer(getg().m))
2755 }
2756
2757 var (
2758
2759
2760
2761
2762
2763
2764 extraM atomic.Uintptr
2765
2766 extraMLength atomic.Uint32
2767
2768 extraMWaiters atomic.Uint32
2769
2770
2771 extraMInUse atomic.Uint32
2772 )
2773
2774
2775
2776
2777
2778
2779
2780
2781 func lockextra(nilokay bool) *m {
2782 const locked = 1
2783
2784 incr := false
2785 for {
2786 old := extraM.Load()
2787 if old == locked {
2788 osyield_no_g()
2789 continue
2790 }
2791 if old == 0 && !nilokay {
2792 if !incr {
2793
2794
2795
2796 extraMWaiters.Add(1)
2797 incr = true
2798 }
2799 usleep_no_g(1)
2800 continue
2801 }
2802 if extraM.CompareAndSwap(old, locked) {
2803 return (*m)(unsafe.Pointer(old))
2804 }
2805 osyield_no_g()
2806 continue
2807 }
2808 }
2809
2810
2811 func unlockextra(mp *m, delta int32) {
2812 extraMLength.Add(delta)
2813 extraM.Store(uintptr(unsafe.Pointer(mp)))
2814 }
2815
2816
2817
2818
2819
2820
2821
2822
2823 func getExtraM() (mp *m, last bool) {
2824 mp = lockextra(false)
2825 extraMInUse.Add(1)
2826 unlockextra(mp.schedlink.ptr(), -1)
2827 return mp, mp.schedlink.ptr() == nil
2828 }
2829
2830
2831
2832
2833
2834 func putExtraM(mp *m) {
2835 extraMInUse.Add(-1)
2836 addExtraM(mp)
2837 }
2838
2839
2840
2841
2842 func addExtraM(mp *m) {
2843 mnext := lockextra(true)
2844 mp.schedlink.set(mnext)
2845 unlockextra(mp, 1)
2846 }
2847
2848 var (
2849
2850
2851
2852 allocmLock rwmutex
2853
2854
2855
2856
2857 execLock rwmutex
2858 )
2859
2860
2861
2862 const (
2863 failthreadcreate = "runtime: failed to create new OS thread\n"
2864 failallocatestack = "runtime: failed to allocate stack for the new OS thread\n"
2865 )
2866
2867
2868
2869
2870 var newmHandoff struct {
2871 lock mutex
2872
2873
2874
2875 newm muintptr
2876
2877
2878
2879 waiting bool
2880 wake note
2881
2882
2883
2884
2885 haveTemplateThread uint32
2886 }
2887
2888
2889
2890
2891
2892
2893
2894
2895 func newm(fn func(), pp *p, id int64) {
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906 acquirem()
2907
2908 mp := allocm(pp, fn, id)
2909 mp.nextp.set(pp)
2910 mp.sigmask = initSigmask
2911 if gp := getg(); gp != nil && gp.m != nil && (gp.m.lockedExt != 0 || gp.m.incgo) && GOOS != "plan9" {
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923 lock(&newmHandoff.lock)
2924 if newmHandoff.haveTemplateThread == 0 {
2925 throw("on a locked thread with no template thread")
2926 }
2927 mp.schedlink = newmHandoff.newm
2928 newmHandoff.newm.set(mp)
2929 if newmHandoff.waiting {
2930 newmHandoff.waiting = false
2931 notewakeup(&newmHandoff.wake)
2932 }
2933 unlock(&newmHandoff.lock)
2934
2935
2936
2937 releasem(getg().m)
2938 return
2939 }
2940 newm1(mp)
2941 releasem(getg().m)
2942 }
2943
2944 func newm1(mp *m) {
2945 if iscgo {
2946 if goexperiment.RuntimeCgoPurego && cgoThreadStart != nil {
2947 execLock.rlock()
2948 systemstack(func() {
2949 if errno, msg := cgoThreadStart(mp.g0); errno != 0 {
2950 execLock.runlock()
2951 print("runtime/cgo: ", msg, ": errno=", errno, "\n")
2952 throw(msg)
2953 }
2954 })
2955 execLock.runlock()
2956 return
2957 }
2958 if _cgo_thread_start != nil {
2959 var ts cgothreadstart
2960 ts.g.set(mp.g0)
2961 ts.tls = (*uint64)(unsafe.Pointer(&mp.tls[0]))
2962 ts.fn = unsafe.Pointer(abi.FuncPCABI0(mstart))
2963 if msanenabled {
2964 msanwrite(unsafe.Pointer(&ts), unsafe.Sizeof(ts))
2965 }
2966 if asanenabled {
2967 asanwrite(unsafe.Pointer(&ts), unsafe.Sizeof(ts))
2968 }
2969 execLock.rlock()
2970 asmcgocall(_cgo_thread_start, unsafe.Pointer(&ts))
2971 execLock.runlock()
2972 return
2973 }
2974 }
2975 execLock.rlock()
2976 newosproc(mp)
2977 execLock.runlock()
2978 }
2979
2980
2981
2982
2983
2984 func startTemplateThread() {
2985 if GOARCH == "wasm" || GOARCH == "wasm32" {
2986 return
2987 }
2988
2989
2990
2991 mp := acquirem()
2992 if !atomic.Cas(&newmHandoff.haveTemplateThread, 0, 1) {
2993 releasem(mp)
2994 return
2995 }
2996 newm(templateThread, nil, -1)
2997 releasem(mp)
2998 }
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012 func templateThread() {
3013 lock(&sched.lock)
3014 sched.nmsys++
3015 checkdead()
3016 unlock(&sched.lock)
3017
3018 for {
3019 lock(&newmHandoff.lock)
3020 for newmHandoff.newm != 0 {
3021 newm := newmHandoff.newm.ptr()
3022 newmHandoff.newm = 0
3023 unlock(&newmHandoff.lock)
3024 for newm != nil {
3025 next := newm.schedlink.ptr()
3026 newm.schedlink = 0
3027 newm1(newm)
3028 newm = next
3029 }
3030 lock(&newmHandoff.lock)
3031 }
3032 newmHandoff.waiting = true
3033 noteclear(&newmHandoff.wake)
3034 unlock(&newmHandoff.lock)
3035 notesleep(&newmHandoff.wake)
3036 }
3037 }
3038
3039
3040
3041 func stopm() {
3042 gp := getg()
3043
3044 if gp.m.locks != 0 {
3045 throw("stopm holding locks")
3046 }
3047 if gp.m.p != 0 {
3048 throw("stopm holding p")
3049 }
3050 if gp.m.spinning {
3051 throw("stopm spinning")
3052 }
3053
3054 lock(&sched.lock)
3055 mput(gp.m)
3056 unlock(&sched.lock)
3057 mPark()
3058 acquirep(gp.m.nextp.ptr())
3059 gp.m.nextp = 0
3060 }
3061
3062 func mspinning() {
3063
3064 getg().m.spinning = true
3065 }
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084 func startm(pp *p, spinning, lockheld bool) {
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101 mp := acquirem()
3102 if !lockheld {
3103 lock(&sched.lock)
3104 }
3105 if pp == nil {
3106 if spinning {
3107
3108
3109
3110 throw("startm: P required for spinning=true")
3111 }
3112 pp, _ = pidleget(0)
3113 if pp == nil {
3114 if !lockheld {
3115 unlock(&sched.lock)
3116 }
3117 releasem(mp)
3118 return
3119 }
3120 }
3121 nmp := mget()
3122 if nmp == nil {
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137 id := mReserveID()
3138 unlock(&sched.lock)
3139
3140 var fn func()
3141 if spinning {
3142
3143 fn = mspinning
3144 }
3145 newm(fn, pp, id)
3146
3147 if lockheld {
3148 lock(&sched.lock)
3149 }
3150
3151
3152 releasem(mp)
3153 return
3154 }
3155 if !lockheld {
3156 unlock(&sched.lock)
3157 }
3158 if nmp.spinning {
3159 throw("startm: m is spinning")
3160 }
3161 if nmp.nextp != 0 {
3162 throw("startm: m has p")
3163 }
3164 if spinning && !runqempty(pp) {
3165 throw("startm: p has runnable gs")
3166 }
3167
3168 nmp.spinning = spinning
3169 nmp.nextp.set(pp)
3170 notewakeup(&nmp.park)
3171
3172
3173 releasem(mp)
3174 }
3175
3176
3177
3178
3179
3180 func handoffp(pp *p) {
3181
3182
3183
3184
3185 if !runqempty(pp) || !sched.runq.empty() {
3186 startm(pp, false, false)
3187 return
3188 }
3189
3190 if (traceEnabled() || traceShuttingDown()) && traceReaderAvailable() != nil {
3191 startm(pp, false, false)
3192 return
3193 }
3194
3195 if gcBlackenEnabled != 0 && gcShouldScheduleWorker(pp) {
3196 startm(pp, false, false)
3197 return
3198 }
3199
3200
3201 if sched.nmspinning.Load()+sched.npidle.Load() == 0 && sched.nmspinning.CompareAndSwap(0, 1) {
3202 sched.needspinning.Store(0)
3203 startm(pp, true, false)
3204 return
3205 }
3206 lock(&sched.lock)
3207 if sched.gcwaiting.Load() {
3208 pp.status = _Pgcstop
3209 pp.gcStopTime = nanotime()
3210 sched.stopwait--
3211 if sched.stopwait == 0 {
3212 notewakeup(&sched.stopnote)
3213 }
3214 unlock(&sched.lock)
3215 return
3216 }
3217 if pp.runSafePointFn != 0 && atomic.Cas(&pp.runSafePointFn, 1, 0) {
3218 sched.safePointFn(pp)
3219 sched.safePointWait--
3220 if sched.safePointWait == 0 {
3221 notewakeup(&sched.safePointNote)
3222 }
3223 }
3224 if !sched.runq.empty() {
3225 unlock(&sched.lock)
3226 startm(pp, false, false)
3227 return
3228 }
3229
3230
3231 if sched.npidle.Load() == gomaxprocs-1 && sched.lastpoll.Load() != 0 {
3232 unlock(&sched.lock)
3233 startm(pp, false, false)
3234 return
3235 }
3236
3237
3238
3239 when := pp.timers.wakeTime()
3240 pidleput(pp, 0)
3241 unlock(&sched.lock)
3242
3243 if when != 0 {
3244 wakeNetPoller(when)
3245 }
3246 }
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261 func wakep() {
3262
3263
3264 if sched.nmspinning.Load() != 0 || !sched.nmspinning.CompareAndSwap(0, 1) {
3265 return
3266 }
3267
3268
3269
3270
3271
3272
3273 mp := acquirem()
3274
3275 var pp *p
3276 lock(&sched.lock)
3277 pp, _ = pidlegetSpinning(0)
3278 if pp == nil {
3279 if sched.nmspinning.Add(-1) < 0 {
3280 throw("wakep: negative nmspinning")
3281 }
3282 unlock(&sched.lock)
3283 releasem(mp)
3284 return
3285 }
3286
3287
3288
3289
3290 unlock(&sched.lock)
3291
3292 startm(pp, true, false)
3293
3294 releasem(mp)
3295 }
3296
3297
3298
3299 func stoplockedm() {
3300 gp := getg()
3301
3302 if gp.m.lockedg == 0 || gp.m.lockedg.ptr().lockedm.ptr() != gp.m {
3303 throw("stoplockedm: inconsistent locking")
3304 }
3305 if gp.m.p != 0 {
3306
3307 pp := releasep()
3308 handoffp(pp)
3309 }
3310 incidlelocked(1)
3311
3312 mPark()
3313 status := readgstatus(gp.m.lockedg.ptr())
3314 if status&^_Gscan != _Grunnable {
3315 print("runtime:stoplockedm: lockedg (atomicstatus=", status, ") is not Grunnable or Gscanrunnable\n")
3316 dumpgstatus(gp.m.lockedg.ptr())
3317 throw("stoplockedm: not runnable")
3318 }
3319 acquirep(gp.m.nextp.ptr())
3320 gp.m.nextp = 0
3321 }
3322
3323
3324
3325
3326
3327 func startlockedm(gp *g) {
3328 mp := gp.lockedm.ptr()
3329 if mp == getg().m {
3330 throw("startlockedm: locked to me")
3331 }
3332 if mp.nextp != 0 {
3333 throw("startlockedm: m has p")
3334 }
3335
3336 incidlelocked(-1)
3337 pp := releasep()
3338 mp.nextp.set(pp)
3339 notewakeup(&mp.park)
3340 stopm()
3341 }
3342
3343
3344
3345 func gcstopm() {
3346 gp := getg()
3347
3348 if !sched.gcwaiting.Load() {
3349 throw("gcstopm: not waiting for gc")
3350 }
3351 if gp.m.spinning {
3352 gp.m.spinning = false
3353
3354
3355 if sched.nmspinning.Add(-1) < 0 {
3356 throw("gcstopm: negative nmspinning")
3357 }
3358 }
3359 pp := releasep()
3360 lock(&sched.lock)
3361 pp.status = _Pgcstop
3362 pp.gcStopTime = nanotime()
3363 sched.stopwait--
3364 if sched.stopwait == 0 {
3365 notewakeup(&sched.stopnote)
3366 }
3367 unlock(&sched.lock)
3368 stopm()
3369 }
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380 func execute(gp *g, inheritTime bool) {
3381 mp := getg().m
3382
3383 if goroutineProfile.active {
3384
3385
3386
3387 tryRecordGoroutineProfile(gp, nil, osyield)
3388 }
3389
3390
3391 mp.curg = gp
3392 gp.m = mp
3393 gp.syncSafePoint = false
3394 casgstatus(gp, _Grunnable, _Grunning)
3395 gp.waitsince = 0
3396 gp.preempt = false
3397 gp.stackguard0 = gp.stack.lo + stackGuard
3398 if !inheritTime {
3399 mp.p.ptr().schedtick++
3400 }
3401
3402 if sys.DITSupported && debug.dataindependenttiming != 1 {
3403 if gp.ditWanted && !mp.ditEnabled {
3404
3405
3406 sys.EnableDIT()
3407 mp.ditEnabled = true
3408 } else if !gp.ditWanted && mp.ditEnabled {
3409
3410
3411
3412
3413
3414 sys.DisableDIT()
3415 mp.ditEnabled = false
3416 }
3417 }
3418
3419
3420 hz := sched.profilehz
3421 if mp.profilehz != hz {
3422 setThreadCPUProfiler(hz)
3423 }
3424
3425 trace := traceAcquire()
3426 if trace.ok() {
3427 trace.GoStart()
3428 traceRelease(trace)
3429 }
3430
3431
3432
3433
3434
3435
3436
3437 if mp.p.ptr().runSafePointFn != 0 {
3438 runSafePointFn()
3439 }
3440
3441 gogo(&gp.sched)
3442 }
3443
3444
3445
3446
3447
3448 func findRunnable() (gp *g, inheritTime, tryWakeP bool) {
3449 mp := getg().m
3450
3451
3452
3453
3454
3455 top:
3456
3457
3458
3459 mp.clearAllpSnapshot()
3460
3461 pp := mp.p.ptr()
3462 if sched.gcwaiting.Load() {
3463 gcstopm()
3464 goto top
3465 }
3466 if pp.runSafePointFn != 0 {
3467 runSafePointFn()
3468 }
3469
3470
3471
3472
3473
3474 now, pollUntil, _ := pp.timers.check(0, nil)
3475
3476
3477 if traceEnabled() || traceShuttingDown() {
3478 gp := traceReader()
3479 if gp != nil {
3480 trace := traceAcquire()
3481 casgstatus(gp, _Gwaiting, _Grunnable)
3482 if trace.ok() {
3483 trace.GoUnpark(gp, 0)
3484 traceRelease(trace)
3485 }
3486 return gp, false, true
3487 }
3488 }
3489
3490
3491 if gcBlackenEnabled != 0 {
3492 gp, tnow := gcController.findRunnableGCWorker(pp, now)
3493 if gp != nil {
3494 return gp, false, true
3495 }
3496 now = tnow
3497 }
3498
3499
3500
3501
3502 if pp.schedtick%61 == 0 && !sched.runq.empty() {
3503 lock(&sched.lock)
3504 gp := globrunqget()
3505 unlock(&sched.lock)
3506 if gp != nil {
3507 return gp, false, false
3508 }
3509 }
3510
3511
3512 if fingStatus.Load()&(fingWait|fingWake) == fingWait|fingWake {
3513 if gp := wakefing(); gp != nil {
3514 ready(gp, 0, true)
3515 }
3516 }
3517
3518
3519 if gcCleanups.needsWake() {
3520 gcCleanups.wake()
3521 }
3522
3523 if *cgo_yield != nil {
3524 asmcgocall(*cgo_yield, nil)
3525 }
3526
3527
3528 if gp, inheritTime := runqget(pp); gp != nil {
3529 return gp, inheritTime, false
3530 }
3531
3532
3533 if !sched.runq.empty() {
3534 lock(&sched.lock)
3535 gp, q := globrunqgetbatch(int32(len(pp.runq)) / 2)
3536 unlock(&sched.lock)
3537 if gp != nil {
3538 if runqputbatch(pp, &q); !q.empty() {
3539 throw("Couldn't put Gs into empty local runq")
3540 }
3541 return gp, false, false
3542 }
3543 }
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554 if netpollinited() && netpollAnyWaiters() && sched.lastpoll.Load() != 0 && sched.pollingNet.Swap(1) == 0 {
3555 list, delta := netpoll(0)
3556 sched.pollingNet.Store(0)
3557 if !list.empty() {
3558 gp := list.pop()
3559 injectglist(&list)
3560 netpollAdjustWaiters(delta)
3561 trace := traceAcquire()
3562 casgstatus(gp, _Gwaiting, _Grunnable)
3563 if trace.ok() {
3564 trace.GoUnpark(gp, 0)
3565 traceRelease(trace)
3566 }
3567 return gp, false, false
3568 }
3569 }
3570
3571
3572
3573
3574
3575
3576 if mp.spinning || 2*sched.nmspinning.Load() < gomaxprocs-sched.npidle.Load() {
3577 if !mp.spinning {
3578 mp.becomeSpinning()
3579 }
3580
3581 gp, inheritTime, tnow, w, newWork := stealWork(now)
3582 if gp != nil {
3583
3584 return gp, inheritTime, false
3585 }
3586 if newWork {
3587
3588
3589 goto top
3590 }
3591
3592 now = tnow
3593 if w != 0 && (pollUntil == 0 || w < pollUntil) {
3594
3595 pollUntil = w
3596 }
3597 }
3598
3599
3600
3601
3602
3603 if gcBlackenEnabled != 0 && gcShouldScheduleWorker(pp) && gcController.addIdleMarkWorker() {
3604 node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
3605 if node != nil {
3606 pp.gcMarkWorkerMode = gcMarkWorkerIdleMode
3607 gp := node.gp.ptr()
3608
3609 trace := traceAcquire()
3610 casgstatus(gp, _Gwaiting, _Grunnable)
3611 if trace.ok() {
3612 trace.GoUnpark(gp, 0)
3613 traceRelease(trace)
3614 }
3615 return gp, false, false
3616 }
3617 gcController.removeIdleMarkWorker()
3618 }
3619
3620
3621
3622
3623
3624 gp, otherReady := beforeIdle(now, pollUntil)
3625 if gp != nil {
3626 trace := traceAcquire()
3627 casgstatus(gp, _Gwaiting, _Grunnable)
3628 if trace.ok() {
3629 trace.GoUnpark(gp, 0)
3630 traceRelease(trace)
3631 }
3632 return gp, false, false
3633 }
3634 if otherReady {
3635 goto top
3636 }
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646 allpSnapshot := mp.snapshotAllp()
3647
3648
3649 idlepMaskSnapshot := idlepMask
3650 timerpMaskSnapshot := timerpMask
3651
3652
3653 lock(&sched.lock)
3654 if sched.gcwaiting.Load() || pp.runSafePointFn != 0 {
3655 unlock(&sched.lock)
3656 goto top
3657 }
3658 if !sched.runq.empty() {
3659 gp, q := globrunqgetbatch(int32(len(pp.runq)) / 2)
3660 unlock(&sched.lock)
3661 if gp == nil {
3662 throw("global runq empty with non-zero runqsize")
3663 }
3664 if runqputbatch(pp, &q); !q.empty() {
3665 throw("Couldn't put Gs into empty local runq")
3666 }
3667 return gp, false, false
3668 }
3669 if !mp.spinning && sched.needspinning.Load() == 1 {
3670
3671 mp.becomeSpinning()
3672 unlock(&sched.lock)
3673 goto top
3674 }
3675 if releasep() != pp {
3676 throw("findRunnable: wrong p")
3677 }
3678 now = pidleput(pp, now)
3679 unlock(&sched.lock)
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717 wasSpinning := mp.spinning
3718 if mp.spinning {
3719 mp.spinning = false
3720 if sched.nmspinning.Add(-1) < 0 {
3721 throw("findRunnable: negative nmspinning")
3722 }
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735 lock(&sched.lock)
3736 if !sched.runq.empty() {
3737 pp, _ := pidlegetSpinning(0)
3738 if pp != nil {
3739 gp, q := globrunqgetbatch(int32(len(pp.runq)) / 2)
3740 unlock(&sched.lock)
3741 if gp == nil {
3742 throw("global runq empty with non-zero runqsize")
3743 }
3744 if runqputbatch(pp, &q); !q.empty() {
3745 throw("Couldn't put Gs into empty local runq")
3746 }
3747 acquirep(pp)
3748 mp.becomeSpinning()
3749 return gp, false, false
3750 }
3751 }
3752 unlock(&sched.lock)
3753
3754 pp := checkRunqsNoP(allpSnapshot, idlepMaskSnapshot)
3755 if pp != nil {
3756 acquirep(pp)
3757 mp.becomeSpinning()
3758 goto top
3759 }
3760
3761
3762 pp, gp := checkIdleGCNoP()
3763 if pp != nil {
3764 acquirep(pp)
3765 mp.becomeSpinning()
3766
3767
3768 pp.gcMarkWorkerMode = gcMarkWorkerIdleMode
3769 trace := traceAcquire()
3770 casgstatus(gp, _Gwaiting, _Grunnable)
3771 if trace.ok() {
3772 trace.GoUnpark(gp, 0)
3773 traceRelease(trace)
3774 }
3775 return gp, false, false
3776 }
3777
3778
3779
3780
3781
3782
3783
3784 pollUntil = checkTimersNoP(allpSnapshot, timerpMaskSnapshot, pollUntil)
3785 }
3786
3787
3788
3789
3790
3791 if netpollinited() && (netpollAnyWaiters() || pollUntil != 0) && sched.lastpoll.Swap(0) != 0 {
3792 sched.pollUntil.Store(pollUntil)
3793 if mp.p != 0 {
3794 throw("findRunnable: netpoll with p")
3795 }
3796 if mp.spinning {
3797 throw("findRunnable: netpoll with spinning")
3798 }
3799 delay := int64(-1)
3800 if pollUntil != 0 {
3801 if now == 0 {
3802 now = nanotime()
3803 }
3804 delay = pollUntil - now
3805 if delay < 0 {
3806 delay = 0
3807 }
3808 }
3809 if faketime != 0 {
3810
3811 delay = 0
3812 }
3813 list, delta := netpoll(delay)
3814
3815 now = nanotime()
3816 sched.pollUntil.Store(0)
3817 sched.lastpoll.Store(now)
3818 if faketime != 0 && list.empty() {
3819
3820
3821 stopm()
3822 goto top
3823 }
3824 lock(&sched.lock)
3825 pp, _ := pidleget(now)
3826 unlock(&sched.lock)
3827 if pp == nil {
3828 injectglist(&list)
3829 netpollAdjustWaiters(delta)
3830 } else {
3831 acquirep(pp)
3832 if !list.empty() {
3833 gp := list.pop()
3834 injectglist(&list)
3835 netpollAdjustWaiters(delta)
3836 trace := traceAcquire()
3837 casgstatus(gp, _Gwaiting, _Grunnable)
3838 if trace.ok() {
3839 trace.GoUnpark(gp, 0)
3840 traceRelease(trace)
3841 }
3842 return gp, false, false
3843 }
3844 if wasSpinning {
3845 mp.becomeSpinning()
3846 }
3847 goto top
3848 }
3849 } else if pollUntil != 0 && netpollinited() {
3850 pollerPollUntil := sched.pollUntil.Load()
3851 if pollerPollUntil == 0 || pollerPollUntil > pollUntil {
3852 netpollBreak()
3853 }
3854 }
3855 stopm()
3856 goto top
3857 }
3858
3859
3860
3861
3862
3863 func pollWork() bool {
3864 if !sched.runq.empty() {
3865 return true
3866 }
3867 p := getg().m.p.ptr()
3868 if !runqempty(p) {
3869 return true
3870 }
3871 if netpollinited() && netpollAnyWaiters() && sched.lastpoll.Load() != 0 {
3872 if list, delta := netpoll(0); !list.empty() {
3873 injectglist(&list)
3874 netpollAdjustWaiters(delta)
3875 return true
3876 }
3877 }
3878 return false
3879 }
3880
3881
3882
3883
3884
3885
3886
3887 func stealWork(now int64) (gp *g, inheritTime bool, rnow, pollUntil int64, newWork bool) {
3888 pp := getg().m.p.ptr()
3889
3890 ranTimer := false
3891
3892 const stealTries = 4
3893 for i := 0; i < stealTries; i++ {
3894 stealTimersOrRunNextG := i == stealTries-1
3895
3896 for enum := stealOrder.start(cheaprand()); !enum.done(); enum.next() {
3897 p2 := allp[enum.position()]
3898 if pp == p2 {
3899 continue
3900 }
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915 if stealTimersOrRunNextG && timerpMask.read(enum.position()) {
3916 tnow, w, ran := p2.timers.check(now, nil)
3917 now = tnow
3918 if w != 0 && (pollUntil == 0 || w < pollUntil) {
3919 pollUntil = w
3920 }
3921 if ran {
3922
3923
3924
3925
3926
3927
3928
3929
3930 if gp, inheritTime := runqget(pp); gp != nil {
3931 return gp, inheritTime, now, pollUntil, ranTimer
3932 }
3933 ranTimer = true
3934 }
3935 }
3936
3937
3938 if !idlepMask.read(enum.position()) {
3939 if gp := runqsteal(pp, p2, stealTimersOrRunNextG); gp != nil {
3940 return gp, false, now, pollUntil, ranTimer
3941 }
3942 }
3943
3944 if sched.gcwaiting.Load() {
3945
3946
3947 return nil, false, now, pollUntil, true
3948 }
3949 }
3950 }
3951
3952
3953
3954
3955 return nil, false, now, pollUntil, ranTimer
3956 }
3957
3958
3959
3960
3961
3962
3963 func checkRunqsNoP(allpSnapshot []*p, idlepMaskSnapshot pMask) *p {
3964 for id, p2 := range allpSnapshot {
3965 if !idlepMaskSnapshot.read(uint32(id)) && !runqempty(p2) {
3966 lock(&sched.lock)
3967 pp, _ := pidlegetSpinning(0)
3968 if pp == nil {
3969
3970 unlock(&sched.lock)
3971 return nil
3972 }
3973 unlock(&sched.lock)
3974 return pp
3975 }
3976 }
3977
3978
3979 return nil
3980 }
3981
3982
3983
3984
3985 func checkTimersNoP(allpSnapshot []*p, timerpMaskSnapshot pMask, pollUntil int64) int64 {
3986 for id, p2 := range allpSnapshot {
3987 if timerpMaskSnapshot.read(uint32(id)) {
3988 w := p2.timers.wakeTime()
3989 if w != 0 && (pollUntil == 0 || w < pollUntil) {
3990 pollUntil = w
3991 }
3992 }
3993 }
3994
3995 return pollUntil
3996 }
3997
3998
3999
4000
4001
4002 func checkIdleGCNoP() (*p, *g) {
4003
4004
4005
4006
4007
4008
4009 if atomic.Load(&gcBlackenEnabled) == 0 || !gcController.needIdleMarkWorker() {
4010 return nil, nil
4011 }
4012 if !gcShouldScheduleWorker(nil) {
4013 return nil, nil
4014 }
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033 lock(&sched.lock)
4034 pp, now := pidlegetSpinning(0)
4035 if pp == nil {
4036 unlock(&sched.lock)
4037 return nil, nil
4038 }
4039
4040
4041 if gcBlackenEnabled == 0 || !gcController.addIdleMarkWorker() {
4042 pidleput(pp, now)
4043 unlock(&sched.lock)
4044 return nil, nil
4045 }
4046
4047 node := (*gcBgMarkWorkerNode)(gcBgMarkWorkerPool.pop())
4048 if node == nil {
4049 pidleput(pp, now)
4050 unlock(&sched.lock)
4051 gcController.removeIdleMarkWorker()
4052 return nil, nil
4053 }
4054
4055 unlock(&sched.lock)
4056
4057 return pp, node.gp.ptr()
4058 }
4059
4060
4061
4062
4063 func wakeNetPoller(when int64) {
4064 if sched.lastpoll.Load() == 0 {
4065
4066
4067
4068
4069 pollerPollUntil := sched.pollUntil.Load()
4070 if pollerPollUntil == 0 || pollerPollUntil > when {
4071 netpollBreak()
4072 }
4073 } else {
4074
4075
4076 if GOOS != "plan9" {
4077 wakep()
4078 }
4079 }
4080 }
4081
4082 func resetspinning() {
4083 gp := getg()
4084 if !gp.m.spinning {
4085 throw("resetspinning: not a spinning m")
4086 }
4087 gp.m.spinning = false
4088 nmspinning := sched.nmspinning.Add(-1)
4089 if nmspinning < 0 {
4090 throw("findRunnable: negative nmspinning")
4091 }
4092
4093
4094
4095 wakep()
4096 }
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106 func injectglist(glist *gList) {
4107 if glist.empty() {
4108 return
4109 }
4110
4111
4112
4113 var tail *g
4114 trace := traceAcquire()
4115 for gp := glist.head.ptr(); gp != nil; gp = gp.schedlink.ptr() {
4116 tail = gp
4117 casgstatus(gp, _Gwaiting, _Grunnable)
4118 if trace.ok() {
4119 trace.GoUnpark(gp, 0)
4120 }
4121 }
4122 if trace.ok() {
4123 traceRelease(trace)
4124 }
4125
4126
4127 q := gQueue{glist.head, tail.guintptr(), glist.size}
4128 *glist = gList{}
4129
4130 startIdle := func(n int32) {
4131 for ; n > 0; n-- {
4132 mp := acquirem()
4133 lock(&sched.lock)
4134
4135 pp, _ := pidlegetSpinning(0)
4136 if pp == nil {
4137 unlock(&sched.lock)
4138 releasem(mp)
4139 break
4140 }
4141
4142 startm(pp, false, true)
4143 unlock(&sched.lock)
4144 releasem(mp)
4145 }
4146 }
4147
4148 pp := getg().m.p.ptr()
4149 if pp == nil {
4150 n := q.size
4151 lock(&sched.lock)
4152 globrunqputbatch(&q)
4153 unlock(&sched.lock)
4154 startIdle(n)
4155 return
4156 }
4157
4158 var globq gQueue
4159 npidle := sched.npidle.Load()
4160 for ; npidle > 0 && !q.empty(); npidle-- {
4161 g := q.pop()
4162 globq.pushBack(g)
4163 }
4164 if !globq.empty() {
4165 n := globq.size
4166 lock(&sched.lock)
4167 globrunqputbatch(&globq)
4168 unlock(&sched.lock)
4169 startIdle(n)
4170 }
4171
4172 if runqputbatch(pp, &q); !q.empty() {
4173 lock(&sched.lock)
4174 globrunqputbatch(&q)
4175 unlock(&sched.lock)
4176 }
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191 wakep()
4192 }
4193
4194
4195
4196 func schedule() {
4197 mp := getg().m
4198
4199 if mp.locks != 0 {
4200 throw("schedule: holding locks")
4201 }
4202
4203 if mp.lockedg != 0 {
4204 stoplockedm()
4205 execute(mp.lockedg.ptr(), false)
4206 }
4207
4208
4209
4210 if mp.incgo {
4211 throw("schedule: in cgo")
4212 }
4213
4214 top:
4215 pp := mp.p.ptr()
4216 pp.preempt = false
4217
4218
4219
4220
4221 if mp.spinning && (pp.runnext != 0 || pp.runqhead != pp.runqtail) {
4222 throw("schedule: spinning with local work")
4223 }
4224
4225 gp, inheritTime, tryWakeP := findRunnable()
4226
4227
4228 pp = mp.p.ptr()
4229
4230
4231
4232
4233 mp.clearAllpSnapshot()
4234
4235
4236
4237
4238
4239
4240
4241
4242 gcController.releaseNextGCMarkWorker(pp)
4243
4244 if debug.dontfreezetheworld > 0 && freezing.Load() {
4245
4246
4247
4248
4249
4250
4251
4252 lock(&deadlock)
4253 lock(&deadlock)
4254 }
4255
4256
4257
4258
4259 if mp.spinning {
4260 resetspinning()
4261 }
4262
4263 if sched.disable.user && !schedEnabled(gp) {
4264
4265
4266
4267 lock(&sched.lock)
4268 if schedEnabled(gp) {
4269
4270
4271 unlock(&sched.lock)
4272 } else {
4273 sched.disable.runnable.pushBack(gp)
4274 unlock(&sched.lock)
4275 goto top
4276 }
4277 }
4278
4279
4280
4281 if tryWakeP {
4282 wakep()
4283 }
4284 if gp.lockedm != 0 {
4285
4286
4287 startlockedm(gp)
4288 goto top
4289 }
4290
4291 execute(gp, inheritTime)
4292 }
4293
4294
4295
4296
4297
4298
4299
4300
4301 func dropg() {
4302 gp := getg()
4303
4304 setMNoWB(&gp.m.curg.m, nil)
4305 setGNoWB(&gp.m.curg, nil)
4306 }
4307
4308 func parkunlock_c(gp *g, lock unsafe.Pointer) bool {
4309 unlock((*mutex)(lock))
4310 return true
4311 }
4312
4313
4314 func park_m(gp *g) {
4315 mp := getg().m
4316
4317 trace := traceAcquire()
4318
4319
4320
4321
4322
4323 bubble := gp.bubble
4324 if bubble != nil {
4325 bubble.incActive()
4326 }
4327
4328 if trace.ok() {
4329
4330
4331
4332 trace.GoPark(mp.waitTraceBlockReason, mp.waitTraceSkip)
4333 }
4334
4335
4336 casgstatus(gp, _Grunning, _Gwaiting)
4337 if trace.ok() {
4338 traceRelease(trace)
4339 }
4340
4341 dropg()
4342
4343 if fn := mp.waitunlockf; fn != nil {
4344 ok := fn(gp, mp.waitlock)
4345 mp.waitunlockf = nil
4346 mp.waitlock = nil
4347 if !ok {
4348 trace := traceAcquire()
4349 casgstatus(gp, _Gwaiting, _Grunnable)
4350 if bubble != nil {
4351 bubble.decActive()
4352 }
4353 if trace.ok() {
4354 trace.GoUnpark(gp, 2)
4355 traceRelease(trace)
4356 }
4357 execute(gp, true)
4358 }
4359 }
4360
4361 if bubble != nil {
4362 bubble.decActive()
4363 }
4364
4365 schedule()
4366 }
4367
4368 func goschedImpl(gp *g, preempted bool) {
4369 pp := gp.m.p.ptr()
4370 trace := traceAcquire()
4371 status := readgstatus(gp)
4372 if status&^_Gscan != _Grunning {
4373 dumpgstatus(gp)
4374 throw("bad g status")
4375 }
4376 if trace.ok() {
4377
4378
4379
4380 if preempted {
4381 trace.GoPreempt()
4382 } else {
4383 trace.GoSched()
4384 }
4385 }
4386 casgstatus(gp, _Grunning, _Grunnable)
4387 if trace.ok() {
4388 traceRelease(trace)
4389 }
4390
4391 dropg()
4392 if preempted && sched.gcwaiting.Load() {
4393
4394
4395 runqput(pp, gp, true)
4396 } else {
4397 lock(&sched.lock)
4398 globrunqput(gp)
4399 unlock(&sched.lock)
4400 }
4401
4402 if mainStarted {
4403 wakep()
4404 }
4405
4406 schedule()
4407 }
4408
4409
4410 func gosched_m(gp *g) {
4411 goschedImpl(gp, false)
4412 }
4413
4414
4415 func goschedguarded_m(gp *g) {
4416 if !canPreemptM(gp.m) {
4417 gogo(&gp.sched)
4418 }
4419 goschedImpl(gp, false)
4420 }
4421
4422 func gopreempt_m(gp *g) {
4423 goschedImpl(gp, true)
4424 }
4425
4426
4427
4428
4429 func preemptPark(gp *g) {
4430 status := readgstatus(gp)
4431 if status&^_Gscan != _Grunning {
4432 dumpgstatus(gp)
4433 throw("bad g status")
4434 }
4435
4436 if gp.asyncSafePoint {
4437
4438
4439
4440 f := findfunc(gp.sched.pc)
4441 if !f.valid() {
4442 throw("preempt at unknown pc")
4443 }
4444 if f.flag&abi.FuncFlagSPWrite != 0 {
4445 println("runtime: unexpected SPWRITE function", funcname(f), "in async preempt")
4446 throw("preempt SPWRITE")
4447 }
4448 }
4449
4450
4451
4452
4453
4454
4455
4456 casGToPreemptScan(gp, _Grunning, _Gscan|_Gpreempted)
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478 trace := traceAcquire()
4479 if trace.ok() {
4480 trace.GoPark(traceBlockPreempted, 0)
4481 }
4482
4483
4484
4485
4486 dropg()
4487
4488
4489 casfrom_Gscanstatus(gp, _Gscan|_Gpreempted, _Gpreempted)
4490 if trace.ok() {
4491 traceRelease(trace)
4492 }
4493
4494
4495 schedule()
4496 }
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512 func goyield() {
4513 checkTimeouts()
4514 mcall(goyield_m)
4515 }
4516
4517 func goyield_m(gp *g) {
4518 trace := traceAcquire()
4519 pp := gp.m.p.ptr()
4520 if trace.ok() {
4521
4522
4523
4524 trace.GoPreempt()
4525 }
4526 casgstatus(gp, _Grunning, _Grunnable)
4527 if trace.ok() {
4528 traceRelease(trace)
4529 }
4530 dropg()
4531 runqput(pp, gp, false)
4532 schedule()
4533 }
4534
4535
4536 func goexit1() {
4537 if raceenabled {
4538 if gp := getg(); gp.bubble != nil {
4539 racereleasemergeg(gp, gp.bubble.raceaddr())
4540 }
4541 racegoend()
4542 }
4543 trace := traceAcquire()
4544 if trace.ok() {
4545 trace.GoEnd()
4546 traceRelease(trace)
4547 }
4548 mcall(goexit0)
4549 }
4550
4551
4552 func goexit0(gp *g) {
4553 if goexperiment.RuntimeSecret && gp.secret > 0 {
4554
4555
4556 memclrNoHeapPointers(unsafe.Pointer(gp.stack.lo), gp.stack.hi-gp.stack.lo)
4557
4558
4559 }
4560 gdestroy(gp)
4561 schedule()
4562 }
4563
4564 func gdestroy(gp *g) {
4565 mp := getg().m
4566 pp := mp.p.ptr()
4567
4568 casgstatus(gp, _Grunning, _Gdead)
4569 gcController.addScannableStack(pp, -int64(gp.stack.hi-gp.stack.lo))
4570 if isSystemGoroutine(gp, false) {
4571 sched.ngsys.Add(-1)
4572 }
4573 gp.m = nil
4574 locked := gp.lockedm != 0
4575 gp.lockedm = 0
4576 mp.lockedg = 0
4577 gp.preemptStop = false
4578 gp.paniconfault = false
4579 gp._defer = nil
4580 gp._panic = nil
4581 gp.waitreason = waitReasonZero
4582 gp.param = nil
4583 gp.labels = nil
4584 gp.timer = nil
4585 gp.bubble = nil
4586 gp.fipsOnlyBypass = false
4587 gp.secret = 0
4588
4589 if gcBlackenEnabled != 0 && gp.gcAssistBytes > 0 {
4590
4591
4592
4593 assistWorkPerByte := gcController.assistWorkPerByte.Load()
4594 scanCredit := int64(assistWorkPerByte * float64(gp.gcAssistBytes))
4595 gcController.bgScanCredit.Add(scanCredit)
4596 gp.gcAssistBytes = 0
4597 }
4598
4599 dropg()
4600
4601 if GOARCH == "wasm" || GOARCH == "wasm32" {
4602 gfput(pp, gp)
4603 return
4604 }
4605
4606 if locked && mp.lockedInt != 0 {
4607 print("runtime: mp.lockedInt = ", mp.lockedInt, "\n")
4608 if mp.isextra {
4609 throw("runtime.Goexit called in a thread that was not created by the Go runtime")
4610 }
4611 throw("exited a goroutine internally locked to the OS thread")
4612 }
4613 gfput(pp, gp)
4614 if locked {
4615
4616
4617
4618
4619
4620
4621 if GOOS != "plan9" {
4622 gogo(&mp.g0.sched)
4623 } else {
4624
4625
4626 mp.lockedExt = 0
4627 }
4628 }
4629 }
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639 func save(pc, sp, bp uintptr) {
4640 gp := getg()
4641
4642 if gp == gp.m.g0 || gp == gp.m.gsignal {
4643
4644
4645
4646
4647
4648 throw("save on system g not allowed")
4649 }
4650
4651 gobufSetPC(&gp.sched, pc)
4652 gp.sched.sp = sp
4653 gp.sched.bp = bp
4654
4655
4656
4657 if gp.sched.ctxt != nil {
4658 badctxt()
4659 }
4660 }
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686 func reentersyscall(pc, sp, bp uintptr) {
4687 gp := getg()
4688
4689
4690
4691 gp.m.locks++
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713 if goexperiment.RuntimeSecret {
4714 eraseSecretsSignalStk()
4715 }
4716
4717
4718
4719
4720
4721 gp.stackguard0 = stackPreempt
4722 gp.throwsplit = true
4723
4724
4725 gp.m.syscalltick = gp.m.p.ptr().syscalltick
4726
4727 pp := gp.m.p.ptr()
4728 if pp.runSafePointFn != 0 {
4729
4730 systemstack(runSafePointFn)
4731 }
4732 gp.m.oldp.set(pp)
4733
4734
4735 save(pc, sp, bp)
4736 gp.syscallsp = sp
4737 gp.syscallpc = pc
4738 gp.syscallbp = bp
4739
4740
4741 if gp.syscallsp < gp.stack.lo || gp.stack.hi < gp.syscallsp {
4742 systemstack(func() {
4743 print("entersyscall inconsistent sp ", hex(gp.syscallsp), " [", hex(gp.stack.lo), ",", hex(gp.stack.hi), "]\n")
4744 throw("entersyscall")
4745 })
4746 }
4747 if gp.syscallbp != 0 && gp.syscallbp < gp.stack.lo || gp.stack.hi < gp.syscallbp {
4748 systemstack(func() {
4749 print("entersyscall inconsistent bp ", hex(gp.syscallbp), " [", hex(gp.stack.lo), ",", hex(gp.stack.hi), "]\n")
4750 throw("entersyscall")
4751 })
4752 }
4753 trace := traceAcquire()
4754 if trace.ok() {
4755
4756
4757
4758
4759 systemstack(func() {
4760 trace.GoSysCall()
4761 })
4762
4763 save(pc, sp, bp)
4764 }
4765 if sched.gcwaiting.Load() {
4766
4767
4768
4769 systemstack(func() {
4770 entersyscallHandleGCWait(trace)
4771 })
4772
4773 save(pc, sp, bp)
4774 }
4775
4776
4777
4778
4779
4780 if gp.bubble != nil || !gp.atomicstatus.CompareAndSwap(_Grunning, _Gsyscall) {
4781 casgstatus(gp, _Grunning, _Gsyscall)
4782 }
4783 if staticLockRanking {
4784
4785 save(pc, sp, bp)
4786 }
4787 if trace.ok() {
4788
4789
4790
4791 traceRelease(trace)
4792 }
4793 if sched.sysmonwait.Load() {
4794 systemstack(entersyscallWakeSysmon)
4795
4796 save(pc, sp, bp)
4797 }
4798 gp.m.locks--
4799 }
4800
4801
4802
4803
4804 const debugExtendGrunningNoP = false
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820 func entersyscall() {
4821
4822
4823
4824
4825 fp := getcallerfp()
4826 reentersyscall(sys.GetCallerPC(), sys.GetCallerSP(), fp)
4827 }
4828
4829 func entersyscallWakeSysmon() {
4830 lock(&sched.lock)
4831 if sched.sysmonwait.Load() {
4832 sched.sysmonwait.Store(false)
4833 notewakeup(&sched.sysmonnote)
4834 }
4835 unlock(&sched.lock)
4836 }
4837
4838 func entersyscallHandleGCWait(trace traceLocker) {
4839 gp := getg()
4840
4841 lock(&sched.lock)
4842 if sched.stopwait > 0 {
4843
4844 pp := gp.m.p.ptr()
4845 pp.m = 0
4846 gp.m.p = 0
4847 atomic.Store(&pp.status, _Pgcstop)
4848
4849 if trace.ok() {
4850 trace.ProcStop(pp)
4851 }
4852 addGSyscallNoP(gp.m)
4853 pp.gcStopTime = nanotime()
4854 pp.syscalltick++
4855 if sched.stopwait--; sched.stopwait == 0 {
4856 notewakeup(&sched.stopnote)
4857 }
4858 }
4859 unlock(&sched.lock)
4860 }
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874 func entersyscallblock() {
4875 gp := getg()
4876
4877 gp.m.locks++
4878 gp.throwsplit = true
4879 gp.stackguard0 = stackPreempt
4880 gp.m.syscalltick = gp.m.p.ptr().syscalltick
4881 gp.m.p.ptr().syscalltick++
4882
4883 addGSyscallNoP(gp.m)
4884
4885
4886 pc := sys.GetCallerPC()
4887 sp := sys.GetCallerSP()
4888 bp := getcallerfp()
4889 save(pc, sp, bp)
4890 gp.syscallsp = gp.sched.sp
4891 gp.syscallpc = gp.sched.pc
4892 gp.syscallbp = gp.sched.bp
4893 if gp.syscallsp < gp.stack.lo || gp.stack.hi < gp.syscallsp {
4894 sp1 := sp
4895 sp2 := gp.sched.sp
4896 sp3 := gp.syscallsp
4897 systemstack(func() {
4898 print("entersyscallblock inconsistent sp ", hex(sp1), " ", hex(sp2), " ", hex(sp3), " [", hex(gp.stack.lo), ",", hex(gp.stack.hi), "]\n")
4899 throw("entersyscallblock")
4900 })
4901 }
4902
4903
4904
4905
4906
4907
4908 trace := traceAcquire()
4909 systemstack(func() {
4910 if trace.ok() {
4911 trace.GoSysCall()
4912 }
4913 handoffp(releasep())
4914 })
4915
4916
4917
4918 if debugExtendGrunningNoP {
4919 usleep(10)
4920 }
4921 casgstatus(gp, _Grunning, _Gsyscall)
4922 if gp.syscallsp < gp.stack.lo || gp.stack.hi < gp.syscallsp {
4923 systemstack(func() {
4924 print("entersyscallblock inconsistent sp ", hex(sp), " ", hex(gp.sched.sp), " ", hex(gp.syscallsp), " [", hex(gp.stack.lo), ",", hex(gp.stack.hi), "]\n")
4925 throw("entersyscallblock")
4926 })
4927 }
4928 if gp.syscallbp != 0 && gp.syscallbp < gp.stack.lo || gp.stack.hi < gp.syscallbp {
4929 systemstack(func() {
4930 print("entersyscallblock inconsistent bp ", hex(bp), " ", hex(gp.sched.bp), " ", hex(gp.syscallbp), " [", hex(gp.stack.lo), ",", hex(gp.stack.hi), "]\n")
4931 throw("entersyscallblock")
4932 })
4933 }
4934 if trace.ok() {
4935 systemstack(func() {
4936 traceRelease(trace)
4937 })
4938 }
4939
4940
4941 save(sys.GetCallerPC(), sys.GetCallerSP(), getcallerfp())
4942
4943 gp.m.locks--
4944 }
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966 func exitsyscall() {
4967 gp := getg()
4968
4969 gp.m.locks++
4970 if sys.GetCallerSP() > gp.syscallsp {
4971 throw("exitsyscall: syscall frame is no longer valid")
4972 }
4973 gp.waitsince = 0
4974
4975 if sched.stopwait == freezeStopWait {
4976
4977
4978
4979 systemstack(func() {
4980 lock(&deadlock)
4981 lock(&deadlock)
4982 })
4983 }
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996 if gp.bubble != nil || !gp.atomicstatus.CompareAndSwap(_Gsyscall, _Grunning) {
4997 casgstatus(gp, _Gsyscall, _Grunning)
4998 }
4999
5000
5001
5002
5003 if debugExtendGrunningNoP {
5004 usleep(10)
5005 }
5006
5007
5008 oldp := gp.m.oldp.ptr()
5009 gp.m.oldp.set(nil)
5010
5011
5012 pp := gp.m.p.ptr()
5013 if pp != nil {
5014
5015 if trace := traceAcquire(); trace.ok() {
5016 systemstack(func() {
5017
5018
5019
5020
5021
5022
5023
5024
5025 if pp.syscalltick == gp.m.syscalltick {
5026 trace.GoSysExit(false)
5027 } else {
5028
5029
5030
5031
5032 trace.ProcSteal(pp)
5033 trace.ProcStart()
5034 trace.GoSysExit(true)
5035 trace.GoStart()
5036 }
5037 traceRelease(trace)
5038 })
5039 }
5040 } else {
5041
5042 systemstack(func() {
5043
5044 if pp := exitsyscallTryGetP(oldp); pp != nil {
5045
5046 acquirepNoTrace(pp)
5047
5048
5049 if trace := traceAcquire(); trace.ok() {
5050 trace.ProcStart()
5051 trace.GoSysExit(true)
5052 trace.GoStart()
5053 traceRelease(trace)
5054 }
5055 }
5056 })
5057 pp = gp.m.p.ptr()
5058 }
5059
5060
5061 if pp != nil {
5062 if goroutineProfile.active {
5063
5064
5065
5066 systemstack(func() {
5067 tryRecordGoroutineProfileWB(gp)
5068 })
5069 }
5070
5071
5072 pp.syscalltick++
5073
5074
5075
5076 gp.syscallsp = 0
5077 gp.m.locks--
5078 if gp.preempt {
5079
5080 gp.stackguard0 = stackPreempt
5081 } else {
5082
5083 gp.stackguard0 = gp.stack.lo + stackGuard
5084 }
5085 gp.throwsplit = false
5086
5087 if sched.disable.user && !schedEnabled(gp) {
5088
5089 Gosched()
5090 }
5091 return
5092 }
5093
5094 gp.m.locks--
5095
5096
5097 mcall(exitsyscallNoP)
5098
5099
5100
5101
5102
5103
5104
5105 gp.syscallsp = 0
5106 gp.m.p.ptr().syscalltick++
5107 gp.throwsplit = false
5108 }
5109
5110
5111
5112
5113
5114
5115
5116 func exitsyscallTryGetP(oldp *p) *p {
5117
5118 if oldp != nil {
5119 if thread, ok := setBlockOnExitSyscall(oldp); ok {
5120 thread.takeP()
5121 decGSyscallNoP(getg().m)
5122 thread.resume()
5123 return oldp
5124 }
5125 }
5126
5127
5128 if sched.pidle != 0 {
5129 lock(&sched.lock)
5130 pp, _ := pidleget(0)
5131 if pp != nil && sched.sysmonwait.Load() {
5132 sched.sysmonwait.Store(false)
5133 notewakeup(&sched.sysmonnote)
5134 }
5135 unlock(&sched.lock)
5136 if pp != nil {
5137 decGSyscallNoP(getg().m)
5138 return pp
5139 }
5140 }
5141 return nil
5142 }
5143
5144
5145
5146
5147
5148
5149
5150 func exitsyscallNoP(gp *g) {
5151 traceExitingSyscall()
5152 trace := traceAcquire()
5153 casgstatus(gp, _Grunning, _Grunnable)
5154 traceExitedSyscall()
5155 if trace.ok() {
5156
5157
5158
5159
5160 trace.GoSysExit(true)
5161 traceRelease(trace)
5162 }
5163 decGSyscallNoP(getg().m)
5164 dropg()
5165 lock(&sched.lock)
5166 var pp *p
5167 if schedEnabled(gp) {
5168 pp, _ = pidleget(0)
5169 }
5170 var locked bool
5171 if pp == nil {
5172 globrunqput(gp)
5173
5174
5175
5176
5177
5178
5179 locked = gp.lockedm != 0
5180 } else if sched.sysmonwait.Load() {
5181 sched.sysmonwait.Store(false)
5182 notewakeup(&sched.sysmonnote)
5183 }
5184 unlock(&sched.lock)
5185 if pp != nil {
5186 acquirep(pp)
5187 execute(gp, false)
5188 }
5189 if locked {
5190
5191
5192
5193
5194 stoplockedm()
5195 execute(gp, false)
5196 }
5197 stopm()
5198 schedule()
5199 }
5200
5201
5202
5203
5204
5205
5206
5207 func addGSyscallNoP(mp *m) {
5208
5209
5210
5211 if !mp.isExtraInC {
5212
5213
5214
5215
5216
5217 sched.nGsyscallNoP.Add(1)
5218 }
5219 }
5220
5221
5222
5223
5224
5225
5226
5227 func decGSyscallNoP(mp *m) {
5228
5229
5230
5231 if !mp.isExtraInC {
5232 sched.nGsyscallNoP.Add(-1)
5233 }
5234 }
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248 func syscall_runtime_BeforeFork() {
5249 gp := getg().m.curg
5250
5251
5252
5253
5254 gp.m.locks++
5255 sigsave(&gp.m.sigmask)
5256 sigblock(false)
5257
5258
5259
5260
5261
5262 gp.stackguard0 = stackFork
5263 }
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277 func syscall_runtime_AfterFork() {
5278 gp := getg().m.curg
5279
5280
5281 gp.stackguard0 = gp.stack.lo + stackGuard
5282
5283 msigrestore(gp.m.sigmask)
5284
5285 gp.m.locks--
5286 }
5287
5288
5289
5290 var inForkedChild bool
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311 func syscall_runtime_AfterForkInChild() {
5312
5313
5314
5315
5316 inForkedChild = true
5317
5318 clearSignalHandlers()
5319
5320
5321
5322 msigrestore(getg().m.sigmask)
5323
5324 inForkedChild = false
5325 }
5326
5327
5328
5329
5330 var pendingPreemptSignals atomic.Int32
5331
5332
5333
5334
5335 func syscall_runtime_BeforeExec() {
5336
5337 execLock.lock()
5338
5339
5340
5341 if GOOS == "darwin" || GOOS == "ios" {
5342 for pendingPreemptSignals.Load() > 0 {
5343 osyield()
5344 }
5345 }
5346 }
5347
5348
5349
5350
5351 func syscall_runtime_AfterExec() {
5352 execLock.unlock()
5353 }
5354
5355
5356 func malg(stacksize int32) *g {
5357 newg := new(g)
5358
5359
5360 wasmContAlloc(newg)
5361 if stacksize >= 0 {
5362 stacksize = round2(stackSystem + stacksize)
5363 systemstack(func() {
5364 newg.stack = stackalloc(uint32(stacksize))
5365 if valgrindenabled {
5366 valgrindRegisterStack(newg)
5367 }
5368 })
5369 newg.stackguard0 = newg.stack.lo + stackGuard
5370 newg.stackguard1 = ^uintptr(0)
5371
5372
5373 *(*uintptr)(unsafe.Pointer(newg.stack.lo)) = 0
5374 }
5375 return newg
5376 }
5377
5378
5379
5380
5381 func newproc(fn *funcval) {
5382 gp := getg()
5383 pc := sys.GetCallerPC()
5384 systemstack(func() {
5385 newg := newproc1(fn, gp, pc, false, waitReasonZero)
5386
5387 pp := getg().m.p.ptr()
5388 runqput(pp, newg, true)
5389
5390 if mainStarted {
5391 wakep()
5392 }
5393 })
5394 }
5395
5396
5397
5398
5399 func newproc1(fn *funcval, callergp *g, callerpc uintptr, parked bool, waitreason waitReason) *g {
5400 if fn == nil {
5401 fatal("go of nil func value")
5402 }
5403
5404 mp := acquirem()
5405 pp := mp.p.ptr()
5406 newg := gfget(pp)
5407 if newg == nil {
5408 newg = malg(stackMin)
5409 casgstatus(newg, _Gidle, _Gdead)
5410 allgadd(newg)
5411 }
5412 if newg.stack.hi == 0 {
5413 throw("newproc1: newg missing stack")
5414 }
5415
5416 if readgstatus(newg) != _Gdead {
5417 throw("newproc1: new g is not Gdead")
5418 }
5419
5420 totalSize := uintptr(4*goarch.PtrSize + sys.MinFrameSize)
5421 totalSize = alignUp(totalSize, sys.StackAlign)
5422 sp := newg.stack.hi - totalSize
5423 if usesLR {
5424
5425 *(*uintptr)(unsafe.Pointer(sp)) = 0
5426 prepGoExitFrame(sp)
5427 }
5428 if GOARCH == "arm64" {
5429
5430 *(*uintptr)(unsafe.Pointer(sp - goarch.PtrSize)) = 0
5431 }
5432
5433 memclrNoHeapPointers(unsafe.Pointer(&newg.sched), unsafe.Sizeof(newg.sched))
5434 newg.sched.sp = sp
5435 newg.stktopsp = sp
5436 gobufSetGoexit(&newg.sched)
5437 newg.sched.g = guintptr(unsafe.Pointer(newg))
5438 gostartcallfn(&newg.sched, fn)
5439 newg.parentGoid = callergp.goid
5440 newg.gopc = callerpc
5441 newg.ancestors = saveAncestors(callergp)
5442 newg.startpc = funcValuePC(fn.fn)
5443 newg.runningCleanups.Store(false)
5444 if isSystemGoroutine(newg, false) {
5445 sched.ngsys.Add(1)
5446 } else {
5447
5448 newg.bubble = callergp.bubble
5449 if mp.curg != nil {
5450 newg.labels = mp.curg.labels
5451 }
5452 if goroutineProfile.active {
5453
5454
5455
5456
5457
5458 newg.goroutineProfiled.Store(goroutineProfileSatisfied)
5459 }
5460 }
5461
5462 newg.trackingSeq = uint8(cheaprand())
5463 if newg.trackingSeq%gTrackingPeriod == 0 {
5464 newg.tracking = true
5465 }
5466 gcController.addScannableStack(pp, int64(newg.stack.hi-newg.stack.lo))
5467
5468
5469
5470 trace := traceAcquire()
5471 var status uint32 = _Grunnable
5472 if parked {
5473 status = _Gwaiting
5474 newg.waitreason = waitreason
5475 }
5476 if pp.goidcache == pp.goidcacheend {
5477
5478
5479
5480 pp.goidcache = sched.goidgen.Add(_GoidCacheBatch)
5481 pp.goidcache -= _GoidCacheBatch - 1
5482 pp.goidcacheend = pp.goidcache + _GoidCacheBatch
5483 }
5484 newg.goid = pp.goidcache
5485 casgstatus(newg, _Gdead, status)
5486 pp.goidcache++
5487 newg.trace.reset()
5488 if trace.ok() {
5489 trace.GoCreate(newg, newg.startpc, parked)
5490 traceRelease(trace)
5491 }
5492
5493
5494 newg.fipsOnlyBypass = callergp.fipsOnlyBypass
5495
5496
5497 newg.ditWanted = callergp.ditWanted
5498
5499 if goexperiment.RuntimeSecret && callergp.secret > 0 {
5500
5501
5502
5503
5504
5505
5506
5507
5508 newg.secret = 1
5509 }
5510
5511
5512 if raceenabled {
5513 newg.racectx = racegostart(callerpc)
5514 newg.raceignore = 0
5515 if newg.labels != nil {
5516
5517
5518 racereleasemergeg(newg, unsafe.Pointer(&labelSync))
5519 }
5520 }
5521 pp.goroutinesCreated++
5522 releasem(mp)
5523
5524 return newg
5525 }
5526
5527
5528
5529
5530 func saveAncestors(callergp *g) *[]ancestorInfo {
5531
5532 if debug.tracebackancestors <= 0 || callergp.goid == 0 {
5533 return nil
5534 }
5535 var callerAncestors []ancestorInfo
5536 if callergp.ancestors != nil {
5537 callerAncestors = *callergp.ancestors
5538 }
5539 n := int32(len(callerAncestors)) + 1
5540 if n > debug.tracebackancestors {
5541 n = debug.tracebackancestors
5542 }
5543 ancestors := make([]ancestorInfo, n)
5544 copy(ancestors[1:], callerAncestors)
5545
5546 var pcs [tracebackInnerFrames]uintptr
5547 npcs := gcallers(callergp, 0, pcs[:])
5548 ipcs := make([]uintptr, npcs)
5549 copy(ipcs, pcs[:])
5550 ancestors[0] = ancestorInfo{
5551 pcs: ipcs,
5552 goid: callergp.goid,
5553 gopc: callergp.gopc,
5554 }
5555
5556 ancestorsp := new([]ancestorInfo)
5557 *ancestorsp = ancestors
5558 return ancestorsp
5559 }
5560
5561
5562
5563 func gfput(pp *p, gp *g) {
5564 if readgstatus(gp) != _Gdead {
5565 throw("gfput: bad status (not Gdead)")
5566 }
5567
5568 stksize := gp.stack.hi - gp.stack.lo
5569
5570 if stksize != uintptr(startingStackSize) {
5571
5572 stackfree(gp.stack)
5573 gp.stack.lo = 0
5574 gp.stack.hi = 0
5575 gp.stackguard0 = 0
5576 if valgrindenabled {
5577 valgrindDeregisterStack(gp)
5578 }
5579 }
5580
5581 pp.gFree.push(gp)
5582 if pp.gFree.size >= 64 {
5583 var (
5584 stackQ gQueue
5585 noStackQ gQueue
5586 )
5587 for pp.gFree.size >= 32 {
5588 gp := pp.gFree.pop()
5589 if gp.stack.lo == 0 {
5590 noStackQ.push(gp)
5591 } else {
5592 stackQ.push(gp)
5593 }
5594 }
5595 lock(&sched.gFree.lock)
5596 sched.gFree.noStack.pushAll(noStackQ)
5597 sched.gFree.stack.pushAll(stackQ)
5598 unlock(&sched.gFree.lock)
5599 }
5600 }
5601
5602
5603
5604 func gfget(pp *p) *g {
5605 retry:
5606 if pp.gFree.empty() && (!sched.gFree.stack.empty() || !sched.gFree.noStack.empty()) {
5607 lock(&sched.gFree.lock)
5608
5609 for pp.gFree.size < 32 {
5610
5611 gp := sched.gFree.stack.pop()
5612 if gp == nil {
5613 gp = sched.gFree.noStack.pop()
5614 if gp == nil {
5615 break
5616 }
5617 }
5618 pp.gFree.push(gp)
5619 }
5620 unlock(&sched.gFree.lock)
5621 goto retry
5622 }
5623 gp := pp.gFree.pop()
5624 if gp == nil {
5625 return nil
5626 }
5627 if gp.stack.lo != 0 && gp.stack.hi-gp.stack.lo != uintptr(startingStackSize) {
5628
5629
5630
5631 systemstack(func() {
5632 stackfree(gp.stack)
5633 gp.stack.lo = 0
5634 gp.stack.hi = 0
5635 gp.stackguard0 = 0
5636 if valgrindenabled {
5637 valgrindDeregisterStack(gp)
5638 }
5639 })
5640 }
5641 if gp.stack.lo == 0 {
5642
5643 systemstack(func() {
5644 gp.stack = stackalloc(startingStackSize)
5645 if valgrindenabled {
5646 valgrindRegisterStack(gp)
5647 }
5648 })
5649 gp.stackguard0 = gp.stack.lo + stackGuard
5650 } else {
5651 if raceenabled {
5652 racemalloc(unsafe.Pointer(gp.stack.lo), gp.stack.hi-gp.stack.lo)
5653 }
5654 if msanenabled {
5655 msanmalloc(unsafe.Pointer(gp.stack.lo), gp.stack.hi-gp.stack.lo)
5656 }
5657 if asanenabled {
5658 asanunpoison(unsafe.Pointer(gp.stack.lo), gp.stack.hi-gp.stack.lo)
5659 }
5660 }
5661 return gp
5662 }
5663
5664
5665 func gfpurge(pp *p) {
5666 var (
5667 stackQ gQueue
5668 noStackQ gQueue
5669 )
5670 for !pp.gFree.empty() {
5671 gp := pp.gFree.pop()
5672 if gp.stack.lo == 0 {
5673 noStackQ.push(gp)
5674 } else {
5675 stackQ.push(gp)
5676 }
5677 }
5678 lock(&sched.gFree.lock)
5679 sched.gFree.noStack.pushAll(noStackQ)
5680 sched.gFree.stack.pushAll(stackQ)
5681 unlock(&sched.gFree.lock)
5682 }
5683
5684
5685 func Breakpoint() {
5686 breakpoint()
5687 }
5688
5689
5690
5691
5692
5693
5694 func dolockOSThread() {
5695 if GOARCH == "wasm" || GOARCH == "wasm32" {
5696 return
5697 }
5698 gp := getg()
5699 gp.m.lockedg.set(gp)
5700 gp.lockedm.set(gp.m)
5701 }
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719 func LockOSThread() {
5720 if atomic.Load(&newmHandoff.haveTemplateThread) == 0 && GOOS != "plan9" {
5721
5722
5723
5724 startTemplateThread()
5725 }
5726 gp := getg()
5727 gp.m.lockedExt++
5728 if gp.m.lockedExt == 0 {
5729 gp.m.lockedExt--
5730 panic("LockOSThread nesting overflow")
5731 }
5732 dolockOSThread()
5733 }
5734
5735
5736 func lockOSThread() {
5737 getg().m.lockedInt++
5738 dolockOSThread()
5739 }
5740
5741
5742
5743
5744
5745
5746 func dounlockOSThread() {
5747 if GOARCH == "wasm" || GOARCH == "wasm32" {
5748 return
5749 }
5750 gp := getg()
5751 if gp.m.lockedInt != 0 || gp.m.lockedExt != 0 {
5752 return
5753 }
5754 gp.m.lockedg = 0
5755 gp.lockedm = 0
5756 }
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772 func UnlockOSThread() {
5773 gp := getg()
5774 if gp.m.lockedExt == 0 {
5775 return
5776 }
5777 gp.m.lockedExt--
5778 dounlockOSThread()
5779 }
5780
5781
5782 func unlockOSThread() {
5783 gp := getg()
5784 if gp.m.lockedInt == 0 {
5785 systemstack(badunlockosthread)
5786 }
5787 gp.m.lockedInt--
5788 dounlockOSThread()
5789 }
5790
5791 func badunlockosthread() {
5792 throw("runtime: internal error: misuse of lockOSThread/unlockOSThread")
5793 }
5794
5795 func gcount(includeSys bool) int32 {
5796 n := int32(atomic.Loaduintptr(&allglen)) - sched.gFree.stack.size - sched.gFree.noStack.size
5797 if !includeSys {
5798 n -= sched.ngsys.Load()
5799 }
5800 for _, pp := range allp {
5801 n -= pp.gFree.size
5802 }
5803
5804
5805
5806 if n < 1 {
5807 n = 1
5808 }
5809 return n
5810 }
5811
5812
5813
5814
5815
5816 func goroutineleakcount() int {
5817 return work.goroutineLeak.count
5818 }
5819
5820 func mcount() int32 {
5821 return int32(sched.mnext - sched.nmfreed)
5822 }
5823
5824 var prof struct {
5825 signalLock atomic.Uint32
5826
5827
5828
5829 hz atomic.Int32
5830 }
5831
5832 func _System() { _System() }
5833 func _ExternalCode() { _ExternalCode() }
5834 func _LostExternalCode() { _LostExternalCode() }
5835 func _GC() { _GC() }
5836 func _LostSIGPROFDuringAtomic64() { _LostSIGPROFDuringAtomic64() }
5837 func _LostContendedRuntimeLock() { _LostContendedRuntimeLock() }
5838 func _VDSO() { _VDSO() }
5839
5840
5841
5842
5843
5844 func sigprof(pc, sp, lr uintptr, gp *g, mp *m) {
5845 if prof.hz.Load() == 0 {
5846 return
5847 }
5848
5849
5850
5851
5852 if mp != nil && mp.profilehz == 0 {
5853 return
5854 }
5855
5856
5857
5858
5859
5860
5861
5862 if GOARCH == "mips" || GOARCH == "mipsle" || GOARCH == "arm" {
5863 if f := findfunc(pc); f.valid() {
5864 if stringslite.HasPrefix(funcname(f), "internal/runtime/atomic") {
5865 cpuprof.lostAtomic++
5866 return
5867 }
5868 }
5869 if GOARCH == "arm" && goarm < 7 && GOOS == "linux" && pc&0xffff0000 == 0xffff0000 {
5870
5871
5872
5873 cpuprof.lostAtomic++
5874 return
5875 }
5876 }
5877
5878
5879
5880
5881
5882
5883
5884 getg().m.mallocing++
5885
5886 var u unwinder
5887 var stk [maxCPUProfStack]uintptr
5888 n := 0
5889 if mp.ncgo > 0 && mp.curg != nil && mp.curg.syscallpc != 0 && mp.curg.syscallsp != 0 {
5890 cgoOff := 0
5891
5892
5893
5894
5895
5896 if mp.cgoCallersUse.Load() == 0 && mp.cgoCallers != nil && mp.cgoCallers[0] != 0 {
5897 for cgoOff < len(mp.cgoCallers) && mp.cgoCallers[cgoOff] != 0 {
5898 cgoOff++
5899 }
5900 n += copy(stk[:], mp.cgoCallers[:cgoOff])
5901 mp.cgoCallers[0] = 0
5902 }
5903
5904
5905 u.initAt(mp.curg.syscallpc, mp.curg.syscallsp, 0, mp.curg, unwindSilentErrors)
5906 } else if usesLibcall() && mp.libcallg != 0 && mp.libcallpc != 0 && mp.libcallsp != 0 {
5907
5908
5909 u.initAt(mp.libcallpc, mp.libcallsp, 0, mp.libcallg.ptr(), unwindSilentErrors)
5910 } else if mp != nil && mp.vdsoSP != 0 {
5911
5912
5913 u.initAt(mp.vdsoPC, mp.vdsoSP, 0, gp, unwindSilentErrors|unwindJumpStack)
5914 } else {
5915 u.initAt(pc, sp, lr, gp, unwindSilentErrors|unwindTrap|unwindJumpStack)
5916 }
5917 n += tracebackPCs(&u, 0, stk[n:])
5918
5919 if n <= 0 {
5920
5921
5922 n = 2
5923 if inVDSOPage(pc) {
5924 pc = abi.FuncPCABIInternal(_VDSO) + sys.PCQuantum
5925 } else if pc > firstmoduledata.etext {
5926
5927 pc = abi.FuncPCABIInternal(_ExternalCode) + sys.PCQuantum
5928 }
5929 stk[0] = pc
5930 if mp.preemptoff != "" {
5931 stk[1] = abi.FuncPCABIInternal(_GC) + sys.PCQuantum
5932 } else {
5933 stk[1] = abi.FuncPCABIInternal(_System) + sys.PCQuantum
5934 }
5935 }
5936
5937 if prof.hz.Load() != 0 {
5938
5939
5940
5941 var tagPtr *unsafe.Pointer
5942 if gp != nil && gp.m != nil && gp.m.curg != nil {
5943 tagPtr = &gp.m.curg.labels
5944 }
5945 cpuprof.add(tagPtr, stk[:n])
5946
5947 gprof := gp
5948 var mp *m
5949 var pp *p
5950 if gp != nil && gp.m != nil {
5951 if gp.m.curg != nil {
5952 gprof = gp.m.curg
5953 }
5954 mp = gp.m
5955 pp = gp.m.p.ptr()
5956 }
5957 traceCPUSample(gprof, mp, pp, stk[:n])
5958 }
5959 getg().m.mallocing--
5960 }
5961
5962
5963
5964 func setcpuprofilerate(hz int32) {
5965
5966 if hz < 0 {
5967 hz = 0
5968 }
5969
5970
5971
5972 gp := getg()
5973 gp.m.locks++
5974
5975
5976
5977
5978 setThreadCPUProfiler(0)
5979
5980 for !prof.signalLock.CompareAndSwap(0, 1) {
5981 osyield()
5982 }
5983 if prof.hz.Load() != hz {
5984 setProcessCPUProfiler(hz)
5985 prof.hz.Store(hz)
5986 }
5987 prof.signalLock.Store(0)
5988
5989 lock(&sched.lock)
5990 sched.profilehz = hz
5991 unlock(&sched.lock)
5992
5993 if hz != 0 {
5994 setThreadCPUProfiler(hz)
5995 }
5996
5997 gp.m.locks--
5998 }
5999
6000
6001
6002 func (pp *p) init(id int32) {
6003 pp.id = id
6004 pp.gcw.id = id
6005 pp.status = _Pgcstop
6006 pp.waitingGCache = pp.waitingGBuf[:0]
6007 pp.deferpool = pp.deferpoolbuf[:0]
6008 pp.wbBuf.reset()
6009 if pp.mcache == nil {
6010 if id == 0 {
6011 if mcache0 == nil {
6012 throw("missing mcache?")
6013 }
6014
6015
6016 pp.mcache = mcache0
6017 } else {
6018 pp.mcache = allocmcache()
6019 }
6020 }
6021 if raceenabled && pp.raceprocctx == 0 {
6022 if id == 0 {
6023 pp.raceprocctx = raceprocctx0
6024 raceprocctx0 = 0
6025 } else {
6026 pp.raceprocctx = raceproccreate()
6027 }
6028 }
6029 lockInit(&pp.timers.mu, lockRankTimers)
6030
6031
6032
6033 timerpMask.set(id)
6034
6035
6036 idlepMask.clear(id)
6037 }
6038
6039
6040
6041
6042
6043 func (pp *p) destroy() {
6044 assertLockHeld(&sched.lock)
6045 assertWorldStopped()
6046
6047
6048 for pp.runqhead != pp.runqtail {
6049
6050 pp.runqtail--
6051 gp := pp.runq[pp.runqtail%uint32(len(pp.runq))].ptr()
6052
6053 globrunqputhead(gp)
6054 }
6055 if pp.runnext != 0 {
6056 globrunqputhead(pp.runnext.ptr())
6057 pp.runnext = 0
6058 }
6059
6060
6061 getg().m.p.ptr().timers.take(&pp.timers)
6062
6063
6064
6065 if phase := gcphase; phase != _GCoff {
6066 println("runtime: p id", pp.id, "destroyed during GC phase", phase)
6067 throw("P destroyed while GC is running")
6068 }
6069
6070 pp.gcw.spanq.destroy()
6071
6072 clear(pp.waitingGBuf[:])
6073 pp.waitingGCache = pp.waitingGBuf[:0]
6074 pp.pinnerCache = nil
6075 if pp.pinCounterCache != nil {
6076 lock(&mheap_.speciallock)
6077 mheap_.specialPinCounterAlloc.free(unsafe.Pointer(pp.pinCounterCache))
6078 unlock(&mheap_.speciallock)
6079 pp.pinCounterCache = nil
6080 }
6081 clear(pp.deferpoolbuf[:])
6082 pp.deferpool = pp.deferpoolbuf[:0]
6083 systemstack(func() {
6084 for i := 0; i < pp.mspancache.len; i++ {
6085
6086 mheap_.spanalloc.free(unsafe.Pointer(pp.mspancache.buf[i]))
6087 }
6088 pp.mspancache.len = 0
6089 lock(&mheap_.lock)
6090 pp.pcache.flush(&mheap_.pages)
6091 unlock(&mheap_.lock)
6092 })
6093 freemcache(pp.mcache)
6094 pp.mcache = nil
6095 gfpurge(pp)
6096 if raceenabled {
6097 if pp.timers.raceCtx != 0 {
6098
6099
6100
6101
6102
6103 mp := getg().m
6104 phold := mp.p.ptr()
6105 mp.p.set(pp)
6106
6107 racectxend(pp.timers.raceCtx)
6108 pp.timers.raceCtx = 0
6109
6110 mp.p.set(phold)
6111 }
6112 raceprocdestroy(pp.raceprocctx)
6113 pp.raceprocctx = 0
6114 }
6115 pp.gcAssistTime = 0
6116 gcCleanups.queued += pp.cleanupsQueued
6117 pp.cleanupsQueued = 0
6118 sched.goroutinesCreated.Add(int64(pp.goroutinesCreated))
6119 pp.goroutinesCreated = 0
6120 pp.xRegs.free()
6121 pp.status = _Pdead
6122 }
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132 func procresize(nprocs int32) *p {
6133 assertLockHeld(&sched.lock)
6134 assertWorldStopped()
6135
6136 old := gomaxprocs
6137 if old < 0 || nprocs <= 0 {
6138 throw("procresize: invalid arg")
6139 }
6140 trace := traceAcquire()
6141 if trace.ok() {
6142 trace.Gomaxprocs(nprocs)
6143 traceRelease(trace)
6144 }
6145
6146
6147 now := nanotime()
6148 if sched.procresizetime != 0 {
6149 sched.totaltime += int64(old) * (now - sched.procresizetime)
6150 }
6151 sched.procresizetime = now
6152
6153
6154 if nprocs > int32(len(allp)) {
6155
6156
6157 lock(&allpLock)
6158 if nprocs <= int32(cap(allp)) {
6159 allp = allp[:nprocs]
6160 } else {
6161 nallp := make([]*p, nprocs)
6162
6163
6164 copy(nallp, allp[:cap(allp)])
6165 allp = nallp
6166 }
6167
6168 idlepMask = idlepMask.resize(nprocs)
6169 timerpMask = timerpMask.resize(nprocs)
6170 work.spanqMask = work.spanqMask.resize(nprocs)
6171 unlock(&allpLock)
6172 }
6173
6174
6175 for i := old; i < nprocs; i++ {
6176 pp := allp[i]
6177 if pp == nil {
6178 pp = new(p)
6179 }
6180 pp.init(i)
6181 atomicstorep(unsafe.Pointer(&allp[i]), unsafe.Pointer(pp))
6182 }
6183
6184 gp := getg()
6185 if gp.m.p != 0 && gp.m.p.ptr().id < nprocs {
6186
6187 gp.m.p.ptr().status = _Prunning
6188 gp.m.p.ptr().mcache.prepareForSweep()
6189 } else {
6190
6191
6192
6193
6194
6195 if gp.m.p != 0 {
6196 trace := traceAcquire()
6197 if trace.ok() {
6198
6199
6200
6201 trace.GoSched()
6202 trace.ProcStop(gp.m.p.ptr())
6203 traceRelease(trace)
6204 }
6205 gp.m.p.ptr().m = 0
6206 }
6207 gp.m.p = 0
6208 pp := allp[0]
6209 pp.m = 0
6210 pp.status = _Pidle
6211 acquirep(pp)
6212 trace := traceAcquire()
6213 if trace.ok() {
6214 trace.GoStart()
6215 traceRelease(trace)
6216 }
6217 }
6218
6219
6220 mcache0 = nil
6221
6222
6223 for i := nprocs; i < old; i++ {
6224 pp := allp[i]
6225 pp.destroy()
6226
6227 }
6228
6229
6230 if int32(len(allp)) != nprocs {
6231 lock(&allpLock)
6232 allp = allp[:nprocs]
6233 idlepMask = idlepMask.resize(nprocs)
6234 timerpMask = timerpMask.resize(nprocs)
6235 work.spanqMask = work.spanqMask.resize(nprocs)
6236 unlock(&allpLock)
6237 }
6238
6239
6240 var runnablePs *p
6241 var runnablePsNeedM *p
6242 var idlePs *p
6243 for i := nprocs - 1; i >= 0; i-- {
6244 pp := allp[i]
6245 if gp.m.p.ptr() == pp {
6246 continue
6247 }
6248 pp.status = _Pidle
6249 if runqempty(pp) {
6250 pp.link.set(idlePs)
6251 idlePs = pp
6252 continue
6253 }
6254
6255
6256
6257
6258
6259
6260
6261
6262 var mp *m
6263 if oldm := pp.oldm.get(); oldm != nil {
6264
6265 mp = mgetSpecific(oldm)
6266 }
6267 if mp == nil {
6268
6269 pp.link.set(runnablePsNeedM)
6270 runnablePsNeedM = pp
6271 continue
6272 }
6273 pp.m.set(mp)
6274 pp.link.set(runnablePs)
6275 runnablePs = pp
6276 }
6277
6278
6279 for runnablePsNeedM != nil {
6280 pp := runnablePsNeedM
6281 runnablePsNeedM = pp.link.ptr()
6282
6283 mp := mget()
6284 pp.m.set(mp)
6285 pp.link.set(runnablePs)
6286 runnablePs = pp
6287 }
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313 if gcBlackenEnabled != 0 {
6314 for idlePs != nil {
6315 pp := idlePs
6316
6317 ok, _ := gcController.assignWaitingGCWorker(pp, now)
6318 if !ok {
6319
6320 break
6321 }
6322
6323
6324
6325
6326
6327
6328
6329
6330 idlePs = pp.link.ptr()
6331 mp := mget()
6332 pp.m.set(mp)
6333 pp.link.set(runnablePs)
6334 runnablePs = pp
6335 }
6336 }
6337
6338
6339 for idlePs != nil {
6340 pp := idlePs
6341 idlePs = pp.link.ptr()
6342 pidleput(pp, now)
6343 }
6344
6345 stealOrder.reset(uint32(nprocs))
6346 var int32p *int32 = &gomaxprocs
6347 atomic.Store((*uint32)(unsafe.Pointer(int32p)), uint32(nprocs))
6348 if old != nprocs {
6349
6350 gcCPULimiter.resetCapacity(now, nprocs)
6351 }
6352 return runnablePs
6353 }
6354
6355
6356
6357
6358
6359
6360
6361 func acquirep(pp *p) {
6362
6363 acquirepNoTrace(pp)
6364
6365
6366 trace := traceAcquire()
6367 if trace.ok() {
6368 trace.ProcStart()
6369 traceRelease(trace)
6370 }
6371 }
6372
6373
6374
6375
6376 func acquirepNoTrace(pp *p) {
6377
6378 wirep(pp)
6379
6380
6381
6382
6383
6384
6385 pp.oldm = pp.m.ptr().self
6386
6387
6388
6389 pp.mcache.prepareForSweep()
6390 }
6391
6392
6393
6394
6395
6396
6397
6398 func wirep(pp *p) {
6399 gp := getg()
6400
6401 if gp.m.p != 0 {
6402
6403
6404 systemstack(func() {
6405 throw("wirep: already in go")
6406 })
6407 }
6408 if pp.m != 0 || pp.status != _Pidle {
6409
6410
6411 systemstack(func() {
6412 id := int64(0)
6413 if pp.m != 0 {
6414 id = pp.m.ptr().id
6415 }
6416 print("wirep: p->m=", pp.m, "(", id, ") p->status=", pp.status, "\n")
6417 throw("wirep: invalid p state")
6418 })
6419 }
6420 gp.m.p.set(pp)
6421 pp.m.set(gp.m)
6422 pp.status = _Prunning
6423 }
6424
6425
6426 func releasep() *p {
6427 trace := traceAcquire()
6428 if trace.ok() {
6429 trace.ProcStop(getg().m.p.ptr())
6430 traceRelease(trace)
6431 }
6432 return releasepNoTrace()
6433 }
6434
6435
6436 func releasepNoTrace() *p {
6437 gp := getg()
6438
6439 if gp.m.p == 0 {
6440 throw("releasep: invalid arg")
6441 }
6442 pp := gp.m.p.ptr()
6443 if pp.m.ptr() != gp.m || pp.status != _Prunning {
6444 print("releasep: m=", gp.m, " m->p=", gp.m.p.ptr(), " p->m=", hex(pp.m), " p->status=", pp.status, "\n")
6445 throw("releasep: invalid p state")
6446 }
6447
6448
6449 gcController.releaseNextGCMarkWorker(pp)
6450
6451 gp.m.p = 0
6452 pp.m = 0
6453 pp.status = _Pidle
6454 return pp
6455 }
6456
6457 func incidlelocked(v int32) {
6458 lock(&sched.lock)
6459 sched.nmidlelocked += v
6460 if v > 0 {
6461 checkdead()
6462 }
6463 unlock(&sched.lock)
6464 }
6465
6466
6467
6468
6469 func checkdead() {
6470 assertLockHeld(&sched.lock)
6471
6472
6473
6474
6475
6476
6477 if (islibrary || isarchive) && GOARCH != "wasm" && GOARCH != "wasm32" {
6478 return
6479 }
6480
6481
6482
6483
6484
6485 if panicking.Load() > 0 {
6486 return
6487 }
6488
6489
6490
6491
6492
6493 var run0 int32
6494 if !iscgo && cgoHasExtraM && extraMLength.Load() > 0 {
6495 run0 = 1
6496 }
6497
6498 run := mcount() - sched.nmidle - sched.nmidlelocked - sched.nmsys
6499 if run > run0 {
6500 return
6501 }
6502 if run < 0 {
6503 print("runtime: checkdead: nmidle=", sched.nmidle, " nmidlelocked=", sched.nmidlelocked, " mcount=", mcount(), " nmsys=", sched.nmsys, "\n")
6504 unlock(&sched.lock)
6505 throw("checkdead: inconsistent counts")
6506 }
6507
6508 grunning := 0
6509 forEachG(func(gp *g) {
6510 if isSystemGoroutine(gp, false) {
6511 return
6512 }
6513 s := readgstatus(gp)
6514 switch s &^ _Gscan {
6515 case _Gwaiting,
6516 _Gpreempted:
6517 grunning++
6518 case _Grunnable,
6519 _Grunning,
6520 _Gsyscall:
6521 print("runtime: checkdead: find g ", gp.goid, " in status ", s, "\n")
6522 unlock(&sched.lock)
6523 throw("checkdead: runnable g")
6524 }
6525 })
6526 if grunning == 0 {
6527 unlock(&sched.lock)
6528 fatal("no goroutines (main called runtime.Goexit) - deadlock!")
6529 }
6530
6531
6532 if faketime != 0 {
6533 if when := timeSleepUntil(); when < maxWhen {
6534 faketime = when
6535
6536
6537 pp, _ := pidleget(faketime)
6538 if pp == nil {
6539
6540
6541 unlock(&sched.lock)
6542 throw("checkdead: no p for timer")
6543 }
6544 mp := mget()
6545 if mp == nil {
6546
6547
6548 unlock(&sched.lock)
6549 throw("checkdead: no m for timer")
6550 }
6551
6552
6553
6554 sched.nmspinning.Add(1)
6555 mp.spinning = true
6556 mp.nextp.set(pp)
6557 notewakeup(&mp.park)
6558 return
6559 }
6560 }
6561
6562
6563 for _, pp := range allp {
6564 if len(pp.timers.heap) > 0 {
6565 return
6566 }
6567 }
6568
6569 unlock(&sched.lock)
6570 fatal("all goroutines are asleep - deadlock!")
6571 }
6572
6573
6574
6575
6576
6577
6578 var forcegcperiod int64 = 2 * 60 * 1e9
6579
6580
6581
6582
6583 const haveSysmon = GOARCH != "wasm" && GOARCH != "wasm32"
6584
6585
6586
6587
6588 func sysmon() {
6589 lock(&sched.lock)
6590 sched.nmsys++
6591 checkdead()
6592 unlock(&sched.lock)
6593
6594 lastgomaxprocs := int64(0)
6595 lasttrace := int64(0)
6596 idle := 0
6597 delay := uint32(0)
6598
6599 for {
6600 if idle == 0 {
6601 delay = 20
6602 } else if idle > 50 {
6603 delay *= 2
6604 }
6605 if delay > 10*1000 {
6606 delay = 10 * 1000
6607 }
6608 usleep(delay)
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625 now := nanotime()
6626 if debug.schedtrace <= 0 && (sched.gcwaiting.Load() || sched.npidle.Load() == gomaxprocs) {
6627 lock(&sched.lock)
6628 if sched.gcwaiting.Load() || sched.npidle.Load() == gomaxprocs {
6629 syscallWake := false
6630 next := timeSleepUntil()
6631 if next > now {
6632 sched.sysmonwait.Store(true)
6633 unlock(&sched.lock)
6634
6635
6636 sleep := forcegcperiod / 2
6637 if next-now < sleep {
6638 sleep = next - now
6639 }
6640 shouldRelax := sleep >= osRelaxMinNS
6641 if shouldRelax {
6642 osRelax(true)
6643 }
6644 syscallWake = notetsleep(&sched.sysmonnote, sleep)
6645 if shouldRelax {
6646 osRelax(false)
6647 }
6648 lock(&sched.lock)
6649 sched.sysmonwait.Store(false)
6650 noteclear(&sched.sysmonnote)
6651 }
6652 if syscallWake {
6653 idle = 0
6654 delay = 20
6655 }
6656 }
6657 unlock(&sched.lock)
6658 }
6659
6660 lock(&sched.sysmonlock)
6661
6662
6663 now = nanotime()
6664
6665
6666 if *cgo_yield != nil {
6667 asmcgocall(*cgo_yield, nil)
6668 }
6669
6670 lastpoll := sched.lastpoll.Load()
6671 if netpollinited() && lastpoll != 0 && lastpoll+10*1000*1000 < now {
6672 sched.lastpoll.CompareAndSwap(lastpoll, now)
6673 list, delta := netpoll(0)
6674 if !list.empty() {
6675
6676
6677
6678
6679
6680
6681
6682 incidlelocked(-1)
6683 injectglist(&list)
6684 incidlelocked(1)
6685 netpollAdjustWaiters(delta)
6686 }
6687 }
6688
6689 if debug.updatemaxprocs != 0 && lastgomaxprocs+1e9 <= now {
6690 sysmonUpdateGOMAXPROCS()
6691 lastgomaxprocs = now
6692 }
6693 if scavenger.sysmonWake.Load() != 0 {
6694
6695 scavenger.wake()
6696 }
6697
6698
6699 if retake(now) != 0 {
6700 idle = 0
6701 } else {
6702 idle++
6703 }
6704
6705 if t := (gcTrigger{kind: gcTriggerTime, now: now}); t.test() && forcegc.idle.Load() {
6706 lock(&forcegc.lock)
6707 forcegc.idle.Store(false)
6708 var list gList
6709 list.push(forcegc.g)
6710 injectglist(&list)
6711 unlock(&forcegc.lock)
6712 }
6713 if debug.schedtrace > 0 && lasttrace+int64(debug.schedtrace)*1000000 <= now {
6714 lasttrace = now
6715 schedtrace(debug.scheddetail > 0)
6716 }
6717 unlock(&sched.sysmonlock)
6718 }
6719 }
6720
6721 type sysmontick struct {
6722 schedtick uint32
6723 syscalltick uint32
6724 schedwhen int64
6725 syscallwhen int64
6726 }
6727
6728
6729
6730 const forcePreemptNS = 10 * 1000 * 1000
6731
6732 func retake(now int64) uint32 {
6733 n := 0
6734
6735
6736 lock(&allpLock)
6737
6738
6739
6740 for i := 0; i < len(allp); i++ {
6741
6742
6743
6744
6745
6746
6747
6748
6749 pp := allp[i]
6750 if pp == nil || atomic.Load(&pp.status) != _Prunning {
6751
6752
6753 continue
6754 }
6755 pd := &pp.sysmontick
6756 sysretake := false
6757
6758
6759
6760
6761
6762 schedt := int64(pp.schedtick)
6763 if int64(pd.schedtick) != schedt {
6764 pd.schedtick = uint32(schedt)
6765 pd.schedwhen = now
6766 } else if pd.schedwhen+forcePreemptNS <= now {
6767 preemptone(pp)
6768
6769
6770
6771
6772 sysretake = true
6773 }
6774
6775
6776 unlock(&allpLock)
6777
6778
6779
6780
6781
6782
6783
6784
6785 incidlelocked(-1)
6786
6787
6788 thread, ok := setBlockOnExitSyscall(pp)
6789 if !ok {
6790
6791 goto done
6792 }
6793
6794
6795 if syst := int64(pp.syscalltick); !sysretake && int64(pd.syscalltick) != syst {
6796 pd.syscalltick = uint32(syst)
6797 pd.syscallwhen = now
6798 thread.resume()
6799 goto done
6800 }
6801
6802
6803
6804
6805 if runqempty(pp) && sched.nmspinning.Load()+sched.npidle.Load() > 0 && pd.syscallwhen+10*1000*1000 > now {
6806 thread.resume()
6807 goto done
6808 }
6809
6810
6811
6812 thread.takeP()
6813 thread.resume()
6814 n++
6815
6816
6817 handoffp(pp)
6818
6819
6820
6821 done:
6822 incidlelocked(1)
6823 lock(&allpLock)
6824 }
6825 unlock(&allpLock)
6826 return uint32(n)
6827 }
6828
6829
6830
6831 type syscallingThread struct {
6832 gp *g
6833 mp *m
6834 pp *p
6835 status uint32
6836 }
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852 func setBlockOnExitSyscall(pp *p) (syscallingThread, bool) {
6853 if pp.status != _Prunning {
6854 return syscallingThread{}, false
6855 }
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867 mp := pp.m.ptr()
6868 if mp == nil {
6869
6870 return syscallingThread{}, false
6871 }
6872 gp := mp.curg
6873 if gp == nil {
6874
6875 return syscallingThread{}, false
6876 }
6877 status := readgstatus(gp) &^ _Gscan
6878
6879
6880
6881
6882 if status != _Gsyscall && status != _Gdeadextra {
6883
6884 return syscallingThread{}, false
6885 }
6886 if !castogscanstatus(gp, status, status|_Gscan) {
6887
6888 return syscallingThread{}, false
6889 }
6890 if gp.m != mp || gp.m.p.ptr() != pp {
6891
6892 casfrom_Gscanstatus(gp, status|_Gscan, status)
6893 return syscallingThread{}, false
6894 }
6895 return syscallingThread{gp, mp, pp, status}, true
6896 }
6897
6898
6899
6900
6901
6902 func (s syscallingThread) gcstopP() {
6903 assertLockHeld(&sched.lock)
6904
6905 s.releaseP(_Pgcstop)
6906 s.pp.gcStopTime = nanotime()
6907 sched.stopwait--
6908 }
6909
6910
6911
6912 func (s syscallingThread) takeP() {
6913 s.releaseP(_Pidle)
6914 }
6915
6916
6917
6918
6919 func (s syscallingThread) releaseP(state uint32) {
6920 if state != _Pidle && state != _Pgcstop {
6921 throw("attempted to release P into a bad state")
6922 }
6923 trace := traceAcquire()
6924 s.pp.m = 0
6925 s.mp.p = 0
6926 atomic.Store(&s.pp.status, state)
6927 if trace.ok() {
6928 trace.ProcSteal(s.pp)
6929 traceRelease(trace)
6930 }
6931 addGSyscallNoP(s.mp)
6932 s.pp.syscalltick++
6933 }
6934
6935
6936 func (s syscallingThread) resume() {
6937 casfrom_Gscanstatus(s.gp, s.status|_Gscan, s.status)
6938 }
6939
6940
6941
6942
6943
6944
6945 func preemptall() bool {
6946 res := false
6947 for _, pp := range allp {
6948 if pp.status != _Prunning {
6949 continue
6950 }
6951 if preemptone(pp) {
6952 res = true
6953 }
6954 }
6955 return res
6956 }
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968 func preemptone(pp *p) bool {
6969 mp := pp.m.ptr()
6970 if mp == nil || mp == getg().m {
6971 return false
6972 }
6973 gp := mp.curg
6974 if gp == nil || gp == mp.g0 {
6975 return false
6976 }
6977 if s := readgstatus(gp) &^ _Gscan; s == _Gsyscall || s == _Gdeadextra {
6978
6979
6980 return false
6981 }
6982
6983 gp.preempt = true
6984
6985
6986
6987
6988
6989 gp.stackguard0 = stackPreempt
6990
6991
6992 if preemptMSupported && debug.asyncpreemptoff == 0 {
6993 pp.preempt = true
6994
6995
6996 if castogscanstatus(gp, _Grunning, _Gscanrunning) {
6997 if gp.m == mp {
6998 preemptM(gp)
6999 } else {
7000 casfrom_Gscanstatus(gp, _Gscanrunning, _Grunning)
7001 }
7002 }
7003 }
7004
7005 return true
7006 }
7007
7008 var starttime int64
7009
7010 func schedtrace(detailed bool) {
7011 now := nanotime()
7012 if starttime == 0 {
7013 starttime = now
7014 }
7015
7016 lock(&sched.lock)
7017 print("SCHED ", (now-starttime)/1e6, "ms: gomaxprocs=", gomaxprocs, " idleprocs=", sched.npidle.Load(), " threads=", mcount(), " spinningthreads=", sched.nmspinning.Load(), " needspinning=", sched.needspinning.Load(), " idlethreads=", sched.nmidle, " runqueue=", sched.runq.size)
7018 if detailed {
7019 print(" gcwaiting=", sched.gcwaiting.Load(), " nmidlelocked=", sched.nmidlelocked, " stopwait=", sched.stopwait, " sysmonwait=", sched.sysmonwait.Load(), "\n")
7020 }
7021
7022
7023
7024 for i, pp := range allp {
7025 h := atomic.Load(&pp.runqhead)
7026 t := atomic.Load(&pp.runqtail)
7027 if detailed {
7028 print(" P", i, ": status=", pp.status, " schedtick=", pp.schedtick, " syscalltick=", pp.syscalltick, " m=")
7029 mp := pp.m.ptr()
7030 if mp != nil {
7031 print(mp.id)
7032 } else {
7033 print("nil")
7034 }
7035 print(" runqsize=", t-h, " gfreecnt=", pp.gFree.size, " timerslen=", len(pp.timers.heap), "\n")
7036 } else {
7037
7038
7039 print(" ")
7040 if i == 0 {
7041 print("[ ")
7042 }
7043 print(t - h)
7044 if i == len(allp)-1 {
7045 print(" ]")
7046 }
7047 }
7048 }
7049
7050 if !detailed {
7051
7052 print(" schedticks=[ ")
7053 for _, pp := range allp {
7054 print(pp.schedtick)
7055 print(" ")
7056 }
7057 print("]\n")
7058 }
7059
7060 if !detailed {
7061 unlock(&sched.lock)
7062 return
7063 }
7064
7065 for mp := allm; mp != nil; mp = mp.alllink {
7066 pp := mp.p.ptr()
7067 print(" M", mp.id, ": p=")
7068 if pp != nil {
7069 print(pp.id)
7070 } else {
7071 print("nil")
7072 }
7073 print(" curg=")
7074 if mp.curg != nil {
7075 print(mp.curg.goid)
7076 } else {
7077 print("nil")
7078 }
7079 print(" mallocing=", mp.mallocing, " throwing=", mp.throwing, " preemptoff=", mp.preemptoff, " locks=", mp.locks, " dying=", mp.dying, " spinning=", mp.spinning, " blocked=", mp.blocked, " lockedg=")
7080 if lockedg := mp.lockedg.ptr(); lockedg != nil {
7081 print(lockedg.goid)
7082 } else {
7083 print("nil")
7084 }
7085 print("\n")
7086 }
7087
7088 forEachG(func(gp *g) {
7089 print(" G", gp.goid, ": status=", readgstatus(gp), "(", gp.waitreason.String(), ") m=")
7090 if gp.m != nil {
7091 print(gp.m.id)
7092 } else {
7093 print("nil")
7094 }
7095 print(" lockedm=")
7096 if lockedm := gp.lockedm.ptr(); lockedm != nil {
7097 print(lockedm.id)
7098 } else {
7099 print("nil")
7100 }
7101 print("\n")
7102 })
7103 unlock(&sched.lock)
7104 }
7105
7106 type updateMaxProcsGState struct {
7107 lock mutex
7108 g *g
7109 idle atomic.Bool
7110
7111
7112 procs int32
7113 }
7114
7115 var (
7116
7117
7118 updatemaxprocs = &godebugInc{name: "updatemaxprocs"}
7119
7120
7121
7122 updateMaxProcsG updateMaxProcsGState
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171 computeMaxProcsLock mutex
7172 )
7173
7174
7175
7176
7177 func defaultGOMAXPROCSUpdateEnable() {
7178 if debug.updatemaxprocs == 0 {
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190 updatemaxprocs.IncNonDefault()
7191 return
7192 }
7193
7194 go updateMaxProcsGoroutine()
7195 }
7196
7197 func updateMaxProcsGoroutine() {
7198 updateMaxProcsG.g = getg()
7199 lockInit(&updateMaxProcsG.lock, lockRankUpdateMaxProcsG)
7200 for {
7201 lock(&updateMaxProcsG.lock)
7202 if updateMaxProcsG.idle.Load() {
7203 throw("updateMaxProcsGoroutine: phase error")
7204 }
7205 updateMaxProcsG.idle.Store(true)
7206 goparkunlock(&updateMaxProcsG.lock, waitReasonUpdateGOMAXPROCSIdle, traceBlockSystemGoroutine, 1)
7207
7208
7209 stw := stopTheWorldGC(stwGOMAXPROCS)
7210
7211
7212 lock(&sched.lock)
7213 custom := sched.customGOMAXPROCS
7214 unlock(&sched.lock)
7215 if custom {
7216 startTheWorldGC(stw)
7217 return
7218 }
7219
7220
7221
7222
7223
7224 newprocs = updateMaxProcsG.procs
7225 lock(&sched.lock)
7226 sched.customGOMAXPROCS = false
7227 unlock(&sched.lock)
7228
7229 startTheWorldGC(stw)
7230 }
7231 }
7232
7233 func sysmonUpdateGOMAXPROCS() {
7234
7235 lock(&computeMaxProcsLock)
7236
7237
7238 lock(&sched.lock)
7239 custom := sched.customGOMAXPROCS
7240 curr := gomaxprocs
7241 unlock(&sched.lock)
7242 if custom {
7243 unlock(&computeMaxProcsLock)
7244 return
7245 }
7246
7247
7248 procs := defaultGOMAXPROCS(0)
7249 unlock(&computeMaxProcsLock)
7250 if procs == curr {
7251
7252 return
7253 }
7254
7255
7256
7257
7258 if updateMaxProcsG.idle.Load() {
7259 lock(&updateMaxProcsG.lock)
7260 updateMaxProcsG.procs = procs
7261 updateMaxProcsG.idle.Store(false)
7262 var list gList
7263 list.push(updateMaxProcsG.g)
7264 injectglist(&list)
7265 unlock(&updateMaxProcsG.lock)
7266 }
7267 }
7268
7269
7270
7271
7272
7273
7274 func schedEnableUser(enable bool) {
7275 lock(&sched.lock)
7276 if sched.disable.user == !enable {
7277 unlock(&sched.lock)
7278 return
7279 }
7280 sched.disable.user = !enable
7281 if enable {
7282 n := sched.disable.runnable.size
7283 globrunqputbatch(&sched.disable.runnable)
7284 unlock(&sched.lock)
7285 for ; n != 0 && sched.npidle.Load() != 0; n-- {
7286 startm(nil, false, false)
7287 }
7288 } else {
7289 unlock(&sched.lock)
7290 }
7291 }
7292
7293
7294
7295
7296
7297 func schedEnabled(gp *g) bool {
7298 assertLockHeld(&sched.lock)
7299
7300 if sched.disable.user {
7301 return isSystemGoroutine(gp, true)
7302 }
7303 return true
7304 }
7305
7306
7307
7308
7309
7310
7311 func mput(mp *m) {
7312 assertLockHeld(&sched.lock)
7313
7314 sched.midle.push(unsafe.Pointer(mp))
7315 sched.nmidle++
7316 checkdead()
7317 }
7318
7319
7320
7321
7322
7323
7324 func mget() *m {
7325 assertLockHeld(&sched.lock)
7326
7327 mp := (*m)(sched.midle.pop())
7328 if mp != nil {
7329 sched.nmidle--
7330 }
7331 return mp
7332 }
7333
7334
7335
7336
7337
7338
7339
7340
7341 func mgetSpecific(mp *m) *m {
7342 assertLockHeld(&sched.lock)
7343
7344 if mp.idleNode.prev == 0 && mp.idleNode.next == 0 {
7345
7346 return nil
7347 }
7348
7349 sched.midle.remove(unsafe.Pointer(mp))
7350 sched.nmidle--
7351
7352 return mp
7353 }
7354
7355
7356
7357
7358
7359
7360 func globrunqput(gp *g) {
7361 assertLockHeld(&sched.lock)
7362
7363 sched.runq.pushBack(gp)
7364 }
7365
7366
7367
7368
7369
7370
7371 func globrunqputhead(gp *g) {
7372 assertLockHeld(&sched.lock)
7373
7374 sched.runq.push(gp)
7375 }
7376
7377
7378
7379
7380
7381
7382
7383 func globrunqputbatch(batch *gQueue) {
7384 assertLockHeld(&sched.lock)
7385
7386 sched.runq.pushBackAll(*batch)
7387 *batch = gQueue{}
7388 }
7389
7390
7391
7392 func globrunqget() *g {
7393 assertLockHeld(&sched.lock)
7394
7395 if sched.runq.size == 0 {
7396 return nil
7397 }
7398
7399 return sched.runq.pop()
7400 }
7401
7402
7403
7404 func globrunqgetbatch(n int32) (gp *g, q gQueue) {
7405 assertLockHeld(&sched.lock)
7406
7407 if sched.runq.size == 0 {
7408 return
7409 }
7410
7411 n = min(n, sched.runq.size, sched.runq.size/gomaxprocs+1)
7412
7413 gp = sched.runq.pop()
7414 n--
7415
7416 for ; n > 0; n-- {
7417 gp1 := sched.runq.pop()
7418 q.pushBack(gp1)
7419 }
7420 return
7421 }
7422
7423
7424 type pMask []uint32
7425
7426
7427 func (p pMask) read(id uint32) bool {
7428 word := id / 32
7429 mask := uint32(1) << (id % 32)
7430 return (atomic.Load(&p[word]) & mask) != 0
7431 }
7432
7433
7434 func (p pMask) set(id int32) {
7435 word := id / 32
7436 mask := uint32(1) << (id % 32)
7437 atomic.Or(&p[word], mask)
7438 }
7439
7440
7441 func (p pMask) clear(id int32) {
7442 word := id / 32
7443 mask := uint32(1) << (id % 32)
7444 atomic.And(&p[word], ^mask)
7445 }
7446
7447
7448 func (p pMask) any() bool {
7449 for i := range p {
7450 if atomic.Load(&p[i]) != 0 {
7451 return true
7452 }
7453 }
7454 return false
7455 }
7456
7457
7458
7459
7460
7461 func (p pMask) resize(nprocs int32) pMask {
7462 maskWords := (nprocs + 31) / 32
7463
7464 if maskWords <= int32(cap(p)) {
7465 return p[:maskWords]
7466 }
7467 newMask := make([]uint32, maskWords)
7468
7469 copy(newMask, p)
7470 return newMask
7471 }
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484 func pidleput(pp *p, now int64) int64 {
7485 assertLockHeld(&sched.lock)
7486
7487 if !runqempty(pp) {
7488 throw("pidleput: P has non-empty run queue")
7489 }
7490 if now == 0 {
7491 now = nanotime()
7492 }
7493 if pp.timers.len.Load() == 0 {
7494 timerpMask.clear(pp.id)
7495 }
7496 idlepMask.set(pp.id)
7497 pp.link = sched.pidle
7498 sched.pidle.set(pp)
7499 sched.npidle.Add(1)
7500 if !pp.limiterEvent.start(limiterEventIdle, now) {
7501 throw("must be able to track idle limiter event")
7502 }
7503 return now
7504 }
7505
7506
7507
7508
7509
7510
7511
7512
7513 func pidleget(now int64) (*p, int64) {
7514 assertLockHeld(&sched.lock)
7515
7516 pp := sched.pidle.ptr()
7517 if pp != nil {
7518
7519 if now == 0 {
7520 now = nanotime()
7521 }
7522 timerpMask.set(pp.id)
7523 idlepMask.clear(pp.id)
7524 sched.pidle = pp.link
7525 sched.npidle.Add(-1)
7526 pp.limiterEvent.stop(limiterEventIdle, now)
7527 }
7528 return pp, now
7529 }
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541 func pidlegetSpinning(now int64) (*p, int64) {
7542 assertLockHeld(&sched.lock)
7543
7544 pp, now := pidleget(now)
7545 if pp == nil {
7546
7547
7548
7549 sched.needspinning.Store(1)
7550 return nil, now
7551 }
7552
7553 return pp, now
7554 }
7555
7556
7557
7558 func runqempty(pp *p) bool {
7559
7560
7561
7562
7563 for {
7564 head := atomic.Load(&pp.runqhead)
7565 tail := atomic.Load(&pp.runqtail)
7566 runnext := atomic.Loaduintptr((*uintptr)(unsafe.Pointer(&pp.runnext)))
7567 if tail == atomic.Load(&pp.runqtail) {
7568 return head == tail && runnext == 0
7569 }
7570 }
7571 }
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582 const randomizeScheduler = raceenabled
7583
7584
7585
7586
7587
7588
7589 func runqput(pp *p, gp *g, next bool) {
7590 if !haveSysmon && next {
7591
7592
7593
7594
7595
7596
7597
7598
7599 next = false
7600 }
7601 if randomizeScheduler && next && randn(2) == 0 {
7602 next = false
7603 }
7604
7605 if next {
7606 retryNext:
7607 oldnext := pp.runnext
7608 if !pp.runnext.cas(oldnext, guintptr(unsafe.Pointer(gp))) {
7609 goto retryNext
7610 }
7611 if oldnext == 0 {
7612 return
7613 }
7614
7615 gp = oldnext.ptr()
7616 }
7617
7618 retry:
7619 h := atomic.LoadAcq(&pp.runqhead)
7620 t := pp.runqtail
7621 if t-h < uint32(len(pp.runq)) {
7622 pp.runq[t%uint32(len(pp.runq))].set(gp)
7623 atomic.StoreRel(&pp.runqtail, t+1)
7624 return
7625 }
7626 if runqputslow(pp, gp, h, t) {
7627 return
7628 }
7629
7630 goto retry
7631 }
7632
7633
7634
7635 func runqputslow(pp *p, gp *g, h, t uint32) bool {
7636 var batch [len(pp.runq)/2 + 1]*g
7637
7638
7639 n := t - h
7640 n = n / 2
7641 if n != uint32(len(pp.runq)/2) {
7642 throw("runqputslow: queue is not full")
7643 }
7644 for i := uint32(0); i < n; i++ {
7645 batch[i] = pp.runq[(h+i)%uint32(len(pp.runq))].ptr()
7646 }
7647 if !atomic.CasRel(&pp.runqhead, h, h+n) {
7648 return false
7649 }
7650 batch[n] = gp
7651
7652 if randomizeScheduler {
7653 for i := uint32(1); i <= n; i++ {
7654 j := cheaprandn(i + 1)
7655 batch[i], batch[j] = batch[j], batch[i]
7656 }
7657 }
7658
7659
7660 for i := uint32(0); i < n; i++ {
7661 batch[i].schedlink.set(batch[i+1])
7662 }
7663
7664 q := gQueue{batch[0].guintptr(), batch[n].guintptr(), int32(n + 1)}
7665
7666
7667 lock(&sched.lock)
7668 globrunqputbatch(&q)
7669 unlock(&sched.lock)
7670 return true
7671 }
7672
7673
7674
7675
7676 func runqputbatch(pp *p, q *gQueue) {
7677 if q.empty() {
7678 return
7679 }
7680 h := atomic.LoadAcq(&pp.runqhead)
7681 t := pp.runqtail
7682 n := uint32(0)
7683 for !q.empty() && t-h < uint32(len(pp.runq)) {
7684 gp := q.pop()
7685 pp.runq[t%uint32(len(pp.runq))].set(gp)
7686 t++
7687 n++
7688 }
7689
7690 if randomizeScheduler {
7691 off := func(o uint32) uint32 {
7692 return (pp.runqtail + o) % uint32(len(pp.runq))
7693 }
7694 for i := uint32(1); i < n; i++ {
7695 j := cheaprandn(i + 1)
7696 pp.runq[off(i)], pp.runq[off(j)] = pp.runq[off(j)], pp.runq[off(i)]
7697 }
7698 }
7699
7700 atomic.StoreRel(&pp.runqtail, t)
7701
7702 return
7703 }
7704
7705
7706
7707
7708
7709 func runqget(pp *p) (gp *g, inheritTime bool) {
7710
7711 next := pp.runnext
7712
7713
7714
7715 if next != 0 && pp.runnext.cas(next, 0) {
7716 return next.ptr(), true
7717 }
7718
7719 for {
7720 h := atomic.LoadAcq(&pp.runqhead)
7721 t := pp.runqtail
7722 if t == h {
7723 return nil, false
7724 }
7725 gp := pp.runq[h%uint32(len(pp.runq))].ptr()
7726 if atomic.CasRel(&pp.runqhead, h, h+1) {
7727 return gp, false
7728 }
7729 }
7730 }
7731
7732
7733
7734 func runqdrain(pp *p) (drainQ gQueue) {
7735 oldNext := pp.runnext
7736 if oldNext != 0 && pp.runnext.cas(oldNext, 0) {
7737 drainQ.pushBack(oldNext.ptr())
7738 }
7739
7740 retry:
7741 h := atomic.LoadAcq(&pp.runqhead)
7742 t := pp.runqtail
7743 qn := t - h
7744 if qn == 0 {
7745 return
7746 }
7747 if qn > uint32(len(pp.runq)) {
7748 goto retry
7749 }
7750
7751 if !atomic.CasRel(&pp.runqhead, h, h+qn) {
7752 goto retry
7753 }
7754
7755
7756
7757
7758
7759
7760
7761
7762 for i := uint32(0); i < qn; i++ {
7763 gp := pp.runq[(h+i)%uint32(len(pp.runq))].ptr()
7764 drainQ.pushBack(gp)
7765 }
7766 return
7767 }
7768
7769
7770
7771
7772
7773 func runqgrab(pp *p, batch *[256]guintptr, batchHead uint32, stealRunNextG bool) uint32 {
7774 for {
7775 h := atomic.LoadAcq(&pp.runqhead)
7776 t := atomic.LoadAcq(&pp.runqtail)
7777 n := t - h
7778 n = n - n/2
7779 if n == 0 {
7780 if stealRunNextG {
7781
7782 if next := pp.runnext; next != 0 {
7783 if pp.status == _Prunning {
7784 if mp := pp.m.ptr(); mp != nil {
7785 if gp := mp.curg; gp == nil || readgstatus(gp)&^_Gscan != _Gsyscall {
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805 stealRunnextSleep(3000)
7806 if sched.gcwaiting.Load() {
7807
7808
7809 return 0
7810 }
7811 }
7812 }
7813 }
7814 if !pp.runnext.cas(next, 0) {
7815 continue
7816 }
7817 batch[batchHead%uint32(len(batch))] = next
7818 return 1
7819 }
7820 }
7821 return 0
7822 }
7823 if n > uint32(len(pp.runq)/2) {
7824 continue
7825 }
7826 for i := uint32(0); i < n; i++ {
7827 g := pp.runq[(h+i)%uint32(len(pp.runq))]
7828 batch[(batchHead+i)%uint32(len(batch))] = g
7829 }
7830 if atomic.CasRel(&pp.runqhead, h, h+n) {
7831 return n
7832 }
7833 }
7834 }
7835
7836
7837
7838
7839 func runqsteal(pp, p2 *p, stealRunNextG bool) *g {
7840 t := pp.runqtail
7841 n := runqgrab(p2, &pp.runq, t, stealRunNextG)
7842 if n == 0 {
7843 return nil
7844 }
7845 n--
7846 gp := pp.runq[(t+n)%uint32(len(pp.runq))].ptr()
7847 if n == 0 {
7848 return gp
7849 }
7850 h := atomic.LoadAcq(&pp.runqhead)
7851 if t-h+n >= uint32(len(pp.runq)) {
7852 throw("runqsteal: runq overflow")
7853 }
7854 atomic.StoreRel(&pp.runqtail, t+n)
7855 return gp
7856 }
7857
7858
7859
7860 type gQueue struct {
7861 head guintptr
7862 tail guintptr
7863 size int32
7864 }
7865
7866
7867 func (q *gQueue) empty() bool {
7868 return q.head == 0
7869 }
7870
7871
7872 func (q *gQueue) push(gp *g) {
7873 gp.schedlink = q.head
7874 q.head.set(gp)
7875 if q.tail == 0 {
7876 q.tail.set(gp)
7877 }
7878 q.size++
7879 }
7880
7881
7882 func (q *gQueue) pushBack(gp *g) {
7883 gp.schedlink = 0
7884 if q.tail != 0 {
7885 q.tail.ptr().schedlink.set(gp)
7886 } else {
7887 q.head.set(gp)
7888 }
7889 q.tail.set(gp)
7890 q.size++
7891 }
7892
7893
7894
7895 func (q *gQueue) pushBackAll(q2 gQueue) {
7896 if q2.tail == 0 {
7897 return
7898 }
7899 q2.tail.ptr().schedlink = 0
7900 if q.tail != 0 {
7901 q.tail.ptr().schedlink = q2.head
7902 } else {
7903 q.head = q2.head
7904 }
7905 q.tail = q2.tail
7906 q.size += q2.size
7907 }
7908
7909
7910
7911 func (q *gQueue) pop() *g {
7912 gp := q.head.ptr()
7913 if gp != nil {
7914 q.head = gp.schedlink
7915 if q.head == 0 {
7916 q.tail = 0
7917 }
7918 q.size--
7919 }
7920 return gp
7921 }
7922
7923
7924 func (q *gQueue) popList() gList {
7925 stack := gList{q.head, q.size}
7926 *q = gQueue{}
7927 return stack
7928 }
7929
7930
7931
7932 type gList struct {
7933 head guintptr
7934 size int32
7935 }
7936
7937
7938 func (l *gList) empty() bool {
7939 return l.head == 0
7940 }
7941
7942
7943 func (l *gList) push(gp *g) {
7944 gp.schedlink = l.head
7945 l.head.set(gp)
7946 l.size++
7947 }
7948
7949
7950 func (l *gList) pushAll(q gQueue) {
7951 if !q.empty() {
7952 q.tail.ptr().schedlink = l.head
7953 l.head = q.head
7954 l.size += q.size
7955 }
7956 }
7957
7958
7959 func (l *gList) pop() *g {
7960 gp := l.head.ptr()
7961 if gp != nil {
7962 l.head = gp.schedlink
7963 l.size--
7964 }
7965 return gp
7966 }
7967
7968
7969 func setMaxThreads(in int) (out int) {
7970 lock(&sched.lock)
7971 out = int(sched.maxmcount)
7972 if in > 0x7fffffff {
7973 sched.maxmcount = 0x7fffffff
7974 } else {
7975 sched.maxmcount = int32(in)
7976 }
7977 checkmcount()
7978 unlock(&sched.lock)
7979 return
7980 }
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994 func procPin() int {
7995 gp := getg()
7996 mp := gp.m
7997
7998 mp.locks++
7999 return int(mp.p.ptr().id)
8000 }
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014 func procUnpin() {
8015 gp := getg()
8016 gp.m.locks--
8017 }
8018
8019
8020
8021 func sync_runtime_procPin() int {
8022 return procPin()
8023 }
8024
8025
8026
8027 func sync_runtime_procUnpin() {
8028 procUnpin()
8029 }
8030
8031
8032
8033 func sync_atomic_runtime_procPin() int {
8034 return procPin()
8035 }
8036
8037
8038
8039 func sync_atomic_runtime_procUnpin() {
8040 procUnpin()
8041 }
8042
8043
8044
8045
8046
8047 func internal_sync_runtime_canSpin(i int) bool {
8048
8049
8050
8051
8052
8053 if i >= active_spin || numCPUStartup <= 1 || gomaxprocs <= sched.npidle.Load()+sched.nmspinning.Load()+1 {
8054 return false
8055 }
8056 if p := getg().m.p.ptr(); !runqempty(p) {
8057 return false
8058 }
8059 return true
8060 }
8061
8062
8063
8064 func internal_sync_runtime_doSpin() {
8065 procyield(active_spin_cnt)
8066 }
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082 func sync_runtime_canSpin(i int) bool {
8083 return internal_sync_runtime_canSpin(i)
8084 }
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098 func sync_runtime_doSpin() {
8099 internal_sync_runtime_doSpin()
8100 }
8101
8102 var stealOrder randomOrder
8103
8104
8105
8106
8107
8108 type randomOrder struct {
8109 count uint32
8110 coprimes []uint32
8111 }
8112
8113 type randomEnum struct {
8114 i uint32
8115 count uint32
8116 pos uint32
8117 inc uint32
8118 }
8119
8120 func (ord *randomOrder) reset(count uint32) {
8121 ord.count = count
8122 ord.coprimes = ord.coprimes[:0]
8123 for i := uint32(1); i <= count; i++ {
8124 if gcd(i, count) == 1 {
8125 ord.coprimes = append(ord.coprimes, i)
8126 }
8127 }
8128 }
8129
8130 func (ord *randomOrder) start(i uint32) randomEnum {
8131 return randomEnum{
8132 count: ord.count,
8133 pos: i % ord.count,
8134 inc: ord.coprimes[i/ord.count%uint32(len(ord.coprimes))],
8135 }
8136 }
8137
8138 func (enum *randomEnum) done() bool {
8139 return enum.i == enum.count
8140 }
8141
8142 func (enum *randomEnum) next() {
8143 enum.i++
8144 enum.pos = (enum.pos + enum.inc) % enum.count
8145 }
8146
8147 func (enum *randomEnum) position() uint32 {
8148 return enum.pos
8149 }
8150
8151 func gcd(a, b uint32) uint32 {
8152 for b != 0 {
8153 a, b = b, a%b
8154 }
8155 return a
8156 }
8157
8158
8159
8160 type initTask struct {
8161 state uint32
8162 nfns uint32
8163
8164 }
8165
8166
8167
8168 var inittrace tracestat
8169
8170 type tracestat struct {
8171 active bool
8172 id uint64
8173 allocs uint64
8174 bytes uint64
8175 }
8176
8177 func doInit(ts []*initTask) {
8178 for _, t := range ts {
8179 doInit1(t)
8180 }
8181 }
8182
8183 func doInit1(t *initTask) {
8184 switch t.state {
8185 case 2:
8186 return
8187 case 1:
8188 throw("recursive call during initialization - linker skew")
8189 default:
8190 t.state = 1
8191
8192 var (
8193 start int64
8194 before tracestat
8195 )
8196
8197 if inittrace.active {
8198 start = nanotime()
8199
8200 before = inittrace
8201 }
8202
8203 if t.nfns == 0 {
8204
8205 throw("inittask with no functions")
8206 }
8207
8208 firstFunc := add(unsafe.Pointer(t), 8)
8209 for i := uint32(0); i < t.nfns; i++ {
8210 p := add(firstFunc, uintptr(i)*goarch.PtrSize)
8211 f := *(*func())(unsafe.Pointer(&p))
8212 f()
8213 }
8214
8215 if inittrace.active {
8216 end := nanotime()
8217
8218 after := inittrace
8219
8220 f := *(*func())(unsafe.Pointer(&firstFunc))
8221 pkg := funcpkgpath(findfunc(abi.FuncPCABIInternal(f)))
8222
8223 var sbuf [24]byte
8224 print("init ", pkg, " @")
8225 print(string(fmtNSAsMS(sbuf[:], uint64(start-runtimeInitTime))), " ms, ")
8226 print(string(fmtNSAsMS(sbuf[:], uint64(end-start))), " ms clock, ")
8227 print(string(itoa(sbuf[:], after.bytes-before.bytes)), " bytes, ")
8228 print(string(itoa(sbuf[:], after.allocs-before.allocs)), " allocs")
8229 print("\n")
8230 }
8231
8232 t.state = 2
8233 }
8234 }
8235
View as plain text