blob: 6c413767abe7adad2c4c814383d50d23656f7645 [file] [log] [blame]
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28#include <sys/types.h>
29#include <unistd.h>
30#include <signal.h>
31#include <stdint.h>
32#include <stdio.h>
33#include <stdlib.h>
34#include <errno.h>
35#include <sys/atomics.h>
36#include <bionic_tls.h>
37#include <sys/mman.h>
38#include <pthread.h>
39#include <time.h>
40#include "pthread_internal.h"
41#include "thread_private.h"
42#include <limits.h>
43#include <memory.h>
44#include <assert.h>
45#include <malloc.h>
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -070046#include <bionic_futex.h>
David 'Digit' Turner6c8a2f22010-06-10 23:34:24 -070047#include <bionic_atomic_inline.h>
André Goddard Rosa78c1c042010-05-19 23:17:16 -030048#include <sys/prctl.h>
49#include <sys/stat.h>
50#include <fcntl.h>
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -070051#include <stdio.h>
Glenn Kastend53cae02011-07-11 15:41:28 -070052#include <bionic_pthread.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080053
54extern int __pthread_clone(int (*fn)(void*), void *child_stack, int flags, void *arg);
55extern void _exit_with_stack_teardown(void * stackBase, int stackSize, int retCode);
56extern void _exit_thread(int retCode);
57extern int __set_errno(int);
58
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -070059int __futex_wake_ex(volatile void *ftx, int pshared, int val)
60{
61 return __futex_syscall3(ftx, pshared ? FUTEX_WAKE : FUTEX_WAKE_PRIVATE, val);
62}
63
64int __futex_wait_ex(volatile void *ftx, int pshared, int val, const struct timespec *timeout)
65{
66 return __futex_syscall4(ftx, pshared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE, val, timeout);
67}
68
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -070069#define __likely(cond) __builtin_expect(!!(cond), 1)
70#define __unlikely(cond) __builtin_expect(!!(cond), 0)
71
Bruce Beare8e551a62011-03-28 09:47:35 -070072#ifdef __i386__
73#define ATTRIBUTES __attribute__((noinline)) __attribute__((fastcall))
74#else
75#define ATTRIBUTES __attribute__((noinline))
76#endif
77
78void ATTRIBUTES _thread_created_hook(pid_t thread_id);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080079
80#define PTHREAD_ATTR_FLAG_DETACHED 0x00000001
81#define PTHREAD_ATTR_FLAG_USER_STACK 0x00000002
82
83#define DEFAULT_STACKSIZE (1024 * 1024)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080084
85static pthread_mutex_t mmap_lock = PTHREAD_MUTEX_INITIALIZER;
86
87
88static const pthread_attr_t gDefaultPthreadAttr = {
89 .flags = 0,
90 .stack_base = NULL,
91 .stack_size = DEFAULT_STACKSIZE,
92 .guard_size = PAGE_SIZE,
93 .sched_policy = SCHED_NORMAL,
94 .sched_priority = 0
95};
96
97#define INIT_THREADS 1
98
99static pthread_internal_t* gThreadList = NULL;
100static pthread_mutex_t gThreadListLock = PTHREAD_MUTEX_INITIALIZER;
101static pthread_mutex_t gDebuggerNotificationLock = PTHREAD_MUTEX_INITIALIZER;
102
103
104/* we simply malloc/free the internal pthread_internal_t structures. we may
105 * want to use a different allocation scheme in the future, but this one should
106 * be largely enough
107 */
108static pthread_internal_t*
109_pthread_internal_alloc(void)
110{
111 pthread_internal_t* thread;
112
113 thread = calloc( sizeof(*thread), 1 );
114 if (thread)
115 thread->intern = 1;
116
117 return thread;
118}
119
120static void
121_pthread_internal_free( pthread_internal_t* thread )
122{
123 if (thread && thread->intern) {
124 thread->intern = 0; /* just in case */
125 free (thread);
126 }
127}
128
129
130static void
131_pthread_internal_remove_locked( pthread_internal_t* thread )
132{
133 thread->next->pref = thread->pref;
134 thread->pref[0] = thread->next;
135}
136
137static void
138_pthread_internal_remove( pthread_internal_t* thread )
139{
140 pthread_mutex_lock(&gThreadListLock);
141 _pthread_internal_remove_locked(thread);
142 pthread_mutex_unlock(&gThreadListLock);
143}
144
145static void
146_pthread_internal_add( pthread_internal_t* thread )
147{
148 pthread_mutex_lock(&gThreadListLock);
149 thread->pref = &gThreadList;
150 thread->next = thread->pref[0];
151 if (thread->next)
152 thread->next->pref = &thread->next;
153 thread->pref[0] = thread;
154 pthread_mutex_unlock(&gThreadListLock);
155}
156
157pthread_internal_t*
158__get_thread(void)
159{
160 void** tls = (void**)__get_tls();
161
162 return (pthread_internal_t*) tls[TLS_SLOT_THREAD_ID];
163}
164
165
166void*
167__get_stack_base(int *p_stack_size)
168{
169 pthread_internal_t* thread = __get_thread();
170
171 *p_stack_size = thread->attr.stack_size;
172 return thread->attr.stack_base;
173}
174
175
176void __init_tls(void** tls, void* thread)
177{
178 int nn;
179
180 ((pthread_internal_t*)thread)->tls = tls;
181
182 // slot 0 must point to the tls area, this is required by the implementation
183 // of the x86 Linux kernel thread-local-storage
184 tls[TLS_SLOT_SELF] = (void*)tls;
185 tls[TLS_SLOT_THREAD_ID] = thread;
186 for (nn = TLS_SLOT_ERRNO; nn < BIONIC_TLS_SLOTS; nn++)
187 tls[nn] = 0;
188
189 __set_tls( (void*)tls );
190}
191
192
193/*
194 * This trampoline is called from the assembly clone() function
195 */
196void __thread_entry(int (*func)(void*), void *arg, void **tls)
197{
198 int retValue;
199 pthread_internal_t * thrInfo;
200
201 // Wait for our creating thread to release us. This lets it have time to
202 // notify gdb about this thread before it starts doing anything.
Andy McFaddene2ac8982010-09-02 13:34:53 -0700203 //
204 // This also provides the memory barrier needed to ensure that all memory
205 // accesses previously made by the creating thread are visible to us.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800206 pthread_mutex_t * start_mutex = (pthread_mutex_t *)&tls[TLS_SLOT_SELF];
207 pthread_mutex_lock(start_mutex);
208 pthread_mutex_destroy(start_mutex);
209
210 thrInfo = (pthread_internal_t *) tls[TLS_SLOT_THREAD_ID];
211
212 __init_tls( tls, thrInfo );
213
214 pthread_exit( (void*)func(arg) );
215}
216
217void _init_thread(pthread_internal_t * thread, pid_t kernel_id, pthread_attr_t * attr, void * stack_base)
218{
219 if (attr == NULL) {
220 thread->attr = gDefaultPthreadAttr;
221 } else {
222 thread->attr = *attr;
223 }
224 thread->attr.stack_base = stack_base;
225 thread->kernel_id = kernel_id;
226
227 // set the scheduling policy/priority of the thread
228 if (thread->attr.sched_policy != SCHED_NORMAL) {
229 struct sched_param param;
230 param.sched_priority = thread->attr.sched_priority;
231 sched_setscheduler(kernel_id, thread->attr.sched_policy, &param);
232 }
233
234 pthread_cond_init(&thread->join_cond, NULL);
235 thread->join_count = 0;
236
237 thread->cleanup_stack = NULL;
238
239 _pthread_internal_add(thread);
240}
241
242
243/* XXX stacks not reclaimed if thread spawn fails */
244/* XXX stacks address spaces should be reused if available again */
245
246static void *mkstack(size_t size, size_t guard_size)
247{
248 void * stack;
249
250 pthread_mutex_lock(&mmap_lock);
251
Nick Kralevich5f64df42011-11-17 12:58:20 -0800252 stack = mmap(NULL, size,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800253 PROT_READ | PROT_WRITE,
254 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
255 -1, 0);
256
257 if(stack == MAP_FAILED) {
258 stack = NULL;
259 goto done;
260 }
261
262 if(mprotect(stack, guard_size, PROT_NONE)){
263 munmap(stack, size);
264 stack = NULL;
265 goto done;
266 }
267
268done:
269 pthread_mutex_unlock(&mmap_lock);
270 return stack;
271}
272
273/*
Andy McFaddene2ac8982010-09-02 13:34:53 -0700274 * Create a new thread. The thread's stack is laid out like so:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800275 *
276 * +---------------------------+
277 * | pthread_internal_t |
278 * +---------------------------+
279 * | |
280 * | TLS area |
281 * | |
282 * +---------------------------+
283 * | |
284 * . .
285 * . stack area .
286 * . .
287 * | |
288 * +---------------------------+
289 * | guard page |
290 * +---------------------------+
291 *
292 * note that TLS[0] must be a pointer to itself, this is required
293 * by the thread-local storage implementation of the x86 Linux
294 * kernel, where the TLS pointer is read by reading fs:[0]
295 */
296int pthread_create(pthread_t *thread_out, pthread_attr_t const * attr,
297 void *(*start_routine)(void *), void * arg)
298{
299 char* stack;
300 void** tls;
301 int tid;
302 pthread_mutex_t * start_mutex;
303 pthread_internal_t * thread;
304 int madestack = 0;
305 int old_errno = errno;
306
307 /* this will inform the rest of the C library that at least one thread
308 * was created. this will enforce certain functions to acquire/release
309 * locks (e.g. atexit()) to protect shared global structures.
310 *
311 * this works because pthread_create() is not called by the C library
312 * initialization routine that sets up the main thread's data structures.
313 */
314 __isthreaded = 1;
315
316 thread = _pthread_internal_alloc();
317 if (thread == NULL)
318 return ENOMEM;
319
320 if (attr == NULL) {
321 attr = &gDefaultPthreadAttr;
322 }
323
324 // make sure the stack is PAGE_SIZE aligned
325 size_t stackSize = (attr->stack_size +
326 (PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
327
328 if (!attr->stack_base) {
329 stack = mkstack(stackSize, attr->guard_size);
330 if(stack == NULL) {
331 _pthread_internal_free(thread);
332 return ENOMEM;
333 }
334 madestack = 1;
335 } else {
336 stack = attr->stack_base;
337 }
338
339 // Make room for TLS
340 tls = (void**)(stack + stackSize - BIONIC_TLS_SLOTS*sizeof(void*));
341
342 // Create a mutex for the thread in TLS_SLOT_SELF to wait on once it starts so we can keep
343 // it from doing anything until after we notify the debugger about it
Andy McFaddene2ac8982010-09-02 13:34:53 -0700344 //
345 // This also provides the memory barrier we need to ensure that all
346 // memory accesses previously performed by this thread are visible to
347 // the new thread.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800348 start_mutex = (pthread_mutex_t *) &tls[TLS_SLOT_SELF];
349 pthread_mutex_init(start_mutex, NULL);
350 pthread_mutex_lock(start_mutex);
351
352 tls[TLS_SLOT_THREAD_ID] = thread;
353
354 tid = __pthread_clone((int(*)(void*))start_routine, tls,
355 CLONE_FILES | CLONE_FS | CLONE_VM | CLONE_SIGHAND
356 | CLONE_THREAD | CLONE_SYSVSEM | CLONE_DETACHED,
357 arg);
358
359 if(tid < 0) {
360 int result;
361 if (madestack)
362 munmap(stack, stackSize);
363 _pthread_internal_free(thread);
364 result = errno;
365 errno = old_errno;
366 return result;
367 }
368
369 _init_thread(thread, tid, (pthread_attr_t*)attr, stack);
370
371 if (!madestack)
372 thread->attr.flags |= PTHREAD_ATTR_FLAG_USER_STACK;
373
374 // Notify any debuggers about the new thread
375 pthread_mutex_lock(&gDebuggerNotificationLock);
376 _thread_created_hook(tid);
377 pthread_mutex_unlock(&gDebuggerNotificationLock);
378
379 // Let the thread do it's thing
380 pthread_mutex_unlock(start_mutex);
381
382 *thread_out = (pthread_t)thread;
383 return 0;
384}
385
386
387int pthread_attr_init(pthread_attr_t * attr)
388{
389 *attr = gDefaultPthreadAttr;
390 return 0;
391}
392
393int pthread_attr_destroy(pthread_attr_t * attr)
394{
395 memset(attr, 0x42, sizeof(pthread_attr_t));
396 return 0;
397}
398
399int pthread_attr_setdetachstate(pthread_attr_t * attr, int state)
400{
401 if (state == PTHREAD_CREATE_DETACHED) {
402 attr->flags |= PTHREAD_ATTR_FLAG_DETACHED;
403 } else if (state == PTHREAD_CREATE_JOINABLE) {
404 attr->flags &= ~PTHREAD_ATTR_FLAG_DETACHED;
405 } else {
406 return EINVAL;
407 }
408 return 0;
409}
410
411int pthread_attr_getdetachstate(pthread_attr_t const * attr, int * state)
412{
413 *state = (attr->flags & PTHREAD_ATTR_FLAG_DETACHED)
414 ? PTHREAD_CREATE_DETACHED
415 : PTHREAD_CREATE_JOINABLE;
416 return 0;
417}
418
419int pthread_attr_setschedpolicy(pthread_attr_t * attr, int policy)
420{
421 attr->sched_policy = policy;
422 return 0;
423}
424
425int pthread_attr_getschedpolicy(pthread_attr_t const * attr, int * policy)
426{
427 *policy = attr->sched_policy;
428 return 0;
429}
430
431int pthread_attr_setschedparam(pthread_attr_t * attr, struct sched_param const * param)
432{
433 attr->sched_priority = param->sched_priority;
434 return 0;
435}
436
437int pthread_attr_getschedparam(pthread_attr_t const * attr, struct sched_param * param)
438{
439 param->sched_priority = attr->sched_priority;
440 return 0;
441}
442
443int pthread_attr_setstacksize(pthread_attr_t * attr, size_t stack_size)
444{
445 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
446 return EINVAL;
447 }
448 attr->stack_size = stack_size;
449 return 0;
450}
451
452int pthread_attr_getstacksize(pthread_attr_t const * attr, size_t * stack_size)
453{
454 *stack_size = attr->stack_size;
455 return 0;
456}
457
458int pthread_attr_setstackaddr(pthread_attr_t * attr, void * stack_addr)
459{
460#if 1
461 // It's not clear if this is setting the top or bottom of the stack, so don't handle it for now.
462 return ENOSYS;
463#else
464 if ((uint32_t)stack_addr & (PAGE_SIZE - 1)) {
465 return EINVAL;
466 }
467 attr->stack_base = stack_addr;
468 return 0;
469#endif
470}
471
472int pthread_attr_getstackaddr(pthread_attr_t const * attr, void ** stack_addr)
473{
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700474 *stack_addr = (char*)attr->stack_base + attr->stack_size;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800475 return 0;
476}
477
478int pthread_attr_setstack(pthread_attr_t * attr, void * stack_base, size_t stack_size)
479{
480 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
481 return EINVAL;
482 }
483 if ((uint32_t)stack_base & (PAGE_SIZE - 1)) {
484 return EINVAL;
485 }
486 attr->stack_base = stack_base;
487 attr->stack_size = stack_size;
488 return 0;
489}
490
491int pthread_attr_getstack(pthread_attr_t const * attr, void ** stack_base, size_t * stack_size)
492{
493 *stack_base = attr->stack_base;
494 *stack_size = attr->stack_size;
495 return 0;
496}
497
498int pthread_attr_setguardsize(pthread_attr_t * attr, size_t guard_size)
499{
500 if (guard_size & (PAGE_SIZE - 1) || guard_size < PAGE_SIZE) {
501 return EINVAL;
502 }
503
504 attr->guard_size = guard_size;
505 return 0;
506}
507
508int pthread_attr_getguardsize(pthread_attr_t const * attr, size_t * guard_size)
509{
510 *guard_size = attr->guard_size;
511 return 0;
512}
513
514int pthread_getattr_np(pthread_t thid, pthread_attr_t * attr)
515{
516 pthread_internal_t * thread = (pthread_internal_t *)thid;
517 *attr = thread->attr;
518 return 0;
519}
520
521int pthread_attr_setscope(pthread_attr_t *attr, int scope)
522{
523 if (scope == PTHREAD_SCOPE_SYSTEM)
524 return 0;
525 if (scope == PTHREAD_SCOPE_PROCESS)
526 return ENOTSUP;
527
528 return EINVAL;
529}
530
531int pthread_attr_getscope(pthread_attr_t const *attr)
532{
533 return PTHREAD_SCOPE_SYSTEM;
534}
535
536
537/* CAVEAT: our implementation of pthread_cleanup_push/pop doesn't support C++ exceptions
538 * and thread cancelation
539 */
540
541void __pthread_cleanup_push( __pthread_cleanup_t* c,
542 __pthread_cleanup_func_t routine,
543 void* arg )
544{
545 pthread_internal_t* thread = __get_thread();
546
547 c->__cleanup_routine = routine;
548 c->__cleanup_arg = arg;
549 c->__cleanup_prev = thread->cleanup_stack;
550 thread->cleanup_stack = c;
551}
552
553void __pthread_cleanup_pop( __pthread_cleanup_t* c, int execute )
554{
555 pthread_internal_t* thread = __get_thread();
556
557 thread->cleanup_stack = c->__cleanup_prev;
558 if (execute)
559 c->__cleanup_routine(c->__cleanup_arg);
560}
561
562/* used by pthread_exit() to clean all TLS keys of the current thread */
563static void pthread_key_clean_all(void);
564
565void pthread_exit(void * retval)
566{
567 pthread_internal_t* thread = __get_thread();
568 void* stack_base = thread->attr.stack_base;
569 int stack_size = thread->attr.stack_size;
570 int user_stack = (thread->attr.flags & PTHREAD_ATTR_FLAG_USER_STACK) != 0;
Jack Rene480fc82011-09-21 12:44:11 +0200571 sigset_t mask;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800572
573 // call the cleanup handlers first
574 while (thread->cleanup_stack) {
575 __pthread_cleanup_t* c = thread->cleanup_stack;
576 thread->cleanup_stack = c->__cleanup_prev;
577 c->__cleanup_routine(c->__cleanup_arg);
578 }
579
580 // call the TLS destructors, it is important to do that before removing this
581 // thread from the global list. this will ensure that if someone else deletes
582 // a TLS key, the corresponding value will be set to NULL in this thread's TLS
583 // space (see pthread_key_delete)
584 pthread_key_clean_all();
585
586 // if the thread is detached, destroy the pthread_internal_t
587 // otherwise, keep it in memory and signal any joiners
588 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
589 _pthread_internal_remove(thread);
590 _pthread_internal_free(thread);
591 } else {
592 /* the join_count field is used to store the number of threads waiting for
593 * the termination of this thread with pthread_join(),
594 *
595 * if it is positive we need to signal the waiters, and we do not touch
596 * the count (it will be decremented by the waiters, the last one will
597 * also remove/free the thread structure
598 *
599 * if it is zero, we set the count value to -1 to indicate that the
600 * thread is in 'zombie' state: it has stopped executing, and its stack
601 * is gone (as well as its TLS area). when another thread calls pthread_join()
602 * on it, it will immediately free the thread and return.
603 */
604 pthread_mutex_lock(&gThreadListLock);
605 thread->return_value = retval;
606 if (thread->join_count > 0) {
607 pthread_cond_broadcast(&thread->join_cond);
608 } else {
609 thread->join_count = -1; /* zombie thread */
610 }
611 pthread_mutex_unlock(&gThreadListLock);
612 }
613
Jack Rene480fc82011-09-21 12:44:11 +0200614 sigfillset(&mask);
615 sigdelset(&mask, SIGSEGV);
616 (void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *)NULL);
617
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800618 // destroy the thread stack
619 if (user_stack)
620 _exit_thread((int)retval);
621 else
622 _exit_with_stack_teardown(stack_base, stack_size, (int)retval);
623}
624
625int pthread_join(pthread_t thid, void ** ret_val)
626{
627 pthread_internal_t* thread = (pthread_internal_t*)thid;
628 int count;
629
630 // check that the thread still exists and is not detached
631 pthread_mutex_lock(&gThreadListLock);
632
633 for (thread = gThreadList; thread != NULL; thread = thread->next)
634 if (thread == (pthread_internal_t*)thid)
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200635 goto FoundIt;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800636
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200637 pthread_mutex_unlock(&gThreadListLock);
638 return ESRCH;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800639
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200640FoundIt:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800641 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
642 pthread_mutex_unlock(&gThreadListLock);
643 return EINVAL;
644 }
645
646 /* wait for thread death when needed
647 *
648 * if the 'join_count' is negative, this is a 'zombie' thread that
649 * is already dead and without stack/TLS
650 *
651 * otherwise, we need to increment 'join-count' and wait to be signaled
652 */
653 count = thread->join_count;
654 if (count >= 0) {
655 thread->join_count += 1;
656 pthread_cond_wait( &thread->join_cond, &gThreadListLock );
657 count = --thread->join_count;
658 }
659 if (ret_val)
660 *ret_val = thread->return_value;
661
662 /* remove thread descriptor when we're the last joiner or when the
663 * thread was already a zombie.
664 */
665 if (count <= 0) {
666 _pthread_internal_remove_locked(thread);
667 _pthread_internal_free(thread);
668 }
669 pthread_mutex_unlock(&gThreadListLock);
670 return 0;
671}
672
673int pthread_detach( pthread_t thid )
674{
675 pthread_internal_t* thread;
676 int result = 0;
677 int flags;
678
679 pthread_mutex_lock(&gThreadListLock);
680 for (thread = gThreadList; thread != NULL; thread = thread->next)
681 if (thread == (pthread_internal_t*)thid)
682 goto FoundIt;
683
684 result = ESRCH;
685 goto Exit;
686
687FoundIt:
688 do {
689 flags = thread->attr.flags;
690
691 if ( flags & PTHREAD_ATTR_FLAG_DETACHED ) {
692 /* thread is not joinable ! */
693 result = EINVAL;
694 goto Exit;
695 }
696 }
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100697 while ( __bionic_cmpxchg( flags, flags | PTHREAD_ATTR_FLAG_DETACHED,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800698 (volatile int*)&thread->attr.flags ) != 0 );
699Exit:
700 pthread_mutex_unlock(&gThreadListLock);
701 return result;
702}
703
704pthread_t pthread_self(void)
705{
706 return (pthread_t)__get_thread();
707}
708
709int pthread_equal(pthread_t one, pthread_t two)
710{
711 return (one == two ? 1 : 0);
712}
713
714int pthread_getschedparam(pthread_t thid, int * policy,
715 struct sched_param * param)
716{
717 int old_errno = errno;
718
719 pthread_internal_t * thread = (pthread_internal_t *)thid;
720 int err = sched_getparam(thread->kernel_id, param);
721 if (!err) {
722 *policy = sched_getscheduler(thread->kernel_id);
723 } else {
724 err = errno;
725 errno = old_errno;
726 }
727 return err;
728}
729
730int pthread_setschedparam(pthread_t thid, int policy,
731 struct sched_param const * param)
732{
733 pthread_internal_t * thread = (pthread_internal_t *)thid;
734 int old_errno = errno;
735 int ret;
736
737 ret = sched_setscheduler(thread->kernel_id, policy, param);
738 if (ret < 0) {
739 ret = errno;
740 errno = old_errno;
741 }
742 return ret;
743}
744
745
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800746// mutex lock states
747//
748// 0: unlocked
749// 1: locked, no waiters
750// 2: locked, maybe waiters
751
752/* a mutex is implemented as a 32-bit integer holding the following fields
753 *
754 * bits: name description
755 * 31-16 tid owner thread's kernel id (recursive and errorcheck only)
756 * 15-14 type mutex type
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700757 * 13 shared process-shared flag
758 * 12-2 counter counter of recursive mutexes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800759 * 1-0 state lock state (0, 1 or 2)
760 */
761
762
763#define MUTEX_OWNER(m) (((m)->value >> 16) & 0xffff)
764#define MUTEX_COUNTER(m) (((m)->value >> 2) & 0xfff)
765
766#define MUTEX_TYPE_MASK 0xc000
767#define MUTEX_TYPE_NORMAL 0x0000
768#define MUTEX_TYPE_RECURSIVE 0x4000
769#define MUTEX_TYPE_ERRORCHECK 0x8000
770
771#define MUTEX_COUNTER_SHIFT 2
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700772#define MUTEX_COUNTER_MASK 0x1ffc
773#define MUTEX_SHARED_MASK 0x2000
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800774
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700775/* a mutex attribute holds the following fields
776 *
777 * bits: name description
778 * 0-3 type type of mutex
779 * 4 shared process-shared flag
780 */
781#define MUTEXATTR_TYPE_MASK 0x000f
782#define MUTEXATTR_SHARED_MASK 0x0010
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800783
784
785int pthread_mutexattr_init(pthread_mutexattr_t *attr)
786{
787 if (attr) {
788 *attr = PTHREAD_MUTEX_DEFAULT;
789 return 0;
790 } else {
791 return EINVAL;
792 }
793}
794
795int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
796{
797 if (attr) {
798 *attr = -1;
799 return 0;
800 } else {
801 return EINVAL;
802 }
803}
804
805int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
806{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700807 if (attr) {
808 int atype = (*attr & MUTEXATTR_TYPE_MASK);
809
810 if (atype >= PTHREAD_MUTEX_NORMAL &&
811 atype <= PTHREAD_MUTEX_ERRORCHECK) {
812 *type = atype;
813 return 0;
814 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800815 }
816 return EINVAL;
817}
818
819int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
820{
821 if (attr && type >= PTHREAD_MUTEX_NORMAL &&
822 type <= PTHREAD_MUTEX_ERRORCHECK ) {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700823 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800824 return 0;
825 }
826 return EINVAL;
827}
828
829/* process-shared mutexes are not supported at the moment */
830
831int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
832{
833 if (!attr)
834 return EINVAL;
835
Mathias Agopianb7681162009-07-13 22:00:33 -0700836 switch (pshared) {
837 case PTHREAD_PROCESS_PRIVATE:
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700838 *attr &= ~MUTEXATTR_SHARED_MASK;
839 return 0;
840
Mathias Agopianb7681162009-07-13 22:00:33 -0700841 case PTHREAD_PROCESS_SHARED:
842 /* our current implementation of pthread actually supports shared
843 * mutexes but won't cleanup if a process dies with the mutex held.
844 * Nevertheless, it's better than nothing. Shared mutexes are used
845 * by surfaceflinger and audioflinger.
846 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700847 *attr |= MUTEXATTR_SHARED_MASK;
Mathias Agopianb7681162009-07-13 22:00:33 -0700848 return 0;
849 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700850 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800851}
852
853int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
854{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700855 if (!attr || !pshared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800856 return EINVAL;
857
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700858 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED
859 : PTHREAD_PROCESS_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800860 return 0;
861}
862
863int pthread_mutex_init(pthread_mutex_t *mutex,
864 const pthread_mutexattr_t *attr)
865{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700866 int value = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800867
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700868 if (mutex == NULL)
869 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800870
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700871 if (__likely(attr == NULL)) {
872 mutex->value = MUTEX_TYPE_NORMAL;
873 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800874 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700875
876 if ((*attr & MUTEXATTR_SHARED_MASK) != 0)
877 value |= MUTEX_SHARED_MASK;
878
879 switch (*attr & MUTEXATTR_TYPE_MASK) {
880 case PTHREAD_MUTEX_NORMAL:
881 value |= MUTEX_TYPE_NORMAL;
882 break;
883 case PTHREAD_MUTEX_RECURSIVE:
884 value |= MUTEX_TYPE_RECURSIVE;
885 break;
886 case PTHREAD_MUTEX_ERRORCHECK:
887 value |= MUTEX_TYPE_ERRORCHECK;
888 break;
889 default:
890 return EINVAL;
891 }
892
893 mutex->value = value;
894 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800895}
896
897int pthread_mutex_destroy(pthread_mutex_t *mutex)
898{
David 'Digit' Turnera02b93b2010-06-28 14:20:22 -0700899 int ret;
900
901 /* use trylock to ensure that the mutex value is
902 * valid and is not already locked. */
903 ret = pthread_mutex_trylock(mutex);
904 if (ret != 0)
905 return ret;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700906
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800907 mutex->value = 0xdead10cc;
908 return 0;
909}
910
911
912/*
913 * Lock a non-recursive mutex.
914 *
915 * As noted above, there are three states:
916 * 0 (unlocked, no contention)
917 * 1 (locked, no contention)
918 * 2 (locked, contention)
919 *
920 * Non-recursive mutexes don't use the thread-id or counter fields, and the
921 * "type" value is zero, so the only bits that will be set are the ones in
922 * the lock state field.
923 */
924static __inline__ void
925_normal_lock(pthread_mutex_t* mutex)
926{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700927 /* We need to preserve the shared flag during operations */
928 int shared = mutex->value & MUTEX_SHARED_MASK;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800929 /*
930 * The common case is an unlocked mutex, so we begin by trying to
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100931 * change the lock's state from 0 to 1. __bionic_cmpxchg() returns 0
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800932 * if it made the swap successfully. If the result is nonzero, this
933 * lock is already held by another thread.
934 */
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100935 if (__bionic_cmpxchg(shared|0, shared|1, &mutex->value ) != 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800936 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800937 * We want to go to sleep until the mutex is available, which
938 * requires promoting it to state 2. We need to swap in the new
939 * state value and then wait until somebody wakes us up.
940 *
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100941 * __bionic_swap() returns the previous value. We swap 2 in and
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800942 * see if we got zero back; if so, we have acquired the lock. If
943 * not, another thread still holds the lock and we wait again.
944 *
945 * The second argument to the __futex_wait() call is compared
946 * against the current value. If it doesn't match, __futex_wait()
947 * returns immediately (otherwise, it sleeps for a time specified
948 * by the third argument; 0 means sleep forever). This ensures
949 * that the mutex is in state 2 when we go to sleep on it, which
950 * guarantees a wake-up call.
951 */
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100952 while (__bionic_swap(shared|2, &mutex->value ) != (shared|0))
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -0700953 __futex_wait_ex(&mutex->value, shared, shared|2, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800954 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700955 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800956}
957
958/*
959 * Release a non-recursive mutex. The caller is responsible for determining
960 * that we are in fact the owner of this lock.
961 */
962static __inline__ void
963_normal_unlock(pthread_mutex_t* mutex)
964{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700965 ANDROID_MEMBAR_FULL();
966
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700967 /* We need to preserve the shared flag during operations */
968 int shared = mutex->value & MUTEX_SHARED_MASK;
969
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800970 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700971 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100972 * to release the lock. __bionic_atomic_dec() returns the previous value;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800973 * if it wasn't 1 we have to do some additional work.
974 */
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100975 if (__bionic_atomic_dec(&mutex->value) != (shared|1)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800976 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800977 * Start by releasing the lock. The decrement changed it from
978 * "contended lock" to "uncontended lock", which means we still
979 * hold it, and anybody who tries to sneak in will push it back
980 * to state 2.
981 *
982 * Once we set it to zero the lock is up for grabs. We follow
983 * this with a __futex_wake() to ensure that one of the waiting
984 * threads has a chance to grab it.
985 *
986 * This doesn't cause a race with the swap/wait pair in
987 * _normal_lock(), because the __futex_wait() call there will
988 * return immediately if the mutex value isn't 2.
989 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700990 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800991
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800992 /*
993 * Wake up one waiting thread. We don't know which thread will be
994 * woken or when it'll start executing -- futexes make no guarantees
995 * here. There may not even be a thread waiting.
996 *
997 * The newly-woken thread will replace the 0 we just set above
998 * with 2, which means that when it eventually releases the mutex
999 * it will also call FUTEX_WAKE. This results in one extra wake
1000 * call whenever a lock is contended, but lets us avoid forgetting
1001 * anyone without requiring us to track the number of sleepers.
1002 *
1003 * It's possible for another thread to sneak in and grab the lock
1004 * between the zero assignment above and the wake call below. If
1005 * the new thread is "slow" and holds the lock for a while, we'll
1006 * wake up a sleeper, which will swap in a 2 and then go back to
1007 * sleep since the lock is still held. If the new thread is "fast",
1008 * running to completion before we call wake, the thread we
1009 * eventually wake will find an unlocked mutex and will execute.
1010 * Either way we have correct behavior and nobody is orphaned on
1011 * the wait queue.
1012 */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001013 __futex_wake_ex(&mutex->value, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001014 }
1015}
1016
1017static pthread_mutex_t __recursive_lock = PTHREAD_MUTEX_INITIALIZER;
1018
1019static void
1020_recursive_lock(void)
1021{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001022 _normal_lock(&__recursive_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001023}
1024
1025static void
1026_recursive_unlock(void)
1027{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001028 _normal_unlock(&__recursive_lock );
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001029}
1030
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001031int pthread_mutex_lock(pthread_mutex_t *mutex)
1032{
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001033 int mtype, tid, new_lock_type, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001034
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001035 if (__unlikely(mutex == NULL))
1036 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001037
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001038 mtype = (mutex->value & MUTEX_TYPE_MASK);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001039 shared = (mutex->value & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001040
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001041 /* Handle normal case first */
1042 if ( __likely(mtype == MUTEX_TYPE_NORMAL) ) {
1043 _normal_lock(mutex);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001044 return 0;
1045 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001046
1047 /* Do we already own this recursive or error-check mutex ? */
1048 tid = __get_thread()->kernel_id;
1049 if ( tid == MUTEX_OWNER(mutex) )
1050 {
1051 int oldv, counter;
1052
1053 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1054 /* trying to re-lock a mutex we already acquired */
1055 return EDEADLK;
1056 }
1057 /*
1058 * We own the mutex, but other threads are able to change
1059 * the contents (e.g. promoting it to "contended"), so we
1060 * need to hold the global lock.
1061 */
1062 _recursive_lock();
1063 oldv = mutex->value;
1064 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1065 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1066 _recursive_unlock();
1067 return 0;
1068 }
1069
1070 /* We don't own the mutex, so try to get it.
1071 *
1072 * First, we try to change its state from 0 to 1, if this
1073 * doesn't work, try to change it to state 2.
1074 */
1075 new_lock_type = 1;
1076
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001077 /* compute futex wait opcode and restore shared flag in mtype */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001078 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001079
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001080 for (;;) {
1081 int oldv;
1082
1083 _recursive_lock();
1084 oldv = mutex->value;
1085 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1086 mutex->value = ((tid << 16) | mtype | new_lock_type);
1087 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1088 oldv ^= 3;
1089 mutex->value = oldv;
1090 }
1091 _recursive_unlock();
1092
1093 if (oldv == mtype)
1094 break;
1095
1096 /*
1097 * The lock was held, possibly contended by others. From
1098 * now on, if we manage to acquire the lock, we have to
1099 * assume that others are still contending for it so that
1100 * we'll wake them when we unlock it.
1101 */
1102 new_lock_type = 2;
1103
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001104 __futex_wait_ex(&mutex->value, shared, oldv, NULL);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001105 }
1106 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001107}
1108
1109
1110int pthread_mutex_unlock(pthread_mutex_t *mutex)
1111{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001112 int mtype, tid, oldv, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001113
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001114 if (__unlikely(mutex == NULL))
1115 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001116
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001117 mtype = (mutex->value & MUTEX_TYPE_MASK);
1118 shared = (mutex->value & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001119
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001120 /* Handle common case first */
1121 if (__likely(mtype == MUTEX_TYPE_NORMAL)) {
1122 _normal_unlock(mutex);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001123 return 0;
1124 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001125
1126 /* Do we already own this recursive or error-check mutex ? */
1127 tid = __get_thread()->kernel_id;
1128 if ( tid != MUTEX_OWNER(mutex) )
1129 return EPERM;
1130
1131 /* We do, decrement counter or release the mutex if it is 0 */
1132 _recursive_lock();
1133 oldv = mutex->value;
1134 if (oldv & MUTEX_COUNTER_MASK) {
1135 mutex->value = oldv - (1 << MUTEX_COUNTER_SHIFT);
1136 oldv = 0;
1137 } else {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001138 mutex->value = shared | mtype;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001139 }
1140 _recursive_unlock();
1141
1142 /* Wake one waiting thread, if any */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001143 if ((oldv & 3) == 2) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001144 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001145 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001146 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001147}
1148
1149
1150int pthread_mutex_trylock(pthread_mutex_t *mutex)
1151{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001152 int mtype, tid, oldv, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001153
1154 if (__unlikely(mutex == NULL))
1155 return EINVAL;
1156
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001157 mtype = (mutex->value & MUTEX_TYPE_MASK);
1158 shared = (mutex->value & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001159
1160 /* Handle common case first */
1161 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001162 {
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001163 if (__bionic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001164 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001165 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001166 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001167
1168 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001169 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001170
1171 /* Do we already own this recursive or error-check mutex ? */
1172 tid = __get_thread()->kernel_id;
1173 if ( tid == MUTEX_OWNER(mutex) )
1174 {
1175 int counter;
1176
1177 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1178 /* already locked by ourselves */
1179 return EDEADLK;
1180 }
1181
1182 _recursive_lock();
1183 oldv = mutex->value;
1184 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1185 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1186 _recursive_unlock();
1187 return 0;
1188 }
1189
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001190 /* Restore sharing bit in mtype */
1191 mtype |= shared;
1192
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001193 /* Try to lock it, just once. */
1194 _recursive_lock();
1195 oldv = mutex->value;
1196 if (oldv == mtype) /* uncontended released lock => state 1 */
1197 mutex->value = ((tid << 16) | mtype | 1);
1198 _recursive_unlock();
1199
1200 if (oldv != mtype)
1201 return EBUSY;
1202
1203 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001204}
1205
1206
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001207/* initialize 'ts' with the difference between 'abstime' and the current time
1208 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
1209 */
1210static int
1211__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
1212{
1213 clock_gettime(clock, ts);
1214 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
1215 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
1216 if (ts->tv_nsec < 0) {
1217 ts->tv_sec--;
1218 ts->tv_nsec += 1000000000;
1219 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001220 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001221 return -1;
1222
1223 return 0;
1224}
1225
1226/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1227 * milliseconds.
1228 */
1229static void
1230__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1231{
1232 clock_gettime(clock, abstime);
1233 abstime->tv_sec += msecs/1000;
1234 abstime->tv_nsec += (msecs%1000)*1000000;
1235 if (abstime->tv_nsec >= 1000000000) {
1236 abstime->tv_sec++;
1237 abstime->tv_nsec -= 1000000000;
1238 }
1239}
1240
1241int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1242{
1243 clockid_t clock = CLOCK_MONOTONIC;
1244 struct timespec abstime;
1245 struct timespec ts;
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001246 int mtype, tid, oldv, new_lock_type, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001247
1248 /* compute absolute expiration time */
1249 __timespec_to_relative_msec(&abstime, msecs, clock);
1250
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001251 if (__unlikely(mutex == NULL))
1252 return EINVAL;
1253
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001254 mtype = (mutex->value & MUTEX_TYPE_MASK);
1255 shared = (mutex->value & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001256
1257 /* Handle common case first */
1258 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001259 {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001260 /* fast path for uncontended lock */
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001261 if (__bionic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001262 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001263 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001264 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001265
1266 /* loop while needed */
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001267 while (__bionic_swap(shared|2, &mutex->value) != (shared|0)) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001268 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1269 return EBUSY;
1270
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001271 __futex_wait_ex(&mutex->value, shared, shared|2, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001272 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001273 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001274 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001275 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001276
1277 /* Do we already own this recursive or error-check mutex ? */
1278 tid = __get_thread()->kernel_id;
1279 if ( tid == MUTEX_OWNER(mutex) )
1280 {
1281 int oldv, counter;
1282
1283 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1284 /* already locked by ourselves */
1285 return EDEADLK;
1286 }
1287
1288 _recursive_lock();
1289 oldv = mutex->value;
1290 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1291 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1292 _recursive_unlock();
1293 return 0;
1294 }
1295
1296 /* We don't own the mutex, so try to get it.
1297 *
1298 * First, we try to change its state from 0 to 1, if this
1299 * doesn't work, try to change it to state 2.
1300 */
1301 new_lock_type = 1;
1302
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001303 /* Compute wait op and restore sharing bit in mtype */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001304 mtype |= shared;
1305
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001306 for (;;) {
1307 int oldv;
1308 struct timespec ts;
1309
1310 _recursive_lock();
1311 oldv = mutex->value;
1312 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1313 mutex->value = ((tid << 16) | mtype | new_lock_type);
1314 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1315 oldv ^= 3;
1316 mutex->value = oldv;
1317 }
1318 _recursive_unlock();
1319
1320 if (oldv == mtype)
1321 break;
1322
1323 /*
1324 * The lock was held, possibly contended by others. From
1325 * now on, if we manage to acquire the lock, we have to
1326 * assume that others are still contending for it so that
1327 * we'll wake them when we unlock it.
1328 */
1329 new_lock_type = 2;
1330
1331 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1332 return EBUSY;
1333
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001334 __futex_wait_ex(&mutex->value, shared, oldv, &ts);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001335 }
1336 return 0;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001337}
1338
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001339int pthread_condattr_init(pthread_condattr_t *attr)
1340{
1341 if (attr == NULL)
1342 return EINVAL;
1343
1344 *attr = PTHREAD_PROCESS_PRIVATE;
1345 return 0;
1346}
1347
1348int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1349{
1350 if (attr == NULL || pshared == NULL)
1351 return EINVAL;
1352
1353 *pshared = *attr;
1354 return 0;
1355}
1356
1357int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1358{
1359 if (attr == NULL)
1360 return EINVAL;
1361
1362 if (pshared != PTHREAD_PROCESS_SHARED &&
1363 pshared != PTHREAD_PROCESS_PRIVATE)
1364 return EINVAL;
1365
1366 *attr = pshared;
1367 return 0;
1368}
1369
1370int pthread_condattr_destroy(pthread_condattr_t *attr)
1371{
1372 if (attr == NULL)
1373 return EINVAL;
1374
1375 *attr = 0xdeada11d;
1376 return 0;
1377}
1378
1379/* We use one bit in condition variable values as the 'shared' flag
1380 * The rest is a counter.
1381 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001382#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001383#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001384#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1385
1386#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001387
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001388/* XXX *technically* there is a race condition that could allow
1389 * XXX a signal to be missed. If thread A is preempted in _wait()
1390 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001391 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001392 * XXX before thread A is scheduled again and calls futex_wait(),
1393 * XXX then the signal will be lost.
1394 */
1395
1396int pthread_cond_init(pthread_cond_t *cond,
1397 const pthread_condattr_t *attr)
1398{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001399 if (cond == NULL)
1400 return EINVAL;
1401
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001402 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001403
1404 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001405 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001406
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001407 return 0;
1408}
1409
1410int pthread_cond_destroy(pthread_cond_t *cond)
1411{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001412 if (cond == NULL)
1413 return EINVAL;
1414
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001415 cond->value = 0xdeadc04d;
1416 return 0;
1417}
1418
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001419/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001420 * pthread_cond_signal to atomically decrement the counter
1421 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001422 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001423static int
1424__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001425{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001426 long flags;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001427
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001428 if (__unlikely(cond == NULL))
1429 return EINVAL;
1430
1431 flags = (cond->value & ~COND_COUNTER_MASK);
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001432 for (;;) {
1433 long oldval = cond->value;
1434 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1435 | flags;
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001436 if (__bionic_cmpxchg(oldval, newval, &cond->value) == 0)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001437 break;
1438 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001439
Andy McFaddene2ac8982010-09-02 13:34:53 -07001440 /*
1441 * Ensure that all memory accesses previously made by this thread are
1442 * visible to the woken thread(s). On the other side, the "wait"
1443 * code will issue any necessary barriers when locking the mutex.
1444 *
1445 * This may not strictly be necessary -- if the caller follows
1446 * recommended practice and holds the mutex before signaling the cond
1447 * var, the mutex ops will provide correct semantics. If they don't
1448 * hold the mutex, they're subject to race conditions anyway.
1449 */
1450 ANDROID_MEMBAR_FULL();
1451
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001452 __futex_wake_ex(&cond->value, COND_IS_SHARED(cond), counter);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001453 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001454}
1455
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001456int pthread_cond_broadcast(pthread_cond_t *cond)
1457{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001458 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001459}
1460
1461int pthread_cond_signal(pthread_cond_t *cond)
1462{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001463 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001464}
1465
1466int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1467{
1468 return pthread_cond_timedwait(cond, mutex, NULL);
1469}
1470
1471int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1472 pthread_mutex_t * mutex,
1473 const struct timespec *reltime)
1474{
1475 int status;
1476 int oldvalue = cond->value;
1477
1478 pthread_mutex_unlock(mutex);
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001479 status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond), oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001480 pthread_mutex_lock(mutex);
1481
1482 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1483 return 0;
1484}
1485
1486int __pthread_cond_timedwait(pthread_cond_t *cond,
1487 pthread_mutex_t * mutex,
1488 const struct timespec *abstime,
1489 clockid_t clock)
1490{
1491 struct timespec ts;
1492 struct timespec * tsp;
1493
1494 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001495 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001496 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001497 tsp = &ts;
1498 } else {
1499 tsp = NULL;
1500 }
1501
1502 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1503}
1504
1505int pthread_cond_timedwait(pthread_cond_t *cond,
1506 pthread_mutex_t * mutex,
1507 const struct timespec *abstime)
1508{
1509 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1510}
1511
1512
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001513/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001514int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1515 pthread_mutex_t * mutex,
1516 const struct timespec *abstime)
1517{
1518 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1519}
1520
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001521int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1522 pthread_mutex_t * mutex,
1523 const struct timespec *abstime)
1524{
1525 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1526}
1527
1528int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1529 pthread_mutex_t * mutex,
1530 const struct timespec *reltime)
1531{
1532 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1533}
1534
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001535int pthread_cond_timeout_np(pthread_cond_t *cond,
1536 pthread_mutex_t * mutex,
1537 unsigned msecs)
1538{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001539 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001540
1541 ts.tv_sec = msecs / 1000;
1542 ts.tv_nsec = (msecs % 1000) * 1000000;
1543
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001544 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001545}
1546
1547
1548
1549/* A technical note regarding our thread-local-storage (TLS) implementation:
1550 *
1551 * There can be up to TLSMAP_SIZE independent TLS keys in a given process,
1552 * though the first TLSMAP_START keys are reserved for Bionic to hold
1553 * special thread-specific variables like errno or a pointer to
1554 * the current thread's descriptor.
1555 *
1556 * while stored in the TLS area, these entries cannot be accessed through
1557 * pthread_getspecific() / pthread_setspecific() and pthread_key_delete()
1558 *
1559 * also, some entries in the key table are pre-allocated (see tlsmap_lock)
1560 * to greatly simplify and speedup some OpenGL-related operations. though the
1561 * initialy value will be NULL on all threads.
1562 *
1563 * you can use pthread_getspecific()/setspecific() on these, and in theory
1564 * you could also call pthread_key_delete() as well, though this would
1565 * probably break some apps.
1566 *
1567 * The 'tlsmap_t' type defined below implements a shared global map of
1568 * currently created/allocated TLS keys and the destructors associated
1569 * with them. You should use tlsmap_lock/unlock to access it to avoid
1570 * any race condition.
1571 *
1572 * the global TLS map simply contains a bitmap of allocated keys, and
1573 * an array of destructors.
1574 *
1575 * each thread has a TLS area that is a simple array of TLSMAP_SIZE void*
1576 * pointers. the TLS area of the main thread is stack-allocated in
1577 * __libc_init_common, while the TLS area of other threads is placed at
1578 * the top of their stack in pthread_create.
1579 *
1580 * when pthread_key_create() is called, it finds the first free key in the
1581 * bitmap, then set it to 1, saving the destructor altogether
1582 *
1583 * when pthread_key_delete() is called. it will erase the key's bitmap bit
1584 * and its destructor, and will also clear the key data in the TLS area of
1585 * all created threads. As mandated by Posix, it is the responsability of
1586 * the caller of pthread_key_delete() to properly reclaim the objects that
1587 * were pointed to by these data fields (either before or after the call).
1588 *
1589 */
1590
1591/* TLS Map implementation
1592 */
1593
1594#define TLSMAP_START (TLS_SLOT_MAX_WELL_KNOWN+1)
1595#define TLSMAP_SIZE BIONIC_TLS_SLOTS
1596#define TLSMAP_BITS 32
1597#define TLSMAP_WORDS ((TLSMAP_SIZE+TLSMAP_BITS-1)/TLSMAP_BITS)
1598#define TLSMAP_WORD(m,k) (m)->map[(k)/TLSMAP_BITS]
1599#define TLSMAP_MASK(k) (1U << ((k)&(TLSMAP_BITS-1)))
1600
1601/* this macro is used to quickly check that a key belongs to a reasonable range */
1602#define TLSMAP_VALIDATE_KEY(key) \
1603 ((key) >= TLSMAP_START && (key) < TLSMAP_SIZE)
1604
1605/* the type of tls key destructor functions */
1606typedef void (*tls_dtor_t)(void*);
1607
1608typedef struct {
1609 int init; /* see comment in tlsmap_lock() */
1610 uint32_t map[TLSMAP_WORDS]; /* bitmap of allocated keys */
1611 tls_dtor_t dtors[TLSMAP_SIZE]; /* key destructors */
1612} tlsmap_t;
1613
1614static pthread_mutex_t _tlsmap_lock = PTHREAD_MUTEX_INITIALIZER;
1615static tlsmap_t _tlsmap;
1616
1617/* lock the global TLS map lock and return a handle to it */
1618static __inline__ tlsmap_t* tlsmap_lock(void)
1619{
1620 tlsmap_t* m = &_tlsmap;
1621
1622 pthread_mutex_lock(&_tlsmap_lock);
1623 /* we need to initialize the first entry of the 'map' array
1624 * with the value TLS_DEFAULT_ALLOC_MAP. doing it statically
1625 * when declaring _tlsmap is a bit awkward and is going to
1626 * produce warnings, so do it the first time we use the map
1627 * instead
1628 */
1629 if (__unlikely(!m->init)) {
1630 TLSMAP_WORD(m,0) = TLS_DEFAULT_ALLOC_MAP;
1631 m->init = 1;
1632 }
1633 return m;
1634}
1635
1636/* unlock the global TLS map */
1637static __inline__ void tlsmap_unlock(tlsmap_t* m)
1638{
1639 pthread_mutex_unlock(&_tlsmap_lock);
1640 (void)m; /* a good compiler is a happy compiler */
1641}
1642
1643/* test to see wether a key is allocated */
1644static __inline__ int tlsmap_test(tlsmap_t* m, int key)
1645{
1646 return (TLSMAP_WORD(m,key) & TLSMAP_MASK(key)) != 0;
1647}
1648
1649/* set the destructor and bit flag on a newly allocated key */
1650static __inline__ void tlsmap_set(tlsmap_t* m, int key, tls_dtor_t dtor)
1651{
1652 TLSMAP_WORD(m,key) |= TLSMAP_MASK(key);
1653 m->dtors[key] = dtor;
1654}
1655
1656/* clear the destructor and bit flag on an existing key */
1657static __inline__ void tlsmap_clear(tlsmap_t* m, int key)
1658{
1659 TLSMAP_WORD(m,key) &= ~TLSMAP_MASK(key);
1660 m->dtors[key] = NULL;
1661}
1662
1663/* allocate a new TLS key, return -1 if no room left */
1664static int tlsmap_alloc(tlsmap_t* m, tls_dtor_t dtor)
1665{
1666 int key;
1667
1668 for ( key = TLSMAP_START; key < TLSMAP_SIZE; key++ ) {
1669 if ( !tlsmap_test(m, key) ) {
1670 tlsmap_set(m, key, dtor);
1671 return key;
1672 }
1673 }
1674 return -1;
1675}
1676
1677
1678int pthread_key_create(pthread_key_t *key, void (*destructor_function)(void *))
1679{
1680 uint32_t err = ENOMEM;
1681 tlsmap_t* map = tlsmap_lock();
1682 int k = tlsmap_alloc(map, destructor_function);
1683
1684 if (k >= 0) {
1685 *key = k;
1686 err = 0;
1687 }
1688 tlsmap_unlock(map);
1689 return err;
1690}
1691
1692
1693/* This deletes a pthread_key_t. note that the standard mandates that this does
1694 * not call the destructor of non-NULL key values. Instead, it is the
1695 * responsability of the caller to properly dispose of the corresponding data
1696 * and resources, using any mean it finds suitable.
1697 *
1698 * On the other hand, this function will clear the corresponding key data
1699 * values in all known threads. this prevents later (invalid) calls to
1700 * pthread_getspecific() to receive invalid/stale values.
1701 */
1702int pthread_key_delete(pthread_key_t key)
1703{
1704 uint32_t err;
1705 pthread_internal_t* thr;
1706 tlsmap_t* map;
1707
1708 if (!TLSMAP_VALIDATE_KEY(key)) {
1709 return EINVAL;
1710 }
1711
1712 map = tlsmap_lock();
1713
1714 if (!tlsmap_test(map, key)) {
1715 err = EINVAL;
1716 goto err1;
1717 }
1718
1719 /* clear value in all threads */
1720 pthread_mutex_lock(&gThreadListLock);
1721 for ( thr = gThreadList; thr != NULL; thr = thr->next ) {
1722 /* avoid zombie threads with a negative 'join_count'. these are really
1723 * already dead and don't have a TLS area anymore.
1724 *
1725 * similarly, it is possible to have thr->tls == NULL for threads that
1726 * were just recently created through pthread_create() but whose
1727 * startup trampoline (__thread_entry) hasn't been run yet by the
1728 * scheduler. so check for this too.
1729 */
1730 if (thr->join_count < 0 || !thr->tls)
1731 continue;
1732
1733 thr->tls[key] = NULL;
1734 }
1735 tlsmap_clear(map, key);
1736
1737 pthread_mutex_unlock(&gThreadListLock);
1738 err = 0;
1739
1740err1:
1741 tlsmap_unlock(map);
1742 return err;
1743}
1744
1745
1746int pthread_setspecific(pthread_key_t key, const void *ptr)
1747{
1748 int err = EINVAL;
1749 tlsmap_t* map;
1750
1751 if (TLSMAP_VALIDATE_KEY(key)) {
1752 /* check that we're trying to set data for an allocated key */
1753 map = tlsmap_lock();
1754 if (tlsmap_test(map, key)) {
1755 ((uint32_t *)__get_tls())[key] = (uint32_t)ptr;
1756 err = 0;
1757 }
1758 tlsmap_unlock(map);
1759 }
1760 return err;
1761}
1762
1763void * pthread_getspecific(pthread_key_t key)
1764{
1765 if (!TLSMAP_VALIDATE_KEY(key)) {
1766 return NULL;
1767 }
1768
1769 /* for performance reason, we do not lock/unlock the global TLS map
1770 * to check that the key is properly allocated. if the key was not
1771 * allocated, the value read from the TLS should always be NULL
1772 * due to pthread_key_delete() clearing the values for all threads.
1773 */
1774 return (void *)(((unsigned *)__get_tls())[key]);
1775}
1776
1777/* Posix mandates that this be defined in <limits.h> but we don't have
1778 * it just yet.
1779 */
1780#ifndef PTHREAD_DESTRUCTOR_ITERATIONS
1781# define PTHREAD_DESTRUCTOR_ITERATIONS 4
1782#endif
1783
1784/* this function is called from pthread_exit() to remove all TLS key data
1785 * from this thread's TLS area. this must call the destructor of all keys
1786 * that have a non-NULL data value (and a non-NULL destructor).
1787 *
1788 * because destructors can do funky things like deleting/creating other
1789 * keys, we need to implement this in a loop
1790 */
1791static void pthread_key_clean_all(void)
1792{
1793 tlsmap_t* map;
1794 void** tls = (void**)__get_tls();
1795 int rounds = PTHREAD_DESTRUCTOR_ITERATIONS;
1796
1797 map = tlsmap_lock();
1798
1799 for (rounds = PTHREAD_DESTRUCTOR_ITERATIONS; rounds > 0; rounds--)
1800 {
1801 int kk, count = 0;
1802
1803 for (kk = TLSMAP_START; kk < TLSMAP_SIZE; kk++) {
1804 if ( tlsmap_test(map, kk) )
1805 {
1806 void* data = tls[kk];
1807 tls_dtor_t dtor = map->dtors[kk];
1808
1809 if (data != NULL && dtor != NULL)
1810 {
1811 /* we need to clear the key data now, this will prevent the
1812 * destructor (or a later one) from seeing the old value if
1813 * it calls pthread_getspecific() for some odd reason
1814 *
1815 * we do not do this if 'dtor == NULL' just in case another
1816 * destructor function might be responsible for manually
1817 * releasing the corresponding data.
1818 */
1819 tls[kk] = NULL;
1820
1821 /* because the destructor is free to call pthread_key_create
1822 * and/or pthread_key_delete, we need to temporarily unlock
1823 * the TLS map
1824 */
1825 tlsmap_unlock(map);
1826 (*dtor)(data);
1827 map = tlsmap_lock();
1828
1829 count += 1;
1830 }
1831 }
1832 }
1833
1834 /* if we didn't call any destructor, there is no need to check the
1835 * TLS data again
1836 */
1837 if (count == 0)
1838 break;
1839 }
1840 tlsmap_unlock(map);
1841}
1842
1843// man says this should be in <linux/unistd.h>, but it isn't
Jeff Brown10c8ce52011-11-18 15:17:07 -08001844extern int tgkill(int tgid, int tid, int sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001845
1846int pthread_kill(pthread_t tid, int sig)
1847{
1848 int ret;
1849 int old_errno = errno;
1850 pthread_internal_t * thread = (pthread_internal_t *)tid;
1851
Jeff Brown10c8ce52011-11-18 15:17:07 -08001852 ret = tgkill(getpid(), thread->kernel_id, sig);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001853 if (ret < 0) {
1854 ret = errno;
1855 errno = old_errno;
1856 }
1857
1858 return ret;
1859}
1860
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001861/* Despite the fact that our kernel headers define sigset_t explicitly
1862 * as a 32-bit integer, the kernel system call really expects a 64-bit
1863 * bitmap for the signal set, or more exactly an array of two-32-bit
1864 * values (see $KERNEL/arch/$ARCH/include/asm/signal.h for details).
1865 *
1866 * Unfortunately, we cannot fix the sigset_t definition without breaking
1867 * the C library ABI, so perform a little runtime translation here.
1868 */
1869typedef union {
1870 sigset_t bionic;
1871 uint32_t kernel[2];
1872} kernel_sigset_t;
1873
1874/* this is a private syscall stub */
1875extern int __rt_sigprocmask(int, const kernel_sigset_t *, kernel_sigset_t *, size_t);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001876
1877int pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
1878{
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001879 /* pthread_sigmask must return the error code, but the syscall
1880 * will set errno instead and return 0/-1
1881 */
1882 int ret, old_errno = errno;
1883
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001884 /* We must convert *set into a kernel_sigset_t */
1885 kernel_sigset_t in_set, *in_set_ptr;
1886 kernel_sigset_t out_set;
1887
Bruce Bearee4a21c82011-12-05 11:25:37 -08001888 in_set.kernel[0] = in_set.kernel[1] = 0;
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001889 out_set.kernel[0] = out_set.kernel[1] = 0;
1890
1891 /* 'in_set_ptr' is the second parameter to __rt_sigprocmask. It must be NULL
1892 * if 'set' is NULL to ensure correct semantics (which in this case would
1893 * be to ignore 'how' and return the current signal set into 'oset'.
David 'Digit' Turner5c8c00a2010-12-20 15:58:06 +01001894 */
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001895 if (set == NULL) {
1896 in_set_ptr = NULL;
1897 } else {
1898 in_set.bionic = *set;
1899 in_set_ptr = &in_set;
1900 }
1901
1902 ret = __rt_sigprocmask(how, in_set_ptr, &out_set, sizeof(kernel_sigset_t));
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001903 if (ret < 0)
1904 ret = errno;
1905
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001906 if (oset)
1907 *oset = out_set.bionic;
1908
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001909 errno = old_errno;
1910 return ret;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001911}
1912
1913
1914int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
1915{
1916 const int CLOCK_IDTYPE_BITS = 3;
1917 pthread_internal_t* thread = (pthread_internal_t*)tid;
1918
1919 if (!thread)
1920 return ESRCH;
1921
1922 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
1923 return 0;
1924}
1925
1926
1927/* NOTE: this implementation doesn't support a init function that throws a C++ exception
1928 * or calls fork()
1929 */
1930int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
1931{
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001932 static pthread_mutex_t once_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001933 volatile pthread_once_t* ocptr = once_control;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001934
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001935 pthread_once_t tmp = *ocptr;
1936 ANDROID_MEMBAR_FULL();
1937 if (tmp == PTHREAD_ONCE_INIT) {
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001938 pthread_mutex_lock( &once_lock );
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001939 if (*ocptr == PTHREAD_ONCE_INIT) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001940 (*init_routine)();
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001941 ANDROID_MEMBAR_FULL();
1942 *ocptr = ~PTHREAD_ONCE_INIT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001943 }
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001944 pthread_mutex_unlock( &once_lock );
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001945 }
1946 return 0;
1947}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03001948
1949/* This value is not exported by kernel headers, so hardcode it here */
1950#define MAX_TASK_COMM_LEN 16
1951#define TASK_COMM_FMT "/proc/self/task/%u/comm"
1952
1953int pthread_setname_np(pthread_t thid, const char *thname)
1954{
1955 size_t thname_len;
1956 int saved_errno, ret;
1957
1958 if (thid == 0 || thname == NULL)
1959 return EINVAL;
1960
1961 thname_len = strlen(thname);
1962 if (thname_len >= MAX_TASK_COMM_LEN)
1963 return ERANGE;
1964
1965 saved_errno = errno;
1966 if (thid == pthread_self())
1967 {
1968 ret = prctl(PR_SET_NAME, (unsigned long)thname, 0, 0, 0) ? errno : 0;
1969 }
1970 else
1971 {
1972 /* Have to change another thread's name */
1973 pthread_internal_t *thread = (pthread_internal_t *)thid;
1974 char comm_name[sizeof(TASK_COMM_FMT) + 8];
1975 ssize_t n;
1976 int fd;
1977
1978 snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, (unsigned int)thread->kernel_id);
1979 fd = open(comm_name, O_RDWR);
1980 if (fd == -1)
1981 {
1982 ret = errno;
1983 goto exit;
1984 }
1985 n = TEMP_FAILURE_RETRY(write(fd, thname, thname_len));
1986 close(fd);
1987
1988 if (n < 0)
1989 ret = errno;
1990 else if ((size_t)n != thname_len)
1991 ret = EIO;
1992 else
1993 ret = 0;
1994 }
1995exit:
1996 errno = saved_errno;
1997 return ret;
1998}
Glenn Kastend53cae02011-07-11 15:41:28 -07001999
2000/* Return the kernel thread ID for a pthread.
2001 * This is only defined for implementations where pthread <-> kernel is 1:1, which this is.
2002 * Not the same as pthread_getthreadid_np, which is commonly defined to be opaque.
2003 * Internal, not an NDK API.
2004 */
2005
2006pid_t __pthread_gettid(pthread_t thid)
2007{
2008 pthread_internal_t* thread = (pthread_internal_t*)thid;
2009 return thread->kernel_id;
2010}