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