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
*))
286 #ifndef USING_SPLIT_STACK
290 // Ensure that all registers are on the stack for the garbage
292 __builtin_unwind_init();
297 runtime_throw("runtime: mcall called on m->g0 stack");
301 #ifdef USING_SPLIT_STACK
302 __splitstack_getcontext(&g
->stackcontext
[0]);
304 // We have to point to an address on the stack that is
305 // below the saved registers.
306 gp
->gcnextsp
= &afterregs
;
308 gp
->fromgogo
= false;
309 getcontext(ucontext_arg(&gp
->context
[0]));
311 // When we return from getcontext, we may be running
312 // in a new thread. That means that g may have
313 // changed. It is a global variables so we will
314 // reload it, but the address of g may be cached in
315 // our local stack frame, and that address may be
316 // wrong. Call the function to reload the value for
321 if(gp
->traceback
!= nil
)
324 if (gp
== nil
|| !gp
->fromgogo
) {
325 #ifdef USING_SPLIT_STACK
326 __splitstack_setcontext(&mp
->g0
->stackcontext
[0]);
328 mp
->g0
->entry
= (byte
*)pfn
;
331 // It's OK to set g directly here because this case
332 // can not occur if we got here via a setcontext to
333 // the getcontext call just above.
336 fixcontext(ucontext_arg(&mp
->g0
->context
[0]));
337 setcontext(ucontext_arg(&mp
->g0
->context
[0]));
338 runtime_throw("runtime: mcall function returned");
342 // Goroutine scheduler
343 // The scheduler's job is to distribute ready-to-run goroutines over worker threads.
345 // The main concepts are:
347 // M - worker thread, or machine.
348 // P - processor, a resource that is required to execute Go code.
349 // M must have an associated P to execute Go code, however it can be
350 // blocked or in a syscall w/o an associated P.
352 // Design doc at http://golang.org/s/go11sched.
356 // Number of goroutine ids to grab from runtime_sched->goidgen to local per-P cache at once.
357 // 16 seems to provide enough amortization, but other than that it's mostly arbitrary number.
361 extern Sched
* runtime_getsched() __asm__ (GOSYM_PREFIX
"runtime.getsched");
363 Sched
* runtime_sched
;
364 int32 runtime_gomaxprocs
;
365 uint32 runtime_needextram
= 1;
367 G runtime_g0
; // idle goroutine for m0
374 bool runtime_precisestack
;
375 static int32 newprocs
;
377 static Lock allglock
; // the following vars are protected by this lock or by stoptheworld
379 uintptr runtime_allglen
;
380 static uintptr allgcap
;
382 bool runtime_isarchive
;
384 void* runtime_mstart(void*);
385 static void runqput(P
*, G
*);
386 static G
* runqget(P
*);
387 static bool runqputslow(P
*, G
*, uint32
, uint32
);
388 static G
* runqsteal(P
*, P
*);
389 static void mput(M
*);
390 static M
* mget(void);
391 static void mcommoninit(M
*);
392 static void schedule(void);
393 static void procresize(int32
);
394 static void acquirep(P
*);
395 static P
* releasep(void);
396 static void newm(void(*)(void), P
*);
397 static void stopm(void);
398 static void startm(P
*, bool);
399 static void handoffp(P
*);
400 static void wakep(void);
401 static void stoplockedm(void);
402 static void startlockedm(G
*);
403 static void sysmon(void);
404 static uint32
retake(int64
);
405 static void incidlelocked(int32
);
406 static void checkdead(void);
407 static void exitsyscall0(G
*);
408 static void park0(G
*);
409 static void goexit0(G
*);
410 static void gfput(P
*, G
*);
412 static void gfpurge(P
*);
413 static void globrunqput(G
*);
414 static void globrunqputbatch(G
*, G
*, int32
);
415 static G
* globrunqget(P
*, int32
);
416 static P
* pidleget(void);
417 static void pidleput(P
*);
418 static void injectglist(G
*);
419 static bool preemptall(void);
420 static bool exitsyscallfast(void);
421 static void allgadd(G
*);
423 bool runtime_isstarted
;
425 // The bootstrap sequence is:
429 // make & queue new G
430 // call runtime_mstart
432 // The new G calls runtime_main.
434 runtime_schedinit(void)
442 runtime_sched
= runtime_getsched();
452 runtime_sched
->maxmcount
= 10000;
453 runtime_precisestack
= 0;
455 // runtime_symtabinit();
456 runtime_mallocinit();
459 // Initialize the itable value for newErrorCString,
460 // so that the next time it gets called, possibly
461 // in a fault during a garbage collection, it will not
462 // need to allocated memory.
463 runtime_newErrorCString(0, &i
);
465 // Initialize the cached gotraceback value, since
466 // gotraceback calls getenv, which mallocs on Plan 9.
467 runtime_gotraceback(nil
);
471 runtime_parsedebugvars();
473 runtime_sched
->lastpoll
= runtime_nanotime();
475 s
= runtime_getenv("GOMAXPROCS");
477 if(p
!= nil
&& (n
= runtime_atoi(p
, s
.len
)) > 0) {
478 if(n
> _MaxGomaxprocs
)
482 runtime_allp
= runtime_malloc((_MaxGomaxprocs
+1)*sizeof(runtime_allp
[0]));
485 // Can not enable GC until all roots are registered.
486 // mstats()->enablegc = 1;
489 extern void main_init(void) __asm__ (GOSYM_PREFIX
"__go_init_main");
490 extern void main_main(void) __asm__ (GOSYM_PREFIX
"main.main");
492 // Used to determine the field alignment.
500 // main_init_done is a signal used by cgocallbackg that initialization
501 // has been completed. It is made before _cgo_notify_runtime_init_done,
502 // so all cgo calls can rely on it existing. When main_init is
503 // complete, it is closed, meaning cgocallbackg can reliably receive
505 Hchan
*runtime_main_init_done
;
507 // The chan bool type, for runtime_main_init_done.
509 extern const struct __go_type_descriptor bool_type_descriptor
510 __asm__ (GOSYM_PREFIX
"__go_tdn_bool");
512 static struct __go_channel_type chan_bool_type_descriptor
=
521 offsetof (struct field_align
, p
) - 1,
525 0, /* This value doesn't matter. */
531 NULL
, /* This value doesn't matter */
533 NULL
, /* This value doesn't matter */
536 /* __pointer_to_this */
540 &bool_type_descriptor
,
545 extern Hchan
*makechan (ChanType
*, int64
)
546 __asm__ (GOSYM_PREFIX
"runtime.makechan");
547 extern void closechan(Hchan
*) __asm__ (GOSYM_PREFIX
"runtime.closechan");
550 initDone(void *arg
__attribute__ ((unused
))) {
551 runtime_unlockOSThread();
554 // The main goroutine.
555 // Note: C frames in general are not copyable during stack growth, for two reasons:
556 // 1) We don't know where in a frame to find pointers to other stack locations.
557 // 2) There's no guarantee that globals or heap values do not point into the frame.
559 // The C frame for runtime.main is copyable, because:
560 // 1) There are no pointers to other stack locations in the frame
561 // (d.fn points at a global, d.link is nil, d.argp is -1).
562 // 2) The only pointer into this frame is from the defer chain,
563 // which is explicitly handled during stack copying.
565 runtime_main(void* dummy
__attribute__((unused
)))
572 // Lock the main goroutine onto this, the main OS thread,
573 // during initialization. Most programs won't care, but a few
574 // do require certain calls to be made by the main thread.
575 // Those can arrange for main.main to run in the main thread
576 // by calling runtime.LockOSThread during initialization
577 // to preserve the lock.
578 runtime_lockOSThread();
580 // Defer unlock so that runtime.Goexit during init does the unlock too.
581 d
.pfn
= (uintptr
)(void*)initDone
;
584 d
._panic
= g
->_panic
;
586 d
.makefunccanrecover
= 0;
591 if(g
->m
!= &runtime_m0
)
592 runtime_throw("runtime_main not on m0");
593 __go_go(runtime_MHeap_Scavenger
, nil
);
595 runtime_main_init_done
= makechan(&chan_bool_type_descriptor
, 0);
597 _cgo_notify_runtime_init_done();
601 closechan(runtime_main_init_done
);
603 if(g
->_defer
!= &d
|| (void*)d
.pfn
!= initDone
)
604 runtime_throw("runtime: bad defer entry after init");
606 runtime_unlockOSThread();
608 // For gccgo we have to wait until after main is initialized
609 // to enable GC, because initializing main registers the GC
611 mstats()->enablegc
= 1;
613 if(runtime_isarchive
) {
614 // This is not a complete program, but is instead a
615 // library built using -buildmode=c-archive or
616 // c-shared. Now that we are initialized, there is
617 // nothing further to do.
623 // Make racy client program work: if panicking on
624 // another goroutine at the same time as main returns,
625 // let the other goroutine finish printing the panic trace.
626 // Once it does, it will exit. See issue 3934.
627 if(runtime_panicking())
628 runtime_park(nil
, nil
, "panicwait");
636 runtime_tracebackothers(G
* volatile me
)
645 traceback
= runtime_gotraceback(nil
);
647 // Show the current goroutine first, if we haven't already.
648 if((gp
= g
->m
->curg
) != nil
&& gp
!= me
) {
649 runtime_printf("\n");
650 runtime_goroutineheader(gp
);
653 #ifdef USING_SPLIT_STACK
654 __splitstack_getcontext(&me
->stackcontext
[0]);
656 getcontext(ucontext_arg(&me
->context
[0]));
658 if(gp
->traceback
!= nil
) {
662 slice
.__values
= &tb
.locbuf
[0];
663 slice
.__count
= tb
.c
;
664 slice
.__capacity
= tb
.c
;
665 runtime_printtrace(slice
, nil
);
666 runtime_printcreatedby(gp
);
669 runtime_lock(&allglock
);
670 for(i
= 0; i
< runtime_allglen
; i
++) {
671 gp
= runtime_allg
[i
];
672 if(gp
== me
|| gp
== g
->m
->curg
|| gp
->atomicstatus
== _Gdead
)
674 if(gp
->issystem
&& traceback
< 2)
676 runtime_printf("\n");
677 runtime_goroutineheader(gp
);
679 // Our only mechanism for doing a stack trace is
680 // _Unwind_Backtrace. And that only works for the
681 // current thread, not for other random goroutines.
682 // So we need to switch context to the goroutine, get
683 // the backtrace, and then switch back.
685 // This means that if g is running or in a syscall, we
686 // can't reliably print a stack trace. FIXME.
688 if(gp
->atomicstatus
== _Grunning
) {
689 runtime_printf("\tgoroutine running on other thread; stack unavailable\n");
690 runtime_printcreatedby(gp
);
691 } else if(gp
->atomicstatus
== _Gsyscall
) {
692 runtime_printf("\tgoroutine in C code; stack unavailable\n");
693 runtime_printcreatedby(gp
);
697 #ifdef USING_SPLIT_STACK
698 __splitstack_getcontext(&me
->stackcontext
[0]);
700 getcontext(ucontext_arg(&me
->context
[0]));
702 if(gp
->traceback
!= nil
) {
706 slice
.__values
= &tb
.locbuf
[0];
707 slice
.__count
= tb
.c
;
708 slice
.__capacity
= tb
.c
;
709 runtime_printtrace(slice
, nil
);
710 runtime_printcreatedby(gp
);
713 runtime_unlock(&allglock
);
719 // sched lock is held
720 if(runtime_sched
->mcount
> runtime_sched
->maxmcount
) {
721 runtime_printf("runtime: program exceeds %d-thread limit\n", runtime_sched
->maxmcount
);
722 runtime_throw("thread exhaustion");
726 // Do a stack trace of gp, and then restore the context to
732 Traceback
* traceback
;
734 traceback
= gp
->traceback
;
737 runtime_throw("gtraceback: m is not nil");
738 gp
->m
= traceback
->gp
->m
;
739 traceback
->c
= runtime_callers(1, traceback
->locbuf
,
740 sizeof traceback
->locbuf
/ sizeof traceback
->locbuf
[0], false);
742 runtime_gogo(traceback
->gp
);
748 // If there is no mcache runtime_callers() will crash,
749 // and we are most likely in sysmon thread so the stack is senseless anyway.
751 runtime_callers(1, mp
->createstack
, nelem(mp
->createstack
), false);
753 mp
->fastrand
= 0x49f6428aUL
+ mp
->id
+ runtime_cputicks();
755 runtime_lock(&runtime_sched
->lock
);
756 mp
->id
= runtime_sched
->mcount
++;
758 runtime_mpreinit(mp
);
760 // Add to runtime_allm so garbage collector doesn't free m
761 // when it is just in a register or thread-local storage.
762 mp
->alllink
= runtime_allm
;
763 // runtime_NumCgoCall() iterates over allm w/o schedlock,
764 // so we need to publish it safely.
765 runtime_atomicstorep(&runtime_allm
, mp
);
766 runtime_unlock(&runtime_sched
->lock
);
769 // Mark gp ready to run.
774 g
->m
->locks
++; // disable preemption because it can be holding p in a local var
775 if(gp
->atomicstatus
!= _Gwaiting
) {
776 runtime_printf("goroutine %D has status %d\n", gp
->goid
, gp
->atomicstatus
);
777 runtime_throw("bad g->atomicstatus in ready");
779 gp
->atomicstatus
= _Grunnable
;
780 runqput((P
*)g
->m
->p
, gp
);
781 if(runtime_atomicload(&runtime_sched
->npidle
) != 0 && runtime_atomicload(&runtime_sched
->nmspinning
) == 0) // TODO: fast atomic
786 void goready(G
*, int) __asm__ (GOSYM_PREFIX
"runtime.goready");
789 goready(G
* gp
, int traceskip
__attribute__ ((unused
)))
795 runtime_gcprocs(void)
799 // Figure out how many CPUs to use during GC.
800 // Limited by gomaxprocs, number of actual CPUs, and MaxGcproc.
801 runtime_lock(&runtime_sched
->lock
);
802 n
= runtime_gomaxprocs
;
804 n
= runtime_ncpu
> 0 ? runtime_ncpu
: 1;
807 if(n
> runtime_sched
->nmidle
+1) // one M is currently running
808 n
= runtime_sched
->nmidle
+1;
809 runtime_unlock(&runtime_sched
->lock
);
818 runtime_lock(&runtime_sched
->lock
);
819 n
= runtime_gomaxprocs
;
824 n
-= runtime_sched
->nmidle
+1; // one M is currently running
825 runtime_unlock(&runtime_sched
->lock
);
830 runtime_helpgc(int32 nproc
)
835 runtime_lock(&runtime_sched
->lock
);
837 for(n
= 1; n
< nproc
; n
++) { // one M is currently running
838 if(runtime_allp
[pos
]->mcache
== g
->m
->mcache
)
842 runtime_throw("runtime_gcprocs inconsistency");
844 mp
->mcache
= runtime_allp
[pos
]->mcache
;
846 runtime_notewakeup(&mp
->park
);
848 runtime_unlock(&runtime_sched
->lock
);
851 // Similar to stoptheworld but best-effort and can be called several times.
852 // There is no reverse operation, used during crashing.
853 // This function must not lock any mutexes.
855 runtime_freezetheworld(void)
859 if(runtime_gomaxprocs
== 1)
861 // stopwait and preemption requests can be lost
862 // due to races with concurrently executing threads,
863 // so try several times
864 for(i
= 0; i
< 5; i
++) {
865 // this should tell the scheduler to not start any new goroutines
866 runtime_sched
->stopwait
= 0x7fffffff;
867 runtime_atomicstore((uint32
*)&runtime_sched
->gcwaiting
, 1);
868 // this should stop running goroutines
870 break; // no running goroutines
871 runtime_usleep(1000);
874 runtime_usleep(1000);
876 runtime_usleep(1000);
880 runtime_stopTheWorldWithSema(void)
887 runtime_lock(&runtime_sched
->lock
);
888 runtime_sched
->stopwait
= runtime_gomaxprocs
;
889 runtime_atomicstore((uint32
*)&runtime_sched
->gcwaiting
, 1);
892 ((P
*)g
->m
->p
)->status
= _Pgcstop
;
893 runtime_sched
->stopwait
--;
894 // try to retake all P's in _Psyscall status
895 for(i
= 0; i
< runtime_gomaxprocs
; i
++) {
898 if(s
== _Psyscall
&& runtime_cas(&p
->status
, s
, _Pgcstop
))
899 runtime_sched
->stopwait
--;
902 while((p
= pidleget()) != nil
) {
903 p
->status
= _Pgcstop
;
904 runtime_sched
->stopwait
--;
906 wait
= runtime_sched
->stopwait
> 0;
907 runtime_unlock(&runtime_sched
->lock
);
909 // wait for remaining P's to stop voluntarily
911 runtime_notesleep(&runtime_sched
->stopnote
);
912 runtime_noteclear(&runtime_sched
->stopnote
);
914 if(runtime_sched
->stopwait
)
915 runtime_throw("stoptheworld: not stopped");
916 for(i
= 0; i
< runtime_gomaxprocs
; i
++) {
918 if(p
->status
!= _Pgcstop
)
919 runtime_throw("stoptheworld: not stopped");
930 runtime_startTheWorldWithSema(void)
937 g
->m
->locks
++; // disable preemption because it can be holding p in a local var
938 gp
= runtime_netpoll(false); // non-blocking
940 add
= needaddgcproc();
941 runtime_lock(&runtime_sched
->lock
);
943 procresize(newprocs
);
946 procresize(runtime_gomaxprocs
);
947 runtime_sched
->gcwaiting
= 0;
950 while((p
= pidleget()) != nil
) {
951 // procresize() puts p's with work at the beginning of the list.
952 // Once we reach a p without a run queue, the rest don't have one either.
953 if(p
->runqhead
== p
->runqtail
) {
957 p
->m
= (uintptr
)mget();
958 p
->link
= (uintptr
)p1
;
961 if(runtime_sched
->sysmonwait
) {
962 runtime_sched
->sysmonwait
= false;
963 runtime_notewakeup(&runtime_sched
->sysmonnote
);
965 runtime_unlock(&runtime_sched
->lock
);
974 runtime_throw("startTheWorldWithSema: inconsistent mp->nextp");
975 mp
->nextp
= (uintptr
)p
;
976 runtime_notewakeup(&mp
->park
);
978 // Start M to run P. Do not start another M below.
985 // If GC could have used another helper proc, start one now,
986 // in the hope that it will be available next time.
987 // It would have been even better to start it before the collection,
988 // but doing so requires allocating memory, so it's tricky to
989 // coordinate. This lazy approach works out in practice:
990 // we don't mind if the first couple gc rounds don't have quite
991 // the maximum number of procs.
997 // Called to start an M.
999 runtime_mstart(void* mp
)
1012 // Record top of stack for use by mcall.
1013 // Once we call schedule we're never coming back,
1014 // so other calls can reuse this stack space.
1015 #ifdef USING_SPLIT_STACK
1016 __splitstack_getcontext(&g
->stackcontext
[0]);
1018 g
->gcinitialsp
= &mp
;
1019 // Setting gcstacksize to 0 is a marker meaning that gcinitialsp
1020 // is the top of the stack, not the bottom.
1024 getcontext(ucontext_arg(&g
->context
[0]));
1026 if(g
->entry
!= nil
) {
1027 // Got here from mcall.
1028 void (*pfn
)(G
*) = (void (*)(G
*))g
->entry
;
1029 G
* gp
= (G
*)g
->param
;
1035 #ifdef USING_SPLIT_STACK
1037 int dont_block_signals
= 0;
1038 __splitstack_block_signals(&dont_block_signals
, nil
);
1042 // Install signal handlers; after minit so that minit can
1043 // prepare the thread to be able to handle the signals.
1044 if(m
== &runtime_m0
) {
1045 if(runtime_iscgo
&& !runtime_cgoHasExtraM
) {
1046 runtime_cgoHasExtraM
= true;
1047 runtime_newextram();
1048 runtime_needextram
= 0;
1050 runtime_initsig(false);
1054 ((void (*)(void))m
->mstartfn
)();
1059 } else if(m
!= &runtime_m0
) {
1060 acquirep((P
*)m
->nextp
);
1065 // TODO(brainman): This point is never reached, because scheduler
1066 // does not release os threads at the moment. But once this path
1067 // is enabled, we must remove our seh here.
1072 typedef struct CgoThreadStart CgoThreadStart
;
1073 struct CgoThreadStart
1081 // Allocate a new m unassociated with any thread.
1082 // Can use p for allocation context if needed.
1084 runtime_allocm(P
*p
, int32 stacksize
, byte
** ret_g0_stack
, uintptr
* ret_g0_stacksize
)
1088 g
->m
->locks
++; // disable GC because it can be called from sysmon
1090 acquirep(p
); // temporarily borrow p for mallocs in this function
1094 runtime_gc_m_ptr(&e
);
1095 mtype
= ((const PtrType
*)e
.__type_descriptor
)->__element_type
;
1099 mp
= runtime_mal(sizeof *mp
);
1101 mp
->g0
= runtime_malg(stacksize
, ret_g0_stack
, ret_g0_stacksize
);
1104 if(p
== (P
*)g
->m
->p
)
1115 // static Type *gtype;
1117 // if(gtype == nil) {
1119 // runtime_gc_g_ptr(&e);
1120 // gtype = ((PtrType*)e.__type_descriptor)->__element_type;
1122 // gp = runtime_cnew(gtype);
1123 gp
= runtime_malloc(sizeof(G
));
1127 static M
* lockextra(bool nilokay
);
1128 static void unlockextra(M
*);
1130 // needm is called when a cgo callback happens on a
1131 // thread without an m (a thread not created by Go).
1132 // In this case, needm is expected to find an m to use
1133 // and return with m, g initialized correctly.
1134 // Since m and g are not set now (likely nil, but see below)
1135 // needm is limited in what routines it can call. In particular
1136 // it can only call nosplit functions (textflag 7) and cannot
1137 // do any scheduling that requires an m.
1139 // In order to avoid needing heavy lifting here, we adopt
1140 // the following strategy: there is a stack of available m's
1141 // that can be stolen. Using compare-and-swap
1142 // to pop from the stack has ABA races, so we simulate
1143 // a lock by doing an exchange (via casp) to steal the stack
1144 // head and replace the top pointer with MLOCKED (1).
1145 // This serves as a simple spin lock that we can use even
1146 // without an m. The thread that locks the stack in this way
1147 // unlocks the stack by storing a valid stack head pointer.
1149 // In order to make sure that there is always an m structure
1150 // available to be stolen, we maintain the invariant that there
1151 // is always one more than needed. At the beginning of the
1152 // program (if cgo is in use) the list is seeded with a single m.
1153 // If needm finds that it has taken the last m off the list, its job
1154 // is - once it has installed its own m so that it can do things like
1155 // allocate memory - to create a spare m and put it on the list.
1157 // Each of these extra m's also has a g0 and a curg that are
1158 // pressed into service as the scheduling stack and current
1159 // goroutine for the duration of the cgo callback.
1161 // When the callback is done with the m, it calls dropm to
1162 // put the m back on the list.
1164 // Unlike the gc toolchain, we start running on curg, since we are
1165 // just going to return and let the caller continue.
1171 if(runtime_needextram
) {
1172 // Can happen if C/C++ code calls Go from a global ctor.
1173 // Can not throw, because scheduler is not initialized yet.
1174 int rv
__attribute__((unused
));
1175 rv
= runtime_write(2, "fatal error: cgo callback before cgo call\n",
1176 sizeof("fatal error: cgo callback before cgo call\n")-1);
1180 // Lock extra list, take head, unlock popped list.
1181 // nilokay=false is safe here because of the invariant above,
1182 // that the extra list always contains or will soon contain
1184 mp
= lockextra(false);
1186 // Set needextram when we've just emptied the list,
1187 // so that the eventual call into cgocallbackg will
1188 // allocate a new m for the extra list. We delay the
1189 // allocation until then so that it can be done
1190 // after exitsyscall makes sure it is okay to be
1191 // running at all (that is, there's no garbage collection
1192 // running right now).
1193 mp
->needextram
= mp
->schedlink
== 0;
1194 unlockextra((M
*)mp
->schedlink
);
1196 // Install g (= m->curg).
1197 runtime_setg(mp
->curg
);
1199 // Initialize g's context as in mstart.
1201 g
->atomicstatus
= _Gsyscall
;
1204 #ifdef USING_SPLIT_STACK
1205 __splitstack_getcontext(&g
->stackcontext
[0]);
1207 g
->gcinitialsp
= &mp
;
1212 getcontext(ucontext_arg(&g
->context
[0]));
1214 if(g
->entry
!= nil
) {
1215 // Got here from mcall.
1216 void (*pfn
)(G
*) = (void (*)(G
*))g
->entry
;
1217 G
* gp
= (G
*)g
->param
;
1222 // Initialize this thread to use the m.
1225 #ifdef USING_SPLIT_STACK
1227 int dont_block_signals
= 0;
1228 __splitstack_block_signals(&dont_block_signals
, nil
);
1233 // newextram allocates an m and puts it on the extra list.
1234 // It is called with a working local m, so that it can do things
1235 // like call schedlock and allocate.
1237 runtime_newextram(void)
1242 uintptr g0_spsize
, spsize
;
1245 // Create extra goroutine locked to extra m.
1246 // The goroutine is the context in which the cgo callback will run.
1247 // The sched.pc will never be returned to, but setting it to
1248 // runtime.goexit makes clear to the traceback routines where
1249 // the goroutine stack ends.
1250 mp
= runtime_allocm(nil
, StackMin
, &g0_sp
, &g0_spsize
);
1251 gp
= runtime_malg(StackMin
, &sp
, &spsize
);
1252 gp
->atomicstatus
= _Gdead
;
1255 mp
->locked
= _LockInternal
;
1258 gp
->goid
= runtime_xadd64(&runtime_sched
->goidgen
, 1);
1259 // put on allg for garbage collector
1262 // The context for gp will be set up in runtime_needm. But
1263 // here we need to set up the context for g0.
1264 uc
= ucontext_arg(&mp
->g0
->context
[0]);
1266 uc
->uc_stack
.ss_sp
= g0_sp
;
1267 uc
->uc_stack
.ss_size
= (size_t)g0_spsize
;
1268 makecontext(uc
, kickoff
, 0);
1270 // Add m to the extra list.
1271 mnext
= lockextra(true);
1272 mp
->schedlink
= (uintptr
)mnext
;
1276 // dropm is called when a cgo callback has called needm but is now
1277 // done with the callback and returning back into the non-Go thread.
1278 // It puts the current m back onto the extra list.
1280 // The main expense here is the call to signalstack to release the
1281 // m's signal stack, and then the call to needm on the next callback
1282 // from this thread. It is tempting to try to save the m for next time,
1283 // which would eliminate both these costs, but there might not be
1284 // a next time: the current thread (which Go does not control) might exit.
1285 // If we saved the m for that thread, there would be an m leak each time
1286 // such a thread exited. Instead, we acquire and release an m on each
1287 // call. These should typically not be scheduling operations, just a few
1288 // atomics, so the cost should be small.
1290 // TODO(rsc): An alternative would be to allocate a dummy pthread per-thread
1291 // variable using pthread_key_create. Unlike the pthread keys we already use
1292 // on OS X, this dummy key would never be read by Go code. It would exist
1293 // only so that we could register at thread-exit-time destructor.
1294 // That destructor would put the m back onto the extra list.
1295 // This is purely a performance optimization. The current version,
1296 // in which dropm happens on each cgo call, is still correct too.
1297 // We may have to keep the current version on systems with cgo
1298 // but without pthreads, like Windows.
1304 // Undo whatever initialization minit did during needm.
1307 // Clear m and g, and return m to the extra list.
1308 // After the call to setg we can only call nosplit functions.
1312 mp
->curg
->atomicstatus
= _Gdead
;
1313 mp
->curg
->gcstack
= nil
;
1314 mp
->curg
->gcnextsp
= nil
;
1316 mnext
= lockextra(true);
1317 mp
->schedlink
= (uintptr
)mnext
;
1321 #define MLOCKED ((M*)1)
1323 // lockextra locks the extra list and returns the list head.
1324 // The caller must unlock the list by storing a new list head
1325 // to runtime.extram. If nilokay is true, then lockextra will
1326 // return a nil list head if that's what it finds. If nilokay is false,
1327 // lockextra will keep waiting until the list head is no longer nil.
1329 lockextra(bool nilokay
)
1332 void (*yield
)(void);
1335 mp
= runtime_atomicloadp(&runtime_extram
);
1337 yield
= runtime_osyield
;
1341 if(mp
== nil
&& !nilokay
) {
1345 if(!runtime_casp(&runtime_extram
, mp
, MLOCKED
)) {
1346 yield
= runtime_osyield
;
1358 runtime_atomicstorep(&runtime_extram
, mp
);
1368 mp
= runtime_atomicloadp(&runtime_extram
);
1373 if(!runtime_casp(&runtime_extram
, mp
, MLOCKED
)) {
1378 for(mc
= mp
; mc
!= nil
; mc
= (M
*)mc
->schedlink
)
1380 runtime_atomicstorep(&runtime_extram
, mp
);
1385 // Create a new m. It will start off with a call to fn, or else the scheduler.
1387 newm(void(*fn
)(void), P
*p
)
1391 mp
= runtime_allocm(p
, -1, nil
, nil
);
1392 mp
->nextp
= (uintptr
)p
;
1393 mp
->mstartfn
= (uintptr
)(void*)fn
;
1395 runtime_newosproc(mp
);
1398 // Stops execution of the current m until new work is available.
1399 // Returns with acquired P.
1407 runtime_throw("stopm holding locks");
1409 runtime_throw("stopm holding p");
1411 m
->spinning
= false;
1412 runtime_xadd(&runtime_sched
->nmspinning
, -1);
1416 runtime_lock(&runtime_sched
->lock
);
1418 runtime_unlock(&runtime_sched
->lock
);
1419 runtime_notesleep(&m
->park
);
1421 runtime_noteclear(&m
->park
);
1428 acquirep((P
*)m
->nextp
);
1435 g
->m
->spinning
= true;
1438 // Schedules some M to run the p (creates an M if necessary).
1439 // If p==nil, tries to get an idle P, if no idle P's does nothing.
1441 startm(P
*p
, bool spinning
)
1446 runtime_lock(&runtime_sched
->lock
);
1450 runtime_unlock(&runtime_sched
->lock
);
1452 runtime_xadd(&runtime_sched
->nmspinning
, -1);
1457 runtime_unlock(&runtime_sched
->lock
);
1466 runtime_throw("startm: m is spinning");
1468 runtime_throw("startm: m has p");
1469 mp
->spinning
= spinning
;
1470 mp
->nextp
= (uintptr
)p
;
1471 runtime_notewakeup(&mp
->park
);
1474 // Hands off P from syscall or locked M.
1478 // if it has local work, start it straight away
1479 if(p
->runqhead
!= p
->runqtail
|| runtime_sched
->runqsize
) {
1483 // no local work, check that there are no spinning/idle M's,
1484 // otherwise our help is not required
1485 if(runtime_atomicload(&runtime_sched
->nmspinning
) + runtime_atomicload(&runtime_sched
->npidle
) == 0 && // TODO: fast atomic
1486 runtime_cas(&runtime_sched
->nmspinning
, 0, 1)) {
1490 runtime_lock(&runtime_sched
->lock
);
1491 if(runtime_sched
->gcwaiting
) {
1492 p
->status
= _Pgcstop
;
1493 if(--runtime_sched
->stopwait
== 0)
1494 runtime_notewakeup(&runtime_sched
->stopnote
);
1495 runtime_unlock(&runtime_sched
->lock
);
1498 if(runtime_sched
->runqsize
) {
1499 runtime_unlock(&runtime_sched
->lock
);
1503 // If this is the last running P and nobody is polling network,
1504 // need to wakeup another M to poll network.
1505 if(runtime_sched
->npidle
== (uint32
)runtime_gomaxprocs
-1 && runtime_atomicload64(&runtime_sched
->lastpoll
) != 0) {
1506 runtime_unlock(&runtime_sched
->lock
);
1511 runtime_unlock(&runtime_sched
->lock
);
1514 // Tries to add one more P to execute G's.
1515 // Called when a G is made runnable (newproc, ready).
1519 // be conservative about spinning threads
1520 if(!runtime_cas(&runtime_sched
->nmspinning
, 0, 1))
1525 // Stops execution of the current m that is locked to a g until the g is runnable again.
1526 // Returns with acquired P.
1534 if(m
->lockedg
== nil
|| m
->lockedg
->lockedm
!= m
)
1535 runtime_throw("stoplockedm: inconsistent locking");
1537 // Schedule another M to run this p.
1542 // Wait until another thread schedules lockedg again.
1543 runtime_notesleep(&m
->park
);
1545 runtime_noteclear(&m
->park
);
1546 if(m
->lockedg
->atomicstatus
!= _Grunnable
)
1547 runtime_throw("stoplockedm: not runnable");
1548 acquirep((P
*)m
->nextp
);
1552 // Schedules the locked m to run the locked gp.
1561 runtime_throw("startlockedm: locked to me");
1563 runtime_throw("startlockedm: m has p");
1564 // directly handoff current P to the locked m
1567 mp
->nextp
= (uintptr
)p
;
1568 runtime_notewakeup(&mp
->park
);
1572 // Stops the current m for stoptheworld.
1573 // Returns when the world is restarted.
1579 if(!runtime_sched
->gcwaiting
)
1580 runtime_throw("gcstopm: not waiting for gc");
1581 if(g
->m
->spinning
) {
1582 g
->m
->spinning
= false;
1583 runtime_xadd(&runtime_sched
->nmspinning
, -1);
1586 runtime_lock(&runtime_sched
->lock
);
1587 p
->status
= _Pgcstop
;
1588 if(--runtime_sched
->stopwait
== 0)
1589 runtime_notewakeup(&runtime_sched
->stopnote
);
1590 runtime_unlock(&runtime_sched
->lock
);
1594 // Schedules gp to run on the current M.
1601 if(gp
->atomicstatus
!= _Grunnable
) {
1602 runtime_printf("execute: bad g status %d\n", gp
->atomicstatus
);
1603 runtime_throw("execute: bad g status");
1605 gp
->atomicstatus
= _Grunning
;
1607 ((P
*)g
->m
->p
)->schedtick
++;
1611 // Check whether the profiler needs to be turned on or off.
1612 hz
= runtime_sched
->profilehz
;
1613 if(g
->m
->profilehz
!= hz
)
1614 runtime_resetcpuprofiler(hz
);
1619 // Finds a runnable goroutine to execute.
1620 // Tries to steal from other P's, get g from global queue, poll network.
1629 if(runtime_sched
->gcwaiting
) {
1633 if(runtime_fingwait
&& runtime_fingwake
&& (gp
= runtime_wakefing()) != nil
)
1636 gp
= runqget((P
*)g
->m
->p
);
1640 if(runtime_sched
->runqsize
) {
1641 runtime_lock(&runtime_sched
->lock
);
1642 gp
= globrunqget((P
*)g
->m
->p
, 0);
1643 runtime_unlock(&runtime_sched
->lock
);
1648 gp
= runtime_netpoll(false); // non-blocking
1650 injectglist((G
*)gp
->schedlink
);
1651 gp
->atomicstatus
= _Grunnable
;
1654 // If number of spinning M's >= number of busy P's, block.
1655 // This is necessary to prevent excessive CPU consumption
1656 // when GOMAXPROCS>>1 but the program parallelism is low.
1657 if(!g
->m
->spinning
&& 2 * runtime_atomicload(&runtime_sched
->nmspinning
) >= runtime_gomaxprocs
- runtime_atomicload(&runtime_sched
->npidle
)) // TODO: fast atomic
1659 if(!g
->m
->spinning
) {
1660 g
->m
->spinning
= true;
1661 runtime_xadd(&runtime_sched
->nmspinning
, 1);
1663 // random steal from other P's
1664 for(i
= 0; i
< 2*runtime_gomaxprocs
; i
++) {
1665 if(runtime_sched
->gcwaiting
)
1667 p
= runtime_allp
[runtime_fastrand1()%runtime_gomaxprocs
];
1668 if(p
== (P
*)g
->m
->p
)
1671 gp
= runqsteal((P
*)g
->m
->p
, p
);
1676 // return P and block
1677 runtime_lock(&runtime_sched
->lock
);
1678 if(runtime_sched
->gcwaiting
) {
1679 runtime_unlock(&runtime_sched
->lock
);
1682 if(runtime_sched
->runqsize
) {
1683 gp
= globrunqget((P
*)g
->m
->p
, 0);
1684 runtime_unlock(&runtime_sched
->lock
);
1689 runtime_unlock(&runtime_sched
->lock
);
1690 if(g
->m
->spinning
) {
1691 g
->m
->spinning
= false;
1692 runtime_xadd(&runtime_sched
->nmspinning
, -1);
1694 // check all runqueues once again
1695 for(i
= 0; i
< runtime_gomaxprocs
; i
++) {
1696 p
= runtime_allp
[i
];
1697 if(p
&& p
->runqhead
!= p
->runqtail
) {
1698 runtime_lock(&runtime_sched
->lock
);
1700 runtime_unlock(&runtime_sched
->lock
);
1709 if(runtime_xchg64(&runtime_sched
->lastpoll
, 0) != 0) {
1711 runtime_throw("findrunnable: netpoll with p");
1713 runtime_throw("findrunnable: netpoll with spinning");
1714 gp
= runtime_netpoll(true); // block until new work is available
1715 runtime_atomicstore64(&runtime_sched
->lastpoll
, runtime_nanotime());
1717 runtime_lock(&runtime_sched
->lock
);
1719 runtime_unlock(&runtime_sched
->lock
);
1722 injectglist((G
*)gp
->schedlink
);
1723 gp
->atomicstatus
= _Grunnable
;
1738 if(g
->m
->spinning
) {
1739 g
->m
->spinning
= false;
1740 nmspinning
= runtime_xadd(&runtime_sched
->nmspinning
, -1);
1742 runtime_throw("findrunnable: negative nmspinning");
1744 nmspinning
= runtime_atomicload(&runtime_sched
->nmspinning
);
1746 // M wakeup policy is deliberately somewhat conservative (see nmspinning handling),
1747 // so see if we need to wakeup another P here.
1748 if (nmspinning
== 0 && runtime_atomicload(&runtime_sched
->npidle
) > 0)
1752 // Injects the list of runnable G's into the scheduler.
1753 // Can run concurrently with GC.
1755 injectglist(G
*glist
)
1762 runtime_lock(&runtime_sched
->lock
);
1763 for(n
= 0; glist
; n
++) {
1765 glist
= (G
*)gp
->schedlink
;
1766 gp
->atomicstatus
= _Grunnable
;
1769 runtime_unlock(&runtime_sched
->lock
);
1771 for(; n
&& runtime_sched
->npidle
; n
--)
1775 // One round of scheduler: find a runnable goroutine and execute it.
1784 runtime_throw("schedule: holding locks");
1787 if(runtime_sched
->gcwaiting
) {
1793 // Check the global runnable queue once in a while to ensure fairness.
1794 // Otherwise two goroutines can completely occupy the local runqueue
1795 // by constantly respawning each other.
1796 tick
= ((P
*)g
->m
->p
)->schedtick
;
1797 // This is a fancy way to say tick%61==0,
1798 // it uses 2 MUL instructions instead of a single DIV and so is faster on modern processors.
1799 if(tick
- (((uint64
)tick
*0x4325c53fu
)>>36)*61 == 0 && runtime_sched
->runqsize
> 0) {
1800 runtime_lock(&runtime_sched
->lock
);
1801 gp
= globrunqget((P
*)g
->m
->p
, 1);
1802 runtime_unlock(&runtime_sched
->lock
);
1807 gp
= runqget((P
*)g
->m
->p
);
1808 if(gp
&& g
->m
->spinning
)
1809 runtime_throw("schedule: spinning with local work");
1812 gp
= findrunnable(); // blocks until work is available
1817 // Hands off own p to the locked m,
1818 // then blocks waiting for a new p.
1826 // Puts the current goroutine into a waiting state and calls unlockf.
1827 // If unlockf returns false, the goroutine is resumed.
1829 runtime_park(bool(*unlockf
)(G
*, void*), void *lock
, const char *reason
)
1831 if(g
->atomicstatus
!= _Grunning
)
1832 runtime_throw("bad g status");
1833 g
->m
->waitlock
= lock
;
1834 g
->m
->waitunlockf
= unlockf
;
1835 g
->waitreason
= runtime_gostringnocopy((const byte
*)reason
);
1836 runtime_mcall(park0
);
1839 void gopark(FuncVal
*, void *, String
, byte
, int)
1840 __asm__ ("runtime.gopark");
1843 gopark(FuncVal
*unlockf
, void *lock
, String reason
,
1844 byte traceEv
__attribute__ ((unused
)),
1845 int traceskip
__attribute__ ((unused
)))
1847 if(g
->atomicstatus
!= _Grunning
)
1848 runtime_throw("bad g status");
1849 g
->m
->waitlock
= lock
;
1850 g
->m
->waitunlockf
= unlockf
== nil
? nil
: (void*)unlockf
->fn
;
1851 g
->waitreason
= reason
;
1852 runtime_mcall(park0
);
1856 parkunlock(G
*gp
, void *lock
)
1859 runtime_unlock(lock
);
1863 // Puts the current goroutine into a waiting state and unlocks the lock.
1864 // The goroutine can be made runnable again by calling runtime_ready(gp).
1866 runtime_parkunlock(Lock
*lock
, const char *reason
)
1868 runtime_park(parkunlock
, lock
, reason
);
1871 void goparkunlock(Lock
*, String
, byte
, int)
1872 __asm__ (GOSYM_PREFIX
"runtime.goparkunlock");
1875 goparkunlock(Lock
*lock
, String reason
, byte traceEv
__attribute__ ((unused
)),
1876 int traceskip
__attribute__ ((unused
)))
1878 if(g
->atomicstatus
!= _Grunning
)
1879 runtime_throw("bad g status");
1880 g
->m
->waitlock
= lock
;
1881 g
->m
->waitunlockf
= parkunlock
;
1882 g
->waitreason
= reason
;
1883 runtime_mcall(park0
);
1886 // runtime_park continuation on g0.
1894 gp
->atomicstatus
= _Gwaiting
;
1897 if(m
->waitunlockf
) {
1898 ok
= ((bool (*)(G
*, void*))m
->waitunlockf
)(gp
, m
->waitlock
);
1899 m
->waitunlockf
= nil
;
1902 gp
->atomicstatus
= _Grunnable
;
1903 execute(gp
); // Schedule it back, never returns.
1908 execute(gp
); // Never returns.
1915 runtime_gosched(void)
1917 if(g
->atomicstatus
!= _Grunning
)
1918 runtime_throw("bad g status");
1919 runtime_mcall(runtime_gosched0
);
1922 // runtime_gosched continuation on g0.
1924 runtime_gosched0(G
*gp
)
1929 gp
->atomicstatus
= _Grunnable
;
1932 runtime_lock(&runtime_sched
->lock
);
1934 runtime_unlock(&runtime_sched
->lock
);
1937 execute(gp
); // Never returns.
1942 // Finishes execution of the current goroutine.
1943 // Need to mark it as nosplit, because it runs with sp > stackbase (as runtime_lessstack).
1944 // Since it does not return it does not matter. But if it is preempted
1945 // at the split stack check, GC will complain about inconsistent sp.
1946 void runtime_goexit1(void) __attribute__ ((noinline
));
1948 runtime_goexit1(void)
1950 if(g
->atomicstatus
!= _Grunning
)
1951 runtime_throw("bad g status");
1952 runtime_mcall(goexit0
);
1955 // runtime_goexit1 continuation on g0.
1962 gp
->atomicstatus
= _Gdead
;
1966 gp
->paniconfault
= 0;
1967 gp
->_defer
= nil
; // should be true already but just in case.
1968 gp
->_panic
= nil
; // non-nil for Goexit during panic. points at stack-allocated data.
1969 gp
->writebuf
.__values
= nil
;
1970 gp
->writebuf
.__count
= 0;
1971 gp
->writebuf
.__capacity
= 0;
1972 gp
->waitreason
= runtime_gostringnocopy(nil
);
1976 if(m
->locked
& ~_LockExternal
) {
1977 runtime_printf("invalid m->locked = %d\n", m
->locked
);
1978 runtime_throw("internal lockOSThread error");
1981 gfput((P
*)m
->p
, gp
);
1985 // The goroutine g is about to enter a system call.
1986 // Record that it's not using the cpu anymore.
1987 // This is called only from the go syscall library and cgocall,
1988 // not from the low-level system calls used by the runtime.
1990 // Entersyscall cannot split the stack: the runtime_gosave must
1991 // make g->sched refer to the caller's stack segment, because
1992 // entersyscall is going to return immediately after.
1994 void runtime_entersyscall(int32
) __attribute__ ((no_split_stack
));
1995 static void doentersyscall(uintptr
, uintptr
)
1996 __attribute__ ((no_split_stack
, noinline
));
1999 runtime_entersyscall(int32 dummy
__attribute__ ((unused
)))
2001 // Save the registers in the g structure so that any pointers
2002 // held in registers will be seen by the garbage collector.
2003 getcontext(ucontext_arg(&g
->gcregs
[0]));
2005 // Do the work in a separate function, so that this function
2006 // doesn't save any registers on its own stack. If this
2007 // function does save any registers, we might store the wrong
2008 // value in the call to getcontext.
2010 // FIXME: This assumes that we do not need to save any
2011 // callee-saved registers to access the TLS variable g. We
2012 // don't want to put the ucontext_t on the stack because it is
2013 // large and we can not split the stack here.
2014 doentersyscall((uintptr
)runtime_getcallerpc(&dummy
),
2015 (uintptr
)runtime_getcallersp(&dummy
));
2019 doentersyscall(uintptr pc
, uintptr sp
)
2021 // Disable preemption because during this function g is in _Gsyscall status,
2022 // but can have inconsistent g->sched, do not let GC observe it.
2025 // Leave SP around for GC and traceback.
2026 #ifdef USING_SPLIT_STACK
2029 g
->gcstack
= __splitstack_find(nil
, nil
, &gcstacksize
,
2030 &g
->gcnextsegment
, &g
->gcnextsp
,
2032 g
->gcstacksize
= (uintptr
)gcstacksize
;
2038 g
->gcnextsp
= (byte
*) &v
;
2045 g
->atomicstatus
= _Gsyscall
;
2047 if(runtime_atomicload(&runtime_sched
->sysmonwait
)) { // TODO: fast atomic
2048 runtime_lock(&runtime_sched
->lock
);
2049 if(runtime_atomicload(&runtime_sched
->sysmonwait
)) {
2050 runtime_atomicstore(&runtime_sched
->sysmonwait
, 0);
2051 runtime_notewakeup(&runtime_sched
->sysmonnote
);
2053 runtime_unlock(&runtime_sched
->lock
);
2057 ((P
*)(g
->m
->p
))->m
= 0;
2058 runtime_atomicstore(&((P
*)g
->m
->p
)->status
, _Psyscall
);
2059 if(runtime_atomicload(&runtime_sched
->gcwaiting
)) {
2060 runtime_lock(&runtime_sched
->lock
);
2061 if (runtime_sched
->stopwait
> 0 && runtime_cas(&((P
*)g
->m
->p
)->status
, _Psyscall
, _Pgcstop
)) {
2062 if(--runtime_sched
->stopwait
== 0)
2063 runtime_notewakeup(&runtime_sched
->stopnote
);
2065 runtime_unlock(&runtime_sched
->lock
);
2071 // The same as runtime_entersyscall(), but with a hint that the syscall is blocking.
2073 runtime_entersyscallblock(int32 dummy
__attribute__ ((unused
)))
2077 g
->m
->locks
++; // see comment in entersyscall
2079 // Leave SP around for GC and traceback.
2080 #ifdef USING_SPLIT_STACK
2083 g
->gcstack
= __splitstack_find(nil
, nil
, &gcstacksize
,
2084 &g
->gcnextsegment
, &g
->gcnextsp
,
2086 g
->gcstacksize
= (uintptr
)gcstacksize
;
2089 g
->gcnextsp
= (byte
*) &p
;
2092 // Save the registers in the g structure so that any pointers
2093 // held in registers will be seen by the garbage collector.
2094 getcontext(ucontext_arg(&g
->gcregs
[0]));
2096 g
->syscallpc
= (uintptr
)runtime_getcallerpc(&dummy
);
2097 g
->syscallsp
= (uintptr
)runtime_getcallersp(&dummy
);
2099 g
->atomicstatus
= _Gsyscall
;
2103 if(g
->isbackground
) // do not consider blocked scavenger for deadlock detection
2109 // The goroutine g exited its system call.
2110 // Arrange for it to run on a cpu again.
2111 // This is called only from the go syscall library, not
2112 // from the low-level system calls used by the runtime.
2114 runtime_exitsyscall(int32 dummy
__attribute__ ((unused
)))
2119 gp
->m
->locks
++; // see comment in entersyscall
2121 if(gp
->isbackground
) // do not consider blocked scavenger for deadlock detection
2125 if(exitsyscallfast()) {
2126 // There's a cpu for us, so we can run.
2127 ((P
*)gp
->m
->p
)->syscalltick
++;
2128 gp
->atomicstatus
= _Grunning
;
2129 // Garbage collector isn't running (since we are),
2130 // so okay to clear gcstack and gcsp.
2131 #ifdef USING_SPLIT_STACK
2135 runtime_memclr(&gp
->gcregs
[0], sizeof gp
->gcregs
);
2143 // Call the scheduler.
2144 runtime_mcall(exitsyscall0
);
2146 // Scheduler returned, so we're allowed to run now.
2147 // Delete the gcstack information that we left for
2148 // the garbage collector during the system call.
2149 // Must wait until now because until gosched returns
2150 // we don't know for sure that the garbage collector
2152 #ifdef USING_SPLIT_STACK
2156 runtime_memclr(&gp
->gcregs
[0], sizeof gp
->gcregs
);
2160 // Note that this gp->m might be different than the earlier
2161 // gp->m after returning from runtime_mcall.
2162 ((P
*)gp
->m
->p
)->syscalltick
++;
2166 exitsyscallfast(void)
2173 // Freezetheworld sets stopwait but does not retake P's.
2174 if(runtime_sched
->stopwait
) {
2179 // Try to re-acquire the last P.
2180 if(gp
->m
->p
&& ((P
*)gp
->m
->p
)->status
== _Psyscall
&& runtime_cas(&((P
*)gp
->m
->p
)->status
, _Psyscall
, _Prunning
)) {
2181 // There's a cpu for us, so we can run.
2182 gp
->m
->mcache
= ((P
*)gp
->m
->p
)->mcache
;
2183 ((P
*)gp
->m
->p
)->m
= (uintptr
)gp
->m
;
2186 // Try to get any other idle P.
2188 if(runtime_sched
->pidle
) {
2189 runtime_lock(&runtime_sched
->lock
);
2191 if(p
&& runtime_atomicload(&runtime_sched
->sysmonwait
)) {
2192 runtime_atomicstore(&runtime_sched
->sysmonwait
, 0);
2193 runtime_notewakeup(&runtime_sched
->sysmonnote
);
2195 runtime_unlock(&runtime_sched
->lock
);
2204 // runtime_exitsyscall slow path on g0.
2205 // Failed to acquire P, enqueue gp as runnable.
2213 gp
->atomicstatus
= _Grunnable
;
2216 runtime_lock(&runtime_sched
->lock
);
2220 else if(runtime_atomicload(&runtime_sched
->sysmonwait
)) {
2221 runtime_atomicstore(&runtime_sched
->sysmonwait
, 0);
2222 runtime_notewakeup(&runtime_sched
->sysmonnote
);
2224 runtime_unlock(&runtime_sched
->lock
);
2227 execute(gp
); // Never returns.
2230 // Wait until another thread schedules gp and so m again.
2232 execute(gp
); // Never returns.
2235 schedule(); // Never returns.
2238 void syscall_entersyscall(void)
2239 __asm__(GOSYM_PREFIX
"syscall.Entersyscall");
2241 void syscall_entersyscall(void) __attribute__ ((no_split_stack
));
2244 syscall_entersyscall()
2246 runtime_entersyscall(0);
2249 void syscall_exitsyscall(void)
2250 __asm__(GOSYM_PREFIX
"syscall.Exitsyscall");
2252 void syscall_exitsyscall(void) __attribute__ ((no_split_stack
));
2255 syscall_exitsyscall()
2257 runtime_exitsyscall(0);
2260 // Called from syscall package before fork.
2261 void syscall_runtime_BeforeFork(void)
2262 __asm__(GOSYM_PREFIX
"syscall.runtime_BeforeFork");
2264 syscall_runtime_BeforeFork(void)
2266 // Fork can hang if preempted with signals frequently enough (see issue 5517).
2267 // Ensure that we stay on the same M where we disable profiling.
2268 runtime_m()->locks
++;
2269 if(runtime_m()->profilehz
!= 0)
2270 runtime_resetcpuprofiler(0);
2273 // Called from syscall package after fork in parent.
2274 void syscall_runtime_AfterFork(void)
2275 __asm__(GOSYM_PREFIX
"syscall.runtime_AfterFork");
2277 syscall_runtime_AfterFork(void)
2281 hz
= runtime_sched
->profilehz
;
2283 runtime_resetcpuprofiler(hz
);
2284 runtime_m()->locks
--;
2287 // Allocate a new g, with a stack big enough for stacksize bytes.
2289 runtime_malg(int32 stacksize
, byte
** ret_stack
, uintptr
* ret_stacksize
)
2294 if(stacksize
>= 0) {
2295 #if USING_SPLIT_STACK
2296 int dont_block_signals
= 0;
2297 size_t ss_stacksize
;
2299 *ret_stack
= __splitstack_makecontext(stacksize
,
2300 &newg
->stackcontext
[0],
2302 *ret_stacksize
= (uintptr
)ss_stacksize
;
2303 __splitstack_block_signals_context(&newg
->stackcontext
[0],
2304 &dont_block_signals
, nil
);
2306 // In 64-bit mode, the maximum Go allocation space is
2307 // 128G. Our stack size is 4M, which only permits 32K
2308 // goroutines. In order to not limit ourselves,
2309 // allocate the stacks out of separate memory. In
2310 // 32-bit mode, the Go allocation space is all of
2312 if(sizeof(void*) == 8) {
2313 void *p
= runtime_SysAlloc(stacksize
, &mstats()->other_sys
);
2315 runtime_throw("runtime: cannot allocate memory for goroutine stack");
2316 *ret_stack
= (byte
*)p
;
2318 *ret_stack
= runtime_mallocgc(stacksize
, 0, FlagNoProfiling
|FlagNoGC
);
2319 runtime_xadd(&runtime_stacks_sys
, stacksize
);
2321 *ret_stacksize
= (uintptr
)stacksize
;
2322 newg
->gcinitialsp
= *ret_stack
;
2323 newg
->gcstacksize
= (uintptr
)stacksize
;
2330 __go_go(void (*fn
)(void*), void* arg
)
2337 //runtime_printf("newproc1 %p %p narg=%d nret=%d\n", fn->fn, argp, narg, nret);
2339 g
->m
->throwing
= -1; // do not dump full stacks
2340 runtime_throw("go of nil func value");
2342 g
->m
->locks
++; // disable preemption because it can be holding p in a local var
2345 if((newg
= gfget(p
)) != nil
) {
2346 #ifdef USING_SPLIT_STACK
2347 int dont_block_signals
= 0;
2349 sp
= __splitstack_resetcontext(&newg
->stackcontext
[0],
2351 __splitstack_block_signals_context(&newg
->stackcontext
[0],
2352 &dont_block_signals
, nil
);
2354 sp
= newg
->gcinitialsp
;
2355 spsize
= newg
->gcstacksize
;
2357 runtime_throw("bad spsize in __go_go");
2358 newg
->gcnextsp
= sp
;
2363 newg
= runtime_malg(StackMin
, &sp
, &malsize
);
2364 spsize
= (size_t)malsize
;
2368 newg
->entry
= (byte
*)fn
;
2370 newg
->gopc
= (uintptr
)__builtin_return_address(0);
2371 newg
->atomicstatus
= _Grunnable
;
2372 if(p
->goidcache
== p
->goidcacheend
) {
2373 p
->goidcache
= runtime_xadd64(&runtime_sched
->goidgen
, GoidCacheBatch
);
2374 p
->goidcacheend
= p
->goidcache
+ GoidCacheBatch
;
2376 newg
->goid
= p
->goidcache
++;
2379 // Avoid warnings about variables clobbered by
2381 byte
* volatile vsp
= sp
;
2382 size_t volatile vspsize
= spsize
;
2383 G
* volatile vnewg
= newg
;
2384 ucontext_t
* volatile uc
;
2386 uc
= ucontext_arg(&vnewg
->context
[0]);
2388 uc
->uc_stack
.ss_sp
= vsp
;
2389 uc
->uc_stack
.ss_size
= vspsize
;
2390 makecontext(uc
, kickoff
, 0);
2394 if(runtime_atomicload(&runtime_sched
->npidle
) != 0 && runtime_atomicload(&runtime_sched
->nmspinning
) == 0 && fn
!= runtime_main
) // TODO: fast atomic
2407 runtime_lock(&allglock
);
2408 if(runtime_allglen
>= allgcap
) {
2409 cap
= 4096/sizeof(new[0]);
2412 new = runtime_malloc(cap
*sizeof(new[0]));
2414 runtime_throw("runtime: cannot allocate memory");
2415 if(runtime_allg
!= nil
) {
2416 runtime_memmove(new, runtime_allg
, runtime_allglen
*sizeof(new[0]));
2417 runtime_free(runtime_allg
);
2422 runtime_allg
[runtime_allglen
++] = gp
;
2423 runtime_unlock(&allglock
);
2426 // Put on gfree list.
2427 // If local list is too long, transfer a batch to the global list.
2431 gp
->schedlink
= (uintptr
)p
->gfree
;
2434 if(p
->gfreecnt
>= 64) {
2435 runtime_lock(&runtime_sched
->gflock
);
2436 while(p
->gfreecnt
>= 32) {
2439 p
->gfree
= (G
*)gp
->schedlink
;
2440 gp
->schedlink
= (uintptr
)runtime_sched
->gfree
;
2441 runtime_sched
->gfree
= gp
;
2443 runtime_unlock(&runtime_sched
->gflock
);
2447 // Get from gfree list.
2448 // If local list is empty, grab a batch from global list.
2456 if(gp
== nil
&& runtime_sched
->gfree
) {
2457 runtime_lock(&runtime_sched
->gflock
);
2458 while(p
->gfreecnt
< 32 && runtime_sched
->gfree
) {
2460 gp
= runtime_sched
->gfree
;
2461 runtime_sched
->gfree
= (G
*)gp
->schedlink
;
2462 gp
->schedlink
= (uintptr
)p
->gfree
;
2465 runtime_unlock(&runtime_sched
->gflock
);
2469 p
->gfree
= (G
*)gp
->schedlink
;
2475 // Purge all cached G's from gfree list to the global list.
2481 runtime_lock(&runtime_sched
->gflock
);
2482 while(p
->gfreecnt
) {
2485 p
->gfree
= (G
*)gp
->schedlink
;
2486 gp
->schedlink
= (uintptr
)runtime_sched
->gfree
;
2487 runtime_sched
->gfree
= gp
;
2489 runtime_unlock(&runtime_sched
->gflock
);
2493 runtime_Breakpoint(void)
2495 runtime_breakpoint();
2498 void runtime_Gosched (void) __asm__ (GOSYM_PREFIX
"runtime.Gosched");
2501 runtime_Gosched(void)
2506 // Implementation of runtime.GOMAXPROCS.
2507 // delete when scheduler is even stronger
2509 intgo
runtime_GOMAXPROCS(intgo
)
2510 __asm__(GOSYM_PREFIX
"runtime.GOMAXPROCS");
2513 runtime_GOMAXPROCS(intgo n
)
2517 if(n
> _MaxGomaxprocs
)
2519 runtime_lock(&runtime_sched
->lock
);
2520 ret
= (intgo
)runtime_gomaxprocs
;
2521 if(n
<= 0 || n
== ret
) {
2522 runtime_unlock(&runtime_sched
->lock
);
2525 runtime_unlock(&runtime_sched
->lock
);
2527 runtime_acquireWorldsema();
2529 runtime_stopTheWorldWithSema();
2530 newprocs
= (int32
)n
;
2532 runtime_releaseWorldsema();
2533 runtime_startTheWorldWithSema();
2538 // lockOSThread is called by runtime.LockOSThread and runtime.lockOSThread below
2539 // after they modify m->locked. Do not allow preemption during this call,
2540 // or else the m might be different in this function than in the caller.
2548 void runtime_LockOSThread(void) __asm__ (GOSYM_PREFIX
"runtime.LockOSThread");
2550 runtime_LockOSThread(void)
2552 g
->m
->locked
|= _LockExternal
;
2557 runtime_lockOSThread(void)
2559 g
->m
->locked
+= _LockInternal
;
2564 // unlockOSThread is called by runtime.UnlockOSThread and runtime.unlockOSThread below
2565 // after they update m->locked. Do not allow preemption during this call,
2566 // or else the m might be in different in this function than in the caller.
2568 unlockOSThread(void)
2570 if(g
->m
->locked
!= 0)
2572 g
->m
->lockedg
= nil
;
2576 void runtime_UnlockOSThread(void) __asm__ (GOSYM_PREFIX
"runtime.UnlockOSThread");
2579 runtime_UnlockOSThread(void)
2581 g
->m
->locked
&= ~_LockExternal
;
2586 runtime_unlockOSThread(void)
2588 if(g
->m
->locked
< _LockInternal
)
2589 runtime_throw("runtime: internal error: misuse of lockOSThread/unlockOSThread");
2590 g
->m
->locked
-= _LockInternal
;
2595 runtime_lockedOSThread(void)
2597 return g
->lockedm
!= nil
&& g
->m
->lockedg
!= nil
;
2601 runtime_gcount(void)
2608 runtime_lock(&allglock
);
2609 // TODO(dvyukov): runtime.NumGoroutine() is O(N).
2610 // We do not want to increment/decrement centralized counter in newproc/goexit,
2611 // just to make runtime.NumGoroutine() faster.
2612 // Compromise solution is to introduce per-P counters of active goroutines.
2613 for(i
= 0; i
< runtime_allglen
; i
++) {
2614 gp
= runtime_allg
[i
];
2615 s
= gp
->atomicstatus
;
2616 if(s
== _Grunnable
|| s
== _Grunning
|| s
== _Gsyscall
|| s
== _Gwaiting
)
2619 runtime_unlock(&allglock
);
2624 runtime_mcount(void)
2626 return runtime_sched
->mcount
;
2634 static void System(void) {}
2635 static void GC(void) {}
2637 // Called if we receive a SIGPROF signal.
2644 uintptr pcbuf
[TracebackMaxFrames
];
2645 Location locbuf
[TracebackMaxFrames
];
2654 // Profiling runs concurrently with GC, so it must not allocate.
2659 if(mp
->mcache
== nil
)
2664 if(runtime_atomicload(&runtime_in_callers
) > 0) {
2665 // If SIGPROF arrived while already fetching runtime
2666 // callers we can have trouble on older systems
2667 // because the unwind library calls dl_iterate_phdr
2668 // which was not recursive in the past.
2673 n
= runtime_callers(0, locbuf
, nelem(locbuf
), false);
2674 for(i
= 0; i
< n
; i
++)
2675 pcbuf
[i
] = locbuf
[i
].pc
;
2677 if(!traceback
|| n
<= 0) {
2679 pcbuf
[0] = (uintptr
)runtime_getcallerpc(&n
);
2680 if(mp
->gcing
|| mp
->helpgc
)
2681 pcbuf
[1] = (uintptr
)GC
;
2683 pcbuf
[1] = (uintptr
)System
;
2687 stk
.__values
= &pcbuf
[0];
2691 // Simple cas-lock to coordinate with setcpuprofilerate.
2692 while (!runtime_cas(&prof
.lock
, 0, 1)) {
2696 runtime_cpuprofAdd(stk
);
2698 runtime_atomicstore(&prof
.lock
, 0);
2704 // Arrange to call fn with a traceback hz times a second.
2706 runtime_setcpuprofilerate_m(int32 hz
)
2708 // Force sane arguments.
2712 // Disable preemption, otherwise we can be rescheduled to another thread
2713 // that has profiling enabled.
2716 // Stop profiler on this thread so that it is safe to lock prof.
2717 // if a profiling signal came in while we had prof locked,
2718 // it would deadlock.
2719 runtime_resetcpuprofiler(0);
2721 while (!runtime_cas(&prof
.lock
, 0, 1)) {
2725 runtime_atomicstore(&prof
.lock
, 0);
2727 runtime_lock(&runtime_sched
->lock
);
2728 runtime_sched
->profilehz
= hz
;
2729 runtime_unlock(&runtime_sched
->lock
);
2732 runtime_resetcpuprofiler(hz
);
2737 // Change number of processors. The world is stopped, sched is locked.
2739 procresize(int32
new)
2747 old
= runtime_gomaxprocs
;
2748 if(old
< 0 || old
> _MaxGomaxprocs
|| new <= 0 || new >_MaxGomaxprocs
)
2749 runtime_throw("procresize: invalid arg");
2750 // initialize new P's
2751 for(i
= 0; i
< new; i
++) {
2752 p
= runtime_allp
[i
];
2754 p
= (P
*)runtime_mallocgc(sizeof(*p
), 0, FlagNoInvokeGC
);
2756 p
->status
= _Pgcstop
;
2757 p
->deferpool
.__values
= &p
->deferpoolbuf
[0];
2758 p
->deferpool
.__count
= 0;
2759 p
->deferpool
.__capacity
= nelem(p
->deferpoolbuf
);
2760 runtime_atomicstorep(&runtime_allp
[i
], p
);
2762 if(p
->mcache
== nil
) {
2764 p
->mcache
= g
->m
->mcache
; // bootstrap
2766 p
->mcache
= runtime_allocmcache();
2770 // redistribute runnable G's evenly
2771 // collect all runnable goroutines in global queue preserving FIFO order
2772 // FIFO order is required to ensure fairness even during frequent GCs
2773 // see http://golang.org/issue/7126
2777 for(i
= 0; i
< old
; i
++) {
2778 p
= runtime_allp
[i
];
2779 if(p
->runqhead
== p
->runqtail
)
2782 // pop from tail of local queue
2784 gp
= (G
*)p
->runq
[p
->runqtail
%nelem(p
->runq
)];
2785 // push onto head of global queue
2786 gp
->schedlink
= runtime_sched
->runqhead
;
2787 runtime_sched
->runqhead
= (uintptr
)gp
;
2788 if(runtime_sched
->runqtail
== 0)
2789 runtime_sched
->runqtail
= (uintptr
)gp
;
2790 runtime_sched
->runqsize
++;
2793 // fill local queues with at most nelem(p->runq)/2 goroutines
2794 // start at 1 because current M already executes some G and will acquire allp[0] below,
2795 // so if we have a spare G we want to put it into allp[1].
2796 for(i
= 1; (uint32
)i
< (uint32
)new * nelem(p
->runq
)/2 && runtime_sched
->runqsize
> 0; i
++) {
2797 gp
= (G
*)runtime_sched
->runqhead
;
2798 runtime_sched
->runqhead
= gp
->schedlink
;
2799 if(runtime_sched
->runqhead
== 0)
2800 runtime_sched
->runqtail
= 0;
2801 runtime_sched
->runqsize
--;
2802 runqput(runtime_allp
[i
%new], gp
);
2806 for(i
= new; i
< old
; i
++) {
2807 p
= runtime_allp
[i
];
2808 for(j
= 0; j
< p
->deferpool
.__count
; j
++) {
2809 ((struct _defer
**)p
->deferpool
.__values
)[j
] = nil
;
2811 p
->deferpool
.__count
= 0;
2812 runtime_freemcache(p
->mcache
);
2816 // can't free P itself because it can be referenced by an M in syscall
2820 ((P
*)g
->m
->p
)->m
= 0;
2823 p
= runtime_allp
[0];
2827 for(i
= new-1; i
> 0; i
--) {
2828 p
= runtime_allp
[i
];
2832 runtime_atomicstore((uint32
*)&runtime_gomaxprocs
, new);
2835 // Associate p and the current m.
2842 if(m
->p
|| m
->mcache
)
2843 runtime_throw("acquirep: already in go");
2844 if(p
->m
|| p
->status
!= _Pidle
) {
2845 runtime_printf("acquirep: p->m=%p(%d) p->status=%d\n", p
->m
, p
->m
? ((M
*)p
->m
)->id
: 0, p
->status
);
2846 runtime_throw("acquirep: invalid p state");
2848 m
->mcache
= p
->mcache
;
2851 p
->status
= _Prunning
;
2854 // Disassociate p and the current m.
2862 if(m
->p
== 0 || m
->mcache
== nil
)
2863 runtime_throw("releasep: invalid arg");
2865 if((M
*)p
->m
!= m
|| p
->mcache
!= m
->mcache
|| p
->status
!= _Prunning
) {
2866 runtime_printf("releasep: m=%p m->p=%p p->m=%p m->mcache=%p p->mcache=%p p->status=%d\n",
2867 m
, m
->p
, p
->m
, m
->mcache
, p
->mcache
, p
->status
);
2868 runtime_throw("releasep: invalid p state");
2878 incidlelocked(int32 v
)
2880 runtime_lock(&runtime_sched
->lock
);
2881 runtime_sched
->nmidlelocked
+= v
;
2884 runtime_unlock(&runtime_sched
->lock
);
2887 // Check for deadlock situation.
2888 // The check is based on number of running M's, if 0 -> deadlock.
2893 int32 run
, grunning
, s
;
2896 // For -buildmode=c-shared or -buildmode=c-archive it's OK if
2897 // there are no running goroutines. The calling program is
2898 // assumed to be running.
2899 if(runtime_isarchive
) {
2904 run
= runtime_sched
->mcount
- runtime_sched
->nmidle
- runtime_sched
->nmidlelocked
- 1 - countextra();
2907 // If we are dying because of a signal caught on an already idle thread,
2908 // freezetheworld will cause all running threads to block.
2909 // And runtime will essentially enter into deadlock state,
2910 // except that there is a thread that will call runtime_exit soon.
2911 if(runtime_panicking() > 0)
2914 runtime_printf("runtime: checkdead: nmidle=%d nmidlelocked=%d mcount=%d\n",
2915 runtime_sched
->nmidle
, runtime_sched
->nmidlelocked
, runtime_sched
->mcount
);
2916 runtime_throw("checkdead: inconsistent counts");
2919 runtime_lock(&allglock
);
2920 for(i
= 0; i
< runtime_allglen
; i
++) {
2921 gp
= runtime_allg
[i
];
2922 if(gp
->isbackground
)
2924 s
= gp
->atomicstatus
;
2927 else if(s
== _Grunnable
|| s
== _Grunning
|| s
== _Gsyscall
) {
2928 runtime_unlock(&allglock
);
2929 runtime_printf("runtime: checkdead: find g %D in status %d\n", gp
->goid
, s
);
2930 runtime_throw("checkdead: runnable g");
2933 runtime_unlock(&allglock
);
2934 if(grunning
== 0) // possible if main goroutine calls runtime_Goexit()
2935 runtime_throw("no goroutines (main called runtime.Goexit) - deadlock!");
2936 g
->m
->throwing
= -1; // do not dump full stacks
2937 runtime_throw("all goroutines are asleep - deadlock!");
2944 int64 now
, lastpoll
, lasttrace
;
2948 idle
= 0; // how many cycles in succession we had not wokeup somebody
2951 if(idle
== 0) // start with 20us sleep...
2953 else if(idle
> 50) // start doubling the sleep after 1ms...
2955 if(delay
> 10*1000) // up to 10ms
2957 runtime_usleep(delay
);
2958 if(runtime_debug
.schedtrace
<= 0 &&
2959 (runtime_sched
->gcwaiting
|| runtime_atomicload(&runtime_sched
->npidle
) == (uint32
)runtime_gomaxprocs
)) { // TODO: fast atomic
2960 runtime_lock(&runtime_sched
->lock
);
2961 if(runtime_atomicload(&runtime_sched
->gcwaiting
) || runtime_atomicload(&runtime_sched
->npidle
) == (uint32
)runtime_gomaxprocs
) {
2962 runtime_atomicstore(&runtime_sched
->sysmonwait
, 1);
2963 runtime_unlock(&runtime_sched
->lock
);
2964 runtime_notesleep(&runtime_sched
->sysmonnote
);
2965 runtime_noteclear(&runtime_sched
->sysmonnote
);
2969 runtime_unlock(&runtime_sched
->lock
);
2971 // poll network if not polled for more than 10ms
2972 lastpoll
= runtime_atomicload64(&runtime_sched
->lastpoll
);
2973 now
= runtime_nanotime();
2974 if(lastpoll
!= 0 && lastpoll
+ 10*1000*1000 < now
) {
2975 runtime_cas64(&runtime_sched
->lastpoll
, lastpoll
, now
);
2976 gp
= runtime_netpoll(false); // non-blocking
2978 // Need to decrement number of idle locked M's
2979 // (pretending that one more is running) before injectglist.
2980 // Otherwise it can lead to the following situation:
2981 // injectglist grabs all P's but before it starts M's to run the P's,
2982 // another M returns from syscall, finishes running its G,
2983 // observes that there is no work to do and no other running M's
2984 // and reports deadlock.
2990 // retake P's blocked in syscalls
2991 // and preempt long running G's
2997 if(runtime_debug
.schedtrace
> 0 && lasttrace
+ runtime_debug
.schedtrace
*1000000ll <= now
) {
2999 runtime_schedtrace(runtime_debug
.scheddetail
);
3004 typedef struct Pdesc Pdesc
;
3012 static Pdesc pdesc
[_MaxGomaxprocs
];
3023 for(i
= 0; i
< (uint32
)runtime_gomaxprocs
; i
++) {
3024 p
= runtime_allp
[i
];
3029 if(s
== _Psyscall
) {
3030 // Retake P from syscall if it's there for more than 1 sysmon tick (at least 20us).
3032 if(pd
->syscalltick
!= t
) {
3033 pd
->syscalltick
= t
;
3034 pd
->syscallwhen
= now
;
3037 // On the one hand we don't want to retake Ps if there is no other work to do,
3038 // but on the other hand we want to retake them eventually
3039 // because they can prevent the sysmon thread from deep sleep.
3040 if(p
->runqhead
== p
->runqtail
&&
3041 runtime_atomicload(&runtime_sched
->nmspinning
) + runtime_atomicload(&runtime_sched
->npidle
) > 0 &&
3042 pd
->syscallwhen
+ 10*1000*1000 > now
)
3044 // Need to decrement number of idle locked M's
3045 // (pretending that one more is running) before the CAS.
3046 // Otherwise the M from which we retake can exit the syscall,
3047 // increment nmidle and report deadlock.
3049 if(runtime_cas(&p
->status
, s
, _Pidle
)) {
3054 } else if(s
== _Prunning
) {
3055 // Preempt G if it's running for more than 10ms.
3057 if(pd
->schedtick
!= t
) {
3059 pd
->schedwhen
= now
;
3062 if(pd
->schedwhen
+ 10*1000*1000 > now
)
3070 // Tell all goroutines that they have been preempted and they should stop.
3071 // This function is purely best-effort. It can fail to inform a goroutine if a
3072 // processor just started running it.
3073 // No locks need to be held.
3074 // Returns true if preemption request was issued to at least one goroutine.
3082 runtime_schedtrace(bool detailed
)
3084 static int64 starttime
;
3086 int64 id1
, id2
, id3
;
3094 now
= runtime_nanotime();
3098 runtime_lock(&runtime_sched
->lock
);
3099 runtime_printf("SCHED %Dms: gomaxprocs=%d idleprocs=%d threads=%d idlethreads=%d runqueue=%d",
3100 (now
-starttime
)/1000000, runtime_gomaxprocs
, runtime_sched
->npidle
, runtime_sched
->mcount
,
3101 runtime_sched
->nmidle
, runtime_sched
->runqsize
);
3103 runtime_printf(" gcwaiting=%d nmidlelocked=%d nmspinning=%d stopwait=%d sysmonwait=%d\n",
3104 runtime_sched
->gcwaiting
, runtime_sched
->nmidlelocked
, runtime_sched
->nmspinning
,
3105 runtime_sched
->stopwait
, runtime_sched
->sysmonwait
);
3107 // We must be careful while reading data from P's, M's and G's.
3108 // Even if we hold schedlock, most data can be changed concurrently.
3109 // E.g. (p->m ? p->m->id : -1) can crash if p->m changes from non-nil to nil.
3110 for(i
= 0; i
< runtime_gomaxprocs
; i
++) {
3111 p
= runtime_allp
[i
];
3115 h
= runtime_atomicload(&p
->runqhead
);
3116 t
= runtime_atomicload(&p
->runqtail
);
3118 runtime_printf(" P%d: status=%d schedtick=%d syscalltick=%d m=%d runqsize=%d gfreecnt=%d\n",
3119 i
, p
->status
, p
->schedtick
, p
->syscalltick
, mp
? mp
->id
: -1, t
-h
, p
->gfreecnt
);
3121 // In non-detailed mode format lengths of per-P run queues as:
3122 // [len1 len2 len3 len4]
3124 if(runtime_gomaxprocs
== 1)
3128 else if(i
== runtime_gomaxprocs
-1)
3130 runtime_printf(fmt
, t
-h
);
3134 runtime_unlock(&runtime_sched
->lock
);
3137 for(mp
= runtime_allm
; mp
; mp
= mp
->alllink
) {
3140 lockedg
= mp
->lockedg
;
3149 id3
= lockedg
->goid
;
3150 runtime_printf(" M%d: p=%D curg=%D mallocing=%d throwing=%d gcing=%d"
3151 " locks=%d dying=%d helpgc=%d spinning=%d blocked=%d lockedg=%D\n",
3153 mp
->mallocing
, mp
->throwing
, mp
->gcing
, mp
->locks
, mp
->dying
, mp
->helpgc
,
3154 mp
->spinning
, mp
->blocked
, id3
);
3156 runtime_lock(&allglock
);
3157 for(gi
= 0; gi
< runtime_allglen
; gi
++) {
3158 gp
= runtime_allg
[gi
];
3160 lockedm
= gp
->lockedm
;
3161 runtime_printf(" G%D: status=%d(%S) m=%d lockedm=%d\n",
3162 gp
->goid
, gp
->atomicstatus
, gp
->waitreason
, mp
? mp
->id
: -1,
3163 lockedm
? lockedm
->id
: -1);
3165 runtime_unlock(&allglock
);
3166 runtime_unlock(&runtime_sched
->lock
);
3169 // Put mp on midle list.
3170 // Sched must be locked.
3174 mp
->schedlink
= runtime_sched
->midle
;
3175 runtime_sched
->midle
= (uintptr
)mp
;
3176 runtime_sched
->nmidle
++;
3180 // Try to get an m from midle list.
3181 // Sched must be locked.
3187 if((mp
= (M
*)runtime_sched
->midle
) != nil
){
3188 runtime_sched
->midle
= mp
->schedlink
;
3189 runtime_sched
->nmidle
--;
3194 // Put gp on the global runnable queue.
3195 // Sched must be locked.
3200 if(runtime_sched
->runqtail
)
3201 ((G
*)runtime_sched
->runqtail
)->schedlink
= (uintptr
)gp
;
3203 runtime_sched
->runqhead
= (uintptr
)gp
;
3204 runtime_sched
->runqtail
= (uintptr
)gp
;
3205 runtime_sched
->runqsize
++;
3208 // Put a batch of runnable goroutines on the global runnable queue.
3209 // Sched must be locked.
3211 globrunqputbatch(G
*ghead
, G
*gtail
, int32 n
)
3213 gtail
->schedlink
= 0;
3214 if(runtime_sched
->runqtail
)
3215 ((G
*)runtime_sched
->runqtail
)->schedlink
= (uintptr
)ghead
;
3217 runtime_sched
->runqhead
= (uintptr
)ghead
;
3218 runtime_sched
->runqtail
= (uintptr
)gtail
;
3219 runtime_sched
->runqsize
+= n
;
3222 // Try get a batch of G's from the global runnable queue.
3223 // Sched must be locked.
3225 globrunqget(P
*p
, int32 max
)
3230 if(runtime_sched
->runqsize
== 0)
3232 n
= runtime_sched
->runqsize
/runtime_gomaxprocs
+1;
3233 if(n
> runtime_sched
->runqsize
)
3234 n
= runtime_sched
->runqsize
;
3235 if(max
> 0 && n
> max
)
3237 if((uint32
)n
> nelem(p
->runq
)/2)
3238 n
= nelem(p
->runq
)/2;
3239 runtime_sched
->runqsize
-= n
;
3240 if(runtime_sched
->runqsize
== 0)
3241 runtime_sched
->runqtail
= 0;
3242 gp
= (G
*)runtime_sched
->runqhead
;
3243 runtime_sched
->runqhead
= gp
->schedlink
;
3246 gp1
= (G
*)runtime_sched
->runqhead
;
3247 runtime_sched
->runqhead
= gp1
->schedlink
;
3253 // Put p to on pidle list.
3254 // Sched must be locked.
3258 p
->link
= runtime_sched
->pidle
;
3259 runtime_sched
->pidle
= (uintptr
)p
;
3260 runtime_xadd(&runtime_sched
->npidle
, 1); // TODO: fast atomic
3263 // Try get a p from pidle list.
3264 // Sched must be locked.
3270 p
= (P
*)runtime_sched
->pidle
;
3272 runtime_sched
->pidle
= p
->link
;
3273 runtime_xadd(&runtime_sched
->npidle
, -1); // TODO: fast atomic
3278 // Try to put g on local runnable queue.
3279 // If it's full, put onto global queue.
3280 // Executed only by the owner P.
3282 runqput(P
*p
, G
*gp
)
3287 h
= runtime_atomicload(&p
->runqhead
); // load-acquire, synchronize with consumers
3289 if(t
- h
< nelem(p
->runq
)) {
3290 p
->runq
[t
%nelem(p
->runq
)] = (uintptr
)gp
;
3291 runtime_atomicstore(&p
->runqtail
, t
+1); // store-release, makes the item available for consumption
3294 if(runqputslow(p
, gp
, h
, t
))
3296 // the queue is not full, now the put above must suceed
3300 // Put g and a batch of work from local runnable queue on global queue.
3301 // Executed only by the owner P.
3303 runqputslow(P
*p
, G
*gp
, uint32 h
, uint32 t
)
3305 G
*batch
[nelem(p
->runq
)/2+1];
3308 // First, grab a batch from local queue.
3311 if(n
!= nelem(p
->runq
)/2)
3312 runtime_throw("runqputslow: queue is not full");
3314 batch
[i
] = (G
*)p
->runq
[(h
+i
)%nelem(p
->runq
)];
3315 if(!runtime_cas(&p
->runqhead
, h
, h
+n
)) // cas-release, commits consume
3318 // Link the goroutines.
3320 batch
[i
]->schedlink
= (uintptr
)batch
[i
+1];
3321 // Now put the batch on global queue.
3322 runtime_lock(&runtime_sched
->lock
);
3323 globrunqputbatch(batch
[0], batch
[n
], n
+1);
3324 runtime_unlock(&runtime_sched
->lock
);
3328 // Get g from local runnable queue.
3329 // Executed only by the owner P.
3337 h
= runtime_atomicload(&p
->runqhead
); // load-acquire, synchronize with other consumers
3341 gp
= (G
*)p
->runq
[h
%nelem(p
->runq
)];
3342 if(runtime_cas(&p
->runqhead
, h
, h
+1)) // cas-release, commits consume
3347 // Grabs a batch of goroutines from local runnable queue.
3348 // batch array must be of size nelem(p->runq)/2. Returns number of grabbed goroutines.
3349 // Can be executed by any P.
3351 runqgrab(P
*p
, G
**batch
)
3356 h
= runtime_atomicload(&p
->runqhead
); // load-acquire, synchronize with other consumers
3357 t
= runtime_atomicload(&p
->runqtail
); // load-acquire, synchronize with the producer
3362 if(n
> nelem(p
->runq
)/2) // read inconsistent h and t
3365 batch
[i
] = (G
*)p
->runq
[(h
+i
)%nelem(p
->runq
)];
3366 if(runtime_cas(&p
->runqhead
, h
, h
+n
)) // cas-release, commits consume
3372 // Steal half of elements from local runnable queue of p2
3373 // and put onto local runnable queue of p.
3374 // Returns one of the stolen elements (or nil if failed).
3376 runqsteal(P
*p
, P
*p2
)
3379 G
*batch
[nelem(p
->runq
)/2];
3382 n
= runqgrab(p2
, batch
);
3389 h
= runtime_atomicload(&p
->runqhead
); // load-acquire, synchronize with consumers
3391 if(t
- h
+ n
>= nelem(p
->runq
))
3392 runtime_throw("runqsteal: runq overflow");
3393 for(i
=0; i
<n
; i
++, t
++)
3394 p
->runq
[t
%nelem(p
->runq
)] = (uintptr
)batch
[i
];
3395 runtime_atomicstore(&p
->runqtail
, t
); // store-release, makes the item available for consumption
3399 void runtime_testSchedLocalQueue(void)
3400 __asm__("runtime.testSchedLocalQueue");
3403 runtime_testSchedLocalQueue(void)
3406 G gs
[nelem(p
.runq
)];
3409 runtime_memclr((byte
*)&p
, sizeof(p
));
3411 for(i
= 0; i
< (int32
)nelem(gs
); i
++) {
3412 if(runqget(&p
) != nil
)
3413 runtime_throw("runq is not empty initially");
3414 for(j
= 0; j
< i
; j
++)
3415 runqput(&p
, &gs
[i
]);
3416 for(j
= 0; j
< i
; j
++) {
3417 if(runqget(&p
) != &gs
[i
]) {
3418 runtime_printf("bad element at iter %d/%d\n", i
, j
);
3419 runtime_throw("bad element");
3422 if(runqget(&p
) != nil
)
3423 runtime_throw("runq is not empty afterwards");
3427 void runtime_testSchedLocalQueueSteal(void)
3428 __asm__("runtime.testSchedLocalQueueSteal");
3431 runtime_testSchedLocalQueueSteal(void)
3434 G gs
[nelem(p1
.runq
)], *gp
;
3437 runtime_memclr((byte
*)&p1
, sizeof(p1
));
3438 runtime_memclr((byte
*)&p2
, sizeof(p2
));
3440 for(i
= 0; i
< (int32
)nelem(gs
); i
++) {
3441 for(j
= 0; j
< i
; j
++) {
3443 runqput(&p1
, &gs
[j
]);
3445 gp
= runqsteal(&p2
, &p1
);
3451 while((gp
= runqget(&p2
)) != nil
) {
3455 while((gp
= runqget(&p1
)) != nil
)
3457 for(j
= 0; j
< i
; j
++) {
3458 if(gs
[j
].sig
!= 1) {
3459 runtime_printf("bad element %d(%d) at iter %d\n", j
, gs
[j
].sig
, i
);
3460 runtime_throw("bad element");
3463 if(s
!= i
/2 && s
!= i
/2+1) {
3464 runtime_printf("bad steal %d, want %d or %d, iter %d\n",
3466 runtime_throw("bad steal");
3472 runtime_setmaxthreads(intgo in
)
3476 runtime_lock(&runtime_sched
->lock
);
3477 out
= (intgo
)runtime_sched
->maxmcount
;
3478 runtime_sched
->maxmcount
= (int32
)in
;
3480 runtime_unlock(&runtime_sched
->lock
);
3491 return (intgo
)(((P
*)mp
->p
)->id
);
3497 runtime_m()->locks
--;
3500 intgo
sync_runtime_procPin(void)
3501 __asm__ (GOSYM_PREFIX
"sync.runtime_procPin");
3504 sync_runtime_procPin()
3509 void sync_runtime_procUnpin(void)
3510 __asm__ (GOSYM_PREFIX
"sync.runtime_procUnpin");
3513 sync_runtime_procUnpin()
3518 intgo
sync_atomic_runtime_procPin(void)
3519 __asm__ (GOSYM_PREFIX
"sync_atomic.runtime_procPin");
3522 sync_atomic_runtime_procPin()
3527 void sync_atomic_runtime_procUnpin(void)
3528 __asm__ (GOSYM_PREFIX
"sync_atomic.runtime_procUnpin");
3531 sync_atomic_runtime_procUnpin()
3537 runtime_proc_scan(struct Workbuf
** wbufp
, void (*enqueue1
)(struct Workbuf
**, Obj
))
3539 enqueue1(wbufp
, (Obj
){(byte
*)&runtime_main_init_done
, sizeof runtime_main_init_done
, 0});
3542 // Return whether we are waiting for a GC. This gc toolchain uses
3543 // preemption instead.
3545 runtime_gcwaiting(void)
3547 return runtime_sched
->gcwaiting
;
3550 // os_beforeExit is called from os.Exit(0).
3551 //go:linkname os_beforeExit os.runtime_beforeExit
3553 extern void os_beforeExit() __asm__ (GOSYM_PREFIX
"os.runtime_beforeExit");
3560 // Active spinning for sync.Mutex.
3561 //go:linkname sync_runtime_canSpin sync.runtime_canSpin
3566 ACTIVE_SPIN_CNT
= 30,
3569 extern _Bool
sync_runtime_canSpin(intgo i
)
3570 __asm__ (GOSYM_PREFIX
"sync.runtime_canSpin");
3573 sync_runtime_canSpin(intgo i
)
3577 // sync.Mutex is cooperative, so we are conservative with spinning.
3578 // Spin only few times and only if running on a multicore machine and
3579 // GOMAXPROCS>1 and there is at least one other running P and local runq is empty.
3580 // As opposed to runtime mutex we don't do passive spinning here,
3581 // because there can be work on global runq on on other Ps.
3582 if (i
>= ACTIVE_SPIN
|| runtime_ncpu
<= 1 || runtime_gomaxprocs
<= (int32
)(runtime_sched
->npidle
+runtime_sched
->nmspinning
)+1) {
3586 return p
!= nil
&& p
->runqhead
== p
->runqtail
;
3589 //go:linkname sync_runtime_doSpin sync.runtime_doSpin
3592 extern void sync_runtime_doSpin(void)
3593 __asm__ (GOSYM_PREFIX
"sync.runtime_doSpin");
3596 sync_runtime_doSpin()
3598 runtime_procyield(ACTIVE_SPIN_CNT
);
3601 // For Go code to look at variables, until we port proc.go.
3603 extern M
** runtime_go_allm(void)
3604 __asm__ (GOSYM_PREFIX
"runtime.allm");
3609 return &runtime_allm
;
3612 extern Slice
runtime_go_allgs(void)
3613 __asm__ (GOSYM_PREFIX
"runtime.allgs");
3620 s
.__values
= runtime_allg
;
3621 s
.__count
= runtime_allglen
;
3622 s
.__capacity
= allgcap
;
3626 intgo
NumCPU(void) __asm__ (GOSYM_PREFIX
"runtime.NumCPU");
3631 return (intgo
)(runtime_ncpu
);