Home | History | Annotate | Line # | Download | only in kern
kern_synch.c revision 1.166.2.2
      1 /*	$NetBSD: kern_synch.c,v 1.166.2.2 2006/10/21 15:20:47 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999, 2000, 2004, 2006 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.166.2.2 2006/10/21 15:20:47 ad Exp $");
     78 
     79 #include "opt_ddb.h"
     80 #include "opt_ktrace.h"
     81 #include "opt_kstack.h"
     82 #include "opt_lockdebug.h"
     83 #include "opt_multiprocessor.h"
     84 #include "opt_perfctrs.h"
     85 
     86 #define	__MUTEX_PRIVATE
     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 #include <sys/sleepq.h>
    104 #include <sys/lockdebug.h>
    105 
    106 #include <uvm/uvm_extern.h>
    107 
    108 #ifdef KTRACE
    109 #include <sys/ktrace.h>
    110 #endif
    111 
    112 #include <machine/cpu.h>
    113 
    114 int	lbolt;			/* once a second sleep address */
    115 int	rrticks;		/* number of hardclock ticks per roundrobin() */
    116 
    117 /*
    118  * The global scheduler state.
    119  */
    120 kmutex_t	sched_mutex;		/* global run queue mutex */
    121 struct prochd	sched_qs[RUNQUE_NQS];	/* run queues */
    122 volatile uint32_t sched_whichqs;	/* bitmap of non-empty queues */
    123 
    124 void	schedcpu(void *);
    125 void	updatepri(struct lwp *);
    126 void	sa_awaken(struct lwp *);
    127 
    128 struct callout schedcpu_ch = CALLOUT_INITIALIZER_SETFUNC(schedcpu, NULL);
    129 static unsigned int schedcpu_ticks;
    130 
    131 /*
    132  * Force switch among equal priority processes every 100ms.
    133  * Called from hardclock every hz/10 == rrticks hardclock ticks.
    134  */
    135 /* ARGSUSED */
    136 void
    137 roundrobin(struct cpu_info *ci)
    138 {
    139 	struct schedstate_percpu *spc = &ci->ci_schedstate;
    140 
    141 	spc->spc_rrticks = rrticks;
    142 
    143 	if (curlwp != NULL) {
    144 		if (spc->spc_flags & SPCF_SEENRR) {
    145 			/*
    146 			 * The process has already been through a roundrobin
    147 			 * without switching and may be hogging the CPU.
    148 			 * Indicate that the process should yield.
    149 			 */
    150 			spc->spc_flags |= SPCF_SHOULDYIELD;
    151 		} else
    152 			spc->spc_flags |= SPCF_SEENRR;
    153 	}
    154 	cpu_need_resched(curcpu());
    155 }
    156 
    157 #define	PPQ	(128 / RUNQUE_NQS)	/* priorities per queue */
    158 #define	NICE_WEIGHT 2			/* priorities per nice level */
    159 
    160 #define	ESTCPU_SHIFT	11
    161 #define	ESTCPU_MAX	((NICE_WEIGHT * PRIO_MAX - PPQ) << ESTCPU_SHIFT)
    162 #define	ESTCPULIM(e)	min((e), ESTCPU_MAX)
    163 
    164 /*
    165  * Constants for digital decay and forget:
    166  *	90% of (p_estcpu) usage in 5 * loadav time
    167  *	95% of (p_pctcpu) usage in 60 seconds (load insensitive)
    168  *          Note that, as ps(1) mentions, this can let percentages
    169  *          total over 100% (I've seen 137.9% for 3 processes).
    170  *
    171  * Note that hardclock updates p_estcpu and p_cpticks independently.
    172  *
    173  * We wish to decay away 90% of p_estcpu in (5 * loadavg) seconds.
    174  * That is, the system wants to compute a value of decay such
    175  * that the following for loop:
    176  * 	for (i = 0; i < (5 * loadavg); i++)
    177  * 		p_estcpu *= decay;
    178  * will compute
    179  * 	p_estcpu *= 0.1;
    180  * for all values of loadavg:
    181  *
    182  * Mathematically this loop can be expressed by saying:
    183  * 	decay ** (5 * loadavg) ~= .1
    184  *
    185  * The system computes decay as:
    186  * 	decay = (2 * loadavg) / (2 * loadavg + 1)
    187  *
    188  * We wish to prove that the system's computation of decay
    189  * will always fulfill the equation:
    190  * 	decay ** (5 * loadavg) ~= .1
    191  *
    192  * If we compute b as:
    193  * 	b = 2 * loadavg
    194  * then
    195  * 	decay = b / (b + 1)
    196  *
    197  * We now need to prove two things:
    198  *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
    199  *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
    200  *
    201  * Facts:
    202  *         For x close to zero, exp(x) =~ 1 + x, since
    203  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
    204  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
    205  *         For x close to zero, ln(1+x) =~ x, since
    206  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
    207  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
    208  *         ln(.1) =~ -2.30
    209  *
    210  * Proof of (1):
    211  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
    212  *	solving for factor,
    213  *      ln(factor) =~ (-2.30/5*loadav), or
    214  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
    215  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
    216  *
    217  * Proof of (2):
    218  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
    219  *	solving for power,
    220  *      power*ln(b/(b+1)) =~ -2.30, or
    221  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
    222  *
    223  * Actual power values for the implemented algorithm are as follows:
    224  *      loadav: 1       2       3       4
    225  *      power:  5.68    10.32   14.94   19.55
    226  */
    227 
    228 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
    229 #define	loadfactor(loadav)	(2 * (loadav))
    230 
    231 static fixpt_t
    232 decay_cpu(fixpt_t loadfac, fixpt_t estcpu)
    233 {
    234 
    235 	if (estcpu == 0) {
    236 		return 0;
    237 	}
    238 
    239 #if !defined(_LP64)
    240 	/* avoid 64bit arithmetics. */
    241 #define	FIXPT_MAX ((fixpt_t)((UINTMAX_C(1) << sizeof(fixpt_t) * CHAR_BIT) - 1))
    242 	if (__predict_true(loadfac <= FIXPT_MAX / ESTCPU_MAX)) {
    243 		return estcpu * loadfac / (loadfac + FSCALE);
    244 	}
    245 #endif /* !defined(_LP64) */
    246 
    247 	return (uint64_t)estcpu * loadfac / (loadfac + FSCALE);
    248 }
    249 
    250 /*
    251  * For all load averages >= 1 and max p_estcpu of (255 << ESTCPU_SHIFT),
    252  * sleeping for at least seven times the loadfactor will decay p_estcpu to
    253  * less than (1 << ESTCPU_SHIFT).
    254  *
    255  * note that our ESTCPU_MAX is actually much smaller than (255 << ESTCPU_SHIFT).
    256  */
    257 static fixpt_t
    258 decay_cpu_batch(fixpt_t loadfac, fixpt_t estcpu, unsigned int n)
    259 {
    260 
    261 	if ((n << FSHIFT) >= 7 * loadfac) {
    262 		return 0;
    263 	}
    264 
    265 	while (estcpu != 0 && n > 1) {
    266 		estcpu = decay_cpu(loadfac, estcpu);
    267 		n--;
    268 	}
    269 
    270 	return estcpu;
    271 }
    272 
    273 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
    274 fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;		/* exp(-1/20) */
    275 
    276 /*
    277  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
    278  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
    279  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
    280  *
    281  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
    282  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
    283  *
    284  * If you dont want to bother with the faster/more-accurate formula, you
    285  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
    286  * (more general) method of calculating the %age of CPU used by a process.
    287  */
    288 #define	CCPU_SHIFT	11
    289 
    290 /*
    291  * Recompute process priorities, every hz ticks.
    292  */
    293 /* ARGSUSED */
    294 void
    295 schedcpu(void *arg)
    296 {
    297 	fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
    298 	struct rlimit *rlim;
    299 	struct lwp *l;
    300 	struct proc *p;
    301 	int s, minslp;
    302 	int clkhz;
    303 	long runtm;
    304 
    305 	schedcpu_ticks++;
    306 
    307 	mutex_enter(&proclist_mutex);
    308 	PROCLIST_FOREACH(p, &allproc) {
    309 		/*
    310 		 * Increment time in/out of memory and sleep time (if
    311 		 * sleeping).  We ignore overflow; with 16-bit int's
    312 		 * (remember them?) overflow takes 45 days.
    313 		 *
    314 		 * XXXSMP Should create an activeproc list so that we
    315 		 * don't touch every proc+LWP in the system on a regular
    316 		 * basis. l->l_swtime/l->l_slptime can become deltas.
    317 		 */
    318 		minslp = 2;
    319 		runtm = 0;
    320 		mutex_enter(&p->p_smutex);
    321 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    322 			lwp_lock(l);
    323 			runtm += l->l_rtime.tv_sec;
    324 			l->l_swtime++;
    325 			if (l->l_stat == LSSLEEP || l->l_stat == LSSTOP ||
    326 			    l->l_stat == LSSUSPENDED) {
    327 				l->l_slptime++;
    328 				minslp = min(minslp, l->l_slptime);
    329 			} else
    330 				minslp = 0;
    331 			lwp_unlock(l);
    332 		}
    333 		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
    334 
    335 		/*
    336 		 * Check if the process exceeds its CPU resource allocation.
    337 		 * If over max, kill it.  In any case, if it has run for more
    338 		 * than autonicetime, reduce priority to give others a chance.
    339 		 */
    340 		rlim = &p->p_rlimit[RLIMIT_CPU];
    341 		if (runtm >= rlim->rlim_cur) {
    342 			if (runtm >= rlim->rlim_max)
    343 				psignal(p, SIGKILL);
    344 			else {
    345 				psignal(p, SIGXCPU);
    346 				if (rlim->rlim_cur < rlim->rlim_max)
    347 					rlim->rlim_cur += 5;
    348 			}
    349 		}
    350 		if (autonicetime && runtm > autonicetime && p->p_nice == NZERO
    351 		    && kauth_cred_geteuid(p->p_cred)) {
    352 			p->p_nice = autoniceval + NZERO;
    353 			resetprocpriority(p);
    354 		}
    355 
    356 		/*
    357 		 * If the process has slept the entire second,
    358 		 * stop recalculating its priority until it wakes up.
    359 		 */
    360 		if (minslp > 1) {
    361 			mutex_exit(&p->p_smutex);
    362 			continue;
    363 		}
    364 		/* XXXAD lock */
    365 		s = splstatclock();	/* prevent state changes */
    366 		/*
    367 		 * p_pctcpu is only for ps.
    368 		 */
    369 		clkhz = stathz != 0 ? stathz : hz;
    370 #if	(FSHIFT >= CCPU_SHIFT)
    371 		p->p_pctcpu += (clkhz == 100)?
    372 			((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT):
    373                 	100 * (((fixpt_t) p->p_cpticks)
    374 				<< (FSHIFT - CCPU_SHIFT)) / clkhz;
    375 #else
    376 		p->p_pctcpu += ((FSCALE - ccpu) *
    377 			(p->p_cpticks * FSCALE / clkhz)) >> FSHIFT;
    378 #endif
    379 		p->p_cpticks = 0;
    380 		p->p_estcpu = decay_cpu(loadfac, p->p_estcpu);
    381 		splx(s);	/* Done with the process CPU ticks update */
    382 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    383 			lwp_lock(l);
    384 			if (l->l_slptime > 1) {
    385 				lwp_unlock(l);
    386 				continue;
    387 			}
    388 			resetpriority(l);
    389 			if (l->l_priority >= PUSER) {
    390 				if (l->l_stat == LSRUN &&
    391 				    (l->l_flag & L_INMEM) &&
    392 				    (l->l_priority / PPQ) != (l->l_usrpri / PPQ)) {
    393 					remrunqueue(l);
    394 					l->l_priority = l->l_usrpri;
    395 					setrunqueue(l);
    396 				} else
    397 					l->l_priority = l->l_usrpri;
    398 			}
    399 			lwp_unlock(l);
    400 		}
    401 		mutex_exit(&p->p_smutex);
    402 	}
    403 	mutex_exit(&proclist_mutex);
    404 	uvm_meter();
    405 	wakeup((caddr_t)&lbolt);
    406 	callout_schedule(&schedcpu_ch, hz);
    407 }
    408 
    409 /*
    410  * Recalculate the priority of a process after it has slept for a while.
    411  */
    412 void
    413 updatepri(struct lwp *l)
    414 {
    415 	struct proc *p = l->l_proc;
    416 	fixpt_t loadfac;
    417 
    418 	LOCK_ASSERT(lwp_locked(l, NULL));
    419 	KASSERT(l->l_slptime > 1);
    420 
    421 	loadfac = loadfactor(averunnable.ldavg[0]);
    422 
    423 	l->l_slptime--; /* the first time was done in schedcpu */
    424 	/* XXX NJWLWP */
    425 	/* XXXSMP occasionaly unlocked. */
    426 	p->p_estcpu = decay_cpu_batch(loadfac, p->p_estcpu, l->l_slptime);
    427 	resetpriority(l);
    428 }
    429 
    430 /*
    431  * During autoconfiguration or after a panic, a sleep will simply lower the
    432  * priority briefly to allow interrupts, then return.  The priority to be
    433  * used (safepri) is machine-dependent, thus this value is initialized and
    434  * maintained in the machine-dependent layers.  This priority will typically
    435  * be 0, or the lowest priority that is safe for use on the interrupt stack;
    436  * it can be made higher to block network software interrupts after panics.
    437  */
    438 int	safepri;
    439 
    440 /*
    441  * ltsleep: see mtsleep() for comments.
    442  */
    443 int
    444 ltsleep(wchan_t ident, int priority, const char *wmesg, int timo,
    445 	volatile struct simplelock *interlock)
    446 {
    447 	struct lwp *l = curlwp;
    448 	sleepq_t *sq;
    449 	int error;
    450 
    451 	if (sleepq_dontsleep(l)) {
    452 		(void)sleepq_abort(NULL, 0);
    453 		if ((priority & PNORELOCK) != 0)
    454 			simple_unlock(interlock);
    455 		return 0;
    456 	}
    457 
    458 	sq = sleeptab_lookup(ident);
    459 	sleepq_enter(sq, priority, ident, wmesg, timo, priority & PCATCH);
    460 
    461 	if (interlock != NULL) {
    462 		LOCK_ASSERT(simple_lock_held(interlock));
    463 		simple_unlock(interlock);
    464 	}
    465 
    466 	error = sleepq_block(sq, timo);
    467 
    468 	if (interlock != NULL && (priority & PNORELOCK) == 0)
    469 		simple_lock(interlock);
    470 
    471 	return error;
    472 }
    473 
    474 /*
    475  * General sleep call.  Suspends the current process until a wakeup is
    476  * performed on the specified identifier.  The process will then be made
    477  * runnable with the specified priority.  Sleeps at most timo/hz seconds (0
    478  * means no timeout).  If pri includes PCATCH flag, signals are checked
    479  * before and after sleeping, else signals are not checked.  Returns 0 if
    480  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
    481  * signal needs to be delivered, ERESTART is returned if the current system
    482  * call should be restarted if possible, and EINTR is returned if the system
    483  * call should be interrupted by the signal (return EINTR).
    484  *
    485  * The interlock is held until we are on a sleep queue. The interlock will
    486  * be locked before returning back to the caller unless the PNORELOCK flag
    487  * is specified, in which case the interlock will always be unlocked upon
    488  * return.
    489  */
    490 int
    491 mtsleep(wchan_t ident, int priority, const char *wmesg, int timo,
    492 	kmutex_t *mtx)
    493 {
    494 	struct lwp *l = curlwp;
    495 	sleepq_t *sq;
    496 	int error;
    497 
    498 	if (sleepq_dontsleep(l))
    499 		return sleepq_abort(mtx, priority & PNORELOCK);
    500 
    501 	sq = sleeptab_lookup(ident);
    502 	sleepq_enter(sq, priority, ident, wmesg, timo, priority & PCATCH);
    503 
    504 	if (mtx != NULL) {
    505 		LOCK_ASSERT(mutex_owned(mtx));
    506 		mutex_exit_linked(mtx, l->l_mutex);
    507 	}
    508 
    509 	error = sleepq_block(sq, timo);
    510 
    511 	if (mtx != NULL && (priority & PNORELOCK) == 0)
    512 		mutex_enter(mtx);
    513 
    514 	return error;
    515 }
    516 
    517 void
    518 sa_awaken(struct lwp *l)
    519 {
    520 
    521 	LOCK_ASSERT(lwp_locked(l, NULL));
    522 
    523 	if (l == l->l_savp->savp_lwp && l->l_flag & L_SA_YIELD)
    524 		l->l_flag &= ~L_SA_IDLE;
    525 }
    526 
    527 /*
    528  * Make all processes sleeping on the specified identifier runnable.
    529  */
    530 void
    531 wakeup(wchan_t ident)
    532 {
    533 	sleepq_t *sq;
    534 
    535 	if (cold)
    536 		return;
    537 
    538 	sq = sleeptab_lookup(ident);
    539 	sleepq_wakeall(sq, ident, (u_int)-1);
    540 }
    541 
    542 /*
    543  * Make the highest priority process first in line on the specified
    544  * identifier runnable.
    545  */
    546 void
    547 wakeup_one(wchan_t ident)
    548 {
    549 	sleepq_t *sq;
    550 
    551 	if (cold)
    552 		return;
    553 
    554 	sq = sleeptab_lookup(ident);
    555 	sleepq_wakeone(sq, ident);
    556 }
    557 
    558 
    559 /*
    560  * General yield call.  Puts the current process back on its run queue and
    561  * performs a voluntary context switch.  Should only be called when the
    562  * current process explicitly requests it (eg sched_yield(2) in compat code).
    563  */
    564 void
    565 yield(void)
    566 {
    567 	struct lwp *l = curlwp;
    568 
    569 	lwp_lock(l);
    570 	if (l->l_stat == LSONPROC) {
    571 		l->l_priority = l->l_usrpri;
    572 		l->l_stat = LSRUN;
    573 		mutex_enter(&sched_mutex);
    574 		lwp_swaplock_linked(l, &sched_mutex);
    575 		setrunqueue(l);
    576 	}
    577 	l->l_nvcsw++;
    578 	mi_switch(l, NULL);
    579 }
    580 
    581 /*
    582  * General preemption call.  Puts the current process back on its run queue
    583  * and performs an involuntary context switch.
    584  * The 'more' ("more work to do") argument is boolean. Returning to userspace
    585  * preempt() calls pass 0. "Voluntary" preemptions in e.g. uiomove() pass 1.
    586  * This will be used to indicate to the SA subsystem that the LWP is
    587  * not yet finished in the kernel.
    588  */
    589 void
    590 preempt(int more)
    591 {
    592 	struct lwp *l = curlwp;
    593 	int r;
    594 
    595 	lwp_lock(l);
    596 	if (l->l_stat == LSONPROC) {
    597 		l->l_priority = l->l_usrpri;
    598 		l->l_stat = LSRUN;
    599 		mutex_enter(&sched_mutex);
    600 		lwp_swaplock_linked(l, &sched_mutex);
    601 		setrunqueue(l);
    602 	}
    603 	l->l_nivcsw++;
    604 	r = mi_switch(l, NULL);
    605 	if ((l->l_flag & L_SA) != 0 && r != 0 && more == 0)	/* XXXAD */
    606 		sa_preempt(l);
    607 }
    608 
    609 /*
    610  * The machine independent parts of context switch.  Switch to "new"
    611  * if non-NULL, otherwise let cpu_switch choose the next lwp.
    612  *
    613  * Returns 1 if another process was actually run.
    614  */
    615 int
    616 mi_switch(struct lwp *l, struct lwp *newl)
    617 {
    618 	struct schedstate_percpu *spc;
    619 	struct timeval tv;
    620 	int hold_count;
    621 	int retval, oldspl;
    622 	long s, u;
    623 #if PERFCTRS
    624 	struct proc *p = l->l_proc;
    625 #endif
    626 
    627 	LOCK_ASSERT(lwp_locked(l, NULL));
    628 
    629 	/*
    630 	 * Release the kernel_lock, as we are about to yield the CPU.
    631 	 */
    632 	hold_count = KERNEL_LOCK_RELEASE_ALL();
    633 
    634 #ifdef LOCKDEBUG
    635 	spinlock_switchcheck();
    636 	simple_lock_switchcheck();
    637 #endif
    638 #ifdef KSTACK_CHECK_MAGIC
    639 	kstack_check_magic(l);
    640 #endif
    641 
    642 	/*
    643 	 * It's safe to read the per CPU schedstate unlocked here, as all we
    644 	 * are after is the run time and that's guarenteed to have been last
    645 	 * updated by this CPU.
    646 	 */
    647 	KDASSERT(l->l_cpu != NULL);
    648 	KDASSERT(l->l_cpu == curcpu());
    649 	spc = &l->l_cpu->ci_schedstate;
    650 
    651 	/*
    652 	 * Compute the amount of time during which the current
    653 	 * process was running.
    654 	 */
    655 	microtime(&tv);
    656 	u = l->l_rtime.tv_usec +
    657 	    (tv.tv_usec - spc->spc_runtime.tv_usec);
    658 	s = l->l_rtime.tv_sec + (tv.tv_sec - spc->spc_runtime.tv_sec);
    659 	if (u < 0) {
    660 		u += 1000000;
    661 		s--;
    662 	} else if (u >= 1000000) {
    663 		u -= 1000000;
    664 		s++;
    665 	}
    666 	l->l_rtime.tv_usec = u;
    667 	l->l_rtime.tv_sec = s;
    668 
    669 	/*
    670 	 * XXXSMP If we are using h/w performance counters, save context.
    671 	 */
    672 #if PERFCTRS
    673 	if (PMC_ENABLED(p)) {
    674 		pmc_save_context(p);
    675 	}
    676 #endif
    677 
    678 	/*
    679 	 * Acquire the sched_mutex if necessary.  It will be released by
    680 	 * cpu_switch once it has decided to idle, or picked another LWP
    681 	 * to run.
    682 	 */
    683 	oldspl = mutex_getspl(l->l_mutex);
    684 	if (l->l_mutex != &sched_mutex) {
    685 		lwp_unlock(l);
    686 		mutex_enter(&sched_mutex);
    687 	}
    688 	uvmexp.swtch++;
    689 
    690 	/*
    691 	 * Process is about to yield the CPU; clear the appropriate
    692 	 * scheduling flags.
    693 	 */
    694 	spc->spc_flags &= ~SPCF_SWITCHCLEAR;
    695 
    696 	LOCKDEBUG_BARRIER(&sched_mutex, 1);
    697 
    698 	/*
    699 	 * Switch to the new current LWP.  When we run again, we'll
    700 	 * return back here.
    701 	 */
    702 	if (newl == NULL)
    703 		retval = cpu_switch(l, NULL);
    704 	else {
    705 		/* XXXAD ? */
    706 		remrunqueue(newl);
    707 		cpu_switchto(l, newl);
    708 		retval = 0;
    709 	}
    710 
    711 	/*
    712 	 * XXXSMP If we are using h/w performance counters, restore context.
    713 	 */
    714 #if PERFCTRS
    715 	if (PMC_ENABLED(p)) {
    716 		pmc_restore_context(p);
    717 	}
    718 #endif
    719 
    720 	/*
    721 	 * We're running again; record our new start time.  We might
    722 	 * be running on a new CPU now, so don't use the cached
    723 	 * schedstate_percpu pointer.
    724 	 */
    725 	KDASSERT(l->l_cpu != NULL);
    726 	KDASSERT(l->l_cpu == curcpu());
    727 	microtime(&l->l_cpu->ci_schedstate.spc_runtime);
    728 
    729 	/*
    730 	 * Reacquire the kernel_lock, and restore the old SPL.
    731 	 */
    732 	KERNEL_LOCK_ACQUIRE_COUNT(hold_count);
    733 	splx(oldspl);
    734 
    735 	return retval;
    736 }
    737 
    738 /*
    739  * Initialize the (doubly-linked) run queues
    740  * to be empty.
    741  */
    742 void
    743 rqinit()
    744 {
    745 	int i;
    746 
    747 	for (i = 0; i < RUNQUE_NQS; i++)
    748 		sched_qs[i].ph_link = sched_qs[i].ph_rlink =
    749 		    (struct lwp *)&sched_qs[i];
    750 
    751 	mutex_init(&sched_mutex, MUTEX_SPIN, IPL_SCHED);
    752 }
    753 
    754 static inline void
    755 resched_lwp(struct lwp *l, u_char pri)
    756 {
    757 	struct cpu_info *ci;
    758 
    759 	LOCK_ASSERT(lwp_locked(l, NULL));
    760 
    761 	/*
    762 	 * XXXSMP
    763 	 * Since l->l_cpu persists across a context switch,
    764 	 * this gives us *very weak* processor affinity, in
    765 	 * that we notify the CPU on which the process last
    766 	 * ran that it should try to switch.
    767 	 *
    768 	 * This does not guarantee that the process will run on
    769 	 * that processor next, because another processor might
    770 	 * grab it the next time it performs a context switch.
    771 	 *
    772 	 * This also does not handle the case where its last
    773 	 * CPU is running a higher-priority process, but every
    774 	 * other CPU is running a lower-priority process.  There
    775 	 * are ways to handle this situation, but they're not
    776 	 * currently very pretty, and we also need to weigh the
    777 	 * cost of moving a process from one CPU to another.
    778 	 */
    779 	ci = (l->l_cpu != NULL) ? l->l_cpu : curcpu();
    780 	if (pri < ci->ci_schedstate.spc_curpriority)
    781 		cpu_need_resched(ci);
    782 }
    783 
    784 /*
    785  * Change process state to be runnable, placing it on the run queue if it is
    786  * in memory, and awakening the swapper if it isn't in memory.
    787  *
    788  * Call with the process and LWP locked.  Will return with the LWP unlocked.
    789  */
    790 void
    791 setrunnable(struct lwp *l)
    792 {
    793 	struct proc *p = l->l_proc;
    794 
    795 	LOCK_ASSERT(mutex_owned(&p->p_smutex));
    796 	LOCK_ASSERT(lwp_locked(l, NULL));
    797 
    798 	switch (l->l_stat) {
    799 	case LSSTOP:
    800 		/*
    801 		 * If we're being traced (possibly because someone attached us
    802 		 * while we were stopped), check for a signal from the debugger.
    803 		 */
    804 		if ((p->p_flag & P_TRACED) != 0 && p->p_xstat != 0) {
    805 			sigaddset(&l->l_sigpend.sp_set, p->p_xstat);
    806 			signotify(l);
    807 		}
    808 		p->p_nrlwps++;
    809 		break;
    810 	case LSSUSPENDED:
    811 		p->p_nrlwps++;
    812 		break;
    813 	case LSSLEEP:
    814 		break;
    815 	default:
    816 		panic("setrunnable: lwp %p state was %d", l, l->l_stat);
    817 	}
    818 
    819 	/*
    820 	 * If the LWP was sleeping interruptably, then it's OK to start it
    821 	 * again.  If not, mark it as still sleeping.
    822 	 */
    823 	if (l->l_wchan != NULL) {
    824 		l->l_stat = LSSLEEP;
    825 		if ((l->l_flag & L_SINTR) != 0)
    826 			sleepq_unsleep(l);
    827 		return;
    828 	}
    829 
    830 	if (l->l_proc->p_sa)
    831 		sa_awaken(l);
    832 
    833 	l->l_stat = LSRUN;
    834 
    835 	/*
    836 	 * Put the LWP onto the run queue, and set sched_mutex as it's
    837 	 * current mutex.
    838 	 */
    839 	mutex_enter(&sched_mutex);
    840 	lwp_swaplock_linked(l, &sched_mutex);
    841 
    842 	if (l->l_slptime > 1)
    843 		updatepri(l);
    844 	l->l_slptime = 0;
    845 
    846 	if (l->l_flag & L_INMEM) {
    847 		setrunqueue(l);
    848 		resched_lwp(l, l->l_priority);
    849 		lwp_unlock(l);
    850 	} else {
    851 		lwp_unlock(l);
    852 
    853 		/*
    854 		 * The LWP is paged out; kick the swapper into action.
    855 		 */
    856 		wakeup(&proc0);
    857 	}
    858 }
    859 
    860 /*
    861  * Compute the priority of a process when running in user mode.
    862  * Arrange to reschedule if the resulting priority is better
    863  * than that of the current process.
    864  */
    865 void
    866 resetpriority(struct lwp *l)
    867 {
    868 	unsigned int newpriority;
    869 	struct proc *p = l->l_proc;
    870 
    871 	LOCK_ASSERT(lwp_locked(l, NULL));
    872 
    873 	/* XXXSMP proc values will be accessed unlocked */
    874 	newpriority = PUSER + (p->p_estcpu >> ESTCPU_SHIFT) +
    875 			NICE_WEIGHT * (p->p_nice - NZERO);
    876 	newpriority = min(newpriority, MAXPRI);
    877 	l->l_usrpri = newpriority;
    878 	resched_lwp(l, l->l_usrpri);
    879 }
    880 
    881 /*
    882  * Recompute priority for all LWPs in a process.
    883  */
    884 void
    885 resetprocpriority(struct proc *p)
    886 {
    887 	struct lwp *l;
    888 
    889 	LOCK_ASSERT(mutex_owned(&p->p_smutex));
    890 
    891 	LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    892 		lwp_lock(l);
    893 		resetpriority(l);
    894 		lwp_unlock(l);
    895 	}
    896 }
    897 
    898 /*
    899  * We adjust the priority of the current process.  The priority of a process
    900  * gets worse as it accumulates CPU time.  The CPU usage estimator (p_estcpu)
    901  * is increased here.  The formula for computing priorities (in kern_synch.c)
    902  * will compute a different value each time p_estcpu increases. This can
    903  * cause a switch, but unless the priority crosses a PPQ boundary the actual
    904  * queue will not change.  The CPU usage estimator ramps up quite quickly
    905  * when the process is running (linearly), and decays away exponentially, at
    906  * a rate which is proportionally slower when the system is busy.  The basic
    907  * principle is that the system will 90% forget that the process used a lot
    908  * of CPU time in 5 * loadav seconds.  This causes the system to favor
    909  * processes which haven't run much recently, and to round-robin among other
    910  * processes.
    911  */
    912 
    913 void
    914 schedclock(struct lwp *l)
    915 {
    916 	struct proc *p = l->l_proc;
    917 
    918 	LOCK_ASSERT(mutex_owned(&p->p_smutex));
    919 
    920 	p->p_estcpu = ESTCPULIM(p->p_estcpu + (1 << ESTCPU_SHIFT));
    921 
    922 	lwp_lock(l);
    923 	resetpriority(l);
    924 	if (l->l_priority >= PUSER)
    925 		l->l_priority = l->l_usrpri;
    926 	lwp_unlock(l);
    927 }
    928 
    929 /*
    930  * suspendsched:
    931  *
    932  *	Convert all non-L_SYSTEM LSSLEEP or LSRUN LWPs to LSSUSPENDED.
    933  *	This violates locking conventions (p->p_smutex is not held),
    934  *	however since it is only used during panic or shutdown that is
    935  *	not a problem.
    936  *
    937  *	XXXAD Do by process?
    938  */
    939 void
    940 suspendsched()
    941 {
    942 	struct lwp *l;
    943 	struct proc *p;
    944 
    945 	mutex_enter(&alllwp_mutex);
    946 	LIST_FOREACH(l, &alllwp, l_list) {
    947 		if ((l->l_flag & L_SYSTEM) != 0)
    948 			continue;
    949 
    950 		p = l->l_proc;
    951 
    952 		lwp_lock(l);
    953 		switch (l->l_stat) {
    954 		case LSRUN:
    955 			p->p_nrlwps--;
    956 			l->l_stat = LSSUSPENDED;
    957 			remrunqueue(l);
    958 			break;
    959 		case LSONPROC:
    960 			p->p_nrlwps--;
    961 			l->l_stat = LSSUSPENDED;
    962 			break;
    963 		case LSSLEEP:
    964 			p->p_nrlwps--;
    965 			l->l_stat = LSSUSPENDED;
    966 			break;
    967 		default:
    968 			break;
    969 		}
    970 		lwp_swaplock(l, &lwp_mutex);
    971 	}
    972 	mutex_exit(&alllwp_mutex);
    973 }
    974 
    975 /*
    976  * scheduler_fork_hook:
    977  *
    978  *	Inherit the parent's scheduler history.
    979  */
    980 void
    981 scheduler_fork_hook(struct proc *parent, struct proc *child)
    982 {
    983 
    984 	mutex_enter(&parent->p_smutex);
    985 	child->p_estcpu = child->p_estcpu_inherited = parent->p_estcpu;
    986 	child->p_forktime = schedcpu_ticks;
    987 	mutex_exit(&parent->p_smutex);
    988 }
    989 
    990 /*
    991  * scheduler_wait_hook:
    992  *
    993  *	Chargeback parents for the sins of their children.
    994  */
    995 void
    996 scheduler_wait_hook(struct proc *parent, struct proc *child)
    997 {
    998 	fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
    999 	fixpt_t estcpu;
   1000 
   1001 	/* XXX Only if parent != init?? */
   1002 
   1003 	mutex_enter(&parent->p_smutex);
   1004 	estcpu = decay_cpu_batch(loadfac, child->p_estcpu_inherited,
   1005 	    schedcpu_ticks - child->p_forktime);
   1006 	if (child->p_estcpu > estcpu)
   1007 		parent->p_estcpu =
   1008 		    ESTCPULIM(parent->p_estcpu + child->p_estcpu - estcpu);
   1009 	mutex_exit(&parent->p_smutex);
   1010 }
   1011 
   1012 /*
   1013  * XXXAD Scale an LWP priority (possibly a user priority) to a kernel one.
   1014  * This is a hack; think of something better.  Do unlocked for now.
   1015  */
   1016 int
   1017 sched_kpri(struct lwp *l)
   1018 {
   1019 	const int obase = PUSER;
   1020 	const int ospan = MAXPRI - obase;
   1021 	const int nbase = PRIBIO;
   1022 	const int nspan = PUSER - nbase;
   1023 
   1024 	if (l->l_priority < obase)
   1025 		return (l->l_priority);
   1026 
   1027 	return (l->l_priority - obase) * nspan / ospan + nbase;
   1028 }
   1029 
   1030 /*
   1031  * Low-level routines to access the run queue.  Optimised assembler
   1032  * routines can override these.
   1033  */
   1034 
   1035 #ifndef __HAVE_MD_RUNQUEUE
   1036 
   1037 /*
   1038  * On some architectures, it's faster to use a MSB ordering for the priorites
   1039  * than the traditional LSB ordering.
   1040  */
   1041 #ifdef __HAVE_BIGENDIAN_BITOPS
   1042 #define	RQMASK(n) (0x80000000 >> (n))
   1043 #else
   1044 #define	RQMASK(n) (0x00000001 << (n))
   1045 #endif
   1046 
   1047 /*
   1048  * The primitives that manipulate the run queues.  whichqs tells which
   1049  * of the 32 queues qs have processes in them.  Setrunqueue puts processes
   1050  * into queues, remrunqueue removes them from queues.  The running process is
   1051  * on no queue, other processes are on a queue related to p->p_priority,
   1052  * divided by 4 actually to shrink the 0-127 range of priorities into the 32
   1053  * available queues.
   1054  */
   1055 #ifdef RQDEBUG
   1056 static void
   1057 checkrunqueue(int whichq, struct lwp *l)
   1058 {
   1059 	const struct prochd * const rq = &sched_qs[whichq];
   1060 	struct lwp *l2;
   1061 	int found = 0;
   1062 	int die = 0;
   1063 	int empty = 1;
   1064 	for (l2 = rq->ph_link; l2 != (const void*) rq; l2 = l2->l_forw) {
   1065 		if (l2->l_stat != LSRUN) {
   1066 			printf("checkrunqueue[%d]: lwp %p state (%d) "
   1067 			    " != LSRUN\n", whichq, l2, l2->l_stat);
   1068 		}
   1069 		if (l2->l_back->l_forw != l2) {
   1070 			printf("checkrunqueue[%d]: lwp %p back-qptr (%p) "
   1071 			    "corrupt %p\n", whichq, l2, l2->l_back,
   1072 			    l2->l_back->l_forw);
   1073 			die = 1;
   1074 		}
   1075 		if (l2->l_forw->l_back != l2) {
   1076 			printf("checkrunqueue[%d]: lwp %p forw-qptr (%p) "
   1077 			    "corrupt %p\n", whichq, l2, l2->l_forw,
   1078 			    l2->l_forw->l_back);
   1079 			die = 1;
   1080 		}
   1081 		if (l2 == l)
   1082 			found = 1;
   1083 		empty = 0;
   1084 	}
   1085 	if (empty && (sched_whichqs & RQMASK(whichq)) != 0) {
   1086 		printf("checkrunqueue[%d]: bit set for empty run-queue %p\n",
   1087 		    whichq, rq);
   1088 		die = 1;
   1089 	} else if (!empty && (sched_whichqs & RQMASK(whichq)) == 0) {
   1090 		printf("checkrunqueue[%d]: bit clear for non-empty "
   1091 		    "run-queue %p\n", whichq, rq);
   1092 		die = 1;
   1093 	}
   1094 	if (l != NULL && (sched_whichqs & RQMASK(whichq)) == 0) {
   1095 		printf("checkrunqueue[%d]: bit clear for active lwp %p\n",
   1096 		    whichq, l);
   1097 		die = 1;
   1098 	}
   1099 	if (l != NULL && empty) {
   1100 		printf("checkrunqueue[%d]: empty run-queue %p with "
   1101 		    "active lwp %p\n", whichq, rq, l);
   1102 		die = 1;
   1103 	}
   1104 	if (l != NULL && !found) {
   1105 		printf("checkrunqueue[%d]: lwp %p not in runqueue %p!",
   1106 		    whichq, l, rq);
   1107 		die = 1;
   1108 	}
   1109 	if (die)
   1110 		panic("checkrunqueue: inconsistency found");
   1111 }
   1112 #endif /* RQDEBUG */
   1113 
   1114 void
   1115 setrunqueue(struct lwp *l)
   1116 {
   1117 	struct prochd *rq;
   1118 	struct lwp *prev;
   1119 	const int whichq = l->l_priority / PPQ;
   1120 
   1121 	LOCK_ASSERT(lwp_locked(l, NULL));
   1122 	LOCK_ASSERT(mutex_owned(&sched_mutex));
   1123 
   1124 #ifdef RQDEBUG
   1125 	checkrunqueue(whichq, NULL);
   1126 #endif
   1127 #ifdef DIAGNOSTIC
   1128 	if (l->l_back != NULL || l->l_stat != LSRUN)
   1129 		panic("setrunqueue");
   1130 #endif
   1131 	sched_whichqs |= RQMASK(whichq);
   1132 	rq = &sched_qs[whichq];
   1133 	prev = rq->ph_rlink;
   1134 	l->l_forw = (struct lwp *)rq;
   1135 	rq->ph_rlink = l;
   1136 	prev->l_forw = l;
   1137 	l->l_back = prev;
   1138 #ifdef RQDEBUG
   1139 	checkrunqueue(whichq, l);
   1140 #endif
   1141 }
   1142 
   1143 void
   1144 remrunqueue(struct lwp *l)
   1145 {
   1146 	struct lwp *prev, *next;
   1147 	const int whichq = l->l_priority / PPQ;
   1148 
   1149 	LOCK_ASSERT(lwp_locked(l, &sched_mutex));
   1150 
   1151 #ifdef RQDEBUG
   1152 	checkrunqueue(whichq, l);
   1153 #endif
   1154 
   1155 #if defined(DIAGNOSTIC)
   1156 	if (((sched_whichqs & RQMASK(whichq)) == 0) || l->l_back == NULL) {
   1157 		/* Shouldn't happen - interrupts disabled. */
   1158 		panic("remrunqueue: bit %d not set", whichq);
   1159 	}
   1160 #endif
   1161 	prev = l->l_back;
   1162 	l->l_back = NULL;
   1163 	next = l->l_forw;
   1164 	prev->l_forw = next;
   1165 	next->l_back = prev;
   1166 	if (prev == next)
   1167 		sched_whichqs &= ~RQMASK(whichq);
   1168 #ifdef RQDEBUG
   1169 	checkrunqueue(whichq, NULL);
   1170 #endif
   1171 }
   1172 
   1173 #undef RQMASK
   1174 #endif /* !defined(__HAVE_MD_RUNQUEUE) */
   1175