blob: f611a21576591c86dcd735878b05bcfe4f779afe [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 {
579 /* the join_count field is used to store the number of threads waiting for
580 * the termination of this thread with pthread_join(),
581 *
582 * if it is positive we need to signal the waiters, and we do not touch
583 * the count (it will be decremented by the waiters, the last one will
584 * also remove/free the thread structure
585 *
586 * if it is zero, we set the count value to -1 to indicate that the
587 * thread is in 'zombie' state: it has stopped executing, and its stack
588 * is gone (as well as its TLS area). when another thread calls pthread_join()
589 * on it, it will immediately free the thread and return.
590 */
591 pthread_mutex_lock(&gThreadListLock);
592 thread->return_value = retval;
593 if (thread->join_count > 0) {
594 pthread_cond_broadcast(&thread->join_cond);
595 } else {
596 thread->join_count = -1; /* zombie thread */
597 }
598 pthread_mutex_unlock(&gThreadListLock);
599 }
600
Jack Rene480fc82011-09-21 12:44:11 +0200601 sigfillset(&mask);
602 sigdelset(&mask, SIGSEGV);
603 (void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *)NULL);
604
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800605 // destroy the thread stack
606 if (user_stack)
607 _exit_thread((int)retval);
608 else
609 _exit_with_stack_teardown(stack_base, stack_size, (int)retval);
610}
611
612int pthread_join(pthread_t thid, void ** ret_val)
613{
614 pthread_internal_t* thread = (pthread_internal_t*)thid;
615 int count;
616
617 // check that the thread still exists and is not detached
618 pthread_mutex_lock(&gThreadListLock);
619
620 for (thread = gThreadList; thread != NULL; thread = thread->next)
621 if (thread == (pthread_internal_t*)thid)
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200622 goto FoundIt;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800623
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200624 pthread_mutex_unlock(&gThreadListLock);
625 return ESRCH;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800626
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200627FoundIt:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800628 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
629 pthread_mutex_unlock(&gThreadListLock);
630 return EINVAL;
631 }
632
633 /* wait for thread death when needed
634 *
635 * if the 'join_count' is negative, this is a 'zombie' thread that
636 * is already dead and without stack/TLS
637 *
638 * otherwise, we need to increment 'join-count' and wait to be signaled
639 */
640 count = thread->join_count;
641 if (count >= 0) {
642 thread->join_count += 1;
643 pthread_cond_wait( &thread->join_cond, &gThreadListLock );
644 count = --thread->join_count;
645 }
646 if (ret_val)
647 *ret_val = thread->return_value;
648
649 /* remove thread descriptor when we're the last joiner or when the
650 * thread was already a zombie.
651 */
652 if (count <= 0) {
653 _pthread_internal_remove_locked(thread);
654 _pthread_internal_free(thread);
655 }
656 pthread_mutex_unlock(&gThreadListLock);
657 return 0;
658}
659
660int pthread_detach( pthread_t thid )
661{
662 pthread_internal_t* thread;
663 int result = 0;
664 int flags;
665
666 pthread_mutex_lock(&gThreadListLock);
667 for (thread = gThreadList; thread != NULL; thread = thread->next)
668 if (thread == (pthread_internal_t*)thid)
669 goto FoundIt;
670
671 result = ESRCH;
672 goto Exit;
673
674FoundIt:
675 do {
676 flags = thread->attr.flags;
677
678 if ( flags & PTHREAD_ATTR_FLAG_DETACHED ) {
679 /* thread is not joinable ! */
680 result = EINVAL;
681 goto Exit;
682 }
683 }
684 while ( __atomic_cmpxchg( flags, flags | PTHREAD_ATTR_FLAG_DETACHED,
685 (volatile int*)&thread->attr.flags ) != 0 );
686Exit:
687 pthread_mutex_unlock(&gThreadListLock);
688 return result;
689}
690
691pthread_t pthread_self(void)
692{
693 return (pthread_t)__get_thread();
694}
695
696int pthread_equal(pthread_t one, pthread_t two)
697{
698 return (one == two ? 1 : 0);
699}
700
701int pthread_getschedparam(pthread_t thid, int * policy,
702 struct sched_param * param)
703{
704 int old_errno = errno;
705
706 pthread_internal_t * thread = (pthread_internal_t *)thid;
707 int err = sched_getparam(thread->kernel_id, param);
708 if (!err) {
709 *policy = sched_getscheduler(thread->kernel_id);
710 } else {
711 err = errno;
712 errno = old_errno;
713 }
714 return err;
715}
716
717int pthread_setschedparam(pthread_t thid, int policy,
718 struct sched_param const * param)
719{
720 pthread_internal_t * thread = (pthread_internal_t *)thid;
721 int old_errno = errno;
722 int ret;
723
724 ret = sched_setscheduler(thread->kernel_id, policy, param);
725 if (ret < 0) {
726 ret = errno;
727 errno = old_errno;
728 }
729 return ret;
730}
731
732
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800733// mutex lock states
734//
735// 0: unlocked
736// 1: locked, no waiters
737// 2: locked, maybe waiters
738
739/* a mutex is implemented as a 32-bit integer holding the following fields
740 *
741 * bits: name description
742 * 31-16 tid owner thread's kernel id (recursive and errorcheck only)
743 * 15-14 type mutex type
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700744 * 13 shared process-shared flag
745 * 12-2 counter counter of recursive mutexes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800746 * 1-0 state lock state (0, 1 or 2)
747 */
748
749
750#define MUTEX_OWNER(m) (((m)->value >> 16) & 0xffff)
751#define MUTEX_COUNTER(m) (((m)->value >> 2) & 0xfff)
752
753#define MUTEX_TYPE_MASK 0xc000
754#define MUTEX_TYPE_NORMAL 0x0000
755#define MUTEX_TYPE_RECURSIVE 0x4000
756#define MUTEX_TYPE_ERRORCHECK 0x8000
757
758#define MUTEX_COUNTER_SHIFT 2
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700759#define MUTEX_COUNTER_MASK 0x1ffc
760#define MUTEX_SHARED_MASK 0x2000
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800761
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700762/* a mutex attribute holds the following fields
763 *
764 * bits: name description
765 * 0-3 type type of mutex
766 * 4 shared process-shared flag
767 */
768#define MUTEXATTR_TYPE_MASK 0x000f
769#define MUTEXATTR_SHARED_MASK 0x0010
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800770
771
772int pthread_mutexattr_init(pthread_mutexattr_t *attr)
773{
774 if (attr) {
775 *attr = PTHREAD_MUTEX_DEFAULT;
776 return 0;
777 } else {
778 return EINVAL;
779 }
780}
781
782int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
783{
784 if (attr) {
785 *attr = -1;
786 return 0;
787 } else {
788 return EINVAL;
789 }
790}
791
792int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
793{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700794 if (attr) {
795 int atype = (*attr & MUTEXATTR_TYPE_MASK);
796
797 if (atype >= PTHREAD_MUTEX_NORMAL &&
798 atype <= PTHREAD_MUTEX_ERRORCHECK) {
799 *type = atype;
800 return 0;
801 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800802 }
803 return EINVAL;
804}
805
806int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
807{
808 if (attr && type >= PTHREAD_MUTEX_NORMAL &&
809 type <= PTHREAD_MUTEX_ERRORCHECK ) {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700810 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800811 return 0;
812 }
813 return EINVAL;
814}
815
816/* process-shared mutexes are not supported at the moment */
817
818int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
819{
820 if (!attr)
821 return EINVAL;
822
Mathias Agopianb7681162009-07-13 22:00:33 -0700823 switch (pshared) {
824 case PTHREAD_PROCESS_PRIVATE:
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700825 *attr &= ~MUTEXATTR_SHARED_MASK;
826 return 0;
827
Mathias Agopianb7681162009-07-13 22:00:33 -0700828 case PTHREAD_PROCESS_SHARED:
829 /* our current implementation of pthread actually supports shared
830 * mutexes but won't cleanup if a process dies with the mutex held.
831 * Nevertheless, it's better than nothing. Shared mutexes are used
832 * by surfaceflinger and audioflinger.
833 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700834 *attr |= MUTEXATTR_SHARED_MASK;
Mathias Agopianb7681162009-07-13 22:00:33 -0700835 return 0;
836 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700837 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800838}
839
840int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
841{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700842 if (!attr || !pshared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800843 return EINVAL;
844
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700845 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED
846 : PTHREAD_PROCESS_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800847 return 0;
848}
849
850int pthread_mutex_init(pthread_mutex_t *mutex,
851 const pthread_mutexattr_t *attr)
852{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700853 int value = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800854
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700855 if (mutex == NULL)
856 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800857
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700858 if (__likely(attr == NULL)) {
859 mutex->value = MUTEX_TYPE_NORMAL;
860 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800861 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700862
863 if ((*attr & MUTEXATTR_SHARED_MASK) != 0)
864 value |= MUTEX_SHARED_MASK;
865
866 switch (*attr & MUTEXATTR_TYPE_MASK) {
867 case PTHREAD_MUTEX_NORMAL:
868 value |= MUTEX_TYPE_NORMAL;
869 break;
870 case PTHREAD_MUTEX_RECURSIVE:
871 value |= MUTEX_TYPE_RECURSIVE;
872 break;
873 case PTHREAD_MUTEX_ERRORCHECK:
874 value |= MUTEX_TYPE_ERRORCHECK;
875 break;
876 default:
877 return EINVAL;
878 }
879
880 mutex->value = value;
881 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800882}
883
884int pthread_mutex_destroy(pthread_mutex_t *mutex)
885{
David 'Digit' Turnera02b93b2010-06-28 14:20:22 -0700886 int ret;
887
888 /* use trylock to ensure that the mutex value is
889 * valid and is not already locked. */
890 ret = pthread_mutex_trylock(mutex);
891 if (ret != 0)
892 return ret;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700893
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800894 mutex->value = 0xdead10cc;
895 return 0;
896}
897
898
899/*
900 * Lock a non-recursive mutex.
901 *
902 * As noted above, there are three states:
903 * 0 (unlocked, no contention)
904 * 1 (locked, no contention)
905 * 2 (locked, contention)
906 *
907 * Non-recursive mutexes don't use the thread-id or counter fields, and the
908 * "type" value is zero, so the only bits that will be set are the ones in
909 * the lock state field.
910 */
911static __inline__ void
912_normal_lock(pthread_mutex_t* mutex)
913{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700914 /* We need to preserve the shared flag during operations */
915 int shared = mutex->value & MUTEX_SHARED_MASK;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800916 /*
917 * The common case is an unlocked mutex, so we begin by trying to
918 * change the lock's state from 0 to 1. __atomic_cmpxchg() returns 0
919 * if it made the swap successfully. If the result is nonzero, this
920 * lock is already held by another thread.
921 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700922 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value ) != 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800923 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800924 * We want to go to sleep until the mutex is available, which
925 * requires promoting it to state 2. We need to swap in the new
926 * state value and then wait until somebody wakes us up.
927 *
928 * __atomic_swap() returns the previous value. We swap 2 in and
929 * see if we got zero back; if so, we have acquired the lock. If
930 * not, another thread still holds the lock and we wait again.
931 *
932 * The second argument to the __futex_wait() call is compared
933 * against the current value. If it doesn't match, __futex_wait()
934 * returns immediately (otherwise, it sleeps for a time specified
935 * by the third argument; 0 means sleep forever). This ensures
936 * that the mutex is in state 2 when we go to sleep on it, which
937 * guarantees a wake-up call.
938 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700939 while (__atomic_swap(shared|2, &mutex->value ) != (shared|0))
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -0700940 __futex_wait_ex(&mutex->value, shared, shared|2, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800941 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700942 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800943}
944
945/*
946 * Release a non-recursive mutex. The caller is responsible for determining
947 * that we are in fact the owner of this lock.
948 */
949static __inline__ void
950_normal_unlock(pthread_mutex_t* mutex)
951{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700952 ANDROID_MEMBAR_FULL();
953
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700954 /* We need to preserve the shared flag during operations */
955 int shared = mutex->value & MUTEX_SHARED_MASK;
956
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800957 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700958 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800959 * to release the lock. __atomic_dec() returns the previous value;
960 * if it wasn't 1 we have to do some additional work.
961 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700962 if (__atomic_dec(&mutex->value) != (shared|1)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800963 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800964 * Start by releasing the lock. The decrement changed it from
965 * "contended lock" to "uncontended lock", which means we still
966 * hold it, and anybody who tries to sneak in will push it back
967 * to state 2.
968 *
969 * Once we set it to zero the lock is up for grabs. We follow
970 * this with a __futex_wake() to ensure that one of the waiting
971 * threads has a chance to grab it.
972 *
973 * This doesn't cause a race with the swap/wait pair in
974 * _normal_lock(), because the __futex_wait() call there will
975 * return immediately if the mutex value isn't 2.
976 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700977 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800978
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800979 /*
980 * Wake up one waiting thread. We don't know which thread will be
981 * woken or when it'll start executing -- futexes make no guarantees
982 * here. There may not even be a thread waiting.
983 *
984 * The newly-woken thread will replace the 0 we just set above
985 * with 2, which means that when it eventually releases the mutex
986 * it will also call FUTEX_WAKE. This results in one extra wake
987 * call whenever a lock is contended, but lets us avoid forgetting
988 * anyone without requiring us to track the number of sleepers.
989 *
990 * It's possible for another thread to sneak in and grab the lock
991 * between the zero assignment above and the wake call below. If
992 * the new thread is "slow" and holds the lock for a while, we'll
993 * wake up a sleeper, which will swap in a 2 and then go back to
994 * sleep since the lock is still held. If the new thread is "fast",
995 * running to completion before we call wake, the thread we
996 * eventually wake will find an unlocked mutex and will execute.
997 * Either way we have correct behavior and nobody is orphaned on
998 * the wait queue.
999 */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001000 __futex_wake_ex(&mutex->value, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001001 }
1002}
1003
1004static pthread_mutex_t __recursive_lock = PTHREAD_MUTEX_INITIALIZER;
1005
1006static void
1007_recursive_lock(void)
1008{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001009 _normal_lock(&__recursive_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001010}
1011
1012static void
1013_recursive_unlock(void)
1014{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001015 _normal_unlock(&__recursive_lock );
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001016}
1017
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001018int pthread_mutex_lock(pthread_mutex_t *mutex)
1019{
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001020 int mtype, tid, new_lock_type, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001021
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001022 if (__unlikely(mutex == NULL))
1023 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001024
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001025 mtype = (mutex->value & MUTEX_TYPE_MASK);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001026 shared = (mutex->value & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001027
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001028 /* Handle normal case first */
1029 if ( __likely(mtype == MUTEX_TYPE_NORMAL) ) {
1030 _normal_lock(mutex);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001031 return 0;
1032 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001033
1034 /* Do we already own this recursive or error-check mutex ? */
1035 tid = __get_thread()->kernel_id;
1036 if ( tid == MUTEX_OWNER(mutex) )
1037 {
1038 int oldv, counter;
1039
1040 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1041 /* trying to re-lock a mutex we already acquired */
1042 return EDEADLK;
1043 }
1044 /*
1045 * We own the mutex, but other threads are able to change
1046 * the contents (e.g. promoting it to "contended"), so we
1047 * need to hold the global lock.
1048 */
1049 _recursive_lock();
1050 oldv = mutex->value;
1051 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1052 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1053 _recursive_unlock();
1054 return 0;
1055 }
1056
1057 /* We don't own the mutex, so try to get it.
1058 *
1059 * First, we try to change its state from 0 to 1, if this
1060 * doesn't work, try to change it to state 2.
1061 */
1062 new_lock_type = 1;
1063
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001064 /* compute futex wait opcode and restore shared flag in mtype */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001065 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001066
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001067 for (;;) {
1068 int oldv;
1069
1070 _recursive_lock();
1071 oldv = mutex->value;
1072 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1073 mutex->value = ((tid << 16) | mtype | new_lock_type);
1074 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1075 oldv ^= 3;
1076 mutex->value = oldv;
1077 }
1078 _recursive_unlock();
1079
1080 if (oldv == mtype)
1081 break;
1082
1083 /*
1084 * The lock was held, possibly contended by others. From
1085 * now on, if we manage to acquire the lock, we have to
1086 * assume that others are still contending for it so that
1087 * we'll wake them when we unlock it.
1088 */
1089 new_lock_type = 2;
1090
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001091 __futex_wait_ex(&mutex->value, shared, oldv, NULL);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001092 }
1093 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001094}
1095
1096
1097int pthread_mutex_unlock(pthread_mutex_t *mutex)
1098{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001099 int mtype, tid, oldv, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001100
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001101 if (__unlikely(mutex == NULL))
1102 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001103
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001104 mtype = (mutex->value & MUTEX_TYPE_MASK);
1105 shared = (mutex->value & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001106
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001107 /* Handle common case first */
1108 if (__likely(mtype == MUTEX_TYPE_NORMAL)) {
1109 _normal_unlock(mutex);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001110 return 0;
1111 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001112
1113 /* Do we already own this recursive or error-check mutex ? */
1114 tid = __get_thread()->kernel_id;
1115 if ( tid != MUTEX_OWNER(mutex) )
1116 return EPERM;
1117
1118 /* We do, decrement counter or release the mutex if it is 0 */
1119 _recursive_lock();
1120 oldv = mutex->value;
1121 if (oldv & MUTEX_COUNTER_MASK) {
1122 mutex->value = oldv - (1 << MUTEX_COUNTER_SHIFT);
1123 oldv = 0;
1124 } else {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001125 mutex->value = shared | mtype;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001126 }
1127 _recursive_unlock();
1128
1129 /* Wake one waiting thread, if any */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001130 if ((oldv & 3) == 2) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001131 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001132 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001133 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001134}
1135
1136
1137int pthread_mutex_trylock(pthread_mutex_t *mutex)
1138{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001139 int mtype, tid, oldv, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001140
1141 if (__unlikely(mutex == NULL))
1142 return EINVAL;
1143
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001144 mtype = (mutex->value & MUTEX_TYPE_MASK);
1145 shared = (mutex->value & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001146
1147 /* Handle common case first */
1148 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001149 {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001150 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
1151 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001152 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001153 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001154
1155 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001156 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001157
1158 /* Do we already own this recursive or error-check mutex ? */
1159 tid = __get_thread()->kernel_id;
1160 if ( tid == MUTEX_OWNER(mutex) )
1161 {
1162 int counter;
1163
1164 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1165 /* already locked by ourselves */
1166 return EDEADLK;
1167 }
1168
1169 _recursive_lock();
1170 oldv = mutex->value;
1171 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1172 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1173 _recursive_unlock();
1174 return 0;
1175 }
1176
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001177 /* Restore sharing bit in mtype */
1178 mtype |= shared;
1179
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001180 /* Try to lock it, just once. */
1181 _recursive_lock();
1182 oldv = mutex->value;
1183 if (oldv == mtype) /* uncontended released lock => state 1 */
1184 mutex->value = ((tid << 16) | mtype | 1);
1185 _recursive_unlock();
1186
1187 if (oldv != mtype)
1188 return EBUSY;
1189
1190 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001191}
1192
1193
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001194/* initialize 'ts' with the difference between 'abstime' and the current time
1195 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
1196 */
1197static int
1198__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
1199{
1200 clock_gettime(clock, ts);
1201 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
1202 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
1203 if (ts->tv_nsec < 0) {
1204 ts->tv_sec--;
1205 ts->tv_nsec += 1000000000;
1206 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001207 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001208 return -1;
1209
1210 return 0;
1211}
1212
1213/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1214 * milliseconds.
1215 */
1216static void
1217__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1218{
1219 clock_gettime(clock, abstime);
1220 abstime->tv_sec += msecs/1000;
1221 abstime->tv_nsec += (msecs%1000)*1000000;
1222 if (abstime->tv_nsec >= 1000000000) {
1223 abstime->tv_sec++;
1224 abstime->tv_nsec -= 1000000000;
1225 }
1226}
1227
1228int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1229{
1230 clockid_t clock = CLOCK_MONOTONIC;
1231 struct timespec abstime;
1232 struct timespec ts;
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001233 int mtype, tid, oldv, new_lock_type, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001234
1235 /* compute absolute expiration time */
1236 __timespec_to_relative_msec(&abstime, msecs, clock);
1237
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001238 if (__unlikely(mutex == NULL))
1239 return EINVAL;
1240
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001241 mtype = (mutex->value & MUTEX_TYPE_MASK);
1242 shared = (mutex->value & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001243
1244 /* Handle common case first */
1245 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001246 {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001247 /* fast path for uncontended lock */
1248 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
1249 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001250 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001251 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001252
1253 /* loop while needed */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001254 while (__atomic_swap(shared|2, &mutex->value) != (shared|0)) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001255 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1256 return EBUSY;
1257
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001258 __futex_wait_ex(&mutex->value, shared, shared|2, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001259 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001260 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001261 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001262 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001263
1264 /* Do we already own this recursive or error-check mutex ? */
1265 tid = __get_thread()->kernel_id;
1266 if ( tid == MUTEX_OWNER(mutex) )
1267 {
1268 int oldv, counter;
1269
1270 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1271 /* already locked by ourselves */
1272 return EDEADLK;
1273 }
1274
1275 _recursive_lock();
1276 oldv = mutex->value;
1277 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1278 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1279 _recursive_unlock();
1280 return 0;
1281 }
1282
1283 /* We don't own the mutex, so try to get it.
1284 *
1285 * First, we try to change its state from 0 to 1, if this
1286 * doesn't work, try to change it to state 2.
1287 */
1288 new_lock_type = 1;
1289
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001290 /* Compute wait op and restore sharing bit in mtype */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001291 mtype |= shared;
1292
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001293 for (;;) {
1294 int oldv;
1295 struct timespec ts;
1296
1297 _recursive_lock();
1298 oldv = mutex->value;
1299 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1300 mutex->value = ((tid << 16) | mtype | new_lock_type);
1301 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1302 oldv ^= 3;
1303 mutex->value = oldv;
1304 }
1305 _recursive_unlock();
1306
1307 if (oldv == mtype)
1308 break;
1309
1310 /*
1311 * The lock was held, possibly contended by others. From
1312 * now on, if we manage to acquire the lock, we have to
1313 * assume that others are still contending for it so that
1314 * we'll wake them when we unlock it.
1315 */
1316 new_lock_type = 2;
1317
1318 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1319 return EBUSY;
1320
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001321 __futex_wait_ex(&mutex->value, shared, oldv, &ts);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001322 }
1323 return 0;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001324}
1325
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001326int pthread_condattr_init(pthread_condattr_t *attr)
1327{
1328 if (attr == NULL)
1329 return EINVAL;
1330
1331 *attr = PTHREAD_PROCESS_PRIVATE;
1332 return 0;
1333}
1334
1335int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1336{
1337 if (attr == NULL || pshared == NULL)
1338 return EINVAL;
1339
1340 *pshared = *attr;
1341 return 0;
1342}
1343
1344int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1345{
1346 if (attr == NULL)
1347 return EINVAL;
1348
1349 if (pshared != PTHREAD_PROCESS_SHARED &&
1350 pshared != PTHREAD_PROCESS_PRIVATE)
1351 return EINVAL;
1352
1353 *attr = pshared;
1354 return 0;
1355}
1356
1357int pthread_condattr_destroy(pthread_condattr_t *attr)
1358{
1359 if (attr == NULL)
1360 return EINVAL;
1361
1362 *attr = 0xdeada11d;
1363 return 0;
1364}
1365
1366/* We use one bit in condition variable values as the 'shared' flag
1367 * The rest is a counter.
1368 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001369#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001370#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001371#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1372
1373#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001374
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001375/* XXX *technically* there is a race condition that could allow
1376 * XXX a signal to be missed. If thread A is preempted in _wait()
1377 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001378 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001379 * XXX before thread A is scheduled again and calls futex_wait(),
1380 * XXX then the signal will be lost.
1381 */
1382
1383int pthread_cond_init(pthread_cond_t *cond,
1384 const pthread_condattr_t *attr)
1385{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001386 if (cond == NULL)
1387 return EINVAL;
1388
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001389 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001390
1391 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001392 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001393
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001394 return 0;
1395}
1396
1397int pthread_cond_destroy(pthread_cond_t *cond)
1398{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001399 if (cond == NULL)
1400 return EINVAL;
1401
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001402 cond->value = 0xdeadc04d;
1403 return 0;
1404}
1405
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001406/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001407 * pthread_cond_signal to atomically decrement the counter
1408 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001409 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001410static int
1411__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001412{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001413 long flags;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001414
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001415 if (__unlikely(cond == NULL))
1416 return EINVAL;
1417
1418 flags = (cond->value & ~COND_COUNTER_MASK);
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001419 for (;;) {
1420 long oldval = cond->value;
1421 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1422 | flags;
1423 if (__atomic_cmpxchg(oldval, newval, &cond->value) == 0)
1424 break;
1425 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001426
Andy McFaddene2ac8982010-09-02 13:34:53 -07001427 /*
1428 * Ensure that all memory accesses previously made by this thread are
1429 * visible to the woken thread(s). On the other side, the "wait"
1430 * code will issue any necessary barriers when locking the mutex.
1431 *
1432 * This may not strictly be necessary -- if the caller follows
1433 * recommended practice and holds the mutex before signaling the cond
1434 * var, the mutex ops will provide correct semantics. If they don't
1435 * hold the mutex, they're subject to race conditions anyway.
1436 */
1437 ANDROID_MEMBAR_FULL();
1438
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001439 __futex_wake_ex(&cond->value, COND_IS_SHARED(cond), counter);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001440 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001441}
1442
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001443int pthread_cond_broadcast(pthread_cond_t *cond)
1444{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001445 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001446}
1447
1448int pthread_cond_signal(pthread_cond_t *cond)
1449{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001450 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001451}
1452
1453int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1454{
1455 return pthread_cond_timedwait(cond, mutex, NULL);
1456}
1457
1458int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1459 pthread_mutex_t * mutex,
1460 const struct timespec *reltime)
1461{
1462 int status;
1463 int oldvalue = cond->value;
1464
1465 pthread_mutex_unlock(mutex);
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001466 status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond), oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001467 pthread_mutex_lock(mutex);
1468
1469 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1470 return 0;
1471}
1472
1473int __pthread_cond_timedwait(pthread_cond_t *cond,
1474 pthread_mutex_t * mutex,
1475 const struct timespec *abstime,
1476 clockid_t clock)
1477{
1478 struct timespec ts;
1479 struct timespec * tsp;
1480
1481 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001482 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001483 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001484 tsp = &ts;
1485 } else {
1486 tsp = NULL;
1487 }
1488
1489 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1490}
1491
1492int pthread_cond_timedwait(pthread_cond_t *cond,
1493 pthread_mutex_t * mutex,
1494 const struct timespec *abstime)
1495{
1496 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1497}
1498
1499
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001500/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001501int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1502 pthread_mutex_t * mutex,
1503 const struct timespec *abstime)
1504{
1505 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1506}
1507
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001508int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1509 pthread_mutex_t * mutex,
1510 const struct timespec *abstime)
1511{
1512 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1513}
1514
1515int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1516 pthread_mutex_t * mutex,
1517 const struct timespec *reltime)
1518{
1519 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1520}
1521
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001522int pthread_cond_timeout_np(pthread_cond_t *cond,
1523 pthread_mutex_t * mutex,
1524 unsigned msecs)
1525{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001526 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001527
1528 ts.tv_sec = msecs / 1000;
1529 ts.tv_nsec = (msecs % 1000) * 1000000;
1530
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001531 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001532}
1533
1534
1535
1536/* A technical note regarding our thread-local-storage (TLS) implementation:
1537 *
1538 * There can be up to TLSMAP_SIZE independent TLS keys in a given process,
1539 * though the first TLSMAP_START keys are reserved for Bionic to hold
1540 * special thread-specific variables like errno or a pointer to
1541 * the current thread's descriptor.
1542 *
1543 * while stored in the TLS area, these entries cannot be accessed through
1544 * pthread_getspecific() / pthread_setspecific() and pthread_key_delete()
1545 *
1546 * also, some entries in the key table are pre-allocated (see tlsmap_lock)
1547 * to greatly simplify and speedup some OpenGL-related operations. though the
1548 * initialy value will be NULL on all threads.
1549 *
1550 * you can use pthread_getspecific()/setspecific() on these, and in theory
1551 * you could also call pthread_key_delete() as well, though this would
1552 * probably break some apps.
1553 *
1554 * The 'tlsmap_t' type defined below implements a shared global map of
1555 * currently created/allocated TLS keys and the destructors associated
1556 * with them. You should use tlsmap_lock/unlock to access it to avoid
1557 * any race condition.
1558 *
1559 * the global TLS map simply contains a bitmap of allocated keys, and
1560 * an array of destructors.
1561 *
1562 * each thread has a TLS area that is a simple array of TLSMAP_SIZE void*
1563 * pointers. the TLS area of the main thread is stack-allocated in
1564 * __libc_init_common, while the TLS area of other threads is placed at
1565 * the top of their stack in pthread_create.
1566 *
1567 * when pthread_key_create() is called, it finds the first free key in the
1568 * bitmap, then set it to 1, saving the destructor altogether
1569 *
1570 * when pthread_key_delete() is called. it will erase the key's bitmap bit
1571 * and its destructor, and will also clear the key data in the TLS area of
1572 * all created threads. As mandated by Posix, it is the responsability of
1573 * the caller of pthread_key_delete() to properly reclaim the objects that
1574 * were pointed to by these data fields (either before or after the call).
1575 *
1576 */
1577
1578/* TLS Map implementation
1579 */
1580
1581#define TLSMAP_START (TLS_SLOT_MAX_WELL_KNOWN+1)
1582#define TLSMAP_SIZE BIONIC_TLS_SLOTS
1583#define TLSMAP_BITS 32
1584#define TLSMAP_WORDS ((TLSMAP_SIZE+TLSMAP_BITS-1)/TLSMAP_BITS)
1585#define TLSMAP_WORD(m,k) (m)->map[(k)/TLSMAP_BITS]
1586#define TLSMAP_MASK(k) (1U << ((k)&(TLSMAP_BITS-1)))
1587
1588/* this macro is used to quickly check that a key belongs to a reasonable range */
1589#define TLSMAP_VALIDATE_KEY(key) \
1590 ((key) >= TLSMAP_START && (key) < TLSMAP_SIZE)
1591
1592/* the type of tls key destructor functions */
1593typedef void (*tls_dtor_t)(void*);
1594
1595typedef struct {
1596 int init; /* see comment in tlsmap_lock() */
1597 uint32_t map[TLSMAP_WORDS]; /* bitmap of allocated keys */
1598 tls_dtor_t dtors[TLSMAP_SIZE]; /* key destructors */
1599} tlsmap_t;
1600
1601static pthread_mutex_t _tlsmap_lock = PTHREAD_MUTEX_INITIALIZER;
1602static tlsmap_t _tlsmap;
1603
1604/* lock the global TLS map lock and return a handle to it */
1605static __inline__ tlsmap_t* tlsmap_lock(void)
1606{
1607 tlsmap_t* m = &_tlsmap;
1608
1609 pthread_mutex_lock(&_tlsmap_lock);
1610 /* we need to initialize the first entry of the 'map' array
1611 * with the value TLS_DEFAULT_ALLOC_MAP. doing it statically
1612 * when declaring _tlsmap is a bit awkward and is going to
1613 * produce warnings, so do it the first time we use the map
1614 * instead
1615 */
1616 if (__unlikely(!m->init)) {
1617 TLSMAP_WORD(m,0) = TLS_DEFAULT_ALLOC_MAP;
1618 m->init = 1;
1619 }
1620 return m;
1621}
1622
1623/* unlock the global TLS map */
1624static __inline__ void tlsmap_unlock(tlsmap_t* m)
1625{
1626 pthread_mutex_unlock(&_tlsmap_lock);
1627 (void)m; /* a good compiler is a happy compiler */
1628}
1629
1630/* test to see wether a key is allocated */
1631static __inline__ int tlsmap_test(tlsmap_t* m, int key)
1632{
1633 return (TLSMAP_WORD(m,key) & TLSMAP_MASK(key)) != 0;
1634}
1635
1636/* set the destructor and bit flag on a newly allocated key */
1637static __inline__ void tlsmap_set(tlsmap_t* m, int key, tls_dtor_t dtor)
1638{
1639 TLSMAP_WORD(m,key) |= TLSMAP_MASK(key);
1640 m->dtors[key] = dtor;
1641}
1642
1643/* clear the destructor and bit flag on an existing key */
1644static __inline__ void tlsmap_clear(tlsmap_t* m, int key)
1645{
1646 TLSMAP_WORD(m,key) &= ~TLSMAP_MASK(key);
1647 m->dtors[key] = NULL;
1648}
1649
1650/* allocate a new TLS key, return -1 if no room left */
1651static int tlsmap_alloc(tlsmap_t* m, tls_dtor_t dtor)
1652{
1653 int key;
1654
1655 for ( key = TLSMAP_START; key < TLSMAP_SIZE; key++ ) {
1656 if ( !tlsmap_test(m, key) ) {
1657 tlsmap_set(m, key, dtor);
1658 return key;
1659 }
1660 }
1661 return -1;
1662}
1663
1664
1665int pthread_key_create(pthread_key_t *key, void (*destructor_function)(void *))
1666{
1667 uint32_t err = ENOMEM;
1668 tlsmap_t* map = tlsmap_lock();
1669 int k = tlsmap_alloc(map, destructor_function);
1670
1671 if (k >= 0) {
1672 *key = k;
1673 err = 0;
1674 }
1675 tlsmap_unlock(map);
1676 return err;
1677}
1678
1679
1680/* This deletes a pthread_key_t. note that the standard mandates that this does
1681 * not call the destructor of non-NULL key values. Instead, it is the
1682 * responsability of the caller to properly dispose of the corresponding data
1683 * and resources, using any mean it finds suitable.
1684 *
1685 * On the other hand, this function will clear the corresponding key data
1686 * values in all known threads. this prevents later (invalid) calls to
1687 * pthread_getspecific() to receive invalid/stale values.
1688 */
1689int pthread_key_delete(pthread_key_t key)
1690{
1691 uint32_t err;
1692 pthread_internal_t* thr;
1693 tlsmap_t* map;
1694
1695 if (!TLSMAP_VALIDATE_KEY(key)) {
1696 return EINVAL;
1697 }
1698
1699 map = tlsmap_lock();
1700
1701 if (!tlsmap_test(map, key)) {
1702 err = EINVAL;
1703 goto err1;
1704 }
1705
1706 /* clear value in all threads */
1707 pthread_mutex_lock(&gThreadListLock);
1708 for ( thr = gThreadList; thr != NULL; thr = thr->next ) {
1709 /* avoid zombie threads with a negative 'join_count'. these are really
1710 * already dead and don't have a TLS area anymore.
1711 *
1712 * similarly, it is possible to have thr->tls == NULL for threads that
1713 * were just recently created through pthread_create() but whose
1714 * startup trampoline (__thread_entry) hasn't been run yet by the
1715 * scheduler. so check for this too.
1716 */
1717 if (thr->join_count < 0 || !thr->tls)
1718 continue;
1719
1720 thr->tls[key] = NULL;
1721 }
1722 tlsmap_clear(map, key);
1723
1724 pthread_mutex_unlock(&gThreadListLock);
1725 err = 0;
1726
1727err1:
1728 tlsmap_unlock(map);
1729 return err;
1730}
1731
1732
1733int pthread_setspecific(pthread_key_t key, const void *ptr)
1734{
1735 int err = EINVAL;
1736 tlsmap_t* map;
1737
1738 if (TLSMAP_VALIDATE_KEY(key)) {
1739 /* check that we're trying to set data for an allocated key */
1740 map = tlsmap_lock();
1741 if (tlsmap_test(map, key)) {
1742 ((uint32_t *)__get_tls())[key] = (uint32_t)ptr;
1743 err = 0;
1744 }
1745 tlsmap_unlock(map);
1746 }
1747 return err;
1748}
1749
1750void * pthread_getspecific(pthread_key_t key)
1751{
1752 if (!TLSMAP_VALIDATE_KEY(key)) {
1753 return NULL;
1754 }
1755
1756 /* for performance reason, we do not lock/unlock the global TLS map
1757 * to check that the key is properly allocated. if the key was not
1758 * allocated, the value read from the TLS should always be NULL
1759 * due to pthread_key_delete() clearing the values for all threads.
1760 */
1761 return (void *)(((unsigned *)__get_tls())[key]);
1762}
1763
1764/* Posix mandates that this be defined in <limits.h> but we don't have
1765 * it just yet.
1766 */
1767#ifndef PTHREAD_DESTRUCTOR_ITERATIONS
1768# define PTHREAD_DESTRUCTOR_ITERATIONS 4
1769#endif
1770
1771/* this function is called from pthread_exit() to remove all TLS key data
1772 * from this thread's TLS area. this must call the destructor of all keys
1773 * that have a non-NULL data value (and a non-NULL destructor).
1774 *
1775 * because destructors can do funky things like deleting/creating other
1776 * keys, we need to implement this in a loop
1777 */
1778static void pthread_key_clean_all(void)
1779{
1780 tlsmap_t* map;
1781 void** tls = (void**)__get_tls();
1782 int rounds = PTHREAD_DESTRUCTOR_ITERATIONS;
1783
1784 map = tlsmap_lock();
1785
1786 for (rounds = PTHREAD_DESTRUCTOR_ITERATIONS; rounds > 0; rounds--)
1787 {
1788 int kk, count = 0;
1789
1790 for (kk = TLSMAP_START; kk < TLSMAP_SIZE; kk++) {
1791 if ( tlsmap_test(map, kk) )
1792 {
1793 void* data = tls[kk];
1794 tls_dtor_t dtor = map->dtors[kk];
1795
1796 if (data != NULL && dtor != NULL)
1797 {
1798 /* we need to clear the key data now, this will prevent the
1799 * destructor (or a later one) from seeing the old value if
1800 * it calls pthread_getspecific() for some odd reason
1801 *
1802 * we do not do this if 'dtor == NULL' just in case another
1803 * destructor function might be responsible for manually
1804 * releasing the corresponding data.
1805 */
1806 tls[kk] = NULL;
1807
1808 /* because the destructor is free to call pthread_key_create
1809 * and/or pthread_key_delete, we need to temporarily unlock
1810 * the TLS map
1811 */
1812 tlsmap_unlock(map);
1813 (*dtor)(data);
1814 map = tlsmap_lock();
1815
1816 count += 1;
1817 }
1818 }
1819 }
1820
1821 /* if we didn't call any destructor, there is no need to check the
1822 * TLS data again
1823 */
1824 if (count == 0)
1825 break;
1826 }
1827 tlsmap_unlock(map);
1828}
1829
1830// man says this should be in <linux/unistd.h>, but it isn't
1831extern int tkill(int tid, int sig);
1832
1833int pthread_kill(pthread_t tid, int sig)
1834{
1835 int ret;
1836 int old_errno = errno;
1837 pthread_internal_t * thread = (pthread_internal_t *)tid;
1838
1839 ret = tkill(thread->kernel_id, sig);
1840 if (ret < 0) {
1841 ret = errno;
1842 errno = old_errno;
1843 }
1844
1845 return ret;
1846}
1847
Bruce Bearee4a21c82011-12-05 11:25:37 -08001848/* Despite the fact that our kernel headers define sigset_t explicitly
1849 * as a 32-bit integer, the kernel system call really expects a 64-bit
1850 * bitmap for the signal set, or more exactly an array of two-32-bit
1851 * values (see $KERNEL/arch/$ARCH/include/asm/signal.h for details).
1852 *
1853 * Unfortunately, we cannot fix the sigset_t definition without breaking
1854 * the C library ABI, so perform a little runtime translation here.
1855 */
1856typedef union {
1857 sigset_t bionic;
1858 uint32_t kernel[2];
1859} kernel_sigset_t;
1860
1861/* this is a private syscall stub */
1862extern int __rt_sigprocmask(int, const kernel_sigset_t *, kernel_sigset_t *, size_t);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001863
1864int pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
1865{
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001866 /* pthread_sigmask must return the error code, but the syscall
1867 * will set errno instead and return 0/-1
1868 */
1869 int ret, old_errno = errno;
1870
Bruce Bearee4a21c82011-12-05 11:25:37 -08001871 /* We must convert *set into a kernel_sigset_t */
1872 kernel_sigset_t in_set, *in_set_ptr;
1873 kernel_sigset_t out_set;
1874
1875 in_set.kernel[0] = in_set.kernel[1] = 0;
1876 out_set.kernel[0] = out_set.kernel[1] = 0;
1877
1878 /* 'in_set_ptr' is the second parameter to __rt_sigprocmask. It must be NULL
1879 * if 'set' is NULL to ensure correct semantics (which in this case would
1880 * be to ignore 'how' and return the current signal set into 'oset'.
1881 */
1882 if (set == NULL) {
1883 in_set_ptr = NULL;
1884 } else {
1885 in_set.bionic = *set;
1886 in_set_ptr = &in_set;
1887 }
1888
1889 ret = __rt_sigprocmask(how, in_set_ptr, &out_set, sizeof(kernel_sigset_t));
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001890 if (ret < 0)
1891 ret = errno;
1892
Bruce Bearee4a21c82011-12-05 11:25:37 -08001893 if (oset)
1894 *oset = out_set.bionic;
1895
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001896 errno = old_errno;
1897 return ret;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001898}
1899
1900
1901int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
1902{
1903 const int CLOCK_IDTYPE_BITS = 3;
1904 pthread_internal_t* thread = (pthread_internal_t*)tid;
1905
1906 if (!thread)
1907 return ESRCH;
1908
1909 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
1910 return 0;
1911}
1912
1913
1914/* NOTE: this implementation doesn't support a init function that throws a C++ exception
1915 * or calls fork()
1916 */
1917int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
1918{
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001919 static pthread_mutex_t once_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001920 volatile pthread_once_t* ocptr = once_control;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001921
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001922 pthread_once_t tmp = *ocptr;
1923 ANDROID_MEMBAR_FULL();
1924 if (tmp == PTHREAD_ONCE_INIT) {
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001925 pthread_mutex_lock( &once_lock );
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001926 if (*ocptr == PTHREAD_ONCE_INIT) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001927 (*init_routine)();
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001928 ANDROID_MEMBAR_FULL();
1929 *ocptr = ~PTHREAD_ONCE_INIT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001930 }
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001931 pthread_mutex_unlock( &once_lock );
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001932 }
1933 return 0;
1934}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03001935
1936/* This value is not exported by kernel headers, so hardcode it here */
1937#define MAX_TASK_COMM_LEN 16
1938#define TASK_COMM_FMT "/proc/self/task/%u/comm"
1939
1940int pthread_setname_np(pthread_t thid, const char *thname)
1941{
1942 size_t thname_len;
1943 int saved_errno, ret;
1944
1945 if (thid == 0 || thname == NULL)
1946 return EINVAL;
1947
1948 thname_len = strlen(thname);
1949 if (thname_len >= MAX_TASK_COMM_LEN)
1950 return ERANGE;
1951
1952 saved_errno = errno;
1953 if (thid == pthread_self())
1954 {
1955 ret = prctl(PR_SET_NAME, (unsigned long)thname, 0, 0, 0) ? errno : 0;
1956 }
1957 else
1958 {
1959 /* Have to change another thread's name */
1960 pthread_internal_t *thread = (pthread_internal_t *)thid;
1961 char comm_name[sizeof(TASK_COMM_FMT) + 8];
1962 ssize_t n;
1963 int fd;
1964
1965 snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, (unsigned int)thread->kernel_id);
1966 fd = open(comm_name, O_RDWR);
1967 if (fd == -1)
1968 {
1969 ret = errno;
1970 goto exit;
1971 }
1972 n = TEMP_FAILURE_RETRY(write(fd, thname, thname_len));
1973 close(fd);
1974
1975 if (n < 0)
1976 ret = errno;
1977 else if ((size_t)n != thname_len)
1978 ret = EIO;
1979 else
1980 ret = 0;
1981 }
1982exit:
1983 errno = saved_errno;
1984 return ret;
1985}
Glenn Kastend53cae02011-07-11 15:41:28 -07001986
1987/* Return the kernel thread ID for a pthread.
1988 * This is only defined for implementations where pthread <-> kernel is 1:1, which this is.
1989 * Not the same as pthread_getthreadid_np, which is commonly defined to be opaque.
1990 * Internal, not an NDK API.
1991 */
1992
1993pid_t __pthread_gettid(pthread_t thid)
1994{
1995 pthread_internal_t* thread = (pthread_internal_t*)thid;
1996 return thread->kernel_id;
1997}
Jack Rend8bc6e72012-01-17 16:27:42 +08001998
1999int __pthread_settid(pthread_t thid, pid_t tid)
2000{
2001 if (thid == 0)
2002 return EINVAL;
2003
2004 pthread_internal_t* thread = (pthread_internal_t*)thid;
2005 thread->kernel_id = tid;
2006
2007 return 0;
2008}