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