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