blob: f29472379900dfbbbc5f9bfb39d84a6e3a381b1f [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
29#include <assert.h>
30#include <errno.h>
31#include <fcntl.h>
32#include <limits.h>
33#include <malloc.h>
34#include <memory.h>
35#include <pthread.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080036#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>
André Goddard Rosa78c1c042010-05-19 23:17:16 -030042#include <sys/prctl.h>
43#include <sys/stat.h>
Pierre Peifferd0c884d2012-02-22 16:40:15 +010044#include <sys/types.h>
45#include <time.h>
46#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"
53#include "pthread_internal.h"
54#include "thread_private.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080055
Mathias Agopian7c0c3792011-09-05 23:54:55 -070056extern void pthread_debug_mutex_lock_check(pthread_mutex_t *mutex);
57extern void pthread_debug_mutex_unlock_check(pthread_mutex_t *mutex);
58
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080059extern int __pthread_clone(int (*fn)(void*), void *child_stack, int flags, void *arg);
60extern void _exit_with_stack_teardown(void * stackBase, int stackSize, int retCode);
61extern void _exit_thread(int retCode);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080062
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -070063int __futex_wake_ex(volatile void *ftx, int pshared, int val)
64{
65 return __futex_syscall3(ftx, pshared ? FUTEX_WAKE : FUTEX_WAKE_PRIVATE, val);
66}
67
68int __futex_wait_ex(volatile void *ftx, int pshared, int val, const struct timespec *timeout)
69{
70 return __futex_syscall4(ftx, pshared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE, val, timeout);
71}
72
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -070073#define __likely(cond) __builtin_expect(!!(cond), 1)
74#define __unlikely(cond) __builtin_expect(!!(cond), 0)
75
Bruce Beare8e551a62011-03-28 09:47:35 -070076#ifdef __i386__
77#define ATTRIBUTES __attribute__((noinline)) __attribute__((fastcall))
78#else
79#define ATTRIBUTES __attribute__((noinline))
80#endif
81
82void ATTRIBUTES _thread_created_hook(pid_t thread_id);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080083
Pierre Peifferd0c884d2012-02-22 16:40:15 +010084static const int kPthreadInitFailed = 1;
85
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080086#define PTHREAD_ATTR_FLAG_DETACHED 0x00000001
87#define PTHREAD_ATTR_FLAG_USER_STACK 0x00000002
88
89#define DEFAULT_STACKSIZE (1024 * 1024)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080090
91static pthread_mutex_t mmap_lock = PTHREAD_MUTEX_INITIALIZER;
92
93
94static const pthread_attr_t gDefaultPthreadAttr = {
95 .flags = 0,
96 .stack_base = NULL,
97 .stack_size = DEFAULT_STACKSIZE,
98 .guard_size = PAGE_SIZE,
99 .sched_policy = SCHED_NORMAL,
100 .sched_priority = 0
101};
102
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100103static pthread_internal_t* gThreadList = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800104static pthread_mutex_t gThreadListLock = PTHREAD_MUTEX_INITIALIZER;
105static pthread_mutex_t gDebuggerNotificationLock = PTHREAD_MUTEX_INITIALIZER;
106
Elliott Hughes4f251be2012-11-01 16:33:29 -0700107static void _pthread_internal_remove_locked(pthread_internal_t* thread) {
108 if (thread->next != NULL) {
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700109 thread->next->prev = thread->prev;
Elliott Hughes4f251be2012-11-01 16:33:29 -0700110 }
111 if (thread->prev != NULL) {
112 thread->prev->next = thread->next;
113 } else {
114 gThreadList = thread->next;
115 }
116
117 // The main thread is not heap-allocated. See __libc_init_tls for the declaration,
118 // and __libc_init_common for the point where it's added to the thread list.
119 if (thread->allocated_on_heap) {
120 free(thread);
121 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800122}
123
Elliott Hughes4f251be2012-11-01 16:33:29 -0700124static void _pthread_internal_remove(pthread_internal_t* thread) {
125 pthread_mutex_lock(&gThreadListLock);
126 _pthread_internal_remove_locked(thread);
127 pthread_mutex_unlock(&gThreadListLock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800128}
129
Elliott Hughes4f251be2012-11-01 16:33:29 -0700130__LIBC_ABI_PRIVATE__ void _pthread_internal_add(pthread_internal_t* thread) {
131 pthread_mutex_lock(&gThreadListLock);
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700132
Elliott Hughes4f251be2012-11-01 16:33:29 -0700133 // We insert at the head.
134 thread->next = gThreadList;
135 thread->prev = NULL;
136 if (thread->next != NULL) {
137 thread->next->prev = thread;
138 }
139 gThreadList = thread;
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700140
Elliott Hughes4f251be2012-11-01 16:33:29 -0700141 pthread_mutex_unlock(&gThreadListLock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800142}
143
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +0400144__LIBC_ABI_PRIVATE__ pthread_internal_t*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800145__get_thread(void)
146{
147 void** tls = (void**)__get_tls();
148
149 return (pthread_internal_t*) tls[TLS_SLOT_THREAD_ID];
150}
151
152
153void*
154__get_stack_base(int *p_stack_size)
155{
156 pthread_internal_t* thread = __get_thread();
157
158 *p_stack_size = thread->attr.stack_size;
159 return thread->attr.stack_base;
160}
161
162
Elliott Hughes5419b942012-10-16 15:54:46 -0700163void __init_tls(void** tls, void* thread) {
164 ((pthread_internal_t*) thread)->tls = tls;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800165
Elliott Hughes5419b942012-10-16 15:54:46 -0700166 // Zero-initialize all the slots.
167 for (size_t i = 0; i < BIONIC_TLS_SLOTS; ++i) {
168 tls[i] = NULL;
169 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800170
Elliott Hughesad88a082012-10-24 18:37:21 -0700171 // Slot 0 must point to itself. The x86 Linux kernel reads the TLS from %fs:0.
Elliott Hughes5419b942012-10-16 15:54:46 -0700172 tls[TLS_SLOT_SELF] = (void*) tls;
173 tls[TLS_SLOT_THREAD_ID] = thread;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800174
Elliott Hughesad88a082012-10-24 18:37:21 -0700175 // Stack guard generation may make system calls, and those system calls may fail.
176 // If they do, they'll try to set errno, so we can only do this after calling __set_tls.
Elliott Hughes5419b942012-10-16 15:54:46 -0700177 __set_tls((void*) tls);
Elliott Hughesad88a082012-10-24 18:37:21 -0700178 tls[TLS_SLOT_STACK_GUARD] = __generate_stack_chk_guard();
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";
232 __libc_android_log_print(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) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800309 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);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800324 return ENOMEM;
325 }
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
382int 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
Wink Savillea12c5442013-01-08 15:15:45 -0800453int pthread_attr_setstackaddr(pthread_attr_t * attr __attribute__((unused)),
454 void * stack_addr __attribute__((unused)))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800455{
Wink Savillea12c5442013-01-08 15:15:45 -0800456 // This was removed from POSIX.1-2008, and is not implemented on bionic.
457 // Needed for ABI compatibility with the NDK.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800458 return ENOSYS;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800459}
460
461int pthread_attr_getstackaddr(pthread_attr_t const * attr, void ** stack_addr)
462{
Wink Savillea12c5442013-01-08 15:15:45 -0800463 // This was removed from POSIX.1-2008.
464 // Needed for ABI compatibility with the NDK.
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700465 *stack_addr = (char*)attr->stack_base + attr->stack_size;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800466 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
Wink Savillea12c5442013-01-08 15:15:45 -0800512int pthread_attr_setscope(pthread_attr_t *attr __attribute__((unused)), int scope)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800513{
514 if (scope == PTHREAD_SCOPE_SYSTEM)
515 return 0;
516 if (scope == PTHREAD_SCOPE_PROCESS)
517 return ENOTSUP;
518
519 return EINVAL;
520}
521
Wink Savillea12c5442013-01-08 15:15:45 -0800522int pthread_attr_getscope(pthread_attr_t const *attr __attribute__((unused)))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800523{
524 return PTHREAD_SCOPE_SYSTEM;
525}
526
527
528/* 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
553/* used by pthread_exit() to clean all TLS keys of the current thread */
554static void pthread_key_clean_all(void);
555
556void pthread_exit(void * retval)
557{
558 pthread_internal_t* thread = __get_thread();
559 void* stack_base = thread->attr.stack_base;
560 int stack_size = thread->attr.stack_size;
561 int user_stack = (thread->attr.flags & PTHREAD_ATTR_FLAG_USER_STACK) != 0;
Jack Rene480fc82011-09-21 12:44:11 +0200562 sigset_t mask;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800563
564 // call the cleanup handlers first
565 while (thread->cleanup_stack) {
566 __pthread_cleanup_t* c = thread->cleanup_stack;
567 thread->cleanup_stack = c->__cleanup_prev;
568 c->__cleanup_routine(c->__cleanup_arg);
569 }
570
571 // call the TLS destructors, it is important to do that before removing this
572 // thread from the global list. this will ensure that if someone else deletes
573 // a TLS key, the corresponding value will be set to NULL in this thread's TLS
574 // space (see pthread_key_delete)
575 pthread_key_clean_all();
576
577 // if the thread is detached, destroy the pthread_internal_t
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400578 // otherwise, keep it in memory and signal any joiners.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800579 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
580 _pthread_internal_remove(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800581 } else {
Bjorn Andersson0753dc62012-05-03 17:12:39 -0700582 pthread_mutex_lock(&gThreadListLock);
583
584 /* make sure that the thread struct doesn't have stale pointers to a stack that
585 * will be unmapped after the exit call below.
586 */
587 if (!user_stack) {
588 thread->attr.stack_base = NULL;
589 thread->attr.stack_size = 0;
590 thread->tls = NULL;
591 }
592
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800593 /* the join_count field is used to store the number of threads waiting for
594 * the termination of this thread with pthread_join(),
595 *
596 * if it is positive we need to signal the waiters, and we do not touch
597 * the count (it will be decremented by the waiters, the last one will
598 * also remove/free the thread structure
599 *
600 * if it is zero, we set the count value to -1 to indicate that the
601 * thread is in 'zombie' state: it has stopped executing, and its stack
602 * is gone (as well as its TLS area). when another thread calls pthread_join()
603 * on it, it will immediately free the thread and return.
604 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800605 thread->return_value = retval;
606 if (thread->join_count > 0) {
607 pthread_cond_broadcast(&thread->join_cond);
608 } else {
609 thread->join_count = -1; /* zombie thread */
610 }
611 pthread_mutex_unlock(&gThreadListLock);
612 }
613
Jack Rene480fc82011-09-21 12:44:11 +0200614 sigfillset(&mask);
615 sigdelset(&mask, SIGSEGV);
616 (void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *)NULL);
617
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800618 // destroy the thread stack
619 if (user_stack)
620 _exit_thread((int)retval);
621 else
622 _exit_with_stack_teardown(stack_base, stack_size, (int)retval);
623}
624
625int pthread_join(pthread_t thid, void ** ret_val)
626{
627 pthread_internal_t* thread = (pthread_internal_t*)thid;
Elliott Hughes14f19592012-10-29 10:19:44 -0700628 if (thid == pthread_self()) {
629 return EDEADLK;
630 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800631
632 // check that the thread still exists and is not detached
633 pthread_mutex_lock(&gThreadListLock);
634
Elliott Hughes14f19592012-10-29 10:19:44 -0700635 for (thread = gThreadList; thread != NULL; thread = thread->next) {
636 if (thread == (pthread_internal_t*)thid) {
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200637 goto FoundIt;
Elliott Hughes14f19592012-10-29 10:19:44 -0700638 }
639 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800640
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200641 pthread_mutex_unlock(&gThreadListLock);
642 return ESRCH;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800643
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200644FoundIt:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800645 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
646 pthread_mutex_unlock(&gThreadListLock);
647 return EINVAL;
648 }
649
650 /* wait for thread death when needed
651 *
652 * if the 'join_count' is negative, this is a 'zombie' thread that
653 * is already dead and without stack/TLS
654 *
655 * otherwise, we need to increment 'join-count' and wait to be signaled
656 */
Elliott Hughes14f19592012-10-29 10:19:44 -0700657 int count = thread->join_count;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800658 if (count >= 0) {
659 thread->join_count += 1;
660 pthread_cond_wait( &thread->join_cond, &gThreadListLock );
661 count = --thread->join_count;
662 }
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400663 if (ret_val) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800664 *ret_val = thread->return_value;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400665 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800666
667 /* remove thread descriptor when we're the last joiner or when the
668 * thread was already a zombie.
669 */
670 if (count <= 0) {
671 _pthread_internal_remove_locked(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800672 }
673 pthread_mutex_unlock(&gThreadListLock);
674 return 0;
675}
676
677int pthread_detach( pthread_t thid )
678{
679 pthread_internal_t* thread;
680 int result = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800681
682 pthread_mutex_lock(&gThreadListLock);
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400683 for (thread = gThreadList; thread != NULL; thread = thread->next) {
684 if (thread == (pthread_internal_t*)thid) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800685 goto FoundIt;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400686 }
687 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800688
689 result = ESRCH;
690 goto Exit;
691
692FoundIt:
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400693 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
694 result = EINVAL; // Already detached.
695 goto Exit;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800696 }
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400697
698 if (thread->join_count > 0) {
699 result = 0; // Already being joined; silently do nothing, like glibc.
700 goto Exit;
701 }
702
703 thread->attr.flags |= PTHREAD_ATTR_FLAG_DETACHED;
704
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800705Exit:
706 pthread_mutex_unlock(&gThreadListLock);
707 return result;
708}
709
710pthread_t pthread_self(void)
711{
712 return (pthread_t)__get_thread();
713}
714
715int pthread_equal(pthread_t one, pthread_t two)
716{
717 return (one == two ? 1 : 0);
718}
719
720int pthread_getschedparam(pthread_t thid, int * policy,
721 struct sched_param * param)
722{
723 int old_errno = errno;
724
725 pthread_internal_t * thread = (pthread_internal_t *)thid;
726 int err = sched_getparam(thread->kernel_id, param);
727 if (!err) {
728 *policy = sched_getscheduler(thread->kernel_id);
729 } else {
730 err = errno;
731 errno = old_errno;
732 }
733 return err;
734}
735
736int pthread_setschedparam(pthread_t thid, int policy,
737 struct sched_param const * param)
738{
739 pthread_internal_t * thread = (pthread_internal_t *)thid;
740 int old_errno = errno;
741 int ret;
742
743 ret = sched_setscheduler(thread->kernel_id, policy, param);
744 if (ret < 0) {
745 ret = errno;
746 errno = old_errno;
747 }
748 return ret;
749}
750
751
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800752/* a mutex is implemented as a 32-bit integer holding the following fields
753 *
754 * bits: name description
755 * 31-16 tid owner thread's kernel id (recursive and errorcheck only)
756 * 15-14 type mutex type
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700757 * 13 shared process-shared flag
758 * 12-2 counter counter of recursive mutexes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800759 * 1-0 state lock state (0, 1 or 2)
760 */
761
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100762/* Convenience macro, creates a mask of 'bits' bits that starts from
763 * the 'shift'-th least significant bit in a 32-bit word.
764 *
765 * Examples: FIELD_MASK(0,4) -> 0xf
766 * FIELD_MASK(16,9) -> 0x1ff0000
767 */
768#define FIELD_MASK(shift,bits) (((1 << (bits))-1) << (shift))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800769
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100770/* This one is used to create a bit pattern from a given field value */
771#define FIELD_TO_BITS(val,shift,bits) (((val) & ((1 << (bits))-1)) << (shift))
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100772
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100773/* And this one does the opposite, i.e. extract a field's value from a bit pattern */
774#define FIELD_FROM_BITS(val,shift,bits) (((val) >> (shift)) & ((1 << (bits))-1))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800775
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100776/* Mutex state:
777 *
778 * 0 for unlocked
779 * 1 for locked, no waiters
780 * 2 for locked, maybe waiters
781 */
782#define MUTEX_STATE_SHIFT 0
783#define MUTEX_STATE_LEN 2
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800784
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100785#define MUTEX_STATE_MASK FIELD_MASK(MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
786#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
787#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
788
789#define MUTEX_STATE_UNLOCKED 0 /* must be 0 to match __PTHREAD_MUTEX_INIT_VALUE */
790#define MUTEX_STATE_LOCKED_UNCONTENDED 1 /* must be 1 due to atomic dec in unlock operation */
791#define MUTEX_STATE_LOCKED_CONTENDED 2 /* must be 1 + LOCKED_UNCONTENDED due to atomic dec */
792
793#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
794#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
795
796#define MUTEX_STATE_BITS_UNLOCKED MUTEX_STATE_TO_BITS(MUTEX_STATE_UNLOCKED)
797#define MUTEX_STATE_BITS_LOCKED_UNCONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_UNCONTENDED)
798#define MUTEX_STATE_BITS_LOCKED_CONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_CONTENDED)
799
800/* return true iff the mutex if locked with no waiters */
801#define MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_UNCONTENDED)
802
803/* return true iff the mutex if locked with maybe waiters */
804#define MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_CONTENDED)
805
806/* used to flip from LOCKED_UNCONTENDED to LOCKED_CONTENDED */
807#define MUTEX_STATE_BITS_FLIP_CONTENTION(v) ((v) ^ (MUTEX_STATE_BITS_LOCKED_CONTENDED ^ MUTEX_STATE_BITS_LOCKED_UNCONTENDED))
808
809/* Mutex counter:
810 *
811 * We need to check for overflow before incrementing, and we also need to
812 * detect when the counter is 0
813 */
814#define MUTEX_COUNTER_SHIFT 2
815#define MUTEX_COUNTER_LEN 11
816#define MUTEX_COUNTER_MASK FIELD_MASK(MUTEX_COUNTER_SHIFT, MUTEX_COUNTER_LEN)
817
818#define MUTEX_COUNTER_BITS_WILL_OVERFLOW(v) (((v) & MUTEX_COUNTER_MASK) == MUTEX_COUNTER_MASK)
819#define MUTEX_COUNTER_BITS_IS_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
820
821/* Used to increment the counter directly after overflow has been checked */
822#define MUTEX_COUNTER_BITS_ONE FIELD_TO_BITS(1,MUTEX_COUNTER_SHIFT,MUTEX_COUNTER_LEN)
823
824/* Returns true iff the counter is 0 */
825#define MUTEX_COUNTER_BITS_ARE_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
826
827/* Mutex shared bit flag
828 *
829 * This flag is set to indicate that the mutex is shared among processes.
830 * This changes the futex opcode we use for futex wait/wake operations
831 * (non-shared operations are much faster).
832 */
833#define MUTEX_SHARED_SHIFT 13
834#define MUTEX_SHARED_MASK FIELD_MASK(MUTEX_SHARED_SHIFT,1)
835
836/* Mutex type:
837 *
838 * We support normal, recursive and errorcheck mutexes.
839 *
840 * The constants defined here *cannot* be changed because they must match
841 * the C library ABI which defines the following initialization values in
842 * <pthread.h>:
843 *
844 * __PTHREAD_MUTEX_INIT_VALUE
845 * __PTHREAD_RECURSIVE_MUTEX_VALUE
846 * __PTHREAD_ERRORCHECK_MUTEX_INIT_VALUE
847 */
848#define MUTEX_TYPE_SHIFT 14
849#define MUTEX_TYPE_LEN 2
850#define MUTEX_TYPE_MASK FIELD_MASK(MUTEX_TYPE_SHIFT,MUTEX_TYPE_LEN)
851
852#define MUTEX_TYPE_NORMAL 0 /* Must be 0 to match __PTHREAD_MUTEX_INIT_VALUE */
853#define MUTEX_TYPE_RECURSIVE 1
854#define MUTEX_TYPE_ERRORCHECK 2
855
856#define MUTEX_TYPE_TO_BITS(t) FIELD_TO_BITS(t, MUTEX_TYPE_SHIFT, MUTEX_TYPE_LEN)
857
858#define MUTEX_TYPE_BITS_NORMAL MUTEX_TYPE_TO_BITS(MUTEX_TYPE_NORMAL)
859#define MUTEX_TYPE_BITS_RECURSIVE MUTEX_TYPE_TO_BITS(MUTEX_TYPE_RECURSIVE)
860#define MUTEX_TYPE_BITS_ERRORCHECK MUTEX_TYPE_TO_BITS(MUTEX_TYPE_ERRORCHECK)
861
862/* Mutex owner field:
863 *
864 * This is only used for recursive and errorcheck mutexes. It holds the
865 * kernel TID of the owning thread. Note that this works because the Linux
866 * kernel _only_ uses 16-bit values for thread ids.
867 *
868 * More specifically, it will wrap to 10000 when it reaches over 32768 for
869 * application processes. You can check this by running the following inside
870 * an adb shell session:
871 *
872 OLDPID=$$;
873 while true; do
874 NEWPID=$(sh -c 'echo $$')
875 if [ "$NEWPID" -gt 32768 ]; then
876 echo "AARGH: new PID $NEWPID is too high!"
877 exit 1
878 fi
879 if [ "$NEWPID" -lt "$OLDPID" ]; then
880 echo "****** Wrapping from PID $OLDPID to $NEWPID. *******"
881 else
882 echo -n "$NEWPID!"
883 fi
884 OLDPID=$NEWPID
885 done
886
887 * Note that you can run the same example on a desktop Linux system,
888 * the wrapping will also happen at 32768, but will go back to 300 instead.
889 */
890#define MUTEX_OWNER_SHIFT 16
891#define MUTEX_OWNER_LEN 16
892
893#define MUTEX_OWNER_FROM_BITS(v) FIELD_FROM_BITS(v,MUTEX_OWNER_SHIFT,MUTEX_OWNER_LEN)
894#define MUTEX_OWNER_TO_BITS(v) FIELD_TO_BITS(v,MUTEX_OWNER_SHIFT,MUTEX_OWNER_LEN)
895
896/* Convenience macros.
897 *
898 * These are used to form or modify the bit pattern of a given mutex value
899 */
900
901
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800902
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700903/* a mutex attribute holds the following fields
904 *
905 * bits: name description
906 * 0-3 type type of mutex
907 * 4 shared process-shared flag
908 */
909#define MUTEXATTR_TYPE_MASK 0x000f
910#define MUTEXATTR_SHARED_MASK 0x0010
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800911
912
913int pthread_mutexattr_init(pthread_mutexattr_t *attr)
914{
915 if (attr) {
916 *attr = PTHREAD_MUTEX_DEFAULT;
917 return 0;
918 } else {
919 return EINVAL;
920 }
921}
922
923int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
924{
925 if (attr) {
926 *attr = -1;
927 return 0;
928 } else {
929 return EINVAL;
930 }
931}
932
933int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
934{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700935 if (attr) {
936 int atype = (*attr & MUTEXATTR_TYPE_MASK);
937
938 if (atype >= PTHREAD_MUTEX_NORMAL &&
939 atype <= PTHREAD_MUTEX_ERRORCHECK) {
940 *type = atype;
941 return 0;
942 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800943 }
944 return EINVAL;
945}
946
947int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
948{
949 if (attr && type >= PTHREAD_MUTEX_NORMAL &&
950 type <= PTHREAD_MUTEX_ERRORCHECK ) {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700951 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800952 return 0;
953 }
954 return EINVAL;
955}
956
957/* process-shared mutexes are not supported at the moment */
958
959int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
960{
961 if (!attr)
962 return EINVAL;
963
Mathias Agopianb7681162009-07-13 22:00:33 -0700964 switch (pshared) {
965 case PTHREAD_PROCESS_PRIVATE:
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700966 *attr &= ~MUTEXATTR_SHARED_MASK;
967 return 0;
968
Mathias Agopianb7681162009-07-13 22:00:33 -0700969 case PTHREAD_PROCESS_SHARED:
970 /* our current implementation of pthread actually supports shared
971 * mutexes but won't cleanup if a process dies with the mutex held.
972 * Nevertheless, it's better than nothing. Shared mutexes are used
973 * by surfaceflinger and audioflinger.
974 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700975 *attr |= MUTEXATTR_SHARED_MASK;
Mathias Agopianb7681162009-07-13 22:00:33 -0700976 return 0;
977 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700978 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800979}
980
981int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
982{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700983 if (!attr || !pshared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800984 return EINVAL;
985
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700986 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED
987 : PTHREAD_PROCESS_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800988 return 0;
989}
990
991int pthread_mutex_init(pthread_mutex_t *mutex,
992 const pthread_mutexattr_t *attr)
993{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700994 int value = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800995
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700996 if (mutex == NULL)
997 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800998
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700999 if (__likely(attr == NULL)) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001000 mutex->value = MUTEX_TYPE_BITS_NORMAL;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001001 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001002 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001003
1004 if ((*attr & MUTEXATTR_SHARED_MASK) != 0)
1005 value |= MUTEX_SHARED_MASK;
1006
1007 switch (*attr & MUTEXATTR_TYPE_MASK) {
1008 case PTHREAD_MUTEX_NORMAL:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001009 value |= MUTEX_TYPE_BITS_NORMAL;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001010 break;
1011 case PTHREAD_MUTEX_RECURSIVE:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001012 value |= MUTEX_TYPE_BITS_RECURSIVE;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001013 break;
1014 case PTHREAD_MUTEX_ERRORCHECK:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001015 value |= MUTEX_TYPE_BITS_ERRORCHECK;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001016 break;
1017 default:
1018 return EINVAL;
1019 }
1020
1021 mutex->value = value;
1022 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001023}
1024
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001025
1026/*
1027 * Lock a non-recursive mutex.
1028 *
1029 * As noted above, there are three states:
1030 * 0 (unlocked, no contention)
1031 * 1 (locked, no contention)
1032 * 2 (locked, contention)
1033 *
1034 * Non-recursive mutexes don't use the thread-id or counter fields, and the
1035 * "type" value is zero, so the only bits that will be set are the ones in
1036 * the lock state field.
1037 */
1038static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001039_normal_lock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001040{
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001041 /* convenience shortcuts */
1042 const int unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
1043 const int locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001044 /*
1045 * The common case is an unlocked mutex, so we begin by trying to
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001046 * change the lock's state from 0 (UNLOCKED) to 1 (LOCKED).
1047 * __bionic_cmpxchg() returns 0 if it made the swap successfully.
1048 * If the result is nonzero, this lock is already held by another thread.
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001049 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001050 if (__bionic_cmpxchg(unlocked, locked_uncontended, &mutex->value) != 0) {
1051 const int locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001052 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001053 * We want to go to sleep until the mutex is available, which
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001054 * requires promoting it to state 2 (CONTENDED). We need to
1055 * swap in the new state value and then wait until somebody wakes us up.
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001056 *
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001057 * __bionic_swap() returns the previous value. We swap 2 in and
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001058 * see if we got zero back; if so, we have acquired the lock. If
1059 * not, another thread still holds the lock and we wait again.
1060 *
1061 * The second argument to the __futex_wait() call is compared
1062 * against the current value. If it doesn't match, __futex_wait()
1063 * returns immediately (otherwise, it sleeps for a time specified
1064 * by the third argument; 0 means sleep forever). This ensures
1065 * that the mutex is in state 2 when we go to sleep on it, which
1066 * guarantees a wake-up call.
1067 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001068 while (__bionic_swap(locked_contended, &mutex->value) != unlocked)
1069 __futex_wait_ex(&mutex->value, shared, locked_contended, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001070 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001071 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001072}
1073
1074/*
1075 * Release a non-recursive mutex. The caller is responsible for determining
1076 * that we are in fact the owner of this lock.
1077 */
1078static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001079_normal_unlock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001080{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001081 ANDROID_MEMBAR_FULL();
1082
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001083 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001084 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001085 * to release the lock. __bionic_atomic_dec() returns the previous value;
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001086 * if it wasn't 1 we have to do some additional work.
1087 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001088 if (__bionic_atomic_dec(&mutex->value) != (shared|MUTEX_STATE_BITS_LOCKED_UNCONTENDED)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001089 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001090 * Start by releasing the lock. The decrement changed it from
1091 * "contended lock" to "uncontended lock", which means we still
1092 * hold it, and anybody who tries to sneak in will push it back
1093 * to state 2.
1094 *
1095 * Once we set it to zero the lock is up for grabs. We follow
1096 * this with a __futex_wake() to ensure that one of the waiting
1097 * threads has a chance to grab it.
1098 *
1099 * This doesn't cause a race with the swap/wait pair in
1100 * _normal_lock(), because the __futex_wait() call there will
1101 * return immediately if the mutex value isn't 2.
1102 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001103 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001104
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001105 /*
1106 * Wake up one waiting thread. We don't know which thread will be
1107 * woken or when it'll start executing -- futexes make no guarantees
1108 * here. There may not even be a thread waiting.
1109 *
1110 * The newly-woken thread will replace the 0 we just set above
1111 * with 2, which means that when it eventually releases the mutex
1112 * it will also call FUTEX_WAKE. This results in one extra wake
1113 * call whenever a lock is contended, but lets us avoid forgetting
1114 * anyone without requiring us to track the number of sleepers.
1115 *
1116 * It's possible for another thread to sneak in and grab the lock
1117 * between the zero assignment above and the wake call below. If
1118 * the new thread is "slow" and holds the lock for a while, we'll
1119 * wake up a sleeper, which will swap in a 2 and then go back to
1120 * sleep since the lock is still held. If the new thread is "fast",
1121 * running to completion before we call wake, the thread we
1122 * eventually wake will find an unlocked mutex and will execute.
1123 * Either way we have correct behavior and nobody is orphaned on
1124 * the wait queue.
1125 */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001126 __futex_wake_ex(&mutex->value, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001127 }
1128}
1129
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001130/* This common inlined function is used to increment the counter of an
1131 * errorcheck or recursive mutex.
1132 *
1133 * For errorcheck mutexes, it will return EDEADLK
1134 * If the counter overflows, it will return EAGAIN
1135 * Otherwise, it atomically increments the counter and returns 0
1136 * after providing an acquire barrier.
1137 *
1138 * mtype is the current mutex type
1139 * mvalue is the current mutex value (already loaded)
1140 * mutex pointers to the mutex.
1141 */
1142static __inline__ __attribute__((always_inline)) int
1143_recursive_increment(pthread_mutex_t* mutex, int mvalue, int mtype)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001144{
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001145 if (mtype == MUTEX_TYPE_BITS_ERRORCHECK) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001146 /* trying to re-lock a mutex we already acquired */
1147 return EDEADLK;
1148 }
1149
1150 /* Detect recursive lock overflow and return EAGAIN.
1151 * This is safe because only the owner thread can modify the
David 'Digit' Turnerb57db752012-01-24 13:20:38 +01001152 * counter bits in the mutex value.
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001153 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001154 if (MUTEX_COUNTER_BITS_WILL_OVERFLOW(mvalue)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001155 return EAGAIN;
1156 }
1157
1158 /* We own the mutex, but other threads are able to change
David 'Digit' Turnerb57db752012-01-24 13:20:38 +01001159 * the lower bits (e.g. promoting it to "contended"), so we
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001160 * need to use an atomic cmpxchg loop to update the counter.
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001161 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001162 for (;;) {
1163 /* increment counter, overflow was already checked */
1164 int newval = mvalue + MUTEX_COUNTER_BITS_ONE;
1165 if (__likely(__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0)) {
1166 /* mutex is still locked, not need for a memory barrier */
1167 return 0;
1168 }
1169 /* the value was changed, this happens when another thread changes
1170 * the lower state bits from 1 to 2 to indicate contention. This
1171 * cannot change the counter, so simply reload and try again.
1172 */
1173 mvalue = mutex->value;
1174 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001175}
1176
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001177__LIBC_HIDDEN__
1178int pthread_mutex_lock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001179{
Wink Savillea12c5442013-01-08 15:15:45 -08001180 int mvalue, mtype, tid, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001181
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001182 if (__unlikely(mutex == NULL))
1183 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001184
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001185 mvalue = mutex->value;
1186 mtype = (mvalue & MUTEX_TYPE_MASK);
1187 shared = (mvalue & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001188
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001189 /* Handle normal case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001190 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) ) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001191 _normal_lock(mutex, shared);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001192 return 0;
1193 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001194
1195 /* Do we already own this recursive or error-check mutex ? */
1196 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001197 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001198 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001199
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001200 /* Add in shared state to avoid extra 'or' operations below */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001201 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001202
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001203 /* First, if the mutex is unlocked, try to quickly acquire it.
1204 * In the optimistic case where this works, set the state to 1 to
1205 * indicate locked with no contention */
1206 if (mvalue == mtype) {
1207 int newval = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1208 if (__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0) {
1209 ANDROID_MEMBAR_FULL();
1210 return 0;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001211 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001212 /* argh, the value changed, reload before entering the loop */
1213 mvalue = mutex->value;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001214 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001215
1216 for (;;) {
1217 int newval;
1218
1219 /* if the mutex is unlocked, its value should be 'mtype' and
1220 * we try to acquire it by setting its owner and state atomically.
1221 * NOTE: We put the state to 2 since we _know_ there is contention
1222 * when we are in this loop. This ensures all waiters will be
1223 * unlocked.
1224 */
1225 if (mvalue == mtype) {
1226 newval = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1227 /* TODO: Change this to __bionic_cmpxchg_acquire when we
1228 * implement it to get rid of the explicit memory
1229 * barrier below.
1230 */
1231 if (__unlikely(__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0)) {
1232 mvalue = mutex->value;
1233 continue;
1234 }
1235 ANDROID_MEMBAR_FULL();
1236 return 0;
1237 }
1238
1239 /* the mutex is already locked by another thread, if its state is 1
1240 * we will change it to 2 to indicate contention. */
1241 if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(mvalue)) {
1242 newval = MUTEX_STATE_BITS_FLIP_CONTENTION(mvalue); /* locked state 1 => state 2 */
1243 if (__unlikely(__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0)) {
1244 mvalue = mutex->value;
1245 continue;
1246 }
1247 mvalue = newval;
1248 }
1249
1250 /* wait until the mutex is unlocked */
1251 __futex_wait_ex(&mutex->value, shared, mvalue, NULL);
1252
1253 mvalue = mutex->value;
1254 }
1255 /* NOTREACHED */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001256}
1257
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001258int pthread_mutex_lock(pthread_mutex_t *mutex)
1259{
1260 int err = pthread_mutex_lock_impl(mutex);
1261#ifdef PTHREAD_DEBUG
1262 if (PTHREAD_DEBUG_ENABLED) {
1263 if (!err) {
1264 pthread_debug_mutex_lock_check(mutex);
1265 }
1266 }
1267#endif
1268 return err;
1269}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001270
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001271__LIBC_HIDDEN__
1272int pthread_mutex_unlock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001273{
Wink Savillea12c5442013-01-08 15:15:45 -08001274 int mvalue, mtype, tid, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001275
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001276 if (__unlikely(mutex == NULL))
1277 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001278
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001279 mvalue = mutex->value;
1280 mtype = (mvalue & MUTEX_TYPE_MASK);
1281 shared = (mvalue & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001282
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001283 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001284 if (__likely(mtype == MUTEX_TYPE_BITS_NORMAL)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001285 _normal_unlock(mutex, shared);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001286 return 0;
1287 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001288
1289 /* Do we already own this recursive or error-check mutex ? */
1290 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001291 if ( tid != MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001292 return EPERM;
1293
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001294 /* If the counter is > 0, we can simply decrement it atomically.
1295 * Since other threads can mutate the lower state bits (and only the
1296 * lower state bits), use a cmpxchg to do it.
1297 */
1298 if (!MUTEX_COUNTER_BITS_IS_ZERO(mvalue)) {
1299 for (;;) {
1300 int newval = mvalue - MUTEX_COUNTER_BITS_ONE;
1301 if (__likely(__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0)) {
1302 /* success: we still own the mutex, so no memory barrier */
1303 return 0;
1304 }
1305 /* the value changed, so reload and loop */
1306 mvalue = mutex->value;
1307 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001308 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001309
1310 /* the counter is 0, so we're going to unlock the mutex by resetting
1311 * its value to 'unlocked'. We need to perform a swap in order
1312 * to read the current state, which will be 2 if there are waiters
1313 * to awake.
1314 *
1315 * TODO: Change this to __bionic_swap_release when we implement it
1316 * to get rid of the explicit memory barrier below.
1317 */
1318 ANDROID_MEMBAR_FULL(); /* RELEASE BARRIER */
1319 mvalue = __bionic_swap(mtype | shared | MUTEX_STATE_BITS_UNLOCKED, &mutex->value);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001320
1321 /* Wake one waiting thread, if any */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001322 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(mvalue)) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001323 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001324 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001325 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001326}
1327
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001328int pthread_mutex_unlock(pthread_mutex_t *mutex)
1329{
1330#ifdef PTHREAD_DEBUG
1331 if (PTHREAD_DEBUG_ENABLED) {
1332 pthread_debug_mutex_unlock_check(mutex);
1333 }
1334#endif
1335 return pthread_mutex_unlock_impl(mutex);
1336}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001337
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001338__LIBC_HIDDEN__
1339int pthread_mutex_trylock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001340{
Wink Savillea12c5442013-01-08 15:15:45 -08001341 int mvalue, mtype, tid, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001342
1343 if (__unlikely(mutex == NULL))
1344 return EINVAL;
1345
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001346 mvalue = mutex->value;
1347 mtype = (mvalue & MUTEX_TYPE_MASK);
1348 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001349
1350 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001351 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001352 {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001353 if (__bionic_cmpxchg(shared|MUTEX_STATE_BITS_UNLOCKED,
1354 shared|MUTEX_STATE_BITS_LOCKED_UNCONTENDED,
1355 &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001356 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001357 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001358 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001359
1360 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001361 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001362
1363 /* Do we already own this recursive or error-check mutex ? */
1364 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001365 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001366 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001367
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001368 /* Same as pthread_mutex_lock, except that we don't want to wait, and
1369 * the only operation that can succeed is a single cmpxchg to acquire the
1370 * lock if it is released / not owned by anyone. No need for a complex loop.
1371 */
1372 mtype |= shared | MUTEX_STATE_BITS_UNLOCKED;
1373 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001374
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001375 if (__likely(__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0)) {
1376 ANDROID_MEMBAR_FULL();
1377 return 0;
1378 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001379
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001380 return EBUSY;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001381}
1382
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001383int pthread_mutex_trylock(pthread_mutex_t *mutex)
1384{
1385 int err = pthread_mutex_trylock_impl(mutex);
1386#ifdef PTHREAD_DEBUG
1387 if (PTHREAD_DEBUG_ENABLED) {
1388 if (!err) {
1389 pthread_debug_mutex_lock_check(mutex);
1390 }
1391 }
1392#endif
1393 return err;
1394}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001395
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001396/* initialize 'ts' with the difference between 'abstime' and the current time
1397 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
1398 */
1399static int
1400__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
1401{
1402 clock_gettime(clock, ts);
1403 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
1404 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
1405 if (ts->tv_nsec < 0) {
1406 ts->tv_sec--;
1407 ts->tv_nsec += 1000000000;
1408 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001409 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001410 return -1;
1411
1412 return 0;
1413}
1414
1415/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1416 * milliseconds.
1417 */
1418static void
1419__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1420{
1421 clock_gettime(clock, abstime);
1422 abstime->tv_sec += msecs/1000;
1423 abstime->tv_nsec += (msecs%1000)*1000000;
1424 if (abstime->tv_nsec >= 1000000000) {
1425 abstime->tv_sec++;
1426 abstime->tv_nsec -= 1000000000;
1427 }
1428}
1429
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001430__LIBC_HIDDEN__
1431int pthread_mutex_lock_timeout_np_impl(pthread_mutex_t *mutex, unsigned msecs)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001432{
1433 clockid_t clock = CLOCK_MONOTONIC;
1434 struct timespec abstime;
1435 struct timespec ts;
Wink Savillea12c5442013-01-08 15:15:45 -08001436 int mvalue, mtype, tid, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001437
1438 /* compute absolute expiration time */
1439 __timespec_to_relative_msec(&abstime, msecs, clock);
1440
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001441 if (__unlikely(mutex == NULL))
1442 return EINVAL;
1443
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001444 mvalue = mutex->value;
1445 mtype = (mvalue & MUTEX_TYPE_MASK);
1446 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001447
1448 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001449 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001450 {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001451 const int unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
1452 const int locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1453 const int locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1454
1455 /* fast path for uncontended lock. Note: MUTEX_TYPE_BITS_NORMAL is 0 */
1456 if (__bionic_cmpxchg(unlocked, locked_uncontended, &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001457 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001458 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001459 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001460
1461 /* loop while needed */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001462 while (__bionic_swap(locked_contended, &mutex->value) != unlocked) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001463 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1464 return EBUSY;
1465
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001466 __futex_wait_ex(&mutex->value, shared, locked_contended, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001467 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001468 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001469 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001470 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001471
1472 /* Do we already own this recursive or error-check mutex ? */
1473 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001474 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001475 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001476
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001477 /* the following implements the same loop than pthread_mutex_lock_impl
1478 * but adds checks to ensure that the operation never exceeds the
1479 * absolute expiration time.
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001480 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001481 mtype |= shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001482
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001483 /* first try a quick lock */
1484 if (mvalue == mtype) {
1485 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1486 if (__likely(__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0)) {
1487 ANDROID_MEMBAR_FULL();
1488 return 0;
1489 }
1490 mvalue = mutex->value;
1491 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001492
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001493 for (;;) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001494 struct timespec ts;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001495
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001496 /* if the value is 'unlocked', try to acquire it directly */
1497 /* NOTE: put state to 2 since we know there is contention */
1498 if (mvalue == mtype) /* unlocked */ {
1499 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1500 if (__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0) {
1501 ANDROID_MEMBAR_FULL();
1502 return 0;
1503 }
1504 /* the value changed before we could lock it. We need to check
1505 * the time to avoid livelocks, reload the value, then loop again. */
1506 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1507 return EBUSY;
1508
1509 mvalue = mutex->value;
1510 continue;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001511 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001512
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001513 /* The value is locked. If 'uncontended', try to switch its state
1514 * to 'contented' to ensure we get woken up later. */
1515 if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(mvalue)) {
1516 int newval = MUTEX_STATE_BITS_FLIP_CONTENTION(mvalue);
1517 if (__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0) {
1518 /* this failed because the value changed, reload it */
1519 mvalue = mutex->value;
1520 } else {
1521 /* this succeeded, update mvalue */
1522 mvalue = newval;
1523 }
1524 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001525
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001526 /* check time and update 'ts' */
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001527 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1528 return EBUSY;
1529
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001530 /* Only wait to be woken up if the state is '2', otherwise we'll
1531 * simply loop right now. This can happen when the second cmpxchg
1532 * in our loop failed because the mutex was unlocked by another
1533 * thread.
1534 */
1535 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(mvalue)) {
1536 if (__futex_wait_ex(&mutex->value, shared, mvalue, &ts) == ETIMEDOUT) {
1537 return EBUSY;
1538 }
1539 mvalue = mutex->value;
1540 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001541 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001542 /* NOTREACHED */
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001543}
1544
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001545int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1546{
1547 int err = pthread_mutex_lock_timeout_np_impl(mutex, msecs);
1548#ifdef PTHREAD_DEBUG
1549 if (PTHREAD_DEBUG_ENABLED) {
1550 if (!err) {
1551 pthread_debug_mutex_lock_check(mutex);
1552 }
1553 }
1554#endif
1555 return err;
1556}
1557
1558int pthread_mutex_destroy(pthread_mutex_t *mutex)
1559{
1560 int ret;
1561
1562 /* use trylock to ensure that the mutex value is
1563 * valid and is not already locked. */
1564 ret = pthread_mutex_trylock_impl(mutex);
1565 if (ret != 0)
1566 return ret;
1567
1568 mutex->value = 0xdead10cc;
1569 return 0;
1570}
1571
1572
1573
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001574int pthread_condattr_init(pthread_condattr_t *attr)
1575{
1576 if (attr == NULL)
1577 return EINVAL;
1578
1579 *attr = PTHREAD_PROCESS_PRIVATE;
1580 return 0;
1581}
1582
1583int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1584{
1585 if (attr == NULL || pshared == NULL)
1586 return EINVAL;
1587
1588 *pshared = *attr;
1589 return 0;
1590}
1591
1592int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1593{
1594 if (attr == NULL)
1595 return EINVAL;
1596
1597 if (pshared != PTHREAD_PROCESS_SHARED &&
1598 pshared != PTHREAD_PROCESS_PRIVATE)
1599 return EINVAL;
1600
1601 *attr = pshared;
1602 return 0;
1603}
1604
1605int pthread_condattr_destroy(pthread_condattr_t *attr)
1606{
1607 if (attr == NULL)
1608 return EINVAL;
1609
1610 *attr = 0xdeada11d;
1611 return 0;
1612}
1613
1614/* We use one bit in condition variable values as the 'shared' flag
1615 * The rest is a counter.
1616 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001617#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001618#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001619#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1620
1621#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001622
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001623/* XXX *technically* there is a race condition that could allow
1624 * XXX a signal to be missed. If thread A is preempted in _wait()
1625 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001626 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001627 * XXX before thread A is scheduled again and calls futex_wait(),
1628 * XXX then the signal will be lost.
1629 */
1630
1631int pthread_cond_init(pthread_cond_t *cond,
1632 const pthread_condattr_t *attr)
1633{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001634 if (cond == NULL)
1635 return EINVAL;
1636
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001637 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001638
1639 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001640 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001641
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001642 return 0;
1643}
1644
1645int pthread_cond_destroy(pthread_cond_t *cond)
1646{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001647 if (cond == NULL)
1648 return EINVAL;
1649
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001650 cond->value = 0xdeadc04d;
1651 return 0;
1652}
1653
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001654/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001655 * pthread_cond_signal to atomically decrement the counter
1656 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001657 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001658static int
1659__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001660{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001661 long flags;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001662
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001663 if (__unlikely(cond == NULL))
1664 return EINVAL;
1665
1666 flags = (cond->value & ~COND_COUNTER_MASK);
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001667 for (;;) {
1668 long oldval = cond->value;
1669 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1670 | flags;
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001671 if (__bionic_cmpxchg(oldval, newval, &cond->value) == 0)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001672 break;
1673 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001674
Andy McFaddene2ac8982010-09-02 13:34:53 -07001675 /*
1676 * Ensure that all memory accesses previously made by this thread are
1677 * visible to the woken thread(s). On the other side, the "wait"
1678 * code will issue any necessary barriers when locking the mutex.
1679 *
1680 * This may not strictly be necessary -- if the caller follows
1681 * recommended practice and holds the mutex before signaling the cond
1682 * var, the mutex ops will provide correct semantics. If they don't
1683 * hold the mutex, they're subject to race conditions anyway.
1684 */
1685 ANDROID_MEMBAR_FULL();
1686
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001687 __futex_wake_ex(&cond->value, COND_IS_SHARED(cond), counter);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001688 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001689}
1690
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001691int pthread_cond_broadcast(pthread_cond_t *cond)
1692{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001693 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001694}
1695
1696int pthread_cond_signal(pthread_cond_t *cond)
1697{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001698 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001699}
1700
1701int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1702{
1703 return pthread_cond_timedwait(cond, mutex, NULL);
1704}
1705
1706int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1707 pthread_mutex_t * mutex,
1708 const struct timespec *reltime)
1709{
1710 int status;
1711 int oldvalue = cond->value;
1712
1713 pthread_mutex_unlock(mutex);
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001714 status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond), oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001715 pthread_mutex_lock(mutex);
1716
1717 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1718 return 0;
1719}
1720
1721int __pthread_cond_timedwait(pthread_cond_t *cond,
1722 pthread_mutex_t * mutex,
1723 const struct timespec *abstime,
1724 clockid_t clock)
1725{
1726 struct timespec ts;
1727 struct timespec * tsp;
1728
1729 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001730 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001731 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001732 tsp = &ts;
1733 } else {
1734 tsp = NULL;
1735 }
1736
1737 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1738}
1739
1740int pthread_cond_timedwait(pthread_cond_t *cond,
1741 pthread_mutex_t * mutex,
1742 const struct timespec *abstime)
1743{
1744 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1745}
1746
1747
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001748/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001749int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1750 pthread_mutex_t * mutex,
1751 const struct timespec *abstime)
1752{
1753 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1754}
1755
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001756int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1757 pthread_mutex_t * mutex,
1758 const struct timespec *abstime)
1759{
1760 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1761}
1762
1763int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1764 pthread_mutex_t * mutex,
1765 const struct timespec *reltime)
1766{
1767 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1768}
1769
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001770int pthread_cond_timeout_np(pthread_cond_t *cond,
1771 pthread_mutex_t * mutex,
1772 unsigned msecs)
1773{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001774 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001775
1776 ts.tv_sec = msecs / 1000;
1777 ts.tv_nsec = (msecs % 1000) * 1000000;
1778
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001779 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001780}
1781
1782
1783
1784/* A technical note regarding our thread-local-storage (TLS) implementation:
1785 *
1786 * There can be up to TLSMAP_SIZE independent TLS keys in a given process,
1787 * though the first TLSMAP_START keys are reserved for Bionic to hold
1788 * special thread-specific variables like errno or a pointer to
1789 * the current thread's descriptor.
1790 *
1791 * while stored in the TLS area, these entries cannot be accessed through
1792 * pthread_getspecific() / pthread_setspecific() and pthread_key_delete()
1793 *
1794 * also, some entries in the key table are pre-allocated (see tlsmap_lock)
1795 * to greatly simplify and speedup some OpenGL-related operations. though the
1796 * initialy value will be NULL on all threads.
1797 *
1798 * you can use pthread_getspecific()/setspecific() on these, and in theory
1799 * you could also call pthread_key_delete() as well, though this would
1800 * probably break some apps.
1801 *
1802 * The 'tlsmap_t' type defined below implements a shared global map of
1803 * currently created/allocated TLS keys and the destructors associated
1804 * with them. You should use tlsmap_lock/unlock to access it to avoid
1805 * any race condition.
1806 *
1807 * the global TLS map simply contains a bitmap of allocated keys, and
1808 * an array of destructors.
1809 *
1810 * each thread has a TLS area that is a simple array of TLSMAP_SIZE void*
1811 * pointers. the TLS area of the main thread is stack-allocated in
1812 * __libc_init_common, while the TLS area of other threads is placed at
1813 * the top of their stack in pthread_create.
1814 *
1815 * when pthread_key_create() is called, it finds the first free key in the
1816 * bitmap, then set it to 1, saving the destructor altogether
1817 *
1818 * when pthread_key_delete() is called. it will erase the key's bitmap bit
1819 * and its destructor, and will also clear the key data in the TLS area of
1820 * all created threads. As mandated by Posix, it is the responsability of
1821 * the caller of pthread_key_delete() to properly reclaim the objects that
1822 * were pointed to by these data fields (either before or after the call).
1823 *
1824 */
1825
1826/* TLS Map implementation
1827 */
1828
1829#define TLSMAP_START (TLS_SLOT_MAX_WELL_KNOWN+1)
1830#define TLSMAP_SIZE BIONIC_TLS_SLOTS
1831#define TLSMAP_BITS 32
1832#define TLSMAP_WORDS ((TLSMAP_SIZE+TLSMAP_BITS-1)/TLSMAP_BITS)
1833#define TLSMAP_WORD(m,k) (m)->map[(k)/TLSMAP_BITS]
1834#define TLSMAP_MASK(k) (1U << ((k)&(TLSMAP_BITS-1)))
1835
1836/* this macro is used to quickly check that a key belongs to a reasonable range */
1837#define TLSMAP_VALIDATE_KEY(key) \
1838 ((key) >= TLSMAP_START && (key) < TLSMAP_SIZE)
1839
1840/* the type of tls key destructor functions */
1841typedef void (*tls_dtor_t)(void*);
1842
1843typedef struct {
1844 int init; /* see comment in tlsmap_lock() */
1845 uint32_t map[TLSMAP_WORDS]; /* bitmap of allocated keys */
1846 tls_dtor_t dtors[TLSMAP_SIZE]; /* key destructors */
1847} tlsmap_t;
1848
1849static pthread_mutex_t _tlsmap_lock = PTHREAD_MUTEX_INITIALIZER;
1850static tlsmap_t _tlsmap;
1851
1852/* lock the global TLS map lock and return a handle to it */
1853static __inline__ tlsmap_t* tlsmap_lock(void)
1854{
1855 tlsmap_t* m = &_tlsmap;
1856
1857 pthread_mutex_lock(&_tlsmap_lock);
1858 /* we need to initialize the first entry of the 'map' array
1859 * with the value TLS_DEFAULT_ALLOC_MAP. doing it statically
1860 * when declaring _tlsmap is a bit awkward and is going to
1861 * produce warnings, so do it the first time we use the map
1862 * instead
1863 */
1864 if (__unlikely(!m->init)) {
1865 TLSMAP_WORD(m,0) = TLS_DEFAULT_ALLOC_MAP;
1866 m->init = 1;
1867 }
1868 return m;
1869}
1870
1871/* unlock the global TLS map */
1872static __inline__ void tlsmap_unlock(tlsmap_t* m)
1873{
1874 pthread_mutex_unlock(&_tlsmap_lock);
1875 (void)m; /* a good compiler is a happy compiler */
1876}
1877
1878/* test to see wether a key is allocated */
1879static __inline__ int tlsmap_test(tlsmap_t* m, int key)
1880{
1881 return (TLSMAP_WORD(m,key) & TLSMAP_MASK(key)) != 0;
1882}
1883
1884/* set the destructor and bit flag on a newly allocated key */
1885static __inline__ void tlsmap_set(tlsmap_t* m, int key, tls_dtor_t dtor)
1886{
1887 TLSMAP_WORD(m,key) |= TLSMAP_MASK(key);
1888 m->dtors[key] = dtor;
1889}
1890
1891/* clear the destructor and bit flag on an existing key */
1892static __inline__ void tlsmap_clear(tlsmap_t* m, int key)
1893{
1894 TLSMAP_WORD(m,key) &= ~TLSMAP_MASK(key);
1895 m->dtors[key] = NULL;
1896}
1897
1898/* allocate a new TLS key, return -1 if no room left */
1899static int tlsmap_alloc(tlsmap_t* m, tls_dtor_t dtor)
1900{
1901 int key;
1902
1903 for ( key = TLSMAP_START; key < TLSMAP_SIZE; key++ ) {
1904 if ( !tlsmap_test(m, key) ) {
1905 tlsmap_set(m, key, dtor);
1906 return key;
1907 }
1908 }
1909 return -1;
1910}
1911
1912
1913int pthread_key_create(pthread_key_t *key, void (*destructor_function)(void *))
1914{
1915 uint32_t err = ENOMEM;
1916 tlsmap_t* map = tlsmap_lock();
1917 int k = tlsmap_alloc(map, destructor_function);
1918
1919 if (k >= 0) {
1920 *key = k;
1921 err = 0;
1922 }
1923 tlsmap_unlock(map);
1924 return err;
1925}
1926
1927
1928/* This deletes a pthread_key_t. note that the standard mandates that this does
1929 * not call the destructor of non-NULL key values. Instead, it is the
Elliott Hughesbfeab1b2012-09-05 17:47:37 -07001930 * responsibility of the caller to properly dispose of the corresponding data
1931 * and resources, using any means it finds suitable.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001932 *
1933 * On the other hand, this function will clear the corresponding key data
1934 * values in all known threads. this prevents later (invalid) calls to
1935 * pthread_getspecific() to receive invalid/stale values.
1936 */
1937int pthread_key_delete(pthread_key_t key)
1938{
1939 uint32_t err;
1940 pthread_internal_t* thr;
1941 tlsmap_t* map;
1942
1943 if (!TLSMAP_VALIDATE_KEY(key)) {
1944 return EINVAL;
1945 }
1946
1947 map = tlsmap_lock();
1948
1949 if (!tlsmap_test(map, key)) {
1950 err = EINVAL;
1951 goto err1;
1952 }
1953
1954 /* clear value in all threads */
1955 pthread_mutex_lock(&gThreadListLock);
1956 for ( thr = gThreadList; thr != NULL; thr = thr->next ) {
1957 /* avoid zombie threads with a negative 'join_count'. these are really
1958 * already dead and don't have a TLS area anymore.
1959 *
1960 * similarly, it is possible to have thr->tls == NULL for threads that
1961 * were just recently created through pthread_create() but whose
1962 * startup trampoline (__thread_entry) hasn't been run yet by the
Bjorn Andersson0753dc62012-05-03 17:12:39 -07001963 * scheduler. thr->tls will also be NULL after it's stack has been
1964 * unmapped but before the ongoing pthread_join() is finished.
1965 * so check for this too.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001966 */
1967 if (thr->join_count < 0 || !thr->tls)
1968 continue;
1969
1970 thr->tls[key] = NULL;
1971 }
1972 tlsmap_clear(map, key);
1973
1974 pthread_mutex_unlock(&gThreadListLock);
1975 err = 0;
1976
1977err1:
1978 tlsmap_unlock(map);
1979 return err;
1980}
1981
1982
1983int pthread_setspecific(pthread_key_t key, const void *ptr)
1984{
1985 int err = EINVAL;
1986 tlsmap_t* map;
1987
1988 if (TLSMAP_VALIDATE_KEY(key)) {
1989 /* check that we're trying to set data for an allocated key */
1990 map = tlsmap_lock();
1991 if (tlsmap_test(map, key)) {
1992 ((uint32_t *)__get_tls())[key] = (uint32_t)ptr;
1993 err = 0;
1994 }
1995 tlsmap_unlock(map);
1996 }
1997 return err;
1998}
1999
2000void * pthread_getspecific(pthread_key_t key)
2001{
2002 if (!TLSMAP_VALIDATE_KEY(key)) {
2003 return NULL;
2004 }
2005
2006 /* for performance reason, we do not lock/unlock the global TLS map
2007 * to check that the key is properly allocated. if the key was not
2008 * allocated, the value read from the TLS should always be NULL
2009 * due to pthread_key_delete() clearing the values for all threads.
2010 */
2011 return (void *)(((unsigned *)__get_tls())[key]);
2012}
2013
2014/* Posix mandates that this be defined in <limits.h> but we don't have
2015 * it just yet.
2016 */
2017#ifndef PTHREAD_DESTRUCTOR_ITERATIONS
2018# define PTHREAD_DESTRUCTOR_ITERATIONS 4
2019#endif
2020
2021/* this function is called from pthread_exit() to remove all TLS key data
2022 * from this thread's TLS area. this must call the destructor of all keys
2023 * that have a non-NULL data value (and a non-NULL destructor).
2024 *
2025 * because destructors can do funky things like deleting/creating other
2026 * keys, we need to implement this in a loop
2027 */
2028static void pthread_key_clean_all(void)
2029{
2030 tlsmap_t* map;
2031 void** tls = (void**)__get_tls();
2032 int rounds = PTHREAD_DESTRUCTOR_ITERATIONS;
2033
2034 map = tlsmap_lock();
2035
2036 for (rounds = PTHREAD_DESTRUCTOR_ITERATIONS; rounds > 0; rounds--)
2037 {
2038 int kk, count = 0;
2039
2040 for (kk = TLSMAP_START; kk < TLSMAP_SIZE; kk++) {
2041 if ( tlsmap_test(map, kk) )
2042 {
2043 void* data = tls[kk];
2044 tls_dtor_t dtor = map->dtors[kk];
2045
2046 if (data != NULL && dtor != NULL)
2047 {
2048 /* we need to clear the key data now, this will prevent the
2049 * destructor (or a later one) from seeing the old value if
2050 * it calls pthread_getspecific() for some odd reason
2051 *
2052 * we do not do this if 'dtor == NULL' just in case another
2053 * destructor function might be responsible for manually
2054 * releasing the corresponding data.
2055 */
2056 tls[kk] = NULL;
2057
2058 /* because the destructor is free to call pthread_key_create
2059 * and/or pthread_key_delete, we need to temporarily unlock
2060 * the TLS map
2061 */
2062 tlsmap_unlock(map);
2063 (*dtor)(data);
2064 map = tlsmap_lock();
2065
2066 count += 1;
2067 }
2068 }
2069 }
2070
2071 /* if we didn't call any destructor, there is no need to check the
2072 * TLS data again
2073 */
2074 if (count == 0)
2075 break;
2076 }
2077 tlsmap_unlock(map);
2078}
2079
2080// man says this should be in <linux/unistd.h>, but it isn't
Jeff Brown10c8ce52011-11-18 15:17:07 -08002081extern int tgkill(int tgid, int tid, int sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002082
2083int pthread_kill(pthread_t tid, int sig)
2084{
2085 int ret;
2086 int old_errno = errno;
2087 pthread_internal_t * thread = (pthread_internal_t *)tid;
2088
Jeff Brown10c8ce52011-11-18 15:17:07 -08002089 ret = tgkill(getpid(), thread->kernel_id, sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002090 if (ret < 0) {
2091 ret = errno;
2092 errno = old_errno;
2093 }
2094
2095 return ret;
2096}
2097
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002098
2099int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
2100{
2101 const int CLOCK_IDTYPE_BITS = 3;
2102 pthread_internal_t* thread = (pthread_internal_t*)tid;
2103
2104 if (!thread)
2105 return ESRCH;
2106
2107 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
2108 return 0;
2109}
2110
2111
2112/* NOTE: this implementation doesn't support a init function that throws a C++ exception
2113 * or calls fork()
2114 */
2115int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
2116{
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07002117 volatile pthread_once_t* ocptr = once_control;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002118
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002119 /* PTHREAD_ONCE_INIT is 0, we use the following bit flags
2120 *
2121 * bit 0 set -> initialization is under way
2122 * bit 1 set -> initialization is complete
2123 */
2124#define ONCE_INITIALIZING (1 << 0)
2125#define ONCE_COMPLETED (1 << 1)
2126
2127 /* First check if the once is already initialized. This will be the common
2128 * case and we want to make this as fast as possible. Note that this still
2129 * requires a load_acquire operation here to ensure that all the
2130 * stores performed by the initialization function are observable on
2131 * this CPU after we exit.
2132 */
2133 if (__likely((*ocptr & ONCE_COMPLETED) != 0)) {
2134 ANDROID_MEMBAR_FULL();
2135 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002136 }
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002137
2138 for (;;) {
2139 /* Try to atomically set the INITIALIZING flag.
2140 * This requires a cmpxchg loop, and we may need
Elliott Hughesbfeab1b2012-09-05 17:47:37 -07002141 * to exit prematurely if we detect that
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002142 * COMPLETED is now set.
2143 */
2144 int32_t oldval, newval;
2145
2146 do {
2147 oldval = *ocptr;
2148 if ((oldval & ONCE_COMPLETED) != 0)
2149 break;
2150
2151 newval = oldval | ONCE_INITIALIZING;
2152 } while (__bionic_cmpxchg(oldval, newval, ocptr) != 0);
2153
2154 if ((oldval & ONCE_COMPLETED) != 0) {
2155 /* We detected that COMPLETED was set while in our loop */
2156 ANDROID_MEMBAR_FULL();
2157 return 0;
2158 }
2159
2160 if ((oldval & ONCE_INITIALIZING) == 0) {
2161 /* We got there first, we can jump out of the loop to
2162 * handle the initialization */
2163 break;
2164 }
2165
2166 /* Another thread is running the initialization and hasn't completed
2167 * yet, so wait for it, then try again. */
2168 __futex_wait_ex(ocptr, 0, oldval, NULL);
2169 }
2170
2171 /* call the initialization function. */
2172 (*init_routine)();
2173
2174 /* Do a store_release indicating that initialization is complete */
2175 ANDROID_MEMBAR_FULL();
2176 *ocptr = ONCE_COMPLETED;
2177
2178 /* Wake up any waiters, if any */
2179 __futex_wake_ex(ocptr, 0, INT_MAX);
2180
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002181 return 0;
2182}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03002183
2184/* This value is not exported by kernel headers, so hardcode it here */
2185#define MAX_TASK_COMM_LEN 16
2186#define TASK_COMM_FMT "/proc/self/task/%u/comm"
2187
2188int pthread_setname_np(pthread_t thid, const char *thname)
2189{
2190 size_t thname_len;
2191 int saved_errno, ret;
2192
2193 if (thid == 0 || thname == NULL)
2194 return EINVAL;
2195
2196 thname_len = strlen(thname);
2197 if (thname_len >= MAX_TASK_COMM_LEN)
2198 return ERANGE;
2199
2200 saved_errno = errno;
2201 if (thid == pthread_self())
2202 {
2203 ret = prctl(PR_SET_NAME, (unsigned long)thname, 0, 0, 0) ? errno : 0;
2204 }
2205 else
2206 {
2207 /* Have to change another thread's name */
2208 pthread_internal_t *thread = (pthread_internal_t *)thid;
2209 char comm_name[sizeof(TASK_COMM_FMT) + 8];
2210 ssize_t n;
2211 int fd;
2212
2213 snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, (unsigned int)thread->kernel_id);
2214 fd = open(comm_name, O_RDWR);
2215 if (fd == -1)
2216 {
2217 ret = errno;
2218 goto exit;
2219 }
2220 n = TEMP_FAILURE_RETRY(write(fd, thname, thname_len));
2221 close(fd);
2222
2223 if (n < 0)
2224 ret = errno;
2225 else if ((size_t)n != thname_len)
2226 ret = EIO;
2227 else
2228 ret = 0;
2229 }
2230exit:
2231 errno = saved_errno;
2232 return ret;
2233}
Glenn Kastend53cae02011-07-11 15:41:28 -07002234
2235/* Return the kernel thread ID for a pthread.
2236 * This is only defined for implementations where pthread <-> kernel is 1:1, which this is.
2237 * Not the same as pthread_getthreadid_np, which is commonly defined to be opaque.
2238 * Internal, not an NDK API.
2239 */
2240
2241pid_t __pthread_gettid(pthread_t thid)
2242{
2243 pthread_internal_t* thread = (pthread_internal_t*)thid;
2244 return thread->kernel_id;
2245}
Jean-Baptiste Querufaca92f2012-03-26 15:25:19 -07002246
2247int __pthread_settid(pthread_t thid, pid_t tid)
2248{
2249 if (thid == 0)
2250 return EINVAL;
2251
2252 pthread_internal_t* thread = (pthread_internal_t*)thid;
2253 thread->kernel_id = tid;
2254
2255 return 0;
2256}