d3ac9f98c6fc9155f9adbd46e7e3226a1eb9175b
[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.16 2003/07/10 04:47:54 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 #include <sys/thread2.h>
54 #ifdef KTRACE
55 #include <sys/uio.h>
56 #include <sys/ktrace.h>
57 #endif
58 #include <sys/xwait.h>
59
60 #include <machine/cpu.h>
61 #include <machine/ipl.h>
62 #include <machine/smp.h>
63
64 static void sched_setup __P((void *dummy));
65 SYSINIT(sched_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, sched_setup, NULL)
66
67 int     hogticks;
68 int     lbolt;
69 int     sched_quantum;          /* Roundrobin scheduling quantum in ticks. */
70 int     ncpus;
71
72 static struct callout loadav_callout;
73
74 struct loadavg averunnable =
75         { {0, 0, 0}, FSCALE };  /* load average, of runnable procs */
76 /*
77  * Constants for averages over 1, 5, and 15 minutes
78  * when sampling at 5 second intervals.
79  */
80 static fixpt_t cexp[3] = {
81         0.9200444146293232 * FSCALE,    /* exp(-1/12) */
82         0.9834714538216174 * FSCALE,    /* exp(-1/60) */
83         0.9944598480048967 * FSCALE,    /* exp(-1/180) */
84 };
85
86 static void     endtsleep __P((void *));
87 static void     loadav __P((void *arg));
88 static void     maybe_resched __P((struct proc *chk));
89 static void     roundrobin __P((void *arg));
90 static void     schedcpu __P((void *arg));
91 static void     updatepri __P((struct proc *p));
92 static void     crit_panicints(void);
93
94 static int
95 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
96 {
97         int error, new_val;
98
99         new_val = sched_quantum * tick;
100         error = sysctl_handle_int(oidp, &new_val, 0, req);
101         if (error != 0 || req->newptr == NULL)
102                 return (error);
103         if (new_val < tick)
104                 return (EINVAL);
105         sched_quantum = new_val / tick;
106         hogticks = 2 * sched_quantum;
107         return (0);
108 }
109
110 SYSCTL_PROC(_kern, OID_AUTO, quantum, CTLTYPE_INT|CTLFLAG_RW,
111         0, sizeof sched_quantum, sysctl_kern_quantum, "I", "");
112
113 /*
114  * Arrange to reschedule if necessary by checking to see if the current
115  * process is on the highest priority user scheduling queue.  This may
116  * be run from an interrupt so we have to follow any preemption chains
117  * back to the original process.
118  */
119 static void
120 maybe_resched(struct proc *chk)
121 {
122         struct proc *cur = lwkt_preempted_proc();
123
124         if (cur == NULL)
125                 return;
126
127         /*
128          * Check the user queue (realtime, normal, idle).  Lower numbers
129          * indicate higher priority queues.  Lower numbers are also better
130          * for p_priority.
131          */
132         if (chk->p_rtprio.type < cur->p_rtprio.type) {
133                 need_resched();
134         } else if (chk->p_rtprio.type == cur->p_rtprio.type) {
135                 if (chk->p_rtprio.type == RTP_PRIO_NORMAL) {
136                         if (chk->p_priority / PPQ < cur->p_priority / PPQ)
137                                 need_resched();
138                 } else {
139                         if (chk->p_rtprio.prio < cur->p_rtprio.prio)
140                                 need_resched();
141                 }
142         }
143 }
144
145 int 
146 roundrobin_interval(void)
147 {
148         return (sched_quantum);
149 }
150
151 /*
152  * Force switch among equal priority processes every 100ms.
153  */
154 /* ARGSUSED */
155 static void
156 roundrobin(arg)
157         void *arg;
158 {
159         struct proc *p = lwkt_preempted_proc();
160 #ifdef SMP
161         if (p == NULL || RTP_PRIO_NEED_RR(p->p_rtprio.type))
162                 need_resched();
163         forward_roundrobin();
164 #else 
165         if (p == NULL || RTP_PRIO_NEED_RR(p->p_rtprio.type))
166                 need_resched();
167 #endif
168         timeout(roundrobin, NULL, sched_quantum);
169 }
170
171 /*
172  * Constants for digital decay and forget:
173  *      90% of (p_estcpu) usage in 5 * loadav time
174  *      95% of (p_pctcpu) usage in 60 seconds (load insensitive)
175  *          Note that, as ps(1) mentions, this can let percentages
176  *          total over 100% (I've seen 137.9% for 3 processes).
177  *
178  * Note that schedclock() updates p_estcpu and p_cpticks asynchronously.
179  *
180  * We wish to decay away 90% of p_estcpu in (5 * loadavg) seconds.
181  * That is, the system wants to compute a value of decay such
182  * that the following for loop:
183  *      for (i = 0; i < (5 * loadavg); i++)
184  *              p_estcpu *= decay;
185  * will compute
186  *      p_estcpu *= 0.1;
187  * for all values of loadavg:
188  *
189  * Mathematically this loop can be expressed by saying:
190  *      decay ** (5 * loadavg) ~= .1
191  *
192  * The system computes decay as:
193  *      decay = (2 * loadavg) / (2 * loadavg + 1)
194  *
195  * We wish to prove that the system's computation of decay
196  * will always fulfill the equation:
197  *      decay ** (5 * loadavg) ~= .1
198  *
199  * If we compute b as:
200  *      b = 2 * loadavg
201  * then
202  *      decay = b / (b + 1)
203  *
204  * We now need to prove two things:
205  *      1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
206  *      2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
207  *
208  * Facts:
209  *         For x close to zero, exp(x) =~ 1 + x, since
210  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
211  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
212  *         For x close to zero, ln(1+x) =~ x, since
213  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
214  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
215  *         ln(.1) =~ -2.30
216  *
217  * Proof of (1):
218  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
219  *      solving for factor,
220  *      ln(factor) =~ (-2.30/5*loadav), or
221  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
222  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
223  *
224  * Proof of (2):
225  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
226  *      solving for power,
227  *      power*ln(b/(b+1)) =~ -2.30, or
228  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
229  *
230  * Actual power values for the implemented algorithm are as follows:
231  *      loadav: 1       2       3       4
232  *      power:  5.68    10.32   14.94   19.55
233  */
234
235 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
236 #define loadfactor(loadav)      (2 * (loadav))
237 #define decay_cpu(loadfac, cpu) (((loadfac) * (cpu)) / ((loadfac) + FSCALE))
238
239 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
240 static fixpt_t  ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
241 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
242
243 /* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */
244 static int      fscale __unused = FSCALE;
245 SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, "");
246
247 /*
248  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
249  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
250  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
251  *
252  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
253  *      1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
254  *
255  * If you don't want to bother with the faster/more-accurate formula, you
256  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
257  * (more general) method of calculating the %age of CPU used by a process.
258  */
259 #define CCPU_SHIFT      11
260
261 /*
262  * Recompute process priorities, every hz ticks.
263  */
264 /* ARGSUSED */
265 static void
266 schedcpu(void *arg)
267 {
268         fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
269         struct proc *p;
270         struct proc *curp;
271         int realstathz, s;
272
273         curp = lwkt_preempted_proc(); /* YYY temporary hack */
274
275         realstathz = stathz ? stathz : hz;
276         LIST_FOREACH(p, &allproc, p_list) {
277                 /*
278                  * Increment time in/out of memory and sleep time
279                  * (if sleeping).  We ignore overflow; with 16-bit int's
280                  * (remember them?) overflow takes 45 days.
281                  */
282                 p->p_swtime++;
283                 if (p->p_stat == SSLEEP || p->p_stat == SSTOP)
284                         p->p_slptime++;
285                 p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
286                 /*
287                  * If the process has slept the entire second,
288                  * stop recalculating its priority until it wakes up.
289                  */
290                 if (p->p_slptime > 1)
291                         continue;
292                 s = splhigh();  /* prevent state changes and protect run queue */
293                 /*
294                  * p_pctcpu is only for ps.
295                  */
296 #if     (FSHIFT >= CCPU_SHIFT)
297                 p->p_pctcpu += (realstathz == 100)?
298                         ((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT):
299                         100 * (((fixpt_t) p->p_cpticks)
300                                 << (FSHIFT - CCPU_SHIFT)) / realstathz;
301 #else
302                 p->p_pctcpu += ((FSCALE - ccpu) *
303                         (p->p_cpticks * FSCALE / realstathz)) >> FSHIFT;
304 #endif
305                 p->p_cpticks = 0;
306                 p->p_estcpu = decay_cpu(loadfac, p->p_estcpu);
307                 resetpriority(p);
308                 splx(s);
309         }
310         wakeup((caddr_t)&lbolt);
311         timeout(schedcpu, (void *)0, hz);
312 }
313
314 /*
315  * Recalculate the priority of a process after it has slept for a while.
316  * For all load averages >= 1 and max p_estcpu of 255, sleeping for at
317  * least six times the loadfactor will decay p_estcpu to zero.
318  */
319 static void
320 updatepri(struct proc *p)
321 {
322         unsigned int newcpu = p->p_estcpu;
323         fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
324
325         if (p->p_slptime > 5 * loadfac) {
326                 p->p_estcpu = 0;
327         } else {
328                 p->p_slptime--; /* the first time was done in schedcpu */
329                 while (newcpu && --p->p_slptime)
330                         newcpu = decay_cpu(loadfac, newcpu);
331                 p->p_estcpu = newcpu;
332         }
333         resetpriority(p);
334 }
335
336 /*
337  * We're only looking at 7 bits of the address; everything is
338  * aligned to 4, lots of things are aligned to greater powers
339  * of 2.  Shift right by 8, i.e. drop the bottom 256 worth.
340  */
341 #define TABLESIZE       128
342 static TAILQ_HEAD(slpquehead, thread) slpque[TABLESIZE];
343 #define LOOKUP(x)       (((intptr_t)(x) >> 8) & (TABLESIZE - 1))
344
345 /*
346  * During autoconfiguration or after a panic, a sleep will simply
347  * lower the priority briefly to allow interrupts, then return.
348  * The priority to be used (safepri) is machine-dependent, thus this
349  * value is initialized and maintained in the machine-dependent layers.
350  * This priority will typically be 0, or the lowest priority
351  * that is safe for use on the interrupt stack; it can be made
352  * higher to block network software interrupts after panics.
353  */
354 int safepri;
355
356 void
357 sleepinit(void)
358 {
359         int i;
360
361         sched_quantum = hz/10;
362         hogticks = 2 * sched_quantum;
363         for (i = 0; i < TABLESIZE; i++)
364                 TAILQ_INIT(&slpque[i]);
365 }
366
367 /*
368  * General sleep call.  Suspends the current process until a wakeup is
369  * performed on the specified identifier.  The process will then be made
370  * runnable with the specified priority.  Sleeps at most timo/hz seconds
371  * (0 means no timeout).  If pri includes PCATCH flag, signals are checked
372  * before and after sleeping, else signals are not checked.  Returns 0 if
373  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
374  * signal needs to be delivered, ERESTART is returned if the current system
375  * call should be restarted if possible, and EINTR is returned if the system
376  * call should be interrupted by the signal (return EINTR).
377  *
378  * If the process has P_CURPROC set mi_switch() will not re-queue it to
379  * the userland scheduler queues because we are in a SSLEEP state.  If
380  * we are not the current process then we have to remove ourselves from
381  * the scheduler queues.
382  *
383  * YYY priority now unused
384  */
385 int
386 tsleep(ident, priority, wmesg, timo)
387         void *ident;
388         int priority, timo;
389         const char *wmesg;
390 {
391         struct thread *td = curthread;
392         struct proc *p = td->td_proc;           /* may be NULL */
393         int s, sig = 0, catch = priority & PCATCH;
394         int id = LOOKUP(ident);
395         struct callout_handle thandle;
396
397         /*
398          * NOTE: removed KTRPOINT, it could cause races due to blocking
399          * even in stable.  Just scrap it for now.
400          */
401         if (cold || panicstr) {
402                 /*
403                  * After a panic, or during autoconfiguration,
404                  * just give interrupts a chance, then just return;
405                  * don't run any other procs or panic below,
406                  * in case this is the idle process and already asleep.
407                  */
408                 crit_panicints();
409                 return (0);
410         }
411         KKASSERT(td != &mycpu->gd_idlethread);  /* you must be kidding! */
412         s = splhigh();
413         KASSERT(ident != NULL, ("tsleep: no ident"));
414         KASSERT(p == NULL || p->p_stat == SRUN, ("tsleep %p %s %d",
415                 ident, wmesg, p->p_stat));
416
417         crit_enter();
418         td->td_wchan = ident;
419         td->td_wmesg = wmesg;
420         if (p) 
421                 p->p_slptime = 0;
422         lwkt_deschedule_self();
423         TAILQ_INSERT_TAIL(&slpque[id], td, td_threadq);
424         if (timo)
425                 thandle = timeout(endtsleep, (void *)td, timo);
426         /*
427          * We put ourselves on the sleep queue and start our timeout
428          * before calling CURSIG, as we could stop there, and a wakeup
429          * or a SIGCONT (or both) could occur while we were stopped.
430          * A SIGCONT would cause us to be marked as SSLEEP
431          * without resuming us, thus we must be ready for sleep
432          * when CURSIG is called.  If the wakeup happens while we're
433          * stopped, td->td_wchan will be 0 upon return from CURSIG.
434          */
435         if (p) {
436                 if (catch) {
437                         p->p_flag |= P_SINTR;
438                         if ((sig = CURSIG(p))) {
439                                 if (td->td_wchan) {
440                                         unsleep(td);
441                                         lwkt_schedule_self();
442                                 }
443                                 p->p_stat = SRUN;
444                                 goto resume;
445                         }
446                         if (td->td_wchan == NULL) {
447                                 catch = 0;
448                                 goto resume;
449                         }
450                 } else {
451                         sig = 0;
452                 }
453
454                 /*
455                  * If we are not the current process we have to remove ourself
456                  * from the run queue.
457                  */
458                 KASSERT(p->p_stat == SRUN, ("PSTAT NOT SRUN %d %d", p->p_pid, p->p_stat));
459                 /*
460                  * If this is the current 'user' process schedule another one.
461                  */
462                 clrrunnable(p, SSLEEP);
463                 p->p_stats->p_ru.ru_nvcsw++;
464                 KKASSERT(td->td_release || (p->p_flag & P_CURPROC) == 0);
465                 mi_switch();
466                 KASSERT(p->p_stat == SRUN, ("tsleep: stat not srun"));
467         } else {
468                 lwkt_switch();
469         }
470 resume:
471         crit_exit();
472         if (p)
473                 p->p_flag &= ~P_SINTR;
474         splx(s);
475         if (td->td_flags & TDF_TIMEOUT) {
476                 td->td_flags &= ~TDF_TIMEOUT;
477                 if (sig == 0)
478                         return (EWOULDBLOCK);
479         } else if (timo) {
480                 untimeout(endtsleep, (void *)td, thandle);
481         }
482         if (p) {
483                 if (catch && (sig != 0 || (sig = CURSIG(p)))) {
484                         if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
485                                 return (EINTR);
486                         return (ERESTART);
487                 }
488         }
489         return (0);
490 }
491
492 #if 0
493
494 /*
495  * General sleep call.  Suspends the current process until a wakeup is
496  * performed on the specified xwait structure.  The process will then be made
497  * runnable with the specified priority.  Sleeps at most timo/hz seconds
498  * (0 means no timeout).  If pri includes PCATCH flag, signals are checked
499  * before and after sleeping, else signals are not checked.  Returns 0 if
500  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
501  * signal needs to be delivered, ERESTART is returned if the current system
502  * call should be restarted if possible, and EINTR is returned if the system
503  * call should be interrupted by the signal (return EINTR).
504  *
505  * If the passed generation number is different from the generation number
506  * in the xwait, return immediately.
507  */
508 int
509 xsleep(struct xwait *w, int priority, const char *wmesg, int timo, int *gen)
510 {
511         struct thread *td = curthread;
512         struct proc *p = td->td_proc;
513         int s, sig, catch = priority & PCATCH;
514         struct callout_handle thandle;
515
516 #ifdef KTRACE
517         if (KTRPOINT(td, KTR_CSW))
518                 ktrcsw(p->p_tracep, 1, 0);
519 #endif
520         if (cold || panicstr) {
521                 /*
522                  * After a panic, or during autoconfiguration,
523                  * just give interrupts a chance, then just return;
524                  * don't run any other procs or panic below,
525                  * in case this is the idle process and already asleep.
526                  */
527                 crit_panicints();
528                 return (0);
529         }
530         s = splhigh();
531         KASSERT(p != NULL, ("xsleep1"));
532         KASSERT(w != NULL && p->p_stat == SRUN, ("xsleep"));
533
534         /*
535          * If the generation number does not match we return immediately.
536          */
537         if (*gen != w->gen) {
538                 *gen = w->gen;
539                 splx(s);
540 #ifdef KTRACE
541                 if (KTRPOINT(td, KTR_CSW))
542                         ktrcsw(p->p_tracep, 0, 0);
543 #endif
544                 return(0);
545         }
546
547         p->p_wchan = w;
548         p->p_wmesg = wmesg;
549         p->p_slptime = 0;
550         p->p_flag |= P_XSLEEP;
551         TAILQ_INSERT_TAIL(&w->waitq, p, p_procq);
552         if (timo)
553                 thandle = timeout(endtsleep, (void *)p, timo);
554         /*
555          * We put ourselves on the sleep queue and start our timeout
556          * before calling CURSIG, as we could stop there, and a wakeup
557          * or a SIGCONT (or both) could occur while we were stopped.
558          * A SIGCONT would cause us to be marked as SSLEEP
559          * without resuming us, thus we must be ready for sleep
560          * when CURSIG is called.  If the wakeup happens while we're
561          * stopped, p->p_wchan will be 0 upon return from CURSIG.
562          */
563         if (catch) {
564                 p->p_flag |= P_SINTR;
565                 if ((sig = CURSIG(p))) {
566                         if (p->p_wchan) {
567                                 unsleep(p);
568                                 lwkt_schedule_self();
569                         }
570                         p->p_stat = SRUN;
571                         goto resume;
572                 }
573                 if (p->p_wchan == NULL) {
574                         catch = 0;
575                         goto resume;
576                 }
577         } else {
578                 sig = 0;
579         }
580         clrrunnable(p, SSLEEP);
581         p->p_stats->p_ru.ru_nvcsw++;
582         mi_switch();
583 resume:
584         *gen = w->gen;  /* update generation number */
585         splx(s);
586         p->p_flag &= ~P_SINTR;
587         if (p->p_flag & P_TIMEOUT) {
588                 p->p_flag &= ~P_TIMEOUT;
589                 if (sig == 0) {
590 #ifdef KTRACE
591                         if (KTRPOINT(td, KTR_CSW))
592                                 ktrcsw(p->p_tracep, 0, 0);
593 #endif
594                         return (EWOULDBLOCK);
595                 }
596         } else if (timo)
597                 untimeout(endtsleep, (void *)p, thandle);
598         if (catch && (sig != 0 || (sig = CURSIG(p)))) {
599 #ifdef KTRACE
600                 if (KTRPOINT(td, KTR_CSW))
601                         ktrcsw(p->p_tracep, 0, 0);
602 #endif
603                 if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
604                         return (EINTR);
605                 return (ERESTART);
606         }
607 #ifdef KTRACE
608         if (KTRPOINT(td, KTR_CSW))
609                 ktrcsw(p->p_tracep, 0, 0);
610 #endif
611         return (0);
612 }
613
614 #endif
615
616 /*
617  * Implement the timeout for tsleep.  We interlock against
618  * wchan when setting TDF_TIMEOUT.  For processes we remove
619  * the sleep if the process is stopped rather then sleeping,
620  * so it remains stopped.
621  */
622 static void
623 endtsleep(void *arg)
624 {
625         thread_t td = arg;
626         struct proc *p;
627         int s;
628
629         s = splhigh();
630         if (td->td_wchan) {
631                 td->td_flags |= TDF_TIMEOUT;
632                 if ((p = td->td_proc) != NULL) {
633                         if (p->p_stat == SSLEEP)
634                                 setrunnable(p);
635                         else
636                                 unsleep(td);
637                 } else {
638                         unsleep(td);
639                         lwkt_schedule(td);
640                 }
641         }
642         splx(s);
643 }
644
645 /*
646  * Remove a process from its wait queue
647  */
648 void
649 unsleep(struct thread *td)
650 {
651         int s;
652
653         s = splhigh();
654         if (td->td_wchan) {
655 #if 0
656                 if (p->p_flag & P_XSLEEP) {
657                         struct xwait *w = p->p_wchan;
658                         TAILQ_REMOVE(&w->waitq, p, p_procq);
659                         p->p_flag &= ~P_XSLEEP;
660                 } else
661 #endif
662                 TAILQ_REMOVE(&slpque[LOOKUP(td->td_wchan)], td, td_threadq);
663                 td->td_wchan = NULL;
664         }
665         splx(s);
666 }
667
668 #if 0
669 /*
670  * Make all processes sleeping on the explicit lock structure runnable.
671  */
672 void
673 xwakeup(struct xwait *w)
674 {
675         struct proc *p;
676         int s;
677
678         s = splhigh();
679         ++w->gen;
680         while ((p = TAILQ_FIRST(&w->waitq)) != NULL) {
681                 TAILQ_REMOVE(&w->waitq, p, p_procq);
682                 KASSERT(p->p_wchan == w && (p->p_flag & P_XSLEEP),
683                     ("xwakeup: wchan mismatch for %p (%p/%p) %08x", p, p->p_wchan, w, p->p_flag & P_XSLEEP));
684                 p->p_wchan = NULL;
685                 p->p_flag &= ~P_XSLEEP;
686                 if (p->p_stat == SSLEEP) {
687                         /* OPTIMIZED EXPANSION OF setrunnable(p); */
688                         if (p->p_slptime > 1)
689                                 updatepri(p);
690                         p->p_slptime = 0;
691                         p->p_stat = SRUN;
692                         if (p->p_flag & P_INMEM) {
693                                 setrunqueue(p);
694                                 maybe_resched(p);
695                         } else {
696                                 p->p_flag |= P_SWAPINREQ;
697                                 wakeup((caddr_t)&proc0);
698                         }
699                 }
700         }
701         splx(s);
702 }
703 #endif
704
705 /*
706  * Make all processes sleeping on the specified identifier runnable.
707  */
708 static void
709 _wakeup(void *ident, int count)
710 {
711         struct slpquehead *qp;
712         struct thread *td;
713         struct thread *ntd;
714         struct proc *p;
715         int s;
716         int id = LOOKUP(ident);
717
718         s = splhigh();
719         qp = &slpque[id];
720 restart:
721         for (td = TAILQ_FIRST(qp); td != NULL; td = ntd) {
722                 ntd = TAILQ_NEXT(td, td_threadq);
723                 if (td->td_wchan == ident) {
724                         TAILQ_REMOVE(qp, td, td_threadq);
725                         td->td_wchan = NULL;
726                         if ((p = td->td_proc) != NULL && p->p_stat == SSLEEP) {
727                                 /* OPTIMIZED EXPANSION OF setrunnable(p); */
728                                 if (p->p_slptime > 1)
729                                         updatepri(p);
730                                 p->p_slptime = 0;
731                                 p->p_stat = SRUN;
732                                 if (p->p_flag & P_INMEM) {
733                                         setrunqueue(p);
734                                         if (p->p_flag & P_CURPROC)
735                                             maybe_resched(p);
736                                 } else {
737                                         p->p_flag |= P_SWAPINREQ;
738                                         wakeup((caddr_t)&proc0);
739                                 }
740                                 /* END INLINE EXPANSION */
741                         } else if (p == NULL) {
742                                 lwkt_schedule(td);
743                         }
744                         if (--count == 0)
745                                 break;
746                         goto restart;
747                 }
748         }
749         splx(s);
750 }
751
752 void
753 wakeup(void *ident)
754 {
755     _wakeup(ident, 0);
756 }
757
758 void
759 wakeup_one(void *ident)
760 {
761     _wakeup(ident, 1);
762 }
763
764 /*
765  * The machine independent parts of mi_switch().
766  * Must be called at splstatclock() or higher.
767  */
768 void
769 mi_switch()
770 {
771         struct thread *td = curthread;
772         struct proc *p = td->td_proc;   /* XXX */
773         struct rlimit *rlim;
774         int x;
775         u_int64_t ttime;
776
777         /*
778          * XXX this spl is almost unnecessary.  It is partly to allow for
779          * sloppy callers that don't do it (issignal() via CURSIG() is the
780          * main offender).  It is partly to work around a bug in the i386
781          * cpu_switch() (the ipl is not preserved).  We ran for years
782          * without it.  I think there was only a interrupt latency problem.
783          * The main caller, tsleep(), does an splx() a couple of instructions
784          * after calling here.  The buggy caller, issignal(), usually calls
785          * here at spl0() and sometimes returns at splhigh().  The process
786          * then runs for a little too long at splhigh().  The ipl gets fixed
787          * when the process returns to user mode (or earlier).
788          *
789          * It would probably be better to always call here at spl0(). Callers
790          * are prepared to give up control to another process, so they must
791          * be prepared to be interrupted.  The clock stuff here may not
792          * actually need splstatclock().
793          */
794         x = splstatclock();
795         clear_resched();
796
797         /*
798          * Check if the process exceeds its cpu resource allocation.
799          * If over max, kill it.  Time spent in interrupts is not 
800          * included.  YYY 64 bit match is expensive.  Ick.
801          */
802         ttime = td->td_sticks + td->td_uticks;
803         if (p->p_stat != SZOMB && p->p_limit->p_cpulimit != RLIM_INFINITY &&
804             ttime > p->p_limit->p_cpulimit) {
805                 rlim = &p->p_rlimit[RLIMIT_CPU];
806                 if (ttime / (rlim_t)1000000 >= rlim->rlim_max) {
807                         killproc(p, "exceeded maximum CPU limit");
808                 } else {
809                         psignal(p, SIGXCPU);
810                         if (rlim->rlim_cur < rlim->rlim_max) {
811                                 /* XXX: we should make a private copy */
812                                 rlim->rlim_cur += 5;
813                         }
814                 }
815         }
816
817         /*
818          * Pick a new current process and record its start time.  If we
819          * are in a SSTOPped state we deschedule ourselves.  YYY this needs
820          * to be cleaned up, remember that LWKTs stay on their run queue
821          * which works differently then the user scheduler which removes
822          * the process from the runq when it runs it.
823          */
824         mycpu->gd_cnt.v_swtch++;
825         if (p->p_stat == SSTOP)
826                 lwkt_deschedule_self();
827         lwkt_switch();
828
829         splx(x);
830 }
831
832 /*
833  * Change process state to be runnable,
834  * placing it on the run queue if it is in memory,
835  * and awakening the swapper if it isn't in memory.
836  */
837 void
838 setrunnable(struct proc *p)
839 {
840         int s;
841
842         s = splhigh();
843         switch (p->p_stat) {
844         case 0:
845         case SRUN:
846         case SZOMB:
847         default:
848                 panic("setrunnable");
849         case SSTOP:
850         case SSLEEP:
851                 unsleep(p->p_thread);   /* e.g. when sending signals */
852                 break;
853
854         case SIDL:
855                 break;
856         }
857         p->p_stat = SRUN;
858         if (p->p_flag & P_INMEM)
859                 setrunqueue(p);
860         splx(s);
861         if (p->p_slptime > 1)
862                 updatepri(p);
863         p->p_slptime = 0;
864         if ((p->p_flag & P_INMEM) == 0) {
865                 p->p_flag |= P_SWAPINREQ;
866                 wakeup((caddr_t)&proc0);
867         } else {
868                 maybe_resched(p);
869         }
870 }
871
872 /*
873  * Change the process state to NOT be runnable, removing it from the run
874  * queue.  If P_CURPROC is not set and we are in SRUN the process is on the
875  * run queue (If P_INMEM is not set then it isn't because it is swapped).
876  */
877 void
878 clrrunnable(struct proc *p, int stat)
879 {
880         int s;
881
882         s = splhigh();
883         switch(p->p_stat) {
884         case SRUN:
885                 if (p->p_flag & P_ONRUNQ)
886                         remrunqueue(p);
887                 break;
888         default:
889                 break;
890         }
891         p->p_stat = stat;
892         splx(s);
893 }
894
895 /*
896  * Compute the priority of a process when running in user mode.
897  * Arrange to reschedule if the resulting priority is better
898  * than that of the current process.
899  *
900  * YYY real time / idle procs do not use p_priority XXX
901  */
902 void
903 resetpriority(struct proc *p)
904 {
905         unsigned int newpriority;
906         int opq;
907         int npq;
908
909         if (p->p_rtprio.type != RTP_PRIO_NORMAL)
910                 return;
911         newpriority = PUSER + p->p_estcpu / INVERSE_ESTCPU_WEIGHT +
912             NICE_WEIGHT * p->p_nice;
913         newpriority = min(newpriority, MAXPRI);
914         npq = newpriority / PPQ;
915         crit_enter();
916         opq = p->p_priority / PPQ;
917         if (p->p_stat == SRUN && (p->p_flag & P_ONRUNQ) && opq != npq) {
918                 /*
919                  * We have to move the process to another queue
920                  */
921                 remrunqueue(p);
922                 p->p_priority = newpriority;
923                 setrunqueue(p);
924         } else {
925                 /*
926                  * We can just adjust the priority and it will be picked
927                  * up later.
928                  */
929                 KKASSERT(opq == npq || (p->p_flag & P_ONRUNQ) == 0);
930                 p->p_priority = newpriority;
931         }
932         crit_exit();
933         maybe_resched(p);
934 }
935
936 /*
937  * Compute a tenex style load average of a quantity on
938  * 1, 5 and 15 minute intervals.
939  */
940 static void
941 loadav(void *arg)
942 {
943         int i, nrun;
944         struct loadavg *avg;
945         struct proc *p;
946
947         avg = &averunnable;
948         nrun = 0;
949         LIST_FOREACH(p, &allproc, p_list) {
950                 switch (p->p_stat) {
951                 case SRUN:
952                 case SIDL:
953                         nrun++;
954                 }
955         }
956         for (i = 0; i < 3; i++)
957                 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
958                     nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
959
960         /*
961          * Schedule the next update to occur after 5 seconds, but add a
962          * random variation to avoid synchronisation with processes that
963          * run at regular intervals.
964          */
965         callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)),
966             loadav, NULL);
967 }
968
969 /* ARGSUSED */
970 static void
971 sched_setup(dummy)
972         void *dummy;
973 {
974
975         callout_init(&loadav_callout);
976
977         /* Kick off timeout driven events by calling first time. */
978         roundrobin(NULL);
979         schedcpu(NULL);
980         loadav(NULL);
981 }
982
983 /*
984  * We adjust the priority of the current process.  The priority of
985  * a process gets worse as it accumulates CPU time.  The cpu usage
986  * estimator (p_estcpu) is increased here.  resetpriority() will
987  * compute a different priority each time p_estcpu increases by
988  * INVERSE_ESTCPU_WEIGHT
989  * (until MAXPRI is reached).  The cpu usage estimator ramps up
990  * quite quickly when the process is running (linearly), and decays
991  * away exponentially, at a rate which is proportionally slower when
992  * the system is busy.  The basic principle is that the system will
993  * 90% forget that the process used a lot of CPU time in 5 * loadav
994  * seconds.  This causes the system to favor processes which haven't
995  * run much recently, and to round-robin among other processes.
996  */
997 void
998 schedclock(p)
999         struct proc *p;
1000 {
1001
1002         p->p_cpticks++;
1003         p->p_estcpu = ESTCPULIM(p->p_estcpu + 1);
1004         if ((p->p_estcpu % INVERSE_ESTCPU_WEIGHT) == 0)
1005                 resetpriority(p);
1006 }
1007
1008 static
1009 void
1010 crit_panicints(void)
1011 {
1012     int s;
1013     int cpri;
1014
1015     s = splhigh();
1016     cpri = crit_panic_save();
1017     splx(safepri);
1018     crit_panic_restore(cpri);
1019     splx(s);
1020 }
1021