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