blob: d5f818744f9618d87810ff8e47fb2f5b77b188c2 [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"
Elliott Hughesad88a082012-10-24 18:37:21 -070039#include "bionic_ssp.h"
Pierre Peifferd0c884d2012-02-22 16:40:15 +010040#include "bionic_tls.h"
41#include "pthread_internal.h"
42#include "thread_private.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080043
Mathias Agopian7c0c3792011-09-05 23:54:55 -070044extern void pthread_debug_mutex_lock_check(pthread_mutex_t *mutex);
45extern void pthread_debug_mutex_unlock_check(pthread_mutex_t *mutex);
46
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080047extern void _exit_with_stack_teardown(void * stackBase, int stackSize, int retCode);
48extern void _exit_thread(int retCode);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080049
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -070050int __futex_wake_ex(volatile void *ftx, int pshared, int val)
51{
52 return __futex_syscall3(ftx, pshared ? FUTEX_WAKE : FUTEX_WAKE_PRIVATE, val);
53}
54
55int __futex_wait_ex(volatile void *ftx, int pshared, int val, const struct timespec *timeout)
56{
57 return __futex_syscall4(ftx, pshared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE, val, timeout);
58}
59
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -070060#define __likely(cond) __builtin_expect(!!(cond), 1)
61#define __unlikely(cond) __builtin_expect(!!(cond), 0)
62
Elliott Hughes44b53ad2013-02-11 20:18:47 +000063__LIBC_HIDDEN__ pthread_internal_t* gThreadList = NULL;
64__LIBC_HIDDEN__ pthread_mutex_t gThreadListLock = PTHREAD_MUTEX_INITIALIZER;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080065
Elliott Hughes4f251be2012-11-01 16:33:29 -070066static void _pthread_internal_remove_locked(pthread_internal_t* thread) {
67 if (thread->next != NULL) {
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070068 thread->next->prev = thread->prev;
Elliott Hughes4f251be2012-11-01 16:33:29 -070069 }
70 if (thread->prev != NULL) {
71 thread->prev->next = thread->next;
72 } else {
73 gThreadList = thread->next;
74 }
75
76 // The main thread is not heap-allocated. See __libc_init_tls for the declaration,
77 // and __libc_init_common for the point where it's added to the thread list.
78 if (thread->allocated_on_heap) {
79 free(thread);
80 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080081}
82
Elliott Hughes4f251be2012-11-01 16:33:29 -070083static void _pthread_internal_remove(pthread_internal_t* thread) {
84 pthread_mutex_lock(&gThreadListLock);
85 _pthread_internal_remove_locked(thread);
86 pthread_mutex_unlock(&gThreadListLock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080087}
88
Elliott Hughes4f251be2012-11-01 16:33:29 -070089__LIBC_ABI_PRIVATE__ void _pthread_internal_add(pthread_internal_t* thread) {
90 pthread_mutex_lock(&gThreadListLock);
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070091
Elliott Hughes4f251be2012-11-01 16:33:29 -070092 // We insert at the head.
93 thread->next = gThreadList;
94 thread->prev = NULL;
95 if (thread->next != NULL) {
96 thread->next->prev = thread;
97 }
98 gThreadList = thread;
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070099
Elliott Hughes4f251be2012-11-01 16:33:29 -0700100 pthread_mutex_unlock(&gThreadListLock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800101}
102
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +0400103__LIBC_ABI_PRIVATE__ pthread_internal_t*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800104__get_thread(void)
105{
106 void** tls = (void**)__get_tls();
107
108 return (pthread_internal_t*) tls[TLS_SLOT_THREAD_ID];
109}
110
111
112void*
113__get_stack_base(int *p_stack_size)
114{
115 pthread_internal_t* thread = __get_thread();
116
117 *p_stack_size = thread->attr.stack_size;
118 return thread->attr.stack_base;
119}
120
121
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800122/* CAVEAT: our implementation of pthread_cleanup_push/pop doesn't support C++ exceptions
123 * and thread cancelation
124 */
125
126void __pthread_cleanup_push( __pthread_cleanup_t* c,
127 __pthread_cleanup_func_t routine,
128 void* arg )
129{
130 pthread_internal_t* thread = __get_thread();
131
132 c->__cleanup_routine = routine;
133 c->__cleanup_arg = arg;
134 c->__cleanup_prev = thread->cleanup_stack;
135 thread->cleanup_stack = c;
136}
137
138void __pthread_cleanup_pop( __pthread_cleanup_t* c, int execute )
139{
140 pthread_internal_t* thread = __get_thread();
141
142 thread->cleanup_stack = c->__cleanup_prev;
143 if (execute)
144 c->__cleanup_routine(c->__cleanup_arg);
145}
146
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800147void pthread_exit(void * retval)
148{
149 pthread_internal_t* thread = __get_thread();
150 void* stack_base = thread->attr.stack_base;
151 int stack_size = thread->attr.stack_size;
152 int user_stack = (thread->attr.flags & PTHREAD_ATTR_FLAG_USER_STACK) != 0;
Jack Rene480fc82011-09-21 12:44:11 +0200153 sigset_t mask;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800154
155 // call the cleanup handlers first
156 while (thread->cleanup_stack) {
157 __pthread_cleanup_t* c = thread->cleanup_stack;
158 thread->cleanup_stack = c->__cleanup_prev;
159 c->__cleanup_routine(c->__cleanup_arg);
160 }
161
162 // call the TLS destructors, it is important to do that before removing this
163 // thread from the global list. this will ensure that if someone else deletes
164 // a TLS key, the corresponding value will be set to NULL in this thread's TLS
165 // space (see pthread_key_delete)
166 pthread_key_clean_all();
167
168 // if the thread is detached, destroy the pthread_internal_t
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400169 // otherwise, keep it in memory and signal any joiners.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800170 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
171 _pthread_internal_remove(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800172 } else {
Bjorn Andersson0753dc62012-05-03 17:12:39 -0700173 pthread_mutex_lock(&gThreadListLock);
174
175 /* make sure that the thread struct doesn't have stale pointers to a stack that
176 * will be unmapped after the exit call below.
177 */
178 if (!user_stack) {
179 thread->attr.stack_base = NULL;
180 thread->attr.stack_size = 0;
181 thread->tls = NULL;
182 }
183
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800184 /* the join_count field is used to store the number of threads waiting for
185 * the termination of this thread with pthread_join(),
186 *
187 * if it is positive we need to signal the waiters, and we do not touch
188 * the count (it will be decremented by the waiters, the last one will
189 * also remove/free the thread structure
190 *
191 * if it is zero, we set the count value to -1 to indicate that the
192 * thread is in 'zombie' state: it has stopped executing, and its stack
193 * is gone (as well as its TLS area). when another thread calls pthread_join()
194 * on it, it will immediately free the thread and return.
195 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800196 thread->return_value = retval;
197 if (thread->join_count > 0) {
198 pthread_cond_broadcast(&thread->join_cond);
199 } else {
200 thread->join_count = -1; /* zombie thread */
201 }
202 pthread_mutex_unlock(&gThreadListLock);
203 }
204
Jack Rene480fc82011-09-21 12:44:11 +0200205 sigfillset(&mask);
206 sigdelset(&mask, SIGSEGV);
207 (void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *)NULL);
208
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800209 // destroy the thread stack
210 if (user_stack)
211 _exit_thread((int)retval);
212 else
213 _exit_with_stack_teardown(stack_base, stack_size, (int)retval);
214}
215
216int pthread_join(pthread_t thid, void ** ret_val)
217{
218 pthread_internal_t* thread = (pthread_internal_t*)thid;
Elliott Hughes14f19592012-10-29 10:19:44 -0700219 if (thid == pthread_self()) {
220 return EDEADLK;
221 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800222
223 // check that the thread still exists and is not detached
224 pthread_mutex_lock(&gThreadListLock);
225
Elliott Hughes14f19592012-10-29 10:19:44 -0700226 for (thread = gThreadList; thread != NULL; thread = thread->next) {
227 if (thread == (pthread_internal_t*)thid) {
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200228 goto FoundIt;
Elliott Hughes14f19592012-10-29 10:19:44 -0700229 }
230 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800231
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200232 pthread_mutex_unlock(&gThreadListLock);
233 return ESRCH;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800234
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200235FoundIt:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800236 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
237 pthread_mutex_unlock(&gThreadListLock);
238 return EINVAL;
239 }
240
241 /* wait for thread death when needed
242 *
243 * if the 'join_count' is negative, this is a 'zombie' thread that
244 * is already dead and without stack/TLS
245 *
246 * otherwise, we need to increment 'join-count' and wait to be signaled
247 */
Elliott Hughes14f19592012-10-29 10:19:44 -0700248 int count = thread->join_count;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800249 if (count >= 0) {
250 thread->join_count += 1;
251 pthread_cond_wait( &thread->join_cond, &gThreadListLock );
252 count = --thread->join_count;
253 }
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400254 if (ret_val) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800255 *ret_val = thread->return_value;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400256 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800257
258 /* remove thread descriptor when we're the last joiner or when the
259 * thread was already a zombie.
260 */
261 if (count <= 0) {
262 _pthread_internal_remove_locked(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800263 }
264 pthread_mutex_unlock(&gThreadListLock);
265 return 0;
266}
267
268int pthread_detach( pthread_t thid )
269{
270 pthread_internal_t* thread;
271 int result = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800272
273 pthread_mutex_lock(&gThreadListLock);
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400274 for (thread = gThreadList; thread != NULL; thread = thread->next) {
275 if (thread == (pthread_internal_t*)thid) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800276 goto FoundIt;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400277 }
278 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800279
280 result = ESRCH;
281 goto Exit;
282
283FoundIt:
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400284 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
285 result = EINVAL; // Already detached.
286 goto Exit;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800287 }
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400288
289 if (thread->join_count > 0) {
290 result = 0; // Already being joined; silently do nothing, like glibc.
291 goto Exit;
292 }
293
294 thread->attr.flags |= PTHREAD_ATTR_FLAG_DETACHED;
295
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800296Exit:
297 pthread_mutex_unlock(&gThreadListLock);
298 return result;
299}
300
301pthread_t pthread_self(void)
302{
303 return (pthread_t)__get_thread();
304}
305
306int pthread_equal(pthread_t one, pthread_t two)
307{
308 return (one == two ? 1 : 0);
309}
310
311int pthread_getschedparam(pthread_t thid, int * policy,
312 struct sched_param * param)
313{
314 int old_errno = errno;
315
316 pthread_internal_t * thread = (pthread_internal_t *)thid;
317 int err = sched_getparam(thread->kernel_id, param);
318 if (!err) {
319 *policy = sched_getscheduler(thread->kernel_id);
320 } else {
321 err = errno;
322 errno = old_errno;
323 }
324 return err;
325}
326
327int pthread_setschedparam(pthread_t thid, int policy,
328 struct sched_param const * param)
329{
330 pthread_internal_t * thread = (pthread_internal_t *)thid;
331 int old_errno = errno;
332 int ret;
333
334 ret = sched_setscheduler(thread->kernel_id, policy, param);
335 if (ret < 0) {
336 ret = errno;
337 errno = old_errno;
338 }
339 return ret;
340}
341
342
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800343/* a mutex is implemented as a 32-bit integer holding the following fields
344 *
345 * bits: name description
346 * 31-16 tid owner thread's kernel id (recursive and errorcheck only)
347 * 15-14 type mutex type
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700348 * 13 shared process-shared flag
349 * 12-2 counter counter of recursive mutexes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800350 * 1-0 state lock state (0, 1 or 2)
351 */
352
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100353/* Convenience macro, creates a mask of 'bits' bits that starts from
354 * the 'shift'-th least significant bit in a 32-bit word.
355 *
356 * Examples: FIELD_MASK(0,4) -> 0xf
357 * FIELD_MASK(16,9) -> 0x1ff0000
358 */
359#define FIELD_MASK(shift,bits) (((1 << (bits))-1) << (shift))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800360
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100361/* This one is used to create a bit pattern from a given field value */
362#define FIELD_TO_BITS(val,shift,bits) (((val) & ((1 << (bits))-1)) << (shift))
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100363
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100364/* And this one does the opposite, i.e. extract a field's value from a bit pattern */
365#define FIELD_FROM_BITS(val,shift,bits) (((val) >> (shift)) & ((1 << (bits))-1))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800366
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100367/* Mutex state:
368 *
369 * 0 for unlocked
370 * 1 for locked, no waiters
371 * 2 for locked, maybe waiters
372 */
373#define MUTEX_STATE_SHIFT 0
374#define MUTEX_STATE_LEN 2
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800375
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100376#define MUTEX_STATE_MASK FIELD_MASK(MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
377#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
378#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
379
380#define MUTEX_STATE_UNLOCKED 0 /* must be 0 to match __PTHREAD_MUTEX_INIT_VALUE */
381#define MUTEX_STATE_LOCKED_UNCONTENDED 1 /* must be 1 due to atomic dec in unlock operation */
382#define MUTEX_STATE_LOCKED_CONTENDED 2 /* must be 1 + LOCKED_UNCONTENDED due to atomic dec */
383
384#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
385#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
386
387#define MUTEX_STATE_BITS_UNLOCKED MUTEX_STATE_TO_BITS(MUTEX_STATE_UNLOCKED)
388#define MUTEX_STATE_BITS_LOCKED_UNCONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_UNCONTENDED)
389#define MUTEX_STATE_BITS_LOCKED_CONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_CONTENDED)
390
391/* return true iff the mutex if locked with no waiters */
392#define MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_UNCONTENDED)
393
394/* return true iff the mutex if locked with maybe waiters */
395#define MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_CONTENDED)
396
397/* used to flip from LOCKED_UNCONTENDED to LOCKED_CONTENDED */
398#define MUTEX_STATE_BITS_FLIP_CONTENTION(v) ((v) ^ (MUTEX_STATE_BITS_LOCKED_CONTENDED ^ MUTEX_STATE_BITS_LOCKED_UNCONTENDED))
399
400/* Mutex counter:
401 *
402 * We need to check for overflow before incrementing, and we also need to
403 * detect when the counter is 0
404 */
405#define MUTEX_COUNTER_SHIFT 2
406#define MUTEX_COUNTER_LEN 11
407#define MUTEX_COUNTER_MASK FIELD_MASK(MUTEX_COUNTER_SHIFT, MUTEX_COUNTER_LEN)
408
409#define MUTEX_COUNTER_BITS_WILL_OVERFLOW(v) (((v) & MUTEX_COUNTER_MASK) == MUTEX_COUNTER_MASK)
410#define MUTEX_COUNTER_BITS_IS_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
411
412/* Used to increment the counter directly after overflow has been checked */
413#define MUTEX_COUNTER_BITS_ONE FIELD_TO_BITS(1,MUTEX_COUNTER_SHIFT,MUTEX_COUNTER_LEN)
414
415/* Returns true iff the counter is 0 */
416#define MUTEX_COUNTER_BITS_ARE_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
417
418/* Mutex shared bit flag
419 *
420 * This flag is set to indicate that the mutex is shared among processes.
421 * This changes the futex opcode we use for futex wait/wake operations
422 * (non-shared operations are much faster).
423 */
424#define MUTEX_SHARED_SHIFT 13
425#define MUTEX_SHARED_MASK FIELD_MASK(MUTEX_SHARED_SHIFT,1)
426
427/* Mutex type:
428 *
429 * We support normal, recursive and errorcheck mutexes.
430 *
431 * The constants defined here *cannot* be changed because they must match
432 * the C library ABI which defines the following initialization values in
433 * <pthread.h>:
434 *
435 * __PTHREAD_MUTEX_INIT_VALUE
436 * __PTHREAD_RECURSIVE_MUTEX_VALUE
437 * __PTHREAD_ERRORCHECK_MUTEX_INIT_VALUE
438 */
439#define MUTEX_TYPE_SHIFT 14
440#define MUTEX_TYPE_LEN 2
441#define MUTEX_TYPE_MASK FIELD_MASK(MUTEX_TYPE_SHIFT,MUTEX_TYPE_LEN)
442
443#define MUTEX_TYPE_NORMAL 0 /* Must be 0 to match __PTHREAD_MUTEX_INIT_VALUE */
444#define MUTEX_TYPE_RECURSIVE 1
445#define MUTEX_TYPE_ERRORCHECK 2
446
447#define MUTEX_TYPE_TO_BITS(t) FIELD_TO_BITS(t, MUTEX_TYPE_SHIFT, MUTEX_TYPE_LEN)
448
449#define MUTEX_TYPE_BITS_NORMAL MUTEX_TYPE_TO_BITS(MUTEX_TYPE_NORMAL)
450#define MUTEX_TYPE_BITS_RECURSIVE MUTEX_TYPE_TO_BITS(MUTEX_TYPE_RECURSIVE)
451#define MUTEX_TYPE_BITS_ERRORCHECK MUTEX_TYPE_TO_BITS(MUTEX_TYPE_ERRORCHECK)
452
453/* Mutex owner field:
454 *
455 * This is only used for recursive and errorcheck mutexes. It holds the
456 * kernel TID of the owning thread. Note that this works because the Linux
457 * kernel _only_ uses 16-bit values for thread ids.
458 *
459 * More specifically, it will wrap to 10000 when it reaches over 32768 for
460 * application processes. You can check this by running the following inside
461 * an adb shell session:
462 *
463 OLDPID=$$;
464 while true; do
465 NEWPID=$(sh -c 'echo $$')
466 if [ "$NEWPID" -gt 32768 ]; then
467 echo "AARGH: new PID $NEWPID is too high!"
468 exit 1
469 fi
470 if [ "$NEWPID" -lt "$OLDPID" ]; then
471 echo "****** Wrapping from PID $OLDPID to $NEWPID. *******"
472 else
473 echo -n "$NEWPID!"
474 fi
475 OLDPID=$NEWPID
476 done
477
478 * Note that you can run the same example on a desktop Linux system,
479 * the wrapping will also happen at 32768, but will go back to 300 instead.
480 */
481#define MUTEX_OWNER_SHIFT 16
482#define MUTEX_OWNER_LEN 16
483
484#define MUTEX_OWNER_FROM_BITS(v) FIELD_FROM_BITS(v,MUTEX_OWNER_SHIFT,MUTEX_OWNER_LEN)
485#define MUTEX_OWNER_TO_BITS(v) FIELD_TO_BITS(v,MUTEX_OWNER_SHIFT,MUTEX_OWNER_LEN)
486
487/* Convenience macros.
488 *
489 * These are used to form or modify the bit pattern of a given mutex value
490 */
491
492
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800493
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700494/* a mutex attribute holds the following fields
495 *
496 * bits: name description
497 * 0-3 type type of mutex
498 * 4 shared process-shared flag
499 */
500#define MUTEXATTR_TYPE_MASK 0x000f
501#define MUTEXATTR_SHARED_MASK 0x0010
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800502
503
504int pthread_mutexattr_init(pthread_mutexattr_t *attr)
505{
506 if (attr) {
507 *attr = PTHREAD_MUTEX_DEFAULT;
508 return 0;
509 } else {
510 return EINVAL;
511 }
512}
513
514int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
515{
516 if (attr) {
517 *attr = -1;
518 return 0;
519 } else {
520 return EINVAL;
521 }
522}
523
524int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
525{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700526 if (attr) {
527 int atype = (*attr & MUTEXATTR_TYPE_MASK);
528
529 if (atype >= PTHREAD_MUTEX_NORMAL &&
530 atype <= PTHREAD_MUTEX_ERRORCHECK) {
531 *type = atype;
532 return 0;
533 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800534 }
535 return EINVAL;
536}
537
538int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
539{
540 if (attr && type >= PTHREAD_MUTEX_NORMAL &&
541 type <= PTHREAD_MUTEX_ERRORCHECK ) {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700542 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800543 return 0;
544 }
545 return EINVAL;
546}
547
548/* process-shared mutexes are not supported at the moment */
549
550int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
551{
552 if (!attr)
553 return EINVAL;
554
Mathias Agopianb7681162009-07-13 22:00:33 -0700555 switch (pshared) {
556 case PTHREAD_PROCESS_PRIVATE:
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700557 *attr &= ~MUTEXATTR_SHARED_MASK;
558 return 0;
559
Mathias Agopianb7681162009-07-13 22:00:33 -0700560 case PTHREAD_PROCESS_SHARED:
561 /* our current implementation of pthread actually supports shared
562 * mutexes but won't cleanup if a process dies with the mutex held.
563 * Nevertheless, it's better than nothing. Shared mutexes are used
564 * by surfaceflinger and audioflinger.
565 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700566 *attr |= MUTEXATTR_SHARED_MASK;
Mathias Agopianb7681162009-07-13 22:00:33 -0700567 return 0;
568 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700569 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800570}
571
572int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
573{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700574 if (!attr || !pshared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800575 return EINVAL;
576
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700577 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED
578 : PTHREAD_PROCESS_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800579 return 0;
580}
581
582int pthread_mutex_init(pthread_mutex_t *mutex,
583 const pthread_mutexattr_t *attr)
584{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700585 int value = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800586
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700587 if (mutex == NULL)
588 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800589
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700590 if (__likely(attr == NULL)) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100591 mutex->value = MUTEX_TYPE_BITS_NORMAL;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700592 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800593 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700594
595 if ((*attr & MUTEXATTR_SHARED_MASK) != 0)
596 value |= MUTEX_SHARED_MASK;
597
598 switch (*attr & MUTEXATTR_TYPE_MASK) {
599 case PTHREAD_MUTEX_NORMAL:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100600 value |= MUTEX_TYPE_BITS_NORMAL;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700601 break;
602 case PTHREAD_MUTEX_RECURSIVE:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100603 value |= MUTEX_TYPE_BITS_RECURSIVE;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700604 break;
605 case PTHREAD_MUTEX_ERRORCHECK:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100606 value |= MUTEX_TYPE_BITS_ERRORCHECK;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700607 break;
608 default:
609 return EINVAL;
610 }
611
612 mutex->value = value;
613 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800614}
615
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800616
617/*
618 * Lock a non-recursive mutex.
619 *
620 * As noted above, there are three states:
621 * 0 (unlocked, no contention)
622 * 1 (locked, no contention)
623 * 2 (locked, contention)
624 *
625 * Non-recursive mutexes don't use the thread-id or counter fields, and the
626 * "type" value is zero, so the only bits that will be set are the ones in
627 * the lock state field.
628 */
629static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100630_normal_lock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800631{
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100632 /* convenience shortcuts */
633 const int unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
634 const int locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800635 /*
636 * The common case is an unlocked mutex, so we begin by trying to
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100637 * change the lock's state from 0 (UNLOCKED) to 1 (LOCKED).
638 * __bionic_cmpxchg() returns 0 if it made the swap successfully.
639 * If the result is nonzero, this lock is already held by another thread.
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800640 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100641 if (__bionic_cmpxchg(unlocked, locked_uncontended, &mutex->value) != 0) {
642 const int locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800643 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800644 * We want to go to sleep until the mutex is available, which
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100645 * requires promoting it to state 2 (CONTENDED). We need to
646 * swap in the new state value and then wait until somebody wakes us up.
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800647 *
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100648 * __bionic_swap() returns the previous value. We swap 2 in and
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800649 * see if we got zero back; if so, we have acquired the lock. If
650 * not, another thread still holds the lock and we wait again.
651 *
652 * The second argument to the __futex_wait() call is compared
653 * against the current value. If it doesn't match, __futex_wait()
654 * returns immediately (otherwise, it sleeps for a time specified
655 * by the third argument; 0 means sleep forever). This ensures
656 * that the mutex is in state 2 when we go to sleep on it, which
657 * guarantees a wake-up call.
658 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100659 while (__bionic_swap(locked_contended, &mutex->value) != unlocked)
660 __futex_wait_ex(&mutex->value, shared, locked_contended, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800661 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700662 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800663}
664
665/*
666 * Release a non-recursive mutex. The caller is responsible for determining
667 * that we are in fact the owner of this lock.
668 */
669static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100670_normal_unlock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800671{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700672 ANDROID_MEMBAR_FULL();
673
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800674 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700675 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100676 * to release the lock. __bionic_atomic_dec() returns the previous value;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800677 * if it wasn't 1 we have to do some additional work.
678 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100679 if (__bionic_atomic_dec(&mutex->value) != (shared|MUTEX_STATE_BITS_LOCKED_UNCONTENDED)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800680 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800681 * Start by releasing the lock. The decrement changed it from
682 * "contended lock" to "uncontended lock", which means we still
683 * hold it, and anybody who tries to sneak in will push it back
684 * to state 2.
685 *
686 * Once we set it to zero the lock is up for grabs. We follow
687 * this with a __futex_wake() to ensure that one of the waiting
688 * threads has a chance to grab it.
689 *
690 * This doesn't cause a race with the swap/wait pair in
691 * _normal_lock(), because the __futex_wait() call there will
692 * return immediately if the mutex value isn't 2.
693 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700694 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800695
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800696 /*
697 * Wake up one waiting thread. We don't know which thread will be
698 * woken or when it'll start executing -- futexes make no guarantees
699 * here. There may not even be a thread waiting.
700 *
701 * The newly-woken thread will replace the 0 we just set above
702 * with 2, which means that when it eventually releases the mutex
703 * it will also call FUTEX_WAKE. This results in one extra wake
704 * call whenever a lock is contended, but lets us avoid forgetting
705 * anyone without requiring us to track the number of sleepers.
706 *
707 * It's possible for another thread to sneak in and grab the lock
708 * between the zero assignment above and the wake call below. If
709 * the new thread is "slow" and holds the lock for a while, we'll
710 * wake up a sleeper, which will swap in a 2 and then go back to
711 * sleep since the lock is still held. If the new thread is "fast",
712 * running to completion before we call wake, the thread we
713 * eventually wake will find an unlocked mutex and will execute.
714 * Either way we have correct behavior and nobody is orphaned on
715 * the wait queue.
716 */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -0700717 __futex_wake_ex(&mutex->value, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800718 }
719}
720
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100721/* This common inlined function is used to increment the counter of an
722 * errorcheck or recursive mutex.
723 *
724 * For errorcheck mutexes, it will return EDEADLK
725 * If the counter overflows, it will return EAGAIN
726 * Otherwise, it atomically increments the counter and returns 0
727 * after providing an acquire barrier.
728 *
729 * mtype is the current mutex type
730 * mvalue is the current mutex value (already loaded)
731 * mutex pointers to the mutex.
732 */
733static __inline__ __attribute__((always_inline)) int
734_recursive_increment(pthread_mutex_t* mutex, int mvalue, int mtype)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800735{
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100736 if (mtype == MUTEX_TYPE_BITS_ERRORCHECK) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100737 /* trying to re-lock a mutex we already acquired */
738 return EDEADLK;
739 }
740
741 /* Detect recursive lock overflow and return EAGAIN.
742 * This is safe because only the owner thread can modify the
David 'Digit' Turnerb57db752012-01-24 13:20:38 +0100743 * counter bits in the mutex value.
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100744 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100745 if (MUTEX_COUNTER_BITS_WILL_OVERFLOW(mvalue)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100746 return EAGAIN;
747 }
748
749 /* We own the mutex, but other threads are able to change
David 'Digit' Turnerb57db752012-01-24 13:20:38 +0100750 * the lower bits (e.g. promoting it to "contended"), so we
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100751 * need to use an atomic cmpxchg loop to update the counter.
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100752 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100753 for (;;) {
754 /* increment counter, overflow was already checked */
755 int newval = mvalue + MUTEX_COUNTER_BITS_ONE;
756 if (__likely(__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0)) {
757 /* mutex is still locked, not need for a memory barrier */
758 return 0;
759 }
760 /* the value was changed, this happens when another thread changes
761 * the lower state bits from 1 to 2 to indicate contention. This
762 * cannot change the counter, so simply reload and try again.
763 */
764 mvalue = mutex->value;
765 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800766}
767
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700768__LIBC_HIDDEN__
769int pthread_mutex_lock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800770{
Wink Savillea12c5442013-01-08 15:15:45 -0800771 int mvalue, mtype, tid, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -0800772
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700773 if (__unlikely(mutex == NULL))
774 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -0800775
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100776 mvalue = mutex->value;
777 mtype = (mvalue & MUTEX_TYPE_MASK);
778 shared = (mvalue & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800779
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700780 /* Handle normal case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100781 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) ) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100782 _normal_lock(mutex, shared);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -0800783 return 0;
784 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700785
786 /* Do we already own this recursive or error-check mutex ? */
787 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100788 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100789 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700790
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100791 /* Add in shared state to avoid extra 'or' operations below */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -0700792 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700793
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100794 /* First, if the mutex is unlocked, try to quickly acquire it.
795 * In the optimistic case where this works, set the state to 1 to
796 * indicate locked with no contention */
797 if (mvalue == mtype) {
798 int newval = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
799 if (__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0) {
800 ANDROID_MEMBAR_FULL();
801 return 0;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700802 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100803 /* argh, the value changed, reload before entering the loop */
804 mvalue = mutex->value;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700805 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100806
807 for (;;) {
808 int newval;
809
810 /* if the mutex is unlocked, its value should be 'mtype' and
811 * we try to acquire it by setting its owner and state atomically.
812 * NOTE: We put the state to 2 since we _know_ there is contention
813 * when we are in this loop. This ensures all waiters will be
814 * unlocked.
815 */
816 if (mvalue == mtype) {
817 newval = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_CONTENDED;
818 /* TODO: Change this to __bionic_cmpxchg_acquire when we
819 * implement it to get rid of the explicit memory
820 * barrier below.
821 */
822 if (__unlikely(__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0)) {
823 mvalue = mutex->value;
824 continue;
825 }
826 ANDROID_MEMBAR_FULL();
827 return 0;
828 }
829
830 /* the mutex is already locked by another thread, if its state is 1
831 * we will change it to 2 to indicate contention. */
832 if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(mvalue)) {
833 newval = MUTEX_STATE_BITS_FLIP_CONTENTION(mvalue); /* locked state 1 => state 2 */
834 if (__unlikely(__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0)) {
835 mvalue = mutex->value;
836 continue;
837 }
838 mvalue = newval;
839 }
840
841 /* wait until the mutex is unlocked */
842 __futex_wait_ex(&mutex->value, shared, mvalue, NULL);
843
844 mvalue = mutex->value;
845 }
846 /* NOTREACHED */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800847}
848
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700849int pthread_mutex_lock(pthread_mutex_t *mutex)
850{
851 int err = pthread_mutex_lock_impl(mutex);
852#ifdef PTHREAD_DEBUG
853 if (PTHREAD_DEBUG_ENABLED) {
854 if (!err) {
855 pthread_debug_mutex_lock_check(mutex);
856 }
857 }
858#endif
859 return err;
860}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800861
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700862__LIBC_HIDDEN__
863int pthread_mutex_unlock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800864{
Wink Savillea12c5442013-01-08 15:15:45 -0800865 int mvalue, mtype, tid, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800866
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700867 if (__unlikely(mutex == NULL))
868 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800869
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100870 mvalue = mutex->value;
871 mtype = (mvalue & MUTEX_TYPE_MASK);
872 shared = (mvalue & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800873
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700874 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100875 if (__likely(mtype == MUTEX_TYPE_BITS_NORMAL)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100876 _normal_unlock(mutex, shared);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800877 return 0;
878 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700879
880 /* Do we already own this recursive or error-check mutex ? */
881 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100882 if ( tid != MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700883 return EPERM;
884
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100885 /* If the counter is > 0, we can simply decrement it atomically.
886 * Since other threads can mutate the lower state bits (and only the
887 * lower state bits), use a cmpxchg to do it.
888 */
889 if (!MUTEX_COUNTER_BITS_IS_ZERO(mvalue)) {
890 for (;;) {
891 int newval = mvalue - MUTEX_COUNTER_BITS_ONE;
892 if (__likely(__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0)) {
893 /* success: we still own the mutex, so no memory barrier */
894 return 0;
895 }
896 /* the value changed, so reload and loop */
897 mvalue = mutex->value;
898 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700899 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100900
901 /* the counter is 0, so we're going to unlock the mutex by resetting
902 * its value to 'unlocked'. We need to perform a swap in order
903 * to read the current state, which will be 2 if there are waiters
904 * to awake.
905 *
906 * TODO: Change this to __bionic_swap_release when we implement it
907 * to get rid of the explicit memory barrier below.
908 */
909 ANDROID_MEMBAR_FULL(); /* RELEASE BARRIER */
910 mvalue = __bionic_swap(mtype | shared | MUTEX_STATE_BITS_UNLOCKED, &mutex->value);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700911
912 /* Wake one waiting thread, if any */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100913 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(mvalue)) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -0700914 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700915 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700916 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800917}
918
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700919int pthread_mutex_unlock(pthread_mutex_t *mutex)
920{
921#ifdef PTHREAD_DEBUG
922 if (PTHREAD_DEBUG_ENABLED) {
923 pthread_debug_mutex_unlock_check(mutex);
924 }
925#endif
926 return pthread_mutex_unlock_impl(mutex);
927}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800928
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700929__LIBC_HIDDEN__
930int pthread_mutex_trylock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800931{
Wink Savillea12c5442013-01-08 15:15:45 -0800932 int mvalue, mtype, tid, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700933
934 if (__unlikely(mutex == NULL))
935 return EINVAL;
936
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100937 mvalue = mutex->value;
938 mtype = (mvalue & MUTEX_TYPE_MASK);
939 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700940
941 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100942 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800943 {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100944 if (__bionic_cmpxchg(shared|MUTEX_STATE_BITS_UNLOCKED,
945 shared|MUTEX_STATE_BITS_LOCKED_UNCONTENDED,
946 &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700947 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800948 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700949 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700950
951 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -0800952 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700953
954 /* Do we already own this recursive or error-check mutex ? */
955 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100956 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100957 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700958
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100959 /* Same as pthread_mutex_lock, except that we don't want to wait, and
960 * the only operation that can succeed is a single cmpxchg to acquire the
961 * lock if it is released / not owned by anyone. No need for a complex loop.
962 */
963 mtype |= shared | MUTEX_STATE_BITS_UNLOCKED;
964 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700965
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100966 if (__likely(__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0)) {
967 ANDROID_MEMBAR_FULL();
968 return 0;
969 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700970
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100971 return EBUSY;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800972}
973
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700974int pthread_mutex_trylock(pthread_mutex_t *mutex)
975{
976 int err = pthread_mutex_trylock_impl(mutex);
977#ifdef PTHREAD_DEBUG
978 if (PTHREAD_DEBUG_ENABLED) {
979 if (!err) {
980 pthread_debug_mutex_lock_check(mutex);
981 }
982 }
983#endif
984 return err;
985}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800986
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700987/* initialize 'ts' with the difference between 'abstime' and the current time
988 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
989 */
990static int
991__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
992{
993 clock_gettime(clock, ts);
994 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
995 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
996 if (ts->tv_nsec < 0) {
997 ts->tv_sec--;
998 ts->tv_nsec += 1000000000;
999 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001000 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001001 return -1;
1002
1003 return 0;
1004}
1005
1006/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1007 * milliseconds.
1008 */
1009static void
1010__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1011{
1012 clock_gettime(clock, abstime);
1013 abstime->tv_sec += msecs/1000;
1014 abstime->tv_nsec += (msecs%1000)*1000000;
1015 if (abstime->tv_nsec >= 1000000000) {
1016 abstime->tv_sec++;
1017 abstime->tv_nsec -= 1000000000;
1018 }
1019}
1020
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001021__LIBC_HIDDEN__
1022int pthread_mutex_lock_timeout_np_impl(pthread_mutex_t *mutex, unsigned msecs)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001023{
1024 clockid_t clock = CLOCK_MONOTONIC;
1025 struct timespec abstime;
1026 struct timespec ts;
Wink Savillea12c5442013-01-08 15:15:45 -08001027 int mvalue, mtype, tid, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001028
1029 /* compute absolute expiration time */
1030 __timespec_to_relative_msec(&abstime, msecs, clock);
1031
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001032 if (__unlikely(mutex == NULL))
1033 return EINVAL;
1034
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001035 mvalue = mutex->value;
1036 mtype = (mvalue & MUTEX_TYPE_MASK);
1037 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001038
1039 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001040 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001041 {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001042 const int unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
1043 const int locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1044 const int locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1045
1046 /* fast path for uncontended lock. Note: MUTEX_TYPE_BITS_NORMAL is 0 */
1047 if (__bionic_cmpxchg(unlocked, locked_uncontended, &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001048 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001049 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001050 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001051
1052 /* loop while needed */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001053 while (__bionic_swap(locked_contended, &mutex->value) != unlocked) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001054 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1055 return EBUSY;
1056
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001057 __futex_wait_ex(&mutex->value, shared, locked_contended, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001058 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001059 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001060 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001061 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001062
1063 /* Do we already own this recursive or error-check mutex ? */
1064 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001065 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001066 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001067
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001068 /* the following implements the same loop than pthread_mutex_lock_impl
1069 * but adds checks to ensure that the operation never exceeds the
1070 * absolute expiration time.
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001071 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001072 mtype |= shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001073
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001074 /* first try a quick lock */
1075 if (mvalue == mtype) {
1076 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1077 if (__likely(__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0)) {
1078 ANDROID_MEMBAR_FULL();
1079 return 0;
1080 }
1081 mvalue = mutex->value;
1082 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001083
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001084 for (;;) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001085 struct timespec ts;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001086
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001087 /* if the value is 'unlocked', try to acquire it directly */
1088 /* NOTE: put state to 2 since we know there is contention */
1089 if (mvalue == mtype) /* unlocked */ {
1090 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1091 if (__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0) {
1092 ANDROID_MEMBAR_FULL();
1093 return 0;
1094 }
1095 /* the value changed before we could lock it. We need to check
1096 * the time to avoid livelocks, reload the value, then loop again. */
1097 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1098 return EBUSY;
1099
1100 mvalue = mutex->value;
1101 continue;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001102 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001103
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001104 /* The value is locked. If 'uncontended', try to switch its state
1105 * to 'contented' to ensure we get woken up later. */
1106 if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(mvalue)) {
1107 int newval = MUTEX_STATE_BITS_FLIP_CONTENTION(mvalue);
1108 if (__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0) {
1109 /* this failed because the value changed, reload it */
1110 mvalue = mutex->value;
1111 } else {
1112 /* this succeeded, update mvalue */
1113 mvalue = newval;
1114 }
1115 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001116
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001117 /* check time and update 'ts' */
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001118 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1119 return EBUSY;
1120
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001121 /* Only wait to be woken up if the state is '2', otherwise we'll
1122 * simply loop right now. This can happen when the second cmpxchg
1123 * in our loop failed because the mutex was unlocked by another
1124 * thread.
1125 */
1126 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(mvalue)) {
1127 if (__futex_wait_ex(&mutex->value, shared, mvalue, &ts) == ETIMEDOUT) {
1128 return EBUSY;
1129 }
1130 mvalue = mutex->value;
1131 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001132 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001133 /* NOTREACHED */
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001134}
1135
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001136int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1137{
1138 int err = pthread_mutex_lock_timeout_np_impl(mutex, msecs);
1139#ifdef PTHREAD_DEBUG
1140 if (PTHREAD_DEBUG_ENABLED) {
1141 if (!err) {
1142 pthread_debug_mutex_lock_check(mutex);
1143 }
1144 }
1145#endif
1146 return err;
1147}
1148
1149int pthread_mutex_destroy(pthread_mutex_t *mutex)
1150{
1151 int ret;
1152
1153 /* use trylock to ensure that the mutex value is
1154 * valid and is not already locked. */
1155 ret = pthread_mutex_trylock_impl(mutex);
1156 if (ret != 0)
1157 return ret;
1158
1159 mutex->value = 0xdead10cc;
1160 return 0;
1161}
1162
1163
1164
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001165int pthread_condattr_init(pthread_condattr_t *attr)
1166{
1167 if (attr == NULL)
1168 return EINVAL;
1169
1170 *attr = PTHREAD_PROCESS_PRIVATE;
1171 return 0;
1172}
1173
1174int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1175{
1176 if (attr == NULL || pshared == NULL)
1177 return EINVAL;
1178
1179 *pshared = *attr;
1180 return 0;
1181}
1182
1183int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1184{
1185 if (attr == NULL)
1186 return EINVAL;
1187
1188 if (pshared != PTHREAD_PROCESS_SHARED &&
1189 pshared != PTHREAD_PROCESS_PRIVATE)
1190 return EINVAL;
1191
1192 *attr = pshared;
1193 return 0;
1194}
1195
1196int pthread_condattr_destroy(pthread_condattr_t *attr)
1197{
1198 if (attr == NULL)
1199 return EINVAL;
1200
1201 *attr = 0xdeada11d;
1202 return 0;
1203}
1204
1205/* We use one bit in condition variable values as the 'shared' flag
1206 * The rest is a counter.
1207 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001208#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001209#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001210#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1211
1212#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001213
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001214/* XXX *technically* there is a race condition that could allow
1215 * XXX a signal to be missed. If thread A is preempted in _wait()
1216 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001217 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001218 * XXX before thread A is scheduled again and calls futex_wait(),
1219 * XXX then the signal will be lost.
1220 */
1221
1222int pthread_cond_init(pthread_cond_t *cond,
1223 const pthread_condattr_t *attr)
1224{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001225 if (cond == NULL)
1226 return EINVAL;
1227
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001228 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001229
1230 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001231 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001232
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001233 return 0;
1234}
1235
1236int pthread_cond_destroy(pthread_cond_t *cond)
1237{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001238 if (cond == NULL)
1239 return EINVAL;
1240
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001241 cond->value = 0xdeadc04d;
1242 return 0;
1243}
1244
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001245/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001246 * pthread_cond_signal to atomically decrement the counter
1247 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001248 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001249static int
1250__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001251{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001252 long flags;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001253
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001254 if (__unlikely(cond == NULL))
1255 return EINVAL;
1256
1257 flags = (cond->value & ~COND_COUNTER_MASK);
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001258 for (;;) {
1259 long oldval = cond->value;
1260 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1261 | flags;
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001262 if (__bionic_cmpxchg(oldval, newval, &cond->value) == 0)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001263 break;
1264 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001265
Andy McFaddene2ac8982010-09-02 13:34:53 -07001266 /*
1267 * Ensure that all memory accesses previously made by this thread are
1268 * visible to the woken thread(s). On the other side, the "wait"
1269 * code will issue any necessary barriers when locking the mutex.
1270 *
1271 * This may not strictly be necessary -- if the caller follows
1272 * recommended practice and holds the mutex before signaling the cond
1273 * var, the mutex ops will provide correct semantics. If they don't
1274 * hold the mutex, they're subject to race conditions anyway.
1275 */
1276 ANDROID_MEMBAR_FULL();
1277
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001278 __futex_wake_ex(&cond->value, COND_IS_SHARED(cond), counter);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001279 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001280}
1281
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001282int pthread_cond_broadcast(pthread_cond_t *cond)
1283{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001284 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001285}
1286
1287int pthread_cond_signal(pthread_cond_t *cond)
1288{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001289 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001290}
1291
1292int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1293{
1294 return pthread_cond_timedwait(cond, mutex, NULL);
1295}
1296
1297int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1298 pthread_mutex_t * mutex,
1299 const struct timespec *reltime)
1300{
1301 int status;
1302 int oldvalue = cond->value;
1303
1304 pthread_mutex_unlock(mutex);
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001305 status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond), oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001306 pthread_mutex_lock(mutex);
1307
1308 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1309 return 0;
1310}
1311
1312int __pthread_cond_timedwait(pthread_cond_t *cond,
1313 pthread_mutex_t * mutex,
1314 const struct timespec *abstime,
1315 clockid_t clock)
1316{
1317 struct timespec ts;
1318 struct timespec * tsp;
1319
1320 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001321 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001322 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001323 tsp = &ts;
1324 } else {
1325 tsp = NULL;
1326 }
1327
1328 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1329}
1330
1331int pthread_cond_timedwait(pthread_cond_t *cond,
1332 pthread_mutex_t * mutex,
1333 const struct timespec *abstime)
1334{
1335 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1336}
1337
1338
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001339/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001340int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1341 pthread_mutex_t * mutex,
1342 const struct timespec *abstime)
1343{
1344 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1345}
1346
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001347int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1348 pthread_mutex_t * mutex,
1349 const struct timespec *abstime)
1350{
1351 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1352}
1353
1354int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1355 pthread_mutex_t * mutex,
1356 const struct timespec *reltime)
1357{
1358 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1359}
1360
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001361int pthread_cond_timeout_np(pthread_cond_t *cond,
1362 pthread_mutex_t * mutex,
1363 unsigned msecs)
1364{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001365 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001366
1367 ts.tv_sec = msecs / 1000;
1368 ts.tv_nsec = (msecs % 1000) * 1000000;
1369
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001370 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001371}
1372
1373
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001374// man says this should be in <linux/unistd.h>, but it isn't
Jeff Brown10c8ce52011-11-18 15:17:07 -08001375extern int tgkill(int tgid, int tid, int sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001376
1377int pthread_kill(pthread_t tid, int sig)
1378{
1379 int ret;
1380 int old_errno = errno;
1381 pthread_internal_t * thread = (pthread_internal_t *)tid;
1382
Jeff Brown10c8ce52011-11-18 15:17:07 -08001383 ret = tgkill(getpid(), thread->kernel_id, sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001384 if (ret < 0) {
1385 ret = errno;
1386 errno = old_errno;
1387 }
1388
1389 return ret;
1390}
1391
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001392
1393int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
1394{
1395 const int CLOCK_IDTYPE_BITS = 3;
1396 pthread_internal_t* thread = (pthread_internal_t*)tid;
1397
1398 if (!thread)
1399 return ESRCH;
1400
1401 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
1402 return 0;
1403}
1404
1405
1406/* NOTE: this implementation doesn't support a init function that throws a C++ exception
1407 * or calls fork()
1408 */
1409int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
1410{
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001411 volatile pthread_once_t* ocptr = once_control;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001412
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001413 /* PTHREAD_ONCE_INIT is 0, we use the following bit flags
1414 *
1415 * bit 0 set -> initialization is under way
1416 * bit 1 set -> initialization is complete
1417 */
1418#define ONCE_INITIALIZING (1 << 0)
1419#define ONCE_COMPLETED (1 << 1)
1420
1421 /* First check if the once is already initialized. This will be the common
1422 * case and we want to make this as fast as possible. Note that this still
1423 * requires a load_acquire operation here to ensure that all the
1424 * stores performed by the initialization function are observable on
1425 * this CPU after we exit.
1426 */
1427 if (__likely((*ocptr & ONCE_COMPLETED) != 0)) {
1428 ANDROID_MEMBAR_FULL();
1429 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001430 }
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001431
1432 for (;;) {
1433 /* Try to atomically set the INITIALIZING flag.
1434 * This requires a cmpxchg loop, and we may need
Elliott Hughesbfeab1b2012-09-05 17:47:37 -07001435 * to exit prematurely if we detect that
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001436 * COMPLETED is now set.
1437 */
1438 int32_t oldval, newval;
1439
1440 do {
1441 oldval = *ocptr;
1442 if ((oldval & ONCE_COMPLETED) != 0)
1443 break;
1444
1445 newval = oldval | ONCE_INITIALIZING;
1446 } while (__bionic_cmpxchg(oldval, newval, ocptr) != 0);
1447
1448 if ((oldval & ONCE_COMPLETED) != 0) {
1449 /* We detected that COMPLETED was set while in our loop */
1450 ANDROID_MEMBAR_FULL();
1451 return 0;
1452 }
1453
1454 if ((oldval & ONCE_INITIALIZING) == 0) {
1455 /* We got there first, we can jump out of the loop to
1456 * handle the initialization */
1457 break;
1458 }
1459
1460 /* Another thread is running the initialization and hasn't completed
1461 * yet, so wait for it, then try again. */
1462 __futex_wait_ex(ocptr, 0, oldval, NULL);
1463 }
1464
1465 /* call the initialization function. */
1466 (*init_routine)();
1467
1468 /* Do a store_release indicating that initialization is complete */
1469 ANDROID_MEMBAR_FULL();
1470 *ocptr = ONCE_COMPLETED;
1471
1472 /* Wake up any waiters, if any */
1473 __futex_wake_ex(ocptr, 0, INT_MAX);
1474
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001475 return 0;
1476}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03001477
Glenn Kastend53cae02011-07-11 15:41:28 -07001478/* Return the kernel thread ID for a pthread.
1479 * This is only defined for implementations where pthread <-> kernel is 1:1, which this is.
1480 * Not the same as pthread_getthreadid_np, which is commonly defined to be opaque.
1481 * Internal, not an NDK API.
1482 */
1483
1484pid_t __pthread_gettid(pthread_t thid)
1485{
1486 pthread_internal_t* thread = (pthread_internal_t*)thid;
1487 return thread->kernel_id;
1488}
Jean-Baptiste Querufaca92f2012-03-26 15:25:19 -07001489
1490int __pthread_settid(pthread_t thid, pid_t tid)
1491{
1492 if (thid == 0)
1493 return EINVAL;
1494
1495 pthread_internal_t* thread = (pthread_internal_t*)thid;
1496 thread->kernel_id = tid;
1497
1498 return 0;
1499}