summaryrefslogtreecommitdiff
path: root/lib/libpthread/pthread_cond.c
blob: 4266250ed7249fbb883040824d25e3b0d740727f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
/*	$NetBSD: pthread_cond.c,v 1.37 2007/09/13 23:51:47 ad Exp $	*/

/*-
 * Copyright (c) 2001, 2006, 2007 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Nathan J. Williams and Andrew Doran.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *        This product includes software developed by the NetBSD
 *        Foundation, Inc. and its contributors.
 * 4. Neither the name of The NetBSD Foundation nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/cdefs.h>
__RCSID("$NetBSD: pthread_cond.c,v 1.37 2007/09/13 23:51:47 ad Exp $");

#include <errno.h>
#include <sys/time.h>
#include <sys/types.h>

#include "pthread.h"
#include "pthread_int.h"

int	_sys_nanosleep(const struct timespec *, struct timespec *);

extern int pthread__started;

static int pthread_cond_wait_nothread(pthread_t, pthread_mutex_t *,
    const struct timespec *);

__strong_alias(__libc_cond_init,pthread_cond_init)
__strong_alias(__libc_cond_signal,pthread_cond_signal)
__strong_alias(__libc_cond_broadcast,pthread_cond_broadcast)
__strong_alias(__libc_cond_wait,pthread_cond_wait)
__strong_alias(__libc_cond_timedwait,pthread_cond_timedwait)
__strong_alias(__libc_cond_destroy,pthread_cond_destroy)

int
pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr)
{

	pthread__error(EINVAL, "Invalid condition variable attribute",
	    (attr == NULL) || (attr->ptca_magic == _PT_CONDATTR_MAGIC));

	cond->ptc_magic = _PT_COND_MAGIC;
	pthread_lockinit(&cond->ptc_lock);
	PTQ_INIT(&cond->ptc_waiters);
	cond->ptc_mutex = NULL;

	return 0;
}


int
pthread_cond_destroy(pthread_cond_t *cond)
{

	pthread__error(EINVAL, "Invalid condition variable",
	    cond->ptc_magic == _PT_COND_MAGIC);
	pthread__error(EBUSY, "Destroying condition variable in use",
	    cond->ptc_mutex == NULL);

	cond->ptc_magic = _PT_COND_DEAD;

	return 0;
}


int
pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
{
	pthread_t self;

	pthread__error(EINVAL, "Invalid condition variable",
	    cond->ptc_magic == _PT_COND_MAGIC);
	pthread__error(EINVAL, "Invalid mutex",
	    mutex->ptm_magic == _PT_MUTEX_MAGIC);
	pthread__error(EPERM, "Mutex not locked in condition wait",
	    mutex->ptm_owner != NULL);

	self = pthread__self();
	PTHREADD_ADD(PTHREADD_COND_WAIT);

	/* Just hang out for a while if threads aren't running yet. */
	if (__predict_false(pthread__started == 0))
		return pthread_cond_wait_nothread(self, mutex, NULL);

	if (__predict_false(self->pt_cancel))
		pthread_exit(PTHREAD_CANCELED);

	/*
	 * Note this thread as waiting on the CV.  To ensure good
	 * performance it's critical that the spinlock is held for
	 * as short a time as possible - that means no system calls.
	 */ 
	pthread_spinlock(&cond->ptc_lock);
#ifdef ERRORCHECK
	if (cond->ptc_mutex == NULL)
		cond->ptc_mutex = mutex;
	else {
		pthread__error(EINVAL,
		    "Multiple mutexes used for condition wait", 
		    cond->ptc_mutex == mutex);
	}
#else
	cond->ptc_mutex = mutex;
#endif
	PTQ_INSERT_HEAD(&cond->ptc_waiters, self, pt_sleep);
	self->pt_signalled = 0;
	self->pt_sleeponq = 1;
	self->pt_sleepobj = &cond->ptc_waiters;
	pthread_spinunlock(&cond->ptc_lock);

 	/*
 	 * Before releasing the mutex, note that this thread is
 	 * about to block by setting the willpark flag.  If there
 	 * is a single waiter on the mutex, setting the flag will
 	 * defer restarting it until calling into the kernel to
 	 * park, saving a syscall & involuntary context switch.
 	 */
	self->pt_willpark = 1;
	pthread_mutex_unlock(mutex);
	(void)pthread__park(self, &cond->ptc_lock, &cond->ptc_waiters,
	    NULL, 1, &mutex->ptm_blocked);
	pthread_mutex_lock(mutex);

	/*
	 * If we awoke abnormally the waiters list will have been
	 * made empty by the current thread (in pthread__park()),
	 * so we can check the value safely without locking.
	 *
	 * Otherwise, it will have been updated by whichever thread
	 * last issued a wakeup.
	 */
	if (PTQ_EMPTY(&cond->ptc_waiters) && cond->ptc_mutex != NULL) {
		pthread_spinlock(&cond->ptc_lock);
		if (PTQ_EMPTY(&cond->ptc_waiters))
			cond->ptc_mutex = NULL;
		pthread_spinunlock(&cond->ptc_lock);
	}

	/*
	 * If we have cancelled then exit.  POSIX dictates that the
	 * mutex must be held when we action the cancellation.
	 */
	if (__predict_false(self->pt_cancel)) {
		if (self->pt_signalled)
			pthread_cond_signal(cond);
		pthread_exit(PTHREAD_CANCELED);
	}

	return 0;
}

