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