kern_synch.c revision 1.75 1 /* $NetBSD: kern_synch.c,v 1.75 2000/05/27 05:00:48 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 #include <machine/cpu.h>
101
102 int lbolt; /* once a second sleep address */
103
104 /*
105 * The global scheduler state.
106 */
107 struct prochd sched_qs[RUNQUE_NQS]; /* run queues */
108 __volatile u_int32_t sched_whichqs; /* bitmap of non-empty queues */
109 struct slpque sched_slpque[SLPQUE_TABLESIZE]; /* sleep queues */
110
111 void roundrobin __P((void *));
112 void schedcpu __P((void *));
113 void updatepri __P((struct proc *));
114 void endtsleep __P((void *));
115
116 __inline void awaken __P((struct proc *));
117
118 struct callout roundrobin_ch = CALLOUT_INITIALIZER;
119 struct callout schedcpu_ch = CALLOUT_INITIALIZER;
120
121 /*
122 * Force switch among equal priority processes every 100ms.
123 */
124 /* ARGSUSED */
125 void
126 roundrobin(arg)
127 void *arg;
128 {
129 struct schedstate_percpu *spc = &curcpu()->ci_schedstate;
130 int s;
131
132 if (curproc != NULL) {
133 s = splstatclock();
134 if (spc->spc_flags & SPCF_SEENRR) {
135 /*
136 * The process has already been through a roundrobin
137 * without switching and may be hogging the CPU.
138 * Indicate that the process should yield.
139 */
140 spc->spc_flags |= SPCF_SHOULDYIELD;
141 } else
142 spc->spc_flags |= SPCF_SEENRR;
143 splx(s);
144 }
145 need_resched();
146 callout_reset(&roundrobin_ch, hz / 10, roundrobin, NULL);
147 }
148
149 /*
150 * Constants for digital decay and forget:
151 * 90% of (p_estcpu) usage in 5 * loadav time
152 * 95% of (p_pctcpu) usage in 60 seconds (load insensitive)
153 * Note that, as ps(1) mentions, this can let percentages
154 * total over 100% (I've seen 137.9% for 3 processes).
155 *
156 * Note that hardclock updates p_estcpu and p_cpticks independently.
157 *
158 * We wish to decay away 90% of p_estcpu in (5 * loadavg) seconds.
159 * That is, the system wants to compute a value of decay such
160 * that the following for loop:
161 * for (i = 0; i < (5 * loadavg); i++)
162 * p_estcpu *= decay;
163 * will compute
164 * p_estcpu *= 0.1;
165 * for all values of loadavg:
166 *
167 * Mathematically this loop can be expressed by saying:
168 * decay ** (5 * loadavg) ~= .1
169 *
170 * The system computes decay as:
171 * decay = (2 * loadavg) / (2 * loadavg + 1)
172 *
173 * We wish to prove that the system's computation of decay
174 * will always fulfill the equation:
175 * decay ** (5 * loadavg) ~= .1
176 *
177 * If we compute b as:
178 * b = 2 * loadavg
179 * then
180 * decay = b / (b + 1)
181 *
182 * We now need to prove two things:
183 * 1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
184 * 2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
185 *
186 * Facts:
187 * For x close to zero, exp(x) =~ 1 + x, since
188 * exp(x) = 0! + x**1/1! + x**2/2! + ... .
189 * therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
190 * For x close to zero, ln(1+x) =~ x, since
191 * ln(1+x) = x - x**2/2 + x**3/3 - ... -1 < x < 1
192 * therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
193 * ln(.1) =~ -2.30
194 *
195 * Proof of (1):
196 * Solve (factor)**(power) =~ .1 given power (5*loadav):
197 * solving for factor,
198 * ln(factor) =~ (-2.30/5*loadav), or
199 * factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
200 * exp(-1/b) =~ (b-1)/b =~ b/(b+1). QED
201 *
202 * Proof of (2):
203 * Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
204 * solving for power,
205 * power*ln(b/(b+1)) =~ -2.30, or
206 * power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav. QED
207 *
208 * Actual power values for the implemented algorithm are as follows:
209 * loadav: 1 2 3 4
210 * power: 5.68 10.32 14.94 19.55
211 */
212
213 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
214 #define loadfactor(loadav) (2 * (loadav))
215 #define decay_cpu(loadfac, cpu) (((loadfac) * (cpu)) / ((loadfac) + FSCALE))
216
217 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
218 fixpt_t ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
219
220 /*
221 * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
222 * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
223 * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
224 *
225 * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
226 * 1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
227 *
228 * If you dont want to bother with the faster/more-accurate formula, you
229 * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
230 * (more general) method of calculating the %age of CPU used by a process.
231 */
232 #define CCPU_SHIFT 11
233
234 /*
235 * Recompute process priorities, every hz ticks.
236 */
237 /* ARGSUSED */
238 void
239 schedcpu(arg)
240 void *arg;
241 {
242 fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
243 struct proc *p;
244 int s;
245 unsigned int newcpu;
246 int clkhz;
247
248 proclist_lock_read();
249 for (p = allproc.lh_first; p != 0; p = p->p_list.le_next) {
250 /*
251 * Increment time in/out of memory and sleep time
252 * (if sleeping). We ignore overflow; with 16-bit int's
253 * (remember them?) overflow takes 45 days.
254 */
255 p->p_swtime++;
256 if (p->p_stat == SSLEEP || p->p_stat == SSTOP)
257 p->p_slptime++;
258 p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
259 /*
260 * If the process has slept the entire second,
261 * stop recalculating its priority until it wakes up.
262 */
263 if (p->p_slptime > 1)
264 continue;
265 s = splstatclock(); /* prevent state changes */
266 /*
267 * p_pctcpu is only for ps.
268 */
269 clkhz = stathz != 0 ? stathz : hz;
270 #if (FSHIFT >= CCPU_SHIFT)
271 p->p_pctcpu += (clkhz == 100)?
272 ((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT):
273 100 * (((fixpt_t) p->p_cpticks)
274 << (FSHIFT - CCPU_SHIFT)) / clkhz;
275 #else
276 p->p_pctcpu += ((FSCALE - ccpu) *
277 (p->p_cpticks * FSCALE / clkhz)) >> FSHIFT;
278 #endif
279 p->p_cpticks = 0;
280 newcpu = (u_int)decay_cpu(loadfac, p->p_estcpu);
281 p->p_estcpu = newcpu;
282 resetpriority(p);
283 if (p->p_priority >= PUSER) {
284 if (p->p_stat == SRUN &&
285 (p->p_flag & P_INMEM) &&
286 (p->p_priority / PPQ) != (p->p_usrpri / PPQ)) {
287 remrunqueue(p);
288 p->p_priority = p->p_usrpri;
289 setrunqueue(p);
290 } else
291 p->p_priority = p->p_usrpri;
292 }
293 splx(s);
294 }
295 proclist_unlock_read();
296 uvm_meter();
297 wakeup((caddr_t)&lbolt);
298 callout_reset(&schedcpu_ch, hz, schedcpu, NULL);
299 }
300
301 /*
302 * Recalculate the priority of a process after it has slept for a while.
303 * For all load averages >= 1 and max p_estcpu of 255, sleeping for at
304 * least six times the loadfactor will decay p_estcpu to zero.
305 */
306 void
307 updatepri(p)
308 struct proc *p;
309 {
310 unsigned int newcpu = p->p_estcpu;
311 fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
312
313 if (p->p_slptime > 5 * loadfac)
314 p->p_estcpu = 0;
315 else {
316 p->p_slptime--; /* the first time was done in schedcpu */
317 while (newcpu && --p->p_slptime)
318 newcpu = (int) decay_cpu(loadfac, newcpu);
319 p->p_estcpu = newcpu;
320 }
321 resetpriority(p);
322 }
323
324 /*
325 * During autoconfiguration or after a panic, a sleep will simply
326 * lower the priority briefly to allow interrupts, then return.
327 * The priority to be used (safepri) is machine-dependent, thus this
328 * value is initialized and maintained in the machine-dependent layers.
329 * This priority will typically be 0, or the lowest priority
330 * that is safe for use on the interrupt stack; it can be made
331 * higher to block network software interrupts after panics.
332 */
333 int safepri;
334
335 /*
336 * General sleep call. Suspends the current process until a wakeup is
337 * performed on the specified identifier. The process will then be made
338 * runnable with the specified priority. Sleeps at most timo/hz seconds
339 * (0 means no timeout). If pri includes PCATCH flag, signals are checked
340 * before and after sleeping, else signals are not checked. Returns 0 if
341 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a
342 * signal needs to be delivered, ERESTART is returned if the current system
343 * call should be restarted if possible, and EINTR is returned if the system
344 * call should be interrupted by the signal (return EINTR).
345 */
346 int
347 tsleep(ident, priority, wmesg, timo)
348 void *ident;
349 int priority, timo;
350 const char *wmesg;
351 {
352 struct proc *p = curproc;
353 struct slpque *qp;
354 int s;
355 int sig, catch = priority & PCATCH;
356
357 if (cold || panicstr) {
358 /*
359 * After a panic, or during autoconfiguration,
360 * just give interrupts a chance, then just return;
361 * don't run any other procs or panic below,
362 * in case this is the idle process and already asleep.
363 */
364 s = splhigh();
365 splx(safepri);
366 splx(s);
367 return (0);
368 }
369
370 #ifdef KTRACE
371 if (KTRPOINT(p, KTR_CSW))
372 ktrcsw(p, 1, 0);
373 #endif
374 s = splhigh();
375
376 #ifdef DIAGNOSTIC
377 if (ident == NULL)
378 panic("tsleep: ident == NULL");
379 if (p->p_stat != SONPROC)
380 panic("tsleep: p_stat %d != SONPROC", p->p_stat);
381 if (p->p_back != NULL)
382 panic("tsleep: p_back != NULL");
383 #endif
384 p->p_wchan = ident;
385 p->p_wmesg = wmesg;
386 p->p_slptime = 0;
387 p->p_priority = priority & PRIMASK;
388 qp = SLPQUE(ident);
389 if (qp->sq_head == 0)
390 qp->sq_head = p;
391 else
392 *qp->sq_tailp = p;
393 *(qp->sq_tailp = &p->p_forw) = 0;
394 if (timo)
395 callout_reset(&p->p_tsleep_ch, timo, endtsleep, p);
396 /*
397 * We put ourselves on the sleep queue and start our timeout
398 * before calling CURSIG, as we could stop there, and a wakeup
399 * or a SIGCONT (or both) could occur while we were stopped.
400 * A SIGCONT would cause us to be marked as SSLEEP
401 * without resuming us, thus we must be ready for sleep
402 * when CURSIG is called. If the wakeup happens while we're
403 * stopped, p->p_wchan will be 0 upon return from CURSIG.
404 */
405 if (catch) {
406 p->p_flag |= P_SINTR;
407 if ((sig = CURSIG(p)) != 0) {
408 if (p->p_wchan)
409 unsleep(p);
410 p->p_stat = SONPROC;
411 goto resume;
412 }
413 if (p->p_wchan == 0) {
414 catch = 0;
415 goto resume;
416 }
417 } else
418 sig = 0;
419 p->p_stat = SSLEEP;
420 p->p_stats->p_ru.ru_nvcsw++;
421 mi_switch(p);
422 #ifdef DDB
423 /* handy breakpoint location after process "wakes" */
424 asm(".globl bpendtsleep ; bpendtsleep:");
425 #endif
426 resume:
427 curcpu()->ci_schedstate.spc_curpriority = p->p_usrpri;
428 splx(s);
429 p->p_flag &= ~P_SINTR;
430 if (p->p_flag & P_TIMEOUT) {
431 p->p_flag &= ~P_TIMEOUT;
432 if (sig == 0) {
433 #ifdef KTRACE
434 if (KTRPOINT(p, KTR_CSW))
435 ktrcsw(p, 0, 0);
436 #endif
437 return (EWOULDBLOCK);
438 }
439 } else if (timo)
440 callout_stop(&p->p_tsleep_ch);
441 if (catch && (sig != 0 || (sig = CURSIG(p)) != 0)) {
442 #ifdef KTRACE
443 if (KTRPOINT(p, KTR_CSW))
444 ktrcsw(p, 0, 0);
445 #endif
446 if ((p->p_sigacts->ps_sigact[sig].sa_flags & SA_RESTART) == 0)
447 return (EINTR);
448 return (ERESTART);
449 }
450 #ifdef KTRACE
451 if (KTRPOINT(p, KTR_CSW))
452 ktrcsw(p, 0, 0);
453 #endif
454 return (0);
455 }
456
457 /*
458 * Implement timeout for tsleep.
459 * If process hasn't been awakened (wchan non-zero),
460 * set timeout flag and undo the sleep. If proc
461 * is stopped, just unsleep so it will remain stopped.
462 */
463 void
464 endtsleep(arg)
465 void *arg;
466 {
467 struct proc *p;
468 int s;
469
470 p = (struct proc *)arg;
471 s = splhigh();
472 if (p->p_wchan) {
473 if (p->p_stat == SSLEEP)
474 setrunnable(p);
475 else
476 unsleep(p);
477 p->p_flag |= P_TIMEOUT;
478 }
479 splx(s);
480 }
481
482 /*
483 * Remove a process from its wait queue
484 */
485 void
486 unsleep(p)
487 struct proc *p;
488 {
489 struct slpque *qp;
490 struct proc **hp;
491 int s;
492
493 s = splhigh();
494 if (p->p_wchan) {
495 hp = &(qp = SLPQUE(p->p_wchan))->sq_head;
496 while (*hp != p)
497 hp = &(*hp)->p_forw;
498 *hp = p->p_forw;
499 if (qp->sq_tailp == &p->p_forw)
500 qp->sq_tailp = hp;
501 p->p_wchan = 0;
502 }
503 splx(s);
504 }
505
506 /*
507 * Optimized-for-wakeup() version of setrunnable().
508 */
509 __inline void
510 awaken(p)
511 struct proc *p;
512 {
513
514 if (p->p_slptime > 1)
515 updatepri(p);
516 p->p_slptime = 0;
517 p->p_stat = SRUN;
518 /*
519 * Since curpriority is a user priority, p->p_priority
520 * is always better than curpriority.
521 */
522 if (p->p_flag & P_INMEM) {
523 setrunqueue(p);
524 need_resched();
525 } else
526 wakeup((caddr_t)&proc0);
527 }
528
529 /*
530 * Make all processes sleeping on the specified identifier runnable.
531 */
532 void
533 wakeup(ident)
534 void *ident;
535 {
536 struct slpque *qp;
537 struct proc *p, **q;
538 int s;
539
540 s = splhigh();
541 qp = SLPQUE(ident);
542 restart:
543 for (q = &qp->sq_head; (p = *q) != NULL; ) {
544 #ifdef DIAGNOSTIC
545 if (p->p_back || (p->p_stat != SSLEEP && p->p_stat != SSTOP))
546 panic("wakeup");
547 #endif
548 if (p->p_wchan == ident) {
549 p->p_wchan = 0;
550 *q = p->p_forw;
551 if (qp->sq_tailp == &p->p_forw)
552 qp->sq_tailp = q;
553 if (p->p_stat == SSLEEP) {
554 awaken(p);
555 goto restart;
556 }
557 } else
558 q = &p->p_forw;
559 }
560 splx(s);
561 }
562
563 /*
564 * Make the highest priority process first in line on the specified
565 * identifier runnable.
566 */
567 void
568 wakeup_one(ident)
569 void *ident;
570 {
571 struct slpque *qp;
572 struct proc *p, **q;
573 struct proc *best_sleepp, **best_sleepq;
574 struct proc *best_stopp, **best_stopq;
575 int s;
576
577 best_sleepp = best_stopp = NULL;
578 best_sleepq = best_stopq = NULL;
579
580 s = splhigh();
581 qp = SLPQUE(ident);
582 for (q = &qp->sq_head; (p = *q) != NULL; q = &p->p_forw) {
583 #ifdef DIAGNOSTIC
584 if (p->p_back || (p->p_stat != SSLEEP && p->p_stat != SSTOP))
585 panic("wakeup_one");
586 #endif
587 if (p->p_wchan == ident) {
588 if (p->p_stat == SSLEEP) {
589 if (best_sleepp == NULL ||
590 p->p_priority < best_sleepp->p_priority) {
591 best_sleepp = p;
592 best_sleepq = q;
593 }
594 } else {
595 if (best_stopp == NULL ||
596 p->p_priority < best_stopp->p_priority) {
597 best_stopp = p;
598 best_stopq = q;
599 }
600 }
601 }
602 }
603
604 /*
605 * Consider any SSLEEP process higher than the highest priority SSTOP
606 * process.
607 */
608 if (best_sleepp != NULL) {
609 p = best_sleepp;
610 q = best_sleepq;
611 } else {
612 p = best_stopp;
613 q = best_stopq;
614 }
615
616 if (p != NULL) {
617 p->p_wchan = 0;
618 *q = p->p_forw;
619 if (qp->sq_tailp == &p->p_forw)
620 qp->sq_tailp = q;
621 if (p->p_stat == SSLEEP)
622 awaken(p);
623 }
624 splx(s);
625 }
626
627 /*
628 * General yield call. Puts the current process back on its run queue and
629 * performs a voluntary context switch.
630 */
631 void
632 yield()
633 {
634 struct proc *p = curproc;
635 int s;
636
637 s = splstatclock();
638 p->p_priority = p->p_usrpri;
639 p->p_stat = SRUN;
640 setrunqueue(p);
641 p->p_stats->p_ru.ru_nvcsw++;
642 mi_switch(p);
643 splx(s);
644 }
645
646 /*
647 * General preemption call. Puts the current process back on its run queue
648 * and performs an involuntary context switch. If a process is supplied,
649 * we switch to that process. Otherwise, we use the normal process selection
650 * criteria.
651 */
652 void
653 preempt(newp)
654 struct proc *newp;
655 {
656 struct proc *p = curproc;
657 int s;
658
659 /*
660 * XXX Switching to a specific process is not supported yet.
661 */
662 if (newp != NULL)
663 panic("preempt: cpu_preempt not yet implemented");
664
665 s = splstatclock();
666 p->p_priority = p->p_usrpri;
667 p->p_stat = SRUN;
668 setrunqueue(p);
669 p->p_stats->p_ru.ru_nivcsw++;
670 mi_switch(p);
671 splx(s);
672 }
673
674 /*
675 * The machine independent parts of context switch.
676 * Must be called at splstatclock() or higher.
677 */
678 void
679 mi_switch(p)
680 struct proc *p;
681 {
682 struct schedstate_percpu *spc = &curcpu()->ci_schedstate;
683 struct rlimit *rlim;
684 long s, u;
685 struct timeval tv;
686
687 #ifdef DEBUG
688 if (p->p_simple_locks) {
689 printf("p->p_simple_locks %d\n", p->p_simple_locks);
690 #ifdef LOCKDEBUG
691 simple_lock_dump();
692 #endif
693 panic("sleep: holding simple lock");
694 }
695 #endif
696 /*
697 * Compute the amount of time during which the current
698 * process was running, and add that to its total so far.
699 */
700 microtime(&tv);
701 u = p->p_rtime.tv_usec + (tv.tv_usec - spc->spc_runtime.tv_usec);
702 s = p->p_rtime.tv_sec + (tv.tv_sec - spc->spc_runtime.tv_sec);
703 if (u < 0) {
704 u += 1000000;
705 s--;
706 } else if (u >= 1000000) {
707 u -= 1000000;
708 s++;
709 }
710 p->p_rtime.tv_usec = u;
711 p->p_rtime.tv_sec = s;
712
713 /*
714 * Check if the process exceeds its cpu resource allocation.
715 * If over max, kill it. In any case, if it has run for more
716 * than 10 minutes, reduce priority to give others a chance.
717 */
718 rlim = &p->p_rlimit[RLIMIT_CPU];
719 if (s >= rlim->rlim_cur) {
720 if (s >= rlim->rlim_max)
721 psignal(p, SIGKILL);
722 else {
723 psignal(p, SIGXCPU);
724 if (rlim->rlim_cur < rlim->rlim_max)
725 rlim->rlim_cur += 5;
726 }
727 }
728 if (autonicetime && s > autonicetime && p->p_ucred->cr_uid && p->p_nice == NZERO) {
729 p->p_nice = autoniceval + NZERO;
730 resetpriority(p);
731 }
732
733 /*
734 * Process is about to yield the CPU; clear the appropriate
735 * scheduling flags.
736 */
737 spc->spc_flags &= ~SPCF_SWITCHCLEAR;
738
739 /*
740 * Pick a new current process and record its start time.
741 */
742 uvmexp.swtch++;
743 cpu_switch(p);
744 microtime(&spc->spc_runtime);
745 }
746
747 /*
748 * Initialize the (doubly-linked) run queues
749 * to be empty.
750 */
751 void
752 rqinit()
753 {
754 int i;
755
756 for (i = 0; i < RUNQUE_NQS; i++)
757 sched_qs[i].ph_link = sched_qs[i].ph_rlink =
758 (struct proc *)&sched_qs[i];
759 }
760
761 /*
762 * Change process state to be runnable,
763 * placing it on the run queue if it is in memory,
764 * and awakening the swapper if it isn't in memory.
765 */
766 void
767 setrunnable(p)
768 struct proc *p;
769 {
770 int s;
771
772 s = splhigh();
773 switch (p->p_stat) {
774 case 0:
775 case SRUN:
776 case SONPROC:
777 case SZOMB:
778 case SDEAD:
779 default:
780 panic("setrunnable");
781 case SSTOP:
782 /*
783 * If we're being traced (possibly because someone attached us
784 * while we were stopped), check for a signal from the debugger.
785 */
786 if ((p->p_flag & P_TRACED) != 0 && p->p_xstat != 0) {
787 sigaddset(&p->p_siglist, p->p_xstat);
788 p->p_sigcheck = 1;
789 }
790 case SSLEEP:
791 unsleep(p); /* e.g. when sending signals */
792 break;
793
794 case SIDL:
795 break;
796 }
797 p->p_stat = SRUN;
798 if (p->p_flag & P_INMEM)
799 setrunqueue(p);
800 splx(s);
801 if (p->p_slptime > 1)
802 updatepri(p);
803 p->p_slptime = 0;
804 if ((p->p_flag & P_INMEM) == 0)
805 wakeup((caddr_t)&proc0);
806 else if (p->p_priority < curcpu()->ci_schedstate.spc_curpriority)
807 need_resched();
808 }
809
810 /*
811 * Compute the priority of a process when running in user mode.
812 * Arrange to reschedule if the resulting priority is better
813 * than that of the current process.
814 */
815 void
816 resetpriority(p)
817 struct proc *p;
818 {
819 unsigned int newpriority;
820
821 newpriority = PUSER + p->p_estcpu + NICE_WEIGHT * (p->p_nice - NZERO);
822 newpriority = min(newpriority, MAXPRI);
823 p->p_usrpri = newpriority;
824 if (newpriority < curcpu()->ci_schedstate.spc_curpriority)
825 need_resched();
826 }
827
828 /*
829 * We adjust the priority of the current process. The priority of a process
830 * gets worse as it accumulates CPU time. The cpu usage estimator (p_estcpu)
831 * is increased here. The formula for computing priorities (in kern_synch.c)
832 * will compute a different value each time p_estcpu increases. This can
833 * cause a switch, but unless the priority crosses a PPQ boundary the actual
834 * queue will not change. The cpu usage estimator ramps up quite quickly
835 * when the process is running (linearly), and decays away exponentially, at
836 * a rate which is proportionally slower when the system is busy. The basic
837 * principal is that the system will 90% forget that the process used a lot
838 * of CPU time in 5 * loadav seconds. This causes the system to favor
839 * processes which haven't run much recently, and to round-robin among other
840 * processes.
841 */
842
843 void
844 schedclock(p)
845 struct proc *p;
846 {
847 p->p_estcpu = ESTCPULIM(p->p_estcpu + 1);
848 resetpriority(p);
849 if (p->p_priority >= PUSER)
850 p->p_priority = p->p_usrpri;
851 }
852