kern_synch.c revision 41971
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.69 1998/11/27 11:44:22 dg 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
65static void rqinit __P((void *));
66SYSINIT(runqueue, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, rqinit, NULL)
67
68u_char	curpriority;		/* usrpri of curproc */
69int	lbolt;			/* once a second sleep address */
70
71static void	endtsleep __P((void *));
72static void	roundrobin __P((void *arg));
73static void	schedcpu __P((void *arg));
74static 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
80static int quantum = DEFAULT_SCHEDULE_QUANTUM; /* default value */
81
82static int
83sysctl_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
100SYSCTL_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 */
106static 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)
128int roundrobin_interval(void)
129{
130	return ROUNDROBIN_INTERVAL;
131}
132
133/*
134 * Force switch among equal priority processes every 100ms.
135 */
136/* ARGSUSED */
137static void
138roundrobin(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 */
225static fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;	/* exp(-1/20) */
226SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
227
228/* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */
229static int	fscale __unused = FSCALE;
230SYSCTL_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 */
250static void
251schedcpu(arg)
252	void *arg;
253{
254	register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
255	register struct proc *p;
256	register int realstathz, s;
257	register unsigned int newcpu;
258
259	realstathz = stathz ? stathz : hz;
260	for (p = allproc.lh_first; p != 0; p = p->p_list.le_next) {
261		/*
262		 * Increment time in/out of memory and sleep time
263		 * (if sleeping).  We ignore overflow; with 16-bit int's
264		 * (remember them?) overflow takes 45 days.
265		 */
266		p->p_swtime++;
267		if (p->p_stat == SSLEEP || p->p_stat == SSTOP)
268			p->p_slptime++;
269		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
270		/*
271		 * If the process has slept the entire second,
272		 * stop recalculating its priority until it wakes up.
273		 */
274		if (p->p_slptime > 1)
275			continue;
276		s = splhigh();	/* prevent state changes and protect run queue */
277		/*
278		 * p_pctcpu is only for ps.
279		 */
280#if	(FSHIFT >= CCPU_SHIFT)
281		p->p_pctcpu += (realstathz == 100)?
282			((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT):
283                	100 * (((fixpt_t) p->p_cpticks)
284				<< (FSHIFT - CCPU_SHIFT)) / realstathz;
285#else
286		p->p_pctcpu += ((FSCALE - ccpu) *
287			(p->p_cpticks * FSCALE / realstathz)) >> FSHIFT;
288#endif
289		p->p_cpticks = 0;
290		newcpu = (u_int) decay_cpu(loadfac, p->p_estcpu) + p->p_nice;
291		p->p_estcpu = min(newcpu, UCHAR_MAX);
292		resetpriority(p);
293		if (p->p_priority >= PUSER) {
294#define	PPQ	(128 / NQS)		/* priorities per queue */
295			if ((p != curproc) &&
296#ifdef SMP
297			    (u_char)p->p_oncpu == 0xff && 	/* idle */
298#endif
299			    p->p_stat == SRUN &&
300			    (p->p_flag & P_INMEM) &&
301			    (p->p_priority / PPQ) != (p->p_usrpri / PPQ)) {
302				remrq(p);
303				p->p_priority = p->p_usrpri;
304				setrunqueue(p);
305			} else
306				p->p_priority = p->p_usrpri;
307		}
308		splx(s);
309	}
310	vmmeter();
311	wakeup((caddr_t)&lbolt);
312	timeout(schedcpu, (void *)0, hz);
313}
314
315/*
316 * Recalculate the priority of a process after it has slept for a while.
317 * For all load averages >= 1 and max p_estcpu of 255, sleeping for at
318 * least six times the loadfactor will decay p_estcpu to zero.
319 */
320static void
321updatepri(p)
322	register struct proc *p;
323{
324	register unsigned int newcpu = p->p_estcpu;
325	register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
326
327	if (p->p_slptime > 5 * loadfac)
328		p->p_estcpu = 0;
329	else {
330		p->p_slptime--;	/* the first time was done in schedcpu */
331		while (newcpu && --p->p_slptime)
332			newcpu = (int) decay_cpu(loadfac, newcpu);
333		p->p_estcpu = min(newcpu, UCHAR_MAX);
334	}
335	resetpriority(p);
336}
337
338/*
339 * We're only looking at 7 bits of the address; everything is
340 * aligned to 4, lots of things are aligned to greater powers
341 * of 2.  Shift right by 8, i.e. drop the bottom 256 worth.
342 */
343#define TABLESIZE	128
344static TAILQ_HEAD(slpquehead, proc) slpque[TABLESIZE];
345#define LOOKUP(x)	(((intptr_t)(x) >> 8) & (TABLESIZE - 1))
346
347/*
348 * During autoconfiguration or after a panic, a sleep will simply
349 * lower the priority briefly to allow interrupts, then return.
350 * The priority to be used (safepri) is machine-dependent, thus this
351 * value is initialized and maintained in the machine-dependent layers.
352 * This priority will typically be 0, or the lowest priority
353 * that is safe for use on the interrupt stack; it can be made
354 * higher to block network software interrupts after panics.
355 */
356int safepri;
357
358void
359sleepinit()
360{
361	int i;
362
363	for (i = 0; i < TABLESIZE; i++)
364		TAILQ_INIT(&slpque[i]);
365}
366
367/*
368 * General sleep call.  Suspends the current process until a wakeup is
369 * performed on the specified identifier.  The process will then be made
370 * runnable with the specified priority.  Sleeps at most timo/hz seconds
371 * (0 means no timeout).  If pri includes PCATCH flag, signals are checked
372 * before and after sleeping, else signals are not checked.  Returns 0 if
373 * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
374 * signal needs to be delivered, ERESTART is returned if the current system
375 * call should be restarted if possible, and EINTR is returned if the system
376 * call should be interrupted by the signal (return EINTR).
377 */
378int
379tsleep(ident, priority, wmesg, timo)
380	void *ident;
381	int priority, timo;
382	const char *wmesg;
383{
384	struct proc *p = curproc;
385	int s, sig, catch = priority & PCATCH;
386	struct callout_handle thandle;
387
388#ifdef KTRACE
389	if (KTRPOINT(p, KTR_CSW))
390		ktrcsw(p->p_tracep, 1, 0);
391#endif
392	s = splhigh();
393	if (cold || panicstr) {
394		/*
395		 * After a panic, or during autoconfiguration,
396		 * just give interrupts a chance, then just return;
397		 * don't run any other procs or panic below,
398		 * in case this is the idle process and already asleep.
399		 */
400		splx(safepri);
401		splx(s);
402		return (0);
403	}
404#ifdef DIAGNOSTIC
405	if(p == NULL)
406		panic("tsleep1");
407	if (ident == NULL || p->p_stat != SRUN)
408		panic("tsleep");
409	/* XXX This is not exhaustive, just the most common case */
410#ifdef NOTDEF
411	/*
412	 * This can happen legitimately now with asleep()/await()
413	 */
414	if ((p->p_procq.tqe_prev != NULL) && (*p->p_procq.tqe_prev == p))
415		panic("sleeping process already on another queue");
416#endif
417#endif
418	/*
419	 * Process may be sitting on a slpque if asleep() was called, remove
420	 * it before re-adding.
421	 */
422	if (p->p_wchan != NULL)
423		unsleep(p);
424
425	p->p_wchan = ident;
426	p->p_wmesg = wmesg;
427	p->p_slptime = 0;
428	p->p_priority = priority & PRIMASK;
429	TAILQ_INSERT_TAIL(&slpque[LOOKUP(ident)], p, p_procq);
430	if (timo)
431		thandle = timeout(endtsleep, (void *)p, timo);
432	/*
433	 * We put ourselves on the sleep queue and start our timeout
434	 * before calling CURSIG, as we could stop there, and a wakeup
435	 * or a SIGCONT (or both) could occur while we were stopped.
436	 * A SIGCONT would cause us to be marked as SSLEEP
437	 * without resuming us, thus we must be ready for sleep
438	 * when CURSIG is called.  If the wakeup happens while we're
439	 * stopped, p->p_wchan will be 0 upon return from CURSIG.
440	 */
441	if (catch) {
442		p->p_flag |= P_SINTR;
443		if ((sig = CURSIG(p))) {
444			if (p->p_wchan)
445				unsleep(p);
446			p->p_stat = SRUN;
447			goto resume;
448		}
449		if (p->p_wchan == 0) {
450			catch = 0;
451			goto resume;
452		}
453	} else
454		sig = 0;
455	p->p_stat = SSLEEP;
456	p->p_stats->p_ru.ru_nvcsw++;
457	mi_switch();
458resume:
459	curpriority = p->p_usrpri;
460	splx(s);
461	p->p_flag &= ~P_SINTR;
462	if (p->p_flag & P_TIMEOUT) {
463		p->p_flag &= ~P_TIMEOUT;
464		if (sig == 0) {
465#ifdef KTRACE
466			if (KTRPOINT(p, KTR_CSW))
467				ktrcsw(p->p_tracep, 0, 0);
468#endif
469			return (EWOULDBLOCK);
470		}
471	} else if (timo)
472		untimeout(endtsleep, (void *)p, thandle);
473	if (catch && (sig != 0 || (sig = CURSIG(p)))) {
474#ifdef KTRACE
475		if (KTRPOINT(p, KTR_CSW))
476			ktrcsw(p->p_tracep, 0, 0);
477#endif
478		if (p->p_sigacts->ps_sigintr & sigmask(sig))
479			return (EINTR);
480		return (ERESTART);
481	}
482#ifdef KTRACE
483	if (KTRPOINT(p, KTR_CSW))
484		ktrcsw(p->p_tracep, 0, 0);
485#endif
486	return (0);
487}
488
489/*
490 * asleep() - async sleep call.  Place process on wait queue and return
491 * immediately without blocking.  The process stays runnable until await()
492 * is called.  If ident is NULL, remove process from wait queue if it is still
493 * on one.
494 *
495 * Only the most recent sleep condition is effective when making successive
496 * calls to asleep() or when calling tsleep().
497 *
498 * The timeout, if any, is not initiated until await() is called.  The sleep
499 * priority, signal, and timeout is specified in the asleep() call but may be
500 * overriden in the await() call.
501 *
502 * <<<<<<<< EXPERIMENTAL, UNTESTED >>>>>>>>>>
503 */
504
505int
506asleep(void *ident, int priority, const char *wmesg, int timo)
507{
508	struct proc *p = curproc;
509	int s;
510
511	/*
512	 * splhigh() while manipulating sleep structures and slpque.
513	 *
514	 * Remove preexisting wait condition (if any) and place process
515	 * on appropriate slpque, but do not put process to sleep.
516	 */
517
518	s = splhigh();
519
520	if (p->p_wchan != NULL)
521		unsleep(p);
522
523	if (ident) {
524		p->p_wchan = ident;
525		p->p_wmesg = wmesg;
526		p->p_slptime = 0;
527		p->p_asleep.as_priority = priority;
528		p->p_asleep.as_timo = timo;
529		TAILQ_INSERT_TAIL(&slpque[LOOKUP(ident)], p, p_procq);
530	}
531
532	splx(s);
533
534	return(0);
535}
536
537/*
538 * await() - wait for async condition to occur.   The process blocks until
539 * wakeup() is called on the most recent asleep() address.  If wakeup is called
540 * priority to await(), await() winds up being a NOP.
541 *
542 * If await() is called more then once (without an intervening asleep() call),
543 * await() is still effectively a NOP but it calls mi_switch() to give other
544 * processes some cpu before returning.  The process is left runnable.
545 *
546 * <<<<<<<< EXPERIMENTAL, UNTESTED >>>>>>>>>>
547 */
548
549int
550await(int priority, int timo)
551{
552	struct proc *p = curproc;
553	int s;
554
555	s = splhigh();
556
557	if (p->p_wchan != NULL) {
558		struct callout_handle thandle;
559		int sig;
560		int catch;
561
562		/*
563		 * The call to await() can override defaults specified in
564		 * the original asleep().
565		 */
566		if (priority < 0)
567			priority = p->p_asleep.as_priority;
568		if (timo < 0)
569			timo = p->p_asleep.as_timo;
570
571		/*
572		 * Install timeout
573		 */
574
575		if (timo)
576			thandle = timeout(endtsleep, (void *)p, timo);
577
578		sig = 0;
579		catch = priority & PCATCH;
580
581		if (catch) {
582			p->p_flag |= P_SINTR;
583			if ((sig = CURSIG(p))) {
584				if (p->p_wchan)
585					unsleep(p);
586				p->p_stat = SRUN;
587				goto resume;
588			}
589			if (p->p_wchan == NULL) {
590				catch = 0;
591				goto resume;
592			}
593		}
594		p->p_stat = SSLEEP;
595		p->p_stats->p_ru.ru_nvcsw++;
596		mi_switch();
597resume:
598		curpriority = p->p_usrpri;
599
600		splx(s);
601		p->p_flag &= ~P_SINTR;
602		if (p->p_flag & P_TIMEOUT) {
603			p->p_flag &= ~P_TIMEOUT;
604			if (sig == 0) {
605#ifdef KTRACE
606				if (KTRPOINT(p, KTR_CSW))
607					ktrcsw(p->p_tracep, 0, 0);
608#endif
609				return (EWOULDBLOCK);
610			}
611		} else if (timo)
612			untimeout(endtsleep, (void *)p, thandle);
613		if (catch && (sig != 0 || (sig = CURSIG(p)))) {
614#ifdef KTRACE
615			if (KTRPOINT(p, KTR_CSW))
616				ktrcsw(p->p_tracep, 0, 0);
617#endif
618			if (p->p_sigacts->ps_sigintr & sigmask(sig))
619				return (EINTR);
620			return (ERESTART);
621		}
622#ifdef KTRACE
623		if (KTRPOINT(p, KTR_CSW))
624			ktrcsw(p->p_tracep, 0, 0);
625#endif
626	} else {
627		/*
628		 * If as_priority is 0, await() has been called without an
629		 * intervening asleep().  We are still effectively a NOP,
630		 * but we call mi_switch() for safety.
631		 */
632
633		if (p->p_asleep.as_priority == 0) {
634			p->p_stats->p_ru.ru_nvcsw++;
635			mi_switch();
636		}
637		splx(s);
638	}
639
640	/*
641	 * clear p_asleep.as_priority as an indication that await() has been
642	 * called.  If await() is called again without an intervening asleep(),
643	 * await() is still effectively a NOP but the above mi_switch() code
644	 * is triggered as a safety.
645	 */
646	p->p_asleep.as_priority = 0;
647
648	return (0);
649}
650
651/*
652 * Implement timeout for tsleep or asleep()/await()
653 *
654 * If process hasn't been awakened (wchan non-zero),
655 * set timeout flag and undo the sleep.  If proc
656 * is stopped, just unsleep so it will remain stopped.
657 */
658static void
659endtsleep(arg)
660	void *arg;
661{
662	register struct proc *p;
663	int s;
664
665	p = (struct proc *)arg;
666	s = splhigh();
667	if (p->p_wchan) {
668		if (p->p_stat == SSLEEP)
669			setrunnable(p);
670		else
671			unsleep(p);
672		p->p_flag |= P_TIMEOUT;
673	}
674	splx(s);
675}
676
677/*
678 * Remove a process from its wait queue
679 */
680void
681unsleep(p)
682	register struct proc *p;
683{
684	int s;
685
686	s = splhigh();
687	if (p->p_wchan) {
688		TAILQ_REMOVE(&slpque[LOOKUP(p->p_wchan)], p, p_procq);
689		p->p_wchan = 0;
690	}
691	splx(s);
692}
693
694/*
695 * Make all processes sleeping on the specified identifier runnable.
696 */
697void
698wakeup(ident)
699	register void *ident;
700{
701	register struct slpquehead *qp;
702	register struct proc *p;
703	int s;
704
705	s = splhigh();
706	qp = &slpque[LOOKUP(ident)];
707restart:
708	for (p = qp->tqh_first; p != NULL; p = p->p_procq.tqe_next) {
709#ifdef DIAGNOSTIC
710#ifdef NOTDEF
711		/*
712		 * The process can legitimately be running now with
713		 * asleep()/await().
714		 */
715		if (p->p_stat != SSLEEP && p->p_stat != SSTOP)
716			panic("wakeup");
717#endif
718#endif
719		if (p->p_wchan == ident) {
720			TAILQ_REMOVE(qp, p, p_procq);
721			p->p_wchan = 0;
722			if (p->p_stat == SSLEEP) {
723				/* OPTIMIZED EXPANSION OF setrunnable(p); */
724				if (p->p_slptime > 1)
725					updatepri(p);
726				p->p_slptime = 0;
727				p->p_stat = SRUN;
728				if (p->p_flag & P_INMEM) {
729					setrunqueue(p);
730					maybe_resched(p);
731				} else {
732					p->p_flag |= P_SWAPINREQ;
733					wakeup((caddr_t)&proc0);
734				}
735				/* END INLINE EXPANSION */
736				goto restart;
737			}
738		}
739	}
740	splx(s);
741}
742
743/*
744 * Make a process sleeping on the specified identifier runnable.
745 * May wake more than one process if a target prcoess is currently
746 * swapped out.
747 */
748void
749wakeup_one(ident)
750	register void *ident;
751{
752	register struct slpquehead *qp;
753	register struct proc *p;
754	int s;
755
756	s = splhigh();
757	qp = &slpque[LOOKUP(ident)];
758
759	for (p = qp->tqh_first; p != NULL; p = p->p_procq.tqe_next) {
760#ifdef DIAGNOSTIC
761#ifdef NOTDEF
762		/*
763		 * The process can legitimately be running now with
764		 * asleep()/await().
765		 */
766		if (p->p_stat != SSLEEP && p->p_stat != SSTOP)
767			panic("wakeup_one");
768#endif
769#endif
770		if (p->p_wchan == ident) {
771			TAILQ_REMOVE(qp, p, p_procq);
772			p->p_wchan = 0;
773			if (p->p_stat == SSLEEP) {
774				/* OPTIMIZED EXPANSION OF setrunnable(p); */
775				if (p->p_slptime > 1)
776					updatepri(p);
777				p->p_slptime = 0;
778				p->p_stat = SRUN;
779				if (p->p_flag & P_INMEM) {
780					setrunqueue(p);
781					maybe_resched(p);
782					break;
783				} else {
784					p->p_flag |= P_SWAPINREQ;
785					wakeup((caddr_t)&proc0);
786				}
787				/* END INLINE EXPANSION */
788			}
789		}
790	}
791	splx(s);
792}
793
794/*
795 * The machine independent parts of mi_switch().
796 * Must be called at splstatclock() or higher.
797 */
798void
799mi_switch()
800{
801	register struct proc *p = curproc;	/* XXX */
802	register struct rlimit *rlim;
803	int x;
804
805	/*
806	 * XXX this spl is almost unnecessary.  It is partly to allow for
807	 * sloppy callers that don't do it (issignal() via CURSIG() is the
808	 * main offender).  It is partly to work around a bug in the i386
809	 * cpu_switch() (the ipl is not preserved).  We ran for years
810	 * without it.  I think there was only a interrupt latency problem.
811	 * The main caller, tsleep(), does an splx() a couple of instructions
812	 * after calling here.  The buggy caller, issignal(), usually calls
813	 * here at spl0() and sometimes returns at splhigh().  The process
814	 * then runs for a little too long at splhigh().  The ipl gets fixed
815	 * when the process returns to user mode (or earlier).
816	 *
817	 * It would probably be better to always call here at spl0(). Callers
818	 * are prepared to give up control to another process, so they must
819	 * be prepared to be interrupted.  The clock stuff here may not
820	 * actually need splstatclock().
821	 */
822	x = splstatclock();
823
824#ifdef SIMPLELOCK_DEBUG
825	if (p->p_simple_locks)
826		printf("sleep: holding simple lock\n");
827#endif
828	/*
829	 * Compute the amount of time during which the current
830	 * process was running, and add that to its total so far.
831	 */
832	microuptime(&switchtime);
833	p->p_runtime += (switchtime.tv_usec - p->p_switchtime.tv_usec) +
834	    (switchtime.tv_sec - p->p_switchtime.tv_sec) * (int64_t)1000000;
835
836	/*
837	 * Check if the process exceeds its cpu resource allocation.
838	 * If over max, kill it.
839	 */
840	if (p->p_stat != SZOMB && p->p_limit->p_cpulimit != RLIM_INFINITY &&
841	    p->p_runtime > p->p_limit->p_cpulimit) {
842		rlim = &p->p_rlimit[RLIMIT_CPU];
843		if (p->p_runtime / (rlim_t)1000000 >= rlim->rlim_max) {
844			killproc(p, "exceeded maximum CPU limit");
845		} else {
846			psignal(p, SIGXCPU);
847			if (rlim->rlim_cur < rlim->rlim_max) {
848				/* XXX: we should make a private copy */
849				rlim->rlim_cur += 5;
850			}
851		}
852	}
853
854	/*
855	 * Pick a new current process and record its start time.
856	 */
857	cnt.v_swtch++;
858	cpu_switch(p);
859	if (switchtime.tv_sec)
860		p->p_switchtime = switchtime;
861	else
862		microuptime(&p->p_switchtime);
863	splx(x);
864}
865
866/*
867 * Initialize the (doubly-linked) run queues
868 * to be empty.
869 */
870/* ARGSUSED*/
871static void
872rqinit(dummy)
873	void *dummy;
874{
875	register int i;
876
877	for (i = 0; i < NQS; i++) {
878		qs[i].ph_link = qs[i].ph_rlink = (struct proc *)&qs[i];
879		rtqs[i].ph_link = rtqs[i].ph_rlink = (struct proc *)&rtqs[i];
880		idqs[i].ph_link = idqs[i].ph_rlink = (struct proc *)&idqs[i];
881	}
882}
883
884/*
885 * Change process state to be runnable,
886 * placing it on the run queue if it is in memory,
887 * and awakening the swapper if it isn't in memory.
888 */
889void
890setrunnable(p)
891	register struct proc *p;
892{
893	register int s;
894
895	s = splhigh();
896	switch (p->p_stat) {
897	case 0:
898	case SRUN:
899	case SZOMB:
900	default:
901		panic("setrunnable");
902	case SSTOP:
903	case SSLEEP:
904		unsleep(p);		/* e.g. when sending signals */
905		break;
906
907	case SIDL:
908		break;
909	}
910	p->p_stat = SRUN;
911	if (p->p_flag & P_INMEM)
912		setrunqueue(p);
913	splx(s);
914	if (p->p_slptime > 1)
915		updatepri(p);
916	p->p_slptime = 0;
917	if ((p->p_flag & P_INMEM) == 0) {
918		p->p_flag |= P_SWAPINREQ;
919		wakeup((caddr_t)&proc0);
920	}
921	else
922		maybe_resched(p);
923}
924
925/*
926 * Compute the priority of a process when running in user mode.
927 * Arrange to reschedule if the resulting priority is better
928 * than that of the current process.
929 */
930void
931resetpriority(p)
932	register struct proc *p;
933{
934	register unsigned int newpriority;
935
936	if (p->p_rtprio.type == RTP_PRIO_NORMAL) {
937		newpriority = PUSER + p->p_estcpu / 4 + 2 * p->p_nice;
938		newpriority = min(newpriority, MAXPRI);
939		p->p_usrpri = newpriority;
940	}
941	maybe_resched(p);
942}
943
944/* ARGSUSED */
945static void sched_setup __P((void *dummy));
946static void
947sched_setup(dummy)
948	void *dummy;
949{
950	/* Kick off timeout driven events by calling first time. */
951	roundrobin(NULL);
952	schedcpu(NULL);
953}
954SYSINIT(sched_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, sched_setup, NULL)
955
956