Home | History | Annotate | Line # | Download | only in kern
sched_4bsd.c revision 1.1.2.8
      1 /*	$NetBSD: sched_4bsd.c,v 1.1.2.8 2007/02/27 16:54:26 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.8 2007/02/27 16:54:26 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/kauth.h>
     96 #include <sys/lockdebug.h>
     97 
     98 #include <uvm/uvm_extern.h>
     99 
    100 /*
    101  * Run queues.
    102  *
    103  * We have 32 run queues in descending priority of 0..31.  We maintain
    104  * a bitmask of non-empty queues in order speed up finding the first
    105  * runnable process.  The bitmask is maintained only by machine-dependent
    106  * code, allowing the most efficient instructions to be used to find the
    107  * first non-empty queue.
    108  */
    109 
    110 
    111 #define	RUNQUE_NQS		32      /* number of runqueues */
    112 #define	PPQ	(128 / RUNQUE_NQS)	/* priorities per queue */
    113 
    114 struct prochd {
    115 	struct lwp *ph_link;
    116 	struct lwp *ph_rlink;
    117 };
    118 
    119 struct prochd sched_qs[RUNQUE_NQS];	/* run queues */
    120 volatile uint32_t sched_whichqs;	/* bitmap of non-empty queues */
    121 
    122 void schedcpu(void *);
    123 void updatepri(struct lwp *);
    124 void resetpriority(struct lwp *);
    125 void resetprocpriority(struct proc *);
    126 
    127 struct callout schedcpu_ch = CALLOUT_INITIALIZER_SETFUNC(schedcpu, NULL);
    128 static unsigned int schedcpu_ticks;
    129 
    130 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 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 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  * Initialize the (doubly-linked) run queues
    433  * to be empty.
    434  */
    435 void
    436 sched_rqinit()
    437 {
    438 	int i;
    439 
    440 	for (i = 0; i < RUNQUE_NQS; i++)
    441 		sched_qs[i].ph_link = sched_qs[i].ph_rlink =
    442 		    (struct lwp *)&sched_qs[i];
    443 
    444 	mutex_init(&sched_mutex, MUTEX_SPIN, IPL_SCHED);
    445 }
    446 
    447 void
    448 sched_setup()
    449 {
    450 	rrticks = hz / 10;
    451 
    452 	schedcpu(NULL);
    453 }
    454 
    455 void
    456 sched_setrunnable(struct lwp *l)
    457 {
    458  	if (l->l_slptime > 1)
    459  		updatepri(l);
    460 }
    461 
    462 boolean_t
    463 sched_curcpu_runnable_p(void)
    464 {
    465 
    466 	return sched_whichqs != 0;
    467 }
    468 
    469 void
    470 sched_nice(struct proc *chgp, int n)
    471 {
    472 	chgp->p_nice = n;
    473 	(void)resetprocpriority(chgp);
    474 }
    475 
    476 /*
    477  * Compute the priority of a process when running in user mode.
    478  * Arrange to reschedule if the resulting priority is better
    479  * than that of the current process.
    480  */
    481 void
    482 resetpriority(struct lwp *l)
    483 {
    484 	unsigned int newpriority;
    485 	struct proc *p = l->l_proc;
    486 
    487 	/* XXXSMP LOCK_ASSERT(mutex_owned(&p->p_stmutex)); */
    488 	LOCK_ASSERT(lwp_locked(l, NULL));
    489 
    490 	if ((l->l_flag & LW_SYSTEM) != 0)
    491 		return;
    492 
    493 	newpriority = PUSER + (p->p_estcpu >> ESTCPU_SHIFT) +
    494 	    NICE_WEIGHT * (p->p_nice - NZERO);
    495 	newpriority = min(newpriority, MAXPRI);
    496 	lwp_changepri(l, newpriority);
    497 }
    498 
    499 /*
    500  * Recompute priority for all LWPs in a process.
    501  */
    502 void
    503 resetprocpriority(struct proc *p)
    504 {
    505 	struct lwp *l;
    506 
    507 	LOCK_ASSERT(mutex_owned(&p->p_stmutex));
    508 
    509 	LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    510 		lwp_lock(l);
    511 		resetpriority(l);
    512 		lwp_unlock(l);
    513 	}
    514 }
    515 
    516 /*
    517  * We adjust the priority of the current process.  The priority of a process
    518  * gets worse as it accumulates CPU time.  The CPU usage estimator (p_estcpu)
    519  * is increased here.  The formula for computing priorities (in kern_synch.c)
    520  * will compute a different value each time p_estcpu increases. This can
    521  * cause a switch, but unless the priority crosses a PPQ boundary the actual
    522  * queue will not change.  The CPU usage estimator ramps up quite quickly
    523  * when the process is running (linearly), and decays away exponentially, at
    524  * a rate which is proportionally slower when the system is busy.  The basic
    525  * principle is that the system will 90% forget that the process used a lot
    526  * of CPU time in 5 * loadav seconds.  This causes the system to favor
    527  * processes which haven't run much recently, and to round-robin among other
    528  * processes.
    529  */
    530 
    531 void
    532 sched_clock(struct lwp *l)
    533 {
    534 	struct proc *p = l->l_proc;
    535 
    536 	KASSERT(!CURCPU_IDLE_P());
    537 	mutex_spin_enter(&p->p_stmutex);
    538 	p->p_estcpu = ESTCPULIM(p->p_estcpu + (1 << ESTCPU_SHIFT));
    539 	lwp_lock(l);
    540 	resetpriority(l);
    541 	mutex_spin_exit(&p->p_stmutex);
    542 	if ((l->l_flag & LW_SYSTEM) == 0 && l->l_priority >= PUSER)
    543 		l->l_priority = l->l_usrpri;
    544 	lwp_unlock(l);
    545 }
    546 
    547 /*
    548  * scheduler_fork_hook:
    549  *
    550  *	Inherit the parent's scheduler history.
    551  */
    552 void
    553 sched_proc_fork(struct proc *parent, struct proc *child)
    554 {
    555 
    556 	LOCK_ASSERT(mutex_owned(&parent->p_smutex));
    557 
    558 	child->p_estcpu = child->p_estcpu_inherited = parent->p_estcpu;
    559 	child->p_forktime = schedcpu_ticks;
    560 }
    561 
    562 /*
    563  * scheduler_wait_hook:
    564  *
    565  *	Chargeback parents for the sins of their children.
    566  */
    567 void
    568 sched_proc_exit(struct proc *parent, struct proc *child)
    569 {
    570 	fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
    571 	fixpt_t estcpu;
    572 
    573 	/* XXX Only if parent != init?? */
    574 
    575 	mutex_spin_enter(&parent->p_stmutex);
    576 	estcpu = decay_cpu_batch(loadfac, child->p_estcpu_inherited,
    577 	    schedcpu_ticks - child->p_forktime);
    578 	if (child->p_estcpu > estcpu)
    579 		parent->p_estcpu =
    580 		    ESTCPULIM(parent->p_estcpu + child->p_estcpu - estcpu);
    581 	mutex_spin_exit(&parent->p_stmutex);
    582 }
    583 
    584 /*
    585  * On some architectures, it's faster to use a MSB ordering for the priorites
    586  * than the traditional LSB ordering.
    587  */
    588 #ifdef __HAVE_BIGENDIAN_BITOPS
    589 #define	RQMASK(n) (0x80000000 >> (n))
    590 #else
    591 #define	RQMASK(n) (0x00000001 << (n))
    592 #endif
    593 
    594 /*
    595  * Low-level routines to access the run queue.  Optimised assembler
    596  * routines can override these.
    597  */
    598 
    599 #ifndef __HAVE_MD_RUNQUEUE
    600 
    601 /*
    602  * The primitives that manipulate the run queues.  whichqs tells which
    603  * of the 32 queues qs have processes in them.  sched_enqueue puts processes
    604  * into queues, sched_dequeue removes them from queues.  The running process is
    605  * on no queue, other processes are on a queue related to p->p_priority,
    606  * divided by 4 actually to shrink the 0-127 range of priorities into the 32
    607  * available queues.
    608  */
    609 #ifdef RQDEBUG
    610 static void
    611 checkrunqueue(int whichq, struct lwp *l)
    612 {
    613 	const struct prochd * const rq = &sched_qs[whichq];
    614 	struct lwp *l2;
    615 	int found = 0;
    616 	int die = 0;
    617 	int empty = 1;
    618 	for (l2 = rq->ph_link; l2 != (const void*) rq; l2 = l2->l_forw) {
    619 		if (l2->l_stat != LSRUN) {
    620 			printf("checkrunqueue[%d]: lwp %p state (%d) "
    621 			    " != LSRUN\n", whichq, l2, l2->l_stat);
    622 		}
    623 		if (l2->l_back->l_forw != l2) {
    624 			printf("checkrunqueue[%d]: lwp %p back-qptr (%p) "
    625 			    "corrupt %p\n", whichq, l2, l2->l_back,
    626 			    l2->l_back->l_forw);
    627 			die = 1;
    628 		}
    629 		if (l2->l_forw->l_back != l2) {
    630 			printf("checkrunqueue[%d]: lwp %p forw-qptr (%p) "
    631 			    "corrupt %p\n", whichq, l2, l2->l_forw,
    632 			    l2->l_forw->l_back);
    633 			die = 1;
    634 		}
    635 		if (l2 == l)
    636 			found = 1;
    637 		empty = 0;
    638 	}
    639 	if (empty && (sched_whichqs & RQMASK(whichq)) != 0) {
    640 		printf("checkrunqueue[%d]: bit set for empty run-queue %p\n",
    641 		    whichq, rq);
    642 		die = 1;
    643 	} else if (!empty && (sched_whichqs & RQMASK(whichq)) == 0) {
    644 		printf("checkrunqueue[%d]: bit clear for non-empty "
    645 		    "run-queue %p\n", whichq, rq);
    646 		die = 1;
    647 	}
    648 	if (l != NULL && (sched_whichqs & RQMASK(whichq)) == 0) {
    649 		printf("checkrunqueue[%d]: bit clear for active lwp %p\n",
    650 		    whichq, l);
    651 		die = 1;
    652 	}
    653 	if (l != NULL && empty) {
    654 		printf("checkrunqueue[%d]: empty run-queue %p with "
    655 		    "active lwp %p\n", whichq, rq, l);
    656 		die = 1;
    657 	}
    658 	if (l != NULL && !found) {
    659 		printf("checkrunqueue[%d]: lwp %p not in runqueue %p!",
    660 		    whichq, l, rq);
    661 		die = 1;
    662 	}
    663 	if (die)
    664 		panic("checkrunqueue: inconsistency found");
    665 }
    666 #endif /* RQDEBUG */
    667 
    668 void
    669 sched_enqueue(struct lwp *l)
    670 {
    671 	struct prochd*rq;
    672 	struct lwp *prev;
    673 	const int whichq = lwp_eprio(l) / PPQ;
    674 
    675 	LOCK_ASSERT(lwp_locked(l, &sched_mutex));
    676 
    677 #ifdef RQDEBUG
    678 	checkrunqueue(whichq, NULL);
    679 #endif
    680 #ifdef DIAGNOSTIC
    681 	if (l->l_back != NULL || l->l_stat != LSRUN)
    682 		panic("sched_enqueue");
    683 #endif
    684 	sched_whichqs |= RQMASK(whichq);
    685 	rq = &sched_qs[whichq];
    686 	prev = rq->ph_rlink;
    687 	l->l_forw = (struct lwp *)rq;
    688 	rq->ph_rlink = l;
    689 	prev->l_forw = l;
    690 	l->l_back = prev;
    691 #ifdef RQDEBUG
    692 	checkrunqueue(whichq, l);
    693 #endif
    694 }
    695 
    696 /*
    697  * XXXSMP When LWP dispatch (cpu_switch()) is changed to use sched_dequeue(),
    698  * drop of the effective priority level from kernel to user needs to be
    699  * moved here from userret().  The assignment in userret() is currently
    700  * done unlocked.
    701  */
    702 void
    703 sched_dequeue(struct lwp *l)
    704 {
    705 	struct lwp *prev, *next;
    706 	const int whichq = lwp_eprio(l) / PPQ;
    707 
    708 	LOCK_ASSERT(lwp_locked(l, &sched_mutex));
    709 
    710 #ifdef RQDEBUG
    711 	checkrunqueue(whichq, l);
    712 #endif
    713 
    714 #if defined(DIAGNOSTIC)
    715 	if (((sched_whichqs & RQMASK(whichq)) == 0) || l->l_back == NULL) {
    716 		/* Shouldn't happen - interrupts disabled. */
    717 		panic("sched_dequeue: bit %d not set", whichq);
    718 	}
    719 #endif
    720 	prev = l->l_back;
    721 	l->l_back = NULL;
    722 	next = l->l_forw;
    723 	prev->l_forw = next;
    724 	next->l_back = prev;
    725 	if (prev == next)
    726 		sched_whichqs &= ~RQMASK(whichq);
    727 #ifdef RQDEBUG
    728 	checkrunqueue(whichq, NULL);
    729 #endif
    730 }
    731 
    732 struct lwp *
    733 sched_nextlwp(void)
    734 {
    735 	const struct prochd *rq;
    736 	struct lwp *l;
    737 	int whichq;
    738 
    739 	if (sched_whichqs == 0) {
    740 		return NULL;
    741 	}
    742 #ifdef __HAVE_BIGENDIAN_BITOPS
    743 	for (whichq = 0; ; whichq++) {
    744 		if ((sched_whichqs & RQMASK(whichq)) != 0) {
    745 			break;
    746 		}
    747 	}
    748 #else
    749 	whichq = ffs(sched_whichqs) - 1;
    750 #endif
    751 	rq = &sched_qs[whichq];
    752 	l = rq->ph_link;
    753 	return l;
    754 }
    755 
    756 #endif /* !defined(__HAVE_MD_RUNQUEUE) */
    757 
    758 #if defined(DDB)
    759 void
    760 sched_print_runqueue(void (*pr)(const char *, ...))
    761 {
    762 	struct prochd *ph;
    763 	struct lwp *l;
    764 	int i, first;
    765 
    766 	for (i = 0; i < RUNQUE_NQS; i++)
    767 	{
    768 		first = 1;
    769 		ph = &sched_qs[i];
    770 		for (l = ph->ph_link; l != (void *)ph; l = l->l_forw) {
    771 			if (first) {
    772 				(*pr)("%c%d",
    773 				    (sched_whichqs & RQMASK(i))
    774 				    ? ' ' : '!', i);
    775 				first = 0;
    776 			}
    777 			(*pr)("\t%d.%d (%s) pri=%d usrpri=%d\n",
    778 			    l->l_proc->p_pid,
    779 			    l->l_lid, l->l_proc->p_comm,
    780 			    (int)l->l_priority, (int)l->l_usrpri);
    781 		}
    782 	}
    783 }
    784 #endif /* defined(DDB) */
    785 #undef RQMASK
    786