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