blob: bdf2b876626bc792b2237e745cdbac581b150a32 [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>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080034#include <sys/mman.h>
Pierre Peifferd0c884d2012-02-22 16:40:15 +010035#include <unistd.h>
36
37#include "bionic_atomic_inline.h"
38#include "bionic_futex.h"
39#include "bionic_pthread.h"
Elliott Hughesad88a082012-10-24 18:37:21 -070040#include "bionic_ssp.h"
Pierre Peifferd0c884d2012-02-22 16:40:15 +010041#include "bionic_tls.h"
Elliott Hughes1e980b62013-01-17 18:36:06 -080042#include "debug_format.h"
Pierre Peifferd0c884d2012-02-22 16:40:15 +010043#include "pthread_internal.h"
44#include "thread_private.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080045
Mathias Agopian7c0c3792011-09-05 23:54:55 -070046extern void pthread_debug_mutex_lock_check(pthread_mutex_t *mutex);
47extern void pthread_debug_mutex_unlock_check(pthread_mutex_t *mutex);
48
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080049extern int __pthread_clone(int (*fn)(void*), void *child_stack, int flags, void *arg);
50extern void _exit_with_stack_teardown(void * stackBase, int stackSize, int retCode);
51extern void _exit_thread(int retCode);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080052
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -070053int __futex_wake_ex(volatile void *ftx, int pshared, int val)
54{
55 return __futex_syscall3(ftx, pshared ? FUTEX_WAKE : FUTEX_WAKE_PRIVATE, val);
56}
57
58int __futex_wait_ex(volatile void *ftx, int pshared, int val, const struct timespec *timeout)
59{
60 return __futex_syscall4(ftx, pshared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE, val, timeout);
61}
62
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -070063#define __likely(cond) __builtin_expect(!!(cond), 1)
64#define __unlikely(cond) __builtin_expect(!!(cond), 0)
65
Bruce Beare8e551a62011-03-28 09:47:35 -070066#ifdef __i386__
67#define ATTRIBUTES __attribute__((noinline)) __attribute__((fastcall))
68#else
69#define ATTRIBUTES __attribute__((noinline))
70#endif
71
72void ATTRIBUTES _thread_created_hook(pid_t thread_id);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080073
Pierre Peifferd0c884d2012-02-22 16:40:15 +010074static const int kPthreadInitFailed = 1;
75
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080076static pthread_mutex_t mmap_lock = PTHREAD_MUTEX_INITIALIZER;
77
Elliott Hughes44b53ad2013-02-11 20:18:47 +000078__LIBC_HIDDEN__ pthread_internal_t* gThreadList = NULL;
79__LIBC_HIDDEN__ pthread_mutex_t gThreadListLock = PTHREAD_MUTEX_INITIALIZER;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080080static pthread_mutex_t gDebuggerNotificationLock = PTHREAD_MUTEX_INITIALIZER;
81
Elliott Hughes4f251be2012-11-01 16:33:29 -070082static void _pthread_internal_remove_locked(pthread_internal_t* thread) {
83 if (thread->next != NULL) {
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070084 thread->next->prev = thread->prev;
Elliott Hughes4f251be2012-11-01 16:33:29 -070085 }
86 if (thread->prev != NULL) {
87 thread->prev->next = thread->next;
88 } else {
89 gThreadList = thread->next;
90 }
91
92 // The main thread is not heap-allocated. See __libc_init_tls for the declaration,
93 // and __libc_init_common for the point where it's added to the thread list.
94 if (thread->allocated_on_heap) {
95 free(thread);
96 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080097}
98
Elliott Hughes4f251be2012-11-01 16:33:29 -070099static void _pthread_internal_remove(pthread_internal_t* thread) {
100 pthread_mutex_lock(&gThreadListLock);
101 _pthread_internal_remove_locked(thread);
102 pthread_mutex_unlock(&gThreadListLock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800103}
104
Elliott Hughes4f251be2012-11-01 16:33:29 -0700105__LIBC_ABI_PRIVATE__ void _pthread_internal_add(pthread_internal_t* thread) {
106 pthread_mutex_lock(&gThreadListLock);
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700107
Elliott Hughes4f251be2012-11-01 16:33:29 -0700108 // We insert at the head.
109 thread->next = gThreadList;
110 thread->prev = NULL;
111 if (thread->next != NULL) {
112 thread->next->prev = thread;
113 }
114 gThreadList = thread;
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700115
Elliott Hughes4f251be2012-11-01 16:33:29 -0700116 pthread_mutex_unlock(&gThreadListLock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800117}
118
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +0400119__LIBC_ABI_PRIVATE__ pthread_internal_t*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800120__get_thread(void)
121{
122 void** tls = (void**)__get_tls();
123
124 return (pthread_internal_t*) tls[TLS_SLOT_THREAD_ID];
125}
126
127
128void*
129__get_stack_base(int *p_stack_size)
130{
131 pthread_internal_t* thread = __get_thread();
132
133 *p_stack_size = thread->attr.stack_size;
134 return thread->attr.stack_base;
135}
136
137
Elliott Hughes5419b942012-10-16 15:54:46 -0700138void __init_tls(void** tls, void* thread) {
139 ((pthread_internal_t*) thread)->tls = tls;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800140
Elliott Hughes5419b942012-10-16 15:54:46 -0700141 // Zero-initialize all the slots.
142 for (size_t i = 0; i < BIONIC_TLS_SLOTS; ++i) {
143 tls[i] = NULL;
144 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800145
Elliott Hughesad88a082012-10-24 18:37:21 -0700146 // Slot 0 must point to itself. The x86 Linux kernel reads the TLS from %fs:0.
Elliott Hughesd3920b32013-02-07 18:39:34 -0800147 tls[TLS_SLOT_SELF] = tls;
Elliott Hughes5419b942012-10-16 15:54:46 -0700148 tls[TLS_SLOT_THREAD_ID] = thread;
Elliott Hughesd3920b32013-02-07 18:39:34 -0800149 // GCC looks in the TLS for the stack guard on x86, so copy it there from our global.
150 tls[TLS_SLOT_STACK_GUARD] = (void*) __stack_chk_guard;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800151
Elliott Hughes5419b942012-10-16 15:54:46 -0700152 __set_tls((void*) tls);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800153}
154
155
156/*
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100157 * This trampoline is called from the assembly _pthread_clone() function.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800158 */
159void __thread_entry(int (*func)(void*), void *arg, void **tls)
160{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800161 // Wait for our creating thread to release us. This lets it have time to
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100162 // notify gdb about this thread before we start doing anything.
Andy McFaddene2ac8982010-09-02 13:34:53 -0700163 //
164 // This also provides the memory barrier needed to ensure that all memory
165 // accesses previously made by the creating thread are visible to us.
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100166 pthread_mutex_t* start_mutex = (pthread_mutex_t*) &tls[TLS_SLOT_SELF];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800167 pthread_mutex_lock(start_mutex);
168 pthread_mutex_destroy(start_mutex);
169
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100170 pthread_internal_t* thread = (pthread_internal_t*) tls[TLS_SLOT_THREAD_ID];
171 __init_tls(tls, thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800172
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100173 if ((thread->internal_flags & kPthreadInitFailed) != 0) {
174 pthread_exit(NULL);
175 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800176
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100177 int result = func(arg);
178 pthread_exit((void*) result);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800179}
180
Dave Burke88f1ea82012-09-17 20:37:38 -0700181#include <private/logd.h>
182
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +0400183__LIBC_ABI_PRIVATE__
Xi Wangae8eb742012-10-27 02:02:01 -0400184int _init_thread(pthread_internal_t* thread, pid_t kernel_id, const pthread_attr_t* attr,
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700185 void* stack_base, bool add_to_thread_list)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800186{
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100187 int error = 0;
188
Xi Wangae8eb742012-10-27 02:02:01 -0400189 thread->attr = *attr;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800190 thread->attr.stack_base = stack_base;
Xi Wangae8eb742012-10-27 02:02:01 -0400191 thread->kernel_id = kernel_id;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800192
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100193 // Make a note of whether the user supplied this stack (so we know whether or not to free it).
194 if (attr->stack_base == stack_base) {
195 thread->attr.flags |= PTHREAD_ATTR_FLAG_USER_STACK;
196 }
197
198 // Set the scheduling policy/priority of the thread.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800199 if (thread->attr.sched_policy != SCHED_NORMAL) {
200 struct sched_param param;
201 param.sched_priority = thread->attr.sched_priority;
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100202 if (sched_setscheduler(kernel_id, thread->attr.sched_policy, &param) == -1) {
Xi Wangae8eb742012-10-27 02:02:01 -0400203 // For backwards compatibility reasons, we just warn about failures here.
204 // error = errno;
Dave Burke88f1ea82012-09-17 20:37:38 -0700205 const char* msg = "pthread_create sched_setscheduler call failed: %s\n";
Elliott Hughes1e980b62013-01-17 18:36:06 -0800206 __libc_format_log(ANDROID_LOG_WARN, "libc", msg, strerror(errno));
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100207 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800208 }
209
210 pthread_cond_init(&thread->join_cond, NULL);
211 thread->join_count = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800212 thread->cleanup_stack = NULL;
213
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700214 if (add_to_thread_list) {
215 _pthread_internal_add(thread);
216 }
217
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100218 return error;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800219}
220
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800221static void *mkstack(size_t size, size_t guard_size)
222{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800223 pthread_mutex_lock(&mmap_lock);
224
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100225 int prot = PROT_READ | PROT_WRITE;
226 int flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE;
Elliott Hughes9c3eca72012-05-08 13:26:28 -0700227 void* stack = mmap(NULL, size, prot, flags, -1, 0);
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100228 if (stack == MAP_FAILED) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800229 stack = NULL;
230 goto done;
231 }
232
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100233 if (mprotect(stack, guard_size, PROT_NONE) == -1) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800234 munmap(stack, size);
235 stack = NULL;
236 goto done;
237 }
238
239done:
240 pthread_mutex_unlock(&mmap_lock);
241 return stack;
242}
243
244/*
Andy McFaddene2ac8982010-09-02 13:34:53 -0700245 * Create a new thread. The thread's stack is laid out like so:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800246 *
247 * +---------------------------+
248 * | pthread_internal_t |
249 * +---------------------------+
250 * | |
251 * | TLS area |
252 * | |
253 * +---------------------------+
254 * | |
255 * . .
256 * . stack area .
257 * . .
258 * | |
259 * +---------------------------+
260 * | guard page |
261 * +---------------------------+
262 *
263 * note that TLS[0] must be a pointer to itself, this is required
264 * by the thread-local storage implementation of the x86 Linux
265 * kernel, where the TLS pointer is read by reading fs:[0]
266 */
267int pthread_create(pthread_t *thread_out, pthread_attr_t const * attr,
268 void *(*start_routine)(void *), void * arg)
269{
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100270 int old_errno = errno;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800271
272 /* this will inform the rest of the C library that at least one thread
273 * was created. this will enforce certain functions to acquire/release
274 * locks (e.g. atexit()) to protect shared global structures.
275 *
276 * this works because pthread_create() is not called by the C library
277 * initialization routine that sets up the main thread's data structures.
278 */
279 __isthreaded = 1;
280
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100281 pthread_internal_t* thread = calloc(sizeof(*thread), 1);
282 if (thread == NULL) {
Elliott Hughes3e898472013-02-12 16:40:24 +0000283 return EAGAIN;
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100284 }
Elliott Hughes4f251be2012-11-01 16:33:29 -0700285 thread->allocated_on_heap = true;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800286
287 if (attr == NULL) {
288 attr = &gDefaultPthreadAttr;
289 }
290
291 // make sure the stack is PAGE_SIZE aligned
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100292 size_t stack_size = (attr->stack_size + (PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
293 uint8_t* stack = attr->stack_base;
294 if (stack == NULL) {
295 stack = mkstack(stack_size, attr->guard_size);
296 if (stack == NULL) {
Elliott Hughes4f251be2012-11-01 16:33:29 -0700297 free(thread);
Elliott Hughes3e898472013-02-12 16:40:24 +0000298 return EAGAIN;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800299 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800300 }
301
302 // Make room for TLS
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100303 void** tls = (void**)(stack + stack_size - BIONIC_TLS_SLOTS*sizeof(void*));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800304
305 // Create a mutex for the thread in TLS_SLOT_SELF to wait on once it starts so we can keep
306 // it from doing anything until after we notify the debugger about it
Andy McFaddene2ac8982010-09-02 13:34:53 -0700307 //
308 // This also provides the memory barrier we need to ensure that all
309 // memory accesses previously performed by this thread are visible to
310 // the new thread.
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100311 pthread_mutex_t* start_mutex = (pthread_mutex_t*) &tls[TLS_SLOT_SELF];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800312 pthread_mutex_init(start_mutex, NULL);
313 pthread_mutex_lock(start_mutex);
314
315 tls[TLS_SLOT_THREAD_ID] = thread;
316
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100317 int flags = CLONE_FILES | CLONE_FS | CLONE_VM | CLONE_SIGHAND |
318 CLONE_THREAD | CLONE_SYSVSEM | CLONE_DETACHED;
319 int tid = __pthread_clone((int(*)(void*))start_routine, tls, flags, arg);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800320
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100321 if (tid < 0) {
322 int clone_errno = errno;
323 pthread_mutex_unlock(start_mutex);
324 if (stack != attr->stack_base) {
325 munmap(stack, stack_size);
326 }
Elliott Hughes4f251be2012-11-01 16:33:29 -0700327 free(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800328 errno = old_errno;
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100329 return clone_errno;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800330 }
331
Xi Wangae8eb742012-10-27 02:02:01 -0400332 int init_errno = _init_thread(thread, tid, attr, stack, true);
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100333 if (init_errno != 0) {
334 // Mark the thread detached and let its __thread_entry run to
335 // completion. (It'll just exit immediately, cleaning up its resources.)
336 thread->internal_flags |= kPthreadInitFailed;
337 thread->attr.flags |= PTHREAD_ATTR_FLAG_DETACHED;
338 pthread_mutex_unlock(start_mutex);
339 errno = old_errno;
340 return init_errno;
341 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800342
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100343 // Notify any debuggers about the new thread.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800344 pthread_mutex_lock(&gDebuggerNotificationLock);
345 _thread_created_hook(tid);
346 pthread_mutex_unlock(&gDebuggerNotificationLock);
347
Jurijs Oniscuks2932f042012-07-05 14:57:38 +0200348 // Publish the pthread_t and let the thread run.
349 *thread_out = (pthread_t) thread;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800350 pthread_mutex_unlock(start_mutex);
351
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800352 return 0;
353}
354
355
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800356/* CAVEAT: our implementation of pthread_cleanup_push/pop doesn't support C++ exceptions
357 * and thread cancelation
358 */
359
360void __pthread_cleanup_push( __pthread_cleanup_t* c,
361 __pthread_cleanup_func_t routine,
362 void* arg )
363{
364 pthread_internal_t* thread = __get_thread();
365
366 c->__cleanup_routine = routine;
367 c->__cleanup_arg = arg;
368 c->__cleanup_prev = thread->cleanup_stack;
369 thread->cleanup_stack = c;
370}
371
372void __pthread_cleanup_pop( __pthread_cleanup_t* c, int execute )
373{
374 pthread_internal_t* thread = __get_thread();
375
376 thread->cleanup_stack = c->__cleanup_prev;
377 if (execute)
378 c->__cleanup_routine(c->__cleanup_arg);
379}
380
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800381void pthread_exit(void * retval)
382{
383 pthread_internal_t* thread = __get_thread();
384 void* stack_base = thread->attr.stack_base;
385 int stack_size = thread->attr.stack_size;
386 int user_stack = (thread->attr.flags & PTHREAD_ATTR_FLAG_USER_STACK) != 0;
Jack Rene480fc82011-09-21 12:44:11 +0200387 sigset_t mask;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800388
389 // call the cleanup handlers first
390 while (thread->cleanup_stack) {
391 __pthread_cleanup_t* c = thread->cleanup_stack;
392 thread->cleanup_stack = c->__cleanup_prev;
393 c->__cleanup_routine(c->__cleanup_arg);
394 }
395
396 // call the TLS destructors, it is important to do that before removing this
397 // thread from the global list. this will ensure that if someone else deletes
398 // a TLS key, the corresponding value will be set to NULL in this thread's TLS
399 // space (see pthread_key_delete)
400 pthread_key_clean_all();
401
402 // if the thread is detached, destroy the pthread_internal_t
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400403 // otherwise, keep it in memory and signal any joiners.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800404 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
405 _pthread_internal_remove(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800406 } else {
Bjorn Andersson0753dc62012-05-03 17:12:39 -0700407 pthread_mutex_lock(&gThreadListLock);
408
409 /* make sure that the thread struct doesn't have stale pointers to a stack that
410 * will be unmapped after the exit call below.
411 */
412 if (!user_stack) {
413 thread->attr.stack_base = NULL;
414 thread->attr.stack_size = 0;
415 thread->tls = NULL;
416 }
417
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800418 /* the join_count field is used to store the number of threads waiting for
419 * the termination of this thread with pthread_join(),
420 *
421 * if it is positive we need to signal the waiters, and we do not touch
422 * the count (it will be decremented by the waiters, the last one will
423 * also remove/free the thread structure
424 *
425 * if it is zero, we set the count value to -1 to indicate that the
426 * thread is in 'zombie' state: it has stopped executing, and its stack
427 * is gone (as well as its TLS area). when another thread calls pthread_join()
428 * on it, it will immediately free the thread and return.
429 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800430 thread->return_value = retval;
431 if (thread->join_count > 0) {
432 pthread_cond_broadcast(&thread->join_cond);
433 } else {
434 thread->join_count = -1; /* zombie thread */
435 }
436 pthread_mutex_unlock(&gThreadListLock);
437 }
438
Jack Rene480fc82011-09-21 12:44:11 +0200439 sigfillset(&mask);
440 sigdelset(&mask, SIGSEGV);
441 (void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *)NULL);
442
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800443 // destroy the thread stack
444 if (user_stack)
445 _exit_thread((int)retval);
446 else
447 _exit_with_stack_teardown(stack_base, stack_size, (int)retval);
448}
449
450int pthread_join(pthread_t thid, void ** ret_val)
451{
452 pthread_internal_t* thread = (pthread_internal_t*)thid;
Elliott Hughes14f19592012-10-29 10:19:44 -0700453 if (thid == pthread_self()) {
454 return EDEADLK;
455 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800456
457 // check that the thread still exists and is not detached
458 pthread_mutex_lock(&gThreadListLock);
459
Elliott Hughes14f19592012-10-29 10:19:44 -0700460 for (thread = gThreadList; thread != NULL; thread = thread->next) {
461 if (thread == (pthread_internal_t*)thid) {
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200462 goto FoundIt;
Elliott Hughes14f19592012-10-29 10:19:44 -0700463 }
464 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800465
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200466 pthread_mutex_unlock(&gThreadListLock);
467 return ESRCH;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800468
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200469FoundIt:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800470 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
471 pthread_mutex_unlock(&gThreadListLock);
472 return EINVAL;
473 }
474
475 /* wait for thread death when needed
476 *
477 * if the 'join_count' is negative, this is a 'zombie' thread that
478 * is already dead and without stack/TLS
479 *
480 * otherwise, we need to increment 'join-count' and wait to be signaled
481 */
Elliott Hughes14f19592012-10-29 10:19:44 -0700482 int count = thread->join_count;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800483 if (count >= 0) {
484 thread->join_count += 1;
485 pthread_cond_wait( &thread->join_cond, &gThreadListLock );
486 count = --thread->join_count;
487 }
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400488 if (ret_val) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800489 *ret_val = thread->return_value;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400490 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800491
492 /* remove thread descriptor when we're the last joiner or when the
493 * thread was already a zombie.
494 */
495 if (count <= 0) {
496 _pthread_internal_remove_locked(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800497 }
498 pthread_mutex_unlock(&gThreadListLock);
499 return 0;
500}
501
502int pthread_detach( pthread_t thid )
503{
504 pthread_internal_t* thread;
505 int result = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800506
507 pthread_mutex_lock(&gThreadListLock);
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400508 for (thread = gThreadList; thread != NULL; thread = thread->next) {
509 if (thread == (pthread_internal_t*)thid) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800510 goto FoundIt;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400511 }
512 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800513
514 result = ESRCH;
515 goto Exit;
516
517FoundIt:
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400518 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
519 result = EINVAL; // Already detached.
520 goto Exit;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800521 }
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400522
523 if (thread->join_count > 0) {
524 result = 0; // Already being joined; silently do nothing, like glibc.
525 goto Exit;
526 }
527
528 thread->attr.flags |= PTHREAD_ATTR_FLAG_DETACHED;
529
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800530Exit:
531 pthread_mutex_unlock(&gThreadListLock);
532 return result;
533}
534
535pthread_t pthread_self(void)
536{
537 return (pthread_t)__get_thread();
538}
539
540int pthread_equal(pthread_t one, pthread_t two)
541{
542 return (one == two ? 1 : 0);
543}
544
545int pthread_getschedparam(pthread_t thid, int * policy,
546 struct sched_param * param)
547{
548 int old_errno = errno;
549
550 pthread_internal_t * thread = (pthread_internal_t *)thid;
551 int err = sched_getparam(thread->kernel_id, param);
552 if (!err) {
553 *policy = sched_getscheduler(thread->kernel_id);
554 } else {
555 err = errno;
556 errno = old_errno;
557 }
558 return err;
559}
560
561int pthread_setschedparam(pthread_t thid, int policy,
562 struct sched_param const * param)
563{
564 pthread_internal_t * thread = (pthread_internal_t *)thid;
565 int old_errno = errno;
566 int ret;
567
568 ret = sched_setscheduler(thread->kernel_id, policy, param);
569 if (ret < 0) {
570 ret = errno;
571 errno = old_errno;
572 }
573 return ret;
574}
575
576
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800577/* a mutex is implemented as a 32-bit integer holding the following fields
578 *
579 * bits: name description
580 * 31-16 tid owner thread's kernel id (recursive and errorcheck only)
581 * 15-14 type mutex type
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700582 * 13 shared process-shared flag
583 * 12-2 counter counter of recursive mutexes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800584 * 1-0 state lock state (0, 1 or 2)
585 */
586
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100587/* Convenience macro, creates a mask of 'bits' bits that starts from
588 * the 'shift'-th least significant bit in a 32-bit word.
589 *
590 * Examples: FIELD_MASK(0,4) -> 0xf
591 * FIELD_MASK(16,9) -> 0x1ff0000
592 */
593#define FIELD_MASK(shift,bits) (((1 << (bits))-1) << (shift))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800594
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100595/* This one is used to create a bit pattern from a given field value */
596#define FIELD_TO_BITS(val,shift,bits) (((val) & ((1 << (bits))-1)) << (shift))
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100597
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100598/* And this one does the opposite, i.e. extract a field's value from a bit pattern */
599#define FIELD_FROM_BITS(val,shift,bits) (((val) >> (shift)) & ((1 << (bits))-1))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800600
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100601/* Mutex state:
602 *
603 * 0 for unlocked
604 * 1 for locked, no waiters
605 * 2 for locked, maybe waiters
606 */
607#define MUTEX_STATE_SHIFT 0
608#define MUTEX_STATE_LEN 2
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800609
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100610#define MUTEX_STATE_MASK FIELD_MASK(MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
611#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
612#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
613
614#define MUTEX_STATE_UNLOCKED 0 /* must be 0 to match __PTHREAD_MUTEX_INIT_VALUE */
615#define MUTEX_STATE_LOCKED_UNCONTENDED 1 /* must be 1 due to atomic dec in unlock operation */
616#define MUTEX_STATE_LOCKED_CONTENDED 2 /* must be 1 + LOCKED_UNCONTENDED due to atomic dec */
617
618#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
619#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
620
621#define MUTEX_STATE_BITS_UNLOCKED MUTEX_STATE_TO_BITS(MUTEX_STATE_UNLOCKED)
622#define MUTEX_STATE_BITS_LOCKED_UNCONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_UNCONTENDED)
623#define MUTEX_STATE_BITS_LOCKED_CONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_CONTENDED)
624
625/* return true iff the mutex if locked with no waiters */
626#define MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_UNCONTENDED)
627
628/* return true iff the mutex if locked with maybe waiters */
629#define MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_CONTENDED)
630
631/* used to flip from LOCKED_UNCONTENDED to LOCKED_CONTENDED */
632#define MUTEX_STATE_BITS_FLIP_CONTENTION(v) ((v) ^ (MUTEX_STATE_BITS_LOCKED_CONTENDED ^ MUTEX_STATE_BITS_LOCKED_UNCONTENDED))
633
634/* Mutex counter:
635 *
636 * We need to check for overflow before incrementing, and we also need to
637 * detect when the counter is 0
638 */
639#define MUTEX_COUNTER_SHIFT 2
640#define MUTEX_COUNTER_LEN 11
641#define MUTEX_COUNTER_MASK FIELD_MASK(MUTEX_COUNTER_SHIFT, MUTEX_COUNTER_LEN)
642
643#define MUTEX_COUNTER_BITS_WILL_OVERFLOW(v) (((v) & MUTEX_COUNTER_MASK) == MUTEX_COUNTER_MASK)
644#define MUTEX_COUNTER_BITS_IS_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
645
646/* Used to increment the counter directly after overflow has been checked */
647#define MUTEX_COUNTER_BITS_ONE FIELD_TO_BITS(1,MUTEX_COUNTER_SHIFT,MUTEX_COUNTER_LEN)
648
649/* Returns true iff the counter is 0 */
650#define MUTEX_COUNTER_BITS_ARE_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
651
652/* Mutex shared bit flag
653 *
654 * This flag is set to indicate that the mutex is shared among processes.
655 * This changes the futex opcode we use for futex wait/wake operations
656 * (non-shared operations are much faster).
657 */
658#define MUTEX_SHARED_SHIFT 13
659#define MUTEX_SHARED_MASK FIELD_MASK(MUTEX_SHARED_SHIFT,1)
660
661/* Mutex type:
662 *
663 * We support normal, recursive and errorcheck mutexes.
664 *
665 * The constants defined here *cannot* be changed because they must match
666 * the C library ABI which defines the following initialization values in
667 * <pthread.h>:
668 *
669 * __PTHREAD_MUTEX_INIT_VALUE
670 * __PTHREAD_RECURSIVE_MUTEX_VALUE
671 * __PTHREAD_ERRORCHECK_MUTEX_INIT_VALUE
672 */
673#define MUTEX_TYPE_SHIFT 14
674#define MUTEX_TYPE_LEN 2
675#define MUTEX_TYPE_MASK FIELD_MASK(MUTEX_TYPE_SHIFT,MUTEX_TYPE_LEN)
676
677#define MUTEX_TYPE_NORMAL 0 /* Must be 0 to match __PTHREAD_MUTEX_INIT_VALUE */
678#define MUTEX_TYPE_RECURSIVE 1
679#define MUTEX_TYPE_ERRORCHECK 2
680
681#define MUTEX_TYPE_TO_BITS(t) FIELD_TO_BITS(t, MUTEX_TYPE_SHIFT, MUTEX_TYPE_LEN)
682
683#define MUTEX_TYPE_BITS_NORMAL MUTEX_TYPE_TO_BITS(MUTEX_TYPE_NORMAL)
684#define MUTEX_TYPE_BITS_RECURSIVE MUTEX_TYPE_TO_BITS(MUTEX_TYPE_RECURSIVE)
685#define MUTEX_TYPE_BITS_ERRORCHECK MUTEX_TYPE_TO_BITS(MUTEX_TYPE_ERRORCHECK)
686
687/* Mutex owner field:
688 *
689 * This is only used for recursive and errorcheck mutexes. It holds the
690 * kernel TID of the owning thread. Note that this works because the Linux
691 * kernel _only_ uses 16-bit values for thread ids.
692 *
693 * More specifically, it will wrap to 10000 when it reaches over 32768 for
694 * application processes. You can check this by running the following inside
695 * an adb shell session:
696 *
697 OLDPID=$$;
698 while true; do
699 NEWPID=$(sh -c 'echo $$')
700 if [ "$NEWPID" -gt 32768 ]; then
701 echo "AARGH: new PID $NEWPID is too high!"
702 exit 1
703 fi
704 if [ "$NEWPID" -lt "$OLDPID" ]; then
705 echo "****** Wrapping from PID $OLDPID to $NEWPID. *******"
706 else
707 echo -n "$NEWPID!"
708 fi
709 OLDPID=$NEWPID
710 done
711
712 * Note that you can run the same example on a desktop Linux system,
713 * the wrapping will also happen at 32768, but will go back to 300 instead.
714 */
715#define MUTEX_OWNER_SHIFT 16
716#define MUTEX_OWNER_LEN 16
717
718#define MUTEX_OWNER_FROM_BITS(v) FIELD_FROM_BITS(v,MUTEX_OWNER_SHIFT,MUTEX_OWNER_LEN)
719#define MUTEX_OWNER_TO_BITS(v) FIELD_TO_BITS(v,MUTEX_OWNER_SHIFT,MUTEX_OWNER_LEN)
720
721/* Convenience macros.
722 *
723 * These are used to form or modify the bit pattern of a given mutex value
724 */
725
726
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800727
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700728/* a mutex attribute holds the following fields
729 *
730 * bits: name description
731 * 0-3 type type of mutex
732 * 4 shared process-shared flag
733 */
734#define MUTEXATTR_TYPE_MASK 0x000f
735#define MUTEXATTR_SHARED_MASK 0x0010
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800736
737
738int pthread_mutexattr_init(pthread_mutexattr_t *attr)
739{
740 if (attr) {
741 *attr = PTHREAD_MUTEX_DEFAULT;
742 return 0;
743 } else {
744 return EINVAL;
745 }
746}
747
748int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
749{
750 if (attr) {
751 *attr = -1;
752 return 0;
753 } else {
754 return EINVAL;
755 }
756}
757
758int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
759{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700760 if (attr) {
761 int atype = (*attr & MUTEXATTR_TYPE_MASK);
762
763 if (atype >= PTHREAD_MUTEX_NORMAL &&
764 atype <= PTHREAD_MUTEX_ERRORCHECK) {
765 *type = atype;
766 return 0;
767 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800768 }
769 return EINVAL;
770}
771
772int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
773{
774 if (attr && type >= PTHREAD_MUTEX_NORMAL &&
775 type <= PTHREAD_MUTEX_ERRORCHECK ) {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700776 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800777 return 0;
778 }
779 return EINVAL;
780}
781
782/* process-shared mutexes are not supported at the moment */
783
784int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
785{
786 if (!attr)
787 return EINVAL;
788
Mathias Agopianb7681162009-07-13 22:00:33 -0700789 switch (pshared) {
790 case PTHREAD_PROCESS_PRIVATE:
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700791 *attr &= ~MUTEXATTR_SHARED_MASK;
792 return 0;
793
Mathias Agopianb7681162009-07-13 22:00:33 -0700794 case PTHREAD_PROCESS_SHARED:
795 /* our current implementation of pthread actually supports shared
796 * mutexes but won't cleanup if a process dies with the mutex held.
797 * Nevertheless, it's better than nothing. Shared mutexes are used
798 * by surfaceflinger and audioflinger.
799 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700800 *attr |= MUTEXATTR_SHARED_MASK;
Mathias Agopianb7681162009-07-13 22:00:33 -0700801 return 0;
802 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700803 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800804}
805
806int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
807{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700808 if (!attr || !pshared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800809 return EINVAL;
810
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700811 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED
812 : PTHREAD_PROCESS_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800813 return 0;
814}
815
816int pthread_mutex_init(pthread_mutex_t *mutex,
817 const pthread_mutexattr_t *attr)
818{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700819 int value = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800820
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700821 if (mutex == NULL)
822 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800823
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700824 if (__likely(attr == NULL)) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100825 mutex->value = MUTEX_TYPE_BITS_NORMAL;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700826 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800827 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700828
829 if ((*attr & MUTEXATTR_SHARED_MASK) != 0)
830 value |= MUTEX_SHARED_MASK;
831
832 switch (*attr & MUTEXATTR_TYPE_MASK) {
833 case PTHREAD_MUTEX_NORMAL:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100834 value |= MUTEX_TYPE_BITS_NORMAL;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700835 break;
836 case PTHREAD_MUTEX_RECURSIVE:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100837 value |= MUTEX_TYPE_BITS_RECURSIVE;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700838 break;
839 case PTHREAD_MUTEX_ERRORCHECK:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100840 value |= MUTEX_TYPE_BITS_ERRORCHECK;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700841 break;
842 default:
843 return EINVAL;
844 }
845
846 mutex->value = value;
847 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800848}
849
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800850
851/*
852 * Lock a non-recursive mutex.
853 *
854 * As noted above, there are three states:
855 * 0 (unlocked, no contention)
856 * 1 (locked, no contention)
857 * 2 (locked, contention)
858 *
859 * Non-recursive mutexes don't use the thread-id or counter fields, and the
860 * "type" value is zero, so the only bits that will be set are the ones in
861 * the lock state field.
862 */
863static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100864_normal_lock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800865{
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100866 /* convenience shortcuts */
867 const int unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
868 const int locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800869 /*
870 * The common case is an unlocked mutex, so we begin by trying to
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100871 * change the lock's state from 0 (UNLOCKED) to 1 (LOCKED).
872 * __bionic_cmpxchg() returns 0 if it made the swap successfully.
873 * If the result is nonzero, this lock is already held by another thread.
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800874 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100875 if (__bionic_cmpxchg(unlocked, locked_uncontended, &mutex->value) != 0) {
876 const int locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800877 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800878 * We want to go to sleep until the mutex is available, which
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100879 * requires promoting it to state 2 (CONTENDED). We need to
880 * swap in the new state value and then wait until somebody wakes us up.
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800881 *
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100882 * __bionic_swap() returns the previous value. We swap 2 in and
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800883 * see if we got zero back; if so, we have acquired the lock. If
884 * not, another thread still holds the lock and we wait again.
885 *
886 * The second argument to the __futex_wait() call is compared
887 * against the current value. If it doesn't match, __futex_wait()
888 * returns immediately (otherwise, it sleeps for a time specified
889 * by the third argument; 0 means sleep forever). This ensures
890 * that the mutex is in state 2 when we go to sleep on it, which
891 * guarantees a wake-up call.
892 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100893 while (__bionic_swap(locked_contended, &mutex->value) != unlocked)
894 __futex_wait_ex(&mutex->value, shared, locked_contended, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800895 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700896 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800897}
898
899/*
900 * Release a non-recursive mutex. The caller is responsible for determining
901 * that we are in fact the owner of this lock.
902 */
903static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100904_normal_unlock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800905{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700906 ANDROID_MEMBAR_FULL();
907
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800908 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700909 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100910 * to release the lock. __bionic_atomic_dec() returns the previous value;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800911 * if it wasn't 1 we have to do some additional work.
912 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100913 if (__bionic_atomic_dec(&mutex->value) != (shared|MUTEX_STATE_BITS_LOCKED_UNCONTENDED)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800914 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800915 * Start by releasing the lock. The decrement changed it from
916 * "contended lock" to "uncontended lock", which means we still
917 * hold it, and anybody who tries to sneak in will push it back
918 * to state 2.
919 *
920 * Once we set it to zero the lock is up for grabs. We follow
921 * this with a __futex_wake() to ensure that one of the waiting
922 * threads has a chance to grab it.
923 *
924 * This doesn't cause a race with the swap/wait pair in
925 * _normal_lock(), because the __futex_wait() call there will
926 * return immediately if the mutex value isn't 2.
927 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700928 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800929
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800930 /*
931 * Wake up one waiting thread. We don't know which thread will be
932 * woken or when it'll start executing -- futexes make no guarantees
933 * here. There may not even be a thread waiting.
934 *
935 * The newly-woken thread will replace the 0 we just set above
936 * with 2, which means that when it eventually releases the mutex
937 * it will also call FUTEX_WAKE. This results in one extra wake
938 * call whenever a lock is contended, but lets us avoid forgetting
939 * anyone without requiring us to track the number of sleepers.
940 *
941 * It's possible for another thread to sneak in and grab the lock
942 * between the zero assignment above and the wake call below. If
943 * the new thread is "slow" and holds the lock for a while, we'll
944 * wake up a sleeper, which will swap in a 2 and then go back to
945 * sleep since the lock is still held. If the new thread is "fast",
946 * running to completion before we call wake, the thread we
947 * eventually wake will find an unlocked mutex and will execute.
948 * Either way we have correct behavior and nobody is orphaned on
949 * the wait queue.
950 */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -0700951 __futex_wake_ex(&mutex->value, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800952 }
953}
954
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100955/* This common inlined function is used to increment the counter of an
956 * errorcheck or recursive mutex.
957 *
958 * For errorcheck mutexes, it will return EDEADLK
959 * If the counter overflows, it will return EAGAIN
960 * Otherwise, it atomically increments the counter and returns 0
961 * after providing an acquire barrier.
962 *
963 * mtype is the current mutex type
964 * mvalue is the current mutex value (already loaded)
965 * mutex pointers to the mutex.
966 */
967static __inline__ __attribute__((always_inline)) int
968_recursive_increment(pthread_mutex_t* mutex, int mvalue, int mtype)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800969{
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100970 if (mtype == MUTEX_TYPE_BITS_ERRORCHECK) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100971 /* trying to re-lock a mutex we already acquired */
972 return EDEADLK;
973 }
974
975 /* Detect recursive lock overflow and return EAGAIN.
976 * This is safe because only the owner thread can modify the
David 'Digit' Turnerb57db752012-01-24 13:20:38 +0100977 * counter bits in the mutex value.
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100978 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100979 if (MUTEX_COUNTER_BITS_WILL_OVERFLOW(mvalue)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100980 return EAGAIN;
981 }
982
983 /* We own the mutex, but other threads are able to change
David 'Digit' Turnerb57db752012-01-24 13:20:38 +0100984 * the lower bits (e.g. promoting it to "contended"), so we
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100985 * need to use an atomic cmpxchg loop to update the counter.
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100986 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100987 for (;;) {
988 /* increment counter, overflow was already checked */
989 int newval = mvalue + MUTEX_COUNTER_BITS_ONE;
990 if (__likely(__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0)) {
991 /* mutex is still locked, not need for a memory barrier */
992 return 0;
993 }
994 /* the value was changed, this happens when another thread changes
995 * the lower state bits from 1 to 2 to indicate contention. This
996 * cannot change the counter, so simply reload and try again.
997 */
998 mvalue = mutex->value;
999 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001000}
1001
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001002__LIBC_HIDDEN__
1003int pthread_mutex_lock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001004{
Wink Savillea12c5442013-01-08 15:15:45 -08001005 int mvalue, mtype, tid, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001006
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001007 if (__unlikely(mutex == NULL))
1008 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001009
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001010 mvalue = mutex->value;
1011 mtype = (mvalue & MUTEX_TYPE_MASK);
1012 shared = (mvalue & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001013
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001014 /* Handle normal case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001015 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) ) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001016 _normal_lock(mutex, shared);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001017 return 0;
1018 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001019
1020 /* Do we already own this recursive or error-check mutex ? */
1021 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001022 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001023 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001024
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001025 /* Add in shared state to avoid extra 'or' operations below */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001026 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001027
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001028 /* First, if the mutex is unlocked, try to quickly acquire it.
1029 * In the optimistic case where this works, set the state to 1 to
1030 * indicate locked with no contention */
1031 if (mvalue == mtype) {
1032 int newval = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1033 if (__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0) {
1034 ANDROID_MEMBAR_FULL();
1035 return 0;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001036 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001037 /* argh, the value changed, reload before entering the loop */
1038 mvalue = mutex->value;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001039 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001040
1041 for (;;) {
1042 int newval;
1043
1044 /* if the mutex is unlocked, its value should be 'mtype' and
1045 * we try to acquire it by setting its owner and state atomically.
1046 * NOTE: We put the state to 2 since we _know_ there is contention
1047 * when we are in this loop. This ensures all waiters will be
1048 * unlocked.
1049 */
1050 if (mvalue == mtype) {
1051 newval = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1052 /* TODO: Change this to __bionic_cmpxchg_acquire when we
1053 * implement it to get rid of the explicit memory
1054 * barrier below.
1055 */
1056 if (__unlikely(__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0)) {
1057 mvalue = mutex->value;
1058 continue;
1059 }
1060 ANDROID_MEMBAR_FULL();
1061 return 0;
1062 }
1063
1064 /* the mutex is already locked by another thread, if its state is 1
1065 * we will change it to 2 to indicate contention. */
1066 if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(mvalue)) {
1067 newval = MUTEX_STATE_BITS_FLIP_CONTENTION(mvalue); /* locked state 1 => state 2 */
1068 if (__unlikely(__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0)) {
1069 mvalue = mutex->value;
1070 continue;
1071 }
1072 mvalue = newval;
1073 }
1074
1075 /* wait until the mutex is unlocked */
1076 __futex_wait_ex(&mutex->value, shared, mvalue, NULL);
1077
1078 mvalue = mutex->value;
1079 }
1080 /* NOTREACHED */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001081}
1082
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001083int pthread_mutex_lock(pthread_mutex_t *mutex)
1084{
1085 int err = pthread_mutex_lock_impl(mutex);
1086#ifdef PTHREAD_DEBUG
1087 if (PTHREAD_DEBUG_ENABLED) {
1088 if (!err) {
1089 pthread_debug_mutex_lock_check(mutex);
1090 }
1091 }
1092#endif
1093 return err;
1094}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001095
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001096__LIBC_HIDDEN__
1097int pthread_mutex_unlock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001098{
Wink Savillea12c5442013-01-08 15:15:45 -08001099 int mvalue, mtype, tid, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001100
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001101 if (__unlikely(mutex == NULL))
1102 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001103
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001104 mvalue = mutex->value;
1105 mtype = (mvalue & MUTEX_TYPE_MASK);
1106 shared = (mvalue & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001107
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001108 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001109 if (__likely(mtype == MUTEX_TYPE_BITS_NORMAL)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001110 _normal_unlock(mutex, shared);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001111 return 0;
1112 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001113
1114 /* Do we already own this recursive or error-check mutex ? */
1115 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001116 if ( tid != MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001117 return EPERM;
1118
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001119 /* If the counter is > 0, we can simply decrement it atomically.
1120 * Since other threads can mutate the lower state bits (and only the
1121 * lower state bits), use a cmpxchg to do it.
1122 */
1123 if (!MUTEX_COUNTER_BITS_IS_ZERO(mvalue)) {
1124 for (;;) {
1125 int newval = mvalue - MUTEX_COUNTER_BITS_ONE;
1126 if (__likely(__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0)) {
1127 /* success: we still own the mutex, so no memory barrier */
1128 return 0;
1129 }
1130 /* the value changed, so reload and loop */
1131 mvalue = mutex->value;
1132 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001133 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001134
1135 /* the counter is 0, so we're going to unlock the mutex by resetting
1136 * its value to 'unlocked'. We need to perform a swap in order
1137 * to read the current state, which will be 2 if there are waiters
1138 * to awake.
1139 *
1140 * TODO: Change this to __bionic_swap_release when we implement it
1141 * to get rid of the explicit memory barrier below.
1142 */
1143 ANDROID_MEMBAR_FULL(); /* RELEASE BARRIER */
1144 mvalue = __bionic_swap(mtype | shared | MUTEX_STATE_BITS_UNLOCKED, &mutex->value);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001145
1146 /* Wake one waiting thread, if any */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001147 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(mvalue)) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001148 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001149 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001150 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001151}
1152
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001153int pthread_mutex_unlock(pthread_mutex_t *mutex)
1154{
1155#ifdef PTHREAD_DEBUG
1156 if (PTHREAD_DEBUG_ENABLED) {
1157 pthread_debug_mutex_unlock_check(mutex);
1158 }
1159#endif
1160 return pthread_mutex_unlock_impl(mutex);
1161}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001162
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001163__LIBC_HIDDEN__
1164int pthread_mutex_trylock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001165{
Wink Savillea12c5442013-01-08 15:15:45 -08001166 int mvalue, mtype, tid, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001167
1168 if (__unlikely(mutex == NULL))
1169 return EINVAL;
1170
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001171 mvalue = mutex->value;
1172 mtype = (mvalue & MUTEX_TYPE_MASK);
1173 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001174
1175 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001176 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001177 {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001178 if (__bionic_cmpxchg(shared|MUTEX_STATE_BITS_UNLOCKED,
1179 shared|MUTEX_STATE_BITS_LOCKED_UNCONTENDED,
1180 &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001181 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001182 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001183 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001184
1185 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001186 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001187
1188 /* Do we already own this recursive or error-check mutex ? */
1189 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001190 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001191 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001192
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001193 /* Same as pthread_mutex_lock, except that we don't want to wait, and
1194 * the only operation that can succeed is a single cmpxchg to acquire the
1195 * lock if it is released / not owned by anyone. No need for a complex loop.
1196 */
1197 mtype |= shared | MUTEX_STATE_BITS_UNLOCKED;
1198 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001199
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001200 if (__likely(__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0)) {
1201 ANDROID_MEMBAR_FULL();
1202 return 0;
1203 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001204
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001205 return EBUSY;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001206}
1207
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001208int pthread_mutex_trylock(pthread_mutex_t *mutex)
1209{
1210 int err = pthread_mutex_trylock_impl(mutex);
1211#ifdef PTHREAD_DEBUG
1212 if (PTHREAD_DEBUG_ENABLED) {
1213 if (!err) {
1214 pthread_debug_mutex_lock_check(mutex);
1215 }
1216 }
1217#endif
1218 return err;
1219}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001220
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001221/* initialize 'ts' with the difference between 'abstime' and the current time
1222 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
1223 */
1224static int
1225__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
1226{
1227 clock_gettime(clock, ts);
1228 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
1229 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
1230 if (ts->tv_nsec < 0) {
1231 ts->tv_sec--;
1232 ts->tv_nsec += 1000000000;
1233 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001234 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001235 return -1;
1236
1237 return 0;
1238}
1239
1240/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1241 * milliseconds.
1242 */
1243static void
1244__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1245{
1246 clock_gettime(clock, abstime);
1247 abstime->tv_sec += msecs/1000;
1248 abstime->tv_nsec += (msecs%1000)*1000000;
1249 if (abstime->tv_nsec >= 1000000000) {
1250 abstime->tv_sec++;
1251 abstime->tv_nsec -= 1000000000;
1252 }
1253}
1254
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001255__LIBC_HIDDEN__
1256int pthread_mutex_lock_timeout_np_impl(pthread_mutex_t *mutex, unsigned msecs)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001257{
1258 clockid_t clock = CLOCK_MONOTONIC;
1259 struct timespec abstime;
1260 struct timespec ts;
Wink Savillea12c5442013-01-08 15:15:45 -08001261 int mvalue, mtype, tid, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001262
1263 /* compute absolute expiration time */
1264 __timespec_to_relative_msec(&abstime, msecs, clock);
1265
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001266 if (__unlikely(mutex == NULL))
1267 return EINVAL;
1268
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001269 mvalue = mutex->value;
1270 mtype = (mvalue & MUTEX_TYPE_MASK);
1271 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001272
1273 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001274 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001275 {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001276 const int unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
1277 const int locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1278 const int locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1279
1280 /* fast path for uncontended lock. Note: MUTEX_TYPE_BITS_NORMAL is 0 */
1281 if (__bionic_cmpxchg(unlocked, locked_uncontended, &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001282 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001283 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001284 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001285
1286 /* loop while needed */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001287 while (__bionic_swap(locked_contended, &mutex->value) != unlocked) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001288 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1289 return EBUSY;
1290
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001291 __futex_wait_ex(&mutex->value, shared, locked_contended, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001292 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001293 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001294 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001295 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001296
1297 /* Do we already own this recursive or error-check mutex ? */
1298 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001299 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001300 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001301
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001302 /* the following implements the same loop than pthread_mutex_lock_impl
1303 * but adds checks to ensure that the operation never exceeds the
1304 * absolute expiration time.
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001305 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001306 mtype |= shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001307
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001308 /* first try a quick lock */
1309 if (mvalue == mtype) {
1310 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1311 if (__likely(__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0)) {
1312 ANDROID_MEMBAR_FULL();
1313 return 0;
1314 }
1315 mvalue = mutex->value;
1316 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001317
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001318 for (;;) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001319 struct timespec ts;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001320
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001321 /* if the value is 'unlocked', try to acquire it directly */
1322 /* NOTE: put state to 2 since we know there is contention */
1323 if (mvalue == mtype) /* unlocked */ {
1324 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1325 if (__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0) {
1326 ANDROID_MEMBAR_FULL();
1327 return 0;
1328 }
1329 /* the value changed before we could lock it. We need to check
1330 * the time to avoid livelocks, reload the value, then loop again. */
1331 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1332 return EBUSY;
1333
1334 mvalue = mutex->value;
1335 continue;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001336 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001337
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001338 /* The value is locked. If 'uncontended', try to switch its state
1339 * to 'contented' to ensure we get woken up later. */
1340 if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(mvalue)) {
1341 int newval = MUTEX_STATE_BITS_FLIP_CONTENTION(mvalue);
1342 if (__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0) {
1343 /* this failed because the value changed, reload it */
1344 mvalue = mutex->value;
1345 } else {
1346 /* this succeeded, update mvalue */
1347 mvalue = newval;
1348 }
1349 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001350
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001351 /* check time and update 'ts' */
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001352 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1353 return EBUSY;
1354
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001355 /* Only wait to be woken up if the state is '2', otherwise we'll
1356 * simply loop right now. This can happen when the second cmpxchg
1357 * in our loop failed because the mutex was unlocked by another
1358 * thread.
1359 */
1360 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(mvalue)) {
1361 if (__futex_wait_ex(&mutex->value, shared, mvalue, &ts) == ETIMEDOUT) {
1362 return EBUSY;
1363 }
1364 mvalue = mutex->value;
1365 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001366 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001367 /* NOTREACHED */
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001368}
1369
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001370int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1371{
1372 int err = pthread_mutex_lock_timeout_np_impl(mutex, msecs);
1373#ifdef PTHREAD_DEBUG
1374 if (PTHREAD_DEBUG_ENABLED) {
1375 if (!err) {
1376 pthread_debug_mutex_lock_check(mutex);
1377 }
1378 }
1379#endif
1380 return err;
1381}
1382
1383int pthread_mutex_destroy(pthread_mutex_t *mutex)
1384{
1385 int ret;
1386
1387 /* use trylock to ensure that the mutex value is
1388 * valid and is not already locked. */
1389 ret = pthread_mutex_trylock_impl(mutex);
1390 if (ret != 0)
1391 return ret;
1392
1393 mutex->value = 0xdead10cc;
1394 return 0;
1395}
1396
1397
1398
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001399int pthread_condattr_init(pthread_condattr_t *attr)
1400{
1401 if (attr == NULL)
1402 return EINVAL;
1403
1404 *attr = PTHREAD_PROCESS_PRIVATE;
1405 return 0;
1406}
1407
1408int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1409{
1410 if (attr == NULL || pshared == NULL)
1411 return EINVAL;
1412
1413 *pshared = *attr;
1414 return 0;
1415}
1416
1417int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1418{
1419 if (attr == NULL)
1420 return EINVAL;
1421
1422 if (pshared != PTHREAD_PROCESS_SHARED &&
1423 pshared != PTHREAD_PROCESS_PRIVATE)
1424 return EINVAL;
1425
1426 *attr = pshared;
1427 return 0;
1428}
1429
1430int pthread_condattr_destroy(pthread_condattr_t *attr)
1431{
1432 if (attr == NULL)
1433 return EINVAL;
1434
1435 *attr = 0xdeada11d;
1436 return 0;
1437}
1438
1439/* We use one bit in condition variable values as the 'shared' flag
1440 * The rest is a counter.
1441 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001442#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001443#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001444#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1445
1446#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001447
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001448/* XXX *technically* there is a race condition that could allow
1449 * XXX a signal to be missed. If thread A is preempted in _wait()
1450 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001451 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001452 * XXX before thread A is scheduled again and calls futex_wait(),
1453 * XXX then the signal will be lost.
1454 */
1455
1456int pthread_cond_init(pthread_cond_t *cond,
1457 const pthread_condattr_t *attr)
1458{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001459 if (cond == NULL)
1460 return EINVAL;
1461
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001462 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001463
1464 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001465 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001466
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001467 return 0;
1468}
1469
1470int pthread_cond_destroy(pthread_cond_t *cond)
1471{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001472 if (cond == NULL)
1473 return EINVAL;
1474
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001475 cond->value = 0xdeadc04d;
1476 return 0;
1477}
1478
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001479/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001480 * pthread_cond_signal to atomically decrement the counter
1481 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001482 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001483static int
1484__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001485{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001486 long flags;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001487
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001488 if (__unlikely(cond == NULL))
1489 return EINVAL;
1490
1491 flags = (cond->value & ~COND_COUNTER_MASK);
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001492 for (;;) {
1493 long oldval = cond->value;
1494 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1495 | flags;
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001496 if (__bionic_cmpxchg(oldval, newval, &cond->value) == 0)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001497 break;
1498 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001499
Andy McFaddene2ac8982010-09-02 13:34:53 -07001500 /*
1501 * Ensure that all memory accesses previously made by this thread are
1502 * visible to the woken thread(s). On the other side, the "wait"
1503 * code will issue any necessary barriers when locking the mutex.
1504 *
1505 * This may not strictly be necessary -- if the caller follows
1506 * recommended practice and holds the mutex before signaling the cond
1507 * var, the mutex ops will provide correct semantics. If they don't
1508 * hold the mutex, they're subject to race conditions anyway.
1509 */
1510 ANDROID_MEMBAR_FULL();
1511
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001512 __futex_wake_ex(&cond->value, COND_IS_SHARED(cond), counter);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001513 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001514}
1515
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001516int pthread_cond_broadcast(pthread_cond_t *cond)
1517{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001518 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001519}
1520
1521int pthread_cond_signal(pthread_cond_t *cond)
1522{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001523 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001524}
1525
1526int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1527{
1528 return pthread_cond_timedwait(cond, mutex, NULL);
1529}
1530
1531int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1532 pthread_mutex_t * mutex,
1533 const struct timespec *reltime)
1534{
1535 int status;
1536 int oldvalue = cond->value;
1537
1538 pthread_mutex_unlock(mutex);
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001539 status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond), oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001540 pthread_mutex_lock(mutex);
1541
1542 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1543 return 0;
1544}
1545
1546int __pthread_cond_timedwait(pthread_cond_t *cond,
1547 pthread_mutex_t * mutex,
1548 const struct timespec *abstime,
1549 clockid_t clock)
1550{
1551 struct timespec ts;
1552 struct timespec * tsp;
1553
1554 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001555 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001556 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001557 tsp = &ts;
1558 } else {
1559 tsp = NULL;
1560 }
1561
1562 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1563}
1564
1565int pthread_cond_timedwait(pthread_cond_t *cond,
1566 pthread_mutex_t * mutex,
1567 const struct timespec *abstime)
1568{
1569 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1570}
1571
1572
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001573/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001574int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1575 pthread_mutex_t * mutex,
1576 const struct timespec *abstime)
1577{
1578 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1579}
1580
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001581int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1582 pthread_mutex_t * mutex,
1583 const struct timespec *abstime)
1584{
1585 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1586}
1587
1588int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1589 pthread_mutex_t * mutex,
1590 const struct timespec *reltime)
1591{
1592 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1593}
1594
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001595int pthread_cond_timeout_np(pthread_cond_t *cond,
1596 pthread_mutex_t * mutex,
1597 unsigned msecs)
1598{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001599 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001600
1601 ts.tv_sec = msecs / 1000;
1602 ts.tv_nsec = (msecs % 1000) * 1000000;
1603
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001604 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001605}
1606
1607
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001608// man says this should be in <linux/unistd.h>, but it isn't
Jeff Brown10c8ce52011-11-18 15:17:07 -08001609extern int tgkill(int tgid, int tid, int sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001610
1611int pthread_kill(pthread_t tid, int sig)
1612{
1613 int ret;
1614 int old_errno = errno;
1615 pthread_internal_t * thread = (pthread_internal_t *)tid;
1616
Jeff Brown10c8ce52011-11-18 15:17:07 -08001617 ret = tgkill(getpid(), thread->kernel_id, sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001618 if (ret < 0) {
1619 ret = errno;
1620 errno = old_errno;
1621 }
1622
1623 return ret;
1624}
1625
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001626
1627int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
1628{
1629 const int CLOCK_IDTYPE_BITS = 3;
1630 pthread_internal_t* thread = (pthread_internal_t*)tid;
1631
1632 if (!thread)
1633 return ESRCH;
1634
1635 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
1636 return 0;
1637}
1638
1639
1640/* NOTE: this implementation doesn't support a init function that throws a C++ exception
1641 * or calls fork()
1642 */
1643int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
1644{
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001645 volatile pthread_once_t* ocptr = once_control;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001646
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001647 /* PTHREAD_ONCE_INIT is 0, we use the following bit flags
1648 *
1649 * bit 0 set -> initialization is under way
1650 * bit 1 set -> initialization is complete
1651 */
1652#define ONCE_INITIALIZING (1 << 0)
1653#define ONCE_COMPLETED (1 << 1)
1654
1655 /* First check if the once is already initialized. This will be the common
1656 * case and we want to make this as fast as possible. Note that this still
1657 * requires a load_acquire operation here to ensure that all the
1658 * stores performed by the initialization function are observable on
1659 * this CPU after we exit.
1660 */
1661 if (__likely((*ocptr & ONCE_COMPLETED) != 0)) {
1662 ANDROID_MEMBAR_FULL();
1663 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001664 }
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001665
1666 for (;;) {
1667 /* Try to atomically set the INITIALIZING flag.
1668 * This requires a cmpxchg loop, and we may need
Elliott Hughesbfeab1b2012-09-05 17:47:37 -07001669 * to exit prematurely if we detect that
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001670 * COMPLETED is now set.
1671 */
1672 int32_t oldval, newval;
1673
1674 do {
1675 oldval = *ocptr;
1676 if ((oldval & ONCE_COMPLETED) != 0)
1677 break;
1678
1679 newval = oldval | ONCE_INITIALIZING;
1680 } while (__bionic_cmpxchg(oldval, newval, ocptr) != 0);
1681
1682 if ((oldval & ONCE_COMPLETED) != 0) {
1683 /* We detected that COMPLETED was set while in our loop */
1684 ANDROID_MEMBAR_FULL();
1685 return 0;
1686 }
1687
1688 if ((oldval & ONCE_INITIALIZING) == 0) {
1689 /* We got there first, we can jump out of the loop to
1690 * handle the initialization */
1691 break;
1692 }
1693
1694 /* Another thread is running the initialization and hasn't completed
1695 * yet, so wait for it, then try again. */
1696 __futex_wait_ex(ocptr, 0, oldval, NULL);
1697 }
1698
1699 /* call the initialization function. */
1700 (*init_routine)();
1701
1702 /* Do a store_release indicating that initialization is complete */
1703 ANDROID_MEMBAR_FULL();
1704 *ocptr = ONCE_COMPLETED;
1705
1706 /* Wake up any waiters, if any */
1707 __futex_wake_ex(ocptr, 0, INT_MAX);
1708
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001709 return 0;
1710}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03001711
Glenn Kastend53cae02011-07-11 15:41:28 -07001712/* Return the kernel thread ID for a pthread.
1713 * This is only defined for implementations where pthread <-> kernel is 1:1, which this is.
1714 * Not the same as pthread_getthreadid_np, which is commonly defined to be opaque.
1715 * Internal, not an NDK API.
1716 */
1717
1718pid_t __pthread_gettid(pthread_t thid)
1719{
1720 pthread_internal_t* thread = (pthread_internal_t*)thid;
1721 return thread->kernel_id;
1722}
Jean-Baptiste Querufaca92f2012-03-26 15:25:19 -07001723
1724int __pthread_settid(pthread_t thid, pid_t tid)
1725{
1726 if (thid == 0)
1727 return EINVAL;
1728
1729 pthread_internal_t* thread = (pthread_internal_t*)thid;
1730 thread->kernel_id = tid;
1731
1732 return 0;
1733}