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