1 #include "threadimpl.h"
5 static uint threadnproc;
6 static uint threadnsysproc;
7 static Lock threadnproclock;
8 static Ref threadidref;
9 static Proc *threadmainproc;
11 static void addproc(Proc*);
12 static void delproc(Proc*);
13 static void addthread(_Threadlist*, _Thread*);
14 static void delthread(_Threadlist*, _Thread*);
15 static int onlist(_Threadlist*, _Thread*);
16 static void addthreadinproc(Proc*, _Thread*);
17 static void delthreadinproc(Proc*, _Thread*);
18 static void contextswitch(Context *from, Context *to);
19 static void procmain(Proc*);
20 static void procscheduler(Proc*);
21 static int threadinfo(void*, char*);
24 _threaddebug(char *fmt, ...)
32 if(_threaddebuglevel == 0)
36 p = strrchr(argv0, '/');
41 snprint(buf, sizeof buf, "/tmp/%s.tlog", p);
42 if((fd = create(buf, OWRITE, 0666)) < 0)
43 fd = open("/dev/null", OWRITE);
44 if(fd >= 0 && fd != 2){
52 vsnprint(buf, sizeof buf, fmt, arg);
56 fprint(fd, "%d.%d: %s\n", getpid(), t->id, buf);
58 fprint(fd, "%d._: %s\n", getpid(), buf);
64 return proc()->thread;
66 _Thread *(*threadnow)(void) = getthreadnow;
73 p = malloc(sizeof *p);
75 sysfatal("procalloc malloc: %r");
76 memset(p, 0, sizeof *p);
78 lock(&threadnproclock);
80 unlock(&threadnproclock);
85 threadstart(uint y, uint x)
90 //print("threadstart\n");
91 z = (ulong)x << 16; /* hide undefined 32-bit shift from 32-bit compilers */
96 //print("threadstart sp=%p arg=%p startfn=%p t=%p\n", &t, t, t->startfn, t->startarg);
97 t->startfn(t->startarg);
98 /*print("threadexits %p\n", v); */
100 /*print("not reacehd\n"); */
104 threadalloc(void (*fn)(void*), void *arg, uint stack)
111 /* allocate the task and stack together */
112 t = malloc(sizeof *t);
114 sysfatal("threadalloc malloc: %r");
115 memset(t, 0, sizeof *t);
116 t->id = incref(&threadidref);
117 //print("fn=%p arg=%p\n", fn, arg);
120 //print("makecontext sp=%p t=%p startfn=%p\n", (char*)t->stk+t->stksize, t, t->startfn);
122 /* do a reasonable initialization */
125 t->stk = _threadstkalloc(stack);
127 sysfatal("threadalloc malloc stack: %r");
129 memset(&t->context.uc, 0, sizeof t->context.uc);
131 sigprocmask(SIG_BLOCK, &zero, &t->context.uc.uc_sigmask);
132 //print("makecontext sp=%p t=%p startfn=%p\n", (char*)t->stk+t->stksize, t, t->startfn);
134 /* must initialize with current context */
135 if(getcontext(&t->context.uc) < 0)
136 sysfatal("threadalloc getcontext: %r");
137 //print("makecontext sp=%p t=%p startfn=%p\n", (char*)t->stk+t->stksize, t, t->startfn);
139 /* call makecontext to do the real work. */
140 /* leave a few words open on both ends */
141 t->context.uc.uc_stack.ss_sp = (void*)(t->stk+8);
142 t->context.uc.uc_stack.ss_size = t->stksize-64;
143 #if defined(__sun__) && !defined(__MAKECONTEXT_V2_SOURCE) /* sigh */
144 /* can avoid this with __MAKECONTEXT_V2_SOURCE but only on SunOS 5.9 */
145 t->context.uc.uc_stack.ss_sp =
146 (char*)t->context.uc.uc_stack.ss_sp
147 +t->context.uc.uc_stack.ss_size;
150 * All this magic is because you have to pass makecontext a
151 * function that takes some number of word-sized variables,
152 * and on 64-bit machines pointers are bigger than words.
154 //print("makecontext sp=%p t=%p startfn=%p\n", (char*)t->stk+t->stksize, t, t->startfn);
157 z >>= 16; /* hide undefined 32-bit shift from 32-bit compilers */
159 makecontext(&t->context.uc, (void(*)(void))threadstart, 2, y, x);
165 _threadcreate(Proc *p, void (*fn)(void*), void *arg, uint stack)
169 /* defend against bad C libraries */
170 if(stack < (256<<10))
174 stack = 0; // not using it
175 t = threadalloc(fn, arg, stack);
177 addthreadinproc(p, t);
184 threadcreate(void (*fn)(void*), void *arg, uint stack)
188 t = _threadcreate(proc(), fn, arg, stack);
193 proccreate(void (*fn)(void*), void *arg, uint stack)
200 t = _threadcreate(p, fn, arg, stack);
201 id = t->id; /* t might be freed after _procstart */
202 _procstart(p, procmain);
213 /*print("threadswtch %p\n", p); */
214 if(p->thread->stk == nil)
217 contextswitch(&p->thread->context, &p->schedcontext);
221 _threadready(_Thread *t)
227 p->runrend.l = &p->lock;
228 addthread(&p->runqueue, t);
229 /*print("%d wake for job %d->%d\n", time(0), getpid(), p->osprocid); */
231 _procwakeupandunlock(&p->runrend);
245 p->runrend.l = &p->lock;
246 addthread(&p->idlequeue, p->thread);
249 return p->nswitch - n;
260 _threadready(p->thread);
262 return p->nswitch - n;
266 threadexits(char *msg)
273 utfecpy(p->msg, p->msg+sizeof p->msg, msg);
274 proc()->thread->exiting = 1;
285 fprint(2, "already pinning a thread - %p %p\n", p->pinthread, p->thread);
288 p->pinthread = p->thread;
297 if(p->pinthread != p->thread){
298 fprint(2, "wrong pinthread - %p %p\n", p->pinthread, p->thread);
305 threadsysfatal(char *fmt, va_list arg)
309 vseprint(buf, buf+sizeof(buf), fmt, arg);
311 fprint(2, "%s: %s\n", argv0 ? argv0 : "<prog>", buf);
316 contextswitch(Context *from, Context *to)
318 if(swapcontext(&from->uc, &to->uc) < 0){
319 fprint(2, "swapcontext failed: %r\n");
331 /* take out first thread to run on system stack */
332 t = p->runqueue.head;
333 delthread(&p->runqueue, t);
334 memset(&t->context.uc, 0, sizeof t->context.uc);
338 t->startfn(t->startarg);
344 procscheduler(Proc *p)
348 _threaddebug("scheduler enter");
349 //print("s %p\n", p);
355 delthreadinproc(p, t);
357 /*print("nthread %d\n", p->nthread); */
358 _threadstkfree(t->stk, t->stksize);
363 if((t = p->pinthread) != nil){
364 while(!onlist(&p->runqueue, t)){
365 p->runrend.l = &p->lock;
366 _threaddebug("scheduler sleep (pin)");
367 _procsleep(&p->runrend);
368 _threaddebug("scheduler wake (pin)");
371 while((t = p->runqueue.head) == nil){
374 if((t = p->idlequeue.head) != nil){
376 * Run all the idling threads once.
378 while((t = p->idlequeue.head) != nil){
379 delthread(&p->idlequeue, t);
380 addthread(&p->runqueue, t);
384 p->runrend.l = &p->lock;
385 _threaddebug("scheduler sleep");
386 _procsleep(&p->runrend);
387 _threaddebug("scheduler wake");
389 if(p->pinthread && p->pinthread != t)
390 fprint(2, "p->pinthread %p t %p\n", p->pinthread, t);
391 assert(p->pinthread == nil || p->pinthread == t);
392 delthread(&p->runqueue, t);
396 _threaddebug("run %d (%s)", t->id, t->name);
397 //print("run %p %p %p %p\n", t, *(uintptr*)(t->context.uc.mc.sp), t->context.uc.mc.di, t->context.uc.mc.si);
400 contextswitch(&p->schedcontext, &t->context);
401 /*print("back in scheduler\n"); */
406 _threaddebug("scheduler exit");
409 * Stupid bug - on Linux 2.6 and maybe elsewhere,
410 * if the main thread exits then the others keep running
411 * but the process shows up as a zombie in ps and is not
412 * attachable with ptrace. We'll just sit around pretending
413 * to be a system proc instead of exiting.
416 lock(&threadnproclock);
417 if(++threadnsysproc == threadnproc)
418 threadexitsall(p->msg);
420 unlock(&threadnproclock);
426 lock(&threadnproclock);
429 if(--threadnproc == threadnsysproc)
430 threadexitsall(p->msg);
431 unlock(&threadnproclock);
439 _threadsetsysproc(void)
441 lock(&threadnproclock);
442 if(++threadnsysproc == threadnproc)
444 unlock(&threadnproclock);
451 return &proc()->udata;
457 return &proc()->thread->udata;
460 extern Jmp *(*_notejmpbuf)(void);
464 return &proc()->sigjmp;
471 threadsetname(char *fmt, ...)
478 vsnprint(t->name, sizeof t->name, fmt, arg);
485 return proc()->thread->name;
489 threadsetstate(char *fmt, ...)
496 vsnprint(t->state, sizeof t->name, fmt, arg);
518 if((char*)&t <= (char*)t->stk
519 || (char*)&t - (char*)t->stk < 256+n){
520 fprint(2, "thread stack overflow: &t=%p tstk=%p n=%d\n", &t, t->stk, 256+n);
528 return threadnproc == 1 && _threadprocs->nthread == 1;
535 threadqlock(QLock *l, int block, ulong pc)
537 /*print("threadqlock %p\n", l); */
540 l->owner = (*threadnow)();
541 /*print("qlock %p @%#x by %p\n", l, pc, l->owner); */
550 if(singlethreaded()){
551 fprint(2, "qlock deadlock\n");
555 /*print("qsleep %p @%#x by %p\n", l, pc, (*threadnow)()); */
556 addthread(&l->waiting, (*threadnow)());
561 if(l->owner != (*threadnow)()){
562 fprint(2, "%s: qlock pc=0x%lux owner=%p self=%p oops\n",
563 argv0, pc, l->owner, (*threadnow)());
566 /*print("qlock wakeup %p @%#x by %p\n", l, pc, (*threadnow)()); */
571 threadqunlock(QLock *l, ulong pc)
576 /*print("qlock unlock %p @%#x by %p (owner %p)\n", l, pc, (*threadnow)(), l->owner); */
578 fprint(2, "%s: qunlock pc=0x%lux owner=%p self=%p oops\n",
579 argv0, pc, l->owner, (*threadnow)());
582 if((l->owner = ready = l->waiting.head) != nil)
583 delthread(&l->waiting, l->owner);
585 * N.B. Cannot call _threadready() before unlocking l->l,
586 * because the thread we are readying might:
587 * - be in another proc
588 * - start running immediately
589 * - and free l before we get a chance to run again
593 _threadready(l->owner);
597 threadrlock(RWLock *l, int block, ulong pc)
602 if(l->writer == nil && l->wwaiting.head == nil){
611 if(singlethreaded()){
612 fprint(2, "rlock deadlock\n");
615 addthread(&l->rwaiting, (*threadnow)());
622 threadwlock(RWLock *l, int block, ulong pc)
627 if(l->writer == nil && l->readers == 0){
628 l->writer = (*threadnow)();
636 if(singlethreaded()){
637 fprint(2, "wlock deadlock\n");
640 addthread(&l->wwaiting, (*threadnow)());
647 threadrunlock(RWLock *l, ulong pc)
655 if(l->readers == 0 && (t = l->wwaiting.head) != nil){
656 delthread(&l->wwaiting, t);
666 threadwunlock(RWLock *l, ulong pc)
673 assert(l->readers == 0);
674 while((t = l->rwaiting.head) != nil){
675 delthread(&l->rwaiting, t);
680 if(l->readers == 0 && (t = l->wwaiting.head) != nil){
681 delthread(&l->wwaiting, t);
693 threadrsleep(Rendez *r, ulong pc)
695 if(singlethreaded()){
696 fprint(2, "rsleep deadlock\n");
699 addthread(&r->waiting, proc()->thread);
706 threadrwakeup(Rendez *r, int all, ulong pc)
714 if((t = r->waiting.head) == nil)
716 delthread(&r->waiting, t);
726 static int threadargc;
727 static char **threadargv;
729 extern int _p9usepwlibrary; /* getgrgid etc. smash the stack - tell _p9dir just say no */
731 threadmainstart(void *v)
736 * N.B. This call to proc() is a program's first call (indirectly) to a
737 * pthreads function while executing on a non-pthreads-allocated
738 * stack. If the pthreads implementation is using the stack pointer
739 * to locate the per-thread data, then this call will blow up.
740 * This means the pthread implementation is not suitable for
741 * running under libthread. Time to write your own. Sorry.
744 threadmainproc = proc();
745 threadmain(threadargc, threadargv);
748 extern void (*_sysfatal)(char*, va_list);
751 main(int argc, char **argv)
757 if(getenv("NOLIBTHREADDAEMONIZE") == nil)
758 _threadsetupdaemonize();
764 * Install locking routines into C library.
767 _unlock = _threadunlock;
768 _qlock = threadqlock;
769 _qunlock = threadqunlock;
770 _rlock = threadrlock;
771 _runlock = threadrunlock;
772 _wlock = threadwlock;
773 _wunlock = threadwunlock;
774 _rsleep = threadrsleep;
775 _rwakeup = threadrwakeup;
776 _notejmpbuf = threadnotejmp;
778 _unpin = threadunpin;
779 _sysfatal = threadsysfatal;
785 if(mainstacksize == 0)
786 mainstacksize = 256*1024;
787 atnotify(threadinfo, 1);
788 _threadcreate(p, threadmainstart, nil, mainstacksize);
790 sysfatal("procscheduler returned in threadmain!");
791 /* does not return */
796 * hooray for linked lists
799 addthread(_Threadlist *l, _Thread *t)
813 delthread(_Threadlist *l, _Thread *t)
816 t->prev->next = t->next;
820 t->next->prev = t->prev;
825 /* inefficient but rarely used */
827 onlist(_Threadlist *l, _Thread *t)
831 for(tt = l->head; tt; tt=tt->next)
838 addthreadinproc(Proc *p, _Thread *t)
844 l->tail->allnext = t;
845 t->allprev = l->tail;
855 delthreadinproc(Proc *p, _Thread *t)
861 t->allprev->allnext = t->allnext;
863 l->head = t->allnext;
865 t->allnext->allprev = t->allprev;
867 l->tail = t->allprev;
871 Lock _threadprocslock;
872 static Proc *_threadprocstail;
877 lock(&_threadprocslock);
878 if(_threadprocstail){
879 _threadprocstail->next = p;
880 p->prev = _threadprocstail;
885 _threadprocstail = p;
887 unlock(&_threadprocslock);
893 lock(&_threadprocslock);
895 p->prev->next = p->next;
897 _threadprocs = p->next;
899 p->next->prev = p->prev;
901 _threadprocstail = p->prev;
902 unlock(&_threadprocslock);
906 * notify - for now just use the usual mechanisms
909 threadnotify(int (*f)(void*, char*), int in)
915 onrunqueue(Proc *p, _Thread *t)
919 for(tt=p->runqueue.head; tt; tt=tt->next)
926 * print state - called from SIGINFO
929 threadinfo(void *v, char *s)
934 if(strcmp(s, "quit") != 0 && strcmp(s, "sys: status request") != 0)
937 for(p=_threadprocs; p; p=p->next){
938 fprint(2, "proc %p %s%s\n", (void*)p->osprocid, p->msg,
939 p->sysproc ? " (sysproc)": "");
940 for(t=p->allthreads.head; t; t=t->allnext){
941 fprint(2, "\tthread %d %s: %s %s\n",
943 t == p->thread ? "Running" :
944 onrunqueue(p, t) ? "Ready" : "Sleeping",