kern_condvar.c revision 1.58 1 /* $NetBSD: kern_condvar.c,v 1.58 2023/10/08 13:23:05 ad Exp $ */
2
3 /*-
4 * Copyright (c) 2006, 2007, 2008, 2019, 2020, 2023
5 * The NetBSD Foundation, Inc.
6 * All rights reserved.
7 *
8 * This code is derived from software contributed to The NetBSD Foundation
9 * by Andrew Doran.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
31 */
32
33 /*
34 * Kernel condition variable implementation.
35 */
36
37 #include <sys/cdefs.h>
38 __KERNEL_RCSID(0, "$NetBSD: kern_condvar.c,v 1.58 2023/10/08 13:23:05 ad Exp $");
39
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/lwp.h>
43 #include <sys/condvar.h>
44 #include <sys/sleepq.h>
45 #include <sys/lockdebug.h>
46 #include <sys/cpu.h>
47 #include <sys/kernel.h>
48
49 /*
50 * Accessors for the private contents of the kcondvar_t data type.
51 *
52 * cv_opaque[0] sleepq_t
53 * cv_opaque[1] description for ps(1)
54 *
55 * cv_opaque[0] is protected by the interlock passed to cv_wait() (enqueue
56 * only), and the sleep queue lock acquired with sleepq_hashlock() (enqueue
57 * and dequeue).
58 *
59 * cv_opaque[1] (the wmesg) is static and does not change throughout the life
60 * of the CV.
61 */
62 #define CV_SLEEPQ(cv) ((sleepq_t *)(cv)->cv_opaque)
63 #define CV_WMESG(cv) ((const char *)(cv)->cv_opaque[1])
64 #define CV_SET_WMESG(cv, v) (cv)->cv_opaque[1] = __UNCONST(v)
65
66 #define CV_DEBUG_P(cv) (CV_WMESG(cv) != nodebug)
67 #define CV_RA ((uintptr_t)__builtin_return_address(0))
68
69 static void cv_unsleep(lwp_t *, bool);
70 static inline void cv_wakeup_one(kcondvar_t *);
71 static inline void cv_wakeup_all(kcondvar_t *);
72
73 syncobj_t cv_syncobj = {
74 .sobj_name = "cv",
75 .sobj_flag = SOBJ_SLEEPQ_SORTED,
76 .sobj_boostpri = PRI_KERNEL,
77 .sobj_unsleep = cv_unsleep,
78 .sobj_changepri = sleepq_changepri,
79 .sobj_lendpri = sleepq_lendpri,
80 .sobj_owner = syncobj_noowner,
81 };
82
83 static const char deadcv[] = "deadcv";
84
85 /*
86 * cv_init:
87 *
88 * Initialize a condition variable for use.
89 */
90 void
91 cv_init(kcondvar_t *cv, const char *wmesg)
92 {
93
94 KASSERT(wmesg != NULL);
95 CV_SET_WMESG(cv, wmesg);
96 sleepq_init(CV_SLEEPQ(cv));
97 }
98
99 /*
100 * cv_destroy:
101 *
102 * Tear down a condition variable.
103 */
104 void
105 cv_destroy(kcondvar_t *cv)
106 {
107
108 sleepq_destroy(CV_SLEEPQ(cv));
109 #ifdef DIAGNOSTIC
110 KASSERT(cv_is_valid(cv));
111 KASSERT(!cv_has_waiters(cv));
112 CV_SET_WMESG(cv, deadcv);
113 #endif
114 }
115
116 /*
117 * cv_enter:
118 *
119 * Look up and lock the sleep queue corresponding to the given
120 * condition variable, and increment the number of waiters.
121 */
122 static inline int
123 cv_enter(kcondvar_t *cv, kmutex_t *mtx, lwp_t *l, bool catch_p)
124 {
125 sleepq_t *sq;
126 kmutex_t *mp;
127 int nlocks;
128
129 KASSERT(cv_is_valid(cv));
130 KASSERT(!cpu_intr_p());
131 KASSERT((l->l_pflag & LP_INTR) == 0 || panicstr != NULL);
132
133 mp = sleepq_hashlock(cv);
134 sq = CV_SLEEPQ(cv);
135 nlocks = sleepq_enter(sq, l, mp);
136 sleepq_enqueue(sq, cv, CV_WMESG(cv), &cv_syncobj, catch_p);
137 mutex_exit(mtx);
138 KASSERT(cv_has_waiters(cv));
139 return nlocks;
140 }
141
142 /*
143 * cv_unsleep:
144 *
145 * Remove an LWP from the condition variable and sleep queue. This
146 * is called when the LWP has not been awoken normally but instead
147 * interrupted: for example, when a signal is received. Must be
148 * called with the LWP locked. Will unlock if "unlock" is true.
149 */
150 static void
151 cv_unsleep(lwp_t *l, bool unlock)
152 {
153 kcondvar_t *cv __diagused;
154
155 cv = (kcondvar_t *)(uintptr_t)l->l_wchan;
156
157 KASSERT(l->l_wchan == (wchan_t)cv);
158 KASSERT(l->l_sleepq == CV_SLEEPQ(cv));
159 KASSERT(cv_is_valid(cv));
160 KASSERT(cv_has_waiters(cv));
161
162 sleepq_unsleep(l, unlock);
163 }
164
165 /*
166 * cv_wait:
167 *
168 * Wait non-interruptably on a condition variable until awoken.
169 */
170 void
171 cv_wait(kcondvar_t *cv, kmutex_t *mtx)
172 {
173 lwp_t *l = curlwp;
174 int nlocks;
175
176 KASSERT(mutex_owned(mtx));
177
178 nlocks = cv_enter(cv, mtx, l, false);
179 (void)sleepq_block(0, false, &cv_syncobj, nlocks);
180 mutex_enter(mtx);
181 }
182
183 /*
184 * cv_wait_sig:
185 *
186 * Wait on a condition variable until a awoken or a signal is received.
187 * Will also return early if the process is exiting. Returns zero if
188 * awoken normally, ERESTART if a signal was received and the system
189 * call is restartable, or EINTR otherwise.
190 */
191 int
192 cv_wait_sig(kcondvar_t *cv, kmutex_t *mtx)
193 {
194 lwp_t *l = curlwp;
195 int error, nlocks;
196
197 KASSERT(mutex_owned(mtx));
198
199 nlocks = cv_enter(cv, mtx, l, true);
200 error = sleepq_block(0, true, &cv_syncobj, nlocks);
201 mutex_enter(mtx);
202 return error;
203 }
204
205 /*
206 * cv_timedwait:
207 *
208 * Wait on a condition variable until awoken or the specified timeout
209 * expires. Returns zero if awoken normally or EWOULDBLOCK if the
210 * timeout expired.
211 *
212 * timo is a timeout in ticks. timo = 0 specifies an infinite timeout.
213 */
214 int
215 cv_timedwait(kcondvar_t *cv, kmutex_t *mtx, int timo)
216 {
217 lwp_t *l = curlwp;
218 int error, nlocks;
219
220 KASSERT(mutex_owned(mtx));
221
222 nlocks = cv_enter(cv, mtx, l, false);
223 error = sleepq_block(timo, false, &cv_syncobj, nlocks);
224 mutex_enter(mtx);
225 return error;
226 }
227
228 /*
229 * cv_timedwait_sig:
230 *
231 * Wait on a condition variable until a timeout expires, awoken or a
232 * signal is received. Will also return early if the process is
233 * exiting. Returns zero if awoken normally, EWOULDBLOCK if the
234 * timeout expires, ERESTART if a signal was received and the system
235 * call is restartable, or EINTR otherwise.
236 *
237 * timo is a timeout in ticks. timo = 0 specifies an infinite timeout.
238 */
239 int
240 cv_timedwait_sig(kcondvar_t *cv, kmutex_t *mtx, int timo)
241 {
242 lwp_t *l = curlwp;
243 int error, nlocks;
244
245 KASSERT(mutex_owned(mtx));
246
247 nlocks = cv_enter(cv, mtx, l, true);
248 error = sleepq_block(timo, true, &cv_syncobj, nlocks);
249 mutex_enter(mtx);
250 return error;
251 }
252
253 /*
254 * Given a number of seconds, sec, and 2^64ths of a second, frac, we
255 * want a number of ticks for a timeout:
256 *
257 * timo = hz*(sec + frac/2^64)
258 * = hz*sec + hz*frac/2^64
259 * = hz*sec + hz*(frachi*2^32 + fraclo)/2^64
260 * = hz*sec + hz*frachi/2^32 + hz*fraclo/2^64,
261 *
262 * where frachi is the high 32 bits of frac and fraclo is the
263 * low 32 bits.
264 *
265 * We assume hz < INT_MAX/2 < UINT32_MAX, so
266 *
267 * hz*fraclo/2^64 < fraclo*2^32/2^64 <= 1,
268 *
269 * since fraclo < 2^32.
270 *
271 * We clamp the result at INT_MAX/2 for a timeout in ticks, since we
272 * can't represent timeouts higher than INT_MAX in cv_timedwait, and
273 * spurious wakeup is OK. Moreover, we don't want to wrap around,
274 * because we compute end - start in ticks in order to compute the
275 * remaining timeout, and that difference cannot wrap around, so we use
276 * a timeout less than INT_MAX. Using INT_MAX/2 provides plenty of
277 * margin for paranoia and will exceed most waits in practice by far.
278 */
279 static unsigned
280 bintime2timo(const struct bintime *bt)
281 {
282
283 KASSERT(hz < INT_MAX/2);
284 CTASSERT(INT_MAX/2 < UINT32_MAX);
285 if (bt->sec > ((INT_MAX/2)/hz))
286 return INT_MAX/2;
287 if ((hz*(bt->frac >> 32) >> 32) > (INT_MAX/2 - hz*bt->sec))
288 return INT_MAX/2;
289
290 return hz*bt->sec + (hz*(bt->frac >> 32) >> 32);
291 }
292
293 /*
294 * timo is in units of ticks. We want units of seconds and 2^64ths of
295 * a second. We know hz = 1 sec/tick, and 2^64 = 1 sec/(2^64th of a
296 * second), from which we can conclude 2^64 / hz = 1 (2^64th of a
297 * second)/tick. So for the fractional part, we compute
298 *
299 * frac = rem * 2^64 / hz
300 * = ((rem * 2^32) / hz) * 2^32
301 *
302 * Using truncating integer division instead of real division will
303 * leave us with only about 32 bits of precision, which means about
304 * 1/4-nanosecond resolution, which is good enough for our purposes.
305 */
306 static struct bintime
307 timo2bintime(unsigned timo)
308 {
309
310 return (struct bintime) {
311 .sec = timo / hz,
312 .frac = (((uint64_t)(timo % hz) << 32)/hz << 32),
313 };
314 }
315
316 /*
317 * cv_timedwaitbt:
318 *
319 * Wait on a condition variable until awoken or the specified
320 * timeout expires. Returns zero if awoken normally or
321 * EWOULDBLOCK if the timeout expires.
322 *
323 * On entry, bt is a timeout in bintime. cv_timedwaitbt subtracts
324 * the time slept, so on exit, bt is the time remaining after
325 * sleeping, possibly negative if the complete time has elapsed.
326 * No infinite timeout; use cv_wait_sig instead.
327 *
328 * epsilon is a requested maximum error in timeout (excluding
329 * spurious wakeups). Currently not used, will be used in the
330 * future to choose between low- and high-resolution timers.
331 * Actual wakeup time will be somewhere in [t, t + max(e, r) + s)
332 * where r is the finest resolution of clock available and s is
333 * scheduling delays for scheduler overhead and competing threads.
334 * Time is measured by the interrupt source implementing the
335 * timeout, not by another timecounter.
336 */
337 int
338 cv_timedwaitbt(kcondvar_t *cv, kmutex_t *mtx, struct bintime *bt,
339 const struct bintime *epsilon __diagused)
340 {
341 struct bintime slept;
342 unsigned start, end;
343 int timo;
344 int error;
345
346 KASSERTMSG(bt->sec >= 0, "negative timeout");
347 KASSERTMSG(epsilon != NULL, "specify maximum requested delay");
348
349 /* If there's nothing left to wait, time out. */
350 if (bt->sec == 0 && bt->frac == 0)
351 return EWOULDBLOCK;
352
353 /* Convert to ticks, but clamp to be >=1. */
354 timo = bintime2timo(bt);
355 KASSERTMSG(timo >= 0, "negative ticks: %d", timo);
356 if (timo == 0)
357 timo = 1;
358
359 /*
360 * getticks() is technically int, but nothing special
361 * happens instead of overflow, so we assume two's-complement
362 * wraparound and just treat it as unsigned.
363 */
364 start = getticks();
365 error = cv_timedwait(cv, mtx, timo);
366 end = getticks();
367
368 /*
369 * Set it to the time left, or zero, whichever is larger. We
370 * do not fail with EWOULDBLOCK here because this may have been
371 * an explicit wakeup, so the caller needs to check before they
372 * give up or else cv_signal would be lost.
373 */
374 slept = timo2bintime(end - start);
375 if (bintimecmp(bt, &slept, <=)) {
376 bt->sec = 0;
377 bt->frac = 0;
378 } else {
379 /* bt := bt - slept */
380 bintime_sub(bt, &slept);
381 }
382
383 return error;
384 }
385
386 /*
387 * cv_timedwaitbt_sig:
388 *
389 * Wait on a condition variable until awoken, the specified
390 * timeout expires, or interrupted by a signal. Returns zero if
391 * awoken normally, EWOULDBLOCK if the timeout expires, or
392 * EINTR/ERESTART if interrupted by a signal.
393 *
394 * On entry, bt is a timeout in bintime. cv_timedwaitbt_sig
395 * subtracts the time slept, so on exit, bt is the time remaining
396 * after sleeping. No infinite timeout; use cv_wait instead.
397 *
398 * epsilon is a requested maximum error in timeout (excluding
399 * spurious wakeups). Currently not used, will be used in the
400 * future to choose between low- and high-resolution timers.
401 */
402 int
403 cv_timedwaitbt_sig(kcondvar_t *cv, kmutex_t *mtx, struct bintime *bt,
404 const struct bintime *epsilon __diagused)
405 {
406 struct bintime slept;
407 unsigned start, end;
408 int timo;
409 int error;
410
411 KASSERTMSG(bt->sec >= 0, "negative timeout");
412 KASSERTMSG(epsilon != NULL, "specify maximum requested delay");
413
414 /* If there's nothing left to wait, time out. */
415 if (bt->sec == 0 && bt->frac == 0)
416 return EWOULDBLOCK;
417
418 /* Convert to ticks, but clamp to be >=1. */
419 timo = bintime2timo(bt);
420 KASSERTMSG(timo >= 0, "negative ticks: %d", timo);
421 if (timo == 0)
422 timo = 1;
423
424 /*
425 * getticks() is technically int, but nothing special
426 * happens instead of overflow, so we assume two's-complement
427 * wraparound and just treat it as unsigned.
428 */
429 start = getticks();
430 error = cv_timedwait_sig(cv, mtx, timo);
431 end = getticks();
432
433 /*
434 * Set it to the time left, or zero, whichever is larger. We
435 * do not fail with EWOULDBLOCK here because this may have been
436 * an explicit wakeup, so the caller needs to check before they
437 * give up or else cv_signal would be lost.
438 */
439 slept = timo2bintime(end - start);
440 if (bintimecmp(bt, &slept, <=)) {
441 bt->sec = 0;
442 bt->frac = 0;
443 } else {
444 /* bt := bt - slept */
445 bintime_sub(bt, &slept);
446 }
447
448 return error;
449 }
450
451 /*
452 * cv_signal:
453 *
454 * Wake the highest priority LWP waiting on a condition variable.
455 * Must be called with the interlocking mutex held.
456 */
457 void
458 cv_signal(kcondvar_t *cv)
459 {
460
461 KASSERT(cv_is_valid(cv));
462
463 if (__predict_false(!LIST_EMPTY(CV_SLEEPQ(cv))))
464 cv_wakeup_one(cv);
465 }
466
467 /*
468 * cv_wakeup_one:
469 *
470 * Slow path for cv_signal(). Deliberately marked __noinline to
471 * prevent the compiler pulling it in to cv_signal(), which adds
472 * extra prologue and epilogue code.
473 */
474 static __noinline void
475 cv_wakeup_one(kcondvar_t *cv)
476 {
477 sleepq_t *sq;
478 kmutex_t *mp;
479 lwp_t *l;
480
481 mp = sleepq_hashlock(cv);
482 sq = CV_SLEEPQ(cv);
483 if (__predict_true((l = LIST_FIRST(sq)) != NULL)) {
484 KASSERT(l->l_sleepq == sq);
485 KASSERT(l->l_mutex == mp);
486 KASSERT(l->l_wchan == cv);
487 sleepq_remove(sq, l, true);
488 }
489 mutex_spin_exit(mp);
490 }
491
492 /*
493 * cv_broadcast:
494 *
495 * Wake all LWPs waiting on a condition variable. Must be called
496 * with the interlocking mutex held.
497 */
498 void
499 cv_broadcast(kcondvar_t *cv)
500 {
501
502 KASSERT(cv_is_valid(cv));
503
504 if (__predict_false(!LIST_EMPTY(CV_SLEEPQ(cv))))
505 cv_wakeup_all(cv);
506 }
507
508 /*
509 * cv_wakeup_all:
510 *
511 * Slow path for cv_broadcast(). Deliberately marked __noinline to
512 * prevent the compiler pulling it in to cv_broadcast(), which adds
513 * extra prologue and epilogue code.
514 */
515 static __noinline void
516 cv_wakeup_all(kcondvar_t *cv)
517 {
518 sleepq_t *sq;
519 kmutex_t *mp;
520 lwp_t *l;
521
522 mp = sleepq_hashlock(cv);
523 sq = CV_SLEEPQ(cv);
524 while ((l = LIST_FIRST(sq)) != NULL) {
525 KASSERT(l->l_sleepq == sq);
526 KASSERT(l->l_mutex == mp);
527 KASSERT(l->l_wchan == cv);
528 sleepq_remove(sq, l, true);
529 }
530 mutex_spin_exit(mp);
531 }
532
533 /*
534 * cv_has_waiters:
535 *
536 * For diagnostic assertions: return non-zero if a condition
537 * variable has waiters.
538 */
539 bool
540 cv_has_waiters(kcondvar_t *cv)
541 {
542
543 return !LIST_EMPTY(CV_SLEEPQ(cv));
544 }
545
546 /*
547 * cv_is_valid:
548 *
549 * For diagnostic assertions: return non-zero if a condition
550 * variable appears to be valid. No locks need be held.
551 */
552 bool
553 cv_is_valid(kcondvar_t *cv)
554 {
555
556 return CV_WMESG(cv) != deadcv && CV_WMESG(cv) != NULL;
557 }
558