Home | History | Annotate | Line # | Download | only in kern
kern_synch.c revision 1.166
      1 /*	$NetBSD: kern_synch.c,v 1.166 2006/09/02 06:32:09 christos Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999, 2000, 2004 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  * This code is derived from software contributed to The NetBSD Foundation
     11  * by Charles M. Hannum.
     12  *
     13  * Redistribution and use in source and binary forms, with or without
     14  * modification, are permitted provided that the following conditions
     15  * are met:
     16  * 1. Redistributions of source code must retain the above copyright
     17  *    notice, this list of conditions and the following disclaimer.
     18  * 2. Redistributions in binary form must reproduce the above copyright
     19  *    notice, this list of conditions and the following disclaimer in the
     20  *    documentation and/or other materials provided with the distribution.
     21  * 3. All advertising materials mentioning features or use of this software
     22  *    must display the following acknowledgement:
     23  *	This product includes software developed by the NetBSD
     24  *	Foundation, Inc. and its contributors.
     25  * 4. Neither the name of The NetBSD Foundation nor the names of its
     26  *    contributors may be used to endorse or promote products derived
     27  *    from this software without specific prior written permission.
     28  *
     29  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     30  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     31  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     32  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     33  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     34  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     35  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     36  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     37  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     39  * POSSIBILITY OF SUCH DAMAGE.
     40  */
     41 
     42 /*-
     43  * Copyright (c) 1982, 1986, 1990, 1991, 1993
     44  *	The Regents of the University of California.  All rights reserved.
     45  * (c) UNIX System Laboratories, Inc.
     46  * All or some portions of this file are derived from material licensed
     47  * to the University of California by American Telephone and Telegraph
     48  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     49  * the permission of UNIX System Laboratories, Inc.
     50  *
     51  * Redistribution and use in source and binary forms, with or without
     52  * modification, are permitted provided that the following conditions
     53  * are met:
     54  * 1. Redistributions of source code must retain the above copyright
     55  *    notice, this list of conditions and the following disclaimer.
     56  * 2. Redistributions in binary form must reproduce the above copyright
     57  *    notice, this list of conditions and the following disclaimer in the
     58  *    documentation and/or other materials provided with the distribution.
     59  * 3. Neither the name of the University nor the names of its contributors
     60  *    may be used to endorse or promote products derived from this software
     61  *    without specific prior written permission.
     62  *
     63  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     64  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     65  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     66  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     67  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     68  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     69  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     70  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     71  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     72  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     73  * SUCH DAMAGE.
     74  *
     75  *	@(#)kern_synch.c	8.9 (Berkeley) 5/19/95
     76  */
     77 
     78 #include <sys/cdefs.h>
     79 __KERNEL_RCSID(0, "$NetBSD: kern_synch.c,v 1.166 2006/09/02 06:32:09 christos Exp $");
     80 
     81 #include "opt_ddb.h"
     82 #include "opt_ktrace.h"
     83 #include "opt_kstack.h"
     84 #include "opt_lockdebug.h"
     85 #include "opt_multiprocessor.h"
     86 #include "opt_perfctrs.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 #if defined(PERFCTRS)
     95 #include <sys/pmc.h>
     96 #endif
     97 #include <sys/signalvar.h>
     98 #include <sys/resourcevar.h>
     99 #include <sys/sched.h>
    100 #include <sys/sa.h>
    101 #include <sys/savar.h>
    102 #include <sys/kauth.h>
    103 
    104 #include <uvm/uvm_extern.h>
    105 
    106 #ifdef KTRACE
    107 #include <sys/ktrace.h>
    108 #endif
    109 
    110 #include <machine/cpu.h>
    111 
    112 int	lbolt;			/* once a second sleep address */
    113 int	rrticks;		/* number of hardclock ticks per roundrobin() */
    114 
    115 /*
    116  * Sleep queues.
    117  *
    118  * We're only looking at 7 bits of the address; everything is
    119  * aligned to 4, lots of things are aligned to greater powers
    120  * of 2.  Shift right by 8, i.e. drop the bottom 256 worth.
    121  */
    122 #define	SLPQUE_TABLESIZE	128
    123 #define	SLPQUE_LOOKUP(x)	(((u_long)(x) >> 8) & (SLPQUE_TABLESIZE - 1))
    124 
    125 #define	SLPQUE(ident)	(&sched_slpque[SLPQUE_LOOKUP(ident)])
    126 
    127 /*
    128  * The global scheduler state.
    129  */
    130 struct prochd sched_qs[RUNQUE_NQS];	/* run queues */
    131 volatile uint32_t sched_whichqs;	/* bitmap of non-empty queues */
    132 struct slpque sched_slpque[SLPQUE_TABLESIZE]; /* sleep queues */
    133 
    134 struct simplelock sched_lock = SIMPLELOCK_INITIALIZER;
    135 
    136 void schedcpu(void *);
    137 void updatepri(struct lwp *);
    138 void endtsleep(void *);
    139 
    140 inline void sa_awaken(struct lwp *);
    141 inline void awaken(struct lwp *);
    142 
    143 struct callout schedcpu_ch = CALLOUT_INITIALIZER_SETFUNC(schedcpu, NULL);
    144 static unsigned int schedcpu_ticks;
    145 
    146 
    147 /*
    148  * Force switch among equal priority processes every 100ms.
    149  * Called from hardclock every hz/10 == rrticks hardclock ticks.
    150  */
    151 /* ARGSUSED */
    152 void
    153 roundrobin(struct cpu_info *ci)
    154 {
    155 	struct schedstate_percpu *spc = &ci->ci_schedstate;
    156 
    157 	spc->spc_rrticks = rrticks;
    158 
    159 	if (curlwp != NULL) {
    160 		if (spc->spc_flags & SPCF_SEENRR) {
    161 			/*
    162 			 * The process has already been through a roundrobin
    163 			 * without switching and may be hogging the CPU.
    164 			 * Indicate that the process should yield.
    165 			 */
    166 			spc->spc_flags |= SPCF_SHOULDYIELD;
    167 		} else
    168 			spc->spc_flags |= SPCF_SEENRR;
    169 	}
    170 	need_resched(curcpu());
    171 }
    172 
    173 #define	PPQ	(128 / RUNQUE_NQS)	/* priorities per queue */
    174 #define	NICE_WEIGHT 2			/* priorities per nice level */
    175 
    176 #define	ESTCPU_SHIFT	11
    177 #define	ESTCPU_MAX	((NICE_WEIGHT * PRIO_MAX - PPQ) << ESTCPU_SHIFT)
    178 #define	ESTCPULIM(e)	min((e), ESTCPU_MAX)
    179 
    180 /*
    181  * Constants for digital decay and forget:
    182  *	90% of (p_estcpu) usage in 5 * loadav time
    183  *	95% of (p_pctcpu) usage in 60 seconds (load insensitive)
    184  *          Note that, as ps(1) mentions, this can let percentages
    185  *          total over 100% (I've seen 137.9% for 3 processes).
    186  *
    187  * Note that hardclock updates p_estcpu and p_cpticks independently.
    188  *
    189  * We wish to decay away 90% of p_estcpu in (5 * loadavg) seconds.
    190  * That is, the system wants to compute a value of decay such
    191  * that the following for loop:
    192  * 	for (i = 0; i < (5 * loadavg); i++)
    193  * 		p_estcpu *= decay;
    194  * will compute
    195  * 	p_estcpu *= 0.1;
    196  * for all values of loadavg:
    197  *
    198  * Mathematically this loop can be expressed by saying:
    199  * 	decay ** (5 * loadavg) ~= .1
    200  *
    201  * The system computes decay as:
    202  * 	decay = (2 * loadavg) / (2 * loadavg + 1)
    203  *
    204  * We wish to prove that the system's computation of decay
    205  * will always fulfill the equation:
    206  * 	decay ** (5 * loadavg) ~= .1
    207  *
    208  * If we compute b as:
    209  * 	b = 2 * loadavg
    210  * then
    211  * 	decay = b / (b + 1)
    212  *
    213  * We now need to prove two things:
    214  *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
    215  *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
    216  *
    217  * Facts:
    218  *         For x close to zero, exp(x) =~ 1 + x, since
    219  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
    220  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
    221  *         For x close to zero, ln(1+x) =~ x, since
    222  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
    223  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
    224  *         ln(.1) =~ -2.30
    225  *
    226  * Proof of (1):
    227  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
    228  *	solving for factor,
    229  *      ln(factor) =~ (-2.30/5*loadav), or
    230  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
    231  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
    232  *
    233  * Proof of (2):
    234  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
    235  *	solving for power,
    236  *      power*ln(b/(b+1)) =~ -2.30, or
    237  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
    238  *
    239  * Actual power values for the implemented algorithm are as follows:
    240  *      loadav: 1       2       3       4
    241  *      power:  5.68    10.32   14.94   19.55
    242  */
    243 
    244 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
    245 #define	loadfactor(loadav)	(2 * (loadav))
    246 
    247 static fixpt_t
    248 decay_cpu(fixpt_t loadfac, fixpt_t estcpu)
    249 {
    250 
    251 	if (estcpu == 0) {
    252 		return 0;
    253 	}
    254 
    255 #if !defined(_LP64)
    256 	/* avoid 64bit arithmetics. */
    257 #define	FIXPT_MAX ((fixpt_t)((UINTMAX_C(1) << sizeof(fixpt_t) * CHAR_BIT) - 1))
    258 	if (__predict_true(loadfac <= FIXPT_MAX / ESTCPU_MAX)) {
    259 		return estcpu * loadfac / (loadfac + FSCALE);
    260 	}
    261 #endif /* !defined(_LP64) */
    262 
    263 	return (uint64_t)estcpu * loadfac / (loadfac + FSCALE);
    264 }
    265 
    266 /*
    267  * For all load averages >= 1 and max p_estcpu of (255 << ESTCPU_SHIFT),
    268  * sleeping for at least seven times the loadfactor will decay p_estcpu to
    269  * less than (1 << ESTCPU_SHIFT).
    270  *
    271  * note that our ESTCPU_MAX is actually much smaller than (255 << ESTCPU_SHIFT).
    272  */
    273 static fixpt_t
    274 decay_cpu_batch(fixpt_t loadfac, fixpt_t estcpu, unsigned int n)
    275 {
    276 
    277 	if ((n << FSHIFT) >= 7 * loadfac) {
    278 		return 0;
    279 	}
    280 
    281 	while (estcpu != 0 && n > 1) {
    282 		estcpu = decay_cpu(loadfac, estcpu);
    283 		n--;
    284 	}
    285 
    286 	return estcpu;
    287 }
    288 
    289 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
    290 fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;		/* exp(-1/20) */
    291 
    292 /*
    293  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
    294  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
    295  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
    296  *
    297  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
    298  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
    299  *
    300  * If you dont want to bother with the faster/more-accurate formula, you
    301  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
    302  * (more general) method of calculating the %age of CPU used by a process.
    303  */
    304 #define	CCPU_SHIFT	11
    305 
    306 /*
    307  * Recompute process priorities, every hz ticks.
    308  */
    309 /* ARGSUSED */
    310 void
    311 schedcpu(void *arg)
    312 {
    313 	fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
    314 	struct lwp *l;
    315 	struct proc *p;
    316 	int s, minslp;
    317 	int clkhz;
    318 
    319 	schedcpu_ticks++;
    320 
    321 	proclist_lock_read();
    322 	PROCLIST_FOREACH(p, &allproc) {
    323 		/*
    324 		 * Increment time in/out of memory and sleep time
    325 		 * (if sleeping).  We ignore overflow; with 16-bit int's
    326 		 * (remember them?) overflow takes 45 days.
    327 		 */
    328 		minslp = 2;
    329 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    330 			l->l_swtime++;
    331 			if (l->l_stat == LSSLEEP || l->l_stat == LSSTOP ||
    332 			    l->l_stat == LSSUSPENDED) {
    333 				l->l_slptime++;
    334 				minslp = min(minslp, l->l_slptime);
    335 			} else
    336 				minslp = 0;
    337 		}
    338 		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
    339 		/*
    340 		 * If the process has slept the entire second,
    341 		 * stop recalculating its priority until it wakes up.
    342 		 */
    343 		if (minslp > 1)
    344 			continue;
    345 		s = splstatclock();	/* prevent state changes */
    346 		/*
    347 		 * p_pctcpu is only for ps.
    348 		 */
    349 		clkhz = stathz != 0 ? stathz : hz;
    350 #if	(FSHIFT >= CCPU_SHIFT)
    351 		p->p_pctcpu += (clkhz == 100)?
    352 			((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT):
    353                 	100 * (((fixpt_t) p->p_cpticks)
    354 				<< (FSHIFT - CCPU_SHIFT)) / clkhz;
    355 #else
    356 		p->p_pctcpu += ((FSCALE - ccpu) *
    357 			(p->p_cpticks * FSCALE / clkhz)) >> FSHIFT;
    358 #endif
    359 		p->p_cpticks = 0;
    360 		p->p_estcpu = decay_cpu(loadfac, p->p_estcpu);
    361 		splx(s);	/* Done with the process CPU ticks update */
    362 		SCHED_LOCK(s);
    363 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    364 			if (l->l_slptime > 1)
    365 				continue;
    366 			resetpriority(l);
    367 			if (l->l_priority >= PUSER) {
    368 				if (l->l_stat == LSRUN &&
    369 				    (l->l_flag & L_INMEM) &&
    370 				    (l->l_priority / PPQ) != (l->l_usrpri / PPQ)) {
    371 					remrunqueue(l);
    372 					l->l_priority = l->l_usrpri;
    373 					setrunqueue(l);
    374 				} else
    375 					l->l_priority = l->l_usrpri;
    376 			}
    377 		}
    378 		SCHED_UNLOCK(s);
    379 	}
    380 	proclist_unlock_read();
    381 	uvm_meter();
    382 	wakeup((caddr_t)&lbolt);
    383 	callout_schedule(&schedcpu_ch, hz);
    384 }
    385 
    386 /*
    387  * Recalculate the priority of a process after it has slept for a while.
    388  */
    389 void
    390 updatepri(struct lwp *l)
    391 {
    392 	struct proc *p = l->l_proc;
    393 	fixpt_t loadfac;
    394 
    395 	SCHED_ASSERT_LOCKED();
    396 	KASSERT(l->l_slptime > 1);
    397 
    398 	loadfac = loadfactor(averunnable.ldavg[0]);
    399 
    400 	l->l_slptime--; /* the first time was done in schedcpu */
    401 	/* XXX NJWLWP */
    402 	p->p_estcpu = decay_cpu_batch(loadfac, p->p_estcpu, l->l_slptime);
    403 	resetpriority(l);
    404 }
    405 
    406 /*
    407  * During autoconfiguration or after a panic, a sleep will simply
    408  * lower the priority briefly to allow interrupts, then return.
    409  * The priority to be used (safepri) is machine-dependent, thus this
    410  * value is initialized and maintained in the machine-dependent layers.
    411  * This priority will typically be 0, or the lowest priority
    412  * that is safe for use on the interrupt stack; it can be made
    413  * higher to block network software interrupts after panics.
    414  */
    415 int safepri;
    416 
    417 /*
    418  * General sleep call.  Suspends the current process until a wakeup is
    419  * performed on the specified identifier.  The process will then be made
    420  * runnable with the specified priority.  Sleeps at most timo/hz seconds
    421  * (0 means no timeout).  If pri includes PCATCH flag, signals are checked
    422  * before and after sleeping, else signals are not checked.  Returns 0 if
    423  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
    424  * signal needs to be delivered, ERESTART is returned if the current system
    425  * call should be restarted if possible, and EINTR is returned if the system
    426  * call should be interrupted by the signal (return EINTR).
    427  *
    428  * The interlock is held until the scheduler_slock is acquired.  The
    429  * interlock will be locked before returning back to the caller
    430  * unless the PNORELOCK flag is specified, in which case the
    431  * interlock will always be unlocked upon return.
    432  */
    433 int
    434 ltsleep(volatile const void *ident, int priority, const char *wmesg, int timo,
    435     volatile struct simplelock *interlock)
    436 {
    437 	struct lwp *l = curlwp;
    438 	struct proc *p = l ? l->l_proc : NULL;
    439 	struct slpque *qp;
    440 	struct sadata_upcall *sau;
    441 	int sig, s;
    442 	int catch = priority & PCATCH;
    443 	int relock = (priority & PNORELOCK) == 0;
    444 	int exiterr = (priority & PNOEXITERR) == 0;
    445 
    446 	/*
    447 	 * XXXSMP
    448 	 * This is probably bogus.  Figure out what the right
    449 	 * thing to do here really is.
    450 	 * Note that not sleeping if ltsleep is called with curlwp == NULL
    451 	 * in the shutdown case is disgusting but partly necessary given
    452 	 * how shutdown (barely) works.
    453 	 */
    454 	if (cold || (doing_shutdown && (panicstr || (l == NULL)))) {
    455 		/*
    456 		 * After a panic, or during autoconfiguration,
    457 		 * just give interrupts a chance, then just return;
    458 		 * don't run any other procs or panic below,
    459 		 * in case this is the idle process and already asleep.
    460 		 */
    461 		s = splhigh();
    462 		splx(safepri);
    463 		splx(s);
    464 		if (interlock != NULL && relock == 0)
    465 			simple_unlock(interlock);
    466 		return (0);
    467 	}
    468 
    469 	KASSERT(p != NULL);
    470 	LOCK_ASSERT(interlock == NULL || simple_lock_held(interlock));
    471 
    472 #ifdef KTRACE
    473 	if (KTRPOINT(p, KTR_CSW))
    474 		ktrcsw(l, 1, 0);
    475 #endif
    476 
    477 	/*
    478 	 * XXX We need to allocate the sadata_upcall structure here,
    479 	 * XXX since we can't sleep while waiting for memory inside
    480 	 * XXX sa_upcall().  It would be nice if we could safely
    481 	 * XXX allocate the sadata_upcall structure on the stack, here.
    482 	 */
    483 	if (l->l_flag & L_SA) {
    484 		sau = sadata_upcall_alloc(0);
    485 	} else {
    486 		sau = NULL;
    487 	}
    488 
    489 	SCHED_LOCK(s);
    490 
    491 #ifdef DIAGNOSTIC
    492 	if (ident == NULL)
    493 		panic("ltsleep: ident == NULL");
    494 	if (l->l_stat != LSONPROC)
    495 		panic("ltsleep: l_stat %d != LSONPROC", l->l_stat);
    496 	if (l->l_back != NULL)
    497 		panic("ltsleep: p_back != NULL");
    498 #endif
    499 
    500 	l->l_wchan = ident;
    501 	l->l_wmesg = wmesg;
    502 	l->l_slptime = 0;
    503 	l->l_priority = priority & PRIMASK;
    504 
    505 	qp = SLPQUE(ident);
    506 	if (qp->sq_head == 0)
    507 		qp->sq_head = l;
    508 	else {
    509 		*qp->sq_tailp = l;
    510 	}
    511 	*(qp->sq_tailp = &l->l_forw) = 0;
    512 
    513 	if (timo)
    514 		callout_reset(&l->l_tsleep_ch, timo, endtsleep, l);
    515 
    516 	/*
    517 	 * We can now release the interlock; the scheduler_slock
    518 	 * is held, so a thread can't get in to do wakeup() before
    519 	 * we do the switch.
    520 	 *
    521 	 * XXX We leave the code block here, after inserting ourselves
    522 	 * on the sleep queue, because we might want a more clever
    523 	 * data structure for the sleep queues at some point.
    524 	 */
    525 	if (interlock != NULL)
    526 		simple_unlock(interlock);
    527 
    528 	/*
    529 	 * We put ourselves on the sleep queue and start our timeout
    530 	 * before calling CURSIG, as we could stop there, and a wakeup
    531 	 * or a SIGCONT (or both) could occur while we were stopped.
    532 	 * A SIGCONT would cause us to be marked as SSLEEP
    533 	 * without resuming us, thus we must be ready for sleep
    534 	 * when CURSIG is called.  If the wakeup happens while we're
    535 	 * stopped, p->p_wchan will be 0 upon return from CURSIG.
    536 	 */
    537 	if (catch) {
    538 		l->l_flag |= L_SINTR;
    539 		if (((sig = CURSIG(l)) != 0) ||
    540 		    ((p->p_flag & P_WEXIT) && p->p_nlwps > 1)) {
    541 			if (l->l_wchan != NULL)
    542 				unsleep(l);
    543 			l->l_stat = LSONPROC;
    544 			SCHED_UNLOCK(s);
    545 			goto resume;
    546 		}
    547 		if (l->l_wchan == NULL) {
    548 			catch = 0;
    549 			SCHED_UNLOCK(s);
    550 			goto resume;
    551 		}
    552 	} else
    553 		sig = 0;
    554 	l->l_stat = LSSLEEP;
    555 	p->p_nrlwps--;
    556 	p->p_stats->p_ru.ru_nvcsw++;
    557 	SCHED_ASSERT_LOCKED();
    558 	if (l->l_flag & L_SA)
    559 		sa_switch(l, sau, SA_UPCALL_BLOCKED);
    560 	else
    561 		mi_switch(l, NULL);
    562 
    563 #if	defined(DDB) && !defined(GPROF) && \
    564 	!defined(__m68k__) && !defined(__vax__)
    565 	/*
    566 	 * XXX
    567 	 * gcc4 optimizer will duplicate this asm statement on some arch
    568 	 * and it will cause a multiple symbol definition error in gas.
    569 	 */
    570 	/* handy breakpoint location after process "wakes" */
    571 	__asm(".globl bpendtsleep\nbpendtsleep:");
    572 #endif
    573 	/*
    574 	 * p->p_nrlwps is incremented by whoever made us runnable again,
    575 	 * either setrunnable() or awaken().
    576 	 */
    577 
    578 	SCHED_ASSERT_UNLOCKED();
    579 	splx(s);
    580 
    581  resume:
    582 	KDASSERT(l->l_cpu != NULL);
    583 	KDASSERT(l->l_cpu == curcpu());
    584 	l->l_cpu->ci_schedstate.spc_curpriority = l->l_usrpri;
    585 
    586 	l->l_flag &= ~L_SINTR;
    587 	if (l->l_flag & L_TIMEOUT) {
    588 		l->l_flag &= ~(L_TIMEOUT|L_CANCELLED);
    589 		if (sig == 0) {
    590 #ifdef KTRACE
    591 			if (KTRPOINT(p, KTR_CSW))
    592 				ktrcsw(l, 0, 0);
    593 #endif
    594 			if (relock && interlock != NULL)
    595 				simple_lock(interlock);
    596 			return (EWOULDBLOCK);
    597 		}
    598 	} else if (timo)
    599 		callout_stop(&l->l_tsleep_ch);
    600 
    601 	if (catch) {
    602 		const int cancelled = l->l_flag & L_CANCELLED;
    603 		l->l_flag &= ~L_CANCELLED;
    604 		if (sig != 0 || (sig = CURSIG(l)) != 0 || cancelled) {
    605 #ifdef KTRACE
    606 			if (KTRPOINT(p, KTR_CSW))
    607 				ktrcsw(l, 0, 0);
    608 #endif
    609 			if (relock && interlock != NULL)
    610 				simple_lock(interlock);
    611 			/*
    612 			 * If this sleep was canceled, don't let the syscall
    613 			 * restart.
    614 			 */
    615 			if (cancelled ||
    616 			    (SIGACTION(p, sig).sa_flags & SA_RESTART) == 0)
    617 				return (EINTR);
    618 			return (ERESTART);
    619 		}
    620 	}
    621 
    622 #ifdef KTRACE
    623 	if (KTRPOINT(p, KTR_CSW))
    624 		ktrcsw(l, 0, 0);
    625 #endif
    626 	if (relock && interlock != NULL)
    627 		simple_lock(interlock);
    628 
    629 	/* XXXNJW this is very much a kluge.
    630 	 * revisit. a better way of preventing looping/hanging syscalls like
    631 	 * wait4() and _lwp_wait() from wedging an exiting process
    632 	 * would be preferred.
    633 	 */
    634 	if (catch && ((p->p_flag & P_WEXIT) && p->p_nlwps > 1 && exiterr))
    635 		return (EINTR);
    636 	return (0);
    637 }
    638 
    639 /*
    640  * Implement timeout for tsleep.
    641  * If process hasn't been awakened (wchan non-zero),
    642  * set timeout flag and undo the sleep.  If proc
    643  * is stopped, just unsleep so it will remain stopped.
    644  */
    645 void
    646 endtsleep(void *arg)
    647 {
    648 	struct lwp *l;
    649 	int s;
    650 
    651 	l = (struct lwp *)arg;
    652 	SCHED_LOCK(s);
    653 	if (l->l_wchan) {
    654 		if (l->l_stat == LSSLEEP)
    655 			setrunnable(l);
    656 		else
    657 			unsleep(l);
    658 		l->l_flag |= L_TIMEOUT;
    659 	}
    660 	SCHED_UNLOCK(s);
    661 }
    662 
    663 /*
    664  * Remove a process from its wait queue
    665  */
    666 void
    667 unsleep(struct lwp *l)
    668 {
    669 	struct slpque *qp;
    670 	struct lwp **hp;
    671 
    672 	SCHED_ASSERT_LOCKED();
    673 
    674 	if (l->l_wchan) {
    675 		hp = &(qp = SLPQUE(l->l_wchan))->sq_head;
    676 		while (*hp != l)
    677 			hp = &(*hp)->l_forw;
    678 		*hp = l->l_forw;
    679 		if (qp->sq_tailp == &l->l_forw)
    680 			qp->sq_tailp = hp;
    681 		l->l_wchan = 0;
    682 	}
    683 }
    684 
    685 inline void
    686 sa_awaken(struct lwp *l)
    687 {
    688 
    689 	SCHED_ASSERT_LOCKED();
    690 
    691 	if (l == l->l_savp->savp_lwp && l->l_flag & L_SA_YIELD)
    692 		l->l_flag &= ~L_SA_IDLE;
    693 }
    694 
    695 /*
    696  * Optimized-for-wakeup() version of setrunnable().
    697  */
    698 inline void
    699 awaken(struct lwp *l)
    700 {
    701 
    702 	SCHED_ASSERT_LOCKED();
    703 
    704 	if (l->l_proc->p_sa)
    705 		sa_awaken(l);
    706 
    707 	if (l->l_slptime > 1)
    708 		updatepri(l);
    709 	l->l_slptime = 0;
    710 	l->l_stat = LSRUN;
    711 	l->l_proc->p_nrlwps++;
    712 	/*
    713 	 * Since curpriority is a user priority, p->p_priority
    714 	 * is always better than curpriority on the last CPU on
    715 	 * which it ran.
    716 	 *
    717 	 * XXXSMP See affinity comment in resched_proc().
    718 	 */
    719 	if (l->l_flag & L_INMEM) {
    720 		setrunqueue(l);
    721 		KASSERT(l->l_cpu != NULL);
    722 		need_resched(l->l_cpu);
    723 	} else
    724 		sched_wakeup(&proc0);
    725 }
    726 
    727 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
    728 void
    729 sched_unlock_idle(void)
    730 {
    731 
    732 	simple_unlock(&sched_lock);
    733 }
    734 
    735 void
    736 sched_lock_idle(void)
    737 {
    738 
    739 	simple_lock(&sched_lock);
    740 }
    741 #endif /* MULTIPROCESSOR || LOCKDEBUG */
    742 
    743 /*
    744  * Make all processes sleeping on the specified identifier runnable.
    745  */
    746 
    747 void
    748 wakeup(volatile const void *ident)
    749 {
    750 	int s;
    751 
    752 	SCHED_ASSERT_UNLOCKED();
    753 
    754 	SCHED_LOCK(s);
    755 	sched_wakeup(ident);
    756 	SCHED_UNLOCK(s);
    757 }
    758 
    759 void
    760 sched_wakeup(volatile const void *ident)
    761 {
    762 	struct slpque *qp;
    763 	struct lwp *l, **q;
    764 
    765 	SCHED_ASSERT_LOCKED();
    766 
    767 	qp = SLPQUE(ident);
    768  restart:
    769 	for (q = &qp->sq_head; (l = *q) != NULL; ) {
    770 #ifdef DIAGNOSTIC
    771 		if (l->l_back || (l->l_stat != LSSLEEP &&
    772 		    l->l_stat != LSSTOP && l->l_stat != LSSUSPENDED))
    773 			panic("wakeup");
    774 #endif
    775 		if (l->l_wchan == ident) {
    776 			l->l_wchan = 0;
    777 			*q = l->l_forw;
    778 			if (qp->sq_tailp == &l->l_forw)
    779 				qp->sq_tailp = q;
    780 			if (l->l_stat == LSSLEEP) {
    781 				awaken(l);
    782 				goto restart;
    783 			}
    784 		} else
    785 			q = &l->l_forw;
    786 	}
    787 }
    788 
    789 /*
    790  * Make the highest priority process first in line on the specified
    791  * identifier runnable.
    792  */
    793 void
    794 wakeup_one(volatile const void *ident)
    795 {
    796 	struct slpque *qp;
    797 	struct lwp *l, **q;
    798 	struct lwp *best_sleepp, **best_sleepq;
    799 	struct lwp *best_stopp, **best_stopq;
    800 	int s;
    801 
    802 	best_sleepp = best_stopp = NULL;
    803 	best_sleepq = best_stopq = NULL;
    804 
    805 	SCHED_LOCK(s);
    806 
    807 	qp = SLPQUE(ident);
    808 
    809 	for (q = &qp->sq_head; (l = *q) != NULL; q = &l->l_forw) {
    810 #ifdef DIAGNOSTIC
    811 		if (l->l_back || (l->l_stat != LSSLEEP &&
    812 		    l->l_stat != LSSTOP && l->l_stat != LSSUSPENDED))
    813 			panic("wakeup_one");
    814 #endif
    815 		if (l->l_wchan == ident) {
    816 			if (l->l_stat == LSSLEEP) {
    817 				if (best_sleepp == NULL ||
    818 				    l->l_priority < best_sleepp->l_priority) {
    819 					best_sleepp = l;
    820 					best_sleepq = q;
    821 				}
    822 			} else {
    823 				if (best_stopp == NULL ||
    824 				    l->l_priority < best_stopp->l_priority) {
    825 				    	best_stopp = l;
    826 					best_stopq = q;
    827 				}
    828 			}
    829 		}
    830 	}
    831 
    832 	/*
    833 	 * Consider any SSLEEP process higher than the highest priority SSTOP
    834 	 * process.
    835 	 */
    836 	if (best_sleepp != NULL) {
    837 		l = best_sleepp;
    838 		q = best_sleepq;
    839 	} else {
    840 		l = best_stopp;
    841 		q = best_stopq;
    842 	}
    843 
    844 	if (l != NULL) {
    845 		l->l_wchan = NULL;
    846 		*q = l->l_forw;
    847 		if (qp->sq_tailp == &l->l_forw)
    848 			qp->sq_tailp = q;
    849 		if (l->l_stat == LSSLEEP)
    850 			awaken(l);
    851 	}
    852 	SCHED_UNLOCK(s);
    853 }
    854 
    855 /*
    856  * General yield call.  Puts the current process back on its run queue and
    857  * performs a voluntary context switch.  Should only be called when the
    858  * current process explicitly requests it (eg sched_yield(2) in compat code).
    859  */
    860 void
    861 yield(void)
    862 {
    863 	struct lwp *l = curlwp;
    864 	int s;
    865 
    866 	SCHED_LOCK(s);
    867 	l->l_priority = l->l_usrpri;
    868 	l->l_stat = LSRUN;
    869 	setrunqueue(l);
    870 	l->l_proc->p_stats->p_ru.ru_nvcsw++;
    871 	mi_switch(l, NULL);
    872 	SCHED_ASSERT_UNLOCKED();
    873 	splx(s);
    874 }
    875 
    876 /*
    877  * General preemption call.  Puts the current process back on its run queue
    878  * and performs an involuntary context switch.
    879  * The 'more' ("more work to do") argument is boolean. Returning to userspace
    880  * preempt() calls pass 0. "Voluntary" preemptions in e.g. uiomove() pass 1.
    881  * This will be used to indicate to the SA subsystem that the LWP is
    882  * not yet finished in the kernel.
    883  */
    884 
    885 void
    886 preempt(int more)
    887 {
    888 	struct lwp *l = curlwp;
    889 	int r, s;
    890 
    891 	SCHED_LOCK(s);
    892 	l->l_priority = l->l_usrpri;
    893 	l->l_stat = LSRUN;
    894 	setrunqueue(l);
    895 	l->l_proc->p_stats->p_ru.ru_nivcsw++;
    896 	r = mi_switch(l, NULL);
    897 	SCHED_ASSERT_UNLOCKED();
    898 	splx(s);
    899 	if ((l->l_flag & L_SA) != 0 && r != 0 && more == 0)
    900 		sa_preempt(l);
    901 }
    902 
    903 /*
    904  * The machine independent parts of context switch.
    905  * Must be called at splsched() (no higher!) and with
    906  * the sched_lock held.
    907  * Switch to "new" if non-NULL, otherwise let cpu_switch choose
    908  * the next lwp.
    909  *
    910  * Returns 1 if another process was actually run.
    911  */
    912 int
    913 mi_switch(struct lwp *l, struct lwp *newl)
    914 {
    915 	struct schedstate_percpu *spc;
    916 	struct rlimit *rlim;
    917 	long s, u;
    918 	struct timeval tv;
    919 	int hold_count;
    920 	struct proc *p = l->l_proc;
    921 	int retval;
    922 
    923 	SCHED_ASSERT_LOCKED();
    924 
    925 	/*
    926 	 * Release the kernel_lock, as we are about to yield the CPU.
    927 	 * The scheduler lock is still held until cpu_switch()
    928 	 * selects a new process and removes it from the run queue.
    929 	 */
    930 	hold_count = KERNEL_LOCK_RELEASE_ALL();
    931 
    932 	KDASSERT(l->l_cpu != NULL);
    933 	KDASSERT(l->l_cpu == curcpu());
    934 
    935 	spc = &l->l_cpu->ci_schedstate;
    936 
    937 #ifdef LOCKDEBUG
    938 	spinlock_switchcheck();
    939 	simple_lock_switchcheck();
    940 #endif
    941 
    942 	/*
    943 	 * Compute the amount of time during which the current
    944 	 * process was running.
    945 	 */
    946 	microtime(&tv);
    947 	u = p->p_rtime.tv_usec +
    948 	    (tv.tv_usec - spc->spc_runtime.tv_usec);
    949 	s = p->p_rtime.tv_sec + (tv.tv_sec - spc->spc_runtime.tv_sec);
    950 	if (u < 0) {
    951 		u += 1000000;
    952 		s--;
    953 	} else if (u >= 1000000) {
    954 		u -= 1000000;
    955 		s++;
    956 	}
    957 	p->p_rtime.tv_usec = u;
    958 	p->p_rtime.tv_sec = s;
    959 
    960 	/*
    961 	 * Check if the process exceeds its CPU resource allocation.
    962 	 * If over max, kill it.  In any case, if it has run for more
    963 	 * than 10 minutes, reduce priority to give others a chance.
    964 	 */
    965 	rlim = &p->p_rlimit[RLIMIT_CPU];
    966 	if (s >= rlim->rlim_cur) {
    967 		/*
    968 		 * XXXSMP: we're inside the scheduler lock perimeter;
    969 		 * use sched_psignal.
    970 		 */
    971 		if (s >= rlim->rlim_max)
    972 			sched_psignal(p, SIGKILL);
    973 		else {
    974 			sched_psignal(p, SIGXCPU);
    975 			if (rlim->rlim_cur < rlim->rlim_max)
    976 				rlim->rlim_cur += 5;
    977 		}
    978 	}
    979 	if (autonicetime && s > autonicetime &&
    980 	    kauth_cred_geteuid(p->p_cred) && p->p_nice == NZERO) {
    981 		p->p_nice = autoniceval + NZERO;
    982 		resetpriority(l);
    983 	}
    984 
    985 	/*
    986 	 * Process is about to yield the CPU; clear the appropriate
    987 	 * scheduling flags.
    988 	 */
    989 	spc->spc_flags &= ~SPCF_SWITCHCLEAR;
    990 
    991 #ifdef KSTACK_CHECK_MAGIC
    992 	kstack_check_magic(l);
    993 #endif
    994 
    995 	/*
    996 	 * If we are using h/w performance counters, save context.
    997 	 */
    998 #if PERFCTRS
    999 	if (PMC_ENABLED(p)) {
   1000 		pmc_save_context(p);
   1001 	}
   1002 #endif
   1003 
   1004 	/*
   1005 	 * Switch to the new current process.  When we
   1006 	 * run again, we'll return back here.
   1007 	 */
   1008 	uvmexp.swtch++;
   1009 	if (newl == NULL) {
   1010 		retval = cpu_switch(l, NULL);
   1011 	} else {
   1012 		remrunqueue(newl);
   1013 		cpu_switchto(l, newl);
   1014 		retval = 0;
   1015 	}
   1016 
   1017 	/*
   1018 	 * If we are using h/w performance counters, restore context.
   1019 	 */
   1020 #if PERFCTRS
   1021 	if (PMC_ENABLED(p)) {
   1022 		pmc_restore_context(p);
   1023 	}
   1024 #endif
   1025 
   1026 	/*
   1027 	 * Make sure that MD code released the scheduler lock before
   1028 	 * resuming us.
   1029 	 */
   1030 	SCHED_ASSERT_UNLOCKED();
   1031 
   1032 	/*
   1033 	 * We're running again; record our new start time.  We might
   1034 	 * be running on a new CPU now, so don't use the cache'd
   1035 	 * schedstate_percpu pointer.
   1036 	 */
   1037 	KDASSERT(l->l_cpu != NULL);
   1038 	KDASSERT(l->l_cpu == curcpu());
   1039 	microtime(&l->l_cpu->ci_schedstate.spc_runtime);
   1040 
   1041 	/*
   1042 	 * Reacquire the kernel_lock now.  We do this after we've
   1043 	 * released the scheduler lock to avoid deadlock, and before
   1044 	 * we reacquire the interlock.
   1045 	 */
   1046 	KERNEL_LOCK_ACQUIRE_COUNT(hold_count);
   1047 
   1048 	return retval;
   1049 }
   1050 
   1051 /*
   1052  * Initialize the (doubly-linked) run queues
   1053  * to be empty.
   1054  */
   1055 void
   1056 rqinit()
   1057 {
   1058 	int i;
   1059 
   1060 	for (i = 0; i < RUNQUE_NQS; i++)
   1061 		sched_qs[i].ph_link = sched_qs[i].ph_rlink =
   1062 		    (struct lwp *)&sched_qs[i];
   1063 }
   1064 
   1065 static inline void
   1066 resched_proc(struct lwp *l, u_char pri)
   1067 {
   1068 	struct cpu_info *ci;
   1069 
   1070 	/*
   1071 	 * XXXSMP
   1072 	 * Since l->l_cpu persists across a context switch,
   1073 	 * this gives us *very weak* processor affinity, in
   1074 	 * that we notify the CPU on which the process last
   1075 	 * ran that it should try to switch.
   1076 	 *
   1077 	 * This does not guarantee that the process will run on
   1078 	 * that processor next, because another processor might
   1079 	 * grab it the next time it performs a context switch.
   1080 	 *
   1081 	 * This also does not handle the case where its last
   1082 	 * CPU is running a higher-priority process, but every
   1083 	 * other CPU is running a lower-priority process.  There
   1084 	 * are ways to handle this situation, but they're not
   1085 	 * currently very pretty, and we also need to weigh the
   1086 	 * cost of moving a process from one CPU to another.
   1087 	 *
   1088 	 * XXXSMP
   1089 	 * There is also the issue of locking the other CPU's
   1090 	 * sched state, which we currently do not do.
   1091 	 */
   1092 	ci = (l->l_cpu != NULL) ? l->l_cpu : curcpu();
   1093 	if (pri < ci->ci_schedstate.spc_curpriority)
   1094 		need_resched(ci);
   1095 }
   1096 
   1097 /*
   1098  * Change process state to be runnable,
   1099  * placing it on the run queue if it is in memory,
   1100  * and awakening the swapper if it isn't in memory.
   1101  */
   1102 void
   1103 setrunnable(struct lwp *l)
   1104 {
   1105 	struct proc *p = l->l_proc;
   1106 
   1107 	SCHED_ASSERT_LOCKED();
   1108 
   1109 	switch (l->l_stat) {
   1110 	case 0:
   1111 	case LSRUN:
   1112 	case LSONPROC:
   1113 	case LSZOMB:
   1114 	case LSDEAD:
   1115 	default:
   1116 		panic("setrunnable: lwp %p state was %d", l, l->l_stat);
   1117 	case LSSTOP:
   1118 		/*
   1119 		 * If we're being traced (possibly because someone attached us
   1120 		 * while we were stopped), check for a signal from the debugger.
   1121 		 */
   1122 		if ((p->p_flag & P_TRACED) != 0 && p->p_xstat != 0) {
   1123 			sigaddset(&p->p_sigctx.ps_siglist, p->p_xstat);
   1124 			CHECKSIGS(p);
   1125 		}
   1126 	case LSSLEEP:
   1127 		unsleep(l);		/* e.g. when sending signals */
   1128 		break;
   1129 
   1130 	case LSIDL:
   1131 		break;
   1132 	case LSSUSPENDED:
   1133 		break;
   1134 	}
   1135 
   1136 	if (l->l_proc->p_sa)
   1137 		sa_awaken(l);
   1138 
   1139 	l->l_stat = LSRUN;
   1140 	p->p_nrlwps++;
   1141 
   1142 	if (l->l_flag & L_INMEM)
   1143 		setrunqueue(l);
   1144 
   1145 	if (l->l_slptime > 1)
   1146 		updatepri(l);
   1147 	l->l_slptime = 0;
   1148 	if ((l->l_flag & L_INMEM) == 0)
   1149 		sched_wakeup((caddr_t)&proc0);
   1150 	else
   1151 		resched_proc(l, l->l_priority);
   1152 }
   1153 
   1154 /*
   1155  * Compute the priority of a process when running in user mode.
   1156  * Arrange to reschedule if the resulting priority is better
   1157  * than that of the current process.
   1158  */
   1159 void
   1160 resetpriority(struct lwp *l)
   1161 {
   1162 	unsigned int newpriority;
   1163 	struct proc *p = l->l_proc;
   1164 
   1165 	SCHED_ASSERT_LOCKED();
   1166 
   1167 	newpriority = PUSER + (p->p_estcpu >> ESTCPU_SHIFT) +
   1168 			NICE_WEIGHT * (p->p_nice - NZERO);
   1169 	newpriority = min(newpriority, MAXPRI);
   1170 	l->l_usrpri = newpriority;
   1171 	resched_proc(l, l->l_usrpri);
   1172 }
   1173 
   1174 /*
   1175  * Recompute priority for all LWPs in a process.
   1176  */
   1177 void
   1178 resetprocpriority(struct proc *p)
   1179 {
   1180 	struct lwp *l;
   1181 
   1182 	LIST_FOREACH(l, &p->p_lwps, l_sibling)
   1183 	    resetpriority(l);
   1184 }
   1185 
   1186 /*
   1187  * We adjust the priority of the current process.  The priority of a process
   1188  * gets worse as it accumulates CPU time.  The CPU usage estimator (p_estcpu)
   1189  * is increased here.  The formula for computing priorities (in kern_synch.c)
   1190  * will compute a different value each time p_estcpu increases. This can
   1191  * cause a switch, but unless the priority crosses a PPQ boundary the actual
   1192  * queue will not change.  The CPU usage estimator ramps up quite quickly
   1193  * when the process is running (linearly), and decays away exponentially, at
   1194  * a rate which is proportionally slower when the system is busy.  The basic
   1195  * principle is that the system will 90% forget that the process used a lot
   1196  * of CPU time in 5 * loadav seconds.  This causes the system to favor
   1197  * processes which haven't run much recently, and to round-robin among other
   1198  * processes.
   1199  */
   1200 
   1201 void
   1202 schedclock(struct lwp *l)
   1203 {
   1204 	struct proc *p = l->l_proc;
   1205 	int s;
   1206 
   1207 	p->p_estcpu = ESTCPULIM(p->p_estcpu + (1 << ESTCPU_SHIFT));
   1208 	SCHED_LOCK(s);
   1209 	resetpriority(l);
   1210 	SCHED_UNLOCK(s);
   1211 
   1212 	if (l->l_priority >= PUSER)
   1213 		l->l_priority = l->l_usrpri;
   1214 }
   1215 
   1216 void
   1217 suspendsched()
   1218 {
   1219 	struct lwp *l;
   1220 	int s;
   1221 
   1222 	/*
   1223 	 * Convert all non-P_SYSTEM LSSLEEP or LSRUN processes to
   1224 	 * LSSUSPENDED.
   1225 	 */
   1226 	proclist_lock_read();
   1227 	SCHED_LOCK(s);
   1228 	LIST_FOREACH(l, &alllwp, l_list) {
   1229 		if ((l->l_proc->p_flag & P_SYSTEM) != 0)
   1230 			continue;
   1231 
   1232 		switch (l->l_stat) {
   1233 		case LSRUN:
   1234 			l->l_proc->p_nrlwps--;
   1235 			if ((l->l_flag & L_INMEM) != 0)
   1236 				remrunqueue(l);
   1237 			/* FALLTHROUGH */
   1238 		case LSSLEEP:
   1239 			l->l_stat = LSSUSPENDED;
   1240 			break;
   1241 		case LSONPROC:
   1242 			/*
   1243 			 * XXX SMP: we need to deal with processes on
   1244 			 * others CPU !
   1245 			 */
   1246 			break;
   1247 		default:
   1248 			break;
   1249 		}
   1250 	}
   1251 	SCHED_UNLOCK(s);
   1252 	proclist_unlock_read();
   1253 }
   1254 
   1255 /*
   1256  * scheduler_fork_hook:
   1257  *
   1258  *	Inherit the parent's scheduler history.
   1259  */
   1260 void
   1261 scheduler_fork_hook(struct proc *parent, struct proc *child)
   1262 {
   1263 
   1264 	child->p_estcpu = child->p_estcpu_inherited = parent->p_estcpu;
   1265 	child->p_forktime = schedcpu_ticks;
   1266 }
   1267 
   1268 /*
   1269  * scheduler_wait_hook:
   1270  *
   1271  *	Chargeback parents for the sins of their children.
   1272  */
   1273 void
   1274 scheduler_wait_hook(struct proc *parent, struct proc *child)
   1275 {
   1276 	fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
   1277 	fixpt_t estcpu;
   1278 
   1279 	/* XXX Only if parent != init?? */
   1280 
   1281 	estcpu = decay_cpu_batch(loadfac, child->p_estcpu_inherited,
   1282 	    schedcpu_ticks - child->p_forktime);
   1283 	if (child->p_estcpu > estcpu) {
   1284 		parent->p_estcpu =
   1285 		    ESTCPULIM(parent->p_estcpu + child->p_estcpu - estcpu);
   1286 	}
   1287 }
   1288 
   1289 /*
   1290  * Low-level routines to access the run queue.  Optimised assembler
   1291  * routines can override these.
   1292  */
   1293 
   1294 #ifndef __HAVE_MD_RUNQUEUE
   1295 
   1296 /*
   1297  * On some architectures, it's faster to use a MSB ordering for the priorites
   1298  * than the traditional LSB ordering.
   1299  */
   1300 #ifdef __HAVE_BIGENDIAN_BITOPS
   1301 #define	RQMASK(n) (0x80000000 >> (n))
   1302 #else
   1303 #define	RQMASK(n) (0x00000001 << (n))
   1304 #endif
   1305 
   1306 /*
   1307  * The primitives that manipulate the run queues.  whichqs tells which
   1308  * of the 32 queues qs have processes in them.  Setrunqueue puts processes
   1309  * into queues, remrunqueue removes them from queues.  The running process is
   1310  * on no queue, other processes are on a queue related to p->p_priority,
   1311  * divided by 4 actually to shrink the 0-127 range of priorities into the 32
   1312  * available queues.
   1313  */
   1314 
   1315 #ifdef RQDEBUG
   1316 static void
   1317 checkrunqueue(int whichq, struct lwp *l)
   1318 {
   1319 	const struct prochd * const rq = &sched_qs[whichq];
   1320 	struct lwp *l2;
   1321 	int found = 0;
   1322 	int die = 0;
   1323 	int empty = 1;
   1324 	for (l2 = rq->ph_link; l2 != (const void*) rq; l2 = l2->l_forw) {
   1325 		if (l2->l_stat != LSRUN) {
   1326 			printf("checkrunqueue[%d]: lwp %p state (%d) "
   1327 			    " != LSRUN\n", whichq, l2, l2->l_stat);
   1328 		}
   1329 		if (l2->l_back->l_forw != l2) {
   1330 			printf("checkrunqueue[%d]: lwp %p back-qptr (%p) "
   1331 			    "corrupt %p\n", whichq, l2, l2->l_back,
   1332 			    l2->l_back->l_forw);
   1333 			die = 1;
   1334 		}
   1335 		if (l2->l_forw->l_back != l2) {
   1336 			printf("checkrunqueue[%d]: lwp %p forw-qptr (%p) "
   1337 			    "corrupt %p\n", whichq, l2, l2->l_forw,
   1338 			    l2->l_forw->l_back);
   1339 			die = 1;
   1340 		}
   1341 		if (l2 == l)
   1342 			found = 1;
   1343 		empty = 0;
   1344 	}
   1345 	if (empty && (sched_whichqs & RQMASK(whichq)) != 0) {
   1346 		printf("checkrunqueue[%d]: bit set for empty run-queue %p\n",
   1347 		    whichq, rq);
   1348 		die = 1;
   1349 	} else if (!empty && (sched_whichqs & RQMASK(whichq)) == 0) {
   1350 		printf("checkrunqueue[%d]: bit clear for non-empty "
   1351 		    "run-queue %p\n", whichq, rq);
   1352 		die = 1;
   1353 	}
   1354 	if (l != NULL && (sched_whichqs & RQMASK(whichq)) == 0) {
   1355 		printf("checkrunqueue[%d]: bit clear for active lwp %p\n",
   1356 		    whichq, l);
   1357 		die = 1;
   1358 	}
   1359 	if (l != NULL && empty) {
   1360 		printf("checkrunqueue[%d]: empty run-queue %p with "
   1361 		    "active lwp %p\n", whichq, rq, l);
   1362 		die = 1;
   1363 	}
   1364 	if (l != NULL && !found) {
   1365 		printf("checkrunqueue[%d]: lwp %p not in runqueue %p!",
   1366 		    whichq, l, rq);
   1367 		die = 1;
   1368 	}
   1369 	if (die)
   1370 		panic("checkrunqueue: inconsistency found");
   1371 }
   1372 #endif /* RQDEBUG */
   1373 
   1374 void
   1375 setrunqueue(struct lwp *l)
   1376 {
   1377 	struct prochd *rq;
   1378 	struct lwp *prev;
   1379 	const int whichq = l->l_priority / PPQ;
   1380 
   1381 #ifdef RQDEBUG
   1382 	checkrunqueue(whichq, NULL);
   1383 #endif
   1384 #ifdef DIAGNOSTIC
   1385 	if (l->l_back != NULL || l->l_wchan != NULL || l->l_stat != LSRUN)
   1386 		panic("setrunqueue");
   1387 #endif
   1388 	sched_whichqs |= RQMASK(whichq);
   1389 	rq = &sched_qs[whichq];
   1390 	prev = rq->ph_rlink;
   1391 	l->l_forw = (struct lwp *)rq;
   1392 	rq->ph_rlink = l;
   1393 	prev->l_forw = l;
   1394 	l->l_back = prev;
   1395 #ifdef RQDEBUG
   1396 	checkrunqueue(whichq, l);
   1397 #endif
   1398 }
   1399 
   1400 void
   1401 remrunqueue(struct lwp *l)
   1402 {
   1403 	struct lwp *prev, *next;
   1404 	const int whichq = l->l_priority / PPQ;
   1405 #ifdef RQDEBUG
   1406 	checkrunqueue(whichq, l);
   1407 #endif
   1408 #ifdef DIAGNOSTIC
   1409 	if (((sched_whichqs & RQMASK(whichq)) == 0))
   1410 		panic("remrunqueue: bit %d not set", whichq);
   1411 #endif
   1412 	prev = l->l_back;
   1413 	l->l_back = NULL;
   1414 	next = l->l_forw;
   1415 	prev->l_forw = next;
   1416 	next->l_back = prev;
   1417 	if (prev == next)
   1418 		sched_whichqs &= ~RQMASK(whichq);
   1419 #ifdef RQDEBUG
   1420 	checkrunqueue(whichq, NULL);
   1421 #endif
   1422 }
   1423 
   1424 #undef RQMASK
   1425 #endif /* !defined(__HAVE_MD_RUNQUEUE) */
   1426