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