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);
218 _threadready(p->thread);
220 return p->nswitch - n;
224 threadexits(char *msg)
231 utfecpy(p->msg, p->msg+sizeof p->msg, msg);
232 proc()->thread->exiting = 1;
237 contextswitch(Context *from, Context *to)
239 if(swapcontext(&from->uc, &to->uc) < 0){
240 fprint(2, "swapcontext failed: %r\n");
246 procscheduler(Proc *p)
251 _threaddebug("scheduler enter");
252 // print("s %p\n", p);
255 while((t = p->runqueue.head) == nil){
258 p->runrend.l = &p->lock;
259 _threaddebug("scheduler sleep");
260 _procsleep(&p->runrend);
261 _threaddebug("scheduler wake");
263 delthread(&p->runqueue, t);
267 _threaddebug("run %d (%s)", t->id, t->name);
268 contextswitch(&p->schedcontext, &t->context);
269 //print("back in scheduler\n");
273 delthreadinproc(p, t);
275 //print("ntrhead %d\n", p->nthread);
281 _threaddebug("scheduler exit");
284 * Stupid bug - on Linux 2.6 and maybe elsewhere,
285 * if the main thread exits then the others keep running
286 * but the process shows up as a zombie in ps and is not
287 * attachable with ptrace. We'll just sit around pretending
288 * to be a system proc instead of exiting.
291 lock(&threadnproclock);
292 if(++threadnsysproc == threadnproc)
293 threadexitsall(p->msg);
295 unlock(&threadnproclock);
301 lock(&threadnproclock);
304 if(--threadnproc == threadnsysproc)
305 threadexitsall(p->msg);
306 unlock(&threadnproclock);
312 _threadsetsysproc(void)
314 lock(&threadnproclock);
315 if(++threadnsysproc == threadnproc)
317 unlock(&threadnproclock);
324 return &proc()->udata;
330 return &proc()->thread->udata;
333 extern Jmp *(*_notejmpbuf)(void);
337 return &proc()->sigjmp;
344 threadsetname(char *fmt, ...)
351 vsnprint(t->name, sizeof t->name, fmt, arg);
358 return proc()->thread->name;
362 threadsetstate(char *fmt, ...)
369 vsnprint(t->state, sizeof t->name, fmt, arg);
380 if((char*)&t <= (char*)t->stk
381 || (char*)&t - (char*)t->stk < 256+n){
382 fprint(2, "thread stack overflow: &t=%p tstk=%p n=%d\n", &t, t->stk, 256+n);
391 threadqlock(QLock *l, int block, ulong pc)
393 //print("threadqlock %p\n", l);
396 l->owner = (*threadnow)();
397 //print("qlock %p @%#x by %p\n", l, pc, l->owner);
405 //print("qsleep %p @%#x by %p\n", l, pc, (*threadnow)());
406 addthread(&l->waiting, (*threadnow)());
411 if(l->owner != (*threadnow)()){
412 fprint(2, "%s: qlock pc=0x%lux owner=%p self=%p oops\n",
413 argv0, pc, l->owner, (*threadnow)());
416 //print("qlock wakeup %p @%#x by %p\n", l, pc, (*threadnow)());
421 threadqunlock(QLock *l, ulong pc)
426 //print("qlock unlock %p @%#x by %p (owner %p)\n", l, pc, (*threadnow)(), l->owner);
428 fprint(2, "%s: qunlock pc=0x%lux owner=%p self=%p oops\n",
429 argv0, pc, l->owner, (*threadnow)());
432 if((l->owner = ready = l->waiting.head) != nil)
433 delthread(&l->waiting, l->owner);
435 * N.B. Cannot call _threadready() before unlocking l->l,
436 * because the thread we are readying might:
437 * - be in another proc
438 * - start running immediately
439 * - and free l before we get a chance to run again
443 _threadready(l->owner);
447 threadrlock(RWLock *l, int block, ulong pc)
452 if(l->writer == nil && l->wwaiting.head == nil){
461 addthread(&l->rwaiting, (*threadnow)());
468 threadwlock(RWLock *l, int block, ulong pc)
473 if(l->writer == nil && l->readers == 0){
474 l->writer = (*threadnow)();
482 addthread(&l->wwaiting, (*threadnow)());
489 threadrunlock(RWLock *l, ulong pc)
497 if(l->readers == 0 && (t = l->wwaiting.head) != nil){
498 delthread(&l->wwaiting, t);
508 threadwunlock(RWLock *l, ulong pc)
515 assert(l->readers == 0);
516 while((t = l->rwaiting.head) != nil){
517 delthread(&l->rwaiting, t);
522 if(l->readers == 0 && (t = l->wwaiting.head) != nil){
523 delthread(&l->wwaiting, t);
535 threadrsleep(Rendez *r, ulong pc)
537 addthread(&r->waiting, proc()->thread);
544 threadrwakeup(Rendez *r, int all, ulong pc)
552 if((t = r->waiting.head) == nil)
554 delthread(&r->waiting, t);
564 static int threadargc;
565 static char **threadargv;
569 threadmainstart(void *v)
574 * N.B. This call to proc() is a program's first call (indirectly) to a
575 * pthreads function while executing on a non-pthreads-allocated
576 * stack. If the pthreads implementation is using the stack pointer
577 * to locate the per-thread data, then this call will blow up.
578 * This means the pthread implementation is not suitable for
579 * running under libthread. Time to write your own. Sorry.
581 threadmainproc = proc();
582 threadmain(threadargc, threadargv);
586 main(int argc, char **argv)
592 _threadsetupdaemonize();
598 * Install locking routines into C library.
601 _unlock = _threadunlock;
602 _qlock = threadqlock;
603 _qunlock = threadqunlock;
604 _rlock = threadrlock;
605 _runlock = threadrunlock;
606 _wlock = threadwlock;
607 _wunlock = threadwunlock;
608 _rsleep = threadrsleep;
609 _rwakeup = threadrwakeup;
610 _notejmpbuf = threadnotejmp;
616 if(mainstacksize == 0)
617 mainstacksize = 256*1024;
618 atnotify(threadinfo, 1);
619 _threadcreate(p, threadmainstart, nil, mainstacksize);
621 sysfatal("procscheduler returned in threadmain!");
622 /* does not return */
627 * hooray for linked lists
630 addthread(_Threadlist *l, _Thread *t)
644 delthread(_Threadlist *l, _Thread *t)
647 t->prev->next = t->next;
651 t->next->prev = t->prev;
657 addthreadinproc(Proc *p, _Thread *t)
663 l->tail->allnext = t;
664 t->allprev = l->tail;
674 delthreadinproc(Proc *p, _Thread *t)
680 t->allprev->allnext = t->allnext;
682 l->head = t->allnext;
684 t->allnext->allprev = t->allprev;
686 l->tail = t->allprev;
690 Lock _threadprocslock;
691 static Proc *_threadprocstail;
696 lock(&_threadprocslock);
697 if(_threadprocstail){
698 _threadprocstail->next = p;
699 p->prev = _threadprocstail;
704 _threadprocstail = p;
706 unlock(&_threadprocslock);
712 lock(&_threadprocslock);
714 p->prev->next = p->next;
716 _threadprocs = p->next;
718 p->next->prev = p->prev;
720 _threadprocstail = p->prev;
721 unlock(&_threadprocslock);
725 * notify - for now just use the usual mechanisms
728 threadnotify(int (*f)(void*, char*), int in)
734 onrunqueue(Proc *p, _Thread *t)
738 for(tt=p->runqueue.head; tt; tt=tt->next)
745 * print state - called from SIGINFO
748 threadinfo(void *v, char *s)
753 if(strcmp(s, "quit") != 0 && strcmp(s, "sys: status request") != 0)
756 for(p=_threadprocs; p; p=p->next){
757 fprint(2, "proc %p %s%s\n", (void*)p->osprocid, p->msg,
758 p->sysproc ? " (sysproc)": "");
759 for(t=p->allthreads.head; t; t=t->allnext){
760 fprint(2, "\tthread %d %s: %s %s\n",
762 t == p->thread ? "Running" :
763 onrunqueue(p, t) ? "Ready" : "Sleeping",