xref: /freebsd/sys/kern/kern_synch.c (revision fbf96e52bbd90bbbb9c9e2ae6fbc101fa6ebd080)
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 process until a wakeup is
105  * performed on the specified identifier.  The process 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 exited before the caller is suspended, and
115  * entered before msleep returns.  If priority includes the PDROP
116  * flag the mutex is not entered 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 sleepqueue *sq;
126 	struct thread *td;
127 	struct proc *p;
128 	int catch, rval, sig;
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 	    ("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 	sq = sleepq_lookup(ident);
169 	mtx_lock_spin(&sched_lock);
170 
171 	if (p->p_flag & P_SA || p->p_numthreads > 1) {
172 		/*
173 		 * Just don't bother if we are exiting
174 		 * and not the exiting thread or thread was marked as
175 		 * interrupted.
176 		 */
177 		if (catch) {
178 			if ((p->p_flag & P_WEXIT) && p->p_singlethread != td) {
179 				mtx_unlock_spin(&sched_lock);
180 				sleepq_release(ident);
181 				return (EINTR);
182 			}
183 			if (td->td_flags & TDF_INTERRUPT) {
184 				mtx_unlock_spin(&sched_lock);
185 				sleepq_release(ident);
186 				return (td->td_intrval);
187 			}
188 		}
189 	}
190 	mtx_unlock_spin(&sched_lock);
191 	CTR5(KTR_PROC, "msleep: thread %p (pid %ld, %s) on %s (%p)",
192 	    (void *)td, (long)p->p_pid, p->p_comm, wmesg, ident);
193 
194 	DROP_GIANT();
195 	if (mtx != NULL) {
196 		mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED);
197 		WITNESS_SAVE(&mtx->mtx_object, mtx);
198 		mtx_unlock(mtx);
199 	}
200 
201 	/*
202 	 * We put ourselves on the sleep queue and start our timeout
203 	 * before calling thread_suspend_check, as we could stop there,
204 	 * and a wakeup or a SIGCONT (or both) could occur while we were
205 	 * stopped without resuming us.  Thus, we must be ready for sleep
206 	 * when cursig() is called.  If the wakeup happens while we're
207 	 * stopped, then td will no longer be on a sleep queue upon
208 	 * return from cursig().
209 	 */
210 	sleepq_add(sq, ident, mtx, wmesg, 0);
211 	if (timo)
212 		sleepq_set_timeout(ident, timo);
213 	if (catch) {
214 		sig = sleepq_catch_signals(ident);
215 		if (sig == 0 && !TD_ON_SLEEPQ(td)) {
216 			mtx_lock_spin(&sched_lock);
217 			td->td_flags &= ~TDF_SINTR;
218 			mtx_unlock_spin(&sched_lock);
219 			catch = 0;
220 		}
221 	} else
222 		sig = 0;
223 
224 	/*
225 	 * Adjust this thread's priority.
226 	 *
227 	 * XXX: do we need to save priority in td_base_pri?
228 	 */
229 	mtx_lock_spin(&sched_lock);
230 	sched_prio(td, priority & PRIMASK);
231 	mtx_unlock_spin(&sched_lock);
232 
233 	if (timo && catch)
234 		rval = sleepq_timedwait_sig(ident, sig != 0);
235 	else if (timo)
236 		rval = sleepq_timedwait(ident);
237 	else if (catch)
238 		rval = sleepq_wait_sig(ident);
239 	else {
240 		sleepq_wait(ident);
241 		rval = 0;
242 	}
243 	if (rval == 0 && catch)
244 		rval = sleepq_calc_signal_retval(sig);
245 #ifdef KTRACE
246 	if (KTRPOINT(td, KTR_CSW))
247 		ktrcsw(0, 0);
248 #endif
249 	PICKUP_GIANT();
250 	if (mtx != NULL && !(priority & PDROP)) {
251 		mtx_lock(mtx);
252 		WITNESS_RESTORE(&mtx->mtx_object, mtx);
253 	}
254 	return (rval);
255 }
256 
257 /*
258  * Make all threads sleeping on the specified identifier runnable.
259  */
260 void
261 wakeup(ident)
262 	register void *ident;
263 {
264 
265 	sleepq_broadcast(ident, 0, -1);
266 }
267 
268 /*
269  * Make a thread sleeping on the specified identifier runnable.
270  * May wake more than one thread if a target thread is currently
271  * swapped out.
272  */
273 void
274 wakeup_one(ident)
275 	register void *ident;
276 {
277 
278 	sleepq_signal(ident, 0, -1);
279 }
280 
281 /*
282  * The machine independent parts of context switching.
283  */
284 void
285 mi_switch(int flags, struct thread *newtd)
286 {
287 	struct bintime new_switchtime;
288 	struct thread *td;
289 	struct proc *p;
290 
291 	mtx_assert(&sched_lock, MA_OWNED | MA_NOTRECURSED);
292 	td = curthread;			/* XXX */
293 	p = td->td_proc;		/* XXX */
294 	KASSERT(!TD_ON_RUNQ(td), ("mi_switch: called by old code"));
295 #ifdef INVARIANTS
296 	if (!TD_ON_LOCK(td) && !TD_IS_RUNNING(td))
297 		mtx_assert(&Giant, MA_NOTOWNED);
298 #endif
299 	KASSERT(td->td_critnest == 1 || (td->td_critnest == 2 &&
300 	    (td->td_flags & TDF_OWEPREEMPT) != 0 && (flags & SW_INVOL) != 0 &&
301 	    newtd == NULL),
302 	    ("mi_switch: switch in a critical section"));
303 	KASSERT((flags & (SW_INVOL | SW_VOL)) != 0,
304 	    ("mi_switch: switch must be voluntary or involuntary"));
305 
306 	if (flags & SW_VOL)
307 		p->p_stats->p_ru.ru_nvcsw++;
308 	else
309 		p->p_stats->p_ru.ru_nivcsw++;
310 
311 	/*
312 	 * Compute the amount of time during which the current
313 	 * process was running, and add that to its total so far.
314 	 */
315 	binuptime(&new_switchtime);
316 	bintime_add(&p->p_runtime, &new_switchtime);
317 	bintime_sub(&p->p_runtime, PCPU_PTR(switchtime));
318 
319 	td->td_generation++;	/* bump preempt-detect counter */
320 
321 	/*
322 	 * Don't perform context switches from the debugger.
323 	 */
324 	if (kdb_active) {
325 		mtx_unlock_spin(&sched_lock);
326 		kdb_backtrace();
327 		kdb_reenter();
328 		panic("%s: did not reenter debugger", __func__);
329 	}
330 
331 	/*
332 	 * Check if the process exceeds its cpu resource allocation.  If
333 	 * over max, arrange to kill the process in ast().
334 	 */
335 	if (p->p_cpulimit != RLIM_INFINITY &&
336 	    p->p_runtime.sec > p->p_cpulimit) {
337 		p->p_sflag |= PS_XCPU;
338 		td->td_flags |= TDF_ASTPENDING;
339 	}
340 
341 	/*
342 	 * Finish up stats for outgoing thread.
343 	 */
344 	cnt.v_swtch++;
345 	PCPU_SET(switchtime, new_switchtime);
346 	PCPU_SET(switchticks, ticks);
347 	CTR3(KTR_PROC, "mi_switch: old thread %p (pid %ld, %s)",
348 	    (void *)td, (long)p->p_pid, p->p_comm);
349 	if (td->td_proc->p_flag & P_SA)
350 		thread_switchout(td);
351 	sched_switch(td, newtd);
352 
353 	CTR3(KTR_PROC, "mi_switch: new thread %p (pid %ld, %s)",
354 	    (void *)td, (long)p->p_pid, p->p_comm);
355 
356 	/*
357 	 * If the last thread was exiting, finish cleaning it up.
358 	 */
359 	if ((td = PCPU_GET(deadthread))) {
360 		PCPU_SET(deadthread, NULL);
361 		thread_stash(td);
362 	}
363 }
364 
365 /*
366  * Change process state to be runnable,
367  * placing it on the run queue if it is in memory,
368  * and awakening the swapper if it isn't in memory.
369  */
370 void
371 setrunnable(struct thread *td)
372 {
373 	struct proc *p;
374 
375 	p = td->td_proc;
376 	mtx_assert(&sched_lock, MA_OWNED);
377 	switch (p->p_state) {
378 	case PRS_ZOMBIE:
379 		panic("setrunnable(1)");
380 	default:
381 		break;
382 	}
383 	switch (td->td_state) {
384 	case TDS_RUNNING:
385 	case TDS_RUNQ:
386 		return;
387 	case TDS_INHIBITED:
388 		/*
389 		 * If we are only inhibited because we are swapped out
390 		 * then arange to swap in this process. Otherwise just return.
391 		 */
392 		if (td->td_inhibitors != TDI_SWAPPED)
393 			return;
394 		/* XXX: intentional fall-through ? */
395 	case TDS_CAN_RUN:
396 		break;
397 	default:
398 		printf("state is 0x%x", td->td_state);
399 		panic("setrunnable(2)");
400 	}
401 	if ((p->p_sflag & PS_INMEM) == 0) {
402 		if ((p->p_sflag & PS_SWAPPINGIN) == 0) {
403 			p->p_sflag |= PS_SWAPINREQ;
404 			wakeup(&proc0);
405 		}
406 	} else
407 		sched_wakeup(td);
408 }
409 
410 /*
411  * Compute a tenex style load average of a quantity on
412  * 1, 5 and 15 minute intervals.
413  * XXXKSE   Needs complete rewrite when correct info is available.
414  * Completely Bogus.. only works with 1:1 (but compiles ok now :-)
415  */
416 static void
417 loadav(void *arg)
418 {
419 	int i, nrun;
420 	struct loadavg *avg;
421 
422 	nrun = sched_load();
423 	avg = &averunnable;
424 
425 	for (i = 0; i < 3; i++)
426 		avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
427 		    nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
428 
429 	/*
430 	 * Schedule the next update to occur after 5 seconds, but add a
431 	 * random variation to avoid synchronisation with processes that
432 	 * run at regular intervals.
433 	 */
434 	callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)),
435 	    loadav, NULL);
436 }
437 
438 static void
439 lboltcb(void *arg)
440 {
441 	wakeup(&lbolt);
442 	callout_reset(&lbolt_callout, hz, lboltcb, NULL);
443 }
444 
445 /* ARGSUSED */
446 static void
447 synch_setup(dummy)
448 	void *dummy;
449 {
450 	callout_init(&loadav_callout, CALLOUT_MPSAFE);
451 	callout_init(&lbolt_callout, CALLOUT_MPSAFE);
452 
453 	/* Kick off timeout driven events by calling first time. */
454 	loadav(NULL);
455 	lboltcb(NULL);
456 }
457 
458 /*
459  * General purpose yield system call
460  */
461 int
462 yield(struct thread *td, struct yield_args *uap)
463 {
464 	struct ksegrp *kg;
465 
466 	kg = td->td_ksegrp;
467 	mtx_assert(&Giant, MA_NOTOWNED);
468 	mtx_lock_spin(&sched_lock);
469 	sched_prio(td, PRI_MAX_TIMESHARE);
470 	mi_switch(SW_VOL, NULL);
471 	mtx_unlock_spin(&sched_lock);
472 	td->td_retval[0] = 0;
473 	return (0);
474 }
475