kern_synch.c revision 1.69 1 /* $NetBSD: kern_synch.c,v 1.69 2000/03/23 20:37:59 thorpej Exp $ */
2
3 /*-
4 * Copyright (c) 1999, 2000 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.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the NetBSD
22 * Foundation, Inc. and its contributors.
23 * 4. Neither the name of The NetBSD Foundation nor the names of its
24 * contributors may be used to endorse or promote products derived
25 * from this software without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
28 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
29 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
31 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37 * POSSIBILITY OF SUCH DAMAGE.
38 */
39
40 /*-
41 * Copyright (c) 1982, 1986, 1990, 1991, 1993
42 * The Regents of the University of California. All rights reserved.
43 * (c) UNIX System Laboratories, Inc.
44 * All or some portions of this file are derived from material licensed
45 * to the University of California by American Telephone and Telegraph
46 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
47 * the permission of UNIX System Laboratories, Inc.
48 *
49 * Redistribution and use in source and binary forms, with or without
50 * modification, are permitted provided that the following conditions
51 * are met:
52 * 1. Redistributions of source code must retain the above copyright
53 * notice, this list of conditions and the following disclaimer.
54 * 2. Redistributions in binary form must reproduce the above copyright
55 * notice, this list of conditions and the following disclaimer in the
56 * documentation and/or other materials provided with the distribution.
57 * 3. All advertising materials mentioning features or use of this software
58 * must display the following acknowledgement:
59 * This product includes software developed by the University of
60 * California, Berkeley and its contributors.
61 * 4. Neither the name of the University nor the names of its contributors
62 * may be used to endorse or promote products derived from this software
63 * without specific prior written permission.
64 *
65 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
66 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
67 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
68 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
69 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
70 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
71 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
72 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
73 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
74 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
75 * SUCH DAMAGE.
76 *
77 * @(#)kern_synch.c 8.9 (Berkeley) 5/19/95
78 */
79
80 #include "opt_ddb.h"
81 #include "opt_ktrace.h"
82
83 #include <sys/param.h>
84 #include <sys/systm.h>
85 #include <sys/callout.h>
86 #include <sys/proc.h>
87 #include <sys/kernel.h>
88 #include <sys/buf.h>
89 #include <sys/signalvar.h>
90 #include <sys/resourcevar.h>
91 #include <vm/vm.h>
92 #include <sys/sched.h>
93
94 #include <uvm/uvm_extern.h>
95
96 #ifdef KTRACE
97 #include <sys/ktrace.h>
98 #endif
99
100 #define NICE_WEIGHT 2 /* priorities per nice level */
101 #define PPQ (128 / NQS) /* priorities per queue */
102
103 #define ESTCPULIM(e) min((e), NICE_WEIGHT * PRIO_MAX - PPQ)
104
105 #include <machine/cpu.h>
106
107 u_char curpriority; /* usrpri of curproc */
108 int lbolt; /* once a second sleep address */
109
110 void roundrobin __P((void *));
111 void schedcpu __P((void *));
112 void updatepri __P((struct proc *));
113 void endtsleep __P((void *));
114
115 __inline void awaken __P((struct proc *));
116
117 struct callout roundrobin_ch = CALLOUT_INITIALIZER;
118 struct callout schedcpu_ch = CALLOUT_INITIALIZER;
119
120 /*
121 * Force switch among equal priority processes every 100ms.
122 */
123 /* ARGSUSED */
124 void
125 roundrobin(arg)
126 void *arg;
127 {
128 int s;
129
130 if (curproc != NULL) {
131 s = splstatclock();
132 if (curproc->p_schedflags & PSCHED_SEENRR) {
133 /*
134 * The process has already been through a roundrobin
135 * without switching and may be hogging the CPU.
136 * Indicate that the process should yield.
137 */
138 curproc->p_schedflags |= PSCHED_SHOULDYIELD;
139 } else
140 curproc->p_schedflags |= PSCHED_SEENRR;
141 splx(s);
142 }
143 need_resched();
144 callout_reset(&roundrobin_ch, hz / 10, roundrobin, NULL);
145 }
146
147 /*
148 * Constants for digital decay and forget:
149 * 90% of (p_estcpu) usage in 5 * loadav time
150 * 95% of (p_pctcpu) usage in 60 seconds (load insensitive)
151 * Note that, as ps(1) mentions, this can let percentages
152 * total over 100% (I've seen 137.9% for 3 processes).
153 *
154 * Note that hardclock updates p_estcpu and p_cpticks independently.
155 *
156 * We wish to decay away 90% of p_estcpu in (5 * loadavg) seconds.
157 * That is, the system wants to compute a value of decay such
158 * that the following for loop:
159 * for (i = 0; i < (5 * loadavg); i++)
160 * p_estcpu *= decay;
161 * will compute
162 * p_estcpu *= 0.1;
163 * for all values of loadavg:
164 *
165 * Mathematically this loop can be expressed by saying:
166 * decay ** (5 * loadavg) ~= .1
167 *
168 * The system computes decay as:
169 * decay = (2 * loadavg) / (2 * loadavg + 1)
170 *
171 * We wish to prove that the system's computation of decay
172 * will always fulfill the equation:
173 * decay ** (5 * loadavg) ~= .1
174 *
175 * If we compute b as:
176 * b = 2 * loadavg
177 * then
178 * decay = b / (b + 1)
179 *
180 * We now need to prove two things:
181 * 1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
182 * 2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
183 *
184 * Facts:
185 * For x close to zero, exp(x) =~ 1 + x, since
186 * exp(x) = 0! + x**1/1! + x**2/2! + ... .
187 * therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
188 * For x close to zero, ln(1+x) =~ x, since
189 * ln(1+x) = x - x**2/2 + x**3/3 - ... -1 < x < 1
190 * therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
191 * ln(.1) =~ -2.30
192 *
193 * Proof of (1):
194 * Solve (factor)**(power) =~ .1 given power (5*loadav):
195 * solving for factor,
196 * ln(factor) =~ (-2.30/5*loadav), or
197 * factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
198 * exp(-1/b) =~ (b-1)/b =~ b/(b+1). QED
199 *
200 * Proof of (2):
201 * Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
202 * solving for power,
203 * power*ln(b/(b+1)) =~ -2.30, or
204 * power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav. QED
205 *
206 * Actual power values for the implemented algorithm are as follows:
207 * loadav: 1 2 3 4
208 * power: 5.68 10.32 14.94 19.55
209 */
210
211 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
212 #define loadfactor(loadav) (2 * (loadav))
213 #define decay_cpu(loadfac, cpu) (((loadfac) * (cpu)) / ((loadfac) + FSCALE))
214
215 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
216 fixpt_t ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
217
218 /*
219 * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
220 * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
221 * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
222 *
223 * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
224 * 1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
225 *
226 * If you dont want to bother with the faster/more-accurate formula, you
227 * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
228 * (more general) method of calculating the %age of CPU used by a process.
229 */
230 #define CCPU_SHIFT 11
231
232 /*
233 * Recompute process priorities, every hz ticks.
234 */
235 /* ARGSUSED */
236 void
237 schedcpu(arg)
238 void *arg;
239 {
240 register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
241 register struct proc *p;
242 register int s;
243 register unsigned int newcpu;
244 int clkhz;
245
246 proclist_lock_read();
247 for (p = allproc.lh_first; p != 0; p = p->p_list.le_next) {
248 /*
249 * Increment time in/out of memory and sleep time
250 * (if sleeping). We ignore overflow; with 16-bit int's
251 * (remember them?) overflow takes 45 days.
252 */
253 p->p_swtime++;
254 if (p->p_stat == SSLEEP || p->p_stat == SSTOP)
255 p->p_slptime++;
256 p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
257 /*
258 * If the process has slept the entire second,
259 * stop recalculating its priority until it wakes up.
260 */
261 if (p->p_slptime > 1)
262 continue;
263 s = splstatclock(); /* prevent state changes */
264 /*
265 * p_pctcpu is only for ps.
266 */
267 clkhz = stathz != 0 ? stathz : hz;
268 #if (FSHIFT >= CCPU_SHIFT)
269 p->p_pctcpu += (clkhz == 100)?
270 ((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT):
271 100 * (((fixpt_t) p->p_cpticks)
272 << (FSHIFT - CCPU_SHIFT)) / clkhz;
273 #else
274 p->p_pctcpu += ((FSCALE - ccpu) *
275 (p->p_cpticks * FSCALE / clkhz)) >> FSHIFT;
276 #endif
277 p->p_cpticks = 0;
278 newcpu = (u_int)decay_cpu(loadfac, p->p_estcpu);
279 p->p_estcpu = newcpu;
280 resetpriority(p);
281 if (p->p_priority >= PUSER) {
282 if ((p != curproc) &&
283 p->p_stat == SRUN &&
284 (p->p_flag & P_INMEM) &&
285 (p->p_priority / PPQ) != (p->p_usrpri / PPQ)) {
286 remrunqueue(p);
287 p->p_priority = p->p_usrpri;
288 setrunqueue(p);
289 } else
290 p->p_priority = p->p_usrpri;
291 }
292 splx(s);
293 }
294 proclist_unlock_read();
295 uvm_meter();
296 wakeup((caddr_t)&lbolt);
297 callout_reset(&schedcpu_ch, hz, schedcpu, NULL);
298 }
299
300 /*
301 * Recalculate the priority of a process after it has slept for a while.
302 * For all load averages >= 1 and max p_estcpu of 255, sleeping for at
303 * least six times the loadfactor will decay p_estcpu to zero.
304 */
305 void
306 updatepri(p)
307 register struct proc *p;
308 {
309 register unsigned int newcpu = p->p_estcpu;
310 register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
311
312 if (p->p_slptime > 5 * loadfac)
313 p->p_estcpu = 0;
314 else {
315 p->p_slptime--; /* the first time was done in schedcpu */
316 while (newcpu && --p->p_slptime)
317 newcpu = (int) decay_cpu(loadfac, newcpu);
318 p->p_estcpu = newcpu;
319 }
320 resetpriority(p);
321 }
322
323 /*
324 * We're only looking at 7 bits of the address; everything is
325 * aligned to 4, lots of things are aligned to greater powers
326 * of 2. Shift right by 8, i.e. drop the bottom 256 worth.
327 */
328 #define TABLESIZE 128
329 #define LOOKUP(x) (((long)(x) >> 8) & (TABLESIZE - 1))
330 struct slpque {
331 struct proc *sq_head;
332 struct proc **sq_tailp;
333 } slpque[TABLESIZE];
334
335 /*
336 * During autoconfiguration or after a panic, a sleep will simply
337 * lower the priority briefly to allow interrupts, then return.
338 * The priority to be used (safepri) is machine-dependent, thus this
339 * value is initialized and maintained in the machine-dependent layers.
340 * This priority will typically be 0, or the lowest priority
341 * that is safe for use on the interrupt stack; it can be made
342 * higher to block network software interrupts after panics.
343 */
344 int safepri;
345
346 /*
347 * General sleep call. Suspends the current process until a wakeup is
348 * performed on the specified identifier. The process will then be made
349 * runnable with the specified priority. Sleeps at most timo/hz seconds
350 * (0 means no timeout). If pri includes PCATCH flag, signals are checked
351 * before and after sleeping, else signals are not checked. Returns 0 if
352 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a
353 * signal needs to be delivered, ERESTART is returned if the current system
354 * call should be restarted if possible, and EINTR is returned if the system
355 * call should be interrupted by the signal (return EINTR).
356 */
357 int
358 tsleep(ident, priority, wmesg, timo)
359 void *ident;
360 int priority, timo;
361 const char *wmesg;
362 {
363 register struct proc *p = curproc;
364 register struct slpque *qp;
365 register int s;
366 int sig, catch = priority & PCATCH;
367 void endtsleep __P((void *));
368
369 if (cold || panicstr) {
370 /*
371 * After a panic, or during autoconfiguration,
372 * just give interrupts a chance, then just return;
373 * don't run any other procs or panic below,
374 * in case this is the idle process and already asleep.
375 */
376 s = splhigh();
377 splx(safepri);
378 splx(s);
379 return (0);
380 }
381
382 #ifdef KTRACE
383 if (KTRPOINT(p, KTR_CSW))
384 ktrcsw(p->p_tracep, 1, 0);
385 #endif
386 s = splhigh();
387
388 #ifdef DIAGNOSTIC
389 if (ident == NULL)
390 panic("tsleep: ident == NULL");
391 if (p->p_stat != SRUN)
392 panic("tsleep: p_stat %d != SRUN", p->p_stat);
393 if (p->p_back != NULL)
394 panic("tsleep: p_back != NULL");
395 #endif
396 p->p_wchan = ident;
397 p->p_wmesg = wmesg;
398 p->p_slptime = 0;
399 p->p_priority = priority & PRIMASK;
400 qp = &slpque[LOOKUP(ident)];
401 if (qp->sq_head == 0)
402 qp->sq_head = p;
403 else
404 *qp->sq_tailp = p;
405 *(qp->sq_tailp = &p->p_forw) = 0;
406 if (timo)
407 callout_reset(&p->p_tsleep_ch, timo, endtsleep, p);
408 /*
409 * We put ourselves on the sleep queue and start our timeout
410 * before calling CURSIG, as we could stop there, and a wakeup
411 * or a SIGCONT (or both) could occur while we were stopped.
412 * A SIGCONT would cause us to be marked as SSLEEP
413 * without resuming us, thus we must be ready for sleep
414 * when CURSIG is called. If the wakeup happens while we're
415 * stopped, p->p_wchan will be 0 upon return from CURSIG.
416 */
417 if (catch) {
418 p->p_flag |= P_SINTR;
419 if ((sig = CURSIG(p)) != 0) {
420 if (p->p_wchan)
421 unsleep(p);
422 p->p_stat = SRUN;
423 goto resume;
424 }
425 if (p->p_wchan == 0) {
426 catch = 0;
427 goto resume;
428 }
429 } else
430 sig = 0;
431 p->p_stat = SSLEEP;
432 p->p_stats->p_ru.ru_nvcsw++;
433 mi_switch();
434 #ifdef DDB
435 /* handy breakpoint location after process "wakes" */
436 asm(".globl bpendtsleep ; bpendtsleep:");
437 #endif
438 resume:
439 curpriority = p->p_usrpri;
440 splx(s);
441 p->p_flag &= ~P_SINTR;
442 if (p->p_flag & P_TIMEOUT) {
443 p->p_flag &= ~P_TIMEOUT;
444 if (sig == 0) {
445 #ifdef KTRACE
446 if (KTRPOINT(p, KTR_CSW))
447 ktrcsw(p->p_tracep, 0, 0);
448 #endif
449 return (EWOULDBLOCK);
450 }
451 } else if (timo)
452 callout_stop(&p->p_tsleep_ch);
453 if (catch && (sig != 0 || (sig = CURSIG(p)) != 0)) {
454 #ifdef KTRACE
455 if (KTRPOINT(p, KTR_CSW))
456 ktrcsw(p->p_tracep, 0, 0);
457 #endif
458 if ((p->p_sigacts->ps_sigact[sig].sa_flags & SA_RESTART) == 0)
459 return (EINTR);
460 return (ERESTART);
461 }
462 #ifdef KTRACE
463 if (KTRPOINT(p, KTR_CSW))
464 ktrcsw(p->p_tracep, 0, 0);
465 #endif
466 return (0);
467 }
468
469 /*
470 * Implement timeout for tsleep.
471 * If process hasn't been awakened (wchan non-zero),
472 * set timeout flag and undo the sleep. If proc
473 * is stopped, just unsleep so it will remain stopped.
474 */
475 void
476 endtsleep(arg)
477 void *arg;
478 {
479 register struct proc *p;
480 int s;
481
482 p = (struct proc *)arg;
483 s = splhigh();
484 if (p->p_wchan) {
485 if (p->p_stat == SSLEEP)
486 setrunnable(p);
487 else
488 unsleep(p);
489 p->p_flag |= P_TIMEOUT;
490 }
491 splx(s);
492 }
493
494 /*
495 * Short-term, non-interruptable sleep.
496 */
497 void
498 sleep(ident, priority)
499 void *ident;
500 int priority;
501 {
502 register struct proc *p = curproc;
503 register struct slpque *qp;
504 register int s;
505
506 #ifdef DIAGNOSTIC
507 if (priority > PZERO) {
508 printf("sleep called with priority %d > PZERO, wchan: %p\n",
509 priority, ident);
510 panic("old sleep");
511 }
512 #endif
513 s = splhigh();
514 if (cold || panicstr) {
515 /*
516 * After a panic, or during autoconfiguration,
517 * just give interrupts a chance, then just return;
518 * don't run any other procs or panic below,
519 * in case this is the idle process and already asleep.
520 */
521 splx(safepri);
522 splx(s);
523 return;
524 }
525 #ifdef DIAGNOSTIC
526 if (ident == NULL || p->p_stat != SRUN || p->p_back)
527 panic("sleep");
528 #endif
529 p->p_wchan = ident;
530 p->p_wmesg = NULL;
531 p->p_slptime = 0;
532 p->p_priority = priority;
533 qp = &slpque[LOOKUP(ident)];
534 if (qp->sq_head == 0)
535 qp->sq_head = p;
536 else
537 *qp->sq_tailp = p;
538 *(qp->sq_tailp = &p->p_forw) = 0;
539 p->p_stat = SSLEEP;
540 p->p_stats->p_ru.ru_nvcsw++;
541 #ifdef KTRACE
542 if (KTRPOINT(p, KTR_CSW))
543 ktrcsw(p->p_tracep, 1, 0);
544 #endif
545 mi_switch();
546 #ifdef DDB
547 /* handy breakpoint location after process "wakes" */
548 asm(".globl bpendsleep ; bpendsleep:");
549 #endif
550 #ifdef KTRACE
551 if (KTRPOINT(p, KTR_CSW))
552 ktrcsw(p->p_tracep, 0, 0);
553 #endif
554 curpriority = p->p_usrpri;
555 splx(s);
556 }
557
558 /*
559 * Remove a process from its wait queue
560 */
561 void
562 unsleep(p)
563 register struct proc *p;
564 {
565 register struct slpque *qp;
566 register struct proc **hp;
567 int s;
568
569 s = splhigh();
570 if (p->p_wchan) {
571 hp = &(qp = &slpque[LOOKUP(p->p_wchan)])->sq_head;
572 while (*hp != p)
573 hp = &(*hp)->p_forw;
574 *hp = p->p_forw;
575 if (qp->sq_tailp == &p->p_forw)
576 qp->sq_tailp = hp;
577 p->p_wchan = 0;
578 }
579 splx(s);
580 }
581
582 /*
583 * Optimized-for-wakeup() version of setrunnable().
584 */
585 __inline void
586 awaken(p)
587 struct proc *p;
588 {
589
590 if (p->p_slptime > 1)
591 updatepri(p);
592 p->p_slptime = 0;
593 p->p_stat = SRUN;
594 /*
595 * Since curpriority is a user priority, p->p_priority
596 * is always better than curpriority.
597 */
598 if (p->p_flag & P_INMEM) {
599 setrunqueue(p);
600 need_resched();
601 } else
602 wakeup((caddr_t)&proc0);
603 }
604
605 /*
606 * Make all processes sleeping on the specified identifier runnable.
607 */
608 void
609 wakeup(ident)
610 register void *ident;
611 {
612 register struct slpque *qp;
613 register struct proc *p, **q;
614 int s;
615
616 s = splhigh();
617 qp = &slpque[LOOKUP(ident)];
618 restart:
619 for (q = &qp->sq_head; (p = *q) != NULL; ) {
620 #ifdef DIAGNOSTIC
621 if (p->p_back || (p->p_stat != SSLEEP && p->p_stat != SSTOP))
622 panic("wakeup");
623 #endif
624 if (p->p_wchan == ident) {
625 p->p_wchan = 0;
626 *q = p->p_forw;
627 if (qp->sq_tailp == &p->p_forw)
628 qp->sq_tailp = q;
629 if (p->p_stat == SSLEEP) {
630 awaken(p);
631 goto restart;
632 }
633 } else
634 q = &p->p_forw;
635 }
636 splx(s);
637 }
638
639 /*
640 * Make the highest priority process first in line on the specified
641 * identifier runnable.
642 */
643 void
644 wakeup_one(ident)
645 void *ident;
646 {
647 struct slpque *qp;
648 struct proc *p, **q;
649 struct proc *best_sleepp, **best_sleepq;
650 struct proc *best_stopp, **best_stopq;
651 int s;
652
653 best_sleepp = best_stopp = NULL;
654 best_sleepq = best_stopq = NULL;
655
656 s = splhigh();
657 qp = &slpque[LOOKUP(ident)];
658 for (q = &qp->sq_head; (p = *q) != NULL; q = &p->p_forw) {
659 #ifdef DIAGNOSTIC
660 if (p->p_back || (p->p_stat != SSLEEP && p->p_stat != SSTOP))
661 panic("wakeup_one");
662 #endif
663 if (p->p_wchan == ident) {
664 if (p->p_stat == SSLEEP) {
665 if (best_sleepp == NULL ||
666 p->p_priority < best_sleepp->p_priority) {
667 best_sleepp = p;
668 best_sleepq = q;
669 }
670 } else {
671 if (best_stopp == NULL ||
672 p->p_priority < best_stopp->p_priority) {
673 best_stopp = p;
674 best_stopq = q;
675 }
676 }
677 }
678 }
679
680 /*
681 * Consider any SSLEEP process higher than the highest priority SSTOP
682 * process.
683 */
684 if (best_sleepp != NULL) {
685 p = best_sleepp;
686 q = best_sleepq;
687 } else {
688 p = best_stopp;
689 q = best_stopq;
690 }
691
692 if (p != NULL) {
693 p->p_wchan = 0;
694 *q = p->p_forw;
695 if (qp->sq_tailp == &p->p_forw)
696 qp->sq_tailp = q;
697 if (p->p_stat == SSLEEP)
698 awaken(p);
699 }
700 splx(s);
701 }
702
703 /*
704 * General yield call. Puts the current process back on its run queue and
705 * performs a voluntary context switch.
706 */
707 void
708 yield()
709 {
710 struct proc *p = curproc;
711 int s;
712
713 p->p_priority = p->p_usrpri;
714 s = splstatclock();
715 setrunqueue(p);
716 p->p_stats->p_ru.ru_nvcsw++;
717 mi_switch();
718 splx(s);
719 }
720
721 /*
722 * General preemption call. Puts the current process back on its run queue
723 * and performs an involuntary context switch. If a process is supplied,
724 * we switch to that process. Otherwise, we use the normal process selection
725 * criteria.
726 */
727 void
728 preempt(newp)
729 struct proc *newp;
730 {
731 struct proc *p = curproc;
732 int s;
733
734 /*
735 * XXX Switching to a specific process is not supported yet.
736 */
737 if (newp != NULL)
738 panic("preempt: cpu_preempt not yet implemented");
739
740 p->p_priority = p->p_usrpri;
741 s = splstatclock();
742 setrunqueue(p);
743 p->p_stats->p_ru.ru_nivcsw++;
744 mi_switch();
745 splx(s);
746 }
747
748 /*
749 * The machine independent parts of mi_switch().
750 * Must be called at splstatclock() or higher.
751 */
752 void
753 mi_switch()
754 {
755 register struct proc *p = curproc; /* XXX */
756 register struct rlimit *rlim;
757 register long s, u;
758 struct timeval tv;
759
760 #ifdef DEBUG
761 if (p->p_simple_locks) {
762 printf("p->p_simple_locks %d\n", p->p_simple_locks);
763 #ifdef LOCKDEBUG
764 simple_lock_dump();
765 #endif
766 panic("sleep: holding simple lock");
767 }
768 #endif
769 /*
770 * Compute the amount of time during which the current
771 * process was running, and add that to its total so far.
772 */
773 microtime(&tv);
774 u = p->p_rtime.tv_usec + (tv.tv_usec - runtime.tv_usec);
775 s = p->p_rtime.tv_sec + (tv.tv_sec - runtime.tv_sec);
776 if (u < 0) {
777 u += 1000000;
778 s--;
779 } else if (u >= 1000000) {
780 u -= 1000000;
781 s++;
782 }
783 p->p_rtime.tv_usec = u;
784 p->p_rtime.tv_sec = s;
785
786 /*
787 * Check if the process exceeds its cpu resource allocation.
788 * If over max, kill it. In any case, if it has run for more
789 * than 10 minutes, reduce priority to give others a chance.
790 */
791 rlim = &p->p_rlimit[RLIMIT_CPU];
792 if (s >= rlim->rlim_cur) {
793 if (s >= rlim->rlim_max)
794 psignal(p, SIGKILL);
795 else {
796 psignal(p, SIGXCPU);
797 if (rlim->rlim_cur < rlim->rlim_max)
798 rlim->rlim_cur += 5;
799 }
800 }
801 if (autonicetime && s > autonicetime && p->p_ucred->cr_uid && p->p_nice == NZERO) {
802 p->p_nice = autoniceval + NZERO;
803 resetpriority(p);
804 }
805
806 /*
807 * Process is about to yield the CPU; clear the appropriate
808 * scheduling flags.
809 */
810 p->p_schedflags &= ~PSCHED_SWITCHCLEAR;
811
812 /*
813 * Pick a new current process and record its start time.
814 */
815 uvmexp.swtch++;
816 cpu_switch(p);
817 microtime(&runtime);
818 }
819
820 /*
821 * Initialize the (doubly-linked) run queues
822 * to be empty.
823 */
824 void
825 rqinit()
826 {
827 register int i;
828
829 for (i = 0; i < NQS; i++)
830 qs[i].ph_link = qs[i].ph_rlink = (struct proc *)&qs[i];
831 }
832
833 /*
834 * Change process state to be runnable,
835 * placing it on the run queue if it is in memory,
836 * and awakening the swapper if it isn't in memory.
837 */
838 void
839 setrunnable(p)
840 register struct proc *p;
841 {
842 register int s;
843
844 s = splhigh();
845 switch (p->p_stat) {
846 case 0:
847 case SRUN:
848 case SZOMB:
849 case SDEAD:
850 default:
851 panic("setrunnable");
852 case SSTOP:
853 /*
854 * If we're being traced (possibly because someone attached us
855 * while we were stopped), check for a signal from the debugger.
856 */
857 if ((p->p_flag & P_TRACED) != 0 && p->p_xstat != 0) {
858 sigaddset(&p->p_siglist, p->p_xstat);
859 p->p_sigcheck = 1;
860 }
861 case SSLEEP:
862 unsleep(p); /* e.g. when sending signals */
863 break;
864
865 case SIDL:
866 break;
867 }
868 p->p_stat = SRUN;
869 if (p->p_flag & P_INMEM)
870 setrunqueue(p);
871 splx(s);
872 if (p->p_slptime > 1)
873 updatepri(p);
874 p->p_slptime = 0;
875 if ((p->p_flag & P_INMEM) == 0)
876 wakeup((caddr_t)&proc0);
877 else if (p->p_priority < curpriority)
878 need_resched();
879 }
880
881 /*
882 * Compute the priority of a process when running in user mode.
883 * Arrange to reschedule if the resulting priority is better
884 * than that of the current process.
885 */
886 void
887 resetpriority(p)
888 register struct proc *p;
889 {
890 register unsigned int newpriority;
891
892 newpriority = PUSER + p->p_estcpu + NICE_WEIGHT * (p->p_nice - NZERO);
893 newpriority = min(newpriority, MAXPRI);
894 p->p_usrpri = newpriority;
895 if (newpriority < curpriority)
896 need_resched();
897 }
898
899 /*
900 * We adjust the priority of the current process. The priority of a process
901 * gets worse as it accumulates CPU time. The cpu usage estimator (p_estcpu)
902 * is increased here. The formula for computing priorities (in kern_synch.c)
903 * will compute a different value each time p_estcpu increases. This can
904 * cause a switch, but unless the priority crosses a PPQ boundary the actual
905 * queue will not change. The cpu usage estimator ramps up quite quickly
906 * when the process is running (linearly), and decays away exponentially, at
907 * a rate which is proportionally slower when the system is busy. The basic
908 * principal is that the system will 90% forget that the process used a lot
909 * of CPU time in 5 * loadav seconds. This causes the system to favor
910 * processes which haven't run much recently, and to round-robin among other
911 * processes.
912 */
913
914 void
915 schedclock(p)
916 struct proc *p;
917 {
918 p->p_estcpu = ESTCPULIM(p->p_estcpu + 1);
919 resetpriority(p);
920 if (p->p_priority >= PUSER)
921 p->p_priority = p->p_usrpri;
922 }
923