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