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.
12 #ifdef HAVE_DL_ITERATE_PHDR
24 #ifdef USING_SPLIT_STACK
26 /* FIXME: These are not declared anywhere. */
28 extern void __splitstack_getcontext(void *context
[10]);
30 extern void __splitstack_setcontext(void *context
[10]);
32 extern void *__splitstack_makecontext(size_t, void *context
[10], size_t *);
34 extern void * __splitstack_resetcontext(void *context
[10], size_t *);
36 extern void *__splitstack_find(void *, void *, size_t *, void **, void **,
39 extern void __splitstack_block_signals (int *, int *);
41 extern void __splitstack_block_signals_context (void *context
[10], int *,
46 #ifndef PTHREAD_STACK_MIN
47 # define PTHREAD_STACK_MIN 8192
50 #if defined(USING_SPLIT_STACK) && defined(LINKER_SUPPORTS_SPLIT_STACK)
51 # define StackMin PTHREAD_STACK_MIN
53 # define StackMin 2 * 1024 * 1024
56 uintptr runtime_stacks_sys
;
58 static void schedule(G
*);
60 static void gtraceback(G
*);
62 typedef struct Sched Sched
;
65 G runtime_g0
; // idle goroutine for m0
74 #ifndef SETCONTEXT_CLOBBERS_TLS
82 fixcontext(ucontext_t
*c
__attribute__ ((unused
)))
88 # if defined(__x86_64__) && defined(__sun__)
90 // x86_64 Solaris 10 and 11 have a bug: setcontext switches the %fs
91 // register to that of the thread which called getcontext. The effect
92 // is that the address of all __thread variables changes. This bug
93 // also affects pthread_self() and pthread_getspecific. We work
94 // around it by clobbering the context field directly to keep %fs the
97 static __thread greg_t fs
;
105 fs
= c
.uc_mcontext
.gregs
[REG_FSBASE
];
109 fixcontext(ucontext_t
* c
)
111 c
->uc_mcontext
.gregs
[REG_FSBASE
] = fs
;
114 # elif defined(__NetBSD__)
116 // NetBSD has a bug: setcontext clobbers tlsbase, we need to save
117 // and restore it ourselves.
119 static __thread __greg_t tlsbase
;
127 tlsbase
= c
.uc_mcontext
._mc_tlsbase
;
131 fixcontext(ucontext_t
* c
)
133 c
->uc_mcontext
._mc_tlsbase
= tlsbase
;
138 # error unknown case for SETCONTEXT_CLOBBERS_TLS
144 // We can not always refer to the TLS variables directly. The
145 // compiler will call tls_get_addr to get the address of the variable,
146 // and it may hold it in a register across a call to schedule. When
147 // we get back from the call we may be running in a different thread,
148 // in which case the register now points to the TLS variable for a
149 // different thread. We use non-inlinable functions to avoid this
152 G
* runtime_g(void) __attribute__ ((noinline
, no_split_stack
));
160 M
* runtime_m(void) __attribute__ ((noinline
, no_split_stack
));
168 int32 runtime_gcwaiting
;
177 // The static TLS size. See runtime_newm.
180 #ifdef HAVE_DL_ITERATE_PHDR
182 // Called via dl_iterate_phdr.
185 addtls(struct dl_phdr_info
* info
, size_t size
__attribute__ ((unused
)), void *data
)
187 size_t *total
= (size_t *)data
;
190 for(i
= 0; i
< info
->dlpi_phnum
; ++i
) {
191 if(info
->dlpi_phdr
[i
].p_type
== PT_TLS
)
192 *total
+= info
->dlpi_phdr
[i
].p_memsz
;
197 // Set the total TLS size.
204 dl_iterate_phdr(addtls
, (void *)&total
);
219 // The go scheduler's job is to match ready-to-run goroutines (`g's)
220 // with waiting-for-work schedulers (`m's). If there are ready g's
221 // and no waiting m's, ready() will start a new m running in a new
222 // OS thread, so that all ready g's can run simultaneously, up to a limit.
223 // For now, m's never go away.
225 // By default, Go keeps only one kernel thread (m) running user code
226 // at a single time; other threads may be blocked in the operating system.
227 // Setting the environment variable $GOMAXPROCS or calling
228 // runtime.GOMAXPROCS() will change the number of user threads
229 // allowed to execute simultaneously. $GOMAXPROCS is thus an
230 // approximation of the maximum number of cores to use.
232 // Even a program that can run without deadlock in a single process
233 // might use more m's if given the chance. For example, the prime
234 // sieve will use as many m's as there are primes (up to runtime_sched.mmax),
235 // allowing different stages of the pipeline to execute in parallel.
236 // We could revisit this choice, only kicking off new m's for blocking
237 // system calls, but that would limit the amount of parallel computation
238 // that go would try to do.
240 // In general, one could imagine all sorts of refinements to the
241 // scheduler, but the goal now is just to get something working on
247 G
*gfree
; // available g's (status == Gdead)
250 G
*ghead
; // g's waiting to run
252 int32 gwait
; // number of g's waiting to run
253 int32 gcount
; // number of g's that are alive
254 int32 grunning
; // number of g's running on cpu or in syscall
256 M
*mhead
; // m's waiting for work
257 int32 mwait
; // number of m's waiting for work
258 int32 mcount
; // number of m's that have been created
260 volatile uint32 atomic
; // atomic scheduling word (see below)
262 int32 profilehz
; // cpu profiling rate
264 bool init
; // running initialization
265 bool lockmain
; // init called runtime.LockOSThread
267 Note stopped
; // one g can set waitstop and wait here for m's to stop
270 // The atomic word in sched is an atomic uint32 that
271 // holds these fields.
273 // [15 bits] mcpu number of m's executing on cpu
274 // [15 bits] mcpumax max number of m's allowed on cpu
275 // [1 bit] waitstop some g is waiting on stopped
276 // [1 bit] gwaiting gwait != 0
278 // These fields are the information needed by entersyscall
279 // and exitsyscall to decide whether to coordinate with the
280 // scheduler. Packing them into a single machine word lets
281 // them use a fast path with a single atomic read/write and
282 // no lock/unlock. This greatly reduces contention in
283 // syscall- or cgo-heavy multithreaded programs.
285 // Except for entersyscall and exitsyscall, the manipulations
286 // to these fields only happen while holding the schedlock,
287 // so the routines holding schedlock only need to worry about
288 // what entersyscall and exitsyscall do, not the other routines
289 // (which also use the schedlock).
291 // In particular, entersyscall and exitsyscall only read mcpumax,
292 // waitstop, and gwaiting. They never write them. Thus, writes to those
293 // fields can be done (holding schedlock) without fear of write conflicts.
294 // There may still be logic conflicts: for example, the set of waitstop must
295 // be conditioned on mcpu >= mcpumax or else the wait may be a
296 // spurious sleep. The Promela model in proc.p verifies these accesses.
299 mcpuMask
= (1<<mcpuWidth
) - 1,
301 mcpumaxShift
= mcpuShift
+ mcpuWidth
,
302 waitstopShift
= mcpumaxShift
+ mcpuWidth
,
303 gwaitingShift
= waitstopShift
+1,
305 // The max value of GOMAXPROCS is constrained
306 // by the max value we can store in the bit fields
307 // of the atomic word. Reserve a few high values
308 // so that we can detect accidental decrement
310 maxgomaxprocs
= mcpuMask
- 10,
313 #define atomic_mcpu(v) (((v)>>mcpuShift)&mcpuMask)
314 #define atomic_mcpumax(v) (((v)>>mcpumaxShift)&mcpuMask)
315 #define atomic_waitstop(v) (((v)>>waitstopShift)&1)
316 #define atomic_gwaiting(v) (((v)>>gwaitingShift)&1)
319 int32 runtime_gomaxprocs
;
320 bool runtime_singleproc
;
322 static bool canaddmcpu(void);
324 // An m that is waiting for notewakeup(&m->havenextg). This may
325 // only be accessed while the scheduler lock is held. This is used to
326 // minimize the number of times we call notewakeup while the scheduler
327 // lock is held, since the m will normally move quickly to lock the
328 // scheduler itself, producing lock contention.
331 // Scheduling helpers. Sched must be locked.
332 static void gput(G
*); // put/get on ghead/gtail
333 static G
* gget(void);
334 static void mput(M
*); // put/get on mhead
336 static void gfput(G
*); // put/get on gfree
337 static G
* gfget(void);
338 static void matchmg(void); // match m's to g's
339 static void readylocked(G
*); // ready, but sched is locked
340 static void mnextg(M
*, G
*);
341 static void mcommoninit(M
*);
349 v
= runtime_sched
.atomic
;
351 w
&= ~(mcpuMask
<<mcpumaxShift
);
352 w
|= n
<<mcpumaxShift
;
353 if(runtime_cas(&runtime_sched
.atomic
, v
, w
))
358 // First function run by a new goroutine. This replaces gogocall.
364 if(g
->traceback
!= nil
)
367 fn
= (void (*)(void*))(g
->entry
);
372 // Switch context to a different goroutine. This is like longjmp.
373 static void runtime_gogo(G
*) __attribute__ ((noinline
));
375 runtime_gogo(G
* newg
)
377 #ifdef USING_SPLIT_STACK
378 __splitstack_setcontext(&newg
->stack_context
[0]);
381 newg
->fromgogo
= true;
382 fixcontext(&newg
->context
);
383 setcontext(&newg
->context
);
384 runtime_throw("gogo setcontext returned");
387 // Save context and call fn passing g as a parameter. This is like
388 // setjmp. Because getcontext always returns 0, unlike setjmp, we use
389 // g->fromgogo as a code. It will be true if we got here via
390 // setcontext. g == nil the first time this is called in a new m.
391 static void runtime_mcall(void (*)(G
*)) __attribute__ ((noinline
));
393 runtime_mcall(void (*pfn
)(G
*))
397 #ifndef USING_SPLIT_STACK
401 // Ensure that all registers are on the stack for the garbage
403 __builtin_unwind_init();
408 runtime_throw("runtime: mcall called on m->g0 stack");
412 #ifdef USING_SPLIT_STACK
413 __splitstack_getcontext(&g
->stack_context
[0]);
417 gp
->fromgogo
= false;
418 getcontext(&gp
->context
);
420 // When we return from getcontext, we may be running
421 // in a new thread. That means that m and g may have
422 // changed. They are global variables so we will
423 // reload them, but the addresses of m and g may be
424 // cached in our local stack frame, and those
425 // addresses may be wrong. Call functions to reload
426 // the values for this thread.
430 if(gp
->traceback
!= nil
)
433 if (gp
== nil
|| !gp
->fromgogo
) {
434 #ifdef USING_SPLIT_STACK
435 __splitstack_setcontext(&mp
->g0
->stack_context
[0]);
437 mp
->g0
->entry
= (byte
*)pfn
;
440 // It's OK to set g directly here because this case
441 // can not occur if we got here via a setcontext to
442 // the getcontext call just above.
445 fixcontext(&mp
->g0
->context
);
446 setcontext(&mp
->g0
->context
);
447 runtime_throw("runtime: mcall function returned");
451 // Keep trace of scavenger's goroutine for deadlock detection.
454 // The bootstrap sequence is:
458 // make & queue new G
459 // call runtime_mstart
461 // The new G calls runtime_main.
463 runtime_schedinit(void)
478 runtime_mallocinit();
485 // Allocate internal symbol table representation now,
486 // so that we don't need to call malloc when we crash.
487 // runtime_findfunc(0);
489 runtime_gomaxprocs
= 1;
490 p
= runtime_getenv("GOMAXPROCS");
491 if(p
!= nil
&& (n
= runtime_atoi(p
)) != 0) {
492 if(n
> maxgomaxprocs
)
494 runtime_gomaxprocs
= n
;
496 // wait for the main goroutine to start before taking
497 // GOMAXPROCS into account.
499 runtime_singleproc
= runtime_gomaxprocs
== 1;
501 canaddmcpu(); // mcpu++ to account for bootstrap m
502 m
->helpgc
= 1; // flag to tell schedule() to mcpu--
503 runtime_sched
.grunning
++;
505 // Can not enable GC until all roots are registered.
506 // mstats.enablegc = 1;
513 extern void main_init(void) __asm__ (GOSYM_PREFIX
"__go_init_main");
514 extern void main_main(void) __asm__ (GOSYM_PREFIX
"main.main");
516 // The main goroutine.
520 // Lock the main goroutine onto this, the main OS thread,
521 // during initialization. Most programs won't care, but a few
522 // do require certain calls to be made by the main thread.
523 // Those can arrange for main.main to run in the main thread
524 // by calling runtime.LockOSThread during initialization
525 // to preserve the lock.
526 runtime_LockOSThread();
527 // From now on, newgoroutines may use non-main threads.
528 setmcpumax(runtime_gomaxprocs
);
529 runtime_sched
.init
= true;
530 scvg
= __go_go(runtime_MHeap_Scavenger
, nil
);
531 scvg
->issystem
= true;
533 runtime_sched
.init
= false;
534 if(!runtime_sched
.lockmain
)
535 runtime_UnlockOSThread();
537 // For gccgo we have to wait until after main is initialized
538 // to enable GC, because initializing main registers the GC
542 // The deadlock detection has false negatives.
543 // Let scvg start up, to eliminate the false negative
544 // for the trivial program func main() { select{} }.
555 // Lock the scheduler.
559 runtime_lock(&runtime_sched
);
562 // Unlock the scheduler.
570 runtime_unlock(&runtime_sched
);
572 runtime_notewakeup(&mp
->havenextg
);
578 g
->status
= Gmoribund
;
583 runtime_goroutineheader(G
*gp
)
602 status
= gp
->waitreason
;
613 runtime_printf("goroutine %D [%s]:\n", gp
->goid
, status
);
617 runtime_goroutinetrailer(G
*g
)
619 if(g
!= nil
&& g
->gopc
!= 0 && g
->goid
!= 1) {
624 if(__go_file_line(g
->gopc
- 1, &fn
, &file
, &line
)) {
625 runtime_printf("created by %S\n", fn
);
626 runtime_printf("\t%S:%D\n", file
, (int64
) line
);
634 Location locbuf
[100];
639 runtime_tracebackothers(G
* volatile me
)
646 traceback
= runtime_gotraceback();
647 for(gp
= runtime_allg
; gp
!= nil
; gp
= gp
->alllink
) {
648 if(gp
== me
|| gp
->status
== Gdead
)
650 if(gp
->issystem
&& traceback
< 2)
652 runtime_printf("\n");
653 runtime_goroutineheader(gp
);
655 // Our only mechanism for doing a stack trace is
656 // _Unwind_Backtrace. And that only works for the
657 // current thread, not for other random goroutines.
658 // So we need to switch context to the goroutine, get
659 // the backtrace, and then switch back.
661 // This means that if g is running or in a syscall, we
662 // can't reliably print a stack trace. FIXME.
663 if(gp
->status
== Gsyscall
|| gp
->status
== Grunning
) {
664 runtime_printf("no stack trace available\n");
665 runtime_goroutinetrailer(gp
);
671 #ifdef USING_SPLIT_STACK
672 __splitstack_getcontext(&me
->stack_context
[0]);
674 getcontext(&me
->context
);
676 if(gp
->traceback
!= nil
) {
680 runtime_printtrace(tb
.locbuf
, tb
.c
, false);
681 runtime_goroutinetrailer(gp
);
685 // Do a stack trace of gp, and then restore the context to
691 Traceback
* traceback
;
693 traceback
= gp
->traceback
;
695 traceback
->c
= runtime_callers(1, traceback
->locbuf
,
696 sizeof traceback
->locbuf
/ sizeof traceback
->locbuf
[0]);
697 runtime_gogo(traceback
->gp
);
700 // Mark this g as m's idle goroutine.
701 // This functionality might be used in environments where programs
702 // are limited to a single thread, to simulate a select-driven
703 // network server. It is not exposed via the standard runtime API.
705 runtime_idlegoroutine(void)
708 runtime_throw("g is already an idle goroutine");
715 mp
->id
= runtime_sched
.mcount
++;
716 mp
->fastrand
= 0x49f6428aUL
+ mp
->id
+ runtime_cputicks();
718 if(mp
->mcache
== nil
)
719 mp
->mcache
= runtime_allocmcache();
721 runtime_callers(1, mp
->createstack
, nelem(mp
->createstack
));
723 // Add to runtime_allm so garbage collector doesn't free m
724 // when it is just in a register or thread-local storage.
725 mp
->alllink
= runtime_allm
;
726 // runtime_NumCgoCall() iterates over allm w/o schedlock,
727 // so we need to publish it safely.
728 runtime_atomicstorep(&runtime_allm
, mp
);
731 // Try to increment mcpu. Report whether succeeded.
738 v
= runtime_sched
.atomic
;
739 if(atomic_mcpu(v
) >= atomic_mcpumax(v
))
741 if(runtime_cas(&runtime_sched
.atomic
, v
, v
+(1<<mcpuShift
)))
746 // Put on `g' queue. Sched must be locked.
752 // If g is wired, hand it off directly.
753 if((mp
= gp
->lockedm
) != nil
&& canaddmcpu()) {
758 // If g is the idle goroutine for an m, hand it off.
759 if(gp
->idlem
!= nil
) {
760 if(gp
->idlem
->idleg
!= nil
) {
761 runtime_printf("m%d idle out of sync: g%D g%D\n",
763 gp
->idlem
->idleg
->goid
, gp
->goid
);
764 runtime_throw("runtime: double idle");
766 gp
->idlem
->idleg
= gp
;
771 if(runtime_sched
.ghead
== nil
)
772 runtime_sched
.ghead
= gp
;
774 runtime_sched
.gtail
->schedlink
= gp
;
775 runtime_sched
.gtail
= gp
;
778 // if it transitions to nonzero, set atomic gwaiting bit.
779 if(runtime_sched
.gwait
++ == 0)
780 runtime_xadd(&runtime_sched
.atomic
, 1<<gwaitingShift
);
783 // Report whether gget would return something.
787 return runtime_sched
.ghead
!= nil
|| m
->idleg
!= nil
;
790 // Get from `g' queue. Sched must be locked.
796 gp
= runtime_sched
.ghead
;
798 runtime_sched
.ghead
= gp
->schedlink
;
799 if(runtime_sched
.ghead
== nil
)
800 runtime_sched
.gtail
= nil
;
802 // if it transitions to zero, clear atomic gwaiting bit.
803 if(--runtime_sched
.gwait
== 0)
804 runtime_xadd(&runtime_sched
.atomic
, -1<<gwaitingShift
);
805 } else if(m
->idleg
!= nil
) {
812 // Put on `m' list. Sched must be locked.
816 mp
->schedlink
= runtime_sched
.mhead
;
817 runtime_sched
.mhead
= mp
;
818 runtime_sched
.mwait
++;
821 // Get an `m' to run `g'. Sched must be locked.
827 // if g has its own m, use it.
828 if(gp
&& (mp
= gp
->lockedm
) != nil
)
831 // otherwise use general m pool.
832 if((mp
= runtime_sched
.mhead
) != nil
) {
833 runtime_sched
.mhead
= mp
->schedlink
;
834 runtime_sched
.mwait
--;
839 // Mark g ready to run.
848 // Mark g ready to run. Sched is already locked.
849 // G might be running already and about to stop.
850 // The sched lock protects g->status from changing underfoot.
855 // Running on another machine.
856 // Ready it when it stops.
862 if(gp
->status
== Grunnable
|| gp
->status
== Grunning
) {
863 runtime_printf("goroutine %D has status %d\n", gp
->goid
, gp
->status
);
864 runtime_throw("bad g->status in ready");
866 gp
->status
= Grunnable
;
872 // Same as readylocked but a different symbol so that
873 // debuggers can set a breakpoint here and catch all
876 newprocreadylocked(G
*gp
)
881 // Pass g to m for running.
882 // Caller has already incremented mcpu.
886 runtime_sched
.grunning
++;
891 runtime_notewakeup(&mwakeup
->havenextg
);
896 // Get the next goroutine that m should run.
897 // Sched must be locked on entry, is unlocked on exit.
898 // Makes sure that at most $GOMAXPROCS g's are
899 // running on cpus (not in system calls) at any given time.
907 if(atomic_mcpu(runtime_sched
.atomic
) >= maxgomaxprocs
)
908 runtime_throw("negative mcpu");
910 // If there is a g waiting as m->nextg, the mcpu++
911 // happened before it was passed to mnextg.
912 if(m
->nextg
!= nil
) {
919 if(m
->lockedg
!= nil
) {
920 // We can only run one g, and it's not available.
921 // Make sure some other cpu is running to handle
922 // the ordinary run queue.
923 if(runtime_sched
.gwait
!= 0) {
925 // m->lockedg might have been on the queue.
926 if(m
->nextg
!= nil
) {
934 // Look for work on global queue.
935 while(haveg() && canaddmcpu()) {
938 runtime_throw("gget inconsistency");
941 mnextg(gp
->lockedm
, gp
);
944 runtime_sched
.grunning
++;
949 // The while loop ended either because the g queue is empty
950 // or because we have maxed out our m procs running go
951 // code (mcpu >= mcpumax). We need to check that
952 // concurrent actions by entersyscall/exitsyscall cannot
953 // invalidate the decision to end the loop.
955 // We hold the sched lock, so no one else is manipulating the
956 // g queue or changing mcpumax. Entersyscall can decrement
957 // mcpu, but if does so when there is something on the g queue,
958 // the gwait bit will be set, so entersyscall will take the slow path
959 // and use the sched lock. So it cannot invalidate our decision.
961 // Wait on global m queue.
965 // Look for deadlock situation.
966 // There is a race with the scavenger that causes false negatives:
967 // if the scavenger is just starting, then we have
968 // scvg != nil && grunning == 0 && gwait == 0
969 // and we do not detect a deadlock. It is possible that we should
970 // add that case to the if statement here, but it is too close to Go 1
971 // to make such a subtle change. Instead, we work around the
972 // false negative in trivial programs by calling runtime.gosched
973 // from the main goroutine just before main.main.
974 // See runtime_main above.
976 // On a related note, it is also possible that the scvg == nil case is
977 // wrong and should include gwait, but that does not happen in
978 // standard Go programs, which all start the scavenger.
980 if((scvg
== nil
&& runtime_sched
.grunning
== 0) ||
981 (scvg
!= nil
&& runtime_sched
.grunning
== 1 && runtime_sched
.gwait
== 0 &&
982 (scvg
->status
== Grunning
|| scvg
->status
== Gsyscall
))) {
983 m
->throwing
= -1; // do not dump full stacks
984 runtime_throw("all goroutines are asleep - deadlock!");
989 runtime_noteclear(&m
->havenextg
);
991 // Stoptheworld is waiting for all but its cpu to go to stop.
992 // Entersyscall might have decremented mcpu too, but if so
993 // it will see the waitstop and take the slow path.
994 // Exitsyscall never increments mcpu beyond mcpumax.
995 v
= runtime_atomicload(&runtime_sched
.atomic
);
996 if(atomic_waitstop(v
) && atomic_mcpu(v
) <= atomic_mcpumax(v
)) {
997 // set waitstop = 0 (known to be 1)
998 runtime_xadd(&runtime_sched
.atomic
, -1<<waitstopShift
);
999 runtime_notewakeup(&runtime_sched
.stopped
);
1003 runtime_notesleep(&m
->havenextg
);
1007 runtime_lock(&runtime_sched
);
1010 if((gp
= m
->nextg
) == nil
)
1011 runtime_throw("bad m->nextg in nextgoroutine");
1017 runtime_gcprocs(void)
1021 // Figure out how many CPUs to use during GC.
1022 // Limited by gomaxprocs, number of actual CPUs, and MaxGcproc.
1023 n
= runtime_gomaxprocs
;
1024 if(n
> runtime_ncpu
)
1025 n
= runtime_ncpu
> 0 ? runtime_ncpu
: 1;
1028 if(n
> runtime_sched
.mwait
+1) // one M is currently running
1029 n
= runtime_sched
.mwait
+1;
1034 runtime_helpgc(int32 nproc
)
1039 runtime_lock(&runtime_sched
);
1040 for(n
= 1; n
< nproc
; n
++) { // one M is currently running
1043 runtime_throw("runtime_gcprocs inconsistency");
1046 runtime_notewakeup(&mp
->havenextg
);
1048 runtime_unlock(&runtime_sched
);
1052 runtime_stoptheworld(void)
1057 runtime_gcwaiting
= 1;
1063 v
= runtime_sched
.atomic
;
1064 if(atomic_mcpu(v
) <= 1)
1067 // It would be unsafe for multiple threads to be using
1068 // the stopped note at once, but there is only
1069 // ever one thread doing garbage collection.
1070 runtime_noteclear(&runtime_sched
.stopped
);
1071 if(atomic_waitstop(v
))
1072 runtime_throw("invalid waitstop");
1074 // atomic { waitstop = 1 }, predicated on mcpu <= 1 check above
1075 // still being true.
1076 if(!runtime_cas(&runtime_sched
.atomic
, v
, v
+(1<<waitstopShift
)))
1080 runtime_notesleep(&runtime_sched
.stopped
);
1083 runtime_singleproc
= runtime_gomaxprocs
== 1;
1088 runtime_starttheworld(void)
1093 // Figure out how many CPUs GC could possibly use.
1094 max
= runtime_gomaxprocs
;
1095 if(max
> runtime_ncpu
)
1096 max
= runtime_ncpu
> 0 ? runtime_ncpu
: 1;
1101 runtime_gcwaiting
= 0;
1102 setmcpumax(runtime_gomaxprocs
);
1104 if(runtime_gcprocs() < max
&& canaddmcpu()) {
1105 // If GC could have used another helper proc, start one now,
1106 // in the hope that it will be available next time.
1107 // It would have been even better to start it before the collection,
1108 // but doing so requires allocating memory, so it's tricky to
1109 // coordinate. This lazy approach works out in practice:
1110 // we don't mind if the first couple gc rounds don't have quite
1111 // the maximum number of procs.
1112 // canaddmcpu above did mcpu++
1113 // (necessary, because m will be doing various
1114 // initialization work so is definitely running),
1115 // but m is not running a specific goroutine,
1116 // so set the helpgc flag as a signal to m's
1117 // first schedule(nil) to mcpu-- and grunning--.
1118 mp
= runtime_newm();
1120 runtime_sched
.grunning
++;
1125 // Called to start an M.
1127 runtime_mstart(void* mp
)
1137 // Record top of stack for use by mcall.
1138 // Once we call schedule we're never coming back,
1139 // so other calls can reuse this stack space.
1140 #ifdef USING_SPLIT_STACK
1141 __splitstack_getcontext(&g
->stack_context
[0]);
1143 g
->gcinitial_sp
= &mp
;
1144 // Setting gcstack_size to 0 is a marker meaning that gcinitial_sp
1145 // is the top of the stack, not the bottom.
1146 g
->gcstack_size
= 0;
1149 getcontext(&g
->context
);
1151 if(g
->entry
!= nil
) {
1152 // Got here from mcall.
1153 void (*pfn
)(G
*) = (void (*)(G
*))g
->entry
;
1154 G
* gp
= (G
*)g
->param
;
1160 #ifdef USING_SPLIT_STACK
1162 int dont_block_signals
= 0;
1163 __splitstack_block_signals(&dont_block_signals
, nil
);
1167 // Install signal handlers; after minit so that minit can
1168 // prepare the thread to be able to handle the signals.
1169 if(m
== &runtime_m0
)
1174 // TODO(brainman): This point is never reached, because scheduler
1175 // does not release os threads at the moment. But once this path
1176 // is enabled, we must remove our seh here.
1181 typedef struct CgoThreadStart CgoThreadStart
;
1182 struct CgoThreadStart
1189 // Kick off new m's as needed (up to mcpumax).
1197 if(m
->mallocing
|| m
->gcing
)
1200 while(haveg() && canaddmcpu()) {
1203 runtime_throw("gget inconsistency");
1205 // Find the m that will run gp.
1206 if((mp
= mget(gp
)) == nil
)
1207 mp
= runtime_newm();
1212 // Create a new m. It will start off with a call to runtime_mstart.
1217 pthread_attr_t attr
;
1222 static const Type
*mtype
; // The Go type M
1225 runtime_gc_m_ptr(&e
);
1226 mtype
= ((const PtrType
*)e
.__type_descriptor
)->__element_type
;
1230 mp
= runtime_mal(sizeof *mp
);
1232 mp
->g0
= runtime_malg(-1, nil
, nil
);
1234 if(pthread_attr_init(&attr
) != 0)
1235 runtime_throw("pthread_attr_init");
1236 if(pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0)
1237 runtime_throw("pthread_attr_setdetachstate");
1239 stacksize
= PTHREAD_STACK_MIN
;
1241 // With glibc before version 2.16 the static TLS size is taken
1242 // out of the stack size, and we get an error or a crash if
1243 // there is not enough stack space left. Add it back in if we
1244 // can, in case the program uses a lot of TLS space. FIXME:
1245 // This can be disabled in glibc 2.16 and later, if the bug is
1246 // indeed fixed then.
1247 stacksize
+= tlssize
;
1249 if(pthread_attr_setstacksize(&attr
, stacksize
) != 0)
1250 runtime_throw("pthread_attr_setstacksize");
1252 if(pthread_create(&tid
, &attr
, runtime_mstart
, mp
) != 0)
1253 runtime_throw("pthread_create");
1258 // One round of scheduler: find a goroutine and run it.
1259 // The argument is the goroutine that was running before
1260 // schedule was called, or nil if this is the first call.
1270 // Just finished running gp.
1272 runtime_sched
.grunning
--;
1274 // atomic { mcpu-- }
1275 v
= runtime_xadd(&runtime_sched
.atomic
, -1<<mcpuShift
);
1276 if(atomic_mcpu(v
) > maxgomaxprocs
)
1277 runtime_throw("negative mcpu in scheduler");
1279 switch(gp
->status
) {
1282 // Shouldn't have been running!
1283 runtime_throw("bad gp->status in sched");
1285 gp
->status
= Grunnable
;
1290 runtime_racegoend(gp
->goid
);
1297 runtime_memclr(&gp
->context
, sizeof gp
->context
);
1299 if(--runtime_sched
.gcount
== 0)
1303 if(gp
->readyonstop
) {
1304 gp
->readyonstop
= 0;
1307 } else if(m
->helpgc
) {
1308 // Bootstrap m or new m started by starttheworld.
1309 // atomic { mcpu-- }
1310 v
= runtime_xadd(&runtime_sched
.atomic
, -1<<mcpuShift
);
1311 if(atomic_mcpu(v
) > maxgomaxprocs
)
1312 runtime_throw("negative mcpu in scheduler");
1313 // Compensate for increment in starttheworld().
1314 runtime_sched
.grunning
--;
1316 } else if(m
->nextg
!= nil
) {
1317 // New m started by matchmg.
1319 runtime_throw("invalid m state in scheduler");
1322 // Find (or wait for) g to run. Unlocks runtime_sched.
1323 gp
= nextgandunlock();
1324 gp
->readyonstop
= 0;
1325 gp
->status
= Grunning
;
1329 // Check whether the profiler needs to be turned on or off.
1330 hz
= runtime_sched
.profilehz
;
1331 if(m
->profilehz
!= hz
)
1332 runtime_resetcpuprofiler(hz
);
1337 // Enter scheduler. If g->status is Grunning,
1338 // re-queues g and runs everyone else who is waiting
1339 // before running g again. If g->status is Gmoribund,
1342 runtime_gosched(void)
1345 runtime_throw("gosched holding locks");
1347 runtime_throw("gosched of g0");
1348 runtime_mcall(schedule
);
1351 // Puts the current goroutine into a waiting state and unlocks the lock.
1352 // The goroutine can be made runnable again by calling runtime_ready(gp).
1354 runtime_park(void (*unlockf
)(Lock
*), Lock
*lock
, const char *reason
)
1356 g
->status
= Gwaiting
;
1357 g
->waitreason
= reason
;
1363 // The goroutine g is about to enter a system call.
1364 // Record that it's not using the cpu anymore.
1365 // This is called only from the go syscall library and cgocall,
1366 // not from the low-level system calls used by the runtime.
1368 // Entersyscall cannot split the stack: the runtime_gosave must
1369 // make g->sched refer to the caller's stack segment, because
1370 // entersyscall is going to return immediately after.
1371 // It's okay to call matchmg and notewakeup even after
1372 // decrementing mcpu, because we haven't released the
1373 // sched lock yet, so the garbage collector cannot be running.
1375 void runtime_entersyscall(void) __attribute__ ((no_split_stack
));
1378 runtime_entersyscall(void)
1382 if(m
->profilehz
> 0)
1383 runtime_setprof(false);
1385 // Leave SP around for gc and traceback.
1386 #ifdef USING_SPLIT_STACK
1387 g
->gcstack
= __splitstack_find(nil
, nil
, &g
->gcstack_size
,
1388 &g
->gcnext_segment
, &g
->gcnext_sp
,
1391 g
->gcnext_sp
= (byte
*) &v
;
1394 // Save the registers in the g structure so that any pointers
1395 // held in registers will be seen by the garbage collector.
1396 getcontext(&g
->gcregs
);
1398 g
->status
= Gsyscall
;
1401 // The slow path inside the schedlock/schedunlock will get
1402 // through without stopping if it does:
1405 // waitstop && mcpu <= mcpumax not true
1406 // If we can do the same with a single atomic add,
1407 // then we can skip the locks.
1408 v
= runtime_xadd(&runtime_sched
.atomic
, -1<<mcpuShift
);
1409 if(!atomic_gwaiting(v
) && (!atomic_waitstop(v
) || atomic_mcpu(v
) > atomic_mcpumax(v
)))
1413 v
= runtime_atomicload(&runtime_sched
.atomic
);
1414 if(atomic_gwaiting(v
)) {
1416 v
= runtime_atomicload(&runtime_sched
.atomic
);
1418 if(atomic_waitstop(v
) && atomic_mcpu(v
) <= atomic_mcpumax(v
)) {
1419 runtime_xadd(&runtime_sched
.atomic
, -1<<waitstopShift
);
1420 runtime_notewakeup(&runtime_sched
.stopped
);
1426 // The goroutine g exited its system call.
1427 // Arrange for it to run on a cpu again.
1428 // This is called only from the go syscall library, not
1429 // from the low-level system calls used by the runtime.
1431 runtime_exitsyscall(void)
1437 // If we can do the mcpu++ bookkeeping and
1438 // find that we still have mcpu <= mcpumax, then we can
1439 // start executing Go code immediately, without having to
1440 // schedlock/schedunlock.
1441 // Also do fast return if any locks are held, so that
1442 // panic code can use syscalls to open a file.
1444 v
= runtime_xadd(&runtime_sched
.atomic
, (1<<mcpuShift
));
1445 if((m
->profilehz
== runtime_sched
.profilehz
&& atomic_mcpu(v
) <= atomic_mcpumax(v
)) || m
->locks
> 0) {
1446 // There's a cpu for us, so we can run.
1447 gp
->status
= Grunning
;
1448 // Garbage collector isn't running (since we are),
1449 // so okay to clear gcstack.
1450 #ifdef USING_SPLIT_STACK
1453 gp
->gcnext_sp
= nil
;
1454 runtime_memclr(&gp
->gcregs
, sizeof gp
->gcregs
);
1456 if(m
->profilehz
> 0)
1457 runtime_setprof(true);
1461 // Tell scheduler to put g back on the run queue:
1462 // mostly equivalent to g->status = Grunning,
1463 // but keeps the garbage collector from thinking
1464 // that g is running right now, which it's not.
1465 gp
->readyonstop
= 1;
1467 // All the cpus are taken.
1468 // The scheduler will ready g and put this m to sleep.
1469 // When the scheduler takes g away from m,
1470 // it will undo the runtime_sched.mcpu++ above.
1473 // Gosched returned, so we're allowed to run now.
1474 // Delete the gcstack information that we left for
1475 // the garbage collector during the system call.
1476 // Must wait until now because until gosched returns
1477 // we don't know for sure that the garbage collector
1479 #ifdef USING_SPLIT_STACK
1482 gp
->gcnext_sp
= nil
;
1483 runtime_memclr(&gp
->gcregs
, sizeof gp
->gcregs
);
1486 // Allocate a new g, with a stack big enough for stacksize bytes.
1488 runtime_malg(int32 stacksize
, byte
** ret_stack
, size_t* ret_stacksize
)
1492 newg
= runtime_malloc(sizeof(G
));
1493 if(stacksize
>= 0) {
1494 #if USING_SPLIT_STACK
1495 int dont_block_signals
= 0;
1497 *ret_stack
= __splitstack_makecontext(stacksize
,
1498 &newg
->stack_context
[0],
1500 __splitstack_block_signals_context(&newg
->stack_context
[0],
1501 &dont_block_signals
, nil
);
1503 *ret_stack
= runtime_mallocgc(stacksize
, FlagNoProfiling
|FlagNoGC
, 0, 0);
1504 *ret_stacksize
= stacksize
;
1505 newg
->gcinitial_sp
= *ret_stack
;
1506 newg
->gcstack_size
= stacksize
;
1507 runtime_xadd(&runtime_stacks_sys
, stacksize
);
1513 /* For runtime package testing. */
1515 void runtime_testing_entersyscall(void)
1516 __asm__ (GOSYM_PREFIX
"runtime.entersyscall");
1519 runtime_testing_entersyscall()
1521 runtime_entersyscall();
1524 void runtime_testing_exitsyscall(void)
1525 __asm__ (GOSYM_PREFIX
"runtime.exitsyscall");
1528 runtime_testing_exitsyscall()
1530 runtime_exitsyscall();
1534 __go_go(void (*fn
)(void*), void* arg
)
1541 goid
= runtime_xadd64((uint64
*)&runtime_sched
.goidgen
, 1);
1543 runtime_racegostart(goid
, runtime_getcallerpc(&fn
));
1547 if((newg
= gfget()) != nil
) {
1548 #ifdef USING_SPLIT_STACK
1549 int dont_block_signals
= 0;
1551 sp
= __splitstack_resetcontext(&newg
->stack_context
[0],
1553 __splitstack_block_signals_context(&newg
->stack_context
[0],
1554 &dont_block_signals
, nil
);
1556 sp
= newg
->gcinitial_sp
;
1557 spsize
= newg
->gcstack_size
;
1559 runtime_throw("bad spsize in __go_go");
1560 newg
->gcnext_sp
= sp
;
1563 newg
= runtime_malg(StackMin
, &sp
, &spsize
);
1564 if(runtime_lastg
== nil
)
1565 runtime_allg
= newg
;
1567 runtime_lastg
->alllink
= newg
;
1568 runtime_lastg
= newg
;
1570 newg
->status
= Gwaiting
;
1571 newg
->waitreason
= "new goroutine";
1573 newg
->entry
= (byte
*)fn
;
1575 newg
->gopc
= (uintptr
)__builtin_return_address(0);
1577 runtime_sched
.gcount
++;
1581 runtime_throw("nil g->stack0");
1584 // Avoid warnings about variables clobbered by
1586 byte
* volatile vsp
= sp
;
1587 size_t volatile vspsize
= spsize
;
1588 G
* volatile vnewg
= newg
;
1590 getcontext(&vnewg
->context
);
1591 vnewg
->context
.uc_stack
.ss_sp
= vsp
;
1592 #ifdef MAKECONTEXT_STACK_TOP
1593 vnewg
->context
.uc_stack
.ss_sp
+= vspsize
;
1595 vnewg
->context
.uc_stack
.ss_size
= vspsize
;
1596 makecontext(&vnewg
->context
, kickoff
, 0);
1598 newprocreadylocked(vnewg
);
1605 // Put on gfree list. Sched must be locked.
1609 gp
->schedlink
= runtime_sched
.gfree
;
1610 runtime_sched
.gfree
= gp
;
1613 // Get from gfree list. Sched must be locked.
1619 gp
= runtime_sched
.gfree
;
1621 runtime_sched
.gfree
= gp
->schedlink
;
1625 void runtime_Gosched (void) __asm__ (GOSYM_PREFIX
"runtime.Gosched");
1628 runtime_Gosched(void)
1633 // Implementation of runtime.GOMAXPROCS.
1634 // delete when scheduler is stronger
1636 runtime_gomaxprocsfunc(int32 n
)
1642 ret
= runtime_gomaxprocs
;
1645 if(n
> maxgomaxprocs
)
1647 runtime_gomaxprocs
= n
;
1648 if(runtime_gomaxprocs
> 1)
1649 runtime_singleproc
= false;
1650 if(runtime_gcwaiting
!= 0) {
1651 if(atomic_mcpumax(runtime_sched
.atomic
) != 1)
1652 runtime_throw("invalid mcpumax during gc");
1659 // If there are now fewer allowed procs
1660 // than procs running, stop.
1661 v
= runtime_atomicload(&runtime_sched
.atomic
);
1662 if((int32
)atomic_mcpu(v
) > n
) {
1667 // handle more procs
1674 runtime_LockOSThread(void)
1676 if(m
== &runtime_m0
&& runtime_sched
.init
) {
1677 runtime_sched
.lockmain
= true;
1685 runtime_UnlockOSThread(void)
1687 if(m
== &runtime_m0
&& runtime_sched
.init
) {
1688 runtime_sched
.lockmain
= false;
1696 runtime_lockedOSThread(void)
1698 return g
->lockedm
!= nil
&& m
->lockedg
!= nil
;
1701 // for testing of callbacks
1703 _Bool
runtime_golockedOSThread(void)
1704 __asm__ (GOSYM_PREFIX
"runtime.golockedOSThread");
1707 runtime_golockedOSThread(void)
1709 return runtime_lockedOSThread();
1712 // for testing of wire, unwire
1719 intgo
runtime_NumGoroutine (void)
1720 __asm__ (GOSYM_PREFIX
"runtime.NumGoroutine");
1723 runtime_NumGoroutine()
1725 return runtime_sched
.gcount
;
1729 runtime_gcount(void)
1731 return runtime_sched
.gcount
;
1735 runtime_mcount(void)
1737 return runtime_sched
.mcount
;
1742 void (*fn
)(uintptr
*, int32
);
1745 Location locbuf
[100];
1748 // Called if we receive a SIGPROF signal.
1754 if(prof
.fn
== nil
|| prof
.hz
== 0)
1757 runtime_lock(&prof
);
1758 if(prof
.fn
== nil
) {
1759 runtime_unlock(&prof
);
1762 n
= runtime_callers(0, prof
.locbuf
, nelem(prof
.locbuf
));
1763 for(i
= 0; i
< n
; i
++)
1764 prof
.pcbuf
[i
] = prof
.locbuf
[i
].pc
;
1766 prof
.fn(prof
.pcbuf
, n
);
1767 runtime_unlock(&prof
);
1770 // Arrange to call fn with a traceback hz times a second.
1772 runtime_setcpuprofilerate(void (*fn
)(uintptr
*, int32
), int32 hz
)
1774 // Force sane arguments.
1782 // Stop profiler on this cpu so that it is safe to lock prof.
1783 // if a profiling signal came in while we had prof locked,
1784 // it would deadlock.
1785 runtime_resetcpuprofiler(0);
1787 runtime_lock(&prof
);
1790 runtime_unlock(&prof
);
1791 runtime_lock(&runtime_sched
);
1792 runtime_sched
.profilehz
= hz
;
1793 runtime_unlock(&runtime_sched
);
1796 runtime_resetcpuprofiler(hz
);