blob: 16d49983d13ffb241ee14ac7d9f6b024c63e8b58 [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 */
28#include <sys/types.h>
29#include <unistd.h>
30#include <signal.h>
31#include <stdint.h>
32#include <stdio.h>
33#include <stdlib.h>
34#include <errno.h>
35#include <sys/atomics.h>
36#include <bionic_tls.h>
37#include <sys/mman.h>
38#include <pthread.h>
39#include <time.h>
40#include "pthread_internal.h"
41#include "thread_private.h"
42#include <limits.h>
43#include <memory.h>
44#include <assert.h>
45#include <malloc.h>
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -070046#include <bionic_futex.h>
David 'Digit' Turner6c8a2f22010-06-10 23:34:24 -070047#include <bionic_atomic_inline.h>
André Goddard Rosa78c1c042010-05-19 23:17:16 -030048#include <sys/prctl.h>
49#include <sys/stat.h>
50#include <fcntl.h>
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -070051#include <stdio.h>
Glenn Kastend53cae02011-07-11 15:41:28 -070052#include <bionic_pthread.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080053
Mathias Agopian7c0c3792011-09-05 23:54:55 -070054extern void pthread_debug_mutex_lock_check(pthread_mutex_t *mutex);
55extern void pthread_debug_mutex_unlock_check(pthread_mutex_t *mutex);
56
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080057extern int __pthread_clone(int (*fn)(void*), void *child_stack, int flags, void *arg);
58extern void _exit_with_stack_teardown(void * stackBase, int stackSize, int retCode);
59extern void _exit_thread(int retCode);
60extern int __set_errno(int);
61
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -070062int __futex_wake_ex(volatile void *ftx, int pshared, int val)
63{
64 return __futex_syscall3(ftx, pshared ? FUTEX_WAKE : FUTEX_WAKE_PRIVATE, val);
65}
66
67int __futex_wait_ex(volatile void *ftx, int pshared, int val, const struct timespec *timeout)
68{
69 return __futex_syscall4(ftx, pshared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE, val, timeout);
70}
71
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -070072#define __likely(cond) __builtin_expect(!!(cond), 1)
73#define __unlikely(cond) __builtin_expect(!!(cond), 0)
74
Bruce Beare8e551a62011-03-28 09:47:35 -070075#ifdef __i386__
76#define ATTRIBUTES __attribute__((noinline)) __attribute__((fastcall))
77#else
78#define ATTRIBUTES __attribute__((noinline))
79#endif
80
81void ATTRIBUTES _thread_created_hook(pid_t thread_id);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080082
83#define PTHREAD_ATTR_FLAG_DETACHED 0x00000001
84#define PTHREAD_ATTR_FLAG_USER_STACK 0x00000002
85
86#define DEFAULT_STACKSIZE (1024 * 1024)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080087
88static pthread_mutex_t mmap_lock = PTHREAD_MUTEX_INITIALIZER;
89
90
91static const pthread_attr_t gDefaultPthreadAttr = {
92 .flags = 0,
93 .stack_base = NULL,
94 .stack_size = DEFAULT_STACKSIZE,
95 .guard_size = PAGE_SIZE,
96 .sched_policy = SCHED_NORMAL,
97 .sched_priority = 0
98};
99
100#define INIT_THREADS 1
101
102static pthread_internal_t* gThreadList = NULL;
103static pthread_mutex_t gThreadListLock = PTHREAD_MUTEX_INITIALIZER;
104static pthread_mutex_t gDebuggerNotificationLock = PTHREAD_MUTEX_INITIALIZER;
105
106
107/* we simply malloc/free the internal pthread_internal_t structures. we may
108 * want to use a different allocation scheme in the future, but this one should
109 * be largely enough
110 */
111static pthread_internal_t*
112_pthread_internal_alloc(void)
113{
114 pthread_internal_t* thread;
115
116 thread = calloc( sizeof(*thread), 1 );
117 if (thread)
118 thread->intern = 1;
119
120 return thread;
121}
122
123static void
124_pthread_internal_free( pthread_internal_t* thread )
125{
126 if (thread && thread->intern) {
127 thread->intern = 0; /* just in case */
128 free (thread);
129 }
130}
131
132
133static void
134_pthread_internal_remove_locked( pthread_internal_t* thread )
135{
136 thread->next->pref = thread->pref;
137 thread->pref[0] = thread->next;
138}
139
140static void
141_pthread_internal_remove( pthread_internal_t* thread )
142{
143 pthread_mutex_lock(&gThreadListLock);
144 _pthread_internal_remove_locked(thread);
145 pthread_mutex_unlock(&gThreadListLock);
146}
147
148static void
149_pthread_internal_add( pthread_internal_t* thread )
150{
151 pthread_mutex_lock(&gThreadListLock);
152 thread->pref = &gThreadList;
153 thread->next = thread->pref[0];
154 if (thread->next)
155 thread->next->pref = &thread->next;
156 thread->pref[0] = thread;
157 pthread_mutex_unlock(&gThreadListLock);
158}
159
160pthread_internal_t*
161__get_thread(void)
162{
163 void** tls = (void**)__get_tls();
164
165 return (pthread_internal_t*) tls[TLS_SLOT_THREAD_ID];
166}
167
168
169void*
170__get_stack_base(int *p_stack_size)
171{
172 pthread_internal_t* thread = __get_thread();
173
174 *p_stack_size = thread->attr.stack_size;
175 return thread->attr.stack_base;
176}
177
178
179void __init_tls(void** tls, void* thread)
180{
181 int nn;
182
183 ((pthread_internal_t*)thread)->tls = tls;
184
185 // slot 0 must point to the tls area, this is required by the implementation
186 // of the x86 Linux kernel thread-local-storage
187 tls[TLS_SLOT_SELF] = (void*)tls;
188 tls[TLS_SLOT_THREAD_ID] = thread;
189 for (nn = TLS_SLOT_ERRNO; nn < BIONIC_TLS_SLOTS; nn++)
190 tls[nn] = 0;
191
192 __set_tls( (void*)tls );
193}
194
195
196/*
197 * This trampoline is called from the assembly clone() function
198 */
199void __thread_entry(int (*func)(void*), void *arg, void **tls)
200{
201 int retValue;
202 pthread_internal_t * thrInfo;
203
204 // Wait for our creating thread to release us. This lets it have time to
205 // notify gdb about this thread before it starts doing anything.
Andy McFaddene2ac8982010-09-02 13:34:53 -0700206 //
207 // This also provides the memory barrier needed to ensure that all memory
208 // accesses previously made by the creating thread are visible to us.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800209 pthread_mutex_t * start_mutex = (pthread_mutex_t *)&tls[TLS_SLOT_SELF];
210 pthread_mutex_lock(start_mutex);
211 pthread_mutex_destroy(start_mutex);
212
213 thrInfo = (pthread_internal_t *) tls[TLS_SLOT_THREAD_ID];
214
215 __init_tls( tls, thrInfo );
216
217 pthread_exit( (void*)func(arg) );
218}
219
220void _init_thread(pthread_internal_t * thread, pid_t kernel_id, pthread_attr_t * attr, void * stack_base)
221{
222 if (attr == NULL) {
223 thread->attr = gDefaultPthreadAttr;
224 } else {
225 thread->attr = *attr;
226 }
227 thread->attr.stack_base = stack_base;
228 thread->kernel_id = kernel_id;
229
230 // set the scheduling policy/priority of the thread
231 if (thread->attr.sched_policy != SCHED_NORMAL) {
232 struct sched_param param;
233 param.sched_priority = thread->attr.sched_priority;
234 sched_setscheduler(kernel_id, thread->attr.sched_policy, &param);
235 }
236
237 pthread_cond_init(&thread->join_cond, NULL);
238 thread->join_count = 0;
239
240 thread->cleanup_stack = NULL;
241
242 _pthread_internal_add(thread);
243}
244
245
246/* XXX stacks not reclaimed if thread spawn fails */
247/* XXX stacks address spaces should be reused if available again */
248
249static void *mkstack(size_t size, size_t guard_size)
250{
251 void * stack;
252
253 pthread_mutex_lock(&mmap_lock);
254
Nick Kralevich5f64df42011-11-17 12:58:20 -0800255 stack = mmap(NULL, size,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800256 PROT_READ | PROT_WRITE,
257 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
258 -1, 0);
259
260 if(stack == MAP_FAILED) {
261 stack = NULL;
262 goto done;
263 }
264
265 if(mprotect(stack, guard_size, PROT_NONE)){
266 munmap(stack, size);
267 stack = NULL;
268 goto done;
269 }
270
271done:
272 pthread_mutex_unlock(&mmap_lock);
273 return stack;
274}
275
276/*
Andy McFaddene2ac8982010-09-02 13:34:53 -0700277 * Create a new thread. The thread's stack is laid out like so:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800278 *
279 * +---------------------------+
280 * | pthread_internal_t |
281 * +---------------------------+
282 * | |
283 * | TLS area |
284 * | |
285 * +---------------------------+
286 * | |
287 * . .
288 * . stack area .
289 * . .
290 * | |
291 * +---------------------------+
292 * | guard page |
293 * +---------------------------+
294 *
295 * note that TLS[0] must be a pointer to itself, this is required
296 * by the thread-local storage implementation of the x86 Linux
297 * kernel, where the TLS pointer is read by reading fs:[0]
298 */
299int pthread_create(pthread_t *thread_out, pthread_attr_t const * attr,
300 void *(*start_routine)(void *), void * arg)
301{
302 char* stack;
303 void** tls;
304 int tid;
305 pthread_mutex_t * start_mutex;
306 pthread_internal_t * thread;
307 int madestack = 0;
308 int old_errno = errno;
309
310 /* this will inform the rest of the C library that at least one thread
311 * was created. this will enforce certain functions to acquire/release
312 * locks (e.g. atexit()) to protect shared global structures.
313 *
314 * this works because pthread_create() is not called by the C library
315 * initialization routine that sets up the main thread's data structures.
316 */
317 __isthreaded = 1;
318
319 thread = _pthread_internal_alloc();
320 if (thread == NULL)
321 return ENOMEM;
322
323 if (attr == NULL) {
324 attr = &gDefaultPthreadAttr;
325 }
326
327 // make sure the stack is PAGE_SIZE aligned
328 size_t stackSize = (attr->stack_size +
329 (PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
330
331 if (!attr->stack_base) {
332 stack = mkstack(stackSize, attr->guard_size);
333 if(stack == NULL) {
334 _pthread_internal_free(thread);
335 return ENOMEM;
336 }
337 madestack = 1;
338 } else {
339 stack = attr->stack_base;
340 }
341
342 // Make room for TLS
343 tls = (void**)(stack + stackSize - BIONIC_TLS_SLOTS*sizeof(void*));
344
345 // Create a mutex for the thread in TLS_SLOT_SELF to wait on once it starts so we can keep
346 // it from doing anything until after we notify the debugger about it
Andy McFaddene2ac8982010-09-02 13:34:53 -0700347 //
348 // This also provides the memory barrier we need to ensure that all
349 // memory accesses previously performed by this thread are visible to
350 // the new thread.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800351 start_mutex = (pthread_mutex_t *) &tls[TLS_SLOT_SELF];
352 pthread_mutex_init(start_mutex, NULL);
353 pthread_mutex_lock(start_mutex);
354
355 tls[TLS_SLOT_THREAD_ID] = thread;
356
357 tid = __pthread_clone((int(*)(void*))start_routine, tls,
358 CLONE_FILES | CLONE_FS | CLONE_VM | CLONE_SIGHAND
359 | CLONE_THREAD | CLONE_SYSVSEM | CLONE_DETACHED,
360 arg);
361
362 if(tid < 0) {
363 int result;
364 if (madestack)
365 munmap(stack, stackSize);
366 _pthread_internal_free(thread);
367 result = errno;
368 errno = old_errno;
369 return result;
370 }
371
372 _init_thread(thread, tid, (pthread_attr_t*)attr, stack);
373
374 if (!madestack)
375 thread->attr.flags |= PTHREAD_ATTR_FLAG_USER_STACK;
376
377 // Notify any debuggers about the new thread
378 pthread_mutex_lock(&gDebuggerNotificationLock);
379 _thread_created_hook(tid);
380 pthread_mutex_unlock(&gDebuggerNotificationLock);
381
382 // Let the thread do it's thing
383 pthread_mutex_unlock(start_mutex);
384
385 *thread_out = (pthread_t)thread;
386 return 0;
387}
388
389
390int pthread_attr_init(pthread_attr_t * attr)
391{
392 *attr = gDefaultPthreadAttr;
393 return 0;
394}
395
396int pthread_attr_destroy(pthread_attr_t * attr)
397{
398 memset(attr, 0x42, sizeof(pthread_attr_t));
399 return 0;
400}
401
402int pthread_attr_setdetachstate(pthread_attr_t * attr, int state)
403{
404 if (state == PTHREAD_CREATE_DETACHED) {
405 attr->flags |= PTHREAD_ATTR_FLAG_DETACHED;
406 } else if (state == PTHREAD_CREATE_JOINABLE) {
407 attr->flags &= ~PTHREAD_ATTR_FLAG_DETACHED;
408 } else {
409 return EINVAL;
410 }
411 return 0;
412}
413
414int pthread_attr_getdetachstate(pthread_attr_t const * attr, int * state)
415{
416 *state = (attr->flags & PTHREAD_ATTR_FLAG_DETACHED)
417 ? PTHREAD_CREATE_DETACHED
418 : PTHREAD_CREATE_JOINABLE;
419 return 0;
420}
421
422int pthread_attr_setschedpolicy(pthread_attr_t * attr, int policy)
423{
424 attr->sched_policy = policy;
425 return 0;
426}
427
428int pthread_attr_getschedpolicy(pthread_attr_t const * attr, int * policy)
429{
430 *policy = attr->sched_policy;
431 return 0;
432}
433
434int pthread_attr_setschedparam(pthread_attr_t * attr, struct sched_param const * param)
435{
436 attr->sched_priority = param->sched_priority;
437 return 0;
438}
439
440int pthread_attr_getschedparam(pthread_attr_t const * attr, struct sched_param * param)
441{
442 param->sched_priority = attr->sched_priority;
443 return 0;
444}
445
446int pthread_attr_setstacksize(pthread_attr_t * attr, size_t stack_size)
447{
448 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
449 return EINVAL;
450 }
451 attr->stack_size = stack_size;
452 return 0;
453}
454
455int pthread_attr_getstacksize(pthread_attr_t const * attr, size_t * stack_size)
456{
457 *stack_size = attr->stack_size;
458 return 0;
459}
460
461int pthread_attr_setstackaddr(pthread_attr_t * attr, void * stack_addr)
462{
463#if 1
464 // It's not clear if this is setting the top or bottom of the stack, so don't handle it for now.
465 return ENOSYS;
466#else
467 if ((uint32_t)stack_addr & (PAGE_SIZE - 1)) {
468 return EINVAL;
469 }
470 attr->stack_base = stack_addr;
471 return 0;
472#endif
473}
474
475int pthread_attr_getstackaddr(pthread_attr_t const * attr, void ** stack_addr)
476{
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700477 *stack_addr = (char*)attr->stack_base + attr->stack_size;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800478 return 0;
479}
480
481int pthread_attr_setstack(pthread_attr_t * attr, void * stack_base, size_t stack_size)
482{
483 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
484 return EINVAL;
485 }
486 if ((uint32_t)stack_base & (PAGE_SIZE - 1)) {
487 return EINVAL;
488 }
489 attr->stack_base = stack_base;
490 attr->stack_size = stack_size;
491 return 0;
492}
493
494int pthread_attr_getstack(pthread_attr_t const * attr, void ** stack_base, size_t * stack_size)
495{
496 *stack_base = attr->stack_base;
497 *stack_size = attr->stack_size;
498 return 0;
499}
500
501int pthread_attr_setguardsize(pthread_attr_t * attr, size_t guard_size)
502{
503 if (guard_size & (PAGE_SIZE - 1) || guard_size < PAGE_SIZE) {
504 return EINVAL;
505 }
506
507 attr->guard_size = guard_size;
508 return 0;
509}
510
511int pthread_attr_getguardsize(pthread_attr_t const * attr, size_t * guard_size)
512{
513 *guard_size = attr->guard_size;
514 return 0;
515}
516
517int pthread_getattr_np(pthread_t thid, pthread_attr_t * attr)
518{
519 pthread_internal_t * thread = (pthread_internal_t *)thid;
520 *attr = thread->attr;
521 return 0;
522}
523
524int pthread_attr_setscope(pthread_attr_t *attr, int scope)
525{
526 if (scope == PTHREAD_SCOPE_SYSTEM)
527 return 0;
528 if (scope == PTHREAD_SCOPE_PROCESS)
529 return ENOTSUP;
530
531 return EINVAL;
532}
533
534int pthread_attr_getscope(pthread_attr_t const *attr)
535{
536 return PTHREAD_SCOPE_SYSTEM;
537}
538
539
540/* CAVEAT: our implementation of pthread_cleanup_push/pop doesn't support C++ exceptions
541 * and thread cancelation
542 */
543
544void __pthread_cleanup_push( __pthread_cleanup_t* c,
545 __pthread_cleanup_func_t routine,
546 void* arg )
547{
548 pthread_internal_t* thread = __get_thread();
549
550 c->__cleanup_routine = routine;
551 c->__cleanup_arg = arg;
552 c->__cleanup_prev = thread->cleanup_stack;
553 thread->cleanup_stack = c;
554}
555
556void __pthread_cleanup_pop( __pthread_cleanup_t* c, int execute )
557{
558 pthread_internal_t* thread = __get_thread();
559
560 thread->cleanup_stack = c->__cleanup_prev;
561 if (execute)
562 c->__cleanup_routine(c->__cleanup_arg);
563}
564
565/* used by pthread_exit() to clean all TLS keys of the current thread */
566static void pthread_key_clean_all(void);
567
568void pthread_exit(void * retval)
569{
570 pthread_internal_t* thread = __get_thread();
571 void* stack_base = thread->attr.stack_base;
572 int stack_size = thread->attr.stack_size;
573 int user_stack = (thread->attr.flags & PTHREAD_ATTR_FLAG_USER_STACK) != 0;
Jack Rene480fc82011-09-21 12:44:11 +0200574 sigset_t mask;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800575
576 // call the cleanup handlers first
577 while (thread->cleanup_stack) {
578 __pthread_cleanup_t* c = thread->cleanup_stack;
579 thread->cleanup_stack = c->__cleanup_prev;
580 c->__cleanup_routine(c->__cleanup_arg);
581 }
582
583 // call the TLS destructors, it is important to do that before removing this
584 // thread from the global list. this will ensure that if someone else deletes
585 // a TLS key, the corresponding value will be set to NULL in this thread's TLS
586 // space (see pthread_key_delete)
587 pthread_key_clean_all();
588
589 // if the thread is detached, destroy the pthread_internal_t
590 // otherwise, keep it in memory and signal any joiners
591 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
592 _pthread_internal_remove(thread);
593 _pthread_internal_free(thread);
594 } else {
595 /* the join_count field is used to store the number of threads waiting for
596 * the termination of this thread with pthread_join(),
597 *
598 * if it is positive we need to signal the waiters, and we do not touch
599 * the count (it will be decremented by the waiters, the last one will
600 * also remove/free the thread structure
601 *
602 * if it is zero, we set the count value to -1 to indicate that the
603 * thread is in 'zombie' state: it has stopped executing, and its stack
604 * is gone (as well as its TLS area). when another thread calls pthread_join()
605 * on it, it will immediately free the thread and return.
606 */
607 pthread_mutex_lock(&gThreadListLock);
608 thread->return_value = retval;
609 if (thread->join_count > 0) {
610 pthread_cond_broadcast(&thread->join_cond);
611 } else {
612 thread->join_count = -1; /* zombie thread */
613 }
614 pthread_mutex_unlock(&gThreadListLock);
615 }
616
Jack Rene480fc82011-09-21 12:44:11 +0200617 sigfillset(&mask);
618 sigdelset(&mask, SIGSEGV);
619 (void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *)NULL);
620
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800621 // destroy the thread stack
622 if (user_stack)
623 _exit_thread((int)retval);
624 else
625 _exit_with_stack_teardown(stack_base, stack_size, (int)retval);
626}
627
628int pthread_join(pthread_t thid, void ** ret_val)
629{
630 pthread_internal_t* thread = (pthread_internal_t*)thid;
631 int count;
632
633 // check that the thread still exists and is not detached
634 pthread_mutex_lock(&gThreadListLock);
635
636 for (thread = gThreadList; thread != NULL; thread = thread->next)
637 if (thread == (pthread_internal_t*)thid)
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200638 goto FoundIt;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800639
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200640 pthread_mutex_unlock(&gThreadListLock);
641 return ESRCH;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800642
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200643FoundIt:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800644 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
645 pthread_mutex_unlock(&gThreadListLock);
646 return EINVAL;
647 }
648
649 /* wait for thread death when needed
650 *
651 * if the 'join_count' is negative, this is a 'zombie' thread that
652 * is already dead and without stack/TLS
653 *
654 * otherwise, we need to increment 'join-count' and wait to be signaled
655 */
656 count = thread->join_count;
657 if (count >= 0) {
658 thread->join_count += 1;
659 pthread_cond_wait( &thread->join_cond, &gThreadListLock );
660 count = --thread->join_count;
661 }
662 if (ret_val)
663 *ret_val = thread->return_value;
664
665 /* remove thread descriptor when we're the last joiner or when the
666 * thread was already a zombie.
667 */
668 if (count <= 0) {
669 _pthread_internal_remove_locked(thread);
670 _pthread_internal_free(thread);
671 }
672 pthread_mutex_unlock(&gThreadListLock);
673 return 0;
674}
675
676int pthread_detach( pthread_t thid )
677{
678 pthread_internal_t* thread;
679 int result = 0;
680 int flags;
681
682 pthread_mutex_lock(&gThreadListLock);
683 for (thread = gThreadList; thread != NULL; thread = thread->next)
684 if (thread == (pthread_internal_t*)thid)
685 goto FoundIt;
686
687 result = ESRCH;
688 goto Exit;
689
690FoundIt:
691 do {
692 flags = thread->attr.flags;
693
694 if ( flags & PTHREAD_ATTR_FLAG_DETACHED ) {
695 /* thread is not joinable ! */
696 result = EINVAL;
697 goto Exit;
698 }
699 }
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100700 while ( __bionic_cmpxchg( flags, flags | PTHREAD_ATTR_FLAG_DETACHED,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800701 (volatile int*)&thread->attr.flags ) != 0 );
702Exit:
703 pthread_mutex_unlock(&gThreadListLock);
704 return result;
705}
706
707pthread_t pthread_self(void)
708{
709 return (pthread_t)__get_thread();
710}
711
712int pthread_equal(pthread_t one, pthread_t two)
713{
714 return (one == two ? 1 : 0);
715}
716
717int pthread_getschedparam(pthread_t thid, int * policy,
718 struct sched_param * param)
719{
720 int old_errno = errno;
721
722 pthread_internal_t * thread = (pthread_internal_t *)thid;
723 int err = sched_getparam(thread->kernel_id, param);
724 if (!err) {
725 *policy = sched_getscheduler(thread->kernel_id);
726 } else {
727 err = errno;
728 errno = old_errno;
729 }
730 return err;
731}
732
733int pthread_setschedparam(pthread_t thid, int policy,
734 struct sched_param const * param)
735{
736 pthread_internal_t * thread = (pthread_internal_t *)thid;
737 int old_errno = errno;
738 int ret;
739
740 ret = sched_setscheduler(thread->kernel_id, policy, param);
741 if (ret < 0) {
742 ret = errno;
743 errno = old_errno;
744 }
745 return ret;
746}
747
748
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800749// mutex lock states
750//
751// 0: unlocked
752// 1: locked, no waiters
753// 2: locked, maybe waiters
754
755/* a mutex is implemented as a 32-bit integer holding the following fields
756 *
757 * bits: name description
758 * 31-16 tid owner thread's kernel id (recursive and errorcheck only)
759 * 15-14 type mutex type
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700760 * 13 shared process-shared flag
761 * 12-2 counter counter of recursive mutexes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800762 * 1-0 state lock state (0, 1 or 2)
763 */
764
765
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100766#define MUTEX_VALUE_OWNER(v) (((v) >> 16) & 0xffff)
767#define MUTEX_VALUE_COUNTER(v) (((v) >> 2) & 0xfff)
768
769#define MUTEX_OWNER(m) MUTEX_VALUE_OWNER((m)->value)
770#define MUTEX_COUNTER(m) MUTEX_VALUE_COUNTER((m)->value)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800771
772#define MUTEX_TYPE_MASK 0xc000
773#define MUTEX_TYPE_NORMAL 0x0000
774#define MUTEX_TYPE_RECURSIVE 0x4000
775#define MUTEX_TYPE_ERRORCHECK 0x8000
776
777#define MUTEX_COUNTER_SHIFT 2
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700778#define MUTEX_COUNTER_MASK 0x1ffc
779#define MUTEX_SHARED_MASK 0x2000
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800780
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700781/* a mutex attribute holds the following fields
782 *
783 * bits: name description
784 * 0-3 type type of mutex
785 * 4 shared process-shared flag
786 */
787#define MUTEXATTR_TYPE_MASK 0x000f
788#define MUTEXATTR_SHARED_MASK 0x0010
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800789
790
791int pthread_mutexattr_init(pthread_mutexattr_t *attr)
792{
793 if (attr) {
794 *attr = PTHREAD_MUTEX_DEFAULT;
795 return 0;
796 } else {
797 return EINVAL;
798 }
799}
800
801int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
802{
803 if (attr) {
804 *attr = -1;
805 return 0;
806 } else {
807 return EINVAL;
808 }
809}
810
811int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
812{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700813 if (attr) {
814 int atype = (*attr & MUTEXATTR_TYPE_MASK);
815
816 if (atype >= PTHREAD_MUTEX_NORMAL &&
817 atype <= PTHREAD_MUTEX_ERRORCHECK) {
818 *type = atype;
819 return 0;
820 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800821 }
822 return EINVAL;
823}
824
825int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
826{
827 if (attr && type >= PTHREAD_MUTEX_NORMAL &&
828 type <= PTHREAD_MUTEX_ERRORCHECK ) {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700829 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800830 return 0;
831 }
832 return EINVAL;
833}
834
835/* process-shared mutexes are not supported at the moment */
836
837int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
838{
839 if (!attr)
840 return EINVAL;
841
Mathias Agopianb7681162009-07-13 22:00:33 -0700842 switch (pshared) {
843 case PTHREAD_PROCESS_PRIVATE:
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700844 *attr &= ~MUTEXATTR_SHARED_MASK;
845 return 0;
846
Mathias Agopianb7681162009-07-13 22:00:33 -0700847 case PTHREAD_PROCESS_SHARED:
848 /* our current implementation of pthread actually supports shared
849 * mutexes but won't cleanup if a process dies with the mutex held.
850 * Nevertheless, it's better than nothing. Shared mutexes are used
851 * by surfaceflinger and audioflinger.
852 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700853 *attr |= MUTEXATTR_SHARED_MASK;
Mathias Agopianb7681162009-07-13 22:00:33 -0700854 return 0;
855 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700856 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800857}
858
859int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
860{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700861 if (!attr || !pshared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800862 return EINVAL;
863
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700864 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED
865 : PTHREAD_PROCESS_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800866 return 0;
867}
868
869int pthread_mutex_init(pthread_mutex_t *mutex,
870 const pthread_mutexattr_t *attr)
871{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700872 int value = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800873
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700874 if (mutex == NULL)
875 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800876
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700877 if (__likely(attr == NULL)) {
878 mutex->value = MUTEX_TYPE_NORMAL;
879 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800880 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700881
882 if ((*attr & MUTEXATTR_SHARED_MASK) != 0)
883 value |= MUTEX_SHARED_MASK;
884
885 switch (*attr & MUTEXATTR_TYPE_MASK) {
886 case PTHREAD_MUTEX_NORMAL:
887 value |= MUTEX_TYPE_NORMAL;
888 break;
889 case PTHREAD_MUTEX_RECURSIVE:
890 value |= MUTEX_TYPE_RECURSIVE;
891 break;
892 case PTHREAD_MUTEX_ERRORCHECK:
893 value |= MUTEX_TYPE_ERRORCHECK;
894 break;
895 default:
896 return EINVAL;
897 }
898
899 mutex->value = value;
900 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800901}
902
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800903
904/*
905 * Lock a non-recursive mutex.
906 *
907 * As noted above, there are three states:
908 * 0 (unlocked, no contention)
909 * 1 (locked, no contention)
910 * 2 (locked, contention)
911 *
912 * Non-recursive mutexes don't use the thread-id or counter fields, and the
913 * "type" value is zero, so the only bits that will be set are the ones in
914 * the lock state field.
915 */
916static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100917_normal_lock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800918{
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800919 /*
920 * The common case is an unlocked mutex, so we begin by trying to
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100921 * change the lock's state from 0 to 1. __bionic_cmpxchg() returns 0
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800922 * if it made the swap successfully. If the result is nonzero, this
923 * lock is already held by another thread.
924 */
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100925 if (__bionic_cmpxchg(shared|0, shared|1, &mutex->value ) != 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800926 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800927 * We want to go to sleep until the mutex is available, which
928 * requires promoting it to state 2. We need to swap in the new
929 * state value and then wait until somebody wakes us up.
930 *
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100931 * __bionic_swap() returns the previous value. We swap 2 in and
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800932 * see if we got zero back; if so, we have acquired the lock. If
933 * not, another thread still holds the lock and we wait again.
934 *
935 * The second argument to the __futex_wait() call is compared
936 * against the current value. If it doesn't match, __futex_wait()
937 * returns immediately (otherwise, it sleeps for a time specified
938 * by the third argument; 0 means sleep forever). This ensures
939 * that the mutex is in state 2 when we go to sleep on it, which
940 * guarantees a wake-up call.
941 */
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100942 while (__bionic_swap(shared|2, &mutex->value ) != (shared|0))
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -0700943 __futex_wait_ex(&mutex->value, shared, shared|2, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800944 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700945 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800946}
947
948/*
949 * Release a non-recursive mutex. The caller is responsible for determining
950 * that we are in fact the owner of this lock.
951 */
952static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100953_normal_unlock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800954{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700955 ANDROID_MEMBAR_FULL();
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
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100959 * to release the lock. __bionic_atomic_dec() returns the previous value;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800960 * if it wasn't 1 we have to do some additional work.
961 */
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100962 if (__bionic_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
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001004/* This common inlined function is used to increment the counter of an
1005 * errorcheck or recursive mutex.
1006 *
1007 * For errorcheck mutexes, it will return EDEADLK
1008 * If the counter overflows, it will return EAGAIN
1009 * Otherwise, it atomically increments the counter and returns 0
1010 * after providing an acquire barrier.
1011 *
1012 * mtype is the current mutex type
1013 * mvalue is the current mutex value (already loaded)
1014 * mutex pointers to the mutex.
1015 */
1016static __inline__ __attribute__((always_inline)) int
1017_recursive_increment(pthread_mutex_t* mutex, int mvalue, int mtype)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001018{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001019 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1020 /* trying to re-lock a mutex we already acquired */
1021 return EDEADLK;
1022 }
1023
1024 /* Detect recursive lock overflow and return EAGAIN.
1025 * This is safe because only the owner thread can modify the
1026 * counter bits in the mutes value
1027 */
1028 if ((mvalue & MUTEX_COUNTER_MASK) == MUTEX_COUNTER_MASK) {
1029 return EAGAIN;
1030 }
1031
1032 /* We own the mutex, but other threads are able to change
1033 * the contents (e.g. promoting it to "contended" by changing
1034 * its lower bits), so we need to atomically update it using
1035 * a cmpxchg loop.
1036 */
1037 for (;;) {
1038 /* increment counter, overflow was already checked */
1039 int newvalue = mvalue + (1 << MUTEX_COUNTER_SHIFT);
1040 if (__likely(__bionic_cmpxchg(mvalue, newvalue, &mutex->value) == 0)) {
1041 ANDROID_MEMBAR_FULL();
1042 return 0;
1043 }
1044 /* argh, value was changed, by another thread which updated the 'state'
1045 * field, so reload and try again.
1046 */
1047 mvalue = mutex->value;
1048 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001049}
1050
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001051static pthread_mutex_t __recursive_lock = PTHREAD_MUTEX_INITIALIZER;
1052
1053static __inline__ void
1054_recursive_lock(void)
1055{
1056 _normal_lock(&__recursive_lock, 0);
1057}
1058
1059static __inline__ void
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001060_recursive_unlock(void)
1061{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001062 _normal_unlock(&__recursive_lock, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001063}
1064
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001065__LIBC_HIDDEN__
1066int pthread_mutex_lock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001067{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001068 int mvalue, mtype, tid, new_lock_type, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001069
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001070 if (__unlikely(mutex == NULL))
1071 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001072
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001073 mvalue = mutex->value;
1074 mtype = (mvalue & MUTEX_TYPE_MASK);
1075 shared = (mvalue & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001076
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001077 /* Handle normal case first */
1078 if ( __likely(mtype == MUTEX_TYPE_NORMAL) ) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001079 _normal_lock(mutex, shared);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001080 return 0;
1081 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001082
1083 /* Do we already own this recursive or error-check mutex ? */
1084 tid = __get_thread()->kernel_id;
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001085 if ( tid == MUTEX_VALUE_OWNER(mvalue) )
1086 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001087
1088 /* We don't own the mutex, so try to get it.
1089 *
1090 * First, we try to change its state from 0 to 1, if this
1091 * doesn't work, try to change it to state 2.
1092 */
1093 new_lock_type = 1;
1094
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001095 /* compute futex wait opcode and restore shared flag in mtype */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001096 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001097
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001098 for (;;) {
1099 int oldv;
1100
1101 _recursive_lock();
1102 oldv = mutex->value;
1103 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1104 mutex->value = ((tid << 16) | mtype | new_lock_type);
1105 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1106 oldv ^= 3;
1107 mutex->value = oldv;
1108 }
1109 _recursive_unlock();
1110
1111 if (oldv == mtype)
1112 break;
1113
1114 /*
1115 * The lock was held, possibly contended by others. From
1116 * now on, if we manage to acquire the lock, we have to
1117 * assume that others are still contending for it so that
1118 * we'll wake them when we unlock it.
1119 */
1120 new_lock_type = 2;
1121
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001122 __futex_wait_ex(&mutex->value, shared, oldv, NULL);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001123 }
1124 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001125}
1126
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001127int pthread_mutex_lock(pthread_mutex_t *mutex)
1128{
1129 int err = pthread_mutex_lock_impl(mutex);
1130#ifdef PTHREAD_DEBUG
1131 if (PTHREAD_DEBUG_ENABLED) {
1132 if (!err) {
1133 pthread_debug_mutex_lock_check(mutex);
1134 }
1135 }
1136#endif
1137 return err;
1138}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001139
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001140__LIBC_HIDDEN__
1141int pthread_mutex_unlock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001142{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001143 int mvalue, mtype, tid, oldv, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001144
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001145 if (__unlikely(mutex == NULL))
1146 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001147
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001148 mvalue = mutex->value;
1149 mtype = (mvalue & MUTEX_TYPE_MASK);
1150 shared = (mvalue & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001151
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001152 /* Handle common case first */
1153 if (__likely(mtype == MUTEX_TYPE_NORMAL)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001154 _normal_unlock(mutex, shared);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001155 return 0;
1156 }
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;
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001160 if ( tid != MUTEX_VALUE_OWNER(mvalue) )
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001161 return EPERM;
1162
1163 /* We do, decrement counter or release the mutex if it is 0 */
1164 _recursive_lock();
1165 oldv = mutex->value;
1166 if (oldv & MUTEX_COUNTER_MASK) {
1167 mutex->value = oldv - (1 << MUTEX_COUNTER_SHIFT);
1168 oldv = 0;
1169 } else {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001170 mutex->value = shared | mtype;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001171 }
1172 _recursive_unlock();
1173
1174 /* Wake one waiting thread, if any */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001175 if ((oldv & 3) == 2) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001176 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001177 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001178 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001179}
1180
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001181int pthread_mutex_unlock(pthread_mutex_t *mutex)
1182{
1183#ifdef PTHREAD_DEBUG
1184 if (PTHREAD_DEBUG_ENABLED) {
1185 pthread_debug_mutex_unlock_check(mutex);
1186 }
1187#endif
1188 return pthread_mutex_unlock_impl(mutex);
1189}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001190
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001191__LIBC_HIDDEN__
1192int pthread_mutex_trylock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001193{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001194 int mvalue, mtype, tid, oldv, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001195
1196 if (__unlikely(mutex == NULL))
1197 return EINVAL;
1198
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001199 mvalue = mutex->value;
1200 mtype = (mvalue & MUTEX_TYPE_MASK);
1201 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001202
1203 /* Handle common case first */
1204 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001205 {
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001206 if (__bionic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001207 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001208 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001209 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001210
1211 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001212 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001213
1214 /* Do we already own this recursive or error-check mutex ? */
1215 tid = __get_thread()->kernel_id;
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001216 if ( tid == MUTEX_VALUE_OWNER(mvalue) )
1217 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001218
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001219 /* Restore sharing bit in mtype */
1220 mtype |= shared;
1221
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001222 /* Try to lock it, just once. */
1223 _recursive_lock();
1224 oldv = mutex->value;
1225 if (oldv == mtype) /* uncontended released lock => state 1 */
1226 mutex->value = ((tid << 16) | mtype | 1);
1227 _recursive_unlock();
1228
1229 if (oldv != mtype)
1230 return EBUSY;
1231
1232 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001233}
1234
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001235int pthread_mutex_trylock(pthread_mutex_t *mutex)
1236{
1237 int err = pthread_mutex_trylock_impl(mutex);
1238#ifdef PTHREAD_DEBUG
1239 if (PTHREAD_DEBUG_ENABLED) {
1240 if (!err) {
1241 pthread_debug_mutex_lock_check(mutex);
1242 }
1243 }
1244#endif
1245 return err;
1246}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001247
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001248/* initialize 'ts' with the difference between 'abstime' and the current time
1249 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
1250 */
1251static int
1252__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
1253{
1254 clock_gettime(clock, ts);
1255 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
1256 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
1257 if (ts->tv_nsec < 0) {
1258 ts->tv_sec--;
1259 ts->tv_nsec += 1000000000;
1260 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001261 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001262 return -1;
1263
1264 return 0;
1265}
1266
1267/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1268 * milliseconds.
1269 */
1270static void
1271__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1272{
1273 clock_gettime(clock, abstime);
1274 abstime->tv_sec += msecs/1000;
1275 abstime->tv_nsec += (msecs%1000)*1000000;
1276 if (abstime->tv_nsec >= 1000000000) {
1277 abstime->tv_sec++;
1278 abstime->tv_nsec -= 1000000000;
1279 }
1280}
1281
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001282__LIBC_HIDDEN__
1283int pthread_mutex_lock_timeout_np_impl(pthread_mutex_t *mutex, unsigned msecs)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001284{
1285 clockid_t clock = CLOCK_MONOTONIC;
1286 struct timespec abstime;
1287 struct timespec ts;
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001288 int mvalue, mtype, tid, oldv, new_lock_type, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001289
1290 /* compute absolute expiration time */
1291 __timespec_to_relative_msec(&abstime, msecs, clock);
1292
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001293 if (__unlikely(mutex == NULL))
1294 return EINVAL;
1295
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001296 mvalue = mutex->value;
1297 mtype = (mvalue & MUTEX_TYPE_MASK);
1298 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001299
1300 /* Handle common case first */
1301 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001302 {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001303 /* fast path for uncontended lock */
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001304 if (__bionic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001305 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001306 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001307 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001308
1309 /* loop while needed */
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001310 while (__bionic_swap(shared|2, &mutex->value) != (shared|0)) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001311 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1312 return EBUSY;
1313
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001314 __futex_wait_ex(&mutex->value, shared, shared|2, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001315 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001316 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001317 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001318 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001319
1320 /* Do we already own this recursive or error-check mutex ? */
1321 tid = __get_thread()->kernel_id;
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001322 if ( tid == MUTEX_VALUE_OWNER(mvalue) )
1323 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001324
1325 /* We don't own the mutex, so try to get it.
1326 *
1327 * First, we try to change its state from 0 to 1, if this
1328 * doesn't work, try to change it to state 2.
1329 */
1330 new_lock_type = 1;
1331
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001332 /* Compute wait op and restore sharing bit in mtype */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001333 mtype |= shared;
1334
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001335 for (;;) {
1336 int oldv;
1337 struct timespec ts;
1338
1339 _recursive_lock();
1340 oldv = mutex->value;
1341 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1342 mutex->value = ((tid << 16) | mtype | new_lock_type);
1343 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1344 oldv ^= 3;
1345 mutex->value = oldv;
1346 }
1347 _recursive_unlock();
1348
1349 if (oldv == mtype)
1350 break;
1351
1352 /*
1353 * The lock was held, possibly contended by others. From
1354 * now on, if we manage to acquire the lock, we have to
1355 * assume that others are still contending for it so that
1356 * we'll wake them when we unlock it.
1357 */
1358 new_lock_type = 2;
1359
1360 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1361 return EBUSY;
1362
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001363 __futex_wait_ex(&mutex->value, shared, oldv, &ts);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001364 }
1365 return 0;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001366}
1367
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001368int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1369{
1370 int err = pthread_mutex_lock_timeout_np_impl(mutex, msecs);
1371#ifdef PTHREAD_DEBUG
1372 if (PTHREAD_DEBUG_ENABLED) {
1373 if (!err) {
1374 pthread_debug_mutex_lock_check(mutex);
1375 }
1376 }
1377#endif
1378 return err;
1379}
1380
1381int pthread_mutex_destroy(pthread_mutex_t *mutex)
1382{
1383 int ret;
1384
1385 /* use trylock to ensure that the mutex value is
1386 * valid and is not already locked. */
1387 ret = pthread_mutex_trylock_impl(mutex);
1388 if (ret != 0)
1389 return ret;
1390
1391 mutex->value = 0xdead10cc;
1392 return 0;
1393}
1394
1395
1396
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001397int pthread_condattr_init(pthread_condattr_t *attr)
1398{
1399 if (attr == NULL)
1400 return EINVAL;
1401
1402 *attr = PTHREAD_PROCESS_PRIVATE;
1403 return 0;
1404}
1405
1406int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1407{
1408 if (attr == NULL || pshared == NULL)
1409 return EINVAL;
1410
1411 *pshared = *attr;
1412 return 0;
1413}
1414
1415int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1416{
1417 if (attr == NULL)
1418 return EINVAL;
1419
1420 if (pshared != PTHREAD_PROCESS_SHARED &&
1421 pshared != PTHREAD_PROCESS_PRIVATE)
1422 return EINVAL;
1423
1424 *attr = pshared;
1425 return 0;
1426}
1427
1428int pthread_condattr_destroy(pthread_condattr_t *attr)
1429{
1430 if (attr == NULL)
1431 return EINVAL;
1432
1433 *attr = 0xdeada11d;
1434 return 0;
1435}
1436
1437/* We use one bit in condition variable values as the 'shared' flag
1438 * The rest is a counter.
1439 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001440#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001441#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001442#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1443
1444#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001445
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001446/* XXX *technically* there is a race condition that could allow
1447 * XXX a signal to be missed. If thread A is preempted in _wait()
1448 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001449 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001450 * XXX before thread A is scheduled again and calls futex_wait(),
1451 * XXX then the signal will be lost.
1452 */
1453
1454int pthread_cond_init(pthread_cond_t *cond,
1455 const pthread_condattr_t *attr)
1456{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001457 if (cond == NULL)
1458 return EINVAL;
1459
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001460 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001461
1462 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001463 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001464
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001465 return 0;
1466}
1467
1468int pthread_cond_destroy(pthread_cond_t *cond)
1469{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001470 if (cond == NULL)
1471 return EINVAL;
1472
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001473 cond->value = 0xdeadc04d;
1474 return 0;
1475}
1476
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001477/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001478 * pthread_cond_signal to atomically decrement the counter
1479 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001480 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001481static int
1482__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001483{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001484 long flags;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001485
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001486 if (__unlikely(cond == NULL))
1487 return EINVAL;
1488
1489 flags = (cond->value & ~COND_COUNTER_MASK);
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001490 for (;;) {
1491 long oldval = cond->value;
1492 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1493 | flags;
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001494 if (__bionic_cmpxchg(oldval, newval, &cond->value) == 0)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001495 break;
1496 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001497
Andy McFaddene2ac8982010-09-02 13:34:53 -07001498 /*
1499 * Ensure that all memory accesses previously made by this thread are
1500 * visible to the woken thread(s). On the other side, the "wait"
1501 * code will issue any necessary barriers when locking the mutex.
1502 *
1503 * This may not strictly be necessary -- if the caller follows
1504 * recommended practice and holds the mutex before signaling the cond
1505 * var, the mutex ops will provide correct semantics. If they don't
1506 * hold the mutex, they're subject to race conditions anyway.
1507 */
1508 ANDROID_MEMBAR_FULL();
1509
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001510 __futex_wake_ex(&cond->value, COND_IS_SHARED(cond), counter);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001511 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001512}
1513
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001514int pthread_cond_broadcast(pthread_cond_t *cond)
1515{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001516 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001517}
1518
1519int pthread_cond_signal(pthread_cond_t *cond)
1520{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001521 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001522}
1523
1524int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1525{
1526 return pthread_cond_timedwait(cond, mutex, NULL);
1527}
1528
1529int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1530 pthread_mutex_t * mutex,
1531 const struct timespec *reltime)
1532{
1533 int status;
1534 int oldvalue = cond->value;
1535
1536 pthread_mutex_unlock(mutex);
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001537 status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond), oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001538 pthread_mutex_lock(mutex);
1539
1540 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1541 return 0;
1542}
1543
1544int __pthread_cond_timedwait(pthread_cond_t *cond,
1545 pthread_mutex_t * mutex,
1546 const struct timespec *abstime,
1547 clockid_t clock)
1548{
1549 struct timespec ts;
1550 struct timespec * tsp;
1551
1552 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001553 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001554 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001555 tsp = &ts;
1556 } else {
1557 tsp = NULL;
1558 }
1559
1560 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1561}
1562
1563int pthread_cond_timedwait(pthread_cond_t *cond,
1564 pthread_mutex_t * mutex,
1565 const struct timespec *abstime)
1566{
1567 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1568}
1569
1570
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001571/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001572int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1573 pthread_mutex_t * mutex,
1574 const struct timespec *abstime)
1575{
1576 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1577}
1578
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001579int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1580 pthread_mutex_t * mutex,
1581 const struct timespec *abstime)
1582{
1583 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1584}
1585
1586int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1587 pthread_mutex_t * mutex,
1588 const struct timespec *reltime)
1589{
1590 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1591}
1592
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001593int pthread_cond_timeout_np(pthread_cond_t *cond,
1594 pthread_mutex_t * mutex,
1595 unsigned msecs)
1596{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001597 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001598
1599 ts.tv_sec = msecs / 1000;
1600 ts.tv_nsec = (msecs % 1000) * 1000000;
1601
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001602 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001603}
1604
1605
1606
1607/* A technical note regarding our thread-local-storage (TLS) implementation:
1608 *
1609 * There can be up to TLSMAP_SIZE independent TLS keys in a given process,
1610 * though the first TLSMAP_START keys are reserved for Bionic to hold
1611 * special thread-specific variables like errno or a pointer to
1612 * the current thread's descriptor.
1613 *
1614 * while stored in the TLS area, these entries cannot be accessed through
1615 * pthread_getspecific() / pthread_setspecific() and pthread_key_delete()
1616 *
1617 * also, some entries in the key table are pre-allocated (see tlsmap_lock)
1618 * to greatly simplify and speedup some OpenGL-related operations. though the
1619 * initialy value will be NULL on all threads.
1620 *
1621 * you can use pthread_getspecific()/setspecific() on these, and in theory
1622 * you could also call pthread_key_delete() as well, though this would
1623 * probably break some apps.
1624 *
1625 * The 'tlsmap_t' type defined below implements a shared global map of
1626 * currently created/allocated TLS keys and the destructors associated
1627 * with them. You should use tlsmap_lock/unlock to access it to avoid
1628 * any race condition.
1629 *
1630 * the global TLS map simply contains a bitmap of allocated keys, and
1631 * an array of destructors.
1632 *
1633 * each thread has a TLS area that is a simple array of TLSMAP_SIZE void*
1634 * pointers. the TLS area of the main thread is stack-allocated in
1635 * __libc_init_common, while the TLS area of other threads is placed at
1636 * the top of their stack in pthread_create.
1637 *
1638 * when pthread_key_create() is called, it finds the first free key in the
1639 * bitmap, then set it to 1, saving the destructor altogether
1640 *
1641 * when pthread_key_delete() is called. it will erase the key's bitmap bit
1642 * and its destructor, and will also clear the key data in the TLS area of
1643 * all created threads. As mandated by Posix, it is the responsability of
1644 * the caller of pthread_key_delete() to properly reclaim the objects that
1645 * were pointed to by these data fields (either before or after the call).
1646 *
1647 */
1648
1649/* TLS Map implementation
1650 */
1651
1652#define TLSMAP_START (TLS_SLOT_MAX_WELL_KNOWN+1)
1653#define TLSMAP_SIZE BIONIC_TLS_SLOTS
1654#define TLSMAP_BITS 32
1655#define TLSMAP_WORDS ((TLSMAP_SIZE+TLSMAP_BITS-1)/TLSMAP_BITS)
1656#define TLSMAP_WORD(m,k) (m)->map[(k)/TLSMAP_BITS]
1657#define TLSMAP_MASK(k) (1U << ((k)&(TLSMAP_BITS-1)))
1658
1659/* this macro is used to quickly check that a key belongs to a reasonable range */
1660#define TLSMAP_VALIDATE_KEY(key) \
1661 ((key) >= TLSMAP_START && (key) < TLSMAP_SIZE)
1662
1663/* the type of tls key destructor functions */
1664typedef void (*tls_dtor_t)(void*);
1665
1666typedef struct {
1667 int init; /* see comment in tlsmap_lock() */
1668 uint32_t map[TLSMAP_WORDS]; /* bitmap of allocated keys */
1669 tls_dtor_t dtors[TLSMAP_SIZE]; /* key destructors */
1670} tlsmap_t;
1671
1672static pthread_mutex_t _tlsmap_lock = PTHREAD_MUTEX_INITIALIZER;
1673static tlsmap_t _tlsmap;
1674
1675/* lock the global TLS map lock and return a handle to it */
1676static __inline__ tlsmap_t* tlsmap_lock(void)
1677{
1678 tlsmap_t* m = &_tlsmap;
1679
1680 pthread_mutex_lock(&_tlsmap_lock);
1681 /* we need to initialize the first entry of the 'map' array
1682 * with the value TLS_DEFAULT_ALLOC_MAP. doing it statically
1683 * when declaring _tlsmap is a bit awkward and is going to
1684 * produce warnings, so do it the first time we use the map
1685 * instead
1686 */
1687 if (__unlikely(!m->init)) {
1688 TLSMAP_WORD(m,0) = TLS_DEFAULT_ALLOC_MAP;
1689 m->init = 1;
1690 }
1691 return m;
1692}
1693
1694/* unlock the global TLS map */
1695static __inline__ void tlsmap_unlock(tlsmap_t* m)
1696{
1697 pthread_mutex_unlock(&_tlsmap_lock);
1698 (void)m; /* a good compiler is a happy compiler */
1699}
1700
1701/* test to see wether a key is allocated */
1702static __inline__ int tlsmap_test(tlsmap_t* m, int key)
1703{
1704 return (TLSMAP_WORD(m,key) & TLSMAP_MASK(key)) != 0;
1705}
1706
1707/* set the destructor and bit flag on a newly allocated key */
1708static __inline__ void tlsmap_set(tlsmap_t* m, int key, tls_dtor_t dtor)
1709{
1710 TLSMAP_WORD(m,key) |= TLSMAP_MASK(key);
1711 m->dtors[key] = dtor;
1712}
1713
1714/* clear the destructor and bit flag on an existing key */
1715static __inline__ void tlsmap_clear(tlsmap_t* m, int key)
1716{
1717 TLSMAP_WORD(m,key) &= ~TLSMAP_MASK(key);
1718 m->dtors[key] = NULL;
1719}
1720
1721/* allocate a new TLS key, return -1 if no room left */
1722static int tlsmap_alloc(tlsmap_t* m, tls_dtor_t dtor)
1723{
1724 int key;
1725
1726 for ( key = TLSMAP_START; key < TLSMAP_SIZE; key++ ) {
1727 if ( !tlsmap_test(m, key) ) {
1728 tlsmap_set(m, key, dtor);
1729 return key;
1730 }
1731 }
1732 return -1;
1733}
1734
1735
1736int pthread_key_create(pthread_key_t *key, void (*destructor_function)(void *))
1737{
1738 uint32_t err = ENOMEM;
1739 tlsmap_t* map = tlsmap_lock();
1740 int k = tlsmap_alloc(map, destructor_function);
1741
1742 if (k >= 0) {
1743 *key = k;
1744 err = 0;
1745 }
1746 tlsmap_unlock(map);
1747 return err;
1748}
1749
1750
1751/* This deletes a pthread_key_t. note that the standard mandates that this does
1752 * not call the destructor of non-NULL key values. Instead, it is the
1753 * responsability of the caller to properly dispose of the corresponding data
1754 * and resources, using any mean it finds suitable.
1755 *
1756 * On the other hand, this function will clear the corresponding key data
1757 * values in all known threads. this prevents later (invalid) calls to
1758 * pthread_getspecific() to receive invalid/stale values.
1759 */
1760int pthread_key_delete(pthread_key_t key)
1761{
1762 uint32_t err;
1763 pthread_internal_t* thr;
1764 tlsmap_t* map;
1765
1766 if (!TLSMAP_VALIDATE_KEY(key)) {
1767 return EINVAL;
1768 }
1769
1770 map = tlsmap_lock();
1771
1772 if (!tlsmap_test(map, key)) {
1773 err = EINVAL;
1774 goto err1;
1775 }
1776
1777 /* clear value in all threads */
1778 pthread_mutex_lock(&gThreadListLock);
1779 for ( thr = gThreadList; thr != NULL; thr = thr->next ) {
1780 /* avoid zombie threads with a negative 'join_count'. these are really
1781 * already dead and don't have a TLS area anymore.
1782 *
1783 * similarly, it is possible to have thr->tls == NULL for threads that
1784 * were just recently created through pthread_create() but whose
1785 * startup trampoline (__thread_entry) hasn't been run yet by the
1786 * scheduler. so check for this too.
1787 */
1788 if (thr->join_count < 0 || !thr->tls)
1789 continue;
1790
1791 thr->tls[key] = NULL;
1792 }
1793 tlsmap_clear(map, key);
1794
1795 pthread_mutex_unlock(&gThreadListLock);
1796 err = 0;
1797
1798err1:
1799 tlsmap_unlock(map);
1800 return err;
1801}
1802
1803
1804int pthread_setspecific(pthread_key_t key, const void *ptr)
1805{
1806 int err = EINVAL;
1807 tlsmap_t* map;
1808
1809 if (TLSMAP_VALIDATE_KEY(key)) {
1810 /* check that we're trying to set data for an allocated key */
1811 map = tlsmap_lock();
1812 if (tlsmap_test(map, key)) {
1813 ((uint32_t *)__get_tls())[key] = (uint32_t)ptr;
1814 err = 0;
1815 }
1816 tlsmap_unlock(map);
1817 }
1818 return err;
1819}
1820
1821void * pthread_getspecific(pthread_key_t key)
1822{
1823 if (!TLSMAP_VALIDATE_KEY(key)) {
1824 return NULL;
1825 }
1826
1827 /* for performance reason, we do not lock/unlock the global TLS map
1828 * to check that the key is properly allocated. if the key was not
1829 * allocated, the value read from the TLS should always be NULL
1830 * due to pthread_key_delete() clearing the values for all threads.
1831 */
1832 return (void *)(((unsigned *)__get_tls())[key]);
1833}
1834
1835/* Posix mandates that this be defined in <limits.h> but we don't have
1836 * it just yet.
1837 */
1838#ifndef PTHREAD_DESTRUCTOR_ITERATIONS
1839# define PTHREAD_DESTRUCTOR_ITERATIONS 4
1840#endif
1841
1842/* this function is called from pthread_exit() to remove all TLS key data
1843 * from this thread's TLS area. this must call the destructor of all keys
1844 * that have a non-NULL data value (and a non-NULL destructor).
1845 *
1846 * because destructors can do funky things like deleting/creating other
1847 * keys, we need to implement this in a loop
1848 */
1849static void pthread_key_clean_all(void)
1850{
1851 tlsmap_t* map;
1852 void** tls = (void**)__get_tls();
1853 int rounds = PTHREAD_DESTRUCTOR_ITERATIONS;
1854
1855 map = tlsmap_lock();
1856
1857 for (rounds = PTHREAD_DESTRUCTOR_ITERATIONS; rounds > 0; rounds--)
1858 {
1859 int kk, count = 0;
1860
1861 for (kk = TLSMAP_START; kk < TLSMAP_SIZE; kk++) {
1862 if ( tlsmap_test(map, kk) )
1863 {
1864 void* data = tls[kk];
1865 tls_dtor_t dtor = map->dtors[kk];
1866
1867 if (data != NULL && dtor != NULL)
1868 {
1869 /* we need to clear the key data now, this will prevent the
1870 * destructor (or a later one) from seeing the old value if
1871 * it calls pthread_getspecific() for some odd reason
1872 *
1873 * we do not do this if 'dtor == NULL' just in case another
1874 * destructor function might be responsible for manually
1875 * releasing the corresponding data.
1876 */
1877 tls[kk] = NULL;
1878
1879 /* because the destructor is free to call pthread_key_create
1880 * and/or pthread_key_delete, we need to temporarily unlock
1881 * the TLS map
1882 */
1883 tlsmap_unlock(map);
1884 (*dtor)(data);
1885 map = tlsmap_lock();
1886
1887 count += 1;
1888 }
1889 }
1890 }
1891
1892 /* if we didn't call any destructor, there is no need to check the
1893 * TLS data again
1894 */
1895 if (count == 0)
1896 break;
1897 }
1898 tlsmap_unlock(map);
1899}
1900
1901// man says this should be in <linux/unistd.h>, but it isn't
Jeff Brown10c8ce52011-11-18 15:17:07 -08001902extern int tgkill(int tgid, int tid, int sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001903
1904int pthread_kill(pthread_t tid, int sig)
1905{
1906 int ret;
1907 int old_errno = errno;
1908 pthread_internal_t * thread = (pthread_internal_t *)tid;
1909
Jeff Brown10c8ce52011-11-18 15:17:07 -08001910 ret = tgkill(getpid(), thread->kernel_id, sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001911 if (ret < 0) {
1912 ret = errno;
1913 errno = old_errno;
1914 }
1915
1916 return ret;
1917}
1918
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001919/* Despite the fact that our kernel headers define sigset_t explicitly
1920 * as a 32-bit integer, the kernel system call really expects a 64-bit
1921 * bitmap for the signal set, or more exactly an array of two-32-bit
1922 * values (see $KERNEL/arch/$ARCH/include/asm/signal.h for details).
1923 *
1924 * Unfortunately, we cannot fix the sigset_t definition without breaking
1925 * the C library ABI, so perform a little runtime translation here.
1926 */
1927typedef union {
1928 sigset_t bionic;
1929 uint32_t kernel[2];
1930} kernel_sigset_t;
1931
1932/* this is a private syscall stub */
1933extern int __rt_sigprocmask(int, const kernel_sigset_t *, kernel_sigset_t *, size_t);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001934
1935int pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
1936{
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001937 /* pthread_sigmask must return the error code, but the syscall
1938 * will set errno instead and return 0/-1
1939 */
1940 int ret, old_errno = errno;
1941
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001942 /* We must convert *set into a kernel_sigset_t */
1943 kernel_sigset_t in_set, *in_set_ptr;
1944 kernel_sigset_t out_set;
1945
Bruce Bearee4a21c82011-12-05 11:25:37 -08001946 in_set.kernel[0] = in_set.kernel[1] = 0;
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001947 out_set.kernel[0] = out_set.kernel[1] = 0;
1948
1949 /* 'in_set_ptr' is the second parameter to __rt_sigprocmask. It must be NULL
1950 * if 'set' is NULL to ensure correct semantics (which in this case would
1951 * be to ignore 'how' and return the current signal set into 'oset'.
David 'Digit' Turner5c8c00a2010-12-20 15:58:06 +01001952 */
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001953 if (set == NULL) {
1954 in_set_ptr = NULL;
1955 } else {
1956 in_set.bionic = *set;
1957 in_set_ptr = &in_set;
1958 }
1959
1960 ret = __rt_sigprocmask(how, in_set_ptr, &out_set, sizeof(kernel_sigset_t));
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001961 if (ret < 0)
1962 ret = errno;
1963
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001964 if (oset)
1965 *oset = out_set.bionic;
1966
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001967 errno = old_errno;
1968 return ret;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001969}
1970
1971
1972int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
1973{
1974 const int CLOCK_IDTYPE_BITS = 3;
1975 pthread_internal_t* thread = (pthread_internal_t*)tid;
1976
1977 if (!thread)
1978 return ESRCH;
1979
1980 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
1981 return 0;
1982}
1983
1984
1985/* NOTE: this implementation doesn't support a init function that throws a C++ exception
1986 * or calls fork()
1987 */
1988int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
1989{
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001990 static pthread_mutex_t once_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001991 volatile pthread_once_t* ocptr = once_control;
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001992 pthread_once_t value;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001993
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001994 /* PTHREAD_ONCE_INIT is 0, we use the following bit flags
1995 *
1996 * bit 0 set -> initialization is under way
1997 * bit 1 set -> initialization is complete
1998 */
1999#define ONCE_INITIALIZING (1 << 0)
2000#define ONCE_COMPLETED (1 << 1)
2001
2002 /* First check if the once is already initialized. This will be the common
2003 * case and we want to make this as fast as possible. Note that this still
2004 * requires a load_acquire operation here to ensure that all the
2005 * stores performed by the initialization function are observable on
2006 * this CPU after we exit.
2007 */
2008 if (__likely((*ocptr & ONCE_COMPLETED) != 0)) {
2009 ANDROID_MEMBAR_FULL();
2010 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002011 }
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002012
2013 for (;;) {
2014 /* Try to atomically set the INITIALIZING flag.
2015 * This requires a cmpxchg loop, and we may need
2016 * to exit prematurely if we detect that
2017 * COMPLETED is now set.
2018 */
2019 int32_t oldval, newval;
2020
2021 do {
2022 oldval = *ocptr;
2023 if ((oldval & ONCE_COMPLETED) != 0)
2024 break;
2025
2026 newval = oldval | ONCE_INITIALIZING;
2027 } while (__bionic_cmpxchg(oldval, newval, ocptr) != 0);
2028
2029 if ((oldval & ONCE_COMPLETED) != 0) {
2030 /* We detected that COMPLETED was set while in our loop */
2031 ANDROID_MEMBAR_FULL();
2032 return 0;
2033 }
2034
2035 if ((oldval & ONCE_INITIALIZING) == 0) {
2036 /* We got there first, we can jump out of the loop to
2037 * handle the initialization */
2038 break;
2039 }
2040
2041 /* Another thread is running the initialization and hasn't completed
2042 * yet, so wait for it, then try again. */
2043 __futex_wait_ex(ocptr, 0, oldval, NULL);
2044 }
2045
2046 /* call the initialization function. */
2047 (*init_routine)();
2048
2049 /* Do a store_release indicating that initialization is complete */
2050 ANDROID_MEMBAR_FULL();
2051 *ocptr = ONCE_COMPLETED;
2052
2053 /* Wake up any waiters, if any */
2054 __futex_wake_ex(ocptr, 0, INT_MAX);
2055
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002056 return 0;
2057}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03002058
2059/* This value is not exported by kernel headers, so hardcode it here */
2060#define MAX_TASK_COMM_LEN 16
2061#define TASK_COMM_FMT "/proc/self/task/%u/comm"
2062
2063int pthread_setname_np(pthread_t thid, const char *thname)
2064{
2065 size_t thname_len;
2066 int saved_errno, ret;
2067
2068 if (thid == 0 || thname == NULL)
2069 return EINVAL;
2070
2071 thname_len = strlen(thname);
2072 if (thname_len >= MAX_TASK_COMM_LEN)
2073 return ERANGE;
2074
2075 saved_errno = errno;
2076 if (thid == pthread_self())
2077 {
2078 ret = prctl(PR_SET_NAME, (unsigned long)thname, 0, 0, 0) ? errno : 0;
2079 }
2080 else
2081 {
2082 /* Have to change another thread's name */
2083 pthread_internal_t *thread = (pthread_internal_t *)thid;
2084 char comm_name[sizeof(TASK_COMM_FMT) + 8];
2085 ssize_t n;
2086 int fd;
2087
2088 snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, (unsigned int)thread->kernel_id);
2089 fd = open(comm_name, O_RDWR);
2090 if (fd == -1)
2091 {
2092 ret = errno;
2093 goto exit;
2094 }
2095 n = TEMP_FAILURE_RETRY(write(fd, thname, thname_len));
2096 close(fd);
2097
2098 if (n < 0)
2099 ret = errno;
2100 else if ((size_t)n != thname_len)
2101 ret = EIO;
2102 else
2103 ret = 0;
2104 }
2105exit:
2106 errno = saved_errno;
2107 return ret;
2108}
Glenn Kastend53cae02011-07-11 15:41:28 -07002109
2110/* Return the kernel thread ID for a pthread.
2111 * This is only defined for implementations where pthread <-> kernel is 1:1, which this is.
2112 * Not the same as pthread_getthreadid_np, which is commonly defined to be opaque.
2113 * Internal, not an NDK API.
2114 */
2115
2116pid_t __pthread_gettid(pthread_t thid)
2117{
2118 pthread_internal_t* thread = (pthread_internal_t*)thid;
2119 return thread->kernel_id;
2120}