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