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