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