Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[dragonfly.git] / sys / kern / kern_synch.c
1 /*-
2  * Copyright (c) 1982, 1986, 1990, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      @(#)kern_synch.c        8.9 (Berkeley) 5/19/95
39  * $FreeBSD: src/sys/kern/kern_synch.c,v 1.87.2.6 2002/10/13 07:29:53 kbyanc Exp $
40  * $DragonFly: src/sys/kern/kern_synch.c,v 1.2 2003/06/17 04:28:41 dillon Exp $
41  */
42
43 #include "opt_ktrace.h"
44
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/proc.h>
48 #include <sys/kernel.h>
49 #include <sys/signalvar.h>
50 #include <sys/resourcevar.h>
51 #include <sys/vmmeter.h>
52 #include <sys/sysctl.h>
53 #ifdef KTRACE
54 #include <sys/uio.h>
55 #include <sys/ktrace.h>
56 #endif
57
58 #include <machine/cpu.h>
59 #include <machine/ipl.h>
60 #include <machine/smp.h>
61
62 static void sched_setup __P((void *dummy));
63 SYSINIT(sched_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, sched_setup, NULL)
64
65 u_char  curpriority;
66 int     hogticks;
67 int     lbolt;
68 int     sched_quantum;          /* Roundrobin scheduling quantum in ticks. */
69
70 static struct callout loadav_callout;
71
72 struct loadavg averunnable =
73         { {0, 0, 0}, FSCALE };  /* load average, of runnable procs */
74 /*
75  * Constants for averages over 1, 5, and 15 minutes
76  * when sampling at 5 second intervals.
77  */
78 static fixpt_t cexp[3] = {
79         0.9200444146293232 * FSCALE,    /* exp(-1/12) */
80         0.9834714538216174 * FSCALE,    /* exp(-1/60) */
81         0.9944598480048967 * FSCALE,    /* exp(-1/180) */
82 };
83
84 static int      curpriority_cmp __P((struct proc *p));
85 static void     endtsleep __P((void *));
86 static void     loadav __P((void *arg));
87 static void     maybe_resched __P((struct proc *chk));
88 static void     roundrobin __P((void *arg));
89 static void     schedcpu __P((void *arg));
90 static void     updatepri __P((struct proc *p));
91
92 static int
93 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
94 {
95         int error, new_val;
96
97         new_val = sched_quantum * tick;
98         error = sysctl_handle_int(oidp, &new_val, 0, req);
99         if (error != 0 || req->newptr == NULL)
100                 return (error);
101         if (new_val < tick)
102                 return (EINVAL);
103         sched_quantum = new_val / tick;
104         hogticks = 2 * sched_quantum;
105         return (0);
106 }
107
108 SYSCTL_PROC(_kern, OID_AUTO, quantum, CTLTYPE_INT|CTLFLAG_RW,
109         0, sizeof sched_quantum, sysctl_kern_quantum, "I", "");
110
111 /*-
112  * Compare priorities.  Return:
113  *     <0: priority of p < current priority
114  *      0: priority of p == current priority
115  *     >0: priority of p > current priority
116  * The priorities are the normal priorities or the normal realtime priorities
117  * if p is on the same scheduler as curproc.  Otherwise the process on the
118  * more realtimeish scheduler has lowest priority.  As usual, a higher
119  * priority really means a lower priority.
120  */
121 static int
122 curpriority_cmp(p)
123         struct proc *p;
124 {
125         int c_class, p_class;
126
127         c_class = RTP_PRIO_BASE(curproc->p_rtprio.type);
128         p_class = RTP_PRIO_BASE(p->p_rtprio.type);
129         if (p_class != c_class)
130                 return (p_class - c_class);
131         if (p_class == RTP_PRIO_NORMAL)
132                 return (((int)p->p_priority - (int)curpriority) / PPQ);
133         return ((int)p->p_rtprio.prio - (int)curproc->p_rtprio.prio);
134 }
135
136 /*
137  * Arrange to reschedule if necessary, taking the priorities and
138  * schedulers into account.
139  */
140 static void
141 maybe_resched(chk)
142         struct proc *chk;
143 {
144         struct proc *p = curproc; /* XXX */
145
146         /*
147          * XXX idle scheduler still broken because proccess stays on idle
148          * scheduler during waits (such as when getting FS locks).  If a
149          * standard process becomes runaway cpu-bound, the system can lockup
150          * due to idle-scheduler processes in wakeup never getting any cpu.
151          */
152         if (p == NULL) {
153 #if 0
154                 need_resched();
155 #endif
156         } else if (chk == p) {
157                 /* We may need to yield if our priority has been raised. */
158                 if (curpriority_cmp(chk) > 0)
159                         need_resched();
160         } else if (curpriority_cmp(chk) < 0)
161                 need_resched();
162 }
163
164 int 
165 roundrobin_interval(void)
166 {
167         return (sched_quantum);
168 }
169
170 /*
171  * Force switch among equal priority processes every 100ms.
172  */
173 /* ARGSUSED */
174 static void
175 roundrobin(arg)
176         void *arg;
177 {
178 #ifndef SMP
179         struct proc *p = curproc; /* XXX */
180 #endif
181  
182 #ifdef SMP
183         need_resched();
184         forward_roundrobin();
185 #else 
186         if (p == 0 || RTP_PRIO_NEED_RR(p->p_rtprio.type))
187                 need_resched();
188 #endif
189
190         timeout(roundrobin, NULL, sched_quantum);
191 }
192
193 /*
194  * Constants for digital decay and forget:
195  *      90% of (p_estcpu) usage in 5 * loadav time
196  *      95% of (p_pctcpu) usage in 60 seconds (load insensitive)
197  *          Note that, as ps(1) mentions, this can let percentages
198  *          total over 100% (I've seen 137.9% for 3 processes).
199  *
200  * Note that schedclock() updates p_estcpu and p_cpticks asynchronously.
201  *
202  * We wish to decay away 90% of p_estcpu in (5 * loadavg) seconds.
203  * That is, the system wants to compute a value of decay such
204  * that the following for loop:
205  *      for (i = 0; i < (5 * loadavg); i++)
206  *              p_estcpu *= decay;
207  * will compute
208  *      p_estcpu *= 0.1;
209  * for all values of loadavg:
210  *
211  * Mathematically this loop can be expressed by saying:
212  *      decay ** (5 * loadavg) ~= .1
213  *
214  * The system computes decay as:
215  *      decay = (2 * loadavg) / (2 * loadavg + 1)
216  *
217  * We wish to prove that the system's computation of decay
218  * will always fulfill the equation:
219  *      decay ** (5 * loadavg) ~= .1
220  *
221  * If we compute b as:
222  *      b = 2 * loadavg
223  * then
224  *      decay = b / (b + 1)
225  *
226  * We now need to prove two things:
227  *      1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
228  *      2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
229  *
230  * Facts:
231  *         For x close to zero, exp(x) =~ 1 + x, since
232  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
233  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
234  *         For x close to zero, ln(1+x) =~ x, since
235  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
236  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
237  *         ln(.1) =~ -2.30
238  *
239  * Proof of (1):
240  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
241  *      solving for factor,
242  *      ln(factor) =~ (-2.30/5*loadav), or
243  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
244  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
245  *
246  * Proof of (2):
247  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
248  *      solving for power,
249  *      power*ln(b/(b+1)) =~ -2.30, or
250  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
251  *
252  * Actual power values for the implemented algorithm are as follows:
253  *      loadav: 1       2       3       4
254  *      power:  5.68    10.32   14.94   19.55
255  */
256
257 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
258 #define loadfactor(loadav)      (2 * (loadav))
259 #define decay_cpu(loadfac, cpu) (((loadfac) * (cpu)) / ((loadfac) + FSCALE))
260
261 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
262 static fixpt_t  ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
263 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
264
265 /* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */
266 static int      fscale __unused = FSCALE;
267 SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, "");
268
269 /*
270  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
271  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
272  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
273  *
274  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
275  *      1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
276  *
277  * If you don't want to bother with the faster/more-accurate formula, you
278  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
279  * (more general) method of calculating the %age of CPU used by a process.
280  */
281 #define CCPU_SHIFT      11
282
283 /*
284  * Recompute process priorities, every hz ticks.
285  */
286 /* ARGSUSED */
287 static void
288 schedcpu(arg)
289         void *arg;
290 {
291         register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
292         register struct proc *p;
293         register int realstathz, s;
294
295         realstathz = stathz ? stathz : hz;
296         LIST_FOREACH(p, &allproc, p_list) {
297                 /*
298                  * Increment time in/out of memory and sleep time
299                  * (if sleeping).  We ignore overflow; with 16-bit int's
300                  * (remember them?) overflow takes 45 days.
301                  */
302                 p->p_swtime++;
303                 if (p->p_stat == SSLEEP || p->p_stat == SSTOP)
304                         p->p_slptime++;
305                 p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
306                 /*
307                  * If the process has slept the entire second,
308                  * stop recalculating its priority until it wakes up.
309                  */
310                 if (p->p_slptime > 1)
311                         continue;
312                 s = splhigh();  /* prevent state changes and protect run queue */
313                 /*
314                  * p_pctcpu is only for ps.
315                  */
316 #if     (FSHIFT >= CCPU_SHIFT)
317                 p->p_pctcpu += (realstathz == 100)?
318                         ((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT):
319                         100 * (((fixpt_t) p->p_cpticks)
320                                 << (FSHIFT - CCPU_SHIFT)) / realstathz;
321 #else
322                 p->p_pctcpu += ((FSCALE - ccpu) *
323                         (p->p_cpticks * FSCALE / realstathz)) >> FSHIFT;
324 #endif
325                 p->p_cpticks = 0;
326                 p->p_estcpu = decay_cpu(loadfac, p->p_estcpu);
327                 resetpriority(p);
328                 if (p->p_priority >= PUSER) {
329                         if ((p != curproc) &&
330 #ifdef SMP
331                             p->p_oncpu == 0xff &&       /* idle */
332 #endif
333                             p->p_stat == SRUN &&
334                             (p->p_flag & P_INMEM) &&
335                             (p->p_priority / PPQ) != (p->p_usrpri / PPQ)) {
336                                 remrunqueue(p);
337                                 p->p_priority = p->p_usrpri;
338                                 setrunqueue(p);
339                         } else
340                                 p->p_priority = p->p_usrpri;
341                 }
342                 splx(s);
343         }
344         wakeup((caddr_t)&lbolt);
345         timeout(schedcpu, (void *)0, hz);
346 }
347
348 /*
349  * Recalculate the priority of a process after it has slept for a while.
350  * For all load averages >= 1 and max p_estcpu of 255, sleeping for at
351  * least six times the loadfactor will decay p_estcpu to zero.
352  */
353 static void
354 updatepri(p)
355         register struct proc *p;
356 {
357         register unsigned int newcpu = p->p_estcpu;
358         register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
359
360         if (p->p_slptime > 5 * loadfac)
361                 p->p_estcpu = 0;
362         else {
363                 p->p_slptime--; /* the first time was done in schedcpu */
364                 while (newcpu && --p->p_slptime)
365                         newcpu = decay_cpu(loadfac, newcpu);
366                 p->p_estcpu = newcpu;
367         }
368         resetpriority(p);
369 }
370
371 /*
372  * We're only looking at 7 bits of the address; everything is
373  * aligned to 4, lots of things are aligned to greater powers
374  * of 2.  Shift right by 8, i.e. drop the bottom 256 worth.
375  */
376 #define TABLESIZE       128
377 static TAILQ_HEAD(slpquehead, proc) slpque[TABLESIZE];
378 #define LOOKUP(x)       (((intptr_t)(x) >> 8) & (TABLESIZE - 1))
379
380 /*
381  * During autoconfiguration or after a panic, a sleep will simply
382  * lower the priority briefly to allow interrupts, then return.
383  * The priority to be used (safepri) is machine-dependent, thus this
384  * value is initialized and maintained in the machine-dependent layers.
385  * This priority will typically be 0, or the lowest priority
386  * that is safe for use on the interrupt stack; it can be made
387  * higher to block network software interrupts after panics.
388  */
389 int safepri;
390
391 void
392 sleepinit(void)
393 {
394         int i;
395
396         sched_quantum = hz/10;
397         hogticks = 2 * sched_quantum;
398         for (i = 0; i < TABLESIZE; i++)
399                 TAILQ_INIT(&slpque[i]);
400 }
401
402 /*
403  * General sleep call.  Suspends the current process until a wakeup is
404  * performed on the specified identifier.  The process will then be made
405  * runnable with the specified priority.  Sleeps at most timo/hz seconds
406  * (0 means no timeout).  If pri includes PCATCH flag, signals are checked
407  * before and after sleeping, else signals are not checked.  Returns 0 if
408  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
409  * signal needs to be delivered, ERESTART is returned if the current system
410  * call should be restarted if possible, and EINTR is returned if the system
411  * call should be interrupted by the signal (return EINTR).
412  */
413 int
414 tsleep(ident, priority, wmesg, timo)
415         void *ident;
416         int priority, timo;
417         const char *wmesg;
418 {
419         struct proc *p = curproc;
420         int s, sig, catch = priority & PCATCH;
421         struct callout_handle thandle;
422
423 #ifdef KTRACE
424         if (p && KTRPOINT(p, KTR_CSW))
425                 ktrcsw(p->p_tracep, 1, 0);
426 #endif
427         s = splhigh();
428         if (cold || panicstr) {
429                 /*
430                  * After a panic, or during autoconfiguration,
431                  * just give interrupts a chance, then just return;
432                  * don't run any other procs or panic below,
433                  * in case this is the idle process and already asleep.
434                  */
435                 splx(safepri);
436                 splx(s);
437                 return (0);
438         }
439         KASSERT(p != NULL, ("tsleep1"));
440         KASSERT(ident != NULL && p->p_stat == SRUN, ("tsleep"));
441         /*
442          * Process may be sitting on a slpque if asleep() was called, remove
443          * it before re-adding.
444          */
445         if (p->p_wchan != NULL)
446                 unsleep(p);
447
448         p->p_wchan = ident;
449         p->p_wmesg = wmesg;
450         p->p_slptime = 0;
451         p->p_priority = priority & PRIMASK;
452         TAILQ_INSERT_TAIL(&slpque[LOOKUP(ident)], p, p_procq);
453         if (timo)
454                 thandle = timeout(endtsleep, (void *)p, timo);
455         /*
456          * We put ourselves on the sleep queue and start our timeout
457          * before calling CURSIG, as we could stop there, and a wakeup
458          * or a SIGCONT (or both) could occur while we were stopped.
459          * A SIGCONT would cause us to be marked as SSLEEP
460          * without resuming us, thus we must be ready for sleep
461          * when CURSIG is called.  If the wakeup happens while we're
462          * stopped, p->p_wchan will be 0 upon return from CURSIG.
463          */
464         if (catch) {
465                 p->p_flag |= P_SINTR;
466                 if ((sig = CURSIG(p))) {
467                         if (p->p_wchan)
468                                 unsleep(p);
469                         p->p_stat = SRUN;
470                         goto resume;
471                 }
472                 if (p->p_wchan == 0) {
473                         catch = 0;
474                         goto resume;
475                 }
476         } else
477                 sig = 0;
478         p->p_stat = SSLEEP;
479         p->p_stats->p_ru.ru_nvcsw++;
480         mi_switch();
481 resume:
482         curpriority = p->p_usrpri;
483         splx(s);
484         p->p_flag &= ~P_SINTR;
485         if (p->p_flag & P_TIMEOUT) {
486                 p->p_flag &= ~P_TIMEOUT;
487                 if (sig == 0) {
488 #ifdef KTRACE
489                         if (KTRPOINT(p, KTR_CSW))
490                                 ktrcsw(p->p_tracep, 0, 0);
491 #endif
492                         return (EWOULDBLOCK);
493                 }
494         } else if (timo)
495                 untimeout(endtsleep, (void *)p, thandle);
496         if (catch && (sig != 0 || (sig = CURSIG(p)))) {
497 #ifdef KTRACE
498                 if (KTRPOINT(p, KTR_CSW))
499                         ktrcsw(p->p_tracep, 0, 0);
500 #endif
501                 if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
502                         return (EINTR);
503                 return (ERESTART);
504         }
505 #ifdef KTRACE
506         if (KTRPOINT(p, KTR_CSW))
507                 ktrcsw(p->p_tracep, 0, 0);
508 #endif
509         return (0);
510 }
511
512 /*
513  * asleep() - async sleep call.  Place process on wait queue and return 
514  * immediately without blocking.  The process stays runnable until await() 
515  * is called.  If ident is NULL, remove process from wait queue if it is still
516  * on one.
517  *
518  * Only the most recent sleep condition is effective when making successive
519  * calls to asleep() or when calling tsleep().
520  *
521  * The timeout, if any, is not initiated until await() is called.  The sleep
522  * priority, signal, and timeout is specified in the asleep() call but may be
523  * overriden in the await() call.
524  *
525  * <<<<<<<< EXPERIMENTAL, UNTESTED >>>>>>>>>>
526  */
527
528 int
529 asleep(void *ident, int priority, const char *wmesg, int timo)
530 {
531         struct proc *p = curproc;
532         int s;
533
534         /*
535          * splhigh() while manipulating sleep structures and slpque.
536          *
537          * Remove preexisting wait condition (if any) and place process
538          * on appropriate slpque, but do not put process to sleep.
539          */
540
541         s = splhigh();
542
543         if (p->p_wchan != NULL)
544                 unsleep(p);
545
546         if (ident) {
547                 p->p_wchan = ident;
548                 p->p_wmesg = wmesg;
549                 p->p_slptime = 0;
550                 p->p_asleep.as_priority = priority;
551                 p->p_asleep.as_timo = timo;
552                 TAILQ_INSERT_TAIL(&slpque[LOOKUP(ident)], p, p_procq);
553         }
554
555         splx(s);
556
557         return(0);
558 }
559
560 /*
561  * await() - wait for async condition to occur.   The process blocks until
562  * wakeup() is called on the most recent asleep() address.  If wakeup is called
563  * priority to await(), await() winds up being a NOP.
564  *
565  * If await() is called more then once (without an intervening asleep() call),
566  * await() is still effectively a NOP but it calls mi_switch() to give other
567  * processes some cpu before returning.  The process is left runnable.
568  *
569  * <<<<<<<< EXPERIMENTAL, UNTESTED >>>>>>>>>>
570  */
571
572 int
573 await(int priority, int timo)
574 {
575         struct proc *p = curproc;
576         int s;
577
578         s = splhigh();
579
580         if (p->p_wchan != NULL) {
581                 struct callout_handle thandle;
582                 int sig;
583                 int catch;
584
585                 /*
586                  * The call to await() can override defaults specified in
587                  * the original asleep().
588                  */
589                 if (priority < 0)
590                         priority = p->p_asleep.as_priority;
591                 if (timo < 0)
592                         timo = p->p_asleep.as_timo;
593
594                 /*
595                  * Install timeout
596                  */
597
598                 if (timo)
599                         thandle = timeout(endtsleep, (void *)p, timo);
600
601                 sig = 0;
602                 catch = priority & PCATCH;
603
604                 if (catch) {
605                         p->p_flag |= P_SINTR;
606                         if ((sig = CURSIG(p))) {
607                                 if (p->p_wchan)
608                                         unsleep(p);
609                                 p->p_stat = SRUN;
610                                 goto resume;
611                         }
612                         if (p->p_wchan == NULL) {
613                                 catch = 0;
614                                 goto resume;
615                         }
616                 }
617                 p->p_stat = SSLEEP;
618                 p->p_stats->p_ru.ru_nvcsw++;
619                 mi_switch();
620 resume:
621                 curpriority = p->p_usrpri;
622
623                 splx(s);
624                 p->p_flag &= ~P_SINTR;
625                 if (p->p_flag & P_TIMEOUT) {
626                         p->p_flag &= ~P_TIMEOUT;
627                         if (sig == 0) {
628 #ifdef KTRACE
629                                 if (KTRPOINT(p, KTR_CSW))
630                                         ktrcsw(p->p_tracep, 0, 0);
631 #endif
632                                 return (EWOULDBLOCK);
633                         }
634                 } else if (timo)
635                         untimeout(endtsleep, (void *)p, thandle);
636                 if (catch && (sig != 0 || (sig = CURSIG(p)))) {
637 #ifdef KTRACE
638                         if (KTRPOINT(p, KTR_CSW))
639                                 ktrcsw(p->p_tracep, 0, 0);
640 #endif
641                         if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
642                                 return (EINTR);
643                         return (ERESTART);
644                 }
645 #ifdef KTRACE
646                 if (KTRPOINT(p, KTR_CSW))
647                         ktrcsw(p->p_tracep, 0, 0);
648 #endif
649         } else {
650                 /*
651                  * If as_priority is 0, await() has been called without an 
652                  * intervening asleep().  We are still effectively a NOP, 
653                  * but we call mi_switch() for safety.
654                  */
655
656                 if (p->p_asleep.as_priority == 0) {
657                         p->p_stats->p_ru.ru_nvcsw++;
658                         mi_switch();
659                 }
660                 splx(s);
661         }
662
663         /*
664          * clear p_asleep.as_priority as an indication that await() has been
665          * called.  If await() is called again without an intervening asleep(),
666          * await() is still effectively a NOP but the above mi_switch() code
667          * is triggered as a safety.
668          */
669         p->p_asleep.as_priority = 0;
670
671         return (0);
672 }
673
674 /*
675  * Implement timeout for tsleep or asleep()/await()
676  *
677  * If process hasn't been awakened (wchan non-zero),
678  * set timeout flag and undo the sleep.  If proc
679  * is stopped, just unsleep so it will remain stopped.
680  */
681 static void
682 endtsleep(arg)
683         void *arg;
684 {
685         register struct proc *p;
686         int s;
687
688         p = (struct proc *)arg;
689         s = splhigh();
690         if (p->p_wchan) {
691                 if (p->p_stat == SSLEEP)
692                         setrunnable(p);
693                 else
694                         unsleep(p);
695                 p->p_flag |= P_TIMEOUT;
696         }
697         splx(s);
698 }
699
700 /*
701  * Remove a process from its wait queue
702  */
703 void
704 unsleep(p)
705         register struct proc *p;
706 {
707         int s;
708
709         s = splhigh();
710         if (p->p_wchan) {
711                 TAILQ_REMOVE(&slpque[LOOKUP(p->p_wchan)], p, p_procq);
712                 p->p_wchan = 0;
713         }
714         splx(s);
715 }
716
717 /*
718  * Make all processes sleeping on the specified identifier runnable.
719  */
720 void
721 wakeup(ident)
722         register void *ident;
723 {
724         register struct slpquehead *qp;
725         register struct proc *p;
726         struct proc *np;
727         int s;
728
729         s = splhigh();
730         qp = &slpque[LOOKUP(ident)];
731 restart:
732         for (p = TAILQ_FIRST(qp); p != NULL; p = np) {
733                 np = TAILQ_NEXT(p, p_procq);
734                 if (p->p_wchan == ident) {
735                         TAILQ_REMOVE(qp, p, p_procq);
736                         p->p_wchan = 0;
737                         if (p->p_stat == SSLEEP) {
738                                 /* OPTIMIZED EXPANSION OF setrunnable(p); */
739                                 if (p->p_slptime > 1)
740                                         updatepri(p);
741                                 p->p_slptime = 0;
742                                 p->p_stat = SRUN;
743                                 if (p->p_flag & P_INMEM) {
744                                         setrunqueue(p);
745                                         maybe_resched(p);
746                                 } else {
747                                         p->p_flag |= P_SWAPINREQ;
748                                         wakeup((caddr_t)&proc0);
749                                 }
750                                 /* END INLINE EXPANSION */
751                                 goto restart;
752                         }
753                 }
754         }
755         splx(s);
756 }
757
758 /*
759  * Make a process sleeping on the specified identifier runnable.
760  * May wake more than one process if a target process is currently
761  * swapped out.
762  */
763 void
764 wakeup_one(ident)
765         register void *ident;
766 {
767         register struct slpquehead *qp;
768         register struct proc *p;
769         struct proc *np;
770         int s;
771
772         s = splhigh();
773         qp = &slpque[LOOKUP(ident)];
774
775 restart:
776         for (p = TAILQ_FIRST(qp); p != NULL; p = np) {
777                 np = TAILQ_NEXT(p, p_procq);
778                 if (p->p_wchan == ident) {
779                         TAILQ_REMOVE(qp, p, p_procq);
780                         p->p_wchan = 0;
781                         if (p->p_stat == SSLEEP) {
782                                 /* OPTIMIZED EXPANSION OF setrunnable(p); */
783                                 if (p->p_slptime > 1)
784                                         updatepri(p);
785                                 p->p_slptime = 0;
786                                 p->p_stat = SRUN;
787                                 if (p->p_flag & P_INMEM) {
788                                         setrunqueue(p);
789                                         maybe_resched(p);
790                                         break;
791                                 } else {
792                                         p->p_flag |= P_SWAPINREQ;
793                                         wakeup((caddr_t)&proc0);
794                                 }
795                                 /* END INLINE EXPANSION */
796                                 goto restart;
797                         }
798                 }
799         }
800         splx(s);
801 }
802
803 /*
804  * The machine independent parts of mi_switch().
805  * Must be called at splstatclock() or higher.
806  */
807 void
808 mi_switch()
809 {
810         struct timeval new_switchtime;
811         register struct proc *p = curproc;      /* XXX */
812         register struct rlimit *rlim;
813         int x;
814
815         /*
816          * XXX this spl is almost unnecessary.  It is partly to allow for
817          * sloppy callers that don't do it (issignal() via CURSIG() is the
818          * main offender).  It is partly to work around a bug in the i386
819          * cpu_switch() (the ipl is not preserved).  We ran for years
820          * without it.  I think there was only a interrupt latency problem.
821          * The main caller, tsleep(), does an splx() a couple of instructions
822          * after calling here.  The buggy caller, issignal(), usually calls
823          * here at spl0() and sometimes returns at splhigh().  The process
824          * then runs for a little too long at splhigh().  The ipl gets fixed
825          * when the process returns to user mode (or earlier).
826          *
827          * It would probably be better to always call here at spl0(). Callers
828          * are prepared to give up control to another process, so they must
829          * be prepared to be interrupted.  The clock stuff here may not
830          * actually need splstatclock().
831          */
832         x = splstatclock();
833
834 #ifdef SIMPLELOCK_DEBUG
835         if (p->p_simple_locks)
836                 printf("sleep: holding simple lock\n");
837 #endif
838         /*
839          * Compute the amount of time during which the current
840          * process was running, and add that to its total so far.
841          */
842         microuptime(&new_switchtime);
843         if (timevalcmp(&new_switchtime, &switchtime, <)) {
844                 printf("microuptime() went backwards (%ld.%06ld -> %ld.%06ld)\n",
845                     switchtime.tv_sec, switchtime.tv_usec, 
846                     new_switchtime.tv_sec, new_switchtime.tv_usec);
847                 new_switchtime = switchtime;
848         } else {
849                 p->p_runtime += (new_switchtime.tv_usec - switchtime.tv_usec) +
850                     (new_switchtime.tv_sec - switchtime.tv_sec) * (int64_t)1000000;
851         }
852
853         /*
854          * Check if the process exceeds its cpu resource allocation.
855          * If over max, kill it.
856          */
857         if (p->p_stat != SZOMB && p->p_limit->p_cpulimit != RLIM_INFINITY &&
858             p->p_runtime > p->p_limit->p_cpulimit) {
859                 rlim = &p->p_rlimit[RLIMIT_CPU];
860                 if (p->p_runtime / (rlim_t)1000000 >= rlim->rlim_max) {
861                         killproc(p, "exceeded maximum CPU limit");
862                 } else {
863                         psignal(p, SIGXCPU);
864                         if (rlim->rlim_cur < rlim->rlim_max) {
865                                 /* XXX: we should make a private copy */
866                                 rlim->rlim_cur += 5;
867                         }
868                 }
869         }
870
871         /*
872          * Pick a new current process and record its start time.
873          */
874         cnt.v_swtch++;
875         switchtime = new_switchtime;
876         cpu_switch(p);
877         if (switchtime.tv_sec == 0)
878                 microuptime(&switchtime);
879         switchticks = ticks;
880
881         splx(x);
882 }
883
884 /*
885  * Change process state to be runnable,
886  * placing it on the run queue if it is in memory,
887  * and awakening the swapper if it isn't in memory.
888  */
889 void
890 setrunnable(p)
891         register struct proc *p;
892 {
893         register int s;
894
895         s = splhigh();
896         switch (p->p_stat) {
897         case 0:
898         case SRUN:
899         case SZOMB:
900         default:
901                 panic("setrunnable");
902         case SSTOP:
903         case SSLEEP:
904                 unsleep(p);             /* e.g. when sending signals */
905                 break;
906
907         case SIDL:
908                 break;
909         }
910         p->p_stat = SRUN;
911         if (p->p_flag & P_INMEM)
912                 setrunqueue(p);
913         splx(s);
914         if (p->p_slptime > 1)
915                 updatepri(p);
916         p->p_slptime = 0;
917         if ((p->p_flag & P_INMEM) == 0) {
918                 p->p_flag |= P_SWAPINREQ;
919                 wakeup((caddr_t)&proc0);
920         }
921         else
922                 maybe_resched(p);
923 }
924
925 /*
926  * Compute the priority of a process when running in user mode.
927  * Arrange to reschedule if the resulting priority is better
928  * than that of the current process.
929  */
930 void
931 resetpriority(p)
932         register struct proc *p;
933 {
934         register unsigned int newpriority;
935
936         if (p->p_rtprio.type == RTP_PRIO_NORMAL) {
937                 newpriority = PUSER + p->p_estcpu / INVERSE_ESTCPU_WEIGHT +
938                     NICE_WEIGHT * p->p_nice;
939                 newpriority = min(newpriority, MAXPRI);
940                 p->p_usrpri = newpriority;
941         }
942         maybe_resched(p);
943 }
944
945 /*
946  * Compute a tenex style load average of a quantity on
947  * 1, 5 and 15 minute intervals.
948  */
949 static void
950 loadav(void *arg)
951 {
952         int i, nrun;
953         struct loadavg *avg;
954         struct proc *p;
955
956         avg = &averunnable;
957         nrun = 0;
958         LIST_FOREACH(p, &allproc, p_list) {
959                 switch (p->p_stat) {
960                 case SRUN:
961                 case SIDL:
962                         nrun++;
963                 }
964         }
965         for (i = 0; i < 3; i++)
966                 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
967                     nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
968
969         /*
970          * Schedule the next update to occur after 5 seconds, but add a
971          * random variation to avoid synchronisation with processes that
972          * run at regular intervals.
973          */
974         callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)),
975             loadav, NULL);
976 }
977
978 /* ARGSUSED */
979 static void
980 sched_setup(dummy)
981         void *dummy;
982 {
983
984         callout_init(&loadav_callout);
985
986         /* Kick off timeout driven events by calling first time. */
987         roundrobin(NULL);
988         schedcpu(NULL);
989         loadav(NULL);
990 }
991
992 /*
993  * We adjust the priority of the current process.  The priority of
994  * a process gets worse as it accumulates CPU time.  The cpu usage
995  * estimator (p_estcpu) is increased here.  resetpriority() will
996  * compute a different priority each time p_estcpu increases by
997  * INVERSE_ESTCPU_WEIGHT
998  * (until MAXPRI is reached).  The cpu usage estimator ramps up
999  * quite quickly when the process is running (linearly), and decays
1000  * away exponentially, at a rate which is proportionally slower when
1001  * the system is busy.  The basic principle is that the system will
1002  * 90% forget that the process used a lot of CPU time in 5 * loadav
1003  * seconds.  This causes the system to favor processes which haven't
1004  * run much recently, and to round-robin among other processes.
1005  */
1006 void
1007 schedclock(p)
1008         struct proc *p;
1009 {
1010
1011         p->p_cpticks++;
1012         p->p_estcpu = ESTCPULIM(p->p_estcpu + 1);
1013         if ((p->p_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
1014                 resetpriority(p);
1015                 if (p->p_priority >= PUSER)
1016                         p->p_priority = p->p_usrpri;
1017         }
1018 }