xref: /netbsd-src/sys/kern/kern_sleepq.c (revision ba65fde2d7fefa7d39838fa5fa855e62bd606b5e)
1 /*	$NetBSD: kern_sleepq.c,v 1.47 2012/07/27 05:36:13 matt Exp $	*/
2 
3 /*-
4  * Copyright (c) 2006, 2007, 2008, 2009 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Andrew Doran.
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  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * Sleep queue implementation, used by turnstiles and general sleep/wakeup
34  * interfaces.
35  */
36 
37 #include <sys/cdefs.h>
38 __KERNEL_RCSID(0, "$NetBSD: kern_sleepq.c,v 1.47 2012/07/27 05:36:13 matt Exp $");
39 
40 #include <sys/param.h>
41 #include <sys/kernel.h>
42 #include <sys/cpu.h>
43 #include <sys/intr.h>
44 #include <sys/pool.h>
45 #include <sys/proc.h>
46 #include <sys/resourcevar.h>
47 #include <sys/sched.h>
48 #include <sys/systm.h>
49 #include <sys/sleepq.h>
50 #include <sys/ktrace.h>
51 
52 /*
53  * for sleepq_abort:
54  * During autoconfiguration or after a panic, a sleep will simply lower the
55  * priority briefly to allow interrupts, then return.  The priority to be
56  * used (IPL_SAFEPRI) is machine-dependent, thus this value is initialized and
57  * maintained in the machine-dependent layers.  This priority will typically
58  * be 0, or the lowest priority that is safe for use on the interrupt stack;
59  * it can be made higher to block network software interrupts after panics.
60  */
61 #ifndef	IPL_SAFEPRI
62 #define	IPL_SAFEPRI	0
63 #endif
64 
65 static int	sleepq_sigtoerror(lwp_t *, int);
66 
67 /* General purpose sleep table, used by mtsleep() and condition variables. */
68 sleeptab_t	sleeptab	__cacheline_aligned;
69 
70 /*
71  * sleeptab_init:
72  *
73  *	Initialize a sleep table.
74  */
75 void
76 sleeptab_init(sleeptab_t *st)
77 {
78 	sleepq_t *sq;
79 	int i;
80 
81 	for (i = 0; i < SLEEPTAB_HASH_SIZE; i++) {
82 		sq = &st->st_queues[i].st_queue;
83 		st->st_queues[i].st_mutex =
84 		    mutex_obj_alloc(MUTEX_DEFAULT, IPL_SCHED);
85 		sleepq_init(sq);
86 	}
87 }
88 
89 /*
90  * sleepq_init:
91  *
92  *	Prepare a sleep queue for use.
93  */
94 void
95 sleepq_init(sleepq_t *sq)
96 {
97 
98 	TAILQ_INIT(sq);
99 }
100 
101 /*
102  * sleepq_remove:
103  *
104  *	Remove an LWP from a sleep queue and wake it up.
105  */
106 void
107 sleepq_remove(sleepq_t *sq, lwp_t *l)
108 {
109 	struct schedstate_percpu *spc;
110 	struct cpu_info *ci;
111 
112 	KASSERT(lwp_locked(l, NULL));
113 
114 	TAILQ_REMOVE(sq, l, l_sleepchain);
115 	l->l_syncobj = &sched_syncobj;
116 	l->l_wchan = NULL;
117 	l->l_sleepq = NULL;
118 	l->l_flag &= ~LW_SINTR;
119 
120 	ci = l->l_cpu;
121 	spc = &ci->ci_schedstate;
122 
123 	/*
124 	 * If not sleeping, the LWP must have been suspended.  Let whoever
125 	 * holds it stopped set it running again.
126 	 */
127 	if (l->l_stat != LSSLEEP) {
128 		KASSERT(l->l_stat == LSSTOP || l->l_stat == LSSUSPENDED);
129 		lwp_setlock(l, spc->spc_lwplock);
130 		return;
131 	}
132 
133 	/*
134 	 * If the LWP is still on the CPU, mark it as LSONPROC.  It may be
135 	 * about to call mi_switch(), in which case it will yield.
136 	 */
137 	if ((l->l_pflag & LP_RUNNING) != 0) {
138 		l->l_stat = LSONPROC;
139 		l->l_slptime = 0;
140 		lwp_setlock(l, spc->spc_lwplock);
141 		return;
142 	}
143 
144 	/* Update sleep time delta, call the wake-up handler of scheduler */
145 	l->l_slpticksum += (hardclock_ticks - l->l_slpticks);
146 	sched_wakeup(l);
147 
148 	/* Look for a CPU to wake up */
149 	l->l_cpu = sched_takecpu(l);
150 	ci = l->l_cpu;
151 	spc = &ci->ci_schedstate;
152 
153 	/*
154 	 * Set it running.
155 	 */
156 	spc_lock(ci);
157 	lwp_setlock(l, spc->spc_mutex);
158 	sched_setrunnable(l);
159 	l->l_stat = LSRUN;
160 	l->l_slptime = 0;
161 	sched_enqueue(l, false);
162 	spc_unlock(ci);
163 }
164 
165 /*
166  * sleepq_insert:
167  *
168  *	Insert an LWP into the sleep queue, optionally sorting by priority.
169  */
170 static void
171 sleepq_insert(sleepq_t *sq, lwp_t *l, syncobj_t *sobj)
172 {
173 
174 	if ((sobj->sobj_flag & SOBJ_SLEEPQ_SORTED) != 0) {
175 		lwp_t *l2;
176 		const int pri = lwp_eprio(l);
177 
178 		TAILQ_FOREACH(l2, sq, l_sleepchain) {
179 			if (lwp_eprio(l2) < pri) {
180 				TAILQ_INSERT_BEFORE(l2, l, l_sleepchain);
181 				return;
182 			}
183 		}
184 	}
185 
186 	if ((sobj->sobj_flag & SOBJ_SLEEPQ_LIFO) != 0)
187 		TAILQ_INSERT_HEAD(sq, l, l_sleepchain);
188 	else
189 		TAILQ_INSERT_TAIL(sq, l, l_sleepchain);
190 }
191 
192 /*
193  * sleepq_enqueue:
194  *
195  *	Enter an LWP into the sleep queue and prepare for sleep.  The sleep
196  *	queue must already be locked, and any interlock (such as the kernel
197  *	lock) must have be released (see sleeptab_lookup(), sleepq_enter()).
198  */
199 void
200 sleepq_enqueue(sleepq_t *sq, wchan_t wchan, const char *wmesg, syncobj_t *sobj)
201 {
202 	lwp_t *l = curlwp;
203 
204 	KASSERT(lwp_locked(l, NULL));
205 	KASSERT(l->l_stat == LSONPROC);
206 	KASSERT(l->l_wchan == NULL && l->l_sleepq == NULL);
207 
208 	l->l_syncobj = sobj;
209 	l->l_wchan = wchan;
210 	l->l_sleepq = sq;
211 	l->l_wmesg = wmesg;
212 	l->l_slptime = 0;
213 	l->l_stat = LSSLEEP;
214 	l->l_sleeperr = 0;
215 
216 	sleepq_insert(sq, l, sobj);
217 
218 	/* Save the time when thread has slept */
219 	l->l_slpticks = hardclock_ticks;
220 	sched_slept(l);
221 }
222 
223 /*
224  * sleepq_block:
225  *
226  *	After any intermediate step such as releasing an interlock, switch.
227  * 	sleepq_block() may return early under exceptional conditions, for
228  * 	example if the LWP's containing process is exiting.
229  */
230 int
231 sleepq_block(int timo, bool catch)
232 {
233 	int error = 0, sig;
234 	struct proc *p;
235 	lwp_t *l = curlwp;
236 	bool early = false;
237 	int biglocks = l->l_biglocks;
238 
239 	ktrcsw(1, 0);
240 
241 	/*
242 	 * If sleeping interruptably, check for pending signals, exits or
243 	 * core dump events.
244 	 */
245 	if (catch) {
246 		l->l_flag |= LW_SINTR;
247 		if ((l->l_flag & (LW_CANCELLED|LW_WEXIT|LW_WCORE)) != 0) {
248 			l->l_flag &= ~LW_CANCELLED;
249 			error = EINTR;
250 			early = true;
251 		} else if ((l->l_flag & LW_PENDSIG) != 0 && sigispending(l, 0))
252 			early = true;
253 	}
254 
255 	if (early) {
256 		/* lwp_unsleep() will release the lock */
257 		lwp_unsleep(l, true);
258 	} else {
259 		if (timo) {
260 			callout_schedule(&l->l_timeout_ch, timo);
261 		}
262 		mi_switch(l);
263 
264 		/* The LWP and sleep queue are now unlocked. */
265 		if (timo) {
266 			/*
267 			 * Even if the callout appears to have fired, we need to
268 			 * stop it in order to synchronise with other CPUs.
269 			 */
270 			if (callout_halt(&l->l_timeout_ch, NULL))
271 				error = EWOULDBLOCK;
272 		}
273 	}
274 
275 	if (catch && error == 0) {
276 		p = l->l_proc;
277 		if ((l->l_flag & (LW_CANCELLED | LW_WEXIT | LW_WCORE)) != 0)
278 			error = EINTR;
279 		else if ((l->l_flag & LW_PENDSIG) != 0) {
280 			/*
281 			 * Acquiring p_lock may cause us to recurse
282 			 * through the sleep path and back into this
283 			 * routine, but is safe because LWPs sleeping
284 			 * on locks are non-interruptable.  We will
285 			 * not recurse again.
286 			 */
287 			mutex_enter(p->p_lock);
288 			if (((sig = sigispending(l, 0)) != 0 &&
289 			    (sigprop[sig] & SA_STOP) == 0) ||
290 			    (sig = issignal(l)) != 0)
291 				error = sleepq_sigtoerror(l, sig);
292 			mutex_exit(p->p_lock);
293 		}
294 	}
295 
296 	ktrcsw(0, 0);
297 	if (__predict_false(biglocks != 0)) {
298 		KERNEL_LOCK(biglocks, NULL);
299 	}
300 	return error;
301 }
302 
303 /*
304  * sleepq_wake:
305  *
306  *	Wake zero or more LWPs blocked on a single wait channel.
307  */
308 lwp_t *
309 sleepq_wake(sleepq_t *sq, wchan_t wchan, u_int expected, kmutex_t *mp)
310 {
311 	lwp_t *l, *next;
312 
313 	KASSERT(mutex_owned(mp));
314 
315 	for (l = TAILQ_FIRST(sq); l != NULL; l = next) {
316 		KASSERT(l->l_sleepq == sq);
317 		KASSERT(l->l_mutex == mp);
318 		next = TAILQ_NEXT(l, l_sleepchain);
319 		if (l->l_wchan != wchan)
320 			continue;
321 		sleepq_remove(sq, l);
322 		if (--expected == 0)
323 			break;
324 	}
325 
326 	mutex_spin_exit(mp);
327 	return l;
328 }
329 
330 /*
331  * sleepq_unsleep:
332  *
333  *	Remove an LWP from its sleep queue and set it runnable again.
334  *	sleepq_unsleep() is called with the LWP's mutex held, and will
335  *	always release it.
336  */
337 void
338 sleepq_unsleep(lwp_t *l, bool cleanup)
339 {
340 	sleepq_t *sq = l->l_sleepq;
341 	kmutex_t *mp = l->l_mutex;
342 
343 	KASSERT(lwp_locked(l, mp));
344 	KASSERT(l->l_wchan != NULL);
345 
346 	sleepq_remove(sq, l);
347 	if (cleanup) {
348 		mutex_spin_exit(mp);
349 	}
350 }
351 
352 /*
353  * sleepq_timeout:
354  *
355  *	Entered via the callout(9) subsystem to time out an LWP that is on a
356  *	sleep queue.
357  */
358 void
359 sleepq_timeout(void *arg)
360 {
361 	lwp_t *l = arg;
362 
363 	/*
364 	 * Lock the LWP.  Assuming it's still on the sleep queue, its
365 	 * current mutex will also be the sleep queue mutex.
366 	 */
367 	lwp_lock(l);
368 
369 	if (l->l_wchan == NULL) {
370 		/* Somebody beat us to it. */
371 		lwp_unlock(l);
372 		return;
373 	}
374 
375 	lwp_unsleep(l, true);
376 }
377 
378 /*
379  * sleepq_sigtoerror:
380  *
381  *	Given a signal number, interpret and return an error code.
382  */
383 static int
384 sleepq_sigtoerror(lwp_t *l, int sig)
385 {
386 	struct proc *p = l->l_proc;
387 	int error;
388 
389 	KASSERT(mutex_owned(p->p_lock));
390 
391 	/*
392 	 * If this sleep was canceled, don't let the syscall restart.
393 	 */
394 	if ((SIGACTION(p, sig).sa_flags & SA_RESTART) == 0)
395 		error = EINTR;
396 	else
397 		error = ERESTART;
398 
399 	return error;
400 }
401 
402 /*
403  * sleepq_abort:
404  *
405  *	After a panic or during autoconfiguration, lower the interrupt
406  *	priority level to give pending interrupts a chance to run, and
407  *	then return.  Called if sleepq_dontsleep() returns non-zero, and
408  *	always returns zero.
409  */
410 int
411 sleepq_abort(kmutex_t *mtx, int unlock)
412 {
413 	int s;
414 
415 	s = splhigh();
416 	splx(IPL_SAFEPRI);
417 	splx(s);
418 	if (mtx != NULL && unlock != 0)
419 		mutex_exit(mtx);
420 
421 	return 0;
422 }
423 
424 /*
425  * sleepq_reinsert:
426  *
427  *	Move the possition of the lwp in the sleep queue after a possible
428  *	change of the lwp's effective priority.
429  */
430 static void
431 sleepq_reinsert(sleepq_t *sq, lwp_t *l)
432 {
433 
434 	KASSERT(l->l_sleepq == sq);
435 	if ((l->l_syncobj->sobj_flag & SOBJ_SLEEPQ_SORTED) == 0) {
436 		return;
437 	}
438 
439 	/*
440 	 * Don't let the sleep queue become empty, even briefly.
441 	 * cv_signal() and cv_broadcast() inspect it without the
442 	 * sleep queue lock held and need to see a non-empty queue
443 	 * head if there are waiters.
444 	 */
445 	if (TAILQ_FIRST(sq) == l && TAILQ_NEXT(l, l_sleepchain) == NULL) {
446 		return;
447 	}
448 	TAILQ_REMOVE(sq, l, l_sleepchain);
449 	sleepq_insert(sq, l, l->l_syncobj);
450 }
451 
452 /*
453  * sleepq_changepri:
454  *
455  *	Adjust the priority of an LWP residing on a sleepq.
456  */
457 void
458 sleepq_changepri(lwp_t *l, pri_t pri)
459 {
460 	sleepq_t *sq = l->l_sleepq;
461 
462 	KASSERT(lwp_locked(l, NULL));
463 
464 	l->l_priority = pri;
465 	sleepq_reinsert(sq, l);
466 }
467 
468 /*
469  * sleepq_changepri:
470  *
471  *	Adjust the lended priority of an LWP residing on a sleepq.
472  */
473 void
474 sleepq_lendpri(lwp_t *l, pri_t pri)
475 {
476 	sleepq_t *sq = l->l_sleepq;
477 
478 	KASSERT(lwp_locked(l, NULL));
479 
480 	l->l_inheritedprio = pri;
481 	sleepq_reinsert(sq, l);
482 }
483