xref: /freebsd/sys/kern/kern_synch.c (revision cacdd70cc751fb68dec4b86c5e5b8c969b6e26ef)
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$");
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/signalvar.h>
55 #include <sys/sleepqueue.h>
56 #include <sys/smp.h>
57 #include <sys/sx.h>
58 #include <sys/sysctl.h>
59 #include <sys/sysproto.h>
60 #include <sys/vmmeter.h>
61 #ifdef KTRACE
62 #include <sys/uio.h>
63 #include <sys/ktrace.h>
64 #endif
65 
66 #include <machine/cpu.h>
67 
68 static void synch_setup(void *dummy);
69 SYSINIT(synch_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, synch_setup,
70     NULL);
71 
72 int	hogticks;
73 int	lbolt;
74 static int pause_wchan;
75 
76 static struct callout loadav_callout;
77 static struct callout lbolt_callout;
78 
79 struct loadavg averunnable =
80 	{ {0, 0, 0}, FSCALE };	/* load average, of runnable procs */
81 /*
82  * Constants for averages over 1, 5, and 15 minutes
83  * when sampling at 5 second intervals.
84  */
85 static fixpt_t cexp[3] = {
86 	0.9200444146293232 * FSCALE,	/* exp(-1/12) */
87 	0.9834714538216174 * FSCALE,	/* exp(-1/60) */
88 	0.9944598480048967 * FSCALE,	/* exp(-1/180) */
89 };
90 
91 /* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */
92 static int      fscale __unused = FSCALE;
93 SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, "");
94 
95 static void	loadav(void *arg);
96 static void	lboltcb(void *arg);
97 
98 void
99 sleepinit(void)
100 {
101 
102 	hogticks = (hz / 10) * 2;	/* Default only. */
103 	init_sleepqueues();
104 }
105 
106 /*
107  * General sleep call.  Suspends the current thread until a wakeup is
108  * performed on the specified identifier.  The thread will then be made
109  * runnable with the specified priority.  Sleeps at most timo/hz seconds
110  * (0 means no timeout).  If pri includes PCATCH flag, signals are checked
111  * before and after sleeping, else signals are not checked.  Returns 0 if
112  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
113  * signal needs to be delivered, ERESTART is returned if the current system
114  * call should be restarted if possible, and EINTR is returned if the system
115  * call should be interrupted by the signal (return EINTR).
116  *
117  * The lock argument is unlocked before the caller is suspended, and
118  * re-locked before _sleep() returns.  If priority includes the PDROP
119  * flag the lock is not re-locked before returning.
120  */
121 int
122 _sleep(void *ident, struct lock_object *lock, int priority,
123     const char *wmesg, int timo)
124 {
125 	struct thread *td;
126 	struct proc *p;
127 	struct lock_class *class;
128 	int catch, flags, lock_state, pri, rval;
129 	WITNESS_SAVE_DECL(lock_witness);
130 
131 	td = curthread;
132 	p = td->td_proc;
133 #ifdef KTRACE
134 	if (KTRPOINT(td, KTR_CSW))
135 		ktrcsw(1, 0);
136 #endif
137 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, lock,
138 	    "Sleeping on \"%s\"", wmesg);
139 	KASSERT(timo != 0 || mtx_owned(&Giant) || lock != NULL ||
140 	    ident == &lbolt, ("sleeping without a lock"));
141 	KASSERT(p != NULL, ("msleep1"));
142 	KASSERT(ident != NULL && TD_IS_RUNNING(td), ("msleep"));
143 	if (priority & PDROP)
144 		KASSERT(lock != NULL && lock != &Giant.lock_object,
145 		    ("PDROP requires a non-Giant lock"));
146 	if (lock != NULL)
147 		class = LOCK_CLASS(lock);
148 	else
149 		class = NULL;
150 
151 	if (cold) {
152 		/*
153 		 * During autoconfiguration, just return;
154 		 * don't run any other threads or panic below,
155 		 * in case this is the idle thread and already asleep.
156 		 * XXX: this used to do "s = splhigh(); splx(safepri);
157 		 * splx(s);" to give interrupts a chance, but there is
158 		 * no way to give interrupts a chance now.
159 		 */
160 		if (lock != NULL && priority & PDROP)
161 			class->lc_unlock(lock);
162 		return (0);
163 	}
164 	catch = priority & PCATCH;
165 	pri = priority & PRIMASK;
166 	rval = 0;
167 
168 	/*
169 	 * If we are already on a sleep queue, then remove us from that
170 	 * sleep queue first.  We have to do this to handle recursive
171 	 * sleeps.
172 	 */
173 	if (TD_ON_SLEEPQ(td))
174 		sleepq_remove(td, td->td_wchan);
175 
176 	if (ident == &pause_wchan)
177 		flags = SLEEPQ_PAUSE;
178 	else
179 		flags = SLEEPQ_SLEEP;
180 	if (catch)
181 		flags |= SLEEPQ_INTERRUPTIBLE;
182 
183 	sleepq_lock(ident);
184 	CTR5(KTR_PROC, "sleep: thread %ld (pid %ld, %s) on %s (%p)",
185 	    td->td_tid, p->p_pid, td->td_name, wmesg, ident);
186 
187 	DROP_GIANT();
188 	if (lock != NULL && lock != &Giant.lock_object &&
189 	    !(class->lc_flags & LC_SLEEPABLE)) {
190 		WITNESS_SAVE(lock, lock_witness);
191 		lock_state = class->lc_unlock(lock);
192 	} else
193 		/* GCC needs to follow the Yellow Brick Road */
194 		lock_state = -1;
195 
196 	/*
197 	 * We put ourselves on the sleep queue and start our timeout
198 	 * before calling thread_suspend_check, as we could stop there,
199 	 * and a wakeup or a SIGCONT (or both) could occur while we were
200 	 * stopped without resuming us.  Thus, we must be ready for sleep
201 	 * when cursig() is called.  If the wakeup happens while we're
202 	 * stopped, then td will no longer be on a sleep queue upon
203 	 * return from cursig().
204 	 */
205 	sleepq_add(ident, ident == &lbolt ? NULL : lock, wmesg, flags, 0);
206 	if (timo)
207 		sleepq_set_timeout(ident, timo);
208 	if (lock != NULL && class->lc_flags & LC_SLEEPABLE) {
209 		sleepq_release(ident);
210 		WITNESS_SAVE(lock, lock_witness);
211 		lock_state = class->lc_unlock(lock);
212 		sleepq_lock(ident);
213 	}
214 	if (timo && catch)
215 		rval = sleepq_timedwait_sig(ident, pri);
216 	else if (timo)
217 		rval = sleepq_timedwait(ident, pri);
218 	else if (catch)
219 		rval = sleepq_wait_sig(ident, pri);
220 	else {
221 		sleepq_wait(ident, pri);
222 		rval = 0;
223 	}
224 #ifdef KTRACE
225 	if (KTRPOINT(td, KTR_CSW))
226 		ktrcsw(0, 0);
227 #endif
228 	PICKUP_GIANT();
229 	if (lock != NULL && lock != &Giant.lock_object && !(priority & PDROP)) {
230 		class->lc_lock(lock, lock_state);
231 		WITNESS_RESTORE(lock, lock_witness);
232 	}
233 	return (rval);
234 }
235 
236 int
237 msleep_spin(void *ident, struct mtx *mtx, const char *wmesg, int timo)
238 {
239 	struct thread *td;
240 	struct proc *p;
241 	int rval;
242 	WITNESS_SAVE_DECL(mtx);
243 
244 	td = curthread;
245 	p = td->td_proc;
246 	KASSERT(mtx != NULL, ("sleeping without a mutex"));
247 	KASSERT(p != NULL, ("msleep1"));
248 	KASSERT(ident != NULL && TD_IS_RUNNING(td), ("msleep"));
249 
250 	if (cold) {
251 		/*
252 		 * During autoconfiguration, just return;
253 		 * don't run any other threads or panic below,
254 		 * in case this is the idle thread and already asleep.
255 		 * XXX: this used to do "s = splhigh(); splx(safepri);
256 		 * splx(s);" to give interrupts a chance, but there is
257 		 * no way to give interrupts a chance now.
258 		 */
259 		return (0);
260 	}
261 
262 	sleepq_lock(ident);
263 	CTR5(KTR_PROC, "msleep_spin: thread %ld (pid %ld, %s) on %s (%p)",
264 	    td->td_tid, p->p_pid, td->td_name, wmesg, ident);
265 
266 	DROP_GIANT();
267 	mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED);
268 	WITNESS_SAVE(&mtx->lock_object, mtx);
269 	mtx_unlock_spin(mtx);
270 
271 	/*
272 	 * We put ourselves on the sleep queue and start our timeout.
273 	 */
274 	sleepq_add(ident, &mtx->lock_object, wmesg, SLEEPQ_SLEEP, 0);
275 	if (timo)
276 		sleepq_set_timeout(ident, timo);
277 
278 	/*
279 	 * Can't call ktrace with any spin locks held so it can lock the
280 	 * ktrace_mtx lock, and WITNESS_WARN considers it an error to hold
281 	 * any spin lock.  Thus, we have to drop the sleepq spin lock while
282 	 * we handle those requests.  This is safe since we have placed our
283 	 * thread on the sleep queue already.
284 	 */
285 #ifdef KTRACE
286 	if (KTRPOINT(td, KTR_CSW)) {
287 		sleepq_release(ident);
288 		ktrcsw(1, 0);
289 		sleepq_lock(ident);
290 	}
291 #endif
292 #ifdef WITNESS
293 	sleepq_release(ident);
294 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, "Sleeping on \"%s\"",
295 	    wmesg);
296 	sleepq_lock(ident);
297 #endif
298 	if (timo)
299 		rval = sleepq_timedwait(ident, 0);
300 	else {
301 		sleepq_wait(ident, 0);
302 		rval = 0;
303 	}
304 #ifdef KTRACE
305 	if (KTRPOINT(td, KTR_CSW))
306 		ktrcsw(0, 0);
307 #endif
308 	PICKUP_GIANT();
309 	mtx_lock_spin(mtx);
310 	WITNESS_RESTORE(&mtx->lock_object, mtx);
311 	return (rval);
312 }
313 
314 /*
315  * pause() is like tsleep() except that the intention is to not be
316  * explicitly woken up by another thread.  Instead, the current thread
317  * simply wishes to sleep until the timeout expires.  It is
318  * implemented using a dummy wait channel.
319  */
320 int
321 pause(const char *wmesg, int timo)
322 {
323 
324 	KASSERT(timo != 0, ("pause: timeout required"));
325 	return (tsleep(&pause_wchan, 0, wmesg, timo));
326 }
327 
328 /*
329  * Make all threads sleeping on the specified identifier runnable.
330  */
331 void
332 wakeup(void *ident)
333 {
334 	int wakeup_swapper;
335 
336 	sleepq_lock(ident);
337 	wakeup_swapper = sleepq_broadcast(ident, SLEEPQ_SLEEP, 0, 0);
338 	sleepq_release(ident);
339 	if (wakeup_swapper)
340 		kick_proc0();
341 }
342 
343 /*
344  * Make a thread sleeping on the specified identifier runnable.
345  * May wake more than one thread if a target thread is currently
346  * swapped out.
347  */
348 void
349 wakeup_one(void *ident)
350 {
351 	int wakeup_swapper;
352 
353 	sleepq_lock(ident);
354 	wakeup_swapper = sleepq_signal(ident, SLEEPQ_SLEEP, 0, 0);
355 	sleepq_release(ident);
356 	if (wakeup_swapper)
357 		kick_proc0();
358 }
359 
360 static void
361 kdb_switch(void)
362 {
363 	thread_unlock(curthread);
364 	kdb_backtrace();
365 	kdb_reenter();
366 	panic("%s: did not reenter debugger", __func__);
367 }
368 
369 /*
370  * The machine independent parts of context switching.
371  */
372 void
373 mi_switch(int flags, struct thread *newtd)
374 {
375 	uint64_t runtime, new_switchtime;
376 	struct thread *td;
377 	struct proc *p;
378 
379 	td = curthread;			/* XXX */
380 	THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
381 	p = td->td_proc;		/* XXX */
382 	KASSERT(!TD_ON_RUNQ(td), ("mi_switch: called by old code"));
383 #ifdef INVARIANTS
384 	if (!TD_ON_LOCK(td) && !TD_IS_RUNNING(td))
385 		mtx_assert(&Giant, MA_NOTOWNED);
386 #endif
387 	KASSERT(td->td_critnest == 1 || (td->td_critnest == 2 &&
388 	    (td->td_owepreempt) && (flags & SW_INVOL) != 0 &&
389 	    newtd == NULL) || panicstr,
390 	    ("mi_switch: switch in a critical section"));
391 	KASSERT((flags & (SW_INVOL | SW_VOL)) != 0,
392 	    ("mi_switch: switch must be voluntary or involuntary"));
393 	KASSERT(newtd != curthread, ("mi_switch: preempting back to ourself"));
394 
395 	/*
396 	 * Don't perform context switches from the debugger.
397 	 */
398 	if (kdb_active)
399 		kdb_switch();
400 	if (flags & SW_VOL)
401 		td->td_ru.ru_nvcsw++;
402 	else
403 		td->td_ru.ru_nivcsw++;
404 #ifdef SCHED_STATS
405 	SCHED_STAT_INC(sched_switch_stats[flags & SW_TYPE_MASK]);
406 #endif
407 	/*
408 	 * Compute the amount of time during which the current
409 	 * thread was running, and add that to its total so far.
410 	 */
411 	new_switchtime = cpu_ticks();
412 	runtime = new_switchtime - PCPU_GET(switchtime);
413 	td->td_runtime += runtime;
414 	td->td_incruntime += runtime;
415 	PCPU_SET(switchtime, new_switchtime);
416 	td->td_generation++;	/* bump preempt-detect counter */
417 	PCPU_INC(cnt.v_swtch);
418 	PCPU_SET(switchticks, ticks);
419 	CTR4(KTR_PROC, "mi_switch: old thread %ld (td_sched %p, pid %ld, %s)",
420 	    td->td_tid, td->td_sched, p->p_pid, td->td_name);
421 #if (KTR_COMPILE & KTR_SCHED) != 0
422 	if (TD_IS_IDLETHREAD(td))
423 		CTR3(KTR_SCHED, "mi_switch: %p(%s) prio %d idle",
424 		    td, td->td_name, td->td_priority);
425 	else if (newtd != NULL)
426 		CTR5(KTR_SCHED,
427 		    "mi_switch: %p(%s) prio %d preempted by %p(%s)",
428 		    td, td->td_name, td->td_priority, newtd,
429 		    newtd->td_name);
430 	else
431 		CTR6(KTR_SCHED,
432 		    "mi_switch: %p(%s) prio %d inhibit %d wmesg %s lock %s",
433 		    td, td->td_name, td->td_priority,
434 		    td->td_inhibitors, td->td_wmesg, td->td_lockname);
435 #endif
436 	sched_switch(td, newtd, flags);
437 	CTR3(KTR_SCHED, "mi_switch: running %p(%s) prio %d",
438 	    td, td->td_name, td->td_priority);
439 
440 	CTR4(KTR_PROC, "mi_switch: new thread %ld (td_sched %p, pid %ld, %s)",
441 	    td->td_tid, td->td_sched, p->p_pid, td->td_name);
442 
443 	/*
444 	 * If the last thread was exiting, finish cleaning it up.
445 	 */
446 	if ((td = PCPU_GET(deadthread))) {
447 		PCPU_SET(deadthread, NULL);
448 		thread_stash(td);
449 	}
450 }
451 
452 /*
453  * Change thread state to be runnable, placing it on the run queue if
454  * it is in memory.  If it is swapped out, return true so our caller
455  * will know to awaken the swapper.
456  */
457 int
458 setrunnable(struct thread *td)
459 {
460 
461 	THREAD_LOCK_ASSERT(td, MA_OWNED);
462 	KASSERT(td->td_proc->p_state != PRS_ZOMBIE,
463 	    ("setrunnable: pid %d is a zombie", td->td_proc->p_pid));
464 	switch (td->td_state) {
465 	case TDS_RUNNING:
466 	case TDS_RUNQ:
467 		return (0);
468 	case TDS_INHIBITED:
469 		/*
470 		 * If we are only inhibited because we are swapped out
471 		 * then arange to swap in this process. Otherwise just return.
472 		 */
473 		if (td->td_inhibitors != TDI_SWAPPED)
474 			return (0);
475 		/* FALLTHROUGH */
476 	case TDS_CAN_RUN:
477 		break;
478 	default:
479 		printf("state is 0x%x", td->td_state);
480 		panic("setrunnable(2)");
481 	}
482 	if ((td->td_flags & TDF_INMEM) == 0) {
483 		if ((td->td_flags & TDF_SWAPINREQ) == 0) {
484 			td->td_flags |= TDF_SWAPINREQ;
485 			return (1);
486 		}
487 	} else
488 		sched_wakeup(td);
489 	return (0);
490 }
491 
492 /*
493  * Compute a tenex style load average of a quantity on
494  * 1, 5 and 15 minute intervals.
495  */
496 static void
497 loadav(void *arg)
498 {
499 	int i, nrun;
500 	struct loadavg *avg;
501 
502 	nrun = sched_load();
503 	avg = &averunnable;
504 
505 	for (i = 0; i < 3; i++)
506 		avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
507 		    nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
508 
509 	/*
510 	 * Schedule the next update to occur after 5 seconds, but add a
511 	 * random variation to avoid synchronisation with processes that
512 	 * run at regular intervals.
513 	 */
514 	callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)),
515 	    loadav, NULL);
516 }
517 
518 static void
519 lboltcb(void *arg)
520 {
521 	wakeup(&lbolt);
522 	callout_reset(&lbolt_callout, hz, lboltcb, NULL);
523 }
524 
525 /* ARGSUSED */
526 static void
527 synch_setup(void *dummy)
528 {
529 	callout_init(&loadav_callout, CALLOUT_MPSAFE);
530 	callout_init(&lbolt_callout, CALLOUT_MPSAFE);
531 
532 	/* Kick off timeout driven events by calling first time. */
533 	loadav(NULL);
534 	lboltcb(NULL);
535 }
536 
537 /*
538  * General purpose yield system call.
539  */
540 int
541 yield(struct thread *td, struct yield_args *uap)
542 {
543 
544 	thread_lock(td);
545 	sched_prio(td, PRI_MAX_TIMESHARE);
546 	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
547 	thread_unlock(td);
548 	td->td_retval[0] = 0;
549 	return (0);
550 }
551