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