blob: f224c54b63f1898c48cc6f31b373deca03e1d2a6 [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;
571
572 // call the cleanup handlers first
573 while (thread->cleanup_stack) {
574 __pthread_cleanup_t* c = thread->cleanup_stack;
575 thread->cleanup_stack = c->__cleanup_prev;
576 c->__cleanup_routine(c->__cleanup_arg);
577 }
578
579 // call the TLS destructors, it is important to do that before removing this
580 // thread from the global list. this will ensure that if someone else deletes
581 // a TLS key, the corresponding value will be set to NULL in this thread's TLS
582 // space (see pthread_key_delete)
583 pthread_key_clean_all();
584
585 // if the thread is detached, destroy the pthread_internal_t
586 // otherwise, keep it in memory and signal any joiners
587 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
588 _pthread_internal_remove(thread);
589 _pthread_internal_free(thread);
590 } else {
591 /* the join_count field is used to store the number of threads waiting for
592 * the termination of this thread with pthread_join(),
593 *
594 * if it is positive we need to signal the waiters, and we do not touch
595 * the count (it will be decremented by the waiters, the last one will
596 * also remove/free the thread structure
597 *
598 * if it is zero, we set the count value to -1 to indicate that the
599 * thread is in 'zombie' state: it has stopped executing, and its stack
600 * is gone (as well as its TLS area). when another thread calls pthread_join()
601 * on it, it will immediately free the thread and return.
602 */
603 pthread_mutex_lock(&gThreadListLock);
604 thread->return_value = retval;
605 if (thread->join_count > 0) {
606 pthread_cond_broadcast(&thread->join_cond);
607 } else {
608 thread->join_count = -1; /* zombie thread */
609 }
610 pthread_mutex_unlock(&gThreadListLock);
611 }
612
613 // destroy the thread stack
614 if (user_stack)
615 _exit_thread((int)retval);
616 else
617 _exit_with_stack_teardown(stack_base, stack_size, (int)retval);
618}
619
620int pthread_join(pthread_t thid, void ** ret_val)
621{
622 pthread_internal_t* thread = (pthread_internal_t*)thid;
623 int count;
624
625 // check that the thread still exists and is not detached
626 pthread_mutex_lock(&gThreadListLock);
627
628 for (thread = gThreadList; thread != NULL; thread = thread->next)
629 if (thread == (pthread_internal_t*)thid)
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200630 goto FoundIt;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800631
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200632 pthread_mutex_unlock(&gThreadListLock);
633 return ESRCH;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800634
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200635FoundIt:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800636 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
637 pthread_mutex_unlock(&gThreadListLock);
638 return EINVAL;
639 }
640
641 /* wait for thread death when needed
642 *
643 * if the 'join_count' is negative, this is a 'zombie' thread that
644 * is already dead and without stack/TLS
645 *
646 * otherwise, we need to increment 'join-count' and wait to be signaled
647 */
648 count = thread->join_count;
649 if (count >= 0) {
650 thread->join_count += 1;
651 pthread_cond_wait( &thread->join_cond, &gThreadListLock );
652 count = --thread->join_count;
653 }
654 if (ret_val)
655 *ret_val = thread->return_value;
656
657 /* remove thread descriptor when we're the last joiner or when the
658 * thread was already a zombie.
659 */
660 if (count <= 0) {
661 _pthread_internal_remove_locked(thread);
662 _pthread_internal_free(thread);
663 }
664 pthread_mutex_unlock(&gThreadListLock);
665 return 0;
666}
667
668int pthread_detach( pthread_t thid )
669{
670 pthread_internal_t* thread;
671 int result = 0;
672 int flags;
673
674 pthread_mutex_lock(&gThreadListLock);
675 for (thread = gThreadList; thread != NULL; thread = thread->next)
676 if (thread == (pthread_internal_t*)thid)
677 goto FoundIt;
678
679 result = ESRCH;
680 goto Exit;
681
682FoundIt:
683 do {
684 flags = thread->attr.flags;
685
686 if ( flags & PTHREAD_ATTR_FLAG_DETACHED ) {
687 /* thread is not joinable ! */
688 result = EINVAL;
689 goto Exit;
690 }
691 }
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100692 while ( __bionic_cmpxchg( flags, flags | PTHREAD_ATTR_FLAG_DETACHED,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800693 (volatile int*)&thread->attr.flags ) != 0 );
694Exit:
695 pthread_mutex_unlock(&gThreadListLock);
696 return result;
697}
698
699pthread_t pthread_self(void)
700{
701 return (pthread_t)__get_thread();
702}
703
704int pthread_equal(pthread_t one, pthread_t two)
705{
706 return (one == two ? 1 : 0);
707}
708
709int pthread_getschedparam(pthread_t thid, int * policy,
710 struct sched_param * param)
711{
712 int old_errno = errno;
713
714 pthread_internal_t * thread = (pthread_internal_t *)thid;
715 int err = sched_getparam(thread->kernel_id, param);
716 if (!err) {
717 *policy = sched_getscheduler(thread->kernel_id);
718 } else {
719 err = errno;
720 errno = old_errno;
721 }
722 return err;
723}
724
725int pthread_setschedparam(pthread_t thid, int policy,
726 struct sched_param const * param)
727{
728 pthread_internal_t * thread = (pthread_internal_t *)thid;
729 int old_errno = errno;
730 int ret;
731
732 ret = sched_setscheduler(thread->kernel_id, policy, param);
733 if (ret < 0) {
734 ret = errno;
735 errno = old_errno;
736 }
737 return ret;
738}
739
740
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800741// mutex lock states
742//
743// 0: unlocked
744// 1: locked, no waiters
745// 2: locked, maybe waiters
746
747/* a mutex is implemented as a 32-bit integer holding the following fields
748 *
749 * bits: name description
750 * 31-16 tid owner thread's kernel id (recursive and errorcheck only)
751 * 15-14 type mutex type
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700752 * 13 shared process-shared flag
753 * 12-2 counter counter of recursive mutexes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800754 * 1-0 state lock state (0, 1 or 2)
755 */
756
757
758#define MUTEX_OWNER(m) (((m)->value >> 16) & 0xffff)
759#define MUTEX_COUNTER(m) (((m)->value >> 2) & 0xfff)
760
761#define MUTEX_TYPE_MASK 0xc000
762#define MUTEX_TYPE_NORMAL 0x0000
763#define MUTEX_TYPE_RECURSIVE 0x4000
764#define MUTEX_TYPE_ERRORCHECK 0x8000
765
766#define MUTEX_COUNTER_SHIFT 2
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700767#define MUTEX_COUNTER_MASK 0x1ffc
768#define MUTEX_SHARED_MASK 0x2000
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800769
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700770/* a mutex attribute holds the following fields
771 *
772 * bits: name description
773 * 0-3 type type of mutex
774 * 4 shared process-shared flag
775 */
776#define MUTEXATTR_TYPE_MASK 0x000f
777#define MUTEXATTR_SHARED_MASK 0x0010
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800778
779
780int pthread_mutexattr_init(pthread_mutexattr_t *attr)
781{
782 if (attr) {
783 *attr = PTHREAD_MUTEX_DEFAULT;
784 return 0;
785 } else {
786 return EINVAL;
787 }
788}
789
790int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
791{
792 if (attr) {
793 *attr = -1;
794 return 0;
795 } else {
796 return EINVAL;
797 }
798}
799
800int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
801{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700802 if (attr) {
803 int atype = (*attr & MUTEXATTR_TYPE_MASK);
804
805 if (atype >= PTHREAD_MUTEX_NORMAL &&
806 atype <= PTHREAD_MUTEX_ERRORCHECK) {
807 *type = atype;
808 return 0;
809 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800810 }
811 return EINVAL;
812}
813
814int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
815{
816 if (attr && type >= PTHREAD_MUTEX_NORMAL &&
817 type <= PTHREAD_MUTEX_ERRORCHECK ) {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700818 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800819 return 0;
820 }
821 return EINVAL;
822}
823
824/* process-shared mutexes are not supported at the moment */
825
826int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
827{
828 if (!attr)
829 return EINVAL;
830
Mathias Agopianb7681162009-07-13 22:00:33 -0700831 switch (pshared) {
832 case PTHREAD_PROCESS_PRIVATE:
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700833 *attr &= ~MUTEXATTR_SHARED_MASK;
834 return 0;
835
Mathias Agopianb7681162009-07-13 22:00:33 -0700836 case PTHREAD_PROCESS_SHARED:
837 /* our current implementation of pthread actually supports shared
838 * mutexes but won't cleanup if a process dies with the mutex held.
839 * Nevertheless, it's better than nothing. Shared mutexes are used
840 * by surfaceflinger and audioflinger.
841 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700842 *attr |= MUTEXATTR_SHARED_MASK;
Mathias Agopianb7681162009-07-13 22:00:33 -0700843 return 0;
844 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700845 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800846}
847
848int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
849{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700850 if (!attr || !pshared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800851 return EINVAL;
852
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700853 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED
854 : PTHREAD_PROCESS_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800855 return 0;
856}
857
858int pthread_mutex_init(pthread_mutex_t *mutex,
859 const pthread_mutexattr_t *attr)
860{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700861 int value = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800862
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700863 if (mutex == NULL)
864 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800865
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700866 if (__likely(attr == NULL)) {
867 mutex->value = MUTEX_TYPE_NORMAL;
868 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800869 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700870
871 if ((*attr & MUTEXATTR_SHARED_MASK) != 0)
872 value |= MUTEX_SHARED_MASK;
873
874 switch (*attr & MUTEXATTR_TYPE_MASK) {
875 case PTHREAD_MUTEX_NORMAL:
876 value |= MUTEX_TYPE_NORMAL;
877 break;
878 case PTHREAD_MUTEX_RECURSIVE:
879 value |= MUTEX_TYPE_RECURSIVE;
880 break;
881 case PTHREAD_MUTEX_ERRORCHECK:
882 value |= MUTEX_TYPE_ERRORCHECK;
883 break;
884 default:
885 return EINVAL;
886 }
887
888 mutex->value = value;
889 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800890}
891
892int pthread_mutex_destroy(pthread_mutex_t *mutex)
893{
David 'Digit' Turnera02b93b2010-06-28 14:20:22 -0700894 int ret;
895
896 /* use trylock to ensure that the mutex value is
897 * valid and is not already locked. */
898 ret = pthread_mutex_trylock(mutex);
899 if (ret != 0)
900 return ret;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700901
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800902 mutex->value = 0xdead10cc;
903 return 0;
904}
905
906
907/*
908 * Lock a non-recursive mutex.
909 *
910 * As noted above, there are three states:
911 * 0 (unlocked, no contention)
912 * 1 (locked, no contention)
913 * 2 (locked, contention)
914 *
915 * Non-recursive mutexes don't use the thread-id or counter fields, and the
916 * "type" value is zero, so the only bits that will be set are the ones in
917 * the lock state field.
918 */
919static __inline__ void
920_normal_lock(pthread_mutex_t* mutex)
921{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700922 /* We need to preserve the shared flag during operations */
923 int shared = mutex->value & MUTEX_SHARED_MASK;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800924 /*
925 * The common case is an unlocked mutex, so we begin by trying to
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100926 * change the lock's state from 0 to 1. __bionic_cmpxchg() returns 0
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800927 * if it made the swap successfully. If the result is nonzero, this
928 * lock is already held by another thread.
929 */
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100930 if (__bionic_cmpxchg(shared|0, shared|1, &mutex->value ) != 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800931 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800932 * We want to go to sleep until the mutex is available, which
933 * requires promoting it to state 2. We need to swap in the new
934 * state value and then wait until somebody wakes us up.
935 *
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100936 * __bionic_swap() returns the previous value. We swap 2 in and
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800937 * see if we got zero back; if so, we have acquired the lock. If
938 * not, another thread still holds the lock and we wait again.
939 *
940 * The second argument to the __futex_wait() call is compared
941 * against the current value. If it doesn't match, __futex_wait()
942 * returns immediately (otherwise, it sleeps for a time specified
943 * by the third argument; 0 means sleep forever). This ensures
944 * that the mutex is in state 2 when we go to sleep on it, which
945 * guarantees a wake-up call.
946 */
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100947 while (__bionic_swap(shared|2, &mutex->value ) != (shared|0))
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -0700948 __futex_wait_ex(&mutex->value, shared, shared|2, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800949 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700950 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800951}
952
953/*
954 * Release a non-recursive mutex. The caller is responsible for determining
955 * that we are in fact the owner of this lock.
956 */
957static __inline__ void
958_normal_unlock(pthread_mutex_t* mutex)
959{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700960 ANDROID_MEMBAR_FULL();
961
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700962 /* We need to preserve the shared flag during operations */
963 int shared = mutex->value & MUTEX_SHARED_MASK;
964
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800965 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700966 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100967 * to release the lock. __bionic_atomic_dec() returns the previous value;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800968 * if it wasn't 1 we have to do some additional work.
969 */
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +0100970 if (__bionic_atomic_dec(&mutex->value) != (shared|1)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800971 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800972 * Start by releasing the lock. The decrement changed it from
973 * "contended lock" to "uncontended lock", which means we still
974 * hold it, and anybody who tries to sneak in will push it back
975 * to state 2.
976 *
977 * Once we set it to zero the lock is up for grabs. We follow
978 * this with a __futex_wake() to ensure that one of the waiting
979 * threads has a chance to grab it.
980 *
981 * This doesn't cause a race with the swap/wait pair in
982 * _normal_lock(), because the __futex_wait() call there will
983 * return immediately if the mutex value isn't 2.
984 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700985 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800986
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800987 /*
988 * Wake up one waiting thread. We don't know which thread will be
989 * woken or when it'll start executing -- futexes make no guarantees
990 * here. There may not even be a thread waiting.
991 *
992 * The newly-woken thread will replace the 0 we just set above
993 * with 2, which means that when it eventually releases the mutex
994 * it will also call FUTEX_WAKE. This results in one extra wake
995 * call whenever a lock is contended, but lets us avoid forgetting
996 * anyone without requiring us to track the number of sleepers.
997 *
998 * It's possible for another thread to sneak in and grab the lock
999 * between the zero assignment above and the wake call below. If
1000 * the new thread is "slow" and holds the lock for a while, we'll
1001 * wake up a sleeper, which will swap in a 2 and then go back to
1002 * sleep since the lock is still held. If the new thread is "fast",
1003 * running to completion before we call wake, the thread we
1004 * eventually wake will find an unlocked mutex and will execute.
1005 * Either way we have correct behavior and nobody is orphaned on
1006 * the wait queue.
1007 */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001008 __futex_wake_ex(&mutex->value, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001009 }
1010}
1011
1012static pthread_mutex_t __recursive_lock = PTHREAD_MUTEX_INITIALIZER;
1013
1014static void
1015_recursive_lock(void)
1016{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001017 _normal_lock(&__recursive_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001018}
1019
1020static void
1021_recursive_unlock(void)
1022{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001023 _normal_unlock(&__recursive_lock );
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001024}
1025
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001026int pthread_mutex_lock(pthread_mutex_t *mutex)
1027{
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001028 int mtype, tid, new_lock_type, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001029
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001030 if (__unlikely(mutex == NULL))
1031 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001032
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001033 mtype = (mutex->value & MUTEX_TYPE_MASK);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001034 shared = (mutex->value & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001035
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001036 /* Handle normal case first */
1037 if ( __likely(mtype == MUTEX_TYPE_NORMAL) ) {
1038 _normal_lock(mutex);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001039 return 0;
1040 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001041
1042 /* Do we already own this recursive or error-check mutex ? */
1043 tid = __get_thread()->kernel_id;
1044 if ( tid == MUTEX_OWNER(mutex) )
1045 {
1046 int oldv, counter;
1047
1048 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1049 /* trying to re-lock a mutex we already acquired */
1050 return EDEADLK;
1051 }
1052 /*
1053 * We own the mutex, but other threads are able to change
1054 * the contents (e.g. promoting it to "contended"), so we
1055 * need to hold the global lock.
1056 */
1057 _recursive_lock();
1058 oldv = mutex->value;
1059 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1060 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1061 _recursive_unlock();
1062 return 0;
1063 }
1064
1065 /* We don't own the mutex, so try to get it.
1066 *
1067 * First, we try to change its state from 0 to 1, if this
1068 * doesn't work, try to change it to state 2.
1069 */
1070 new_lock_type = 1;
1071
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001072 /* compute futex wait opcode and restore shared flag in mtype */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001073 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001074
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001075 for (;;) {
1076 int oldv;
1077
1078 _recursive_lock();
1079 oldv = mutex->value;
1080 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1081 mutex->value = ((tid << 16) | mtype | new_lock_type);
1082 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1083 oldv ^= 3;
1084 mutex->value = oldv;
1085 }
1086 _recursive_unlock();
1087
1088 if (oldv == mtype)
1089 break;
1090
1091 /*
1092 * The lock was held, possibly contended by others. From
1093 * now on, if we manage to acquire the lock, we have to
1094 * assume that others are still contending for it so that
1095 * we'll wake them when we unlock it.
1096 */
1097 new_lock_type = 2;
1098
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001099 __futex_wait_ex(&mutex->value, shared, oldv, NULL);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001100 }
1101 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001102}
1103
1104
1105int pthread_mutex_unlock(pthread_mutex_t *mutex)
1106{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001107 int mtype, tid, oldv, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001108
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001109 if (__unlikely(mutex == NULL))
1110 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001111
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001112 mtype = (mutex->value & MUTEX_TYPE_MASK);
1113 shared = (mutex->value & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001114
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001115 /* Handle common case first */
1116 if (__likely(mtype == MUTEX_TYPE_NORMAL)) {
1117 _normal_unlock(mutex);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001118 return 0;
1119 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001120
1121 /* Do we already own this recursive or error-check mutex ? */
1122 tid = __get_thread()->kernel_id;
1123 if ( tid != MUTEX_OWNER(mutex) )
1124 return EPERM;
1125
1126 /* We do, decrement counter or release the mutex if it is 0 */
1127 _recursive_lock();
1128 oldv = mutex->value;
1129 if (oldv & MUTEX_COUNTER_MASK) {
1130 mutex->value = oldv - (1 << MUTEX_COUNTER_SHIFT);
1131 oldv = 0;
1132 } else {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001133 mutex->value = shared | mtype;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001134 }
1135 _recursive_unlock();
1136
1137 /* Wake one waiting thread, if any */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001138 if ((oldv & 3) == 2) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001139 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001140 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001141 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001142}
1143
1144
1145int pthread_mutex_trylock(pthread_mutex_t *mutex)
1146{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001147 int mtype, tid, oldv, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001148
1149 if (__unlikely(mutex == NULL))
1150 return EINVAL;
1151
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001152 mtype = (mutex->value & MUTEX_TYPE_MASK);
1153 shared = (mutex->value & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001154
1155 /* Handle common case first */
1156 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001157 {
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001158 if (__bionic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001159 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001160 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001161 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001162
1163 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001164 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001165
1166 /* Do we already own this recursive or error-check mutex ? */
1167 tid = __get_thread()->kernel_id;
1168 if ( tid == MUTEX_OWNER(mutex) )
1169 {
1170 int counter;
1171
1172 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1173 /* already locked by ourselves */
1174 return EDEADLK;
1175 }
1176
1177 _recursive_lock();
1178 oldv = mutex->value;
1179 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1180 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1181 _recursive_unlock();
1182 return 0;
1183 }
1184
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001185 /* Restore sharing bit in mtype */
1186 mtype |= shared;
1187
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001188 /* Try to lock it, just once. */
1189 _recursive_lock();
1190 oldv = mutex->value;
1191 if (oldv == mtype) /* uncontended released lock => state 1 */
1192 mutex->value = ((tid << 16) | mtype | 1);
1193 _recursive_unlock();
1194
1195 if (oldv != mtype)
1196 return EBUSY;
1197
1198 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001199}
1200
1201
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001202/* initialize 'ts' with the difference between 'abstime' and the current time
1203 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
1204 */
1205static int
1206__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
1207{
1208 clock_gettime(clock, ts);
1209 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
1210 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
1211 if (ts->tv_nsec < 0) {
1212 ts->tv_sec--;
1213 ts->tv_nsec += 1000000000;
1214 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001215 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001216 return -1;
1217
1218 return 0;
1219}
1220
1221/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1222 * milliseconds.
1223 */
1224static void
1225__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1226{
1227 clock_gettime(clock, abstime);
1228 abstime->tv_sec += msecs/1000;
1229 abstime->tv_nsec += (msecs%1000)*1000000;
1230 if (abstime->tv_nsec >= 1000000000) {
1231 abstime->tv_sec++;
1232 abstime->tv_nsec -= 1000000000;
1233 }
1234}
1235
1236int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1237{
1238 clockid_t clock = CLOCK_MONOTONIC;
1239 struct timespec abstime;
1240 struct timespec ts;
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001241 int mtype, tid, oldv, new_lock_type, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001242
1243 /* compute absolute expiration time */
1244 __timespec_to_relative_msec(&abstime, msecs, clock);
1245
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001246 if (__unlikely(mutex == NULL))
1247 return EINVAL;
1248
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001249 mtype = (mutex->value & MUTEX_TYPE_MASK);
1250 shared = (mutex->value & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001251
1252 /* Handle common case first */
1253 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001254 {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001255 /* fast path for uncontended lock */
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001256 if (__bionic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001257 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001258 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001259 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001260
1261 /* loop while needed */
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001262 while (__bionic_swap(shared|2, &mutex->value) != (shared|0)) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001263 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1264 return EBUSY;
1265
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001266 __futex_wait_ex(&mutex->value, shared, shared|2, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001267 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001268 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001269 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001270 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001271
1272 /* Do we already own this recursive or error-check mutex ? */
1273 tid = __get_thread()->kernel_id;
1274 if ( tid == MUTEX_OWNER(mutex) )
1275 {
1276 int oldv, counter;
1277
1278 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1279 /* already locked by ourselves */
1280 return EDEADLK;
1281 }
1282
1283 _recursive_lock();
1284 oldv = mutex->value;
1285 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1286 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1287 _recursive_unlock();
1288 return 0;
1289 }
1290
1291 /* We don't own the mutex, so try to get it.
1292 *
1293 * First, we try to change its state from 0 to 1, if this
1294 * doesn't work, try to change it to state 2.
1295 */
1296 new_lock_type = 1;
1297
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001298 /* Compute wait op and restore sharing bit in mtype */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001299 mtype |= shared;
1300
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001301 for (;;) {
1302 int oldv;
1303 struct timespec ts;
1304
1305 _recursive_lock();
1306 oldv = mutex->value;
1307 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1308 mutex->value = ((tid << 16) | mtype | new_lock_type);
1309 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1310 oldv ^= 3;
1311 mutex->value = oldv;
1312 }
1313 _recursive_unlock();
1314
1315 if (oldv == mtype)
1316 break;
1317
1318 /*
1319 * The lock was held, possibly contended by others. From
1320 * now on, if we manage to acquire the lock, we have to
1321 * assume that others are still contending for it so that
1322 * we'll wake them when we unlock it.
1323 */
1324 new_lock_type = 2;
1325
1326 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1327 return EBUSY;
1328
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001329 __futex_wait_ex(&mutex->value, shared, oldv, &ts);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001330 }
1331 return 0;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001332}
1333
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001334int pthread_condattr_init(pthread_condattr_t *attr)
1335{
1336 if (attr == NULL)
1337 return EINVAL;
1338
1339 *attr = PTHREAD_PROCESS_PRIVATE;
1340 return 0;
1341}
1342
1343int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1344{
1345 if (attr == NULL || pshared == NULL)
1346 return EINVAL;
1347
1348 *pshared = *attr;
1349 return 0;
1350}
1351
1352int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1353{
1354 if (attr == NULL)
1355 return EINVAL;
1356
1357 if (pshared != PTHREAD_PROCESS_SHARED &&
1358 pshared != PTHREAD_PROCESS_PRIVATE)
1359 return EINVAL;
1360
1361 *attr = pshared;
1362 return 0;
1363}
1364
1365int pthread_condattr_destroy(pthread_condattr_t *attr)
1366{
1367 if (attr == NULL)
1368 return EINVAL;
1369
1370 *attr = 0xdeada11d;
1371 return 0;
1372}
1373
1374/* We use one bit in condition variable values as the 'shared' flag
1375 * The rest is a counter.
1376 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001377#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001378#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001379#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1380
1381#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001382
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001383/* XXX *technically* there is a race condition that could allow
1384 * XXX a signal to be missed. If thread A is preempted in _wait()
1385 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001386 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001387 * XXX before thread A is scheduled again and calls futex_wait(),
1388 * XXX then the signal will be lost.
1389 */
1390
1391int pthread_cond_init(pthread_cond_t *cond,
1392 const pthread_condattr_t *attr)
1393{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001394 if (cond == NULL)
1395 return EINVAL;
1396
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001397 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001398
1399 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001400 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001401
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001402 return 0;
1403}
1404
1405int pthread_cond_destroy(pthread_cond_t *cond)
1406{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001407 if (cond == NULL)
1408 return EINVAL;
1409
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001410 cond->value = 0xdeadc04d;
1411 return 0;
1412}
1413
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001414/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001415 * pthread_cond_signal to atomically decrement the counter
1416 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001417 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001418static int
1419__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001420{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001421 long flags;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001422
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001423 if (__unlikely(cond == NULL))
1424 return EINVAL;
1425
1426 flags = (cond->value & ~COND_COUNTER_MASK);
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001427 for (;;) {
1428 long oldval = cond->value;
1429 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1430 | flags;
David 'Digit' Turnere31bfae2011-11-15 15:47:02 +01001431 if (__bionic_cmpxchg(oldval, newval, &cond->value) == 0)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001432 break;
1433 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001434
Andy McFaddene2ac8982010-09-02 13:34:53 -07001435 /*
1436 * Ensure that all memory accesses previously made by this thread are
1437 * visible to the woken thread(s). On the other side, the "wait"
1438 * code will issue any necessary barriers when locking the mutex.
1439 *
1440 * This may not strictly be necessary -- if the caller follows
1441 * recommended practice and holds the mutex before signaling the cond
1442 * var, the mutex ops will provide correct semantics. If they don't
1443 * hold the mutex, they're subject to race conditions anyway.
1444 */
1445 ANDROID_MEMBAR_FULL();
1446
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001447 __futex_wake_ex(&cond->value, COND_IS_SHARED(cond), counter);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001448 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001449}
1450
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001451int pthread_cond_broadcast(pthread_cond_t *cond)
1452{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001453 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001454}
1455
1456int pthread_cond_signal(pthread_cond_t *cond)
1457{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001458 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001459}
1460
1461int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1462{
1463 return pthread_cond_timedwait(cond, mutex, NULL);
1464}
1465
1466int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1467 pthread_mutex_t * mutex,
1468 const struct timespec *reltime)
1469{
1470 int status;
1471 int oldvalue = cond->value;
1472
1473 pthread_mutex_unlock(mutex);
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001474 status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond), oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001475 pthread_mutex_lock(mutex);
1476
1477 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1478 return 0;
1479}
1480
1481int __pthread_cond_timedwait(pthread_cond_t *cond,
1482 pthread_mutex_t * mutex,
1483 const struct timespec *abstime,
1484 clockid_t clock)
1485{
1486 struct timespec ts;
1487 struct timespec * tsp;
1488
1489 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001490 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001491 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001492 tsp = &ts;
1493 } else {
1494 tsp = NULL;
1495 }
1496
1497 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1498}
1499
1500int pthread_cond_timedwait(pthread_cond_t *cond,
1501 pthread_mutex_t * mutex,
1502 const struct timespec *abstime)
1503{
1504 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1505}
1506
1507
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001508/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001509int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1510 pthread_mutex_t * mutex,
1511 const struct timespec *abstime)
1512{
1513 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1514}
1515
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001516int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1517 pthread_mutex_t * mutex,
1518 const struct timespec *abstime)
1519{
1520 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1521}
1522
1523int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1524 pthread_mutex_t * mutex,
1525 const struct timespec *reltime)
1526{
1527 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1528}
1529
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001530int pthread_cond_timeout_np(pthread_cond_t *cond,
1531 pthread_mutex_t * mutex,
1532 unsigned msecs)
1533{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001534 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001535
1536 ts.tv_sec = msecs / 1000;
1537 ts.tv_nsec = (msecs % 1000) * 1000000;
1538
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001539 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001540}
1541
1542
1543
1544/* A technical note regarding our thread-local-storage (TLS) implementation:
1545 *
1546 * There can be up to TLSMAP_SIZE independent TLS keys in a given process,
1547 * though the first TLSMAP_START keys are reserved for Bionic to hold
1548 * special thread-specific variables like errno or a pointer to
1549 * the current thread's descriptor.
1550 *
1551 * while stored in the TLS area, these entries cannot be accessed through
1552 * pthread_getspecific() / pthread_setspecific() and pthread_key_delete()
1553 *
1554 * also, some entries in the key table are pre-allocated (see tlsmap_lock)
1555 * to greatly simplify and speedup some OpenGL-related operations. though the
1556 * initialy value will be NULL on all threads.
1557 *
1558 * you can use pthread_getspecific()/setspecific() on these, and in theory
1559 * you could also call pthread_key_delete() as well, though this would
1560 * probably break some apps.
1561 *
1562 * The 'tlsmap_t' type defined below implements a shared global map of
1563 * currently created/allocated TLS keys and the destructors associated
1564 * with them. You should use tlsmap_lock/unlock to access it to avoid
1565 * any race condition.
1566 *
1567 * the global TLS map simply contains a bitmap of allocated keys, and
1568 * an array of destructors.
1569 *
1570 * each thread has a TLS area that is a simple array of TLSMAP_SIZE void*
1571 * pointers. the TLS area of the main thread is stack-allocated in
1572 * __libc_init_common, while the TLS area of other threads is placed at
1573 * the top of their stack in pthread_create.
1574 *
1575 * when pthread_key_create() is called, it finds the first free key in the
1576 * bitmap, then set it to 1, saving the destructor altogether
1577 *
1578 * when pthread_key_delete() is called. it will erase the key's bitmap bit
1579 * and its destructor, and will also clear the key data in the TLS area of
1580 * all created threads. As mandated by Posix, it is the responsability of
1581 * the caller of pthread_key_delete() to properly reclaim the objects that
1582 * were pointed to by these data fields (either before or after the call).
1583 *
1584 */
1585
1586/* TLS Map implementation
1587 */
1588
1589#define TLSMAP_START (TLS_SLOT_MAX_WELL_KNOWN+1)
1590#define TLSMAP_SIZE BIONIC_TLS_SLOTS
1591#define TLSMAP_BITS 32
1592#define TLSMAP_WORDS ((TLSMAP_SIZE+TLSMAP_BITS-1)/TLSMAP_BITS)
1593#define TLSMAP_WORD(m,k) (m)->map[(k)/TLSMAP_BITS]
1594#define TLSMAP_MASK(k) (1U << ((k)&(TLSMAP_BITS-1)))
1595
1596/* this macro is used to quickly check that a key belongs to a reasonable range */
1597#define TLSMAP_VALIDATE_KEY(key) \
1598 ((key) >= TLSMAP_START && (key) < TLSMAP_SIZE)
1599
1600/* the type of tls key destructor functions */
1601typedef void (*tls_dtor_t)(void*);
1602
1603typedef struct {
1604 int init; /* see comment in tlsmap_lock() */
1605 uint32_t map[TLSMAP_WORDS]; /* bitmap of allocated keys */
1606 tls_dtor_t dtors[TLSMAP_SIZE]; /* key destructors */
1607} tlsmap_t;
1608
1609static pthread_mutex_t _tlsmap_lock = PTHREAD_MUTEX_INITIALIZER;
1610static tlsmap_t _tlsmap;
1611
1612/* lock the global TLS map lock and return a handle to it */
1613static __inline__ tlsmap_t* tlsmap_lock(void)
1614{
1615 tlsmap_t* m = &_tlsmap;
1616
1617 pthread_mutex_lock(&_tlsmap_lock);
1618 /* we need to initialize the first entry of the 'map' array
1619 * with the value TLS_DEFAULT_ALLOC_MAP. doing it statically
1620 * when declaring _tlsmap is a bit awkward and is going to
1621 * produce warnings, so do it the first time we use the map
1622 * instead
1623 */
1624 if (__unlikely(!m->init)) {
1625 TLSMAP_WORD(m,0) = TLS_DEFAULT_ALLOC_MAP;
1626 m->init = 1;
1627 }
1628 return m;
1629}
1630
1631/* unlock the global TLS map */
1632static __inline__ void tlsmap_unlock(tlsmap_t* m)
1633{
1634 pthread_mutex_unlock(&_tlsmap_lock);
1635 (void)m; /* a good compiler is a happy compiler */
1636}
1637
1638/* test to see wether a key is allocated */
1639static __inline__ int tlsmap_test(tlsmap_t* m, int key)
1640{
1641 return (TLSMAP_WORD(m,key) & TLSMAP_MASK(key)) != 0;
1642}
1643
1644/* set the destructor and bit flag on a newly allocated key */
1645static __inline__ void tlsmap_set(tlsmap_t* m, int key, tls_dtor_t dtor)
1646{
1647 TLSMAP_WORD(m,key) |= TLSMAP_MASK(key);
1648 m->dtors[key] = dtor;
1649}
1650
1651/* clear the destructor and bit flag on an existing key */
1652static __inline__ void tlsmap_clear(tlsmap_t* m, int key)
1653{
1654 TLSMAP_WORD(m,key) &= ~TLSMAP_MASK(key);
1655 m->dtors[key] = NULL;
1656}
1657
1658/* allocate a new TLS key, return -1 if no room left */
1659static int tlsmap_alloc(tlsmap_t* m, tls_dtor_t dtor)
1660{
1661 int key;
1662
1663 for ( key = TLSMAP_START; key < TLSMAP_SIZE; key++ ) {
1664 if ( !tlsmap_test(m, key) ) {
1665 tlsmap_set(m, key, dtor);
1666 return key;
1667 }
1668 }
1669 return -1;
1670}
1671
1672
1673int pthread_key_create(pthread_key_t *key, void (*destructor_function)(void *))
1674{
1675 uint32_t err = ENOMEM;
1676 tlsmap_t* map = tlsmap_lock();
1677 int k = tlsmap_alloc(map, destructor_function);
1678
1679 if (k >= 0) {
1680 *key = k;
1681 err = 0;
1682 }
1683 tlsmap_unlock(map);
1684 return err;
1685}
1686
1687
1688/* This deletes a pthread_key_t. note that the standard mandates that this does
1689 * not call the destructor of non-NULL key values. Instead, it is the
1690 * responsability of the caller to properly dispose of the corresponding data
1691 * and resources, using any mean it finds suitable.
1692 *
1693 * On the other hand, this function will clear the corresponding key data
1694 * values in all known threads. this prevents later (invalid) calls to
1695 * pthread_getspecific() to receive invalid/stale values.
1696 */
1697int pthread_key_delete(pthread_key_t key)
1698{
1699 uint32_t err;
1700 pthread_internal_t* thr;
1701 tlsmap_t* map;
1702
1703 if (!TLSMAP_VALIDATE_KEY(key)) {
1704 return EINVAL;
1705 }
1706
1707 map = tlsmap_lock();
1708
1709 if (!tlsmap_test(map, key)) {
1710 err = EINVAL;
1711 goto err1;
1712 }
1713
1714 /* clear value in all threads */
1715 pthread_mutex_lock(&gThreadListLock);
1716 for ( thr = gThreadList; thr != NULL; thr = thr->next ) {
1717 /* avoid zombie threads with a negative 'join_count'. these are really
1718 * already dead and don't have a TLS area anymore.
1719 *
1720 * similarly, it is possible to have thr->tls == NULL for threads that
1721 * were just recently created through pthread_create() but whose
1722 * startup trampoline (__thread_entry) hasn't been run yet by the
1723 * scheduler. so check for this too.
1724 */
1725 if (thr->join_count < 0 || !thr->tls)
1726 continue;
1727
1728 thr->tls[key] = NULL;
1729 }
1730 tlsmap_clear(map, key);
1731
1732 pthread_mutex_unlock(&gThreadListLock);
1733 err = 0;
1734
1735err1:
1736 tlsmap_unlock(map);
1737 return err;
1738}
1739
1740
1741int pthread_setspecific(pthread_key_t key, const void *ptr)
1742{
1743 int err = EINVAL;
1744 tlsmap_t* map;
1745
1746 if (TLSMAP_VALIDATE_KEY(key)) {
1747 /* check that we're trying to set data for an allocated key */
1748 map = tlsmap_lock();
1749 if (tlsmap_test(map, key)) {
1750 ((uint32_t *)__get_tls())[key] = (uint32_t)ptr;
1751 err = 0;
1752 }
1753 tlsmap_unlock(map);
1754 }
1755 return err;
1756}
1757
1758void * pthread_getspecific(pthread_key_t key)
1759{
1760 if (!TLSMAP_VALIDATE_KEY(key)) {
1761 return NULL;
1762 }
1763
1764 /* for performance reason, we do not lock/unlock the global TLS map
1765 * to check that the key is properly allocated. if the key was not
1766 * allocated, the value read from the TLS should always be NULL
1767 * due to pthread_key_delete() clearing the values for all threads.
1768 */
1769 return (void *)(((unsigned *)__get_tls())[key]);
1770}
1771
1772/* Posix mandates that this be defined in <limits.h> but we don't have
1773 * it just yet.
1774 */
1775#ifndef PTHREAD_DESTRUCTOR_ITERATIONS
1776# define PTHREAD_DESTRUCTOR_ITERATIONS 4
1777#endif
1778
1779/* this function is called from pthread_exit() to remove all TLS key data
1780 * from this thread's TLS area. this must call the destructor of all keys
1781 * that have a non-NULL data value (and a non-NULL destructor).
1782 *
1783 * because destructors can do funky things like deleting/creating other
1784 * keys, we need to implement this in a loop
1785 */
1786static void pthread_key_clean_all(void)
1787{
1788 tlsmap_t* map;
1789 void** tls = (void**)__get_tls();
1790 int rounds = PTHREAD_DESTRUCTOR_ITERATIONS;
1791
1792 map = tlsmap_lock();
1793
1794 for (rounds = PTHREAD_DESTRUCTOR_ITERATIONS; rounds > 0; rounds--)
1795 {
1796 int kk, count = 0;
1797
1798 for (kk = TLSMAP_START; kk < TLSMAP_SIZE; kk++) {
1799 if ( tlsmap_test(map, kk) )
1800 {
1801 void* data = tls[kk];
1802 tls_dtor_t dtor = map->dtors[kk];
1803
1804 if (data != NULL && dtor != NULL)
1805 {
1806 /* we need to clear the key data now, this will prevent the
1807 * destructor (or a later one) from seeing the old value if
1808 * it calls pthread_getspecific() for some odd reason
1809 *
1810 * we do not do this if 'dtor == NULL' just in case another
1811 * destructor function might be responsible for manually
1812 * releasing the corresponding data.
1813 */
1814 tls[kk] = NULL;
1815
1816 /* because the destructor is free to call pthread_key_create
1817 * and/or pthread_key_delete, we need to temporarily unlock
1818 * the TLS map
1819 */
1820 tlsmap_unlock(map);
1821 (*dtor)(data);
1822 map = tlsmap_lock();
1823
1824 count += 1;
1825 }
1826 }
1827 }
1828
1829 /* if we didn't call any destructor, there is no need to check the
1830 * TLS data again
1831 */
1832 if (count == 0)
1833 break;
1834 }
1835 tlsmap_unlock(map);
1836}
1837
1838// man says this should be in <linux/unistd.h>, but it isn't
1839extern int tkill(int tid, int sig);
1840
1841int pthread_kill(pthread_t tid, int sig)
1842{
1843 int ret;
1844 int old_errno = errno;
1845 pthread_internal_t * thread = (pthread_internal_t *)tid;
1846
1847 ret = tkill(thread->kernel_id, sig);
1848 if (ret < 0) {
1849 ret = errno;
1850 errno = old_errno;
1851 }
1852
1853 return ret;
1854}
1855
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001856/* Despite the fact that our kernel headers define sigset_t explicitly
1857 * as a 32-bit integer, the kernel system call really expects a 64-bit
1858 * bitmap for the signal set, or more exactly an array of two-32-bit
1859 * values (see $KERNEL/arch/$ARCH/include/asm/signal.h for details).
1860 *
1861 * Unfortunately, we cannot fix the sigset_t definition without breaking
1862 * the C library ABI, so perform a little runtime translation here.
1863 */
1864typedef union {
1865 sigset_t bionic;
1866 uint32_t kernel[2];
1867} kernel_sigset_t;
1868
1869/* this is a private syscall stub */
1870extern int __rt_sigprocmask(int, const kernel_sigset_t *, kernel_sigset_t *, size_t);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001871
1872int pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
1873{
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001874 /* pthread_sigmask must return the error code, but the syscall
1875 * will set errno instead and return 0/-1
1876 */
1877 int ret, old_errno = errno;
1878
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001879 /* We must convert *set into a kernel_sigset_t */
1880 kernel_sigset_t in_set, *in_set_ptr;
1881 kernel_sigset_t out_set;
1882
1883 in_set.kernel[0] = in_set.kernel[1] = 0;
1884 out_set.kernel[0] = out_set.kernel[1] = 0;
1885
1886 /* 'in_set_ptr' is the second parameter to __rt_sigprocmask. It must be NULL
1887 * if 'set' is NULL to ensure correct semantics (which in this case would
1888 * be to ignore 'how' and return the current signal set into 'oset'.
David 'Digit' Turner5c8c00a2010-12-20 15:58:06 +01001889 */
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001890 if (set == NULL) {
1891 in_set_ptr = NULL;
1892 } else {
1893 in_set.bionic = *set;
1894 in_set_ptr = &in_set;
1895 }
1896
1897 ret = __rt_sigprocmask(how, in_set_ptr, &out_set, sizeof(kernel_sigset_t));
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001898 if (ret < 0)
1899 ret = errno;
1900
David 'Digit' Turner9bf330b2011-11-14 12:57:47 +01001901 if (oset)
1902 *oset = out_set.bionic;
1903
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001904 errno = old_errno;
1905 return ret;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001906}
1907
1908
1909int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
1910{
1911 const int CLOCK_IDTYPE_BITS = 3;
1912 pthread_internal_t* thread = (pthread_internal_t*)tid;
1913
1914 if (!thread)
1915 return ESRCH;
1916
1917 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
1918 return 0;
1919}
1920
1921
1922/* NOTE: this implementation doesn't support a init function that throws a C++ exception
1923 * or calls fork()
1924 */
1925int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
1926{
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001927 static pthread_mutex_t once_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001928 volatile pthread_once_t* ocptr = once_control;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001929
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001930 pthread_once_t tmp = *ocptr;
1931 ANDROID_MEMBAR_FULL();
1932 if (tmp == PTHREAD_ONCE_INIT) {
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001933 pthread_mutex_lock( &once_lock );
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001934 if (*ocptr == PTHREAD_ONCE_INIT) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001935 (*init_routine)();
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001936 ANDROID_MEMBAR_FULL();
1937 *ocptr = ~PTHREAD_ONCE_INIT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001938 }
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001939 pthread_mutex_unlock( &once_lock );
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001940 }
1941 return 0;
1942}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03001943
1944/* This value is not exported by kernel headers, so hardcode it here */
1945#define MAX_TASK_COMM_LEN 16
1946#define TASK_COMM_FMT "/proc/self/task/%u/comm"
1947
1948int pthread_setname_np(pthread_t thid, const char *thname)
1949{
1950 size_t thname_len;
1951 int saved_errno, ret;
1952
1953 if (thid == 0 || thname == NULL)
1954 return EINVAL;
1955
1956 thname_len = strlen(thname);
1957 if (thname_len >= MAX_TASK_COMM_LEN)
1958 return ERANGE;
1959
1960 saved_errno = errno;
1961 if (thid == pthread_self())
1962 {
1963 ret = prctl(PR_SET_NAME, (unsigned long)thname, 0, 0, 0) ? errno : 0;
1964 }
1965 else
1966 {
1967 /* Have to change another thread's name */
1968 pthread_internal_t *thread = (pthread_internal_t *)thid;
1969 char comm_name[sizeof(TASK_COMM_FMT) + 8];
1970 ssize_t n;
1971 int fd;
1972
1973 snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, (unsigned int)thread->kernel_id);
1974 fd = open(comm_name, O_RDWR);
1975 if (fd == -1)
1976 {
1977 ret = errno;
1978 goto exit;
1979 }
1980 n = TEMP_FAILURE_RETRY(write(fd, thname, thname_len));
1981 close(fd);
1982
1983 if (n < 0)
1984 ret = errno;
1985 else if ((size_t)n != thname_len)
1986 ret = EIO;
1987 else
1988 ret = 0;
1989 }
1990exit:
1991 errno = saved_errno;
1992 return ret;
1993}
Glenn Kastend53cae02011-07-11 15:41:28 -07001994
1995/* Return the kernel thread ID for a pthread.
1996 * This is only defined for implementations where pthread <-> kernel is 1:1, which this is.
1997 * Not the same as pthread_getthreadid_np, which is commonly defined to be opaque.
1998 * Internal, not an NDK API.
1999 */
2000
2001pid_t __pthread_gettid(pthread_t thid)
2002{
2003 pthread_internal_t* thread = (pthread_internal_t*)thid;
2004 return thread->kernel_id;
2005}