blob: c075d51e19b230dff38c3019d997c368be841979 [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
55extern int __pthread_clone(int (*fn)(void*), void *child_stack, int flags, void *arg);
56extern void _exit_with_stack_teardown(void * stackBase, int stackSize, int retCode);
57extern void _exit_thread(int retCode);
58extern int __set_errno(int);
59
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -070060int __futex_wake_ex(volatile void *ftx, int pshared, int val)
61{
62 return __futex_syscall3(ftx, pshared ? FUTEX_WAKE : FUTEX_WAKE_PRIVATE, val);
63}
64
65int __futex_wait_ex(volatile void *ftx, int pshared, int val, const struct timespec *timeout)
66{
67 return __futex_syscall4(ftx, pshared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE, val, timeout);
68}
69
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -070070#define __likely(cond) __builtin_expect(!!(cond), 1)
71#define __unlikely(cond) __builtin_expect(!!(cond), 0)
72
Bruce Beare8e551a62011-03-28 09:47:35 -070073#ifdef __i386__
74#define ATTRIBUTES __attribute__((noinline)) __attribute__((fastcall))
75#else
76#define ATTRIBUTES __attribute__((noinline))
77#endif
78
79void ATTRIBUTES _thread_created_hook(pid_t thread_id);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080080
Pierre Peifferd0c884d2012-02-22 16:40:15 +010081static const int kPthreadInitFailed = 1;
82
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080083#define PTHREAD_ATTR_FLAG_DETACHED 0x00000001
84#define PTHREAD_ATTR_FLAG_USER_STACK 0x00000002
85
86#define DEFAULT_STACKSIZE (1024 * 1024)
87#define STACKBASE 0x10000000
88
89static uint8_t * gStackBase = (uint8_t *)STACKBASE;
90
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
132static void
133_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
144pthread_internal_t*
145__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
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100205int _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 -0800206{
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100207 int error = 0;
208
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800209 if (attr == NULL) {
210 thread->attr = gDefaultPthreadAttr;
211 } else {
212 thread->attr = *attr;
213 }
214 thread->attr.stack_base = stack_base;
215 thread->kernel_id = kernel_id;
216
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100217 // Make a note of whether the user supplied this stack (so we know whether or not to free it).
218 if (attr->stack_base == stack_base) {
219 thread->attr.flags |= PTHREAD_ATTR_FLAG_USER_STACK;
220 }
221
222 // Set the scheduling policy/priority of the thread.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800223 if (thread->attr.sched_policy != SCHED_NORMAL) {
224 struct sched_param param;
225 param.sched_priority = thread->attr.sched_priority;
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100226 if (sched_setscheduler(kernel_id, thread->attr.sched_policy, &param) == -1) {
227 error = errno;
228 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800229 }
230
231 pthread_cond_init(&thread->join_cond, NULL);
232 thread->join_count = 0;
233
234 thread->cleanup_stack = NULL;
235
236 _pthread_internal_add(thread);
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100237 return error;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800238}
239
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800240static void *mkstack(size_t size, size_t guard_size)
241{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800242 pthread_mutex_lock(&mmap_lock);
243
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100244 int prot = PROT_READ | PROT_WRITE;
245 int flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE;
246 void* stack = mmap((void*) gStackBase, size, prot, flags, -1, 0);
247 if (stack == MAP_FAILED) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800248 stack = NULL;
249 goto done;
250 }
251
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100252 if (mprotect(stack, guard_size, PROT_NONE) == -1) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800253 munmap(stack, size);
254 stack = NULL;
255 goto done;
256 }
257
258done:
259 pthread_mutex_unlock(&mmap_lock);
260 return stack;
261}
262
263/*
Andy McFaddene2ac8982010-09-02 13:34:53 -0700264 * Create a new thread. The thread's stack is laid out like so:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800265 *
266 * +---------------------------+
267 * | pthread_internal_t |
268 * +---------------------------+
269 * | |
270 * | TLS area |
271 * | |
272 * +---------------------------+
273 * | |
274 * . .
275 * . stack area .
276 * . .
277 * | |
278 * +---------------------------+
279 * | guard page |
280 * +---------------------------+
281 *
282 * note that TLS[0] must be a pointer to itself, this is required
283 * by the thread-local storage implementation of the x86 Linux
284 * kernel, where the TLS pointer is read by reading fs:[0]
285 */
286int pthread_create(pthread_t *thread_out, pthread_attr_t const * attr,
287 void *(*start_routine)(void *), void * arg)
288{
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100289 int old_errno = errno;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800290
291 /* this will inform the rest of the C library that at least one thread
292 * was created. this will enforce certain functions to acquire/release
293 * locks (e.g. atexit()) to protect shared global structures.
294 *
295 * this works because pthread_create() is not called by the C library
296 * initialization routine that sets up the main thread's data structures.
297 */
298 __isthreaded = 1;
299
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100300 pthread_internal_t* thread = calloc(sizeof(*thread), 1);
301 if (thread == NULL) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800302 return ENOMEM;
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100303 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800304
305 if (attr == NULL) {
306 attr = &gDefaultPthreadAttr;
307 }
308
309 // make sure the stack is PAGE_SIZE aligned
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100310 size_t stack_size = (attr->stack_size + (PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
311 uint8_t* stack = attr->stack_base;
312 if (stack == NULL) {
313 stack = mkstack(stack_size, attr->guard_size);
314 if (stack == NULL) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800315 _pthread_internal_free(thread);
316 return ENOMEM;
317 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800318 }
319
320 // Make room for TLS
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100321 void** tls = (void**)(stack + stack_size - BIONIC_TLS_SLOTS*sizeof(void*));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800322
323 // Create a mutex for the thread in TLS_SLOT_SELF to wait on once it starts so we can keep
324 // it from doing anything until after we notify the debugger about it
Andy McFaddene2ac8982010-09-02 13:34:53 -0700325 //
326 // This also provides the memory barrier we need to ensure that all
327 // memory accesses previously performed by this thread are visible to
328 // the new thread.
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100329 pthread_mutex_t* start_mutex = (pthread_mutex_t*) &tls[TLS_SLOT_SELF];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800330 pthread_mutex_init(start_mutex, NULL);
331 pthread_mutex_lock(start_mutex);
332
333 tls[TLS_SLOT_THREAD_ID] = thread;
334
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100335 int flags = CLONE_FILES | CLONE_FS | CLONE_VM | CLONE_SIGHAND |
336 CLONE_THREAD | CLONE_SYSVSEM | CLONE_DETACHED;
337 int tid = __pthread_clone((int(*)(void*))start_routine, tls, flags, arg);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800338
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100339 if (tid < 0) {
340 int clone_errno = errno;
341 pthread_mutex_unlock(start_mutex);
342 if (stack != attr->stack_base) {
343 munmap(stack, stack_size);
344 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800345 _pthread_internal_free(thread);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800346 errno = old_errno;
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100347 return clone_errno;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800348 }
349
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100350 int init_errno = _init_thread(thread, tid, (pthread_attr_t*) attr, stack);
351 if (init_errno != 0) {
352 // Mark the thread detached and let its __thread_entry run to
353 // completion. (It'll just exit immediately, cleaning up its resources.)
354 thread->internal_flags |= kPthreadInitFailed;
355 thread->attr.flags |= PTHREAD_ATTR_FLAG_DETACHED;
356 pthread_mutex_unlock(start_mutex);
357 errno = old_errno;
358 return init_errno;
359 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800360
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100361 // Notify any debuggers about the new thread.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800362 pthread_mutex_lock(&gDebuggerNotificationLock);
363 _thread_created_hook(tid);
364 pthread_mutex_unlock(&gDebuggerNotificationLock);
365
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100366 // Let the thread run.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800367 pthread_mutex_unlock(start_mutex);
368
Pierre Peifferd0c884d2012-02-22 16:40:15 +0100369 *thread_out = (pthread_t) thread;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800370 return 0;
371}
372
373
374int pthread_attr_init(pthread_attr_t * attr)
375{
376 *attr = gDefaultPthreadAttr;
377 return 0;
378}
379
380int pthread_attr_destroy(pthread_attr_t * attr)
381{
382 memset(attr, 0x42, sizeof(pthread_attr_t));
383 return 0;
384}
385
386int pthread_attr_setdetachstate(pthread_attr_t * attr, int state)
387{
388 if (state == PTHREAD_CREATE_DETACHED) {
389 attr->flags |= PTHREAD_ATTR_FLAG_DETACHED;
390 } else if (state == PTHREAD_CREATE_JOINABLE) {
391 attr->flags &= ~PTHREAD_ATTR_FLAG_DETACHED;
392 } else {
393 return EINVAL;
394 }
395 return 0;
396}
397
398int pthread_attr_getdetachstate(pthread_attr_t const * attr, int * state)
399{
400 *state = (attr->flags & PTHREAD_ATTR_FLAG_DETACHED)
401 ? PTHREAD_CREATE_DETACHED
402 : PTHREAD_CREATE_JOINABLE;
403 return 0;
404}
405
406int pthread_attr_setschedpolicy(pthread_attr_t * attr, int policy)
407{
408 attr->sched_policy = policy;
409 return 0;
410}
411
412int pthread_attr_getschedpolicy(pthread_attr_t const * attr, int * policy)
413{
414 *policy = attr->sched_policy;
415 return 0;
416}
417
418int pthread_attr_setschedparam(pthread_attr_t * attr, struct sched_param const * param)
419{
420 attr->sched_priority = param->sched_priority;
421 return 0;
422}
423
424int pthread_attr_getschedparam(pthread_attr_t const * attr, struct sched_param * param)
425{
426 param->sched_priority = attr->sched_priority;
427 return 0;
428}
429
430int pthread_attr_setstacksize(pthread_attr_t * attr, size_t stack_size)
431{
432 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
433 return EINVAL;
434 }
435 attr->stack_size = stack_size;
436 return 0;
437}
438
439int pthread_attr_getstacksize(pthread_attr_t const * attr, size_t * stack_size)
440{
441 *stack_size = attr->stack_size;
442 return 0;
443}
444
445int pthread_attr_setstackaddr(pthread_attr_t * attr, void * stack_addr)
446{
447#if 1
448 // It's not clear if this is setting the top or bottom of the stack, so don't handle it for now.
449 return ENOSYS;
450#else
451 if ((uint32_t)stack_addr & (PAGE_SIZE - 1)) {
452 return EINVAL;
453 }
454 attr->stack_base = stack_addr;
455 return 0;
456#endif
457}
458
459int pthread_attr_getstackaddr(pthread_attr_t const * attr, void ** stack_addr)
460{
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700461 *stack_addr = (char*)attr->stack_base + attr->stack_size;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800462 return 0;
463}
464
465int pthread_attr_setstack(pthread_attr_t * attr, void * stack_base, size_t stack_size)
466{
467 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
468 return EINVAL;
469 }
470 if ((uint32_t)stack_base & (PAGE_SIZE - 1)) {
471 return EINVAL;
472 }
473 attr->stack_base = stack_base;
474 attr->stack_size = stack_size;
475 return 0;
476}
477
478int pthread_attr_getstack(pthread_attr_t const * attr, void ** stack_base, size_t * stack_size)
479{
480 *stack_base = attr->stack_base;
481 *stack_size = attr->stack_size;
482 return 0;
483}
484
485int pthread_attr_setguardsize(pthread_attr_t * attr, size_t guard_size)
486{
487 if (guard_size & (PAGE_SIZE - 1) || guard_size < PAGE_SIZE) {
488 return EINVAL;
489 }
490
491 attr->guard_size = guard_size;
492 return 0;
493}
494
495int pthread_attr_getguardsize(pthread_attr_t const * attr, size_t * guard_size)
496{
497 *guard_size = attr->guard_size;
498 return 0;
499}
500
501int pthread_getattr_np(pthread_t thid, pthread_attr_t * attr)
502{
503 pthread_internal_t * thread = (pthread_internal_t *)thid;
504 *attr = thread->attr;
505 return 0;
506}
507
508int pthread_attr_setscope(pthread_attr_t *attr, int scope)
509{
510 if (scope == PTHREAD_SCOPE_SYSTEM)
511 return 0;
512 if (scope == PTHREAD_SCOPE_PROCESS)
513 return ENOTSUP;
514
515 return EINVAL;
516}
517
518int pthread_attr_getscope(pthread_attr_t const *attr)
519{
520 return PTHREAD_SCOPE_SYSTEM;
521}
522
523
524/* CAVEAT: our implementation of pthread_cleanup_push/pop doesn't support C++ exceptions
525 * and thread cancelation
526 */
527
528void __pthread_cleanup_push( __pthread_cleanup_t* c,
529 __pthread_cleanup_func_t routine,
530 void* arg )
531{
532 pthread_internal_t* thread = __get_thread();
533
534 c->__cleanup_routine = routine;
535 c->__cleanup_arg = arg;
536 c->__cleanup_prev = thread->cleanup_stack;
537 thread->cleanup_stack = c;
538}
539
540void __pthread_cleanup_pop( __pthread_cleanup_t* c, int execute )
541{
542 pthread_internal_t* thread = __get_thread();
543
544 thread->cleanup_stack = c->__cleanup_prev;
545 if (execute)
546 c->__cleanup_routine(c->__cleanup_arg);
547}
548
549/* used by pthread_exit() to clean all TLS keys of the current thread */
550static void pthread_key_clean_all(void);
551
552void pthread_exit(void * retval)
553{
554 pthread_internal_t* thread = __get_thread();
555 void* stack_base = thread->attr.stack_base;
556 int stack_size = thread->attr.stack_size;
557 int user_stack = (thread->attr.flags & PTHREAD_ATTR_FLAG_USER_STACK) != 0;
Jack Rene480fc82011-09-21 12:44:11 +0200558 sigset_t mask;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800559
560 // call the cleanup handlers first
561 while (thread->cleanup_stack) {
562 __pthread_cleanup_t* c = thread->cleanup_stack;
563 thread->cleanup_stack = c->__cleanup_prev;
564 c->__cleanup_routine(c->__cleanup_arg);
565 }
566
567 // call the TLS destructors, it is important to do that before removing this
568 // thread from the global list. this will ensure that if someone else deletes
569 // a TLS key, the corresponding value will be set to NULL in this thread's TLS
570 // space (see pthread_key_delete)
571 pthread_key_clean_all();
572
573 // if the thread is detached, destroy the pthread_internal_t
574 // otherwise, keep it in memory and signal any joiners
575 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
576 _pthread_internal_remove(thread);
577 _pthread_internal_free(thread);
578 } else {
Bjorn Andersson0753dc62012-05-03 17:12:39 -0700579 pthread_mutex_lock(&gThreadListLock);
580
581 /* make sure that the thread struct doesn't have stale pointers to a stack that
582 * will be unmapped after the exit call below.
583 */
584 if (!user_stack) {
585 thread->attr.stack_base = NULL;
586 thread->attr.stack_size = 0;
587 thread->tls = NULL;
588 }
589
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800590 /* the join_count field is used to store the number of threads waiting for
591 * the termination of this thread with pthread_join(),
592 *
593 * if it is positive we need to signal the waiters, and we do not touch
594 * the count (it will be decremented by the waiters, the last one will
595 * also remove/free the thread structure
596 *
597 * if it is zero, we set the count value to -1 to indicate that the
598 * thread is in 'zombie' state: it has stopped executing, and its stack
599 * is gone (as well as its TLS area). when another thread calls pthread_join()
600 * on it, it will immediately free the thread and return.
601 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800602 thread->return_value = retval;
603 if (thread->join_count > 0) {
604 pthread_cond_broadcast(&thread->join_cond);
605 } else {
606 thread->join_count = -1; /* zombie thread */
607 }
608 pthread_mutex_unlock(&gThreadListLock);
609 }
610
Jack Rene480fc82011-09-21 12:44:11 +0200611 sigfillset(&mask);
612 sigdelset(&mask, SIGSEGV);
613 (void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *)NULL);
614
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800615 // destroy the thread stack
616 if (user_stack)
617 _exit_thread((int)retval);
618 else
619 _exit_with_stack_teardown(stack_base, stack_size, (int)retval);
620}
621
622int pthread_join(pthread_t thid, void ** ret_val)
623{
624 pthread_internal_t* thread = (pthread_internal_t*)thid;
625 int count;
626
627 // check that the thread still exists and is not detached
628 pthread_mutex_lock(&gThreadListLock);
629
630 for (thread = gThreadList; thread != NULL; thread = thread->next)
631 if (thread == (pthread_internal_t*)thid)
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200632 goto FoundIt;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800633
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200634 pthread_mutex_unlock(&gThreadListLock);
635 return ESRCH;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800636
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200637FoundIt:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800638 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
639 pthread_mutex_unlock(&gThreadListLock);
640 return EINVAL;
641 }
642
643 /* wait for thread death when needed
644 *
645 * if the 'join_count' is negative, this is a 'zombie' thread that
646 * is already dead and without stack/TLS
647 *
648 * otherwise, we need to increment 'join-count' and wait to be signaled
649 */
650 count = thread->join_count;
651 if (count >= 0) {
652 thread->join_count += 1;
653 pthread_cond_wait( &thread->join_cond, &gThreadListLock );
654 count = --thread->join_count;
655 }
656 if (ret_val)
657 *ret_val = thread->return_value;
658
659 /* remove thread descriptor when we're the last joiner or when the
660 * thread was already a zombie.
661 */
662 if (count <= 0) {
663 _pthread_internal_remove_locked(thread);
664 _pthread_internal_free(thread);
665 }
666 pthread_mutex_unlock(&gThreadListLock);
667 return 0;
668}
669
670int pthread_detach( pthread_t thid )
671{
672 pthread_internal_t* thread;
673 int result = 0;
674 int flags;
675
676 pthread_mutex_lock(&gThreadListLock);
677 for (thread = gThreadList; thread != NULL; thread = thread->next)
678 if (thread == (pthread_internal_t*)thid)
679 goto FoundIt;
680
681 result = ESRCH;
682 goto Exit;
683
684FoundIt:
685 do {
686 flags = thread->attr.flags;
687
688 if ( flags & PTHREAD_ATTR_FLAG_DETACHED ) {
689 /* thread is not joinable ! */
690 result = EINVAL;
691 goto Exit;
692 }
693 }
694 while ( __atomic_cmpxchg( flags, flags | PTHREAD_ATTR_FLAG_DETACHED,
695 (volatile int*)&thread->attr.flags ) != 0 );
696Exit:
697 pthread_mutex_unlock(&gThreadListLock);
698 return result;
699}
700
701pthread_t pthread_self(void)
702{
703 return (pthread_t)__get_thread();
704}
705
706int pthread_equal(pthread_t one, pthread_t two)
707{
708 return (one == two ? 1 : 0);
709}
710
711int pthread_getschedparam(pthread_t thid, int * policy,
712 struct sched_param * param)
713{
714 int old_errno = errno;
715
716 pthread_internal_t * thread = (pthread_internal_t *)thid;
717 int err = sched_getparam(thread->kernel_id, param);
718 if (!err) {
719 *policy = sched_getscheduler(thread->kernel_id);
720 } else {
721 err = errno;
722 errno = old_errno;
723 }
724 return err;
725}
726
727int pthread_setschedparam(pthread_t thid, int policy,
728 struct sched_param const * param)
729{
730 pthread_internal_t * thread = (pthread_internal_t *)thid;
731 int old_errno = errno;
732 int ret;
733
734 ret = sched_setscheduler(thread->kernel_id, policy, param);
735 if (ret < 0) {
736 ret = errno;
737 errno = old_errno;
738 }
739 return ret;
740}
741
742
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800743// mutex lock states
744//
745// 0: unlocked
746// 1: locked, no waiters
747// 2: locked, maybe waiters
748
749/* a mutex is implemented as a 32-bit integer holding the following fields
750 *
751 * bits: name description
752 * 31-16 tid owner thread's kernel id (recursive and errorcheck only)
753 * 15-14 type mutex type
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700754 * 13 shared process-shared flag
755 * 12-2 counter counter of recursive mutexes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800756 * 1-0 state lock state (0, 1 or 2)
757 */
758
759
760#define MUTEX_OWNER(m) (((m)->value >> 16) & 0xffff)
761#define MUTEX_COUNTER(m) (((m)->value >> 2) & 0xfff)
762
763#define MUTEX_TYPE_MASK 0xc000
764#define MUTEX_TYPE_NORMAL 0x0000
765#define MUTEX_TYPE_RECURSIVE 0x4000
766#define MUTEX_TYPE_ERRORCHECK 0x8000
767
768#define MUTEX_COUNTER_SHIFT 2
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700769#define MUTEX_COUNTER_MASK 0x1ffc
770#define MUTEX_SHARED_MASK 0x2000
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800771
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700772/* a mutex attribute holds the following fields
773 *
774 * bits: name description
775 * 0-3 type type of mutex
776 * 4 shared process-shared flag
777 */
778#define MUTEXATTR_TYPE_MASK 0x000f
779#define MUTEXATTR_SHARED_MASK 0x0010
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800780
781
782int pthread_mutexattr_init(pthread_mutexattr_t *attr)
783{
784 if (attr) {
785 *attr = PTHREAD_MUTEX_DEFAULT;
786 return 0;
787 } else {
788 return EINVAL;
789 }
790}
791
792int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
793{
794 if (attr) {
795 *attr = -1;
796 return 0;
797 } else {
798 return EINVAL;
799 }
800}
801
802int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
803{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700804 if (attr) {
805 int atype = (*attr & MUTEXATTR_TYPE_MASK);
806
807 if (atype >= PTHREAD_MUTEX_NORMAL &&
808 atype <= PTHREAD_MUTEX_ERRORCHECK) {
809 *type = atype;
810 return 0;
811 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800812 }
813 return EINVAL;
814}
815
816int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
817{
818 if (attr && type >= PTHREAD_MUTEX_NORMAL &&
819 type <= PTHREAD_MUTEX_ERRORCHECK ) {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700820 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800821 return 0;
822 }
823 return EINVAL;
824}
825
826/* process-shared mutexes are not supported at the moment */
827
828int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
829{
830 if (!attr)
831 return EINVAL;
832
Mathias Agopianb7681162009-07-13 22:00:33 -0700833 switch (pshared) {
834 case PTHREAD_PROCESS_PRIVATE:
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700835 *attr &= ~MUTEXATTR_SHARED_MASK;
836 return 0;
837
Mathias Agopianb7681162009-07-13 22:00:33 -0700838 case PTHREAD_PROCESS_SHARED:
839 /* our current implementation of pthread actually supports shared
840 * mutexes but won't cleanup if a process dies with the mutex held.
841 * Nevertheless, it's better than nothing. Shared mutexes are used
842 * by surfaceflinger and audioflinger.
843 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700844 *attr |= MUTEXATTR_SHARED_MASK;
Mathias Agopianb7681162009-07-13 22:00:33 -0700845 return 0;
846 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700847 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800848}
849
850int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
851{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700852 if (!attr || !pshared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800853 return EINVAL;
854
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700855 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED
856 : PTHREAD_PROCESS_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800857 return 0;
858}
859
860int pthread_mutex_init(pthread_mutex_t *mutex,
861 const pthread_mutexattr_t *attr)
862{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700863 int value = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800864
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700865 if (mutex == NULL)
866 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800867
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700868 if (__likely(attr == NULL)) {
869 mutex->value = MUTEX_TYPE_NORMAL;
870 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800871 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700872
873 if ((*attr & MUTEXATTR_SHARED_MASK) != 0)
874 value |= MUTEX_SHARED_MASK;
875
876 switch (*attr & MUTEXATTR_TYPE_MASK) {
877 case PTHREAD_MUTEX_NORMAL:
878 value |= MUTEX_TYPE_NORMAL;
879 break;
880 case PTHREAD_MUTEX_RECURSIVE:
881 value |= MUTEX_TYPE_RECURSIVE;
882 break;
883 case PTHREAD_MUTEX_ERRORCHECK:
884 value |= MUTEX_TYPE_ERRORCHECK;
885 break;
886 default:
887 return EINVAL;
888 }
889
890 mutex->value = value;
891 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800892}
893
894int pthread_mutex_destroy(pthread_mutex_t *mutex)
895{
David 'Digit' Turnera02b93b2010-06-28 14:20:22 -0700896 int ret;
897
898 /* use trylock to ensure that the mutex value is
899 * valid and is not already locked. */
900 ret = pthread_mutex_trylock(mutex);
901 if (ret != 0)
902 return ret;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700903
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800904 mutex->value = 0xdead10cc;
905 return 0;
906}
907
908
909/*
910 * Lock a non-recursive mutex.
911 *
912 * As noted above, there are three states:
913 * 0 (unlocked, no contention)
914 * 1 (locked, no contention)
915 * 2 (locked, contention)
916 *
917 * Non-recursive mutexes don't use the thread-id or counter fields, and the
918 * "type" value is zero, so the only bits that will be set are the ones in
919 * the lock state field.
920 */
921static __inline__ void
922_normal_lock(pthread_mutex_t* mutex)
923{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700924 /* We need to preserve the shared flag during operations */
925 int shared = mutex->value & MUTEX_SHARED_MASK;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800926 /*
927 * The common case is an unlocked mutex, so we begin by trying to
928 * change the lock's state from 0 to 1. __atomic_cmpxchg() returns 0
929 * if it made the swap successfully. If the result is nonzero, this
930 * lock is already held by another thread.
931 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700932 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value ) != 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800933 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800934 * We want to go to sleep until the mutex is available, which
935 * requires promoting it to state 2. We need to swap in the new
936 * state value and then wait until somebody wakes us up.
937 *
938 * __atomic_swap() returns the previous value. We swap 2 in and
939 * see if we got zero back; if so, we have acquired the lock. If
940 * not, another thread still holds the lock and we wait again.
941 *
942 * The second argument to the __futex_wait() call is compared
943 * against the current value. If it doesn't match, __futex_wait()
944 * returns immediately (otherwise, it sleeps for a time specified
945 * by the third argument; 0 means sleep forever). This ensures
946 * that the mutex is in state 2 when we go to sleep on it, which
947 * guarantees a wake-up call.
948 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700949 while (__atomic_swap(shared|2, &mutex->value ) != (shared|0))
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -0700950 __futex_wait_ex(&mutex->value, shared, shared|2, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800951 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700952 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800953}
954
955/*
956 * Release a non-recursive mutex. The caller is responsible for determining
957 * that we are in fact the owner of this lock.
958 */
959static __inline__ void
960_normal_unlock(pthread_mutex_t* mutex)
961{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700962 ANDROID_MEMBAR_FULL();
963
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700964 /* We need to preserve the shared flag during operations */
965 int shared = mutex->value & MUTEX_SHARED_MASK;
966
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800967 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700968 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800969 * to release the lock. __atomic_dec() returns the previous value;
970 * if it wasn't 1 we have to do some additional work.
971 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700972 if (__atomic_dec(&mutex->value) != (shared|1)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800973 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800974 * Start by releasing the lock. The decrement changed it from
975 * "contended lock" to "uncontended lock", which means we still
976 * hold it, and anybody who tries to sneak in will push it back
977 * to state 2.
978 *
979 * Once we set it to zero the lock is up for grabs. We follow
980 * this with a __futex_wake() to ensure that one of the waiting
981 * threads has a chance to grab it.
982 *
983 * This doesn't cause a race with the swap/wait pair in
984 * _normal_lock(), because the __futex_wait() call there will
985 * return immediately if the mutex value isn't 2.
986 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700987 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800988
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800989 /*
990 * Wake up one waiting thread. We don't know which thread will be
991 * woken or when it'll start executing -- futexes make no guarantees
992 * here. There may not even be a thread waiting.
993 *
994 * The newly-woken thread will replace the 0 we just set above
995 * with 2, which means that when it eventually releases the mutex
996 * it will also call FUTEX_WAKE. This results in one extra wake
997 * call whenever a lock is contended, but lets us avoid forgetting
998 * anyone without requiring us to track the number of sleepers.
999 *
1000 * It's possible for another thread to sneak in and grab the lock
1001 * between the zero assignment above and the wake call below. If
1002 * the new thread is "slow" and holds the lock for a while, we'll
1003 * wake up a sleeper, which will swap in a 2 and then go back to
1004 * sleep since the lock is still held. If the new thread is "fast",
1005 * running to completion before we call wake, the thread we
1006 * eventually wake will find an unlocked mutex and will execute.
1007 * Either way we have correct behavior and nobody is orphaned on
1008 * the wait queue.
1009 */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001010 __futex_wake_ex(&mutex->value, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001011 }
1012}
1013
1014static pthread_mutex_t __recursive_lock = PTHREAD_MUTEX_INITIALIZER;
1015
1016static void
1017_recursive_lock(void)
1018{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001019 _normal_lock(&__recursive_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001020}
1021
1022static void
1023_recursive_unlock(void)
1024{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001025 _normal_unlock(&__recursive_lock );
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001026}
1027
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001028int pthread_mutex_lock(pthread_mutex_t *mutex)
1029{
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001030 int mtype, tid, new_lock_type, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001031
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001032 if (__unlikely(mutex == NULL))
1033 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001034
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001035 mtype = (mutex->value & MUTEX_TYPE_MASK);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001036 shared = (mutex->value & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001037
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001038 /* Handle normal case first */
1039 if ( __likely(mtype == MUTEX_TYPE_NORMAL) ) {
1040 _normal_lock(mutex);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001041 return 0;
1042 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001043
1044 /* Do we already own this recursive or error-check mutex ? */
1045 tid = __get_thread()->kernel_id;
1046 if ( tid == MUTEX_OWNER(mutex) )
1047 {
1048 int oldv, counter;
1049
1050 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1051 /* trying to re-lock a mutex we already acquired */
1052 return EDEADLK;
1053 }
1054 /*
1055 * We own the mutex, but other threads are able to change
1056 * the contents (e.g. promoting it to "contended"), so we
1057 * need to hold the global lock.
1058 */
1059 _recursive_lock();
1060 oldv = mutex->value;
1061 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1062 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1063 _recursive_unlock();
1064 return 0;
1065 }
1066
1067 /* We don't own the mutex, so try to get it.
1068 *
1069 * First, we try to change its state from 0 to 1, if this
1070 * doesn't work, try to change it to state 2.
1071 */
1072 new_lock_type = 1;
1073
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001074 /* compute futex wait opcode and restore shared flag in mtype */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001075 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001076
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001077 for (;;) {
1078 int oldv;
1079
1080 _recursive_lock();
1081 oldv = mutex->value;
1082 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1083 mutex->value = ((tid << 16) | mtype | new_lock_type);
1084 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1085 oldv ^= 3;
1086 mutex->value = oldv;
1087 }
1088 _recursive_unlock();
1089
1090 if (oldv == mtype)
1091 break;
1092
1093 /*
1094 * The lock was held, possibly contended by others. From
1095 * now on, if we manage to acquire the lock, we have to
1096 * assume that others are still contending for it so that
1097 * we'll wake them when we unlock it.
1098 */
1099 new_lock_type = 2;
1100
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001101 __futex_wait_ex(&mutex->value, shared, oldv, NULL);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001102 }
1103 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001104}
1105
1106
1107int pthread_mutex_unlock(pthread_mutex_t *mutex)
1108{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001109 int mtype, tid, oldv, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001110
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001111 if (__unlikely(mutex == NULL))
1112 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001113
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001114 mtype = (mutex->value & MUTEX_TYPE_MASK);
1115 shared = (mutex->value & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001116
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001117 /* Handle common case first */
1118 if (__likely(mtype == MUTEX_TYPE_NORMAL)) {
1119 _normal_unlock(mutex);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001120 return 0;
1121 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001122
1123 /* Do we already own this recursive or error-check mutex ? */
1124 tid = __get_thread()->kernel_id;
1125 if ( tid != MUTEX_OWNER(mutex) )
1126 return EPERM;
1127
1128 /* We do, decrement counter or release the mutex if it is 0 */
1129 _recursive_lock();
1130 oldv = mutex->value;
1131 if (oldv & MUTEX_COUNTER_MASK) {
1132 mutex->value = oldv - (1 << MUTEX_COUNTER_SHIFT);
1133 oldv = 0;
1134 } else {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001135 mutex->value = shared | mtype;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001136 }
1137 _recursive_unlock();
1138
1139 /* Wake one waiting thread, if any */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001140 if ((oldv & 3) == 2) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001141 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001142 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001143 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001144}
1145
1146
1147int pthread_mutex_trylock(pthread_mutex_t *mutex)
1148{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001149 int mtype, tid, oldv, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001150
1151 if (__unlikely(mutex == NULL))
1152 return EINVAL;
1153
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001154 mtype = (mutex->value & MUTEX_TYPE_MASK);
1155 shared = (mutex->value & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001156
1157 /* Handle common case first */
1158 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001159 {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001160 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
1161 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001162 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001163 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001164
1165 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001166 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001167
1168 /* Do we already own this recursive or error-check mutex ? */
1169 tid = __get_thread()->kernel_id;
1170 if ( tid == MUTEX_OWNER(mutex) )
1171 {
1172 int counter;
1173
1174 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1175 /* already locked by ourselves */
1176 return EDEADLK;
1177 }
1178
1179 _recursive_lock();
1180 oldv = mutex->value;
1181 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1182 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1183 _recursive_unlock();
1184 return 0;
1185 }
1186
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001187 /* Restore sharing bit in mtype */
1188 mtype |= shared;
1189
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001190 /* Try to lock it, just once. */
1191 _recursive_lock();
1192 oldv = mutex->value;
1193 if (oldv == mtype) /* uncontended released lock => state 1 */
1194 mutex->value = ((tid << 16) | mtype | 1);
1195 _recursive_unlock();
1196
1197 if (oldv != mtype)
1198 return EBUSY;
1199
1200 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001201}
1202
1203
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001204/* initialize 'ts' with the difference between 'abstime' and the current time
1205 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
1206 */
1207static int
1208__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
1209{
1210 clock_gettime(clock, ts);
1211 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
1212 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
1213 if (ts->tv_nsec < 0) {
1214 ts->tv_sec--;
1215 ts->tv_nsec += 1000000000;
1216 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001217 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001218 return -1;
1219
1220 return 0;
1221}
1222
1223/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1224 * milliseconds.
1225 */
1226static void
1227__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1228{
1229 clock_gettime(clock, abstime);
1230 abstime->tv_sec += msecs/1000;
1231 abstime->tv_nsec += (msecs%1000)*1000000;
1232 if (abstime->tv_nsec >= 1000000000) {
1233 abstime->tv_sec++;
1234 abstime->tv_nsec -= 1000000000;
1235 }
1236}
1237
1238int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1239{
1240 clockid_t clock = CLOCK_MONOTONIC;
1241 struct timespec abstime;
1242 struct timespec ts;
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001243 int mtype, tid, oldv, new_lock_type, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001244
1245 /* compute absolute expiration time */
1246 __timespec_to_relative_msec(&abstime, msecs, clock);
1247
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001248 if (__unlikely(mutex == NULL))
1249 return EINVAL;
1250
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001251 mtype = (mutex->value & MUTEX_TYPE_MASK);
1252 shared = (mutex->value & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001253
1254 /* Handle common case first */
1255 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001256 {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001257 /* fast path for uncontended lock */
1258 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
1259 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001260 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001261 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001262
1263 /* loop while needed */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001264 while (__atomic_swap(shared|2, &mutex->value) != (shared|0)) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001265 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1266 return EBUSY;
1267
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001268 __futex_wait_ex(&mutex->value, shared, shared|2, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001269 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001270 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001271 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001272 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001273
1274 /* Do we already own this recursive or error-check mutex ? */
1275 tid = __get_thread()->kernel_id;
1276 if ( tid == MUTEX_OWNER(mutex) )
1277 {
1278 int oldv, counter;
1279
1280 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1281 /* already locked by ourselves */
1282 return EDEADLK;
1283 }
1284
1285 _recursive_lock();
1286 oldv = mutex->value;
1287 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1288 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1289 _recursive_unlock();
1290 return 0;
1291 }
1292
1293 /* We don't own the mutex, so try to get it.
1294 *
1295 * First, we try to change its state from 0 to 1, if this
1296 * doesn't work, try to change it to state 2.
1297 */
1298 new_lock_type = 1;
1299
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001300 /* Compute wait op and restore sharing bit in mtype */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001301 mtype |= shared;
1302
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001303 for (;;) {
1304 int oldv;
1305 struct timespec ts;
1306
1307 _recursive_lock();
1308 oldv = mutex->value;
1309 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1310 mutex->value = ((tid << 16) | mtype | new_lock_type);
1311 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1312 oldv ^= 3;
1313 mutex->value = oldv;
1314 }
1315 _recursive_unlock();
1316
1317 if (oldv == mtype)
1318 break;
1319
1320 /*
1321 * The lock was held, possibly contended by others. From
1322 * now on, if we manage to acquire the lock, we have to
1323 * assume that others are still contending for it so that
1324 * we'll wake them when we unlock it.
1325 */
1326 new_lock_type = 2;
1327
1328 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1329 return EBUSY;
1330
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001331 __futex_wait_ex(&mutex->value, shared, oldv, &ts);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001332 }
1333 return 0;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001334}
1335
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001336int pthread_condattr_init(pthread_condattr_t *attr)
1337{
1338 if (attr == NULL)
1339 return EINVAL;
1340
1341 *attr = PTHREAD_PROCESS_PRIVATE;
1342 return 0;
1343}
1344
1345int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1346{
1347 if (attr == NULL || pshared == NULL)
1348 return EINVAL;
1349
1350 *pshared = *attr;
1351 return 0;
1352}
1353
1354int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1355{
1356 if (attr == NULL)
1357 return EINVAL;
1358
1359 if (pshared != PTHREAD_PROCESS_SHARED &&
1360 pshared != PTHREAD_PROCESS_PRIVATE)
1361 return EINVAL;
1362
1363 *attr = pshared;
1364 return 0;
1365}
1366
1367int pthread_condattr_destroy(pthread_condattr_t *attr)
1368{
1369 if (attr == NULL)
1370 return EINVAL;
1371
1372 *attr = 0xdeada11d;
1373 return 0;
1374}
1375
1376/* We use one bit in condition variable values as the 'shared' flag
1377 * The rest is a counter.
1378 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001379#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001380#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001381#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1382
1383#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001384
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001385/* XXX *technically* there is a race condition that could allow
1386 * XXX a signal to be missed. If thread A is preempted in _wait()
1387 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001388 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001389 * XXX before thread A is scheduled again and calls futex_wait(),
1390 * XXX then the signal will be lost.
1391 */
1392
1393int pthread_cond_init(pthread_cond_t *cond,
1394 const pthread_condattr_t *attr)
1395{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001396 if (cond == NULL)
1397 return EINVAL;
1398
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001399 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001400
1401 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001402 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001403
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001404 return 0;
1405}
1406
1407int pthread_cond_destroy(pthread_cond_t *cond)
1408{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001409 if (cond == NULL)
1410 return EINVAL;
1411
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001412 cond->value = 0xdeadc04d;
1413 return 0;
1414}
1415
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001416/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001417 * pthread_cond_signal to atomically decrement the counter
1418 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001419 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001420static int
1421__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001422{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001423 long flags;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001424
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001425 if (__unlikely(cond == NULL))
1426 return EINVAL;
1427
1428 flags = (cond->value & ~COND_COUNTER_MASK);
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001429 for (;;) {
1430 long oldval = cond->value;
1431 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1432 | flags;
1433 if (__atomic_cmpxchg(oldval, newval, &cond->value) == 0)
1434 break;
1435 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001436
Andy McFaddene2ac8982010-09-02 13:34:53 -07001437 /*
1438 * Ensure that all memory accesses previously made by this thread are
1439 * visible to the woken thread(s). On the other side, the "wait"
1440 * code will issue any necessary barriers when locking the mutex.
1441 *
1442 * This may not strictly be necessary -- if the caller follows
1443 * recommended practice and holds the mutex before signaling the cond
1444 * var, the mutex ops will provide correct semantics. If they don't
1445 * hold the mutex, they're subject to race conditions anyway.
1446 */
1447 ANDROID_MEMBAR_FULL();
1448
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001449 __futex_wake_ex(&cond->value, COND_IS_SHARED(cond), counter);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001450 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001451}
1452
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001453int pthread_cond_broadcast(pthread_cond_t *cond)
1454{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001455 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001456}
1457
1458int pthread_cond_signal(pthread_cond_t *cond)
1459{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001460 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001461}
1462
1463int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1464{
1465 return pthread_cond_timedwait(cond, mutex, NULL);
1466}
1467
1468int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1469 pthread_mutex_t * mutex,
1470 const struct timespec *reltime)
1471{
1472 int status;
1473 int oldvalue = cond->value;
1474
1475 pthread_mutex_unlock(mutex);
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001476 status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond), oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001477 pthread_mutex_lock(mutex);
1478
1479 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1480 return 0;
1481}
1482
1483int __pthread_cond_timedwait(pthread_cond_t *cond,
1484 pthread_mutex_t * mutex,
1485 const struct timespec *abstime,
1486 clockid_t clock)
1487{
1488 struct timespec ts;
1489 struct timespec * tsp;
1490
1491 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001492 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001493 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001494 tsp = &ts;
1495 } else {
1496 tsp = NULL;
1497 }
1498
1499 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1500}
1501
1502int pthread_cond_timedwait(pthread_cond_t *cond,
1503 pthread_mutex_t * mutex,
1504 const struct timespec *abstime)
1505{
1506 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1507}
1508
1509
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001510/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001511int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1512 pthread_mutex_t * mutex,
1513 const struct timespec *abstime)
1514{
1515 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1516}
1517
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001518int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1519 pthread_mutex_t * mutex,
1520 const struct timespec *abstime)
1521{
1522 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1523}
1524
1525int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1526 pthread_mutex_t * mutex,
1527 const struct timespec *reltime)
1528{
1529 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1530}
1531
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001532int pthread_cond_timeout_np(pthread_cond_t *cond,
1533 pthread_mutex_t * mutex,
1534 unsigned msecs)
1535{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001536 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001537
1538 ts.tv_sec = msecs / 1000;
1539 ts.tv_nsec = (msecs % 1000) * 1000000;
1540
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001541 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001542}
1543
1544
1545
1546/* A technical note regarding our thread-local-storage (TLS) implementation:
1547 *
1548 * There can be up to TLSMAP_SIZE independent TLS keys in a given process,
1549 * though the first TLSMAP_START keys are reserved for Bionic to hold
1550 * special thread-specific variables like errno or a pointer to
1551 * the current thread's descriptor.
1552 *
1553 * while stored in the TLS area, these entries cannot be accessed through
1554 * pthread_getspecific() / pthread_setspecific() and pthread_key_delete()
1555 *
1556 * also, some entries in the key table are pre-allocated (see tlsmap_lock)
1557 * to greatly simplify and speedup some OpenGL-related operations. though the
1558 * initialy value will be NULL on all threads.
1559 *
1560 * you can use pthread_getspecific()/setspecific() on these, and in theory
1561 * you could also call pthread_key_delete() as well, though this would
1562 * probably break some apps.
1563 *
1564 * The 'tlsmap_t' type defined below implements a shared global map of
1565 * currently created/allocated TLS keys and the destructors associated
1566 * with them. You should use tlsmap_lock/unlock to access it to avoid
1567 * any race condition.
1568 *
1569 * the global TLS map simply contains a bitmap of allocated keys, and
1570 * an array of destructors.
1571 *
1572 * each thread has a TLS area that is a simple array of TLSMAP_SIZE void*
1573 * pointers. the TLS area of the main thread is stack-allocated in
1574 * __libc_init_common, while the TLS area of other threads is placed at
1575 * the top of their stack in pthread_create.
1576 *
1577 * when pthread_key_create() is called, it finds the first free key in the
1578 * bitmap, then set it to 1, saving the destructor altogether
1579 *
1580 * when pthread_key_delete() is called. it will erase the key's bitmap bit
1581 * and its destructor, and will also clear the key data in the TLS area of
1582 * all created threads. As mandated by Posix, it is the responsability of
1583 * the caller of pthread_key_delete() to properly reclaim the objects that
1584 * were pointed to by these data fields (either before or after the call).
1585 *
1586 */
1587
1588/* TLS Map implementation
1589 */
1590
1591#define TLSMAP_START (TLS_SLOT_MAX_WELL_KNOWN+1)
1592#define TLSMAP_SIZE BIONIC_TLS_SLOTS
1593#define TLSMAP_BITS 32
1594#define TLSMAP_WORDS ((TLSMAP_SIZE+TLSMAP_BITS-1)/TLSMAP_BITS)
1595#define TLSMAP_WORD(m,k) (m)->map[(k)/TLSMAP_BITS]
1596#define TLSMAP_MASK(k) (1U << ((k)&(TLSMAP_BITS-1)))
1597
1598/* this macro is used to quickly check that a key belongs to a reasonable range */
1599#define TLSMAP_VALIDATE_KEY(key) \
1600 ((key) >= TLSMAP_START && (key) < TLSMAP_SIZE)
1601
1602/* the type of tls key destructor functions */
1603typedef void (*tls_dtor_t)(void*);
1604
1605typedef struct {
1606 int init; /* see comment in tlsmap_lock() */
1607 uint32_t map[TLSMAP_WORDS]; /* bitmap of allocated keys */
1608 tls_dtor_t dtors[TLSMAP_SIZE]; /* key destructors */
1609} tlsmap_t;
1610
1611static pthread_mutex_t _tlsmap_lock = PTHREAD_MUTEX_INITIALIZER;
1612static tlsmap_t _tlsmap;
1613
1614/* lock the global TLS map lock and return a handle to it */
1615static __inline__ tlsmap_t* tlsmap_lock(void)
1616{
1617 tlsmap_t* m = &_tlsmap;
1618
1619 pthread_mutex_lock(&_tlsmap_lock);
1620 /* we need to initialize the first entry of the 'map' array
1621 * with the value TLS_DEFAULT_ALLOC_MAP. doing it statically
1622 * when declaring _tlsmap is a bit awkward and is going to
1623 * produce warnings, so do it the first time we use the map
1624 * instead
1625 */
1626 if (__unlikely(!m->init)) {
1627 TLSMAP_WORD(m,0) = TLS_DEFAULT_ALLOC_MAP;
1628 m->init = 1;
1629 }
1630 return m;
1631}
1632
1633/* unlock the global TLS map */
1634static __inline__ void tlsmap_unlock(tlsmap_t* m)
1635{
1636 pthread_mutex_unlock(&_tlsmap_lock);
1637 (void)m; /* a good compiler is a happy compiler */
1638}
1639
1640/* test to see wether a key is allocated */
1641static __inline__ int tlsmap_test(tlsmap_t* m, int key)
1642{
1643 return (TLSMAP_WORD(m,key) & TLSMAP_MASK(key)) != 0;
1644}
1645
1646/* set the destructor and bit flag on a newly allocated key */
1647static __inline__ void tlsmap_set(tlsmap_t* m, int key, tls_dtor_t dtor)
1648{
1649 TLSMAP_WORD(m,key) |= TLSMAP_MASK(key);
1650 m->dtors[key] = dtor;
1651}
1652
1653/* clear the destructor and bit flag on an existing key */
1654static __inline__ void tlsmap_clear(tlsmap_t* m, int key)
1655{
1656 TLSMAP_WORD(m,key) &= ~TLSMAP_MASK(key);
1657 m->dtors[key] = NULL;
1658}
1659
1660/* allocate a new TLS key, return -1 if no room left */
1661static int tlsmap_alloc(tlsmap_t* m, tls_dtor_t dtor)
1662{
1663 int key;
1664
1665 for ( key = TLSMAP_START; key < TLSMAP_SIZE; key++ ) {
1666 if ( !tlsmap_test(m, key) ) {
1667 tlsmap_set(m, key, dtor);
1668 return key;
1669 }
1670 }
1671 return -1;
1672}
1673
1674
1675int pthread_key_create(pthread_key_t *key, void (*destructor_function)(void *))
1676{
1677 uint32_t err = ENOMEM;
1678 tlsmap_t* map = tlsmap_lock();
1679 int k = tlsmap_alloc(map, destructor_function);
1680
1681 if (k >= 0) {
1682 *key = k;
1683 err = 0;
1684 }
1685 tlsmap_unlock(map);
1686 return err;
1687}
1688
1689
1690/* This deletes a pthread_key_t. note that the standard mandates that this does
1691 * not call the destructor of non-NULL key values. Instead, it is the
1692 * responsability of the caller to properly dispose of the corresponding data
1693 * and resources, using any mean it finds suitable.
1694 *
1695 * On the other hand, this function will clear the corresponding key data
1696 * values in all known threads. this prevents later (invalid) calls to
1697 * pthread_getspecific() to receive invalid/stale values.
1698 */
1699int pthread_key_delete(pthread_key_t key)
1700{
1701 uint32_t err;
1702 pthread_internal_t* thr;
1703 tlsmap_t* map;
1704
1705 if (!TLSMAP_VALIDATE_KEY(key)) {
1706 return EINVAL;
1707 }
1708
1709 map = tlsmap_lock();
1710
1711 if (!tlsmap_test(map, key)) {
1712 err = EINVAL;
1713 goto err1;
1714 }
1715
1716 /* clear value in all threads */
1717 pthread_mutex_lock(&gThreadListLock);
1718 for ( thr = gThreadList; thr != NULL; thr = thr->next ) {
1719 /* avoid zombie threads with a negative 'join_count'. these are really
1720 * already dead and don't have a TLS area anymore.
1721 *
1722 * similarly, it is possible to have thr->tls == NULL for threads that
1723 * were just recently created through pthread_create() but whose
1724 * startup trampoline (__thread_entry) hasn't been run yet by the
Bjorn Andersson0753dc62012-05-03 17:12:39 -07001725 * scheduler. thr->tls will also be NULL after it's stack has been
1726 * unmapped but before the ongoing pthread_join() is finished.
1727 * so check for this too.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001728 */
1729 if (thr->join_count < 0 || !thr->tls)
1730 continue;
1731
1732 thr->tls[key] = NULL;
1733 }
1734 tlsmap_clear(map, key);
1735
1736 pthread_mutex_unlock(&gThreadListLock);
1737 err = 0;
1738
1739err1:
1740 tlsmap_unlock(map);
1741 return err;
1742}
1743
1744
1745int pthread_setspecific(pthread_key_t key, const void *ptr)
1746{
1747 int err = EINVAL;
1748 tlsmap_t* map;
1749
1750 if (TLSMAP_VALIDATE_KEY(key)) {
1751 /* check that we're trying to set data for an allocated key */
1752 map = tlsmap_lock();
1753 if (tlsmap_test(map, key)) {
1754 ((uint32_t *)__get_tls())[key] = (uint32_t)ptr;
1755 err = 0;
1756 }
1757 tlsmap_unlock(map);
1758 }
1759 return err;
1760}
1761
1762void * pthread_getspecific(pthread_key_t key)
1763{
1764 if (!TLSMAP_VALIDATE_KEY(key)) {
1765 return NULL;
1766 }
1767
1768 /* for performance reason, we do not lock/unlock the global TLS map
1769 * to check that the key is properly allocated. if the key was not
1770 * allocated, the value read from the TLS should always be NULL
1771 * due to pthread_key_delete() clearing the values for all threads.
1772 */
1773 return (void *)(((unsigned *)__get_tls())[key]);
1774}
1775
1776/* Posix mandates that this be defined in <limits.h> but we don't have
1777 * it just yet.
1778 */
1779#ifndef PTHREAD_DESTRUCTOR_ITERATIONS
1780# define PTHREAD_DESTRUCTOR_ITERATIONS 4
1781#endif
1782
1783/* this function is called from pthread_exit() to remove all TLS key data
1784 * from this thread's TLS area. this must call the destructor of all keys
1785 * that have a non-NULL data value (and a non-NULL destructor).
1786 *
1787 * because destructors can do funky things like deleting/creating other
1788 * keys, we need to implement this in a loop
1789 */
1790static void pthread_key_clean_all(void)
1791{
1792 tlsmap_t* map;
1793 void** tls = (void**)__get_tls();
1794 int rounds = PTHREAD_DESTRUCTOR_ITERATIONS;
1795
1796 map = tlsmap_lock();
1797
1798 for (rounds = PTHREAD_DESTRUCTOR_ITERATIONS; rounds > 0; rounds--)
1799 {
1800 int kk, count = 0;
1801
1802 for (kk = TLSMAP_START; kk < TLSMAP_SIZE; kk++) {
1803 if ( tlsmap_test(map, kk) )
1804 {
1805 void* data = tls[kk];
1806 tls_dtor_t dtor = map->dtors[kk];
1807
1808 if (data != NULL && dtor != NULL)
1809 {
1810 /* we need to clear the key data now, this will prevent the
1811 * destructor (or a later one) from seeing the old value if
1812 * it calls pthread_getspecific() for some odd reason
1813 *
1814 * we do not do this if 'dtor == NULL' just in case another
1815 * destructor function might be responsible for manually
1816 * releasing the corresponding data.
1817 */
1818 tls[kk] = NULL;
1819
1820 /* because the destructor is free to call pthread_key_create
1821 * and/or pthread_key_delete, we need to temporarily unlock
1822 * the TLS map
1823 */
1824 tlsmap_unlock(map);
1825 (*dtor)(data);
1826 map = tlsmap_lock();
1827
1828 count += 1;
1829 }
1830 }
1831 }
1832
1833 /* if we didn't call any destructor, there is no need to check the
1834 * TLS data again
1835 */
1836 if (count == 0)
1837 break;
1838 }
1839 tlsmap_unlock(map);
1840}
1841
1842// man says this should be in <linux/unistd.h>, but it isn't
1843extern int tkill(int tid, int sig);
1844
1845int pthread_kill(pthread_t tid, int sig)
1846{
1847 int ret;
1848 int old_errno = errno;
1849 pthread_internal_t * thread = (pthread_internal_t *)tid;
1850
1851 ret = tkill(thread->kernel_id, sig);
1852 if (ret < 0) {
1853 ret = errno;
1854 errno = old_errno;
1855 }
1856
1857 return ret;
1858}
1859
Bruce Bearee4a21c82011-12-05 11:25:37 -08001860/* Despite the fact that our kernel headers define sigset_t explicitly
1861 * as a 32-bit integer, the kernel system call really expects a 64-bit
1862 * bitmap for the signal set, or more exactly an array of two-32-bit
1863 * values (see $KERNEL/arch/$ARCH/include/asm/signal.h for details).
1864 *
1865 * Unfortunately, we cannot fix the sigset_t definition without breaking
1866 * the C library ABI, so perform a little runtime translation here.
1867 */
1868typedef union {
1869 sigset_t bionic;
1870 uint32_t kernel[2];
1871} kernel_sigset_t;
1872
1873/* this is a private syscall stub */
1874extern int __rt_sigprocmask(int, const kernel_sigset_t *, kernel_sigset_t *, size_t);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001875
1876int pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
1877{
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001878 /* pthread_sigmask must return the error code, but the syscall
1879 * will set errno instead and return 0/-1
1880 */
1881 int ret, old_errno = errno;
1882
Bruce Bearee4a21c82011-12-05 11:25:37 -08001883 /* We must convert *set into a kernel_sigset_t */
1884 kernel_sigset_t in_set, *in_set_ptr;
1885 kernel_sigset_t out_set;
1886
1887 in_set.kernel[0] = in_set.kernel[1] = 0;
1888 out_set.kernel[0] = out_set.kernel[1] = 0;
1889
1890 /* 'in_set_ptr' is the second parameter to __rt_sigprocmask. It must be NULL
1891 * if 'set' is NULL to ensure correct semantics (which in this case would
1892 * be to ignore 'how' and return the current signal set into 'oset'.
1893 */
1894 if (set == NULL) {
1895 in_set_ptr = NULL;
1896 } else {
1897 in_set.bionic = *set;
1898 in_set_ptr = &in_set;
1899 }
1900
1901 ret = __rt_sigprocmask(how, in_set_ptr, &out_set, sizeof(kernel_sigset_t));
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001902 if (ret < 0)
1903 ret = errno;
1904
Bruce Bearee4a21c82011-12-05 11:25:37 -08001905 if (oset)
1906 *oset = out_set.bionic;
1907
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001908 errno = old_errno;
1909 return ret;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001910}
1911
1912
1913int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
1914{
1915 const int CLOCK_IDTYPE_BITS = 3;
1916 pthread_internal_t* thread = (pthread_internal_t*)tid;
1917
1918 if (!thread)
1919 return ESRCH;
1920
1921 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
1922 return 0;
1923}
1924
1925
1926/* NOTE: this implementation doesn't support a init function that throws a C++ exception
1927 * or calls fork()
1928 */
1929int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
1930{
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001931 static pthread_mutex_t once_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001932 volatile pthread_once_t* ocptr = once_control;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001933
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001934 pthread_once_t tmp = *ocptr;
1935 ANDROID_MEMBAR_FULL();
1936 if (tmp == PTHREAD_ONCE_INIT) {
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001937 pthread_mutex_lock( &once_lock );
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001938 if (*ocptr == PTHREAD_ONCE_INIT) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001939 (*init_routine)();
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001940 ANDROID_MEMBAR_FULL();
1941 *ocptr = ~PTHREAD_ONCE_INIT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001942 }
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001943 pthread_mutex_unlock( &once_lock );
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001944 }
1945 return 0;
1946}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03001947
1948/* This value is not exported by kernel headers, so hardcode it here */
1949#define MAX_TASK_COMM_LEN 16
1950#define TASK_COMM_FMT "/proc/self/task/%u/comm"
1951
1952int pthread_setname_np(pthread_t thid, const char *thname)
1953{
1954 size_t thname_len;
1955 int saved_errno, ret;
1956
1957 if (thid == 0 || thname == NULL)
1958 return EINVAL;
1959
1960 thname_len = strlen(thname);
1961 if (thname_len >= MAX_TASK_COMM_LEN)
1962 return ERANGE;
1963
1964 saved_errno = errno;
1965 if (thid == pthread_self())
1966 {
1967 ret = prctl(PR_SET_NAME, (unsigned long)thname, 0, 0, 0) ? errno : 0;
1968 }
1969 else
1970 {
1971 /* Have to change another thread's name */
1972 pthread_internal_t *thread = (pthread_internal_t *)thid;
1973 char comm_name[sizeof(TASK_COMM_FMT) + 8];
1974 ssize_t n;
1975 int fd;
1976
1977 snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, (unsigned int)thread->kernel_id);
1978 fd = open(comm_name, O_RDWR);
1979 if (fd == -1)
1980 {
1981 ret = errno;
1982 goto exit;
1983 }
1984 n = TEMP_FAILURE_RETRY(write(fd, thname, thname_len));
1985 close(fd);
1986
1987 if (n < 0)
1988 ret = errno;
1989 else if ((size_t)n != thname_len)
1990 ret = EIO;
1991 else
1992 ret = 0;
1993 }
1994exit:
1995 errno = saved_errno;
1996 return ret;
1997}
Glenn Kastend53cae02011-07-11 15:41:28 -07001998
1999/* Return the kernel thread ID for a pthread.
2000 * This is only defined for implementations where pthread <-> kernel is 1:1, which this is.
2001 * Not the same as pthread_getthreadid_np, which is commonly defined to be opaque.
2002 * Internal, not an NDK API.
2003 */
2004
2005pid_t __pthread_gettid(pthread_t thid)
2006{
2007 pthread_internal_t* thread = (pthread_internal_t*)thid;
2008 return thread->kernel_id;
2009}
Jack Rend8bc6e72012-01-17 16:27:42 +08002010
2011int __pthread_settid(pthread_t thid, pid_t tid)
2012{
2013 if (thid == 0)
2014 return EINVAL;
2015
2016 pthread_internal_t* thread = (pthread_internal_t*)thid;
2017 thread->kernel_id = tid;
2018
2019 return 0;
2020}