int
pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex,
    const struct timespec *abstime)
{
	pthread_t self;
	int retval;

	pthread__error(EINVAL, "Invalid condition variable",
	    cond->ptc_magic == _PT_COND_MAGIC);
	pthread__error(EINVAL, "Invalid mutex",
	    mutex->ptm_magic == _PT_MUTEX_MAGIC);
	pthread__error(EPERM, "Mutex not locked in condition wait",
	    mutex->ptm_owner != NULL);
	pthread__error(EINVAL, "Invalid wait time", 
	    (abstime->tv_sec >= 0) &&
	    (abstime->tv_nsec >= 0) && (abstime->tv_nsec < 1000000000));

	self = pthread__self();
	PTHREADD_ADD(PTHREADD_COND_TIMEDWAIT);

	/* Just hang out for a while if threads aren't running yet. */
	if (__predict_false(pthread__started == 0))
		return pthread_cond_wait_nothread(self, mutex, abstime);

	if (__predict_false(self->pt_cancel))
		pthread_exit(PTHREAD_CANCELED);

	/*
	 * Note this thread as waiting on the CV.  To ensure good
	 * performance it's critical that the spinlock is held for
	 * as short a time as possible - that means no system calls.
	 */ 
	pthread_spinlock(&cond->ptc_lock);
#ifdef ERRORCHECK
	if (cond->ptc_mutex == NULL)
		cond->ptc_mutex = mutex;
	else {
		pthread__error(EINVAL,
		    "Multiple mutexes used for condition wait",
		    cond->ptc_mutex == mutex);
	}
#else
	cond->ptc_mutex = mutex;
#endif
	PTQ_INSERT_HEAD(&cond->ptc_waiters, self, pt_sleep);
	self->pt_signalled = 0;
	self->pt_sleeponq = 1;
	self->pt_sleepobj = &cond->ptc_waiters;
	pthread_spinunlock(&cond->ptc_lock);

 	/*
 	 * Before releasing the mutex, note that this thread is
 	 * about to block by setting the willpark flag.  If there
 	 * is a single waiter on the mutex, setting the flag will
 	 * defer restarting it until calling into the kernel to
 	 * park, saving a syscall & involuntary context switch.
 	 */
	self->pt_willpark = 1;
	pthread_mutex_unlock(mutex);
	retval = pthread__park(self, &cond->ptc_lock, &cond->ptc_waiters,
	    abstime, 1, &mutex->ptm_blocked);
	pthread_mutex_lock(mutex);

	/*
	 * If we awoke abnormally the waiters list will have been
	 * made empty by the current thread (in pthread__park()),
	 * so we can check the value safely without locking.
	 *
	 * Otherwise, it will have been updated by whichever thread
	 * last issued a wakeup.
	 */
	if (PTQ_EMPTY(&cond->ptc_waiters) && cond->ptc_mutex != NULL) {
		pthread_spinlock(&cond->ptc_lock);
		if (PTQ_EMPTY(&cond->ptc_waiters))
			cond->ptc_mutex = NULL;
		pthread_spinunlock(&cond->ptc_lock);
	}

	/*
	 * If we have cancelled then exit.  POSIX dictates that the
	 * mutex must be held when we action the cancellation.
	 */
	if (__predict_false(self->pt_cancel | retval)) {
		if (self->pt_signalled)
			pthread_cond_signal(cond);
		if (self->pt_cancel)
			pthread_exit(PTHREAD_CANCELED);
	}

	return retval;
}

