blob: 3435d219cbf385cebbca2e528000e015887fc3b6 [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)
84#define STACKBASE 0x10000000
85
86static uint8_t * gStackBase = (uint8_t *)STACKBASE;
87
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
255 stack = mmap((void *)gStackBase, size,
256 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 }
700 while ( __atomic_cmpxchg( flags, flags | PTHREAD_ATTR_FLAG_DETACHED,
701 (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
766#define MUTEX_OWNER(m) (((m)->value >> 16) & 0xffff)
767#define MUTEX_COUNTER(m) (((m)->value >> 2) & 0xfff)
768
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
928_normal_lock(pthread_mutex_t* mutex)
929{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700930 /* We need to preserve the shared flag during operations */
931 int shared = mutex->value & MUTEX_SHARED_MASK;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800932 /*
933 * The common case is an unlocked mutex, so we begin by trying to
934 * change the lock's state from 0 to 1. __atomic_cmpxchg() returns 0
935 * if it made the swap successfully. If the result is nonzero, this
936 * lock is already held by another thread.
937 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700938 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value ) != 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800939 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800940 * We want to go to sleep until the mutex is available, which
941 * requires promoting it to state 2. We need to swap in the new
942 * state value and then wait until somebody wakes us up.
943 *
944 * __atomic_swap() returns the previous value. We swap 2 in and
945 * see if we got zero back; if so, we have acquired the lock. If
946 * not, another thread still holds the lock and we wait again.
947 *
948 * The second argument to the __futex_wait() call is compared
949 * against the current value. If it doesn't match, __futex_wait()
950 * returns immediately (otherwise, it sleeps for a time specified
951 * by the third argument; 0 means sleep forever). This ensures
952 * that the mutex is in state 2 when we go to sleep on it, which
953 * guarantees a wake-up call.
954 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700955 while (__atomic_swap(shared|2, &mutex->value ) != (shared|0))
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -0700956 __futex_wait_ex(&mutex->value, shared, shared|2, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800957 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700958 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800959}
960
961/*
962 * Release a non-recursive mutex. The caller is responsible for determining
963 * that we are in fact the owner of this lock.
964 */
965static __inline__ void
966_normal_unlock(pthread_mutex_t* mutex)
967{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700968 ANDROID_MEMBAR_FULL();
969
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700970 /* We need to preserve the shared flag during operations */
971 int shared = mutex->value & MUTEX_SHARED_MASK;
972
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800973 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700974 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800975 * to release the lock. __atomic_dec() returns the previous value;
976 * if it wasn't 1 we have to do some additional work.
977 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700978 if (__atomic_dec(&mutex->value) != (shared|1)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800979 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800980 * Start by releasing the lock. The decrement changed it from
981 * "contended lock" to "uncontended lock", which means we still
982 * hold it, and anybody who tries to sneak in will push it back
983 * to state 2.
984 *
985 * Once we set it to zero the lock is up for grabs. We follow
986 * this with a __futex_wake() to ensure that one of the waiting
987 * threads has a chance to grab it.
988 *
989 * This doesn't cause a race with the swap/wait pair in
990 * _normal_lock(), because the __futex_wait() call there will
991 * return immediately if the mutex value isn't 2.
992 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700993 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800994
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800995 /*
996 * Wake up one waiting thread. We don't know which thread will be
997 * woken or when it'll start executing -- futexes make no guarantees
998 * here. There may not even be a thread waiting.
999 *
1000 * The newly-woken thread will replace the 0 we just set above
1001 * with 2, which means that when it eventually releases the mutex
1002 * it will also call FUTEX_WAKE. This results in one extra wake
1003 * call whenever a lock is contended, but lets us avoid forgetting
1004 * anyone without requiring us to track the number of sleepers.
1005 *
1006 * It's possible for another thread to sneak in and grab the lock
1007 * between the zero assignment above and the wake call below. If
1008 * the new thread is "slow" and holds the lock for a while, we'll
1009 * wake up a sleeper, which will swap in a 2 and then go back to
1010 * sleep since the lock is still held. If the new thread is "fast",
1011 * running to completion before we call wake, the thread we
1012 * eventually wake will find an unlocked mutex and will execute.
1013 * Either way we have correct behavior and nobody is orphaned on
1014 * the wait queue.
1015 */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001016 __futex_wake_ex(&mutex->value, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001017 }
1018}
1019
1020static pthread_mutex_t __recursive_lock = PTHREAD_MUTEX_INITIALIZER;
1021
1022static void
1023_recursive_lock(void)
1024{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001025 _normal_lock(&__recursive_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001026}
1027
1028static void
1029_recursive_unlock(void)
1030{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001031 _normal_unlock(&__recursive_lock );
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001032}
1033
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001034int pthread_mutex_lock(pthread_mutex_t *mutex)
1035{
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001036 int mtype, tid, new_lock_type, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001037
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001038 if (__unlikely(mutex == NULL))
1039 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001040
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001041 mtype = (mutex->value & MUTEX_TYPE_MASK);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001042 shared = (mutex->value & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001043
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001044 /* Handle normal case first */
1045 if ( __likely(mtype == MUTEX_TYPE_NORMAL) ) {
1046 _normal_lock(mutex);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001047 return 0;
1048 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001049
1050 /* Do we already own this recursive or error-check mutex ? */
1051 tid = __get_thread()->kernel_id;
1052 if ( tid == MUTEX_OWNER(mutex) )
1053 {
1054 int oldv, counter;
1055
1056 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1057 /* trying to re-lock a mutex we already acquired */
1058 return EDEADLK;
1059 }
1060 /*
1061 * We own the mutex, but other threads are able to change
1062 * the contents (e.g. promoting it to "contended"), so we
1063 * need to hold the global lock.
1064 */
1065 _recursive_lock();
1066 oldv = mutex->value;
1067 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1068 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1069 _recursive_unlock();
1070 return 0;
1071 }
1072
1073 /* We don't own the mutex, so try to get it.
1074 *
1075 * First, we try to change its state from 0 to 1, if this
1076 * doesn't work, try to change it to state 2.
1077 */
1078 new_lock_type = 1;
1079
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001080 /* compute futex wait opcode and restore shared flag in mtype */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001081 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001082
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001083 for (;;) {
1084 int oldv;
1085
1086 _recursive_lock();
1087 oldv = mutex->value;
1088 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1089 mutex->value = ((tid << 16) | mtype | new_lock_type);
1090 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1091 oldv ^= 3;
1092 mutex->value = oldv;
1093 }
1094 _recursive_unlock();
1095
1096 if (oldv == mtype)
1097 break;
1098
1099 /*
1100 * The lock was held, possibly contended by others. From
1101 * now on, if we manage to acquire the lock, we have to
1102 * assume that others are still contending for it so that
1103 * we'll wake them when we unlock it.
1104 */
1105 new_lock_type = 2;
1106
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001107 __futex_wait_ex(&mutex->value, shared, oldv, NULL);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001108 }
1109 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001110}
1111
1112
1113int pthread_mutex_unlock(pthread_mutex_t *mutex)
1114{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001115 int mtype, tid, oldv, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001116
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001117 if (__unlikely(mutex == NULL))
1118 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001119
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001120 mtype = (mutex->value & MUTEX_TYPE_MASK);
1121 shared = (mutex->value & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001122
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001123 /* Handle common case first */
1124 if (__likely(mtype == MUTEX_TYPE_NORMAL)) {
1125 _normal_unlock(mutex);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001126 return 0;
1127 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001128
1129 /* Do we already own this recursive or error-check mutex ? */
1130 tid = __get_thread()->kernel_id;
1131 if ( tid != MUTEX_OWNER(mutex) )
1132 return EPERM;
1133
1134 /* We do, decrement counter or release the mutex if it is 0 */
1135 _recursive_lock();
1136 oldv = mutex->value;
1137 if (oldv & MUTEX_COUNTER_MASK) {
1138 mutex->value = oldv - (1 << MUTEX_COUNTER_SHIFT);
1139 oldv = 0;
1140 } else {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001141 mutex->value = shared | mtype;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001142 }
1143 _recursive_unlock();
1144
1145 /* Wake one waiting thread, if any */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001146 if ((oldv & 3) == 2) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001147 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001148 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001149 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001150}
1151
1152
1153int pthread_mutex_trylock(pthread_mutex_t *mutex)
1154{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001155 int mtype, tid, oldv, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001156
1157 if (__unlikely(mutex == NULL))
1158 return EINVAL;
1159
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001160 mtype = (mutex->value & MUTEX_TYPE_MASK);
1161 shared = (mutex->value & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001162
1163 /* Handle common case first */
1164 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001165 {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001166 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
1167 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001168 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001169 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001170
1171 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001172 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001173
1174 /* Do we already own this recursive or error-check mutex ? */
1175 tid = __get_thread()->kernel_id;
1176 if ( tid == MUTEX_OWNER(mutex) )
1177 {
1178 int counter;
1179
1180 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1181 /* already locked by ourselves */
1182 return EDEADLK;
1183 }
1184
1185 _recursive_lock();
1186 oldv = mutex->value;
1187 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1188 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1189 _recursive_unlock();
1190 return 0;
1191 }
1192
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001193 /* Restore sharing bit in mtype */
1194 mtype |= shared;
1195
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001196 /* Try to lock it, just once. */
1197 _recursive_lock();
1198 oldv = mutex->value;
1199 if (oldv == mtype) /* uncontended released lock => state 1 */
1200 mutex->value = ((tid << 16) | mtype | 1);
1201 _recursive_unlock();
1202
1203 if (oldv != mtype)
1204 return EBUSY;
1205
1206 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001207}
1208
1209
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001210/* initialize 'ts' with the difference between 'abstime' and the current time
1211 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
1212 */
1213static int
1214__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
1215{
1216 clock_gettime(clock, ts);
1217 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
1218 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
1219 if (ts->tv_nsec < 0) {
1220 ts->tv_sec--;
1221 ts->tv_nsec += 1000000000;
1222 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001223 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001224 return -1;
1225
1226 return 0;
1227}
1228
1229/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1230 * milliseconds.
1231 */
1232static void
1233__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1234{
1235 clock_gettime(clock, abstime);
1236 abstime->tv_sec += msecs/1000;
1237 abstime->tv_nsec += (msecs%1000)*1000000;
1238 if (abstime->tv_nsec >= 1000000000) {
1239 abstime->tv_sec++;
1240 abstime->tv_nsec -= 1000000000;
1241 }
1242}
1243
1244int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1245{
1246 clockid_t clock = CLOCK_MONOTONIC;
1247 struct timespec abstime;
1248 struct timespec ts;
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001249 int mtype, tid, oldv, new_lock_type, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001250
1251 /* compute absolute expiration time */
1252 __timespec_to_relative_msec(&abstime, msecs, clock);
1253
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001254 if (__unlikely(mutex == NULL))
1255 return EINVAL;
1256
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001257 mtype = (mutex->value & MUTEX_TYPE_MASK);
1258 shared = (mutex->value & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001259
1260 /* Handle common case first */
1261 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001262 {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001263 /* fast path for uncontended lock */
1264 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
1265 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001266 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001267 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001268
1269 /* loop while needed */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001270 while (__atomic_swap(shared|2, &mutex->value) != (shared|0)) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001271 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1272 return EBUSY;
1273
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001274 __futex_wait_ex(&mutex->value, shared, shared|2, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001275 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001276 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001277 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001278 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001279
1280 /* Do we already own this recursive or error-check mutex ? */
1281 tid = __get_thread()->kernel_id;
1282 if ( tid == MUTEX_OWNER(mutex) )
1283 {
1284 int oldv, counter;
1285
1286 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1287 /* already locked by ourselves */
1288 return EDEADLK;
1289 }
1290
1291 _recursive_lock();
1292 oldv = mutex->value;
1293 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1294 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1295 _recursive_unlock();
1296 return 0;
1297 }
1298
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;
1439 if (__atomic_cmpxchg(oldval, newval, &cond->value) == 0)
1440 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
1847extern int tkill(int tid, int sig);
1848
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
1855 ret = tkill(thread->kernel_id, sig);
1856 if (ret < 0) {
1857 ret = errno;
1858 errno = old_errno;
1859 }
1860
1861 return ret;
1862}
1863
Bruce Bearee4a21c82011-12-05 11:25:37 -08001864/* 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
Bruce Bearee4a21c82011-12-05 11:25:37 -08001887 /* 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
1891 in_set.kernel[0] = in_set.kernel[1] = 0;
1892 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'.
1897 */
1898 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
Bruce Bearee4a21c82011-12-05 11:25:37 -08001909 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;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001937
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001938 pthread_once_t tmp = *ocptr;
1939 ANDROID_MEMBAR_FULL();
1940 if (tmp == PTHREAD_ONCE_INIT) {
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001941 pthread_mutex_lock( &once_lock );
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001942 if (*ocptr == PTHREAD_ONCE_INIT) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001943 (*init_routine)();
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001944 ANDROID_MEMBAR_FULL();
1945 *ocptr = ~PTHREAD_ONCE_INIT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001946 }
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001947 pthread_mutex_unlock( &once_lock );
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001948 }
1949 return 0;
1950}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03001951
1952/* This value is not exported by kernel headers, so hardcode it here */
1953#define MAX_TASK_COMM_LEN 16
1954#define TASK_COMM_FMT "/proc/self/task/%u/comm"
1955
1956int pthread_setname_np(pthread_t thid, const char *thname)
1957{
1958 size_t thname_len;
1959 int saved_errno, ret;
1960
1961 if (thid == 0 || thname == NULL)
1962 return EINVAL;
1963
1964 thname_len = strlen(thname);
1965 if (thname_len >= MAX_TASK_COMM_LEN)
1966 return ERANGE;
1967
1968 saved_errno = errno;
1969 if (thid == pthread_self())
1970 {
1971 ret = prctl(PR_SET_NAME, (unsigned long)thname, 0, 0, 0) ? errno : 0;
1972 }
1973 else
1974 {
1975 /* Have to change another thread's name */
1976 pthread_internal_t *thread = (pthread_internal_t *)thid;
1977 char comm_name[sizeof(TASK_COMM_FMT) + 8];
1978 ssize_t n;
1979 int fd;
1980
1981 snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, (unsigned int)thread->kernel_id);
1982 fd = open(comm_name, O_RDWR);
1983 if (fd == -1)
1984 {
1985 ret = errno;
1986 goto exit;
1987 }
1988 n = TEMP_FAILURE_RETRY(write(fd, thname, thname_len));
1989 close(fd);
1990
1991 if (n < 0)
1992 ret = errno;
1993 else if ((size_t)n != thname_len)
1994 ret = EIO;
1995 else
1996 ret = 0;
1997 }
1998exit:
1999 errno = saved_errno;
2000 return ret;
2001}
Glenn Kastend53cae02011-07-11 15:41:28 -07002002
2003/* Return the kernel thread ID for a pthread.
2004 * This is only defined for implementations where pthread <-> kernel is 1:1, which this is.
2005 * Not the same as pthread_getthreadid_np, which is commonly defined to be opaque.
2006 * Internal, not an NDK API.
2007 */
2008
2009pid_t __pthread_gettid(pthread_t thid)
2010{
2011 pthread_internal_t* thread = (pthread_internal_t*)thid;
2012 return thread->kernel_id;
2013}