pthread_cond.c revision 1.31.2.4 1 /* $NetBSD: pthread_cond.c,v 1.31.2.4 2007/09/10 10:54:05 skrll Exp $ */
2
3 /*-
4 * Copyright (c) 2001, 2006, 2007 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Nathan J. Williams and Andrew Doran.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following 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 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the NetBSD
21 * Foundation, Inc. and its contributors.
22 * 4. Neither the name of The NetBSD Foundation nor the names of its
23 * contributors may be used to endorse or promote products derived
24 * from this software without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
37 */
38
39 #include <sys/cdefs.h>
40 __RCSID("$NetBSD: pthread_cond.c,v 1.31.2.4 2007/09/10 10:54:05 skrll Exp $");
41
42 #include <errno.h>
43 #include <sys/time.h>
44 #include <sys/types.h>
45 #include <sys/lock.h>
46
47 #include "pthread.h"
48 #include "pthread_int.h"
49
50 int _sys_nanosleep(const struct timespec *, struct timespec *);
51
52 extern int pthread__started;
53
54 static int pthread_cond_wait_nothread(pthread_t, pthread_mutex_t *,
55 const struct timespec *);
56
57 __strong_alias(__libc_cond_init,pthread_cond_init)
58 __strong_alias(__libc_cond_signal,pthread_cond_signal)
59 __strong_alias(__libc_cond_broadcast,pthread_cond_broadcast)
60 __strong_alias(__libc_cond_wait,pthread_cond_wait)
61 __strong_alias(__libc_cond_timedwait,pthread_cond_timedwait)
62 __strong_alias(__libc_cond_destroy,pthread_cond_destroy)
63
64 int
65 pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr)
66 {
67
68 pthread__error(EINVAL, "Invalid condition variable attribute",
69 (attr == NULL) || (attr->ptca_magic == _PT_CONDATTR_MAGIC));
70
71 cond->ptc_magic = _PT_COND_MAGIC;
72 pthread_lockinit(&cond->ptc_lock);
73 PTQ_INIT(&cond->ptc_waiters);
74 cond->ptc_mutex = NULL;
75
76 return 0;
77 }
78
79
80 int
81 pthread_cond_destroy(pthread_cond_t *cond)
82 {
83
84 pthread__error(EINVAL, "Invalid condition variable",
85 cond->ptc_magic == _PT_COND_MAGIC);
86 pthread__error(EBUSY, "Destroying condition variable in use",
87 cond->ptc_mutex == NULL);
88
89 cond->ptc_magic = _PT_COND_DEAD;
90
91 return 0;
92 }
93
94
95 int
96 pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
97 {
98 pthread_t self;
99
100 pthread__error(EINVAL, "Invalid condition variable",
101 cond->ptc_magic == _PT_COND_MAGIC);
102 pthread__error(EINVAL, "Invalid mutex",
103 mutex->ptm_magic == _PT_MUTEX_MAGIC);
104 pthread__error(EPERM, "Mutex not locked in condition wait",
105 mutex->ptm_owner != NULL);
106
107 self = pthread__self();
108 PTHREADD_ADD(PTHREADD_COND_WAIT);
109
110 /* Just hang out for a while if threads aren't running yet. */
111 if (__predict_false(pthread__started == 0))
112 return pthread_cond_wait_nothread(self, mutex, NULL);
113
114 if (__predict_false(self->pt_cancel))
115 pthread_exit(PTHREAD_CANCELED);
116
117 /*
118 * Note this thread as waiting on the CV. To ensure good
119 * performance it's critical that the spinlock is held for
120 * as short a time as possible - that means no system calls.
121 */
122 pthread_spinlock(&cond->ptc_lock);
123 #ifdef ERRORCHECK
124 if (cond->ptc_mutex == NULL)
125 cond->ptc_mutex = mutex;
126 else {
127 pthread__error(EINVAL,
128 "Multiple mutexes used for condition wait",
129 cond->ptc_mutex == mutex);
130 }
131 #else
132 cond->ptc_mutex = mutex;
133 #endif
134 PTQ_INSERT_HEAD(&cond->ptc_waiters, self, pt_sleep);
135 self->pt_signalled = 0;
136 self->pt_sleeponq = 1;
137 self->pt_sleepobj = &cond->ptc_waiters;
138 pthread_spinunlock(&cond->ptc_lock);
139
140 /*
141 * Before releasing the mutex, note that this thread is
142 * about to block by setting the willpark flag. If there
143 * is a single waiter on the mutex, setting the flag will
144 * defer restarting it until calling into the kernel to
145 * park, saving a syscall & involuntary context switch.
146 */
147 self->pt_willpark = 1;
148 pthread_mutex_unlock(mutex);
149 (void)pthread__park(self, &cond->ptc_lock, &cond->ptc_waiters,
150 NULL, 1, &mutex->ptm_blocked);
151 pthread_mutex_lock(mutex);
152
153 /*
154 * If we awoke abnormally the waiters list will have been
155 * made empty by the current thread (in pthread__park()),
156 * so we can check the value safely without locking.
157 *
158 * Otherwise, it will have been updated by whichever thread
159 * last issued a wakeup.
160 */
161 if (PTQ_EMPTY(&cond->ptc_waiters) && cond->ptc_mutex != NULL) {
162 pthread_spinlock(&cond->ptc_lock);
163 if (PTQ_EMPTY(&cond->ptc_waiters))
164 cond->ptc_mutex = NULL;
165 pthread_spinunlock(&cond->ptc_lock);
166 }
167
168 /*
169 * If we have cancelled then exit. POSIX dictates that the
170 * mutex must be held when we action the cancellation.
171 */
172 if (__predict_false(self->pt_cancel)) {
173 if (self->pt_signalled)
174 pthread_cond_signal(cond);
175 pthread_exit(PTHREAD_CANCELED);
176 }
177
178 return 0;
179 }
180
181 int
182 pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex,
183 const struct timespec *abstime)
184 {
185 pthread_t self;
186 int retval;
187
188 pthread__error(EINVAL, "Invalid condition variable",
189 cond->ptc_magic == _PT_COND_MAGIC);
190 pthread__error(EINVAL, "Invalid mutex",
191 mutex->ptm_magic == _PT_MUTEX_MAGIC);
192 pthread__error(EPERM, "Mutex not locked in condition wait",
193 __SIMPLELOCK_LOCKED_P(&mutex->ptm_lock));
194 pthread__error(EINVAL, "Invalid wait time",
195 (abstime->tv_sec >= 0) &&
196 (abstime->tv_nsec >= 0) && (abstime->tv_nsec < 1000000000));
197
198 self = pthread__self();
199 PTHREADD_ADD(PTHREADD_COND_TIMEDWAIT);
200
201 /* Just hang out for a while if threads aren't running yet. */
202 if (__predict_false(pthread__started == 0))
203 return pthread_cond_wait_nothread(self, mutex, abstime);
204
205 if (__predict_false(self->pt_cancel))
206 pthread_exit(PTHREAD_CANCELED);
207
208 /*
209 * Note this thread as waiting on the CV. To ensure good
210 * performance it's critical that the spinlock is held for
211 * as short a time as possible - that means no system calls.
212 */
213 pthread_spinlock(&cond->ptc_lock);
214 #ifdef ERRORCHECK
215 if (cond->ptc_mutex == NULL)
216 cond->ptc_mutex = mutex;
217 else {
218 pthread__error(EINVAL,
219 "Multiple mutexes used for condition wait",
220 cond->ptc_mutex == mutex);
221 }
222 #else
223 cond->ptc_mutex = mutex;
224 #endif
225 PTQ_INSERT_HEAD(&cond->ptc_waiters, self, pt_sleep);
226 self->pt_signalled = 0;
227 self->pt_sleeponq = 1;
228 self->pt_sleepobj = &cond->ptc_waiters;
229 pthread_spinunlock(&cond->ptc_lock);
230
231 /*
232 * Before releasing the mutex, note that this thread is
233 * about to block by setting the willpark flag. If there
234 * is a single waiter on the mutex, setting the flag will
235 * defer restarting it until calling into the kernel to
236 * park, saving a syscall & involuntary context switch.
237 */
238 self->pt_willpark = 1;
239 pthread_mutex_unlock(mutex);
240 retval = pthread__park(self, &cond->ptc_lock, &cond->ptc_waiters,
241 abstime, 1, &mutex->ptm_blocked);
242 pthread_mutex_lock(mutex);
243
244 /*
245 * If we awoke abnormally the waiters list will have been
246 * made empty by the current thread (in pthread__park()),
247 * so we can check the value safely without locking.
248 *
249 * Otherwise, it will have been updated by whichever thread
250 * last issued a wakeup.
251 */
252 if (PTQ_EMPTY(&cond->ptc_waiters) && cond->ptc_mutex != NULL) {
253 pthread_spinlock(&cond->ptc_lock);
254 if (PTQ_EMPTY(&cond->ptc_waiters))
255 cond->ptc_mutex = NULL;
256 pthread_spinunlock(&cond->ptc_lock);
257 }
258
259 /*
260 * If we have cancelled then exit. POSIX dictates that the
261 * mutex must be held when we action the cancellation.
262 */
263 if (__predict_false(self->pt_cancel | retval)) {
264 if (self->pt_signalled)
265 pthread_cond_signal(cond);
266 if (self->pt_cancel)
267 pthread_exit(PTHREAD_CANCELED);
268 }
269
270 return retval;
271 }
272
273 int
274 pthread_cond_signal(pthread_cond_t *cond)
275 {
276 pthread_t self, signaled;
277 pthread_mutex_t *mutex;
278
279 pthread__error(EINVAL, "Invalid condition variable",
280 cond->ptc_magic == _PT_COND_MAGIC);
281 PTHREADD_ADD(PTHREADD_COND_SIGNAL);
282
283 if (PTQ_EMPTY(&cond->ptc_waiters))
284 return 0;
285
286 self = pthread__self();
287 pthread_spinlock(&cond->ptc_lock);
288
289 /*
290 * Find a thread that is still blocked (no pending wakeup).
291 * A wakeup can be pending if we have interrupted unpark_all
292 * as it releases the interlock.
293 */
294 PTQ_FOREACH(signaled, &cond->ptc_waiters, pt_sleep) {
295 if (signaled->pt_sleepobj != NULL)
296 break;
297 }
298 if (__predict_false(signaled == NULL)) {
299 cond->ptc_mutex = NULL;
300 pthread_spinunlock(&cond->ptc_lock);
301 return 0;
302 }
303
304 /*
305 * Pull the thread off the queue, and set pt_signalled.
306 *
307 * After resuming execution, the thread must check to see if it
308 * has been restarted as a result of pthread_cond_signal(). If it
309 * has, but cannot take the wakeup (because of eg a timeout) then
310 * try to ensure that another thread sees it. This is necessary
311 * because there may be multiple waiters, and at least one should
312 * take the wakeup if possible.
313 */
314 PTQ_REMOVE(&cond->ptc_waiters, signaled, pt_sleep);
315 mutex = cond->ptc_mutex;
316 if (PTQ_EMPTY(&cond->ptc_waiters))
317 cond->ptc_mutex = NULL;
318 signaled->pt_signalled = 1;
319
320 /*
321 * For all valid uses of pthread_cond_signal(), the caller will
322 * hold the mutex that the target is using to synchronize with.
323 * To avoid the target awakening and immediatley blocking on the
324 * mutex, transfer the thread to be awoken to the current thread's
325 * deferred wakeup list. The waiter will be set running when the
326 * caller (this thread) releases the mutex.
327 */
328 if (mutex != NULL && pthread__mutex_owned(self, mutex) &&
329 self->pt_nwaiters < pthread__unpark_max) {
330 signaled->pt_sleepobj = NULL;
331 signaled->pt_sleeponq = 0;
332 pthread_spinunlock(&cond->ptc_lock);
333 self->pt_waiters[self->pt_nwaiters++] = signaled->pt_lid;
334 } else {
335 pthread__unpark(self, &cond->ptc_lock,
336 &cond->ptc_waiters, signaled);
337 }
338 PTHREADD_ADD(PTHREADD_COND_WOKEUP);
339
340 return 0;
341 }
342
343
344 int
345 pthread_cond_broadcast(pthread_cond_t *cond)
346 {
347 pthread_t self, signaled, next;
348 pthread_mutex_t *mutex;
349
350 pthread__error(EINVAL, "Invalid condition variable",
351 cond->ptc_magic == _PT_COND_MAGIC);
352
353 PTHREADD_ADD(PTHREADD_COND_BROADCAST);
354
355 if (PTQ_EMPTY(&cond->ptc_waiters))
356 return 0;
357
358 self = pthread__self();
359 pthread_spinlock(&cond->ptc_lock);
360 mutex = cond->ptc_mutex;
361 cond->ptc_mutex = NULL;
362
363 /*
364 * Try to defer waking threads (see pthread_cond_signal()).
365 * Only transfer waiters for which there is no pending wakeup.
366 */
367 if (mutex != NULL && pthread__mutex_owned(self, mutex)) {
368 for (signaled = PTQ_FIRST(&cond->ptc_waiters);
369 signaled != NULL;
370 signaled = next) {
371 next = PTQ_NEXT(signaled, pt_sleep);
372 if (__predict_false(signaled->pt_sleepobj == NULL))
373 continue;
374 if (self->pt_nwaiters == pthread__unpark_max) {
375 /* Overflow, take the slow path. */
376 break;
377 }
378 PTQ_REMOVE(&cond->ptc_waiters, signaled, pt_sleep);
379 signaled->pt_sleepobj = NULL;
380 signaled->pt_sleeponq = 0;
381 self->pt_waiters[self->pt_nwaiters++] =
382 signaled->pt_lid;
383 }
384 if (signaled == NULL) {
385 /* Anything more to do? */
386 pthread_spinunlock(&cond->ptc_lock);
387 return 0;
388 }
389 }
390 pthread__unpark_all(self, &cond->ptc_lock, &cond->ptc_waiters);
391
392 PTHREADD_ADD(PTHREADD_COND_WOKEUP);
393
394 return 0;
395
396 }
397
398
399 int
400 pthread_condattr_init(pthread_condattr_t *attr)
401 {
402
403 attr->ptca_magic = _PT_CONDATTR_MAGIC;
404
405 return 0;
406 }
407
408
409 int
410 pthread_condattr_destroy(pthread_condattr_t *attr)
411 {
412
413 pthread__error(EINVAL, "Invalid condition variable attribute",
414 attr->ptca_magic == _PT_CONDATTR_MAGIC);
415
416 attr->ptca_magic = _PT_CONDATTR_DEAD;
417
418 return 0;
419 }
420
421 /* Utility routine to hang out for a while if threads haven't started yet. */
422 static int
423 pthread_cond_wait_nothread(pthread_t self, pthread_mutex_t *mutex,
424 const struct timespec *abstime)
425 {
426 struct timespec now, diff;
427 int retval;
428
429 if (abstime == NULL) {
430 diff.tv_sec = 99999999;
431 diff.tv_nsec = 0;
432 } else {
433 clock_gettime(CLOCK_REALTIME, &now);
434 if (timespeccmp(abstime, &now, <))
435 timespecclear(&diff);
436 else
437 timespecsub(abstime, &now, &diff);
438 }
439
440 do {
441 pthread__testcancel(self);
442 pthread_mutex_unlock(mutex);
443 retval = _sys_nanosleep(&diff, NULL);
444 pthread_mutex_lock(mutex);
445 } while (abstime == NULL && retval == 0);
446 pthread__testcancel(self);
447
448 if (retval == 0)
449 return ETIMEDOUT;
450 else
451 /* spurious wakeup */
452 return 0;
453 }
454