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