xref: /freebsd/lib/libthr/thread/thr_cond.c (revision a259b98fa211ed87bfee58c575de4e2de94ee0fa)
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 "namespace.h"
34 #include <stdlib.h>
35 #include <errno.h>
36 #include <string.h>
37 #include <pthread.h>
38 #include <limits.h>
39 #include "un-namespace.h"
40 
41 #include "thr_private.h"
42 
43 _Static_assert(sizeof(struct pthread_cond) <= THR_PAGE_SIZE_MIN,
44     "pthread_cond too large");
45 
46 /*
47  * Prototypes
48  */
49 int __pthread_cond_clockwait(pthread_cond_t *cond, pthread_mutex_t *mutex,
50     clockid_t clockid, const struct timespec *abstime);
51 int __pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex,
52     const struct timespec * abstime);
53 static int cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr);
54 static int cond_wait_common(pthread_cond_t *cond, pthread_mutex_t *mutex,
55     clockid_t clockid, const struct timespec *abstime, bool cancel,
56     bool clockwait);
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_timedwait, _pthread_cond_timedwait);
70 __weak_reference(__pthread_cond_clockwait, pthread_cond_clockwait);
71 __weak_reference(_thr_cond_init, pthread_cond_init);
72 __weak_reference(_thr_cond_init, _pthread_cond_init);
73 __weak_reference(_thr_cond_destroy, pthread_cond_destroy);
74 __weak_reference(_thr_cond_destroy, _pthread_cond_destroy);
75 __weak_reference(_thr_cond_signal, pthread_cond_signal);
76 __weak_reference(_thr_cond_signal, _pthread_cond_signal);
77 __weak_reference(_thr_cond_broadcast, pthread_cond_broadcast);
78 __weak_reference(_thr_cond_broadcast, _pthread_cond_broadcast);
79 
80 #define CV_PSHARED(cvp)	(((cvp)->kcond.c_flags & USYNC_PROCESS_SHARED) != 0)
81 
82 static void
83 cond_init_body(struct pthread_cond *cvp, const struct pthread_cond_attr *cattr)
84 {
85 
86 	if (cattr == NULL) {
87 		cvp->kcond.c_clockid = CLOCK_REALTIME;
88 	} else {
89 		if (cattr->c_pshared)
90 			cvp->kcond.c_flags |= USYNC_PROCESS_SHARED;
91 		cvp->kcond.c_clockid = cattr->c_clockid;
92 	}
93 }
94 
95 static int
96 cond_init(pthread_cond_t *cond, const pthread_condattr_t *cond_attr)
97 {
98 	struct pthread_cond *cvp;
99 	const struct pthread_cond_attr *cattr;
100 	int pshared;
101 
102 	cattr = cond_attr != NULL ? *cond_attr : NULL;
103 	if (cattr == NULL || cattr->c_pshared == PTHREAD_PROCESS_PRIVATE) {
104 		pshared = 0;
105 		cvp = calloc(1, sizeof(struct pthread_cond));
106 		if (cvp == NULL)
107 			return (ENOMEM);
108 	} else {
109 		pshared = 1;
110 		cvp = __thr_pshared_offpage(cond, 1);
111 		if (cvp == NULL)
112 			return (EFAULT);
113 	}
114 
115 	/*
116 	 * Initialise the condition variable structure:
117 	 */
118 	cond_init_body(cvp, cattr);
119 	*cond = pshared ? THR_PSHARED_PTR : cvp;
120 	return (0);
121 }
122 
123 static int
124 init_static(struct pthread *thread, pthread_cond_t *cond)
125 {
126 	int ret;
127 
128 	THR_LOCK_ACQUIRE(thread, &_cond_static_lock);
129 
130 	if (*cond == NULL)
131 		ret = cond_init(cond, NULL);
132 	else
133 		ret = 0;
134 
135 	THR_LOCK_RELEASE(thread, &_cond_static_lock);
136 
137 	return (ret);
138 }
139 
140 #define CHECK_AND_INIT_COND							\
141 	if (*cond == THR_PSHARED_PTR) {						\
142 		cvp = __thr_pshared_offpage(cond, 0);				\
143 		if (cvp == NULL)						\
144 			return (EINVAL);					\
145 	} else if (__predict_false((cvp = (*cond)) <= THR_COND_DESTROYED)) {	\
146 		if (cvp == THR_COND_INITIALIZER) {				\
147 			int ret;						\
148 			ret = init_static(_get_curthread(), cond);		\
149 			if (ret)						\
150 				return (ret);					\
151 		} else if (cvp == THR_COND_DESTROYED) {				\
152 			return (EINVAL);					\
153 		}								\
154 		cvp = *cond;							\
155 	}
156 
157 int
158 _thr_cond_init(pthread_cond_t * __restrict cond,
159     const pthread_condattr_t * __restrict cond_attr)
160 {
161 
162 	*cond = NULL;
163 	return (cond_init(cond, cond_attr));
164 }
165 
166 int
167 _thr_cond_destroy(pthread_cond_t *cond)
168 {
169 	struct pthread_cond *cvp;
170 	int error;
171 
172 	error = 0;
173 	if (*cond == THR_PSHARED_PTR) {
174 		cvp = __thr_pshared_offpage(cond, 0);
175 		if (cvp != NULL) {
176 			if (cvp->kcond.c_has_waiters)
177 				error = EBUSY;
178 			else
179 				__thr_pshared_destroy(cond);
180 		}
181 		if (error == 0)
182 			*cond = THR_COND_DESTROYED;
183 	} else if ((cvp = *cond) == THR_COND_INITIALIZER) {
184 		/* nothing */
185 	} else if (cvp == THR_COND_DESTROYED) {
186 		error = EINVAL;
187 	} else {
188 		cvp = *cond;
189 		if (cvp->__has_user_waiters || cvp->kcond.c_has_waiters)
190 			error = EBUSY;
191 		else {
192 			*cond = THR_COND_DESTROYED;
193 			free(cvp);
194 		}
195 	}
196 	return (error);
197 }
198 
199 /*
200  * Cancellation behavior:
201  *   Thread may be canceled at start, if thread is canceled, it means it
202  *   did not get a wakeup from pthread_cond_signal(), otherwise, it is
203  *   not canceled.
204  *   Thread cancellation never cause wakeup from pthread_cond_signal()
205  *   to be lost.
206  */
207 static int
208 cond_wait_kernel(struct pthread_cond *cvp, struct pthread_mutex *mp,
209     clockid_t clockid, const struct timespec *abstime, bool cancel,
210     bool clockwait)
211 {
212 	struct pthread *curthread;
213 	struct _umtx_time utime;
214 	int error, error2, recurse, robust;
215 
216 	curthread = _get_curthread();
217 	robust = _mutex_enter_robust(curthread, mp);
218 
219 	error = _mutex_cv_detach(mp, &recurse);
220 	if (error != 0) {
221 		if (robust)
222 			_mutex_leave_robust(curthread, mp);
223 		return (error);
224 	}
225 
226 	if (cancel)
227 		_thr_cancel_enter2(curthread, 0);
228 	if (clockwait) {
229 		utime._timeout = *abstime;
230 		utime._flags = UMTX_ABSTIME;
231 		utime._clockid = clockid;
232 		error = _thr_ucond_wait(&cvp->kcond, &mp->m_lock, NULL,
233 		    &utime, CVWAIT_UMTX_TIME);
234 	} else {
235 		error = _thr_ucond_wait(&cvp->kcond, &mp->m_lock, abstime,
236 		    NULL, CVWAIT_ABSTIME | CVWAIT_CLOCKID);
237 	}
238 	if (cancel)
239 		_thr_cancel_leave(curthread, 0);
240 
241 	/*
242 	 * Note that PP mutex and ROBUST mutex may return
243 	 * interesting error codes.
244 	 */
245 	if (error == 0) {
246 		error2 = _mutex_cv_lock(mp, recurse, true);
247 	} else if (error == EINTR || error == ETIMEDOUT) {
248 		error2 = _mutex_cv_lock(mp, recurse, true);
249 		/*
250 		 * Do not do cancellation on EOWNERDEAD there.  The
251 		 * cancellation cleanup handler will use the protected
252 		 * state and unlock the mutex without making the state
253 		 * consistent and the state will be unrecoverable.
254 		 */
255 		if (error2 == 0 && cancel) {
256 			if (robust) {
257 				_mutex_leave_robust(curthread, mp);
258 				robust = false;
259 			}
260 			_thr_testcancel(curthread);
261 		}
262 
263 		if (error == EINTR)
264 			error = 0;
265 	} else {
266 		/* We know that it didn't unlock the mutex. */
267 		_mutex_cv_attach(mp, recurse);
268 		if (cancel) {
269 			if (robust) {
270 				_mutex_leave_robust(curthread, mp);
271 				robust = false;
272 			}
273 			_thr_testcancel(curthread);
274 		}
275 		error2 = 0;
276 	}
277 	if (robust)
278 		_mutex_leave_robust(curthread, mp);
279 	return (error2 != 0 ? error2 : error);
280 }
281 
282 /*
283  * Thread waits in userland queue whenever possible, when thread
284  * is signaled or broadcasted, it is removed from the queue, and
285  * is saved in curthread's defer_waiters[] buffer, but won't be
286  * woken up until mutex is unlocked.
287  */
288 
289 static int
290 cond_wait_user(struct pthread_cond *cvp, struct pthread_mutex *mp,
291     clockid_t clockid, const struct timespec *abstime, bool cancel)
292 {
293 	struct pthread *curthread;
294 	struct sleepqueue *sq;
295 	int deferred, error, error2, recurse;
296 
297 	curthread = _get_curthread();
298 	if (curthread->wchan != NULL)
299 		PANIC("thread %p was already on queue.", curthread);
300 
301 	if (cancel)
302 		_thr_testcancel(curthread);
303 
304 	_sleepq_lock(cvp);
305 	/*
306 	 * set __has_user_waiters before unlocking mutex, this allows
307 	 * us to check it without locking in pthread_cond_signal().
308 	 */
309 	cvp->__has_user_waiters = 1;
310 	deferred = 0;
311 	(void)_mutex_cv_unlock(mp, &recurse, &deferred);
312 	curthread->mutex_obj = mp;
313 	_sleepq_add(cvp, curthread);
314 	for(;;) {
315 		_thr_clear_wake(curthread);
316 		_sleepq_unlock(cvp);
317 		if (deferred) {
318 			deferred = 0;
319 			if ((mp->m_lock.m_owner & UMUTEX_CONTESTED) == 0)
320 				(void)_umtx_op_err(&mp->m_lock,
321 				    UMTX_OP_MUTEX_WAKE2, mp->m_lock.m_flags,
322 				    0, 0);
323 		}
324 		if (curthread->nwaiter_defer > 0) {
325 			_thr_wake_all(curthread->defer_waiters,
326 			    curthread->nwaiter_defer);
327 			curthread->nwaiter_defer = 0;
328 		}
329 
330 		if (cancel)
331 			_thr_cancel_enter2(curthread, 0);
332 		error = _thr_sleep(curthread, clockid, abstime);
333 		if (cancel)
334 			_thr_cancel_leave(curthread, 0);
335 
336 		_sleepq_lock(cvp);
337 		if (curthread->wchan == NULL) {
338 			error = 0;
339 			break;
340 		} else if (cancel && SHOULD_CANCEL(curthread)) {
341 			sq = _sleepq_lookup(cvp);
342 			cvp->__has_user_waiters = _sleepq_remove(sq, curthread);
343 			_sleepq_unlock(cvp);
344 			curthread->mutex_obj = NULL;
345 			error2 = _mutex_cv_lock(mp, recurse, false);
346 			if (!THR_IN_CRITICAL(curthread))
347 				_pthread_exit(PTHREAD_CANCELED);
348 			else /* this should not happen */
349 				return (error2);
350 		} else if (error == ETIMEDOUT) {
351 			sq = _sleepq_lookup(cvp);
352 			cvp->__has_user_waiters =
353 			    _sleepq_remove(sq, curthread);
354 			break;
355 		}
356 	}
357 	_sleepq_unlock(cvp);
358 	curthread->mutex_obj = NULL;
359 	error2 = _mutex_cv_lock(mp, recurse, false);
360 	if (error == 0)
361 		error = error2;
362 	return (error);
363 }
364 
365 static int
366 cond_wait_common(pthread_cond_t *cond, pthread_mutex_t *mutex,
367     clockid_t clockid, const struct timespec *abstime, bool cancel,
368     bool clockwait)
369 {
370 	struct pthread	*curthread = _get_curthread();
371 	struct pthread_cond *cvp;
372 	struct pthread_mutex *mp;
373 	int error;
374 
375 	CHECK_AND_INIT_COND
376 
377 	if (!clockwait)
378 		clockid = cvp->kcond.c_clockid;
379 
380 	if (*mutex == THR_PSHARED_PTR) {
381 		mp = __thr_pshared_offpage(mutex, 0);
382 		if (mp == NULL)
383 			return (EINVAL);
384 	} else {
385 		mp = *mutex;
386 	}
387 
388 	if ((error = _mutex_owned(curthread, mp)) != 0)
389 		return (error);
390 
391 	if (curthread->attr.sched_policy != SCHED_OTHER ||
392 	    (mp->m_lock.m_flags & (UMUTEX_PRIO_PROTECT | UMUTEX_PRIO_INHERIT |
393 	    USYNC_PROCESS_SHARED)) != 0 || CV_PSHARED(cvp)) {
394 		return (cond_wait_kernel(cvp, mp, clockid, abstime, cancel,
395 		    clockwait));
396 	} else {
397 		return (cond_wait_user(cvp, mp, clockid, abstime, cancel));
398 	}
399 }
400 
401 int
402 _thr_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
403 {
404 	return (cond_wait_common(cond, mutex, 0, NULL, false, false));
405 }
406 
407 int
408 __thr_cond_wait(pthread_cond_t * __restrict cond,
409     pthread_mutex_t * __restrict mutex)
410 {
411 	return (cond_wait_common(cond, mutex, 0, NULL, true, false));
412 }
413 
414 int
415 _thr_cond_timedwait(pthread_cond_t * __restrict cond,
416     pthread_mutex_t * __restrict mutex,
417     const struct timespec * __restrict abstime)
418 {
419 	if (abstime == NULL || abstime->tv_sec < 0 || abstime->tv_nsec < 0 ||
420 	    abstime->tv_nsec >= 1000000000)
421 		return (EINVAL);
422 
423 	return (cond_wait_common(cond, mutex, 0, abstime, false, false));
424 }
425 
426 int
427 __pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex,
428     const struct timespec *abstime)
429 {
430 	if (abstime == NULL || abstime->tv_sec < 0 || abstime->tv_nsec < 0 ||
431 	    abstime->tv_nsec >= 1000000000)
432 		return (EINVAL);
433 
434 	return (cond_wait_common(cond, mutex, 0, abstime, true, false));
435 }
436 
437 int
438 __pthread_cond_clockwait(pthread_cond_t *cond, pthread_mutex_t *mutex,
439     clockid_t clockid, const struct timespec *abstime)
440 {
441 
442 	if (abstime == NULL || abstime->tv_sec < 0 || abstime->tv_nsec < 0 ||
443 	    abstime->tv_nsec >= 1000000000)
444 		return (EINVAL);
445 
446 	return (cond_wait_common(cond, mutex, clockid, abstime, true, true));
447 }
448 
449 static int
450 cond_signal_common(pthread_cond_t *cond)
451 {
452 	struct pthread	*curthread = _get_curthread();
453 	struct pthread *td;
454 	struct pthread_cond *cvp;
455 	struct pthread_mutex *mp;
456 	struct sleepqueue *sq;
457 	int	*waddr;
458 	int	pshared;
459 
460 	/*
461 	 * If the condition variable is statically initialized, perform dynamic
462 	 * initialization.
463 	 */
464 	CHECK_AND_INIT_COND
465 
466 	pshared = CV_PSHARED(cvp);
467 
468 	_thr_ucond_signal(&cvp->kcond);
469 
470 	if (pshared || cvp->__has_user_waiters == 0)
471 		return (0);
472 
473 	curthread = _get_curthread();
474 	waddr = NULL;
475 	_sleepq_lock(cvp);
476 	sq = _sleepq_lookup(cvp);
477 	if (sq == NULL) {
478 		_sleepq_unlock(cvp);
479 		return (0);
480 	}
481 
482 	td = _sleepq_first(sq);
483 	mp = td->mutex_obj;
484 	cvp->__has_user_waiters = _sleepq_remove(sq, td);
485 	if (PMUTEX_OWNER_ID(mp) == TID(curthread)) {
486 		if (curthread->nwaiter_defer >= MAX_DEFER_WAITERS) {
487 			_thr_wake_all(curthread->defer_waiters,
488 			    curthread->nwaiter_defer);
489 			curthread->nwaiter_defer = 0;
490 		}
491 		curthread->defer_waiters[curthread->nwaiter_defer++] =
492 		    &td->wake_addr->value;
493 		mp->m_flags |= PMUTEX_FLAG_DEFERRED;
494 	} else {
495 		waddr = &td->wake_addr->value;
496 	}
497 	_sleepq_unlock(cvp);
498 	if (waddr != NULL)
499 		_thr_set_wake(waddr);
500 	return (0);
501 }
502 
503 struct broadcast_arg {
504 	struct pthread *curthread;
505 	unsigned int *waddrs[MAX_DEFER_WAITERS];
506 	int count;
507 };
508 
509 static void
510 drop_cb(struct pthread *td, void *arg)
511 {
512 	struct broadcast_arg *ba = arg;
513 	struct pthread_mutex *mp;
514 	struct pthread *curthread = ba->curthread;
515 
516 	mp = td->mutex_obj;
517 	if (PMUTEX_OWNER_ID(mp) == TID(curthread)) {
518 		if (curthread->nwaiter_defer >= MAX_DEFER_WAITERS) {
519 			_thr_wake_all(curthread->defer_waiters,
520 			    curthread->nwaiter_defer);
521 			curthread->nwaiter_defer = 0;
522 		}
523 		curthread->defer_waiters[curthread->nwaiter_defer++] =
524 		    &td->wake_addr->value;
525 		mp->m_flags |= PMUTEX_FLAG_DEFERRED;
526 	} else {
527 		if (ba->count >= MAX_DEFER_WAITERS) {
528 			_thr_wake_all(ba->waddrs, ba->count);
529 			ba->count = 0;
530 		}
531 		ba->waddrs[ba->count++] = &td->wake_addr->value;
532 	}
533 }
534 
535 static int
536 cond_broadcast_common(pthread_cond_t *cond)
537 {
538 	int    pshared;
539 	struct pthread_cond *cvp;
540 	struct sleepqueue *sq;
541 	struct broadcast_arg ba;
542 
543 	/*
544 	 * If the condition variable is statically initialized, perform dynamic
545 	 * initialization.
546 	 */
547 	CHECK_AND_INIT_COND
548 
549 	pshared = CV_PSHARED(cvp);
550 
551 	_thr_ucond_broadcast(&cvp->kcond);
552 
553 	if (pshared || cvp->__has_user_waiters == 0)
554 		return (0);
555 
556 	ba.curthread = _get_curthread();
557 	ba.count = 0;
558 
559 	_sleepq_lock(cvp);
560 	sq = _sleepq_lookup(cvp);
561 	if (sq == NULL) {
562 		_sleepq_unlock(cvp);
563 		return (0);
564 	}
565 	_sleepq_drop(sq, drop_cb, &ba);
566 	cvp->__has_user_waiters = 0;
567 	_sleepq_unlock(cvp);
568 	if (ba.count > 0)
569 		_thr_wake_all(ba.waddrs, ba.count);
570 	return (0);
571 }
572 
573 int
574 _thr_cond_signal(pthread_cond_t * cond)
575 {
576 
577 	return (cond_signal_common(cond));
578 }
579 
580 int
581 _thr_cond_broadcast(pthread_cond_t * cond)
582 {
583 
584 	return (cond_broadcast_common(cond));
585 }
586