xref: /freebsd/lib/libthr/thread/thr_cond.c (revision 9f23cbd6cae82fd77edfad7173432fa8dccd0a95)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2005 David Xu <davidxu@freebsd.org>
5  * Copyright (c) 2015 The FreeBSD Foundation
6  * All rights reserved.
7  *
8  * Portions of this software were developed by Konstantin Belousov
9  * under sponsorship from the FreeBSD Foundation.
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 unmodified, this list of conditions, and the following
16  *    disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
22  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
23  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
24  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
26  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35 
36 #include "namespace.h"
37 #include <stdlib.h>
38 #include <errno.h>
39 #include <string.h>
40 #include <pthread.h>
41 #include <limits.h>
42 #include "un-namespace.h"
43 
44 #include "thr_private.h"
45 
46 _Static_assert(sizeof(struct pthread_cond) <= THR_PAGE_SIZE_MIN,
47     "pthread_cond too large");
48 
49 /*
50  * Prototypes
51  */
52 int	__pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex,
53 		       const struct timespec * abstime);
54 static int cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr);
55 static int cond_wait_common(pthread_cond_t *cond, pthread_mutex_t *mutex,
56 		    const struct timespec *abstime, int cancel);
57 static int cond_signal_common(pthread_cond_t *cond);
58 static int cond_broadcast_common(pthread_cond_t *cond);
59 
60 /*
61  * Double underscore versions are cancellation points.  Single underscore
62  * versions are not and are provided for libc internal usage (which
63  * shouldn't introduce cancellation points).
64  */
65 __weak_reference(__thr_cond_wait, pthread_cond_wait);
66 __weak_reference(__thr_cond_wait, __pthread_cond_wait);
67 __weak_reference(_thr_cond_wait, _pthread_cond_wait);
68 __weak_reference(__pthread_cond_timedwait, pthread_cond_timedwait);
69 __weak_reference(_thr_cond_init, pthread_cond_init);
70 __weak_reference(_thr_cond_init, _pthread_cond_init);
71 __weak_reference(_thr_cond_destroy, pthread_cond_destroy);
72 __weak_reference(_thr_cond_destroy, _pthread_cond_destroy);
73 __weak_reference(_thr_cond_signal, pthread_cond_signal);
74 __weak_reference(_thr_cond_signal, _pthread_cond_signal);
75 __weak_reference(_thr_cond_broadcast, pthread_cond_broadcast);
76 __weak_reference(_thr_cond_broadcast, _pthread_cond_broadcast);
77 
78 #define CV_PSHARED(cvp)	(((cvp)->kcond.c_flags & USYNC_PROCESS_SHARED) != 0)
79 
80 static void
81 cond_init_body(struct pthread_cond *cvp, const struct pthread_cond_attr *cattr)
82 {
83 
84 	if (cattr == NULL) {
85 		cvp->kcond.c_clockid = CLOCK_REALTIME;
86 	} else {
87 		if (cattr->c_pshared)
88 			cvp->kcond.c_flags |= USYNC_PROCESS_SHARED;
89 		cvp->kcond.c_clockid = cattr->c_clockid;
90 	}
91 }
92 
93 static int
94 cond_init(pthread_cond_t *cond, const pthread_condattr_t *cond_attr)
95 {
96 	struct pthread_cond *cvp;
97 	const struct pthread_cond_attr *cattr;
98 	int pshared;
99 
100 	cattr = cond_attr != NULL ? *cond_attr : NULL;
101 	if (cattr == NULL || cattr->c_pshared == PTHREAD_PROCESS_PRIVATE) {
102 		pshared = 0;
103 		cvp = calloc(1, sizeof(struct pthread_cond));
104 		if (cvp == NULL)
105 			return (ENOMEM);
106 	} else {
107 		pshared = 1;
108 		cvp = __thr_pshared_offpage(cond, 1);
109 		if (cvp == NULL)
110 			return (EFAULT);
111 	}
112 
113 	/*
114 	 * Initialise the condition variable structure:
115 	 */
116 	cond_init_body(cvp, cattr);
117 	*cond = pshared ? THR_PSHARED_PTR : cvp;
118 	return (0);
119 }
120 
121 static int
122 init_static(struct pthread *thread, pthread_cond_t *cond)
123 {
124 	int ret;
125 
126 	THR_LOCK_ACQUIRE(thread, &_cond_static_lock);
127 
128 	if (*cond == NULL)
129 		ret = cond_init(cond, NULL);
130 	else
131 		ret = 0;
132 
133 	THR_LOCK_RELEASE(thread, &_cond_static_lock);
134 
135 	return (ret);
136 }
137 
138 #define CHECK_AND_INIT_COND							\
139 	if (*cond == THR_PSHARED_PTR) {						\
140 		cvp = __thr_pshared_offpage(cond, 0);				\
141 		if (cvp == NULL)						\
142 			return (EINVAL);					\
143 	} else if (__predict_false((cvp = (*cond)) <= THR_COND_DESTROYED)) {	\
144 		if (cvp == THR_COND_INITIALIZER) {				\
145 			int ret;						\
146 			ret = init_static(_get_curthread(), cond);		\
147 			if (ret)						\
148 				return (ret);					\
149 		} else if (cvp == THR_COND_DESTROYED) {				\
150 			return (EINVAL);					\
151 		}								\
152 		cvp = *cond;							\
153 	}
154 
155 int
156 _thr_cond_init(pthread_cond_t * __restrict cond,
157     const pthread_condattr_t * __restrict cond_attr)
158 {
159 
160 	*cond = NULL;
161 	return (cond_init(cond, cond_attr));
162 }
163 
164 int
165 _thr_cond_destroy(pthread_cond_t *cond)
166 {
167 	struct pthread_cond *cvp;
168 	int error;
169 
170 	error = 0;
171 	if (*cond == THR_PSHARED_PTR) {
172 		cvp = __thr_pshared_offpage(cond, 0);
173 		if (cvp != NULL) {
174 			if (cvp->kcond.c_has_waiters)
175 				error = EBUSY;
176 			else
177 				__thr_pshared_destroy(cond);
178 		}
179 		if (error == 0)
180 			*cond = THR_COND_DESTROYED;
181 	} else if ((cvp = *cond) == THR_COND_INITIALIZER) {
182 		/* nothing */
183 	} else if (cvp == THR_COND_DESTROYED) {
184 		error = EINVAL;
185 	} else {
186 		cvp = *cond;
187 		if (cvp->__has_user_waiters || cvp->kcond.c_has_waiters)
188 			error = EBUSY;
189 		else {
190 			*cond = THR_COND_DESTROYED;
191 			free(cvp);
192 		}
193 	}
194 	return (error);
195 }
196 
197 /*
198  * Cancellation behavior:
199  *   Thread may be canceled at start, if thread is canceled, it means it
200  *   did not get a wakeup from pthread_cond_signal(), otherwise, it is
201  *   not canceled.
202  *   Thread cancellation never cause wakeup from pthread_cond_signal()
203  *   to be lost.
204  */
205 static int
206 cond_wait_kernel(struct pthread_cond *cvp, struct pthread_mutex *mp,
207     const struct timespec *abstime, int cancel)
208 {
209 	struct pthread *curthread;
210 	int error, error2, recurse, robust;
211 
212 	curthread = _get_curthread();
213 	robust = _mutex_enter_robust(curthread, mp);
214 
215 	error = _mutex_cv_detach(mp, &recurse);
216 	if (error != 0) {
217 		if (robust)
218 			_mutex_leave_robust(curthread, mp);
219 		return (error);
220 	}
221 
222 	if (cancel)
223 		_thr_cancel_enter2(curthread, 0);
224 	error = _thr_ucond_wait(&cvp->kcond, &mp->m_lock, abstime,
225 	    CVWAIT_ABSTIME | CVWAIT_CLOCKID);
226 	if (cancel)
227 		_thr_cancel_leave(curthread, 0);
228 
229 	/*
230 	 * Note that PP mutex and ROBUST mutex may return
231 	 * interesting error codes.
232 	 */
233 	if (error == 0) {
234 		error2 = _mutex_cv_lock(mp, recurse, true);
235 	} else if (error == EINTR || error == ETIMEDOUT) {
236 		error2 = _mutex_cv_lock(mp, recurse, true);
237 		/*
238 		 * Do not do cancellation on EOWNERDEAD there.  The
239 		 * cancellation cleanup handler will use the protected
240 		 * state and unlock the mutex without making the state
241 		 * consistent and the state will be unrecoverable.
242 		 */
243 		if (error2 == 0 && cancel) {
244 			if (robust) {
245 				_mutex_leave_robust(curthread, mp);
246 				robust = false;
247 			}
248 			_thr_testcancel(curthread);
249 		}
250 
251 		if (error == EINTR)
252 			error = 0;
253 	} else {
254 		/* We know that it didn't unlock the mutex. */
255 		_mutex_cv_attach(mp, recurse);
256 		if (cancel) {
257 			if (robust) {
258 				_mutex_leave_robust(curthread, mp);
259 				robust = false;
260 			}
261 			_thr_testcancel(curthread);
262 		}
263 		error2 = 0;
264 	}
265 	if (robust)
266 		_mutex_leave_robust(curthread, mp);
267 	return (error2 != 0 ? error2 : error);
268 }
269 
270 /*
271  * Thread waits in userland queue whenever possible, when thread
272  * is signaled or broadcasted, it is removed from the queue, and
273  * is saved in curthread's defer_waiters[] buffer, but won't be
274  * woken up until mutex is unlocked.
275  */
276 
277 static int
278 cond_wait_user(struct pthread_cond *cvp, struct pthread_mutex *mp,
279     const struct timespec *abstime, int cancel)
280 {
281 	struct pthread *curthread;
282 	struct sleepqueue *sq;
283 	int deferred, error, error2, recurse;
284 
285 	curthread = _get_curthread();
286 	if (curthread->wchan != NULL)
287 		PANIC("thread %p was already on queue.", curthread);
288 
289 	if (cancel)
290 		_thr_testcancel(curthread);
291 
292 	_sleepq_lock(cvp);
293 	/*
294 	 * set __has_user_waiters before unlocking mutex, this allows
295 	 * us to check it without locking in pthread_cond_signal().
296 	 */
297 	cvp->__has_user_waiters = 1;
298 	deferred = 0;
299 	(void)_mutex_cv_unlock(mp, &recurse, &deferred);
300 	curthread->mutex_obj = mp;
301 	_sleepq_add(cvp, curthread);
302 	for(;;) {
303 		_thr_clear_wake(curthread);
304 		_sleepq_unlock(cvp);
305 		if (deferred) {
306 			deferred = 0;
307 			if ((mp->m_lock.m_owner & UMUTEX_CONTESTED) == 0)
308 				(void)_umtx_op_err(&mp->m_lock,
309 				    UMTX_OP_MUTEX_WAKE2, mp->m_lock.m_flags,
310 				    0, 0);
311 		}
312 		if (curthread->nwaiter_defer > 0) {
313 			_thr_wake_all(curthread->defer_waiters,
314 			    curthread->nwaiter_defer);
315 			curthread->nwaiter_defer = 0;
316 		}
317 
318 		if (cancel)
319 			_thr_cancel_enter2(curthread, 0);
320 		error = _thr_sleep(curthread, cvp->kcond.c_clockid, abstime);
321 		if (cancel)
322 			_thr_cancel_leave(curthread, 0);
323 
324 		_sleepq_lock(cvp);
325 		if (curthread->wchan == NULL) {
326 			error = 0;
327 			break;
328 		} else if (cancel && SHOULD_CANCEL(curthread)) {
329 			sq = _sleepq_lookup(cvp);
330 			cvp->__has_user_waiters = _sleepq_remove(sq, curthread);
331 			_sleepq_unlock(cvp);
332 			curthread->mutex_obj = NULL;
333 			error2 = _mutex_cv_lock(mp, recurse, false);
334 			if (!THR_IN_CRITICAL(curthread))
335 				_pthread_exit(PTHREAD_CANCELED);
336 			else /* this should not happen */
337 				return (error2);
338 		} else if (error == ETIMEDOUT) {
339 			sq = _sleepq_lookup(cvp);
340 			cvp->__has_user_waiters =
341 			    _sleepq_remove(sq, curthread);
342 			break;
343 		}
344 	}
345 	_sleepq_unlock(cvp);
346 	curthread->mutex_obj = NULL;
347 	error2 = _mutex_cv_lock(mp, recurse, false);
348 	if (error == 0)
349 		error = error2;
350 	return (error);
351 }
352 
353 static int
354 cond_wait_common(pthread_cond_t *cond, pthread_mutex_t *mutex,
355 	const struct timespec *abstime, int cancel)
356 {
357 	struct pthread	*curthread = _get_curthread();
358 	struct pthread_cond *cvp;
359 	struct pthread_mutex *mp;
360 	int	error;
361 
362 	CHECK_AND_INIT_COND
363 
364 	if (*mutex == THR_PSHARED_PTR) {
365 		mp = __thr_pshared_offpage(mutex, 0);
366 		if (mp == NULL)
367 			return (EINVAL);
368 	} else {
369 		mp = *mutex;
370 	}
371 
372 	if ((error = _mutex_owned(curthread, mp)) != 0)
373 		return (error);
374 
375 	if (curthread->attr.sched_policy != SCHED_OTHER ||
376 	    (mp->m_lock.m_flags & (UMUTEX_PRIO_PROTECT | UMUTEX_PRIO_INHERIT |
377 	    USYNC_PROCESS_SHARED)) != 0 || CV_PSHARED(cvp))
378 		return (cond_wait_kernel(cvp, mp, abstime, cancel));
379 	else
380 		return (cond_wait_user(cvp, mp, abstime, cancel));
381 }
382 
383 int
384 _thr_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
385 {
386 
387 	return (cond_wait_common(cond, mutex, NULL, 0));
388 }
389 
390 int
391 __thr_cond_wait(pthread_cond_t * __restrict cond,
392     pthread_mutex_t * __restrict mutex)
393 {
394 
395 	return (cond_wait_common(cond, mutex, NULL, 1));
396 }
397 
398 int
399 _thr_cond_timedwait(pthread_cond_t * __restrict cond,
400     pthread_mutex_t * __restrict mutex,
401     const struct timespec * __restrict abstime)
402 {
403 
404 	if (abstime == NULL || abstime->tv_sec < 0 || abstime->tv_nsec < 0 ||
405 	    abstime->tv_nsec >= 1000000000)
406 		return (EINVAL);
407 
408 	return (cond_wait_common(cond, mutex, abstime, 0));
409 }
410 
411 int
412 __pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex,
413 		       const struct timespec *abstime)
414 {
415 
416 	if (abstime == NULL || abstime->tv_sec < 0 || abstime->tv_nsec < 0 ||
417 	    abstime->tv_nsec >= 1000000000)
418 		return (EINVAL);
419 
420 	return (cond_wait_common(cond, mutex, abstime, 1));
421 }
422 
423 static int
424 cond_signal_common(pthread_cond_t *cond)
425 {
426 	struct pthread	*curthread = _get_curthread();
427 	struct pthread *td;
428 	struct pthread_cond *cvp;
429 	struct pthread_mutex *mp;
430 	struct sleepqueue *sq;
431 	int	*waddr;
432 	int	pshared;
433 
434 	/*
435 	 * If the condition variable is statically initialized, perform dynamic
436 	 * initialization.
437 	 */
438 	CHECK_AND_INIT_COND
439 
440 	pshared = CV_PSHARED(cvp);
441 
442 	_thr_ucond_signal(&cvp->kcond);
443 
444 	if (pshared || cvp->__has_user_waiters == 0)
445 		return (0);
446 
447 	curthread = _get_curthread();
448 	waddr = NULL;
449 	_sleepq_lock(cvp);
450 	sq = _sleepq_lookup(cvp);
451 	if (sq == NULL) {
452 		_sleepq_unlock(cvp);
453 		return (0);
454 	}
455 
456 	td = _sleepq_first(sq);
457 	mp = td->mutex_obj;
458 	cvp->__has_user_waiters = _sleepq_remove(sq, td);
459 	if (PMUTEX_OWNER_ID(mp) == TID(curthread)) {
460 		if (curthread->nwaiter_defer >= MAX_DEFER_WAITERS) {
461 			_thr_wake_all(curthread->defer_waiters,
462 			    curthread->nwaiter_defer);
463 			curthread->nwaiter_defer = 0;
464 		}
465 		curthread->defer_waiters[curthread->nwaiter_defer++] =
466 		    &td->wake_addr->value;
467 		mp->m_flags |= PMUTEX_FLAG_DEFERRED;
468 	} else {
469 		waddr = &td->wake_addr->value;
470 	}
471 	_sleepq_unlock(cvp);
472 	if (waddr != NULL)
473 		_thr_set_wake(waddr);
474 	return (0);
475 }
476 
477 struct broadcast_arg {
478 	struct pthread *curthread;
479 	unsigned int *waddrs[MAX_DEFER_WAITERS];
480 	int count;
481 };
482 
483 static void
484 drop_cb(struct pthread *td, void *arg)
485 {
486 	struct broadcast_arg *ba = arg;
487 	struct pthread_mutex *mp;
488 	struct pthread *curthread = ba->curthread;
489 
490 	mp = td->mutex_obj;
491 	if (PMUTEX_OWNER_ID(mp) == TID(curthread)) {
492 		if (curthread->nwaiter_defer >= MAX_DEFER_WAITERS) {
493 			_thr_wake_all(curthread->defer_waiters,
494 			    curthread->nwaiter_defer);
495 			curthread->nwaiter_defer = 0;
496 		}
497 		curthread->defer_waiters[curthread->nwaiter_defer++] =
498 		    &td->wake_addr->value;
499 		mp->m_flags |= PMUTEX_FLAG_DEFERRED;
500 	} else {
501 		if (ba->count >= MAX_DEFER_WAITERS) {
502 			_thr_wake_all(ba->waddrs, ba->count);
503 			ba->count = 0;
504 		}
505 		ba->waddrs[ba->count++] = &td->wake_addr->value;
506 	}
507 }
508 
509 static int
510 cond_broadcast_common(pthread_cond_t *cond)
511 {
512 	int    pshared;
513 	struct pthread_cond *cvp;
514 	struct sleepqueue *sq;
515 	struct broadcast_arg ba;
516 
517 	/*
518 	 * If the condition variable is statically initialized, perform dynamic
519 	 * initialization.
520 	 */
521 	CHECK_AND_INIT_COND
522 
523 	pshared = CV_PSHARED(cvp);
524 
525 	_thr_ucond_broadcast(&cvp->kcond);
526 
527 	if (pshared || cvp->__has_user_waiters == 0)
528 		return (0);
529 
530 	ba.curthread = _get_curthread();
531 	ba.count = 0;
532 
533 	_sleepq_lock(cvp);
534 	sq = _sleepq_lookup(cvp);
535 	if (sq == NULL) {
536 		_sleepq_unlock(cvp);
537 		return (0);
538 	}
539 	_sleepq_drop(sq, drop_cb, &ba);
540 	cvp->__has_user_waiters = 0;
541 	_sleepq_unlock(cvp);
542 	if (ba.count > 0)
543 		_thr_wake_all(ba.waddrs, ba.count);
544 	return (0);
545 }
546 
547 int
548 _thr_cond_signal(pthread_cond_t * cond)
549 {
550 
551 	return (cond_signal_common(cond));
552 }
553 
554 int
555 _thr_cond_broadcast(pthread_cond_t * cond)
556 {
557 
558 	return (cond_broadcast_common(cond));
559 }
560