blob: 791a772b0a81481cc7198d87869a7b9d45807f13 [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__
Xi Wangae8eb742012-10-27 02:02:01 -0400214int _init_thread(pthread_internal_t* thread, pid_t kernel_id, const pthread_attr_t* attr,
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700215 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
Xi Wangae8eb742012-10-27 02:02:01 -0400219 thread->attr = *attr;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800220 thread->attr.stack_base = stack_base;
Xi Wangae8eb742012-10-27 02:02:01 -0400221 thread->kernel_id = kernel_id;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800222
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100223 // Make a note of whether the user supplied this stack (so we know whether or not to free it).
224 if (attr->stack_base == stack_base) {
225 thread->attr.flags |= PTHREAD_ATTR_FLAG_USER_STACK;
226 }
227
228 // Set the scheduling policy/priority of the thread.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800229 if (thread->attr.sched_policy != SCHED_NORMAL) {
230 struct sched_param param;
231 param.sched_priority = thread->attr.sched_priority;
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100232 if (sched_setscheduler(kernel_id, thread->attr.sched_policy, &param) == -1) {
Xi Wangae8eb742012-10-27 02:02:01 -0400233 // For backwards compatibility reasons, we just warn about failures here.
234 // error = errno;
Dave Burke88f1ea82012-09-17 20:37:38 -0700235 const char* msg = "pthread_create sched_setscheduler call failed: %s\n";
236 __libc_android_log_print(ANDROID_LOG_WARN, "libc", msg, strerror(errno));
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100237 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800238 }
239
240 pthread_cond_init(&thread->join_cond, NULL);
241 thread->join_count = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800242 thread->cleanup_stack = NULL;
243
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700244 if (add_to_thread_list) {
245 _pthread_internal_add(thread);
246 }
247
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100248 return error;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800249}
250
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800251static void *mkstack(size_t size, size_t guard_size)
252{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800253 pthread_mutex_lock(&mmap_lock);
254
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100255 int prot = PROT_READ | PROT_WRITE;
256 int flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE;
Elliott Hughes9c3eca72012-05-08 13:26:28 -0700257 void* stack = mmap(NULL, size, prot, flags, -1, 0);
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100258 if (stack == MAP_FAILED) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800259 stack = NULL;
260 goto done;
261 }
262
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100263 if (mprotect(stack, guard_size, PROT_NONE) == -1) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800264 munmap(stack, size);
265 stack = NULL;
266 goto done;
267 }
268
269done:
270 pthread_mutex_unlock(&mmap_lock);
271 return stack;
272}
273
274/*
Andy McFaddene2ac8982010-09-02 13:34:53 -0700275 * Create a new thread. The thread's stack is laid out like so:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800276 *
277 * +---------------------------+
278 * | pthread_internal_t |
279 * +---------------------------+
280 * | |
281 * | TLS area |
282 * | |
283 * +---------------------------+
284 * | |
285 * . .
286 * . stack area .
287 * . .
288 * | |
289 * +---------------------------+
290 * | guard page |
291 * +---------------------------+
292 *
293 * note that TLS[0] must be a pointer to itself, this is required
294 * by the thread-local storage implementation of the x86 Linux
295 * kernel, where the TLS pointer is read by reading fs:[0]
296 */
297int pthread_create(pthread_t *thread_out, pthread_attr_t const * attr,
298 void *(*start_routine)(void *), void * arg)
299{
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100300 int old_errno = errno;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800301
302 /* this will inform the rest of the C library that at least one thread
303 * was created. this will enforce certain functions to acquire/release
304 * locks (e.g. atexit()) to protect shared global structures.
305 *
306 * this works because pthread_create() is not called by the C library
307 * initialization routine that sets up the main thread's data structures.
308 */
309 __isthreaded = 1;
310
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100311 pthread_internal_t* thread = calloc(sizeof(*thread), 1);
312 if (thread == NULL) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800313 return ENOMEM;
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100314 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800315
316 if (attr == NULL) {
317 attr = &gDefaultPthreadAttr;
318 }
319
320 // make sure the stack is PAGE_SIZE aligned
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100321 size_t stack_size = (attr->stack_size + (PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
322 uint8_t* stack = attr->stack_base;
323 if (stack == NULL) {
324 stack = mkstack(stack_size, attr->guard_size);
325 if (stack == NULL) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800326 _pthread_internal_free(thread);
327 return ENOMEM;
328 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800329 }
330
331 // Make room for TLS
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100332 void** tls = (void**)(stack + stack_size - BIONIC_TLS_SLOTS*sizeof(void*));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800333
334 // Create a mutex for the thread in TLS_SLOT_SELF to wait on once it starts so we can keep
335 // it from doing anything until after we notify the debugger about it
Andy McFaddene2ac8982010-09-02 13:34:53 -0700336 //
337 // This also provides the memory barrier we need to ensure that all
338 // memory accesses previously performed by this thread are visible to
339 // the new thread.
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100340 pthread_mutex_t* start_mutex = (pthread_mutex_t*) &tls[TLS_SLOT_SELF];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800341 pthread_mutex_init(start_mutex, NULL);
342 pthread_mutex_lock(start_mutex);
343
344 tls[TLS_SLOT_THREAD_ID] = thread;
345
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100346 int flags = CLONE_FILES | CLONE_FS | CLONE_VM | CLONE_SIGHAND |
347 CLONE_THREAD | CLONE_SYSVSEM | CLONE_DETACHED;
348 int tid = __pthread_clone((int(*)(void*))start_routine, tls, flags, arg);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800349
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100350 if (tid < 0) {
351 int clone_errno = errno;
352 pthread_mutex_unlock(start_mutex);
353 if (stack != attr->stack_base) {
354 munmap(stack, stack_size);
355 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800356 _pthread_internal_free(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800357 errno = old_errno;
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100358 return clone_errno;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800359 }
360
Xi Wangae8eb742012-10-27 02:02:01 -0400361 int init_errno = _init_thread(thread, tid, attr, stack, true);
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100362 if (init_errno != 0) {
363 // Mark the thread detached and let its __thread_entry run to
364 // completion. (It'll just exit immediately, cleaning up its resources.)
365 thread->internal_flags |= kPthreadInitFailed;
366 thread->attr.flags |= PTHREAD_ATTR_FLAG_DETACHED;
367 pthread_mutex_unlock(start_mutex);
368 errno = old_errno;
369 return init_errno;
370 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800371
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100372 // Notify any debuggers about the new thread.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800373 pthread_mutex_lock(&gDebuggerNotificationLock);
374 _thread_created_hook(tid);
375 pthread_mutex_unlock(&gDebuggerNotificationLock);
376
Jurijs Oniscuks2932f042012-07-05 14:57:38 +0200377 // Publish the pthread_t and let the thread run.
378 *thread_out = (pthread_t) thread;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800379 pthread_mutex_unlock(start_mutex);
380
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800381 return 0;
382}
383
384
385int pthread_attr_init(pthread_attr_t * attr)
386{
387 *attr = gDefaultPthreadAttr;
388 return 0;
389}
390
391int pthread_attr_destroy(pthread_attr_t * attr)
392{
393 memset(attr, 0x42, sizeof(pthread_attr_t));
394 return 0;
395}
396
397int pthread_attr_setdetachstate(pthread_attr_t * attr, int state)
398{
399 if (state == PTHREAD_CREATE_DETACHED) {
400 attr->flags |= PTHREAD_ATTR_FLAG_DETACHED;
401 } else if (state == PTHREAD_CREATE_JOINABLE) {
402 attr->flags &= ~PTHREAD_ATTR_FLAG_DETACHED;
403 } else {
404 return EINVAL;
405 }
406 return 0;
407}
408
409int pthread_attr_getdetachstate(pthread_attr_t const * attr, int * state)
410{
411 *state = (attr->flags & PTHREAD_ATTR_FLAG_DETACHED)
412 ? PTHREAD_CREATE_DETACHED
413 : PTHREAD_CREATE_JOINABLE;
414 return 0;
415}
416
417int pthread_attr_setschedpolicy(pthread_attr_t * attr, int policy)
418{
419 attr->sched_policy = policy;
420 return 0;
421}
422
423int pthread_attr_getschedpolicy(pthread_attr_t const * attr, int * policy)
424{
425 *policy = attr->sched_policy;
426 return 0;
427}
428
429int pthread_attr_setschedparam(pthread_attr_t * attr, struct sched_param const * param)
430{
431 attr->sched_priority = param->sched_priority;
432 return 0;
433}
434
435int pthread_attr_getschedparam(pthread_attr_t const * attr, struct sched_param * param)
436{
437 param->sched_priority = attr->sched_priority;
438 return 0;
439}
440
441int pthread_attr_setstacksize(pthread_attr_t * attr, size_t stack_size)
442{
443 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
444 return EINVAL;
445 }
446 attr->stack_size = stack_size;
447 return 0;
448}
449
450int pthread_attr_getstacksize(pthread_attr_t const * attr, size_t * stack_size)
451{
452 *stack_size = attr->stack_size;
453 return 0;
454}
455
456int pthread_attr_setstackaddr(pthread_attr_t * attr, void * stack_addr)
457{
458#if 1
459 // It's not clear if this is setting the top or bottom of the stack, so don't handle it for now.
460 return ENOSYS;
461#else
462 if ((uint32_t)stack_addr & (PAGE_SIZE - 1)) {
463 return EINVAL;
464 }
465 attr->stack_base = stack_addr;
466 return 0;
467#endif
468}
469
470int pthread_attr_getstackaddr(pthread_attr_t const * attr, void ** stack_addr)
471{
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700472 *stack_addr = (char*)attr->stack_base + attr->stack_size;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800473 return 0;
474}
475
476int pthread_attr_setstack(pthread_attr_t * attr, void * stack_base, size_t stack_size)
477{
478 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
479 return EINVAL;
480 }
481 if ((uint32_t)stack_base & (PAGE_SIZE - 1)) {
482 return EINVAL;
483 }
484 attr->stack_base = stack_base;
485 attr->stack_size = stack_size;
486 return 0;
487}
488
489int pthread_attr_getstack(pthread_attr_t const * attr, void ** stack_base, size_t * stack_size)
490{
491 *stack_base = attr->stack_base;
492 *stack_size = attr->stack_size;
493 return 0;
494}
495
496int pthread_attr_setguardsize(pthread_attr_t * attr, size_t guard_size)
497{
498 if (guard_size & (PAGE_SIZE - 1) || guard_size < PAGE_SIZE) {
499 return EINVAL;
500 }
501
502 attr->guard_size = guard_size;
503 return 0;
504}
505
506int pthread_attr_getguardsize(pthread_attr_t const * attr, size_t * guard_size)
507{
508 *guard_size = attr->guard_size;
509 return 0;
510}
511
512int pthread_getattr_np(pthread_t thid, pthread_attr_t * attr)
513{
514 pthread_internal_t * thread = (pthread_internal_t *)thid;
515 *attr = thread->attr;
516 return 0;
517}
518
519int pthread_attr_setscope(pthread_attr_t *attr, int scope)
520{
521 if (scope == PTHREAD_SCOPE_SYSTEM)
522 return 0;
523 if (scope == PTHREAD_SCOPE_PROCESS)
524 return ENOTSUP;
525
526 return EINVAL;
527}
528
529int pthread_attr_getscope(pthread_attr_t const *attr)
530{
531 return PTHREAD_SCOPE_SYSTEM;
532}
533
534
535/* CAVEAT: our implementation of pthread_cleanup_push/pop doesn't support C++ exceptions
536 * and thread cancelation
537 */
538
539void __pthread_cleanup_push( __pthread_cleanup_t* c,
540 __pthread_cleanup_func_t routine,
541 void* arg )
542{
543 pthread_internal_t* thread = __get_thread();
544
545 c->__cleanup_routine = routine;
546 c->__cleanup_arg = arg;
547 c->__cleanup_prev = thread->cleanup_stack;
548 thread->cleanup_stack = c;
549}
550
551void __pthread_cleanup_pop( __pthread_cleanup_t* c, int execute )
552{
553 pthread_internal_t* thread = __get_thread();
554
555 thread->cleanup_stack = c->__cleanup_prev;
556 if (execute)
557 c->__cleanup_routine(c->__cleanup_arg);
558}
559
560/* used by pthread_exit() to clean all TLS keys of the current thread */
561static void pthread_key_clean_all(void);
562
563void pthread_exit(void * retval)
564{
565 pthread_internal_t* thread = __get_thread();
566 void* stack_base = thread->attr.stack_base;
567 int stack_size = thread->attr.stack_size;
568 int user_stack = (thread->attr.flags & PTHREAD_ATTR_FLAG_USER_STACK) != 0;
Jack Rene480fc82011-09-21 12:44:11 +0200569 sigset_t mask;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800570
571 // call the cleanup handlers first
572 while (thread->cleanup_stack) {
573 __pthread_cleanup_t* c = thread->cleanup_stack;
574 thread->cleanup_stack = c->__cleanup_prev;
575 c->__cleanup_routine(c->__cleanup_arg);
576 }
577
578 // call the TLS destructors, it is important to do that before removing this
579 // thread from the global list. this will ensure that if someone else deletes
580 // a TLS key, the corresponding value will be set to NULL in this thread's TLS
581 // space (see pthread_key_delete)
582 pthread_key_clean_all();
583
584 // if the thread is detached, destroy the pthread_internal_t
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400585 // otherwise, keep it in memory and signal any joiners.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800586 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
587 _pthread_internal_remove(thread);
588 _pthread_internal_free(thread);
589 } else {
Bjorn Andersson0753dc62012-05-03 17:12:39 -0700590 pthread_mutex_lock(&gThreadListLock);
591
592 /* make sure that the thread struct doesn't have stale pointers to a stack that
593 * will be unmapped after the exit call below.
594 */
595 if (!user_stack) {
596 thread->attr.stack_base = NULL;
597 thread->attr.stack_size = 0;
598 thread->tls = NULL;
599 }
600
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800601 /* the join_count field is used to store the number of threads waiting for
602 * the termination of this thread with pthread_join(),
603 *
604 * if it is positive we need to signal the waiters, and we do not touch
605 * the count (it will be decremented by the waiters, the last one will
606 * also remove/free the thread structure
607 *
608 * if it is zero, we set the count value to -1 to indicate that the
609 * thread is in 'zombie' state: it has stopped executing, and its stack
610 * is gone (as well as its TLS area). when another thread calls pthread_join()
611 * on it, it will immediately free the thread and return.
612 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800613 thread->return_value = retval;
614 if (thread->join_count > 0) {
615 pthread_cond_broadcast(&thread->join_cond);
616 } else {
617 thread->join_count = -1; /* zombie thread */
618 }
619 pthread_mutex_unlock(&gThreadListLock);
620 }
621
Jack Rene480fc82011-09-21 12:44:11 +0200622 sigfillset(&mask);
623 sigdelset(&mask, SIGSEGV);
624 (void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *)NULL);
625
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800626 // destroy the thread stack
627 if (user_stack)
628 _exit_thread((int)retval);
629 else
630 _exit_with_stack_teardown(stack_base, stack_size, (int)retval);
631}
632
633int pthread_join(pthread_t thid, void ** ret_val)
634{
635 pthread_internal_t* thread = (pthread_internal_t*)thid;
Elliott Hughes14f19592012-10-29 10:19:44 -0700636 if (thid == pthread_self()) {
637 return EDEADLK;
638 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800639
640 // check that the thread still exists and is not detached
641 pthread_mutex_lock(&gThreadListLock);
642
Elliott Hughes14f19592012-10-29 10:19:44 -0700643 for (thread = gThreadList; thread != NULL; thread = thread->next) {
644 if (thread == (pthread_internal_t*)thid) {
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200645 goto FoundIt;
Elliott Hughes14f19592012-10-29 10:19:44 -0700646 }
647 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800648
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200649 pthread_mutex_unlock(&gThreadListLock);
650 return ESRCH;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800651
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200652FoundIt:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800653 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
654 pthread_mutex_unlock(&gThreadListLock);
655 return EINVAL;
656 }
657
658 /* wait for thread death when needed
659 *
660 * if the 'join_count' is negative, this is a 'zombie' thread that
661 * is already dead and without stack/TLS
662 *
663 * otherwise, we need to increment 'join-count' and wait to be signaled
664 */
Elliott Hughes14f19592012-10-29 10:19:44 -0700665 int count = thread->join_count;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800666 if (count >= 0) {
667 thread->join_count += 1;
668 pthread_cond_wait( &thread->join_cond, &gThreadListLock );
669 count = --thread->join_count;
670 }
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400671 if (ret_val) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800672 *ret_val = thread->return_value;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400673 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800674
675 /* remove thread descriptor when we're the last joiner or when the
676 * thread was already a zombie.
677 */
678 if (count <= 0) {
679 _pthread_internal_remove_locked(thread);
680 _pthread_internal_free(thread);
681 }
682 pthread_mutex_unlock(&gThreadListLock);
683 return 0;
684}
685
686int pthread_detach( pthread_t thid )
687{
688 pthread_internal_t* thread;
689 int result = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800690
691 pthread_mutex_lock(&gThreadListLock);
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400692 for (thread = gThreadList; thread != NULL; thread = thread->next) {
693 if (thread == (pthread_internal_t*)thid) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800694 goto FoundIt;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400695 }
696 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800697
698 result = ESRCH;
699 goto Exit;
700
701FoundIt:
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400702 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
703 result = EINVAL; // Already detached.
704 goto Exit;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800705 }
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400706
707 if (thread->join_count > 0) {
708 result = 0; // Already being joined; silently do nothing, like glibc.
709 goto Exit;
710 }
711
712 thread->attr.flags |= PTHREAD_ATTR_FLAG_DETACHED;
713
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800714Exit:
715 pthread_mutex_unlock(&gThreadListLock);
716 return result;
717}
718
719pthread_t pthread_self(void)
720{
721 return (pthread_t)__get_thread();
722}
723
724int pthread_equal(pthread_t one, pthread_t two)
725{
726 return (one == two ? 1 : 0);
727}
728
729int pthread_getschedparam(pthread_t thid, int * policy,
730 struct sched_param * param)
731{
732 int old_errno = errno;
733
734 pthread_internal_t * thread = (pthread_internal_t *)thid;
735 int err = sched_getparam(thread->kernel_id, param);
736 if (!err) {
737 *policy = sched_getscheduler(thread->kernel_id);
738 } else {
739 err = errno;
740 errno = old_errno;
741 }
742 return err;
743}
744
745int pthread_setschedparam(pthread_t thid, int policy,
746 struct sched_param const * param)
747{
748 pthread_internal_t * thread = (pthread_internal_t *)thid;
749 int old_errno = errno;
750 int ret;
751
752 ret = sched_setscheduler(thread->kernel_id, policy, param);
753 if (ret < 0) {
754 ret = errno;
755 errno = old_errno;
756 }
757 return ret;
758}
759
760
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800761/* a mutex is implemented as a 32-bit integer holding the following fields
762 *
763 * bits: name description
764 * 31-16 tid owner thread's kernel id (recursive and errorcheck only)
765 * 15-14 type mutex type
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700766 * 13 shared process-shared flag
767 * 12-2 counter counter of recursive mutexes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800768 * 1-0 state lock state (0, 1 or 2)
769 */
770
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100771/* Convenience macro, creates a mask of 'bits' bits that starts from
772 * the 'shift'-th least significant bit in a 32-bit word.
773 *
774 * Examples: FIELD_MASK(0,4) -> 0xf
775 * FIELD_MASK(16,9) -> 0x1ff0000
776 */
777#define FIELD_MASK(shift,bits) (((1 << (bits))-1) << (shift))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800778
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100779/* This one is used to create a bit pattern from a given field value */
780#define FIELD_TO_BITS(val,shift,bits) (((val) & ((1 << (bits))-1)) << (shift))
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100781
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100782/* And this one does the opposite, i.e. extract a field's value from a bit pattern */
783#define FIELD_FROM_BITS(val,shift,bits) (((val) >> (shift)) & ((1 << (bits))-1))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800784
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100785/* Mutex state:
786 *
787 * 0 for unlocked
788 * 1 for locked, no waiters
789 * 2 for locked, maybe waiters
790 */
791#define MUTEX_STATE_SHIFT 0
792#define MUTEX_STATE_LEN 2
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800793
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100794#define MUTEX_STATE_MASK FIELD_MASK(MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
795#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
796#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
797
798#define MUTEX_STATE_UNLOCKED 0 /* must be 0 to match __PTHREAD_MUTEX_INIT_VALUE */
799#define MUTEX_STATE_LOCKED_UNCONTENDED 1 /* must be 1 due to atomic dec in unlock operation */
800#define MUTEX_STATE_LOCKED_CONTENDED 2 /* must be 1 + LOCKED_UNCONTENDED due to atomic dec */
801
802#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
803#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
804
805#define MUTEX_STATE_BITS_UNLOCKED MUTEX_STATE_TO_BITS(MUTEX_STATE_UNLOCKED)
806#define MUTEX_STATE_BITS_LOCKED_UNCONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_UNCONTENDED)
807#define MUTEX_STATE_BITS_LOCKED_CONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_CONTENDED)
808
809/* return true iff the mutex if locked with no waiters */
810#define MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_UNCONTENDED)
811
812/* return true iff the mutex if locked with maybe waiters */
813#define MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_CONTENDED)
814
815/* used to flip from LOCKED_UNCONTENDED to LOCKED_CONTENDED */
816#define MUTEX_STATE_BITS_FLIP_CONTENTION(v) ((v) ^ (MUTEX_STATE_BITS_LOCKED_CONTENDED ^ MUTEX_STATE_BITS_LOCKED_UNCONTENDED))
817
818/* Mutex counter:
819 *
820 * We need to check for overflow before incrementing, and we also need to
821 * detect when the counter is 0
822 */
823#define MUTEX_COUNTER_SHIFT 2
824#define MUTEX_COUNTER_LEN 11
825#define MUTEX_COUNTER_MASK FIELD_MASK(MUTEX_COUNTER_SHIFT, MUTEX_COUNTER_LEN)
826
827#define MUTEX_COUNTER_BITS_WILL_OVERFLOW(v) (((v) & MUTEX_COUNTER_MASK) == MUTEX_COUNTER_MASK)
828#define MUTEX_COUNTER_BITS_IS_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
829
830/* Used to increment the counter directly after overflow has been checked */
831#define MUTEX_COUNTER_BITS_ONE FIELD_TO_BITS(1,MUTEX_COUNTER_SHIFT,MUTEX_COUNTER_LEN)
832
833/* Returns true iff the counter is 0 */
834#define MUTEX_COUNTER_BITS_ARE_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
835
836/* Mutex shared bit flag
837 *
838 * This flag is set to indicate that the mutex is shared among processes.
839 * This changes the futex opcode we use for futex wait/wake operations
840 * (non-shared operations are much faster).
841 */
842#define MUTEX_SHARED_SHIFT 13
843#define MUTEX_SHARED_MASK FIELD_MASK(MUTEX_SHARED_SHIFT,1)
844
845/* Mutex type:
846 *
847 * We support normal, recursive and errorcheck mutexes.
848 *
849 * The constants defined here *cannot* be changed because they must match
850 * the C library ABI which defines the following initialization values in
851 * <pthread.h>:
852 *
853 * __PTHREAD_MUTEX_INIT_VALUE
854 * __PTHREAD_RECURSIVE_MUTEX_VALUE
855 * __PTHREAD_ERRORCHECK_MUTEX_INIT_VALUE
856 */
857#define MUTEX_TYPE_SHIFT 14
858#define MUTEX_TYPE_LEN 2
859#define MUTEX_TYPE_MASK FIELD_MASK(MUTEX_TYPE_SHIFT,MUTEX_TYPE_LEN)
860
861#define MUTEX_TYPE_NORMAL 0 /* Must be 0 to match __PTHREAD_MUTEX_INIT_VALUE */
862#define MUTEX_TYPE_RECURSIVE 1
863#define MUTEX_TYPE_ERRORCHECK 2
864
865#define MUTEX_TYPE_TO_BITS(t) FIELD_TO_BITS(t, MUTEX_TYPE_SHIFT, MUTEX_TYPE_LEN)
866
867#define MUTEX_TYPE_BITS_NORMAL MUTEX_TYPE_TO_BITS(MUTEX_TYPE_NORMAL)
868#define MUTEX_TYPE_BITS_RECURSIVE MUTEX_TYPE_TO_BITS(MUTEX_TYPE_RECURSIVE)
869#define MUTEX_TYPE_BITS_ERRORCHECK MUTEX_TYPE_TO_BITS(MUTEX_TYPE_ERRORCHECK)
870
871/* Mutex owner field:
872 *
873 * This is only used for recursive and errorcheck mutexes. It holds the
874 * kernel TID of the owning thread. Note that this works because the Linux
875 * kernel _only_ uses 16-bit values for thread ids.
876 *
877 * More specifically, it will wrap to 10000 when it reaches over 32768 for
878 * application processes. You can check this by running the following inside
879 * an adb shell session:
880 *
881 OLDPID=$$;
882 while true; do
883 NEWPID=$(sh -c 'echo $$')
884 if [ "$NEWPID" -gt 32768 ]; then
885 echo "AARGH: new PID $NEWPID is too high!"
886 exit 1
887 fi
888 if [ "$NEWPID" -lt "$OLDPID" ]; then
889 echo "****** Wrapping from PID $OLDPID to $NEWPID. *******"
890 else
891 echo -n "$NEWPID!"
892 fi
893 OLDPID=$NEWPID
894 done
895
896 * Note that you can run the same example on a desktop Linux system,
897 * the wrapping will also happen at 32768, but will go back to 300 instead.
898 */
899#define MUTEX_OWNER_SHIFT 16
900#define MUTEX_OWNER_LEN 16
901
902#define MUTEX_OWNER_FROM_BITS(v) FIELD_FROM_BITS(v,MUTEX_OWNER_SHIFT,MUTEX_OWNER_LEN)
903#define MUTEX_OWNER_TO_BITS(v) FIELD_TO_BITS(v,MUTEX_OWNER_SHIFT,MUTEX_OWNER_LEN)
904
905/* Convenience macros.
906 *
907 * These are used to form or modify the bit pattern of a given mutex value
908 */
909
910
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800911
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700912/* a mutex attribute holds the following fields
913 *
914 * bits: name description
915 * 0-3 type type of mutex
916 * 4 shared process-shared flag
917 */
918#define MUTEXATTR_TYPE_MASK 0x000f
919#define MUTEXATTR_SHARED_MASK 0x0010
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800920
921
922int pthread_mutexattr_init(pthread_mutexattr_t *attr)
923{
924 if (attr) {
925 *attr = PTHREAD_MUTEX_DEFAULT;
926 return 0;
927 } else {
928 return EINVAL;
929 }
930}
931
932int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
933{
934 if (attr) {
935 *attr = -1;
936 return 0;
937 } else {
938 return EINVAL;
939 }
940}
941
942int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
943{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700944 if (attr) {
945 int atype = (*attr & MUTEXATTR_TYPE_MASK);
946
947 if (atype >= PTHREAD_MUTEX_NORMAL &&
948 atype <= PTHREAD_MUTEX_ERRORCHECK) {
949 *type = atype;
950 return 0;
951 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800952 }
953 return EINVAL;
954}
955
956int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
957{
958 if (attr && type >= PTHREAD_MUTEX_NORMAL &&
959 type <= PTHREAD_MUTEX_ERRORCHECK ) {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700960 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800961 return 0;
962 }
963 return EINVAL;
964}
965
966/* process-shared mutexes are not supported at the moment */
967
968int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
969{
970 if (!attr)
971 return EINVAL;
972
Mathias Agopianb7681162009-07-13 22:00:33 -0700973 switch (pshared) {
974 case PTHREAD_PROCESS_PRIVATE:
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700975 *attr &= ~MUTEXATTR_SHARED_MASK;
976 return 0;
977
Mathias Agopianb7681162009-07-13 22:00:33 -0700978 case PTHREAD_PROCESS_SHARED:
979 /* our current implementation of pthread actually supports shared
980 * mutexes but won't cleanup if a process dies with the mutex held.
981 * Nevertheless, it's better than nothing. Shared mutexes are used
982 * by surfaceflinger and audioflinger.
983 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700984 *attr |= MUTEXATTR_SHARED_MASK;
Mathias Agopianb7681162009-07-13 22:00:33 -0700985 return 0;
986 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700987 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800988}
989
990int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
991{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700992 if (!attr || !pshared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800993 return EINVAL;
994
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700995 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED
996 : PTHREAD_PROCESS_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800997 return 0;
998}
999
1000int pthread_mutex_init(pthread_mutex_t *mutex,
1001 const pthread_mutexattr_t *attr)
1002{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001003 int value = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001004
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001005 if (mutex == NULL)
1006 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001007
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001008 if (__likely(attr == NULL)) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001009 mutex->value = MUTEX_TYPE_BITS_NORMAL;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001010 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001011 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001012
1013 if ((*attr & MUTEXATTR_SHARED_MASK) != 0)
1014 value |= MUTEX_SHARED_MASK;
1015
1016 switch (*attr & MUTEXATTR_TYPE_MASK) {
1017 case PTHREAD_MUTEX_NORMAL:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001018 value |= MUTEX_TYPE_BITS_NORMAL;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001019 break;
1020 case PTHREAD_MUTEX_RECURSIVE:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001021 value |= MUTEX_TYPE_BITS_RECURSIVE;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001022 break;
1023 case PTHREAD_MUTEX_ERRORCHECK:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001024 value |= MUTEX_TYPE_BITS_ERRORCHECK;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001025 break;
1026 default:
1027 return EINVAL;
1028 }
1029
1030 mutex->value = value;
1031 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001032}
1033
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001034
1035/*
1036 * Lock a non-recursive mutex.
1037 *
1038 * As noted above, there are three states:
1039 * 0 (unlocked, no contention)
1040 * 1 (locked, no contention)
1041 * 2 (locked, contention)
1042 *
1043 * Non-recursive mutexes don't use the thread-id or counter fields, and the
1044 * "type" value is zero, so the only bits that will be set are the ones in
1045 * the lock state field.
1046 */
1047static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001048_normal_lock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001049{
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001050 /* convenience shortcuts */
1051 const int unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
1052 const int locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001053 /*
1054 * The common case is an unlocked mutex, so we begin by trying to
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001055 * change the lock's state from 0 (UNLOCKED) to 1 (LOCKED).
1056 * __bionic_cmpxchg() returns 0 if it made the swap successfully.
1057 * If the result is nonzero, this lock is already held by another thread.
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001058 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001059 if (__bionic_cmpxchg(unlocked, locked_uncontended, &mutex->value) != 0) {
1060 const int locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001061 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001062 * We want to go to sleep until the mutex is available, which
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001063 * requires promoting it to state 2 (CONTENDED). We need to
1064 * swap in the new state value and then wait until somebody wakes us up.
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001065 *
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001066 * __bionic_swap() returns the previous value. We swap 2 in and
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001067 * see if we got zero back; if so, we have acquired the lock. If
1068 * not, another thread still holds the lock and we wait again.
1069 *
1070 * The second argument to the __futex_wait() call is compared
1071 * against the current value. If it doesn't match, __futex_wait()
1072 * returns immediately (otherwise, it sleeps for a time specified
1073 * by the third argument; 0 means sleep forever). This ensures
1074 * that the mutex is in state 2 when we go to sleep on it, which
1075 * guarantees a wake-up call.
1076 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001077 while (__bionic_swap(locked_contended, &mutex->value) != unlocked)
1078 __futex_wait_ex(&mutex->value, shared, locked_contended, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001079 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001080 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001081}
1082
1083/*
1084 * Release a non-recursive mutex. The caller is responsible for determining
1085 * that we are in fact the owner of this lock.
1086 */
1087static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001088_normal_unlock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001089{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001090 ANDROID_MEMBAR_FULL();
1091
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001092 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001093 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001094 * to release the lock. __bionic_atomic_dec() returns the previous value;
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001095 * if it wasn't 1 we have to do some additional work.
1096 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001097 if (__bionic_atomic_dec(&mutex->value) != (shared|MUTEX_STATE_BITS_LOCKED_UNCONTENDED)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001098 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001099 * Start by releasing the lock. The decrement changed it from
1100 * "contended lock" to "uncontended lock", which means we still
1101 * hold it, and anybody who tries to sneak in will push it back
1102 * to state 2.
1103 *
1104 * Once we set it to zero the lock is up for grabs. We follow
1105 * this with a __futex_wake() to ensure that one of the waiting
1106 * threads has a chance to grab it.
1107 *
1108 * This doesn't cause a race with the swap/wait pair in
1109 * _normal_lock(), because the __futex_wait() call there will
1110 * return immediately if the mutex value isn't 2.
1111 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001112 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001113
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001114 /*
1115 * Wake up one waiting thread. We don't know which thread will be
1116 * woken or when it'll start executing -- futexes make no guarantees
1117 * here. There may not even be a thread waiting.
1118 *
1119 * The newly-woken thread will replace the 0 we just set above
1120 * with 2, which means that when it eventually releases the mutex
1121 * it will also call FUTEX_WAKE. This results in one extra wake
1122 * call whenever a lock is contended, but lets us avoid forgetting
1123 * anyone without requiring us to track the number of sleepers.
1124 *
1125 * It's possible for another thread to sneak in and grab the lock
1126 * between the zero assignment above and the wake call below. If
1127 * the new thread is "slow" and holds the lock for a while, we'll
1128 * wake up a sleeper, which will swap in a 2 and then go back to
1129 * sleep since the lock is still held. If the new thread is "fast",
1130 * running to completion before we call wake, the thread we
1131 * eventually wake will find an unlocked mutex and will execute.
1132 * Either way we have correct behavior and nobody is orphaned on
1133 * the wait queue.
1134 */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001135 __futex_wake_ex(&mutex->value, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001136 }
1137}
1138
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001139/* This common inlined function is used to increment the counter of an
1140 * errorcheck or recursive mutex.
1141 *
1142 * For errorcheck mutexes, it will return EDEADLK
1143 * If the counter overflows, it will return EAGAIN
1144 * Otherwise, it atomically increments the counter and returns 0
1145 * after providing an acquire barrier.
1146 *
1147 * mtype is the current mutex type
1148 * mvalue is the current mutex value (already loaded)
1149 * mutex pointers to the mutex.
1150 */
1151static __inline__ __attribute__((always_inline)) int
1152_recursive_increment(pthread_mutex_t* mutex, int mvalue, int mtype)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001153{
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001154 if (mtype == MUTEX_TYPE_BITS_ERRORCHECK) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001155 /* trying to re-lock a mutex we already acquired */
1156 return EDEADLK;
1157 }
1158
1159 /* Detect recursive lock overflow and return EAGAIN.
1160 * This is safe because only the owner thread can modify the
David 'Digit' Turnerb57db752012-01-24 13:20:38 +01001161 * counter bits in the mutex value.
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001162 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001163 if (MUTEX_COUNTER_BITS_WILL_OVERFLOW(mvalue)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001164 return EAGAIN;
1165 }
1166
1167 /* We own the mutex, but other threads are able to change
David 'Digit' Turnerb57db752012-01-24 13:20:38 +01001168 * the lower bits (e.g. promoting it to "contended"), so we
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001169 * need to use an atomic cmpxchg loop to update the counter.
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001170 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001171 for (;;) {
1172 /* increment counter, overflow was already checked */
1173 int newval = mvalue + MUTEX_COUNTER_BITS_ONE;
1174 if (__likely(__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0)) {
1175 /* mutex is still locked, not need for a memory barrier */
1176 return 0;
1177 }
1178 /* the value was changed, this happens when another thread changes
1179 * the lower state bits from 1 to 2 to indicate contention. This
1180 * cannot change the counter, so simply reload and try again.
1181 */
1182 mvalue = mutex->value;
1183 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001184}
1185
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001186__LIBC_HIDDEN__
1187int pthread_mutex_lock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001188{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001189 int mvalue, mtype, tid, new_lock_type, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001190
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001191 if (__unlikely(mutex == NULL))
1192 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001193
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001194 mvalue = mutex->value;
1195 mtype = (mvalue & MUTEX_TYPE_MASK);
1196 shared = (mvalue & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001197
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001198 /* Handle normal case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001199 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) ) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001200 _normal_lock(mutex, shared);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001201 return 0;
1202 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001203
1204 /* Do we already own this recursive or error-check mutex ? */
1205 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001206 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001207 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001208
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001209 /* Add in shared state to avoid extra 'or' operations below */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001210 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001211
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001212 /* First, if the mutex is unlocked, try to quickly acquire it.
1213 * In the optimistic case where this works, set the state to 1 to
1214 * indicate locked with no contention */
1215 if (mvalue == mtype) {
1216 int newval = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1217 if (__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0) {
1218 ANDROID_MEMBAR_FULL();
1219 return 0;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001220 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001221 /* argh, the value changed, reload before entering the loop */
1222 mvalue = mutex->value;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001223 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001224
1225 for (;;) {
1226 int newval;
1227
1228 /* if the mutex is unlocked, its value should be 'mtype' and
1229 * we try to acquire it by setting its owner and state atomically.
1230 * NOTE: We put the state to 2 since we _know_ there is contention
1231 * when we are in this loop. This ensures all waiters will be
1232 * unlocked.
1233 */
1234 if (mvalue == mtype) {
1235 newval = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1236 /* TODO: Change this to __bionic_cmpxchg_acquire when we
1237 * implement it to get rid of the explicit memory
1238 * barrier below.
1239 */
1240 if (__unlikely(__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0)) {
1241 mvalue = mutex->value;
1242 continue;
1243 }
1244 ANDROID_MEMBAR_FULL();
1245 return 0;
1246 }
1247
1248 /* the mutex is already locked by another thread, if its state is 1
1249 * we will change it to 2 to indicate contention. */
1250 if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(mvalue)) {
1251 newval = MUTEX_STATE_BITS_FLIP_CONTENTION(mvalue); /* locked state 1 => state 2 */
1252 if (__unlikely(__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0)) {
1253 mvalue = mutex->value;
1254 continue;
1255 }
1256 mvalue = newval;
1257 }
1258
1259 /* wait until the mutex is unlocked */
1260 __futex_wait_ex(&mutex->value, shared, mvalue, NULL);
1261
1262 mvalue = mutex->value;
1263 }
1264 /* NOTREACHED */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001265}
1266
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001267int pthread_mutex_lock(pthread_mutex_t *mutex)
1268{
1269 int err = pthread_mutex_lock_impl(mutex);
1270#ifdef PTHREAD_DEBUG
1271 if (PTHREAD_DEBUG_ENABLED) {
1272 if (!err) {
1273 pthread_debug_mutex_lock_check(mutex);
1274 }
1275 }
1276#endif
1277 return err;
1278}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001279
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001280__LIBC_HIDDEN__
1281int pthread_mutex_unlock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001282{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001283 int mvalue, mtype, tid, oldv, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001284
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001285 if (__unlikely(mutex == NULL))
1286 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001287
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001288 mvalue = mutex->value;
1289 mtype = (mvalue & MUTEX_TYPE_MASK);
1290 shared = (mvalue & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001291
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001292 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001293 if (__likely(mtype == MUTEX_TYPE_BITS_NORMAL)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001294 _normal_unlock(mutex, shared);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001295 return 0;
1296 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001297
1298 /* Do we already own this recursive or error-check mutex ? */
1299 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001300 if ( tid != MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001301 return EPERM;
1302
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001303 /* If the counter is > 0, we can simply decrement it atomically.
1304 * Since other threads can mutate the lower state bits (and only the
1305 * lower state bits), use a cmpxchg to do it.
1306 */
1307 if (!MUTEX_COUNTER_BITS_IS_ZERO(mvalue)) {
1308 for (;;) {
1309 int newval = mvalue - MUTEX_COUNTER_BITS_ONE;
1310 if (__likely(__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0)) {
1311 /* success: we still own the mutex, so no memory barrier */
1312 return 0;
1313 }
1314 /* the value changed, so reload and loop */
1315 mvalue = mutex->value;
1316 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001317 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001318
1319 /* the counter is 0, so we're going to unlock the mutex by resetting
1320 * its value to 'unlocked'. We need to perform a swap in order
1321 * to read the current state, which will be 2 if there are waiters
1322 * to awake.
1323 *
1324 * TODO: Change this to __bionic_swap_release when we implement it
1325 * to get rid of the explicit memory barrier below.
1326 */
1327 ANDROID_MEMBAR_FULL(); /* RELEASE BARRIER */
1328 mvalue = __bionic_swap(mtype | shared | MUTEX_STATE_BITS_UNLOCKED, &mutex->value);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001329
1330 /* Wake one waiting thread, if any */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001331 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(mvalue)) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001332 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001333 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001334 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001335}
1336
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001337int pthread_mutex_unlock(pthread_mutex_t *mutex)
1338{
1339#ifdef PTHREAD_DEBUG
1340 if (PTHREAD_DEBUG_ENABLED) {
1341 pthread_debug_mutex_unlock_check(mutex);
1342 }
1343#endif
1344 return pthread_mutex_unlock_impl(mutex);
1345}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001346
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001347__LIBC_HIDDEN__
1348int pthread_mutex_trylock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001349{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001350 int mvalue, mtype, tid, oldv, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001351
1352 if (__unlikely(mutex == NULL))
1353 return EINVAL;
1354
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001355 mvalue = mutex->value;
1356 mtype = (mvalue & MUTEX_TYPE_MASK);
1357 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001358
1359 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001360 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001361 {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001362 if (__bionic_cmpxchg(shared|MUTEX_STATE_BITS_UNLOCKED,
1363 shared|MUTEX_STATE_BITS_LOCKED_UNCONTENDED,
1364 &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001365 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001366 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001367 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001368
1369 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001370 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001371
1372 /* Do we already own this recursive or error-check mutex ? */
1373 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001374 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001375 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001376
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001377 /* Same as pthread_mutex_lock, except that we don't want to wait, and
1378 * the only operation that can succeed is a single cmpxchg to acquire the
1379 * lock if it is released / not owned by anyone. No need for a complex loop.
1380 */
1381 mtype |= shared | MUTEX_STATE_BITS_UNLOCKED;
1382 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001383
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001384 if (__likely(__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0)) {
1385 ANDROID_MEMBAR_FULL();
1386 return 0;
1387 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001388
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001389 return EBUSY;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001390}
1391
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001392int pthread_mutex_trylock(pthread_mutex_t *mutex)
1393{
1394 int err = pthread_mutex_trylock_impl(mutex);
1395#ifdef PTHREAD_DEBUG
1396 if (PTHREAD_DEBUG_ENABLED) {
1397 if (!err) {
1398 pthread_debug_mutex_lock_check(mutex);
1399 }
1400 }
1401#endif
1402 return err;
1403}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001404
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001405/* initialize 'ts' with the difference between 'abstime' and the current time
1406 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
1407 */
1408static int
1409__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
1410{
1411 clock_gettime(clock, ts);
1412 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
1413 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
1414 if (ts->tv_nsec < 0) {
1415 ts->tv_sec--;
1416 ts->tv_nsec += 1000000000;
1417 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001418 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001419 return -1;
1420
1421 return 0;
1422}
1423
1424/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1425 * milliseconds.
1426 */
1427static void
1428__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1429{
1430 clock_gettime(clock, abstime);
1431 abstime->tv_sec += msecs/1000;
1432 abstime->tv_nsec += (msecs%1000)*1000000;
1433 if (abstime->tv_nsec >= 1000000000) {
1434 abstime->tv_sec++;
1435 abstime->tv_nsec -= 1000000000;
1436 }
1437}
1438
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001439__LIBC_HIDDEN__
1440int pthread_mutex_lock_timeout_np_impl(pthread_mutex_t *mutex, unsigned msecs)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001441{
1442 clockid_t clock = CLOCK_MONOTONIC;
1443 struct timespec abstime;
1444 struct timespec ts;
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001445 int mvalue, mtype, tid, oldv, new_lock_type, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001446
1447 /* compute absolute expiration time */
1448 __timespec_to_relative_msec(&abstime, msecs, clock);
1449
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001450 if (__unlikely(mutex == NULL))
1451 return EINVAL;
1452
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001453 mvalue = mutex->value;
1454 mtype = (mvalue & MUTEX_TYPE_MASK);
1455 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001456
1457 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001458 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001459 {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001460 const int unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
1461 const int locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1462 const int locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1463
1464 /* fast path for uncontended lock. Note: MUTEX_TYPE_BITS_NORMAL is 0 */
1465 if (__bionic_cmpxchg(unlocked, locked_uncontended, &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001466 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001467 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001468 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001469
1470 /* loop while needed */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001471 while (__bionic_swap(locked_contended, &mutex->value) != unlocked) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001472 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1473 return EBUSY;
1474
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001475 __futex_wait_ex(&mutex->value, shared, locked_contended, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001476 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001477 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001478 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001479 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001480
1481 /* Do we already own this recursive or error-check mutex ? */
1482 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001483 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001484 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001485
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001486 /* the following implements the same loop than pthread_mutex_lock_impl
1487 * but adds checks to ensure that the operation never exceeds the
1488 * absolute expiration time.
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001489 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001490 mtype |= shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001491
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001492 /* first try a quick lock */
1493 if (mvalue == mtype) {
1494 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1495 if (__likely(__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0)) {
1496 ANDROID_MEMBAR_FULL();
1497 return 0;
1498 }
1499 mvalue = mutex->value;
1500 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001501
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001502 for (;;) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001503 struct timespec ts;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001504
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001505 /* if the value is 'unlocked', try to acquire it directly */
1506 /* NOTE: put state to 2 since we know there is contention */
1507 if (mvalue == mtype) /* unlocked */ {
1508 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1509 if (__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0) {
1510 ANDROID_MEMBAR_FULL();
1511 return 0;
1512 }
1513 /* the value changed before we could lock it. We need to check
1514 * the time to avoid livelocks, reload the value, then loop again. */
1515 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1516 return EBUSY;
1517
1518 mvalue = mutex->value;
1519 continue;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001520 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001521
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001522 /* The value is locked. If 'uncontended', try to switch its state
1523 * to 'contented' to ensure we get woken up later. */
1524 if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(mvalue)) {
1525 int newval = MUTEX_STATE_BITS_FLIP_CONTENTION(mvalue);
1526 if (__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0) {
1527 /* this failed because the value changed, reload it */
1528 mvalue = mutex->value;
1529 } else {
1530 /* this succeeded, update mvalue */
1531 mvalue = newval;
1532 }
1533 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001534
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001535 /* check time and update 'ts' */
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001536 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1537 return EBUSY;
1538
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001539 /* Only wait to be woken up if the state is '2', otherwise we'll
1540 * simply loop right now. This can happen when the second cmpxchg
1541 * in our loop failed because the mutex was unlocked by another
1542 * thread.
1543 */
1544 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(mvalue)) {
1545 if (__futex_wait_ex(&mutex->value, shared, mvalue, &ts) == ETIMEDOUT) {
1546 return EBUSY;
1547 }
1548 mvalue = mutex->value;
1549 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001550 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001551 /* NOTREACHED */
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001552}
1553
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001554int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1555{
1556 int err = pthread_mutex_lock_timeout_np_impl(mutex, msecs);
1557#ifdef PTHREAD_DEBUG
1558 if (PTHREAD_DEBUG_ENABLED) {
1559 if (!err) {
1560 pthread_debug_mutex_lock_check(mutex);
1561 }
1562 }
1563#endif
1564 return err;
1565}
1566
1567int pthread_mutex_destroy(pthread_mutex_t *mutex)
1568{
1569 int ret;
1570
1571 /* use trylock to ensure that the mutex value is
1572 * valid and is not already locked. */
1573 ret = pthread_mutex_trylock_impl(mutex);
1574 if (ret != 0)
1575 return ret;
1576
1577 mutex->value = 0xdead10cc;
1578 return 0;
1579}
1580
1581
1582
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001583int pthread_condattr_init(pthread_condattr_t *attr)
1584{
1585 if (attr == NULL)
1586 return EINVAL;
1587
1588 *attr = PTHREAD_PROCESS_PRIVATE;
1589 return 0;
1590}
1591
1592int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1593{
1594 if (attr == NULL || pshared == NULL)
1595 return EINVAL;
1596
1597 *pshared = *attr;
1598 return 0;
1599}
1600
1601int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1602{
1603 if (attr == NULL)
1604 return EINVAL;
1605
1606 if (pshared != PTHREAD_PROCESS_SHARED &&
1607 pshared != PTHREAD_PROCESS_PRIVATE)
1608 return EINVAL;
1609
1610 *attr = pshared;
1611 return 0;
1612}
1613
1614int pthread_condattr_destroy(pthread_condattr_t *attr)
1615{
1616 if (attr == NULL)
1617 return EINVAL;
1618
1619 *attr = 0xdeada11d;
1620 return 0;
1621}
1622
1623/* We use one bit in condition variable values as the 'shared' flag
1624 * The rest is a counter.
1625 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001626#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001627#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001628#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1629
1630#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001631
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001632/* XXX *technically* there is a race condition that could allow
1633 * XXX a signal to be missed. If thread A is preempted in _wait()
1634 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001635 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001636 * XXX before thread A is scheduled again and calls futex_wait(),
1637 * XXX then the signal will be lost.
1638 */
1639
1640int pthread_cond_init(pthread_cond_t *cond,
1641 const pthread_condattr_t *attr)
1642{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001643 if (cond == NULL)
1644 return EINVAL;
1645
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001646 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001647
1648 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001649 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001650
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001651 return 0;
1652}
1653
1654int pthread_cond_destroy(pthread_cond_t *cond)
1655{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001656 if (cond == NULL)
1657 return EINVAL;
1658
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001659 cond->value = 0xdeadc04d;
1660 return 0;
1661}
1662
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001663/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001664 * pthread_cond_signal to atomically decrement the counter
1665 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001666 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001667static int
1668__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001669{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001670 long flags;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001671
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001672 if (__unlikely(cond == NULL))
1673 return EINVAL;
1674
1675 flags = (cond->value & ~COND_COUNTER_MASK);
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001676 for (;;) {
1677 long oldval = cond->value;
1678 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1679 | flags;
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001680 if (__bionic_cmpxchg(oldval, newval, &cond->value) == 0)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001681 break;
1682 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001683
Andy McFaddene2ac8982010-09-02 13:34:53 -07001684 /*
1685 * Ensure that all memory accesses previously made by this thread are
1686 * visible to the woken thread(s). On the other side, the "wait"
1687 * code will issue any necessary barriers when locking the mutex.
1688 *
1689 * This may not strictly be necessary -- if the caller follows
1690 * recommended practice and holds the mutex before signaling the cond
1691 * var, the mutex ops will provide correct semantics. If they don't
1692 * hold the mutex, they're subject to race conditions anyway.
1693 */
1694 ANDROID_MEMBAR_FULL();
1695
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001696 __futex_wake_ex(&cond->value, COND_IS_SHARED(cond), counter);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001697 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001698}
1699
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001700int pthread_cond_broadcast(pthread_cond_t *cond)
1701{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001702 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001703}
1704
1705int pthread_cond_signal(pthread_cond_t *cond)
1706{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001707 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001708}
1709
1710int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1711{
1712 return pthread_cond_timedwait(cond, mutex, NULL);
1713}
1714
1715int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1716 pthread_mutex_t * mutex,
1717 const struct timespec *reltime)
1718{
1719 int status;
1720 int oldvalue = cond->value;
1721
1722 pthread_mutex_unlock(mutex);
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001723 status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond), oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001724 pthread_mutex_lock(mutex);
1725
1726 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1727 return 0;
1728}
1729
1730int __pthread_cond_timedwait(pthread_cond_t *cond,
1731 pthread_mutex_t * mutex,
1732 const struct timespec *abstime,
1733 clockid_t clock)
1734{
1735 struct timespec ts;
1736 struct timespec * tsp;
1737
1738 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001739 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001740 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001741 tsp = &ts;
1742 } else {
1743 tsp = NULL;
1744 }
1745
1746 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1747}
1748
1749int pthread_cond_timedwait(pthread_cond_t *cond,
1750 pthread_mutex_t * mutex,
1751 const struct timespec *abstime)
1752{
1753 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1754}
1755
1756
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001757/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001758int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1759 pthread_mutex_t * mutex,
1760 const struct timespec *abstime)
1761{
1762 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1763}
1764
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001765int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1766 pthread_mutex_t * mutex,
1767 const struct timespec *abstime)
1768{
1769 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1770}
1771
1772int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1773 pthread_mutex_t * mutex,
1774 const struct timespec *reltime)
1775{
1776 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1777}
1778
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001779int pthread_cond_timeout_np(pthread_cond_t *cond,
1780 pthread_mutex_t * mutex,
1781 unsigned msecs)
1782{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001783 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001784
1785 ts.tv_sec = msecs / 1000;
1786 ts.tv_nsec = (msecs % 1000) * 1000000;
1787
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001788 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001789}
1790
1791
1792
1793/* A technical note regarding our thread-local-storage (TLS) implementation:
1794 *
1795 * There can be up to TLSMAP_SIZE independent TLS keys in a given process,
1796 * though the first TLSMAP_START keys are reserved for Bionic to hold
1797 * special thread-specific variables like errno or a pointer to
1798 * the current thread's descriptor.
1799 *
1800 * while stored in the TLS area, these entries cannot be accessed through
1801 * pthread_getspecific() / pthread_setspecific() and pthread_key_delete()
1802 *
1803 * also, some entries in the key table are pre-allocated (see tlsmap_lock)
1804 * to greatly simplify and speedup some OpenGL-related operations. though the
1805 * initialy value will be NULL on all threads.
1806 *
1807 * you can use pthread_getspecific()/setspecific() on these, and in theory
1808 * you could also call pthread_key_delete() as well, though this would
1809 * probably break some apps.
1810 *
1811 * The 'tlsmap_t' type defined below implements a shared global map of
1812 * currently created/allocated TLS keys and the destructors associated
1813 * with them. You should use tlsmap_lock/unlock to access it to avoid
1814 * any race condition.
1815 *
1816 * the global TLS map simply contains a bitmap of allocated keys, and
1817 * an array of destructors.
1818 *
1819 * each thread has a TLS area that is a simple array of TLSMAP_SIZE void*
1820 * pointers. the TLS area of the main thread is stack-allocated in
1821 * __libc_init_common, while the TLS area of other threads is placed at
1822 * the top of their stack in pthread_create.
1823 *
1824 * when pthread_key_create() is called, it finds the first free key in the
1825 * bitmap, then set it to 1, saving the destructor altogether
1826 *
1827 * when pthread_key_delete() is called. it will erase the key's bitmap bit
1828 * and its destructor, and will also clear the key data in the TLS area of
1829 * all created threads. As mandated by Posix, it is the responsability of
1830 * the caller of pthread_key_delete() to properly reclaim the objects that
1831 * were pointed to by these data fields (either before or after the call).
1832 *
1833 */
1834
1835/* TLS Map implementation
1836 */
1837
1838#define TLSMAP_START (TLS_SLOT_MAX_WELL_KNOWN+1)
1839#define TLSMAP_SIZE BIONIC_TLS_SLOTS
1840#define TLSMAP_BITS 32
1841#define TLSMAP_WORDS ((TLSMAP_SIZE+TLSMAP_BITS-1)/TLSMAP_BITS)
1842#define TLSMAP_WORD(m,k) (m)->map[(k)/TLSMAP_BITS]
1843#define TLSMAP_MASK(k) (1U << ((k)&(TLSMAP_BITS-1)))
1844
1845/* this macro is used to quickly check that a key belongs to a reasonable range */
1846#define TLSMAP_VALIDATE_KEY(key) \
1847 ((key) >= TLSMAP_START && (key) < TLSMAP_SIZE)
1848
1849/* the type of tls key destructor functions */
1850typedef void (*tls_dtor_t)(void*);
1851
1852typedef struct {
1853 int init; /* see comment in tlsmap_lock() */
1854 uint32_t map[TLSMAP_WORDS]; /* bitmap of allocated keys */
1855 tls_dtor_t dtors[TLSMAP_SIZE]; /* key destructors */
1856} tlsmap_t;
1857
1858static pthread_mutex_t _tlsmap_lock = PTHREAD_MUTEX_INITIALIZER;
1859static tlsmap_t _tlsmap;
1860
1861/* lock the global TLS map lock and return a handle to it */
1862static __inline__ tlsmap_t* tlsmap_lock(void)
1863{
1864 tlsmap_t* m = &_tlsmap;
1865
1866 pthread_mutex_lock(&_tlsmap_lock);
1867 /* we need to initialize the first entry of the 'map' array
1868 * with the value TLS_DEFAULT_ALLOC_MAP. doing it statically
1869 * when declaring _tlsmap is a bit awkward and is going to
1870 * produce warnings, so do it the first time we use the map
1871 * instead
1872 */
1873 if (__unlikely(!m->init)) {
1874 TLSMAP_WORD(m,0) = TLS_DEFAULT_ALLOC_MAP;
1875 m->init = 1;
1876 }
1877 return m;
1878}
1879
1880/* unlock the global TLS map */
1881static __inline__ void tlsmap_unlock(tlsmap_t* m)
1882{
1883 pthread_mutex_unlock(&_tlsmap_lock);
1884 (void)m; /* a good compiler is a happy compiler */
1885}
1886
1887/* test to see wether a key is allocated */
1888static __inline__ int tlsmap_test(tlsmap_t* m, int key)
1889{
1890 return (TLSMAP_WORD(m,key) & TLSMAP_MASK(key)) != 0;
1891}
1892
1893/* set the destructor and bit flag on a newly allocated key */
1894static __inline__ void tlsmap_set(tlsmap_t* m, int key, tls_dtor_t dtor)
1895{
1896 TLSMAP_WORD(m,key) |= TLSMAP_MASK(key);
1897 m->dtors[key] = dtor;
1898}
1899
1900/* clear the destructor and bit flag on an existing key */
1901static __inline__ void tlsmap_clear(tlsmap_t* m, int key)
1902{
1903 TLSMAP_WORD(m,key) &= ~TLSMAP_MASK(key);
1904 m->dtors[key] = NULL;
1905}
1906
1907/* allocate a new TLS key, return -1 if no room left */
1908static int tlsmap_alloc(tlsmap_t* m, tls_dtor_t dtor)
1909{
1910 int key;
1911
1912 for ( key = TLSMAP_START; key < TLSMAP_SIZE; key++ ) {
1913 if ( !tlsmap_test(m, key) ) {
1914 tlsmap_set(m, key, dtor);
1915 return key;
1916 }
1917 }
1918 return -1;
1919}
1920
1921
1922int pthread_key_create(pthread_key_t *key, void (*destructor_function)(void *))
1923{
1924 uint32_t err = ENOMEM;
1925 tlsmap_t* map = tlsmap_lock();
1926 int k = tlsmap_alloc(map, destructor_function);
1927
1928 if (k >= 0) {
1929 *key = k;
1930 err = 0;
1931 }
1932 tlsmap_unlock(map);
1933 return err;
1934}
1935
1936
1937/* This deletes a pthread_key_t. note that the standard mandates that this does
1938 * not call the destructor of non-NULL key values. Instead, it is the
Elliott Hughesbfeab1b2012-09-05 17:47:37 -07001939 * responsibility of the caller to properly dispose of the corresponding data
1940 * and resources, using any means it finds suitable.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001941 *
1942 * On the other hand, this function will clear the corresponding key data
1943 * values in all known threads. this prevents later (invalid) calls to
1944 * pthread_getspecific() to receive invalid/stale values.
1945 */
1946int pthread_key_delete(pthread_key_t key)
1947{
1948 uint32_t err;
1949 pthread_internal_t* thr;
1950 tlsmap_t* map;
1951
1952 if (!TLSMAP_VALIDATE_KEY(key)) {
1953 return EINVAL;
1954 }
1955
1956 map = tlsmap_lock();
1957
1958 if (!tlsmap_test(map, key)) {
1959 err = EINVAL;
1960 goto err1;
1961 }
1962
1963 /* clear value in all threads */
1964 pthread_mutex_lock(&gThreadListLock);
1965 for ( thr = gThreadList; thr != NULL; thr = thr->next ) {
1966 /* avoid zombie threads with a negative 'join_count'. these are really
1967 * already dead and don't have a TLS area anymore.
1968 *
1969 * similarly, it is possible to have thr->tls == NULL for threads that
1970 * were just recently created through pthread_create() but whose
1971 * startup trampoline (__thread_entry) hasn't been run yet by the
Bjorn Andersson0753dc62012-05-03 17:12:39 -07001972 * scheduler. thr->tls will also be NULL after it's stack has been
1973 * unmapped but before the ongoing pthread_join() is finished.
1974 * so check for this too.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001975 */
1976 if (thr->join_count < 0 || !thr->tls)
1977 continue;
1978
1979 thr->tls[key] = NULL;
1980 }
1981 tlsmap_clear(map, key);
1982
1983 pthread_mutex_unlock(&gThreadListLock);
1984 err = 0;
1985
1986err1:
1987 tlsmap_unlock(map);
1988 return err;
1989}
1990
1991
1992int pthread_setspecific(pthread_key_t key, const void *ptr)
1993{
1994 int err = EINVAL;
1995 tlsmap_t* map;
1996
1997 if (TLSMAP_VALIDATE_KEY(key)) {
1998 /* check that we're trying to set data for an allocated key */
1999 map = tlsmap_lock();
2000 if (tlsmap_test(map, key)) {
2001 ((uint32_t *)__get_tls())[key] = (uint32_t)ptr;
2002 err = 0;
2003 }
2004 tlsmap_unlock(map);
2005 }
2006 return err;
2007}
2008
2009void * pthread_getspecific(pthread_key_t key)
2010{
2011 if (!TLSMAP_VALIDATE_KEY(key)) {
2012 return NULL;
2013 }
2014
2015 /* for performance reason, we do not lock/unlock the global TLS map
2016 * to check that the key is properly allocated. if the key was not
2017 * allocated, the value read from the TLS should always be NULL
2018 * due to pthread_key_delete() clearing the values for all threads.
2019 */
2020 return (void *)(((unsigned *)__get_tls())[key]);
2021}
2022
2023/* Posix mandates that this be defined in <limits.h> but we don't have
2024 * it just yet.
2025 */
2026#ifndef PTHREAD_DESTRUCTOR_ITERATIONS
2027# define PTHREAD_DESTRUCTOR_ITERATIONS 4
2028#endif
2029
2030/* this function is called from pthread_exit() to remove all TLS key data
2031 * from this thread's TLS area. this must call the destructor of all keys
2032 * that have a non-NULL data value (and a non-NULL destructor).
2033 *
2034 * because destructors can do funky things like deleting/creating other
2035 * keys, we need to implement this in a loop
2036 */
2037static void pthread_key_clean_all(void)
2038{
2039 tlsmap_t* map;
2040 void** tls = (void**)__get_tls();
2041 int rounds = PTHREAD_DESTRUCTOR_ITERATIONS;
2042
2043 map = tlsmap_lock();
2044
2045 for (rounds = PTHREAD_DESTRUCTOR_ITERATIONS; rounds > 0; rounds--)
2046 {
2047 int kk, count = 0;
2048
2049 for (kk = TLSMAP_START; kk < TLSMAP_SIZE; kk++) {
2050 if ( tlsmap_test(map, kk) )
2051 {
2052 void* data = tls[kk];
2053 tls_dtor_t dtor = map->dtors[kk];
2054
2055 if (data != NULL && dtor != NULL)
2056 {
2057 /* we need to clear the key data now, this will prevent the
2058 * destructor (or a later one) from seeing the old value if
2059 * it calls pthread_getspecific() for some odd reason
2060 *
2061 * we do not do this if 'dtor == NULL' just in case another
2062 * destructor function might be responsible for manually
2063 * releasing the corresponding data.
2064 */
2065 tls[kk] = NULL;
2066
2067 /* because the destructor is free to call pthread_key_create
2068 * and/or pthread_key_delete, we need to temporarily unlock
2069 * the TLS map
2070 */
2071 tlsmap_unlock(map);
2072 (*dtor)(data);
2073 map = tlsmap_lock();
2074
2075 count += 1;
2076 }
2077 }
2078 }
2079
2080 /* if we didn't call any destructor, there is no need to check the
2081 * TLS data again
2082 */
2083 if (count == 0)
2084 break;
2085 }
2086 tlsmap_unlock(map);
2087}
2088
2089// man says this should be in <linux/unistd.h>, but it isn't
Jeff Brown10c8ce52011-11-18 15:17:07 -08002090extern int tgkill(int tgid, int tid, int sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002091
2092int pthread_kill(pthread_t tid, int sig)
2093{
2094 int ret;
2095 int old_errno = errno;
2096 pthread_internal_t * thread = (pthread_internal_t *)tid;
2097
Jeff Brown10c8ce52011-11-18 15:17:07 -08002098 ret = tgkill(getpid(), thread->kernel_id, sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002099 if (ret < 0) {
2100 ret = errno;
2101 errno = old_errno;
2102 }
2103
2104 return ret;
2105}
2106
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01002107/* Despite the fact that our kernel headers define sigset_t explicitly
2108 * as a 32-bit integer, the kernel system call really expects a 64-bit
2109 * bitmap for the signal set, or more exactly an array of two-32-bit
2110 * values (see $KERNEL/arch/$ARCH/include/asm/signal.h for details).
2111 *
2112 * Unfortunately, we cannot fix the sigset_t definition without breaking
2113 * the C library ABI, so perform a little runtime translation here.
2114 */
2115typedef union {
2116 sigset_t bionic;
2117 uint32_t kernel[2];
2118} kernel_sigset_t;
2119
2120/* this is a private syscall stub */
2121extern int __rt_sigprocmask(int, const kernel_sigset_t *, kernel_sigset_t *, size_t);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002122
2123int pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
2124{
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08002125 /* pthread_sigmask must return the error code, but the syscall
2126 * will set errno instead and return 0/-1
2127 */
2128 int ret, old_errno = errno;
2129
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01002130 /* We must convert *set into a kernel_sigset_t */
2131 kernel_sigset_t in_set, *in_set_ptr;
2132 kernel_sigset_t out_set;
2133
Bruce Bearee4a21c82011-12-05 11:25:37 -08002134 in_set.kernel[0] = in_set.kernel[1] = 0;
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01002135 out_set.kernel[0] = out_set.kernel[1] = 0;
2136
2137 /* 'in_set_ptr' is the second parameter to __rt_sigprocmask. It must be NULL
2138 * if 'set' is NULL to ensure correct semantics (which in this case would
2139 * be to ignore 'how' and return the current signal set into 'oset'.
David 'Digit' Turner5c8c00a2010-12-20 15:58:06 +01002140 */
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01002141 if (set == NULL) {
2142 in_set_ptr = NULL;
2143 } else {
2144 in_set.bionic = *set;
2145 in_set_ptr = &in_set;
2146 }
2147
2148 ret = __rt_sigprocmask(how, in_set_ptr, &out_set, sizeof(kernel_sigset_t));
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08002149 if (ret < 0)
2150 ret = errno;
2151
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01002152 if (oset)
2153 *oset = out_set.bionic;
2154
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08002155 errno = old_errno;
2156 return ret;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002157}
2158
2159
2160int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
2161{
2162 const int CLOCK_IDTYPE_BITS = 3;
2163 pthread_internal_t* thread = (pthread_internal_t*)tid;
2164
2165 if (!thread)
2166 return ESRCH;
2167
2168 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
2169 return 0;
2170}
2171
2172
2173/* NOTE: this implementation doesn't support a init function that throws a C++ exception
2174 * or calls fork()
2175 */
2176int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
2177{
Wink Savilleccc3d1e2010-06-28 11:41:16 -07002178 static pthread_mutex_t once_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07002179 volatile pthread_once_t* ocptr = once_control;
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002180 pthread_once_t value;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002181
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002182 /* PTHREAD_ONCE_INIT is 0, we use the following bit flags
2183 *
2184 * bit 0 set -> initialization is under way
2185 * bit 1 set -> initialization is complete
2186 */
2187#define ONCE_INITIALIZING (1 << 0)
2188#define ONCE_COMPLETED (1 << 1)
2189
2190 /* First check if the once is already initialized. This will be the common
2191 * case and we want to make this as fast as possible. Note that this still
2192 * requires a load_acquire operation here to ensure that all the
2193 * stores performed by the initialization function are observable on
2194 * this CPU after we exit.
2195 */
2196 if (__likely((*ocptr & ONCE_COMPLETED) != 0)) {
2197 ANDROID_MEMBAR_FULL();
2198 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002199 }
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002200
2201 for (;;) {
2202 /* Try to atomically set the INITIALIZING flag.
2203 * This requires a cmpxchg loop, and we may need
Elliott Hughesbfeab1b2012-09-05 17:47:37 -07002204 * to exit prematurely if we detect that
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002205 * COMPLETED is now set.
2206 */
2207 int32_t oldval, newval;
2208
2209 do {
2210 oldval = *ocptr;
2211 if ((oldval & ONCE_COMPLETED) != 0)
2212 break;
2213
2214 newval = oldval | ONCE_INITIALIZING;
2215 } while (__bionic_cmpxchg(oldval, newval, ocptr) != 0);
2216
2217 if ((oldval & ONCE_COMPLETED) != 0) {
2218 /* We detected that COMPLETED was set while in our loop */
2219 ANDROID_MEMBAR_FULL();
2220 return 0;
2221 }
2222
2223 if ((oldval & ONCE_INITIALIZING) == 0) {
2224 /* We got there first, we can jump out of the loop to
2225 * handle the initialization */
2226 break;
2227 }
2228
2229 /* Another thread is running the initialization and hasn't completed
2230 * yet, so wait for it, then try again. */
2231 __futex_wait_ex(ocptr, 0, oldval, NULL);
2232 }
2233
2234 /* call the initialization function. */
2235 (*init_routine)();
2236
2237 /* Do a store_release indicating that initialization is complete */
2238 ANDROID_MEMBAR_FULL();
2239 *ocptr = ONCE_COMPLETED;
2240
2241 /* Wake up any waiters, if any */
2242 __futex_wake_ex(ocptr, 0, INT_MAX);
2243
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002244 return 0;
2245}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03002246
2247/* This value is not exported by kernel headers, so hardcode it here */
2248#define MAX_TASK_COMM_LEN 16
2249#define TASK_COMM_FMT "/proc/self/task/%u/comm"
2250
2251int pthread_setname_np(pthread_t thid, const char *thname)
2252{
2253 size_t thname_len;
2254 int saved_errno, ret;
2255
2256 if (thid == 0 || thname == NULL)
2257 return EINVAL;
2258
2259 thname_len = strlen(thname);
2260 if (thname_len >= MAX_TASK_COMM_LEN)
2261 return ERANGE;
2262
2263 saved_errno = errno;
2264 if (thid == pthread_self())
2265 {
2266 ret = prctl(PR_SET_NAME, (unsigned long)thname, 0, 0, 0) ? errno : 0;
2267 }
2268 else
2269 {
2270 /* Have to change another thread's name */
2271 pthread_internal_t *thread = (pthread_internal_t *)thid;
2272 char comm_name[sizeof(TASK_COMM_FMT) + 8];
2273 ssize_t n;
2274 int fd;
2275
2276 snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, (unsigned int)thread->kernel_id);
2277 fd = open(comm_name, O_RDWR);
2278 if (fd == -1)
2279 {
2280 ret = errno;
2281 goto exit;
2282 }
2283 n = TEMP_FAILURE_RETRY(write(fd, thname, thname_len));
2284 close(fd);
2285
2286 if (n < 0)
2287 ret = errno;
2288 else if ((size_t)n != thname_len)
2289 ret = EIO;
2290 else
2291 ret = 0;
2292 }
2293exit:
2294 errno = saved_errno;
2295 return ret;
2296}
Glenn Kastend53cae02011-07-11 15:41:28 -07002297
2298/* Return the kernel thread ID for a pthread.
2299 * This is only defined for implementations where pthread <-> kernel is 1:1, which this is.
2300 * Not the same as pthread_getthreadid_np, which is commonly defined to be opaque.
2301 * Internal, not an NDK API.
2302 */
2303
2304pid_t __pthread_gettid(pthread_t thid)
2305{
2306 pthread_internal_t* thread = (pthread_internal_t*)thid;
2307 return thread->kernel_id;
2308}
Jean-Baptiste Querufaca92f2012-03-26 15:25:19 -07002309
2310int __pthread_settid(pthread_t thid, pid_t tid)
2311{
2312 if (thid == 0)
2313 return EINVAL;
2314
2315 pthread_internal_t* thread = (pthread_internal_t*)thid;
2316 thread->kernel_id = tid;
2317
2318 return 0;
2319}