int
pthread_cond_signal(pthread_cond_t *cond)
{
	pthread_t self, signaled;
	pthread_mutex_t *mutex;

	pthread__error(EINVAL, "Invalid condition variable",
	    cond->ptc_magic == _PT_COND_MAGIC);
	PTHREADD_ADD(PTHREADD_COND_SIGNAL);

	if (PTQ_EMPTY(&cond->ptc_waiters))
		return 0;

	self = pthread__self();
	pthread_spinlock(&cond->ptc_lock);

	/*
	 * Find a thread that is still blocked (no pending wakeup).
	 * A wakeup can be pending if we have interrupted unpark_all
	 * as it releases the interlock.
	 */
	PTQ_FOREACH(signaled, &cond->ptc_waiters, pt_sleep) {	
		if (signaled->pt_sleepobj != NULL)
			break;
	}
	if (__predict_false(signaled == NULL)) {
		cond->ptc_mutex = NULL;
		pthread_spinunlock(&cond->ptc_lock);
		return 0;
	}

	/*
	 * Pull the thread off the queue, and set pt_signalled.
	 *
	 * After resuming execution, the thread must check to see if it
	 * has been restarted as a result of pthread_cond_signal().  If it
	 * has, but cannot take the wakeup (because of eg a timeout) then
	 * try to ensure that another thread sees it.  This is necessary
	 * because there may be multiple waiters, and at least one should
	 * take the wakeup if possible.
	 */
	PTQ_REMOVE(&cond->ptc_waiters, signaled, pt_sleep);
	mutex = cond->ptc_mutex;
	if (PTQ_EMPTY(&cond->ptc_waiters))
		cond->ptc_mutex = NULL;
	signaled->pt_signalled = 1;

	/*
	 * For all valid uses of pthread_cond_signal(), the caller will
	 * hold the mutex that the target is using to synchronize with.
	 * To avoid the target awakening and immediatley blocking on the
	 * mutex, transfer the thread to be awoken to the current thread's
	 * deferred wakeup list.  The waiter will be set running when the
	 * caller (this thread) releases the mutex.
	 */
	if (mutex != NULL && self->pt_nwaiters < pthread__unpark_max &&
	    pthread__mutex_deferwake(self, mutex)) {
		signaled->pt_sleepobj = NULL;
		signaled->pt_sleeponq = 0;
		pthread_spinunlock(&cond->ptc_lock);
		self->pt_waiters[self->pt_nwaiters++] = signaled->pt_lid;
	} else {
		pthread__unpark(self, &cond->ptc_lock,
		    &cond->ptc_waiters, signaled);
	}
	PTHREADD_ADD(PTHREADD_COND_WOKEUP);

	return 0;
}


int
pthread_cond_broadcast(pthread_cond_t *cond)
{
	pthread_t self, signaled, next;
	pthread_mutex_t *mutex;

	pthread__error(EINVAL, "Invalid condition variable",
	    cond->ptc_magic == _PT_COND_MAGIC);

	PTHREADD_ADD(PTHREADD_COND_BROADCAST);

	if (PTQ_EMPTY(&cond->ptc_waiters))
		return 0;

	self = pthread__self();
	pthread_spinlock(&cond->ptc_lock);
	mutex = cond->ptc_mutex;
	cond->ptc_mutex = NULL;

	/*
	 * Try to defer waking threads (see pthread_cond_signal()).
	 * Only transfer waiters for which there is no pending wakeup.
	 */
	if (mutex != NULL && pthread__mutex_deferwake(self, mutex)) {
		for (signaled = PTQ_FIRST(&cond->ptc_waiters);
		    signaled != NULL;
		    signaled = next) {	
		    	next = PTQ_NEXT(signaled, pt_sleep);
		    	if (__predict_false(signaled->pt_sleepobj == NULL))
		    		continue;
			if (self->pt_nwaiters == pthread__unpark_max) {
				/* Overflow, take the slow path. */
				break;
			}
		    	PTQ_REMOVE(&cond->ptc_waiters, signaled, pt_sleep);
			signaled->pt_sleepobj = NULL;
			signaled->pt_sleeponq = 0;
			self->pt_waiters[self->pt_nwaiters++] =
			    signaled->pt_lid;
		}
		if (signaled == NULL) {
			/* Anything more to do? */
			pthread_spinunlock(&cond->ptc_lock);
			return 0;
		}
	}
	pthread__unpark_all(self, &cond->ptc_lock, &cond->ptc_waiters);

	PTHREADD_ADD(PTHREADD_COND_WOKEUP);

	return 0;

}


int
pthread_condattr_init(pthread_condattr_t *attr)
{

	attr->ptca_magic = _PT_CONDATTR_MAGIC;

	return 0;
}


int
pthread_condattr_destroy(pthread_condattr_t *attr)
{

	pthread__error(EINVAL, "Invalid condition variable attribute",
	    attr->ptca_magic == _PT_CONDATTR_MAGIC);

	attr->ptca_magic = _PT_CONDATTR_DEAD;

	return 0;
}

/* Utility routine to hang out for a while if threads haven't started yet. */
static int
pthread_cond_wait_nothread(pthread_t self, pthread_mutex_t *mutex,
    const struct timespec *abstime)
{
	struct timespec now, diff;
	int retval;

	if (abstime == NULL) {
		diff.tv_sec = 99999999;
		diff.tv_nsec = 0;
	} else {
		clock_gettime(CLOCK_REALTIME, &now);
		if  (timespeccmp(abstime, &now, <))
			timespecclear(&diff);
		else
			timespecsub(abstime, &now, &diff);
	}

	do {
		pthread__testcancel(self);
		pthread_mutex_unlock(mutex);
		retval = _sys_nanosleep(&diff, NULL);
		pthread_mutex_lock(mutex);
	} while (abstime == NULL && retval == 0);
	pthread__testcancel(self);

	if (retval == 0)
		return ETIMEDOUT;
	else
		/* spurious wakeup */
		return 0;
}