blob: e1ace7dc2a8d3f06c4ce51005e66aa87a35e48b3 [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 <assert.h>
Elliott Hughes2a1bb4e2013-02-11 12:34:03 -080030#include <errno.h>
Elliott Hughes6f94de32013-02-12 06:06:22 +000031#include <fcntl.h>
Elliott Hughes2a1bb4e2013-02-11 12:34:03 -080032#include <limits.h>
Elliott Hughes6f94de32013-02-12 06:06:22 +000033#include <malloc.h>
34#include <memory.h>
35#include <pthread.h>
36#include <signal.h>
37#include <stdint.h>
38#include <stdio.h>
39#include <stdlib.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080040#include <sys/atomics.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080041#include <sys/mman.h>
Elliott Hughes6f94de32013-02-12 06:06:22 +000042#include <sys/prctl.h>
43#include <sys/stat.h>
44#include <sys/types.h>
45#include <time.h>
Pierre Peifferd0c884d2012-02-22 16:40:15 +010046#include <unistd.h>
47
48#include "bionic_atomic_inline.h"
49#include "bionic_futex.h"
50#include "bionic_pthread.h"
Elliott Hughesad88a082012-10-24 18:37:21 -070051#include "bionic_ssp.h"
Pierre Peifferd0c884d2012-02-22 16:40:15 +010052#include "bionic_tls.h"
Elliott Hughes1e980b62013-01-17 18:36:06 -080053#include "debug_format.h"
Pierre Peifferd0c884d2012-02-22 16:40:15 +010054#include "pthread_internal.h"
55#include "thread_private.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080056
Mathias Agopian7c0c3792011-09-05 23:54:55 -070057extern void pthread_debug_mutex_lock_check(pthread_mutex_t *mutex);
58extern void pthread_debug_mutex_unlock_check(pthread_mutex_t *mutex);
59
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080060extern int __pthread_clone(int (*fn)(void*), void *child_stack, int flags, void *arg);
61extern void _exit_with_stack_teardown(void * stackBase, int stackSize, int retCode);
62extern void _exit_thread(int retCode);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080063
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -070064int __futex_wake_ex(volatile void *ftx, int pshared, int val)
65{
66 return __futex_syscall3(ftx, pshared ? FUTEX_WAKE : FUTEX_WAKE_PRIVATE, val);
67}
68
69int __futex_wait_ex(volatile void *ftx, int pshared, int val, const struct timespec *timeout)
70{
71 return __futex_syscall4(ftx, pshared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE, val, timeout);
72}
73
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -070074#define __likely(cond) __builtin_expect(!!(cond), 1)
75#define __unlikely(cond) __builtin_expect(!!(cond), 0)
76
Bruce Beare8e551a62011-03-28 09:47:35 -070077#ifdef __i386__
78#define ATTRIBUTES __attribute__((noinline)) __attribute__((fastcall))
79#else
80#define ATTRIBUTES __attribute__((noinline))
81#endif
82
83void ATTRIBUTES _thread_created_hook(pid_t thread_id);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080084
Pierre Peifferd0c884d2012-02-22 16:40:15 +010085static const int kPthreadInitFailed = 1;
86
Elliott Hughes6f94de32013-02-12 06:06:22 +000087#define PTHREAD_ATTR_FLAG_DETACHED 0x00000001
88#define PTHREAD_ATTR_FLAG_USER_STACK 0x00000002
89
90#define DEFAULT_STACKSIZE (1024 * 1024)
91
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080092static pthread_mutex_t mmap_lock = PTHREAD_MUTEX_INITIALIZER;
93
Elliott Hughes6f94de32013-02-12 06:06:22 +000094
95static const pthread_attr_t gDefaultPthreadAttr = {
96 .flags = 0,
97 .stack_base = NULL,
98 .stack_size = DEFAULT_STACKSIZE,
99 .guard_size = PAGE_SIZE,
100 .sched_policy = SCHED_NORMAL,
101 .sched_priority = 0
102};
103
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000104__LIBC_HIDDEN__ pthread_internal_t* gThreadList = NULL;
105__LIBC_HIDDEN__ pthread_mutex_t gThreadListLock = PTHREAD_MUTEX_INITIALIZER;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800106static pthread_mutex_t gDebuggerNotificationLock = PTHREAD_MUTEX_INITIALIZER;
107
Elliott Hughes4f251be2012-11-01 16:33:29 -0700108static void _pthread_internal_remove_locked(pthread_internal_t* thread) {
109 if (thread->next != NULL) {
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700110 thread->next->prev = thread->prev;
Elliott Hughes4f251be2012-11-01 16:33:29 -0700111 }
112 if (thread->prev != NULL) {
113 thread->prev->next = thread->next;
114 } else {
115 gThreadList = thread->next;
116 }
117
118 // The main thread is not heap-allocated. See __libc_init_tls for the declaration,
119 // and __libc_init_common for the point where it's added to the thread list.
120 if (thread->allocated_on_heap) {
121 free(thread);
122 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800123}
124
Elliott Hughes4f251be2012-11-01 16:33:29 -0700125static void _pthread_internal_remove(pthread_internal_t* thread) {
126 pthread_mutex_lock(&gThreadListLock);
127 _pthread_internal_remove_locked(thread);
128 pthread_mutex_unlock(&gThreadListLock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800129}
130
Elliott Hughes4f251be2012-11-01 16:33:29 -0700131__LIBC_ABI_PRIVATE__ void _pthread_internal_add(pthread_internal_t* thread) {
132 pthread_mutex_lock(&gThreadListLock);
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700133
Elliott Hughes4f251be2012-11-01 16:33:29 -0700134 // We insert at the head.
135 thread->next = gThreadList;
136 thread->prev = NULL;
137 if (thread->next != NULL) {
138 thread->next->prev = thread;
139 }
140 gThreadList = thread;
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700141
Elliott Hughes4f251be2012-11-01 16:33:29 -0700142 pthread_mutex_unlock(&gThreadListLock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800143}
144
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +0400145__LIBC_ABI_PRIVATE__ pthread_internal_t*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800146__get_thread(void)
147{
148 void** tls = (void**)__get_tls();
149
150 return (pthread_internal_t*) tls[TLS_SLOT_THREAD_ID];
151}
152
153
154void*
155__get_stack_base(int *p_stack_size)
156{
157 pthread_internal_t* thread = __get_thread();
158
159 *p_stack_size = thread->attr.stack_size;
160 return thread->attr.stack_base;
161}
162
163
Elliott Hughes5419b942012-10-16 15:54:46 -0700164void __init_tls(void** tls, void* thread) {
165 ((pthread_internal_t*) thread)->tls = tls;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800166
Elliott Hughes5419b942012-10-16 15:54:46 -0700167 // Zero-initialize all the slots.
168 for (size_t i = 0; i < BIONIC_TLS_SLOTS; ++i) {
169 tls[i] = NULL;
170 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800171
Elliott Hughesad88a082012-10-24 18:37:21 -0700172 // Slot 0 must point to itself. The x86 Linux kernel reads the TLS from %fs:0.
Elliott Hughesd3920b32013-02-07 18:39:34 -0800173 tls[TLS_SLOT_SELF] = tls;
Elliott Hughes5419b942012-10-16 15:54:46 -0700174 tls[TLS_SLOT_THREAD_ID] = thread;
Elliott Hughesd3920b32013-02-07 18:39:34 -0800175 // GCC looks in the TLS for the stack guard on x86, so copy it there from our global.
176 tls[TLS_SLOT_STACK_GUARD] = (void*) __stack_chk_guard;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800177
Elliott Hughes5419b942012-10-16 15:54:46 -0700178 __set_tls((void*) tls);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800179}
180
181
182/*
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100183 * This trampoline is called from the assembly _pthread_clone() function.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800184 */
185void __thread_entry(int (*func)(void*), void *arg, void **tls)
186{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800187 // Wait for our creating thread to release us. This lets it have time to
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100188 // notify gdb about this thread before we start doing anything.
Andy McFaddene2ac8982010-09-02 13:34:53 -0700189 //
190 // This also provides the memory barrier needed to ensure that all memory
191 // accesses previously made by the creating thread are visible to us.
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100192 pthread_mutex_t* start_mutex = (pthread_mutex_t*) &tls[TLS_SLOT_SELF];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800193 pthread_mutex_lock(start_mutex);
194 pthread_mutex_destroy(start_mutex);
195
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100196 pthread_internal_t* thread = (pthread_internal_t*) tls[TLS_SLOT_THREAD_ID];
197 __init_tls(tls, thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800198
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100199 if ((thread->internal_flags & kPthreadInitFailed) != 0) {
200 pthread_exit(NULL);
201 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800202
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100203 int result = func(arg);
204 pthread_exit((void*) result);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800205}
206
Dave Burke88f1ea82012-09-17 20:37:38 -0700207#include <private/logd.h>
208
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +0400209__LIBC_ABI_PRIVATE__
Xi Wangae8eb742012-10-27 02:02:01 -0400210int _init_thread(pthread_internal_t* thread, pid_t kernel_id, const pthread_attr_t* attr,
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700211 void* stack_base, bool add_to_thread_list)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800212{
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100213 int error = 0;
214
Xi Wangae8eb742012-10-27 02:02:01 -0400215 thread->attr = *attr;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800216 thread->attr.stack_base = stack_base;
Xi Wangae8eb742012-10-27 02:02:01 -0400217 thread->kernel_id = kernel_id;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800218
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100219 // Make a note of whether the user supplied this stack (so we know whether or not to free it).
220 if (attr->stack_base == stack_base) {
221 thread->attr.flags |= PTHREAD_ATTR_FLAG_USER_STACK;
222 }
223
224 // Set the scheduling policy/priority of the thread.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800225 if (thread->attr.sched_policy != SCHED_NORMAL) {
226 struct sched_param param;
227 param.sched_priority = thread->attr.sched_priority;
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100228 if (sched_setscheduler(kernel_id, thread->attr.sched_policy, &param) == -1) {
Xi Wangae8eb742012-10-27 02:02:01 -0400229 // For backwards compatibility reasons, we just warn about failures here.
230 // error = errno;
Dave Burke88f1ea82012-09-17 20:37:38 -0700231 const char* msg = "pthread_create sched_setscheduler call failed: %s\n";
Elliott Hughes1e980b62013-01-17 18:36:06 -0800232 __libc_format_log(ANDROID_LOG_WARN, "libc", msg, strerror(errno));
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100233 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800234 }
235
236 pthread_cond_init(&thread->join_cond, NULL);
237 thread->join_count = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800238 thread->cleanup_stack = NULL;
239
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700240 if (add_to_thread_list) {
241 _pthread_internal_add(thread);
242 }
243
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100244 return error;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800245}
246
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800247static void *mkstack(size_t size, size_t guard_size)
248{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800249 pthread_mutex_lock(&mmap_lock);
250
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100251 int prot = PROT_READ | PROT_WRITE;
252 int flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE;
Elliott Hughes9c3eca72012-05-08 13:26:28 -0700253 void* stack = mmap(NULL, size, prot, flags, -1, 0);
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100254 if (stack == MAP_FAILED) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800255 stack = NULL;
256 goto done;
257 }
258
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100259 if (mprotect(stack, guard_size, PROT_NONE) == -1) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800260 munmap(stack, size);
261 stack = NULL;
262 goto done;
263 }
264
265done:
266 pthread_mutex_unlock(&mmap_lock);
267 return stack;
268}
269
270/*
Andy McFaddene2ac8982010-09-02 13:34:53 -0700271 * Create a new thread. The thread's stack is laid out like so:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800272 *
273 * +---------------------------+
274 * | pthread_internal_t |
275 * +---------------------------+
276 * | |
277 * | TLS area |
278 * | |
279 * +---------------------------+
280 * | |
281 * . .
282 * . stack area .
283 * . .
284 * | |
285 * +---------------------------+
286 * | guard page |
287 * +---------------------------+
288 *
289 * note that TLS[0] must be a pointer to itself, this is required
290 * by the thread-local storage implementation of the x86 Linux
291 * kernel, where the TLS pointer is read by reading fs:[0]
292 */
293int pthread_create(pthread_t *thread_out, pthread_attr_t const * attr,
294 void *(*start_routine)(void *), void * arg)
295{
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100296 int old_errno = errno;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800297
298 /* this will inform the rest of the C library that at least one thread
299 * was created. this will enforce certain functions to acquire/release
300 * locks (e.g. atexit()) to protect shared global structures.
301 *
302 * this works because pthread_create() is not called by the C library
303 * initialization routine that sets up the main thread's data structures.
304 */
305 __isthreaded = 1;
306
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100307 pthread_internal_t* thread = calloc(sizeof(*thread), 1);
308 if (thread == NULL) {
Elliott Hughes6f94de32013-02-12 06:06:22 +0000309 return ENOMEM;
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100310 }
Elliott Hughes4f251be2012-11-01 16:33:29 -0700311 thread->allocated_on_heap = true;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800312
313 if (attr == NULL) {
314 attr = &gDefaultPthreadAttr;
315 }
316
317 // make sure the stack is PAGE_SIZE aligned
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100318 size_t stack_size = (attr->stack_size + (PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
319 uint8_t* stack = attr->stack_base;
320 if (stack == NULL) {
321 stack = mkstack(stack_size, attr->guard_size);
322 if (stack == NULL) {
Elliott Hughes4f251be2012-11-01 16:33:29 -0700323 free(thread);
Elliott Hughes6f94de32013-02-12 06:06:22 +0000324 return ENOMEM;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800325 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800326 }
327
328 // Make room for TLS
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100329 void** tls = (void**)(stack + stack_size - BIONIC_TLS_SLOTS*sizeof(void*));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800330
331 // Create a mutex for the thread in TLS_SLOT_SELF to wait on once it starts so we can keep
332 // it from doing anything until after we notify the debugger about it
Andy McFaddene2ac8982010-09-02 13:34:53 -0700333 //
334 // This also provides the memory barrier we need to ensure that all
335 // memory accesses previously performed by this thread are visible to
336 // the new thread.
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100337 pthread_mutex_t* start_mutex = (pthread_mutex_t*) &tls[TLS_SLOT_SELF];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800338 pthread_mutex_init(start_mutex, NULL);
339 pthread_mutex_lock(start_mutex);
340
341 tls[TLS_SLOT_THREAD_ID] = thread;
342
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100343 int flags = CLONE_FILES | CLONE_FS | CLONE_VM | CLONE_SIGHAND |
344 CLONE_THREAD | CLONE_SYSVSEM | CLONE_DETACHED;
345 int tid = __pthread_clone((int(*)(void*))start_routine, tls, flags, arg);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800346
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100347 if (tid < 0) {
348 int clone_errno = errno;
349 pthread_mutex_unlock(start_mutex);
350 if (stack != attr->stack_base) {
351 munmap(stack, stack_size);
352 }
Elliott Hughes4f251be2012-11-01 16:33:29 -0700353 free(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800354 errno = old_errno;
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100355 return clone_errno;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800356 }
357
Xi Wangae8eb742012-10-27 02:02:01 -0400358 int init_errno = _init_thread(thread, tid, attr, stack, true);
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100359 if (init_errno != 0) {
360 // Mark the thread detached and let its __thread_entry run to
361 // completion. (It'll just exit immediately, cleaning up its resources.)
362 thread->internal_flags |= kPthreadInitFailed;
363 thread->attr.flags |= PTHREAD_ATTR_FLAG_DETACHED;
364 pthread_mutex_unlock(start_mutex);
365 errno = old_errno;
366 return init_errno;
367 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800368
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100369 // Notify any debuggers about the new thread.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800370 pthread_mutex_lock(&gDebuggerNotificationLock);
371 _thread_created_hook(tid);
372 pthread_mutex_unlock(&gDebuggerNotificationLock);
373
Jurijs Oniscuks2932f042012-07-05 14:57:38 +0200374 // Publish the pthread_t and let the thread run.
375 *thread_out = (pthread_t) thread;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800376 pthread_mutex_unlock(start_mutex);
377
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800378 return 0;
379}
380
381
Elliott Hughes6f94de32013-02-12 06:06:22 +0000382int pthread_attr_init(pthread_attr_t * attr)
383{
384 *attr = gDefaultPthreadAttr;
385 return 0;
386}
387
388int pthread_attr_destroy(pthread_attr_t * attr)
389{
390 memset(attr, 0x42, sizeof(pthread_attr_t));
391 return 0;
392}
393
394int pthread_attr_setdetachstate(pthread_attr_t * attr, int state)
395{
396 if (state == PTHREAD_CREATE_DETACHED) {
397 attr->flags |= PTHREAD_ATTR_FLAG_DETACHED;
398 } else if (state == PTHREAD_CREATE_JOINABLE) {
399 attr->flags &= ~PTHREAD_ATTR_FLAG_DETACHED;
400 } else {
401 return EINVAL;
402 }
403 return 0;
404}
405
406int pthread_attr_getdetachstate(pthread_attr_t const * attr, int * state)
407{
408 *state = (attr->flags & PTHREAD_ATTR_FLAG_DETACHED)
409 ? PTHREAD_CREATE_DETACHED
410 : PTHREAD_CREATE_JOINABLE;
411 return 0;
412}
413
414int pthread_attr_setschedpolicy(pthread_attr_t * attr, int policy)
415{
416 attr->sched_policy = policy;
417 return 0;
418}
419
420int pthread_attr_getschedpolicy(pthread_attr_t const * attr, int * policy)
421{
422 *policy = attr->sched_policy;
423 return 0;
424}
425
426int pthread_attr_setschedparam(pthread_attr_t * attr, struct sched_param const * param)
427{
428 attr->sched_priority = param->sched_priority;
429 return 0;
430}
431
432int pthread_attr_getschedparam(pthread_attr_t const * attr, struct sched_param * param)
433{
434 param->sched_priority = attr->sched_priority;
435 return 0;
436}
437
438int pthread_attr_setstacksize(pthread_attr_t * attr, size_t stack_size)
439{
440 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
441 return EINVAL;
442 }
443 attr->stack_size = stack_size;
444 return 0;
445}
446
447int pthread_attr_getstacksize(pthread_attr_t const * attr, size_t * stack_size)
448{
449 *stack_size = attr->stack_size;
450 return 0;
451}
452
453int pthread_attr_setstackaddr(pthread_attr_t * attr __attribute__((unused)),
454 void * stack_addr __attribute__((unused)))
455{
456 // This was removed from POSIX.1-2008, and is not implemented on bionic.
457 // Needed for ABI compatibility with the NDK.
458 return ENOSYS;
459}
460
461int pthread_attr_getstackaddr(pthread_attr_t const * attr, void ** stack_addr)
462{
463 // This was removed from POSIX.1-2008.
464 // Needed for ABI compatibility with the NDK.
465 *stack_addr = (char*)attr->stack_base + attr->stack_size;
466 return 0;
467}
468
469int pthread_attr_setstack(pthread_attr_t * attr, void * stack_base, size_t stack_size)
470{
471 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
472 return EINVAL;
473 }
474 if ((uint32_t)stack_base & (PAGE_SIZE - 1)) {
475 return EINVAL;
476 }
477 attr->stack_base = stack_base;
478 attr->stack_size = stack_size;
479 return 0;
480}
481
482int pthread_attr_getstack(pthread_attr_t const * attr, void ** stack_base, size_t * stack_size)
483{
484 *stack_base = attr->stack_base;
485 *stack_size = attr->stack_size;
486 return 0;
487}
488
489int pthread_attr_setguardsize(pthread_attr_t * attr, size_t guard_size)
490{
491 if (guard_size & (PAGE_SIZE - 1) || guard_size < PAGE_SIZE) {
492 return EINVAL;
493 }
494
495 attr->guard_size = guard_size;
496 return 0;
497}
498
499int pthread_attr_getguardsize(pthread_attr_t const * attr, size_t * guard_size)
500{
501 *guard_size = attr->guard_size;
502 return 0;
503}
504
505int pthread_getattr_np(pthread_t thid, pthread_attr_t * attr)
506{
507 pthread_internal_t * thread = (pthread_internal_t *)thid;
508 *attr = thread->attr;
509 return 0;
510}
511
512int pthread_attr_setscope(pthread_attr_t *attr __attribute__((unused)), int scope)
513{
514 if (scope == PTHREAD_SCOPE_SYSTEM)
515 return 0;
516 if (scope == PTHREAD_SCOPE_PROCESS)
517 return ENOTSUP;
518
519 return EINVAL;
520}
521
522int pthread_attr_getscope(pthread_attr_t const *attr __attribute__((unused)))
523{
524 return PTHREAD_SCOPE_SYSTEM;
525}
526
527
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800528/* CAVEAT: our implementation of pthread_cleanup_push/pop doesn't support C++ exceptions
529 * and thread cancelation
530 */
531
532void __pthread_cleanup_push( __pthread_cleanup_t* c,
533 __pthread_cleanup_func_t routine,
534 void* arg )
535{
536 pthread_internal_t* thread = __get_thread();
537
538 c->__cleanup_routine = routine;
539 c->__cleanup_arg = arg;
540 c->__cleanup_prev = thread->cleanup_stack;
541 thread->cleanup_stack = c;
542}
543
544void __pthread_cleanup_pop( __pthread_cleanup_t* c, int execute )
545{
546 pthread_internal_t* thread = __get_thread();
547
548 thread->cleanup_stack = c->__cleanup_prev;
549 if (execute)
550 c->__cleanup_routine(c->__cleanup_arg);
551}
552
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800553void pthread_exit(void * retval)
554{
555 pthread_internal_t* thread = __get_thread();
556 void* stack_base = thread->attr.stack_base;
557 int stack_size = thread->attr.stack_size;
558 int user_stack = (thread->attr.flags & PTHREAD_ATTR_FLAG_USER_STACK) != 0;
Jack Rene480fc82011-09-21 12:44:11 +0200559 sigset_t mask;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800560
561 // call the cleanup handlers first
562 while (thread->cleanup_stack) {
563 __pthread_cleanup_t* c = thread->cleanup_stack;
564 thread->cleanup_stack = c->__cleanup_prev;
565 c->__cleanup_routine(c->__cleanup_arg);
566 }
567
568 // call the TLS destructors, it is important to do that before removing this
569 // thread from the global list. this will ensure that if someone else deletes
570 // a TLS key, the corresponding value will be set to NULL in this thread's TLS
571 // space (see pthread_key_delete)
572 pthread_key_clean_all();
573
574 // if the thread is detached, destroy the pthread_internal_t
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400575 // otherwise, keep it in memory and signal any joiners.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800576 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
577 _pthread_internal_remove(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800578 } else {
Bjorn Andersson0753dc62012-05-03 17:12:39 -0700579 pthread_mutex_lock(&gThreadListLock);
580
581 /* make sure that the thread struct doesn't have stale pointers to a stack that
582 * will be unmapped after the exit call below.
583 */
584 if (!user_stack) {
585 thread->attr.stack_base = NULL;
586 thread->attr.stack_size = 0;
587 thread->tls = NULL;
588 }
589
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800590 /* the join_count field is used to store the number of threads waiting for
591 * the termination of this thread with pthread_join(),
592 *
593 * if it is positive we need to signal the waiters, and we do not touch
594 * the count (it will be decremented by the waiters, the last one will
595 * also remove/free the thread structure
596 *
597 * if it is zero, we set the count value to -1 to indicate that the
598 * thread is in 'zombie' state: it has stopped executing, and its stack
599 * is gone (as well as its TLS area). when another thread calls pthread_join()
600 * on it, it will immediately free the thread and return.
601 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800602 thread->return_value = retval;
603 if (thread->join_count > 0) {
604 pthread_cond_broadcast(&thread->join_cond);
605 } else {
606 thread->join_count = -1; /* zombie thread */
607 }
608 pthread_mutex_unlock(&gThreadListLock);
609 }
610
Jack Rene480fc82011-09-21 12:44:11 +0200611 sigfillset(&mask);
612 sigdelset(&mask, SIGSEGV);
613 (void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *)NULL);
614
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800615 // destroy the thread stack
616 if (user_stack)
617 _exit_thread((int)retval);
618 else
619 _exit_with_stack_teardown(stack_base, stack_size, (int)retval);
620}
621
622int pthread_join(pthread_t thid, void ** ret_val)
623{
624 pthread_internal_t* thread = (pthread_internal_t*)thid;
Elliott Hughes14f19592012-10-29 10:19:44 -0700625 if (thid == pthread_self()) {
626 return EDEADLK;
627 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800628
629 // check that the thread still exists and is not detached
630 pthread_mutex_lock(&gThreadListLock);
631
Elliott Hughes14f19592012-10-29 10:19:44 -0700632 for (thread = gThreadList; thread != NULL; thread = thread->next) {
633 if (thread == (pthread_internal_t*)thid) {
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200634 goto FoundIt;
Elliott Hughes14f19592012-10-29 10:19:44 -0700635 }
636 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800637
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200638 pthread_mutex_unlock(&gThreadListLock);
639 return ESRCH;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800640
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200641FoundIt:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800642 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
643 pthread_mutex_unlock(&gThreadListLock);
644 return EINVAL;
645 }
646
647 /* wait for thread death when needed
648 *
649 * if the 'join_count' is negative, this is a 'zombie' thread that
650 * is already dead and without stack/TLS
651 *
652 * otherwise, we need to increment 'join-count' and wait to be signaled
653 */
Elliott Hughes14f19592012-10-29 10:19:44 -0700654 int count = thread->join_count;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800655 if (count >= 0) {
656 thread->join_count += 1;
657 pthread_cond_wait( &thread->join_cond, &gThreadListLock );
658 count = --thread->join_count;
659 }
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400660 if (ret_val) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800661 *ret_val = thread->return_value;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400662 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800663
664 /* remove thread descriptor when we're the last joiner or when the
665 * thread was already a zombie.
666 */
667 if (count <= 0) {
668 _pthread_internal_remove_locked(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800669 }
670 pthread_mutex_unlock(&gThreadListLock);
671 return 0;
672}
673
674int pthread_detach( pthread_t thid )
675{
676 pthread_internal_t* thread;
677 int result = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800678
679 pthread_mutex_lock(&gThreadListLock);
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400680 for (thread = gThreadList; thread != NULL; thread = thread->next) {
681 if (thread == (pthread_internal_t*)thid) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800682 goto FoundIt;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400683 }
684 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800685
686 result = ESRCH;
687 goto Exit;
688
689FoundIt:
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400690 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
691 result = EINVAL; // Already detached.
692 goto Exit;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800693 }
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400694
695 if (thread->join_count > 0) {
696 result = 0; // Already being joined; silently do nothing, like glibc.
697 goto Exit;
698 }
699
700 thread->attr.flags |= PTHREAD_ATTR_FLAG_DETACHED;
701
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800702Exit:
703 pthread_mutex_unlock(&gThreadListLock);
704 return result;
705}
706
707pthread_t pthread_self(void)
708{
709 return (pthread_t)__get_thread();
710}
711
712int pthread_equal(pthread_t one, pthread_t two)
713{
714 return (one == two ? 1 : 0);
715}
716
717int pthread_getschedparam(pthread_t thid, int * policy,
718 struct sched_param * param)
719{
720 int old_errno = errno;
721
722 pthread_internal_t * thread = (pthread_internal_t *)thid;
723 int err = sched_getparam(thread->kernel_id, param);
724 if (!err) {
725 *policy = sched_getscheduler(thread->kernel_id);
726 } else {
727 err = errno;
728 errno = old_errno;
729 }
730 return err;
731}
732
733int pthread_setschedparam(pthread_t thid, int policy,
734 struct sched_param const * param)
735{
736 pthread_internal_t * thread = (pthread_internal_t *)thid;
737 int old_errno = errno;
738 int ret;
739
740 ret = sched_setscheduler(thread->kernel_id, policy, param);
741 if (ret < 0) {
742 ret = errno;
743 errno = old_errno;
744 }
745 return ret;
746}
747
748
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800749/* a mutex is implemented as a 32-bit integer holding the following fields
750 *
751 * bits: name description
752 * 31-16 tid owner thread's kernel id (recursive and errorcheck only)
753 * 15-14 type mutex type
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700754 * 13 shared process-shared flag
755 * 12-2 counter counter of recursive mutexes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800756 * 1-0 state lock state (0, 1 or 2)
757 */
758
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100759/* Convenience macro, creates a mask of 'bits' bits that starts from
760 * the 'shift'-th least significant bit in a 32-bit word.
761 *
762 * Examples: FIELD_MASK(0,4) -> 0xf
763 * FIELD_MASK(16,9) -> 0x1ff0000
764 */
765#define FIELD_MASK(shift,bits) (((1 << (bits))-1) << (shift))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800766
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100767/* This one is used to create a bit pattern from a given field value */
768#define FIELD_TO_BITS(val,shift,bits) (((val) & ((1 << (bits))-1)) << (shift))
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100769
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100770/* And this one does the opposite, i.e. extract a field's value from a bit pattern */
771#define FIELD_FROM_BITS(val,shift,bits) (((val) >> (shift)) & ((1 << (bits))-1))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800772
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100773/* Mutex state:
774 *
775 * 0 for unlocked
776 * 1 for locked, no waiters
777 * 2 for locked, maybe waiters
778 */
779#define MUTEX_STATE_SHIFT 0
780#define MUTEX_STATE_LEN 2
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800781
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100782#define MUTEX_STATE_MASK FIELD_MASK(MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
783#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
784#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
785
786#define MUTEX_STATE_UNLOCKED 0 /* must be 0 to match __PTHREAD_MUTEX_INIT_VALUE */
787#define MUTEX_STATE_LOCKED_UNCONTENDED 1 /* must be 1 due to atomic dec in unlock operation */
788#define MUTEX_STATE_LOCKED_CONTENDED 2 /* must be 1 + LOCKED_UNCONTENDED due to atomic dec */
789
790#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
791#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
792
793#define MUTEX_STATE_BITS_UNLOCKED MUTEX_STATE_TO_BITS(MUTEX_STATE_UNLOCKED)
794#define MUTEX_STATE_BITS_LOCKED_UNCONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_UNCONTENDED)
795#define MUTEX_STATE_BITS_LOCKED_CONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_CONTENDED)
796
797/* return true iff the mutex if locked with no waiters */
798#define MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_UNCONTENDED)
799
800/* return true iff the mutex if locked with maybe waiters */
801#define MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_CONTENDED)
802
803/* used to flip from LOCKED_UNCONTENDED to LOCKED_CONTENDED */
804#define MUTEX_STATE_BITS_FLIP_CONTENTION(v) ((v) ^ (MUTEX_STATE_BITS_LOCKED_CONTENDED ^ MUTEX_STATE_BITS_LOCKED_UNCONTENDED))
805
806/* Mutex counter:
807 *
808 * We need to check for overflow before incrementing, and we also need to
809 * detect when the counter is 0
810 */
811#define MUTEX_COUNTER_SHIFT 2
812#define MUTEX_COUNTER_LEN 11
813#define MUTEX_COUNTER_MASK FIELD_MASK(MUTEX_COUNTER_SHIFT, MUTEX_COUNTER_LEN)
814
815#define MUTEX_COUNTER_BITS_WILL_OVERFLOW(v) (((v) & MUTEX_COUNTER_MASK) == MUTEX_COUNTER_MASK)
816#define MUTEX_COUNTER_BITS_IS_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
817
818/* Used to increment the counter directly after overflow has been checked */
819#define MUTEX_COUNTER_BITS_ONE FIELD_TO_BITS(1,MUTEX_COUNTER_SHIFT,MUTEX_COUNTER_LEN)
820
821/* Returns true iff the counter is 0 */
822#define MUTEX_COUNTER_BITS_ARE_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
823
824/* Mutex shared bit flag
825 *
826 * This flag is set to indicate that the mutex is shared among processes.
827 * This changes the futex opcode we use for futex wait/wake operations
828 * (non-shared operations are much faster).
829 */
830#define MUTEX_SHARED_SHIFT 13
831#define MUTEX_SHARED_MASK FIELD_MASK(MUTEX_SHARED_SHIFT,1)
832
833/* Mutex type:
834 *
835 * We support normal, recursive and errorcheck mutexes.
836 *
837 * The constants defined here *cannot* be changed because they must match
838 * the C library ABI which defines the following initialization values in
839 * <pthread.h>:
840 *
841 * __PTHREAD_MUTEX_INIT_VALUE
842 * __PTHREAD_RECURSIVE_MUTEX_VALUE
843 * __PTHREAD_ERRORCHECK_MUTEX_INIT_VALUE
844 */
845#define MUTEX_TYPE_SHIFT 14
846#define MUTEX_TYPE_LEN 2
847#define MUTEX_TYPE_MASK FIELD_MASK(MUTEX_TYPE_SHIFT,MUTEX_TYPE_LEN)
848
849#define MUTEX_TYPE_NORMAL 0 /* Must be 0 to match __PTHREAD_MUTEX_INIT_VALUE */
850#define MUTEX_TYPE_RECURSIVE 1
851#define MUTEX_TYPE_ERRORCHECK 2
852
853#define MUTEX_TYPE_TO_BITS(t) FIELD_TO_BITS(t, MUTEX_TYPE_SHIFT, MUTEX_TYPE_LEN)
854
855#define MUTEX_TYPE_BITS_NORMAL MUTEX_TYPE_TO_BITS(MUTEX_TYPE_NORMAL)
856#define MUTEX_TYPE_BITS_RECURSIVE MUTEX_TYPE_TO_BITS(MUTEX_TYPE_RECURSIVE)
857#define MUTEX_TYPE_BITS_ERRORCHECK MUTEX_TYPE_TO_BITS(MUTEX_TYPE_ERRORCHECK)
858
859/* Mutex owner field:
860 *
861 * This is only used for recursive and errorcheck mutexes. It holds the
862 * kernel TID of the owning thread. Note that this works because the Linux
863 * kernel _only_ uses 16-bit values for thread ids.
864 *
865 * More specifically, it will wrap to 10000 when it reaches over 32768 for
866 * application processes. You can check this by running the following inside
867 * an adb shell session:
868 *
869 OLDPID=$$;
870 while true; do
871 NEWPID=$(sh -c 'echo $$')
872 if [ "$NEWPID" -gt 32768 ]; then
873 echo "AARGH: new PID $NEWPID is too high!"
874 exit 1
875 fi
876 if [ "$NEWPID" -lt "$OLDPID" ]; then
877 echo "****** Wrapping from PID $OLDPID to $NEWPID. *******"
878 else
879 echo -n "$NEWPID!"
880 fi
881 OLDPID=$NEWPID
882 done
883
884 * Note that you can run the same example on a desktop Linux system,
885 * the wrapping will also happen at 32768, but will go back to 300 instead.
886 */
887#define MUTEX_OWNER_SHIFT 16
888#define MUTEX_OWNER_LEN 16
889
890#define MUTEX_OWNER_FROM_BITS(v) FIELD_FROM_BITS(v,MUTEX_OWNER_SHIFT,MUTEX_OWNER_LEN)
891#define MUTEX_OWNER_TO_BITS(v) FIELD_TO_BITS(v,MUTEX_OWNER_SHIFT,MUTEX_OWNER_LEN)
892
893/* Convenience macros.
894 *
895 * These are used to form or modify the bit pattern of a given mutex value
896 */
897
898
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800899
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700900/* a mutex attribute holds the following fields
901 *
902 * bits: name description
903 * 0-3 type type of mutex
904 * 4 shared process-shared flag
905 */
906#define MUTEXATTR_TYPE_MASK 0x000f
907#define MUTEXATTR_SHARED_MASK 0x0010
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800908
909
910int pthread_mutexattr_init(pthread_mutexattr_t *attr)
911{
912 if (attr) {
913 *attr = PTHREAD_MUTEX_DEFAULT;
914 return 0;
915 } else {
916 return EINVAL;
917 }
918}
919
920int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
921{
922 if (attr) {
923 *attr = -1;
924 return 0;
925 } else {
926 return EINVAL;
927 }
928}
929
930int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
931{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700932 if (attr) {
933 int atype = (*attr & MUTEXATTR_TYPE_MASK);
934
935 if (atype >= PTHREAD_MUTEX_NORMAL &&
936 atype <= PTHREAD_MUTEX_ERRORCHECK) {
937 *type = atype;
938 return 0;
939 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800940 }
941 return EINVAL;
942}
943
944int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
945{
946 if (attr && type >= PTHREAD_MUTEX_NORMAL &&
947 type <= PTHREAD_MUTEX_ERRORCHECK ) {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700948 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800949 return 0;
950 }
951 return EINVAL;
952}
953
954/* process-shared mutexes are not supported at the moment */
955
956int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
957{
958 if (!attr)
959 return EINVAL;
960
Mathias Agopianb7681162009-07-13 22:00:33 -0700961 switch (pshared) {
962 case PTHREAD_PROCESS_PRIVATE:
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700963 *attr &= ~MUTEXATTR_SHARED_MASK;
964 return 0;
965
Mathias Agopianb7681162009-07-13 22:00:33 -0700966 case PTHREAD_PROCESS_SHARED:
967 /* our current implementation of pthread actually supports shared
968 * mutexes but won't cleanup if a process dies with the mutex held.
969 * Nevertheless, it's better than nothing. Shared mutexes are used
970 * by surfaceflinger and audioflinger.
971 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700972 *attr |= MUTEXATTR_SHARED_MASK;
Mathias Agopianb7681162009-07-13 22:00:33 -0700973 return 0;
974 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700975 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800976}
977
978int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
979{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700980 if (!attr || !pshared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800981 return EINVAL;
982
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700983 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED
984 : PTHREAD_PROCESS_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800985 return 0;
986}
987
988int pthread_mutex_init(pthread_mutex_t *mutex,
989 const pthread_mutexattr_t *attr)
990{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700991 int value = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800992
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700993 if (mutex == NULL)
994 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800995
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700996 if (__likely(attr == NULL)) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100997 mutex->value = MUTEX_TYPE_BITS_NORMAL;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700998 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800999 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001000
1001 if ((*attr & MUTEXATTR_SHARED_MASK) != 0)
1002 value |= MUTEX_SHARED_MASK;
1003
1004 switch (*attr & MUTEXATTR_TYPE_MASK) {
1005 case PTHREAD_MUTEX_NORMAL:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001006 value |= MUTEX_TYPE_BITS_NORMAL;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001007 break;
1008 case PTHREAD_MUTEX_RECURSIVE:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001009 value |= MUTEX_TYPE_BITS_RECURSIVE;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001010 break;
1011 case PTHREAD_MUTEX_ERRORCHECK:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001012 value |= MUTEX_TYPE_BITS_ERRORCHECK;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001013 break;
1014 default:
1015 return EINVAL;
1016 }
1017
1018 mutex->value = value;
1019 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001020}
1021
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001022
1023/*
1024 * Lock a non-recursive mutex.
1025 *
1026 * As noted above, there are three states:
1027 * 0 (unlocked, no contention)
1028 * 1 (locked, no contention)
1029 * 2 (locked, contention)
1030 *
1031 * Non-recursive mutexes don't use the thread-id or counter fields, and the
1032 * "type" value is zero, so the only bits that will be set are the ones in
1033 * the lock state field.
1034 */
1035static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001036_normal_lock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001037{
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001038 /* convenience shortcuts */
1039 const int unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
1040 const int locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001041 /*
1042 * The common case is an unlocked mutex, so we begin by trying to
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001043 * change the lock's state from 0 (UNLOCKED) to 1 (LOCKED).
1044 * __bionic_cmpxchg() returns 0 if it made the swap successfully.
1045 * If the result is nonzero, this lock is already held by another thread.
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001046 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001047 if (__bionic_cmpxchg(unlocked, locked_uncontended, &mutex->value) != 0) {
1048 const int locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001049 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001050 * We want to go to sleep until the mutex is available, which
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001051 * requires promoting it to state 2 (CONTENDED). We need to
1052 * swap in the new state value and then wait until somebody wakes us up.
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001053 *
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001054 * __bionic_swap() returns the previous value. We swap 2 in and
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001055 * see if we got zero back; if so, we have acquired the lock. If
1056 * not, another thread still holds the lock and we wait again.
1057 *
1058 * The second argument to the __futex_wait() call is compared
1059 * against the current value. If it doesn't match, __futex_wait()
1060 * returns immediately (otherwise, it sleeps for a time specified
1061 * by the third argument; 0 means sleep forever). This ensures
1062 * that the mutex is in state 2 when we go to sleep on it, which
1063 * guarantees a wake-up call.
1064 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001065 while (__bionic_swap(locked_contended, &mutex->value) != unlocked)
1066 __futex_wait_ex(&mutex->value, shared, locked_contended, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001067 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001068 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001069}
1070
1071/*
1072 * Release a non-recursive mutex. The caller is responsible for determining
1073 * that we are in fact the owner of this lock.
1074 */
1075static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001076_normal_unlock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001077{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001078 ANDROID_MEMBAR_FULL();
1079
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001080 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001081 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001082 * to release the lock. __bionic_atomic_dec() returns the previous value;
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001083 * if it wasn't 1 we have to do some additional work.
1084 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001085 if (__bionic_atomic_dec(&mutex->value) != (shared|MUTEX_STATE_BITS_LOCKED_UNCONTENDED)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001086 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001087 * Start by releasing the lock. The decrement changed it from
1088 * "contended lock" to "uncontended lock", which means we still
1089 * hold it, and anybody who tries to sneak in will push it back
1090 * to state 2.
1091 *
1092 * Once we set it to zero the lock is up for grabs. We follow
1093 * this with a __futex_wake() to ensure that one of the waiting
1094 * threads has a chance to grab it.
1095 *
1096 * This doesn't cause a race with the swap/wait pair in
1097 * _normal_lock(), because the __futex_wait() call there will
1098 * return immediately if the mutex value isn't 2.
1099 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001100 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001101
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001102 /*
1103 * Wake up one waiting thread. We don't know which thread will be
1104 * woken or when it'll start executing -- futexes make no guarantees
1105 * here. There may not even be a thread waiting.
1106 *
1107 * The newly-woken thread will replace the 0 we just set above
1108 * with 2, which means that when it eventually releases the mutex
1109 * it will also call FUTEX_WAKE. This results in one extra wake
1110 * call whenever a lock is contended, but lets us avoid forgetting
1111 * anyone without requiring us to track the number of sleepers.
1112 *
1113 * It's possible for another thread to sneak in and grab the lock
1114 * between the zero assignment above and the wake call below. If
1115 * the new thread is "slow" and holds the lock for a while, we'll
1116 * wake up a sleeper, which will swap in a 2 and then go back to
1117 * sleep since the lock is still held. If the new thread is "fast",
1118 * running to completion before we call wake, the thread we
1119 * eventually wake will find an unlocked mutex and will execute.
1120 * Either way we have correct behavior and nobody is orphaned on
1121 * the wait queue.
1122 */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001123 __futex_wake_ex(&mutex->value, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001124 }
1125}
1126
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001127/* This common inlined function is used to increment the counter of an
1128 * errorcheck or recursive mutex.
1129 *
1130 * For errorcheck mutexes, it will return EDEADLK
1131 * If the counter overflows, it will return EAGAIN
1132 * Otherwise, it atomically increments the counter and returns 0
1133 * after providing an acquire barrier.
1134 *
1135 * mtype is the current mutex type
1136 * mvalue is the current mutex value (already loaded)
1137 * mutex pointers to the mutex.
1138 */
1139static __inline__ __attribute__((always_inline)) int
1140_recursive_increment(pthread_mutex_t* mutex, int mvalue, int mtype)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001141{
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001142 if (mtype == MUTEX_TYPE_BITS_ERRORCHECK) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001143 /* trying to re-lock a mutex we already acquired */
1144 return EDEADLK;
1145 }
1146
1147 /* Detect recursive lock overflow and return EAGAIN.
1148 * This is safe because only the owner thread can modify the
David 'Digit' Turnerb57db752012-01-24 13:20:38 +01001149 * counter bits in the mutex value.
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001150 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001151 if (MUTEX_COUNTER_BITS_WILL_OVERFLOW(mvalue)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001152 return EAGAIN;
1153 }
1154
1155 /* We own the mutex, but other threads are able to change
David 'Digit' Turnerb57db752012-01-24 13:20:38 +01001156 * the lower bits (e.g. promoting it to "contended"), so we
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001157 * need to use an atomic cmpxchg loop to update the counter.
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001158 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001159 for (;;) {
1160 /* increment counter, overflow was already checked */
1161 int newval = mvalue + MUTEX_COUNTER_BITS_ONE;
1162 if (__likely(__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0)) {
1163 /* mutex is still locked, not need for a memory barrier */
1164 return 0;
1165 }
1166 /* the value was changed, this happens when another thread changes
1167 * the lower state bits from 1 to 2 to indicate contention. This
1168 * cannot change the counter, so simply reload and try again.
1169 */
1170 mvalue = mutex->value;
1171 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001172}
1173
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001174__LIBC_HIDDEN__
1175int pthread_mutex_lock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001176{
Wink Savillea12c5442013-01-08 15:15:45 -08001177 int mvalue, mtype, tid, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001178
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001179 if (__unlikely(mutex == NULL))
1180 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001181
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001182 mvalue = mutex->value;
1183 mtype = (mvalue & MUTEX_TYPE_MASK);
1184 shared = (mvalue & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001185
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001186 /* Handle normal case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001187 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) ) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001188 _normal_lock(mutex, shared);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001189 return 0;
1190 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001191
1192 /* Do we already own this recursive or error-check mutex ? */
1193 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001194 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001195 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001196
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001197 /* Add in shared state to avoid extra 'or' operations below */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001198 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001199
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001200 /* First, if the mutex is unlocked, try to quickly acquire it.
1201 * In the optimistic case where this works, set the state to 1 to
1202 * indicate locked with no contention */
1203 if (mvalue == mtype) {
1204 int newval = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1205 if (__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0) {
1206 ANDROID_MEMBAR_FULL();
1207 return 0;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001208 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001209 /* argh, the value changed, reload before entering the loop */
1210 mvalue = mutex->value;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001211 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001212
1213 for (;;) {
1214 int newval;
1215
1216 /* if the mutex is unlocked, its value should be 'mtype' and
1217 * we try to acquire it by setting its owner and state atomically.
1218 * NOTE: We put the state to 2 since we _know_ there is contention
1219 * when we are in this loop. This ensures all waiters will be
1220 * unlocked.
1221 */
1222 if (mvalue == mtype) {
1223 newval = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1224 /* TODO: Change this to __bionic_cmpxchg_acquire when we
1225 * implement it to get rid of the explicit memory
1226 * barrier below.
1227 */
1228 if (__unlikely(__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0)) {
1229 mvalue = mutex->value;
1230 continue;
1231 }
1232 ANDROID_MEMBAR_FULL();
1233 return 0;
1234 }
1235
1236 /* the mutex is already locked by another thread, if its state is 1
1237 * we will change it to 2 to indicate contention. */
1238 if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(mvalue)) {
1239 newval = MUTEX_STATE_BITS_FLIP_CONTENTION(mvalue); /* locked state 1 => state 2 */
1240 if (__unlikely(__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0)) {
1241 mvalue = mutex->value;
1242 continue;
1243 }
1244 mvalue = newval;
1245 }
1246
1247 /* wait until the mutex is unlocked */
1248 __futex_wait_ex(&mutex->value, shared, mvalue, NULL);
1249
1250 mvalue = mutex->value;
1251 }
1252 /* NOTREACHED */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001253}
1254
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001255int pthread_mutex_lock(pthread_mutex_t *mutex)
1256{
1257 int err = pthread_mutex_lock_impl(mutex);
1258#ifdef PTHREAD_DEBUG
1259 if (PTHREAD_DEBUG_ENABLED) {
1260 if (!err) {
1261 pthread_debug_mutex_lock_check(mutex);
1262 }
1263 }
1264#endif
1265 return err;
1266}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001267
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001268__LIBC_HIDDEN__
1269int pthread_mutex_unlock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001270{
Wink Savillea12c5442013-01-08 15:15:45 -08001271 int mvalue, mtype, tid, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001272
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001273 if (__unlikely(mutex == NULL))
1274 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001275
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001276 mvalue = mutex->value;
1277 mtype = (mvalue & MUTEX_TYPE_MASK);
1278 shared = (mvalue & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001279
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001280 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001281 if (__likely(mtype == MUTEX_TYPE_BITS_NORMAL)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001282 _normal_unlock(mutex, shared);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001283 return 0;
1284 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001285
1286 /* Do we already own this recursive or error-check mutex ? */
1287 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001288 if ( tid != MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001289 return EPERM;
1290
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001291 /* If the counter is > 0, we can simply decrement it atomically.
1292 * Since other threads can mutate the lower state bits (and only the
1293 * lower state bits), use a cmpxchg to do it.
1294 */
1295 if (!MUTEX_COUNTER_BITS_IS_ZERO(mvalue)) {
1296 for (;;) {
1297 int newval = mvalue - MUTEX_COUNTER_BITS_ONE;
1298 if (__likely(__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0)) {
1299 /* success: we still own the mutex, so no memory barrier */
1300 return 0;
1301 }
1302 /* the value changed, so reload and loop */
1303 mvalue = mutex->value;
1304 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001305 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001306
1307 /* the counter is 0, so we're going to unlock the mutex by resetting
1308 * its value to 'unlocked'. We need to perform a swap in order
1309 * to read the current state, which will be 2 if there are waiters
1310 * to awake.
1311 *
1312 * TODO: Change this to __bionic_swap_release when we implement it
1313 * to get rid of the explicit memory barrier below.
1314 */
1315 ANDROID_MEMBAR_FULL(); /* RELEASE BARRIER */
1316 mvalue = __bionic_swap(mtype | shared | MUTEX_STATE_BITS_UNLOCKED, &mutex->value);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001317
1318 /* Wake one waiting thread, if any */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001319 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(mvalue)) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001320 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001321 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001322 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001323}
1324
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001325int pthread_mutex_unlock(pthread_mutex_t *mutex)
1326{
1327#ifdef PTHREAD_DEBUG
1328 if (PTHREAD_DEBUG_ENABLED) {
1329 pthread_debug_mutex_unlock_check(mutex);
1330 }
1331#endif
1332 return pthread_mutex_unlock_impl(mutex);
1333}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001334
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001335__LIBC_HIDDEN__
1336int pthread_mutex_trylock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001337{
Wink Savillea12c5442013-01-08 15:15:45 -08001338 int mvalue, mtype, tid, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001339
1340 if (__unlikely(mutex == NULL))
1341 return EINVAL;
1342
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001343 mvalue = mutex->value;
1344 mtype = (mvalue & MUTEX_TYPE_MASK);
1345 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001346
1347 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001348 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001349 {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001350 if (__bionic_cmpxchg(shared|MUTEX_STATE_BITS_UNLOCKED,
1351 shared|MUTEX_STATE_BITS_LOCKED_UNCONTENDED,
1352 &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001353 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001354 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001355 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001356
1357 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001358 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001359
1360 /* Do we already own this recursive or error-check mutex ? */
1361 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001362 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001363 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001364
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001365 /* Same as pthread_mutex_lock, except that we don't want to wait, and
1366 * the only operation that can succeed is a single cmpxchg to acquire the
1367 * lock if it is released / not owned by anyone. No need for a complex loop.
1368 */
1369 mtype |= shared | MUTEX_STATE_BITS_UNLOCKED;
1370 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001371
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001372 if (__likely(__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0)) {
1373 ANDROID_MEMBAR_FULL();
1374 return 0;
1375 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001376
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001377 return EBUSY;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001378}
1379
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001380int pthread_mutex_trylock(pthread_mutex_t *mutex)
1381{
1382 int err = pthread_mutex_trylock_impl(mutex);
1383#ifdef PTHREAD_DEBUG
1384 if (PTHREAD_DEBUG_ENABLED) {
1385 if (!err) {
1386 pthread_debug_mutex_lock_check(mutex);
1387 }
1388 }
1389#endif
1390 return err;
1391}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001392
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001393/* initialize 'ts' with the difference between 'abstime' and the current time
1394 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
1395 */
1396static int
1397__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
1398{
1399 clock_gettime(clock, ts);
1400 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
1401 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
1402 if (ts->tv_nsec < 0) {
1403 ts->tv_sec--;
1404 ts->tv_nsec += 1000000000;
1405 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001406 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001407 return -1;
1408
1409 return 0;
1410}
1411
1412/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1413 * milliseconds.
1414 */
1415static void
1416__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1417{
1418 clock_gettime(clock, abstime);
1419 abstime->tv_sec += msecs/1000;
1420 abstime->tv_nsec += (msecs%1000)*1000000;
1421 if (abstime->tv_nsec >= 1000000000) {
1422 abstime->tv_sec++;
1423 abstime->tv_nsec -= 1000000000;
1424 }
1425}
1426
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001427__LIBC_HIDDEN__
1428int pthread_mutex_lock_timeout_np_impl(pthread_mutex_t *mutex, unsigned msecs)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001429{
1430 clockid_t clock = CLOCK_MONOTONIC;
1431 struct timespec abstime;
1432 struct timespec ts;
Wink Savillea12c5442013-01-08 15:15:45 -08001433 int mvalue, mtype, tid, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001434
1435 /* compute absolute expiration time */
1436 __timespec_to_relative_msec(&abstime, msecs, clock);
1437
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001438 if (__unlikely(mutex == NULL))
1439 return EINVAL;
1440
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001441 mvalue = mutex->value;
1442 mtype = (mvalue & MUTEX_TYPE_MASK);
1443 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001444
1445 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001446 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001447 {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001448 const int unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
1449 const int locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1450 const int locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1451
1452 /* fast path for uncontended lock. Note: MUTEX_TYPE_BITS_NORMAL is 0 */
1453 if (__bionic_cmpxchg(unlocked, locked_uncontended, &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001454 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001455 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001456 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001457
1458 /* loop while needed */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001459 while (__bionic_swap(locked_contended, &mutex->value) != unlocked) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001460 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1461 return EBUSY;
1462
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001463 __futex_wait_ex(&mutex->value, shared, locked_contended, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001464 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001465 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001466 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001467 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001468
1469 /* Do we already own this recursive or error-check mutex ? */
1470 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001471 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001472 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001473
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001474 /* the following implements the same loop than pthread_mutex_lock_impl
1475 * but adds checks to ensure that the operation never exceeds the
1476 * absolute expiration time.
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001477 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001478 mtype |= shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001479
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001480 /* first try a quick lock */
1481 if (mvalue == mtype) {
1482 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1483 if (__likely(__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0)) {
1484 ANDROID_MEMBAR_FULL();
1485 return 0;
1486 }
1487 mvalue = mutex->value;
1488 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001489
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001490 for (;;) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001491 struct timespec ts;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001492
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001493 /* if the value is 'unlocked', try to acquire it directly */
1494 /* NOTE: put state to 2 since we know there is contention */
1495 if (mvalue == mtype) /* unlocked */ {
1496 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1497 if (__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0) {
1498 ANDROID_MEMBAR_FULL();
1499 return 0;
1500 }
1501 /* the value changed before we could lock it. We need to check
1502 * the time to avoid livelocks, reload the value, then loop again. */
1503 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1504 return EBUSY;
1505
1506 mvalue = mutex->value;
1507 continue;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001508 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001509
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001510 /* The value is locked. If 'uncontended', try to switch its state
1511 * to 'contented' to ensure we get woken up later. */
1512 if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(mvalue)) {
1513 int newval = MUTEX_STATE_BITS_FLIP_CONTENTION(mvalue);
1514 if (__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0) {
1515 /* this failed because the value changed, reload it */
1516 mvalue = mutex->value;
1517 } else {
1518 /* this succeeded, update mvalue */
1519 mvalue = newval;
1520 }
1521 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001522
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001523 /* check time and update 'ts' */
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001524 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1525 return EBUSY;
1526
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001527 /* Only wait to be woken up if the state is '2', otherwise we'll
1528 * simply loop right now. This can happen when the second cmpxchg
1529 * in our loop failed because the mutex was unlocked by another
1530 * thread.
1531 */
1532 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(mvalue)) {
1533 if (__futex_wait_ex(&mutex->value, shared, mvalue, &ts) == ETIMEDOUT) {
1534 return EBUSY;
1535 }
1536 mvalue = mutex->value;
1537 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001538 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001539 /* NOTREACHED */
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001540}
1541
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001542int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1543{
1544 int err = pthread_mutex_lock_timeout_np_impl(mutex, msecs);
1545#ifdef PTHREAD_DEBUG
1546 if (PTHREAD_DEBUG_ENABLED) {
1547 if (!err) {
1548 pthread_debug_mutex_lock_check(mutex);
1549 }
1550 }
1551#endif
1552 return err;
1553}
1554
1555int pthread_mutex_destroy(pthread_mutex_t *mutex)
1556{
1557 int ret;
1558
1559 /* use trylock to ensure that the mutex value is
1560 * valid and is not already locked. */
1561 ret = pthread_mutex_trylock_impl(mutex);
1562 if (ret != 0)
1563 return ret;
1564
1565 mutex->value = 0xdead10cc;
1566 return 0;
1567}
1568
1569
1570
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001571int pthread_condattr_init(pthread_condattr_t *attr)
1572{
1573 if (attr == NULL)
1574 return EINVAL;
1575
1576 *attr = PTHREAD_PROCESS_PRIVATE;
1577 return 0;
1578}
1579
1580int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1581{
1582 if (attr == NULL || pshared == NULL)
1583 return EINVAL;
1584
1585 *pshared = *attr;
1586 return 0;
1587}
1588
1589int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1590{
1591 if (attr == NULL)
1592 return EINVAL;
1593
1594 if (pshared != PTHREAD_PROCESS_SHARED &&
1595 pshared != PTHREAD_PROCESS_PRIVATE)
1596 return EINVAL;
1597
1598 *attr = pshared;
1599 return 0;
1600}
1601
1602int pthread_condattr_destroy(pthread_condattr_t *attr)
1603{
1604 if (attr == NULL)
1605 return EINVAL;
1606
1607 *attr = 0xdeada11d;
1608 return 0;
1609}
1610
1611/* We use one bit in condition variable values as the 'shared' flag
1612 * The rest is a counter.
1613 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001614#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001615#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001616#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1617
1618#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001619
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001620/* XXX *technically* there is a race condition that could allow
1621 * XXX a signal to be missed. If thread A is preempted in _wait()
1622 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001623 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001624 * XXX before thread A is scheduled again and calls futex_wait(),
1625 * XXX then the signal will be lost.
1626 */
1627
1628int pthread_cond_init(pthread_cond_t *cond,
1629 const pthread_condattr_t *attr)
1630{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001631 if (cond == NULL)
1632 return EINVAL;
1633
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001634 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001635
1636 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001637 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001638
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001639 return 0;
1640}
1641
1642int pthread_cond_destroy(pthread_cond_t *cond)
1643{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001644 if (cond == NULL)
1645 return EINVAL;
1646
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001647 cond->value = 0xdeadc04d;
1648 return 0;
1649}
1650
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001651/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001652 * pthread_cond_signal to atomically decrement the counter
1653 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001654 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001655static int
1656__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001657{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001658 long flags;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001659
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001660 if (__unlikely(cond == NULL))
1661 return EINVAL;
1662
1663 flags = (cond->value & ~COND_COUNTER_MASK);
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001664 for (;;) {
1665 long oldval = cond->value;
1666 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1667 | flags;
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001668 if (__bionic_cmpxchg(oldval, newval, &cond->value) == 0)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001669 break;
1670 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001671
Andy McFaddene2ac8982010-09-02 13:34:53 -07001672 /*
1673 * Ensure that all memory accesses previously made by this thread are
1674 * visible to the woken thread(s). On the other side, the "wait"
1675 * code will issue any necessary barriers when locking the mutex.
1676 *
1677 * This may not strictly be necessary -- if the caller follows
1678 * recommended practice and holds the mutex before signaling the cond
1679 * var, the mutex ops will provide correct semantics. If they don't
1680 * hold the mutex, they're subject to race conditions anyway.
1681 */
1682 ANDROID_MEMBAR_FULL();
1683
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001684 __futex_wake_ex(&cond->value, COND_IS_SHARED(cond), counter);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001685 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001686}
1687
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001688int pthread_cond_broadcast(pthread_cond_t *cond)
1689{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001690 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001691}
1692
1693int pthread_cond_signal(pthread_cond_t *cond)
1694{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001695 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001696}
1697
1698int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1699{
1700 return pthread_cond_timedwait(cond, mutex, NULL);
1701}
1702
1703int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1704 pthread_mutex_t * mutex,
1705 const struct timespec *reltime)
1706{
1707 int status;
1708 int oldvalue = cond->value;
1709
1710 pthread_mutex_unlock(mutex);
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001711 status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond), oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001712 pthread_mutex_lock(mutex);
1713
1714 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1715 return 0;
1716}
1717
1718int __pthread_cond_timedwait(pthread_cond_t *cond,
1719 pthread_mutex_t * mutex,
1720 const struct timespec *abstime,
1721 clockid_t clock)
1722{
1723 struct timespec ts;
1724 struct timespec * tsp;
1725
1726 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001727 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001728 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001729 tsp = &ts;
1730 } else {
1731 tsp = NULL;
1732 }
1733
1734 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1735}
1736
1737int pthread_cond_timedwait(pthread_cond_t *cond,
1738 pthread_mutex_t * mutex,
1739 const struct timespec *abstime)
1740{
1741 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1742}
1743
1744
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001745/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001746int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1747 pthread_mutex_t * mutex,
1748 const struct timespec *abstime)
1749{
1750 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1751}
1752
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001753int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1754 pthread_mutex_t * mutex,
1755 const struct timespec *abstime)
1756{
1757 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1758}
1759
1760int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1761 pthread_mutex_t * mutex,
1762 const struct timespec *reltime)
1763{
1764 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1765}
1766
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001767int pthread_cond_timeout_np(pthread_cond_t *cond,
1768 pthread_mutex_t * mutex,
1769 unsigned msecs)
1770{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001771 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001772
1773 ts.tv_sec = msecs / 1000;
1774 ts.tv_nsec = (msecs % 1000) * 1000000;
1775
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001776 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001777}
1778
1779
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001780// man says this should be in <linux/unistd.h>, but it isn't
Jeff Brown10c8ce52011-11-18 15:17:07 -08001781extern int tgkill(int tgid, int tid, int sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001782
1783int pthread_kill(pthread_t tid, int sig)
1784{
1785 int ret;
1786 int old_errno = errno;
1787 pthread_internal_t * thread = (pthread_internal_t *)tid;
1788
Jeff Brown10c8ce52011-11-18 15:17:07 -08001789 ret = tgkill(getpid(), thread->kernel_id, sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001790 if (ret < 0) {
1791 ret = errno;
1792 errno = old_errno;
1793 }
1794
1795 return ret;
1796}
1797
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001798
1799int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
1800{
1801 const int CLOCK_IDTYPE_BITS = 3;
1802 pthread_internal_t* thread = (pthread_internal_t*)tid;
1803
1804 if (!thread)
1805 return ESRCH;
1806
1807 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
1808 return 0;
1809}
1810
1811
1812/* NOTE: this implementation doesn't support a init function that throws a C++ exception
1813 * or calls fork()
1814 */
1815int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
1816{
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001817 volatile pthread_once_t* ocptr = once_control;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001818
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001819 /* PTHREAD_ONCE_INIT is 0, we use the following bit flags
1820 *
1821 * bit 0 set -> initialization is under way
1822 * bit 1 set -> initialization is complete
1823 */
1824#define ONCE_INITIALIZING (1 << 0)
1825#define ONCE_COMPLETED (1 << 1)
1826
1827 /* First check if the once is already initialized. This will be the common
1828 * case and we want to make this as fast as possible. Note that this still
1829 * requires a load_acquire operation here to ensure that all the
1830 * stores performed by the initialization function are observable on
1831 * this CPU after we exit.
1832 */
1833 if (__likely((*ocptr & ONCE_COMPLETED) != 0)) {
1834 ANDROID_MEMBAR_FULL();
1835 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001836 }
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001837
1838 for (;;) {
1839 /* Try to atomically set the INITIALIZING flag.
1840 * This requires a cmpxchg loop, and we may need
Elliott Hughesbfeab1b2012-09-05 17:47:37 -07001841 * to exit prematurely if we detect that
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001842 * COMPLETED is now set.
1843 */
1844 int32_t oldval, newval;
1845
1846 do {
1847 oldval = *ocptr;
1848 if ((oldval & ONCE_COMPLETED) != 0)
1849 break;
1850
1851 newval = oldval | ONCE_INITIALIZING;
1852 } while (__bionic_cmpxchg(oldval, newval, ocptr) != 0);
1853
1854 if ((oldval & ONCE_COMPLETED) != 0) {
1855 /* We detected that COMPLETED was set while in our loop */
1856 ANDROID_MEMBAR_FULL();
1857 return 0;
1858 }
1859
1860 if ((oldval & ONCE_INITIALIZING) == 0) {
1861 /* We got there first, we can jump out of the loop to
1862 * handle the initialization */
1863 break;
1864 }
1865
1866 /* Another thread is running the initialization and hasn't completed
1867 * yet, so wait for it, then try again. */
1868 __futex_wait_ex(ocptr, 0, oldval, NULL);
1869 }
1870
1871 /* call the initialization function. */
1872 (*init_routine)();
1873
1874 /* Do a store_release indicating that initialization is complete */
1875 ANDROID_MEMBAR_FULL();
1876 *ocptr = ONCE_COMPLETED;
1877
1878 /* Wake up any waiters, if any */
1879 __futex_wake_ex(ocptr, 0, INT_MAX);
1880
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001881 return 0;
1882}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03001883
Elliott Hughes6f94de32013-02-12 06:06:22 +00001884/* This value is not exported by kernel headers, so hardcode it here */
1885#define MAX_TASK_COMM_LEN 16
1886#define TASK_COMM_FMT "/proc/self/task/%u/comm"
1887
1888int pthread_setname_np(pthread_t thid, const char *thname)
1889{
1890 size_t thname_len;
1891 int saved_errno, ret;
1892
1893 if (thid == 0 || thname == NULL)
1894 return EINVAL;
1895
1896 thname_len = strlen(thname);
1897 if (thname_len >= MAX_TASK_COMM_LEN)
1898 return ERANGE;
1899
1900 saved_errno = errno;
1901 if (thid == pthread_self())
1902 {
1903 ret = prctl(PR_SET_NAME, (unsigned long)thname, 0, 0, 0) ? errno : 0;
1904 }
1905 else
1906 {
1907 /* Have to change another thread's name */
1908 pthread_internal_t *thread = (pthread_internal_t *)thid;
1909 char comm_name[sizeof(TASK_COMM_FMT) + 8];
1910 ssize_t n;
1911 int fd;
1912
1913 snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, (unsigned int)thread->kernel_id);
1914 fd = open(comm_name, O_RDWR);
1915 if (fd == -1)
1916 {
1917 ret = errno;
1918 goto exit;
1919 }
1920 n = TEMP_FAILURE_RETRY(write(fd, thname, thname_len));
1921 close(fd);
1922
1923 if (n < 0)
1924 ret = errno;
1925 else if ((size_t)n != thname_len)
1926 ret = EIO;
1927 else
1928 ret = 0;
1929 }
1930exit:
1931 errno = saved_errno;
1932 return ret;
1933}
1934
Glenn Kastend53cae02011-07-11 15:41:28 -07001935/* Return the kernel thread ID for a pthread.
1936 * This is only defined for implementations where pthread <-> kernel is 1:1, which this is.
1937 * Not the same as pthread_getthreadid_np, which is commonly defined to be opaque.
1938 * Internal, not an NDK API.
1939 */
1940
1941pid_t __pthread_gettid(pthread_t thid)
1942{
1943 pthread_internal_t* thread = (pthread_internal_t*)thid;
1944 return thread->kernel_id;
1945}
Jean-Baptiste Querufaca92f2012-03-26 15:25:19 -07001946
1947int __pthread_settid(pthread_t thid, pid_t tid)
1948{
1949 if (thid == 0)
1950 return EINVAL;
1951
1952 pthread_internal_t* thread = (pthread_internal_t*)thid;
1953 thread->kernel_id = tid;
1954
1955 return 0;
1956}