Home | History | Annotate | Line # | Download | only in kern
sched_4bsd.c revision 1.1.2.18
      1 /*	$NetBSD: sched_4bsd.c,v 1.1.2.18 2007/03/23 17:20:24 yamt Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999, 2000, 2004, 2006, 2007 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
      9  * NASA Ames Research Center, by Charles M. Hannum, Andrew Doran, and
     10  * Daniel Sieger.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. All advertising materials mentioning features or use of this software
     21  *    must display the following acknowledgement:
     22  *	This product includes software developed by the NetBSD
     23  *	Foundation, Inc. and its contributors.
     24  * 4. Neither the name of The NetBSD Foundation nor the names of its
     25  *    contributors may be used to endorse or promote products derived
     26  *    from this software without specific prior written permission.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     29  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     30  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     31  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     32  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     34  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     36  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     37  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     38  * POSSIBILITY OF SUCH DAMAGE.
     39  */
     40 
     41 /*-
     42  * Copyright (c) 1982, 1986, 1990, 1991, 1993
     43  *	The Regents of the University of California.  All rights reserved.
     44  * (c) UNIX System Laboratories, Inc.
     45  * All or some portions of this file are derived from material licensed
     46  * to the University of California by American Telephone and Telegraph
     47  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     48  * the permission of UNIX System Laboratories, Inc.
     49  *
     50  * Redistribution and use in source and binary forms, with or without
     51  * modification, are permitted provided that the following conditions
     52  * are met:
     53  * 1. Redistributions of source code must retain the above copyright
     54  *    notice, this list of conditions and the following disclaimer.
     55  * 2. Redistributions in binary form must reproduce the above copyright
     56  *    notice, this list of conditions and the following disclaimer in the
     57  *    documentation and/or other materials provided with the distribution.
     58  * 3. Neither the name of the University nor the names of its contributors
     59  *    may be used to endorse or promote products derived from this software
     60  *    without specific prior written permission.
     61  *
     62  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     63  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     64  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     65  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     66  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     67  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     68  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     69  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     70  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     71  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     72  * SUCH DAMAGE.
     73  *
     74  *	@(#)kern_synch.c	8.9 (Berkeley) 5/19/95
     75  */
     76 
     77 #include <sys/cdefs.h>
     78 __KERNEL_RCSID(0, "$NetBSD: sched_4bsd.c,v 1.1.2.18 2007/03/23 17:20:24 yamt Exp $");
     79 
     80 #include "opt_ddb.h"
     81 #include "opt_lockdebug.h"
     82 #include "opt_perfctrs.h"
     83 
     84 #define	__MUTEX_PRIVATE
     85 
     86 #include <sys/param.h>
     87 #include <sys/systm.h>
     88 #include <sys/callout.h>
     89 #include <sys/cpu.h>
     90 #include <sys/proc.h>
     91 #include <sys/kernel.h>
     92 #include <sys/signalvar.h>
     93 #include <sys/resourcevar.h>
     94 #include <sys/sched.h>
     95 #include <sys/sysctl.h>
     96 #include <sys/kauth.h>
     97 #include <sys/lockdebug.h>
     98 
     99 #include <uvm/uvm_extern.h>
    100 
    101 /*
    102  * Run queues.
    103  *
    104  * We have 32 run queues in descending priority of 0..31.  We maintain
    105  * a bitmask of non-empty queues in order speed up finding the first
    106  * runnable process.  The bitmask is maintained only by machine-dependent
    107  * code, allowing the most efficient instructions to be used to find the
    108  * first non-empty queue.
    109  */
    110 
    111 #define	RUNQUE_NQS		32      /* number of runqueues */
    112 #define	PPQ	(128 / RUNQUE_NQS)	/* priorities per queue */
    113 
    114 typedef struct subqueue {
    115 	TAILQ_HEAD(, lwp) sq_queue;
    116 } subqueue_t;
    117 typedef struct runqueue {
    118 	subqueue_t rq_subqueues[RUNQUE_NQS];	/* run queues */
    119 	uint32_t rq_bitmap;	/* bitmap of non-empty queues */
    120 } runqueue_t;
    121 static runqueue_t global_queue;
    122 
    123 static void schedcpu(void *);
    124 static void updatepri(struct lwp *);
    125 static void resetpriority(struct lwp *);
    126 static void resetprocpriority(struct proc *);
    127 
    128 struct callout schedcpu_ch = CALLOUT_INITIALIZER_SETFUNC(schedcpu, NULL);
    129 static unsigned int schedcpu_ticks;
    130 static int rrticks; /* number of hardclock ticks per sched_tick() */
    131 
    132 /*
    133  * Force switch among equal priority processes every 100ms.
    134  * Called from hardclock every hz/10 == rrticks hardclock ticks.
    135  */
    136 /* ARGSUSED */
    137 void
    138 sched_tick(struct cpu_info *ci)
    139 {
    140 	struct schedstate_percpu *spc = &ci->ci_schedstate;
    141 
    142 	spc->spc_ticks = rrticks;
    143 
    144 	if (!CURCPU_IDLE_P()) {
    145 		if (spc->spc_flags & SPCF_SEENRR) {
    146 			/*
    147 			 * The process has already been through a roundrobin
    148 			 * without switching and may be hogging the CPU.
    149 			 * Indicate that the process should yield.
    150 			 */
    151 			spc->spc_flags |= SPCF_SHOULDYIELD;
    152 		} else
    153 			spc->spc_flags |= SPCF_SEENRR;
    154 	}
    155 	cpu_need_resched(curcpu(), 0);
    156 }
    157 
    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  * schedcpu:
    292  *
    293  *	Recompute process priorities, every hz ticks.
    294  *
    295  *	XXXSMP This needs to be reorganised in order to reduce the locking
    296  *	burden.
    297  */
    298 /* ARGSUSED */
    299 static void
    300 schedcpu(void *arg)
    301 {
    302 	fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
    303 	struct rlimit *rlim;
    304 	struct lwp *l;
    305 	struct proc *p;
    306 	int minslp, clkhz, sig;
    307 	long runtm;
    308 
    309 	schedcpu_ticks++;
    310 
    311 	mutex_enter(&proclist_mutex);
    312 	PROCLIST_FOREACH(p, &allproc) {
    313 		/*
    314 		 * Increment time in/out of memory and sleep time (if
    315 		 * sleeping).  We ignore overflow; with 16-bit int's
    316 		 * (remember them?) overflow takes 45 days.
    317 		 */
    318 		minslp = 2;
    319 		mutex_enter(&p->p_smutex);
    320 		runtm = p->p_rtime.tv_sec;
    321 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    322 			if ((l->l_flag & LW_IDLE) != 0)
    323 				continue;
    324 			lwp_lock(l);
    325 			runtm += l->l_rtime.tv_sec;
    326 			l->l_swtime++;
    327 			if (l->l_stat == LSSLEEP || l->l_stat == LSSTOP ||
    328 			    l->l_stat == LSSUSPENDED) {
    329 				l->l_slptime++;
    330 				minslp = min(minslp, l->l_slptime);
    331 			} else
    332 				minslp = 0;
    333 			lwp_unlock(l);
    334 		}
    335 		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
    336 
    337 		/*
    338 		 * Check if the process exceeds its CPU resource allocation.
    339 		 * If over max, kill it.
    340 		 */
    341 		rlim = &p->p_rlimit[RLIMIT_CPU];
    342 		sig = 0;
    343 		if (runtm >= rlim->rlim_cur) {
    344 			if (runtm >= rlim->rlim_max)
    345 				sig = SIGKILL;
    346 			else {
    347 				sig = SIGXCPU;
    348 				if (rlim->rlim_cur < rlim->rlim_max)
    349 					rlim->rlim_cur += 5;
    350 			}
    351 		}
    352 
    353 		/*
    354 		 * If the process has run for more than autonicetime, reduce
    355 		 * priority to give others a chance.
    356 		 */
    357 		if (autonicetime && runtm > autonicetime && p->p_nice == NZERO
    358 		    && kauth_cred_geteuid(p->p_cred)) {
    359 			mutex_spin_enter(&p->p_stmutex);
    360 			p->p_nice = autoniceval + NZERO;
    361 			resetprocpriority(p);
    362 			mutex_spin_exit(&p->p_stmutex);
    363 		}
    364 
    365 		/*
    366 		 * If the process has slept the entire second,
    367 		 * stop recalculating its priority until it wakes up.
    368 		 */
    369 		if (minslp <= 1) {
    370 			/*
    371 			 * p_pctcpu is only for ps.
    372 			 */
    373 			mutex_spin_enter(&p->p_stmutex);
    374 			clkhz = stathz != 0 ? stathz : hz;
    375 #if	(FSHIFT >= CCPU_SHIFT)
    376 			p->p_pctcpu += (clkhz == 100)?
    377 			    ((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT):
    378 			    100 * (((fixpt_t) p->p_cpticks)
    379 			    << (FSHIFT - CCPU_SHIFT)) / clkhz;
    380 #else
    381 			p->p_pctcpu += ((FSCALE - ccpu) *
    382 			    (p->p_cpticks * FSCALE / clkhz)) >> FSHIFT;
    383 #endif
    384 			p->p_cpticks = 0;
    385 			p->p_estcpu = decay_cpu(loadfac, p->p_estcpu);
    386 
    387 			LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    388 				if ((l->l_flag & LW_IDLE) != 0)
    389 					continue;
    390 				lwp_lock(l);
    391 				if (l->l_slptime <= 1 &&
    392 				    l->l_priority >= PUSER)
    393 					resetpriority(l);
    394 				lwp_unlock(l);
    395 			}
    396 			mutex_spin_exit(&p->p_stmutex);
    397 		}
    398 
    399 		mutex_exit(&p->p_smutex);
    400 		if (sig) {
    401 			psignal(p, sig);
    402 		}
    403 	}
    404 	mutex_exit(&proclist_mutex);
    405 	uvm_meter();
    406 	wakeup((caddr_t)&lbolt);
    407 	callout_schedule(&schedcpu_ch, hz);
    408 }
    409 
    410 /*
    411  * Recalculate the priority of a process after it has slept for a while.
    412  */
    413 static void
    414 updatepri(struct lwp *l)
    415 {
    416 	struct proc *p = l->l_proc;
    417 	fixpt_t loadfac;
    418 
    419 	LOCK_ASSERT(lwp_locked(l, NULL));
    420 	KASSERT(l->l_slptime > 1);
    421 
    422 	loadfac = loadfactor(averunnable.ldavg[0]);
    423 
    424 	l->l_slptime--; /* the first time was done in schedcpu */
    425 	/* XXX NJWLWP */
    426 	/* XXXSMP occasionally unlocked, should be per-LWP */
    427 	p->p_estcpu = decay_cpu_batch(loadfac, p->p_estcpu, l->l_slptime);
    428 	resetpriority(l);
    429 }
    430 
    431 /*
    432  * On some architectures, it's faster to use a MSB ordering for the priorites
    433  * than the traditional LSB ordering.
    434  */
    435 #ifdef __HAVE_BIGENDIAN_BITOPS
    436 #define	RQMASK(n) (0x80000000 >> (n))
    437 #else
    438 #define	RQMASK(n) (0x00000001 << (n))
    439 #endif
    440 
    441 /*
    442  * The primitives that manipulate the run queues.  whichqs tells which
    443  * of the 32 queues qs have processes in them.  sched_enqueue() puts processes
    444  * into queues, sched_dequeue removes them from queues.  The running process is
    445  * on no queue, other processes are on a queue related to p->p_priority,
    446  * divided by 4 actually to shrink the 0-127 range of priorities into the 32
    447  * available queues.
    448  */
    449 #ifdef RQDEBUG
    450 static void
    451 runqueue_check(const runqueue_t *rq, int whichq, struct lwp *l)
    452 {
    453 	const subqueue_t * const sq = &rq->rq_subqueues[whichq];
    454 	const uint32_t bitmap = rq->rq_bitmap;
    455 	struct lwp *l2;
    456 	int found = 0;
    457 	int die = 0;
    458 	int empty = 1;
    459 
    460 	TAILQ_FOREACH(l2, &sq->sq_queue, l_runq) {
    461 		if (l2->l_stat != LSRUN) {
    462 			printf("runqueue_check[%d]: lwp %p state (%d) "
    463 			    " != LSRUN\n", whichq, l2, l2->l_stat);
    464 		}
    465 		if (l2 == l)
    466 			found = 1;
    467 		empty = 0;
    468 	}
    469 	if (empty && (bitmap & RQMASK(whichq)) != 0) {
    470 		printf("runqueue_check[%d]: bit set for empty run-queue %p\n",
    471 		    whichq, rq);
    472 		die = 1;
    473 	} else if (!empty && (bitmap & RQMASK(whichq)) == 0) {
    474 		printf("runqueue_check[%d]: bit clear for non-empty "
    475 		    "run-queue %p\n", whichq, rq);
    476 		die = 1;
    477 	}
    478 	if (l != NULL && (bitmap & RQMASK(whichq)) == 0) {
    479 		printf("runqueue_check[%d]: bit clear for active lwp %p\n",
    480 		    whichq, l);
    481 		die = 1;
    482 	}
    483 	if (l != NULL && empty) {
    484 		printf("runqueue_check[%d]: empty run-queue %p with "
    485 		    "active lwp %p\n", whichq, rq, l);
    486 		die = 1;
    487 	}
    488 	if (l != NULL && !found) {
    489 		printf("runqueue_check[%d]: lwp %p not in runqueue %p!",
    490 		    whichq, l, rq);
    491 		die = 1;
    492 	}
    493 	if (die)
    494 		panic("runqueue_check: inconsistency found");
    495 }
    496 #else /* RQDEBUG */
    497 #define	runqueue_check(a, b, c)	/* nothing */
    498 #endif /* RQDEBUG */
    499 
    500 static void
    501 runqueue_init(runqueue_t *rq)
    502 {
    503 	int i;
    504 
    505 	for (i = 0; i < RUNQUE_NQS; i++)
    506 		TAILQ_INIT(&rq->rq_subqueues[i].sq_queue);
    507 }
    508 
    509 static void
    510 runqueue_enqueue(runqueue_t *rq, struct lwp *l)
    511 {
    512 	subqueue_t *sq;
    513 	const int whichq = lwp_eprio(l) / PPQ;
    514 
    515 	LOCK_ASSERT(lwp_locked(l, &sched_mutex));
    516 
    517 	runqueue_check(rq, whichq, NULL);
    518 	rq->rq_bitmap |= RQMASK(whichq);
    519 	sq = &rq->rq_subqueues[whichq];
    520 	TAILQ_INSERT_TAIL(&sq->sq_queue, l, l_runq);
    521 	runqueue_check(rq, whichq, l);
    522 }
    523 
    524 static void
    525 runqueue_dequeue(runqueue_t *rq, struct lwp *l)
    526 {
    527 	subqueue_t *sq;
    528 	const int whichq = lwp_eprio(l) / PPQ;
    529 
    530 	LOCK_ASSERT(lwp_locked(l, &sched_mutex));
    531 
    532 	runqueue_check(rq, whichq, l);
    533 	KASSERT((rq->rq_bitmap & RQMASK(whichq)) != 0);
    534 	sq = &rq->rq_subqueues[whichq];
    535 	TAILQ_REMOVE(&sq->sq_queue, l, l_runq);
    536 	if (TAILQ_EMPTY(&sq->sq_queue))
    537 		rq->rq_bitmap &= ~RQMASK(whichq);
    538 	runqueue_check(rq, whichq, NULL);
    539 }
    540 
    541 static struct lwp *
    542 runqueue_nextlwp(runqueue_t *rq)
    543 {
    544 	const uint32_t bitmap = rq->rq_bitmap;
    545 	int whichq;
    546 
    547 	LOCK_ASSERT(lwp_locked(l, &sched_mutex));
    548 
    549 	if (bitmap == 0) {
    550 		return NULL;
    551 	}
    552 #ifdef __HAVE_BIGENDIAN_BITOPS
    553 	/* XXX should introduce a fast "fls" function. */
    554 	for (whichq = 0; ; whichq++) {
    555 		if ((bitmap & RQMASK(whichq)) != 0) {
    556 			break;
    557 		}
    558 	}
    559 #else
    560 	whichq = ffs(bitmap) - 1;
    561 #endif
    562 	return TAILQ_FIRST(&rq->rq_subqueues[whichq].sq_queue);
    563 }
    564 
    565 #if defined(DDB)
    566 static void
    567 runqueue_print(const runqueue_t *rq, void (*pr)(const char *, ...))
    568 {
    569 	const uint32_t bitmap = rq->rq_bitmap;
    570 	struct lwp *l;
    571 	int i, first;
    572 
    573 	for (i = 0; i < RUNQUE_NQS; i++) {
    574 		const subqueue_t *sq;
    575 		first = 1;
    576 		sq = &rq->rq_subqueues[i];
    577 		TAILQ_FOREACH(l, &sq->sq_queue, l_runq) {
    578 			if (first) {
    579 				(*pr)("%c%d",
    580 				    (bitmap & RQMASK(i)) ? ' ' : '!', i);
    581 				first = 0;
    582 			}
    583 			(*pr)("\t%d.%d (%s) pri=%d usrpri=%d\n",
    584 			    l->l_proc->p_pid,
    585 			    l->l_lid, l->l_proc->p_comm,
    586 			    (int)l->l_priority, (int)l->l_usrpri);
    587 		}
    588 	}
    589 }
    590 #endif /* defined(DDB) */
    591 #undef RQMASK
    592 
    593 /*
    594  * Initialize the (doubly-linked) run queues
    595  * to be empty.
    596  */
    597 void
    598 sched_rqinit()
    599 {
    600 
    601 	runqueue_init(&global_queue);
    602 	mutex_init(&sched_mutex, MUTEX_SPIN, IPL_SCHED);
    603 }
    604 
    605 void
    606 sched_setup()
    607 {
    608 
    609 	rrticks = hz / 10;
    610 	schedcpu(NULL);
    611 }
    612 
    613 void
    614 sched_setrunnable(struct lwp *l)
    615 {
    616 
    617  	if (l->l_slptime > 1)
    618  		updatepri(l);
    619 }
    620 
    621 bool
    622 sched_curcpu_runnable_p(void)
    623 {
    624 
    625 	return global_queue.rq_bitmap != 0;
    626 }
    627 
    628 void
    629 sched_nice(struct proc *chgp, int n)
    630 {
    631 
    632 	chgp->p_nice = n;
    633 	(void)resetprocpriority(chgp);
    634 }
    635 
    636 /*
    637  * Compute the priority of a process when running in user mode.
    638  * Arrange to reschedule if the resulting priority is better
    639  * than that of the current process.
    640  */
    641 static void
    642 resetpriority(struct lwp *l)
    643 {
    644 	unsigned int newpriority;
    645 	struct proc *p = l->l_proc;
    646 
    647 	/* XXXSMP LOCK_ASSERT(mutex_owned(&p->p_stmutex)); */
    648 	LOCK_ASSERT(lwp_locked(l, NULL));
    649 
    650 	if ((l->l_flag & LW_SYSTEM) != 0)
    651 		return;
    652 
    653 	newpriority = PUSER + (p->p_estcpu >> ESTCPU_SHIFT) +
    654 	    NICE_WEIGHT * (p->p_nice - NZERO);
    655 	newpriority = min(newpriority, MAXPRI);
    656 	lwp_changepri(l, newpriority);
    657 }
    658 
    659 /*
    660  * Recompute priority for all LWPs in a process.
    661  */
    662 static void
    663 resetprocpriority(struct proc *p)
    664 {
    665 	struct lwp *l;
    666 
    667 	LOCK_ASSERT(mutex_owned(&p->p_stmutex));
    668 
    669 	LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    670 		lwp_lock(l);
    671 		resetpriority(l);
    672 		lwp_unlock(l);
    673 	}
    674 }
    675 
    676 /*
    677  * We adjust the priority of the current process.  The priority of a process
    678  * gets worse as it accumulates CPU time.  The CPU usage estimator (p_estcpu)
    679  * is increased here.  The formula for computing priorities (in kern_synch.c)
    680  * will compute a different value each time p_estcpu increases. This can
    681  * cause a switch, but unless the priority crosses a PPQ boundary the actual
    682  * queue will not change.  The CPU usage estimator ramps up quite quickly
    683  * when the process is running (linearly), and decays away exponentially, at
    684  * a rate which is proportionally slower when the system is busy.  The basic
    685  * principle is that the system will 90% forget that the process used a lot
    686  * of CPU time in 5 * loadav seconds.  This causes the system to favor
    687  * processes which haven't run much recently, and to round-robin among other
    688  * processes.
    689  */
    690 
    691 void
    692 sched_schedclock(struct lwp *l)
    693 {
    694 	struct proc *p = l->l_proc;
    695 
    696 	KASSERT(!CURCPU_IDLE_P());
    697 	mutex_spin_enter(&p->p_stmutex);
    698 	p->p_estcpu = ESTCPULIM(p->p_estcpu + (1 << ESTCPU_SHIFT));
    699 	lwp_lock(l);
    700 	resetpriority(l);
    701 	mutex_spin_exit(&p->p_stmutex);
    702 	if ((l->l_flag & LW_SYSTEM) == 0 && l->l_priority >= PUSER)
    703 		l->l_priority = l->l_usrpri;
    704 	lwp_unlock(l);
    705 }
    706 
    707 /*
    708  * scheduler_fork_hook:
    709  *
    710  *	Inherit the parent's scheduler history.
    711  */
    712 void
    713 sched_proc_fork(struct proc *parent, struct proc *child)
    714 {
    715 
    716 	LOCK_ASSERT(mutex_owned(&parent->p_smutex));
    717 
    718 	child->p_estcpu = child->p_estcpu_inherited = parent->p_estcpu;
    719 	child->p_forktime = schedcpu_ticks;
    720 }
    721 
    722 /*
    723  * scheduler_wait_hook:
    724  *
    725  *	Chargeback parents for the sins of their children.
    726  */
    727 void
    728 sched_proc_exit(struct proc *parent, struct proc *child)
    729 {
    730 	fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
    731 	fixpt_t estcpu;
    732 
    733 	/* XXX Only if parent != init?? */
    734 
    735 	mutex_spin_enter(&parent->p_stmutex);
    736 	estcpu = decay_cpu_batch(loadfac, child->p_estcpu_inherited,
    737 	    schedcpu_ticks - child->p_forktime);
    738 	if (child->p_estcpu > estcpu)
    739 		parent->p_estcpu =
    740 		    ESTCPULIM(parent->p_estcpu + child->p_estcpu - estcpu);
    741 	mutex_spin_exit(&parent->p_stmutex);
    742 }
    743 
    744 void
    745 sched_enqueue(struct lwp *l, bool ctxswitch)
    746 {
    747 
    748 	runqueue_enqueue(&global_queue, l);
    749 }
    750 
    751 /*
    752  * XXXSMP When LWP dispatch (cpu_switch()) is changed to use sched_dequeue(),
    753  * drop of the effective priority level from kernel to user needs to be
    754  * moved here from userret().  The assignment in userret() is currently
    755  * done unlocked.
    756  */
    757 void
    758 sched_dequeue(struct lwp *l)
    759 {
    760 
    761 	runqueue_dequeue(&global_queue, l);
    762 }
    763 
    764 struct lwp *
    765 sched_nextlwp(struct lwp *l)
    766 {
    767 
    768 	return runqueue_nextlwp(&global_queue);
    769 }
    770 
    771 /* Dummy */
    772 void
    773 sched_lwp_fork(struct lwp *l)
    774 {
    775 
    776 }
    777 
    778 void
    779 sched_lwp_exit(struct lwp *l)
    780 {
    781 
    782 }
    783 
    784 void
    785 sched_slept(struct lwp *l)
    786 {
    787 
    788 }
    789 
    790 /* SysCtl */
    791 
    792 SYSCTL_SETUP(sysctl_sched_setup, "sysctl kern.sched subtree setup")
    793 {
    794 
    795 	sysctl_createv(clog, 0, NULL, NULL,
    796 		CTLFLAG_PERMANENT,
    797 		CTLTYPE_NODE, "kern", NULL,
    798 		NULL, 0, NULL, 0,
    799 		CTL_KERN, CTL_EOL);
    800 	sysctl_createv(clog, 0, NULL, NULL,
    801 		CTLFLAG_PERMANENT,
    802 		CTLTYPE_NODE, "sched",
    803 		SYSCTL_DESCR("Scheduler options"),
    804 		NULL, 0, NULL, 0,
    805 		CTL_KERN, KERN_SCHED, CTL_EOL);
    806 	sysctl_createv(clog, 0, NULL, NULL,
    807 		CTLFLAG_PERMANENT,
    808 		CTLTYPE_STRING, "name", NULL,
    809 		NULL, 0, __UNCONST("4.4BSD"), 0,
    810 		CTL_KERN, KERN_SCHED, CTL_CREATE, CTL_EOL);
    811 	sysctl_createv(clog, 0, NULL, NULL,
    812 		CTLFLAG_PERMANENT,
    813 		CTLTYPE_INT, "ccpu",
    814 		SYSCTL_DESCR("Scheduler exponential decay value"),
    815 		NULL, 0, &ccpu, 0,
    816 		CTL_KERN, KERN_SCHED, CTL_CREATE, CTL_EOL);
    817 }
    818 
    819 #if defined(DDB)
    820 void
    821 sched_print_runqueue(void (*pr)(const char *, ...))
    822 {
    823 
    824 	runqueue_print(&global_queue, pr);
    825 }
    826 #endif /* defined(DDB) */
    827