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 z = (ulong)x << 16; /* hide undefined 32-bit shift from 32-bit compilers */
94 /*print("threadstart %p\n", v); */
95 t->startfn(t->startarg);
96 /*print("threadexits %p\n", v); */
98 /*print("not reacehd\n"); */
102 threadalloc(void (*fn)(void*), void *arg, uint stack)
109 /* allocate the task and stack together */
110 t = malloc(sizeof *t+stack);
112 sysfatal("threadalloc malloc: %r");
113 memset(t, 0, sizeof *t);
114 t->stk = (uchar*)(t+1);
116 t->id = incref(&threadidref);
120 /* do a reasonable initialization */
121 memset(&t->context.uc, 0, sizeof t->context.uc);
123 sigprocmask(SIG_BLOCK, &zero, &t->context.uc.uc_sigmask);
125 /* must initialize with current context */
126 if(getcontext(&t->context.uc) < 0)
127 sysfatal("threadalloc getcontext: %r");
129 /* call makecontext to do the real work. */
130 /* leave a few words open on both ends */
131 t->context.uc.uc_stack.ss_sp = (void*)(t->stk+8);
132 t->context.uc.uc_stack.ss_size = t->stksize-64;
133 #if defined(__sun__) && !defined(__MAKECONTEXT_V2_SOURCE) /* sigh */
134 /* can avoid this with __MAKECONTEXT_V2_SOURCE but only on SunOS 5.9 */
135 t->context.uc.uc_stack.ss_sp =
136 (char*)t->context.uc.uc_stack.ss_sp
137 +t->context.uc.uc_stack.ss_size;
140 * All this magic is because you have to pass makecontext a
141 * function that takes some number of word-sized variables,
142 * and on 64-bit machines pointers are bigger than words.
146 z >>= 16; /* hide undefined 32-bit shift from 32-bit compilers */
148 makecontext(&t->context.uc, (void(*)(void))threadstart, 2, y, x);
154 _threadcreate(Proc *p, void (*fn)(void*), void *arg, uint stack)
158 /* defend against bad C libraries */
159 if(stack < (256<<10))
162 t = threadalloc(fn, arg, stack);
164 addthreadinproc(p, t);
171 threadcreate(void (*fn)(void*), void *arg, uint stack)
175 t = _threadcreate(proc(), fn, arg, stack);
180 proccreate(void (*fn)(void*), void *arg, uint stack)
187 t = _threadcreate(p, fn, arg, stack);
188 id = t->id; /* t might be freed after _procstart */
189 _procstart(p, procscheduler);
200 /*print("threadswtch %p\n", p); */
201 contextswitch(&p->thread->context, &p->schedcontext);
205 _threadready(_Thread *t)
211 p->runrend.l = &p->lock;
212 addthread(&p->runqueue, t);
213 /*print("%d wake for job %d->%d\n", time(0), getpid(), p->osprocid); */
215 _procwakeupandunlock(&p->runrend);
229 p->runrend.l = &p->lock;
230 addthread(&p->idlequeue, p->thread);
233 return p->nswitch - n;
244 _threadready(p->thread);
246 return p->nswitch - n;
250 threadexits(char *msg)
257 utfecpy(p->msg, p->msg+sizeof p->msg, msg);
258 proc()->thread->exiting = 1;
269 fprint(2, "already pinning a thread - %p %p\n", p->pinthread, p->thread);
272 p->pinthread = p->thread;
281 if(p->pinthread != p->thread){
282 fprint(2, "wrong pinthread - %p %p\n", p->pinthread, p->thread);
289 threadsysfatal(char *fmt, va_list arg)
293 vseprint(buf, buf+sizeof(buf), fmt, arg);
295 fprint(2, "%s: %s\n", argv0 ? argv0 : "<prog>", buf);
300 contextswitch(Context *from, Context *to)
302 if(swapcontext(&from->uc, &to->uc) < 0){
303 fprint(2, "swapcontext failed: %r\n");
309 procscheduler(Proc *p)
314 _threaddebug("scheduler enter");
315 /* print("s %p\n", p); */
318 if((t = p->pinthread) != nil){
319 while(!onlist(&p->runqueue, t)){
320 p->runrend.l = &p->lock;
321 _threaddebug("scheduler sleep (pin)");
322 _procsleep(&p->runrend);
323 _threaddebug("scheduler wake (pin)");
326 while((t = p->runqueue.head) == nil){
329 if((t = p->idlequeue.head) != nil){
331 * Run all the idling threads once.
333 while((t = p->idlequeue.head) != nil){
334 delthread(&p->idlequeue, t);
335 addthread(&p->runqueue, t);
339 p->runrend.l = &p->lock;
340 _threaddebug("scheduler sleep");
341 _procsleep(&p->runrend);
342 _threaddebug("scheduler wake");
344 if(p->pinthread && p->pinthread != t)
345 fprint(2, "p->pinthread %p t %p\n", p->pinthread, t);
346 assert(p->pinthread == nil || p->pinthread == t);
347 delthread(&p->runqueue, t);
351 _threaddebug("run %d (%s)", t->id, t->name);
352 contextswitch(&p->schedcontext, &t->context);
353 /*print("back in scheduler\n"); */
357 delthreadinproc(p, t);
359 /*print("nthread %d\n", p->nthread); */
365 _threaddebug("scheduler exit");
368 * Stupid bug - on Linux 2.6 and maybe elsewhere,
369 * if the main thread exits then the others keep running
370 * but the process shows up as a zombie in ps and is not
371 * attachable with ptrace. We'll just sit around pretending
372 * to be a system proc instead of exiting.
375 lock(&threadnproclock);
376 if(++threadnsysproc == threadnproc)
377 threadexitsall(p->msg);
379 unlock(&threadnproclock);
385 lock(&threadnproclock);
388 if(--threadnproc == threadnsysproc)
389 threadexitsall(p->msg);
390 unlock(&threadnproclock);
397 _threadsetsysproc(void)
399 lock(&threadnproclock);
400 if(++threadnsysproc == threadnproc)
402 unlock(&threadnproclock);
409 return &proc()->udata;
415 return &proc()->thread->udata;
418 extern Jmp *(*_notejmpbuf)(void);
422 return &proc()->sigjmp;
429 threadsetname(char *fmt, ...)
436 vsnprint(t->name, sizeof t->name, fmt, arg);
443 return proc()->thread->name;
447 threadsetstate(char *fmt, ...)
454 vsnprint(t->state, sizeof t->name, fmt, arg);
474 if((char*)&t <= (char*)t->stk
475 || (char*)&t - (char*)t->stk < 256+n){
476 fprint(2, "thread stack overflow: &t=%p tstk=%p n=%d\n", &t, t->stk, 256+n);
484 return threadnproc == 1 && _threadprocs->nthread == 1;
491 threadqlock(QLock *l, int block, ulong pc)
493 /*print("threadqlock %p\n", l); */
496 l->owner = (*threadnow)();
497 /*print("qlock %p @%#x by %p\n", l, pc, l->owner); */
506 if(singlethreaded()){
507 fprint(2, "qlock deadlock\n");
511 /*print("qsleep %p @%#x by %p\n", l, pc, (*threadnow)()); */
512 addthread(&l->waiting, (*threadnow)());
517 if(l->owner != (*threadnow)()){
518 fprint(2, "%s: qlock pc=0x%lux owner=%p self=%p oops\n",
519 argv0, pc, l->owner, (*threadnow)());
522 /*print("qlock wakeup %p @%#x by %p\n", l, pc, (*threadnow)()); */
527 threadqunlock(QLock *l, ulong pc)
532 /*print("qlock unlock %p @%#x by %p (owner %p)\n", l, pc, (*threadnow)(), l->owner); */
534 fprint(2, "%s: qunlock pc=0x%lux owner=%p self=%p oops\n",
535 argv0, pc, l->owner, (*threadnow)());
538 if((l->owner = ready = l->waiting.head) != nil)
539 delthread(&l->waiting, l->owner);
541 * N.B. Cannot call _threadready() before unlocking l->l,
542 * because the thread we are readying might:
543 * - be in another proc
544 * - start running immediately
545 * - and free l before we get a chance to run again
549 _threadready(l->owner);
553 threadrlock(RWLock *l, int block, ulong pc)
558 if(l->writer == nil && l->wwaiting.head == nil){
567 if(singlethreaded()){
568 fprint(2, "rlock deadlock\n");
571 addthread(&l->rwaiting, (*threadnow)());
578 threadwlock(RWLock *l, int block, ulong pc)
583 if(l->writer == nil && l->readers == 0){
584 l->writer = (*threadnow)();
592 if(singlethreaded()){
593 fprint(2, "wlock deadlock\n");
596 addthread(&l->wwaiting, (*threadnow)());
603 threadrunlock(RWLock *l, ulong pc)
611 if(l->readers == 0 && (t = l->wwaiting.head) != nil){
612 delthread(&l->wwaiting, t);
622 threadwunlock(RWLock *l, ulong pc)
629 assert(l->readers == 0);
630 while((t = l->rwaiting.head) != nil){
631 delthread(&l->rwaiting, t);
636 if(l->readers == 0 && (t = l->wwaiting.head) != nil){
637 delthread(&l->wwaiting, t);
649 threadrsleep(Rendez *r, ulong pc)
651 if(singlethreaded()){
652 fprint(2, "rsleep deadlock\n");
655 addthread(&r->waiting, proc()->thread);
662 threadrwakeup(Rendez *r, int all, ulong pc)
670 if((t = r->waiting.head) == nil)
672 delthread(&r->waiting, t);
682 static int threadargc;
683 static char **threadargv;
685 extern int _p9usepwlibrary; /* getgrgid etc. smash the stack - tell _p9dir just say no */
687 threadmainstart(void *v)
692 * N.B. This call to proc() is a program's first call (indirectly) to a
693 * pthreads function while executing on a non-pthreads-allocated
694 * stack. If the pthreads implementation is using the stack pointer
695 * to locate the per-thread data, then this call will blow up.
696 * This means the pthread implementation is not suitable for
697 * running under libthread. Time to write your own. Sorry.
700 threadmainproc = proc();
701 threadmain(threadargc, threadargv);
704 extern void (*_sysfatal)(char*, va_list);
707 main(int argc, char **argv)
713 if(getenv("NOLIBTHREADDAEMONIZE") == nil)
714 _threadsetupdaemonize();
720 * Install locking routines into C library.
723 _unlock = _threadunlock;
724 _qlock = threadqlock;
725 _qunlock = threadqunlock;
726 _rlock = threadrlock;
727 _runlock = threadrunlock;
728 _wlock = threadwlock;
729 _wunlock = threadwunlock;
730 _rsleep = threadrsleep;
731 _rwakeup = threadrwakeup;
732 _notejmpbuf = threadnotejmp;
734 _unpin = threadunpin;
735 _sysfatal = threadsysfatal;
741 if(mainstacksize == 0)
742 mainstacksize = 256*1024;
743 atnotify(threadinfo, 1);
744 _threadcreate(p, threadmainstart, nil, mainstacksize);
746 sysfatal("procscheduler returned in threadmain!");
747 /* does not return */
752 * hooray for linked lists
755 addthread(_Threadlist *l, _Thread *t)
769 delthread(_Threadlist *l, _Thread *t)
772 t->prev->next = t->next;
776 t->next->prev = t->prev;
781 /* inefficient but rarely used */
783 onlist(_Threadlist *l, _Thread *t)
787 for(tt = l->head; tt; tt=tt->next)
794 addthreadinproc(Proc *p, _Thread *t)
800 l->tail->allnext = t;
801 t->allprev = l->tail;
811 delthreadinproc(Proc *p, _Thread *t)
817 t->allprev->allnext = t->allnext;
819 l->head = t->allnext;
821 t->allnext->allprev = t->allprev;
823 l->tail = t->allprev;
827 Lock _threadprocslock;
828 static Proc *_threadprocstail;
833 lock(&_threadprocslock);
834 if(_threadprocstail){
835 _threadprocstail->next = p;
836 p->prev = _threadprocstail;
841 _threadprocstail = p;
843 unlock(&_threadprocslock);
849 lock(&_threadprocslock);
851 p->prev->next = p->next;
853 _threadprocs = p->next;
855 p->next->prev = p->prev;
857 _threadprocstail = p->prev;
858 unlock(&_threadprocslock);
862 * notify - for now just use the usual mechanisms
865 threadnotify(int (*f)(void*, char*), int in)
871 onrunqueue(Proc *p, _Thread *t)
875 for(tt=p->runqueue.head; tt; tt=tt->next)
882 * print state - called from SIGINFO
885 threadinfo(void *v, char *s)
890 if(strcmp(s, "quit") != 0 && strcmp(s, "sys: status request") != 0)
893 for(p=_threadprocs; p; p=p->next){
894 fprint(2, "proc %p %s%s\n", (void*)p->osprocid, p->msg,
895 p->sysproc ? " (sysproc)": "");
896 for(t=p->allthreads.head; t; t=t->allnext){
897 fprint(2, "\tthread %d %s: %s %s\n",
899 t == p->thread ? "Running" :
900 onrunqueue(p, t) ? "Ready" : "Sleeping",