xref: /csrg-svn/sys/kern/kern_synch.c (revision 49226)
1 /*
2  * Copyright (c) 1982, 1986, 1990, 1991 Regents of the University of California.
3  * All rights reserved.  The Berkeley software License Agreement
4  * specifies the terms and conditions for redistribution.
5  *
6  *	@(#)kern_synch.c	7.16 (Berkeley) 05/06/91
7  */
8 
9 #include "param.h"
10 #include "systm.h"
11 #include "proc.h"
12 #include "kernel.h"
13 #include "buf.h"
14 #include "signalvar.h"
15 #include "resourcevar.h"
16 
17 #include "machine/cpu.h"
18 
19 u_char	curpri;			/* usrpri of curproc */
20 
21 /*
22  * Force switch among equal priority processes every 100ms.
23  */
24 roundrobin()
25 {
26 
27 	need_resched();
28 	timeout(roundrobin, (caddr_t)0, hz / 10);
29 }
30 
31 /*
32  * constants for digital decay and forget
33  *	90% of (p_cpu) usage in 5*loadav time
34  *	95% of (p_pctcpu) usage in 60 seconds (load insensitive)
35  *          Note that, as ps(1) mentions, this can let percentages
36  *          total over 100% (I've seen 137.9% for 3 processes).
37  *
38  * Note that hardclock updates p_cpu and p_cpticks independently.
39  *
40  * We wish to decay away 90% of p_cpu in (5 * loadavg) seconds.
41  * That is, the system wants to compute a value of decay such
42  * that the following for loop:
43  * 	for (i = 0; i < (5 * loadavg); i++)
44  * 		p_cpu *= decay;
45  * will compute
46  * 	p_cpu *= 0.1;
47  * for all values of loadavg:
48  *
49  * Mathematically this loop can be expressed by saying:
50  * 	decay ** (5 * loadavg) ~= .1
51  *
52  * The system computes decay as:
53  * 	decay = (2 * loadavg) / (2 * loadavg + 1)
54  *
55  * We wish to prove that the system's computation of decay
56  * will always fulfill the equation:
57  * 	decay ** (5 * loadavg) ~= .1
58  *
59  * If we compute b as:
60  * 	b = 2 * loadavg
61  * then
62  * 	decay = b / (b + 1)
63  *
64  * We now need to prove two things:
65  *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
66  *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
67  *
68  * Facts:
69  *         For x close to zero, exp(x) =~ 1 + x, since
70  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
71  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
72  *         For x close to zero, ln(1+x) =~ x, since
73  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
74  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
75  *         ln(.1) =~ -2.30
76  *
77  * Proof of (1):
78  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
79  *	solving for factor,
80  *      ln(factor) =~ (-2.30/5*loadav), or
81  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
82  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
83  *
84  * Proof of (2):
85  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
86  *	solving for power,
87  *      power*ln(b/(b+1)) =~ -2.30, or
88  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
89  *
90  * Actual power values for the implemented algorithm are as follows:
91  *      loadav: 1       2       3       4
92  *      power:  5.68    10.32   14.94   19.55
93  */
94 
95 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
96 #define	loadfactor(loadav)	(2 * (loadav))
97 #define	decay_cpu(loadfac, cpu)	(((loadfac) * (cpu)) / ((loadfac) + FSCALE))
98 
99 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
100 fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;		/* exp(-1/20) */
101 
102 /*
103  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
104  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
105  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
106  *
107  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
108  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
109  *
110  * If you dont want to bother with the faster/more-accurate formula, you
111  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
112  * (more general) method of calculating the %age of CPU used by a process.
113  */
114 #define	CCPU_SHIFT	11
115 
116 /*
117  * Recompute process priorities, once a second
118  */
119 schedcpu()
120 {
121 	register fixpt_t loadfac = loadfactor(averunnable[0]);
122 	register struct proc *p;
123 	register int s;
124 	register unsigned int newcpu;
125 
126 	wakeup((caddr_t)&lbolt);
127 	for (p = allproc; p != NULL; p = p->p_nxt) {
128 		/*
129 		 * Increment time in/out of memory and sleep time
130 		 * (if sleeping).  We ignore overflow; with 16-bit int's
131 		 * (remember them?) overflow takes 45 days.
132 		 */
133 		p->p_time++;
134 		if (p->p_stat == SSLEEP || p->p_stat == SSTOP)
135 			p->p_slptime++;
136 		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
137 		/*
138 		 * If the process has slept the entire second,
139 		 * stop recalculating its priority until it wakes up.
140 		 */
141 		if (p->p_slptime > 1)
142 			continue;
143 		/*
144 		 * p_pctcpu is only for ps.
145 		 */
146 #if	(FSHIFT >= CCPU_SHIFT)
147 		p->p_pctcpu += (hz == 100)?
148 			((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT):
149                 	100 * (((fixpt_t) p->p_cpticks)
150 				<< (FSHIFT - CCPU_SHIFT)) / hz;
151 #else
152 		p->p_pctcpu += ((FSCALE - ccpu) *
153 			(p->p_cpticks * FSCALE / hz)) >> FSHIFT;
154 #endif
155 		p->p_cpticks = 0;
156 		newcpu = (u_int) decay_cpu(loadfac, p->p_cpu) + p->p_nice;
157 		p->p_cpu = min(newcpu, UCHAR_MAX);
158 		setpri(p);
159 		s = splhigh();	/* prevent state changes */
160 		if (p->p_pri >= PUSER) {
161 #define	PPQ	(128 / NQS)		/* priorities per queue */
162 			if ((p != curproc) &&
163 			    p->p_stat == SRUN &&
164 			    (p->p_flag & SLOAD) &&
165 			    (p->p_pri / PPQ) != (p->p_usrpri / PPQ)) {
166 				remrq(p);
167 				p->p_pri = p->p_usrpri;
168 				setrq(p);
169 			} else
170 				p->p_pri = p->p_usrpri;
171 		}
172 		splx(s);
173 	}
174 	vmmeter();
175 	if (bclnlist != NULL)
176 		wakeup((caddr_t)pageproc);
177 	timeout(schedcpu, (caddr_t)0, hz);
178 }
179 
180 /*
181  * Recalculate the priority of a process after it has slept for a while.
182  * For all load averages >= 1 and max p_cpu of 255, sleeping for at least
183  * six times the loadfactor will decay p_cpu to zero.
184  */
185 updatepri(p)
186 	register struct proc *p;
187 {
188 	register unsigned int newcpu = p->p_cpu;
189 	register fixpt_t loadfac = loadfactor(averunnable[0]);
190 
191 	if (p->p_slptime > 5 * loadfac)
192 		p->p_cpu = 0;
193 	else {
194 		p->p_slptime--;	/* the first time was done in schedcpu */
195 		while (newcpu && --p->p_slptime)
196 			newcpu = (int) decay_cpu(loadfac, newcpu);
197 		p->p_cpu = min(newcpu, UCHAR_MAX);
198 	}
199 	setpri(p);
200 }
201 
202 #define SQSIZE 0100	/* Must be power of 2 */
203 #define HASH(x)	(( (int) x >> 5) & (SQSIZE-1))
204 struct slpque {
205 	struct proc *sq_head;
206 	struct proc **sq_tailp;
207 } slpque[SQSIZE];
208 
209 /*
210  * During autoconfiguration or after a panic, a sleep will simply
211  * lower the priority briefly to allow interrupts, then return.
212  * The priority to be used (safepri) is machine-dependent, thus this
213  * value is initialized and maintained in the machine-dependent layers.
214  * This priority will typically be 0, or the lowest priority
215  * that is safe for use on the interrupt stack; it can be made
216  * higher to block network software interrupts after panics.
217  */
218 int safepri;
219 
220 /*
221  * General sleep call.
222  * Suspends current process until a wakeup is made on chan.
223  * The process will then be made runnable with priority pri.
224  * Sleeps at most timo/hz seconds (0 means no timeout).
225  * If pri includes PCATCH flag, signals are checked
226  * before and after sleeping, else signals are not checked.
227  * Returns 0 if awakened, EWOULDBLOCK if the timeout expires.
228  * If PCATCH is set and a signal needs to be delivered,
229  * ERESTART is returned if the current system call should be restarted
230  * if possible, and EINTR is returned if the system call should
231  * be interrupted by the signal (return EINTR).
232  */
233 tsleep(chan, pri, wmesg, timo)
234 	caddr_t chan;
235 	int pri;
236 	char *wmesg;
237 	int timo;
238 {
239 	register struct proc *p = curproc;
240 	register struct slpque *qp;
241 	register s;
242 	int sig, catch = pri & PCATCH;
243 	extern int cold;
244 	int endtsleep();
245 
246 	s = splhigh();
247 	if (cold || panicstr) {
248 		/*
249 		 * After a panic, or during autoconfiguration,
250 		 * just give interrupts a chance, then just return;
251 		 * don't run any other procs or panic below,
252 		 * in case this is the idle process and already asleep.
253 		 */
254 		splx(safepri);
255 		splx(s);
256 		return (0);
257 	}
258 #ifdef DIAGNOSTIC
259 	if (chan == 0 || p->p_stat != SRUN || p->p_rlink)
260 		panic("tsleep");
261 #endif
262 	p->p_wchan = chan;
263 	p->p_wmesg = wmesg;
264 	p->p_slptime = 0;
265 	p->p_pri = pri & PRIMASK;
266 	qp = &slpque[HASH(chan)];
267 	if (qp->sq_head == 0)
268 		qp->sq_head = p;
269 	else
270 		*qp->sq_tailp = p;
271 	*(qp->sq_tailp = &p->p_link) = 0;
272 	if (timo)
273 		timeout(endtsleep, (caddr_t)p, timo);
274 	/*
275 	 * We put ourselves on the sleep queue and start our timeout
276 	 * before calling CURSIG, as we could stop there, and a wakeup
277 	 * or a SIGCONT (or both) could occur while we were stopped.
278 	 * A SIGCONT would cause us to be marked as SSLEEP
279 	 * without resuming us, thus we must be ready for sleep
280 	 * when CURSIG is called.  If the wakeup happens while we're
281 	 * stopped, p->p_wchan will be 0 upon return from CURSIG.
282 	 */
283 	if (catch) {
284 		p->p_flag |= SSINTR;
285 		if (sig = CURSIG(p)) {
286 			if (p->p_wchan)
287 				unsleep(p);
288 			p->p_stat = SRUN;
289 			goto resume;
290 		}
291 		if (p->p_wchan == 0) {
292 			catch = 0;
293 			goto resume;
294 		}
295 	}
296 	p->p_stat = SSLEEP;
297 	(void) spl0();
298 	p->p_stats->p_ru.ru_nvcsw++;
299 	swtch();
300 resume:
301 	curpri = p->p_usrpri;
302 	splx(s);
303 	p->p_flag &= ~SSINTR;
304 	if (p->p_flag & STIMO) {
305 		p->p_flag &= ~STIMO;
306 		if (catch == 0 || sig == 0)
307 			return (EWOULDBLOCK);
308 	} else if (timo)
309 		untimeout(endtsleep, (caddr_t)p);
310 	if (catch && (sig != 0 || (sig = CURSIG(p)))) {
311 		if (p->p_sigacts->ps_sigintr & sigmask(sig))
312 			return (EINTR);
313 		return (ERESTART);
314 	}
315 	return (0);
316 }
317 
318 /*
319  * Implement timeout for tsleep.
320  * If process hasn't been awakened (wchan non-zero),
321  * set timeout flag and undo the sleep.  If proc
322  * is stopped, just unsleep so it will remain stopped.
323  */
324 endtsleep(p)
325 	register struct proc *p;
326 {
327 	int s = splhigh();
328 
329 	if (p->p_wchan) {
330 		if (p->p_stat == SSLEEP)
331 			setrun(p);
332 		else
333 			unsleep(p);
334 		p->p_flag |= STIMO;
335 	}
336 	splx(s);
337 }
338 
339 /*
340  * Short-term, non-interruptable sleep.
341  */
342 sleep(chan, pri)
343 	caddr_t chan;
344 	int pri;
345 {
346 	register struct proc *p = curproc;
347 	register struct slpque *qp;
348 	register s;
349 	extern int cold;
350 
351 #ifdef DIAGNOSTIC
352 	if (pri > PZERO) {
353 		printf("sleep called with pri %d > PZERO, wchan: %x\n",
354 			pri, chan);
355 		panic("old sleep");
356 	}
357 #endif
358 	s = splhigh();
359 	if (cold || panicstr) {
360 		/*
361 		 * After a panic, or during autoconfiguration,
362 		 * just give interrupts a chance, then just return;
363 		 * don't run any other procs or panic below,
364 		 * in case this is the idle process and already asleep.
365 		 */
366 		splx(safepri);
367 		splx(s);
368 		return;
369 	}
370 #ifdef DIAGNOSTIC
371 	if (chan==0 || p->p_stat != SRUN || p->p_rlink)
372 		panic("sleep");
373 #endif
374 	p->p_wchan = chan;
375 	p->p_wmesg = NULL;
376 	p->p_slptime = 0;
377 	p->p_pri = pri;
378 	qp = &slpque[HASH(chan)];
379 	if (qp->sq_head == 0)
380 		qp->sq_head = p;
381 	else
382 		*qp->sq_tailp = p;
383 	*(qp->sq_tailp = &p->p_link) = 0;
384 	p->p_stat = SSLEEP;
385 	(void) spl0();
386 	p->p_stats->p_ru.ru_nvcsw++;
387 	swtch();
388 	curpri = p->p_usrpri;
389 	splx(s);
390 }
391 
392 /*
393  * Remove a process from its wait queue
394  */
395 unsleep(p)
396 	register struct proc *p;
397 {
398 	register struct slpque *qp;
399 	register struct proc **hp;
400 	int s;
401 
402 	s = splhigh();
403 	if (p->p_wchan) {
404 		hp = &(qp = &slpque[HASH(p->p_wchan)])->sq_head;
405 		while (*hp != p)
406 			hp = &(*hp)->p_link;
407 		*hp = p->p_link;
408 		if (qp->sq_tailp == &p->p_link)
409 			qp->sq_tailp = hp;
410 		p->p_wchan = 0;
411 	}
412 	splx(s);
413 }
414 
415 /*
416  * Wakeup on "chan"; set all processes
417  * sleeping on chan to run state.
418  */
419 wakeup(chan)
420 	register caddr_t chan;
421 {
422 	register struct slpque *qp;
423 	register struct proc *p, **q;
424 	int s;
425 
426 	s = splhigh();
427 	qp = &slpque[HASH(chan)];
428 restart:
429 	for (q = &qp->sq_head; p = *q; ) {
430 #ifdef DIAGNOSTIC
431 		if (p->p_rlink || p->p_stat != SSLEEP && p->p_stat != SSTOP)
432 			panic("wakeup");
433 #endif
434 		if (p->p_wchan == chan) {
435 			p->p_wchan = 0;
436 			*q = p->p_link;
437 			if (qp->sq_tailp == &p->p_link)
438 				qp->sq_tailp = q;
439 			if (p->p_stat == SSLEEP) {
440 				/* OPTIMIZED INLINE EXPANSION OF setrun(p) */
441 				if (p->p_slptime > 1)
442 					updatepri(p);
443 				p->p_slptime = 0;
444 				p->p_stat = SRUN;
445 				if (p->p_flag & SLOAD)
446 					setrq(p);
447 				/*
448 				 * Since curpri is a usrpri,
449 				 * p->p_pri is always better than curpri.
450 				 */
451 				if ((p->p_flag&SLOAD) == 0)
452 					wakeup((caddr_t)&proc0);
453 				else
454 					need_resched();
455 				/* END INLINE EXPANSION */
456 				goto restart;
457 			}
458 		} else
459 			q = &p->p_link;
460 	}
461 	splx(s);
462 }
463 
464 /*
465  * Initialize the (doubly-linked) run queues
466  * to be empty.
467  */
468 rqinit()
469 {
470 	register int i;
471 
472 	for (i = 0; i < NQS; i++)
473 		qs[i].ph_link = qs[i].ph_rlink = (struct proc *)&qs[i];
474 }
475 
476 /*
477  * Change process state to be runnable,
478  * placing it on the run queue if it is in memory,
479  * and awakening the swapper if it isn't in memory.
480  */
481 setrun(p)
482 	register struct proc *p;
483 {
484 	register int s;
485 
486 	s = splhigh();
487 	switch (p->p_stat) {
488 
489 	case 0:
490 	case SWAIT:
491 	case SRUN:
492 	case SZOMB:
493 	default:
494 		panic("setrun");
495 
496 	case SSTOP:
497 	case SSLEEP:
498 		unsleep(p);		/* e.g. when sending signals */
499 		break;
500 
501 	case SIDL:
502 		break;
503 	}
504 	p->p_stat = SRUN;
505 	if (p->p_flag & SLOAD)
506 		setrq(p);
507 	splx(s);
508 	if (p->p_slptime > 1)
509 		updatepri(p);
510 	p->p_slptime = 0;
511 	if ((p->p_flag&SLOAD) == 0)
512 		wakeup((caddr_t)&proc0);
513 	else if (p->p_pri < curpri)
514 		need_resched();
515 }
516 
517 /*
518  * Compute priority of process when running in user mode.
519  * Arrange to reschedule if the resulting priority
520  * is better than that of the current process.
521  */
522 setpri(p)
523 	register struct proc *p;
524 {
525 	register unsigned int newpri;
526 
527 	newpri = PUSER + p->p_cpu / 4 + 2 * p->p_nice;
528 	newpri = min(newpri, MAXPRI);
529 	p->p_usrpri = newpri;
530 	if (newpri < curpri)
531 		need_resched();
532 }
533