xref: /netbsd-src/lib/libpthread/pthread_cond.c (revision 33881f779a77dce6440bdc44610d94de75bebefe)
1 /*	$NetBSD: pthread_cond.c,v 1.67 2020/01/29 15:07:46 kamil 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.67 2020/01/29 15:07:46 kamil 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 static clockid_t
79 pthread_cond_getclock(const pthread_cond_t *cond)
80 {
81 
82 	pthread__error(EINVAL, "Invalid condition variable",
83 	    cond->ptc_magic == _PT_COND_MAGIC);
84 
85 	return cond->ptc_private ?
86 	    *(clockid_t *)cond->ptc_private : CLOCK_REALTIME;
87 }
88 
89 int
90 pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr)
91 {
92 	if (__predict_false(__uselibcstub))
93 		return __libc_cond_init_stub(cond, attr);
94 
95 	pthread__error(EINVAL, "Invalid condition variable attribute",
96 	    (attr == NULL) || (attr->ptca_magic == _PT_CONDATTR_MAGIC));
97 
98 	cond->ptc_magic = _PT_COND_MAGIC;
99 	pthread_lockinit(&cond->ptc_lock);
100 	PTQ_INIT(&cond->ptc_waiters);
101 	cond->ptc_mutex = NULL;
102 	if (attr && attr->ptca_private) {
103 		cond->ptc_private = malloc(sizeof(clockid_t));
104 		if (cond->ptc_private == NULL)
105 			return errno;
106 		*(clockid_t *)cond->ptc_private =
107 		    *(clockid_t *)attr->ptca_private;
108 	} else
109 		cond->ptc_private = NULL;
110 
111 	return 0;
112 }
113 
114 
115 int
116 pthread_cond_destroy(pthread_cond_t *cond)
117 {
118 	if (__predict_false(__uselibcstub))
119 		return __libc_cond_destroy_stub(cond);
120 
121 	pthread__error(EINVAL, "Invalid condition variable",
122 	    cond->ptc_magic == _PT_COND_MAGIC);
123 	pthread__error(EBUSY, "Destroying condition variable in use",
124 	    cond->ptc_mutex == NULL);
125 
126 	cond->ptc_magic = _PT_COND_DEAD;
127 	free(cond->ptc_private);
128 
129 	return 0;
130 }
131 
132 int
133 pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex,
134 		       const struct timespec *abstime)
135 {
136 	pthread_t self;
137 	int retval;
138 	clockid_t clkid = pthread_cond_getclock(cond);
139 
140 	if (__predict_false(__uselibcstub))
141 		return __libc_cond_timedwait_stub(cond, mutex, abstime);
142 
143 	pthread__error(EINVAL, "Invalid condition variable",
144 	    cond->ptc_magic == _PT_COND_MAGIC);
145 	pthread__error(EINVAL, "Invalid mutex",
146 	    mutex->ptm_magic == _PT_MUTEX_MAGIC);
147 	pthread__error(EPERM, "Mutex not locked in condition wait",
148 	    mutex->ptm_owner != NULL);
149 
150 	self = pthread__self();
151 
152 	/* Just hang out for a while if threads aren't running yet. */
153 	if (__predict_false(pthread__started == 0)) {
154 		return pthread_cond_wait_nothread(self, mutex, cond, abstime);
155 	}
156 	if (__predict_false(self->pt_cancel)) {
157 		pthread__cancelled();
158 	}
159 
160 	/* Note this thread as waiting on the CV. */
161 	pthread__spinlock(self, &cond->ptc_lock);
162 	cond->ptc_mutex = mutex;
163 	PTQ_INSERT_HEAD(&cond->ptc_waiters, self, pt_sleep);
164 	self->pt_sleepobj = cond;
165 	pthread__spinunlock(self, &cond->ptc_lock);
166 
167 	do {
168 		self->pt_willpark = 1;
169 		pthread_mutex_unlock(mutex);
170 		self->pt_willpark = 0;
171 		do {
172 			retval = _lwp_park(clkid, TIMER_ABSTIME,
173 			    __UNCONST(abstime), self->pt_unpark,
174 			    __UNVOLATILE(&mutex->ptm_waiters),
175 			    __UNVOLATILE(&mutex->ptm_waiters));
176 			self->pt_unpark = 0;
177 		} while (retval == -1 && errno == ESRCH);
178 		pthread_mutex_lock(mutex);
179 
180 		/*
181 		 * If we have cancelled then exit.  POSIX dictates that
182 		 * the mutex must be held when we action the cancellation.
183 		 *
184 		 * If we absorbed a pthread_cond_signal() and cannot take
185 		 * the wakeup, we must ensure that another thread does.
186 		 *
187 		 * If awoke early, we may still be on the sleep queue and
188 		 * must remove ourself.
189 		 */
190 		if (__predict_false(retval != 0)) {
191 			switch (errno) {
192 			case EINTR:
193 			case EALREADY:
194 				retval = 0;
195 				break;
196 			default:
197 				retval = errno;
198 				break;
199 			}
200 		}
201 		if (__predict_false(self->pt_cancel | retval)) {
202 			pthread_cond_signal(cond);
203 			if (self->pt_cancel) {
204 				pthread__cancelled();
205 			}
206 			break;
207 		}
208 	} while (self->pt_sleepobj != NULL);
209 
210 	return retval;
211 }
212 
213 int
214 pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
215 {
216 	if (__predict_false(__uselibcstub))
217 		return __libc_cond_wait_stub(cond, mutex);
218 
219 	return pthread_cond_timedwait(cond, mutex, NULL);
220 }
221 
222 static int __noinline
223 pthread__cond_wake_one(pthread_cond_t *cond)
224 {
225 	pthread_t self, signaled;
226 	pthread_mutex_t *mutex;
227 	lwpid_t lid;
228 
229 	/*
230 	 * Pull the first thread off the queue.  If the current thread
231 	 * is associated with the condition variable, remove it without
232 	 * awakening (error case in pthread_cond_timedwait()).
233 	 */
234 	self = pthread__self();
235 	pthread__spinlock(self, &cond->ptc_lock);
236 	if (self->pt_sleepobj == cond) {
237 		PTQ_REMOVE(&cond->ptc_waiters, self, pt_sleep);
238 		self->pt_sleepobj = NULL;
239 	}
240 	signaled = PTQ_FIRST(&cond->ptc_waiters);
241 	if (__predict_false(signaled == NULL)) {
242 		cond->ptc_mutex = NULL;
243 		pthread__spinunlock(self, &cond->ptc_lock);
244 		return 0;
245 	}
246 	mutex = cond->ptc_mutex;
247 	if (PTQ_NEXT(signaled, pt_sleep) == NULL) {
248 		cond->ptc_mutex = NULL;
249 		PTQ_INIT(&cond->ptc_waiters);
250 	} else {
251 		PTQ_REMOVE(&cond->ptc_waiters, signaled, pt_sleep);
252 	}
253 	signaled->pt_sleepobj = NULL;
254 	lid = signaled->pt_lid;
255 	pthread__spinunlock(self, &cond->ptc_lock);
256 
257 	/*
258 	 * For all valid uses of pthread_cond_signal(), the caller will
259 	 * hold the mutex that the target is using to synchronize with.
260 	 * To avoid the target awakening and immediately blocking on the
261 	 * mutex, transfer the thread to be awoken to the current thread's
262 	 * deferred wakeup list.  The waiter will be set running when the
263 	 * caller (this thread) releases the mutex.
264 	 */
265 	if (__predict_false(self->pt_nwaiters == (size_t)pthread__unpark_max)) {
266 		(void)_lwp_unpark_all(self->pt_waiters, self->pt_nwaiters,
267 		    __UNVOLATILE(&mutex->ptm_waiters));
268 		self->pt_nwaiters = 0;
269 	}
270 	self->pt_waiters[self->pt_nwaiters++] = lid;
271 	pthread__mutex_deferwake(self, mutex);
272 	return 0;
273 }
274 
275 int
276 pthread_cond_signal(pthread_cond_t *cond)
277 {
278 
279 	if (__predict_false(__uselibcstub))
280 		return __libc_cond_signal_stub(cond);
281 
282 	pthread__error(EINVAL, "Invalid condition variable",
283 	    cond->ptc_magic == _PT_COND_MAGIC);
284 
285 	if (__predict_true(PTQ_EMPTY(&cond->ptc_waiters)))
286 		return 0;
287 	return pthread__cond_wake_one(cond);
288 }
289 
290 static int __noinline
291 pthread__cond_wake_all(pthread_cond_t *cond)
292 {
293 	pthread_t self, signaled;
294 	pthread_mutex_t *mutex;
295 	u_int max;
296 	size_t nwaiters;
297 
298 	/*
299 	 * Try to defer waking threads (see pthread_cond_signal()).
300 	 * Only transfer waiters for which there is no pending wakeup.
301 	 */
302 	self = pthread__self();
303 	pthread__spinlock(self, &cond->ptc_lock);
304 	max = pthread__unpark_max;
305 	mutex = cond->ptc_mutex;
306 	nwaiters = self->pt_nwaiters;
307 	PTQ_FOREACH(signaled, &cond->ptc_waiters, pt_sleep) {
308 		if (__predict_false(nwaiters == max)) {
309 			/* Overflow. */
310 			(void)_lwp_unpark_all(self->pt_waiters,
311 			    nwaiters, __UNVOLATILE(&mutex->ptm_waiters));
312 			nwaiters = 0;
313 		}
314 		signaled->pt_sleepobj = NULL;
315 		self->pt_waiters[nwaiters++] = signaled->pt_lid;
316 	}
317 	PTQ_INIT(&cond->ptc_waiters);
318 	self->pt_nwaiters = nwaiters;
319 	cond->ptc_mutex = NULL;
320 	pthread__spinunlock(self, &cond->ptc_lock);
321 	pthread__mutex_deferwake(self, mutex);
322 
323 	return 0;
324 }
325 
326 int
327 pthread_cond_broadcast(pthread_cond_t *cond)
328 {
329 	if (__predict_false(__uselibcstub))
330 		return __libc_cond_broadcast_stub(cond);
331 
332 	pthread__error(EINVAL, "Invalid condition variable",
333 	    cond->ptc_magic == _PT_COND_MAGIC);
334 
335 	if (__predict_true(PTQ_EMPTY(&cond->ptc_waiters)))
336 		return 0;
337 	return pthread__cond_wake_all(cond);
338 }
339 
340 int
341 _pthread_cond_has_waiters_np(pthread_cond_t *cond)
342 {
343 
344 	return !PTQ_EMPTY(&cond->ptc_waiters);
345 }
346 
347 int
348 pthread_condattr_init(pthread_condattr_t *attr)
349 {
350 
351 	attr->ptca_magic = _PT_CONDATTR_MAGIC;
352 	attr->ptca_private = NULL;
353 
354 	return 0;
355 }
356 
357 int
358 pthread_condattr_setclock(pthread_condattr_t *attr, clockid_t clck)
359 {
360 
361 	pthread__error(EINVAL, "Invalid condition variable attribute",
362 	    attr->ptca_magic == _PT_CONDATTR_MAGIC);
363 
364 	switch (clck) {
365 	case CLOCK_MONOTONIC:
366 	case CLOCK_REALTIME:
367 		if (attr->ptca_private == NULL)
368 			attr->ptca_private = malloc(sizeof(clockid_t));
369 		if (attr->ptca_private == NULL)
370 			return errno;
371 		*(clockid_t *)attr->ptca_private = clck;
372 		return 0;
373 	default:
374 		return EINVAL;
375 	}
376 }
377 
378 int
379 pthread_condattr_getclock(const pthread_condattr_t *__restrict attr,
380     clockid_t *__restrict clock_id)
381 {
382 
383 	pthread__error(EINVAL, "Invalid condition variable attribute",
384 	    attr->ptca_magic == _PT_CONDATTR_MAGIC);
385 
386 	if (attr == NULL || attr->ptca_private == NULL)
387 		return EINVAL;
388 	*clock_id = *(clockid_t *)attr->ptca_private;
389 	return 0;
390 }
391 
392 int
393 pthread_condattr_destroy(pthread_condattr_t *attr)
394 {
395 
396 	pthread__error(EINVAL, "Invalid condition variable attribute",
397 	    attr->ptca_magic == _PT_CONDATTR_MAGIC);
398 
399 	attr->ptca_magic = _PT_CONDATTR_DEAD;
400 	free(attr->ptca_private);
401 
402 	return 0;
403 }
404 
405 #ifdef _PTHREAD_PSHARED
406 int
407 pthread_condattr_getpshared(const pthread_condattr_t * __restrict attr,
408     int * __restrict pshared)
409 {
410 
411 	pthread__error(EINVAL, "Invalid condition variable attribute",
412 	    attr->ptca_magic == _PT_CONDATTR_MAGIC);
413 
414 	*pshared = PTHREAD_PROCESS_PRIVATE;
415 	return 0;
416 }
417 
418 int
419 pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
420 {
421 
422 	pthread__error(EINVAL, "Invalid condition variable attribute",
423 	    attr->ptca_magic == _PT_CONDATTR_MAGIC);
424 
425 	switch(pshared) {
426 	case PTHREAD_PROCESS_PRIVATE:
427 		return 0;
428 	case PTHREAD_PROCESS_SHARED:
429 		return ENOSYS;
430 	}
431 	return EINVAL;
432 }
433 #endif
434 
435 /* Utility routine to hang out for a while if threads haven't started yet. */
436 static int
437 pthread_cond_wait_nothread(pthread_t self, pthread_mutex_t *mutex,
438     pthread_cond_t *cond, const struct timespec *abstime)
439 {
440 	struct timespec now, diff;
441 	int retval;
442 
443 	if (abstime == NULL) {
444 		diff.tv_sec = 99999999;
445 		diff.tv_nsec = 0;
446 	} else {
447 		clockid_t clck = pthread_cond_getclock(cond);
448 		clock_gettime(clck, &now);
449 		if  (timespeccmp(abstime, &now, <))
450 			timespecclear(&diff);
451 		else
452 			timespecsub(abstime, &now, &diff);
453 	}
454 
455 	do {
456 		pthread__testcancel(self);
457 		pthread_mutex_unlock(mutex);
458 		retval = _sys___nanosleep50(&diff, NULL);
459 		pthread_mutex_lock(mutex);
460 	} while (abstime == NULL && retval == 0);
461 	pthread__testcancel(self);
462 
463 	if (retval == 0)
464 		return ETIMEDOUT;
465 	else
466 		/* spurious wakeup */
467 		return 0;
468 }
469