Home | History | Annotate | Line # | Download | only in kern
kern_synch.c revision 1.84
      1 /*	$NetBSD: kern_synch.c,v 1.84 2000/08/22 17:28:29 thorpej 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 #include "opt_lockdebug.h"
     83 #include "opt_multiprocessor.h"
     84 
     85 #include <sys/param.h>
     86 #include <sys/systm.h>
     87 #include <sys/callout.h>
     88 #include <sys/proc.h>
     89 #include <sys/kernel.h>
     90 #include <sys/buf.h>
     91 #include <sys/signalvar.h>
     92 #include <sys/resourcevar.h>
     93 #include <sys/sched.h>
     94 
     95 #include <uvm/uvm_extern.h>
     96 
     97 #ifdef KTRACE
     98 #include <sys/ktrace.h>
     99 #endif
    100 
    101 #include <machine/cpu.h>
    102 
    103 int	lbolt;			/* once a second sleep address */
    104 
    105 /*
    106  * The global scheduler state.
    107  */
    108 struct prochd sched_qs[RUNQUE_NQS];	/* run queues */
    109 __volatile u_int32_t sched_whichqs;	/* bitmap of non-empty queues */
    110 struct slpque sched_slpque[SLPQUE_TABLESIZE]; /* sleep queues */
    111 
    112 struct simplelock sched_lock = SIMPLELOCK_INITIALIZER;
    113 #if defined(MULTIPROCESSOR)
    114 struct lock kernel_lock;
    115 #endif
    116 
    117 void roundrobin(void *);
    118 void schedcpu(void *);
    119 void updatepri(struct proc *);
    120 void endtsleep(void *);
    121 
    122 __inline void awaken(struct proc *);
    123 
    124 struct callout roundrobin_ch = CALLOUT_INITIALIZER;
    125 struct callout schedcpu_ch = CALLOUT_INITIALIZER;
    126 
    127 /*
    128  * Force switch among equal priority processes every 100ms.
    129  */
    130 /* ARGSUSED */
    131 void
    132 roundrobin(void *arg)
    133 {
    134 	struct schedstate_percpu *spc = &curcpu()->ci_schedstate;
    135 	int s;
    136 
    137 	if (curproc != NULL) {
    138 		s = splstatclock();
    139 		if (spc->spc_flags & SPCF_SEENRR) {
    140 			/*
    141 			 * The process has already been through a roundrobin
    142 			 * without switching and may be hogging the CPU.
    143 			 * Indicate that the process should yield.
    144 			 */
    145 			spc->spc_flags |= SPCF_SHOULDYIELD;
    146 		} else
    147 			spc->spc_flags |= SPCF_SEENRR;
    148 		splx(s);
    149 	}
    150 	/* XXXSMP: should need_resched() on all CPUs */
    151 	need_resched();
    152 	callout_reset(&roundrobin_ch, hz / 10, roundrobin, NULL);
    153 }
    154 
    155 /*
    156  * Constants for digital decay and forget:
    157  *	90% of (p_estcpu) usage in 5 * loadav time
    158  *	95% of (p_pctcpu) usage in 60 seconds (load insensitive)
    159  *          Note that, as ps(1) mentions, this can let percentages
    160  *          total over 100% (I've seen 137.9% for 3 processes).
    161  *
    162  * Note that hardclock updates p_estcpu and p_cpticks independently.
    163  *
    164  * We wish to decay away 90% of p_estcpu in (5 * loadavg) seconds.
    165  * That is, the system wants to compute a value of decay such
    166  * that the following for loop:
    167  * 	for (i = 0; i < (5 * loadavg); i++)
    168  * 		p_estcpu *= decay;
    169  * will compute
    170  * 	p_estcpu *= 0.1;
    171  * for all values of loadavg:
    172  *
    173  * Mathematically this loop can be expressed by saying:
    174  * 	decay ** (5 * loadavg) ~= .1
    175  *
    176  * The system computes decay as:
    177  * 	decay = (2 * loadavg) / (2 * loadavg + 1)
    178  *
    179  * We wish to prove that the system's computation of decay
    180  * will always fulfill the equation:
    181  * 	decay ** (5 * loadavg) ~= .1
    182  *
    183  * If we compute b as:
    184  * 	b = 2 * loadavg
    185  * then
    186  * 	decay = b / (b + 1)
    187  *
    188  * We now need to prove two things:
    189  *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
    190  *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
    191  *
    192  * Facts:
    193  *         For x close to zero, exp(x) =~ 1 + x, since
    194  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
    195  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
    196  *         For x close to zero, ln(1+x) =~ x, since
    197  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
    198  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
    199  *         ln(.1) =~ -2.30
    200  *
    201  * Proof of (1):
    202  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
    203  *	solving for factor,
    204  *      ln(factor) =~ (-2.30/5*loadav), or
    205  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
    206  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
    207  *
    208  * Proof of (2):
    209  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
    210  *	solving for power,
    211  *      power*ln(b/(b+1)) =~ -2.30, or
    212  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
    213  *
    214  * Actual power values for the implemented algorithm are as follows:
    215  *      loadav: 1       2       3       4
    216  *      power:  5.68    10.32   14.94   19.55
    217  */
    218 
    219 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
    220 #define	loadfactor(loadav)	(2 * (loadav))
    221 #define	decay_cpu(loadfac, cpu)	(((loadfac) * (cpu)) / ((loadfac) + FSCALE))
    222 
    223 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
    224 fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;		/* exp(-1/20) */
    225 
    226 /*
    227  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
    228  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
    229  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
    230  *
    231  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
    232  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
    233  *
    234  * If you dont want to bother with the faster/more-accurate formula, you
    235  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
    236  * (more general) method of calculating the %age of CPU used by a process.
    237  */
    238 #define	CCPU_SHIFT	11
    239 
    240 /*
    241  * Recompute process priorities, every hz ticks.
    242  */
    243 /* ARGSUSED */
    244 void
    245 schedcpu(void *arg)
    246 {
    247 	fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
    248 	struct proc *p;
    249 	int s, s1;
    250 	unsigned int newcpu;
    251 	int clkhz;
    252 
    253 	proclist_lock_read();
    254 	for (p = allproc.lh_first; p != 0; p = p->p_list.le_next) {
    255 		/*
    256 		 * Increment time in/out of memory and sleep time
    257 		 * (if sleeping).  We ignore overflow; with 16-bit int's
    258 		 * (remember them?) overflow takes 45 days.
    259 		 */
    260 		p->p_swtime++;
    261 		if (p->p_stat == SSLEEP || p->p_stat == SSTOP)
    262 			p->p_slptime++;
    263 		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
    264 		/*
    265 		 * If the process has slept the entire second,
    266 		 * stop recalculating its priority until it wakes up.
    267 		 */
    268 		if (p->p_slptime > 1)
    269 			continue;
    270 		s = splstatclock();	/* prevent state changes */
    271 		/*
    272 		 * p_pctcpu is only for ps.
    273 		 */
    274 		clkhz = stathz != 0 ? stathz : hz;
    275 #if	(FSHIFT >= CCPU_SHIFT)
    276 		p->p_pctcpu += (clkhz == 100)?
    277 			((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT):
    278                 	100 * (((fixpt_t) p->p_cpticks)
    279 				<< (FSHIFT - CCPU_SHIFT)) / clkhz;
    280 #else
    281 		p->p_pctcpu += ((FSCALE - ccpu) *
    282 			(p->p_cpticks * FSCALE / clkhz)) >> FSHIFT;
    283 #endif
    284 		p->p_cpticks = 0;
    285 		newcpu = (u_int)decay_cpu(loadfac, p->p_estcpu);
    286 		p->p_estcpu = newcpu;
    287 		SCHED_LOCK(s1);
    288 		resetpriority(p);
    289 		if (p->p_priority >= PUSER) {
    290 			if (p->p_stat == SRUN &&
    291 			    (p->p_flag & P_INMEM) &&
    292 			    (p->p_priority / PPQ) != (p->p_usrpri / PPQ)) {
    293 				remrunqueue(p);
    294 				p->p_priority = p->p_usrpri;
    295 				setrunqueue(p);
    296 			} else
    297 				p->p_priority = p->p_usrpri;
    298 		}
    299 		SCHED_UNLOCK(s1);
    300 		splx(s);
    301 	}
    302 	proclist_unlock_read();
    303 	uvm_meter();
    304 	wakeup((caddr_t)&lbolt);
    305 	callout_reset(&schedcpu_ch, hz, schedcpu, NULL);
    306 }
    307 
    308 /*
    309  * Recalculate the priority of a process after it has slept for a while.
    310  * For all load averages >= 1 and max p_estcpu of 255, sleeping for at
    311  * least six times the loadfactor will decay p_estcpu to zero.
    312  */
    313 void
    314 updatepri(struct proc *p)
    315 {
    316 	unsigned int newcpu;
    317 	fixpt_t loadfac;
    318 
    319 	SCHED_ASSERT_LOCKED();
    320 
    321 	newcpu = p->p_estcpu;
    322 	loadfac = loadfactor(averunnable.ldavg[0]);
    323 
    324 	if (p->p_slptime > 5 * loadfac)
    325 		p->p_estcpu = 0;
    326 	else {
    327 		p->p_slptime--;	/* the first time was done in schedcpu */
    328 		while (newcpu && --p->p_slptime)
    329 			newcpu = (int) decay_cpu(loadfac, newcpu);
    330 		p->p_estcpu = newcpu;
    331 	}
    332 	resetpriority(p);
    333 }
    334 
    335 #if defined(MULTIPROCESSOR)
    336 /*
    337  * XXX Need to tweak lockmgr() for this!
    338  */
    339 static int
    340 kernel_lock_release_all(void)
    341 {
    342 	int count, s;
    343 
    344 	s = splsched();
    345 	count = kernel_lock.lk_exclusivecount;
    346 	KDASSERT(count > 0);
    347 	kernel_lock.lk_exclusivecount = 1;
    348 	kernel_lock.lk_recurselevel = 1;
    349 	spinlockmgr(&kernel_lock, LK_RELEASE, 0);
    350 	splx(s);
    351 
    352 	return (count);
    353 }
    354 
    355 static void
    356 kernel_lock_acquire_count(int flags, int count)
    357 {
    358 	int s;
    359 
    360 	s = splsched();
    361 	KDASSERT(count > 0);
    362 	spinlockmgr(&kernel_lock, flags, 0);
    363 	KDASSERT(kernel_lock.lk_exclusivecount == 1);
    364 	kernel_lock.lk_exclusivecount = count;
    365 	splx(s);
    366 }
    367 #endif /* MULTIPROCESSOR */
    368 
    369 /*
    370  * During autoconfiguration or after a panic, a sleep will simply
    371  * lower the priority briefly to allow interrupts, then return.
    372  * The priority to be used (safepri) is machine-dependent, thus this
    373  * value is initialized and maintained in the machine-dependent layers.
    374  * This priority will typically be 0, or the lowest priority
    375  * that is safe for use on the interrupt stack; it can be made
    376  * higher to block network software interrupts after panics.
    377  */
    378 int safepri;
    379 
    380 /*
    381  * General sleep call.  Suspends the current process until a wakeup is
    382  * performed on the specified identifier.  The process will then be made
    383  * runnable with the specified priority.  Sleeps at most timo/hz seconds
    384  * (0 means no timeout).  If pri includes PCATCH flag, signals are checked
    385  * before and after sleeping, else signals are not checked.  Returns 0 if
    386  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
    387  * signal needs to be delivered, ERESTART is returned if the current system
    388  * call should be restarted if possible, and EINTR is returned if the system
    389  * call should be interrupted by the signal (return EINTR).
    390  *
    391  * The interlock is held until the scheduler_slock is held.  The
    392  * interlock will be locked before returning back to the caller
    393  * unless the PNORELOCK flag is specified, in which case the
    394  * interlock will always be unlocked upon return.
    395  */
    396 int
    397 ltsleep(void *ident, int priority, const char *wmesg, int timo,
    398     __volatile struct simplelock *interlock)
    399 {
    400 	struct proc *p = curproc;
    401 	struct slpque *qp;
    402 	int sig, s;
    403 	int catch = priority & PCATCH;
    404 	int relock = (priority & PNORELOCK) == 0;
    405 #if defined(MULTIPROCESSOR)
    406 	int dobiglock, held_count;
    407 #endif
    408 
    409 	/*
    410 	 * XXXSMP
    411 	 * This is probably bogus.  Figure out what the right
    412 	 * thing to do here really is.
    413 	 * Note that not sleeping if ltsleep is called with curproc == NULL
    414 	 * in the shutdown case is disgusting but partly necessary given
    415 	 * how shutdown (barely) works.
    416 	 */
    417 	if (cold || (doing_shutdown && (panicstr || (p == NULL)))) {
    418 		/*
    419 		 * After a panic, or during autoconfiguration,
    420 		 * just give interrupts a chance, then just return;
    421 		 * don't run any other procs or panic below,
    422 		 * in case this is the idle process and already asleep.
    423 		 */
    424 		s = splhigh();
    425 		splx(safepri);
    426 		splx(s);
    427 		if (interlock != NULL && relock == 0)
    428 			simple_unlock(interlock);
    429 		return (0);
    430 	}
    431 
    432 #if defined(MULTIPROCESSOR)
    433 	dobiglock = (p->p_flag & P_BIGLOCK) != 0;
    434 #endif
    435 
    436 #ifdef KTRACE
    437 	if (KTRPOINT(p, KTR_CSW))
    438 		ktrcsw(p, 1, 0);
    439 #endif
    440 
    441 	SCHED_LOCK(s);
    442 
    443 #ifdef DIAGNOSTIC
    444 	if (ident == NULL)
    445 		panic("ltsleep: ident == NULL");
    446 	if (p->p_stat != SONPROC)
    447 		panic("ltsleep: p_stat %d != SONPROC", p->p_stat);
    448 	if (p->p_back != NULL)
    449 		panic("ltsleep: p_back != NULL");
    450 #endif
    451 
    452 	p->p_wchan = ident;
    453 	p->p_wmesg = wmesg;
    454 	p->p_slptime = 0;
    455 	p->p_priority = priority & PRIMASK;
    456 
    457 	qp = SLPQUE(ident);
    458 	if (qp->sq_head == 0)
    459 		qp->sq_head = p;
    460 	else
    461 		*qp->sq_tailp = p;
    462 	*(qp->sq_tailp = &p->p_forw) = 0;
    463 
    464 	if (timo)
    465 		callout_reset(&p->p_tsleep_ch, timo, endtsleep, p);
    466 
    467 	/*
    468 	 * We can now release the interlock; the scheduler_slock
    469 	 * is held, so a thread can't get in to do wakeup() before
    470 	 * we do the switch.
    471 	 *
    472 	 * XXX We leave the code block here, after inserting ourselves
    473 	 * on the sleep queue, because we might want a more clever
    474 	 * data structure for the sleep queues at some point.
    475 	 */
    476 	if (interlock != NULL)
    477 		simple_unlock(interlock);
    478 
    479 	/*
    480 	 * We put ourselves on the sleep queue and start our timeout
    481 	 * before calling CURSIG, as we could stop there, and a wakeup
    482 	 * or a SIGCONT (or both) could occur while we were stopped.
    483 	 * A SIGCONT would cause us to be marked as SSLEEP
    484 	 * without resuming us, thus we must be ready for sleep
    485 	 * when CURSIG is called.  If the wakeup happens while we're
    486 	 * stopped, p->p_wchan will be 0 upon return from CURSIG.
    487 	 */
    488 	if (catch) {
    489 		p->p_flag |= P_SINTR;
    490 		if ((sig = CURSIG(p)) != 0) {
    491 			if (p->p_wchan != NULL)
    492 				unsleep(p);
    493 			p->p_stat = SONPROC;
    494 #if defined(MULTIPROCESSOR)
    495 			/*
    496 			 * We're going to skip the unlock, so
    497 			 * we don't need to relock after resume.
    498 			 */
    499 			dobiglock = 0;
    500 #endif
    501 			SCHED_UNLOCK(s);
    502 			goto resume;
    503 		}
    504 		if (p->p_wchan == NULL) {
    505 			catch = 0;
    506 #if defined(MULTIPROCESSOR)
    507 			/* See above. */
    508 			dobiglock = 0;
    509 #endif
    510 			SCHED_UNLOCK(s);
    511 			goto resume;
    512 		}
    513 	} else
    514 		sig = 0;
    515 	p->p_stat = SSLEEP;
    516 	p->p_stats->p_ru.ru_nvcsw++;
    517 
    518 #if defined(MULTIPROCESSOR)
    519 	if (dobiglock) {
    520 		/*
    521 		 * Release the kernel_lock, as we are about to
    522 		 * yield the CPU.  The scheduler_slock is still
    523 		 * held until cpu_switch() selects a new process
    524 		 * and removes it from the run queue.
    525 		 */
    526 		held_count = kernel_lock_release_all();
    527 	}
    528 #endif
    529 
    530 	SCHED_ASSERT_LOCKED();
    531 	mi_switch(p);
    532 
    533 #ifdef	DDB
    534 	/* handy breakpoint location after process "wakes" */
    535 	asm(".globl bpendtsleep ; bpendtsleep:");
    536 #endif
    537 
    538 	SCHED_ASSERT_UNLOCKED();
    539 	splx(s);
    540 
    541  resume:
    542 	KDASSERT(p->p_cpu != NULL);
    543 	KDASSERT(p->p_cpu == curcpu());
    544 	p->p_cpu->ci_schedstate.spc_curpriority = p->p_usrpri;
    545 
    546 #if defined(MULTIPROCESSOR)
    547 	if (dobiglock) {
    548 		/*
    549 		 * Reacquire the kernel_lock now.  We do this after
    550 		 * we've released sched_lock to avoid deadlock,
    551 		 * and before we reacquire the interlock.
    552 		 */
    553 		kernel_lock_acquire_count(LK_EXCLUSIVE|LK_CANRECURSE,
    554 		    held_count);
    555 	}
    556 #endif
    557 	p->p_flag &= ~P_SINTR;
    558 	if (p->p_flag & P_TIMEOUT) {
    559 		p->p_flag &= ~P_TIMEOUT;
    560 		if (sig == 0) {
    561 #ifdef KTRACE
    562 			if (KTRPOINT(p, KTR_CSW))
    563 				ktrcsw(p, 0, 0);
    564 #endif
    565 			if (relock && interlock != NULL)
    566 				simple_lock(interlock);
    567 			return (EWOULDBLOCK);
    568 		}
    569 	} else if (timo)
    570 		callout_stop(&p->p_tsleep_ch);
    571 	if (catch && (sig != 0 || (sig = CURSIG(p)) != 0)) {
    572 #ifdef KTRACE
    573 		if (KTRPOINT(p, KTR_CSW))
    574 			ktrcsw(p, 0, 0);
    575 #endif
    576 		if (relock && interlock != NULL)
    577 			simple_lock(interlock);
    578 		if ((p->p_sigacts->ps_sigact[sig].sa_flags & SA_RESTART) == 0)
    579 			return (EINTR);
    580 		return (ERESTART);
    581 	}
    582 #ifdef KTRACE
    583 	if (KTRPOINT(p, KTR_CSW))
    584 		ktrcsw(p, 0, 0);
    585 #endif
    586 	if (relock && interlock != NULL)
    587 		simple_lock(interlock);
    588 	return (0);
    589 }
    590 
    591 /*
    592  * Implement timeout for tsleep.
    593  * If process hasn't been awakened (wchan non-zero),
    594  * set timeout flag and undo the sleep.  If proc
    595  * is stopped, just unsleep so it will remain stopped.
    596  */
    597 void
    598 endtsleep(void *arg)
    599 {
    600 	struct proc *p;
    601 	int s;
    602 
    603 	p = (struct proc *)arg;
    604 
    605 	SCHED_LOCK(s);
    606 	if (p->p_wchan) {
    607 		if (p->p_stat == SSLEEP)
    608 			setrunnable(p);
    609 		else
    610 			unsleep(p);
    611 		p->p_flag |= P_TIMEOUT;
    612 	}
    613 	SCHED_UNLOCK(s);
    614 }
    615 
    616 /*
    617  * Remove a process from its wait queue
    618  */
    619 void
    620 unsleep(struct proc *p)
    621 {
    622 	struct slpque *qp;
    623 	struct proc **hp;
    624 
    625 	SCHED_ASSERT_LOCKED();
    626 
    627 	if (p->p_wchan) {
    628 		hp = &(qp = SLPQUE(p->p_wchan))->sq_head;
    629 		while (*hp != p)
    630 			hp = &(*hp)->p_forw;
    631 		*hp = p->p_forw;
    632 		if (qp->sq_tailp == &p->p_forw)
    633 			qp->sq_tailp = hp;
    634 		p->p_wchan = 0;
    635 	}
    636 }
    637 
    638 /*
    639  * Optimized-for-wakeup() version of setrunnable().
    640  */
    641 __inline void
    642 awaken(struct proc *p)
    643 {
    644 
    645 	SCHED_ASSERT_LOCKED();
    646 
    647 	if (p->p_slptime > 1)
    648 		updatepri(p);
    649 	p->p_slptime = 0;
    650 	p->p_stat = SRUN;
    651 
    652 	/*
    653 	 * Since curpriority is a user priority, p->p_priority
    654 	 * is always better than curpriority.
    655 	 */
    656 	if (p->p_flag & P_INMEM) {
    657 		setrunqueue(p);
    658 		need_resched();
    659 	} else
    660 		sched_wakeup(&proc0);
    661 }
    662 
    663 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
    664 void
    665 sched_unlock_idle(void)
    666 {
    667 
    668 	simple_unlock(&sched_lock);
    669 }
    670 
    671 void
    672 sched_lock_idle(void)
    673 {
    674 
    675 	simple_lock(&sched_lock);
    676 }
    677 #endif /* MULTIPROCESSOR || LOCKDEBUG */
    678 
    679 /*
    680  * Make all processes sleeping on the specified identifier runnable.
    681  */
    682 
    683 void
    684 wakeup(void *ident)
    685 {
    686 	int s;
    687 
    688 	SCHED_ASSERT_UNLOCKED();
    689 
    690 	SCHED_LOCK(s);
    691 	sched_wakeup(ident);
    692 	SCHED_UNLOCK(s);
    693 }
    694 
    695 void
    696 sched_wakeup(void *ident)
    697 {
    698 	struct slpque *qp;
    699 	struct proc *p, **q;
    700 
    701 	SCHED_ASSERT_LOCKED();
    702 
    703 	qp = SLPQUE(ident);
    704  restart:
    705 	for (q = &qp->sq_head; (p = *q) != NULL; ) {
    706 #ifdef DIAGNOSTIC
    707 		if (p->p_back || (p->p_stat != SSLEEP && p->p_stat != SSTOP))
    708 			panic("wakeup");
    709 #endif
    710 		if (p->p_wchan == ident) {
    711 			p->p_wchan = 0;
    712 			*q = p->p_forw;
    713 			if (qp->sq_tailp == &p->p_forw)
    714 				qp->sq_tailp = q;
    715 			if (p->p_stat == SSLEEP) {
    716 				awaken(p);
    717 				goto restart;
    718 			}
    719 		} else
    720 			q = &p->p_forw;
    721 	}
    722 }
    723 
    724 /*
    725  * Make the highest priority process first in line on the specified
    726  * identifier runnable.
    727  */
    728 void
    729 wakeup_one(void *ident)
    730 {
    731 	struct slpque *qp;
    732 	struct proc *p, **q;
    733 	struct proc *best_sleepp, **best_sleepq;
    734 	struct proc *best_stopp, **best_stopq;
    735 	int s;
    736 
    737 	best_sleepp = best_stopp = NULL;
    738 	best_sleepq = best_stopq = NULL;
    739 
    740 	SCHED_LOCK(s);
    741 
    742 	qp = SLPQUE(ident);
    743 
    744 	for (q = &qp->sq_head; (p = *q) != NULL; q = &p->p_forw) {
    745 #ifdef DIAGNOSTIC
    746 		if (p->p_back || (p->p_stat != SSLEEP && p->p_stat != SSTOP))
    747 			panic("wakeup_one");
    748 #endif
    749 		if (p->p_wchan == ident) {
    750 			if (p->p_stat == SSLEEP) {
    751 				if (best_sleepp == NULL ||
    752 				    p->p_priority < best_sleepp->p_priority) {
    753 					best_sleepp = p;
    754 					best_sleepq = q;
    755 				}
    756 			} else {
    757 				if (best_stopp == NULL ||
    758 				    p->p_priority < best_stopp->p_priority) {
    759 					best_stopp = p;
    760 					best_stopq = q;
    761 				}
    762 			}
    763 		}
    764 	}
    765 
    766 	/*
    767 	 * Consider any SSLEEP process higher than the highest priority SSTOP
    768 	 * process.
    769 	 */
    770 	if (best_sleepp != NULL) {
    771 		p = best_sleepp;
    772 		q = best_sleepq;
    773 	} else {
    774 		p = best_stopp;
    775 		q = best_stopq;
    776 	}
    777 
    778 	if (p != NULL) {
    779 		p->p_wchan = NULL;
    780 		*q = p->p_forw;
    781 		if (qp->sq_tailp == &p->p_forw)
    782 			qp->sq_tailp = q;
    783 		if (p->p_stat == SSLEEP)
    784 			awaken(p);
    785 	}
    786 	SCHED_UNLOCK(s);
    787 }
    788 
    789 /*
    790  * General yield call.  Puts the current process back on its run queue and
    791  * performs a voluntary context switch.
    792  */
    793 void
    794 yield(void)
    795 {
    796 	struct proc *p = curproc;
    797 	int s;
    798 
    799 	SCHED_LOCK(s);
    800 	p->p_priority = p->p_usrpri;
    801 	p->p_stat = SRUN;
    802 	setrunqueue(p);
    803 	p->p_stats->p_ru.ru_nvcsw++;
    804 	mi_switch(p);
    805 	SCHED_ASSERT_UNLOCKED();
    806 	splx(s);
    807 }
    808 
    809 /*
    810  * General preemption call.  Puts the current process back on its run queue
    811  * and performs an involuntary context switch.  If a process is supplied,
    812  * we switch to that process.  Otherwise, we use the normal process selection
    813  * criteria.
    814  */
    815 void
    816 preempt(struct proc *newp)
    817 {
    818 	struct proc *p = curproc;
    819 	int s;
    820 
    821 	/*
    822 	 * XXX Switching to a specific process is not supported yet.
    823 	 */
    824 	if (newp != NULL)
    825 		panic("preempt: cpu_preempt not yet implemented");
    826 
    827 	SCHED_LOCK(s);
    828 	p->p_priority = p->p_usrpri;
    829 	p->p_stat = SRUN;
    830 	setrunqueue(p);
    831 	p->p_stats->p_ru.ru_nivcsw++;
    832 	mi_switch(p);
    833 	SCHED_ASSERT_UNLOCKED();
    834 	splx(s);
    835 }
    836 
    837 /*
    838  * The machine independent parts of context switch.
    839  * Must be called at splstatclock() or higher.
    840  */
    841 void
    842 mi_switch(struct proc *p)
    843 {
    844 	struct schedstate_percpu *spc;
    845 	struct rlimit *rlim;
    846 	long s, u;
    847 	struct timeval tv;
    848 
    849 	SCHED_ASSERT_LOCKED();
    850 
    851 	KDASSERT(p->p_cpu != NULL);
    852 	KDASSERT(p->p_cpu == curcpu());
    853 
    854 	spc = &p->p_cpu->ci_schedstate;
    855 
    856 #if defined(LOCKDEBUG) || defined(DIAGNOSTIC)
    857 	spinlock_switchcheck();
    858 #endif
    859 #ifdef LOCKDEBUG
    860 	simple_lock_switchcheck();
    861 #endif
    862 
    863 	/*
    864 	 * Compute the amount of time during which the current
    865 	 * process was running, and add that to its total so far.
    866 	 */
    867 	microtime(&tv);
    868 	u = p->p_rtime.tv_usec + (tv.tv_usec - spc->spc_runtime.tv_usec);
    869 	s = p->p_rtime.tv_sec + (tv.tv_sec - spc->spc_runtime.tv_sec);
    870 	if (u < 0) {
    871 		u += 1000000;
    872 		s--;
    873 	} else if (u >= 1000000) {
    874 		u -= 1000000;
    875 		s++;
    876 	}
    877 	p->p_rtime.tv_usec = u;
    878 	p->p_rtime.tv_sec = s;
    879 
    880 	/*
    881 	 * Check if the process exceeds its cpu resource allocation.
    882 	 * If over max, kill it.  In any case, if it has run for more
    883 	 * than 10 minutes, reduce priority to give others a chance.
    884 	 */
    885 	rlim = &p->p_rlimit[RLIMIT_CPU];
    886 	if (s >= rlim->rlim_cur) {
    887 		if (s >= rlim->rlim_max)
    888 			psignal(p, SIGKILL);
    889 		else {
    890 			psignal(p, SIGXCPU);
    891 			if (rlim->rlim_cur < rlim->rlim_max)
    892 				rlim->rlim_cur += 5;
    893 		}
    894 	}
    895 	if (autonicetime && s > autonicetime && p->p_ucred->cr_uid &&
    896 	    p->p_nice == NZERO) {
    897 		p->p_nice = autoniceval + NZERO;
    898 		resetpriority(p);
    899 	}
    900 
    901 	/*
    902 	 * Process is about to yield the CPU; clear the appropriate
    903 	 * scheduling flags.
    904 	 */
    905 	spc->spc_flags &= ~SPCF_SWITCHCLEAR;
    906 
    907 	/*
    908 	 * Pick a new current process and switch to it.  When we
    909 	 * run again, we'll return back here.
    910 	 */
    911 	uvmexp.swtch++;
    912 	cpu_switch(p);
    913 
    914 	/*
    915 	 * Make sure that MD code released the scheduler lock before
    916 	 * resuming us.
    917 	 */
    918 	SCHED_ASSERT_UNLOCKED();
    919 
    920 	/*
    921 	 * We're running again; record our new start time.  We might
    922 	 * be running on a new CPU now, so don't use the cache'd
    923 	 * schedstate_percpu pointer.
    924 	 */
    925 	KDASSERT(p->p_cpu != NULL);
    926 	KDASSERT(p->p_cpu == curcpu());
    927 	microtime(&p->p_cpu->ci_schedstate.spc_runtime);
    928 }
    929 
    930 /*
    931  * Initialize the (doubly-linked) run queues
    932  * to be empty.
    933  */
    934 void
    935 rqinit()
    936 {
    937 	int i;
    938 
    939 	for (i = 0; i < RUNQUE_NQS; i++)
    940 		sched_qs[i].ph_link = sched_qs[i].ph_rlink =
    941 		    (struct proc *)&sched_qs[i];
    942 }
    943 
    944 /*
    945  * Change process state to be runnable,
    946  * placing it on the run queue if it is in memory,
    947  * and awakening the swapper if it isn't in memory.
    948  */
    949 void
    950 setrunnable(struct proc *p)
    951 {
    952 
    953 	SCHED_ASSERT_LOCKED();
    954 
    955 	switch (p->p_stat) {
    956 	case 0:
    957 	case SRUN:
    958 	case SONPROC:
    959 	case SZOMB:
    960 	case SDEAD:
    961 	default:
    962 		panic("setrunnable");
    963 	case SSTOP:
    964 		/*
    965 		 * If we're being traced (possibly because someone attached us
    966 		 * while we were stopped), check for a signal from the debugger.
    967 		 */
    968 		if ((p->p_flag & P_TRACED) != 0 && p->p_xstat != 0) {
    969 			sigaddset(&p->p_siglist, p->p_xstat);
    970 			p->p_sigcheck = 1;
    971 		}
    972 	case SSLEEP:
    973 		unsleep(p);		/* e.g. when sending signals */
    974 		break;
    975 
    976 	case SIDL:
    977 		break;
    978 	}
    979 	p->p_stat = SRUN;
    980 	if (p->p_flag & P_INMEM)
    981 		setrunqueue(p);
    982 
    983 	if (p->p_slptime > 1)
    984 		updatepri(p);
    985 	p->p_slptime = 0;
    986 	if ((p->p_flag & P_INMEM) == 0)
    987 		sched_wakeup((caddr_t)&proc0);
    988 	else if (p->p_priority < curcpu()->ci_schedstate.spc_curpriority) {
    989 		/*
    990 		 * XXXSMP
    991 		 * This is wrong.  It will work, but what really
    992 		 * needs to happen is:
    993 		 *
    994 		 *	- Need to check if p is higher priority
    995 		 *	  than the process currently running on
    996 		 *	  the CPU p last ran on (let p_cpu persist
    997 		 *	  after a context switch?), and preempt
    998 		 *	  that one (or, if there is no process
    999 		 *	  there, simply need_resched() that CPU.
   1000 		 *
   1001 		 *	- Failing that, traverse a list of
   1002 		 *	  available CPUs and need_resched() the
   1003 		 *	  CPU with the lowest priority that's
   1004 		 *	  lower than p's.
   1005 		 */
   1006 		need_resched();
   1007 	}
   1008 }
   1009 
   1010 /*
   1011  * Compute the priority of a process when running in user mode.
   1012  * Arrange to reschedule if the resulting priority is better
   1013  * than that of the current process.
   1014  */
   1015 void
   1016 resetpriority(struct proc *p)
   1017 {
   1018 	unsigned int newpriority;
   1019 
   1020 	SCHED_ASSERT_LOCKED();
   1021 
   1022 	newpriority = PUSER + p->p_estcpu + NICE_WEIGHT * (p->p_nice - NZERO);
   1023 	newpriority = min(newpriority, MAXPRI);
   1024 	p->p_usrpri = newpriority;
   1025 	if (newpriority < curcpu()->ci_schedstate.spc_curpriority) {
   1026 		/*
   1027 		 * XXXSMP
   1028 		 * Same applies as in setrunnable() above.
   1029 		 */
   1030 		need_resched();
   1031 	}
   1032 }
   1033 
   1034 /*
   1035  * We adjust the priority of the current process.  The priority of a process
   1036  * gets worse as it accumulates CPU time.  The cpu usage estimator (p_estcpu)
   1037  * is increased here.  The formula for computing priorities (in kern_synch.c)
   1038  * will compute a different value each time p_estcpu increases. This can
   1039  * cause a switch, but unless the priority crosses a PPQ boundary the actual
   1040  * queue will not change.  The cpu usage estimator ramps up quite quickly
   1041  * when the process is running (linearly), and decays away exponentially, at
   1042  * a rate which is proportionally slower when the system is busy.  The basic
   1043  * principle is that the system will 90% forget that the process used a lot
   1044  * of CPU time in 5 * loadav seconds.  This causes the system to favor
   1045  * processes which haven't run much recently, and to round-robin among other
   1046  * processes.
   1047  */
   1048 
   1049 void
   1050 schedclock(struct proc *p)
   1051 {
   1052 	int s;
   1053 
   1054 	p->p_estcpu = ESTCPULIM(p->p_estcpu + 1);
   1055 
   1056 	SCHED_LOCK(s);
   1057 	resetpriority(p);
   1058 	SCHED_UNLOCK(s);
   1059 
   1060 	if (p->p_priority >= PUSER)
   1061 		p->p_priority = p->p_usrpri;
   1062 }
   1063