kern_synch.c revision 69360
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 69360 2000-11-29 18:32:50Z 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	p->p_nativepri = p->p_priority;
468	CTR4(KTR_PROC, "msleep: proc %p (pid %d, %s), schedlock %p",
469		p, p->p_pid, p->p_comm, (void *) sched_lock.mtx_lock);
470	TAILQ_INSERT_TAIL(&slpque[LOOKUP(ident)], p, p_slpq);
471	if (timo)
472		callout_reset(&p->p_slpcallout, timo, endtsleep, p);
473	/*
474	 * We put ourselves on the sleep queue and start our timeout
475	 * before calling CURSIG, as we could stop there, and a wakeup
476	 * or a SIGCONT (or both) could occur while we were stopped.
477	 * A SIGCONT would cause us to be marked as SSLEEP
478	 * without resuming us, thus we must be ready for sleep
479	 * when CURSIG is called.  If the wakeup happens while we're
480	 * stopped, p->p_wchan will be 0 upon return from CURSIG.
481	 */
482	if (catch) {
483		CTR4(KTR_PROC,
484		        "msleep caught: proc %p (pid %d, %s), schedlock %p",
485			p, p->p_pid, p->p_comm, (void *) sched_lock.mtx_lock);
486		p->p_flag |= P_SINTR;
487		mtx_exit(&sched_lock, MTX_SPIN);
488		if ((sig = CURSIG(p))) {
489			mtx_enter(&sched_lock, MTX_SPIN);
490			if (p->p_wchan)
491				unsleep(p);
492			p->p_stat = SRUN;
493			goto resume;
494		}
495		mtx_enter(&sched_lock, MTX_SPIN);
496		if (p->p_wchan == 0) {
497			catch = 0;
498			goto resume;
499		}
500	} else
501		sig = 0;
502	p->p_stat = SSLEEP;
503	p->p_stats->p_ru.ru_nvcsw++;
504	mi_switch();
505	CTR4(KTR_PROC,
506	        "msleep resume: proc %p (pid %d, %s), schedlock %p",
507		p, p->p_pid, p->p_comm, (void *) sched_lock.mtx_lock);
508resume:
509	curpriority = p->p_usrpri;
510	splx(s);
511	p->p_flag &= ~P_SINTR;
512	if (p->p_flag & P_TIMEOUT) {
513		p->p_flag &= ~P_TIMEOUT;
514		if (sig == 0) {
515#ifdef KTRACE
516			if (KTRPOINT(p, KTR_CSW))
517				ktrcsw(p->p_tracep, 0, 0);
518#endif
519			rval = EWOULDBLOCK;
520			mtx_exit(&sched_lock, MTX_SPIN);
521			goto out;
522		}
523	} else if (timo)
524		callout_stop(&p->p_slpcallout);
525	mtx_exit(&sched_lock, MTX_SPIN);
526
527	if (catch && (sig != 0 || (sig = CURSIG(p)))) {
528#ifdef KTRACE
529		if (KTRPOINT(p, KTR_CSW))
530			ktrcsw(p->p_tracep, 0, 0);
531#endif
532		if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
533			rval = EINTR;
534		else
535			rval = ERESTART;
536		goto out;
537	}
538out:
539#ifdef KTRACE
540	if (KTRPOINT(p, KTR_CSW))
541		ktrcsw(p->p_tracep, 0, 0);
542#endif
543	PICKUP_GIANT();
544	if (mtx != NULL) {
545		mtx_enter(mtx, MTX_DEF);
546		WITNESS_RESTORE(mtx, mtx);
547	}
548	return (rval);
549}
550
551/*
552 * asleep() - async sleep call.  Place process on wait queue and return
553 * immediately without blocking.  The process stays runnable until mawait()
554 * is called.  If ident is NULL, remove process from wait queue if it is still
555 * on one.
556 *
557 * Only the most recent sleep condition is effective when making successive
558 * calls to asleep() or when calling msleep().
559 *
560 * The timeout, if any, is not initiated until mawait() is called.  The sleep
561 * priority, signal, and timeout is specified in the asleep() call but may be
562 * overriden in the mawait() call.
563 *
564 * <<<<<<<< EXPERIMENTAL, UNTESTED >>>>>>>>>>
565 */
566
567int
568asleep(void *ident, int priority, const char *wmesg, int timo)
569{
570	struct proc *p = curproc;
571	int s;
572
573	/*
574	 * obtain sched_lock while manipulating sleep structures and slpque.
575	 *
576	 * Remove preexisting wait condition (if any) and place process
577	 * on appropriate slpque, but do not put process to sleep.
578	 */
579
580	s = splhigh();
581	mtx_enter(&sched_lock, MTX_SPIN);
582
583	if (p->p_wchan != NULL)
584		unsleep(p);
585
586	if (ident) {
587		p->p_wchan = ident;
588		p->p_wmesg = wmesg;
589		p->p_slptime = 0;
590		p->p_asleep.as_priority = priority;
591		p->p_asleep.as_timo = timo;
592		TAILQ_INSERT_TAIL(&slpque[LOOKUP(ident)], p, p_slpq);
593	}
594
595	mtx_exit(&sched_lock, MTX_SPIN);
596	splx(s);
597
598	return(0);
599}
600
601/*
602 * mawait() - wait for async condition to occur.   The process blocks until
603 * wakeup() is called on the most recent asleep() address.  If wakeup is called
604 * prior to mawait(), mawait() winds up being a NOP.
605 *
606 * If mawait() is called more then once (without an intervening asleep() call),
607 * mawait() is still effectively a NOP but it calls mi_switch() to give other
608 * processes some cpu before returning.  The process is left runnable.
609 *
610 * <<<<<<<< EXPERIMENTAL, UNTESTED >>>>>>>>>>
611 */
612
613int
614mawait(struct mtx *mtx, int priority, int timo)
615{
616	struct proc *p = curproc;
617	int rval = 0;
618	int s;
619	WITNESS_SAVE_DECL(mtx);
620
621	WITNESS_SLEEP(0, mtx);
622	mtx_enter(&sched_lock, MTX_SPIN);
623	DROP_GIANT_NOSWITCH();
624	if (mtx != NULL) {
625		mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED);
626		WITNESS_SAVE(mtx, mtx);
627		mtx_exit(mtx, MTX_DEF | MTX_NOSWITCH);
628		if (priority & PDROP)
629			mtx = NULL;
630	}
631
632	s = splhigh();
633
634	if (p->p_wchan != NULL) {
635		int sig;
636		int catch;
637
638		/*
639		 * The call to mawait() can override defaults specified in
640		 * the original asleep().
641		 */
642		if (priority < 0)
643			priority = p->p_asleep.as_priority;
644		if (timo < 0)
645			timo = p->p_asleep.as_timo;
646
647		/*
648		 * Install timeout
649		 */
650
651		if (timo)
652			callout_reset(&p->p_slpcallout, timo, endtsleep, p);
653
654		sig = 0;
655		catch = priority & PCATCH;
656
657		if (catch) {
658			p->p_flag |= P_SINTR;
659			mtx_exit(&sched_lock, MTX_SPIN);
660			if ((sig = CURSIG(p))) {
661				mtx_enter(&sched_lock, MTX_SPIN);
662				if (p->p_wchan)
663					unsleep(p);
664				p->p_stat = SRUN;
665				goto resume;
666			}
667			mtx_enter(&sched_lock, MTX_SPIN);
668			if (p->p_wchan == NULL) {
669				catch = 0;
670				goto resume;
671			}
672		}
673		p->p_stat = SSLEEP;
674		p->p_stats->p_ru.ru_nvcsw++;
675		mi_switch();
676resume:
677		curpriority = p->p_usrpri;
678
679		splx(s);
680		p->p_flag &= ~P_SINTR;
681		if (p->p_flag & P_TIMEOUT) {
682			p->p_flag &= ~P_TIMEOUT;
683			if (sig == 0) {
684#ifdef KTRACE
685				if (KTRPOINT(p, KTR_CSW))
686					ktrcsw(p->p_tracep, 0, 0);
687#endif
688				rval = EWOULDBLOCK;
689				mtx_exit(&sched_lock, MTX_SPIN);
690				goto out;
691			}
692		} else if (timo)
693			callout_stop(&p->p_slpcallout);
694		mtx_exit(&sched_lock, MTX_SPIN);
695
696		if (catch && (sig != 0 || (sig = CURSIG(p)))) {
697#ifdef KTRACE
698			if (KTRPOINT(p, KTR_CSW))
699				ktrcsw(p->p_tracep, 0, 0);
700#endif
701			if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
702				rval = EINTR;
703			else
704				rval = ERESTART;
705			goto out;
706		}
707#ifdef KTRACE
708		if (KTRPOINT(p, KTR_CSW))
709			ktrcsw(p->p_tracep, 0, 0);
710#endif
711	} else {
712		/*
713		 * If as_priority is 0, mawait() has been called without an
714		 * intervening asleep().  We are still effectively a NOP,
715		 * but we call mi_switch() for safety.
716		 */
717
718		if (p->p_asleep.as_priority == 0) {
719			p->p_stats->p_ru.ru_nvcsw++;
720			mi_switch();
721		}
722		mtx_exit(&sched_lock, MTX_SPIN);
723		splx(s);
724	}
725
726	/*
727	 * clear p_asleep.as_priority as an indication that mawait() has been
728	 * called.  If mawait() is called again without an intervening asleep(),
729	 * mawait() is still effectively a NOP but the above mi_switch() code
730	 * is triggered as a safety.
731	 */
732	p->p_asleep.as_priority = 0;
733
734out:
735	PICKUP_GIANT();
736	if (mtx != NULL) {
737		mtx_enter(mtx, MTX_DEF);
738		WITNESS_RESTORE(mtx, mtx);
739	}
740	return (rval);
741}
742
743/*
744 * Implement timeout for msleep or asleep()/mawait()
745 *
746 * If process hasn't been awakened (wchan non-zero),
747 * set timeout flag and undo the sleep.  If proc
748 * is stopped, just unsleep so it will remain stopped.
749 */
750static void
751endtsleep(arg)
752	void *arg;
753{
754	register struct proc *p;
755	int s;
756
757	p = (struct proc *)arg;
758	CTR4(KTR_PROC,
759	        "endtsleep: proc %p (pid %d, %s), schedlock %p",
760		p, p->p_pid, p->p_comm, (void *) sched_lock.mtx_lock);
761	s = splhigh();
762	mtx_enter(&sched_lock, MTX_SPIN);
763	if (p->p_wchan) {
764		if (p->p_stat == SSLEEP)
765			setrunnable(p);
766		else
767			unsleep(p);
768		p->p_flag |= P_TIMEOUT;
769	}
770	mtx_exit(&sched_lock, MTX_SPIN);
771	splx(s);
772}
773
774/*
775 * Remove a process from its wait queue
776 */
777void
778unsleep(p)
779	register struct proc *p;
780{
781	int s;
782
783	s = splhigh();
784	mtx_enter(&sched_lock, MTX_SPIN);
785	if (p->p_wchan) {
786		TAILQ_REMOVE(&slpque[LOOKUP(p->p_wchan)], p, p_slpq);
787		p->p_wchan = 0;
788	}
789	mtx_exit(&sched_lock, MTX_SPIN);
790	splx(s);
791}
792
793/*
794 * Make all processes sleeping on the specified identifier runnable.
795 */
796void
797wakeup(ident)
798	register void *ident;
799{
800	register struct slpquehead *qp;
801	register struct proc *p;
802	int s;
803
804	s = splhigh();
805	mtx_enter(&sched_lock, MTX_SPIN);
806	qp = &slpque[LOOKUP(ident)];
807restart:
808	TAILQ_FOREACH(p, qp, p_slpq) {
809		if (p->p_wchan == ident) {
810			TAILQ_REMOVE(qp, p, p_slpq);
811			p->p_wchan = 0;
812			if (p->p_stat == SSLEEP) {
813				/* OPTIMIZED EXPANSION OF setrunnable(p); */
814				CTR4(KTR_PROC,
815				        "wakeup: proc %p (pid %d, %s), schedlock %p",
816					p, p->p_pid, p->p_comm, (void *) sched_lock.mtx_lock);
817				if (p->p_slptime > 1)
818					updatepri(p);
819				p->p_slptime = 0;
820				p->p_stat = SRUN;
821				if (p->p_flag & P_INMEM) {
822					setrunqueue(p);
823					maybe_resched(p);
824				} else {
825					p->p_flag |= P_SWAPINREQ;
826					wakeup((caddr_t)&proc0);
827				}
828				/* END INLINE EXPANSION */
829				goto restart;
830			}
831		}
832	}
833	mtx_exit(&sched_lock, MTX_SPIN);
834	splx(s);
835}
836
837/*
838 * Make a process sleeping on the specified identifier runnable.
839 * May wake more than one process if a target process is currently
840 * swapped out.
841 */
842void
843wakeup_one(ident)
844	register void *ident;
845{
846	register struct slpquehead *qp;
847	register struct proc *p;
848	int s;
849
850	s = splhigh();
851	mtx_enter(&sched_lock, MTX_SPIN);
852	qp = &slpque[LOOKUP(ident)];
853
854	TAILQ_FOREACH(p, qp, p_slpq) {
855		if (p->p_wchan == ident) {
856			TAILQ_REMOVE(qp, p, p_slpq);
857			p->p_wchan = 0;
858			if (p->p_stat == SSLEEP) {
859				/* OPTIMIZED EXPANSION OF setrunnable(p); */
860				CTR4(KTR_PROC,
861				        "wakeup1: proc %p (pid %d, %s), schedlock %p",
862					p, p->p_pid, p->p_comm, (void *) sched_lock.mtx_lock);
863				if (p->p_slptime > 1)
864					updatepri(p);
865				p->p_slptime = 0;
866				p->p_stat = SRUN;
867				if (p->p_flag & P_INMEM) {
868					setrunqueue(p);
869					maybe_resched(p);
870					break;
871				} else {
872					p->p_flag |= P_SWAPINREQ;
873					wakeup((caddr_t)&proc0);
874				}
875				/* END INLINE EXPANSION */
876			}
877		}
878	}
879	mtx_exit(&sched_lock, MTX_SPIN);
880	splx(s);
881}
882
883/*
884 * The machine independent parts of mi_switch().
885 * Must be called at splstatclock() or higher.
886 */
887void
888mi_switch()
889{
890	struct timeval new_switchtime;
891	register struct proc *p = curproc;	/* XXX */
892	register struct rlimit *rlim;
893	int x;
894
895	/*
896	 * XXX this spl is almost unnecessary.  It is partly to allow for
897	 * sloppy callers that don't do it (issignal() via CURSIG() is the
898	 * main offender).  It is partly to work around a bug in the i386
899	 * cpu_switch() (the ipl is not preserved).  We ran for years
900	 * without it.  I think there was only a interrupt latency problem.
901	 * The main caller, msleep(), does an splx() a couple of instructions
902	 * after calling here.  The buggy caller, issignal(), usually calls
903	 * here at spl0() and sometimes returns at splhigh().  The process
904	 * then runs for a little too long at splhigh().  The ipl gets fixed
905	 * when the process returns to user mode (or earlier).
906	 *
907	 * It would probably be better to always call here at spl0(). Callers
908	 * are prepared to give up control to another process, so they must
909	 * be prepared to be interrupted.  The clock stuff here may not
910	 * actually need splstatclock().
911	 */
912	x = splstatclock();
913
914	mtx_assert(&sched_lock, MA_OWNED);
915
916#ifdef SIMPLELOCK_DEBUG
917	if (p->p_simple_locks)
918		printf("sleep: holding simple lock\n");
919#endif
920	/*
921	 * Compute the amount of time during which the current
922	 * process was running, and add that to its total so far.
923	 */
924	microuptime(&new_switchtime);
925	if (timevalcmp(&new_switchtime, &switchtime, <)) {
926		printf("microuptime() went backwards (%ld.%06ld -> %ld.%06ld)\n",
927		    switchtime.tv_sec, switchtime.tv_usec,
928		    new_switchtime.tv_sec, new_switchtime.tv_usec);
929		new_switchtime = switchtime;
930	} else {
931		p->p_runtime += (new_switchtime.tv_usec - switchtime.tv_usec) +
932		    (new_switchtime.tv_sec - switchtime.tv_sec) * (int64_t)1000000;
933	}
934
935	/*
936	 * Check if the process exceeds its cpu resource allocation.
937	 * If over max, kill it.
938	 *
939	 * XXX drop sched_lock, pickup Giant
940	 */
941	if (p->p_stat != SZOMB && p->p_limit->p_cpulimit != RLIM_INFINITY &&
942	    p->p_runtime > p->p_limit->p_cpulimit) {
943		rlim = &p->p_rlimit[RLIMIT_CPU];
944		if (p->p_runtime / (rlim_t)1000000 >= rlim->rlim_max) {
945			killproc(p, "exceeded maximum CPU limit");
946		} else {
947			psignal(p, SIGXCPU);
948			if (rlim->rlim_cur < rlim->rlim_max) {
949				/* XXX: we should make a private copy */
950				rlim->rlim_cur += 5;
951			}
952		}
953	}
954
955	/*
956	 * Pick a new current process and record its start time.
957	 */
958	cnt.v_swtch++;
959	switchtime = new_switchtime;
960	CTR4(KTR_PROC, "mi_switch: old proc %p (pid %d, %s), schedlock %p",
961		p, p->p_pid, p->p_comm, (void *) sched_lock.mtx_lock);
962	cpu_switch();
963	CTR4(KTR_PROC, "mi_switch: new proc %p (pid %d, %s), schedlock %p",
964		p, p->p_pid, p->p_comm, (void *) sched_lock.mtx_lock);
965	if (switchtime.tv_sec == 0)
966		microuptime(&switchtime);
967	switchticks = ticks;
968	splx(x);
969}
970
971/*
972 * Change process state to be runnable,
973 * placing it on the run queue if it is in memory,
974 * and awakening the swapper if it isn't in memory.
975 */
976void
977setrunnable(p)
978	register struct proc *p;
979{
980	register int s;
981
982	s = splhigh();
983	mtx_enter(&sched_lock, MTX_SPIN);
984	switch (p->p_stat) {
985	case 0:
986	case SRUN:
987	case SZOMB:
988	case SWAIT:
989	default:
990		panic("setrunnable");
991	case SSTOP:
992	case SSLEEP:
993		unsleep(p);		/* e.g. when sending signals */
994		break;
995
996	case SIDL:
997		break;
998	}
999	p->p_stat = SRUN;
1000	if (p->p_flag & P_INMEM)
1001		setrunqueue(p);
1002	splx(s);
1003	if (p->p_slptime > 1)
1004		updatepri(p);
1005	p->p_slptime = 0;
1006	if ((p->p_flag & P_INMEM) == 0) {
1007		p->p_flag |= P_SWAPINREQ;
1008		wakeup((caddr_t)&proc0);
1009	}
1010	else
1011		maybe_resched(p);
1012	mtx_exit(&sched_lock, MTX_SPIN);
1013}
1014
1015/*
1016 * Compute the priority of a process when running in user mode.
1017 * Arrange to reschedule if the resulting priority is better
1018 * than that of the current process.
1019 */
1020void
1021resetpriority(p)
1022	register struct proc *p;
1023{
1024	register unsigned int newpriority;
1025
1026	mtx_enter(&sched_lock, MTX_SPIN);
1027	if (p->p_rtprio.type == RTP_PRIO_NORMAL) {
1028		newpriority = PUSER + p->p_estcpu / INVERSE_ESTCPU_WEIGHT +
1029		    NICE_WEIGHT * (p->p_nice - PRIO_MIN);
1030		newpriority = min(newpriority, MAXPRI);
1031		p->p_usrpri = newpriority;
1032	}
1033	maybe_resched(p);
1034	mtx_exit(&sched_lock, MTX_SPIN);
1035}
1036
1037/* ARGSUSED */
1038static void
1039sched_setup(dummy)
1040	void *dummy;
1041{
1042
1043	callout_init(&schedcpu_callout, 1);
1044	callout_init(&roundrobin_callout, 0);
1045
1046	/* Kick off timeout driven events by calling first time. */
1047	roundrobin(NULL);
1048	schedcpu(NULL);
1049}
1050
1051/*
1052 * We adjust the priority of the current process.  The priority of
1053 * a process gets worse as it accumulates CPU time.  The cpu usage
1054 * estimator (p_estcpu) is increased here.  resetpriority() will
1055 * compute a different priority each time p_estcpu increases by
1056 * INVERSE_ESTCPU_WEIGHT
1057 * (until MAXPRI is reached).  The cpu usage estimator ramps up
1058 * quite quickly when the process is running (linearly), and decays
1059 * away exponentially, at a rate which is proportionally slower when
1060 * the system is busy.  The basic principle is that the system will
1061 * 90% forget that the process used a lot of CPU time in 5 * loadav
1062 * seconds.  This causes the system to favor processes which haven't
1063 * run much recently, and to round-robin among other processes.
1064 */
1065void
1066schedclock(p)
1067	struct proc *p;
1068{
1069
1070	p->p_cpticks++;
1071	p->p_estcpu = ESTCPULIM(p->p_estcpu + 1);
1072	if ((p->p_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
1073		resetpriority(p);
1074		if (p->p_priority >= PUSER)
1075			p->p_priority = p->p_usrpri;
1076	}
1077}
1078