kern_synch.c revision 134013
1274262Sdelphij/*-
2274262Sdelphij * Copyright (c) 1982, 1986, 1990, 1991, 1993
3166255Sdelphij *	The Regents of the University of California.  All rights reserved.
4166255Sdelphij * (c) UNIX System Laboratories, Inc.
5166255Sdelphij * All or some portions of this file are derived from material licensed
6166255Sdelphij * to the University of California by American Telephone and Telegraph
7166255Sdelphij * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8166255Sdelphij * the permission of UNIX System Laboratories, Inc.
9166255Sdelphij *
10166255Sdelphij * Redistribution and use in source and binary forms, with or without
11166255Sdelphij * modification, are permitted provided that the following conditions
12166255Sdelphij * are met:
13166255Sdelphij * 1. Redistributions of source code must retain the above copyright
14166255Sdelphij *    notice, this list of conditions and the following disclaimer.
15166255Sdelphij * 2. Redistributions in binary form must reproduce the above copyright
16166255Sdelphij *    notice, this list of conditions and the following disclaimer in the
17166255Sdelphij *    documentation and/or other materials provided with the distribution.
18166255Sdelphij * 4. Neither the name of the University nor the names of its contributors
19166255Sdelphij *    may be used to endorse or promote products derived from this software
20166255Sdelphij *    without specific prior written permission.
21166255Sdelphij *
22166255Sdelphij * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23274262Sdelphij * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24166255Sdelphij * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25166255Sdelphij * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26166255Sdelphij * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27274262Sdelphij * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28274262Sdelphij * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29218421Sgjb * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30166255Sdelphij * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31166255Sdelphij * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32166255Sdelphij * SUCH DAMAGE.
33274262Sdelphij *
34274262Sdelphij *	@(#)kern_synch.c	8.9 (Berkeley) 5/19/95
35274262Sdelphij */
36274262Sdelphij
37166255Sdelphij#include <sys/cdefs.h>
38166255Sdelphij__FBSDID("$FreeBSD: head/sys/kern/kern_synch.c 134013 2004-08-19 11:31:42Z jhb $");
39166255Sdelphij
40166255Sdelphij#include "opt_ktrace.h"
41166255Sdelphij
42166255Sdelphij#include <sys/param.h>
43166255Sdelphij#include <sys/systm.h>
44166255Sdelphij#include <sys/condvar.h>
45166255Sdelphij#include <sys/kdb.h>
46166255Sdelphij#include <sys/kernel.h>
47166255Sdelphij#include <sys/ktr.h>
48166255Sdelphij#include <sys/lock.h>
49166255Sdelphij#include <sys/mutex.h>
50166255Sdelphij#include <sys/proc.h>
51166255Sdelphij#include <sys/resourcevar.h>
52166255Sdelphij#include <sys/sched.h>
53166255Sdelphij#include <sys/signalvar.h>
54166255Sdelphij#include <sys/sleepqueue.h>
55166255Sdelphij#include <sys/smp.h>
56166255Sdelphij#include <sys/sx.h>
57166255Sdelphij#include <sys/sysctl.h>
58274262Sdelphij#include <sys/sysproto.h>
59274262Sdelphij#include <sys/vmmeter.h>
60274262Sdelphij#ifdef KTRACE
61274262Sdelphij#include <sys/uio.h>
62274262Sdelphij#include <sys/ktrace.h>
63274262Sdelphij#endif
64274262Sdelphij
65274262Sdelphij#include <machine/cpu.h>
66166255Sdelphij
67166255Sdelphijstatic void synch_setup(void *dummy);
68166255SdelphijSYSINIT(synch_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, synch_setup, NULL)
69166255Sdelphij
70166255Sdelphijint	hogticks;
71166255Sdelphijint	lbolt;
72166255Sdelphij
73166255Sdelphijstatic struct callout loadav_callout;
74166255Sdelphijstatic struct callout lbolt_callout;
75166255Sdelphij
76166255Sdelphijstruct loadavg averunnable =
77166255Sdelphij	{ {0, 0, 0}, FSCALE };	/* load average, of runnable procs */
78166255Sdelphij/*
79166255Sdelphij * Constants for averages over 1, 5, and 15 minutes
80166255Sdelphij * when sampling at 5 second intervals.
81166255Sdelphij */
82166255Sdelphijstatic fixpt_t cexp[3] = {
83166255Sdelphij	0.9200444146293232 * FSCALE,	/* exp(-1/12) */
84166255Sdelphij	0.9834714538216174 * FSCALE,	/* exp(-1/60) */
85166255Sdelphij	0.9944598480048967 * FSCALE,	/* exp(-1/180) */
86166255Sdelphij};
87166255Sdelphij
88166255Sdelphij/* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */
89166255Sdelphijstatic int      fscale __unused = FSCALE;
90166255SdelphijSYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, "");
91166255Sdelphij
92166255Sdelphijstatic void	loadav(void *arg);
93166255Sdelphijstatic void	lboltcb(void *arg);
94166255Sdelphij
95166255Sdelphijvoid
96166255Sdelphijsleepinit(void)
97166255Sdelphij{
98166255Sdelphij
99166255Sdelphij	hogticks = (hz / 10) * 2;	/* Default only. */
100166255Sdelphij	init_sleepqueues();
101274262Sdelphij}
102274262Sdelphij
103274262Sdelphij/*
104274262Sdelphij * General sleep call.  Suspends the current process until a wakeup is
105274262Sdelphij * performed on the specified identifier.  The process will then be made
106166255Sdelphij * runnable with the specified priority.  Sleeps at most timo/hz seconds
107166255Sdelphij * (0 means no timeout).  If pri includes PCATCH flag, signals are checked
108166255Sdelphij * before and after sleeping, else signals are not checked.  Returns 0 if
109166255Sdelphij * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
110166255Sdelphij * 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 */
118int
119msleep(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, flags;
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	if (catch) {
170		/*
171		 * Don't bother sleeping if we are exiting and not the exiting
172		 * thread or if our thread is marked as interrupted.
173		 */
174		mtx_lock_spin(&sched_lock);
175		rval = thread_sleep_check(td);
176		mtx_unlock_spin(&sched_lock);
177		if (rval != 0) {
178			sleepq_release(ident);
179			return (rval);
180		}
181	}
182	CTR5(KTR_PROC, "msleep: thread %p (pid %ld, %s) on %s (%p)",
183	    (void *)td, (long)p->p_pid, p->p_comm, wmesg, ident);
184
185	DROP_GIANT();
186	if (mtx != NULL) {
187		mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED);
188		WITNESS_SAVE(&mtx->mtx_object, mtx);
189		mtx_unlock(mtx);
190	}
191
192	/*
193	 * We put ourselves on the sleep queue and start our timeout
194	 * before calling thread_suspend_check, as we could stop there,
195	 * and a wakeup or a SIGCONT (or both) could occur while we were
196	 * stopped without resuming us.  Thus, we must be ready for sleep
197	 * when cursig() is called.  If the wakeup happens while we're
198	 * stopped, then td will no longer be on a sleep queue upon
199	 * return from cursig().
200	 */
201	flags = SLEEPQ_MSLEEP;
202	if (catch)
203		flags |= SLEEPQ_INTERRUPTIBLE;
204	sleepq_add(sq, ident, mtx, wmesg, flags);
205	if (timo)
206		sleepq_set_timeout(ident, timo);
207	if (catch) {
208		sig = sleepq_catch_signals(ident);
209	} else
210		sig = 0;
211
212	/*
213	 * Adjust this thread's priority.
214	 *
215	 * XXX: do we need to save priority in td_base_pri?
216	 */
217	mtx_lock_spin(&sched_lock);
218	sched_prio(td, priority & PRIMASK);
219	mtx_unlock_spin(&sched_lock);
220
221	if (timo && catch)
222		rval = sleepq_timedwait_sig(ident, sig != 0);
223	else if (timo)
224		rval = sleepq_timedwait(ident);
225	else if (catch)
226		rval = sleepq_wait_sig(ident);
227	else {
228		sleepq_wait(ident);
229		rval = 0;
230	}
231	if (rval == 0 && catch)
232		rval = sleepq_calc_signal_retval(sig);
233#ifdef KTRACE
234	if (KTRPOINT(td, KTR_CSW))
235		ktrcsw(0, 0);
236#endif
237	PICKUP_GIANT();
238	if (mtx != NULL && !(priority & PDROP)) {
239		mtx_lock(mtx);
240		WITNESS_RESTORE(&mtx->mtx_object, mtx);
241	}
242	return (rval);
243}
244
245/*
246 * Make all threads sleeping on the specified identifier runnable.
247 */
248void
249wakeup(ident)
250	register void *ident;
251{
252
253	sleepq_broadcast(ident, SLEEPQ_MSLEEP, -1);
254}
255
256/*
257 * Make a thread sleeping on the specified identifier runnable.
258 * May wake more than one thread if a target thread is currently
259 * swapped out.
260 */
261void
262wakeup_one(ident)
263	register void *ident;
264{
265
266	sleepq_signal(ident, SLEEPQ_MSLEEP, -1);
267}
268
269/*
270 * The machine independent parts of context switching.
271 */
272void
273mi_switch(int flags, struct thread *newtd)
274{
275	struct bintime new_switchtime;
276	struct thread *td;
277	struct proc *p;
278
279	mtx_assert(&sched_lock, MA_OWNED | MA_NOTRECURSED);
280	td = curthread;			/* XXX */
281	p = td->td_proc;		/* XXX */
282	KASSERT(!TD_ON_RUNQ(td), ("mi_switch: called by old code"));
283#ifdef INVARIANTS
284	if (!TD_ON_LOCK(td) && !TD_IS_RUNNING(td))
285		mtx_assert(&Giant, MA_NOTOWNED);
286#endif
287	KASSERT(td->td_critnest == 1 || (td->td_critnest == 2 &&
288	    (td->td_pflags & TDP_OWEPREEMPT) != 0 && (flags & SW_INVOL) != 0 &&
289	    newtd == NULL),
290	    ("mi_switch: switch in a critical section"));
291	KASSERT((flags & (SW_INVOL | SW_VOL)) != 0,
292	    ("mi_switch: switch must be voluntary or involuntary"));
293	KASSERT(newtd != curthread, ("mi_switch: preempting back to ourself"));
294
295	if (flags & SW_VOL)
296		p->p_stats->p_ru.ru_nvcsw++;
297	else
298		p->p_stats->p_ru.ru_nivcsw++;
299
300	/*
301	 * Compute the amount of time during which the current
302	 * process was running, and add that to its total so far.
303	 */
304	binuptime(&new_switchtime);
305	bintime_add(&p->p_runtime, &new_switchtime);
306	bintime_sub(&p->p_runtime, PCPU_PTR(switchtime));
307
308	td->td_generation++;	/* bump preempt-detect counter */
309
310	/*
311	 * Don't perform context switches from the debugger.
312	 */
313	if (kdb_active) {
314		mtx_unlock_spin(&sched_lock);
315		kdb_backtrace();
316		kdb_reenter();
317		panic("%s: did not reenter debugger", __func__);
318	}
319
320	/*
321	 * Check if the process exceeds its cpu resource allocation.  If
322	 * over max, arrange to kill the process in ast().
323	 */
324	if (p->p_cpulimit != RLIM_INFINITY &&
325	    p->p_runtime.sec > p->p_cpulimit) {
326		p->p_sflag |= PS_XCPU;
327		td->td_flags |= TDF_ASTPENDING;
328	}
329
330	/*
331	 * Finish up stats for outgoing thread.
332	 */
333	cnt.v_swtch++;
334	PCPU_SET(switchtime, new_switchtime);
335	PCPU_SET(switchticks, ticks);
336	CTR4(KTR_PROC, "mi_switch: old thread %p (kse %p, pid %ld, %s)",
337	    (void *)td, td->td_kse, (long)p->p_pid, p->p_comm);
338	if (td->td_proc->p_flag & P_SA)
339		thread_switchout(td);
340	sched_switch(td, newtd);
341
342	CTR4(KTR_PROC, "mi_switch: new thread %p (kse %p, pid %ld, %s)",
343	    (void *)td, td->td_kse, (long)p->p_pid, p->p_comm);
344
345	/*
346	 * If the last thread was exiting, finish cleaning it up.
347	 */
348	if ((td = PCPU_GET(deadthread))) {
349		PCPU_SET(deadthread, NULL);
350		thread_stash(td);
351	}
352}
353
354/*
355 * Change process state to be runnable,
356 * placing it on the run queue if it is in memory,
357 * and awakening the swapper if it isn't in memory.
358 */
359void
360setrunnable(struct thread *td)
361{
362	struct proc *p;
363
364	p = td->td_proc;
365	mtx_assert(&sched_lock, MA_OWNED);
366	switch (p->p_state) {
367	case PRS_ZOMBIE:
368		panic("setrunnable(1)");
369	default:
370		break;
371	}
372	switch (td->td_state) {
373	case TDS_RUNNING:
374	case TDS_RUNQ:
375		return;
376	case TDS_INHIBITED:
377		/*
378		 * If we are only inhibited because we are swapped out
379		 * then arange to swap in this process. Otherwise just return.
380		 */
381		if (td->td_inhibitors != TDI_SWAPPED)
382			return;
383		/* XXX: intentional fall-through ? */
384	case TDS_CAN_RUN:
385		break;
386	default:
387		printf("state is 0x%x", td->td_state);
388		panic("setrunnable(2)");
389	}
390	if ((p->p_sflag & PS_INMEM) == 0) {
391		if ((p->p_sflag & PS_SWAPPINGIN) == 0) {
392			p->p_sflag |= PS_SWAPINREQ;
393#ifndef SMP
394			/*
395			 * XXX: Disabled on SMP due to a LOR between
396			 * sched_lock and the sleepqueue chain locks.
397			 */
398			wakeup(&proc0);
399#endif
400		}
401	} else
402		sched_wakeup(td);
403}
404
405/*
406 * Compute a tenex style load average of a quantity on
407 * 1, 5 and 15 minute intervals.
408 * XXXKSE   Needs complete rewrite when correct info is available.
409 * Completely Bogus.. only works with 1:1 (but compiles ok now :-)
410 */
411static void
412loadav(void *arg)
413{
414	int i, nrun;
415	struct loadavg *avg;
416
417	nrun = sched_load();
418	avg = &averunnable;
419
420	for (i = 0; i < 3; i++)
421		avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
422		    nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
423
424	/*
425	 * Schedule the next update to occur after 5 seconds, but add a
426	 * random variation to avoid synchronisation with processes that
427	 * run at regular intervals.
428	 */
429	callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)),
430	    loadav, NULL);
431}
432
433static void
434lboltcb(void *arg)
435{
436	wakeup(&lbolt);
437	callout_reset(&lbolt_callout, hz, lboltcb, NULL);
438}
439
440/* ARGSUSED */
441static void
442synch_setup(dummy)
443	void *dummy;
444{
445	callout_init(&loadav_callout, CALLOUT_MPSAFE);
446	callout_init(&lbolt_callout, CALLOUT_MPSAFE);
447
448	/* Kick off timeout driven events by calling first time. */
449	loadav(NULL);
450	lboltcb(NULL);
451}
452
453/*
454 * General purpose yield system call
455 */
456int
457yield(struct thread *td, struct yield_args *uap)
458{
459	struct ksegrp *kg;
460
461	kg = td->td_ksegrp;
462	mtx_assert(&Giant, MA_NOTOWNED);
463	mtx_lock_spin(&sched_lock);
464	sched_prio(td, PRI_MAX_TIMESHARE);
465	mi_switch(SW_VOL, NULL);
466	mtx_unlock_spin(&sched_lock);
467	td->td_retval[0] = 0;
468	return (0);
469}
470