2 #include "../port/lib.h"
6 #include "../port/error.h"
10 int schedgain = 30; /* units in seconds */
13 void updatecpu(Proc*);
14 int reprioritize(Proc*);
16 ulong delayedscheds; /* statistics */
21 static struct Procalloc
40 { /* BUG: generate automatically */
56 static void pidfree(Proc*);
57 static void rebalance(void);
63 schedinit(void) /* never returns */
69 if((e = up->edf) && (e->flags & Admitted))
84 * Holding locks from pexit:
94 up->qnext = procalloc.free;
97 /* proc is free now, make sure unlock() wont touch it */
98 up = procalloc.Lock.p = nil;
110 * If changing this routine, look also at sleep(). It
111 * contains a copy of the guts of sched().
119 panic("cpu%d: ilockdepth %d, last lock %#p at %#p, sched called from %#p",
122 up? up->lastilock: nil,
123 (up && up->lastilock)? up->lastilock->pc: 0,
127 * Delay the sched until the process gives up the locks
128 * it is holding. This avoids dumb lock loops.
129 * Don't delay if the process is Moribund.
130 * It called sched to die.
131 * But do sched eventually. This avoids a missing unlock
132 * from hanging the entire kernel.
133 * But don't reschedule procs holding palloc or procalloc.
134 * Those are far too important to be holding while asleep.
136 * This test is not exact. There can still be a few instructions
137 * in the middle of taslock when a process holds a lock
138 * but Lock.p has not yet been initialized.
141 if(up->state != Moribund)
142 if(up->delaysched < 20
143 || palloc.Lock.p == up
144 || procalloc.Lock.p == up){
157 if(setlabel(&up->sched)){
162 gotolabel(&m->sched);
167 p->priority = reprioritize(p);
170 m->schedticks = m->ticks + HZ/10;
174 up->mach = MACHP(m->machno);
177 gotolabel(&up->sched);
189 return runvec & ~((1<<(up->priority+1))-1);
193 * here once per clock tick to see if we should resched
198 /* once a second, rebalance will reprioritize ready procs */
202 /* unless preempted, get to run for at least 100ms */
204 || (!up->fixedpri && m->ticks > m->schedticks && anyready())){
205 m->readied = nil; /* avoid cooperative scheduling */
211 * here at the end of non-clock interrupts to see if we should preempt the
212 * current process. Returns 1 if preempted, 0 otherwise.
217 if(up && up->state == Running)
218 if(up->preempted == 0)
221 m->readied = nil; /* avoid cooperative scheduling */
232 * Update the cpu time average for this particular process,
233 * which is about to change from up -> not up or vice versa.
234 * p->lastupdate is the last time an updatecpu happened.
236 * The cpu time average is a decaying average that lasts
237 * about D clock ticks. D is chosen to be approximately
238 * the cpu time of a cpu-intensive "quick job". A job has to run
239 * for approximately D clock ticks before we home in on its
240 * actual cpu usage. Thus if you manage to get in and get out
241 * quickly, you won't be penalized during your burst. Once you
242 * start using your share of the cpu for more than about D
243 * clock ticks though, your p->cpu hits 1000 (1.0) and you end up
244 * below all the other quick jobs. Interactive tasks, because
245 * they basically always use less than their fair share of cpu,
248 * If the process has not been running, then we want to
251 * cpu = cpu * (D-1)/D
255 * cpu = cpu * ((D-1)/D)^n
257 * but D is big enough that this is approximately
259 * cpu = cpu * (D-n)/D
261 * so we use that instead.
263 * If the process has been running, we apply the filter to
264 * 1 - cpu, yielding a similar equation. Note that cpu is
265 * stored in fixed point (* 1000).
267 * Updatecpu must be called before changing up, in order
268 * to maintain accurate cpu usage statistics. It can be called
269 * at any time to bring the stats for a given proc up-to-date.
275 int D = schedgain*HZ*Scaling;
280 t = MACHP(0)->ticks*Scaling + Scaling/2;
281 n = t - p->lastupdate;
291 p->cpu = (ocpu*(D-n))/D;
298 //iprint("pid %d %s for %d cpu %d -> %d\n", p->pid,p==up?"active":"inactive",n, ocpu,p->cpu);
302 * On average, p has used p->cpu of a cpu recently.
303 * Its fair share is conf.nmach/m->load of a cpu. If it has been getting
304 * too much, penalize it. If it has been getting not enough, reward it.
305 * I don't think you can get much more than your fair share that
306 * often, so most of the queues are for using less. Having a priority
307 * of 3 means you're just right. Having a higher priority (up to p->basepri)
308 * means you're not using as much as you could.
311 reprioritize(Proc *p)
313 int fairshare, n, load, ratio;
315 load = MACHP(0)->load;
320 * fairshare = 1.000 * conf.nmach * 1.000/load,
321 * except the decimal point is moved three places
322 * on both load and fairshare.
324 fairshare = (conf.nmach*1000*1000)/load;
328 ratio = (fairshare+n/2) / n;
329 if(ratio > p->basepri)
332 panic("reprioritize");
333 //iprint("pid %d cpu %d load %d fair %d pri %d\n", p->pid, p->cpu, load, fairshare, ratio);
338 * add a process to a scheduling queue
341 queueproc(Schedq *rq, Proc *p)
361 * try to remove a process from a scheduling queue (called splhi)
364 dequeueproc(Schedq *rq, Proc *tp)
372 * the queue may have changed before we locked runq,
373 * refind the target process.
376 for(p = rq->head; p; p = p->rnext){
383 * p->mach==0 only when process state is saved
385 if(p == 0 || p->mach){
396 runvec &= ~(1<<(rq-runq));
399 if(p->state != Ready)
400 print("dequeueproc %s %lud %s\n", p->text, p->pid, statename[p->state]);
407 * ready(p) picks a new priority for a process and sticks it in the
408 * runq for that priority.
415 void (*pt)(Proc*, int, vlong);
417 if(p->state == Ready){
418 print("double ready %s %lud pc %p\n", p->text, p->pid, getcallerpc(&p));
429 m->readied = p; /* group scheduling */
432 pri = reprioritize(p);
444 * yield the processor and drop our priority
450 /* pretend we just used 1/2 tick */
451 up->lastupdate -= Scaling/2;
457 * recalculate priorities once a second. We need to do this
458 * since priorities will otherwise only be recalculated when
459 * the running process blocks.
471 if(t - balancetime < HZ)
475 for(pri=0, rq=runq; pri<Npriq; pri++, rq++){
480 if(p->mp != MACHP(m->machno))
482 if(pri == p->basepri)
485 npri = reprioritize(p);
488 p = dequeueproc(rq, p);
490 queueproc(&runq[npri], p);
499 * pick a process to run
508 void (*pt)(Proc*, int, vlong);
512 /* cooperative scheduling until the clock ticks */
513 if((p=m->readied) && p->mach==0 && p->state==Ready
514 && runq[Nrq-1].head == nil && runq[Nrq-2].head == nil){
516 rq = &runq[p->priority];
524 * find a process that last ran on this processor (affinity),
525 * or one that hasn't moved in a while (load balancing). Every
526 * time around the loop affinity goes down.
531 * find the highest priority target process that this
532 * processor can run given affinity constraints.
535 for(rq = &runq[Nrq-1]; rq >= runq; rq--){
536 for(p = rq->head; p; p = p->rnext){
537 if(p->mp == nil || p->mp == MACHP(m->machno)
538 || (!p->wired && i > 0))
543 /* waste time or halt the CPU */
546 /* remember how much time we're here */
548 m->perf.inidle += now-start;
554 p = dequeueproc(rq, p);
559 p->mp = MACHP(m->machno);
562 edfrun(p, rq == &runq[PriEdf]); /* start deadline timer and do admin */
578 /* Only reliable way to see if we are Running */
597 if(p = procalloc.free)
600 snprint(msg, sizeof msg, "no procs; %s forking",
601 up? up->text: "kernel");
606 procalloc.free = p->qnext;
631 p->errstr = p->errbuf0;
632 p->syserrstr = p->errbuf1;
633 p->errbuf0[0] = '\0';
634 p->errbuf1[0] = '\0';
638 kstrdup(&p->user, "*nouser");
639 kstrdup(&p->text, "*notext");
640 kstrdup(&p->args, "");
643 memset(p->seg, 0, sizeof p->seg);
645 p->noteid = pidalloc(p);
647 p->kstack = smalloc(KSTACK);
652 procpriority(p, PriNormal, 0);
654 p->lastupdate = MACHP(0)->ticks*Scaling;
661 * wire this proc to a machine
664 procwired(Proc *p, int bm)
668 char nwired[MAXMACH];
672 /* pick a machine to wire to */
673 memset(nwired, 0, sizeof(nwired));
676 for(i=0; i<conf.nproc; i++, pp++){
679 nwired[wm->machno]++;
682 for(i=0; i<conf.nmach; i++)
683 if(nwired[i] < nwired[bm])
686 /* use the virtual machine requested */
687 bm = bm % conf.nmach;
690 p->wired = MACHP(bm);
695 procpriority(Proc *p, int pri, int fixed)
711 procinit0(void) /* bad planning - clashes with devproc.c */
716 procalloc.free = xalloc(conf.nproc*sizeof(Proc));
717 if(procalloc.free == nil){
719 panic("cannot allocate %lud procs (%ludMB)", conf.nproc, conf.nproc*sizeof(Proc)/(1024*1024));
721 procalloc.arena = procalloc.free;
724 for(i=0; i<conf.nproc-1; i++,p++)
730 * sleep if a condition is not true. Another process will
731 * awaken us after it sets the condition. When we awaken
732 * the condition may no longer be true.
734 * we lock both the process and the rendezvous to keep r->p
735 * and p->r synchronized.
738 sleep(Rendez *r, int (*f)(void*), void *arg)
741 void (*pt)(Proc*, int, vlong);
746 print("process %lud sleeps with %lud locks held, last lock %#p locked at pc %#lux, sleep called from %#p\n",
747 up->pid, up->nlocks.ref, up->lastlock, up->lastlock->pc, getcallerpc(&r));
751 print("double sleep called from %#p, %lud %lud\n", getcallerpc(&r), r->p->pid, up->pid);
756 * Wakeup only knows there may be something to do by testing
757 * r->p in order to get something to lock on.
758 * Flush that information out to memory in case the sleep is
763 if((*f)(arg) || up->notepending){
765 * if condition happened or a note is pending
773 * now we are committed to
774 * change state and call scheduler
786 if(setlabel(&up->sched)) {
788 * here when the process is awakened
794 * here to go to sleep (i.e. stop Running)
798 gotolabel(&m->sched);
802 if(up->notepending) {
805 if(up->procctl == Proc_exitme && up->closingfgrp)
816 return up->trend == nil || up->tfn(arg);
820 twakeup(Ureg*, Timer *t)
833 tsleep(Rendez *r, int (*fn)(void*), void *arg, ulong ms)
836 print("tsleep: timer active: mode %d, tf %#p\n", up->tmode, up->tf);
841 up->tmode = Trelative;
859 * Expects that only one process can call wakeup for any given Rendez.
860 * We hold both locks to ensure that r->p and p->r remain consistent.
861 * Richard Miller has a better solution that doesn't require both to
862 * be held simultaneously, but I'm a paranoid - presotto.
877 if(p->state != Wakeme || p->r != r){
878 iprint("%p %p %d\n", p->r, r, p->state);
879 panic("wakeup: state");
894 * if waking a sleeping process, this routine must hold both
895 * p->rlock and r->lock. However, it can't know them in
896 * the same order as wakeup causing a possible lock ordering
897 * deadlock. We break the deadlock by giving up the p->rlock
898 * lock if we can't get the r->lock and retrying.
901 postnote(Proc *p, int dolock, char *n, int flag)
918 if(n != nil && flag != NUser && (p->notify == 0 || p->notified))
922 if(p->nnote < NNOTE && n != nil) {
923 kstrcpy(p->note[p->nnote].msg, n, ERRMAX);
924 p->note[p->nnote++].flag = flag;
931 /* this loop is to avoid lock ordering problems. */
939 /* waiting for a wakeup? */
943 /* try for the second lock */
945 if(p->state != Wakeme || r->p != p)
946 panic("postnote: state %d %d %d", r->p != p, p->r != r, p->state);
954 /* give other process time to get out of critical section and try again */
964 /* Try and pull out of a eqlock */
967 if(p->state == Queueing && p->eql == q){
970 for(l = nil, d = q->head; d; l = d, d = d->qnext){
979 p->eql = 0; /* not taken */
989 /* Try and pull out of a rendezvous */
991 if(p->state == Rendezvous) {
994 l = &REND(p->rgrp, p->rendtag);
995 for(d = *l; d; d = d->rendhash) {
1012 * weird thing: keep at most NBROKEN around
1026 if(broken.n == NBROKEN) {
1028 memmove(&broken.p[0], &broken.p[1], sizeof(Proc*)*(NBROKEN-1));
1031 broken.p[broken.n++] = p;
1046 for(b=0; b < broken.n; b++)
1047 if(broken.p[b] == p) {
1049 memmove(&broken.p[b], &broken.p[b+1],
1050 sizeof(Proc*)*(NBROKEN-(b+1)));
1064 for(i=0; i<n; i++) {
1074 pexit(char *exitstr, int freemem)
1085 void (*pt)(Proc*, int, vlong);
1094 /* nil out all the resources under lock (free later) */
1106 qunlock(&up->debug);
1120 * if not a kernel process and have a parent,
1121 * do some housekeeping.
1123 if(up->kp == 0 && up->parentpid != 0) {
1124 wq = smalloc(sizeof(Waitq));
1125 wq->w.pid = up->pid;
1126 utime = up->time[TUser] + up->time[TCUser];
1127 stime = up->time[TSys] + up->time[TCSys];
1128 wq->w.time[TUser] = tk2ms(utime);
1129 wq->w.time[TSys] = tk2ms(stime);
1130 wq->w.time[TReal] = tk2ms(MACHP(0)->ticks - up->time[TReal]);
1131 if(exitstr && exitstr[0])
1132 snprint(wq->w.msg, sizeof(wq->w.msg), "%s %lud: %s", up->text, up->pid, exitstr);
1134 wq->w.msg[0] = '\0';
1139 * Check that parent is still alive.
1141 if(p->pid == up->parentpid && p->state != Broken) {
1143 p->time[TCUser] += utime;
1144 p->time[TCSys] += stime;
1146 * If there would be more than 128 wait records
1147 * processes for my parent, then don't leave a wait
1148 * record behind. This helps prevent badly written
1149 * daemon processes from accumulating lots of wait
1152 if(p->nwait < 128) {
1153 wq->next = p->waitq;
1164 else if(up->kp == 0 && up->parent == 0){
1166 exitstr = "unknown";
1167 panic("boot process died: %s", exitstr);
1173 qlock(&up->seglock);
1174 es = &up->seg[NSEG];
1175 for(s = up->seg; s < es; s++) {
1181 qunlock(&up->seglock);
1183 lock(&up->exl); /* Prevent my children from leaving waits */
1189 while((wq = up->waitq) != 0){
1190 up->waitq = wq->next;
1194 /* release debuggers */
1197 wakeup(&up->pdbg->sleep);
1200 if(up->syscalltrace) {
1201 free(up->syscalltrace);
1202 up->syscalltrace = 0;
1204 qunlock(&up->debug);
1206 /* Sched must not loop for these locks */
1211 up->state = Moribund;
1222 return p->waitq != 0;
1231 if(!canqlock(&up->qwaitr))
1235 qunlock(&up->qwaitr);
1240 while(up->waitq == 0) {
1241 if(up->nchild == 0) {
1246 sleep(&up->waitr, haswaitq, up);
1250 up->waitq = wq->next;
1254 qunlock(&up->qwaitr);
1258 memmove(w, &wq->w, sizeof(Waitmsg));
1267 return &procalloc.arena[i];
1281 bss = p->seg[BSEG]->top;
1285 s = statename[p->state];
1286 print("%3lud:%10s pc %8lux dbgpc %8lux %8s (%s) ut %ld st %ld bss %lux qpc %lux nl %lud nd %lud lpc %lux pri %lud\n",
1287 p->pid, p->text, p->pc, dbgpc(p), s, statename[p->state],
1288 p->time[0], p->time[1], bss, p->qpc, p->nlocks.ref, p->delaysched, p->lastlock ? p->lastlock->pc : 0, p->priority);
1298 print("up %lud\n", up->pid);
1300 print("no current process\n");
1301 for(i=0; i<conf.nproc; i++) {
1302 p = &procalloc.arena[i];
1303 if(p->state == Dead)
1311 * wait till all processes have flushed their mmu
1312 * state about segement s
1315 procflushseg(Segment *s)
1317 int i, ns, nm, nwait;
1321 * tell all processes with this
1322 * segment to flush their mmu's
1325 for(i=0; i<conf.nproc; i++) {
1326 p = &procalloc.arena[i];
1327 if(p->state == Dead)
1329 for(ns = 0; ns < NSEG; ns++)
1330 if(p->seg[ns] == s){
1332 for(nm = 0; nm < conf.nmach; nm++){
1333 if(MACHP(nm)->proc == p){
1334 MACHP(nm)->flushmmu = 1;
1346 * wait for all processors to take a clock interrupt
1347 * and flush their mmu's
1349 for(nm = 0; nm < conf.nmach; nm++)
1351 while(MACHP(nm)->flushmmu)
1361 for(rq = &runq[Nrq-1]; rq >= runq; rq--){
1364 print("rq%ld:", rq-runq);
1365 for(p = rq->head; p; p = p->rnext)
1366 print(" %lud(%lud)", p->pid, m->ticks - p->readytime);
1370 print("nrdy %d\n", nrdy);
1374 kproc(char *name, void (*func)(void *), void *arg)
1385 p->scallnr = up->scallnr;
1388 p->slash = up->slash;
1393 memmove(p->note, up->note, sizeof(p->note));
1394 p->nnote = up->nnote;
1396 p->lastnote = up->lastnote;
1397 p->notify = up->notify;
1401 procpriority(p, PriKproc, 0);
1403 kprocchild(p, func, arg);
1405 kstrdup(&p->user, eve);
1406 kstrdup(&p->text, name);
1412 memset(p->time, 0, sizeof(p->time));
1413 p->time[TReal] = MACHP(0)->ticks;
1418 * called splhi() by notify(). See comment in notify for the
1427 switch(p->procctl) {
1430 pprint("Killed: Insufficient physical memory\n");
1431 pexit("Killed: Insufficient physical memory", 1);
1434 spllo(); /* pexit has locks in it */
1445 p->psstate = "Stopped";
1446 /* free a waiting debugger */
1450 wakeup(&p->pdbg->sleep);
1470 assert(up->nerrlab < NERR);
1471 kstrcpy(up->errstr, err, ERRMAX);
1472 setlabel(&up->errlab[NERR-1]);
1479 assert(up->nerrlab > 0);
1480 gotolabel(&up->errlab[--up->nerrlab]);
1484 exhausted(char *resource)
1488 snprint(buf, sizeof buf, "no free %s", resource);
1489 iprint("%s\n", buf);
1503 ep = procalloc.arena+conf.nproc;
1504 for(p = procalloc.arena; p < ep; p++) {
1505 if(p->state == Dead || p->kp || !canqlock(&p->seglock))
1508 for(i=1; i<NSEG; i++) {
1510 if(s == 0 || !canqlock(&s->lk))
1512 l += (ulong)mcountseg(s);
1515 qunlock(&p->seglock);
1516 if(l > max && ((p->procmode&0222) || strcmp(eve, p->user)!=0)) {
1521 if(kp == 0 || !canqlock(&kp->seglock))
1523 print("%lud: %s killed: %s\n", kp->pid, kp->text, why);
1524 for(p = procalloc.arena; p < ep; p++) {
1525 if(p->state == Dead || p->kp)
1527 if(p != kp && p->seg[BSEG] && p->seg[BSEG] == kp->seg[BSEG])
1528 p->procctl = Proc_exitbig;
1530 kp->procctl = Proc_exitbig;
1531 for(i = 0; i < NSEG; i++) {
1533 if(s != 0 && canqlock(&s->lk)) {
1534 mfreeseg(s, s->base, (s->top - s->base)/BY2PG);
1538 qunlock(&kp->seglock);
1542 * change ownership to 'new' of all processes owned by 'old'. Used when
1546 renameuser(char *old, char *new)
1550 ep = procalloc.arena+conf.nproc;
1551 for(p = procalloc.arena; p < ep; p++)
1552 if(p->user!=nil && strcmp(old, p->user)==0)
1553 kstrdup(&p->user, new);
1557 * time accounting called by clock() splhi'd
1569 p->time[p->insyscall]++;
1572 /* calculate decaying duty cycles */
1574 per = n - m->perf.last;
1576 per = (m->perf.period*(HZ-1) + per)/HZ;
1578 m->perf.period = per;
1580 m->perf.avg_inidle = (m->perf.avg_inidle*(HZ-1)+m->perf.inidle)/HZ;
1583 m->perf.avg_inintr = (m->perf.avg_inintr*(HZ-1)+m->perf.inintr)/HZ;
1586 /* only one processor gets to compute system load averages */
1591 * calculate decaying load average.
1592 * if we decay by (n-1)/n then it takes
1593 * n clock ticks to go from load L to .36 L once
1594 * things quiet down. it takes about 5 n clock
1595 * ticks to go to zero. so using HZ means this is
1596 * approximately the load over the last second,
1597 * with a tail lasting about 5 seconds.
1602 m->load = (m->load*(HZ-1)+n)/HZ;
1608 static int gen, wrapped;
1614 pid = ++gen & 0x7FFFFFFF;
1619 h = pid % nelem(procalloc.ht);
1621 for(x = procalloc.ht[h]; x != nil; x = x->pidhash)
1626 p->pidhash = procalloc.ht[h];
1627 procalloc.ht[h] = p;
1639 h = p->pid % nelem(procalloc.ht);
1641 for(l = &procalloc.ht[h]; *l != nil; l = &(*l)->pidhash)
1650 procindex(ulong pid)
1657 h = pid % nelem(procalloc.ht);
1659 for(p = procalloc.ht[h]; p != nil; p = p->pidhash)
1661 s = p - procalloc.arena;