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
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 2 * 1024 * 1024
55 uintptr runtime_stacks_sys
;
57 static void schedule(G
*);
59 static void gtraceback(G
*);
61 typedef struct Sched Sched
;
64 G runtime_g0
; // idle goroutine for m0
73 #ifndef SETCONTEXT_CLOBBERS_TLS
81 fixcontext(ucontext_t
*c
__attribute__ ((unused
)))
87 # if defined(__x86_64__) && defined(__sun__)
89 // x86_64 Solaris 10 and 11 have a bug: setcontext switches the %fs
90 // register to that of the thread which called getcontext. The effect
91 // is that the address of all __thread variables changes. This bug
92 // also affects pthread_self() and pthread_getspecific. We work
93 // around it by clobbering the context field directly to keep %fs the
96 static __thread greg_t fs
;
104 fs
= c
.uc_mcontext
.gregs
[REG_FSBASE
];
108 fixcontext(ucontext_t
* c
)
110 c
->uc_mcontext
.gregs
[REG_FSBASE
] = fs
;
113 # elif defined(__NetBSD__)
115 // NetBSD has a bug: setcontext clobbers tlsbase, we need to save
116 // and restore it ourselves.
118 static __thread __greg_t tlsbase
;
126 tlsbase
= c
.uc_mcontext
._mc_tlsbase
;
130 fixcontext(ucontext_t
* c
)
132 c
->uc_mcontext
._mc_tlsbase
= tlsbase
;
137 # error unknown case for SETCONTEXT_CLOBBERS_TLS
143 // We can not always refer to the TLS variables directly. The
144 // compiler will call tls_get_addr to get the address of the variable,
145 // and it may hold it in a register across a call to schedule. When
146 // we get back from the call we may be running in a different thread,
147 // in which case the register now points to the TLS variable for a
148 // different thread. We use non-inlinable functions to avoid this
151 G
* runtime_g(void) __attribute__ ((noinline
, no_split_stack
));
159 M
* runtime_m(void) __attribute__ ((noinline
, no_split_stack
));
167 int32 runtime_gcwaiting
;
169 // The static TLS size. See runtime_newm.
172 #ifdef HAVE_DL_ITERATE_PHDR
174 // Called via dl_iterate_phdr.
177 addtls(struct dl_phdr_info
* info
, size_t size
__attribute__ ((unused
)), void *data
)
179 size_t *total
= (size_t *)data
;
182 for(i
= 0; i
< info
->dlpi_phnum
; ++i
) {
183 if(info
->dlpi_phdr
[i
].p_type
== PT_TLS
)
184 *total
+= info
->dlpi_phdr
[i
].p_memsz
;
189 // Set the total TLS size.
196 dl_iterate_phdr(addtls
, (void *)&total
);
211 // The go scheduler's job is to match ready-to-run goroutines (`g's)
212 // with waiting-for-work schedulers (`m's). If there are ready g's
213 // and no waiting m's, ready() will start a new m running in a new
214 // OS thread, so that all ready g's can run simultaneously, up to a limit.
215 // For now, m's never go away.
217 // By default, Go keeps only one kernel thread (m) running user code
218 // at a single time; other threads may be blocked in the operating system.
219 // Setting the environment variable $GOMAXPROCS or calling
220 // runtime.GOMAXPROCS() will change the number of user threads
221 // allowed to execute simultaneously. $GOMAXPROCS is thus an
222 // approximation of the maximum number of cores to use.
224 // Even a program that can run without deadlock in a single process
225 // might use more m's if given the chance. For example, the prime
226 // sieve will use as many m's as there are primes (up to runtime_sched.mmax),
227 // allowing different stages of the pipeline to execute in parallel.
228 // We could revisit this choice, only kicking off new m's for blocking
229 // system calls, but that would limit the amount of parallel computation
230 // that go would try to do.
232 // In general, one could imagine all sorts of refinements to the
233 // scheduler, but the goal now is just to get something working on
239 G
*gfree
; // available g's (status == Gdead)
242 G
*ghead
; // g's waiting to run
244 int32 gwait
; // number of g's waiting to run
245 int32 gcount
; // number of g's that are alive
246 int32 grunning
; // number of g's running on cpu or in syscall
248 M
*mhead
; // m's waiting for work
249 int32 mwait
; // number of m's waiting for work
250 int32 mcount
; // number of m's that have been created
252 volatile uint32 atomic
; // atomic scheduling word (see below)
254 int32 profilehz
; // cpu profiling rate
256 bool init
; // running initialization
257 bool lockmain
; // init called runtime.LockOSThread
259 Note stopped
; // one g can set waitstop and wait here for m's to stop
262 // The atomic word in sched is an atomic uint32 that
263 // holds these fields.
265 // [15 bits] mcpu number of m's executing on cpu
266 // [15 bits] mcpumax max number of m's allowed on cpu
267 // [1 bit] waitstop some g is waiting on stopped
268 // [1 bit] gwaiting gwait != 0
270 // These fields are the information needed by entersyscall
271 // and exitsyscall to decide whether to coordinate with the
272 // scheduler. Packing them into a single machine word lets
273 // them use a fast path with a single atomic read/write and
274 // no lock/unlock. This greatly reduces contention in
275 // syscall- or cgo-heavy multithreaded programs.
277 // Except for entersyscall and exitsyscall, the manipulations
278 // to these fields only happen while holding the schedlock,
279 // so the routines holding schedlock only need to worry about
280 // what entersyscall and exitsyscall do, not the other routines
281 // (which also use the schedlock).
283 // In particular, entersyscall and exitsyscall only read mcpumax,
284 // waitstop, and gwaiting. They never write them. Thus, writes to those
285 // fields can be done (holding schedlock) without fear of write conflicts.
286 // There may still be logic conflicts: for example, the set of waitstop must
287 // be conditioned on mcpu >= mcpumax or else the wait may be a
288 // spurious sleep. The Promela model in proc.p verifies these accesses.
291 mcpuMask
= (1<<mcpuWidth
) - 1,
293 mcpumaxShift
= mcpuShift
+ mcpuWidth
,
294 waitstopShift
= mcpumaxShift
+ mcpuWidth
,
295 gwaitingShift
= waitstopShift
+1,
297 // The max value of GOMAXPROCS is constrained
298 // by the max value we can store in the bit fields
299 // of the atomic word. Reserve a few high values
300 // so that we can detect accidental decrement
302 maxgomaxprocs
= mcpuMask
- 10,
305 #define atomic_mcpu(v) (((v)>>mcpuShift)&mcpuMask)
306 #define atomic_mcpumax(v) (((v)>>mcpumaxShift)&mcpuMask)
307 #define atomic_waitstop(v) (((v)>>waitstopShift)&1)
308 #define atomic_gwaiting(v) (((v)>>gwaitingShift)&1)
311 int32 runtime_gomaxprocs
;
312 bool runtime_singleproc
;
314 static bool canaddmcpu(void);
316 // An m that is waiting for notewakeup(&m->havenextg). This may
317 // only be accessed while the scheduler lock is held. This is used to
318 // minimize the number of times we call notewakeup while the scheduler
319 // lock is held, since the m will normally move quickly to lock the
320 // scheduler itself, producing lock contention.
323 // Scheduling helpers. Sched must be locked.
324 static void gput(G
*); // put/get on ghead/gtail
325 static G
* gget(void);
326 static void mput(M
*); // put/get on mhead
328 static void gfput(G
*); // put/get on gfree
329 static G
* gfget(void);
330 static void matchmg(void); // match m's to g's
331 static void readylocked(G
*); // ready, but sched is locked
332 static void mnextg(M
*, G
*);
333 static void mcommoninit(M
*);
341 v
= runtime_sched
.atomic
;
343 w
&= ~(mcpuMask
<<mcpumaxShift
);
344 w
|= n
<<mcpumaxShift
;
345 if(runtime_cas(&runtime_sched
.atomic
, v
, w
))
350 // First function run by a new goroutine. This replaces gogocall.
356 if(g
->traceback
!= nil
)
359 fn
= (void (*)(void*))(g
->entry
);
364 // Switch context to a different goroutine. This is like longjmp.
365 static void runtime_gogo(G
*) __attribute__ ((noinline
));
367 runtime_gogo(G
* newg
)
369 #ifdef USING_SPLIT_STACK
370 __splitstack_setcontext(&newg
->stack_context
[0]);
373 newg
->fromgogo
= true;
374 fixcontext(&newg
->context
);
375 setcontext(&newg
->context
);
376 runtime_throw("gogo setcontext returned");
379 // Save context and call fn passing g as a parameter. This is like
380 // setjmp. Because getcontext always returns 0, unlike setjmp, we use
381 // g->fromgogo as a code. It will be true if we got here via
382 // setcontext. g == nil the first time this is called in a new m.
383 static void runtime_mcall(void (*)(G
*)) __attribute__ ((noinline
));
385 runtime_mcall(void (*pfn
)(G
*))
389 #ifndef USING_SPLIT_STACK
393 // Ensure that all registers are on the stack for the garbage
395 __builtin_unwind_init();
400 runtime_throw("runtime: mcall called on m->g0 stack");
404 #ifdef USING_SPLIT_STACK
405 __splitstack_getcontext(&g
->stack_context
[0]);
409 gp
->fromgogo
= false;
410 getcontext(&gp
->context
);
412 // When we return from getcontext, we may be running
413 // in a new thread. That means that m and g may have
414 // changed. They are global variables so we will
415 // reload them, but the addresses of m and g may be
416 // cached in our local stack frame, and those
417 // addresses may be wrong. Call functions to reload
418 // the values for this thread.
422 if(gp
->traceback
!= nil
)
425 if (gp
== nil
|| !gp
->fromgogo
) {
426 #ifdef USING_SPLIT_STACK
427 __splitstack_setcontext(&mp
->g0
->stack_context
[0]);
429 mp
->g0
->entry
= (byte
*)pfn
;
432 // It's OK to set g directly here because this case
433 // can not occur if we got here via a setcontext to
434 // the getcontext call just above.
437 fixcontext(&mp
->g0
->context
);
438 setcontext(&mp
->g0
->context
);
439 runtime_throw("runtime: mcall function returned");
443 // Keep trace of scavenger's goroutine for deadlock detection.
446 // The bootstrap sequence is:
450 // make & queue new G
451 // call runtime_mstart
453 // The new G calls runtime_main.
455 runtime_schedinit(void)
470 runtime_mallocinit();
477 // Allocate internal symbol table representation now,
478 // so that we don't need to call malloc when we crash.
479 // runtime_findfunc(0);
481 runtime_gomaxprocs
= 1;
482 p
= runtime_getenv("GOMAXPROCS");
483 if(p
!= nil
&& (n
= runtime_atoi(p
)) != 0) {
484 if(n
> maxgomaxprocs
)
486 runtime_gomaxprocs
= n
;
488 // wait for the main goroutine to start before taking
489 // GOMAXPROCS into account.
491 runtime_singleproc
= runtime_gomaxprocs
== 1;
493 canaddmcpu(); // mcpu++ to account for bootstrap m
494 m
->helpgc
= 1; // flag to tell schedule() to mcpu--
495 runtime_sched
.grunning
++;
497 // Can not enable GC until all roots are registered.
498 // mstats.enablegc = 1;
505 extern void main_init(void) __asm__ ("__go_init_main");
506 extern void main_main(void) __asm__ ("main.main");
508 // The main goroutine.
512 // Lock the main goroutine onto this, the main OS thread,
513 // during initialization. Most programs won't care, but a few
514 // do require certain calls to be made by the main thread.
515 // Those can arrange for main.main to run in the main thread
516 // by calling runtime.LockOSThread during initialization
517 // to preserve the lock.
518 runtime_LockOSThread();
519 // From now on, newgoroutines may use non-main threads.
520 setmcpumax(runtime_gomaxprocs
);
521 runtime_sched
.init
= true;
522 scvg
= __go_go(runtime_MHeap_Scavenger
, nil
);
524 runtime_sched
.init
= false;
525 if(!runtime_sched
.lockmain
)
526 runtime_UnlockOSThread();
528 // For gccgo we have to wait until after main is initialized
529 // to enable GC, because initializing main registers the GC
533 // The deadlock detection has false negatives.
534 // Let scvg start up, to eliminate the false negative
535 // for the trivial program func main() { select{} }.
546 // Lock the scheduler.
550 runtime_lock(&runtime_sched
);
553 // Unlock the scheduler.
561 runtime_unlock(&runtime_sched
);
563 runtime_notewakeup(&m
->havenextg
);
569 g
->status
= Gmoribund
;
574 runtime_goroutineheader(G
*gp
)
593 status
= gp
->waitreason
;
604 runtime_printf("goroutine %d [%s]:\n", gp
->goid
, status
);
608 runtime_goroutinetrailer(G
*g
)
610 if(g
!= nil
&& g
->gopc
!= 0 && g
->goid
!= 1) {
615 if(__go_file_line(g
->gopc
- 1, &fn
, &file
, &line
)) {
616 runtime_printf("created by %S\n", fn
);
617 runtime_printf("\t%S:%d\n", file
, line
);
630 runtime_tracebackothers(G
* volatile me
)
636 for(gp
= runtime_allg
; gp
!= nil
; gp
= gp
->alllink
) {
637 if(gp
== me
|| gp
->status
== Gdead
)
639 runtime_printf("\n");
640 runtime_goroutineheader(gp
);
642 // Our only mechanism for doing a stack trace is
643 // _Unwind_Backtrace. And that only works for the
644 // current thread, not for other random goroutines.
645 // So we need to switch context to the goroutine, get
646 // the backtrace, and then switch back.
648 // This means that if g is running or in a syscall, we
649 // can't reliably print a stack trace. FIXME.
650 if(gp
->status
== Gsyscall
|| gp
->status
== Grunning
) {
651 runtime_printf("no stack trace available\n");
652 runtime_goroutinetrailer(gp
);
656 gp
->traceback
= &traceback
;
658 #ifdef USING_SPLIT_STACK
659 __splitstack_getcontext(&me
->stack_context
[0]);
661 getcontext(&me
->context
);
663 if(gp
->traceback
!= nil
) {
667 runtime_printtrace(traceback
.pcbuf
, traceback
.c
);
668 runtime_goroutinetrailer(gp
);
672 // Do a stack trace of gp, and then restore the context to
678 Traceback
* traceback
;
680 traceback
= gp
->traceback
;
682 traceback
->c
= runtime_callers(1, traceback
->pcbuf
,
683 sizeof traceback
->pcbuf
/ sizeof traceback
->pcbuf
[0]);
684 runtime_gogo(traceback
->gp
);
687 // Mark this g as m's idle goroutine.
688 // This functionality might be used in environments where programs
689 // are limited to a single thread, to simulate a select-driven
690 // network server. It is not exposed via the standard runtime API.
692 runtime_idlegoroutine(void)
695 runtime_throw("g is already an idle goroutine");
702 mp
->id
= runtime_sched
.mcount
++;
703 mp
->fastrand
= 0x49f6428aUL
+ mp
->id
+ runtime_cputicks();
705 if(mp
->mcache
== nil
)
706 mp
->mcache
= runtime_allocmcache();
708 runtime_callers(1, mp
->createstack
, nelem(mp
->createstack
));
710 // Add to runtime_allm so garbage collector doesn't free m
711 // when it is just in a register or thread-local storage.
712 mp
->alllink
= runtime_allm
;
713 // runtime_NumCgoCall() iterates over allm w/o schedlock,
714 // so we need to publish it safely.
715 runtime_atomicstorep(&runtime_allm
, mp
);
718 // Try to increment mcpu. Report whether succeeded.
725 v
= runtime_sched
.atomic
;
726 if(atomic_mcpu(v
) >= atomic_mcpumax(v
))
728 if(runtime_cas(&runtime_sched
.atomic
, v
, v
+(1<<mcpuShift
)))
733 // Put on `g' queue. Sched must be locked.
739 // If g is wired, hand it off directly.
740 if((mp
= gp
->lockedm
) != nil
&& canaddmcpu()) {
745 // If g is the idle goroutine for an m, hand it off.
746 if(gp
->idlem
!= nil
) {
747 if(gp
->idlem
->idleg
!= nil
) {
748 runtime_printf("m%d idle out of sync: g%d g%d\n",
750 gp
->idlem
->idleg
->goid
, gp
->goid
);
751 runtime_throw("runtime: double idle");
753 gp
->idlem
->idleg
= gp
;
758 if(runtime_sched
.ghead
== nil
)
759 runtime_sched
.ghead
= gp
;
761 runtime_sched
.gtail
->schedlink
= gp
;
762 runtime_sched
.gtail
= gp
;
765 // if it transitions to nonzero, set atomic gwaiting bit.
766 if(runtime_sched
.gwait
++ == 0)
767 runtime_xadd(&runtime_sched
.atomic
, 1<<gwaitingShift
);
770 // Report whether gget would return something.
774 return runtime_sched
.ghead
!= nil
|| m
->idleg
!= nil
;
777 // Get from `g' queue. Sched must be locked.
783 gp
= runtime_sched
.ghead
;
785 runtime_sched
.ghead
= gp
->schedlink
;
786 if(runtime_sched
.ghead
== nil
)
787 runtime_sched
.gtail
= nil
;
789 // if it transitions to zero, clear atomic gwaiting bit.
790 if(--runtime_sched
.gwait
== 0)
791 runtime_xadd(&runtime_sched
.atomic
, -1<<gwaitingShift
);
792 } else if(m
->idleg
!= nil
) {
799 // Put on `m' list. Sched must be locked.
803 mp
->schedlink
= runtime_sched
.mhead
;
804 runtime_sched
.mhead
= mp
;
805 runtime_sched
.mwait
++;
808 // Get an `m' to run `g'. Sched must be locked.
814 // if g has its own m, use it.
815 if(gp
&& (mp
= gp
->lockedm
) != nil
)
818 // otherwise use general m pool.
819 if((mp
= runtime_sched
.mhead
) != nil
) {
820 runtime_sched
.mhead
= mp
->schedlink
;
821 runtime_sched
.mwait
--;
826 // Mark g ready to run.
835 // Mark g ready to run. Sched is already locked.
836 // G might be running already and about to stop.
837 // The sched lock protects g->status from changing underfoot.
842 // Running on another machine.
843 // Ready it when it stops.
849 if(gp
->status
== Grunnable
|| gp
->status
== Grunning
) {
850 runtime_printf("goroutine %d has status %d\n", gp
->goid
, gp
->status
);
851 runtime_throw("bad g->status in ready");
853 gp
->status
= Grunnable
;
859 // Same as readylocked but a different symbol so that
860 // debuggers can set a breakpoint here and catch all
863 newprocreadylocked(G
*gp
)
868 // Pass g to m for running.
869 // Caller has already incremented mcpu.
873 runtime_sched
.grunning
++;
878 runtime_notewakeup(&mwakeup
->havenextg
);
883 // Get the next goroutine that m should run.
884 // Sched must be locked on entry, is unlocked on exit.
885 // Makes sure that at most $GOMAXPROCS g's are
886 // running on cpus (not in system calls) at any given time.
894 if(atomic_mcpu(runtime_sched
.atomic
) >= maxgomaxprocs
)
895 runtime_throw("negative mcpu");
897 // If there is a g waiting as m->nextg, the mcpu++
898 // happened before it was passed to mnextg.
899 if(m
->nextg
!= nil
) {
906 if(m
->lockedg
!= nil
) {
907 // We can only run one g, and it's not available.
908 // Make sure some other cpu is running to handle
909 // the ordinary run queue.
910 if(runtime_sched
.gwait
!= 0) {
912 // m->lockedg might have been on the queue.
913 if(m
->nextg
!= nil
) {
921 // Look for work on global queue.
922 while(haveg() && canaddmcpu()) {
925 runtime_throw("gget inconsistency");
928 mnextg(gp
->lockedm
, gp
);
931 runtime_sched
.grunning
++;
936 // The while loop ended either because the g queue is empty
937 // or because we have maxed out our m procs running go
938 // code (mcpu >= mcpumax). We need to check that
939 // concurrent actions by entersyscall/exitsyscall cannot
940 // invalidate the decision to end the loop.
942 // We hold the sched lock, so no one else is manipulating the
943 // g queue or changing mcpumax. Entersyscall can decrement
944 // mcpu, but if does so when there is something on the g queue,
945 // the gwait bit will be set, so entersyscall will take the slow path
946 // and use the sched lock. So it cannot invalidate our decision.
948 // Wait on global m queue.
952 // Look for deadlock situation.
953 // There is a race with the scavenger that causes false negatives:
954 // if the scavenger is just starting, then we have
955 // scvg != nil && grunning == 0 && gwait == 0
956 // and we do not detect a deadlock. It is possible that we should
957 // add that case to the if statement here, but it is too close to Go 1
958 // to make such a subtle change. Instead, we work around the
959 // false negative in trivial programs by calling runtime.gosched
960 // from the main goroutine just before main.main.
961 // See runtime_main above.
963 // On a related note, it is also possible that the scvg == nil case is
964 // wrong and should include gwait, but that does not happen in
965 // standard Go programs, which all start the scavenger.
967 if((scvg
== nil
&& runtime_sched
.grunning
== 0) ||
968 (scvg
!= nil
&& runtime_sched
.grunning
== 1 && runtime_sched
.gwait
== 0 &&
969 (scvg
->status
== Grunning
|| scvg
->status
== Gsyscall
))) {
970 runtime_throw("all goroutines are asleep - deadlock!");
975 runtime_noteclear(&m
->havenextg
);
977 // Stoptheworld is waiting for all but its cpu to go to stop.
978 // Entersyscall might have decremented mcpu too, but if so
979 // it will see the waitstop and take the slow path.
980 // Exitsyscall never increments mcpu beyond mcpumax.
981 v
= runtime_atomicload(&runtime_sched
.atomic
);
982 if(atomic_waitstop(v
) && atomic_mcpu(v
) <= atomic_mcpumax(v
)) {
983 // set waitstop = 0 (known to be 1)
984 runtime_xadd(&runtime_sched
.atomic
, -1<<waitstopShift
);
985 runtime_notewakeup(&runtime_sched
.stopped
);
989 runtime_notesleep(&m
->havenextg
);
993 runtime_lock(&runtime_sched
);
996 if((gp
= m
->nextg
) == nil
)
997 runtime_throw("bad m->nextg in nextgoroutine");
1003 runtime_gcprocs(void)
1007 // Figure out how many CPUs to use during GC.
1008 // Limited by gomaxprocs, number of actual CPUs, and MaxGcproc.
1009 n
= runtime_gomaxprocs
;
1010 if(n
> runtime_ncpu
)
1011 n
= runtime_ncpu
> 0 ? runtime_ncpu
: 1;
1014 if(n
> runtime_sched
.mwait
+1) // one M is currently running
1015 n
= runtime_sched
.mwait
+1;
1020 runtime_helpgc(int32 nproc
)
1025 runtime_lock(&runtime_sched
);
1026 for(n
= 1; n
< nproc
; n
++) { // one M is currently running
1029 runtime_throw("runtime_gcprocs inconsistency");
1032 runtime_notewakeup(&mp
->havenextg
);
1034 runtime_unlock(&runtime_sched
);
1038 runtime_stoptheworld(void)
1043 runtime_gcwaiting
= 1;
1049 v
= runtime_sched
.atomic
;
1050 if(atomic_mcpu(v
) <= 1)
1053 // It would be unsafe for multiple threads to be using
1054 // the stopped note at once, but there is only
1055 // ever one thread doing garbage collection.
1056 runtime_noteclear(&runtime_sched
.stopped
);
1057 if(atomic_waitstop(v
))
1058 runtime_throw("invalid waitstop");
1060 // atomic { waitstop = 1 }, predicated on mcpu <= 1 check above
1061 // still being true.
1062 if(!runtime_cas(&runtime_sched
.atomic
, v
, v
+(1<<waitstopShift
)))
1066 runtime_notesleep(&runtime_sched
.stopped
);
1069 runtime_singleproc
= runtime_gomaxprocs
== 1;
1074 runtime_starttheworld(void)
1079 // Figure out how many CPUs GC could possibly use.
1080 max
= runtime_gomaxprocs
;
1081 if(max
> runtime_ncpu
)
1082 max
= runtime_ncpu
> 0 ? runtime_ncpu
: 1;
1087 runtime_gcwaiting
= 0;
1088 setmcpumax(runtime_gomaxprocs
);
1090 if(runtime_gcprocs() < max
&& canaddmcpu()) {
1091 // If GC could have used another helper proc, start one now,
1092 // in the hope that it will be available next time.
1093 // It would have been even better to start it before the collection,
1094 // but doing so requires allocating memory, so it's tricky to
1095 // coordinate. This lazy approach works out in practice:
1096 // we don't mind if the first couple gc rounds don't have quite
1097 // the maximum number of procs.
1098 // canaddmcpu above did mcpu++
1099 // (necessary, because m will be doing various
1100 // initialization work so is definitely running),
1101 // but m is not running a specific goroutine,
1102 // so set the helpgc flag as a signal to m's
1103 // first schedule(nil) to mcpu-- and grunning--.
1104 mp
= runtime_newm();
1106 runtime_sched
.grunning
++;
1111 // Called to start an M.
1113 runtime_mstart(void* mp
)
1123 // Record top of stack for use by mcall.
1124 // Once we call schedule we're never coming back,
1125 // so other calls can reuse this stack space.
1126 #ifdef USING_SPLIT_STACK
1127 __splitstack_getcontext(&g
->stack_context
[0]);
1129 g
->gcinitial_sp
= &mp
;
1130 // Setting gcstack_size to 0 is a marker meaning that gcinitial_sp
1131 // is the top of the stack, not the bottom.
1132 g
->gcstack_size
= 0;
1135 getcontext(&g
->context
);
1137 if(g
->entry
!= nil
) {
1138 // Got here from mcall.
1139 void (*pfn
)(G
*) = (void (*)(G
*))g
->entry
;
1140 G
* gp
= (G
*)g
->param
;
1146 #ifdef USING_SPLIT_STACK
1148 int dont_block_signals
= 0;
1149 __splitstack_block_signals(&dont_block_signals
, nil
);
1153 // Install signal handlers; after minit so that minit can
1154 // prepare the thread to be able to handle the signals.
1155 if(m
== &runtime_m0
)
1160 // TODO(brainman): This point is never reached, because scheduler
1161 // does not release os threads at the moment. But once this path
1162 // is enabled, we must remove our seh here.
1167 typedef struct CgoThreadStart CgoThreadStart
;
1168 struct CgoThreadStart
1175 // Kick off new m's as needed (up to mcpumax).
1183 if(m
->mallocing
|| m
->gcing
)
1186 while(haveg() && canaddmcpu()) {
1189 runtime_throw("gget inconsistency");
1191 // Find the m that will run gp.
1192 if((mp
= mget(gp
)) == nil
)
1193 mp
= runtime_newm();
1198 // Create a new m. It will start off with a call to runtime_mstart.
1203 pthread_attr_t attr
;
1207 mp
= runtime_malloc(sizeof(M
));
1209 mp
->g0
= runtime_malg(-1, nil
, nil
);
1211 if(pthread_attr_init(&attr
) != 0)
1212 runtime_throw("pthread_attr_init");
1213 if(pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0)
1214 runtime_throw("pthread_attr_setdetachstate");
1216 stacksize
= PTHREAD_STACK_MIN
;
1218 // With glibc before version 2.16 the static TLS size is taken
1219 // out of the stack size, and we get an error or a crash if
1220 // there is not enough stack space left. Add it back in if we
1221 // can, in case the program uses a lot of TLS space. FIXME:
1222 // This can be disabled in glibc 2.16 and later, if the bug is
1223 // indeed fixed then.
1224 stacksize
+= tlssize
;
1226 if(pthread_attr_setstacksize(&attr
, stacksize
) != 0)
1227 runtime_throw("pthread_attr_setstacksize");
1229 if(pthread_create(&tid
, &attr
, runtime_mstart
, mp
) != 0)
1230 runtime_throw("pthread_create");
1235 // One round of scheduler: find a goroutine and run it.
1236 // The argument is the goroutine that was running before
1237 // schedule was called, or nil if this is the first call.
1247 // Just finished running gp.
1249 runtime_sched
.grunning
--;
1251 // atomic { mcpu-- }
1252 v
= runtime_xadd(&runtime_sched
.atomic
, -1<<mcpuShift
);
1253 if(atomic_mcpu(v
) > maxgomaxprocs
)
1254 runtime_throw("negative mcpu in scheduler");
1256 switch(gp
->status
) {
1259 // Shouldn't have been running!
1260 runtime_throw("bad gp->status in sched");
1262 gp
->status
= Grunnable
;
1267 runtime_racegoend(gp
->goid
);
1274 runtime_memclr(&gp
->context
, sizeof gp
->context
);
1276 if(--runtime_sched
.gcount
== 0)
1280 if(gp
->readyonstop
) {
1281 gp
->readyonstop
= 0;
1284 } else if(m
->helpgc
) {
1285 // Bootstrap m or new m started by starttheworld.
1286 // atomic { mcpu-- }
1287 v
= runtime_xadd(&runtime_sched
.atomic
, -1<<mcpuShift
);
1288 if(atomic_mcpu(v
) > maxgomaxprocs
)
1289 runtime_throw("negative mcpu in scheduler");
1290 // Compensate for increment in starttheworld().
1291 runtime_sched
.grunning
--;
1293 } else if(m
->nextg
!= nil
) {
1294 // New m started by matchmg.
1296 runtime_throw("invalid m state in scheduler");
1299 // Find (or wait for) g to run. Unlocks runtime_sched.
1300 gp
= nextgandunlock();
1301 gp
->readyonstop
= 0;
1302 gp
->status
= Grunning
;
1306 // Check whether the profiler needs to be turned on or off.
1307 hz
= runtime_sched
.profilehz
;
1308 if(m
->profilehz
!= hz
)
1309 runtime_resetcpuprofiler(hz
);
1314 // Enter scheduler. If g->status is Grunning,
1315 // re-queues g and runs everyone else who is waiting
1316 // before running g again. If g->status is Gmoribund,
1319 runtime_gosched(void)
1322 runtime_throw("gosched holding locks");
1324 runtime_throw("gosched of g0");
1325 runtime_mcall(schedule
);
1328 // Puts the current goroutine into a waiting state and unlocks the lock.
1329 // The goroutine can be made runnable again by calling runtime_ready(gp).
1331 runtime_park(void (*unlockf
)(Lock
*), Lock
*lock
, const char *reason
)
1333 g
->status
= Gwaiting
;
1334 g
->waitreason
= reason
;
1340 // The goroutine g is about to enter a system call.
1341 // Record that it's not using the cpu anymore.
1342 // This is called only from the go syscall library and cgocall,
1343 // not from the low-level system calls used by the runtime.
1345 // Entersyscall cannot split the stack: the runtime_gosave must
1346 // make g->sched refer to the caller's stack segment, because
1347 // entersyscall is going to return immediately after.
1348 // It's okay to call matchmg and notewakeup even after
1349 // decrementing mcpu, because we haven't released the
1350 // sched lock yet, so the garbage collector cannot be running.
1352 void runtime_entersyscall(void) __attribute__ ((no_split_stack
));
1355 runtime_entersyscall(void)
1359 if(m
->profilehz
> 0)
1360 runtime_setprof(false);
1362 // Leave SP around for gc and traceback.
1363 #ifdef USING_SPLIT_STACK
1364 g
->gcstack
= __splitstack_find(nil
, nil
, &g
->gcstack_size
,
1365 &g
->gcnext_segment
, &g
->gcnext_sp
,
1368 g
->gcnext_sp
= (byte
*) &v
;
1371 // Save the registers in the g structure so that any pointers
1372 // held in registers will be seen by the garbage collector.
1373 getcontext(&g
->gcregs
);
1375 g
->status
= Gsyscall
;
1378 // The slow path inside the schedlock/schedunlock will get
1379 // through without stopping if it does:
1382 // waitstop && mcpu <= mcpumax not true
1383 // If we can do the same with a single atomic add,
1384 // then we can skip the locks.
1385 v
= runtime_xadd(&runtime_sched
.atomic
, -1<<mcpuShift
);
1386 if(!atomic_gwaiting(v
) && (!atomic_waitstop(v
) || atomic_mcpu(v
) > atomic_mcpumax(v
)))
1390 v
= runtime_atomicload(&runtime_sched
.atomic
);
1391 if(atomic_gwaiting(v
)) {
1393 v
= runtime_atomicload(&runtime_sched
.atomic
);
1395 if(atomic_waitstop(v
) && atomic_mcpu(v
) <= atomic_mcpumax(v
)) {
1396 runtime_xadd(&runtime_sched
.atomic
, -1<<waitstopShift
);
1397 runtime_notewakeup(&runtime_sched
.stopped
);
1403 // The goroutine g exited its system call.
1404 // Arrange for it to run on a cpu again.
1405 // This is called only from the go syscall library, not
1406 // from the low-level system calls used by the runtime.
1408 runtime_exitsyscall(void)
1414 // If we can do the mcpu++ bookkeeping and
1415 // find that we still have mcpu <= mcpumax, then we can
1416 // start executing Go code immediately, without having to
1417 // schedlock/schedunlock.
1418 // Also do fast return if any locks are held, so that
1419 // panic code can use syscalls to open a file.
1421 v
= runtime_xadd(&runtime_sched
.atomic
, (1<<mcpuShift
));
1422 if((m
->profilehz
== runtime_sched
.profilehz
&& atomic_mcpu(v
) <= atomic_mcpumax(v
)) || m
->locks
> 0) {
1423 // There's a cpu for us, so we can run.
1424 gp
->status
= Grunning
;
1425 // Garbage collector isn't running (since we are),
1426 // so okay to clear gcstack.
1427 #ifdef USING_SPLIT_STACK
1430 gp
->gcnext_sp
= nil
;
1431 runtime_memclr(&gp
->gcregs
, sizeof gp
->gcregs
);
1433 if(m
->profilehz
> 0)
1434 runtime_setprof(true);
1438 // Tell scheduler to put g back on the run queue:
1439 // mostly equivalent to g->status = Grunning,
1440 // but keeps the garbage collector from thinking
1441 // that g is running right now, which it's not.
1442 gp
->readyonstop
= 1;
1444 // All the cpus are taken.
1445 // The scheduler will ready g and put this m to sleep.
1446 // When the scheduler takes g away from m,
1447 // it will undo the runtime_sched.mcpu++ above.
1450 // Gosched returned, so we're allowed to run now.
1451 // Delete the gcstack information that we left for
1452 // the garbage collector during the system call.
1453 // Must wait until now because until gosched returns
1454 // we don't know for sure that the garbage collector
1456 #ifdef USING_SPLIT_STACK
1459 gp
->gcnext_sp
= nil
;
1460 runtime_memclr(&gp
->gcregs
, sizeof gp
->gcregs
);
1463 // Allocate a new g, with a stack big enough for stacksize bytes.
1465 runtime_malg(int32 stacksize
, byte
** ret_stack
, size_t* ret_stacksize
)
1469 newg
= runtime_malloc(sizeof(G
));
1470 if(stacksize
>= 0) {
1471 #if USING_SPLIT_STACK
1472 int dont_block_signals
= 0;
1474 *ret_stack
= __splitstack_makecontext(stacksize
,
1475 &newg
->stack_context
[0],
1477 __splitstack_block_signals_context(&newg
->stack_context
[0],
1478 &dont_block_signals
, nil
);
1480 *ret_stack
= runtime_mallocgc(stacksize
, FlagNoProfiling
|FlagNoGC
, 0, 0);
1481 *ret_stacksize
= stacksize
;
1482 newg
->gcinitial_sp
= *ret_stack
;
1483 newg
->gcstack_size
= stacksize
;
1484 runtime_xadd(&runtime_stacks_sys
, stacksize
);
1490 /* For runtime package testing. */
1492 void runtime_testing_entersyscall(void)
1493 __asm__("runtime.entersyscall");
1496 runtime_testing_entersyscall()
1498 runtime_entersyscall();
1501 void runtime_testing_exitsyscall(void)
1502 __asm__("runtime.exitsyscall");
1505 runtime_testing_exitsyscall()
1507 runtime_exitsyscall();
1511 __go_go(void (*fn
)(void*), void* arg
)
1518 goid
= runtime_xadd((uint32
*)&runtime_sched
.goidgen
, 1);
1520 runtime_racegostart(goid
, runtime_getcallerpc(&fn
));
1524 if((newg
= gfget()) != nil
) {
1525 #ifdef USING_SPLIT_STACK
1526 int dont_block_signals
= 0;
1528 sp
= __splitstack_resetcontext(&newg
->stack_context
[0],
1530 __splitstack_block_signals_context(&newg
->stack_context
[0],
1531 &dont_block_signals
, nil
);
1533 sp
= newg
->gcinitial_sp
;
1534 spsize
= newg
->gcstack_size
;
1536 runtime_throw("bad spsize in __go_go");
1537 newg
->gcnext_sp
= sp
;
1540 newg
= runtime_malg(StackMin
, &sp
, &spsize
);
1541 if(runtime_lastg
== nil
)
1542 runtime_allg
= newg
;
1544 runtime_lastg
->alllink
= newg
;
1545 runtime_lastg
= newg
;
1547 newg
->status
= Gwaiting
;
1548 newg
->waitreason
= "new goroutine";
1550 newg
->entry
= (byte
*)fn
;
1552 newg
->gopc
= (uintptr
)__builtin_return_address(0);
1554 runtime_sched
.gcount
++;
1558 runtime_throw("nil g->stack0");
1561 // Avoid warnings about variables clobbered by
1563 byte
* volatile vsp
= sp
;
1564 size_t volatile vspsize
= spsize
;
1565 G
* volatile vnewg
= newg
;
1567 getcontext(&vnewg
->context
);
1568 vnewg
->context
.uc_stack
.ss_sp
= vsp
;
1569 #ifdef MAKECONTEXT_STACK_TOP
1570 vnewg
->context
.uc_stack
.ss_sp
+= vspsize
;
1572 vnewg
->context
.uc_stack
.ss_size
= vspsize
;
1573 makecontext(&vnewg
->context
, kickoff
, 0);
1575 newprocreadylocked(vnewg
);
1582 // Put on gfree list. Sched must be locked.
1586 gp
->schedlink
= runtime_sched
.gfree
;
1587 runtime_sched
.gfree
= gp
;
1590 // Get from gfree list. Sched must be locked.
1596 gp
= runtime_sched
.gfree
;
1598 runtime_sched
.gfree
= gp
->schedlink
;
1602 void runtime_Gosched (void) asm ("runtime.Gosched");
1605 runtime_Gosched(void)
1610 // Implementation of runtime.GOMAXPROCS.
1611 // delete when scheduler is stronger
1613 runtime_gomaxprocsfunc(int32 n
)
1619 ret
= runtime_gomaxprocs
;
1622 if(n
> maxgomaxprocs
)
1624 runtime_gomaxprocs
= n
;
1625 if(runtime_gomaxprocs
> 1)
1626 runtime_singleproc
= false;
1627 if(runtime_gcwaiting
!= 0) {
1628 if(atomic_mcpumax(runtime_sched
.atomic
) != 1)
1629 runtime_throw("invalid mcpumax during gc");
1636 // If there are now fewer allowed procs
1637 // than procs running, stop.
1638 v
= runtime_atomicload(&runtime_sched
.atomic
);
1639 if((int32
)atomic_mcpu(v
) > n
) {
1644 // handle more procs
1651 runtime_LockOSThread(void)
1653 if(m
== &runtime_m0
&& runtime_sched
.init
) {
1654 runtime_sched
.lockmain
= true;
1662 runtime_UnlockOSThread(void)
1664 if(m
== &runtime_m0
&& runtime_sched
.init
) {
1665 runtime_sched
.lockmain
= false;
1673 runtime_lockedOSThread(void)
1675 return g
->lockedm
!= nil
&& m
->lockedg
!= nil
;
1678 // for testing of callbacks
1680 _Bool
runtime_golockedOSThread(void)
1681 asm("runtime.golockedOSThread");
1684 runtime_golockedOSThread(void)
1686 return runtime_lockedOSThread();
1689 // for testing of wire, unwire
1696 intgo
runtime_NumGoroutine (void)
1697 __asm__ ("runtime.NumGoroutine");
1700 runtime_NumGoroutine()
1702 return runtime_sched
.gcount
;
1706 runtime_gcount(void)
1708 return runtime_sched
.gcount
;
1712 runtime_mcount(void)
1714 return runtime_sched
.mcount
;
1719 void (*fn
)(uintptr
*, int32
);
1724 // Called if we receive a SIGPROF signal.
1730 if(prof
.fn
== nil
|| prof
.hz
== 0)
1733 runtime_lock(&prof
);
1734 if(prof
.fn
== nil
) {
1735 runtime_unlock(&prof
);
1738 n
= runtime_callers(0, prof
.pcbuf
, nelem(prof
.pcbuf
));
1740 prof
.fn(prof
.pcbuf
, n
);
1741 runtime_unlock(&prof
);
1744 // Arrange to call fn with a traceback hz times a second.
1746 runtime_setcpuprofilerate(void (*fn
)(uintptr
*, int32
), int32 hz
)
1748 // Force sane arguments.
1756 // Stop profiler on this cpu so that it is safe to lock prof.
1757 // if a profiling signal came in while we had prof locked,
1758 // it would deadlock.
1759 runtime_resetcpuprofiler(0);
1761 runtime_lock(&prof
);
1764 runtime_unlock(&prof
);
1765 runtime_lock(&runtime_sched
);
1766 runtime_sched
.profilehz
= hz
;
1767 runtime_unlock(&runtime_sched
);
1770 runtime_resetcpuprofiler(hz
);