xref: /freebsd/sys/kern/kern_condvar.c (revision ee2ea5ceafed78a5bd9810beb9e3ca927180c226)
1 /*-
2  * Copyright (c) 2000 Jake Burkholder <jake@freebsd.org>.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD$
27  */
28 
29 #include "opt_ktrace.h"
30 
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/lock.h>
34 #include <sys/mutex.h>
35 #include <sys/proc.h>
36 #include <sys/kernel.h>
37 #include <sys/ktr.h>
38 #include <sys/condvar.h>
39 #include <sys/signalvar.h>
40 #include <sys/resourcevar.h>
41 #ifdef KTRACE
42 #include <sys/uio.h>
43 #include <sys/ktrace.h>
44 #endif
45 
46 /*
47  * Common sanity checks for cv_wait* functions.
48  */
49 #define	CV_ASSERT(cvp, mp, td) do {					\
50 	KASSERT((td) != NULL, ("%s: curthread NULL", __func__));	\
51 	KASSERT((td)->td_proc->p_stat == SRUN, ("%s: not SRUN", __func__));	\
52 	KASSERT((cvp) != NULL, ("%s: cvp NULL", __func__));		\
53 	KASSERT((mp) != NULL, ("%s: mp NULL", __func__));		\
54 	mtx_assert((mp), MA_OWNED | MA_NOTRECURSED);			\
55 } while (0)
56 
57 #ifdef INVARIANTS
58 #define	CV_WAIT_VALIDATE(cvp, mp) do {					\
59 	if (TAILQ_EMPTY(&(cvp)->cv_waitq)) {				\
60 		/* Only waiter. */					\
61 		(cvp)->cv_mtx = (mp);					\
62 	} else {							\
63 		/*							\
64 		 * Other waiter; assert that we're using the		\
65 		 * same mutex.						\
66 		 */							\
67 		KASSERT((cvp)->cv_mtx == (mp),				\
68 		    ("%s: Multiple mutexes", __func__));		\
69 	}								\
70 } while (0)
71 #define	CV_SIGNAL_VALIDATE(cvp) do {					\
72 	if (!TAILQ_EMPTY(&(cvp)->cv_waitq)) {				\
73 		KASSERT(mtx_owned((cvp)->cv_mtx),			\
74 		    ("%s: Mutex not owned", __func__));		\
75 	}								\
76 } while (0)
77 #else
78 #define	CV_WAIT_VALIDATE(cvp, mp)
79 #define	CV_SIGNAL_VALIDATE(cvp)
80 #endif
81 
82 static void cv_timedwait_end(void *arg);
83 
84 /*
85  * Initialize a condition variable.  Must be called before use.
86  */
87 void
88 cv_init(struct cv *cvp, const char *desc)
89 {
90 
91 	TAILQ_INIT(&cvp->cv_waitq);
92 	cvp->cv_mtx = NULL;
93 	cvp->cv_description = desc;
94 }
95 
96 /*
97  * Destroy a condition variable.  The condition variable must be re-initialized
98  * in order to be re-used.
99  */
100 void
101 cv_destroy(struct cv *cvp)
102 {
103 
104 	KASSERT(cv_waitq_empty(cvp), ("%s: cv_waitq non-empty", __func__));
105 }
106 
107 /*
108  * Common code for cv_wait* functions.  All require sched_lock.
109  */
110 
111 /*
112  * Switch context.
113  */
114 static __inline void
115 cv_switch(struct thread *td)
116 {
117 
118 	td->td_proc->p_stat = SSLEEP;
119 	td->td_proc->p_stats->p_ru.ru_nvcsw++;
120 	mi_switch();
121 	CTR3(KTR_PROC, "cv_switch: resume thread %p (pid %d, %s)", td,
122 	    td->td_proc->p_pid, td->td_proc->p_comm);
123 }
124 
125 /*
126  * Switch context, catching signals.
127  */
128 static __inline int
129 cv_switch_catch(struct thread *td)
130 {
131 	struct proc *p;
132 	int sig;
133 
134 	/*
135 	 * We put ourselves on the sleep queue and start our timeout before
136 	 * calling CURSIG, as we could stop there, and a wakeup or a SIGCONT (or
137 	 * both) could occur while we were stopped.  A SIGCONT would cause us to
138 	 * be marked as SSLEEP without resuming us, thus we must be ready for
139 	 * sleep when CURSIG is called.  If the wakeup happens while we're
140 	 * stopped, td->td_wchan will be 0 upon return from CURSIG.
141 	 */
142 	td->td_flags |= TDF_SINTR;
143 	mtx_unlock_spin(&sched_lock);
144 	p = td->td_proc;
145 	PROC_LOCK(p);
146 	sig = CURSIG(p);	/* XXXKSE */
147 	mtx_lock_spin(&sched_lock);
148 	PROC_UNLOCK(p);
149 	if (sig != 0) {
150 		if (td->td_wchan != NULL)
151 			cv_waitq_remove(td);
152 		td->td_proc->p_stat = SRUN;
153 	} else if (td->td_wchan != NULL) {
154 		cv_switch(td);
155 	}
156 	td->td_flags &= ~TDF_SINTR;
157 
158 	return sig;
159 }
160 
161 /*
162  * Add a thread to the wait queue of a condition variable.
163  */
164 static __inline void
165 cv_waitq_add(struct cv *cvp, struct thread *td)
166 {
167 
168 	/*
169 	 * Process may be sitting on a slpque if asleep() was called, remove it
170 	 * before re-adding.
171 	 */
172 	if (td->td_wchan != NULL)
173 		unsleep(td);
174 
175 	td->td_flags |= TDF_CVWAITQ;
176 	td->td_wchan = cvp;
177 	td->td_wmesg = cvp->cv_description;
178 	td->td_kse->ke_slptime = 0; /* XXXKSE */
179 	td->td_ksegrp->kg_slptime = 0; /* XXXKSE */
180 	td->td_base_pri = td->td_priority;
181 	CTR3(KTR_PROC, "cv_waitq_add: thread %p (pid %d, %s)", td,
182 	    td->td_proc->p_pid, td->td_proc->p_comm);
183 	TAILQ_INSERT_TAIL(&cvp->cv_waitq, td, td_slpq);
184 }
185 
186 /*
187  * Wait on a condition variable.  The current thread is placed on the condition
188  * variable's wait queue and suspended.  A cv_signal or cv_broadcast on the same
189  * condition variable will resume the thread.  The mutex is released before
190  * sleeping and will be held on return.  It is recommended that the mutex be
191  * held when cv_signal or cv_broadcast are called.
192  */
193 void
194 cv_wait(struct cv *cvp, struct mtx *mp)
195 {
196 	struct thread *td;
197 	WITNESS_SAVE_DECL(mp);
198 
199 	td = curthread;
200 #ifdef KTRACE
201 	if (td->td_proc && KTRPOINT(td->td_proc, KTR_CSW))
202 		ktrcsw(td->td_proc->p_tracep, 1, 0);
203 #endif
204 	CV_ASSERT(cvp, mp, td);
205 	WITNESS_SLEEP(0, &mp->mtx_object);
206 	WITNESS_SAVE(&mp->mtx_object, mp);
207 
208 	if (cold || panicstr) {
209 		/*
210 		 * After a panic, or during autoconfiguration, just give
211 		 * interrupts a chance, then just return; don't run any other
212 		 * thread or panic below, in case this is the idle process and
213 		 * already asleep.
214 		 */
215 		return;
216 	}
217 
218 	mtx_lock_spin(&sched_lock);
219 
220 	CV_WAIT_VALIDATE(cvp, mp);
221 
222 	DROP_GIANT();
223 	mtx_unlock(mp);
224 
225 	cv_waitq_add(cvp, td);
226 	cv_switch(td);
227 
228 	mtx_unlock_spin(&sched_lock);
229 #ifdef KTRACE
230 	if (KTRPOINT(td->td_proc, KTR_CSW))
231 		ktrcsw(td->td_proc->p_tracep, 0, 0);
232 #endif
233 	PICKUP_GIANT();
234 	mtx_lock(mp);
235 	WITNESS_RESTORE(&mp->mtx_object, mp);
236 }
237 
238 /*
239  * Wait on a condition variable, allowing interruption by signals.  Return 0 if
240  * the thread was resumed with cv_signal or cv_broadcast, EINTR or ERESTART if
241  * a signal was caught.  If ERESTART is returned the system call should be
242  * restarted if possible.
243  */
244 int
245 cv_wait_sig(struct cv *cvp, struct mtx *mp)
246 {
247 	struct thread *td;
248 	struct proc *p;
249 	int rval;
250 	int sig;
251 	WITNESS_SAVE_DECL(mp);
252 
253 	td = curthread;
254 	p = td->td_proc;
255 	rval = 0;
256 #ifdef KTRACE
257 	if (td->td_proc && KTRPOINT(td->td_proc, KTR_CSW))
258 		ktrcsw(td->td_proc->p_tracep, 1, 0);
259 #endif
260 	CV_ASSERT(cvp, mp, td);
261 	WITNESS_SLEEP(0, &mp->mtx_object);
262 	WITNESS_SAVE(&mp->mtx_object, mp);
263 
264 	if (cold || panicstr) {
265 		/*
266 		 * After a panic, or during autoconfiguration, just give
267 		 * interrupts a chance, then just return; don't run any other
268 		 * procs or panic below, in case this is the idle process and
269 		 * already asleep.
270 		 */
271 		return 0;
272 	}
273 
274 	mtx_lock_spin(&sched_lock);
275 
276 	CV_WAIT_VALIDATE(cvp, mp);
277 
278 	DROP_GIANT();
279 	mtx_unlock(mp);
280 
281 	cv_waitq_add(cvp, td);
282 	sig = cv_switch_catch(td);
283 
284 	mtx_unlock_spin(&sched_lock);
285 	PICKUP_GIANT();
286 
287 	PROC_LOCK(p);
288 	if (sig == 0)
289 		sig = CURSIG(p);  /* XXXKSE */
290 	if (sig != 0) {
291 		if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
292 			rval = EINTR;
293 		else
294 			rval = ERESTART;
295 	}
296 	PROC_UNLOCK(p);
297 
298 #ifdef KTRACE
299 	mtx_lock(&Giant);
300 	if (KTRPOINT(td->td_proc, KTR_CSW))
301 		ktrcsw(td->td_proc->p_tracep, 0, 0);
302 	mtx_unlock(&Giant);
303 #endif
304 	mtx_lock(mp);
305 	WITNESS_RESTORE(&mp->mtx_object, mp);
306 
307 	return (rval);
308 }
309 
310 /*
311  * Wait on a condition variable for at most timo/hz seconds.  Returns 0 if the
312  * process was resumed by cv_signal or cv_broadcast, EWOULDBLOCK if the timeout
313  * expires.
314  */
315 int
316 cv_timedwait(struct cv *cvp, struct mtx *mp, int timo)
317 {
318 	struct thread *td;
319 	int rval;
320 	WITNESS_SAVE_DECL(mp);
321 
322 	td = curthread;
323 	rval = 0;
324 #ifdef KTRACE
325 	ktrcsw(td->td_proc->p_tracep, 1, 0);
326 #endif
327 	CV_ASSERT(cvp, mp, td);
328 	WITNESS_SLEEP(0, &mp->mtx_object);
329 	WITNESS_SAVE(&mp->mtx_object, mp);
330 
331 	if (cold || panicstr) {
332 		/*
333 		 * After a panic, or during autoconfiguration, just give
334 		 * interrupts a chance, then just return; don't run any other
335 		 * thread or panic below, in case this is the idle process and
336 		 * already asleep.
337 		 */
338 		return 0;
339 	}
340 
341 	mtx_lock_spin(&sched_lock);
342 
343 	CV_WAIT_VALIDATE(cvp, mp);
344 
345 	DROP_GIANT();
346 	mtx_unlock(mp);
347 
348 	cv_waitq_add(cvp, td);
349 	callout_reset(&td->td_slpcallout, timo, cv_timedwait_end, td);
350 	cv_switch(td);
351 
352 	if (td->td_flags & TDF_TIMEOUT) {
353 		td->td_flags &= ~TDF_TIMEOUT;
354 		rval = EWOULDBLOCK;
355 	} else if (td->td_flags & TDF_TIMOFAIL)
356 		td->td_flags &= ~TDF_TIMOFAIL;
357 	else if (callout_stop(&td->td_slpcallout) == 0) {
358 		/*
359 		 * Work around race with cv_timedwait_end similar to that
360 		 * between msleep and endtsleep.
361 		 */
362 		td->td_flags |= TDF_TIMEOUT;
363 		td->td_proc->p_stats->p_ru.ru_nivcsw++;
364 		mi_switch();
365 	}
366 
367 	mtx_unlock_spin(&sched_lock);
368 #ifdef KTRACE
369 	if (KTRPOINT(td->td_proc, KTR_CSW))
370 		ktrcsw(td->td_proc->p_tracep, 0, 0);
371 #endif
372 	PICKUP_GIANT();
373 	mtx_lock(mp);
374 	WITNESS_RESTORE(&mp->mtx_object, mp);
375 
376 	return (rval);
377 }
378 
379 /*
380  * Wait on a condition variable for at most timo/hz seconds, allowing
381  * interruption by signals.  Returns 0 if the thread was resumed by cv_signal
382  * or cv_broadcast, EWOULDBLOCK if the timeout expires, and EINTR or ERESTART if
383  * a signal was caught.
384  */
385 int
386 cv_timedwait_sig(struct cv *cvp, struct mtx *mp, int timo)
387 {
388 	struct thread *td;
389 	struct proc *p;
390 	int rval;
391 	int sig;
392 	WITNESS_SAVE_DECL(mp);
393 
394 	td = curthread;
395 	p = td->td_proc;
396 	rval = 0;
397 #ifdef KTRACE
398 	if (td->td_proc && KTRPOINT(td->td_proc, KTR_CSW))
399 		ktrcsw(td->td_proc->p_tracep, 1, 0);
400 #endif
401 	CV_ASSERT(cvp, mp, td);
402 	WITNESS_SLEEP(0, &mp->mtx_object);
403 	WITNESS_SAVE(&mp->mtx_object, mp);
404 
405 	if (cold || panicstr) {
406 		/*
407 		 * After a panic, or during autoconfiguration, just give
408 		 * interrupts a chance, then just return; don't run any other
409 		 * thread or panic below, in case this is the idle process and
410 		 * already asleep.
411 		 */
412 		return 0;
413 	}
414 
415 	mtx_lock_spin(&sched_lock);
416 
417 	CV_WAIT_VALIDATE(cvp, mp);
418 
419 	DROP_GIANT();
420 	mtx_unlock(mp);
421 
422 	cv_waitq_add(cvp, td);
423 	callout_reset(&td->td_slpcallout, timo, cv_timedwait_end, td);
424 	sig = cv_switch_catch(td);
425 
426 	if (td->td_flags & TDF_TIMEOUT) {
427 		td->td_flags &= ~TDF_TIMEOUT;
428 		rval = EWOULDBLOCK;
429 	} else if (td->td_flags & TDF_TIMOFAIL)
430 		td->td_flags &= ~TDF_TIMOFAIL;
431 	else if (callout_stop(&td->td_slpcallout) == 0) {
432 		/*
433 		 * Work around race with cv_timedwait_end similar to that
434 		 * between msleep and endtsleep.
435 		 */
436 		td->td_flags |= TDF_TIMEOUT;
437 		td->td_proc->p_stats->p_ru.ru_nivcsw++;
438 		mi_switch();
439 	}
440 
441 	mtx_unlock_spin(&sched_lock);
442 	PICKUP_GIANT();
443 
444 	PROC_LOCK(p);
445 	if (sig == 0)
446 		sig = CURSIG(p);
447 	if (sig != 0) {
448 		if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
449 			rval = EINTR;
450 		else
451 			rval = ERESTART;
452 	}
453 	PROC_UNLOCK(p);
454 
455 #ifdef KTRACE
456 	mtx_lock(&Giant);
457 	if (KTRPOINT(td->td_proc, KTR_CSW))
458 		ktrcsw(td->td_proc->p_tracep, 0, 0);
459 	mtx_unlock(&Giant);
460 #endif
461 	mtx_lock(mp);
462 	WITNESS_RESTORE(&mp->mtx_object, mp);
463 
464 	return (rval);
465 }
466 
467 /*
468  * Common code for signal and broadcast.  Assumes waitq is not empty.  Must be
469  * called with sched_lock held.
470  */
471 static __inline void
472 cv_wakeup(struct cv *cvp)
473 {
474 	struct thread *td;
475 
476 	mtx_assert(&sched_lock, MA_OWNED);
477 	td = TAILQ_FIRST(&cvp->cv_waitq);
478 	KASSERT(td->td_wchan == cvp, ("%s: bogus wchan", __func__));
479 	KASSERT(td->td_flags & TDF_CVWAITQ, ("%s: not on waitq", __func__));
480 	TAILQ_REMOVE(&cvp->cv_waitq, td, td_slpq);
481 	td->td_flags &= ~TDF_CVWAITQ;
482 	td->td_wchan = 0;
483 	if (td->td_proc->p_stat == SSLEEP) {
484 		/* OPTIMIZED EXPANSION OF setrunnable(td); */
485 		CTR3(KTR_PROC, "cv_signal: thread %p (pid %d, %s)",
486 		    td, td->td_proc->p_pid, td->td_proc->p_comm);
487 		if (td->td_ksegrp->kg_slptime > 1) /* XXXKSE */
488 			updatepri(td);
489 		td->td_kse->ke_slptime = 0;
490 		td->td_ksegrp->kg_slptime = 0;
491 		td->td_proc->p_stat = SRUN;
492 		if (td->td_proc->p_sflag & PS_INMEM) {
493 			setrunqueue(td);
494 			maybe_resched(td);
495 		} else {
496 			td->td_proc->p_sflag |= PS_SWAPINREQ;
497 			wakeup(&proc0); /* XXXKSE */
498 		}
499 		/* END INLINE EXPANSION */
500 	}
501 }
502 
503 /*
504  * Signal a condition variable, wakes up one waiting thread.  Will also wakeup
505  * the swapper if the process is not in memory, so that it can bring the
506  * sleeping process in.  Note that this may also result in additional threads
507  * being made runnable.  Should be called with the same mutex as was passed to
508  * cv_wait held.
509  */
510 void
511 cv_signal(struct cv *cvp)
512 {
513 
514 	KASSERT(cvp != NULL, ("%s: cvp NULL", __func__));
515 	mtx_lock_spin(&sched_lock);
516 	if (!TAILQ_EMPTY(&cvp->cv_waitq)) {
517 		CV_SIGNAL_VALIDATE(cvp);
518 		cv_wakeup(cvp);
519 	}
520 	mtx_unlock_spin(&sched_lock);
521 }
522 
523 /*
524  * Broadcast a signal to a condition variable.  Wakes up all waiting threads.
525  * Should be called with the same mutex as was passed to cv_wait held.
526  */
527 void
528 cv_broadcast(struct cv *cvp)
529 {
530 
531 	KASSERT(cvp != NULL, ("%s: cvp NULL", __func__));
532 	mtx_lock_spin(&sched_lock);
533 	CV_SIGNAL_VALIDATE(cvp);
534 	while (!TAILQ_EMPTY(&cvp->cv_waitq))
535 		cv_wakeup(cvp);
536 	mtx_unlock_spin(&sched_lock);
537 }
538 
539 /*
540  * Remove a thread from the wait queue of its condition variable.  This may be
541  * called externally.
542  */
543 void
544 cv_waitq_remove(struct thread *td)
545 {
546 	struct cv *cvp;
547 
548 	mtx_lock_spin(&sched_lock);
549 	if ((cvp = td->td_wchan) != NULL && td->td_flags & TDF_CVWAITQ) {
550 		TAILQ_REMOVE(&cvp->cv_waitq, td, td_slpq);
551 		td->td_flags &= ~TDF_CVWAITQ;
552 		td->td_wchan = NULL;
553 	}
554 	mtx_unlock_spin(&sched_lock);
555 }
556 
557 /*
558  * Timeout function for cv_timedwait.  Put the thread on the runqueue and set
559  * its timeout flag.
560  */
561 static void
562 cv_timedwait_end(void *arg)
563 {
564 	struct thread *td;
565 
566 	td = arg;
567 	CTR3(KTR_PROC, "cv_timedwait_end: thread %p (pid %d, %s)", td, td->td_proc->p_pid,
568 	    td->td_proc->p_comm);
569 	mtx_lock_spin(&sched_lock);
570 	if (td->td_flags & TDF_TIMEOUT) {
571 		td->td_flags &= ~TDF_TIMEOUT;
572 		setrunqueue(td);
573 	} else if (td->td_wchan != NULL) {
574 		if (td->td_proc->p_stat == SSLEEP) /* XXXKSE */
575 			setrunnable(td);
576 		else
577 			cv_waitq_remove(td);
578 		td->td_flags |= TDF_TIMEOUT;
579 	} else
580 		td->td_flags |= TDF_TIMOFAIL;
581 	mtx_unlock_spin(&sched_lock);
582 }
583