xref: /netbsd-src/sys/kern/kern_synch.c (revision 4472dbe5e3bd91ef2540bada7a7ca7384627ff9b)
1 /*	$NetBSD: kern_synch.c,v 1.76 2000/05/31 05:02:33 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 	KDASSERT(p->p_cpu != NULL);
428 	KDASSERT(p->p_cpu == curcpu());
429 	p->p_cpu->ci_schedstate.spc_curpriority = p->p_usrpri;
430 	splx(s);
431 	p->p_flag &= ~P_SINTR;
432 	if (p->p_flag & P_TIMEOUT) {
433 		p->p_flag &= ~P_TIMEOUT;
434 		if (sig == 0) {
435 #ifdef KTRACE
436 			if (KTRPOINT(p, KTR_CSW))
437 				ktrcsw(p, 0, 0);
438 #endif
439 			return (EWOULDBLOCK);
440 		}
441 	} else if (timo)
442 		callout_stop(&p->p_tsleep_ch);
443 	if (catch && (sig != 0 || (sig = CURSIG(p)) != 0)) {
444 #ifdef KTRACE
445 		if (KTRPOINT(p, KTR_CSW))
446 			ktrcsw(p, 0, 0);
447 #endif
448 		if ((p->p_sigacts->ps_sigact[sig].sa_flags & SA_RESTART) == 0)
449 			return (EINTR);
450 		return (ERESTART);
451 	}
452 #ifdef KTRACE
453 	if (KTRPOINT(p, KTR_CSW))
454 		ktrcsw(p, 0, 0);
455 #endif
456 	return (0);
457 }
458 
459 /*
460  * Implement timeout for tsleep.
461  * If process hasn't been awakened (wchan non-zero),
462  * set timeout flag and undo the sleep.  If proc
463  * is stopped, just unsleep so it will remain stopped.
464  */
465 void
466 endtsleep(arg)
467 	void *arg;
468 {
469 	struct proc *p;
470 	int s;
471 
472 	p = (struct proc *)arg;
473 	s = splhigh();
474 	if (p->p_wchan) {
475 		if (p->p_stat == SSLEEP)
476 			setrunnable(p);
477 		else
478 			unsleep(p);
479 		p->p_flag |= P_TIMEOUT;
480 	}
481 	splx(s);
482 }
483 
484 /*
485  * Remove a process from its wait queue
486  */
487 void
488 unsleep(p)
489 	struct proc *p;
490 {
491 	struct slpque *qp;
492 	struct proc **hp;
493 	int s;
494 
495 	s = splhigh();
496 	if (p->p_wchan) {
497 		hp = &(qp = SLPQUE(p->p_wchan))->sq_head;
498 		while (*hp != p)
499 			hp = &(*hp)->p_forw;
500 		*hp = p->p_forw;
501 		if (qp->sq_tailp == &p->p_forw)
502 			qp->sq_tailp = hp;
503 		p->p_wchan = 0;
504 	}
505 	splx(s);
506 }
507 
508 /*
509  * Optimized-for-wakeup() version of setrunnable().
510  */
511 __inline void
512 awaken(p)
513 	struct proc *p;
514 {
515 
516 	if (p->p_slptime > 1)
517 		updatepri(p);
518 	p->p_slptime = 0;
519 	p->p_stat = SRUN;
520 	/*
521 	 * Since curpriority is a user priority, p->p_priority
522 	 * is always better than curpriority.
523 	 */
524 	if (p->p_flag & P_INMEM) {
525 		setrunqueue(p);
526 		need_resched();
527 	} else
528 		wakeup((caddr_t)&proc0);
529 }
530 
531 /*
532  * Make all processes sleeping on the specified identifier runnable.
533  */
534 void
535 wakeup(ident)
536 	void *ident;
537 {
538 	struct slpque *qp;
539 	struct proc *p, **q;
540 	int s;
541 
542 	s = splhigh();
543 	qp = SLPQUE(ident);
544 restart:
545 	for (q = &qp->sq_head; (p = *q) != NULL; ) {
546 #ifdef DIAGNOSTIC
547 		if (p->p_back || (p->p_stat != SSLEEP && p->p_stat != SSTOP))
548 			panic("wakeup");
549 #endif
550 		if (p->p_wchan == ident) {
551 			p->p_wchan = 0;
552 			*q = p->p_forw;
553 			if (qp->sq_tailp == &p->p_forw)
554 				qp->sq_tailp = q;
555 			if (p->p_stat == SSLEEP) {
556 				awaken(p);
557 				goto restart;
558 			}
559 		} else
560 			q = &p->p_forw;
561 	}
562 	splx(s);
563 }
564 
565 /*
566  * Make the highest priority process first in line on the specified
567  * identifier runnable.
568  */
569 void
570 wakeup_one(ident)
571 	void *ident;
572 {
573 	struct slpque *qp;
574 	struct proc *p, **q;
575 	struct proc *best_sleepp, **best_sleepq;
576 	struct proc *best_stopp, **best_stopq;
577 	int s;
578 
579 	best_sleepp = best_stopp = NULL;
580 	best_sleepq = best_stopq = NULL;
581 
582 	s = splhigh();
583 	qp = SLPQUE(ident);
584 	for (q = &qp->sq_head; (p = *q) != NULL; q = &p->p_forw) {
585 #ifdef DIAGNOSTIC
586 		if (p->p_back || (p->p_stat != SSLEEP && p->p_stat != SSTOP))
587 			panic("wakeup_one");
588 #endif
589 		if (p->p_wchan == ident) {
590 			if (p->p_stat == SSLEEP) {
591 				if (best_sleepp == NULL ||
592 				    p->p_priority < best_sleepp->p_priority) {
593 					best_sleepp = p;
594 					best_sleepq = q;
595 				}
596 			} else {
597 				if (best_stopp == NULL ||
598 				    p->p_priority < best_stopp->p_priority) {
599 					best_stopp = p;
600 					best_stopq = q;
601 				}
602 			}
603 		}
604 	}
605 
606 	/*
607 	 * Consider any SSLEEP process higher than the highest priority SSTOP
608 	 * process.
609 	 */
610 	if (best_sleepp != NULL) {
611 		p = best_sleepp;
612 		q = best_sleepq;
613 	} else {
614 		p = best_stopp;
615 		q = best_stopq;
616 	}
617 
618 	if (p != NULL) {
619 		p->p_wchan = 0;
620 		*q = p->p_forw;
621 		if (qp->sq_tailp == &p->p_forw)
622 			qp->sq_tailp = q;
623 		if (p->p_stat == SSLEEP)
624 			awaken(p);
625 	}
626 	splx(s);
627 }
628 
629 /*
630  * General yield call.  Puts the current process back on its run queue and
631  * performs a voluntary context switch.
632  */
633 void
634 yield()
635 {
636 	struct proc *p = curproc;
637 	int s;
638 
639 	s = splstatclock();
640 	p->p_priority = p->p_usrpri;
641 	p->p_stat = SRUN;
642 	setrunqueue(p);
643 	p->p_stats->p_ru.ru_nvcsw++;
644 	mi_switch(p);
645 	splx(s);
646 }
647 
648 /*
649  * General preemption call.  Puts the current process back on its run queue
650  * and performs an involuntary context switch.  If a process is supplied,
651  * we switch to that process.  Otherwise, we use the normal process selection
652  * criteria.
653  */
654 void
655 preempt(newp)
656 	struct proc *newp;
657 {
658 	struct proc *p = curproc;
659 	int s;
660 
661 	/*
662 	 * XXX Switching to a specific process is not supported yet.
663 	 */
664 	if (newp != NULL)
665 		panic("preempt: cpu_preempt not yet implemented");
666 
667 	s = splstatclock();
668 	p->p_priority = p->p_usrpri;
669 	p->p_stat = SRUN;
670 	setrunqueue(p);
671 	p->p_stats->p_ru.ru_nivcsw++;
672 	mi_switch(p);
673 	splx(s);
674 }
675 
676 /*
677  * The machine independent parts of context switch.
678  * Must be called at splstatclock() or higher.
679  */
680 void
681 mi_switch(p)
682 	struct proc *p;
683 {
684 	struct schedstate_percpu *spc;
685 	struct rlimit *rlim;
686 	long s, u;
687 	struct timeval tv;
688 
689 	KDASSERT(p->p_cpu != NULL);
690 	KDASSERT(p->p_cpu == curcpu());
691 
692 	spc = &p->p_cpu->ci_schedstate;
693 
694 #ifdef DEBUG
695 	if (p->p_simple_locks) {
696 		printf("p->p_simple_locks %d\n", p->p_simple_locks);
697 #ifdef LOCKDEBUG
698 		simple_lock_dump();
699 #endif
700 		panic("sleep: holding simple lock");
701 	}
702 #endif
703 	/*
704 	 * Compute the amount of time during which the current
705 	 * process was running, and add that to its total so far.
706 	 */
707 	microtime(&tv);
708 	u = p->p_rtime.tv_usec + (tv.tv_usec - spc->spc_runtime.tv_usec);
709 	s = p->p_rtime.tv_sec + (tv.tv_sec - spc->spc_runtime.tv_sec);
710 	if (u < 0) {
711 		u += 1000000;
712 		s--;
713 	} else if (u >= 1000000) {
714 		u -= 1000000;
715 		s++;
716 	}
717 	p->p_rtime.tv_usec = u;
718 	p->p_rtime.tv_sec = s;
719 
720 	/*
721 	 * Check if the process exceeds its cpu resource allocation.
722 	 * If over max, kill it.  In any case, if it has run for more
723 	 * than 10 minutes, reduce priority to give others a chance.
724 	 */
725 	rlim = &p->p_rlimit[RLIMIT_CPU];
726 	if (s >= rlim->rlim_cur) {
727 		if (s >= rlim->rlim_max)
728 			psignal(p, SIGKILL);
729 		else {
730 			psignal(p, SIGXCPU);
731 			if (rlim->rlim_cur < rlim->rlim_max)
732 				rlim->rlim_cur += 5;
733 		}
734 	}
735 	if (autonicetime && s > autonicetime && p->p_ucred->cr_uid && p->p_nice == NZERO) {
736 		p->p_nice = autoniceval + NZERO;
737 		resetpriority(p);
738 	}
739 
740 	/*
741 	 * Process is about to yield the CPU; clear the appropriate
742 	 * scheduling flags.
743 	 */
744 	spc->spc_flags &= ~SPCF_SWITCHCLEAR;
745 
746 	/*
747 	 * Pick a new current process and switch to it.  When we
748 	 * run again, we'll return back here.
749 	 */
750 	uvmexp.swtch++;
751 	cpu_switch(p);
752 
753 	/*
754 	 * We're running again; record our new start time.  We might
755 	 * be running on a new CPU now, so don't use the cache'd
756 	 * schedstate_percpu pointer.
757 	 */
758 	KDASSERT(p->p_cpu != NULL);
759 	KDASSERT(p->p_cpu == curcpu());
760 	microtime(&p->p_cpu->ci_schedstate.spc_runtime);
761 }
762 
763 /*
764  * Initialize the (doubly-linked) run queues
765  * to be empty.
766  */
767 void
768 rqinit()
769 {
770 	int i;
771 
772 	for (i = 0; i < RUNQUE_NQS; i++)
773 		sched_qs[i].ph_link = sched_qs[i].ph_rlink =
774 		    (struct proc *)&sched_qs[i];
775 }
776 
777 /*
778  * Change process state to be runnable,
779  * placing it on the run queue if it is in memory,
780  * and awakening the swapper if it isn't in memory.
781  */
782 void
783 setrunnable(p)
784 	struct proc *p;
785 {
786 	int s;
787 
788 	s = splhigh();
789 	switch (p->p_stat) {
790 	case 0:
791 	case SRUN:
792 	case SONPROC:
793 	case SZOMB:
794 	case SDEAD:
795 	default:
796 		panic("setrunnable");
797 	case SSTOP:
798 		/*
799 		 * If we're being traced (possibly because someone attached us
800 		 * while we were stopped), check for a signal from the debugger.
801 		 */
802 		if ((p->p_flag & P_TRACED) != 0 && p->p_xstat != 0) {
803 			sigaddset(&p->p_siglist, p->p_xstat);
804 			p->p_sigcheck = 1;
805 		}
806 	case SSLEEP:
807 		unsleep(p);		/* e.g. when sending signals */
808 		break;
809 
810 	case SIDL:
811 		break;
812 	}
813 	p->p_stat = SRUN;
814 	if (p->p_flag & P_INMEM)
815 		setrunqueue(p);
816 	splx(s);
817 	if (p->p_slptime > 1)
818 		updatepri(p);
819 	p->p_slptime = 0;
820 	if ((p->p_flag & P_INMEM) == 0)
821 		wakeup((caddr_t)&proc0);
822 	else if (p->p_priority < curcpu()->ci_schedstate.spc_curpriority) {
823 		/*
824 		 * XXXSMP
825 		 * This is wrong.  It will work, but what really
826 		 * needs to happen is:
827 		 *
828 		 *	- Need to check if p is higher priority
829 		 *	  than the process currently running on
830 		 *	  the CPU p last ran on (let p_cpu persist
831 		 *	  after a context switch?), and preempt
832 		 *	  that one (or, if there is no process
833 		 *	  there, simply need_resched() that CPU.
834 		 *
835 		 *	- Failing that, traverse a list of
836 		 *	  available CPUs and need_resched() the
837 		 *	  CPU with the lowest priority that's
838 		 *	  lower than p's.
839 		 */
840 		need_resched();
841 	}
842 }
843 
844 /*
845  * Compute the priority of a process when running in user mode.
846  * Arrange to reschedule if the resulting priority is better
847  * than that of the current process.
848  */
849 void
850 resetpriority(p)
851 	struct proc *p;
852 {
853 	unsigned int newpriority;
854 
855 	newpriority = PUSER + p->p_estcpu + NICE_WEIGHT * (p->p_nice - NZERO);
856 	newpriority = min(newpriority, MAXPRI);
857 	p->p_usrpri = newpriority;
858 	if (newpriority < curcpu()->ci_schedstate.spc_curpriority) {
859 		/*
860 		 * XXXSMP
861 		 * Same applies as in setrunnable() above.
862 		 */
863 		need_resched();
864 	}
865 }
866 
867 /*
868  * We adjust the priority of the current process.  The priority of a process
869  * gets worse as it accumulates CPU time.  The cpu usage estimator (p_estcpu)
870  * is increased here.  The formula for computing priorities (in kern_synch.c)
871  * will compute a different value each time p_estcpu increases. This can
872  * cause a switch, but unless the priority crosses a PPQ boundary the actual
873  * queue will not change.  The cpu usage estimator ramps up quite quickly
874  * when the process is running (linearly), and decays away exponentially, at
875  * a rate which is proportionally slower when the system is busy.  The basic
876  * principal is that the system will 90% forget that the process used a lot
877  * of CPU time in 5 * loadav seconds.  This causes the system to favor
878  * processes which haven't run much recently, and to round-robin among other
879  * processes.
880  */
881 
882 void
883 schedclock(p)
884 	struct proc *p;
885 {
886 	p->p_estcpu = ESTCPULIM(p->p_estcpu + 1);
887 	resetpriority(p);
888 	if (p->p_priority >= PUSER)
889 		p->p_priority = p->p_usrpri;
890 }
891