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