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