blob: b685f2dcd462c86a2b5b697601de46900a5ed720 [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
453int pthread_attr_setstackaddr(pthread_attr_t * attr, void * stack_addr)
454{
455#if 1
456 // It's not clear if this is setting the top or bottom of the stack, so don't handle it for now.
457 return ENOSYS;
458#else
459 if ((uint32_t)stack_addr & (PAGE_SIZE - 1)) {
460 return EINVAL;
461 }
462 attr->stack_base = stack_addr;
463 return 0;
464#endif
465}
466
467int pthread_attr_getstackaddr(pthread_attr_t const * attr, void ** stack_addr)
468{
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700469 *stack_addr = (char*)attr->stack_base + attr->stack_size;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800470 return 0;
471}
472
473int pthread_attr_setstack(pthread_attr_t * attr, void * stack_base, size_t stack_size)
474{
475 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
476 return EINVAL;
477 }
478 if ((uint32_t)stack_base & (PAGE_SIZE - 1)) {
479 return EINVAL;
480 }
481 attr->stack_base = stack_base;
482 attr->stack_size = stack_size;
483 return 0;
484}
485
486int pthread_attr_getstack(pthread_attr_t const * attr, void ** stack_base, size_t * stack_size)
487{
488 *stack_base = attr->stack_base;
489 *stack_size = attr->stack_size;
490 return 0;
491}
492
493int pthread_attr_setguardsize(pthread_attr_t * attr, size_t guard_size)
494{
495 if (guard_size & (PAGE_SIZE - 1) || guard_size < PAGE_SIZE) {
496 return EINVAL;
497 }
498
499 attr->guard_size = guard_size;
500 return 0;
501}
502
503int pthread_attr_getguardsize(pthread_attr_t const * attr, size_t * guard_size)
504{
505 *guard_size = attr->guard_size;
506 return 0;
507}
508
509int pthread_getattr_np(pthread_t thid, pthread_attr_t * attr)
510{
511 pthread_internal_t * thread = (pthread_internal_t *)thid;
512 *attr = thread->attr;
513 return 0;
514}
515
516int pthread_attr_setscope(pthread_attr_t *attr, int scope)
517{
518 if (scope == PTHREAD_SCOPE_SYSTEM)
519 return 0;
520 if (scope == PTHREAD_SCOPE_PROCESS)
521 return ENOTSUP;
522
523 return EINVAL;
524}
525
526int pthread_attr_getscope(pthread_attr_t const *attr)
527{
528 return PTHREAD_SCOPE_SYSTEM;
529}
530
531
532/* CAVEAT: our implementation of pthread_cleanup_push/pop doesn't support C++ exceptions
533 * and thread cancelation
534 */
535
536void __pthread_cleanup_push( __pthread_cleanup_t* c,
537 __pthread_cleanup_func_t routine,
538 void* arg )
539{
540 pthread_internal_t* thread = __get_thread();
541
542 c->__cleanup_routine = routine;
543 c->__cleanup_arg = arg;
544 c->__cleanup_prev = thread->cleanup_stack;
545 thread->cleanup_stack = c;
546}
547
548void __pthread_cleanup_pop( __pthread_cleanup_t* c, int execute )
549{
550 pthread_internal_t* thread = __get_thread();
551
552 thread->cleanup_stack = c->__cleanup_prev;
553 if (execute)
554 c->__cleanup_routine(c->__cleanup_arg);
555}
556
557/* used by pthread_exit() to clean all TLS keys of the current thread */
558static void pthread_key_clean_all(void);
559
560void pthread_exit(void * retval)
561{
562 pthread_internal_t* thread = __get_thread();
563 void* stack_base = thread->attr.stack_base;
564 int stack_size = thread->attr.stack_size;
565 int user_stack = (thread->attr.flags & PTHREAD_ATTR_FLAG_USER_STACK) != 0;
Jack Rene480fc82011-09-21 12:44:11 +0200566 sigset_t mask;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800567
568 // call the cleanup handlers first
569 while (thread->cleanup_stack) {
570 __pthread_cleanup_t* c = thread->cleanup_stack;
571 thread->cleanup_stack = c->__cleanup_prev;
572 c->__cleanup_routine(c->__cleanup_arg);
573 }
574
575 // call the TLS destructors, it is important to do that before removing this
576 // thread from the global list. this will ensure that if someone else deletes
577 // a TLS key, the corresponding value will be set to NULL in this thread's TLS
578 // space (see pthread_key_delete)
579 pthread_key_clean_all();
580
581 // if the thread is detached, destroy the pthread_internal_t
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400582 // otherwise, keep it in memory and signal any joiners.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800583 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
584 _pthread_internal_remove(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800585 } else {
Bjorn Andersson0753dc62012-05-03 17:12:39 -0700586 pthread_mutex_lock(&gThreadListLock);
587
588 /* make sure that the thread struct doesn't have stale pointers to a stack that
589 * will be unmapped after the exit call below.
590 */
591 if (!user_stack) {
592 thread->attr.stack_base = NULL;
593 thread->attr.stack_size = 0;
594 thread->tls = NULL;
595 }
596
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800597 /* the join_count field is used to store the number of threads waiting for
598 * the termination of this thread with pthread_join(),
599 *
600 * if it is positive we need to signal the waiters, and we do not touch
601 * the count (it will be decremented by the waiters, the last one will
602 * also remove/free the thread structure
603 *
604 * if it is zero, we set the count value to -1 to indicate that the
605 * thread is in 'zombie' state: it has stopped executing, and its stack
606 * is gone (as well as its TLS area). when another thread calls pthread_join()
607 * on it, it will immediately free the thread and return.
608 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800609 thread->return_value = retval;
610 if (thread->join_count > 0) {
611 pthread_cond_broadcast(&thread->join_cond);
612 } else {
613 thread->join_count = -1; /* zombie thread */
614 }
615 pthread_mutex_unlock(&gThreadListLock);
616 }
617
Jack Rene480fc82011-09-21 12:44:11 +0200618 sigfillset(&mask);
619 sigdelset(&mask, SIGSEGV);
620 (void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *)NULL);
621
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800622 // destroy the thread stack
623 if (user_stack)
624 _exit_thread((int)retval);
625 else
626 _exit_with_stack_teardown(stack_base, stack_size, (int)retval);
627}
628
629int pthread_join(pthread_t thid, void ** ret_val)
630{
631 pthread_internal_t* thread = (pthread_internal_t*)thid;
Elliott Hughes14f19592012-10-29 10:19:44 -0700632 if (thid == pthread_self()) {
633 return EDEADLK;
634 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800635
636 // check that the thread still exists and is not detached
637 pthread_mutex_lock(&gThreadListLock);
638
Elliott Hughes14f19592012-10-29 10:19:44 -0700639 for (thread = gThreadList; thread != NULL; thread = thread->next) {
640 if (thread == (pthread_internal_t*)thid) {
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200641 goto FoundIt;
Elliott Hughes14f19592012-10-29 10:19:44 -0700642 }
643 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800644
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200645 pthread_mutex_unlock(&gThreadListLock);
646 return ESRCH;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800647
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200648FoundIt:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800649 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
650 pthread_mutex_unlock(&gThreadListLock);
651 return EINVAL;
652 }
653
654 /* wait for thread death when needed
655 *
656 * if the 'join_count' is negative, this is a 'zombie' thread that
657 * is already dead and without stack/TLS
658 *
659 * otherwise, we need to increment 'join-count' and wait to be signaled
660 */
Elliott Hughes14f19592012-10-29 10:19:44 -0700661 int count = thread->join_count;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800662 if (count >= 0) {
663 thread->join_count += 1;
664 pthread_cond_wait( &thread->join_cond, &gThreadListLock );
665 count = --thread->join_count;
666 }
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400667 if (ret_val) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800668 *ret_val = thread->return_value;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400669 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800670
671 /* remove thread descriptor when we're the last joiner or when the
672 * thread was already a zombie.
673 */
674 if (count <= 0) {
675 _pthread_internal_remove_locked(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800676 }
677 pthread_mutex_unlock(&gThreadListLock);
678 return 0;
679}
680
681int pthread_detach( pthread_t thid )
682{
683 pthread_internal_t* thread;
684 int result = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800685
686 pthread_mutex_lock(&gThreadListLock);
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400687 for (thread = gThreadList; thread != NULL; thread = thread->next) {
688 if (thread == (pthread_internal_t*)thid) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800689 goto FoundIt;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400690 }
691 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800692
693 result = ESRCH;
694 goto Exit;
695
696FoundIt:
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400697 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
698 result = EINVAL; // Already detached.
699 goto Exit;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800700 }
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400701
702 if (thread->join_count > 0) {
703 result = 0; // Already being joined; silently do nothing, like glibc.
704 goto Exit;
705 }
706
707 thread->attr.flags |= PTHREAD_ATTR_FLAG_DETACHED;
708
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800709Exit:
710 pthread_mutex_unlock(&gThreadListLock);
711 return result;
712}
713
714pthread_t pthread_self(void)
715{
716 return (pthread_t)__get_thread();
717}
718
719int pthread_equal(pthread_t one, pthread_t two)
720{
721 return (one == two ? 1 : 0);
722}
723
724int pthread_getschedparam(pthread_t thid, int * policy,
725 struct sched_param * param)
726{
727 int old_errno = errno;
728
729 pthread_internal_t * thread = (pthread_internal_t *)thid;
730 int err = sched_getparam(thread->kernel_id, param);
731 if (!err) {
732 *policy = sched_getscheduler(thread->kernel_id);
733 } else {
734 err = errno;
735 errno = old_errno;
736 }
737 return err;
738}
739
740int pthread_setschedparam(pthread_t thid, int policy,
741 struct sched_param const * param)
742{
743 pthread_internal_t * thread = (pthread_internal_t *)thid;
744 int old_errno = errno;
745 int ret;
746
747 ret = sched_setscheduler(thread->kernel_id, policy, param);
748 if (ret < 0) {
749 ret = errno;
750 errno = old_errno;
751 }
752 return ret;
753}
754
755
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800756/* a mutex is implemented as a 32-bit integer holding the following fields
757 *
758 * bits: name description
759 * 31-16 tid owner thread's kernel id (recursive and errorcheck only)
760 * 15-14 type mutex type
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700761 * 13 shared process-shared flag
762 * 12-2 counter counter of recursive mutexes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800763 * 1-0 state lock state (0, 1 or 2)
764 */
765
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100766/* Convenience macro, creates a mask of 'bits' bits that starts from
767 * the 'shift'-th least significant bit in a 32-bit word.
768 *
769 * Examples: FIELD_MASK(0,4) -> 0xf
770 * FIELD_MASK(16,9) -> 0x1ff0000
771 */
772#define FIELD_MASK(shift,bits) (((1 << (bits))-1) << (shift))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800773
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100774/* This one is used to create a bit pattern from a given field value */
775#define FIELD_TO_BITS(val,shift,bits) (((val) & ((1 << (bits))-1)) << (shift))
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100776
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100777/* And this one does the opposite, i.e. extract a field's value from a bit pattern */
778#define FIELD_FROM_BITS(val,shift,bits) (((val) >> (shift)) & ((1 << (bits))-1))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800779
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100780/* Mutex state:
781 *
782 * 0 for unlocked
783 * 1 for locked, no waiters
784 * 2 for locked, maybe waiters
785 */
786#define MUTEX_STATE_SHIFT 0
787#define MUTEX_STATE_LEN 2
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800788
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100789#define MUTEX_STATE_MASK FIELD_MASK(MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
790#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
791#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
792
793#define MUTEX_STATE_UNLOCKED 0 /* must be 0 to match __PTHREAD_MUTEX_INIT_VALUE */
794#define MUTEX_STATE_LOCKED_UNCONTENDED 1 /* must be 1 due to atomic dec in unlock operation */
795#define MUTEX_STATE_LOCKED_CONTENDED 2 /* must be 1 + LOCKED_UNCONTENDED due to atomic dec */
796
797#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
798#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
799
800#define MUTEX_STATE_BITS_UNLOCKED MUTEX_STATE_TO_BITS(MUTEX_STATE_UNLOCKED)
801#define MUTEX_STATE_BITS_LOCKED_UNCONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_UNCONTENDED)
802#define MUTEX_STATE_BITS_LOCKED_CONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_CONTENDED)
803
804/* return true iff the mutex if locked with no waiters */
805#define MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_UNCONTENDED)
806
807/* return true iff the mutex if locked with maybe waiters */
808#define MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_CONTENDED)
809
810/* used to flip from LOCKED_UNCONTENDED to LOCKED_CONTENDED */
811#define MUTEX_STATE_BITS_FLIP_CONTENTION(v) ((v) ^ (MUTEX_STATE_BITS_LOCKED_CONTENDED ^ MUTEX_STATE_BITS_LOCKED_UNCONTENDED))
812
813/* Mutex counter:
814 *
815 * We need to check for overflow before incrementing, and we also need to
816 * detect when the counter is 0
817 */
818#define MUTEX_COUNTER_SHIFT 2
819#define MUTEX_COUNTER_LEN 11
820#define MUTEX_COUNTER_MASK FIELD_MASK(MUTEX_COUNTER_SHIFT, MUTEX_COUNTER_LEN)
821
822#define MUTEX_COUNTER_BITS_WILL_OVERFLOW(v) (((v) & MUTEX_COUNTER_MASK) == MUTEX_COUNTER_MASK)
823#define MUTEX_COUNTER_BITS_IS_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
824
825/* Used to increment the counter directly after overflow has been checked */
826#define MUTEX_COUNTER_BITS_ONE FIELD_TO_BITS(1,MUTEX_COUNTER_SHIFT,MUTEX_COUNTER_LEN)
827
828/* Returns true iff the counter is 0 */
829#define MUTEX_COUNTER_BITS_ARE_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
830
831/* Mutex shared bit flag
832 *
833 * This flag is set to indicate that the mutex is shared among processes.
834 * This changes the futex opcode we use for futex wait/wake operations
835 * (non-shared operations are much faster).
836 */
837#define MUTEX_SHARED_SHIFT 13
838#define MUTEX_SHARED_MASK FIELD_MASK(MUTEX_SHARED_SHIFT,1)
839
840/* Mutex type:
841 *
842 * We support normal, recursive and errorcheck mutexes.
843 *
844 * The constants defined here *cannot* be changed because they must match
845 * the C library ABI which defines the following initialization values in
846 * <pthread.h>:
847 *
848 * __PTHREAD_MUTEX_INIT_VALUE
849 * __PTHREAD_RECURSIVE_MUTEX_VALUE
850 * __PTHREAD_ERRORCHECK_MUTEX_INIT_VALUE
851 */
852#define MUTEX_TYPE_SHIFT 14
853#define MUTEX_TYPE_LEN 2
854#define MUTEX_TYPE_MASK FIELD_MASK(MUTEX_TYPE_SHIFT,MUTEX_TYPE_LEN)
855
856#define MUTEX_TYPE_NORMAL 0 /* Must be 0 to match __PTHREAD_MUTEX_INIT_VALUE */
857#define MUTEX_TYPE_RECURSIVE 1
858#define MUTEX_TYPE_ERRORCHECK 2
859
860#define MUTEX_TYPE_TO_BITS(t) FIELD_TO_BITS(t, MUTEX_TYPE_SHIFT, MUTEX_TYPE_LEN)
861
862#define MUTEX_TYPE_BITS_NORMAL MUTEX_TYPE_TO_BITS(MUTEX_TYPE_NORMAL)
863#define MUTEX_TYPE_BITS_RECURSIVE MUTEX_TYPE_TO_BITS(MUTEX_TYPE_RECURSIVE)
864#define MUTEX_TYPE_BITS_ERRORCHECK MUTEX_TYPE_TO_BITS(MUTEX_TYPE_ERRORCHECK)
865
866/* Mutex owner field:
867 *
868 * This is only used for recursive and errorcheck mutexes. It holds the
869 * kernel TID of the owning thread. Note that this works because the Linux
870 * kernel _only_ uses 16-bit values for thread ids.
871 *
872 * More specifically, it will wrap to 10000 when it reaches over 32768 for
873 * application processes. You can check this by running the following inside
874 * an adb shell session:
875 *
876 OLDPID=$$;
877 while true; do
878 NEWPID=$(sh -c 'echo $$')
879 if [ "$NEWPID" -gt 32768 ]; then
880 echo "AARGH: new PID $NEWPID is too high!"
881 exit 1
882 fi
883 if [ "$NEWPID" -lt "$OLDPID" ]; then
884 echo "****** Wrapping from PID $OLDPID to $NEWPID. *******"
885 else
886 echo -n "$NEWPID!"
887 fi
888 OLDPID=$NEWPID
889 done
890
891 * Note that you can run the same example on a desktop Linux system,
892 * the wrapping will also happen at 32768, but will go back to 300 instead.
893 */
894#define MUTEX_OWNER_SHIFT 16
895#define MUTEX_OWNER_LEN 16
896
897#define MUTEX_OWNER_FROM_BITS(v) FIELD_FROM_BITS(v,MUTEX_OWNER_SHIFT,MUTEX_OWNER_LEN)
898#define MUTEX_OWNER_TO_BITS(v) FIELD_TO_BITS(v,MUTEX_OWNER_SHIFT,MUTEX_OWNER_LEN)
899
900/* Convenience macros.
901 *
902 * These are used to form or modify the bit pattern of a given mutex value
903 */
904
905
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800906
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700907/* a mutex attribute holds the following fields
908 *
909 * bits: name description
910 * 0-3 type type of mutex
911 * 4 shared process-shared flag
912 */
913#define MUTEXATTR_TYPE_MASK 0x000f
914#define MUTEXATTR_SHARED_MASK 0x0010
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800915
916
917int pthread_mutexattr_init(pthread_mutexattr_t *attr)
918{
919 if (attr) {
920 *attr = PTHREAD_MUTEX_DEFAULT;
921 return 0;
922 } else {
923 return EINVAL;
924 }
925}
926
927int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
928{
929 if (attr) {
930 *attr = -1;
931 return 0;
932 } else {
933 return EINVAL;
934 }
935}
936
937int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
938{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700939 if (attr) {
940 int atype = (*attr & MUTEXATTR_TYPE_MASK);
941
942 if (atype >= PTHREAD_MUTEX_NORMAL &&
943 atype <= PTHREAD_MUTEX_ERRORCHECK) {
944 *type = atype;
945 return 0;
946 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800947 }
948 return EINVAL;
949}
950
951int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
952{
953 if (attr && type >= PTHREAD_MUTEX_NORMAL &&
954 type <= PTHREAD_MUTEX_ERRORCHECK ) {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700955 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800956 return 0;
957 }
958 return EINVAL;
959}
960
961/* process-shared mutexes are not supported at the moment */
962
963int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
964{
965 if (!attr)
966 return EINVAL;
967
Mathias Agopianb7681162009-07-13 22:00:33 -0700968 switch (pshared) {
969 case PTHREAD_PROCESS_PRIVATE:
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700970 *attr &= ~MUTEXATTR_SHARED_MASK;
971 return 0;
972
Mathias Agopianb7681162009-07-13 22:00:33 -0700973 case PTHREAD_PROCESS_SHARED:
974 /* our current implementation of pthread actually supports shared
975 * mutexes but won't cleanup if a process dies with the mutex held.
976 * Nevertheless, it's better than nothing. Shared mutexes are used
977 * by surfaceflinger and audioflinger.
978 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700979 *attr |= MUTEXATTR_SHARED_MASK;
Mathias Agopianb7681162009-07-13 22:00:33 -0700980 return 0;
981 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700982 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800983}
984
985int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
986{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700987 if (!attr || !pshared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800988 return EINVAL;
989
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700990 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED
991 : PTHREAD_PROCESS_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800992 return 0;
993}
994
995int pthread_mutex_init(pthread_mutex_t *mutex,
996 const pthread_mutexattr_t *attr)
997{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700998 int value = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800999
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001000 if (mutex == NULL)
1001 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001002
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001003 if (__likely(attr == NULL)) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001004 mutex->value = MUTEX_TYPE_BITS_NORMAL;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001005 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001006 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001007
1008 if ((*attr & MUTEXATTR_SHARED_MASK) != 0)
1009 value |= MUTEX_SHARED_MASK;
1010
1011 switch (*attr & MUTEXATTR_TYPE_MASK) {
1012 case PTHREAD_MUTEX_NORMAL:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001013 value |= MUTEX_TYPE_BITS_NORMAL;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001014 break;
1015 case PTHREAD_MUTEX_RECURSIVE:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001016 value |= MUTEX_TYPE_BITS_RECURSIVE;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001017 break;
1018 case PTHREAD_MUTEX_ERRORCHECK:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001019 value |= MUTEX_TYPE_BITS_ERRORCHECK;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001020 break;
1021 default:
1022 return EINVAL;
1023 }
1024
1025 mutex->value = value;
1026 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001027}
1028
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001029
1030/*
1031 * Lock a non-recursive mutex.
1032 *
1033 * As noted above, there are three states:
1034 * 0 (unlocked, no contention)
1035 * 1 (locked, no contention)
1036 * 2 (locked, contention)
1037 *
1038 * Non-recursive mutexes don't use the thread-id or counter fields, and the
1039 * "type" value is zero, so the only bits that will be set are the ones in
1040 * the lock state field.
1041 */
1042static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001043_normal_lock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001044{
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001045 /* convenience shortcuts */
1046 const int unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
1047 const int locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001048 /*
1049 * The common case is an unlocked mutex, so we begin by trying to
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001050 * change the lock's state from 0 (UNLOCKED) to 1 (LOCKED).
1051 * __bionic_cmpxchg() returns 0 if it made the swap successfully.
1052 * If the result is nonzero, this lock is already held by another thread.
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001053 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001054 if (__bionic_cmpxchg(unlocked, locked_uncontended, &mutex->value) != 0) {
1055 const int locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001056 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001057 * We want to go to sleep until the mutex is available, which
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001058 * requires promoting it to state 2 (CONTENDED). We need to
1059 * swap in the new state value and then wait until somebody wakes us up.
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001060 *
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001061 * __bionic_swap() returns the previous value. We swap 2 in and
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001062 * see if we got zero back; if so, we have acquired the lock. If
1063 * not, another thread still holds the lock and we wait again.
1064 *
1065 * The second argument to the __futex_wait() call is compared
1066 * against the current value. If it doesn't match, __futex_wait()
1067 * returns immediately (otherwise, it sleeps for a time specified
1068 * by the third argument; 0 means sleep forever). This ensures
1069 * that the mutex is in state 2 when we go to sleep on it, which
1070 * guarantees a wake-up call.
1071 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001072 while (__bionic_swap(locked_contended, &mutex->value) != unlocked)
1073 __futex_wait_ex(&mutex->value, shared, locked_contended, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001074 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001075 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001076}
1077
1078/*
1079 * Release a non-recursive mutex. The caller is responsible for determining
1080 * that we are in fact the owner of this lock.
1081 */
1082static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001083_normal_unlock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001084{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001085 ANDROID_MEMBAR_FULL();
1086
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001087 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001088 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001089 * to release the lock. __bionic_atomic_dec() returns the previous value;
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001090 * if it wasn't 1 we have to do some additional work.
1091 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001092 if (__bionic_atomic_dec(&mutex->value) != (shared|MUTEX_STATE_BITS_LOCKED_UNCONTENDED)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001093 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001094 * Start by releasing the lock. The decrement changed it from
1095 * "contended lock" to "uncontended lock", which means we still
1096 * hold it, and anybody who tries to sneak in will push it back
1097 * to state 2.
1098 *
1099 * Once we set it to zero the lock is up for grabs. We follow
1100 * this with a __futex_wake() to ensure that one of the waiting
1101 * threads has a chance to grab it.
1102 *
1103 * This doesn't cause a race with the swap/wait pair in
1104 * _normal_lock(), because the __futex_wait() call there will
1105 * return immediately if the mutex value isn't 2.
1106 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001107 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001108
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001109 /*
1110 * Wake up one waiting thread. We don't know which thread will be
1111 * woken or when it'll start executing -- futexes make no guarantees
1112 * here. There may not even be a thread waiting.
1113 *
1114 * The newly-woken thread will replace the 0 we just set above
1115 * with 2, which means that when it eventually releases the mutex
1116 * it will also call FUTEX_WAKE. This results in one extra wake
1117 * call whenever a lock is contended, but lets us avoid forgetting
1118 * anyone without requiring us to track the number of sleepers.
1119 *
1120 * It's possible for another thread to sneak in and grab the lock
1121 * between the zero assignment above and the wake call below. If
1122 * the new thread is "slow" and holds the lock for a while, we'll
1123 * wake up a sleeper, which will swap in a 2 and then go back to
1124 * sleep since the lock is still held. If the new thread is "fast",
1125 * running to completion before we call wake, the thread we
1126 * eventually wake will find an unlocked mutex and will execute.
1127 * Either way we have correct behavior and nobody is orphaned on
1128 * the wait queue.
1129 */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001130 __futex_wake_ex(&mutex->value, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001131 }
1132}
1133
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001134/* This common inlined function is used to increment the counter of an
1135 * errorcheck or recursive mutex.
1136 *
1137 * For errorcheck mutexes, it will return EDEADLK
1138 * If the counter overflows, it will return EAGAIN
1139 * Otherwise, it atomically increments the counter and returns 0
1140 * after providing an acquire barrier.
1141 *
1142 * mtype is the current mutex type
1143 * mvalue is the current mutex value (already loaded)
1144 * mutex pointers to the mutex.
1145 */
1146static __inline__ __attribute__((always_inline)) int
1147_recursive_increment(pthread_mutex_t* mutex, int mvalue, int mtype)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001148{
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001149 if (mtype == MUTEX_TYPE_BITS_ERRORCHECK) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001150 /* trying to re-lock a mutex we already acquired */
1151 return EDEADLK;
1152 }
1153
1154 /* Detect recursive lock overflow and return EAGAIN.
1155 * This is safe because only the owner thread can modify the
David 'Digit' Turnerb57db752012-01-24 13:20:38 +01001156 * counter bits in the mutex value.
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001157 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001158 if (MUTEX_COUNTER_BITS_WILL_OVERFLOW(mvalue)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001159 return EAGAIN;
1160 }
1161
1162 /* We own the mutex, but other threads are able to change
David 'Digit' Turnerb57db752012-01-24 13:20:38 +01001163 * the lower bits (e.g. promoting it to "contended"), so we
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001164 * need to use an atomic cmpxchg loop to update the counter.
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001165 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001166 for (;;) {
1167 /* increment counter, overflow was already checked */
1168 int newval = mvalue + MUTEX_COUNTER_BITS_ONE;
1169 if (__likely(__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0)) {
1170 /* mutex is still locked, not need for a memory barrier */
1171 return 0;
1172 }
1173 /* the value was changed, this happens when another thread changes
1174 * the lower state bits from 1 to 2 to indicate contention. This
1175 * cannot change the counter, so simply reload and try again.
1176 */
1177 mvalue = mutex->value;
1178 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001179}
1180
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001181__LIBC_HIDDEN__
1182int pthread_mutex_lock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001183{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001184 int mvalue, mtype, tid, new_lock_type, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001185
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001186 if (__unlikely(mutex == NULL))
1187 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001188
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001189 mvalue = mutex->value;
1190 mtype = (mvalue & MUTEX_TYPE_MASK);
1191 shared = (mvalue & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001192
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001193 /* Handle normal case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001194 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) ) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001195 _normal_lock(mutex, shared);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001196 return 0;
1197 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001198
1199 /* Do we already own this recursive or error-check mutex ? */
1200 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001201 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001202 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001203
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001204 /* Add in shared state to avoid extra 'or' operations below */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001205 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001206
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001207 /* First, if the mutex is unlocked, try to quickly acquire it.
1208 * In the optimistic case where this works, set the state to 1 to
1209 * indicate locked with no contention */
1210 if (mvalue == mtype) {
1211 int newval = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1212 if (__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0) {
1213 ANDROID_MEMBAR_FULL();
1214 return 0;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001215 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001216 /* argh, the value changed, reload before entering the loop */
1217 mvalue = mutex->value;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001218 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001219
1220 for (;;) {
1221 int newval;
1222
1223 /* if the mutex is unlocked, its value should be 'mtype' and
1224 * we try to acquire it by setting its owner and state atomically.
1225 * NOTE: We put the state to 2 since we _know_ there is contention
1226 * when we are in this loop. This ensures all waiters will be
1227 * unlocked.
1228 */
1229 if (mvalue == mtype) {
1230 newval = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1231 /* TODO: Change this to __bionic_cmpxchg_acquire when we
1232 * implement it to get rid of the explicit memory
1233 * barrier below.
1234 */
1235 if (__unlikely(__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0)) {
1236 mvalue = mutex->value;
1237 continue;
1238 }
1239 ANDROID_MEMBAR_FULL();
1240 return 0;
1241 }
1242
1243 /* the mutex is already locked by another thread, if its state is 1
1244 * we will change it to 2 to indicate contention. */
1245 if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(mvalue)) {
1246 newval = MUTEX_STATE_BITS_FLIP_CONTENTION(mvalue); /* locked state 1 => state 2 */
1247 if (__unlikely(__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0)) {
1248 mvalue = mutex->value;
1249 continue;
1250 }
1251 mvalue = newval;
1252 }
1253
1254 /* wait until the mutex is unlocked */
1255 __futex_wait_ex(&mutex->value, shared, mvalue, NULL);
1256
1257 mvalue = mutex->value;
1258 }
1259 /* NOTREACHED */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001260}
1261
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001262int pthread_mutex_lock(pthread_mutex_t *mutex)
1263{
1264 int err = pthread_mutex_lock_impl(mutex);
1265#ifdef PTHREAD_DEBUG
1266 if (PTHREAD_DEBUG_ENABLED) {
1267 if (!err) {
1268 pthread_debug_mutex_lock_check(mutex);
1269 }
1270 }
1271#endif
1272 return err;
1273}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001274
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001275__LIBC_HIDDEN__
1276int pthread_mutex_unlock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001277{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001278 int mvalue, mtype, tid, oldv, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001279
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001280 if (__unlikely(mutex == NULL))
1281 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001282
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001283 mvalue = mutex->value;
1284 mtype = (mvalue & MUTEX_TYPE_MASK);
1285 shared = (mvalue & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001286
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001287 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001288 if (__likely(mtype == MUTEX_TYPE_BITS_NORMAL)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001289 _normal_unlock(mutex, shared);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001290 return 0;
1291 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001292
1293 /* Do we already own this recursive or error-check mutex ? */
1294 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001295 if ( tid != MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001296 return EPERM;
1297
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001298 /* If the counter is > 0, we can simply decrement it atomically.
1299 * Since other threads can mutate the lower state bits (and only the
1300 * lower state bits), use a cmpxchg to do it.
1301 */
1302 if (!MUTEX_COUNTER_BITS_IS_ZERO(mvalue)) {
1303 for (;;) {
1304 int newval = mvalue - MUTEX_COUNTER_BITS_ONE;
1305 if (__likely(__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0)) {
1306 /* success: we still own the mutex, so no memory barrier */
1307 return 0;
1308 }
1309 /* the value changed, so reload and loop */
1310 mvalue = mutex->value;
1311 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001312 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001313
1314 /* the counter is 0, so we're going to unlock the mutex by resetting
1315 * its value to 'unlocked'. We need to perform a swap in order
1316 * to read the current state, which will be 2 if there are waiters
1317 * to awake.
1318 *
1319 * TODO: Change this to __bionic_swap_release when we implement it
1320 * to get rid of the explicit memory barrier below.
1321 */
1322 ANDROID_MEMBAR_FULL(); /* RELEASE BARRIER */
1323 mvalue = __bionic_swap(mtype | shared | MUTEX_STATE_BITS_UNLOCKED, &mutex->value);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001324
1325 /* Wake one waiting thread, if any */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001326 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(mvalue)) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001327 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001328 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001329 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001330}
1331
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001332int pthread_mutex_unlock(pthread_mutex_t *mutex)
1333{
1334#ifdef PTHREAD_DEBUG
1335 if (PTHREAD_DEBUG_ENABLED) {
1336 pthread_debug_mutex_unlock_check(mutex);
1337 }
1338#endif
1339 return pthread_mutex_unlock_impl(mutex);
1340}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001341
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001342__LIBC_HIDDEN__
1343int pthread_mutex_trylock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001344{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001345 int mvalue, mtype, tid, oldv, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001346
1347 if (__unlikely(mutex == NULL))
1348 return EINVAL;
1349
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001350 mvalue = mutex->value;
1351 mtype = (mvalue & MUTEX_TYPE_MASK);
1352 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001353
1354 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001355 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001356 {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001357 if (__bionic_cmpxchg(shared|MUTEX_STATE_BITS_UNLOCKED,
1358 shared|MUTEX_STATE_BITS_LOCKED_UNCONTENDED,
1359 &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001360 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001361 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001362 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001363
1364 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001365 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001366
1367 /* Do we already own this recursive or error-check mutex ? */
1368 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001369 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001370 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001371
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001372 /* Same as pthread_mutex_lock, except that we don't want to wait, and
1373 * the only operation that can succeed is a single cmpxchg to acquire the
1374 * lock if it is released / not owned by anyone. No need for a complex loop.
1375 */
1376 mtype |= shared | MUTEX_STATE_BITS_UNLOCKED;
1377 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001378
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001379 if (__likely(__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0)) {
1380 ANDROID_MEMBAR_FULL();
1381 return 0;
1382 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001383
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001384 return EBUSY;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001385}
1386
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001387int pthread_mutex_trylock(pthread_mutex_t *mutex)
1388{
1389 int err = pthread_mutex_trylock_impl(mutex);
1390#ifdef PTHREAD_DEBUG
1391 if (PTHREAD_DEBUG_ENABLED) {
1392 if (!err) {
1393 pthread_debug_mutex_lock_check(mutex);
1394 }
1395 }
1396#endif
1397 return err;
1398}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001399
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001400/* initialize 'ts' with the difference between 'abstime' and the current time
1401 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
1402 */
1403static int
1404__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
1405{
1406 clock_gettime(clock, ts);
1407 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
1408 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
1409 if (ts->tv_nsec < 0) {
1410 ts->tv_sec--;
1411 ts->tv_nsec += 1000000000;
1412 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001413 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001414 return -1;
1415
1416 return 0;
1417}
1418
1419/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1420 * milliseconds.
1421 */
1422static void
1423__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1424{
1425 clock_gettime(clock, abstime);
1426 abstime->tv_sec += msecs/1000;
1427 abstime->tv_nsec += (msecs%1000)*1000000;
1428 if (abstime->tv_nsec >= 1000000000) {
1429 abstime->tv_sec++;
1430 abstime->tv_nsec -= 1000000000;
1431 }
1432}
1433
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001434__LIBC_HIDDEN__
1435int pthread_mutex_lock_timeout_np_impl(pthread_mutex_t *mutex, unsigned msecs)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001436{
1437 clockid_t clock = CLOCK_MONOTONIC;
1438 struct timespec abstime;
1439 struct timespec ts;
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001440 int mvalue, mtype, tid, oldv, new_lock_type, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001441
1442 /* compute absolute expiration time */
1443 __timespec_to_relative_msec(&abstime, msecs, clock);
1444
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001445 if (__unlikely(mutex == NULL))
1446 return EINVAL;
1447
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001448 mvalue = mutex->value;
1449 mtype = (mvalue & MUTEX_TYPE_MASK);
1450 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001451
1452 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001453 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001454 {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001455 const int unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
1456 const int locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1457 const int locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1458
1459 /* fast path for uncontended lock. Note: MUTEX_TYPE_BITS_NORMAL is 0 */
1460 if (__bionic_cmpxchg(unlocked, locked_uncontended, &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001461 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001462 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001463 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001464
1465 /* loop while needed */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001466 while (__bionic_swap(locked_contended, &mutex->value) != unlocked) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001467 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1468 return EBUSY;
1469
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001470 __futex_wait_ex(&mutex->value, shared, locked_contended, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001471 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001472 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001473 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001474 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001475
1476 /* Do we already own this recursive or error-check mutex ? */
1477 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001478 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001479 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001480
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001481 /* the following implements the same loop than pthread_mutex_lock_impl
1482 * but adds checks to ensure that the operation never exceeds the
1483 * absolute expiration time.
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001484 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001485 mtype |= shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001486
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001487 /* first try a quick lock */
1488 if (mvalue == mtype) {
1489 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1490 if (__likely(__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0)) {
1491 ANDROID_MEMBAR_FULL();
1492 return 0;
1493 }
1494 mvalue = mutex->value;
1495 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001496
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001497 for (;;) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001498 struct timespec ts;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001499
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001500 /* if the value is 'unlocked', try to acquire it directly */
1501 /* NOTE: put state to 2 since we know there is contention */
1502 if (mvalue == mtype) /* unlocked */ {
1503 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1504 if (__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0) {
1505 ANDROID_MEMBAR_FULL();
1506 return 0;
1507 }
1508 /* the value changed before we could lock it. We need to check
1509 * the time to avoid livelocks, reload the value, then loop again. */
1510 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1511 return EBUSY;
1512
1513 mvalue = mutex->value;
1514 continue;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001515 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001516
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001517 /* The value is locked. If 'uncontended', try to switch its state
1518 * to 'contented' to ensure we get woken up later. */
1519 if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(mvalue)) {
1520 int newval = MUTEX_STATE_BITS_FLIP_CONTENTION(mvalue);
1521 if (__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0) {
1522 /* this failed because the value changed, reload it */
1523 mvalue = mutex->value;
1524 } else {
1525 /* this succeeded, update mvalue */
1526 mvalue = newval;
1527 }
1528 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001529
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001530 /* check time and update 'ts' */
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001531 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1532 return EBUSY;
1533
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001534 /* Only wait to be woken up if the state is '2', otherwise we'll
1535 * simply loop right now. This can happen when the second cmpxchg
1536 * in our loop failed because the mutex was unlocked by another
1537 * thread.
1538 */
1539 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(mvalue)) {
1540 if (__futex_wait_ex(&mutex->value, shared, mvalue, &ts) == ETIMEDOUT) {
1541 return EBUSY;
1542 }
1543 mvalue = mutex->value;
1544 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001545 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001546 /* NOTREACHED */
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001547}
1548
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001549int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1550{
1551 int err = pthread_mutex_lock_timeout_np_impl(mutex, msecs);
1552#ifdef PTHREAD_DEBUG
1553 if (PTHREAD_DEBUG_ENABLED) {
1554 if (!err) {
1555 pthread_debug_mutex_lock_check(mutex);
1556 }
1557 }
1558#endif
1559 return err;
1560}
1561
1562int pthread_mutex_destroy(pthread_mutex_t *mutex)
1563{
1564 int ret;
1565
1566 /* use trylock to ensure that the mutex value is
1567 * valid and is not already locked. */
1568 ret = pthread_mutex_trylock_impl(mutex);
1569 if (ret != 0)
1570 return ret;
1571
1572 mutex->value = 0xdead10cc;
1573 return 0;
1574}
1575
1576
1577
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001578int pthread_condattr_init(pthread_condattr_t *attr)
1579{
1580 if (attr == NULL)
1581 return EINVAL;
1582
1583 *attr = PTHREAD_PROCESS_PRIVATE;
1584 return 0;
1585}
1586
1587int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1588{
1589 if (attr == NULL || pshared == NULL)
1590 return EINVAL;
1591
1592 *pshared = *attr;
1593 return 0;
1594}
1595
1596int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1597{
1598 if (attr == NULL)
1599 return EINVAL;
1600
1601 if (pshared != PTHREAD_PROCESS_SHARED &&
1602 pshared != PTHREAD_PROCESS_PRIVATE)
1603 return EINVAL;
1604
1605 *attr = pshared;
1606 return 0;
1607}
1608
1609int pthread_condattr_destroy(pthread_condattr_t *attr)
1610{
1611 if (attr == NULL)
1612 return EINVAL;
1613
1614 *attr = 0xdeada11d;
1615 return 0;
1616}
1617
1618/* We use one bit in condition variable values as the 'shared' flag
1619 * The rest is a counter.
1620 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001621#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001622#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001623#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1624
1625#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001626
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001627/* XXX *technically* there is a race condition that could allow
1628 * XXX a signal to be missed. If thread A is preempted in _wait()
1629 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001630 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001631 * XXX before thread A is scheduled again and calls futex_wait(),
1632 * XXX then the signal will be lost.
1633 */
1634
1635int pthread_cond_init(pthread_cond_t *cond,
1636 const pthread_condattr_t *attr)
1637{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001638 if (cond == NULL)
1639 return EINVAL;
1640
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001641 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001642
1643 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001644 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001645
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001646 return 0;
1647}
1648
1649int pthread_cond_destroy(pthread_cond_t *cond)
1650{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001651 if (cond == NULL)
1652 return EINVAL;
1653
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001654 cond->value = 0xdeadc04d;
1655 return 0;
1656}
1657
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001658/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001659 * pthread_cond_signal to atomically decrement the counter
1660 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001661 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001662static int
1663__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001664{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001665 long flags;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001666
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001667 if (__unlikely(cond == NULL))
1668 return EINVAL;
1669
1670 flags = (cond->value & ~COND_COUNTER_MASK);
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001671 for (;;) {
1672 long oldval = cond->value;
1673 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1674 | flags;
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001675 if (__bionic_cmpxchg(oldval, newval, &cond->value) == 0)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001676 break;
1677 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001678
Andy McFaddene2ac8982010-09-02 13:34:53 -07001679 /*
1680 * Ensure that all memory accesses previously made by this thread are
1681 * visible to the woken thread(s). On the other side, the "wait"
1682 * code will issue any necessary barriers when locking the mutex.
1683 *
1684 * This may not strictly be necessary -- if the caller follows
1685 * recommended practice and holds the mutex before signaling the cond
1686 * var, the mutex ops will provide correct semantics. If they don't
1687 * hold the mutex, they're subject to race conditions anyway.
1688 */
1689 ANDROID_MEMBAR_FULL();
1690
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001691 __futex_wake_ex(&cond->value, COND_IS_SHARED(cond), counter);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001692 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001693}
1694
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001695int pthread_cond_broadcast(pthread_cond_t *cond)
1696{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001697 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001698}
1699
1700int pthread_cond_signal(pthread_cond_t *cond)
1701{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001702 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001703}
1704
1705int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1706{
1707 return pthread_cond_timedwait(cond, mutex, NULL);
1708}
1709
1710int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1711 pthread_mutex_t * mutex,
1712 const struct timespec *reltime)
1713{
1714 int status;
1715 int oldvalue = cond->value;
1716
1717 pthread_mutex_unlock(mutex);
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001718 status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond), oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001719 pthread_mutex_lock(mutex);
1720
1721 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1722 return 0;
1723}
1724
1725int __pthread_cond_timedwait(pthread_cond_t *cond,
1726 pthread_mutex_t * mutex,
1727 const struct timespec *abstime,
1728 clockid_t clock)
1729{
1730 struct timespec ts;
1731 struct timespec * tsp;
1732
1733 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001734 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001735 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001736 tsp = &ts;
1737 } else {
1738 tsp = NULL;
1739 }
1740
1741 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1742}
1743
1744int pthread_cond_timedwait(pthread_cond_t *cond,
1745 pthread_mutex_t * mutex,
1746 const struct timespec *abstime)
1747{
1748 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1749}
1750
1751
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001752/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001753int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1754 pthread_mutex_t * mutex,
1755 const struct timespec *abstime)
1756{
1757 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1758}
1759
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001760int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1761 pthread_mutex_t * mutex,
1762 const struct timespec *abstime)
1763{
1764 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1765}
1766
1767int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1768 pthread_mutex_t * mutex,
1769 const struct timespec *reltime)
1770{
1771 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1772}
1773
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001774int pthread_cond_timeout_np(pthread_cond_t *cond,
1775 pthread_mutex_t * mutex,
1776 unsigned msecs)
1777{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001778 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001779
1780 ts.tv_sec = msecs / 1000;
1781 ts.tv_nsec = (msecs % 1000) * 1000000;
1782
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001783 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001784}
1785
1786
1787
1788/* A technical note regarding our thread-local-storage (TLS) implementation:
1789 *
1790 * There can be up to TLSMAP_SIZE independent TLS keys in a given process,
1791 * though the first TLSMAP_START keys are reserved for Bionic to hold
1792 * special thread-specific variables like errno or a pointer to
1793 * the current thread's descriptor.
1794 *
1795 * while stored in the TLS area, these entries cannot be accessed through
1796 * pthread_getspecific() / pthread_setspecific() and pthread_key_delete()
1797 *
1798 * also, some entries in the key table are pre-allocated (see tlsmap_lock)
1799 * to greatly simplify and speedup some OpenGL-related operations. though the
1800 * initialy value will be NULL on all threads.
1801 *
1802 * you can use pthread_getspecific()/setspecific() on these, and in theory
1803 * you could also call pthread_key_delete() as well, though this would
1804 * probably break some apps.
1805 *
1806 * The 'tlsmap_t' type defined below implements a shared global map of
1807 * currently created/allocated TLS keys and the destructors associated
1808 * with them. You should use tlsmap_lock/unlock to access it to avoid
1809 * any race condition.
1810 *
1811 * the global TLS map simply contains a bitmap of allocated keys, and
1812 * an array of destructors.
1813 *
1814 * each thread has a TLS area that is a simple array of TLSMAP_SIZE void*
1815 * pointers. the TLS area of the main thread is stack-allocated in
1816 * __libc_init_common, while the TLS area of other threads is placed at
1817 * the top of their stack in pthread_create.
1818 *
1819 * when pthread_key_create() is called, it finds the first free key in the
1820 * bitmap, then set it to 1, saving the destructor altogether
1821 *
1822 * when pthread_key_delete() is called. it will erase the key's bitmap bit
1823 * and its destructor, and will also clear the key data in the TLS area of
1824 * all created threads. As mandated by Posix, it is the responsability of
1825 * the caller of pthread_key_delete() to properly reclaim the objects that
1826 * were pointed to by these data fields (either before or after the call).
1827 *
1828 */
1829
1830/* TLS Map implementation
1831 */
1832
1833#define TLSMAP_START (TLS_SLOT_MAX_WELL_KNOWN+1)
1834#define TLSMAP_SIZE BIONIC_TLS_SLOTS
1835#define TLSMAP_BITS 32
1836#define TLSMAP_WORDS ((TLSMAP_SIZE+TLSMAP_BITS-1)/TLSMAP_BITS)
1837#define TLSMAP_WORD(m,k) (m)->map[(k)/TLSMAP_BITS]
1838#define TLSMAP_MASK(k) (1U << ((k)&(TLSMAP_BITS-1)))
1839
1840/* this macro is used to quickly check that a key belongs to a reasonable range */
1841#define TLSMAP_VALIDATE_KEY(key) \
1842 ((key) >= TLSMAP_START && (key) < TLSMAP_SIZE)
1843
1844/* the type of tls key destructor functions */
1845typedef void (*tls_dtor_t)(void*);
1846
1847typedef struct {
1848 int init; /* see comment in tlsmap_lock() */
1849 uint32_t map[TLSMAP_WORDS]; /* bitmap of allocated keys */
1850 tls_dtor_t dtors[TLSMAP_SIZE]; /* key destructors */
1851} tlsmap_t;
1852
1853static pthread_mutex_t _tlsmap_lock = PTHREAD_MUTEX_INITIALIZER;
1854static tlsmap_t _tlsmap;
1855
1856/* lock the global TLS map lock and return a handle to it */
1857static __inline__ tlsmap_t* tlsmap_lock(void)
1858{
1859 tlsmap_t* m = &_tlsmap;
1860
1861 pthread_mutex_lock(&_tlsmap_lock);
1862 /* we need to initialize the first entry of the 'map' array
1863 * with the value TLS_DEFAULT_ALLOC_MAP. doing it statically
1864 * when declaring _tlsmap is a bit awkward and is going to
1865 * produce warnings, so do it the first time we use the map
1866 * instead
1867 */
1868 if (__unlikely(!m->init)) {
1869 TLSMAP_WORD(m,0) = TLS_DEFAULT_ALLOC_MAP;
1870 m->init = 1;
1871 }
1872 return m;
1873}
1874
1875/* unlock the global TLS map */
1876static __inline__ void tlsmap_unlock(tlsmap_t* m)
1877{
1878 pthread_mutex_unlock(&_tlsmap_lock);
1879 (void)m; /* a good compiler is a happy compiler */
1880}
1881
1882/* test to see wether a key is allocated */
1883static __inline__ int tlsmap_test(tlsmap_t* m, int key)
1884{
1885 return (TLSMAP_WORD(m,key) & TLSMAP_MASK(key)) != 0;
1886}
1887
1888/* set the destructor and bit flag on a newly allocated key */
1889static __inline__ void tlsmap_set(tlsmap_t* m, int key, tls_dtor_t dtor)
1890{
1891 TLSMAP_WORD(m,key) |= TLSMAP_MASK(key);
1892 m->dtors[key] = dtor;
1893}
1894
1895/* clear the destructor and bit flag on an existing key */
1896static __inline__ void tlsmap_clear(tlsmap_t* m, int key)
1897{
1898 TLSMAP_WORD(m,key) &= ~TLSMAP_MASK(key);
1899 m->dtors[key] = NULL;
1900}
1901
1902/* allocate a new TLS key, return -1 if no room left */
1903static int tlsmap_alloc(tlsmap_t* m, tls_dtor_t dtor)
1904{
1905 int key;
1906
1907 for ( key = TLSMAP_START; key < TLSMAP_SIZE; key++ ) {
1908 if ( !tlsmap_test(m, key) ) {
1909 tlsmap_set(m, key, dtor);
1910 return key;
1911 }
1912 }
1913 return -1;
1914}
1915
1916
1917int pthread_key_create(pthread_key_t *key, void (*destructor_function)(void *))
1918{
1919 uint32_t err = ENOMEM;
1920 tlsmap_t* map = tlsmap_lock();
1921 int k = tlsmap_alloc(map, destructor_function);
1922
1923 if (k >= 0) {
1924 *key = k;
1925 err = 0;
1926 }
1927 tlsmap_unlock(map);
1928 return err;
1929}
1930
1931
1932/* This deletes a pthread_key_t. note that the standard mandates that this does
1933 * not call the destructor of non-NULL key values. Instead, it is the
Elliott Hughesbfeab1b2012-09-05 17:47:37 -07001934 * responsibility of the caller to properly dispose of the corresponding data
1935 * and resources, using any means it finds suitable.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001936 *
1937 * On the other hand, this function will clear the corresponding key data
1938 * values in all known threads. this prevents later (invalid) calls to
1939 * pthread_getspecific() to receive invalid/stale values.
1940 */
1941int pthread_key_delete(pthread_key_t key)
1942{
1943 uint32_t err;
1944 pthread_internal_t* thr;
1945 tlsmap_t* map;
1946
1947 if (!TLSMAP_VALIDATE_KEY(key)) {
1948 return EINVAL;
1949 }
1950
1951 map = tlsmap_lock();
1952
1953 if (!tlsmap_test(map, key)) {
1954 err = EINVAL;
1955 goto err1;
1956 }
1957
1958 /* clear value in all threads */
1959 pthread_mutex_lock(&gThreadListLock);
1960 for ( thr = gThreadList; thr != NULL; thr = thr->next ) {
1961 /* avoid zombie threads with a negative 'join_count'. these are really
1962 * already dead and don't have a TLS area anymore.
1963 *
1964 * similarly, it is possible to have thr->tls == NULL for threads that
1965 * were just recently created through pthread_create() but whose
1966 * startup trampoline (__thread_entry) hasn't been run yet by the
Bjorn Andersson0753dc62012-05-03 17:12:39 -07001967 * scheduler. thr->tls will also be NULL after it's stack has been
1968 * unmapped but before the ongoing pthread_join() is finished.
1969 * so check for this too.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001970 */
1971 if (thr->join_count < 0 || !thr->tls)
1972 continue;
1973
1974 thr->tls[key] = NULL;
1975 }
1976 tlsmap_clear(map, key);
1977
1978 pthread_mutex_unlock(&gThreadListLock);
1979 err = 0;
1980
1981err1:
1982 tlsmap_unlock(map);
1983 return err;
1984}
1985
1986
1987int pthread_setspecific(pthread_key_t key, const void *ptr)
1988{
1989 int err = EINVAL;
1990 tlsmap_t* map;
1991
1992 if (TLSMAP_VALIDATE_KEY(key)) {
1993 /* check that we're trying to set data for an allocated key */
1994 map = tlsmap_lock();
1995 if (tlsmap_test(map, key)) {
1996 ((uint32_t *)__get_tls())[key] = (uint32_t)ptr;
1997 err = 0;
1998 }
1999 tlsmap_unlock(map);
2000 }
2001 return err;
2002}
2003
2004void * pthread_getspecific(pthread_key_t key)
2005{
2006 if (!TLSMAP_VALIDATE_KEY(key)) {
2007 return NULL;
2008 }
2009
2010 /* for performance reason, we do not lock/unlock the global TLS map
2011 * to check that the key is properly allocated. if the key was not
2012 * allocated, the value read from the TLS should always be NULL
2013 * due to pthread_key_delete() clearing the values for all threads.
2014 */
2015 return (void *)(((unsigned *)__get_tls())[key]);
2016}
2017
2018/* Posix mandates that this be defined in <limits.h> but we don't have
2019 * it just yet.
2020 */
2021#ifndef PTHREAD_DESTRUCTOR_ITERATIONS
2022# define PTHREAD_DESTRUCTOR_ITERATIONS 4
2023#endif
2024
2025/* this function is called from pthread_exit() to remove all TLS key data
2026 * from this thread's TLS area. this must call the destructor of all keys
2027 * that have a non-NULL data value (and a non-NULL destructor).
2028 *
2029 * because destructors can do funky things like deleting/creating other
2030 * keys, we need to implement this in a loop
2031 */
2032static void pthread_key_clean_all(void)
2033{
2034 tlsmap_t* map;
2035 void** tls = (void**)__get_tls();
2036 int rounds = PTHREAD_DESTRUCTOR_ITERATIONS;
2037
2038 map = tlsmap_lock();
2039
2040 for (rounds = PTHREAD_DESTRUCTOR_ITERATIONS; rounds > 0; rounds--)
2041 {
2042 int kk, count = 0;
2043
2044 for (kk = TLSMAP_START; kk < TLSMAP_SIZE; kk++) {
2045 if ( tlsmap_test(map, kk) )
2046 {
2047 void* data = tls[kk];
2048 tls_dtor_t dtor = map->dtors[kk];
2049
2050 if (data != NULL && dtor != NULL)
2051 {
2052 /* we need to clear the key data now, this will prevent the
2053 * destructor (or a later one) from seeing the old value if
2054 * it calls pthread_getspecific() for some odd reason
2055 *
2056 * we do not do this if 'dtor == NULL' just in case another
2057 * destructor function might be responsible for manually
2058 * releasing the corresponding data.
2059 */
2060 tls[kk] = NULL;
2061
2062 /* because the destructor is free to call pthread_key_create
2063 * and/or pthread_key_delete, we need to temporarily unlock
2064 * the TLS map
2065 */
2066 tlsmap_unlock(map);
2067 (*dtor)(data);
2068 map = tlsmap_lock();
2069
2070 count += 1;
2071 }
2072 }
2073 }
2074
2075 /* if we didn't call any destructor, there is no need to check the
2076 * TLS data again
2077 */
2078 if (count == 0)
2079 break;
2080 }
2081 tlsmap_unlock(map);
2082}
2083
2084// man says this should be in <linux/unistd.h>, but it isn't
Jeff Brown10c8ce52011-11-18 15:17:07 -08002085extern int tgkill(int tgid, int tid, int sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002086
2087int pthread_kill(pthread_t tid, int sig)
2088{
2089 int ret;
2090 int old_errno = errno;
2091 pthread_internal_t * thread = (pthread_internal_t *)tid;
2092
Jeff Brown10c8ce52011-11-18 15:17:07 -08002093 ret = tgkill(getpid(), thread->kernel_id, sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002094 if (ret < 0) {
2095 ret = errno;
2096 errno = old_errno;
2097 }
2098
2099 return ret;
2100}
2101
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01002102/* Despite the fact that our kernel headers define sigset_t explicitly
2103 * as a 32-bit integer, the kernel system call really expects a 64-bit
2104 * bitmap for the signal set, or more exactly an array of two-32-bit
2105 * values (see $KERNEL/arch/$ARCH/include/asm/signal.h for details).
2106 *
2107 * Unfortunately, we cannot fix the sigset_t definition without breaking
2108 * the C library ABI, so perform a little runtime translation here.
2109 */
2110typedef union {
2111 sigset_t bionic;
2112 uint32_t kernel[2];
2113} kernel_sigset_t;
2114
2115/* this is a private syscall stub */
2116extern int __rt_sigprocmask(int, const kernel_sigset_t *, kernel_sigset_t *, size_t);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002117
2118int pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
2119{
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08002120 /* pthread_sigmask must return the error code, but the syscall
2121 * will set errno instead and return 0/-1
2122 */
2123 int ret, old_errno = errno;
2124
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01002125 /* We must convert *set into a kernel_sigset_t */
2126 kernel_sigset_t in_set, *in_set_ptr;
2127 kernel_sigset_t out_set;
2128
Bruce Bearee4a21c82011-12-05 11:25:37 -08002129 in_set.kernel[0] = in_set.kernel[1] = 0;
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01002130 out_set.kernel[0] = out_set.kernel[1] = 0;
2131
2132 /* 'in_set_ptr' is the second parameter to __rt_sigprocmask. It must be NULL
2133 * if 'set' is NULL to ensure correct semantics (which in this case would
2134 * be to ignore 'how' and return the current signal set into 'oset'.
David 'Digit' Turner5c8c00a2010-12-20 15:58:06 +01002135 */
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01002136 if (set == NULL) {
2137 in_set_ptr = NULL;
2138 } else {
2139 in_set.bionic = *set;
2140 in_set_ptr = &in_set;
2141 }
2142
2143 ret = __rt_sigprocmask(how, in_set_ptr, &out_set, sizeof(kernel_sigset_t));
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08002144 if (ret < 0)
2145 ret = errno;
2146
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01002147 if (oset)
2148 *oset = out_set.bionic;
2149
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08002150 errno = old_errno;
2151 return ret;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002152}
2153
2154
2155int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
2156{
2157 const int CLOCK_IDTYPE_BITS = 3;
2158 pthread_internal_t* thread = (pthread_internal_t*)tid;
2159
2160 if (!thread)
2161 return ESRCH;
2162
2163 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
2164 return 0;
2165}
2166
2167
2168/* NOTE: this implementation doesn't support a init function that throws a C++ exception
2169 * or calls fork()
2170 */
2171int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
2172{
Wink Savilleccc3d1e2010-06-28 11:41:16 -07002173 static pthread_mutex_t once_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07002174 volatile pthread_once_t* ocptr = once_control;
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002175 pthread_once_t value;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002176
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002177 /* PTHREAD_ONCE_INIT is 0, we use the following bit flags
2178 *
2179 * bit 0 set -> initialization is under way
2180 * bit 1 set -> initialization is complete
2181 */
2182#define ONCE_INITIALIZING (1 << 0)
2183#define ONCE_COMPLETED (1 << 1)
2184
2185 /* First check if the once is already initialized. This will be the common
2186 * case and we want to make this as fast as possible. Note that this still
2187 * requires a load_acquire operation here to ensure that all the
2188 * stores performed by the initialization function are observable on
2189 * this CPU after we exit.
2190 */
2191 if (__likely((*ocptr & ONCE_COMPLETED) != 0)) {
2192 ANDROID_MEMBAR_FULL();
2193 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002194 }
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002195
2196 for (;;) {
2197 /* Try to atomically set the INITIALIZING flag.
2198 * This requires a cmpxchg loop, and we may need
Elliott Hughesbfeab1b2012-09-05 17:47:37 -07002199 * to exit prematurely if we detect that
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002200 * COMPLETED is now set.
2201 */
2202 int32_t oldval, newval;
2203
2204 do {
2205 oldval = *ocptr;
2206 if ((oldval & ONCE_COMPLETED) != 0)
2207 break;
2208
2209 newval = oldval | ONCE_INITIALIZING;
2210 } while (__bionic_cmpxchg(oldval, newval, ocptr) != 0);
2211
2212 if ((oldval & ONCE_COMPLETED) != 0) {
2213 /* We detected that COMPLETED was set while in our loop */
2214 ANDROID_MEMBAR_FULL();
2215 return 0;
2216 }
2217
2218 if ((oldval & ONCE_INITIALIZING) == 0) {
2219 /* We got there first, we can jump out of the loop to
2220 * handle the initialization */
2221 break;
2222 }
2223
2224 /* Another thread is running the initialization and hasn't completed
2225 * yet, so wait for it, then try again. */
2226 __futex_wait_ex(ocptr, 0, oldval, NULL);
2227 }
2228
2229 /* call the initialization function. */
2230 (*init_routine)();
2231
2232 /* Do a store_release indicating that initialization is complete */
2233 ANDROID_MEMBAR_FULL();
2234 *ocptr = ONCE_COMPLETED;
2235
2236 /* Wake up any waiters, if any */
2237 __futex_wake_ex(ocptr, 0, INT_MAX);
2238
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002239 return 0;
2240}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03002241
2242/* This value is not exported by kernel headers, so hardcode it here */
2243#define MAX_TASK_COMM_LEN 16
2244#define TASK_COMM_FMT "/proc/self/task/%u/comm"
2245
2246int pthread_setname_np(pthread_t thid, const char *thname)
2247{
2248 size_t thname_len;
2249 int saved_errno, ret;
2250
2251 if (thid == 0 || thname == NULL)
2252 return EINVAL;
2253
2254 thname_len = strlen(thname);
2255 if (thname_len >= MAX_TASK_COMM_LEN)
2256 return ERANGE;
2257
2258 saved_errno = errno;
2259 if (thid == pthread_self())
2260 {
2261 ret = prctl(PR_SET_NAME, (unsigned long)thname, 0, 0, 0) ? errno : 0;
2262 }
2263 else
2264 {
2265 /* Have to change another thread's name */
2266 pthread_internal_t *thread = (pthread_internal_t *)thid;
2267 char comm_name[sizeof(TASK_COMM_FMT) + 8];
2268 ssize_t n;
2269 int fd;
2270
2271 snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, (unsigned int)thread->kernel_id);
2272 fd = open(comm_name, O_RDWR);
2273 if (fd == -1)
2274 {
2275 ret = errno;
2276 goto exit;
2277 }
2278 n = TEMP_FAILURE_RETRY(write(fd, thname, thname_len));
2279 close(fd);
2280
2281 if (n < 0)
2282 ret = errno;
2283 else if ((size_t)n != thname_len)
2284 ret = EIO;
2285 else
2286 ret = 0;
2287 }
2288exit:
2289 errno = saved_errno;
2290 return ret;
2291}
Glenn Kastend53cae02011-07-11 15:41:28 -07002292
2293/* Return the kernel thread ID for a pthread.
2294 * This is only defined for implementations where pthread <-> kernel is 1:1, which this is.
2295 * Not the same as pthread_getthreadid_np, which is commonly defined to be opaque.
2296 * Internal, not an NDK API.
2297 */
2298
2299pid_t __pthread_gettid(pthread_t thid)
2300{
2301 pthread_internal_t* thread = (pthread_internal_t*)thid;
2302 return thread->kernel_id;
2303}
Jean-Baptiste Querufaca92f2012-03-26 15:25:19 -07002304
2305int __pthread_settid(pthread_t thid, pid_t tid)
2306{
2307 if (thid == 0)
2308 return EINVAL;
2309
2310 pthread_internal_t* thread = (pthread_internal_t*)thid;
2311 thread->kernel_id = tid;
2312
2313 return 0;
2314}