kern_synch.c revision 85227
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 85227 2001-10-20 13:10:43Z iedowse $
40 */
41
42#include "opt_ddb.h"
43#include "opt_ktrace.h"
44
45#include <sys/param.h>
46#include <sys/systm.h>
47#include <sys/condvar.h>
48#include <sys/kernel.h>
49#include <sys/ktr.h>
50#include <sys/lock.h>
51#include <sys/mutex.h>
52#include <sys/proc.h>
53#include <sys/resourcevar.h>
54#include <sys/signalvar.h>
55#include <sys/smp.h>
56#include <sys/sx.h>
57#include <sys/sysctl.h>
58#include <sys/sysproto.h>
59#include <sys/vmmeter.h>
60#ifdef DDB
61#include <ddb/ddb.h>
62#endif
63#ifdef KTRACE
64#include <sys/uio.h>
65#include <sys/ktrace.h>
66#endif
67
68#include <machine/cpu.h>
69
70static void sched_setup __P((void *dummy));
71SYSINIT(sched_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, sched_setup, NULL)
72
73int	hogticks;
74int	lbolt;
75int	sched_quantum;		/* Roundrobin scheduling quantum in ticks. */
76
77static struct callout schedcpu_callout;
78static struct callout roundrobin_callout;
79
80struct loadavg averunnable =
81	{ {0, 0, 0}, FSCALE };	/* load average, of runnable procs */
82/*
83 * Constants for averages over 1, 5, and 15 minutes
84 * when sampling at 5 second intervals.
85 */
86static fixpt_t cexp[3] = {
87	0.9200444146293232 * FSCALE,	/* exp(-1/12) */
88	0.9834714538216174 * FSCALE,	/* exp(-1/60) */
89	0.9944598480048967 * FSCALE,	/* exp(-1/180) */
90};
91
92static void	endtsleep __P((void *));
93static void	loadav __P((struct loadavg *));
94static void	roundrobin __P((void *arg));
95static void	schedcpu __P((void *arg));
96
97static int
98sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
99{
100	int error, new_val;
101
102	new_val = sched_quantum * tick;
103	error = sysctl_handle_int(oidp, &new_val, 0, req);
104        if (error != 0 || req->newptr == NULL)
105		return (error);
106	if (new_val < tick)
107		return (EINVAL);
108	sched_quantum = new_val / tick;
109	hogticks = 2 * sched_quantum;
110	return (0);
111}
112
113SYSCTL_PROC(_kern, OID_AUTO, quantum, CTLTYPE_INT|CTLFLAG_RW,
114	0, sizeof sched_quantum, sysctl_kern_quantum, "I", "");
115
116/*
117 * Arrange to reschedule if necessary, taking the priorities and
118 * schedulers into account.
119 */
120void
121maybe_resched(kg)
122	struct ksegrp *kg;
123{
124
125	mtx_assert(&sched_lock, MA_OWNED);
126	if (kg->kg_pri.pri_level < curthread->td_ksegrp->kg_pri.pri_level)
127		curthread->td_kse->ke_flags |= KEF_NEEDRESCHED;
128}
129
130int
131roundrobin_interval(void)
132{
133	return (sched_quantum);
134}
135
136/*
137 * Force switch among equal priority processes every 100ms.
138 * We don't actually need to force a context switch of the current process.
139 * The act of firing the event triggers a context switch to softclock() and
140 * then switching back out again which is equivalent to a preemption, thus
141 * no further work is needed on the local CPU.
142 */
143/* ARGSUSED */
144static void
145roundrobin(arg)
146	void *arg;
147{
148
149#ifdef SMP
150	mtx_lock_spin(&sched_lock);
151	forward_roundrobin();
152	mtx_unlock_spin(&sched_lock);
153#endif
154
155	callout_reset(&roundrobin_callout, sched_quantum, roundrobin, NULL);
156}
157
158/*
159 * Constants for digital decay and forget:
160 *	90% of (p_estcpu) usage in 5 * loadav time
161 *	95% of (p_pctcpu) usage in 60 seconds (load insensitive)
162 *          Note that, as ps(1) mentions, this can let percentages
163 *          total over 100% (I've seen 137.9% for 3 processes).
164 *
165 * Note that schedclock() updates p_estcpu and p_cpticks asynchronously.
166 *
167 * We wish to decay away 90% of p_estcpu in (5 * loadavg) seconds.
168 * That is, the system wants to compute a value of decay such
169 * that the following for loop:
170 * 	for (i = 0; i < (5 * loadavg); i++)
171 * 		p_estcpu *= decay;
172 * will compute
173 * 	p_estcpu *= 0.1;
174 * for all values of loadavg:
175 *
176 * Mathematically this loop can be expressed by saying:
177 * 	decay ** (5 * loadavg) ~= .1
178 *
179 * The system computes decay as:
180 * 	decay = (2 * loadavg) / (2 * loadavg + 1)
181 *
182 * We wish to prove that the system's computation of decay
183 * will always fulfill the equation:
184 * 	decay ** (5 * loadavg) ~= .1
185 *
186 * If we compute b as:
187 * 	b = 2 * loadavg
188 * then
189 * 	decay = b / (b + 1)
190 *
191 * We now need to prove two things:
192 *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
193 *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
194 *
195 * Facts:
196 *         For x close to zero, exp(x) =~ 1 + x, since
197 *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
198 *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
199 *         For x close to zero, ln(1+x) =~ x, since
200 *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
201 *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
202 *         ln(.1) =~ -2.30
203 *
204 * Proof of (1):
205 *    Solve (factor)**(power) =~ .1 given power (5*loadav):
206 *	solving for factor,
207 *      ln(factor) =~ (-2.30/5*loadav), or
208 *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
209 *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
210 *
211 * Proof of (2):
212 *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
213 *	solving for power,
214 *      power*ln(b/(b+1)) =~ -2.30, or
215 *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
216 *
217 * Actual power values for the implemented algorithm are as follows:
218 *      loadav: 1       2       3       4
219 *      power:  5.68    10.32   14.94   19.55
220 */
221
222/* calculations for digital decay to forget 90% of usage in 5*loadav sec */
223#define	loadfactor(loadav)	(2 * (loadav))
224#define	decay_cpu(loadfac, cpu)	(((loadfac) * (cpu)) / ((loadfac) + FSCALE))
225
226/* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
227static fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;	/* exp(-1/20) */
228SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
229
230/* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */
231static int	fscale __unused = FSCALE;
232SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, "");
233
234/*
235 * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
236 * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
237 * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
238 *
239 * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
240 *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
241 *
242 * If you don't want to bother with the faster/more-accurate formula, you
243 * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
244 * (more general) method of calculating the %age of CPU used by a process.
245 */
246#define	CCPU_SHIFT	11
247
248/*
249 * Recompute process priorities, every hz ticks.
250 * MP-safe, called without the Giant mutex.
251 */
252/* ARGSUSED */
253static void
254schedcpu(arg)
255	void *arg;
256{
257	register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
258	register struct proc *p;
259	register struct kse *ke;
260	register struct ksegrp *kg;
261	register int realstathz;
262	int awake;
263
264	realstathz = stathz ? stathz : hz;
265	sx_slock(&allproc_lock);
266	FOREACH_PROC_IN_SYSTEM(p) {
267		mtx_lock_spin(&sched_lock);
268		p->p_swtime++;
269		FOREACH_KSEGRP_IN_PROC(p, kg) {
270			awake = 0;
271			FOREACH_KSE_IN_GROUP(kg, ke) {
272				/*
273				 * Increment time in/out of memory and sleep
274				 * time (if sleeping).  We ignore overflow;
275				 * with 16-bit int's (remember them?)
276				 * overflow takes 45 days.
277				 */
278				/* XXXKSE */
279			/*	if ((ke->ke_flags & KEF_ONRUNQ) == 0) */
280				if (p->p_stat == SSLEEP || p->p_stat == SSTOP) {
281					ke->ke_slptime++;
282				} else {
283					ke->ke_slptime = 0;
284					awake = 1;
285				}
286
287				/*
288				 * pctcpu is only for ps?
289				 * Do it per kse.. and add them up at the end?
290				 * XXXKSE
291				 */
292				ke->ke_pctcpu = (ke->ke_pctcpu * ccpu) >> FSHIFT;
293				/*
294				 * If the kse has been idle the entire second,
295				 * stop recalculating its priority until
296				 * it wakes up.
297				 */
298				if (ke->ke_slptime > 1) {
299					continue;
300				}
301
302#if	(FSHIFT >= CCPU_SHIFT)
303				ke->ke_pctcpu += (realstathz == 100) ?
304				    ((fixpt_t) ke->ke_cpticks) <<
305				    (FSHIFT - CCPU_SHIFT) :
306				    100 * (((fixpt_t) ke->ke_cpticks) <<
307				    (FSHIFT - CCPU_SHIFT)) / realstathz;
308#else
309				ke->ke_pctcpu += ((FSCALE - ccpu) *
310				    (ke->ke_cpticks * FSCALE / realstathz)) >>
311				    FSHIFT;
312#endif
313				ke->ke_cpticks = 0;
314			} /* end of kse loop */
315			if (awake == 0) {
316				kg->kg_slptime++;
317			} else {
318				kg->kg_slptime = 0;
319			}
320			kg->kg_estcpu = decay_cpu(loadfac, kg->kg_estcpu);
321		      	resetpriority(kg);
322		      	if (kg->kg_pri.pri_level >= PUSER &&
323			    (p->p_sflag & PS_INMEM)) {
324				int changedqueue =
325				    ((kg->kg_pri.pri_level / RQ_PPQ) !=
326				     (kg->kg_pri.pri_user / RQ_PPQ));
327
328				kg->kg_pri.pri_level = kg->kg_pri.pri_user;
329				FOREACH_KSE_IN_GROUP(kg, ke) {
330					if ((ke->ke_oncpu == NOCPU) && 	/* idle */
331					    (p->p_stat == SRUN) && /* XXXKSE */
332					    changedqueue) {
333						remrunqueue(ke->ke_thread);
334						setrunqueue(ke->ke_thread);
335					}
336				}
337			}
338		} /* end of ksegrp loop */
339		mtx_unlock_spin(&sched_lock);
340	} /* end of process loop */
341	sx_sunlock(&allproc_lock);
342	if (time_second % 5 == 0)
343		loadav(&averunnable);
344	wakeup((caddr_t)&lbolt);
345	callout_reset(&schedcpu_callout, hz, schedcpu, NULL);
346}
347
348/*
349 * Recalculate the priority of a process after it has slept for a while.
350 * For all load averages >= 1 and max p_estcpu of 255, sleeping for at
351 * least six times the loadfactor will decay p_estcpu to zero.
352 */
353void
354updatepri(td)
355	register struct thread *td;
356{
357	register struct ksegrp *kg;
358	register unsigned int newcpu;
359	register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
360
361	if (td == NULL)
362		return;
363	kg = td->td_ksegrp;
364	newcpu = kg->kg_estcpu;
365	if (kg->kg_slptime > 5 * loadfac)
366		kg->kg_estcpu = 0;
367	else {
368		kg->kg_slptime--;	/* the first time was done in schedcpu */
369		while (newcpu && --kg->kg_slptime)
370			newcpu = decay_cpu(loadfac, newcpu);
371		kg->kg_estcpu = newcpu;
372	}
373	resetpriority(td->td_ksegrp);
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, thread) 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	struct thread *td = curthread;
420	int sig, catch = priority & PCATCH;
421	int rval = 0;
422	WITNESS_SAVE_DECL(mtx);
423
424#ifdef KTRACE
425	if (p && KTRPOINT(p, KTR_CSW))
426		ktrcsw(p->p_tracep, 1, 0);
427#endif
428	WITNESS_SLEEP(0, &mtx->mtx_object);
429	KASSERT(timo != 0 || mtx_owned(&Giant) || mtx != NULL,
430	    ("sleeping without a mutex"));
431	mtx_lock_spin(&sched_lock);
432	if (cold || panicstr) {
433		/*
434		 * After a panic, or during autoconfiguration,
435		 * just give interrupts a chance, then just return;
436		 * don't run any other procs or panic below,
437		 * in case this is the idle process and already asleep.
438		 */
439		if (mtx != NULL && priority & PDROP)
440			mtx_unlock_flags(mtx, MTX_NOSWITCH);
441		mtx_unlock_spin(&sched_lock);
442		return (0);
443	}
444
445	DROP_GIANT_NOSWITCH();
446
447	if (mtx != NULL) {
448		mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED);
449		WITNESS_SAVE(&mtx->mtx_object, mtx);
450		mtx_unlock_flags(mtx, MTX_NOSWITCH);
451		if (priority & PDROP)
452			mtx = NULL;
453	}
454
455	KASSERT(p != NULL, ("msleep1"));
456	KASSERT(ident != NULL && td->td_proc->p_stat == SRUN, ("msleep"));
457
458	td->td_wchan = ident;
459	td->td_wmesg = wmesg;
460	td->td_kse->ke_slptime = 0;	/* XXXKSE */
461	td->td_ksegrp->kg_slptime = 0;
462	td->td_ksegrp->kg_pri.pri_level = priority & PRIMASK;
463	CTR5(KTR_PROC, "msleep: thread %p (pid %d, %s) on %s (%p)",
464	    td, p->p_pid, p->p_comm, wmesg, ident);
465	TAILQ_INSERT_TAIL(&slpque[LOOKUP(ident)], td, td_slpq);
466	if (timo)
467		callout_reset(&td->td_slpcallout, timo, endtsleep, td);
468	/*
469	 * We put ourselves on the sleep queue and start our timeout
470	 * before calling CURSIG, as we could stop there, and a wakeup
471	 * or a SIGCONT (or both) could occur while we were stopped.
472	 * A SIGCONT would cause us to be marked as SSLEEP
473	 * without resuming us, thus we must be ready for sleep
474	 * when CURSIG is called.  If the wakeup happens while we're
475	 * stopped, td->td_wchan will be 0 upon return from CURSIG.
476	 */
477	if (catch) {
478		CTR3(KTR_PROC, "msleep caught: proc %p (pid %d, %s)", p,
479		    p->p_pid, p->p_comm);
480		td->td_flags |= TDF_SINTR;
481		mtx_unlock_spin(&sched_lock);
482		PROC_LOCK(p);
483		sig = CURSIG(p);
484		mtx_lock_spin(&sched_lock);
485		PROC_UNLOCK_NOSWITCH(p);
486		if (sig != 0) {
487			if (td->td_wchan != NULL)
488				unsleep(td);
489		} else if (td->td_wchan == NULL)
490			catch = 0;
491	} else
492		sig = 0;
493	if (td->td_wchan != NULL) {
494		td->td_proc->p_stat = SSLEEP;
495		p->p_stats->p_ru.ru_nvcsw++;
496		mi_switch();
497	}
498	CTR3(KTR_PROC, "msleep resume: proc %p (pid %d, %s)", td, p->p_pid,
499	    p->p_comm);
500	KASSERT(td->td_proc->p_stat == SRUN, ("running but not SRUN"));
501	td->td_flags &= ~TDF_SINTR;
502	if (td->td_flags & TDF_TIMEOUT) {
503		td->td_flags &= ~TDF_TIMEOUT;
504		if (sig == 0)
505			rval = EWOULDBLOCK;
506	} else if (td->td_flags & TDF_TIMOFAIL)
507		td->td_flags &= ~TDF_TIMOFAIL;
508	else if (timo && callout_stop(&td->td_slpcallout) == 0) {
509		/*
510		 * This isn't supposed to be pretty.  If we are here, then
511		 * the endtsleep() callout is currently executing on another
512		 * CPU and is either spinning on the sched_lock or will be
513		 * soon.  If we don't synchronize here, there is a chance
514		 * that this process may msleep() again before the callout
515		 * has a chance to run and the callout may end up waking up
516		 * the wrong msleep().  Yuck.
517		 */
518		td->td_flags |= TDF_TIMEOUT;
519		p->p_stats->p_ru.ru_nivcsw++;
520		mi_switch();
521	}
522	mtx_unlock_spin(&sched_lock);
523
524	if (rval == 0 && catch) {
525		PROC_LOCK(p);
526		/* XXX: shouldn't we always be calling CURSIG() */
527		if (sig != 0 || (sig = CURSIG(p))) {
528			if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
529				rval = EINTR;
530			else
531				rval = ERESTART;
532		}
533		PROC_UNLOCK(p);
534	}
535	PICKUP_GIANT();
536#ifdef KTRACE
537	mtx_lock(&Giant);
538	if (KTRPOINT(p, KTR_CSW))
539		ktrcsw(p->p_tracep, 0, 0);
540	mtx_unlock(&Giant);
541#endif
542	if (mtx != NULL) {
543		mtx_lock(mtx);
544		WITNESS_RESTORE(&mtx->mtx_object, mtx);
545	}
546	return (rval);
547}
548
549/*
550 * Implement timeout for msleep()
551 *
552 * If process hasn't been awakened (wchan non-zero),
553 * set timeout flag and undo the sleep.  If proc
554 * is stopped, just unsleep so it will remain stopped.
555 * MP-safe, called without the Giant mutex.
556 */
557static void
558endtsleep(arg)
559	void *arg;
560{
561	register struct thread *td = arg;
562
563	CTR3(KTR_PROC, "endtsleep: thread %p (pid %d, %s)", td, td->td_proc->p_pid,
564	    td->td_proc->p_comm);
565	mtx_lock_spin(&sched_lock);
566	/*
567	 * This is the other half of the synchronization with msleep()
568	 * described above.  If the PS_TIMEOUT flag is set, we lost the
569	 * race and just need to put the process back on the runqueue.
570	 */
571	if ((td->td_flags & TDF_TIMEOUT) != 0) {
572		td->td_flags &= ~TDF_TIMEOUT;
573		setrunqueue(td);
574	} else if (td->td_wchan != NULL) {
575		if (td->td_proc->p_stat == SSLEEP)  /* XXXKSE */
576			setrunnable(td);
577		else
578			unsleep(td);
579		td->td_flags |= TDF_TIMEOUT;
580	} else {
581		td->td_flags |= TDF_TIMOFAIL;
582	}
583	mtx_unlock_spin(&sched_lock);
584}
585
586/*
587 * Remove a process from its wait queue
588 */
589void
590unsleep(struct thread *td)
591{
592
593	mtx_lock_spin(&sched_lock);
594	if (td->td_wchan != NULL) {
595		TAILQ_REMOVE(&slpque[LOOKUP(td->td_wchan)], td, td_slpq);
596		td->td_wchan = NULL;
597	}
598	mtx_unlock_spin(&sched_lock);
599}
600
601/*
602 * Make all processes sleeping on the specified identifier runnable.
603 */
604void
605wakeup(ident)
606	register void *ident;
607{
608	register struct slpquehead *qp;
609	register struct thread *td;
610	struct proc *p;
611
612	mtx_lock_spin(&sched_lock);
613	qp = &slpque[LOOKUP(ident)];
614restart:
615	TAILQ_FOREACH(td, qp, td_slpq) {
616		p = td->td_proc;
617		if (td->td_wchan == ident) {
618			TAILQ_REMOVE(qp, td, td_slpq);
619			td->td_wchan = NULL;
620			if (td->td_proc->p_stat == SSLEEP) {
621				/* OPTIMIZED EXPANSION OF setrunnable(p); */
622				CTR3(KTR_PROC, "wakeup: thread %p (pid %d, %s)",
623				    td, p->p_pid, p->p_comm);
624				if (td->td_ksegrp->kg_slptime > 1)
625					updatepri(td);
626				td->td_ksegrp->kg_slptime = 0;
627				td->td_kse->ke_slptime = 0;
628				td->td_proc->p_stat = SRUN;
629				if (p->p_sflag & PS_INMEM) {
630					setrunqueue(td);
631					maybe_resched(td->td_ksegrp);
632				} else {
633					p->p_sflag |= PS_SWAPINREQ;
634					wakeup((caddr_t)&proc0);
635				}
636				/* END INLINE EXPANSION */
637				goto restart;
638			}
639		}
640	}
641	mtx_unlock_spin(&sched_lock);
642}
643
644/*
645 * Make a process sleeping on the specified identifier runnable.
646 * May wake more than one process if a target process is currently
647 * swapped out.
648 */
649void
650wakeup_one(ident)
651	register void *ident;
652{
653	register struct slpquehead *qp;
654	register struct thread *td;
655	register struct proc *p;
656
657	mtx_lock_spin(&sched_lock);
658	qp = &slpque[LOOKUP(ident)];
659
660	TAILQ_FOREACH(td, qp, td_slpq) {
661		p = td->td_proc;
662		if (td->td_wchan == ident) {
663			TAILQ_REMOVE(qp, td, td_slpq);
664			td->td_wchan = NULL;
665			if (td->td_proc->p_stat == SSLEEP) {
666				/* OPTIMIZED EXPANSION OF setrunnable(p); */
667				CTR3(KTR_PROC, "wakeup1: proc %p (pid %d, %s)",
668				    p, p->p_pid, p->p_comm);
669				if (td->td_ksegrp->kg_slptime > 1)
670					updatepri(td);
671				td->td_ksegrp->kg_slptime = 0;
672				td->td_kse->ke_slptime = 0;
673				td->td_proc->p_stat = SRUN;
674				if (p->p_sflag & PS_INMEM) {
675					setrunqueue(td);
676					maybe_resched(td->td_ksegrp);
677					break;
678				} else {
679					p->p_sflag |= PS_SWAPINREQ;
680					wakeup((caddr_t)&proc0);
681				}
682				/* END INLINE EXPANSION */
683			}
684		}
685	}
686	mtx_unlock_spin(&sched_lock);
687}
688
689/*
690 * The machine independent parts of mi_switch().
691 */
692void
693mi_switch()
694{
695	struct timeval new_switchtime;
696	struct thread *td = curthread;	/* XXX */
697	register struct proc *p = td->td_proc;	/* XXX */
698#if 0
699	register struct rlimit *rlim;
700#endif
701	critical_t sched_crit;
702	u_int sched_nest;
703
704	mtx_assert(&sched_lock, MA_OWNED | MA_NOTRECURSED);
705
706	/*
707	 * Compute the amount of time during which the current
708	 * process was running, and add that to its total so far.
709	 */
710	microuptime(&new_switchtime);
711	if (timevalcmp(&new_switchtime, PCPU_PTR(switchtime), <)) {
712#if 0
713		/* XXX: This doesn't play well with sched_lock right now. */
714		printf("microuptime() went backwards (%ld.%06ld -> %ld.%06ld)\n",
715		    PCPU_GET(switchtime.tv_sec), PCPU_GET(switchtime.tv_usec),
716		    new_switchtime.tv_sec, new_switchtime.tv_usec);
717#endif
718		new_switchtime = PCPU_GET(switchtime);
719	} else {
720		p->p_runtime += (new_switchtime.tv_usec - PCPU_GET(switchtime.tv_usec)) +
721		    (new_switchtime.tv_sec - PCPU_GET(switchtime.tv_sec)) *
722		    (int64_t)1000000;
723	}
724
725#ifdef DDB
726	/*
727	 * Don't perform context switches from the debugger.
728	 */
729	if (db_active) {
730		mtx_unlock_spin(&sched_lock);
731		db_error("Context switches not allowed in the debugger.");
732	}
733#endif
734
735#if 0
736	/*
737	 * Check if the process exceeds its cpu resource allocation.
738	 * If over max, kill it.
739	 *
740	 * XXX drop sched_lock, pickup Giant
741	 */
742	if (p->p_stat != SZOMB && p->p_limit->p_cpulimit != RLIM_INFINITY &&
743	    p->p_runtime > p->p_limit->p_cpulimit) {
744		rlim = &p->p_rlimit[RLIMIT_CPU];
745		if (p->p_runtime / (rlim_t)1000000 >= rlim->rlim_max) {
746			mtx_unlock_spin(&sched_lock);
747			PROC_LOCK(p);
748			killproc(p, "exceeded maximum CPU limit");
749			mtx_lock_spin(&sched_lock);
750			PROC_UNLOCK_NOSWITCH(p);
751		} else {
752			mtx_unlock_spin(&sched_lock);
753			PROC_LOCK(p);
754			psignal(p, SIGXCPU);
755			mtx_lock_spin(&sched_lock);
756			PROC_UNLOCK_NOSWITCH(p);
757			if (rlim->rlim_cur < rlim->rlim_max) {
758				/* XXX: we should make a private copy */
759				rlim->rlim_cur += 5;
760			}
761		}
762	}
763#endif
764
765	/*
766	 * Pick a new current process and record its start time.
767	 */
768	cnt.v_swtch++;
769	PCPU_SET(switchtime, new_switchtime);
770	CTR3(KTR_PROC, "mi_switch: old proc %p (pid %d, %s)", p, p->p_pid,
771	    p->p_comm);
772	sched_crit = sched_lock.mtx_savecrit;
773	sched_nest = sched_lock.mtx_recurse;
774	td->td_lastcpu = td->td_kse->ke_oncpu;
775	td->td_kse->ke_oncpu = NOCPU;
776	td->td_kse->ke_flags &= ~KEF_NEEDRESCHED;
777	cpu_switch();
778	td->td_kse->ke_oncpu = PCPU_GET(cpuid);
779	sched_lock.mtx_savecrit = sched_crit;
780	sched_lock.mtx_recurse = sched_nest;
781	sched_lock.mtx_lock = (uintptr_t)td;
782	CTR3(KTR_PROC, "mi_switch: new proc %p (pid %d, %s)", p, p->p_pid,
783	    p->p_comm);
784	if (PCPU_GET(switchtime.tv_sec) == 0)
785		microuptime(PCPU_PTR(switchtime));
786	PCPU_SET(switchticks, ticks);
787}
788
789/*
790 * Change process state to be runnable,
791 * placing it on the run queue if it is in memory,
792 * and awakening the swapper if it isn't in memory.
793 */
794void
795setrunnable(struct thread *td)
796{
797	struct proc *p = td->td_proc;
798
799	mtx_lock_spin(&sched_lock);
800	switch (p->p_stat) {
801	case SZOMB: /* not a thread flag XXXKSE */
802		panic("setrunnable(1)");
803	}
804	switch (td->td_proc->p_stat) {
805	case 0:
806	case SRUN:
807	case SWAIT:
808	default:
809		panic("setrunnable(2)");
810	case SSTOP:
811	case SSLEEP:			/* e.g. when sending signals */
812		if (td->td_flags & TDF_CVWAITQ)
813			cv_waitq_remove(td);
814		else
815			unsleep(td);
816		break;
817
818	case SIDL:
819		break;
820	}
821	td->td_proc->p_stat = SRUN;
822	if (td->td_ksegrp->kg_slptime > 1)
823		updatepri(td);
824	td->td_ksegrp->kg_slptime = 0;
825	td->td_kse->ke_slptime = 0;
826	if ((p->p_sflag & PS_INMEM) == 0) {
827		p->p_sflag |= PS_SWAPINREQ;
828		wakeup((caddr_t)&proc0);
829	} else {
830		setrunqueue(td);
831		maybe_resched(td->td_ksegrp);
832	}
833	mtx_unlock_spin(&sched_lock);
834}
835
836/*
837 * Compute the priority of a process when running in user mode.
838 * Arrange to reschedule if the resulting priority is better
839 * than that of the current process.
840 */
841void
842resetpriority(kg)
843	register struct ksegrp *kg;
844{
845	register unsigned int newpriority;
846
847	mtx_lock_spin(&sched_lock);
848	if (kg->kg_pri.pri_class == PRI_TIMESHARE) {
849		newpriority = PUSER + kg->kg_estcpu / INVERSE_ESTCPU_WEIGHT +
850		    NICE_WEIGHT * (kg->kg_nice - PRIO_MIN);
851		newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
852		    PRI_MAX_TIMESHARE);
853		kg->kg_pri.pri_user = newpriority;
854	}
855	maybe_resched(kg);
856	mtx_unlock_spin(&sched_lock);
857}
858
859/*
860 * Compute a tenex style load average of a quantity on
861 * 1, 5 and 15 minute intervals.
862 * XXXKSE   Needs complete rewrite when correct info is available.
863 * Completely Bogus.. only works with 1:1 (but compiles ok now :-)
864 */
865static void
866loadav(struct loadavg *avg)
867{
868	int i, nrun;
869	struct proc *p;
870	struct ksegrp *kg;
871
872	sx_slock(&allproc_lock);
873	nrun = 0;
874	FOREACH_PROC_IN_SYSTEM(p) {
875		FOREACH_KSEGRP_IN_PROC(p, kg) {
876			switch (p->p_stat) {
877			case SRUN:
878				if ((p->p_flag & P_NOLOAD) != 0)
879					goto nextproc;
880				/* FALLTHROUGH */
881			case SIDL:
882				nrun++;
883			}
884nextproc:
885		}
886	}
887	sx_sunlock(&allproc_lock);
888	for (i = 0; i < 3; i++)
889		avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
890		    nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
891}
892
893/* ARGSUSED */
894static void
895sched_setup(dummy)
896	void *dummy;
897{
898
899	callout_init(&schedcpu_callout, 1);
900	callout_init(&roundrobin_callout, 0);
901
902	/* Kick off timeout driven events by calling first time. */
903	roundrobin(NULL);
904	schedcpu(NULL);
905}
906
907/*
908 * We adjust the priority of the current process.  The priority of
909 * a process gets worse as it accumulates CPU time.  The cpu usage
910 * estimator (p_estcpu) is increased here.  resetpriority() will
911 * compute a different priority each time p_estcpu increases by
912 * INVERSE_ESTCPU_WEIGHT
913 * (until MAXPRI is reached).  The cpu usage estimator ramps up
914 * quite quickly when the process is running (linearly), and decays
915 * away exponentially, at a rate which is proportionally slower when
916 * the system is busy.  The basic principle is that the system will
917 * 90% forget that the process used a lot of CPU time in 5 * loadav
918 * seconds.  This causes the system to favor processes which haven't
919 * run much recently, and to round-robin among other processes.
920 */
921void
922schedclock(td)
923	struct thread *td;
924{
925	struct kse *ke = td->td_kse;
926	struct ksegrp *kg = td->td_ksegrp;
927
928	if (td) {
929		ke->ke_cpticks++;
930		kg->kg_estcpu = ESTCPULIM(kg->kg_estcpu + 1);
931		if ((kg->kg_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
932			resetpriority(td->td_ksegrp);
933			if (kg->kg_pri.pri_level >= PUSER)
934				kg->kg_pri.pri_level = kg->kg_pri.pri_user;
935		}
936	} else {
937		panic("schedclock");
938	}
939}
940
941/*
942 * General purpose yield system call
943 */
944int
945yield(struct thread *td, struct yield_args *uap)
946{
947	struct ksegrp *kg = td->td_ksegrp;
948
949	mtx_assert(&Giant, MA_NOTOWNED);
950	mtx_lock_spin(&sched_lock);
951	kg->kg_pri.pri_level = PRI_MAX_TIMESHARE;
952	setrunqueue(td);
953	kg->kg_proc->p_stats->p_ru.ru_nvcsw++;
954	mi_switch();
955	mtx_unlock_spin(&sched_lock);
956	td->td_retval[0] = 0;
957
958	return (0);
959}
960
961