Home | History | Annotate | Line # | Download | only in kern
kern_synch.c revision 1.187
      1 /*	$NetBSD: kern_synch.c,v 1.187 2007/03/11 21:36:49 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999, 2000, 2004, 2006, 2007 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, by Charles M. Hannum, and by Andrew Doran.
     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. Neither the name of the University nor the names of its contributors
     58  *    may be used to endorse or promote products derived from this software
     59  *    without specific prior written permission.
     60  *
     61  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     62  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     63  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     64  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     65  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     66  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     67  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     68  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     69  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     70  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     71  * SUCH DAMAGE.
     72  *
     73  *	@(#)kern_synch.c	8.9 (Berkeley) 5/19/95
     74  */
     75 
     76 #include <sys/cdefs.h>
     77 __KERNEL_RCSID(0, "$NetBSD: kern_synch.c,v 1.187 2007/03/11 21:36:49 ad Exp $");
     78 
     79 #include "opt_ddb.h"
     80 #include "opt_kstack.h"
     81 #include "opt_lockdebug.h"
     82 #include "opt_multiprocessor.h"
     83 #include "opt_perfctrs.h"
     84 
     85 #define	__MUTEX_PRIVATE
     86 
     87 #include <sys/param.h>
     88 #include <sys/systm.h>
     89 #include <sys/callout.h>
     90 #include <sys/proc.h>
     91 #include <sys/kernel.h>
     92 #include <sys/buf.h>
     93 #if defined(PERFCTRS)
     94 #include <sys/pmc.h>
     95 #endif
     96 #include <sys/signalvar.h>
     97 #include <sys/resourcevar.h>
     98 #include <sys/sched.h>
     99 #include <sys/syscall_stats.h>
    100 #include <sys/kauth.h>
    101 #include <sys/sleepq.h>
    102 #include <sys/lockdebug.h>
    103 
    104 #include <uvm/uvm_extern.h>
    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 kmutex_t	sched_mutex;		/* global sched state mutex */
    115 struct prochd	sched_qs[RUNQUE_NQS];	/* run queues */
    116 volatile uint32_t sched_whichqs;	/* bitmap of non-empty queues */
    117 
    118 void	schedcpu(void *);
    119 void	updatepri(struct lwp *);
    120 
    121 void	sched_unsleep(struct lwp *);
    122 void	sched_changepri(struct lwp *, pri_t);
    123 void	sched_lendpri(struct lwp *, pri_t);
    124 
    125 struct callout schedcpu_ch = CALLOUT_INITIALIZER_SETFUNC(schedcpu, NULL);
    126 static unsigned int schedcpu_ticks;
    127 
    128 syncobj_t sleep_syncobj = {
    129 	SOBJ_SLEEPQ_SORTED,
    130 	sleepq_unsleep,
    131 	sleepq_changepri,
    132 	sleepq_lendpri,
    133 	syncobj_noowner,
    134 };
    135 
    136 syncobj_t sched_syncobj = {
    137 	SOBJ_SLEEPQ_SORTED,
    138 	sched_unsleep,
    139 	sched_changepri,
    140 	sched_lendpri,
    141 	syncobj_noowner,
    142 };
    143 
    144 /*
    145  * Force switch among equal priority processes every 100ms.
    146  * Called from hardclock every hz/10 == rrticks hardclock ticks.
    147  */
    148 /* ARGSUSED */
    149 void
    150 roundrobin(struct cpu_info *ci)
    151 {
    152 	struct schedstate_percpu *spc = &ci->ci_schedstate;
    153 
    154 	spc->spc_rrticks = rrticks;
    155 
    156 	if (curlwp != NULL) {
    157 		if (spc->spc_flags & SPCF_SEENRR) {
    158 			/*
    159 			 * The process has already been through a roundrobin
    160 			 * without switching and may be hogging the CPU.
    161 			 * Indicate that the process should yield.
    162 			 */
    163 			spc->spc_flags |= SPCF_SHOULDYIELD;
    164 		} else
    165 			spc->spc_flags |= SPCF_SEENRR;
    166 	}
    167 	cpu_need_resched(curcpu());
    168 }
    169 
    170 #define	PPQ	(128 / RUNQUE_NQS)	/* priorities per queue */
    171 #define	NICE_WEIGHT 2			/* priorities per nice level */
    172 
    173 #define	ESTCPU_SHIFT	11
    174 #define	ESTCPU_MAX	((NICE_WEIGHT * PRIO_MAX - PPQ) << ESTCPU_SHIFT)
    175 #define	ESTCPULIM(e)	min((e), ESTCPU_MAX)
    176 
    177 /*
    178  * Constants for digital decay and forget:
    179  *	90% of (p_estcpu) usage in 5 * loadav time
    180  *	95% of (p_pctcpu) usage in 60 seconds (load insensitive)
    181  *          Note that, as ps(1) mentions, this can let percentages
    182  *          total over 100% (I've seen 137.9% for 3 processes).
    183  *
    184  * Note that hardclock updates p_estcpu and p_cpticks independently.
    185  *
    186  * We wish to decay away 90% of p_estcpu in (5 * loadavg) seconds.
    187  * That is, the system wants to compute a value of decay such
    188  * that the following for loop:
    189  * 	for (i = 0; i < (5 * loadavg); i++)
    190  * 		p_estcpu *= decay;
    191  * will compute
    192  * 	p_estcpu *= 0.1;
    193  * for all values of loadavg:
    194  *
    195  * Mathematically this loop can be expressed by saying:
    196  * 	decay ** (5 * loadavg) ~= .1
    197  *
    198  * The system computes decay as:
    199  * 	decay = (2 * loadavg) / (2 * loadavg + 1)
    200  *
    201  * We wish to prove that the system's computation of decay
    202  * will always fulfill the equation:
    203  * 	decay ** (5 * loadavg) ~= .1
    204  *
    205  * If we compute b as:
    206  * 	b = 2 * loadavg
    207  * then
    208  * 	decay = b / (b + 1)
    209  *
    210  * We now need to prove two things:
    211  *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
    212  *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
    213  *
    214  * Facts:
    215  *         For x close to zero, exp(x) =~ 1 + x, since
    216  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
    217  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
    218  *         For x close to zero, ln(1+x) =~ x, since
    219  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
    220  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
    221  *         ln(.1) =~ -2.30
    222  *
    223  * Proof of (1):
    224  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
    225  *	solving for factor,
    226  *      ln(factor) =~ (-2.30/5*loadav), or
    227  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
    228  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
    229  *
    230  * Proof of (2):
    231  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
    232  *	solving for power,
    233  *      power*ln(b/(b+1)) =~ -2.30, or
    234  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
    235  *
    236  * Actual power values for the implemented algorithm are as follows:
    237  *      loadav: 1       2       3       4
    238  *      power:  5.68    10.32   14.94   19.55
    239  */
    240 
    241 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
    242 #define	loadfactor(loadav)	(2 * (loadav))
    243 
    244 static fixpt_t
    245 decay_cpu(fixpt_t loadfac, fixpt_t estcpu)
    246 {
    247 
    248 	if (estcpu == 0) {
    249 		return 0;
    250 	}
    251 
    252 #if !defined(_LP64)
    253 	/* avoid 64bit arithmetics. */
    254 #define	FIXPT_MAX ((fixpt_t)((UINTMAX_C(1) << sizeof(fixpt_t) * CHAR_BIT) - 1))
    255 	if (__predict_true(loadfac <= FIXPT_MAX / ESTCPU_MAX)) {
    256 		return estcpu * loadfac / (loadfac + FSCALE);
    257 	}
    258 #endif /* !defined(_LP64) */
    259 
    260 	return (uint64_t)estcpu * loadfac / (loadfac + FSCALE);
    261 }
    262 
    263 /*
    264  * For all load averages >= 1 and max p_estcpu of (255 << ESTCPU_SHIFT),
    265  * sleeping for at least seven times the loadfactor will decay p_estcpu to
    266  * less than (1 << ESTCPU_SHIFT).
    267  *
    268  * note that our ESTCPU_MAX is actually much smaller than (255 << ESTCPU_SHIFT).
    269  */
    270 static fixpt_t
    271 decay_cpu_batch(fixpt_t loadfac, fixpt_t estcpu, unsigned int n)
    272 {
    273 
    274 	if ((n << FSHIFT) >= 7 * loadfac) {
    275 		return 0;
    276 	}
    277 
    278 	while (estcpu != 0 && n > 1) {
    279 		estcpu = decay_cpu(loadfac, estcpu);
    280 		n--;
    281 	}
    282 
    283 	return estcpu;
    284 }
    285 
    286 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
    287 fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;		/* exp(-1/20) */
    288 
    289 /*
    290  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
    291  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
    292  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
    293  *
    294  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
    295  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
    296  *
    297  * If you dont want to bother with the faster/more-accurate formula, you
    298  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
    299  * (more general) method of calculating the %age of CPU used by a process.
    300  */
    301 #define	CCPU_SHIFT	11
    302 
    303 /*
    304  * schedcpu:
    305  *
    306  *	Recompute process priorities, every hz ticks.
    307  *
    308  *	XXXSMP This needs to be reorganised in order to reduce the locking
    309  *	burden.
    310  */
    311 /* ARGSUSED */
    312 void
    313 schedcpu(void *arg)
    314 {
    315 	fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
    316 	struct rlimit *rlim;
    317 	struct lwp *l;
    318 	struct proc *p;
    319 	int minslp, clkhz, sig;
    320 	long runtm;
    321 
    322 	schedcpu_ticks++;
    323 
    324 	mutex_enter(&proclist_mutex);
    325 	PROCLIST_FOREACH(p, &allproc) {
    326 		/*
    327 		 * Increment time in/out of memory and sleep time (if
    328 		 * sleeping).  We ignore overflow; with 16-bit int's
    329 		 * (remember them?) overflow takes 45 days.
    330 		 */
    331 		minslp = 2;
    332 		mutex_enter(&p->p_smutex);
    333 		runtm = p->p_rtime.tv_sec;
    334 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    335 			lwp_lock(l);
    336 			runtm += l->l_rtime.tv_sec;
    337 			l->l_swtime++;
    338 			if (l->l_stat == LSSLEEP || l->l_stat == LSSTOP ||
    339 			    l->l_stat == LSSUSPENDED) {
    340 				l->l_slptime++;
    341 				minslp = min(minslp, l->l_slptime);
    342 			} else
    343 				minslp = 0;
    344 			lwp_unlock(l);
    345 		}
    346 		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
    347 
    348 		/*
    349 		 * Check if the process exceeds its CPU resource allocation.
    350 		 * If over max, kill it.
    351 		 */
    352 		rlim = &p->p_rlimit[RLIMIT_CPU];
    353 		sig = 0;
    354 		if (runtm >= rlim->rlim_cur) {
    355 			if (runtm >= rlim->rlim_max)
    356 				sig = SIGKILL;
    357 			else {
    358 				sig = SIGXCPU;
    359 				if (rlim->rlim_cur < rlim->rlim_max)
    360 					rlim->rlim_cur += 5;
    361 			}
    362 		}
    363 
    364 		/*
    365 		 * If the process has run for more than autonicetime, reduce
    366 		 * priority to give others a chance.
    367 		 */
    368 		if (autonicetime && runtm > autonicetime && p->p_nice == NZERO
    369 		    && kauth_cred_geteuid(p->p_cred)) {
    370 			mutex_spin_enter(&p->p_stmutex);
    371 			p->p_nice = autoniceval + NZERO;
    372 			resetprocpriority(p);
    373 			mutex_spin_exit(&p->p_stmutex);
    374 		}
    375 
    376 		/*
    377 		 * If the process has slept the entire second,
    378 		 * stop recalculating its priority until it wakes up.
    379 		 */
    380 		if (minslp <= 1) {
    381 			/*
    382 			 * p_pctcpu is only for ps.
    383 			 */
    384 			mutex_spin_enter(&p->p_stmutex);
    385 			clkhz = stathz != 0 ? stathz : hz;
    386 #if	(FSHIFT >= CCPU_SHIFT)
    387 			p->p_pctcpu += (clkhz == 100)?
    388 			    ((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT):
    389 			    100 * (((fixpt_t) p->p_cpticks)
    390 			    << (FSHIFT - CCPU_SHIFT)) / clkhz;
    391 #else
    392 			p->p_pctcpu += ((FSCALE - ccpu) *
    393 			    (p->p_cpticks * FSCALE / clkhz)) >> FSHIFT;
    394 #endif
    395 			p->p_cpticks = 0;
    396 			p->p_estcpu = decay_cpu(loadfac, p->p_estcpu);
    397 
    398 			LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    399 				lwp_lock(l);
    400 				if (l->l_slptime <= 1 &&
    401 				    l->l_priority >= PUSER)
    402 					resetpriority(l);
    403 				lwp_unlock(l);
    404 			}
    405 			mutex_spin_exit(&p->p_stmutex);
    406 		}
    407 
    408 		mutex_exit(&p->p_smutex);
    409 		if (sig) {
    410 			psignal(p, sig);
    411 		}
    412 	}
    413 	mutex_exit(&proclist_mutex);
    414 	uvm_meter();
    415 	wakeup((void *)&lbolt);
    416 	callout_schedule(&schedcpu_ch, hz);
    417 }
    418 
    419 /*
    420  * Recalculate the priority of a process after it has slept for a while.
    421  */
    422 void
    423 updatepri(struct lwp *l)
    424 {
    425 	struct proc *p = l->l_proc;
    426 	fixpt_t loadfac;
    427 
    428 	LOCK_ASSERT(lwp_locked(l, NULL));
    429 	KASSERT(l->l_slptime > 1);
    430 
    431 	loadfac = loadfactor(averunnable.ldavg[0]);
    432 
    433 	l->l_slptime--; /* the first time was done in schedcpu */
    434 	/* XXX NJWLWP */
    435 	/* XXXSMP occasionally unlocked, should be per-LWP */
    436 	p->p_estcpu = decay_cpu_batch(loadfac, p->p_estcpu, l->l_slptime);
    437 	resetpriority(l);
    438 }
    439 
    440 /*
    441  * During autoconfiguration or after a panic, a sleep will simply lower the
    442  * priority briefly to allow interrupts, then return.  The priority to be
    443  * used (safepri) is machine-dependent, thus this value is initialized and
    444  * maintained in the machine-dependent layers.  This priority will typically
    445  * be 0, or the lowest priority that is safe for use on the interrupt stack;
    446  * it can be made higher to block network software interrupts after panics.
    447  */
    448 int	safepri;
    449 
    450 /*
    451  * OBSOLETE INTERFACE
    452  *
    453  * General sleep call.  Suspends the current process until a wakeup is
    454  * performed on the specified identifier.  The process will then be made
    455  * runnable with the specified priority.  Sleeps at most timo/hz seconds (0
    456  * means no timeout).  If pri includes PCATCH flag, signals are checked
    457  * before and after sleeping, else signals are not checked.  Returns 0 if
    458  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
    459  * signal needs to be delivered, ERESTART is returned if the current system
    460  * call should be restarted if possible, and EINTR is returned if the system
    461  * call should be interrupted by the signal (return EINTR).
    462  *
    463  * The interlock is held until we are on a sleep queue. The interlock will
    464  * be locked before returning back to the caller unless the PNORELOCK flag
    465  * is specified, in which case the interlock will always be unlocked upon
    466  * return.
    467  */
    468 int
    469 ltsleep(wchan_t ident, pri_t priority, const char *wmesg, int timo,
    470 	volatile struct simplelock *interlock)
    471 {
    472 	struct lwp *l = curlwp;
    473 	sleepq_t *sq;
    474 	int error, catch;
    475 
    476 	if (sleepq_dontsleep(l)) {
    477 		(void)sleepq_abort(NULL, 0);
    478 		if ((priority & PNORELOCK) != 0)
    479 			simple_unlock(interlock);
    480 		return 0;
    481 	}
    482 
    483 	sq = sleeptab_lookup(&sleeptab, ident);
    484 	sleepq_enter(sq, l);
    485 
    486 	if (interlock != NULL) {
    487 		LOCK_ASSERT(simple_lock_held(interlock));
    488 		simple_unlock(interlock);
    489 	}
    490 
    491 	catch = priority & PCATCH;
    492 	sleepq_block(sq, priority & PRIMASK, ident, wmesg, timo, catch,
    493 	    &sleep_syncobj);
    494 	error = sleepq_unblock(timo, catch);
    495 
    496 	if (interlock != NULL && (priority & PNORELOCK) == 0)
    497 		simple_lock(interlock);
    498 
    499 	return error;
    500 }
    501 
    502 int
    503 mtsleep(wchan_t ident, pri_t priority, const char *wmesg, int timo,
    504 	kmutex_t *mtx)
    505 {
    506 	struct lwp *l = curlwp;
    507 	sleepq_t *sq;
    508 	int error, catch;
    509 
    510 	if (sleepq_dontsleep(l)) {
    511 		(void)sleepq_abort(mtx, (priority & PNORELOCK) != 0);
    512 		return 0;
    513 	}
    514 
    515 	sq = sleeptab_lookup(&sleeptab, ident);
    516 	sleepq_enter(sq, l);
    517 	mutex_exit(mtx);
    518 
    519 	catch = priority & PCATCH;
    520 	sleepq_block(sq, priority & PRIMASK, ident, wmesg, timo, catch,
    521 	    &sleep_syncobj);
    522 	error = sleepq_unblock(timo, catch);
    523 
    524 	if ((priority & PNORELOCK) == 0)
    525 		mutex_enter(mtx);
    526 
    527 	return error;
    528 }
    529 
    530 /*
    531  * General sleep call for situations where a wake-up is not expected.
    532  */
    533 int
    534 kpause(const char *wmesg, bool intr, int timo, kmutex_t *mtx)
    535 {
    536 	struct lwp *l = curlwp;
    537 	sleepq_t *sq;
    538 	int error;
    539 
    540 	if (sleepq_dontsleep(l))
    541 		return sleepq_abort(NULL, 0);
    542 
    543 	if (mtx != NULL)
    544 		mutex_exit(mtx);
    545 	sq = sleeptab_lookup(&sleeptab, l);
    546 	sleepq_enter(sq, l);
    547 	sleepq_block(sq, sched_kpri(l), l, wmesg, timo, intr, &sleep_syncobj);
    548 	error = sleepq_unblock(timo, intr);
    549 	if (mtx != NULL)
    550 		mutex_enter(mtx);
    551 
    552 	return error;
    553 }
    554 
    555 /*
    556  * OBSOLETE INTERFACE
    557  *
    558  * Make all processes sleeping on the specified identifier runnable.
    559  */
    560 void
    561 wakeup(wchan_t ident)
    562 {
    563 	sleepq_t *sq;
    564 
    565 	if (cold)
    566 		return;
    567 
    568 	sq = sleeptab_lookup(&sleeptab, ident);
    569 	sleepq_wake(sq, ident, (u_int)-1);
    570 }
    571 
    572 /*
    573  * OBSOLETE INTERFACE
    574  *
    575  * Make the highest priority process first in line on the specified
    576  * identifier runnable.
    577  */
    578 void
    579 wakeup_one(wchan_t ident)
    580 {
    581 	sleepq_t *sq;
    582 
    583 	if (cold)
    584 		return;
    585 
    586 	sq = sleeptab_lookup(&sleeptab, ident);
    587 	sleepq_wake(sq, ident, 1);
    588 }
    589 
    590 
    591 /*
    592  * General yield call.  Puts the current process back on its run queue and
    593  * performs a voluntary context switch.  Should only be called when the
    594  * current process explicitly requests it (eg sched_yield(2) in compat code).
    595  */
    596 void
    597 yield(void)
    598 {
    599 	struct lwp *l = curlwp;
    600 
    601 	KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
    602 	lwp_lock(l);
    603 	if (l->l_stat == LSONPROC) {
    604 		KASSERT(lwp_locked(l, &sched_mutex));
    605 		l->l_priority = l->l_usrpri;
    606 	}
    607 	l->l_nvcsw++;
    608 	mi_switch(l, NULL);
    609 	KERNEL_LOCK(l->l_biglocks, l);
    610 }
    611 
    612 /*
    613  * General preemption call.  Puts the current process back on its run queue
    614  * and performs an involuntary context switch.
    615  */
    616 void
    617 preempt(void)
    618 {
    619 	struct lwp *l = curlwp;
    620 
    621 	KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
    622 	lwp_lock(l);
    623 	if (l->l_stat == LSONPROC) {
    624 		KASSERT(lwp_locked(l, &sched_mutex));
    625 		l->l_priority = l->l_usrpri;
    626 	}
    627 	l->l_nivcsw++;
    628 	(void)mi_switch(l, NULL);
    629 	KERNEL_LOCK(l->l_biglocks, l);
    630 }
    631 
    632 /*
    633  * The machine independent parts of context switch.  Switch to "new"
    634  * if non-NULL, otherwise let cpu_switch choose the next lwp.
    635  *
    636  * Returns 1 if another process was actually run.
    637  */
    638 int
    639 mi_switch(struct lwp *l, struct lwp *newl)
    640 {
    641 	struct schedstate_percpu *spc;
    642 	struct timeval tv;
    643 	int retval, oldspl;
    644 	long s, u;
    645 
    646 	LOCK_ASSERT(lwp_locked(l, NULL));
    647 
    648 #ifdef LOCKDEBUG
    649 	spinlock_switchcheck();
    650 	simple_lock_switchcheck();
    651 #endif
    652 #ifdef KSTACK_CHECK_MAGIC
    653 	kstack_check_magic(l);
    654 #endif
    655 
    656 	/*
    657 	 * It's safe to read the per CPU schedstate unlocked here, as all we
    658 	 * are after is the run time and that's guarenteed to have been last
    659 	 * updated by this CPU.
    660 	 */
    661 	KDASSERT(l->l_cpu == curcpu());
    662 	spc = &l->l_cpu->ci_schedstate;
    663 
    664 	/*
    665 	 * Compute the amount of time during which the current
    666 	 * process was running.
    667 	 */
    668 	microtime(&tv);
    669 	u = l->l_rtime.tv_usec +
    670 	    (tv.tv_usec - spc->spc_runtime.tv_usec);
    671 	s = l->l_rtime.tv_sec + (tv.tv_sec - spc->spc_runtime.tv_sec);
    672 	if (u < 0) {
    673 		u += 1000000;
    674 		s--;
    675 	} else if (u >= 1000000) {
    676 		u -= 1000000;
    677 		s++;
    678 	}
    679 	l->l_rtime.tv_usec = u;
    680 	l->l_rtime.tv_sec = s;
    681 
    682 	/* Count time spent in current system call */
    683 	SYSCALL_TIME_SLEEP(l);
    684 
    685 	/*
    686 	 * XXXSMP If we are using h/w performance counters, save context.
    687 	 */
    688 #if PERFCTRS
    689 	if (PMC_ENABLED(l->l_proc)) {
    690 		pmc_save_context(l->l_proc);
    691 	}
    692 #endif
    693 
    694 	/*
    695 	 * Acquire the sched_mutex if necessary.  It will be released by
    696 	 * cpu_switch once it has decided to idle, or picked another LWP
    697 	 * to run.
    698 	 */
    699 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
    700 	if (l->l_mutex != &sched_mutex) {
    701 		mutex_spin_enter(&sched_mutex);
    702 		lwp_unlock(l);
    703 	}
    704 #endif
    705 
    706 	/*
    707 	 * If on the CPU and we have gotten this far, then we must yield.
    708 	 */
    709 	KASSERT(l->l_stat != LSRUN);
    710 	if (l->l_stat == LSONPROC) {
    711 		KASSERT(lwp_locked(l, &sched_mutex));
    712 		l->l_stat = LSRUN;
    713 		setrunqueue(l);
    714 	}
    715 	uvmexp.swtch++;
    716 
    717 	/*
    718 	 * Process is about to yield the CPU; clear the appropriate
    719 	 * scheduling flags.
    720 	 */
    721 	spc->spc_flags &= ~SPCF_SWITCHCLEAR;
    722 
    723 	LOCKDEBUG_BARRIER(&sched_mutex, 1);
    724 
    725 	/*
    726 	 * Switch to the new current LWP.  When we run again, we'll
    727 	 * return back here.
    728 	 */
    729 	oldspl = MUTEX_SPIN_OLDSPL(l->l_cpu);
    730 
    731 	if (newl == NULL || newl->l_back == NULL)
    732 		retval = cpu_switch(l, NULL);
    733 	else {
    734 		KASSERT(lwp_locked(newl, &sched_mutex));
    735 		remrunqueue(newl);
    736 		cpu_switchto(l, newl);
    737 		retval = 0;
    738 	}
    739 
    740 	/*
    741 	 * XXXSMP If we are using h/w performance counters, restore context.
    742 	 */
    743 #if PERFCTRS
    744 	if (PMC_ENABLED(l->l_proc)) {
    745 		pmc_restore_context(l->l_proc);
    746 	}
    747 #endif
    748 
    749 	/*
    750 	 * We're running again; record our new start time.  We might
    751 	 * be running on a new CPU now, so don't use the cached
    752 	 * schedstate_percpu pointer.
    753 	 */
    754 	SYSCALL_TIME_WAKEUP(l);
    755 	KDASSERT(l->l_cpu == curcpu());
    756 	microtime(&l->l_cpu->ci_schedstate.spc_runtime);
    757 	splx(oldspl);
    758 
    759 	return retval;
    760 }
    761 
    762 /*
    763  * Initialize the (doubly-linked) run queues
    764  * to be empty.
    765  */
    766 void
    767 rqinit()
    768 {
    769 	int i;
    770 
    771 	for (i = 0; i < RUNQUE_NQS; i++)
    772 		sched_qs[i].ph_link = sched_qs[i].ph_rlink =
    773 		    (struct lwp *)&sched_qs[i];
    774 
    775 	mutex_init(&sched_mutex, MUTEX_SPIN, IPL_SCHED);
    776 }
    777 
    778 static inline void
    779 resched_lwp(struct lwp *l)
    780 {
    781 	struct cpu_info *ci;
    782 	const pri_t pri = lwp_eprio(l);
    783 
    784 	/*
    785 	 * XXXSMP
    786 	 * Since l->l_cpu persists across a context switch,
    787 	 * this gives us *very weak* processor affinity, in
    788 	 * that we notify the CPU on which the process last
    789 	 * ran that it should try to switch.
    790 	 *
    791 	 * This does not guarantee that the process will run on
    792 	 * that processor next, because another processor might
    793 	 * grab it the next time it performs a context switch.
    794 	 *
    795 	 * This also does not handle the case where its last
    796 	 * CPU is running a higher-priority process, but every
    797 	 * other CPU is running a lower-priority process.  There
    798 	 * are ways to handle this situation, but they're not
    799 	 * currently very pretty, and we also need to weigh the
    800 	 * cost of moving a process from one CPU to another.
    801 	 *
    802 	 * XXXSMP
    803 	 * There is also the issue of locking the other CPU's
    804 	 * sched state, which we currently do not do.
    805 	 */
    806 	ci = (l->l_cpu != NULL) ? l->l_cpu : curcpu();
    807 	if (pri < ci->ci_schedstate.spc_curpriority)
    808 		cpu_need_resched(ci);
    809 }
    810 
    811 /*
    812  * Change process state to be runnable, placing it on the run queue if it is
    813  * in memory, and awakening the swapper if it isn't in memory.
    814  *
    815  * Call with the process and LWP locked.  Will return with the LWP unlocked.
    816  */
    817 void
    818 setrunnable(struct lwp *l)
    819 {
    820 	struct proc *p = l->l_proc;
    821 	sigset_t *ss;
    822 
    823 	KASSERT(mutex_owned(&p->p_smutex));
    824 	KASSERT(lwp_locked(l, NULL));
    825 
    826 	switch (l->l_stat) {
    827 	case LSSTOP:
    828 		/*
    829 		 * If we're being traced (possibly because someone attached us
    830 		 * while we were stopped), check for a signal from the debugger.
    831 		 */
    832 		if ((p->p_slflag & PSL_TRACED) != 0 && p->p_xstat != 0) {
    833 			if ((sigprop[p->p_xstat] & SA_TOLWP) != 0)
    834 				ss = &l->l_sigpend.sp_set;
    835 			else
    836 				ss = &p->p_sigpend.sp_set;
    837 			sigaddset(ss, p->p_xstat);
    838 			signotify(l);
    839 		}
    840 		p->p_nrlwps++;
    841 		break;
    842 	case LSSUSPENDED:
    843 		l->l_flag &= ~LW_WSUSPEND;
    844 		p->p_nrlwps++;
    845 		break;
    846 	case LSSLEEP:
    847 		KASSERT(l->l_wchan != NULL);
    848 		break;
    849 	default:
    850 		panic("setrunnable: lwp %p state was %d", l, l->l_stat);
    851 	}
    852 
    853 	/*
    854 	 * If the LWP was sleeping interruptably, then it's OK to start it
    855 	 * again.  If not, mark it as still sleeping.
    856 	 */
    857 	if (l->l_wchan != NULL) {
    858 		l->l_stat = LSSLEEP;
    859 		/* lwp_unsleep() will release the lock. */
    860 		lwp_unsleep(l);
    861 		return;
    862 	}
    863 
    864 	LOCK_ASSERT(lwp_locked(l, &sched_mutex));
    865 
    866 	/*
    867 	 * If the LWP is still on the CPU, mark it as LSONPROC.  It may be
    868 	 * about to call mi_switch(), in which case it will yield.
    869 	 *
    870 	 * XXXSMP Will need to change for preemption.
    871 	 */
    872 #ifdef MULTIPROCESSOR
    873 	if (l->l_cpu->ci_curlwp == l) {
    874 #else
    875 	if (l == curlwp) {
    876 #endif
    877 		l->l_stat = LSONPROC;
    878 		l->l_slptime = 0;
    879 		lwp_unlock(l);
    880 		return;
    881 	}
    882 
    883 	/*
    884 	 * Set the LWP runnable.  If it's swapped out, we need to wake the swapper
    885 	 * to bring it back in.  Otherwise, enter it into a run queue.
    886 	 */
    887 	if (l->l_slptime > 1)
    888 		updatepri(l);
    889 	l->l_stat = LSRUN;
    890 	l->l_slptime = 0;
    891 
    892 	if (l->l_flag & LW_INMEM) {
    893 		setrunqueue(l);
    894 		resched_lwp(l);
    895 		lwp_unlock(l);
    896 	} else {
    897 		lwp_unlock(l);
    898 		uvm_kick_scheduler();
    899 	}
    900 }
    901 
    902 /*
    903  * Compute the priority of a process when running in user mode.
    904  * Arrange to reschedule if the resulting priority is better
    905  * than that of the current process.
    906  */
    907 void
    908 resetpriority(struct lwp *l)
    909 {
    910 	pri_t newpriority;
    911 	struct proc *p = l->l_proc;
    912 
    913 	/* XXXSMP LOCK_ASSERT(mutex_owned(&p->p_stmutex)); */
    914 	LOCK_ASSERT(lwp_locked(l, NULL));
    915 
    916 	if ((l->l_flag & LW_SYSTEM) != 0)
    917 		return;
    918 
    919 	newpriority = PUSER + (p->p_estcpu >> ESTCPU_SHIFT) +
    920 	    NICE_WEIGHT * (p->p_nice - NZERO);
    921 	newpriority = min(newpriority, MAXPRI);
    922 	lwp_changepri(l, newpriority);
    923 }
    924 
    925 /*
    926  * Recompute priority for all LWPs in a process.
    927  */
    928 void
    929 resetprocpriority(struct proc *p)
    930 {
    931 	struct lwp *l;
    932 
    933 	LOCK_ASSERT(mutex_owned(&p->p_stmutex));
    934 
    935 	LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    936 		lwp_lock(l);
    937 		resetpriority(l);
    938 		lwp_unlock(l);
    939 	}
    940 }
    941 
    942 /*
    943  * We adjust the priority of the current process.  The priority of a process
    944  * gets worse as it accumulates CPU time.  The CPU usage estimator (p_estcpu)
    945  * is increased here.  The formula for computing priorities (in kern_synch.c)
    946  * will compute a different value each time p_estcpu increases. This can
    947  * cause a switch, but unless the priority crosses a PPQ boundary the actual
    948  * queue will not change.  The CPU usage estimator ramps up quite quickly
    949  * when the process is running (linearly), and decays away exponentially, at
    950  * a rate which is proportionally slower when the system is busy.  The basic
    951  * principle is that the system will 90% forget that the process used a lot
    952  * of CPU time in 5 * loadav seconds.  This causes the system to favor
    953  * processes which haven't run much recently, and to round-robin among other
    954  * processes.
    955  */
    956 
    957 void
    958 schedclock(struct lwp *l)
    959 {
    960 	struct proc *p = l->l_proc;
    961 
    962 	mutex_spin_enter(&p->p_stmutex);
    963 	p->p_estcpu = ESTCPULIM(p->p_estcpu + (1 << ESTCPU_SHIFT));
    964 	lwp_lock(l);
    965 	resetpriority(l);
    966 	mutex_spin_exit(&p->p_stmutex);
    967 	if ((l->l_flag & LW_SYSTEM) == 0 && l->l_priority >= PUSER)
    968 		l->l_priority = l->l_usrpri;
    969 	lwp_unlock(l);
    970 }
    971 
    972 /*
    973  * suspendsched:
    974  *
    975  *	Convert all non-L_SYSTEM LSSLEEP or LSRUN LWPs to LSSUSPENDED.
    976  */
    977 void
    978 suspendsched(void)
    979 {
    980 #ifdef MULTIPROCESSOR
    981 	CPU_INFO_ITERATOR cii;
    982 	struct cpu_info *ci;
    983 #endif
    984 	struct lwp *l;
    985 	struct proc *p;
    986 
    987 	/*
    988 	 * We do this by process in order not to violate the locking rules.
    989 	 */
    990 	mutex_enter(&proclist_mutex);
    991 	PROCLIST_FOREACH(p, &allproc) {
    992 		mutex_enter(&p->p_smutex);
    993 
    994 		if ((p->p_flag & PK_SYSTEM) != 0) {
    995 			mutex_exit(&p->p_smutex);
    996 			continue;
    997 		}
    998 
    999 		p->p_stat = SSTOP;
   1000 
   1001 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
   1002 			if (l == curlwp)
   1003 				continue;
   1004 
   1005 			lwp_lock(l);
   1006 
   1007 			/*
   1008 			 * Set L_WREBOOT so that the LWP will suspend itself
   1009 			 * when it tries to return to user mode.  We want to
   1010 			 * try and get to get as many LWPs as possible to
   1011 			 * the user / kernel boundary, so that they will
   1012 			 * release any locks that they hold.
   1013 			 */
   1014 			l->l_flag |= (LW_WREBOOT | LW_WSUSPEND);
   1015 
   1016 			if (l->l_stat == LSSLEEP &&
   1017 			    (l->l_flag & LW_SINTR) != 0) {
   1018 				/* setrunnable() will release the lock. */
   1019 				setrunnable(l);
   1020 				continue;
   1021 			}
   1022 
   1023 			lwp_unlock(l);
   1024 		}
   1025 
   1026 		mutex_exit(&p->p_smutex);
   1027 	}
   1028 	mutex_exit(&proclist_mutex);
   1029 
   1030 	/*
   1031 	 * Kick all CPUs to make them preempt any LWPs running in user mode.
   1032 	 * They'll trap into the kernel and suspend themselves in userret().
   1033 	 */
   1034 	sched_lock(0);
   1035 #ifdef MULTIPROCESSOR
   1036 	for (CPU_INFO_FOREACH(cii, ci))
   1037 		cpu_need_resched(ci);
   1038 #else
   1039 	cpu_need_resched(curcpu());
   1040 #endif
   1041 	sched_unlock(0);
   1042 }
   1043 
   1044 /*
   1045  * scheduler_fork_hook:
   1046  *
   1047  *	Inherit the parent's scheduler history.
   1048  */
   1049 void
   1050 scheduler_fork_hook(struct proc *parent, struct proc *child)
   1051 {
   1052 
   1053 	LOCK_ASSERT(mutex_owned(&parent->p_smutex));
   1054 
   1055 	child->p_estcpu = child->p_estcpu_inherited = parent->p_estcpu;
   1056 	child->p_forktime = schedcpu_ticks;
   1057 }
   1058 
   1059 /*
   1060  * scheduler_wait_hook:
   1061  *
   1062  *	Chargeback parents for the sins of their children.
   1063  */
   1064 void
   1065 scheduler_wait_hook(struct proc *parent, struct proc *child)
   1066 {
   1067 	fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
   1068 	fixpt_t estcpu;
   1069 
   1070 	/* XXX Only if parent != init?? */
   1071 
   1072 	mutex_spin_enter(&parent->p_stmutex);
   1073 	estcpu = decay_cpu_batch(loadfac, child->p_estcpu_inherited,
   1074 	    schedcpu_ticks - child->p_forktime);
   1075 	if (child->p_estcpu > estcpu)
   1076 		parent->p_estcpu =
   1077 		    ESTCPULIM(parent->p_estcpu + child->p_estcpu - estcpu);
   1078 	mutex_spin_exit(&parent->p_stmutex);
   1079 }
   1080 
   1081 /*
   1082  * sched_kpri:
   1083  *
   1084  *	Scale a priority level to a kernel priority level, usually
   1085  *	for an LWP that is about to sleep.
   1086  */
   1087 pri_t
   1088 sched_kpri(struct lwp *l)
   1089 {
   1090 	/*
   1091 	 * Scale user priorities (127 -> 50) up to kernel priorities
   1092 	 * in the range (49 -> 8).  Reserve the top 8 kernel priorities
   1093 	 * for high priority kthreads.  Kernel priorities passed in
   1094 	 * are left "as is".  XXX This is somewhat arbitrary.
   1095 	 */
   1096 	static const uint8_t kpri_tab[] = {
   1097 		 0,   1,   2,   3,   4,   5,   6,   7,
   1098 		 8,   9,  10,  11,  12,  13,  14,  15,
   1099 		16,  17,  18,  19,  20,  21,  22,  23,
   1100 		24,  25,  26,  27,  28,  29,  30,  31,
   1101 		32,  33,  34,  35,  36,  37,  38,  39,
   1102 		40,  41,  42,  43,  44,  45,  46,  47,
   1103 		48,  49,   8,   8,   9,   9,  10,  10,
   1104 		11,  11,  12,  12,  13,  14,  14,  15,
   1105 		15,  16,  16,  17,  17,  18,  18,  19,
   1106 		20,  20,  21,  21,  22,  22,  23,  23,
   1107 		24,  24,  25,  26,  26,  27,  27,  28,
   1108 		28,  29,  29,  30,  30,  31,  32,  32,
   1109 		33,  33,  34,  34,  35,  35,  36,  36,
   1110 		37,  38,  38,  39,  39,  40,  40,  41,
   1111 		41,  42,  42,  43,  44,  44,  45,  45,
   1112 		46,  46,  47,  47,  48,  48,  49,  49,
   1113 	};
   1114 
   1115 	return (pri_t)kpri_tab[l->l_usrpri];
   1116 }
   1117 
   1118 /*
   1119  * sched_unsleep:
   1120  *
   1121  *	The is called when the LWP has not been awoken normally but instead
   1122  *	interrupted: for example, if the sleep timed out.  Because of this,
   1123  *	it's not a valid action for running or idle LWPs.
   1124  */
   1125 void
   1126 sched_unsleep(struct lwp *l)
   1127 {
   1128 
   1129 	lwp_unlock(l);
   1130 	panic("sched_unsleep");
   1131 }
   1132 
   1133 /*
   1134  * sched_changepri:
   1135  *
   1136  *	Adjust the priority of an LWP.
   1137  */
   1138 void
   1139 sched_changepri(struct lwp *l, pri_t pri)
   1140 {
   1141 
   1142 	LOCK_ASSERT(lwp_locked(l, &sched_mutex));
   1143 
   1144 	l->l_usrpri = pri;
   1145 	if (l->l_priority < PUSER)
   1146 		return;
   1147 
   1148 	if (l->l_stat != LSRUN || (l->l_flag & LW_INMEM) == 0) {
   1149 		l->l_priority = pri;
   1150 		return;
   1151 	}
   1152 
   1153 	remrunqueue(l);
   1154 	l->l_priority = pri;
   1155 	setrunqueue(l);
   1156 	resched_lwp(l);
   1157 }
   1158 
   1159 void
   1160 sched_lendpri(struct lwp *l, pri_t pri)
   1161 {
   1162 
   1163 	LOCK_ASSERT(lwp_locked(l, &sched_mutex));
   1164 
   1165 	if (l->l_stat != LSRUN || (l->l_flag & LW_INMEM) == 0) {
   1166 		l->l_inheritedprio = pri;
   1167 		return;
   1168 	}
   1169 
   1170 	remrunqueue(l);
   1171 	l->l_inheritedprio = pri;
   1172 	setrunqueue(l);
   1173 	resched_lwp(l);
   1174 }
   1175 
   1176 struct lwp *
   1177 syncobj_noowner(wchan_t wchan)
   1178 {
   1179 
   1180 	return NULL;
   1181 }
   1182 
   1183 /*
   1184  * Low-level routines to access the run queue.  Optimised assembler
   1185  * routines can override these.
   1186  */
   1187 
   1188 #ifndef __HAVE_MD_RUNQUEUE
   1189 
   1190 /*
   1191  * On some architectures, it's faster to use a MSB ordering for the priorites
   1192  * than the traditional LSB ordering.
   1193  */
   1194 #ifdef __HAVE_BIGENDIAN_BITOPS
   1195 #define	RQMASK(n) (0x80000000 >> (n))
   1196 #else
   1197 #define	RQMASK(n) (0x00000001 << (n))
   1198 #endif
   1199 
   1200 /*
   1201  * The primitives that manipulate the run queues.  whichqs tells which
   1202  * of the 32 queues qs have processes in them.  Setrunqueue puts processes
   1203  * into queues, remrunqueue removes them from queues.  The running process is
   1204  * on no queue, other processes are on a queue related to p->p_priority,
   1205  * divided by 4 actually to shrink the 0-127 range of priorities into the 32
   1206  * available queues.
   1207  */
   1208 #ifdef RQDEBUG
   1209 static void
   1210 checkrunqueue(int whichq, struct lwp *l)
   1211 {
   1212 	const struct prochd * const rq = &sched_qs[whichq];
   1213 	struct lwp *l2;
   1214 	int found = 0;
   1215 	int die = 0;
   1216 	int empty = 1;
   1217 	for (l2 = rq->ph_link; l2 != (const void*) rq; l2 = l2->l_forw) {
   1218 		if (l2->l_stat != LSRUN) {
   1219 			printf("checkrunqueue[%d]: lwp %p state (%d) "
   1220 			    " != LSRUN\n", whichq, l2, l2->l_stat);
   1221 		}
   1222 		if (l2->l_back->l_forw != l2) {
   1223 			printf("checkrunqueue[%d]: lwp %p back-qptr (%p) "
   1224 			    "corrupt %p\n", whichq, l2, l2->l_back,
   1225 			    l2->l_back->l_forw);
   1226 			die = 1;
   1227 		}
   1228 		if (l2->l_forw->l_back != l2) {
   1229 			printf("checkrunqueue[%d]: lwp %p forw-qptr (%p) "
   1230 			    "corrupt %p\n", whichq, l2, l2->l_forw,
   1231 			    l2->l_forw->l_back);
   1232 			die = 1;
   1233 		}
   1234 		if (l2 == l)
   1235 			found = 1;
   1236 		empty = 0;
   1237 	}
   1238 	if (empty && (sched_whichqs & RQMASK(whichq)) != 0) {
   1239 		printf("checkrunqueue[%d]: bit set for empty run-queue %p\n",
   1240 		    whichq, rq);
   1241 		die = 1;
   1242 	} else if (!empty && (sched_whichqs & RQMASK(whichq)) == 0) {
   1243 		printf("checkrunqueue[%d]: bit clear for non-empty "
   1244 		    "run-queue %p\n", whichq, rq);
   1245 		die = 1;
   1246 	}
   1247 	if (l != NULL && (sched_whichqs & RQMASK(whichq)) == 0) {
   1248 		printf("checkrunqueue[%d]: bit clear for active lwp %p\n",
   1249 		    whichq, l);
   1250 		die = 1;
   1251 	}
   1252 	if (l != NULL && empty) {
   1253 		printf("checkrunqueue[%d]: empty run-queue %p with "
   1254 		    "active lwp %p\n", whichq, rq, l);
   1255 		die = 1;
   1256 	}
   1257 	if (l != NULL && !found) {
   1258 		printf("checkrunqueue[%d]: lwp %p not in runqueue %p!",
   1259 		    whichq, l, rq);
   1260 		die = 1;
   1261 	}
   1262 	if (die)
   1263 		panic("checkrunqueue: inconsistency found");
   1264 }
   1265 #endif /* RQDEBUG */
   1266 
   1267 void
   1268 setrunqueue(struct lwp *l)
   1269 {
   1270 	struct prochd *rq;
   1271 	struct lwp *prev;
   1272 	const int whichq = lwp_eprio(l) / PPQ;
   1273 
   1274 	LOCK_ASSERT(lwp_locked(l, &sched_mutex));
   1275 
   1276 #ifdef RQDEBUG
   1277 	checkrunqueue(whichq, NULL);
   1278 #endif
   1279 #ifdef DIAGNOSTIC
   1280 	if (l->l_back != NULL || l->l_stat != LSRUN)
   1281 		panic("setrunqueue");
   1282 #endif
   1283 	sched_whichqs |= RQMASK(whichq);
   1284 	rq = &sched_qs[whichq];
   1285 	prev = rq->ph_rlink;
   1286 	l->l_forw = (struct lwp *)rq;
   1287 	rq->ph_rlink = l;
   1288 	prev->l_forw = l;
   1289 	l->l_back = prev;
   1290 #ifdef RQDEBUG
   1291 	checkrunqueue(whichq, l);
   1292 #endif
   1293 }
   1294 
   1295 /*
   1296  * XXXSMP When LWP dispatch (cpu_switch()) is changed to use remrunqueue(),
   1297  * drop of the effective priority level from kernel to user needs to be
   1298  * moved here from userret().  The assignment in userret() is currently
   1299  * done unlocked.
   1300  */
   1301 void
   1302 remrunqueue(struct lwp *l)
   1303 {
   1304 	struct lwp *prev, *next;
   1305 	const int whichq = lwp_eprio(l) / PPQ;
   1306 
   1307 	LOCK_ASSERT(lwp_locked(l, &sched_mutex));
   1308 
   1309 #ifdef RQDEBUG
   1310 	checkrunqueue(whichq, l);
   1311 #endif
   1312 
   1313 #if defined(DIAGNOSTIC)
   1314 	if (((sched_whichqs & RQMASK(whichq)) == 0) || l->l_back == NULL) {
   1315 		/* Shouldn't happen - interrupts disabled. */
   1316 		panic("remrunqueue: bit %d not set", whichq);
   1317 	}
   1318 #endif
   1319 	prev = l->l_back;
   1320 	l->l_back = NULL;
   1321 	next = l->l_forw;
   1322 	prev->l_forw = next;
   1323 	next->l_back = prev;
   1324 	if (prev == next)
   1325 		sched_whichqs &= ~RQMASK(whichq);
   1326 #ifdef RQDEBUG
   1327 	checkrunqueue(whichq, NULL);
   1328 #endif
   1329 }
   1330 
   1331 #undef RQMASK
   1332 #endif /* !defined(__HAVE_MD_RUNQUEUE) */
   1333