blob: 7c22b45b22bc8d8db840050c0c74bd30fa17c2f9 [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);
62extern int __set_errno(int);
63
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -070064int __futex_wake_ex(volatile void *ftx, int pshared, int val)
65{
66 return __futex_syscall3(ftx, pshared ? FUTEX_WAKE : FUTEX_WAKE_PRIVATE, val);
67}
68
69int __futex_wait_ex(volatile void *ftx, int pshared, int val, const struct timespec *timeout)
70{
71 return __futex_syscall4(ftx, pshared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE, val, timeout);
72}
73
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -070074#define __likely(cond) __builtin_expect(!!(cond), 1)
75#define __unlikely(cond) __builtin_expect(!!(cond), 0)
76
Bruce Beare8e551a62011-03-28 09:47:35 -070077#ifdef __i386__
78#define ATTRIBUTES __attribute__((noinline)) __attribute__((fastcall))
79#else
80#define ATTRIBUTES __attribute__((noinline))
81#endif
82
83void ATTRIBUTES _thread_created_hook(pid_t thread_id);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080084
Pierre Peifferd0c884d2012-02-22 16:40:15 +010085static const int kPthreadInitFailed = 1;
86
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080087#define PTHREAD_ATTR_FLAG_DETACHED 0x00000001
88#define PTHREAD_ATTR_FLAG_USER_STACK 0x00000002
89
90#define DEFAULT_STACKSIZE (1024 * 1024)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080091
92static pthread_mutex_t mmap_lock = PTHREAD_MUTEX_INITIALIZER;
93
94
95static const pthread_attr_t gDefaultPthreadAttr = {
96 .flags = 0,
97 .stack_base = NULL,
98 .stack_size = DEFAULT_STACKSIZE,
99 .guard_size = PAGE_SIZE,
100 .sched_policy = SCHED_NORMAL,
101 .sched_priority = 0
102};
103
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100104static pthread_internal_t* gThreadList = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800105static pthread_mutex_t gThreadListLock = PTHREAD_MUTEX_INITIALIZER;
106static pthread_mutex_t gDebuggerNotificationLock = PTHREAD_MUTEX_INITIALIZER;
107
108
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800109static void
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100110_pthread_internal_free(pthread_internal_t* thread)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800111{
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100112 if (thread != NULL) {
113 free(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800114 }
115}
116
117
118static void
119_pthread_internal_remove_locked( pthread_internal_t* thread )
120{
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700121 thread->next->prev = thread->prev;
122 thread->prev[0] = thread->next;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800123}
124
125static void
126_pthread_internal_remove( pthread_internal_t* thread )
127{
128 pthread_mutex_lock(&gThreadListLock);
129 _pthread_internal_remove_locked(thread);
130 pthread_mutex_unlock(&gThreadListLock);
131}
132
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +0400133__LIBC_ABI_PRIVATE__ void
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700134_pthread_internal_add(pthread_internal_t* thread)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800135{
136 pthread_mutex_lock(&gThreadListLock);
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700137
138 thread->prev = &gThreadList;
139 thread->next = *(thread->prev);
140 if (thread->next != NULL) {
141 thread->next->prev = &thread->next;
142 }
143 *(thread->prev) = thread;
144
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800145 pthread_mutex_unlock(&gThreadListLock);
146}
147
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +0400148__LIBC_ABI_PRIVATE__ pthread_internal_t*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800149__get_thread(void)
150{
151 void** tls = (void**)__get_tls();
152
153 return (pthread_internal_t*) tls[TLS_SLOT_THREAD_ID];
154}
155
156
157void*
158__get_stack_base(int *p_stack_size)
159{
160 pthread_internal_t* thread = __get_thread();
161
162 *p_stack_size = thread->attr.stack_size;
163 return thread->attr.stack_base;
164}
165
166
Elliott Hughes5419b942012-10-16 15:54:46 -0700167void __init_tls(void** tls, void* thread) {
168 ((pthread_internal_t*) thread)->tls = tls;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800169
Elliott Hughes5419b942012-10-16 15:54:46 -0700170 // Zero-initialize all the slots.
171 for (size_t i = 0; i < BIONIC_TLS_SLOTS; ++i) {
172 tls[i] = NULL;
173 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800174
Elliott Hughesad88a082012-10-24 18:37:21 -0700175 // Slot 0 must point to itself. The x86 Linux kernel reads the TLS from %fs:0.
Elliott Hughes5419b942012-10-16 15:54:46 -0700176 tls[TLS_SLOT_SELF] = (void*) tls;
177 tls[TLS_SLOT_THREAD_ID] = thread;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800178
Elliott Hughesad88a082012-10-24 18:37:21 -0700179 // Stack guard generation may make system calls, and those system calls may fail.
180 // 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 -0700181 __set_tls((void*) tls);
Elliott Hughesad88a082012-10-24 18:37:21 -0700182 tls[TLS_SLOT_STACK_GUARD] = __generate_stack_chk_guard();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800183}
184
185
186/*
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100187 * This trampoline is called from the assembly _pthread_clone() function.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800188 */
189void __thread_entry(int (*func)(void*), void *arg, void **tls)
190{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800191 // Wait for our creating thread to release us. This lets it have time to
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100192 // notify gdb about this thread before we start doing anything.
Andy McFaddene2ac8982010-09-02 13:34:53 -0700193 //
194 // This also provides the memory barrier needed to ensure that all memory
195 // accesses previously made by the creating thread are visible to us.
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100196 pthread_mutex_t* start_mutex = (pthread_mutex_t*) &tls[TLS_SLOT_SELF];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800197 pthread_mutex_lock(start_mutex);
198 pthread_mutex_destroy(start_mutex);
199
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100200 pthread_internal_t* thread = (pthread_internal_t*) tls[TLS_SLOT_THREAD_ID];
201 __init_tls(tls, thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800202
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100203 if ((thread->internal_flags & kPthreadInitFailed) != 0) {
204 pthread_exit(NULL);
205 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800206
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100207 int result = func(arg);
208 pthread_exit((void*) result);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800209}
210
Dave Burke88f1ea82012-09-17 20:37:38 -0700211#include <private/logd.h>
212
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +0400213__LIBC_ABI_PRIVATE__
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700214int _init_thread(pthread_internal_t* thread, pid_t kernel_id, pthread_attr_t* attr,
215 void* stack_base, bool add_to_thread_list)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800216{
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100217 int error = 0;
218
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800219 if (attr == NULL) {
220 thread->attr = gDefaultPthreadAttr;
221 } else {
222 thread->attr = *attr;
223 }
224 thread->attr.stack_base = stack_base;
225 thread->kernel_id = kernel_id;
226
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100227 // Make a note of whether the user supplied this stack (so we know whether or not to free it).
228 if (attr->stack_base == stack_base) {
229 thread->attr.flags |= PTHREAD_ATTR_FLAG_USER_STACK;
230 }
231
232 // Set the scheduling policy/priority of the thread.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800233 if (thread->attr.sched_policy != SCHED_NORMAL) {
234 struct sched_param param;
235 param.sched_priority = thread->attr.sched_priority;
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100236 if (sched_setscheduler(kernel_id, thread->attr.sched_policy, &param) == -1) {
Dave Burke88f1ea82012-09-17 20:37:38 -0700237 // For back compat reasons, we just warn about possible invalid sched_policy
238 const char* msg = "pthread_create sched_setscheduler call failed: %s\n";
239 __libc_android_log_print(ANDROID_LOG_WARN, "libc", msg, strerror(errno));
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100240 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800241 }
242
243 pthread_cond_init(&thread->join_cond, NULL);
244 thread->join_count = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800245 thread->cleanup_stack = NULL;
246
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700247 if (add_to_thread_list) {
248 _pthread_internal_add(thread);
249 }
250
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100251 return error;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800252}
253
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800254static void *mkstack(size_t size, size_t guard_size)
255{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800256 pthread_mutex_lock(&mmap_lock);
257
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100258 int prot = PROT_READ | PROT_WRITE;
259 int flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE;
Elliott Hughes9c3eca72012-05-08 13:26:28 -0700260 void* stack = mmap(NULL, size, prot, flags, -1, 0);
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100261 if (stack == MAP_FAILED) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800262 stack = NULL;
263 goto done;
264 }
265
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100266 if (mprotect(stack, guard_size, PROT_NONE) == -1) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800267 munmap(stack, size);
268 stack = NULL;
269 goto done;
270 }
271
272done:
273 pthread_mutex_unlock(&mmap_lock);
274 return stack;
275}
276
277/*
Andy McFaddene2ac8982010-09-02 13:34:53 -0700278 * Create a new thread. The thread's stack is laid out like so:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800279 *
280 * +---------------------------+
281 * | pthread_internal_t |
282 * +---------------------------+
283 * | |
284 * | TLS area |
285 * | |
286 * +---------------------------+
287 * | |
288 * . .
289 * . stack area .
290 * . .
291 * | |
292 * +---------------------------+
293 * | guard page |
294 * +---------------------------+
295 *
296 * note that TLS[0] must be a pointer to itself, this is required
297 * by the thread-local storage implementation of the x86 Linux
298 * kernel, where the TLS pointer is read by reading fs:[0]
299 */
300int pthread_create(pthread_t *thread_out, pthread_attr_t const * attr,
301 void *(*start_routine)(void *), void * arg)
302{
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100303 int old_errno = errno;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800304
305 /* this will inform the rest of the C library that at least one thread
306 * was created. this will enforce certain functions to acquire/release
307 * locks (e.g. atexit()) to protect shared global structures.
308 *
309 * this works because pthread_create() is not called by the C library
310 * initialization routine that sets up the main thread's data structures.
311 */
312 __isthreaded = 1;
313
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100314 pthread_internal_t* thread = calloc(sizeof(*thread), 1);
315 if (thread == NULL) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800316 return ENOMEM;
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100317 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800318
319 if (attr == NULL) {
320 attr = &gDefaultPthreadAttr;
321 }
322
323 // make sure the stack is PAGE_SIZE aligned
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100324 size_t stack_size = (attr->stack_size + (PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
325 uint8_t* stack = attr->stack_base;
326 if (stack == NULL) {
327 stack = mkstack(stack_size, attr->guard_size);
328 if (stack == NULL) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800329 _pthread_internal_free(thread);
330 return ENOMEM;
331 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800332 }
333
334 // Make room for TLS
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100335 void** tls = (void**)(stack + stack_size - BIONIC_TLS_SLOTS*sizeof(void*));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800336
337 // Create a mutex for the thread in TLS_SLOT_SELF to wait on once it starts so we can keep
338 // it from doing anything until after we notify the debugger about it
Andy McFaddene2ac8982010-09-02 13:34:53 -0700339 //
340 // This also provides the memory barrier we need to ensure that all
341 // memory accesses previously performed by this thread are visible to
342 // the new thread.
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100343 pthread_mutex_t* start_mutex = (pthread_mutex_t*) &tls[TLS_SLOT_SELF];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800344 pthread_mutex_init(start_mutex, NULL);
345 pthread_mutex_lock(start_mutex);
346
347 tls[TLS_SLOT_THREAD_ID] = thread;
348
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100349 int flags = CLONE_FILES | CLONE_FS | CLONE_VM | CLONE_SIGHAND |
350 CLONE_THREAD | CLONE_SYSVSEM | CLONE_DETACHED;
351 int tid = __pthread_clone((int(*)(void*))start_routine, tls, flags, arg);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800352
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100353 if (tid < 0) {
354 int clone_errno = errno;
355 pthread_mutex_unlock(start_mutex);
356 if (stack != attr->stack_base) {
357 munmap(stack, stack_size);
358 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800359 _pthread_internal_free(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800360 errno = old_errno;
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100361 return clone_errno;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800362 }
363
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700364 int init_errno = _init_thread(thread, tid, (pthread_attr_t*) attr, stack, true);
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100365 if (init_errno != 0) {
366 // Mark the thread detached and let its __thread_entry run to
367 // completion. (It'll just exit immediately, cleaning up its resources.)
368 thread->internal_flags |= kPthreadInitFailed;
369 thread->attr.flags |= PTHREAD_ATTR_FLAG_DETACHED;
370 pthread_mutex_unlock(start_mutex);
371 errno = old_errno;
372 return init_errno;
373 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800374
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100375 // Notify any debuggers about the new thread.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800376 pthread_mutex_lock(&gDebuggerNotificationLock);
377 _thread_created_hook(tid);
378 pthread_mutex_unlock(&gDebuggerNotificationLock);
379
Jurijs Oniscuks2932f042012-07-05 14:57:38 +0200380 // Publish the pthread_t and let the thread run.
381 *thread_out = (pthread_t) thread;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800382 pthread_mutex_unlock(start_mutex);
383
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800384 return 0;
385}
386
387
388int pthread_attr_init(pthread_attr_t * attr)
389{
390 *attr = gDefaultPthreadAttr;
391 return 0;
392}
393
394int pthread_attr_destroy(pthread_attr_t * attr)
395{
396 memset(attr, 0x42, sizeof(pthread_attr_t));
397 return 0;
398}
399
400int pthread_attr_setdetachstate(pthread_attr_t * attr, int state)
401{
402 if (state == PTHREAD_CREATE_DETACHED) {
403 attr->flags |= PTHREAD_ATTR_FLAG_DETACHED;
404 } else if (state == PTHREAD_CREATE_JOINABLE) {
405 attr->flags &= ~PTHREAD_ATTR_FLAG_DETACHED;
406 } else {
407 return EINVAL;
408 }
409 return 0;
410}
411
412int pthread_attr_getdetachstate(pthread_attr_t const * attr, int * state)
413{
414 *state = (attr->flags & PTHREAD_ATTR_FLAG_DETACHED)
415 ? PTHREAD_CREATE_DETACHED
416 : PTHREAD_CREATE_JOINABLE;
417 return 0;
418}
419
420int pthread_attr_setschedpolicy(pthread_attr_t * attr, int policy)
421{
422 attr->sched_policy = policy;
423 return 0;
424}
425
426int pthread_attr_getschedpolicy(pthread_attr_t const * attr, int * policy)
427{
428 *policy = attr->sched_policy;
429 return 0;
430}
431
432int pthread_attr_setschedparam(pthread_attr_t * attr, struct sched_param const * param)
433{
434 attr->sched_priority = param->sched_priority;
435 return 0;
436}
437
438int pthread_attr_getschedparam(pthread_attr_t const * attr, struct sched_param * param)
439{
440 param->sched_priority = attr->sched_priority;
441 return 0;
442}
443
444int pthread_attr_setstacksize(pthread_attr_t * attr, size_t stack_size)
445{
446 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
447 return EINVAL;
448 }
449 attr->stack_size = stack_size;
450 return 0;
451}
452
453int pthread_attr_getstacksize(pthread_attr_t const * attr, size_t * stack_size)
454{
455 *stack_size = attr->stack_size;
456 return 0;
457}
458
459int pthread_attr_setstackaddr(pthread_attr_t * attr, void * stack_addr)
460{
461#if 1
462 // It's not clear if this is setting the top or bottom of the stack, so don't handle it for now.
463 return ENOSYS;
464#else
465 if ((uint32_t)stack_addr & (PAGE_SIZE - 1)) {
466 return EINVAL;
467 }
468 attr->stack_base = stack_addr;
469 return 0;
470#endif
471}
472
473int pthread_attr_getstackaddr(pthread_attr_t const * attr, void ** stack_addr)
474{
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700475 *stack_addr = (char*)attr->stack_base + attr->stack_size;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800476 return 0;
477}
478
479int pthread_attr_setstack(pthread_attr_t * attr, void * stack_base, size_t stack_size)
480{
481 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
482 return EINVAL;
483 }
484 if ((uint32_t)stack_base & (PAGE_SIZE - 1)) {
485 return EINVAL;
486 }
487 attr->stack_base = stack_base;
488 attr->stack_size = stack_size;
489 return 0;
490}
491
492int pthread_attr_getstack(pthread_attr_t const * attr, void ** stack_base, size_t * stack_size)
493{
494 *stack_base = attr->stack_base;
495 *stack_size = attr->stack_size;
496 return 0;
497}
498
499int pthread_attr_setguardsize(pthread_attr_t * attr, size_t guard_size)
500{
501 if (guard_size & (PAGE_SIZE - 1) || guard_size < PAGE_SIZE) {
502 return EINVAL;
503 }
504
505 attr->guard_size = guard_size;
506 return 0;
507}
508
509int pthread_attr_getguardsize(pthread_attr_t const * attr, size_t * guard_size)
510{
511 *guard_size = attr->guard_size;
512 return 0;
513}
514
515int pthread_getattr_np(pthread_t thid, pthread_attr_t * attr)
516{
517 pthread_internal_t * thread = (pthread_internal_t *)thid;
518 *attr = thread->attr;
519 return 0;
520}
521
522int pthread_attr_setscope(pthread_attr_t *attr, int scope)
523{
524 if (scope == PTHREAD_SCOPE_SYSTEM)
525 return 0;
526 if (scope == PTHREAD_SCOPE_PROCESS)
527 return ENOTSUP;
528
529 return EINVAL;
530}
531
532int pthread_attr_getscope(pthread_attr_t const *attr)
533{
534 return PTHREAD_SCOPE_SYSTEM;
535}
536
537
538/* CAVEAT: our implementation of pthread_cleanup_push/pop doesn't support C++ exceptions
539 * and thread cancelation
540 */
541
542void __pthread_cleanup_push( __pthread_cleanup_t* c,
543 __pthread_cleanup_func_t routine,
544 void* arg )
545{
546 pthread_internal_t* thread = __get_thread();
547
548 c->__cleanup_routine = routine;
549 c->__cleanup_arg = arg;
550 c->__cleanup_prev = thread->cleanup_stack;
551 thread->cleanup_stack = c;
552}
553
554void __pthread_cleanup_pop( __pthread_cleanup_t* c, int execute )
555{
556 pthread_internal_t* thread = __get_thread();
557
558 thread->cleanup_stack = c->__cleanup_prev;
559 if (execute)
560 c->__cleanup_routine(c->__cleanup_arg);
561}
562
563/* used by pthread_exit() to clean all TLS keys of the current thread */
564static void pthread_key_clean_all(void);
565
566void pthread_exit(void * retval)
567{
568 pthread_internal_t* thread = __get_thread();
569 void* stack_base = thread->attr.stack_base;
570 int stack_size = thread->attr.stack_size;
571 int user_stack = (thread->attr.flags & PTHREAD_ATTR_FLAG_USER_STACK) != 0;
Jack Rene480fc82011-09-21 12:44:11 +0200572 sigset_t mask;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800573
574 // call the cleanup handlers first
575 while (thread->cleanup_stack) {
576 __pthread_cleanup_t* c = thread->cleanup_stack;
577 thread->cleanup_stack = c->__cleanup_prev;
578 c->__cleanup_routine(c->__cleanup_arg);
579 }
580
581 // call the TLS destructors, it is important to do that before removing this
582 // thread from the global list. this will ensure that if someone else deletes
583 // a TLS key, the corresponding value will be set to NULL in this thread's TLS
584 // space (see pthread_key_delete)
585 pthread_key_clean_all();
586
587 // if the thread is detached, destroy the pthread_internal_t
588 // otherwise, keep it in memory and signal any joiners
589 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
590 _pthread_internal_remove(thread);
591 _pthread_internal_free(thread);
592 } else {
Bjorn Andersson0753dc62012-05-03 17:12:39 -0700593 pthread_mutex_lock(&gThreadListLock);
594
595 /* make sure that the thread struct doesn't have stale pointers to a stack that
596 * will be unmapped after the exit call below.
597 */
598 if (!user_stack) {
599 thread->attr.stack_base = NULL;
600 thread->attr.stack_size = 0;
601 thread->tls = NULL;
602 }
603
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800604 /* the join_count field is used to store the number of threads waiting for
605 * the termination of this thread with pthread_join(),
606 *
607 * if it is positive we need to signal the waiters, and we do not touch
608 * the count (it will be decremented by the waiters, the last one will
609 * also remove/free the thread structure
610 *
611 * if it is zero, we set the count value to -1 to indicate that the
612 * thread is in 'zombie' state: it has stopped executing, and its stack
613 * is gone (as well as its TLS area). when another thread calls pthread_join()
614 * on it, it will immediately free the thread and return.
615 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800616 thread->return_value = retval;
617 if (thread->join_count > 0) {
618 pthread_cond_broadcast(&thread->join_cond);
619 } else {
620 thread->join_count = -1; /* zombie thread */
621 }
622 pthread_mutex_unlock(&gThreadListLock);
623 }
624
Jack Rene480fc82011-09-21 12:44:11 +0200625 sigfillset(&mask);
626 sigdelset(&mask, SIGSEGV);
627 (void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *)NULL);
628
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800629 // destroy the thread stack
630 if (user_stack)
631 _exit_thread((int)retval);
632 else
633 _exit_with_stack_teardown(stack_base, stack_size, (int)retval);
634}
635
636int pthread_join(pthread_t thid, void ** ret_val)
637{
638 pthread_internal_t* thread = (pthread_internal_t*)thid;
639 int count;
640
641 // check that the thread still exists and is not detached
642 pthread_mutex_lock(&gThreadListLock);
643
644 for (thread = gThreadList; thread != NULL; thread = thread->next)
645 if (thread == (pthread_internal_t*)thid)
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200646 goto FoundIt;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800647
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200648 pthread_mutex_unlock(&gThreadListLock);
649 return ESRCH;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800650
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200651FoundIt:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800652 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
653 pthread_mutex_unlock(&gThreadListLock);
654 return EINVAL;
655 }
656
657 /* wait for thread death when needed
658 *
659 * if the 'join_count' is negative, this is a 'zombie' thread that
660 * is already dead and without stack/TLS
661 *
662 * otherwise, we need to increment 'join-count' and wait to be signaled
663 */
664 count = thread->join_count;
665 if (count >= 0) {
666 thread->join_count += 1;
667 pthread_cond_wait( &thread->join_cond, &gThreadListLock );
668 count = --thread->join_count;
669 }
670 if (ret_val)
671 *ret_val = thread->return_value;
672
673 /* remove thread descriptor when we're the last joiner or when the
674 * thread was already a zombie.
675 */
676 if (count <= 0) {
677 _pthread_internal_remove_locked(thread);
678 _pthread_internal_free(thread);
679 }
680 pthread_mutex_unlock(&gThreadListLock);
681 return 0;
682}
683
684int pthread_detach( pthread_t thid )
685{
686 pthread_internal_t* thread;
687 int result = 0;
688 int flags;
689
690 pthread_mutex_lock(&gThreadListLock);
691 for (thread = gThreadList; thread != NULL; thread = thread->next)
692 if (thread == (pthread_internal_t*)thid)
693 goto FoundIt;
694
695 result = ESRCH;
696 goto Exit;
697
698FoundIt:
699 do {
700 flags = thread->attr.flags;
701
702 if ( flags & PTHREAD_ATTR_FLAG_DETACHED ) {
703 /* thread is not joinable ! */
704 result = EINVAL;
705 goto Exit;
706 }
707 }
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100708 while ( __bionic_cmpxchg( flags, flags | PTHREAD_ATTR_FLAG_DETACHED,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800709 (volatile int*)&thread->attr.flags ) != 0 );
710Exit:
711 pthread_mutex_unlock(&gThreadListLock);
712 return result;
713}
714
715pthread_t pthread_self(void)
716{
717 return (pthread_t)__get_thread();
718}
719
720int pthread_equal(pthread_t one, pthread_t two)
721{
722 return (one == two ? 1 : 0);
723}
724
725int pthread_getschedparam(pthread_t thid, int * policy,
726 struct sched_param * param)
727{
728 int old_errno = errno;
729
730 pthread_internal_t * thread = (pthread_internal_t *)thid;
731 int err = sched_getparam(thread->kernel_id, param);
732 if (!err) {
733 *policy = sched_getscheduler(thread->kernel_id);
734 } else {
735 err = errno;
736 errno = old_errno;
737 }
738 return err;
739}
740
741int pthread_setschedparam(pthread_t thid, int policy,
742 struct sched_param const * param)
743{
744 pthread_internal_t * thread = (pthread_internal_t *)thid;
745 int old_errno = errno;
746 int ret;
747
748 ret = sched_setscheduler(thread->kernel_id, policy, param);
749 if (ret < 0) {
750 ret = errno;
751 errno = old_errno;
752 }
753 return ret;
754}
755
756
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800757/* a mutex is implemented as a 32-bit integer holding the following fields
758 *
759 * bits: name description
760 * 31-16 tid owner thread's kernel id (recursive and errorcheck only)
761 * 15-14 type mutex type
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700762 * 13 shared process-shared flag
763 * 12-2 counter counter of recursive mutexes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800764 * 1-0 state lock state (0, 1 or 2)
765 */
766
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100767/* Convenience macro, creates a mask of 'bits' bits that starts from
768 * the 'shift'-th least significant bit in a 32-bit word.
769 *
770 * Examples: FIELD_MASK(0,4) -> 0xf
771 * FIELD_MASK(16,9) -> 0x1ff0000
772 */
773#define FIELD_MASK(shift,bits) (((1 << (bits))-1) << (shift))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800774
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100775/* This one is used to create a bit pattern from a given field value */
776#define FIELD_TO_BITS(val,shift,bits) (((val) & ((1 << (bits))-1)) << (shift))
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100777
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100778/* And this one does the opposite, i.e. extract a field's value from a bit pattern */
779#define FIELD_FROM_BITS(val,shift,bits) (((val) >> (shift)) & ((1 << (bits))-1))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800780
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100781/* Mutex state:
782 *
783 * 0 for unlocked
784 * 1 for locked, no waiters
785 * 2 for locked, maybe waiters
786 */
787#define MUTEX_STATE_SHIFT 0
788#define MUTEX_STATE_LEN 2
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800789
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100790#define MUTEX_STATE_MASK FIELD_MASK(MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
791#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
792#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
793
794#define MUTEX_STATE_UNLOCKED 0 /* must be 0 to match __PTHREAD_MUTEX_INIT_VALUE */
795#define MUTEX_STATE_LOCKED_UNCONTENDED 1 /* must be 1 due to atomic dec in unlock operation */
796#define MUTEX_STATE_LOCKED_CONTENDED 2 /* must be 1 + LOCKED_UNCONTENDED due to atomic dec */
797
798#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
799#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
800
801#define MUTEX_STATE_BITS_UNLOCKED MUTEX_STATE_TO_BITS(MUTEX_STATE_UNLOCKED)
802#define MUTEX_STATE_BITS_LOCKED_UNCONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_UNCONTENDED)
803#define MUTEX_STATE_BITS_LOCKED_CONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_CONTENDED)
804
805/* return true iff the mutex if locked with no waiters */
806#define MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_UNCONTENDED)
807
808/* return true iff the mutex if locked with maybe waiters */
809#define MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_CONTENDED)
810
811/* used to flip from LOCKED_UNCONTENDED to LOCKED_CONTENDED */
812#define MUTEX_STATE_BITS_FLIP_CONTENTION(v) ((v) ^ (MUTEX_STATE_BITS_LOCKED_CONTENDED ^ MUTEX_STATE_BITS_LOCKED_UNCONTENDED))
813
814/* Mutex counter:
815 *
816 * We need to check for overflow before incrementing, and we also need to
817 * detect when the counter is 0
818 */
819#define MUTEX_COUNTER_SHIFT 2
820#define MUTEX_COUNTER_LEN 11
821#define MUTEX_COUNTER_MASK FIELD_MASK(MUTEX_COUNTER_SHIFT, MUTEX_COUNTER_LEN)
822
823#define MUTEX_COUNTER_BITS_WILL_OVERFLOW(v) (((v) & MUTEX_COUNTER_MASK) == MUTEX_COUNTER_MASK)
824#define MUTEX_COUNTER_BITS_IS_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
825
826/* Used to increment the counter directly after overflow has been checked */
827#define MUTEX_COUNTER_BITS_ONE FIELD_TO_BITS(1,MUTEX_COUNTER_SHIFT,MUTEX_COUNTER_LEN)
828
829/* Returns true iff the counter is 0 */
830#define MUTEX_COUNTER_BITS_ARE_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
831
832/* Mutex shared bit flag
833 *
834 * This flag is set to indicate that the mutex is shared among processes.
835 * This changes the futex opcode we use for futex wait/wake operations
836 * (non-shared operations are much faster).
837 */
838#define MUTEX_SHARED_SHIFT 13
839#define MUTEX_SHARED_MASK FIELD_MASK(MUTEX_SHARED_SHIFT,1)
840
841/* Mutex type:
842 *
843 * We support normal, recursive and errorcheck mutexes.
844 *
845 * The constants defined here *cannot* be changed because they must match
846 * the C library ABI which defines the following initialization values in
847 * <pthread.h>:
848 *
849 * __PTHREAD_MUTEX_INIT_VALUE
850 * __PTHREAD_RECURSIVE_MUTEX_VALUE
851 * __PTHREAD_ERRORCHECK_MUTEX_INIT_VALUE
852 */
853#define MUTEX_TYPE_SHIFT 14
854#define MUTEX_TYPE_LEN 2
855#define MUTEX_TYPE_MASK FIELD_MASK(MUTEX_TYPE_SHIFT,MUTEX_TYPE_LEN)
856
857#define MUTEX_TYPE_NORMAL 0 /* Must be 0 to match __PTHREAD_MUTEX_INIT_VALUE */
858#define MUTEX_TYPE_RECURSIVE 1
859#define MUTEX_TYPE_ERRORCHECK 2
860
861#define MUTEX_TYPE_TO_BITS(t) FIELD_TO_BITS(t, MUTEX_TYPE_SHIFT, MUTEX_TYPE_LEN)
862
863#define MUTEX_TYPE_BITS_NORMAL MUTEX_TYPE_TO_BITS(MUTEX_TYPE_NORMAL)
864#define MUTEX_TYPE_BITS_RECURSIVE MUTEX_TYPE_TO_BITS(MUTEX_TYPE_RECURSIVE)
865#define MUTEX_TYPE_BITS_ERRORCHECK MUTEX_TYPE_TO_BITS(MUTEX_TYPE_ERRORCHECK)
866
867/* Mutex owner field:
868 *
869 * This is only used for recursive and errorcheck mutexes. It holds the
870 * kernel TID of the owning thread. Note that this works because the Linux
871 * kernel _only_ uses 16-bit values for thread ids.
872 *
873 * More specifically, it will wrap to 10000 when it reaches over 32768 for
874 * application processes. You can check this by running the following inside
875 * an adb shell session:
876 *
877 OLDPID=$$;
878 while true; do
879 NEWPID=$(sh -c 'echo $$')
880 if [ "$NEWPID" -gt 32768 ]; then
881 echo "AARGH: new PID $NEWPID is too high!"
882 exit 1
883 fi
884 if [ "$NEWPID" -lt "$OLDPID" ]; then
885 echo "****** Wrapping from PID $OLDPID to $NEWPID. *******"
886 else
887 echo -n "$NEWPID!"
888 fi
889 OLDPID=$NEWPID
890 done
891
892 * Note that you can run the same example on a desktop Linux system,
893 * the wrapping will also happen at 32768, but will go back to 300 instead.
894 */
895#define MUTEX_OWNER_SHIFT 16
896#define MUTEX_OWNER_LEN 16
897
898#define MUTEX_OWNER_FROM_BITS(v) FIELD_FROM_BITS(v,MUTEX_OWNER_SHIFT,MUTEX_OWNER_LEN)
899#define MUTEX_OWNER_TO_BITS(v) FIELD_TO_BITS(v,MUTEX_OWNER_SHIFT,MUTEX_OWNER_LEN)
900
901/* Convenience macros.
902 *
903 * These are used to form or modify the bit pattern of a given mutex value
904 */
905
906
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800907
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700908/* a mutex attribute holds the following fields
909 *
910 * bits: name description
911 * 0-3 type type of mutex
912 * 4 shared process-shared flag
913 */
914#define MUTEXATTR_TYPE_MASK 0x000f
915#define MUTEXATTR_SHARED_MASK 0x0010
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800916
917
918int pthread_mutexattr_init(pthread_mutexattr_t *attr)
919{
920 if (attr) {
921 *attr = PTHREAD_MUTEX_DEFAULT;
922 return 0;
923 } else {
924 return EINVAL;
925 }
926}
927
928int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
929{
930 if (attr) {
931 *attr = -1;
932 return 0;
933 } else {
934 return EINVAL;
935 }
936}
937
938int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
939{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700940 if (attr) {
941 int atype = (*attr & MUTEXATTR_TYPE_MASK);
942
943 if (atype >= PTHREAD_MUTEX_NORMAL &&
944 atype <= PTHREAD_MUTEX_ERRORCHECK) {
945 *type = atype;
946 return 0;
947 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800948 }
949 return EINVAL;
950}
951
952int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
953{
954 if (attr && type >= PTHREAD_MUTEX_NORMAL &&
955 type <= PTHREAD_MUTEX_ERRORCHECK ) {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700956 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800957 return 0;
958 }
959 return EINVAL;
960}
961
962/* process-shared mutexes are not supported at the moment */
963
964int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
965{
966 if (!attr)
967 return EINVAL;
968
Mathias Agopianb7681162009-07-13 22:00:33 -0700969 switch (pshared) {
970 case PTHREAD_PROCESS_PRIVATE:
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700971 *attr &= ~MUTEXATTR_SHARED_MASK;
972 return 0;
973
Mathias Agopianb7681162009-07-13 22:00:33 -0700974 case PTHREAD_PROCESS_SHARED:
975 /* our current implementation of pthread actually supports shared
976 * mutexes but won't cleanup if a process dies with the mutex held.
977 * Nevertheless, it's better than nothing. Shared mutexes are used
978 * by surfaceflinger and audioflinger.
979 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700980 *attr |= MUTEXATTR_SHARED_MASK;
Mathias Agopianb7681162009-07-13 22:00:33 -0700981 return 0;
982 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700983 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800984}
985
986int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
987{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700988 if (!attr || !pshared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800989 return EINVAL;
990
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700991 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED
992 : PTHREAD_PROCESS_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800993 return 0;
994}
995
996int pthread_mutex_init(pthread_mutex_t *mutex,
997 const pthread_mutexattr_t *attr)
998{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700999 int value = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001000
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001001 if (mutex == NULL)
1002 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001003
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001004 if (__likely(attr == NULL)) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001005 mutex->value = MUTEX_TYPE_BITS_NORMAL;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001006 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001007 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001008
1009 if ((*attr & MUTEXATTR_SHARED_MASK) != 0)
1010 value |= MUTEX_SHARED_MASK;
1011
1012 switch (*attr & MUTEXATTR_TYPE_MASK) {
1013 case PTHREAD_MUTEX_NORMAL:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001014 value |= MUTEX_TYPE_BITS_NORMAL;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001015 break;
1016 case PTHREAD_MUTEX_RECURSIVE:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001017 value |= MUTEX_TYPE_BITS_RECURSIVE;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001018 break;
1019 case PTHREAD_MUTEX_ERRORCHECK:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001020 value |= MUTEX_TYPE_BITS_ERRORCHECK;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001021 break;
1022 default:
1023 return EINVAL;
1024 }
1025
1026 mutex->value = value;
1027 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001028}
1029
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001030
1031/*
1032 * Lock a non-recursive mutex.
1033 *
1034 * As noted above, there are three states:
1035 * 0 (unlocked, no contention)
1036 * 1 (locked, no contention)
1037 * 2 (locked, contention)
1038 *
1039 * Non-recursive mutexes don't use the thread-id or counter fields, and the
1040 * "type" value is zero, so the only bits that will be set are the ones in
1041 * the lock state field.
1042 */
1043static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001044_normal_lock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001045{
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001046 /* convenience shortcuts */
1047 const int unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
1048 const int locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001049 /*
1050 * The common case is an unlocked mutex, so we begin by trying to
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001051 * change the lock's state from 0 (UNLOCKED) to 1 (LOCKED).
1052 * __bionic_cmpxchg() returns 0 if it made the swap successfully.
1053 * If the result is nonzero, this lock is already held by another thread.
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001054 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001055 if (__bionic_cmpxchg(unlocked, locked_uncontended, &mutex->value) != 0) {
1056 const int locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001057 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001058 * We want to go to sleep until the mutex is available, which
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001059 * requires promoting it to state 2 (CONTENDED). We need to
1060 * swap in the new state value and then wait until somebody wakes us up.
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001061 *
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001062 * __bionic_swap() returns the previous value. We swap 2 in and
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001063 * see if we got zero back; if so, we have acquired the lock. If
1064 * not, another thread still holds the lock and we wait again.
1065 *
1066 * The second argument to the __futex_wait() call is compared
1067 * against the current value. If it doesn't match, __futex_wait()
1068 * returns immediately (otherwise, it sleeps for a time specified
1069 * by the third argument; 0 means sleep forever). This ensures
1070 * that the mutex is in state 2 when we go to sleep on it, which
1071 * guarantees a wake-up call.
1072 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001073 while (__bionic_swap(locked_contended, &mutex->value) != unlocked)
1074 __futex_wait_ex(&mutex->value, shared, locked_contended, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001075 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001076 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001077}
1078
1079/*
1080 * Release a non-recursive mutex. The caller is responsible for determining
1081 * that we are in fact the owner of this lock.
1082 */
1083static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001084_normal_unlock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001085{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001086 ANDROID_MEMBAR_FULL();
1087
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001088 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001089 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001090 * to release the lock. __bionic_atomic_dec() returns the previous value;
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001091 * if it wasn't 1 we have to do some additional work.
1092 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001093 if (__bionic_atomic_dec(&mutex->value) != (shared|MUTEX_STATE_BITS_LOCKED_UNCONTENDED)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001094 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001095 * Start by releasing the lock. The decrement changed it from
1096 * "contended lock" to "uncontended lock", which means we still
1097 * hold it, and anybody who tries to sneak in will push it back
1098 * to state 2.
1099 *
1100 * Once we set it to zero the lock is up for grabs. We follow
1101 * this with a __futex_wake() to ensure that one of the waiting
1102 * threads has a chance to grab it.
1103 *
1104 * This doesn't cause a race with the swap/wait pair in
1105 * _normal_lock(), because the __futex_wait() call there will
1106 * return immediately if the mutex value isn't 2.
1107 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001108 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001109
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001110 /*
1111 * Wake up one waiting thread. We don't know which thread will be
1112 * woken or when it'll start executing -- futexes make no guarantees
1113 * here. There may not even be a thread waiting.
1114 *
1115 * The newly-woken thread will replace the 0 we just set above
1116 * with 2, which means that when it eventually releases the mutex
1117 * it will also call FUTEX_WAKE. This results in one extra wake
1118 * call whenever a lock is contended, but lets us avoid forgetting
1119 * anyone without requiring us to track the number of sleepers.
1120 *
1121 * It's possible for another thread to sneak in and grab the lock
1122 * between the zero assignment above and the wake call below. If
1123 * the new thread is "slow" and holds the lock for a while, we'll
1124 * wake up a sleeper, which will swap in a 2 and then go back to
1125 * sleep since the lock is still held. If the new thread is "fast",
1126 * running to completion before we call wake, the thread we
1127 * eventually wake will find an unlocked mutex and will execute.
1128 * Either way we have correct behavior and nobody is orphaned on
1129 * the wait queue.
1130 */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001131 __futex_wake_ex(&mutex->value, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001132 }
1133}
1134
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001135/* This common inlined function is used to increment the counter of an
1136 * errorcheck or recursive mutex.
1137 *
1138 * For errorcheck mutexes, it will return EDEADLK
1139 * If the counter overflows, it will return EAGAIN
1140 * Otherwise, it atomically increments the counter and returns 0
1141 * after providing an acquire barrier.
1142 *
1143 * mtype is the current mutex type
1144 * mvalue is the current mutex value (already loaded)
1145 * mutex pointers to the mutex.
1146 */
1147static __inline__ __attribute__((always_inline)) int
1148_recursive_increment(pthread_mutex_t* mutex, int mvalue, int mtype)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001149{
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001150 if (mtype == MUTEX_TYPE_BITS_ERRORCHECK) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001151 /* trying to re-lock a mutex we already acquired */
1152 return EDEADLK;
1153 }
1154
1155 /* Detect recursive lock overflow and return EAGAIN.
1156 * This is safe because only the owner thread can modify the
David 'Digit' Turnerb57db752012-01-24 13:20:38 +01001157 * counter bits in the mutex value.
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001158 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001159 if (MUTEX_COUNTER_BITS_WILL_OVERFLOW(mvalue)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001160 return EAGAIN;
1161 }
1162
1163 /* We own the mutex, but other threads are able to change
David 'Digit' Turnerb57db752012-01-24 13:20:38 +01001164 * the lower bits (e.g. promoting it to "contended"), so we
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001165 * need to use an atomic cmpxchg loop to update the counter.
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001166 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001167 for (;;) {
1168 /* increment counter, overflow was already checked */
1169 int newval = mvalue + MUTEX_COUNTER_BITS_ONE;
1170 if (__likely(__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0)) {
1171 /* mutex is still locked, not need for a memory barrier */
1172 return 0;
1173 }
1174 /* the value was changed, this happens when another thread changes
1175 * the lower state bits from 1 to 2 to indicate contention. This
1176 * cannot change the counter, so simply reload and try again.
1177 */
1178 mvalue = mutex->value;
1179 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001180}
1181
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001182__LIBC_HIDDEN__
1183int pthread_mutex_lock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001184{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001185 int mvalue, mtype, tid, new_lock_type, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001186
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001187 if (__unlikely(mutex == NULL))
1188 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001189
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001190 mvalue = mutex->value;
1191 mtype = (mvalue & MUTEX_TYPE_MASK);
1192 shared = (mvalue & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001193
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001194 /* Handle normal case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001195 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) ) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001196 _normal_lock(mutex, shared);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001197 return 0;
1198 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001199
1200 /* Do we already own this recursive or error-check mutex ? */
1201 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001202 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001203 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001204
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001205 /* Add in shared state to avoid extra 'or' operations below */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001206 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001207
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001208 /* First, if the mutex is unlocked, try to quickly acquire it.
1209 * In the optimistic case where this works, set the state to 1 to
1210 * indicate locked with no contention */
1211 if (mvalue == mtype) {
1212 int newval = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1213 if (__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0) {
1214 ANDROID_MEMBAR_FULL();
1215 return 0;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001216 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001217 /* argh, the value changed, reload before entering the loop */
1218 mvalue = mutex->value;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001219 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001220
1221 for (;;) {
1222 int newval;
1223
1224 /* if the mutex is unlocked, its value should be 'mtype' and
1225 * we try to acquire it by setting its owner and state atomically.
1226 * NOTE: We put the state to 2 since we _know_ there is contention
1227 * when we are in this loop. This ensures all waiters will be
1228 * unlocked.
1229 */
1230 if (mvalue == mtype) {
1231 newval = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1232 /* TODO: Change this to __bionic_cmpxchg_acquire when we
1233 * implement it to get rid of the explicit memory
1234 * barrier below.
1235 */
1236 if (__unlikely(__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0)) {
1237 mvalue = mutex->value;
1238 continue;
1239 }
1240 ANDROID_MEMBAR_FULL();
1241 return 0;
1242 }
1243
1244 /* the mutex is already locked by another thread, if its state is 1
1245 * we will change it to 2 to indicate contention. */
1246 if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(mvalue)) {
1247 newval = MUTEX_STATE_BITS_FLIP_CONTENTION(mvalue); /* locked state 1 => state 2 */
1248 if (__unlikely(__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0)) {
1249 mvalue = mutex->value;
1250 continue;
1251 }
1252 mvalue = newval;
1253 }
1254
1255 /* wait until the mutex is unlocked */
1256 __futex_wait_ex(&mutex->value, shared, mvalue, NULL);
1257
1258 mvalue = mutex->value;
1259 }
1260 /* NOTREACHED */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001261}
1262
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001263int pthread_mutex_lock(pthread_mutex_t *mutex)
1264{
1265 int err = pthread_mutex_lock_impl(mutex);
1266#ifdef PTHREAD_DEBUG
1267 if (PTHREAD_DEBUG_ENABLED) {
1268 if (!err) {
1269 pthread_debug_mutex_lock_check(mutex);
1270 }
1271 }
1272#endif
1273 return err;
1274}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001275
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001276__LIBC_HIDDEN__
1277int pthread_mutex_unlock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001278{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001279 int mvalue, mtype, tid, oldv, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001280
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001281 if (__unlikely(mutex == NULL))
1282 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001283
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001284 mvalue = mutex->value;
1285 mtype = (mvalue & MUTEX_TYPE_MASK);
1286 shared = (mvalue & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001287
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001288 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001289 if (__likely(mtype == MUTEX_TYPE_BITS_NORMAL)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001290 _normal_unlock(mutex, shared);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001291 return 0;
1292 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001293
1294 /* Do we already own this recursive or error-check mutex ? */
1295 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001296 if ( tid != MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001297 return EPERM;
1298
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001299 /* If the counter is > 0, we can simply decrement it atomically.
1300 * Since other threads can mutate the lower state bits (and only the
1301 * lower state bits), use a cmpxchg to do it.
1302 */
1303 if (!MUTEX_COUNTER_BITS_IS_ZERO(mvalue)) {
1304 for (;;) {
1305 int newval = mvalue - MUTEX_COUNTER_BITS_ONE;
1306 if (__likely(__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0)) {
1307 /* success: we still own the mutex, so no memory barrier */
1308 return 0;
1309 }
1310 /* the value changed, so reload and loop */
1311 mvalue = mutex->value;
1312 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001313 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001314
1315 /* the counter is 0, so we're going to unlock the mutex by resetting
1316 * its value to 'unlocked'. We need to perform a swap in order
1317 * to read the current state, which will be 2 if there are waiters
1318 * to awake.
1319 *
1320 * TODO: Change this to __bionic_swap_release when we implement it
1321 * to get rid of the explicit memory barrier below.
1322 */
1323 ANDROID_MEMBAR_FULL(); /* RELEASE BARRIER */
1324 mvalue = __bionic_swap(mtype | shared | MUTEX_STATE_BITS_UNLOCKED, &mutex->value);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001325
1326 /* Wake one waiting thread, if any */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001327 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(mvalue)) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001328 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001329 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001330 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001331}
1332
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001333int pthread_mutex_unlock(pthread_mutex_t *mutex)
1334{
1335#ifdef PTHREAD_DEBUG
1336 if (PTHREAD_DEBUG_ENABLED) {
1337 pthread_debug_mutex_unlock_check(mutex);
1338 }
1339#endif
1340 return pthread_mutex_unlock_impl(mutex);
1341}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001342
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001343__LIBC_HIDDEN__
1344int pthread_mutex_trylock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001345{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001346 int mvalue, mtype, tid, oldv, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001347
1348 if (__unlikely(mutex == NULL))
1349 return EINVAL;
1350
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001351 mvalue = mutex->value;
1352 mtype = (mvalue & MUTEX_TYPE_MASK);
1353 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001354
1355 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001356 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001357 {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001358 if (__bionic_cmpxchg(shared|MUTEX_STATE_BITS_UNLOCKED,
1359 shared|MUTEX_STATE_BITS_LOCKED_UNCONTENDED,
1360 &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001361 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001362 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001363 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001364
1365 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001366 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001367
1368 /* Do we already own this recursive or error-check mutex ? */
1369 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001370 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001371 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001372
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001373 /* Same as pthread_mutex_lock, except that we don't want to wait, and
1374 * the only operation that can succeed is a single cmpxchg to acquire the
1375 * lock if it is released / not owned by anyone. No need for a complex loop.
1376 */
1377 mtype |= shared | MUTEX_STATE_BITS_UNLOCKED;
1378 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001379
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001380 if (__likely(__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0)) {
1381 ANDROID_MEMBAR_FULL();
1382 return 0;
1383 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001384
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001385 return EBUSY;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001386}
1387
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001388int pthread_mutex_trylock(pthread_mutex_t *mutex)
1389{
1390 int err = pthread_mutex_trylock_impl(mutex);
1391#ifdef PTHREAD_DEBUG
1392 if (PTHREAD_DEBUG_ENABLED) {
1393 if (!err) {
1394 pthread_debug_mutex_lock_check(mutex);
1395 }
1396 }
1397#endif
1398 return err;
1399}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001400
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001401/* initialize 'ts' with the difference between 'abstime' and the current time
1402 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
1403 */
1404static int
1405__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
1406{
1407 clock_gettime(clock, ts);
1408 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
1409 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
1410 if (ts->tv_nsec < 0) {
1411 ts->tv_sec--;
1412 ts->tv_nsec += 1000000000;
1413 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001414 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001415 return -1;
1416
1417 return 0;
1418}
1419
1420/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1421 * milliseconds.
1422 */
1423static void
1424__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1425{
1426 clock_gettime(clock, abstime);
1427 abstime->tv_sec += msecs/1000;
1428 abstime->tv_nsec += (msecs%1000)*1000000;
1429 if (abstime->tv_nsec >= 1000000000) {
1430 abstime->tv_sec++;
1431 abstime->tv_nsec -= 1000000000;
1432 }
1433}
1434
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001435__LIBC_HIDDEN__
1436int pthread_mutex_lock_timeout_np_impl(pthread_mutex_t *mutex, unsigned msecs)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001437{
1438 clockid_t clock = CLOCK_MONOTONIC;
1439 struct timespec abstime;
1440 struct timespec ts;
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001441 int mvalue, mtype, tid, oldv, new_lock_type, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001442
1443 /* compute absolute expiration time */
1444 __timespec_to_relative_msec(&abstime, msecs, clock);
1445
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001446 if (__unlikely(mutex == NULL))
1447 return EINVAL;
1448
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001449 mvalue = mutex->value;
1450 mtype = (mvalue & MUTEX_TYPE_MASK);
1451 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001452
1453 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001454 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001455 {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001456 const int unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
1457 const int locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1458 const int locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1459
1460 /* fast path for uncontended lock. Note: MUTEX_TYPE_BITS_NORMAL is 0 */
1461 if (__bionic_cmpxchg(unlocked, locked_uncontended, &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001462 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001463 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001464 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001465
1466 /* loop while needed */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001467 while (__bionic_swap(locked_contended, &mutex->value) != unlocked) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001468 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1469 return EBUSY;
1470
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001471 __futex_wait_ex(&mutex->value, shared, locked_contended, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001472 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001473 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001474 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001475 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001476
1477 /* Do we already own this recursive or error-check mutex ? */
1478 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001479 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001480 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001481
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001482 /* the following implements the same loop than pthread_mutex_lock_impl
1483 * but adds checks to ensure that the operation never exceeds the
1484 * absolute expiration time.
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001485 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001486 mtype |= shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001487
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001488 /* first try a quick lock */
1489 if (mvalue == mtype) {
1490 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1491 if (__likely(__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0)) {
1492 ANDROID_MEMBAR_FULL();
1493 return 0;
1494 }
1495 mvalue = mutex->value;
1496 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001497
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001498 for (;;) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001499 struct timespec ts;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001500
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001501 /* if the value is 'unlocked', try to acquire it directly */
1502 /* NOTE: put state to 2 since we know there is contention */
1503 if (mvalue == mtype) /* unlocked */ {
1504 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1505 if (__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0) {
1506 ANDROID_MEMBAR_FULL();
1507 return 0;
1508 }
1509 /* the value changed before we could lock it. We need to check
1510 * the time to avoid livelocks, reload the value, then loop again. */
1511 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1512 return EBUSY;
1513
1514 mvalue = mutex->value;
1515 continue;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001516 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001517
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001518 /* The value is locked. If 'uncontended', try to switch its state
1519 * to 'contented' to ensure we get woken up later. */
1520 if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(mvalue)) {
1521 int newval = MUTEX_STATE_BITS_FLIP_CONTENTION(mvalue);
1522 if (__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0) {
1523 /* this failed because the value changed, reload it */
1524 mvalue = mutex->value;
1525 } else {
1526 /* this succeeded, update mvalue */
1527 mvalue = newval;
1528 }
1529 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001530
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001531 /* check time and update 'ts' */
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001532 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1533 return EBUSY;
1534
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001535 /* Only wait to be woken up if the state is '2', otherwise we'll
1536 * simply loop right now. This can happen when the second cmpxchg
1537 * in our loop failed because the mutex was unlocked by another
1538 * thread.
1539 */
1540 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(mvalue)) {
1541 if (__futex_wait_ex(&mutex->value, shared, mvalue, &ts) == ETIMEDOUT) {
1542 return EBUSY;
1543 }
1544 mvalue = mutex->value;
1545 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001546 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001547 /* NOTREACHED */
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001548}
1549
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001550int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1551{
1552 int err = pthread_mutex_lock_timeout_np_impl(mutex, msecs);
1553#ifdef PTHREAD_DEBUG
1554 if (PTHREAD_DEBUG_ENABLED) {
1555 if (!err) {
1556 pthread_debug_mutex_lock_check(mutex);
1557 }
1558 }
1559#endif
1560 return err;
1561}
1562
1563int pthread_mutex_destroy(pthread_mutex_t *mutex)
1564{
1565 int ret;
1566
1567 /* use trylock to ensure that the mutex value is
1568 * valid and is not already locked. */
1569 ret = pthread_mutex_trylock_impl(mutex);
1570 if (ret != 0)
1571 return ret;
1572
1573 mutex->value = 0xdead10cc;
1574 return 0;
1575}
1576
1577
1578
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001579int pthread_condattr_init(pthread_condattr_t *attr)
1580{
1581 if (attr == NULL)
1582 return EINVAL;
1583
1584 *attr = PTHREAD_PROCESS_PRIVATE;
1585 return 0;
1586}
1587
1588int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1589{
1590 if (attr == NULL || pshared == NULL)
1591 return EINVAL;
1592
1593 *pshared = *attr;
1594 return 0;
1595}
1596
1597int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1598{
1599 if (attr == NULL)
1600 return EINVAL;
1601
1602 if (pshared != PTHREAD_PROCESS_SHARED &&
1603 pshared != PTHREAD_PROCESS_PRIVATE)
1604 return EINVAL;
1605
1606 *attr = pshared;
1607 return 0;
1608}
1609
1610int pthread_condattr_destroy(pthread_condattr_t *attr)
1611{
1612 if (attr == NULL)
1613 return EINVAL;
1614
1615 *attr = 0xdeada11d;
1616 return 0;
1617}
1618
1619/* We use one bit in condition variable values as the 'shared' flag
1620 * The rest is a counter.
1621 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001622#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001623#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001624#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1625
1626#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001627
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001628/* XXX *technically* there is a race condition that could allow
1629 * XXX a signal to be missed. If thread A is preempted in _wait()
1630 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001631 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001632 * XXX before thread A is scheduled again and calls futex_wait(),
1633 * XXX then the signal will be lost.
1634 */
1635
1636int pthread_cond_init(pthread_cond_t *cond,
1637 const pthread_condattr_t *attr)
1638{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001639 if (cond == NULL)
1640 return EINVAL;
1641
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001642 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001643
1644 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001645 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001646
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001647 return 0;
1648}
1649
1650int pthread_cond_destroy(pthread_cond_t *cond)
1651{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001652 if (cond == NULL)
1653 return EINVAL;
1654
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001655 cond->value = 0xdeadc04d;
1656 return 0;
1657}
1658
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001659/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001660 * pthread_cond_signal to atomically decrement the counter
1661 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001662 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001663static int
1664__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001665{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001666 long flags;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001667
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001668 if (__unlikely(cond == NULL))
1669 return EINVAL;
1670
1671 flags = (cond->value & ~COND_COUNTER_MASK);
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001672 for (;;) {
1673 long oldval = cond->value;
1674 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1675 | flags;
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001676 if (__bionic_cmpxchg(oldval, newval, &cond->value) == 0)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001677 break;
1678 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001679
Andy McFaddene2ac8982010-09-02 13:34:53 -07001680 /*
1681 * Ensure that all memory accesses previously made by this thread are
1682 * visible to the woken thread(s). On the other side, the "wait"
1683 * code will issue any necessary barriers when locking the mutex.
1684 *
1685 * This may not strictly be necessary -- if the caller follows
1686 * recommended practice and holds the mutex before signaling the cond
1687 * var, the mutex ops will provide correct semantics. If they don't
1688 * hold the mutex, they're subject to race conditions anyway.
1689 */
1690 ANDROID_MEMBAR_FULL();
1691
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001692 __futex_wake_ex(&cond->value, COND_IS_SHARED(cond), counter);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001693 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001694}
1695
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001696int pthread_cond_broadcast(pthread_cond_t *cond)
1697{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001698 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001699}
1700
1701int pthread_cond_signal(pthread_cond_t *cond)
1702{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001703 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001704}
1705
1706int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1707{
1708 return pthread_cond_timedwait(cond, mutex, NULL);
1709}
1710
1711int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1712 pthread_mutex_t * mutex,
1713 const struct timespec *reltime)
1714{
1715 int status;
1716 int oldvalue = cond->value;
1717
1718 pthread_mutex_unlock(mutex);
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001719 status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond), oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001720 pthread_mutex_lock(mutex);
1721
1722 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1723 return 0;
1724}
1725
1726int __pthread_cond_timedwait(pthread_cond_t *cond,
1727 pthread_mutex_t * mutex,
1728 const struct timespec *abstime,
1729 clockid_t clock)
1730{
1731 struct timespec ts;
1732 struct timespec * tsp;
1733
1734 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001735 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001736 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001737 tsp = &ts;
1738 } else {
1739 tsp = NULL;
1740 }
1741
1742 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1743}
1744
1745int pthread_cond_timedwait(pthread_cond_t *cond,
1746 pthread_mutex_t * mutex,
1747 const struct timespec *abstime)
1748{
1749 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1750}
1751
1752
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001753/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001754int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1755 pthread_mutex_t * mutex,
1756 const struct timespec *abstime)
1757{
1758 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1759}
1760
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001761int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1762 pthread_mutex_t * mutex,
1763 const struct timespec *abstime)
1764{
1765 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1766}
1767
1768int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1769 pthread_mutex_t * mutex,
1770 const struct timespec *reltime)
1771{
1772 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1773}
1774
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001775int pthread_cond_timeout_np(pthread_cond_t *cond,
1776 pthread_mutex_t * mutex,
1777 unsigned msecs)
1778{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001779 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001780
1781 ts.tv_sec = msecs / 1000;
1782 ts.tv_nsec = (msecs % 1000) * 1000000;
1783
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001784 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001785}
1786
1787
1788
1789/* A technical note regarding our thread-local-storage (TLS) implementation:
1790 *
1791 * There can be up to TLSMAP_SIZE independent TLS keys in a given process,
1792 * though the first TLSMAP_START keys are reserved for Bionic to hold
1793 * special thread-specific variables like errno or a pointer to
1794 * the current thread's descriptor.
1795 *
1796 * while stored in the TLS area, these entries cannot be accessed through
1797 * pthread_getspecific() / pthread_setspecific() and pthread_key_delete()
1798 *
1799 * also, some entries in the key table are pre-allocated (see tlsmap_lock)
1800 * to greatly simplify and speedup some OpenGL-related operations. though the
1801 * initialy value will be NULL on all threads.
1802 *
1803 * you can use pthread_getspecific()/setspecific() on these, and in theory
1804 * you could also call pthread_key_delete() as well, though this would
1805 * probably break some apps.
1806 *
1807 * The 'tlsmap_t' type defined below implements a shared global map of
1808 * currently created/allocated TLS keys and the destructors associated
1809 * with them. You should use tlsmap_lock/unlock to access it to avoid
1810 * any race condition.
1811 *
1812 * the global TLS map simply contains a bitmap of allocated keys, and
1813 * an array of destructors.
1814 *
1815 * each thread has a TLS area that is a simple array of TLSMAP_SIZE void*
1816 * pointers. the TLS area of the main thread is stack-allocated in
1817 * __libc_init_common, while the TLS area of other threads is placed at
1818 * the top of their stack in pthread_create.
1819 *
1820 * when pthread_key_create() is called, it finds the first free key in the
1821 * bitmap, then set it to 1, saving the destructor altogether
1822 *
1823 * when pthread_key_delete() is called. it will erase the key's bitmap bit
1824 * and its destructor, and will also clear the key data in the TLS area of
1825 * all created threads. As mandated by Posix, it is the responsability of
1826 * the caller of pthread_key_delete() to properly reclaim the objects that
1827 * were pointed to by these data fields (either before or after the call).
1828 *
1829 */
1830
1831/* TLS Map implementation
1832 */
1833
1834#define TLSMAP_START (TLS_SLOT_MAX_WELL_KNOWN+1)
1835#define TLSMAP_SIZE BIONIC_TLS_SLOTS
1836#define TLSMAP_BITS 32
1837#define TLSMAP_WORDS ((TLSMAP_SIZE+TLSMAP_BITS-1)/TLSMAP_BITS)
1838#define TLSMAP_WORD(m,k) (m)->map[(k)/TLSMAP_BITS]
1839#define TLSMAP_MASK(k) (1U << ((k)&(TLSMAP_BITS-1)))
1840
1841/* this macro is used to quickly check that a key belongs to a reasonable range */
1842#define TLSMAP_VALIDATE_KEY(key) \
1843 ((key) >= TLSMAP_START && (key) < TLSMAP_SIZE)
1844
1845/* the type of tls key destructor functions */
1846typedef void (*tls_dtor_t)(void*);
1847
1848typedef struct {
1849 int init; /* see comment in tlsmap_lock() */
1850 uint32_t map[TLSMAP_WORDS]; /* bitmap of allocated keys */
1851 tls_dtor_t dtors[TLSMAP_SIZE]; /* key destructors */
1852} tlsmap_t;
1853
1854static pthread_mutex_t _tlsmap_lock = PTHREAD_MUTEX_INITIALIZER;
1855static tlsmap_t _tlsmap;
1856
1857/* lock the global TLS map lock and return a handle to it */
1858static __inline__ tlsmap_t* tlsmap_lock(void)
1859{
1860 tlsmap_t* m = &_tlsmap;
1861
1862 pthread_mutex_lock(&_tlsmap_lock);
1863 /* we need to initialize the first entry of the 'map' array
1864 * with the value TLS_DEFAULT_ALLOC_MAP. doing it statically
1865 * when declaring _tlsmap is a bit awkward and is going to
1866 * produce warnings, so do it the first time we use the map
1867 * instead
1868 */
1869 if (__unlikely(!m->init)) {
1870 TLSMAP_WORD(m,0) = TLS_DEFAULT_ALLOC_MAP;
1871 m->init = 1;
1872 }
1873 return m;
1874}
1875
1876/* unlock the global TLS map */
1877static __inline__ void tlsmap_unlock(tlsmap_t* m)
1878{
1879 pthread_mutex_unlock(&_tlsmap_lock);
1880 (void)m; /* a good compiler is a happy compiler */
1881}
1882
1883/* test to see wether a key is allocated */
1884static __inline__ int tlsmap_test(tlsmap_t* m, int key)
1885{
1886 return (TLSMAP_WORD(m,key) & TLSMAP_MASK(key)) != 0;
1887}
1888
1889/* set the destructor and bit flag on a newly allocated key */
1890static __inline__ void tlsmap_set(tlsmap_t* m, int key, tls_dtor_t dtor)
1891{
1892 TLSMAP_WORD(m,key) |= TLSMAP_MASK(key);
1893 m->dtors[key] = dtor;
1894}
1895
1896/* clear the destructor and bit flag on an existing key */
1897static __inline__ void tlsmap_clear(tlsmap_t* m, int key)
1898{
1899 TLSMAP_WORD(m,key) &= ~TLSMAP_MASK(key);
1900 m->dtors[key] = NULL;
1901}
1902
1903/* allocate a new TLS key, return -1 if no room left */
1904static int tlsmap_alloc(tlsmap_t* m, tls_dtor_t dtor)
1905{
1906 int key;
1907
1908 for ( key = TLSMAP_START; key < TLSMAP_SIZE; key++ ) {
1909 if ( !tlsmap_test(m, key) ) {
1910 tlsmap_set(m, key, dtor);
1911 return key;
1912 }
1913 }
1914 return -1;
1915}
1916
1917
1918int pthread_key_create(pthread_key_t *key, void (*destructor_function)(void *))
1919{
1920 uint32_t err = ENOMEM;
1921 tlsmap_t* map = tlsmap_lock();
1922 int k = tlsmap_alloc(map, destructor_function);
1923
1924 if (k >= 0) {
1925 *key = k;
1926 err = 0;
1927 }
1928 tlsmap_unlock(map);
1929 return err;
1930}
1931
1932
1933/* This deletes a pthread_key_t. note that the standard mandates that this does
1934 * not call the destructor of non-NULL key values. Instead, it is the
Elliott Hughesbfeab1b2012-09-05 17:47:37 -07001935 * responsibility of the caller to properly dispose of the corresponding data
1936 * and resources, using any means it finds suitable.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001937 *
1938 * On the other hand, this function will clear the corresponding key data
1939 * values in all known threads. this prevents later (invalid) calls to
1940 * pthread_getspecific() to receive invalid/stale values.
1941 */
1942int pthread_key_delete(pthread_key_t key)
1943{
1944 uint32_t err;
1945 pthread_internal_t* thr;
1946 tlsmap_t* map;
1947
1948 if (!TLSMAP_VALIDATE_KEY(key)) {
1949 return EINVAL;
1950 }
1951
1952 map = tlsmap_lock();
1953
1954 if (!tlsmap_test(map, key)) {
1955 err = EINVAL;
1956 goto err1;
1957 }
1958
1959 /* clear value in all threads */
1960 pthread_mutex_lock(&gThreadListLock);
1961 for ( thr = gThreadList; thr != NULL; thr = thr->next ) {
1962 /* avoid zombie threads with a negative 'join_count'. these are really
1963 * already dead and don't have a TLS area anymore.
1964 *
1965 * similarly, it is possible to have thr->tls == NULL for threads that
1966 * were just recently created through pthread_create() but whose
1967 * startup trampoline (__thread_entry) hasn't been run yet by the
Bjorn Andersson0753dc62012-05-03 17:12:39 -07001968 * scheduler. thr->tls will also be NULL after it's stack has been
1969 * unmapped but before the ongoing pthread_join() is finished.
1970 * so check for this too.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001971 */
1972 if (thr->join_count < 0 || !thr->tls)
1973 continue;
1974
1975 thr->tls[key] = NULL;
1976 }
1977 tlsmap_clear(map, key);
1978
1979 pthread_mutex_unlock(&gThreadListLock);
1980 err = 0;
1981
1982err1:
1983 tlsmap_unlock(map);
1984 return err;
1985}
1986
1987
1988int pthread_setspecific(pthread_key_t key, const void *ptr)
1989{
1990 int err = EINVAL;
1991 tlsmap_t* map;
1992
1993 if (TLSMAP_VALIDATE_KEY(key)) {
1994 /* check that we're trying to set data for an allocated key */
1995 map = tlsmap_lock();
1996 if (tlsmap_test(map, key)) {
1997 ((uint32_t *)__get_tls())[key] = (uint32_t)ptr;
1998 err = 0;
1999 }
2000 tlsmap_unlock(map);
2001 }
2002 return err;
2003}
2004
2005void * pthread_getspecific(pthread_key_t key)
2006{
2007 if (!TLSMAP_VALIDATE_KEY(key)) {
2008 return NULL;
2009 }
2010
2011 /* for performance reason, we do not lock/unlock the global TLS map
2012 * to check that the key is properly allocated. if the key was not
2013 * allocated, the value read from the TLS should always be NULL
2014 * due to pthread_key_delete() clearing the values for all threads.
2015 */
2016 return (void *)(((unsigned *)__get_tls())[key]);
2017}
2018
2019/* Posix mandates that this be defined in <limits.h> but we don't have
2020 * it just yet.
2021 */
2022#ifndef PTHREAD_DESTRUCTOR_ITERATIONS
2023# define PTHREAD_DESTRUCTOR_ITERATIONS 4
2024#endif
2025
2026/* this function is called from pthread_exit() to remove all TLS key data
2027 * from this thread's TLS area. this must call the destructor of all keys
2028 * that have a non-NULL data value (and a non-NULL destructor).
2029 *
2030 * because destructors can do funky things like deleting/creating other
2031 * keys, we need to implement this in a loop
2032 */
2033static void pthread_key_clean_all(void)
2034{
2035 tlsmap_t* map;
2036 void** tls = (void**)__get_tls();
2037 int rounds = PTHREAD_DESTRUCTOR_ITERATIONS;
2038
2039 map = tlsmap_lock();
2040
2041 for (rounds = PTHREAD_DESTRUCTOR_ITERATIONS; rounds > 0; rounds--)
2042 {
2043 int kk, count = 0;
2044
2045 for (kk = TLSMAP_START; kk < TLSMAP_SIZE; kk++) {
2046 if ( tlsmap_test(map, kk) )
2047 {
2048 void* data = tls[kk];
2049 tls_dtor_t dtor = map->dtors[kk];
2050
2051 if (data != NULL && dtor != NULL)
2052 {
2053 /* we need to clear the key data now, this will prevent the
2054 * destructor (or a later one) from seeing the old value if
2055 * it calls pthread_getspecific() for some odd reason
2056 *
2057 * we do not do this if 'dtor == NULL' just in case another
2058 * destructor function might be responsible for manually
2059 * releasing the corresponding data.
2060 */
2061 tls[kk] = NULL;
2062
2063 /* because the destructor is free to call pthread_key_create
2064 * and/or pthread_key_delete, we need to temporarily unlock
2065 * the TLS map
2066 */
2067 tlsmap_unlock(map);
2068 (*dtor)(data);
2069 map = tlsmap_lock();
2070
2071 count += 1;
2072 }
2073 }
2074 }
2075
2076 /* if we didn't call any destructor, there is no need to check the
2077 * TLS data again
2078 */
2079 if (count == 0)
2080 break;
2081 }
2082 tlsmap_unlock(map);
2083}
2084
2085// man says this should be in <linux/unistd.h>, but it isn't
Jeff Brown10c8ce52011-11-18 15:17:07 -08002086extern int tgkill(int tgid, int tid, int sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002087
2088int pthread_kill(pthread_t tid, int sig)
2089{
2090 int ret;
2091 int old_errno = errno;
2092 pthread_internal_t * thread = (pthread_internal_t *)tid;
2093
Jeff Brown10c8ce52011-11-18 15:17:07 -08002094 ret = tgkill(getpid(), thread->kernel_id, sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002095 if (ret < 0) {
2096 ret = errno;
2097 errno = old_errno;
2098 }
2099
2100 return ret;
2101}
2102
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01002103/* Despite the fact that our kernel headers define sigset_t explicitly
2104 * as a 32-bit integer, the kernel system call really expects a 64-bit
2105 * bitmap for the signal set, or more exactly an array of two-32-bit
2106 * values (see $KERNEL/arch/$ARCH/include/asm/signal.h for details).
2107 *
2108 * Unfortunately, we cannot fix the sigset_t definition without breaking
2109 * the C library ABI, so perform a little runtime translation here.
2110 */
2111typedef union {
2112 sigset_t bionic;
2113 uint32_t kernel[2];
2114} kernel_sigset_t;
2115
2116/* this is a private syscall stub */
2117extern int __rt_sigprocmask(int, const kernel_sigset_t *, kernel_sigset_t *, size_t);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002118
2119int pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
2120{
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08002121 /* pthread_sigmask must return the error code, but the syscall
2122 * will set errno instead and return 0/-1
2123 */
2124 int ret, old_errno = errno;
2125
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01002126 /* We must convert *set into a kernel_sigset_t */
2127 kernel_sigset_t in_set, *in_set_ptr;
2128 kernel_sigset_t out_set;
2129
Bruce Bearee4a21c82011-12-05 11:25:37 -08002130 in_set.kernel[0] = in_set.kernel[1] = 0;
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01002131 out_set.kernel[0] = out_set.kernel[1] = 0;
2132
2133 /* 'in_set_ptr' is the second parameter to __rt_sigprocmask. It must be NULL
2134 * if 'set' is NULL to ensure correct semantics (which in this case would
2135 * be to ignore 'how' and return the current signal set into 'oset'.
David 'Digit' Turner5c8c00a2010-12-20 15:58:06 +01002136 */
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01002137 if (set == NULL) {
2138 in_set_ptr = NULL;
2139 } else {
2140 in_set.bionic = *set;
2141 in_set_ptr = &in_set;
2142 }
2143
2144 ret = __rt_sigprocmask(how, in_set_ptr, &out_set, sizeof(kernel_sigset_t));
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08002145 if (ret < 0)
2146 ret = errno;
2147
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01002148 if (oset)
2149 *oset = out_set.bionic;
2150
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08002151 errno = old_errno;
2152 return ret;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002153}
2154
2155
2156int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
2157{
2158 const int CLOCK_IDTYPE_BITS = 3;
2159 pthread_internal_t* thread = (pthread_internal_t*)tid;
2160
2161 if (!thread)
2162 return ESRCH;
2163
2164 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
2165 return 0;
2166}
2167
2168
2169/* NOTE: this implementation doesn't support a init function that throws a C++ exception
2170 * or calls fork()
2171 */
2172int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
2173{
Wink Savilleccc3d1e2010-06-28 11:41:16 -07002174 static pthread_mutex_t once_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07002175 volatile pthread_once_t* ocptr = once_control;
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002176 pthread_once_t value;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002177
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002178 /* PTHREAD_ONCE_INIT is 0, we use the following bit flags
2179 *
2180 * bit 0 set -> initialization is under way
2181 * bit 1 set -> initialization is complete
2182 */
2183#define ONCE_INITIALIZING (1 << 0)
2184#define ONCE_COMPLETED (1 << 1)
2185
2186 /* First check if the once is already initialized. This will be the common
2187 * case and we want to make this as fast as possible. Note that this still
2188 * requires a load_acquire operation here to ensure that all the
2189 * stores performed by the initialization function are observable on
2190 * this CPU after we exit.
2191 */
2192 if (__likely((*ocptr & ONCE_COMPLETED) != 0)) {
2193 ANDROID_MEMBAR_FULL();
2194 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002195 }
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002196
2197 for (;;) {
2198 /* Try to atomically set the INITIALIZING flag.
2199 * This requires a cmpxchg loop, and we may need
Elliott Hughesbfeab1b2012-09-05 17:47:37 -07002200 * to exit prematurely if we detect that
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002201 * COMPLETED is now set.
2202 */
2203 int32_t oldval, newval;
2204
2205 do {
2206 oldval = *ocptr;
2207 if ((oldval & ONCE_COMPLETED) != 0)
2208 break;
2209
2210 newval = oldval | ONCE_INITIALIZING;
2211 } while (__bionic_cmpxchg(oldval, newval, ocptr) != 0);
2212
2213 if ((oldval & ONCE_COMPLETED) != 0) {
2214 /* We detected that COMPLETED was set while in our loop */
2215 ANDROID_MEMBAR_FULL();
2216 return 0;
2217 }
2218
2219 if ((oldval & ONCE_INITIALIZING) == 0) {
2220 /* We got there first, we can jump out of the loop to
2221 * handle the initialization */
2222 break;
2223 }
2224
2225 /* Another thread is running the initialization and hasn't completed
2226 * yet, so wait for it, then try again. */
2227 __futex_wait_ex(ocptr, 0, oldval, NULL);
2228 }
2229
2230 /* call the initialization function. */
2231 (*init_routine)();
2232
2233 /* Do a store_release indicating that initialization is complete */
2234 ANDROID_MEMBAR_FULL();
2235 *ocptr = ONCE_COMPLETED;
2236
2237 /* Wake up any waiters, if any */
2238 __futex_wake_ex(ocptr, 0, INT_MAX);
2239
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002240 return 0;
2241}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03002242
2243/* This value is not exported by kernel headers, so hardcode it here */
2244#define MAX_TASK_COMM_LEN 16
2245#define TASK_COMM_FMT "/proc/self/task/%u/comm"
2246
2247int pthread_setname_np(pthread_t thid, const char *thname)
2248{
2249 size_t thname_len;
2250 int saved_errno, ret;
2251
2252 if (thid == 0 || thname == NULL)
2253 return EINVAL;
2254
2255 thname_len = strlen(thname);
2256 if (thname_len >= MAX_TASK_COMM_LEN)
2257 return ERANGE;
2258
2259 saved_errno = errno;
2260 if (thid == pthread_self())
2261 {
2262 ret = prctl(PR_SET_NAME, (unsigned long)thname, 0, 0, 0) ? errno : 0;
2263 }
2264 else
2265 {
2266 /* Have to change another thread's name */
2267 pthread_internal_t *thread = (pthread_internal_t *)thid;
2268 char comm_name[sizeof(TASK_COMM_FMT) + 8];
2269 ssize_t n;
2270 int fd;
2271
2272 snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, (unsigned int)thread->kernel_id);
2273 fd = open(comm_name, O_RDWR);
2274 if (fd == -1)
2275 {
2276 ret = errno;
2277 goto exit;
2278 }
2279 n = TEMP_FAILURE_RETRY(write(fd, thname, thname_len));
2280 close(fd);
2281
2282 if (n < 0)
2283 ret = errno;
2284 else if ((size_t)n != thname_len)
2285 ret = EIO;
2286 else
2287 ret = 0;
2288 }
2289exit:
2290 errno = saved_errno;
2291 return ret;
2292}
Glenn Kastend53cae02011-07-11 15:41:28 -07002293
2294/* Return the kernel thread ID for a pthread.
2295 * This is only defined for implementations where pthread <-> kernel is 1:1, which this is.
2296 * Not the same as pthread_getthreadid_np, which is commonly defined to be opaque.
2297 * Internal, not an NDK API.
2298 */
2299
2300pid_t __pthread_gettid(pthread_t thid)
2301{
2302 pthread_internal_t* thread = (pthread_internal_t*)thid;
2303 return thread->kernel_id;
2304}
Jean-Baptiste Querufaca92f2012-03-26 15:25:19 -07002305
2306int __pthread_settid(pthread_t thid, pid_t tid)
2307{
2308 if (thid == 0)
2309 return EINVAL;
2310
2311 pthread_internal_t* thread = (pthread_internal_t*)thid;
2312 thread->kernel_id = tid;
2313
2314 return 0;
2315}