kern_synch.c revision 1.107.8.2 1 /* $NetBSD: kern_synch.c,v 1.107.8.2 2002/07/15 10:36:35 gehenna 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 <sys/cdefs.h>
81 __KERNEL_RCSID(0, "$NetBSD: kern_synch.c,v 1.107.8.2 2002/07/15 10:36:35 gehenna Exp $");
82
83 #include "opt_ddb.h"
84 #include "opt_ktrace.h"
85 #include "opt_kstack.h"
86 #include "opt_lockdebug.h"
87 #include "opt_multiprocessor.h"
88
89 #include <sys/param.h>
90 #include <sys/systm.h>
91 #include <sys/callout.h>
92 #include <sys/proc.h>
93 #include <sys/kernel.h>
94 #include <sys/buf.h>
95 #include <sys/signalvar.h>
96 #include <sys/resourcevar.h>
97 #include <sys/sched.h>
98
99 #include <uvm/uvm_extern.h>
100
101 #ifdef KTRACE
102 #include <sys/ktrace.h>
103 #endif
104
105 #include <machine/cpu.h>
106
107 int lbolt; /* once a second sleep address */
108 int rrticks; /* number of hardclock ticks per roundrobin() */
109
110 /*
111 * The global scheduler state.
112 */
113 struct prochd sched_qs[RUNQUE_NQS]; /* run queues */
114 __volatile u_int32_t sched_whichqs; /* bitmap of non-empty queues */
115 struct slpque sched_slpque[SLPQUE_TABLESIZE]; /* sleep queues */
116
117 struct simplelock sched_lock = SIMPLELOCK_INITIALIZER;
118
119 void schedcpu(void *);
120 void updatepri(struct proc *);
121 void endtsleep(void *);
122
123 __inline void awaken(struct proc *);
124
125 struct callout schedcpu_ch = CALLOUT_INITIALIZER;
126
127 /*
128 * Force switch among equal priority processes every 100ms.
129 * Called from hardclock every hz/10 == rrticks hardclock ticks.
130 */
131 /* ARGSUSED */
132 void
133 roundrobin(struct cpu_info *ci)
134 {
135 struct schedstate_percpu *spc = &ci->ci_schedstate;
136
137 spc->spc_rrticks = rrticks;
138
139 if (curproc != NULL) {
140 if (spc->spc_flags & SPCF_SEENRR) {
141 /*
142 * The process has already been through a roundrobin
143 * without switching and may be hogging the CPU.
144 * Indicate that the process should yield.
145 */
146 spc->spc_flags |= SPCF_SHOULDYIELD;
147 } else
148 spc->spc_flags |= SPCF_SEENRR;
149 }
150 need_resched(curcpu());
151 }
152
153 /*
154 * Constants for digital decay and forget:
155 * 90% of (p_estcpu) usage in 5 * loadav time
156 * 95% of (p_pctcpu) usage in 60 seconds (load insensitive)
157 * Note that, as ps(1) mentions, this can let percentages
158 * total over 100% (I've seen 137.9% for 3 processes).
159 *
160 * Note that hardclock updates p_estcpu and p_cpticks independently.
161 *
162 * We wish to decay away 90% of p_estcpu in (5 * loadavg) seconds.
163 * That is, the system wants to compute a value of decay such
164 * that the following for loop:
165 * for (i = 0; i < (5 * loadavg); i++)
166 * p_estcpu *= decay;
167 * will compute
168 * p_estcpu *= 0.1;
169 * for all values of loadavg:
170 *
171 * Mathematically this loop can be expressed by saying:
172 * decay ** (5 * loadavg) ~= .1
173 *
174 * The system computes decay as:
175 * decay = (2 * loadavg) / (2 * loadavg + 1)
176 *
177 * We wish to prove that the system's computation of decay
178 * will always fulfill the equation:
179 * decay ** (5 * loadavg) ~= .1
180 *
181 * If we compute b as:
182 * b = 2 * loadavg
183 * then
184 * decay = b / (b + 1)
185 *
186 * We now need to prove two things:
187 * 1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
188 * 2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
189 *
190 * Facts:
191 * For x close to zero, exp(x) =~ 1 + x, since
192 * exp(x) = 0! + x**1/1! + x**2/2! + ... .
193 * therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
194 * For x close to zero, ln(1+x) =~ x, since
195 * ln(1+x) = x - x**2/2 + x**3/3 - ... -1 < x < 1
196 * therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
197 * ln(.1) =~ -2.30
198 *
199 * Proof of (1):
200 * Solve (factor)**(power) =~ .1 given power (5*loadav):
201 * solving for factor,
202 * ln(factor) =~ (-2.30/5*loadav), or
203 * factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
204 * exp(-1/b) =~ (b-1)/b =~ b/(b+1). QED
205 *
206 * Proof of (2):
207 * Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
208 * solving for power,
209 * power*ln(b/(b+1)) =~ -2.30, or
210 * power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav. QED
211 *
212 * Actual power values for the implemented algorithm are as follows:
213 * loadav: 1 2 3 4
214 * power: 5.68 10.32 14.94 19.55
215 */
216
217 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
218 #define loadfactor(loadav) (2 * (loadav))
219 #define decay_cpu(loadfac, cpu) (((loadfac) * (cpu)) / ((loadfac) + FSCALE))
220
221 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
222 fixpt_t ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
223
224 /*
225 * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
226 * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
227 * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
228 *
229 * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
230 * 1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
231 *
232 * If you dont want to bother with the faster/more-accurate formula, you
233 * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
234 * (more general) method of calculating the %age of CPU used by a process.
235 */
236 #define CCPU_SHIFT 11
237
238 /*
239 * Recompute process priorities, every hz ticks.
240 */
241 /* ARGSUSED */
242 void
243 schedcpu(void *arg)
244 {
245 fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
246 struct proc *p;
247 int s, s1;
248 unsigned int newcpu;
249 int clkhz;
250
251 proclist_lock_read();
252 for (p = allproc.lh_first; p != 0; p = p->p_list.le_next) {
253 /*
254 * Increment time in/out of memory and sleep time
255 * (if sleeping). We ignore overflow; with 16-bit int's
256 * (remember them?) overflow takes 45 days.
257 */
258 p->p_swtime++;
259 if (p->p_stat == SSLEEP || p->p_stat == SSTOP)
260 p->p_slptime++;
261 p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
262 /*
263 * If the process has slept the entire second,
264 * stop recalculating its priority until it wakes up.
265 */
266 if (p->p_slptime > 1)
267 continue;
268 s = splstatclock(); /* prevent state changes */
269 /*
270 * p_pctcpu is only for ps.
271 */
272 clkhz = stathz != 0 ? stathz : hz;
273 #if (FSHIFT >= CCPU_SHIFT)
274 p->p_pctcpu += (clkhz == 100)?
275 ((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT):
276 100 * (((fixpt_t) p->p_cpticks)
277 << (FSHIFT - CCPU_SHIFT)) / clkhz;
278 #else
279 p->p_pctcpu += ((FSCALE - ccpu) *
280 (p->p_cpticks * FSCALE / clkhz)) >> FSHIFT;
281 #endif
282 p->p_cpticks = 0;
283 newcpu = (u_int)decay_cpu(loadfac, p->p_estcpu);
284 p->p_estcpu = newcpu;
285 SCHED_LOCK(s1);
286 resetpriority(p);
287 if (p->p_priority >= PUSER) {
288 if (p->p_stat == SRUN &&
289 (p->p_flag & P_INMEM) &&
290 (p->p_priority / PPQ) != (p->p_usrpri / PPQ)) {
291 remrunqueue(p);
292 p->p_priority = p->p_usrpri;
293 setrunqueue(p);
294 } else
295 p->p_priority = p->p_usrpri;
296 }
297 SCHED_UNLOCK(s1);
298 splx(s);
299 }
300 proclist_unlock_read();
301 uvm_meter();
302 wakeup((caddr_t)&lbolt);
303 callout_reset(&schedcpu_ch, hz, schedcpu, NULL);
304 }
305
306 /*
307 * Recalculate the priority of a process after it has slept for a while.
308 * For all load averages >= 1 and max p_estcpu of 255, sleeping for at
309 * least six times the loadfactor will decay p_estcpu to zero.
310 */
311 void
312 updatepri(struct proc *p)
313 {
314 unsigned int newcpu;
315 fixpt_t loadfac;
316
317 SCHED_ASSERT_LOCKED();
318
319 newcpu = p->p_estcpu;
320 loadfac = loadfactor(averunnable.ldavg[0]);
321
322 if (p->p_slptime > 5 * loadfac)
323 p->p_estcpu = 0;
324 else {
325 p->p_slptime--; /* the first time was done in schedcpu */
326 while (newcpu && --p->p_slptime)
327 newcpu = (int) decay_cpu(loadfac, newcpu);
328 p->p_estcpu = newcpu;
329 }
330 resetpriority(p);
331 }
332
333 /*
334 * During autoconfiguration or after a panic, a sleep will simply
335 * lower the priority briefly to allow interrupts, then return.
336 * The priority to be used (safepri) is machine-dependent, thus this
337 * value is initialized and maintained in the machine-dependent layers.
338 * This priority will typically be 0, or the lowest priority
339 * that is safe for use on the interrupt stack; it can be made
340 * higher to block network software interrupts after panics.
341 */
342 int safepri;
343
344 /*
345 * General sleep call. Suspends the current process until a wakeup is
346 * performed on the specified identifier. The process will then be made
347 * runnable with the specified priority. Sleeps at most timo/hz seconds
348 * (0 means no timeout). If pri includes PCATCH flag, signals are checked
349 * before and after sleeping, else signals are not checked. Returns 0 if
350 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a
351 * signal needs to be delivered, ERESTART is returned if the current system
352 * call should be restarted if possible, and EINTR is returned if the system
353 * call should be interrupted by the signal (return EINTR).
354 *
355 * The interlock is held until the scheduler_slock is acquired. The
356 * interlock will be locked before returning back to the caller
357 * unless the PNORELOCK flag is specified, in which case the
358 * interlock will always be unlocked upon return.
359 */
360 int
361 ltsleep(void *ident, int priority, const char *wmesg, int timo,
362 __volatile struct simplelock *interlock)
363 {
364 struct proc *p = curproc;
365 struct slpque *qp;
366 int sig, s;
367 int catch = priority & PCATCH;
368 int relock = (priority & PNORELOCK) == 0;
369
370 /*
371 * XXXSMP
372 * This is probably bogus. Figure out what the right
373 * thing to do here really is.
374 * Note that not sleeping if ltsleep is called with curproc == NULL
375 * in the shutdown case is disgusting but partly necessary given
376 * how shutdown (barely) works.
377 */
378 if (cold || (doing_shutdown && (panicstr || (p == NULL)))) {
379 /*
380 * After a panic, or during autoconfiguration,
381 * just give interrupts a chance, then just return;
382 * don't run any other procs or panic below,
383 * in case this is the idle process and already asleep.
384 */
385 s = splhigh();
386 splx(safepri);
387 splx(s);
388 if (interlock != NULL && relock == 0)
389 simple_unlock(interlock);
390 return (0);
391 }
392
393 KASSERT(p != NULL);
394 LOCK_ASSERT(interlock == NULL || simple_lock_held(interlock));
395
396 #ifdef KTRACE
397 if (KTRPOINT(p, KTR_CSW))
398 ktrcsw(p, 1, 0);
399 #endif
400
401 SCHED_LOCK(s);
402
403 #ifdef DIAGNOSTIC
404 if (ident == NULL)
405 panic("ltsleep: ident == NULL");
406 if (p->p_stat != SONPROC)
407 panic("ltsleep: p_stat %d != SONPROC", p->p_stat);
408 if (p->p_back != NULL)
409 panic("ltsleep: p_back != NULL");
410 #endif
411
412 p->p_wchan = ident;
413 p->p_wmesg = wmesg;
414 p->p_slptime = 0;
415 p->p_priority = priority & PRIMASK;
416
417 qp = SLPQUE(ident);
418 if (qp->sq_head == 0)
419 qp->sq_head = p;
420 else
421 *qp->sq_tailp = p;
422 *(qp->sq_tailp = &p->p_forw) = 0;
423
424 if (timo)
425 callout_reset(&p->p_tsleep_ch, timo, endtsleep, p);
426
427 /*
428 * We can now release the interlock; the scheduler_slock
429 * is held, so a thread can't get in to do wakeup() before
430 * we do the switch.
431 *
432 * XXX We leave the code block here, after inserting ourselves
433 * on the sleep queue, because we might want a more clever
434 * data structure for the sleep queues at some point.
435 */
436 if (interlock != NULL)
437 simple_unlock(interlock);
438
439 /*
440 * We put ourselves on the sleep queue and start our timeout
441 * before calling CURSIG, as we could stop there, and a wakeup
442 * or a SIGCONT (or both) could occur while we were stopped.
443 * A SIGCONT would cause us to be marked as SSLEEP
444 * without resuming us, thus we must be ready for sleep
445 * when CURSIG is called. If the wakeup happens while we're
446 * stopped, p->p_wchan will be 0 upon return from CURSIG.
447 */
448 if (catch) {
449 p->p_flag |= P_SINTR;
450 if ((sig = CURSIG(p)) != 0) {
451 if (p->p_wchan != NULL)
452 unsleep(p);
453 p->p_stat = SONPROC;
454 SCHED_UNLOCK(s);
455 goto resume;
456 }
457 if (p->p_wchan == NULL) {
458 catch = 0;
459 SCHED_UNLOCK(s);
460 goto resume;
461 }
462 } else
463 sig = 0;
464 p->p_stat = SSLEEP;
465 p->p_stats->p_ru.ru_nvcsw++;
466
467 SCHED_ASSERT_LOCKED();
468 mi_switch(p);
469
470 #if defined(DDB) && !defined(GPROF)
471 /* handy breakpoint location after process "wakes" */
472 __asm(".globl bpendtsleep ; bpendtsleep:");
473 #endif
474
475 SCHED_ASSERT_UNLOCKED();
476 splx(s);
477
478 resume:
479 KDASSERT(p->p_cpu != NULL);
480 KDASSERT(p->p_cpu == curcpu());
481 p->p_cpu->ci_schedstate.spc_curpriority = p->p_usrpri;
482
483 p->p_flag &= ~P_SINTR;
484 if (p->p_flag & P_TIMEOUT) {
485 p->p_flag &= ~P_TIMEOUT;
486 if (sig == 0) {
487 #ifdef KTRACE
488 if (KTRPOINT(p, KTR_CSW))
489 ktrcsw(p, 0, 0);
490 #endif
491 if (relock && interlock != NULL)
492 simple_lock(interlock);
493 return (EWOULDBLOCK);
494 }
495 } else if (timo)
496 callout_stop(&p->p_tsleep_ch);
497 if (catch && (sig != 0 || (sig = CURSIG(p)) != 0)) {
498 #ifdef KTRACE
499 if (KTRPOINT(p, KTR_CSW))
500 ktrcsw(p, 0, 0);
501 #endif
502 if (relock && interlock != NULL)
503 simple_lock(interlock);
504 if ((SIGACTION(p, sig).sa_flags & SA_RESTART) == 0)
505 return (EINTR);
506 return (ERESTART);
507 }
508 #ifdef KTRACE
509 if (KTRPOINT(p, KTR_CSW))
510 ktrcsw(p, 0, 0);
511 #endif
512 if (relock && interlock != NULL)
513 simple_lock(interlock);
514 return (0);
515 }
516
517 /*
518 * Implement timeout for tsleep.
519 * If process hasn't been awakened (wchan non-zero),
520 * set timeout flag and undo the sleep. If proc
521 * is stopped, just unsleep so it will remain stopped.
522 */
523 void
524 endtsleep(void *arg)
525 {
526 struct proc *p;
527 int s;
528
529 p = (struct proc *)arg;
530
531 SCHED_LOCK(s);
532 if (p->p_wchan) {
533 if (p->p_stat == SSLEEP)
534 setrunnable(p);
535 else
536 unsleep(p);
537 p->p_flag |= P_TIMEOUT;
538 }
539 SCHED_UNLOCK(s);
540 }
541
542 /*
543 * Remove a process from its wait queue
544 */
545 void
546 unsleep(struct proc *p)
547 {
548 struct slpque *qp;
549 struct proc **hp;
550
551 SCHED_ASSERT_LOCKED();
552
553 if (p->p_wchan) {
554 hp = &(qp = SLPQUE(p->p_wchan))->sq_head;
555 while (*hp != p)
556 hp = &(*hp)->p_forw;
557 *hp = p->p_forw;
558 if (qp->sq_tailp == &p->p_forw)
559 qp->sq_tailp = hp;
560 p->p_wchan = 0;
561 }
562 }
563
564 /*
565 * Optimized-for-wakeup() version of setrunnable().
566 */
567 __inline void
568 awaken(struct proc *p)
569 {
570
571 SCHED_ASSERT_LOCKED();
572
573 if (p->p_slptime > 1)
574 updatepri(p);
575 p->p_slptime = 0;
576 p->p_stat = SRUN;
577
578 /*
579 * Since curpriority is a user priority, p->p_priority
580 * is always better than curpriority.
581 */
582 if (p->p_flag & P_INMEM) {
583 setrunqueue(p);
584 KASSERT(p->p_cpu != NULL);
585 need_resched(p->p_cpu);
586 } else
587 sched_wakeup(&proc0);
588 }
589
590 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
591 void
592 sched_unlock_idle(void)
593 {
594
595 simple_unlock(&sched_lock);
596 }
597
598 void
599 sched_lock_idle(void)
600 {
601
602 simple_lock(&sched_lock);
603 }
604 #endif /* MULTIPROCESSOR || LOCKDEBUG */
605
606 /*
607 * Make all processes sleeping on the specified identifier runnable.
608 */
609
610 void
611 wakeup(void *ident)
612 {
613 int s;
614
615 SCHED_ASSERT_UNLOCKED();
616
617 SCHED_LOCK(s);
618 sched_wakeup(ident);
619 SCHED_UNLOCK(s);
620 }
621
622 void
623 sched_wakeup(void *ident)
624 {
625 struct slpque *qp;
626 struct proc *p, **q;
627
628 SCHED_ASSERT_LOCKED();
629
630 qp = SLPQUE(ident);
631 restart:
632 for (q = &qp->sq_head; (p = *q) != NULL; ) {
633 #ifdef DIAGNOSTIC
634 if (p->p_back || (p->p_stat != SSLEEP && p->p_stat != SSTOP))
635 panic("wakeup");
636 #endif
637 if (p->p_wchan == ident) {
638 p->p_wchan = 0;
639 *q = p->p_forw;
640 if (qp->sq_tailp == &p->p_forw)
641 qp->sq_tailp = q;
642 if (p->p_stat == SSLEEP) {
643 awaken(p);
644 goto restart;
645 }
646 } else
647 q = &p->p_forw;
648 }
649 }
650
651 /*
652 * Make the highest priority process first in line on the specified
653 * identifier runnable.
654 */
655 void
656 wakeup_one(void *ident)
657 {
658 struct slpque *qp;
659 struct proc *p, **q;
660 struct proc *best_sleepp, **best_sleepq;
661 struct proc *best_stopp, **best_stopq;
662 int s;
663
664 best_sleepp = best_stopp = NULL;
665 best_sleepq = best_stopq = NULL;
666
667 SCHED_LOCK(s);
668
669 qp = SLPQUE(ident);
670
671 for (q = &qp->sq_head; (p = *q) != NULL; q = &p->p_forw) {
672 #ifdef DIAGNOSTIC
673 if (p->p_back || (p->p_stat != SSLEEP && p->p_stat != SSTOP))
674 panic("wakeup_one");
675 #endif
676 if (p->p_wchan == ident) {
677 if (p->p_stat == SSLEEP) {
678 if (best_sleepp == NULL ||
679 p->p_priority < best_sleepp->p_priority) {
680 best_sleepp = p;
681 best_sleepq = q;
682 }
683 } else {
684 if (best_stopp == NULL ||
685 p->p_priority < best_stopp->p_priority) {
686 best_stopp = p;
687 best_stopq = q;
688 }
689 }
690 }
691 }
692
693 /*
694 * Consider any SSLEEP process higher than the highest priority SSTOP
695 * process.
696 */
697 if (best_sleepp != NULL) {
698 p = best_sleepp;
699 q = best_sleepq;
700 } else {
701 p = best_stopp;
702 q = best_stopq;
703 }
704
705 if (p != NULL) {
706 p->p_wchan = NULL;
707 *q = p->p_forw;
708 if (qp->sq_tailp == &p->p_forw)
709 qp->sq_tailp = q;
710 if (p->p_stat == SSLEEP)
711 awaken(p);
712 }
713 SCHED_UNLOCK(s);
714 }
715
716 /*
717 * General yield call. Puts the current process back on its run queue and
718 * performs a voluntary context switch.
719 */
720 void
721 yield(void)
722 {
723 struct proc *p = curproc;
724 int s;
725
726 SCHED_LOCK(s);
727 p->p_priority = p->p_usrpri;
728 p->p_stat = SRUN;
729 setrunqueue(p);
730 p->p_stats->p_ru.ru_nvcsw++;
731 mi_switch(p);
732 SCHED_ASSERT_UNLOCKED();
733 splx(s);
734 }
735
736 /*
737 * General preemption call. Puts the current process back on its run queue
738 * and performs an involuntary context switch. If a process is supplied,
739 * we switch to that process. Otherwise, we use the normal process selection
740 * criteria.
741 */
742 void
743 preempt(struct proc *newp)
744 {
745 struct proc *p = curproc;
746 int s;
747
748 /*
749 * XXX Switching to a specific process is not supported yet.
750 */
751 if (newp != NULL)
752 panic("preempt: cpu_preempt not yet implemented");
753
754 SCHED_LOCK(s);
755 p->p_priority = p->p_usrpri;
756 p->p_stat = SRUN;
757 setrunqueue(p);
758 p->p_stats->p_ru.ru_nivcsw++;
759 mi_switch(p);
760 SCHED_ASSERT_UNLOCKED();
761 splx(s);
762 }
763
764 /*
765 * The machine independent parts of context switch.
766 * Must be called at splsched() (no higher!) and with
767 * the sched_lock held.
768 */
769 void
770 mi_switch(struct proc *p)
771 {
772 struct schedstate_percpu *spc;
773 struct rlimit *rlim;
774 long s, u;
775 struct timeval tv;
776 #if defined(MULTIPROCESSOR)
777 int hold_count;
778 #endif
779
780 SCHED_ASSERT_LOCKED();
781
782 #if defined(MULTIPROCESSOR)
783 /*
784 * Release the kernel_lock, as we are about to yield the CPU.
785 * The scheduler lock is still held until cpu_switch()
786 * selects a new process and removes it from the run queue.
787 */
788 if (p->p_flag & P_BIGLOCK)
789 hold_count = spinlock_release_all(&kernel_lock);
790 #endif
791
792 KDASSERT(p->p_cpu != NULL);
793 KDASSERT(p->p_cpu == curcpu());
794
795 spc = &p->p_cpu->ci_schedstate;
796
797 #if defined(LOCKDEBUG) || defined(DIAGNOSTIC)
798 spinlock_switchcheck();
799 #endif
800 #ifdef LOCKDEBUG
801 simple_lock_switchcheck();
802 #endif
803
804 /*
805 * Compute the amount of time during which the current
806 * process was running, and add that to its total so far.
807 */
808 microtime(&tv);
809 u = p->p_rtime.tv_usec + (tv.tv_usec - spc->spc_runtime.tv_usec);
810 s = p->p_rtime.tv_sec + (tv.tv_sec - spc->spc_runtime.tv_sec);
811 if (u < 0) {
812 u += 1000000;
813 s--;
814 } else if (u >= 1000000) {
815 u -= 1000000;
816 s++;
817 }
818 p->p_rtime.tv_usec = u;
819 p->p_rtime.tv_sec = s;
820
821 /*
822 * Check if the process exceeds its cpu resource allocation.
823 * If over max, kill it. In any case, if it has run for more
824 * than 10 minutes, reduce priority to give others a chance.
825 */
826 rlim = &p->p_rlimit[RLIMIT_CPU];
827 if (s >= rlim->rlim_cur) {
828 /*
829 * XXXSMP: we're inside the scheduler lock perimeter;
830 * use sched_psignal.
831 */
832 if (s >= rlim->rlim_max)
833 sched_psignal(p, SIGKILL);
834 else {
835 sched_psignal(p, SIGXCPU);
836 if (rlim->rlim_cur < rlim->rlim_max)
837 rlim->rlim_cur += 5;
838 }
839 }
840 if (autonicetime && s > autonicetime && p->p_ucred->cr_uid &&
841 p->p_nice == NZERO) {
842 p->p_nice = autoniceval + NZERO;
843 resetpriority(p);
844 }
845
846 /*
847 * Process is about to yield the CPU; clear the appropriate
848 * scheduling flags.
849 */
850 spc->spc_flags &= ~SPCF_SWITCHCLEAR;
851
852 #ifdef KSTACK_CHECK_MAGIC
853 kstack_check_magic(p);
854 #endif
855
856 /*
857 * Pick a new current process and switch to it. When we
858 * run again, we'll return back here.
859 */
860 uvmexp.swtch++;
861 cpu_switch(p);
862
863 /*
864 * Make sure that MD code released the scheduler lock before
865 * resuming us.
866 */
867 SCHED_ASSERT_UNLOCKED();
868
869 /*
870 * We're running again; record our new start time. We might
871 * be running on a new CPU now, so don't use the cache'd
872 * schedstate_percpu pointer.
873 */
874 KDASSERT(p->p_cpu != NULL);
875 KDASSERT(p->p_cpu == curcpu());
876 microtime(&p->p_cpu->ci_schedstate.spc_runtime);
877
878 #if defined(MULTIPROCESSOR)
879 /*
880 * Reacquire the kernel_lock now. We do this after we've
881 * released the scheduler lock to avoid deadlock, and before
882 * we reacquire the interlock.
883 */
884 if (p->p_flag & P_BIGLOCK)
885 spinlock_acquire_count(&kernel_lock, hold_count);
886 #endif
887 }
888
889 /*
890 * Initialize the (doubly-linked) run queues
891 * to be empty.
892 */
893 void
894 rqinit()
895 {
896 int i;
897
898 for (i = 0; i < RUNQUE_NQS; i++)
899 sched_qs[i].ph_link = sched_qs[i].ph_rlink =
900 (struct proc *)&sched_qs[i];
901 }
902
903 /*
904 * Change process state to be runnable,
905 * placing it on the run queue if it is in memory,
906 * and awakening the swapper if it isn't in memory.
907 */
908 void
909 setrunnable(struct proc *p)
910 {
911
912 SCHED_ASSERT_LOCKED();
913
914 switch (p->p_stat) {
915 case 0:
916 case SRUN:
917 case SONPROC:
918 case SZOMB:
919 case SDEAD:
920 default:
921 panic("setrunnable");
922 case SSTOP:
923 /*
924 * If we're being traced (possibly because someone attached us
925 * while we were stopped), check for a signal from the debugger.
926 */
927 if ((p->p_flag & P_TRACED) != 0 && p->p_xstat != 0) {
928 sigaddset(&p->p_sigctx.ps_siglist, p->p_xstat);
929 CHECKSIGS(p);
930 }
931 case SSLEEP:
932 unsleep(p); /* e.g. when sending signals */
933 break;
934
935 case SIDL:
936 break;
937 }
938 p->p_stat = SRUN;
939 if (p->p_flag & P_INMEM)
940 setrunqueue(p);
941
942 if (p->p_slptime > 1)
943 updatepri(p);
944 p->p_slptime = 0;
945 if ((p->p_flag & P_INMEM) == 0)
946 sched_wakeup((caddr_t)&proc0);
947 else if (p->p_priority < curcpu()->ci_schedstate.spc_curpriority) {
948 /*
949 * XXXSMP
950 * This is not exactly right. Since p->p_cpu persists
951 * across a context switch, this gives us some sort
952 * of processor affinity. But we need to figure out
953 * at what point it's better to reschedule on a different
954 * CPU than the last one.
955 */
956 need_resched((p->p_cpu != NULL) ? p->p_cpu : curcpu());
957 }
958 }
959
960 /*
961 * Compute the priority of a process when running in user mode.
962 * Arrange to reschedule if the resulting priority is better
963 * than that of the current process.
964 */
965 void
966 resetpriority(struct proc *p)
967 {
968 unsigned int newpriority;
969
970 SCHED_ASSERT_LOCKED();
971
972 newpriority = PUSER + p->p_estcpu + NICE_WEIGHT * (p->p_nice - NZERO);
973 newpriority = min(newpriority, MAXPRI);
974 p->p_usrpri = newpriority;
975 if (newpriority < curcpu()->ci_schedstate.spc_curpriority) {
976 /*
977 * XXXSMP
978 * Same applies as in setrunnable() above.
979 */
980 need_resched((p->p_cpu != NULL) ? p->p_cpu : curcpu());
981 }
982 }
983
984 /*
985 * We adjust the priority of the current process. The priority of a process
986 * gets worse as it accumulates CPU time. The cpu usage estimator (p_estcpu)
987 * is increased here. The formula for computing priorities (in kern_synch.c)
988 * will compute a different value each time p_estcpu increases. This can
989 * cause a switch, but unless the priority crosses a PPQ boundary the actual
990 * queue will not change. The cpu usage estimator ramps up quite quickly
991 * when the process is running (linearly), and decays away exponentially, at
992 * a rate which is proportionally slower when the system is busy. The basic
993 * principle is that the system will 90% forget that the process used a lot
994 * of CPU time in 5 * loadav seconds. This causes the system to favor
995 * processes which haven't run much recently, and to round-robin among other
996 * processes.
997 */
998
999 void
1000 schedclock(struct proc *p)
1001 {
1002 int s;
1003
1004 p->p_estcpu = ESTCPULIM(p->p_estcpu + 1);
1005
1006 SCHED_LOCK(s);
1007 resetpriority(p);
1008 SCHED_UNLOCK(s);
1009
1010 if (p->p_priority >= PUSER)
1011 p->p_priority = p->p_usrpri;
1012 }
1013
1014 void
1015 suspendsched()
1016 {
1017 struct proc *p;
1018 int s;
1019
1020 /*
1021 * Convert all non-P_SYSTEM SSLEEP or SRUN processes to SSTOP.
1022 */
1023 proclist_lock_read();
1024 SCHED_LOCK(s);
1025 for (p = LIST_FIRST(&allproc); p != NULL; p = LIST_NEXT(p, p_list)) {
1026 if ((p->p_flag & P_SYSTEM) != 0)
1027 continue;
1028 switch (p->p_stat) {
1029 case SRUN:
1030 if ((p->p_flag & P_INMEM) != 0)
1031 remrunqueue(p);
1032 /* FALLTHROUGH */
1033 case SSLEEP:
1034 p->p_stat = SSTOP;
1035 break;
1036 case SONPROC:
1037 /*
1038 * XXX SMP: we need to deal with processes on
1039 * others CPU !
1040 */
1041 break;
1042 default:
1043 break;
1044 }
1045 }
1046 SCHED_UNLOCK(s);
1047 proclist_unlock_read();
1048 }
1049