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