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