kern_condvar.c revision 1.50 1 /* $NetBSD: kern_condvar.c,v 1.50 2020/05/03 17:36:33 thorpej Exp $ */
2
3 /*-
4 * Copyright (c) 2006, 2007, 2008, 2019, 2020 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 * Kernel condition variable implementation.
34 */
35
36 #include <sys/cdefs.h>
37 __KERNEL_RCSID(0, "$NetBSD: kern_condvar.c,v 1.50 2020/05/03 17:36:33 thorpej Exp $");
38
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/lwp.h>
42 #include <sys/condvar.h>
43 #include <sys/sleepq.h>
44 #include <sys/lockdebug.h>
45 #include <sys/cpu.h>
46 #include <sys/kernel.h>
47
48 /*
49 * Accessors for the private contents of the kcondvar_t data type.
50 *
51 * cv_opaque[0] sleepq_t
52 * cv_opaque[1] description for ps(1)
53 *
54 * cv_opaque[0] is protected by the interlock passed to cv_wait() (enqueue
55 * only), and the sleep queue lock acquired with sleepq_hashlock() (enqueue
56 * and dequeue).
57 *
58 * cv_opaque[1] (the wmesg) is static and does not change throughout the life
59 * of the CV.
60 */
61 #define CV_SLEEPQ(cv) ((sleepq_t *)(cv)->cv_opaque)
62 #define CV_WMESG(cv) ((const char *)(cv)->cv_opaque[1])
63 #define CV_SET_WMESG(cv, v) (cv)->cv_opaque[1] = __UNCONST(v)
64
65 #define CV_DEBUG_P(cv) (CV_WMESG(cv) != nodebug)
66 #define CV_RA ((uintptr_t)__builtin_return_address(0))
67
68 static void cv_unsleep(lwp_t *, bool);
69 static inline void cv_wakeup_one(kcondvar_t *);
70 static inline void cv_wakeup_all(kcondvar_t *);
71
72 syncobj_t cv_syncobj = {
73 .sobj_flag = SOBJ_SLEEPQ_SORTED,
74 .sobj_unsleep = cv_unsleep,
75 .sobj_changepri = sleepq_changepri,
76 .sobj_lendpri = sleepq_lendpri,
77 .sobj_owner = syncobj_noowner,
78 };
79
80 static const char deadcv[] = "deadcv";
81
82 /*
83 * cv_init:
84 *
85 * Initialize a condition variable for use.
86 */
87 void
88 cv_init(kcondvar_t *cv, const char *wmesg)
89 {
90
91 KASSERT(wmesg != NULL);
92 CV_SET_WMESG(cv, wmesg);
93 sleepq_init(CV_SLEEPQ(cv));
94 }
95
96 /*
97 * cv_destroy:
98 *
99 * Tear down a condition variable.
100 */
101 void
102 cv_destroy(kcondvar_t *cv)
103 {
104
105 #ifdef DIAGNOSTIC
106 KASSERT(cv_is_valid(cv));
107 KASSERT(!cv_has_waiters(cv));
108 CV_SET_WMESG(cv, deadcv);
109 #endif
110 }
111
112 /*
113 * cv_enter:
114 *
115 * Look up and lock the sleep queue corresponding to the given
116 * condition variable, and increment the number of waiters.
117 */
118 static inline void
119 cv_enter(kcondvar_t *cv, kmutex_t *mtx, lwp_t *l, bool catch_p)
120 {
121 sleepq_t *sq;
122 kmutex_t *mp;
123
124 KASSERT(cv_is_valid(cv));
125 KASSERT(!cpu_intr_p());
126 KASSERT((l->l_pflag & LP_INTR) == 0 || panicstr != NULL);
127
128 l->l_kpriority = true;
129 mp = sleepq_hashlock(cv);
130 sq = CV_SLEEPQ(cv);
131 sleepq_enter(sq, l, mp);
132 sleepq_enqueue(sq, cv, CV_WMESG(cv), &cv_syncobj, catch_p);
133 mutex_exit(mtx);
134 KASSERT(cv_has_waiters(cv));
135 }
136
137 /*
138 * cv_unsleep:
139 *
140 * Remove an LWP from the condition variable and sleep queue. This
141 * is called when the LWP has not been awoken normally but instead
142 * interrupted: for example, when a signal is received. Must be
143 * called with the LWP locked. Will unlock if "unlock" is true.
144 */
145 static void
146 cv_unsleep(lwp_t *l, bool unlock)
147 {
148 kcondvar_t *cv __diagused;
149
150 cv = (kcondvar_t *)(uintptr_t)l->l_wchan;
151
152 KASSERT(l->l_wchan == (wchan_t)cv);
153 KASSERT(l->l_sleepq == CV_SLEEPQ(cv));
154 KASSERT(cv_is_valid(cv));
155 KASSERT(cv_has_waiters(cv));
156
157 sleepq_unsleep(l, unlock);
158 }
159
160 /*
161 * cv_wait:
162 *
163 * Wait non-interruptably on a condition variable until awoken.
164 */
165 void
166 cv_wait(kcondvar_t *cv, kmutex_t *mtx)
167 {
168 lwp_t *l = curlwp;
169
170 KASSERT(mutex_owned(mtx));
171
172 cv_enter(cv, mtx, l, false);
173 (void)sleepq_block(0, false);
174 mutex_enter(mtx);
175 }
176
177 /*
178 * cv_wait_sig:
179 *
180 * Wait on a condition variable until a awoken or a signal is received.
181 * Will also return early if the process is exiting. Returns zero if
182 * awoken normally, ERESTART if a signal was received and the system
183 * call is restartable, or EINTR otherwise.
184 */
185 int
186 cv_wait_sig(kcondvar_t *cv, kmutex_t *mtx)
187 {
188 lwp_t *l = curlwp;
189 int error;
190
191 KASSERT(mutex_owned(mtx));
192
193 cv_enter(cv, mtx, l, true);
194 error = sleepq_block(0, true);
195 mutex_enter(mtx);
196 return error;
197 }
198
199 /*
200 * cv_timedwait:
201 *
202 * Wait on a condition variable until awoken or the specified timeout
203 * expires. Returns zero if awoken normally or EWOULDBLOCK if the
204 * timeout expired.
205 *
206 * timo is a timeout in ticks. timo = 0 specifies an infinite timeout.
207 */
208 int
209 cv_timedwait(kcondvar_t *cv, kmutex_t *mtx, int timo)
210 {
211 lwp_t *l = curlwp;
212 int error;
213
214 KASSERT(mutex_owned(mtx));
215
216 cv_enter(cv, mtx, l, false);
217 error = sleepq_block(timo, false);
218 mutex_enter(mtx);
219 return error;
220 }
221
222 /*
223 * cv_timedwait_sig:
224 *
225 * Wait on a condition variable until a timeout expires, awoken or a
226 * signal is received. Will also return early if the process is
227 * exiting. Returns zero if awoken normally, EWOULDBLOCK if the
228 * timeout expires, ERESTART if a signal was received and the system
229 * call is restartable, or EINTR otherwise.
230 *
231 * timo is a timeout in ticks. timo = 0 specifies an infinite timeout.
232 */
233 int
234 cv_timedwait_sig(kcondvar_t *cv, kmutex_t *mtx, int timo)
235 {
236 lwp_t *l = curlwp;
237 int error;
238
239 KASSERT(mutex_owned(mtx));
240
241 cv_enter(cv, mtx, l, true);
242 error = sleepq_block(timo, true);
243 mutex_enter(mtx);
244 return error;
245 }
246
247 /*
248 * cv_timedwaitclock:
249 *
250 * Wait on a condition variable until awoken normally, or the
251 * specified timeout expires according to the provided clock.
252 * Returns zero if awoken normally or EWOULDBLOCK if the timeout
253 * expired. For relative timeouts ((flags & TIMER_ABSTIME) == 0),
254 * updates timeout with the time left.
255 *
256 * timeout == NULL specifies an infinite timeout. epsilon is a
257 * requested maximum error in timeout (excluding spurious
258 * wakeups).
259 */
260 int
261 cv_timedwaitclock(kcondvar_t *cv, kmutex_t *mtx, struct timespec *timeout,
262 clockid_t clockid, int flags, const struct bintime *epsilon)
263 {
264 struct timedwaitclock T = {
265 .timeout = timeout,
266 .clockid = clockid,
267 .flags = flags,
268 .epsilon = epsilon,
269 };
270 int timo;
271 int error;
272
273 if (timeout == NULL) {
274 cv_wait(cv, mtx);
275 return 0;
276 }
277
278 error = timedwaitclock_begin(&T, &timo);
279 if (error)
280 return error;
281 error = cv_timedwait(cv, mtx, timo);
282 timedwaitclock_end(&T);
283 return error;
284 }
285
286 /*
287 * cv_timedwaitclock_sig:
288 *
289 * Wait on a condition variable until awoken normally, interrupted
290 * by a signal, or the specified timeout expires according to the
291 * provided clock. Returns zero if awoken normally,
292 * EINTR/ERESTART if interrupted by a signal, or EWOULDBLOCK if
293 * the timeout expired. For relative timeouts ((flags &
294 * TIMER_ABSTIME) == 0), updates timeout with the time left.
295 *
296 * timeout == NULL specifies an infinite timeout. epsilon is a
297 * requested maximum error in timeout (excluding spurious
298 * wakeups).
299 */
300 int
301 cv_timedwaitclock_sig(kcondvar_t *cv, kmutex_t *mtx, struct timespec *timeout,
302 clockid_t clockid, int flags, const struct bintime *epsilon)
303 {
304 struct timedwaitclock T = {
305 .timeout = timeout,
306 .clockid = clockid,
307 .flags = flags,
308 .epsilon = epsilon,
309 };
310 int timo;
311 int error;
312
313 if (timeout == NULL)
314 return cv_wait_sig(cv, mtx);
315
316 error = timedwaitclock_begin(&T, &timo);
317 if (error)
318 return error;
319 error = cv_timedwait_sig(cv, mtx, timo);
320 timedwaitclock_end(&T);
321 return error;
322 }
323
324 /*
325 * Given a number of seconds, sec, and 2^64ths of a second, frac, we
326 * want a number of ticks for a timeout:
327 *
328 * timo = hz*(sec + frac/2^64)
329 * = hz*sec + hz*frac/2^64
330 * = hz*sec + hz*(frachi*2^32 + fraclo)/2^64
331 * = hz*sec + hz*frachi/2^32 + hz*fraclo/2^64,
332 *
333 * where frachi is the high 32 bits of frac and fraclo is the
334 * low 32 bits.
335 *
336 * We assume hz < INT_MAX/2 < UINT32_MAX, so
337 *
338 * hz*fraclo/2^64 < fraclo*2^32/2^64 <= 1,
339 *
340 * since fraclo < 2^32.
341 *
342 * We clamp the result at INT_MAX/2 for a timeout in ticks, since we
343 * can't represent timeouts higher than INT_MAX in cv_timedwait, and
344 * spurious wakeup is OK. Moreover, we don't want to wrap around,
345 * because we compute end - start in ticks in order to compute the
346 * remaining timeout, and that difference cannot wrap around, so we use
347 * a timeout less than INT_MAX. Using INT_MAX/2 provides plenty of
348 * margin for paranoia and will exceed most waits in practice by far.
349 */
350 static unsigned
351 bintime2timo(const struct bintime *bt)
352 {
353
354 KASSERT(hz < INT_MAX/2);
355 CTASSERT(INT_MAX/2 < UINT32_MAX);
356 if (bt->sec > ((INT_MAX/2)/hz))
357 return INT_MAX/2;
358 if ((hz*(bt->frac >> 32) >> 32) > (INT_MAX/2 - hz*bt->sec))
359 return INT_MAX/2;
360
361 return hz*bt->sec + (hz*(bt->frac >> 32) >> 32);
362 }
363
364 /*
365 * timo is in units of ticks. We want units of seconds and 2^64ths of
366 * a second. We know hz = 1 sec/tick, and 2^64 = 1 sec/(2^64th of a
367 * second), from which we can conclude 2^64 / hz = 1 (2^64th of a
368 * second)/tick. So for the fractional part, we compute
369 *
370 * frac = rem * 2^64 / hz
371 * = ((rem * 2^32) / hz) * 2^32
372 *
373 * Using truncating integer division instead of real division will
374 * leave us with only about 32 bits of precision, which means about
375 * 1/4-nanosecond resolution, which is good enough for our purposes.
376 */
377 static struct bintime
378 timo2bintime(unsigned timo)
379 {
380
381 return (struct bintime) {
382 .sec = timo / hz,
383 .frac = (((uint64_t)(timo % hz) << 32)/hz << 32),
384 };
385 }
386
387 /*
388 * cv_timedwaitbt:
389 *
390 * Wait on a condition variable until awoken or the specified
391 * timeout expires. Returns zero if awoken normally or
392 * EWOULDBLOCK if the timeout expires.
393 *
394 * On entry, bt is a timeout in bintime. cv_timedwaitbt subtracts
395 * the time slept, so on exit, bt is the time remaining after
396 * sleeping, possibly negative if the complete time has elapsed.
397 * No infinite timeout; use cv_wait_sig instead.
398 *
399 * epsilon is a requested maximum error in timeout (excluding
400 * spurious wakeups). Currently not used, will be used in the
401 * future to choose between low- and high-resolution timers.
402 * Actual wakeup time will be somewhere in [t, t + max(e, r) + s)
403 * where r is the finest resolution of clock available and s is
404 * scheduling delays for scheduler overhead and competing threads.
405 * Time is measured by the interrupt source implementing the
406 * timeout, not by another timecounter.
407 */
408 int
409 cv_timedwaitbt(kcondvar_t *cv, kmutex_t *mtx, struct bintime *bt,
410 const struct bintime *epsilon __diagused)
411 {
412 struct bintime slept;
413 unsigned start, end;
414 int timo;
415 int error;
416
417 KASSERTMSG(bt->sec >= 0, "negative timeout");
418 KASSERTMSG(epsilon != NULL, "specify maximum requested delay");
419
420 /* If there's nothing left to wait, time out. */
421 if (bt->sec == 0 && bt->frac == 0)
422 return EWOULDBLOCK;
423
424 /* Convert to ticks, but clamp to be >=1. */
425 timo = bintime2timo(bt);
426 KASSERTMSG(timo >= 0, "negative ticks: %d", timo);
427 if (timo == 0)
428 timo = 1;
429
430 /*
431 * getticks() is technically int, but nothing special
432 * happens instead of overflow, so we assume two's-complement
433 * wraparound and just treat it as unsigned.
434 */
435 start = getticks();
436 error = cv_timedwait(cv, mtx, timo);
437 end = getticks();
438
439 /*
440 * Set it to the time left, or zero, whichever is larger. We
441 * do not fail with EWOULDBLOCK here because this may have been
442 * an explicit wakeup, so the caller needs to check before they
443 * give up or else cv_signal would be lost.
444 */
445 slept = timo2bintime(end - start);
446 if (bintimecmp(bt, &slept, <=)) {
447 bt->sec = 0;
448 bt->frac = 0;
449 } else {
450 /* bt := bt - slept */
451 bintime_sub(bt, &slept);
452 }
453
454 return error;
455 }
456
457 /*
458 * cv_timedwaitbt_sig:
459 *
460 * Wait on a condition variable until awoken, the specified
461 * timeout expires, or interrupted by a signal. Returns zero if
462 * awoken normally, EWOULDBLOCK if the timeout expires, or
463 * EINTR/ERESTART if interrupted by a signal.
464 *
465 * On entry, bt is a timeout in bintime. cv_timedwaitbt_sig
466 * subtracts the time slept, so on exit, bt is the time remaining
467 * after sleeping. No infinite timeout; use cv_wait instead.
468 *
469 * epsilon is a requested maximum error in timeout (excluding
470 * spurious wakeups). Currently not used, will be used in the
471 * future to choose between low- and high-resolution timers.
472 */
473 int
474 cv_timedwaitbt_sig(kcondvar_t *cv, kmutex_t *mtx, struct bintime *bt,
475 const struct bintime *epsilon __diagused)
476 {
477 struct bintime slept;
478 unsigned start, end;
479 int timo;
480 int error;
481
482 KASSERTMSG(bt->sec >= 0, "negative timeout");
483 KASSERTMSG(epsilon != NULL, "specify maximum requested delay");
484
485 /* If there's nothing left to wait, time out. */
486 if (bt->sec == 0 && bt->frac == 0)
487 return EWOULDBLOCK;
488
489 /* Convert to ticks, but clamp to be >=1. */
490 timo = bintime2timo(bt);
491 KASSERTMSG(timo >= 0, "negative ticks: %d", timo);
492 if (timo == 0)
493 timo = 1;
494
495 /*
496 * getticks() is technically int, but nothing special
497 * happens instead of overflow, so we assume two's-complement
498 * wraparound and just treat it as unsigned.
499 */
500 start = getticks();
501 error = cv_timedwait_sig(cv, mtx, timo);
502 end = getticks();
503
504 /*
505 * Set it to the time left, or zero, whichever is larger. We
506 * do not fail with EWOULDBLOCK here because this may have been
507 * an explicit wakeup, so the caller needs to check before they
508 * give up or else cv_signal would be lost.
509 */
510 slept = timo2bintime(end - start);
511 if (bintimecmp(bt, &slept, <=)) {
512 bt->sec = 0;
513 bt->frac = 0;
514 } else {
515 /* bt := bt - slept */
516 bintime_sub(bt, &slept);
517 }
518
519 return error;
520 }
521
522 /*
523 * cv_signal:
524 *
525 * Wake the highest priority LWP waiting on a condition variable.
526 * Must be called with the interlocking mutex held.
527 */
528 void
529 cv_signal(kcondvar_t *cv)
530 {
531
532 KASSERT(cv_is_valid(cv));
533
534 if (__predict_false(!LIST_EMPTY(CV_SLEEPQ(cv))))
535 cv_wakeup_one(cv);
536 }
537
538 /*
539 * cv_wakeup_one:
540 *
541 * Slow path for cv_signal(). Deliberately marked __noinline to
542 * prevent the compiler pulling it in to cv_signal(), which adds
543 * extra prologue and epilogue code.
544 */
545 static __noinline void
546 cv_wakeup_one(kcondvar_t *cv)
547 {
548 sleepq_t *sq;
549 kmutex_t *mp;
550 lwp_t *l;
551
552 /*
553 * Keep waking LWPs until a non-interruptable waiter is found. An
554 * interruptable waiter could fail to do something useful with the
555 * wakeup due to an error return from cv_[timed]wait_sig(), and the
556 * caller of cv_signal() may not expect such a scenario.
557 *
558 * This isn't a problem for non-interruptable waits (untimed and
559 * timed), because if such a waiter is woken here it will not return
560 * an error.
561 */
562 mp = sleepq_hashlock(cv);
563 sq = CV_SLEEPQ(cv);
564 while ((l = LIST_FIRST(sq)) != NULL) {
565 KASSERT(l->l_sleepq == sq);
566 KASSERT(l->l_mutex == mp);
567 KASSERT(l->l_wchan == cv);
568 if ((l->l_flag & LW_SINTR) == 0) {
569 sleepq_remove(sq, l);
570 break;
571 } else
572 sleepq_remove(sq, l);
573 }
574 mutex_spin_exit(mp);
575 }
576
577 /*
578 * cv_broadcast:
579 *
580 * Wake all LWPs waiting on a condition variable. Must be called
581 * with the interlocking mutex held.
582 */
583 void
584 cv_broadcast(kcondvar_t *cv)
585 {
586
587 KASSERT(cv_is_valid(cv));
588
589 if (__predict_false(!LIST_EMPTY(CV_SLEEPQ(cv))))
590 cv_wakeup_all(cv);
591 }
592
593 /*
594 * cv_wakeup_all:
595 *
596 * Slow path for cv_broadcast(). Deliberately marked __noinline to
597 * prevent the compiler pulling it in to cv_broadcast(), which adds
598 * extra prologue and epilogue code.
599 */
600 static __noinline void
601 cv_wakeup_all(kcondvar_t *cv)
602 {
603 sleepq_t *sq;
604 kmutex_t *mp;
605 lwp_t *l;
606
607 mp = sleepq_hashlock(cv);
608 sq = CV_SLEEPQ(cv);
609 while ((l = LIST_FIRST(sq)) != NULL) {
610 KASSERT(l->l_sleepq == sq);
611 KASSERT(l->l_mutex == mp);
612 KASSERT(l->l_wchan == cv);
613 sleepq_remove(sq, l);
614 }
615 mutex_spin_exit(mp);
616 }
617
618 /*
619 * cv_has_waiters:
620 *
621 * For diagnostic assertions: return non-zero if a condition
622 * variable has waiters.
623 */
624 bool
625 cv_has_waiters(kcondvar_t *cv)
626 {
627
628 return !LIST_EMPTY(CV_SLEEPQ(cv));
629 }
630
631 /*
632 * cv_is_valid:
633 *
634 * For diagnostic assertions: return non-zero if a condition
635 * variable appears to be valid. No locks need be held.
636 */
637 bool
638 cv_is_valid(kcondvar_t *cv)
639 {
640
641 return CV_WMESG(cv) != deadcv && CV_WMESG(cv) != NULL;
642 }
643