[24/77] Replace a != BLKmode check with is_a <scalar_int_mode>
[official-gcc.git] / libgo / runtime / proc.c
blob3e3437e6a4795a79c85f9455de9b086ffa846c62
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.
5 #include <errno.h>
6 #include <limits.h>
7 #include <signal.h>
8 #include <stdlib.h>
9 #include <pthread.h>
10 #include <unistd.h>
12 #include "config.h"
14 #ifdef HAVE_DL_ITERATE_PHDR
15 #include <link.h>
16 #endif
18 #include "runtime.h"
19 #include "arch.h"
20 #include "defs.h"
21 #include "go-type.h"
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 **,
36 void **);
38 extern void __splitstack_block_signals (int *, int *);
40 extern void __splitstack_block_signals_context (void *context[10], int *,
41 int *);
43 #endif
45 #ifndef PTHREAD_STACK_MIN
46 # define PTHREAD_STACK_MIN 8192
47 #endif
49 #if defined(USING_SPLIT_STACK) && defined(LINKER_SUPPORTS_SPLIT_STACK)
50 # define StackMin PTHREAD_STACK_MIN
51 #else
52 # define StackMin ((sizeof(char *) < 8) ? 2 * 1024 * 1024 : 4 * 1024 * 1024)
53 #endif
55 uintptr runtime_stacks_sys;
57 void gtraceback(G*)
58 __asm__(GOSYM_PREFIX "runtime.gtraceback");
60 #ifdef __rtems__
61 #define __thread
62 #endif
64 static __thread G *g;
66 #ifndef SETCONTEXT_CLOBBERS_TLS
68 static inline void
69 initcontext(void)
73 static inline void
74 fixcontext(ucontext_t *c __attribute__ ((unused)))
78 #else
80 # if defined(__x86_64__) && defined(__sun__)
82 // x86_64 Solaris 10 and 11 have a bug: setcontext switches the %fs
83 // register to that of the thread which called getcontext. The effect
84 // is that the address of all __thread variables changes. This bug
85 // also affects pthread_self() and pthread_getspecific. We work
86 // around it by clobbering the context field directly to keep %fs the
87 // same.
89 static __thread greg_t fs;
91 static inline void
92 initcontext(void)
94 ucontext_t c;
96 getcontext(&c);
97 fs = c.uc_mcontext.gregs[REG_FSBASE];
100 static inline void
101 fixcontext(ucontext_t* c)
103 c->uc_mcontext.gregs[REG_FSBASE] = fs;
106 # elif defined(__NetBSD__)
108 // NetBSD has a bug: setcontext clobbers tlsbase, we need to save
109 // and restore it ourselves.
111 static __thread __greg_t tlsbase;
113 static inline void
114 initcontext(void)
116 ucontext_t c;
118 getcontext(&c);
119 tlsbase = c.uc_mcontext._mc_tlsbase;
122 static inline void
123 fixcontext(ucontext_t* c)
125 c->uc_mcontext._mc_tlsbase = tlsbase;
128 # elif defined(__sparc__)
130 static inline void
131 initcontext(void)
135 static inline void
136 fixcontext(ucontext_t *c)
138 /* ??? Using
139 register unsigned long thread __asm__("%g7");
140 c->uc_mcontext.gregs[REG_G7] = thread;
141 results in
142 error: variable ‘thread’ might be clobbered by \
143 ‘longjmp’ or ‘vfork’ [-Werror=clobbered]
144 which ought to be false, as %g7 is a fixed register. */
146 if (sizeof (c->uc_mcontext.gregs[REG_G7]) == 8)
147 asm ("stx %%g7, %0" : "=m"(c->uc_mcontext.gregs[REG_G7]));
148 else
149 asm ("st %%g7, %0" : "=m"(c->uc_mcontext.gregs[REG_G7]));
152 # elif defined(_AIX)
154 static inline void
155 initcontext(void)
159 static inline void
160 fixcontext(ucontext_t* c)
162 // Thread pointer is in r13, per 64-bit ABI.
163 if (sizeof (c->uc_mcontext.jmp_context.gpr[13]) == 8)
164 asm ("std 13, %0" : "=m"(c->uc_mcontext.jmp_context.gpr[13]));
167 # else
169 # error unknown case for SETCONTEXT_CLOBBERS_TLS
171 # endif
173 #endif
175 // ucontext_arg returns a properly aligned ucontext_t value. On some
176 // systems a ucontext_t value must be aligned to a 16-byte boundary.
177 // The g structure that has fields of type ucontext_t is defined in
178 // Go, and Go has no simple way to align a field to such a boundary.
179 // So we make the field larger in runtime2.go and pick an appropriate
180 // offset within the field here.
181 static ucontext_t*
182 ucontext_arg(uintptr* go_ucontext)
184 uintptr_t p = (uintptr_t)go_ucontext;
185 size_t align = __alignof__(ucontext_t);
186 if(align > 16) {
187 // We only ensured space for up to a 16 byte alignment
188 // in libgo/go/runtime/runtime2.go.
189 runtime_throw("required alignment of ucontext_t too large");
191 p = (p + align - 1) &~ (uintptr_t)(align - 1);
192 return (ucontext_t*)p;
195 // We can not always refer to the TLS variables directly. The
196 // compiler will call tls_get_addr to get the address of the variable,
197 // and it may hold it in a register across a call to schedule. When
198 // we get back from the call we may be running in a different thread,
199 // in which case the register now points to the TLS variable for a
200 // different thread. We use non-inlinable functions to avoid this
201 // when necessary.
203 G* runtime_g(void) __attribute__ ((noinline, no_split_stack));
206 runtime_g(void)
208 return g;
211 M* runtime_m(void) __attribute__ ((noinline, no_split_stack));
214 runtime_m(void)
216 if(g == nil)
217 return nil;
218 return g->m;
221 // Set g.
222 void
223 runtime_setg(G* gp)
225 g = gp;
228 void runtime_newosproc(M *)
229 __asm__(GOSYM_PREFIX "runtime.newosproc");
231 // Start a new thread.
232 void
233 runtime_newosproc(M *mp)
235 pthread_attr_t attr;
236 sigset_t clear, old;
237 pthread_t tid;
238 int tries;
239 int ret;
241 if(pthread_attr_init(&attr) != 0)
242 runtime_throw("pthread_attr_init");
243 if(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0)
244 runtime_throw("pthread_attr_setdetachstate");
246 // Block signals during pthread_create so that the new thread
247 // starts with signals disabled. It will enable them in minit.
248 sigfillset(&clear);
250 #ifdef SIGTRAP
251 // Blocking SIGTRAP reportedly breaks gdb on Alpha GNU/Linux.
252 sigdelset(&clear, SIGTRAP);
253 #endif
255 sigemptyset(&old);
256 pthread_sigmask(SIG_BLOCK, &clear, &old);
258 for (tries = 0; tries < 20; tries++) {
259 ret = pthread_create(&tid, &attr, runtime_mstart, mp);
260 if (ret != EAGAIN) {
261 break;
263 runtime_usleep((tries + 1) * 1000); // Milliseconds.
266 pthread_sigmask(SIG_SETMASK, &old, nil);
268 if (ret != 0) {
269 runtime_printf("pthread_create failed: %d\n", ret);
270 runtime_throw("pthread_create");
274 // Switch context to a different goroutine. This is like longjmp.
275 void runtime_gogo(G*) __attribute__ ((noinline));
276 void
277 runtime_gogo(G* newg)
279 #ifdef USING_SPLIT_STACK
280 __splitstack_setcontext((void*)(&newg->stackcontext[0]));
281 #endif
282 g = newg;
283 newg->fromgogo = true;
284 fixcontext(ucontext_arg(&newg->context[0]));
285 setcontext(ucontext_arg(&newg->context[0]));
286 runtime_throw("gogo setcontext returned");
289 // Save context and call fn passing g as a parameter. This is like
290 // setjmp. Because getcontext always returns 0, unlike setjmp, we use
291 // g->fromgogo as a code. It will be true if we got here via
292 // setcontext. g == nil the first time this is called in a new m.
293 void runtime_mcall(FuncVal *) __attribute__ ((noinline));
294 void
295 runtime_mcall(FuncVal *fv)
297 M *mp;
298 G *gp;
299 #ifndef USING_SPLIT_STACK
300 void *afterregs;
301 #endif
303 // Ensure that all registers are on the stack for the garbage
304 // collector.
305 __builtin_unwind_init();
307 gp = g;
308 mp = gp->m;
309 if(gp == mp->g0)
310 runtime_throw("runtime: mcall called on m->g0 stack");
312 if(gp != nil) {
314 #ifdef USING_SPLIT_STACK
315 __splitstack_getcontext((void*)(&g->stackcontext[0]));
316 #else
317 // We have to point to an address on the stack that is
318 // below the saved registers.
319 gp->gcnextsp = (uintptr)(&afterregs);
320 #endif
321 gp->fromgogo = false;
322 getcontext(ucontext_arg(&gp->context[0]));
324 // When we return from getcontext, we may be running
325 // in a new thread. That means that g may have
326 // changed. It is a global variables so we will
327 // reload it, but the address of g may be cached in
328 // our local stack frame, and that address may be
329 // wrong. Call the function to reload the value for
330 // this thread.
331 gp = runtime_g();
332 mp = gp->m;
334 if(gp->traceback != nil)
335 gtraceback(gp);
337 if (gp == nil || !gp->fromgogo) {
338 #ifdef USING_SPLIT_STACK
339 __splitstack_setcontext((void*)(&mp->g0->stackcontext[0]));
340 #endif
341 mp->g0->entry = fv;
342 mp->g0->param = gp;
344 // It's OK to set g directly here because this case
345 // can not occur if we got here via a setcontext to
346 // the getcontext call just above.
347 g = mp->g0;
349 fixcontext(ucontext_arg(&mp->g0->context[0]));
350 setcontext(ucontext_arg(&mp->g0->context[0]));
351 runtime_throw("runtime: mcall function returned");
355 // Goroutine scheduler
356 // The scheduler's job is to distribute ready-to-run goroutines over worker threads.
358 // The main concepts are:
359 // G - goroutine.
360 // M - worker thread, or machine.
361 // P - processor, a resource that is required to execute Go code.
362 // M must have an associated P to execute Go code, however it can be
363 // blocked or in a syscall w/o an associated P.
365 // Design doc at http://golang.org/s/go11sched.
367 extern bool* runtime_getCgoHasExtraM()
368 __asm__ (GOSYM_PREFIX "runtime.getCgoHasExtraM");
369 extern G* allocg(void)
370 __asm__ (GOSYM_PREFIX "runtime.allocg");
372 Sched* runtime_sched;
374 bool runtime_isarchive;
376 extern void kickoff(void)
377 __asm__(GOSYM_PREFIX "runtime.kickoff");
378 extern void mstart1(void)
379 __asm__(GOSYM_PREFIX "runtime.mstart1");
380 extern void stopm(void)
381 __asm__(GOSYM_PREFIX "runtime.stopm");
382 extern void handoffp(P*)
383 __asm__(GOSYM_PREFIX "runtime.handoffp");
384 extern void wakep(void)
385 __asm__(GOSYM_PREFIX "runtime.wakep");
386 extern void stoplockedm(void)
387 __asm__(GOSYM_PREFIX "runtime.stoplockedm");
388 extern void schedule(void)
389 __asm__(GOSYM_PREFIX "runtime.schedule");
390 extern void execute(G*, bool)
391 __asm__(GOSYM_PREFIX "runtime.execute");
392 extern void reentersyscall(uintptr, uintptr)
393 __asm__(GOSYM_PREFIX "runtime.reentersyscall");
394 extern void reentersyscallblock(uintptr, uintptr)
395 __asm__(GOSYM_PREFIX "runtime.reentersyscallblock");
396 extern G* gfget(P*)
397 __asm__(GOSYM_PREFIX "runtime.gfget");
398 extern void acquirep(P*)
399 __asm__(GOSYM_PREFIX "runtime.acquirep");
400 extern P* releasep(void)
401 __asm__(GOSYM_PREFIX "runtime.releasep");
402 extern void incidlelocked(int32)
403 __asm__(GOSYM_PREFIX "runtime.incidlelocked");
404 extern void globrunqput(G*)
405 __asm__(GOSYM_PREFIX "runtime.globrunqput");
406 extern P* pidleget(void)
407 __asm__(GOSYM_PREFIX "runtime.pidleget");
408 extern struct mstats* getMemstats(void)
409 __asm__(GOSYM_PREFIX "runtime.getMemstats");
411 bool runtime_isstarted;
413 // Used to determine the field alignment.
415 struct field_align
417 char c;
418 Hchan *p;
421 void getTraceback(G*, G*) __asm__(GOSYM_PREFIX "runtime.getTraceback");
423 // getTraceback stores a traceback of gp in the g's traceback field
424 // and then returns to me. We expect that gp's traceback is not nil.
425 // It works by saving me's current context, and checking gp's traceback field.
426 // If gp's traceback field is not nil, it starts running gp.
427 // In places where we call getcontext, we check the traceback field.
428 // If it is not nil, we collect a traceback, and then return to the
429 // goroutine stored in the traceback field, which is me.
430 void getTraceback(G* me, G* gp)
432 #ifdef USING_SPLIT_STACK
433 __splitstack_getcontext((void*)(&me->stackcontext[0]));
434 #endif
435 getcontext(ucontext_arg(&me->context[0]));
437 if (gp->traceback != nil) {
438 runtime_gogo(gp);
442 // Do a stack trace of gp, and then restore the context to
443 // gp->traceback->gp.
445 void
446 gtraceback(G* gp)
448 Traceback* traceback;
449 M* holdm;
451 traceback = gp->traceback;
452 gp->traceback = nil;
453 holdm = gp->m;
454 if(holdm != nil && holdm != g->m)
455 runtime_throw("gtraceback: m is not nil");
456 gp->m = traceback->gp->m;
457 traceback->c = runtime_callers(1, traceback->locbuf,
458 sizeof traceback->locbuf / sizeof traceback->locbuf[0], false);
459 gp->m = holdm;
460 runtime_gogo(traceback->gp);
463 // Called by pthread_create to start an M.
464 void*
465 runtime_mstart(void *arg)
467 M* mp;
468 G* gp;
470 mp = (M*)(arg);
471 gp = mp->g0;
472 gp->m = mp;
474 g = gp;
476 gp->entry = nil;
477 gp->param = nil;
479 initcontext();
481 // Record top of stack for use by mcall.
482 // Once we call schedule we're never coming back,
483 // so other calls can reuse this stack space.
484 #ifdef USING_SPLIT_STACK
485 __splitstack_getcontext((void*)(&gp->stackcontext[0]));
486 #else
487 gp->gcinitialsp = &arg;
488 // Setting gcstacksize to 0 is a marker meaning that gcinitialsp
489 // is the top of the stack, not the bottom.
490 gp->gcstacksize = 0;
491 gp->gcnextsp = (uintptr)(&arg);
492 #endif
494 // Save the currently active context. This will return
495 // multiple times via the setcontext call in mcall.
496 getcontext(ucontext_arg(&gp->context[0]));
498 if(gp->traceback != nil) {
499 // Got here from getTraceback.
500 // I'm not sure this ever actually happens--getTraceback
501 // may always go to the getcontext call in mcall.
502 gtraceback(gp);
505 if(gp->entry != nil) {
506 // Got here from mcall.
507 FuncVal *fv = gp->entry;
508 void (*pfn)(G*) = (void (*)(G*))fv->fn;
509 G* gp1 = (G*)gp->param;
510 gp->entry = nil;
511 gp->param = nil;
512 __builtin_call_with_static_chain(pfn(gp1), fv);
513 *(int*)0x21 = 0x21;
516 // Initial call to getcontext--starting thread.
518 #ifdef USING_SPLIT_STACK
520 int dont_block_signals = 0;
521 __splitstack_block_signals(&dont_block_signals, nil);
523 #endif
525 mstart1();
527 // mstart1 does not return, but we need a return statement
528 // here to avoid a compiler warning.
529 return nil;
532 typedef struct CgoThreadStart CgoThreadStart;
533 struct CgoThreadStart
535 M *m;
536 G *g;
537 uintptr *tls;
538 void (*fn)(void);
541 void setGContext(void) __asm__ (GOSYM_PREFIX "runtime.setGContext");
543 // setGContext sets up a new goroutine context for the current g.
544 void
545 setGContext()
547 int val;
548 G *gp;
550 initcontext();
551 gp = g;
552 gp->entry = nil;
553 gp->param = nil;
554 #ifdef USING_SPLIT_STACK
555 __splitstack_getcontext((void*)(&gp->stackcontext[0]));
556 val = 0;
557 __splitstack_block_signals(&val, nil);
558 #else
559 gp->gcinitialsp = &val;
560 gp->gcstack = 0;
561 gp->gcstacksize = 0;
562 gp->gcnextsp = (uintptr)(&val);
563 #endif
564 getcontext(ucontext_arg(&gp->context[0]));
566 if(gp->entry != nil) {
567 // Got here from mcall.
568 FuncVal *fv = gp->entry;
569 void (*pfn)(G*) = (void (*)(G*))fv->fn;
570 G* gp1 = (G*)gp->param;
571 gp->entry = nil;
572 gp->param = nil;
573 __builtin_call_with_static_chain(pfn(gp1), fv);
574 *(int*)0x22 = 0x22;
578 void makeGContext(G*, byte*, uintptr)
579 __asm__(GOSYM_PREFIX "runtime.makeGContext");
581 // makeGContext makes a new context for a g.
582 void
583 makeGContext(G* gp, byte* sp, uintptr spsize) {
584 ucontext_t *uc;
586 uc = ucontext_arg(&gp->context[0]);
587 getcontext(uc);
588 uc->uc_stack.ss_sp = sp;
589 uc->uc_stack.ss_size = (size_t)spsize;
590 makecontext(uc, kickoff, 0);
593 // The goroutine g is about to enter a system call.
594 // Record that it's not using the cpu anymore.
595 // This is called only from the go syscall library and cgocall,
596 // not from the low-level system calls used by the runtime.
598 // Entersyscall cannot split the stack: the runtime_gosave must
599 // make g->sched refer to the caller's stack segment, because
600 // entersyscall is going to return immediately after.
602 void runtime_entersyscall(int32) __attribute__ ((no_split_stack));
603 static void doentersyscall(uintptr, uintptr)
604 __attribute__ ((no_split_stack, noinline));
606 void
607 runtime_entersyscall(int32 dummy __attribute__ ((unused)))
609 // Save the registers in the g structure so that any pointers
610 // held in registers will be seen by the garbage collector.
611 getcontext(ucontext_arg(&g->gcregs[0]));
613 // Note that if this function does save any registers itself,
614 // we might store the wrong value in the call to getcontext.
615 // FIXME: This assumes that we do not need to save any
616 // callee-saved registers to access the TLS variable g. We
617 // don't want to put the ucontext_t on the stack because it is
618 // large and we can not split the stack here.
619 doentersyscall((uintptr)runtime_getcallerpc(&dummy),
620 (uintptr)runtime_getcallersp(&dummy));
623 static void
624 doentersyscall(uintptr pc, uintptr sp)
626 // Leave SP around for GC and traceback.
627 #ifdef USING_SPLIT_STACK
629 size_t gcstacksize;
630 g->gcstack = (uintptr)(__splitstack_find(nil, nil, &gcstacksize,
631 (void**)(&g->gcnextsegment),
632 (void**)(&g->gcnextsp),
633 &g->gcinitialsp));
634 g->gcstacksize = (uintptr)gcstacksize;
636 #else
638 void *v;
640 g->gcnextsp = (uintptr)(&v);
642 #endif
644 reentersyscall(pc, sp);
647 static void doentersyscallblock(uintptr, uintptr)
648 __attribute__ ((no_split_stack, noinline));
650 // The same as runtime_entersyscall(), but with a hint that the syscall is blocking.
651 void
652 runtime_entersyscallblock(int32 dummy __attribute__ ((unused)))
654 // Save the registers in the g structure so that any pointers
655 // held in registers will be seen by the garbage collector.
656 getcontext(ucontext_arg(&g->gcregs[0]));
658 // See comment in runtime_entersyscall.
659 doentersyscallblock((uintptr)runtime_getcallerpc(&dummy),
660 (uintptr)runtime_getcallersp(&dummy));
663 static void
664 doentersyscallblock(uintptr pc, uintptr sp)
666 // Leave SP around for GC and traceback.
667 #ifdef USING_SPLIT_STACK
669 size_t gcstacksize;
670 g->gcstack = (uintptr)(__splitstack_find(nil, nil, &gcstacksize,
671 (void**)(&g->gcnextsegment),
672 (void**)(&g->gcnextsp),
673 &g->gcinitialsp));
674 g->gcstacksize = (uintptr)gcstacksize;
676 #else
678 void *v;
680 g->gcnextsp = (uintptr)(&v);
682 #endif
684 reentersyscallblock(pc, sp);
687 // Allocate a new g, with a stack big enough for stacksize bytes.
689 runtime_malg(bool allocatestack, bool signalstack, byte** ret_stack, uintptr* ret_stacksize)
691 uintptr stacksize;
692 G *newg;
693 byte* unused_stack;
694 uintptr unused_stacksize;
695 #if USING_SPLIT_STACK
696 int dont_block_signals = 0;
697 size_t ss_stacksize;
698 #endif
700 if (ret_stack == nil) {
701 ret_stack = &unused_stack;
703 if (ret_stacksize == nil) {
704 ret_stacksize = &unused_stacksize;
706 newg = allocg();
707 if(allocatestack) {
708 stacksize = StackMin;
709 if(signalstack) {
710 stacksize = 32 * 1024; // OS X wants >= 8K, GNU/Linux >= 2K
711 #ifdef SIGSTKSZ
712 if(stacksize < SIGSTKSZ)
713 stacksize = SIGSTKSZ;
714 #endif
717 #if USING_SPLIT_STACK
718 *ret_stack = __splitstack_makecontext(stacksize,
719 (void*)(&newg->stackcontext[0]),
720 &ss_stacksize);
721 *ret_stacksize = (uintptr)ss_stacksize;
722 __splitstack_block_signals_context((void*)(&newg->stackcontext[0]),
723 &dont_block_signals, nil);
724 #else
725 // In 64-bit mode, the maximum Go allocation space is
726 // 128G. Our stack size is 4M, which only permits 32K
727 // goroutines. In order to not limit ourselves,
728 // allocate the stacks out of separate memory. In
729 // 32-bit mode, the Go allocation space is all of
730 // memory anyhow.
731 if(sizeof(void*) == 8) {
732 void *p = runtime_sysAlloc(stacksize, &getMemstats()->stacks_sys);
733 if(p == nil)
734 runtime_throw("runtime: cannot allocate memory for goroutine stack");
735 *ret_stack = (byte*)p;
736 } else {
737 *ret_stack = runtime_mallocgc(stacksize, nil, false);
738 runtime_xadd(&runtime_stacks_sys, stacksize);
740 *ret_stacksize = (uintptr)stacksize;
741 newg->gcinitialsp = *ret_stack;
742 newg->gcstacksize = (uintptr)stacksize;
743 #endif
745 return newg;
748 void resetNewG(G*, void **, uintptr*)
749 __asm__(GOSYM_PREFIX "runtime.resetNewG");
751 // Reset stack information for g pulled out of the cache to start a
752 // new goroutine.
753 void
754 resetNewG(G *newg, void **sp, uintptr *spsize)
756 #ifdef USING_SPLIT_STACK
757 int dont_block_signals = 0;
758 size_t ss_spsize;
760 *sp = __splitstack_resetcontext((void*)(&newg->stackcontext[0]), &ss_spsize);
761 *spsize = ss_spsize;
762 __splitstack_block_signals_context((void*)(&newg->stackcontext[0]),
763 &dont_block_signals, nil);
764 #else
765 *sp = newg->gcinitialsp;
766 *spsize = newg->gcstacksize;
767 if(*spsize == 0)
768 runtime_throw("bad spsize in resetNewG");
769 newg->gcnextsp = (uintptr)(*sp);
770 #endif
773 // Return whether we are waiting for a GC. This gc toolchain uses
774 // preemption instead.
775 bool
776 runtime_gcwaiting(void)
778 return runtime_sched->gcwaiting;