6dd4d5b6b5db04fc3c90600c70bf37988fefe6fb
[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.45 2005/06/26 04:36:31 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 int     ncpus2, ncpus2_shift, ncpus2_mask;
72 int     safepri;
73
74 static struct callout loadav_callout;
75 static struct callout roundrobin_callout;
76 static struct callout schedcpu_callout;
77
78 struct loadavg averunnable =
79         { {0, 0, 0}, FSCALE };  /* load average, of runnable procs */
80 /*
81  * Constants for averages over 1, 5, and 15 minutes
82  * when sampling at 5 second intervals.
83  */
84 static fixpt_t cexp[3] = {
85         0.9200444146293232 * FSCALE,    /* exp(-1/12) */
86         0.9834714538216174 * FSCALE,    /* exp(-1/60) */
87         0.9944598480048967 * FSCALE,    /* exp(-1/180) */
88 };
89
90 static void     endtsleep (void *);
91 static void     loadav (void *arg);
92 static void     roundrobin (void *arg);
93 static void     schedcpu (void *arg);
94 static void     updatepri (struct proc *p);
95
96 static int
97 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
98 {
99         int error, new_val;
100
101         new_val = sched_quantum * tick;
102         error = sysctl_handle_int(oidp, &new_val, 0, req);
103         if (error != 0 || req->newptr == NULL)
104                 return (error);
105         if (new_val < tick)
106                 return (EINVAL);
107         sched_quantum = new_val / tick;
108         hogticks = 2 * sched_quantum;
109         return (0);
110 }
111
112 SYSCTL_PROC(_kern, OID_AUTO, quantum, CTLTYPE_INT|CTLFLAG_RW,
113         0, sizeof sched_quantum, sysctl_kern_quantum, "I", "");
114
115 int 
116 roundrobin_interval(void)
117 {
118         return (sched_quantum);
119 }
120
121 /*
122  * Force switch among equal priority processes every 100ms. 
123  *
124  * WARNING!  The MP lock is not held on ipi message remotes.
125  */
126 #ifdef SMP
127
128 static void
129 roundrobin_remote(void *arg)
130 {
131         struct proc *p = lwkt_preempted_proc();
132         if (p == NULL || RTP_PRIO_NEED_RR(p->p_rtprio.type))
133                 need_user_resched();
134 }
135
136 #endif
137
138 static void
139 roundrobin(void *arg)
140 {
141         struct proc *p = lwkt_preempted_proc();
142         if (p == NULL || RTP_PRIO_NEED_RR(p->p_rtprio.type))
143                 need_user_resched();
144 #ifdef SMP
145         lwkt_send_ipiq_mask(mycpu->gd_other_cpus, roundrobin_remote, NULL);
146 #endif
147         callout_reset(&roundrobin_callout, sched_quantum, roundrobin, NULL);
148 }
149
150 #ifdef SMP
151
152 void
153 resched_cpus(u_int32_t mask)
154 {
155         lwkt_send_ipiq_mask(mask, roundrobin_remote, NULL);
156 }
157
158 #endif
159
160 /*
161  * The load average is scaled by FSCALE (2048 typ).  The estimated cpu is
162  * incremented at a rate of ESTCPUVFREQ per second (40hz typ), but this is
163  * divided up across all cpu bound processes running in the system so an
164  * individual process will get less under load.  ESTCPULIM typicaly caps
165  * out at ESTCPUMAX (around 376, or 11 nice levels).
166  *
167  * Generally speaking the decay equation needs to break-even on growth
168  * at the limit at all load levels >= 1.0, so if the estimated cpu for
169  * a process increases by (ESTVCPUFREQ / load) per second, then the decay
170  * should reach this value when estcpu reaches ESTCPUMAX.  That calculation
171  * is:
172  *
173  *      ESTCPUMAX * decay = ESTCPUVFREQ / load
174  *      decay = ESTCPUVFREQ / (load * ESTCPUMAX)
175  *      decay = estcpu * 0.053 / load
176  *
177  * If the load is less then 1.0 we assume a load of 1.0.
178  */
179
180 #define cload(loadav)   ((loadav) < FSCALE ? FSCALE : (loadav))
181 #define decay_cpu(loadav,estcpu)        \
182     ((estcpu) * (FSCALE * ESTCPUVFREQ / ESTCPUMAX) / cload(loadav))
183
184 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
185 static fixpt_t  ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
186 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
187
188 /* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */
189 static int      fscale __unused = FSCALE;
190 SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, "");
191
192 /*
193  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
194  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
195  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
196  *
197  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
198  *      1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
199  *
200  * If you don't want to bother with the faster/more-accurate formula, you
201  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
202  * (more general) method of calculating the %age of CPU used by a process.
203  */
204 #define CCPU_SHIFT      11
205
206 /*
207  * Recompute process priorities, once a second.
208  */
209 /* ARGSUSED */
210 static void
211 schedcpu(void *arg)
212 {
213         fixpt_t loadfac = averunnable.ldavg[0];
214         struct proc *p;
215         unsigned int ndecay;
216
217         FOREACH_PROC_IN_SYSTEM(p) {
218                 /*
219                  * Increment time in/out of memory and sleep time
220                  * (if sleeping).  We ignore overflow; with 16-bit int's
221                  * (remember them?) overflow takes 45 days.
222                  */
223                 p->p_swtime++;
224                 if (p->p_stat == SSLEEP || p->p_stat == SSTOP)
225                         p->p_slptime++;
226                 p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
227
228                 /*
229                  * If the process has slept the entire second,
230                  * stop recalculating its priority until it wakes up.
231                  *
232                  * Note that interactive calculations do not occur for
233                  * long sleeps (because that isn't necessarily indicative
234                  * of an interactive process).
235                  */
236                 if (p->p_slptime > 1)
237                         continue;
238                 /* prevent state changes and protect run queue */
239                 crit_enter();
240
241                 /*
242                  * p_cpticks runs at ESTCPUFREQ but must be divided by the
243                  * load average for par-100% use.  Higher p_interactive
244                  * values mean less interactive, lower values mean more 
245                  * interactive.
246                  */
247                 if ((((fixpt_t)p->p_cpticks * cload(loadfac)) >> FSHIFT)  >
248                     ESTCPUFREQ / 4) {
249                         p->p_usched->heuristic_estcpu(p, 1);
250                 } else {
251                         p->p_usched->heuristic_estcpu(p, -1);
252                 }
253                 /*
254                  * p_pctcpu is only for ps.
255                  */
256 #if     (FSHIFT >= CCPU_SHIFT)
257                 p->p_pctcpu += (ESTCPUFREQ == 100)?
258                         ((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT):
259                         100 * (((fixpt_t) p->p_cpticks)
260                                 << (FSHIFT - CCPU_SHIFT)) / ESTCPUFREQ;
261 #else
262                 p->p_pctcpu += ((FSCALE - ccpu) *
263                         (p->p_cpticks * FSCALE / ESTCPUFREQ)) >> FSHIFT;
264 #endif
265                 p->p_cpticks = 0;
266                 ndecay = decay_cpu(loadfac, p->p_estcpu);
267                 if (p->p_estcpu > ndecay)
268                         p->p_estcpu -= ndecay;
269                 else
270                         p->p_estcpu = 0;
271                 p->p_usched->resetpriority(p);
272                 crit_exit();
273         }
274         wakeup((caddr_t)&lbolt);
275         callout_reset(&schedcpu_callout, hz, schedcpu, NULL);
276 }
277
278 /*
279  * Recalculate the priority of a process after it has slept for a while.
280  * For all load averages >= 1 and max p_estcpu of 255, sleeping for at
281  * least six times the loadfactor will decay p_estcpu to zero.
282  */
283 static void
284 updatepri(struct proc *p)
285 {
286         unsigned int ndecay;
287
288         ndecay = decay_cpu(averunnable.ldavg[0], p->p_estcpu) * p->p_slptime;
289         if (p->p_estcpu > ndecay)
290                 p->p_estcpu -= ndecay;
291         else
292                 p->p_estcpu = 0;
293         p->p_usched->resetpriority(p);
294 }
295
296 /*
297  * We're only looking at 7 bits of the address; everything is
298  * aligned to 4, lots of things are aligned to greater powers
299  * of 2.  Shift right by 8, i.e. drop the bottom 256 worth.
300  */
301 #define TABLESIZE       128
302 static TAILQ_HEAD(slpquehead, thread) slpque[TABLESIZE];
303 #define LOOKUP(x)       (((intptr_t)(x) >> 8) & (TABLESIZE - 1))
304
305 /*
306  * During autoconfiguration or after a panic, a sleep will simply
307  * lower the priority briefly to allow interrupts, then return.
308  */
309
310 void
311 sleepinit(void)
312 {
313         int i;
314
315         sched_quantum = hz/10;
316         hogticks = 2 * sched_quantum;
317         for (i = 0; i < TABLESIZE; i++)
318                 TAILQ_INIT(&slpque[i]);
319 }
320
321 /*
322  * General sleep call.  Suspends the current process until a wakeup is
323  * performed on the specified identifier.  The process will then be made
324  * runnable with the specified priority.  Sleeps at most timo/hz seconds
325  * (0 means no timeout).  If flags includes PCATCH flag, signals are checked
326  * before and after sleeping, else signals are not checked.  Returns 0 if
327  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
328  * signal needs to be delivered, ERESTART is returned if the current system
329  * call should be restarted if possible, and EINTR is returned if the system
330  * call should be interrupted by the signal (return EINTR).
331  *
332  * Note that if we are a process, we release_curproc() before messing with
333  * the LWKT scheduler.
334  */
335 int
336 tsleep(void *ident, int flags, const char *wmesg, int timo)
337 {
338         struct thread *td = curthread;
339         struct proc *p = td->td_proc;           /* may be NULL */
340         int sig = 0, catch = flags & PCATCH;
341         int id = LOOKUP(ident);
342         int oldpri;
343         struct callout thandle;
344
345         /*
346          * NOTE: removed KTRPOINT, it could cause races due to blocking
347          * even in stable.  Just scrap it for now.
348          */
349         if (cold || panicstr) {
350                 /*
351                  * After a panic, or during autoconfiguration,
352                  * just give interrupts a chance, then just return;
353                  * don't run any other procs or panic below,
354                  * in case this is the idle process and already asleep.
355                  */
356                 splz();
357                 oldpri = td->td_pri & TDPRI_MASK;
358                 lwkt_setpri_self(safepri);
359                 lwkt_switch();
360                 lwkt_setpri_self(oldpri);
361                 return (0);
362         }
363         KKASSERT(td != &mycpu->gd_idlethread);  /* you must be kidding! */
364         crit_enter_quick(td);
365         KASSERT(ident != NULL, ("tsleep: no ident"));
366         KASSERT(p == NULL || p->p_stat == SRUN, ("tsleep %p %s %d",
367                 ident, wmesg, p->p_stat));
368
369         td->td_wchan = ident;
370         td->td_wmesg = wmesg;
371         td->td_wdomain = flags & PDOMAIN_MASK;
372         if (p) {
373                 if (flags & PNORESCHED)
374                         td->td_flags |= TDF_NORESCHED;
375                 p->p_usched->release_curproc(p);
376                 p->p_slptime = 0;
377         }
378         lwkt_deschedule_self(td);
379         TAILQ_INSERT_TAIL(&slpque[id], td, td_threadq);
380         if (timo) {
381                 callout_init(&thandle);
382                 callout_reset(&thandle, timo, endtsleep, td);
383         }
384         /*
385          * We put ourselves on the sleep queue and start our timeout
386          * before calling CURSIG, as we could stop there, and a wakeup
387          * or a SIGCONT (or both) could occur while we were stopped.
388          * A SIGCONT would cause us to be marked as SSLEEP
389          * without resuming us, thus we must be ready for sleep
390          * when CURSIG is called.  If the wakeup happens while we're
391          * stopped, td->td_wchan will be 0 upon return from CURSIG.
392          */
393         if (p) {
394                 if (catch) {
395                         p->p_flag |= P_SINTR;
396                         if ((sig = CURSIG(p))) {
397                                 if (td->td_wchan) {
398                                         unsleep(td);
399                                         lwkt_schedule_self(td);
400                                 }
401                                 p->p_stat = SRUN;
402                                 goto resume;
403                         }
404                         if (td->td_wchan == NULL) {
405                                 catch = 0;
406                                 goto resume;
407                         }
408                 } else {
409                         sig = 0;
410                 }
411
412                 /*
413                  * If we are not the current process we have to remove ourself
414                  * from the run queue.
415                  */
416                 KASSERT(p->p_stat == SRUN, ("PSTAT NOT SRUN %d %d", p->p_pid, p->p_stat));
417                 /*
418                  * If this is the current 'user' process schedule another one.
419                  */
420                 clrrunnable(p, SSLEEP);
421                 p->p_stats->p_ru.ru_nvcsw++;
422                 mi_switch(p);
423                 KASSERT(p->p_stat == SRUN, ("tsleep: stat not srun"));
424         } else {
425                 lwkt_switch();
426         }
427 resume:
428         if (p)
429                 p->p_flag &= ~P_SINTR;
430         crit_exit_quick(td);
431         td->td_flags &= ~TDF_NORESCHED;
432         if (td->td_flags & TDF_TIMEOUT) {
433                 td->td_flags &= ~TDF_TIMEOUT;
434                 if (sig == 0)
435                         return (EWOULDBLOCK);
436         } else if (timo) {
437                 callout_stop(&thandle);
438         } else if (td->td_wmesg) {
439                 /*
440                  * This can happen if a thread is woken up directly.  Clear
441                  * wmesg to avoid debugging confusion.
442                  */
443                 td->td_wmesg = NULL;
444         }
445         /* inline of iscaught() */
446         if (p) {
447                 if (catch && (sig != 0 || (sig = CURSIG(p)))) {
448                         if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
449                                 return (EINTR);
450                         return (ERESTART);
451                 }
452         }
453         return (0);
454 }
455
456 /*
457  * Implement the timeout for tsleep.  We interlock against
458  * wchan when setting TDF_TIMEOUT.  For processes we remove
459  * the sleep if the process is stopped rather then sleeping,
460  * so it remains stopped.
461  */
462 static void
463 endtsleep(void *arg)
464 {
465         thread_t td = arg;
466         struct proc *p;
467
468         crit_enter();
469         if (td->td_wchan) {
470                 td->td_flags |= TDF_TIMEOUT;
471                 if ((p = td->td_proc) != NULL) {
472                         if (p->p_stat == SSLEEP)
473                                 setrunnable(p);
474                         else
475                                 unsleep(td);
476                 } else {
477                         unsleep(td);
478                         lwkt_schedule(td);
479                 }
480         }
481         crit_exit();
482 }
483
484 /*
485  * Remove a process from its wait queue
486  */
487 void
488 unsleep(struct thread *td)
489 {
490         crit_enter();
491         if (td->td_wchan) {
492                 TAILQ_REMOVE(&slpque[LOOKUP(td->td_wchan)], td, td_threadq);
493                 td->td_wchan = NULL;
494         }
495         crit_exit();
496 }
497
498 /*
499  * Make all processes sleeping on the specified identifier runnable.
500  */
501 static void
502 _wakeup(void *ident, int domain, int count)
503 {
504         struct slpquehead *qp;
505         struct thread *td;
506         struct thread *ntd;
507         struct proc *p;
508         int id = LOOKUP(ident);
509
510         crit_enter();
511         qp = &slpque[id];
512 restart:
513         for (td = TAILQ_FIRST(qp); td != NULL; td = ntd) {
514                 ntd = TAILQ_NEXT(td, td_threadq);
515                 if (td->td_wchan == ident && td->td_wdomain == domain) {
516                         TAILQ_REMOVE(qp, td, td_threadq);
517                         td->td_wchan = NULL;
518                         if ((p = td->td_proc) != NULL && p->p_stat == SSLEEP) {
519                                 /* OPTIMIZED EXPANSION OF setrunnable(p); */
520                                 if (p->p_slptime > 1)
521                                         updatepri(p);
522                                 p->p_slptime = 0;
523                                 p->p_stat = SRUN;
524                                 if (p->p_flag & P_INMEM) {
525                                         /*
526                                          * LWKT scheduled now, there is no
527                                          * userland runq interaction until
528                                          * the thread tries to return to user
529                                          * mode.
530                                          *
531                                          * setrunqueue(p); 
532                                          */
533                                         lwkt_schedule(td);
534                                 } else {
535                                         p->p_flag |= P_SWAPINREQ;
536                                         wakeup((caddr_t)&proc0);
537                                 }
538                                 /* END INLINE EXPANSION */
539                         } else if (p == NULL) {
540                                 lwkt_schedule(td);
541                         }
542                         if (--count == 0)
543                                 break;
544                         goto restart;
545                 }
546         }
547         crit_exit();
548 }
549
550 void
551 wakeup(void *ident)
552 {
553     _wakeup(ident, 0, 0);
554 }
555
556 void
557 wakeup_one(void *ident)
558 {
559     _wakeup(ident, 0, 1);
560 }
561
562 void
563 wakeup_domain(void *ident, int domain)
564 {
565     _wakeup(ident, domain, 0);
566 }
567
568 void
569 wakeup_domain_one(void *ident, int domain)
570 {
571     _wakeup(ident, domain, 1);
572 }
573
574 /*
575  * The machine independent parts of mi_switch().
576  *
577  * 'p' must be the current process.
578  */
579 void
580 mi_switch(struct proc *p)
581 {
582         thread_t td = p->p_thread;
583         struct rlimit *rlim;
584         u_int64_t ttime;
585
586         KKASSERT(td == mycpu->gd_curthread);
587
588         crit_enter_quick(td);
589
590         /*
591          * Check if the process exceeds its cpu resource allocation.
592          * If over max, kill it.  Time spent in interrupts is not 
593          * included.  YYY 64 bit match is expensive.  Ick.
594          */
595         ttime = td->td_sticks + td->td_uticks;
596         if (p->p_stat != SZOMB && p->p_limit->p_cpulimit != RLIM_INFINITY &&
597             ttime > p->p_limit->p_cpulimit) {
598                 rlim = &p->p_rlimit[RLIMIT_CPU];
599                 if (ttime / (rlim_t)1000000 >= rlim->rlim_max) {
600                         killproc(p, "exceeded maximum CPU limit");
601                 } else {
602                         psignal(p, SIGXCPU);
603                         if (rlim->rlim_cur < rlim->rlim_max) {
604                                 /* XXX: we should make a private copy */
605                                 rlim->rlim_cur += 5;
606                         }
607                 }
608         }
609
610         /*
611          * If we are in a SSTOPped state we deschedule ourselves.  
612          * YYY this needs to be cleaned up, remember that LWKTs stay on
613          * their run queue which works differently then the user scheduler
614          * which removes the process from the runq when it runs it.
615          */
616         mycpu->gd_cnt.v_swtch++;
617         if (p->p_stat == SSTOP)
618                 lwkt_deschedule_self(td);
619         lwkt_switch();
620         crit_exit_quick(td);
621 }
622
623 /*
624  * Change process state to be runnable,
625  * placing it on the run queue if it is in memory,
626  * and awakening the swapper if it isn't in memory.
627  */
628 void
629 setrunnable(struct proc *p)
630 {
631         crit_enter();
632
633         switch (p->p_stat) {
634         case 0:
635         case SRUN:
636         case SZOMB:
637         default:
638                 panic("setrunnable");
639         case SSTOP:
640         case SSLEEP:
641                 unsleep(p->p_thread);   /* e.g. when sending signals */
642                 break;
643
644         case SIDL:
645                 break;
646         }
647         p->p_stat = SRUN;
648
649         /*
650          * The process is controlled by LWKT at this point, we do not mess
651          * around with the userland scheduler until the thread tries to 
652          * return to user mode.
653          */
654         if (p->p_flag & P_INMEM)
655                 lwkt_schedule(p->p_thread);
656         crit_exit();
657         if (p->p_slptime > 1)
658                 updatepri(p);
659         p->p_slptime = 0;
660         if ((p->p_flag & P_INMEM) == 0) {
661                 p->p_flag |= P_SWAPINREQ;
662                 wakeup((caddr_t)&proc0);
663         }
664 }
665
666 /*
667  * Yield / synchronous reschedule.  This is a bit tricky because the trap
668  * code might have set a lazy release on the switch function.   Setting
669  * P_PASSIVE_ACQ will ensure that the lazy release executes when we call
670  * switch, and that we are given a greater chance of affinity with our
671  * current cpu.
672  *
673  * We call lwkt_setpri_self() to rotate our thread to the end of the lwkt
674  * run queue.  lwkt_switch() will also execute any assigned passive release
675  * (which usually calls release_curproc()), allowing a same/higher priority
676  * process to be designated as the current process.  
677  *
678  * While it is possible for a lower priority process to be designated,
679  * it's call to lwkt_maybe_switch() in acquire_curproc() will likely
680  * round-robin back to us and we will be able to re-acquire the current
681  * process designation.
682  */
683 void
684 uio_yield(void)
685 {
686         struct thread *td = curthread;
687         struct proc *p = td->td_proc;
688
689         lwkt_setpri_self(td->td_pri & TDPRI_MASK);
690         if (p) {
691                 p->p_flag |= P_PASSIVE_ACQ;
692                 lwkt_switch();
693                 p->p_flag &= ~P_PASSIVE_ACQ;
694         } else {
695                 lwkt_switch();
696         }
697 }
698
699 /*
700  * Change the process state to NOT be runnable, removing it from the run
701  * queue.
702  */
703 void
704 clrrunnable(struct proc *p, int stat)
705 {
706         crit_enter_quick(p->p_thread);
707         if (p->p_stat == SRUN && (p->p_flag & P_ONRUNQ))
708                 p->p_usched->remrunqueue(p);
709         p->p_stat = stat;
710         crit_exit_quick(p->p_thread);
711 }
712
713 /*
714  * Compute a tenex style load average of a quantity on
715  * 1, 5 and 15 minute intervals.
716  */
717 static void
718 loadav(void *arg)
719 {
720         int i, nrun;
721         struct loadavg *avg;
722         struct proc *p;
723         thread_t td;
724
725         avg = &averunnable;
726         nrun = 0;
727         FOREACH_PROC_IN_SYSTEM(p) {
728                 switch (p->p_stat) {
729                 case SRUN:
730                         if ((td = p->p_thread) == NULL)
731                                 break;
732                         if (td->td_flags & TDF_BLOCKED)
733                                 break;
734                         /* fall through */
735                 case SIDL:
736                         nrun++;
737                         break;
738                 default:
739                         break;
740                 }
741         }
742         for (i = 0; i < 3; i++)
743                 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
744                     nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
745
746         /*
747          * Schedule the next update to occur after 5 seconds, but add a
748          * random variation to avoid synchronisation with processes that
749          * run at regular intervals.
750          */
751         callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)),
752             loadav, NULL);
753 }
754
755 /* ARGSUSED */
756 static void
757 sched_setup(void *dummy)
758 {
759         callout_init(&loadav_callout);
760         callout_init(&roundrobin_callout);
761         callout_init(&schedcpu_callout);
762
763         /* Kick off timeout driven events by calling first time. */
764         roundrobin(NULL);
765         schedcpu(NULL);
766         loadav(NULL);
767 }
768
769 /*
770  * We adjust the priority of the current process.  The priority of
771  * a process gets worse as it accumulates CPU time.  The cpu usage
772  * estimator (p_estcpu) is increased here.  resetpriority() will
773  * compute a different priority each time p_estcpu increases by
774  * INVERSE_ESTCPU_WEIGHT * (until MAXPRI is reached).
775  *
776  * The cpu usage estimator ramps up quite quickly when the process is 
777  * running (linearly), and decays away exponentially, at a rate which
778  * is proportionally slower when the system is busy.  The basic principle
779  * is that the system will 90% forget that the process used a lot of CPU
780  * time in 5 * loadav seconds.  This causes the system to favor processes
781  * which haven't run much recently, and to round-robin among other processes.
782  *
783  * The actual schedulerclock interrupt rate is ESTCPUFREQ, but we generally
784  * want to ramp-up at a faster rate, ESTCPUVFREQ, so p_estcpu is scaled
785  * by (ESTCPUVFREQ / ESTCPUFREQ).  You can control the ramp-up/ramp-down
786  * rate by adjusting ESTCPUVFREQ in sys/proc.h in integer multiples
787  * of ESTCPUFREQ.
788  *
789  * WARNING! called from a fast-int or an IPI, the MP lock MIGHT NOT BE HELD
790  * and we cannot block.
791  */
792 void
793 schedulerclock(void *dummy)
794 {
795         struct thread *td;
796         struct proc *p;
797
798         td = curthread;
799         if ((p = td->td_proc) != NULL) {
800                 p->p_cpticks++;         /* cpticks runs at ESTCPUFREQ */
801                 p->p_estcpu = ESTCPULIM(p->p_estcpu + ESTCPUVFREQ / ESTCPUFREQ);
802                 if (try_mplock()) {
803                         p->p_usched->resetpriority(p);
804                         rel_mplock();
805                 }
806         }
807 }
808