Home | History | Annotate | Line # | Download | only in kern
kern_synch.c revision 1.63
      1 /*	$NetBSD: kern_synch.c,v 1.63 1999/07/26 23:00:59 thorpej Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
      9  * NASA Ames Research Center.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  * 3. All advertising materials mentioning features or use of this software
     20  *    must display the following acknowledgement:
     21  *	This product includes software developed by the NetBSD
     22  *	Foundation, Inc. and its contributors.
     23  * 4. Neither the name of The NetBSD Foundation nor the names of its
     24  *    contributors may be used to endorse or promote products derived
     25  *    from this software without specific prior written permission.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     37  * POSSIBILITY OF SUCH DAMAGE.
     38  */
     39 
     40 /*-
     41  * Copyright (c) 1982, 1986, 1990, 1991, 1993
     42  *	The Regents of the University of California.  All rights reserved.
     43  * (c) UNIX System Laboratories, Inc.
     44  * All or some portions of this file are derived from material licensed
     45  * to the University of California by American Telephone and Telegraph
     46  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     47  * the permission of UNIX System Laboratories, Inc.
     48  *
     49  * Redistribution and use in source and binary forms, with or without
     50  * modification, are permitted provided that the following conditions
     51  * are met:
     52  * 1. Redistributions of source code must retain the above copyright
     53  *    notice, this list of conditions and the following disclaimer.
     54  * 2. Redistributions in binary form must reproduce the above copyright
     55  *    notice, this list of conditions and the following disclaimer in the
     56  *    documentation and/or other materials provided with the distribution.
     57  * 3. All advertising materials mentioning features or use of this software
     58  *    must display the following acknowledgement:
     59  *	This product includes software developed by the University of
     60  *	California, Berkeley and its contributors.
     61  * 4. Neither the name of the University nor the names of its contributors
     62  *    may be used to endorse or promote products derived from this software
     63  *    without specific prior written permission.
     64  *
     65  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     66  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     67  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     68  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     69  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     70  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     71  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     72  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     73  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     74  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     75  * SUCH DAMAGE.
     76  *
     77  *	@(#)kern_synch.c	8.9 (Berkeley) 5/19/95
     78  */
     79 
     80 #include "opt_ddb.h"
     81 #include "opt_ktrace.h"
     82 
     83 #include <sys/param.h>
     84 #include <sys/systm.h>
     85 #include <sys/proc.h>
     86 #include <sys/kernel.h>
     87 #include <sys/buf.h>
     88 #include <sys/signalvar.h>
     89 #include <sys/resourcevar.h>
     90 #include <vm/vm.h>
     91 #include <sys/sched.h>
     92 
     93 #include <uvm/uvm_extern.h>
     94 
     95 #ifdef KTRACE
     96 #include <sys/ktrace.h>
     97 #endif
     98 
     99 #define NICE_WEIGHT 2			/* priorities per nice level */
    100 #define	PPQ	(128 / NQS)		/* priorities per queue */
    101 
    102 #define	ESTCPULIM(e) min((e), NICE_WEIGHT * PRIO_MAX - PPQ)
    103 
    104 #include <machine/cpu.h>
    105 
    106 u_char	curpriority;		/* usrpri of curproc */
    107 int	lbolt;			/* once a second sleep address */
    108 
    109 void roundrobin __P((void *));
    110 void schedcpu __P((void *));
    111 void updatepri __P((struct proc *));
    112 void endtsleep __P((void *));
    113 
    114 __inline void awaken __P((struct proc *));
    115 
    116 /*
    117  * Force switch among equal priority processes every 100ms.
    118  */
    119 /* ARGSUSED */
    120 void
    121 roundrobin(arg)
    122 	void *arg;
    123 {
    124 
    125 	need_resched();
    126 	timeout(roundrobin, NULL, hz / 10);
    127 }
    128 
    129 /*
    130  * Constants for digital decay and forget:
    131  *	90% of (p_estcpu) usage in 5 * loadav time
    132  *	95% of (p_pctcpu) usage in 60 seconds (load insensitive)
    133  *          Note that, as ps(1) mentions, this can let percentages
    134  *          total over 100% (I've seen 137.9% for 3 processes).
    135  *
    136  * Note that hardclock updates p_estcpu and p_cpticks independently.
    137  *
    138  * We wish to decay away 90% of p_estcpu in (5 * loadavg) seconds.
    139  * That is, the system wants to compute a value of decay such
    140  * that the following for loop:
    141  * 	for (i = 0; i < (5 * loadavg); i++)
    142  * 		p_estcpu *= decay;
    143  * will compute
    144  * 	p_estcpu *= 0.1;
    145  * for all values of loadavg:
    146  *
    147  * Mathematically this loop can be expressed by saying:
    148  * 	decay ** (5 * loadavg) ~= .1
    149  *
    150  * The system computes decay as:
    151  * 	decay = (2 * loadavg) / (2 * loadavg + 1)
    152  *
    153  * We wish to prove that the system's computation of decay
    154  * will always fulfill the equation:
    155  * 	decay ** (5 * loadavg) ~= .1
    156  *
    157  * If we compute b as:
    158  * 	b = 2 * loadavg
    159  * then
    160  * 	decay = b / (b + 1)
    161  *
    162  * We now need to prove two things:
    163  *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
    164  *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
    165  *
    166  * Facts:
    167  *         For x close to zero, exp(x) =~ 1 + x, since
    168  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
    169  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
    170  *         For x close to zero, ln(1+x) =~ x, since
    171  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
    172  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
    173  *         ln(.1) =~ -2.30
    174  *
    175  * Proof of (1):
    176  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
    177  *	solving for factor,
    178  *      ln(factor) =~ (-2.30/5*loadav), or
    179  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
    180  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
    181  *
    182  * Proof of (2):
    183  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
    184  *	solving for power,
    185  *      power*ln(b/(b+1)) =~ -2.30, or
    186  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
    187  *
    188  * Actual power values for the implemented algorithm are as follows:
    189  *      loadav: 1       2       3       4
    190  *      power:  5.68    10.32   14.94   19.55
    191  */
    192 
    193 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
    194 #define	loadfactor(loadav)	(2 * (loadav))
    195 #define	decay_cpu(loadfac, cpu)	(((loadfac) * (cpu)) / ((loadfac) + FSCALE))
    196 
    197 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
    198 fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;		/* exp(-1/20) */
    199 
    200 /*
    201  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
    202  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
    203  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
    204  *
    205  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
    206  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
    207  *
    208  * If you dont want to bother with the faster/more-accurate formula, you
    209  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
    210  * (more general) method of calculating the %age of CPU used by a process.
    211  */
    212 #define	CCPU_SHIFT	11
    213 
    214 /*
    215  * Recompute process priorities, every hz ticks.
    216  */
    217 /* ARGSUSED */
    218 void
    219 schedcpu(arg)
    220 	void *arg;
    221 {
    222 	register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
    223 	register struct proc *p;
    224 	register int s;
    225 	register unsigned int newcpu;
    226 
    227 	wakeup((caddr_t)&lbolt);
    228 	proclist_lock_read();
    229 	for (p = allproc.lh_first; p != 0; p = p->p_list.le_next) {
    230 		/*
    231 		 * Increment time in/out of memory and sleep time
    232 		 * (if sleeping).  We ignore overflow; with 16-bit int's
    233 		 * (remember them?) overflow takes 45 days.
    234 		 */
    235 		p->p_swtime++;
    236 		if (p->p_stat == SSLEEP || p->p_stat == SSTOP)
    237 			p->p_slptime++;
    238 		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
    239 		/*
    240 		 * If the process has slept the entire second,
    241 		 * stop recalculating its priority until it wakes up.
    242 		 */
    243 		if (p->p_slptime > 1)
    244 			continue;
    245 		s = splstatclock();	/* prevent state changes */
    246 		/*
    247 		 * p_pctcpu is only for ps.
    248 		 */
    249 		KASSERT(profhz);
    250 #if	(FSHIFT >= CCPU_SHIFT)
    251 		p->p_pctcpu += (profhz == 100)?
    252 			((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT):
    253                 	100 * (((fixpt_t) p->p_cpticks)
    254 				<< (FSHIFT - CCPU_SHIFT)) / profhz;
    255 #else
    256 		p->p_pctcpu += ((FSCALE - ccpu) *
    257 			(p->p_cpticks * FSCALE / profhz)) >> FSHIFT;
    258 #endif
    259 		p->p_cpticks = 0;
    260 		newcpu = (u_int)decay_cpu(loadfac, p->p_estcpu);
    261 		p->p_estcpu = newcpu;
    262 		resetpriority(p);
    263 		if (p->p_priority >= PUSER) {
    264 			if ((p != curproc) &&
    265 			    p->p_stat == SRUN &&
    266 			    (p->p_flag & P_INMEM) &&
    267 			    (p->p_priority / PPQ) != (p->p_usrpri / PPQ)) {
    268 				remrunqueue(p);
    269 				p->p_priority = p->p_usrpri;
    270 				setrunqueue(p);
    271 			} else
    272 				p->p_priority = p->p_usrpri;
    273 		}
    274 		splx(s);
    275 	}
    276 	proclist_unlock_read();
    277 	uvm_meter();
    278 	timeout(schedcpu, (void *)0, hz);
    279 }
    280 
    281 /*
    282  * Recalculate the priority of a process after it has slept for a while.
    283  * For all load averages >= 1 and max p_estcpu of 255, sleeping for at
    284  * least six times the loadfactor will decay p_estcpu to zero.
    285  */
    286 void
    287 updatepri(p)
    288 	register struct proc *p;
    289 {
    290 	register unsigned int newcpu = p->p_estcpu;
    291 	register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
    292 
    293 	if (p->p_slptime > 5 * loadfac)
    294 		p->p_estcpu = 0;
    295 	else {
    296 		p->p_slptime--;	/* the first time was done in schedcpu */
    297 		while (newcpu && --p->p_slptime)
    298 			newcpu = (int) decay_cpu(loadfac, newcpu);
    299 		p->p_estcpu = newcpu;
    300 	}
    301 	resetpriority(p);
    302 }
    303 
    304 /*
    305  * We're only looking at 7 bits of the address; everything is
    306  * aligned to 4, lots of things are aligned to greater powers
    307  * of 2.  Shift right by 8, i.e. drop the bottom 256 worth.
    308  */
    309 #define TABLESIZE	128
    310 #define LOOKUP(x)	(((long)(x) >> 8) & (TABLESIZE - 1))
    311 struct slpque {
    312 	struct proc *sq_head;
    313 	struct proc **sq_tailp;
    314 } slpque[TABLESIZE];
    315 
    316 /*
    317  * During autoconfiguration or after a panic, a sleep will simply
    318  * lower the priority briefly to allow interrupts, then return.
    319  * The priority to be used (safepri) is machine-dependent, thus this
    320  * value is initialized and maintained in the machine-dependent layers.
    321  * This priority will typically be 0, or the lowest priority
    322  * that is safe for use on the interrupt stack; it can be made
    323  * higher to block network software interrupts after panics.
    324  */
    325 int safepri;
    326 
    327 /*
    328  * General sleep call.  Suspends the current process until a wakeup is
    329  * performed on the specified identifier.  The process will then be made
    330  * runnable with the specified priority.  Sleeps at most timo/hz seconds
    331  * (0 means no timeout).  If pri includes PCATCH flag, signals are checked
    332  * before and after sleeping, else signals are not checked.  Returns 0 if
    333  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
    334  * signal needs to be delivered, ERESTART is returned if the current system
    335  * call should be restarted if possible, and EINTR is returned if the system
    336  * call should be interrupted by the signal (return EINTR).
    337  */
    338 int
    339 tsleep(ident, priority, wmesg, timo)
    340 	void *ident;
    341 	int priority, timo;
    342 	const char *wmesg;
    343 {
    344 	register struct proc *p = curproc;
    345 	register struct slpque *qp;
    346 	register int s;
    347 	int sig, catch = priority & PCATCH;
    348 	extern int cold;
    349 	void endtsleep __P((void *));
    350 
    351 	if (cold || panicstr) {
    352 		/*
    353 		 * After a panic, or during autoconfiguration,
    354 		 * just give interrupts a chance, then just return;
    355 		 * don't run any other procs or panic below,
    356 		 * in case this is the idle process and already asleep.
    357 		 */
    358 		s = splhigh();
    359 		splx(safepri);
    360 		splx(s);
    361 		return (0);
    362 	}
    363 
    364 #ifdef KTRACE
    365 	if (KTRPOINT(p, KTR_CSW))
    366 		ktrcsw(p->p_tracep, 1, 0);
    367 #endif
    368 	s = splhigh();
    369 
    370 #ifdef DIAGNOSTIC
    371 	if (ident == NULL || p->p_stat != SRUN || p->p_back)
    372 		panic("tsleep");
    373 #endif
    374 	p->p_wchan = ident;
    375 	p->p_wmesg = wmesg;
    376 	p->p_slptime = 0;
    377 	p->p_priority = priority & PRIMASK;
    378 	qp = &slpque[LOOKUP(ident)];
    379 	if (qp->sq_head == 0)
    380 		qp->sq_head = p;
    381 	else
    382 		*qp->sq_tailp = p;
    383 	*(qp->sq_tailp = &p->p_forw) = 0;
    384 	if (timo)
    385 		timeout(endtsleep, (void *)p, timo);
    386 	/*
    387 	 * We put ourselves on the sleep queue and start our timeout
    388 	 * before calling CURSIG, as we could stop there, and a wakeup
    389 	 * or a SIGCONT (or both) could occur while we were stopped.
    390 	 * A SIGCONT would cause us to be marked as SSLEEP
    391 	 * without resuming us, thus we must be ready for sleep
    392 	 * when CURSIG is called.  If the wakeup happens while we're
    393 	 * stopped, p->p_wchan will be 0 upon return from CURSIG.
    394 	 */
    395 	if (catch) {
    396 		p->p_flag |= P_SINTR;
    397 		if ((sig = CURSIG(p)) != 0) {
    398 			if (p->p_wchan)
    399 				unsleep(p);
    400 			p->p_stat = SRUN;
    401 			goto resume;
    402 		}
    403 		if (p->p_wchan == 0) {
    404 			catch = 0;
    405 			goto resume;
    406 		}
    407 	} else
    408 		sig = 0;
    409 	p->p_stat = SSLEEP;
    410 	p->p_stats->p_ru.ru_nvcsw++;
    411 	mi_switch();
    412 #ifdef	DDB
    413 	/* handy breakpoint location after process "wakes" */
    414 	asm(".globl bpendtsleep ; bpendtsleep:");
    415 #endif
    416 resume:
    417 	curpriority = p->p_usrpri;
    418 	splx(s);
    419 	p->p_flag &= ~P_SINTR;
    420 	if (p->p_flag & P_TIMEOUT) {
    421 		p->p_flag &= ~P_TIMEOUT;
    422 		if (sig == 0) {
    423 #ifdef KTRACE
    424 			if (KTRPOINT(p, KTR_CSW))
    425 				ktrcsw(p->p_tracep, 0, 0);
    426 #endif
    427 			return (EWOULDBLOCK);
    428 		}
    429 	} else if (timo)
    430 		untimeout(endtsleep, (void *)p);
    431 	if (catch && (sig != 0 || (sig = CURSIG(p)) != 0)) {
    432 #ifdef KTRACE
    433 		if (KTRPOINT(p, KTR_CSW))
    434 			ktrcsw(p->p_tracep, 0, 0);
    435 #endif
    436 		if ((p->p_sigacts->ps_sigact[sig].sa_flags & SA_RESTART) == 0)
    437 			return (EINTR);
    438 		return (ERESTART);
    439 	}
    440 #ifdef KTRACE
    441 	if (KTRPOINT(p, KTR_CSW))
    442 		ktrcsw(p->p_tracep, 0, 0);
    443 #endif
    444 	return (0);
    445 }
    446 
    447 /*
    448  * Implement timeout for tsleep.
    449  * If process hasn't been awakened (wchan non-zero),
    450  * set timeout flag and undo the sleep.  If proc
    451  * is stopped, just unsleep so it will remain stopped.
    452  */
    453 void
    454 endtsleep(arg)
    455 	void *arg;
    456 {
    457 	register struct proc *p;
    458 	int s;
    459 
    460 	p = (struct proc *)arg;
    461 	s = splhigh();
    462 	if (p->p_wchan) {
    463 		if (p->p_stat == SSLEEP)
    464 			setrunnable(p);
    465 		else
    466 			unsleep(p);
    467 		p->p_flag |= P_TIMEOUT;
    468 	}
    469 	splx(s);
    470 }
    471 
    472 /*
    473  * Short-term, non-interruptable sleep.
    474  */
    475 void
    476 sleep(ident, priority)
    477 	void *ident;
    478 	int priority;
    479 {
    480 	register struct proc *p = curproc;
    481 	register struct slpque *qp;
    482 	register int s;
    483 	extern int cold;
    484 
    485 #ifdef DIAGNOSTIC
    486 	if (priority > PZERO) {
    487 		printf("sleep called with priority %d > PZERO, wchan: %p\n",
    488 		    priority, ident);
    489 		panic("old sleep");
    490 	}
    491 #endif
    492 	s = splhigh();
    493 	if (cold || panicstr) {
    494 		/*
    495 		 * After a panic, or during autoconfiguration,
    496 		 * just give interrupts a chance, then just return;
    497 		 * don't run any other procs or panic below,
    498 		 * in case this is the idle process and already asleep.
    499 		 */
    500 		splx(safepri);
    501 		splx(s);
    502 		return;
    503 	}
    504 #ifdef DIAGNOSTIC
    505 	if (ident == NULL || p->p_stat != SRUN || p->p_back)
    506 		panic("sleep");
    507 #endif
    508 	p->p_wchan = ident;
    509 	p->p_wmesg = NULL;
    510 	p->p_slptime = 0;
    511 	p->p_priority = priority;
    512 	qp = &slpque[LOOKUP(ident)];
    513 	if (qp->sq_head == 0)
    514 		qp->sq_head = p;
    515 	else
    516 		*qp->sq_tailp = p;
    517 	*(qp->sq_tailp = &p->p_forw) = 0;
    518 	p->p_stat = SSLEEP;
    519 	p->p_stats->p_ru.ru_nvcsw++;
    520 #ifdef KTRACE
    521 	if (KTRPOINT(p, KTR_CSW))
    522 		ktrcsw(p->p_tracep, 1, 0);
    523 #endif
    524 	mi_switch();
    525 #ifdef	DDB
    526 	/* handy breakpoint location after process "wakes" */
    527 	asm(".globl bpendsleep ; bpendsleep:");
    528 #endif
    529 #ifdef KTRACE
    530 	if (KTRPOINT(p, KTR_CSW))
    531 		ktrcsw(p->p_tracep, 0, 0);
    532 #endif
    533 	curpriority = p->p_usrpri;
    534 	splx(s);
    535 }
    536 
    537 /*
    538  * Remove a process from its wait queue
    539  */
    540 void
    541 unsleep(p)
    542 	register struct proc *p;
    543 {
    544 	register struct slpque *qp;
    545 	register struct proc **hp;
    546 	int s;
    547 
    548 	s = splhigh();
    549 	if (p->p_wchan) {
    550 		hp = &(qp = &slpque[LOOKUP(p->p_wchan)])->sq_head;
    551 		while (*hp != p)
    552 			hp = &(*hp)->p_forw;
    553 		*hp = p->p_forw;
    554 		if (qp->sq_tailp == &p->p_forw)
    555 			qp->sq_tailp = hp;
    556 		p->p_wchan = 0;
    557 	}
    558 	splx(s);
    559 }
    560 
    561 /*
    562  * Optimized-for-wakeup() version of setrunnable().
    563  */
    564 __inline void
    565 awaken(p)
    566 	struct proc *p;
    567 {
    568 
    569 	if (p->p_slptime > 1)
    570 		updatepri(p);
    571 	p->p_slptime = 0;
    572 	p->p_stat = SRUN;
    573 	/*
    574 	 * Since curpriority is a user priority, p->p_priority
    575 	 * is always better than curpriority.
    576 	 */
    577 	if (p->p_flag & P_INMEM) {
    578 		setrunqueue(p);
    579 		need_resched();
    580 	} else
    581 		wakeup((caddr_t)&proc0);
    582 }
    583 
    584 /*
    585  * Make all processes sleeping on the specified identifier runnable.
    586  */
    587 void
    588 wakeup(ident)
    589 	register void *ident;
    590 {
    591 	register struct slpque *qp;
    592 	register struct proc *p, **q;
    593 	int s;
    594 
    595 	s = splhigh();
    596 	qp = &slpque[LOOKUP(ident)];
    597 restart:
    598 	for (q = &qp->sq_head; (p = *q) != NULL; ) {
    599 #ifdef DIAGNOSTIC
    600 		if (p->p_back || (p->p_stat != SSLEEP && p->p_stat != SSTOP))
    601 			panic("wakeup");
    602 #endif
    603 		if (p->p_wchan == ident) {
    604 			p->p_wchan = 0;
    605 			*q = p->p_forw;
    606 			if (qp->sq_tailp == &p->p_forw)
    607 				qp->sq_tailp = q;
    608 			if (p->p_stat == SSLEEP) {
    609 				awaken(p);
    610 				goto restart;
    611 			}
    612 		} else
    613 			q = &p->p_forw;
    614 	}
    615 	splx(s);
    616 }
    617 
    618 /*
    619  * Make the highest priority process first in line on the specified
    620  * identifier runnable.
    621  */
    622 void
    623 wakeup_one(ident)
    624 	void *ident;
    625 {
    626 	struct slpque *qp;
    627 	struct proc *p, **q;
    628 	struct proc *best_sleepp, **best_sleepq;
    629 	struct proc *best_stopp, **best_stopq;
    630 	int s;
    631 
    632 	best_sleepp = best_stopp = NULL;
    633 	best_sleepq = best_stopq = NULL;
    634 
    635 	s = splhigh();
    636 	qp = &slpque[LOOKUP(ident)];
    637 	for (q = &qp->sq_head; (p = *q) != NULL; q = &p->p_forw) {
    638 #ifdef DIAGNOSTIC
    639 		if (p->p_back || (p->p_stat != SSLEEP && p->p_stat != SSTOP))
    640 			panic("wakeup_one");
    641 #endif
    642 		if (p->p_wchan == ident) {
    643 			if (p->p_stat == SSLEEP) {
    644 				if (best_sleepp == NULL ||
    645 				    p->p_priority < best_sleepp->p_priority) {
    646 					best_sleepp = p;
    647 					best_sleepq = q;
    648 				}
    649 			} else {
    650 				if (best_stopp == NULL ||
    651 				    p->p_priority < best_stopp->p_priority) {
    652 					best_stopp = p;
    653 					best_stopq = q;
    654 				}
    655 			}
    656 		}
    657 	}
    658 
    659 	/*
    660 	 * Consider any SSLEEP process higher than the highest priority SSTOP
    661 	 * process.
    662 	 */
    663 	if (best_sleepp != NULL) {
    664 		p = best_sleepp;
    665 		q = best_sleepq;
    666 	} else {
    667 		p = best_stopp;
    668 		q = best_stopq;
    669 	}
    670 
    671 	if (p != NULL) {
    672 		p->p_wchan = 0;
    673 		*q = p->p_forw;
    674 		if (qp->sq_tailp == &p->p_forw)
    675 			qp->sq_tailp = q;
    676 		if (p->p_stat == SSLEEP)
    677 			awaken(p);
    678 	}
    679 	splx(s);
    680 }
    681 
    682 /*
    683  * The machine independent parts of mi_switch().
    684  * Must be called at splstatclock() or higher.
    685  */
    686 void
    687 mi_switch()
    688 {
    689 	register struct proc *p = curproc;	/* XXX */
    690 	register struct rlimit *rlim;
    691 	register long s, u;
    692 	struct timeval tv;
    693 
    694 #ifdef DEBUG
    695 	if (p->p_simple_locks) {
    696 		printf("p->p_simple_locks %d\n", p->p_simple_locks);
    697 #ifdef LOCKDEBUG
    698 		simple_lock_dump();
    699 #endif
    700 		panic("sleep: holding simple lock");
    701 	}
    702 #endif
    703 	/*
    704 	 * Compute the amount of time during which the current
    705 	 * process was running, and add that to its total so far.
    706 	 */
    707 	microtime(&tv);
    708 	u = p->p_rtime.tv_usec + (tv.tv_usec - runtime.tv_usec);
    709 	s = p->p_rtime.tv_sec + (tv.tv_sec - runtime.tv_sec);
    710 	if (u < 0) {
    711 		u += 1000000;
    712 		s--;
    713 	} else if (u >= 1000000) {
    714 		u -= 1000000;
    715 		s++;
    716 	}
    717 	p->p_rtime.tv_usec = u;
    718 	p->p_rtime.tv_sec = s;
    719 
    720 	/*
    721 	 * Check if the process exceeds its cpu resource allocation.
    722 	 * If over max, kill it.  In any case, if it has run for more
    723 	 * than 10 minutes, reduce priority to give others a chance.
    724 	 */
    725 	rlim = &p->p_rlimit[RLIMIT_CPU];
    726 	if (s >= rlim->rlim_cur) {
    727 		if (s >= rlim->rlim_max)
    728 			psignal(p, SIGKILL);
    729 		else {
    730 			psignal(p, SIGXCPU);
    731 			if (rlim->rlim_cur < rlim->rlim_max)
    732 				rlim->rlim_cur += 5;
    733 		}
    734 	}
    735 	if (autonicetime && s > autonicetime && p->p_ucred->cr_uid && p->p_nice == NZERO) {
    736 		p->p_nice = autoniceval + NZERO;
    737 		resetpriority(p);
    738 	}
    739 
    740 	/*
    741 	 * Pick a new current process and record its start time.
    742 	 */
    743 	uvmexp.swtch++;
    744 	cpu_switch(p);
    745 	microtime(&runtime);
    746 }
    747 
    748 /*
    749  * Initialize the (doubly-linked) run queues
    750  * to be empty.
    751  */
    752 void
    753 rqinit()
    754 {
    755 	register int i;
    756 
    757 	for (i = 0; i < NQS; i++)
    758 		qs[i].ph_link = qs[i].ph_rlink = (struct proc *)&qs[i];
    759 }
    760 
    761 /*
    762  * Change process state to be runnable,
    763  * placing it on the run queue if it is in memory,
    764  * and awakening the swapper if it isn't in memory.
    765  */
    766 void
    767 setrunnable(p)
    768 	register struct proc *p;
    769 {
    770 	register int s;
    771 
    772 	s = splhigh();
    773 	switch (p->p_stat) {
    774 	case 0:
    775 	case SRUN:
    776 	case SZOMB:
    777 	case SDEAD:
    778 	default:
    779 		panic("setrunnable");
    780 	case SSTOP:
    781 		/*
    782 		 * If we're being traced (possibly because someone attached us
    783 		 * while we were stopped), check for a signal from the debugger.
    784 		 */
    785 		if ((p->p_flag & P_TRACED) != 0 && p->p_xstat != 0) {
    786 			sigaddset(&p->p_siglist, p->p_xstat);
    787 			p->p_sigcheck = 1;
    788 		}
    789 	case SSLEEP:
    790 		unsleep(p);		/* e.g. when sending signals */
    791 		break;
    792 
    793 	case SIDL:
    794 		break;
    795 	}
    796 	p->p_stat = SRUN;
    797 	if (p->p_flag & P_INMEM)
    798 		setrunqueue(p);
    799 	splx(s);
    800 	if (p->p_slptime > 1)
    801 		updatepri(p);
    802 	p->p_slptime = 0;
    803 	if ((p->p_flag & P_INMEM) == 0)
    804 		wakeup((caddr_t)&proc0);
    805 	else if (p->p_priority < curpriority)
    806 		need_resched();
    807 }
    808 
    809 /*
    810  * Compute the priority of a process when running in user mode.
    811  * Arrange to reschedule if the resulting priority is better
    812  * than that of the current process.
    813  */
    814 void
    815 resetpriority(p)
    816 	register struct proc *p;
    817 {
    818 	register unsigned int newpriority;
    819 
    820 	newpriority = PUSER + p->p_estcpu + NICE_WEIGHT * (p->p_nice - NZERO);
    821 	newpriority = min(newpriority, MAXPRI);
    822 	p->p_usrpri = newpriority;
    823 	if (newpriority < curpriority)
    824 		need_resched();
    825 }
    826 
    827 /*
    828  * We adjust the priority of the current process.  The priority of a process
    829  * gets worse as it accumulates CPU time.  The cpu usage estimator (p_estcpu)
    830  * is increased here.  The formula for computing priorities (in kern_synch.c)
    831  * will compute a different value each time p_estcpu increases. This can
    832  * cause a switch, but unless the priority crosses a PPQ boundary the actual
    833  * queue will not change.  The cpu usage estimator ramps up quite quickly
    834  * when the process is running (linearly), and decays away exponentially, at
    835  * a rate which is proportionally slower when the system is busy.  The basic
    836  * principal is that the system will 90% forget that the process used a lot
    837  * of CPU time in 5 * loadav seconds.  This causes the system to favor
    838  * processes which haven't run much recently, and to round-robin among other
    839  * processes.
    840  */
    841 
    842 void
    843 schedclock(p)
    844 	struct proc *p;
    845 {
    846 	p->p_estcpu = ESTCPULIM(p->p_estcpu + 1);
    847 	resetpriority(p);
    848 	if (p->p_priority >= PUSER)
    849 		p->p_priority = p->p_usrpri;
    850 }
    851