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