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