kern_synch.c revision 126326
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 * 3. All advertising materials mentioning features or use of this software
19 *    must display the following acknowledgement:
20 *	This product includes software developed by the University of
21 *	California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 *    may be used to endorse or promote products derived from this software
24 *    without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * SUCH DAMAGE.
37 *
38 *	@(#)kern_synch.c	8.9 (Berkeley) 5/19/95
39 */
40
41#include <sys/cdefs.h>
42__FBSDID("$FreeBSD: head/sys/kern/kern_synch.c 126326 2004-02-27 18:52:44Z jhb $");
43
44#include "opt_ddb.h"
45#include "opt_ktrace.h"
46
47#include <sys/param.h>
48#include <sys/systm.h>
49#include <sys/condvar.h>
50#include <sys/kernel.h>
51#include <sys/ktr.h>
52#include <sys/lock.h>
53#include <sys/mutex.h>
54#include <sys/proc.h>
55#include <sys/resourcevar.h>
56#include <sys/sched.h>
57#include <sys/signalvar.h>
58#include <sys/sleepqueue.h>
59#include <sys/smp.h>
60#include <sys/sx.h>
61#include <sys/sysctl.h>
62#include <sys/sysproto.h>
63#include <sys/vmmeter.h>
64#ifdef DDB
65#include <ddb/ddb.h>
66#endif
67#ifdef KTRACE
68#include <sys/uio.h>
69#include <sys/ktrace.h>
70#endif
71
72#include <machine/cpu.h>
73
74static void synch_setup(void *dummy);
75SYSINIT(synch_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, synch_setup, NULL)
76
77int	hogticks;
78int	lbolt;
79
80static struct callout loadav_callout;
81static struct callout lbolt_callout;
82
83struct loadavg averunnable =
84	{ {0, 0, 0}, FSCALE };	/* load average, of runnable procs */
85/*
86 * Constants for averages over 1, 5, and 15 minutes
87 * when sampling at 5 second intervals.
88 */
89static fixpt_t cexp[3] = {
90	0.9200444146293232 * FSCALE,	/* exp(-1/12) */
91	0.9834714538216174 * FSCALE,	/* exp(-1/60) */
92	0.9944598480048967 * FSCALE,	/* exp(-1/180) */
93};
94
95/* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */
96static int      fscale __unused = FSCALE;
97SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, "");
98
99static void	loadav(void *arg);
100static void	lboltcb(void *arg);
101
102/*
103 * We're only looking at 7 bits of the address; everything is
104 * aligned to 4, lots of things are aligned to greater powers
105 * of 2.  Shift right by 8, i.e. drop the bottom 256 worth.
106 */
107#define TABLESIZE	128
108static TAILQ_HEAD(slpquehead, thread) slpque[TABLESIZE];
109#define LOOKUP(x)	(((intptr_t)(x) >> 8) & (TABLESIZE - 1))
110
111void
112sleepinit(void)
113{
114	int i;
115
116	hogticks = (hz / 10) * 2;	/* Default only. */
117	for (i = 0; i < TABLESIZE; i++)
118		TAILQ_INIT(&slpque[i]);
119	init_sleepqueues();
120}
121
122/*
123 * General sleep call.  Suspends the current process until a wakeup is
124 * performed on the specified identifier.  The process will then be made
125 * runnable with the specified priority.  Sleeps at most timo/hz seconds
126 * (0 means no timeout).  If pri includes PCATCH flag, signals are checked
127 * before and after sleeping, else signals are not checked.  Returns 0 if
128 * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
129 * signal needs to be delivered, ERESTART is returned if the current system
130 * call should be restarted if possible, and EINTR is returned if the system
131 * call should be interrupted by the signal (return EINTR).
132 *
133 * The mutex argument is exited before the caller is suspended, and
134 * entered before msleep returns.  If priority includes the PDROP
135 * flag the mutex is not entered before returning.
136 */
137
138int
139msleep(ident, mtx, priority, wmesg, timo)
140	void *ident;
141	struct mtx *mtx;
142	int priority, timo;
143	const char *wmesg;
144{
145	struct sleepqueue *sq;
146	struct thread *td;
147	struct proc *p;
148	int catch, rval, sig;
149	WITNESS_SAVE_DECL(mtx);
150
151	td = curthread;
152	p = td->td_proc;
153#ifdef KTRACE
154	if (KTRPOINT(td, KTR_CSW))
155		ktrcsw(1, 0);
156#endif
157	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, mtx == NULL ? NULL :
158	    &mtx->mtx_object, "Sleeping on \"%s\"", wmesg);
159	KASSERT(timo != 0 || mtx_owned(&Giant) || mtx != NULL,
160	    ("sleeping without a mutex"));
161	KASSERT(p != NULL, ("msleep1"));
162	KASSERT(ident != NULL && TD_IS_RUNNING(td), ("msleep"));
163
164	if (cold) {
165		/*
166		 * During autoconfiguration, just return;
167		 * don't run any other procs or panic below,
168		 * in case this is the idle process and already asleep.
169		 * XXX: this used to do "s = splhigh(); splx(safepri);
170		 * splx(s);" to give interrupts a chance, but there is
171		 * no way to give interrupts a chance now.
172		 */
173		if (mtx != NULL && priority & PDROP)
174			mtx_unlock(mtx);
175		return (0);
176	}
177	catch = priority & PCATCH;
178	rval = 0;
179
180	/*
181	 * If we are already on a sleep queue, then remove us from that
182	 * sleep queue first.  We have to do this to handle recursive
183	 * sleeps.
184	 */
185	if (TD_ON_SLEEPQ(td))
186		sleepq_remove(td, td->td_wchan);
187
188	sq = sleepq_lookup(ident);
189	mtx_lock_spin(&sched_lock);
190
191	/*
192	 * If we are capable of async syscalls and there isn't already
193	 * another one ready to return, start a new thread
194	 * and queue it as ready to run. Note that there is danger here
195	 * because we need to make sure that we don't sleep allocating
196	 * the thread (recursion here might be bad).
197	 */
198	if (p->p_flag & P_SA || p->p_numthreads > 1) {
199		/*
200		 * Just don't bother if we are exiting
201		 * and not the exiting thread or thread was marked as
202		 * interrupted.
203		 */
204		if (catch) {
205			if ((p->p_flag & P_WEXIT) && p->p_singlethread != td) {
206				mtx_unlock_spin(&sched_lock);
207				sleepq_release(ident);
208				return (EINTR);
209			}
210			if (td->td_flags & TDF_INTERRUPT) {
211				mtx_unlock_spin(&sched_lock);
212				sleepq_release(ident);
213				return (td->td_intrval);
214			}
215		}
216	}
217	mtx_unlock_spin(&sched_lock);
218	CTR5(KTR_PROC, "msleep: thread %p (pid %d, %s) on %s (%p)",
219	    td, p->p_pid, p->p_comm, wmesg, ident);
220
221	DROP_GIANT();
222	if (mtx != NULL) {
223		mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED);
224		WITNESS_SAVE(&mtx->mtx_object, mtx);
225		mtx_unlock(mtx);
226		if (priority & PDROP)
227			mtx = NULL;
228	}
229
230	/*
231	 * We put ourselves on the sleep queue and start our timeout
232	 * before calling thread_suspend_check, as we could stop there,
233	 * and a wakeup or a SIGCONT (or both) could occur while we were
234	 * stopped without resuming us.  Thus, we must be ready for sleep
235	 * when cursig() is called.  If the wakeup happens while we're
236	 * stopped, then td will no longer be on a sleep queue upon
237	 * return from cursig().
238	 */
239	sleepq_add(sq, ident, mtx, wmesg, 0);
240	if (timo)
241		sleepq_set_timeout(sq, ident, timo);
242	if (catch) {
243		sig = sleepq_catch_signals(ident);
244		if (sig == 0 && !TD_ON_SLEEPQ(td)) {
245			mtx_lock_spin(&sched_lock);
246			td->td_flags &= ~TDF_SINTR;
247			mtx_unlock_spin(&sched_lock);
248			catch = 0;
249		}
250	} else
251		sig = 0;
252
253	/*
254	 * Adjust this threads priority.
255	 *
256	 * XXX: Do we need to save priority in td_base_pri?
257	 */
258	mtx_lock_spin(&sched_lock);
259	sched_prio(td, priority & PRIMASK);
260	mtx_unlock_spin(&sched_lock);
261
262	if (timo && catch)
263		rval = sleepq_timedwait_sig(ident, sig != 0);
264	else if (timo)
265		rval = sleepq_timedwait(ident, sig != 0);
266	else if (catch)
267		rval = sleepq_wait_sig(ident);
268	else {
269		sleepq_wait(ident);
270		rval = 0;
271	}
272
273	/*
274	 * We're awake from voluntary sleep.
275	 */
276	if (rval == 0 && catch)
277		rval = sleepq_calc_signal_retval(sig);
278#ifdef KTRACE
279	if (KTRPOINT(td, KTR_CSW))
280		ktrcsw(0, 0);
281#endif
282	PICKUP_GIANT();
283	if (mtx != NULL) {
284		mtx_lock(mtx);
285		WITNESS_RESTORE(&mtx->mtx_object, mtx);
286	}
287	return (rval);
288}
289
290/*
291 * Make all processes sleeping on the specified identifier runnable.
292 */
293void
294wakeup(ident)
295	register void *ident;
296{
297
298	sleepq_broadcast(ident, 0, -1);
299}
300
301/*
302 * Make a process sleeping on the specified identifier runnable.
303 * May wake more than one process if a target process is currently
304 * swapped out.
305 */
306void
307wakeup_one(ident)
308	register void *ident;
309{
310
311	sleepq_signal(ident, 0, -1);
312}
313
314/*
315 * The machine independent parts of mi_switch().
316 */
317void
318mi_switch(int flags)
319{
320	struct bintime new_switchtime;
321	struct thread *td;
322	struct proc *p;
323
324	mtx_assert(&sched_lock, MA_OWNED | MA_NOTRECURSED);
325	td = curthread;			/* XXX */
326	p = td->td_proc;		/* XXX */
327	KASSERT(!TD_ON_RUNQ(td), ("mi_switch: called by old code"));
328#ifdef INVARIANTS
329	if (!TD_ON_LOCK(td) && !TD_IS_RUNNING(td))
330		mtx_assert(&Giant, MA_NOTOWNED);
331#endif
332	KASSERT(td->td_critnest == 1,
333	    ("mi_switch: switch in a critical section"));
334	KASSERT((flags & (SW_INVOL | SW_VOL)) != 0,
335	    ("mi_switch: switch must be voluntary or involuntary"));
336
337	if (flags & SW_VOL)
338		p->p_stats->p_ru.ru_nvcsw++;
339	else
340		p->p_stats->p_ru.ru_nivcsw++;
341	/*
342	 * Compute the amount of time during which the current
343	 * process was running, and add that to its total so far.
344	 */
345	binuptime(&new_switchtime);
346	bintime_add(&p->p_runtime, &new_switchtime);
347	bintime_sub(&p->p_runtime, PCPU_PTR(switchtime));
348
349	td->td_generation++;	/* bump preempt-detect counter */
350
351#ifdef DDB
352	/*
353	 * Don't perform context switches from the debugger.
354	 */
355	if (db_active) {
356		mtx_unlock_spin(&sched_lock);
357		db_print_backtrace();
358		db_error("Context switches not allowed in the debugger");
359	}
360#endif
361
362	/*
363	 * Check if the process exceeds its cpu resource allocation.  If
364	 * over max, arrange to kill the process in ast().
365	 */
366	if (p->p_cpulimit != RLIM_INFINITY &&
367	    p->p_runtime.sec > p->p_cpulimit) {
368		p->p_sflag |= PS_XCPU;
369		td->td_flags |= TDF_ASTPENDING;
370	}
371
372	/*
373	 * Finish up stats for outgoing thread.
374	 */
375	cnt.v_swtch++;
376	PCPU_SET(switchtime, new_switchtime);
377	PCPU_SET(switchticks, ticks);
378	CTR3(KTR_PROC, "mi_switch: old thread %p (pid %d, %s)", td, p->p_pid,
379	    p->p_comm);
380	if (td->td_proc->p_flag & P_SA)
381		thread_switchout(td);
382	sched_switch(td);
383
384	CTR3(KTR_PROC, "mi_switch: new thread %p (pid %d, %s)", td, p->p_pid,
385	    p->p_comm);
386
387	/*
388	 * If the last thread was exiting, finish cleaning it up.
389	 */
390	if ((td = PCPU_GET(deadthread))) {
391		PCPU_SET(deadthread, NULL);
392		thread_stash(td);
393	}
394}
395
396/*
397 * Change process state to be runnable,
398 * placing it on the run queue if it is in memory,
399 * and awakening the swapper if it isn't in memory.
400 */
401void
402setrunnable(struct thread *td)
403{
404	struct proc *p;
405
406	p = td->td_proc;
407	mtx_assert(&sched_lock, MA_OWNED);
408	switch (p->p_state) {
409	case PRS_ZOMBIE:
410		panic("setrunnable(1)");
411	default:
412		break;
413	}
414	switch (td->td_state) {
415	case TDS_RUNNING:
416	case TDS_RUNQ:
417		return;
418	case TDS_INHIBITED:
419		/*
420		 * If we are only inhibited because we are swapped out
421		 * then arange to swap in this process. Otherwise just return.
422		 */
423		if (td->td_inhibitors != TDI_SWAPPED)
424			return;
425		/* XXX: intentional fall-through ? */
426	case TDS_CAN_RUN:
427		break;
428	default:
429		printf("state is 0x%x", td->td_state);
430		panic("setrunnable(2)");
431	}
432	if ((p->p_sflag & PS_INMEM) == 0) {
433		if ((p->p_sflag & PS_SWAPPINGIN) == 0) {
434			p->p_sflag |= PS_SWAPINREQ;
435			wakeup(&proc0);
436		}
437	} else
438		sched_wakeup(td);
439}
440
441/*
442 * Compute a tenex style load average of a quantity on
443 * 1, 5 and 15 minute intervals.
444 * XXXKSE   Needs complete rewrite when correct info is available.
445 * Completely Bogus.. only works with 1:1 (but compiles ok now :-)
446 */
447static void
448loadav(void *arg)
449{
450	int i, nrun;
451	struct loadavg *avg;
452
453	nrun = sched_load();
454	avg = &averunnable;
455
456	for (i = 0; i < 3; i++)
457		avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
458		    nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
459
460	/*
461	 * Schedule the next update to occur after 5 seconds, but add a
462	 * random variation to avoid synchronisation with processes that
463	 * run at regular intervals.
464	 */
465	callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)),
466	    loadav, NULL);
467}
468
469static void
470lboltcb(void *arg)
471{
472	wakeup(&lbolt);
473	callout_reset(&lbolt_callout, hz, lboltcb, NULL);
474}
475
476/* ARGSUSED */
477static void
478synch_setup(dummy)
479	void *dummy;
480{
481	callout_init(&loadav_callout, 0);
482	callout_init(&lbolt_callout, CALLOUT_MPSAFE);
483
484	/* Kick off timeout driven events by calling first time. */
485	loadav(NULL);
486	lboltcb(NULL);
487}
488
489/*
490 * General purpose yield system call
491 */
492int
493yield(struct thread *td, struct yield_args *uap)
494{
495	struct ksegrp *kg;
496
497	kg = td->td_ksegrp;
498	mtx_assert(&Giant, MA_NOTOWNED);
499	mtx_lock_spin(&sched_lock);
500	sched_prio(td, PRI_MAX_TIMESHARE);
501	mi_switch(SW_VOL);
502	mtx_unlock_spin(&sched_lock);
503	td->td_retval[0] = 0;
504	return (0);
505}
506