]> git.lizzy.rs Git - plan9front.git/blob - sys/src/9/port/proc.c
kernel: make noswap flag exclude processes from killbig() if not eve, reset noswap...
[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 long skipscheds;
18 long 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                 || procalloc.Lock.p == up){
145                         up->delaysched++;
146                         delayedscheds++;
147                         return;
148                 }
149                 up->delaysched = 0;
150
151                 splhi();
152
153                 /* statistics */
154                 m->cs++;
155
156                 procsave(up);
157                 if(setlabel(&up->sched)){
158                         procrestore(up);
159                         spllo();
160                         return;
161                 }
162                 gotolabel(&m->sched);
163         }
164         p = runproc();
165         if(p->edf == nil){
166                 updatecpu(p);
167                 p->priority = reprioritize(p);
168         }
169         if(p != m->readied)
170                 m->schedticks = m->ticks + HZ/10;
171         m->readied = nil;
172         up = p;
173         up->state = Running;
174         up->mach = MACHP(m->machno);
175         m->proc = up;
176         mmuswitch(up);
177         gotolabel(&up->sched);
178 }
179
180 int
181 anyready(void)
182 {
183         return runvec;
184 }
185
186 int
187 anyhigher(void)
188 {
189         return runvec & ~((1<<(up->priority+1))-1);
190 }
191
192 /*
193  *  here once per clock tick to see if we should resched
194  */
195 void
196 hzsched(void)
197 {
198         /* once a second, rebalance will reprioritize ready procs */
199         if(m->machno == 0)
200                 rebalance();
201
202         /* unless preempted, get to run for at least 100ms */
203         if(anyhigher()
204         || (!up->fixedpri && m->ticks > m->schedticks && anyready())){
205                 m->readied = nil;       /* avoid cooperative scheduling */
206                 up->delaysched++;
207         }
208 }
209
210 /*
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.
213  */
214 int
215 preempted(void)
216 {
217         if(up != nil && up->state == Running)
218         if(up->preempted == 0)
219         if(anyhigher())
220         if(!active.exiting){
221                 m->readied = nil;       /* avoid cooperative scheduling */
222                 up->preempted = 1;
223                 sched();
224                 splhi();
225                 up->preempted = 0;
226                 return 1;
227         }
228         return 0;
229 }
230
231 /*
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.
235  *
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,
246  * will be rewarded.
247  *
248  * If the process has not been running, then we want to
249  * apply the filter
250  *
251  *      cpu = cpu * (D-1)/D
252  *
253  * n times, yielding 
254  * 
255  *      cpu = cpu * ((D-1)/D)^n
256  *
257  * but D is big enough that this is approximately 
258  *
259  *      cpu = cpu * (D-n)/D
260  *
261  * so we use that instead.
262  * 
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).
266  *
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.
270  */
271 void
272 updatecpu(Proc *p)
273 {
274         int n, t, ocpu;
275         int D = schedgain*HZ*Scaling;
276
277         if(p->edf != nil)
278                 return;
279
280         t = MACHP(0)->ticks*Scaling + Scaling/2;
281         n = t - p->lastupdate;
282         p->lastupdate = t;
283
284         if(n == 0)
285                 return;
286         if(n > D)
287                 n = D;
288
289         ocpu = p->cpu;
290         if(p != up)
291                 p->cpu = (ocpu*(D-n))/D;
292         else{
293                 t = 1000 - ocpu;
294                 t = (t*(D-n))/D;
295                 p->cpu = 1000 - t;
296         }
297
298 //iprint("pid %d %s for %d cpu %d -> %d\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 %d cpu %d 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, t, x;
467         Schedq *rq;
468         Proc *p;
469
470         t = m->ticks;
471         if(t - balancetime < HZ)
472                 return;
473         balancetime = t;
474
475         for(pri=0, rq=runq; pri<Npriq; pri++, rq++){
476 another:
477                 p = rq->head;
478                 if(p == nil)
479                         continue;
480                 if(p->mp != MACHP(m->machno))
481                         continue;
482                 if(pri == p->basepri)
483                         continue;
484                 updatecpu(p);
485                 npri = reprioritize(p);
486                 if(npri != pri){
487                         x = splhi();
488                         p = dequeueproc(rq, p);
489                         if(p != nil)
490                                 queueproc(&runq[npri], p);
491                         splx(x);
492                         goto another;
493                 }
494         }
495 }
496         
497
498 /*
499  *  pick a process to run
500  */
501 Proc*
502 runproc(void)
503 {
504         Schedq *rq;
505         Proc *p;
506         ulong start, now;
507         int i;
508         void (*pt)(Proc*, int, vlong);
509
510         start = perfticks();
511
512         /* cooperative scheduling until the clock ticks */
513         if((p = m->readied) != nil && p->mach == nil && p->state == Ready
514         && (p->wired == nil || p->wired == MACHP(m->machno))
515         && runq[Nrq-1].head == nil && runq[Nrq-2].head == nil){
516                 skipscheds++;
517                 rq = &runq[p->priority];
518                 goto found;
519         }
520
521         preempts++;
522
523 loop:
524         /*
525          *  find a process that last ran on this processor (affinity),
526          *  or one that hasn't moved in a while (load balancing).  Every
527          *  time around the loop affinity goes down.
528          */
529         spllo();
530         for(i = 0;; i++){
531                 /*
532                  *  find the highest priority target process that this
533                  *  processor can run given affinity constraints.
534                  *
535                  */
536                 for(rq = &runq[Nrq-1]; rq >= runq; rq--){
537                         for(p = rq->head; p != nil; p = p->rnext){
538                                 if(p->mp == nil || p->mp == MACHP(m->machno)
539                                 || (p->wired == nil && i > 0))
540                                         goto found;
541                         }
542                 }
543
544                 /* waste time or halt the CPU */
545                 idlehands();
546
547                 /* remember how much time we're here */
548                 now = perfticks();
549                 m->perf.inidle += now-start;
550                 start = now;
551         }
552
553 found:
554         splhi();
555         p = dequeueproc(rq, p);
556         if(p == nil)
557                 goto loop;
558
559         p->state = Scheding;
560         p->mp = MACHP(m->machno);
561
562         if(edflock(p)){
563                 edfrun(p, rq == &runq[PriEdf]); /* start deadline timer and do admin */
564                 edfunlock();
565         }
566         pt = proctrace;
567         if(pt != nil)
568                 pt(p, SRun, 0);
569         return p;
570 }
571
572 int
573 canpage(Proc *p)
574 {
575         int ok = 0;
576
577         splhi();
578         lock(runq);
579         /* Only reliable way to see if we are Running */
580         if(p->mach == nil) {
581                 p->newtlb = 1;
582                 ok = 1;
583         }
584         unlock(runq);
585         spllo();
586
587         return ok;
588 }
589
590 Proc*
591 newproc(void)
592 {
593         char msg[64];
594         Proc *p;
595
596         lock(&procalloc);
597         for(;;) {
598                 if((p = procalloc.free) != nil)
599                         break;
600
601                 snprint(msg, sizeof msg, "no procs; %s forking",
602                         up != nil ? up->text: "kernel");
603                 unlock(&procalloc);
604                 resrcwait(msg);
605                 lock(&procalloc);
606         }
607         procalloc.free = p->qnext;
608         unlock(&procalloc);
609
610         p->state = Scheding;
611         p->psstate = "New";
612         p->mach = nil;
613         p->eql = nil;
614         p->qnext = nil;
615         p->nchild = 0;
616         p->nwait = 0;
617         p->waitq = nil;
618         p->parent = nil;
619         p->pgrp = nil;
620         p->egrp = nil;
621         p->fgrp = nil;
622         p->rgrp = nil;
623         p->pdbg = nil;
624         p->fpstate = FPinit;
625         p->kp = 0;
626         p->procctl = 0;
627         p->syscalltrace = nil;  
628         p->notepending = 0;
629         p->ureg = nil;
630         p->privatemem = 0;
631         p->noswap = 0;
632         p->errstr = p->errbuf0;
633         p->syserrstr = p->errbuf1;
634         p->errbuf0[0] = '\0';
635         p->errbuf1[0] = '\0';
636         p->nlocks = 0;
637         p->delaysched = 0;
638         p->trace = 0;
639         kstrdup(&p->user, "*nouser");
640         kstrdup(&p->text, "*notext");
641         kstrdup(&p->args, "");
642         p->nargs = 0;
643         p->setargs = 0;
644         memset(p->seg, 0, sizeof p->seg);
645         p->parentpid = 0;
646         p->noteid = pidalloc(p);
647         if(p->kstack == nil)
648                 p->kstack = smalloc(KSTACK);
649
650         /* sched params */
651         p->mp = nil;
652         p->wired = nil;
653         procpriority(p, PriNormal, 0);
654         p->cpu = 0;
655         p->lastupdate = MACHP(0)->ticks*Scaling;
656         p->edf = nil;
657
658         return p;
659 }
660
661 /*
662  * wire this proc to a machine
663  */
664 void
665 procwired(Proc *p, int bm)
666 {
667         Proc *pp;
668         int i;
669         char nwired[MAXMACH];
670         Mach *wm;
671
672         if(bm < 0){
673                 /* pick a machine to wire to */
674                 memset(nwired, 0, sizeof(nwired));
675                 p->wired = nil;
676                 pp = proctab(0);
677                 for(i=0; i<conf.nproc; i++, pp++){
678                         wm = pp->wired;
679                         if(wm != nil && pp->pid)
680                                 nwired[wm->machno]++;
681                 }
682                 bm = 0;
683                 for(i=0; i<conf.nmach; i++)
684                         if(nwired[i] < nwired[bm])
685                                 bm = i;
686         } else {
687                 /* use the virtual machine requested */
688                 bm = bm % conf.nmach;
689         }
690
691         p->wired = MACHP(bm);
692         p->mp = p->wired;
693 }
694
695 void
696 procpriority(Proc *p, int pri, int fixed)
697 {
698         if(pri >= Npriq)
699                 pri = Npriq - 1;
700         else if(pri < 0)
701                 pri = 0;
702         p->basepri = pri;
703         p->priority = pri;
704         if(fixed){
705                 p->fixedpri = 1;
706         } else {
707                 p->fixedpri = 0;
708         }
709 }
710
711 void
712 procinit0(void)         /* bad planning - clashes with devproc.c */
713 {
714         Proc *p;
715         int i;
716
717         p = xalloc(conf.nproc*sizeof(Proc));
718         if(p == nil){
719                 xsummary();
720                 panic("cannot allocate %lud procs (%ludMB)", conf.nproc, conf.nproc*sizeof(Proc)/(1024*1024));
721         }
722         procalloc.arena = p;
723         procalloc.free = p;
724         for(i=0; i<conf.nproc-1; i++, p++)
725                 p->qnext = p+1;
726         p->qnext = nil;
727 }
728
729 /*
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.
733  *
734  *  we lock both the process and the rendezvous to keep r->p
735  *  and p->r synchronized.
736  */
737 void
738 sleep(Rendez *r, int (*f)(void*), void *arg)
739 {
740         int s;
741         void (*pt)(Proc*, int, vlong);
742
743         s = splhi();
744
745         if(up->nlocks)
746                 print("process %lud sleeps with %d locks held, last lock %#p locked at pc %#p, sleep called from %#p\n",
747                         up->pid, up->nlocks, up->lastlock, up->lastlock->pc, getcallerpc(&r));
748         lock(r);
749         lock(&up->rlock);
750         if(r->p != nil){
751                 print("double sleep called from %#p, %lud %lud\n", getcallerpc(&r), r->p->pid, up->pid);
752                 dumpstack();
753         }
754
755         /*
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
759          *  committed.
760          */
761         r->p = up;
762
763         if((*f)(arg) || up->notepending){
764                 /*
765                  *  if condition happened or a note is pending
766                  *  never mind
767                  */
768                 r->p = nil;
769                 unlock(&up->rlock);
770                 unlock(r);
771         } else {
772                 /*
773                  *  now we are committed to
774                  *  change state and call scheduler
775                  */
776                 pt = proctrace;
777                 if(pt != nil)
778                         pt(up, SSleep, 0);
779                 up->state = Wakeme;
780                 up->r = r;
781
782                 /* statistics */
783                 m->cs++;
784
785                 procsave(up);
786                 if(setlabel(&up->sched)) {
787                         /*
788                          *  here when the process is awakened
789                          */
790                         procrestore(up);
791                         spllo();
792                 } else {
793                         /*
794                          *  here to go to sleep (i.e. stop Running)
795                          */
796                         unlock(&up->rlock);
797                         unlock(r);
798                         gotolabel(&m->sched);
799                 }
800         }
801
802         if(up->notepending) {
803                 up->notepending = 0;
804                 splx(s);
805                 interrupted();
806         }
807
808         splx(s);
809 }
810
811 void
812 interrupted(void)
813 {
814         if(up->procctl == Proc_exitme && up->closingfgrp != nil)
815                 forceclosefgrp();
816         error(Eintr);
817 }
818
819 static int
820 tfn(void *arg)
821 {
822         return up->trend == nil || up->tfn(arg);
823 }
824
825 void
826 twakeup(Ureg*, Timer *t)
827 {
828         Proc *p;
829         Rendez *trend;
830
831         p = t->ta;
832         trend = p->trend;
833         p->trend = nil;
834         if(trend != nil)
835                 wakeup(trend);
836 }
837
838 void
839 tsleep(Rendez *r, int (*fn)(void*), void *arg, ulong ms)
840 {
841         if(up->tt != nil){
842                 print("tsleep: timer active: mode %d, tf %#p\n", up->tmode, up->tf);
843                 timerdel(up);
844         }
845         up->tns = MS2NS(ms);
846         up->tf = twakeup;
847         up->tmode = Trelative;
848         up->ta = up;
849         up->trend = r;
850         up->tfn = fn;
851         timeradd(up);
852
853         if(waserror()){
854                 timerdel(up);
855                 nexterror();
856         }
857         sleep(r, tfn, arg);
858         if(up->tt != nil)
859                 timerdel(up);
860         up->twhen = 0;
861         poperror();
862 }
863
864 /*
865  *  Expects that only one process can call wakeup for any given Rendez.
866  *  We hold both locks to ensure that r->p and p->r remain consistent.
867  *  Richard Miller has a better solution that doesn't require both to
868  *  be held simultaneously, but I'm a paranoid - presotto.
869  */
870 Proc*
871 wakeup(Rendez *r)
872 {
873         Proc *p;
874         int s;
875
876         s = splhi();
877
878         lock(r);
879         p = r->p;
880
881         if(p != nil){
882                 lock(&p->rlock);
883                 if(p->state != Wakeme || p->r != r){
884                         iprint("%p %p %d\n", p->r, r, p->state);
885                         panic("wakeup: state");
886                 }
887                 r->p = nil;
888                 p->r = nil;
889                 ready(p);
890                 unlock(&p->rlock);
891         }
892         unlock(r);
893
894         splx(s);
895
896         return p;
897 }
898
899 /*
900  *  if waking a sleeping process, this routine must hold both
901  *  p->rlock and r->lock.  However, it can't know them in
902  *  the same order as wakeup causing a possible lock ordering
903  *  deadlock.  We break the deadlock by giving up the p->rlock
904  *  lock if we can't get the r->lock and retrying.
905  */
906 int
907 postnote(Proc *p, int dolock, char *n, int flag)
908 {
909         int s, ret;
910         QLock *q;
911
912         if(p == nil)
913                 return 0;
914
915         if(dolock)
916                 qlock(&p->debug);
917
918         if(p->pid == 0){
919                 if(dolock)
920                         qunlock(&p->debug);
921                 return 0;
922         }
923
924         if(n != nil && flag != NUser && (p->notify == 0 || p->notified))
925                 p->nnote = 0;
926
927         ret = 0;
928         if(p->nnote < NNOTE && n != nil) {
929                 kstrcpy(p->note[p->nnote].msg, n, ERRMAX);
930                 p->note[p->nnote++].flag = flag;
931                 ret = 1;
932         }
933         p->notepending = 1;
934         if(dolock)
935                 qunlock(&p->debug);
936
937         /* this loop is to avoid lock ordering problems. */
938         for(;;){
939                 Rendez *r;
940
941                 s = splhi();
942                 lock(&p->rlock);
943                 r = p->r;
944
945                 /* waiting for a wakeup? */
946                 if(r == nil)
947                         break;  /* no */
948
949                 /* try for the second lock */
950                 if(canlock(r)){
951                         if(p->state != Wakeme || r->p != p)
952                                 panic("postnote: state %d %d %d", r->p != p, p->r != r, p->state);
953                         p->r = nil;
954                         r->p = nil;
955                         ready(p);
956                         unlock(r);
957                         break;
958                 }
959
960                 /* give other process time to get out of critical section and try again */
961                 unlock(&p->rlock);
962                 splx(s);
963                 sched();
964         }
965         unlock(&p->rlock);
966         splx(s);
967
968         switch(p->state){
969         case Queueing:
970                 /* Try and pull out of a eqlock */
971                 if((q = p->eql) != nil){
972                         lock(&q->use);
973                         if(p->state == Queueing && p->eql == q){
974                                 Proc *d, *l;
975
976                                 for(l = nil, d = q->head; d != nil; l = d, d = d->qnext){
977                                         if(d == p){
978                                                 if(l != nil)
979                                                         l->qnext = p->qnext;
980                                                 else
981                                                         q->head = p->qnext;
982                                                 if(p->qnext == nil)
983                                                         q->tail = l;
984                                                 p->qnext = nil;
985                                                 p->eql = nil;   /* not taken */
986                                                 ready(p);
987                                                 break;
988                                         }
989                                 }
990                         }
991                         unlock(&q->use);
992                 }
993                 break;
994         case Rendezvous:
995                 /* Try and pull out of a rendezvous */
996                 lock(p->rgrp);
997                 if(p->state == Rendezvous) {
998                         Proc *d, **l;
999
1000                         l = &REND(p->rgrp, p->rendtag);
1001                         for(d = *l; d != nil; d = d->rendhash) {
1002                                 if(d == p) {
1003                                         *l = p->rendhash;
1004                                         p->rendval = ~0;
1005                                         ready(p);
1006                                         break;
1007                                 }
1008                                 l = &d->rendhash;
1009                         }
1010                 }
1011                 unlock(p->rgrp);
1012                 break;
1013         }
1014         return ret;
1015 }
1016
1017 /*
1018  * weird thing: keep at most NBROKEN around
1019  */
1020 #define NBROKEN 4
1021 struct
1022 {
1023         QLock;
1024         int     n;
1025         Proc    *p[NBROKEN];
1026 }broken;
1027
1028 void
1029 addbroken(Proc *p)
1030 {
1031         qlock(&broken);
1032         if(broken.n == NBROKEN) {
1033                 ready(broken.p[0]);
1034                 memmove(&broken.p[0], &broken.p[1], sizeof(Proc*)*(NBROKEN-1));
1035                 --broken.n;
1036         }
1037         broken.p[broken.n++] = p;
1038         qunlock(&broken);
1039
1040         edfstop(up);
1041         p->state = Broken;
1042         p->psstate = nil;
1043         sched();
1044 }
1045
1046 void
1047 unbreak(Proc *p)
1048 {
1049         int b;
1050
1051         qlock(&broken);
1052         for(b=0; b < broken.n; b++)
1053                 if(broken.p[b] == p) {
1054                         broken.n--;
1055                         memmove(&broken.p[b], &broken.p[b+1],
1056                                         sizeof(Proc*)*(NBROKEN-(b+1)));
1057                         ready(p);
1058                         break;
1059                 }
1060         qunlock(&broken);
1061 }
1062
1063 int
1064 freebroken(void)
1065 {
1066         int i, n;
1067
1068         qlock(&broken);
1069         n = broken.n;
1070         for(i=0; i<n; i++) {
1071                 ready(broken.p[i]);
1072                 broken.p[i] = nil;
1073         }
1074         broken.n = 0;
1075         qunlock(&broken);
1076         return n;
1077 }
1078
1079 void
1080 pexit(char *exitstr, int freemem)
1081 {
1082         Proc *p;
1083         Segment **s, **es;
1084         long utime, stime;
1085         Waitq *wq;
1086         Fgrp *fgrp;
1087         Egrp *egrp;
1088         Rgrp *rgrp;
1089         Pgrp *pgrp;
1090         Chan *dot;
1091         void (*pt)(Proc*, int, vlong);
1092
1093         up->alarm = 0;
1094         if(up->tt != nil)
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         qunlock(&up->debug);
1211
1212         /* Sched must not loop for these locks */
1213         lock(&procalloc);
1214         lock(&palloc);
1215
1216         edfstop(up);
1217         up->state = Moribund;
1218         sched();
1219         panic("pexit");
1220 }
1221
1222 static int
1223 haswaitq(void *x)
1224 {
1225         return ((Proc*)x)->waitq != nil;
1226 }
1227
1228 ulong
1229 pwait(Waitmsg *w)
1230 {
1231         ulong cpid;
1232         Waitq *wq;
1233
1234         if(!canqlock(&up->qwaitr))
1235                 error(Einuse);
1236
1237         if(waserror()) {
1238                 qunlock(&up->qwaitr);
1239                 nexterror();
1240         }
1241
1242         lock(&up->exl);
1243         while(up->waitq == nil) {
1244                 if(up->nchild == 0) {
1245                         unlock(&up->exl);
1246                         error(Enochild);
1247                 }
1248                 unlock(&up->exl);
1249                 sleep(&up->waitr, haswaitq, up);
1250                 lock(&up->exl);
1251         }
1252         wq = up->waitq;
1253         up->waitq = wq->next;
1254         up->nwait--;
1255         unlock(&up->exl);
1256
1257         qunlock(&up->qwaitr);
1258         poperror();
1259
1260         if(w != nil)
1261                 memmove(w, &wq->w, sizeof(Waitmsg));
1262         cpid = wq->w.pid;
1263         free(wq);
1264         return cpid;
1265 }
1266
1267 Proc*
1268 proctab(int i)
1269 {
1270         return &procalloc.arena[i];
1271 }
1272
1273 void
1274 dumpaproc(Proc *p)
1275 {
1276         ulong bss;
1277         char *s;
1278
1279         if(p == nil)
1280                 return;
1281
1282         bss = 0;
1283         if(p->seg[BSEG] != nil)
1284                 bss = p->seg[BSEG]->top;
1285
1286         s = p->psstate;
1287         if(s == nil)
1288                 s = statename[p->state];
1289         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",
1290                 p->pid, p->text, p->pc, dbgpc(p),  s, statename[p->state],
1291                 p->time[0], p->time[1], bss, p->qpc, p->nlocks, p->delaysched,
1292                 p->lastlock ? p->lastlock->pc : 0, p->priority);
1293 }
1294
1295 void
1296 procdump(void)
1297 {
1298         int i;
1299         Proc *p;
1300
1301         if(up != nil)
1302                 print("up %lud\n", up->pid);
1303         else
1304                 print("no current process\n");
1305         for(i=0; i<conf.nproc; i++) {
1306                 p = &procalloc.arena[i];
1307                 if(p->state != Dead)
1308                         dumpaproc(p);
1309         }
1310 }
1311
1312 /*
1313  *  wait till all processes have flushed their mmu
1314  *  state about segement s
1315  */
1316 void
1317 procflushseg(Segment *s)
1318 {
1319         int i, ns, nm, nwait;
1320         Proc *p;
1321
1322         /*
1323          *  tell all processes with this
1324          *  segment to flush their mmu's
1325          */
1326         nwait = 0;
1327         for(i=0; i<conf.nproc; i++) {
1328                 p = &procalloc.arena[i];
1329                 if(p->state == Dead)
1330                         continue;
1331                 for(ns = 0; ns < NSEG; ns++)
1332                         if(p->seg[ns] == s){
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                                 break;
1341                         }
1342         }
1343
1344         if(nwait == 0)
1345                 return;
1346
1347         /*
1348          *  wait for all other processors to take a clock interrupt
1349          *  and flush their mmu's
1350          */
1351         for(nm = 0; nm < conf.nmach; nm++)
1352                 while(m->machno != nm && MACHP(nm)->flushmmu)
1353                         sched();
1354 }
1355
1356 void
1357 scheddump(void)
1358 {
1359         Proc *p;
1360         Schedq *rq;
1361
1362         for(rq = &runq[Nrq-1]; rq >= runq; rq--){
1363                 if(rq->head == nil)
1364                         continue;
1365                 print("rq%ld:", rq-runq);
1366                 for(p = rq->head; p != nil; p = p->rnext)
1367                         print(" %lud(%lud)", p->pid, m->ticks - p->readytime);
1368                 print("\n");
1369                 delay(150);
1370         }
1371         print("nrdy %d\n", nrdy);
1372 }
1373
1374 void
1375 kproc(char *name, void (*func)(void *), void *arg)
1376 {
1377         Proc *p;
1378         static Pgrp *kpgrp;
1379
1380         p = newproc();
1381         p->psstate = nil;
1382         p->procmode = 0640;
1383         p->kp = 1;
1384         p->noswap = 1;
1385
1386         p->scallnr = up->scallnr;
1387         p->s = up->s;
1388         p->nerrlab = 0;
1389         p->slash = up->slash;
1390         p->dot = up->dot;
1391         if(p->dot != nil)
1392                 incref(p->dot);
1393
1394         memmove(p->note, up->note, sizeof(p->note));
1395         p->nnote = up->nnote;
1396         p->notified = 0;
1397         p->lastnote = up->lastnote;
1398         p->notify = up->notify;
1399         p->ureg = nil;
1400         p->dbgreg = nil;
1401
1402         procpriority(p, PriKproc, 0);
1403
1404         kprocchild(p, func, arg);
1405
1406         kstrdup(&p->user, eve);
1407         kstrdup(&p->text, name);
1408         if(kpgrp == nil)
1409                 kpgrp = newpgrp();
1410         p->pgrp = kpgrp;
1411         incref(kpgrp);
1412
1413         memset(p->time, 0, sizeof(p->time));
1414         p->time[TReal] = MACHP(0)->ticks;
1415         ready(p);
1416 }
1417
1418 /*
1419  *  called splhi() by notify().  See comment in notify for the
1420  *  reasoning.
1421  */
1422 void
1423 procctl(Proc *p)
1424 {
1425         char *state;
1426         ulong s;
1427
1428         switch(p->procctl) {
1429         case Proc_exitbig:
1430                 spllo();
1431                 pprint("Killed: Insufficient physical memory\n");
1432                 pexit("Killed: Insufficient physical memory", 1);
1433
1434         case Proc_exitme:
1435                 spllo();                /* pexit has locks in it */
1436                 pexit("Killed", 1);
1437
1438         case Proc_traceme:
1439                 if(p->nnote == 0)
1440                         return;
1441                 /* No break */
1442
1443         case Proc_stopme:
1444                 p->procctl = 0;
1445                 state = p->psstate;
1446                 p->psstate = "Stopped";
1447                 /* free a waiting debugger */
1448                 s = spllo();
1449                 qlock(&p->debug);
1450                 if(p->pdbg != nil) {
1451                         wakeup(&p->pdbg->sleep);
1452                         p->pdbg = nil;
1453                 }
1454                 qunlock(&p->debug);
1455                 splhi();
1456                 p->state = Stopped;
1457                 sched();
1458                 p->psstate = state;
1459                 splx(s);
1460                 return;
1461         }
1462 }
1463
1464 #include "errstr.h"
1465
1466 void
1467 error(char *err)
1468 {
1469         spllo();
1470
1471         assert(up->nerrlab < NERR);
1472         kstrcpy(up->errstr, err, ERRMAX);
1473         setlabel(&up->errlab[NERR-1]);
1474         nexterror();
1475 }
1476
1477 void
1478 nexterror(void)
1479 {
1480         assert(up->nerrlab > 0);
1481         gotolabel(&up->errlab[--up->nerrlab]);
1482 }
1483
1484 void
1485 exhausted(char *resource)
1486 {
1487         char buf[ERRMAX];
1488
1489         snprint(buf, sizeof buf, "no free %s", resource);
1490         iprint("%s\n", buf);
1491         error(buf);
1492 }
1493
1494 ulong
1495 procpagecount(Proc *p)
1496 {
1497         Segment *s;
1498         ulong pages;
1499         int i;
1500
1501         eqlock(&p->seglock);
1502         if(waserror()){
1503                 qunlock(&p->seglock);
1504                 nexterror();
1505         }
1506         pages = 0;
1507         for(i=0; i<NSEG; i++){
1508                 if((s = p->seg[i]) != nil){
1509                         eqlock(s);
1510                         pages += mcountseg(s);
1511                         qunlock(s);
1512                 }
1513         }
1514         qunlock(&p->seglock);
1515         poperror();
1516
1517         return pages;
1518 }
1519
1520 void
1521 killbig(char *why)
1522 {
1523         int i;
1524         Segment *s;
1525         ulong l, max;
1526         Proc *p, *ep, *kp;
1527
1528         max = 0;
1529         kp = nil;
1530         ep = procalloc.arena+conf.nproc;
1531         for(p = procalloc.arena; p < ep; p++) {
1532                 if(p->state == Dead || p->kp)
1533                         continue;
1534                 if((p->noswap || (p->procmode & 0222) == 0) && strcmp(eve, p->user) == 0)
1535                         continue;
1536                 l = procpagecount(p);
1537                 if(l > max){
1538                         kp = p;
1539                         max = l;
1540                 }
1541         }
1542         if(kp == nil)
1543                 return;
1544         print("%lud: %s killed: %s\n", kp->pid, kp->text, why);
1545         qlock(&kp->seglock);
1546         for(p = procalloc.arena; p < ep; p++) {
1547                 if(p->state == Dead || p->kp)
1548                         continue;
1549                 if(p != kp && p->seg[BSEG] != nil && p->seg[BSEG] == kp->seg[BSEG])
1550                         p->procctl = Proc_exitbig;
1551         }
1552         kp->procctl = Proc_exitbig;
1553         for(i = 0; i < NSEG; i++) {
1554                 s = kp->seg[i];
1555                 if(s != nil) {
1556                         qlock(s);
1557                         mfreeseg(s, s->base, (s->top - s->base)/BY2PG);
1558                         qunlock(s);
1559                 }
1560         }
1561         qunlock(&kp->seglock);
1562 }
1563
1564 /*
1565  *  change ownership to 'new' of all processes owned by 'old'.  Used when
1566  *  eve changes.
1567  */
1568 void
1569 renameuser(char *old, char *new)
1570 {
1571         Proc *p, *ep;
1572
1573         ep = procalloc.arena+conf.nproc;
1574         for(p = procalloc.arena; p < ep; p++)
1575                 if(p->user != nil && strcmp(old, p->user) == 0)
1576                         kstrdup(&p->user, new);
1577 }
1578
1579 /*
1580  *  time accounting called by clock() splhi'd
1581  */
1582 void
1583 accounttime(void)
1584 {
1585         Proc *p;
1586         ulong n, per;
1587         static ulong nrun;
1588
1589         p = m->proc;
1590         if(p != nil) {
1591                 nrun++;
1592                 p->time[p->insyscall]++;
1593         }
1594
1595         /* calculate decaying duty cycles */
1596         n = perfticks();
1597         per = n - m->perf.last;
1598         m->perf.last = n;
1599         per = (m->perf.period*(HZ-1) + per)/HZ;
1600         if(per != 0)
1601                 m->perf.period = per;
1602
1603         m->perf.avg_inidle = (m->perf.avg_inidle*(HZ-1)+m->perf.inidle)/HZ;
1604         m->perf.inidle = 0;
1605
1606         m->perf.avg_inintr = (m->perf.avg_inintr*(HZ-1)+m->perf.inintr)/HZ;
1607         m->perf.inintr = 0;
1608
1609         /* only one processor gets to compute system load averages */
1610         if(m->machno != 0)
1611                 return;
1612
1613         /*
1614          * calculate decaying load average.
1615          * if we decay by (n-1)/n then it takes
1616          * n clock ticks to go from load L to .36 L once
1617          * things quiet down.  it takes about 5 n clock
1618          * ticks to go to zero.  so using HZ means this is
1619          * approximately the load over the last second,
1620          * with a tail lasting about 5 seconds.
1621          */
1622         n = nrun;
1623         nrun = 0;
1624         n = (nrdy+n)*1000;
1625         m->load = (m->load*(HZ-1)+n)/HZ;
1626 }
1627
1628 int
1629 pidalloc(Proc *p)
1630 {
1631         static int gen, wrapped;
1632         int pid, h;
1633         Proc *x;
1634
1635         lock(&procalloc);
1636 Retry:
1637         pid = ++gen & 0x7FFFFFFF;
1638         if(pid == 0){
1639                 wrapped = 1;
1640                 goto Retry;
1641         }
1642         h = pid % nelem(procalloc.ht);
1643         if(wrapped)
1644                 for(x = procalloc.ht[h]; x != nil; x = x->pidhash)
1645                         if(x->pid == pid)
1646                                 goto Retry;
1647         if(p != nil){
1648                 p->pid = pid;
1649                 p->pidhash = procalloc.ht[h];
1650                 procalloc.ht[h] = p;
1651         }
1652         unlock(&procalloc);
1653         return pid;
1654 }
1655
1656 static void
1657 pidfree(Proc *p)
1658 {
1659         int h;
1660         Proc **l;
1661
1662         h = p->pid % nelem(procalloc.ht);
1663         lock(&procalloc);
1664         for(l = &procalloc.ht[h]; *l != nil; l = &(*l)->pidhash)
1665                 if(*l == p){
1666                         *l = p->pidhash;
1667                         break;
1668                 }
1669         unlock(&procalloc);
1670 }
1671
1672 int
1673 procindex(ulong pid)
1674 {
1675         Proc *p;
1676         int h;
1677         int s;
1678
1679         s = -1;
1680         h = pid % nelem(procalloc.ht);
1681         lock(&procalloc);
1682         for(p = procalloc.ht[h]; p != nil; p = p->pidhash)
1683                 if(p->pid == pid){
1684                         s = p - procalloc.arena;
1685                         break;
1686                 }
1687         unlock(&procalloc);
1688         return s;
1689 }