kern_synch.c revision 106180
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 * $FreeBSD: head/sys/kern/kern_synch.c 106180 2002-10-30 02:28:41Z davidxu $
40 */
41
42#include "opt_ddb.h"
43#include "opt_ktrace.h"
44
45#include <sys/param.h>
46#include <sys/systm.h>
47#include <sys/condvar.h>
48#include <sys/kernel.h>
49#include <sys/ktr.h>
50#include <sys/lock.h>
51#include <sys/mutex.h>
52#include <sys/proc.h>
53#include <sys/resourcevar.h>
54#include <sys/sched.h>
55#include <sys/signalvar.h>
56#include <sys/smp.h>
57#include <sys/sx.h>
58#include <sys/sysctl.h>
59#include <sys/sysproto.h>
60#include <sys/vmmeter.h>
61#ifdef DDB
62#include <ddb/ddb.h>
63#endif
64#ifdef KTRACE
65#include <sys/uio.h>
66#include <sys/ktrace.h>
67#endif
68
69#include <machine/cpu.h>
70
71static void sched_setup(void *dummy);
72SYSINIT(sched_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, sched_setup, NULL)
73
74int	hogticks;
75int	lbolt;
76
77static struct callout loadav_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
91static void	endtsleep(void *);
92static void	loadav(void *arg);
93
94/*
95 * We're only looking at 7 bits of the address; everything is
96 * aligned to 4, lots of things are aligned to greater powers
97 * of 2.  Shift right by 8, i.e. drop the bottom 256 worth.
98 */
99#define TABLESIZE	128
100static TAILQ_HEAD(slpquehead, thread) slpque[TABLESIZE];
101#define LOOKUP(x)	(((intptr_t)(x) >> 8) & (TABLESIZE - 1))
102
103void
104sleepinit(void)
105{
106	int i;
107
108	hogticks = (hz / 10) * 2;	/* Default only. */
109	for (i = 0; i < TABLESIZE; i++)
110		TAILQ_INIT(&slpque[i]);
111}
112
113/*
114 * General sleep call.  Suspends the current process until a wakeup is
115 * performed on the specified identifier.  The process will then be made
116 * runnable with the specified priority.  Sleeps at most timo/hz seconds
117 * (0 means no timeout).  If pri includes PCATCH flag, signals are checked
118 * before and after sleeping, else signals are not checked.  Returns 0 if
119 * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
120 * signal needs to be delivered, ERESTART is returned if the current system
121 * call should be restarted if possible, and EINTR is returned if the system
122 * call should be interrupted by the signal (return EINTR).
123 *
124 * The mutex argument is exited before the caller is suspended, and
125 * entered before msleep returns.  If priority includes the PDROP
126 * flag the mutex is not entered before returning.
127 */
128
129int
130msleep(ident, mtx, priority, wmesg, timo)
131	void *ident;
132	struct mtx *mtx;
133	int priority, timo;
134	const char *wmesg;
135{
136	struct thread *td = curthread;
137	struct proc *p = td->td_proc;
138	int sig, catch = priority & PCATCH;
139	int rval = 0;
140	WITNESS_SAVE_DECL(mtx);
141
142#ifdef KTRACE
143	if (KTRPOINT(td, KTR_CSW))
144		ktrcsw(1, 0);
145#endif
146	WITNESS_SLEEP(0, &mtx->mtx_object);
147	KASSERT(timo != 0 || mtx_owned(&Giant) || mtx != NULL,
148	    ("sleeping without a mutex"));
149	/*
150	 * If we are capable of async syscalls and there isn't already
151	 * another one ready to return, start a new thread
152	 * and queue it as ready to run. Note that there is danger here
153	 * because we need to make sure that we don't sleep allocating
154	 * the thread (recursion here might be bad).
155	 * Hence the TDF_INMSLEEP flag.
156	 */
157	if (p->p_flag & P_KSES) {
158		/*
159		 * Just don't bother if we are exiting
160		 * and not the exiting thread or thread was marked as
161		 * interrupted.
162		 */
163		if (catch &&
164		    (((p->p_flag & P_WEXIT) && (p->p_singlethread != td)) ||
165		     (td->td_flags & TDF_INTERRUPT))) {
166			td->td_flags &= ~TDF_INTERRUPT;
167			return (EINTR);
168		}
169		mtx_lock_spin(&sched_lock);
170		if ((td->td_flags & (TDF_UNBOUND|TDF_INMSLEEP)) ==
171		    TDF_UNBOUND) {
172			/*
173			 * Arrange for an upcall to be readied.
174			 * it will not actually happen until all
175			 * pending in-kernel work for this KSEGRP
176			 * has been done.
177			 */
178			/* Don't recurse here! */
179			td->td_flags |= TDF_INMSLEEP;
180			thread_schedule_upcall(td, td->td_kse);
181			td->td_flags &= ~TDF_INMSLEEP;
182		}
183	} else {
184		mtx_lock_spin(&sched_lock);
185	}
186	if (cold ) {
187		/*
188		 * During autoconfiguration, just give interrupts
189		 * a chance, then just return.
190		 * Don't run any other procs or panic below,
191		 * in case this is the idle process and already asleep.
192		 */
193		if (mtx != NULL && priority & PDROP)
194			mtx_unlock(mtx);
195		mtx_unlock_spin(&sched_lock);
196		return (0);
197	}
198
199	DROP_GIANT();
200
201	if (mtx != NULL) {
202		mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED);
203		WITNESS_SAVE(&mtx->mtx_object, mtx);
204		mtx_unlock(mtx);
205		if (priority & PDROP)
206			mtx = NULL;
207	}
208
209	KASSERT(p != NULL, ("msleep1"));
210	KASSERT(ident != NULL && TD_IS_RUNNING(td), ("msleep"));
211
212	CTR5(KTR_PROC, "msleep: thread %p (pid %d, %s) on %s (%p)",
213	    td, p->p_pid, p->p_comm, wmesg, ident);
214
215	td->td_wchan = ident;
216	td->td_wmesg = wmesg;
217	TAILQ_INSERT_TAIL(&slpque[LOOKUP(ident)], td, td_slpq);
218	TD_SET_ON_SLEEPQ(td);
219	if (timo)
220		callout_reset(&td->td_slpcallout, timo, endtsleep, td);
221	/*
222	 * We put ourselves on the sleep queue and start our timeout
223	 * before calling thread_suspend_check, as we could stop there, and
224	 * a wakeup or a SIGCONT (or both) could occur while we were stopped.
225	 * without resuming us, thus we must be ready for sleep
226	 * when cursig is called.  If the wakeup happens while we're
227	 * stopped, td->td_wchan will be 0 upon return from cursig.
228	 */
229	if (catch) {
230		CTR3(KTR_PROC, "msleep caught: thread %p (pid %d, %s)", td,
231		    p->p_pid, p->p_comm);
232		td->td_flags |= TDF_SINTR;
233		mtx_unlock_spin(&sched_lock);
234		PROC_LOCK(p);
235		sig = cursig(td);
236		if (sig == 0 && thread_suspend_check(1))
237			sig = SIGSTOP;
238		mtx_lock_spin(&sched_lock);
239		PROC_UNLOCK(p);
240		if (sig != 0) {
241			if (TD_ON_SLEEPQ(td))
242				unsleep(td);
243		} else if (!TD_ON_SLEEPQ(td))
244			catch = 0;
245	} else
246		sig = 0;
247
248	/*
249	 * Let the scheduler know we're about to voluntarily go to sleep.
250	 */
251	sched_sleep(td, priority & PRIMASK);
252
253	if (TD_ON_SLEEPQ(td)) {
254		p->p_stats->p_ru.ru_nvcsw++;
255		TD_SET_SLEEPING(td);
256		mi_switch();
257	}
258	/*
259	 * We're awake from voluntary sleep.
260	 */
261	CTR3(KTR_PROC, "msleep resume: thread %p (pid %d, %s)", td, p->p_pid,
262	    p->p_comm);
263	KASSERT(TD_IS_RUNNING(td), ("running but not TDS_RUNNING"));
264	td->td_flags &= ~TDF_SINTR;
265	if (td->td_flags & TDF_TIMEOUT) {
266		td->td_flags &= ~TDF_TIMEOUT;
267		if (sig == 0)
268			rval = EWOULDBLOCK;
269	} else if (td->td_flags & TDF_TIMOFAIL) {
270		td->td_flags &= ~TDF_TIMOFAIL;
271	} else if (timo && callout_stop(&td->td_slpcallout) == 0) {
272		/*
273		 * This isn't supposed to be pretty.  If we are here, then
274		 * the endtsleep() callout is currently executing on another
275		 * CPU and is either spinning on the sched_lock or will be
276		 * soon.  If we don't synchronize here, there is a chance
277		 * that this process may msleep() again before the callout
278		 * has a chance to run and the callout may end up waking up
279		 * the wrong msleep().  Yuck.
280		 */
281		TD_SET_SLEEPING(td);
282		p->p_stats->p_ru.ru_nivcsw++;
283		mi_switch();
284		td->td_flags &= ~TDF_TIMOFAIL;
285	}
286	if ((td->td_flags & TDF_INTERRUPT) && (priority & PCATCH) &&
287	    (rval == 0)) {
288		td->td_flags &= ~TDF_INTERRUPT;
289		rval = EINTR;
290	}
291	mtx_unlock_spin(&sched_lock);
292
293	if (rval == 0 && catch) {
294		PROC_LOCK(p);
295		/* XXX: shouldn't we always be calling cursig() */
296		if (sig != 0 || (sig = cursig(td))) {
297			if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
298				rval = EINTR;
299			else
300				rval = ERESTART;
301		}
302		PROC_UNLOCK(p);
303	}
304#ifdef KTRACE
305	if (KTRPOINT(td, KTR_CSW))
306		ktrcsw(0, 0);
307#endif
308	PICKUP_GIANT();
309	if (mtx != NULL) {
310		mtx_lock(mtx);
311		WITNESS_RESTORE(&mtx->mtx_object, mtx);
312	}
313	return (rval);
314}
315
316/*
317 * Implement timeout for msleep()
318 *
319 * If process hasn't been awakened (wchan non-zero),
320 * set timeout flag and undo the sleep.  If proc
321 * is stopped, just unsleep so it will remain stopped.
322 * MP-safe, called without the Giant mutex.
323 */
324static void
325endtsleep(arg)
326	void *arg;
327{
328	register struct thread *td = arg;
329
330	CTR3(KTR_PROC, "endtsleep: thread %p (pid %d, %s)",
331	    td, td->td_proc->p_pid, td->td_proc->p_comm);
332	mtx_lock_spin(&sched_lock);
333	/*
334	 * This is the other half of the synchronization with msleep()
335	 * described above.  If the TDS_TIMEOUT flag is set, we lost the
336	 * race and just need to put the process back on the runqueue.
337	 */
338	if (TD_ON_SLEEPQ(td)) {
339		TAILQ_REMOVE(&slpque[LOOKUP(td->td_wchan)], td, td_slpq);
340		TD_CLR_ON_SLEEPQ(td);
341		td->td_flags |= TDF_TIMEOUT;
342	} else {
343		td->td_flags |= TDF_TIMOFAIL;
344	}
345	TD_CLR_SLEEPING(td);
346	setrunnable(td);
347	mtx_unlock_spin(&sched_lock);
348}
349
350/*
351 * Abort a thread, as if an interrupt had occured.  Only abort
352 * interruptable waits (unfortunatly it isn't only safe to abort others).
353 * This is about identical to cv_abort().
354 * Think about merging them?
355 * Also, whatever the signal code does...
356 */
357void
358abortsleep(struct thread *td)
359{
360
361	mtx_assert(&sched_lock, MA_OWNED);
362	/*
363	 * If the TDF_TIMEOUT flag is set, just leave. A
364	 * timeout is scheduled anyhow.
365	 */
366	if ((td->td_flags & (TDF_TIMEOUT | TDF_SINTR)) == TDF_SINTR) {
367		if (TD_ON_SLEEPQ(td)) {
368			unsleep(td);
369			TD_CLR_SLEEPING(td);
370			setrunnable(td);
371		}
372	}
373}
374
375/*
376 * Remove a process from its wait queue
377 */
378void
379unsleep(struct thread *td)
380{
381
382	mtx_lock_spin(&sched_lock);
383	if (TD_ON_SLEEPQ(td)) {
384		TAILQ_REMOVE(&slpque[LOOKUP(td->td_wchan)], td, td_slpq);
385		TD_CLR_ON_SLEEPQ(td);
386	}
387	mtx_unlock_spin(&sched_lock);
388}
389
390/*
391 * Make all processes sleeping on the specified identifier runnable.
392 */
393void
394wakeup(ident)
395	register void *ident;
396{
397	register struct slpquehead *qp;
398	register struct thread *td;
399	struct thread *ntd;
400	struct proc *p;
401
402	mtx_lock_spin(&sched_lock);
403	qp = &slpque[LOOKUP(ident)];
404restart:
405	for (td = TAILQ_FIRST(qp); td != NULL; td = ntd) {
406		ntd = TAILQ_NEXT(td, td_slpq);
407		if (td->td_wchan == ident) {
408			unsleep(td);
409			TD_CLR_SLEEPING(td);
410			setrunnable(td);
411			p = td->td_proc;
412			CTR3(KTR_PROC,"wakeup: thread %p (pid %d, %s)",
413			    td, p->p_pid, p->p_comm);
414			goto restart;
415		}
416	}
417	mtx_unlock_spin(&sched_lock);
418}
419
420/*
421 * Make a process sleeping on the specified identifier runnable.
422 * May wake more than one process if a target process is currently
423 * swapped out.
424 */
425void
426wakeup_one(ident)
427	register void *ident;
428{
429	register struct slpquehead *qp;
430	register struct thread *td;
431	register struct proc *p;
432	struct thread *ntd;
433
434	mtx_lock_spin(&sched_lock);
435	qp = &slpque[LOOKUP(ident)];
436	for (td = TAILQ_FIRST(qp); td != NULL; td = ntd) {
437		ntd = TAILQ_NEXT(td, td_slpq);
438		if (td->td_wchan == ident) {
439			unsleep(td);
440			TD_CLR_SLEEPING(td);
441			setrunnable(td);
442			p = td->td_proc;
443			CTR3(KTR_PROC,"wakeup1: thread %p (pid %d, %s)",
444			    td, p->p_pid, p->p_comm);
445			break;
446		}
447	}
448	mtx_unlock_spin(&sched_lock);
449}
450
451/*
452 * The machine independent parts of mi_switch().
453 */
454void
455mi_switch(void)
456{
457	struct bintime new_switchtime;
458	struct thread *td = curthread;	/* XXX */
459	struct proc *p = td->td_proc;	/* XXX */
460	struct kse *ke = td->td_kse;
461	u_int sched_nest;
462
463	mtx_assert(&sched_lock, MA_OWNED | MA_NOTRECURSED);
464
465	KASSERT(!TD_ON_RUNQ(td), ("mi_switch: called by old code"));
466#ifdef INVARIANTS
467	if (!TD_ON_LOCK(td) &&
468	    !TD_ON_RUNQ(td) &&
469	    !TD_IS_RUNNING(td))
470		mtx_assert(&Giant, MA_NOTOWNED);
471#endif
472	KASSERT(td->td_critnest == 1,
473	    ("mi_switch: switch in a critical section"));
474
475	/*
476	 * Compute the amount of time during which the current
477	 * process was running, and add that to its total so far.
478	 */
479	binuptime(&new_switchtime);
480	bintime_add(&p->p_runtime, &new_switchtime);
481	bintime_sub(&p->p_runtime, PCPU_PTR(switchtime));
482
483#ifdef DDB
484	/*
485	 * Don't perform context switches from the debugger.
486	 */
487	if (db_active) {
488		mtx_unlock_spin(&sched_lock);
489		db_error("Context switches not allowed in the debugger.");
490	}
491#endif
492
493	/*
494	 * Check if the process exceeds its cpu resource allocation.  If
495	 * over max, arrange to kill the process in ast().
496	 */
497	if (p->p_cpulimit != RLIM_INFINITY &&
498	    p->p_runtime.sec > p->p_cpulimit) {
499		p->p_sflag |= PS_XCPU;
500		ke->ke_flags |= KEF_ASTPENDING;
501	}
502
503	/*
504	 * Finish up stats for outgoing thread.
505	 */
506	cnt.v_swtch++;
507	PCPU_SET(switchtime, new_switchtime);
508	CTR3(KTR_PROC, "mi_switch: old thread %p (pid %d, %s)", td, p->p_pid,
509	    p->p_comm);
510
511	sched_nest = sched_lock.mtx_recurse;
512	sched_switchout(td);
513
514	cpu_switch();		/* SHAZAM!!*/
515
516	sched_lock.mtx_recurse = sched_nest;
517	sched_lock.mtx_lock = (uintptr_t)td;
518	sched_switchin(td);
519
520	/*
521	 * Start setting up stats etc. for the incoming thread.
522	 * Similar code in fork_exit() is returned to by cpu_switch()
523	 * in the case of a new thread/process.
524	 */
525	CTR3(KTR_PROC, "mi_switch: new thread %p (pid %d, %s)", td, p->p_pid,
526	    p->p_comm);
527	if (PCPU_GET(switchtime.sec) == 0)
528		binuptime(PCPU_PTR(switchtime));
529	PCPU_SET(switchticks, ticks);
530
531	/*
532	 * Call the switchin function while still holding the scheduler lock
533	 * (used by the idlezero code and the general page-zeroing code)
534	 */
535	if (td->td_switchin)
536		td->td_switchin();
537}
538
539/*
540 * Change process state to be runnable,
541 * placing it on the run queue if it is in memory,
542 * and awakening the swapper if it isn't in memory.
543 */
544void
545setrunnable(struct thread *td)
546{
547	struct proc *p = td->td_proc;
548
549	mtx_assert(&sched_lock, MA_OWNED);
550	switch (p->p_state) {
551	case PRS_ZOMBIE:
552		panic("setrunnable(1)");
553	default:
554		break;
555	}
556	switch (td->td_state) {
557	case TDS_RUNNING:
558	case TDS_RUNQ:
559		return;
560	case TDS_INHIBITED:
561		/*
562		 * If we are only inhibited because we are swapped out
563		 * then arange to swap in this process. Otherwise just return.
564		 */
565		if (td->td_inhibitors != TDI_SWAPPED)
566			return;
567	case TDS_CAN_RUN:
568		break;
569	default:
570		printf("state is 0x%x", td->td_state);
571		panic("setrunnable(2)");
572	}
573	if ((p->p_sflag & PS_INMEM) == 0) {
574		if ((p->p_sflag & PS_SWAPPINGIN) == 0) {
575			p->p_sflag |= PS_SWAPINREQ;
576			wakeup(&proc0);
577		}
578	} else
579		sched_wakeup(td);
580}
581
582/*
583 * Compute a tenex style load average of a quantity on
584 * 1, 5 and 15 minute intervals.
585 * XXXKSE   Needs complete rewrite when correct info is available.
586 * Completely Bogus.. only works with 1:1 (but compiles ok now :-)
587 */
588static void
589loadav(void *arg)
590{
591	int i, nrun;
592	struct loadavg *avg;
593	struct proc *p;
594	struct thread *td;
595
596	avg = &averunnable;
597	sx_slock(&allproc_lock);
598	nrun = 0;
599	FOREACH_PROC_IN_SYSTEM(p) {
600		FOREACH_THREAD_IN_PROC(p, td) {
601			switch (td->td_state) {
602			case TDS_RUNQ:
603			case TDS_RUNNING:
604				if ((p->p_flag & P_NOLOAD) != 0)
605					goto nextproc;
606				nrun++; /* XXXKSE */
607			default:
608				break;
609			}
610nextproc:
611			continue;
612		}
613	}
614	sx_sunlock(&allproc_lock);
615	for (i = 0; i < 3; i++)
616		avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
617		    nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
618
619	/*
620	 * Schedule the next update to occur after 5 seconds, but add a
621	 * random variation to avoid synchronisation with processes that
622	 * run at regular intervals.
623	 */
624	callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)),
625	    loadav, NULL);
626}
627
628/* ARGSUSED */
629static void
630sched_setup(dummy)
631	void *dummy;
632{
633	callout_init(&loadav_callout, 0);
634
635	/* Kick off timeout driven events by calling first time. */
636	loadav(NULL);
637}
638
639/*
640 * General purpose yield system call
641 */
642int
643yield(struct thread *td, struct yield_args *uap)
644{
645	struct ksegrp *kg = td->td_ksegrp;
646
647	mtx_assert(&Giant, MA_NOTOWNED);
648	mtx_lock_spin(&sched_lock);
649	kg->kg_proc->p_stats->p_ru.ru_nvcsw++;
650	sched_prio(td, PRI_MAX_TIMESHARE);
651	mi_switch();
652	mtx_unlock_spin(&sched_lock);
653	td->td_retval[0] = 0;
654
655	return (0);
656}
657
658