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 void addthreadinproc(Proc*, _Thread*);
16 static void delthreadinproc(Proc*, _Thread*);
17 static void contextswitch(Context *from, Context *to);
18 static void procscheduler(Proc*);
19 static int threadinfo(void*, char*);
22 _threaddebug(char *fmt, ...)
30 if(_threaddebuglevel == 0)
34 p = strrchr(argv0, '/');
39 snprint(buf, sizeof buf, "/tmp/%s.tlog", p);
40 if((fd = create(buf, OWRITE, 0666)) < 0)
41 fd = open("/dev/null", OWRITE);
42 if(fd >= 0 && fd != 2){
50 vsnprint(buf, sizeof buf, fmt, arg);
54 fprint(fd, "%d.%d: %s\n", getpid(), t->id, buf);
56 fprint(fd, "%d._: %s\n", getpid(), buf);
62 return proc()->thread;
64 _Thread *(*threadnow)(void) = getthreadnow;
71 p = malloc(sizeof *p);
73 sysfatal("procalloc malloc: %r");
74 memset(p, 0, sizeof *p);
76 lock(&threadnproclock);
78 unlock(&threadnproclock);
83 threadstart(uint y, uint x)
88 z = x<<16; /* hide undefined 32-bit shift from 32-bit compilers */
93 /*print("threadstart %p\n", v); */
94 t->startfn(t->startarg);
95 /*print("threadexits %p\n", v); */
97 /*print("not reacehd\n"); */
101 threadalloc(void (*fn)(void*), void *arg, uint stack)
108 /* allocate the task and stack together */
109 t = malloc(sizeof *t+stack);
111 sysfatal("threadalloc malloc: %r");
112 memset(t, 0, sizeof *t);
113 t->stk = (uchar*)(t+1);
115 t->id = incref(&threadidref);
119 /* do a reasonable initialization */
120 memset(&t->context.uc, 0, sizeof t->context.uc);
122 sigprocmask(SIG_BLOCK, &zero, &t->context.uc.uc_sigmask);
124 /* must initialize with current context */
125 if(getcontext(&t->context.uc) < 0)
126 sysfatal("threadalloc getcontext: %r");
128 /* call makecontext to do the real work. */
129 /* leave a few words open on both ends */
130 t->context.uc.uc_stack.ss_sp = t->stk+8;
131 t->context.uc.uc_stack.ss_size = t->stksize-64;
132 #if defined(__sun__) && !defined(__MAKECONTEXT_V2_SOURCE) /* sigh */
133 /* can avoid this with __MAKECONTEXT_V2_SOURCE but only on SunOS 5.9 */
134 t->context.uc.uc_stack.ss_sp =
135 (char*)t->context.uc.uc_stack.ss_sp
136 +t->context.uc.uc_stack.ss_size;
139 * All this magic is because you have to pass makecontext a
140 * function that takes some number of word-sized variables,
141 * and on 64-bit machines pointers are bigger than words.
145 z >>= 16; /* hide undefined 32-bit shift from 32-bit compilers */
147 makecontext(&t->context.uc, (void(*)(void))threadstart, 2, y, x);
153 _threadcreate(Proc *p, void (*fn)(void*), void *arg, uint stack)
157 t = threadalloc(fn, arg, stack);
159 addthreadinproc(p, t);
166 threadcreate(void (*fn)(void*), void *arg, uint stack)
170 t = _threadcreate(proc(), fn, arg, stack);
175 proccreate(void (*fn)(void*), void *arg, uint stack)
182 t = _threadcreate(p, fn, arg, stack);
183 id = t->id; /* t might be freed after _procstart */
184 _procstart(p, procscheduler);
195 /*print("threadswtch %p\n", p); */
196 contextswitch(&p->thread->context, &p->schedcontext);
200 _threadready(_Thread *t)
206 p->runrend.l = &p->lock;
207 addthread(&p->runqueue, t);
208 /*print("%d wake for job %d->%d\n", time(0), getpid(), p->osprocid); */
210 _procwakeupandunlock(&p->runrend);
224 p->runrend.l = &p->lock;
225 addthread(&p->idlequeue, p->thread);
228 return p->nswitch - n;
239 _threadready(p->thread);
241 return p->nswitch - n;
245 threadexits(char *msg)
252 utfecpy(p->msg, p->msg+sizeof p->msg, msg);
253 proc()->thread->exiting = 1;
258 contextswitch(Context *from, Context *to)
260 if(swapcontext(&from->uc, &to->uc) < 0){
261 fprint(2, "swapcontext failed: %r\n");
267 procscheduler(Proc *p)
272 _threaddebug("scheduler enter");
273 /* print("s %p\n", p); */
276 while((t = p->runqueue.head) == nil){
279 if((t = p->idlequeue.head) != nil){
281 * Run all the idling threads once.
283 while((t = p->idlequeue.head) != nil){
284 delthread(&p->idlequeue, t);
285 addthread(&p->runqueue, t);
289 p->runrend.l = &p->lock;
290 _threaddebug("scheduler sleep");
291 _procsleep(&p->runrend);
292 _threaddebug("scheduler wake");
294 delthread(&p->runqueue, t);
298 _threaddebug("run %d (%s)", t->id, t->name);
299 contextswitch(&p->schedcontext, &t->context);
300 /*print("back in scheduler\n"); */
304 delthreadinproc(p, t);
306 /*print("nthread %d\n", p->nthread); */
312 _threaddebug("scheduler exit");
315 * Stupid bug - on Linux 2.6 and maybe elsewhere,
316 * if the main thread exits then the others keep running
317 * but the process shows up as a zombie in ps and is not
318 * attachable with ptrace. We'll just sit around pretending
319 * to be a system proc instead of exiting.
322 lock(&threadnproclock);
323 if(++threadnsysproc == threadnproc)
324 threadexitsall(p->msg);
326 unlock(&threadnproclock);
332 lock(&threadnproclock);
335 if(--threadnproc == threadnsysproc)
336 threadexitsall(p->msg);
337 unlock(&threadnproclock);
344 _threadsetsysproc(void)
346 lock(&threadnproclock);
347 if(++threadnsysproc == threadnproc)
349 unlock(&threadnproclock);
356 return &proc()->udata;
362 return &proc()->thread->udata;
365 extern Jmp *(*_notejmpbuf)(void);
369 return &proc()->sigjmp;
376 threadsetname(char *fmt, ...)
383 vsnprint(t->name, sizeof t->name, fmt, arg);
390 return proc()->thread->name;
394 threadsetstate(char *fmt, ...)
401 vsnprint(t->state, sizeof t->name, fmt, arg);
421 if((char*)&t <= (char*)t->stk
422 || (char*)&t - (char*)t->stk < 256+n){
423 fprint(2, "thread stack overflow: &t=%p tstk=%p n=%d\n", &t, t->stk, 256+n);
432 threadqlock(QLock *l, int block, ulong pc)
434 /*print("threadqlock %p\n", l); */
437 l->owner = (*threadnow)();
438 /*print("qlock %p @%#x by %p\n", l, pc, l->owner); */
446 /*print("qsleep %p @%#x by %p\n", l, pc, (*threadnow)()); */
447 addthread(&l->waiting, (*threadnow)());
452 if(l->owner != (*threadnow)()){
453 fprint(2, "%s: qlock pc=0x%lux owner=%p self=%p oops\n",
454 argv0, pc, l->owner, (*threadnow)());
457 /*print("qlock wakeup %p @%#x by %p\n", l, pc, (*threadnow)()); */
462 threadqunlock(QLock *l, ulong pc)
467 /*print("qlock unlock %p @%#x by %p (owner %p)\n", l, pc, (*threadnow)(), l->owner); */
469 fprint(2, "%s: qunlock pc=0x%lux owner=%p self=%p oops\n",
470 argv0, pc, l->owner, (*threadnow)());
473 if((l->owner = ready = l->waiting.head) != nil)
474 delthread(&l->waiting, l->owner);
476 * N.B. Cannot call _threadready() before unlocking l->l,
477 * because the thread we are readying might:
478 * - be in another proc
479 * - start running immediately
480 * - and free l before we get a chance to run again
484 _threadready(l->owner);
488 threadrlock(RWLock *l, int block, ulong pc)
493 if(l->writer == nil && l->wwaiting.head == nil){
502 addthread(&l->rwaiting, (*threadnow)());
509 threadwlock(RWLock *l, int block, ulong pc)
514 if(l->writer == nil && l->readers == 0){
515 l->writer = (*threadnow)();
523 addthread(&l->wwaiting, (*threadnow)());
530 threadrunlock(RWLock *l, ulong pc)
538 if(l->readers == 0 && (t = l->wwaiting.head) != nil){
539 delthread(&l->wwaiting, t);
549 threadwunlock(RWLock *l, ulong pc)
556 assert(l->readers == 0);
557 while((t = l->rwaiting.head) != nil){
558 delthread(&l->rwaiting, t);
563 if(l->readers == 0 && (t = l->wwaiting.head) != nil){
564 delthread(&l->wwaiting, t);
576 threadrsleep(Rendez *r, ulong pc)
578 addthread(&r->waiting, proc()->thread);
585 threadrwakeup(Rendez *r, int all, ulong pc)
593 if((t = r->waiting.head) == nil)
595 delthread(&r->waiting, t);
605 static int threadargc;
606 static char **threadargv;
608 extern int _p9usepwlibrary; /* getgrgid etc. smash the stack - tell _p9dir just say no */
610 threadmainstart(void *v)
615 * N.B. This call to proc() is a program's first call (indirectly) to a
616 * pthreads function while executing on a non-pthreads-allocated
617 * stack. If the pthreads implementation is using the stack pointer
618 * to locate the per-thread data, then this call will blow up.
619 * This means the pthread implementation is not suitable for
620 * running under libthread. Time to write your own. Sorry.
623 threadmainproc = proc();
624 threadmain(threadargc, threadargv);
628 main(int argc, char **argv)
635 if(getenv("NOLIBTHREADDAEMONIZE") == nil)
636 _threadsetupdaemonize();
642 * Install locking routines into C library.
645 _unlock = _threadunlock;
646 _qlock = threadqlock;
647 _qunlock = threadqunlock;
648 _rlock = threadrlock;
649 _runlock = threadrunlock;
650 _wlock = threadwlock;
651 _wunlock = threadwunlock;
652 _rsleep = threadrsleep;
653 _rwakeup = threadrwakeup;
654 _notejmpbuf = threadnotejmp;
660 if(mainstacksize == 0)
661 mainstacksize = 256*1024;
662 atnotify(threadinfo, 1);
663 _threadcreate(p, threadmainstart, nil, mainstacksize);
665 sysfatal("procscheduler returned in threadmain!");
666 /* does not return */
671 * hooray for linked lists
674 addthread(_Threadlist *l, _Thread *t)
688 delthread(_Threadlist *l, _Thread *t)
691 t->prev->next = t->next;
695 t->next->prev = t->prev;
701 addthreadinproc(Proc *p, _Thread *t)
707 l->tail->allnext = t;
708 t->allprev = l->tail;
718 delthreadinproc(Proc *p, _Thread *t)
724 t->allprev->allnext = t->allnext;
726 l->head = t->allnext;
728 t->allnext->allprev = t->allprev;
730 l->tail = t->allprev;
734 Lock _threadprocslock;
735 static Proc *_threadprocstail;
740 lock(&_threadprocslock);
741 if(_threadprocstail){
742 _threadprocstail->next = p;
743 p->prev = _threadprocstail;
748 _threadprocstail = p;
750 unlock(&_threadprocslock);
756 lock(&_threadprocslock);
758 p->prev->next = p->next;
760 _threadprocs = p->next;
762 p->next->prev = p->prev;
764 _threadprocstail = p->prev;
765 unlock(&_threadprocslock);
769 * notify - for now just use the usual mechanisms
772 threadnotify(int (*f)(void*, char*), int in)
778 onrunqueue(Proc *p, _Thread *t)
782 for(tt=p->runqueue.head; tt; tt=tt->next)
789 * print state - called from SIGINFO
792 threadinfo(void *v, char *s)
797 if(strcmp(s, "quit") != 0 && strcmp(s, "sys: status request") != 0)
800 for(p=_threadprocs; p; p=p->next){
801 fprint(2, "proc %p %s%s\n", (void*)p->osprocid, p->msg,
802 p->sysproc ? " (sysproc)": "");
803 for(t=p->allthreads.head; t; t=t->allnext){
804 fprint(2, "\tthread %d %s: %s %s\n",
806 t == p->thread ? "Running" :
807 onrunqueue(p, t) ? "Ready" : "Sleeping",