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