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.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
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.4 2003/06/20 02:09:56 dillon Exp $
43 #include "opt_ktrace.h"
45 #include <sys/param.h>
46 #include <sys/systm.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>
55 #include <sys/ktrace.h>
58 #include <machine/cpu.h>
59 #include <machine/ipl.h>
60 #include <machine/smp.h>
62 static void sched_setup __P((void *dummy));
63 SYSINIT(sched_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, sched_setup, NULL)
68 int sched_quantum; /* Roundrobin scheduling quantum in ticks. */
70 static struct callout loadav_callout;
72 struct loadavg averunnable =
73 { {0, 0, 0}, FSCALE }; /* load average, of runnable procs */
75 * Constants for averages over 1, 5, and 15 minutes
76 * when sampling at 5 second intervals.
78 static fixpt_t cexp[3] = {
79 0.9200444146293232 * FSCALE, /* exp(-1/12) */
80 0.9834714538216174 * FSCALE, /* exp(-1/60) */
81 0.9944598480048967 * FSCALE, /* exp(-1/180) */
84 static int curpriority_cmp __P((struct proc *p));
85 static void endtsleep __P((void *));
86 static void loadav __P((void *arg));
87 static void maybe_resched __P((struct proc *chk));
88 static void roundrobin __P((void *arg));
89 static void schedcpu __P((void *arg));
90 static void updatepri __P((struct proc *p));
93 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
97 new_val = sched_quantum * tick;
98 error = sysctl_handle_int(oidp, &new_val, 0, req);
99 if (error != 0 || req->newptr == NULL)
103 sched_quantum = new_val / tick;
104 hogticks = 2 * sched_quantum;
108 SYSCTL_PROC(_kern, OID_AUTO, quantum, CTLTYPE_INT|CTLFLAG_RW,
109 0, sizeof sched_quantum, sysctl_kern_quantum, "I", "");
112 * Compare priorities. Return:
113 * <0: priority of p < current priority
114 * 0: priority of p == current priority
115 * >0: priority of p > current priority
116 * The priorities are the normal priorities or the normal realtime priorities
117 * if p is on the same scheduler as curproc. Otherwise the process on the
118 * more realtimeish scheduler has lowest priority. As usual, a higher
119 * priority really means a lower priority.
125 int c_class, p_class;
127 c_class = RTP_PRIO_BASE(curproc->p_rtprio.type);
128 p_class = RTP_PRIO_BASE(p->p_rtprio.type);
129 if (p_class != c_class)
130 return (p_class - c_class);
131 if (p_class == RTP_PRIO_NORMAL)
132 return (((int)p->p_priority - (int)curpriority) / PPQ);
133 return ((int)p->p_rtprio.prio - (int)curproc->p_rtprio.prio);
137 * Arrange to reschedule if necessary, taking the priorities and
138 * schedulers into account.
144 struct proc *p = curproc; /* XXX */
147 * XXX idle scheduler still broken because proccess stays on idle
148 * scheduler during waits (such as when getting FS locks). If a
149 * standard process becomes runaway cpu-bound, the system can lockup
150 * due to idle-scheduler processes in wakeup never getting any cpu.
156 } else if (chk == p) {
157 /* We may need to yield if our priority has been raised. */
158 if (curpriority_cmp(chk) > 0)
160 } else if (curpriority_cmp(chk) < 0)
165 roundrobin_interval(void)
167 return (sched_quantum);
171 * Force switch among equal priority processes every 100ms.
179 struct proc *p = curproc; /* XXX */
184 forward_roundrobin();
186 if (p == 0 || RTP_PRIO_NEED_RR(p->p_rtprio.type))
190 timeout(roundrobin, NULL, sched_quantum);
194 * Constants for digital decay and forget:
195 * 90% of (p_estcpu) usage in 5 * loadav time
196 * 95% of (p_pctcpu) usage in 60 seconds (load insensitive)
197 * Note that, as ps(1) mentions, this can let percentages
198 * total over 100% (I've seen 137.9% for 3 processes).
200 * Note that schedclock() updates p_estcpu and p_cpticks asynchronously.
202 * We wish to decay away 90% of p_estcpu in (5 * loadavg) seconds.
203 * That is, the system wants to compute a value of decay such
204 * that the following for loop:
205 * for (i = 0; i < (5 * loadavg); i++)
209 * for all values of loadavg:
211 * Mathematically this loop can be expressed by saying:
212 * decay ** (5 * loadavg) ~= .1
214 * The system computes decay as:
215 * decay = (2 * loadavg) / (2 * loadavg + 1)
217 * We wish to prove that the system's computation of decay
218 * will always fulfill the equation:
219 * decay ** (5 * loadavg) ~= .1
221 * If we compute b as:
224 * decay = b / (b + 1)
226 * We now need to prove two things:
227 * 1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
228 * 2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
231 * For x close to zero, exp(x) =~ 1 + x, since
232 * exp(x) = 0! + x**1/1! + x**2/2! + ... .
233 * therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
234 * For x close to zero, ln(1+x) =~ x, since
235 * ln(1+x) = x - x**2/2 + x**3/3 - ... -1 < x < 1
236 * therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
240 * Solve (factor)**(power) =~ .1 given power (5*loadav):
241 * solving for factor,
242 * ln(factor) =~ (-2.30/5*loadav), or
243 * factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
244 * exp(-1/b) =~ (b-1)/b =~ b/(b+1). QED
247 * Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
249 * power*ln(b/(b+1)) =~ -2.30, or
250 * power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav. QED
252 * Actual power values for the implemented algorithm are as follows:
254 * power: 5.68 10.32 14.94 19.55
257 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
258 #define loadfactor(loadav) (2 * (loadav))
259 #define decay_cpu(loadfac, cpu) (((loadfac) * (cpu)) / ((loadfac) + FSCALE))
261 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
262 static fixpt_t ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
263 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
265 /* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */
266 static int fscale __unused = FSCALE;
267 SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, "");
270 * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
271 * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
272 * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
274 * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
275 * 1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
277 * If you don't want to bother with the faster/more-accurate formula, you
278 * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
279 * (more general) method of calculating the %age of CPU used by a process.
281 #define CCPU_SHIFT 11
284 * Recompute process priorities, every hz ticks.
291 register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
292 register struct proc *p;
293 register int realstathz, s;
295 realstathz = stathz ? stathz : hz;
296 LIST_FOREACH(p, &allproc, p_list) {
298 * Increment time in/out of memory and sleep time
299 * (if sleeping). We ignore overflow; with 16-bit int's
300 * (remember them?) overflow takes 45 days.
303 if (p->p_stat == SSLEEP || p->p_stat == SSTOP)
305 p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
307 * If the process has slept the entire second,
308 * stop recalculating its priority until it wakes up.
310 if (p->p_slptime > 1)
312 s = splhigh(); /* prevent state changes and protect run queue */
314 * p_pctcpu is only for ps.
316 #if (FSHIFT >= CCPU_SHIFT)
317 p->p_pctcpu += (realstathz == 100)?
318 ((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT):
319 100 * (((fixpt_t) p->p_cpticks)
320 << (FSHIFT - CCPU_SHIFT)) / realstathz;
322 p->p_pctcpu += ((FSCALE - ccpu) *
323 (p->p_cpticks * FSCALE / realstathz)) >> FSHIFT;
326 p->p_estcpu = decay_cpu(loadfac, p->p_estcpu);
328 if (p->p_priority >= PUSER) {
329 if ((p != curproc) &&
331 p->p_oncpu == 0xff && /* idle */
334 (p->p_flag & P_INMEM) &&
335 (p->p_priority / PPQ) != (p->p_usrpri / PPQ)) {
337 p->p_priority = p->p_usrpri;
340 p->p_priority = p->p_usrpri;
345 wakeup((caddr_t)&lbolt);
346 timeout(schedcpu, (void *)0, hz);
350 * Recalculate the priority of a process after it has slept for a while.
351 * For all load averages >= 1 and max p_estcpu of 255, sleeping for at
352 * least six times the loadfactor will decay p_estcpu to zero.
356 register struct proc *p;
358 register unsigned int newcpu = p->p_estcpu;
359 register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
361 if (p->p_slptime > 5 * loadfac)
364 p->p_slptime--; /* the first time was done in schedcpu */
365 while (newcpu && --p->p_slptime)
366 newcpu = decay_cpu(loadfac, newcpu);
367 p->p_estcpu = newcpu;
373 * We're only looking at 7 bits of the address; everything is
374 * aligned to 4, lots of things are aligned to greater powers
375 * of 2. Shift right by 8, i.e. drop the bottom 256 worth.
377 #define TABLESIZE 128
378 static TAILQ_HEAD(slpquehead, proc) slpque[TABLESIZE];
379 #define LOOKUP(x) (((intptr_t)(x) >> 8) & (TABLESIZE - 1))
382 * During autoconfiguration or after a panic, a sleep will simply
383 * lower the priority briefly to allow interrupts, then return.
384 * The priority to be used (safepri) is machine-dependent, thus this
385 * value is initialized and maintained in the machine-dependent layers.
386 * This priority will typically be 0, or the lowest priority
387 * that is safe for use on the interrupt stack; it can be made
388 * higher to block network software interrupts after panics.
397 sched_quantum = hz/10;
398 hogticks = 2 * sched_quantum;
399 for (i = 0; i < TABLESIZE; i++)
400 TAILQ_INIT(&slpque[i]);
404 * General sleep call. Suspends the current process until a wakeup is
405 * performed on the specified identifier. The process will then be made
406 * runnable with the specified priority. Sleeps at most timo/hz seconds
407 * (0 means no timeout). If pri includes PCATCH flag, signals are checked
408 * before and after sleeping, else signals are not checked. Returns 0 if
409 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a
410 * signal needs to be delivered, ERESTART is returned if the current system
411 * call should be restarted if possible, and EINTR is returned if the system
412 * call should be interrupted by the signal (return EINTR).
415 tsleep(ident, priority, wmesg, timo)
420 struct proc *p = curproc;
421 int s, sig, catch = priority & PCATCH;
422 struct callout_handle thandle;
425 if (p && KTRPOINT(p, KTR_CSW))
426 ktrcsw(p->p_tracep, 1, 0);
429 if (cold || panicstr) {
431 * After a panic, or during autoconfiguration,
432 * just give interrupts a chance, then just return;
433 * don't run any other procs or panic below,
434 * in case this is the idle process and already asleep.
440 KASSERT(p != NULL, ("tsleep1"));
441 KASSERT(ident != NULL && p->p_stat == SRUN, ("tsleep"));
443 * Process may be sitting on a slpque if asleep() was called, remove
444 * it before re-adding.
446 if (p->p_wchan != NULL)
452 p->p_priority = priority & PRIMASK;
453 TAILQ_INSERT_TAIL(&slpque[LOOKUP(ident)], p, p_procq);
455 thandle = timeout(endtsleep, (void *)p, timo);
457 * We put ourselves on the sleep queue and start our timeout
458 * before calling CURSIG, as we could stop there, and a wakeup
459 * or a SIGCONT (or both) could occur while we were stopped.
460 * A SIGCONT would cause us to be marked as SSLEEP
461 * without resuming us, thus we must be ready for sleep
462 * when CURSIG is called. If the wakeup happens while we're
463 * stopped, p->p_wchan will be 0 upon return from CURSIG.
466 p->p_flag |= P_SINTR;
467 if ((sig = CURSIG(p))) {
473 if (p->p_wchan == 0) {
480 p->p_stats->p_ru.ru_nvcsw++;
483 curpriority = p->p_usrpri;
485 p->p_flag &= ~P_SINTR;
486 if (p->p_flag & P_TIMEOUT) {
487 p->p_flag &= ~P_TIMEOUT;
490 if (KTRPOINT(p, KTR_CSW))
491 ktrcsw(p->p_tracep, 0, 0);
493 return (EWOULDBLOCK);
496 untimeout(endtsleep, (void *)p, thandle);
497 if (catch && (sig != 0 || (sig = CURSIG(p)))) {
499 if (KTRPOINT(p, KTR_CSW))
500 ktrcsw(p->p_tracep, 0, 0);
502 if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
507 if (KTRPOINT(p, KTR_CSW))
508 ktrcsw(p->p_tracep, 0, 0);
514 * asleep() - async sleep call. Place process on wait queue and return
515 * immediately without blocking. The process stays runnable until await()
516 * is called. If ident is NULL, remove process from wait queue if it is still
519 * Only the most recent sleep condition is effective when making successive
520 * calls to asleep() or when calling tsleep().
522 * The timeout, if any, is not initiated until await() is called. The sleep
523 * priority, signal, and timeout is specified in the asleep() call but may be
524 * overriden in the await() call.
526 * <<<<<<<< EXPERIMENTAL, UNTESTED >>>>>>>>>>
530 asleep(void *ident, int priority, const char *wmesg, int timo)
532 struct proc *p = curproc;
536 * splhigh() while manipulating sleep structures and slpque.
538 * Remove preexisting wait condition (if any) and place process
539 * on appropriate slpque, but do not put process to sleep.
544 if (p->p_wchan != NULL)
551 p->p_asleep.as_priority = priority;
552 p->p_asleep.as_timo = timo;
553 TAILQ_INSERT_TAIL(&slpque[LOOKUP(ident)], p, p_procq);
562 * await() - wait for async condition to occur. The process blocks until
563 * wakeup() is called on the most recent asleep() address. If wakeup is called
564 * priority to await(), await() winds up being a NOP.
566 * If await() is called more then once (without an intervening asleep() call),
567 * await() is still effectively a NOP but it calls mi_switch() to give other
568 * processes some cpu before returning. The process is left runnable.
570 * <<<<<<<< EXPERIMENTAL, UNTESTED >>>>>>>>>>
574 await(int priority, int timo)
576 struct proc *p = curproc;
581 if (p->p_wchan != NULL) {
582 struct callout_handle thandle;
587 * The call to await() can override defaults specified in
588 * the original asleep().
591 priority = p->p_asleep.as_priority;
593 timo = p->p_asleep.as_timo;
600 thandle = timeout(endtsleep, (void *)p, timo);
603 catch = priority & PCATCH;
606 p->p_flag |= P_SINTR;
607 if ((sig = CURSIG(p))) {
613 if (p->p_wchan == NULL) {
619 p->p_stats->p_ru.ru_nvcsw++;
622 curpriority = p->p_usrpri;
625 p->p_flag &= ~P_SINTR;
626 if (p->p_flag & P_TIMEOUT) {
627 p->p_flag &= ~P_TIMEOUT;
630 if (KTRPOINT(p, KTR_CSW))
631 ktrcsw(p->p_tracep, 0, 0);
633 return (EWOULDBLOCK);
636 untimeout(endtsleep, (void *)p, thandle);
637 if (catch && (sig != 0 || (sig = CURSIG(p)))) {
639 if (KTRPOINT(p, KTR_CSW))
640 ktrcsw(p->p_tracep, 0, 0);
642 if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
647 if (KTRPOINT(p, KTR_CSW))
648 ktrcsw(p->p_tracep, 0, 0);
652 * If as_priority is 0, await() has been called without an
653 * intervening asleep(). We are still effectively a NOP,
654 * but we call mi_switch() for safety.
657 if (p->p_asleep.as_priority == 0) {
658 p->p_stats->p_ru.ru_nvcsw++;
665 * clear p_asleep.as_priority as an indication that await() has been
666 * called. If await() is called again without an intervening asleep(),
667 * await() is still effectively a NOP but the above mi_switch() code
668 * is triggered as a safety.
670 p->p_asleep.as_priority = 0;
676 * Implement timeout for tsleep or asleep()/await()
678 * If process hasn't been awakened (wchan non-zero),
679 * set timeout flag and undo the sleep. If proc
680 * is stopped, just unsleep so it will remain stopped.
686 register struct proc *p;
689 p = (struct proc *)arg;
692 if (p->p_stat == SSLEEP)
696 p->p_flag |= P_TIMEOUT;
702 * Remove a process from its wait queue
706 register struct proc *p;
712 TAILQ_REMOVE(&slpque[LOOKUP(p->p_wchan)], p, p_procq);
719 * Make all processes sleeping on the specified identifier runnable.
723 register void *ident;
725 register struct slpquehead *qp;
726 register struct proc *p;
731 qp = &slpque[LOOKUP(ident)];
733 for (p = TAILQ_FIRST(qp); p != NULL; p = np) {
734 np = TAILQ_NEXT(p, p_procq);
735 if (p->p_wchan == ident) {
736 TAILQ_REMOVE(qp, p, p_procq);
738 if (p->p_stat == SSLEEP) {
739 /* OPTIMIZED EXPANSION OF setrunnable(p); */
740 if (p->p_slptime > 1)
744 if (p->p_flag & P_INMEM) {
748 p->p_flag |= P_SWAPINREQ;
749 wakeup((caddr_t)&proc0);
751 /* END INLINE EXPANSION */
760 * Make a process sleeping on the specified identifier runnable.
761 * May wake more than one process if a target process is currently
766 register void *ident;
768 register struct slpquehead *qp;
769 register struct proc *p;
774 qp = &slpque[LOOKUP(ident)];
777 for (p = TAILQ_FIRST(qp); p != NULL; p = np) {
778 np = TAILQ_NEXT(p, p_procq);
779 if (p->p_wchan == ident) {
780 TAILQ_REMOVE(qp, p, p_procq);
782 if (p->p_stat == SSLEEP) {
783 /* OPTIMIZED EXPANSION OF setrunnable(p); */
784 if (p->p_slptime > 1)
788 if (p->p_flag & P_INMEM) {
793 p->p_flag |= P_SWAPINREQ;
794 wakeup((caddr_t)&proc0);
796 /* END INLINE EXPANSION */
805 * The machine independent parts of mi_switch().
806 * Must be called at splstatclock() or higher.
811 struct timeval new_switchtime;
812 register struct proc *p = curproc; /* XXX */
813 register struct rlimit *rlim;
817 * XXX this spl is almost unnecessary. It is partly to allow for
818 * sloppy callers that don't do it (issignal() via CURSIG() is the
819 * main offender). It is partly to work around a bug in the i386
820 * cpu_switch() (the ipl is not preserved). We ran for years
821 * without it. I think there was only a interrupt latency problem.
822 * The main caller, tsleep(), does an splx() a couple of instructions
823 * after calling here. The buggy caller, issignal(), usually calls
824 * here at spl0() and sometimes returns at splhigh(). The process
825 * then runs for a little too long at splhigh(). The ipl gets fixed
826 * when the process returns to user mode (or earlier).
828 * It would probably be better to always call here at spl0(). Callers
829 * are prepared to give up control to another process, so they must
830 * be prepared to be interrupted. The clock stuff here may not
831 * actually need splstatclock().
836 #ifdef SIMPLELOCK_DEBUG
837 if (p->p_simple_locks)
838 printf("sleep: holding simple lock\n");
841 * Compute the amount of time during which the current
842 * process was running, and add that to its total so far.
844 microuptime(&new_switchtime);
845 if (timevalcmp(&new_switchtime, &mycpu->gd_switchtime, <)) {
846 printf("microuptime() went backwards (%ld.%06ld -> %ld.%06ld)\n",
847 mycpu->gd_switchtime.tv_sec, mycpu->gd_switchtime.tv_usec,
848 new_switchtime.tv_sec, new_switchtime.tv_usec);
849 new_switchtime = mycpu->gd_switchtime;
852 (new_switchtime.tv_usec - mycpu->gd_switchtime.tv_usec) +
853 (new_switchtime.tv_sec - mycpu->gd_switchtime.tv_sec) *
858 * Check if the process exceeds its cpu resource allocation.
859 * If over max, kill it.
861 if (p->p_stat != SZOMB && p->p_limit->p_cpulimit != RLIM_INFINITY &&
862 p->p_runtime > p->p_limit->p_cpulimit) {
863 rlim = &p->p_rlimit[RLIMIT_CPU];
864 if (p->p_runtime / (rlim_t)1000000 >= rlim->rlim_max) {
865 killproc(p, "exceeded maximum CPU limit");
868 if (rlim->rlim_cur < rlim->rlim_max) {
869 /* XXX: we should make a private copy */
876 * Pick a new current process and record its start time.
877 * YYY lwkt_switch() will run the heavy weight process restoration
878 * code, which removes the target thread and process from their
879 * respective run queues to temporarily mimic 5.x behavior.
880 * YYY the userland scheduler should pick only one user process
881 * at a time to run per cpu.
884 mycpu->gd_switchtime = new_switchtime;
887 if (mycpu->gd_switchtime.tv_sec == 0)
888 microuptime(&mycpu->gd_switchtime);
889 mycpu->gd_switchticks = ticks;
895 * Change process state to be runnable,
896 * placing it on the run queue if it is in memory,
897 * and awakening the swapper if it isn't in memory.
901 register struct proc *p;
911 panic("setrunnable");
914 unsleep(p); /* e.g. when sending signals */
921 if (p->p_flag & P_INMEM)
924 if (p->p_slptime > 1)
927 if ((p->p_flag & P_INMEM) == 0) {
928 p->p_flag |= P_SWAPINREQ;
929 wakeup((caddr_t)&proc0);
936 * Compute the priority of a process when running in user mode.
937 * Arrange to reschedule if the resulting priority is better
938 * than that of the current process.
942 register struct proc *p;
944 register unsigned int newpriority;
946 if (p->p_rtprio.type == RTP_PRIO_NORMAL) {
947 newpriority = PUSER + p->p_estcpu / INVERSE_ESTCPU_WEIGHT +
948 NICE_WEIGHT * p->p_nice;
949 newpriority = min(newpriority, MAXPRI);
950 p->p_usrpri = newpriority;
956 * Compute a tenex style load average of a quantity on
957 * 1, 5 and 15 minute intervals.
968 LIST_FOREACH(p, &allproc, p_list) {
975 for (i = 0; i < 3; i++)
976 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
977 nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
980 * Schedule the next update to occur after 5 seconds, but add a
981 * random variation to avoid synchronisation with processes that
982 * run at regular intervals.
984 callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)),
994 callout_init(&loadav_callout);
996 /* Kick off timeout driven events by calling first time. */
1003 * We adjust the priority of the current process. The priority of
1004 * a process gets worse as it accumulates CPU time. The cpu usage
1005 * estimator (p_estcpu) is increased here. resetpriority() will
1006 * compute a different priority each time p_estcpu increases by
1007 * INVERSE_ESTCPU_WEIGHT
1008 * (until MAXPRI is reached). The cpu usage estimator ramps up
1009 * quite quickly when the process is running (linearly), and decays
1010 * away exponentially, at a rate which is proportionally slower when
1011 * the system is busy. The basic principle is that the system will
1012 * 90% forget that the process used a lot of CPU time in 5 * loadav
1013 * seconds. This causes the system to favor processes which haven't
1014 * run much recently, and to round-robin among other processes.
1022 p->p_estcpu = ESTCPULIM(p->p_estcpu + 1);
1023 if ((p->p_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
1025 if (p->p_priority >= PUSER)
1026 p->p_priority = p->p_usrpri;