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) != nil && (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 != nil ? up->lastilock: nil,
123 (up != nil && up->lastilock != nil) ? 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);
176 //print("poolcheck sched %s\n", p->text);
178 //poolcheck(mainmem);
180 gotolabel(&up->sched);
192 return runvec & ~((1<<(up->priority+1))-1);
196 * here once per clock tick to see if we should resched
201 /* once a second, rebalance will reprioritize ready procs */
205 /* unless preempted, get to run for at least 100ms */
207 || (!up->fixedpri && m->ticks > m->schedticks && anyready())){
208 m->readied = nil; /* avoid cooperative scheduling */
214 * here at the end of non-clock interrupts to see if we should preempt the
215 * current process. Returns 1 if preempted, 0 otherwise.
220 if(up != nil && up->state == Running)
221 if(up->preempted == 0)
224 m->readied = nil; /* avoid cooperative scheduling */
235 * Update the cpu time average for this particular process,
236 * which is about to change from up -> not up or vice versa.
237 * p->lastupdate is the last time an updatecpu happened.
239 * The cpu time average is a decaying average that lasts
240 * about D clock ticks. D is chosen to be approximately
241 * the cpu time of a cpu-intensive "quick job". A job has to run
242 * for approximately D clock ticks before we home in on its
243 * actual cpu usage. Thus if you manage to get in and get out
244 * quickly, you won't be penalized during your burst. Once you
245 * start using your share of the cpu for more than about D
246 * clock ticks though, your p->cpu hits 1000 (1.0) and you end up
247 * below all the other quick jobs. Interactive tasks, because
248 * they basically always use less than their fair share of cpu,
251 * If the process has not been running, then we want to
254 * cpu = cpu * (D-1)/D
258 * cpu = cpu * ((D-1)/D)^n
260 * but D is big enough that this is approximately
262 * cpu = cpu * (D-n)/D
264 * so we use that instead.
266 * If the process has been running, we apply the filter to
267 * 1 - cpu, yielding a similar equation. Note that cpu is
268 * stored in fixed point (* 1000).
270 * Updatecpu must be called before changing up, in order
271 * to maintain accurate cpu usage statistics. It can be called
272 * at any time to bring the stats for a given proc up-to-date.
278 int D = schedgain*HZ*Scaling;
283 t = MACHP(0)->ticks*Scaling + Scaling/2;
284 n = t - p->lastupdate;
294 p->cpu = (ocpu*(D-n))/D;
301 //iprint("pid %d %s for %d cpu %d -> %d\n", p->pid,p==up?"active":"inactive",n, ocpu,p->cpu);
305 * On average, p has used p->cpu of a cpu recently.
306 * Its fair share is conf.nmach/m->load of a cpu. If it has been getting
307 * too much, penalize it. If it has been getting not enough, reward it.
308 * I don't think you can get much more than your fair share that
309 * often, so most of the queues are for using less. Having a priority
310 * of 3 means you're just right. Having a higher priority (up to p->basepri)
311 * means you're not using as much as you could.
314 reprioritize(Proc *p)
316 int fairshare, n, load, ratio;
318 load = MACHP(0)->load;
323 * fairshare = 1.000 * conf.nmach * 1.000/load,
324 * except the decimal point is moved three places
325 * on both load and fairshare.
327 fairshare = (conf.nmach*1000*1000)/load;
331 ratio = (fairshare+n/2) / n;
332 if(ratio > p->basepri)
335 panic("reprioritize");
336 //iprint("pid %d cpu %d load %d fair %d pri %d\n", p->pid, p->cpu, load, fairshare, ratio);
341 * add a process to a scheduling queue
344 queueproc(Schedq *rq, Proc *p)
364 * try to remove a process from a scheduling queue (called splhi)
367 dequeueproc(Schedq *rq, Proc *tp)
375 * the queue may have changed before we locked runq,
376 * refind the target process.
379 for(p = rq->head; p != nil; p = p->rnext){
386 * p->mach==0 only when process state is saved
388 if(p == nil || p->mach != nil){
399 runvec &= ~(1<<(rq-runq));
402 if(p->state != Ready)
403 print("dequeueproc %s %lud %s\n", p->text, p->pid, statename[p->state]);
410 * ready(p) picks a new priority for a process and sticks it in the
411 * runq for that priority.
418 void (*pt)(Proc*, int, vlong);
420 if(p->state == Ready){
421 print("double ready %s %lud pc %p\n", p->text, p->pid, getcallerpc(&p));
431 if(up != p && (p->wired == nil || p->wired == MACHP(m->machno)))
432 m->readied = p; /* group scheduling */
435 pri = reprioritize(p);
447 * yield the processor and drop our priority
453 /* pretend we just used 1/2 tick */
454 up->lastupdate -= Scaling/2;
460 * recalculate priorities once a second. We need to do this
461 * since priorities will otherwise only be recalculated when
462 * the running process blocks.
474 if(t - balancetime < HZ)
478 for(pri=0, rq=runq; pri<Npriq; pri++, rq++){
483 if(p->mp != MACHP(m->machno))
485 if(pri == p->basepri)
488 npri = reprioritize(p);
491 p = dequeueproc(rq, p);
493 queueproc(&runq[npri], p);
502 * pick a process to run
511 void (*pt)(Proc*, int, vlong);
515 /* cooperative scheduling until the clock ticks */
516 if((p = m->readied) != nil && p->mach == nil && p->state == Ready
517 && (p->wired == nil || p->wired == MACHP(m->machno))
518 && runq[Nrq-1].head == nil && runq[Nrq-2].head == nil){
520 rq = &runq[p->priority];
528 * find a process that last ran on this processor (affinity),
529 * or one that hasn't moved in a while (load balancing). Every
530 * time around the loop affinity goes down.
535 * find the highest priority target process that this
536 * processor can run given affinity constraints.
539 for(rq = &runq[Nrq-1]; rq >= runq; rq--){
540 for(p = rq->head; p != nil; p = p->rnext){
541 if(p->mp == nil || p->mp == MACHP(m->machno)
542 || (p->wired == nil && i > 0))
547 /* waste time or halt the CPU */
550 /* remember how much time we're here */
552 m->perf.inidle += now-start;
558 p = dequeueproc(rq, p);
563 p->mp = MACHP(m->machno);
566 edfrun(p, rq == &runq[PriEdf]); /* start deadline timer and do admin */
582 /* Only reliable way to see if we are Running */
601 if((p = procalloc.free) != nil)
604 snprint(msg, sizeof msg, "no procs; %s forking",
605 up != nil ? up->text: "kernel");
610 procalloc.free = p->qnext;
630 p->syscalltrace = nil;
635 p->errstr = p->errbuf0;
636 p->syserrstr = p->errbuf1;
637 p->errbuf0[0] = '\0';
638 p->errbuf1[0] = '\0';
642 kstrdup(&p->user, "*nouser");
643 kstrdup(&p->text, "*notext");
644 kstrdup(&p->args, "");
647 memset(p->seg, 0, sizeof p->seg);
649 p->noteid = pidalloc(p);
651 p->kstack = smalloc(KSTACK);
656 procpriority(p, PriNormal, 0);
658 p->lastupdate = MACHP(0)->ticks*Scaling;
665 * wire this proc to a machine
668 procwired(Proc *p, int bm)
672 char nwired[MAXMACH];
676 /* pick a machine to wire to */
677 memset(nwired, 0, sizeof(nwired));
680 for(i=0; i<conf.nproc; i++, pp++){
682 if(wm != nil && pp->pid)
683 nwired[wm->machno]++;
686 for(i=0; i<conf.nmach; i++)
687 if(nwired[i] < nwired[bm])
690 /* use the virtual machine requested */
691 bm = bm % conf.nmach;
694 p->wired = MACHP(bm);
699 procpriority(Proc *p, int pri, int fixed)
715 procinit0(void) /* bad planning - clashes with devproc.c */
720 p = xalloc(conf.nproc*sizeof(Proc));
723 panic("cannot allocate %lud procs (%ludMB)", conf.nproc, conf.nproc*sizeof(Proc)/(1024*1024));
727 for(i=0; i<conf.nproc-1; i++, p++)
733 * sleep if a condition is not true. Another process will
734 * awaken us after it sets the condition. When we awaken
735 * the condition may no longer be true.
737 * we lock both the process and the rendezvous to keep r->p
738 * and p->r synchronized.
741 sleep(Rendez *r, int (*f)(void*), void *arg)
744 void (*pt)(Proc*, int, vlong);
749 print("process %lud sleeps with %d locks held, last lock %#p locked at pc %#p, sleep called from %#p\n",
750 up->pid, up->nlocks, up->lastlock, up->lastlock->pc, getcallerpc(&r));
754 print("double sleep called from %#p, %lud %lud\n", getcallerpc(&r), r->p->pid, up->pid);
759 * Wakeup only knows there may be something to do by testing
760 * r->p in order to get something to lock on.
761 * Flush that information out to memory in case the sleep is
766 if((*f)(arg) || up->notepending){
768 * if condition happened or a note is pending
776 * now we are committed to
777 * change state and call scheduler
789 if(setlabel(&up->sched)) {
791 * here when the process is awakened
797 * here to go to sleep (i.e. stop Running)
801 gotolabel(&m->sched);
805 if(up->notepending) {
817 if(up->procctl == Proc_exitme && up->closingfgrp != nil)
825 return up->trend == nil || up->tfn(arg);
829 twakeup(Ureg*, Timer *t)
842 tsleep(Rendez *r, int (*fn)(void*), void *arg, ulong ms)
845 print("tsleep: timer active: mode %d, tf %#p\n", up->tmode, up->tf);
850 up->tmode = Trelative;
868 * Expects that only one process can call wakeup for any given Rendez.
869 * We hold both locks to ensure that r->p and p->r remain consistent.
870 * Richard Miller has a better solution that doesn't require both to
871 * be held simultaneously, but I'm a paranoid - presotto.
886 if(p->state != Wakeme || p->r != r){
887 iprint("%p %p %d\n", p->r, r, p->state);
888 panic("wakeup: state");
903 * if waking a sleeping process, this routine must hold both
904 * p->rlock and r->lock. However, it can't know them in
905 * the same order as wakeup causing a possible lock ordering
906 * deadlock. We break the deadlock by giving up the p->rlock
907 * lock if we can't get the r->lock and retrying.
910 postnote(Proc *p, int dolock, char *n, int flag)
927 if(n != nil && flag != NUser && (p->notify == 0 || p->notified))
931 if(p->nnote < NNOTE && n != nil) {
932 kstrcpy(p->note[p->nnote].msg, n, ERRMAX);
933 p->note[p->nnote++].flag = flag;
940 /* this loop is to avoid lock ordering problems. */
948 /* waiting for a wakeup? */
952 /* try for the second lock */
954 if(p->state != Wakeme || r->p != p)
955 panic("postnote: state %d %d %d", r->p != p, p->r != r, p->state);
963 /* give other process time to get out of critical section and try again */
973 /* Try and pull out of a eqlock */
974 if((q = p->eql) != nil){
976 if(p->state == Queueing && p->eql == q){
979 for(l = nil, d = q->head; d != nil; l = d, d = d->qnext){
988 p->eql = nil; /* not taken */
998 /* Try and pull out of a rendezvous */
1000 if(p->state == Rendezvous) {
1003 l = &REND(p->rgrp, p->rendtag);
1004 for(d = *l; d != nil; d = d->rendhash) {
1021 * weird thing: keep at most NBROKEN around
1035 if(broken.n == NBROKEN) {
1037 memmove(&broken.p[0], &broken.p[1], sizeof(Proc*)*(NBROKEN-1));
1040 broken.p[broken.n++] = p;
1055 for(b=0; b < broken.n; b++)
1056 if(broken.p[b] == p) {
1058 memmove(&broken.p[b], &broken.p[b+1],
1059 sizeof(Proc*)*(NBROKEN-(b+1)));
1073 for(i=0; i<n; i++) {
1083 pexit(char *exitstr, int freemem)
1094 void (*pt)(Proc*, int, vlong);
1103 /* nil out all the resources under lock (free later) */
1115 qunlock(&up->debug);
1129 * if not a kernel process and have a parent,
1130 * do some housekeeping.
1132 if(up->kp == 0 && up->parentpid != 0) {
1133 wq = smalloc(sizeof(Waitq));
1134 wq->w.pid = up->pid;
1135 utime = up->time[TUser] + up->time[TCUser];
1136 stime = up->time[TSys] + up->time[TCSys];
1137 wq->w.time[TUser] = tk2ms(utime);
1138 wq->w.time[TSys] = tk2ms(stime);
1139 wq->w.time[TReal] = tk2ms(MACHP(0)->ticks - up->time[TReal]);
1140 if(exitstr != nil && exitstr[0])
1141 snprint(wq->w.msg, sizeof(wq->w.msg), "%s %lud: %s", up->text, up->pid, exitstr);
1143 wq->w.msg[0] = '\0';
1148 * Check that parent is still alive.
1150 if(p->pid == up->parentpid && p->state != Broken) {
1152 p->time[TCUser] += utime;
1153 p->time[TCSys] += stime;
1155 * If there would be more than 128 wait records
1156 * processes for my parent, then don't leave a wait
1157 * record behind. This helps prevent badly written
1158 * daemon processes from accumulating lots of wait
1161 if(p->nwait < 128) {
1162 wq->next = p->waitq;
1173 else if(up->kp == 0 && up->parent == nil){
1175 exitstr = "unknown";
1176 panic("boot process died: %s", exitstr);
1182 qlock(&up->seglock);
1183 es = &up->seg[NSEG];
1184 for(s = up->seg; s < es; s++) {
1190 qunlock(&up->seglock);
1192 lock(&up->exl); /* Prevent my children from leaving waits */
1198 while((wq = up->waitq) != nil){
1199 up->waitq = wq->next;
1203 /* release debuggers */
1205 if(up->pdbg != nil) {
1206 wakeup(&up->pdbg->sleep);
1209 if(up->syscalltrace != nil) {
1210 free(up->syscalltrace);
1211 up->syscalltrace = nil;
1213 qunlock(&up->debug);
1215 /* Sched must not loop for these locks */
1220 up->state = Moribund;
1228 return ((Proc*)x)->waitq != nil;
1237 if(!canqlock(&up->qwaitr))
1241 qunlock(&up->qwaitr);
1246 while(up->waitq == nil) {
1247 if(up->nchild == 0) {
1252 sleep(&up->waitr, haswaitq, up);
1256 up->waitq = wq->next;
1260 qunlock(&up->qwaitr);
1264 memmove(w, &wq->w, sizeof(Waitmsg));
1273 return &procalloc.arena[i];
1286 if(p->seg[BSEG] != nil)
1287 bss = p->seg[BSEG]->top;
1291 s = statename[p->state];
1292 print("%3lud:%10s pc %#p dbgpc %#p %8s (%s) ut %ld st %ld bss %lux qpc %#p nl %d nd %lud lpc %#p pri %lud\n",
1293 p->pid, p->text, p->pc, dbgpc(p), s, statename[p->state],
1294 p->time[0], p->time[1], bss, p->qpc, p->nlocks, p->delaysched,
1295 p->lastlock ? p->lastlock->pc : 0, p->priority);
1305 print("up %lud\n", up->pid);
1307 print("no current process\n");
1308 for(i=0; i<conf.nproc; i++) {
1309 p = &procalloc.arena[i];
1310 if(p->state != Dead)
1316 * wait till all processes have flushed their mmu
1317 * state about segement s
1320 procflushseg(Segment *s)
1322 int i, ns, nm, nwait;
1326 * tell all processes with this
1327 * segment to flush their mmu's
1330 for(i=0; i<conf.nproc; i++) {
1331 p = &procalloc.arena[i];
1332 if(p->state == Dead)
1334 for(ns = 0; ns < NSEG; ns++)
1335 if(p->seg[ns] == s){
1337 for(nm = 0; nm < conf.nmach; nm++){
1338 if(MACHP(nm)->proc == p){
1339 MACHP(nm)->flushmmu = 1;
1351 * wait for all other processors to take a clock interrupt
1352 * and flush their mmu's
1354 for(nm = 0; nm < conf.nmach; nm++)
1355 while(m->machno != nm && MACHP(nm)->flushmmu)
1365 for(rq = &runq[Nrq-1]; rq >= runq; rq--){
1368 print("rq%ld:", rq-runq);
1369 for(p = rq->head; p != nil; p = p->rnext)
1370 print(" %lud(%lud)", p->pid, m->ticks - p->readytime);
1374 print("nrdy %d\n", nrdy);
1378 kproc(char *name, void (*func)(void *), void *arg)
1389 p->scallnr = up->scallnr;
1392 p->slash = up->slash;
1393 p->dot = up->slash; /* unlike fork, do not inherit the dot for kprocs */
1397 memmove(p->note, up->note, sizeof(p->note));
1398 p->nnote = up->nnote;
1400 p->lastnote = up->lastnote;
1401 p->notify = up->notify;
1405 procpriority(p, PriKproc, 0);
1407 kprocchild(p, func, arg);
1409 kstrdup(&p->user, eve);
1410 kstrdup(&p->text, name);
1416 memset(p->time, 0, sizeof(p->time));
1417 p->time[TReal] = MACHP(0)->ticks;
1422 * called splhi() by notify(). See comment in notify for the
1431 switch(up->procctl) {
1434 pprint("Killed: Insufficient physical memory\n");
1435 pexit("Killed: Insufficient physical memory", 1);
1438 spllo(); /* pexit has locks in it */
1448 state = up->psstate;
1449 up->psstate = "Stopped";
1450 /* free a waiting debugger */
1453 if(up->pdbg != nil) {
1454 wakeup(&up->pdbg->sleep);
1457 qunlock(&up->debug);
1459 up->state = Stopped;
1461 up->psstate = state;
1474 assert(up->nerrlab < NERR);
1475 kstrcpy(up->errstr, err, ERRMAX);
1476 setlabel(&up->errlab[NERR-1]);
1483 assert(up->nerrlab > 0);
1484 gotolabel(&up->errlab[--up->nerrlab]);
1488 exhausted(char *resource)
1492 snprint(buf, sizeof buf, "no free %s", resource);
1493 iprint("%s\n", buf);
1498 procpagecount(Proc *p)
1504 eqlock(&p->seglock);
1506 qunlock(&p->seglock);
1510 for(i=0; i<NSEG; i++){
1511 if((s = p->seg[i]) != nil){
1513 pages += mcountseg(s);
1517 qunlock(&p->seglock);
1533 ep = procalloc.arena+conf.nproc;
1534 for(p = procalloc.arena; p < ep; p++) {
1535 if(p->state == Dead || p->kp)
1537 if((p->noswap || (p->procmode & 0222) == 0) && strcmp(eve, p->user) == 0)
1539 l = procpagecount(p);
1547 print("%lud: %s killed: %s\n", kp->pid, kp->text, why);
1548 qlock(&kp->seglock);
1549 for(p = procalloc.arena; p < ep; p++) {
1550 if(p->state == Dead || p->kp)
1552 if(p != kp && p->seg[BSEG] != nil && p->seg[BSEG] == kp->seg[BSEG])
1553 p->procctl = Proc_exitbig;
1555 kp->procctl = Proc_exitbig;
1556 for(i = 0; i < NSEG; i++) {
1560 switch(s->type & SG_TYPE){
1567 mfreeseg(s, s->base, (s->top - s->base)/BY2PG);
1570 qunlock(&kp->seglock);
1574 * change ownership to 'new' of all processes owned by 'old'. Used when
1578 renameuser(char *old, char *new)
1582 ep = procalloc.arena+conf.nproc;
1583 for(p = procalloc.arena; p < ep; p++)
1584 if(p->user != nil && strcmp(old, p->user) == 0)
1585 kstrdup(&p->user, new);
1589 * time accounting called by clock() splhi'd
1601 p->time[p->insyscall]++;
1604 /* calculate decaying duty cycles */
1606 per = n - m->perf.last;
1608 per = ((uvlong)m->perf.period*(HZ-1) + per)/HZ;
1610 m->perf.period = per;
1612 m->perf.avg_inidle = ((uvlong)m->perf.avg_inidle*(HZ-1)+m->perf.inidle)/HZ;
1615 m->perf.avg_inintr = ((uvlong)m->perf.avg_inintr*(HZ-1)+m->perf.inintr)/HZ;
1618 /* only one processor gets to compute system load averages */
1623 * calculate decaying load average.
1624 * if we decay by (n-1)/n then it takes
1625 * n clock ticks to go from load L to .36 L once
1626 * things quiet down. it takes about 5 n clock
1627 * ticks to go to zero. so using HZ means this is
1628 * approximately the load over the last second,
1629 * with a tail lasting about 5 seconds.
1633 n = (nrdy+n)*1000*100;
1634 load = ((uvlong)load*(HZ-1)+n)/HZ;
1641 static int gen, wrapped;
1647 pid = ++gen & 0x7FFFFFFF;
1652 h = pid % nelem(procalloc.ht);
1654 for(x = procalloc.ht[h]; x != nil; x = x->pidhash)
1659 p->pidhash = procalloc.ht[h];
1660 procalloc.ht[h] = p;
1672 h = p->pid % nelem(procalloc.ht);
1674 for(l = &procalloc.ht[h]; *l != nil; l = &(*l)->pidhash)
1683 procindex(ulong pid)
1690 h = pid % nelem(procalloc.ht);
1692 for(p = procalloc.ht[h]; p != nil; p = p->pidhash)
1694 s = p - procalloc.arena;