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