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