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.
13 #ifdef HAVE_DL_ITERATE_PHDR
23 #ifdef USING_SPLIT_STACK
25 /* FIXME: These are not declared anywhere. */
27 extern void __splitstack_getcontext(void *context
[10]);
29 extern void __splitstack_setcontext(void *context
[10]);
31 extern void *__splitstack_makecontext(size_t, void *context
[10], size_t *);
33 extern void * __splitstack_resetcontext(void *context
[10], size_t *);
35 extern void *__splitstack_find(void *, void *, size_t *, void **, void **,
38 extern void __splitstack_block_signals (int *, int *);
40 extern void __splitstack_block_signals_context (void *context
[10], int *,
45 #ifndef PTHREAD_STACK_MIN
46 # define PTHREAD_STACK_MIN 8192
49 #if defined(USING_SPLIT_STACK) && defined(LINKER_SUPPORTS_SPLIT_STACK)
50 # define StackMin PTHREAD_STACK_MIN
52 # define StackMin ((sizeof(char *) < 8) ? 2 * 1024 * 1024 : 4 * 1024 * 1024)
55 uintptr runtime_stacks_sys
;
57 static void gtraceback(G
*);
65 #ifndef SETCONTEXT_CLOBBERS_TLS
73 fixcontext(ucontext_t
*c
__attribute__ ((unused
)))
79 # if defined(__x86_64__) && defined(__sun__)
81 // x86_64 Solaris 10 and 11 have a bug: setcontext switches the %fs
82 // register to that of the thread which called getcontext. The effect
83 // is that the address of all __thread variables changes. This bug
84 // also affects pthread_self() and pthread_getspecific. We work
85 // around it by clobbering the context field directly to keep %fs the
88 static __thread greg_t fs
;
96 fs
= c
.uc_mcontext
.gregs
[REG_FSBASE
];
100 fixcontext(ucontext_t
* c
)
102 c
->uc_mcontext
.gregs
[REG_FSBASE
] = fs
;
105 # elif defined(__NetBSD__)
107 // NetBSD has a bug: setcontext clobbers tlsbase, we need to save
108 // and restore it ourselves.
110 static __thread __greg_t tlsbase
;
118 tlsbase
= c
.uc_mcontext
._mc_tlsbase
;
122 fixcontext(ucontext_t
* c
)
124 c
->uc_mcontext
._mc_tlsbase
= tlsbase
;
127 # elif defined(__sparc__)
135 fixcontext(ucontext_t
*c
)
138 register unsigned long thread __asm__("%g7");
139 c->uc_mcontext.gregs[REG_G7] = thread;
141 error: variable ‘thread’ might be clobbered by \
142 ‘longjmp’ or ‘vfork’ [-Werror=clobbered]
143 which ought to be false, as %g7 is a fixed register. */
145 if (sizeof (c
->uc_mcontext
.gregs
[REG_G7
]) == 8)
146 asm ("stx %%g7, %0" : "=m"(c
->uc_mcontext
.gregs
[REG_G7
]));
148 asm ("st %%g7, %0" : "=m"(c
->uc_mcontext
.gregs
[REG_G7
]));
153 # error unknown case for SETCONTEXT_CLOBBERS_TLS
159 // ucontext_arg returns a properly aligned ucontext_t value. On some
160 // systems a ucontext_t value must be aligned to a 16-byte boundary.
161 // The g structure that has fields of type ucontext_t is defined in
162 // Go, and Go has no simple way to align a field to such a boundary.
163 // So we make the field larger in runtime2.go and pick an appropriate
164 // offset within the field here.
166 ucontext_arg(void** go_ucontext
)
168 uintptr_t p
= (uintptr_t)go_ucontext
;
169 size_t align
= __alignof__(ucontext_t
);
171 // We only ensured space for up to a 16 byte alignment
172 // in libgo/go/runtime/runtime2.go.
173 runtime_throw("required alignment of ucontext_t too large");
175 p
= (p
+ align
- 1) &~ (uintptr_t)(align
- 1);
176 return (ucontext_t
*)p
;
179 // We can not always refer to the TLS variables directly. The
180 // compiler will call tls_get_addr to get the address of the variable,
181 // and it may hold it in a register across a call to schedule. When
182 // we get back from the call we may be running in a different thread,
183 // in which case the register now points to the TLS variable for a
184 // different thread. We use non-inlinable functions to avoid this
187 G
* runtime_g(void) __attribute__ ((noinline
, no_split_stack
));
195 M
* runtime_m(void) __attribute__ ((noinline
, no_split_stack
));
212 // Start a new thread.
214 runtime_newosproc(M
*mp
)
221 if(pthread_attr_init(&attr
) != 0)
222 runtime_throw("pthread_attr_init");
223 if(pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0)
224 runtime_throw("pthread_attr_setdetachstate");
226 // Block signals during pthread_create so that the new thread
227 // starts with signals disabled. It will enable them in minit.
231 // Blocking SIGTRAP reportedly breaks gdb on Alpha GNU/Linux.
232 sigdelset(&clear
, SIGTRAP
);
236 pthread_sigmask(SIG_BLOCK
, &clear
, &old
);
237 ret
= pthread_create(&tid
, &attr
, runtime_mstart
, mp
);
238 pthread_sigmask(SIG_SETMASK
, &old
, nil
);
241 runtime_throw("pthread_create");
244 // First function run by a new goroutine. This replaces gogocall.
251 if(g
->traceback
!= nil
)
254 fn
= (void (*)(void*))(g
->entry
);
261 // Switch context to a different goroutine. This is like longjmp.
262 void runtime_gogo(G
*) __attribute__ ((noinline
));
264 runtime_gogo(G
* newg
)
266 #ifdef USING_SPLIT_STACK
267 __splitstack_setcontext(&newg
->stackcontext
[0]);
270 newg
->fromgogo
= true;
271 fixcontext(ucontext_arg(&newg
->context
[0]));
272 setcontext(ucontext_arg(&newg
->context
[0]));
273 runtime_throw("gogo setcontext returned");
276 // Save context and call fn passing g as a parameter. This is like
277 // setjmp. Because getcontext always returns 0, unlike setjmp, we use
278 // g->fromgogo as a code. It will be true if we got here via
279 // setcontext. g == nil the first time this is called in a new m.
280 void runtime_mcall(void (*)(G
*)) __attribute__ ((noinline
));
282 runtime_mcall(void (*pfn
)(G
*))
287 // Ensure that all registers are on the stack for the garbage
289 __builtin_unwind_init();
294 runtime_throw("runtime: mcall called on m->g0 stack");
298 #ifdef USING_SPLIT_STACK
299 __splitstack_getcontext(&g
->stackcontext
[0]);
303 gp
->fromgogo
= false;
304 getcontext(ucontext_arg(&gp
->context
[0]));
306 // When we return from getcontext, we may be running
307 // in a new thread. That means that g may have
308 // changed. It is a global variables so we will
309 // reload it, but the address of g may be cached in
310 // our local stack frame, and that address may be
311 // wrong. Call the function to reload the value for
316 if(gp
->traceback
!= nil
)
319 if (gp
== nil
|| !gp
->fromgogo
) {
320 #ifdef USING_SPLIT_STACK
321 __splitstack_setcontext(&mp
->g0
->stackcontext
[0]);
323 mp
->g0
->entry
= (byte
*)pfn
;
326 // It's OK to set g directly here because this case
327 // can not occur if we got here via a setcontext to
328 // the getcontext call just above.
331 fixcontext(ucontext_arg(&mp
->g0
->context
[0]));
332 setcontext(ucontext_arg(&mp
->g0
->context
[0]));
333 runtime_throw("runtime: mcall function returned");
337 // Goroutine scheduler
338 // The scheduler's job is to distribute ready-to-run goroutines over worker threads.
340 // The main concepts are:
342 // M - worker thread, or machine.
343 // P - processor, a resource that is required to execute Go code.
344 // M must have an associated P to execute Go code, however it can be
345 // blocked or in a syscall w/o an associated P.
347 // Design doc at http://golang.org/s/go11sched.
349 typedef struct Sched Sched
;
354 M
* midle
; // idle m's waiting for work
355 int32 nmidle
; // number of idle m's waiting for work
356 int32 nmidlelocked
; // number of locked m's waiting for work
357 int32 mcount
; // number of m's that have been created
358 int32 maxmcount
; // maximum number of m's allowed (or die)
360 P
* pidle
; // idle P's
364 // Global runnable queue.
369 // Global cache of dead G's.
373 uint32 gcwaiting
; // gc is waiting to run
380 int32 profilehz
; // cpu profiling rate
385 // Number of goroutine ids to grab from runtime_sched.goidgen to local per-P cache at once.
386 // 16 seems to provide enough amortization, but other than that it's mostly arbitrary number.
391 int32 runtime_gomaxprocs
;
392 uint32 runtime_needextram
= 1;
394 G runtime_g0
; // idle goroutine for m0
401 bool runtime_precisestack
;
402 static int32 newprocs
;
404 static Lock allglock
; // the following vars are protected by this lock or by stoptheworld
406 uintptr runtime_allglen
;
407 static uintptr allgcap
;
409 bool runtime_isarchive
;
411 void* runtime_mstart(void*);
412 static void runqput(P
*, G
*);
413 static G
* runqget(P
*);
414 static bool runqputslow(P
*, G
*, uint32
, uint32
);
415 static G
* runqsteal(P
*, P
*);
416 static void mput(M
*);
417 static M
* mget(void);
418 static void mcommoninit(M
*);
419 static void schedule(void);
420 static void procresize(int32
);
421 static void acquirep(P
*);
422 static P
* releasep(void);
423 static void newm(void(*)(void), P
*);
424 static void stopm(void);
425 static void startm(P
*, bool);
426 static void handoffp(P
*);
427 static void wakep(void);
428 static void stoplockedm(void);
429 static void startlockedm(G
*);
430 static void sysmon(void);
431 static uint32
retake(int64
);
432 static void incidlelocked(int32
);
433 static void checkdead(void);
434 static void exitsyscall0(G
*);
435 static void park0(G
*);
436 static void goexit0(G
*);
437 static void gfput(P
*, G
*);
439 static void gfpurge(P
*);
440 static void globrunqput(G
*);
441 static void globrunqputbatch(G
*, G
*, int32
);
442 static G
* globrunqget(P
*, int32
);
443 static P
* pidleget(void);
444 static void pidleput(P
*);
445 static void injectglist(G
*);
446 static bool preemptall(void);
447 static bool exitsyscallfast(void);
448 static void allgadd(G
*);
450 bool runtime_isstarted
;
452 // The bootstrap sequence is:
456 // make & queue new G
457 // call runtime_mstart
459 // The new G calls runtime_main.
461 runtime_schedinit(void)
477 runtime_sched
.maxmcount
= 10000;
478 runtime_precisestack
= 0;
480 // runtime_symtabinit();
481 runtime_mallocinit();
484 // Initialize the itable value for newErrorCString,
485 // so that the next time it gets called, possibly
486 // in a fault during a garbage collection, it will not
487 // need to allocated memory.
488 runtime_newErrorCString(0, &i
);
490 // Initialize the cached gotraceback value, since
491 // gotraceback calls getenv, which mallocs on Plan 9.
492 runtime_gotraceback(nil
);
496 runtime_parsedebugvars();
498 runtime_sched
.lastpoll
= runtime_nanotime();
500 s
= runtime_getenv("GOMAXPROCS");
502 if(p
!= nil
&& (n
= runtime_atoi(p
, s
.len
)) > 0) {
503 if(n
> _MaxGomaxprocs
)
507 runtime_allp
= runtime_malloc((_MaxGomaxprocs
+1)*sizeof(runtime_allp
[0]));
510 // Can not enable GC until all roots are registered.
511 // mstats.enablegc = 1;
514 extern void main_init(void) __asm__ (GOSYM_PREFIX
"__go_init_main");
515 extern void main_main(void) __asm__ (GOSYM_PREFIX
"main.main");
517 // Used to determine the field alignment.
525 // main_init_done is a signal used by cgocallbackg that initialization
526 // has been completed. It is made before _cgo_notify_runtime_init_done,
527 // so all cgo calls can rely on it existing. When main_init is
528 // complete, it is closed, meaning cgocallbackg can reliably receive
530 Hchan
*runtime_main_init_done
;
532 // The chan bool type, for runtime_main_init_done.
534 extern const struct __go_type_descriptor bool_type_descriptor
535 __asm__ (GOSYM_PREFIX
"__go_tdn_bool");
537 static struct __go_channel_type chan_bool_type_descriptor
=
546 offsetof (struct field_align
, p
) - 1,
550 0, /* This value doesn't matter. */
556 NULL
, /* This value doesn't matter */
558 NULL
, /* This value doesn't matter */
561 /* __pointer_to_this */
565 &bool_type_descriptor
,
570 extern Hchan
*makechan (ChanType
*, int64
)
571 __asm__ (GOSYM_PREFIX
"runtime.makechan");
572 extern void closechan(Hchan
*) __asm__ (GOSYM_PREFIX
"runtime.closechan");
575 initDone(void *arg
__attribute__ ((unused
))) {
576 runtime_unlockOSThread();
579 // The main goroutine.
580 // Note: C frames in general are not copyable during stack growth, for two reasons:
581 // 1) We don't know where in a frame to find pointers to other stack locations.
582 // 2) There's no guarantee that globals or heap values do not point into the frame.
584 // The C frame for runtime.main is copyable, because:
585 // 1) There are no pointers to other stack locations in the frame
586 // (d.fn points at a global, d.link is nil, d.argp is -1).
587 // 2) The only pointer into this frame is from the defer chain,
588 // which is explicitly handled during stack copying.
590 runtime_main(void* dummy
__attribute__((unused
)))
597 // Lock the main goroutine onto this, the main OS thread,
598 // during initialization. Most programs won't care, but a few
599 // do require certain calls to be made by the main thread.
600 // Those can arrange for main.main to run in the main thread
601 // by calling runtime.LockOSThread during initialization
602 // to preserve the lock.
603 runtime_lockOSThread();
605 // Defer unlock so that runtime.Goexit during init does the unlock too.
606 d
.pfn
= (uintptr
)(void*)initDone
;
609 d
._panic
= g
->_panic
;
611 d
.makefunccanrecover
= 0;
616 if(g
->m
!= &runtime_m0
)
617 runtime_throw("runtime_main not on m0");
618 __go_go(runtime_MHeap_Scavenger
, nil
);
620 runtime_main_init_done
= makechan(&chan_bool_type_descriptor
, 0);
622 _cgo_notify_runtime_init_done();
626 closechan(runtime_main_init_done
);
628 if(g
->_defer
!= &d
|| (void*)d
.pfn
!= initDone
)
629 runtime_throw("runtime: bad defer entry after init");
631 runtime_unlockOSThread();
633 // For gccgo we have to wait until after main is initialized
634 // to enable GC, because initializing main registers the GC
638 if(runtime_isarchive
) {
639 // This is not a complete program, but is instead a
640 // library built using -buildmode=c-archive or
641 // c-shared. Now that we are initialized, there is
642 // nothing further to do.
648 // Make racy client program work: if panicking on
649 // another goroutine at the same time as main returns,
650 // let the other goroutine finish printing the panic trace.
651 // Once it does, it will exit. See issue 3934.
652 if(runtime_panicking
)
653 runtime_park(nil
, nil
, "panicwait");
661 runtime_goroutineheader(G
*gp
)
666 switch(gp
->atomicstatus
) {
668 status
= runtime_gostringnocopy((const byte
*)"idle");
671 status
= runtime_gostringnocopy((const byte
*)"runnable");
674 status
= runtime_gostringnocopy((const byte
*)"running");
677 status
= runtime_gostringnocopy((const byte
*)"syscall");
680 if(gp
->waitreason
.len
> 0)
681 status
= gp
->waitreason
;
683 status
= runtime_gostringnocopy((const byte
*)"waiting");
686 status
= runtime_gostringnocopy((const byte
*)"???");
690 // approx time the G is blocked, in minutes
692 if((gp
->atomicstatus
== _Gwaiting
|| gp
->atomicstatus
== _Gsyscall
) && gp
->waitsince
!= 0)
693 waitfor
= (runtime_nanotime() - gp
->waitsince
) / (60LL*1000*1000*1000);
696 runtime_printf("goroutine %D [%S]:\n", gp
->goid
, status
);
698 runtime_printf("goroutine %D [%S, %D minutes]:\n", gp
->goid
, status
, waitfor
);
702 runtime_printcreatedby(G
*g
)
704 if(g
!= nil
&& g
->gopc
!= 0 && g
->goid
!= 1) {
709 if(__go_file_line(g
->gopc
- 1, -1, &fn
, &file
, &line
)) {
710 runtime_printf("created by %S\n", fn
);
711 runtime_printf("\t%S:%D\n", file
, (int64
) line
);
717 runtime_tracebackothers(G
* volatile me
)
725 traceback
= runtime_gotraceback(nil
);
727 // Show the current goroutine first, if we haven't already.
728 if((gp
= g
->m
->curg
) != nil
&& gp
!= me
) {
729 runtime_printf("\n");
730 runtime_goroutineheader(gp
);
733 #ifdef USING_SPLIT_STACK
734 __splitstack_getcontext(&me
->stackcontext
[0]);
736 getcontext(ucontext_arg(&me
->context
[0]));
738 if(gp
->traceback
!= nil
) {
742 runtime_printtrace(tb
.locbuf
, tb
.c
, false);
743 runtime_printcreatedby(gp
);
746 runtime_lock(&allglock
);
747 for(i
= 0; i
< runtime_allglen
; i
++) {
748 gp
= runtime_allg
[i
];
749 if(gp
== me
|| gp
== g
->m
->curg
|| gp
->atomicstatus
== _Gdead
)
751 if(gp
->issystem
&& traceback
< 2)
753 runtime_printf("\n");
754 runtime_goroutineheader(gp
);
756 // Our only mechanism for doing a stack trace is
757 // _Unwind_Backtrace. And that only works for the
758 // current thread, not for other random goroutines.
759 // So we need to switch context to the goroutine, get
760 // the backtrace, and then switch back.
762 // This means that if g is running or in a syscall, we
763 // can't reliably print a stack trace. FIXME.
765 if(gp
->atomicstatus
== _Grunning
) {
766 runtime_printf("\tgoroutine running on other thread; stack unavailable\n");
767 runtime_printcreatedby(gp
);
768 } else if(gp
->atomicstatus
== _Gsyscall
) {
769 runtime_printf("\tgoroutine in C code; stack unavailable\n");
770 runtime_printcreatedby(gp
);
774 #ifdef USING_SPLIT_STACK
775 __splitstack_getcontext(&me
->stackcontext
[0]);
777 getcontext(ucontext_arg(&me
->context
[0]));
779 if(gp
->traceback
!= nil
) {
783 runtime_printtrace(tb
.locbuf
, tb
.c
, false);
784 runtime_printcreatedby(gp
);
787 runtime_unlock(&allglock
);
793 // sched lock is held
794 if(runtime_sched
.mcount
> runtime_sched
.maxmcount
) {
795 runtime_printf("runtime: program exceeds %d-thread limit\n", runtime_sched
.maxmcount
);
796 runtime_throw("thread exhaustion");
800 // Do a stack trace of gp, and then restore the context to
806 Traceback
* traceback
;
808 traceback
= gp
->traceback
;
811 runtime_throw("gtraceback: m is not nil");
812 gp
->m
= traceback
->gp
->m
;
813 traceback
->c
= runtime_callers(1, traceback
->locbuf
,
814 sizeof traceback
->locbuf
/ sizeof traceback
->locbuf
[0], false);
816 runtime_gogo(traceback
->gp
);
822 // If there is no mcache runtime_callers() will crash,
823 // and we are most likely in sysmon thread so the stack is senseless anyway.
825 runtime_callers(1, mp
->createstack
, nelem(mp
->createstack
), false);
827 mp
->fastrand
= 0x49f6428aUL
+ mp
->id
+ runtime_cputicks();
829 runtime_lock(&runtime_sched
);
830 mp
->id
= runtime_sched
.mcount
++;
832 runtime_mpreinit(mp
);
834 // Add to runtime_allm so garbage collector doesn't free m
835 // when it is just in a register or thread-local storage.
836 mp
->alllink
= runtime_allm
;
837 // runtime_NumCgoCall() iterates over allm w/o schedlock,
838 // so we need to publish it safely.
839 runtime_atomicstorep(&runtime_allm
, mp
);
840 runtime_unlock(&runtime_sched
);
843 // Mark gp ready to run.
848 g
->m
->locks
++; // disable preemption because it can be holding p in a local var
849 if(gp
->atomicstatus
!= _Gwaiting
) {
850 runtime_printf("goroutine %D has status %d\n", gp
->goid
, gp
->atomicstatus
);
851 runtime_throw("bad g->atomicstatus in ready");
853 gp
->atomicstatus
= _Grunnable
;
854 runqput((P
*)g
->m
->p
, gp
);
855 if(runtime_atomicload(&runtime_sched
.npidle
) != 0 && runtime_atomicload(&runtime_sched
.nmspinning
) == 0) // TODO: fast atomic
860 void goready(G
*, int) __asm__ (GOSYM_PREFIX
"runtime.goready");
863 goready(G
* gp
, int traceskip
__attribute__ ((unused
)))
869 runtime_gcprocs(void)
873 // Figure out how many CPUs to use during GC.
874 // Limited by gomaxprocs, number of actual CPUs, and MaxGcproc.
875 runtime_lock(&runtime_sched
);
876 n
= runtime_gomaxprocs
;
878 n
= runtime_ncpu
> 0 ? runtime_ncpu
: 1;
881 if(n
> runtime_sched
.nmidle
+1) // one M is currently running
882 n
= runtime_sched
.nmidle
+1;
883 runtime_unlock(&runtime_sched
);
892 runtime_lock(&runtime_sched
);
893 n
= runtime_gomaxprocs
;
898 n
-= runtime_sched
.nmidle
+1; // one M is currently running
899 runtime_unlock(&runtime_sched
);
904 runtime_helpgc(int32 nproc
)
909 runtime_lock(&runtime_sched
);
911 for(n
= 1; n
< nproc
; n
++) { // one M is currently running
912 if(runtime_allp
[pos
]->mcache
== g
->m
->mcache
)
916 runtime_throw("runtime_gcprocs inconsistency");
918 mp
->mcache
= runtime_allp
[pos
]->mcache
;
920 runtime_notewakeup(&mp
->park
);
922 runtime_unlock(&runtime_sched
);
925 // Similar to stoptheworld but best-effort and can be called several times.
926 // There is no reverse operation, used during crashing.
927 // This function must not lock any mutexes.
929 runtime_freezetheworld(void)
933 if(runtime_gomaxprocs
== 1)
935 // stopwait and preemption requests can be lost
936 // due to races with concurrently executing threads,
937 // so try several times
938 for(i
= 0; i
< 5; i
++) {
939 // this should tell the scheduler to not start any new goroutines
940 runtime_sched
.stopwait
= 0x7fffffff;
941 runtime_atomicstore((uint32
*)&runtime_sched
.gcwaiting
, 1);
942 // this should stop running goroutines
944 break; // no running goroutines
945 runtime_usleep(1000);
948 runtime_usleep(1000);
950 runtime_usleep(1000);
954 runtime_stoptheworld(void)
961 runtime_lock(&runtime_sched
);
962 runtime_sched
.stopwait
= runtime_gomaxprocs
;
963 runtime_atomicstore((uint32
*)&runtime_sched
.gcwaiting
, 1);
966 ((P
*)g
->m
->p
)->status
= _Pgcstop
;
967 runtime_sched
.stopwait
--;
968 // try to retake all P's in _Psyscall status
969 for(i
= 0; i
< runtime_gomaxprocs
; i
++) {
972 if(s
== _Psyscall
&& runtime_cas(&p
->status
, s
, _Pgcstop
))
973 runtime_sched
.stopwait
--;
976 while((p
= pidleget()) != nil
) {
977 p
->status
= _Pgcstop
;
978 runtime_sched
.stopwait
--;
980 wait
= runtime_sched
.stopwait
> 0;
981 runtime_unlock(&runtime_sched
);
983 // wait for remaining P's to stop voluntarily
985 runtime_notesleep(&runtime_sched
.stopnote
);
986 runtime_noteclear(&runtime_sched
.stopnote
);
988 if(runtime_sched
.stopwait
)
989 runtime_throw("stoptheworld: not stopped");
990 for(i
= 0; i
< runtime_gomaxprocs
; i
++) {
992 if(p
->status
!= _Pgcstop
)
993 runtime_throw("stoptheworld: not stopped");
1004 runtime_starttheworld(void)
1011 g
->m
->locks
++; // disable preemption because it can be holding p in a local var
1012 gp
= runtime_netpoll(false); // non-blocking
1014 add
= needaddgcproc();
1015 runtime_lock(&runtime_sched
);
1017 procresize(newprocs
);
1020 procresize(runtime_gomaxprocs
);
1021 runtime_sched
.gcwaiting
= 0;
1024 while((p
= pidleget()) != nil
) {
1025 // procresize() puts p's with work at the beginning of the list.
1026 // Once we reach a p without a run queue, the rest don't have one either.
1027 if(p
->runqhead
== p
->runqtail
) {
1031 p
->m
= (uintptr
)mget();
1032 p
->link
= (uintptr
)p1
;
1035 if(runtime_sched
.sysmonwait
) {
1036 runtime_sched
.sysmonwait
= false;
1037 runtime_notewakeup(&runtime_sched
.sysmonnote
);
1039 runtime_unlock(&runtime_sched
);
1048 runtime_throw("starttheworld: inconsistent mp->nextp");
1049 mp
->nextp
= (uintptr
)p
;
1050 runtime_notewakeup(&mp
->park
);
1052 // Start M to run P. Do not start another M below.
1059 // If GC could have used another helper proc, start one now,
1060 // in the hope that it will be available next time.
1061 // It would have been even better to start it before the collection,
1062 // but doing so requires allocating memory, so it's tricky to
1063 // coordinate. This lazy approach works out in practice:
1064 // we don't mind if the first couple gc rounds don't have quite
1065 // the maximum number of procs.
1071 // Called to start an M.
1073 runtime_mstart(void* mp
)
1086 // Record top of stack for use by mcall.
1087 // Once we call schedule we're never coming back,
1088 // so other calls can reuse this stack space.
1089 #ifdef USING_SPLIT_STACK
1090 __splitstack_getcontext(&g
->stackcontext
[0]);
1092 g
->gcinitialsp
= &mp
;
1093 // Setting gcstacksize to 0 is a marker meaning that gcinitialsp
1094 // is the top of the stack, not the bottom.
1098 getcontext(ucontext_arg(&g
->context
[0]));
1100 if(g
->entry
!= nil
) {
1101 // Got here from mcall.
1102 void (*pfn
)(G
*) = (void (*)(G
*))g
->entry
;
1103 G
* gp
= (G
*)g
->param
;
1109 #ifdef USING_SPLIT_STACK
1111 int dont_block_signals
= 0;
1112 __splitstack_block_signals(&dont_block_signals
, nil
);
1116 // Install signal handlers; after minit so that minit can
1117 // prepare the thread to be able to handle the signals.
1118 if(m
== &runtime_m0
) {
1119 if(runtime_iscgo
&& !runtime_cgoHasExtraM
) {
1120 runtime_cgoHasExtraM
= true;
1121 runtime_newextram();
1122 runtime_needextram
= 0;
1124 runtime_initsig(false);
1128 ((void (*)(void))m
->mstartfn
)();
1133 } else if(m
!= &runtime_m0
) {
1134 acquirep((P
*)m
->nextp
);
1139 // TODO(brainman): This point is never reached, because scheduler
1140 // does not release os threads at the moment. But once this path
1141 // is enabled, we must remove our seh here.
1146 typedef struct CgoThreadStart CgoThreadStart
;
1147 struct CgoThreadStart
1155 // Allocate a new m unassociated with any thread.
1156 // Can use p for allocation context if needed.
1158 runtime_allocm(P
*p
, int32 stacksize
, byte
** ret_g0_stack
, uintptr
* ret_g0_stacksize
)
1162 g
->m
->locks
++; // disable GC because it can be called from sysmon
1164 acquirep(p
); // temporarily borrow p for mallocs in this function
1168 runtime_gc_m_ptr(&e
);
1169 mtype
= ((const PtrType
*)e
.__type_descriptor
)->__element_type
;
1173 mp
= runtime_mal(sizeof *mp
);
1175 mp
->g0
= runtime_malg(stacksize
, ret_g0_stack
, ret_g0_stacksize
);
1178 if(p
== (P
*)g
->m
->p
)
1189 // static Type *gtype;
1191 // if(gtype == nil) {
1193 // runtime_gc_g_ptr(&e);
1194 // gtype = ((PtrType*)e.__type_descriptor)->__element_type;
1196 // gp = runtime_cnew(gtype);
1197 gp
= runtime_malloc(sizeof(G
));
1201 static M
* lockextra(bool nilokay
);
1202 static void unlockextra(M
*);
1204 // needm is called when a cgo callback happens on a
1205 // thread without an m (a thread not created by Go).
1206 // In this case, needm is expected to find an m to use
1207 // and return with m, g initialized correctly.
1208 // Since m and g are not set now (likely nil, but see below)
1209 // needm is limited in what routines it can call. In particular
1210 // it can only call nosplit functions (textflag 7) and cannot
1211 // do any scheduling that requires an m.
1213 // In order to avoid needing heavy lifting here, we adopt
1214 // the following strategy: there is a stack of available m's
1215 // that can be stolen. Using compare-and-swap
1216 // to pop from the stack has ABA races, so we simulate
1217 // a lock by doing an exchange (via casp) to steal the stack
1218 // head and replace the top pointer with MLOCKED (1).
1219 // This serves as a simple spin lock that we can use even
1220 // without an m. The thread that locks the stack in this way
1221 // unlocks the stack by storing a valid stack head pointer.
1223 // In order to make sure that there is always an m structure
1224 // available to be stolen, we maintain the invariant that there
1225 // is always one more than needed. At the beginning of the
1226 // program (if cgo is in use) the list is seeded with a single m.
1227 // If needm finds that it has taken the last m off the list, its job
1228 // is - once it has installed its own m so that it can do things like
1229 // allocate memory - to create a spare m and put it on the list.
1231 // Each of these extra m's also has a g0 and a curg that are
1232 // pressed into service as the scheduling stack and current
1233 // goroutine for the duration of the cgo callback.
1235 // When the callback is done with the m, it calls dropm to
1236 // put the m back on the list.
1238 // Unlike the gc toolchain, we start running on curg, since we are
1239 // just going to return and let the caller continue.
1245 if(runtime_needextram
) {
1246 // Can happen if C/C++ code calls Go from a global ctor.
1247 // Can not throw, because scheduler is not initialized yet.
1248 int rv
__attribute__((unused
));
1249 rv
= runtime_write(2, "fatal error: cgo callback before cgo call\n",
1250 sizeof("fatal error: cgo callback before cgo call\n")-1);
1254 // Lock extra list, take head, unlock popped list.
1255 // nilokay=false is safe here because of the invariant above,
1256 // that the extra list always contains or will soon contain
1258 mp
= lockextra(false);
1260 // Set needextram when we've just emptied the list,
1261 // so that the eventual call into cgocallbackg will
1262 // allocate a new m for the extra list. We delay the
1263 // allocation until then so that it can be done
1264 // after exitsyscall makes sure it is okay to be
1265 // running at all (that is, there's no garbage collection
1266 // running right now).
1267 mp
->needextram
= mp
->schedlink
== 0;
1268 unlockextra((M
*)mp
->schedlink
);
1270 // Install g (= m->curg).
1271 runtime_setg(mp
->curg
);
1273 // Initialize g's context as in mstart.
1275 g
->atomicstatus
= _Gsyscall
;
1278 #ifdef USING_SPLIT_STACK
1279 __splitstack_getcontext(&g
->stackcontext
[0]);
1281 g
->gcinitialsp
= &mp
;
1286 getcontext(ucontext_arg(&g
->context
[0]));
1288 if(g
->entry
!= nil
) {
1289 // Got here from mcall.
1290 void (*pfn
)(G
*) = (void (*)(G
*))g
->entry
;
1291 G
* gp
= (G
*)g
->param
;
1296 // Initialize this thread to use the m.
1299 #ifdef USING_SPLIT_STACK
1301 int dont_block_signals
= 0;
1302 __splitstack_block_signals(&dont_block_signals
, nil
);
1307 // newextram allocates an m and puts it on the extra list.
1308 // It is called with a working local m, so that it can do things
1309 // like call schedlock and allocate.
1311 runtime_newextram(void)
1316 uintptr g0_spsize
, spsize
;
1319 // Create extra goroutine locked to extra m.
1320 // The goroutine is the context in which the cgo callback will run.
1321 // The sched.pc will never be returned to, but setting it to
1322 // runtime.goexit makes clear to the traceback routines where
1323 // the goroutine stack ends.
1324 mp
= runtime_allocm(nil
, StackMin
, &g0_sp
, &g0_spsize
);
1325 gp
= runtime_malg(StackMin
, &sp
, &spsize
);
1326 gp
->atomicstatus
= _Gdead
;
1329 mp
->locked
= _LockInternal
;
1332 gp
->goid
= runtime_xadd64(&runtime_sched
.goidgen
, 1);
1333 // put on allg for garbage collector
1336 // The context for gp will be set up in runtime_needm. But
1337 // here we need to set up the context for g0.
1338 uc
= ucontext_arg(&mp
->g0
->context
[0]);
1340 uc
->uc_stack
.ss_sp
= g0_sp
;
1341 uc
->uc_stack
.ss_size
= (size_t)g0_spsize
;
1342 makecontext(uc
, kickoff
, 0);
1344 // Add m to the extra list.
1345 mnext
= lockextra(true);
1346 mp
->schedlink
= (uintptr
)mnext
;
1350 // dropm is called when a cgo callback has called needm but is now
1351 // done with the callback and returning back into the non-Go thread.
1352 // It puts the current m back onto the extra list.
1354 // The main expense here is the call to signalstack to release the
1355 // m's signal stack, and then the call to needm on the next callback
1356 // from this thread. It is tempting to try to save the m for next time,
1357 // which would eliminate both these costs, but there might not be
1358 // a next time: the current thread (which Go does not control) might exit.
1359 // If we saved the m for that thread, there would be an m leak each time
1360 // such a thread exited. Instead, we acquire and release an m on each
1361 // call. These should typically not be scheduling operations, just a few
1362 // atomics, so the cost should be small.
1364 // TODO(rsc): An alternative would be to allocate a dummy pthread per-thread
1365 // variable using pthread_key_create. Unlike the pthread keys we already use
1366 // on OS X, this dummy key would never be read by Go code. It would exist
1367 // only so that we could register at thread-exit-time destructor.
1368 // That destructor would put the m back onto the extra list.
1369 // This is purely a performance optimization. The current version,
1370 // in which dropm happens on each cgo call, is still correct too.
1371 // We may have to keep the current version on systems with cgo
1372 // but without pthreads, like Windows.
1378 // Undo whatever initialization minit did during needm.
1381 // Clear m and g, and return m to the extra list.
1382 // After the call to setg we can only call nosplit functions.
1386 mp
->curg
->atomicstatus
= _Gdead
;
1387 mp
->curg
->gcstack
= nil
;
1388 mp
->curg
->gcnextsp
= nil
;
1390 mnext
= lockextra(true);
1391 mp
->schedlink
= (uintptr
)mnext
;
1395 #define MLOCKED ((M*)1)
1397 // lockextra locks the extra list and returns the list head.
1398 // The caller must unlock the list by storing a new list head
1399 // to runtime.extram. If nilokay is true, then lockextra will
1400 // return a nil list head if that's what it finds. If nilokay is false,
1401 // lockextra will keep waiting until the list head is no longer nil.
1403 lockextra(bool nilokay
)
1406 void (*yield
)(void);
1409 mp
= runtime_atomicloadp(&runtime_extram
);
1411 yield
= runtime_osyield
;
1415 if(mp
== nil
&& !nilokay
) {
1419 if(!runtime_casp(&runtime_extram
, mp
, MLOCKED
)) {
1420 yield
= runtime_osyield
;
1432 runtime_atomicstorep(&runtime_extram
, mp
);
1442 mp
= runtime_atomicloadp(&runtime_extram
);
1447 if(!runtime_casp(&runtime_extram
, mp
, MLOCKED
)) {
1452 for(mc
= mp
; mc
!= nil
; mc
= (M
*)mc
->schedlink
)
1454 runtime_atomicstorep(&runtime_extram
, mp
);
1459 // Create a new m. It will start off with a call to fn, or else the scheduler.
1461 newm(void(*fn
)(void), P
*p
)
1465 mp
= runtime_allocm(p
, -1, nil
, nil
);
1466 mp
->nextp
= (uintptr
)p
;
1467 mp
->mstartfn
= (uintptr
)(void*)fn
;
1469 runtime_newosproc(mp
);
1472 // Stops execution of the current m until new work is available.
1473 // Returns with acquired P.
1481 runtime_throw("stopm holding locks");
1483 runtime_throw("stopm holding p");
1485 m
->spinning
= false;
1486 runtime_xadd(&runtime_sched
.nmspinning
, -1);
1490 runtime_lock(&runtime_sched
);
1492 runtime_unlock(&runtime_sched
);
1493 runtime_notesleep(&m
->park
);
1495 runtime_noteclear(&m
->park
);
1502 acquirep((P
*)m
->nextp
);
1509 g
->m
->spinning
= true;
1512 // Schedules some M to run the p (creates an M if necessary).
1513 // If p==nil, tries to get an idle P, if no idle P's does nothing.
1515 startm(P
*p
, bool spinning
)
1520 runtime_lock(&runtime_sched
);
1524 runtime_unlock(&runtime_sched
);
1526 runtime_xadd(&runtime_sched
.nmspinning
, -1);
1531 runtime_unlock(&runtime_sched
);
1540 runtime_throw("startm: m is spinning");
1542 runtime_throw("startm: m has p");
1543 mp
->spinning
= spinning
;
1544 mp
->nextp
= (uintptr
)p
;
1545 runtime_notewakeup(&mp
->park
);
1548 // Hands off P from syscall or locked M.
1552 // if it has local work, start it straight away
1553 if(p
->runqhead
!= p
->runqtail
|| runtime_sched
.runqsize
) {
1557 // no local work, check that there are no spinning/idle M's,
1558 // otherwise our help is not required
1559 if(runtime_atomicload(&runtime_sched
.nmspinning
) + runtime_atomicload(&runtime_sched
.npidle
) == 0 && // TODO: fast atomic
1560 runtime_cas(&runtime_sched
.nmspinning
, 0, 1)) {
1564 runtime_lock(&runtime_sched
);
1565 if(runtime_sched
.gcwaiting
) {
1566 p
->status
= _Pgcstop
;
1567 if(--runtime_sched
.stopwait
== 0)
1568 runtime_notewakeup(&runtime_sched
.stopnote
);
1569 runtime_unlock(&runtime_sched
);
1572 if(runtime_sched
.runqsize
) {
1573 runtime_unlock(&runtime_sched
);
1577 // If this is the last running P and nobody is polling network,
1578 // need to wakeup another M to poll network.
1579 if(runtime_sched
.npidle
== (uint32
)runtime_gomaxprocs
-1 && runtime_atomicload64(&runtime_sched
.lastpoll
) != 0) {
1580 runtime_unlock(&runtime_sched
);
1585 runtime_unlock(&runtime_sched
);
1588 // Tries to add one more P to execute G's.
1589 // Called when a G is made runnable (newproc, ready).
1593 // be conservative about spinning threads
1594 if(!runtime_cas(&runtime_sched
.nmspinning
, 0, 1))
1599 // Stops execution of the current m that is locked to a g until the g is runnable again.
1600 // Returns with acquired P.
1608 if(m
->lockedg
== nil
|| m
->lockedg
->lockedm
!= m
)
1609 runtime_throw("stoplockedm: inconsistent locking");
1611 // Schedule another M to run this p.
1616 // Wait until another thread schedules lockedg again.
1617 runtime_notesleep(&m
->park
);
1619 runtime_noteclear(&m
->park
);
1620 if(m
->lockedg
->atomicstatus
!= _Grunnable
)
1621 runtime_throw("stoplockedm: not runnable");
1622 acquirep((P
*)m
->nextp
);
1626 // Schedules the locked m to run the locked gp.
1635 runtime_throw("startlockedm: locked to me");
1637 runtime_throw("startlockedm: m has p");
1638 // directly handoff current P to the locked m
1641 mp
->nextp
= (uintptr
)p
;
1642 runtime_notewakeup(&mp
->park
);
1646 // Stops the current m for stoptheworld.
1647 // Returns when the world is restarted.
1653 if(!runtime_sched
.gcwaiting
)
1654 runtime_throw("gcstopm: not waiting for gc");
1655 if(g
->m
->spinning
) {
1656 g
->m
->spinning
= false;
1657 runtime_xadd(&runtime_sched
.nmspinning
, -1);
1660 runtime_lock(&runtime_sched
);
1661 p
->status
= _Pgcstop
;
1662 if(--runtime_sched
.stopwait
== 0)
1663 runtime_notewakeup(&runtime_sched
.stopnote
);
1664 runtime_unlock(&runtime_sched
);
1668 // Schedules gp to run on the current M.
1675 if(gp
->atomicstatus
!= _Grunnable
) {
1676 runtime_printf("execute: bad g status %d\n", gp
->atomicstatus
);
1677 runtime_throw("execute: bad g status");
1679 gp
->atomicstatus
= _Grunning
;
1681 ((P
*)g
->m
->p
)->schedtick
++;
1685 // Check whether the profiler needs to be turned on or off.
1686 hz
= runtime_sched
.profilehz
;
1687 if(g
->m
->profilehz
!= hz
)
1688 runtime_resetcpuprofiler(hz
);
1693 // Finds a runnable goroutine to execute.
1694 // Tries to steal from other P's, get g from global queue, poll network.
1703 if(runtime_sched
.gcwaiting
) {
1707 if(runtime_fingwait
&& runtime_fingwake
&& (gp
= runtime_wakefing()) != nil
)
1710 gp
= runqget((P
*)g
->m
->p
);
1714 if(runtime_sched
.runqsize
) {
1715 runtime_lock(&runtime_sched
);
1716 gp
= globrunqget((P
*)g
->m
->p
, 0);
1717 runtime_unlock(&runtime_sched
);
1722 gp
= runtime_netpoll(false); // non-blocking
1724 injectglist((G
*)gp
->schedlink
);
1725 gp
->atomicstatus
= _Grunnable
;
1728 // If number of spinning M's >= number of busy P's, block.
1729 // This is necessary to prevent excessive CPU consumption
1730 // when GOMAXPROCS>>1 but the program parallelism is low.
1731 if(!g
->m
->spinning
&& 2 * runtime_atomicload(&runtime_sched
.nmspinning
) >= runtime_gomaxprocs
- runtime_atomicload(&runtime_sched
.npidle
)) // TODO: fast atomic
1733 if(!g
->m
->spinning
) {
1734 g
->m
->spinning
= true;
1735 runtime_xadd(&runtime_sched
.nmspinning
, 1);
1737 // random steal from other P's
1738 for(i
= 0; i
< 2*runtime_gomaxprocs
; i
++) {
1739 if(runtime_sched
.gcwaiting
)
1741 p
= runtime_allp
[runtime_fastrand1()%runtime_gomaxprocs
];
1742 if(p
== (P
*)g
->m
->p
)
1745 gp
= runqsteal((P
*)g
->m
->p
, p
);
1750 // return P and block
1751 runtime_lock(&runtime_sched
);
1752 if(runtime_sched
.gcwaiting
) {
1753 runtime_unlock(&runtime_sched
);
1756 if(runtime_sched
.runqsize
) {
1757 gp
= globrunqget((P
*)g
->m
->p
, 0);
1758 runtime_unlock(&runtime_sched
);
1763 runtime_unlock(&runtime_sched
);
1764 if(g
->m
->spinning
) {
1765 g
->m
->spinning
= false;
1766 runtime_xadd(&runtime_sched
.nmspinning
, -1);
1768 // check all runqueues once again
1769 for(i
= 0; i
< runtime_gomaxprocs
; i
++) {
1770 p
= runtime_allp
[i
];
1771 if(p
&& p
->runqhead
!= p
->runqtail
) {
1772 runtime_lock(&runtime_sched
);
1774 runtime_unlock(&runtime_sched
);
1783 if(runtime_xchg64(&runtime_sched
.lastpoll
, 0) != 0) {
1785 runtime_throw("findrunnable: netpoll with p");
1787 runtime_throw("findrunnable: netpoll with spinning");
1788 gp
= runtime_netpoll(true); // block until new work is available
1789 runtime_atomicstore64(&runtime_sched
.lastpoll
, runtime_nanotime());
1791 runtime_lock(&runtime_sched
);
1793 runtime_unlock(&runtime_sched
);
1796 injectglist((G
*)gp
->schedlink
);
1797 gp
->atomicstatus
= _Grunnable
;
1812 if(g
->m
->spinning
) {
1813 g
->m
->spinning
= false;
1814 nmspinning
= runtime_xadd(&runtime_sched
.nmspinning
, -1);
1816 runtime_throw("findrunnable: negative nmspinning");
1818 nmspinning
= runtime_atomicload(&runtime_sched
.nmspinning
);
1820 // M wakeup policy is deliberately somewhat conservative (see nmspinning handling),
1821 // so see if we need to wakeup another P here.
1822 if (nmspinning
== 0 && runtime_atomicload(&runtime_sched
.npidle
) > 0)
1826 // Injects the list of runnable G's into the scheduler.
1827 // Can run concurrently with GC.
1829 injectglist(G
*glist
)
1836 runtime_lock(&runtime_sched
);
1837 for(n
= 0; glist
; n
++) {
1839 glist
= (G
*)gp
->schedlink
;
1840 gp
->atomicstatus
= _Grunnable
;
1843 runtime_unlock(&runtime_sched
);
1845 for(; n
&& runtime_sched
.npidle
; n
--)
1849 // One round of scheduler: find a runnable goroutine and execute it.
1858 runtime_throw("schedule: holding locks");
1861 if(runtime_sched
.gcwaiting
) {
1867 // Check the global runnable queue once in a while to ensure fairness.
1868 // Otherwise two goroutines can completely occupy the local runqueue
1869 // by constantly respawning each other.
1870 tick
= ((P
*)g
->m
->p
)->schedtick
;
1871 // This is a fancy way to say tick%61==0,
1872 // it uses 2 MUL instructions instead of a single DIV and so is faster on modern processors.
1873 if(tick
- (((uint64
)tick
*0x4325c53fu
)>>36)*61 == 0 && runtime_sched
.runqsize
> 0) {
1874 runtime_lock(&runtime_sched
);
1875 gp
= globrunqget((P
*)g
->m
->p
, 1);
1876 runtime_unlock(&runtime_sched
);
1881 gp
= runqget((P
*)g
->m
->p
);
1882 if(gp
&& g
->m
->spinning
)
1883 runtime_throw("schedule: spinning with local work");
1886 gp
= findrunnable(); // blocks until work is available
1891 // Hands off own p to the locked m,
1892 // then blocks waiting for a new p.
1900 // Puts the current goroutine into a waiting state and calls unlockf.
1901 // If unlockf returns false, the goroutine is resumed.
1903 runtime_park(bool(*unlockf
)(G
*, void*), void *lock
, const char *reason
)
1905 if(g
->atomicstatus
!= _Grunning
)
1906 runtime_throw("bad g status");
1907 g
->m
->waitlock
= lock
;
1908 g
->m
->waitunlockf
= unlockf
;
1909 g
->waitreason
= runtime_gostringnocopy((const byte
*)reason
);
1910 runtime_mcall(park0
);
1913 void gopark(FuncVal
*, void *, String
, byte
, int)
1914 __asm__ ("runtime.gopark");
1917 gopark(FuncVal
*unlockf
, void *lock
, String reason
,
1918 byte traceEv
__attribute__ ((unused
)),
1919 int traceskip
__attribute__ ((unused
)))
1921 if(g
->atomicstatus
!= _Grunning
)
1922 runtime_throw("bad g status");
1923 g
->m
->waitlock
= lock
;
1924 g
->m
->waitunlockf
= unlockf
== nil
? nil
: (void*)unlockf
->fn
;
1925 g
->waitreason
= reason
;
1926 runtime_mcall(park0
);
1930 parkunlock(G
*gp
, void *lock
)
1933 runtime_unlock(lock
);
1937 // Puts the current goroutine into a waiting state and unlocks the lock.
1938 // The goroutine can be made runnable again by calling runtime_ready(gp).
1940 runtime_parkunlock(Lock
*lock
, const char *reason
)
1942 runtime_park(parkunlock
, lock
, reason
);
1945 void goparkunlock(Lock
*, String
, byte
, int)
1946 __asm__ (GOSYM_PREFIX
"runtime.goparkunlock");
1949 goparkunlock(Lock
*lock
, String reason
, byte traceEv
__attribute__ ((unused
)),
1950 int traceskip
__attribute__ ((unused
)))
1952 if(g
->atomicstatus
!= _Grunning
)
1953 runtime_throw("bad g status");
1954 g
->m
->waitlock
= lock
;
1955 g
->m
->waitunlockf
= parkunlock
;
1956 g
->waitreason
= reason
;
1957 runtime_mcall(park0
);
1960 // runtime_park continuation on g0.
1968 gp
->atomicstatus
= _Gwaiting
;
1971 if(m
->waitunlockf
) {
1972 ok
= ((bool (*)(G
*, void*))m
->waitunlockf
)(gp
, m
->waitlock
);
1973 m
->waitunlockf
= nil
;
1976 gp
->atomicstatus
= _Grunnable
;
1977 execute(gp
); // Schedule it back, never returns.
1982 execute(gp
); // Never returns.
1989 runtime_gosched(void)
1991 if(g
->atomicstatus
!= _Grunning
)
1992 runtime_throw("bad g status");
1993 runtime_mcall(runtime_gosched0
);
1996 // runtime_gosched continuation on g0.
1998 runtime_gosched0(G
*gp
)
2003 gp
->atomicstatus
= _Grunnable
;
2006 runtime_lock(&runtime_sched
);
2008 runtime_unlock(&runtime_sched
);
2011 execute(gp
); // Never returns.
2016 // Finishes execution of the current goroutine.
2017 // Need to mark it as nosplit, because it runs with sp > stackbase (as runtime_lessstack).
2018 // Since it does not return it does not matter. But if it is preempted
2019 // at the split stack check, GC will complain about inconsistent sp.
2020 void runtime_goexit(void) __attribute__ ((noinline
));
2022 runtime_goexit(void)
2024 if(g
->atomicstatus
!= _Grunning
)
2025 runtime_throw("bad g status");
2026 runtime_mcall(goexit0
);
2029 // runtime_goexit continuation on g0.
2036 gp
->atomicstatus
= _Gdead
;
2040 gp
->paniconfault
= 0;
2041 gp
->_defer
= nil
; // should be true already but just in case.
2042 gp
->_panic
= nil
; // non-nil for Goexit during panic. points at stack-allocated data.
2043 gp
->writebuf
.__values
= nil
;
2044 gp
->writebuf
.__count
= 0;
2045 gp
->writebuf
.__capacity
= 0;
2046 gp
->waitreason
= runtime_gostringnocopy(nil
);
2050 if(m
->locked
& ~_LockExternal
) {
2051 runtime_printf("invalid m->locked = %d\n", m
->locked
);
2052 runtime_throw("internal lockOSThread error");
2055 gfput((P
*)m
->p
, gp
);
2059 // The goroutine g is about to enter a system call.
2060 // Record that it's not using the cpu anymore.
2061 // This is called only from the go syscall library and cgocall,
2062 // not from the low-level system calls used by the runtime.
2064 // Entersyscall cannot split the stack: the runtime_gosave must
2065 // make g->sched refer to the caller's stack segment, because
2066 // entersyscall is going to return immediately after.
2068 void runtime_entersyscall(int32
) __attribute__ ((no_split_stack
));
2069 static void doentersyscall(void) __attribute__ ((no_split_stack
, noinline
));
2072 runtime_entersyscall(int32 dummy
__attribute__ ((unused
)))
2074 // Save the registers in the g structure so that any pointers
2075 // held in registers will be seen by the garbage collector.
2076 getcontext(ucontext_arg(&g
->gcregs
[0]));
2078 // Do the work in a separate function, so that this function
2079 // doesn't save any registers on its own stack. If this
2080 // function does save any registers, we might store the wrong
2081 // value in the call to getcontext.
2083 // FIXME: This assumes that we do not need to save any
2084 // callee-saved registers to access the TLS variable g. We
2085 // don't want to put the ucontext_t on the stack because it is
2086 // large and we can not split the stack here.
2093 // Disable preemption because during this function g is in _Gsyscall status,
2094 // but can have inconsistent g->sched, do not let GC observe it.
2097 // Leave SP around for GC and traceback.
2098 #ifdef USING_SPLIT_STACK
2101 g
->gcstack
= __splitstack_find(nil
, nil
, &gcstacksize
,
2102 &g
->gcnextsegment
, &g
->gcnextsp
,
2104 g
->gcstacksize
= (uintptr
)gcstacksize
;
2110 g
->gcnextsp
= (byte
*) &v
;
2114 g
->atomicstatus
= _Gsyscall
;
2116 if(runtime_atomicload(&runtime_sched
.sysmonwait
)) { // TODO: fast atomic
2117 runtime_lock(&runtime_sched
);
2118 if(runtime_atomicload(&runtime_sched
.sysmonwait
)) {
2119 runtime_atomicstore(&runtime_sched
.sysmonwait
, 0);
2120 runtime_notewakeup(&runtime_sched
.sysmonnote
);
2122 runtime_unlock(&runtime_sched
);
2126 ((P
*)(g
->m
->p
))->m
= 0;
2127 runtime_atomicstore(&((P
*)g
->m
->p
)->status
, _Psyscall
);
2128 if(runtime_atomicload(&runtime_sched
.gcwaiting
)) {
2129 runtime_lock(&runtime_sched
);
2130 if (runtime_sched
.stopwait
> 0 && runtime_cas(&((P
*)g
->m
->p
)->status
, _Psyscall
, _Pgcstop
)) {
2131 if(--runtime_sched
.stopwait
== 0)
2132 runtime_notewakeup(&runtime_sched
.stopnote
);
2134 runtime_unlock(&runtime_sched
);
2140 // The same as runtime_entersyscall(), but with a hint that the syscall is blocking.
2142 runtime_entersyscallblock(int32 dummy
__attribute__ ((unused
)))
2146 g
->m
->locks
++; // see comment in entersyscall
2148 // Leave SP around for GC and traceback.
2149 #ifdef USING_SPLIT_STACK
2152 g
->gcstack
= __splitstack_find(nil
, nil
, &gcstacksize
,
2153 &g
->gcnextsegment
, &g
->gcnextsp
,
2155 g
->gcstacksize
= (uintptr
)gcstacksize
;
2158 g
->gcnextsp
= (byte
*) &p
;
2161 // Save the registers in the g structure so that any pointers
2162 // held in registers will be seen by the garbage collector.
2163 getcontext(ucontext_arg(&g
->gcregs
[0]));
2165 g
->atomicstatus
= _Gsyscall
;
2169 if(g
->isbackground
) // do not consider blocked scavenger for deadlock detection
2175 // The goroutine g exited its system call.
2176 // Arrange for it to run on a cpu again.
2177 // This is called only from the go syscall library, not
2178 // from the low-level system calls used by the runtime.
2180 runtime_exitsyscall(int32 dummy
__attribute__ ((unused
)))
2185 gp
->m
->locks
++; // see comment in entersyscall
2187 if(gp
->isbackground
) // do not consider blocked scavenger for deadlock detection
2191 if(exitsyscallfast()) {
2192 // There's a cpu for us, so we can run.
2193 ((P
*)gp
->m
->p
)->syscalltick
++;
2194 gp
->atomicstatus
= _Grunning
;
2195 // Garbage collector isn't running (since we are),
2196 // so okay to clear gcstack and gcsp.
2197 #ifdef USING_SPLIT_STACK
2201 runtime_memclr(&gp
->gcregs
[0], sizeof gp
->gcregs
);
2208 // Call the scheduler.
2209 runtime_mcall(exitsyscall0
);
2211 // Scheduler returned, so we're allowed to run now.
2212 // Delete the gcstack information that we left for
2213 // the garbage collector during the system call.
2214 // Must wait until now because until gosched returns
2215 // we don't know for sure that the garbage collector
2217 #ifdef USING_SPLIT_STACK
2221 runtime_memclr(&gp
->gcregs
[0], sizeof gp
->gcregs
);
2223 // Note that this gp->m might be different than the earlier
2224 // gp->m after returning from runtime_mcall.
2225 ((P
*)gp
->m
->p
)->syscalltick
++;
2229 exitsyscallfast(void)
2236 // Freezetheworld sets stopwait but does not retake P's.
2237 if(runtime_sched
.stopwait
) {
2242 // Try to re-acquire the last P.
2243 if(gp
->m
->p
&& ((P
*)gp
->m
->p
)->status
== _Psyscall
&& runtime_cas(&((P
*)gp
->m
->p
)->status
, _Psyscall
, _Prunning
)) {
2244 // There's a cpu for us, so we can run.
2245 gp
->m
->mcache
= ((P
*)gp
->m
->p
)->mcache
;
2246 ((P
*)gp
->m
->p
)->m
= (uintptr
)gp
->m
;
2249 // Try to get any other idle P.
2251 if(runtime_sched
.pidle
) {
2252 runtime_lock(&runtime_sched
);
2254 if(p
&& runtime_atomicload(&runtime_sched
.sysmonwait
)) {
2255 runtime_atomicstore(&runtime_sched
.sysmonwait
, 0);
2256 runtime_notewakeup(&runtime_sched
.sysmonnote
);
2258 runtime_unlock(&runtime_sched
);
2267 // runtime_exitsyscall slow path on g0.
2268 // Failed to acquire P, enqueue gp as runnable.
2276 gp
->atomicstatus
= _Grunnable
;
2279 runtime_lock(&runtime_sched
);
2283 else if(runtime_atomicload(&runtime_sched
.sysmonwait
)) {
2284 runtime_atomicstore(&runtime_sched
.sysmonwait
, 0);
2285 runtime_notewakeup(&runtime_sched
.sysmonnote
);
2287 runtime_unlock(&runtime_sched
);
2290 execute(gp
); // Never returns.
2293 // Wait until another thread schedules gp and so m again.
2295 execute(gp
); // Never returns.
2298 schedule(); // Never returns.
2301 void syscall_entersyscall(void)
2302 __asm__(GOSYM_PREFIX
"syscall.Entersyscall");
2304 void syscall_entersyscall(void) __attribute__ ((no_split_stack
));
2307 syscall_entersyscall()
2309 runtime_entersyscall(0);
2312 void syscall_exitsyscall(void)
2313 __asm__(GOSYM_PREFIX
"syscall.Exitsyscall");
2315 void syscall_exitsyscall(void) __attribute__ ((no_split_stack
));
2318 syscall_exitsyscall()
2320 runtime_exitsyscall(0);
2323 // Called from syscall package before fork.
2324 void syscall_runtime_BeforeFork(void)
2325 __asm__(GOSYM_PREFIX
"syscall.runtime_BeforeFork");
2327 syscall_runtime_BeforeFork(void)
2329 // Fork can hang if preempted with signals frequently enough (see issue 5517).
2330 // Ensure that we stay on the same M where we disable profiling.
2331 runtime_m()->locks
++;
2332 if(runtime_m()->profilehz
!= 0)
2333 runtime_resetcpuprofiler(0);
2336 // Called from syscall package after fork in parent.
2337 void syscall_runtime_AfterFork(void)
2338 __asm__(GOSYM_PREFIX
"syscall.runtime_AfterFork");
2340 syscall_runtime_AfterFork(void)
2344 hz
= runtime_sched
.profilehz
;
2346 runtime_resetcpuprofiler(hz
);
2347 runtime_m()->locks
--;
2350 // Allocate a new g, with a stack big enough for stacksize bytes.
2352 runtime_malg(int32 stacksize
, byte
** ret_stack
, uintptr
* ret_stacksize
)
2357 if(stacksize
>= 0) {
2358 #if USING_SPLIT_STACK
2359 int dont_block_signals
= 0;
2360 size_t ss_stacksize
;
2362 *ret_stack
= __splitstack_makecontext(stacksize
,
2363 &newg
->stackcontext
[0],
2365 *ret_stacksize
= (uintptr
)ss_stacksize
;
2366 __splitstack_block_signals_context(&newg
->stackcontext
[0],
2367 &dont_block_signals
, nil
);
2369 // In 64-bit mode, the maximum Go allocation space is
2370 // 128G. Our stack size is 4M, which only permits 32K
2371 // goroutines. In order to not limit ourselves,
2372 // allocate the stacks out of separate memory. In
2373 // 32-bit mode, the Go allocation space is all of
2375 if(sizeof(void*) == 8) {
2376 void *p
= runtime_SysAlloc(stacksize
, &mstats
.other_sys
);
2378 runtime_throw("runtime: cannot allocate memory for goroutine stack");
2379 *ret_stack
= (byte
*)p
;
2381 *ret_stack
= runtime_mallocgc(stacksize
, 0, FlagNoProfiling
|FlagNoGC
);
2382 runtime_xadd(&runtime_stacks_sys
, stacksize
);
2384 *ret_stacksize
= (uintptr
)stacksize
;
2385 newg
->gcinitialsp
= *ret_stack
;
2386 newg
->gcstacksize
= (uintptr
)stacksize
;
2393 __go_go(void (*fn
)(void*), void* arg
)
2400 //runtime_printf("newproc1 %p %p narg=%d nret=%d\n", fn->fn, argp, narg, nret);
2402 g
->m
->throwing
= -1; // do not dump full stacks
2403 runtime_throw("go of nil func value");
2405 g
->m
->locks
++; // disable preemption because it can be holding p in a local var
2408 if((newg
= gfget(p
)) != nil
) {
2409 #ifdef USING_SPLIT_STACK
2410 int dont_block_signals
= 0;
2412 sp
= __splitstack_resetcontext(&newg
->stackcontext
[0],
2414 __splitstack_block_signals_context(&newg
->stackcontext
[0],
2415 &dont_block_signals
, nil
);
2417 sp
= newg
->gcinitialsp
;
2418 spsize
= newg
->gcstacksize
;
2420 runtime_throw("bad spsize in __go_go");
2421 newg
->gcnextsp
= sp
;
2426 newg
= runtime_malg(StackMin
, &sp
, &malsize
);
2427 spsize
= (size_t)malsize
;
2431 newg
->entry
= (byte
*)fn
;
2433 newg
->gopc
= (uintptr
)__builtin_return_address(0);
2434 newg
->atomicstatus
= _Grunnable
;
2435 if(p
->goidcache
== p
->goidcacheend
) {
2436 p
->goidcache
= runtime_xadd64(&runtime_sched
.goidgen
, GoidCacheBatch
);
2437 p
->goidcacheend
= p
->goidcache
+ GoidCacheBatch
;
2439 newg
->goid
= p
->goidcache
++;
2442 // Avoid warnings about variables clobbered by
2444 byte
* volatile vsp
= sp
;
2445 size_t volatile vspsize
= spsize
;
2446 G
* volatile vnewg
= newg
;
2447 ucontext_t
* volatile uc
;
2449 uc
= ucontext_arg(&vnewg
->context
[0]);
2451 uc
->uc_stack
.ss_sp
= vsp
;
2452 uc
->uc_stack
.ss_size
= vspsize
;
2453 makecontext(uc
, kickoff
, 0);
2457 if(runtime_atomicload(&runtime_sched
.npidle
) != 0 && runtime_atomicload(&runtime_sched
.nmspinning
) == 0 && fn
!= runtime_main
) // TODO: fast atomic
2470 runtime_lock(&allglock
);
2471 if(runtime_allglen
>= allgcap
) {
2472 cap
= 4096/sizeof(new[0]);
2475 new = runtime_malloc(cap
*sizeof(new[0]));
2477 runtime_throw("runtime: cannot allocate memory");
2478 if(runtime_allg
!= nil
) {
2479 runtime_memmove(new, runtime_allg
, runtime_allglen
*sizeof(new[0]));
2480 runtime_free(runtime_allg
);
2485 runtime_allg
[runtime_allglen
++] = gp
;
2486 runtime_unlock(&allglock
);
2489 // Put on gfree list.
2490 // If local list is too long, transfer a batch to the global list.
2494 gp
->schedlink
= (uintptr
)p
->gfree
;
2497 if(p
->gfreecnt
>= 64) {
2498 runtime_lock(&runtime_sched
.gflock
);
2499 while(p
->gfreecnt
>= 32) {
2502 p
->gfree
= (G
*)gp
->schedlink
;
2503 gp
->schedlink
= (uintptr
)runtime_sched
.gfree
;
2504 runtime_sched
.gfree
= gp
;
2506 runtime_unlock(&runtime_sched
.gflock
);
2510 // Get from gfree list.
2511 // If local list is empty, grab a batch from global list.
2519 if(gp
== nil
&& runtime_sched
.gfree
) {
2520 runtime_lock(&runtime_sched
.gflock
);
2521 while(p
->gfreecnt
< 32 && runtime_sched
.gfree
) {
2523 gp
= runtime_sched
.gfree
;
2524 runtime_sched
.gfree
= (G
*)gp
->schedlink
;
2525 gp
->schedlink
= (uintptr
)p
->gfree
;
2528 runtime_unlock(&runtime_sched
.gflock
);
2532 p
->gfree
= (G
*)gp
->schedlink
;
2538 // Purge all cached G's from gfree list to the global list.
2544 runtime_lock(&runtime_sched
.gflock
);
2545 while(p
->gfreecnt
) {
2548 p
->gfree
= (G
*)gp
->schedlink
;
2549 gp
->schedlink
= (uintptr
)runtime_sched
.gfree
;
2550 runtime_sched
.gfree
= gp
;
2552 runtime_unlock(&runtime_sched
.gflock
);
2556 runtime_Breakpoint(void)
2558 runtime_breakpoint();
2561 void runtime_Gosched (void) __asm__ (GOSYM_PREFIX
"runtime.Gosched");
2564 runtime_Gosched(void)
2569 // Implementation of runtime.GOMAXPROCS.
2570 // delete when scheduler is even stronger
2572 runtime_gomaxprocsfunc(int32 n
)
2576 if(n
> _MaxGomaxprocs
)
2578 runtime_lock(&runtime_sched
);
2579 ret
= runtime_gomaxprocs
;
2580 if(n
<= 0 || n
== ret
) {
2581 runtime_unlock(&runtime_sched
);
2584 runtime_unlock(&runtime_sched
);
2586 runtime_semacquire(&runtime_worldsema
, false);
2588 runtime_stoptheworld();
2591 runtime_semrelease(&runtime_worldsema
);
2592 runtime_starttheworld();
2597 // lockOSThread is called by runtime.LockOSThread and runtime.lockOSThread below
2598 // after they modify m->locked. Do not allow preemption during this call,
2599 // or else the m might be different in this function than in the caller.
2607 void runtime_LockOSThread(void) __asm__ (GOSYM_PREFIX
"runtime.LockOSThread");
2609 runtime_LockOSThread(void)
2611 g
->m
->locked
|= _LockExternal
;
2616 runtime_lockOSThread(void)
2618 g
->m
->locked
+= _LockInternal
;
2623 // unlockOSThread is called by runtime.UnlockOSThread and runtime.unlockOSThread below
2624 // after they update m->locked. Do not allow preemption during this call,
2625 // or else the m might be in different in this function than in the caller.
2627 unlockOSThread(void)
2629 if(g
->m
->locked
!= 0)
2631 g
->m
->lockedg
= nil
;
2635 void runtime_UnlockOSThread(void) __asm__ (GOSYM_PREFIX
"runtime.UnlockOSThread");
2638 runtime_UnlockOSThread(void)
2640 g
->m
->locked
&= ~_LockExternal
;
2645 runtime_unlockOSThread(void)
2647 if(g
->m
->locked
< _LockInternal
)
2648 runtime_throw("runtime: internal error: misuse of lockOSThread/unlockOSThread");
2649 g
->m
->locked
-= _LockInternal
;
2654 runtime_lockedOSThread(void)
2656 return g
->lockedm
!= nil
&& g
->m
->lockedg
!= nil
;
2660 runtime_gcount(void)
2667 runtime_lock(&allglock
);
2668 // TODO(dvyukov): runtime.NumGoroutine() is O(N).
2669 // We do not want to increment/decrement centralized counter in newproc/goexit,
2670 // just to make runtime.NumGoroutine() faster.
2671 // Compromise solution is to introduce per-P counters of active goroutines.
2672 for(i
= 0; i
< runtime_allglen
; i
++) {
2673 gp
= runtime_allg
[i
];
2674 s
= gp
->atomicstatus
;
2675 if(s
== _Grunnable
|| s
== _Grunning
|| s
== _Gsyscall
|| s
== _Gwaiting
)
2678 runtime_unlock(&allglock
);
2683 runtime_mcount(void)
2685 return runtime_sched
.mcount
;
2690 void (*fn
)(uintptr
*, int32
);
2692 uintptr pcbuf
[TracebackMaxFrames
];
2693 Location locbuf
[TracebackMaxFrames
];
2696 static void System(void) {}
2697 static void GC(void) {}
2699 // Called if we receive a SIGPROF signal.
2707 if(prof
.fn
== nil
|| prof
.hz
== 0)
2713 // Profiling runs concurrently with GC, so it must not allocate.
2718 if(mp
->mcache
== nil
)
2721 runtime_lock(&prof
);
2722 if(prof
.fn
== nil
) {
2723 runtime_unlock(&prof
);
2729 if(runtime_atomicload(&runtime_in_callers
) > 0) {
2730 // If SIGPROF arrived while already fetching runtime
2731 // callers we can have trouble on older systems
2732 // because the unwind library calls dl_iterate_phdr
2733 // which was not recursive in the past.
2738 n
= runtime_callers(0, prof
.locbuf
, nelem(prof
.locbuf
), false);
2739 for(i
= 0; i
< n
; i
++)
2740 prof
.pcbuf
[i
] = prof
.locbuf
[i
].pc
;
2742 if(!traceback
|| n
<= 0) {
2744 prof
.pcbuf
[0] = (uintptr
)runtime_getcallerpc(&n
);
2745 if(mp
->gcing
|| mp
->helpgc
)
2746 prof
.pcbuf
[1] = (uintptr
)GC
;
2748 prof
.pcbuf
[1] = (uintptr
)System
;
2750 prof
.fn(prof
.pcbuf
, n
);
2751 runtime_unlock(&prof
);
2755 // Arrange to call fn with a traceback hz times a second.
2757 runtime_setcpuprofilerate(void (*fn
)(uintptr
*, int32
), int32 hz
)
2759 // Force sane arguments.
2767 // Disable preemption, otherwise we can be rescheduled to another thread
2768 // that has profiling enabled.
2771 // Stop profiler on this thread so that it is safe to lock prof.
2772 // if a profiling signal came in while we had prof locked,
2773 // it would deadlock.
2774 runtime_resetcpuprofiler(0);
2776 runtime_lock(&prof
);
2779 runtime_unlock(&prof
);
2780 runtime_lock(&runtime_sched
);
2781 runtime_sched
.profilehz
= hz
;
2782 runtime_unlock(&runtime_sched
);
2785 runtime_resetcpuprofiler(hz
);
2790 // Change number of processors. The world is stopped, sched is locked.
2792 procresize(int32
new)
2799 old
= runtime_gomaxprocs
;
2800 if(old
< 0 || old
> _MaxGomaxprocs
|| new <= 0 || new >_MaxGomaxprocs
)
2801 runtime_throw("procresize: invalid arg");
2802 // initialize new P's
2803 for(i
= 0; i
< new; i
++) {
2804 p
= runtime_allp
[i
];
2806 p
= (P
*)runtime_mallocgc(sizeof(*p
), 0, FlagNoInvokeGC
);
2808 p
->status
= _Pgcstop
;
2809 runtime_atomicstorep(&runtime_allp
[i
], p
);
2811 if(p
->mcache
== nil
) {
2813 p
->mcache
= g
->m
->mcache
; // bootstrap
2815 p
->mcache
= runtime_allocmcache();
2819 // redistribute runnable G's evenly
2820 // collect all runnable goroutines in global queue preserving FIFO order
2821 // FIFO order is required to ensure fairness even during frequent GCs
2822 // see http://golang.org/issue/7126
2826 for(i
= 0; i
< old
; i
++) {
2827 p
= runtime_allp
[i
];
2828 if(p
->runqhead
== p
->runqtail
)
2831 // pop from tail of local queue
2833 gp
= (G
*)p
->runq
[p
->runqtail
%nelem(p
->runq
)];
2834 // push onto head of global queue
2835 gp
->schedlink
= (uintptr
)runtime_sched
.runqhead
;
2836 runtime_sched
.runqhead
= gp
;
2837 if(runtime_sched
.runqtail
== nil
)
2838 runtime_sched
.runqtail
= gp
;
2839 runtime_sched
.runqsize
++;
2842 // fill local queues with at most nelem(p->runq)/2 goroutines
2843 // start at 1 because current M already executes some G and will acquire allp[0] below,
2844 // so if we have a spare G we want to put it into allp[1].
2845 for(i
= 1; (uint32
)i
< (uint32
)new * nelem(p
->runq
)/2 && runtime_sched
.runqsize
> 0; i
++) {
2846 gp
= runtime_sched
.runqhead
;
2847 runtime_sched
.runqhead
= (G
*)gp
->schedlink
;
2848 if(runtime_sched
.runqhead
== nil
)
2849 runtime_sched
.runqtail
= nil
;
2850 runtime_sched
.runqsize
--;
2851 runqput(runtime_allp
[i
%new], gp
);
2855 for(i
= new; i
< old
; i
++) {
2856 p
= runtime_allp
[i
];
2857 runtime_freemcache(p
->mcache
);
2861 // can't free P itself because it can be referenced by an M in syscall
2865 ((P
*)g
->m
->p
)->m
= 0;
2868 p
= runtime_allp
[0];
2872 for(i
= new-1; i
> 0; i
--) {
2873 p
= runtime_allp
[i
];
2877 runtime_atomicstore((uint32
*)&runtime_gomaxprocs
, new);
2880 // Associate p and the current m.
2887 if(m
->p
|| m
->mcache
)
2888 runtime_throw("acquirep: already in go");
2889 if(p
->m
|| p
->status
!= _Pidle
) {
2890 runtime_printf("acquirep: p->m=%p(%d) p->status=%d\n", p
->m
, p
->m
? ((M
*)p
->m
)->id
: 0, p
->status
);
2891 runtime_throw("acquirep: invalid p state");
2893 m
->mcache
= p
->mcache
;
2896 p
->status
= _Prunning
;
2899 // Disassociate p and the current m.
2907 if(m
->p
== 0 || m
->mcache
== nil
)
2908 runtime_throw("releasep: invalid arg");
2910 if((M
*)p
->m
!= m
|| p
->mcache
!= m
->mcache
|| p
->status
!= _Prunning
) {
2911 runtime_printf("releasep: m=%p m->p=%p p->m=%p m->mcache=%p p->mcache=%p p->status=%d\n",
2912 m
, m
->p
, p
->m
, m
->mcache
, p
->mcache
, p
->status
);
2913 runtime_throw("releasep: invalid p state");
2923 incidlelocked(int32 v
)
2925 runtime_lock(&runtime_sched
);
2926 runtime_sched
.nmidlelocked
+= v
;
2929 runtime_unlock(&runtime_sched
);
2932 // Check for deadlock situation.
2933 // The check is based on number of running M's, if 0 -> deadlock.
2938 int32 run
, grunning
, s
;
2941 // For -buildmode=c-shared or -buildmode=c-archive it's OK if
2942 // there are no running goroutines. The calling program is
2943 // assumed to be running.
2944 if(runtime_isarchive
) {
2949 run
= runtime_sched
.mcount
- runtime_sched
.nmidle
- runtime_sched
.nmidlelocked
- 1 - countextra();
2952 // If we are dying because of a signal caught on an already idle thread,
2953 // freezetheworld will cause all running threads to block.
2954 // And runtime will essentially enter into deadlock state,
2955 // except that there is a thread that will call runtime_exit soon.
2956 if(runtime_panicking
> 0)
2959 runtime_printf("runtime: checkdead: nmidle=%d nmidlelocked=%d mcount=%d\n",
2960 runtime_sched
.nmidle
, runtime_sched
.nmidlelocked
, runtime_sched
.mcount
);
2961 runtime_throw("checkdead: inconsistent counts");
2964 runtime_lock(&allglock
);
2965 for(i
= 0; i
< runtime_allglen
; i
++) {
2966 gp
= runtime_allg
[i
];
2967 if(gp
->isbackground
)
2969 s
= gp
->atomicstatus
;
2972 else if(s
== _Grunnable
|| s
== _Grunning
|| s
== _Gsyscall
) {
2973 runtime_unlock(&allglock
);
2974 runtime_printf("runtime: checkdead: find g %D in status %d\n", gp
->goid
, s
);
2975 runtime_throw("checkdead: runnable g");
2978 runtime_unlock(&allglock
);
2979 if(grunning
== 0) // possible if main goroutine calls runtime_Goexit()
2980 runtime_throw("no goroutines (main called runtime.Goexit) - deadlock!");
2981 g
->m
->throwing
= -1; // do not dump full stacks
2982 runtime_throw("all goroutines are asleep - deadlock!");
2989 int64 now
, lastpoll
, lasttrace
;
2993 idle
= 0; // how many cycles in succession we had not wokeup somebody
2996 if(idle
== 0) // start with 20us sleep...
2998 else if(idle
> 50) // start doubling the sleep after 1ms...
3000 if(delay
> 10*1000) // up to 10ms
3002 runtime_usleep(delay
);
3003 if(runtime_debug
.schedtrace
<= 0 &&
3004 (runtime_sched
.gcwaiting
|| runtime_atomicload(&runtime_sched
.npidle
) == (uint32
)runtime_gomaxprocs
)) { // TODO: fast atomic
3005 runtime_lock(&runtime_sched
);
3006 if(runtime_atomicload(&runtime_sched
.gcwaiting
) || runtime_atomicload(&runtime_sched
.npidle
) == (uint32
)runtime_gomaxprocs
) {
3007 runtime_atomicstore(&runtime_sched
.sysmonwait
, 1);
3008 runtime_unlock(&runtime_sched
);
3009 runtime_notesleep(&runtime_sched
.sysmonnote
);
3010 runtime_noteclear(&runtime_sched
.sysmonnote
);
3014 runtime_unlock(&runtime_sched
);
3016 // poll network if not polled for more than 10ms
3017 lastpoll
= runtime_atomicload64(&runtime_sched
.lastpoll
);
3018 now
= runtime_nanotime();
3019 if(lastpoll
!= 0 && lastpoll
+ 10*1000*1000 < now
) {
3020 runtime_cas64(&runtime_sched
.lastpoll
, lastpoll
, now
);
3021 gp
= runtime_netpoll(false); // non-blocking
3023 // Need to decrement number of idle locked M's
3024 // (pretending that one more is running) before injectglist.
3025 // Otherwise it can lead to the following situation:
3026 // injectglist grabs all P's but before it starts M's to run the P's,
3027 // another M returns from syscall, finishes running its G,
3028 // observes that there is no work to do and no other running M's
3029 // and reports deadlock.
3035 // retake P's blocked in syscalls
3036 // and preempt long running G's
3042 if(runtime_debug
.schedtrace
> 0 && lasttrace
+ runtime_debug
.schedtrace
*1000000ll <= now
) {
3044 runtime_schedtrace(runtime_debug
.scheddetail
);
3049 typedef struct Pdesc Pdesc
;
3057 static Pdesc pdesc
[_MaxGomaxprocs
];
3068 for(i
= 0; i
< (uint32
)runtime_gomaxprocs
; i
++) {
3069 p
= runtime_allp
[i
];
3074 if(s
== _Psyscall
) {
3075 // Retake P from syscall if it's there for more than 1 sysmon tick (at least 20us).
3077 if(pd
->syscalltick
!= t
) {
3078 pd
->syscalltick
= t
;
3079 pd
->syscallwhen
= now
;
3082 // On the one hand we don't want to retake Ps if there is no other work to do,
3083 // but on the other hand we want to retake them eventually
3084 // because they can prevent the sysmon thread from deep sleep.
3085 if(p
->runqhead
== p
->runqtail
&&
3086 runtime_atomicload(&runtime_sched
.nmspinning
) + runtime_atomicload(&runtime_sched
.npidle
) > 0 &&
3087 pd
->syscallwhen
+ 10*1000*1000 > now
)
3089 // Need to decrement number of idle locked M's
3090 // (pretending that one more is running) before the CAS.
3091 // Otherwise the M from which we retake can exit the syscall,
3092 // increment nmidle and report deadlock.
3094 if(runtime_cas(&p
->status
, s
, _Pidle
)) {
3099 } else if(s
== _Prunning
) {
3100 // Preempt G if it's running for more than 10ms.
3102 if(pd
->schedtick
!= t
) {
3104 pd
->schedwhen
= now
;
3107 if(pd
->schedwhen
+ 10*1000*1000 > now
)
3115 // Tell all goroutines that they have been preempted and they should stop.
3116 // This function is purely best-effort. It can fail to inform a goroutine if a
3117 // processor just started running it.
3118 // No locks need to be held.
3119 // Returns true if preemption request was issued to at least one goroutine.
3127 runtime_schedtrace(bool detailed
)
3129 static int64 starttime
;
3131 int64 id1
, id2
, id3
;
3139 now
= runtime_nanotime();
3143 runtime_lock(&runtime_sched
);
3144 runtime_printf("SCHED %Dms: gomaxprocs=%d idleprocs=%d threads=%d idlethreads=%d runqueue=%d",
3145 (now
-starttime
)/1000000, runtime_gomaxprocs
, runtime_sched
.npidle
, runtime_sched
.mcount
,
3146 runtime_sched
.nmidle
, runtime_sched
.runqsize
);
3148 runtime_printf(" gcwaiting=%d nmidlelocked=%d nmspinning=%d stopwait=%d sysmonwait=%d\n",
3149 runtime_sched
.gcwaiting
, runtime_sched
.nmidlelocked
, runtime_sched
.nmspinning
,
3150 runtime_sched
.stopwait
, runtime_sched
.sysmonwait
);
3152 // We must be careful while reading data from P's, M's and G's.
3153 // Even if we hold schedlock, most data can be changed concurrently.
3154 // E.g. (p->m ? p->m->id : -1) can crash if p->m changes from non-nil to nil.
3155 for(i
= 0; i
< runtime_gomaxprocs
; i
++) {
3156 p
= runtime_allp
[i
];
3160 h
= runtime_atomicload(&p
->runqhead
);
3161 t
= runtime_atomicload(&p
->runqtail
);
3163 runtime_printf(" P%d: status=%d schedtick=%d syscalltick=%d m=%d runqsize=%d gfreecnt=%d\n",
3164 i
, p
->status
, p
->schedtick
, p
->syscalltick
, mp
? mp
->id
: -1, t
-h
, p
->gfreecnt
);
3166 // In non-detailed mode format lengths of per-P run queues as:
3167 // [len1 len2 len3 len4]
3169 if(runtime_gomaxprocs
== 1)
3173 else if(i
== runtime_gomaxprocs
-1)
3175 runtime_printf(fmt
, t
-h
);
3179 runtime_unlock(&runtime_sched
);
3182 for(mp
= runtime_allm
; mp
; mp
= mp
->alllink
) {
3185 lockedg
= mp
->lockedg
;
3194 id3
= lockedg
->goid
;
3195 runtime_printf(" M%d: p=%D curg=%D mallocing=%d throwing=%d gcing=%d"
3196 " locks=%d dying=%d helpgc=%d spinning=%d blocked=%d lockedg=%D\n",
3198 mp
->mallocing
, mp
->throwing
, mp
->gcing
, mp
->locks
, mp
->dying
, mp
->helpgc
,
3199 mp
->spinning
, mp
->blocked
, id3
);
3201 runtime_lock(&allglock
);
3202 for(gi
= 0; gi
< runtime_allglen
; gi
++) {
3203 gp
= runtime_allg
[gi
];
3205 lockedm
= gp
->lockedm
;
3206 runtime_printf(" G%D: status=%d(%S) m=%d lockedm=%d\n",
3207 gp
->goid
, gp
->atomicstatus
, gp
->waitreason
, mp
? mp
->id
: -1,
3208 lockedm
? lockedm
->id
: -1);
3210 runtime_unlock(&allglock
);
3211 runtime_unlock(&runtime_sched
);
3214 // Put mp on midle list.
3215 // Sched must be locked.
3219 mp
->schedlink
= (uintptr
)runtime_sched
.midle
;
3220 runtime_sched
.midle
= mp
;
3221 runtime_sched
.nmidle
++;
3225 // Try to get an m from midle list.
3226 // Sched must be locked.
3232 if((mp
= runtime_sched
.midle
) != nil
){
3233 runtime_sched
.midle
= (M
*)mp
->schedlink
;
3234 runtime_sched
.nmidle
--;
3239 // Put gp on the global runnable queue.
3240 // Sched must be locked.
3245 if(runtime_sched
.runqtail
)
3246 runtime_sched
.runqtail
->schedlink
= (uintptr
)gp
;
3248 runtime_sched
.runqhead
= gp
;
3249 runtime_sched
.runqtail
= gp
;
3250 runtime_sched
.runqsize
++;
3253 // Put a batch of runnable goroutines on the global runnable queue.
3254 // Sched must be locked.
3256 globrunqputbatch(G
*ghead
, G
*gtail
, int32 n
)
3258 gtail
->schedlink
= 0;
3259 if(runtime_sched
.runqtail
)
3260 runtime_sched
.runqtail
->schedlink
= (uintptr
)ghead
;
3262 runtime_sched
.runqhead
= ghead
;
3263 runtime_sched
.runqtail
= gtail
;
3264 runtime_sched
.runqsize
+= n
;
3267 // Try get a batch of G's from the global runnable queue.
3268 // Sched must be locked.
3270 globrunqget(P
*p
, int32 max
)
3275 if(runtime_sched
.runqsize
== 0)
3277 n
= runtime_sched
.runqsize
/runtime_gomaxprocs
+1;
3278 if(n
> runtime_sched
.runqsize
)
3279 n
= runtime_sched
.runqsize
;
3280 if(max
> 0 && n
> max
)
3282 if((uint32
)n
> nelem(p
->runq
)/2)
3283 n
= nelem(p
->runq
)/2;
3284 runtime_sched
.runqsize
-= n
;
3285 if(runtime_sched
.runqsize
== 0)
3286 runtime_sched
.runqtail
= nil
;
3287 gp
= runtime_sched
.runqhead
;
3288 runtime_sched
.runqhead
= (G
*)gp
->schedlink
;
3291 gp1
= runtime_sched
.runqhead
;
3292 runtime_sched
.runqhead
= (G
*)gp1
->schedlink
;
3298 // Put p to on pidle list.
3299 // Sched must be locked.
3303 p
->link
= (uintptr
)runtime_sched
.pidle
;
3304 runtime_sched
.pidle
= p
;
3305 runtime_xadd(&runtime_sched
.npidle
, 1); // TODO: fast atomic
3308 // Try get a p from pidle list.
3309 // Sched must be locked.
3315 p
= runtime_sched
.pidle
;
3317 runtime_sched
.pidle
= (P
*)p
->link
;
3318 runtime_xadd(&runtime_sched
.npidle
, -1); // TODO: fast atomic
3323 // Try to put g on local runnable queue.
3324 // If it's full, put onto global queue.
3325 // Executed only by the owner P.
3327 runqput(P
*p
, G
*gp
)
3332 h
= runtime_atomicload(&p
->runqhead
); // load-acquire, synchronize with consumers
3334 if(t
- h
< nelem(p
->runq
)) {
3335 p
->runq
[t
%nelem(p
->runq
)] = (uintptr
)gp
;
3336 runtime_atomicstore(&p
->runqtail
, t
+1); // store-release, makes the item available for consumption
3339 if(runqputslow(p
, gp
, h
, t
))
3341 // the queue is not full, now the put above must suceed
3345 // Put g and a batch of work from local runnable queue on global queue.
3346 // Executed only by the owner P.
3348 runqputslow(P
*p
, G
*gp
, uint32 h
, uint32 t
)
3350 G
*batch
[nelem(p
->runq
)/2+1];
3353 // First, grab a batch from local queue.
3356 if(n
!= nelem(p
->runq
)/2)
3357 runtime_throw("runqputslow: queue is not full");
3359 batch
[i
] = (G
*)p
->runq
[(h
+i
)%nelem(p
->runq
)];
3360 if(!runtime_cas(&p
->runqhead
, h
, h
+n
)) // cas-release, commits consume
3363 // Link the goroutines.
3365 batch
[i
]->schedlink
= (uintptr
)batch
[i
+1];
3366 // Now put the batch on global queue.
3367 runtime_lock(&runtime_sched
);
3368 globrunqputbatch(batch
[0], batch
[n
], n
+1);
3369 runtime_unlock(&runtime_sched
);
3373 // Get g from local runnable queue.
3374 // Executed only by the owner P.
3382 h
= runtime_atomicload(&p
->runqhead
); // load-acquire, synchronize with other consumers
3386 gp
= (G
*)p
->runq
[h
%nelem(p
->runq
)];
3387 if(runtime_cas(&p
->runqhead
, h
, h
+1)) // cas-release, commits consume
3392 // Grabs a batch of goroutines from local runnable queue.
3393 // batch array must be of size nelem(p->runq)/2. Returns number of grabbed goroutines.
3394 // Can be executed by any P.
3396 runqgrab(P
*p
, G
**batch
)
3401 h
= runtime_atomicload(&p
->runqhead
); // load-acquire, synchronize with other consumers
3402 t
= runtime_atomicload(&p
->runqtail
); // load-acquire, synchronize with the producer
3407 if(n
> nelem(p
->runq
)/2) // read inconsistent h and t
3410 batch
[i
] = (G
*)p
->runq
[(h
+i
)%nelem(p
->runq
)];
3411 if(runtime_cas(&p
->runqhead
, h
, h
+n
)) // cas-release, commits consume
3417 // Steal half of elements from local runnable queue of p2
3418 // and put onto local runnable queue of p.
3419 // Returns one of the stolen elements (or nil if failed).
3421 runqsteal(P
*p
, P
*p2
)
3424 G
*batch
[nelem(p
->runq
)/2];
3427 n
= runqgrab(p2
, batch
);
3434 h
= runtime_atomicload(&p
->runqhead
); // load-acquire, synchronize with consumers
3436 if(t
- h
+ n
>= nelem(p
->runq
))
3437 runtime_throw("runqsteal: runq overflow");
3438 for(i
=0; i
<n
; i
++, t
++)
3439 p
->runq
[t
%nelem(p
->runq
)] = (uintptr
)batch
[i
];
3440 runtime_atomicstore(&p
->runqtail
, t
); // store-release, makes the item available for consumption
3444 void runtime_testSchedLocalQueue(void)
3445 __asm__("runtime.testSchedLocalQueue");
3448 runtime_testSchedLocalQueue(void)
3451 G gs
[nelem(p
.runq
)];
3454 runtime_memclr((byte
*)&p
, sizeof(p
));
3456 for(i
= 0; i
< (int32
)nelem(gs
); i
++) {
3457 if(runqget(&p
) != nil
)
3458 runtime_throw("runq is not empty initially");
3459 for(j
= 0; j
< i
; j
++)
3460 runqput(&p
, &gs
[i
]);
3461 for(j
= 0; j
< i
; j
++) {
3462 if(runqget(&p
) != &gs
[i
]) {
3463 runtime_printf("bad element at iter %d/%d\n", i
, j
);
3464 runtime_throw("bad element");
3467 if(runqget(&p
) != nil
)
3468 runtime_throw("runq is not empty afterwards");
3472 void runtime_testSchedLocalQueueSteal(void)
3473 __asm__("runtime.testSchedLocalQueueSteal");
3476 runtime_testSchedLocalQueueSteal(void)
3479 G gs
[nelem(p1
.runq
)], *gp
;
3482 runtime_memclr((byte
*)&p1
, sizeof(p1
));
3483 runtime_memclr((byte
*)&p2
, sizeof(p2
));
3485 for(i
= 0; i
< (int32
)nelem(gs
); i
++) {
3486 for(j
= 0; j
< i
; j
++) {
3488 runqput(&p1
, &gs
[j
]);
3490 gp
= runqsteal(&p2
, &p1
);
3496 while((gp
= runqget(&p2
)) != nil
) {
3500 while((gp
= runqget(&p1
)) != nil
)
3502 for(j
= 0; j
< i
; j
++) {
3503 if(gs
[j
].sig
!= 1) {
3504 runtime_printf("bad element %d(%d) at iter %d\n", j
, gs
[j
].sig
, i
);
3505 runtime_throw("bad element");
3508 if(s
!= i
/2 && s
!= i
/2+1) {
3509 runtime_printf("bad steal %d, want %d or %d, iter %d\n",
3511 runtime_throw("bad steal");
3517 runtime_setmaxthreads(int32 in
)
3521 runtime_lock(&runtime_sched
);
3522 out
= runtime_sched
.maxmcount
;
3523 runtime_sched
.maxmcount
= in
;
3525 runtime_unlock(&runtime_sched
);
3530 runtime_proc_scan(struct Workbuf
** wbufp
, void (*enqueue1
)(struct Workbuf
**, Obj
))
3532 enqueue1(wbufp
, (Obj
){(byte
*)&runtime_sched
, sizeof runtime_sched
, 0});
3533 enqueue1(wbufp
, (Obj
){(byte
*)&runtime_main_init_done
, sizeof runtime_main_init_done
, 0});
3536 // Return whether we are waiting for a GC. This gc toolchain uses
3537 // preemption instead.
3539 runtime_gcwaiting(void)
3541 return runtime_sched
.gcwaiting
;
3544 // os_beforeExit is called from os.Exit(0).
3545 //go:linkname os_beforeExit os.runtime_beforeExit
3547 extern void os_beforeExit() __asm__ (GOSYM_PREFIX
"os.runtime_beforeExit");
3554 // Active spinning for sync.Mutex.
3555 //go:linkname sync_runtime_canSpin sync.runtime_canSpin
3560 ACTIVE_SPIN_CNT
= 30,
3563 extern _Bool
sync_runtime_canSpin(intgo i
)
3564 __asm__ (GOSYM_PREFIX
"sync.runtime_canSpin");
3567 sync_runtime_canSpin(intgo i
)
3571 // sync.Mutex is cooperative, so we are conservative with spinning.
3572 // Spin only few times and only if running on a multicore machine and
3573 // GOMAXPROCS>1 and there is at least one other running P and local runq is empty.
3574 // As opposed to runtime mutex we don't do passive spinning here,
3575 // because there can be work on global runq on on other Ps.
3576 if (i
>= ACTIVE_SPIN
|| runtime_ncpu
<= 1 || runtime_gomaxprocs
<= (int32
)(runtime_sched
.npidle
+runtime_sched
.nmspinning
)+1) {
3580 return p
!= nil
&& p
->runqhead
== p
->runqtail
;
3583 //go:linkname sync_runtime_doSpin sync.runtime_doSpin
3586 extern void sync_runtime_doSpin(void)
3587 __asm__ (GOSYM_PREFIX
"sync.runtime_doSpin");
3590 sync_runtime_doSpin()
3592 runtime_procyield(ACTIVE_SPIN_CNT
);