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