Home | History | Annotate | Line # | Download | only in kern
sched_4bsd.c revision 1.16
      1 /*	$NetBSD: sched_4bsd.c,v 1.16 2008/04/12 17:02:08 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999, 2000, 2004, 2006, 2007, 2008 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.16 2008/04/12 17:02:08 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 static void updatepri(struct lwp *);
    104 static void resetpriority(struct lwp *);
    105 
    106 fixpt_t decay_cpu(fixpt_t, fixpt_t);
    107 
    108 extern unsigned int sched_pstats_ticks; /* defined in kern_synch.c */
    109 
    110 /* Number of hardclock ticks per sched_tick() */
    111 static int rrticks;
    112 
    113 /*
    114  * Force switch among equal priority processes every 100ms.
    115  * Called from hardclock every hz/10 == rrticks hardclock ticks.
    116  *
    117  * There's no need to lock anywhere in this routine, as it's
    118  * CPU-local and runs at IPL_SCHED (called from clock interrupt).
    119  */
    120 /* ARGSUSED */
    121 void
    122 sched_tick(struct cpu_info *ci)
    123 {
    124 	struct schedstate_percpu *spc = &ci->ci_schedstate;
    125 
    126 	spc->spc_ticks = rrticks;
    127 
    128 	if (CURCPU_IDLE_P()) {
    129 		cpu_need_resched(ci, 0);
    130 		return;
    131 	}
    132 
    133 	if (spc->spc_flags & SPCF_SEENRR) {
    134 		/*
    135 		 * The process has already been through a roundrobin
    136 		 * without switching and may be hogging the CPU.
    137 		 * Indicate that the process should yield.
    138 		 */
    139 		spc->spc_flags |= SPCF_SHOULDYIELD;
    140 		cpu_need_resched(ci, 0);
    141 	} else
    142 		spc->spc_flags |= SPCF_SEENRR;
    143 }
    144 
    145 /*
    146  * Why PRIO_MAX - 2? From setpriority(2):
    147  *
    148  *	prio is a value in the range -20 to 20.  The default priority is
    149  *	0; lower priorities cause more favorable scheduling.  A value of
    150  *	19 or 20 will schedule a process only when nothing at priority <=
    151  *	0 is runnable.
    152  *
    153  * This gives estcpu influence over 18 priority levels, and leaves nice
    154  * with 40 levels.  One way to think about it is that nice has 20 levels
    155  * either side of estcpu's 18.
    156  */
    157 #define	ESTCPU_SHIFT	11
    158 #define	ESTCPU_MAX	((PRIO_MAX - 2) << ESTCPU_SHIFT)
    159 #define	ESTCPU_ACCUM	(1 << (ESTCPU_SHIFT - 1))
    160 #define	ESTCPULIM(e)	min((e), ESTCPU_MAX)
    161 
    162 /*
    163  * Constants for digital decay and forget:
    164  *	90% of (l_estcpu) usage in 5 * loadav time
    165  *	95% of (l_pctcpu) usage in 60 seconds (load insensitive)
    166  *          Note that, as ps(1) mentions, this can let percentages
    167  *          total over 100% (I've seen 137.9% for 3 processes).
    168  *
    169  * Note that hardclock updates l_estcpu and l_cpticks independently.
    170  *
    171  * We wish to decay away 90% of l_estcpu in (5 * loadavg) seconds.
    172  * That is, the system wants to compute a value of decay such
    173  * that the following for loop:
    174  * 	for (i = 0; i < (5 * loadavg); i++)
    175  * 		l_estcpu *= decay;
    176  * will compute
    177  * 	l_estcpu *= 0.1;
    178  * for all values of loadavg:
    179  *
    180  * Mathematically this loop can be expressed by saying:
    181  * 	decay ** (5 * loadavg) ~= .1
    182  *
    183  * The system computes decay as:
    184  * 	decay = (2 * loadavg) / (2 * loadavg + 1)
    185  *
    186  * We wish to prove that the system's computation of decay
    187  * will always fulfill the equation:
    188  * 	decay ** (5 * loadavg) ~= .1
    189  *
    190  * If we compute b as:
    191  * 	b = 2 * loadavg
    192  * then
    193  * 	decay = b / (b + 1)
    194  *
    195  * We now need to prove two things:
    196  *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
    197  *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
    198  *
    199  * Facts:
    200  *         For x close to zero, exp(x) =~ 1 + x, since
    201  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
    202  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
    203  *         For x close to zero, ln(1+x) =~ x, since
    204  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
    205  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
    206  *         ln(.1) =~ -2.30
    207  *
    208  * Proof of (1):
    209  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
    210  *	solving for factor,
    211  *      ln(factor) =~ (-2.30/5*loadav), or
    212  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
    213  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
    214  *
    215  * Proof of (2):
    216  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
    217  *	solving for power,
    218  *      power*ln(b/(b+1)) =~ -2.30, or
    219  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
    220  *
    221  * Actual power values for the implemented algorithm are as follows:
    222  *      loadav: 1       2       3       4
    223  *      power:  5.68    10.32   14.94   19.55
    224  */
    225 
    226 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
    227 #define	loadfactor(loadav)	(2 * (loadav))
    228 
    229 fixpt_t
    230 decay_cpu(fixpt_t loadfac, fixpt_t estcpu)
    231 {
    232 
    233 	if (estcpu == 0) {
    234 		return 0;
    235 	}
    236 
    237 #if !defined(_LP64)
    238 	/* avoid 64bit arithmetics. */
    239 #define	FIXPT_MAX ((fixpt_t)((UINTMAX_C(1) << sizeof(fixpt_t) * CHAR_BIT) - 1))
    240 	if (__predict_true(loadfac <= FIXPT_MAX / ESTCPU_MAX)) {
    241 		return estcpu * loadfac / (loadfac + FSCALE);
    242 	}
    243 #endif /* !defined(_LP64) */
    244 
    245 	return (uint64_t)estcpu * loadfac / (loadfac + FSCALE);
    246 }
    247 
    248 /*
    249  * For all load averages >= 1 and max l_estcpu of (255 << ESTCPU_SHIFT),
    250  * sleeping for at least seven times the loadfactor will decay l_estcpu to
    251  * less than (1 << ESTCPU_SHIFT).
    252  *
    253  * note that our ESTCPU_MAX is actually much smaller than (255 << ESTCPU_SHIFT).
    254  */
    255 static fixpt_t
    256 decay_cpu_batch(fixpt_t loadfac, fixpt_t estcpu, unsigned int n)
    257 {
    258 
    259 	if ((n << FSHIFT) >= 7 * loadfac) {
    260 		return 0;
    261 	}
    262 
    263 	while (estcpu != 0 && n > 1) {
    264 		estcpu = decay_cpu(loadfac, estcpu);
    265 		n--;
    266 	}
    267 
    268 	return estcpu;
    269 }
    270 
    271 /*
    272  * sched_pstats_hook:
    273  *
    274  * Periodically called from sched_pstats(); used to recalculate priorities.
    275  */
    276 void
    277 sched_pstats_hook(struct lwp *l)
    278 {
    279 	fixpt_t loadfac;
    280 	int sleeptm;
    281 
    282 	/*
    283 	 * If the LWP has slept an entire second, stop recalculating
    284 	 * its priority until it wakes up.
    285 	 */
    286 	if (l->l_stat == LSSLEEP || l->l_stat == LSSTOP ||
    287 	    l->l_stat == LSSUSPENDED) {
    288 		l->l_slptime++;
    289 		sleeptm = 1;
    290 	} else {
    291 		sleeptm = 0x7fffffff;
    292 	}
    293 
    294 	if (l->l_slptime <= sleeptm) {
    295 		loadfac = 2 * (averunnable.ldavg[0]);
    296 		l->l_estcpu = decay_cpu(loadfac, l->l_estcpu);
    297 		resetpriority(l);
    298 	}
    299 }
    300 
    301 /*
    302  * Recalculate the priority of a process after it has slept for a while.
    303  */
    304 static void
    305 updatepri(struct lwp *l)
    306 {
    307 	fixpt_t loadfac;
    308 
    309 	KASSERT(lwp_locked(l, NULL));
    310 	KASSERT(l->l_slptime > 1);
    311 
    312 	loadfac = loadfactor(averunnable.ldavg[0]);
    313 
    314 	l->l_slptime--; /* the first time was done in sched_pstats */
    315 	l->l_estcpu = decay_cpu_batch(loadfac, l->l_estcpu, l->l_slptime);
    316 	resetpriority(l);
    317 }
    318 
    319 void
    320 sched_rqinit(void)
    321 {
    322 
    323 }
    324 
    325 void
    326 sched_setrunnable(struct lwp *l)
    327 {
    328 
    329  	if (l->l_slptime > 1)
    330  		updatepri(l);
    331 }
    332 
    333 void
    334 sched_nice(struct proc *p, int n)
    335 {
    336 	struct lwp *l;
    337 
    338 	KASSERT(mutex_owned(&p->p_smutex));
    339 
    340 	p->p_nice = n;
    341 	LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    342 		lwp_lock(l);
    343 		resetpriority(l);
    344 		lwp_unlock(l);
    345 	}
    346 }
    347 
    348 /*
    349  * Recompute the priority of an LWP.  Arrange to reschedule if
    350  * the resulting priority is better than that of the current LWP.
    351  */
    352 static void
    353 resetpriority(struct lwp *l)
    354 {
    355 	pri_t pri;
    356 	struct proc *p = l->l_proc;
    357 
    358 	KASSERT(lwp_locked(l, NULL));
    359 
    360 	if (l->l_class != SCHED_OTHER)
    361 		return;
    362 
    363 	/* See comments above ESTCPU_SHIFT definition. */
    364 	pri = (PRI_KERNEL - 1) - (l->l_estcpu >> ESTCPU_SHIFT) - p->p_nice;
    365 	pri = imax(pri, 0);
    366 	if (pri != l->l_priority)
    367 		lwp_changepri(l, pri);
    368 }
    369 
    370 /*
    371  * We adjust the priority of the current process.  The priority of a process
    372  * gets worse as it accumulates CPU time.  The CPU usage estimator (l_estcpu)
    373  * is increased here.  The formula for computing priorities (in kern_synch.c)
    374  * will compute a different value each time l_estcpu increases. This can
    375  * cause a switch, but unless the priority crosses a PPQ boundary the actual
    376  * queue will not change.  The CPU usage estimator ramps up quite quickly
    377  * when the process is running (linearly), and decays away exponentially, at
    378  * a rate which is proportionally slower when the system is busy.  The basic
    379  * principle is that the system will 90% forget that the process used a lot
    380  * of CPU time in 5 * loadav seconds.  This causes the system to favor
    381  * processes which haven't run much recently, and to round-robin among other
    382  * processes.
    383  */
    384 
    385 void
    386 sched_schedclock(struct lwp *l)
    387 {
    388 
    389 	if (l->l_class != SCHED_OTHER)
    390 		return;
    391 
    392 	KASSERT(!CURCPU_IDLE_P());
    393 	l->l_estcpu = ESTCPULIM(l->l_estcpu + ESTCPU_ACCUM);
    394 	lwp_lock(l);
    395 	resetpriority(l);
    396 	lwp_unlock(l);
    397 }
    398 
    399 /*
    400  * sched_proc_fork:
    401  *
    402  *	Inherit the parent's scheduler history.
    403  */
    404 void
    405 sched_proc_fork(struct proc *parent, struct proc *child)
    406 {
    407 	lwp_t *pl;
    408 
    409 	KASSERT(mutex_owned(&parent->p_smutex));
    410 
    411 	pl = LIST_FIRST(&parent->p_lwps);
    412 	child->p_estcpu_inherited = pl->l_estcpu;
    413 	child->p_forktime = sched_pstats_ticks;
    414 }
    415 
    416 /*
    417  * sched_proc_exit:
    418  *
    419  *	Chargeback parents for the sins of their children.
    420  */
    421 void
    422 sched_proc_exit(struct proc *parent, struct proc *child)
    423 {
    424 	fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
    425 	fixpt_t estcpu;
    426 	lwp_t *pl, *cl;
    427 
    428 	/* XXX Only if parent != init?? */
    429 
    430 	mutex_enter(&parent->p_smutex);
    431 	pl = LIST_FIRST(&parent->p_lwps);
    432 	cl = LIST_FIRST(&child->p_lwps);
    433 	estcpu = decay_cpu_batch(loadfac, child->p_estcpu_inherited,
    434 	    sched_pstats_ticks - child->p_forktime);
    435 	if (cl->l_estcpu > estcpu) {
    436 		lwp_lock(pl);
    437 		pl->l_estcpu = ESTCPULIM(pl->l_estcpu + cl->l_estcpu - estcpu);
    438 		lwp_unlock(pl);
    439 	}
    440 	mutex_exit(&parent->p_smutex);
    441 }
    442 
    443 void
    444 sched_wakeup(struct lwp *l)
    445 {
    446 
    447 	l->l_cpu = sched_takecpu(l);
    448 }
    449 
    450 void
    451 sched_slept(struct lwp *l)
    452 {
    453 
    454 }
    455 
    456 void
    457 sched_lwp_fork(struct lwp *l1, struct lwp *l2)
    458 {
    459 
    460 	l2->l_estcpu = l1->l_estcpu;
    461 }
    462 
    463 void
    464 sched_lwp_exit(struct lwp *l)
    465 {
    466 
    467 }
    468 
    469 void
    470 sched_lwp_collect(struct lwp *t)
    471 {
    472 	lwp_t *l;
    473 
    474 	/* Absorb estcpu value of collected LWP. */
    475 	l = curlwp;
    476 	lwp_lock(l);
    477 	l->l_estcpu += t->l_estcpu;
    478 	lwp_unlock(l);
    479 }
    480 
    481 void
    482 sched_oncpu(lwp_t *l)
    483 {
    484 
    485 }
    486 
    487 void
    488 sched_newts(lwp_t *l)
    489 {
    490 
    491 }
    492 
    493 /*
    494  * Sysctl nodes and initialization.
    495  */
    496 
    497 static int
    498 sysctl_sched_rtts(SYSCTLFN_ARGS)
    499 {
    500 	struct sysctlnode node;
    501 	int rttsms = hztoms(rrticks);
    502 
    503 	node = *rnode;
    504 	node.sysctl_data = &rttsms;
    505 	return sysctl_lookup(SYSCTLFN_CALL(&node));
    506 }
    507 
    508 SYSCTL_SETUP(sysctl_sched_4bsd_setup, "sysctl sched setup")
    509 {
    510 	const struct sysctlnode *node = NULL;
    511 
    512 	sysctl_createv(clog, 0, NULL, NULL,
    513 		CTLFLAG_PERMANENT,
    514 		CTLTYPE_NODE, "kern", NULL,
    515 		NULL, 0, NULL, 0,
    516 		CTL_KERN, CTL_EOL);
    517 	sysctl_createv(clog, 0, NULL, &node,
    518 		CTLFLAG_PERMANENT,
    519 		CTLTYPE_NODE, "sched",
    520 		SYSCTL_DESCR("Scheduler options"),
    521 		NULL, 0, NULL, 0,
    522 		CTL_KERN, CTL_CREATE, CTL_EOL);
    523 
    524 	if (node == NULL)
    525 		return;
    526 
    527 	rrticks = hz / 10;
    528 
    529 	sysctl_createv(NULL, 0, &node, NULL,
    530 		CTLFLAG_PERMANENT,
    531 		CTLTYPE_STRING, "name", NULL,
    532 		NULL, 0, __UNCONST("4.4BSD"), 0,
    533 		CTL_CREATE, CTL_EOL);
    534 	sysctl_createv(NULL, 0, &node, NULL,
    535 		CTLFLAG_PERMANENT,
    536 		CTLTYPE_INT, "rtts",
    537 		SYSCTL_DESCR("Round-robin time quantum (in miliseconds)"),
    538 		sysctl_sched_rtts, 0, NULL, 0,
    539 		CTL_CREATE, CTL_EOL);
    540 }
    541