xref: /freebsd/sys/kern/kern_synch.c (revision 7bd6fde3951af84ef3b68e4d1eadc1840c2fc1b3)
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, NULL)
69 
70 int	hogticks;
71 int	lbolt;
72 static int pause_wchan;
73 
74 static struct callout loadav_callout;
75 static struct callout lbolt_callout;
76 
77 struct loadavg averunnable =
78 	{ {0, 0, 0}, FSCALE };	/* load average, of runnable procs */
79 /*
80  * Constants for averages over 1, 5, and 15 minutes
81  * when sampling at 5 second intervals.
82  */
83 static fixpt_t cexp[3] = {
84 	0.9200444146293232 * FSCALE,	/* exp(-1/12) */
85 	0.9834714538216174 * FSCALE,	/* exp(-1/60) */
86 	0.9944598480048967 * FSCALE,	/* exp(-1/180) */
87 };
88 
89 /* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */
90 static int      fscale __unused = FSCALE;
91 SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, "");
92 
93 static void	loadav(void *arg);
94 static void	lboltcb(void *arg);
95 
96 void
97 sleepinit(void)
98 {
99 
100 	hogticks = (hz / 10) * 2;	/* Default only. */
101 	init_sleepqueues();
102 }
103 
104 /*
105  * General sleep call.  Suspends the current thread until a wakeup is
106  * performed on the specified identifier.  The thread will then be made
107  * runnable with the specified priority.  Sleeps at most timo/hz seconds
108  * (0 means no timeout).  If pri includes PCATCH flag, signals are checked
109  * before and after sleeping, else signals are not checked.  Returns 0 if
110  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
111  * signal needs to be delivered, ERESTART is returned if the current system
112  * call should be restarted if possible, and EINTR is returned if the system
113  * call should be interrupted by the signal (return EINTR).
114  *
115  * The mutex argument is unlocked before the caller is suspended, and
116  * re-locked before msleep returns.  If priority includes the PDROP
117  * flag the mutex is not re-locked before returning.
118  */
119 int
120 msleep(ident, mtx, priority, wmesg, timo)
121 	void *ident;
122 	struct mtx *mtx;
123 	int priority, timo;
124 	const char *wmesg;
125 {
126 	struct thread *td;
127 	struct proc *p;
128 	int catch, rval, flags, pri;
129 	WITNESS_SAVE_DECL(mtx);
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, mtx == NULL ? NULL :
138 	    &mtx->mtx_object, "Sleeping on \"%s\"", wmesg);
139 	KASSERT(timo != 0 || mtx_owned(&Giant) || mtx != NULL ||
140 	    ident == &lbolt, ("sleeping without a mutex"));
141 	KASSERT(p != NULL, ("msleep1"));
142 	KASSERT(ident != NULL && TD_IS_RUNNING(td), ("msleep"));
143 
144 	if (cold) {
145 		/*
146 		 * During autoconfiguration, just return;
147 		 * don't run any other threads or panic below,
148 		 * in case this is the idle thread and already asleep.
149 		 * XXX: this used to do "s = splhigh(); splx(safepri);
150 		 * splx(s);" to give interrupts a chance, but there is
151 		 * no way to give interrupts a chance now.
152 		 */
153 		if (mtx != NULL && priority & PDROP)
154 			mtx_unlock(mtx);
155 		return (0);
156 	}
157 	catch = priority & PCATCH;
158 	rval = 0;
159 
160 	/*
161 	 * If we are already on a sleep queue, then remove us from that
162 	 * sleep queue first.  We have to do this to handle recursive
163 	 * sleeps.
164 	 */
165 	if (TD_ON_SLEEPQ(td))
166 		sleepq_remove(td, td->td_wchan);
167 
168 	if (ident == &pause_wchan)
169 		flags = SLEEPQ_PAUSE;
170 	else
171 		flags = SLEEPQ_MSLEEP;
172 	if (catch)
173 		flags |= SLEEPQ_INTERRUPTIBLE;
174 
175 	sleepq_lock(ident);
176 	CTR5(KTR_PROC, "msleep: thread %ld (pid %ld, %s) on %s (%p)",
177 	    td->td_tid, p->p_pid, p->p_comm, wmesg, ident);
178 
179 	DROP_GIANT();
180 	if (mtx != NULL) {
181 		mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED);
182 		WITNESS_SAVE(&mtx->mtx_object, mtx);
183 		mtx_unlock(mtx);
184 	}
185 
186 	/*
187 	 * We put ourselves on the sleep queue and start our timeout
188 	 * before calling thread_suspend_check, as we could stop there,
189 	 * and a wakeup or a SIGCONT (or both) could occur while we were
190 	 * stopped without resuming us.  Thus, we must be ready for sleep
191 	 * when cursig() is called.  If the wakeup happens while we're
192 	 * stopped, then td will no longer be on a sleep queue upon
193 	 * return from cursig().
194 	 */
195 	sleepq_add(ident, ident == &lbolt ? NULL : &mtx->mtx_object, wmesg,
196 	    flags, 0);
197 	if (timo)
198 		sleepq_set_timeout(ident, timo);
199 
200 	/*
201 	 * Adjust this thread's priority, if necessary.
202 	 */
203 	pri = priority & PRIMASK;
204 	if (pri != 0 && pri != td->td_priority) {
205 		mtx_lock_spin(&sched_lock);
206 		sched_prio(td, pri);
207 		mtx_unlock_spin(&sched_lock);
208 	}
209 
210 	if (timo && catch)
211 		rval = sleepq_timedwait_sig(ident);
212 	else if (timo)
213 		rval = sleepq_timedwait(ident);
214 	else if (catch)
215 		rval = sleepq_wait_sig(ident);
216 	else {
217 		sleepq_wait(ident);
218 		rval = 0;
219 	}
220 #ifdef KTRACE
221 	if (KTRPOINT(td, KTR_CSW))
222 		ktrcsw(0, 0);
223 #endif
224 	PICKUP_GIANT();
225 	if (mtx != NULL && !(priority & PDROP)) {
226 		mtx_lock(mtx);
227 		WITNESS_RESTORE(&mtx->mtx_object, mtx);
228 	}
229 	return (rval);
230 }
231 
232 int
233 msleep_spin(ident, mtx, wmesg, timo)
234 	void *ident;
235 	struct mtx *mtx;
236 	const char *wmesg;
237 	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, p->p_comm, wmesg, ident);
265 
266 	DROP_GIANT();
267 	mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED);
268 	WITNESS_SAVE(&mtx->mtx_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->mtx_object, wmesg, SLEEPQ_MSLEEP, 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);
300 	else {
301 		sleepq_wait(ident);
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->mtx_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(wmesg, timo)
322 	const char *wmesg;
323 	int timo;
324 {
325 
326 	KASSERT(timo != 0, ("pause: timeout required"));
327 	return (tsleep(&pause_wchan, 0, wmesg, timo));
328 }
329 
330 /*
331  * Make all threads sleeping on the specified identifier runnable.
332  */
333 void
334 wakeup(ident)
335 	register void *ident;
336 {
337 
338 	sleepq_lock(ident);
339 	sleepq_broadcast(ident, SLEEPQ_MSLEEP, -1, 0);
340 }
341 
342 /*
343  * Make a thread sleeping on the specified identifier runnable.
344  * May wake more than one thread if a target thread is currently
345  * swapped out.
346  */
347 void
348 wakeup_one(ident)
349 	register void *ident;
350 {
351 
352 	sleepq_lock(ident);
353 	sleepq_signal(ident, SLEEPQ_MSLEEP, -1, 0);
354 }
355 
356 /*
357  * The machine independent parts of context switching.
358  */
359 void
360 mi_switch(int flags, struct thread *newtd)
361 {
362 	uint64_t new_switchtime;
363 	struct thread *td;
364 	struct proc *p;
365 
366 	mtx_assert(&sched_lock, MA_OWNED | MA_NOTRECURSED);
367 	td = curthread;			/* XXX */
368 	p = td->td_proc;		/* XXX */
369 	KASSERT(!TD_ON_RUNQ(td), ("mi_switch: called by old code"));
370 #ifdef INVARIANTS
371 	if (!TD_ON_LOCK(td) && !TD_IS_RUNNING(td))
372 		mtx_assert(&Giant, MA_NOTOWNED);
373 #endif
374 	KASSERT(td->td_critnest == 1 || (td->td_critnest == 2 &&
375 	    (td->td_owepreempt) && (flags & SW_INVOL) != 0 &&
376 	    newtd == NULL) || panicstr,
377 	    ("mi_switch: switch in a critical section"));
378 	KASSERT((flags & (SW_INVOL | SW_VOL)) != 0,
379 	    ("mi_switch: switch must be voluntary or involuntary"));
380 	KASSERT(newtd != curthread, ("mi_switch: preempting back to ourself"));
381 
382 	/*
383 	 * Don't perform context switches from the debugger.
384 	 */
385 	if (kdb_active) {
386 		mtx_unlock_spin(&sched_lock);
387 		kdb_backtrace();
388 		kdb_reenter();
389 		panic("%s: did not reenter debugger", __func__);
390 	}
391 
392 	if (flags & SW_VOL)
393 		p->p_stats->p_ru.ru_nvcsw++;
394 	else
395 		p->p_stats->p_ru.ru_nivcsw++;
396 
397 	/*
398 	 * Compute the amount of time during which the current
399 	 * process was running, and add that to its total so far.
400 	 */
401 	new_switchtime = cpu_ticks();
402 	p->p_rux.rux_runtime += (new_switchtime - PCPU_GET(switchtime));
403 	p->p_rux.rux_uticks += td->td_uticks;
404 	td->td_uticks = 0;
405 	p->p_rux.rux_iticks += td->td_iticks;
406 	td->td_iticks = 0;
407 	p->p_rux.rux_sticks += td->td_sticks;
408 	td->td_sticks = 0;
409 
410 	td->td_generation++;	/* bump preempt-detect counter */
411 
412 	/*
413 	 * Check if the process exceeds its cpu resource allocation.  If
414 	 * it reaches the max, arrange to kill the process in ast().
415 	 */
416 	if (p->p_cpulimit != RLIM_INFINITY &&
417 	    p->p_rux.rux_runtime >= p->p_cpulimit * cpu_tickrate()) {
418 		p->p_sflag |= PS_XCPU;
419 		td->td_flags |= TDF_ASTPENDING;
420 	}
421 
422 	/*
423 	 * Finish up stats for outgoing thread.
424 	 */
425 	cnt.v_swtch++;
426 	PCPU_SET(switchtime, new_switchtime);
427 	PCPU_SET(switchticks, ticks);
428 	CTR4(KTR_PROC, "mi_switch: old thread %ld (kse %p, pid %ld, %s)",
429 	    td->td_tid, td->td_sched, p->p_pid, p->p_comm);
430 #if (KTR_COMPILE & KTR_SCHED) != 0
431 	if (td == PCPU_GET(idlethread))
432 		CTR3(KTR_SCHED, "mi_switch: %p(%s) prio %d idle",
433 		    td, td->td_proc->p_comm, td->td_priority);
434 	else if (newtd != NULL)
435 		CTR5(KTR_SCHED,
436 		    "mi_switch: %p(%s) prio %d preempted by %p(%s)",
437 		    td, td->td_proc->p_comm, td->td_priority, newtd,
438 		    newtd->td_proc->p_comm);
439 	else
440 		CTR6(KTR_SCHED,
441 		    "mi_switch: %p(%s) prio %d inhibit %d wmesg %s lock %s",
442 		    td, td->td_proc->p_comm, td->td_priority,
443 		    td->td_inhibitors, td->td_wmesg, td->td_lockname);
444 #endif
445 	/*
446 	 * We call thread_switchout after the KTR_SCHED prints above so kse
447 	 * selecting a new thread to run does not show up as a preemption.
448 	 */
449 #ifdef KSE
450 	if ((flags & SW_VOL) && (td->td_proc->p_flag & P_SA))
451 		newtd = thread_switchout(td, flags, newtd);
452 #endif
453 	sched_switch(td, newtd, flags);
454 	CTR3(KTR_SCHED, "mi_switch: running %p(%s) prio %d",
455 	    td, td->td_proc->p_comm, td->td_priority);
456 
457 	CTR4(KTR_PROC, "mi_switch: new thread %ld (kse %p, pid %ld, %s)",
458 	    td->td_tid, td->td_sched, p->p_pid, p->p_comm);
459 
460 	/*
461 	 * If the last thread was exiting, finish cleaning it up.
462 	 */
463 	if ((td = PCPU_GET(deadthread))) {
464 		PCPU_SET(deadthread, NULL);
465 		thread_stash(td);
466 	}
467 }
468 
469 /*
470  * Change process state to be runnable,
471  * placing it on the run queue if it is in memory,
472  * and awakening the swapper if it isn't in memory.
473  */
474 void
475 setrunnable(struct thread *td)
476 {
477 	struct proc *p;
478 
479 	p = td->td_proc;
480 	mtx_assert(&sched_lock, MA_OWNED);
481 	switch (p->p_state) {
482 	case PRS_ZOMBIE:
483 		panic("setrunnable(1)");
484 	default:
485 		break;
486 	}
487 	switch (td->td_state) {
488 	case TDS_RUNNING:
489 	case TDS_RUNQ:
490 		return;
491 	case TDS_INHIBITED:
492 		/*
493 		 * If we are only inhibited because we are swapped out
494 		 * then arange to swap in this process. Otherwise just return.
495 		 */
496 		if (td->td_inhibitors != TDI_SWAPPED)
497 			return;
498 		/* XXX: intentional fall-through ? */
499 	case TDS_CAN_RUN:
500 		break;
501 	default:
502 		printf("state is 0x%x", td->td_state);
503 		panic("setrunnable(2)");
504 	}
505 	if ((p->p_sflag & PS_INMEM) == 0) {
506 		if ((p->p_sflag & PS_SWAPPINGIN) == 0) {
507 			p->p_sflag |= PS_SWAPINREQ;
508 			/*
509 			 * due to a LOR between sched_lock and
510 			 * the sleepqueue chain locks, use
511 			 * lower level scheduling functions.
512 			 */
513 			kick_proc0();
514 		}
515 	} else
516 		sched_wakeup(td);
517 }
518 
519 /*
520  * Compute a tenex style load average of a quantity on
521  * 1, 5 and 15 minute intervals.
522  * XXXKSE   Needs complete rewrite when correct info is available.
523  * Completely Bogus.. only works with 1:1 (but compiles ok now :-)
524  */
525 static void
526 loadav(void *arg)
527 {
528 	int i, nrun;
529 	struct loadavg *avg;
530 
531 	nrun = sched_load();
532 	avg = &averunnable;
533 
534 	for (i = 0; i < 3; i++)
535 		avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
536 		    nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
537 
538 	/*
539 	 * Schedule the next update to occur after 5 seconds, but add a
540 	 * random variation to avoid synchronisation with processes that
541 	 * run at regular intervals.
542 	 */
543 	callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)),
544 	    loadav, NULL);
545 }
546 
547 static void
548 lboltcb(void *arg)
549 {
550 	wakeup(&lbolt);
551 	callout_reset(&lbolt_callout, hz, lboltcb, NULL);
552 }
553 
554 /* ARGSUSED */
555 static void
556 synch_setup(dummy)
557 	void *dummy;
558 {
559 	callout_init(&loadav_callout, CALLOUT_MPSAFE);
560 	callout_init(&lbolt_callout, CALLOUT_MPSAFE);
561 
562 	/* Kick off timeout driven events by calling first time. */
563 	loadav(NULL);
564 	lboltcb(NULL);
565 }
566 
567 /*
568  * General purpose yield system call
569  */
570 int
571 yield(struct thread *td, struct yield_args *uap)
572 {
573 	mtx_assert(&Giant, MA_NOTOWNED);
574 	(void)uap;
575 	sched_relinquish(td);
576 	return (0);
577 }
578