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