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