blob: 40a09ba6e4c325f607aa1c09efd2f24f199cfb06 [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"
51#include "bionic_tls.h"
52#include "pthread_internal.h"
53#include "thread_private.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080054
Mathias Agopian7c0c3792011-09-05 23:54:55 -070055extern void pthread_debug_mutex_lock_check(pthread_mutex_t *mutex);
56extern void pthread_debug_mutex_unlock_check(pthread_mutex_t *mutex);
57
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080058extern int __pthread_clone(int (*fn)(void*), void *child_stack, int flags, void *arg);
59extern void _exit_with_stack_teardown(void * stackBase, int stackSize, int retCode);
60extern void _exit_thread(int retCode);
61extern int __set_errno(int);
62
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -070063int __futex_wake_ex(volatile void *ftx, int pshared, int val)
64{
65 return __futex_syscall3(ftx, pshared ? FUTEX_WAKE : FUTEX_WAKE_PRIVATE, val);
66}
67
68int __futex_wait_ex(volatile void *ftx, int pshared, int val, const struct timespec *timeout)
69{
70 return __futex_syscall4(ftx, pshared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE, val, timeout);
71}
72
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -070073#define __likely(cond) __builtin_expect(!!(cond), 1)
74#define __unlikely(cond) __builtin_expect(!!(cond), 0)
75
Bruce Beare8e551a62011-03-28 09:47:35 -070076#ifdef __i386__
77#define ATTRIBUTES __attribute__((noinline)) __attribute__((fastcall))
78#else
79#define ATTRIBUTES __attribute__((noinline))
80#endif
81
82void ATTRIBUTES _thread_created_hook(pid_t thread_id);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080083
Pierre Peifferd0c884d2012-02-22 16:40:15 +010084static const int kPthreadInitFailed = 1;
85
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080086#define PTHREAD_ATTR_FLAG_DETACHED 0x00000001
87#define PTHREAD_ATTR_FLAG_USER_STACK 0x00000002
88
89#define DEFAULT_STACKSIZE (1024 * 1024)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080090
91static pthread_mutex_t mmap_lock = PTHREAD_MUTEX_INITIALIZER;
92
93
94static const pthread_attr_t gDefaultPthreadAttr = {
95 .flags = 0,
96 .stack_base = NULL,
97 .stack_size = DEFAULT_STACKSIZE,
98 .guard_size = PAGE_SIZE,
99 .sched_policy = SCHED_NORMAL,
100 .sched_priority = 0
101};
102
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100103static pthread_internal_t* gThreadList = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800104static pthread_mutex_t gThreadListLock = PTHREAD_MUTEX_INITIALIZER;
105static pthread_mutex_t gDebuggerNotificationLock = PTHREAD_MUTEX_INITIALIZER;
106
107
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800108static void
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100109_pthread_internal_free(pthread_internal_t* thread)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800110{
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100111 if (thread != NULL) {
112 free(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800113 }
114}
115
116
117static void
118_pthread_internal_remove_locked( pthread_internal_t* thread )
119{
120 thread->next->pref = thread->pref;
121 thread->pref[0] = thread->next;
122}
123
124static void
125_pthread_internal_remove( pthread_internal_t* thread )
126{
127 pthread_mutex_lock(&gThreadListLock);
128 _pthread_internal_remove_locked(thread);
129 pthread_mutex_unlock(&gThreadListLock);
130}
131
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +0400132__LIBC_ABI_PRIVATE__ void
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800133_pthread_internal_add( pthread_internal_t* thread )
134{
135 pthread_mutex_lock(&gThreadListLock);
136 thread->pref = &gThreadList;
137 thread->next = thread->pref[0];
138 if (thread->next)
139 thread->next->pref = &thread->next;
140 thread->pref[0] = thread;
141 pthread_mutex_unlock(&gThreadListLock);
142}
143
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +0400144__LIBC_ABI_PRIVATE__ pthread_internal_t*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800145__get_thread(void)
146{
147 void** tls = (void**)__get_tls();
148
149 return (pthread_internal_t*) tls[TLS_SLOT_THREAD_ID];
150}
151
152
153void*
154__get_stack_base(int *p_stack_size)
155{
156 pthread_internal_t* thread = __get_thread();
157
158 *p_stack_size = thread->attr.stack_size;
159 return thread->attr.stack_base;
160}
161
162
163void __init_tls(void** tls, void* thread)
164{
165 int nn;
166
167 ((pthread_internal_t*)thread)->tls = tls;
168
169 // slot 0 must point to the tls area, this is required by the implementation
170 // of the x86 Linux kernel thread-local-storage
171 tls[TLS_SLOT_SELF] = (void*)tls;
172 tls[TLS_SLOT_THREAD_ID] = thread;
173 for (nn = TLS_SLOT_ERRNO; nn < BIONIC_TLS_SLOTS; nn++)
174 tls[nn] = 0;
175
176 __set_tls( (void*)tls );
177}
178
179
180/*
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100181 * This trampoline is called from the assembly _pthread_clone() function.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800182 */
183void __thread_entry(int (*func)(void*), void *arg, void **tls)
184{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800185 // Wait for our creating thread to release us. This lets it have time to
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100186 // notify gdb about this thread before we start doing anything.
Andy McFaddene2ac8982010-09-02 13:34:53 -0700187 //
188 // This also provides the memory barrier needed to ensure that all memory
189 // accesses previously made by the creating thread are visible to us.
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100190 pthread_mutex_t* start_mutex = (pthread_mutex_t*) &tls[TLS_SLOT_SELF];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800191 pthread_mutex_lock(start_mutex);
192 pthread_mutex_destroy(start_mutex);
193
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100194 pthread_internal_t* thread = (pthread_internal_t*) tls[TLS_SLOT_THREAD_ID];
195 __init_tls(tls, thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800196
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100197 if ((thread->internal_flags & kPthreadInitFailed) != 0) {
198 pthread_exit(NULL);
199 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800200
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100201 int result = func(arg);
202 pthread_exit((void*) result);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800203}
204
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +0400205__LIBC_ABI_PRIVATE__
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100206int _init_thread(pthread_internal_t * thread, pid_t kernel_id, pthread_attr_t * attr, void * stack_base)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800207{
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100208 int error = 0;
209
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800210 if (attr == NULL) {
211 thread->attr = gDefaultPthreadAttr;
212 } else {
213 thread->attr = *attr;
214 }
215 thread->attr.stack_base = stack_base;
216 thread->kernel_id = kernel_id;
217
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100218 // Make a note of whether the user supplied this stack (so we know whether or not to free it).
219 if (attr->stack_base == stack_base) {
220 thread->attr.flags |= PTHREAD_ATTR_FLAG_USER_STACK;
221 }
222
223 // Set the scheduling policy/priority of the thread.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800224 if (thread->attr.sched_policy != SCHED_NORMAL) {
225 struct sched_param param;
226 param.sched_priority = thread->attr.sched_priority;
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100227 if (sched_setscheduler(kernel_id, thread->attr.sched_policy, &param) == -1) {
228 error = errno;
229 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800230 }
231
232 pthread_cond_init(&thread->join_cond, NULL);
233 thread->join_count = 0;
234
235 thread->cleanup_stack = NULL;
236
237 _pthread_internal_add(thread);
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100238 return error;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800239}
240
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800241static void *mkstack(size_t size, size_t guard_size)
242{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800243 pthread_mutex_lock(&mmap_lock);
244
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100245 int prot = PROT_READ | PROT_WRITE;
246 int flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE;
Elliott Hughes9c3eca72012-05-08 13:26:28 -0700247 void* stack = mmap(NULL, size, prot, flags, -1, 0);
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100248 if (stack == MAP_FAILED) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800249 stack = NULL;
250 goto done;
251 }
252
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100253 if (mprotect(stack, guard_size, PROT_NONE) == -1) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800254 munmap(stack, size);
255 stack = NULL;
256 goto done;
257 }
258
259done:
260 pthread_mutex_unlock(&mmap_lock);
261 return stack;
262}
263
264/*
Andy McFaddene2ac8982010-09-02 13:34:53 -0700265 * Create a new thread. The thread's stack is laid out like so:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800266 *
267 * +---------------------------+
268 * | pthread_internal_t |
269 * +---------------------------+
270 * | |
271 * | TLS area |
272 * | |
273 * +---------------------------+
274 * | |
275 * . .
276 * . stack area .
277 * . .
278 * | |
279 * +---------------------------+
280 * | guard page |
281 * +---------------------------+
282 *
283 * note that TLS[0] must be a pointer to itself, this is required
284 * by the thread-local storage implementation of the x86 Linux
285 * kernel, where the TLS pointer is read by reading fs:[0]
286 */
287int pthread_create(pthread_t *thread_out, pthread_attr_t const * attr,
288 void *(*start_routine)(void *), void * arg)
289{
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100290 int old_errno = errno;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800291
292 /* this will inform the rest of the C library that at least one thread
293 * was created. this will enforce certain functions to acquire/release
294 * locks (e.g. atexit()) to protect shared global structures.
295 *
296 * this works because pthread_create() is not called by the C library
297 * initialization routine that sets up the main thread's data structures.
298 */
299 __isthreaded = 1;
300
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100301 pthread_internal_t* thread = calloc(sizeof(*thread), 1);
302 if (thread == NULL) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800303 return ENOMEM;
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100304 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800305
306 if (attr == NULL) {
307 attr = &gDefaultPthreadAttr;
308 }
309
310 // make sure the stack is PAGE_SIZE aligned
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100311 size_t stack_size = (attr->stack_size + (PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
312 uint8_t* stack = attr->stack_base;
313 if (stack == NULL) {
314 stack = mkstack(stack_size, attr->guard_size);
315 if (stack == NULL) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800316 _pthread_internal_free(thread);
317 return ENOMEM;
318 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800319 }
320
321 // Make room for TLS
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100322 void** tls = (void**)(stack + stack_size - BIONIC_TLS_SLOTS*sizeof(void*));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800323
324 // Create a mutex for the thread in TLS_SLOT_SELF to wait on once it starts so we can keep
325 // it from doing anything until after we notify the debugger about it
Andy McFaddene2ac8982010-09-02 13:34:53 -0700326 //
327 // This also provides the memory barrier we need to ensure that all
328 // memory accesses previously performed by this thread are visible to
329 // the new thread.
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100330 pthread_mutex_t* start_mutex = (pthread_mutex_t*) &tls[TLS_SLOT_SELF];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800331 pthread_mutex_init(start_mutex, NULL);
332 pthread_mutex_lock(start_mutex);
333
334 tls[TLS_SLOT_THREAD_ID] = thread;
335
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100336 int flags = CLONE_FILES | CLONE_FS | CLONE_VM | CLONE_SIGHAND |
337 CLONE_THREAD | CLONE_SYSVSEM | CLONE_DETACHED;
338 int tid = __pthread_clone((int(*)(void*))start_routine, tls, flags, arg);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800339
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100340 if (tid < 0) {
341 int clone_errno = errno;
342 pthread_mutex_unlock(start_mutex);
343 if (stack != attr->stack_base) {
344 munmap(stack, stack_size);
345 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800346 _pthread_internal_free(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800347 errno = old_errno;
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100348 return clone_errno;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800349 }
350
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100351 int init_errno = _init_thread(thread, tid, (pthread_attr_t*) attr, stack);
352 if (init_errno != 0) {
353 // Mark the thread detached and let its __thread_entry run to
354 // completion. (It'll just exit immediately, cleaning up its resources.)
355 thread->internal_flags |= kPthreadInitFailed;
356 thread->attr.flags |= PTHREAD_ATTR_FLAG_DETACHED;
357 pthread_mutex_unlock(start_mutex);
358 errno = old_errno;
359 return init_errno;
360 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800361
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100362 // Notify any debuggers about the new thread.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800363 pthread_mutex_lock(&gDebuggerNotificationLock);
364 _thread_created_hook(tid);
365 pthread_mutex_unlock(&gDebuggerNotificationLock);
366
Jurijs Oniscuks2932f042012-07-05 14:57:38 +0200367 // Publish the pthread_t and let the thread run.
368 *thread_out = (pthread_t) thread;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800369 pthread_mutex_unlock(start_mutex);
370
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800371 return 0;
372}
373
374
375int pthread_attr_init(pthread_attr_t * attr)
376{
377 *attr = gDefaultPthreadAttr;
378 return 0;
379}
380
381int pthread_attr_destroy(pthread_attr_t * attr)
382{
383 memset(attr, 0x42, sizeof(pthread_attr_t));
384 return 0;
385}
386
387int pthread_attr_setdetachstate(pthread_attr_t * attr, int state)
388{
389 if (state == PTHREAD_CREATE_DETACHED) {
390 attr->flags |= PTHREAD_ATTR_FLAG_DETACHED;
391 } else if (state == PTHREAD_CREATE_JOINABLE) {
392 attr->flags &= ~PTHREAD_ATTR_FLAG_DETACHED;
393 } else {
394 return EINVAL;
395 }
396 return 0;
397}
398
399int pthread_attr_getdetachstate(pthread_attr_t const * attr, int * state)
400{
401 *state = (attr->flags & PTHREAD_ATTR_FLAG_DETACHED)
402 ? PTHREAD_CREATE_DETACHED
403 : PTHREAD_CREATE_JOINABLE;
404 return 0;
405}
406
407int pthread_attr_setschedpolicy(pthread_attr_t * attr, int policy)
408{
409 attr->sched_policy = policy;
410 return 0;
411}
412
413int pthread_attr_getschedpolicy(pthread_attr_t const * attr, int * policy)
414{
415 *policy = attr->sched_policy;
416 return 0;
417}
418
419int pthread_attr_setschedparam(pthread_attr_t * attr, struct sched_param const * param)
420{
421 attr->sched_priority = param->sched_priority;
422 return 0;
423}
424
425int pthread_attr_getschedparam(pthread_attr_t const * attr, struct sched_param * param)
426{
427 param->sched_priority = attr->sched_priority;
428 return 0;
429}
430
431int pthread_attr_setstacksize(pthread_attr_t * attr, size_t stack_size)
432{
433 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
434 return EINVAL;
435 }
436 attr->stack_size = stack_size;
437 return 0;
438}
439
440int pthread_attr_getstacksize(pthread_attr_t const * attr, size_t * stack_size)
441{
442 *stack_size = attr->stack_size;
443 return 0;
444}
445
446int pthread_attr_setstackaddr(pthread_attr_t * attr, void * stack_addr)
447{
448#if 1
449 // It's not clear if this is setting the top or bottom of the stack, so don't handle it for now.
450 return ENOSYS;
451#else
452 if ((uint32_t)stack_addr & (PAGE_SIZE - 1)) {
453 return EINVAL;
454 }
455 attr->stack_base = stack_addr;
456 return 0;
457#endif
458}
459
460int pthread_attr_getstackaddr(pthread_attr_t const * attr, void ** stack_addr)
461{
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700462 *stack_addr = (char*)attr->stack_base + attr->stack_size;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800463 return 0;
464}
465
466int pthread_attr_setstack(pthread_attr_t * attr, void * stack_base, size_t stack_size)
467{
468 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
469 return EINVAL;
470 }
471 if ((uint32_t)stack_base & (PAGE_SIZE - 1)) {
472 return EINVAL;
473 }
474 attr->stack_base = stack_base;
475 attr->stack_size = stack_size;
476 return 0;
477}
478
479int pthread_attr_getstack(pthread_attr_t const * attr, void ** stack_base, size_t * stack_size)
480{
481 *stack_base = attr->stack_base;
482 *stack_size = attr->stack_size;
483 return 0;
484}
485
486int pthread_attr_setguardsize(pthread_attr_t * attr, size_t guard_size)
487{
488 if (guard_size & (PAGE_SIZE - 1) || guard_size < PAGE_SIZE) {
489 return EINVAL;
490 }
491
492 attr->guard_size = guard_size;
493 return 0;
494}
495
496int pthread_attr_getguardsize(pthread_attr_t const * attr, size_t * guard_size)
497{
498 *guard_size = attr->guard_size;
499 return 0;
500}
501
502int pthread_getattr_np(pthread_t thid, pthread_attr_t * attr)
503{
504 pthread_internal_t * thread = (pthread_internal_t *)thid;
505 *attr = thread->attr;
506 return 0;
507}
508
509int pthread_attr_setscope(pthread_attr_t *attr, int scope)
510{
511 if (scope == PTHREAD_SCOPE_SYSTEM)
512 return 0;
513 if (scope == PTHREAD_SCOPE_PROCESS)
514 return ENOTSUP;
515
516 return EINVAL;
517}
518
519int pthread_attr_getscope(pthread_attr_t const *attr)
520{
521 return PTHREAD_SCOPE_SYSTEM;
522}
523
524
525/* CAVEAT: our implementation of pthread_cleanup_push/pop doesn't support C++ exceptions
526 * and thread cancelation
527 */
528
529void __pthread_cleanup_push( __pthread_cleanup_t* c,
530 __pthread_cleanup_func_t routine,
531 void* arg )
532{
533 pthread_internal_t* thread = __get_thread();
534
535 c->__cleanup_routine = routine;
536 c->__cleanup_arg = arg;
537 c->__cleanup_prev = thread->cleanup_stack;
538 thread->cleanup_stack = c;
539}
540
541void __pthread_cleanup_pop( __pthread_cleanup_t* c, int execute )
542{
543 pthread_internal_t* thread = __get_thread();
544
545 thread->cleanup_stack = c->__cleanup_prev;
546 if (execute)
547 c->__cleanup_routine(c->__cleanup_arg);
548}
549
550/* used by pthread_exit() to clean all TLS keys of the current thread */
551static void pthread_key_clean_all(void);
552
553void pthread_exit(void * retval)
554{
555 pthread_internal_t* thread = __get_thread();
556 void* stack_base = thread->attr.stack_base;
557 int stack_size = thread->attr.stack_size;
558 int user_stack = (thread->attr.flags & PTHREAD_ATTR_FLAG_USER_STACK) != 0;
Jack Rene480fc82011-09-21 12:44:11 +0200559 sigset_t mask;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800560
561 // call the cleanup handlers first
562 while (thread->cleanup_stack) {
563 __pthread_cleanup_t* c = thread->cleanup_stack;
564 thread->cleanup_stack = c->__cleanup_prev;
565 c->__cleanup_routine(c->__cleanup_arg);
566 }
567
568 // call the TLS destructors, it is important to do that before removing this
569 // thread from the global list. this will ensure that if someone else deletes
570 // a TLS key, the corresponding value will be set to NULL in this thread's TLS
571 // space (see pthread_key_delete)
572 pthread_key_clean_all();
573
574 // if the thread is detached, destroy the pthread_internal_t
575 // otherwise, keep it in memory and signal any joiners
576 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
577 _pthread_internal_remove(thread);
578 _pthread_internal_free(thread);
579 } else {
Bjorn Andersson0753dc62012-05-03 17:12:39 -0700580 pthread_mutex_lock(&gThreadListLock);
581
582 /* make sure that the thread struct doesn't have stale pointers to a stack that
583 * will be unmapped after the exit call below.
584 */
585 if (!user_stack) {
586 thread->attr.stack_base = NULL;
587 thread->attr.stack_size = 0;
588 thread->tls = NULL;
589 }
590
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800591 /* the join_count field is used to store the number of threads waiting for
592 * the termination of this thread with pthread_join(),
593 *
594 * if it is positive we need to signal the waiters, and we do not touch
595 * the count (it will be decremented by the waiters, the last one will
596 * also remove/free the thread structure
597 *
598 * if it is zero, we set the count value to -1 to indicate that the
599 * thread is in 'zombie' state: it has stopped executing, and its stack
600 * is gone (as well as its TLS area). when another thread calls pthread_join()
601 * on it, it will immediately free the thread and return.
602 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800603 thread->return_value = retval;
604 if (thread->join_count > 0) {
605 pthread_cond_broadcast(&thread->join_cond);
606 } else {
607 thread->join_count = -1; /* zombie thread */
608 }
609 pthread_mutex_unlock(&gThreadListLock);
610 }
611
Jack Rene480fc82011-09-21 12:44:11 +0200612 sigfillset(&mask);
613 sigdelset(&mask, SIGSEGV);
614 (void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *)NULL);
615
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800616 // destroy the thread stack
617 if (user_stack)
618 _exit_thread((int)retval);
619 else
620 _exit_with_stack_teardown(stack_base, stack_size, (int)retval);
621}
622
623int pthread_join(pthread_t thid, void ** ret_val)
624{
625 pthread_internal_t* thread = (pthread_internal_t*)thid;
626 int count;
627
628 // check that the thread still exists and is not detached
629 pthread_mutex_lock(&gThreadListLock);
630
631 for (thread = gThreadList; thread != NULL; thread = thread->next)
632 if (thread == (pthread_internal_t*)thid)
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200633 goto FoundIt;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800634
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200635 pthread_mutex_unlock(&gThreadListLock);
636 return ESRCH;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800637
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200638FoundIt:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800639 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
640 pthread_mutex_unlock(&gThreadListLock);
641 return EINVAL;
642 }
643
644 /* wait for thread death when needed
645 *
646 * if the 'join_count' is negative, this is a 'zombie' thread that
647 * is already dead and without stack/TLS
648 *
649 * otherwise, we need to increment 'join-count' and wait to be signaled
650 */
651 count = thread->join_count;
652 if (count >= 0) {
653 thread->join_count += 1;
654 pthread_cond_wait( &thread->join_cond, &gThreadListLock );
655 count = --thread->join_count;
656 }
657 if (ret_val)
658 *ret_val = thread->return_value;
659
660 /* remove thread descriptor when we're the last joiner or when the
661 * thread was already a zombie.
662 */
663 if (count <= 0) {
664 _pthread_internal_remove_locked(thread);
665 _pthread_internal_free(thread);
666 }
667 pthread_mutex_unlock(&gThreadListLock);
668 return 0;
669}
670
671int pthread_detach( pthread_t thid )
672{
673 pthread_internal_t* thread;
674 int result = 0;
675 int flags;
676
677 pthread_mutex_lock(&gThreadListLock);
678 for (thread = gThreadList; thread != NULL; thread = thread->next)
679 if (thread == (pthread_internal_t*)thid)
680 goto FoundIt;
681
682 result = ESRCH;
683 goto Exit;
684
685FoundIt:
686 do {
687 flags = thread->attr.flags;
688
689 if ( flags & PTHREAD_ATTR_FLAG_DETACHED ) {
690 /* thread is not joinable ! */
691 result = EINVAL;
692 goto Exit;
693 }
694 }
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100695 while ( __bionic_cmpxchg( flags, flags | PTHREAD_ATTR_FLAG_DETACHED,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800696 (volatile int*)&thread->attr.flags ) != 0 );
697Exit:
698 pthread_mutex_unlock(&gThreadListLock);
699 return result;
700}
701
702pthread_t pthread_self(void)
703{
704 return (pthread_t)__get_thread();
705}
706
707int pthread_equal(pthread_t one, pthread_t two)
708{
709 return (one == two ? 1 : 0);
710}
711
712int pthread_getschedparam(pthread_t thid, int * policy,
713 struct sched_param * param)
714{
715 int old_errno = errno;
716
717 pthread_internal_t * thread = (pthread_internal_t *)thid;
718 int err = sched_getparam(thread->kernel_id, param);
719 if (!err) {
720 *policy = sched_getscheduler(thread->kernel_id);
721 } else {
722 err = errno;
723 errno = old_errno;
724 }
725 return err;
726}
727
728int pthread_setschedparam(pthread_t thid, int policy,
729 struct sched_param const * param)
730{
731 pthread_internal_t * thread = (pthread_internal_t *)thid;
732 int old_errno = errno;
733 int ret;
734
735 ret = sched_setscheduler(thread->kernel_id, policy, param);
736 if (ret < 0) {
737 ret = errno;
738 errno = old_errno;
739 }
740 return ret;
741}
742
743
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800744/* a mutex is implemented as a 32-bit integer holding the following fields
745 *
746 * bits: name description
747 * 31-16 tid owner thread's kernel id (recursive and errorcheck only)
748 * 15-14 type mutex type
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700749 * 13 shared process-shared flag
750 * 12-2 counter counter of recursive mutexes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800751 * 1-0 state lock state (0, 1 or 2)
752 */
753
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100754/* Convenience macro, creates a mask of 'bits' bits that starts from
755 * the 'shift'-th least significant bit in a 32-bit word.
756 *
757 * Examples: FIELD_MASK(0,4) -> 0xf
758 * FIELD_MASK(16,9) -> 0x1ff0000
759 */
760#define FIELD_MASK(shift,bits) (((1 << (bits))-1) << (shift))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800761
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100762/* This one is used to create a bit pattern from a given field value */
763#define FIELD_TO_BITS(val,shift,bits) (((val) & ((1 << (bits))-1)) << (shift))
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100764
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100765/* And this one does the opposite, i.e. extract a field's value from a bit pattern */
766#define FIELD_FROM_BITS(val,shift,bits) (((val) >> (shift)) & ((1 << (bits))-1))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800767
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100768/* Mutex state:
769 *
770 * 0 for unlocked
771 * 1 for locked, no waiters
772 * 2 for locked, maybe waiters
773 */
774#define MUTEX_STATE_SHIFT 0
775#define MUTEX_STATE_LEN 2
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800776
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100777#define MUTEX_STATE_MASK FIELD_MASK(MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
778#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
779#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
780
781#define MUTEX_STATE_UNLOCKED 0 /* must be 0 to match __PTHREAD_MUTEX_INIT_VALUE */
782#define MUTEX_STATE_LOCKED_UNCONTENDED 1 /* must be 1 due to atomic dec in unlock operation */
783#define MUTEX_STATE_LOCKED_CONTENDED 2 /* must be 1 + LOCKED_UNCONTENDED due to atomic dec */
784
785#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
786#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
787
788#define MUTEX_STATE_BITS_UNLOCKED MUTEX_STATE_TO_BITS(MUTEX_STATE_UNLOCKED)
789#define MUTEX_STATE_BITS_LOCKED_UNCONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_UNCONTENDED)
790#define MUTEX_STATE_BITS_LOCKED_CONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_CONTENDED)
791
792/* return true iff the mutex if locked with no waiters */
793#define MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_UNCONTENDED)
794
795/* return true iff the mutex if locked with maybe waiters */
796#define MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_CONTENDED)
797
798/* used to flip from LOCKED_UNCONTENDED to LOCKED_CONTENDED */
799#define MUTEX_STATE_BITS_FLIP_CONTENTION(v) ((v) ^ (MUTEX_STATE_BITS_LOCKED_CONTENDED ^ MUTEX_STATE_BITS_LOCKED_UNCONTENDED))
800
801/* Mutex counter:
802 *
803 * We need to check for overflow before incrementing, and we also need to
804 * detect when the counter is 0
805 */
806#define MUTEX_COUNTER_SHIFT 2
807#define MUTEX_COUNTER_LEN 11
808#define MUTEX_COUNTER_MASK FIELD_MASK(MUTEX_COUNTER_SHIFT, MUTEX_COUNTER_LEN)
809
810#define MUTEX_COUNTER_BITS_WILL_OVERFLOW(v) (((v) & MUTEX_COUNTER_MASK) == MUTEX_COUNTER_MASK)
811#define MUTEX_COUNTER_BITS_IS_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
812
813/* Used to increment the counter directly after overflow has been checked */
814#define MUTEX_COUNTER_BITS_ONE FIELD_TO_BITS(1,MUTEX_COUNTER_SHIFT,MUTEX_COUNTER_LEN)
815
816/* Returns true iff the counter is 0 */
817#define MUTEX_COUNTER_BITS_ARE_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
818
819/* Mutex shared bit flag
820 *
821 * This flag is set to indicate that the mutex is shared among processes.
822 * This changes the futex opcode we use for futex wait/wake operations
823 * (non-shared operations are much faster).
824 */
825#define MUTEX_SHARED_SHIFT 13
826#define MUTEX_SHARED_MASK FIELD_MASK(MUTEX_SHARED_SHIFT,1)
827
828/* Mutex type:
829 *
830 * We support normal, recursive and errorcheck mutexes.
831 *
832 * The constants defined here *cannot* be changed because they must match
833 * the C library ABI which defines the following initialization values in
834 * <pthread.h>:
835 *
836 * __PTHREAD_MUTEX_INIT_VALUE
837 * __PTHREAD_RECURSIVE_MUTEX_VALUE
838 * __PTHREAD_ERRORCHECK_MUTEX_INIT_VALUE
839 */
840#define MUTEX_TYPE_SHIFT 14
841#define MUTEX_TYPE_LEN 2
842#define MUTEX_TYPE_MASK FIELD_MASK(MUTEX_TYPE_SHIFT,MUTEX_TYPE_LEN)
843
844#define MUTEX_TYPE_NORMAL 0 /* Must be 0 to match __PTHREAD_MUTEX_INIT_VALUE */
845#define MUTEX_TYPE_RECURSIVE 1
846#define MUTEX_TYPE_ERRORCHECK 2
847
848#define MUTEX_TYPE_TO_BITS(t) FIELD_TO_BITS(t, MUTEX_TYPE_SHIFT, MUTEX_TYPE_LEN)
849
850#define MUTEX_TYPE_BITS_NORMAL MUTEX_TYPE_TO_BITS(MUTEX_TYPE_NORMAL)
851#define MUTEX_TYPE_BITS_RECURSIVE MUTEX_TYPE_TO_BITS(MUTEX_TYPE_RECURSIVE)
852#define MUTEX_TYPE_BITS_ERRORCHECK MUTEX_TYPE_TO_BITS(MUTEX_TYPE_ERRORCHECK)
853
854/* Mutex owner field:
855 *
856 * This is only used for recursive and errorcheck mutexes. It holds the
857 * kernel TID of the owning thread. Note that this works because the Linux
858 * kernel _only_ uses 16-bit values for thread ids.
859 *
860 * More specifically, it will wrap to 10000 when it reaches over 32768 for
861 * application processes. You can check this by running the following inside
862 * an adb shell session:
863 *
864 OLDPID=$$;
865 while true; do
866 NEWPID=$(sh -c 'echo $$')
867 if [ "$NEWPID" -gt 32768 ]; then
868 echo "AARGH: new PID $NEWPID is too high!"
869 exit 1
870 fi
871 if [ "$NEWPID" -lt "$OLDPID" ]; then
872 echo "****** Wrapping from PID $OLDPID to $NEWPID. *******"
873 else
874 echo -n "$NEWPID!"
875 fi
876 OLDPID=$NEWPID
877 done
878
879 * Note that you can run the same example on a desktop Linux system,
880 * the wrapping will also happen at 32768, but will go back to 300 instead.
881 */
882#define MUTEX_OWNER_SHIFT 16
883#define MUTEX_OWNER_LEN 16
884
885#define MUTEX_OWNER_FROM_BITS(v) FIELD_FROM_BITS(v,MUTEX_OWNER_SHIFT,MUTEX_OWNER_LEN)
886#define MUTEX_OWNER_TO_BITS(v) FIELD_TO_BITS(v,MUTEX_OWNER_SHIFT,MUTEX_OWNER_LEN)
887
888/* Convenience macros.
889 *
890 * These are used to form or modify the bit pattern of a given mutex value
891 */
892
893
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800894
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700895/* a mutex attribute holds the following fields
896 *
897 * bits: name description
898 * 0-3 type type of mutex
899 * 4 shared process-shared flag
900 */
901#define MUTEXATTR_TYPE_MASK 0x000f
902#define MUTEXATTR_SHARED_MASK 0x0010
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800903
904
905int pthread_mutexattr_init(pthread_mutexattr_t *attr)
906{
907 if (attr) {
908 *attr = PTHREAD_MUTEX_DEFAULT;
909 return 0;
910 } else {
911 return EINVAL;
912 }
913}
914
915int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
916{
917 if (attr) {
918 *attr = -1;
919 return 0;
920 } else {
921 return EINVAL;
922 }
923}
924
925int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
926{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700927 if (attr) {
928 int atype = (*attr & MUTEXATTR_TYPE_MASK);
929
930 if (atype >= PTHREAD_MUTEX_NORMAL &&
931 atype <= PTHREAD_MUTEX_ERRORCHECK) {
932 *type = atype;
933 return 0;
934 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800935 }
936 return EINVAL;
937}
938
939int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
940{
941 if (attr && type >= PTHREAD_MUTEX_NORMAL &&
942 type <= PTHREAD_MUTEX_ERRORCHECK ) {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700943 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800944 return 0;
945 }
946 return EINVAL;
947}
948
949/* process-shared mutexes are not supported at the moment */
950
951int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
952{
953 if (!attr)
954 return EINVAL;
955
Mathias Agopianb7681162009-07-13 22:00:33 -0700956 switch (pshared) {
957 case PTHREAD_PROCESS_PRIVATE:
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700958 *attr &= ~MUTEXATTR_SHARED_MASK;
959 return 0;
960
Mathias Agopianb7681162009-07-13 22:00:33 -0700961 case PTHREAD_PROCESS_SHARED:
962 /* our current implementation of pthread actually supports shared
963 * mutexes but won't cleanup if a process dies with the mutex held.
964 * Nevertheless, it's better than nothing. Shared mutexes are used
965 * by surfaceflinger and audioflinger.
966 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700967 *attr |= MUTEXATTR_SHARED_MASK;
Mathias Agopianb7681162009-07-13 22:00:33 -0700968 return 0;
969 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700970 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800971}
972
973int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
974{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700975 if (!attr || !pshared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800976 return EINVAL;
977
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700978 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED
979 : PTHREAD_PROCESS_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800980 return 0;
981}
982
983int pthread_mutex_init(pthread_mutex_t *mutex,
984 const pthread_mutexattr_t *attr)
985{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700986 int value = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800987
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700988 if (mutex == NULL)
989 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800990
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700991 if (__likely(attr == NULL)) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100992 mutex->value = MUTEX_TYPE_BITS_NORMAL;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700993 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800994 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700995
996 if ((*attr & MUTEXATTR_SHARED_MASK) != 0)
997 value |= MUTEX_SHARED_MASK;
998
999 switch (*attr & MUTEXATTR_TYPE_MASK) {
1000 case PTHREAD_MUTEX_NORMAL:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001001 value |= MUTEX_TYPE_BITS_NORMAL;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001002 break;
1003 case PTHREAD_MUTEX_RECURSIVE:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001004 value |= MUTEX_TYPE_BITS_RECURSIVE;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001005 break;
1006 case PTHREAD_MUTEX_ERRORCHECK:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001007 value |= MUTEX_TYPE_BITS_ERRORCHECK;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001008 break;
1009 default:
1010 return EINVAL;
1011 }
1012
1013 mutex->value = value;
1014 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001015}
1016
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001017
1018/*
1019 * Lock a non-recursive mutex.
1020 *
1021 * As noted above, there are three states:
1022 * 0 (unlocked, no contention)
1023 * 1 (locked, no contention)
1024 * 2 (locked, contention)
1025 *
1026 * Non-recursive mutexes don't use the thread-id or counter fields, and the
1027 * "type" value is zero, so the only bits that will be set are the ones in
1028 * the lock state field.
1029 */
1030static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001031_normal_lock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001032{
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001033 /* convenience shortcuts */
1034 const int unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
1035 const int locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001036 /*
1037 * The common case is an unlocked mutex, so we begin by trying to
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001038 * change the lock's state from 0 (UNLOCKED) to 1 (LOCKED).
1039 * __bionic_cmpxchg() returns 0 if it made the swap successfully.
1040 * If the result is nonzero, this lock is already held by another thread.
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001041 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001042 if (__bionic_cmpxchg(unlocked, locked_uncontended, &mutex->value) != 0) {
1043 const int locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001044 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001045 * We want to go to sleep until the mutex is available, which
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001046 * requires promoting it to state 2 (CONTENDED). We need to
1047 * swap in the new state value and then wait until somebody wakes us up.
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001048 *
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001049 * __bionic_swap() returns the previous value. We swap 2 in and
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001050 * see if we got zero back; if so, we have acquired the lock. If
1051 * not, another thread still holds the lock and we wait again.
1052 *
1053 * The second argument to the __futex_wait() call is compared
1054 * against the current value. If it doesn't match, __futex_wait()
1055 * returns immediately (otherwise, it sleeps for a time specified
1056 * by the third argument; 0 means sleep forever). This ensures
1057 * that the mutex is in state 2 when we go to sleep on it, which
1058 * guarantees a wake-up call.
1059 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001060 while (__bionic_swap(locked_contended, &mutex->value) != unlocked)
1061 __futex_wait_ex(&mutex->value, shared, locked_contended, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001062 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001063 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001064}
1065
1066/*
1067 * Release a non-recursive mutex. The caller is responsible for determining
1068 * that we are in fact the owner of this lock.
1069 */
1070static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001071_normal_unlock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001072{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001073 ANDROID_MEMBAR_FULL();
1074
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001075 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001076 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001077 * to release the lock. __bionic_atomic_dec() returns the previous value;
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001078 * if it wasn't 1 we have to do some additional work.
1079 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001080 if (__bionic_atomic_dec(&mutex->value) != (shared|MUTEX_STATE_BITS_LOCKED_UNCONTENDED)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001081 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001082 * Start by releasing the lock. The decrement changed it from
1083 * "contended lock" to "uncontended lock", which means we still
1084 * hold it, and anybody who tries to sneak in will push it back
1085 * to state 2.
1086 *
1087 * Once we set it to zero the lock is up for grabs. We follow
1088 * this with a __futex_wake() to ensure that one of the waiting
1089 * threads has a chance to grab it.
1090 *
1091 * This doesn't cause a race with the swap/wait pair in
1092 * _normal_lock(), because the __futex_wait() call there will
1093 * return immediately if the mutex value isn't 2.
1094 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001095 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001096
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001097 /*
1098 * Wake up one waiting thread. We don't know which thread will be
1099 * woken or when it'll start executing -- futexes make no guarantees
1100 * here. There may not even be a thread waiting.
1101 *
1102 * The newly-woken thread will replace the 0 we just set above
1103 * with 2, which means that when it eventually releases the mutex
1104 * it will also call FUTEX_WAKE. This results in one extra wake
1105 * call whenever a lock is contended, but lets us avoid forgetting
1106 * anyone without requiring us to track the number of sleepers.
1107 *
1108 * It's possible for another thread to sneak in and grab the lock
1109 * between the zero assignment above and the wake call below. If
1110 * the new thread is "slow" and holds the lock for a while, we'll
1111 * wake up a sleeper, which will swap in a 2 and then go back to
1112 * sleep since the lock is still held. If the new thread is "fast",
1113 * running to completion before we call wake, the thread we
1114 * eventually wake will find an unlocked mutex and will execute.
1115 * Either way we have correct behavior and nobody is orphaned on
1116 * the wait queue.
1117 */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001118 __futex_wake_ex(&mutex->value, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001119 }
1120}
1121
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001122/* This common inlined function is used to increment the counter of an
1123 * errorcheck or recursive mutex.
1124 *
1125 * For errorcheck mutexes, it will return EDEADLK
1126 * If the counter overflows, it will return EAGAIN
1127 * Otherwise, it atomically increments the counter and returns 0
1128 * after providing an acquire barrier.
1129 *
1130 * mtype is the current mutex type
1131 * mvalue is the current mutex value (already loaded)
1132 * mutex pointers to the mutex.
1133 */
1134static __inline__ __attribute__((always_inline)) int
1135_recursive_increment(pthread_mutex_t* mutex, int mvalue, int mtype)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001136{
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001137 if (mtype == MUTEX_TYPE_BITS_ERRORCHECK) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001138 /* trying to re-lock a mutex we already acquired */
1139 return EDEADLK;
1140 }
1141
1142 /* Detect recursive lock overflow and return EAGAIN.
1143 * This is safe because only the owner thread can modify the
David 'Digit' Turnerb57db752012-01-24 13:20:38 +01001144 * counter bits in the mutex value.
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001145 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001146 if (MUTEX_COUNTER_BITS_WILL_OVERFLOW(mvalue)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001147 return EAGAIN;
1148 }
1149
1150 /* We own the mutex, but other threads are able to change
David 'Digit' Turnerb57db752012-01-24 13:20:38 +01001151 * the lower bits (e.g. promoting it to "contended"), so we
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001152 * need to use an atomic cmpxchg loop to update the counter.
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001153 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001154 for (;;) {
1155 /* increment counter, overflow was already checked */
1156 int newval = mvalue + MUTEX_COUNTER_BITS_ONE;
1157 if (__likely(__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0)) {
1158 /* mutex is still locked, not need for a memory barrier */
1159 return 0;
1160 }
1161 /* the value was changed, this happens when another thread changes
1162 * the lower state bits from 1 to 2 to indicate contention. This
1163 * cannot change the counter, so simply reload and try again.
1164 */
1165 mvalue = mutex->value;
1166 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001167}
1168
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001169__LIBC_HIDDEN__
1170int pthread_mutex_lock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001171{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001172 int mvalue, mtype, tid, new_lock_type, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001173
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001174 if (__unlikely(mutex == NULL))
1175 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001176
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001177 mvalue = mutex->value;
1178 mtype = (mvalue & MUTEX_TYPE_MASK);
1179 shared = (mvalue & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001180
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001181 /* Handle normal case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001182 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) ) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001183 _normal_lock(mutex, shared);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001184 return 0;
1185 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001186
1187 /* Do we already own this recursive or error-check mutex ? */
1188 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001189 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001190 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001191
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001192 /* Add in shared state to avoid extra 'or' operations below */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001193 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001194
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001195 /* First, if the mutex is unlocked, try to quickly acquire it.
1196 * In the optimistic case where this works, set the state to 1 to
1197 * indicate locked with no contention */
1198 if (mvalue == mtype) {
1199 int newval = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1200 if (__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0) {
1201 ANDROID_MEMBAR_FULL();
1202 return 0;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001203 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001204 /* argh, the value changed, reload before entering the loop */
1205 mvalue = mutex->value;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001206 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001207
1208 for (;;) {
1209 int newval;
1210
1211 /* if the mutex is unlocked, its value should be 'mtype' and
1212 * we try to acquire it by setting its owner and state atomically.
1213 * NOTE: We put the state to 2 since we _know_ there is contention
1214 * when we are in this loop. This ensures all waiters will be
1215 * unlocked.
1216 */
1217 if (mvalue == mtype) {
1218 newval = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1219 /* TODO: Change this to __bionic_cmpxchg_acquire when we
1220 * implement it to get rid of the explicit memory
1221 * barrier below.
1222 */
1223 if (__unlikely(__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0)) {
1224 mvalue = mutex->value;
1225 continue;
1226 }
1227 ANDROID_MEMBAR_FULL();
1228 return 0;
1229 }
1230
1231 /* the mutex is already locked by another thread, if its state is 1
1232 * we will change it to 2 to indicate contention. */
1233 if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(mvalue)) {
1234 newval = MUTEX_STATE_BITS_FLIP_CONTENTION(mvalue); /* locked state 1 => state 2 */
1235 if (__unlikely(__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0)) {
1236 mvalue = mutex->value;
1237 continue;
1238 }
1239 mvalue = newval;
1240 }
1241
1242 /* wait until the mutex is unlocked */
1243 __futex_wait_ex(&mutex->value, shared, mvalue, NULL);
1244
1245 mvalue = mutex->value;
1246 }
1247 /* NOTREACHED */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001248}
1249
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001250int pthread_mutex_lock(pthread_mutex_t *mutex)
1251{
1252 int err = pthread_mutex_lock_impl(mutex);
1253#ifdef PTHREAD_DEBUG
1254 if (PTHREAD_DEBUG_ENABLED) {
1255 if (!err) {
1256 pthread_debug_mutex_lock_check(mutex);
1257 }
1258 }
1259#endif
1260 return err;
1261}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001262
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001263__LIBC_HIDDEN__
1264int pthread_mutex_unlock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001265{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001266 int mvalue, mtype, tid, oldv, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001267
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001268 if (__unlikely(mutex == NULL))
1269 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001270
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001271 mvalue = mutex->value;
1272 mtype = (mvalue & MUTEX_TYPE_MASK);
1273 shared = (mvalue & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001274
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001275 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001276 if (__likely(mtype == MUTEX_TYPE_BITS_NORMAL)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001277 _normal_unlock(mutex, shared);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001278 return 0;
1279 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001280
1281 /* Do we already own this recursive or error-check mutex ? */
1282 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001283 if ( tid != MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001284 return EPERM;
1285
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001286 /* If the counter is > 0, we can simply decrement it atomically.
1287 * Since other threads can mutate the lower state bits (and only the
1288 * lower state bits), use a cmpxchg to do it.
1289 */
1290 if (!MUTEX_COUNTER_BITS_IS_ZERO(mvalue)) {
1291 for (;;) {
1292 int newval = mvalue - MUTEX_COUNTER_BITS_ONE;
1293 if (__likely(__bionic_cmpxchg(mvalue, newval, &mutex->value) == 0)) {
1294 /* success: we still own the mutex, so no memory barrier */
1295 return 0;
1296 }
1297 /* the value changed, so reload and loop */
1298 mvalue = mutex->value;
1299 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001300 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001301
1302 /* the counter is 0, so we're going to unlock the mutex by resetting
1303 * its value to 'unlocked'. We need to perform a swap in order
1304 * to read the current state, which will be 2 if there are waiters
1305 * to awake.
1306 *
1307 * TODO: Change this to __bionic_swap_release when we implement it
1308 * to get rid of the explicit memory barrier below.
1309 */
1310 ANDROID_MEMBAR_FULL(); /* RELEASE BARRIER */
1311 mvalue = __bionic_swap(mtype | shared | MUTEX_STATE_BITS_UNLOCKED, &mutex->value);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001312
1313 /* Wake one waiting thread, if any */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001314 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(mvalue)) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001315 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001316 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001317 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001318}
1319
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001320int pthread_mutex_unlock(pthread_mutex_t *mutex)
1321{
1322#ifdef PTHREAD_DEBUG
1323 if (PTHREAD_DEBUG_ENABLED) {
1324 pthread_debug_mutex_unlock_check(mutex);
1325 }
1326#endif
1327 return pthread_mutex_unlock_impl(mutex);
1328}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001329
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001330__LIBC_HIDDEN__
1331int pthread_mutex_trylock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001332{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001333 int mvalue, mtype, tid, oldv, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001334
1335 if (__unlikely(mutex == NULL))
1336 return EINVAL;
1337
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001338 mvalue = mutex->value;
1339 mtype = (mvalue & MUTEX_TYPE_MASK);
1340 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001341
1342 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001343 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001344 {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001345 if (__bionic_cmpxchg(shared|MUTEX_STATE_BITS_UNLOCKED,
1346 shared|MUTEX_STATE_BITS_LOCKED_UNCONTENDED,
1347 &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001348 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001349 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001350 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001351
1352 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001353 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001354
1355 /* Do we already own this recursive or error-check mutex ? */
1356 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001357 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001358 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001359
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001360 /* Same as pthread_mutex_lock, except that we don't want to wait, and
1361 * the only operation that can succeed is a single cmpxchg to acquire the
1362 * lock if it is released / not owned by anyone. No need for a complex loop.
1363 */
1364 mtype |= shared | MUTEX_STATE_BITS_UNLOCKED;
1365 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001366
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001367 if (__likely(__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0)) {
1368 ANDROID_MEMBAR_FULL();
1369 return 0;
1370 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001371
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001372 return EBUSY;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001373}
1374
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001375int pthread_mutex_trylock(pthread_mutex_t *mutex)
1376{
1377 int err = pthread_mutex_trylock_impl(mutex);
1378#ifdef PTHREAD_DEBUG
1379 if (PTHREAD_DEBUG_ENABLED) {
1380 if (!err) {
1381 pthread_debug_mutex_lock_check(mutex);
1382 }
1383 }
1384#endif
1385 return err;
1386}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001387
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001388/* initialize 'ts' with the difference between 'abstime' and the current time
1389 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
1390 */
1391static int
1392__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
1393{
1394 clock_gettime(clock, ts);
1395 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
1396 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
1397 if (ts->tv_nsec < 0) {
1398 ts->tv_sec--;
1399 ts->tv_nsec += 1000000000;
1400 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001401 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001402 return -1;
1403
1404 return 0;
1405}
1406
1407/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1408 * milliseconds.
1409 */
1410static void
1411__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1412{
1413 clock_gettime(clock, abstime);
1414 abstime->tv_sec += msecs/1000;
1415 abstime->tv_nsec += (msecs%1000)*1000000;
1416 if (abstime->tv_nsec >= 1000000000) {
1417 abstime->tv_sec++;
1418 abstime->tv_nsec -= 1000000000;
1419 }
1420}
1421
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001422__LIBC_HIDDEN__
1423int pthread_mutex_lock_timeout_np_impl(pthread_mutex_t *mutex, unsigned msecs)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001424{
1425 clockid_t clock = CLOCK_MONOTONIC;
1426 struct timespec abstime;
1427 struct timespec ts;
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001428 int mvalue, mtype, tid, oldv, new_lock_type, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001429
1430 /* compute absolute expiration time */
1431 __timespec_to_relative_msec(&abstime, msecs, clock);
1432
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001433 if (__unlikely(mutex == NULL))
1434 return EINVAL;
1435
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001436 mvalue = mutex->value;
1437 mtype = (mvalue & MUTEX_TYPE_MASK);
1438 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001439
1440 /* Handle common case first */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001441 if ( __likely(mtype == MUTEX_TYPE_BITS_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001442 {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001443 const int unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
1444 const int locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1445 const int locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1446
1447 /* fast path for uncontended lock. Note: MUTEX_TYPE_BITS_NORMAL is 0 */
1448 if (__bionic_cmpxchg(unlocked, locked_uncontended, &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001449 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001450 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001451 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001452
1453 /* loop while needed */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001454 while (__bionic_swap(locked_contended, &mutex->value) != unlocked) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001455 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1456 return EBUSY;
1457
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001458 __futex_wait_ex(&mutex->value, shared, locked_contended, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001459 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001460 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001461 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001462 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001463
1464 /* Do we already own this recursive or error-check mutex ? */
1465 tid = __get_thread()->kernel_id;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001466 if ( tid == MUTEX_OWNER_FROM_BITS(mvalue) )
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001467 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001468
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001469 /* the following implements the same loop than pthread_mutex_lock_impl
1470 * but adds checks to ensure that the operation never exceeds the
1471 * absolute expiration time.
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001472 */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001473 mtype |= shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001474
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001475 /* first try a quick lock */
1476 if (mvalue == mtype) {
1477 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
1478 if (__likely(__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0)) {
1479 ANDROID_MEMBAR_FULL();
1480 return 0;
1481 }
1482 mvalue = mutex->value;
1483 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001484
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001485 for (;;) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001486 struct timespec ts;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001487
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001488 /* if the value is 'unlocked', try to acquire it directly */
1489 /* NOTE: put state to 2 since we know there is contention */
1490 if (mvalue == mtype) /* unlocked */ {
1491 mvalue = MUTEX_OWNER_TO_BITS(tid) | mtype | MUTEX_STATE_BITS_LOCKED_CONTENDED;
1492 if (__bionic_cmpxchg(mtype, mvalue, &mutex->value) == 0) {
1493 ANDROID_MEMBAR_FULL();
1494 return 0;
1495 }
1496 /* the value changed before we could lock it. We need to check
1497 * the time to avoid livelocks, reload the value, then loop again. */
1498 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1499 return EBUSY;
1500
1501 mvalue = mutex->value;
1502 continue;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001503 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001504
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001505 /* The value is locked. If 'uncontended', try to switch its state
1506 * to 'contented' to ensure we get woken up later. */
1507 if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(mvalue)) {
1508 int newval = MUTEX_STATE_BITS_FLIP_CONTENTION(mvalue);
1509 if (__bionic_cmpxchg(mvalue, newval, &mutex->value) != 0) {
1510 /* this failed because the value changed, reload it */
1511 mvalue = mutex->value;
1512 } else {
1513 /* this succeeded, update mvalue */
1514 mvalue = newval;
1515 }
1516 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001517
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001518 /* check time and update 'ts' */
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001519 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1520 return EBUSY;
1521
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001522 /* Only wait to be woken up if the state is '2', otherwise we'll
1523 * simply loop right now. This can happen when the second cmpxchg
1524 * in our loop failed because the mutex was unlocked by another
1525 * thread.
1526 */
1527 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(mvalue)) {
1528 if (__futex_wait_ex(&mutex->value, shared, mvalue, &ts) == ETIMEDOUT) {
1529 return EBUSY;
1530 }
1531 mvalue = mutex->value;
1532 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001533 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +01001534 /* NOTREACHED */
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001535}
1536
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001537int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1538{
1539 int err = pthread_mutex_lock_timeout_np_impl(mutex, msecs);
1540#ifdef PTHREAD_DEBUG
1541 if (PTHREAD_DEBUG_ENABLED) {
1542 if (!err) {
1543 pthread_debug_mutex_lock_check(mutex);
1544 }
1545 }
1546#endif
1547 return err;
1548}
1549
1550int pthread_mutex_destroy(pthread_mutex_t *mutex)
1551{
1552 int ret;
1553
1554 /* use trylock to ensure that the mutex value is
1555 * valid and is not already locked. */
1556 ret = pthread_mutex_trylock_impl(mutex);
1557 if (ret != 0)
1558 return ret;
1559
1560 mutex->value = 0xdead10cc;
1561 return 0;
1562}
1563
1564
1565
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001566int pthread_condattr_init(pthread_condattr_t *attr)
1567{
1568 if (attr == NULL)
1569 return EINVAL;
1570
1571 *attr = PTHREAD_PROCESS_PRIVATE;
1572 return 0;
1573}
1574
1575int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1576{
1577 if (attr == NULL || pshared == NULL)
1578 return EINVAL;
1579
1580 *pshared = *attr;
1581 return 0;
1582}
1583
1584int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1585{
1586 if (attr == NULL)
1587 return EINVAL;
1588
1589 if (pshared != PTHREAD_PROCESS_SHARED &&
1590 pshared != PTHREAD_PROCESS_PRIVATE)
1591 return EINVAL;
1592
1593 *attr = pshared;
1594 return 0;
1595}
1596
1597int pthread_condattr_destroy(pthread_condattr_t *attr)
1598{
1599 if (attr == NULL)
1600 return EINVAL;
1601
1602 *attr = 0xdeada11d;
1603 return 0;
1604}
1605
1606/* We use one bit in condition variable values as the 'shared' flag
1607 * The rest is a counter.
1608 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001609#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001610#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001611#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1612
1613#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001614
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001615/* XXX *technically* there is a race condition that could allow
1616 * XXX a signal to be missed. If thread A is preempted in _wait()
1617 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001618 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001619 * XXX before thread A is scheduled again and calls futex_wait(),
1620 * XXX then the signal will be lost.
1621 */
1622
1623int pthread_cond_init(pthread_cond_t *cond,
1624 const pthread_condattr_t *attr)
1625{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001626 if (cond == NULL)
1627 return EINVAL;
1628
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001629 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001630
1631 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001632 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001633
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001634 return 0;
1635}
1636
1637int pthread_cond_destroy(pthread_cond_t *cond)
1638{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001639 if (cond == NULL)
1640 return EINVAL;
1641
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001642 cond->value = 0xdeadc04d;
1643 return 0;
1644}
1645
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001646/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001647 * pthread_cond_signal to atomically decrement the counter
1648 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001649 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001650static int
1651__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001652{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001653 long flags;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001654
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001655 if (__unlikely(cond == NULL))
1656 return EINVAL;
1657
1658 flags = (cond->value & ~COND_COUNTER_MASK);
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001659 for (;;) {
1660 long oldval = cond->value;
1661 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1662 | flags;
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001663 if (__bionic_cmpxchg(oldval, newval, &cond->value) == 0)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001664 break;
1665 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001666
Andy McFaddene2ac8982010-09-02 13:34:53 -07001667 /*
1668 * Ensure that all memory accesses previously made by this thread are
1669 * visible to the woken thread(s). On the other side, the "wait"
1670 * code will issue any necessary barriers when locking the mutex.
1671 *
1672 * This may not strictly be necessary -- if the caller follows
1673 * recommended practice and holds the mutex before signaling the cond
1674 * var, the mutex ops will provide correct semantics. If they don't
1675 * hold the mutex, they're subject to race conditions anyway.
1676 */
1677 ANDROID_MEMBAR_FULL();
1678
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001679 __futex_wake_ex(&cond->value, COND_IS_SHARED(cond), counter);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001680 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001681}
1682
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001683int pthread_cond_broadcast(pthread_cond_t *cond)
1684{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001685 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001686}
1687
1688int pthread_cond_signal(pthread_cond_t *cond)
1689{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001690 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001691}
1692
1693int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1694{
1695 return pthread_cond_timedwait(cond, mutex, NULL);
1696}
1697
1698int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1699 pthread_mutex_t * mutex,
1700 const struct timespec *reltime)
1701{
1702 int status;
1703 int oldvalue = cond->value;
1704
1705 pthread_mutex_unlock(mutex);
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001706 status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond), oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001707 pthread_mutex_lock(mutex);
1708
1709 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1710 return 0;
1711}
1712
1713int __pthread_cond_timedwait(pthread_cond_t *cond,
1714 pthread_mutex_t * mutex,
1715 const struct timespec *abstime,
1716 clockid_t clock)
1717{
1718 struct timespec ts;
1719 struct timespec * tsp;
1720
1721 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001722 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001723 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001724 tsp = &ts;
1725 } else {
1726 tsp = NULL;
1727 }
1728
1729 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1730}
1731
1732int pthread_cond_timedwait(pthread_cond_t *cond,
1733 pthread_mutex_t * mutex,
1734 const struct timespec *abstime)
1735{
1736 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1737}
1738
1739
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001740/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001741int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1742 pthread_mutex_t * mutex,
1743 const struct timespec *abstime)
1744{
1745 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1746}
1747
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001748int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1749 pthread_mutex_t * mutex,
1750 const struct timespec *abstime)
1751{
1752 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1753}
1754
1755int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1756 pthread_mutex_t * mutex,
1757 const struct timespec *reltime)
1758{
1759 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1760}
1761
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001762int pthread_cond_timeout_np(pthread_cond_t *cond,
1763 pthread_mutex_t * mutex,
1764 unsigned msecs)
1765{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001766 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001767
1768 ts.tv_sec = msecs / 1000;
1769 ts.tv_nsec = (msecs % 1000) * 1000000;
1770
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001771 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001772}
1773
1774
1775
1776/* A technical note regarding our thread-local-storage (TLS) implementation:
1777 *
1778 * There can be up to TLSMAP_SIZE independent TLS keys in a given process,
1779 * though the first TLSMAP_START keys are reserved for Bionic to hold
1780 * special thread-specific variables like errno or a pointer to
1781 * the current thread's descriptor.
1782 *
1783 * while stored in the TLS area, these entries cannot be accessed through
1784 * pthread_getspecific() / pthread_setspecific() and pthread_key_delete()
1785 *
1786 * also, some entries in the key table are pre-allocated (see tlsmap_lock)
1787 * to greatly simplify and speedup some OpenGL-related operations. though the
1788 * initialy value will be NULL on all threads.
1789 *
1790 * you can use pthread_getspecific()/setspecific() on these, and in theory
1791 * you could also call pthread_key_delete() as well, though this would
1792 * probably break some apps.
1793 *
1794 * The 'tlsmap_t' type defined below implements a shared global map of
1795 * currently created/allocated TLS keys and the destructors associated
1796 * with them. You should use tlsmap_lock/unlock to access it to avoid
1797 * any race condition.
1798 *
1799 * the global TLS map simply contains a bitmap of allocated keys, and
1800 * an array of destructors.
1801 *
1802 * each thread has a TLS area that is a simple array of TLSMAP_SIZE void*
1803 * pointers. the TLS area of the main thread is stack-allocated in
1804 * __libc_init_common, while the TLS area of other threads is placed at
1805 * the top of their stack in pthread_create.
1806 *
1807 * when pthread_key_create() is called, it finds the first free key in the
1808 * bitmap, then set it to 1, saving the destructor altogether
1809 *
1810 * when pthread_key_delete() is called. it will erase the key's bitmap bit
1811 * and its destructor, and will also clear the key data in the TLS area of
1812 * all created threads. As mandated by Posix, it is the responsability of
1813 * the caller of pthread_key_delete() to properly reclaim the objects that
1814 * were pointed to by these data fields (either before or after the call).
1815 *
1816 */
1817
1818/* TLS Map implementation
1819 */
1820
1821#define TLSMAP_START (TLS_SLOT_MAX_WELL_KNOWN+1)
1822#define TLSMAP_SIZE BIONIC_TLS_SLOTS
1823#define TLSMAP_BITS 32
1824#define TLSMAP_WORDS ((TLSMAP_SIZE+TLSMAP_BITS-1)/TLSMAP_BITS)
1825#define TLSMAP_WORD(m,k) (m)->map[(k)/TLSMAP_BITS]
1826#define TLSMAP_MASK(k) (1U << ((k)&(TLSMAP_BITS-1)))
1827
1828/* this macro is used to quickly check that a key belongs to a reasonable range */
1829#define TLSMAP_VALIDATE_KEY(key) \
1830 ((key) >= TLSMAP_START && (key) < TLSMAP_SIZE)
1831
1832/* the type of tls key destructor functions */
1833typedef void (*tls_dtor_t)(void*);
1834
1835typedef struct {
1836 int init; /* see comment in tlsmap_lock() */
1837 uint32_t map[TLSMAP_WORDS]; /* bitmap of allocated keys */
1838 tls_dtor_t dtors[TLSMAP_SIZE]; /* key destructors */
1839} tlsmap_t;
1840
1841static pthread_mutex_t _tlsmap_lock = PTHREAD_MUTEX_INITIALIZER;
1842static tlsmap_t _tlsmap;
1843
1844/* lock the global TLS map lock and return a handle to it */
1845static __inline__ tlsmap_t* tlsmap_lock(void)
1846{
1847 tlsmap_t* m = &_tlsmap;
1848
1849 pthread_mutex_lock(&_tlsmap_lock);
1850 /* we need to initialize the first entry of the 'map' array
1851 * with the value TLS_DEFAULT_ALLOC_MAP. doing it statically
1852 * when declaring _tlsmap is a bit awkward and is going to
1853 * produce warnings, so do it the first time we use the map
1854 * instead
1855 */
1856 if (__unlikely(!m->init)) {
1857 TLSMAP_WORD(m,0) = TLS_DEFAULT_ALLOC_MAP;
1858 m->init = 1;
1859 }
1860 return m;
1861}
1862
1863/* unlock the global TLS map */
1864static __inline__ void tlsmap_unlock(tlsmap_t* m)
1865{
1866 pthread_mutex_unlock(&_tlsmap_lock);
1867 (void)m; /* a good compiler is a happy compiler */
1868}
1869
1870/* test to see wether a key is allocated */
1871static __inline__ int tlsmap_test(tlsmap_t* m, int key)
1872{
1873 return (TLSMAP_WORD(m,key) & TLSMAP_MASK(key)) != 0;
1874}
1875
1876/* set the destructor and bit flag on a newly allocated key */
1877static __inline__ void tlsmap_set(tlsmap_t* m, int key, tls_dtor_t dtor)
1878{
1879 TLSMAP_WORD(m,key) |= TLSMAP_MASK(key);
1880 m->dtors[key] = dtor;
1881}
1882
1883/* clear the destructor and bit flag on an existing key */
1884static __inline__ void tlsmap_clear(tlsmap_t* m, int key)
1885{
1886 TLSMAP_WORD(m,key) &= ~TLSMAP_MASK(key);
1887 m->dtors[key] = NULL;
1888}
1889
1890/* allocate a new TLS key, return -1 if no room left */
1891static int tlsmap_alloc(tlsmap_t* m, tls_dtor_t dtor)
1892{
1893 int key;
1894
1895 for ( key = TLSMAP_START; key < TLSMAP_SIZE; key++ ) {
1896 if ( !tlsmap_test(m, key) ) {
1897 tlsmap_set(m, key, dtor);
1898 return key;
1899 }
1900 }
1901 return -1;
1902}
1903
1904
1905int pthread_key_create(pthread_key_t *key, void (*destructor_function)(void *))
1906{
1907 uint32_t err = ENOMEM;
1908 tlsmap_t* map = tlsmap_lock();
1909 int k = tlsmap_alloc(map, destructor_function);
1910
1911 if (k >= 0) {
1912 *key = k;
1913 err = 0;
1914 }
1915 tlsmap_unlock(map);
1916 return err;
1917}
1918
1919
1920/* This deletes a pthread_key_t. note that the standard mandates that this does
1921 * not call the destructor of non-NULL key values. Instead, it is the
1922 * responsability of the caller to properly dispose of the corresponding data
1923 * and resources, using any mean it finds suitable.
1924 *
1925 * On the other hand, this function will clear the corresponding key data
1926 * values in all known threads. this prevents later (invalid) calls to
1927 * pthread_getspecific() to receive invalid/stale values.
1928 */
1929int pthread_key_delete(pthread_key_t key)
1930{
1931 uint32_t err;
1932 pthread_internal_t* thr;
1933 tlsmap_t* map;
1934
1935 if (!TLSMAP_VALIDATE_KEY(key)) {
1936 return EINVAL;
1937 }
1938
1939 map = tlsmap_lock();
1940
1941 if (!tlsmap_test(map, key)) {
1942 err = EINVAL;
1943 goto err1;
1944 }
1945
1946 /* clear value in all threads */
1947 pthread_mutex_lock(&gThreadListLock);
1948 for ( thr = gThreadList; thr != NULL; thr = thr->next ) {
1949 /* avoid zombie threads with a negative 'join_count'. these are really
1950 * already dead and don't have a TLS area anymore.
1951 *
1952 * similarly, it is possible to have thr->tls == NULL for threads that
1953 * were just recently created through pthread_create() but whose
1954 * startup trampoline (__thread_entry) hasn't been run yet by the
Bjorn Andersson0753dc62012-05-03 17:12:39 -07001955 * scheduler. thr->tls will also be NULL after it's stack has been
1956 * unmapped but before the ongoing pthread_join() is finished.
1957 * so check for this too.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001958 */
1959 if (thr->join_count < 0 || !thr->tls)
1960 continue;
1961
1962 thr->tls[key] = NULL;
1963 }
1964 tlsmap_clear(map, key);
1965
1966 pthread_mutex_unlock(&gThreadListLock);
1967 err = 0;
1968
1969err1:
1970 tlsmap_unlock(map);
1971 return err;
1972}
1973
1974
1975int pthread_setspecific(pthread_key_t key, const void *ptr)
1976{
1977 int err = EINVAL;
1978 tlsmap_t* map;
1979
1980 if (TLSMAP_VALIDATE_KEY(key)) {
1981 /* check that we're trying to set data for an allocated key */
1982 map = tlsmap_lock();
1983 if (tlsmap_test(map, key)) {
1984 ((uint32_t *)__get_tls())[key] = (uint32_t)ptr;
1985 err = 0;
1986 }
1987 tlsmap_unlock(map);
1988 }
1989 return err;
1990}
1991
1992void * pthread_getspecific(pthread_key_t key)
1993{
1994 if (!TLSMAP_VALIDATE_KEY(key)) {
1995 return NULL;
1996 }
1997
1998 /* for performance reason, we do not lock/unlock the global TLS map
1999 * to check that the key is properly allocated. if the key was not
2000 * allocated, the value read from the TLS should always be NULL
2001 * due to pthread_key_delete() clearing the values for all threads.
2002 */
2003 return (void *)(((unsigned *)__get_tls())[key]);
2004}
2005
2006/* Posix mandates that this be defined in <limits.h> but we don't have
2007 * it just yet.
2008 */
2009#ifndef PTHREAD_DESTRUCTOR_ITERATIONS
2010# define PTHREAD_DESTRUCTOR_ITERATIONS 4
2011#endif
2012
2013/* this function is called from pthread_exit() to remove all TLS key data
2014 * from this thread's TLS area. this must call the destructor of all keys
2015 * that have a non-NULL data value (and a non-NULL destructor).
2016 *
2017 * because destructors can do funky things like deleting/creating other
2018 * keys, we need to implement this in a loop
2019 */
2020static void pthread_key_clean_all(void)
2021{
2022 tlsmap_t* map;
2023 void** tls = (void**)__get_tls();
2024 int rounds = PTHREAD_DESTRUCTOR_ITERATIONS;
2025
2026 map = tlsmap_lock();
2027
2028 for (rounds = PTHREAD_DESTRUCTOR_ITERATIONS; rounds > 0; rounds--)
2029 {
2030 int kk, count = 0;
2031
2032 for (kk = TLSMAP_START; kk < TLSMAP_SIZE; kk++) {
2033 if ( tlsmap_test(map, kk) )
2034 {
2035 void* data = tls[kk];
2036 tls_dtor_t dtor = map->dtors[kk];
2037
2038 if (data != NULL && dtor != NULL)
2039 {
2040 /* we need to clear the key data now, this will prevent the
2041 * destructor (or a later one) from seeing the old value if
2042 * it calls pthread_getspecific() for some odd reason
2043 *
2044 * we do not do this if 'dtor == NULL' just in case another
2045 * destructor function might be responsible for manually
2046 * releasing the corresponding data.
2047 */
2048 tls[kk] = NULL;
2049
2050 /* because the destructor is free to call pthread_key_create
2051 * and/or pthread_key_delete, we need to temporarily unlock
2052 * the TLS map
2053 */
2054 tlsmap_unlock(map);
2055 (*dtor)(data);
2056 map = tlsmap_lock();
2057
2058 count += 1;
2059 }
2060 }
2061 }
2062
2063 /* if we didn't call any destructor, there is no need to check the
2064 * TLS data again
2065 */
2066 if (count == 0)
2067 break;
2068 }
2069 tlsmap_unlock(map);
2070}
2071
2072// man says this should be in <linux/unistd.h>, but it isn't
Jeff Brown10c8ce52011-11-18 15:17:07 -08002073extern int tgkill(int tgid, int tid, int sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002074
2075int pthread_kill(pthread_t tid, int sig)
2076{
2077 int ret;
2078 int old_errno = errno;
2079 pthread_internal_t * thread = (pthread_internal_t *)tid;
2080
Jeff Brown10c8ce52011-11-18 15:17:07 -08002081 ret = tgkill(getpid(), thread->kernel_id, sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002082 if (ret < 0) {
2083 ret = errno;
2084 errno = old_errno;
2085 }
2086
2087 return ret;
2088}
2089
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01002090/* Despite the fact that our kernel headers define sigset_t explicitly
2091 * as a 32-bit integer, the kernel system call really expects a 64-bit
2092 * bitmap for the signal set, or more exactly an array of two-32-bit
2093 * values (see $KERNEL/arch/$ARCH/include/asm/signal.h for details).
2094 *
2095 * Unfortunately, we cannot fix the sigset_t definition without breaking
2096 * the C library ABI, so perform a little runtime translation here.
2097 */
2098typedef union {
2099 sigset_t bionic;
2100 uint32_t kernel[2];
2101} kernel_sigset_t;
2102
2103/* this is a private syscall stub */
2104extern int __rt_sigprocmask(int, const kernel_sigset_t *, kernel_sigset_t *, size_t);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002105
2106int pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
2107{
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08002108 /* pthread_sigmask must return the error code, but the syscall
2109 * will set errno instead and return 0/-1
2110 */
2111 int ret, old_errno = errno;
2112
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01002113 /* We must convert *set into a kernel_sigset_t */
2114 kernel_sigset_t in_set, *in_set_ptr;
2115 kernel_sigset_t out_set;
2116
Bruce Bearee4a21c82011-12-05 11:25:37 -08002117 in_set.kernel[0] = in_set.kernel[1] = 0;
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01002118 out_set.kernel[0] = out_set.kernel[1] = 0;
2119
2120 /* 'in_set_ptr' is the second parameter to __rt_sigprocmask. It must be NULL
2121 * if 'set' is NULL to ensure correct semantics (which in this case would
2122 * be to ignore 'how' and return the current signal set into 'oset'.
David 'Digit' Turner5c8c00a2010-12-20 15:58:06 +01002123 */
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01002124 if (set == NULL) {
2125 in_set_ptr = NULL;
2126 } else {
2127 in_set.bionic = *set;
2128 in_set_ptr = &in_set;
2129 }
2130
2131 ret = __rt_sigprocmask(how, in_set_ptr, &out_set, sizeof(kernel_sigset_t));
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08002132 if (ret < 0)
2133 ret = errno;
2134
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01002135 if (oset)
2136 *oset = out_set.bionic;
2137
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08002138 errno = old_errno;
2139 return ret;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002140}
2141
2142
2143int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
2144{
2145 const int CLOCK_IDTYPE_BITS = 3;
2146 pthread_internal_t* thread = (pthread_internal_t*)tid;
2147
2148 if (!thread)
2149 return ESRCH;
2150
2151 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
2152 return 0;
2153}
2154
2155
2156/* NOTE: this implementation doesn't support a init function that throws a C++ exception
2157 * or calls fork()
2158 */
2159int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
2160{
Wink Savilleccc3d1e2010-06-28 11:41:16 -07002161 static pthread_mutex_t once_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07002162 volatile pthread_once_t* ocptr = once_control;
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002163 pthread_once_t value;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002164
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002165 /* PTHREAD_ONCE_INIT is 0, we use the following bit flags
2166 *
2167 * bit 0 set -> initialization is under way
2168 * bit 1 set -> initialization is complete
2169 */
2170#define ONCE_INITIALIZING (1 << 0)
2171#define ONCE_COMPLETED (1 << 1)
2172
2173 /* First check if the once is already initialized. This will be the common
2174 * case and we want to make this as fast as possible. Note that this still
2175 * requires a load_acquire operation here to ensure that all the
2176 * stores performed by the initialization function are observable on
2177 * this CPU after we exit.
2178 */
2179 if (__likely((*ocptr & ONCE_COMPLETED) != 0)) {
2180 ANDROID_MEMBAR_FULL();
2181 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002182 }
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002183
2184 for (;;) {
2185 /* Try to atomically set the INITIALIZING flag.
2186 * This requires a cmpxchg loop, and we may need
2187 * to exit prematurely if we detect that
2188 * COMPLETED is now set.
2189 */
2190 int32_t oldval, newval;
2191
2192 do {
2193 oldval = *ocptr;
2194 if ((oldval & ONCE_COMPLETED) != 0)
2195 break;
2196
2197 newval = oldval | ONCE_INITIALIZING;
2198 } while (__bionic_cmpxchg(oldval, newval, ocptr) != 0);
2199
2200 if ((oldval & ONCE_COMPLETED) != 0) {
2201 /* We detected that COMPLETED was set while in our loop */
2202 ANDROID_MEMBAR_FULL();
2203 return 0;
2204 }
2205
2206 if ((oldval & ONCE_INITIALIZING) == 0) {
2207 /* We got there first, we can jump out of the loop to
2208 * handle the initialization */
2209 break;
2210 }
2211
2212 /* Another thread is running the initialization and hasn't completed
2213 * yet, so wait for it, then try again. */
2214 __futex_wait_ex(ocptr, 0, oldval, NULL);
2215 }
2216
2217 /* call the initialization function. */
2218 (*init_routine)();
2219
2220 /* Do a store_release indicating that initialization is complete */
2221 ANDROID_MEMBAR_FULL();
2222 *ocptr = ONCE_COMPLETED;
2223
2224 /* Wake up any waiters, if any */
2225 __futex_wake_ex(ocptr, 0, INT_MAX);
2226
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002227 return 0;
2228}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03002229
2230/* This value is not exported by kernel headers, so hardcode it here */
2231#define MAX_TASK_COMM_LEN 16
2232#define TASK_COMM_FMT "/proc/self/task/%u/comm"
2233
2234int pthread_setname_np(pthread_t thid, const char *thname)
2235{
2236 size_t thname_len;
2237 int saved_errno, ret;
2238
2239 if (thid == 0 || thname == NULL)
2240 return EINVAL;
2241
2242 thname_len = strlen(thname);
2243 if (thname_len >= MAX_TASK_COMM_LEN)
2244 return ERANGE;
2245
2246 saved_errno = errno;
2247 if (thid == pthread_self())
2248 {
2249 ret = prctl(PR_SET_NAME, (unsigned long)thname, 0, 0, 0) ? errno : 0;
2250 }
2251 else
2252 {
2253 /* Have to change another thread's name */
2254 pthread_internal_t *thread = (pthread_internal_t *)thid;
2255 char comm_name[sizeof(TASK_COMM_FMT) + 8];
2256 ssize_t n;
2257 int fd;
2258
2259 snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, (unsigned int)thread->kernel_id);
2260 fd = open(comm_name, O_RDWR);
2261 if (fd == -1)
2262 {
2263 ret = errno;
2264 goto exit;
2265 }
2266 n = TEMP_FAILURE_RETRY(write(fd, thname, thname_len));
2267 close(fd);
2268
2269 if (n < 0)
2270 ret = errno;
2271 else if ((size_t)n != thname_len)
2272 ret = EIO;
2273 else
2274 ret = 0;
2275 }
2276exit:
2277 errno = saved_errno;
2278 return ret;
2279}
Glenn Kastend53cae02011-07-11 15:41:28 -07002280
2281/* Return the kernel thread ID for a pthread.
2282 * This is only defined for implementations where pthread <-> kernel is 1:1, which this is.
2283 * Not the same as pthread_getthreadid_np, which is commonly defined to be opaque.
2284 * Internal, not an NDK API.
2285 */
2286
2287pid_t __pthread_gettid(pthread_t thid)
2288{
2289 pthread_internal_t* thread = (pthread_internal_t*)thid;
2290 return thread->kernel_id;
2291}
Jean-Baptiste Querufaca92f2012-03-26 15:25:19 -07002292
2293int __pthread_settid(pthread_t thid, pid_t tid)
2294{
2295 if (thid == 0)
2296 return EINVAL;
2297
2298 pthread_internal_t* thread = (pthread_internal_t*)thid;
2299 thread->kernel_id = tid;
2300
2301 return 0;
2302}