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
25 #ifdef USING_SPLIT_STACK
27 /* FIXME: These are not declared anywhere. */
29 extern void __splitstack_getcontext(void *context
[10]);
31 extern void __splitstack_setcontext(void *context
[10]);
33 extern void *__splitstack_makecontext(size_t, void *context
[10], size_t *);
35 extern void * __splitstack_resetcontext(void *context
[10], size_t *);
37 extern void *__splitstack_find(void *, void *, size_t *, void **, void **,
40 extern void __splitstack_block_signals (int *, int *);
42 extern void __splitstack_block_signals_context (void *context
[10], int *,
47 #ifndef PTHREAD_STACK_MIN
48 # define PTHREAD_STACK_MIN 8192
51 #if defined(USING_SPLIT_STACK) && defined(LINKER_SUPPORTS_SPLIT_STACK)
52 # define StackMin PTHREAD_STACK_MIN
54 # define StackMin 2 * 1024 * 1024
57 uintptr runtime_stacks_sys
;
59 static void gtraceback(G
*);
68 #ifndef SETCONTEXT_CLOBBERS_TLS
76 fixcontext(ucontext_t
*c
__attribute__ ((unused
)))
82 # if defined(__x86_64__) && defined(__sun__)
84 // x86_64 Solaris 10 and 11 have a bug: setcontext switches the %fs
85 // register to that of the thread which called getcontext. The effect
86 // is that the address of all __thread variables changes. This bug
87 // also affects pthread_self() and pthread_getspecific. We work
88 // around it by clobbering the context field directly to keep %fs the
91 static __thread greg_t fs
;
99 fs
= c
.uc_mcontext
.gregs
[REG_FSBASE
];
103 fixcontext(ucontext_t
* c
)
105 c
->uc_mcontext
.gregs
[REG_FSBASE
] = fs
;
108 # elif defined(__NetBSD__)
110 // NetBSD has a bug: setcontext clobbers tlsbase, we need to save
111 // and restore it ourselves.
113 static __thread __greg_t tlsbase
;
121 tlsbase
= c
.uc_mcontext
._mc_tlsbase
;
125 fixcontext(ucontext_t
* c
)
127 c
->uc_mcontext
._mc_tlsbase
= tlsbase
;
132 # error unknown case for SETCONTEXT_CLOBBERS_TLS
138 // We can not always refer to the TLS variables directly. The
139 // compiler will call tls_get_addr to get the address of the variable,
140 // and it may hold it in a register across a call to schedule. When
141 // we get back from the call we may be running in a different thread,
142 // in which case the register now points to the TLS variable for a
143 // different thread. We use non-inlinable functions to avoid this
146 G
* runtime_g(void) __attribute__ ((noinline
, no_split_stack
));
154 M
* runtime_m(void) __attribute__ ((noinline
, no_split_stack
));
164 runtime_setmg(M
* mp
, G
* gp
)
170 // The static TLS size. See runtime_newm.
173 // Start a new thread.
175 runtime_newosproc(M
*mp
)
183 if(pthread_attr_init(&attr
) != 0)
184 runtime_throw("pthread_attr_init");
185 if(pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0)
186 runtime_throw("pthread_attr_setdetachstate");
188 stacksize
= PTHREAD_STACK_MIN
;
190 // With glibc before version 2.16 the static TLS size is taken
191 // out of the stack size, and we get an error or a crash if
192 // there is not enough stack space left. Add it back in if we
193 // can, in case the program uses a lot of TLS space. FIXME:
194 // This can be disabled in glibc 2.16 and later, if the bug is
195 // indeed fixed then.
196 stacksize
+= tlssize
;
198 if(pthread_attr_setstacksize(&attr
, stacksize
) != 0)
199 runtime_throw("pthread_attr_setstacksize");
201 // Block signals during pthread_create so that the new thread
202 // starts with signals disabled. It will enable them in minit.
206 // Blocking SIGTRAP reportedly breaks gdb on Alpha GNU/Linux.
207 sigdelset(&clear
, SIGTRAP
);
211 pthread_sigmask(SIG_BLOCK
, &clear
, &old
);
212 ret
= pthread_create(&tid
, &attr
, runtime_mstart
, mp
);
213 pthread_sigmask(SIG_SETMASK
, &old
, nil
);
216 runtime_throw("pthread_create");
219 // First function run by a new goroutine. This replaces gogocall.
225 if(g
->traceback
!= nil
)
228 fn
= (void (*)(void*))(g
->entry
);
233 // Switch context to a different goroutine. This is like longjmp.
234 void runtime_gogo(G
*) __attribute__ ((noinline
));
236 runtime_gogo(G
* newg
)
238 #ifdef USING_SPLIT_STACK
239 __splitstack_setcontext(&newg
->stack_context
[0]);
242 newg
->fromgogo
= true;
243 fixcontext(&newg
->context
);
244 setcontext(&newg
->context
);
245 runtime_throw("gogo setcontext returned");
248 // Save context and call fn passing g as a parameter. This is like
249 // setjmp. Because getcontext always returns 0, unlike setjmp, we use
250 // g->fromgogo as a code. It will be true if we got here via
251 // setcontext. g == nil the first time this is called in a new m.
252 void runtime_mcall(void (*)(G
*)) __attribute__ ((noinline
));
254 runtime_mcall(void (*pfn
)(G
*))
259 // Ensure that all registers are on the stack for the garbage
261 __builtin_unwind_init();
266 runtime_throw("runtime: mcall called on m->g0 stack");
270 #ifdef USING_SPLIT_STACK
271 __splitstack_getcontext(&g
->stack_context
[0]);
273 gp
->gcnext_sp
= &pfn
;
275 gp
->fromgogo
= false;
276 getcontext(&gp
->context
);
278 // When we return from getcontext, we may be running
279 // in a new thread. That means that m and g may have
280 // changed. They are global variables so we will
281 // reload them, but the addresses of m and g may be
282 // cached in our local stack frame, and those
283 // addresses may be wrong. Call functions to reload
284 // the values for this thread.
288 if(gp
->traceback
!= nil
)
291 if (gp
== nil
|| !gp
->fromgogo
) {
292 #ifdef USING_SPLIT_STACK
293 __splitstack_setcontext(&mp
->g0
->stack_context
[0]);
295 mp
->g0
->entry
= (byte
*)pfn
;
298 // It's OK to set g directly here because this case
299 // can not occur if we got here via a setcontext to
300 // the getcontext call just above.
303 fixcontext(&mp
->g0
->context
);
304 setcontext(&mp
->g0
->context
);
305 runtime_throw("runtime: mcall function returned");
309 #ifdef HAVE_DL_ITERATE_PHDR
311 // Called via dl_iterate_phdr.
314 addtls(struct dl_phdr_info
* info
, size_t size
__attribute__ ((unused
)), void *data
)
316 size_t *total
= (size_t *)data
;
319 for(i
= 0; i
< info
->dlpi_phnum
; ++i
) {
320 if(info
->dlpi_phdr
[i
].p_type
== PT_TLS
)
321 *total
+= info
->dlpi_phdr
[i
].p_memsz
;
326 // Set the total TLS size.
333 dl_iterate_phdr(addtls
, (void *)&total
);
346 // Goroutine scheduler
347 // The scheduler's job is to distribute ready-to-run goroutines over worker threads.
349 // The main concepts are:
351 // M - worker thread, or machine.
352 // P - processor, a resource that is required to execute Go code.
353 // M must have an associated P to execute Go code, however it can be
354 // blocked or in a syscall w/o an associated P.
356 // Design doc at http://golang.org/s/go11sched.
358 typedef struct Sched Sched
;
363 M
* midle
; // idle m's waiting for work
364 int32 nmidle
; // number of idle m's waiting for work
365 int32 nmidlelocked
; // number of locked m's waiting for work
366 int32 mcount
; // number of m's that have been created
367 int32 maxmcount
; // maximum number of m's allowed (or die)
369 P
* pidle
; // idle P's
373 // Global runnable queue.
378 // Global cache of dead G's.
382 uint32 gcwaiting
; // gc is waiting to run
389 int32 profilehz
; // cpu profiling rate
394 // The max value of GOMAXPROCS.
395 // There are no fundamental restrictions on the value.
396 MaxGomaxprocs
= 1<<8,
398 // Number of goroutine ids to grab from runtime_sched.goidgen to local per-P cache at once.
399 // 16 seems to provide enough amortization, but other than that it's mostly arbitrary number.
404 int32 runtime_gomaxprocs
;
405 uint32 runtime_needextram
= 1;
406 bool runtime_iscgo
= true;
408 G runtime_g0
; // idle goroutine for m0
415 bool runtime_precisestack
;
416 static int32 newprocs
;
418 static Lock allglock
; // the following vars are protected by this lock or by stoptheworld
420 uintptr runtime_allglen
;
421 static uintptr allgcap
;
423 void* runtime_mstart(void*);
424 static void runqput(P
*, G
*);
425 static G
* runqget(P
*);
426 static bool runqputslow(P
*, G
*, uint32
, uint32
);
427 static G
* runqsteal(P
*, P
*);
428 static void mput(M
*);
429 static M
* mget(void);
430 static void mcommoninit(M
*);
431 static void schedule(void);
432 static void procresize(int32
);
433 static void acquirep(P
*);
434 static P
* releasep(void);
435 static void newm(void(*)(void), P
*);
436 static void stopm(void);
437 static void startm(P
*, bool);
438 static void handoffp(P
*);
439 static void wakep(void);
440 static void stoplockedm(void);
441 static void startlockedm(G
*);
442 static void sysmon(void);
443 static uint32
retake(int64
);
444 static void incidlelocked(int32
);
445 static void checkdead(void);
446 static void exitsyscall0(G
*);
447 static void park0(G
*);
448 static void goexit0(G
*);
449 static void gfput(P
*, G
*);
451 static void gfpurge(P
*);
452 static void globrunqput(G
*);
453 static void globrunqputbatch(G
*, G
*, int32
);
454 static G
* globrunqget(P
*, int32
);
455 static P
* pidleget(void);
456 static void pidleput(P
*);
457 static void injectglist(G
*);
458 static bool preemptall(void);
459 static bool exitsyscallfast(void);
460 static void allgadd(G
*);
462 // The bootstrap sequence is:
466 // make & queue new G
467 // call runtime_mstart
469 // The new G calls runtime_main.
471 runtime_schedinit(void)
486 runtime_sched
.maxmcount
= 10000;
487 runtime_precisestack
= 0;
489 runtime_mallocinit();
492 // Initialize the itable value for newErrorCString,
493 // so that the next time it gets called, possibly
494 // in a fault during a garbage collection, it will not
495 // need to allocated memory.
496 runtime_newErrorCString(0, &i
);
500 runtime_parsedebugvars();
502 runtime_sched
.lastpoll
= runtime_nanotime();
504 p
= runtime_getenv("GOMAXPROCS");
505 if(p
!= nil
&& (n
= runtime_atoi(p
)) > 0) {
506 if(n
> MaxGomaxprocs
)
510 runtime_allp
= runtime_malloc((MaxGomaxprocs
+1)*sizeof(runtime_allp
[0]));
513 // Can not enable GC until all roots are registered.
514 // mstats.enablegc = 1;
517 // g->racectx = runtime_raceinit();
520 extern void main_init(void) __asm__ (GOSYM_PREFIX
"__go_init_main");
521 extern void main_main(void) __asm__ (GOSYM_PREFIX
"main.main");
524 initDone(void *arg
__attribute__ ((unused
))) {
525 runtime_unlockOSThread();
528 // The main goroutine.
530 runtime_main(void* dummy
__attribute__((unused
)))
537 // Lock the main goroutine onto this, the main OS thread,
538 // during initialization. Most programs won't care, but a few
539 // do require certain calls to be made by the main thread.
540 // Those can arrange for main.main to run in the main thread
541 // by calling runtime.LockOSThread during initialization
542 // to preserve the lock.
543 runtime_lockOSThread();
545 // Defer unlock so that runtime.Goexit during init does the unlock too.
549 d
.__panic
= g
->panic
;
551 d
.__makefunc_can_recover
= 0;
557 runtime_throw("runtime_main not on m0");
558 __go_go(runtime_MHeap_Scavenger
, nil
);
561 if(g
->defer
!= &d
|| d
.__pfn
!= initDone
)
562 runtime_throw("runtime: bad defer entry after init");
564 runtime_unlockOSThread();
566 // For gccgo we have to wait until after main is initialized
567 // to enable GC, because initializing main registers the GC
575 // Make racy client program work: if panicking on
576 // another goroutine at the same time as main returns,
577 // let the other goroutine finish printing the panic trace.
578 // Once it does, it will exit. See issue 3934.
579 if(runtime_panicking
)
580 runtime_park(nil
, nil
, "panicwait");
588 runtime_goroutineheader(G
*gp
)
608 status
= gp
->waitreason
;
617 // approx time the G is blocked, in minutes
619 if((gp
->status
== Gwaiting
|| gp
->status
== Gsyscall
) && gp
->waitsince
!= 0)
620 waitfor
= (runtime_nanotime() - gp
->waitsince
) / (60LL*1000*1000*1000);
623 runtime_printf("goroutine %D [%s]:\n", gp
->goid
, status
);
625 runtime_printf("goroutine %D [%s, %D minutes]:\n", gp
->goid
, status
, waitfor
);
629 runtime_printcreatedby(G
*g
)
631 if(g
!= nil
&& g
->gopc
!= 0 && g
->goid
!= 1) {
636 if(__go_file_line(g
->gopc
- 1, &fn
, &file
, &line
)) {
637 runtime_printf("created by %S\n", fn
);
638 runtime_printf("\t%S:%D\n", file
, (int64
) line
);
646 Location locbuf
[TracebackMaxFrames
];
651 runtime_tracebackothers(G
* volatile me
)
659 traceback
= runtime_gotraceback(nil
);
661 // Show the current goroutine first, if we haven't already.
662 if((gp
= m
->curg
) != nil
&& gp
!= me
) {
663 runtime_printf("\n");
664 runtime_goroutineheader(gp
);
667 #ifdef USING_SPLIT_STACK
668 __splitstack_getcontext(&me
->stack_context
[0]);
670 getcontext(&me
->context
);
672 if(gp
->traceback
!= nil
) {
676 runtime_printtrace(tb
.locbuf
, tb
.c
, false);
677 runtime_printcreatedby(gp
);
680 runtime_lock(&allglock
);
681 for(i
= 0; i
< runtime_allglen
; i
++) {
682 gp
= runtime_allg
[i
];
683 if(gp
== me
|| gp
== m
->curg
|| gp
->status
== Gdead
)
685 if(gp
->issystem
&& traceback
< 2)
687 runtime_printf("\n");
688 runtime_goroutineheader(gp
);
690 // Our only mechanism for doing a stack trace is
691 // _Unwind_Backtrace. And that only works for the
692 // current thread, not for other random goroutines.
693 // So we need to switch context to the goroutine, get
694 // the backtrace, and then switch back.
696 // This means that if g is running or in a syscall, we
697 // can't reliably print a stack trace. FIXME.
699 if(gp
->status
== Grunning
) {
700 runtime_printf("\tgoroutine running on other thread; stack unavailable\n");
701 runtime_printcreatedby(gp
);
702 } else if(gp
->status
== Gsyscall
) {
703 runtime_printf("\tgoroutine in C code; stack unavailable\n");
704 runtime_printcreatedby(gp
);
708 #ifdef USING_SPLIT_STACK
709 __splitstack_getcontext(&me
->stack_context
[0]);
711 getcontext(&me
->context
);
713 if(gp
->traceback
!= nil
) {
717 runtime_printtrace(tb
.locbuf
, tb
.c
, false);
718 runtime_printcreatedby(gp
);
721 runtime_unlock(&allglock
);
727 // sched lock is held
728 if(runtime_sched
.mcount
> runtime_sched
.maxmcount
) {
729 runtime_printf("runtime: program exceeds %d-thread limit\n", runtime_sched
.maxmcount
);
730 runtime_throw("thread exhaustion");
734 // Do a stack trace of gp, and then restore the context to
740 Traceback
* traceback
;
742 traceback
= gp
->traceback
;
744 traceback
->c
= runtime_callers(1, traceback
->locbuf
,
745 sizeof traceback
->locbuf
/ sizeof traceback
->locbuf
[0]);
746 runtime_gogo(traceback
->gp
);
752 // If there is no mcache runtime_callers() will crash,
753 // and we are most likely in sysmon thread so the stack is senseless anyway.
755 runtime_callers(1, mp
->createstack
, nelem(mp
->createstack
));
757 mp
->fastrand
= 0x49f6428aUL
+ mp
->id
+ runtime_cputicks();
759 runtime_lock(&runtime_sched
);
760 mp
->id
= runtime_sched
.mcount
++;
762 runtime_mpreinit(mp
);
764 // Add to runtime_allm so garbage collector doesn't free m
765 // when it is just in a register or thread-local storage.
766 mp
->alllink
= runtime_allm
;
767 // runtime_NumCgoCall() iterates over allm w/o schedlock,
768 // so we need to publish it safely.
769 runtime_atomicstorep(&runtime_allm
, mp
);
770 runtime_unlock(&runtime_sched
);
773 // Mark gp ready to run.
778 m
->locks
++; // disable preemption because it can be holding p in a local var
779 if(gp
->status
!= Gwaiting
) {
780 runtime_printf("goroutine %D has status %d\n", gp
->goid
, gp
->status
);
781 runtime_throw("bad g->status in ready");
783 gp
->status
= Grunnable
;
785 if(runtime_atomicload(&runtime_sched
.npidle
) != 0 && runtime_atomicload(&runtime_sched
.nmspinning
) == 0) // TODO: fast atomic
791 runtime_gcprocs(void)
795 // Figure out how many CPUs to use during GC.
796 // Limited by gomaxprocs, number of actual CPUs, and MaxGcproc.
797 runtime_lock(&runtime_sched
);
798 n
= runtime_gomaxprocs
;
800 n
= runtime_ncpu
> 0 ? runtime_ncpu
: 1;
803 if(n
> runtime_sched
.nmidle
+1) // one M is currently running
804 n
= runtime_sched
.nmidle
+1;
805 runtime_unlock(&runtime_sched
);
814 runtime_lock(&runtime_sched
);
815 n
= runtime_gomaxprocs
;
820 n
-= runtime_sched
.nmidle
+1; // one M is currently running
821 runtime_unlock(&runtime_sched
);
826 runtime_helpgc(int32 nproc
)
831 runtime_lock(&runtime_sched
);
833 for(n
= 1; n
< nproc
; n
++) { // one M is currently running
834 if(runtime_allp
[pos
]->mcache
== m
->mcache
)
838 runtime_throw("runtime_gcprocs inconsistency");
840 mp
->mcache
= runtime_allp
[pos
]->mcache
;
842 runtime_notewakeup(&mp
->park
);
844 runtime_unlock(&runtime_sched
);
847 // Similar to stoptheworld but best-effort and can be called several times.
848 // There is no reverse operation, used during crashing.
849 // This function must not lock any mutexes.
851 runtime_freezetheworld(void)
855 if(runtime_gomaxprocs
== 1)
857 // stopwait and preemption requests can be lost
858 // due to races with concurrently executing threads,
859 // so try several times
860 for(i
= 0; i
< 5; i
++) {
861 // this should tell the scheduler to not start any new goroutines
862 runtime_sched
.stopwait
= 0x7fffffff;
863 runtime_atomicstore((uint32
*)&runtime_sched
.gcwaiting
, 1);
864 // this should stop running goroutines
866 break; // no running goroutines
867 runtime_usleep(1000);
870 runtime_usleep(1000);
872 runtime_usleep(1000);
876 runtime_stoptheworld(void)
883 runtime_lock(&runtime_sched
);
884 runtime_sched
.stopwait
= runtime_gomaxprocs
;
885 runtime_atomicstore((uint32
*)&runtime_sched
.gcwaiting
, 1);
888 m
->p
->status
= Pgcstop
;
889 runtime_sched
.stopwait
--;
890 // try to retake all P's in Psyscall status
891 for(i
= 0; i
< runtime_gomaxprocs
; i
++) {
894 if(s
== Psyscall
&& runtime_cas(&p
->status
, s
, Pgcstop
))
895 runtime_sched
.stopwait
--;
898 while((p
= pidleget()) != nil
) {
900 runtime_sched
.stopwait
--;
902 wait
= runtime_sched
.stopwait
> 0;
903 runtime_unlock(&runtime_sched
);
905 // wait for remaining P's to stop voluntarily
907 runtime_notesleep(&runtime_sched
.stopnote
);
908 runtime_noteclear(&runtime_sched
.stopnote
);
910 if(runtime_sched
.stopwait
)
911 runtime_throw("stoptheworld: not stopped");
912 for(i
= 0; i
< runtime_gomaxprocs
; i
++) {
914 if(p
->status
!= Pgcstop
)
915 runtime_throw("stoptheworld: not stopped");
926 runtime_starttheworld(void)
933 m
->locks
++; // disable preemption because it can be holding p in a local var
934 gp
= runtime_netpoll(false); // non-blocking
936 add
= needaddgcproc();
937 runtime_lock(&runtime_sched
);
939 procresize(newprocs
);
942 procresize(runtime_gomaxprocs
);
943 runtime_sched
.gcwaiting
= 0;
946 while((p
= pidleget()) != nil
) {
947 // procresize() puts p's with work at the beginning of the list.
948 // Once we reach a p without a run queue, the rest don't have one either.
949 if(p
->runqhead
== p
->runqtail
) {
957 if(runtime_sched
.sysmonwait
) {
958 runtime_sched
.sysmonwait
= false;
959 runtime_notewakeup(&runtime_sched
.sysmonnote
);
961 runtime_unlock(&runtime_sched
);
970 runtime_throw("starttheworld: inconsistent mp->nextp");
972 runtime_notewakeup(&mp
->park
);
974 // Start M to run P. Do not start another M below.
981 // If GC could have used another helper proc, start one now,
982 // in the hope that it will be available next time.
983 // It would have been even better to start it before the collection,
984 // but doing so requires allocating memory, so it's tricky to
985 // coordinate. This lazy approach works out in practice:
986 // we don't mind if the first couple gc rounds don't have quite
987 // the maximum number of procs.
993 // Called to start an M.
995 runtime_mstart(void* mp
)
1005 // Record top of stack for use by mcall.
1006 // Once we call schedule we're never coming back,
1007 // so other calls can reuse this stack space.
1008 #ifdef USING_SPLIT_STACK
1009 __splitstack_getcontext(&g
->stack_context
[0]);
1011 g
->gcinitial_sp
= &mp
;
1012 // Setting gcstack_size to 0 is a marker meaning that gcinitial_sp
1013 // is the top of the stack, not the bottom.
1014 g
->gcstack_size
= 0;
1017 getcontext(&g
->context
);
1019 if(g
->entry
!= nil
) {
1020 // Got here from mcall.
1021 void (*pfn
)(G
*) = (void (*)(G
*))g
->entry
;
1022 G
* gp
= (G
*)g
->param
;
1028 #ifdef USING_SPLIT_STACK
1030 int dont_block_signals
= 0;
1031 __splitstack_block_signals(&dont_block_signals
, nil
);
1035 // Install signal handlers; after minit so that minit can
1036 // prepare the thread to be able to handle the signals.
1037 if(m
== &runtime_m0
)
1046 } else if(m
!= &runtime_m0
) {
1052 // TODO(brainman): This point is never reached, because scheduler
1053 // does not release os threads at the moment. But once this path
1054 // is enabled, we must remove our seh here.
1059 typedef struct CgoThreadStart CgoThreadStart
;
1060 struct CgoThreadStart
1068 // Allocate a new m unassociated with any thread.
1069 // Can use p for allocation context if needed.
1071 runtime_allocm(P
*p
, int32 stacksize
, byte
** ret_g0_stack
, size_t* ret_g0_stacksize
)
1075 m
->locks
++; // disable GC because it can be called from sysmon
1077 acquirep(p
); // temporarily borrow p for mallocs in this function
1081 runtime_gc_m_ptr(&e
);
1082 mtype
= ((const PtrType
*)e
.__type_descriptor
)->__element_type
;
1086 mp
= runtime_mal(sizeof *mp
);
1088 mp
->g0
= runtime_malg(stacksize
, ret_g0_stack
, ret_g0_stacksize
);
1097 static M
* lockextra(bool nilokay
);
1098 static void unlockextra(M
*);
1100 // needm is called when a cgo callback happens on a
1101 // thread without an m (a thread not created by Go).
1102 // In this case, needm is expected to find an m to use
1103 // and return with m, g initialized correctly.
1104 // Since m and g are not set now (likely nil, but see below)
1105 // needm is limited in what routines it can call. In particular
1106 // it can only call nosplit functions (textflag 7) and cannot
1107 // do any scheduling that requires an m.
1109 // In order to avoid needing heavy lifting here, we adopt
1110 // the following strategy: there is a stack of available m's
1111 // that can be stolen. Using compare-and-swap
1112 // to pop from the stack has ABA races, so we simulate
1113 // a lock by doing an exchange (via casp) to steal the stack
1114 // head and replace the top pointer with MLOCKED (1).
1115 // This serves as a simple spin lock that we can use even
1116 // without an m. The thread that locks the stack in this way
1117 // unlocks the stack by storing a valid stack head pointer.
1119 // In order to make sure that there is always an m structure
1120 // available to be stolen, we maintain the invariant that there
1121 // is always one more than needed. At the beginning of the
1122 // program (if cgo is in use) the list is seeded with a single m.
1123 // If needm finds that it has taken the last m off the list, its job
1124 // is - once it has installed its own m so that it can do things like
1125 // allocate memory - to create a spare m and put it on the list.
1127 // Each of these extra m's also has a g0 and a curg that are
1128 // pressed into service as the scheduling stack and current
1129 // goroutine for the duration of the cgo callback.
1131 // When the callback is done with the m, it calls dropm to
1132 // put the m back on the list.
1134 // Unlike the gc toolchain, we start running on curg, since we are
1135 // just going to return and let the caller continue.
1141 if(runtime_needextram
) {
1142 // Can happen if C/C++ code calls Go from a global ctor.
1143 // Can not throw, because scheduler is not initialized yet.
1144 int rv
__attribute__((unused
));
1145 rv
= runtime_write(2, "fatal error: cgo callback before cgo call\n",
1146 sizeof("fatal error: cgo callback before cgo call\n")-1);
1150 // Lock extra list, take head, unlock popped list.
1151 // nilokay=false is safe here because of the invariant above,
1152 // that the extra list always contains or will soon contain
1154 mp
= lockextra(false);
1156 // Set needextram when we've just emptied the list,
1157 // so that the eventual call into cgocallbackg will
1158 // allocate a new m for the extra list. We delay the
1159 // allocation until then so that it can be done
1160 // after exitsyscall makes sure it is okay to be
1161 // running at all (that is, there's no garbage collection
1162 // running right now).
1163 mp
->needextram
= mp
->schedlink
== nil
;
1164 unlockextra(mp
->schedlink
);
1166 // Install m and g (= m->curg).
1167 runtime_setmg(mp
, mp
->curg
);
1169 // Initialize g's context as in mstart.
1171 g
->status
= Gsyscall
;
1174 #ifdef USING_SPLIT_STACK
1175 __splitstack_getcontext(&g
->stack_context
[0]);
1177 g
->gcinitial_sp
= &mp
;
1178 g
->gcstack_size
= 0;
1181 getcontext(&g
->context
);
1183 if(g
->entry
!= nil
) {
1184 // Got here from mcall.
1185 void (*pfn
)(G
*) = (void (*)(G
*))g
->entry
;
1186 G
* gp
= (G
*)g
->param
;
1191 // Initialize this thread to use the m.
1194 #ifdef USING_SPLIT_STACK
1196 int dont_block_signals
= 0;
1197 __splitstack_block_signals(&dont_block_signals
, nil
);
1202 // newextram allocates an m and puts it on the extra list.
1203 // It is called with a working local m, so that it can do things
1204 // like call schedlock and allocate.
1206 runtime_newextram(void)
1211 size_t g0_spsize
, spsize
;
1213 // Create extra goroutine locked to extra m.
1214 // The goroutine is the context in which the cgo callback will run.
1215 // The sched.pc will never be returned to, but setting it to
1216 // runtime.goexit makes clear to the traceback routines where
1217 // the goroutine stack ends.
1218 mp
= runtime_allocm(nil
, StackMin
, &g0_sp
, &g0_spsize
);
1219 gp
= runtime_malg(StackMin
, &sp
, &spsize
);
1222 mp
->locked
= LockInternal
;
1225 gp
->goid
= runtime_xadd64(&runtime_sched
.goidgen
, 1);
1226 // put on allg for garbage collector
1229 // The context for gp will be set up in runtime_needm. But
1230 // here we need to set up the context for g0.
1231 getcontext(&mp
->g0
->context
);
1232 mp
->g0
->context
.uc_stack
.ss_sp
= g0_sp
;
1233 mp
->g0
->context
.uc_stack
.ss_size
= g0_spsize
;
1234 makecontext(&mp
->g0
->context
, kickoff
, 0);
1236 // Add m to the extra list.
1237 mnext
= lockextra(true);
1238 mp
->schedlink
= mnext
;
1242 // dropm is called when a cgo callback has called needm but is now
1243 // done with the callback and returning back into the non-Go thread.
1244 // It puts the current m back onto the extra list.
1246 // The main expense here is the call to signalstack to release the
1247 // m's signal stack, and then the call to needm on the next callback
1248 // from this thread. It is tempting to try to save the m for next time,
1249 // which would eliminate both these costs, but there might not be
1250 // a next time: the current thread (which Go does not control) might exit.
1251 // If we saved the m for that thread, there would be an m leak each time
1252 // such a thread exited. Instead, we acquire and release an m on each
1253 // call. These should typically not be scheduling operations, just a few
1254 // atomics, so the cost should be small.
1256 // TODO(rsc): An alternative would be to allocate a dummy pthread per-thread
1257 // variable using pthread_key_create. Unlike the pthread keys we already use
1258 // on OS X, this dummy key would never be read by Go code. It would exist
1259 // only so that we could register at thread-exit-time destructor.
1260 // That destructor would put the m back onto the extra list.
1261 // This is purely a performance optimization. The current version,
1262 // in which dropm happens on each cgo call, is still correct too.
1263 // We may have to keep the current version on systems with cgo
1264 // but without pthreads, like Windows.
1270 // Undo whatever initialization minit did during needm.
1273 // Clear m and g, and return m to the extra list.
1274 // After the call to setmg we can only call nosplit functions.
1276 runtime_setmg(nil
, nil
);
1278 mp
->curg
->status
= Gdead
;
1280 mnext
= lockextra(true);
1281 mp
->schedlink
= mnext
;
1285 #define MLOCKED ((M*)1)
1287 // lockextra locks the extra list and returns the list head.
1288 // The caller must unlock the list by storing a new list head
1289 // to runtime.extram. If nilokay is true, then lockextra will
1290 // return a nil list head if that's what it finds. If nilokay is false,
1291 // lockextra will keep waiting until the list head is no longer nil.
1293 lockextra(bool nilokay
)
1296 void (*yield
)(void);
1299 mp
= runtime_atomicloadp(&runtime_extram
);
1301 yield
= runtime_osyield
;
1305 if(mp
== nil
&& !nilokay
) {
1309 if(!runtime_casp(&runtime_extram
, mp
, MLOCKED
)) {
1310 yield
= runtime_osyield
;
1322 runtime_atomicstorep(&runtime_extram
, mp
);
1332 mp
= runtime_atomicloadp(&runtime_extram
);
1337 if(!runtime_casp(&runtime_extram
, mp
, MLOCKED
)) {
1342 for(mc
= mp
; mc
!= nil
; mc
= mc
->schedlink
)
1344 runtime_atomicstorep(&runtime_extram
, mp
);
1349 // Create a new m. It will start off with a call to fn, or else the scheduler.
1351 newm(void(*fn
)(void), P
*p
)
1355 mp
= runtime_allocm(p
, -1, nil
, nil
);
1359 runtime_newosproc(mp
);
1362 // Stops execution of the current m until new work is available.
1363 // Returns with acquired P.
1368 runtime_throw("stopm holding locks");
1370 runtime_throw("stopm holding p");
1372 m
->spinning
= false;
1373 runtime_xadd(&runtime_sched
.nmspinning
, -1);
1377 runtime_lock(&runtime_sched
);
1379 runtime_unlock(&runtime_sched
);
1380 runtime_notesleep(&m
->park
);
1381 runtime_noteclear(&m
->park
);
1398 // Schedules some M to run the p (creates an M if necessary).
1399 // If p==nil, tries to get an idle P, if no idle P's does nothing.
1401 startm(P
*p
, bool spinning
)
1406 runtime_lock(&runtime_sched
);
1410 runtime_unlock(&runtime_sched
);
1412 runtime_xadd(&runtime_sched
.nmspinning
, -1);
1417 runtime_unlock(&runtime_sched
);
1426 runtime_throw("startm: m is spinning");
1428 runtime_throw("startm: m has p");
1429 mp
->spinning
= spinning
;
1431 runtime_notewakeup(&mp
->park
);
1434 // Hands off P from syscall or locked M.
1438 // if it has local work, start it straight away
1439 if(p
->runqhead
!= p
->runqtail
|| runtime_sched
.runqsize
) {
1443 // no local work, check that there are no spinning/idle M's,
1444 // otherwise our help is not required
1445 if(runtime_atomicload(&runtime_sched
.nmspinning
) + runtime_atomicload(&runtime_sched
.npidle
) == 0 && // TODO: fast atomic
1446 runtime_cas(&runtime_sched
.nmspinning
, 0, 1)) {
1450 runtime_lock(&runtime_sched
);
1451 if(runtime_sched
.gcwaiting
) {
1452 p
->status
= Pgcstop
;
1453 if(--runtime_sched
.stopwait
== 0)
1454 runtime_notewakeup(&runtime_sched
.stopnote
);
1455 runtime_unlock(&runtime_sched
);
1458 if(runtime_sched
.runqsize
) {
1459 runtime_unlock(&runtime_sched
);
1463 // If this is the last running P and nobody is polling network,
1464 // need to wakeup another M to poll network.
1465 if(runtime_sched
.npidle
== (uint32
)runtime_gomaxprocs
-1 && runtime_atomicload64(&runtime_sched
.lastpoll
) != 0) {
1466 runtime_unlock(&runtime_sched
);
1471 runtime_unlock(&runtime_sched
);
1474 // Tries to add one more P to execute G's.
1475 // Called when a G is made runnable (newproc, ready).
1479 // be conservative about spinning threads
1480 if(!runtime_cas(&runtime_sched
.nmspinning
, 0, 1))
1485 // Stops execution of the current m that is locked to a g until the g is runnable again.
1486 // Returns with acquired P.
1492 if(m
->lockedg
== nil
|| m
->lockedg
->lockedm
!= m
)
1493 runtime_throw("stoplockedm: inconsistent locking");
1495 // Schedule another M to run this p.
1500 // Wait until another thread schedules lockedg again.
1501 runtime_notesleep(&m
->park
);
1502 runtime_noteclear(&m
->park
);
1503 if(m
->lockedg
->status
!= Grunnable
)
1504 runtime_throw("stoplockedm: not runnable");
1509 // Schedules the locked m to run the locked gp.
1518 runtime_throw("startlockedm: locked to me");
1520 runtime_throw("startlockedm: m has p");
1521 // directly handoff current P to the locked m
1525 runtime_notewakeup(&mp
->park
);
1529 // Stops the current m for stoptheworld.
1530 // Returns when the world is restarted.
1536 if(!runtime_sched
.gcwaiting
)
1537 runtime_throw("gcstopm: not waiting for gc");
1539 m
->spinning
= false;
1540 runtime_xadd(&runtime_sched
.nmspinning
, -1);
1543 runtime_lock(&runtime_sched
);
1544 p
->status
= Pgcstop
;
1545 if(--runtime_sched
.stopwait
== 0)
1546 runtime_notewakeup(&runtime_sched
.stopnote
);
1547 runtime_unlock(&runtime_sched
);
1551 // Schedules gp to run on the current M.
1558 if(gp
->status
!= Grunnable
) {
1559 runtime_printf("execute: bad g status %d\n", gp
->status
);
1560 runtime_throw("execute: bad g status");
1562 gp
->status
= Grunning
;
1568 // Check whether the profiler needs to be turned on or off.
1569 hz
= runtime_sched
.profilehz
;
1570 if(m
->profilehz
!= hz
)
1571 runtime_resetcpuprofiler(hz
);
1576 // Finds a runnable goroutine to execute.
1577 // Tries to steal from other P's, get g from global queue, poll network.
1586 if(runtime_sched
.gcwaiting
) {
1595 if(runtime_sched
.runqsize
) {
1596 runtime_lock(&runtime_sched
);
1597 gp
= globrunqget(m
->p
, 0);
1598 runtime_unlock(&runtime_sched
);
1603 gp
= runtime_netpoll(false); // non-blocking
1605 injectglist(gp
->schedlink
);
1606 gp
->status
= Grunnable
;
1609 // If number of spinning M's >= number of busy P's, block.
1610 // This is necessary to prevent excessive CPU consumption
1611 // when GOMAXPROCS>>1 but the program parallelism is low.
1612 if(!m
->spinning
&& 2 * runtime_atomicload(&runtime_sched
.nmspinning
) >= runtime_gomaxprocs
- runtime_atomicload(&runtime_sched
.npidle
)) // TODO: fast atomic
1616 runtime_xadd(&runtime_sched
.nmspinning
, 1);
1618 // random steal from other P's
1619 for(i
= 0; i
< 2*runtime_gomaxprocs
; i
++) {
1620 if(runtime_sched
.gcwaiting
)
1622 p
= runtime_allp
[runtime_fastrand1()%runtime_gomaxprocs
];
1626 gp
= runqsteal(m
->p
, p
);
1631 // return P and block
1632 runtime_lock(&runtime_sched
);
1633 if(runtime_sched
.gcwaiting
) {
1634 runtime_unlock(&runtime_sched
);
1637 if(runtime_sched
.runqsize
) {
1638 gp
= globrunqget(m
->p
, 0);
1639 runtime_unlock(&runtime_sched
);
1644 runtime_unlock(&runtime_sched
);
1646 m
->spinning
= false;
1647 runtime_xadd(&runtime_sched
.nmspinning
, -1);
1649 // check all runqueues once again
1650 for(i
= 0; i
< runtime_gomaxprocs
; i
++) {
1651 p
= runtime_allp
[i
];
1652 if(p
&& p
->runqhead
!= p
->runqtail
) {
1653 runtime_lock(&runtime_sched
);
1655 runtime_unlock(&runtime_sched
);
1664 if(runtime_xchg64(&runtime_sched
.lastpoll
, 0) != 0) {
1666 runtime_throw("findrunnable: netpoll with p");
1668 runtime_throw("findrunnable: netpoll with spinning");
1669 gp
= runtime_netpoll(true); // block until new work is available
1670 runtime_atomicstore64(&runtime_sched
.lastpoll
, runtime_nanotime());
1672 runtime_lock(&runtime_sched
);
1674 runtime_unlock(&runtime_sched
);
1677 injectglist(gp
->schedlink
);
1678 gp
->status
= Grunnable
;
1694 m
->spinning
= false;
1695 nmspinning
= runtime_xadd(&runtime_sched
.nmspinning
, -1);
1697 runtime_throw("findrunnable: negative nmspinning");
1699 nmspinning
= runtime_atomicload(&runtime_sched
.nmspinning
);
1701 // M wakeup policy is deliberately somewhat conservative (see nmspinning handling),
1702 // so see if we need to wakeup another P here.
1703 if (nmspinning
== 0 && runtime_atomicload(&runtime_sched
.npidle
) > 0)
1707 // Injects the list of runnable G's into the scheduler.
1708 // Can run concurrently with GC.
1710 injectglist(G
*glist
)
1717 runtime_lock(&runtime_sched
);
1718 for(n
= 0; glist
; n
++) {
1720 glist
= gp
->schedlink
;
1721 gp
->status
= Grunnable
;
1724 runtime_unlock(&runtime_sched
);
1726 for(; n
&& runtime_sched
.npidle
; n
--)
1730 // One round of scheduler: find a runnable goroutine and execute it.
1739 runtime_throw("schedule: holding locks");
1742 if(runtime_sched
.gcwaiting
) {
1748 // Check the global runnable queue once in a while to ensure fairness.
1749 // Otherwise two goroutines can completely occupy the local runqueue
1750 // by constantly respawning each other.
1751 tick
= m
->p
->schedtick
;
1752 // This is a fancy way to say tick%61==0,
1753 // it uses 2 MUL instructions instead of a single DIV and so is faster on modern processors.
1754 if(tick
- (((uint64
)tick
*0x4325c53fu
)>>36)*61 == 0 && runtime_sched
.runqsize
> 0) {
1755 runtime_lock(&runtime_sched
);
1756 gp
= globrunqget(m
->p
, 1);
1757 runtime_unlock(&runtime_sched
);
1763 if(gp
&& m
->spinning
)
1764 runtime_throw("schedule: spinning with local work");
1767 gp
= findrunnable(); // blocks until work is available
1772 // Hands off own p to the locked m,
1773 // then blocks waiting for a new p.
1781 // Puts the current goroutine into a waiting state and calls unlockf.
1782 // If unlockf returns false, the goroutine is resumed.
1784 runtime_park(bool(*unlockf
)(G
*, void*), void *lock
, const char *reason
)
1787 m
->waitunlockf
= unlockf
;
1788 g
->waitreason
= reason
;
1789 runtime_mcall(park0
);
1793 parkunlock(G
*gp
, void *lock
)
1796 runtime_unlock(lock
);
1800 // Puts the current goroutine into a waiting state and unlocks the lock.
1801 // The goroutine can be made runnable again by calling runtime_ready(gp).
1803 runtime_parkunlock(Lock
*lock
, const char *reason
)
1805 runtime_park(parkunlock
, lock
, reason
);
1808 // runtime_park continuation on g0.
1814 gp
->status
= Gwaiting
;
1817 if(m
->waitunlockf
) {
1818 ok
= m
->waitunlockf(gp
, m
->waitlock
);
1819 m
->waitunlockf
= nil
;
1822 gp
->status
= Grunnable
;
1823 execute(gp
); // Schedule it back, never returns.
1828 execute(gp
); // Never returns.
1835 runtime_gosched(void)
1837 runtime_mcall(runtime_gosched0
);
1840 // runtime_gosched continuation on g0.
1842 runtime_gosched0(G
*gp
)
1844 gp
->status
= Grunnable
;
1847 runtime_lock(&runtime_sched
);
1849 runtime_unlock(&runtime_sched
);
1852 execute(gp
); // Never returns.
1857 // Finishes execution of the current goroutine.
1858 // Need to mark it as nosplit, because it runs with sp > stackbase (as runtime_lessstack).
1859 // Since it does not return it does not matter. But if it is preempted
1860 // at the split stack check, GC will complain about inconsistent sp.
1862 runtime_goexit(void)
1865 runtime_racegoend();
1866 runtime_mcall(goexit0
);
1869 // runtime_goexit continuation on g0.
1879 if(m
->locked
& ~LockExternal
) {
1880 runtime_printf("invalid m->locked = %d\n", m
->locked
);
1881 runtime_throw("internal lockOSThread error");
1888 // The goroutine g is about to enter a system call.
1889 // Record that it's not using the cpu anymore.
1890 // This is called only from the go syscall library and cgocall,
1891 // not from the low-level system calls used by the runtime.
1893 // Entersyscall cannot split the stack: the runtime_gosave must
1894 // make g->sched refer to the caller's stack segment, because
1895 // entersyscall is going to return immediately after.
1897 void runtime_entersyscall(void) __attribute__ ((no_split_stack
));
1898 static void doentersyscall(void) __attribute__ ((no_split_stack
, noinline
));
1901 runtime_entersyscall()
1903 // Save the registers in the g structure so that any pointers
1904 // held in registers will be seen by the garbage collector.
1905 getcontext(&g
->gcregs
);
1907 // Do the work in a separate function, so that this function
1908 // doesn't save any registers on its own stack. If this
1909 // function does save any registers, we might store the wrong
1910 // value in the call to getcontext.
1912 // FIXME: This assumes that we do not need to save any
1913 // callee-saved registers to access the TLS variable g. We
1914 // don't want to put the ucontext_t on the stack because it is
1915 // large and we can not split the stack here.
1922 // Disable preemption because during this function g is in Gsyscall status,
1923 // but can have inconsistent g->sched, do not let GC observe it.
1926 // Leave SP around for GC and traceback.
1927 #ifdef USING_SPLIT_STACK
1928 g
->gcstack
= __splitstack_find(nil
, nil
, &g
->gcstack_size
,
1929 &g
->gcnext_segment
, &g
->gcnext_sp
,
1935 g
->gcnext_sp
= (byte
*) &v
;
1939 g
->status
= Gsyscall
;
1941 if(runtime_atomicload(&runtime_sched
.sysmonwait
)) { // TODO: fast atomic
1942 runtime_lock(&runtime_sched
);
1943 if(runtime_atomicload(&runtime_sched
.sysmonwait
)) {
1944 runtime_atomicstore(&runtime_sched
.sysmonwait
, 0);
1945 runtime_notewakeup(&runtime_sched
.sysmonnote
);
1947 runtime_unlock(&runtime_sched
);
1952 runtime_atomicstore(&m
->p
->status
, Psyscall
);
1953 if(runtime_sched
.gcwaiting
) {
1954 runtime_lock(&runtime_sched
);
1955 if (runtime_sched
.stopwait
> 0 && runtime_cas(&m
->p
->status
, Psyscall
, Pgcstop
)) {
1956 if(--runtime_sched
.stopwait
== 0)
1957 runtime_notewakeup(&runtime_sched
.stopnote
);
1959 runtime_unlock(&runtime_sched
);
1965 // The same as runtime_entersyscall(), but with a hint that the syscall is blocking.
1967 runtime_entersyscallblock(void)
1971 m
->locks
++; // see comment in entersyscall
1973 // Leave SP around for GC and traceback.
1974 #ifdef USING_SPLIT_STACK
1975 g
->gcstack
= __splitstack_find(nil
, nil
, &g
->gcstack_size
,
1976 &g
->gcnext_segment
, &g
->gcnext_sp
,
1979 g
->gcnext_sp
= (byte
*) &p
;
1982 // Save the registers in the g structure so that any pointers
1983 // held in registers will be seen by the garbage collector.
1984 getcontext(&g
->gcregs
);
1986 g
->status
= Gsyscall
;
1990 if(g
->isbackground
) // do not consider blocked scavenger for deadlock detection
1996 // The goroutine g exited its system call.
1997 // Arrange for it to run on a cpu again.
1998 // This is called only from the go syscall library, not
1999 // from the low-level system calls used by the runtime.
2001 runtime_exitsyscall(void)
2005 m
->locks
++; // see comment in entersyscall
2008 if(gp
->isbackground
) // do not consider blocked scavenger for deadlock detection
2012 if(exitsyscallfast()) {
2013 // There's a cpu for us, so we can run.
2014 m
->p
->syscalltick
++;
2015 gp
->status
= Grunning
;
2016 // Garbage collector isn't running (since we are),
2017 // so okay to clear gcstack and gcsp.
2018 #ifdef USING_SPLIT_STACK
2021 gp
->gcnext_sp
= nil
;
2022 runtime_memclr(&gp
->gcregs
, sizeof gp
->gcregs
);
2029 // Call the scheduler.
2030 runtime_mcall(exitsyscall0
);
2032 // Scheduler returned, so we're allowed to run now.
2033 // Delete the gcstack information that we left for
2034 // the garbage collector during the system call.
2035 // Must wait until now because until gosched returns
2036 // we don't know for sure that the garbage collector
2038 #ifdef USING_SPLIT_STACK
2041 gp
->gcnext_sp
= nil
;
2042 runtime_memclr(&gp
->gcregs
, sizeof gp
->gcregs
);
2044 // Don't refer to m again, we might be running on a different
2045 // thread after returning from runtime_mcall.
2046 runtime_m()->p
->syscalltick
++;
2050 exitsyscallfast(void)
2054 // Freezetheworld sets stopwait but does not retake P's.
2055 if(runtime_sched
.stopwait
) {
2060 // Try to re-acquire the last P.
2061 if(m
->p
&& m
->p
->status
== Psyscall
&& runtime_cas(&m
->p
->status
, Psyscall
, Prunning
)) {
2062 // There's a cpu for us, so we can run.
2063 m
->mcache
= m
->p
->mcache
;
2067 // Try to get any other idle P.
2069 if(runtime_sched
.pidle
) {
2070 runtime_lock(&runtime_sched
);
2072 if(p
&& runtime_atomicload(&runtime_sched
.sysmonwait
)) {
2073 runtime_atomicstore(&runtime_sched
.sysmonwait
, 0);
2074 runtime_notewakeup(&runtime_sched
.sysmonnote
);
2076 runtime_unlock(&runtime_sched
);
2085 // runtime_exitsyscall slow path on g0.
2086 // Failed to acquire P, enqueue gp as runnable.
2092 gp
->status
= Grunnable
;
2095 runtime_lock(&runtime_sched
);
2099 else if(runtime_atomicload(&runtime_sched
.sysmonwait
)) {
2100 runtime_atomicstore(&runtime_sched
.sysmonwait
, 0);
2101 runtime_notewakeup(&runtime_sched
.sysmonnote
);
2103 runtime_unlock(&runtime_sched
);
2106 execute(gp
); // Never returns.
2109 // Wait until another thread schedules gp and so m again.
2111 execute(gp
); // Never returns.
2114 schedule(); // Never returns.
2117 // Called from syscall package before fork.
2118 void syscall_runtime_BeforeFork(void)
2119 __asm__(GOSYM_PREFIX
"syscall.runtime_BeforeFork");
2121 syscall_runtime_BeforeFork(void)
2123 // Fork can hang if preempted with signals frequently enough (see issue 5517).
2124 // Ensure that we stay on the same M where we disable profiling.
2126 if(m
->profilehz
!= 0)
2127 runtime_resetcpuprofiler(0);
2130 // Called from syscall package after fork in parent.
2131 void syscall_runtime_AfterFork(void)
2132 __asm__(GOSYM_PREFIX
"syscall.runtime_AfterFork");
2134 syscall_runtime_AfterFork(void)
2138 hz
= runtime_sched
.profilehz
;
2140 runtime_resetcpuprofiler(hz
);
2144 // Allocate a new g, with a stack big enough for stacksize bytes.
2146 runtime_malg(int32 stacksize
, byte
** ret_stack
, size_t* ret_stacksize
)
2150 newg
= runtime_malloc(sizeof(G
));
2151 if(stacksize
>= 0) {
2152 #if USING_SPLIT_STACK
2153 int dont_block_signals
= 0;
2155 *ret_stack
= __splitstack_makecontext(stacksize
,
2156 &newg
->stack_context
[0],
2158 __splitstack_block_signals_context(&newg
->stack_context
[0],
2159 &dont_block_signals
, nil
);
2161 *ret_stack
= runtime_mallocgc(stacksize
, 0, FlagNoProfiling
|FlagNoGC
);
2162 *ret_stacksize
= stacksize
;
2163 newg
->gcinitial_sp
= *ret_stack
;
2164 newg
->gcstack_size
= stacksize
;
2165 runtime_xadd(&runtime_stacks_sys
, stacksize
);
2171 /* For runtime package testing. */
2174 // Create a new g running fn with siz bytes of arguments.
2175 // Put it on the queue of g's waiting to run.
2176 // The compiler turns a go statement into a call to this.
2177 // Cannot split the stack because it assumes that the arguments
2178 // are available sequentially after &fn; they would not be
2179 // copied if a stack split occurred. It's OK for this to call
2180 // functions that split the stack.
2181 void runtime_testing_entersyscall(void)
2182 __asm__ (GOSYM_PREFIX
"runtime.entersyscall");
2184 runtime_testing_entersyscall()
2186 runtime_entersyscall();
2189 void runtime_testing_exitsyscall(void)
2190 __asm__ (GOSYM_PREFIX
"runtime.exitsyscall");
2193 runtime_testing_exitsyscall()
2195 runtime_exitsyscall();
2199 __go_go(void (*fn
)(void*), void* arg
)
2206 //runtime_printf("newproc1 %p %p narg=%d nret=%d\n", fn->fn, argp, narg, nret);
2207 m
->locks
++; // disable preemption because it can be holding p in a local var
2210 if((newg
= gfget(p
)) != nil
) {
2211 #ifdef USING_SPLIT_STACK
2212 int dont_block_signals
= 0;
2214 sp
= __splitstack_resetcontext(&newg
->stack_context
[0],
2216 __splitstack_block_signals_context(&newg
->stack_context
[0],
2217 &dont_block_signals
, nil
);
2219 sp
= newg
->gcinitial_sp
;
2220 spsize
= newg
->gcstack_size
;
2222 runtime_throw("bad spsize in __go_go");
2223 newg
->gcnext_sp
= sp
;
2226 newg
= runtime_malg(StackMin
, &sp
, &spsize
);
2230 newg
->entry
= (byte
*)fn
;
2232 newg
->gopc
= (uintptr
)__builtin_return_address(0);
2233 newg
->status
= Grunnable
;
2234 if(p
->goidcache
== p
->goidcacheend
) {
2235 p
->goidcache
= runtime_xadd64(&runtime_sched
.goidgen
, GoidCacheBatch
);
2236 p
->goidcacheend
= p
->goidcache
+ GoidCacheBatch
;
2238 newg
->goid
= p
->goidcache
++;
2241 // Avoid warnings about variables clobbered by
2243 byte
* volatile vsp
= sp
;
2244 size_t volatile vspsize
= spsize
;
2245 G
* volatile vnewg
= newg
;
2247 getcontext(&vnewg
->context
);
2248 vnewg
->context
.uc_stack
.ss_sp
= vsp
;
2249 #ifdef MAKECONTEXT_STACK_TOP
2250 vnewg
->context
.uc_stack
.ss_sp
+= vspsize
;
2252 vnewg
->context
.uc_stack
.ss_size
= vspsize
;
2253 makecontext(&vnewg
->context
, kickoff
, 0);
2257 if(runtime_atomicload(&runtime_sched
.npidle
) != 0 && runtime_atomicload(&runtime_sched
.nmspinning
) == 0 && fn
!= runtime_main
) // TODO: fast atomic
2270 runtime_lock(&allglock
);
2271 if(runtime_allglen
>= allgcap
) {
2272 cap
= 4096/sizeof(new[0]);
2275 new = runtime_malloc(cap
*sizeof(new[0]));
2277 runtime_throw("runtime: cannot allocate memory");
2278 if(runtime_allg
!= nil
) {
2279 runtime_memmove(new, runtime_allg
, runtime_allglen
*sizeof(new[0]));
2280 runtime_free(runtime_allg
);
2285 runtime_allg
[runtime_allglen
++] = gp
;
2286 runtime_unlock(&allglock
);
2289 // Put on gfree list.
2290 // If local list is too long, transfer a batch to the global list.
2294 gp
->schedlink
= p
->gfree
;
2297 if(p
->gfreecnt
>= 64) {
2298 runtime_lock(&runtime_sched
.gflock
);
2299 while(p
->gfreecnt
>= 32) {
2302 p
->gfree
= gp
->schedlink
;
2303 gp
->schedlink
= runtime_sched
.gfree
;
2304 runtime_sched
.gfree
= gp
;
2306 runtime_unlock(&runtime_sched
.gflock
);
2310 // Get from gfree list.
2311 // If local list is empty, grab a batch from global list.
2319 if(gp
== nil
&& runtime_sched
.gfree
) {
2320 runtime_lock(&runtime_sched
.gflock
);
2321 while(p
->gfreecnt
< 32 && runtime_sched
.gfree
) {
2323 gp
= runtime_sched
.gfree
;
2324 runtime_sched
.gfree
= gp
->schedlink
;
2325 gp
->schedlink
= p
->gfree
;
2328 runtime_unlock(&runtime_sched
.gflock
);
2332 p
->gfree
= gp
->schedlink
;
2338 // Purge all cached G's from gfree list to the global list.
2344 runtime_lock(&runtime_sched
.gflock
);
2345 while(p
->gfreecnt
) {
2348 p
->gfree
= gp
->schedlink
;
2349 gp
->schedlink
= runtime_sched
.gfree
;
2350 runtime_sched
.gfree
= gp
;
2352 runtime_unlock(&runtime_sched
.gflock
);
2356 runtime_Breakpoint(void)
2358 runtime_breakpoint();
2361 void runtime_Gosched (void) __asm__ (GOSYM_PREFIX
"runtime.Gosched");
2364 runtime_Gosched(void)
2369 // Implementation of runtime.GOMAXPROCS.
2370 // delete when scheduler is even stronger
2372 runtime_gomaxprocsfunc(int32 n
)
2376 if(n
> MaxGomaxprocs
)
2378 runtime_lock(&runtime_sched
);
2379 ret
= runtime_gomaxprocs
;
2380 if(n
<= 0 || n
== ret
) {
2381 runtime_unlock(&runtime_sched
);
2384 runtime_unlock(&runtime_sched
);
2386 runtime_semacquire(&runtime_worldsema
, false);
2388 runtime_stoptheworld();
2391 runtime_semrelease(&runtime_worldsema
);
2392 runtime_starttheworld();
2397 // lockOSThread is called by runtime.LockOSThread and runtime.lockOSThread below
2398 // after they modify m->locked. Do not allow preemption during this call,
2399 // or else the m might be different in this function than in the caller.
2407 void runtime_LockOSThread(void) __asm__ (GOSYM_PREFIX
"runtime.LockOSThread");
2409 runtime_LockOSThread(void)
2411 m
->locked
|= LockExternal
;
2416 runtime_lockOSThread(void)
2418 m
->locked
+= LockInternal
;
2423 // unlockOSThread is called by runtime.UnlockOSThread and runtime.unlockOSThread below
2424 // after they update m->locked. Do not allow preemption during this call,
2425 // or else the m might be in different in this function than in the caller.
2427 unlockOSThread(void)
2435 void runtime_UnlockOSThread(void) __asm__ (GOSYM_PREFIX
"runtime.UnlockOSThread");
2438 runtime_UnlockOSThread(void)
2440 m
->locked
&= ~LockExternal
;
2445 runtime_unlockOSThread(void)
2447 if(m
->locked
< LockInternal
)
2448 runtime_throw("runtime: internal error: misuse of lockOSThread/unlockOSThread");
2449 m
->locked
-= LockInternal
;
2454 runtime_lockedOSThread(void)
2456 return g
->lockedm
!= nil
&& m
->lockedg
!= nil
;
2460 runtime_gcount(void)
2467 runtime_lock(&allglock
);
2468 // TODO(dvyukov): runtime.NumGoroutine() is O(N).
2469 // We do not want to increment/decrement centralized counter in newproc/goexit,
2470 // just to make runtime.NumGoroutine() faster.
2471 // Compromise solution is to introduce per-P counters of active goroutines.
2472 for(i
= 0; i
< runtime_allglen
; i
++) {
2473 gp
= runtime_allg
[i
];
2475 if(s
== Grunnable
|| s
== Grunning
|| s
== Gsyscall
|| s
== Gwaiting
)
2478 runtime_unlock(&allglock
);
2483 runtime_mcount(void)
2485 return runtime_sched
.mcount
;
2490 void (*fn
)(uintptr
*, int32
);
2492 uintptr pcbuf
[TracebackMaxFrames
];
2493 Location locbuf
[TracebackMaxFrames
];
2496 static void System(void) {}
2497 static void GC(void) {}
2499 // Called if we receive a SIGPROF signal.
2507 if(prof
.fn
== nil
|| prof
.hz
== 0)
2515 if(mp
->mcache
== nil
)
2518 // Profiling runs concurrently with GC, so it must not allocate.
2521 runtime_lock(&prof
);
2522 if(prof
.fn
== nil
) {
2523 runtime_unlock(&prof
);
2529 if(runtime_atomicload(&runtime_in_callers
) > 0) {
2530 // If SIGPROF arrived while already fetching runtime
2531 // callers we can have trouble on older systems
2532 // because the unwind library calls dl_iterate_phdr
2533 // which was not recursive in the past.
2538 n
= runtime_callers(0, prof
.locbuf
, nelem(prof
.locbuf
));
2539 for(i
= 0; i
< n
; i
++)
2540 prof
.pcbuf
[i
] = prof
.locbuf
[i
].pc
;
2542 if(!traceback
|| n
<= 0) {
2544 prof
.pcbuf
[0] = (uintptr
)runtime_getcallerpc(&n
);
2545 if(mp
->gcing
|| mp
->helpgc
)
2546 prof
.pcbuf
[1] = (uintptr
)GC
;
2548 prof
.pcbuf
[1] = (uintptr
)System
;
2550 prof
.fn(prof
.pcbuf
, n
);
2551 runtime_unlock(&prof
);
2555 // Arrange to call fn with a traceback hz times a second.
2557 runtime_setcpuprofilerate(void (*fn
)(uintptr
*, int32
), int32 hz
)
2559 // Force sane arguments.
2567 // Disable preemption, otherwise we can be rescheduled to another thread
2568 // that has profiling enabled.
2571 // Stop profiler on this thread so that it is safe to lock prof.
2572 // if a profiling signal came in while we had prof locked,
2573 // it would deadlock.
2574 runtime_resetcpuprofiler(0);
2576 runtime_lock(&prof
);
2579 runtime_unlock(&prof
);
2580 runtime_lock(&runtime_sched
);
2581 runtime_sched
.profilehz
= hz
;
2582 runtime_unlock(&runtime_sched
);
2585 runtime_resetcpuprofiler(hz
);
2590 // Change number of processors. The world is stopped, sched is locked.
2592 procresize(int32
new)
2599 old
= runtime_gomaxprocs
;
2600 if(old
< 0 || old
> MaxGomaxprocs
|| new <= 0 || new >MaxGomaxprocs
)
2601 runtime_throw("procresize: invalid arg");
2602 // initialize new P's
2603 for(i
= 0; i
< new; i
++) {
2604 p
= runtime_allp
[i
];
2606 p
= (P
*)runtime_mallocgc(sizeof(*p
), 0, FlagNoInvokeGC
);
2608 p
->status
= Pgcstop
;
2609 runtime_atomicstorep(&runtime_allp
[i
], p
);
2611 if(p
->mcache
== nil
) {
2613 p
->mcache
= m
->mcache
; // bootstrap
2615 p
->mcache
= runtime_allocmcache();
2619 // redistribute runnable G's evenly
2620 // collect all runnable goroutines in global queue preserving FIFO order
2621 // FIFO order is required to ensure fairness even during frequent GCs
2622 // see http://golang.org/issue/7126
2626 for(i
= 0; i
< old
; i
++) {
2627 p
= runtime_allp
[i
];
2628 if(p
->runqhead
== p
->runqtail
)
2631 // pop from tail of local queue
2633 gp
= p
->runq
[p
->runqtail
%nelem(p
->runq
)];
2634 // push onto head of global queue
2635 gp
->schedlink
= runtime_sched
.runqhead
;
2636 runtime_sched
.runqhead
= gp
;
2637 if(runtime_sched
.runqtail
== nil
)
2638 runtime_sched
.runqtail
= gp
;
2639 runtime_sched
.runqsize
++;
2642 // fill local queues with at most nelem(p->runq)/2 goroutines
2643 // start at 1 because current M already executes some G and will acquire allp[0] below,
2644 // so if we have a spare G we want to put it into allp[1].
2645 for(i
= 1; (uint32
)i
< (uint32
)new * nelem(p
->runq
)/2 && runtime_sched
.runqsize
> 0; i
++) {
2646 gp
= runtime_sched
.runqhead
;
2647 runtime_sched
.runqhead
= gp
->schedlink
;
2648 if(runtime_sched
.runqhead
== nil
)
2649 runtime_sched
.runqtail
= nil
;
2650 runtime_sched
.runqsize
--;
2651 runqput(runtime_allp
[i
%new], gp
);
2655 for(i
= new; i
< old
; i
++) {
2656 p
= runtime_allp
[i
];
2657 runtime_freemcache(p
->mcache
);
2661 // can't free P itself because it can be referenced by an M in syscall
2668 p
= runtime_allp
[0];
2672 for(i
= new-1; i
> 0; i
--) {
2673 p
= runtime_allp
[i
];
2677 runtime_atomicstore((uint32
*)&runtime_gomaxprocs
, new);
2680 // Associate p and the current m.
2684 if(m
->p
|| m
->mcache
)
2685 runtime_throw("acquirep: already in go");
2686 if(p
->m
|| p
->status
!= Pidle
) {
2687 runtime_printf("acquirep: p->m=%p(%d) p->status=%d\n", p
->m
, p
->m
? p
->m
->id
: 0, p
->status
);
2688 runtime_throw("acquirep: invalid p state");
2690 m
->mcache
= p
->mcache
;
2693 p
->status
= Prunning
;
2696 // Disassociate p and the current m.
2702 if(m
->p
== nil
|| m
->mcache
== nil
)
2703 runtime_throw("releasep: invalid arg");
2705 if(p
->m
!= m
|| p
->mcache
!= m
->mcache
|| p
->status
!= Prunning
) {
2706 runtime_printf("releasep: m=%p m->p=%p p->m=%p m->mcache=%p p->mcache=%p p->status=%d\n",
2707 m
, m
->p
, p
->m
, m
->mcache
, p
->mcache
, p
->status
);
2708 runtime_throw("releasep: invalid p state");
2718 incidlelocked(int32 v
)
2720 runtime_lock(&runtime_sched
);
2721 runtime_sched
.nmidlelocked
+= v
;
2724 runtime_unlock(&runtime_sched
);
2727 // Check for deadlock situation.
2728 // The check is based on number of running M's, if 0 -> deadlock.
2733 int32 run
, grunning
, s
;
2737 run
= runtime_sched
.mcount
- runtime_sched
.nmidle
- runtime_sched
.nmidlelocked
- 1 - countextra();
2740 // If we are dying because of a signal caught on an already idle thread,
2741 // freezetheworld will cause all running threads to block.
2742 // And runtime will essentially enter into deadlock state,
2743 // except that there is a thread that will call runtime_exit soon.
2744 if(runtime_panicking
> 0)
2747 runtime_printf("runtime: checkdead: nmidle=%d nmidlelocked=%d mcount=%d\n",
2748 runtime_sched
.nmidle
, runtime_sched
.nmidlelocked
, runtime_sched
.mcount
);
2749 runtime_throw("checkdead: inconsistent counts");
2752 runtime_lock(&allglock
);
2753 for(i
= 0; i
< runtime_allglen
; i
++) {
2754 gp
= runtime_allg
[i
];
2755 if(gp
->isbackground
)
2760 else if(s
== Grunnable
|| s
== Grunning
|| s
== Gsyscall
) {
2761 runtime_unlock(&allglock
);
2762 runtime_printf("runtime: checkdead: find g %D in status %d\n", gp
->goid
, s
);
2763 runtime_throw("checkdead: runnable g");
2766 runtime_unlock(&allglock
);
2767 if(grunning
== 0) // possible if main goroutine calls runtime_Goexit()
2769 m
->throwing
= -1; // do not dump full stacks
2770 runtime_throw("all goroutines are asleep - deadlock!");
2777 int64 now
, lastpoll
, lasttrace
;
2781 idle
= 0; // how many cycles in succession we had not wokeup somebody
2784 if(idle
== 0) // start with 20us sleep...
2786 else if(idle
> 50) // start doubling the sleep after 1ms...
2788 if(delay
> 10*1000) // up to 10ms
2790 runtime_usleep(delay
);
2791 if(runtime_debug
.schedtrace
<= 0 &&
2792 (runtime_sched
.gcwaiting
|| runtime_atomicload(&runtime_sched
.npidle
) == (uint32
)runtime_gomaxprocs
)) { // TODO: fast atomic
2793 runtime_lock(&runtime_sched
);
2794 if(runtime_atomicload(&runtime_sched
.gcwaiting
) || runtime_atomicload(&runtime_sched
.npidle
) == (uint32
)runtime_gomaxprocs
) {
2795 runtime_atomicstore(&runtime_sched
.sysmonwait
, 1);
2796 runtime_unlock(&runtime_sched
);
2797 runtime_notesleep(&runtime_sched
.sysmonnote
);
2798 runtime_noteclear(&runtime_sched
.sysmonnote
);
2802 runtime_unlock(&runtime_sched
);
2804 // poll network if not polled for more than 10ms
2805 lastpoll
= runtime_atomicload64(&runtime_sched
.lastpoll
);
2806 now
= runtime_nanotime();
2807 if(lastpoll
!= 0 && lastpoll
+ 10*1000*1000 < now
) {
2808 runtime_cas64(&runtime_sched
.lastpoll
, lastpoll
, now
);
2809 gp
= runtime_netpoll(false); // non-blocking
2811 // Need to decrement number of idle locked M's
2812 // (pretending that one more is running) before injectglist.
2813 // Otherwise it can lead to the following situation:
2814 // injectglist grabs all P's but before it starts M's to run the P's,
2815 // another M returns from syscall, finishes running its G,
2816 // observes that there is no work to do and no other running M's
2817 // and reports deadlock.
2823 // retake P's blocked in syscalls
2824 // and preempt long running G's
2830 if(runtime_debug
.schedtrace
> 0 && lasttrace
+ runtime_debug
.schedtrace
*1000000ll <= now
) {
2832 runtime_schedtrace(runtime_debug
.scheddetail
);
2837 typedef struct Pdesc Pdesc
;
2845 static Pdesc pdesc
[MaxGomaxprocs
];
2856 for(i
= 0; i
< (uint32
)runtime_gomaxprocs
; i
++) {
2857 p
= runtime_allp
[i
];
2863 // Retake P from syscall if it's there for more than 1 sysmon tick (at least 20us).
2865 if(pd
->syscalltick
!= t
) {
2866 pd
->syscalltick
= t
;
2867 pd
->syscallwhen
= now
;
2870 // On the one hand we don't want to retake Ps if there is no other work to do,
2871 // but on the other hand we want to retake them eventually
2872 // because they can prevent the sysmon thread from deep sleep.
2873 if(p
->runqhead
== p
->runqtail
&&
2874 runtime_atomicload(&runtime_sched
.nmspinning
) + runtime_atomicload(&runtime_sched
.npidle
) > 0 &&
2875 pd
->syscallwhen
+ 10*1000*1000 > now
)
2877 // Need to decrement number of idle locked M's
2878 // (pretending that one more is running) before the CAS.
2879 // Otherwise the M from which we retake can exit the syscall,
2880 // increment nmidle and report deadlock.
2882 if(runtime_cas(&p
->status
, s
, Pidle
)) {
2887 } else if(s
== Prunning
) {
2888 // Preempt G if it's running for more than 10ms.
2890 if(pd
->schedtick
!= t
) {
2892 pd
->schedwhen
= now
;
2895 if(pd
->schedwhen
+ 10*1000*1000 > now
)
2903 // Tell all goroutines that they have been preempted and they should stop.
2904 // This function is purely best-effort. It can fail to inform a goroutine if a
2905 // processor just started running it.
2906 // No locks need to be held.
2907 // Returns true if preemption request was issued to at least one goroutine.
2915 runtime_schedtrace(bool detailed
)
2917 static int64 starttime
;
2919 int64 id1
, id2
, id3
;
2927 now
= runtime_nanotime();
2931 runtime_lock(&runtime_sched
);
2932 runtime_printf("SCHED %Dms: gomaxprocs=%d idleprocs=%d threads=%d idlethreads=%d runqueue=%d",
2933 (now
-starttime
)/1000000, runtime_gomaxprocs
, runtime_sched
.npidle
, runtime_sched
.mcount
,
2934 runtime_sched
.nmidle
, runtime_sched
.runqsize
);
2936 runtime_printf(" gcwaiting=%d nmidlelocked=%d nmspinning=%d stopwait=%d sysmonwait=%d\n",
2937 runtime_sched
.gcwaiting
, runtime_sched
.nmidlelocked
, runtime_sched
.nmspinning
,
2938 runtime_sched
.stopwait
, runtime_sched
.sysmonwait
);
2940 // We must be careful while reading data from P's, M's and G's.
2941 // Even if we hold schedlock, most data can be changed concurrently.
2942 // E.g. (p->m ? p->m->id : -1) can crash if p->m changes from non-nil to nil.
2943 for(i
= 0; i
< runtime_gomaxprocs
; i
++) {
2944 p
= runtime_allp
[i
];
2948 h
= runtime_atomicload(&p
->runqhead
);
2949 t
= runtime_atomicload(&p
->runqtail
);
2951 runtime_printf(" P%d: status=%d schedtick=%d syscalltick=%d m=%d runqsize=%d gfreecnt=%d\n",
2952 i
, p
->status
, p
->schedtick
, p
->syscalltick
, mp
? mp
->id
: -1, t
-h
, p
->gfreecnt
);
2954 // In non-detailed mode format lengths of per-P run queues as:
2955 // [len1 len2 len3 len4]
2957 if(runtime_gomaxprocs
== 1)
2961 else if(i
== runtime_gomaxprocs
-1)
2963 runtime_printf(fmt
, t
-h
);
2967 runtime_unlock(&runtime_sched
);
2970 for(mp
= runtime_allm
; mp
; mp
= mp
->alllink
) {
2973 lockedg
= mp
->lockedg
;
2982 id3
= lockedg
->goid
;
2983 runtime_printf(" M%d: p=%D curg=%D mallocing=%d throwing=%d gcing=%d"
2984 " locks=%d dying=%d helpgc=%d spinning=%d blocked=%d lockedg=%D\n",
2986 mp
->mallocing
, mp
->throwing
, mp
->gcing
, mp
->locks
, mp
->dying
, mp
->helpgc
,
2987 mp
->spinning
, m
->blocked
, id3
);
2989 runtime_lock(&allglock
);
2990 for(gi
= 0; gi
< runtime_allglen
; gi
++) {
2991 gp
= runtime_allg
[gi
];
2993 lockedm
= gp
->lockedm
;
2994 runtime_printf(" G%D: status=%d(%s) m=%d lockedm=%d\n",
2995 gp
->goid
, gp
->status
, gp
->waitreason
, mp
? mp
->id
: -1,
2996 lockedm
? lockedm
->id
: -1);
2998 runtime_unlock(&allglock
);
2999 runtime_unlock(&runtime_sched
);
3002 // Put mp on midle list.
3003 // Sched must be locked.
3007 mp
->schedlink
= runtime_sched
.midle
;
3008 runtime_sched
.midle
= mp
;
3009 runtime_sched
.nmidle
++;
3013 // Try to get an m from midle list.
3014 // Sched must be locked.
3020 if((mp
= runtime_sched
.midle
) != nil
){
3021 runtime_sched
.midle
= mp
->schedlink
;
3022 runtime_sched
.nmidle
--;
3027 // Put gp on the global runnable queue.
3028 // Sched must be locked.
3032 gp
->schedlink
= nil
;
3033 if(runtime_sched
.runqtail
)
3034 runtime_sched
.runqtail
->schedlink
= gp
;
3036 runtime_sched
.runqhead
= gp
;
3037 runtime_sched
.runqtail
= gp
;
3038 runtime_sched
.runqsize
++;
3041 // Put a batch of runnable goroutines on the global runnable queue.
3042 // Sched must be locked.
3044 globrunqputbatch(G
*ghead
, G
*gtail
, int32 n
)
3046 gtail
->schedlink
= nil
;
3047 if(runtime_sched
.runqtail
)
3048 runtime_sched
.runqtail
->schedlink
= ghead
;
3050 runtime_sched
.runqhead
= ghead
;
3051 runtime_sched
.runqtail
= gtail
;
3052 runtime_sched
.runqsize
+= n
;
3055 // Try get a batch of G's from the global runnable queue.
3056 // Sched must be locked.
3058 globrunqget(P
*p
, int32 max
)
3063 if(runtime_sched
.runqsize
== 0)
3065 n
= runtime_sched
.runqsize
/runtime_gomaxprocs
+1;
3066 if(n
> runtime_sched
.runqsize
)
3067 n
= runtime_sched
.runqsize
;
3068 if(max
> 0 && n
> max
)
3070 if((uint32
)n
> nelem(p
->runq
)/2)
3071 n
= nelem(p
->runq
)/2;
3072 runtime_sched
.runqsize
-= n
;
3073 if(runtime_sched
.runqsize
== 0)
3074 runtime_sched
.runqtail
= nil
;
3075 gp
= runtime_sched
.runqhead
;
3076 runtime_sched
.runqhead
= gp
->schedlink
;
3079 gp1
= runtime_sched
.runqhead
;
3080 runtime_sched
.runqhead
= gp1
->schedlink
;
3086 // Put p to on pidle list.
3087 // Sched must be locked.
3091 p
->link
= runtime_sched
.pidle
;
3092 runtime_sched
.pidle
= p
;
3093 runtime_xadd(&runtime_sched
.npidle
, 1); // TODO: fast atomic
3096 // Try get a p from pidle list.
3097 // Sched must be locked.
3103 p
= runtime_sched
.pidle
;
3105 runtime_sched
.pidle
= p
->link
;
3106 runtime_xadd(&runtime_sched
.npidle
, -1); // TODO: fast atomic
3111 // Try to put g on local runnable queue.
3112 // If it's full, put onto global queue.
3113 // Executed only by the owner P.
3115 runqput(P
*p
, G
*gp
)
3120 h
= runtime_atomicload(&p
->runqhead
); // load-acquire, synchronize with consumers
3122 if(t
- h
< nelem(p
->runq
)) {
3123 p
->runq
[t
%nelem(p
->runq
)] = gp
;
3124 runtime_atomicstore(&p
->runqtail
, t
+1); // store-release, makes the item available for consumption
3127 if(runqputslow(p
, gp
, h
, t
))
3129 // the queue is not full, now the put above must suceed
3133 // Put g and a batch of work from local runnable queue on global queue.
3134 // Executed only by the owner P.
3136 runqputslow(P
*p
, G
*gp
, uint32 h
, uint32 t
)
3138 G
*batch
[nelem(p
->runq
)/2+1];
3141 // First, grab a batch from local queue.
3144 if(n
!= nelem(p
->runq
)/2)
3145 runtime_throw("runqputslow: queue is not full");
3147 batch
[i
] = p
->runq
[(h
+i
)%nelem(p
->runq
)];
3148 if(!runtime_cas(&p
->runqhead
, h
, h
+n
)) // cas-release, commits consume
3151 // Link the goroutines.
3153 batch
[i
]->schedlink
= batch
[i
+1];
3154 // Now put the batch on global queue.
3155 runtime_lock(&runtime_sched
);
3156 globrunqputbatch(batch
[0], batch
[n
], n
+1);
3157 runtime_unlock(&runtime_sched
);
3161 // Get g from local runnable queue.
3162 // Executed only by the owner P.
3170 h
= runtime_atomicload(&p
->runqhead
); // load-acquire, synchronize with other consumers
3174 gp
= p
->runq
[h
%nelem(p
->runq
)];
3175 if(runtime_cas(&p
->runqhead
, h
, h
+1)) // cas-release, commits consume
3180 // Grabs a batch of goroutines from local runnable queue.
3181 // batch array must be of size nelem(p->runq)/2. Returns number of grabbed goroutines.
3182 // Can be executed by any P.
3184 runqgrab(P
*p
, G
**batch
)
3189 h
= runtime_atomicload(&p
->runqhead
); // load-acquire, synchronize with other consumers
3190 t
= runtime_atomicload(&p
->runqtail
); // load-acquire, synchronize with the producer
3195 if(n
> nelem(p
->runq
)/2) // read inconsistent h and t
3198 batch
[i
] = p
->runq
[(h
+i
)%nelem(p
->runq
)];
3199 if(runtime_cas(&p
->runqhead
, h
, h
+n
)) // cas-release, commits consume
3205 // Steal half of elements from local runnable queue of p2
3206 // and put onto local runnable queue of p.
3207 // Returns one of the stolen elements (or nil if failed).
3209 runqsteal(P
*p
, P
*p2
)
3212 G
*batch
[nelem(p
->runq
)/2];
3215 n
= runqgrab(p2
, batch
);
3222 h
= runtime_atomicload(&p
->runqhead
); // load-acquire, synchronize with consumers
3224 if(t
- h
+ n
>= nelem(p
->runq
))
3225 runtime_throw("runqsteal: runq overflow");
3226 for(i
=0; i
<n
; i
++, t
++)
3227 p
->runq
[t
%nelem(p
->runq
)] = batch
[i
];
3228 runtime_atomicstore(&p
->runqtail
, t
); // store-release, makes the item available for consumption
3232 void runtime_testSchedLocalQueue(void)
3233 __asm__("runtime.testSchedLocalQueue");
3236 runtime_testSchedLocalQueue(void)
3239 G gs
[nelem(p
.runq
)];
3242 runtime_memclr((byte
*)&p
, sizeof(p
));
3244 for(i
= 0; i
< (int32
)nelem(gs
); i
++) {
3245 if(runqget(&p
) != nil
)
3246 runtime_throw("runq is not empty initially");
3247 for(j
= 0; j
< i
; j
++)
3248 runqput(&p
, &gs
[i
]);
3249 for(j
= 0; j
< i
; j
++) {
3250 if(runqget(&p
) != &gs
[i
]) {
3251 runtime_printf("bad element at iter %d/%d\n", i
, j
);
3252 runtime_throw("bad element");
3255 if(runqget(&p
) != nil
)
3256 runtime_throw("runq is not empty afterwards");
3260 void runtime_testSchedLocalQueueSteal(void)
3261 __asm__("runtime.testSchedLocalQueueSteal");
3264 runtime_testSchedLocalQueueSteal(void)
3267 G gs
[nelem(p1
.runq
)], *gp
;
3270 runtime_memclr((byte
*)&p1
, sizeof(p1
));
3271 runtime_memclr((byte
*)&p2
, sizeof(p2
));
3273 for(i
= 0; i
< (int32
)nelem(gs
); i
++) {
3274 for(j
= 0; j
< i
; j
++) {
3276 runqput(&p1
, &gs
[j
]);
3278 gp
= runqsteal(&p2
, &p1
);
3284 while((gp
= runqget(&p2
)) != nil
) {
3288 while((gp
= runqget(&p1
)) != nil
)
3290 for(j
= 0; j
< i
; j
++) {
3291 if(gs
[j
].sig
!= 1) {
3292 runtime_printf("bad element %d(%d) at iter %d\n", j
, gs
[j
].sig
, i
);
3293 runtime_throw("bad element");
3296 if(s
!= i
/2 && s
!= i
/2+1) {
3297 runtime_printf("bad steal %d, want %d or %d, iter %d\n",
3299 runtime_throw("bad steal");
3305 runtime_setmaxthreads(int32 in
)
3309 runtime_lock(&runtime_sched
);
3310 out
= runtime_sched
.maxmcount
;
3311 runtime_sched
.maxmcount
= in
;
3313 runtime_unlock(&runtime_sched
);
3318 runtime_proc_scan(struct Workbuf
** wbufp
, void (*enqueue1
)(struct Workbuf
**, Obj
))
3320 enqueue1(wbufp
, (Obj
){(byte
*)&runtime_sched
, sizeof runtime_sched
, 0});
3323 // When a function calls a closure, it passes the closure value to
3324 // __go_set_closure immediately before the function call. When a
3325 // function uses a closure, it calls __go_get_closure immediately on
3326 // function entry. This is a hack, but it will work on any system.
3327 // It would be better to use the static chain register when there is
3328 // one. It is also worth considering expanding these functions
3329 // directly in the compiler.
3332 __go_set_closure(void* v
)
3338 __go_get_closure(void)
3343 // Return whether we are waiting for a GC. This gc toolchain uses
3344 // preemption instead.
3346 runtime_gcwaiting(void)
3348 return runtime_sched
.gcwaiting
;