-
-
Notifications
You must be signed in to change notification settings - Fork 504
/
proc.go
5596 lines (5019 loc) · 158 KB
/
proc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package runtime
import (
"internal/cpu"
"runtime/internal/atomic"
"runtime/internal/sys"
"unsafe"
)
var buildVersion = sys.TheVersion
// set using cmd/go/internal/modload.ModInfoProg
var modinfo string
// Goroutine 调度器
// 调度器的任务是给不同的工作线程 (worker thread) 分发 ready-to-run goroutine。
//
// 主要概念:
// G - goroutine.
// M - worker thread, 或 machine.
// P - processor,一种执行 Go 代码被要求资源。M 必须关联一个 P 才能执行 Go 代码,
// 但它可以被阻塞或在一个系统调用中没有关联的 P。
//
// 设计文档:https://golang.org/s/go11sched
// 工作线程的 park/unpark
//
// 我们需要在保持足够的运行 worker thread 来利用有效硬件并发资源,和 park 运行
// 过多的 worker thread 来节约 CPU 能耗之间进行权衡。这个权衡并不简单,有以下两点原因:
// 1. 调度器状态是有意分布的(具体而言,是一个 per-P 的 work 队列),因此在快速路径
// (fast path)计算出全局谓词 (global predicates) 是不可能的。
// 2. 为了获得最佳的线程管理,我们必须知道未来的情况(当一个新的 goroutine 会
// 在不久的将来 ready,不再 park 一个 worker thread)
//
// 这三种被驳回的方法很糟糕:
// 1. 集中式管理所有调度器状态(会将限制可扩展性)
// 2. 直接切换 goroutine。也就是说,当我们 ready 一个新的 goroutine 时,让出一个 P,
// unpark 一个线程并切换到这个线程运行 goroutine。因为 ready 的 goroutine 线程可能
// 在下一个瞬间 out of work,从而导致线程 thrashing(当计算机虚拟内存饱和时会发生
// thrashing,最终导致分页调度状态不再变化。这个状态会一直持续,知道用户关闭一些运行的
// 应用或者活跃进程释放一些虚拟内存资源),因此我们需要 park 这个线程。同样,我们
// 希望在相同的线程内保存维护 goroutine,这种方式还会摧毁计算的局部性原理。
// 3. 任何时候 ready 一个 goroutine 时也存在一个空闲的 P 时,都 unpark 一个额外的线程,
// 但不进行切换。因为额外线程会在没有检查任何 work 的情况下立即 park ,最终导致大量线程的
// parking/unparking。
// 目前方法:
//
// 如果存在一个空闲的 P 并且没有 spinning 状态的工作线程,当 ready 一个 goroutine 时,
// 就 unpark 一个额外的线程。如果一个工作线程的本地队列里没有 work ,且在全局运行队列或 netpoller
// 中也没有 work,则称一个工作线程被称之为 spinning;spinning 状态由 sched.nmspinning 和
// m.spinning 表示。
// 这种方式下被 unpark 的线程同样也成为 spinning,我们也不对这种线程进行 goroutine 切换,
// 因此这类线程最初就是 out of work。spinning 线程会在 park 前,从 per-P 中运行队列中寻找 work。
// 如果一个 spinning 进程发现 work,就会将自身切换出 spinning 状态,并且开始执行。
// 如果它没有发现 work 则会将自己带 spinning 转状态然后进行 park。
//
// 如果至少有一个 spinning 进程(sched.nmspinning>1),则 ready 一个 goroutine 时,
// 不会去 unpark 一个新的线程。作为补偿,如果最后一个 spinning 线程发现 work 并且停止 spinning,
// 则必须 unpark 一个新的 spinning 线程。这个方法消除了不合理的线程 unpark 峰值,
// 且同时保证最终的最大 CPU 并行度利用率。
//
// 主要的实现复杂性表现为当进行 spinning->non-spinning 线程转换时必须非常小心。这种转换在提交一个
// 新的 goroutine ,并且任何一个部分都需要取消另一个工作线程会发生竞争。如果双方均失败,则会以半静态
// CPU 利用不足而结束。ready 一个 goroutine 的通用范式为:提交一个 goroutine 到 per-P 的局部 work 队列,
// #StoreLoad-style 内存屏障,检查 sched.nmspinning。从 spinning->non-spinning 转换的一般模式为:
// 减少 nmspinning, #StoreLoad-style 内存屏障,在所有 per-P 工作队列检查新的 work。注意,此种复杂性
// 并不适用于全局工作队列,因为我们不会蠢到当给一个全局队列提交 work 时进行线程 unpark。更多细节参见
// nmspinning 操作。
var (
m0 m
g0 g
raceprocctx0 uintptr
)
//go:linkname runtime_inittask runtime..inittask
var runtime_inittask initTask
//go:linkname main_inittask main..inittask
var main_inittask initTask
// main_init_done is a signal used by cgocallbackg that initialization
// has been completed. It is made before _cgo_notify_runtime_init_done,
// so all cgo calls can rely on it existing. When main_init is complete,
// it is closed, meaning cgocallbackg can reliably receive from it.
var main_init_done chan bool
//go:linkname main_main main.main
func main_main()
// mainStarted 表示主 M 是否已经开始运行
var mainStarted bool
// runtimeInitTime 是运行时启动的 nanotime()
var runtimeInitTime int64
// 用于新创建的 M 的信号掩码 signal mask 的值。
var initSigmask sigset
// 主 goroutine
func main() {
g := getg()
// race 检测有关,不关心
g.m.g0.racectx = 0
// 执行栈最大限制:1GB(64位系统)或者 250MB(32位系统)
// 这里使用十进制而非二进制的 GB 和 MB 因为在栈溢出失败消息中好看一些
if sys.PtrSize == 8 {
maxstacksize = 1000000000
} else {
maxstacksize = 250000000
}
// 允许 newproc 启动新的 m
mainStarted = true
if GOARCH != "wasm" { // 1.11 新引入的 web assembly, 目前 wasm 不支持线程,无系统监控
// 启动系统后台监控(定期垃圾回收、并发任务调度)
systemstack(func() {
newm(sysmon, nil)
})
}
// 将主 goroutine 锁在主 OS 线程下进行初始化工作
// 大部分程序并不关心这一点,但是有一些图形库(基本上属于 cgo 调用)
// 会要求在主线程下进行初始化工作。
// 即便是在 main.main 下仍然可以通过公共方法 runtime.LockOSThread
// 来强制将一些特殊的需要主 OS 线程的调用锁在主 OS 线程下执行初始化
lockOSThread()
if g.m != &m0 {
throw("runtime.main not on m0")
}
// 执行 runtime.init
doInit(&runtime_inittask) // defer 必须在此调用结束后才能使用
if nanotime() == 0 {
throw("nanotime returning zero")
}
// defer unlock,从而在 init 期间 runtime.Goexit 来 unlock
needUnlock := true
defer func() {
if needUnlock {
unlockOSThread()
}
}()
// 记录程序的启动时间
runtimeInitTime = nanotime()
// 启动垃圾回收器后台操作
gcenable()
main_init_done = make(chan bool)
if iscgo {
if _cgo_thread_start == nil {
throw("_cgo_thread_start missing")
}
if GOOS != "windows" {
if _cgo_setenv == nil {
throw("_cgo_setenv missing")
}
if _cgo_unsetenv == nil {
throw("_cgo_unsetenv missing")
}
}
if _cgo_notify_runtime_init_done == nil {
throw("_cgo_notify_runtime_init_done missing")
}
// 启动模板线程来处理从 C 创建的线程进入 Go 时需要创建一个新的线程的情况。
startTemplateThread()
cgocall(_cgo_notify_runtime_init_done, nil)
}
doInit(&main_inittask)
close(main_init_done) // main.init 执行完毕
needUnlock = false
unlockOSThread()
// 如果是基础库则不需要执行 main 函数了
if isarchive || islibrary {
// 由 -buildmode=c-archive 或 c-shared 但不会执行的程序
return
}
// 执行用户 main 包中的 main 函数
// 处理为非间接调用,因为链接器在设定运行时不知道 main 包的地址
fn := main_main
fn()
// race 相关
if raceenabled {
racefini()
}
// 使客户端程序可行:如果在其他 goroutine 上 panic 、与此同时
// main 返回,也让其他 goroutine 能够完成 panic trace 的打印。
// 打印完成后,立即退出。见 issue 3934 和 20018
if atomic.Load(&runningPanicDefers) != 0 {
// 运行包含 defer 的函数不会花太长时间
for c := 0; c < 1000; c++ {
if atomic.Load(&runningPanicDefers) == 0 {
break
}
Gosched()
}
}
if atomic.Load(&panicking) != 0 {
gopark(nil, nil, waitReasonPanicWait, traceEvGoStop, 1)
}
// 退出执行,返回退出状态码
exit(0)
// 如果 exit 没有被正确实现,则下面的代码能够强制退出程序,因为 *nil (nil deref) 会崩溃。
// http://golang.org/ref/spec#Terminating_statements
// https://github.com/golang/go/commit/c81a0ed3c50606d1ada0fd9b571611b3687c90e1
for {
var x *int32
*x = 0
}
}
// os_beforeExit is called from os.Exit(0).
//go:linkname os_beforeExit os.runtime_beforeExit
func os_beforeExit() {
if raceenabled {
racefini()
}
}
// 启动 forcegc helper goroutine
func init() {
go forcegchelper()
}
func forcegchelper() {
forcegc.g = getg()
for {
lock(&forcegc.lock)
if forcegc.idle != 0 {
throw("forcegc: phase error")
}
atomic.Store(&forcegc.idle, 1)
goparkunlock(&forcegc.lock, waitReasonForceGGIdle, traceEvGoBlock, 1)
// this goroutine is explicitly resumed by sysmon
if debug.gctrace > 0 {
println("GC forced")
}
// Time-triggered, fully concurrent.
gcStart(gcTrigger{kind: gcTriggerTime, now: nanotime()})
}
}
//go:nosplit
// Gosched 会让出当前的 P,并允许其他 goroutine 运行。它不会推迟当前的 goroutine,因此执行会被自动恢复
func Gosched() {
checkTimeouts()
mcall(gosched_m)
}
// goschedguarded yields the processor like gosched, but also checks
// for forbidden states and opts out of the yield in those cases.
//go:nosplit
func goschedguarded() {
mcall(goschedguarded_m)
}
// Puts the current goroutine into a waiting state and calls unlockf.
// If unlockf returns false, the goroutine is resumed.
// unlockf must not access this G's stack, as it may be moved between
// the call to gopark and the call to unlockf.
// Reason explains why the goroutine has been parked.
// It is displayed in stack traces and heap dumps.
// Reasons should be unique and descriptive.
// Do not re-use reasons, add new ones.
func gopark(unlockf func(*g, unsafe.Pointer) bool, lock unsafe.Pointer, reason waitReason, traceEv byte, traceskip int) {
if reason != waitReasonSleep {
checkTimeouts() // timeouts may expire while two goroutines keep the scheduler busy
}
mp := acquirem()
gp := mp.curg
status := readgstatus(gp)
if status != _Grunning && status != _Gscanrunning {
throw("gopark: bad g status")
}
mp.waitlock = lock
mp.waitunlockf = unlockf
gp.waitreason = reason
mp.waittraceev = traceEv
mp.waittraceskip = traceskip
releasem(mp)
// can't do anything that might move the G between Ms here.
mcall(park_m) // 切换到 waiting 状态并重新进入调度循环
}
// 将当前 goroutine 置于等待状态并解锁 lock。
// 通过调用 goready(gp) 可让 goroutine 再次 runnable
func goparkunlock(lock *mutex, reason waitReason, traceEv byte, traceskip int) {
gopark(parkunlock_c, unsafe.Pointer(lock), reason, traceEv, traceskip)
}
func goready(gp *g, traceskip int) {
systemstack(func() {
ready(gp, traceskip, true)
})
}
//go:nosplit
func acquireSudog() *sudog {
// Delicate dance: the semaphore implementation calls
// acquireSudog, acquireSudog calls new(sudog),
// new calls malloc, malloc can call the garbage collector,
// and the garbage collector calls the semaphore implementation
// in stopTheWorld.
// Break the cycle by doing acquirem/releasem around new(sudog).
// The acquirem/releasem increments m.locks during new(sudog),
// which keeps the garbage collector from being invoked.
mp := acquirem()
pp := mp.p.ptr()
if len(pp.sudogcache) == 0 {
lock(&sched.sudoglock)
// First, try to grab a batch from central cache.
for len(pp.sudogcache) < cap(pp.sudogcache)/2 && sched.sudogcache != nil {
s := sched.sudogcache
sched.sudogcache = s.next
s.next = nil
pp.sudogcache = append(pp.sudogcache, s)
}
unlock(&sched.sudoglock)
// If the central cache is empty, allocate a new one.
if len(pp.sudogcache) == 0 {
pp.sudogcache = append(pp.sudogcache, new(sudog))
}
}
n := len(pp.sudogcache)
s := pp.sudogcache[n-1]
pp.sudogcache[n-1] = nil
pp.sudogcache = pp.sudogcache[:n-1]
if s.elem != nil {
throw("acquireSudog: found s.elem != nil in cache")
}
releasem(mp)
return s
}
//go:nosplit
func releaseSudog(s *sudog) {
if s.elem != nil {
throw("runtime: sudog with non-nil elem")
}
if s.isSelect {
throw("runtime: sudog with non-false isSelect")
}
if s.next != nil {
throw("runtime: sudog with non-nil next")
}
if s.prev != nil {
throw("runtime: sudog with non-nil prev")
}
if s.waitlink != nil {
throw("runtime: sudog with non-nil waitlink")
}
if s.c != nil {
throw("runtime: sudog with non-nil c")
}
gp := getg()
if gp.param != nil {
throw("runtime: releaseSudog with non-nil gp.param")
}
mp := acquirem() // avoid rescheduling to another P
pp := mp.p.ptr()
if len(pp.sudogcache) == cap(pp.sudogcache) {
// Transfer half of local cache to the central cache.
var first, last *sudog
for len(pp.sudogcache) > cap(pp.sudogcache)/2 {
n := len(pp.sudogcache)
p := pp.sudogcache[n-1]
pp.sudogcache[n-1] = nil
pp.sudogcache = pp.sudogcache[:n-1]
if first == nil {
first = p
} else {
last.next = p
}
last = p
}
lock(&sched.sudoglock)
last.next = sched.sudogcache
sched.sudogcache = first
unlock(&sched.sudoglock)
}
pp.sudogcache = append(pp.sudogcache, s)
releasem(mp)
}
// funcPC 返回函数 f 的入口 PC。
// 它假设 f 是一个 func 值。否则行为是未定义的。
// 小心:在包含插件的程序中,funcPC 可以对相同的函数返回不同的值(因为在地址空间中相同的函数可能有多个副本)
// 为安全起见,不要在任何 == 表达式中使用此函数。它只在作为地址用于执行代码时是安全的。
//go:nosplit
func funcPC(f interface{}) uintptr {
return *(*uintptr)(efaceOf(&f).data)
}
// called from assembly
func badmcall(fn func(*g)) {
throw("runtime: mcall called on m->g0 stack")
}
func badmcall2(fn func(*g)) {
throw("runtime: mcall function returned")
}
func badreflectcall() {
panic(plainError("arg size to reflect.call more than 1GB"))
}
var badmorestackg0Msg = "fatal: morestack on g0\n"
//go:nosplit
//go:nowritebarrierrec
func badmorestackg0() {
sp := stringStructOf(&badmorestackg0Msg)
write(2, sp.str, int32(sp.len))
}
var badmorestackgsignalMsg = "fatal: morestack on gsignal\n"
//go:nosplit
//go:nowritebarrierrec
func badmorestackgsignal() {
sp := stringStructOf(&badmorestackgsignalMsg)
write(2, sp.str, int32(sp.len))
}
//go:nosplit
func badctxt() {
throw("ctxt != 0")
}
func lockedOSThread() bool {
gp := getg()
return gp.lockedm != 0 && gp.m.lockedg != 0
}
var (
allgs []*g
allglock mutex
)
func allgadd(gp *g) {
if readgstatus(gp) == _Gidle {
throw("allgadd: bad status Gidle")
}
lock(&allglock)
allgs = append(allgs, gp)
allglen = uintptr(len(allgs))
unlock(&allglock)
}
const (
// Number of goroutine ids to grab from sched.goidgen to local per-P cache at once.
// 16 seems to provide enough amortization, but other than that it's mostly arbitrary number.
_GoidCacheBatch = 16
)
// cpuinit 提取环境变量 GODEBUGCPU,如果 GOEXPERIMENT debugcpu 被设置,则还会调用 internal/cpu.initialize
func cpuinit() {
const prefix = "GODEBUG="
var env string
switch GOOS {
case "aix", "darwin", "dragonfly", "freebsd", "netbsd", "openbsd", "illumos", "solaris", "linux":
cpu.DebugOptions = true
// 类似于 goenv_unix 但为 GODEBUG 直接提取了环境变量
// TODO(moehrmann): remove when general goenvs() can be called before cpuinit()
n := int32(0)
for argv_index(argv, argc+1+n) != nil {
n++
}
for i := int32(0); i < n; i++ {
p := argv_index(argv, argc+1+i)
s := *(*string)(unsafe.Pointer(&stringStruct{unsafe.Pointer(p), findnull(p)}))
if hasprefix(s, prefix) {
env = gostring(p)[len(prefix):]
break
}
}
}
cpu.Initialize(env)
// 支持 CPU 特性的变量由编译器生成的代码来阻止指令的执行,从而不能假设总是支持的
x86HasPOPCNT = cpu.X86.HasPOPCNT
x86HasSSE41 = cpu.X86.HasSSE41
x86HasFMA = cpu.X86.HasFMA
armHasVFPv4 = cpu.ARM.HasVFPv4
arm64HasATOMICS = cpu.ARM64.HasATOMICS
}
// 启动顺序
//
// 调用 osinit
// 调用 schedinit
// make & queue new G
// 调用 runtime·mstart
//
// 创建 G 的调用 runtime·main.
func schedinit() {
_g_ := getg()
// 不重要,race 检查有关
// raceinit 必须受限调用竞争检查器 race detector
// 特别的,它必须在 mallocinit 下面的 racemapshadow 之前完成。
if raceenabled {
_g_.racectx, raceprocctx0 = raceinit()
}
// 最大系统线程数量(即 M),参考标准库 runtime/debug.SetMaxThreads
sched.maxmcount = 10000
// 不重要,与 trace 有关
tracebackinit()
// 模块数据验证
moduledataverify()
// 栈、内存分配器、调度器相关初始化。
// 栈初始化,复用管理链表
stackinit()
// 必须在 mcommoninit 之前运行
fastrandinit()
// 内存分配器初始化
mallocinit()
// 初始化当前 M
mcommoninit(_g_.m)
// cpu 相关的初始化
cpuinit() // 必须在 alginit 之前运行
alginit() // maps 不能在此调用之前使用,从 CPU 指令集初始化散列算法
// 模块加载相关的初始化
modulesinit() // 模块链接,提供 activeModules
typelinksinit() // 使用 maps, activeModules
itabsinit() // 初始化 interface table,使用 activeModules
msigsave(_g_.m)
initSigmask = _g_.m.sigmask
// 处理y命令行用户参数和环境变量
goargs()
goenvs()
// 处理 GODEBUG、GOTRACEBACK 调试相关的环境变量设置
parsedebugvars()
// 垃圾回收器初始化
gcinit()
// 网络的上次轮询时间
sched.lastpoll = uint64(nanotime())
// 通过 CPU 核心数和 GOMAXPROCS 环境变量确定 P 的数量
procs := ncpu
if n, ok := atoi32(gogetenv("GOMAXPROCS")); ok && n > 0 {
procs = n
}
// 调整 P 的数量
// 这时所有 P 均为新建的 P,因此不能返回有本地任务的 P
if procresize(procs) != nil {
throw("unknown runnable goroutine during bootstrap")
}
// 不重要,调试相关
// For cgocheck > 1, we turn on the write barrier at all times
// and check all pointer writes. We can't do this until after
// procresize because the write barrier needs a P.
if debug.cgocheck > 1 {
writeBarrier.cgo = true
writeBarrier.enabled = true
for _, p := range allp {
p.wbBuf.reset()
}
}
if buildVersion == "" {
// 该条件永远不会被触发,此处只是为了防止 buildVersion 被编译器优化移除掉。
buildVersion = "unknown"
}
if len(modinfo) == 1 {
// Condition should never trigger. This code just serves
// to ensure runtime·modinfo is kept in the resulting binary.
modinfo = ""
}
}
func dumpgstatus(gp *g) {
_g_ := getg()
print("runtime: gp: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n")
print("runtime: g: g=", _g_, ", goid=", _g_.goid, ", g->atomicstatus=", readgstatus(_g_), "\n")
}
// 检查 m 的数量是否太多
func checkmcount() {
// 此时 sched 是锁住的
if mcount() > sched.maxmcount {
print("runtime: program exceeds ", sched.maxmcount, "-thread limit\n")
throw("thread exhaustion")
}
}
func mcommoninit(mp *m) {
_g_ := getg()
// 检查当前 g 是否是 g0
// g0 栈对用户而言是没有意义的(且不是不可避免的)
if _g_ != _g_.m.g0 {
callers(1, mp.createstack[:])
}
// 锁住调度器
lock(&sched.lock)
// 确保线程数量不会太多而溢出
if sched.mnext+1 < sched.mnext {
throw("runtime: thread ID overflow")
}
// mnext 表示当前 m 的数量,还表示下一个 m 的 id
mp.id = sched.mnext
// 增加 m 的数量
sched.mnext++
// 检查 m 的数量不会太多
checkmcount()
// 用于 fastrand 快速取随机数
mp.fastrand[0] = uint32(int64Hash(uint64(mp.id), fastrandseed))
mp.fastrand[1] = uint32(int64Hash(uint64(cputicks()), ^fastrandseed))
if mp.fastrand[0]|mp.fastrand[1] == 0 {
mp.fastrand[1] = 1
}
// 初始化 gsignal,用于处理 m 上的信号。
mpreinit(mp)
// gsignal 的运行栈边界处理
if mp.gsignal != nil {
mp.gsignal.stackguard1 = mp.gsignal.stack.lo + _StackGuard
}
// 添加到 allm 中,从而当它刚保存到寄存器或本地线程存储时候 GC 不会释放 g->m
// 每一次调用都会讲 allm 给 alllink,给完之后自身被 mp 替换,在下一次的时候由给 alllink
// 从而形成链表
mp.alllink = allm
// NumCgoCall() 会在没有使用 schedlock 时遍历 allm
// 等价于 allm = mp
atomicstorep(unsafe.Pointer(&allm), unsafe.Pointer(mp))
// m 的通用初始化完成,解锁调度器
unlock(&sched.lock)
// 分配内存来保存当 cgo 调用崩溃时候的回溯
if iscgo || GOOS == "solaris" || GOOS == "illumos" || GOOS == "windows" {
mp.cgoCallers = new(cgoCallers)
}
}
var fastrandseed uintptr
func fastrandinit() {
s := (*[unsafe.Sizeof(fastrandseed)]byte)(unsafe.Pointer(&fastrandseed))[:]
getRandomData(s)
}
// 将 gp 标记为 ready 来运行
func ready(gp *g, traceskip int, next bool) {
if trace.enabled {
traceGoUnpark(gp, traceskip)
}
status := readgstatus(gp)
// 标记为 runnable.
_g_ := getg()
mp := acquirem() // 禁止抢占,因为它可以在局部变量中保存 p
if status&^_Gscan != _Gwaiting {
dumpgstatus(gp)
throw("bad g->status in ready")
}
// 状态为 Gwaiting 或 Gscanwaiting, 标记 Grunnable 并将其放入运行队列 runq
casgstatus(gp, _Gwaiting, _Grunnable)
runqput(_g_.m.p.ptr(), gp, next)
if atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 {
wakep()
}
releasem(mp)
}
// freezeStopWait is a large value that freezetheworld sets
// sched.stopwait to in order to request that all Gs permanently stop.
const freezeStopWait = 0x7fffffff
// freezing is set to non-zero if the runtime is trying to freeze the
// world.
var freezing uint32
// Similar to stopTheWorld but best-effort and can be called several times.
// There is no reverse operation, used during crashing.
// This function must not lock any mutexes.
func freezetheworld() {
atomic.Store(&freezing, 1)
// stopwait and preemption requests can be lost
// due to races with concurrently executing threads,
// so try several times
for i := 0; i < 5; i++ {
// this should tell the scheduler to not start any new goroutines
sched.stopwait = freezeStopWait
atomic.Store(&sched.gcwaiting, 1)
// this should stop running goroutines
if !preemptall() {
break // no running goroutines
}
usleep(1000)
}
// to be sure
usleep(1000)
preemptall()
usleep(1000)
}
// All reads and writes of g's status go through readgstatus, casgstatus
// castogscanstatus, casfrom_Gscanstatus.
//go:nosplit
func readgstatus(gp *g) uint32 {
return atomic.Load(&gp.atomicstatus)
}
// The Gscanstatuses are acting like locks and this releases them.
// If it proves to be a performance hit we should be able to make these
// simple atomic stores but for now we are going to throw if
// we see an inconsistent state.
func casfrom_Gscanstatus(gp *g, oldval, newval uint32) {
success := false
// Check that transition is valid.
switch oldval {
default:
print("runtime: casfrom_Gscanstatus bad oldval gp=", gp, ", oldval=", hex(oldval), ", newval=", hex(newval), "\n")
dumpgstatus(gp)
throw("casfrom_Gscanstatus:top gp->status is not in scan state")
case _Gscanrunnable,
_Gscanwaiting,
_Gscanrunning,
_Gscansyscall,
_Gscanpreempted:
if newval == oldval&^_Gscan {
success = atomic.Cas(&gp.atomicstatus, oldval, newval)
}
}
if !success {
print("runtime: casfrom_Gscanstatus failed gp=", gp, ", oldval=", hex(oldval), ", newval=", hex(newval), "\n")
dumpgstatus(gp)
throw("casfrom_Gscanstatus: gp->status is not in scan state")
}
}
// This will return false if the gp is not in the expected status and the cas fails.
// This acts like a lock acquire while the casfromgstatus acts like a lock release.
func castogscanstatus(gp *g, oldval, newval uint32) bool {
switch oldval {
case _Grunnable,
_Grunning,
_Gwaiting,
_Gsyscall:
if newval == oldval|_Gscan {
return atomic.Cas(&gp.atomicstatus, oldval, newval)
}
}
print("runtime: castogscanstatus oldval=", hex(oldval), " newval=", hex(newval), "\n")
throw("castogscanstatus")
panic("not reached")
}
// If asked to move to or from a Gscanstatus this will throw. Use the castogscanstatus
// and casfrom_Gscanstatus instead.
// casgstatus will loop if the g->atomicstatus is in a Gscan status until the routine that
// put it in the Gscan state is finished.
//go:nosplit
func casgstatus(gp *g, oldval, newval uint32) {
if (oldval&_Gscan != 0) || (newval&_Gscan != 0) || oldval == newval {
systemstack(func() {
print("runtime: casgstatus: oldval=", hex(oldval), " newval=", hex(newval), "\n")
throw("casgstatus: bad incoming values")
})
}
// See https://golang.org/cl/21503 for justification of the yield delay.
const yieldDelay = 5 * 1000
var nextYield int64
// loop if gp->atomicstatus is in a scan state giving
// GC time to finish and change the state to oldval.
for i := 0; !atomic.Cas(&gp.atomicstatus, oldval, newval); i++ {
if oldval == _Gwaiting && gp.atomicstatus == _Grunnable {
throw("casgstatus: waiting for Gwaiting but is Grunnable")
}
if i == 0 {
nextYield = nanotime() + yieldDelay
}
if nanotime() < nextYield {
for x := 0; x < 10 && gp.atomicstatus != oldval; x++ {
procyield(1)
}
} else {
osyield()
nextYield = nanotime() + yieldDelay/2
}
}
}
// casgstatus(gp, oldstatus, Gcopystack), assuming oldstatus is Gwaiting or Grunnable.
// Returns old status. Cannot call casgstatus directly, because we are racing with an
// async wakeup that might come in from netpoll. If we see Gwaiting from the readgstatus,
// it might have become Grunnable by the time we get to the cas. If we called casgstatus,
// it would loop waiting for the status to go back to Gwaiting, which it never will.
//go:nosplit
func casgcopystack(gp *g) uint32 {
for {
oldstatus := readgstatus(gp) &^ _Gscan
if oldstatus != _Gwaiting && oldstatus != _Grunnable {
throw("copystack: bad status, not Gwaiting or Grunnable")
}
if atomic.Cas(&gp.atomicstatus, oldstatus, _Gcopystack) {
return oldstatus
}
}
}
// casGToPreemptScan transitions gp from _Grunning to _Gscan|_Gpreempted.
//
// TODO(austin): This is the only status operation that both changes
// the status and locks the _Gscan bit. Rethink this.
func casGToPreemptScan(gp *g, old, new uint32) {
if old != _Grunning || new != _Gscan|_Gpreempted {
throw("bad g transition")
}
for !atomic.Cas(&gp.atomicstatus, _Grunning, _Gscan|_Gpreempted) {
}
}
// casGFromPreempted attempts to transition gp from _Gpreempted to
// _Gwaiting. If successful, the caller is responsible for
// re-scheduling gp.
func casGFromPreempted(gp *g, old, new uint32) bool {
if old != _Gpreempted || new != _Gwaiting {
throw("bad g transition")
}
return atomic.Cas(&gp.atomicstatus, _Gpreempted, _Gwaiting)
}
// stopTheWorld 从正在执行的 goroutine 中停止所有的 P,在 GC 安全点 safe point
// 打断所有 goroutine 并记录打断的原因。作为结果,只有当前 goroutine 的 P 正在运行。
// stopTheWorld 不能在系统栈上调用,调用方也不能持有 worldsema。调用方必须在其他 P
// 应该恢复执行的时候调用 startTheWorld。
//
// stopTheWorld 在多个 goroutine 间同时调用时安全的。每个 goroutine 都会执行自己
// 的 stop,所有的 stop 都会被有序的执行。
//
// 这个函数也会被 stack dump 的 routine 使用。如果系统处于 panic 或 exit 状态,
// 这可能无法可靠地停止所有的 goroutine。
func stopTheWorld(reason string) {
// 抢占 worldsema
semacquire(&worldsema)
getg().m.preemptoff = reason
systemstack(stopTheWorldWithSema)
}
// startTheWorld undoes the effects of stopTheWorld.
func startTheWorld() {
systemstack(func() { startTheWorldWithSema(false) })
// worldsema must be held over startTheWorldWithSema to ensure
// gomaxprocs cannot change while worldsema is held.
semrelease(&worldsema)
getg().m.preemptoff = ""
}
// 持有 worldsema 会授权 M stop the world 的权利。
// 并保护并发的被修改 gomaxprocs
var worldsema uint32 = 1
// stopTheWorldWithSema 是 stopTheWorld 的核心实现。调用方负责抢占 worldsema
// 并经用其可抢占的属性,然后再系统栈上调用 stopTheWorldWithSema:
//
// semacquire(&worldsema, 0)
// m.preemptoff = "reason"
// systemstack(stopTheWorldWithSema)
//
// 当完成时,调用方必须调用 startTheWorld ,或者分别撤销刚才的三个操作:
//
// m.preemptoff = ""
// systemstack(startTheWorldWithSema)
// semrelease(&worldsema)
//
// 占有 worldsema 后可以多次执行 startTheWorldWithSema/stopTheWorldWithSema 对;
// 其他的 P 可以在连续调用 startTheWorldWithSema 和 stopTheWorldWithSema 间进行执行。
// 持有 worldsema 会导致其他 goroutine 调用的 stopTheWorld 阻塞。
func stopTheWorldWithSema() {
_g_ := getg()
// If we hold a lock, then we won't be able to stop another M
// that is blocked trying to acquire the lock.
if _g_.m.locks > 0 {
throw("stopTheWorld: holding locks")
}
lock(&sched.lock)
sched.stopwait = gomaxprocs
atomic.Store(&sched.gcwaiting, 1)
preemptall()
// 停止当前的 P
_g_.m.p.ptr().status = _Pgcstop // Pgcstop 只用于诊断.
sched.stopwait--
// 尝试抢占所有在 Psyscall 状态的 P
for _, p := range allp {
s := p.status
if s == _Psyscall && atomic.Cas(&p.status, s, _Pgcstop) {
if trace.enabled {
traceGoSysBlock(p)
traceProcStop(p)
}
p.syscalltick++
sched.stopwait--
}
}
// 停止 idle P's
for {
p := pidleget()
if p == nil {
break
}
p.status = _Pgcstop
sched.stopwait--
}
wait := sched.stopwait > 0
unlock(&sched.lock)
// 等待剩余的 P 主动停止
if wait {
for {
// 等待 100us, 然后尝试重新抢占,从而防止竞争
if notetsleep(&sched.stopnote, 100*1000) {
noteclear(&sched.stopnote)
break
}
preemptall()
}
}
// sanity checks
bad := ""
if sched.stopwait != 0 {
bad = "stopTheWorld: not stopped (stopwait != 0)"
} else {
for _, p := range allp {
if p.status != _Pgcstop {
bad = "stopTheWorld: not stopped (status != _Pgcstop)"
}
}
}
if atomic.Load(&freezing) != 0 {
// Some other thread is panicking. This can cause the
// sanity checks above to fail if the panic happens in
// the signal handler on a stopped thread. Either way,
// we should halt this thread.
lock(&deadlock)
lock(&deadlock)
}
if bad != "" {
throw(bad)
}
}