Home | History | Annotate | Line # | Download | only in kern
kern_condvar.c revision 1.56
      1 /*	$NetBSD: kern_condvar.c,v 1.56 2023/09/23 18:48:04 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.56 2023/09/23 18:48:04 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 void
    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 
    128 	KASSERT(cv_is_valid(cv));
    129 	KASSERT(!cpu_intr_p());
    130 	KASSERT((l->l_pflag & LP_INTR) == 0 || panicstr != NULL);
    131 
    132 	mp = sleepq_hashlock(cv);
    133 	sq = CV_SLEEPQ(cv);
    134 	sleepq_enter(sq, l, mp);
    135 	sleepq_enqueue(sq, cv, CV_WMESG(cv), &cv_syncobj, catch_p);
    136 	mutex_exit(mtx);
    137 	KASSERT(cv_has_waiters(cv));
    138 }
    139 
    140 /*
    141  * cv_unsleep:
    142  *
    143  *	Remove an LWP from the condition variable and sleep queue.  This
    144  *	is called when the LWP has not been awoken normally but instead
    145  *	interrupted: for example, when a signal is received.  Must be
    146  *	called with the LWP locked.  Will unlock if "unlock" is true.
    147  */
    148 static void
    149 cv_unsleep(lwp_t *l, bool unlock)
    150 {
    151 	kcondvar_t *cv __diagused;
    152 
    153 	cv = (kcondvar_t *)(uintptr_t)l->l_wchan;
    154 
    155 	KASSERT(l->l_wchan == (wchan_t)cv);
    156 	KASSERT(l->l_sleepq == CV_SLEEPQ(cv));
    157 	KASSERT(cv_is_valid(cv));
    158 	KASSERT(cv_has_waiters(cv));
    159 
    160 	sleepq_unsleep(l, unlock);
    161 }
    162 
    163 /*
    164  * cv_wait:
    165  *
    166  *	Wait non-interruptably on a condition variable until awoken.
    167  */
    168 void
    169 cv_wait(kcondvar_t *cv, kmutex_t *mtx)
    170 {
    171 	lwp_t *l = curlwp;
    172 
    173 	KASSERT(mutex_owned(mtx));
    174 
    175 	cv_enter(cv, mtx, l, false);
    176 	(void)sleepq_block(0, false, &cv_syncobj);
    177 	mutex_enter(mtx);
    178 }
    179 
    180 /*
    181  * cv_wait_sig:
    182  *
    183  *	Wait on a condition variable until a awoken or a signal is received.
    184  *	Will also return early if the process is exiting.  Returns zero if
    185  *	awoken normally, ERESTART if a signal was received and the system
    186  *	call is restartable, or EINTR otherwise.
    187  */
    188 int
    189 cv_wait_sig(kcondvar_t *cv, kmutex_t *mtx)
    190 {
    191 	lwp_t *l = curlwp;
    192 	int error;
    193 
    194 	KASSERT(mutex_owned(mtx));
    195 
    196 	cv_enter(cv, mtx, l, true);
    197 	error = sleepq_block(0, true, &cv_syncobj);
    198 	mutex_enter(mtx);
    199 	return error;
    200 }
    201 
    202 /*
    203  * cv_timedwait:
    204  *
    205  *	Wait on a condition variable until awoken or the specified timeout
    206  *	expires.  Returns zero if awoken normally or EWOULDBLOCK if the
    207  *	timeout expired.
    208  *
    209  *	timo is a timeout in ticks.  timo = 0 specifies an infinite timeout.
    210  */
    211 int
    212 cv_timedwait(kcondvar_t *cv, kmutex_t *mtx, int timo)
    213 {
    214 	lwp_t *l = curlwp;
    215 	int error;
    216 
    217 	KASSERT(mutex_owned(mtx));
    218 
    219 	cv_enter(cv, mtx, l, false);
    220 	error = sleepq_block(timo, false, &cv_syncobj);
    221 	mutex_enter(mtx);
    222 	return error;
    223 }
    224 
    225 /*
    226  * cv_timedwait_sig:
    227  *
    228  *	Wait on a condition variable until a timeout expires, awoken or a
    229  *	signal is received.  Will also return early if the process is
    230  *	exiting.  Returns zero if awoken normally, EWOULDBLOCK if the
    231  *	timeout expires, ERESTART if a signal was received and the system
    232  *	call is restartable, or EINTR otherwise.
    233  *
    234  *	timo is a timeout in ticks.  timo = 0 specifies an infinite timeout.
    235  */
    236 int
    237 cv_timedwait_sig(kcondvar_t *cv, kmutex_t *mtx, int timo)
    238 {
    239 	lwp_t *l = curlwp;
    240 	int error;
    241 
    242 	KASSERT(mutex_owned(mtx));
    243 
    244 	cv_enter(cv, mtx, l, true);
    245 	error = sleepq_block(timo, true, &cv_syncobj);
    246 	mutex_enter(mtx);
    247 	return error;
    248 }
    249 
    250 /*
    251  * Given a number of seconds, sec, and 2^64ths of a second, frac, we
    252  * want a number of ticks for a timeout:
    253  *
    254  *	timo = hz*(sec + frac/2^64)
    255  *	     = hz*sec + hz*frac/2^64
    256  *	     = hz*sec + hz*(frachi*2^32 + fraclo)/2^64
    257  *	     = hz*sec + hz*frachi/2^32 + hz*fraclo/2^64,
    258  *
    259  * where frachi is the high 32 bits of frac and fraclo is the
    260  * low 32 bits.
    261  *
    262  * We assume hz < INT_MAX/2 < UINT32_MAX, so
    263  *
    264  *	hz*fraclo/2^64 < fraclo*2^32/2^64 <= 1,
    265  *
    266  * since fraclo < 2^32.
    267  *
    268  * We clamp the result at INT_MAX/2 for a timeout in ticks, since we
    269  * can't represent timeouts higher than INT_MAX in cv_timedwait, and
    270  * spurious wakeup is OK.  Moreover, we don't want to wrap around,
    271  * because we compute end - start in ticks in order to compute the
    272  * remaining timeout, and that difference cannot wrap around, so we use
    273  * a timeout less than INT_MAX.  Using INT_MAX/2 provides plenty of
    274  * margin for paranoia and will exceed most waits in practice by far.
    275  */
    276 static unsigned
    277 bintime2timo(const struct bintime *bt)
    278 {
    279 
    280 	KASSERT(hz < INT_MAX/2);
    281 	CTASSERT(INT_MAX/2 < UINT32_MAX);
    282 	if (bt->sec > ((INT_MAX/2)/hz))
    283 		return INT_MAX/2;
    284 	if ((hz*(bt->frac >> 32) >> 32) > (INT_MAX/2 - hz*bt->sec))
    285 		return INT_MAX/2;
    286 
    287 	return hz*bt->sec + (hz*(bt->frac >> 32) >> 32);
    288 }
    289 
    290 /*
    291  * timo is in units of ticks.  We want units of seconds and 2^64ths of
    292  * a second.  We know hz = 1 sec/tick, and 2^64 = 1 sec/(2^64th of a
    293  * second), from which we can conclude 2^64 / hz = 1 (2^64th of a
    294  * second)/tick.  So for the fractional part, we compute
    295  *
    296  *	frac = rem * 2^64 / hz
    297  *	     = ((rem * 2^32) / hz) * 2^32
    298  *
    299  * Using truncating integer division instead of real division will
    300  * leave us with only about 32 bits of precision, which means about
    301  * 1/4-nanosecond resolution, which is good enough for our purposes.
    302  */
    303 static struct bintime
    304 timo2bintime(unsigned timo)
    305 {
    306 
    307 	return (struct bintime) {
    308 		.sec = timo / hz,
    309 		.frac = (((uint64_t)(timo % hz) << 32)/hz << 32),
    310 	};
    311 }
    312 
    313 /*
    314  * cv_timedwaitbt:
    315  *
    316  *	Wait on a condition variable until awoken or the specified
    317  *	timeout expires.  Returns zero if awoken normally or
    318  *	EWOULDBLOCK if the timeout expires.
    319  *
    320  *	On entry, bt is a timeout in bintime.  cv_timedwaitbt subtracts
    321  *	the time slept, so on exit, bt is the time remaining after
    322  *	sleeping, possibly negative if the complete time has elapsed.
    323  *	No infinite timeout; use cv_wait_sig instead.
    324  *
    325  *	epsilon is a requested maximum error in timeout (excluding
    326  *	spurious wakeups).  Currently not used, will be used in the
    327  *	future to choose between low- and high-resolution timers.
    328  *	Actual wakeup time will be somewhere in [t, t + max(e, r) + s)
    329  *	where r is the finest resolution of clock available and s is
    330  *	scheduling delays for scheduler overhead and competing threads.
    331  *	Time is measured by the interrupt source implementing the
    332  *	timeout, not by another timecounter.
    333  */
    334 int
    335 cv_timedwaitbt(kcondvar_t *cv, kmutex_t *mtx, struct bintime *bt,
    336     const struct bintime *epsilon __diagused)
    337 {
    338 	struct bintime slept;
    339 	unsigned start, end;
    340 	int timo;
    341 	int error;
    342 
    343 	KASSERTMSG(bt->sec >= 0, "negative timeout");
    344 	KASSERTMSG(epsilon != NULL, "specify maximum requested delay");
    345 
    346 	/* If there's nothing left to wait, time out.  */
    347 	if (bt->sec == 0 && bt->frac == 0)
    348 		return EWOULDBLOCK;
    349 
    350 	/* Convert to ticks, but clamp to be >=1.  */
    351 	timo = bintime2timo(bt);
    352 	KASSERTMSG(timo >= 0, "negative ticks: %d", timo);
    353 	if (timo == 0)
    354 		timo = 1;
    355 
    356 	/*
    357 	 * getticks() is technically int, but nothing special
    358 	 * happens instead of overflow, so we assume two's-complement
    359 	 * wraparound and just treat it as unsigned.
    360 	 */
    361 	start = getticks();
    362 	error = cv_timedwait(cv, mtx, timo);
    363 	end = getticks();
    364 
    365 	/*
    366 	 * Set it to the time left, or zero, whichever is larger.  We
    367 	 * do not fail with EWOULDBLOCK here because this may have been
    368 	 * an explicit wakeup, so the caller needs to check before they
    369 	 * give up or else cv_signal would be lost.
    370 	 */
    371 	slept = timo2bintime(end - start);
    372 	if (bintimecmp(bt, &slept, <=)) {
    373 		bt->sec = 0;
    374 		bt->frac = 0;
    375 	} else {
    376 		/* bt := bt - slept */
    377 		bintime_sub(bt, &slept);
    378 	}
    379 
    380 	return error;
    381 }
    382 
    383 /*
    384  * cv_timedwaitbt_sig:
    385  *
    386  *	Wait on a condition variable until awoken, the specified
    387  *	timeout expires, or interrupted by a signal.  Returns zero if
    388  *	awoken normally, EWOULDBLOCK if the timeout expires, or
    389  *	EINTR/ERESTART if interrupted by a signal.
    390  *
    391  *	On entry, bt is a timeout in bintime.  cv_timedwaitbt_sig
    392  *	subtracts the time slept, so on exit, bt is the time remaining
    393  *	after sleeping.  No infinite timeout; use cv_wait instead.
    394  *
    395  *	epsilon is a requested maximum error in timeout (excluding
    396  *	spurious wakeups).  Currently not used, will be used in the
    397  *	future to choose between low- and high-resolution timers.
    398  */
    399 int
    400 cv_timedwaitbt_sig(kcondvar_t *cv, kmutex_t *mtx, struct bintime *bt,
    401     const struct bintime *epsilon __diagused)
    402 {
    403 	struct bintime slept;
    404 	unsigned start, end;
    405 	int timo;
    406 	int error;
    407 
    408 	KASSERTMSG(bt->sec >= 0, "negative timeout");
    409 	KASSERTMSG(epsilon != NULL, "specify maximum requested delay");
    410 
    411 	/* If there's nothing left to wait, time out.  */
    412 	if (bt->sec == 0 && bt->frac == 0)
    413 		return EWOULDBLOCK;
    414 
    415 	/* Convert to ticks, but clamp to be >=1.  */
    416 	timo = bintime2timo(bt);
    417 	KASSERTMSG(timo >= 0, "negative ticks: %d", timo);
    418 	if (timo == 0)
    419 		timo = 1;
    420 
    421 	/*
    422 	 * getticks() is technically int, but nothing special
    423 	 * happens instead of overflow, so we assume two's-complement
    424 	 * wraparound and just treat it as unsigned.
    425 	 */
    426 	start = getticks();
    427 	error = cv_timedwait_sig(cv, mtx, timo);
    428 	end = getticks();
    429 
    430 	/*
    431 	 * Set it to the time left, or zero, whichever is larger.  We
    432 	 * do not fail with EWOULDBLOCK here because this may have been
    433 	 * an explicit wakeup, so the caller needs to check before they
    434 	 * give up or else cv_signal would be lost.
    435 	 */
    436 	slept = timo2bintime(end - start);
    437 	if (bintimecmp(bt, &slept, <=)) {
    438 		bt->sec = 0;
    439 		bt->frac = 0;
    440 	} else {
    441 		/* bt := bt - slept */
    442 		bintime_sub(bt, &slept);
    443 	}
    444 
    445 	return error;
    446 }
    447 
    448 /*
    449  * cv_signal:
    450  *
    451  *	Wake the highest priority LWP waiting on a condition variable.
    452  *	Must be called with the interlocking mutex held.
    453  */
    454 void
    455 cv_signal(kcondvar_t *cv)
    456 {
    457 
    458 	KASSERT(cv_is_valid(cv));
    459 
    460 	if (__predict_false(!LIST_EMPTY(CV_SLEEPQ(cv))))
    461 		cv_wakeup_one(cv);
    462 }
    463 
    464 /*
    465  * cv_wakeup_one:
    466  *
    467  *	Slow path for cv_signal().  Deliberately marked __noinline to
    468  *	prevent the compiler pulling it in to cv_signal(), which adds
    469  *	extra prologue and epilogue code.
    470  */
    471 static __noinline void
    472 cv_wakeup_one(kcondvar_t *cv)
    473 {
    474 	sleepq_t *sq;
    475 	kmutex_t *mp;
    476 	lwp_t *l;
    477 
    478 	/*
    479 	 * Keep waking LWPs until a non-interruptable waiter is found.  An
    480 	 * interruptable waiter could fail to do something useful with the
    481 	 * wakeup due to an error return from cv_[timed]wait_sig(), and the
    482 	 * caller of cv_signal() may not expect such a scenario.
    483 	 *
    484 	 * This isn't a problem for non-interruptable waits (untimed and
    485 	 * timed), because if such a waiter is woken here it will not return
    486 	 * an error.
    487 	 */
    488 	mp = sleepq_hashlock(cv);
    489 	sq = CV_SLEEPQ(cv);
    490 	while ((l = LIST_FIRST(sq)) != NULL) {
    491 		KASSERT(l->l_sleepq == sq);
    492 		KASSERT(l->l_mutex == mp);
    493 		KASSERT(l->l_wchan == cv);
    494 		if ((l->l_flag & LW_SINTR) == 0) {
    495 			sleepq_remove(sq, l);
    496 			break;
    497 		} else
    498 			sleepq_remove(sq, l);
    499 	}
    500 	mutex_spin_exit(mp);
    501 }
    502 
    503 /*
    504  * cv_broadcast:
    505  *
    506  *	Wake all LWPs waiting on a condition variable.  Must be called
    507  *	with the interlocking mutex held.
    508  */
    509 void
    510 cv_broadcast(kcondvar_t *cv)
    511 {
    512 
    513 	KASSERT(cv_is_valid(cv));
    514 
    515 	if (__predict_false(!LIST_EMPTY(CV_SLEEPQ(cv))))
    516 		cv_wakeup_all(cv);
    517 }
    518 
    519 /*
    520  * cv_wakeup_all:
    521  *
    522  *	Slow path for cv_broadcast().  Deliberately marked __noinline to
    523  *	prevent the compiler pulling it in to cv_broadcast(), which adds
    524  *	extra prologue and epilogue code.
    525  */
    526 static __noinline void
    527 cv_wakeup_all(kcondvar_t *cv)
    528 {
    529 	sleepq_t *sq;
    530 	kmutex_t *mp;
    531 	lwp_t *l;
    532 
    533 	mp = sleepq_hashlock(cv);
    534 	sq = CV_SLEEPQ(cv);
    535 	while ((l = LIST_FIRST(sq)) != NULL) {
    536 		KASSERT(l->l_sleepq == sq);
    537 		KASSERT(l->l_mutex == mp);
    538 		KASSERT(l->l_wchan == cv);
    539 		sleepq_remove(sq, l);
    540 	}
    541 	mutex_spin_exit(mp);
    542 }
    543 
    544 /*
    545  * cv_has_waiters:
    546  *
    547  *	For diagnostic assertions: return non-zero if a condition
    548  *	variable has waiters.
    549  */
    550 bool
    551 cv_has_waiters(kcondvar_t *cv)
    552 {
    553 
    554 	return !LIST_EMPTY(CV_SLEEPQ(cv));
    555 }
    556 
    557 /*
    558  * cv_is_valid:
    559  *
    560  *	For diagnostic assertions: return non-zero if a condition
    561  *	variable appears to be valid.  No locks need be held.
    562  */
    563 bool
    564 cv_is_valid(kcondvar_t *cv)
    565 {
    566 
    567 	return CV_WMESG(cv) != deadcv && CV_WMESG(cv) != NULL;
    568 }
    569