blob: aa300e9e934c86d1cfacb80dde273ef455d5ca6c [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>
Elliott Hughes84114c82013-07-17 13:33:19 -070034#include <sys/mman.h>
Pierre Peifferd0c884d2012-02-22 16:40:15 +010035#include <unistd.h>
36
Pierre Peifferd0c884d2012-02-22 16:40:15 +010037#include "pthread_internal.h"
Elliott Hugheseb847bc2013-10-09 15:50:50 -070038
39#include "private/bionic_atomic_inline.h"
40#include "private/bionic_futex.h"
41#include "private/bionic_pthread.h"
42#include "private/bionic_tls.h"
43#include "private/thread_private.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080044
Mathias Agopian7c0c3792011-09-05 23:54:55 -070045extern void pthread_debug_mutex_lock_check(pthread_mutex_t *mutex);
46extern void pthread_debug_mutex_unlock_check(pthread_mutex_t *mutex);
47
Serban Constantinescu7f70c9b2013-10-13 22:07:26 +010048extern void _exit_with_stack_teardown(void * stackBase, size_t stackSize, int status);
Elliott Hughes6b53c232013-10-24 22:36:58 -070049extern void __exit(int status);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080050
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -070051int __futex_wake_ex(volatile void *ftx, int pshared, int val)
52{
53 return __futex_syscall3(ftx, pshared ? FUTEX_WAKE : FUTEX_WAKE_PRIVATE, val);
54}
55
56int __futex_wait_ex(volatile void *ftx, int pshared, int val, const struct timespec *timeout)
57{
58 return __futex_syscall4(ftx, pshared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE, val, timeout);
59}
60
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080061/* CAVEAT: our implementation of pthread_cleanup_push/pop doesn't support C++ exceptions
62 * and thread cancelation
63 */
64
65void __pthread_cleanup_push( __pthread_cleanup_t* c,
66 __pthread_cleanup_func_t routine,
67 void* arg )
68{
69 pthread_internal_t* thread = __get_thread();
70
71 c->__cleanup_routine = routine;
72 c->__cleanup_arg = arg;
73 c->__cleanup_prev = thread->cleanup_stack;
74 thread->cleanup_stack = c;
75}
76
77void __pthread_cleanup_pop( __pthread_cleanup_t* c, int execute )
78{
79 pthread_internal_t* thread = __get_thread();
80
81 thread->cleanup_stack = c->__cleanup_prev;
82 if (execute)
83 c->__cleanup_routine(c->__cleanup_arg);
84}
85
Elliott Hughes2b6e43e2013-10-29 16:11:06 -070086void pthread_exit(void* retval) {
87 pthread_internal_t* thread = __get_thread();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080088
Elliott Hughes2b6e43e2013-10-29 16:11:06 -070089 // Call the cleanup handlers first.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080090 while (thread->cleanup_stack) {
Elliott Hughes2b6e43e2013-10-29 16:11:06 -070091 __pthread_cleanup_t* c = thread->cleanup_stack;
92 thread->cleanup_stack = c->__cleanup_prev;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080093 c->__cleanup_routine(c->__cleanup_arg);
94 }
95
Elliott Hughes2b6e43e2013-10-29 16:11:06 -070096 // Call the TLS destructors. It is important to do that before removing this
97 // thread from the global list. This will ensure that if someone else deletes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080098 // a TLS key, the corresponding value will be set to NULL in this thread's TLS
Elliott Hughes2b6e43e2013-10-29 16:11:06 -070099 // space (see pthread_key_delete).
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800100 pthread_key_clean_all();
101
Elliott Hughes84114c82013-07-17 13:33:19 -0700102 if (thread->alternate_signal_stack != NULL) {
103 // Tell the kernel to stop using the alternate signal stack.
104 stack_t ss;
105 ss.ss_sp = NULL;
106 ss.ss_flags = SS_DISABLE;
107 sigaltstack(&ss, NULL);
108
109 // Free it.
110 munmap(thread->alternate_signal_stack, SIGSTKSZ);
111 thread->alternate_signal_stack = NULL;
112 }
113
Elliott Hughes2b6e43e2013-10-29 16:11:06 -0700114 // Keep track of what we need to know about the stack before we lose the pthread_internal_t.
115 void* stack_base = thread->attr.stack_base;
116 size_t stack_size = thread->attr.stack_size;
117 bool user_allocated_stack = ((thread->attr.flags & PTHREAD_ATTR_FLAG_USER_ALLOCATED_STACK) != 0);
118
119 // If the thread is detached, destroy the pthread_internal_t,
120 // otherwise keep it in memory and signal any joiners.
Elliott Hughes9d23e042013-02-15 19:21:51 -0800121 pthread_mutex_lock(&gThreadListLock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800122 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
Elliott Hughes9d23e042013-02-15 19:21:51 -0800123 _pthread_internal_remove_locked(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800124 } else {
Elliott Hughes2b6e43e2013-10-29 16:11:06 -0700125 // Make sure that the thread struct doesn't have stale pointers to a stack that
126 // will be unmapped after the exit call below.
127 if (!user_allocated_stack) {
Bjorn Andersson0753dc62012-05-03 17:12:39 -0700128 thread->attr.stack_base = NULL;
129 thread->attr.stack_size = 0;
130 thread->tls = NULL;
131 }
132
Elliott Hughes2b6e43e2013-10-29 16:11:06 -0700133 // Indicate that the thread has exited for joining threads.
msg5550f020d12013-06-06 14:59:28 -0400134 thread->attr.flags |= PTHREAD_ATTR_FLAG_ZOMBIE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800135 thread->return_value = retval;
msg5550f020d12013-06-06 14:59:28 -0400136
Elliott Hughes2b6e43e2013-10-29 16:11:06 -0700137 // Signal the joining thread if present.
msg5550f020d12013-06-06 14:59:28 -0400138 if (thread->attr.flags & PTHREAD_ATTR_FLAG_JOINED) {
139 pthread_cond_signal(&thread->join_cond);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800140 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800141 }
Elliott Hughes9d23e042013-02-15 19:21:51 -0800142 pthread_mutex_unlock(&gThreadListLock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800143
Elliott Hughes2b6e43e2013-10-29 16:11:06 -0700144 if (user_allocated_stack) {
Elliott Hughesc4c6e192013-10-08 14:48:05 -0700145 // Cleaning up this thread's stack is the creator's responsibility, not ours.
Elliott Hughes6b53c232013-10-24 22:36:58 -0700146 __exit(0);
Elliott Hughesa97cc5b2013-10-07 10:20:24 -0700147 } else {
148 // We need to munmap the stack we're running on before calling exit.
149 // That's not something we can do in C.
Elliott Hughes2b6e43e2013-10-29 16:11:06 -0700150
151 // We don't want to take a signal after we've unmapped the stack.
152 // That's one last thing we can handle in C.
153 sigset_t mask;
154 sigfillset(&mask);
155 sigprocmask(SIG_SETMASK, &mask, NULL);
156
Elliott Hughesc4c6e192013-10-08 14:48:05 -0700157 _exit_with_stack_teardown(stack_base, stack_size, 0);
Elliott Hughesa97cc5b2013-10-07 10:20:24 -0700158 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800159}
160
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800161/* a mutex is implemented as a 32-bit integer holding the following fields
162 *
163 * bits: name description
Elliott Hughes40eabe22013-02-14 18:59:37 -0800164 * 31-16 tid owner thread's tid (recursive and errorcheck only)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800165 * 15-14 type mutex type
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700166 * 13 shared process-shared flag
167 * 12-2 counter counter of recursive mutexes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800168 * 1-0 state lock state (0, 1 or 2)
169 */
170
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100171/* Convenience macro, creates a mask of 'bits' bits that starts from
172 * the 'shift'-th least significant bit in a 32-bit word.
173 *
174 * Examples: FIELD_MASK(0,4) -> 0xf
175 * FIELD_MASK(16,9) -> 0x1ff0000
176 */
177#define FIELD_MASK(shift,bits) (((1 << (bits))-1) << (shift))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800178
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100179/* This one is used to create a bit pattern from a given field value */
180#define FIELD_TO_BITS(val,shift,bits) (((val) & ((1 << (bits))-1)) << (shift))
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100181
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100182/* And this one does the opposite, i.e. extract a field's value from a bit pattern */
183#define FIELD_FROM_BITS(val,shift,bits) (((val) >> (shift)) & ((1 << (bits))-1))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800184
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100185/* Mutex state:
186 *
187 * 0 for unlocked
188 * 1 for locked, no waiters
189 * 2 for locked, maybe waiters
190 */
191#define MUTEX_STATE_SHIFT 0
192#define MUTEX_STATE_LEN 2
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800193
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100194#define MUTEX_STATE_MASK FIELD_MASK(MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
195#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
196#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
197
198#define MUTEX_STATE_UNLOCKED 0 /* must be 0 to match __PTHREAD_MUTEX_INIT_VALUE */
199#define MUTEX_STATE_LOCKED_UNCONTENDED 1 /* must be 1 due to atomic dec in unlock operation */
200#define MUTEX_STATE_LOCKED_CONTENDED 2 /* must be 1 + LOCKED_UNCONTENDED due to atomic dec */
201
202#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
203#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
204
205#define MUTEX_STATE_BITS_UNLOCKED MUTEX_STATE_TO_BITS(MUTEX_STATE_UNLOCKED)
206#define MUTEX_STATE_BITS_LOCKED_UNCONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_UNCONTENDED)
207#define MUTEX_STATE_BITS_LOCKED_CONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_CONTENDED)
208
209/* return true iff the mutex if locked with no waiters */
210#define MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_UNCONTENDED)
211
212/* return true iff the mutex if locked with maybe waiters */
213#define MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_CONTENDED)
214
215/* used to flip from LOCKED_UNCONTENDED to LOCKED_CONTENDED */
216#define MUTEX_STATE_BITS_FLIP_CONTENTION(v) ((v) ^ (MUTEX_STATE_BITS_LOCKED_CONTENDED ^ MUTEX_STATE_BITS_LOCKED_UNCONTENDED))
217
218/* Mutex counter:
219 *
220 * We need to check for overflow before incrementing, and we also need to
221 * detect when the counter is 0
222 */
223#define MUTEX_COUNTER_SHIFT 2
224#define MUTEX_COUNTER_LEN 11
225#define MUTEX_COUNTER_MASK FIELD_MASK(MUTEX_COUNTER_SHIFT, MUTEX_COUNTER_LEN)
226
227#define MUTEX_COUNTER_BITS_WILL_OVERFLOW(v) (((v) & MUTEX_COUNTER_MASK) == MUTEX_COUNTER_MASK)
228#define MUTEX_COUNTER_BITS_IS_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
229
230/* Used to increment the counter directly after overflow has been checked */
231#define MUTEX_COUNTER_BITS_ONE FIELD_TO_BITS(1,MUTEX_COUNTER_SHIFT,MUTEX_COUNTER_LEN)
232
233/* Returns true iff the counter is 0 */
234#define MUTEX_COUNTER_BITS_ARE_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
235
236/* Mutex shared bit flag
237 *
238 * This flag is set to indicate that the mutex is shared among processes.
239 * This changes the futex opcode we use for futex wait/wake operations
240 * (non-shared operations are much faster).
241 */
242#define MUTEX_SHARED_SHIFT 13
243#define MUTEX_SHARED_MASK FIELD_MASK(MUTEX_SHARED_SHIFT,1)
244
245/* Mutex type:
246 *
247 * We support normal, recursive and errorcheck mutexes.
248 *
249 * The constants defined here *cannot* be changed because they must match
250 * the C library ABI which defines the following initialization values in
251 * <pthread.h>:
252 *
253 * __PTHREAD_MUTEX_INIT_VALUE
254 * __PTHREAD_RECURSIVE_MUTEX_VALUE
255 * __PTHREAD_ERRORCHECK_MUTEX_INIT_VALUE
256 */
257#define MUTEX_TYPE_SHIFT 14
258#define MUTEX_TYPE_LEN 2
259#define MUTEX_TYPE_MASK FIELD_MASK(MUTEX_TYPE_SHIFT,MUTEX_TYPE_LEN)
260
261#define MUTEX_TYPE_NORMAL 0 /* Must be 0 to match __PTHREAD_MUTEX_INIT_VALUE */
262#define MUTEX_TYPE_RECURSIVE 1
263#define MUTEX_TYPE_ERRORCHECK 2
264
265#define MUTEX_TYPE_TO_BITS(t) FIELD_TO_BITS(t, MUTEX_TYPE_SHIFT, MUTEX_TYPE_LEN)
266
267#define MUTEX_TYPE_BITS_NORMAL MUTEX_TYPE_TO_BITS(MUTEX_TYPE_NORMAL)
268#define MUTEX_TYPE_BITS_RECURSIVE MUTEX_TYPE_TO_BITS(MUTEX_TYPE_RECURSIVE)
269#define MUTEX_TYPE_BITS_ERRORCHECK MUTEX_TYPE_TO_BITS(MUTEX_TYPE_ERRORCHECK)
270
271/* Mutex owner field:
272 *
273 * This is only used for recursive and errorcheck mutexes. It holds the
Elliott Hughes40eabe22013-02-14 18:59:37 -0800274 * tid of the owning thread. Note that this works because the Linux
275 * kernel _only_ uses 16-bit values for tids.
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100276 *
277 * More specifically, it will wrap to 10000 when it reaches over 32768 for
278 * application processes. You can check this by running the following inside
279 * an adb shell session:
280 *
281 OLDPID=$$;
282 while true; do
283 NEWPID=$(sh -c 'echo $$')
284 if [ "$NEWPID" -gt 32768 ]; then
285 echo "AARGH: new PID $NEWPID is too high!"
286 exit 1
287 fi
288 if [ "$NEWPID" -lt "$OLDPID" ]; then
289 echo "****** Wrapping from PID $OLDPID to $NEWPID. *******"
290 else
291 echo -n "$NEWPID!"
292 fi
293 OLDPID=$NEWPID
294 done
295
296 * Note that you can run the same example on a desktop Linux system,
297 * the wrapping will also happen at 32768, but will go back to 300 instead.
298 */
299#define MUTEX_OWNER_SHIFT 16
300#define MUTEX_OWNER_LEN 16
301
302#define MUTEX_OWNER_FROM_BITS(v) FIELD_FROM_BITS(v,MUTEX_OWNER_SHIFT,MUTEX_OWNER_LEN)
303#define MUTEX_OWNER_TO_BITS(v) FIELD_TO_BITS(v,MUTEX_OWNER_SHIFT,MUTEX_OWNER_LEN)
304
305/* Convenience macros.
306 *
307 * These are used to form or modify the bit pattern of a given mutex value
308 */
309
310
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800311
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700312/* a mutex attribute holds the following fields
313 *
314 * bits: name description
315 * 0-3 type type of mutex
316 * 4 shared process-shared flag
317 */
318#define MUTEXATTR_TYPE_MASK 0x000f
319#define MUTEXATTR_SHARED_MASK 0x0010
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800320
321
322int pthread_mutexattr_init(pthread_mutexattr_t *attr)
323{
324 if (attr) {
325 *attr = PTHREAD_MUTEX_DEFAULT;
326 return 0;
327 } else {
328 return EINVAL;
329 }
330}
331
332int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
333{
334 if (attr) {
335 *attr = -1;
336 return 0;
337 } else {
338 return EINVAL;
339 }
340}
341
342int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
343{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700344 if (attr) {
345 int atype = (*attr & MUTEXATTR_TYPE_MASK);
346
347 if (atype >= PTHREAD_MUTEX_NORMAL &&
348 atype <= PTHREAD_MUTEX_ERRORCHECK) {
349 *type = atype;
350 return 0;
351 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800352 }
353 return EINVAL;
354}
355
356int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
357{
358 if (attr && type >= PTHREAD_MUTEX_NORMAL &&
359 type <= PTHREAD_MUTEX_ERRORCHECK ) {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700360 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800361 return 0;
362 }
363 return EINVAL;
364}
365
366/* process-shared mutexes are not supported at the moment */
367
368int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
369{
370 if (!attr)
371 return EINVAL;
372
Mathias Agopianb7681162009-07-13 22:00:33 -0700373 switch (pshared) {
374 case PTHREAD_PROCESS_PRIVATE:
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700375 *attr &= ~MUTEXATTR_SHARED_MASK;
376 return 0;
377
Mathias Agopianb7681162009-07-13 22:00:33 -0700378 case PTHREAD_PROCESS_SHARED:
379 /* our current implementation of pthread actually supports shared
380 * mutexes but won't cleanup if a process dies with the mutex held.
381 * Nevertheless, it's better than nothing. Shared mutexes are used
382 * by surfaceflinger and audioflinger.
383 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700384 *attr |= MUTEXATTR_SHARED_MASK;
Mathias Agopianb7681162009-07-13 22:00:33 -0700385 return 0;
386 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700387 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800388}
389
390int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
391{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700392 if (!attr || !pshared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800393 return EINVAL;
394
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700395 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED
396 : PTHREAD_PROCESS_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800397 return 0;
398}
399
400int pthread_mutex_init(pthread_mutex_t *mutex,
401 const pthread_mutexattr_t *attr)
402{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700403 int value = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800404
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700405 if (mutex == NULL)
406 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800407
Elliott Hughesd4e753f2013-07-16 12:45:46 -0700408 if (__predict_true(attr == NULL)) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100409 mutex->value = MUTEX_TYPE_BITS_NORMAL;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700410 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800411 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700412
413 if ((*attr & MUTEXATTR_SHARED_MASK) != 0)
414 value |= MUTEX_SHARED_MASK;
415
416 switch (*attr & MUTEXATTR_TYPE_MASK) {
417 case PTHREAD_MUTEX_NORMAL:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100418 value |= MUTEX_TYPE_BITS_NORMAL;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700419 break;
420 case PTHREAD_MUTEX_RECURSIVE:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100421 value |= MUTEX_TYPE_BITS_RECURSIVE;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700422 break;
423 case PTHREAD_MUTEX_ERRORCHECK:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100424 value |= MUTEX_TYPE_BITS_ERRORCHECK;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700425 break;
426 default:
427 return EINVAL;
428 }
429
430 mutex->value = value;
431 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800432}
433
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800434
435/*
436 * Lock a non-recursive mutex.
437 *
438 * As noted above, there are three states:
439 * 0 (unlocked, no contention)
440 * 1 (locked, no contention)
441 * 2 (locked, contention)
442 *
443 * Non-recursive mutexes don't use the thread-id or counter fields, and the
444 * "type" value is zero, so the only bits that will be set are the ones in
445 * the lock state field.
446 */
447static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100448_normal_lock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800449{
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100450 /* convenience shortcuts */
451 const int unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
452 const int locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800453 /*
454 * The common case is an unlocked mutex, so we begin by trying to
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100455 * change the lock's state from 0 (UNLOCKED) to 1 (LOCKED).
456 * __bionic_cmpxchg() returns 0 if it made the swap successfully.
457 * If the result is nonzero, this lock is already held by another thread.
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800458 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100459 if (__bionic_cmpxchg(unlocked, locked_uncontended, &mutex->value) != 0) {
460 const int locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800461 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800462 * We want to go to sleep until the mutex is available, which
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100463 * requires promoting it to state 2 (CONTENDED). We need to
464 * swap in the new state value and then wait until somebody wakes us up.
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800465 *
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100466 * __bionic_swap() returns the previous value. We swap 2 in and
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800467 * see if we got zero back; if so, we have acquired the lock. If
468 * not, another thread still holds the lock and we wait again.
469 *
470 * The second argument to the __futex_wait() call is compared
471 * against the current value. If it doesn't match, __futex_wait()
472 * returns immediately (otherwise, it sleeps for a time specified
473 * by the third argument; 0 means sleep forever). This ensures
474 * that the mutex is in state 2 when we go to sleep on it, which
475 * guarantees a wake-up call.
476 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100477 while (__bionic_swap(locked_contended, &mutex->value) != unlocked)
478 __futex_wait_ex(&mutex->value, shared, locked_contended, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800479 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700480 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800481}
482
483/*
484 * Release a non-recursive mutex. The caller is responsible for determining
485 * that we are in fact the owner of this lock.
486 */
487static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100488_normal_unlock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800489{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700490 ANDROID_MEMBAR_FULL();
491
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800492 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700493 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100494 * to release the lock. __bionic_atomic_dec() returns the previous value;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800495 * if it wasn't 1 we have to do some additional work.
496 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100497 if (__bionic_atomic_dec(&mutex->value) != (shared|MUTEX_STATE_BITS_LOCKED_UNCONTENDED)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800498 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800499 * Start by releasing the lock. The decrement changed it from
500 * "contended lock" to "uncontended lock", which means we still
501 * hold it, and anybody who tries to sneak in will push it back
502 * to state 2.
503 *
504 * Once we set it to zero the lock is up for grabs. We follow
505 * this with a __futex_wake() to ensure that one of the waiting
506 * threads has a chance to grab it.
507 *
508 * This doesn't cause a race with the swap/wait pair in
509 * _normal_lock(), because the __futex_wait() call there will
510 * return immediately if the mutex value isn't 2.
511 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700512 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800513
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800514 /*
515 * Wake up one waiting thread. We don't know which thread will be
516 * woken or when it'll start executing -- futexes make no guarantees
517 * here. There may not even be a thread waiting.
518 *
519 * The newly-woken thread will replace the 0 we just set above
520 * with 2, which means that when it eventually releases the mutex
521 * it will also call FUTEX_WAKE. This results in one extra wake
522 * call whenever a lock is contended, but lets us avoid forgetting
523 * anyone without requiring us to track the number of sleepers.
524 *
525 * It's possible for another thread to sneak in and grab the lock
526 * between the zero assignment above and the wake call below. If
527 * the new thread is "slow" and holds the lock for a while, we'll
528 * wake up a sleeper, which will swap in a 2 and then go back to
529 * sleep since the lock is still held. If the new thread is "fast",
530 * running to completion before we call wake, the thread we
531 * eventually wake will find an unlocked mutex and will execute.
532 * Either way we have correct behavior and nobody is orphaned on
533 * the wait queue.
534 */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -0700535 __futex_wake_ex(&mutex->value, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800536 }
537}
538
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100539/* This common inlined function is used to increment the counter of an
540 * errorcheck or recursive mutex.
541 *
542 * For errorcheck mutexes, it will return EDEADLK
543 * If the counter overflows, it will return EAGAIN
544 * Otherwise, it atomically increments the counter and returns 0
545 * after providing an acquire barrier.
546 *
547 * mtype is the current mutex type
548 * mvalue is the current mutex value (already loaded)
549 * mutex pointers to the mutex.
550 */
551static __inline__ __attribute__((always_inline)) int
552_recursive_increment(pthread_mutex_t* mutex, int mvalue, int mtype)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800553{
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100554 if (mtype == MUTEX_TYPE_BITS_ERRORCHECK) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100555 /* trying to re-lock a mutex we already acquired */
556 return EDEADLK;
557 }
558
559 /* Detect recursive lock overflow and return EAGAIN.
560 * This is safe because only the owner thread can modify the
David 'Digit' Turnerb57db752012-01-24 13:20:38 +0100561 * counter bits in the mutex value.
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100562 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100563 if (MUTEX_COUNTER_BITS_WILL_OVERFLOW(mvalue)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100564 return EAGAIN;
565 }
566
567 /* We own the mutex, but other threads are able to change
David 'Digit' Turnerb57db752012-01-24 13:20:38 +0100568 * the lower bits (e.g. promoting it to "contended"), so we
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100569 * need to use an atomic cmpxchg loop to update the counter.
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100570 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100571 for (;;) {
572 /* increment counter, overflow was already checked */
573 int newval = mvalue + MUTEX_COUNTER_BITS_ONE;
Elliott Hughesd4e753f2013-07-16 12:45:46 -0700574 if (__predict_true(__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0)) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100575 /* mutex is still locked, not need for a memory barrier */
576 return 0;
577 }
578 /* the value was changed, this happens when another thread changes
579 * the lower state bits from 1 to 2 to indicate contention. This
580 * cannot change the counter, so simply reload and try again.
581 */
582 mvalue = mutex->value;
583 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800584}
585
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700586__LIBC_HIDDEN__
587int pthread_mutex_lock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800588{
Wink Savillea12c5442013-01-08 15:15:45 -0800589 int mvalue, mtype, tid, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -0800590
Elliott Hughesd4e753f2013-07-16 12:45:46 -0700591 if (__predict_false(mutex == NULL))
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700592 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -0800593
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100594 mvalue = mutex->value;
595 mtype = (mvalue & MUTEX_TYPE_MASK);
596 shared = (mvalue & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800597
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700598 /* Handle normal case first */
Elliott Hughesd4e753f2013-07-16 12:45:46 -0700599 if ( __predict_true(mtype == MUTEX_TYPE_BITS_NORMAL) ) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100600 _normal_lock(mutex, shared);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -0800601 return 0;
602 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700603
604 /* Do we already own this recursive or error-check mutex ? */
Elliott Hughes40eabe22013-02-14 18:59:37 -0800605 tid = __get_thread()->tid;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100606 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100607 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700608
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100609 /* Add in shared state to avoid extra 'or' operations below */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -0700610 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700611
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100612 /* First, if the mutex is unlocked, try to quickly acquire it.
613 * In the optimistic case where this works, set the state to 1 to
614 * indicate locked with no contention */
615 if (mvalue == mtype) {
616 int newval = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
617 if (__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0) {
618 ANDROID_MEMBAR_FULL();
619 return 0;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700620 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100621 /* argh, the value changed, reload before entering the loop */
622 mvalue = mutex->value;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700623 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100624
625 for (;;) {
626 int newval;
627
628 /* if the mutex is unlocked, its value should be 'mtype' and
629 * we try to acquire it by setting its owner and state atomically.
630 * NOTE: We put the state to 2 since we _know_ there is contention
631 * when we are in this loop. This ensures all waiters will be
632 * unlocked.
633 */
634 if (mvalue == mtype) {
635 newval = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_CONTENDED;
636 /* TODO: Change this to __bionic_cmpxchg_acquire when we
637 * implement it to get rid of the explicit memory
638 * barrier below.
639 */
Elliott Hughesd4e753f2013-07-16 12:45:46 -0700640 if (__predict_false(__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0)) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100641 mvalue = mutex->value;
642 continue;
643 }
644 ANDROID_MEMBAR_FULL();
645 return 0;
646 }
647
648 /* the mutex is already locked by another thread, if its state is 1
649 * we will change it to 2 to indicate contention. */
650 if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(mvalue)) {
651 newval = MUTEX_STATE_BITS_FLIP_CONTENTION(mvalue); /* locked state 1 => state 2 */
Elliott Hughesd4e753f2013-07-16 12:45:46 -0700652 if (__predict_false(__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0)) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100653 mvalue = mutex->value;
654 continue;
655 }
656 mvalue = newval;
657 }
658
659 /* wait until the mutex is unlocked */
660 __futex_wait_ex(&mutex->value, shared, mvalue, NULL);
661
662 mvalue = mutex->value;
663 }
664 /* NOTREACHED */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800665}
666
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700667int pthread_mutex_lock(pthread_mutex_t *mutex)
668{
669 int err = pthread_mutex_lock_impl(mutex);
670#ifdef PTHREAD_DEBUG
671 if (PTHREAD_DEBUG_ENABLED) {
672 if (!err) {
673 pthread_debug_mutex_lock_check(mutex);
674 }
675 }
676#endif
677 return err;
678}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800679
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700680__LIBC_HIDDEN__
681int pthread_mutex_unlock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800682{
Wink Savillea12c5442013-01-08 15:15:45 -0800683 int mvalue, mtype, tid, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800684
Elliott Hughesd4e753f2013-07-16 12:45:46 -0700685 if (__predict_false(mutex == NULL))
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700686 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800687
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100688 mvalue = mutex->value;
689 mtype = (mvalue & MUTEX_TYPE_MASK);
690 shared = (mvalue & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800691
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700692 /* Handle common case first */
Elliott Hughesd4e753f2013-07-16 12:45:46 -0700693 if (__predict_true(mtype == MUTEX_TYPE_BITS_NORMAL)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100694 _normal_unlock(mutex, shared);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800695 return 0;
696 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700697
698 /* Do we already own this recursive or error-check mutex ? */
Elliott Hughes40eabe22013-02-14 18:59:37 -0800699 tid = __get_thread()->tid;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100700 if ( tid != MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700701 return EPERM;
702
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100703 /* If the counter is > 0, we can simply decrement it atomically.
704 * Since other threads can mutate the lower state bits (and only the
705 * lower state bits), use a cmpxchg to do it.
706 */
707 if (!MUTEX_COUNTER_BITS_IS_ZERO(mvalue)) {
708 for (;;) {
709 int newval = mvalue - MUTEX_COUNTER_BITS_ONE;
Elliott Hughesd4e753f2013-07-16 12:45:46 -0700710 if (__predict_true(__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0)) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100711 /* success: we still own the mutex, so no memory barrier */
712 return 0;
713 }
714 /* the value changed, so reload and loop */
715 mvalue = mutex->value;
716 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700717 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100718
719 /* the counter is 0, so we're going to unlock the mutex by resetting
720 * its value to 'unlocked'. We need to perform a swap in order
721 * to read the current state, which will be 2 if there are waiters
722 * to awake.
723 *
724 * TODO: Change this to __bionic_swap_release when we implement it
725 * to get rid of the explicit memory barrier below.
726 */
727 ANDROID_MEMBAR_FULL(); /* RELEASE BARRIER */
728 mvalue = __bionic_swap(mtype | shared | MUTEX_STATE_BITS_UNLOCKED, &mutex->value);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700729
730 /* Wake one waiting thread, if any */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100731 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(mvalue)) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -0700732 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700733 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700734 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800735}
736
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700737int pthread_mutex_unlock(pthread_mutex_t *mutex)
738{
739#ifdef PTHREAD_DEBUG
740 if (PTHREAD_DEBUG_ENABLED) {
741 pthread_debug_mutex_unlock_check(mutex);
742 }
743#endif
744 return pthread_mutex_unlock_impl(mutex);
745}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800746
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700747__LIBC_HIDDEN__
748int pthread_mutex_trylock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800749{
Wink Savillea12c5442013-01-08 15:15:45 -0800750 int mvalue, mtype, tid, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700751
Elliott Hughesd4e753f2013-07-16 12:45:46 -0700752 if (__predict_false(mutex == NULL))
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700753 return EINVAL;
754
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100755 mvalue = mutex->value;
756 mtype = (mvalue & MUTEX_TYPE_MASK);
757 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700758
759 /* Handle common case first */
Elliott Hughesd4e753f2013-07-16 12:45:46 -0700760 if ( __predict_true(mtype == MUTEX_TYPE_BITS_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800761 {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100762 if (__bionic_cmpxchg(shared|MUTEX_STATE_BITS_UNLOCKED,
763 shared|MUTEX_STATE_BITS_LOCKED_UNCONTENDED,
764 &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700765 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800766 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700767 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700768
769 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -0800770 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700771
772 /* Do we already own this recursive or error-check mutex ? */
Elliott Hughes40eabe22013-02-14 18:59:37 -0800773 tid = __get_thread()->tid;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100774 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100775 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700776
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100777 /* Same as pthread_mutex_lock, except that we don't want to wait, and
778 * the only operation that can succeed is a single cmpxchg to acquire the
779 * lock if it is released / not owned by anyone. No need for a complex loop.
780 */
781 mtype |= shared | MUTEX_STATE_BITS_UNLOCKED;
782 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700783
Elliott Hughesd4e753f2013-07-16 12:45:46 -0700784 if (__predict_true(__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0)) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100785 ANDROID_MEMBAR_FULL();
786 return 0;
787 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700788
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100789 return EBUSY;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800790}
791
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700792int pthread_mutex_trylock(pthread_mutex_t *mutex)
793{
794 int err = pthread_mutex_trylock_impl(mutex);
795#ifdef PTHREAD_DEBUG
796 if (PTHREAD_DEBUG_ENABLED) {
797 if (!err) {
798 pthread_debug_mutex_lock_check(mutex);
799 }
800 }
801#endif
802 return err;
803}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800804
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700805/* initialize 'ts' with the difference between 'abstime' and the current time
806 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
807 */
808static int
809__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
810{
811 clock_gettime(clock, ts);
812 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
813 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
814 if (ts->tv_nsec < 0) {
815 ts->tv_sec--;
816 ts->tv_nsec += 1000000000;
817 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -0700818 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700819 return -1;
820
821 return 0;
822}
823
824/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
825 * milliseconds.
826 */
827static void
828__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
829{
830 clock_gettime(clock, abstime);
831 abstime->tv_sec += msecs/1000;
832 abstime->tv_nsec += (msecs%1000)*1000000;
833 if (abstime->tv_nsec >= 1000000000) {
834 abstime->tv_sec++;
835 abstime->tv_nsec -= 1000000000;
836 }
837}
838
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700839__LIBC_HIDDEN__
840int pthread_mutex_lock_timeout_np_impl(pthread_mutex_t *mutex, unsigned msecs)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700841{
842 clockid_t clock = CLOCK_MONOTONIC;
843 struct timespec abstime;
844 struct timespec ts;
Wink Savillea12c5442013-01-08 15:15:45 -0800845 int mvalue, mtype, tid, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700846
847 /* compute absolute expiration time */
848 __timespec_to_relative_msec(&abstime, msecs, clock);
849
Elliott Hughesd4e753f2013-07-16 12:45:46 -0700850 if (__predict_false(mutex == NULL))
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700851 return EINVAL;
852
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100853 mvalue = mutex->value;
854 mtype = (mvalue & MUTEX_TYPE_MASK);
855 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700856
857 /* Handle common case first */
Elliott Hughesd4e753f2013-07-16 12:45:46 -0700858 if ( __predict_true(mtype == MUTEX_TYPE_BITS_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -0800859 {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100860 const int unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
861 const int locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
862 const int locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
863
864 /* fast path for uncontended lock. Note: MUTEX_TYPE_BITS_NORMAL is 0 */
865 if (__bionic_cmpxchg(unlocked, locked_uncontended, &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700866 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800867 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700868 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700869
870 /* loop while needed */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100871 while (__bionic_swap(locked_contended, &mutex->value) != unlocked) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700872 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
873 return EBUSY;
874
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100875 __futex_wait_ex(&mutex->value, shared, locked_contended, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800876 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700877 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700878 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -0800879 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700880
881 /* Do we already own this recursive or error-check mutex ? */
Elliott Hughes40eabe22013-02-14 18:59:37 -0800882 tid = __get_thread()->tid;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100883 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100884 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700885
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100886 /* the following implements the same loop than pthread_mutex_lock_impl
887 * but adds checks to ensure that the operation never exceeds the
888 * absolute expiration time.
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700889 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100890 mtype |= shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700891
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100892 /* first try a quick lock */
893 if (mvalue == mtype) {
894 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
Elliott Hughesd4e753f2013-07-16 12:45:46 -0700895 if (__predict_true(__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0)) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100896 ANDROID_MEMBAR_FULL();
897 return 0;
898 }
899 mvalue = mutex->value;
900 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700901
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700902 for (;;) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100903 struct timespec ts;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700904
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100905 /* if the value is 'unlocked', try to acquire it directly */
906 /* NOTE: put state to 2 since we know there is contention */
907 if (mvalue == mtype) /* unlocked */ {
908 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_CONTENDED;
909 if (__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0) {
910 ANDROID_MEMBAR_FULL();
911 return 0;
912 }
913 /* the value changed before we could lock it. We need to check
914 * the time to avoid livelocks, reload the value, then loop again. */
915 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
916 return EBUSY;
917
918 mvalue = mutex->value;
919 continue;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700920 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700921
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100922 /* The value is locked. If 'uncontended', try to switch its state
923 * to 'contented' to ensure we get woken up later. */
924 if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(mvalue)) {
925 int newval = MUTEX_STATE_BITS_FLIP_CONTENTION(mvalue);
926 if (__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0) {
927 /* this failed because the value changed, reload it */
928 mvalue = mutex->value;
929 } else {
930 /* this succeeded, update mvalue */
931 mvalue = newval;
932 }
933 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700934
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100935 /* check time and update 'ts' */
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700936 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
937 return EBUSY;
938
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100939 /* Only wait to be woken up if the state is '2', otherwise we'll
940 * simply loop right now. This can happen when the second cmpxchg
941 * in our loop failed because the mutex was unlocked by another
942 * thread.
943 */
944 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(mvalue)) {
945 if (__futex_wait_ex(&mutex->value, shared, mvalue, &ts) == ETIMEDOUT) {
946 return EBUSY;
947 }
948 mvalue = mutex->value;
949 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700950 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100951 /* NOTREACHED */
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700952}
953
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700954int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
955{
956 int err = pthread_mutex_lock_timeout_np_impl(mutex, msecs);
957#ifdef PTHREAD_DEBUG
958 if (PTHREAD_DEBUG_ENABLED) {
959 if (!err) {
960 pthread_debug_mutex_lock_check(mutex);
961 }
962 }
963#endif
964 return err;
965}
966
967int pthread_mutex_destroy(pthread_mutex_t *mutex)
968{
969 int ret;
970
971 /* use trylock to ensure that the mutex value is
972 * valid and is not already locked. */
973 ret = pthread_mutex_trylock_impl(mutex);
974 if (ret != 0)
975 return ret;
976
977 mutex->value = 0xdead10cc;
978 return 0;
979}
980
981
982
David 'Digit' Turneree7b0772010-03-18 14:07:42 -0700983int pthread_condattr_init(pthread_condattr_t *attr)
984{
985 if (attr == NULL)
986 return EINVAL;
987
988 *attr = PTHREAD_PROCESS_PRIVATE;
989 return 0;
990}
991
992int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
993{
994 if (attr == NULL || pshared == NULL)
995 return EINVAL;
996
997 *pshared = *attr;
998 return 0;
999}
1000
1001int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1002{
1003 if (attr == NULL)
1004 return EINVAL;
1005
1006 if (pshared != PTHREAD_PROCESS_SHARED &&
1007 pshared != PTHREAD_PROCESS_PRIVATE)
1008 return EINVAL;
1009
1010 *attr = pshared;
1011 return 0;
1012}
1013
1014int pthread_condattr_destroy(pthread_condattr_t *attr)
1015{
1016 if (attr == NULL)
1017 return EINVAL;
1018
1019 *attr = 0xdeada11d;
1020 return 0;
1021}
1022
1023/* We use one bit in condition variable values as the 'shared' flag
1024 * The rest is a counter.
1025 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001026#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001027#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001028#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1029
1030#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001031
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001032/* XXX *technically* there is a race condition that could allow
1033 * XXX a signal to be missed. If thread A is preempted in _wait()
1034 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001035 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001036 * XXX before thread A is scheduled again and calls futex_wait(),
1037 * XXX then the signal will be lost.
1038 */
1039
1040int pthread_cond_init(pthread_cond_t *cond,
1041 const pthread_condattr_t *attr)
1042{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001043 if (cond == NULL)
1044 return EINVAL;
1045
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001046 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001047
1048 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001049 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001050
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001051 return 0;
1052}
1053
1054int pthread_cond_destroy(pthread_cond_t *cond)
1055{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001056 if (cond == NULL)
1057 return EINVAL;
1058
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001059 cond->value = 0xdeadc04d;
1060 return 0;
1061}
1062
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001063/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001064 * pthread_cond_signal to atomically decrement the counter
1065 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001066 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001067static int
1068__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001069{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001070 long flags;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001071
Elliott Hughesd4e753f2013-07-16 12:45:46 -07001072 if (__predict_false(cond == NULL))
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001073 return EINVAL;
1074
1075 flags = (cond->value & ~COND_COUNTER_MASK);
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001076 for (;;) {
1077 long oldval = cond->value;
1078 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1079 | flags;
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001080 if (__bionic_cmpxchg(oldval, newval, &cond->value) == 0)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001081 break;
1082 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001083
Andy McFaddene2ac8982010-09-02 13:34:53 -07001084 /*
1085 * Ensure that all memory accesses previously made by this thread are
1086 * visible to the woken thread(s). On the other side, the "wait"
1087 * code will issue any necessary barriers when locking the mutex.
1088 *
1089 * This may not strictly be necessary -- if the caller follows
1090 * recommended practice and holds the mutex before signaling the cond
1091 * var, the mutex ops will provide correct semantics. If they don't
1092 * hold the mutex, they're subject to race conditions anyway.
1093 */
1094 ANDROID_MEMBAR_FULL();
1095
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001096 __futex_wake_ex(&cond->value, COND_IS_SHARED(cond), counter);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001097 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001098}
1099
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001100int pthread_cond_broadcast(pthread_cond_t *cond)
1101{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001102 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001103}
1104
1105int pthread_cond_signal(pthread_cond_t *cond)
1106{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001107 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001108}
1109
1110int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1111{
1112 return pthread_cond_timedwait(cond, mutex, NULL);
1113}
1114
1115int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1116 pthread_mutex_t * mutex,
1117 const struct timespec *reltime)
1118{
1119 int status;
1120 int oldvalue = cond->value;
1121
1122 pthread_mutex_unlock(mutex);
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001123 status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond), oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001124 pthread_mutex_lock(mutex);
1125
1126 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1127 return 0;
1128}
1129
1130int __pthread_cond_timedwait(pthread_cond_t *cond,
1131 pthread_mutex_t * mutex,
1132 const struct timespec *abstime,
1133 clockid_t clock)
1134{
1135 struct timespec ts;
1136 struct timespec * tsp;
1137
1138 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001139 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001140 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001141 tsp = &ts;
1142 } else {
1143 tsp = NULL;
1144 }
1145
1146 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1147}
1148
1149int pthread_cond_timedwait(pthread_cond_t *cond,
1150 pthread_mutex_t * mutex,
1151 const struct timespec *abstime)
1152{
1153 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1154}
1155
1156
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001157/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001158int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1159 pthread_mutex_t * mutex,
1160 const struct timespec *abstime)
1161{
1162 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1163}
1164
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001165int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1166 pthread_mutex_t * mutex,
1167 const struct timespec *abstime)
1168{
1169 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1170}
1171
1172int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1173 pthread_mutex_t * mutex,
1174 const struct timespec *reltime)
1175{
1176 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1177}
1178
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001179int pthread_cond_timeout_np(pthread_cond_t *cond,
1180 pthread_mutex_t * mutex,
Elliott Hughes11952072013-10-24 15:15:14 -07001181 unsigned ms)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001182{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001183 struct timespec ts;
Elliott Hughes11952072013-10-24 15:15:14 -07001184 timespec_from_ms(ts, ms);
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001185 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001186}
1187
1188
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001189/* NOTE: this implementation doesn't support a init function that throws a C++ exception
1190 * or calls fork()
1191 */
Elliott Hughes9d23e042013-02-15 19:21:51 -08001192int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001193{
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001194 volatile pthread_once_t* ocptr = once_control;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001195
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001196 /* PTHREAD_ONCE_INIT is 0, we use the following bit flags
1197 *
1198 * bit 0 set -> initialization is under way
1199 * bit 1 set -> initialization is complete
1200 */
1201#define ONCE_INITIALIZING (1 << 0)
1202#define ONCE_COMPLETED (1 << 1)
1203
1204 /* First check if the once is already initialized. This will be the common
1205 * case and we want to make this as fast as possible. Note that this still
1206 * requires a load_acquire operation here to ensure that all the
1207 * stores performed by the initialization function are observable on
1208 * this CPU after we exit.
1209 */
Elliott Hughesd4e753f2013-07-16 12:45:46 -07001210 if (__predict_true((*ocptr & ONCE_COMPLETED) != 0)) {
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001211 ANDROID_MEMBAR_FULL();
1212 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001213 }
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001214
1215 for (;;) {
1216 /* Try to atomically set the INITIALIZING flag.
1217 * This requires a cmpxchg loop, and we may need
Elliott Hughesbfeab1b2012-09-05 17:47:37 -07001218 * to exit prematurely if we detect that
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001219 * COMPLETED is now set.
1220 */
1221 int32_t oldval, newval;
1222
1223 do {
1224 oldval = *ocptr;
1225 if ((oldval & ONCE_COMPLETED) != 0)
1226 break;
1227
1228 newval = oldval | ONCE_INITIALIZING;
1229 } while (__bionic_cmpxchg(oldval, newval, ocptr) != 0);
1230
1231 if ((oldval & ONCE_COMPLETED) != 0) {
1232 /* We detected that COMPLETED was set while in our loop */
1233 ANDROID_MEMBAR_FULL();
1234 return 0;
1235 }
1236
1237 if ((oldval & ONCE_INITIALIZING) == 0) {
1238 /* We got there first, we can jump out of the loop to
1239 * handle the initialization */
1240 break;
1241 }
1242
1243 /* Another thread is running the initialization and hasn't completed
1244 * yet, so wait for it, then try again. */
1245 __futex_wait_ex(ocptr, 0, oldval, NULL);
1246 }
1247
1248 /* call the initialization function. */
1249 (*init_routine)();
1250
1251 /* Do a store_release indicating that initialization is complete */
1252 ANDROID_MEMBAR_FULL();
1253 *ocptr = ONCE_COMPLETED;
1254
1255 /* Wake up any waiters, if any */
1256 __futex_wake_ex(ocptr, 0, INT_MAX);
1257
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001258 return 0;
1259}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03001260
Elliott Hughes40eabe22013-02-14 18:59:37 -08001261pid_t __pthread_gettid(pthread_t thid) {
1262 pthread_internal_t* thread = (pthread_internal_t*) thid;
1263 return thread->tid;
Glenn Kastend53cae02011-07-11 15:41:28 -07001264}
Jean-Baptiste Querufaca92f2012-03-26 15:25:19 -07001265
Elliott Hughes40eabe22013-02-14 18:59:37 -08001266int __pthread_settid(pthread_t thid, pid_t tid) {
1267 if (thid == 0) {
1268 return EINVAL;
1269 }
Jean-Baptiste Querufaca92f2012-03-26 15:25:19 -07001270
Elliott Hughes40eabe22013-02-14 18:59:37 -08001271 pthread_internal_t* thread = (pthread_internal_t*) thid;
1272 thread->tid = tid;
Jean-Baptiste Querufaca92f2012-03-26 15:25:19 -07001273
Elliott Hughes40eabe22013-02-14 18:59:37 -08001274 return 0;
Jean-Baptiste Querufaca92f2012-03-26 15:25:19 -07001275}