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