Home | History | Annotate | Line # | Download | only in kern
sched_4bsd.c revision 1.1.6.8
      1 /*	$NetBSD: sched_4bsd.c,v 1.1.6.8 2007/08/26 12:04:47 ad 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.6.8 2007/08/26 12:04:47 ad 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 #include <sys/kmem.h>
     99 #include <sys/intr.h>
    100 
    101 #include <uvm/uvm_extern.h>
    102 
    103 /*
    104  * Run queues.
    105  *
    106  * We maintain a bitmask of non-empty queues in order speed up finding
    107  * the first runnable process.
    108  */
    109 
    110 #define	PPQ		4			/* priorities per queue */
    111 #define	RUNQUE_NQS	(PRI_COUNT / PPQ)	/* number of runqueues */
    112 
    113 typedef struct subqueue {
    114 	TAILQ_HEAD(, lwp) sq_queue;
    115 } subqueue_t;
    116 
    117 typedef struct runqueue {
    118 	subqueue_t	rq_subqueues[RUNQUE_NQS];	/* run queues */
    119 	uint64_t	rq_bitmap;	/* bitmap of non-empty queues */
    120 } runqueue_t;
    121 
    122 static runqueue_t global_queue;
    123 
    124 static void updatepri(struct lwp *);
    125 static void resetpriority(struct lwp *);
    126 static void resetprocpriority(struct proc *);
    127 
    128 extern unsigned int sched_pstats_ticks; /* defined in kern_synch.c */
    129 
    130 /* The global scheduler state */
    131 kmutex_t sched_mutex;
    132 
    133 /* Number of hardclock ticks per sched_tick() */
    134 int rrticks;
    135 
    136 const int schedppq = PPQ;
    137 
    138 /*
    139  * Force switch among equal priority processes every 100ms.
    140  * Called from hardclock every hz/10 == rrticks hardclock ticks.
    141  *
    142  * There's no need to lock anywhere in this routine, as it's
    143  * CPU-local and runs at IPL_SCHED (called from clock interrupt).
    144  */
    145 /* ARGSUSED */
    146 void
    147 sched_tick(struct cpu_info *ci)
    148 {
    149 	struct schedstate_percpu *spc = &ci->ci_schedstate;
    150 
    151 	spc->spc_ticks = rrticks;
    152 
    153 	if (!CURCPU_IDLE_P()) {
    154 		if (spc->spc_flags & SPCF_SEENRR) {
    155 			/*
    156 			 * The process has already been through a roundrobin
    157 			 * without switching and may be hogging the CPU.
    158 			 * Indicate that the process should yield.
    159 			 */
    160 			spc->spc_flags |= SPCF_SHOULDYIELD;
    161 		} else
    162 			spc->spc_flags |= SPCF_SEENRR;
    163 	}
    164 	cpu_need_resched(ci, 0);
    165 }
    166 
    167 #define	NICE_WEIGHT 	1			/* priorities per nice level */
    168 
    169 #define	ESTCPU_SHIFT	11
    170 #define	ESTCPU_MAX	((NICE_WEIGHT * PRIO_MAX - PPQ) << ESTCPU_SHIFT)
    171 #define	ESTCPULIM(e)	min((e), ESTCPU_MAX)
    172 
    173 /*
    174  * Constants for digital decay and forget:
    175  *	90% of (p_estcpu) usage in 5 * loadav time
    176  *	95% of (p_pctcpu) usage in 60 seconds (load insensitive)
    177  *          Note that, as ps(1) mentions, this can let percentages
    178  *          total over 100% (I've seen 137.9% for 3 processes).
    179  *
    180  * Note that hardclock updates p_estcpu and p_cpticks independently.
    181  *
    182  * We wish to decay away 90% of p_estcpu in (5 * loadavg) seconds.
    183  * That is, the system wants to compute a value of decay such
    184  * that the following for loop:
    185  * 	for (i = 0; i < (5 * loadavg); i++)
    186  * 		p_estcpu *= decay;
    187  * will compute
    188  * 	p_estcpu *= 0.1;
    189  * for all values of loadavg:
    190  *
    191  * Mathematically this loop can be expressed by saying:
    192  * 	decay ** (5 * loadavg) ~= .1
    193  *
    194  * The system computes decay as:
    195  * 	decay = (2 * loadavg) / (2 * loadavg + 1)
    196  *
    197  * We wish to prove that the system's computation of decay
    198  * will always fulfill the equation:
    199  * 	decay ** (5 * loadavg) ~= .1
    200  *
    201  * If we compute b as:
    202  * 	b = 2 * loadavg
    203  * then
    204  * 	decay = b / (b + 1)
    205  *
    206  * We now need to prove two things:
    207  *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
    208  *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
    209  *
    210  * Facts:
    211  *         For x close to zero, exp(x) =~ 1 + x, since
    212  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
    213  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
    214  *         For x close to zero, ln(1+x) =~ x, since
    215  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
    216  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
    217  *         ln(.1) =~ -2.30
    218  *
    219  * Proof of (1):
    220  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
    221  *	solving for factor,
    222  *      ln(factor) =~ (-2.30/5*loadav), or
    223  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
    224  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
    225  *
    226  * Proof of (2):
    227  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
    228  *	solving for power,
    229  *      power*ln(b/(b+1)) =~ -2.30, or
    230  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
    231  *
    232  * Actual power values for the implemented algorithm are as follows:
    233  *      loadav: 1       2       3       4
    234  *      power:  5.68    10.32   14.94   19.55
    235  */
    236 
    237 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
    238 #define	loadfactor(loadav)	(2 * (loadav))
    239 
    240 static fixpt_t
    241 decay_cpu(fixpt_t loadfac, fixpt_t estcpu)
    242 {
    243 
    244 	if (estcpu == 0) {
    245 		return 0;
    246 	}
    247 
    248 #if !defined(_LP64)
    249 	/* avoid 64bit arithmetics. */
    250 #define	FIXPT_MAX ((fixpt_t)((UINTMAX_C(1) << sizeof(fixpt_t) * CHAR_BIT) - 1))
    251 	if (__predict_true(loadfac <= FIXPT_MAX / ESTCPU_MAX)) {
    252 		return estcpu * loadfac / (loadfac + FSCALE);
    253 	}
    254 #endif /* !defined(_LP64) */
    255 
    256 	return (uint64_t)estcpu * loadfac / (loadfac + FSCALE);
    257 }
    258 
    259 /*
    260  * For all load averages >= 1 and max p_estcpu of (255 << ESTCPU_SHIFT),
    261  * sleeping for at least seven times the loadfactor will decay p_estcpu to
    262  * less than (1 << ESTCPU_SHIFT).
    263  *
    264  * note that our ESTCPU_MAX is actually much smaller than (255 << ESTCPU_SHIFT).
    265  */
    266 static fixpt_t
    267 decay_cpu_batch(fixpt_t loadfac, fixpt_t estcpu, unsigned int n)
    268 {
    269 
    270 	if ((n << FSHIFT) >= 7 * loadfac) {
    271 		return 0;
    272 	}
    273 
    274 	while (estcpu != 0 && n > 1) {
    275 		estcpu = decay_cpu(loadfac, estcpu);
    276 		n--;
    277 	}
    278 
    279 	return estcpu;
    280 }
    281 
    282 /*
    283  * sched_pstats_hook:
    284  *
    285  * Periodically called from sched_pstats(); used to recalculate priorities.
    286  */
    287 void
    288 sched_pstats_hook(struct proc *p, int minslp)
    289 {
    290 	struct lwp *l;
    291 	fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
    292 
    293 	/*
    294 	 * If the process has slept the entire second,
    295 	 * stop recalculating its priority until it wakes up.
    296 	 */
    297 	if (minslp <= 1) {
    298 		p->p_estcpu = decay_cpu(loadfac, p->p_estcpu);
    299 
    300 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    301 			if ((l->l_flag & LW_IDLE) != 0)
    302 				continue;
    303 			lwp_lock(l);
    304 			if (l->l_slptime <= 1 && l->l_priority < PRI_KERNEL)
    305 				resetpriority(l);
    306 			lwp_unlock(l);
    307 		}
    308 	}
    309 }
    310 
    311 /*
    312  * Recalculate the priority of a process after it has slept for a while.
    313  */
    314 static void
    315 updatepri(struct lwp *l)
    316 {
    317 	struct proc *p = l->l_proc;
    318 	fixpt_t loadfac;
    319 
    320 	KASSERT(lwp_locked(l, NULL));
    321 	KASSERT(l->l_slptime > 1);
    322 
    323 	loadfac = loadfactor(averunnable.ldavg[0]);
    324 
    325 	l->l_slptime--; /* the first time was done in sched_pstats */
    326 	/* XXX NJWLWP */
    327 	/* XXXSMP occasionally unlocked, should be per-LWP */
    328 	p->p_estcpu = decay_cpu_batch(loadfac, p->p_estcpu, l->l_slptime);
    329 	resetpriority(l);
    330 }
    331 
    332 /*
    333  * On some architectures, it's faster to use a MSB ordering for the priorites
    334  * than the traditional LSB ordering.
    335  */
    336 #define	RQMASK(n)	(1ULL << (n))
    337 #define WHICHQ(p)	(RUNQUE_NQS - 1 - ((p) / PPQ))
    338 
    339 /*
    340  * The primitives that manipulate the run queues.  whichqs tells which of
    341  * the queues have processes in them.  sched_enqueue() puts processes into
    342  * queues, sched_dequeue() removes them from queues.
    343  */
    344 #ifdef RQDEBUG
    345 static void
    346 runqueue_check(const runqueue_t *rq, int whichq, struct lwp *l)
    347 {
    348 	const subqueue_t * const sq = &rq->rq_subqueues[whichq];
    349 	const uint32_t bitmap = rq->rq_bitmap;
    350 	struct lwp *l2;
    351 	int found = 0;
    352 	int die = 0;
    353 	int empty = 1;
    354 
    355 	TAILQ_FOREACH(l2, &sq->sq_queue, l_runq) {
    356 		if (l2->l_stat != LSRUN) {
    357 			printf("runqueue_check[%d]: lwp %p state (%d) "
    358 			    " != LSRUN\n", whichq, l2, l2->l_stat);
    359 		}
    360 		if (l2 == l)
    361 			found = 1;
    362 		empty = 0;
    363 	}
    364 	if (empty && (bitmap & RQMASK(whichq)) != 0) {
    365 		printf("runqueue_check[%d]: bit set for empty run-queue %p\n",
    366 		    whichq, rq);
    367 		die = 1;
    368 	} else if (!empty && (bitmap & RQMASK(whichq)) == 0) {
    369 		printf("runqueue_check[%d]: bit clear for non-empty "
    370 		    "run-queue %p\n", whichq, rq);
    371 		die = 1;
    372 	}
    373 	if (l != NULL && (bitmap & RQMASK(whichq)) == 0) {
    374 		printf("runqueue_check[%d]: bit clear for active lwp %p\n",
    375 		    whichq, l);
    376 		die = 1;
    377 	}
    378 	if (l != NULL && empty) {
    379 		printf("runqueue_check[%d]: empty run-queue %p with "
    380 		    "active lwp %p\n", whichq, rq, l);
    381 		die = 1;
    382 	}
    383 	if (l != NULL && !found) {
    384 		printf("runqueue_check[%d]: lwp %p not in runqueue %p!",
    385 		    whichq, l, rq);
    386 		die = 1;
    387 	}
    388 	if (die)
    389 		panic("runqueue_check: inconsistency found");
    390 }
    391 #else /* RQDEBUG */
    392 #define	runqueue_check(a, b, c)	/* nothing */
    393 #endif /* RQDEBUG */
    394 
    395 static void
    396 runqueue_init(runqueue_t *rq)
    397 {
    398 	int i;
    399 
    400 	for (i = 0; i < RUNQUE_NQS; i++)
    401 		TAILQ_INIT(&rq->rq_subqueues[i].sq_queue);
    402 }
    403 
    404 static void
    405 runqueue_enqueue(runqueue_t *rq, struct lwp *l)
    406 {
    407 	subqueue_t *sq;
    408 	const int whichq = WHICHQ(lwp_eprio(l));
    409 	const uint64_t rqmask = RQMASK(whichq);
    410 
    411 	KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
    412 
    413 	runqueue_check(rq, whichq, NULL);
    414 	rq->rq_bitmap |= rqmask;
    415 	sq = &rq->rq_subqueues[whichq];
    416 	TAILQ_INSERT_TAIL(&sq->sq_queue, l, l_runq);
    417 	runqueue_check(rq, whichq, l);
    418 }
    419 
    420 static void
    421 runqueue_dequeue(runqueue_t *rq, struct lwp *l)
    422 {
    423 	subqueue_t *sq;
    424 	const int whichq = WHICHQ(lwp_eprio(l));
    425 	const uint64_t rqmask = RQMASK(whichq);
    426 
    427 	KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
    428 
    429 	runqueue_check(rq, whichq, l);
    430 	KASSERT((rq->rq_bitmap & rqmask) != 0);
    431 	sq = &rq->rq_subqueues[whichq];
    432 	TAILQ_REMOVE(&sq->sq_queue, l, l_runq);
    433 	if (TAILQ_EMPTY(&sq->sq_queue))
    434 		rq->rq_bitmap &= ~rqmask;
    435 	runqueue_check(rq, whichq, NULL);
    436 }
    437 
    438 static struct lwp *
    439 runqueue_nextlwp(runqueue_t *rq)
    440 {
    441 	const uint64_t bitmap = rq->rq_bitmap;
    442 	int whichq;
    443 
    444 	if (bitmap == 0) {
    445 		return NULL;
    446 	}
    447 	whichq = ffs((uint32_t)bitmap) - 1;
    448 	if (whichq != -1)
    449 		return TAILQ_FIRST(&rq->rq_subqueues[whichq].sq_queue);
    450 	whichq = ffs((uint32_t)(bitmap >> 32)) - 1;
    451 	return TAILQ_FIRST(&rq->rq_subqueues[whichq + 32].sq_queue);
    452 }
    453 
    454 #if defined(DDB)
    455 static void
    456 runqueue_print(const runqueue_t *rq, void (*pr)(const char *, ...))
    457 {
    458 	const uint64_t bitmap = rq->rq_bitmap;
    459 	struct lwp *l;
    460 	int i, first;
    461 
    462 	for (i = 0; i < RUNQUE_NQS; i++) {
    463 		const subqueue_t *sq;
    464 		first = 1;
    465 		sq = &rq->rq_subqueues[i];
    466 		TAILQ_FOREACH(l, &sq->sq_queue, l_runq) {
    467 			if (first) {
    468 				(*pr)("%c%d",
    469 				    (bitmap & RQMASK(i)) ? ' ' : '!', i);
    470 				first = 0;
    471 			}
    472 			(*pr)("\t%d.%d (%s) pri=%d usrpri=%d\n",
    473 			    l->l_proc->p_pid,
    474 			    l->l_lid, l->l_proc->p_comm,
    475 			    (int)l->l_priority, (int)l->l_usrpri);
    476 		}
    477 	}
    478 }
    479 #endif /* defined(DDB) */
    480 
    481 /*
    482  * Initialize the (doubly-linked) run queues
    483  * to be empty.
    484  */
    485 void
    486 sched_rqinit()
    487 {
    488 
    489 	runqueue_init(&global_queue);
    490 	mutex_init(&sched_mutex, MUTEX_SPIN, IPL_SCHED);
    491 	/* Initialize the lock pointer for lwp0 */
    492 	lwp0.l_mutex = &curcpu()->ci_schedstate.spc_lwplock;
    493 }
    494 
    495 void
    496 sched_cpuattach(struct cpu_info *ci)
    497 {
    498 	runqueue_t *rq;
    499 
    500 	ci->ci_schedstate.spc_mutex = &sched_mutex;
    501 	rq = kmem_zalloc(sizeof(*rq), KM_NOSLEEP);
    502 	runqueue_init(rq);
    503 	ci->ci_schedstate.spc_sched_info = rq;
    504 }
    505 
    506 void
    507 sched_setup()
    508 {
    509 
    510 	rrticks = hz / 10;
    511 }
    512 
    513 void
    514 sched_setrunnable(struct lwp *l)
    515 {
    516 
    517  	if (l->l_slptime > 1)
    518  		updatepri(l);
    519 }
    520 
    521 bool
    522 sched_curcpu_runnable_p(void)
    523 {
    524 	struct schedstate_percpu *spc;
    525 	runqueue_t *rq;
    526 
    527 	spc = &curcpu()->ci_schedstate;
    528 	rq = spc->spc_sched_info;
    529 
    530 	if (__predict_true((spc->spc_flags & SPCF_OFFLINE) == 0))
    531 		return (global_queue.rq_bitmap | rq->rq_bitmap) != 0;
    532 	return rq->rq_bitmap != 0;
    533 }
    534 
    535 void
    536 sched_nice(struct proc *chgp, int n)
    537 {
    538 
    539 	chgp->p_nice = n;
    540 	(void)resetprocpriority(chgp);
    541 }
    542 
    543 /*
    544  * Compute the priority of a process when running in user mode.
    545  * Arrange to reschedule if the resulting priority is better
    546  * than that of the current process.
    547  */
    548 static void
    549 resetpriority(struct lwp *l)
    550 {
    551 	unsigned int newpriority;
    552 	struct proc *p = l->l_proc;
    553 
    554 	/* XXXSMP KASSERT(mutex_owned(&p->p_stmutex)); */
    555 	KASSERT(lwp_locked(l, NULL));
    556 
    557 	if ((l->l_flag & LW_SYSTEM) != 0)
    558 		return;
    559 
    560 	newpriority = PRI_KERNEL - 1 - (p->p_estcpu >> ESTCPU_SHIFT) -
    561 	    NICE_WEIGHT * (p->p_nice - NZERO);
    562 	newpriority = max(newpriority, 0);
    563 	lwp_changepri(l, newpriority);
    564 }
    565 
    566 /*
    567  * Recompute priority for all LWPs in a process.
    568  */
    569 static void
    570 resetprocpriority(struct proc *p)
    571 {
    572 	struct lwp *l;
    573 
    574 	KASSERT(mutex_owned(&p->p_stmutex));
    575 
    576 	LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    577 		lwp_lock(l);
    578 		resetpriority(l);
    579 		lwp_unlock(l);
    580 	}
    581 }
    582 
    583 /*
    584  * We adjust the priority of the current process.  The priority of a process
    585  * gets worse as it accumulates CPU time.  The CPU usage estimator (p_estcpu)
    586  * is increased here.  The formula for computing priorities (in kern_synch.c)
    587  * will compute a different value each time p_estcpu increases. This can
    588  * cause a switch, but unless the priority crosses a PPQ boundary the actual
    589  * queue will not change.  The CPU usage estimator ramps up quite quickly
    590  * when the process is running (linearly), and decays away exponentially, at
    591  * a rate which is proportionally slower when the system is busy.  The basic
    592  * principle is that the system will 90% forget that the process used a lot
    593  * of CPU time in 5 * loadav seconds.  This causes the system to favor
    594  * processes which haven't run much recently, and to round-robin among other
    595  * processes.
    596  */
    597 
    598 void
    599 sched_schedclock(struct lwp *l)
    600 {
    601 	struct proc *p = l->l_proc;
    602 
    603 	KASSERT(!CURCPU_IDLE_P());
    604 	mutex_spin_enter(&p->p_stmutex);
    605 	p->p_estcpu = ESTCPULIM(p->p_estcpu + (1 << ESTCPU_SHIFT));
    606 	lwp_lock(l);
    607 	resetpriority(l);
    608 	mutex_spin_exit(&p->p_stmutex);
    609 	if ((l->l_flag & LW_SYSTEM) == 0 && l->l_priority < PRI_KERNEL)
    610 		l->l_priority = l->l_usrpri;
    611 	lwp_unlock(l);
    612 }
    613 
    614 /*
    615  * sched_proc_fork:
    616  *
    617  *	Inherit the parent's scheduler history.
    618  */
    619 void
    620 sched_proc_fork(struct proc *parent, struct proc *child)
    621 {
    622 
    623 	KASSERT(mutex_owned(&parent->p_smutex));
    624 
    625 	child->p_estcpu = child->p_estcpu_inherited = parent->p_estcpu;
    626 	child->p_forktime = sched_pstats_ticks;
    627 }
    628 
    629 /*
    630  * sched_proc_exit:
    631  *
    632  *	Chargeback parents for the sins of their children.
    633  */
    634 void
    635 sched_proc_exit(struct proc *parent, struct proc *child)
    636 {
    637 	fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
    638 	fixpt_t estcpu;
    639 
    640 	/* XXX Only if parent != init?? */
    641 
    642 	mutex_spin_enter(&parent->p_stmutex);
    643 	estcpu = decay_cpu_batch(loadfac, child->p_estcpu_inherited,
    644 	    sched_pstats_ticks - child->p_forktime);
    645 	if (child->p_estcpu > estcpu)
    646 		parent->p_estcpu =
    647 		    ESTCPULIM(parent->p_estcpu + child->p_estcpu - estcpu);
    648 	mutex_spin_exit(&parent->p_stmutex);
    649 }
    650 
    651 void
    652 sched_enqueue(struct lwp *l, bool ctxswitch)
    653 {
    654 
    655 	if ((l->l_flag & LW_BOUND) != 0)
    656 		runqueue_enqueue(l->l_cpu->ci_schedstate.spc_sched_info, l);
    657 	else
    658 		runqueue_enqueue(&global_queue, l);
    659 }
    660 
    661 /*
    662  * XXXSMP When LWP dispatch (cpu_switch()) is changed to use sched_dequeue(),
    663  * drop of the effective priority level from kernel to user needs to be
    664  * moved here from userret().  The assignment in userret() is currently
    665  * done unlocked.
    666  */
    667 void
    668 sched_dequeue(struct lwp *l)
    669 {
    670 
    671 	if ((l->l_flag & LW_BOUND) != 0)
    672 		runqueue_dequeue(l->l_cpu->ci_schedstate.spc_sched_info, l);
    673 	else
    674 		runqueue_dequeue(&global_queue, l);
    675 }
    676 
    677 struct lwp *
    678 sched_nextlwp(void)
    679 {
    680 	struct schedstate_percpu *spc;
    681 	lwp_t *l1, *l2;
    682 
    683 	spc = &curcpu()->ci_schedstate;
    684 
    685 	/* For now, just pick the highest priority LWP. */
    686 	l1 = runqueue_nextlwp(spc->spc_sched_info);
    687 	if (__predict_false((spc->spc_flags & SPCF_OFFLINE) != 0))
    688 		return l1;
    689 	l2 = runqueue_nextlwp(&global_queue);
    690 
    691 	if (l1 == NULL)
    692 		return l2;
    693 	if (l2 == NULL)
    694 		return l1;
    695 	if (lwp_eprio(l2) > lwp_eprio(l1))
    696 		return l2;
    697 	else
    698 		return l1;
    699 }
    700 
    701 void
    702 sched_lwp_fork(struct lwp *l)
    703 {
    704 
    705 }
    706 
    707 void
    708 sched_lwp_exit(struct lwp *l)
    709 {
    710 
    711 }
    712 
    713 /*
    714  * sysctl setup.  XXX This should be split with kern_synch.c.
    715  */
    716 SYSCTL_SETUP(sysctl_sched_setup, "sysctl kern.sched subtree setup")
    717 {
    718 	const struct sysctlnode *node = NULL;
    719 
    720 	sysctl_createv(clog, 0, NULL, NULL,
    721 		CTLFLAG_PERMANENT,
    722 		CTLTYPE_NODE, "kern", NULL,
    723 		NULL, 0, NULL, 0,
    724 		CTL_KERN, CTL_EOL);
    725 	sysctl_createv(clog, 0, NULL, &node,
    726 		CTLFLAG_PERMANENT,
    727 		CTLTYPE_NODE, "sched",
    728 		SYSCTL_DESCR("Scheduler options"),
    729 		NULL, 0, NULL, 0,
    730 		CTL_KERN, CTL_CREATE, CTL_EOL);
    731 
    732 	KASSERT(node != NULL);
    733 
    734 	sysctl_createv(clog, 0, &node, NULL,
    735 		CTLFLAG_PERMANENT,
    736 		CTLTYPE_STRING, "name", NULL,
    737 		NULL, 0, __UNCONST("4.4BSD"), 0,
    738 		CTL_CREATE, CTL_EOL);
    739 	sysctl_createv(clog, 0, &node, NULL,
    740 		CTLFLAG_READWRITE,
    741 		CTLTYPE_INT, "timesoftints",
    742 		SYSCTL_DESCR("Track CPU time for soft interrupts"),
    743 		NULL, 0, &softint_timing, 0,
    744 		CTL_CREATE, CTL_EOL);
    745 }
    746 
    747 #if defined(DDB)
    748 void
    749 sched_print_runqueue(void (*pr)(const char *, ...))
    750 {
    751 
    752 	runqueue_print(&global_queue, pr);
    753 }
    754 #endif /* defined(DDB) */
    755