1 #include "threadimpl.h"
5 static uint threadnproc;
6 static uint threadnsysproc;
7 static Lock threadnproclock;
8 static Ref threadidref;
9 static Proc *threadmainproc;
10 static int pthreadperthread;
12 static void addproc(Proc*);
13 static void delproc(Proc*);
14 static void addthread(_Threadlist*, _Thread*);
15 static void delthread(_Threadlist*, _Thread*);
16 static int onlist(_Threadlist*, _Thread*);
17 static void addthreadinproc(Proc*, _Thread*);
18 static void delthreadinproc(Proc*, _Thread*);
19 static void contextswitch(Context *from, Context *to);
20 static void procmain(Proc*);
21 static void procscheduler(Proc*);
22 static int threadinfo(void*, char*);
25 _threaddebug(char *fmt, ...)
33 if(_threaddebuglevel == 0)
37 p = strrchr(argv0, '/');
42 snprint(buf, sizeof buf, "/tmp/%s.tlog", p);
43 if((fd = create(buf, OWRITE, 0666)) < 0)
44 fd = open("/dev/null", OWRITE);
45 if(fd >= 0 && fd != 2){
53 vsnprint(buf, sizeof buf, fmt, arg);
57 fprint(fd, "%p %d.%d: %s\n", proc(), getpid(), t->id, buf);
59 fprint(fd, "%p %d._: %s\n", proc(), getpid(), buf);
65 return proc()->thread;
67 _Thread *(*threadnow)(void) = getthreadnow;
74 p = malloc(sizeof *p);
76 sysfatal("procalloc malloc: %r");
77 memset(p, 0, sizeof *p);
79 lock(&threadnproclock);
81 unlock(&threadnproclock);
86 threadstart(uint y, uint x)
91 //print("threadstart\n");
92 z = (ulong)x << 16; /* hide undefined 32-bit shift from 32-bit compilers */
97 //print("threadstart sp=%p arg=%p startfn=%p t=%p\n", &t, t, t->startfn, t->startarg);
98 t->startfn(t->startarg);
99 /*print("threadexits %p\n", v); */
101 /*print("not reacehd\n"); */
105 threadalloc(void (*fn)(void*), void *arg, uint stack)
112 /* allocate the task and stack together */
113 t = malloc(sizeof *t);
115 sysfatal("threadalloc malloc: %r");
116 memset(t, 0, sizeof *t);
117 t->id = incref(&threadidref);
118 //print("fn=%p arg=%p\n", fn, arg);
121 //print("makecontext sp=%p t=%p startfn=%p\n", (char*)t->stk+t->stksize, t, t->startfn);
123 /* do a reasonable initialization */
126 t->stk = _threadstkalloc(stack);
128 sysfatal("threadalloc malloc stack: %r");
130 memset(&t->context.uc, 0, sizeof t->context.uc);
132 sigprocmask(SIG_BLOCK, &zero, &t->context.uc.uc_sigmask);
133 //print("makecontext sp=%p t=%p startfn=%p\n", (char*)t->stk+t->stksize, t, t->startfn);
135 /* must initialize with current context */
136 if(getcontext(&t->context.uc) < 0)
137 sysfatal("threadalloc getcontext: %r");
138 //print("makecontext sp=%p t=%p startfn=%p\n", (char*)t->stk+t->stksize, t, t->startfn);
141 * Call makecontext to do the real work.
142 * To avoid various mistakes on other system software,
143 * debuggers, and so on, don't get too close to both
144 * ends of the stack. Just staying away is much easier
145 * than debugging everything (outside our control)
146 * that has off-by-one errors.
148 t->context.uc.uc_stack.ss_sp = (void*)(t->stk+64);
149 t->context.uc.uc_stack.ss_size = t->stksize-2*64;
150 #if defined(__sun__) && !defined(__MAKECONTEXT_V2_SOURCE) /* sigh */
151 /* can avoid this with __MAKECONTEXT_V2_SOURCE but only on SunOS 5.9 */
152 t->context.uc.uc_stack.ss_sp =
153 (char*)t->context.uc.uc_stack.ss_sp
154 +t->context.uc.uc_stack.ss_size;
157 * All this magic is because you have to pass makecontext a
158 * function that takes some number of word-sized variables,
159 * and on 64-bit machines pointers are bigger than words.
161 //print("makecontext sp=%p t=%p startfn=%p\n", (char*)t->stk+t->stksize, t, t->startfn);
164 z >>= 16; /* hide undefined 32-bit shift from 32-bit compilers */
166 makecontext(&t->context.uc, (void(*)(void))threadstart, 2, y, x);
172 _threadcreate(Proc *p, void (*fn)(void*), void *arg, uint stack)
176 /* defend against bad C libraries */
177 if(stack < (256<<10))
180 if(p->nthread == 0 || pthreadperthread)
181 stack = 0; // not using it
182 t = threadalloc(fn, arg, stack);
186 else if(pthreadperthread)
187 _threadpthreadstart(p, t);
189 addthreadinproc(p, t);
195 threadcreate(void (*fn)(void*), void *arg, uint stack)
199 t = _threadcreate(proc(), fn, arg, stack);
204 proccreate(void (*fn)(void*), void *arg, uint stack)
211 t = _threadcreate(p, fn, arg, stack);
212 id = t->id; /* t might be freed after _procstart */
213 _procstart(p, procmain);
217 // For pthreadperthread mode, procswitch flips
218 // between the threads.
220 procswitch(Proc *p, _Thread *from, _Thread *to)
222 _threaddebug("procswitch %p %d %d", p, from?from->id:-1, to?to->id:-1);
224 from->schedrend.l = &p->schedlock;
227 to->schedrend.l = &p->schedlock;
228 _threaddebug("procswitch wakeup %p %d", p, to->id);
229 _procwakeup(&to->schedrend);
231 if(p->schedthread != from) {
233 unlock(&p->schedlock);
235 _threaddebug("procswitch exit wakeup!!!\n");
237 while(p->schedthread != from) {
238 _threaddebug("procswitch sleep %p %d", p, from->id);
239 _procsleep(&from->schedrend);
240 _threaddebug("procswitch awake %p %d", p, from->id);
242 if(p->schedthread != from)
243 sysfatal("_procswitch %p %p oops", p->schedthread, from);
245 unlock(&p->schedlock);
256 /*print("threadswtch %p\n", p); */
258 if(p->thread == p->thread0)
260 else if(pthreadperthread)
261 procswitch(p, p->thread, p->thread0);
263 contextswitch(&p->thread->context, &p->schedcontext);
267 _threadready(_Thread *t)
273 p->runrend.l = &p->lock;
274 addthread(&p->runqueue, t);
275 /*print("%d wake for job %d->%d\n", time(0), getpid(), p->osprocid); */
277 _procwakeupandunlock(&p->runrend);
291 p->runrend.l = &p->lock;
292 addthread(&p->idlequeue, p->thread);
295 return p->nswitch - n;
306 _threadready(p->thread);
308 return p->nswitch - n;
312 threadexits(char *msg)
319 utfecpy(p->msg, p->msg+sizeof p->msg, msg);
320 proc()->thread->exiting = 1;
331 fprint(2, "already pinning a thread - %p %p\n", p->pinthread, p->thread);
334 p->pinthread = p->thread;
343 if(p->pinthread != p->thread){
344 fprint(2, "wrong pinthread - %p %p\n", p->pinthread, p->thread);
351 threadsysfatal(char *fmt, va_list arg)
355 vseprint(buf, buf+sizeof(buf), fmt, arg);
357 fprint(2, "%s: %s\n", argv0 ? argv0 : "<prog>", buf);
362 contextswitch(Context *from, Context *to)
364 if(swapcontext(&from->uc, &to->uc) < 0){
365 fprint(2, "swapcontext failed: %r\n");
377 /* take out first thread to run on system stack */
378 t = p->runqueue.head;
379 delthread(&p->runqueue, t);
380 memset(&t->context.uc, 0, sizeof t->context.uc);
384 t->startfn(t->startarg);
390 _threadpthreadmain(Proc *p, _Thread *t)
393 procswitch(p, t, nil);
394 t->startfn(t->startarg);
399 procscheduler(Proc *p)
403 _threaddebug("scheduler enter");
404 //print("s %p\n", p);
410 delthreadinproc(p, t);
412 /*print("nthread %d\n", p->nthread); */
413 _threadstkfree(t->stk, t->stksize);
418 if((t = p->pinthread) != nil){
419 while(!onlist(&p->runqueue, t)){
420 p->runrend.l = &p->lock;
421 _threaddebug("scheduler sleep (pin)");
422 _procsleep(&p->runrend);
423 _threaddebug("scheduler wake (pin)");
426 while((t = p->runqueue.head) == nil){
429 if((t = p->idlequeue.head) != nil){
431 * Run all the idling threads once.
433 while((t = p->idlequeue.head) != nil){
434 delthread(&p->idlequeue, t);
435 addthread(&p->runqueue, t);
439 p->runrend.l = &p->lock;
440 _threaddebug("scheduler sleep");
441 _procsleep(&p->runrend);
442 _threaddebug("scheduler wake");
444 if(p->pinthread && p->pinthread != t)
445 fprint(2, "p->pinthread %p t %p\n", p->pinthread, t);
446 assert(p->pinthread == nil || p->pinthread == t);
447 delthread(&p->runqueue, t);
451 _threaddebug("run %d (%s)", t->id, t->name);
452 //print("run %p %p %p %p\n", t, *(uintptr*)(t->context.uc.mc.sp), t->context.uc.mc.di, t->context.uc.mc.si);
456 procswitch(p, p->thread0, t);
458 contextswitch(&p->schedcontext, &t->context);
459 _threaddebug("back in scheduler");
460 /*print("back in scheduler\n"); */
465 _threaddebug("scheduler exit");
468 * Stupid bug - on Linux 2.6 and maybe elsewhere,
469 * if the main thread exits then the others keep running
470 * but the process shows up as a zombie in ps and is not
471 * attachable with ptrace. We'll just sit around pretending
472 * to be a system proc instead of exiting.
475 lock(&threadnproclock);
476 if(++threadnsysproc == threadnproc)
477 threadexitsall(p->msg);
479 unlock(&threadnproclock);
485 lock(&threadnproclock);
488 if(--threadnproc == threadnsysproc)
489 threadexitsall(p->msg);
490 unlock(&threadnproclock);
498 _threadsetsysproc(void)
500 lock(&threadnproclock);
501 if(++threadnsysproc == threadnproc)
503 unlock(&threadnproclock);
510 return &proc()->udata;
516 return &proc()->thread->udata;
519 extern Jmp *(*_notejmpbuf)(void);
523 return &proc()->sigjmp;
530 threadsetname(char *fmt, ...)
537 vsnprint(t->name, sizeof t->name, fmt, arg);
544 return proc()->thread->name;
548 threadsetstate(char *fmt, ...)
555 vsnprint(t->state, sizeof t->name, fmt, arg);
577 if((char*)&t <= (char*)t->stk
578 || (char*)&t - (char*)t->stk < 256+n){
579 fprint(2, "thread stack overflow: &t=%p tstk=%p n=%d\n", &t, t->stk, 256+n);
587 return threadnproc == 1 && _threadprocs->nthread == 1;
594 threadqlock(QLock *l, int block, ulong pc)
596 /*print("threadqlock %p\n", l); */
599 l->owner = (*threadnow)();
600 /*print("qlock %p @%#x by %p\n", l, pc, l->owner); */
601 if(l->owner == nil) {
602 fprint(2, "%s: qlock uncontended owner=nil oops\n", argv0);
613 if(singlethreaded()){
614 fprint(2, "qlock deadlock\n");
618 /*print("qsleep %p @%#x by %p\n", l, pc, (*threadnow)()); */
619 addthread(&l->waiting, (*threadnow)());
624 if(l->owner != (*threadnow)()){
625 fprint(2, "%s: qlock pc=0x%lux owner=%p self=%p oops\n",
626 argv0, pc, l->owner, (*threadnow)());
629 if(l->owner == nil) {
630 fprint(2, "%s: qlock threadswitch owner=nil oops\n", argv0);
634 /*print("qlock wakeup %p @%#x by %p\n", l, pc, (*threadnow)()); */
639 threadqunlock(QLock *l, ulong pc)
644 /*print("qlock unlock %p @%#x by %p (owner %p)\n", l, pc, (*threadnow)(), l->owner); */
646 fprint(2, "%s: qunlock pc=0x%lux owner=%p self=%p oops\n",
647 argv0, pc, l->owner, (*threadnow)());
650 if((l->owner = ready = l->waiting.head) != nil)
651 delthread(&l->waiting, l->owner);
653 * N.B. Cannot call _threadready() before unlocking l->l,
654 * because the thread we are readying might:
655 * - be in another proc
656 * - start running immediately
657 * - and free l before we get a chance to run again
661 _threadready(l->owner);
665 threadrlock(RWLock *l, int block, ulong pc)
670 if(l->writer == nil && l->wwaiting.head == nil){
679 if(singlethreaded()){
680 fprint(2, "rlock deadlock\n");
683 addthread(&l->rwaiting, (*threadnow)());
690 threadwlock(RWLock *l, int block, ulong pc)
695 if(l->writer == nil && l->readers == 0){
696 l->writer = (*threadnow)();
704 if(singlethreaded()){
705 fprint(2, "wlock deadlock\n");
708 addthread(&l->wwaiting, (*threadnow)());
715 threadrunlock(RWLock *l, ulong pc)
723 if(l->readers == 0 && (t = l->wwaiting.head) != nil){
724 delthread(&l->wwaiting, t);
734 threadwunlock(RWLock *l, ulong pc)
741 assert(l->readers == 0);
742 while((t = l->rwaiting.head) != nil){
743 delthread(&l->rwaiting, t);
748 if(l->readers == 0 && (t = l->wwaiting.head) != nil){
749 delthread(&l->wwaiting, t);
761 threadrsleep(Rendez *r, ulong pc)
763 if(singlethreaded()){
764 fprint(2, "rsleep deadlock\n");
767 addthread(&r->waiting, proc()->thread);
774 threadrwakeup(Rendez *r, int all, ulong pc)
782 if((t = r->waiting.head) == nil)
784 delthread(&r->waiting, t);
794 static int threadargc;
795 static char **threadargv;
797 extern int _p9usepwlibrary; /* getgrgid etc. smash the stack - tell _p9dir just say no */
799 threadmainstart(void *v)
804 * N.B. This call to proc() is a program's first call (indirectly) to a
805 * pthreads function while executing on a non-pthreads-allocated
806 * stack. If the pthreads implementation is using the stack pointer
807 * to locate the per-thread data, then this call will blow up.
808 * This means the pthread implementation is not suitable for
809 * running under libthread. Time to write your own. Sorry.
812 threadmainproc = proc();
813 threadmain(threadargc, threadargv);
816 extern void (*_sysfatal)(char*, va_list);
819 main(int argc, char **argv)
826 opts = getenv("LIBTHREAD");
830 pthreadperthread = (strstr(opts, "pthreadperthread") != nil);
831 #ifdef PLAN9PORT_ASAN
832 // ASAN can't deal with the coroutine stack switches.
833 // In theory it has support for informing it about stack switches,
834 // but even with those calls added it can't deal with things
835 // like fork or exit from a coroutine stack.
836 // Easier to just run in pthread-per-thread mode.
837 pthreadperthread = 1;
839 if(strstr(opts, "nodaemon") == nil && getenv("NOLIBTHREADDAEMONIZE") == nil)
840 _threadsetupdaemonize();
846 * Install locking routines into C library.
849 _unlock = _threadunlock;
850 _qlock = threadqlock;
851 _qunlock = threadqunlock;
852 _rlock = threadrlock;
853 _runlock = threadrunlock;
854 _wlock = threadwlock;
855 _wunlock = threadwunlock;
856 _rsleep = threadrsleep;
857 _rwakeup = threadrwakeup;
858 _notejmpbuf = threadnotejmp;
860 _unpin = threadunpin;
861 _sysfatal = threadsysfatal;
867 if(mainstacksize == 0)
868 mainstacksize = 256*1024;
869 atnotify(threadinfo, 1);
870 _threadcreate(p, threadmainstart, nil, mainstacksize);
872 sysfatal("procscheduler returned in threadmain!");
873 /* does not return */
878 * hooray for linked lists
881 addthread(_Threadlist *l, _Thread *t)
895 delthread(_Threadlist *l, _Thread *t)
898 t->prev->next = t->next;
902 t->next->prev = t->prev;
907 /* inefficient but rarely used */
909 onlist(_Threadlist *l, _Thread *t)
913 for(tt = l->head; tt; tt=tt->next)
920 addthreadinproc(Proc *p, _Thread *t)
926 l->tail->allnext = t;
927 t->allprev = l->tail;
937 delthreadinproc(Proc *p, _Thread *t)
943 t->allprev->allnext = t->allnext;
945 l->head = t->allnext;
947 t->allnext->allprev = t->allprev;
949 l->tail = t->allprev;
953 Lock _threadprocslock;
954 static Proc *_threadprocstail;
959 lock(&_threadprocslock);
960 if(_threadprocstail){
961 _threadprocstail->next = p;
962 p->prev = _threadprocstail;
967 _threadprocstail = p;
969 unlock(&_threadprocslock);
975 lock(&_threadprocslock);
977 p->prev->next = p->next;
979 _threadprocs = p->next;
981 p->next->prev = p->prev;
983 _threadprocstail = p->prev;
984 unlock(&_threadprocslock);
988 * notify - for now just use the usual mechanisms
991 threadnotify(int (*f)(void*, char*), int in)
997 onrunqueue(Proc *p, _Thread *t)
1001 for(tt=p->runqueue.head; tt; tt=tt->next)
1008 * print state - called from SIGINFO
1011 threadinfo(void *v, char *s)
1016 if(strcmp(s, "quit") != 0 && strcmp(s, "sys: status request") != 0)
1019 for(p=_threadprocs; p; p=p->next){
1020 fprint(2, "proc %p %s%s\n", (void*)p->osprocid, p->msg,
1021 p->sysproc ? " (sysproc)": "");
1022 for(t=p->allthreads.head; t; t=t->allnext){
1023 fprint(2, "\tthread %d %s: %s %s\n",
1025 t == p->thread ? "Running" :
1026 onrunqueue(p, t) ? "Ready" : "Sleeping",