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);
45 vsnprint(buf, sizeof buf, fmt, arg);
49 fprint(fd, "%d.%d: %s\n", getpid(), t->id, buf);
51 fprint(fd, "%d._: %s\n", getpid(), buf);
57 return proc()->thread;
59 _Thread *(*threadnow)(void) = getthreadnow;
66 p = malloc(sizeof *p);
68 sysfatal("procalloc malloc: %r");
69 memset(p, 0, sizeof *p);
71 lock(&threadnproclock);
73 unlock(&threadnproclock);
78 threadstart(uint y, uint x)
83 z = x<<16; /* hide undefined 32-bit shift from 32-bit compilers */
88 //print("threadstart %p\n", v);
89 t->startfn(t->startarg);
90 //print("threadexits %p\n", v);
92 //print("not reacehd\n");
96 threadalloc(void (*fn)(void*), void *arg, uint stack)
103 /* allocate the task and stack together */
104 t = malloc(sizeof *t+stack);
106 sysfatal("threadalloc malloc: %r");
107 memset(t, 0, sizeof *t);
108 t->stk = (uchar*)(t+1);
110 t->id = incref(&threadidref);
114 /* do a reasonable initialization */
115 memset(&t->context.uc, 0, sizeof t->context.uc);
117 sigprocmask(SIG_BLOCK, &zero, &t->context.uc.uc_sigmask);
119 /* must initialize with current context */
120 if(getcontext(&t->context.uc) < 0)
121 sysfatal("threadalloc getcontext: %r");
123 /* call makecontext to do the real work. */
124 /* leave a few words open on both ends */
125 t->context.uc.uc_stack.ss_sp = t->stk+8;
126 t->context.uc.uc_stack.ss_size = t->stksize-64;
127 #if defined(__sun__) && !defined(__MAKECONTEXT_V2_SOURCE) /* sigh */
128 /* can avoid this with __MAKECONTEXT_V2_SOURCE but only on SunOS 5.9 */
129 t->context.uc.uc_stack.ss_sp =
130 (char*)t->context.uc.uc_stack.ss_sp
131 +t->context.uc.uc_stack.ss_size;
134 * All this magic is because you have to pass makecontext a
135 * function that takes some number of word-sized variables,
136 * and on 64-bit machines pointers are bigger than words.
140 z >>= 16; /* hide undefined 32-bit shift from 32-bit compilers */
142 makecontext(&t->context.uc, (void(*)(void))threadstart, 2, y, x);
148 _threadcreate(Proc *p, void (*fn)(void*), void *arg, uint stack)
152 t = threadalloc(fn, arg, stack);
154 addthreadinproc(p, t);
161 threadcreate(void (*fn)(void*), void *arg, uint stack)
165 t = _threadcreate(proc(), fn, arg, stack);
170 proccreate(void (*fn)(void*), void *arg, uint stack)
177 t = _threadcreate(p, fn, arg, stack);
178 id = t->id; /* t might be freed after _procstart */
179 _procstart(p, procscheduler);
190 //print("threadswtch %p\n", p);
191 contextswitch(&p->thread->context, &p->schedcontext);
195 _threadready(_Thread *t)
201 p->runrend.l = &p->lock;
202 addthread(&p->runqueue, t);
203 //print("%d wake for job %d->%d\n", time(0), getpid(), p->osprocid);
205 _procwakeupandunlock(&p->runrend);
219 p->runrend.l = &p->lock;
220 addthread(&p->idlequeue, p->thread);
223 return p->nswitch - n;
234 _threadready(p->thread);
236 return p->nswitch - n;
240 threadexits(char *msg)
247 utfecpy(p->msg, p->msg+sizeof p->msg, msg);
248 proc()->thread->exiting = 1;
253 contextswitch(Context *from, Context *to)
255 if(swapcontext(&from->uc, &to->uc) < 0){
256 fprint(2, "swapcontext failed: %r\n");
262 procscheduler(Proc *p)
267 _threaddebug("scheduler enter");
268 // print("s %p\n", p);
271 while((t = p->runqueue.head) == nil){
274 if((t = p->idlequeue.head) != nil){
276 * Run all the idling threads once.
278 while((t = p->idlequeue.head) != nil){
279 delthread(&p->idlequeue, t);
280 addthread(&p->runqueue, t);
284 p->runrend.l = &p->lock;
285 _threaddebug("scheduler sleep");
286 _procsleep(&p->runrend);
287 _threaddebug("scheduler wake");
289 delthread(&p->runqueue, t);
293 _threaddebug("run %d (%s)", t->id, t->name);
294 contextswitch(&p->schedcontext, &t->context);
295 //print("back in scheduler\n");
299 delthreadinproc(p, t);
301 //print("nthread %d\n", p->nthread);
307 _threaddebug("scheduler exit");
310 * Stupid bug - on Linux 2.6 and maybe elsewhere,
311 * if the main thread exits then the others keep running
312 * but the process shows up as a zombie in ps and is not
313 * attachable with ptrace. We'll just sit around pretending
314 * to be a system proc instead of exiting.
317 lock(&threadnproclock);
318 if(++threadnsysproc == threadnproc)
319 threadexitsall(p->msg);
321 unlock(&threadnproclock);
327 lock(&threadnproclock);
330 if(--threadnproc == threadnsysproc)
331 threadexitsall(p->msg);
332 unlock(&threadnproclock);
338 _threadsetsysproc(void)
340 lock(&threadnproclock);
341 if(++threadnsysproc == threadnproc)
343 unlock(&threadnproclock);
350 return &proc()->udata;
356 return &proc()->thread->udata;
359 extern Jmp *(*_notejmpbuf)(void);
363 return &proc()->sigjmp;
370 threadsetname(char *fmt, ...)
377 vsnprint(t->name, sizeof t->name, fmt, arg);
384 return proc()->thread->name;
388 threadsetstate(char *fmt, ...)
395 vsnprint(t->state, sizeof t->name, fmt, arg);
415 if((char*)&t <= (char*)t->stk
416 || (char*)&t - (char*)t->stk < 256+n){
417 fprint(2, "thread stack overflow: &t=%p tstk=%p n=%d\n", &t, t->stk, 256+n);
426 threadqlock(QLock *l, int block, ulong pc)
428 //print("threadqlock %p\n", l);
431 l->owner = (*threadnow)();
432 //print("qlock %p @%#x by %p\n", l, pc, l->owner);
440 //print("qsleep %p @%#x by %p\n", l, pc, (*threadnow)());
441 addthread(&l->waiting, (*threadnow)());
446 if(l->owner != (*threadnow)()){
447 fprint(2, "%s: qlock pc=0x%lux owner=%p self=%p oops\n",
448 argv0, pc, l->owner, (*threadnow)());
451 //print("qlock wakeup %p @%#x by %p\n", l, pc, (*threadnow)());
456 threadqunlock(QLock *l, ulong pc)
461 //print("qlock unlock %p @%#x by %p (owner %p)\n", l, pc, (*threadnow)(), l->owner);
463 fprint(2, "%s: qunlock pc=0x%lux owner=%p self=%p oops\n",
464 argv0, pc, l->owner, (*threadnow)());
467 if((l->owner = ready = l->waiting.head) != nil)
468 delthread(&l->waiting, l->owner);
470 * N.B. Cannot call _threadready() before unlocking l->l,
471 * because the thread we are readying might:
472 * - be in another proc
473 * - start running immediately
474 * - and free l before we get a chance to run again
478 _threadready(l->owner);
482 threadrlock(RWLock *l, int block, ulong pc)
487 if(l->writer == nil && l->wwaiting.head == nil){
496 addthread(&l->rwaiting, (*threadnow)());
503 threadwlock(RWLock *l, int block, ulong pc)
508 if(l->writer == nil && l->readers == 0){
509 l->writer = (*threadnow)();
517 addthread(&l->wwaiting, (*threadnow)());
524 threadrunlock(RWLock *l, ulong pc)
532 if(l->readers == 0 && (t = l->wwaiting.head) != nil){
533 delthread(&l->wwaiting, t);
543 threadwunlock(RWLock *l, ulong pc)
550 assert(l->readers == 0);
551 while((t = l->rwaiting.head) != nil){
552 delthread(&l->rwaiting, t);
557 if(l->readers == 0 && (t = l->wwaiting.head) != nil){
558 delthread(&l->wwaiting, t);
570 threadrsleep(Rendez *r, ulong pc)
572 addthread(&r->waiting, proc()->thread);
579 threadrwakeup(Rendez *r, int all, ulong pc)
587 if((t = r->waiting.head) == nil)
589 delthread(&r->waiting, t);
599 static int threadargc;
600 static char **threadargv;
604 threadmainstart(void *v)
609 * N.B. This call to proc() is a program's first call (indirectly) to a
610 * pthreads function while executing on a non-pthreads-allocated
611 * stack. If the pthreads implementation is using the stack pointer
612 * to locate the per-thread data, then this call will blow up.
613 * This means the pthread implementation is not suitable for
614 * running under libthread. Time to write your own. Sorry.
616 threadmainproc = proc();
617 threadmain(threadargc, threadargv);
621 main(int argc, char **argv)
627 if(getenv("NOLIBTHREADDAEMONIZE") == nil)
628 _threadsetupdaemonize();
634 * Install locking routines into C library.
637 _unlock = _threadunlock;
638 _qlock = threadqlock;
639 _qunlock = threadqunlock;
640 _rlock = threadrlock;
641 _runlock = threadrunlock;
642 _wlock = threadwlock;
643 _wunlock = threadwunlock;
644 _rsleep = threadrsleep;
645 _rwakeup = threadrwakeup;
646 _notejmpbuf = threadnotejmp;
652 if(mainstacksize == 0)
653 mainstacksize = 256*1024;
654 atnotify(threadinfo, 1);
655 _threadcreate(p, threadmainstart, nil, mainstacksize);
657 sysfatal("procscheduler returned in threadmain!");
658 /* does not return */
663 * hooray for linked lists
666 addthread(_Threadlist *l, _Thread *t)
680 delthread(_Threadlist *l, _Thread *t)
683 t->prev->next = t->next;
687 t->next->prev = t->prev;
693 addthreadinproc(Proc *p, _Thread *t)
699 l->tail->allnext = t;
700 t->allprev = l->tail;
710 delthreadinproc(Proc *p, _Thread *t)
716 t->allprev->allnext = t->allnext;
718 l->head = t->allnext;
720 t->allnext->allprev = t->allprev;
722 l->tail = t->allprev;
726 Lock _threadprocslock;
727 static Proc *_threadprocstail;
732 lock(&_threadprocslock);
733 if(_threadprocstail){
734 _threadprocstail->next = p;
735 p->prev = _threadprocstail;
740 _threadprocstail = p;
742 unlock(&_threadprocslock);
748 lock(&_threadprocslock);
750 p->prev->next = p->next;
752 _threadprocs = p->next;
754 p->next->prev = p->prev;
756 _threadprocstail = p->prev;
757 unlock(&_threadprocslock);
761 * notify - for now just use the usual mechanisms
764 threadnotify(int (*f)(void*, char*), int in)
770 onrunqueue(Proc *p, _Thread *t)
774 for(tt=p->runqueue.head; tt; tt=tt->next)
781 * print state - called from SIGINFO
784 threadinfo(void *v, char *s)
789 if(strcmp(s, "quit") != 0 && strcmp(s, "sys: status request") != 0)
792 for(p=_threadprocs; p; p=p->next){
793 fprint(2, "proc %p %s%s\n", (void*)p->osprocid, p->msg,
794 p->sysproc ? " (sysproc)": "");
795 for(t=p->allthreads.head; t; t=t->allnext){
796 fprint(2, "\tthread %d %s: %s %s\n",
798 t == p->thread ? "Running" :
799 onrunqueue(p, t) ? "Ready" : "Sleeping",