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