2 #include "threadimpl.h"
4 //static Thread *runthread(Proc*);
7 static char *_psstate[] = {
17 if(s < 0 || s >= nelem(_psstate))
28 extern void ignusr1(void), _threaddie(int);
30 signal(SIGTERM, _threaddie);
34 p->pid = _threadgetpid();
37 while(_setlabel(&p->sched))
39 _threaddebug(DBGSCHED, "top of schedinit, _threadexitsallstatus=%p", _threadexitsallstatus);
40 if(_threadexitsallstatus)
41 exits(_threadexitsallstatus);
43 if((t=p->thread) != nil){
47 fprint(2, "moribund %d\n", t->moribund);
48 assert(t->moribund == 1);
51 t->prevt->nextt = t->nextt;
53 p->threads.head = t->nextt;
55 t->nextt->prevt = t->prevt;
57 p->threads.tail = t->prevt;
65 free(t); /* XXX how do we know there are no references? */
71 t->ret = _schedexec(&p->exec);
75 t->ret = _schedfork(p->newproc);
77 //fprint(2, "_schedfork: %r\n");
82 t->state = t->nextstate;
96 if(p->nthreads==0 || (p->nthreads==1 && p->idle))
102 if(p->idle->state != Ready){
103 fprint(2, "everyone is asleep\n");
104 exits("everyone is asleep");
106 unlock(&p->readylock);
107 _threaddebug(DBGSCHED, "running idle thread", p->nthreads);
111 _threaddebug(DBGSCHED, "sleeping for more work (%d threads)", p->nthreads);
113 unlock(&p->readylock);
114 while(rendezvous((ulong)q, 0) == ~0){
115 if(_threadexitsallstatus)
116 exits(_threadexitsallstatus);
118 /* lock picked up from _threadready */
122 unlock(&p->readylock);
133 p = _threadgetproc();
134 //fprint(2, "p %p\n", p);
135 if((t = p->thread) != nil){
136 if((ulong)&p < (ulong)t->stk){ /* stack overflow */
137 fprint(2, "stack overflow %lux %lux\n", (ulong)&p, (ulong)t->stk);
140 // _threaddebug(DBGSCHED, "pausing, state=%s set %p goto %p",
141 // psstate(t->state), &t->sched, &p->sched);
142 if(_setlabel(&t->sched)==0)
143 _gotolabel(&p->sched);
148 _threaddebug(DBGSCHED, "all threads gone; exiting");
152 _threaddebug(DBGSCHED, "running %d.%d", t->proc->pid, t->id);
155 _threaddebug(DBGSCHED, "%d.%d marked to die");
159 t->nextstate = Ready;
160 _gotolabel(&t->sched);
170 p = _threadgetproc();
172 return (ulong)&p - (ulong)t->stk;
176 _threadready(Thread *t)
180 if(t == t->proc->idle){
181 _threaddebug(DBGSCHED, "idle thread is ready");
185 assert(t->state == Ready);
186 _threaddebug(DBGSCHED, "readying %d.%d", t->proc->pid, t->id);
188 lock(&t->proc->readylock);
196 assert(q->asleep == 1);
198 /* lock passes to runthread */
199 _threaddebug(DBGSCHED, "waking process %d", t->proc->pid);
200 while(rendezvous((ulong)q, 0) == ~0){
201 if(_threadexitsallstatus)
202 exits(_threadexitsallstatus);
205 unlock(&t->proc->readylock);
215 p = _threadgetproc();
224 for(t=q->head; t->next!=q->tail; t=t->next)
230 _threaddebug(DBGSCHED, "p->idle is %d\n", idle->id);
231 unlock(&p->readylock);