kern_synch.c revision 42453
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.71 1999/01/08 17:31:10 eivind 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	KASSERT(p != NULL, ("tsleep1"));
405	KASSERT(ident != NULL && p->p_stat == SRUN, ("tsleep"));
406	/*
407	 * Process may be sitting on a slpque if asleep() was called, remove
408	 * it before re-adding.
409	 */
410	if (p->p_wchan != NULL)
411		unsleep(p);
412
413	p->p_wchan = ident;
414	p->p_wmesg = wmesg;
415	p->p_slptime = 0;
416	p->p_priority = priority & PRIMASK;
417	TAILQ_INSERT_TAIL(&slpque[LOOKUP(ident)], p, p_procq);
418	if (timo)
419		thandle = timeout(endtsleep, (void *)p, timo);
420	/*
421	 * We put ourselves on the sleep queue and start our timeout
422	 * before calling CURSIG, as we could stop there, and a wakeup
423	 * or a SIGCONT (or both) could occur while we were stopped.
424	 * A SIGCONT would cause us to be marked as SSLEEP
425	 * without resuming us, thus we must be ready for sleep
426	 * when CURSIG is called.  If the wakeup happens while we're
427	 * stopped, p->p_wchan will be 0 upon return from CURSIG.
428	 */
429	if (catch) {
430		p->p_flag |= P_SINTR;
431		if ((sig = CURSIG(p))) {
432			if (p->p_wchan)
433				unsleep(p);
434			p->p_stat = SRUN;
435			goto resume;
436		}
437		if (p->p_wchan == 0) {
438			catch = 0;
439			goto resume;
440		}
441	} else
442		sig = 0;
443	p->p_stat = SSLEEP;
444	p->p_stats->p_ru.ru_nvcsw++;
445	mi_switch();
446resume:
447	curpriority = p->p_usrpri;
448	splx(s);
449	p->p_flag &= ~P_SINTR;
450	if (p->p_flag & P_TIMEOUT) {
451		p->p_flag &= ~P_TIMEOUT;
452		if (sig == 0) {
453#ifdef KTRACE
454			if (KTRPOINT(p, KTR_CSW))
455				ktrcsw(p->p_tracep, 0, 0);
456#endif
457			return (EWOULDBLOCK);
458		}
459	} else if (timo)
460		untimeout(endtsleep, (void *)p, thandle);
461	if (catch && (sig != 0 || (sig = CURSIG(p)))) {
462#ifdef KTRACE
463		if (KTRPOINT(p, KTR_CSW))
464			ktrcsw(p->p_tracep, 0, 0);
465#endif
466		if (p->p_sigacts->ps_sigintr & sigmask(sig))
467			return (EINTR);
468		return (ERESTART);
469	}
470#ifdef KTRACE
471	if (KTRPOINT(p, KTR_CSW))
472		ktrcsw(p->p_tracep, 0, 0);
473#endif
474	return (0);
475}
476
477/*
478 * asleep() - async sleep call.  Place process on wait queue and return
479 * immediately without blocking.  The process stays runnable until await()
480 * is called.  If ident is NULL, remove process from wait queue if it is still
481 * on one.
482 *
483 * Only the most recent sleep condition is effective when making successive
484 * calls to asleep() or when calling tsleep().
485 *
486 * The timeout, if any, is not initiated until await() is called.  The sleep
487 * priority, signal, and timeout is specified in the asleep() call but may be
488 * overriden in the await() call.
489 *
490 * <<<<<<<< EXPERIMENTAL, UNTESTED >>>>>>>>>>
491 */
492
493int
494asleep(void *ident, int priority, const char *wmesg, int timo)
495{
496	struct proc *p = curproc;
497	int s;
498
499	/*
500	 * splhigh() while manipulating sleep structures and slpque.
501	 *
502	 * Remove preexisting wait condition (if any) and place process
503	 * on appropriate slpque, but do not put process to sleep.
504	 */
505
506	s = splhigh();
507
508	if (p->p_wchan != NULL)
509		unsleep(p);
510
511	if (ident) {
512		p->p_wchan = ident;
513		p->p_wmesg = wmesg;
514		p->p_slptime = 0;
515		p->p_asleep.as_priority = priority;
516		p->p_asleep.as_timo = timo;
517		TAILQ_INSERT_TAIL(&slpque[LOOKUP(ident)], p, p_procq);
518	}
519
520	splx(s);
521
522	return(0);
523}
524
525/*
526 * await() - wait for async condition to occur.   The process blocks until
527 * wakeup() is called on the most recent asleep() address.  If wakeup is called
528 * priority to await(), await() winds up being a NOP.
529 *
530 * If await() is called more then once (without an intervening asleep() call),
531 * await() is still effectively a NOP but it calls mi_switch() to give other
532 * processes some cpu before returning.  The process is left runnable.
533 *
534 * <<<<<<<< EXPERIMENTAL, UNTESTED >>>>>>>>>>
535 */
536
537int
538await(int priority, int timo)
539{
540	struct proc *p = curproc;
541	int s;
542
543	s = splhigh();
544
545	if (p->p_wchan != NULL) {
546		struct callout_handle thandle;
547		int sig;
548		int catch;
549
550		/*
551		 * The call to await() can override defaults specified in
552		 * the original asleep().
553		 */
554		if (priority < 0)
555			priority = p->p_asleep.as_priority;
556		if (timo < 0)
557			timo = p->p_asleep.as_timo;
558
559		/*
560		 * Install timeout
561		 */
562
563		if (timo)
564			thandle = timeout(endtsleep, (void *)p, timo);
565
566		sig = 0;
567		catch = priority & PCATCH;
568
569		if (catch) {
570			p->p_flag |= P_SINTR;
571			if ((sig = CURSIG(p))) {
572				if (p->p_wchan)
573					unsleep(p);
574				p->p_stat = SRUN;
575				goto resume;
576			}
577			if (p->p_wchan == NULL) {
578				catch = 0;
579				goto resume;
580			}
581		}
582		p->p_stat = SSLEEP;
583		p->p_stats->p_ru.ru_nvcsw++;
584		mi_switch();
585resume:
586		curpriority = p->p_usrpri;
587
588		splx(s);
589		p->p_flag &= ~P_SINTR;
590		if (p->p_flag & P_TIMEOUT) {
591			p->p_flag &= ~P_TIMEOUT;
592			if (sig == 0) {
593#ifdef KTRACE
594				if (KTRPOINT(p, KTR_CSW))
595					ktrcsw(p->p_tracep, 0, 0);
596#endif
597				return (EWOULDBLOCK);
598			}
599		} else if (timo)
600			untimeout(endtsleep, (void *)p, thandle);
601		if (catch && (sig != 0 || (sig = CURSIG(p)))) {
602#ifdef KTRACE
603			if (KTRPOINT(p, KTR_CSW))
604				ktrcsw(p->p_tracep, 0, 0);
605#endif
606			if (p->p_sigacts->ps_sigintr & sigmask(sig))
607				return (EINTR);
608			return (ERESTART);
609		}
610#ifdef KTRACE
611		if (KTRPOINT(p, KTR_CSW))
612			ktrcsw(p->p_tracep, 0, 0);
613#endif
614	} else {
615		/*
616		 * If as_priority is 0, await() has been called without an
617		 * intervening asleep().  We are still effectively a NOP,
618		 * but we call mi_switch() for safety.
619		 */
620
621		if (p->p_asleep.as_priority == 0) {
622			p->p_stats->p_ru.ru_nvcsw++;
623			mi_switch();
624		}
625		splx(s);
626	}
627
628	/*
629	 * clear p_asleep.as_priority as an indication that await() has been
630	 * called.  If await() is called again without an intervening asleep(),
631	 * await() is still effectively a NOP but the above mi_switch() code
632	 * is triggered as a safety.
633	 */
634	p->p_asleep.as_priority = 0;
635
636	return (0);
637}
638
639/*
640 * Implement timeout for tsleep or asleep()/await()
641 *
642 * If process hasn't been awakened (wchan non-zero),
643 * set timeout flag and undo the sleep.  If proc
644 * is stopped, just unsleep so it will remain stopped.
645 */
646static void
647endtsleep(arg)
648	void *arg;
649{
650	register struct proc *p;
651	int s;
652
653	p = (struct proc *)arg;
654	s = splhigh();
655	if (p->p_wchan) {
656		if (p->p_stat == SSLEEP)
657			setrunnable(p);
658		else
659			unsleep(p);
660		p->p_flag |= P_TIMEOUT;
661	}
662	splx(s);
663}
664
665/*
666 * Remove a process from its wait queue
667 */
668void
669unsleep(p)
670	register struct proc *p;
671{
672	int s;
673
674	s = splhigh();
675	if (p->p_wchan) {
676		TAILQ_REMOVE(&slpque[LOOKUP(p->p_wchan)], p, p_procq);
677		p->p_wchan = 0;
678	}
679	splx(s);
680}
681
682/*
683 * Make all processes sleeping on the specified identifier runnable.
684 */
685void
686wakeup(ident)
687	register void *ident;
688{
689	register struct slpquehead *qp;
690	register struct proc *p;
691	int s;
692
693	s = splhigh();
694	qp = &slpque[LOOKUP(ident)];
695restart:
696	for (p = qp->tqh_first; p != NULL; p = p->p_procq.tqe_next) {
697		if (p->p_wchan == ident) {
698			TAILQ_REMOVE(qp, p, p_procq);
699			p->p_wchan = 0;
700			if (p->p_stat == SSLEEP) {
701				/* OPTIMIZED EXPANSION OF setrunnable(p); */
702				if (p->p_slptime > 1)
703					updatepri(p);
704				p->p_slptime = 0;
705				p->p_stat = SRUN;
706				if (p->p_flag & P_INMEM) {
707					setrunqueue(p);
708					maybe_resched(p);
709				} else {
710					p->p_flag |= P_SWAPINREQ;
711					wakeup((caddr_t)&proc0);
712				}
713				/* END INLINE EXPANSION */
714				goto restart;
715			}
716		}
717	}
718	splx(s);
719}
720
721/*
722 * Make a process sleeping on the specified identifier runnable.
723 * May wake more than one process if a target prcoess is currently
724 * swapped out.
725 */
726void
727wakeup_one(ident)
728	register void *ident;
729{
730	register struct slpquehead *qp;
731	register struct proc *p;
732	int s;
733
734	s = splhigh();
735	qp = &slpque[LOOKUP(ident)];
736
737	for (p = qp->tqh_first; p != NULL; p = p->p_procq.tqe_next) {
738		if (p->p_wchan == ident) {
739			TAILQ_REMOVE(qp, p, p_procq);
740			p->p_wchan = 0;
741			if (p->p_stat == SSLEEP) {
742				/* OPTIMIZED EXPANSION OF setrunnable(p); */
743				if (p->p_slptime > 1)
744					updatepri(p);
745				p->p_slptime = 0;
746				p->p_stat = SRUN;
747				if (p->p_flag & P_INMEM) {
748					setrunqueue(p);
749					maybe_resched(p);
750					break;
751				} else {
752					p->p_flag |= P_SWAPINREQ;
753					wakeup((caddr_t)&proc0);
754				}
755				/* END INLINE EXPANSION */
756			}
757		}
758	}
759	splx(s);
760}
761
762/*
763 * The machine independent parts of mi_switch().
764 * Must be called at splstatclock() or higher.
765 */
766void
767mi_switch()
768{
769	register struct proc *p = curproc;	/* XXX */
770	register struct rlimit *rlim;
771	int x;
772
773	/*
774	 * XXX this spl is almost unnecessary.  It is partly to allow for
775	 * sloppy callers that don't do it (issignal() via CURSIG() is the
776	 * main offender).  It is partly to work around a bug in the i386
777	 * cpu_switch() (the ipl is not preserved).  We ran for years
778	 * without it.  I think there was only a interrupt latency problem.
779	 * The main caller, tsleep(), does an splx() a couple of instructions
780	 * after calling here.  The buggy caller, issignal(), usually calls
781	 * here at spl0() and sometimes returns at splhigh().  The process
782	 * then runs for a little too long at splhigh().  The ipl gets fixed
783	 * when the process returns to user mode (or earlier).
784	 *
785	 * It would probably be better to always call here at spl0(). Callers
786	 * are prepared to give up control to another process, so they must
787	 * be prepared to be interrupted.  The clock stuff here may not
788	 * actually need splstatclock().
789	 */
790	x = splstatclock();
791
792#ifdef SIMPLELOCK_DEBUG
793	if (p->p_simple_locks)
794		printf("sleep: holding simple lock\n");
795#endif
796	/*
797	 * Compute the amount of time during which the current
798	 * process was running, and add that to its total so far.
799	 */
800	microuptime(&switchtime);
801	p->p_runtime += (switchtime.tv_usec - p->p_switchtime.tv_usec) +
802	    (switchtime.tv_sec - p->p_switchtime.tv_sec) * (int64_t)1000000;
803
804	/*
805	 * Check if the process exceeds its cpu resource allocation.
806	 * If over max, kill it.
807	 */
808	if (p->p_stat != SZOMB && p->p_limit->p_cpulimit != RLIM_INFINITY &&
809	    p->p_runtime > p->p_limit->p_cpulimit) {
810		rlim = &p->p_rlimit[RLIMIT_CPU];
811		if (p->p_runtime / (rlim_t)1000000 >= rlim->rlim_max) {
812			killproc(p, "exceeded maximum CPU limit");
813		} else {
814			psignal(p, SIGXCPU);
815			if (rlim->rlim_cur < rlim->rlim_max) {
816				/* XXX: we should make a private copy */
817				rlim->rlim_cur += 5;
818			}
819		}
820	}
821
822	/*
823	 * Pick a new current process and record its start time.
824	 */
825	cnt.v_swtch++;
826	cpu_switch(p);
827	if (switchtime.tv_sec)
828		p->p_switchtime = switchtime;
829	else
830		microuptime(&p->p_switchtime);
831	splx(x);
832}
833
834/*
835 * Initialize the (doubly-linked) run queues
836 * to be empty.
837 */
838/* ARGSUSED*/
839static void
840rqinit(dummy)
841	void *dummy;
842{
843	register int i;
844
845	for (i = 0; i < NQS; i++) {
846		qs[i].ph_link = qs[i].ph_rlink = (struct proc *)&qs[i];
847		rtqs[i].ph_link = rtqs[i].ph_rlink = (struct proc *)&rtqs[i];
848		idqs[i].ph_link = idqs[i].ph_rlink = (struct proc *)&idqs[i];
849	}
850}
851
852/*
853 * Change process state to be runnable,
854 * placing it on the run queue if it is in memory,
855 * and awakening the swapper if it isn't in memory.
856 */
857void
858setrunnable(p)
859	register struct proc *p;
860{
861	register int s;
862
863	s = splhigh();
864	switch (p->p_stat) {
865	case 0:
866	case SRUN:
867	case SZOMB:
868	default:
869		panic("setrunnable");
870	case SSTOP:
871	case SSLEEP:
872		unsleep(p);		/* e.g. when sending signals */
873		break;
874
875	case SIDL:
876		break;
877	}
878	p->p_stat = SRUN;
879	if (p->p_flag & P_INMEM)
880		setrunqueue(p);
881	splx(s);
882	if (p->p_slptime > 1)
883		updatepri(p);
884	p->p_slptime = 0;
885	if ((p->p_flag & P_INMEM) == 0) {
886		p->p_flag |= P_SWAPINREQ;
887		wakeup((caddr_t)&proc0);
888	}
889	else
890		maybe_resched(p);
891}
892
893/*
894 * Compute the priority of a process when running in user mode.
895 * Arrange to reschedule if the resulting priority is better
896 * than that of the current process.
897 */
898void
899resetpriority(p)
900	register struct proc *p;
901{
902	register unsigned int newpriority;
903
904	if (p->p_rtprio.type == RTP_PRIO_NORMAL) {
905		newpriority = PUSER + p->p_estcpu / 4 + 2 * p->p_nice;
906		newpriority = min(newpriority, MAXPRI);
907		p->p_usrpri = newpriority;
908	}
909	maybe_resched(p);
910}
911
912/* ARGSUSED */
913static void sched_setup __P((void *dummy));
914static void
915sched_setup(dummy)
916	void *dummy;
917{
918	/* Kick off timeout driven events by calling first time. */
919	roundrobin(NULL);
920	schedcpu(NULL);
921}
922SYSINIT(sched_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, sched_setup, NULL)
923
924