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 procscheduler(Proc*);
20 static int threadinfo(void*, char*);
23 _threaddebug(char *fmt, ...)
31 if(_threaddebuglevel == 0)
35 p = strrchr(argv0, '/');
40 snprint(buf, sizeof buf, "/tmp/%s.tlog", p);
41 if((fd = create(buf, OWRITE, 0666)) < 0)
42 fd = open("/dev/null", OWRITE);
43 if(fd >= 0 && fd != 2){
51 vsnprint(buf, sizeof buf, fmt, arg);
55 fprint(fd, "%d.%d: %s\n", getpid(), t->id, buf);
57 fprint(fd, "%d._: %s\n", getpid(), buf);
63 return proc()->thread;
65 _Thread *(*threadnow)(void) = getthreadnow;
72 p = malloc(sizeof *p);
74 sysfatal("procalloc malloc: %r");
75 memset(p, 0, sizeof *p);
77 lock(&threadnproclock);
79 unlock(&threadnproclock);
84 threadstart(uint y, uint x)
89 //print("threadstart\n");
90 z = (ulong)x << 16; /* hide undefined 32-bit shift from 32-bit compilers */
95 //print("threadstart sp=%p arg=%p startfn=%p t=%p\n", &t, t, t->startfn, t->startarg);
96 t->startfn(t->startarg);
97 /*print("threadexits %p\n", v); */
99 /*print("not reacehd\n"); */
103 threadalloc(void (*fn)(void*), void *arg, uint stack)
110 /* allocate the task and stack together */
111 t = malloc(sizeof *t+stack);
113 sysfatal("threadalloc malloc: %r");
114 memset(t, 0, sizeof *t);
115 t->stk = (uchar*)(t+1);
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 */
124 memset(&t->context.uc, 0, sizeof t->context.uc);
126 sigprocmask(SIG_BLOCK, &zero, &t->context.uc.uc_sigmask);
127 //print("makecontext sp=%p t=%p startfn=%p\n", (char*)t->stk+t->stksize, t, t->startfn);
129 /* must initialize with current context */
130 if(getcontext(&t->context.uc) < 0)
131 sysfatal("threadalloc getcontext: %r");
132 //print("makecontext sp=%p t=%p startfn=%p\n", (char*)t->stk+t->stksize, t, t->startfn);
134 /* call makecontext to do the real work. */
135 /* leave a few words open on both ends */
136 t->context.uc.uc_stack.ss_sp = (void*)(t->stk+8);
137 t->context.uc.uc_stack.ss_size = t->stksize-64;
138 #if defined(__sun__) && !defined(__MAKECONTEXT_V2_SOURCE) /* sigh */
139 /* can avoid this with __MAKECONTEXT_V2_SOURCE but only on SunOS 5.9 */
140 t->context.uc.uc_stack.ss_sp =
141 (char*)t->context.uc.uc_stack.ss_sp
142 +t->context.uc.uc_stack.ss_size;
145 * All this magic is because you have to pass makecontext a
146 * function that takes some number of word-sized variables,
147 * and on 64-bit machines pointers are bigger than words.
149 //print("makecontext sp=%p t=%p startfn=%p\n", (char*)t->stk+t->stksize, t, t->startfn);
152 z >>= 16; /* hide undefined 32-bit shift from 32-bit compilers */
154 makecontext(&t->context.uc, (void(*)(void))threadstart, 2, y, x);
160 _threadcreate(Proc *p, void (*fn)(void*), void *arg, uint stack)
164 /* defend against bad C libraries */
165 if(stack < (256<<10))
168 t = threadalloc(fn, arg, stack);
170 addthreadinproc(p, t);
177 threadcreate(void (*fn)(void*), void *arg, uint stack)
181 t = _threadcreate(proc(), fn, arg, stack);
186 proccreate(void (*fn)(void*), void *arg, uint stack)
193 t = _threadcreate(p, fn, arg, stack);
194 id = t->id; /* t might be freed after _procstart */
195 _procstart(p, procscheduler);
206 /*print("threadswtch %p\n", p); */
207 contextswitch(&p->thread->context, &p->schedcontext);
211 _threadready(_Thread *t)
217 p->runrend.l = &p->lock;
218 addthread(&p->runqueue, t);
219 /*print("%d wake for job %d->%d\n", time(0), getpid(), p->osprocid); */
221 _procwakeupandunlock(&p->runrend);
235 p->runrend.l = &p->lock;
236 addthread(&p->idlequeue, p->thread);
239 return p->nswitch - n;
250 _threadready(p->thread);
252 return p->nswitch - n;
256 threadexits(char *msg)
263 utfecpy(p->msg, p->msg+sizeof p->msg, msg);
264 proc()->thread->exiting = 1;
275 fprint(2, "already pinning a thread - %p %p\n", p->pinthread, p->thread);
278 p->pinthread = p->thread;
287 if(p->pinthread != p->thread){
288 fprint(2, "wrong pinthread - %p %p\n", p->pinthread, p->thread);
295 threadsysfatal(char *fmt, va_list arg)
299 vseprint(buf, buf+sizeof(buf), fmt, arg);
301 fprint(2, "%s: %s\n", argv0 ? argv0 : "<prog>", buf);
306 contextswitch(Context *from, Context *to)
308 if(swapcontext(&from->uc, &to->uc) < 0){
309 fprint(2, "swapcontext failed: %r\n");
315 procscheduler(Proc *p)
320 _threaddebug("scheduler enter");
321 //print("s %p\n", p);
324 if((t = p->pinthread) != nil){
325 while(!onlist(&p->runqueue, t)){
326 p->runrend.l = &p->lock;
327 _threaddebug("scheduler sleep (pin)");
328 _procsleep(&p->runrend);
329 _threaddebug("scheduler wake (pin)");
332 while((t = p->runqueue.head) == nil){
335 if((t = p->idlequeue.head) != nil){
337 * Run all the idling threads once.
339 while((t = p->idlequeue.head) != nil){
340 delthread(&p->idlequeue, t);
341 addthread(&p->runqueue, t);
345 p->runrend.l = &p->lock;
346 _threaddebug("scheduler sleep");
347 _procsleep(&p->runrend);
348 _threaddebug("scheduler wake");
350 if(p->pinthread && p->pinthread != t)
351 fprint(2, "p->pinthread %p t %p\n", p->pinthread, t);
352 assert(p->pinthread == nil || p->pinthread == t);
353 delthread(&p->runqueue, t);
357 _threaddebug("run %d (%s)", t->id, t->name);
358 //print("run %p %p %p %p\n", t, *(uintptr*)(t->context.uc.mc.sp), t->context.uc.mc.di, t->context.uc.mc.si);
359 contextswitch(&p->schedcontext, &t->context);
360 /*print("back in scheduler\n"); */
364 delthreadinproc(p, t);
366 /*print("nthread %d\n", p->nthread); */
372 _threaddebug("scheduler exit");
375 * Stupid bug - on Linux 2.6 and maybe elsewhere,
376 * if the main thread exits then the others keep running
377 * but the process shows up as a zombie in ps and is not
378 * attachable with ptrace. We'll just sit around pretending
379 * to be a system proc instead of exiting.
382 lock(&threadnproclock);
383 if(++threadnsysproc == threadnproc)
384 threadexitsall(p->msg);
386 unlock(&threadnproclock);
392 lock(&threadnproclock);
395 if(--threadnproc == threadnsysproc)
396 threadexitsall(p->msg);
397 unlock(&threadnproclock);
404 _threadsetsysproc(void)
406 lock(&threadnproclock);
407 if(++threadnsysproc == threadnproc)
409 unlock(&threadnproclock);
416 return &proc()->udata;
422 return &proc()->thread->udata;
425 extern Jmp *(*_notejmpbuf)(void);
429 return &proc()->sigjmp;
436 threadsetname(char *fmt, ...)
443 vsnprint(t->name, sizeof t->name, fmt, arg);
450 return proc()->thread->name;
454 threadsetstate(char *fmt, ...)
461 vsnprint(t->state, sizeof t->name, fmt, arg);
481 if((char*)&t <= (char*)t->stk
482 || (char*)&t - (char*)t->stk < 256+n){
483 fprint(2, "thread stack overflow: &t=%p tstk=%p n=%d\n", &t, t->stk, 256+n);
491 return threadnproc == 1 && _threadprocs->nthread == 1;
498 threadqlock(QLock *l, int block, ulong pc)
500 /*print("threadqlock %p\n", l); */
503 l->owner = (*threadnow)();
504 /*print("qlock %p @%#x by %p\n", l, pc, l->owner); */
513 if(singlethreaded()){
514 fprint(2, "qlock deadlock\n");
518 /*print("qsleep %p @%#x by %p\n", l, pc, (*threadnow)()); */
519 addthread(&l->waiting, (*threadnow)());
524 if(l->owner != (*threadnow)()){
525 fprint(2, "%s: qlock pc=0x%lux owner=%p self=%p oops\n",
526 argv0, pc, l->owner, (*threadnow)());
529 /*print("qlock wakeup %p @%#x by %p\n", l, pc, (*threadnow)()); */
534 threadqunlock(QLock *l, ulong pc)
539 /*print("qlock unlock %p @%#x by %p (owner %p)\n", l, pc, (*threadnow)(), l->owner); */
541 fprint(2, "%s: qunlock pc=0x%lux owner=%p self=%p oops\n",
542 argv0, pc, l->owner, (*threadnow)());
545 if((l->owner = ready = l->waiting.head) != nil)
546 delthread(&l->waiting, l->owner);
548 * N.B. Cannot call _threadready() before unlocking l->l,
549 * because the thread we are readying might:
550 * - be in another proc
551 * - start running immediately
552 * - and free l before we get a chance to run again
556 _threadready(l->owner);
560 threadrlock(RWLock *l, int block, ulong pc)
565 if(l->writer == nil && l->wwaiting.head == nil){
574 if(singlethreaded()){
575 fprint(2, "rlock deadlock\n");
578 addthread(&l->rwaiting, (*threadnow)());
585 threadwlock(RWLock *l, int block, ulong pc)
590 if(l->writer == nil && l->readers == 0){
591 l->writer = (*threadnow)();
599 if(singlethreaded()){
600 fprint(2, "wlock deadlock\n");
603 addthread(&l->wwaiting, (*threadnow)());
610 threadrunlock(RWLock *l, ulong pc)
618 if(l->readers == 0 && (t = l->wwaiting.head) != nil){
619 delthread(&l->wwaiting, t);
629 threadwunlock(RWLock *l, ulong pc)
636 assert(l->readers == 0);
637 while((t = l->rwaiting.head) != nil){
638 delthread(&l->rwaiting, t);
643 if(l->readers == 0 && (t = l->wwaiting.head) != nil){
644 delthread(&l->wwaiting, t);
656 threadrsleep(Rendez *r, ulong pc)
658 if(singlethreaded()){
659 fprint(2, "rsleep deadlock\n");
662 addthread(&r->waiting, proc()->thread);
669 threadrwakeup(Rendez *r, int all, ulong pc)
677 if((t = r->waiting.head) == nil)
679 delthread(&r->waiting, t);
689 static int threadargc;
690 static char **threadargv;
692 extern int _p9usepwlibrary; /* getgrgid etc. smash the stack - tell _p9dir just say no */
694 threadmainstart(void *v)
699 * N.B. This call to proc() is a program's first call (indirectly) to a
700 * pthreads function while executing on a non-pthreads-allocated
701 * stack. If the pthreads implementation is using the stack pointer
702 * to locate the per-thread data, then this call will blow up.
703 * This means the pthread implementation is not suitable for
704 * running under libthread. Time to write your own. Sorry.
707 threadmainproc = proc();
708 threadmain(threadargc, threadargv);
711 extern void (*_sysfatal)(char*, va_list);
714 main(int argc, char **argv)
720 if(getenv("NOLIBTHREADDAEMONIZE") == nil)
721 _threadsetupdaemonize();
727 * Install locking routines into C library.
730 _unlock = _threadunlock;
731 _qlock = threadqlock;
732 _qunlock = threadqunlock;
733 _rlock = threadrlock;
734 _runlock = threadrunlock;
735 _wlock = threadwlock;
736 _wunlock = threadwunlock;
737 _rsleep = threadrsleep;
738 _rwakeup = threadrwakeup;
739 _notejmpbuf = threadnotejmp;
741 _unpin = threadunpin;
742 _sysfatal = threadsysfatal;
748 if(mainstacksize == 0)
749 mainstacksize = 256*1024;
750 atnotify(threadinfo, 1);
751 _threadcreate(p, threadmainstart, nil, mainstacksize);
753 sysfatal("procscheduler returned in threadmain!");
754 /* does not return */
759 * hooray for linked lists
762 addthread(_Threadlist *l, _Thread *t)
776 delthread(_Threadlist *l, _Thread *t)
779 t->prev->next = t->next;
783 t->next->prev = t->prev;
788 /* inefficient but rarely used */
790 onlist(_Threadlist *l, _Thread *t)
794 for(tt = l->head; tt; tt=tt->next)
801 addthreadinproc(Proc *p, _Thread *t)
807 l->tail->allnext = t;
808 t->allprev = l->tail;
818 delthreadinproc(Proc *p, _Thread *t)
824 t->allprev->allnext = t->allnext;
826 l->head = t->allnext;
828 t->allnext->allprev = t->allprev;
830 l->tail = t->allprev;
834 Lock _threadprocslock;
835 static Proc *_threadprocstail;
840 lock(&_threadprocslock);
841 if(_threadprocstail){
842 _threadprocstail->next = p;
843 p->prev = _threadprocstail;
848 _threadprocstail = p;
850 unlock(&_threadprocslock);
856 lock(&_threadprocslock);
858 p->prev->next = p->next;
860 _threadprocs = p->next;
862 p->next->prev = p->prev;
864 _threadprocstail = p->prev;
865 unlock(&_threadprocslock);
869 * notify - for now just use the usual mechanisms
872 threadnotify(int (*f)(void*, char*), int in)
878 onrunqueue(Proc *p, _Thread *t)
882 for(tt=p->runqueue.head; tt; tt=tt->next)
889 * print state - called from SIGINFO
892 threadinfo(void *v, char *s)
897 if(strcmp(s, "quit") != 0 && strcmp(s, "sys: status request") != 0)
900 for(p=_threadprocs; p; p=p->next){
901 fprint(2, "proc %p %s%s\n", (void*)p->osprocid, p->msg,
902 p->sysproc ? " (sysproc)": "");
903 for(t=p->allthreads.head; t; t=t->allnext){
904 fprint(2, "\tthread %d %s: %s %s\n",
906 t == p->thread ? "Running" :
907 onrunqueue(p, t) ? "Ready" : "Sleeping",