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