]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/proc1.go
[dev.cc] runtime: convert openbsd/386 port to Go
[gostls13.git] / src / runtime / proc1.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package runtime
6
7 import "unsafe"
8
9 var (
10         m0 m
11         g0 g
12 )
13
14 // Goroutine scheduler
15 // The scheduler's job is to distribute ready-to-run goroutines over worker threads.
16 //
17 // The main concepts are:
18 // G - goroutine.
19 // M - worker thread, or machine.
20 // P - processor, a resource that is required to execute Go code.
21 //     M must have an associated P to execute Go code, however it can be
22 //     blocked or in a syscall w/o an associated P.
23 //
24 // Design doc at http://golang.org/s/go11sched.
25
26 const (
27         // Number of goroutine ids to grab from sched.goidgen to local per-P cache at once.
28         // 16 seems to provide enough amortization, but other than that it's mostly arbitrary number.
29         _GoidCacheBatch = 16
30 )
31
32 /*
33 SchedT  sched;
34 int32   gomaxprocs;
35 uint32  needextram;
36 bool    iscgo;
37 M       m0;
38 G       g0;     // idle goroutine for m0
39 G*      lastg;
40 M*      allm;
41 M*      extram;
42 P*      allp[MaxGomaxprocs+1];
43 int8*   goos;
44 int32   ncpu;
45 int32   newprocs;
46
47 Mutex allglock; // the following vars are protected by this lock or by stoptheworld
48 G**     allg;
49 Slice   allgs;
50 uintptr allglen;
51 ForceGCState    forcegc;
52
53 void mstart(void);
54 static void runqput(P*, G*);
55 static G* runqget(P*);
56 static bool runqputslow(P*, G*, uint32, uint32);
57 static G* runqsteal(P*, P*);
58 static void mput(M*);
59 static M* mget(void);
60 static void mcommoninit(M*);
61 static void schedule(void);
62 static void procresize(int32);
63 static void acquirep(P*);
64 static P* releasep(void);
65 static void newm(void(*)(void), P*);
66 static void stopm(void);
67 static void startm(P*, bool);
68 static void handoffp(P*);
69 static void wakep(void);
70 static void stoplockedm(void);
71 static void startlockedm(G*);
72 static void sysmon(void);
73 static uint32 retake(int64);
74 static void incidlelocked(int32);
75 static void checkdead(void);
76 static void exitsyscall0(G*);
77 void park_m(G*);
78 static void goexit0(G*);
79 static void gfput(P*, G*);
80 static G* gfget(P*);
81 static void gfpurge(P*);
82 static void globrunqput(G*);
83 static void globrunqputbatch(G*, G*, int32);
84 static G* globrunqget(P*, int32);
85 static P* pidleget(void);
86 static void pidleput(P*);
87 static void injectglist(G*);
88 static bool preemptall(void);
89 static bool preemptone(P*);
90 static bool exitsyscallfast(void);
91 static bool haveexperiment(int8*);
92 void allgadd(G*);
93 static void dropg(void);
94
95 extern String buildVersion;
96 */
97
98 // The bootstrap sequence is:
99 //
100 //      call osinit
101 //      call schedinit
102 //      make & queue new G
103 //      call runtimeĀ·mstart
104 //
105 // The new G calls runtimeĀ·main.
106 func schedinit() {
107         // raceinit must be the first call to race detector.
108         // In particular, it must be done before mallocinit below calls racemapshadow.
109         _g_ := getg()
110         if raceenabled {
111                 _g_.racectx = raceinit()
112         }
113
114         sched.maxmcount = 10000
115
116         tracebackinit()
117         symtabinit()
118         stackinit()
119         mallocinit()
120         mcommoninit(_g_.m)
121
122         goargs()
123         goenvs()
124         parsedebugvars()
125         gcinit()
126
127         sched.lastpoll = uint64(nanotime())
128         procs := 1
129         if n := goatoi(gogetenv("GOMAXPROCS")); n > 0 {
130                 if n > _MaxGomaxprocs {
131                         n = _MaxGomaxprocs
132                 }
133                 procs = n
134         }
135         procresize(int32(procs))
136
137         if buildVersion == "" {
138                 // Condition should never trigger.  This code just serves
139                 // to ensure runtimeĀ·buildVersion is kept in the resulting binary.
140                 buildVersion = "unknown"
141         }
142 }
143
144 func newsysmon() {
145         _newm(sysmon, nil)
146 }
147
148 func dumpgstatus(gp *g) {
149         _g_ := getg()
150         print("runtime: gp: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n")
151         print("runtime:  g:  g=", _g_, ", goid=", _g_.goid, ",  g->atomicstatus=", readgstatus(_g_), "\n")
152 }
153
154 func checkmcount() {
155         // sched lock is held
156         if sched.mcount > sched.maxmcount {
157                 print("runtime: program exceeds ", sched.maxmcount, "-thread limit\n")
158                 gothrow("thread exhaustion")
159         }
160 }
161
162 func mcommoninit(mp *m) {
163         _g_ := getg()
164
165         // g0 stack won't make sense for user (and is not necessary unwindable).
166         if _g_ != _g_.m.g0 {
167                 callers(1, &mp.createstack[0], len(mp.createstack))
168         }
169
170         mp.fastrand = 0x49f6428a + uint32(mp.id) + uint32(cputicks())
171         if mp.fastrand == 0 {
172                 mp.fastrand = 0x49f6428a
173         }
174
175         lock(&sched.lock)
176         mp.id = sched.mcount
177         sched.mcount++
178         checkmcount()
179         mpreinit(mp)
180         if mp.gsignal != nil {
181                 mp.gsignal.stackguard1 = mp.gsignal.stack.lo + _StackGuard
182         }
183
184         // Add to allm so garbage collector doesn't free g->m
185         // when it is just in a register or thread-local storage.
186         mp.alllink = allm
187
188         // NumCgoCall() iterates over allm w/o schedlock,
189         // so we need to publish it safely.
190         atomicstorep(unsafe.Pointer(&allm), unsafe.Pointer(mp))
191         unlock(&sched.lock)
192 }
193
194 // Mark gp ready to run.
195 func ready(gp *g) {
196         status := readgstatus(gp)
197
198         // Mark runnable.
199         _g_ := getg()
200         _g_.m.locks++ // disable preemption because it can be holding p in a local var
201         if status&^_Gscan != _Gwaiting {
202                 dumpgstatus(gp)
203                 gothrow("bad g->status in ready")
204         }
205
206         // status is Gwaiting or Gscanwaiting, make Grunnable and put on runq
207         casgstatus(gp, _Gwaiting, _Grunnable)
208         runqput(_g_.m.p, gp)
209         if atomicload(&sched.npidle) != 0 && atomicload(&sched.nmspinning) == 0 { // TODO: fast atomic
210                 wakep()
211         }
212         _g_.m.locks--
213         if _g_.m.locks == 0 && _g_.preempt { // restore the preemption request in case we've cleared it in newstack
214                 _g_.stackguard0 = stackPreempt
215         }
216 }
217
218 func gcprocs() int32 {
219         // Figure out how many CPUs to use during GC.
220         // Limited by gomaxprocs, number of actual CPUs, and MaxGcproc.
221         lock(&sched.lock)
222         n := gomaxprocs
223         if n > ncpu {
224                 n = ncpu
225         }
226         if n > _MaxGcproc {
227                 n = _MaxGcproc
228         }
229         if n > sched.nmidle+1 { // one M is currently running
230                 n = sched.nmidle + 1
231         }
232         unlock(&sched.lock)
233         return n
234 }
235
236 func needaddgcproc() bool {
237         lock(&sched.lock)
238         n := gomaxprocs
239         if n > ncpu {
240                 n = ncpu
241         }
242         if n > _MaxGcproc {
243                 n = _MaxGcproc
244         }
245         n -= sched.nmidle + 1 // one M is currently running
246         unlock(&sched.lock)
247         return n > 0
248 }
249
250 func helpgc(nproc int32) {
251         _g_ := getg()
252         lock(&sched.lock)
253         pos := 0
254         for n := int32(1); n < nproc; n++ { // one M is currently running
255                 if allp[pos].mcache == _g_.m.mcache {
256                         pos++
257                 }
258                 mp := mget()
259                 if mp == nil {
260                         gothrow("gcprocs inconsistency")
261                 }
262                 mp.helpgc = n
263                 mp.mcache = allp[pos].mcache
264                 pos++
265                 notewakeup(&mp.park)
266         }
267         unlock(&sched.lock)
268 }
269
270 // Similar to stoptheworld but best-effort and can be called several times.
271 // There is no reverse operation, used during crashing.
272 // This function must not lock any mutexes.
273 func freezetheworld() {
274         if gomaxprocs == 1 {
275                 return
276         }
277         // stopwait and preemption requests can be lost
278         // due to races with concurrently executing threads,
279         // so try several times
280         for i := 0; i < 5; i++ {
281                 // this should tell the scheduler to not start any new goroutines
282                 sched.stopwait = 0x7fffffff
283                 atomicstore(&sched.gcwaiting, 1)
284                 // this should stop running goroutines
285                 if !preemptall() {
286                         break // no running goroutines
287                 }
288                 usleep(1000)
289         }
290         // to be sure
291         usleep(1000)
292         preemptall()
293         usleep(1000)
294 }
295
296 func isscanstatus(status uint32) bool {
297         if status == _Gscan {
298                 gothrow("isscanstatus: Bad status Gscan")
299         }
300         return status&_Gscan == _Gscan
301 }
302
303 // All reads and writes of g's status go through readgstatus, casgstatus
304 // castogscanstatus, casfrom_Gscanstatus.
305 //go:nosplit
306 func readgstatus(gp *g) uint32 {
307         return atomicload(&gp.atomicstatus)
308 }
309
310 // The Gscanstatuses are acting like locks and this releases them.
311 // If it proves to be a performance hit we should be able to make these
312 // simple atomic stores but for now we are going to throw if
313 // we see an inconsistent state.
314 func casfrom_Gscanstatus(gp *g, oldval, newval uint32) {
315         success := false
316
317         // Check that transition is valid.
318         switch oldval {
319         case _Gscanrunnable,
320                 _Gscanwaiting,
321                 _Gscanrunning,
322                 _Gscansyscall:
323                 if newval == oldval&^_Gscan {
324                         success = cas(&gp.atomicstatus, oldval, newval)
325                 }
326         case _Gscanenqueue:
327                 if newval == _Gwaiting {
328                         success = cas(&gp.atomicstatus, oldval, newval)
329                 }
330         }
331         if !success {
332                 print("runtime: casfrom_Gscanstatus failed gp=", gp, ", oldval=", hex(oldval), ", newval=", hex(newval), "\n")
333                 dumpgstatus(gp)
334                 gothrow("casfrom_Gscanstatus: gp->status is not in scan state")
335         }
336 }
337
338 // This will return false if the gp is not in the expected status and the cas fails.
339 // This acts like a lock acquire while the casfromgstatus acts like a lock release.
340 func castogscanstatus(gp *g, oldval, newval uint32) bool {
341         switch oldval {
342         case _Grunnable,
343                 _Gwaiting,
344                 _Gsyscall:
345                 if newval == oldval|_Gscan {
346                         return cas(&gp.atomicstatus, oldval, newval)
347                 }
348         case _Grunning:
349                 if newval == _Gscanrunning || newval == _Gscanenqueue {
350                         return cas(&gp.atomicstatus, oldval, newval)
351                 }
352         }
353         print("runtime: castogscanstatus oldval=", hex(oldval), " newval=", hex(newval), "\n")
354         gothrow("castogscanstatus")
355         panic("not reached")
356 }
357
358 // If asked to move to or from a Gscanstatus this will throw. Use the castogscanstatus
359 // and casfrom_Gscanstatus instead.
360 // casgstatus will loop if the g->atomicstatus is in a Gscan status until the routine that
361 // put it in the Gscan state is finished.
362 //go:nosplit
363 func casgstatus(gp *g, oldval, newval uint32) {
364         if (oldval&_Gscan != 0) || (newval&_Gscan != 0) || oldval == newval {
365                 systemstack(func() {
366                         print("casgstatus: oldval=", hex(oldval), " newval=", hex(newval), "\n")
367                         gothrow("casgstatus: bad incoming values")
368                 })
369         }
370
371         // loop if gp->atomicstatus is in a scan state giving
372         // GC time to finish and change the state to oldval.
373         for !cas(&gp.atomicstatus, oldval, newval) {
374                 // Help GC if needed.
375                 if gp.preemptscan && !gp.gcworkdone && (oldval == _Grunning || oldval == _Gsyscall) {
376                         gp.preemptscan = false
377                         systemstack(func() {
378                                 gcphasework(gp)
379                         })
380                 }
381         }
382 }
383
384 // stopg ensures that gp is stopped at a GC safe point where its stack can be scanned
385 // or in the context of a moving collector the pointers can be flipped from pointing
386 // to old object to pointing to new objects.
387 // If stopg returns true, the caller knows gp is at a GC safe point and will remain there until
388 // the caller calls restartg.
389 // If stopg returns false, the caller is not responsible for calling restartg. This can happen
390 // if another thread, either the gp itself or another GC thread is taking the responsibility
391 // to do the GC work related to this thread.
392 func stopg(gp *g) bool {
393         for {
394                 if gp.gcworkdone {
395                         return false
396                 }
397
398                 switch s := readgstatus(gp); s {
399                 default:
400                         dumpgstatus(gp)
401                         gothrow("stopg: gp->atomicstatus is not valid")
402
403                 case _Gdead:
404                         return false
405
406                 case _Gcopystack:
407                         // Loop until a new stack is in place.
408
409                 case _Grunnable,
410                         _Gsyscall,
411                         _Gwaiting:
412                         // Claim goroutine by setting scan bit.
413                         if !castogscanstatus(gp, s, s|_Gscan) {
414                                 break
415                         }
416                         // In scan state, do work.
417                         gcphasework(gp)
418                         return true
419
420                 case _Gscanrunnable,
421                         _Gscanwaiting,
422                         _Gscansyscall:
423                         // Goroutine already claimed by another GC helper.
424                         return false
425
426                 case _Grunning:
427                         // Claim goroutine, so we aren't racing with a status
428                         // transition away from Grunning.
429                         if !castogscanstatus(gp, _Grunning, _Gscanrunning) {
430                                 break
431                         }
432
433                         // Mark gp for preemption.
434                         if !gp.gcworkdone {
435                                 gp.preemptscan = true
436                                 gp.preempt = true
437                                 gp.stackguard0 = stackPreempt
438                         }
439
440                         // Unclaim.
441                         casfrom_Gscanstatus(gp, _Gscanrunning, _Grunning)
442                         return false
443                 }
444         }
445 }
446
447 // The GC requests that this routine be moved from a scanmumble state to a mumble state.
448 func restartg(gp *g) {
449         s := readgstatus(gp)
450         switch s {
451         default:
452                 dumpgstatus(gp)
453                 gothrow("restartg: unexpected status")
454
455         case _Gdead:
456                 // ok
457
458         case _Gscanrunnable,
459                 _Gscanwaiting,
460                 _Gscansyscall:
461                 casfrom_Gscanstatus(gp, s, s&^_Gscan)
462
463         // Scan is now completed.
464         // Goroutine now needs to be made runnable.
465         // We put it on the global run queue; ready blocks on the global scheduler lock.
466         case _Gscanenqueue:
467                 casfrom_Gscanstatus(gp, _Gscanenqueue, _Gwaiting)
468                 if gp != getg().m.curg {
469                         gothrow("processing Gscanenqueue on wrong m")
470                 }
471                 dropg()
472                 ready(gp)
473         }
474 }
475
476 func stopscanstart(gp *g) {
477         _g_ := getg()
478         if _g_ == gp {
479                 gothrow("GC not moved to G0")
480         }
481         if stopg(gp) {
482                 if !isscanstatus(readgstatus(gp)) {
483                         dumpgstatus(gp)
484                         gothrow("GC not in scan state")
485                 }
486                 restartg(gp)
487         }
488 }
489
490 // Runs on g0 and does the actual work after putting the g back on the run queue.
491 func mquiesce(gpmaster *g) {
492         activeglen := len(allgs)
493         // enqueue the calling goroutine.
494         restartg(gpmaster)
495         for i := 0; i < activeglen; i++ {
496                 gp := allgs[i]
497                 if readgstatus(gp) == _Gdead {
498                         gp.gcworkdone = true // noop scan.
499                 } else {
500                         gp.gcworkdone = false
501                 }
502                 stopscanstart(gp)
503         }
504
505         // Check that the G's gcwork (such as scanning) has been done. If not do it now.
506         // You can end up doing work here if the page trap on a Grunning Goroutine has
507         // not been sprung or in some race situations. For example a runnable goes dead
508         // and is started up again with a gp->gcworkdone set to false.
509         for i := 0; i < activeglen; i++ {
510                 gp := allgs[i]
511                 for !gp.gcworkdone {
512                         status := readgstatus(gp)
513                         if status == _Gdead {
514                                 //do nothing, scan not needed.
515                                 gp.gcworkdone = true // scan is a noop
516                                 break
517                         }
518                         if status == _Grunning && gp.stackguard0 == uintptr(stackPreempt) && notetsleep(&sched.stopnote, 100*1000) { // nanosecond arg
519                                 noteclear(&sched.stopnote)
520                         } else {
521                                 stopscanstart(gp)
522                         }
523                 }
524         }
525
526         for i := 0; i < activeglen; i++ {
527                 gp := allgs[i]
528                 status := readgstatus(gp)
529                 if isscanstatus(status) {
530                         print("mstopandscang:bottom: post scan bad status gp=", gp, " has status ", hex(status), "\n")
531                         dumpgstatus(gp)
532                 }
533                 if !gp.gcworkdone && status != _Gdead {
534                         print("mstopandscang:bottom: post scan gp=", gp, "->gcworkdone still false\n")
535                         dumpgstatus(gp)
536                 }
537         }
538
539         schedule() // Never returns.
540 }
541
542 // quiesce moves all the goroutines to a GC safepoint which for now is a at preemption point.
543 // If the global gcphase is GCmark quiesce will ensure that all of the goroutine's stacks
544 // have been scanned before it returns.
545 func quiesce(mastergp *g) {
546         castogscanstatus(mastergp, _Grunning, _Gscanenqueue)
547         // Now move this to the g0 (aka m) stack.
548         // g0 will potentially scan this thread and put mastergp on the runqueue
549         mcall(mquiesce)
550 }
551
552 // This is used by the GC as well as the routines that do stack dumps. In the case
553 // of GC all the routines can be reliably stopped. This is not always the case
554 // when the system is in panic or being exited.
555 func stoptheworld() {
556         _g_ := getg()
557
558         // If we hold a lock, then we won't be able to stop another M
559         // that is blocked trying to acquire the lock.
560         if _g_.m.locks > 0 {
561                 gothrow("stoptheworld: holding locks")
562         }
563
564         lock(&sched.lock)
565         sched.stopwait = gomaxprocs
566         atomicstore(&sched.gcwaiting, 1)
567         preemptall()
568         // stop current P
569         _g_.m.p.status = _Pgcstop // Pgcstop is only diagnostic.
570         sched.stopwait--
571         // try to retake all P's in Psyscall status
572         for i := 0; i < int(gomaxprocs); i++ {
573                 p := allp[i]
574                 s := p.status
575                 if s == _Psyscall && cas(&p.status, s, _Pgcstop) {
576                         sched.stopwait--
577                 }
578         }
579         // stop idle P's
580         for {
581                 p := pidleget()
582                 if p == nil {
583                         break
584                 }
585                 p.status = _Pgcstop
586                 sched.stopwait--
587         }
588         wait := sched.stopwait > 0
589         unlock(&sched.lock)
590
591         // wait for remaining P's to stop voluntarily
592         if wait {
593                 for {
594                         // wait for 100us, then try to re-preempt in case of any races
595                         if notetsleep(&sched.stopnote, 100*1000) {
596                                 noteclear(&sched.stopnote)
597                                 break
598                         }
599                         preemptall()
600                 }
601         }
602         if sched.stopwait != 0 {
603                 gothrow("stoptheworld: not stopped")
604         }
605         for i := 0; i < int(gomaxprocs); i++ {
606                 p := allp[i]
607                 if p.status != _Pgcstop {
608                         gothrow("stoptheworld: not stopped")
609                 }
610         }
611 }
612
613 func mhelpgc() {
614         _g_ := getg()
615         _g_.m.helpgc = -1
616 }
617
618 func starttheworld() {
619         _g_ := getg()
620
621         _g_.m.locks++        // disable preemption because it can be holding p in a local var
622         gp := netpoll(false) // non-blocking
623         injectglist(gp)
624         add := needaddgcproc()
625         lock(&sched.lock)
626         if newprocs != 0 {
627                 procresize(newprocs)
628                 newprocs = 0
629         } else {
630                 procresize(gomaxprocs)
631         }
632         sched.gcwaiting = 0
633
634         var p1 *p
635         for {
636                 p := pidleget()
637                 if p == nil {
638                         break
639                 }
640                 // procresize() puts p's with work at the beginning of the list.
641                 // Once we reach a p without a run queue, the rest don't have one either.
642                 if p.runqhead == p.runqtail {
643                         pidleput(p)
644                         break
645                 }
646                 p.m = mget()
647                 p.link = p1
648                 p1 = p
649         }
650         if sched.sysmonwait != 0 {
651                 sched.sysmonwait = 0
652                 notewakeup(&sched.sysmonnote)
653         }
654         unlock(&sched.lock)
655
656         for p1 != nil {
657                 p := p1
658                 p1 = p1.link
659                 if p.m != nil {
660                         mp := p.m
661                         p.m = nil
662                         if mp.nextp != nil {
663                                 gothrow("starttheworld: inconsistent mp->nextp")
664                         }
665                         mp.nextp = p
666                         notewakeup(&mp.park)
667                 } else {
668                         // Start M to run P.  Do not start another M below.
669                         _newm(nil, p)
670                         add = false
671                 }
672         }
673
674         if add {
675                 // If GC could have used another helper proc, start one now,
676                 // in the hope that it will be available next time.
677                 // It would have been even better to start it before the collection,
678                 // but doing so requires allocating memory, so it's tricky to
679                 // coordinate.  This lazy approach works out in practice:
680                 // we don't mind if the first couple gc rounds don't have quite
681                 // the maximum number of procs.
682                 _newm(mhelpgc, nil)
683         }
684         _g_.m.locks--
685         if _g_.m.locks == 0 && _g_.preempt { // restore the preemption request in case we've cleared it in newstack
686                 _g_.stackguard0 = stackPreempt
687         }
688 }
689
690 // Called to start an M.
691 //go:nosplit
692 func mstart() {
693         _g_ := getg()
694
695         if _g_.stack.lo == 0 {
696                 // Initialize stack bounds from system stack.
697                 // Cgo may have left stack size in stack.hi.
698                 size := _g_.stack.hi
699                 if size == 0 {
700                         size = 8192
701                 }
702                 _g_.stack.hi = uintptr(noescape(unsafe.Pointer(&size)))
703                 _g_.stack.lo = _g_.stack.hi - size + 1024
704         }
705         // Initialize stack guards so that we can start calling
706         // both Go and C functions with stack growth prologues.
707         _g_.stackguard0 = _g_.stack.lo + _StackGuard
708         _g_.stackguard1 = _g_.stackguard0
709         mstart1()
710 }
711
712 func mstart1() {
713         _g_ := getg()
714
715         if _g_ != _g_.m.g0 {
716                 gothrow("bad runtimeĀ·mstart")
717         }
718
719         // Record top of stack for use by mcall.
720         // Once we call schedule we're never coming back,
721         // so other calls can reuse this stack space.
722         gosave(&_g_.m.g0.sched)
723         _g_.m.g0.sched.pc = ^uintptr(0) // make sure it is never used
724         asminit()
725         minit()
726
727         // Install signal handlers; after minit so that minit can
728         // prepare the thread to be able to handle the signals.
729         if _g_.m == &m0 {
730                 initsig()
731         }
732
733         if _g_.m.mstartfn != nil {
734                 fn := *(*func())(unsafe.Pointer(&_g_.m.mstartfn))
735                 fn()
736         }
737
738         if _g_.m.helpgc != 0 {
739                 _g_.m.helpgc = 0
740                 stopm()
741         } else if _g_.m != &m0 {
742                 acquirep(_g_.m.nextp)
743                 _g_.m.nextp = nil
744         }
745         schedule()
746
747         // TODO(brainman): This point is never reached, because scheduler
748         // does not release os threads at the moment. But once this path
749         // is enabled, we must remove our seh here.
750 }
751
752 // When running with cgo, we call _cgo_thread_start
753 // to start threads for us so that we can play nicely with
754 // foreign code.
755 var cgoThreadStart unsafe.Pointer
756
757 type cgothreadstart struct {
758         g   *g
759         tls *uint64
760         fn  unsafe.Pointer
761 }
762
763 // Allocate a new m unassociated with any thread.
764 // Can use p for allocation context if needed.
765 func allocm(_p_ *p) *m {
766         _g_ := getg()
767         _g_.m.locks++ // disable GC because it can be called from sysmon
768         if _g_.m.p == nil {
769                 acquirep(_p_) // temporarily borrow p for mallocs in this function
770         }
771         mp := newM()
772         mcommoninit(mp)
773
774         // In case of cgo or Solaris, pthread_create will make us a stack.
775         // Windows and Plan 9 will layout sched stack on OS stack.
776         if iscgo || GOOS == "solaris" || GOOS == "windows" || GOOS == "plan9" {
777                 mp.g0 = malg(-1)
778         } else {
779                 mp.g0 = malg(8192)
780         }
781         mp.g0.m = mp
782
783         if _p_ == _g_.m.p {
784                 releasep()
785         }
786         _g_.m.locks--
787         if _g_.m.locks == 0 && _g_.preempt { // restore the preemption request in case we've cleared it in newstack
788                 _g_.stackguard0 = stackPreempt
789         }
790
791         return mp
792 }
793
794 func allocg() *g {
795         return newG()
796 }
797
798 // needm is called when a cgo callback happens on a
799 // thread without an m (a thread not created by Go).
800 // In this case, needm is expected to find an m to use
801 // and return with m, g initialized correctly.
802 // Since m and g are not set now (likely nil, but see below)
803 // needm is limited in what routines it can call. In particular
804 // it can only call nosplit functions (textflag 7) and cannot
805 // do any scheduling that requires an m.
806 //
807 // In order to avoid needing heavy lifting here, we adopt
808 // the following strategy: there is a stack of available m's
809 // that can be stolen. Using compare-and-swap
810 // to pop from the stack has ABA races, so we simulate
811 // a lock by doing an exchange (via casp) to steal the stack
812 // head and replace the top pointer with MLOCKED (1).
813 // This serves as a simple spin lock that we can use even
814 // without an m. The thread that locks the stack in this way
815 // unlocks the stack by storing a valid stack head pointer.
816 //
817 // In order to make sure that there is always an m structure
818 // available to be stolen, we maintain the invariant that there
819 // is always one more than needed. At the beginning of the
820 // program (if cgo is in use) the list is seeded with a single m.
821 // If needm finds that it has taken the last m off the list, its job
822 // is - once it has installed its own m so that it can do things like
823 // allocate memory - to create a spare m and put it on the list.
824 //
825 // Each of these extra m's also has a g0 and a curg that are
826 // pressed into service as the scheduling stack and current
827 // goroutine for the duration of the cgo callback.
828 //
829 // When the callback is done with the m, it calls dropm to
830 // put the m back on the list.
831 //go:nosplit
832 func needm(x byte) {
833         if needextram != 0 {
834                 // Can happen if C/C++ code calls Go from a global ctor.
835                 // Can not throw, because scheduler is not initialized yet.
836                 // XXX
837                 // write(2, unsafe.Pointer("fatal error: cgo callback before cgo call\n"), sizeof("fatal error: cgo callback before cgo call\n") - 1)
838                 exit(1)
839         }
840
841         // Lock extra list, take head, unlock popped list.
842         // nilokay=false is safe here because of the invariant above,
843         // that the extra list always contains or will soon contain
844         // at least one m.
845         mp := lockextra(false)
846
847         // Set needextram when we've just emptied the list,
848         // so that the eventual call into cgocallbackg will
849         // allocate a new m for the extra list. We delay the
850         // allocation until then so that it can be done
851         // after exitsyscall makes sure it is okay to be
852         // running at all (that is, there's no garbage collection
853         // running right now).
854         mp.needextram = mp.schedlink == nil
855         unlockextra(mp.schedlink)
856
857         // Install g (= m->g0) and set the stack bounds
858         // to match the current stack. We don't actually know
859         // how big the stack is, like we don't know how big any
860         // scheduling stack is, but we assume there's at least 32 kB,
861         // which is more than enough for us.
862         setg(mp.g0)
863         _g_ := getg()
864         _g_.stack.hi = uintptr(noescape(unsafe.Pointer(&x))) + 1024
865         _g_.stack.lo = uintptr(noescape(unsafe.Pointer(&x))) - 32*1024
866         _g_.stackguard0 = _g_.stack.lo + _StackGuard
867
868         // Initialize this thread to use the m.
869         asminit()
870         minit()
871 }
872
873 // newextram allocates an m and puts it on the extra list.
874 // It is called with a working local m, so that it can do things
875 // like call schedlock and allocate.
876 func newextram() {
877         // Create extra goroutine locked to extra m.
878         // The goroutine is the context in which the cgo callback will run.
879         // The sched.pc will never be returned to, but setting it to
880         // goexit makes clear to the traceback routines where
881         // the goroutine stack ends.
882         mp := allocm(nil)
883         gp := malg(4096)
884         gp.sched.pc = funcPC(goexit) + _PCQuantum
885         gp.sched.sp = gp.stack.hi
886         gp.sched.sp -= 4 * regSize // extra space in case of reads slightly beyond frame
887         gp.sched.lr = 0
888         gp.sched.g = gp
889         gp.syscallpc = gp.sched.pc
890         gp.syscallsp = gp.sched.sp
891         // malg returns status as Gidle, change to Gsyscall before adding to allg
892         // where GC will see it.
893         casgstatus(gp, _Gidle, _Gsyscall)
894         gp.m = mp
895         mp.curg = gp
896         mp.locked = _LockInternal
897         mp.lockedg = gp
898         gp.lockedm = mp
899         gp.goid = int64(xadd64(&sched.goidgen, 1))
900         if raceenabled {
901                 gp.racectx = racegostart(funcPC(newextram))
902         }
903         // put on allg for garbage collector
904         allgadd(gp)
905
906         // Add m to the extra list.
907         mnext := lockextra(true)
908         mp.schedlink = mnext
909         unlockextra(mp)
910 }
911
912 // dropm is called when a cgo callback has called needm but is now
913 // done with the callback and returning back into the non-Go thread.
914 // It puts the current m back onto the extra list.
915 //
916 // The main expense here is the call to signalstack to release the
917 // m's signal stack, and then the call to needm on the next callback
918 // from this thread. It is tempting to try to save the m for next time,
919 // which would eliminate both these costs, but there might not be
920 // a next time: the current thread (which Go does not control) might exit.
921 // If we saved the m for that thread, there would be an m leak each time
922 // such a thread exited. Instead, we acquire and release an m on each
923 // call. These should typically not be scheduling operations, just a few
924 // atomics, so the cost should be small.
925 //
926 // TODO(rsc): An alternative would be to allocate a dummy pthread per-thread
927 // variable using pthread_key_create. Unlike the pthread keys we already use
928 // on OS X, this dummy key would never be read by Go code. It would exist
929 // only so that we could register at thread-exit-time destructor.
930 // That destructor would put the m back onto the extra list.
931 // This is purely a performance optimization. The current version,
932 // in which dropm happens on each cgo call, is still correct too.
933 // We may have to keep the current version on systems with cgo
934 // but without pthreads, like Windows.
935 func dropm() {
936         // Undo whatever initialization minit did during needm.
937         unminit()
938
939         // Clear m and g, and return m to the extra list.
940         // After the call to setmg we can only call nosplit functions.
941         mp := getg().m
942         setg(nil)
943
944         mnext := lockextra(true)
945         mp.schedlink = mnext
946         unlockextra(mp)
947 }
948
949 var extram uintptr
950
951 // lockextra locks the extra list and returns the list head.
952 // The caller must unlock the list by storing a new list head
953 // to extram. If nilokay is true, then lockextra will
954 // return a nil list head if that's what it finds. If nilokay is false,
955 // lockextra will keep waiting until the list head is no longer nil.
956 //go:nosplit
957 func lockextra(nilokay bool) *m {
958         const locked = 1
959
960         for {
961                 old := atomicloaduintptr(&extram)
962                 if old == locked {
963                         yield := osyield
964                         yield()
965                         continue
966                 }
967                 if old == 0 && !nilokay {
968                         usleep(1)
969                         continue
970                 }
971                 if casuintptr(&extram, old, locked) {
972                         return (*m)(unsafe.Pointer(old))
973                 }
974                 yield := osyield
975                 yield()
976                 continue
977         }
978 }
979
980 //go:nosplit
981 func unlockextra(mp *m) {
982         atomicstoreuintptr(&extram, uintptr(unsafe.Pointer(mp)))
983 }
984
985 // Create a new m.  It will start off with a call to fn, or else the scheduler.
986 func _newm(fn func(), _p_ *p) {
987         mp := allocm(_p_)
988         mp.nextp = _p_
989         mp.mstartfn = *(*unsafe.Pointer)(unsafe.Pointer(&fn))
990
991         if iscgo {
992                 var ts cgothreadstart
993                 if _cgo_thread_start == nil {
994                         gothrow("_cgo_thread_start missing")
995                 }
996                 ts.g = mp.g0
997                 ts.tls = (*uint64)(unsafe.Pointer(&mp.tls[0]))
998                 ts.fn = unsafe.Pointer(funcPC(mstart))
999                 asmcgocall(_cgo_thread_start, unsafe.Pointer(&ts))
1000                 return
1001         }
1002         newosproc(mp, unsafe.Pointer(mp.g0.stack.hi))
1003 }
1004
1005 // Stops execution of the current m until new work is available.
1006 // Returns with acquired P.
1007 func stopm() {
1008         _g_ := getg()
1009
1010         if _g_.m.locks != 0 {
1011                 gothrow("stopm holding locks")
1012         }
1013         if _g_.m.p != nil {
1014                 gothrow("stopm holding p")
1015         }
1016         if _g_.m.spinning {
1017                 _g_.m.spinning = false
1018                 xadd(&sched.nmspinning, -1)
1019         }
1020
1021 retry:
1022         lock(&sched.lock)
1023         mput(_g_.m)
1024         unlock(&sched.lock)
1025         notesleep(&_g_.m.park)
1026         noteclear(&_g_.m.park)
1027         if _g_.m.helpgc != 0 {
1028                 gchelper()
1029                 _g_.m.helpgc = 0
1030                 _g_.m.mcache = nil
1031                 goto retry
1032         }
1033         acquirep(_g_.m.nextp)
1034         _g_.m.nextp = nil
1035 }
1036
1037 func mspinning() {
1038         getg().m.spinning = true
1039 }
1040
1041 // Schedules some M to run the p (creates an M if necessary).
1042 // If p==nil, tries to get an idle P, if no idle P's does nothing.
1043 func startm(_p_ *p, spinning bool) {
1044         lock(&sched.lock)
1045         if _p_ == nil {
1046                 _p_ = pidleget()
1047                 if _p_ == nil {
1048                         unlock(&sched.lock)
1049                         if spinning {
1050                                 xadd(&sched.nmspinning, -1)
1051                         }
1052                         return
1053                 }
1054         }
1055         mp := mget()
1056         unlock(&sched.lock)
1057         if mp == nil {
1058                 var fn func()
1059                 if spinning {
1060                         fn = mspinning
1061                 }
1062                 _newm(fn, _p_)
1063                 return
1064         }
1065         if mp.spinning {
1066                 gothrow("startm: m is spinning")
1067         }
1068         if mp.nextp != nil {
1069                 gothrow("startm: m has p")
1070         }
1071         mp.spinning = spinning
1072         mp.nextp = _p_
1073         notewakeup(&mp.park)
1074 }
1075
1076 // Hands off P from syscall or locked M.
1077 func handoffp(_p_ *p) {
1078         // if it has local work, start it straight away
1079         if _p_.runqhead != _p_.runqtail || sched.runqsize != 0 {
1080                 startm(_p_, false)
1081                 return
1082         }
1083         // no local work, check that there are no spinning/idle M's,
1084         // otherwise our help is not required
1085         if atomicload(&sched.nmspinning)+atomicload(&sched.npidle) == 0 && cas(&sched.nmspinning, 0, 1) { // TODO: fast atomic
1086                 startm(_p_, true)
1087                 return
1088         }
1089         lock(&sched.lock)
1090         if sched.gcwaiting != 0 {
1091                 _p_.status = _Pgcstop
1092                 sched.stopwait--
1093                 if sched.stopwait == 0 {
1094                         notewakeup(&sched.stopnote)
1095                 }
1096                 unlock(&sched.lock)
1097                 return
1098         }
1099         if sched.runqsize != 0 {
1100                 unlock(&sched.lock)
1101                 startm(_p_, false)
1102                 return
1103         }
1104         // If this is the last running P and nobody is polling network,
1105         // need to wakeup another M to poll network.
1106         if sched.npidle == uint32(gomaxprocs-1) && atomicload64(&sched.lastpoll) != 0 {
1107                 unlock(&sched.lock)
1108                 startm(_p_, false)
1109                 return
1110         }
1111         pidleput(_p_)
1112         unlock(&sched.lock)
1113 }
1114
1115 // Tries to add one more P to execute G's.
1116 // Called when a G is made runnable (newproc, ready).
1117 func wakep() {
1118         // be conservative about spinning threads
1119         if !cas(&sched.nmspinning, 0, 1) {
1120                 return
1121         }
1122         startm(nil, true)
1123 }
1124
1125 // Stops execution of the current m that is locked to a g until the g is runnable again.
1126 // Returns with acquired P.
1127 func stoplockedm() {
1128         _g_ := getg()
1129
1130         if _g_.m.lockedg == nil || _g_.m.lockedg.lockedm != _g_.m {
1131                 gothrow("stoplockedm: inconsistent locking")
1132         }
1133         if _g_.m.p != nil {
1134                 // Schedule another M to run this p.
1135                 _p_ := releasep()
1136                 handoffp(_p_)
1137         }
1138         incidlelocked(1)
1139         // Wait until another thread schedules lockedg again.
1140         notesleep(&_g_.m.park)
1141         noteclear(&_g_.m.park)
1142         status := readgstatus(_g_.m.lockedg)
1143         if status&^_Gscan != _Grunnable {
1144                 print("runtime:stoplockedm: g is not Grunnable or Gscanrunnable\n")
1145                 dumpgstatus(_g_)
1146                 gothrow("stoplockedm: not runnable")
1147         }
1148         acquirep(_g_.m.nextp)
1149         _g_.m.nextp = nil
1150 }
1151
1152 // Schedules the locked m to run the locked gp.
1153 func startlockedm(gp *g) {
1154         _g_ := getg()
1155
1156         mp := gp.lockedm
1157         if mp == _g_.m {
1158                 gothrow("startlockedm: locked to me")
1159         }
1160         if mp.nextp != nil {
1161                 gothrow("startlockedm: m has p")
1162         }
1163         // directly handoff current P to the locked m
1164         incidlelocked(-1)
1165         _p_ := releasep()
1166         mp.nextp = _p_
1167         notewakeup(&mp.park)
1168         stopm()
1169 }
1170
1171 // Stops the current m for stoptheworld.
1172 // Returns when the world is restarted.
1173 func gcstopm() {
1174         _g_ := getg()
1175
1176         if sched.gcwaiting == 0 {
1177                 gothrow("gcstopm: not waiting for gc")
1178         }
1179         if _g_.m.spinning {
1180                 _g_.m.spinning = false
1181                 xadd(&sched.nmspinning, -1)
1182         }
1183         _p_ := releasep()
1184         lock(&sched.lock)
1185         _p_.status = _Pgcstop
1186         sched.stopwait--
1187         if sched.stopwait == 0 {
1188                 notewakeup(&sched.stopnote)
1189         }
1190         unlock(&sched.lock)
1191         stopm()
1192 }
1193
1194 // Schedules gp to run on the current M.
1195 // Never returns.
1196 func execute(gp *g) {
1197         _g_ := getg()
1198
1199         casgstatus(gp, _Grunnable, _Grunning)
1200         gp.waitsince = 0
1201         gp.preempt = false
1202         gp.stackguard0 = gp.stack.lo + _StackGuard
1203         _g_.m.p.schedtick++
1204         _g_.m.curg = gp
1205         gp.m = _g_.m
1206
1207         // Check whether the profiler needs to be turned on or off.
1208         hz := sched.profilehz
1209         if _g_.m.profilehz != hz {
1210                 resetcpuprofiler(hz)
1211         }
1212
1213         gogo(&gp.sched)
1214 }
1215
1216 // Finds a runnable goroutine to execute.
1217 // Tries to steal from other P's, get g from global queue, poll network.
1218 func findrunnable() *g {
1219         _g_ := getg()
1220
1221 top:
1222         if sched.gcwaiting != 0 {
1223                 gcstopm()
1224                 goto top
1225         }
1226         if fingwait && fingwake {
1227                 if gp := wakefing(); gp != nil {
1228                         ready(gp)
1229                 }
1230         }
1231
1232         // local runq
1233         if gp := runqget(_g_.m.p); gp != nil {
1234                 return gp
1235         }
1236
1237         // global runq
1238         if sched.runqsize != 0 {
1239                 lock(&sched.lock)
1240                 gp := globrunqget(_g_.m.p, 0)
1241                 unlock(&sched.lock)
1242                 if gp != nil {
1243                         return gp
1244                 }
1245         }
1246
1247         // poll network - returns list of goroutines
1248         if gp := netpoll(false); gp != nil { // non-blocking
1249                 injectglist(gp.schedlink)
1250                 casgstatus(gp, _Gwaiting, _Grunnable)
1251                 return gp
1252         }
1253
1254         // If number of spinning M's >= number of busy P's, block.
1255         // This is necessary to prevent excessive CPU consumption
1256         // when GOMAXPROCS>>1 but the program parallelism is low.
1257         if !_g_.m.spinning && 2*atomicload(&sched.nmspinning) >= uint32(gomaxprocs)-atomicload(&sched.npidle) { // TODO: fast atomic
1258                 goto stop
1259         }
1260         if !_g_.m.spinning {
1261                 _g_.m.spinning = true
1262                 xadd(&sched.nmspinning, 1)
1263         }
1264         // random steal from other P's
1265         for i := 0; i < int(2*gomaxprocs); i++ {
1266                 if sched.gcwaiting != 0 {
1267                         goto top
1268                 }
1269                 _p_ := allp[fastrand1()%uint32(gomaxprocs)]
1270                 var gp *g
1271                 if _p_ == _g_.m.p {
1272                         gp = runqget(_p_)
1273                 } else {
1274                         gp = runqsteal(_g_.m.p, _p_)
1275                 }
1276                 if gp != nil {
1277                         return gp
1278                 }
1279         }
1280 stop:
1281
1282         // return P and block
1283         lock(&sched.lock)
1284         if sched.gcwaiting != 0 {
1285                 unlock(&sched.lock)
1286                 goto top
1287         }
1288         if sched.runqsize != 0 {
1289                 gp := globrunqget(_g_.m.p, 0)
1290                 unlock(&sched.lock)
1291                 return gp
1292         }
1293         _p_ := releasep()
1294         pidleput(_p_)
1295         unlock(&sched.lock)
1296         if _g_.m.spinning {
1297                 _g_.m.spinning = false
1298                 xadd(&sched.nmspinning, -1)
1299         }
1300
1301         // check all runqueues once again
1302         for i := 0; i < int(gomaxprocs); i++ {
1303                 _p_ := allp[i]
1304                 if _p_ != nil && _p_.runqhead != _p_.runqtail {
1305                         lock(&sched.lock)
1306                         _p_ = pidleget()
1307                         unlock(&sched.lock)
1308                         if _p_ != nil {
1309                                 acquirep(_p_)
1310                                 goto top
1311                         }
1312                         break
1313                 }
1314         }
1315
1316         // poll network
1317         if xchg64(&sched.lastpoll, 0) != 0 {
1318                 if _g_.m.p != nil {
1319                         gothrow("findrunnable: netpoll with p")
1320                 }
1321                 if _g_.m.spinning {
1322                         gothrow("findrunnable: netpoll with spinning")
1323                 }
1324                 gp := netpoll(true) // block until new work is available
1325                 atomicstore64(&sched.lastpoll, uint64(nanotime()))
1326                 if gp != nil {
1327                         lock(&sched.lock)
1328                         _p_ = pidleget()
1329                         unlock(&sched.lock)
1330                         if _p_ != nil {
1331                                 acquirep(_p_)
1332                                 injectglist(gp.schedlink)
1333                                 casgstatus(gp, _Gwaiting, _Grunnable)
1334                                 return gp
1335                         }
1336                         injectglist(gp)
1337                 }
1338         }
1339         stopm()
1340         goto top
1341 }
1342
1343 func resetspinning() {
1344         _g_ := getg()
1345
1346         var nmspinning uint32
1347         if _g_.m.spinning {
1348                 _g_.m.spinning = false
1349                 nmspinning = xadd(&sched.nmspinning, -1)
1350                 if nmspinning < 0 {
1351                         gothrow("findrunnable: negative nmspinning")
1352                 }
1353         } else {
1354                 nmspinning = atomicload(&sched.nmspinning)
1355         }
1356
1357         // M wakeup policy is deliberately somewhat conservative (see nmspinning handling),
1358         // so see if we need to wakeup another P here.
1359         if nmspinning == 0 && atomicload(&sched.npidle) > 0 {
1360                 wakep()
1361         }
1362 }
1363
1364 // Injects the list of runnable G's into the scheduler.
1365 // Can run concurrently with GC.
1366 func injectglist(glist *g) {
1367         if glist == nil {
1368                 return
1369         }
1370         lock(&sched.lock)
1371         var n int
1372         for n = 0; glist != nil; n++ {
1373                 gp := glist
1374                 glist = gp.schedlink
1375                 casgstatus(gp, _Gwaiting, _Grunnable)
1376                 globrunqput(gp)
1377         }
1378         unlock(&sched.lock)
1379         for ; n != 0 && sched.npidle != 0; n-- {
1380                 startm(nil, false)
1381         }
1382 }
1383
1384 // One round of scheduler: find a runnable goroutine and execute it.
1385 // Never returns.
1386 func schedule() {
1387         _g_ := getg()
1388
1389         if _g_.m.locks != 0 {
1390                 gothrow("schedule: holding locks")
1391         }
1392
1393         if _g_.m.lockedg != nil {
1394                 stoplockedm()
1395                 execute(_g_.m.lockedg) // Never returns.
1396         }
1397
1398 top:
1399         if sched.gcwaiting != 0 {
1400                 gcstopm()
1401                 goto top
1402         }
1403
1404         var gp *g
1405         // Check the global runnable queue once in a while to ensure fairness.
1406         // Otherwise two goroutines can completely occupy the local runqueue
1407         // by constantly respawning each other.
1408         tick := _g_.m.p.schedtick
1409         // This is a fancy way to say tick%61==0,
1410         // it uses 2 MUL instructions instead of a single DIV and so is faster on modern processors.
1411         if uint64(tick)-((uint64(tick)*0x4325c53f)>>36)*61 == 0 && sched.runqsize > 0 {
1412                 lock(&sched.lock)
1413                 gp = globrunqget(_g_.m.p, 1)
1414                 unlock(&sched.lock)
1415                 if gp != nil {
1416                         resetspinning()
1417                 }
1418         }
1419         if gp == nil {
1420                 gp = runqget(_g_.m.p)
1421                 if gp != nil && _g_.m.spinning {
1422                         gothrow("schedule: spinning with local work")
1423                 }
1424         }
1425         if gp == nil {
1426                 gp = findrunnable() // blocks until work is available
1427                 resetspinning()
1428         }
1429
1430         if gp.lockedm != nil {
1431                 // Hands off own p to the locked m,
1432                 // then blocks waiting for a new p.
1433                 startlockedm(gp)
1434                 goto top
1435         }
1436
1437         execute(gp)
1438 }
1439
1440 // dropg removes the association between m and the current goroutine m->curg (gp for short).
1441 // Typically a caller sets gp's status away from Grunning and then
1442 // immediately calls dropg to finish the job. The caller is also responsible
1443 // for arranging that gp will be restarted using ready at an
1444 // appropriate time. After calling dropg and arranging for gp to be
1445 // readied later, the caller can do other work but eventually should
1446 // call schedule to restart the scheduling of goroutines on this m.
1447 func dropg() {
1448         _g_ := getg()
1449
1450         if _g_.m.lockedg == nil {
1451                 _g_.m.curg.m = nil
1452                 _g_.m.curg = nil
1453         }
1454 }
1455
1456 // Puts the current goroutine into a waiting state and calls unlockf.
1457 // If unlockf returns false, the goroutine is resumed.
1458 func park(unlockf func(*g, unsafe.Pointer) bool, lock unsafe.Pointer, reason string) {
1459         _g_ := getg()
1460
1461         _g_.m.waitlock = lock
1462         _g_.m.waitunlockf = *(*unsafe.Pointer)(unsafe.Pointer(&unlockf))
1463         _g_.waitreason = reason
1464         mcall(park_m)
1465 }
1466
1467 func parkunlock_c(gp *g, lock unsafe.Pointer) bool {
1468         unlock((*mutex)(lock))
1469         return true
1470 }
1471
1472 // Puts the current goroutine into a waiting state and unlocks the lock.
1473 // The goroutine can be made runnable again by calling ready(gp).
1474 func parkunlock(lock *mutex, reason string) {
1475         park(parkunlock_c, unsafe.Pointer(lock), reason)
1476 }
1477
1478 // park continuation on g0.
1479 func park_m(gp *g) {
1480         _g_ := getg()
1481
1482         casgstatus(gp, _Grunning, _Gwaiting)
1483         dropg()
1484
1485         if _g_.m.waitunlockf != nil {
1486                 fn := *(*func(*g, unsafe.Pointer) bool)(unsafe.Pointer(&_g_.m.waitunlockf))
1487                 ok := fn(gp, _g_.m.waitlock)
1488                 _g_.m.waitunlockf = nil
1489                 _g_.m.waitlock = nil
1490                 if !ok {
1491                         casgstatus(gp, _Gwaiting, _Grunnable)
1492                         execute(gp) // Schedule it back, never returns.
1493                 }
1494         }
1495         schedule()
1496 }
1497
1498 // Gosched continuation on g0.
1499 func gosched_m(gp *g) {
1500         status := readgstatus(gp)
1501         if status&^_Gscan != _Grunning {
1502                 dumpgstatus(gp)
1503                 gothrow("bad g status")
1504         }
1505         casgstatus(gp, _Grunning, _Grunnable)
1506         dropg()
1507         lock(&sched.lock)
1508         globrunqput(gp)
1509         unlock(&sched.lock)
1510
1511         schedule()
1512 }
1513
1514 // Finishes execution of the current goroutine.
1515 // Must be NOSPLIT because it is called from Go. (TODO - probably not anymore)
1516 //go:nosplit
1517 func goexit1() {
1518         if raceenabled {
1519                 racegoend()
1520         }
1521         mcall(goexit0)
1522 }
1523
1524 // goexit continuation on g0.
1525 func goexit0(gp *g) {
1526         _g_ := getg()
1527
1528         casgstatus(gp, _Grunning, _Gdead)
1529         gp.m = nil
1530         gp.lockedm = nil
1531         _g_.m.lockedg = nil
1532         gp.paniconfault = false
1533         gp._defer = nil // should be true already but just in case.
1534         gp._panic = nil // non-nil for Goexit during panic. points at stack-allocated data.
1535         gp.writebuf = nil
1536         gp.waitreason = ""
1537         gp.param = nil
1538
1539         dropg()
1540
1541         if _g_.m.locked&^_LockExternal != 0 {
1542                 print("invalid m->locked = ", _g_.m.locked, "\n")
1543                 gothrow("internal lockOSThread error")
1544         }
1545         _g_.m.locked = 0
1546         gfput(_g_.m.p, gp)
1547         schedule()
1548 }
1549
1550 //go:nosplit
1551 func save(pc, sp uintptr) {
1552         _g_ := getg()
1553
1554         _g_.sched.pc = pc
1555         _g_.sched.sp = sp
1556         _g_.sched.lr = 0
1557         _g_.sched.ret = 0
1558         _g_.sched.ctxt = nil
1559         _g_.sched.g = _g_
1560 }
1561
1562 // The goroutine g is about to enter a system call.
1563 // Record that it's not using the cpu anymore.
1564 // This is called only from the go syscall library and cgocall,
1565 // not from the low-level system calls used by the
1566 //
1567 // Entersyscall cannot split the stack: the gosave must
1568 // make g->sched refer to the caller's stack segment, because
1569 // entersyscall is going to return immediately after.
1570 //
1571 // Nothing entersyscall calls can split the stack either.
1572 // We cannot safely move the stack during an active call to syscall,
1573 // because we do not know which of the uintptr arguments are
1574 // really pointers (back into the stack).
1575 // In practice, this means that we make the fast path run through
1576 // entersyscall doing no-split things, and the slow path has to use systemstack
1577 // to run bigger things on the system stack.
1578 //
1579 // reentersyscall is the entry point used by cgo callbacks, where explicitly
1580 // saved SP and PC are restored. This is needed when exitsyscall will be called
1581 // from a function further up in the call stack than the parent, as g->syscallsp
1582 // must always point to a valid stack frame. entersyscall below is the normal
1583 // entry point for syscalls, which obtains the SP and PC from the caller.
1584 //go:nosplit
1585 func reentersyscall(pc, sp uintptr) {
1586         _g_ := getg()
1587
1588         // Disable preemption because during this function g is in Gsyscall status,
1589         // but can have inconsistent g->sched, do not let GC observe it.
1590         _g_.m.locks++
1591
1592         // Entersyscall must not call any function that might split/grow the stack.
1593         // (See details in comment above.)
1594         // Catch calls that might, by replacing the stack guard with something that
1595         // will trip any stack check and leaving a flag to tell newstack to die.
1596         _g_.stackguard0 = stackPreempt
1597         _g_.throwsplit = true
1598
1599         // Leave SP around for GC and traceback.
1600         save(pc, sp)
1601         _g_.syscallsp = sp
1602         _g_.syscallpc = pc
1603         casgstatus(_g_, _Grunning, _Gsyscall)
1604         if _g_.syscallsp < _g_.stack.lo || _g_.stack.hi < _g_.syscallsp {
1605                 systemstack(entersyscall_bad)
1606         }
1607
1608         if atomicload(&sched.sysmonwait) != 0 { // TODO: fast atomic
1609                 systemstack(entersyscall_sysmon)
1610                 save(pc, sp)
1611         }
1612
1613         _g_.m.mcache = nil
1614         _g_.m.p.m = nil
1615         atomicstore(&_g_.m.p.status, _Psyscall)
1616         if sched.gcwaiting != 0 {
1617                 systemstack(entersyscall_gcwait)
1618                 save(pc, sp)
1619         }
1620
1621         // Goroutines must not split stacks in Gsyscall status (it would corrupt g->sched).
1622         // We set _StackGuard to StackPreempt so that first split stack check calls morestack.
1623         // Morestack detects this case and throws.
1624         _g_.stackguard0 = stackPreempt
1625         _g_.m.locks--
1626 }
1627
1628 // Standard syscall entry used by the go syscall library and normal cgo calls.
1629 //go:nosplit
1630 func entersyscall(dummy int32) {
1631         reentersyscall(getcallerpc(unsafe.Pointer(&dummy)), getcallersp(unsafe.Pointer(&dummy)))
1632 }
1633
1634 func entersyscall_bad() {
1635         var gp *g
1636         gp = getg().m.curg
1637         print("entersyscall inconsistent ", hex(gp.syscallsp), " [", hex(gp.stack.lo), ",", hex(gp.stack.hi), "]\n")
1638         gothrow("entersyscall")
1639 }
1640
1641 func entersyscall_sysmon() {
1642         lock(&sched.lock)
1643         if atomicload(&sched.sysmonwait) != 0 {
1644                 atomicstore(&sched.sysmonwait, 0)
1645                 notewakeup(&sched.sysmonnote)
1646         }
1647         unlock(&sched.lock)
1648 }
1649
1650 func entersyscall_gcwait() {
1651         _g_ := getg()
1652
1653         lock(&sched.lock)
1654         if sched.stopwait > 0 && cas(&_g_.m.p.status, _Psyscall, _Pgcstop) {
1655                 if sched.stopwait--; sched.stopwait == 0 {
1656                         notewakeup(&sched.stopnote)
1657                 }
1658         }
1659         unlock(&sched.lock)
1660 }
1661
1662 // The same as entersyscall(), but with a hint that the syscall is blocking.
1663 //go:nosplit
1664 func entersyscallblock(dummy int32) {
1665         _g_ := getg()
1666
1667         _g_.m.locks++ // see comment in entersyscall
1668         _g_.throwsplit = true
1669         _g_.stackguard0 = stackPreempt // see comment in entersyscall
1670
1671         // Leave SP around for GC and traceback.
1672         save(getcallerpc(unsafe.Pointer(&dummy)), getcallersp(unsafe.Pointer(&dummy)))
1673         _g_.syscallsp = _g_.sched.sp
1674         _g_.syscallpc = _g_.sched.pc
1675         casgstatus(_g_, _Grunning, _Gsyscall)
1676         if _g_.syscallsp < _g_.stack.lo || _g_.stack.hi < _g_.syscallsp {
1677                 systemstack(entersyscall_bad)
1678         }
1679
1680         systemstack(entersyscallblock_handoff)
1681
1682         // Resave for traceback during blocked call.
1683         save(getcallerpc(unsafe.Pointer(&dummy)), getcallersp(unsafe.Pointer(&dummy)))
1684
1685         _g_.m.locks--
1686 }
1687
1688 func entersyscallblock_handoff() {
1689         handoffp(releasep())
1690 }
1691
1692 // The goroutine g exited its system call.
1693 // Arrange for it to run on a cpu again.
1694 // This is called only from the go syscall library, not
1695 // from the low-level system calls used by the
1696 //go:nosplit
1697 func exitsyscall(dummy int32) {
1698         _g_ := getg()
1699
1700         _g_.m.locks++ // see comment in entersyscall
1701         if getcallersp(unsafe.Pointer(&dummy)) > _g_.syscallsp {
1702                 gothrow("exitsyscall: syscall frame is no longer valid")
1703         }
1704
1705         _g_.waitsince = 0
1706         if exitsyscallfast() {
1707                 if _g_.m.mcache == nil {
1708                         gothrow("lost mcache")
1709                 }
1710                 // There's a cpu for us, so we can run.
1711                 _g_.m.p.syscalltick++
1712                 // We need to cas the status and scan before resuming...
1713                 casgstatus(_g_, _Gsyscall, _Grunning)
1714
1715                 // Garbage collector isn't running (since we are),
1716                 // so okay to clear syscallsp.
1717                 _g_.syscallsp = 0
1718                 _g_.m.locks--
1719                 if _g_.preempt {
1720                         // restore the preemption request in case we've cleared it in newstack
1721                         _g_.stackguard0 = stackPreempt
1722                 } else {
1723                         // otherwise restore the real _StackGuard, we've spoiled it in entersyscall/entersyscallblock
1724                         _g_.stackguard0 = _g_.stack.lo + _StackGuard
1725                 }
1726                 _g_.throwsplit = false
1727                 return
1728         }
1729
1730         _g_.m.locks--
1731
1732         // Call the scheduler.
1733         mcall(exitsyscall0)
1734
1735         if _g_.m.mcache == nil {
1736                 gothrow("lost mcache")
1737         }
1738
1739         // Scheduler returned, so we're allowed to run now.
1740         // Delete the syscallsp information that we left for
1741         // the garbage collector during the system call.
1742         // Must wait until now because until gosched returns
1743         // we don't know for sure that the garbage collector
1744         // is not running.
1745         _g_.syscallsp = 0
1746         _g_.m.p.syscalltick++
1747         _g_.throwsplit = false
1748 }
1749
1750 //go:nosplit
1751 func exitsyscallfast() bool {
1752         _g_ := getg()
1753
1754         // Freezetheworld sets stopwait but does not retake P's.
1755         if sched.stopwait != 0 {
1756                 _g_.m.p = nil
1757                 return false
1758         }
1759
1760         // Try to re-acquire the last P.
1761         if _g_.m.p != nil && _g_.m.p.status == _Psyscall && cas(&_g_.m.p.status, _Psyscall, _Prunning) {
1762                 // There's a cpu for us, so we can run.
1763                 _g_.m.mcache = _g_.m.p.mcache
1764                 _g_.m.p.m = _g_.m
1765                 return true
1766         }
1767
1768         // Try to get any other idle P.
1769         _g_.m.p = nil
1770         if sched.pidle != nil {
1771                 var ok bool
1772                 systemstack(func() {
1773                         ok = exitsyscallfast_pidle()
1774                 })
1775                 if ok {
1776                         return true
1777                 }
1778         }
1779         return false
1780 }
1781
1782 func exitsyscallfast_pidle() bool {
1783         lock(&sched.lock)
1784         _p_ := pidleget()
1785         if _p_ != nil && atomicload(&sched.sysmonwait) != 0 {
1786                 atomicstore(&sched.sysmonwait, 0)
1787                 notewakeup(&sched.sysmonnote)
1788         }
1789         unlock(&sched.lock)
1790         if _p_ != nil {
1791                 acquirep(_p_)
1792                 return true
1793         }
1794         return false
1795 }
1796
1797 // exitsyscall slow path on g0.
1798 // Failed to acquire P, enqueue gp as runnable.
1799 func exitsyscall0(gp *g) {
1800         _g_ := getg()
1801
1802         casgstatus(gp, _Gsyscall, _Grunnable)
1803         dropg()
1804         lock(&sched.lock)
1805         _p_ := pidleget()
1806         if _p_ == nil {
1807                 globrunqput(gp)
1808         } else if atomicload(&sched.sysmonwait) != 0 {
1809                 atomicstore(&sched.sysmonwait, 0)
1810                 notewakeup(&sched.sysmonnote)
1811         }
1812         unlock(&sched.lock)
1813         if _p_ != nil {
1814                 acquirep(_p_)
1815                 execute(gp) // Never returns.
1816         }
1817         if _g_.m.lockedg != nil {
1818                 // Wait until another thread schedules gp and so m again.
1819                 stoplockedm()
1820                 execute(gp) // Never returns.
1821         }
1822         stopm()
1823         schedule() // Never returns.
1824 }
1825
1826 func beforefork() {
1827         gp := getg().m.curg
1828
1829         // Fork can hang if preempted with signals frequently enough (see issue 5517).
1830         // Ensure that we stay on the same M where we disable profiling.
1831         gp.m.locks++
1832         if gp.m.profilehz != 0 {
1833                 resetcpuprofiler(0)
1834         }
1835
1836         // This function is called before fork in syscall package.
1837         // Code between fork and exec must not allocate memory nor even try to grow stack.
1838         // Here we spoil g->_StackGuard to reliably detect any attempts to grow stack.
1839         // runtime_AfterFork will undo this in parent process, but not in child.
1840         gp.stackguard0 = stackFork
1841 }
1842
1843 // Called from syscall package before fork.
1844 //go:nosplit
1845 func syscall_BeforeFork() {
1846         systemstack(beforefork)
1847 }
1848
1849 func afterfork() {
1850         gp := getg().m.curg
1851
1852         // See the comment in beforefork.
1853         gp.stackguard0 = gp.stack.lo + _StackGuard
1854
1855         hz := sched.profilehz
1856         if hz != 0 {
1857                 resetcpuprofiler(hz)
1858         }
1859         gp.m.locks--
1860 }
1861
1862 // Called from syscall package after fork in parent.
1863 //go:nosplit
1864 func syscall_AfterFork() {
1865         systemstack(afterfork)
1866 }
1867
1868 // Allocate a new g, with a stack big enough for stacksize bytes.
1869 func malg(stacksize int32) *g {
1870         newg := allocg()
1871         if stacksize >= 0 {
1872                 stacksize = round2(_StackSystem + stacksize)
1873                 systemstack(func() {
1874                         newg.stack = stackalloc(uint32(stacksize))
1875                 })
1876                 newg.stackguard0 = newg.stack.lo + _StackGuard
1877                 newg.stackguard1 = ^uintptr(0)
1878         }
1879         return newg
1880 }
1881
1882 // Create a new g running fn with siz bytes of arguments.
1883 // Put it on the queue of g's waiting to run.
1884 // The compiler turns a go statement into a call to this.
1885 // Cannot split the stack because it assumes that the arguments
1886 // are available sequentially after &fn; they would not be
1887 // copied if a stack split occurred.
1888 //go:nosplit
1889 func newproc(siz int32, fn *funcval) {
1890         argp := add(unsafe.Pointer(&fn), ptrSize)
1891         if thechar == '5' {
1892                 argp = add(argp, ptrSize) // skip caller's saved LR
1893         }
1894
1895         pc := getcallerpc(unsafe.Pointer(&siz))
1896         systemstack(func() {
1897                 newproc1(fn, (*uint8)(argp), siz, 0, pc)
1898         })
1899 }
1900
1901 // Create a new g running fn with narg bytes of arguments starting
1902 // at argp and returning nret bytes of results.  callerpc is the
1903 // address of the go statement that created this.  The new g is put
1904 // on the queue of g's waiting to run.
1905 func newproc1(fn *funcval, argp *uint8, narg int32, nret int32, callerpc uintptr) *g {
1906         _g_ := getg()
1907
1908         if fn == nil {
1909                 _g_.m.throwing = -1 // do not dump full stacks
1910                 gothrow("go of nil func value")
1911         }
1912         _g_.m.locks++ // disable preemption because it can be holding p in a local var
1913         siz := narg + nret
1914         siz = (siz + 7) &^ 7
1915
1916         // We could allocate a larger initial stack if necessary.
1917         // Not worth it: this is almost always an error.
1918         // 4*sizeof(uintreg): extra space added below
1919         // sizeof(uintreg): caller's LR (arm) or return address (x86, in gostartcall).
1920         if siz >= _StackMin-4*regSize-regSize {
1921                 gothrow("newproc: function arguments too large for new goroutine")
1922         }
1923
1924         _p_ := _g_.m.p
1925         newg := gfget(_p_)
1926         if newg == nil {
1927                 newg = malg(_StackMin)
1928                 casgstatus(newg, _Gidle, _Gdead)
1929                 allgadd(newg) // publishes with a g->status of Gdead so GC scanner doesn't look at uninitialized stack.
1930         }
1931         if newg.stack.hi == 0 {
1932                 gothrow("newproc1: newg missing stack")
1933         }
1934
1935         if readgstatus(newg) != _Gdead {
1936                 gothrow("newproc1: new g is not Gdead")
1937         }
1938
1939         sp := newg.stack.hi
1940         sp -= 4 * regSize // extra space in case of reads slightly beyond frame
1941         sp -= uintptr(siz)
1942         memmove(unsafe.Pointer(sp), unsafe.Pointer(argp), uintptr(narg))
1943         if thechar == '5' {
1944                 // caller's LR
1945                 sp -= ptrSize
1946                 *(*unsafe.Pointer)(unsafe.Pointer(sp)) = nil
1947         }
1948
1949         memclr(unsafe.Pointer(&newg.sched), unsafe.Sizeof(newg.sched))
1950         newg.sched.sp = sp
1951         newg.sched.pc = funcPC(goexit) + _PCQuantum // +PCQuantum so that previous instruction is in same function
1952         newg.sched.g = newg
1953         gostartcallfn(&newg.sched, fn)
1954         newg.gopc = callerpc
1955         casgstatus(newg, _Gdead, _Grunnable)
1956
1957         if _p_.goidcache == _p_.goidcacheend {
1958                 // Sched.goidgen is the last allocated id,
1959                 // this batch must be [sched.goidgen+1, sched.goidgen+GoidCacheBatch].
1960                 // At startup sched.goidgen=0, so main goroutine receives goid=1.
1961                 _p_.goidcache = xadd64(&sched.goidgen, _GoidCacheBatch)
1962                 _p_.goidcache -= _GoidCacheBatch - 1
1963                 _p_.goidcacheend = _p_.goidcache + _GoidCacheBatch
1964         }
1965         newg.goid = int64(_p_.goidcache)
1966         _p_.goidcache++
1967         if raceenabled {
1968                 newg.racectx = racegostart(callerpc)
1969         }
1970         runqput(_p_, newg)
1971
1972         if atomicload(&sched.npidle) != 0 && atomicload(&sched.nmspinning) == 0 && unsafe.Pointer(fn.fn) != unsafe.Pointer(funcPC(main)) { // TODO: fast atomic
1973                 wakep()
1974         }
1975         _g_.m.locks--
1976         if _g_.m.locks == 0 && _g_.preempt { // restore the preemption request in case we've cleared it in newstack
1977                 _g_.stackguard0 = stackPreempt
1978         }
1979         return newg
1980 }
1981
1982 // Put on gfree list.
1983 // If local list is too long, transfer a batch to the global list.
1984 func gfput(_p_ *p, gp *g) {
1985         if readgstatus(gp) != _Gdead {
1986                 gothrow("gfput: bad status (not Gdead)")
1987         }
1988
1989         stksize := gp.stack.hi - gp.stack.lo
1990
1991         if stksize != _FixedStack {
1992                 // non-standard stack size - free it.
1993                 stackfree(gp.stack)
1994                 gp.stack.lo = 0
1995                 gp.stack.hi = 0
1996                 gp.stackguard0 = 0
1997         }
1998
1999         gp.schedlink = _p_.gfree
2000         _p_.gfree = gp
2001         _p_.gfreecnt++
2002         if _p_.gfreecnt >= 64 {
2003                 lock(&sched.gflock)
2004                 for _p_.gfreecnt >= 32 {
2005                         _p_.gfreecnt--
2006                         gp = _p_.gfree
2007                         _p_.gfree = gp.schedlink
2008                         gp.schedlink = sched.gfree
2009                         sched.gfree = gp
2010                         sched.ngfree++
2011                 }
2012                 unlock(&sched.gflock)
2013         }
2014 }
2015
2016 // Get from gfree list.
2017 // If local list is empty, grab a batch from global list.
2018 func gfget(_p_ *p) *g {
2019 retry:
2020         gp := _p_.gfree
2021         if gp == nil && sched.gfree != nil {
2022                 lock(&sched.gflock)
2023                 for _p_.gfreecnt < 32 && sched.gfree != nil {
2024                         _p_.gfreecnt++
2025                         gp = sched.gfree
2026                         sched.gfree = gp.schedlink
2027                         sched.ngfree--
2028                         gp.schedlink = _p_.gfree
2029                         _p_.gfree = gp
2030                 }
2031                 unlock(&sched.gflock)
2032                 goto retry
2033         }
2034         if gp != nil {
2035                 _p_.gfree = gp.schedlink
2036                 _p_.gfreecnt--
2037                 if gp.stack.lo == 0 {
2038                         // Stack was deallocated in gfput.  Allocate a new one.
2039                         systemstack(func() {
2040                                 gp.stack = stackalloc(_FixedStack)
2041                         })
2042                         gp.stackguard0 = gp.stack.lo + _StackGuard
2043                 } else {
2044                         if raceenabled {
2045                                 racemalloc(unsafe.Pointer(gp.stack.lo), gp.stack.hi-gp.stack.lo)
2046                         }
2047                 }
2048         }
2049         return gp
2050 }
2051
2052 // Purge all cached G's from gfree list to the global list.
2053 func gfpurge(_p_ *p) {
2054         lock(&sched.gflock)
2055         for _p_.gfreecnt != 0 {
2056                 _p_.gfreecnt--
2057                 gp := _p_.gfree
2058                 _p_.gfree = gp.schedlink
2059                 gp.schedlink = sched.gfree
2060                 sched.gfree = gp
2061                 sched.ngfree++
2062         }
2063         unlock(&sched.gflock)
2064 }
2065
2066 // Breakpoint executes a breakpoint trap.
2067 func Breakpoint() {
2068         breakpoint()
2069 }
2070
2071 // dolockOSThread is called by LockOSThread and lockOSThread below
2072 // after they modify m.locked. Do not allow preemption during this call,
2073 // or else the m might be different in this function than in the caller.
2074 //go:nosplit
2075 func dolockOSThread() {
2076         _g_ := getg()
2077         _g_.m.lockedg = _g_
2078         _g_.lockedm = _g_.m
2079 }
2080
2081 //go:nosplit
2082
2083 // LockOSThread wires the calling goroutine to its current operating system thread.
2084 // Until the calling goroutine exits or calls UnlockOSThread, it will always
2085 // execute in that thread, and no other goroutine can.
2086 func LockOSThread() {
2087         getg().m.locked |= _LockExternal
2088         dolockOSThread()
2089 }
2090
2091 //go:nosplit
2092 func lockOSThread() {
2093         getg().m.locked += _LockInternal
2094         dolockOSThread()
2095 }
2096
2097 // dounlockOSThread is called by UnlockOSThread and unlockOSThread below
2098 // after they update m->locked. Do not allow preemption during this call,
2099 // or else the m might be in different in this function than in the caller.
2100 //go:nosplit
2101 func dounlockOSThread() {
2102         _g_ := getg()
2103         if _g_.m.locked != 0 {
2104                 return
2105         }
2106         _g_.m.lockedg = nil
2107         _g_.lockedm = nil
2108 }
2109
2110 //go:nosplit
2111
2112 // UnlockOSThread unwires the calling goroutine from its fixed operating system thread.
2113 // If the calling goroutine has not called LockOSThread, UnlockOSThread is a no-op.
2114 func UnlockOSThread() {
2115         getg().m.locked &^= _LockExternal
2116         dounlockOSThread()
2117 }
2118
2119 //go:nosplit
2120 func unlockOSThread() {
2121         _g_ := getg()
2122         if _g_.m.locked < _LockInternal {
2123                 systemstack(badunlockosthread)
2124         }
2125         _g_.m.locked -= _LockInternal
2126         dounlockOSThread()
2127 }
2128
2129 func badunlockosthread() {
2130         gothrow("runtime: internal error: misuse of lockOSThread/unlockOSThread")
2131 }
2132
2133 func gcount() int32 {
2134         n := int32(allglen) - sched.ngfree
2135         for i := 0; ; i++ {
2136                 _p_ := allp[i]
2137                 if _p_ == nil {
2138                         break
2139                 }
2140                 n -= _p_.gfreecnt
2141         }
2142
2143         // All these variables can be changed concurrently, so the result can be inconsistent.
2144         // But at least the current goroutine is running.
2145         if n < 1 {
2146                 n = 1
2147         }
2148         return n
2149 }
2150
2151 func mcount() int32 {
2152         return sched.mcount
2153 }
2154
2155 var prof struct {
2156         lock uint32
2157         hz   int32
2158 }
2159
2160 func _System()       { _System() }
2161 func _ExternalCode() { _ExternalCode() }
2162 func _GC()           { _GC() }
2163
2164 var etext struct{}
2165
2166 // Called if we receive a SIGPROF signal.
2167 func sigprof(pc *uint8, sp *uint8, lr *uint8, gp *g, mp *m) {
2168         var n int32
2169         var traceback bool
2170         var stk [100]uintptr
2171
2172         if prof.hz == 0 {
2173                 return
2174         }
2175
2176         // Profiling runs concurrently with GC, so it must not allocate.
2177         mp.mallocing++
2178
2179         // Define that a "user g" is a user-created goroutine, and a "system g"
2180         // is one that is m->g0 or m->gsignal. We've only made sure that we
2181         // can unwind user g's, so exclude the system g's.
2182         //
2183         // It is not quite as easy as testing gp == m->curg (the current user g)
2184         // because we might be interrupted for profiling halfway through a
2185         // goroutine switch. The switch involves updating three (or four) values:
2186         // g, PC, SP, and (on arm) LR. The PC must be the last to be updated,
2187         // because once it gets updated the new g is running.
2188         //
2189         // When switching from a user g to a system g, LR is not considered live,
2190         // so the update only affects g, SP, and PC. Since PC must be last, there
2191         // the possible partial transitions in ordinary execution are (1) g alone is updated,
2192         // (2) both g and SP are updated, and (3) SP alone is updated.
2193         // If g is updated, we'll see a system g and not look closer.
2194         // If SP alone is updated, we can detect the partial transition by checking
2195         // whether the SP is within g's stack bounds. (We could also require that SP
2196         // be changed only after g, but the stack bounds check is needed by other
2197         // cases, so there is no need to impose an additional requirement.)
2198         //
2199         // There is one exceptional transition to a system g, not in ordinary execution.
2200         // When a signal arrives, the operating system starts the signal handler running
2201         // with an updated PC and SP. The g is updated last, at the beginning of the
2202         // handler. There are two reasons this is okay. First, until g is updated the
2203         // g and SP do not match, so the stack bounds check detects the partial transition.
2204         // Second, signal handlers currently run with signals disabled, so a profiling
2205         // signal cannot arrive during the handler.
2206         //
2207         // When switching from a system g to a user g, there are three possibilities.
2208         //
2209         // First, it may be that the g switch has no PC update, because the SP
2210         // either corresponds to a user g throughout (as in asmcgocall)
2211         // or because it has been arranged to look like a user g frame
2212         // (as in cgocallback_gofunc). In this case, since the entire
2213         // transition is a g+SP update, a partial transition updating just one of
2214         // those will be detected by the stack bounds check.
2215         //
2216         // Second, when returning from a signal handler, the PC and SP updates
2217         // are performed by the operating system in an atomic update, so the g
2218         // update must be done before them. The stack bounds check detects
2219         // the partial transition here, and (again) signal handlers run with signals
2220         // disabled, so a profiling signal cannot arrive then anyway.
2221         //
2222         // Third, the common case: it may be that the switch updates g, SP, and PC
2223         // separately, as in gogo.
2224         //
2225         // Because gogo is the only instance, we check whether the PC lies
2226         // within that function, and if so, not ask for a traceback. This approach
2227         // requires knowing the size of the gogo function, which we
2228         // record in arch_*.h and check in runtime_test.go.
2229         //
2230         // There is another apparently viable approach, recorded here in case
2231         // the "PC within gogo" check turns out not to be usable.
2232         // It would be possible to delay the update of either g or SP until immediately
2233         // before the PC update instruction. Then, because of the stack bounds check,
2234         // the only problematic interrupt point is just before that PC update instruction,
2235         // and the sigprof handler can detect that instruction and simulate stepping past
2236         // it in order to reach a consistent state. On ARM, the update of g must be made
2237         // in two places (in R10 and also in a TLS slot), so the delayed update would
2238         // need to be the SP update. The sigprof handler must read the instruction at
2239         // the current PC and if it was the known instruction (for example, JMP BX or
2240         // MOV R2, PC), use that other register in place of the PC value.
2241         // The biggest drawback to this solution is that it requires that we can tell
2242         // whether it's safe to read from the memory pointed at by PC.
2243         // In a correct program, we can test PC == nil and otherwise read,
2244         // but if a profiling signal happens at the instant that a program executes
2245         // a bad jump (before the program manages to handle the resulting fault)
2246         // the profiling handler could fault trying to read nonexistent memory.
2247         //
2248         // To recap, there are no constraints on the assembly being used for the
2249         // transition. We simply require that g and SP match and that the PC is not
2250         // in gogo.
2251         traceback = true
2252         usp := uintptr(unsafe.Pointer(sp))
2253         gogo := funcPC(gogo)
2254         if gp == nil || gp != mp.curg ||
2255                 usp < gp.stack.lo || gp.stack.hi < usp ||
2256                 (gogo <= uintptr(unsafe.Pointer(pc)) && uintptr(unsafe.Pointer(pc)) < gogo+_RuntimeGogoBytes) {
2257                 traceback = false
2258         }
2259
2260         n = 0
2261         if traceback {
2262                 n = int32(gentraceback(uintptr(unsafe.Pointer(pc)), uintptr(unsafe.Pointer(sp)), uintptr(unsafe.Pointer(lr)), gp, 0, &stk[0], len(stk), nil, nil, _TraceTrap))
2263         }
2264         if !traceback || n <= 0 {
2265                 // Normal traceback is impossible or has failed.
2266                 // See if it falls into several common cases.
2267                 n = 0
2268                 if mp.ncgo > 0 && mp.curg != nil && mp.curg.syscallpc != 0 && mp.curg.syscallsp != 0 {
2269                         // Cgo, we can't unwind and symbolize arbitrary C code,
2270                         // so instead collect Go stack that leads to the cgo call.
2271                         // This is especially important on windows, since all syscalls are cgo calls.
2272                         n = int32(gentraceback(mp.curg.syscallpc, mp.curg.syscallsp, 0, mp.curg, 0, &stk[0], len(stk), nil, nil, 0))
2273                 }
2274                 if GOOS == "windows" && n == 0 && mp.libcallg != nil && mp.libcallpc != 0 && mp.libcallsp != 0 {
2275                         // Libcall, i.e. runtime syscall on windows.
2276                         // Collect Go stack that leads to the call.
2277                         n = int32(gentraceback(mp.libcallpc, mp.libcallsp, 0, mp.libcallg, 0, &stk[0], len(stk), nil, nil, 0))
2278                 }
2279                 if n == 0 {
2280                         // If all of the above has failed, account it against abstract "System" or "GC".
2281                         n = 2
2282                         // "ExternalCode" is better than "etext".
2283                         if uintptr(unsafe.Pointer(pc)) > uintptr(unsafe.Pointer(&etext)) {
2284                                 pc = (*uint8)(unsafe.Pointer(uintptr(funcPC(_ExternalCode) + _PCQuantum)))
2285                         }
2286                         stk[0] = uintptr(unsafe.Pointer(pc))
2287                         if mp.gcing != 0 || mp.helpgc != 0 {
2288                                 stk[1] = funcPC(_GC) + _PCQuantum
2289                         } else {
2290                                 stk[1] = funcPC(_System) + _PCQuantum
2291                         }
2292                 }
2293         }
2294
2295         if prof.hz != 0 {
2296                 // Simple cas-lock to coordinate with setcpuprofilerate.
2297                 for !cas(&prof.lock, 0, 1) {
2298                         osyield()
2299                 }
2300                 if prof.hz != 0 {
2301                         cpuproftick(&stk[0], n)
2302                 }
2303                 atomicstore(&prof.lock, 0)
2304         }
2305         mp.mallocing--
2306 }
2307
2308 // Arrange to call fn with a traceback hz times a second.
2309 func setcpuprofilerate_m(hz int32) {
2310         // Force sane arguments.
2311         if hz < 0 {
2312                 hz = 0
2313         }
2314
2315         // Disable preemption, otherwise we can be rescheduled to another thread
2316         // that has profiling enabled.
2317         _g_ := getg()
2318         _g_.m.locks++
2319
2320         // Stop profiler on this thread so that it is safe to lock prof.
2321         // if a profiling signal came in while we had prof locked,
2322         // it would deadlock.
2323         resetcpuprofiler(0)
2324
2325         for !cas(&prof.lock, 0, 1) {
2326                 osyield()
2327         }
2328         prof.hz = hz
2329         atomicstore(&prof.lock, 0)
2330
2331         lock(&sched.lock)
2332         sched.profilehz = hz
2333         unlock(&sched.lock)
2334
2335         if hz != 0 {
2336                 resetcpuprofiler(hz)
2337         }
2338
2339         _g_.m.locks--
2340 }
2341
2342 // Change number of processors.  The world is stopped, sched is locked.
2343 func procresize(new int32) {
2344         old := gomaxprocs
2345         if old < 0 || old > _MaxGomaxprocs || new <= 0 || new > _MaxGomaxprocs {
2346                 gothrow("procresize: invalid arg")
2347         }
2348
2349         // initialize new P's
2350         for i := int32(0); i < new; i++ {
2351                 p := allp[i]
2352                 if p == nil {
2353                         p = newP()
2354                         p.id = i
2355                         p.status = _Pgcstop
2356                         atomicstorep(unsafe.Pointer(&allp[i]), unsafe.Pointer(p))
2357                 }
2358                 if p.mcache == nil {
2359                         if old == 0 && i == 0 {
2360                                 if getg().m.mcache == nil {
2361                                         gothrow("missing mcache?")
2362                                 }
2363                                 p.mcache = getg().m.mcache // bootstrap
2364                         } else {
2365                                 p.mcache = allocmcache()
2366                         }
2367                 }
2368         }
2369
2370         // redistribute runnable G's evenly
2371         // collect all runnable goroutines in global queue preserving FIFO order
2372         // FIFO order is required to ensure fairness even during frequent GCs
2373         // see http://golang.org/issue/7126
2374         empty := false
2375         for !empty {
2376                 empty = true
2377                 for i := int32(0); i < old; i++ {
2378                         p := allp[i]
2379                         if p.runqhead == p.runqtail {
2380                                 continue
2381                         }
2382                         empty = false
2383                         // pop from tail of local queue
2384                         p.runqtail--
2385                         gp := p.runq[p.runqtail%uint32(len(p.runq))]
2386                         // push onto head of global queue
2387                         gp.schedlink = sched.runqhead
2388                         sched.runqhead = gp
2389                         if sched.runqtail == nil {
2390                                 sched.runqtail = gp
2391                         }
2392                         sched.runqsize++
2393                 }
2394         }
2395
2396         // fill local queues with at most len(p.runq)/2 goroutines
2397         // start at 1 because current M already executes some G and will acquire allp[0] below,
2398         // so if we have a spare G we want to put it into allp[1].
2399         var _p_ p
2400         for i := int32(1); i < new*int32(len(_p_.runq))/2 && sched.runqsize > 0; i++ {
2401                 gp := sched.runqhead
2402                 sched.runqhead = gp.schedlink
2403                 if sched.runqhead == nil {
2404                         sched.runqtail = nil
2405                 }
2406                 sched.runqsize--
2407                 runqput(allp[i%new], gp)
2408         }
2409
2410         // free unused P's
2411         for i := new; i < old; i++ {
2412                 p := allp[i]
2413                 freemcache(p.mcache)
2414                 p.mcache = nil
2415                 gfpurge(p)
2416                 p.status = _Pdead
2417                 // can't free P itself because it can be referenced by an M in syscall
2418         }
2419
2420         _g_ := getg()
2421         if _g_.m.p != nil {
2422                 _g_.m.p.m = nil
2423         }
2424         _g_.m.p = nil
2425         _g_.m.mcache = nil
2426         p := allp[0]
2427         p.m = nil
2428         p.status = _Pidle
2429         acquirep(p)
2430         for i := new - 1; i > 0; i-- {
2431                 p := allp[i]
2432                 p.status = _Pidle
2433                 pidleput(p)
2434         }
2435         var int32p *int32 = &gomaxprocs // make compiler check that gomaxprocs is an int32
2436         atomicstore((*uint32)(unsafe.Pointer(int32p)), uint32(new))
2437 }
2438
2439 // Associate p and the current m.
2440 func acquirep(_p_ *p) {
2441         _g_ := getg()
2442
2443         if _g_.m.p != nil || _g_.m.mcache != nil {
2444                 gothrow("acquirep: already in go")
2445         }
2446         if _p_.m != nil || _p_.status != _Pidle {
2447                 id := int32(0)
2448                 if _p_.m != nil {
2449                         id = _p_.m.id
2450                 }
2451                 print("acquirep: p->m=", _p_.m, "(", id, ") p->status=", _p_.status, "\n")
2452                 gothrow("acquirep: invalid p state")
2453         }
2454         _g_.m.mcache = _p_.mcache
2455         _g_.m.p = _p_
2456         _p_.m = _g_.m
2457         _p_.status = _Prunning
2458 }
2459
2460 // Disassociate p and the current m.
2461 func releasep() *p {
2462         _g_ := getg()
2463
2464         if _g_.m.p == nil || _g_.m.mcache == nil {
2465                 gothrow("releasep: invalid arg")
2466         }
2467         _p_ := _g_.m.p
2468         if _p_.m != _g_.m || _p_.mcache != _g_.m.mcache || _p_.status != _Prunning {
2469                 print("releasep: m=", _g_.m, " m->p=", _g_.m.p, " p->m=", _p_.m, " m->mcache=", _g_.m.mcache, " p->mcache=", _p_.mcache, " p->status=", _p_.status, "\n")
2470                 gothrow("releasep: invalid p state")
2471         }
2472         _g_.m.p = nil
2473         _g_.m.mcache = nil
2474         _p_.m = nil
2475         _p_.status = _Pidle
2476         return _p_
2477 }
2478
2479 func incidlelocked(v int32) {
2480         lock(&sched.lock)
2481         sched.nmidlelocked += v
2482         if v > 0 {
2483                 checkdead()
2484         }
2485         unlock(&sched.lock)
2486 }
2487
2488 // Check for deadlock situation.
2489 // The check is based on number of running M's, if 0 -> deadlock.
2490 func checkdead() {
2491         // If we are dying because of a signal caught on an already idle thread,
2492         // freezetheworld will cause all running threads to block.
2493         // And runtime will essentially enter into deadlock state,
2494         // except that there is a thread that will call exit soon.
2495         if panicking > 0 {
2496                 return
2497         }
2498
2499         // -1 for sysmon
2500         run := sched.mcount - sched.nmidle - sched.nmidlelocked - 1
2501         if run > 0 {
2502                 return
2503         }
2504         if run < 0 {
2505                 print("runtime: checkdead: nmidle=", sched.nmidle, " nmidlelocked=", sched.nmidlelocked, " mcount=", sched.mcount, "\n")
2506                 gothrow("checkdead: inconsistent counts")
2507         }
2508
2509         grunning := 0
2510         lock(&allglock)
2511         for i := 0; i < len(allgs); i++ {
2512                 gp := allgs[i]
2513                 if gp.issystem {
2514                         continue
2515                 }
2516                 s := readgstatus(gp)
2517                 switch s &^ _Gscan {
2518                 case _Gwaiting:
2519                         grunning++
2520                 case _Grunnable,
2521                         _Grunning,
2522                         _Gsyscall:
2523                         unlock(&allglock)
2524                         print("runtime: checkdead: find g ", gp.goid, " in status ", s, "\n")
2525                         gothrow("checkdead: runnable g")
2526                 }
2527         }
2528         unlock(&allglock)
2529         if grunning == 0 { // possible if main goroutine calls runtimeĀ·Goexit()
2530                 gothrow("no goroutines (main called runtime.Goexit) - deadlock!")
2531         }
2532
2533         // Maybe jump time forward for playground.
2534         gp := timejump()
2535         if gp != nil {
2536                 casgstatus(gp, _Gwaiting, _Grunnable)
2537                 globrunqput(gp)
2538                 _p_ := pidleget()
2539                 if _p_ == nil {
2540                         gothrow("checkdead: no p for timer")
2541                 }
2542                 mp := mget()
2543                 if mp == nil {
2544                         _newm(nil, _p_)
2545                 } else {
2546                         mp.nextp = _p_
2547                         notewakeup(&mp.park)
2548                 }
2549                 return
2550         }
2551
2552         getg().m.throwing = -1 // do not dump full stacks
2553         gothrow("all goroutines are asleep - deadlock!")
2554 }
2555
2556 func sysmon() {
2557         // If we go two minutes without a garbage collection, force one to run.
2558         forcegcperiod := int64(2 * 60 * 1e9)
2559
2560         // If a heap span goes unused for 5 minutes after a garbage collection,
2561         // we hand it back to the operating system.
2562         scavengelimit := int64(5 * 60 * 1e9)
2563
2564         if debug.scavenge > 0 {
2565                 // Scavenge-a-lot for testing.
2566                 forcegcperiod = 10 * 1e6
2567                 scavengelimit = 20 * 1e6
2568         }
2569
2570         lastscavenge := nanotime()
2571         nscavenge := 0
2572
2573         // Make wake-up period small enough for the sampling to be correct.
2574         maxsleep := forcegcperiod / 2
2575         if scavengelimit < forcegcperiod {
2576                 maxsleep = scavengelimit / 2
2577         }
2578
2579         lasttrace := int64(0)
2580         idle := 0 // how many cycles in succession we had not wokeup somebody
2581         delay := uint32(0)
2582         for {
2583                 if idle == 0 { // start with 20us sleep...
2584                         delay = 20
2585                 } else if idle > 50 { // start doubling the sleep after 1ms...
2586                         delay *= 2
2587                 }
2588                 if delay > 10*1000 { // up to 10ms
2589                         delay = 10 * 1000
2590                 }
2591                 usleep(delay)
2592                 if debug.schedtrace <= 0 && (sched.gcwaiting != 0 || atomicload(&sched.npidle) == uint32(gomaxprocs)) { // TODO: fast atomic
2593                         lock(&sched.lock)
2594                         if atomicload(&sched.gcwaiting) != 0 || atomicload(&sched.npidle) == uint32(gomaxprocs) {
2595                                 atomicstore(&sched.sysmonwait, 1)
2596                                 unlock(&sched.lock)
2597                                 notetsleep(&sched.sysmonnote, maxsleep)
2598                                 lock(&sched.lock)
2599                                 atomicstore(&sched.sysmonwait, 0)
2600                                 noteclear(&sched.sysmonnote)
2601                                 idle = 0
2602                                 delay = 20
2603                         }
2604                         unlock(&sched.lock)
2605                 }
2606                 // poll network if not polled for more than 10ms
2607                 lastpoll := int64(atomicload64(&sched.lastpoll))
2608                 now := nanotime()
2609                 unixnow := unixnanotime()
2610                 if lastpoll != 0 && lastpoll+10*1000*1000 < now {
2611                         cas64(&sched.lastpoll, uint64(lastpoll), uint64(now))
2612                         gp := netpoll(false) // non-blocking - returns list of goroutines
2613                         if gp != nil {
2614                                 // Need to decrement number of idle locked M's
2615                                 // (pretending that one more is running) before injectglist.
2616                                 // Otherwise it can lead to the following situation:
2617                                 // injectglist grabs all P's but before it starts M's to run the P's,
2618                                 // another M returns from syscall, finishes running its G,
2619                                 // observes that there is no work to do and no other running M's
2620                                 // and reports deadlock.
2621                                 incidlelocked(-1)
2622                                 injectglist(gp)
2623                                 incidlelocked(1)
2624                         }
2625                 }
2626                 // retake P's blocked in syscalls
2627                 // and preempt long running G's
2628                 if retake(now) != 0 {
2629                         idle = 0
2630                 } else {
2631                         idle++
2632                 }
2633                 // check if we need to force a GC
2634                 lastgc := int64(atomicload64(&memstats.last_gc))
2635                 if lastgc != 0 && unixnow-lastgc > forcegcperiod && atomicload(&forcegc.idle) != 0 {
2636                         lock(&forcegc.lock)
2637                         forcegc.idle = 0
2638                         forcegc.g.schedlink = nil
2639                         injectglist(forcegc.g)
2640                         unlock(&forcegc.lock)
2641                 }
2642                 // scavenge heap once in a while
2643                 if lastscavenge+scavengelimit/2 < now {
2644                         mHeap_Scavenge(int32(nscavenge), uint64(now), uint64(scavengelimit))
2645                         lastscavenge = now
2646                         nscavenge++
2647                 }
2648                 if debug.schedtrace > 0 && lasttrace+int64(debug.schedtrace*1000000) <= now {
2649                         lasttrace = now
2650                         schedtrace(debug.scheddetail > 0)
2651                 }
2652         }
2653 }
2654
2655 var pdesc [_MaxGomaxprocs]struct {
2656         schedtick   uint32
2657         schedwhen   int64
2658         syscalltick uint32
2659         syscallwhen int64
2660 }
2661
2662 func retake(now int64) uint32 {
2663         n := 0
2664         for i := int32(0); i < gomaxprocs; i++ {
2665                 _p_ := allp[i]
2666                 if _p_ == nil {
2667                         continue
2668                 }
2669                 pd := &pdesc[i]
2670                 s := _p_.status
2671                 if s == _Psyscall {
2672                         // Retake P from syscall if it's there for more than 1 sysmon tick (at least 20us).
2673                         t := int64(_p_.syscalltick)
2674                         if int64(pd.syscalltick) != t {
2675                                 pd.syscalltick = uint32(t)
2676                                 pd.syscallwhen = now
2677                                 continue
2678                         }
2679                         // On the one hand we don't want to retake Ps if there is no other work to do,
2680                         // but on the other hand we want to retake them eventually
2681                         // because they can prevent the sysmon thread from deep sleep.
2682                         if _p_.runqhead == _p_.runqtail && atomicload(&sched.nmspinning)+atomicload(&sched.npidle) > 0 && pd.syscallwhen+10*1000*1000 > now {
2683                                 continue
2684                         }
2685                         // Need to decrement number of idle locked M's
2686                         // (pretending that one more is running) before the CAS.
2687                         // Otherwise the M from which we retake can exit the syscall,
2688                         // increment nmidle and report deadlock.
2689                         incidlelocked(-1)
2690                         if cas(&_p_.status, s, _Pidle) {
2691                                 n++
2692                                 handoffp(_p_)
2693                         }
2694                         incidlelocked(1)
2695                 } else if s == _Prunning {
2696                         // Preempt G if it's running for more than 10ms.
2697                         t := int64(_p_.schedtick)
2698                         if int64(pd.schedtick) != t {
2699                                 pd.schedtick = uint32(t)
2700                                 pd.schedwhen = now
2701                                 continue
2702                         }
2703                         if pd.schedwhen+10*1000*1000 > now {
2704                                 continue
2705                         }
2706                         preemptone(_p_)
2707                 }
2708         }
2709         return uint32(n)
2710 }
2711
2712 // Tell all goroutines that they have been preempted and they should stop.
2713 // This function is purely best-effort.  It can fail to inform a goroutine if a
2714 // processor just started running it.
2715 // No locks need to be held.
2716 // Returns true if preemption request was issued to at least one goroutine.
2717 func preemptall() bool {
2718         res := false
2719         for i := int32(0); i < gomaxprocs; i++ {
2720                 _p_ := allp[i]
2721                 if _p_ == nil || _p_.status != _Prunning {
2722                         continue
2723                 }
2724                 if preemptone(_p_) {
2725                         res = true
2726                 }
2727         }
2728         return res
2729 }
2730
2731 // Tell the goroutine running on processor P to stop.
2732 // This function is purely best-effort.  It can incorrectly fail to inform the
2733 // goroutine.  It can send inform the wrong goroutine.  Even if it informs the
2734 // correct goroutine, that goroutine might ignore the request if it is
2735 // simultaneously executing newstack.
2736 // No lock needs to be held.
2737 // Returns true if preemption request was issued.
2738 // The actual preemption will happen at some point in the future
2739 // and will be indicated by the gp->status no longer being
2740 // Grunning
2741 func preemptone(_p_ *p) bool {
2742         mp := _p_.m
2743         if mp == nil || mp == getg().m {
2744                 return false
2745         }
2746         gp := mp.curg
2747         if gp == nil || gp == mp.g0 {
2748                 return false
2749         }
2750
2751         gp.preempt = true
2752
2753         // Every call in a go routine checks for stack overflow by
2754         // comparing the current stack pointer to gp->stackguard0.
2755         // Setting gp->stackguard0 to StackPreempt folds
2756         // preemption into the normal stack overflow check.
2757         gp.stackguard0 = stackPreempt
2758         return true
2759 }
2760
2761 var starttime int64
2762
2763 func schedtrace(detailed bool) {
2764         now := nanotime()
2765         if starttime == 0 {
2766                 starttime = now
2767         }
2768
2769         lock(&sched.lock)
2770         print("SCHED ", (now-starttime)/1e6, "ms: gomaxprocs=", gomaxprocs, " idleprocs=", sched.npidle, " threads=", sched.mcount, " spinningthreads=", sched.nmspinning, " idlethreads=", sched.nmidle, " runqueue=", sched.runqsize)
2771         if detailed {
2772                 print(" gcwaiting=", sched.gcwaiting, " nmidlelocked=", sched.nmidlelocked, " stopwait=", sched.stopwait, " sysmonwait=", sched.sysmonwait, "\n")
2773         }
2774         // We must be careful while reading data from P's, M's and G's.
2775         // Even if we hold schedlock, most data can be changed concurrently.
2776         // E.g. (p->m ? p->m->id : -1) can crash if p->m changes from non-nil to nil.
2777         for i := int32(0); i < gomaxprocs; i++ {
2778                 _p_ := allp[i]
2779                 if _p_ == nil {
2780                         continue
2781                 }
2782                 mp := _p_.m
2783                 h := atomicload(&_p_.runqhead)
2784                 t := atomicload(&_p_.runqtail)
2785                 if detailed {
2786                         id := int32(-1)
2787                         if mp != nil {
2788                                 id = mp.id
2789                         }
2790                         print("  P", i, ": status=", _p_.status, " schedtick=", _p_.schedtick, " syscalltick=", _p_.syscalltick, " m=", id, " runqsize=", t-h, " gfreecnt=", _p_.gfreecnt, "\n")
2791                 } else {
2792                         // In non-detailed mode format lengths of per-P run queues as:
2793                         // [len1 len2 len3 len4]
2794                         print(" ")
2795                         if i == 0 {
2796                                 print("[")
2797                         }
2798                         print(t - h)
2799                         if i == gomaxprocs-1 {
2800                                 print("]\n")
2801                         }
2802                 }
2803         }
2804
2805         if !detailed {
2806                 unlock(&sched.lock)
2807                 return
2808         }
2809
2810         for mp := allm; mp != nil; mp = mp.alllink {
2811                 _p_ := mp.p
2812                 gp := mp.curg
2813                 lockedg := mp.lockedg
2814                 id1 := int32(-1)
2815                 if _p_ != nil {
2816                         id1 = _p_.id
2817                 }
2818                 id2 := int64(-1)
2819                 if gp != nil {
2820                         id2 = gp.goid
2821                 }
2822                 id3 := int64(-1)
2823                 if lockedg != nil {
2824                         id3 = lockedg.goid
2825                 }
2826                 print("  M", mp.id, ": p=", id1, " curg=", id2, " mallocing=", mp.mallocing, " throwing=", mp.throwing, " gcing=", mp.gcing, ""+" locks=", mp.locks, " dying=", mp.dying, " helpgc=", mp.helpgc, " spinning=", mp.spinning, " blocked=", getg().m.blocked, " lockedg=", id3, "\n")
2827         }
2828
2829         lock(&allglock)
2830         for gi := 0; gi < len(allgs); gi++ {
2831                 gp := allgs[gi]
2832                 mp := gp.m
2833                 lockedm := gp.lockedm
2834                 id1 := int32(-1)
2835                 if mp != nil {
2836                         id1 = mp.id
2837                 }
2838                 id2 := int32(-1)
2839                 if lockedm != nil {
2840                         id2 = lockedm.id
2841                 }
2842                 print("  G", gp.goid, ": status=", readgstatus(gp), "(", gp.waitreason, ") m=", id1, " lockedm=", id2, "\n")
2843         }
2844         unlock(&allglock)
2845         unlock(&sched.lock)
2846 }
2847
2848 // Put mp on midle list.
2849 // Sched must be locked.
2850 func mput(mp *m) {
2851         mp.schedlink = sched.midle
2852         sched.midle = mp
2853         sched.nmidle++
2854         checkdead()
2855 }
2856
2857 // Try to get an m from midle list.
2858 // Sched must be locked.
2859 func mget() *m {
2860         mp := sched.midle
2861         if mp != nil {
2862                 sched.midle = mp.schedlink
2863                 sched.nmidle--
2864         }
2865         return mp
2866 }
2867
2868 // Put gp on the global runnable queue.
2869 // Sched must be locked.
2870 func globrunqput(gp *g) {
2871         gp.schedlink = nil
2872         if sched.runqtail != nil {
2873                 sched.runqtail.schedlink = gp
2874         } else {
2875                 sched.runqhead = gp
2876         }
2877         sched.runqtail = gp
2878         sched.runqsize++
2879 }
2880
2881 // Put a batch of runnable goroutines on the global runnable queue.
2882 // Sched must be locked.
2883 func globrunqputbatch(ghead *g, gtail *g, n int32) {
2884         gtail.schedlink = nil
2885         if sched.runqtail != nil {
2886                 sched.runqtail.schedlink = ghead
2887         } else {
2888                 sched.runqhead = ghead
2889         }
2890         sched.runqtail = gtail
2891         sched.runqsize += n
2892 }
2893
2894 // Try get a batch of G's from the global runnable queue.
2895 // Sched must be locked.
2896 func globrunqget(_p_ *p, max int32) *g {
2897         if sched.runqsize == 0 {
2898                 return nil
2899         }
2900
2901         n := sched.runqsize/gomaxprocs + 1
2902         if n > sched.runqsize {
2903                 n = sched.runqsize
2904         }
2905         if max > 0 && n > max {
2906                 n = max
2907         }
2908         if n > int32(len(_p_.runq))/2 {
2909                 n = int32(len(_p_.runq)) / 2
2910         }
2911
2912         sched.runqsize -= n
2913         if sched.runqsize == 0 {
2914                 sched.runqtail = nil
2915         }
2916
2917         gp := sched.runqhead
2918         sched.runqhead = gp.schedlink
2919         n--
2920         for ; n > 0; n-- {
2921                 gp1 := sched.runqhead
2922                 sched.runqhead = gp1.schedlink
2923                 runqput(_p_, gp1)
2924         }
2925         return gp
2926 }
2927
2928 // Put p to on _Pidle list.
2929 // Sched must be locked.
2930 func pidleput(_p_ *p) {
2931         _p_.link = sched.pidle
2932         sched.pidle = _p_
2933         xadd(&sched.npidle, 1) // TODO: fast atomic
2934 }
2935
2936 // Try get a p from _Pidle list.
2937 // Sched must be locked.
2938 func pidleget() *p {
2939         _p_ := sched.pidle
2940         if _p_ != nil {
2941                 sched.pidle = _p_.link
2942                 xadd(&sched.npidle, -1) // TODO: fast atomic
2943         }
2944         return _p_
2945 }
2946
2947 // Try to put g on local runnable queue.
2948 // If it's full, put onto global queue.
2949 // Executed only by the owner P.
2950 func runqput(_p_ *p, gp *g) {
2951 retry:
2952         h := atomicload(&_p_.runqhead) // load-acquire, synchronize with consumers
2953         t := _p_.runqtail
2954         if t-h < uint32(len(_p_.runq)) {
2955                 _p_.runq[t%uint32(len(_p_.runq))] = gp
2956                 atomicstore(&_p_.runqtail, t+1) // store-release, makes the item available for consumption
2957                 return
2958         }
2959         if runqputslow(_p_, gp, h, t) {
2960                 return
2961         }
2962         // the queue is not full, now the put above must suceed
2963         goto retry
2964 }
2965
2966 // Put g and a batch of work from local runnable queue on global queue.
2967 // Executed only by the owner P.
2968 func runqputslow(_p_ *p, gp *g, h, t uint32) bool {
2969         var batch [len(_p_.runq)/2 + 1]*g
2970
2971         // First, grab a batch from local queue.
2972         n := t - h
2973         n = n / 2
2974         if n != uint32(len(_p_.runq)/2) {
2975                 gothrow("runqputslow: queue is not full")
2976         }
2977         for i := uint32(0); i < n; i++ {
2978                 batch[i] = _p_.runq[(h+i)%uint32(len(_p_.runq))]
2979         }
2980         if !cas(&_p_.runqhead, h, h+n) { // cas-release, commits consume
2981                 return false
2982         }
2983         batch[n] = gp
2984
2985         // Link the goroutines.
2986         for i := uint32(0); i < n; i++ {
2987                 batch[i].schedlink = batch[i+1]
2988         }
2989
2990         // Now put the batch on global queue.
2991         lock(&sched.lock)
2992         globrunqputbatch(batch[0], batch[n], int32(n+1))
2993         unlock(&sched.lock)
2994         return true
2995 }
2996
2997 // Get g from local runnable queue.
2998 // Executed only by the owner P.
2999 func runqget(_p_ *p) *g {
3000         for {
3001                 h := atomicload(&_p_.runqhead) // load-acquire, synchronize with other consumers
3002                 t := _p_.runqtail
3003                 if t == h {
3004                         return nil
3005                 }
3006                 gp := _p_.runq[h%uint32(len(_p_.runq))]
3007                 if cas(&_p_.runqhead, h, h+1) { // cas-release, commits consume
3008                         return gp
3009                 }
3010         }
3011 }
3012
3013 // Grabs a batch of goroutines from local runnable queue.
3014 // batch array must be of size len(p->runq)/2. Returns number of grabbed goroutines.
3015 // Can be executed by any P.
3016 func runqgrab(_p_ *p, batch []*g) uint32 {
3017         for {
3018                 h := atomicload(&_p_.runqhead) // load-acquire, synchronize with other consumers
3019                 t := atomicload(&_p_.runqtail) // load-acquire, synchronize with the producer
3020                 n := t - h
3021                 n = n - n/2
3022                 if n == 0 {
3023                         return 0
3024                 }
3025                 if n > uint32(len(_p_.runq)/2) { // read inconsistent h and t
3026                         continue
3027                 }
3028                 for i := uint32(0); i < n; i++ {
3029                         batch[i] = _p_.runq[(h+i)%uint32(len(_p_.runq))]
3030                 }
3031                 if cas(&_p_.runqhead, h, h+n) { // cas-release, commits consume
3032                         return n
3033                 }
3034         }
3035 }
3036
3037 // Steal half of elements from local runnable queue of p2
3038 // and put onto local runnable queue of p.
3039 // Returns one of the stolen elements (or nil if failed).
3040 func runqsteal(_p_, p2 *p) *g {
3041         var batch [len(_p_.runq) / 2]*g
3042
3043         n := runqgrab(p2, batch[:])
3044         if n == 0 {
3045                 return nil
3046         }
3047         n--
3048         gp := batch[n]
3049         if n == 0 {
3050                 return gp
3051         }
3052         h := atomicload(&_p_.runqhead) // load-acquire, synchronize with consumers
3053         t := _p_.runqtail
3054         if t-h+n >= uint32(len(_p_.runq)) {
3055                 gothrow("runqsteal: runq overflow")
3056         }
3057         for i := uint32(0); i < n; i++ {
3058                 _p_.runq[(t+i)%uint32(len(_p_.runq))] = batch[i]
3059         }
3060         atomicstore(&_p_.runqtail, t+n) // store-release, makes the item available for consumption
3061         return gp
3062 }
3063
3064 func testSchedLocalQueue() {
3065         _p_ := new(p)
3066         gs := make([]g, len(_p_.runq))
3067         for i := 0; i < len(_p_.runq); i++ {
3068                 if runqget(_p_) != nil {
3069                         gothrow("runq is not empty initially")
3070                 }
3071                 for j := 0; j < i; j++ {
3072                         runqput(_p_, &gs[i])
3073                 }
3074                 for j := 0; j < i; j++ {
3075                         if runqget(_p_) != &gs[i] {
3076                                 print("bad element at iter ", i, "/", j, "\n")
3077                                 gothrow("bad element")
3078                         }
3079                 }
3080                 if runqget(_p_) != nil {
3081                         gothrow("runq is not empty afterwards")
3082                 }
3083         }
3084 }
3085
3086 func testSchedLocalQueueSteal() {
3087         p1 := new(p)
3088         p2 := new(p)
3089         gs := make([]g, len(p1.runq))
3090         for i := 0; i < len(p1.runq); i++ {
3091                 for j := 0; j < i; j++ {
3092                         gs[j].sig = 0
3093                         runqput(p1, &gs[j])
3094                 }
3095                 gp := runqsteal(p2, p1)
3096                 s := 0
3097                 if gp != nil {
3098                         s++
3099                         gp.sig++
3100                 }
3101                 for {
3102                         gp = runqget(p2)
3103                         if gp == nil {
3104                                 break
3105                         }
3106                         s++
3107                         gp.sig++
3108                 }
3109                 for {
3110                         gp = runqget(p1)
3111                         if gp == nil {
3112                                 break
3113                         }
3114                         gp.sig++
3115                 }
3116                 for j := 0; j < i; j++ {
3117                         if gs[j].sig != 1 {
3118                                 print("bad element ", j, "(", gs[j].sig, ") at iter ", i, "\n")
3119                                 gothrow("bad element")
3120                         }
3121                 }
3122                 if s != i/2 && s != i/2+1 {
3123                         print("bad steal ", s, ", want ", i/2, " or ", i/2+1, ", iter ", i, "\n")
3124                         gothrow("bad steal")
3125                 }
3126         }
3127 }
3128
3129 func setMaxThreads(in int) (out int) {
3130         lock(&sched.lock)
3131         out = int(sched.maxmcount)
3132         sched.maxmcount = int32(in)
3133         checkmcount()
3134         unlock(&sched.lock)
3135         return
3136 }
3137
3138 var goexperiment string = "GOEXPERIMENT" // TODO: defined in zaexperiment.h
3139
3140 func haveexperiment(name string) bool {
3141         x := goexperiment
3142         for x != "" {
3143                 xname := ""
3144                 i := index(x, ",")
3145                 if i < 0 {
3146                         xname, x = x, ""
3147                 } else {
3148                         xname, x = x[:i], x[i+1:]
3149                 }
3150                 if xname == name {
3151                         return true
3152                 }
3153         }
3154         return false
3155 }
3156
3157 //go:nosplit
3158 func sync_procPin() int {
3159         _g_ := getg()
3160         mp := _g_.m
3161
3162         mp.locks++
3163         return int(mp.p.id)
3164 }
3165
3166 //go:nosplit
3167 func sync_procUnpin() {
3168         _g_ := getg()
3169         _g_.m.locks--
3170 }