xref: /dragonfly/sys/kern/kern_synch.c (revision 279dd846)
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. 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  * $FreeBSD: src/sys/kern/kern_synch.c,v 1.87.2.6 2002/10/13 07:29:53 kbyanc Exp $
36  */
37 
38 #include "opt_ktrace.h"
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/proc.h>
43 #include <sys/kernel.h>
44 #include <sys/signalvar.h>
45 #include <sys/resourcevar.h>
46 #include <sys/vmmeter.h>
47 #include <sys/sysctl.h>
48 #include <sys/lock.h>
49 #include <sys/uio.h>
50 #ifdef KTRACE
51 #include <sys/ktrace.h>
52 #endif
53 #include <sys/ktr.h>
54 #include <sys/serialize.h>
55 
56 #include <sys/signal2.h>
57 #include <sys/thread2.h>
58 #include <sys/spinlock2.h>
59 #include <sys/mutex2.h>
60 
61 #include <machine/cpu.h>
62 #include <machine/smp.h>
63 
64 TAILQ_HEAD(tslpque, thread);
65 
66 static void sched_setup (void *dummy);
67 SYSINIT(sched_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, sched_setup, NULL);
68 
69 int	lbolt;
70 void	*lbolt_syncer;
71 int	sched_quantum;		/* Roundrobin scheduling quantum in ticks. */
72 int	ncpus;
73 int	ncpus2, ncpus2_shift, ncpus2_mask;	/* note: mask not cpumask_t */
74 int	ncpus_fit, ncpus_fit_mask;		/* note: mask not cpumask_t */
75 int	safepri;
76 int	tsleep_now_works;
77 int	tsleep_crypto_dump = 0;
78 
79 static struct callout loadav_callout;
80 static struct callout schedcpu_callout;
81 MALLOC_DEFINE(M_TSLEEP, "tslpque", "tsleep queues");
82 
83 #define __DEALL(ident)	__DEQUALIFY(void *, ident)
84 
85 #if !defined(KTR_TSLEEP)
86 #define KTR_TSLEEP	KTR_ALL
87 #endif
88 KTR_INFO_MASTER(tsleep);
89 KTR_INFO(KTR_TSLEEP, tsleep, tsleep_beg, 0, "tsleep enter %p", const volatile void *ident);
90 KTR_INFO(KTR_TSLEEP, tsleep, tsleep_end, 1, "tsleep exit");
91 KTR_INFO(KTR_TSLEEP, tsleep, wakeup_beg, 2, "wakeup enter %p", const volatile void *ident);
92 KTR_INFO(KTR_TSLEEP, tsleep, wakeup_end, 3, "wakeup exit");
93 KTR_INFO(KTR_TSLEEP, tsleep, ilockfail,  4, "interlock failed %p", const volatile void *ident);
94 
95 #define logtsleep1(name)	KTR_LOG(tsleep_ ## name)
96 #define logtsleep2(name, val)	KTR_LOG(tsleep_ ## name, val)
97 
98 struct loadavg averunnable =
99 	{ {0, 0, 0}, FSCALE };	/* load average, of runnable procs */
100 /*
101  * Constants for averages over 1, 5, and 15 minutes
102  * when sampling at 5 second intervals.
103  */
104 static fixpt_t cexp[3] = {
105 	0.9200444146293232 * FSCALE,	/* exp(-1/12) */
106 	0.9834714538216174 * FSCALE,	/* exp(-1/60) */
107 	0.9944598480048967 * FSCALE,	/* exp(-1/180) */
108 };
109 
110 static void	endtsleep (void *);
111 static void	loadav (void *arg);
112 static void	schedcpu (void *arg);
113 
114 /*
115  * Adjust the scheduler quantum.  The quantum is specified in microseconds.
116  * Note that 'tick' is in microseconds per tick.
117  */
118 static int
119 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
120 {
121 	int error, new_val;
122 
123 	new_val = sched_quantum * ustick;
124 	error = sysctl_handle_int(oidp, &new_val, 0, req);
125         if (error != 0 || req->newptr == NULL)
126 		return (error);
127 	if (new_val < ustick)
128 		return (EINVAL);
129 	sched_quantum = new_val / ustick;
130 	return (0);
131 }
132 
133 SYSCTL_PROC(_kern, OID_AUTO, quantum, CTLTYPE_INT|CTLFLAG_RW,
134 	0, sizeof sched_quantum, sysctl_kern_quantum, "I", "");
135 
136 static int pctcpu_decay = 10;
137 SYSCTL_INT(_kern, OID_AUTO, pctcpu_decay, CTLFLAG_RW, &pctcpu_decay, 0, "");
138 
139 /*
140  * kernel uses `FSCALE', userland (SHOULD) use kern.fscale
141  */
142 int     fscale __unused = FSCALE;	/* exported to systat */
143 SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, "");
144 
145 /*
146  * Recompute process priorities, once a second.
147  *
148  * Since the userland schedulers are typically event oriented, if the
149  * estcpu calculation at wakeup() time is not sufficient to make a
150  * process runnable relative to other processes in the system we have
151  * a 1-second recalc to help out.
152  *
153  * This code also allows us to store sysclock_t data in the process structure
154  * without fear of an overrun, since sysclock_t are guarenteed to hold
155  * several seconds worth of count.
156  *
157  * WARNING!  callouts can preempt normal threads.  However, they will not
158  * preempt a thread holding a spinlock so we *can* safely use spinlocks.
159  */
160 static int schedcpu_stats(struct proc *p, void *data __unused);
161 static int schedcpu_resource(struct proc *p, void *data __unused);
162 
163 static void
164 schedcpu(void *arg)
165 {
166 	allproc_scan(schedcpu_stats, NULL);
167 	allproc_scan(schedcpu_resource, NULL);
168 	wakeup((caddr_t)&lbolt);
169 	wakeup(lbolt_syncer);
170 	callout_reset(&schedcpu_callout, hz, schedcpu, NULL);
171 }
172 
173 /*
174  * General process statistics once a second
175  */
176 static int
177 schedcpu_stats(struct proc *p, void *data __unused)
178 {
179 	struct lwp *lp;
180 
181 	/*
182 	 * Threads may not be completely set up if process in SIDL state.
183 	 */
184 	if (p->p_stat == SIDL)
185 		return(0);
186 
187 	PHOLD(p);
188 	if (lwkt_trytoken(&p->p_token) == FALSE) {
189 		PRELE(p);
190 		return(0);
191 	}
192 
193 	p->p_swtime++;
194 	FOREACH_LWP_IN_PROC(lp, p) {
195 		if (lp->lwp_stat == LSSLEEP) {
196 			++lp->lwp_slptime;
197 			if (lp->lwp_slptime == 1)
198 				p->p_usched->uload_update(lp);
199 		}
200 
201 		/*
202 		 * Only recalculate processes that are active or have slept
203 		 * less then 2 seconds.  The schedulers understand this.
204 		 * Otherwise decay by 50% per second.
205 		 */
206 		if (lp->lwp_slptime <= 1) {
207 			p->p_usched->recalculate(lp);
208 		} else {
209 			int decay;
210 
211 			decay = pctcpu_decay;
212 			cpu_ccfence();
213 			if (decay <= 1)
214 				decay = 1;
215 			if (decay > 100)
216 				decay = 100;
217 			lp->lwp_pctcpu = (lp->lwp_pctcpu * (decay - 1)) / decay;
218 		}
219 	}
220 	lwkt_reltoken(&p->p_token);
221 	lwkt_yield();
222 	PRELE(p);
223 	return(0);
224 }
225 
226 /*
227  * Resource checks.  XXX break out since ksignal/killproc can block,
228  * limiting us to one process killed per second.  There is probably
229  * a better way.
230  */
231 static int
232 schedcpu_resource(struct proc *p, void *data __unused)
233 {
234 	u_int64_t ttime;
235 	struct lwp *lp;
236 
237 	if (p->p_stat == SIDL)
238 		return(0);
239 
240 	PHOLD(p);
241 	if (lwkt_trytoken(&p->p_token) == FALSE) {
242 		PRELE(p);
243 		return(0);
244 	}
245 
246 	if (p->p_stat == SZOMB || p->p_limit == NULL) {
247 		lwkt_reltoken(&p->p_token);
248 		PRELE(p);
249 		return(0);
250 	}
251 
252 	ttime = 0;
253 	FOREACH_LWP_IN_PROC(lp, p) {
254 		/*
255 		 * We may have caught an lp in the middle of being
256 		 * created, lwp_thread can be NULL.
257 		 */
258 		if (lp->lwp_thread) {
259 			ttime += lp->lwp_thread->td_sticks;
260 			ttime += lp->lwp_thread->td_uticks;
261 		}
262 	}
263 
264 	switch(plimit_testcpulimit(p->p_limit, ttime)) {
265 	case PLIMIT_TESTCPU_KILL:
266 		killproc(p, "exceeded maximum CPU limit");
267 		break;
268 	case PLIMIT_TESTCPU_XCPU:
269 		if ((p->p_flags & P_XCPU) == 0) {
270 			p->p_flags |= P_XCPU;
271 			ksignal(p, SIGXCPU);
272 		}
273 		break;
274 	default:
275 		break;
276 	}
277 	lwkt_reltoken(&p->p_token);
278 	lwkt_yield();
279 	PRELE(p);
280 	return(0);
281 }
282 
283 /*
284  * This is only used by ps.  Generate a cpu percentage use over
285  * a period of one second.
286  */
287 void
288 updatepcpu(struct lwp *lp, int cpticks, int ttlticks)
289 {
290 	fixpt_t acc;
291 	int remticks;
292 
293 	acc = (cpticks << FSHIFT) / ttlticks;
294 	if (ttlticks >= ESTCPUFREQ) {
295 		lp->lwp_pctcpu = acc;
296 	} else {
297 		remticks = ESTCPUFREQ - ttlticks;
298 		lp->lwp_pctcpu = (acc * ttlticks + lp->lwp_pctcpu * remticks) /
299 				ESTCPUFREQ;
300 	}
301 }
302 
303 /*
304  * tsleep/wakeup hash table parameters.  Try to find the sweet spot for
305  * like addresses being slept on.
306  */
307 #define TABLESIZE	4001
308 #define LOOKUP(x)	(((u_int)(uintptr_t)(x)) % TABLESIZE)
309 
310 static cpumask_t slpque_cpumasks[TABLESIZE];
311 
312 /*
313  * General scheduler initialization.  We force a reschedule 25 times
314  * a second by default.  Note that cpu0 is initialized in early boot and
315  * cannot make any high level calls.
316  *
317  * Each cpu has its own sleep queue.
318  */
319 void
320 sleep_gdinit(globaldata_t gd)
321 {
322 	static struct tslpque slpque_cpu0[TABLESIZE];
323 	int i;
324 
325 	if (gd->gd_cpuid == 0) {
326 		sched_quantum = (hz + 24) / 25;
327 		gd->gd_tsleep_hash = slpque_cpu0;
328 	} else {
329 		gd->gd_tsleep_hash = kmalloc(sizeof(slpque_cpu0),
330 					    M_TSLEEP, M_WAITOK | M_ZERO);
331 	}
332 	for (i = 0; i < TABLESIZE; ++i)
333 		TAILQ_INIT(&gd->gd_tsleep_hash[i]);
334 }
335 
336 /*
337  * This is a dandy function that allows us to interlock tsleep/wakeup
338  * operations with unspecified upper level locks, such as lockmgr locks,
339  * simply by holding a critical section.  The sequence is:
340  *
341  *	(acquire upper level lock)
342  *	tsleep_interlock(blah)
343  *	(release upper level lock)
344  *	tsleep(blah, ...)
345  *
346  * Basically this functions queues us on the tsleep queue without actually
347  * descheduling us.  When tsleep() is later called with PINTERLOCK it
348  * assumes the thread was already queued, otherwise it queues it there.
349  *
350  * Thus it is possible to receive the wakeup prior to going to sleep and
351  * the race conditions are covered.
352  */
353 static __inline void
354 _tsleep_interlock(globaldata_t gd, const volatile void *ident, int flags)
355 {
356 	thread_t td = gd->gd_curthread;
357 	int id;
358 
359 	crit_enter_quick(td);
360 	if (td->td_flags & TDF_TSLEEPQ) {
361 		id = LOOKUP(td->td_wchan);
362 		TAILQ_REMOVE(&gd->gd_tsleep_hash[id], td, td_sleepq);
363 		if (TAILQ_FIRST(&gd->gd_tsleep_hash[id]) == NULL) {
364 			ATOMIC_CPUMASK_NANDBIT(slpque_cpumasks[id],
365 					       gd->gd_cpuid);
366 		}
367 	} else {
368 		td->td_flags |= TDF_TSLEEPQ;
369 	}
370 	id = LOOKUP(ident);
371 	TAILQ_INSERT_TAIL(&gd->gd_tsleep_hash[id], td, td_sleepq);
372 	ATOMIC_CPUMASK_ORBIT(slpque_cpumasks[id], gd->gd_cpuid);
373 	td->td_wchan = ident;
374 	td->td_wdomain = flags & PDOMAIN_MASK;
375 	crit_exit_quick(td);
376 }
377 
378 void
379 tsleep_interlock(const volatile void *ident, int flags)
380 {
381 	_tsleep_interlock(mycpu, ident, flags);
382 }
383 
384 /*
385  * Remove thread from sleepq.  Must be called with a critical section held.
386  * The thread must not be migrating.
387  */
388 static __inline void
389 _tsleep_remove(thread_t td)
390 {
391 	globaldata_t gd = mycpu;
392 	int id;
393 
394 	KKASSERT(td->td_gd == gd && IN_CRITICAL_SECT(td));
395 	KKASSERT((td->td_flags & TDF_MIGRATING) == 0);
396 	if (td->td_flags & TDF_TSLEEPQ) {
397 		td->td_flags &= ~TDF_TSLEEPQ;
398 		id = LOOKUP(td->td_wchan);
399 		TAILQ_REMOVE(&gd->gd_tsleep_hash[id], td, td_sleepq);
400 		if (TAILQ_FIRST(&gd->gd_tsleep_hash[id]) == NULL) {
401 			ATOMIC_CPUMASK_NANDBIT(slpque_cpumasks[id],
402 					       gd->gd_cpuid);
403 		}
404 		td->td_wchan = NULL;
405 		td->td_wdomain = 0;
406 	}
407 }
408 
409 void
410 tsleep_remove(thread_t td)
411 {
412 	_tsleep_remove(td);
413 }
414 
415 /*
416  * General sleep call.  Suspends the current process until a wakeup is
417  * performed on the specified identifier.  The process will then be made
418  * runnable with the specified priority.  Sleeps at most timo/hz seconds
419  * (0 means no timeout).  If flags includes PCATCH flag, signals are checked
420  * before and after sleeping, else signals are not checked.  Returns 0 if
421  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
422  * signal needs to be delivered, ERESTART is returned if the current system
423  * call should be restarted if possible, and EINTR is returned if the system
424  * call should be interrupted by the signal (return EINTR).
425  *
426  * Note that if we are a process, we release_curproc() before messing with
427  * the LWKT scheduler.
428  *
429  * During autoconfiguration or after a panic, a sleep will simply
430  * lower the priority briefly to allow interrupts, then return.
431  *
432  * WARNING!  This code can't block (short of switching away), or bad things
433  *           will happen.  No getting tokens, no blocking locks, etc.
434  */
435 int
436 tsleep(const volatile void *ident, int flags, const char *wmesg, int timo)
437 {
438 	struct thread *td = curthread;
439 	struct lwp *lp = td->td_lwp;
440 	struct proc *p = td->td_proc;		/* may be NULL */
441 	globaldata_t gd;
442 	int sig;
443 	int catch;
444 	int error;
445 	int oldpri;
446 	struct callout thandle;
447 
448 	/*
449 	 * Currently a severe hack.  Make sure any delayed wakeups
450 	 * are flushed before we sleep or we might deadlock on whatever
451 	 * event we are sleeping on.
452 	 */
453 	if (td->td_flags & TDF_DELAYED_WAKEUP)
454 		wakeup_end_delayed();
455 
456 	/*
457 	 * NOTE: removed KTRPOINT, it could cause races due to blocking
458 	 * even in stable.  Just scrap it for now.
459 	 */
460 	if (!tsleep_crypto_dump && (tsleep_now_works == 0 || panicstr)) {
461 		/*
462 		 * After a panic, or before we actually have an operational
463 		 * softclock, just give interrupts a chance, then just return;
464 		 *
465 		 * don't run any other procs or panic below,
466 		 * in case this is the idle process and already asleep.
467 		 */
468 		splz();
469 		oldpri = td->td_pri;
470 		lwkt_setpri_self(safepri);
471 		lwkt_switch();
472 		lwkt_setpri_self(oldpri);
473 		return (0);
474 	}
475 	logtsleep2(tsleep_beg, ident);
476 	gd = td->td_gd;
477 	KKASSERT(td != &gd->gd_idlethread);	/* you must be kidding! */
478 	td->td_wakefromcpu = -1;		/* overwritten by _wakeup */
479 
480 	/*
481 	 * NOTE: all of this occurs on the current cpu, including any
482 	 * callout-based wakeups, so a critical section is a sufficient
483 	 * interlock.
484 	 *
485 	 * The entire sequence through to where we actually sleep must
486 	 * run without breaking the critical section.
487 	 */
488 	catch = flags & PCATCH;
489 	error = 0;
490 	sig = 0;
491 
492 	crit_enter_quick(td);
493 
494 	KASSERT(ident != NULL, ("tsleep: no ident"));
495 	KASSERT(lp == NULL ||
496 		lp->lwp_stat == LSRUN ||	/* Obvious */
497 		lp->lwp_stat == LSSTOP,		/* Set in tstop */
498 		("tsleep %p %s %d",
499 			ident, wmesg, lp->lwp_stat));
500 
501 	/*
502 	 * We interlock the sleep queue if the caller has not already done
503 	 * it for us.  This must be done before we potentially acquire any
504 	 * tokens or we can loose the wakeup.
505 	 */
506 	if ((flags & PINTERLOCKED) == 0) {
507 		_tsleep_interlock(gd, ident, flags);
508 	}
509 
510 	/*
511 	 * Setup for the current process (if this is a process).  We must
512 	 * interlock with lwp_token to avoid remote wakeup races via
513 	 * setrunnable()
514 	 */
515 	if (lp) {
516 		lwkt_gettoken(&lp->lwp_token);
517 		if (catch) {
518 			/*
519 			 * Early termination if PCATCH was set and a
520 			 * signal is pending, interlocked with the
521 			 * critical section.
522 			 *
523 			 * Early termination only occurs when tsleep() is
524 			 * entered while in a normal LSRUN state.
525 			 */
526 			if ((sig = CURSIG(lp)) != 0)
527 				goto resume;
528 
529 			/*
530 			 * Causes ksignal to wake us up if a signal is
531 			 * received (interlocked with p->p_token).
532 			 */
533 			lp->lwp_flags |= LWP_SINTR;
534 		}
535 	} else {
536 		KKASSERT(p == NULL);
537 	}
538 
539 	/*
540 	 * Make sure the current process has been untangled from
541 	 * the userland scheduler and initialize slptime to start
542 	 * counting.
543 	 *
544 	 * NOTE: td->td_wakefromcpu is pre-set by the release function
545 	 *	 for the dfly scheduler, and then adjusted by _wakeup()
546 	 */
547 	if (lp) {
548 		p->p_usched->release_curproc(lp);
549 		lp->lwp_slptime = 0;
550 	}
551 
552 	/*
553 	 * If the interlocked flag is set but our cpu bit in the slpqueue
554 	 * is no longer set, then a wakeup was processed inbetween the
555 	 * tsleep_interlock() (ours or the callers), and here.  This can
556 	 * occur under numerous circumstances including when we release the
557 	 * current process.
558 	 *
559 	 * Extreme loads can cause the sending of an IPI (e.g. wakeup()'s)
560 	 * to process incoming IPIs, thus draining incoming wakeups.
561 	 */
562 	if ((td->td_flags & TDF_TSLEEPQ) == 0) {
563 		logtsleep2(ilockfail, ident);
564 		goto resume;
565 	}
566 
567 	/*
568 	 * scheduling is blocked while in a critical section.  Coincide
569 	 * the descheduled-by-tsleep flag with the descheduling of the
570 	 * lwkt.
571 	 *
572 	 * The timer callout is localized on our cpu and interlocked by
573 	 * our critical section.
574 	 */
575 	lwkt_deschedule_self(td);
576 	td->td_flags |= TDF_TSLEEP_DESCHEDULED;
577 	td->td_wmesg = wmesg;
578 
579 	/*
580 	 * Setup the timeout, if any.  The timeout is only operable while
581 	 * the thread is flagged descheduled.
582 	 */
583 	KKASSERT((td->td_flags & TDF_TIMEOUT) == 0);
584 	if (timo) {
585 		callout_init_mp(&thandle);
586 		callout_reset(&thandle, timo, endtsleep, td);
587 	}
588 
589 	/*
590 	 * Beddy bye bye.
591 	 */
592 	if (lp) {
593 		/*
594 		 * Ok, we are sleeping.  Place us in the SSLEEP state.
595 		 */
596 		KKASSERT((lp->lwp_mpflags & LWP_MP_ONRUNQ) == 0);
597 
598 		/*
599 		 * tstop() sets LSSTOP, so don't fiddle with that.
600 		 */
601 		if (lp->lwp_stat != LSSTOP)
602 			lp->lwp_stat = LSSLEEP;
603 		lp->lwp_ru.ru_nvcsw++;
604 		p->p_usched->uload_update(lp);
605 		lwkt_switch();
606 
607 		/*
608 		 * And when we are woken up, put us back in LSRUN.  If we
609 		 * slept for over a second, recalculate our estcpu.
610 		 */
611 		lp->lwp_stat = LSRUN;
612 		if (lp->lwp_slptime) {
613 			p->p_usched->uload_update(lp);
614 			p->p_usched->recalculate(lp);
615 		}
616 		lp->lwp_slptime = 0;
617 	} else {
618 		lwkt_switch();
619 	}
620 
621 	/*
622 	 * Make sure we haven't switched cpus while we were asleep.  It's
623 	 * not supposed to happen.  Cleanup our temporary flags.
624 	 */
625 	KKASSERT(gd == td->td_gd);
626 
627 	/*
628 	 * Cleanup the timeout.  If the timeout has already occured thandle
629 	 * has already been stopped, otherwise stop thandle.  If the timeout
630 	 * is running (the callout thread must be blocked trying to get
631 	 * lwp_token) then wait for us to get scheduled.
632 	 */
633 	if (timo) {
634 		while (td->td_flags & TDF_TIMEOUT_RUNNING) {
635 			lwkt_deschedule_self(td);
636 			td->td_wmesg = "tsrace";
637 			lwkt_switch();
638 			kprintf("td %p %s: timeout race\n", td, td->td_comm);
639 		}
640 		if (td->td_flags & TDF_TIMEOUT) {
641 			td->td_flags &= ~TDF_TIMEOUT;
642 			error = EWOULDBLOCK;
643 		} else {
644 			/* does not block when on same cpu */
645 			callout_stop(&thandle);
646 		}
647 	}
648 	td->td_flags &= ~TDF_TSLEEP_DESCHEDULED;
649 
650 	/*
651 	 * Make sure we have been removed from the sleepq.  In most
652 	 * cases this will have been done for us already but it is
653 	 * possible for a scheduling IPI to be in-flight from a
654 	 * previous tsleep/tsleep_interlock() or due to a straight-out
655 	 * call to lwkt_schedule() (in the case of an interrupt thread),
656 	 * causing a spurious wakeup.
657 	 */
658 	_tsleep_remove(td);
659 	td->td_wmesg = NULL;
660 
661 	/*
662 	 * Figure out the correct error return.  If interrupted by a
663 	 * signal we want to return EINTR or ERESTART.
664 	 */
665 resume:
666 	if (lp) {
667 		if (catch && error == 0) {
668 			if (sig != 0 || (sig = CURSIG(lp))) {
669 				if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
670 					error = EINTR;
671 				else
672 					error = ERESTART;
673 			}
674 		}
675 		lp->lwp_flags &= ~LWP_SINTR;
676 		lwkt_reltoken(&lp->lwp_token);
677 	}
678 	logtsleep1(tsleep_end);
679 	crit_exit_quick(td);
680 	return (error);
681 }
682 
683 /*
684  * Interlocked spinlock sleep.  An exclusively held spinlock must
685  * be passed to ssleep().  The function will atomically release the
686  * spinlock and tsleep on the ident, then reacquire the spinlock and
687  * return.
688  *
689  * This routine is fairly important along the critical path, so optimize it
690  * heavily.
691  */
692 int
693 ssleep(const volatile void *ident, struct spinlock *spin, int flags,
694        const char *wmesg, int timo)
695 {
696 	globaldata_t gd = mycpu;
697 	int error;
698 
699 	_tsleep_interlock(gd, ident, flags);
700 	spin_unlock_quick(gd, spin);
701 	error = tsleep(ident, flags | PINTERLOCKED, wmesg, timo);
702 	_spin_lock_quick(gd, spin, wmesg);
703 
704 	return (error);
705 }
706 
707 int
708 lksleep(const volatile void *ident, struct lock *lock, int flags,
709 	const char *wmesg, int timo)
710 {
711 	globaldata_t gd = mycpu;
712 	int error;
713 
714 	_tsleep_interlock(gd, ident, flags);
715 	lockmgr(lock, LK_RELEASE);
716 	error = tsleep(ident, flags | PINTERLOCKED, wmesg, timo);
717 	lockmgr(lock, LK_EXCLUSIVE);
718 
719 	return (error);
720 }
721 
722 /*
723  * Interlocked mutex sleep.  An exclusively held mutex must be passed
724  * to mtxsleep().  The function will atomically release the mutex
725  * and tsleep on the ident, then reacquire the mutex and return.
726  */
727 int
728 mtxsleep(const volatile void *ident, struct mtx *mtx, int flags,
729 	 const char *wmesg, int timo)
730 {
731 	globaldata_t gd = mycpu;
732 	int error;
733 
734 	_tsleep_interlock(gd, ident, flags);
735 	mtx_unlock(mtx);
736 	error = tsleep(ident, flags | PINTERLOCKED, wmesg, timo);
737 	mtx_lock_ex_quick(mtx);
738 
739 	return (error);
740 }
741 
742 /*
743  * Interlocked serializer sleep.  An exclusively held serializer must
744  * be passed to zsleep().  The function will atomically release
745  * the serializer and tsleep on the ident, then reacquire the serializer
746  * and return.
747  */
748 int
749 zsleep(const volatile void *ident, struct lwkt_serialize *slz, int flags,
750        const char *wmesg, int timo)
751 {
752 	globaldata_t gd = mycpu;
753 	int ret;
754 
755 	ASSERT_SERIALIZED(slz);
756 
757 	_tsleep_interlock(gd, ident, flags);
758 	lwkt_serialize_exit(slz);
759 	ret = tsleep(ident, flags | PINTERLOCKED, wmesg, timo);
760 	lwkt_serialize_enter(slz);
761 
762 	return ret;
763 }
764 
765 /*
766  * Directly block on the LWKT thread by descheduling it.  This
767  * is much faster then tsleep(), but the only legal way to wake
768  * us up is to directly schedule the thread.
769  *
770  * Setting TDF_SINTR will cause new signals to directly schedule us.
771  *
772  * This routine must be called while in a critical section.
773  */
774 int
775 lwkt_sleep(const char *wmesg, int flags)
776 {
777 	thread_t td = curthread;
778 	int sig;
779 
780 	if ((flags & PCATCH) == 0 || td->td_lwp == NULL) {
781 		td->td_flags |= TDF_BLOCKED;
782 		td->td_wmesg = wmesg;
783 		lwkt_deschedule_self(td);
784 		lwkt_switch();
785 		td->td_wmesg = NULL;
786 		td->td_flags &= ~TDF_BLOCKED;
787 		return(0);
788 	}
789 	if ((sig = CURSIG(td->td_lwp)) != 0) {
790 		if (SIGISMEMBER(td->td_proc->p_sigacts->ps_sigintr, sig))
791 			return(EINTR);
792 		else
793 			return(ERESTART);
794 
795 	}
796 	td->td_flags |= TDF_BLOCKED | TDF_SINTR;
797 	td->td_wmesg = wmesg;
798 	lwkt_deschedule_self(td);
799 	lwkt_switch();
800 	td->td_flags &= ~(TDF_BLOCKED | TDF_SINTR);
801 	td->td_wmesg = NULL;
802 	return(0);
803 }
804 
805 /*
806  * Implement the timeout for tsleep.
807  *
808  * This type of callout timeout is scheduled on the same cpu the process
809  * is sleeping on.  Also, at the moment, the MP lock is held.
810  */
811 static void
812 endtsleep(void *arg)
813 {
814 	thread_t td = arg;
815 	struct lwp *lp;
816 
817 	/*
818 	 * We are going to have to get the lwp_token, which means we might
819 	 * block.  This can race a tsleep getting woken up by other means
820 	 * so set TDF_TIMEOUT_RUNNING to force the tsleep to wait for our
821 	 * processing to complete (sorry tsleep!).
822 	 *
823 	 * We can safely set td_flags because td MUST be on the same cpu
824 	 * as we are.
825 	 */
826 	KKASSERT(td->td_gd == mycpu);
827 	crit_enter();
828 	td->td_flags |= TDF_TIMEOUT_RUNNING | TDF_TIMEOUT;
829 
830 	/*
831 	 * This can block but TDF_TIMEOUT_RUNNING will prevent the thread
832 	 * from exiting the tsleep on us.  The flag is interlocked by virtue
833 	 * of lp being on the same cpu as we are.
834 	 */
835 	if ((lp = td->td_lwp) != NULL)
836 		lwkt_gettoken(&lp->lwp_token);
837 
838 	KKASSERT(td->td_flags & TDF_TSLEEP_DESCHEDULED);
839 
840 	if (lp) {
841 		/*
842 		 * callout timer should never be set in tstop() because
843 		 * it passes a timeout of 0.
844 		 */
845 		KKASSERT(lp->lwp_stat != LSSTOP);
846 		setrunnable(lp);
847 		lwkt_reltoken(&lp->lwp_token);
848 	} else {
849 		_tsleep_remove(td);
850 		lwkt_schedule(td);
851 	}
852 	KKASSERT(td->td_gd == mycpu);
853 	td->td_flags &= ~TDF_TIMEOUT_RUNNING;
854 	crit_exit();
855 }
856 
857 /*
858  * Make all processes sleeping on the specified identifier runnable.
859  * count may be zero or one only.
860  *
861  * The domain encodes the sleep/wakeup domain, flags, plus the originating
862  * cpu.
863  *
864  * This call may run without the MP lock held.  We can only manipulate thread
865  * state on the cpu owning the thread.  We CANNOT manipulate process state
866  * at all.
867  *
868  * _wakeup() can be passed to an IPI so we can't use (const volatile
869  * void *ident).
870  */
871 static void
872 _wakeup(void *ident, int domain)
873 {
874 	struct tslpque *qp;
875 	struct thread *td;
876 	struct thread *ntd;
877 	globaldata_t gd;
878 	cpumask_t mask;
879 	int id;
880 
881 	crit_enter();
882 	logtsleep2(wakeup_beg, ident);
883 	gd = mycpu;
884 	id = LOOKUP(ident);
885 	qp = &gd->gd_tsleep_hash[id];
886 restart:
887 	for (td = TAILQ_FIRST(qp); td != NULL; td = ntd) {
888 		ntd = TAILQ_NEXT(td, td_sleepq);
889 		if (td->td_wchan == ident &&
890 		    td->td_wdomain == (domain & PDOMAIN_MASK)
891 		) {
892 			KKASSERT(td->td_gd == gd);
893 			_tsleep_remove(td);
894 			td->td_wakefromcpu = PWAKEUP_DECODE(domain);
895 			if (td->td_flags & TDF_TSLEEP_DESCHEDULED) {
896 				lwkt_schedule(td);
897 				if (domain & PWAKEUP_ONE)
898 					goto done;
899 			}
900 			goto restart;
901 		}
902 	}
903 
904 	/*
905 	 * We finished checking the current cpu but there still may be
906 	 * more work to do.  Either wakeup_one was requested and no matching
907 	 * thread was found, or a normal wakeup was requested and we have
908 	 * to continue checking cpus.
909 	 *
910 	 * It should be noted that this scheme is actually less expensive then
911 	 * the old scheme when waking up multiple threads, since we send
912 	 * only one IPI message per target candidate which may then schedule
913 	 * multiple threads.  Before we could have wound up sending an IPI
914 	 * message for each thread on the target cpu (!= current cpu) that
915 	 * needed to be woken up.
916 	 *
917 	 * NOTE: Wakeups occuring on remote cpus are asynchronous.  This
918 	 * should be ok since we are passing idents in the IPI rather then
919 	 * thread pointers.
920 	 */
921 	if ((domain & PWAKEUP_MYCPU) == 0) {
922 		mask = slpque_cpumasks[id];
923 		CPUMASK_ANDMASK(mask, gd->gd_other_cpus);
924 		if (CPUMASK_TESTNZERO(mask)) {
925 			lwkt_send_ipiq2_mask(mask, _wakeup, ident,
926 					     domain | PWAKEUP_MYCPU);
927 		}
928 	}
929 done:
930 	logtsleep1(wakeup_end);
931 	crit_exit();
932 }
933 
934 /*
935  * Wakeup all threads tsleep()ing on the specified ident, on all cpus
936  */
937 void
938 wakeup(const volatile void *ident)
939 {
940     globaldata_t gd = mycpu;
941     thread_t td = gd->gd_curthread;
942 
943     if (td && (td->td_flags & TDF_DELAYED_WAKEUP)) {
944 	/*
945 	 * If we are in a delayed wakeup section, record up to two wakeups in
946 	 * a per-CPU queue and issue them when we block or exit the delayed
947 	 * wakeup section.
948 	 */
949 	if (atomic_cmpset_ptr(&gd->gd_delayed_wakeup[0], NULL, ident))
950 		return;
951 	if (atomic_cmpset_ptr(&gd->gd_delayed_wakeup[1], NULL, ident))
952 		return;
953 
954 	ident = atomic_swap_ptr(__DEQUALIFY(volatile void **, &gd->gd_delayed_wakeup[1]),
955 				__DEALL(ident));
956 	ident = atomic_swap_ptr(__DEQUALIFY(volatile void **, &gd->gd_delayed_wakeup[0]),
957 				__DEALL(ident));
958     }
959 
960     _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, gd->gd_cpuid));
961 }
962 
963 /*
964  * Wakeup one thread tsleep()ing on the specified ident, on any cpu.
965  */
966 void
967 wakeup_one(const volatile void *ident)
968 {
969     /* XXX potentially round-robin the first responding cpu */
970     _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, mycpu->gd_cpuid) |
971 			    PWAKEUP_ONE);
972 }
973 
974 /*
975  * Wakeup threads tsleep()ing on the specified ident on the current cpu
976  * only.
977  */
978 void
979 wakeup_mycpu(const volatile void *ident)
980 {
981     _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, mycpu->gd_cpuid) |
982 			    PWAKEUP_MYCPU);
983 }
984 
985 /*
986  * Wakeup one thread tsleep()ing on the specified ident on the current cpu
987  * only.
988  */
989 void
990 wakeup_mycpu_one(const volatile void *ident)
991 {
992     /* XXX potentially round-robin the first responding cpu */
993     _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, mycpu->gd_cpuid) |
994 			    PWAKEUP_MYCPU | PWAKEUP_ONE);
995 }
996 
997 /*
998  * Wakeup all thread tsleep()ing on the specified ident on the specified cpu
999  * only.
1000  */
1001 void
1002 wakeup_oncpu(globaldata_t gd, const volatile void *ident)
1003 {
1004     globaldata_t mygd = mycpu;
1005     if (gd == mycpu) {
1006 	_wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, mygd->gd_cpuid) |
1007 				PWAKEUP_MYCPU);
1008     } else {
1009 	lwkt_send_ipiq2(gd, _wakeup, __DEALL(ident),
1010 			PWAKEUP_ENCODE(0, mygd->gd_cpuid) |
1011 			PWAKEUP_MYCPU);
1012     }
1013 }
1014 
1015 /*
1016  * Wakeup one thread tsleep()ing on the specified ident on the specified cpu
1017  * only.
1018  */
1019 void
1020 wakeup_oncpu_one(globaldata_t gd, const volatile void *ident)
1021 {
1022     globaldata_t mygd = mycpu;
1023     if (gd == mygd) {
1024 	_wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, mygd->gd_cpuid) |
1025 				PWAKEUP_MYCPU | PWAKEUP_ONE);
1026     } else {
1027 	lwkt_send_ipiq2(gd, _wakeup, __DEALL(ident),
1028 			PWAKEUP_ENCODE(0, mygd->gd_cpuid) |
1029 			PWAKEUP_MYCPU | PWAKEUP_ONE);
1030     }
1031 }
1032 
1033 /*
1034  * Wakeup all threads waiting on the specified ident that slept using
1035  * the specified domain, on all cpus.
1036  */
1037 void
1038 wakeup_domain(const volatile void *ident, int domain)
1039 {
1040     _wakeup(__DEALL(ident), PWAKEUP_ENCODE(domain, mycpu->gd_cpuid));
1041 }
1042 
1043 /*
1044  * Wakeup one thread waiting on the specified ident that slept using
1045  * the specified  domain, on any cpu.
1046  */
1047 void
1048 wakeup_domain_one(const volatile void *ident, int domain)
1049 {
1050     /* XXX potentially round-robin the first responding cpu */
1051     _wakeup(__DEALL(ident),
1052 	    PWAKEUP_ENCODE(domain, mycpu->gd_cpuid) | PWAKEUP_ONE);
1053 }
1054 
1055 void
1056 wakeup_start_delayed(void)
1057 {
1058     globaldata_t gd = mycpu;
1059 
1060     crit_enter();
1061     gd->gd_curthread->td_flags |= TDF_DELAYED_WAKEUP;
1062     crit_exit();
1063 }
1064 
1065 void
1066 wakeup_end_delayed(void)
1067 {
1068     globaldata_t gd = mycpu;
1069 
1070     if (gd->gd_curthread->td_flags & TDF_DELAYED_WAKEUP) {
1071 	crit_enter();
1072 	gd->gd_curthread->td_flags &= ~TDF_DELAYED_WAKEUP;
1073 	if (gd->gd_delayed_wakeup[0] || gd->gd_delayed_wakeup[1]) {
1074 	    if (gd->gd_delayed_wakeup[0]) {
1075 		    wakeup(gd->gd_delayed_wakeup[0]);
1076 		    gd->gd_delayed_wakeup[0] = NULL;
1077 	    }
1078 	    if (gd->gd_delayed_wakeup[1]) {
1079 		    wakeup(gd->gd_delayed_wakeup[1]);
1080 		    gd->gd_delayed_wakeup[1] = NULL;
1081 	    }
1082 	}
1083 	crit_exit();
1084     }
1085 }
1086 
1087 /*
1088  * setrunnable()
1089  *
1090  * Make a process runnable.  lp->lwp_token must be held on call and this
1091  * function must be called from the cpu owning lp.
1092  *
1093  * This only has an effect if we are in LSSTOP or LSSLEEP.
1094  */
1095 void
1096 setrunnable(struct lwp *lp)
1097 {
1098 	thread_t td = lp->lwp_thread;
1099 
1100 	ASSERT_LWKT_TOKEN_HELD(&lp->lwp_token);
1101 	KKASSERT(td->td_gd == mycpu);
1102 	crit_enter();
1103 	if (lp->lwp_stat == LSSTOP)
1104 		lp->lwp_stat = LSSLEEP;
1105 	if (lp->lwp_stat == LSSLEEP) {
1106 		_tsleep_remove(td);
1107 		lwkt_schedule(td);
1108 	} else if (td->td_flags & TDF_SINTR) {
1109 		lwkt_schedule(td);
1110 	}
1111 	crit_exit();
1112 }
1113 
1114 /*
1115  * The process is stopped due to some condition, usually because p_stat is
1116  * set to SSTOP, but also possibly due to being traced.
1117  *
1118  * Caller must hold p->p_token
1119  *
1120  * NOTE!  If the caller sets SSTOP, the caller must also clear P_WAITED
1121  * because the parent may check the child's status before the child actually
1122  * gets to this routine.
1123  *
1124  * This routine is called with the current lwp only, typically just
1125  * before returning to userland if the process state is detected as
1126  * possibly being in a stopped state.
1127  */
1128 void
1129 tstop(void)
1130 {
1131 	struct lwp *lp = curthread->td_lwp;
1132 	struct proc *p = lp->lwp_proc;
1133 	struct proc *q;
1134 
1135 	lwkt_gettoken(&lp->lwp_token);
1136 	crit_enter();
1137 
1138 	/*
1139 	 * If LWP_MP_WSTOP is set, we were sleeping
1140 	 * while our process was stopped.  At this point
1141 	 * we were already counted as stopped.
1142 	 */
1143 	if ((lp->lwp_mpflags & LWP_MP_WSTOP) == 0) {
1144 		/*
1145 		 * If we're the last thread to stop, signal
1146 		 * our parent.
1147 		 */
1148 		p->p_nstopped++;
1149 		atomic_set_int(&lp->lwp_mpflags, LWP_MP_WSTOP);
1150 		wakeup(&p->p_nstopped);
1151 		if (p->p_nstopped == p->p_nthreads) {
1152 			/*
1153 			 * Token required to interlock kern_wait()
1154 			 */
1155 			q = p->p_pptr;
1156 			PHOLD(q);
1157 			lwkt_gettoken(&q->p_token);
1158 			p->p_flags &= ~P_WAITED;
1159 			wakeup(p->p_pptr);
1160 			if ((q->p_sigacts->ps_flag & PS_NOCLDSTOP) == 0)
1161 				ksignal(q, SIGCHLD);
1162 			lwkt_reltoken(&q->p_token);
1163 			PRELE(q);
1164 		}
1165 	}
1166 	while (p->p_stat == SSTOP || p->p_stat == SCORE) {
1167 		lp->lwp_stat = LSSTOP;
1168 		tsleep(p, 0, "stop", 0);
1169 	}
1170 	p->p_nstopped--;
1171 	atomic_clear_int(&lp->lwp_mpflags, LWP_MP_WSTOP);
1172 	crit_exit();
1173 	lwkt_reltoken(&lp->lwp_token);
1174 }
1175 
1176 /*
1177  * Compute a tenex style load average of a quantity on
1178  * 1, 5 and 15 minute intervals.
1179  */
1180 static int loadav_count_runnable(struct lwp *p, void *data);
1181 
1182 static void
1183 loadav(void *arg)
1184 {
1185 	struct loadavg *avg;
1186 	int i, nrun;
1187 
1188 	nrun = 0;
1189 	alllwp_scan(loadav_count_runnable, &nrun);
1190 	avg = &averunnable;
1191 	for (i = 0; i < 3; i++) {
1192 		avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
1193 		    nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
1194 	}
1195 
1196 	/*
1197 	 * Schedule the next update to occur after 5 seconds, but add a
1198 	 * random variation to avoid synchronisation with processes that
1199 	 * run at regular intervals.
1200 	 */
1201 	callout_reset(&loadav_callout, hz * 4 + (int)(krandom() % (hz * 2 + 1)),
1202 		      loadav, NULL);
1203 }
1204 
1205 static int
1206 loadav_count_runnable(struct lwp *lp, void *data)
1207 {
1208 	int *nrunp = data;
1209 	thread_t td;
1210 
1211 	switch (lp->lwp_stat) {
1212 	case LSRUN:
1213 		if ((td = lp->lwp_thread) == NULL)
1214 			break;
1215 		if (td->td_flags & TDF_BLOCKED)
1216 			break;
1217 		++*nrunp;
1218 		break;
1219 	default:
1220 		break;
1221 	}
1222 	lwkt_yield();
1223 	return(0);
1224 }
1225 
1226 /* ARGSUSED */
1227 static void
1228 sched_setup(void *dummy)
1229 {
1230 	callout_init_mp(&loadav_callout);
1231 	callout_init_mp(&schedcpu_callout);
1232 
1233 	/* Kick off timeout driven events by calling first time. */
1234 	schedcpu(NULL);
1235 	loadav(NULL);
1236 }
1237 
1238