blob: 6fd47f270a38d1e81d2ebaffac3fea3dc678ae35 [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' Turner88f06cd2010-03-18 17:13:41 -070046#include <linux/futex.h>
Andy McFaddenfcd00eb2010-05-28 13:31:45 -070047#include <cutils/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>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080051
52extern int __pthread_clone(int (*fn)(void*), void *child_stack, int flags, void *arg);
53extern void _exit_with_stack_teardown(void * stackBase, int stackSize, int retCode);
54extern void _exit_thread(int retCode);
55extern int __set_errno(int);
56
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -070057#define __likely(cond) __builtin_expect(!!(cond), 1)
58#define __unlikely(cond) __builtin_expect(!!(cond), 0)
59
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080060void _thread_created_hook(pid_t thread_id) __attribute__((noinline));
61
62#define PTHREAD_ATTR_FLAG_DETACHED 0x00000001
63#define PTHREAD_ATTR_FLAG_USER_STACK 0x00000002
64
65#define DEFAULT_STACKSIZE (1024 * 1024)
66#define STACKBASE 0x10000000
67
68static uint8_t * gStackBase = (uint8_t *)STACKBASE;
69
70static pthread_mutex_t mmap_lock = PTHREAD_MUTEX_INITIALIZER;
71
72
73static const pthread_attr_t gDefaultPthreadAttr = {
74 .flags = 0,
75 .stack_base = NULL,
76 .stack_size = DEFAULT_STACKSIZE,
77 .guard_size = PAGE_SIZE,
78 .sched_policy = SCHED_NORMAL,
79 .sched_priority = 0
80};
81
82#define INIT_THREADS 1
83
84static pthread_internal_t* gThreadList = NULL;
85static pthread_mutex_t gThreadListLock = PTHREAD_MUTEX_INITIALIZER;
86static pthread_mutex_t gDebuggerNotificationLock = PTHREAD_MUTEX_INITIALIZER;
87
88
89/* we simply malloc/free the internal pthread_internal_t structures. we may
90 * want to use a different allocation scheme in the future, but this one should
91 * be largely enough
92 */
93static pthread_internal_t*
94_pthread_internal_alloc(void)
95{
96 pthread_internal_t* thread;
97
98 thread = calloc( sizeof(*thread), 1 );
99 if (thread)
100 thread->intern = 1;
101
102 return thread;
103}
104
105static void
106_pthread_internal_free( pthread_internal_t* thread )
107{
108 if (thread && thread->intern) {
109 thread->intern = 0; /* just in case */
110 free (thread);
111 }
112}
113
114
115static void
116_pthread_internal_remove_locked( pthread_internal_t* thread )
117{
118 thread->next->pref = thread->pref;
119 thread->pref[0] = thread->next;
120}
121
122static void
123_pthread_internal_remove( pthread_internal_t* thread )
124{
125 pthread_mutex_lock(&gThreadListLock);
126 _pthread_internal_remove_locked(thread);
127 pthread_mutex_unlock(&gThreadListLock);
128}
129
130static void
131_pthread_internal_add( pthread_internal_t* thread )
132{
133 pthread_mutex_lock(&gThreadListLock);
134 thread->pref = &gThreadList;
135 thread->next = thread->pref[0];
136 if (thread->next)
137 thread->next->pref = &thread->next;
138 thread->pref[0] = thread;
139 pthread_mutex_unlock(&gThreadListLock);
140}
141
142pthread_internal_t*
143__get_thread(void)
144{
145 void** tls = (void**)__get_tls();
146
147 return (pthread_internal_t*) tls[TLS_SLOT_THREAD_ID];
148}
149
150
151void*
152__get_stack_base(int *p_stack_size)
153{
154 pthread_internal_t* thread = __get_thread();
155
156 *p_stack_size = thread->attr.stack_size;
157 return thread->attr.stack_base;
158}
159
160
161void __init_tls(void** tls, void* thread)
162{
163 int nn;
164
165 ((pthread_internal_t*)thread)->tls = tls;
166
167 // slot 0 must point to the tls area, this is required by the implementation
168 // of the x86 Linux kernel thread-local-storage
169 tls[TLS_SLOT_SELF] = (void*)tls;
170 tls[TLS_SLOT_THREAD_ID] = thread;
171 for (nn = TLS_SLOT_ERRNO; nn < BIONIC_TLS_SLOTS; nn++)
172 tls[nn] = 0;
173
174 __set_tls( (void*)tls );
175}
176
177
178/*
179 * This trampoline is called from the assembly clone() function
180 */
181void __thread_entry(int (*func)(void*), void *arg, void **tls)
182{
183 int retValue;
184 pthread_internal_t * thrInfo;
185
186 // Wait for our creating thread to release us. This lets it have time to
187 // notify gdb about this thread before it starts doing anything.
188 pthread_mutex_t * start_mutex = (pthread_mutex_t *)&tls[TLS_SLOT_SELF];
189 pthread_mutex_lock(start_mutex);
190 pthread_mutex_destroy(start_mutex);
191
192 thrInfo = (pthread_internal_t *) tls[TLS_SLOT_THREAD_ID];
193
194 __init_tls( tls, thrInfo );
195
196 pthread_exit( (void*)func(arg) );
197}
198
199void _init_thread(pthread_internal_t * thread, pid_t kernel_id, pthread_attr_t * attr, void * stack_base)
200{
201 if (attr == NULL) {
202 thread->attr = gDefaultPthreadAttr;
203 } else {
204 thread->attr = *attr;
205 }
206 thread->attr.stack_base = stack_base;
207 thread->kernel_id = kernel_id;
208
209 // set the scheduling policy/priority of the thread
210 if (thread->attr.sched_policy != SCHED_NORMAL) {
211 struct sched_param param;
212 param.sched_priority = thread->attr.sched_priority;
213 sched_setscheduler(kernel_id, thread->attr.sched_policy, &param);
214 }
215
216 pthread_cond_init(&thread->join_cond, NULL);
217 thread->join_count = 0;
218
219 thread->cleanup_stack = NULL;
220
221 _pthread_internal_add(thread);
222}
223
224
225/* XXX stacks not reclaimed if thread spawn fails */
226/* XXX stacks address spaces should be reused if available again */
227
228static void *mkstack(size_t size, size_t guard_size)
229{
230 void * stack;
231
232 pthread_mutex_lock(&mmap_lock);
233
234 stack = mmap((void *)gStackBase, size,
235 PROT_READ | PROT_WRITE,
236 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
237 -1, 0);
238
239 if(stack == MAP_FAILED) {
240 stack = NULL;
241 goto done;
242 }
243
244 if(mprotect(stack, guard_size, PROT_NONE)){
245 munmap(stack, size);
246 stack = NULL;
247 goto done;
248 }
249
250done:
251 pthread_mutex_unlock(&mmap_lock);
252 return stack;
253}
254
255/*
256 * Create a new thread. The thread's stack is layed out like so:
257 *
258 * +---------------------------+
259 * | pthread_internal_t |
260 * +---------------------------+
261 * | |
262 * | TLS area |
263 * | |
264 * +---------------------------+
265 * | |
266 * . .
267 * . stack area .
268 * . .
269 * | |
270 * +---------------------------+
271 * | guard page |
272 * +---------------------------+
273 *
274 * note that TLS[0] must be a pointer to itself, this is required
275 * by the thread-local storage implementation of the x86 Linux
276 * kernel, where the TLS pointer is read by reading fs:[0]
277 */
278int pthread_create(pthread_t *thread_out, pthread_attr_t const * attr,
279 void *(*start_routine)(void *), void * arg)
280{
281 char* stack;
282 void** tls;
283 int tid;
284 pthread_mutex_t * start_mutex;
285 pthread_internal_t * thread;
286 int madestack = 0;
287 int old_errno = errno;
288
289 /* this will inform the rest of the C library that at least one thread
290 * was created. this will enforce certain functions to acquire/release
291 * locks (e.g. atexit()) to protect shared global structures.
292 *
293 * this works because pthread_create() is not called by the C library
294 * initialization routine that sets up the main thread's data structures.
295 */
296 __isthreaded = 1;
297
298 thread = _pthread_internal_alloc();
299 if (thread == NULL)
300 return ENOMEM;
301
302 if (attr == NULL) {
303 attr = &gDefaultPthreadAttr;
304 }
305
306 // make sure the stack is PAGE_SIZE aligned
307 size_t stackSize = (attr->stack_size +
308 (PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
309
310 if (!attr->stack_base) {
311 stack = mkstack(stackSize, attr->guard_size);
312 if(stack == NULL) {
313 _pthread_internal_free(thread);
314 return ENOMEM;
315 }
316 madestack = 1;
317 } else {
318 stack = attr->stack_base;
319 }
320
321 // Make room for TLS
322 tls = (void**)(stack + stackSize - BIONIC_TLS_SLOTS*sizeof(void*));
323
324 // Create a mutex for the thread in TLS_SLOT_SELF to wait on once it starts so we can keep
325 // it from doing anything until after we notify the debugger about it
326 start_mutex = (pthread_mutex_t *) &tls[TLS_SLOT_SELF];
327 pthread_mutex_init(start_mutex, NULL);
328 pthread_mutex_lock(start_mutex);
329
330 tls[TLS_SLOT_THREAD_ID] = thread;
331
332 tid = __pthread_clone((int(*)(void*))start_routine, tls,
333 CLONE_FILES | CLONE_FS | CLONE_VM | CLONE_SIGHAND
334 | CLONE_THREAD | CLONE_SYSVSEM | CLONE_DETACHED,
335 arg);
336
337 if(tid < 0) {
338 int result;
339 if (madestack)
340 munmap(stack, stackSize);
341 _pthread_internal_free(thread);
342 result = errno;
343 errno = old_errno;
344 return result;
345 }
346
347 _init_thread(thread, tid, (pthread_attr_t*)attr, stack);
348
349 if (!madestack)
350 thread->attr.flags |= PTHREAD_ATTR_FLAG_USER_STACK;
351
352 // Notify any debuggers about the new thread
353 pthread_mutex_lock(&gDebuggerNotificationLock);
354 _thread_created_hook(tid);
355 pthread_mutex_unlock(&gDebuggerNotificationLock);
356
357 // Let the thread do it's thing
358 pthread_mutex_unlock(start_mutex);
359
360 *thread_out = (pthread_t)thread;
361 return 0;
362}
363
364
365int pthread_attr_init(pthread_attr_t * attr)
366{
367 *attr = gDefaultPthreadAttr;
368 return 0;
369}
370
371int pthread_attr_destroy(pthread_attr_t * attr)
372{
373 memset(attr, 0x42, sizeof(pthread_attr_t));
374 return 0;
375}
376
377int pthread_attr_setdetachstate(pthread_attr_t * attr, int state)
378{
379 if (state == PTHREAD_CREATE_DETACHED) {
380 attr->flags |= PTHREAD_ATTR_FLAG_DETACHED;
381 } else if (state == PTHREAD_CREATE_JOINABLE) {
382 attr->flags &= ~PTHREAD_ATTR_FLAG_DETACHED;
383 } else {
384 return EINVAL;
385 }
386 return 0;
387}
388
389int pthread_attr_getdetachstate(pthread_attr_t const * attr, int * state)
390{
391 *state = (attr->flags & PTHREAD_ATTR_FLAG_DETACHED)
392 ? PTHREAD_CREATE_DETACHED
393 : PTHREAD_CREATE_JOINABLE;
394 return 0;
395}
396
397int pthread_attr_setschedpolicy(pthread_attr_t * attr, int policy)
398{
399 attr->sched_policy = policy;
400 return 0;
401}
402
403int pthread_attr_getschedpolicy(pthread_attr_t const * attr, int * policy)
404{
405 *policy = attr->sched_policy;
406 return 0;
407}
408
409int pthread_attr_setschedparam(pthread_attr_t * attr, struct sched_param const * param)
410{
411 attr->sched_priority = param->sched_priority;
412 return 0;
413}
414
415int pthread_attr_getschedparam(pthread_attr_t const * attr, struct sched_param * param)
416{
417 param->sched_priority = attr->sched_priority;
418 return 0;
419}
420
421int pthread_attr_setstacksize(pthread_attr_t * attr, size_t stack_size)
422{
423 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
424 return EINVAL;
425 }
426 attr->stack_size = stack_size;
427 return 0;
428}
429
430int pthread_attr_getstacksize(pthread_attr_t const * attr, size_t * stack_size)
431{
432 *stack_size = attr->stack_size;
433 return 0;
434}
435
436int pthread_attr_setstackaddr(pthread_attr_t * attr, void * stack_addr)
437{
438#if 1
439 // It's not clear if this is setting the top or bottom of the stack, so don't handle it for now.
440 return ENOSYS;
441#else
442 if ((uint32_t)stack_addr & (PAGE_SIZE - 1)) {
443 return EINVAL;
444 }
445 attr->stack_base = stack_addr;
446 return 0;
447#endif
448}
449
450int pthread_attr_getstackaddr(pthread_attr_t const * attr, void ** stack_addr)
451{
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700452 *stack_addr = (char*)attr->stack_base + attr->stack_size;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800453 return 0;
454}
455
456int pthread_attr_setstack(pthread_attr_t * attr, void * stack_base, size_t stack_size)
457{
458 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
459 return EINVAL;
460 }
461 if ((uint32_t)stack_base & (PAGE_SIZE - 1)) {
462 return EINVAL;
463 }
464 attr->stack_base = stack_base;
465 attr->stack_size = stack_size;
466 return 0;
467}
468
469int pthread_attr_getstack(pthread_attr_t const * attr, void ** stack_base, size_t * stack_size)
470{
471 *stack_base = attr->stack_base;
472 *stack_size = attr->stack_size;
473 return 0;
474}
475
476int pthread_attr_setguardsize(pthread_attr_t * attr, size_t guard_size)
477{
478 if (guard_size & (PAGE_SIZE - 1) || guard_size < PAGE_SIZE) {
479 return EINVAL;
480 }
481
482 attr->guard_size = guard_size;
483 return 0;
484}
485
486int pthread_attr_getguardsize(pthread_attr_t const * attr, size_t * guard_size)
487{
488 *guard_size = attr->guard_size;
489 return 0;
490}
491
492int pthread_getattr_np(pthread_t thid, pthread_attr_t * attr)
493{
494 pthread_internal_t * thread = (pthread_internal_t *)thid;
495 *attr = thread->attr;
496 return 0;
497}
498
499int pthread_attr_setscope(pthread_attr_t *attr, int scope)
500{
501 if (scope == PTHREAD_SCOPE_SYSTEM)
502 return 0;
503 if (scope == PTHREAD_SCOPE_PROCESS)
504 return ENOTSUP;
505
506 return EINVAL;
507}
508
509int pthread_attr_getscope(pthread_attr_t const *attr)
510{
511 return PTHREAD_SCOPE_SYSTEM;
512}
513
514
515/* CAVEAT: our implementation of pthread_cleanup_push/pop doesn't support C++ exceptions
516 * and thread cancelation
517 */
518
519void __pthread_cleanup_push( __pthread_cleanup_t* c,
520 __pthread_cleanup_func_t routine,
521 void* arg )
522{
523 pthread_internal_t* thread = __get_thread();
524
525 c->__cleanup_routine = routine;
526 c->__cleanup_arg = arg;
527 c->__cleanup_prev = thread->cleanup_stack;
528 thread->cleanup_stack = c;
529}
530
531void __pthread_cleanup_pop( __pthread_cleanup_t* c, int execute )
532{
533 pthread_internal_t* thread = __get_thread();
534
535 thread->cleanup_stack = c->__cleanup_prev;
536 if (execute)
537 c->__cleanup_routine(c->__cleanup_arg);
538}
539
540/* used by pthread_exit() to clean all TLS keys of the current thread */
541static void pthread_key_clean_all(void);
542
543void pthread_exit(void * retval)
544{
545 pthread_internal_t* thread = __get_thread();
546 void* stack_base = thread->attr.stack_base;
547 int stack_size = thread->attr.stack_size;
548 int user_stack = (thread->attr.flags & PTHREAD_ATTR_FLAG_USER_STACK) != 0;
549
550 // call the cleanup handlers first
551 while (thread->cleanup_stack) {
552 __pthread_cleanup_t* c = thread->cleanup_stack;
553 thread->cleanup_stack = c->__cleanup_prev;
554 c->__cleanup_routine(c->__cleanup_arg);
555 }
556
557 // call the TLS destructors, it is important to do that before removing this
558 // thread from the global list. this will ensure that if someone else deletes
559 // a TLS key, the corresponding value will be set to NULL in this thread's TLS
560 // space (see pthread_key_delete)
561 pthread_key_clean_all();
562
563 // if the thread is detached, destroy the pthread_internal_t
564 // otherwise, keep it in memory and signal any joiners
565 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
566 _pthread_internal_remove(thread);
567 _pthread_internal_free(thread);
568 } else {
569 /* the join_count field is used to store the number of threads waiting for
570 * the termination of this thread with pthread_join(),
571 *
572 * if it is positive we need to signal the waiters, and we do not touch
573 * the count (it will be decremented by the waiters, the last one will
574 * also remove/free the thread structure
575 *
576 * if it is zero, we set the count value to -1 to indicate that the
577 * thread is in 'zombie' state: it has stopped executing, and its stack
578 * is gone (as well as its TLS area). when another thread calls pthread_join()
579 * on it, it will immediately free the thread and return.
580 */
581 pthread_mutex_lock(&gThreadListLock);
582 thread->return_value = retval;
583 if (thread->join_count > 0) {
584 pthread_cond_broadcast(&thread->join_cond);
585 } else {
586 thread->join_count = -1; /* zombie thread */
587 }
588 pthread_mutex_unlock(&gThreadListLock);
589 }
590
591 // destroy the thread stack
592 if (user_stack)
593 _exit_thread((int)retval);
594 else
595 _exit_with_stack_teardown(stack_base, stack_size, (int)retval);
596}
597
598int pthread_join(pthread_t thid, void ** ret_val)
599{
600 pthread_internal_t* thread = (pthread_internal_t*)thid;
601 int count;
602
603 // check that the thread still exists and is not detached
604 pthread_mutex_lock(&gThreadListLock);
605
606 for (thread = gThreadList; thread != NULL; thread = thread->next)
607 if (thread == (pthread_internal_t*)thid)
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200608 goto FoundIt;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800609
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200610 pthread_mutex_unlock(&gThreadListLock);
611 return ESRCH;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800612
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200613FoundIt:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800614 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
615 pthread_mutex_unlock(&gThreadListLock);
616 return EINVAL;
617 }
618
619 /* wait for thread death when needed
620 *
621 * if the 'join_count' is negative, this is a 'zombie' thread that
622 * is already dead and without stack/TLS
623 *
624 * otherwise, we need to increment 'join-count' and wait to be signaled
625 */
626 count = thread->join_count;
627 if (count >= 0) {
628 thread->join_count += 1;
629 pthread_cond_wait( &thread->join_cond, &gThreadListLock );
630 count = --thread->join_count;
631 }
632 if (ret_val)
633 *ret_val = thread->return_value;
634
635 /* remove thread descriptor when we're the last joiner or when the
636 * thread was already a zombie.
637 */
638 if (count <= 0) {
639 _pthread_internal_remove_locked(thread);
640 _pthread_internal_free(thread);
641 }
642 pthread_mutex_unlock(&gThreadListLock);
643 return 0;
644}
645
646int pthread_detach( pthread_t thid )
647{
648 pthread_internal_t* thread;
649 int result = 0;
650 int flags;
651
652 pthread_mutex_lock(&gThreadListLock);
653 for (thread = gThreadList; thread != NULL; thread = thread->next)
654 if (thread == (pthread_internal_t*)thid)
655 goto FoundIt;
656
657 result = ESRCH;
658 goto Exit;
659
660FoundIt:
661 do {
662 flags = thread->attr.flags;
663
664 if ( flags & PTHREAD_ATTR_FLAG_DETACHED ) {
665 /* thread is not joinable ! */
666 result = EINVAL;
667 goto Exit;
668 }
669 }
670 while ( __atomic_cmpxchg( flags, flags | PTHREAD_ATTR_FLAG_DETACHED,
671 (volatile int*)&thread->attr.flags ) != 0 );
672Exit:
673 pthread_mutex_unlock(&gThreadListLock);
674 return result;
675}
676
677pthread_t pthread_self(void)
678{
679 return (pthread_t)__get_thread();
680}
681
682int pthread_equal(pthread_t one, pthread_t two)
683{
684 return (one == two ? 1 : 0);
685}
686
687int pthread_getschedparam(pthread_t thid, int * policy,
688 struct sched_param * param)
689{
690 int old_errno = errno;
691
692 pthread_internal_t * thread = (pthread_internal_t *)thid;
693 int err = sched_getparam(thread->kernel_id, param);
694 if (!err) {
695 *policy = sched_getscheduler(thread->kernel_id);
696 } else {
697 err = errno;
698 errno = old_errno;
699 }
700 return err;
701}
702
703int pthread_setschedparam(pthread_t thid, int policy,
704 struct sched_param const * param)
705{
706 pthread_internal_t * thread = (pthread_internal_t *)thid;
707 int old_errno = errno;
708 int ret;
709
710 ret = sched_setscheduler(thread->kernel_id, policy, param);
711 if (ret < 0) {
712 ret = errno;
713 errno = old_errno;
714 }
715 return ret;
716}
717
718
719int __futex_wait(volatile void *ftx, int val, const struct timespec *timeout);
720int __futex_wake(volatile void *ftx, int count);
721
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700722int __futex_syscall3(volatile void *ftx, int op, int val);
723int __futex_syscall4(volatile void *ftx, int op, int val, const struct timespec *timeout);
724
725#ifndef FUTEX_PRIVATE_FLAG
726#define FUTEX_PRIVATE_FLAG 128
727#endif
728
729#ifndef FUTEX_WAIT_PRIVATE
730#define FUTEX_WAIT_PRIVATE (FUTEX_WAIT|FUTEX_PRIVATE_FLAG)
731#endif
732
733#ifndef FUTEX_WAKE_PRIVATE
734#define FUTEX_WAKE_PRIVATE (FUTEX_WAKE|FUTEX_PRIVATE_FLAG)
735#endif
736
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800737// mutex lock states
738//
739// 0: unlocked
740// 1: locked, no waiters
741// 2: locked, maybe waiters
742
743/* a mutex is implemented as a 32-bit integer holding the following fields
744 *
745 * bits: name description
746 * 31-16 tid owner thread's kernel id (recursive and errorcheck only)
747 * 15-14 type mutex type
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700748 * 13 shared process-shared flag
749 * 12-2 counter counter of recursive mutexes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800750 * 1-0 state lock state (0, 1 or 2)
751 */
752
753
754#define MUTEX_OWNER(m) (((m)->value >> 16) & 0xffff)
755#define MUTEX_COUNTER(m) (((m)->value >> 2) & 0xfff)
756
757#define MUTEX_TYPE_MASK 0xc000
758#define MUTEX_TYPE_NORMAL 0x0000
759#define MUTEX_TYPE_RECURSIVE 0x4000
760#define MUTEX_TYPE_ERRORCHECK 0x8000
761
762#define MUTEX_COUNTER_SHIFT 2
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700763#define MUTEX_COUNTER_MASK 0x1ffc
764#define MUTEX_SHARED_MASK 0x2000
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800765
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700766/* a mutex attribute holds the following fields
767 *
768 * bits: name description
769 * 0-3 type type of mutex
770 * 4 shared process-shared flag
771 */
772#define MUTEXATTR_TYPE_MASK 0x000f
773#define MUTEXATTR_SHARED_MASK 0x0010
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800774
775
776int pthread_mutexattr_init(pthread_mutexattr_t *attr)
777{
778 if (attr) {
779 *attr = PTHREAD_MUTEX_DEFAULT;
780 return 0;
781 } else {
782 return EINVAL;
783 }
784}
785
786int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
787{
788 if (attr) {
789 *attr = -1;
790 return 0;
791 } else {
792 return EINVAL;
793 }
794}
795
796int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
797{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700798 if (attr) {
799 int atype = (*attr & MUTEXATTR_TYPE_MASK);
800
801 if (atype >= PTHREAD_MUTEX_NORMAL &&
802 atype <= PTHREAD_MUTEX_ERRORCHECK) {
803 *type = atype;
804 return 0;
805 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800806 }
807 return EINVAL;
808}
809
810int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
811{
812 if (attr && type >= PTHREAD_MUTEX_NORMAL &&
813 type <= PTHREAD_MUTEX_ERRORCHECK ) {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700814 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800815 return 0;
816 }
817 return EINVAL;
818}
819
820/* process-shared mutexes are not supported at the moment */
821
822int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
823{
824 if (!attr)
825 return EINVAL;
826
Mathias Agopianb7681162009-07-13 22:00:33 -0700827 switch (pshared) {
828 case PTHREAD_PROCESS_PRIVATE:
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700829 *attr &= ~MUTEXATTR_SHARED_MASK;
830 return 0;
831
Mathias Agopianb7681162009-07-13 22:00:33 -0700832 case PTHREAD_PROCESS_SHARED:
833 /* our current implementation of pthread actually supports shared
834 * mutexes but won't cleanup if a process dies with the mutex held.
835 * Nevertheless, it's better than nothing. Shared mutexes are used
836 * by surfaceflinger and audioflinger.
837 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700838 *attr |= MUTEXATTR_SHARED_MASK;
Mathias Agopianb7681162009-07-13 22:00:33 -0700839 return 0;
840 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700841 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800842}
843
844int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
845{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700846 if (!attr || !pshared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800847 return EINVAL;
848
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700849 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED
850 : PTHREAD_PROCESS_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800851 return 0;
852}
853
854int pthread_mutex_init(pthread_mutex_t *mutex,
855 const pthread_mutexattr_t *attr)
856{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700857 int value = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800858
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700859 if (mutex == NULL)
860 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800861
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700862 if (__likely(attr == NULL)) {
863 mutex->value = MUTEX_TYPE_NORMAL;
864 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800865 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700866
867 if ((*attr & MUTEXATTR_SHARED_MASK) != 0)
868 value |= MUTEX_SHARED_MASK;
869
870 switch (*attr & MUTEXATTR_TYPE_MASK) {
871 case PTHREAD_MUTEX_NORMAL:
872 value |= MUTEX_TYPE_NORMAL;
873 break;
874 case PTHREAD_MUTEX_RECURSIVE:
875 value |= MUTEX_TYPE_RECURSIVE;
876 break;
877 case PTHREAD_MUTEX_ERRORCHECK:
878 value |= MUTEX_TYPE_ERRORCHECK;
879 break;
880 default:
881 return EINVAL;
882 }
883
884 mutex->value = value;
885 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800886}
887
888int pthread_mutex_destroy(pthread_mutex_t *mutex)
889{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700890 if (__unlikely(mutex == NULL))
891 return EINVAL;
892
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800893 mutex->value = 0xdead10cc;
894 return 0;
895}
896
897
898/*
899 * Lock a non-recursive mutex.
900 *
901 * As noted above, there are three states:
902 * 0 (unlocked, no contention)
903 * 1 (locked, no contention)
904 * 2 (locked, contention)
905 *
906 * Non-recursive mutexes don't use the thread-id or counter fields, and the
907 * "type" value is zero, so the only bits that will be set are the ones in
908 * the lock state field.
909 */
910static __inline__ void
911_normal_lock(pthread_mutex_t* mutex)
912{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700913 /* We need to preserve the shared flag during operations */
914 int shared = mutex->value & MUTEX_SHARED_MASK;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800915 /*
916 * The common case is an unlocked mutex, so we begin by trying to
917 * change the lock's state from 0 to 1. __atomic_cmpxchg() returns 0
918 * if it made the swap successfully. If the result is nonzero, this
919 * lock is already held by another thread.
920 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700921 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value ) != 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800922 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800923 * We want to go to sleep until the mutex is available, which
924 * requires promoting it to state 2. We need to swap in the new
925 * state value and then wait until somebody wakes us up.
926 *
927 * __atomic_swap() returns the previous value. We swap 2 in and
928 * see if we got zero back; if so, we have acquired the lock. If
929 * not, another thread still holds the lock and we wait again.
930 *
931 * The second argument to the __futex_wait() call is compared
932 * against the current value. If it doesn't match, __futex_wait()
933 * returns immediately (otherwise, it sleeps for a time specified
934 * by the third argument; 0 means sleep forever). This ensures
935 * that the mutex is in state 2 when we go to sleep on it, which
936 * guarantees a wake-up call.
937 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700938 int wait_op = shared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE;
939
940 while (__atomic_swap(shared|2, &mutex->value ) != (shared|0))
941 __futex_syscall4(&mutex->value, wait_op, shared|2, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800942 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700943 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800944}
945
946/*
947 * Release a non-recursive mutex. The caller is responsible for determining
948 * that we are in fact the owner of this lock.
949 */
950static __inline__ void
951_normal_unlock(pthread_mutex_t* mutex)
952{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700953 ANDROID_MEMBAR_FULL();
954
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700955 /* We need to preserve the shared flag during operations */
956 int shared = mutex->value & MUTEX_SHARED_MASK;
957
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800958 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700959 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800960 * to release the lock. __atomic_dec() returns the previous value;
961 * if it wasn't 1 we have to do some additional work.
962 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700963 if (__atomic_dec(&mutex->value) != (shared|1)) {
964 int wake_op = shared ? FUTEX_WAKE : FUTEX_WAKE_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800965 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800966 * Start by releasing the lock. The decrement changed it from
967 * "contended lock" to "uncontended lock", which means we still
968 * hold it, and anybody who tries to sneak in will push it back
969 * to state 2.
970 *
971 * Once we set it to zero the lock is up for grabs. We follow
972 * this with a __futex_wake() to ensure that one of the waiting
973 * threads has a chance to grab it.
974 *
975 * This doesn't cause a race with the swap/wait pair in
976 * _normal_lock(), because the __futex_wait() call there will
977 * return immediately if the mutex value isn't 2.
978 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700979 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800980
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800981 /*
982 * Wake up one waiting thread. We don't know which thread will be
983 * woken or when it'll start executing -- futexes make no guarantees
984 * here. There may not even be a thread waiting.
985 *
986 * The newly-woken thread will replace the 0 we just set above
987 * with 2, which means that when it eventually releases the mutex
988 * it will also call FUTEX_WAKE. This results in one extra wake
989 * call whenever a lock is contended, but lets us avoid forgetting
990 * anyone without requiring us to track the number of sleepers.
991 *
992 * It's possible for another thread to sneak in and grab the lock
993 * between the zero assignment above and the wake call below. If
994 * the new thread is "slow" and holds the lock for a while, we'll
995 * wake up a sleeper, which will swap in a 2 and then go back to
996 * sleep since the lock is still held. If the new thread is "fast",
997 * running to completion before we call wake, the thread we
998 * eventually wake will find an unlocked mutex and will execute.
999 * Either way we have correct behavior and nobody is orphaned on
1000 * the wait queue.
1001 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001002 __futex_syscall3(&mutex->value, wake_op, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001003 }
1004}
1005
1006static pthread_mutex_t __recursive_lock = PTHREAD_MUTEX_INITIALIZER;
1007
1008static void
1009_recursive_lock(void)
1010{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001011 _normal_lock(&__recursive_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001012}
1013
1014static void
1015_recursive_unlock(void)
1016{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001017 _normal_unlock(&__recursive_lock );
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001018}
1019
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001020int pthread_mutex_lock(pthread_mutex_t *mutex)
1021{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001022 int mtype, tid, new_lock_type, shared, wait_op;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001023
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001024 if (__unlikely(mutex == NULL))
1025 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001026
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001027 mtype = (mutex->value & MUTEX_TYPE_MASK);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001028 shared = (mutex->value & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001029
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001030 /* Handle normal case first */
1031 if ( __likely(mtype == MUTEX_TYPE_NORMAL) ) {
1032 _normal_lock(mutex);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001033 return 0;
1034 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001035
1036 /* Do we already own this recursive or error-check mutex ? */
1037 tid = __get_thread()->kernel_id;
1038 if ( tid == MUTEX_OWNER(mutex) )
1039 {
1040 int oldv, counter;
1041
1042 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1043 /* trying to re-lock a mutex we already acquired */
1044 return EDEADLK;
1045 }
1046 /*
1047 * We own the mutex, but other threads are able to change
1048 * the contents (e.g. promoting it to "contended"), so we
1049 * need to hold the global lock.
1050 */
1051 _recursive_lock();
1052 oldv = mutex->value;
1053 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1054 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1055 _recursive_unlock();
1056 return 0;
1057 }
1058
1059 /* We don't own the mutex, so try to get it.
1060 *
1061 * First, we try to change its state from 0 to 1, if this
1062 * doesn't work, try to change it to state 2.
1063 */
1064 new_lock_type = 1;
1065
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001066 /* compute futex wait opcode and restore shared flag in mtype */
1067 wait_op = shared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE;
1068 mtype |= shared;
1069
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001070 for (;;) {
1071 int oldv;
1072
1073 _recursive_lock();
1074 oldv = mutex->value;
1075 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1076 mutex->value = ((tid << 16) | mtype | new_lock_type);
1077 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1078 oldv ^= 3;
1079 mutex->value = oldv;
1080 }
1081 _recursive_unlock();
1082
1083 if (oldv == mtype)
1084 break;
1085
1086 /*
1087 * The lock was held, possibly contended by others. From
1088 * now on, if we manage to acquire the lock, we have to
1089 * assume that others are still contending for it so that
1090 * we'll wake them when we unlock it.
1091 */
1092 new_lock_type = 2;
1093
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001094 __futex_syscall4(&mutex->value, wait_op, oldv, NULL);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001095 }
1096 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001097}
1098
1099
1100int pthread_mutex_unlock(pthread_mutex_t *mutex)
1101{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001102 int mtype, tid, oldv, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001103
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001104 if (__unlikely(mutex == NULL))
1105 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001106
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001107 mtype = (mutex->value & MUTEX_TYPE_MASK);
1108 shared = (mutex->value & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001109
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001110 /* Handle common case first */
1111 if (__likely(mtype == MUTEX_TYPE_NORMAL)) {
1112 _normal_unlock(mutex);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001113 return 0;
1114 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001115
1116 /* Do we already own this recursive or error-check mutex ? */
1117 tid = __get_thread()->kernel_id;
1118 if ( tid != MUTEX_OWNER(mutex) )
1119 return EPERM;
1120
1121 /* We do, decrement counter or release the mutex if it is 0 */
1122 _recursive_lock();
1123 oldv = mutex->value;
1124 if (oldv & MUTEX_COUNTER_MASK) {
1125 mutex->value = oldv - (1 << MUTEX_COUNTER_SHIFT);
1126 oldv = 0;
1127 } else {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001128 mutex->value = shared | mtype;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001129 }
1130 _recursive_unlock();
1131
1132 /* Wake one waiting thread, if any */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001133 if ((oldv & 3) == 2) {
David 'Digit' Turner5207d782010-03-23 05:30:55 -07001134 int wake_op = shared ? FUTEX_WAKE : FUTEX_WAKE_PRIVATE;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001135 __futex_syscall3(&mutex->value, wake_op, 1);
1136 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001137 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001138}
1139
1140
1141int pthread_mutex_trylock(pthread_mutex_t *mutex)
1142{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001143 int mtype, tid, oldv, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001144
1145 if (__unlikely(mutex == NULL))
1146 return EINVAL;
1147
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001148 mtype = (mutex->value & MUTEX_TYPE_MASK);
1149 shared = (mutex->value & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001150
1151 /* Handle common case first */
1152 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001153 {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001154 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
1155 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001156 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001157 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001158
1159 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001160 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001161
1162 /* Do we already own this recursive or error-check mutex ? */
1163 tid = __get_thread()->kernel_id;
1164 if ( tid == MUTEX_OWNER(mutex) )
1165 {
1166 int counter;
1167
1168 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1169 /* already locked by ourselves */
1170 return EDEADLK;
1171 }
1172
1173 _recursive_lock();
1174 oldv = mutex->value;
1175 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1176 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1177 _recursive_unlock();
1178 return 0;
1179 }
1180
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001181 /* Restore sharing bit in mtype */
1182 mtype |= shared;
1183
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001184 /* Try to lock it, just once. */
1185 _recursive_lock();
1186 oldv = mutex->value;
1187 if (oldv == mtype) /* uncontended released lock => state 1 */
1188 mutex->value = ((tid << 16) | mtype | 1);
1189 _recursive_unlock();
1190
1191 if (oldv != mtype)
1192 return EBUSY;
1193
1194 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001195}
1196
1197
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001198/* initialize 'ts' with the difference between 'abstime' and the current time
1199 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
1200 */
1201static int
1202__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
1203{
1204 clock_gettime(clock, ts);
1205 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
1206 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
1207 if (ts->tv_nsec < 0) {
1208 ts->tv_sec--;
1209 ts->tv_nsec += 1000000000;
1210 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001211 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001212 return -1;
1213
1214 return 0;
1215}
1216
1217/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1218 * milliseconds.
1219 */
1220static void
1221__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1222{
1223 clock_gettime(clock, abstime);
1224 abstime->tv_sec += msecs/1000;
1225 abstime->tv_nsec += (msecs%1000)*1000000;
1226 if (abstime->tv_nsec >= 1000000000) {
1227 abstime->tv_sec++;
1228 abstime->tv_nsec -= 1000000000;
1229 }
1230}
1231
1232int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1233{
1234 clockid_t clock = CLOCK_MONOTONIC;
1235 struct timespec abstime;
1236 struct timespec ts;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001237 int mtype, tid, oldv, new_lock_type, shared, wait_op;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001238
1239 /* compute absolute expiration time */
1240 __timespec_to_relative_msec(&abstime, msecs, clock);
1241
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001242 if (__unlikely(mutex == NULL))
1243 return EINVAL;
1244
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001245 mtype = (mutex->value & MUTEX_TYPE_MASK);
1246 shared = (mutex->value & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001247
1248 /* Handle common case first */
1249 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001250 {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001251 int wait_op = shared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE;
1252
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001253 /* fast path for uncontended lock */
1254 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
1255 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001256 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001257 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001258
1259 /* loop while needed */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001260 while (__atomic_swap(shared|2, &mutex->value) != (shared|0)) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001261 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1262 return EBUSY;
1263
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001264 __futex_syscall4(&mutex->value, wait_op, shared|2, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001265 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001266 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001267 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001268 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001269
1270 /* Do we already own this recursive or error-check mutex ? */
1271 tid = __get_thread()->kernel_id;
1272 if ( tid == MUTEX_OWNER(mutex) )
1273 {
1274 int oldv, counter;
1275
1276 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1277 /* already locked by ourselves */
1278 return EDEADLK;
1279 }
1280
1281 _recursive_lock();
1282 oldv = mutex->value;
1283 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1284 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1285 _recursive_unlock();
1286 return 0;
1287 }
1288
1289 /* We don't own the mutex, so try to get it.
1290 *
1291 * First, we try to change its state from 0 to 1, if this
1292 * doesn't work, try to change it to state 2.
1293 */
1294 new_lock_type = 1;
1295
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001296 /* Compute wait op and restore sharing bit in mtype */
1297 wait_op = shared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE;
1298 mtype |= shared;
1299
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001300 for (;;) {
1301 int oldv;
1302 struct timespec ts;
1303
1304 _recursive_lock();
1305 oldv = mutex->value;
1306 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1307 mutex->value = ((tid << 16) | mtype | new_lock_type);
1308 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1309 oldv ^= 3;
1310 mutex->value = oldv;
1311 }
1312 _recursive_unlock();
1313
1314 if (oldv == mtype)
1315 break;
1316
1317 /*
1318 * The lock was held, possibly contended by others. From
1319 * now on, if we manage to acquire the lock, we have to
1320 * assume that others are still contending for it so that
1321 * we'll wake them when we unlock it.
1322 */
1323 new_lock_type = 2;
1324
1325 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1326 return EBUSY;
1327
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001328 __futex_syscall4(&mutex->value, wait_op, oldv, &ts);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001329 }
1330 return 0;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001331}
1332
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001333int pthread_condattr_init(pthread_condattr_t *attr)
1334{
1335 if (attr == NULL)
1336 return EINVAL;
1337
1338 *attr = PTHREAD_PROCESS_PRIVATE;
1339 return 0;
1340}
1341
1342int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1343{
1344 if (attr == NULL || pshared == NULL)
1345 return EINVAL;
1346
1347 *pshared = *attr;
1348 return 0;
1349}
1350
1351int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1352{
1353 if (attr == NULL)
1354 return EINVAL;
1355
1356 if (pshared != PTHREAD_PROCESS_SHARED &&
1357 pshared != PTHREAD_PROCESS_PRIVATE)
1358 return EINVAL;
1359
1360 *attr = pshared;
1361 return 0;
1362}
1363
1364int pthread_condattr_destroy(pthread_condattr_t *attr)
1365{
1366 if (attr == NULL)
1367 return EINVAL;
1368
1369 *attr = 0xdeada11d;
1370 return 0;
1371}
1372
1373/* We use one bit in condition variable values as the 'shared' flag
1374 * The rest is a counter.
1375 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001376#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001377#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001378#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1379
1380#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001381
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001382/* XXX *technically* there is a race condition that could allow
1383 * XXX a signal to be missed. If thread A is preempted in _wait()
1384 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001385 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001386 * XXX before thread A is scheduled again and calls futex_wait(),
1387 * XXX then the signal will be lost.
1388 */
1389
1390int pthread_cond_init(pthread_cond_t *cond,
1391 const pthread_condattr_t *attr)
1392{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001393 if (cond == NULL)
1394 return EINVAL;
1395
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001396 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001397
1398 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001399 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001400
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001401 return 0;
1402}
1403
1404int pthread_cond_destroy(pthread_cond_t *cond)
1405{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001406 if (cond == NULL)
1407 return EINVAL;
1408
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001409 cond->value = 0xdeadc04d;
1410 return 0;
1411}
1412
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001413/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001414 * pthread_cond_signal to atomically decrement the counter
1415 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001416 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001417static int
1418__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001419{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001420 long flags;
1421 int wake_op;
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;
1431 if (__atomic_cmpxchg(oldval, newval, &cond->value) == 0)
1432 break;
1433 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001434
1435 wake_op = COND_IS_SHARED(cond) ? FUTEX_WAKE : FUTEX_WAKE_PRIVATE;
1436 __futex_syscall3(&cond->value, wake_op, counter);
1437 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001438}
1439
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001440int pthread_cond_broadcast(pthread_cond_t *cond)
1441{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001442 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001443}
1444
1445int pthread_cond_signal(pthread_cond_t *cond)
1446{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001447 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001448}
1449
1450int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1451{
1452 return pthread_cond_timedwait(cond, mutex, NULL);
1453}
1454
1455int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1456 pthread_mutex_t * mutex,
1457 const struct timespec *reltime)
1458{
1459 int status;
1460 int oldvalue = cond->value;
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001461 int wait_op = COND_IS_SHARED(cond) ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001462
1463 pthread_mutex_unlock(mutex);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001464 status = __futex_syscall4(&cond->value, wait_op, oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001465 pthread_mutex_lock(mutex);
1466
1467 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1468 return 0;
1469}
1470
1471int __pthread_cond_timedwait(pthread_cond_t *cond,
1472 pthread_mutex_t * mutex,
1473 const struct timespec *abstime,
1474 clockid_t clock)
1475{
1476 struct timespec ts;
1477 struct timespec * tsp;
1478
1479 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001480 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001481 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001482 tsp = &ts;
1483 } else {
1484 tsp = NULL;
1485 }
1486
1487 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1488}
1489
1490int pthread_cond_timedwait(pthread_cond_t *cond,
1491 pthread_mutex_t * mutex,
1492 const struct timespec *abstime)
1493{
1494 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1495}
1496
1497
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001498/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001499int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1500 pthread_mutex_t * mutex,
1501 const struct timespec *abstime)
1502{
1503 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1504}
1505
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001506int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1507 pthread_mutex_t * mutex,
1508 const struct timespec *abstime)
1509{
1510 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1511}
1512
1513int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1514 pthread_mutex_t * mutex,
1515 const struct timespec *reltime)
1516{
1517 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1518}
1519
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001520int pthread_cond_timeout_np(pthread_cond_t *cond,
1521 pthread_mutex_t * mutex,
1522 unsigned msecs)
1523{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001524 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001525
1526 ts.tv_sec = msecs / 1000;
1527 ts.tv_nsec = (msecs % 1000) * 1000000;
1528
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001529 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001530}
1531
1532
1533
1534/* A technical note regarding our thread-local-storage (TLS) implementation:
1535 *
1536 * There can be up to TLSMAP_SIZE independent TLS keys in a given process,
1537 * though the first TLSMAP_START keys are reserved for Bionic to hold
1538 * special thread-specific variables like errno or a pointer to
1539 * the current thread's descriptor.
1540 *
1541 * while stored in the TLS area, these entries cannot be accessed through
1542 * pthread_getspecific() / pthread_setspecific() and pthread_key_delete()
1543 *
1544 * also, some entries in the key table are pre-allocated (see tlsmap_lock)
1545 * to greatly simplify and speedup some OpenGL-related operations. though the
1546 * initialy value will be NULL on all threads.
1547 *
1548 * you can use pthread_getspecific()/setspecific() on these, and in theory
1549 * you could also call pthread_key_delete() as well, though this would
1550 * probably break some apps.
1551 *
1552 * The 'tlsmap_t' type defined below implements a shared global map of
1553 * currently created/allocated TLS keys and the destructors associated
1554 * with them. You should use tlsmap_lock/unlock to access it to avoid
1555 * any race condition.
1556 *
1557 * the global TLS map simply contains a bitmap of allocated keys, and
1558 * an array of destructors.
1559 *
1560 * each thread has a TLS area that is a simple array of TLSMAP_SIZE void*
1561 * pointers. the TLS area of the main thread is stack-allocated in
1562 * __libc_init_common, while the TLS area of other threads is placed at
1563 * the top of their stack in pthread_create.
1564 *
1565 * when pthread_key_create() is called, it finds the first free key in the
1566 * bitmap, then set it to 1, saving the destructor altogether
1567 *
1568 * when pthread_key_delete() is called. it will erase the key's bitmap bit
1569 * and its destructor, and will also clear the key data in the TLS area of
1570 * all created threads. As mandated by Posix, it is the responsability of
1571 * the caller of pthread_key_delete() to properly reclaim the objects that
1572 * were pointed to by these data fields (either before or after the call).
1573 *
1574 */
1575
1576/* TLS Map implementation
1577 */
1578
1579#define TLSMAP_START (TLS_SLOT_MAX_WELL_KNOWN+1)
1580#define TLSMAP_SIZE BIONIC_TLS_SLOTS
1581#define TLSMAP_BITS 32
1582#define TLSMAP_WORDS ((TLSMAP_SIZE+TLSMAP_BITS-1)/TLSMAP_BITS)
1583#define TLSMAP_WORD(m,k) (m)->map[(k)/TLSMAP_BITS]
1584#define TLSMAP_MASK(k) (1U << ((k)&(TLSMAP_BITS-1)))
1585
1586/* this macro is used to quickly check that a key belongs to a reasonable range */
1587#define TLSMAP_VALIDATE_KEY(key) \
1588 ((key) >= TLSMAP_START && (key) < TLSMAP_SIZE)
1589
1590/* the type of tls key destructor functions */
1591typedef void (*tls_dtor_t)(void*);
1592
1593typedef struct {
1594 int init; /* see comment in tlsmap_lock() */
1595 uint32_t map[TLSMAP_WORDS]; /* bitmap of allocated keys */
1596 tls_dtor_t dtors[TLSMAP_SIZE]; /* key destructors */
1597} tlsmap_t;
1598
1599static pthread_mutex_t _tlsmap_lock = PTHREAD_MUTEX_INITIALIZER;
1600static tlsmap_t _tlsmap;
1601
1602/* lock the global TLS map lock and return a handle to it */
1603static __inline__ tlsmap_t* tlsmap_lock(void)
1604{
1605 tlsmap_t* m = &_tlsmap;
1606
1607 pthread_mutex_lock(&_tlsmap_lock);
1608 /* we need to initialize the first entry of the 'map' array
1609 * with the value TLS_DEFAULT_ALLOC_MAP. doing it statically
1610 * when declaring _tlsmap is a bit awkward and is going to
1611 * produce warnings, so do it the first time we use the map
1612 * instead
1613 */
1614 if (__unlikely(!m->init)) {
1615 TLSMAP_WORD(m,0) = TLS_DEFAULT_ALLOC_MAP;
1616 m->init = 1;
1617 }
1618 return m;
1619}
1620
1621/* unlock the global TLS map */
1622static __inline__ void tlsmap_unlock(tlsmap_t* m)
1623{
1624 pthread_mutex_unlock(&_tlsmap_lock);
1625 (void)m; /* a good compiler is a happy compiler */
1626}
1627
1628/* test to see wether a key is allocated */
1629static __inline__ int tlsmap_test(tlsmap_t* m, int key)
1630{
1631 return (TLSMAP_WORD(m,key) & TLSMAP_MASK(key)) != 0;
1632}
1633
1634/* set the destructor and bit flag on a newly allocated key */
1635static __inline__ void tlsmap_set(tlsmap_t* m, int key, tls_dtor_t dtor)
1636{
1637 TLSMAP_WORD(m,key) |= TLSMAP_MASK(key);
1638 m->dtors[key] = dtor;
1639}
1640
1641/* clear the destructor and bit flag on an existing key */
1642static __inline__ void tlsmap_clear(tlsmap_t* m, int key)
1643{
1644 TLSMAP_WORD(m,key) &= ~TLSMAP_MASK(key);
1645 m->dtors[key] = NULL;
1646}
1647
1648/* allocate a new TLS key, return -1 if no room left */
1649static int tlsmap_alloc(tlsmap_t* m, tls_dtor_t dtor)
1650{
1651 int key;
1652
1653 for ( key = TLSMAP_START; key < TLSMAP_SIZE; key++ ) {
1654 if ( !tlsmap_test(m, key) ) {
1655 tlsmap_set(m, key, dtor);
1656 return key;
1657 }
1658 }
1659 return -1;
1660}
1661
1662
1663int pthread_key_create(pthread_key_t *key, void (*destructor_function)(void *))
1664{
1665 uint32_t err = ENOMEM;
1666 tlsmap_t* map = tlsmap_lock();
1667 int k = tlsmap_alloc(map, destructor_function);
1668
1669 if (k >= 0) {
1670 *key = k;
1671 err = 0;
1672 }
1673 tlsmap_unlock(map);
1674 return err;
1675}
1676
1677
1678/* This deletes a pthread_key_t. note that the standard mandates that this does
1679 * not call the destructor of non-NULL key values. Instead, it is the
1680 * responsability of the caller to properly dispose of the corresponding data
1681 * and resources, using any mean it finds suitable.
1682 *
1683 * On the other hand, this function will clear the corresponding key data
1684 * values in all known threads. this prevents later (invalid) calls to
1685 * pthread_getspecific() to receive invalid/stale values.
1686 */
1687int pthread_key_delete(pthread_key_t key)
1688{
1689 uint32_t err;
1690 pthread_internal_t* thr;
1691 tlsmap_t* map;
1692
1693 if (!TLSMAP_VALIDATE_KEY(key)) {
1694 return EINVAL;
1695 }
1696
1697 map = tlsmap_lock();
1698
1699 if (!tlsmap_test(map, key)) {
1700 err = EINVAL;
1701 goto err1;
1702 }
1703
1704 /* clear value in all threads */
1705 pthread_mutex_lock(&gThreadListLock);
1706 for ( thr = gThreadList; thr != NULL; thr = thr->next ) {
1707 /* avoid zombie threads with a negative 'join_count'. these are really
1708 * already dead and don't have a TLS area anymore.
1709 *
1710 * similarly, it is possible to have thr->tls == NULL for threads that
1711 * were just recently created through pthread_create() but whose
1712 * startup trampoline (__thread_entry) hasn't been run yet by the
1713 * scheduler. so check for this too.
1714 */
1715 if (thr->join_count < 0 || !thr->tls)
1716 continue;
1717
1718 thr->tls[key] = NULL;
1719 }
1720 tlsmap_clear(map, key);
1721
1722 pthread_mutex_unlock(&gThreadListLock);
1723 err = 0;
1724
1725err1:
1726 tlsmap_unlock(map);
1727 return err;
1728}
1729
1730
1731int pthread_setspecific(pthread_key_t key, const void *ptr)
1732{
1733 int err = EINVAL;
1734 tlsmap_t* map;
1735
1736 if (TLSMAP_VALIDATE_KEY(key)) {
1737 /* check that we're trying to set data for an allocated key */
1738 map = tlsmap_lock();
1739 if (tlsmap_test(map, key)) {
1740 ((uint32_t *)__get_tls())[key] = (uint32_t)ptr;
1741 err = 0;
1742 }
1743 tlsmap_unlock(map);
1744 }
1745 return err;
1746}
1747
1748void * pthread_getspecific(pthread_key_t key)
1749{
1750 if (!TLSMAP_VALIDATE_KEY(key)) {
1751 return NULL;
1752 }
1753
1754 /* for performance reason, we do not lock/unlock the global TLS map
1755 * to check that the key is properly allocated. if the key was not
1756 * allocated, the value read from the TLS should always be NULL
1757 * due to pthread_key_delete() clearing the values for all threads.
1758 */
1759 return (void *)(((unsigned *)__get_tls())[key]);
1760}
1761
1762/* Posix mandates that this be defined in <limits.h> but we don't have
1763 * it just yet.
1764 */
1765#ifndef PTHREAD_DESTRUCTOR_ITERATIONS
1766# define PTHREAD_DESTRUCTOR_ITERATIONS 4
1767#endif
1768
1769/* this function is called from pthread_exit() to remove all TLS key data
1770 * from this thread's TLS area. this must call the destructor of all keys
1771 * that have a non-NULL data value (and a non-NULL destructor).
1772 *
1773 * because destructors can do funky things like deleting/creating other
1774 * keys, we need to implement this in a loop
1775 */
1776static void pthread_key_clean_all(void)
1777{
1778 tlsmap_t* map;
1779 void** tls = (void**)__get_tls();
1780 int rounds = PTHREAD_DESTRUCTOR_ITERATIONS;
1781
1782 map = tlsmap_lock();
1783
1784 for (rounds = PTHREAD_DESTRUCTOR_ITERATIONS; rounds > 0; rounds--)
1785 {
1786 int kk, count = 0;
1787
1788 for (kk = TLSMAP_START; kk < TLSMAP_SIZE; kk++) {
1789 if ( tlsmap_test(map, kk) )
1790 {
1791 void* data = tls[kk];
1792 tls_dtor_t dtor = map->dtors[kk];
1793
1794 if (data != NULL && dtor != NULL)
1795 {
1796 /* we need to clear the key data now, this will prevent the
1797 * destructor (or a later one) from seeing the old value if
1798 * it calls pthread_getspecific() for some odd reason
1799 *
1800 * we do not do this if 'dtor == NULL' just in case another
1801 * destructor function might be responsible for manually
1802 * releasing the corresponding data.
1803 */
1804 tls[kk] = NULL;
1805
1806 /* because the destructor is free to call pthread_key_create
1807 * and/or pthread_key_delete, we need to temporarily unlock
1808 * the TLS map
1809 */
1810 tlsmap_unlock(map);
1811 (*dtor)(data);
1812 map = tlsmap_lock();
1813
1814 count += 1;
1815 }
1816 }
1817 }
1818
1819 /* if we didn't call any destructor, there is no need to check the
1820 * TLS data again
1821 */
1822 if (count == 0)
1823 break;
1824 }
1825 tlsmap_unlock(map);
1826}
1827
1828// man says this should be in <linux/unistd.h>, but it isn't
1829extern int tkill(int tid, int sig);
1830
1831int pthread_kill(pthread_t tid, int sig)
1832{
1833 int ret;
1834 int old_errno = errno;
1835 pthread_internal_t * thread = (pthread_internal_t *)tid;
1836
1837 ret = tkill(thread->kernel_id, sig);
1838 if (ret < 0) {
1839 ret = errno;
1840 errno = old_errno;
1841 }
1842
1843 return ret;
1844}
1845
1846extern int __rt_sigprocmask(int, const sigset_t *, sigset_t *, size_t);
1847
1848int pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
1849{
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001850 /* pthread_sigmask must return the error code, but the syscall
1851 * will set errno instead and return 0/-1
1852 */
1853 int ret, old_errno = errno;
1854
1855 ret = __rt_sigprocmask(how, set, oset, _NSIG / 8);
1856 if (ret < 0)
1857 ret = errno;
1858
1859 errno = old_errno;
1860 return ret;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001861}
1862
1863
1864int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
1865{
1866 const int CLOCK_IDTYPE_BITS = 3;
1867 pthread_internal_t* thread = (pthread_internal_t*)tid;
1868
1869 if (!thread)
1870 return ESRCH;
1871
1872 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
1873 return 0;
1874}
1875
1876
1877/* NOTE: this implementation doesn't support a init function that throws a C++ exception
1878 * or calls fork()
1879 */
1880int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
1881{
1882 static pthread_mutex_t once_lock = PTHREAD_MUTEX_INITIALIZER;
1883
1884 if (*once_control == PTHREAD_ONCE_INIT) {
1885 _normal_lock( &once_lock );
1886 if (*once_control == PTHREAD_ONCE_INIT) {
1887 (*init_routine)();
1888 *once_control = ~PTHREAD_ONCE_INIT;
1889 }
1890 _normal_unlock( &once_lock );
1891 }
1892 return 0;
1893}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03001894
1895/* This value is not exported by kernel headers, so hardcode it here */
1896#define MAX_TASK_COMM_LEN 16
1897#define TASK_COMM_FMT "/proc/self/task/%u/comm"
1898
1899int pthread_setname_np(pthread_t thid, const char *thname)
1900{
1901 size_t thname_len;
1902 int saved_errno, ret;
1903
1904 if (thid == 0 || thname == NULL)
1905 return EINVAL;
1906
1907 thname_len = strlen(thname);
1908 if (thname_len >= MAX_TASK_COMM_LEN)
1909 return ERANGE;
1910
1911 saved_errno = errno;
1912 if (thid == pthread_self())
1913 {
1914 ret = prctl(PR_SET_NAME, (unsigned long)thname, 0, 0, 0) ? errno : 0;
1915 }
1916 else
1917 {
1918 /* Have to change another thread's name */
1919 pthread_internal_t *thread = (pthread_internal_t *)thid;
1920 char comm_name[sizeof(TASK_COMM_FMT) + 8];
1921 ssize_t n;
1922 int fd;
1923
1924 snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, (unsigned int)thread->kernel_id);
1925 fd = open(comm_name, O_RDWR);
1926 if (fd == -1)
1927 {
1928 ret = errno;
1929 goto exit;
1930 }
1931 n = TEMP_FAILURE_RETRY(write(fd, thname, thname_len));
1932 close(fd);
1933
1934 if (n < 0)
1935 ret = errno;
1936 else if ((size_t)n != thname_len)
1937 ret = EIO;
1938 else
1939 ret = 0;
1940 }
1941exit:
1942 errno = saved_errno;
1943 return ret;
1944}