Home | History | Annotate | Line # | Download | only in kern
kern_synch.c revision 1.65
      1 /*	$NetBSD: kern_synch.c,v 1.65 1999/09/17 20:09:05 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 	void endtsleep __P((void *));
    349 
    350 	if (cold || panicstr) {
    351 		/*
    352 		 * After a panic, or during autoconfiguration,
    353 		 * just give interrupts a chance, then just return;
    354 		 * don't run any other procs or panic below,
    355 		 * in case this is the idle process and already asleep.
    356 		 */
    357 		s = splhigh();
    358 		splx(safepri);
    359 		splx(s);
    360 		return (0);
    361 	}
    362 
    363 #ifdef KTRACE
    364 	if (KTRPOINT(p, KTR_CSW))
    365 		ktrcsw(p->p_tracep, 1, 0);
    366 #endif
    367 	s = splhigh();
    368 
    369 #ifdef DIAGNOSTIC
    370 	if (ident == NULL)
    371 		panic("tsleep: ident == NULL");
    372 	if (p->p_stat != SRUN)
    373 		panic("tsleep: p_stat %d != SRUN", p->p_stat);
    374 	if (p->p_back != NULL)
    375 		panic("tsleep: p_back != NULL");
    376 #endif
    377 	p->p_wchan = ident;
    378 	p->p_wmesg = wmesg;
    379 	p->p_slptime = 0;
    380 	p->p_priority = priority & PRIMASK;
    381 	qp = &slpque[LOOKUP(ident)];
    382 	if (qp->sq_head == 0)
    383 		qp->sq_head = p;
    384 	else
    385 		*qp->sq_tailp = p;
    386 	*(qp->sq_tailp = &p->p_forw) = 0;
    387 	if (timo)
    388 		timeout(endtsleep, (void *)p, timo);
    389 	/*
    390 	 * We put ourselves on the sleep queue and start our timeout
    391 	 * before calling CURSIG, as we could stop there, and a wakeup
    392 	 * or a SIGCONT (or both) could occur while we were stopped.
    393 	 * A SIGCONT would cause us to be marked as SSLEEP
    394 	 * without resuming us, thus we must be ready for sleep
    395 	 * when CURSIG is called.  If the wakeup happens while we're
    396 	 * stopped, p->p_wchan will be 0 upon return from CURSIG.
    397 	 */
    398 	if (catch) {
    399 		p->p_flag |= P_SINTR;
    400 		if ((sig = CURSIG(p)) != 0) {
    401 			if (p->p_wchan)
    402 				unsleep(p);
    403 			p->p_stat = SRUN;
    404 			goto resume;
    405 		}
    406 		if (p->p_wchan == 0) {
    407 			catch = 0;
    408 			goto resume;
    409 		}
    410 	} else
    411 		sig = 0;
    412 	p->p_stat = SSLEEP;
    413 	p->p_stats->p_ru.ru_nvcsw++;
    414 	mi_switch();
    415 #ifdef	DDB
    416 	/* handy breakpoint location after process "wakes" */
    417 	asm(".globl bpendtsleep ; bpendtsleep:");
    418 #endif
    419 resume:
    420 	curpriority = p->p_usrpri;
    421 	splx(s);
    422 	p->p_flag &= ~P_SINTR;
    423 	if (p->p_flag & P_TIMEOUT) {
    424 		p->p_flag &= ~P_TIMEOUT;
    425 		if (sig == 0) {
    426 #ifdef KTRACE
    427 			if (KTRPOINT(p, KTR_CSW))
    428 				ktrcsw(p->p_tracep, 0, 0);
    429 #endif
    430 			return (EWOULDBLOCK);
    431 		}
    432 	} else if (timo)
    433 		untimeout(endtsleep, (void *)p);
    434 	if (catch && (sig != 0 || (sig = CURSIG(p)) != 0)) {
    435 #ifdef KTRACE
    436 		if (KTRPOINT(p, KTR_CSW))
    437 			ktrcsw(p->p_tracep, 0, 0);
    438 #endif
    439 		if ((p->p_sigacts->ps_sigact[sig].sa_flags & SA_RESTART) == 0)
    440 			return (EINTR);
    441 		return (ERESTART);
    442 	}
    443 #ifdef KTRACE
    444 	if (KTRPOINT(p, KTR_CSW))
    445 		ktrcsw(p->p_tracep, 0, 0);
    446 #endif
    447 	return (0);
    448 }
    449 
    450 /*
    451  * Implement timeout for tsleep.
    452  * If process hasn't been awakened (wchan non-zero),
    453  * set timeout flag and undo the sleep.  If proc
    454  * is stopped, just unsleep so it will remain stopped.
    455  */
    456 void
    457 endtsleep(arg)
    458 	void *arg;
    459 {
    460 	register struct proc *p;
    461 	int s;
    462 
    463 	p = (struct proc *)arg;
    464 	s = splhigh();
    465 	if (p->p_wchan) {
    466 		if (p->p_stat == SSLEEP)
    467 			setrunnable(p);
    468 		else
    469 			unsleep(p);
    470 		p->p_flag |= P_TIMEOUT;
    471 	}
    472 	splx(s);
    473 }
    474 
    475 /*
    476  * Short-term, non-interruptable sleep.
    477  */
    478 void
    479 sleep(ident, priority)
    480 	void *ident;
    481 	int priority;
    482 {
    483 	register struct proc *p = curproc;
    484 	register struct slpque *qp;
    485 	register int s;
    486 
    487 #ifdef DIAGNOSTIC
    488 	if (priority > PZERO) {
    489 		printf("sleep called with priority %d > PZERO, wchan: %p\n",
    490 		    priority, ident);
    491 		panic("old sleep");
    492 	}
    493 #endif
    494 	s = splhigh();
    495 	if (cold || panicstr) {
    496 		/*
    497 		 * After a panic, or during autoconfiguration,
    498 		 * just give interrupts a chance, then just return;
    499 		 * don't run any other procs or panic below,
    500 		 * in case this is the idle process and already asleep.
    501 		 */
    502 		splx(safepri);
    503 		splx(s);
    504 		return;
    505 	}
    506 #ifdef DIAGNOSTIC
    507 	if (ident == NULL || p->p_stat != SRUN || p->p_back)
    508 		panic("sleep");
    509 #endif
    510 	p->p_wchan = ident;
    511 	p->p_wmesg = NULL;
    512 	p->p_slptime = 0;
    513 	p->p_priority = priority;
    514 	qp = &slpque[LOOKUP(ident)];
    515 	if (qp->sq_head == 0)
    516 		qp->sq_head = p;
    517 	else
    518 		*qp->sq_tailp = p;
    519 	*(qp->sq_tailp = &p->p_forw) = 0;
    520 	p->p_stat = SSLEEP;
    521 	p->p_stats->p_ru.ru_nvcsw++;
    522 #ifdef KTRACE
    523 	if (KTRPOINT(p, KTR_CSW))
    524 		ktrcsw(p->p_tracep, 1, 0);
    525 #endif
    526 	mi_switch();
    527 #ifdef	DDB
    528 	/* handy breakpoint location after process "wakes" */
    529 	asm(".globl bpendsleep ; bpendsleep:");
    530 #endif
    531 #ifdef KTRACE
    532 	if (KTRPOINT(p, KTR_CSW))
    533 		ktrcsw(p->p_tracep, 0, 0);
    534 #endif
    535 	curpriority = p->p_usrpri;
    536 	splx(s);
    537 }
    538 
    539 /*
    540  * Remove a process from its wait queue
    541  */
    542 void
    543 unsleep(p)
    544 	register struct proc *p;
    545 {
    546 	register struct slpque *qp;
    547 	register struct proc **hp;
    548 	int s;
    549 
    550 	s = splhigh();
    551 	if (p->p_wchan) {
    552 		hp = &(qp = &slpque[LOOKUP(p->p_wchan)])->sq_head;
    553 		while (*hp != p)
    554 			hp = &(*hp)->p_forw;
    555 		*hp = p->p_forw;
    556 		if (qp->sq_tailp == &p->p_forw)
    557 			qp->sq_tailp = hp;
    558 		p->p_wchan = 0;
    559 	}
    560 	splx(s);
    561 }
    562 
    563 /*
    564  * Optimized-for-wakeup() version of setrunnable().
    565  */
    566 __inline void
    567 awaken(p)
    568 	struct proc *p;
    569 {
    570 
    571 	if (p->p_slptime > 1)
    572 		updatepri(p);
    573 	p->p_slptime = 0;
    574 	p->p_stat = SRUN;
    575 	/*
    576 	 * Since curpriority is a user priority, p->p_priority
    577 	 * is always better than curpriority.
    578 	 */
    579 	if (p->p_flag & P_INMEM) {
    580 		setrunqueue(p);
    581 		need_resched();
    582 	} else
    583 		wakeup((caddr_t)&proc0);
    584 }
    585 
    586 /*
    587  * Make all processes sleeping on the specified identifier runnable.
    588  */
    589 void
    590 wakeup(ident)
    591 	register void *ident;
    592 {
    593 	register struct slpque *qp;
    594 	register struct proc *p, **q;
    595 	int s;
    596 
    597 	s = splhigh();
    598 	qp = &slpque[LOOKUP(ident)];
    599 restart:
    600 	for (q = &qp->sq_head; (p = *q) != NULL; ) {
    601 #ifdef DIAGNOSTIC
    602 		if (p->p_back || (p->p_stat != SSLEEP && p->p_stat != SSTOP))
    603 			panic("wakeup");
    604 #endif
    605 		if (p->p_wchan == ident) {
    606 			p->p_wchan = 0;
    607 			*q = p->p_forw;
    608 			if (qp->sq_tailp == &p->p_forw)
    609 				qp->sq_tailp = q;
    610 			if (p->p_stat == SSLEEP) {
    611 				awaken(p);
    612 				goto restart;
    613 			}
    614 		} else
    615 			q = &p->p_forw;
    616 	}
    617 	splx(s);
    618 }
    619 
    620 /*
    621  * Make the highest priority process first in line on the specified
    622  * identifier runnable.
    623  */
    624 void
    625 wakeup_one(ident)
    626 	void *ident;
    627 {
    628 	struct slpque *qp;
    629 	struct proc *p, **q;
    630 	struct proc *best_sleepp, **best_sleepq;
    631 	struct proc *best_stopp, **best_stopq;
    632 	int s;
    633 
    634 	best_sleepp = best_stopp = NULL;
    635 	best_sleepq = best_stopq = NULL;
    636 
    637 	s = splhigh();
    638 	qp = &slpque[LOOKUP(ident)];
    639 	for (q = &qp->sq_head; (p = *q) != NULL; q = &p->p_forw) {
    640 #ifdef DIAGNOSTIC
    641 		if (p->p_back || (p->p_stat != SSLEEP && p->p_stat != SSTOP))
    642 			panic("wakeup_one");
    643 #endif
    644 		if (p->p_wchan == ident) {
    645 			if (p->p_stat == SSLEEP) {
    646 				if (best_sleepp == NULL ||
    647 				    p->p_priority < best_sleepp->p_priority) {
    648 					best_sleepp = p;
    649 					best_sleepq = q;
    650 				}
    651 			} else {
    652 				if (best_stopp == NULL ||
    653 				    p->p_priority < best_stopp->p_priority) {
    654 					best_stopp = p;
    655 					best_stopq = q;
    656 				}
    657 			}
    658 		}
    659 	}
    660 
    661 	/*
    662 	 * Consider any SSLEEP process higher than the highest priority SSTOP
    663 	 * process.
    664 	 */
    665 	if (best_sleepp != NULL) {
    666 		p = best_sleepp;
    667 		q = best_sleepq;
    668 	} else {
    669 		p = best_stopp;
    670 		q = best_stopq;
    671 	}
    672 
    673 	if (p != NULL) {
    674 		p->p_wchan = 0;
    675 		*q = p->p_forw;
    676 		if (qp->sq_tailp == &p->p_forw)
    677 			qp->sq_tailp = q;
    678 		if (p->p_stat == SSLEEP)
    679 			awaken(p);
    680 	}
    681 	splx(s);
    682 }
    683 
    684 /*
    685  * The machine independent parts of mi_switch().
    686  * Must be called at splstatclock() or higher.
    687  */
    688 void
    689 mi_switch()
    690 {
    691 	register struct proc *p = curproc;	/* XXX */
    692 	register struct rlimit *rlim;
    693 	register long s, u;
    694 	struct timeval tv;
    695 
    696 #ifdef DEBUG
    697 	if (p->p_simple_locks) {
    698 		printf("p->p_simple_locks %d\n", p->p_simple_locks);
    699 #ifdef LOCKDEBUG
    700 		simple_lock_dump();
    701 #endif
    702 		panic("sleep: holding simple lock");
    703 	}
    704 #endif
    705 	/*
    706 	 * Compute the amount of time during which the current
    707 	 * process was running, and add that to its total so far.
    708 	 */
    709 	microtime(&tv);
    710 	u = p->p_rtime.tv_usec + (tv.tv_usec - runtime.tv_usec);
    711 	s = p->p_rtime.tv_sec + (tv.tv_sec - runtime.tv_sec);
    712 	if (u < 0) {
    713 		u += 1000000;
    714 		s--;
    715 	} else if (u >= 1000000) {
    716 		u -= 1000000;
    717 		s++;
    718 	}
    719 	p->p_rtime.tv_usec = u;
    720 	p->p_rtime.tv_sec = s;
    721 
    722 	/*
    723 	 * Check if the process exceeds its cpu resource allocation.
    724 	 * If over max, kill it.  In any case, if it has run for more
    725 	 * than 10 minutes, reduce priority to give others a chance.
    726 	 */
    727 	rlim = &p->p_rlimit[RLIMIT_CPU];
    728 	if (s >= rlim->rlim_cur) {
    729 		if (s >= rlim->rlim_max)
    730 			psignal(p, SIGKILL);
    731 		else {
    732 			psignal(p, SIGXCPU);
    733 			if (rlim->rlim_cur < rlim->rlim_max)
    734 				rlim->rlim_cur += 5;
    735 		}
    736 	}
    737 	if (autonicetime && s > autonicetime && p->p_ucred->cr_uid && p->p_nice == NZERO) {
    738 		p->p_nice = autoniceval + NZERO;
    739 		resetpriority(p);
    740 	}
    741 
    742 	/*
    743 	 * Pick a new current process and record its start time.
    744 	 */
    745 	uvmexp.swtch++;
    746 	cpu_switch(p);
    747 	microtime(&runtime);
    748 }
    749 
    750 /*
    751  * Initialize the (doubly-linked) run queues
    752  * to be empty.
    753  */
    754 void
    755 rqinit()
    756 {
    757 	register int i;
    758 
    759 	for (i = 0; i < NQS; i++)
    760 		qs[i].ph_link = qs[i].ph_rlink = (struct proc *)&qs[i];
    761 }
    762 
    763 /*
    764  * Change process state to be runnable,
    765  * placing it on the run queue if it is in memory,
    766  * and awakening the swapper if it isn't in memory.
    767  */
    768 void
    769 setrunnable(p)
    770 	register struct proc *p;
    771 {
    772 	register int s;
    773 
    774 	s = splhigh();
    775 	switch (p->p_stat) {
    776 	case 0:
    777 	case SRUN:
    778 	case SZOMB:
    779 	case SDEAD:
    780 	default:
    781 		panic("setrunnable");
    782 	case SSTOP:
    783 		/*
    784 		 * If we're being traced (possibly because someone attached us
    785 		 * while we were stopped), check for a signal from the debugger.
    786 		 */
    787 		if ((p->p_flag & P_TRACED) != 0 && p->p_xstat != 0) {
    788 			sigaddset(&p->p_siglist, p->p_xstat);
    789 			p->p_sigcheck = 1;
    790 		}
    791 	case SSLEEP:
    792 		unsleep(p);		/* e.g. when sending signals */
    793 		break;
    794 
    795 	case SIDL:
    796 		break;
    797 	}
    798 	p->p_stat = SRUN;
    799 	if (p->p_flag & P_INMEM)
    800 		setrunqueue(p);
    801 	splx(s);
    802 	if (p->p_slptime > 1)
    803 		updatepri(p);
    804 	p->p_slptime = 0;
    805 	if ((p->p_flag & P_INMEM) == 0)
    806 		wakeup((caddr_t)&proc0);
    807 	else if (p->p_priority < curpriority)
    808 		need_resched();
    809 }
    810 
    811 /*
    812  * Compute the priority of a process when running in user mode.
    813  * Arrange to reschedule if the resulting priority is better
    814  * than that of the current process.
    815  */
    816 void
    817 resetpriority(p)
    818 	register struct proc *p;
    819 {
    820 	register unsigned int newpriority;
    821 
    822 	newpriority = PUSER + p->p_estcpu + NICE_WEIGHT * (p->p_nice - NZERO);
    823 	newpriority = min(newpriority, MAXPRI);
    824 	p->p_usrpri = newpriority;
    825 	if (newpriority < curpriority)
    826 		need_resched();
    827 }
    828 
    829 /*
    830  * We adjust the priority of the current process.  The priority of a process
    831  * gets worse as it accumulates CPU time.  The cpu usage estimator (p_estcpu)
    832  * is increased here.  The formula for computing priorities (in kern_synch.c)
    833  * will compute a different value each time p_estcpu increases. This can
    834  * cause a switch, but unless the priority crosses a PPQ boundary the actual
    835  * queue will not change.  The cpu usage estimator ramps up quite quickly
    836  * when the process is running (linearly), and decays away exponentially, at
    837  * a rate which is proportionally slower when the system is busy.  The basic
    838  * principal is that the system will 90% forget that the process used a lot
    839  * of CPU time in 5 * loadav seconds.  This causes the system to favor
    840  * processes which haven't run much recently, and to round-robin among other
    841  * processes.
    842  */
    843 
    844 void
    845 schedclock(p)
    846 	struct proc *p;
    847 {
    848 	p->p_estcpu = ESTCPULIM(p->p_estcpu + 1);
    849 	resetpriority(p);
    850 	if (p->p_priority >= PUSER)
    851 		p->p_priority = p->p_usrpri;
    852 }
    853