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.
14 #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_releasecontext(void *context
[10]);
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 ((sizeof(char *) < 8) ? 2 * 1024 * 1024 : 4 * 1024 * 1024)
57 uintptr runtime_stacks_sys
;
60 __asm__(GOSYM_PREFIX
"runtime.gtraceback");
62 static void gscanstack(G
*);
70 #ifndef SETCONTEXT_CLOBBERS_TLS
78 fixcontext(ucontext_t
*c
__attribute__ ((unused
)))
84 # if defined(__x86_64__) && defined(__sun__)
86 // x86_64 Solaris 10 and 11 have a bug: setcontext switches the %fs
87 // register to that of the thread which called getcontext. The effect
88 // is that the address of all __thread variables changes. This bug
89 // also affects pthread_self() and pthread_getspecific. We work
90 // around it by clobbering the context field directly to keep %fs the
93 static __thread greg_t fs
;
101 fs
= c
.uc_mcontext
.gregs
[REG_FSBASE
];
105 fixcontext(ucontext_t
* c
)
107 c
->uc_mcontext
.gregs
[REG_FSBASE
] = fs
;
110 # elif defined(__NetBSD__)
112 // NetBSD has a bug: setcontext clobbers tlsbase, we need to save
113 // and restore it ourselves.
115 static __thread __greg_t tlsbase
;
123 tlsbase
= c
.uc_mcontext
._mc_tlsbase
;
127 fixcontext(ucontext_t
* c
)
129 c
->uc_mcontext
._mc_tlsbase
= tlsbase
;
132 # elif defined(__sparc__)
140 fixcontext(ucontext_t
*c
)
143 register unsigned long thread __asm__("%g7");
144 c->uc_mcontext.gregs[REG_G7] = thread;
146 error: variable ‘thread’ might be clobbered by \
147 ‘longjmp’ or ‘vfork’ [-Werror=clobbered]
148 which ought to be false, as %g7 is a fixed register. */
150 if (sizeof (c
->uc_mcontext
.gregs
[REG_G7
]) == 8)
151 asm ("stx %%g7, %0" : "=m"(c
->uc_mcontext
.gregs
[REG_G7
]));
153 asm ("st %%g7, %0" : "=m"(c
->uc_mcontext
.gregs
[REG_G7
]));
164 fixcontext(ucontext_t
* c
)
166 // Thread pointer is in r13, per 64-bit ABI.
167 if (sizeof (c
->uc_mcontext
.jmp_context
.gpr
[13]) == 8)
168 asm ("std 13, %0" : "=m"(c
->uc_mcontext
.jmp_context
.gpr
[13]));
173 # error unknown case for SETCONTEXT_CLOBBERS_TLS
179 // ucontext_arg returns a properly aligned ucontext_t value. On some
180 // systems a ucontext_t value must be aligned to a 16-byte boundary.
181 // The g structure that has fields of type ucontext_t is defined in
182 // Go, and Go has no simple way to align a field to such a boundary.
183 // So we make the field larger in runtime2.go and pick an appropriate
184 // offset within the field here.
186 ucontext_arg(uintptr_t* go_ucontext
)
188 uintptr_t p
= (uintptr_t)go_ucontext
;
189 size_t align
= __alignof__(ucontext_t
);
191 // We only ensured space for up to a 16 byte alignment
192 // in libgo/go/runtime/runtime2.go.
193 runtime_throw("required alignment of ucontext_t too large");
195 p
= (p
+ align
- 1) &~ (uintptr_t)(align
- 1);
196 return (ucontext_t
*)p
;
199 // We can not always refer to the TLS variables directly. The
200 // compiler will call tls_get_addr to get the address of the variable,
201 // and it may hold it in a register across a call to schedule. When
202 // we get back from the call we may be running in a different thread,
203 // in which case the register now points to the TLS variable for a
204 // different thread. We use non-inlinable functions to avoid this
207 G
* runtime_g(void) __attribute__ ((noinline
, no_split_stack
));
215 M
* runtime_m(void) __attribute__ ((noinline
, no_split_stack
));
232 void runtime_newosproc(M
*)
233 __asm__(GOSYM_PREFIX
"runtime.newosproc");
235 // Start a new thread.
237 runtime_newosproc(M
*mp
)
245 if(pthread_attr_init(&attr
) != 0)
246 runtime_throw("pthread_attr_init");
247 if(pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0)
248 runtime_throw("pthread_attr_setdetachstate");
250 // Block signals during pthread_create so that the new thread
251 // starts with signals disabled. It will enable them in minit.
255 // Blocking SIGTRAP reportedly breaks gdb on Alpha GNU/Linux.
256 sigdelset(&clear
, SIGTRAP
);
260 pthread_sigmask(SIG_BLOCK
, &clear
, &old
);
262 for (tries
= 0; tries
< 20; tries
++) {
263 ret
= pthread_create(&tid
, &attr
, runtime_mstart
, mp
);
267 runtime_usleep((tries
+ 1) * 1000); // Milliseconds.
270 pthread_sigmask(SIG_SETMASK
, &old
, nil
);
273 runtime_printf("pthread_create failed: %d\n", ret
);
274 runtime_throw("pthread_create");
277 if(pthread_attr_destroy(&attr
) != 0)
278 runtime_throw("pthread_attr_destroy");
281 // Switch context to a different goroutine. This is like longjmp.
282 void runtime_gogo(G
*) __attribute__ ((noinline
));
284 runtime_gogo(G
* newg
)
286 #ifdef USING_SPLIT_STACK
287 __splitstack_setcontext((void*)(&newg
->stackcontext
[0]));
290 newg
->fromgogo
= true;
291 fixcontext(ucontext_arg(&newg
->context
[0]));
292 setcontext(ucontext_arg(&newg
->context
[0]));
293 runtime_throw("gogo setcontext returned");
296 // Save context and call fn passing g as a parameter. This is like
297 // setjmp. Because getcontext always returns 0, unlike setjmp, we use
298 // g->fromgogo as a code. It will be true if we got here via
299 // setcontext. g == nil the first time this is called in a new m.
300 void runtime_mcall(FuncVal
*) __attribute__ ((noinline
));
302 runtime_mcall(FuncVal
*fv
)
306 #ifndef USING_SPLIT_STACK
310 // Ensure that all registers are on the stack for the garbage
312 __builtin_unwind_init();
313 flush_registers_to_secondary_stack();
318 runtime_throw("runtime: mcall called on m->g0 stack");
322 #ifdef USING_SPLIT_STACK
323 __splitstack_getcontext((void*)(&g
->stackcontext
[0]));
325 // We have to point to an address on the stack that is
326 // below the saved registers.
327 gp
->gcnextsp
= (uintptr
)(&afterregs
);
328 gp
->gcnextsp2
= (uintptr
)(secondary_stack_pointer());
330 gp
->fromgogo
= false;
331 getcontext(ucontext_arg(&gp
->context
[0]));
333 // When we return from getcontext, we may be running
334 // in a new thread. That means that g may have
335 // changed. It is a global variables so we will
336 // reload it, but the address of g may be cached in
337 // our local stack frame, and that address may be
338 // wrong. Call the function to reload the value for
343 if(gp
->traceback
!= 0)
348 if (gp
== nil
|| !gp
->fromgogo
) {
349 #ifdef USING_SPLIT_STACK
350 __splitstack_setcontext((void*)(&mp
->g0
->stackcontext
[0]));
355 // It's OK to set g directly here because this case
356 // can not occur if we got here via a setcontext to
357 // the getcontext call just above.
360 fixcontext(ucontext_arg(&mp
->g0
->context
[0]));
361 setcontext(ucontext_arg(&mp
->g0
->context
[0]));
362 runtime_throw("runtime: mcall function returned");
366 // Goroutine scheduler
367 // The scheduler's job is to distribute ready-to-run goroutines over worker threads.
369 // The main concepts are:
371 // M - worker thread, or machine.
372 // P - processor, a resource that is required to execute Go code.
373 // M must have an associated P to execute Go code, however it can be
374 // blocked or in a syscall w/o an associated P.
376 // Design doc at http://golang.org/s/go11sched.
378 extern G
* allocg(void)
379 __asm__ (GOSYM_PREFIX
"runtime.allocg");
381 Sched
* runtime_sched
;
383 bool runtime_isarchive
;
385 extern void kickoff(void)
386 __asm__(GOSYM_PREFIX
"runtime.kickoff");
387 extern void minit(void)
388 __asm__(GOSYM_PREFIX
"runtime.minit");
389 extern void mstart1()
390 __asm__(GOSYM_PREFIX
"runtime.mstart1");
391 extern void stopm(void)
392 __asm__(GOSYM_PREFIX
"runtime.stopm");
393 extern void mexit(bool)
394 __asm__(GOSYM_PREFIX
"runtime.mexit");
395 extern void handoffp(P
*)
396 __asm__(GOSYM_PREFIX
"runtime.handoffp");
397 extern void wakep(void)
398 __asm__(GOSYM_PREFIX
"runtime.wakep");
399 extern void stoplockedm(void)
400 __asm__(GOSYM_PREFIX
"runtime.stoplockedm");
401 extern void schedule(void)
402 __asm__(GOSYM_PREFIX
"runtime.schedule");
403 extern void execute(G
*, bool)
404 __asm__(GOSYM_PREFIX
"runtime.execute");
405 extern void reentersyscall(uintptr
, uintptr
)
406 __asm__(GOSYM_PREFIX
"runtime.reentersyscall");
407 extern void reentersyscallblock(uintptr
, uintptr
)
408 __asm__(GOSYM_PREFIX
"runtime.reentersyscallblock");
410 __asm__(GOSYM_PREFIX
"runtime.gfget");
411 extern void acquirep(P
*)
412 __asm__(GOSYM_PREFIX
"runtime.acquirep");
413 extern P
* releasep(void)
414 __asm__(GOSYM_PREFIX
"runtime.releasep");
415 extern void incidlelocked(int32
)
416 __asm__(GOSYM_PREFIX
"runtime.incidlelocked");
417 extern void globrunqput(G
*)
418 __asm__(GOSYM_PREFIX
"runtime.globrunqput");
419 extern P
* pidleget(void)
420 __asm__(GOSYM_PREFIX
"runtime.pidleget");
421 extern struct mstats
* getMemstats(void)
422 __asm__(GOSYM_PREFIX
"runtime.getMemstats");
424 bool runtime_isstarted
;
426 // Used to determine the field alignment.
434 void getTraceback(G
*, G
*) __asm__(GOSYM_PREFIX
"runtime.getTraceback");
436 // getTraceback stores a traceback of gp in the g's traceback field
437 // and then returns to me. We expect that gp's traceback is not nil.
438 // It works by saving me's current context, and checking gp's traceback field.
439 // If gp's traceback field is not nil, it starts running gp.
440 // In places where we call getcontext, we check the traceback field.
441 // If it is not nil, we collect a traceback, and then return to the
442 // goroutine stored in the traceback field, which is me.
443 void getTraceback(G
* me
, G
* gp
)
450 #ifdef USING_SPLIT_STACK
451 __splitstack_getcontext((void*)(&me
->stackcontext
[0]));
453 getcontext(ucontext_arg(&me
->context
[0]));
455 if (gp
->traceback
!= 0) {
462 // Do a stack trace of gp, and then restore the context to
463 // gp->traceback->gp.
468 Traceback
* traceback
;
470 traceback
= (Traceback
*)gp
->traceback
;
472 traceback
->c
= runtime_callers(1, traceback
->locbuf
,
473 sizeof traceback
->locbuf
/ sizeof traceback
->locbuf
[0], false);
474 runtime_gogo(traceback
->gp
);
477 void doscanstackswitch(G
*, G
*) __asm__(GOSYM_PREFIX
"runtime.doscanstackswitch");
479 // Switch to gp and let it scan its stack.
480 // The first time gp->scang is set (to me). The second time here
481 // gp is done scanning, and has unset gp->scang, so we just return.
483 doscanstackswitch(G
* me
, G
* gp
)
487 __go_assert(me
->entry
== nil
);
488 me
->fromgogo
= false;
493 #ifdef USING_SPLIT_STACK
494 __splitstack_getcontext((void*)(&me
->stackcontext
[0]));
496 getcontext(ucontext_arg(&me
->context
[0]));
498 if(me
->entry
!= nil
) {
499 // Got here from mcall.
500 // The stack scanning code may call systemstack, which calls
501 // mcall, which calls setcontext.
502 // Run the function, which at the end will switch back to gp.
503 FuncVal
*fv
= me
->entry
;
504 void (*pfn
)(G
*) = (void (*)(G
*))fv
->fn
;
505 G
* gp1
= (G
*)me
->param
;
506 __go_assert(gp1
== gp
);
509 __builtin_call_with_static_chain(pfn(gp1
), fv
);
519 // Do a stack scan, then switch back to the g that triggers this scan.
520 // We come here from doscanstackswitch.
526 oldg
= (G
*)gp
->scang
;
527 oldcurg
= oldg
->m
->curg
;
531 doscanstack(gp
, (void*)gp
->scangcw
);
534 oldg
->m
->curg
= oldcurg
;
538 // Called by pthread_create to start an M.
540 runtime_mstart(void *arg
)
554 // We have to call minit before we call getcontext,
555 // because getcontext will copy the signal mask.
560 // Record top of stack for use by mcall.
561 // Once we call schedule we're never coming back,
562 // so other calls can reuse this stack space.
563 #ifdef USING_SPLIT_STACK
564 __splitstack_getcontext((void*)(&gp
->stackcontext
[0]));
566 gp
->gcinitialsp
= &arg
;
567 // Setting gcstacksize to 0 is a marker meaning that gcinitialsp
568 // is the top of the stack, not the bottom.
570 gp
->gcnextsp
= (uintptr
)(&arg
);
571 gp
->gcinitialsp2
= secondary_stack_pointer();
572 gp
->gcnextsp2
= (uintptr
)(gp
->gcinitialsp2
);
575 // Save the currently active context. This will return
576 // multiple times via the setcontext call in mcall.
577 getcontext(ucontext_arg(&gp
->context
[0]));
579 if(gp
->traceback
!= 0) {
580 // Got here from getTraceback.
581 // I'm not sure this ever actually happens--getTraceback
582 // may always go to the getcontext call in mcall.
586 // Got here from doscanswitch. Should not happen.
587 runtime_throw("mstart with scang");
589 if(gp
->entry
!= nil
) {
590 // Got here from mcall.
591 FuncVal
*fv
= gp
->entry
;
592 void (*pfn
)(G
*) = (void (*)(G
*))fv
->fn
;
593 G
* gp1
= (G
*)gp
->param
;
596 __builtin_call_with_static_chain(pfn(gp1
), fv
);
605 // Initial call to getcontext--starting thread.
607 #ifdef USING_SPLIT_STACK
609 int dont_block_signals
= 0;
610 __splitstack_block_signals(&dont_block_signals
, nil
);
616 // mstart1 does not return, but we need a return statement
617 // here to avoid a compiler warning.
621 typedef struct CgoThreadStart CgoThreadStart
;
622 struct CgoThreadStart
630 void setGContext(void) __asm__ (GOSYM_PREFIX
"runtime.setGContext");
632 // setGContext sets up a new goroutine context for the current g.
643 #ifdef USING_SPLIT_STACK
644 __splitstack_getcontext((void*)(&gp
->stackcontext
[0]));
646 __splitstack_block_signals(&val
, nil
);
648 gp
->gcinitialsp
= &val
;
651 gp
->gcnextsp
= (uintptr
)(&val
);
652 gp
->gcinitialsp2
= secondary_stack_pointer();
653 gp
->gcnextsp2
= (uintptr
)(gp
->gcinitialsp2
);
655 getcontext(ucontext_arg(&gp
->context
[0]));
657 if(gp
->entry
!= nil
) {
658 // Got here from mcall.
659 FuncVal
*fv
= gp
->entry
;
660 void (*pfn
)(G
*) = (void (*)(G
*))fv
->fn
;
661 G
* gp1
= (G
*)gp
->param
;
664 __builtin_call_with_static_chain(pfn(gp1
), fv
);
669 void makeGContext(G
*, byte
*, uintptr
)
670 __asm__(GOSYM_PREFIX
"runtime.makeGContext");
672 // makeGContext makes a new context for a g.
674 makeGContext(G
* gp
, byte
* sp
, uintptr spsize
) {
677 uc
= ucontext_arg(&gp
->context
[0]);
679 uc
->uc_stack
.ss_sp
= sp
;
680 uc
->uc_stack
.ss_size
= (size_t)spsize
;
681 makecontext(uc
, kickoff
, 0);
684 // The goroutine g is about to enter a system call.
685 // Record that it's not using the cpu anymore.
686 // This is called only from the go syscall library and cgocall,
687 // not from the low-level system calls used by the runtime.
689 // Entersyscall cannot split the stack: the runtime_gosave must
690 // make g->sched refer to the caller's stack segment, because
691 // entersyscall is going to return immediately after.
693 void runtime_entersyscall() __attribute__ ((no_split_stack
));
694 static void doentersyscall(uintptr
, uintptr
)
695 __attribute__ ((no_split_stack
, noinline
));
698 runtime_entersyscall()
700 // Save the registers in the g structure so that any pointers
701 // held in registers will be seen by the garbage collector.
702 if (!runtime_usestackmaps
)
703 getcontext(ucontext_arg(&g
->gcregs
[0]));
705 // Note that if this function does save any registers itself,
706 // we might store the wrong value in the call to getcontext.
707 // FIXME: This assumes that we do not need to save any
708 // callee-saved registers to access the TLS variable g. We
709 // don't want to put the ucontext_t on the stack because it is
710 // large and we can not split the stack here.
711 doentersyscall((uintptr
)runtime_getcallerpc(),
712 (uintptr
)runtime_getcallersp());
716 doentersyscall(uintptr pc
, uintptr sp
)
718 // Leave SP around for GC and traceback.
719 #ifdef USING_SPLIT_STACK
722 g
->gcstack
= (uintptr
)(__splitstack_find(nil
, nil
, &gcstacksize
,
723 (void**)(&g
->gcnextsegment
),
724 (void**)(&g
->gcnextsp
),
726 g
->gcstacksize
= (uintptr
)gcstacksize
;
732 g
->gcnextsp
= (uintptr
)(&v
);
733 g
->gcnextsp2
= (uintptr
)(secondary_stack_pointer());
737 reentersyscall(pc
, sp
);
740 static void doentersyscallblock(uintptr
, uintptr
)
741 __attribute__ ((no_split_stack
, noinline
));
743 // The same as runtime_entersyscall(), but with a hint that the syscall is blocking.
745 runtime_entersyscallblock()
747 // Save the registers in the g structure so that any pointers
748 // held in registers will be seen by the garbage collector.
749 if (!runtime_usestackmaps
)
750 getcontext(ucontext_arg(&g
->gcregs
[0]));
752 // See comment in runtime_entersyscall.
753 doentersyscallblock((uintptr
)runtime_getcallerpc(),
754 (uintptr
)runtime_getcallersp());
758 doentersyscallblock(uintptr pc
, uintptr sp
)
760 // Leave SP around for GC and traceback.
761 #ifdef USING_SPLIT_STACK
764 g
->gcstack
= (uintptr
)(__splitstack_find(nil
, nil
, &gcstacksize
,
765 (void**)(&g
->gcnextsegment
),
766 (void**)(&g
->gcnextsp
),
768 g
->gcstacksize
= (uintptr
)gcstacksize
;
774 g
->gcnextsp
= (uintptr
)(&v
);
775 g
->gcnextsp2
= (uintptr
)(secondary_stack_pointer());
779 reentersyscallblock(pc
, sp
);
782 // Allocate a new g, with a stack big enough for stacksize bytes.
784 runtime_malg(bool allocatestack
, bool signalstack
, byte
** ret_stack
, uintptr
* ret_stacksize
)
789 uintptr unused_stacksize
;
790 #ifdef USING_SPLIT_STACK
791 int dont_block_signals
= 0;
795 if (ret_stack
== nil
) {
796 ret_stack
= &unused_stack
;
798 if (ret_stacksize
== nil
) {
799 ret_stacksize
= &unused_stacksize
;
803 stacksize
= StackMin
;
805 stacksize
= 32 * 1024; // OS X wants >= 8K, GNU/Linux >= 2K
807 if(stacksize
< SIGSTKSZ
)
808 stacksize
= SIGSTKSZ
;
812 #ifdef USING_SPLIT_STACK
813 *ret_stack
= __splitstack_makecontext(stacksize
,
814 (void*)(&newg
->stackcontext
[0]),
816 *ret_stacksize
= (uintptr
)ss_stacksize
;
817 __splitstack_block_signals_context((void*)(&newg
->stackcontext
[0]),
818 &dont_block_signals
, nil
);
820 // In 64-bit mode, the maximum Go allocation space is
821 // 128G. Our stack size is 4M, which only permits 32K
822 // goroutines. In order to not limit ourselves,
823 // allocate the stacks out of separate memory. In
824 // 32-bit mode, the Go allocation space is all of
826 if(sizeof(void*) == 8) {
827 void *p
= runtime_sysAlloc(stacksize
, &getMemstats()->stacks_sys
);
829 runtime_throw("runtime: cannot allocate memory for goroutine stack");
830 *ret_stack
= (byte
*)p
;
832 *ret_stack
= runtime_mallocgc(stacksize
, nil
, false);
833 runtime_xadd(&runtime_stacks_sys
, stacksize
);
835 *ret_stacksize
= (uintptr
)stacksize
;
836 newg
->gcinitialsp
= *ret_stack
;
837 newg
->gcstacksize
= (uintptr
)stacksize
;
838 newg
->gcinitialsp2
= initial_secondary_stack_pointer(*ret_stack
);
845 __asm__(GOSYM_PREFIX
"runtime.stackfree");
847 // stackfree frees the stack of a g.
851 #ifdef USING_SPLIT_STACK
852 __splitstack_releasecontext((void*)(&gp
->stackcontext
[0]));
854 // If gcstacksize is 0, the stack is allocated by libc and will be
855 // released when the thread exits. Otherwise, in 64-bit mode it was
856 // allocated using sysAlloc and in 32-bit mode it was allocated
857 // using garbage collected memory.
858 if (gp
->gcstacksize
!= 0) {
859 if (sizeof(void*) == 8) {
860 runtime_sysFree(gp
->gcinitialsp
, gp
->gcstacksize
, &getMemstats()->stacks_sys
);
862 gp
->gcinitialsp
= nil
;
868 void resetNewG(G
*, void **, uintptr
*)
869 __asm__(GOSYM_PREFIX
"runtime.resetNewG");
871 // Reset stack information for g pulled out of the cache to start a
874 resetNewG(G
*newg
, void **sp
, uintptr
*spsize
)
876 #ifdef USING_SPLIT_STACK
877 int dont_block_signals
= 0;
880 *sp
= __splitstack_resetcontext((void*)(&newg
->stackcontext
[0]), &ss_spsize
);
882 __splitstack_block_signals_context((void*)(&newg
->stackcontext
[0]),
883 &dont_block_signals
, nil
);
885 *sp
= newg
->gcinitialsp
;
886 *spsize
= newg
->gcstacksize
;
888 runtime_throw("bad spsize in resetNewG");
889 newg
->gcnextsp
= (uintptr
)(*sp
);
890 newg
->gcnextsp2
= (uintptr
)(newg
->gcinitialsp2
);
894 // Return whether we are waiting for a GC. This gc toolchain uses
895 // preemption instead.
897 runtime_gcwaiting(void)
899 return runtime_sched
->gcwaiting
;