kern_synch.c revision 281702
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 * 4. Neither the name of the University nor the names of its contributors
19 *    may be used to endorse or promote products derived from this software
20 *    without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 *
34 *	@(#)kern_synch.c	8.9 (Berkeley) 5/19/95
35 */
36
37#include <sys/cdefs.h>
38__FBSDID("$FreeBSD: head/sys/kern/kern_synch.c 281702 2015-04-18 20:36:58Z markj $");
39
40#include "opt_ktrace.h"
41#include "opt_sched.h"
42
43#include <sys/param.h>
44#include <sys/systm.h>
45#include <sys/condvar.h>
46#include <sys/kdb.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/sched.h>
54#include <sys/sdt.h>
55#include <sys/signalvar.h>
56#include <sys/sleepqueue.h>
57#include <sys/smp.h>
58#include <sys/sx.h>
59#include <sys/sysctl.h>
60#include <sys/sysproto.h>
61#include <sys/vmmeter.h>
62#ifdef KTRACE
63#include <sys/uio.h>
64#include <sys/ktrace.h>
65#endif
66
67#include <machine/cpu.h>
68
69#ifdef XEN
70#include <vm/vm.h>
71#include <vm/vm_param.h>
72#include <vm/pmap.h>
73#endif
74
75#define	KTDSTATE(td)							\
76	(((td)->td_inhibitors & TDI_SLEEPING) != 0 ? "sleep"  :		\
77	((td)->td_inhibitors & TDI_SUSPENDED) != 0 ? "suspended" :	\
78	((td)->td_inhibitors & TDI_SWAPPED) != 0 ? "swapped" :		\
79	((td)->td_inhibitors & TDI_LOCK) != 0 ? "blocked" :		\
80	((td)->td_inhibitors & TDI_IWAIT) != 0 ? "iwait" : "yielding")
81
82static void synch_setup(void *dummy);
83SYSINIT(synch_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, synch_setup,
84    NULL);
85
86int	hogticks;
87static uint8_t pause_wchan[MAXCPU];
88
89static struct callout loadav_callout;
90
91struct loadavg averunnable =
92	{ {0, 0, 0}, FSCALE };	/* load average, of runnable procs */
93/*
94 * Constants for averages over 1, 5, and 15 minutes
95 * when sampling at 5 second intervals.
96 */
97static fixpt_t cexp[3] = {
98	0.9200444146293232 * FSCALE,	/* exp(-1/12) */
99	0.9834714538216174 * FSCALE,	/* exp(-1/60) */
100	0.9944598480048967 * FSCALE,	/* exp(-1/180) */
101};
102
103/* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */
104SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, SYSCTL_NULL_INT_PTR, FSCALE, "");
105
106static void	loadav(void *arg);
107
108SDT_PROVIDER_DECLARE(sched);
109SDT_PROBE_DEFINE(sched, , , preempt);
110
111static void
112sleepinit(void *unused)
113{
114
115	hogticks = (hz / 10) * 2;	/* Default only. */
116	init_sleepqueues();
117}
118
119/*
120 * vmem tries to lock the sleepq mutexes when free'ing kva, so make sure
121 * it is available.
122 */
123SYSINIT(sleepinit, SI_SUB_KMEM, SI_ORDER_ANY, sleepinit, 0);
124
125/*
126 * General sleep call.  Suspends the current thread until a wakeup is
127 * performed on the specified identifier.  The thread will then be made
128 * runnable with the specified priority.  Sleeps at most sbt units of time
129 * (0 means no timeout).  If pri includes the PCATCH flag, let signals
130 * interrupt the sleep, otherwise ignore them while sleeping.  Returns 0 if
131 * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
132 * signal becomes pending, 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 lock argument is unlocked before the caller is suspended, and
137 * re-locked before _sleep() returns.  If priority includes the PDROP
138 * flag the lock is not re-locked before returning.
139 */
140int
141_sleep(void *ident, struct lock_object *lock, int priority,
142    const char *wmesg, sbintime_t sbt, sbintime_t pr, int flags)
143{
144	struct thread *td;
145	struct proc *p;
146	struct lock_class *class;
147	uintptr_t lock_state;
148	int catch, pri, rval, sleepq_flags;
149	WITNESS_SAVE_DECL(lock_witness);
150
151	td = curthread;
152	p = td->td_proc;
153#ifdef KTRACE
154	if (KTRPOINT(td, KTR_CSW))
155		ktrcsw(1, 0, wmesg);
156#endif
157	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, lock,
158	    "Sleeping on \"%s\"", wmesg);
159	KASSERT(sbt != 0 || mtx_owned(&Giant) || lock != NULL,
160	    ("sleeping without a lock"));
161	KASSERT(p != NULL, ("msleep1"));
162	KASSERT(ident != NULL && TD_IS_RUNNING(td), ("msleep"));
163	if (priority & PDROP)
164		KASSERT(lock != NULL && lock != &Giant.lock_object,
165		    ("PDROP requires a non-Giant lock"));
166	if (lock != NULL)
167		class = LOCK_CLASS(lock);
168	else
169		class = NULL;
170
171	if (cold || SCHEDULER_STOPPED()) {
172		/*
173		 * During autoconfiguration, just return;
174		 * don't run any other threads or panic below,
175		 * in case this is the idle thread and already asleep.
176		 * XXX: this used to do "s = splhigh(); splx(safepri);
177		 * splx(s);" to give interrupts a chance, but there is
178		 * no way to give interrupts a chance now.
179		 */
180		if (lock != NULL && priority & PDROP)
181			class->lc_unlock(lock);
182		return (0);
183	}
184	catch = priority & PCATCH;
185	pri = priority & PRIMASK;
186
187	/*
188	 * If we are already on a sleep queue, then remove us from that
189	 * sleep queue first.  We have to do this to handle recursive
190	 * sleeps.
191	 */
192	if (TD_ON_SLEEPQ(td))
193		sleepq_remove(td, td->td_wchan);
194
195	if ((uint8_t *)ident >= &pause_wchan[0] &&
196	    (uint8_t *)ident <= &pause_wchan[MAXCPU - 1])
197		sleepq_flags = SLEEPQ_PAUSE;
198	else
199		sleepq_flags = SLEEPQ_SLEEP;
200	if (catch)
201		sleepq_flags |= SLEEPQ_INTERRUPTIBLE;
202
203	sleepq_lock(ident);
204	CTR5(KTR_PROC, "sleep: thread %ld (pid %ld, %s) on %s (%p)",
205	    td->td_tid, p->p_pid, td->td_name, wmesg, ident);
206
207	if (lock == &Giant.lock_object)
208		mtx_assert(&Giant, MA_OWNED);
209	DROP_GIANT();
210	if (lock != NULL && lock != &Giant.lock_object &&
211	    !(class->lc_flags & LC_SLEEPABLE)) {
212		WITNESS_SAVE(lock, lock_witness);
213		lock_state = class->lc_unlock(lock);
214	} else
215		/* GCC needs to follow the Yellow Brick Road */
216		lock_state = -1;
217
218	/*
219	 * We put ourselves on the sleep queue and start our timeout
220	 * before calling thread_suspend_check, as we could stop there,
221	 * and a wakeup or a SIGCONT (or both) could occur while we were
222	 * stopped without resuming us.  Thus, we must be ready for sleep
223	 * when cursig() is called.  If the wakeup happens while we're
224	 * stopped, then td will no longer be on a sleep queue upon
225	 * return from cursig().
226	 */
227	sleepq_add(ident, lock, wmesg, sleepq_flags, 0);
228	if (sbt != 0)
229		sleepq_set_timeout_sbt(ident, sbt, pr, flags);
230	if (lock != NULL && class->lc_flags & LC_SLEEPABLE) {
231		sleepq_release(ident);
232		WITNESS_SAVE(lock, lock_witness);
233		lock_state = class->lc_unlock(lock);
234		sleepq_lock(ident);
235	}
236	if (sbt != 0 && catch)
237		rval = sleepq_timedwait_sig(ident, pri);
238	else if (sbt != 0)
239		rval = sleepq_timedwait(ident, pri);
240	else if (catch)
241		rval = sleepq_wait_sig(ident, pri);
242	else {
243		sleepq_wait(ident, pri);
244		rval = 0;
245	}
246#ifdef KTRACE
247	if (KTRPOINT(td, KTR_CSW))
248		ktrcsw(0, 0, wmesg);
249#endif
250	PICKUP_GIANT();
251	if (lock != NULL && lock != &Giant.lock_object && !(priority & PDROP)) {
252		class->lc_lock(lock, lock_state);
253		WITNESS_RESTORE(lock, lock_witness);
254	}
255	return (rval);
256}
257
258int
259msleep_spin_sbt(void *ident, struct mtx *mtx, const char *wmesg,
260    sbintime_t sbt, sbintime_t pr, int flags)
261{
262	struct thread *td;
263	struct proc *p;
264	int rval;
265	WITNESS_SAVE_DECL(mtx);
266
267	td = curthread;
268	p = td->td_proc;
269	KASSERT(mtx != NULL, ("sleeping without a mutex"));
270	KASSERT(p != NULL, ("msleep1"));
271	KASSERT(ident != NULL && TD_IS_RUNNING(td), ("msleep"));
272
273	if (cold || SCHEDULER_STOPPED()) {
274		/*
275		 * During autoconfiguration, just return;
276		 * don't run any other threads or panic below,
277		 * in case this is the idle thread and already asleep.
278		 * XXX: this used to do "s = splhigh(); splx(safepri);
279		 * splx(s);" to give interrupts a chance, but there is
280		 * no way to give interrupts a chance now.
281		 */
282		return (0);
283	}
284
285	sleepq_lock(ident);
286	CTR5(KTR_PROC, "msleep_spin: thread %ld (pid %ld, %s) on %s (%p)",
287	    td->td_tid, p->p_pid, td->td_name, wmesg, ident);
288
289	DROP_GIANT();
290	mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED);
291	WITNESS_SAVE(&mtx->lock_object, mtx);
292	mtx_unlock_spin(mtx);
293
294	/*
295	 * We put ourselves on the sleep queue and start our timeout.
296	 */
297	sleepq_add(ident, &mtx->lock_object, wmesg, SLEEPQ_SLEEP, 0);
298	if (sbt != 0)
299		sleepq_set_timeout_sbt(ident, sbt, pr, flags);
300
301	/*
302	 * Can't call ktrace with any spin locks held so it can lock the
303	 * ktrace_mtx lock, and WITNESS_WARN considers it an error to hold
304	 * any spin lock.  Thus, we have to drop the sleepq spin lock while
305	 * we handle those requests.  This is safe since we have placed our
306	 * thread on the sleep queue already.
307	 */
308#ifdef KTRACE
309	if (KTRPOINT(td, KTR_CSW)) {
310		sleepq_release(ident);
311		ktrcsw(1, 0, wmesg);
312		sleepq_lock(ident);
313	}
314#endif
315#ifdef WITNESS
316	sleepq_release(ident);
317	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, "Sleeping on \"%s\"",
318	    wmesg);
319	sleepq_lock(ident);
320#endif
321	if (sbt != 0)
322		rval = sleepq_timedwait(ident, 0);
323	else {
324		sleepq_wait(ident, 0);
325		rval = 0;
326	}
327#ifdef KTRACE
328	if (KTRPOINT(td, KTR_CSW))
329		ktrcsw(0, 0, wmesg);
330#endif
331	PICKUP_GIANT();
332	mtx_lock_spin(mtx);
333	WITNESS_RESTORE(&mtx->lock_object, mtx);
334	return (rval);
335}
336
337/*
338 * pause() delays the calling thread by the given number of system ticks.
339 * During cold bootup, pause() uses the DELAY() function instead of
340 * the tsleep() function to do the waiting. The "timo" argument must be
341 * greater than or equal to zero. A "timo" value of zero is equivalent
342 * to a "timo" value of one.
343 */
344int
345pause_sbt(const char *wmesg, sbintime_t sbt, sbintime_t pr, int flags)
346{
347	KASSERT(sbt >= 0, ("pause: timeout must be >= 0"));
348
349	/* silently convert invalid timeouts */
350	if (sbt == 0)
351		sbt = tick_sbt;
352
353	if (cold || kdb_active) {
354		/*
355		 * We delay one second at a time to avoid overflowing the
356		 * system specific DELAY() function(s):
357		 */
358		while (sbt >= SBT_1S) {
359			DELAY(1000000);
360			sbt -= SBT_1S;
361		}
362		/* Do the delay remainder, if any */
363		sbt = (sbt + SBT_1US - 1) / SBT_1US;
364		if (sbt > 0)
365			DELAY(sbt);
366		return (0);
367	}
368	return (_sleep(&pause_wchan[curcpu], NULL, 0, wmesg, sbt, pr, flags));
369}
370
371/*
372 * Make all threads sleeping on the specified identifier runnable.
373 */
374void
375wakeup(void *ident)
376{
377	int wakeup_swapper;
378
379	sleepq_lock(ident);
380	wakeup_swapper = sleepq_broadcast(ident, SLEEPQ_SLEEP, 0, 0);
381	sleepq_release(ident);
382	if (wakeup_swapper) {
383		KASSERT(ident != &proc0,
384		    ("wakeup and wakeup_swapper and proc0"));
385		kick_proc0();
386	}
387}
388
389/*
390 * Make a thread sleeping on the specified identifier runnable.
391 * May wake more than one thread if a target thread is currently
392 * swapped out.
393 */
394void
395wakeup_one(void *ident)
396{
397	int wakeup_swapper;
398
399	sleepq_lock(ident);
400	wakeup_swapper = sleepq_signal(ident, SLEEPQ_SLEEP, 0, 0);
401	sleepq_release(ident);
402	if (wakeup_swapper)
403		kick_proc0();
404}
405
406static void
407kdb_switch(void)
408{
409	thread_unlock(curthread);
410	kdb_backtrace();
411	kdb_reenter();
412	panic("%s: did not reenter debugger", __func__);
413}
414
415/*
416 * The machine independent parts of context switching.
417 */
418void
419mi_switch(int flags, struct thread *newtd)
420{
421	uint64_t runtime, new_switchtime;
422	struct thread *td;
423	struct proc *p;
424
425	td = curthread;			/* XXX */
426	THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
427	p = td->td_proc;		/* XXX */
428	KASSERT(!TD_ON_RUNQ(td), ("mi_switch: called by old code"));
429#ifdef INVARIANTS
430	if (!TD_ON_LOCK(td) && !TD_IS_RUNNING(td))
431		mtx_assert(&Giant, MA_NOTOWNED);
432#endif
433	KASSERT(td->td_critnest == 1 || panicstr,
434	    ("mi_switch: switch in a critical section"));
435	KASSERT((flags & (SW_INVOL | SW_VOL)) != 0,
436	    ("mi_switch: switch must be voluntary or involuntary"));
437	KASSERT(newtd != curthread, ("mi_switch: preempting back to ourself"));
438
439	/*
440	 * Don't perform context switches from the debugger.
441	 */
442	if (kdb_active)
443		kdb_switch();
444	if (SCHEDULER_STOPPED())
445		return;
446	if (flags & SW_VOL) {
447		td->td_ru.ru_nvcsw++;
448		td->td_swvoltick = ticks;
449	} else
450		td->td_ru.ru_nivcsw++;
451#ifdef SCHED_STATS
452	SCHED_STAT_INC(sched_switch_stats[flags & SW_TYPE_MASK]);
453#endif
454	/*
455	 * Compute the amount of time during which the current
456	 * thread was running, and add that to its total so far.
457	 */
458	new_switchtime = cpu_ticks();
459	runtime = new_switchtime - PCPU_GET(switchtime);
460	td->td_runtime += runtime;
461	td->td_incruntime += runtime;
462	PCPU_SET(switchtime, new_switchtime);
463	td->td_generation++;	/* bump preempt-detect counter */
464	PCPU_INC(cnt.v_swtch);
465	PCPU_SET(switchticks, ticks);
466	CTR4(KTR_PROC, "mi_switch: old thread %ld (td_sched %p, pid %ld, %s)",
467	    td->td_tid, td->td_sched, p->p_pid, td->td_name);
468#if (KTR_COMPILE & KTR_SCHED) != 0
469	if (TD_IS_IDLETHREAD(td))
470		KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "idle",
471		    "prio:%d", td->td_priority);
472	else
473		KTR_STATE3(KTR_SCHED, "thread", sched_tdname(td), KTDSTATE(td),
474		    "prio:%d", td->td_priority, "wmesg:\"%s\"", td->td_wmesg,
475		    "lockname:\"%s\"", td->td_lockname);
476#endif
477	SDT_PROBE0(sched, , , preempt);
478#ifdef XEN
479	PT_UPDATES_FLUSH();
480#endif
481	sched_switch(td, newtd, flags);
482	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
483	    "prio:%d", td->td_priority);
484
485	CTR4(KTR_PROC, "mi_switch: new thread %ld (td_sched %p, pid %ld, %s)",
486	    td->td_tid, td->td_sched, p->p_pid, td->td_name);
487
488	/*
489	 * If the last thread was exiting, finish cleaning it up.
490	 */
491	if ((td = PCPU_GET(deadthread))) {
492		PCPU_SET(deadthread, NULL);
493		thread_stash(td);
494	}
495}
496
497/*
498 * Change thread state to be runnable, placing it on the run queue if
499 * it is in memory.  If it is swapped out, return true so our caller
500 * will know to awaken the swapper.
501 */
502int
503setrunnable(struct thread *td)
504{
505
506	THREAD_LOCK_ASSERT(td, MA_OWNED);
507	KASSERT(td->td_proc->p_state != PRS_ZOMBIE,
508	    ("setrunnable: pid %d is a zombie", td->td_proc->p_pid));
509	switch (td->td_state) {
510	case TDS_RUNNING:
511	case TDS_RUNQ:
512		return (0);
513	case TDS_INHIBITED:
514		/*
515		 * If we are only inhibited because we are swapped out
516		 * then arange to swap in this process. Otherwise just return.
517		 */
518		if (td->td_inhibitors != TDI_SWAPPED)
519			return (0);
520		/* FALLTHROUGH */
521	case TDS_CAN_RUN:
522		break;
523	default:
524		printf("state is 0x%x", td->td_state);
525		panic("setrunnable(2)");
526	}
527	if ((td->td_flags & TDF_INMEM) == 0) {
528		if ((td->td_flags & TDF_SWAPINREQ) == 0) {
529			td->td_flags |= TDF_SWAPINREQ;
530			return (1);
531		}
532	} else
533		sched_wakeup(td);
534	return (0);
535}
536
537/*
538 * Compute a tenex style load average of a quantity on
539 * 1, 5 and 15 minute intervals.
540 */
541static void
542loadav(void *arg)
543{
544	int i, nrun;
545	struct loadavg *avg;
546
547	nrun = sched_load();
548	avg = &averunnable;
549
550	for (i = 0; i < 3; i++)
551		avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
552		    nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
553
554	/*
555	 * Schedule the next update to occur after 5 seconds, but add a
556	 * random variation to avoid synchronisation with processes that
557	 * run at regular intervals.
558	 */
559	callout_reset_sbt(&loadav_callout,
560	    SBT_1US * (4000000 + (int)(random() % 2000001)), SBT_1US,
561	    loadav, NULL, C_DIRECT_EXEC | C_PREL(32));
562}
563
564/* ARGSUSED */
565static void
566synch_setup(void *dummy)
567{
568	callout_init(&loadav_callout, CALLOUT_MPSAFE);
569
570	/* Kick off timeout driven events by calling first time. */
571	loadav(NULL);
572}
573
574int
575should_yield(void)
576{
577
578	return ((u_int)ticks - (u_int)curthread->td_swvoltick >= hogticks);
579}
580
581void
582maybe_yield(void)
583{
584
585	if (should_yield())
586		kern_yield(PRI_USER);
587}
588
589void
590kern_yield(int prio)
591{
592	struct thread *td;
593
594	td = curthread;
595	DROP_GIANT();
596	thread_lock(td);
597	if (prio == PRI_USER)
598		prio = td->td_user_pri;
599	if (prio >= 0)
600		sched_prio(td, prio);
601	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
602	thread_unlock(td);
603	PICKUP_GIANT();
604}
605
606/*
607 * General purpose yield system call.
608 */
609int
610sys_yield(struct thread *td, struct yield_args *uap)
611{
612
613	thread_lock(td);
614	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
615		sched_prio(td, PRI_MAX_TIMESHARE);
616	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
617	thread_unlock(td);
618	td->td_retval[0] = 0;
619	return (0);
620}
621