blob: 3a743751e1c89981586d881d0162fe2a04e7a2df [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
54extern int __pthread_clone(int (*fn)(void*), void *child_stack, int flags, void *arg);
55extern void _exit_with_stack_teardown(void * stackBase, int stackSize, int retCode);
56extern void _exit_thread(int retCode);
57extern int __set_errno(int);
58
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -070059int __futex_wake_ex(volatile void *ftx, int pshared, int val)
60{
61 return __futex_syscall3(ftx, pshared ? FUTEX_WAKE : FUTEX_WAKE_PRIVATE, val);
62}
63
64int __futex_wait_ex(volatile void *ftx, int pshared, int val, const struct timespec *timeout)
65{
66 return __futex_syscall4(ftx, pshared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE, val, timeout);
67}
68
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -070069#define __likely(cond) __builtin_expect(!!(cond), 1)
70#define __unlikely(cond) __builtin_expect(!!(cond), 0)
71
Bruce Beare8e551a62011-03-28 09:47:35 -070072#ifdef __i386__
73#define ATTRIBUTES __attribute__((noinline)) __attribute__((fastcall))
74#else
75#define ATTRIBUTES __attribute__((noinline))
76#endif
77
78void ATTRIBUTES _thread_created_hook(pid_t thread_id);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080079
80#define PTHREAD_ATTR_FLAG_DETACHED 0x00000001
81#define PTHREAD_ATTR_FLAG_USER_STACK 0x00000002
82
83#define DEFAULT_STACKSIZE (1024 * 1024)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080084
85static pthread_mutex_t mmap_lock = PTHREAD_MUTEX_INITIALIZER;
86
87
88static const pthread_attr_t gDefaultPthreadAttr = {
89 .flags = 0,
90 .stack_base = NULL,
91 .stack_size = DEFAULT_STACKSIZE,
92 .guard_size = PAGE_SIZE,
93 .sched_policy = SCHED_NORMAL,
94 .sched_priority = 0
95};
96
97#define INIT_THREADS 1
98
99static pthread_internal_t* gThreadList = NULL;
100static pthread_mutex_t gThreadListLock = PTHREAD_MUTEX_INITIALIZER;
101static pthread_mutex_t gDebuggerNotificationLock = PTHREAD_MUTEX_INITIALIZER;
102
103
104/* we simply malloc/free the internal pthread_internal_t structures. we may
105 * want to use a different allocation scheme in the future, but this one should
106 * be largely enough
107 */
108static pthread_internal_t*
109_pthread_internal_alloc(void)
110{
111 pthread_internal_t* thread;
112
113 thread = calloc( sizeof(*thread), 1 );
114 if (thread)
115 thread->intern = 1;
116
117 return thread;
118}
119
120static void
121_pthread_internal_free( pthread_internal_t* thread )
122{
123 if (thread && thread->intern) {
124 thread->intern = 0; /* just in case */
125 free (thread);
126 }
127}
128
129
130static void
131_pthread_internal_remove_locked( pthread_internal_t* thread )
132{
133 thread->next->pref = thread->pref;
134 thread->pref[0] = thread->next;
135}
136
137static void
138_pthread_internal_remove( pthread_internal_t* thread )
139{
140 pthread_mutex_lock(&gThreadListLock);
141 _pthread_internal_remove_locked(thread);
142 pthread_mutex_unlock(&gThreadListLock);
143}
144
145static void
146_pthread_internal_add( pthread_internal_t* thread )
147{
148 pthread_mutex_lock(&gThreadListLock);
149 thread->pref = &gThreadList;
150 thread->next = thread->pref[0];
151 if (thread->next)
152 thread->next->pref = &thread->next;
153 thread->pref[0] = thread;
154 pthread_mutex_unlock(&gThreadListLock);
155}
156
157pthread_internal_t*
158__get_thread(void)
159{
160 void** tls = (void**)__get_tls();
161
162 return (pthread_internal_t*) tls[TLS_SLOT_THREAD_ID];
163}
164
165
166void*
167__get_stack_base(int *p_stack_size)
168{
169 pthread_internal_t* thread = __get_thread();
170
171 *p_stack_size = thread->attr.stack_size;
172 return thread->attr.stack_base;
173}
174
175
176void __init_tls(void** tls, void* thread)
177{
178 int nn;
179
180 ((pthread_internal_t*)thread)->tls = tls;
181
182 // slot 0 must point to the tls area, this is required by the implementation
183 // of the x86 Linux kernel thread-local-storage
184 tls[TLS_SLOT_SELF] = (void*)tls;
185 tls[TLS_SLOT_THREAD_ID] = thread;
186 for (nn = TLS_SLOT_ERRNO; nn < BIONIC_TLS_SLOTS; nn++)
187 tls[nn] = 0;
188
189 __set_tls( (void*)tls );
190}
191
192
193/*
194 * This trampoline is called from the assembly clone() function
195 */
196void __thread_entry(int (*func)(void*), void *arg, void **tls)
197{
198 int retValue;
199 pthread_internal_t * thrInfo;
200
201 // Wait for our creating thread to release us. This lets it have time to
202 // notify gdb about this thread before it starts doing anything.
Andy McFaddene2ac8982010-09-02 13:34:53 -0700203 //
204 // This also provides the memory barrier needed to ensure that all memory
205 // accesses previously made by the creating thread are visible to us.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800206 pthread_mutex_t * start_mutex = (pthread_mutex_t *)&tls[TLS_SLOT_SELF];
207 pthread_mutex_lock(start_mutex);
208 pthread_mutex_destroy(start_mutex);
209
210 thrInfo = (pthread_internal_t *) tls[TLS_SLOT_THREAD_ID];
211
212 __init_tls( tls, thrInfo );
213
214 pthread_exit( (void*)func(arg) );
215}
216
217void _init_thread(pthread_internal_t * thread, pid_t kernel_id, pthread_attr_t * attr, void * stack_base)
218{
219 if (attr == NULL) {
220 thread->attr = gDefaultPthreadAttr;
221 } else {
222 thread->attr = *attr;
223 }
224 thread->attr.stack_base = stack_base;
225 thread->kernel_id = kernel_id;
226
227 // set the scheduling policy/priority of the thread
228 if (thread->attr.sched_policy != SCHED_NORMAL) {
229 struct sched_param param;
230 param.sched_priority = thread->attr.sched_priority;
231 sched_setscheduler(kernel_id, thread->attr.sched_policy, &param);
232 }
233
234 pthread_cond_init(&thread->join_cond, NULL);
235 thread->join_count = 0;
236
237 thread->cleanup_stack = NULL;
238
239 _pthread_internal_add(thread);
240}
241
242
243/* XXX stacks not reclaimed if thread spawn fails */
244/* XXX stacks address spaces should be reused if available again */
245
246static void *mkstack(size_t size, size_t guard_size)
247{
248 void * stack;
249
250 pthread_mutex_lock(&mmap_lock);
251
Nick Kralevich5f64df42011-11-17 12:58:20 -0800252 stack = mmap(NULL, size,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800253 PROT_READ | PROT_WRITE,
254 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
255 -1, 0);
256
257 if(stack == MAP_FAILED) {
258 stack = NULL;
259 goto done;
260 }
261
262 if(mprotect(stack, guard_size, PROT_NONE)){
263 munmap(stack, size);
264 stack = NULL;
265 goto done;
266 }
267
268done:
269 pthread_mutex_unlock(&mmap_lock);
270 return stack;
271}
272
273/*
Andy McFaddene2ac8982010-09-02 13:34:53 -0700274 * Create a new thread. The thread's stack is laid out like so:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800275 *
276 * +---------------------------+
277 * | pthread_internal_t |
278 * +---------------------------+
279 * | |
280 * | TLS area |
281 * | |
282 * +---------------------------+
283 * | |
284 * . .
285 * . stack area .
286 * . .
287 * | |
288 * +---------------------------+
289 * | guard page |
290 * +---------------------------+
291 *
292 * note that TLS[0] must be a pointer to itself, this is required
293 * by the thread-local storage implementation of the x86 Linux
294 * kernel, where the TLS pointer is read by reading fs:[0]
295 */
296int pthread_create(pthread_t *thread_out, pthread_attr_t const * attr,
297 void *(*start_routine)(void *), void * arg)
298{
299 char* stack;
300 void** tls;
301 int tid;
302 pthread_mutex_t * start_mutex;
303 pthread_internal_t * thread;
304 int madestack = 0;
305 int old_errno = errno;
306
307 /* this will inform the rest of the C library that at least one thread
308 * was created. this will enforce certain functions to acquire/release
309 * locks (e.g. atexit()) to protect shared global structures.
310 *
311 * this works because pthread_create() is not called by the C library
312 * initialization routine that sets up the main thread's data structures.
313 */
314 __isthreaded = 1;
315
316 thread = _pthread_internal_alloc();
317 if (thread == NULL)
318 return ENOMEM;
319
320 if (attr == NULL) {
321 attr = &gDefaultPthreadAttr;
322 }
323
324 // make sure the stack is PAGE_SIZE aligned
325 size_t stackSize = (attr->stack_size +
326 (PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
327
328 if (!attr->stack_base) {
329 stack = mkstack(stackSize, attr->guard_size);
330 if(stack == NULL) {
331 _pthread_internal_free(thread);
332 return ENOMEM;
333 }
334 madestack = 1;
335 } else {
336 stack = attr->stack_base;
337 }
338
339 // Make room for TLS
340 tls = (void**)(stack + stackSize - BIONIC_TLS_SLOTS*sizeof(void*));
341
342 // Create a mutex for the thread in TLS_SLOT_SELF to wait on once it starts so we can keep
343 // it from doing anything until after we notify the debugger about it
Andy McFaddene2ac8982010-09-02 13:34:53 -0700344 //
345 // This also provides the memory barrier we need to ensure that all
346 // memory accesses previously performed by this thread are visible to
347 // the new thread.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800348 start_mutex = (pthread_mutex_t *) &tls[TLS_SLOT_SELF];
349 pthread_mutex_init(start_mutex, NULL);
350 pthread_mutex_lock(start_mutex);
351
352 tls[TLS_SLOT_THREAD_ID] = thread;
353
354 tid = __pthread_clone((int(*)(void*))start_routine, tls,
355 CLONE_FILES | CLONE_FS | CLONE_VM | CLONE_SIGHAND
356 | CLONE_THREAD | CLONE_SYSVSEM | CLONE_DETACHED,
357 arg);
358
359 if(tid < 0) {
360 int result;
361 if (madestack)
362 munmap(stack, stackSize);
363 _pthread_internal_free(thread);
364 result = errno;
365 errno = old_errno;
366 return result;
367 }
368
369 _init_thread(thread, tid, (pthread_attr_t*)attr, stack);
370
371 if (!madestack)
372 thread->attr.flags |= PTHREAD_ATTR_FLAG_USER_STACK;
373
374 // Notify any debuggers about the new thread
375 pthread_mutex_lock(&gDebuggerNotificationLock);
376 _thread_created_hook(tid);
377 pthread_mutex_unlock(&gDebuggerNotificationLock);
378
379 // Let the thread do it's thing
380 pthread_mutex_unlock(start_mutex);
381
382 *thread_out = (pthread_t)thread;
383 return 0;
384}
385
386
387int pthread_attr_init(pthread_attr_t * attr)
388{
389 *attr = gDefaultPthreadAttr;
390 return 0;
391}
392
393int pthread_attr_destroy(pthread_attr_t * attr)
394{
395 memset(attr, 0x42, sizeof(pthread_attr_t));
396 return 0;
397}
398
399int pthread_attr_setdetachstate(pthread_attr_t * attr, int state)
400{
401 if (state == PTHREAD_CREATE_DETACHED) {
402 attr->flags |= PTHREAD_ATTR_FLAG_DETACHED;
403 } else if (state == PTHREAD_CREATE_JOINABLE) {
404 attr->flags &= ~PTHREAD_ATTR_FLAG_DETACHED;
405 } else {
406 return EINVAL;
407 }
408 return 0;
409}
410
411int pthread_attr_getdetachstate(pthread_attr_t const * attr, int * state)
412{
413 *state = (attr->flags & PTHREAD_ATTR_FLAG_DETACHED)
414 ? PTHREAD_CREATE_DETACHED
415 : PTHREAD_CREATE_JOINABLE;
416 return 0;
417}
418
419int pthread_attr_setschedpolicy(pthread_attr_t * attr, int policy)
420{
421 attr->sched_policy = policy;
422 return 0;
423}
424
425int pthread_attr_getschedpolicy(pthread_attr_t const * attr, int * policy)
426{
427 *policy = attr->sched_policy;
428 return 0;
429}
430
431int pthread_attr_setschedparam(pthread_attr_t * attr, struct sched_param const * param)
432{
433 attr->sched_priority = param->sched_priority;
434 return 0;
435}
436
437int pthread_attr_getschedparam(pthread_attr_t const * attr, struct sched_param * param)
438{
439 param->sched_priority = attr->sched_priority;
440 return 0;
441}
442
443int pthread_attr_setstacksize(pthread_attr_t * attr, size_t stack_size)
444{
445 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
446 return EINVAL;
447 }
448 attr->stack_size = stack_size;
449 return 0;
450}
451
452int pthread_attr_getstacksize(pthread_attr_t const * attr, size_t * stack_size)
453{
454 *stack_size = attr->stack_size;
455 return 0;
456}
457
458int pthread_attr_setstackaddr(pthread_attr_t * attr, void * stack_addr)
459{
460#if 1
461 // It's not clear if this is setting the top or bottom of the stack, so don't handle it for now.
462 return ENOSYS;
463#else
464 if ((uint32_t)stack_addr & (PAGE_SIZE - 1)) {
465 return EINVAL;
466 }
467 attr->stack_base = stack_addr;
468 return 0;
469#endif
470}
471
472int pthread_attr_getstackaddr(pthread_attr_t const * attr, void ** stack_addr)
473{
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700474 *stack_addr = (char*)attr->stack_base + attr->stack_size;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800475 return 0;
476}
477
478int pthread_attr_setstack(pthread_attr_t * attr, void * stack_base, size_t stack_size)
479{
480 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
481 return EINVAL;
482 }
483 if ((uint32_t)stack_base & (PAGE_SIZE - 1)) {
484 return EINVAL;
485 }
486 attr->stack_base = stack_base;
487 attr->stack_size = stack_size;
488 return 0;
489}
490
491int pthread_attr_getstack(pthread_attr_t const * attr, void ** stack_base, size_t * stack_size)
492{
493 *stack_base = attr->stack_base;
494 *stack_size = attr->stack_size;
495 return 0;
496}
497
498int pthread_attr_setguardsize(pthread_attr_t * attr, size_t guard_size)
499{
500 if (guard_size & (PAGE_SIZE - 1) || guard_size < PAGE_SIZE) {
501 return EINVAL;
502 }
503
504 attr->guard_size = guard_size;
505 return 0;
506}
507
508int pthread_attr_getguardsize(pthread_attr_t const * attr, size_t * guard_size)
509{
510 *guard_size = attr->guard_size;
511 return 0;
512}
513
514int pthread_getattr_np(pthread_t thid, pthread_attr_t * attr)
515{
516 pthread_internal_t * thread = (pthread_internal_t *)thid;
517 *attr = thread->attr;
518 return 0;
519}
520
521int pthread_attr_setscope(pthread_attr_t *attr, int scope)
522{
523 if (scope == PTHREAD_SCOPE_SYSTEM)
524 return 0;
525 if (scope == PTHREAD_SCOPE_PROCESS)
526 return ENOTSUP;
527
528 return EINVAL;
529}
530
531int pthread_attr_getscope(pthread_attr_t const *attr)
532{
533 return PTHREAD_SCOPE_SYSTEM;
534}
535
536
537/* CAVEAT: our implementation of pthread_cleanup_push/pop doesn't support C++ exceptions
538 * and thread cancelation
539 */
540
541void __pthread_cleanup_push( __pthread_cleanup_t* c,
542 __pthread_cleanup_func_t routine,
543 void* arg )
544{
545 pthread_internal_t* thread = __get_thread();
546
547 c->__cleanup_routine = routine;
548 c->__cleanup_arg = arg;
549 c->__cleanup_prev = thread->cleanup_stack;
550 thread->cleanup_stack = c;
551}
552
553void __pthread_cleanup_pop( __pthread_cleanup_t* c, int execute )
554{
555 pthread_internal_t* thread = __get_thread();
556
557 thread->cleanup_stack = c->__cleanup_prev;
558 if (execute)
559 c->__cleanup_routine(c->__cleanup_arg);
560}
561
562/* used by pthread_exit() to clean all TLS keys of the current thread */
563static void pthread_key_clean_all(void);
564
565void pthread_exit(void * retval)
566{
567 pthread_internal_t* thread = __get_thread();
568 void* stack_base = thread->attr.stack_base;
569 int stack_size = thread->attr.stack_size;
570 int user_stack = (thread->attr.flags & PTHREAD_ATTR_FLAG_USER_STACK) != 0;
Jack Rene480fc82011-09-21 12:44:11 +0200571 sigset_t mask;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800572
573 // call the cleanup handlers first
574 while (thread->cleanup_stack) {
575 __pthread_cleanup_t* c = thread->cleanup_stack;
576 thread->cleanup_stack = c->__cleanup_prev;
577 c->__cleanup_routine(c->__cleanup_arg);
578 }
579
580 // call the TLS destructors, it is important to do that before removing this
581 // thread from the global list. this will ensure that if someone else deletes
582 // a TLS key, the corresponding value will be set to NULL in this thread's TLS
583 // space (see pthread_key_delete)
584 pthread_key_clean_all();
585
586 // if the thread is detached, destroy the pthread_internal_t
587 // otherwise, keep it in memory and signal any joiners
588 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
589 _pthread_internal_remove(thread);
590 _pthread_internal_free(thread);
591 } else {
592 /* the join_count field is used to store the number of threads waiting for
593 * the termination of this thread with pthread_join(),
594 *
595 * if it is positive we need to signal the waiters, and we do not touch
596 * the count (it will be decremented by the waiters, the last one will
597 * also remove/free the thread structure
598 *
599 * if it is zero, we set the count value to -1 to indicate that the
600 * thread is in 'zombie' state: it has stopped executing, and its stack
601 * is gone (as well as its TLS area). when another thread calls pthread_join()
602 * on it, it will immediately free the thread and return.
603 */
604 pthread_mutex_lock(&gThreadListLock);
605 thread->return_value = retval;
606 if (thread->join_count > 0) {
607 pthread_cond_broadcast(&thread->join_cond);
608 } else {
609 thread->join_count = -1; /* zombie thread */
610 }
611 pthread_mutex_unlock(&gThreadListLock);
612 }
613
Jack Rene480fc82011-09-21 12:44:11 +0200614 sigfillset(&mask);
615 sigdelset(&mask, SIGSEGV);
616 (void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *)NULL);
617
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800618 // destroy the thread stack
619 if (user_stack)
620 _exit_thread((int)retval);
621 else
622 _exit_with_stack_teardown(stack_base, stack_size, (int)retval);
623}
624
625int pthread_join(pthread_t thid, void ** ret_val)
626{
627 pthread_internal_t* thread = (pthread_internal_t*)thid;
628 int count;
629
630 // check that the thread still exists and is not detached
631 pthread_mutex_lock(&gThreadListLock);
632
633 for (thread = gThreadList; thread != NULL; thread = thread->next)
634 if (thread == (pthread_internal_t*)thid)
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200635 goto FoundIt;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800636
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200637 pthread_mutex_unlock(&gThreadListLock);
638 return ESRCH;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800639
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200640FoundIt:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800641 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
642 pthread_mutex_unlock(&gThreadListLock);
643 return EINVAL;
644 }
645
646 /* wait for thread death when needed
647 *
648 * if the 'join_count' is negative, this is a 'zombie' thread that
649 * is already dead and without stack/TLS
650 *
651 * otherwise, we need to increment 'join-count' and wait to be signaled
652 */
653 count = thread->join_count;
654 if (count >= 0) {
655 thread->join_count += 1;
656 pthread_cond_wait( &thread->join_cond, &gThreadListLock );
657 count = --thread->join_count;
658 }
659 if (ret_val)
660 *ret_val = thread->return_value;
661
662 /* remove thread descriptor when we're the last joiner or when the
663 * thread was already a zombie.
664 */
665 if (count <= 0) {
666 _pthread_internal_remove_locked(thread);
667 _pthread_internal_free(thread);
668 }
669 pthread_mutex_unlock(&gThreadListLock);
670 return 0;
671}
672
673int pthread_detach( pthread_t thid )
674{
675 pthread_internal_t* thread;
676 int result = 0;
677 int flags;
678
679 pthread_mutex_lock(&gThreadListLock);
680 for (thread = gThreadList; thread != NULL; thread = thread->next)
681 if (thread == (pthread_internal_t*)thid)
682 goto FoundIt;
683
684 result = ESRCH;
685 goto Exit;
686
687FoundIt:
688 do {
689 flags = thread->attr.flags;
690
691 if ( flags & PTHREAD_ATTR_FLAG_DETACHED ) {
692 /* thread is not joinable ! */
693 result = EINVAL;
694 goto Exit;
695 }
696 }
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100697 while ( __bionic_cmpxchg( flags, flags | PTHREAD_ATTR_FLAG_DETACHED,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800698 (volatile int*)&thread->attr.flags ) != 0 );
699Exit:
700 pthread_mutex_unlock(&gThreadListLock);
701 return result;
702}
703
704pthread_t pthread_self(void)
705{
706 return (pthread_t)__get_thread();
707}
708
709int pthread_equal(pthread_t one, pthread_t two)
710{
711 return (one == two ? 1 : 0);
712}
713
714int pthread_getschedparam(pthread_t thid, int * policy,
715 struct sched_param * param)
716{
717 int old_errno = errno;
718
719 pthread_internal_t * thread = (pthread_internal_t *)thid;
720 int err = sched_getparam(thread->kernel_id, param);
721 if (!err) {
722 *policy = sched_getscheduler(thread->kernel_id);
723 } else {
724 err = errno;
725 errno = old_errno;
726 }
727 return err;
728}
729
730int pthread_setschedparam(pthread_t thid, int policy,
731 struct sched_param const * param)
732{
733 pthread_internal_t * thread = (pthread_internal_t *)thid;
734 int old_errno = errno;
735 int ret;
736
737 ret = sched_setscheduler(thread->kernel_id, policy, param);
738 if (ret < 0) {
739 ret = errno;
740 errno = old_errno;
741 }
742 return ret;
743}
744
745
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800746// mutex lock states
747//
748// 0: unlocked
749// 1: locked, no waiters
750// 2: locked, maybe waiters
751
752/* a mutex is implemented as a 32-bit integer holding the following fields
753 *
754 * bits: name description
755 * 31-16 tid owner thread's kernel id (recursive and errorcheck only)
756 * 15-14 type mutex type
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700757 * 13 shared process-shared flag
758 * 12-2 counter counter of recursive mutexes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800759 * 1-0 state lock state (0, 1 or 2)
760 */
761
762
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100763#define MUTEX_VALUE_OWNER(v) (((v) >> 16) & 0xffff)
764#define MUTEX_VALUE_COUNTER(v) (((v) >> 2) & 0xfff)
765
766#define MUTEX_OWNER(m) MUTEX_VALUE_OWNER((m)->value)
767#define MUTEX_COUNTER(m) MUTEX_VALUE_COUNTER((m)->value)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800768
769#define MUTEX_TYPE_MASK 0xc000
770#define MUTEX_TYPE_NORMAL 0x0000
771#define MUTEX_TYPE_RECURSIVE 0x4000
772#define MUTEX_TYPE_ERRORCHECK 0x8000
773
774#define MUTEX_COUNTER_SHIFT 2
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700775#define MUTEX_COUNTER_MASK 0x1ffc
776#define MUTEX_SHARED_MASK 0x2000
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800777
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700778/* a mutex attribute holds the following fields
779 *
780 * bits: name description
781 * 0-3 type type of mutex
782 * 4 shared process-shared flag
783 */
784#define MUTEXATTR_TYPE_MASK 0x000f
785#define MUTEXATTR_SHARED_MASK 0x0010
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800786
787
788int pthread_mutexattr_init(pthread_mutexattr_t *attr)
789{
790 if (attr) {
791 *attr = PTHREAD_MUTEX_DEFAULT;
792 return 0;
793 } else {
794 return EINVAL;
795 }
796}
797
798int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
799{
800 if (attr) {
801 *attr = -1;
802 return 0;
803 } else {
804 return EINVAL;
805 }
806}
807
808int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
809{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700810 if (attr) {
811 int atype = (*attr & MUTEXATTR_TYPE_MASK);
812
813 if (atype >= PTHREAD_MUTEX_NORMAL &&
814 atype <= PTHREAD_MUTEX_ERRORCHECK) {
815 *type = atype;
816 return 0;
817 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800818 }
819 return EINVAL;
820}
821
822int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
823{
824 if (attr && type >= PTHREAD_MUTEX_NORMAL &&
825 type <= PTHREAD_MUTEX_ERRORCHECK ) {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700826 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800827 return 0;
828 }
829 return EINVAL;
830}
831
832/* process-shared mutexes are not supported at the moment */
833
834int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
835{
836 if (!attr)
837 return EINVAL;
838
Mathias Agopianb7681162009-07-13 22:00:33 -0700839 switch (pshared) {
840 case PTHREAD_PROCESS_PRIVATE:
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700841 *attr &= ~MUTEXATTR_SHARED_MASK;
842 return 0;
843
Mathias Agopianb7681162009-07-13 22:00:33 -0700844 case PTHREAD_PROCESS_SHARED:
845 /* our current implementation of pthread actually supports shared
846 * mutexes but won't cleanup if a process dies with the mutex held.
847 * Nevertheless, it's better than nothing. Shared mutexes are used
848 * by surfaceflinger and audioflinger.
849 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700850 *attr |= MUTEXATTR_SHARED_MASK;
Mathias Agopianb7681162009-07-13 22:00:33 -0700851 return 0;
852 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700853 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800854}
855
856int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
857{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700858 if (!attr || !pshared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800859 return EINVAL;
860
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700861 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED
862 : PTHREAD_PROCESS_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800863 return 0;
864}
865
866int pthread_mutex_init(pthread_mutex_t *mutex,
867 const pthread_mutexattr_t *attr)
868{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700869 int value = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800870
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700871 if (mutex == NULL)
872 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800873
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700874 if (__likely(attr == NULL)) {
875 mutex->value = MUTEX_TYPE_NORMAL;
876 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800877 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700878
879 if ((*attr & MUTEXATTR_SHARED_MASK) != 0)
880 value |= MUTEX_SHARED_MASK;
881
882 switch (*attr & MUTEXATTR_TYPE_MASK) {
883 case PTHREAD_MUTEX_NORMAL:
884 value |= MUTEX_TYPE_NORMAL;
885 break;
886 case PTHREAD_MUTEX_RECURSIVE:
887 value |= MUTEX_TYPE_RECURSIVE;
888 break;
889 case PTHREAD_MUTEX_ERRORCHECK:
890 value |= MUTEX_TYPE_ERRORCHECK;
891 break;
892 default:
893 return EINVAL;
894 }
895
896 mutex->value = value;
897 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800898}
899
900int pthread_mutex_destroy(pthread_mutex_t *mutex)
901{
David 'Digit' Turnera02b93b2010-06-28 14:20:22 -0700902 int ret;
903
904 /* use trylock to ensure that the mutex value is
905 * valid and is not already locked. */
906 ret = pthread_mutex_trylock(mutex);
907 if (ret != 0)
908 return ret;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700909
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800910 mutex->value = 0xdead10cc;
911 return 0;
912}
913
914
915/*
916 * Lock a non-recursive mutex.
917 *
918 * As noted above, there are three states:
919 * 0 (unlocked, no contention)
920 * 1 (locked, no contention)
921 * 2 (locked, contention)
922 *
923 * Non-recursive mutexes don't use the thread-id or counter fields, and the
924 * "type" value is zero, so the only bits that will be set are the ones in
925 * the lock state field.
926 */
927static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100928_normal_lock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800929{
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800930 /*
931 * The common case is an unlocked mutex, so we begin by trying to
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100932 * change the lock's state from 0 to 1. __bionic_cmpxchg() returns 0
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800933 * if it made the swap successfully. If the result is nonzero, this
934 * lock is already held by another thread.
935 */
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100936 if (__bionic_cmpxchg(shared|0, shared|1, &mutex->value ) != 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800937 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800938 * We want to go to sleep until the mutex is available, which
939 * requires promoting it to state 2. We need to swap in the new
940 * state value and then wait until somebody wakes us up.
941 *
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100942 * __bionic_swap() returns the previous value. We swap 2 in and
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800943 * see if we got zero back; if so, we have acquired the lock. If
944 * not, another thread still holds the lock and we wait again.
945 *
946 * The second argument to the __futex_wait() call is compared
947 * against the current value. If it doesn't match, __futex_wait()
948 * returns immediately (otherwise, it sleeps for a time specified
949 * by the third argument; 0 means sleep forever). This ensures
950 * that the mutex is in state 2 when we go to sleep on it, which
951 * guarantees a wake-up call.
952 */
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100953 while (__bionic_swap(shared|2, &mutex->value ) != (shared|0))
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -0700954 __futex_wait_ex(&mutex->value, shared, shared|2, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800955 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700956 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800957}
958
959/*
960 * Release a non-recursive mutex. The caller is responsible for determining
961 * that we are in fact the owner of this lock.
962 */
963static __inline__ void
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100964_normal_unlock(pthread_mutex_t* mutex, int shared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800965{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700966 ANDROID_MEMBAR_FULL();
967
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800968 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700969 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100970 * to release the lock. __bionic_atomic_dec() returns the previous value;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800971 * if it wasn't 1 we have to do some additional work.
972 */
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100973 if (__bionic_atomic_dec(&mutex->value) != (shared|1)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800974 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800975 * Start by releasing the lock. The decrement changed it from
976 * "contended lock" to "uncontended lock", which means we still
977 * hold it, and anybody who tries to sneak in will push it back
978 * to state 2.
979 *
980 * Once we set it to zero the lock is up for grabs. We follow
981 * this with a __futex_wake() to ensure that one of the waiting
982 * threads has a chance to grab it.
983 *
984 * This doesn't cause a race with the swap/wait pair in
985 * _normal_lock(), because the __futex_wait() call there will
986 * return immediately if the mutex value isn't 2.
987 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700988 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800989
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800990 /*
991 * Wake up one waiting thread. We don't know which thread will be
992 * woken or when it'll start executing -- futexes make no guarantees
993 * here. There may not even be a thread waiting.
994 *
995 * The newly-woken thread will replace the 0 we just set above
996 * with 2, which means that when it eventually releases the mutex
997 * it will also call FUTEX_WAKE. This results in one extra wake
998 * call whenever a lock is contended, but lets us avoid forgetting
999 * anyone without requiring us to track the number of sleepers.
1000 *
1001 * It's possible for another thread to sneak in and grab the lock
1002 * between the zero assignment above and the wake call below. If
1003 * the new thread is "slow" and holds the lock for a while, we'll
1004 * wake up a sleeper, which will swap in a 2 and then go back to
1005 * sleep since the lock is still held. If the new thread is "fast",
1006 * running to completion before we call wake, the thread we
1007 * eventually wake will find an unlocked mutex and will execute.
1008 * Either way we have correct behavior and nobody is orphaned on
1009 * the wait queue.
1010 */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001011 __futex_wake_ex(&mutex->value, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001012 }
1013}
1014
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001015/* This common inlined function is used to increment the counter of an
1016 * errorcheck or recursive mutex.
1017 *
1018 * For errorcheck mutexes, it will return EDEADLK
1019 * If the counter overflows, it will return EAGAIN
1020 * Otherwise, it atomically increments the counter and returns 0
1021 * after providing an acquire barrier.
1022 *
1023 * mtype is the current mutex type
1024 * mvalue is the current mutex value (already loaded)
1025 * mutex pointers to the mutex.
1026 */
1027static __inline__ __attribute__((always_inline)) int
1028_recursive_increment(pthread_mutex_t* mutex, int mvalue, int mtype)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001029{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001030 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1031 /* trying to re-lock a mutex we already acquired */
1032 return EDEADLK;
1033 }
1034
1035 /* Detect recursive lock overflow and return EAGAIN.
1036 * This is safe because only the owner thread can modify the
1037 * counter bits in the mutes value
1038 */
1039 if ((mvalue & MUTEX_COUNTER_MASK) == MUTEX_COUNTER_MASK) {
1040 return EAGAIN;
1041 }
1042
1043 /* We own the mutex, but other threads are able to change
1044 * the contents (e.g. promoting it to "contended" by changing
1045 * its lower bits), so we need to atomically update it using
1046 * a cmpxchg loop.
1047 */
1048 for (;;) {
1049 /* increment counter, overflow was already checked */
1050 int newvalue = mvalue + (1 << MUTEX_COUNTER_SHIFT);
1051 if (__likely(__bionic_cmpxchg(mvalue, newvalue, &mutex->value) == 0)) {
1052 ANDROID_MEMBAR_FULL();
1053 return 0;
1054 }
1055 /* argh, value was changed, by another thread which updated the 'state'
1056 * field, so reload and try again.
1057 */
1058 mvalue = mutex->value;
1059 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001060}
1061
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001062static pthread_mutex_t __recursive_lock = PTHREAD_MUTEX_INITIALIZER;
1063
1064static __inline__ void
1065_recursive_lock(void)
1066{
1067 _normal_lock(&__recursive_lock, 0);
1068}
1069
1070static __inline__ void
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001071_recursive_unlock(void)
1072{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001073 _normal_unlock(&__recursive_lock, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001074}
1075
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001076int pthread_mutex_lock(pthread_mutex_t *mutex)
1077{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001078 int mvalue, mtype, tid, new_lock_type, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001079
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001080 if (__unlikely(mutex == NULL))
1081 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001082
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001083 mvalue = mutex->value;
1084 mtype = (mvalue & MUTEX_TYPE_MASK);
1085 shared = (mvalue & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001086
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001087 /* Handle normal case first */
1088 if ( __likely(mtype == MUTEX_TYPE_NORMAL) ) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001089 _normal_lock(mutex, shared);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001090 return 0;
1091 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001092
1093 /* Do we already own this recursive or error-check mutex ? */
1094 tid = __get_thread()->kernel_id;
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001095 if ( tid == MUTEX_VALUE_OWNER(mvalue) )
1096 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001097
1098 /* We don't own the mutex, so try to get it.
1099 *
1100 * First, we try to change its state from 0 to 1, if this
1101 * doesn't work, try to change it to state 2.
1102 */
1103 new_lock_type = 1;
1104
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001105 /* compute futex wait opcode and restore shared flag in mtype */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001106 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001107
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001108 for (;;) {
1109 int oldv;
1110
1111 _recursive_lock();
1112 oldv = mutex->value;
1113 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1114 mutex->value = ((tid << 16) | mtype | new_lock_type);
1115 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1116 oldv ^= 3;
1117 mutex->value = oldv;
1118 }
1119 _recursive_unlock();
1120
1121 if (oldv == mtype)
1122 break;
1123
1124 /*
1125 * The lock was held, possibly contended by others. From
1126 * now on, if we manage to acquire the lock, we have to
1127 * assume that others are still contending for it so that
1128 * we'll wake them when we unlock it.
1129 */
1130 new_lock_type = 2;
1131
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001132 __futex_wait_ex(&mutex->value, shared, oldv, NULL);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001133 }
1134 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001135}
1136
1137
1138int pthread_mutex_unlock(pthread_mutex_t *mutex)
1139{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001140 int mvalue, mtype, tid, oldv, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001141
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001142 if (__unlikely(mutex == NULL))
1143 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001144
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001145 mvalue = mutex->value;
1146 mtype = (mvalue & MUTEX_TYPE_MASK);
1147 shared = (mvalue & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001148
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001149 /* Handle common case first */
1150 if (__likely(mtype == MUTEX_TYPE_NORMAL)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001151 _normal_unlock(mutex, shared);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001152 return 0;
1153 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001154
1155 /* Do we already own this recursive or error-check mutex ? */
1156 tid = __get_thread()->kernel_id;
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001157 if ( tid != MUTEX_VALUE_OWNER(mvalue) )
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001158 return EPERM;
1159
1160 /* We do, decrement counter or release the mutex if it is 0 */
1161 _recursive_lock();
1162 oldv = mutex->value;
1163 if (oldv & MUTEX_COUNTER_MASK) {
1164 mutex->value = oldv - (1 << MUTEX_COUNTER_SHIFT);
1165 oldv = 0;
1166 } else {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001167 mutex->value = shared | mtype;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001168 }
1169 _recursive_unlock();
1170
1171 /* Wake one waiting thread, if any */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001172 if ((oldv & 3) == 2) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001173 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001174 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001175 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001176}
1177
1178
1179int pthread_mutex_trylock(pthread_mutex_t *mutex)
1180{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001181 int mvalue, mtype, tid, oldv, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001182
1183 if (__unlikely(mutex == NULL))
1184 return EINVAL;
1185
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001186 mvalue = mutex->value;
1187 mtype = (mvalue & MUTEX_TYPE_MASK);
1188 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001189
1190 /* Handle common case first */
1191 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001192 {
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001193 if (__bionic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001194 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001195 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001196 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001197
1198 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001199 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001200
1201 /* Do we already own this recursive or error-check mutex ? */
1202 tid = __get_thread()->kernel_id;
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001203 if ( tid == MUTEX_VALUE_OWNER(mvalue) )
1204 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001205
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001206 /* Restore sharing bit in mtype */
1207 mtype |= shared;
1208
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001209 /* Try to lock it, just once. */
1210 _recursive_lock();
1211 oldv = mutex->value;
1212 if (oldv == mtype) /* uncontended released lock => state 1 */
1213 mutex->value = ((tid << 16) | mtype | 1);
1214 _recursive_unlock();
1215
1216 if (oldv != mtype)
1217 return EBUSY;
1218
1219 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001220}
1221
1222
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001223/* initialize 'ts' with the difference between 'abstime' and the current time
1224 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
1225 */
1226static int
1227__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
1228{
1229 clock_gettime(clock, ts);
1230 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
1231 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
1232 if (ts->tv_nsec < 0) {
1233 ts->tv_sec--;
1234 ts->tv_nsec += 1000000000;
1235 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001236 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001237 return -1;
1238
1239 return 0;
1240}
1241
1242/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1243 * milliseconds.
1244 */
1245static void
1246__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1247{
1248 clock_gettime(clock, abstime);
1249 abstime->tv_sec += msecs/1000;
1250 abstime->tv_nsec += (msecs%1000)*1000000;
1251 if (abstime->tv_nsec >= 1000000000) {
1252 abstime->tv_sec++;
1253 abstime->tv_nsec -= 1000000000;
1254 }
1255}
1256
1257int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1258{
1259 clockid_t clock = CLOCK_MONOTONIC;
1260 struct timespec abstime;
1261 struct timespec ts;
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001262 int mvalue, mtype, tid, oldv, new_lock_type, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001263
1264 /* compute absolute expiration time */
1265 __timespec_to_relative_msec(&abstime, msecs, clock);
1266
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001267 if (__unlikely(mutex == NULL))
1268 return EINVAL;
1269
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001270 mvalue = mutex->value;
1271 mtype = (mvalue & MUTEX_TYPE_MASK);
1272 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001273
1274 /* Handle common case first */
1275 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001276 {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001277 /* fast path for uncontended lock */
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001278 if (__bionic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001279 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001280 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001281 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001282
1283 /* loop while needed */
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001284 while (__bionic_swap(shared|2, &mutex->value) != (shared|0)) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001285 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1286 return EBUSY;
1287
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001288 __futex_wait_ex(&mutex->value, shared, shared|2, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001289 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001290 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001291 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001292 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001293
1294 /* Do we already own this recursive or error-check mutex ? */
1295 tid = __get_thread()->kernel_id;
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001296 if ( tid == MUTEX_VALUE_OWNER(mvalue) )
1297 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001298
1299 /* We don't own the mutex, so try to get it.
1300 *
1301 * First, we try to change its state from 0 to 1, if this
1302 * doesn't work, try to change it to state 2.
1303 */
1304 new_lock_type = 1;
1305
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001306 /* Compute wait op and restore sharing bit in mtype */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001307 mtype |= shared;
1308
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001309 for (;;) {
1310 int oldv;
1311 struct timespec ts;
1312
1313 _recursive_lock();
1314 oldv = mutex->value;
1315 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1316 mutex->value = ((tid << 16) | mtype | new_lock_type);
1317 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1318 oldv ^= 3;
1319 mutex->value = oldv;
1320 }
1321 _recursive_unlock();
1322
1323 if (oldv == mtype)
1324 break;
1325
1326 /*
1327 * The lock was held, possibly contended by others. From
1328 * now on, if we manage to acquire the lock, we have to
1329 * assume that others are still contending for it so that
1330 * we'll wake them when we unlock it.
1331 */
1332 new_lock_type = 2;
1333
1334 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1335 return EBUSY;
1336
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001337 __futex_wait_ex(&mutex->value, shared, oldv, &ts);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001338 }
1339 return 0;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001340}
1341
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001342int pthread_condattr_init(pthread_condattr_t *attr)
1343{
1344 if (attr == NULL)
1345 return EINVAL;
1346
1347 *attr = PTHREAD_PROCESS_PRIVATE;
1348 return 0;
1349}
1350
1351int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1352{
1353 if (attr == NULL || pshared == NULL)
1354 return EINVAL;
1355
1356 *pshared = *attr;
1357 return 0;
1358}
1359
1360int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1361{
1362 if (attr == NULL)
1363 return EINVAL;
1364
1365 if (pshared != PTHREAD_PROCESS_SHARED &&
1366 pshared != PTHREAD_PROCESS_PRIVATE)
1367 return EINVAL;
1368
1369 *attr = pshared;
1370 return 0;
1371}
1372
1373int pthread_condattr_destroy(pthread_condattr_t *attr)
1374{
1375 if (attr == NULL)
1376 return EINVAL;
1377
1378 *attr = 0xdeada11d;
1379 return 0;
1380}
1381
1382/* We use one bit in condition variable values as the 'shared' flag
1383 * The rest is a counter.
1384 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001385#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001386#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001387#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1388
1389#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001390
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001391/* XXX *technically* there is a race condition that could allow
1392 * XXX a signal to be missed. If thread A is preempted in _wait()
1393 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001394 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001395 * XXX before thread A is scheduled again and calls futex_wait(),
1396 * XXX then the signal will be lost.
1397 */
1398
1399int pthread_cond_init(pthread_cond_t *cond,
1400 const pthread_condattr_t *attr)
1401{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001402 if (cond == NULL)
1403 return EINVAL;
1404
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001405 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001406
1407 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001408 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001409
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001410 return 0;
1411}
1412
1413int pthread_cond_destroy(pthread_cond_t *cond)
1414{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001415 if (cond == NULL)
1416 return EINVAL;
1417
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001418 cond->value = 0xdeadc04d;
1419 return 0;
1420}
1421
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001422/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001423 * pthread_cond_signal to atomically decrement the counter
1424 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001425 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001426static int
1427__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001428{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001429 long flags;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001430
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001431 if (__unlikely(cond == NULL))
1432 return EINVAL;
1433
1434 flags = (cond->value & ~COND_COUNTER_MASK);
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001435 for (;;) {
1436 long oldval = cond->value;
1437 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1438 | flags;
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001439 if (__bionic_cmpxchg(oldval, newval, &cond->value) == 0)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001440 break;
1441 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001442
Andy McFaddene2ac8982010-09-02 13:34:53 -07001443 /*
1444 * Ensure that all memory accesses previously made by this thread are
1445 * visible to the woken thread(s). On the other side, the "wait"
1446 * code will issue any necessary barriers when locking the mutex.
1447 *
1448 * This may not strictly be necessary -- if the caller follows
1449 * recommended practice and holds the mutex before signaling the cond
1450 * var, the mutex ops will provide correct semantics. If they don't
1451 * hold the mutex, they're subject to race conditions anyway.
1452 */
1453 ANDROID_MEMBAR_FULL();
1454
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001455 __futex_wake_ex(&cond->value, COND_IS_SHARED(cond), counter);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001456 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001457}
1458
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001459int pthread_cond_broadcast(pthread_cond_t *cond)
1460{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001461 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001462}
1463
1464int pthread_cond_signal(pthread_cond_t *cond)
1465{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001466 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001467}
1468
1469int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1470{
1471 return pthread_cond_timedwait(cond, mutex, NULL);
1472}
1473
1474int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1475 pthread_mutex_t * mutex,
1476 const struct timespec *reltime)
1477{
1478 int status;
1479 int oldvalue = cond->value;
1480
1481 pthread_mutex_unlock(mutex);
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001482 status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond), oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001483 pthread_mutex_lock(mutex);
1484
1485 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1486 return 0;
1487}
1488
1489int __pthread_cond_timedwait(pthread_cond_t *cond,
1490 pthread_mutex_t * mutex,
1491 const struct timespec *abstime,
1492 clockid_t clock)
1493{
1494 struct timespec ts;
1495 struct timespec * tsp;
1496
1497 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001498 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001499 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001500 tsp = &ts;
1501 } else {
1502 tsp = NULL;
1503 }
1504
1505 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1506}
1507
1508int pthread_cond_timedwait(pthread_cond_t *cond,
1509 pthread_mutex_t * mutex,
1510 const struct timespec *abstime)
1511{
1512 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1513}
1514
1515
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001516/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001517int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1518 pthread_mutex_t * mutex,
1519 const struct timespec *abstime)
1520{
1521 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1522}
1523
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001524int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1525 pthread_mutex_t * mutex,
1526 const struct timespec *abstime)
1527{
1528 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1529}
1530
1531int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1532 pthread_mutex_t * mutex,
1533 const struct timespec *reltime)
1534{
1535 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1536}
1537
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001538int pthread_cond_timeout_np(pthread_cond_t *cond,
1539 pthread_mutex_t * mutex,
1540 unsigned msecs)
1541{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001542 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001543
1544 ts.tv_sec = msecs / 1000;
1545 ts.tv_nsec = (msecs % 1000) * 1000000;
1546
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001547 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001548}
1549
1550
1551
1552/* A technical note regarding our thread-local-storage (TLS) implementation:
1553 *
1554 * There can be up to TLSMAP_SIZE independent TLS keys in a given process,
1555 * though the first TLSMAP_START keys are reserved for Bionic to hold
1556 * special thread-specific variables like errno or a pointer to
1557 * the current thread's descriptor.
1558 *
1559 * while stored in the TLS area, these entries cannot be accessed through
1560 * pthread_getspecific() / pthread_setspecific() and pthread_key_delete()
1561 *
1562 * also, some entries in the key table are pre-allocated (see tlsmap_lock)
1563 * to greatly simplify and speedup some OpenGL-related operations. though the
1564 * initialy value will be NULL on all threads.
1565 *
1566 * you can use pthread_getspecific()/setspecific() on these, and in theory
1567 * you could also call pthread_key_delete() as well, though this would
1568 * probably break some apps.
1569 *
1570 * The 'tlsmap_t' type defined below implements a shared global map of
1571 * currently created/allocated TLS keys and the destructors associated
1572 * with them. You should use tlsmap_lock/unlock to access it to avoid
1573 * any race condition.
1574 *
1575 * the global TLS map simply contains a bitmap of allocated keys, and
1576 * an array of destructors.
1577 *
1578 * each thread has a TLS area that is a simple array of TLSMAP_SIZE void*
1579 * pointers. the TLS area of the main thread is stack-allocated in
1580 * __libc_init_common, while the TLS area of other threads is placed at
1581 * the top of their stack in pthread_create.
1582 *
1583 * when pthread_key_create() is called, it finds the first free key in the
1584 * bitmap, then set it to 1, saving the destructor altogether
1585 *
1586 * when pthread_key_delete() is called. it will erase the key's bitmap bit
1587 * and its destructor, and will also clear the key data in the TLS area of
1588 * all created threads. As mandated by Posix, it is the responsability of
1589 * the caller of pthread_key_delete() to properly reclaim the objects that
1590 * were pointed to by these data fields (either before or after the call).
1591 *
1592 */
1593
1594/* TLS Map implementation
1595 */
1596
1597#define TLSMAP_START (TLS_SLOT_MAX_WELL_KNOWN+1)
1598#define TLSMAP_SIZE BIONIC_TLS_SLOTS
1599#define TLSMAP_BITS 32
1600#define TLSMAP_WORDS ((TLSMAP_SIZE+TLSMAP_BITS-1)/TLSMAP_BITS)
1601#define TLSMAP_WORD(m,k) (m)->map[(k)/TLSMAP_BITS]
1602#define TLSMAP_MASK(k) (1U << ((k)&(TLSMAP_BITS-1)))
1603
1604/* this macro is used to quickly check that a key belongs to a reasonable range */
1605#define TLSMAP_VALIDATE_KEY(key) \
1606 ((key) >= TLSMAP_START && (key) < TLSMAP_SIZE)
1607
1608/* the type of tls key destructor functions */
1609typedef void (*tls_dtor_t)(void*);
1610
1611typedef struct {
1612 int init; /* see comment in tlsmap_lock() */
1613 uint32_t map[TLSMAP_WORDS]; /* bitmap of allocated keys */
1614 tls_dtor_t dtors[TLSMAP_SIZE]; /* key destructors */
1615} tlsmap_t;
1616
1617static pthread_mutex_t _tlsmap_lock = PTHREAD_MUTEX_INITIALIZER;
1618static tlsmap_t _tlsmap;
1619
1620/* lock the global TLS map lock and return a handle to it */
1621static __inline__ tlsmap_t* tlsmap_lock(void)
1622{
1623 tlsmap_t* m = &_tlsmap;
1624
1625 pthread_mutex_lock(&_tlsmap_lock);
1626 /* we need to initialize the first entry of the 'map' array
1627 * with the value TLS_DEFAULT_ALLOC_MAP. doing it statically
1628 * when declaring _tlsmap is a bit awkward and is going to
1629 * produce warnings, so do it the first time we use the map
1630 * instead
1631 */
1632 if (__unlikely(!m->init)) {
1633 TLSMAP_WORD(m,0) = TLS_DEFAULT_ALLOC_MAP;
1634 m->init = 1;
1635 }
1636 return m;
1637}
1638
1639/* unlock the global TLS map */
1640static __inline__ void tlsmap_unlock(tlsmap_t* m)
1641{
1642 pthread_mutex_unlock(&_tlsmap_lock);
1643 (void)m; /* a good compiler is a happy compiler */
1644}
1645
1646/* test to see wether a key is allocated */
1647static __inline__ int tlsmap_test(tlsmap_t* m, int key)
1648{
1649 return (TLSMAP_WORD(m,key) & TLSMAP_MASK(key)) != 0;
1650}
1651
1652/* set the destructor and bit flag on a newly allocated key */
1653static __inline__ void tlsmap_set(tlsmap_t* m, int key, tls_dtor_t dtor)
1654{
1655 TLSMAP_WORD(m,key) |= TLSMAP_MASK(key);
1656 m->dtors[key] = dtor;
1657}
1658
1659/* clear the destructor and bit flag on an existing key */
1660static __inline__ void tlsmap_clear(tlsmap_t* m, int key)
1661{
1662 TLSMAP_WORD(m,key) &= ~TLSMAP_MASK(key);
1663 m->dtors[key] = NULL;
1664}
1665
1666/* allocate a new TLS key, return -1 if no room left */
1667static int tlsmap_alloc(tlsmap_t* m, tls_dtor_t dtor)
1668{
1669 int key;
1670
1671 for ( key = TLSMAP_START; key < TLSMAP_SIZE; key++ ) {
1672 if ( !tlsmap_test(m, key) ) {
1673 tlsmap_set(m, key, dtor);
1674 return key;
1675 }
1676 }
1677 return -1;
1678}
1679
1680
1681int pthread_key_create(pthread_key_t *key, void (*destructor_function)(void *))
1682{
1683 uint32_t err = ENOMEM;
1684 tlsmap_t* map = tlsmap_lock();
1685 int k = tlsmap_alloc(map, destructor_function);
1686
1687 if (k >= 0) {
1688 *key = k;
1689 err = 0;
1690 }
1691 tlsmap_unlock(map);
1692 return err;
1693}
1694
1695
1696/* This deletes a pthread_key_t. note that the standard mandates that this does
1697 * not call the destructor of non-NULL key values. Instead, it is the
1698 * responsability of the caller to properly dispose of the corresponding data
1699 * and resources, using any mean it finds suitable.
1700 *
1701 * On the other hand, this function will clear the corresponding key data
1702 * values in all known threads. this prevents later (invalid) calls to
1703 * pthread_getspecific() to receive invalid/stale values.
1704 */
1705int pthread_key_delete(pthread_key_t key)
1706{
1707 uint32_t err;
1708 pthread_internal_t* thr;
1709 tlsmap_t* map;
1710
1711 if (!TLSMAP_VALIDATE_KEY(key)) {
1712 return EINVAL;
1713 }
1714
1715 map = tlsmap_lock();
1716
1717 if (!tlsmap_test(map, key)) {
1718 err = EINVAL;
1719 goto err1;
1720 }
1721
1722 /* clear value in all threads */
1723 pthread_mutex_lock(&gThreadListLock);
1724 for ( thr = gThreadList; thr != NULL; thr = thr->next ) {
1725 /* avoid zombie threads with a negative 'join_count'. these are really
1726 * already dead and don't have a TLS area anymore.
1727 *
1728 * similarly, it is possible to have thr->tls == NULL for threads that
1729 * were just recently created through pthread_create() but whose
1730 * startup trampoline (__thread_entry) hasn't been run yet by the
1731 * scheduler. so check for this too.
1732 */
1733 if (thr->join_count < 0 || !thr->tls)
1734 continue;
1735
1736 thr->tls[key] = NULL;
1737 }
1738 tlsmap_clear(map, key);
1739
1740 pthread_mutex_unlock(&gThreadListLock);
1741 err = 0;
1742
1743err1:
1744 tlsmap_unlock(map);
1745 return err;
1746}
1747
1748
1749int pthread_setspecific(pthread_key_t key, const void *ptr)
1750{
1751 int err = EINVAL;
1752 tlsmap_t* map;
1753
1754 if (TLSMAP_VALIDATE_KEY(key)) {
1755 /* check that we're trying to set data for an allocated key */
1756 map = tlsmap_lock();
1757 if (tlsmap_test(map, key)) {
1758 ((uint32_t *)__get_tls())[key] = (uint32_t)ptr;
1759 err = 0;
1760 }
1761 tlsmap_unlock(map);
1762 }
1763 return err;
1764}
1765
1766void * pthread_getspecific(pthread_key_t key)
1767{
1768 if (!TLSMAP_VALIDATE_KEY(key)) {
1769 return NULL;
1770 }
1771
1772 /* for performance reason, we do not lock/unlock the global TLS map
1773 * to check that the key is properly allocated. if the key was not
1774 * allocated, the value read from the TLS should always be NULL
1775 * due to pthread_key_delete() clearing the values for all threads.
1776 */
1777 return (void *)(((unsigned *)__get_tls())[key]);
1778}
1779
1780/* Posix mandates that this be defined in <limits.h> but we don't have
1781 * it just yet.
1782 */
1783#ifndef PTHREAD_DESTRUCTOR_ITERATIONS
1784# define PTHREAD_DESTRUCTOR_ITERATIONS 4
1785#endif
1786
1787/* this function is called from pthread_exit() to remove all TLS key data
1788 * from this thread's TLS area. this must call the destructor of all keys
1789 * that have a non-NULL data value (and a non-NULL destructor).
1790 *
1791 * because destructors can do funky things like deleting/creating other
1792 * keys, we need to implement this in a loop
1793 */
1794static void pthread_key_clean_all(void)
1795{
1796 tlsmap_t* map;
1797 void** tls = (void**)__get_tls();
1798 int rounds = PTHREAD_DESTRUCTOR_ITERATIONS;
1799
1800 map = tlsmap_lock();
1801
1802 for (rounds = PTHREAD_DESTRUCTOR_ITERATIONS; rounds > 0; rounds--)
1803 {
1804 int kk, count = 0;
1805
1806 for (kk = TLSMAP_START; kk < TLSMAP_SIZE; kk++) {
1807 if ( tlsmap_test(map, kk) )
1808 {
1809 void* data = tls[kk];
1810 tls_dtor_t dtor = map->dtors[kk];
1811
1812 if (data != NULL && dtor != NULL)
1813 {
1814 /* we need to clear the key data now, this will prevent the
1815 * destructor (or a later one) from seeing the old value if
1816 * it calls pthread_getspecific() for some odd reason
1817 *
1818 * we do not do this if 'dtor == NULL' just in case another
1819 * destructor function might be responsible for manually
1820 * releasing the corresponding data.
1821 */
1822 tls[kk] = NULL;
1823
1824 /* because the destructor is free to call pthread_key_create
1825 * and/or pthread_key_delete, we need to temporarily unlock
1826 * the TLS map
1827 */
1828 tlsmap_unlock(map);
1829 (*dtor)(data);
1830 map = tlsmap_lock();
1831
1832 count += 1;
1833 }
1834 }
1835 }
1836
1837 /* if we didn't call any destructor, there is no need to check the
1838 * TLS data again
1839 */
1840 if (count == 0)
1841 break;
1842 }
1843 tlsmap_unlock(map);
1844}
1845
1846// man says this should be in <linux/unistd.h>, but it isn't
Jeff Brown10c8ce52011-11-18 15:17:07 -08001847extern int tgkill(int tgid, int tid, int sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001848
1849int pthread_kill(pthread_t tid, int sig)
1850{
1851 int ret;
1852 int old_errno = errno;
1853 pthread_internal_t * thread = (pthread_internal_t *)tid;
1854
Jeff Brown10c8ce52011-11-18 15:17:07 -08001855 ret = tgkill(getpid(), thread->kernel_id, sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001856 if (ret < 0) {
1857 ret = errno;
1858 errno = old_errno;
1859 }
1860
1861 return ret;
1862}
1863
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001864/* Despite the fact that our kernel headers define sigset_t explicitly
1865 * as a 32-bit integer, the kernel system call really expects a 64-bit
1866 * bitmap for the signal set, or more exactly an array of two-32-bit
1867 * values (see $KERNEL/arch/$ARCH/include/asm/signal.h for details).
1868 *
1869 * Unfortunately, we cannot fix the sigset_t definition without breaking
1870 * the C library ABI, so perform a little runtime translation here.
1871 */
1872typedef union {
1873 sigset_t bionic;
1874 uint32_t kernel[2];
1875} kernel_sigset_t;
1876
1877/* this is a private syscall stub */
1878extern int __rt_sigprocmask(int, const kernel_sigset_t *, kernel_sigset_t *, size_t);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001879
1880int pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
1881{
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001882 /* pthread_sigmask must return the error code, but the syscall
1883 * will set errno instead and return 0/-1
1884 */
1885 int ret, old_errno = errno;
1886
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001887 /* We must convert *set into a kernel_sigset_t */
1888 kernel_sigset_t in_set, *in_set_ptr;
1889 kernel_sigset_t out_set;
1890
Bruce Bearee4a21c82011-12-05 11:25:37 -08001891 in_set.kernel[0] = in_set.kernel[1] = 0;
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001892 out_set.kernel[0] = out_set.kernel[1] = 0;
1893
1894 /* 'in_set_ptr' is the second parameter to __rt_sigprocmask. It must be NULL
1895 * if 'set' is NULL to ensure correct semantics (which in this case would
1896 * be to ignore 'how' and return the current signal set into 'oset'.
David 'Digit' Turner5c8c00a2010-12-20 15:58:06 +01001897 */
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001898 if (set == NULL) {
1899 in_set_ptr = NULL;
1900 } else {
1901 in_set.bionic = *set;
1902 in_set_ptr = &in_set;
1903 }
1904
1905 ret = __rt_sigprocmask(how, in_set_ptr, &out_set, sizeof(kernel_sigset_t));
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001906 if (ret < 0)
1907 ret = errno;
1908
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001909 if (oset)
1910 *oset = out_set.bionic;
1911
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001912 errno = old_errno;
1913 return ret;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001914}
1915
1916
1917int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
1918{
1919 const int CLOCK_IDTYPE_BITS = 3;
1920 pthread_internal_t* thread = (pthread_internal_t*)tid;
1921
1922 if (!thread)
1923 return ESRCH;
1924
1925 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
1926 return 0;
1927}
1928
1929
1930/* NOTE: this implementation doesn't support a init function that throws a C++ exception
1931 * or calls fork()
1932 */
1933int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
1934{
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001935 static pthread_mutex_t once_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001936 volatile pthread_once_t* ocptr = once_control;
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001937 pthread_once_t value;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001938
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001939 /* PTHREAD_ONCE_INIT is 0, we use the following bit flags
1940 *
1941 * bit 0 set -> initialization is under way
1942 * bit 1 set -> initialization is complete
1943 */
1944#define ONCE_INITIALIZING (1 << 0)
1945#define ONCE_COMPLETED (1 << 1)
1946
1947 /* First check if the once is already initialized. This will be the common
1948 * case and we want to make this as fast as possible. Note that this still
1949 * requires a load_acquire operation here to ensure that all the
1950 * stores performed by the initialization function are observable on
1951 * this CPU after we exit.
1952 */
1953 if (__likely((*ocptr & ONCE_COMPLETED) != 0)) {
1954 ANDROID_MEMBAR_FULL();
1955 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001956 }
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001957
1958 for (;;) {
1959 /* Try to atomically set the INITIALIZING flag.
1960 * This requires a cmpxchg loop, and we may need
1961 * to exit prematurely if we detect that
1962 * COMPLETED is now set.
1963 */
1964 int32_t oldval, newval;
1965
1966 do {
1967 oldval = *ocptr;
1968 if ((oldval & ONCE_COMPLETED) != 0)
1969 break;
1970
1971 newval = oldval | ONCE_INITIALIZING;
1972 } while (__bionic_cmpxchg(oldval, newval, ocptr) != 0);
1973
1974 if ((oldval & ONCE_COMPLETED) != 0) {
1975 /* We detected that COMPLETED was set while in our loop */
1976 ANDROID_MEMBAR_FULL();
1977 return 0;
1978 }
1979
1980 if ((oldval & ONCE_INITIALIZING) == 0) {
1981 /* We got there first, we can jump out of the loop to
1982 * handle the initialization */
1983 break;
1984 }
1985
1986 /* Another thread is running the initialization and hasn't completed
1987 * yet, so wait for it, then try again. */
1988 __futex_wait_ex(ocptr, 0, oldval, NULL);
1989 }
1990
1991 /* call the initialization function. */
1992 (*init_routine)();
1993
1994 /* Do a store_release indicating that initialization is complete */
1995 ANDROID_MEMBAR_FULL();
1996 *ocptr = ONCE_COMPLETED;
1997
1998 /* Wake up any waiters, if any */
1999 __futex_wake_ex(ocptr, 0, INT_MAX);
2000
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002001 return 0;
2002}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03002003
2004/* This value is not exported by kernel headers, so hardcode it here */
2005#define MAX_TASK_COMM_LEN 16
2006#define TASK_COMM_FMT "/proc/self/task/%u/comm"
2007
2008int pthread_setname_np(pthread_t thid, const char *thname)
2009{
2010 size_t thname_len;
2011 int saved_errno, ret;
2012
2013 if (thid == 0 || thname == NULL)
2014 return EINVAL;
2015
2016 thname_len = strlen(thname);
2017 if (thname_len >= MAX_TASK_COMM_LEN)
2018 return ERANGE;
2019
2020 saved_errno = errno;
2021 if (thid == pthread_self())
2022 {
2023 ret = prctl(PR_SET_NAME, (unsigned long)thname, 0, 0, 0) ? errno : 0;
2024 }
2025 else
2026 {
2027 /* Have to change another thread's name */
2028 pthread_internal_t *thread = (pthread_internal_t *)thid;
2029 char comm_name[sizeof(TASK_COMM_FMT) + 8];
2030 ssize_t n;
2031 int fd;
2032
2033 snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, (unsigned int)thread->kernel_id);
2034 fd = open(comm_name, O_RDWR);
2035 if (fd == -1)
2036 {
2037 ret = errno;
2038 goto exit;
2039 }
2040 n = TEMP_FAILURE_RETRY(write(fd, thname, thname_len));
2041 close(fd);
2042
2043 if (n < 0)
2044 ret = errno;
2045 else if ((size_t)n != thname_len)
2046 ret = EIO;
2047 else
2048 ret = 0;
2049 }
2050exit:
2051 errno = saved_errno;
2052 return ret;
2053}
Glenn Kastend53cae02011-07-11 15:41:28 -07002054
2055/* Return the kernel thread ID for a pthread.
2056 * This is only defined for implementations where pthread <-> kernel is 1:1, which this is.
2057 * Not the same as pthread_getthreadid_np, which is commonly defined to be opaque.
2058 * Internal, not an NDK API.
2059 */
2060
2061pid_t __pthread_gettid(pthread_t thid)
2062{
2063 pthread_internal_t* thread = (pthread_internal_t*)thid;
2064 return thread->kernel_id;
2065}