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