xref: /freebsd/sys/kern/kern_synch.c (revision 2008043f386721d58158e37e0d7e50df8095942d)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1990, 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	@(#)kern_synch.c	8.9 (Berkeley) 5/19/95
37  */
38 
39 #include <sys/cdefs.h>
40 #include "opt_ktrace.h"
41 #include "opt_sched.h"
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/blockcount.h>
46 #include <sys/condvar.h>
47 #include <sys/kdb.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/sched.h>
55 #include <sys/sdt.h>
56 #include <sys/signalvar.h>
57 #include <sys/sleepqueue.h>
58 #include <sys/smp.h>
59 #include <sys/sx.h>
60 #include <sys/sysctl.h>
61 #include <sys/sysproto.h>
62 #include <sys/vmmeter.h>
63 #ifdef KTRACE
64 #include <sys/uio.h>
65 #include <sys/ktrace.h>
66 #endif
67 #ifdef EPOCH_TRACE
68 #include <sys/epoch.h>
69 #endif
70 
71 #include <machine/cpu.h>
72 
73 static void synch_setup(void *dummy);
74 SYSINIT(synch_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, synch_setup,
75     NULL);
76 
77 int	hogticks;
78 static const char pause_wchan[MAXCPU];
79 
80 static struct callout loadav_callout;
81 
82 struct loadavg averunnable =
83 	{ {0, 0, 0}, FSCALE };	/* load average, of runnable procs */
84 /*
85  * Constants for averages over 1, 5, and 15 minutes
86  * when sampling at 5 second intervals.
87  */
88 static uint64_t cexp[3] = {
89 	0.9200444146293232 * FSCALE,	/* exp(-1/12) */
90 	0.9834714538216174 * FSCALE,	/* exp(-1/60) */
91 	0.9944598480048967 * FSCALE,	/* exp(-1/180) */
92 };
93 
94 /* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */
95 SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, SYSCTL_NULL_INT_PTR, FSCALE,
96     "Fixed-point scale factor used for calculating load average values");
97 
98 static void	loadav(void *arg);
99 
100 SDT_PROVIDER_DECLARE(sched);
101 SDT_PROBE_DEFINE(sched, , , preempt);
102 
103 static void
104 sleepinit(void *unused)
105 {
106 
107 	hogticks = (hz / 10) * 2;	/* Default only. */
108 	init_sleepqueues();
109 }
110 
111 /*
112  * vmem tries to lock the sleepq mutexes when free'ing kva, so make sure
113  * it is available.
114  */
115 SYSINIT(sleepinit, SI_SUB_KMEM, SI_ORDER_ANY, sleepinit, NULL);
116 
117 /*
118  * General sleep call.  Suspends the current thread until a wakeup is
119  * performed on the specified identifier.  The thread will then be made
120  * runnable with the specified priority.  Sleeps at most sbt units of time
121  * (0 means no timeout).  If pri includes the PCATCH flag, let signals
122  * interrupt the sleep, otherwise ignore them while sleeping.  Returns 0 if
123  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
124  * signal becomes pending, ERESTART is returned if the current system
125  * call should be restarted if possible, and EINTR is returned if the system
126  * call should be interrupted by the signal (return EINTR).
127  *
128  * The lock argument is unlocked before the caller is suspended, and
129  * re-locked before _sleep() returns.  If priority includes the PDROP
130  * flag the lock is not re-locked before returning.
131  */
132 int
133 _sleep(const void *ident, struct lock_object *lock, int priority,
134     const char *wmesg, sbintime_t sbt, sbintime_t pr, int flags)
135 {
136 	struct thread *td;
137 	struct lock_class *class;
138 	uintptr_t lock_state;
139 	int catch, pri, rval, sleepq_flags;
140 	WITNESS_SAVE_DECL(lock_witness);
141 
142 	TSENTER();
143 	td = curthread;
144 #ifdef KTRACE
145 	if (KTRPOINT(td, KTR_CSW))
146 		ktrcsw(1, 0, wmesg);
147 #endif
148 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, lock,
149 	    "Sleeping on \"%s\"", wmesg);
150 	KASSERT(sbt != 0 || mtx_owned(&Giant) || lock != NULL ||
151 	    (priority & PNOLOCK) != 0,
152 	    ("sleeping without a lock"));
153 	KASSERT(ident != NULL, ("_sleep: NULL ident"));
154 	KASSERT(TD_IS_RUNNING(td), ("_sleep: curthread not running"));
155 	if (priority & PDROP)
156 		KASSERT(lock != NULL && lock != &Giant.lock_object,
157 		    ("PDROP requires a non-Giant lock"));
158 	if (lock != NULL)
159 		class = LOCK_CLASS(lock);
160 	else
161 		class = NULL;
162 
163 	if (SCHEDULER_STOPPED_TD(td)) {
164 		if (lock != NULL && priority & PDROP)
165 			class->lc_unlock(lock);
166 		return (0);
167 	}
168 	catch = priority & PCATCH;
169 	pri = priority & PRIMASK;
170 
171 	KASSERT(!TD_ON_SLEEPQ(td), ("recursive sleep"));
172 
173 	if ((uintptr_t)ident >= (uintptr_t)&pause_wchan[0] &&
174 	    (uintptr_t)ident <= (uintptr_t)&pause_wchan[MAXCPU - 1])
175 		sleepq_flags = SLEEPQ_PAUSE;
176 	else
177 		sleepq_flags = SLEEPQ_SLEEP;
178 	if (catch)
179 		sleepq_flags |= SLEEPQ_INTERRUPTIBLE;
180 
181 	sleepq_lock(ident);
182 	CTR5(KTR_PROC, "sleep: thread %ld (pid %ld, %s) on %s (%p)",
183 	    td->td_tid, td->td_proc->p_pid, td->td_name, wmesg, ident);
184 
185 	if (lock == &Giant.lock_object)
186 		mtx_assert(&Giant, MA_OWNED);
187 	DROP_GIANT();
188 	if (lock != NULL && lock != &Giant.lock_object &&
189 	    !(class->lc_flags & LC_SLEEPABLE)) {
190 		KASSERT(!(class->lc_flags & LC_SPINLOCK),
191 		    ("spin locks can only use msleep_spin"));
192 		WITNESS_SAVE(lock, lock_witness);
193 		lock_state = class->lc_unlock(lock);
194 	} else
195 		/* GCC needs to follow the Yellow Brick Road */
196 		lock_state = -1;
197 
198 	/*
199 	 * We put ourselves on the sleep queue and start our timeout
200 	 * before calling thread_suspend_check, as we could stop there,
201 	 * and a wakeup or a SIGCONT (or both) could occur while we were
202 	 * stopped without resuming us.  Thus, we must be ready for sleep
203 	 * when cursig() is called.  If the wakeup happens while we're
204 	 * stopped, then td will no longer be on a sleep queue upon
205 	 * return from cursig().
206 	 */
207 	sleepq_add(ident, lock, wmesg, sleepq_flags, 0);
208 	if (sbt != 0)
209 		sleepq_set_timeout_sbt(ident, sbt, pr, flags);
210 	if (lock != NULL && class->lc_flags & LC_SLEEPABLE) {
211 		sleepq_release(ident);
212 		WITNESS_SAVE(lock, lock_witness);
213 		lock_state = class->lc_unlock(lock);
214 		sleepq_lock(ident);
215 	}
216 	if (sbt != 0 && catch)
217 		rval = sleepq_timedwait_sig(ident, pri);
218 	else if (sbt != 0)
219 		rval = sleepq_timedwait(ident, pri);
220 	else if (catch)
221 		rval = sleepq_wait_sig(ident, pri);
222 	else {
223 		sleepq_wait(ident, pri);
224 		rval = 0;
225 	}
226 #ifdef KTRACE
227 	if (KTRPOINT(td, KTR_CSW))
228 		ktrcsw(0, 0, wmesg);
229 #endif
230 	PICKUP_GIANT();
231 	if (lock != NULL && lock != &Giant.lock_object && !(priority & PDROP)) {
232 		class->lc_lock(lock, lock_state);
233 		WITNESS_RESTORE(lock, lock_witness);
234 	}
235 	TSEXIT();
236 	return (rval);
237 }
238 
239 int
240 msleep_spin_sbt(const void *ident, struct mtx *mtx, const char *wmesg,
241     sbintime_t sbt, sbintime_t pr, int flags)
242 {
243 	struct thread *td;
244 	int rval;
245 	WITNESS_SAVE_DECL(mtx);
246 
247 	td = curthread;
248 	KASSERT(mtx != NULL, ("sleeping without a mutex"));
249 	KASSERT(ident != NULL, ("msleep_spin_sbt: NULL ident"));
250 	KASSERT(TD_IS_RUNNING(td), ("msleep_spin_sbt: curthread not running"));
251 
252 	if (SCHEDULER_STOPPED_TD(td))
253 		return (0);
254 
255 	sleepq_lock(ident);
256 	CTR5(KTR_PROC, "msleep_spin: thread %ld (pid %ld, %s) on %s (%p)",
257 	    td->td_tid, td->td_proc->p_pid, td->td_name, wmesg, ident);
258 
259 	DROP_GIANT();
260 	mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED);
261 	WITNESS_SAVE(&mtx->lock_object, mtx);
262 	mtx_unlock_spin(mtx);
263 
264 	/*
265 	 * We put ourselves on the sleep queue and start our timeout.
266 	 */
267 	sleepq_add(ident, &mtx->lock_object, wmesg, SLEEPQ_SLEEP, 0);
268 	if (sbt != 0)
269 		sleepq_set_timeout_sbt(ident, sbt, pr, flags);
270 
271 	/*
272 	 * Can't call ktrace with any spin locks held so it can lock the
273 	 * ktrace_mtx lock, and WITNESS_WARN considers it an error to hold
274 	 * any spin lock.  Thus, we have to drop the sleepq spin lock while
275 	 * we handle those requests.  This is safe since we have placed our
276 	 * thread on the sleep queue already.
277 	 */
278 #ifdef KTRACE
279 	if (KTRPOINT(td, KTR_CSW)) {
280 		sleepq_release(ident);
281 		ktrcsw(1, 0, wmesg);
282 		sleepq_lock(ident);
283 	}
284 #endif
285 #ifdef WITNESS
286 	sleepq_release(ident);
287 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, "Sleeping on \"%s\"",
288 	    wmesg);
289 	sleepq_lock(ident);
290 #endif
291 	if (sbt != 0)
292 		rval = sleepq_timedwait(ident, 0);
293 	else {
294 		sleepq_wait(ident, 0);
295 		rval = 0;
296 	}
297 #ifdef KTRACE
298 	if (KTRPOINT(td, KTR_CSW))
299 		ktrcsw(0, 0, wmesg);
300 #endif
301 	PICKUP_GIANT();
302 	mtx_lock_spin(mtx);
303 	WITNESS_RESTORE(&mtx->lock_object, mtx);
304 	return (rval);
305 }
306 
307 /*
308  * pause_sbt() delays the calling thread by the given signed binary
309  * time. During cold bootup, pause_sbt() uses the DELAY() function
310  * instead of the _sleep() function to do the waiting. The "sbt"
311  * argument must be greater than or equal to zero. A "sbt" value of
312  * zero is equivalent to a "sbt" value of one tick.
313  */
314 int
315 pause_sbt(const char *wmesg, sbintime_t sbt, sbintime_t pr, int flags)
316 {
317 	KASSERT(sbt >= 0, ("pause_sbt: timeout must be >= 0"));
318 
319 	/* silently convert invalid timeouts */
320 	if (sbt == 0)
321 		sbt = tick_sbt;
322 
323 	if ((cold && curthread == &thread0) || kdb_active ||
324 	    SCHEDULER_STOPPED()) {
325 		/*
326 		 * We delay one second at a time to avoid overflowing the
327 		 * system specific DELAY() function(s):
328 		 */
329 		while (sbt >= SBT_1S) {
330 			DELAY(1000000);
331 			sbt -= SBT_1S;
332 		}
333 		/* Do the delay remainder, if any */
334 		sbt = howmany(sbt, SBT_1US);
335 		if (sbt > 0)
336 			DELAY(sbt);
337 		return (EWOULDBLOCK);
338 	}
339 	return (_sleep(&pause_wchan[curcpu], NULL,
340 	    (flags & C_CATCH) ? PCATCH : 0, wmesg, sbt, pr, flags));
341 }
342 
343 /*
344  * Make all threads sleeping on the specified identifier runnable.
345  */
346 void
347 wakeup(const void *ident)
348 {
349 	int wakeup_swapper;
350 
351 	sleepq_lock(ident);
352 	wakeup_swapper = sleepq_broadcast(ident, SLEEPQ_SLEEP, 0, 0);
353 	sleepq_release(ident);
354 	if (wakeup_swapper) {
355 		KASSERT(ident != &proc0,
356 		    ("wakeup and wakeup_swapper and proc0"));
357 		kick_proc0();
358 	}
359 }
360 
361 /*
362  * Make a thread sleeping on the specified identifier runnable.
363  * May wake more than one thread if a target thread is currently
364  * swapped out.
365  */
366 void
367 wakeup_one(const void *ident)
368 {
369 	int wakeup_swapper;
370 
371 	sleepq_lock(ident);
372 	wakeup_swapper = sleepq_signal(ident, SLEEPQ_SLEEP | SLEEPQ_DROP, 0, 0);
373 	if (wakeup_swapper)
374 		kick_proc0();
375 }
376 
377 void
378 wakeup_any(const void *ident)
379 {
380 	int wakeup_swapper;
381 
382 	sleepq_lock(ident);
383 	wakeup_swapper = sleepq_signal(ident, SLEEPQ_SLEEP | SLEEPQ_UNFAIR |
384 	    SLEEPQ_DROP, 0, 0);
385 	if (wakeup_swapper)
386 		kick_proc0();
387 }
388 
389 /*
390  * Signal sleeping waiters after the counter has reached zero.
391  */
392 void
393 _blockcount_wakeup(blockcount_t *bc, u_int old)
394 {
395 
396 	KASSERT(_BLOCKCOUNT_WAITERS(old),
397 	    ("%s: no waiters on %p", __func__, bc));
398 
399 	if (atomic_cmpset_int(&bc->__count, _BLOCKCOUNT_WAITERS_FLAG, 0))
400 		wakeup(bc);
401 }
402 
403 /*
404  * Wait for a wakeup or a signal.  This does not guarantee that the count is
405  * still zero on return.  Callers wanting a precise answer should use
406  * blockcount_wait() with an interlock.
407  *
408  * If there is no work to wait for, return 0.  If the sleep was interrupted by a
409  * signal, return EINTR or ERESTART, and return EAGAIN otherwise.
410  */
411 int
412 _blockcount_sleep(blockcount_t *bc, struct lock_object *lock, const char *wmesg,
413     int prio)
414 {
415 	void *wchan;
416 	uintptr_t lock_state;
417 	u_int old;
418 	int ret;
419 	bool catch, drop;
420 
421 	KASSERT(lock != &Giant.lock_object,
422 	    ("%s: cannot use Giant as the interlock", __func__));
423 
424 	catch = (prio & PCATCH) != 0;
425 	drop = (prio & PDROP) != 0;
426 	prio &= PRIMASK;
427 
428 	/*
429 	 * Synchronize with the fence in blockcount_release().  If we end up
430 	 * waiting, the sleepqueue lock acquisition will provide the required
431 	 * side effects.
432 	 *
433 	 * If there is no work to wait for, but waiters are present, try to put
434 	 * ourselves to sleep to avoid jumping ahead.
435 	 */
436 	if (atomic_load_acq_int(&bc->__count) == 0) {
437 		if (lock != NULL && drop)
438 			LOCK_CLASS(lock)->lc_unlock(lock);
439 		return (0);
440 	}
441 	lock_state = 0;
442 	wchan = bc;
443 	sleepq_lock(wchan);
444 	DROP_GIANT();
445 	if (lock != NULL)
446 		lock_state = LOCK_CLASS(lock)->lc_unlock(lock);
447 	old = blockcount_read(bc);
448 	ret = 0;
449 	do {
450 		if (_BLOCKCOUNT_COUNT(old) == 0) {
451 			sleepq_release(wchan);
452 			goto out;
453 		}
454 		if (_BLOCKCOUNT_WAITERS(old))
455 			break;
456 	} while (!atomic_fcmpset_int(&bc->__count, &old,
457 	    old | _BLOCKCOUNT_WAITERS_FLAG));
458 	sleepq_add(wchan, NULL, wmesg, catch ? SLEEPQ_INTERRUPTIBLE : 0, 0);
459 	if (catch)
460 		ret = sleepq_wait_sig(wchan, prio);
461 	else
462 		sleepq_wait(wchan, prio);
463 	if (ret == 0)
464 		ret = EAGAIN;
465 
466 out:
467 	PICKUP_GIANT();
468 	if (lock != NULL && !drop)
469 		LOCK_CLASS(lock)->lc_lock(lock, lock_state);
470 
471 	return (ret);
472 }
473 
474 static void
475 kdb_switch(void)
476 {
477 	thread_unlock(curthread);
478 	kdb_backtrace();
479 	kdb_reenter();
480 	panic("%s: did not reenter debugger", __func__);
481 }
482 
483 /*
484  * mi_switch(9): The machine-independent parts of context switching.
485  *
486  * The thread lock is required on entry and is no longer held on return.
487  */
488 void
489 mi_switch(int flags)
490 {
491 	uint64_t runtime, new_switchtime;
492 	struct thread *td;
493 
494 	td = curthread;			/* XXX */
495 	THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
496 	KASSERT(!TD_ON_RUNQ(td), ("mi_switch: called by old code"));
497 #ifdef INVARIANTS
498 	if (!TD_ON_LOCK(td) && !TD_IS_RUNNING(td))
499 		mtx_assert(&Giant, MA_NOTOWNED);
500 #endif
501 	/* thread_lock() performs spinlock_enter(). */
502 	KASSERT(td->td_critnest == 1 || KERNEL_PANICKED(),
503 	    ("mi_switch: switch in a critical section"));
504 	KASSERT((flags & (SW_INVOL | SW_VOL)) != 0,
505 	    ("mi_switch: switch must be voluntary or involuntary"));
506 	KASSERT((flags & SW_TYPE_MASK) != 0,
507 	    ("mi_switch: a switch reason (type) must be specified"));
508 	KASSERT((flags & SW_TYPE_MASK) < SWT_COUNT,
509 	    ("mi_switch: invalid switch reason %d", (flags & SW_TYPE_MASK)));
510 
511 	/*
512 	 * Don't perform context switches from the debugger.
513 	 */
514 	if (kdb_active)
515 		kdb_switch();
516 	if (SCHEDULER_STOPPED_TD(td))
517 		return;
518 	if (flags & SW_VOL) {
519 		td->td_ru.ru_nvcsw++;
520 		td->td_swvoltick = ticks;
521 	} else {
522 		td->td_ru.ru_nivcsw++;
523 		td->td_swinvoltick = ticks;
524 	}
525 #ifdef SCHED_STATS
526 	SCHED_STAT_INC(sched_switch_stats[flags & SW_TYPE_MASK]);
527 #endif
528 	/*
529 	 * Compute the amount of time during which the current
530 	 * thread was running, and add that to its total so far.
531 	 */
532 	new_switchtime = cpu_ticks();
533 	runtime = new_switchtime - PCPU_GET(switchtime);
534 	td->td_runtime += runtime;
535 	td->td_incruntime += runtime;
536 	PCPU_SET(switchtime, new_switchtime);
537 	td->td_generation++;	/* bump preempt-detect counter */
538 	VM_CNT_INC(v_swtch);
539 	PCPU_SET(switchticks, ticks);
540 	CTR4(KTR_PROC, "mi_switch: old thread %ld (td_sched %p, pid %ld, %s)",
541 	    td->td_tid, td_get_sched(td), td->td_proc->p_pid, td->td_name);
542 #ifdef KDTRACE_HOOKS
543 	if (SDT_PROBES_ENABLED() &&
544 	    ((flags & SW_PREEMPT) != 0 || ((flags & SW_INVOL) != 0 &&
545 	    (flags & SW_TYPE_MASK) == SWT_NEEDRESCHED)))
546 		SDT_PROBE0(sched, , , preempt);
547 #endif
548 	sched_switch(td, flags);
549 	CTR4(KTR_PROC, "mi_switch: new thread %ld (td_sched %p, pid %ld, %s)",
550 	    td->td_tid, td_get_sched(td), td->td_proc->p_pid, td->td_name);
551 
552 	/*
553 	 * If the last thread was exiting, finish cleaning it up.
554 	 */
555 	if ((td = PCPU_GET(deadthread))) {
556 		PCPU_SET(deadthread, NULL);
557 		thread_stash(td);
558 	}
559 	spinlock_exit();
560 }
561 
562 /*
563  * Change thread state to be runnable, placing it on the run queue if
564  * it is in memory.  If it is swapped out, return true so our caller
565  * will know to awaken the swapper.
566  *
567  * Requires the thread lock on entry, drops on exit.
568  */
569 int
570 setrunnable(struct thread *td, int srqflags)
571 {
572 	int swapin;
573 
574 	THREAD_LOCK_ASSERT(td, MA_OWNED);
575 	KASSERT(td->td_proc->p_state != PRS_ZOMBIE,
576 	    ("setrunnable: pid %d is a zombie", td->td_proc->p_pid));
577 
578 	swapin = 0;
579 	switch (TD_GET_STATE(td)) {
580 	case TDS_RUNNING:
581 	case TDS_RUNQ:
582 		break;
583 	case TDS_CAN_RUN:
584 		KASSERT((td->td_flags & TDF_INMEM) != 0,
585 		    ("setrunnable: td %p not in mem, flags 0x%X inhibit 0x%X",
586 		    td, td->td_flags, td->td_inhibitors));
587 		/* unlocks thread lock according to flags */
588 		sched_wakeup(td, srqflags);
589 		return (0);
590 	case TDS_INHIBITED:
591 		/*
592 		 * If we are only inhibited because we are swapped out
593 		 * arrange to swap in this process.
594 		 */
595 		if (td->td_inhibitors == TDI_SWAPPED &&
596 		    (td->td_flags & TDF_SWAPINREQ) == 0) {
597 			td->td_flags |= TDF_SWAPINREQ;
598 			swapin = 1;
599 		}
600 		break;
601 	default:
602 		panic("setrunnable: state 0x%x", TD_GET_STATE(td));
603 	}
604 	if ((srqflags & (SRQ_HOLD | SRQ_HOLDTD)) == 0)
605 		thread_unlock(td);
606 
607 	return (swapin);
608 }
609 
610 /*
611  * Compute a tenex style load average of a quantity on
612  * 1, 5 and 15 minute intervals.
613  */
614 static void
615 loadav(void *arg)
616 {
617 	int i;
618 	uint64_t nrun;
619 	struct loadavg *avg;
620 
621 	nrun = (uint64_t)sched_load();
622 	avg = &averunnable;
623 
624 	for (i = 0; i < 3; i++)
625 		avg->ldavg[i] = (cexp[i] * (uint64_t)avg->ldavg[i] +
626 		    nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
627 
628 	/*
629 	 * Schedule the next update to occur after 5 seconds, but add a
630 	 * random variation to avoid synchronisation with processes that
631 	 * run at regular intervals.
632 	 */
633 	callout_reset_sbt(&loadav_callout,
634 	    SBT_1US * (4000000 + (int)(random() % 2000001)), SBT_1US,
635 	    loadav, NULL, C_DIRECT_EXEC | C_PREL(32));
636 }
637 
638 static void
639 ast_scheduler(struct thread *td, int tda __unused)
640 {
641 #ifdef KTRACE
642 	if (KTRPOINT(td, KTR_CSW))
643 		ktrcsw(1, 1, __func__);
644 #endif
645 	thread_lock(td);
646 	sched_prio(td, td->td_user_pri);
647 	mi_switch(SW_INVOL | SWT_NEEDRESCHED);
648 #ifdef KTRACE
649 	if (KTRPOINT(td, KTR_CSW))
650 		ktrcsw(0, 1, __func__);
651 #endif
652 }
653 
654 static void
655 synch_setup(void *dummy __unused)
656 {
657 	callout_init(&loadav_callout, 1);
658 	ast_register(TDA_SCHED, ASTR_ASTF_REQUIRED, 0, ast_scheduler);
659 
660 	/* Kick off timeout driven events by calling first time. */
661 	loadav(NULL);
662 }
663 
664 bool
665 should_yield(void)
666 {
667 
668 	return ((u_int)ticks - (u_int)curthread->td_swvoltick >= hogticks);
669 }
670 
671 void
672 maybe_yield(void)
673 {
674 
675 	if (should_yield())
676 		kern_yield(PRI_USER);
677 }
678 
679 void
680 kern_yield(int prio)
681 {
682 	struct thread *td;
683 
684 	td = curthread;
685 	DROP_GIANT();
686 	thread_lock(td);
687 	if (prio == PRI_USER)
688 		prio = td->td_user_pri;
689 	if (prio >= 0)
690 		sched_prio(td, prio);
691 	mi_switch(SW_VOL | SWT_RELINQUISH);
692 	PICKUP_GIANT();
693 }
694 
695 /*
696  * General purpose yield system call.
697  */
698 int
699 sys_yield(struct thread *td, struct yield_args *uap)
700 {
701 
702 	thread_lock(td);
703 	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
704 		sched_prio(td, PRI_MAX_TIMESHARE);
705 	mi_switch(SW_VOL | SWT_RELINQUISH);
706 	td->td_retval[0] = 0;
707 	return (0);
708 }
709 
710 int
711 sys_sched_getcpu(struct thread *td, struct sched_getcpu_args *uap)
712 {
713 	td->td_retval[0] = td->td_oncpu;
714 	return (0);
715 }
716