xref: /freebsd/sys/kern/kern_synch.c (revision 06a31d6a6779b74405b41c8ad4579b5d81db4d4c)
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 #ifdef __i386__
45 #include "opt_swtch.h"
46 #endif
47 
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/condvar.h>
51 #include <sys/kernel.h>
52 #include <sys/ktr.h>
53 #include <sys/lock.h>
54 #include <sys/mutex.h>
55 #include <sys/proc.h>
56 #include <sys/resourcevar.h>
57 #include <sys/sched.h>
58 #include <sys/signalvar.h>
59 #include <sys/smp.h>
60 #include <sys/sx.h>
61 #include <sys/sysctl.h>
62 #include <sys/sysproto.h>
63 #include <sys/vmmeter.h>
64 #ifdef DDB
65 #include <ddb/ddb.h>
66 #endif
67 #ifdef KTRACE
68 #include <sys/uio.h>
69 #include <sys/ktrace.h>
70 #endif
71 
72 #include <machine/cpu.h>
73 #ifdef SWTCH_OPTIM_STATS
74 #include <machine/md_var.h>
75 #endif
76 
77 static void sched_setup(void *dummy);
78 SYSINIT(sched_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, sched_setup, NULL)
79 
80 int	hogticks;
81 int	lbolt;
82 
83 static struct callout loadav_callout;
84 static struct callout lbolt_callout;
85 
86 struct loadavg averunnable =
87 	{ {0, 0, 0}, FSCALE };	/* load average, of runnable procs */
88 /*
89  * Constants for averages over 1, 5, and 15 minutes
90  * when sampling at 5 second intervals.
91  */
92 static fixpt_t cexp[3] = {
93 	0.9200444146293232 * FSCALE,	/* exp(-1/12) */
94 	0.9834714538216174 * FSCALE,	/* exp(-1/60) */
95 	0.9944598480048967 * FSCALE,	/* exp(-1/180) */
96 };
97 
98 /* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */
99 static int      fscale __unused = FSCALE;
100 SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, "");
101 
102 static void	endtsleep(void *);
103 static void	loadav(void *arg);
104 static void	lboltcb(void *arg);
105 
106 /*
107  * We're only looking at 7 bits of the address; everything is
108  * aligned to 4, lots of things are aligned to greater powers
109  * of 2.  Shift right by 8, i.e. drop the bottom 256 worth.
110  */
111 #define TABLESIZE	128
112 static TAILQ_HEAD(slpquehead, thread) slpque[TABLESIZE];
113 #define LOOKUP(x)	(((intptr_t)(x) >> 8) & (TABLESIZE - 1))
114 
115 void
116 sleepinit(void)
117 {
118 	int i;
119 
120 	hogticks = (hz / 10) * 2;	/* Default only. */
121 	for (i = 0; i < TABLESIZE; i++)
122 		TAILQ_INIT(&slpque[i]);
123 }
124 
125 /*
126  * General sleep call.  Suspends the current process until a wakeup is
127  * performed on the specified identifier.  The process will then be made
128  * runnable with the specified priority.  Sleeps at most timo/hz seconds
129  * (0 means no timeout).  If pri includes PCATCH flag, signals are checked
130  * before and after sleeping, else signals are not checked.  Returns 0 if
131  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
132  * signal needs to be delivered, ERESTART is returned if the current system
133  * call should be restarted if possible, and EINTR is returned if the system
134  * call should be interrupted by the signal (return EINTR).
135  *
136  * The mutex argument is exited before the caller is suspended, and
137  * entered before msleep returns.  If priority includes the PDROP
138  * flag the mutex is not entered before returning.
139  */
140 
141 int
142 msleep(ident, mtx, priority, wmesg, timo)
143 	void *ident;
144 	struct mtx *mtx;
145 	int priority, timo;
146 	const char *wmesg;
147 {
148 	struct thread *td = curthread;
149 	struct proc *p = td->td_proc;
150 	int sig, catch = priority & PCATCH;
151 	int rval = 0;
152 	WITNESS_SAVE_DECL(mtx);
153 
154 #ifdef KTRACE
155 	if (KTRPOINT(td, KTR_CSW))
156 		ktrcsw(1, 0);
157 #endif
158 	/* XXX: mtx == NULL ?? */
159 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, &mtx->mtx_object,
160 	    "Sleeping on \"%s\"", wmesg);
161 	KASSERT(timo != 0 || mtx_owned(&Giant) || mtx != NULL,
162 	    ("sleeping without a mutex"));
163 	/*
164 	 * If we are capable of async syscalls and there isn't already
165 	 * another one ready to return, start a new thread
166 	 * and queue it as ready to run. Note that there is danger here
167 	 * because we need to make sure that we don't sleep allocating
168 	 * the thread (recursion here might be bad).
169 	 */
170 	mtx_lock_spin(&sched_lock);
171 	if (p->p_flag & P_THREADED || p->p_numthreads > 1) {
172 		/*
173 		 * Just don't bother if we are exiting
174 		 * and not the exiting thread or thread was marked as
175 		 * interrupted.
176 		 */
177 		if (catch &&
178 		    (((p->p_flag & P_WEXIT) && (p->p_singlethread != td)) ||
179 		     (td->td_flags & TDF_INTERRUPT))) {
180 			td->td_flags &= ~TDF_INTERRUPT;
181 			mtx_unlock_spin(&sched_lock);
182 			return (EINTR);
183 		}
184 	}
185 	if (cold ) {
186 		/*
187 		 * During autoconfiguration, just give interrupts
188 		 * a chance, then just return.
189 		 * Don't run any other procs or panic below,
190 		 * in case this is the idle process and already asleep.
191 		 */
192 		if (mtx != NULL && priority & PDROP)
193 			mtx_unlock(mtx);
194 		mtx_unlock_spin(&sched_lock);
195 		return (0);
196 	}
197 
198 	DROP_GIANT();
199 
200 	if (mtx != NULL) {
201 		mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED);
202 		WITNESS_SAVE(&mtx->mtx_object, mtx);
203 		mtx_unlock(mtx);
204 		if (priority & PDROP)
205 			mtx = NULL;
206 	}
207 
208 	KASSERT(p != NULL, ("msleep1"));
209 	KASSERT(ident != NULL && TD_IS_RUNNING(td), ("msleep"));
210 
211 	CTR5(KTR_PROC, "msleep: thread %p (pid %d, %s) on %s (%p)",
212 	    td, p->p_pid, p->p_comm, wmesg, ident);
213 
214 	td->td_wchan = ident;
215 	td->td_wmesg = wmesg;
216 	TAILQ_INSERT_TAIL(&slpque[LOOKUP(ident)], td, td_slpq);
217 	TD_SET_ON_SLEEPQ(td);
218 	if (timo)
219 		callout_reset(&td->td_slpcallout, timo, endtsleep, td);
220 	/*
221 	 * We put ourselves on the sleep queue and start our timeout
222 	 * before calling thread_suspend_check, as we could stop there, and
223 	 * a wakeup or a SIGCONT (or both) could occur while we were stopped.
224 	 * without resuming us, thus we must be ready for sleep
225 	 * when cursig is called.  If the wakeup happens while we're
226 	 * stopped, td->td_wchan will be 0 upon return from cursig.
227 	 */
228 	if (catch) {
229 		CTR3(KTR_PROC, "msleep caught: thread %p (pid %d, %s)", td,
230 		    p->p_pid, p->p_comm);
231 		td->td_flags |= TDF_SINTR;
232 		mtx_unlock_spin(&sched_lock);
233 		PROC_LOCK(p);
234 		mtx_lock(&p->p_sigacts->ps_mtx);
235 		sig = cursig(td);
236 		mtx_unlock(&p->p_sigacts->ps_mtx);
237 		if (sig == 0 && thread_suspend_check(1))
238 			sig = SIGSTOP;
239 		mtx_lock_spin(&sched_lock);
240 		PROC_UNLOCK(p);
241 		if (sig != 0) {
242 			if (TD_ON_SLEEPQ(td))
243 				unsleep(td);
244 		} else if (!TD_ON_SLEEPQ(td))
245 			catch = 0;
246 	} else
247 		sig = 0;
248 
249 	/*
250 	 * Let the scheduler know we're about to voluntarily go to sleep.
251 	 */
252 	sched_sleep(td, priority & PRIMASK);
253 
254 	if (TD_ON_SLEEPQ(td)) {
255 		p->p_stats->p_ru.ru_nvcsw++;
256 		TD_SET_SLEEPING(td);
257 		mi_switch();
258 	}
259 	/*
260 	 * We're awake from voluntary sleep.
261 	 */
262 	CTR3(KTR_PROC, "msleep resume: thread %p (pid %d, %s)", td, p->p_pid,
263 	    p->p_comm);
264 	KASSERT(TD_IS_RUNNING(td), ("running but not TDS_RUNNING"));
265 	td->td_flags &= ~TDF_SINTR;
266 	if (td->td_flags & TDF_TIMEOUT) {
267 		td->td_flags &= ~TDF_TIMEOUT;
268 		if (sig == 0)
269 			rval = EWOULDBLOCK;
270 	} else if (td->td_flags & TDF_TIMOFAIL) {
271 		td->td_flags &= ~TDF_TIMOFAIL;
272 	} else if (timo && callout_stop(&td->td_slpcallout) == 0) {
273 		/*
274 		 * This isn't supposed to be pretty.  If we are here, then
275 		 * the endtsleep() callout is currently executing on another
276 		 * CPU and is either spinning on the sched_lock or will be
277 		 * soon.  If we don't synchronize here, there is a chance
278 		 * that this process may msleep() again before the callout
279 		 * has a chance to run and the callout may end up waking up
280 		 * the wrong msleep().  Yuck.
281 		 */
282 		TD_SET_SLEEPING(td);
283 		p->p_stats->p_ru.ru_nivcsw++;
284 		mi_switch();
285 		td->td_flags &= ~TDF_TIMOFAIL;
286 	}
287 	if ((td->td_flags & TDF_INTERRUPT) && (priority & PCATCH) &&
288 	    (rval == 0)) {
289 		td->td_flags &= ~TDF_INTERRUPT;
290 		rval = EINTR;
291 	}
292 	mtx_unlock_spin(&sched_lock);
293 
294 	if (rval == 0 && catch) {
295 		PROC_LOCK(p);
296 		/* XXX: shouldn't we always be calling cursig() */
297 		mtx_lock(&p->p_sigacts->ps_mtx);
298 		if (sig != 0 || (sig = cursig(td))) {
299 			if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
300 				rval = EINTR;
301 			else
302 				rval = ERESTART;
303 		}
304 		mtx_unlock(&p->p_sigacts->ps_mtx);
305 		PROC_UNLOCK(p);
306 	}
307 #ifdef KTRACE
308 	if (KTRPOINT(td, KTR_CSW))
309 		ktrcsw(0, 0);
310 #endif
311 	PICKUP_GIANT();
312 	if (mtx != NULL) {
313 		mtx_lock(mtx);
314 		WITNESS_RESTORE(&mtx->mtx_object, mtx);
315 	}
316 	return (rval);
317 }
318 
319 /*
320  * Implement timeout for msleep()
321  *
322  * If process hasn't been awakened (wchan non-zero),
323  * set timeout flag and undo the sleep.  If proc
324  * is stopped, just unsleep so it will remain stopped.
325  * MP-safe, called without the Giant mutex.
326  */
327 static void
328 endtsleep(arg)
329 	void *arg;
330 {
331 	register struct thread *td = arg;
332 
333 	CTR3(KTR_PROC, "endtsleep: thread %p (pid %d, %s)",
334 	    td, td->td_proc->p_pid, td->td_proc->p_comm);
335 	mtx_lock_spin(&sched_lock);
336 	/*
337 	 * This is the other half of the synchronization with msleep()
338 	 * described above.  If the TDS_TIMEOUT flag is set, we lost the
339 	 * race and just need to put the process back on the runqueue.
340 	 */
341 	if (TD_ON_SLEEPQ(td)) {
342 		TAILQ_REMOVE(&slpque[LOOKUP(td->td_wchan)], td, td_slpq);
343 		TD_CLR_ON_SLEEPQ(td);
344 		td->td_flags |= TDF_TIMEOUT;
345 		td->td_wmesg = NULL;
346 	} else {
347 		td->td_flags |= TDF_TIMOFAIL;
348 	}
349 	TD_CLR_SLEEPING(td);
350 	setrunnable(td);
351 	mtx_unlock_spin(&sched_lock);
352 }
353 
354 /*
355  * Abort a thread, as if an interrupt had occured.  Only abort
356  * interruptable waits (unfortunatly it isn't only safe to abort others).
357  * This is about identical to cv_abort().
358  * Think about merging them?
359  * Also, whatever the signal code does...
360  */
361 void
362 abortsleep(struct thread *td)
363 {
364 
365 	mtx_assert(&sched_lock, MA_OWNED);
366 	/*
367 	 * If the TDF_TIMEOUT flag is set, just leave. A
368 	 * timeout is scheduled anyhow.
369 	 */
370 	if ((td->td_flags & (TDF_TIMEOUT | TDF_SINTR)) == TDF_SINTR) {
371 		if (TD_ON_SLEEPQ(td)) {
372 			unsleep(td);
373 			TD_CLR_SLEEPING(td);
374 			setrunnable(td);
375 		}
376 	}
377 }
378 
379 /*
380  * Remove a process from its wait queue
381  */
382 void
383 unsleep(struct thread *td)
384 {
385 
386 	mtx_lock_spin(&sched_lock);
387 	if (TD_ON_SLEEPQ(td)) {
388 		TAILQ_REMOVE(&slpque[LOOKUP(td->td_wchan)], td, td_slpq);
389 		TD_CLR_ON_SLEEPQ(td);
390 		td->td_wmesg = NULL;
391 	}
392 	mtx_unlock_spin(&sched_lock);
393 }
394 
395 /*
396  * Make all processes sleeping on the specified identifier runnable.
397  */
398 void
399 wakeup(ident)
400 	register void *ident;
401 {
402 	register struct slpquehead *qp;
403 	register struct thread *td;
404 	struct thread *ntd;
405 	struct proc *p;
406 
407 	mtx_lock_spin(&sched_lock);
408 	qp = &slpque[LOOKUP(ident)];
409 restart:
410 	for (td = TAILQ_FIRST(qp); td != NULL; td = ntd) {
411 		ntd = TAILQ_NEXT(td, td_slpq);
412 		if (td->td_wchan == ident) {
413 			unsleep(td);
414 			TD_CLR_SLEEPING(td);
415 			setrunnable(td);
416 			p = td->td_proc;
417 			CTR3(KTR_PROC,"wakeup: thread %p (pid %d, %s)",
418 			    td, p->p_pid, p->p_comm);
419 			goto restart;
420 		}
421 	}
422 	mtx_unlock_spin(&sched_lock);
423 }
424 
425 /*
426  * Make a process sleeping on the specified identifier runnable.
427  * May wake more than one process if a target process is currently
428  * swapped out.
429  */
430 void
431 wakeup_one(ident)
432 	register void *ident;
433 {
434 	register struct slpquehead *qp;
435 	register struct thread *td;
436 	register struct proc *p;
437 	struct thread *ntd;
438 
439 	mtx_lock_spin(&sched_lock);
440 	qp = &slpque[LOOKUP(ident)];
441 	for (td = TAILQ_FIRST(qp); td != NULL; td = ntd) {
442 		ntd = TAILQ_NEXT(td, td_slpq);
443 		if (td->td_wchan == ident) {
444 			unsleep(td);
445 			TD_CLR_SLEEPING(td);
446 			setrunnable(td);
447 			p = td->td_proc;
448 			CTR3(KTR_PROC,"wakeup1: thread %p (pid %d, %s)",
449 			    td, p->p_pid, p->p_comm);
450 			break;
451 		}
452 	}
453 	mtx_unlock_spin(&sched_lock);
454 }
455 
456 /*
457  * The machine independent parts of mi_switch().
458  */
459 void
460 mi_switch(void)
461 {
462 	struct bintime new_switchtime;
463 	struct thread *td;
464 #if !defined(__alpha__) && !defined(__powerpc__)
465 	struct thread *newtd;
466 #endif
467 	struct proc *p;
468 	u_int sched_nest;
469 
470 	mtx_assert(&sched_lock, MA_OWNED | MA_NOTRECURSED);
471 	td = curthread;			/* XXX */
472 	p = td->td_proc;		/* XXX */
473 	KASSERT(!TD_ON_RUNQ(td), ("mi_switch: called by old code"));
474 #ifdef INVARIANTS
475 	if (!TD_ON_LOCK(td) && !TD_IS_RUNNING(td))
476 		mtx_assert(&Giant, MA_NOTOWNED);
477 #endif
478 	KASSERT(td->td_critnest == 1,
479 	    ("mi_switch: switch in a critical section"));
480 
481 	/*
482 	 * Compute the amount of time during which the current
483 	 * process was running, and add that to its total so far.
484 	 */
485 	binuptime(&new_switchtime);
486 	bintime_add(&p->p_runtime, &new_switchtime);
487 	bintime_sub(&p->p_runtime, PCPU_PTR(switchtime));
488 
489 #ifdef DDB
490 	/*
491 	 * Don't perform context switches from the debugger.
492 	 */
493 	if (db_active) {
494 		mtx_unlock_spin(&sched_lock);
495 		db_print_backtrace();
496 		db_error("Context switches not allowed in the debugger.");
497 	}
498 #endif
499 
500 	/*
501 	 * Check if the process exceeds its cpu resource allocation.  If
502 	 * over max, arrange to kill the process in ast().
503 	 */
504 	if (p->p_cpulimit != RLIM_INFINITY &&
505 	    p->p_runtime.sec > p->p_cpulimit) {
506 		p->p_sflag |= PS_XCPU;
507 		td->td_flags |= TDF_ASTPENDING;
508 	}
509 
510 	/*
511 	 * Finish up stats for outgoing thread.
512 	 */
513 	cnt.v_swtch++;
514 	PCPU_SET(switchtime, new_switchtime);
515 	CTR3(KTR_PROC, "mi_switch: old thread %p (pid %d, %s)", td, p->p_pid,
516 	    p->p_comm);
517 	sched_nest = sched_lock.mtx_recurse;
518 	if (td->td_proc->p_flag & P_THREADED)
519 		thread_switchout(td);
520 	sched_switchout(td);
521 
522 #if !defined(__alpha__) && !defined(__powerpc__)
523 	newtd = choosethread();
524 	if (td != newtd)
525 		cpu_switch(td, newtd);	/* SHAZAM!! */
526 #ifdef SWTCH_OPTIM_STATS
527 	else
528 		stupid_switch++;
529 #endif
530 #else
531 	cpu_switch();		/* SHAZAM!!*/
532 #endif
533 
534 	sched_lock.mtx_recurse = sched_nest;
535 	sched_lock.mtx_lock = (uintptr_t)td;
536 	sched_switchin(td);
537 
538 	/*
539 	 * Start setting up stats etc. for the incoming thread.
540 	 * Similar code in fork_exit() is returned to by cpu_switch()
541 	 * in the case of a new thread/process.
542 	 */
543 	CTR3(KTR_PROC, "mi_switch: new thread %p (pid %d, %s)", td, p->p_pid,
544 	    p->p_comm);
545 	if (PCPU_GET(switchtime.sec) == 0)
546 		binuptime(PCPU_PTR(switchtime));
547 	PCPU_SET(switchticks, ticks);
548 
549 	/*
550 	 * Call the switchin function while still holding the scheduler lock
551 	 * (used by the idlezero code and the general page-zeroing code)
552 	 */
553 	if (td->td_switchin)
554 		td->td_switchin();
555 
556 	/*
557 	 * If the last thread was exiting, finish cleaning it up.
558 	 */
559 	if ((td = PCPU_GET(deadthread))) {
560 		PCPU_SET(deadthread, NULL);
561 		thread_stash(td);
562 	}
563 }
564 
565 /*
566  * Change process state to be runnable,
567  * placing it on the run queue if it is in memory,
568  * and awakening the swapper if it isn't in memory.
569  */
570 void
571 setrunnable(struct thread *td)
572 {
573 	struct proc *p = td->td_proc;
574 
575 	mtx_assert(&sched_lock, MA_OWNED);
576 	switch (p->p_state) {
577 	case PRS_ZOMBIE:
578 		panic("setrunnable(1)");
579 	default:
580 		break;
581 	}
582 	switch (td->td_state) {
583 	case TDS_RUNNING:
584 	case TDS_RUNQ:
585 		return;
586 	case TDS_INHIBITED:
587 		/*
588 		 * If we are only inhibited because we are swapped out
589 		 * then arange to swap in this process. Otherwise just return.
590 		 */
591 		if (td->td_inhibitors != TDI_SWAPPED)
592 			return;
593 		/* XXX: intentional fall-through ? */
594 	case TDS_CAN_RUN:
595 		break;
596 	default:
597 		printf("state is 0x%x", td->td_state);
598 		panic("setrunnable(2)");
599 	}
600 	if ((p->p_sflag & PS_INMEM) == 0) {
601 		if ((p->p_sflag & PS_SWAPPINGIN) == 0) {
602 			p->p_sflag |= PS_SWAPINREQ;
603 			wakeup(&proc0);
604 		}
605 	} else
606 		sched_wakeup(td);
607 }
608 
609 /*
610  * Compute a tenex style load average of a quantity on
611  * 1, 5 and 15 minute intervals.
612  * XXXKSE   Needs complete rewrite when correct info is available.
613  * Completely Bogus.. only works with 1:1 (but compiles ok now :-)
614  */
615 static void
616 loadav(void *arg)
617 {
618 	int i, nrun;
619 	struct loadavg *avg;
620 	struct proc *p;
621 	struct thread *td;
622 
623 	avg = &averunnable;
624 	sx_slock(&allproc_lock);
625 	nrun = 0;
626 	FOREACH_PROC_IN_SYSTEM(p) {
627 		FOREACH_THREAD_IN_PROC(p, td) {
628 			switch (td->td_state) {
629 			case TDS_RUNQ:
630 			case TDS_RUNNING:
631 				if ((p->p_flag & P_NOLOAD) != 0)
632 					goto nextproc;
633 				nrun++; /* XXXKSE */
634 			default:
635 				break;
636 			}
637 nextproc:
638 			continue;
639 		}
640 	}
641 	sx_sunlock(&allproc_lock);
642 	for (i = 0; i < 3; i++)
643 		avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
644 		    nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
645 
646 	/*
647 	 * Schedule the next update to occur after 5 seconds, but add a
648 	 * random variation to avoid synchronisation with processes that
649 	 * run at regular intervals.
650 	 */
651 	callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)),
652 	    loadav, NULL);
653 }
654 
655 static void
656 lboltcb(void *arg)
657 {
658 	wakeup(&lbolt);
659 	callout_reset(&lbolt_callout, hz, lboltcb, NULL);
660 }
661 
662 /* ARGSUSED */
663 static void
664 sched_setup(dummy)
665 	void *dummy;
666 {
667 	callout_init(&loadav_callout, 0);
668 	callout_init(&lbolt_callout, 1);
669 
670 	/* Kick off timeout driven events by calling first time. */
671 	loadav(NULL);
672 	lboltcb(NULL);
673 }
674 
675 /*
676  * General purpose yield system call
677  */
678 int
679 yield(struct thread *td, struct yield_args *uap)
680 {
681 	struct ksegrp *kg = td->td_ksegrp;
682 
683 	mtx_assert(&Giant, MA_NOTOWNED);
684 	mtx_lock_spin(&sched_lock);
685 	kg->kg_proc->p_stats->p_ru.ru_nvcsw++;
686 	sched_prio(td, PRI_MAX_TIMESHARE);
687 	mi_switch();
688 	mtx_unlock_spin(&sched_lock);
689 	td->td_retval[0] = 0;
690 
691 	return (0);
692 }
693 
694