xref: /csrg-svn/sys/kern/kern_synch.c (revision 52667)
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.21 (Berkeley) 02/25/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.ldavg[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.ldavg[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 	} else
305 		sig = 0;
306 	p->p_stat = SSLEEP;
307 	p->p_stats->p_ru.ru_nvcsw++;
308 	swtch();
309 resume:
310 	curpri = p->p_usrpri;
311 	splx(s);
312 	p->p_flag &= ~SSINTR;
313 	if (p->p_flag & STIMO) {
314 		p->p_flag &= ~STIMO;
315 		if (sig == 0) {
316 #ifdef KTRACE
317 			if (KTRPOINT(p, KTR_CSW))
318 				ktrcsw(p->p_tracep, 0, 0);
319 #endif
320 			return (EWOULDBLOCK);
321 		}
322 	} else if (timo)
323 		untimeout(endtsleep, (caddr_t)p);
324 	if (catch && (sig != 0 || (sig = CURSIG(p)))) {
325 #ifdef KTRACE
326 		if (KTRPOINT(p, KTR_CSW))
327 			ktrcsw(p->p_tracep, 0, 0);
328 #endif
329 		if (p->p_sigacts->ps_sigintr & sigmask(sig))
330 			return (EINTR);
331 		return (ERESTART);
332 	}
333 #ifdef KTRACE
334 	if (KTRPOINT(p, KTR_CSW))
335 		ktrcsw(p->p_tracep, 0, 0);
336 #endif
337 	return (0);
338 }
339 
340 /*
341  * Implement timeout for tsleep.
342  * If process hasn't been awakened (wchan non-zero),
343  * set timeout flag and undo the sleep.  If proc
344  * is stopped, just unsleep so it will remain stopped.
345  */
346 endtsleep(p)
347 	register struct proc *p;
348 {
349 	int s = splhigh();
350 
351 	if (p->p_wchan) {
352 		if (p->p_stat == SSLEEP)
353 			setrun(p);
354 		else
355 			unsleep(p);
356 		p->p_flag |= STIMO;
357 	}
358 	splx(s);
359 }
360 
361 /*
362  * Short-term, non-interruptable sleep.
363  */
364 sleep(chan, pri)
365 	caddr_t chan;
366 	int pri;
367 {
368 	register struct proc *p = curproc;
369 	register struct slpque *qp;
370 	register s;
371 	extern int cold;
372 
373 #ifdef DIAGNOSTIC
374 	if (pri > PZERO) {
375 		printf("sleep called with pri %d > PZERO, wchan: %x\n",
376 			pri, chan);
377 		panic("old sleep");
378 	}
379 #endif
380 	s = splhigh();
381 	if (cold || panicstr) {
382 		/*
383 		 * After a panic, or during autoconfiguration,
384 		 * just give interrupts a chance, then just return;
385 		 * don't run any other procs or panic below,
386 		 * in case this is the idle process and already asleep.
387 		 */
388 		splx(safepri);
389 		splx(s);
390 		return;
391 	}
392 #ifdef DIAGNOSTIC
393 	if (chan==0 || p->p_stat != SRUN || p->p_rlink)
394 		panic("sleep");
395 #endif
396 	p->p_wchan = chan;
397 	p->p_wmesg = NULL;
398 	p->p_slptime = 0;
399 	p->p_pri = pri;
400 	qp = &slpque[HASH(chan)];
401 	if (qp->sq_head == 0)
402 		qp->sq_head = p;
403 	else
404 		*qp->sq_tailp = p;
405 	*(qp->sq_tailp = &p->p_link) = 0;
406 	p->p_stat = SSLEEP;
407 	p->p_stats->p_ru.ru_nvcsw++;
408 #ifdef KTRACE
409 	if (KTRPOINT(p, KTR_CSW))
410 		ktrcsw(p->p_tracep, 1, 0);
411 #endif
412 	swtch();
413 #ifdef KTRACE
414 	if (KTRPOINT(p, KTR_CSW))
415 		ktrcsw(p->p_tracep, 0, 0);
416 #endif
417 	curpri = p->p_usrpri;
418 	splx(s);
419 }
420 
421 /*
422  * Remove a process from its wait queue
423  */
424 unsleep(p)
425 	register struct proc *p;
426 {
427 	register struct slpque *qp;
428 	register struct proc **hp;
429 	int s;
430 
431 	s = splhigh();
432 	if (p->p_wchan) {
433 		hp = &(qp = &slpque[HASH(p->p_wchan)])->sq_head;
434 		while (*hp != p)
435 			hp = &(*hp)->p_link;
436 		*hp = p->p_link;
437 		if (qp->sq_tailp == &p->p_link)
438 			qp->sq_tailp = hp;
439 		p->p_wchan = 0;
440 	}
441 	splx(s);
442 }
443 
444 /*
445  * Wakeup on "chan"; set all processes
446  * sleeping on chan to run state.
447  */
448 wakeup(chan)
449 	register caddr_t chan;
450 {
451 	register struct slpque *qp;
452 	register struct proc *p, **q;
453 	int s;
454 
455 	s = splhigh();
456 	qp = &slpque[HASH(chan)];
457 restart:
458 	for (q = &qp->sq_head; p = *q; ) {
459 #ifdef DIAGNOSTIC
460 		if (p->p_rlink || p->p_stat != SSLEEP && p->p_stat != SSTOP)
461 			panic("wakeup");
462 #endif
463 		if (p->p_wchan == chan) {
464 			p->p_wchan = 0;
465 			*q = p->p_link;
466 			if (qp->sq_tailp == &p->p_link)
467 				qp->sq_tailp = q;
468 			if (p->p_stat == SSLEEP) {
469 				/* OPTIMIZED INLINE EXPANSION OF setrun(p) */
470 				if (p->p_slptime > 1)
471 					updatepri(p);
472 				p->p_slptime = 0;
473 				p->p_stat = SRUN;
474 				if (p->p_flag & SLOAD)
475 					setrq(p);
476 				/*
477 				 * Since curpri is a usrpri,
478 				 * p->p_pri is always better than curpri.
479 				 */
480 				if ((p->p_flag&SLOAD) == 0)
481 					wakeup((caddr_t)&proc0);
482 				else
483 					need_resched();
484 				/* END INLINE EXPANSION */
485 				goto restart;
486 			}
487 		} else
488 			q = &p->p_link;
489 	}
490 	splx(s);
491 }
492 
493 /*
494  * Initialize the (doubly-linked) run queues
495  * to be empty.
496  */
497 rqinit()
498 {
499 	register int i;
500 
501 	for (i = 0; i < NQS; i++)
502 		qs[i].ph_link = qs[i].ph_rlink = (struct proc *)&qs[i];
503 }
504 
505 /*
506  * Change process state to be runnable,
507  * placing it on the run queue if it is in memory,
508  * and awakening the swapper if it isn't in memory.
509  */
510 setrun(p)
511 	register struct proc *p;
512 {
513 	register int s;
514 
515 	s = splhigh();
516 	switch (p->p_stat) {
517 
518 	case 0:
519 	case SWAIT:
520 	case SRUN:
521 	case SZOMB:
522 	default:
523 		panic("setrun");
524 
525 	case SSTOP:
526 	case SSLEEP:
527 		unsleep(p);		/* e.g. when sending signals */
528 		break;
529 
530 	case SIDL:
531 		break;
532 	}
533 	p->p_stat = SRUN;
534 	if (p->p_flag & SLOAD)
535 		setrq(p);
536 	splx(s);
537 	if (p->p_slptime > 1)
538 		updatepri(p);
539 	p->p_slptime = 0;
540 	if ((p->p_flag&SLOAD) == 0)
541 		wakeup((caddr_t)&proc0);
542 	else if (p->p_pri < curpri)
543 		need_resched();
544 }
545 
546 /*
547  * Compute priority of process when running in user mode.
548  * Arrange to reschedule if the resulting priority
549  * is better than that of the current process.
550  */
551 setpri(p)
552 	register struct proc *p;
553 {
554 	register unsigned int newpri;
555 
556 	newpri = PUSER + p->p_cpu / 4 + 2 * p->p_nice;
557 	newpri = min(newpri, MAXPRI);
558 	p->p_usrpri = newpri;
559 	if (newpri < curpri)
560 		need_resched();
561 }
562