blob: f2a7ebe44c234aee9e15ab98aadb5c9ef9d1caeb [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"
Elliott Hughes1e980b62013-01-17 18:36:06 -080053#include "debug_format.h"
Pierre Peifferd0c884d2012-02-22 16:40:15 +010054#include "pthread_internal.h"
55#include "thread_private.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080056
Mathias Agopian7c0c3792011-09-05 23:54:55 -070057extern void pthread_debug_mutex_lock_check(pthread_mutex_t *mutex);
58extern void pthread_debug_mutex_unlock_check(pthread_mutex_t *mutex);
59
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080060extern int __pthread_clone(int (*fn)(void*), void *child_stack, int flags, void *arg);
61extern void _exit_with_stack_teardown(void * stackBase, int stackSize, int retCode);
62extern void _exit_thread(int retCode);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080063
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -070064int __futex_wake_ex(volatile void *ftx, int pshared, int val)
65{
66 return __futex_syscall3(ftx, pshared ? FUTEX_WAKE : FUTEX_WAKE_PRIVATE, val);
67}
68
69int __futex_wait_ex(volatile void *ftx, int pshared, int val, const struct timespec *timeout)
70{
71 return __futex_syscall4(ftx, pshared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE, val, timeout);
72}
73
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -070074#define __likely(cond) __builtin_expect(!!(cond), 1)
75#define __unlikely(cond) __builtin_expect(!!(cond), 0)
76
Bruce Beare8e551a62011-03-28 09:47:35 -070077#ifdef __i386__
78#define ATTRIBUTES __attribute__((noinline)) __attribute__((fastcall))
79#else
80#define ATTRIBUTES __attribute__((noinline))
81#endif
82
83void ATTRIBUTES _thread_created_hook(pid_t thread_id);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080084
Pierre Peifferd0c884d2012-02-22 16:40:15 +010085static const int kPthreadInitFailed = 1;
86
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
Elliott Hughes4f251be2012-11-01 16:33:29 -0700108static void _pthread_internal_remove_locked(pthread_internal_t* thread) {
109 if (thread->next != NULL) {
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700110 thread->next->prev = thread->prev;
Elliott Hughes4f251be2012-11-01 16:33:29 -0700111 }
112 if (thread->prev != NULL) {
113 thread->prev->next = thread->next;
114 } else {
115 gThreadList = thread->next;
116 }
117
118 // The main thread is not heap-allocated. See __libc_init_tls for the declaration,
119 // and __libc_init_common for the point where it's added to the thread list.
120 if (thread->allocated_on_heap) {
121 free(thread);
122 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800123}
124
Elliott Hughes4f251be2012-11-01 16:33:29 -0700125static void _pthread_internal_remove(pthread_internal_t* thread) {
126 pthread_mutex_lock(&gThreadListLock);
127 _pthread_internal_remove_locked(thread);
128 pthread_mutex_unlock(&gThreadListLock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800129}
130
Elliott Hughes4f251be2012-11-01 16:33:29 -0700131__LIBC_ABI_PRIVATE__ void _pthread_internal_add(pthread_internal_t* thread) {
132 pthread_mutex_lock(&gThreadListLock);
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700133
Elliott Hughes4f251be2012-11-01 16:33:29 -0700134 // We insert at the head.
135 thread->next = gThreadList;
136 thread->prev = NULL;
137 if (thread->next != NULL) {
138 thread->next->prev = thread;
139 }
140 gThreadList = thread;
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700141
Elliott Hughes4f251be2012-11-01 16:33:29 -0700142 pthread_mutex_unlock(&gThreadListLock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800143}
144
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +0400145__LIBC_ABI_PRIVATE__ pthread_internal_t*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800146__get_thread(void)
147{
148 void** tls = (void**)__get_tls();
149
150 return (pthread_internal_t*) tls[TLS_SLOT_THREAD_ID];
151}
152
153
154void*
155__get_stack_base(int *p_stack_size)
156{
157 pthread_internal_t* thread = __get_thread();
158
159 *p_stack_size = thread->attr.stack_size;
160 return thread->attr.stack_base;
161}
162
163
Elliott Hughes5419b942012-10-16 15:54:46 -0700164void __init_tls(void** tls, void* thread) {
165 ((pthread_internal_t*) thread)->tls = tls;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800166
Elliott Hughes5419b942012-10-16 15:54:46 -0700167 // Zero-initialize all the slots.
168 for (size_t i = 0; i < BIONIC_TLS_SLOTS; ++i) {
169 tls[i] = NULL;
170 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800171
Elliott Hughesad88a082012-10-24 18:37:21 -0700172 // Slot 0 must point to itself. The x86 Linux kernel reads the TLS from %fs:0.
Elliott Hughes5419b942012-10-16 15:54:46 -0700173 tls[TLS_SLOT_SELF] = (void*) tls;
174 tls[TLS_SLOT_THREAD_ID] = thread;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800175
Elliott Hughesad88a082012-10-24 18:37:21 -0700176 // Stack guard generation may make system calls, and those system calls may fail.
177 // 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 -0700178 __set_tls((void*) tls);
Elliott Hughesad88a082012-10-24 18:37:21 -0700179 tls[TLS_SLOT_STACK_GUARD] = __generate_stack_chk_guard();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800180}
181
182
183/*
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100184 * This trampoline is called from the assembly _pthread_clone() function.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800185 */
186void __thread_entry(int (*func)(void*), void *arg, void **tls)
187{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800188 // Wait for our creating thread to release us. This lets it have time to
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100189 // notify gdb about this thread before we start doing anything.
Andy McFaddene2ac8982010-09-02 13:34:53 -0700190 //
191 // This also provides the memory barrier needed to ensure that all memory
192 // accesses previously made by the creating thread are visible to us.
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100193 pthread_mutex_t* start_mutex = (pthread_mutex_t*) &tls[TLS_SLOT_SELF];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800194 pthread_mutex_lock(start_mutex);
195 pthread_mutex_destroy(start_mutex);
196
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100197 pthread_internal_t* thread = (pthread_internal_t*) tls[TLS_SLOT_THREAD_ID];
198 __init_tls(tls, thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800199
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100200 if ((thread->internal_flags & kPthreadInitFailed) != 0) {
201 pthread_exit(NULL);
202 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800203
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100204 int result = func(arg);
205 pthread_exit((void*) result);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800206}
207
Dave Burke88f1ea82012-09-17 20:37:38 -0700208#include <private/logd.h>
209
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +0400210__LIBC_ABI_PRIVATE__
Xi Wangae8eb742012-10-27 02:02:01 -0400211int _init_thread(pthread_internal_t* thread, pid_t kernel_id, const pthread_attr_t* attr,
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700212 void* stack_base, bool add_to_thread_list)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800213{
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100214 int error = 0;
215
Xi Wangae8eb742012-10-27 02:02:01 -0400216 thread->attr = *attr;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800217 thread->attr.stack_base = stack_base;
Xi Wangae8eb742012-10-27 02:02:01 -0400218 thread->kernel_id = kernel_id;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800219
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100220 // Make a note of whether the user supplied this stack (so we know whether or not to free it).
221 if (attr->stack_base == stack_base) {
222 thread->attr.flags |= PTHREAD_ATTR_FLAG_USER_STACK;
223 }
224
225 // Set the scheduling policy/priority of the thread.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800226 if (thread->attr.sched_policy != SCHED_NORMAL) {
227 struct sched_param param;
228 param.sched_priority = thread->attr.sched_priority;
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100229 if (sched_setscheduler(kernel_id, thread->attr.sched_policy, &param) == -1) {
Xi Wangae8eb742012-10-27 02:02:01 -0400230 // For backwards compatibility reasons, we just warn about failures here.
231 // error = errno;
Dave Burke88f1ea82012-09-17 20:37:38 -0700232 const char* msg = "pthread_create sched_setscheduler call failed: %s\n";
Elliott Hughes1e980b62013-01-17 18:36:06 -0800233 __libc_format_log(ANDROID_LOG_WARN, "libc", msg, strerror(errno));
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100234 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800235 }
236
237 pthread_cond_init(&thread->join_cond, NULL);
238 thread->join_count = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800239 thread->cleanup_stack = NULL;
240
Elliott Hughesbfeab1b2012-09-05 17:47:37 -0700241 if (add_to_thread_list) {
242 _pthread_internal_add(thread);
243 }
244
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100245 return error;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800246}
247
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800248static void *mkstack(size_t size, size_t guard_size)
249{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800250 pthread_mutex_lock(&mmap_lock);
251
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100252 int prot = PROT_READ | PROT_WRITE;
253 int flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE;
Elliott Hughes9c3eca72012-05-08 13:26:28 -0700254 void* stack = mmap(NULL, size, prot, flags, -1, 0);
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100255 if (stack == MAP_FAILED) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800256 stack = NULL;
257 goto done;
258 }
259
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100260 if (mprotect(stack, guard_size, PROT_NONE) == -1) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800261 munmap(stack, size);
262 stack = NULL;
263 goto done;
264 }
265
266done:
267 pthread_mutex_unlock(&mmap_lock);
268 return stack;
269}
270
271/*
Andy McFaddene2ac8982010-09-02 13:34:53 -0700272 * Create a new thread. The thread's stack is laid out like so:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800273 *
274 * +---------------------------+
275 * | pthread_internal_t |
276 * +---------------------------+
277 * | |
278 * | TLS area |
279 * | |
280 * +---------------------------+
281 * | |
282 * . .
283 * . stack area .
284 * . .
285 * | |
286 * +---------------------------+
287 * | guard page |
288 * +---------------------------+
289 *
290 * note that TLS[0] must be a pointer to itself, this is required
291 * by the thread-local storage implementation of the x86 Linux
292 * kernel, where the TLS pointer is read by reading fs:[0]
293 */
294int pthread_create(pthread_t *thread_out, pthread_attr_t const * attr,
295 void *(*start_routine)(void *), void * arg)
296{
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100297 int old_errno = errno;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800298
299 /* this will inform the rest of the C library that at least one thread
300 * was created. this will enforce certain functions to acquire/release
301 * locks (e.g. atexit()) to protect shared global structures.
302 *
303 * this works because pthread_create() is not called by the C library
304 * initialization routine that sets up the main thread's data structures.
305 */
306 __isthreaded = 1;
307
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100308 pthread_internal_t* thread = calloc(sizeof(*thread), 1);
309 if (thread == NULL) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800310 return ENOMEM;
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100311 }
Elliott Hughes4f251be2012-11-01 16:33:29 -0700312 thread->allocated_on_heap = true;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800313
314 if (attr == NULL) {
315 attr = &gDefaultPthreadAttr;
316 }
317
318 // make sure the stack is PAGE_SIZE aligned
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100319 size_t stack_size = (attr->stack_size + (PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
320 uint8_t* stack = attr->stack_base;
321 if (stack == NULL) {
322 stack = mkstack(stack_size, attr->guard_size);
323 if (stack == NULL) {
Elliott Hughes4f251be2012-11-01 16:33:29 -0700324 free(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800325 return ENOMEM;
326 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800327 }
328
329 // Make room for TLS
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100330 void** tls = (void**)(stack + stack_size - BIONIC_TLS_SLOTS*sizeof(void*));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800331
332 // Create a mutex for the thread in TLS_SLOT_SELF to wait on once it starts so we can keep
333 // it from doing anything until after we notify the debugger about it
Andy McFaddene2ac8982010-09-02 13:34:53 -0700334 //
335 // This also provides the memory barrier we need to ensure that all
336 // memory accesses previously performed by this thread are visible to
337 // the new thread.
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100338 pthread_mutex_t* start_mutex = (pthread_mutex_t*) &tls[TLS_SLOT_SELF];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800339 pthread_mutex_init(start_mutex, NULL);
340 pthread_mutex_lock(start_mutex);
341
342 tls[TLS_SLOT_THREAD_ID] = thread;
343
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100344 int flags = CLONE_FILES | CLONE_FS | CLONE_VM | CLONE_SIGHAND |
345 CLONE_THREAD | CLONE_SYSVSEM | CLONE_DETACHED;
346 int tid = __pthread_clone((int(*)(void*))start_routine, tls, flags, arg);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800347
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100348 if (tid < 0) {
349 int clone_errno = errno;
350 pthread_mutex_unlock(start_mutex);
351 if (stack != attr->stack_base) {
352 munmap(stack, stack_size);
353 }
Elliott Hughes4f251be2012-11-01 16:33:29 -0700354 free(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800355 errno = old_errno;
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100356 return clone_errno;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800357 }
358
Xi Wangae8eb742012-10-27 02:02:01 -0400359 int init_errno = _init_thread(thread, tid, attr, stack, true);
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100360 if (init_errno != 0) {
361 // Mark the thread detached and let its __thread_entry run to
362 // completion. (It'll just exit immediately, cleaning up its resources.)
363 thread->internal_flags |= kPthreadInitFailed;
364 thread->attr.flags |= PTHREAD_ATTR_FLAG_DETACHED;
365 pthread_mutex_unlock(start_mutex);
366 errno = old_errno;
367 return init_errno;
368 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800369
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100370 // Notify any debuggers about the new thread.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800371 pthread_mutex_lock(&gDebuggerNotificationLock);
372 _thread_created_hook(tid);
373 pthread_mutex_unlock(&gDebuggerNotificationLock);
374
Jurijs Oniscuks2932f042012-07-05 14:57:38 +0200375 // Publish the pthread_t and let the thread run.
376 *thread_out = (pthread_t) thread;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800377 pthread_mutex_unlock(start_mutex);
378
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800379 return 0;
380}
381
382
383int pthread_attr_init(pthread_attr_t * attr)
384{
385 *attr = gDefaultPthreadAttr;
386 return 0;
387}
388
389int pthread_attr_destroy(pthread_attr_t * attr)
390{
391 memset(attr, 0x42, sizeof(pthread_attr_t));
392 return 0;
393}
394
395int pthread_attr_setdetachstate(pthread_attr_t * attr, int state)
396{
397 if (state == PTHREAD_CREATE_DETACHED) {
398 attr->flags |= PTHREAD_ATTR_FLAG_DETACHED;
399 } else if (state == PTHREAD_CREATE_JOINABLE) {
400 attr->flags &= ~PTHREAD_ATTR_FLAG_DETACHED;
401 } else {
402 return EINVAL;
403 }
404 return 0;
405}
406
407int pthread_attr_getdetachstate(pthread_attr_t const * attr, int * state)
408{
409 *state = (attr->flags & PTHREAD_ATTR_FLAG_DETACHED)
410 ? PTHREAD_CREATE_DETACHED
411 : PTHREAD_CREATE_JOINABLE;
412 return 0;
413}
414
415int pthread_attr_setschedpolicy(pthread_attr_t * attr, int policy)
416{
417 attr->sched_policy = policy;
418 return 0;
419}
420
421int pthread_attr_getschedpolicy(pthread_attr_t const * attr, int * policy)
422{
423 *policy = attr->sched_policy;
424 return 0;
425}
426
427int pthread_attr_setschedparam(pthread_attr_t * attr, struct sched_param const * param)
428{
429 attr->sched_priority = param->sched_priority;
430 return 0;
431}
432
433int pthread_attr_getschedparam(pthread_attr_t const * attr, struct sched_param * param)
434{
435 param->sched_priority = attr->sched_priority;
436 return 0;
437}
438
439int pthread_attr_setstacksize(pthread_attr_t * attr, size_t stack_size)
440{
441 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
442 return EINVAL;
443 }
444 attr->stack_size = stack_size;
445 return 0;
446}
447
448int pthread_attr_getstacksize(pthread_attr_t const * attr, size_t * stack_size)
449{
450 *stack_size = attr->stack_size;
451 return 0;
452}
453
Wink Savillea12c5442013-01-08 15:15:45 -0800454int pthread_attr_setstackaddr(pthread_attr_t * attr __attribute__((unused)),
455 void * stack_addr __attribute__((unused)))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800456{
Wink Savillea12c5442013-01-08 15:15:45 -0800457 // This was removed from POSIX.1-2008, and is not implemented on bionic.
458 // Needed for ABI compatibility with the NDK.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800459 return ENOSYS;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800460}
461
462int pthread_attr_getstackaddr(pthread_attr_t const * attr, void ** stack_addr)
463{
Wink Savillea12c5442013-01-08 15:15:45 -0800464 // This was removed from POSIX.1-2008.
465 // Needed for ABI compatibility with the NDK.
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700466 *stack_addr = (char*)attr->stack_base + attr->stack_size;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800467 return 0;
468}
469
470int pthread_attr_setstack(pthread_attr_t * attr, void * stack_base, size_t stack_size)
471{
472 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
473 return EINVAL;
474 }
475 if ((uint32_t)stack_base & (PAGE_SIZE - 1)) {
476 return EINVAL;
477 }
478 attr->stack_base = stack_base;
479 attr->stack_size = stack_size;
480 return 0;
481}
482
483int pthread_attr_getstack(pthread_attr_t const * attr, void ** stack_base, size_t * stack_size)
484{
485 *stack_base = attr->stack_base;
486 *stack_size = attr->stack_size;
487 return 0;
488}
489
490int pthread_attr_setguardsize(pthread_attr_t * attr, size_t guard_size)
491{
492 if (guard_size & (PAGE_SIZE - 1) || guard_size < PAGE_SIZE) {
493 return EINVAL;
494 }
495
496 attr->guard_size = guard_size;
497 return 0;
498}
499
500int pthread_attr_getguardsize(pthread_attr_t const * attr, size_t * guard_size)
501{
502 *guard_size = attr->guard_size;
503 return 0;
504}
505
506int pthread_getattr_np(pthread_t thid, pthread_attr_t * attr)
507{
508 pthread_internal_t * thread = (pthread_internal_t *)thid;
509 *attr = thread->attr;
510 return 0;
511}
512
Wink Savillea12c5442013-01-08 15:15:45 -0800513int pthread_attr_setscope(pthread_attr_t *attr __attribute__((unused)), int scope)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800514{
515 if (scope == PTHREAD_SCOPE_SYSTEM)
516 return 0;
517 if (scope == PTHREAD_SCOPE_PROCESS)
518 return ENOTSUP;
519
520 return EINVAL;
521}
522
Wink Savillea12c5442013-01-08 15:15:45 -0800523int pthread_attr_getscope(pthread_attr_t const *attr __attribute__((unused)))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800524{
525 return PTHREAD_SCOPE_SYSTEM;
526}
527
528
529/* CAVEAT: our implementation of pthread_cleanup_push/pop doesn't support C++ exceptions
530 * and thread cancelation
531 */
532
533void __pthread_cleanup_push( __pthread_cleanup_t* c,
534 __pthread_cleanup_func_t routine,
535 void* arg )
536{
537 pthread_internal_t* thread = __get_thread();
538
539 c->__cleanup_routine = routine;
540 c->__cleanup_arg = arg;
541 c->__cleanup_prev = thread->cleanup_stack;
542 thread->cleanup_stack = c;
543}
544
545void __pthread_cleanup_pop( __pthread_cleanup_t* c, int execute )
546{
547 pthread_internal_t* thread = __get_thread();
548
549 thread->cleanup_stack = c->__cleanup_prev;
550 if (execute)
551 c->__cleanup_routine(c->__cleanup_arg);
552}
553
554/* used by pthread_exit() to clean all TLS keys of the current thread */
555static void pthread_key_clean_all(void);
556
557void pthread_exit(void * retval)
558{
559 pthread_internal_t* thread = __get_thread();
560 void* stack_base = thread->attr.stack_base;
561 int stack_size = thread->attr.stack_size;
562 int user_stack = (thread->attr.flags & PTHREAD_ATTR_FLAG_USER_STACK) != 0;
Jack Rene480fc82011-09-21 12:44:11 +0200563 sigset_t mask;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800564
565 // call the cleanup handlers first
566 while (thread->cleanup_stack) {
567 __pthread_cleanup_t* c = thread->cleanup_stack;
568 thread->cleanup_stack = c->__cleanup_prev;
569 c->__cleanup_routine(c->__cleanup_arg);
570 }
571
572 // call the TLS destructors, it is important to do that before removing this
573 // thread from the global list. this will ensure that if someone else deletes
574 // a TLS key, the corresponding value will be set to NULL in this thread's TLS
575 // space (see pthread_key_delete)
576 pthread_key_clean_all();
577
578 // if the thread is detached, destroy the pthread_internal_t
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400579 // otherwise, keep it in memory and signal any joiners.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800580 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
581 _pthread_internal_remove(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800582 } else {
Bjorn Andersson0753dc62012-05-03 17:12:39 -0700583 pthread_mutex_lock(&gThreadListLock);
584
585 /* make sure that the thread struct doesn't have stale pointers to a stack that
586 * will be unmapped after the exit call below.
587 */
588 if (!user_stack) {
589 thread->attr.stack_base = NULL;
590 thread->attr.stack_size = 0;
591 thread->tls = NULL;
592 }
593
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800594 /* the join_count field is used to store the number of threads waiting for
595 * the termination of this thread with pthread_join(),
596 *
597 * if it is positive we need to signal the waiters, and we do not touch
598 * the count (it will be decremented by the waiters, the last one will
599 * also remove/free the thread structure
600 *
601 * if it is zero, we set the count value to -1 to indicate that the
602 * thread is in 'zombie' state: it has stopped executing, and its stack
603 * is gone (as well as its TLS area). when another thread calls pthread_join()
604 * on it, it will immediately free the thread and return.
605 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800606 thread->return_value = retval;
607 if (thread->join_count > 0) {
608 pthread_cond_broadcast(&thread->join_cond);
609 } else {
610 thread->join_count = -1; /* zombie thread */
611 }
612 pthread_mutex_unlock(&gThreadListLock);
613 }
614
Jack Rene480fc82011-09-21 12:44:11 +0200615 sigfillset(&mask);
616 sigdelset(&mask, SIGSEGV);
617 (void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *)NULL);
618
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800619 // destroy the thread stack
620 if (user_stack)
621 _exit_thread((int)retval);
622 else
623 _exit_with_stack_teardown(stack_base, stack_size, (int)retval);
624}
625
626int pthread_join(pthread_t thid, void ** ret_val)
627{
628 pthread_internal_t* thread = (pthread_internal_t*)thid;
Elliott Hughes14f19592012-10-29 10:19:44 -0700629 if (thid == pthread_self()) {
630 return EDEADLK;
631 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800632
633 // check that the thread still exists and is not detached
634 pthread_mutex_lock(&gThreadListLock);
635
Elliott Hughes14f19592012-10-29 10:19:44 -0700636 for (thread = gThreadList; thread != NULL; thread = thread->next) {
637 if (thread == (pthread_internal_t*)thid) {
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200638 goto FoundIt;
Elliott Hughes14f19592012-10-29 10:19:44 -0700639 }
640 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800641
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200642 pthread_mutex_unlock(&gThreadListLock);
643 return ESRCH;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800644
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200645FoundIt:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800646 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
647 pthread_mutex_unlock(&gThreadListLock);
648 return EINVAL;
649 }
650
651 /* wait for thread death when needed
652 *
653 * if the 'join_count' is negative, this is a 'zombie' thread that
654 * is already dead and without stack/TLS
655 *
656 * otherwise, we need to increment 'join-count' and wait to be signaled
657 */
Elliott Hughes14f19592012-10-29 10:19:44 -0700658 int count = thread->join_count;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800659 if (count >= 0) {
660 thread->join_count += 1;
661 pthread_cond_wait( &thread->join_cond, &gThreadListLock );
662 count = --thread->join_count;
663 }
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400664 if (ret_val) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800665 *ret_val = thread->return_value;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400666 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800667
668 /* remove thread descriptor when we're the last joiner or when the
669 * thread was already a zombie.
670 */
671 if (count <= 0) {
672 _pthread_internal_remove_locked(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800673 }
674 pthread_mutex_unlock(&gThreadListLock);
675 return 0;
676}
677
678int pthread_detach( pthread_t thid )
679{
680 pthread_internal_t* thread;
681 int result = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800682
683 pthread_mutex_lock(&gThreadListLock);
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400684 for (thread = gThreadList; thread != NULL; thread = thread->next) {
685 if (thread == (pthread_internal_t*)thid) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800686 goto FoundIt;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400687 }
688 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800689
690 result = ESRCH;
691 goto Exit;
692
693FoundIt:
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400694 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
695 result = EINVAL; // Already detached.
696 goto Exit;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800697 }
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400698
699 if (thread->join_count > 0) {
700 result = 0; // Already being joined; silently do nothing, like glibc.
701 goto Exit;
702 }
703
704 thread->attr.flags |= PTHREAD_ATTR_FLAG_DETACHED;
705
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800706Exit:
707 pthread_mutex_unlock(&gThreadListLock);
708 return result;
709}
710
711pthread_t pthread_self(void)
712{
713 return (pthread_t)__get_thread();
714}
715
716int pthread_equal(pthread_t one, pthread_t two)
717{
718 return (one == two ? 1 : 0);
719}
720
721int pthread_getschedparam(pthread_t thid, int * policy,
722 struct sched_param * param)
723{
724 int old_errno = errno;
725
726 pthread_internal_t * thread = (pthread_internal_t *)thid;
727 int err = sched_getparam(thread->kernel_id, param);
728 if (!err) {
729 *policy = sched_getscheduler(thread->kernel_id);
730 } else {
731 err = errno;
732 errno = old_errno;
733 }
734 return err;
735}
736
737int pthread_setschedparam(pthread_t thid, int policy,
738 struct sched_param const * param)
739{
740 pthread_internal_t * thread = (pthread_internal_t *)thid;
741 int old_errno = errno;
742 int ret;
743
744 ret = sched_setscheduler(thread->kernel_id, policy, param);
745 if (ret < 0) {
746 ret = errno;
747 errno = old_errno;
748 }
749 return ret;
750}
751
752
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800753/* a mutex is implemented as a 32-bit integer holding the following fields
754 *
755 * bits: name description
756 * 31-16 tid owner thread's kernel id (recursive and errorcheck only)
757 * 15-14 type mutex type
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700758 * 13 shared process-shared flag
759 * 12-2 counter counter of recursive mutexes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800760 * 1-0 state lock state (0, 1 or 2)
761 */
762
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100763/* Convenience macro, creates a mask of 'bits' bits that starts from
764 * the 'shift'-th least significant bit in a 32-bit word.
765 *
766 * Examples: FIELD_MASK(0,4) -> 0xf
767 * FIELD_MASK(16,9) -> 0x1ff0000
768 */
769#define FIELD_MASK(shift,bits) (((1 << (bits))-1) << (shift))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800770
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100771/* This one is used to create a bit pattern from a given field value */
772#define FIELD_TO_BITS(val,shift,bits) (((val) & ((1 << (bits))-1)) << (shift))
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100773
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100774/* And this one does the opposite, i.e. extract a field's value from a bit pattern */
775#define FIELD_FROM_BITS(val,shift,bits) (((val) >> (shift)) & ((1 << (bits))-1))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800776
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100777/* Mutex state:
778 *
779 * 0 for unlocked
780 * 1 for locked, no waiters
781 * 2 for locked, maybe waiters
782 */
783#define MUTEX_STATE_SHIFT 0
784#define MUTEX_STATE_LEN 2
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800785
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100786#define MUTEX_STATE_MASK FIELD_MASK(MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
787#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
788#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
789
790#define MUTEX_STATE_UNLOCKED 0 /* must be 0 to match __PTHREAD_MUTEX_INIT_VALUE */
791#define MUTEX_STATE_LOCKED_UNCONTENDED 1 /* must be 1 due to atomic dec in unlock operation */
792#define MUTEX_STATE_LOCKED_CONTENDED 2 /* must be 1 + LOCKED_UNCONTENDED due to atomic dec */
793
794#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
795#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
796
797#define MUTEX_STATE_BITS_UNLOCKED MUTEX_STATE_TO_BITS(MUTEX_STATE_UNLOCKED)
798#define MUTEX_STATE_BITS_LOCKED_UNCONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_UNCONTENDED)
799#define MUTEX_STATE_BITS_LOCKED_CONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_CONTENDED)
800
801/* return true iff the mutex if locked with no waiters */
802#define MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_UNCONTENDED)
803
804/* return true iff the mutex if locked with maybe waiters */
805#define MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_CONTENDED)
806
807/* used to flip from LOCKED_UNCONTENDED to LOCKED_CONTENDED */
808#define MUTEX_STATE_BITS_FLIP_CONTENTION(v) ((v) ^ (MUTEX_STATE_BITS_LOCKED_CONTENDED ^ MUTEX_STATE_BITS_LOCKED_UNCONTENDED))
809
810/* Mutex counter:
811 *
812 * We need to check for overflow before incrementing, and we also need to
813 * detect when the counter is 0
814 */
815#define MUTEX_COUNTER_SHIFT 2
816#define MUTEX_COUNTER_LEN 11
817#define MUTEX_COUNTER_MASK FIELD_MASK(MUTEX_COUNTER_SHIFT, MUTEX_COUNTER_LEN)
818
819#define MUTEX_COUNTER_BITS_WILL_OVERFLOW(v) (((v) & MUTEX_COUNTER_MASK) == MUTEX_COUNTER_MASK)
820#define MUTEX_COUNTER_BITS_IS_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
821
822/* Used to increment the counter directly after overflow has been checked */
823#define MUTEX_COUNTER_BITS_ONE FIELD_TO_BITS(1,MUTEX_COUNTER_SHIFT,MUTEX_COUNTER_LEN)
824
825/* Returns true iff the counter is 0 */
826#define MUTEX_COUNTER_BITS_ARE_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
827
828/* Mutex shared bit flag
829 *
830 * This flag is set to indicate that the mutex is shared among processes.
831 * This changes the futex opcode we use for futex wait/wake operations
832 * (non-shared operations are much faster).
833 */
834#define MUTEX_SHARED_SHIFT 13
835#define MUTEX_SHARED_MASK FIELD_MASK(MUTEX_SHARED_SHIFT,1)
836
837/* Mutex type:
838 *
839 * We support normal, recursive and errorcheck mutexes.
840 *
841 * The constants defined here *cannot* be changed because they must match
842 * the C library ABI which defines the following initialization values in
843 * <pthread.h>:
844 *
845 * __PTHREAD_MUTEX_INIT_VALUE
846 * __PTHREAD_RECURSIVE_MUTEX_VALUE
847 * __PTHREAD_ERRORCHECK_MUTEX_INIT_VALUE
848 */
849#define MUTEX_TYPE_SHIFT 14
850#define MUTEX_TYPE_LEN 2
851#define MUTEX_TYPE_MASK FIELD_MASK(MUTEX_TYPE_SHIFT,MUTEX_TYPE_LEN)
852
853#define MUTEX_TYPE_NORMAL 0 /* Must be 0 to match __PTHREAD_MUTEX_INIT_VALUE */
854#define MUTEX_TYPE_RECURSIVE 1
855#define MUTEX_TYPE_ERRORCHECK 2
856
857#define MUTEX_TYPE_TO_BITS(t) FIELD_TO_BITS(t, MUTEX_TYPE_SHIFT, MUTEX_TYPE_LEN)
858
859#define MUTEX_TYPE_BITS_NORMAL MUTEX_TYPE_TO_BITS(MUTEX_TYPE_NORMAL)
860#define MUTEX_TYPE_BITS_RECURSIVE MUTEX_TYPE_TO_BITS(MUTEX_TYPE_RECURSIVE)
861#define MUTEX_TYPE_BITS_ERRORCHECK MUTEX_TYPE_TO_BITS(MUTEX_TYPE_ERRORCHECK)
862
863/* Mutex owner field:
864 *
865 * This is only used for recursive and errorcheck mutexes. It holds the
866 * kernel TID of the owning thread. Note that this works because the Linux
867 * kernel _only_ uses 16-bit values for thread ids.
868 *
869 * More specifically, it will wrap to 10000 when it reaches over 32768 for
870 * application processes. You can check this by running the following inside
871 * an adb shell session:
872 *
873 OLDPID=$$;
874 while true; do
875 NEWPID=$(sh -c 'echo $$')
876 if [ "$NEWPID" -gt 32768 ]; then
877 echo "AARGH: new PID $NEWPID is too high!"
878 exit 1
879 fi
880 if [ "$NEWPID" -lt "$OLDPID" ]; then
881 echo "****** Wrapping from PID $OLDPID to $NEWPID. *******"
882 else
883 echo -n "$NEWPID!"
884 fi
885 OLDPID=$NEWPID
886 done
887
888 * Note that you can run the same example on a desktop Linux system,
889 * the wrapping will also happen at 32768, but will go back to 300 instead.
890 */
891#define MUTEX_OWNER_SHIFT 16
892#define MUTEX_OWNER_LEN 16
893
894#define MUTEX_OWNER_FROM_BITS(v) FIELD_FROM_BITS(v,MUTEX_OWNER_SHIFT,MUTEX_OWNER_LEN)
895#define MUTEX_OWNER_TO_BITS(v) FIELD_TO_BITS(v,MUTEX_OWNER_SHIFT,MUTEX_OWNER_LEN)
896
897/* Convenience macros.
898 *
899 * These are used to form or modify the bit pattern of a given mutex value
900 */
901
902
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800903
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700904/* a mutex attribute holds the following fields
905 *
906 * bits: name description
907 * 0-3 type type of mutex
908 * 4 shared process-shared flag
909 */
910#define MUTEXATTR_TYPE_MASK 0x000f
911#define MUTEXATTR_SHARED_MASK 0x0010
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800912
913
914int pthread_mutexattr_init(pthread_mutexattr_t *attr)
915{
916 if (attr) {
917 *attr = PTHREAD_MUTEX_DEFAULT;
918 return 0;
919 } else {
920 return EINVAL;
921 }
922}
923
924int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
925{
926 if (attr) {
927 *attr = -1;
928 return 0;
929 } else {
930 return EINVAL;
931 }
932}
933
934int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
935{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700936 if (attr) {
937 int atype = (*attr & MUTEXATTR_TYPE_MASK);
938
939 if (atype >= PTHREAD_MUTEX_NORMAL &&
940 atype <= PTHREAD_MUTEX_ERRORCHECK) {
941 *type = atype;
942 return 0;
943 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800944 }
945 return EINVAL;
946}
947
948int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
949{
950 if (attr && type >= PTHREAD_MUTEX_NORMAL &&
951 type <= PTHREAD_MUTEX_ERRORCHECK ) {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700952 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800953 return 0;
954 }
955 return EINVAL;
956}
957
958/* process-shared mutexes are not supported at the moment */
959
960int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
961{
962 if (!attr)
963 return EINVAL;
964
Mathias Agopianb7681162009-07-13 22:00:33 -0700965 switch (pshared) {
966 case PTHREAD_PROCESS_PRIVATE:
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700967 *attr &= ~MUTEXATTR_SHARED_MASK;
968 return 0;
969
Mathias Agopianb7681162009-07-13 22:00:33 -0700970 case PTHREAD_PROCESS_SHARED:
971 /* our current implementation of pthread actually supports shared
972 * mutexes but won't cleanup if a process dies with the mutex held.
973 * Nevertheless, it's better than nothing. Shared mutexes are used
974 * by surfaceflinger and audioflinger.
975 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700976 *attr |= MUTEXATTR_SHARED_MASK;
Mathias Agopianb7681162009-07-13 22:00:33 -0700977 return 0;
978 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700979 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800980}
981
982int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
983{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700984 if (!attr || !pshared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800985 return EINVAL;
986
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700987 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED
988 : PTHREAD_PROCESS_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800989 return 0;
990}
991
992int pthread_mutex_init(pthread_mutex_t *mutex,
993 const pthread_mutexattr_t *attr)
994{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700995 int value = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800996
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700997 if (mutex == NULL)
998 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800999
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001000 if (__likely(attr == NULL)) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001001 mutex->value = MUTEX_TYPE_BITS_NORMAL;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001002 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001003 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001004
1005 if ((*attr & MUTEXATTR_SHARED_MASK) != 0)
1006 value |= MUTEX_SHARED_MASK;
1007
1008 switch (*attr & MUTEXATTR_TYPE_MASK) {
1009 case PTHREAD_MUTEX_NORMAL:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001010 value |= MUTEX_TYPE_BITS_NORMAL;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001011 break;
1012 case PTHREAD_MUTEX_RECURSIVE:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001013 value |= MUTEX_TYPE_BITS_RECURSIVE;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001014 break;
1015 case PTHREAD_MUTEX_ERRORCHECK:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001016 value |= MUTEX_TYPE_BITS_ERRORCHECK;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001017 break;
1018 default:
1019 return EINVAL;
1020 }
1021
1022 mutex->value = value;
1023 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001024}
1025
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001026
1027/*
1028 * Lock a non-recursive mutex.
1029 *
1030 * As noted above, there are three states:
1031 * 0 (unlocked, no contention)
1032 * 1 (locked, no contention)
1033 * 2 (locked, contention)
1034 *
1035 * Non-recursive mutexes don't use the thread-id or counter fields, and the
1036 * "type" value is zero, so the only bits that will be set are the ones in
1037 * the lock state field.
1038 */
1039static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001040_normal_lock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001041{
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001042 /* convenience shortcuts */
1043 const int unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
1044 const int locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001045 /*
1046 * The common case is an unlocked mutex, so we begin by trying to
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001047 * change the lock's state from 0 (UNLOCKED) to 1 (LOCKED).
1048 * __bionic_cmpxchg() returns 0 if it made the swap successfully.
1049 * If the result is nonzero, this lock is already held by another thread.
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001050 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001051 if (__bionic_cmpxchg(unlocked, locked_uncontended, &mutex->value) != 0) {
1052 const int locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001053 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001054 * We want to go to sleep until the mutex is available, which
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001055 * requires promoting it to state 2 (CONTENDED). We need to
1056 * swap in the new state value and then wait until somebody wakes us up.
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001057 *
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001058 * __bionic_swap() returns the previous value. We swap 2 in and
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001059 * see if we got zero back; if so, we have acquired the lock. If
1060 * not, another thread still holds the lock and we wait again.
1061 *
1062 * The second argument to the __futex_wait() call is compared
1063 * against the current value. If it doesn't match, __futex_wait()
1064 * returns immediately (otherwise, it sleeps for a time specified
1065 * by the third argument; 0 means sleep forever). This ensures
1066 * that the mutex is in state 2 when we go to sleep on it, which
1067 * guarantees a wake-up call.
1068 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001069 while (__bionic_swap(locked_contended, &mutex->value) != unlocked)
1070 __futex_wait_ex(&mutex->value, shared, locked_contended, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001071 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001072 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001073}
1074
1075/*
1076 * Release a non-recursive mutex. The caller is responsible for determining
1077 * that we are in fact the owner of this lock.
1078 */
1079static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001080_normal_unlock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001081{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001082 ANDROID_MEMBAR_FULL();
1083
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001084 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001085 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001086 * to release the lock. __bionic_atomic_dec() returns the previous value;
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001087 * if it wasn't 1 we have to do some additional work.
1088 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001089 if (__bionic_atomic_dec(&mutex->value) != (shared|MUTEX_STATE_BITS_LOCKED_UNCONTENDED)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001090 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001091 * Start by releasing the lock. The decrement changed it from
1092 * "contended lock" to "uncontended lock", which means we still
1093 * hold it, and anybody who tries to sneak in will push it back
1094 * to state 2.
1095 *
1096 * Once we set it to zero the lock is up for grabs. We follow
1097 * this with a __futex_wake() to ensure that one of the waiting
1098 * threads has a chance to grab it.
1099 *
1100 * This doesn't cause a race with the swap/wait pair in
1101 * _normal_lock(), because the __futex_wait() call there will
1102 * return immediately if the mutex value isn't 2.
1103 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001104 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001105
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001106 /*
1107 * Wake up one waiting thread. We don't know which thread will be
1108 * woken or when it'll start executing -- futexes make no guarantees
1109 * here. There may not even be a thread waiting.
1110 *
1111 * The newly-woken thread will replace the 0 we just set above
1112 * with 2, which means that when it eventually releases the mutex
1113 * it will also call FUTEX_WAKE. This results in one extra wake
1114 * call whenever a lock is contended, but lets us avoid forgetting
1115 * anyone without requiring us to track the number of sleepers.
1116 *
1117 * It's possible for another thread to sneak in and grab the lock
1118 * between the zero assignment above and the wake call below. If
1119 * the new thread is "slow" and holds the lock for a while, we'll
1120 * wake up a sleeper, which will swap in a 2 and then go back to
1121 * sleep since the lock is still held. If the new thread is "fast",
1122 * running to completion before we call wake, the thread we
1123 * eventually wake will find an unlocked mutex and will execute.
1124 * Either way we have correct behavior and nobody is orphaned on
1125 * the wait queue.
1126 */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001127 __futex_wake_ex(&mutex->value, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001128 }
1129}
1130
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001131/* This common inlined function is used to increment the counter of an
1132 * errorcheck or recursive mutex.
1133 *
1134 * For errorcheck mutexes, it will return EDEADLK
1135 * If the counter overflows, it will return EAGAIN
1136 * Otherwise, it atomically increments the counter and returns 0
1137 * after providing an acquire barrier.
1138 *
1139 * mtype is the current mutex type
1140 * mvalue is the current mutex value (already loaded)
1141 * mutex pointers to the mutex.
1142 */
1143static __inline__ __attribute__((always_inline)) int
1144_recursive_increment(pthread_mutex_t* mutex, int mvalue, int mtype)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001145{
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001146 if (mtype == MUTEX_TYPE_BITS_ERRORCHECK) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001147 /* trying to re-lock a mutex we already acquired */
1148 return EDEADLK;
1149 }
1150
1151 /* Detect recursive lock overflow and return EAGAIN.
1152 * This is safe because only the owner thread can modify the
David 'Digit' Turnerb57db752012-01-24 13:20:38 +01001153 * counter bits in the mutex value.
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001154 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001155 if (MUTEX_COUNTER_BITS_WILL_OVERFLOW(mvalue)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001156 return EAGAIN;
1157 }
1158
1159 /* We own the mutex, but other threads are able to change
David 'Digit' Turnerb57db752012-01-24 13:20:38 +01001160 * the lower bits (e.g. promoting it to "contended"), so we
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001161 * need to use an atomic cmpxchg loop to update the counter.
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001162 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001163 for (;;) {
1164 /* increment counter, overflow was already checked */
1165 int newval = mvalue + MUTEX_COUNTER_BITS_ONE;
1166 if (__likely(__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0)) {
1167 /* mutex is still locked, not need for a memory barrier */
1168 return 0;
1169 }
1170 /* the value was changed, this happens when another thread changes
1171 * the lower state bits from 1 to 2 to indicate contention. This
1172 * cannot change the counter, so simply reload and try again.
1173 */
1174 mvalue = mutex->value;
1175 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001176}
1177
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001178__LIBC_HIDDEN__
1179int pthread_mutex_lock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001180{
Wink Savillea12c5442013-01-08 15:15:45 -08001181 int mvalue, mtype, tid, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001182
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001183 if (__unlikely(mutex == NULL))
1184 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001185
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001186 mvalue = mutex->value;
1187 mtype = (mvalue & MUTEX_TYPE_MASK);
1188 shared = (mvalue & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001189
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001190 /* Handle normal case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001191 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) ) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001192 _normal_lock(mutex, shared);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001193 return 0;
1194 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001195
1196 /* Do we already own this recursive or error-check mutex ? */
1197 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001198 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001199 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001200
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001201 /* Add in shared state to avoid extra 'or' operations below */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001202 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001203
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001204 /* First, if the mutex is unlocked, try to quickly acquire it.
1205 * In the optimistic case where this works, set the state to 1 to
1206 * indicate locked with no contention */
1207 if (mvalue == mtype) {
1208 int newval = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1209 if (__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0) {
1210 ANDROID_MEMBAR_FULL();
1211 return 0;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001212 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001213 /* argh, the value changed, reload before entering the loop */
1214 mvalue = mutex->value;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001215 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001216
1217 for (;;) {
1218 int newval;
1219
1220 /* if the mutex is unlocked, its value should be 'mtype' and
1221 * we try to acquire it by setting its owner and state atomically.
1222 * NOTE: We put the state to 2 since we _know_ there is contention
1223 * when we are in this loop. This ensures all waiters will be
1224 * unlocked.
1225 */
1226 if (mvalue == mtype) {
1227 newval = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1228 /* TODO: Change this to __bionic_cmpxchg_acquire when we
1229 * implement it to get rid of the explicit memory
1230 * barrier below.
1231 */
1232 if (__unlikely(__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0)) {
1233 mvalue = mutex->value;
1234 continue;
1235 }
1236 ANDROID_MEMBAR_FULL();
1237 return 0;
1238 }
1239
1240 /* the mutex is already locked by another thread, if its state is 1
1241 * we will change it to 2 to indicate contention. */
1242 if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(mvalue)) {
1243 newval = MUTEX_STATE_BITS_FLIP_CONTENTION(mvalue); /* locked state 1 => state 2 */
1244 if (__unlikely(__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0)) {
1245 mvalue = mutex->value;
1246 continue;
1247 }
1248 mvalue = newval;
1249 }
1250
1251 /* wait until the mutex is unlocked */
1252 __futex_wait_ex(&mutex->value, shared, mvalue, NULL);
1253
1254 mvalue = mutex->value;
1255 }
1256 /* NOTREACHED */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001257}
1258
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001259int pthread_mutex_lock(pthread_mutex_t *mutex)
1260{
1261 int err = pthread_mutex_lock_impl(mutex);
1262#ifdef PTHREAD_DEBUG
1263 if (PTHREAD_DEBUG_ENABLED) {
1264 if (!err) {
1265 pthread_debug_mutex_lock_check(mutex);
1266 }
1267 }
1268#endif
1269 return err;
1270}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001271
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001272__LIBC_HIDDEN__
1273int pthread_mutex_unlock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001274{
Wink Savillea12c5442013-01-08 15:15:45 -08001275 int mvalue, mtype, tid, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001276
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001277 if (__unlikely(mutex == NULL))
1278 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001279
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001280 mvalue = mutex->value;
1281 mtype = (mvalue & MUTEX_TYPE_MASK);
1282 shared = (mvalue & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001283
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001284 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001285 if (__likely(mtype == MUTEX_TYPE_BITS_NORMAL)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001286 _normal_unlock(mutex, shared);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001287 return 0;
1288 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001289
1290 /* Do we already own this recursive or error-check mutex ? */
1291 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001292 if ( tid != MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001293 return EPERM;
1294
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001295 /* If the counter is > 0, we can simply decrement it atomically.
1296 * Since other threads can mutate the lower state bits (and only the
1297 * lower state bits), use a cmpxchg to do it.
1298 */
1299 if (!MUTEX_COUNTER_BITS_IS_ZERO(mvalue)) {
1300 for (;;) {
1301 int newval = mvalue - MUTEX_COUNTER_BITS_ONE;
1302 if (__likely(__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0)) {
1303 /* success: we still own the mutex, so no memory barrier */
1304 return 0;
1305 }
1306 /* the value changed, so reload and loop */
1307 mvalue = mutex->value;
1308 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001309 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001310
1311 /* the counter is 0, so we're going to unlock the mutex by resetting
1312 * its value to 'unlocked'. We need to perform a swap in order
1313 * to read the current state, which will be 2 if there are waiters
1314 * to awake.
1315 *
1316 * TODO: Change this to __bionic_swap_release when we implement it
1317 * to get rid of the explicit memory barrier below.
1318 */
1319 ANDROID_MEMBAR_FULL(); /* RELEASE BARRIER */
1320 mvalue = __bionic_swap(mtype | shared | MUTEX_STATE_BITS_UNLOCKED, &mutex->value);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001321
1322 /* Wake one waiting thread, if any */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001323 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(mvalue)) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001324 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001325 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001326 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001327}
1328
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001329int pthread_mutex_unlock(pthread_mutex_t *mutex)
1330{
1331#ifdef PTHREAD_DEBUG
1332 if (PTHREAD_DEBUG_ENABLED) {
1333 pthread_debug_mutex_unlock_check(mutex);
1334 }
1335#endif
1336 return pthread_mutex_unlock_impl(mutex);
1337}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001338
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001339__LIBC_HIDDEN__
1340int pthread_mutex_trylock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001341{
Wink Savillea12c5442013-01-08 15:15:45 -08001342 int mvalue, mtype, tid, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001343
1344 if (__unlikely(mutex == NULL))
1345 return EINVAL;
1346
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001347 mvalue = mutex->value;
1348 mtype = (mvalue & MUTEX_TYPE_MASK);
1349 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001350
1351 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001352 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001353 {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001354 if (__bionic_cmpxchg(shared|MUTEX_STATE_BITS_UNLOCKED,
1355 shared|MUTEX_STATE_BITS_LOCKED_UNCONTENDED,
1356 &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001357 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001358 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001359 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001360
1361 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001362 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001363
1364 /* Do we already own this recursive or error-check mutex ? */
1365 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001366 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001367 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001368
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001369 /* Same as pthread_mutex_lock, except that we don't want to wait, and
1370 * the only operation that can succeed is a single cmpxchg to acquire the
1371 * lock if it is released / not owned by anyone. No need for a complex loop.
1372 */
1373 mtype |= shared | MUTEX_STATE_BITS_UNLOCKED;
1374 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001375
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001376 if (__likely(__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0)) {
1377 ANDROID_MEMBAR_FULL();
1378 return 0;
1379 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001380
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001381 return EBUSY;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001382}
1383
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001384int pthread_mutex_trylock(pthread_mutex_t *mutex)
1385{
1386 int err = pthread_mutex_trylock_impl(mutex);
1387#ifdef PTHREAD_DEBUG
1388 if (PTHREAD_DEBUG_ENABLED) {
1389 if (!err) {
1390 pthread_debug_mutex_lock_check(mutex);
1391 }
1392 }
1393#endif
1394 return err;
1395}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001396
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001397/* initialize 'ts' with the difference between 'abstime' and the current time
1398 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
1399 */
1400static int
1401__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
1402{
1403 clock_gettime(clock, ts);
1404 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
1405 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
1406 if (ts->tv_nsec < 0) {
1407 ts->tv_sec--;
1408 ts->tv_nsec += 1000000000;
1409 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001410 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001411 return -1;
1412
1413 return 0;
1414}
1415
1416/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1417 * milliseconds.
1418 */
1419static void
1420__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1421{
1422 clock_gettime(clock, abstime);
1423 abstime->tv_sec += msecs/1000;
1424 abstime->tv_nsec += (msecs%1000)*1000000;
1425 if (abstime->tv_nsec >= 1000000000) {
1426 abstime->tv_sec++;
1427 abstime->tv_nsec -= 1000000000;
1428 }
1429}
1430
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001431__LIBC_HIDDEN__
1432int pthread_mutex_lock_timeout_np_impl(pthread_mutex_t *mutex, unsigned msecs)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001433{
1434 clockid_t clock = CLOCK_MONOTONIC;
1435 struct timespec abstime;
1436 struct timespec ts;
Wink Savillea12c5442013-01-08 15:15:45 -08001437 int mvalue, mtype, tid, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001438
1439 /* compute absolute expiration time */
1440 __timespec_to_relative_msec(&abstime, msecs, clock);
1441
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001442 if (__unlikely(mutex == NULL))
1443 return EINVAL;
1444
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001445 mvalue = mutex->value;
1446 mtype = (mvalue & MUTEX_TYPE_MASK);
1447 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001448
1449 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001450 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001451 {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001452 const int unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
1453 const int locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1454 const int locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1455
1456 /* fast path for uncontended lock. Note: MUTEX_TYPE_BITS_NORMAL is 0 */
1457 if (__bionic_cmpxchg(unlocked, locked_uncontended, &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001458 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001459 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001460 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001461
1462 /* loop while needed */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001463 while (__bionic_swap(locked_contended, &mutex->value) != unlocked) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001464 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1465 return EBUSY;
1466
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001467 __futex_wait_ex(&mutex->value, shared, locked_contended, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001468 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001469 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001470 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001471 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001472
1473 /* Do we already own this recursive or error-check mutex ? */
1474 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001475 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001476 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001477
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001478 /* the following implements the same loop than pthread_mutex_lock_impl
1479 * but adds checks to ensure that the operation never exceeds the
1480 * absolute expiration time.
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001481 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001482 mtype |= shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001483
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001484 /* first try a quick lock */
1485 if (mvalue == mtype) {
1486 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1487 if (__likely(__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0)) {
1488 ANDROID_MEMBAR_FULL();
1489 return 0;
1490 }
1491 mvalue = mutex->value;
1492 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001493
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001494 for (;;) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001495 struct timespec ts;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001496
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001497 /* if the value is 'unlocked', try to acquire it directly */
1498 /* NOTE: put state to 2 since we know there is contention */
1499 if (mvalue == mtype) /* unlocked */ {
1500 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1501 if (__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0) {
1502 ANDROID_MEMBAR_FULL();
1503 return 0;
1504 }
1505 /* the value changed before we could lock it. We need to check
1506 * the time to avoid livelocks, reload the value, then loop again. */
1507 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1508 return EBUSY;
1509
1510 mvalue = mutex->value;
1511 continue;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001512 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001513
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001514 /* The value is locked. If 'uncontended', try to switch its state
1515 * to 'contented' to ensure we get woken up later. */
1516 if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(mvalue)) {
1517 int newval = MUTEX_STATE_BITS_FLIP_CONTENTION(mvalue);
1518 if (__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0) {
1519 /* this failed because the value changed, reload it */
1520 mvalue = mutex->value;
1521 } else {
1522 /* this succeeded, update mvalue */
1523 mvalue = newval;
1524 }
1525 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001526
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001527 /* check time and update 'ts' */
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001528 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1529 return EBUSY;
1530
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001531 /* Only wait to be woken up if the state is '2', otherwise we'll
1532 * simply loop right now. This can happen when the second cmpxchg
1533 * in our loop failed because the mutex was unlocked by another
1534 * thread.
1535 */
1536 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(mvalue)) {
1537 if (__futex_wait_ex(&mutex->value, shared, mvalue, &ts) == ETIMEDOUT) {
1538 return EBUSY;
1539 }
1540 mvalue = mutex->value;
1541 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001542 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001543 /* NOTREACHED */
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001544}
1545
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001546int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1547{
1548 int err = pthread_mutex_lock_timeout_np_impl(mutex, msecs);
1549#ifdef PTHREAD_DEBUG
1550 if (PTHREAD_DEBUG_ENABLED) {
1551 if (!err) {
1552 pthread_debug_mutex_lock_check(mutex);
1553 }
1554 }
1555#endif
1556 return err;
1557}
1558
1559int pthread_mutex_destroy(pthread_mutex_t *mutex)
1560{
1561 int ret;
1562
1563 /* use trylock to ensure that the mutex value is
1564 * valid and is not already locked. */
1565 ret = pthread_mutex_trylock_impl(mutex);
1566 if (ret != 0)
1567 return ret;
1568
1569 mutex->value = 0xdead10cc;
1570 return 0;
1571}
1572
1573
1574
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001575int pthread_condattr_init(pthread_condattr_t *attr)
1576{
1577 if (attr == NULL)
1578 return EINVAL;
1579
1580 *attr = PTHREAD_PROCESS_PRIVATE;
1581 return 0;
1582}
1583
1584int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1585{
1586 if (attr == NULL || pshared == NULL)
1587 return EINVAL;
1588
1589 *pshared = *attr;
1590 return 0;
1591}
1592
1593int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1594{
1595 if (attr == NULL)
1596 return EINVAL;
1597
1598 if (pshared != PTHREAD_PROCESS_SHARED &&
1599 pshared != PTHREAD_PROCESS_PRIVATE)
1600 return EINVAL;
1601
1602 *attr = pshared;
1603 return 0;
1604}
1605
1606int pthread_condattr_destroy(pthread_condattr_t *attr)
1607{
1608 if (attr == NULL)
1609 return EINVAL;
1610
1611 *attr = 0xdeada11d;
1612 return 0;
1613}
1614
1615/* We use one bit in condition variable values as the 'shared' flag
1616 * The rest is a counter.
1617 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001618#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001619#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001620#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1621
1622#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001623
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001624/* XXX *technically* there is a race condition that could allow
1625 * XXX a signal to be missed. If thread A is preempted in _wait()
1626 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001627 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001628 * XXX before thread A is scheduled again and calls futex_wait(),
1629 * XXX then the signal will be lost.
1630 */
1631
1632int pthread_cond_init(pthread_cond_t *cond,
1633 const pthread_condattr_t *attr)
1634{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001635 if (cond == NULL)
1636 return EINVAL;
1637
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001638 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001639
1640 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001641 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001642
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001643 return 0;
1644}
1645
1646int pthread_cond_destroy(pthread_cond_t *cond)
1647{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001648 if (cond == NULL)
1649 return EINVAL;
1650
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001651 cond->value = 0xdeadc04d;
1652 return 0;
1653}
1654
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001655/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001656 * pthread_cond_signal to atomically decrement the counter
1657 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001658 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001659static int
1660__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001661{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001662 long flags;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001663
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001664 if (__unlikely(cond == NULL))
1665 return EINVAL;
1666
1667 flags = (cond->value & ~COND_COUNTER_MASK);
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001668 for (;;) {
1669 long oldval = cond->value;
1670 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1671 | flags;
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001672 if (__bionic_cmpxchg(oldval, newval, &cond->value) == 0)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001673 break;
1674 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001675
Andy McFaddene2ac8982010-09-02 13:34:53 -07001676 /*
1677 * Ensure that all memory accesses previously made by this thread are
1678 * visible to the woken thread(s). On the other side, the "wait"
1679 * code will issue any necessary barriers when locking the mutex.
1680 *
1681 * This may not strictly be necessary -- if the caller follows
1682 * recommended practice and holds the mutex before signaling the cond
1683 * var, the mutex ops will provide correct semantics. If they don't
1684 * hold the mutex, they're subject to race conditions anyway.
1685 */
1686 ANDROID_MEMBAR_FULL();
1687
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001688 __futex_wake_ex(&cond->value, COND_IS_SHARED(cond), counter);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001689 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001690}
1691
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001692int pthread_cond_broadcast(pthread_cond_t *cond)
1693{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001694 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001695}
1696
1697int pthread_cond_signal(pthread_cond_t *cond)
1698{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001699 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001700}
1701
1702int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1703{
1704 return pthread_cond_timedwait(cond, mutex, NULL);
1705}
1706
1707int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1708 pthread_mutex_t * mutex,
1709 const struct timespec *reltime)
1710{
1711 int status;
1712 int oldvalue = cond->value;
1713
1714 pthread_mutex_unlock(mutex);
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001715 status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond), oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001716 pthread_mutex_lock(mutex);
1717
1718 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1719 return 0;
1720}
1721
1722int __pthread_cond_timedwait(pthread_cond_t *cond,
1723 pthread_mutex_t * mutex,
1724 const struct timespec *abstime,
1725 clockid_t clock)
1726{
1727 struct timespec ts;
1728 struct timespec * tsp;
1729
1730 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001731 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001732 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001733 tsp = &ts;
1734 } else {
1735 tsp = NULL;
1736 }
1737
1738 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1739}
1740
1741int pthread_cond_timedwait(pthread_cond_t *cond,
1742 pthread_mutex_t * mutex,
1743 const struct timespec *abstime)
1744{
1745 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1746}
1747
1748
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001749/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001750int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1751 pthread_mutex_t * mutex,
1752 const struct timespec *abstime)
1753{
1754 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1755}
1756
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001757int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1758 pthread_mutex_t * mutex,
1759 const struct timespec *abstime)
1760{
1761 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1762}
1763
1764int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1765 pthread_mutex_t * mutex,
1766 const struct timespec *reltime)
1767{
1768 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1769}
1770
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001771int pthread_cond_timeout_np(pthread_cond_t *cond,
1772 pthread_mutex_t * mutex,
1773 unsigned msecs)
1774{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001775 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001776
1777 ts.tv_sec = msecs / 1000;
1778 ts.tv_nsec = (msecs % 1000) * 1000000;
1779
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001780 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001781}
1782
1783
1784
1785/* A technical note regarding our thread-local-storage (TLS) implementation:
1786 *
1787 * There can be up to TLSMAP_SIZE independent TLS keys in a given process,
1788 * though the first TLSMAP_START keys are reserved for Bionic to hold
1789 * special thread-specific variables like errno or a pointer to
1790 * the current thread's descriptor.
1791 *
1792 * while stored in the TLS area, these entries cannot be accessed through
1793 * pthread_getspecific() / pthread_setspecific() and pthread_key_delete()
1794 *
1795 * also, some entries in the key table are pre-allocated (see tlsmap_lock)
1796 * to greatly simplify and speedup some OpenGL-related operations. though the
1797 * initialy value will be NULL on all threads.
1798 *
1799 * you can use pthread_getspecific()/setspecific() on these, and in theory
1800 * you could also call pthread_key_delete() as well, though this would
1801 * probably break some apps.
1802 *
1803 * The 'tlsmap_t' type defined below implements a shared global map of
1804 * currently created/allocated TLS keys and the destructors associated
1805 * with them. You should use tlsmap_lock/unlock to access it to avoid
1806 * any race condition.
1807 *
1808 * the global TLS map simply contains a bitmap of allocated keys, and
1809 * an array of destructors.
1810 *
1811 * each thread has a TLS area that is a simple array of TLSMAP_SIZE void*
1812 * pointers. the TLS area of the main thread is stack-allocated in
1813 * __libc_init_common, while the TLS area of other threads is placed at
1814 * the top of their stack in pthread_create.
1815 *
1816 * when pthread_key_create() is called, it finds the first free key in the
1817 * bitmap, then set it to 1, saving the destructor altogether
1818 *
1819 * when pthread_key_delete() is called. it will erase the key's bitmap bit
1820 * and its destructor, and will also clear the key data in the TLS area of
1821 * all created threads. As mandated by Posix, it is the responsability of
1822 * the caller of pthread_key_delete() to properly reclaim the objects that
1823 * were pointed to by these data fields (either before or after the call).
1824 *
1825 */
1826
1827/* TLS Map implementation
1828 */
1829
1830#define TLSMAP_START (TLS_SLOT_MAX_WELL_KNOWN+1)
1831#define TLSMAP_SIZE BIONIC_TLS_SLOTS
1832#define TLSMAP_BITS 32
1833#define TLSMAP_WORDS ((TLSMAP_SIZE+TLSMAP_BITS-1)/TLSMAP_BITS)
1834#define TLSMAP_WORD(m,k) (m)->map[(k)/TLSMAP_BITS]
1835#define TLSMAP_MASK(k) (1U << ((k)&(TLSMAP_BITS-1)))
1836
1837/* this macro is used to quickly check that a key belongs to a reasonable range */
1838#define TLSMAP_VALIDATE_KEY(key) \
1839 ((key) >= TLSMAP_START && (key) < TLSMAP_SIZE)
1840
1841/* the type of tls key destructor functions */
1842typedef void (*tls_dtor_t)(void*);
1843
1844typedef struct {
1845 int init; /* see comment in tlsmap_lock() */
1846 uint32_t map[TLSMAP_WORDS]; /* bitmap of allocated keys */
1847 tls_dtor_t dtors[TLSMAP_SIZE]; /* key destructors */
1848} tlsmap_t;
1849
1850static pthread_mutex_t _tlsmap_lock = PTHREAD_MUTEX_INITIALIZER;
1851static tlsmap_t _tlsmap;
1852
1853/* lock the global TLS map lock and return a handle to it */
1854static __inline__ tlsmap_t* tlsmap_lock(void)
1855{
1856 tlsmap_t* m = &_tlsmap;
1857
1858 pthread_mutex_lock(&_tlsmap_lock);
1859 /* we need to initialize the first entry of the 'map' array
1860 * with the value TLS_DEFAULT_ALLOC_MAP. doing it statically
1861 * when declaring _tlsmap is a bit awkward and is going to
1862 * produce warnings, so do it the first time we use the map
1863 * instead
1864 */
1865 if (__unlikely(!m->init)) {
1866 TLSMAP_WORD(m,0) = TLS_DEFAULT_ALLOC_MAP;
1867 m->init = 1;
1868 }
1869 return m;
1870}
1871
1872/* unlock the global TLS map */
1873static __inline__ void tlsmap_unlock(tlsmap_t* m)
1874{
1875 pthread_mutex_unlock(&_tlsmap_lock);
1876 (void)m; /* a good compiler is a happy compiler */
1877}
1878
1879/* test to see wether a key is allocated */
1880static __inline__ int tlsmap_test(tlsmap_t* m, int key)
1881{
1882 return (TLSMAP_WORD(m,key) & TLSMAP_MASK(key)) != 0;
1883}
1884
1885/* set the destructor and bit flag on a newly allocated key */
1886static __inline__ void tlsmap_set(tlsmap_t* m, int key, tls_dtor_t dtor)
1887{
1888 TLSMAP_WORD(m,key) |= TLSMAP_MASK(key);
1889 m->dtors[key] = dtor;
1890}
1891
1892/* clear the destructor and bit flag on an existing key */
1893static __inline__ void tlsmap_clear(tlsmap_t* m, int key)
1894{
1895 TLSMAP_WORD(m,key) &= ~TLSMAP_MASK(key);
1896 m->dtors[key] = NULL;
1897}
1898
1899/* allocate a new TLS key, return -1 if no room left */
1900static int tlsmap_alloc(tlsmap_t* m, tls_dtor_t dtor)
1901{
1902 int key;
1903
1904 for ( key = TLSMAP_START; key < TLSMAP_SIZE; key++ ) {
1905 if ( !tlsmap_test(m, key) ) {
1906 tlsmap_set(m, key, dtor);
1907 return key;
1908 }
1909 }
1910 return -1;
1911}
1912
1913
1914int pthread_key_create(pthread_key_t *key, void (*destructor_function)(void *))
1915{
1916 uint32_t err = ENOMEM;
1917 tlsmap_t* map = tlsmap_lock();
1918 int k = tlsmap_alloc(map, destructor_function);
1919
1920 if (k >= 0) {
1921 *key = k;
1922 err = 0;
1923 }
1924 tlsmap_unlock(map);
1925 return err;
1926}
1927
1928
1929/* This deletes a pthread_key_t. note that the standard mandates that this does
1930 * not call the destructor of non-NULL key values. Instead, it is the
Elliott Hughesbfeab1b2012-09-05 17:47:37 -07001931 * responsibility of the caller to properly dispose of the corresponding data
1932 * and resources, using any means it finds suitable.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001933 *
1934 * On the other hand, this function will clear the corresponding key data
1935 * values in all known threads. this prevents later (invalid) calls to
1936 * pthread_getspecific() to receive invalid/stale values.
1937 */
1938int pthread_key_delete(pthread_key_t key)
1939{
1940 uint32_t err;
1941 pthread_internal_t* thr;
1942 tlsmap_t* map;
1943
1944 if (!TLSMAP_VALIDATE_KEY(key)) {
1945 return EINVAL;
1946 }
1947
1948 map = tlsmap_lock();
1949
1950 if (!tlsmap_test(map, key)) {
1951 err = EINVAL;
1952 goto err1;
1953 }
1954
1955 /* clear value in all threads */
1956 pthread_mutex_lock(&gThreadListLock);
1957 for ( thr = gThreadList; thr != NULL; thr = thr->next ) {
1958 /* avoid zombie threads with a negative 'join_count'. these are really
1959 * already dead and don't have a TLS area anymore.
1960 *
1961 * similarly, it is possible to have thr->tls == NULL for threads that
1962 * were just recently created through pthread_create() but whose
1963 * startup trampoline (__thread_entry) hasn't been run yet by the
Bjorn Andersson0753dc62012-05-03 17:12:39 -07001964 * scheduler. thr->tls will also be NULL after it's stack has been
1965 * unmapped but before the ongoing pthread_join() is finished.
1966 * so check for this too.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001967 */
1968 if (thr->join_count < 0 || !thr->tls)
1969 continue;
1970
1971 thr->tls[key] = NULL;
1972 }
1973 tlsmap_clear(map, key);
1974
1975 pthread_mutex_unlock(&gThreadListLock);
1976 err = 0;
1977
1978err1:
1979 tlsmap_unlock(map);
1980 return err;
1981}
1982
1983
1984int pthread_setspecific(pthread_key_t key, const void *ptr)
1985{
1986 int err = EINVAL;
1987 tlsmap_t* map;
1988
1989 if (TLSMAP_VALIDATE_KEY(key)) {
1990 /* check that we're trying to set data for an allocated key */
1991 map = tlsmap_lock();
1992 if (tlsmap_test(map, key)) {
1993 ((uint32_t *)__get_tls())[key] = (uint32_t)ptr;
1994 err = 0;
1995 }
1996 tlsmap_unlock(map);
1997 }
1998 return err;
1999}
2000
2001void * pthread_getspecific(pthread_key_t key)
2002{
2003 if (!TLSMAP_VALIDATE_KEY(key)) {
2004 return NULL;
2005 }
2006
2007 /* for performance reason, we do not lock/unlock the global TLS map
2008 * to check that the key is properly allocated. if the key was not
2009 * allocated, the value read from the TLS should always be NULL
2010 * due to pthread_key_delete() clearing the values for all threads.
2011 */
2012 return (void *)(((unsigned *)__get_tls())[key]);
2013}
2014
2015/* Posix mandates that this be defined in <limits.h> but we don't have
2016 * it just yet.
2017 */
2018#ifndef PTHREAD_DESTRUCTOR_ITERATIONS
2019# define PTHREAD_DESTRUCTOR_ITERATIONS 4
2020#endif
2021
2022/* this function is called from pthread_exit() to remove all TLS key data
2023 * from this thread's TLS area. this must call the destructor of all keys
2024 * that have a non-NULL data value (and a non-NULL destructor).
2025 *
2026 * because destructors can do funky things like deleting/creating other
2027 * keys, we need to implement this in a loop
2028 */
2029static void pthread_key_clean_all(void)
2030{
2031 tlsmap_t* map;
2032 void** tls = (void**)__get_tls();
2033 int rounds = PTHREAD_DESTRUCTOR_ITERATIONS;
2034
2035 map = tlsmap_lock();
2036
2037 for (rounds = PTHREAD_DESTRUCTOR_ITERATIONS; rounds > 0; rounds--)
2038 {
2039 int kk, count = 0;
2040
2041 for (kk = TLSMAP_START; kk < TLSMAP_SIZE; kk++) {
2042 if ( tlsmap_test(map, kk) )
2043 {
2044 void* data = tls[kk];
2045 tls_dtor_t dtor = map->dtors[kk];
2046
2047 if (data != NULL && dtor != NULL)
2048 {
2049 /* we need to clear the key data now, this will prevent the
2050 * destructor (or a later one) from seeing the old value if
2051 * it calls pthread_getspecific() for some odd reason
2052 *
2053 * we do not do this if 'dtor == NULL' just in case another
2054 * destructor function might be responsible for manually
2055 * releasing the corresponding data.
2056 */
2057 tls[kk] = NULL;
2058
2059 /* because the destructor is free to call pthread_key_create
2060 * and/or pthread_key_delete, we need to temporarily unlock
2061 * the TLS map
2062 */
2063 tlsmap_unlock(map);
2064 (*dtor)(data);
2065 map = tlsmap_lock();
2066
2067 count += 1;
2068 }
2069 }
2070 }
2071
2072 /* if we didn't call any destructor, there is no need to check the
2073 * TLS data again
2074 */
2075 if (count == 0)
2076 break;
2077 }
2078 tlsmap_unlock(map);
2079}
2080
2081// man says this should be in <linux/unistd.h>, but it isn't
Jeff Brown10c8ce52011-11-18 15:17:07 -08002082extern int tgkill(int tgid, int tid, int sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002083
2084int pthread_kill(pthread_t tid, int sig)
2085{
2086 int ret;
2087 int old_errno = errno;
2088 pthread_internal_t * thread = (pthread_internal_t *)tid;
2089
Jeff Brown10c8ce52011-11-18 15:17:07 -08002090 ret = tgkill(getpid(), thread->kernel_id, sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002091 if (ret < 0) {
2092 ret = errno;
2093 errno = old_errno;
2094 }
2095
2096 return ret;
2097}
2098
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002099
2100int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
2101{
2102 const int CLOCK_IDTYPE_BITS = 3;
2103 pthread_internal_t* thread = (pthread_internal_t*)tid;
2104
2105 if (!thread)
2106 return ESRCH;
2107
2108 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
2109 return 0;
2110}
2111
2112
2113/* NOTE: this implementation doesn't support a init function that throws a C++ exception
2114 * or calls fork()
2115 */
2116int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
2117{
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07002118 volatile pthread_once_t* ocptr = once_control;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002119
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002120 /* PTHREAD_ONCE_INIT is 0, we use the following bit flags
2121 *
2122 * bit 0 set -> initialization is under way
2123 * bit 1 set -> initialization is complete
2124 */
2125#define ONCE_INITIALIZING (1 << 0)
2126#define ONCE_COMPLETED (1 << 1)
2127
2128 /* First check if the once is already initialized. This will be the common
2129 * case and we want to make this as fast as possible. Note that this still
2130 * requires a load_acquire operation here to ensure that all the
2131 * stores performed by the initialization function are observable on
2132 * this CPU after we exit.
2133 */
2134 if (__likely((*ocptr & ONCE_COMPLETED) != 0)) {
2135 ANDROID_MEMBAR_FULL();
2136 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002137 }
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002138
2139 for (;;) {
2140 /* Try to atomically set the INITIALIZING flag.
2141 * This requires a cmpxchg loop, and we may need
Elliott Hughesbfeab1b2012-09-05 17:47:37 -07002142 * to exit prematurely if we detect that
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002143 * COMPLETED is now set.
2144 */
2145 int32_t oldval, newval;
2146
2147 do {
2148 oldval = *ocptr;
2149 if ((oldval & ONCE_COMPLETED) != 0)
2150 break;
2151
2152 newval = oldval | ONCE_INITIALIZING;
2153 } while (__bionic_cmpxchg(oldval, newval, ocptr) != 0);
2154
2155 if ((oldval & ONCE_COMPLETED) != 0) {
2156 /* We detected that COMPLETED was set while in our loop */
2157 ANDROID_MEMBAR_FULL();
2158 return 0;
2159 }
2160
2161 if ((oldval & ONCE_INITIALIZING) == 0) {
2162 /* We got there first, we can jump out of the loop to
2163 * handle the initialization */
2164 break;
2165 }
2166
2167 /* Another thread is running the initialization and hasn't completed
2168 * yet, so wait for it, then try again. */
2169 __futex_wait_ex(ocptr, 0, oldval, NULL);
2170 }
2171
2172 /* call the initialization function. */
2173 (*init_routine)();
2174
2175 /* Do a store_release indicating that initialization is complete */
2176 ANDROID_MEMBAR_FULL();
2177 *ocptr = ONCE_COMPLETED;
2178
2179 /* Wake up any waiters, if any */
2180 __futex_wake_ex(ocptr, 0, INT_MAX);
2181
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002182 return 0;
2183}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03002184
2185/* This value is not exported by kernel headers, so hardcode it here */
2186#define MAX_TASK_COMM_LEN 16
2187#define TASK_COMM_FMT "/proc/self/task/%u/comm"
2188
2189int pthread_setname_np(pthread_t thid, const char *thname)
2190{
2191 size_t thname_len;
2192 int saved_errno, ret;
2193
2194 if (thid == 0 || thname == NULL)
2195 return EINVAL;
2196
2197 thname_len = strlen(thname);
2198 if (thname_len >= MAX_TASK_COMM_LEN)
2199 return ERANGE;
2200
2201 saved_errno = errno;
2202 if (thid == pthread_self())
2203 {
2204 ret = prctl(PR_SET_NAME, (unsigned long)thname, 0, 0, 0) ? errno : 0;
2205 }
2206 else
2207 {
2208 /* Have to change another thread's name */
2209 pthread_internal_t *thread = (pthread_internal_t *)thid;
2210 char comm_name[sizeof(TASK_COMM_FMT) + 8];
2211 ssize_t n;
2212 int fd;
2213
2214 snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, (unsigned int)thread->kernel_id);
2215 fd = open(comm_name, O_RDWR);
2216 if (fd == -1)
2217 {
2218 ret = errno;
2219 goto exit;
2220 }
2221 n = TEMP_FAILURE_RETRY(write(fd, thname, thname_len));
2222 close(fd);
2223
2224 if (n < 0)
2225 ret = errno;
2226 else if ((size_t)n != thname_len)
2227 ret = EIO;
2228 else
2229 ret = 0;
2230 }
2231exit:
2232 errno = saved_errno;
2233 return ret;
2234}
Glenn Kastend53cae02011-07-11 15:41:28 -07002235
2236/* Return the kernel thread ID for a pthread.
2237 * This is only defined for implementations where pthread <-> kernel is 1:1, which this is.
2238 * Not the same as pthread_getthreadid_np, which is commonly defined to be opaque.
2239 * Internal, not an NDK API.
2240 */
2241
2242pid_t __pthread_gettid(pthread_t thid)
2243{
2244 pthread_internal_t* thread = (pthread_internal_t*)thid;
2245 return thread->kernel_id;
2246}
Jean-Baptiste Querufaca92f2012-03-26 15:25:19 -07002247
2248int __pthread_settid(pthread_t thid, pid_t tid)
2249{
2250 if (thid == 0)
2251 return EINVAL;
2252
2253 pthread_internal_t* thread = (pthread_internal_t*)thid;
2254 thread->kernel_id = tid;
2255
2256 return 0;
2257}