blob: 59fb8b3c5b98b070807c5756f4d529b9943492ad [file] [log] [blame]
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
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 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
Pierre Peifferd0c884d2012-02-22 16:40:15 +010028
Elliott Hughes6f94de32013-02-12 06:06:22 +000029#include <pthread.h>
Elliott Hughes3e898472013-02-12 16:40:24 +000030
31#include <errno.h>
32#include <limits.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080033#include <sys/atomics.h>
Pierre Peifferd0c884d2012-02-22 16:40:15 +010034#include <unistd.h>
35
36#include "bionic_atomic_inline.h"
37#include "bionic_futex.h"
38#include "bionic_pthread.h"
39#include "bionic_tls.h"
40#include "pthread_internal.h"
41#include "thread_private.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080042
Mathias Agopian7c0c3792011-09-05 23:54:55 -070043extern void pthread_debug_mutex_lock_check(pthread_mutex_t *mutex);
44extern void pthread_debug_mutex_unlock_check(pthread_mutex_t *mutex);
45
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080046extern void _exit_with_stack_teardown(void * stackBase, int stackSize, int retCode);
47extern void _exit_thread(int retCode);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080048
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -070049int __futex_wake_ex(volatile void *ftx, int pshared, int val)
50{
51 return __futex_syscall3(ftx, pshared ? FUTEX_WAKE : FUTEX_WAKE_PRIVATE, val);
52}
53
54int __futex_wait_ex(volatile void *ftx, int pshared, int val, const struct timespec *timeout)
55{
56 return __futex_syscall4(ftx, pshared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE, val, timeout);
57}
58
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -070059#define __likely(cond) __builtin_expect(!!(cond), 1)
60#define __unlikely(cond) __builtin_expect(!!(cond), 0)
61
Elliott Hughes44b53ad2013-02-11 20:18:47 +000062__LIBC_HIDDEN__ pthread_internal_t* gThreadList = NULL;
63__LIBC_HIDDEN__ pthread_mutex_t gThreadListLock = PTHREAD_MUTEX_INITIALIZER;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080064
Elliott Hughes4f251be2012-11-01 16:33:29 -070065static void _pthread_internal_remove_locked(pthread_internal_t* thread) {
66 if (thread->next != NULL) {
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070067 thread->next->prev = thread->prev;
Elliott Hughes4f251be2012-11-01 16:33:29 -070068 }
69 if (thread->prev != NULL) {
70 thread->prev->next = thread->next;
71 } else {
72 gThreadList = thread->next;
73 }
74
75 // The main thread is not heap-allocated. See __libc_init_tls for the declaration,
76 // and __libc_init_common for the point where it's added to the thread list.
77 if (thread->allocated_on_heap) {
78 free(thread);
79 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080080}
81
Elliott Hughes4f251be2012-11-01 16:33:29 -070082static void _pthread_internal_remove(pthread_internal_t* thread) {
83 pthread_mutex_lock(&gThreadListLock);
84 _pthread_internal_remove_locked(thread);
85 pthread_mutex_unlock(&gThreadListLock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080086}
87
Elliott Hughes4f251be2012-11-01 16:33:29 -070088__LIBC_ABI_PRIVATE__ void _pthread_internal_add(pthread_internal_t* thread) {
89 pthread_mutex_lock(&gThreadListLock);
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070090
Elliott Hughes4f251be2012-11-01 16:33:29 -070091 // We insert at the head.
92 thread->next = gThreadList;
93 thread->prev = NULL;
94 if (thread->next != NULL) {
95 thread->next->prev = thread;
96 }
97 gThreadList = thread;
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070098
Elliott Hughes4f251be2012-11-01 16:33:29 -070099 pthread_mutex_unlock(&gThreadListLock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800100}
101
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +0400102__LIBC_ABI_PRIVATE__ pthread_internal_t*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800103__get_thread(void)
104{
105 void** tls = (void**)__get_tls();
106
107 return (pthread_internal_t*) tls[TLS_SLOT_THREAD_ID];
108}
109
110
111void*
112__get_stack_base(int *p_stack_size)
113{
114 pthread_internal_t* thread = __get_thread();
115
116 *p_stack_size = thread->attr.stack_size;
117 return thread->attr.stack_base;
118}
119
120
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800121/* CAVEAT: our implementation of pthread_cleanup_push/pop doesn't support C++ exceptions
122 * and thread cancelation
123 */
124
125void __pthread_cleanup_push( __pthread_cleanup_t* c,
126 __pthread_cleanup_func_t routine,
127 void* arg )
128{
129 pthread_internal_t* thread = __get_thread();
130
131 c->__cleanup_routine = routine;
132 c->__cleanup_arg = arg;
133 c->__cleanup_prev = thread->cleanup_stack;
134 thread->cleanup_stack = c;
135}
136
137void __pthread_cleanup_pop( __pthread_cleanup_t* c, int execute )
138{
139 pthread_internal_t* thread = __get_thread();
140
141 thread->cleanup_stack = c->__cleanup_prev;
142 if (execute)
143 c->__cleanup_routine(c->__cleanup_arg);
144}
145
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800146void pthread_exit(void * retval)
147{
148 pthread_internal_t* thread = __get_thread();
149 void* stack_base = thread->attr.stack_base;
150 int stack_size = thread->attr.stack_size;
151 int user_stack = (thread->attr.flags & PTHREAD_ATTR_FLAG_USER_STACK) != 0;
Jack Rene480fc82011-09-21 12:44:11 +0200152 sigset_t mask;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800153
154 // call the cleanup handlers first
155 while (thread->cleanup_stack) {
156 __pthread_cleanup_t* c = thread->cleanup_stack;
157 thread->cleanup_stack = c->__cleanup_prev;
158 c->__cleanup_routine(c->__cleanup_arg);
159 }
160
161 // call the TLS destructors, it is important to do that before removing this
162 // thread from the global list. this will ensure that if someone else deletes
163 // a TLS key, the corresponding value will be set to NULL in this thread's TLS
164 // space (see pthread_key_delete)
165 pthread_key_clean_all();
166
167 // if the thread is detached, destroy the pthread_internal_t
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400168 // otherwise, keep it in memory and signal any joiners.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800169 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
170 _pthread_internal_remove(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800171 } else {
Bjorn Andersson0753dc62012-05-03 17:12:39 -0700172 pthread_mutex_lock(&gThreadListLock);
173
174 /* make sure that the thread struct doesn't have stale pointers to a stack that
175 * will be unmapped after the exit call below.
176 */
177 if (!user_stack) {
178 thread->attr.stack_base = NULL;
179 thread->attr.stack_size = 0;
180 thread->tls = NULL;
181 }
182
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800183 /* the join_count field is used to store the number of threads waiting for
184 * the termination of this thread with pthread_join(),
185 *
186 * if it is positive we need to signal the waiters, and we do not touch
187 * the count (it will be decremented by the waiters, the last one will
188 * also remove/free the thread structure
189 *
190 * if it is zero, we set the count value to -1 to indicate that the
191 * thread is in 'zombie' state: it has stopped executing, and its stack
192 * is gone (as well as its TLS area). when another thread calls pthread_join()
193 * on it, it will immediately free the thread and return.
194 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800195 thread->return_value = retval;
196 if (thread->join_count > 0) {
197 pthread_cond_broadcast(&thread->join_cond);
198 } else {
199 thread->join_count = -1; /* zombie thread */
200 }
201 pthread_mutex_unlock(&gThreadListLock);
202 }
203
Jack Rene480fc82011-09-21 12:44:11 +0200204 sigfillset(&mask);
205 sigdelset(&mask, SIGSEGV);
206 (void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *)NULL);
207
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800208 // destroy the thread stack
209 if (user_stack)
210 _exit_thread((int)retval);
211 else
212 _exit_with_stack_teardown(stack_base, stack_size, (int)retval);
213}
214
215int pthread_join(pthread_t thid, void ** ret_val)
216{
217 pthread_internal_t* thread = (pthread_internal_t*)thid;
Elliott Hughes14f19592012-10-29 10:19:44 -0700218 if (thid == pthread_self()) {
219 return EDEADLK;
220 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800221
222 // check that the thread still exists and is not detached
223 pthread_mutex_lock(&gThreadListLock);
224
Elliott Hughes14f19592012-10-29 10:19:44 -0700225 for (thread = gThreadList; thread != NULL; thread = thread->next) {
226 if (thread == (pthread_internal_t*)thid) {
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200227 goto FoundIt;
Elliott Hughes14f19592012-10-29 10:19:44 -0700228 }
229 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800230
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200231 pthread_mutex_unlock(&gThreadListLock);
232 return ESRCH;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800233
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200234FoundIt:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800235 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
236 pthread_mutex_unlock(&gThreadListLock);
237 return EINVAL;
238 }
239
240 /* wait for thread death when needed
241 *
242 * if the 'join_count' is negative, this is a 'zombie' thread that
243 * is already dead and without stack/TLS
244 *
245 * otherwise, we need to increment 'join-count' and wait to be signaled
246 */
Elliott Hughes14f19592012-10-29 10:19:44 -0700247 int count = thread->join_count;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800248 if (count >= 0) {
249 thread->join_count += 1;
250 pthread_cond_wait( &thread->join_cond, &gThreadListLock );
251 count = --thread->join_count;
252 }
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400253 if (ret_val) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800254 *ret_val = thread->return_value;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400255 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800256
257 /* remove thread descriptor when we're the last joiner or when the
258 * thread was already a zombie.
259 */
260 if (count <= 0) {
261 _pthread_internal_remove_locked(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800262 }
263 pthread_mutex_unlock(&gThreadListLock);
264 return 0;
265}
266
267int pthread_detach( pthread_t thid )
268{
269 pthread_internal_t* thread;
270 int result = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800271
272 pthread_mutex_lock(&gThreadListLock);
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400273 for (thread = gThreadList; thread != NULL; thread = thread->next) {
274 if (thread == (pthread_internal_t*)thid) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800275 goto FoundIt;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400276 }
277 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800278
279 result = ESRCH;
280 goto Exit;
281
282FoundIt:
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400283 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
284 result = EINVAL; // Already detached.
285 goto Exit;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800286 }
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400287
288 if (thread->join_count > 0) {
289 result = 0; // Already being joined; silently do nothing, like glibc.
290 goto Exit;
291 }
292
293 thread->attr.flags |= PTHREAD_ATTR_FLAG_DETACHED;
294
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800295Exit:
296 pthread_mutex_unlock(&gThreadListLock);
297 return result;
298}
299
300pthread_t pthread_self(void)
301{
302 return (pthread_t)__get_thread();
303}
304
305int pthread_equal(pthread_t one, pthread_t two)
306{
307 return (one == two ? 1 : 0);
308}
309
310int pthread_getschedparam(pthread_t thid, int * policy,
311 struct sched_param * param)
312{
313 int old_errno = errno;
314
315 pthread_internal_t * thread = (pthread_internal_t *)thid;
316 int err = sched_getparam(thread->kernel_id, param);
317 if (!err) {
318 *policy = sched_getscheduler(thread->kernel_id);
319 } else {
320 err = errno;
321 errno = old_errno;
322 }
323 return err;
324}
325
326int pthread_setschedparam(pthread_t thid, int policy,
327 struct sched_param const * param)
328{
329 pthread_internal_t * thread = (pthread_internal_t *)thid;
330 int old_errno = errno;
331 int ret;
332
333 ret = sched_setscheduler(thread->kernel_id, policy, param);
334 if (ret < 0) {
335 ret = errno;
336 errno = old_errno;
337 }
338 return ret;
339}
340
341
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800342/* a mutex is implemented as a 32-bit integer holding the following fields
343 *
344 * bits: name description
345 * 31-16 tid owner thread's kernel id (recursive and errorcheck only)
346 * 15-14 type mutex type
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700347 * 13 shared process-shared flag
348 * 12-2 counter counter of recursive mutexes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800349 * 1-0 state lock state (0, 1 or 2)
350 */
351
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100352/* Convenience macro, creates a mask of 'bits' bits that starts from
353 * the 'shift'-th least significant bit in a 32-bit word.
354 *
355 * Examples: FIELD_MASK(0,4) -> 0xf
356 * FIELD_MASK(16,9) -> 0x1ff0000
357 */
358#define FIELD_MASK(shift,bits) (((1 << (bits))-1) << (shift))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800359
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100360/* This one is used to create a bit pattern from a given field value */
361#define FIELD_TO_BITS(val,shift,bits) (((val) & ((1 << (bits))-1)) << (shift))
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100362
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100363/* And this one does the opposite, i.e. extract a field's value from a bit pattern */
364#define FIELD_FROM_BITS(val,shift,bits) (((val) >> (shift)) & ((1 << (bits))-1))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800365
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100366/* Mutex state:
367 *
368 * 0 for unlocked
369 * 1 for locked, no waiters
370 * 2 for locked, maybe waiters
371 */
372#define MUTEX_STATE_SHIFT 0
373#define MUTEX_STATE_LEN 2
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800374
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100375#define MUTEX_STATE_MASK FIELD_MASK(MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
376#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
377#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
378
379#define MUTEX_STATE_UNLOCKED 0 /* must be 0 to match __PTHREAD_MUTEX_INIT_VALUE */
380#define MUTEX_STATE_LOCKED_UNCONTENDED 1 /* must be 1 due to atomic dec in unlock operation */
381#define MUTEX_STATE_LOCKED_CONTENDED 2 /* must be 1 + LOCKED_UNCONTENDED due to atomic dec */
382
383#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
384#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
385
386#define MUTEX_STATE_BITS_UNLOCKED MUTEX_STATE_TO_BITS(MUTEX_STATE_UNLOCKED)
387#define MUTEX_STATE_BITS_LOCKED_UNCONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_UNCONTENDED)
388#define MUTEX_STATE_BITS_LOCKED_CONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_CONTENDED)
389
390/* return true iff the mutex if locked with no waiters */
391#define MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_UNCONTENDED)
392
393/* return true iff the mutex if locked with maybe waiters */
394#define MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_CONTENDED)
395
396/* used to flip from LOCKED_UNCONTENDED to LOCKED_CONTENDED */
397#define MUTEX_STATE_BITS_FLIP_CONTENTION(v) ((v) ^ (MUTEX_STATE_BITS_LOCKED_CONTENDED ^ MUTEX_STATE_BITS_LOCKED_UNCONTENDED))
398
399/* Mutex counter:
400 *
401 * We need to check for overflow before incrementing, and we also need to
402 * detect when the counter is 0
403 */
404#define MUTEX_COUNTER_SHIFT 2
405#define MUTEX_COUNTER_LEN 11
406#define MUTEX_COUNTER_MASK FIELD_MASK(MUTEX_COUNTER_SHIFT, MUTEX_COUNTER_LEN)
407
408#define MUTEX_COUNTER_BITS_WILL_OVERFLOW(v) (((v) & MUTEX_COUNTER_MASK) == MUTEX_COUNTER_MASK)
409#define MUTEX_COUNTER_BITS_IS_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
410
411/* Used to increment the counter directly after overflow has been checked */
412#define MUTEX_COUNTER_BITS_ONE FIELD_TO_BITS(1,MUTEX_COUNTER_SHIFT,MUTEX_COUNTER_LEN)
413
414/* Returns true iff the counter is 0 */
415#define MUTEX_COUNTER_BITS_ARE_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
416
417/* Mutex shared bit flag
418 *
419 * This flag is set to indicate that the mutex is shared among processes.
420 * This changes the futex opcode we use for futex wait/wake operations
421 * (non-shared operations are much faster).
422 */
423#define MUTEX_SHARED_SHIFT 13
424#define MUTEX_SHARED_MASK FIELD_MASK(MUTEX_SHARED_SHIFT,1)
425
426/* Mutex type:
427 *
428 * We support normal, recursive and errorcheck mutexes.
429 *
430 * The constants defined here *cannot* be changed because they must match
431 * the C library ABI which defines the following initialization values in
432 * <pthread.h>:
433 *
434 * __PTHREAD_MUTEX_INIT_VALUE
435 * __PTHREAD_RECURSIVE_MUTEX_VALUE
436 * __PTHREAD_ERRORCHECK_MUTEX_INIT_VALUE
437 */
438#define MUTEX_TYPE_SHIFT 14
439#define MUTEX_TYPE_LEN 2
440#define MUTEX_TYPE_MASK FIELD_MASK(MUTEX_TYPE_SHIFT,MUTEX_TYPE_LEN)
441
442#define MUTEX_TYPE_NORMAL 0 /* Must be 0 to match __PTHREAD_MUTEX_INIT_VALUE */
443#define MUTEX_TYPE_RECURSIVE 1
444#define MUTEX_TYPE_ERRORCHECK 2
445
446#define MUTEX_TYPE_TO_BITS(t) FIELD_TO_BITS(t, MUTEX_TYPE_SHIFT, MUTEX_TYPE_LEN)
447
448#define MUTEX_TYPE_BITS_NORMAL MUTEX_TYPE_TO_BITS(MUTEX_TYPE_NORMAL)
449#define MUTEX_TYPE_BITS_RECURSIVE MUTEX_TYPE_TO_BITS(MUTEX_TYPE_RECURSIVE)
450#define MUTEX_TYPE_BITS_ERRORCHECK MUTEX_TYPE_TO_BITS(MUTEX_TYPE_ERRORCHECK)
451
452/* Mutex owner field:
453 *
454 * This is only used for recursive and errorcheck mutexes. It holds the
455 * kernel TID of the owning thread. Note that this works because the Linux
456 * kernel _only_ uses 16-bit values for thread ids.
457 *
458 * More specifically, it will wrap to 10000 when it reaches over 32768 for
459 * application processes. You can check this by running the following inside
460 * an adb shell session:
461 *
462 OLDPID=$$;
463 while true; do
464 NEWPID=$(sh -c 'echo $$')
465 if [ "$NEWPID" -gt 32768 ]; then
466 echo "AARGH: new PID $NEWPID is too high!"
467 exit 1
468 fi
469 if [ "$NEWPID" -lt "$OLDPID" ]; then
470 echo "****** Wrapping from PID $OLDPID to $NEWPID. *******"
471 else
472 echo -n "$NEWPID!"
473 fi
474 OLDPID=$NEWPID
475 done
476
477 * Note that you can run the same example on a desktop Linux system,
478 * the wrapping will also happen at 32768, but will go back to 300 instead.
479 */
480#define MUTEX_OWNER_SHIFT 16
481#define MUTEX_OWNER_LEN 16
482
483#define MUTEX_OWNER_FROM_BITS(v) FIELD_FROM_BITS(v,MUTEX_OWNER_SHIFT,MUTEX_OWNER_LEN)
484#define MUTEX_OWNER_TO_BITS(v) FIELD_TO_BITS(v,MUTEX_OWNER_SHIFT,MUTEX_OWNER_LEN)
485
486/* Convenience macros.
487 *
488 * These are used to form or modify the bit pattern of a given mutex value
489 */
490
491
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800492
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700493/* a mutex attribute holds the following fields
494 *
495 * bits: name description
496 * 0-3 type type of mutex
497 * 4 shared process-shared flag
498 */
499#define MUTEXATTR_TYPE_MASK 0x000f
500#define MUTEXATTR_SHARED_MASK 0x0010
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800501
502
503int pthread_mutexattr_init(pthread_mutexattr_t *attr)
504{
505 if (attr) {
506 *attr = PTHREAD_MUTEX_DEFAULT;
507 return 0;
508 } else {
509 return EINVAL;
510 }
511}
512
513int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
514{
515 if (attr) {
516 *attr = -1;
517 return 0;
518 } else {
519 return EINVAL;
520 }
521}
522
523int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
524{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700525 if (attr) {
526 int atype = (*attr & MUTEXATTR_TYPE_MASK);
527
528 if (atype >= PTHREAD_MUTEX_NORMAL &&
529 atype <= PTHREAD_MUTEX_ERRORCHECK) {
530 *type = atype;
531 return 0;
532 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800533 }
534 return EINVAL;
535}
536
537int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
538{
539 if (attr && type >= PTHREAD_MUTEX_NORMAL &&
540 type <= PTHREAD_MUTEX_ERRORCHECK ) {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700541 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800542 return 0;
543 }
544 return EINVAL;
545}
546
547/* process-shared mutexes are not supported at the moment */
548
549int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
550{
551 if (!attr)
552 return EINVAL;
553
Mathias Agopianb7681162009-07-13 22:00:33 -0700554 switch (pshared) {
555 case PTHREAD_PROCESS_PRIVATE:
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700556 *attr &= ~MUTEXATTR_SHARED_MASK;
557 return 0;
558
Mathias Agopianb7681162009-07-13 22:00:33 -0700559 case PTHREAD_PROCESS_SHARED:
560 /* our current implementation of pthread actually supports shared
561 * mutexes but won't cleanup if a process dies with the mutex held.
562 * Nevertheless, it's better than nothing. Shared mutexes are used
563 * by surfaceflinger and audioflinger.
564 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700565 *attr |= MUTEXATTR_SHARED_MASK;
Mathias Agopianb7681162009-07-13 22:00:33 -0700566 return 0;
567 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700568 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800569}
570
571int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
572{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700573 if (!attr || !pshared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800574 return EINVAL;
575
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700576 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED
577 : PTHREAD_PROCESS_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800578 return 0;
579}
580
581int pthread_mutex_init(pthread_mutex_t *mutex,
582 const pthread_mutexattr_t *attr)
583{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700584 int value = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800585
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700586 if (mutex == NULL)
587 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800588
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700589 if (__likely(attr == NULL)) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100590 mutex->value = MUTEX_TYPE_BITS_NORMAL;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700591 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800592 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700593
594 if ((*attr & MUTEXATTR_SHARED_MASK) != 0)
595 value |= MUTEX_SHARED_MASK;
596
597 switch (*attr & MUTEXATTR_TYPE_MASK) {
598 case PTHREAD_MUTEX_NORMAL:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100599 value |= MUTEX_TYPE_BITS_NORMAL;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700600 break;
601 case PTHREAD_MUTEX_RECURSIVE:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100602 value |= MUTEX_TYPE_BITS_RECURSIVE;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700603 break;
604 case PTHREAD_MUTEX_ERRORCHECK:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100605 value |= MUTEX_TYPE_BITS_ERRORCHECK;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700606 break;
607 default:
608 return EINVAL;
609 }
610
611 mutex->value = value;
612 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800613}
614
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800615
616/*
617 * Lock a non-recursive mutex.
618 *
619 * As noted above, there are three states:
620 * 0 (unlocked, no contention)
621 * 1 (locked, no contention)
622 * 2 (locked, contention)
623 *
624 * Non-recursive mutexes don't use the thread-id or counter fields, and the
625 * "type" value is zero, so the only bits that will be set are the ones in
626 * the lock state field.
627 */
628static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100629_normal_lock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800630{
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100631 /* convenience shortcuts */
632 const int unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
633 const int locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800634 /*
635 * The common case is an unlocked mutex, so we begin by trying to
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100636 * change the lock's state from 0 (UNLOCKED) to 1 (LOCKED).
637 * __bionic_cmpxchg() returns 0 if it made the swap successfully.
638 * If the result is nonzero, this lock is already held by another thread.
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800639 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100640 if (__bionic_cmpxchg(unlocked, locked_uncontended, &mutex->value) != 0) {
641 const int locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800642 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800643 * We want to go to sleep until the mutex is available, which
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100644 * requires promoting it to state 2 (CONTENDED). We need to
645 * swap in the new state value and then wait until somebody wakes us up.
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800646 *
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100647 * __bionic_swap() returns the previous value. We swap 2 in and
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800648 * see if we got zero back; if so, we have acquired the lock. If
649 * not, another thread still holds the lock and we wait again.
650 *
651 * The second argument to the __futex_wait() call is compared
652 * against the current value. If it doesn't match, __futex_wait()
653 * returns immediately (otherwise, it sleeps for a time specified
654 * by the third argument; 0 means sleep forever). This ensures
655 * that the mutex is in state 2 when we go to sleep on it, which
656 * guarantees a wake-up call.
657 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100658 while (__bionic_swap(locked_contended, &mutex->value) != unlocked)
659 __futex_wait_ex(&mutex->value, shared, locked_contended, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800660 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700661 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800662}
663
664/*
665 * Release a non-recursive mutex. The caller is responsible for determining
666 * that we are in fact the owner of this lock.
667 */
668static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100669_normal_unlock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800670{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700671 ANDROID_MEMBAR_FULL();
672
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800673 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700674 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100675 * to release the lock. __bionic_atomic_dec() returns the previous value;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800676 * if it wasn't 1 we have to do some additional work.
677 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100678 if (__bionic_atomic_dec(&mutex->value) != (shared|MUTEX_STATE_BITS_LOCKED_UNCONTENDED)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800679 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800680 * Start by releasing the lock. The decrement changed it from
681 * "contended lock" to "uncontended lock", which means we still
682 * hold it, and anybody who tries to sneak in will push it back
683 * to state 2.
684 *
685 * Once we set it to zero the lock is up for grabs. We follow
686 * this with a __futex_wake() to ensure that one of the waiting
687 * threads has a chance to grab it.
688 *
689 * This doesn't cause a race with the swap/wait pair in
690 * _normal_lock(), because the __futex_wait() call there will
691 * return immediately if the mutex value isn't 2.
692 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700693 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800694
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800695 /*
696 * Wake up one waiting thread. We don't know which thread will be
697 * woken or when it'll start executing -- futexes make no guarantees
698 * here. There may not even be a thread waiting.
699 *
700 * The newly-woken thread will replace the 0 we just set above
701 * with 2, which means that when it eventually releases the mutex
702 * it will also call FUTEX_WAKE. This results in one extra wake
703 * call whenever a lock is contended, but lets us avoid forgetting
704 * anyone without requiring us to track the number of sleepers.
705 *
706 * It's possible for another thread to sneak in and grab the lock
707 * between the zero assignment above and the wake call below. If
708 * the new thread is "slow" and holds the lock for a while, we'll
709 * wake up a sleeper, which will swap in a 2 and then go back to
710 * sleep since the lock is still held. If the new thread is "fast",
711 * running to completion before we call wake, the thread we
712 * eventually wake will find an unlocked mutex and will execute.
713 * Either way we have correct behavior and nobody is orphaned on
714 * the wait queue.
715 */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -0700716 __futex_wake_ex(&mutex->value, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800717 }
718}
719
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100720/* This common inlined function is used to increment the counter of an
721 * errorcheck or recursive mutex.
722 *
723 * For errorcheck mutexes, it will return EDEADLK
724 * If the counter overflows, it will return EAGAIN
725 * Otherwise, it atomically increments the counter and returns 0
726 * after providing an acquire barrier.
727 *
728 * mtype is the current mutex type
729 * mvalue is the current mutex value (already loaded)
730 * mutex pointers to the mutex.
731 */
732static __inline__ __attribute__((always_inline)) int
733_recursive_increment(pthread_mutex_t* mutex, int mvalue, int mtype)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800734{
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100735 if (mtype == MUTEX_TYPE_BITS_ERRORCHECK) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100736 /* trying to re-lock a mutex we already acquired */
737 return EDEADLK;
738 }
739
740 /* Detect recursive lock overflow and return EAGAIN.
741 * This is safe because only the owner thread can modify the
David 'Digit' Turnerb57db752012-01-24 13:20:38 +0100742 * counter bits in the mutex value.
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100743 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100744 if (MUTEX_COUNTER_BITS_WILL_OVERFLOW(mvalue)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100745 return EAGAIN;
746 }
747
748 /* We own the mutex, but other threads are able to change
David 'Digit' Turnerb57db752012-01-24 13:20:38 +0100749 * the lower bits (e.g. promoting it to "contended"), so we
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100750 * need to use an atomic cmpxchg loop to update the counter.
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100751 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100752 for (;;) {
753 /* increment counter, overflow was already checked */
754 int newval = mvalue + MUTEX_COUNTER_BITS_ONE;
755 if (__likely(__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0)) {
756 /* mutex is still locked, not need for a memory barrier */
757 return 0;
758 }
759 /* the value was changed, this happens when another thread changes
760 * the lower state bits from 1 to 2 to indicate contention. This
761 * cannot change the counter, so simply reload and try again.
762 */
763 mvalue = mutex->value;
764 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800765}
766
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700767__LIBC_HIDDEN__
768int pthread_mutex_lock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800769{
Wink Savillea12c5442013-01-08 15:15:45 -0800770 int mvalue, mtype, tid, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -0800771
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700772 if (__unlikely(mutex == NULL))
773 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -0800774
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100775 mvalue = mutex->value;
776 mtype = (mvalue & MUTEX_TYPE_MASK);
777 shared = (mvalue & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800778
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700779 /* Handle normal case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100780 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) ) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100781 _normal_lock(mutex, shared);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -0800782 return 0;
783 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700784
785 /* Do we already own this recursive or error-check mutex ? */
786 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100787 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100788 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700789
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100790 /* Add in shared state to avoid extra 'or' operations below */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -0700791 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700792
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100793 /* First, if the mutex is unlocked, try to quickly acquire it.
794 * In the optimistic case where this works, set the state to 1 to
795 * indicate locked with no contention */
796 if (mvalue == mtype) {
797 int newval = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
798 if (__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0) {
799 ANDROID_MEMBAR_FULL();
800 return 0;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700801 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100802 /* argh, the value changed, reload before entering the loop */
803 mvalue = mutex->value;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700804 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100805
806 for (;;) {
807 int newval;
808
809 /* if the mutex is unlocked, its value should be 'mtype' and
810 * we try to acquire it by setting its owner and state atomically.
811 * NOTE: We put the state to 2 since we _know_ there is contention
812 * when we are in this loop. This ensures all waiters will be
813 * unlocked.
814 */
815 if (mvalue == mtype) {
816 newval = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_CONTENDED;
817 /* TODO: Change this to __bionic_cmpxchg_acquire when we
818 * implement it to get rid of the explicit memory
819 * barrier below.
820 */
821 if (__unlikely(__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0)) {
822 mvalue = mutex->value;
823 continue;
824 }
825 ANDROID_MEMBAR_FULL();
826 return 0;
827 }
828
829 /* the mutex is already locked by another thread, if its state is 1
830 * we will change it to 2 to indicate contention. */
831 if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(mvalue)) {
832 newval = MUTEX_STATE_BITS_FLIP_CONTENTION(mvalue); /* locked state 1 => state 2 */
833 if (__unlikely(__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0)) {
834 mvalue = mutex->value;
835 continue;
836 }
837 mvalue = newval;
838 }
839
840 /* wait until the mutex is unlocked */
841 __futex_wait_ex(&mutex->value, shared, mvalue, NULL);
842
843 mvalue = mutex->value;
844 }
845 /* NOTREACHED */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800846}
847
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700848int pthread_mutex_lock(pthread_mutex_t *mutex)
849{
850 int err = pthread_mutex_lock_impl(mutex);
851#ifdef PTHREAD_DEBUG
852 if (PTHREAD_DEBUG_ENABLED) {
853 if (!err) {
854 pthread_debug_mutex_lock_check(mutex);
855 }
856 }
857#endif
858 return err;
859}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800860
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700861__LIBC_HIDDEN__
862int pthread_mutex_unlock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800863{
Wink Savillea12c5442013-01-08 15:15:45 -0800864 int mvalue, mtype, tid, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800865
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700866 if (__unlikely(mutex == NULL))
867 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800868
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100869 mvalue = mutex->value;
870 mtype = (mvalue & MUTEX_TYPE_MASK);
871 shared = (mvalue & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800872
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700873 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100874 if (__likely(mtype == MUTEX_TYPE_BITS_NORMAL)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100875 _normal_unlock(mutex, shared);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800876 return 0;
877 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700878
879 /* Do we already own this recursive or error-check mutex ? */
880 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100881 if ( tid != MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700882 return EPERM;
883
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100884 /* If the counter is > 0, we can simply decrement it atomically.
885 * Since other threads can mutate the lower state bits (and only the
886 * lower state bits), use a cmpxchg to do it.
887 */
888 if (!MUTEX_COUNTER_BITS_IS_ZERO(mvalue)) {
889 for (;;) {
890 int newval = mvalue - MUTEX_COUNTER_BITS_ONE;
891 if (__likely(__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0)) {
892 /* success: we still own the mutex, so no memory barrier */
893 return 0;
894 }
895 /* the value changed, so reload and loop */
896 mvalue = mutex->value;
897 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700898 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100899
900 /* the counter is 0, so we're going to unlock the mutex by resetting
901 * its value to 'unlocked'. We need to perform a swap in order
902 * to read the current state, which will be 2 if there are waiters
903 * to awake.
904 *
905 * TODO: Change this to __bionic_swap_release when we implement it
906 * to get rid of the explicit memory barrier below.
907 */
908 ANDROID_MEMBAR_FULL(); /* RELEASE BARRIER */
909 mvalue = __bionic_swap(mtype | shared | MUTEX_STATE_BITS_UNLOCKED, &mutex->value);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700910
911 /* Wake one waiting thread, if any */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100912 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(mvalue)) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -0700913 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700914 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700915 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800916}
917
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700918int pthread_mutex_unlock(pthread_mutex_t *mutex)
919{
920#ifdef PTHREAD_DEBUG
921 if (PTHREAD_DEBUG_ENABLED) {
922 pthread_debug_mutex_unlock_check(mutex);
923 }
924#endif
925 return pthread_mutex_unlock_impl(mutex);
926}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800927
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700928__LIBC_HIDDEN__
929int pthread_mutex_trylock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800930{
Wink Savillea12c5442013-01-08 15:15:45 -0800931 int mvalue, mtype, tid, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700932
933 if (__unlikely(mutex == NULL))
934 return EINVAL;
935
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100936 mvalue = mutex->value;
937 mtype = (mvalue & MUTEX_TYPE_MASK);
938 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700939
940 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100941 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800942 {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100943 if (__bionic_cmpxchg(shared|MUTEX_STATE_BITS_UNLOCKED,
944 shared|MUTEX_STATE_BITS_LOCKED_UNCONTENDED,
945 &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700946 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800947 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700948 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700949
950 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -0800951 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700952
953 /* Do we already own this recursive or error-check mutex ? */
954 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100955 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100956 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700957
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100958 /* Same as pthread_mutex_lock, except that we don't want to wait, and
959 * the only operation that can succeed is a single cmpxchg to acquire the
960 * lock if it is released / not owned by anyone. No need for a complex loop.
961 */
962 mtype |= shared | MUTEX_STATE_BITS_UNLOCKED;
963 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700964
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100965 if (__likely(__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0)) {
966 ANDROID_MEMBAR_FULL();
967 return 0;
968 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700969
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100970 return EBUSY;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800971}
972
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700973int pthread_mutex_trylock(pthread_mutex_t *mutex)
974{
975 int err = pthread_mutex_trylock_impl(mutex);
976#ifdef PTHREAD_DEBUG
977 if (PTHREAD_DEBUG_ENABLED) {
978 if (!err) {
979 pthread_debug_mutex_lock_check(mutex);
980 }
981 }
982#endif
983 return err;
984}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800985
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700986/* initialize 'ts' with the difference between 'abstime' and the current time
987 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
988 */
989static int
990__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
991{
992 clock_gettime(clock, ts);
993 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
994 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
995 if (ts->tv_nsec < 0) {
996 ts->tv_sec--;
997 ts->tv_nsec += 1000000000;
998 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -0700999 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001000 return -1;
1001
1002 return 0;
1003}
1004
1005/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1006 * milliseconds.
1007 */
1008static void
1009__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1010{
1011 clock_gettime(clock, abstime);
1012 abstime->tv_sec += msecs/1000;
1013 abstime->tv_nsec += (msecs%1000)*1000000;
1014 if (abstime->tv_nsec >= 1000000000) {
1015 abstime->tv_sec++;
1016 abstime->tv_nsec -= 1000000000;
1017 }
1018}
1019
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001020__LIBC_HIDDEN__
1021int pthread_mutex_lock_timeout_np_impl(pthread_mutex_t *mutex, unsigned msecs)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001022{
1023 clockid_t clock = CLOCK_MONOTONIC;
1024 struct timespec abstime;
1025 struct timespec ts;
Wink Savillea12c5442013-01-08 15:15:45 -08001026 int mvalue, mtype, tid, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001027
1028 /* compute absolute expiration time */
1029 __timespec_to_relative_msec(&abstime, msecs, clock);
1030
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001031 if (__unlikely(mutex == NULL))
1032 return EINVAL;
1033
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001034 mvalue = mutex->value;
1035 mtype = (mvalue & MUTEX_TYPE_MASK);
1036 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001037
1038 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001039 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001040 {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001041 const int unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
1042 const int locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1043 const int locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1044
1045 /* fast path for uncontended lock. Note: MUTEX_TYPE_BITS_NORMAL is 0 */
1046 if (__bionic_cmpxchg(unlocked, locked_uncontended, &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001047 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001048 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001049 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001050
1051 /* loop while needed */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001052 while (__bionic_swap(locked_contended, &mutex->value) != unlocked) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001053 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1054 return EBUSY;
1055
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001056 __futex_wait_ex(&mutex->value, shared, locked_contended, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001057 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001058 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001059 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001060 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001061
1062 /* Do we already own this recursive or error-check mutex ? */
1063 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001064 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001065 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001066
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001067 /* the following implements the same loop than pthread_mutex_lock_impl
1068 * but adds checks to ensure that the operation never exceeds the
1069 * absolute expiration time.
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001070 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001071 mtype |= shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001072
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001073 /* first try a quick lock */
1074 if (mvalue == mtype) {
1075 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1076 if (__likely(__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0)) {
1077 ANDROID_MEMBAR_FULL();
1078 return 0;
1079 }
1080 mvalue = mutex->value;
1081 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001082
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001083 for (;;) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001084 struct timespec ts;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001085
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001086 /* if the value is 'unlocked', try to acquire it directly */
1087 /* NOTE: put state to 2 since we know there is contention */
1088 if (mvalue == mtype) /* unlocked */ {
1089 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1090 if (__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0) {
1091 ANDROID_MEMBAR_FULL();
1092 return 0;
1093 }
1094 /* the value changed before we could lock it. We need to check
1095 * the time to avoid livelocks, reload the value, then loop again. */
1096 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1097 return EBUSY;
1098
1099 mvalue = mutex->value;
1100 continue;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001101 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001102
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001103 /* The value is locked. If 'uncontended', try to switch its state
1104 * to 'contented' to ensure we get woken up later. */
1105 if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(mvalue)) {
1106 int newval = MUTEX_STATE_BITS_FLIP_CONTENTION(mvalue);
1107 if (__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0) {
1108 /* this failed because the value changed, reload it */
1109 mvalue = mutex->value;
1110 } else {
1111 /* this succeeded, update mvalue */
1112 mvalue = newval;
1113 }
1114 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001115
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001116 /* check time and update 'ts' */
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001117 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1118 return EBUSY;
1119
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001120 /* Only wait to be woken up if the state is '2', otherwise we'll
1121 * simply loop right now. This can happen when the second cmpxchg
1122 * in our loop failed because the mutex was unlocked by another
1123 * thread.
1124 */
1125 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(mvalue)) {
1126 if (__futex_wait_ex(&mutex->value, shared, mvalue, &ts) == ETIMEDOUT) {
1127 return EBUSY;
1128 }
1129 mvalue = mutex->value;
1130 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001131 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001132 /* NOTREACHED */
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001133}
1134
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001135int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1136{
1137 int err = pthread_mutex_lock_timeout_np_impl(mutex, msecs);
1138#ifdef PTHREAD_DEBUG
1139 if (PTHREAD_DEBUG_ENABLED) {
1140 if (!err) {
1141 pthread_debug_mutex_lock_check(mutex);
1142 }
1143 }
1144#endif
1145 return err;
1146}
1147
1148int pthread_mutex_destroy(pthread_mutex_t *mutex)
1149{
1150 int ret;
1151
1152 /* use trylock to ensure that the mutex value is
1153 * valid and is not already locked. */
1154 ret = pthread_mutex_trylock_impl(mutex);
1155 if (ret != 0)
1156 return ret;
1157
1158 mutex->value = 0xdead10cc;
1159 return 0;
1160}
1161
1162
1163
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001164int pthread_condattr_init(pthread_condattr_t *attr)
1165{
1166 if (attr == NULL)
1167 return EINVAL;
1168
1169 *attr = PTHREAD_PROCESS_PRIVATE;
1170 return 0;
1171}
1172
1173int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1174{
1175 if (attr == NULL || pshared == NULL)
1176 return EINVAL;
1177
1178 *pshared = *attr;
1179 return 0;
1180}
1181
1182int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1183{
1184 if (attr == NULL)
1185 return EINVAL;
1186
1187 if (pshared != PTHREAD_PROCESS_SHARED &&
1188 pshared != PTHREAD_PROCESS_PRIVATE)
1189 return EINVAL;
1190
1191 *attr = pshared;
1192 return 0;
1193}
1194
1195int pthread_condattr_destroy(pthread_condattr_t *attr)
1196{
1197 if (attr == NULL)
1198 return EINVAL;
1199
1200 *attr = 0xdeada11d;
1201 return 0;
1202}
1203
1204/* We use one bit in condition variable values as the 'shared' flag
1205 * The rest is a counter.
1206 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001207#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001208#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001209#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1210
1211#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001212
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001213/* XXX *technically* there is a race condition that could allow
1214 * XXX a signal to be missed. If thread A is preempted in _wait()
1215 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001216 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001217 * XXX before thread A is scheduled again and calls futex_wait(),
1218 * XXX then the signal will be lost.
1219 */
1220
1221int pthread_cond_init(pthread_cond_t *cond,
1222 const pthread_condattr_t *attr)
1223{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001224 if (cond == NULL)
1225 return EINVAL;
1226
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001227 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001228
1229 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001230 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001231
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001232 return 0;
1233}
1234
1235int pthread_cond_destroy(pthread_cond_t *cond)
1236{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001237 if (cond == NULL)
1238 return EINVAL;
1239
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001240 cond->value = 0xdeadc04d;
1241 return 0;
1242}
1243
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001244/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001245 * pthread_cond_signal to atomically decrement the counter
1246 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001247 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001248static int
1249__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001250{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001251 long flags;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001252
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001253 if (__unlikely(cond == NULL))
1254 return EINVAL;
1255
1256 flags = (cond->value & ~COND_COUNTER_MASK);
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001257 for (;;) {
1258 long oldval = cond->value;
1259 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1260 | flags;
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001261 if (__bionic_cmpxchg(oldval, newval, &cond->value) == 0)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001262 break;
1263 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001264
Andy McFaddene2ac8982010-09-02 13:34:53 -07001265 /*
1266 * Ensure that all memory accesses previously made by this thread are
1267 * visible to the woken thread(s). On the other side, the "wait"
1268 * code will issue any necessary barriers when locking the mutex.
1269 *
1270 * This may not strictly be necessary -- if the caller follows
1271 * recommended practice and holds the mutex before signaling the cond
1272 * var, the mutex ops will provide correct semantics. If they don't
1273 * hold the mutex, they're subject to race conditions anyway.
1274 */
1275 ANDROID_MEMBAR_FULL();
1276
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001277 __futex_wake_ex(&cond->value, COND_IS_SHARED(cond), counter);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001278 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001279}
1280
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001281int pthread_cond_broadcast(pthread_cond_t *cond)
1282{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001283 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001284}
1285
1286int pthread_cond_signal(pthread_cond_t *cond)
1287{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001288 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001289}
1290
1291int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1292{
1293 return pthread_cond_timedwait(cond, mutex, NULL);
1294}
1295
1296int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1297 pthread_mutex_t * mutex,
1298 const struct timespec *reltime)
1299{
1300 int status;
1301 int oldvalue = cond->value;
1302
1303 pthread_mutex_unlock(mutex);
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001304 status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond), oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001305 pthread_mutex_lock(mutex);
1306
1307 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1308 return 0;
1309}
1310
1311int __pthread_cond_timedwait(pthread_cond_t *cond,
1312 pthread_mutex_t * mutex,
1313 const struct timespec *abstime,
1314 clockid_t clock)
1315{
1316 struct timespec ts;
1317 struct timespec * tsp;
1318
1319 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001320 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001321 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001322 tsp = &ts;
1323 } else {
1324 tsp = NULL;
1325 }
1326
1327 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1328}
1329
1330int pthread_cond_timedwait(pthread_cond_t *cond,
1331 pthread_mutex_t * mutex,
1332 const struct timespec *abstime)
1333{
1334 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1335}
1336
1337
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001338/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001339int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1340 pthread_mutex_t * mutex,
1341 const struct timespec *abstime)
1342{
1343 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1344}
1345
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001346int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1347 pthread_mutex_t * mutex,
1348 const struct timespec *abstime)
1349{
1350 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1351}
1352
1353int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1354 pthread_mutex_t * mutex,
1355 const struct timespec *reltime)
1356{
1357 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1358}
1359
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001360int pthread_cond_timeout_np(pthread_cond_t *cond,
1361 pthread_mutex_t * mutex,
1362 unsigned msecs)
1363{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001364 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001365
1366 ts.tv_sec = msecs / 1000;
1367 ts.tv_nsec = (msecs % 1000) * 1000000;
1368
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001369 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001370}
1371
1372
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001373// man says this should be in <linux/unistd.h>, but it isn't
Jeff Brown10c8ce52011-11-18 15:17:07 -08001374extern int tgkill(int tgid, int tid, int sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001375
1376int pthread_kill(pthread_t tid, int sig)
1377{
1378 int ret;
1379 int old_errno = errno;
1380 pthread_internal_t * thread = (pthread_internal_t *)tid;
1381
Jeff Brown10c8ce52011-11-18 15:17:07 -08001382 ret = tgkill(getpid(), thread->kernel_id, sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001383 if (ret < 0) {
1384 ret = errno;
1385 errno = old_errno;
1386 }
1387
1388 return ret;
1389}
1390
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001391
1392int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
1393{
1394 const int CLOCK_IDTYPE_BITS = 3;
1395 pthread_internal_t* thread = (pthread_internal_t*)tid;
1396
1397 if (!thread)
1398 return ESRCH;
1399
1400 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
1401 return 0;
1402}
1403
1404
1405/* NOTE: this implementation doesn't support a init function that throws a C++ exception
1406 * or calls fork()
1407 */
1408int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
1409{
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001410 volatile pthread_once_t* ocptr = once_control;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001411
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001412 /* PTHREAD_ONCE_INIT is 0, we use the following bit flags
1413 *
1414 * bit 0 set -> initialization is under way
1415 * bit 1 set -> initialization is complete
1416 */
1417#define ONCE_INITIALIZING (1 << 0)
1418#define ONCE_COMPLETED (1 << 1)
1419
1420 /* First check if the once is already initialized. This will be the common
1421 * case and we want to make this as fast as possible. Note that this still
1422 * requires a load_acquire operation here to ensure that all the
1423 * stores performed by the initialization function are observable on
1424 * this CPU after we exit.
1425 */
1426 if (__likely((*ocptr & ONCE_COMPLETED) != 0)) {
1427 ANDROID_MEMBAR_FULL();
1428 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001429 }
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001430
1431 for (;;) {
1432 /* Try to atomically set the INITIALIZING flag.
1433 * This requires a cmpxchg loop, and we may need
Elliott Hughesbfeab1b2012-09-05 17:47:37 -07001434 * to exit prematurely if we detect that
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001435 * COMPLETED is now set.
1436 */
1437 int32_t oldval, newval;
1438
1439 do {
1440 oldval = *ocptr;
1441 if ((oldval & ONCE_COMPLETED) != 0)
1442 break;
1443
1444 newval = oldval | ONCE_INITIALIZING;
1445 } while (__bionic_cmpxchg(oldval, newval, ocptr) != 0);
1446
1447 if ((oldval & ONCE_COMPLETED) != 0) {
1448 /* We detected that COMPLETED was set while in our loop */
1449 ANDROID_MEMBAR_FULL();
1450 return 0;
1451 }
1452
1453 if ((oldval & ONCE_INITIALIZING) == 0) {
1454 /* We got there first, we can jump out of the loop to
1455 * handle the initialization */
1456 break;
1457 }
1458
1459 /* Another thread is running the initialization and hasn't completed
1460 * yet, so wait for it, then try again. */
1461 __futex_wait_ex(ocptr, 0, oldval, NULL);
1462 }
1463
1464 /* call the initialization function. */
1465 (*init_routine)();
1466
1467 /* Do a store_release indicating that initialization is complete */
1468 ANDROID_MEMBAR_FULL();
1469 *ocptr = ONCE_COMPLETED;
1470
1471 /* Wake up any waiters, if any */
1472 __futex_wake_ex(ocptr, 0, INT_MAX);
1473
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001474 return 0;
1475}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03001476
Glenn Kastend53cae02011-07-11 15:41:28 -07001477/* Return the kernel thread ID for a pthread.
1478 * This is only defined for implementations where pthread <-> kernel is 1:1, which this is.
1479 * Not the same as pthread_getthreadid_np, which is commonly defined to be opaque.
1480 * Internal, not an NDK API.
1481 */
1482
1483pid_t __pthread_gettid(pthread_t thid)
1484{
1485 pthread_internal_t* thread = (pthread_internal_t*)thid;
1486 return thread->kernel_id;
1487}
Jean-Baptiste Querufaca92f2012-03-26 15:25:19 -07001488
1489int __pthread_settid(pthread_t thid, pid_t tid)
1490{
1491 if (thid == 0)
1492 return EINVAL;
1493
1494 pthread_internal_t* thread = (pthread_internal_t*)thid;
1495 thread->kernel_id = tid;
1496
1497 return 0;
1498}