Blob


1 #include "threadimpl.h"
3 int _threaddebuglevel;
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*);
22 static void
23 _threaddebug(char *fmt, ...)
24 {
25 va_list arg;
26 char buf[128];
27 _Thread *t;
28 char *p;
29 static int fd = -1;
31 if(_threaddebuglevel == 0)
32 return;
34 if(fd < 0){
35 p = strrchr(argv0, '/');
36 if(p)
37 p++;
38 else
39 p = 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){
44 dup(fd, 2);
45 close(fd);
46 fd = 2;
47 }
48 }
50 va_start(arg, fmt);
51 vsnprint(buf, sizeof buf, fmt, arg);
52 va_end(arg);
53 t = proc()->thread;
54 if(t)
55 fprint(fd, "%d.%d: %s\n", getpid(), t->id, buf);
56 else
57 fprint(fd, "%d._: %s\n", getpid(), buf);
58 }
60 static _Thread*
61 getthreadnow(void)
62 {
63 return proc()->thread;
64 }
65 _Thread *(*threadnow)(void) = getthreadnow;
67 static Proc*
68 procalloc(void)
69 {
70 Proc *p;
72 p = malloc(sizeof *p);
73 if(p == nil)
74 sysfatal("procalloc malloc: %r");
75 memset(p, 0, sizeof *p);
76 addproc(p);
77 lock(&threadnproclock);
78 threadnproc++;
79 unlock(&threadnproclock);
80 return p;
81 }
83 static void
84 threadstart(uint y, uint x)
85 {
86 _Thread *t;
87 ulong z;
89 z = (ulong)x << 16; /* hide undefined 32-bit shift from 32-bit compilers */
90 z <<= 16;
91 z |= y;
92 t = (_Thread*)z;
94 /*print("threadstart %p\n", v); */
95 t->startfn(t->startarg);
96 /*print("threadexits %p\n", v); */
97 threadexits(nil);
98 /*print("not reacehd\n"); */
99 }
101 static _Thread*
102 threadalloc(void (*fn)(void*), void *arg, uint stack)
104 _Thread *t;
105 sigset_t zero;
106 uint x, y;
107 ulong z;
109 /* allocate the task and stack together */
110 t = malloc(sizeof *t+stack);
111 if(t == nil)
112 sysfatal("threadalloc malloc: %r");
113 memset(t, 0, sizeof *t);
114 t->stk = (uchar*)(t+1);
115 t->stksize = stack;
116 t->id = incref(&threadidref);
117 t->startfn = fn;
118 t->startarg = arg;
120 /* do a reasonable initialization */
121 memset(&t->context.uc, 0, sizeof t->context.uc);
122 sigemptyset(&zero);
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 = 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;
138 #endif
139 /*
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.
143 */
144 z = (ulong)t;
145 y = z;
146 z >>= 16; /* hide undefined 32-bit shift from 32-bit compilers */
147 x = z>>16;
148 makecontext(&t->context.uc, (void(*)(void))threadstart, 2, y, x);
150 return t;
153 _Thread*
154 _threadcreate(Proc *p, void (*fn)(void*), void *arg, uint stack)
156 _Thread *t;
158 t = threadalloc(fn, arg, stack);
159 t->proc = p;
160 addthreadinproc(p, t);
161 p->nthread++;
162 _threadready(t);
163 return t;
166 int
167 threadcreate(void (*fn)(void*), void *arg, uint stack)
169 _Thread *t;
171 t = _threadcreate(proc(), fn, arg, stack);
172 return t->id;
175 int
176 proccreate(void (*fn)(void*), void *arg, uint stack)
178 int id;
179 _Thread *t;
180 Proc *p;
182 p = procalloc();
183 t = _threadcreate(p, fn, arg, stack);
184 id = t->id; /* t might be freed after _procstart */
185 _procstart(p, procscheduler);
186 return id;
189 void
190 _threadswitch(void)
192 Proc *p;
194 needstack(0);
195 p = proc();
196 /*print("threadswtch %p\n", p); */
197 contextswitch(&p->thread->context, &p->schedcontext);
200 void
201 _threadready(_Thread *t)
203 Proc *p;
205 p = t->proc;
206 lock(&p->lock);
207 p->runrend.l = &p->lock;
208 addthread(&p->runqueue, t);
209 /*print("%d wake for job %d->%d\n", time(0), getpid(), p->osprocid); */
210 if(p != proc())
211 _procwakeupandunlock(&p->runrend);
212 else
213 unlock(&p->lock);
216 int
217 threadidle(void)
219 int n;
220 Proc *p;
222 p = proc();
223 n = p->nswitch;
224 lock(&p->lock);
225 p->runrend.l = &p->lock;
226 addthread(&p->idlequeue, p->thread);
227 unlock(&p->lock);
228 _threadswitch();
229 return p->nswitch - n;
232 int
233 threadyield(void)
235 int n;
236 Proc *p;
238 p = proc();
239 n = p->nswitch;
240 _threadready(p->thread);
241 _threadswitch();
242 return p->nswitch - n;
245 void
246 threadexits(char *msg)
248 Proc *p;
250 p = proc();
251 if(msg == nil)
252 msg = "";
253 utfecpy(p->msg, p->msg+sizeof p->msg, msg);
254 proc()->thread->exiting = 1;
255 _threadswitch();
258 void
259 threadpin(void)
261 Proc *p;
263 p = proc();
264 if(p->pinthread){
265 fprint(2, "already pinning a thread - %p %p\n", p->pinthread, p->thread);
266 assert(0);
268 p->pinthread = p->thread;
271 void
272 threadunpin(void)
274 Proc *p;
276 p = proc();
277 if(p->pinthread != p->thread){
278 fprint(2, "wrong pinthread - %p %p\n", p->pinthread, p->thread);
279 assert(0);
281 p->pinthread = nil;
284 static void
285 contextswitch(Context *from, Context *to)
287 if(swapcontext(&from->uc, &to->uc) < 0){
288 fprint(2, "swapcontext failed: %r\n");
289 assert(0);
293 static void
294 procscheduler(Proc *p)
296 _Thread *t;
298 setproc(p);
299 _threaddebug("scheduler enter");
300 /* print("s %p\n", p); */
301 lock(&p->lock);
302 for(;;){
303 if((t = p->pinthread) != nil){
304 while(!onlist(&p->runqueue, t)){
305 p->runrend.l = &p->lock;
306 _threaddebug("scheduler sleep (pin)");
307 _procsleep(&p->runrend);
308 _threaddebug("scheduler wake (pin)");
310 }else
311 while((t = p->runqueue.head) == nil){
312 if(p->nthread == 0)
313 goto Out;
314 if((t = p->idlequeue.head) != nil){
315 /*
316 * Run all the idling threads once.
317 */
318 while((t = p->idlequeue.head) != nil){
319 delthread(&p->idlequeue, t);
320 addthread(&p->runqueue, t);
322 continue;
324 p->runrend.l = &p->lock;
325 _threaddebug("scheduler sleep");
326 _procsleep(&p->runrend);
327 _threaddebug("scheduler wake");
329 if(p->pinthread && p->pinthread != t)
330 fprint(2, "p->pinthread %p t %p\n", p->pinthread, t);
331 assert(p->pinthread == nil || p->pinthread == t);
332 delthread(&p->runqueue, t);
333 unlock(&p->lock);
334 p->thread = t;
335 p->nswitch++;
336 _threaddebug("run %d (%s)", t->id, t->name);
337 contextswitch(&p->schedcontext, &t->context);
338 /*print("back in scheduler\n"); */
339 p->thread = nil;
340 lock(&p->lock);
341 if(t->exiting){
342 delthreadinproc(p, t);
343 p->nthread--;
344 /*print("nthread %d\n", p->nthread); */
345 free(t);
349 Out:
350 _threaddebug("scheduler exit");
351 if(p->mainproc){
352 /*
353 * Stupid bug - on Linux 2.6 and maybe elsewhere,
354 * if the main thread exits then the others keep running
355 * but the process shows up as a zombie in ps and is not
356 * attachable with ptrace. We'll just sit around pretending
357 * to be a system proc instead of exiting.
358 */
359 _threaddaemonize();
360 lock(&threadnproclock);
361 if(++threadnsysproc == threadnproc)
362 threadexitsall(p->msg);
363 p->sysproc = 1;
364 unlock(&threadnproclock);
365 for(;;)
366 sleep(1000);
369 delproc(p);
370 lock(&threadnproclock);
371 if(p->sysproc)
372 --threadnsysproc;
373 if(--threadnproc == threadnsysproc)
374 threadexitsall(p->msg);
375 unlock(&threadnproclock);
376 unlock(&p->lock);
377 _threadsetproc(nil);
378 free(p);
381 void
382 _threadsetsysproc(void)
384 lock(&threadnproclock);
385 if(++threadnsysproc == threadnproc)
386 threadexitsall(nil);
387 unlock(&threadnproclock);
388 proc()->sysproc = 1;
391 void**
392 procdata(void)
394 return &proc()->udata;
397 void**
398 threaddata(void)
400 return &proc()->thread->udata;
403 extern Jmp *(*_notejmpbuf)(void);
404 static Jmp*
405 threadnotejmp(void)
407 return &proc()->sigjmp;
410 /*
411 * debugging
412 */
413 void
414 threadsetname(char *fmt, ...)
416 va_list arg;
417 _Thread *t;
419 t = proc()->thread;
420 va_start(arg, fmt);
421 vsnprint(t->name, sizeof t->name, fmt, arg);
422 va_end(arg);
425 char*
426 threadgetname(void)
428 return proc()->thread->name;
431 void
432 threadsetstate(char *fmt, ...)
434 va_list arg;
435 _Thread *t;
437 t = proc()->thread;
438 va_start(arg, fmt);
439 vsnprint(t->state, sizeof t->name, fmt, arg);
440 va_end(arg);
443 int
444 threadid(void)
446 _Thread *t;
448 t = proc()->thread;
449 return t->id;
452 void
453 needstack(int n)
455 _Thread *t;
457 t = proc()->thread;
459 if((char*)&t <= (char*)t->stk
460 || (char*)&t - (char*)t->stk < 256+n){
461 fprint(2, "thread stack overflow: &t=%p tstk=%p n=%d\n", &t, t->stk, 256+n);
462 abort();
466 /*
467 * locking
468 */
469 static int
470 threadqlock(QLock *l, int block, ulong pc)
472 /*print("threadqlock %p\n", l); */
473 lock(&l->l);
474 if(l->owner == nil){
475 l->owner = (*threadnow)();
476 /*print("qlock %p @%#x by %p\n", l, pc, l->owner); */
477 unlock(&l->l);
478 return 1;
480 if(!block){
481 unlock(&l->l);
482 return 0;
484 /*print("qsleep %p @%#x by %p\n", l, pc, (*threadnow)()); */
485 addthread(&l->waiting, (*threadnow)());
486 unlock(&l->l);
488 _threadswitch();
490 if(l->owner != (*threadnow)()){
491 fprint(2, "%s: qlock pc=0x%lux owner=%p self=%p oops\n",
492 argv0, pc, l->owner, (*threadnow)());
493 abort();
495 /*print("qlock wakeup %p @%#x by %p\n", l, pc, (*threadnow)()); */
496 return 1;
499 static void
500 threadqunlock(QLock *l, ulong pc)
502 _Thread *ready;
504 lock(&l->l);
505 /*print("qlock unlock %p @%#x by %p (owner %p)\n", l, pc, (*threadnow)(), l->owner); */
506 if(l->owner == 0){
507 fprint(2, "%s: qunlock pc=0x%lux owner=%p self=%p oops\n",
508 argv0, pc, l->owner, (*threadnow)());
509 abort();
511 if((l->owner = ready = l->waiting.head) != nil)
512 delthread(&l->waiting, l->owner);
513 /*
514 * N.B. Cannot call _threadready() before unlocking l->l,
515 * because the thread we are readying might:
516 * - be in another proc
517 * - start running immediately
518 * - and free l before we get a chance to run again
519 */
520 unlock(&l->l);
521 if(ready)
522 _threadready(l->owner);
525 static int
526 threadrlock(RWLock *l, int block, ulong pc)
528 USED(pc);
530 lock(&l->l);
531 if(l->writer == nil && l->wwaiting.head == nil){
532 l->readers++;
533 unlock(&l->l);
534 return 1;
536 if(!block){
537 unlock(&l->l);
538 return 0;
540 addthread(&l->rwaiting, (*threadnow)());
541 unlock(&l->l);
542 _threadswitch();
543 return 1;
546 static int
547 threadwlock(RWLock *l, int block, ulong pc)
549 USED(pc);
551 lock(&l->l);
552 if(l->writer == nil && l->readers == 0){
553 l->writer = (*threadnow)();
554 unlock(&l->l);
555 return 1;
557 if(!block){
558 unlock(&l->l);
559 return 0;
561 addthread(&l->wwaiting, (*threadnow)());
562 unlock(&l->l);
563 _threadswitch();
564 return 1;
567 static void
568 threadrunlock(RWLock *l, ulong pc)
570 _Thread *t;
572 USED(pc);
573 t = nil;
574 lock(&l->l);
575 --l->readers;
576 if(l->readers == 0 && (t = l->wwaiting.head) != nil){
577 delthread(&l->wwaiting, t);
578 l->writer = t;
580 unlock(&l->l);
581 if(t)
582 _threadready(t);
586 static void
587 threadwunlock(RWLock *l, ulong pc)
589 _Thread *t;
591 USED(pc);
592 lock(&l->l);
593 l->writer = nil;
594 assert(l->readers == 0);
595 while((t = l->rwaiting.head) != nil){
596 delthread(&l->rwaiting, t);
597 l->readers++;
598 _threadready(t);
600 t = nil;
601 if(l->readers == 0 && (t = l->wwaiting.head) != nil){
602 delthread(&l->wwaiting, t);
603 l->writer = t;
605 unlock(&l->l);
606 if(t)
607 _threadready(t);
610 /*
611 * sleep and wakeup
612 */
613 static void
614 threadrsleep(Rendez *r, ulong pc)
616 addthread(&r->waiting, proc()->thread);
617 qunlock(r->l);
618 _threadswitch();
619 qlock(r->l);
622 static int
623 threadrwakeup(Rendez *r, int all, ulong pc)
625 int i;
626 _Thread *t;
628 for(i=0;; i++){
629 if(i==1 && !all)
630 break;
631 if((t = r->waiting.head) == nil)
632 break;
633 delthread(&r->waiting, t);
634 _threadready(t);
636 return i;
639 /*
640 * startup
641 */
643 static int threadargc;
644 static char **threadargv;
645 int mainstacksize;
646 extern int _p9usepwlibrary; /* getgrgid etc. smash the stack - tell _p9dir just say no */
647 static void
648 threadmainstart(void *v)
650 USED(v);
652 /*
653 * N.B. This call to proc() is a program's first call (indirectly) to a
654 * pthreads function while executing on a non-pthreads-allocated
655 * stack. If the pthreads implementation is using the stack pointer
656 * to locate the per-thread data, then this call will blow up.
657 * This means the pthread implementation is not suitable for
658 * running under libthread. Time to write your own. Sorry.
659 */
660 _p9usepwlibrary = 0;
661 threadmainproc = proc();
662 threadmain(threadargc, threadargv);
665 int
666 main(int argc, char **argv)
668 Proc *p;
670 argv0 = argv[0];
672 if(getenv("NOLIBTHREADDAEMONIZE") == nil)
673 _threadsetupdaemonize();
675 threadargc = argc;
676 threadargv = argv;
678 /*
679 * Install locking routines into C library.
680 */
681 _lock = _threadlock;
682 _unlock = _threadunlock;
683 _qlock = threadqlock;
684 _qunlock = threadqunlock;
685 _rlock = threadrlock;
686 _runlock = threadrunlock;
687 _wlock = threadwlock;
688 _wunlock = threadwunlock;
689 _rsleep = threadrsleep;
690 _rwakeup = threadrwakeup;
691 _notejmpbuf = threadnotejmp;
692 _pin = threadpin;
693 _unpin = threadunpin;
695 _pthreadinit();
696 p = procalloc();
697 p->mainproc = 1;
698 _threadsetproc(p);
699 if(mainstacksize == 0)
700 mainstacksize = 256*1024;
701 atnotify(threadinfo, 1);
702 _threadcreate(p, threadmainstart, nil, mainstacksize);
703 procscheduler(p);
704 sysfatal("procscheduler returned in threadmain!");
705 /* does not return */
706 return 0;
709 /*
710 * hooray for linked lists
711 */
712 static void
713 addthread(_Threadlist *l, _Thread *t)
715 if(l->tail){
716 l->tail->next = t;
717 t->prev = l->tail;
718 }else{
719 l->head = t;
720 t->prev = nil;
722 l->tail = t;
723 t->next = nil;
726 static void
727 delthread(_Threadlist *l, _Thread *t)
729 if(t->prev)
730 t->prev->next = t->next;
731 else
732 l->head = t->next;
733 if(t->next)
734 t->next->prev = t->prev;
735 else
736 l->tail = t->prev;
739 /* inefficient but rarely used */
740 static int
741 onlist(_Threadlist *l, _Thread *t)
743 _Thread *tt;
745 for(tt = l->head; tt; tt=tt->next)
746 if(tt == t)
747 return 1;
748 return 0;
751 static void
752 addthreadinproc(Proc *p, _Thread *t)
754 _Threadlist *l;
756 l = &p->allthreads;
757 if(l->tail){
758 l->tail->allnext = t;
759 t->allprev = l->tail;
760 }else{
761 l->head = t;
762 t->allprev = nil;
764 l->tail = t;
765 t->allnext = nil;
768 static void
769 delthreadinproc(Proc *p, _Thread *t)
771 _Threadlist *l;
773 l = &p->allthreads;
774 if(t->allprev)
775 t->allprev->allnext = t->allnext;
776 else
777 l->head = t->allnext;
778 if(t->allnext)
779 t->allnext->allprev = t->allprev;
780 else
781 l->tail = t->allprev;
784 Proc *_threadprocs;
785 Lock _threadprocslock;
786 static Proc *_threadprocstail;
788 static void
789 addproc(Proc *p)
791 lock(&_threadprocslock);
792 if(_threadprocstail){
793 _threadprocstail->next = p;
794 p->prev = _threadprocstail;
795 }else{
796 _threadprocs = p;
797 p->prev = nil;
799 _threadprocstail = p;
800 p->next = nil;
801 unlock(&_threadprocslock);
804 static void
805 delproc(Proc *p)
807 lock(&_threadprocslock);
808 if(p->prev)
809 p->prev->next = p->next;
810 else
811 _threadprocs = p->next;
812 if(p->next)
813 p->next->prev = p->prev;
814 else
815 _threadprocstail = p->prev;
816 unlock(&_threadprocslock);
819 /*
820 * notify - for now just use the usual mechanisms
821 */
822 void
823 threadnotify(int (*f)(void*, char*), int in)
825 atnotify(f, in);
828 static int
829 onrunqueue(Proc *p, _Thread *t)
831 _Thread *tt;
833 for(tt=p->runqueue.head; tt; tt=tt->next)
834 if(tt == t)
835 return 1;
836 return 0;
839 /*
840 * print state - called from SIGINFO
841 */
842 static int
843 threadinfo(void *v, char *s)
845 Proc *p;
846 _Thread *t;
848 if(strcmp(s, "quit") != 0 && strcmp(s, "sys: status request") != 0)
849 return 0;
851 for(p=_threadprocs; p; p=p->next){
852 fprint(2, "proc %p %s%s\n", (void*)p->osprocid, p->msg,
853 p->sysproc ? " (sysproc)": "");
854 for(t=p->allthreads.head; t; t=t->allnext){
855 fprint(2, "\tthread %d %s: %s %s\n",
856 t->id,
857 t == p->thread ? "Running" :
858 onrunqueue(p, t) ? "Ready" : "Sleeping",
859 t->state, t->name);
862 return 1;