blob: a6002de6cc6455ac4991e620cd0affa361805d07 [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' Turnerb57db752012-01-24 13:20:38 +01001004static pthread_mutex_t __recursive_lock = PTHREAD_MUTEX_INITIALIZER;
1005
1006static __inline__ void
1007_recursive_lock(void)
1008{
1009 _normal_lock(&__recursive_lock, 0);
1010}
1011
1012static __inline__ void
1013_recursive_unlock(void)
1014{
1015 _normal_unlock(&__recursive_lock, 0);
1016}
1017
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001018/* This common inlined function is used to increment the counter of an
1019 * errorcheck or recursive mutex.
1020 *
1021 * For errorcheck mutexes, it will return EDEADLK
1022 * If the counter overflows, it will return EAGAIN
1023 * Otherwise, it atomically increments the counter and returns 0
1024 * after providing an acquire barrier.
1025 *
1026 * mtype is the current mutex type
1027 * mvalue is the current mutex value (already loaded)
1028 * mutex pointers to the mutex.
1029 */
1030static __inline__ __attribute__((always_inline)) int
1031_recursive_increment(pthread_mutex_t* mutex, int mvalue, int mtype)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001032{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001033 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1034 /* trying to re-lock a mutex we already acquired */
1035 return EDEADLK;
1036 }
1037
1038 /* Detect recursive lock overflow and return EAGAIN.
1039 * This is safe because only the owner thread can modify the
David 'Digit' Turnerb57db752012-01-24 13:20:38 +01001040 * counter bits in the mutex value.
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001041 */
1042 if ((mvalue & MUTEX_COUNTER_MASK) == MUTEX_COUNTER_MASK) {
1043 return EAGAIN;
1044 }
1045
1046 /* We own the mutex, but other threads are able to change
David 'Digit' Turnerb57db752012-01-24 13:20:38 +01001047 * the lower bits (e.g. promoting it to "contended"), so we
1048 * need to use the recursive global lock to do that.
1049 *
1050 * The lock/unlock sequence also provides a full memory barrier
1051 * so we don't need to add one here explicitely.
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001052 */
David 'Digit' Turnerb57db752012-01-24 13:20:38 +01001053 _recursive_lock();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001054
David 'Digit' Turnerb57db752012-01-24 13:20:38 +01001055 /* increment counter, overflow was already checked */
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001056
David 'Digit' Turnerb57db752012-01-24 13:20:38 +01001057 /* NOTE: we need to reload the value since its lower bits could have
1058 * been modified since the exit of _recursive_lock()
1059 */
1060 mutex->value = mutex->value + (1 << MUTEX_COUNTER_SHIFT);
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001061
David 'Digit' Turnerb57db752012-01-24 13:20:38 +01001062 _recursive_unlock();
1063 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001064}
1065
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001066__LIBC_HIDDEN__
1067int pthread_mutex_lock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001068{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001069 int mvalue, mtype, tid, new_lock_type, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001070
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001071 if (__unlikely(mutex == NULL))
1072 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001073
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001074 mvalue = mutex->value;
1075 mtype = (mvalue & MUTEX_TYPE_MASK);
1076 shared = (mvalue & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001077
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001078 /* Handle normal case first */
1079 if ( __likely(mtype == MUTEX_TYPE_NORMAL) ) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001080 _normal_lock(mutex, shared);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001081 return 0;
1082 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001083
1084 /* Do we already own this recursive or error-check mutex ? */
1085 tid = __get_thread()->kernel_id;
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001086 if ( tid == MUTEX_VALUE_OWNER(mvalue) )
1087 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001088
1089 /* We don't own the mutex, so try to get it.
1090 *
1091 * First, we try to change its state from 0 to 1, if this
1092 * doesn't work, try to change it to state 2.
1093 */
1094 new_lock_type = 1;
1095
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001096 /* compute futex wait opcode and restore shared flag in mtype */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001097 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001098
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001099 for (;;) {
1100 int oldv;
1101
1102 _recursive_lock();
1103 oldv = mutex->value;
1104 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1105 mutex->value = ((tid << 16) | mtype | new_lock_type);
1106 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1107 oldv ^= 3;
1108 mutex->value = oldv;
1109 }
1110 _recursive_unlock();
1111
1112 if (oldv == mtype)
1113 break;
1114
1115 /*
1116 * The lock was held, possibly contended by others. From
1117 * now on, if we manage to acquire the lock, we have to
1118 * assume that others are still contending for it so that
1119 * we'll wake them when we unlock it.
1120 */
1121 new_lock_type = 2;
1122
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001123 __futex_wait_ex(&mutex->value, shared, oldv, NULL);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001124 }
1125 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001126}
1127
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001128int pthread_mutex_lock(pthread_mutex_t *mutex)
1129{
1130 int err = pthread_mutex_lock_impl(mutex);
1131#ifdef PTHREAD_DEBUG
1132 if (PTHREAD_DEBUG_ENABLED) {
1133 if (!err) {
1134 pthread_debug_mutex_lock_check(mutex);
1135 }
1136 }
1137#endif
1138 return err;
1139}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001140
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001141__LIBC_HIDDEN__
1142int pthread_mutex_unlock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001143{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001144 int mvalue, mtype, tid, oldv, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001145
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001146 if (__unlikely(mutex == NULL))
1147 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001148
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001149 mvalue = mutex->value;
1150 mtype = (mvalue & MUTEX_TYPE_MASK);
1151 shared = (mvalue & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001152
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001153 /* Handle common case first */
1154 if (__likely(mtype == MUTEX_TYPE_NORMAL)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001155 _normal_unlock(mutex, shared);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001156 return 0;
1157 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001158
1159 /* Do we already own this recursive or error-check mutex ? */
1160 tid = __get_thread()->kernel_id;
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001161 if ( tid != MUTEX_VALUE_OWNER(mvalue) )
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001162 return EPERM;
1163
1164 /* We do, decrement counter or release the mutex if it is 0 */
1165 _recursive_lock();
1166 oldv = mutex->value;
1167 if (oldv & MUTEX_COUNTER_MASK) {
1168 mutex->value = oldv - (1 << MUTEX_COUNTER_SHIFT);
1169 oldv = 0;
1170 } else {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001171 mutex->value = shared | mtype;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001172 }
1173 _recursive_unlock();
1174
1175 /* Wake one waiting thread, if any */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001176 if ((oldv & 3) == 2) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001177 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001178 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001179 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001180}
1181
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001182int pthread_mutex_unlock(pthread_mutex_t *mutex)
1183{
1184#ifdef PTHREAD_DEBUG
1185 if (PTHREAD_DEBUG_ENABLED) {
1186 pthread_debug_mutex_unlock_check(mutex);
1187 }
1188#endif
1189 return pthread_mutex_unlock_impl(mutex);
1190}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001191
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001192__LIBC_HIDDEN__
1193int pthread_mutex_trylock_impl(pthread_mutex_t *mutex)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001194{
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001195 int mvalue, mtype, tid, oldv, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001196
1197 if (__unlikely(mutex == NULL))
1198 return EINVAL;
1199
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001200 mvalue = mutex->value;
1201 mtype = (mvalue & MUTEX_TYPE_MASK);
1202 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001203
1204 /* Handle common case first */
1205 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001206 {
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001207 if (__bionic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001208 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001209 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001210 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001211
1212 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001213 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001214
1215 /* Do we already own this recursive or error-check mutex ? */
1216 tid = __get_thread()->kernel_id;
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001217 if ( tid == MUTEX_VALUE_OWNER(mvalue) )
1218 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001219
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001220 /* Restore sharing bit in mtype */
1221 mtype |= shared;
1222
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001223 /* Try to lock it, just once. */
1224 _recursive_lock();
1225 oldv = mutex->value;
1226 if (oldv == mtype) /* uncontended released lock => state 1 */
1227 mutex->value = ((tid << 16) | mtype | 1);
1228 _recursive_unlock();
1229
1230 if (oldv != mtype)
1231 return EBUSY;
1232
1233 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001234}
1235
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001236int pthread_mutex_trylock(pthread_mutex_t *mutex)
1237{
1238 int err = pthread_mutex_trylock_impl(mutex);
1239#ifdef PTHREAD_DEBUG
1240 if (PTHREAD_DEBUG_ENABLED) {
1241 if (!err) {
1242 pthread_debug_mutex_lock_check(mutex);
1243 }
1244 }
1245#endif
1246 return err;
1247}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001248
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001249/* initialize 'ts' with the difference between 'abstime' and the current time
1250 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
1251 */
1252static int
1253__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
1254{
1255 clock_gettime(clock, ts);
1256 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
1257 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
1258 if (ts->tv_nsec < 0) {
1259 ts->tv_sec--;
1260 ts->tv_nsec += 1000000000;
1261 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001262 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001263 return -1;
1264
1265 return 0;
1266}
1267
1268/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1269 * milliseconds.
1270 */
1271static void
1272__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1273{
1274 clock_gettime(clock, abstime);
1275 abstime->tv_sec += msecs/1000;
1276 abstime->tv_nsec += (msecs%1000)*1000000;
1277 if (abstime->tv_nsec >= 1000000000) {
1278 abstime->tv_sec++;
1279 abstime->tv_nsec -= 1000000000;
1280 }
1281}
1282
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001283__LIBC_HIDDEN__
1284int pthread_mutex_lock_timeout_np_impl(pthread_mutex_t *mutex, unsigned msecs)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001285{
1286 clockid_t clock = CLOCK_MONOTONIC;
1287 struct timespec abstime;
1288 struct timespec ts;
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001289 int mvalue, mtype, tid, oldv, new_lock_type, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001290
1291 /* compute absolute expiration time */
1292 __timespec_to_relative_msec(&abstime, msecs, clock);
1293
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001294 if (__unlikely(mutex == NULL))
1295 return EINVAL;
1296
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001297 mvalue = mutex->value;
1298 mtype = (mvalue & MUTEX_TYPE_MASK);
1299 shared = (mvalue & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001300
1301 /* Handle common case first */
1302 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001303 {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001304 /* fast path for uncontended lock */
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001305 if (__bionic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001306 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001307 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001308 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001309
1310 /* loop while needed */
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001311 while (__bionic_swap(shared|2, &mutex->value) != (shared|0)) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001312 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1313 return EBUSY;
1314
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001315 __futex_wait_ex(&mutex->value, shared, shared|2, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001316 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001317 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001318 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001319 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001320
1321 /* Do we already own this recursive or error-check mutex ? */
1322 tid = __get_thread()->kernel_id;
David 'Digit' Turner022d3032011-12-07 14:02:17 +01001323 if ( tid == MUTEX_VALUE_OWNER(mvalue) )
1324 return _recursive_increment(mutex, mvalue, mtype);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001325
1326 /* We don't own the mutex, so try to get it.
1327 *
1328 * First, we try to change its state from 0 to 1, if this
1329 * doesn't work, try to change it to state 2.
1330 */
1331 new_lock_type = 1;
1332
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001333 /* Compute wait op and restore sharing bit in mtype */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001334 mtype |= shared;
1335
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001336 for (;;) {
1337 int oldv;
1338 struct timespec ts;
1339
1340 _recursive_lock();
1341 oldv = mutex->value;
1342 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1343 mutex->value = ((tid << 16) | mtype | new_lock_type);
1344 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1345 oldv ^= 3;
1346 mutex->value = oldv;
1347 }
1348 _recursive_unlock();
1349
1350 if (oldv == mtype)
1351 break;
1352
1353 /*
1354 * The lock was held, possibly contended by others. From
1355 * now on, if we manage to acquire the lock, we have to
1356 * assume that others are still contending for it so that
1357 * we'll wake them when we unlock it.
1358 */
1359 new_lock_type = 2;
1360
1361 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1362 return EBUSY;
1363
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001364 __futex_wait_ex(&mutex->value, shared, oldv, &ts);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001365 }
1366 return 0;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001367}
1368
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001369int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1370{
1371 int err = pthread_mutex_lock_timeout_np_impl(mutex, msecs);
1372#ifdef PTHREAD_DEBUG
1373 if (PTHREAD_DEBUG_ENABLED) {
1374 if (!err) {
1375 pthread_debug_mutex_lock_check(mutex);
1376 }
1377 }
1378#endif
1379 return err;
1380}
1381
1382int pthread_mutex_destroy(pthread_mutex_t *mutex)
1383{
1384 int ret;
1385
1386 /* use trylock to ensure that the mutex value is
1387 * valid and is not already locked. */
1388 ret = pthread_mutex_trylock_impl(mutex);
1389 if (ret != 0)
1390 return ret;
1391
1392 mutex->value = 0xdead10cc;
1393 return 0;
1394}
1395
1396
1397
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001398int pthread_condattr_init(pthread_condattr_t *attr)
1399{
1400 if (attr == NULL)
1401 return EINVAL;
1402
1403 *attr = PTHREAD_PROCESS_PRIVATE;
1404 return 0;
1405}
1406
1407int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1408{
1409 if (attr == NULL || pshared == NULL)
1410 return EINVAL;
1411
1412 *pshared = *attr;
1413 return 0;
1414}
1415
1416int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1417{
1418 if (attr == NULL)
1419 return EINVAL;
1420
1421 if (pshared != PTHREAD_PROCESS_SHARED &&
1422 pshared != PTHREAD_PROCESS_PRIVATE)
1423 return EINVAL;
1424
1425 *attr = pshared;
1426 return 0;
1427}
1428
1429int pthread_condattr_destroy(pthread_condattr_t *attr)
1430{
1431 if (attr == NULL)
1432 return EINVAL;
1433
1434 *attr = 0xdeada11d;
1435 return 0;
1436}
1437
1438/* We use one bit in condition variable values as the 'shared' flag
1439 * The rest is a counter.
1440 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001441#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001442#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001443#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1444
1445#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001446
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001447/* XXX *technically* there is a race condition that could allow
1448 * XXX a signal to be missed. If thread A is preempted in _wait()
1449 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001450 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001451 * XXX before thread A is scheduled again and calls futex_wait(),
1452 * XXX then the signal will be lost.
1453 */
1454
1455int pthread_cond_init(pthread_cond_t *cond,
1456 const pthread_condattr_t *attr)
1457{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001458 if (cond == NULL)
1459 return EINVAL;
1460
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001461 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001462
1463 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001464 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001465
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001466 return 0;
1467}
1468
1469int pthread_cond_destroy(pthread_cond_t *cond)
1470{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001471 if (cond == NULL)
1472 return EINVAL;
1473
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001474 cond->value = 0xdeadc04d;
1475 return 0;
1476}
1477
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001478/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001479 * pthread_cond_signal to atomically decrement the counter
1480 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001481 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001482static int
1483__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001484{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001485 long flags;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001486
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001487 if (__unlikely(cond == NULL))
1488 return EINVAL;
1489
1490 flags = (cond->value & ~COND_COUNTER_MASK);
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001491 for (;;) {
1492 long oldval = cond->value;
1493 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1494 | flags;
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001495 if (__bionic_cmpxchg(oldval, newval, &cond->value) == 0)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001496 break;
1497 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001498
Andy McFaddene2ac8982010-09-02 13:34:53 -07001499 /*
1500 * Ensure that all memory accesses previously made by this thread are
1501 * visible to the woken thread(s). On the other side, the "wait"
1502 * code will issue any necessary barriers when locking the mutex.
1503 *
1504 * This may not strictly be necessary -- if the caller follows
1505 * recommended practice and holds the mutex before signaling the cond
1506 * var, the mutex ops will provide correct semantics. If they don't
1507 * hold the mutex, they're subject to race conditions anyway.
1508 */
1509 ANDROID_MEMBAR_FULL();
1510
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001511 __futex_wake_ex(&cond->value, COND_IS_SHARED(cond), counter);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001512 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001513}
1514
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001515int pthread_cond_broadcast(pthread_cond_t *cond)
1516{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001517 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001518}
1519
1520int pthread_cond_signal(pthread_cond_t *cond)
1521{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001522 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001523}
1524
1525int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1526{
1527 return pthread_cond_timedwait(cond, mutex, NULL);
1528}
1529
1530int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1531 pthread_mutex_t * mutex,
1532 const struct timespec *reltime)
1533{
1534 int status;
1535 int oldvalue = cond->value;
1536
1537 pthread_mutex_unlock(mutex);
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001538 status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond), oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001539 pthread_mutex_lock(mutex);
1540
1541 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1542 return 0;
1543}
1544
1545int __pthread_cond_timedwait(pthread_cond_t *cond,
1546 pthread_mutex_t * mutex,
1547 const struct timespec *abstime,
1548 clockid_t clock)
1549{
1550 struct timespec ts;
1551 struct timespec * tsp;
1552
1553 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001554 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001555 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001556 tsp = &ts;
1557 } else {
1558 tsp = NULL;
1559 }
1560
1561 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1562}
1563
1564int pthread_cond_timedwait(pthread_cond_t *cond,
1565 pthread_mutex_t * mutex,
1566 const struct timespec *abstime)
1567{
1568 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1569}
1570
1571
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001572/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001573int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1574 pthread_mutex_t * mutex,
1575 const struct timespec *abstime)
1576{
1577 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1578}
1579
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001580int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1581 pthread_mutex_t * mutex,
1582 const struct timespec *abstime)
1583{
1584 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1585}
1586
1587int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1588 pthread_mutex_t * mutex,
1589 const struct timespec *reltime)
1590{
1591 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1592}
1593
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001594int pthread_cond_timeout_np(pthread_cond_t *cond,
1595 pthread_mutex_t * mutex,
1596 unsigned msecs)
1597{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001598 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001599
1600 ts.tv_sec = msecs / 1000;
1601 ts.tv_nsec = (msecs % 1000) * 1000000;
1602
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001603 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001604}
1605
1606
1607
1608/* A technical note regarding our thread-local-storage (TLS) implementation:
1609 *
1610 * There can be up to TLSMAP_SIZE independent TLS keys in a given process,
1611 * though the first TLSMAP_START keys are reserved for Bionic to hold
1612 * special thread-specific variables like errno or a pointer to
1613 * the current thread's descriptor.
1614 *
1615 * while stored in the TLS area, these entries cannot be accessed through
1616 * pthread_getspecific() / pthread_setspecific() and pthread_key_delete()
1617 *
1618 * also, some entries in the key table are pre-allocated (see tlsmap_lock)
1619 * to greatly simplify and speedup some OpenGL-related operations. though the
1620 * initialy value will be NULL on all threads.
1621 *
1622 * you can use pthread_getspecific()/setspecific() on these, and in theory
1623 * you could also call pthread_key_delete() as well, though this would
1624 * probably break some apps.
1625 *
1626 * The 'tlsmap_t' type defined below implements a shared global map of
1627 * currently created/allocated TLS keys and the destructors associated
1628 * with them. You should use tlsmap_lock/unlock to access it to avoid
1629 * any race condition.
1630 *
1631 * the global TLS map simply contains a bitmap of allocated keys, and
1632 * an array of destructors.
1633 *
1634 * each thread has a TLS area that is a simple array of TLSMAP_SIZE void*
1635 * pointers. the TLS area of the main thread is stack-allocated in
1636 * __libc_init_common, while the TLS area of other threads is placed at
1637 * the top of their stack in pthread_create.
1638 *
1639 * when pthread_key_create() is called, it finds the first free key in the
1640 * bitmap, then set it to 1, saving the destructor altogether
1641 *
1642 * when pthread_key_delete() is called. it will erase the key's bitmap bit
1643 * and its destructor, and will also clear the key data in the TLS area of
1644 * all created threads. As mandated by Posix, it is the responsability of
1645 * the caller of pthread_key_delete() to properly reclaim the objects that
1646 * were pointed to by these data fields (either before or after the call).
1647 *
1648 */
1649
1650/* TLS Map implementation
1651 */
1652
1653#define TLSMAP_START (TLS_SLOT_MAX_WELL_KNOWN+1)
1654#define TLSMAP_SIZE BIONIC_TLS_SLOTS
1655#define TLSMAP_BITS 32
1656#define TLSMAP_WORDS ((TLSMAP_SIZE+TLSMAP_BITS-1)/TLSMAP_BITS)
1657#define TLSMAP_WORD(m,k) (m)->map[(k)/TLSMAP_BITS]
1658#define TLSMAP_MASK(k) (1U << ((k)&(TLSMAP_BITS-1)))
1659
1660/* this macro is used to quickly check that a key belongs to a reasonable range */
1661#define TLSMAP_VALIDATE_KEY(key) \
1662 ((key) >= TLSMAP_START && (key) < TLSMAP_SIZE)
1663
1664/* the type of tls key destructor functions */
1665typedef void (*tls_dtor_t)(void*);
1666
1667typedef struct {
1668 int init; /* see comment in tlsmap_lock() */
1669 uint32_t map[TLSMAP_WORDS]; /* bitmap of allocated keys */
1670 tls_dtor_t dtors[TLSMAP_SIZE]; /* key destructors */
1671} tlsmap_t;
1672
1673static pthread_mutex_t _tlsmap_lock = PTHREAD_MUTEX_INITIALIZER;
1674static tlsmap_t _tlsmap;
1675
1676/* lock the global TLS map lock and return a handle to it */
1677static __inline__ tlsmap_t* tlsmap_lock(void)
1678{
1679 tlsmap_t* m = &_tlsmap;
1680
1681 pthread_mutex_lock(&_tlsmap_lock);
1682 /* we need to initialize the first entry of the 'map' array
1683 * with the value TLS_DEFAULT_ALLOC_MAP. doing it statically
1684 * when declaring _tlsmap is a bit awkward and is going to
1685 * produce warnings, so do it the first time we use the map
1686 * instead
1687 */
1688 if (__unlikely(!m->init)) {
1689 TLSMAP_WORD(m,0) = TLS_DEFAULT_ALLOC_MAP;
1690 m->init = 1;
1691 }
1692 return m;
1693}
1694
1695/* unlock the global TLS map */
1696static __inline__ void tlsmap_unlock(tlsmap_t* m)
1697{
1698 pthread_mutex_unlock(&_tlsmap_lock);
1699 (void)m; /* a good compiler is a happy compiler */
1700}
1701
1702/* test to see wether a key is allocated */
1703static __inline__ int tlsmap_test(tlsmap_t* m, int key)
1704{
1705 return (TLSMAP_WORD(m,key) & TLSMAP_MASK(key)) != 0;
1706}
1707
1708/* set the destructor and bit flag on a newly allocated key */
1709static __inline__ void tlsmap_set(tlsmap_t* m, int key, tls_dtor_t dtor)
1710{
1711 TLSMAP_WORD(m,key) |= TLSMAP_MASK(key);
1712 m->dtors[key] = dtor;
1713}
1714
1715/* clear the destructor and bit flag on an existing key */
1716static __inline__ void tlsmap_clear(tlsmap_t* m, int key)
1717{
1718 TLSMAP_WORD(m,key) &= ~TLSMAP_MASK(key);
1719 m->dtors[key] = NULL;
1720}
1721
1722/* allocate a new TLS key, return -1 if no room left */
1723static int tlsmap_alloc(tlsmap_t* m, tls_dtor_t dtor)
1724{
1725 int key;
1726
1727 for ( key = TLSMAP_START; key < TLSMAP_SIZE; key++ ) {
1728 if ( !tlsmap_test(m, key) ) {
1729 tlsmap_set(m, key, dtor);
1730 return key;
1731 }
1732 }
1733 return -1;
1734}
1735
1736
1737int pthread_key_create(pthread_key_t *key, void (*destructor_function)(void *))
1738{
1739 uint32_t err = ENOMEM;
1740 tlsmap_t* map = tlsmap_lock();
1741 int k = tlsmap_alloc(map, destructor_function);
1742
1743 if (k >= 0) {
1744 *key = k;
1745 err = 0;
1746 }
1747 tlsmap_unlock(map);
1748 return err;
1749}
1750
1751
1752/* This deletes a pthread_key_t. note that the standard mandates that this does
1753 * not call the destructor of non-NULL key values. Instead, it is the
1754 * responsability of the caller to properly dispose of the corresponding data
1755 * and resources, using any mean it finds suitable.
1756 *
1757 * On the other hand, this function will clear the corresponding key data
1758 * values in all known threads. this prevents later (invalid) calls to
1759 * pthread_getspecific() to receive invalid/stale values.
1760 */
1761int pthread_key_delete(pthread_key_t key)
1762{
1763 uint32_t err;
1764 pthread_internal_t* thr;
1765 tlsmap_t* map;
1766
1767 if (!TLSMAP_VALIDATE_KEY(key)) {
1768 return EINVAL;
1769 }
1770
1771 map = tlsmap_lock();
1772
1773 if (!tlsmap_test(map, key)) {
1774 err = EINVAL;
1775 goto err1;
1776 }
1777
1778 /* clear value in all threads */
1779 pthread_mutex_lock(&gThreadListLock);
1780 for ( thr = gThreadList; thr != NULL; thr = thr->next ) {
1781 /* avoid zombie threads with a negative 'join_count'. these are really
1782 * already dead and don't have a TLS area anymore.
1783 *
1784 * similarly, it is possible to have thr->tls == NULL for threads that
1785 * were just recently created through pthread_create() but whose
1786 * startup trampoline (__thread_entry) hasn't been run yet by the
1787 * scheduler. so check for this too.
1788 */
1789 if (thr->join_count < 0 || !thr->tls)
1790 continue;
1791
1792 thr->tls[key] = NULL;
1793 }
1794 tlsmap_clear(map, key);
1795
1796 pthread_mutex_unlock(&gThreadListLock);
1797 err = 0;
1798
1799err1:
1800 tlsmap_unlock(map);
1801 return err;
1802}
1803
1804
1805int pthread_setspecific(pthread_key_t key, const void *ptr)
1806{
1807 int err = EINVAL;
1808 tlsmap_t* map;
1809
1810 if (TLSMAP_VALIDATE_KEY(key)) {
1811 /* check that we're trying to set data for an allocated key */
1812 map = tlsmap_lock();
1813 if (tlsmap_test(map, key)) {
1814 ((uint32_t *)__get_tls())[key] = (uint32_t)ptr;
1815 err = 0;
1816 }
1817 tlsmap_unlock(map);
1818 }
1819 return err;
1820}
1821
1822void * pthread_getspecific(pthread_key_t key)
1823{
1824 if (!TLSMAP_VALIDATE_KEY(key)) {
1825 return NULL;
1826 }
1827
1828 /* for performance reason, we do not lock/unlock the global TLS map
1829 * to check that the key is properly allocated. if the key was not
1830 * allocated, the value read from the TLS should always be NULL
1831 * due to pthread_key_delete() clearing the values for all threads.
1832 */
1833 return (void *)(((unsigned *)__get_tls())[key]);
1834}
1835
1836/* Posix mandates that this be defined in <limits.h> but we don't have
1837 * it just yet.
1838 */
1839#ifndef PTHREAD_DESTRUCTOR_ITERATIONS
1840# define PTHREAD_DESTRUCTOR_ITERATIONS 4
1841#endif
1842
1843/* this function is called from pthread_exit() to remove all TLS key data
1844 * from this thread's TLS area. this must call the destructor of all keys
1845 * that have a non-NULL data value (and a non-NULL destructor).
1846 *
1847 * because destructors can do funky things like deleting/creating other
1848 * keys, we need to implement this in a loop
1849 */
1850static void pthread_key_clean_all(void)
1851{
1852 tlsmap_t* map;
1853 void** tls = (void**)__get_tls();
1854 int rounds = PTHREAD_DESTRUCTOR_ITERATIONS;
1855
1856 map = tlsmap_lock();
1857
1858 for (rounds = PTHREAD_DESTRUCTOR_ITERATIONS; rounds > 0; rounds--)
1859 {
1860 int kk, count = 0;
1861
1862 for (kk = TLSMAP_START; kk < TLSMAP_SIZE; kk++) {
1863 if ( tlsmap_test(map, kk) )
1864 {
1865 void* data = tls[kk];
1866 tls_dtor_t dtor = map->dtors[kk];
1867
1868 if (data != NULL && dtor != NULL)
1869 {
1870 /* we need to clear the key data now, this will prevent the
1871 * destructor (or a later one) from seeing the old value if
1872 * it calls pthread_getspecific() for some odd reason
1873 *
1874 * we do not do this if 'dtor == NULL' just in case another
1875 * destructor function might be responsible for manually
1876 * releasing the corresponding data.
1877 */
1878 tls[kk] = NULL;
1879
1880 /* because the destructor is free to call pthread_key_create
1881 * and/or pthread_key_delete, we need to temporarily unlock
1882 * the TLS map
1883 */
1884 tlsmap_unlock(map);
1885 (*dtor)(data);
1886 map = tlsmap_lock();
1887
1888 count += 1;
1889 }
1890 }
1891 }
1892
1893 /* if we didn't call any destructor, there is no need to check the
1894 * TLS data again
1895 */
1896 if (count == 0)
1897 break;
1898 }
1899 tlsmap_unlock(map);
1900}
1901
1902// man says this should be in <linux/unistd.h>, but it isn't
Jeff Brown10c8ce52011-11-18 15:17:07 -08001903extern int tgkill(int tgid, int tid, int sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001904
1905int pthread_kill(pthread_t tid, int sig)
1906{
1907 int ret;
1908 int old_errno = errno;
1909 pthread_internal_t * thread = (pthread_internal_t *)tid;
1910
Jeff Brown10c8ce52011-11-18 15:17:07 -08001911 ret = tgkill(getpid(), thread->kernel_id, sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001912 if (ret < 0) {
1913 ret = errno;
1914 errno = old_errno;
1915 }
1916
1917 return ret;
1918}
1919
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001920/* Despite the fact that our kernel headers define sigset_t explicitly
1921 * as a 32-bit integer, the kernel system call really expects a 64-bit
1922 * bitmap for the signal set, or more exactly an array of two-32-bit
1923 * values (see $KERNEL/arch/$ARCH/include/asm/signal.h for details).
1924 *
1925 * Unfortunately, we cannot fix the sigset_t definition without breaking
1926 * the C library ABI, so perform a little runtime translation here.
1927 */
1928typedef union {
1929 sigset_t bionic;
1930 uint32_t kernel[2];
1931} kernel_sigset_t;
1932
1933/* this is a private syscall stub */
1934extern int __rt_sigprocmask(int, const kernel_sigset_t *, kernel_sigset_t *, size_t);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001935
1936int pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
1937{
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001938 /* pthread_sigmask must return the error code, but the syscall
1939 * will set errno instead and return 0/-1
1940 */
1941 int ret, old_errno = errno;
1942
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001943 /* We must convert *set into a kernel_sigset_t */
1944 kernel_sigset_t in_set, *in_set_ptr;
1945 kernel_sigset_t out_set;
1946
Bruce Bearee4a21c82011-12-05 11:25:37 -08001947 in_set.kernel[0] = in_set.kernel[1] = 0;
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001948 out_set.kernel[0] = out_set.kernel[1] = 0;
1949
1950 /* 'in_set_ptr' is the second parameter to __rt_sigprocmask. It must be NULL
1951 * if 'set' is NULL to ensure correct semantics (which in this case would
1952 * be to ignore 'how' and return the current signal set into 'oset'.
David 'Digit' Turner5c8c00a2010-12-20 15:58:06 +01001953 */
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001954 if (set == NULL) {
1955 in_set_ptr = NULL;
1956 } else {
1957 in_set.bionic = *set;
1958 in_set_ptr = &in_set;
1959 }
1960
1961 ret = __rt_sigprocmask(how, in_set_ptr, &out_set, sizeof(kernel_sigset_t));
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001962 if (ret < 0)
1963 ret = errno;
1964
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001965 if (oset)
1966 *oset = out_set.bionic;
1967
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001968 errno = old_errno;
1969 return ret;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001970}
1971
1972
1973int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
1974{
1975 const int CLOCK_IDTYPE_BITS = 3;
1976 pthread_internal_t* thread = (pthread_internal_t*)tid;
1977
1978 if (!thread)
1979 return ESRCH;
1980
1981 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
1982 return 0;
1983}
1984
1985
1986/* NOTE: this implementation doesn't support a init function that throws a C++ exception
1987 * or calls fork()
1988 */
1989int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
1990{
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001991 static pthread_mutex_t once_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001992 volatile pthread_once_t* ocptr = once_control;
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001993 pthread_once_t value;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001994
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01001995 /* PTHREAD_ONCE_INIT is 0, we use the following bit flags
1996 *
1997 * bit 0 set -> initialization is under way
1998 * bit 1 set -> initialization is complete
1999 */
2000#define ONCE_INITIALIZING (1 << 0)
2001#define ONCE_COMPLETED (1 << 1)
2002
2003 /* First check if the once is already initialized. This will be the common
2004 * case and we want to make this as fast as possible. Note that this still
2005 * requires a load_acquire operation here to ensure that all the
2006 * stores performed by the initialization function are observable on
2007 * this CPU after we exit.
2008 */
2009 if (__likely((*ocptr & ONCE_COMPLETED) != 0)) {
2010 ANDROID_MEMBAR_FULL();
2011 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002012 }
David 'Digit' Turner6c6de442011-12-07 12:20:44 +01002013
2014 for (;;) {
2015 /* Try to atomically set the INITIALIZING flag.
2016 * This requires a cmpxchg loop, and we may need
2017 * to exit prematurely if we detect that
2018 * COMPLETED is now set.
2019 */
2020 int32_t oldval, newval;
2021
2022 do {
2023 oldval = *ocptr;
2024 if ((oldval & ONCE_COMPLETED) != 0)
2025 break;
2026
2027 newval = oldval | ONCE_INITIALIZING;
2028 } while (__bionic_cmpxchg(oldval, newval, ocptr) != 0);
2029
2030 if ((oldval & ONCE_COMPLETED) != 0) {
2031 /* We detected that COMPLETED was set while in our loop */
2032 ANDROID_MEMBAR_FULL();
2033 return 0;
2034 }
2035
2036 if ((oldval & ONCE_INITIALIZING) == 0) {
2037 /* We got there first, we can jump out of the loop to
2038 * handle the initialization */
2039 break;
2040 }
2041
2042 /* Another thread is running the initialization and hasn't completed
2043 * yet, so wait for it, then try again. */
2044 __futex_wait_ex(ocptr, 0, oldval, NULL);
2045 }
2046
2047 /* call the initialization function. */
2048 (*init_routine)();
2049
2050 /* Do a store_release indicating that initialization is complete */
2051 ANDROID_MEMBAR_FULL();
2052 *ocptr = ONCE_COMPLETED;
2053
2054 /* Wake up any waiters, if any */
2055 __futex_wake_ex(ocptr, 0, INT_MAX);
2056
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002057 return 0;
2058}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03002059
2060/* This value is not exported by kernel headers, so hardcode it here */
2061#define MAX_TASK_COMM_LEN 16
2062#define TASK_COMM_FMT "/proc/self/task/%u/comm"
2063
2064int pthread_setname_np(pthread_t thid, const char *thname)
2065{
2066 size_t thname_len;
2067 int saved_errno, ret;
2068
2069 if (thid == 0 || thname == NULL)
2070 return EINVAL;
2071
2072 thname_len = strlen(thname);
2073 if (thname_len >= MAX_TASK_COMM_LEN)
2074 return ERANGE;
2075
2076 saved_errno = errno;
2077 if (thid == pthread_self())
2078 {
2079 ret = prctl(PR_SET_NAME, (unsigned long)thname, 0, 0, 0) ? errno : 0;
2080 }
2081 else
2082 {
2083 /* Have to change another thread's name */
2084 pthread_internal_t *thread = (pthread_internal_t *)thid;
2085 char comm_name[sizeof(TASK_COMM_FMT) + 8];
2086 ssize_t n;
2087 int fd;
2088
2089 snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, (unsigned int)thread->kernel_id);
2090 fd = open(comm_name, O_RDWR);
2091 if (fd == -1)
2092 {
2093 ret = errno;
2094 goto exit;
2095 }
2096 n = TEMP_FAILURE_RETRY(write(fd, thname, thname_len));
2097 close(fd);
2098
2099 if (n < 0)
2100 ret = errno;
2101 else if ((size_t)n != thname_len)
2102 ret = EIO;
2103 else
2104 ret = 0;
2105 }
2106exit:
2107 errno = saved_errno;
2108 return ret;
2109}
Glenn Kastend53cae02011-07-11 15:41:28 -07002110
2111/* Return the kernel thread ID for a pthread.
2112 * This is only defined for implementations where pthread <-> kernel is 1:1, which this is.
2113 * Not the same as pthread_getthreadid_np, which is commonly defined to be opaque.
2114 * Internal, not an NDK API.
2115 */
2116
2117pid_t __pthread_gettid(pthread_t thid)
2118{
2119 pthread_internal_t* thread = (pthread_internal_t*)thid;
2120 return thread->kernel_id;
2121}