/
proc.c
3521 lines (3163 loc) · 92.5 KB
/
proc.c
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 2009 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.
#include "runtime.h"
#include "arch_GOARCH.h"
#include "zaexperiment.h"
#include "malloc.h"
#include "stack.h"
#include "race.h"
#include "type.h"
#include "mgc0.h"
#include "textflag.h"
// Goroutine scheduler
// The scheduler's job is to distribute ready-to-run goroutines over worker threads.
//
// The main concepts are:
// G - goroutine.
// M - worker thread, or machine.
// P - processor, a resource that is required to execute Go code.
// M must have an associated P to execute Go code, however it can be
// blocked or in a syscall w/o an associated P.
//
// Design doc at http://golang.org/s/go11sched.
enum
{
// Number of goroutine ids to grab from runtime·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,
};
SchedT runtime·sched;
int32 runtime·gomaxprocs;
uint32 runtime·needextram;
bool runtime·iscgo;
M runtime·m0;
G runtime·g0; // idle goroutine for m0
G* runtime·lastg;
M* runtime·allm;
M* runtime·extram;
P* runtime·allp[MaxGomaxprocs+1];
int8* runtime·goos;
int32 runtime·ncpu;
int32 runtime·newprocs;
Mutex runtime·allglock; // the following vars are protected by this lock or by stoptheworld
G** runtime·allg;
Slice runtime·allgs;
uintptr runtime·allglen;
ForceGCState runtime·forcegc;
void runtime·mstart(void);
static void runqput(P*, G*);
static G* runqget(P*);
static bool runqputslow(P*, G*, uint32, uint32);
static G* runqsteal(P*, P*);
static void mput(M*);
static M* mget(void);
static void mcommoninit(M*);
static void schedule(void);
static void procresize(int32);
static void acquirep(P*);
static P* releasep(void);
static void newm(void(*)(void), P*);
static void stopm(void);
static void startm(P*, bool);
static void handoffp(P*);
static void wakep(void);
static void stoplockedm(void);
static void startlockedm(G*);
static void sysmon(void);
static uint32 retake(int64);
static void incidlelocked(int32);
static void checkdead(void);
static void exitsyscall0(G*);
void runtime·park_m(G*);
static void goexit0(G*);
static void gfput(P*, G*);
static G* gfget(P*);
static void gfpurge(P*);
static void globrunqput(G*);
static void globrunqputbatch(G*, G*, int32);
static G* globrunqget(P*, int32);
static P* pidleget(void);
static void pidleput(P*);
static void injectglist(G*);
static bool preemptall(void);
static bool preemptone(P*);
static bool exitsyscallfast(void);
static bool haveexperiment(int8*);
void runtime·allgadd(G*);
static void dropg(void);
extern String runtime·buildVersion;
// For cgo-using programs with external linking,
// export "main" (defined in assembly) so that libc can handle basic
// C runtime startup and call the Go program as if it were
// the C main function.
#pragma cgo_export_static main
// Filled in by dynamic linker when Cgo is available.
void (*_cgo_init)(void);
void (*_cgo_malloc)(void);
void (*_cgo_free)(void);
// Copy for Go code.
void* runtime·cgoMalloc;
void* runtime·cgoFree;
// The bootstrap sequence is:
//
// call osinit
// call schedinit
// make & queue new G
// call runtime·mstart
//
// The new G calls runtime·main.
void
runtime·schedinit(void)
{
int32 n, procs;
byte *p;
// raceinit must be the first call to race detector.
// In particular, it must be done before mallocinit below calls racemapshadow.
if(raceenabled)
g->racectx = runtime·raceinit();
runtime·sched.maxmcount = 10000;
runtime·tracebackinit();
runtime·symtabinit();
runtime·stackinit();
runtime·mallocinit();
mcommoninit(g->m);
runtime·goargs();
runtime·goenvs();
runtime·parsedebugvars();
runtime·gcinit();
runtime·sched.lastpoll = runtime·nanotime();
procs = 1;
p = runtime·getenv("GOMAXPROCS");
if(p != nil && (n = runtime·atoi(p)) > 0) {
if(n > MaxGomaxprocs)
n = MaxGomaxprocs;
procs = n;
}
procresize(procs);
if(runtime·buildVersion.str == nil) {
// Condition should never trigger. This code just serves
// to ensure runtime·buildVersion is kept in the resulting binary.
runtime·buildVersion.str = (uint8*)"unknown";
runtime·buildVersion.len = 7;
}
runtime·cgoMalloc = _cgo_malloc;
runtime·cgoFree = _cgo_free;
}
void
runtime·newsysmon(void)
{
newm(sysmon, nil);
}
static void
dumpgstatus(G* gp)
{
runtime·printf("runtime: gp: gp=%p, goid=%D, gp->atomicstatus=%x\n", gp, gp->goid, runtime·readgstatus(gp));
runtime·printf("runtime: g: g=%p, goid=%D, g->atomicstatus=%x\n", g, g->goid, runtime·readgstatus(g));
}
static void
checkmcount(void)
{
// sched lock is held
if(runtime·sched.mcount > runtime·sched.maxmcount){
runtime·printf("runtime: program exceeds %d-thread limit\n", runtime·sched.maxmcount);
runtime·throw("thread exhaustion");
}
}
static void
mcommoninit(M *mp)
{
// g0 stack won't make sense for user (and is not necessary unwindable).
if(g != g->m->g0)
runtime·callers(1, mp->createstack, nelem(mp->createstack));
mp->fastrand = 0x49f6428aUL + mp->id + runtime·cputicks();
runtime·lock(&runtime·sched.lock);
mp->id = runtime·sched.mcount++;
checkmcount();
runtime·mpreinit(mp);
if(mp->gsignal)
mp->gsignal->stackguard1 = mp->gsignal->stack.lo + StackGuard;
// Add to runtime·allm so garbage collector doesn't free g->m
// when it is just in a register or thread-local storage.
mp->alllink = runtime·allm;
// runtime·NumCgoCall() iterates over allm w/o schedlock,
// so we need to publish it safely.
runtime·atomicstorep(&runtime·allm, mp);
runtime·unlock(&runtime·sched.lock);
}
// Mark gp ready to run.
void
runtime·ready(G *gp)
{
uint32 status;
status = runtime·readgstatus(gp);
// Mark runnable.
g->m->locks++; // disable preemption because it can be holding p in a local var
if((status&~Gscan) != Gwaiting){
dumpgstatus(gp);
runtime·throw("bad g->status in ready");
}
// status is Gwaiting or Gscanwaiting, make Grunnable and put on runq
runtime·casgstatus(gp, Gwaiting, Grunnable);
runqput(g->m->p, gp);
if(runtime·atomicload(&runtime·sched.npidle) != 0 && runtime·atomicload(&runtime·sched.nmspinning) == 0) // TODO: fast atomic
wakep();
g->m->locks--;
if(g->m->locks == 0 && g->preempt) // restore the preemption request in case we've cleared it in newstack
g->stackguard0 = StackPreempt;
}
void
runtime·ready_m(void)
{
G *gp;
gp = g->m->ptrarg[0];
g->m->ptrarg[0] = nil;
runtime·ready(gp);
}
int32
runtime·gcprocs(void)
{
int32 n;
// Figure out how many CPUs to use during GC.
// Limited by gomaxprocs, number of actual CPUs, and MaxGcproc.
runtime·lock(&runtime·sched.lock);
n = runtime·gomaxprocs;
if(n > runtime·ncpu)
n = runtime·ncpu;
if(n > MaxGcproc)
n = MaxGcproc;
if(n > runtime·sched.nmidle+1) // one M is currently running
n = runtime·sched.nmidle+1;
runtime·unlock(&runtime·sched.lock);
return n;
}
static bool
needaddgcproc(void)
{
int32 n;
runtime·lock(&runtime·sched.lock);
n = runtime·gomaxprocs;
if(n > runtime·ncpu)
n = runtime·ncpu;
if(n > MaxGcproc)
n = MaxGcproc;
n -= runtime·sched.nmidle+1; // one M is currently running
runtime·unlock(&runtime·sched.lock);
return n > 0;
}
void
runtime·helpgc(int32 nproc)
{
M *mp;
int32 n, pos;
runtime·lock(&runtime·sched.lock);
pos = 0;
for(n = 1; n < nproc; n++) { // one M is currently running
if(runtime·allp[pos]->mcache == g->m->mcache)
pos++;
mp = mget();
if(mp == nil)
runtime·throw("runtime·gcprocs inconsistency");
mp->helpgc = n;
mp->mcache = runtime·allp[pos]->mcache;
pos++;
runtime·notewakeup(&mp->park);
}
runtime·unlock(&runtime·sched.lock);
}
// 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.
void
runtime·freezetheworld(void)
{
int32 i;
if(runtime·gomaxprocs == 1)
return;
// 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
runtime·sched.stopwait = 0x7fffffff;
runtime·atomicstore((uint32*)&runtime·sched.gcwaiting, 1);
// this should stop running goroutines
if(!preemptall())
break; // no running goroutines
runtime·usleep(1000);
}
// to be sure
runtime·usleep(1000);
preemptall();
runtime·usleep(1000);
}
static bool
isscanstatus(uint32 status)
{
if(status == Gscan)
runtime·throw("isscanstatus: Bad status Gscan");
return (status&Gscan) == Gscan;
}
// All reads and writes of g's status go through readgstatus, casgstatus
// castogscanstatus, casfromgscanstatus.
#pragma textflag NOSPLIT
uint32
runtime·readgstatus(G *gp)
{
return runtime·atomicload(&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.
void
runtime·casfromgscanstatus(G *gp, uint32 oldval, uint32 newval)
{
bool success = false;
// Check that transition is valid.
switch(oldval) {
case Gscanrunnable:
case Gscanwaiting:
case Gscanrunning:
case Gscansyscall:
if(newval == (oldval&~Gscan))
success = runtime·cas(&gp->atomicstatus, oldval, newval);
break;
case Gscanenqueue:
if(newval == Gwaiting)
success = runtime·cas(&gp->atomicstatus, oldval, newval);
break;
}
if(!success){
runtime·printf("runtime: casfromgscanstatus failed gp=%p, oldval=%d, newval=%d\n",
gp, oldval, newval);
dumpgstatus(gp);
runtime·throw("casfromgscanstatus: 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.
bool
runtime·castogscanstatus(G *gp, uint32 oldval, uint32 newval)
{
switch(oldval) {
case Grunnable:
case Gwaiting:
case Gsyscall:
if(newval == (oldval|Gscan))
return runtime·cas(&gp->atomicstatus, oldval, newval);
break;
case Grunning:
if(newval == Gscanrunning || newval == Gscanenqueue)
return runtime·cas(&gp->atomicstatus, oldval, newval);
break;
}
runtime·printf("runtime: castogscanstatus oldval=%d newval=%d\n", oldval, newval);
runtime·throw("castogscanstatus");
return false; // not reached
}
static void badcasgstatus(void);
static void helpcasgstatus(void);
static void badgstatusrunnable(void);
// If asked to move to or from a Gscanstatus this will throw. Use the castogscanstatus
// and casfromgscanstatus 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.
#pragma textflag NOSPLIT
void
runtime·casgstatus(G *gp, uint32 oldval, uint32 newval)
{
void (*fn)(void);
if((oldval&Gscan) || (newval&Gscan) || oldval == newval) {
g->m->scalararg[0] = oldval;
g->m->scalararg[1] = newval;
fn = badcasgstatus;
runtime·onM(&fn);
}
// loop if gp->atomicstatus is in a scan state giving
// GC time to finish and change the state to oldval.
while(!runtime·cas(&gp->atomicstatus, oldval, newval)) {
if(oldval == Gwaiting && gp->atomicstatus == Grunnable) {
fn = badgstatusrunnable;
runtime·onM(&fn);
}
// Help GC if needed.
if(gp->preemptscan && !gp->gcworkdone && (oldval == Grunning || oldval == Gsyscall)) {
gp->preemptscan = false;
g->m->ptrarg[0] = gp;
fn = helpcasgstatus;
runtime·onM(&fn);
}
}
}
static void
badgstatusrunnable(void)
{
runtime·throw("casgstatus: waiting for Gwaiting but is Grunnable");
}
// 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.
#pragma textflag NOSPLIT
uint32
runtime·casgcopystack(G *gp)
{
uint32 oldstatus;
for(;;) {
oldstatus = runtime·readgstatus(gp) & ~Gscan;
if(oldstatus != Gwaiting && oldstatus != Grunnable)
runtime·throw("copystack: bad status, not Gwaiting or Grunnable");
if(runtime·cas(&gp->atomicstatus, oldstatus, Gcopystack))
break;
}
return oldstatus;
}
static void
badcasgstatus(void)
{
uint32 oldval, newval;
oldval = g->m->scalararg[0];
newval = g->m->scalararg[1];
g->m->scalararg[0] = 0;
g->m->scalararg[1] = 0;
runtime·printf("casgstatus: oldval=%d, newval=%d\n", oldval, newval);
runtime·throw("casgstatus: bad incoming values");
}
static void
helpcasgstatus(void)
{
G *gp;
gp = g->m->ptrarg[0];
g->m->ptrarg[0] = 0;
runtime·gcphasework(gp);
}
// stopg ensures that gp is stopped at a GC safe point where its stack can be scanned
// or in the context of a moving collector the pointers can be flipped from pointing
// to old object to pointing to new objects.
// If stopg returns true, the caller knows gp is at a GC safe point and will remain there until
// the caller calls restartg.
// If stopg returns false, the caller is not responsible for calling restartg. This can happen
// if another thread, either the gp itself or another GC thread is taking the responsibility
// to do the GC work related to this thread.
bool
runtime·stopg(G *gp)
{
uint32 s;
for(;;) {
if(gp->gcworkdone)
return false;
s = runtime·readgstatus(gp);
switch(s) {
default:
dumpgstatus(gp);
runtime·throw("stopg: gp->atomicstatus is not valid");
case Gdead:
return false;
case Gcopystack:
// Loop until a new stack is in place.
break;
case Grunnable:
case Gsyscall:
case Gwaiting:
// Claim goroutine by setting scan bit.
if(!runtime·castogscanstatus(gp, s, s|Gscan))
break;
// In scan state, do work.
runtime·gcphasework(gp);
return true;
case Gscanrunnable:
case Gscanwaiting:
case Gscansyscall:
// Goroutine already claimed by another GC helper.
return false;
case Grunning:
// Claim goroutine, so we aren't racing with a status
// transition away from Grunning.
if(!runtime·castogscanstatus(gp, Grunning, Gscanrunning))
break;
// Mark gp for preemption.
if(!gp->gcworkdone) {
gp->preemptscan = true;
gp->preempt = true;
gp->stackguard0 = StackPreempt;
}
// Unclaim.
runtime·casfromgscanstatus(gp, Gscanrunning, Grunning);
return false;
}
}
// Should not be here....
}
// The GC requests that this routine be moved from a scanmumble state to a mumble state.
void
runtime·restartg (G *gp)
{
uint32 s;
s = runtime·readgstatus(gp);
switch(s) {
default:
dumpgstatus(gp);
runtime·throw("restartg: unexpected status");
case Gdead:
break;
case Gscanrunnable:
case Gscanwaiting:
case Gscansyscall:
runtime·casfromgscanstatus(gp, s, s&~Gscan);
break;
case Gscanenqueue:
// Scan is now completed.
// Goroutine now needs to be made runnable.
// We put it on the global run queue; ready blocks on the global scheduler lock.
runtime·casfromgscanstatus(gp, Gscanenqueue, Gwaiting);
if(gp != g->m->curg)
runtime·throw("processing Gscanenqueue on wrong m");
dropg();
runtime·ready(gp);
break;
}
}
static void
stopscanstart(G* gp)
{
if(g == gp)
runtime·throw("GC not moved to G0");
if(runtime·stopg(gp)) {
if(!isscanstatus(runtime·readgstatus(gp))) {
dumpgstatus(gp);
runtime·throw("GC not in scan state");
}
runtime·restartg(gp);
}
}
// Runs on g0 and does the actual work after putting the g back on the run queue.
static void
mquiesce(G *gpmaster)
{
G* gp;
uint32 i;
uint32 status;
uint32 activeglen;
activeglen = runtime·allglen;
// enqueue the calling goroutine.
runtime·restartg(gpmaster);
for(i = 0; i < activeglen; i++) {
gp = runtime·allg[i];
if(runtime·readgstatus(gp) == Gdead)
gp->gcworkdone = true; // noop scan.
else
gp->gcworkdone = false;
stopscanstart(gp);
}
// Check that the G's gcwork (such as scanning) has been done. If not do it now.
// You can end up doing work here if the page trap on a Grunning Goroutine has
// not been sprung or in some race situations. For example a runnable goes dead
// and is started up again with a gp->gcworkdone set to false.
for(i = 0; i < activeglen; i++) {
gp = runtime·allg[i];
while (!gp->gcworkdone) {
status = runtime·readgstatus(gp);
if(status == Gdead) {
gp->gcworkdone = true; // scan is a noop
break;
//do nothing, scan not needed.
}
if(status == Grunning && gp->stackguard0 == (uintptr)StackPreempt && runtime·notetsleep(&runtime·sched.stopnote, 100*1000)) // nanosecond arg
runtime·noteclear(&runtime·sched.stopnote);
else
stopscanstart(gp);
}
}
for(i = 0; i < activeglen; i++) {
gp = runtime·allg[i];
status = runtime·readgstatus(gp);
if(isscanstatus(status)) {
runtime·printf("mstopandscang:bottom: post scan bad status gp=%p has status %x\n", gp, status);
dumpgstatus(gp);
}
if(!gp->gcworkdone && status != Gdead) {
runtime·printf("mstopandscang:bottom: post scan gp=%p->gcworkdone still false\n", gp);
dumpgstatus(gp);
}
}
schedule(); // Never returns.
}
// quiesce moves all the goroutines to a GC safepoint which for now is a at preemption point.
// If the global runtime·gcphase is GCmark quiesce will ensure that all of the goroutine's stacks
// have been scanned before it returns.
void
runtime·quiesce(G* mastergp)
{
void (*fn)(G*);
runtime·castogscanstatus(mastergp, Grunning, Gscanenqueue);
// Now move this to the g0 (aka m) stack.
// g0 will potentially scan this thread and put mastergp on the runqueue
fn = mquiesce;
runtime·mcall(&fn);
}
// This is used by the GC as well as the routines that do stack dumps. In the case
// of GC all the routines can be reliably stopped. This is not always the case
// when the system is in panic or being exited.
void
runtime·stoptheworld(void)
{
int32 i;
uint32 s;
P *p;
bool wait;
// 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)
runtime·throw("stoptheworld: holding locks");
runtime·lock(&runtime·sched.lock);
runtime·sched.stopwait = runtime·gomaxprocs;
runtime·atomicstore((uint32*)&runtime·sched.gcwaiting, 1);
preemptall();
// stop current P
g->m->p->status = Pgcstop; // Pgcstop is only diagnostic.
runtime·sched.stopwait--;
// try to retake all P's in Psyscall status
for(i = 0; i < runtime·gomaxprocs; i++) {
p = runtime·allp[i];
s = p->status;
if(s == Psyscall && runtime·cas(&p->status, s, Pgcstop))
runtime·sched.stopwait--;
}
// stop idle P's
while(p = pidleget()) {
p->status = Pgcstop;
runtime·sched.stopwait--;
}
wait = runtime·sched.stopwait > 0;
runtime·unlock(&runtime·sched.lock);
// wait for remaining P's to stop voluntarily
if(wait) {
for(;;) {
// wait for 100us, then try to re-preempt in case of any races
if(runtime·notetsleep(&runtime·sched.stopnote, 100*1000)) {
runtime·noteclear(&runtime·sched.stopnote);
break;
}
preemptall();
}
}
if(runtime·sched.stopwait)
runtime·throw("stoptheworld: not stopped");
for(i = 0; i < runtime·gomaxprocs; i++) {
p = runtime·allp[i];
if(p->status != Pgcstop)
runtime·throw("stoptheworld: not stopped");
}
}
static void
mhelpgc(void)
{
g->m->helpgc = -1;
}
void
runtime·starttheworld(void)
{
P *p, *p1;
M *mp;
G *gp;
bool add;
g->m->locks++; // disable preemption because it can be holding p in a local var
gp = runtime·netpoll(false); // non-blocking
injectglist(gp);
add = needaddgcproc();
runtime·lock(&runtime·sched.lock);
if(runtime·newprocs) {
procresize(runtime·newprocs);
runtime·newprocs = 0;
} else
procresize(runtime·gomaxprocs);
runtime·sched.gcwaiting = 0;
p1 = nil;
while(p = pidleget()) {
// procresize() puts p's with work at the beginning of the list.
// Once we reach a p without a run queue, the rest don't have one either.
if(p->runqhead == p->runqtail) {
pidleput(p);
break;
}
p->m = mget();
p->link = p1;
p1 = p;
}
if(runtime·sched.sysmonwait) {
runtime·sched.sysmonwait = false;
runtime·notewakeup(&runtime·sched.sysmonnote);
}
runtime·unlock(&runtime·sched.lock);
while(p1) {
p = p1;
p1 = p1->link;
if(p->m) {
mp = p->m;
p->m = nil;
if(mp->nextp)
runtime·throw("starttheworld: inconsistent mp->nextp");
mp->nextp = p;
runtime·notewakeup(&mp->park);
} else {
// Start M to run P. Do not start another M below.
newm(nil, p);
add = false;
}
}
if(add) {
// If GC could have used another helper proc, start one now,
// in the hope that it will be available next time.
// It would have been even better to start it before the collection,
// but doing so requires allocating memory, so it's tricky to
// coordinate. This lazy approach works out in practice:
// we don't mind if the first couple gc rounds don't have quite
// the maximum number of procs.
newm(mhelpgc, nil);
}
g->m->locks--;
if(g->m->locks == 0 && g->preempt) // restore the preemption request in case we've cleared it in newstack
g->stackguard0 = StackPreempt;
}
static void mstart(void);
// Called to start an M.
#pragma textflag NOSPLIT
void
runtime·mstart(void)
{
uintptr x, size;
if(g->stack.lo == 0) {
// Initialize stack bounds from system stack.
// Cgo may have left stack size in stack.hi.
size = g->stack.hi;
if(size == 0)
size = 8192;
g->stack.hi = (uintptr)&x;
g->stack.lo = g->stack.hi - size + 1024;
}
// Initialize stack guards so that we can start calling
// both Go and C functions with stack growth prologues.
g->stackguard0 = g->stack.lo + StackGuard;
g->stackguard1 = g->stackguard0;
mstart();
}
static void
mstart(void)
{
if(g != g->m->g0)
runtime·throw("bad runtime·mstart");
// Record top of stack for use by mcall.
// Once we call schedule we're never coming back,
// so other calls can reuse this stack space.
runtime·gosave(&g->m->g0->sched);
g->m->g0->sched.pc = (uintptr)-1; // make sure it is never used
runtime·asminit();
runtime·minit();
// Install signal handlers; after minit so that minit can
// prepare the thread to be able to handle the signals.
if(g->m == &runtime·m0)
runtime·initsig();
if(g->m->mstartfn)
g->m->mstartfn();
if(g->m->helpgc) {
g->m->helpgc = 0;
stopm();
} else if(g->m != &runtime·m0) {
acquirep(g->m->nextp);
g->m->nextp = nil;
}
schedule();
// TODO(brainman): This point is never reached, because scheduler
// does not release os threads at the moment. But once this path
// is enabled, we must remove our seh here.
}
// When running with cgo, we call _cgo_thread_start
// to start threads for us so that we can play nicely with
// foreign code.
void (*_cgo_thread_start)(void*);
typedef struct CgoThreadStart CgoThreadStart;
struct CgoThreadStart
{
G *g;
uintptr *tls;
void (*fn)(void);
};
M *runtime·newM(void); // in proc.go
// Allocate a new m unassociated with any thread.
// Can use p for allocation context if needed.
M*
runtime·allocm(P *p)
{
M *mp;
g->m->locks++; // disable GC because it can be called from sysmon
if(g->m->p == nil)
acquirep(p); // temporarily borrow p for mallocs in this function
mp = runtime·newM();
mcommoninit(mp);
// In case of cgo or Solaris, pthread_create will make us a stack.
// Windows and Plan 9 will layout sched stack on OS stack.
if(runtime·iscgo || Solaris || Windows || Plan9)
mp->g0 = runtime·malg(-1);
else
mp->g0 = runtime·malg(8192);
mp->g0->m = mp;
if(p == g->m->p)
releasep();
g->m->locks--;
if(g->m->locks == 0 && g->preempt) // restore the preemption request in case we've cleared it in newstack
g->stackguard0 = StackPreempt;
return mp;
}
G *runtime·newG(void); // in proc.go
static G*
allocg(void)
{
return runtime·newG();
}
static M* lockextra(bool nilokay);
static void unlockextra(M*);
// needm is called when a cgo callback happens on a
// thread without an m (a thread not created by Go).
// In this case, needm is expected to find an m to use
// and return with m, g initialized correctly.
// Since m and g are not set now (likely nil, but see below)
// needm is limited in what routines it can call. In particular
// it can only call nosplit functions (textflag 7) and cannot
// do any scheduling that requires an m.
//
// In order to avoid needing heavy lifting here, we adopt
// the following strategy: there is a stack of available m's
// that can be stolen. Using compare-and-swap
// to pop from the stack has ABA races, so we simulate
// a lock by doing an exchange (via casp) to steal the stack
// head and replace the top pointer with MLOCKED (1).
// This serves as a simple spin lock that we can use even
// without an m. The thread that locks the stack in this way
// unlocks the stack by storing a valid stack head pointer.
//
// In order to make sure that there is always an m structure
// available to be stolen, we maintain the invariant that there
// is always one more than needed. At the beginning of the
// program (if cgo is in use) the list is seeded with a single m.
// If needm finds that it has taken the last m off the list, its job
// is - once it has installed its own m so that it can do things like
// allocate memory - to create a spare m and put it on the list.
//
// Each of these extra m's also has a g0 and a curg that are
// pressed into service as the scheduling stack and current
// goroutine for the duration of the cgo callback.
//
// When the callback is done with the m, it calls dropm to
// put the m back on the list.
#pragma textflag NOSPLIT
void
runtime·needm(byte x)
{
M *mp;
if(runtime·needextram) {
// Can happen if C/C++ code calls Go from a global ctor.
// Can not throw, because scheduler is not initialized yet.
runtime·write(2, "fatal error: cgo callback before cgo call\n",
sizeof("fatal error: cgo callback before cgo call\n")-1);
runtime·exit(1);
}
// Lock extra list, take head, unlock popped list.
// nilokay=false is safe here because of the invariant above,
// that the extra list always contains or will soon contain
// at least one m.
mp = lockextra(false);
// Set needextram when we've just emptied the list,
// so that the eventual call into cgocallbackg will
// allocate a new m for the extra list. We delay the
// allocation until then so that it can be done
// after exitsyscall makes sure it is okay to be
// running at all (that is, there's no garbage collection
// running right now).
mp->needextram = mp->schedlink == nil;
unlockextra(mp->schedlink);
// Install g (= m->g0) and set the stack bounds
// to match the current stack. We don't actually know
// how big the stack is, like we don't know how big any
// scheduling stack is, but we assume there's at least 32 kB,
// which is more than enough for us.
runtime·setg(mp->g0);
g->stack.hi = (uintptr)(&x + 1024);