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