]> git.lizzy.rs Git - plan9front.git/blob - sys/src/9/port/proc.c
kernel: fix livelock in rebalance (thanks Richard Miller)
[plan9front.git] / sys / src / 9 / port / proc.c
1 #include        <u.h>
2 #include        "../port/lib.h"
3 #include        "mem.h"
4 #include        "dat.h"
5 #include        "fns.h"
6 #include        "../port/error.h"
7 #include        "edf.h"
8 #include        <trace.h>
9
10 int     schedgain = 30; /* units in seconds */
11 int     nrdy;
12
13 void updatecpu(Proc*);
14 int reprioritize(Proc*);
15
16 ulong   delayedscheds;  /* statistics */
17 ulong   skipscheds;
18 ulong   preempts;
19 ulong   load;
20
21 static struct Procalloc
22 {
23         Lock;
24         Proc*   ht[128];
25         Proc*   arena;
26         Proc*   free;
27 } procalloc;
28
29 enum
30 {
31         Q=10,
32         DQ=4,
33         Scaling=2,
34 };
35
36 Schedq  runq[Nrq];
37 ulong   runvec;
38
39 char *statename[] =
40 {       /* BUG: generate automatically */
41         "Dead",
42         "Moribund",
43         "Ready",
44         "Scheding",
45         "Running",
46         "Queueing",
47         "QueueingR",
48         "QueueingW",
49         "Wakeme",
50         "Broken",
51         "Stopped",
52         "Rendez",
53         "Waitrelease",
54 };
55
56 static void pidfree(Proc*);
57 static void rebalance(void);
58
59 /*
60  * Always splhi()'ed.
61  */
62 void
63 schedinit(void)         /* never returns */
64 {
65         Edf *e;
66
67         setlabel(&m->sched);
68         if(up != nil) {
69                 if((e = up->edf) != nil && (e->flags & Admitted))
70                         edfrecord(up);
71                 m->proc = nil;
72                 switch(up->state) {
73                 case Running:
74                         ready(up);
75                         break;
76                 case Moribund:
77                         up->state = Dead;
78                         edfstop(up);
79                         if(up->edf != nil)
80                                 free(up->edf);
81                         up->edf = nil;
82
83                         /*
84                          * Holding locks from pexit:
85                          *      procalloc
86                          *      palloc
87                          */
88                         mmurelease(up);
89                         unlock(&palloc);
90
91                         up->mach = nil;
92                         updatecpu(up);
93
94                         up->qnext = procalloc.free;
95                         procalloc.free = up;
96
97                         /* proc is free now, make sure unlock() wont touch it */
98                         up = procalloc.Lock.p = nil;
99                         unlock(&procalloc);
100                         sched();
101                 }
102                 up->mach = nil;
103                 updatecpu(up);
104                 up = nil;
105         }
106         sched();
107 }
108
109 /*
110  *  If changing this routine, look also at sleep().  It
111  *  contains a copy of the guts of sched().
112  */
113 void
114 sched(void)
115 {
116         Proc *p;
117
118         if(m->ilockdepth)
119                 panic("cpu%d: ilockdepth %d, last lock %#p at %#p, sched called from %#p",
120                         m->machno,
121                         m->ilockdepth,
122                         up != nil ? up->lastilock: nil,
123                         (up != nil && up->lastilock != nil) ? up->lastilock->pc: 0,
124                         getcallerpc(&p+2));
125         if(up != nil) {
126                 /*
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.
135                  *
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.
139                  */
140                 if(up->nlocks)
141                 if(up->state != Moribund)
142                 if(up->delaysched < 20
143                 || palloc.Lock.p == up
144                 || fscache.Lock.p == up
145                 || procalloc.Lock.p == up){
146                         up->delaysched++;
147                         delayedscheds++;
148                         return;
149                 }
150                 up->delaysched = 0;
151
152                 splhi();
153
154                 /* statistics */
155                 m->cs++;
156
157                 procsave(up);
158                 if(setlabel(&up->sched)){
159                         procrestore(up);
160                         spllo();
161                         return;
162                 }
163                 gotolabel(&m->sched);
164         }
165         p = runproc();
166         if(p->edf == nil){
167                 updatecpu(p);
168                 p->priority = reprioritize(p);
169         }
170         if(p != m->readied)
171                 m->schedticks = m->ticks + HZ/10;
172         m->readied = nil;
173         up = p;
174         up->state = Running;
175         up->mach = MACHP(m->machno);
176         m->proc = up;
177         mmuswitch(up);
178         gotolabel(&up->sched);
179 }
180
181 int
182 anyready(void)
183 {
184         return runvec;
185 }
186
187 int
188 anyhigher(void)
189 {
190         return runvec & ~((1<<(up->priority+1))-1);
191 }
192
193 /*
194  *  here once per clock tick to see if we should resched
195  */
196 void
197 hzsched(void)
198 {
199         /* once a second, rebalance will reprioritize ready procs */
200         if(m->machno == 0)
201                 rebalance();
202
203         /* unless preempted, get to run for at least 100ms */
204         if(anyhigher()
205         || (!up->fixedpri && (long)(m->ticks - m->schedticks) > 0 && anyready())){
206                 m->readied = nil;       /* avoid cooperative scheduling */
207                 up->delaysched++;
208         }
209 }
210
211 /*
212  *  here at the end of non-clock interrupts to see if we should preempt the
213  *  current process.  Returns 1 if preempted, 0 otherwise.
214  */
215 int
216 preempted(void)
217 {
218         if(up != nil && up->state == Running)
219         if(up->preempted == 0)
220         if(anyhigher())
221         if(!active.exiting){
222                 m->readied = nil;       /* avoid cooperative scheduling */
223                 up->preempted = 1;
224                 sched();
225                 splhi();
226                 up->preempted = 0;
227                 return 1;
228         }
229         return 0;
230 }
231
232 /*
233  * Update the cpu time average for this particular process,
234  * which is about to change from up -> not up or vice versa.
235  * p->lastupdate is the last time an updatecpu happened.
236  *
237  * The cpu time average is a decaying average that lasts
238  * about D clock ticks.  D is chosen to be approximately
239  * the cpu time of a cpu-intensive "quick job".  A job has to run
240  * for approximately D clock ticks before we home in on its 
241  * actual cpu usage.  Thus if you manage to get in and get out
242  * quickly, you won't be penalized during your burst.  Once you
243  * start using your share of the cpu for more than about D
244  * clock ticks though, your p->cpu hits 1000 (1.0) and you end up 
245  * below all the other quick jobs.  Interactive tasks, because
246  * they basically always use less than their fair share of cpu,
247  * will be rewarded.
248  *
249  * If the process has not been running, then we want to
250  * apply the filter
251  *
252  *      cpu = cpu * (D-1)/D
253  *
254  * n times, yielding 
255  * 
256  *      cpu = cpu * ((D-1)/D)^n
257  *
258  * but D is big enough that this is approximately 
259  *
260  *      cpu = cpu * (D-n)/D
261  *
262  * so we use that instead.
263  * 
264  * If the process has been running, we apply the filter to
265  * 1 - cpu, yielding a similar equation.  Note that cpu is 
266  * stored in fixed point (* 1000).
267  *
268  * Updatecpu must be called before changing up, in order
269  * to maintain accurate cpu usage statistics.  It can be called
270  * at any time to bring the stats for a given proc up-to-date.
271  */
272 void
273 updatecpu(Proc *p)
274 {
275         ulong t, ocpu, n, D;
276
277         if(p->edf != nil)
278                 return;
279
280         t = MACHP(0)->ticks*Scaling + Scaling/2;
281         n = t - p->lastupdate;
282         if(n == 0)
283                 return;
284         p->lastupdate = t;
285
286         D = schedgain*HZ*Scaling;
287         if(n > D)
288                 n = D;
289
290         ocpu = p->cpu;
291         if(p != up)
292                 p->cpu = (ocpu*(D-n))/D;
293         else{
294                 t = 1000 - ocpu;
295                 t = (t*(D-n))/D;
296                 p->cpu = 1000 - t;
297         }
298 //iprint("pid %lud %s for %lud cpu %lud -> %lud\n", p->pid,p==up?"active":"inactive",n, ocpu,p->cpu);
299 }
300
301 /*
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.
309  */
310 int
311 reprioritize(Proc *p)
312 {
313         int fairshare, n, load, ratio;
314
315         load = MACHP(0)->load;
316         if(load == 0)
317                 return p->basepri;
318
319         /*
320          * fairshare = 1.000 * conf.nmach * 1.000/load,
321          * except the decimal point is moved three places
322          * on both load and fairshare.
323          */
324         fairshare = (conf.nmach*1000*1000)/load;
325         n = p->cpu;
326         if(n == 0)
327                 n = 1;
328         ratio = (fairshare+n/2) / n;
329         if(ratio > p->basepri)
330                 ratio = p->basepri;
331         if(ratio < 0)
332                 panic("reprioritize");
333 //iprint("pid %lud cpu %lud load %d fair %d pri %d\n", p->pid, p->cpu, load, fairshare, ratio);
334         return ratio;
335 }
336
337 /*
338  * add a process to a scheduling queue
339  */
340 void
341 queueproc(Schedq *rq, Proc *p)
342 {
343         int pri;
344
345         pri = rq - runq;
346         lock(runq);
347         p->priority = pri;
348         p->rnext = nil;
349         if(rq->tail != nil)
350                 rq->tail->rnext = p;
351         else
352                 rq->head = p;
353         rq->tail = p;
354         rq->n++;
355         nrdy++;
356         runvec |= 1<<pri;
357         unlock(runq);
358 }
359
360 /*
361  *  try to remove a process from a scheduling queue (called splhi)
362  */
363 Proc*
364 dequeueproc(Schedq *rq, Proc *tp)
365 {
366         Proc *l, *p;
367
368         if(!canlock(runq))
369                 return nil;
370
371         /*
372          *  the queue may have changed before we locked runq,
373          *  refind the target process.
374          */
375         l = nil;
376         for(p = rq->head; p != nil; p = p->rnext){
377                 if(p == tp)
378                         break;
379                 l = p;
380         }
381
382         /*
383          *  p->mach==0 only when process state is saved
384          */
385         if(p == nil || p->mach != nil){
386                 unlock(runq);
387                 return nil;
388         }
389         if(p->rnext == nil)
390                 rq->tail = l;
391         if(l != nil)
392                 l->rnext = p->rnext;
393         else
394                 rq->head = p->rnext;
395         if(rq->head == nil)
396                 runvec &= ~(1<<(rq-runq));
397         rq->n--;
398         nrdy--;
399         if(p->state != Ready)
400                 print("dequeueproc %s %lud %s\n", p->text, p->pid, statename[p->state]);
401
402         unlock(runq);
403         return p;
404 }
405
406 /*
407  *  ready(p) picks a new priority for a process and sticks it in the
408  *  runq for that priority.
409  */
410 void
411 ready(Proc *p)
412 {
413         int s, pri;
414         Schedq *rq;
415         void (*pt)(Proc*, int, vlong);
416
417         if(p->state == Ready){
418                 print("double ready %s %lud pc %p\n", p->text, p->pid, getcallerpc(&p));
419                 return;
420         }
421
422         s = splhi();
423         if(edfready(p)){
424                 splx(s);
425                 return;
426         }
427
428         if(up != p && (p->wired == nil || p->wired == MACHP(m->machno)))
429                 m->readied = p; /* group scheduling */
430
431         updatecpu(p);
432         pri = reprioritize(p);
433         p->priority = pri;
434         rq = &runq[pri];
435         p->state = Ready;
436         queueproc(rq, p);
437         pt = proctrace;
438         if(pt != nil)
439                 pt(p, SReady, 0);
440         splx(s);
441 }
442
443 /*
444  *  yield the processor and drop our priority
445  */
446 void
447 yield(void)
448 {
449         if(anyready()){
450                 /* pretend we just used 1/2 tick */
451                 up->lastupdate -= Scaling/2;  
452                 sched();
453         }
454 }
455
456 /*
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.
460  */
461 ulong balancetime;
462
463 static void
464 rebalance(void)
465 {
466         int pri, npri, x;
467         Schedq *rq;
468         Proc *p;
469         ulong t;
470
471         t = m->ticks;
472         if(t - balancetime < HZ)
473                 return;
474         balancetime = t;
475
476         for(pri=0, rq=runq; pri<Npriq; pri++, rq++){
477 another:
478                 p = rq->head;
479                 if(p == nil)
480                         continue;
481                 if(pri == p->basepri)
482                         continue;
483                 updatecpu(p);
484                 npri = reprioritize(p);
485                 if(npri != pri){
486                         x = splhi();
487                         p = dequeueproc(rq, p);
488                         if(p != nil)
489                                 queueproc(&runq[npri], p);
490                         splx(x);
491                         goto another;
492                 }
493         }
494 }
495         
496
497 /*
498  *  pick a process to run
499  */
500 Proc*
501 runproc(void)
502 {
503         Schedq *rq;
504         Proc *p;
505         ulong start, now;
506         int i;
507         void (*pt)(Proc*, int, vlong);
508
509         start = perfticks();
510
511         /* cooperative scheduling until the clock ticks */
512         if((p = m->readied) != nil && p->mach == nil && p->state == Ready
513         && (p->wired == nil || p->wired == MACHP(m->machno))
514         && runq[Nrq-1].head == nil && runq[Nrq-2].head == nil){
515                 skipscheds++;
516                 rq = &runq[p->priority];
517                 goto found;
518         }
519
520         preempts++;
521
522 loop:
523         /*
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.
527          */
528         spllo();
529         for(i = 0;; i++){
530                 /*
531                  *  find the highest priority target process that this
532                  *  processor can run given affinity constraints.
533                  *
534                  */
535                 for(rq = &runq[Nrq-1]; rq >= runq; rq--){
536                         for(p = rq->head; p != nil; p = p->rnext){
537                                 if(p->mp == nil || p->mp == MACHP(m->machno)
538                                 || (p->wired == nil && i > 0))
539                                         goto found;
540                         }
541                 }
542
543                 /* waste time or halt the CPU */
544                 idlehands();
545
546                 /* remember how much time we're here */
547                 now = perfticks();
548                 m->perf.inidle += now-start;
549                 start = now;
550         }
551
552 found:
553         splhi();
554         p = dequeueproc(rq, p);
555         if(p == nil)
556                 goto loop;
557
558         p->state = Scheding;
559         p->mp = MACHP(m->machno);
560
561         if(edflock(p)){
562                 edfrun(p, rq == &runq[PriEdf]); /* start deadline timer and do admin */
563                 edfunlock();
564         }
565         pt = proctrace;
566         if(pt != nil)
567                 pt(p, SRun, 0);
568         return p;
569 }
570
571 int
572 canpage(Proc *p)
573 {
574         int ok = 0;
575
576         splhi();
577         lock(runq);
578         /* Only reliable way to see if we are Running */
579         if(p->mach == nil) {
580                 p->newtlb = 1;
581                 ok = 1;
582         }
583         unlock(runq);
584         spllo();
585
586         return ok;
587 }
588
589 Proc*
590 newproc(void)
591 {
592         char msg[64];
593         Proc *p;
594
595         lock(&procalloc);
596         for(;;) {
597                 if((p = procalloc.free) != nil)
598                         break;
599
600                 snprint(msg, sizeof msg, "no procs; %s forking",
601                         up != nil ? up->text: "kernel");
602                 unlock(&procalloc);
603                 resrcwait(msg);
604                 lock(&procalloc);
605         }
606         procalloc.free = p->qnext;
607         unlock(&procalloc);
608
609         p->state = Scheding;
610         p->psstate = "New";
611         p->mach = nil;
612         p->eql = nil;
613         p->qnext = nil;
614         p->nchild = 0;
615         p->nwait = 0;
616         p->waitq = nil;
617         p->parent = nil;
618         p->pgrp = nil;
619         p->egrp = nil;
620         p->fgrp = nil;
621         p->rgrp = nil;
622         p->pdbg = nil;
623         p->fpstate = FPinit;
624         p->kp = 0;
625         p->procctl = 0;
626         p->syscalltrace = nil;  
627         p->notepending = 0;
628         p->ureg = nil;
629         p->privatemem = 0;
630         p->noswap = 0;
631         p->errstr = p->errbuf0;
632         p->syserrstr = p->errbuf1;
633         p->errbuf0[0] = '\0';
634         p->errbuf1[0] = '\0';
635         p->nlocks = 0;
636         p->delaysched = 0;
637         p->trace = 0;
638         kstrdup(&p->user, "*nouser");
639         kstrdup(&p->text, "*notext");
640         kstrdup(&p->args, "");
641         p->nargs = 0;
642         p->setargs = 0;
643         memset(p->seg, 0, sizeof p->seg);
644         p->parentpid = 0;
645         p->noteid = pidalloc(p);
646         if(p->kstack == nil)
647                 p->kstack = smalloc(KSTACK);
648
649         /* sched params */
650         p->mp = nil;
651         p->wired = nil;
652         procpriority(p, PriNormal, 0);
653         p->cpu = 0;
654         p->lastupdate = MACHP(0)->ticks*Scaling;
655         p->edf = nil;
656
657         return p;
658 }
659
660 /*
661  * wire this proc to a machine
662  */
663 void
664 procwired(Proc *p, int bm)
665 {
666         Proc *pp;
667         int i;
668         char nwired[MAXMACH];
669         Mach *wm;
670
671         if(bm < 0){
672                 /* pick a machine to wire to */
673                 memset(nwired, 0, sizeof(nwired));
674                 p->wired = nil;
675                 pp = proctab(0);
676                 for(i=0; i<conf.nproc; i++, pp++){
677                         wm = pp->wired;
678                         if(wm != nil && pp->pid)
679                                 nwired[wm->machno]++;
680                 }
681                 bm = 0;
682                 for(i=0; i<conf.nmach; i++)
683                         if(nwired[i] < nwired[bm])
684                                 bm = i;
685         } else {
686                 /* use the virtual machine requested */
687                 bm = bm % conf.nmach;
688         }
689
690         p->wired = MACHP(bm);
691         p->mp = p->wired;
692 }
693
694 void
695 procpriority(Proc *p, int pri, int fixed)
696 {
697         if(pri >= Npriq)
698                 pri = Npriq - 1;
699         else if(pri < 0)
700                 pri = 0;
701         p->basepri = pri;
702         p->priority = pri;
703         if(fixed){
704                 p->fixedpri = 1;
705         } else {
706                 p->fixedpri = 0;
707         }
708 }
709
710 void
711 procinit0(void)         /* bad planning - clashes with devproc.c */
712 {
713         Proc *p;
714         int i;
715
716         p = xalloc(conf.nproc*sizeof(Proc));
717         if(p == nil){
718                 xsummary();
719                 panic("cannot allocate %lud procs (%ludMB)", conf.nproc, conf.nproc*sizeof(Proc)/(1024*1024));
720         }
721         procalloc.arena = p;
722         procalloc.free = p;
723         for(i=0; i<conf.nproc-1; i++, p++)
724                 p->qnext = p+1;
725         p->qnext = nil;
726 }
727
728 /*
729  *  sleep if a condition is not true.  Another process will
730  *  awaken us after it sets the condition.  When we awaken
731  *  the condition may no longer be true.
732  *
733  *  we lock both the process and the rendezvous to keep r->p
734  *  and p->r synchronized.
735  */
736 void
737 sleep(Rendez *r, int (*f)(void*), void *arg)
738 {
739         int s;
740         void (*pt)(Proc*, int, vlong);
741
742         s = splhi();
743
744         if(up->nlocks)
745                 print("process %lud sleeps with %d locks held, last lock %#p locked at pc %#p, sleep called from %#p\n",
746                         up->pid, up->nlocks, up->lastlock, up->lastlock->pc, getcallerpc(&r));
747         lock(r);
748         lock(&up->rlock);
749         if(r->p != nil){
750                 print("double sleep called from %#p, %lud %lud\n", getcallerpc(&r), r->p->pid, up->pid);
751                 dumpstack();
752         }
753
754         /*
755          *  Wakeup only knows there may be something to do by testing
756          *  r->p in order to get something to lock on.
757          *  Flush that information out to memory in case the sleep is
758          *  committed.
759          */
760         r->p = up;
761
762         if((*f)(arg) || up->notepending){
763                 /*
764                  *  if condition happened or a note is pending
765                  *  never mind
766                  */
767                 r->p = nil;
768                 unlock(&up->rlock);
769                 unlock(r);
770         } else {
771                 /*
772                  *  now we are committed to
773                  *  change state and call scheduler
774                  */
775                 pt = proctrace;
776                 if(pt != nil)
777                         pt(up, SSleep, 0);
778                 up->state = Wakeme;
779                 up->r = r;
780
781                 /* statistics */
782                 m->cs++;
783
784                 procsave(up);
785                 if(setlabel(&up->sched)) {
786                         /*
787                          *  here when the process is awakened
788                          */
789                         procrestore(up);
790                         spllo();
791                 } else {
792                         /*
793                          *  here to go to sleep (i.e. stop Running)
794                          */
795                         unlock(&up->rlock);
796                         unlock(r);
797                         gotolabel(&m->sched);
798                 }
799         }
800
801         if(up->notepending) {
802                 up->notepending = 0;
803                 splx(s);
804                 interrupted();
805         }
806
807         splx(s);
808 }
809
810 void
811 interrupted(void)
812 {
813         if(up->procctl == Proc_exitme && up->closingfgrp != nil)
814                 forceclosefgrp();
815         error(Eintr);
816 }
817
818 static int
819 tfn(void *arg)
820 {
821         return up->trend == nil || up->tfn(arg);
822 }
823
824 void
825 twakeup(Ureg*, Timer *t)
826 {
827         Proc *p;
828         Rendez *trend;
829
830         p = t->ta;
831         trend = p->trend;
832         if(trend != nil){
833                 p->trend = nil;
834                 wakeup(trend);
835         }
836 }
837
838 void
839 tsleep(Rendez *r, int (*fn)(void*), void *arg, ulong ms)
840 {
841         if(up->tt != nil){
842                 print("%s %lud: tsleep timer active: mode %d, tf %#p, pc %#p\n",
843                         up->text, up->pid, up->tmode, up->tf, getcallerpc(&r));
844                 timerdel(up);
845         }
846         up->tns = MS2NS(ms);
847         up->tf = twakeup;
848         up->tmode = Trelative;
849         up->ta = up;
850         up->trend = r;
851         up->tfn = fn;
852         timeradd(up);
853
854         if(waserror()){
855                 up->trend = nil;
856                 timerdel(up);
857                 nexterror();
858         }
859         sleep(r, tfn, arg);
860         up->trend = nil;
861         timerdel(up);
862         poperror();
863 }
864
865 /*
866  *  Expects that only one process can call wakeup for any given Rendez.
867  *  We hold both locks to ensure that r->p and p->r remain consistent.
868  *  Richard Miller has a better solution that doesn't require both to
869  *  be held simultaneously, but I'm a paranoid - presotto.
870  */
871 Proc*
872 wakeup(Rendez *r)
873 {
874         Proc *p;
875         int s;
876
877         s = splhi();
878
879         lock(r);
880         p = r->p;
881
882         if(p != nil){
883                 lock(&p->rlock);
884                 if(p->state != Wakeme || p->r != r){
885                         iprint("%p %p %d\n", p->r, r, p->state);
886                         panic("wakeup: state");
887                 }
888                 r->p = nil;
889                 p->r = nil;
890                 ready(p);
891                 unlock(&p->rlock);
892         }
893         unlock(r);
894
895         splx(s);
896
897         return p;
898 }
899
900 /*
901  *  if waking a sleeping process, this routine must hold both
902  *  p->rlock and r->lock.  However, it can't know them in
903  *  the same order as wakeup causing a possible lock ordering
904  *  deadlock.  We break the deadlock by giving up the p->rlock
905  *  lock if we can't get the r->lock and retrying.
906  */
907 int
908 postnote(Proc *p, int dolock, char *n, int flag)
909 {
910         int s, ret;
911         QLock *q;
912
913         if(p == nil)
914                 return 0;
915
916         if(dolock)
917                 qlock(&p->debug);
918
919         if(p->pid == 0){
920                 if(dolock)
921                         qunlock(&p->debug);
922                 return 0;
923         }
924
925         if(n != nil && flag != NUser && (p->notify == 0 || p->notified))
926                 p->nnote = 0;
927
928         ret = 0;
929         if(p->nnote < NNOTE && n != nil) {
930                 kstrcpy(p->note[p->nnote].msg, n, ERRMAX);
931                 p->note[p->nnote++].flag = flag;
932                 ret = 1;
933         }
934         p->notepending = 1;
935         if(dolock)
936                 qunlock(&p->debug);
937
938         /* this loop is to avoid lock ordering problems. */
939         for(;;){
940                 Rendez *r;
941
942                 s = splhi();
943                 lock(&p->rlock);
944                 r = p->r;
945
946                 /* waiting for a wakeup? */
947                 if(r == nil)
948                         break;  /* no */
949
950                 /* try for the second lock */
951                 if(canlock(r)){
952                         if(p->state != Wakeme || r->p != p)
953                                 panic("postnote: state %d %d %d", r->p != p, p->r != r, p->state);
954                         p->r = nil;
955                         r->p = nil;
956                         ready(p);
957                         unlock(r);
958                         break;
959                 }
960
961                 /* give other process time to get out of critical section and try again */
962                 unlock(&p->rlock);
963                 splx(s);
964                 sched();
965         }
966         unlock(&p->rlock);
967         splx(s);
968
969         switch(p->state){
970         case Queueing:
971                 /* Try and pull out of a eqlock */
972                 if((q = p->eql) != nil){
973                         lock(&q->use);
974                         if(p->state == Queueing && p->eql == q){
975                                 Proc *d, *l;
976
977                                 for(l = nil, d = q->head; d != nil; l = d, d = d->qnext){
978                                         if(d == p){
979                                                 if(l != nil)
980                                                         l->qnext = p->qnext;
981                                                 else
982                                                         q->head = p->qnext;
983                                                 if(p->qnext == nil)
984                                                         q->tail = l;
985                                                 p->qnext = nil;
986                                                 p->eql = nil;   /* not taken */
987                                                 ready(p);
988                                                 break;
989                                         }
990                                 }
991                         }
992                         unlock(&q->use);
993                 }
994                 break;
995         case Rendezvous:
996                 /* Try and pull out of a rendezvous */
997                 lock(p->rgrp);
998                 if(p->state == Rendezvous) {
999                         Proc *d, **l;
1000
1001                         l = &REND(p->rgrp, p->rendtag);
1002                         for(d = *l; d != nil; d = d->rendhash) {
1003                                 if(d == p) {
1004                                         *l = p->rendhash;
1005                                         p->rendval = ~0;
1006                                         ready(p);
1007                                         break;
1008                                 }
1009                                 l = &d->rendhash;
1010                         }
1011                 }
1012                 unlock(p->rgrp);
1013                 break;
1014         }
1015         return ret;
1016 }
1017
1018 /*
1019  * weird thing: keep at most NBROKEN around
1020  */
1021 #define NBROKEN 4
1022 struct
1023 {
1024         QLock;
1025         int     n;
1026         Proc    *p[NBROKEN];
1027 }broken;
1028
1029 void
1030 addbroken(Proc *p)
1031 {
1032         qlock(&broken);
1033         if(broken.n == NBROKEN) {
1034                 ready(broken.p[0]);
1035                 memmove(&broken.p[0], &broken.p[1], sizeof(Proc*)*(NBROKEN-1));
1036                 --broken.n;
1037         }
1038         broken.p[broken.n++] = p;
1039         qunlock(&broken);
1040
1041         edfstop(up);
1042         p->state = Broken;
1043         p->psstate = nil;
1044         sched();
1045 }
1046
1047 void
1048 unbreak(Proc *p)
1049 {
1050         int b;
1051
1052         qlock(&broken);
1053         for(b=0; b < broken.n; b++)
1054                 if(broken.p[b] == p) {
1055                         broken.n--;
1056                         memmove(&broken.p[b], &broken.p[b+1],
1057                                         sizeof(Proc*)*(NBROKEN-(b+1)));
1058                         ready(p);
1059                         break;
1060                 }
1061         qunlock(&broken);
1062 }
1063
1064 int
1065 freebroken(void)
1066 {
1067         int i, n;
1068
1069         qlock(&broken);
1070         n = broken.n;
1071         for(i=0; i<n; i++) {
1072                 ready(broken.p[i]);
1073                 broken.p[i] = nil;
1074         }
1075         broken.n = 0;
1076         qunlock(&broken);
1077         return n;
1078 }
1079
1080 void
1081 pexit(char *exitstr, int freemem)
1082 {
1083         Proc *p;
1084         Segment **s, **es;
1085         ulong utime, stime;
1086         Waitq *wq;
1087         Fgrp *fgrp;
1088         Egrp *egrp;
1089         Rgrp *rgrp;
1090         Pgrp *pgrp;
1091         Chan *dot;
1092         void (*pt)(Proc*, int, vlong);
1093
1094         up->alarm = 0;
1095         timerdel(up);
1096         pt = proctrace;
1097         if(pt != nil)
1098                 pt(up, SDead, 0);
1099
1100         /* nil out all the resources under lock (free later) */
1101         qlock(&up->debug);
1102         fgrp = up->fgrp;
1103         up->fgrp = nil;
1104         egrp = up->egrp;
1105         up->egrp = nil;
1106         rgrp = up->rgrp;
1107         up->rgrp = nil;
1108         pgrp = up->pgrp;
1109         up->pgrp = nil;
1110         dot = up->dot;
1111         up->dot = nil;
1112         qunlock(&up->debug);
1113
1114         if(fgrp != nil)
1115                 closefgrp(fgrp);
1116         if(egrp != nil)
1117                 closeegrp(egrp);
1118         if(rgrp != nil)
1119                 closergrp(rgrp);
1120         if(dot != nil)
1121                 cclose(dot);
1122         if(pgrp != nil)
1123                 closepgrp(pgrp);
1124
1125         /*
1126          * if not a kernel process and have a parent,
1127          * do some housekeeping.
1128          */
1129         if(up->kp == 0 && up->parentpid != 0) {
1130                 wq = smalloc(sizeof(Waitq));
1131                 wq->w.pid = up->pid;
1132                 utime = up->time[TUser] + up->time[TCUser];
1133                 stime = up->time[TSys] + up->time[TCSys];
1134                 wq->w.time[TUser] = tk2ms(utime);
1135                 wq->w.time[TSys] = tk2ms(stime);
1136                 wq->w.time[TReal] = tk2ms(MACHP(0)->ticks - up->time[TReal]);
1137                 if(exitstr != nil && exitstr[0])
1138                         snprint(wq->w.msg, sizeof(wq->w.msg), "%s %lud: %s", up->text, up->pid, exitstr);
1139                 else
1140                         wq->w.msg[0] = '\0';
1141
1142                 p = up->parent;
1143                 lock(&p->exl);
1144                 /*
1145                  * Check that parent is still alive.
1146                  */
1147                 if(p->pid == up->parentpid && p->state != Broken) {
1148                         p->nchild--;
1149                         p->time[TCUser] += utime;
1150                         p->time[TCSys] += stime;
1151                         /*
1152                          * If there would be more than 128 wait records
1153                          * processes for my parent, then don't leave a wait
1154                          * record behind.  This helps prevent badly written
1155                          * daemon processes from accumulating lots of wait
1156                          * records.
1157                          */
1158                         if(p->nwait < 128) {
1159                                 wq->next = p->waitq;
1160                                 p->waitq = wq;
1161                                 p->nwait++;
1162                                 wq = nil;
1163                                 wakeup(&p->waitr);
1164                         }
1165                 }
1166                 unlock(&p->exl);
1167                 if(wq != nil)
1168                         free(wq);
1169         }
1170         else if(up->kp == 0 && up->parent == nil){
1171                 if(exitstr == nil)
1172                         exitstr = "unknown";
1173                 panic("boot process died: %s", exitstr);
1174         }
1175
1176         if(!freemem)
1177                 addbroken(up);
1178
1179         qlock(&up->seglock);
1180         es = &up->seg[NSEG];
1181         for(s = up->seg; s < es; s++) {
1182                 if(*s != nil) {
1183                         putseg(*s);
1184                         *s = nil;
1185                 }
1186         }
1187         qunlock(&up->seglock);
1188
1189         lock(&up->exl);         /* Prevent my children from leaving waits */
1190         pidfree(up);
1191         up->pid = 0;
1192         wakeup(&up->waitr);
1193         unlock(&up->exl);
1194
1195         while((wq = up->waitq) != nil){
1196                 up->waitq = wq->next;
1197                 free(wq);
1198         }
1199
1200         /* release debuggers */
1201         qlock(&up->debug);
1202         if(up->pdbg != nil) {
1203                 wakeup(&up->pdbg->sleep);
1204                 up->pdbg = nil;
1205         }
1206         if(up->syscalltrace != nil) {
1207                 free(up->syscalltrace);
1208                 up->syscalltrace = nil;
1209         }
1210         if(up->watchpt != nil){
1211                 free(up->watchpt);
1212                 up->watchpt = nil;
1213         }
1214         up->nwatchpt = 0;
1215         qunlock(&up->debug);
1216
1217         /* Sched must not loop for these locks */
1218         lock(&procalloc);
1219         lock(&palloc);
1220
1221         edfstop(up);
1222         up->state = Moribund;
1223         sched();
1224         panic("pexit");
1225 }
1226
1227 static int
1228 haswaitq(void *x)
1229 {
1230         return ((Proc*)x)->waitq != nil;
1231 }
1232
1233 ulong
1234 pwait(Waitmsg *w)
1235 {
1236         ulong cpid;
1237         Waitq *wq;
1238
1239         if(!canqlock(&up->qwaitr))
1240                 error(Einuse);
1241
1242         if(waserror()) {
1243                 qunlock(&up->qwaitr);
1244                 nexterror();
1245         }
1246
1247         lock(&up->exl);
1248         while(up->waitq == nil) {
1249                 if(up->nchild == 0) {
1250                         unlock(&up->exl);
1251                         error(Enochild);
1252                 }
1253                 unlock(&up->exl);
1254                 sleep(&up->waitr, haswaitq, up);
1255                 lock(&up->exl);
1256         }
1257         wq = up->waitq;
1258         up->waitq = wq->next;
1259         up->nwait--;
1260         unlock(&up->exl);
1261
1262         qunlock(&up->qwaitr);
1263         poperror();
1264
1265         if(w != nil)
1266                 memmove(w, &wq->w, sizeof(Waitmsg));
1267         cpid = wq->w.pid;
1268         free(wq);
1269         return cpid;
1270 }
1271
1272 Proc*
1273 proctab(int i)
1274 {
1275         return &procalloc.arena[i];
1276 }
1277
1278 void
1279 dumpaproc(Proc *p)
1280 {
1281         ulong bss;
1282         char *s;
1283
1284         if(p == nil)
1285                 return;
1286
1287         bss = 0;
1288         if(p->seg[BSEG] != nil)
1289                 bss = p->seg[BSEG]->top;
1290
1291         s = p->psstate;
1292         if(s == nil)
1293                 s = statename[p->state];
1294         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",
1295                 p->pid, p->text, p->pc, dbgpc(p),  s, statename[p->state],
1296                 p->time[0], p->time[1], bss, p->qpc, p->nlocks, p->delaysched,
1297                 p->lastlock ? p->lastlock->pc : 0, p->priority);
1298 }
1299
1300 void
1301 procdump(void)
1302 {
1303         int i;
1304         Proc *p;
1305
1306         if(up != nil)
1307                 print("up %lud\n", up->pid);
1308         else
1309                 print("no current process\n");
1310         for(i=0; i<conf.nproc; i++) {
1311                 p = &procalloc.arena[i];
1312                 if(p->state != Dead)
1313                         dumpaproc(p);
1314         }
1315 }
1316
1317 /*
1318  *  wait till all matching processes have flushed their mmu
1319  */
1320 static void
1321 procflushmmu(int (*match)(Proc*, void*), void *a)
1322 {
1323         int i, nm, nwait;
1324         Proc *p;
1325
1326         /*
1327          *  tell all matching processes to flush their mmu's
1328          */
1329         nwait = 0;
1330         for(i=0; i<conf.nproc; i++) {
1331                 p = &procalloc.arena[i];
1332                 if(p->state != Dead && (*match)(p, a)){
1333                         p->newtlb = 1;
1334                         for(nm = 0; nm < conf.nmach; nm++){
1335                                 if(MACHP(nm)->proc == p){
1336                                         MACHP(nm)->flushmmu = 1;
1337                                         nwait++;
1338                                 }
1339                         }
1340                 }
1341         }
1342
1343         if(nwait == 0)
1344                 return;
1345
1346         /*
1347          *  wait for all other processors to take a clock interrupt
1348          *  and flush their mmu's
1349          */
1350         for(nm = 0; nm < conf.nmach; nm++)
1351                 while(m->machno != nm && MACHP(nm)->flushmmu)
1352                         sched();
1353 }
1354
1355 static int
1356 matchseg(Proc *p, void *a)
1357 {
1358         int ns;
1359
1360         for(ns = 0; ns < NSEG; ns++){
1361                 if(p->seg[ns] == a)
1362                         return 1;
1363         }
1364         return 0;
1365 }
1366 void
1367 procflushseg(Segment *s)
1368 {
1369         procflushmmu(matchseg, s);
1370 }
1371
1372 static int
1373 matchpseg(Proc *p, void *a)
1374 {
1375         Segment *s;
1376         int ns;
1377
1378         for(ns = 0; ns < NSEG; ns++){
1379                 s = p->seg[ns];
1380                 if(s != nil && s->pseg == a)
1381                         return 1;
1382         }
1383         return 0;
1384 }
1385 void
1386 procflushpseg(Physseg *ps)
1387 {
1388         procflushmmu(matchpseg, ps);
1389 }
1390
1391 void
1392 scheddump(void)
1393 {
1394         Proc *p;
1395         Schedq *rq;
1396
1397         for(rq = &runq[Nrq-1]; rq >= runq; rq--){
1398                 if(rq->head == nil)
1399                         continue;
1400                 print("rq%zd:", rq-runq);
1401                 for(p = rq->head; p != nil; p = p->rnext)
1402                         print(" %lud(%lud)", p->pid, m->ticks - p->readytime);
1403                 print("\n");
1404                 delay(150);
1405         }
1406         print("nrdy %d\n", nrdy);
1407 }
1408
1409 void
1410 kproc(char *name, void (*func)(void *), void *arg)
1411 {
1412         Proc *p;
1413         static Pgrp *kpgrp;
1414
1415         p = newproc();
1416         p->psstate = nil;
1417         p->procmode = 0640;
1418         p->kp = 1;
1419         p->noswap = 1;
1420
1421         p->scallnr = up->scallnr;
1422         p->s = up->s;
1423         p->nerrlab = 0;
1424         p->slash = up->slash;
1425         p->dot = up->slash;     /* unlike fork, do not inherit the dot for kprocs */
1426         if(p->dot != nil)
1427                 incref(p->dot);
1428
1429         memmove(p->note, up->note, sizeof(p->note));
1430         p->nnote = up->nnote;
1431         p->notified = 0;
1432         p->lastnote = up->lastnote;
1433         p->notify = up->notify;
1434         p->ureg = nil;
1435         p->dbgreg = nil;
1436
1437         procpriority(p, PriKproc, 0);
1438
1439         kprocchild(p, func, arg);
1440
1441         kstrdup(&p->user, eve);
1442         kstrdup(&p->text, name);
1443         if(kpgrp == nil)
1444                 kpgrp = newpgrp();
1445         p->pgrp = kpgrp;
1446         incref(kpgrp);
1447
1448         memset(p->time, 0, sizeof(p->time));
1449         p->time[TReal] = MACHP(0)->ticks;
1450         ready(p);
1451 }
1452
1453 /*
1454  *  called splhi() by notify().  See comment in notify for the
1455  *  reasoning.
1456  */
1457 void
1458 procctl(void)
1459 {
1460         char *state;
1461         ulong s;
1462
1463         switch(up->procctl) {
1464         case Proc_exitbig:
1465                 spllo();
1466                 pprint("Killed: Insufficient physical memory\n");
1467                 pexit("Killed: Insufficient physical memory", 1);
1468
1469         case Proc_exitme:
1470                 spllo();                /* pexit has locks in it */
1471                 pexit("Killed", 1);
1472
1473         case Proc_traceme:
1474                 if(up->nnote == 0)
1475                         return;
1476                 /* No break */
1477
1478         case Proc_stopme:
1479                 up->procctl = 0;
1480                 state = up->psstate;
1481                 up->psstate = "Stopped";
1482                 /* free a waiting debugger */
1483                 s = spllo();
1484                 qlock(&up->debug);
1485                 if(up->pdbg != nil) {
1486                         wakeup(&up->pdbg->sleep);
1487                         up->pdbg = nil;
1488                 }
1489                 qunlock(&up->debug);
1490                 splhi();
1491                 up->state = Stopped;
1492                 sched();
1493                 up->psstate = state;
1494                 splx(s);
1495                 return;
1496         }
1497 }
1498
1499 #include "errstr.h"
1500
1501 void
1502 error(char *err)
1503 {
1504         spllo();
1505
1506         assert(up->nerrlab < NERR);
1507         kstrcpy(up->errstr, err, ERRMAX);
1508         setlabel(&up->errlab[NERR-1]);
1509         nexterror();
1510 }
1511
1512 void
1513 nexterror(void)
1514 {
1515         assert(up->nerrlab > 0);
1516         gotolabel(&up->errlab[--up->nerrlab]);
1517 }
1518
1519 void
1520 exhausted(char *resource)
1521 {
1522         char buf[ERRMAX];
1523
1524         snprint(buf, sizeof buf, "no free %s", resource);
1525         iprint("%s\n", buf);
1526         error(buf);
1527 }
1528
1529 ulong
1530 procpagecount(Proc *p)
1531 {
1532         Segment *s;
1533         ulong pages;
1534         int i;
1535
1536         eqlock(&p->seglock);
1537         if(waserror()){
1538                 qunlock(&p->seglock);
1539                 nexterror();
1540         }
1541         pages = 0;
1542         for(i=0; i<NSEG; i++){
1543                 if((s = p->seg[i]) != nil){
1544                         eqlock(s);
1545                         pages += mcountseg(s);
1546                         qunlock(s);
1547                 }
1548         }
1549         qunlock(&p->seglock);
1550         poperror();
1551
1552         return pages;
1553 }
1554
1555 void
1556 killbig(char *why)
1557 {
1558         int i;
1559         Segment *s;
1560         ulong l, max;
1561         Proc *p, *ep, *kp;
1562
1563         max = 0;
1564         kp = nil;
1565         ep = procalloc.arena+conf.nproc;
1566         for(p = procalloc.arena; p < ep; p++) {
1567                 if(p->state == Dead || p->kp)
1568                         continue;
1569                 if((p->noswap || (p->procmode & 0222) == 0) && strcmp(eve, p->user) == 0)
1570                         continue;
1571                 l = procpagecount(p);
1572                 if(l > max){
1573                         kp = p;
1574                         max = l;
1575                 }
1576         }
1577         if(kp == nil)
1578                 return;
1579         print("%lud: %s killed: %s\n", kp->pid, kp->text, why);
1580         qlock(&kp->seglock);
1581         for(p = procalloc.arena; p < ep; p++) {
1582                 if(p->state == Dead || p->kp)
1583                         continue;
1584                 if(p != kp && p->seg[BSEG] != nil && p->seg[BSEG] == kp->seg[BSEG])
1585                         p->procctl = Proc_exitbig;
1586         }
1587         kp->procctl = Proc_exitbig;
1588         for(i = 0; i < NSEG; i++) {
1589                 s = kp->seg[i];
1590                 if(s == nil)
1591                         continue;
1592                 switch(s->type & SG_TYPE){
1593                 case SG_SHARED:
1594                 case SG_PHYSICAL:
1595                 case SG_FIXED:
1596                 case SG_STICKY:
1597                         continue;
1598                 }
1599                 qlock(s);
1600                 mfreeseg(s, s->base, (s->top - s->base)/BY2PG);
1601                 qunlock(s);
1602         }
1603         qunlock(&kp->seglock);
1604 }
1605
1606 /*
1607  *  change ownership to 'new' of all processes owned by 'old'.  Used when
1608  *  eve changes.
1609  */
1610 void
1611 renameuser(char *old, char *new)
1612 {
1613         Proc *p, *ep;
1614
1615         ep = procalloc.arena+conf.nproc;
1616         for(p = procalloc.arena; p < ep; p++)
1617                 if(p->user != nil && strcmp(old, p->user) == 0)
1618                         kstrdup(&p->user, new);
1619 }
1620
1621 /*
1622  *  time accounting called by clock() splhi'd
1623  */
1624 void
1625 accounttime(void)
1626 {
1627         Proc *p;
1628         ulong n, per;
1629         static ulong nrun;
1630
1631         p = m->proc;
1632         if(p != nil) {
1633                 nrun++;
1634                 p->time[p->insyscall]++;
1635         }
1636
1637         /* calculate decaying duty cycles */
1638         n = perfticks();
1639         per = n - m->perf.last;
1640         m->perf.last = n;
1641         per = ((uvlong)m->perf.period*(HZ-1) + per)/HZ;
1642         if(per != 0)
1643                 m->perf.period = per;
1644
1645         m->perf.avg_inidle = ((uvlong)m->perf.avg_inidle*(HZ-1)+m->perf.inidle)/HZ;
1646         m->perf.inidle = 0;
1647
1648         m->perf.avg_inintr = ((uvlong)m->perf.avg_inintr*(HZ-1)+m->perf.inintr)/HZ;
1649         m->perf.inintr = 0;
1650
1651         /* only one processor gets to compute system load averages */
1652         if(m->machno != 0)
1653                 return;
1654
1655         /*
1656          * calculate decaying load average.
1657          * if we decay by (n-1)/n then it takes
1658          * n clock ticks to go from load L to .36 L once
1659          * things quiet down.  it takes about 5 n clock
1660          * ticks to go to zero.  so using HZ means this is
1661          * approximately the load over the last second,
1662          * with a tail lasting about 5 seconds.
1663          */
1664         n = nrun;
1665         nrun = 0;
1666         n = (nrdy+n)*1000*100;
1667         load = ((uvlong)load*(HZ-1)+n)/HZ;
1668         m->load = load/100;
1669 }
1670
1671 int
1672 pidalloc(Proc *p)
1673 {
1674         static int gen, wrapped;
1675         int pid, h;
1676         Proc *x;
1677
1678         lock(&procalloc);
1679 Retry:
1680         pid = ++gen & 0x7FFFFFFF;
1681         if(pid == 0){
1682                 wrapped = 1;
1683                 goto Retry;
1684         }
1685         h = pid % nelem(procalloc.ht);
1686         if(wrapped)
1687                 for(x = procalloc.ht[h]; x != nil; x = x->pidhash)
1688                         if(x->pid == pid)
1689                                 goto Retry;
1690         if(p != nil){
1691                 p->pid = pid;
1692                 p->pidhash = procalloc.ht[h];
1693                 procalloc.ht[h] = p;
1694         }
1695         unlock(&procalloc);
1696         return pid;
1697 }
1698
1699 static void
1700 pidfree(Proc *p)
1701 {
1702         int h;
1703         Proc **l;
1704
1705         h = p->pid % nelem(procalloc.ht);
1706         lock(&procalloc);
1707         for(l = &procalloc.ht[h]; *l != nil; l = &(*l)->pidhash)
1708                 if(*l == p){
1709                         *l = p->pidhash;
1710                         break;
1711                 }
1712         unlock(&procalloc);
1713 }
1714
1715 int
1716 procindex(ulong pid)
1717 {
1718         Proc *p;
1719         int h;
1720         int s;
1721
1722         s = -1;
1723         h = pid % nelem(procalloc.ht);
1724         lock(&procalloc);
1725         for(p = procalloc.ht[h]; p != nil; p = p->pidhash)
1726                 if(p->pid == pid){
1727                         s = p - procalloc.arena;
1728                         break;
1729                 }
1730         unlock(&procalloc);
1731         return s;
1732 }