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