kern_synch.c revision 57701
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 * $FreeBSD: head/sys/kern/kern_synch.c 57701 2000-03-02 16:20:07Z dufault $
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
64static void sched_setup __P((void *dummy));
65SYSINIT(sched_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, sched_setup, NULL)
66
67u_char	curpriority;
68u_char	currtpriority;
69int	hogticks;
70int	lbolt;
71int	sched_quantum;		/* Roundrobin scheduling quantum in ticks. */
72
73static int	curpriority_cmp __P((struct proc *p));
74static void	endtsleep __P((void *));
75static void	maybe_resched __P((struct proc *chk));
76static void	roundrobin __P((void *arg));
77static void	schedcpu __P((void *arg));
78static void	updatepri __P((struct proc *p));
79
80static int
81sysctl_kern_quantum SYSCTL_HANDLER_ARGS
82{
83	int error, new_val;
84
85	new_val = sched_quantum * tick;
86	error = sysctl_handle_int(oidp, &new_val, 0, req);
87        if (error != 0 || req->newptr == NULL)
88		return (error);
89	if (new_val < tick)
90		return (EINVAL);
91	sched_quantum = new_val / tick;
92	hogticks = 2 * sched_quantum;
93	return (0);
94}
95
96SYSCTL_PROC(_kern, OID_AUTO, quantum, CTLTYPE_INT|CTLFLAG_RW,
97	0, sizeof sched_quantum, sysctl_kern_quantum, "I", "");
98
99/*-
100 * Compare priorities.  Return:
101 *     <0: priority of p < current priority
102 *      0: priority of p == current priority
103 *     >0: priority of p > current priority
104 * The priorities are the normal priorities or the normal realtime priorities
105 * if p is on the same scheduler as curproc.  Otherwise the process on the
106 * more realtimeish scheduler has lowest priority.  As usual, a higher
107 * priority really means a lower priority.
108 */
109static int
110curpriority_cmp(p)
111	struct proc *p;
112{
113	int c_class, p_class;
114
115	if (curproc->p_rtprio.prio != currtpriority)
116		Debugger("currtprio");
117	c_class = RTP_PRIO_BASE(curproc->p_rtprio.type);
118	p_class = RTP_PRIO_BASE(p->p_rtprio.type);
119	if (p_class != c_class)
120		return (p_class - c_class);
121	if (p_class == RTP_PRIO_NORMAL)
122		return (((int)p->p_priority - (int)curpriority) / PPQ);
123	return ((int)p->p_rtprio.prio - (int)currtpriority);
124}
125
126/*
127 * Arrange to reschedule if necessary, taking the priorities and
128 * schedulers into account.
129 */
130static void
131maybe_resched(chk)
132	struct proc *chk;
133{
134	struct proc *p = curproc; /* XXX */
135
136	/*
137	 * XXX idle scheduler still broken because proccess stays on idle
138	 * scheduler during waits (such as when getting FS locks).  If a
139	 * standard process becomes runaway cpu-bound, the system can lockup
140	 * due to idle-scheduler processes in wakeup never getting any cpu.
141	 */
142	if (p == NULL) {
143#if 0
144		need_resched();
145#endif
146	} else if (chk == p) {
147		/* We may need to yield if our priority has been raised. */
148		if (curpriority_cmp(chk) > 0)
149			need_resched();
150	} else if (curpriority_cmp(chk) < 0)
151		need_resched();
152}
153
154int
155roundrobin_interval(void)
156{
157	return (sched_quantum);
158}
159
160/*
161 * Force switch among equal priority processes every 100ms.
162 */
163/* ARGSUSED */
164static void
165roundrobin(arg)
166	void *arg;
167{
168#ifndef SMP
169 	struct proc *p = curproc; /* XXX */
170#endif
171
172#ifdef SMP
173	need_resched();
174	forward_roundrobin();
175#else
176 	if (p == 0 || RTP_PRIO_NEED_RR(p->p_rtprio.type))
177 		need_resched();
178#endif
179
180 	timeout(roundrobin, NULL, sched_quantum);
181}
182
183/*
184 * Constants for digital decay and forget:
185 *	90% of (p_estcpu) usage in 5 * loadav time
186 *	95% of (p_pctcpu) usage in 60 seconds (load insensitive)
187 *          Note that, as ps(1) mentions, this can let percentages
188 *          total over 100% (I've seen 137.9% for 3 processes).
189 *
190 * Note that schedclock() updates p_estcpu and p_cpticks asynchronously.
191 *
192 * We wish to decay away 90% of p_estcpu in (5 * loadavg) seconds.
193 * That is, the system wants to compute a value of decay such
194 * that the following for loop:
195 * 	for (i = 0; i < (5 * loadavg); i++)
196 * 		p_estcpu *= decay;
197 * will compute
198 * 	p_estcpu *= 0.1;
199 * for all values of loadavg:
200 *
201 * Mathematically this loop can be expressed by saying:
202 * 	decay ** (5 * loadavg) ~= .1
203 *
204 * The system computes decay as:
205 * 	decay = (2 * loadavg) / (2 * loadavg + 1)
206 *
207 * We wish to prove that the system's computation of decay
208 * will always fulfill the equation:
209 * 	decay ** (5 * loadavg) ~= .1
210 *
211 * If we compute b as:
212 * 	b = 2 * loadavg
213 * then
214 * 	decay = b / (b + 1)
215 *
216 * We now need to prove two things:
217 *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
218 *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
219 *
220 * Facts:
221 *         For x close to zero, exp(x) =~ 1 + x, since
222 *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
223 *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
224 *         For x close to zero, ln(1+x) =~ x, since
225 *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
226 *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
227 *         ln(.1) =~ -2.30
228 *
229 * Proof of (1):
230 *    Solve (factor)**(power) =~ .1 given power (5*loadav):
231 *	solving for factor,
232 *      ln(factor) =~ (-2.30/5*loadav), or
233 *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
234 *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
235 *
236 * Proof of (2):
237 *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
238 *	solving for power,
239 *      power*ln(b/(b+1)) =~ -2.30, or
240 *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
241 *
242 * Actual power values for the implemented algorithm are as follows:
243 *      loadav: 1       2       3       4
244 *      power:  5.68    10.32   14.94   19.55
245 */
246
247/* calculations for digital decay to forget 90% of usage in 5*loadav sec */
248#define	loadfactor(loadav)	(2 * (loadav))
249#define	decay_cpu(loadfac, cpu)	(((loadfac) * (cpu)) / ((loadfac) + FSCALE))
250
251/* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
252static fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;	/* exp(-1/20) */
253SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
254
255/* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */
256static int	fscale __unused = FSCALE;
257SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, "");
258
259/*
260 * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
261 * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
262 * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
263 *
264 * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
265 *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
266 *
267 * If you don't want to bother with the faster/more-accurate formula, you
268 * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
269 * (more general) method of calculating the %age of CPU used by a process.
270 */
271#define	CCPU_SHIFT	11
272
273/*
274 * Recompute process priorities, every hz ticks.
275 */
276/* ARGSUSED */
277static void
278schedcpu(arg)
279	void *arg;
280{
281	register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
282	register struct proc *p;
283	register int realstathz, s;
284
285	realstathz = stathz ? stathz : hz;
286	LIST_FOREACH(p, &allproc, p_list) {
287		/*
288		 * Increment time in/out of memory and sleep time
289		 * (if sleeping).  We ignore overflow; with 16-bit int's
290		 * (remember them?) overflow takes 45 days.
291		 */
292		p->p_swtime++;
293		if (p->p_stat == SSLEEP || p->p_stat == SSTOP)
294			p->p_slptime++;
295		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
296		/*
297		 * If the process has slept the entire second,
298		 * stop recalculating its priority until it wakes up.
299		 */
300		if (p->p_slptime > 1)
301			continue;
302		s = splhigh();	/* prevent state changes and protect run queue */
303		/*
304		 * p_pctcpu is only for ps.
305		 */
306#if	(FSHIFT >= CCPU_SHIFT)
307		p->p_pctcpu += (realstathz == 100)?
308			((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT):
309                	100 * (((fixpt_t) p->p_cpticks)
310				<< (FSHIFT - CCPU_SHIFT)) / realstathz;
311#else
312		p->p_pctcpu += ((FSCALE - ccpu) *
313			(p->p_cpticks * FSCALE / realstathz)) >> FSHIFT;
314#endif
315		p->p_cpticks = 0;
316		p->p_estcpu = decay_cpu(loadfac, p->p_estcpu);
317		resetpriority(p);
318		if (p->p_priority >= PUSER) {
319			if ((p != curproc) &&
320#ifdef SMP
321			    p->p_oncpu == 0xff && 	/* idle */
322#endif
323			    p->p_stat == SRUN &&
324			    (p->p_flag & P_INMEM) &&
325			    (p->p_priority / PPQ) != (p->p_usrpri / PPQ)) {
326				remrunqueue(p);
327				p->p_priority = p->p_usrpri;
328				setrunqueue(p);
329			} else
330				p->p_priority = p->p_usrpri;
331		}
332		splx(s);
333	}
334	vmmeter();
335	wakeup((caddr_t)&lbolt);
336	timeout(schedcpu, (void *)0, hz);
337}
338
339/*
340 * Recalculate the priority of a process after it has slept for a while.
341 * For all load averages >= 1 and max p_estcpu of 255, sleeping for at
342 * least six times the loadfactor will decay p_estcpu to zero.
343 */
344static void
345updatepri(p)
346	register struct proc *p;
347{
348	register unsigned int newcpu = p->p_estcpu;
349	register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
350
351	if (p->p_slptime > 5 * loadfac)
352		p->p_estcpu = 0;
353	else {
354		p->p_slptime--;	/* the first time was done in schedcpu */
355		while (newcpu && --p->p_slptime)
356			newcpu = decay_cpu(loadfac, newcpu);
357		p->p_estcpu = newcpu;
358	}
359	resetpriority(p);
360}
361
362/*
363 * We're only looking at 7 bits of the address; everything is
364 * aligned to 4, lots of things are aligned to greater powers
365 * of 2.  Shift right by 8, i.e. drop the bottom 256 worth.
366 */
367#define TABLESIZE	128
368static TAILQ_HEAD(slpquehead, proc) slpque[TABLESIZE];
369#define LOOKUP(x)	(((intptr_t)(x) >> 8) & (TABLESIZE - 1))
370
371/*
372 * During autoconfiguration or after a panic, a sleep will simply
373 * lower the priority briefly to allow interrupts, then return.
374 * The priority to be used (safepri) is machine-dependent, thus this
375 * value is initialized and maintained in the machine-dependent layers.
376 * This priority will typically be 0, or the lowest priority
377 * that is safe for use on the interrupt stack; it can be made
378 * higher to block network software interrupts after panics.
379 */
380int safepri;
381
382void
383sleepinit(void)
384{
385	int i;
386
387	sched_quantum = hz/10;
388	hogticks = 2 * sched_quantum;
389	for (i = 0; i < TABLESIZE; i++)
390		TAILQ_INIT(&slpque[i]);
391}
392
393/*
394 * General sleep call.  Suspends the current process until a wakeup is
395 * performed on the specified identifier.  The process will then be made
396 * runnable with the specified priority.  Sleeps at most timo/hz seconds
397 * (0 means no timeout).  If pri includes PCATCH flag, signals are checked
398 * before and after sleeping, else signals are not checked.  Returns 0 if
399 * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
400 * signal needs to be delivered, ERESTART is returned if the current system
401 * call should be restarted if possible, and EINTR is returned if the system
402 * call should be interrupted by the signal (return EINTR).
403 */
404int
405tsleep(ident, priority, wmesg, timo)
406	void *ident;
407	int priority, timo;
408	const char *wmesg;
409{
410	struct proc *p = curproc;
411	int s, sig, catch = priority & PCATCH;
412	struct callout_handle thandle;
413
414#ifdef KTRACE
415	if (p && KTRPOINT(p, KTR_CSW))
416		ktrcsw(p->p_tracep, 1, 0);
417#endif
418	s = splhigh();
419	if (cold || panicstr) {
420		/*
421		 * After a panic, or during autoconfiguration,
422		 * just give interrupts a chance, then just return;
423		 * don't run any other procs or panic below,
424		 * in case this is the idle process and already asleep.
425		 */
426		splx(safepri);
427		splx(s);
428		return (0);
429	}
430	KASSERT(p != NULL, ("tsleep1"));
431	KASSERT(ident != NULL && p->p_stat == SRUN, ("tsleep"));
432	/*
433	 * Process may be sitting on a slpque if asleep() was called, remove
434	 * it before re-adding.
435	 */
436	if (p->p_wchan != NULL)
437		unsleep(p);
438
439	p->p_wchan = ident;
440	p->p_wmesg = wmesg;
441	p->p_slptime = 0;
442	p->p_priority = priority & PRIMASK;
443	TAILQ_INSERT_TAIL(&slpque[LOOKUP(ident)], p, p_procq);
444	if (timo)
445		thandle = timeout(endtsleep, (void *)p, timo);
446	/*
447	 * We put ourselves on the sleep queue and start our timeout
448	 * before calling CURSIG, as we could stop there, and a wakeup
449	 * or a SIGCONT (or both) could occur while we were stopped.
450	 * A SIGCONT would cause us to be marked as SSLEEP
451	 * without resuming us, thus we must be ready for sleep
452	 * when CURSIG is called.  If the wakeup happens while we're
453	 * stopped, p->p_wchan will be 0 upon return from CURSIG.
454	 */
455	if (catch) {
456		p->p_flag |= P_SINTR;
457		if ((sig = CURSIG(p))) {
458			if (p->p_wchan)
459				unsleep(p);
460			p->p_stat = SRUN;
461			goto resume;
462		}
463		if (p->p_wchan == 0) {
464			catch = 0;
465			goto resume;
466		}
467	} else
468		sig = 0;
469	p->p_stat = SSLEEP;
470	p->p_stats->p_ru.ru_nvcsw++;
471	mi_switch();
472resume:
473	curpriority = p->p_usrpri;
474	currtpriority = p->p_rtprio.prio;
475	splx(s);
476	p->p_flag &= ~P_SINTR;
477	if (p->p_flag & P_TIMEOUT) {
478		p->p_flag &= ~P_TIMEOUT;
479		if (sig == 0) {
480#ifdef KTRACE
481			if (KTRPOINT(p, KTR_CSW))
482				ktrcsw(p->p_tracep, 0, 0);
483#endif
484			return (EWOULDBLOCK);
485		}
486	} else if (timo)
487		untimeout(endtsleep, (void *)p, thandle);
488	if (catch && (sig != 0 || (sig = CURSIG(p)))) {
489#ifdef KTRACE
490		if (KTRPOINT(p, KTR_CSW))
491			ktrcsw(p->p_tracep, 0, 0);
492#endif
493		if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
494			return (EINTR);
495		return (ERESTART);
496	}
497#ifdef KTRACE
498	if (KTRPOINT(p, KTR_CSW))
499		ktrcsw(p->p_tracep, 0, 0);
500#endif
501	return (0);
502}
503
504/*
505 * asleep() - async sleep call.  Place process on wait queue and return
506 * immediately without blocking.  The process stays runnable until await()
507 * is called.  If ident is NULL, remove process from wait queue if it is still
508 * on one.
509 *
510 * Only the most recent sleep condition is effective when making successive
511 * calls to asleep() or when calling tsleep().
512 *
513 * The timeout, if any, is not initiated until await() is called.  The sleep
514 * priority, signal, and timeout is specified in the asleep() call but may be
515 * overriden in the await() call.
516 *
517 * <<<<<<<< EXPERIMENTAL, UNTESTED >>>>>>>>>>
518 */
519
520int
521asleep(void *ident, int priority, const char *wmesg, int timo)
522{
523	struct proc *p = curproc;
524	int s;
525
526	/*
527	 * splhigh() while manipulating sleep structures and slpque.
528	 *
529	 * Remove preexisting wait condition (if any) and place process
530	 * on appropriate slpque, but do not put process to sleep.
531	 */
532
533	s = splhigh();
534
535	if (p->p_wchan != NULL)
536		unsleep(p);
537
538	if (ident) {
539		p->p_wchan = ident;
540		p->p_wmesg = wmesg;
541		p->p_slptime = 0;
542		p->p_asleep.as_priority = priority;
543		p->p_asleep.as_timo = timo;
544		TAILQ_INSERT_TAIL(&slpque[LOOKUP(ident)], p, p_procq);
545	}
546
547	splx(s);
548
549	return(0);
550}
551
552/*
553 * await() - wait for async condition to occur.   The process blocks until
554 * wakeup() is called on the most recent asleep() address.  If wakeup is called
555 * priority to await(), await() winds up being a NOP.
556 *
557 * If await() is called more then once (without an intervening asleep() call),
558 * await() is still effectively a NOP but it calls mi_switch() to give other
559 * processes some cpu before returning.  The process is left runnable.
560 *
561 * <<<<<<<< EXPERIMENTAL, UNTESTED >>>>>>>>>>
562 */
563
564int
565await(int priority, int timo)
566{
567	struct proc *p = curproc;
568	int s;
569
570	s = splhigh();
571
572	if (p->p_wchan != NULL) {
573		struct callout_handle thandle;
574		int sig;
575		int catch;
576
577		/*
578		 * The call to await() can override defaults specified in
579		 * the original asleep().
580		 */
581		if (priority < 0)
582			priority = p->p_asleep.as_priority;
583		if (timo < 0)
584			timo = p->p_asleep.as_timo;
585
586		/*
587		 * Install timeout
588		 */
589
590		if (timo)
591			thandle = timeout(endtsleep, (void *)p, timo);
592
593		sig = 0;
594		catch = priority & PCATCH;
595
596		if (catch) {
597			p->p_flag |= P_SINTR;
598			if ((sig = CURSIG(p))) {
599				if (p->p_wchan)
600					unsleep(p);
601				p->p_stat = SRUN;
602				goto resume;
603			}
604			if (p->p_wchan == NULL) {
605				catch = 0;
606				goto resume;
607			}
608		}
609		p->p_stat = SSLEEP;
610		p->p_stats->p_ru.ru_nvcsw++;
611		mi_switch();
612resume:
613		curpriority = p->p_usrpri;
614		currtpriority = p->p_rtprio.prio;
615
616		splx(s);
617		p->p_flag &= ~P_SINTR;
618		if (p->p_flag & P_TIMEOUT) {
619			p->p_flag &= ~P_TIMEOUT;
620			if (sig == 0) {
621#ifdef KTRACE
622				if (KTRPOINT(p, KTR_CSW))
623					ktrcsw(p->p_tracep, 0, 0);
624#endif
625				return (EWOULDBLOCK);
626			}
627		} else if (timo)
628			untimeout(endtsleep, (void *)p, thandle);
629		if (catch && (sig != 0 || (sig = CURSIG(p)))) {
630#ifdef KTRACE
631			if (KTRPOINT(p, KTR_CSW))
632				ktrcsw(p->p_tracep, 0, 0);
633#endif
634			if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
635				return (EINTR);
636			return (ERESTART);
637		}
638#ifdef KTRACE
639		if (KTRPOINT(p, KTR_CSW))
640			ktrcsw(p->p_tracep, 0, 0);
641#endif
642	} else {
643		/*
644		 * If as_priority is 0, await() has been called without an
645		 * intervening asleep().  We are still effectively a NOP,
646		 * but we call mi_switch() for safety.
647		 */
648
649		if (p->p_asleep.as_priority == 0) {
650			p->p_stats->p_ru.ru_nvcsw++;
651			mi_switch();
652		}
653		splx(s);
654	}
655
656	/*
657	 * clear p_asleep.as_priority as an indication that await() has been
658	 * called.  If await() is called again without an intervening asleep(),
659	 * await() is still effectively a NOP but the above mi_switch() code
660	 * is triggered as a safety.
661	 */
662	p->p_asleep.as_priority = 0;
663
664	return (0);
665}
666
667/*
668 * Implement timeout for tsleep or asleep()/await()
669 *
670 * If process hasn't been awakened (wchan non-zero),
671 * set timeout flag and undo the sleep.  If proc
672 * is stopped, just unsleep so it will remain stopped.
673 */
674static void
675endtsleep(arg)
676	void *arg;
677{
678	register struct proc *p;
679	int s;
680
681	p = (struct proc *)arg;
682	s = splhigh();
683	if (p->p_wchan) {
684		if (p->p_stat == SSLEEP)
685			setrunnable(p);
686		else
687			unsleep(p);
688		p->p_flag |= P_TIMEOUT;
689	}
690	splx(s);
691}
692
693/*
694 * Remove a process from its wait queue
695 */
696void
697unsleep(p)
698	register struct proc *p;
699{
700	int s;
701
702	s = splhigh();
703	if (p->p_wchan) {
704		TAILQ_REMOVE(&slpque[LOOKUP(p->p_wchan)], p, p_procq);
705		p->p_wchan = 0;
706	}
707	splx(s);
708}
709
710/*
711 * Make all processes sleeping on the specified identifier runnable.
712 */
713void
714wakeup(ident)
715	register void *ident;
716{
717	register struct slpquehead *qp;
718	register struct proc *p;
719	int s;
720
721	s = splhigh();
722	qp = &slpque[LOOKUP(ident)];
723restart:
724	TAILQ_FOREACH(p, qp, p_procq) {
725		if (p->p_wchan == ident) {
726			TAILQ_REMOVE(qp, p, p_procq);
727			p->p_wchan = 0;
728			if (p->p_stat == SSLEEP) {
729				/* OPTIMIZED EXPANSION OF setrunnable(p); */
730				if (p->p_slptime > 1)
731					updatepri(p);
732				p->p_slptime = 0;
733				p->p_stat = SRUN;
734				if (p->p_flag & P_INMEM) {
735					setrunqueue(p);
736					maybe_resched(p);
737				} else {
738					p->p_flag |= P_SWAPINREQ;
739					wakeup((caddr_t)&proc0);
740				}
741				/* END INLINE EXPANSION */
742				goto restart;
743			}
744		}
745	}
746	splx(s);
747}
748
749/*
750 * Make a process sleeping on the specified identifier runnable.
751 * May wake more than one process if a target prcoess is currently
752 * swapped out.
753 */
754void
755wakeup_one(ident)
756	register void *ident;
757{
758	register struct slpquehead *qp;
759	register struct proc *p;
760	int s;
761
762	s = splhigh();
763	qp = &slpque[LOOKUP(ident)];
764
765	TAILQ_FOREACH(p, qp, p_procq) {
766		if (p->p_wchan == ident) {
767			TAILQ_REMOVE(qp, p, p_procq);
768			p->p_wchan = 0;
769			if (p->p_stat == SSLEEP) {
770				/* OPTIMIZED EXPANSION OF setrunnable(p); */
771				if (p->p_slptime > 1)
772					updatepri(p);
773				p->p_slptime = 0;
774				p->p_stat = SRUN;
775				if (p->p_flag & P_INMEM) {
776					setrunqueue(p);
777					maybe_resched(p);
778					break;
779				} else {
780					p->p_flag |= P_SWAPINREQ;
781					wakeup((caddr_t)&proc0);
782				}
783				/* END INLINE EXPANSION */
784			}
785		}
786	}
787	splx(s);
788}
789
790/*
791 * The machine independent parts of mi_switch().
792 * Must be called at splstatclock() or higher.
793 */
794void
795mi_switch()
796{
797	struct timeval new_switchtime;
798	register struct proc *p = curproc;	/* XXX */
799	register struct rlimit *rlim;
800	int x;
801
802	/*
803	 * XXX this spl is almost unnecessary.  It is partly to allow for
804	 * sloppy callers that don't do it (issignal() via CURSIG() is the
805	 * main offender).  It is partly to work around a bug in the i386
806	 * cpu_switch() (the ipl is not preserved).  We ran for years
807	 * without it.  I think there was only a interrupt latency problem.
808	 * The main caller, tsleep(), does an splx() a couple of instructions
809	 * after calling here.  The buggy caller, issignal(), usually calls
810	 * here at spl0() and sometimes returns at splhigh().  The process
811	 * then runs for a little too long at splhigh().  The ipl gets fixed
812	 * when the process returns to user mode (or earlier).
813	 *
814	 * It would probably be better to always call here at spl0(). Callers
815	 * are prepared to give up control to another process, so they must
816	 * be prepared to be interrupted.  The clock stuff here may not
817	 * actually need splstatclock().
818	 */
819	x = splstatclock();
820
821#ifdef SIMPLELOCK_DEBUG
822	if (p->p_simple_locks)
823		printf("sleep: holding simple lock\n");
824#endif
825	/*
826	 * Compute the amount of time during which the current
827	 * process was running, and add that to its total so far.
828	 */
829	microuptime(&new_switchtime);
830	if (timevalcmp(&new_switchtime, &switchtime, <)) {
831		printf("microuptime() went backwards (%ld.%06ld -> %ld,%06ld)\n",
832		    switchtime.tv_sec, switchtime.tv_usec,
833		    new_switchtime.tv_sec, new_switchtime.tv_usec);
834		new_switchtime = switchtime;
835	} else {
836		p->p_runtime += (new_switchtime.tv_usec - switchtime.tv_usec) +
837		    (new_switchtime.tv_sec - switchtime.tv_sec) * (int64_t)1000000;
838	}
839
840	/*
841	 * Check if the process exceeds its cpu resource allocation.
842	 * If over max, kill it.
843	 */
844	if (p->p_stat != SZOMB && p->p_limit->p_cpulimit != RLIM_INFINITY &&
845	    p->p_runtime > p->p_limit->p_cpulimit) {
846		rlim = &p->p_rlimit[RLIMIT_CPU];
847		if (p->p_runtime / (rlim_t)1000000 >= rlim->rlim_max) {
848			killproc(p, "exceeded maximum CPU limit");
849		} else {
850			psignal(p, SIGXCPU);
851			if (rlim->rlim_cur < rlim->rlim_max) {
852				/* XXX: we should make a private copy */
853				rlim->rlim_cur += 5;
854			}
855		}
856	}
857
858	/*
859	 * Pick a new current process and record its start time.
860	 */
861	cnt.v_swtch++;
862	switchtime = new_switchtime;
863	cpu_switch(p);
864	if (switchtime.tv_sec == 0)
865		microuptime(&switchtime);
866	switchticks = ticks;
867
868	splx(x);
869}
870
871/*
872 * Change process state to be runnable,
873 * placing it on the run queue if it is in memory,
874 * and awakening the swapper if it isn't in memory.
875 */
876void
877setrunnable(p)
878	register struct proc *p;
879{
880	register int s;
881
882	s = splhigh();
883	switch (p->p_stat) {
884	case 0:
885	case SRUN:
886	case SZOMB:
887	default:
888		panic("setrunnable");
889	case SSTOP:
890	case SSLEEP:
891		unsleep(p);		/* e.g. when sending signals */
892		break;
893
894	case SIDL:
895		break;
896	}
897	p->p_stat = SRUN;
898	if (p->p_flag & P_INMEM)
899		setrunqueue(p);
900	splx(s);
901	if (p->p_slptime > 1)
902		updatepri(p);
903	p->p_slptime = 0;
904	if ((p->p_flag & P_INMEM) == 0) {
905		p->p_flag |= P_SWAPINREQ;
906		wakeup((caddr_t)&proc0);
907	}
908	else
909		maybe_resched(p);
910}
911
912/*
913 * Compute the priority of a process when running in user mode.
914 * Arrange to reschedule if the resulting priority is better
915 * than that of the current process.
916 */
917void
918resetpriority(p)
919	register struct proc *p;
920{
921	register unsigned int newpriority;
922
923	if (p->p_rtprio.type == RTP_PRIO_NORMAL) {
924		newpriority = PUSER + p->p_estcpu / INVERSE_ESTCPU_WEIGHT +
925		    NICE_WEIGHT * p->p_nice;
926		newpriority = min(newpriority, MAXPRI);
927		p->p_usrpri = newpriority;
928	}
929	maybe_resched(p);
930}
931
932/* ARGSUSED */
933static void
934sched_setup(dummy)
935	void *dummy;
936{
937	/* Kick off timeout driven events by calling first time. */
938	roundrobin(NULL);
939	schedcpu(NULL);
940}
941
942/*
943 * We adjust the priority of the current process.  The priority of
944 * a process gets worse as it accumulates CPU time.  The cpu usage
945 * estimator (p_estcpu) is increased here.  resetpriority() will
946 * compute a different priority each time p_estcpu increases by
947 * INVERSE_ESTCPU_WEIGHT
948 * (until MAXPRI is reached).  The cpu usage estimator ramps up
949 * quite quickly when the process is running (linearly), and decays
950 * away exponentially, at a rate which is proportionally slower when
951 * the system is busy.  The basic principle is that the system will
952 * 90% forget that the process used a lot of CPU time in 5 * loadav
953 * seconds.  This causes the system to favor processes which haven't
954 * run much recently, and to round-robin among other processes.
955 */
956void
957schedclock(p)
958	struct proc *p;
959{
960
961	p->p_cpticks++;
962	p->p_estcpu = ESTCPULIM(p->p_estcpu + 1);
963	if ((p->p_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
964		resetpriority(p);
965		if (p->p_priority >= PUSER)
966			p->p_priority = p->p_usrpri;
967	}
968}
969