1 /* $NetBSD: pthread_cond.c,v 1.59 2013/03/21 16:49:12 christos Exp $ */ 2 3 /*- 4 * Copyright (c) 2001, 2006, 2007, 2008 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 * 19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 29 * POSSIBILITY OF SUCH DAMAGE. 30 */ 31 32 /* 33 * We assume that there will be no contention on pthread_cond_t::ptc_lock 34 * because functioning applications must call both the wait and wakeup 35 * functions while holding the same application provided mutex. The 36 * spinlock is present only to prevent libpthread causing the application 37 * to crash or malfunction as a result of corrupted data structures, in 38 * the event that the application is buggy. 39 * 40 * If there is contention on spinlock when real-time threads are in use, 41 * it could cause a deadlock due to priority inversion: the thread holding 42 * the spinlock may not get CPU time to make forward progress and release 43 * the spinlock to a higher priority thread that is waiting for it. 44 * Contention on the spinlock will only occur with buggy applications, 45 * so at the time of writing it's not considered a major bug in libpthread. 46 */ 47 48 #include <sys/cdefs.h> 49 __RCSID("$NetBSD: pthread_cond.c,v 1.59 2013/03/21 16:49:12 christos Exp $"); 50 51 #include <stdlib.h> 52 #include <errno.h> 53 #include <sys/time.h> 54 #include <sys/types.h> 55 56 #include "pthread.h" 57 #include "pthread_int.h" 58 #include "reentrant.h" 59 60 int _sys___nanosleep50(const struct timespec *, struct timespec *); 61 62 extern int pthread__started; 63 64 static int pthread_cond_wait_nothread(pthread_t, pthread_mutex_t *, 65 pthread_cond_t *, const struct timespec *); 66 67 int _pthread_cond_has_waiters_np(pthread_cond_t *); 68 69 __weak_alias(pthread_cond_has_waiters_np,_pthread_cond_has_waiters_np) 70 71 __strong_alias(__libc_cond_init,pthread_cond_init) 72 __strong_alias(__libc_cond_signal,pthread_cond_signal) 73 __strong_alias(__libc_cond_broadcast,pthread_cond_broadcast) 74 __strong_alias(__libc_cond_wait,pthread_cond_wait) 75 __strong_alias(__libc_cond_timedwait,pthread_cond_timedwait) 76 __strong_alias(__libc_cond_destroy,pthread_cond_destroy) 77 78 int 79 pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr) 80 { 81 if (__predict_false(__uselibcstub)) 82 return __libc_cond_init_stub(cond, attr); 83 84 pthread__error(EINVAL, "Invalid condition variable attribute", 85 (attr == NULL) || (attr->ptca_magic == _PT_CONDATTR_MAGIC)); 86 87 cond->ptc_magic = _PT_COND_MAGIC; 88 pthread_lockinit(&cond->ptc_lock); 89 PTQ_INIT(&cond->ptc_waiters); 90 cond->ptc_mutex = NULL; 91 if (attr && attr->ptca_private) { 92 cond->ptc_private = malloc(sizeof(clockid_t)); 93 if (cond->ptc_private == NULL) 94 return errno; 95 *(clockid_t *)cond->ptc_private = 96 *(clockid_t *)attr->ptca_private; 97 } else 98 cond->ptc_private = NULL; 99 100 return 0; 101 } 102 103 104 int 105 pthread_cond_destroy(pthread_cond_t *cond) 106 { 107 if (__predict_false(__uselibcstub)) 108 return __libc_cond_destroy_stub(cond); 109 110 pthread__error(EINVAL, "Invalid condition variable", 111 cond->ptc_magic == _PT_COND_MAGIC); 112 pthread__error(EBUSY, "Destroying condition variable in use", 113 cond->ptc_mutex == NULL); 114 115 cond->ptc_magic = _PT_COND_DEAD; 116 free(cond->ptc_private); 117 118 return 0; 119 } 120 121 int 122 pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, 123 const struct timespec *abstime) 124 { 125 pthread_t self; 126 int retval; 127 128 if (__predict_false(__uselibcstub)) 129 return __libc_cond_timedwait_stub(cond, mutex, abstime); 130 131 pthread__error(EINVAL, "Invalid condition variable", 132 cond->ptc_magic == _PT_COND_MAGIC); 133 pthread__error(EINVAL, "Invalid mutex", 134 mutex->ptm_magic == _PT_MUTEX_MAGIC); 135 pthread__error(EPERM, "Mutex not locked in condition wait", 136 mutex->ptm_owner != NULL); 137 if (abstime != NULL) { 138 pthread__error(EINVAL, "Invalid wait time", 139 (abstime->tv_sec >= 0) && 140 (abstime->tv_nsec >= 0) && 141 (abstime->tv_nsec < 1000000000)); 142 } 143 144 self = pthread__self(); 145 146 /* Just hang out for a while if threads aren't running yet. */ 147 if (__predict_false(pthread__started == 0)) { 148 return pthread_cond_wait_nothread(self, mutex, cond, abstime); 149 } 150 if (__predict_false(self->pt_cancel)) { 151 pthread__cancelled(); 152 } 153 154 /* Note this thread as waiting on the CV. */ 155 pthread__spinlock(self, &cond->ptc_lock); 156 cond->ptc_mutex = mutex; 157 PTQ_INSERT_HEAD(&cond->ptc_waiters, self, pt_sleep); 158 self->pt_sleepobj = cond; 159 pthread__spinunlock(self, &cond->ptc_lock); 160 161 do { 162 self->pt_willpark = 1; 163 pthread_mutex_unlock(mutex); 164 self->pt_willpark = 0; 165 self->pt_blocking++; 166 retval = _lwp_park(abstime, self->pt_unpark, 167 __UNVOLATILE(&mutex->ptm_waiters), 168 __UNVOLATILE(&mutex->ptm_waiters)); 169 self->pt_unpark = 0; 170 self->pt_blocking--; 171 membar_sync(); 172 pthread_mutex_lock(mutex); 173 174 /* 175 * If we have cancelled then exit. POSIX dictates that 176 * the mutex must be held when we action the cancellation. 177 * 178 * If we absorbed a pthread_cond_signal() and cannot take 179 * the wakeup, we must ensure that another thread does. 180 * 181 * If awoke early, we may still be on the sleep queue and 182 * must remove ourself. 183 */ 184 if (__predict_false(retval != 0)) { 185 switch (errno) { 186 case EINTR: 187 case EALREADY: 188 retval = 0; 189 break; 190 default: 191 retval = errno; 192 break; 193 } 194 } 195 if (__predict_false(self->pt_cancel | retval)) { 196 pthread_cond_signal(cond); 197 if (self->pt_cancel) { 198 pthread__cancelled(); 199 } 200 break; 201 } 202 } while (self->pt_sleepobj != NULL); 203 204 return retval; 205 } 206 207 int 208 pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex) 209 { 210 if (__predict_false(__uselibcstub)) 211 return __libc_cond_wait_stub(cond, mutex); 212 213 return pthread_cond_timedwait(cond, mutex, NULL); 214 } 215 216 static int __noinline 217 pthread__cond_wake_one(pthread_cond_t *cond) 218 { 219 pthread_t self, signaled; 220 pthread_mutex_t *mutex; 221 lwpid_t lid; 222 223 pthread__error(EINVAL, "Invalid condition variable", 224 cond->ptc_magic == _PT_COND_MAGIC); 225 226 /* 227 * Pull the first thread off the queue. If the current thread 228 * is associated with the condition variable, remove it without 229 * awakening (error case in pthread_cond_timedwait()). 230 */ 231 self = pthread__self(); 232 pthread__spinlock(self, &cond->ptc_lock); 233 if (self->pt_sleepobj == cond) { 234 PTQ_REMOVE(&cond->ptc_waiters, self, pt_sleep); 235 self->pt_sleepobj = NULL; 236 } 237 signaled = PTQ_FIRST(&cond->ptc_waiters); 238 if (__predict_false(signaled == NULL)) { 239 cond->ptc_mutex = NULL; 240 pthread__spinunlock(self, &cond->ptc_lock); 241 return 0; 242 } 243 mutex = cond->ptc_mutex; 244 if (PTQ_NEXT(signaled, pt_sleep) == NULL) { 245 cond->ptc_mutex = NULL; 246 PTQ_INIT(&cond->ptc_waiters); 247 } else { 248 PTQ_REMOVE(&cond->ptc_waiters, signaled, pt_sleep); 249 } 250 signaled->pt_sleepobj = NULL; 251 lid = signaled->pt_lid; 252 pthread__spinunlock(self, &cond->ptc_lock); 253 254 /* 255 * For all valid uses of pthread_cond_signal(), the caller will 256 * hold the mutex that the target is using to synchronize with. 257 * To avoid the target awakening and immediately blocking on the 258 * mutex, transfer the thread to be awoken to the current thread's 259 * deferred wakeup list. The waiter will be set running when the 260 * caller (this thread) releases the mutex. 261 */ 262 if (__predict_false(self->pt_nwaiters == (size_t)pthread__unpark_max)) { 263 (void)_lwp_unpark_all(self->pt_waiters, self->pt_nwaiters, 264 __UNVOLATILE(&mutex->ptm_waiters)); 265 self->pt_nwaiters = 0; 266 } 267 self->pt_waiters[self->pt_nwaiters++] = lid; 268 pthread__mutex_deferwake(self, mutex); 269 return 0; 270 } 271 272 int 273 pthread_cond_signal(pthread_cond_t *cond) 274 { 275 276 if (__predict_false(__uselibcstub)) 277 return __libc_cond_signal_stub(cond); 278 279 if (__predict_true(PTQ_EMPTY(&cond->ptc_waiters))) 280 return 0; 281 return pthread__cond_wake_one(cond); 282 } 283 284 static int __noinline 285 pthread__cond_wake_all(pthread_cond_t *cond) 286 { 287 pthread_t self, signaled; 288 pthread_mutex_t *mutex; 289 u_int max; 290 size_t nwaiters; 291 292 pthread__error(EINVAL, "Invalid condition variable", 293 cond->ptc_magic == _PT_COND_MAGIC); 294 295 /* 296 * Try to defer waking threads (see pthread_cond_signal()). 297 * Only transfer waiters for which there is no pending wakeup. 298 */ 299 self = pthread__self(); 300 pthread__spinlock(self, &cond->ptc_lock); 301 max = pthread__unpark_max; 302 mutex = cond->ptc_mutex; 303 nwaiters = self->pt_nwaiters; 304 PTQ_FOREACH(signaled, &cond->ptc_waiters, pt_sleep) { 305 if (__predict_false(nwaiters == max)) { 306 /* Overflow. */ 307 (void)_lwp_unpark_all(self->pt_waiters, 308 nwaiters, __UNVOLATILE(&mutex->ptm_waiters)); 309 nwaiters = 0; 310 } 311 signaled->pt_sleepobj = NULL; 312 self->pt_waiters[nwaiters++] = signaled->pt_lid; 313 } 314 PTQ_INIT(&cond->ptc_waiters); 315 self->pt_nwaiters = nwaiters; 316 cond->ptc_mutex = NULL; 317 pthread__spinunlock(self, &cond->ptc_lock); 318 pthread__mutex_deferwake(self, mutex); 319 320 return 0; 321 } 322 323 int 324 pthread_cond_broadcast(pthread_cond_t *cond) 325 { 326 if (__predict_false(__uselibcstub)) 327 return __libc_cond_broadcast_stub(cond); 328 329 if (__predict_true(PTQ_EMPTY(&cond->ptc_waiters))) 330 return 0; 331 return pthread__cond_wake_all(cond); 332 } 333 334 int 335 _pthread_cond_has_waiters_np(pthread_cond_t *cond) 336 { 337 338 return !PTQ_EMPTY(&cond->ptc_waiters); 339 } 340 341 int 342 pthread_condattr_init(pthread_condattr_t *attr) 343 { 344 345 attr->ptca_magic = _PT_CONDATTR_MAGIC; 346 attr->ptca_private = NULL; 347 348 return 0; 349 } 350 351 int 352 pthread_condattr_setclock(pthread_condattr_t *attr, clockid_t clck) 353 { 354 switch (clck) { 355 case CLOCK_MONOTONIC: 356 case CLOCK_REALTIME: 357 if (attr->ptca_private == NULL) 358 attr->ptca_private = malloc(sizeof(clockid_t)); 359 if (attr->ptca_private == NULL) 360 return errno; 361 *(clockid_t *)attr->ptca_private = clck; 362 return 0; 363 default: 364 return EINVAL; 365 } 366 } 367 368 int 369 pthread_condattr_destroy(pthread_condattr_t *attr) 370 { 371 372 pthread__error(EINVAL, "Invalid condition variable attribute", 373 attr->ptca_magic == _PT_CONDATTR_MAGIC); 374 375 attr->ptca_magic = _PT_CONDATTR_DEAD; 376 free(attr->ptca_private); 377 378 return 0; 379 } 380 381 /* Utility routine to hang out for a while if threads haven't started yet. */ 382 static int 383 pthread_cond_wait_nothread(pthread_t self, pthread_mutex_t *mutex, 384 pthread_cond_t *cond, const struct timespec *abstime) 385 { 386 struct timespec now, diff; 387 int retval; 388 389 if (abstime == NULL) { 390 diff.tv_sec = 99999999; 391 diff.tv_nsec = 0; 392 } else { 393 clockid_t clck = cond->ptc_private ? 394 *(clockid_t *)cond->ptc_private : CLOCK_REALTIME; 395 clock_gettime(clck, &now); 396 if (timespeccmp(abstime, &now, <)) 397 timespecclear(&diff); 398 else 399 timespecsub(abstime, &now, &diff); 400 } 401 402 do { 403 pthread__testcancel(self); 404 pthread_mutex_unlock(mutex); 405 retval = _sys___nanosleep50(&diff, NULL); 406 pthread_mutex_lock(mutex); 407 } while (abstime == NULL && retval == 0); 408 pthread__testcancel(self); 409 410 if (retval == 0) 411 return ETIMEDOUT; 412 else 413 /* spurious wakeup */ 414 return 0; 415 } 416