blob: 061cce1e8d17aca7bad1a6a366be3703cca2c3fe [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>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080052
53extern int __pthread_clone(int (*fn)(void*), void *child_stack, int flags, void *arg);
54extern void _exit_with_stack_teardown(void * stackBase, int stackSize, int retCode);
55extern void _exit_thread(int retCode);
56extern int __set_errno(int);
57
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -070058int __futex_wake_ex(volatile void *ftx, int pshared, int val)
59{
60 return __futex_syscall3(ftx, pshared ? FUTEX_WAKE : FUTEX_WAKE_PRIVATE, val);
61}
62
63int __futex_wait_ex(volatile void *ftx, int pshared, int val, const struct timespec *timeout)
64{
65 return __futex_syscall4(ftx, pshared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE, val, timeout);
66}
67
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -070068#define __likely(cond) __builtin_expect(!!(cond), 1)
69#define __unlikely(cond) __builtin_expect(!!(cond), 0)
70
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080071void _thread_created_hook(pid_t thread_id) __attribute__((noinline));
72
73#define PTHREAD_ATTR_FLAG_DETACHED 0x00000001
74#define PTHREAD_ATTR_FLAG_USER_STACK 0x00000002
75
76#define DEFAULT_STACKSIZE (1024 * 1024)
77#define STACKBASE 0x10000000
78
79static uint8_t * gStackBase = (uint8_t *)STACKBASE;
80
81static pthread_mutex_t mmap_lock = PTHREAD_MUTEX_INITIALIZER;
82
83
84static const pthread_attr_t gDefaultPthreadAttr = {
85 .flags = 0,
86 .stack_base = NULL,
87 .stack_size = DEFAULT_STACKSIZE,
88 .guard_size = PAGE_SIZE,
89 .sched_policy = SCHED_NORMAL,
90 .sched_priority = 0
91};
92
93#define INIT_THREADS 1
94
95static pthread_internal_t* gThreadList = NULL;
96static pthread_mutex_t gThreadListLock = PTHREAD_MUTEX_INITIALIZER;
97static pthread_mutex_t gDebuggerNotificationLock = PTHREAD_MUTEX_INITIALIZER;
98
99
100/* we simply malloc/free the internal pthread_internal_t structures. we may
101 * want to use a different allocation scheme in the future, but this one should
102 * be largely enough
103 */
104static pthread_internal_t*
105_pthread_internal_alloc(void)
106{
107 pthread_internal_t* thread;
108
109 thread = calloc( sizeof(*thread), 1 );
110 if (thread)
111 thread->intern = 1;
112
113 return thread;
114}
115
116static void
117_pthread_internal_free( pthread_internal_t* thread )
118{
119 if (thread && thread->intern) {
120 thread->intern = 0; /* just in case */
121 free (thread);
122 }
123}
124
125
126static void
127_pthread_internal_remove_locked( pthread_internal_t* thread )
128{
129 thread->next->pref = thread->pref;
130 thread->pref[0] = thread->next;
131}
132
133static void
134_pthread_internal_remove( pthread_internal_t* thread )
135{
136 pthread_mutex_lock(&gThreadListLock);
137 _pthread_internal_remove_locked(thread);
138 pthread_mutex_unlock(&gThreadListLock);
139}
140
141static void
142_pthread_internal_add( pthread_internal_t* thread )
143{
144 pthread_mutex_lock(&gThreadListLock);
145 thread->pref = &gThreadList;
146 thread->next = thread->pref[0];
147 if (thread->next)
148 thread->next->pref = &thread->next;
149 thread->pref[0] = thread;
150 pthread_mutex_unlock(&gThreadListLock);
151}
152
153pthread_internal_t*
154__get_thread(void)
155{
156 void** tls = (void**)__get_tls();
157
158 return (pthread_internal_t*) tls[TLS_SLOT_THREAD_ID];
159}
160
161
162void*
163__get_stack_base(int *p_stack_size)
164{
165 pthread_internal_t* thread = __get_thread();
166
167 *p_stack_size = thread->attr.stack_size;
168 return thread->attr.stack_base;
169}
170
171
172void __init_tls(void** tls, void* thread)
173{
174 int nn;
175
176 ((pthread_internal_t*)thread)->tls = tls;
177
178 // slot 0 must point to the tls area, this is required by the implementation
179 // of the x86 Linux kernel thread-local-storage
180 tls[TLS_SLOT_SELF] = (void*)tls;
181 tls[TLS_SLOT_THREAD_ID] = thread;
182 for (nn = TLS_SLOT_ERRNO; nn < BIONIC_TLS_SLOTS; nn++)
183 tls[nn] = 0;
184
185 __set_tls( (void*)tls );
186}
187
188
189/*
190 * This trampoline is called from the assembly clone() function
191 */
192void __thread_entry(int (*func)(void*), void *arg, void **tls)
193{
194 int retValue;
195 pthread_internal_t * thrInfo;
196
197 // Wait for our creating thread to release us. This lets it have time to
198 // notify gdb about this thread before it starts doing anything.
199 pthread_mutex_t * start_mutex = (pthread_mutex_t *)&tls[TLS_SLOT_SELF];
200 pthread_mutex_lock(start_mutex);
201 pthread_mutex_destroy(start_mutex);
202
203 thrInfo = (pthread_internal_t *) tls[TLS_SLOT_THREAD_ID];
204
205 __init_tls( tls, thrInfo );
206
207 pthread_exit( (void*)func(arg) );
208}
209
210void _init_thread(pthread_internal_t * thread, pid_t kernel_id, pthread_attr_t * attr, void * stack_base)
211{
212 if (attr == NULL) {
213 thread->attr = gDefaultPthreadAttr;
214 } else {
215 thread->attr = *attr;
216 }
217 thread->attr.stack_base = stack_base;
218 thread->kernel_id = kernel_id;
219
220 // set the scheduling policy/priority of the thread
221 if (thread->attr.sched_policy != SCHED_NORMAL) {
222 struct sched_param param;
223 param.sched_priority = thread->attr.sched_priority;
224 sched_setscheduler(kernel_id, thread->attr.sched_policy, &param);
225 }
226
227 pthread_cond_init(&thread->join_cond, NULL);
228 thread->join_count = 0;
229
230 thread->cleanup_stack = NULL;
231
232 _pthread_internal_add(thread);
233}
234
235
236/* XXX stacks not reclaimed if thread spawn fails */
237/* XXX stacks address spaces should be reused if available again */
238
239static void *mkstack(size_t size, size_t guard_size)
240{
241 void * stack;
242
243 pthread_mutex_lock(&mmap_lock);
244
245 stack = mmap((void *)gStackBase, size,
246 PROT_READ | PROT_WRITE,
247 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
248 -1, 0);
249
250 if(stack == MAP_FAILED) {
251 stack = NULL;
252 goto done;
253 }
254
255 if(mprotect(stack, guard_size, PROT_NONE)){
256 munmap(stack, size);
257 stack = NULL;
258 goto done;
259 }
260
261done:
262 pthread_mutex_unlock(&mmap_lock);
263 return stack;
264}
265
266/*
267 * Create a new thread. The thread's stack is layed out like so:
268 *
269 * +---------------------------+
270 * | pthread_internal_t |
271 * +---------------------------+
272 * | |
273 * | TLS area |
274 * | |
275 * +---------------------------+
276 * | |
277 * . .
278 * . stack area .
279 * . .
280 * | |
281 * +---------------------------+
282 * | guard page |
283 * +---------------------------+
284 *
285 * note that TLS[0] must be a pointer to itself, this is required
286 * by the thread-local storage implementation of the x86 Linux
287 * kernel, where the TLS pointer is read by reading fs:[0]
288 */
289int pthread_create(pthread_t *thread_out, pthread_attr_t const * attr,
290 void *(*start_routine)(void *), void * arg)
291{
292 char* stack;
293 void** tls;
294 int tid;
295 pthread_mutex_t * start_mutex;
296 pthread_internal_t * thread;
297 int madestack = 0;
298 int old_errno = errno;
299
300 /* this will inform the rest of the C library that at least one thread
301 * was created. this will enforce certain functions to acquire/release
302 * locks (e.g. atexit()) to protect shared global structures.
303 *
304 * this works because pthread_create() is not called by the C library
305 * initialization routine that sets up the main thread's data structures.
306 */
307 __isthreaded = 1;
308
309 thread = _pthread_internal_alloc();
310 if (thread == NULL)
311 return ENOMEM;
312
313 if (attr == NULL) {
314 attr = &gDefaultPthreadAttr;
315 }
316
317 // make sure the stack is PAGE_SIZE aligned
318 size_t stackSize = (attr->stack_size +
319 (PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
320
321 if (!attr->stack_base) {
322 stack = mkstack(stackSize, attr->guard_size);
323 if(stack == NULL) {
324 _pthread_internal_free(thread);
325 return ENOMEM;
326 }
327 madestack = 1;
328 } else {
329 stack = attr->stack_base;
330 }
331
332 // Make room for TLS
333 tls = (void**)(stack + stackSize - BIONIC_TLS_SLOTS*sizeof(void*));
334
335 // Create a mutex for the thread in TLS_SLOT_SELF to wait on once it starts so we can keep
336 // it from doing anything until after we notify the debugger about it
337 start_mutex = (pthread_mutex_t *) &tls[TLS_SLOT_SELF];
338 pthread_mutex_init(start_mutex, NULL);
339 pthread_mutex_lock(start_mutex);
340
341 tls[TLS_SLOT_THREAD_ID] = thread;
342
343 tid = __pthread_clone((int(*)(void*))start_routine, tls,
344 CLONE_FILES | CLONE_FS | CLONE_VM | CLONE_SIGHAND
345 | CLONE_THREAD | CLONE_SYSVSEM | CLONE_DETACHED,
346 arg);
347
348 if(tid < 0) {
349 int result;
350 if (madestack)
351 munmap(stack, stackSize);
352 _pthread_internal_free(thread);
353 result = errno;
354 errno = old_errno;
355 return result;
356 }
357
358 _init_thread(thread, tid, (pthread_attr_t*)attr, stack);
359
360 if (!madestack)
361 thread->attr.flags |= PTHREAD_ATTR_FLAG_USER_STACK;
362
363 // Notify any debuggers about the new thread
364 pthread_mutex_lock(&gDebuggerNotificationLock);
365 _thread_created_hook(tid);
366 pthread_mutex_unlock(&gDebuggerNotificationLock);
367
368 // Let the thread do it's thing
369 pthread_mutex_unlock(start_mutex);
370
371 *thread_out = (pthread_t)thread;
372 return 0;
373}
374
375
376int pthread_attr_init(pthread_attr_t * attr)
377{
378 *attr = gDefaultPthreadAttr;
379 return 0;
380}
381
382int pthread_attr_destroy(pthread_attr_t * attr)
383{
384 memset(attr, 0x42, sizeof(pthread_attr_t));
385 return 0;
386}
387
388int pthread_attr_setdetachstate(pthread_attr_t * attr, int state)
389{
390 if (state == PTHREAD_CREATE_DETACHED) {
391 attr->flags |= PTHREAD_ATTR_FLAG_DETACHED;
392 } else if (state == PTHREAD_CREATE_JOINABLE) {
393 attr->flags &= ~PTHREAD_ATTR_FLAG_DETACHED;
394 } else {
395 return EINVAL;
396 }
397 return 0;
398}
399
400int pthread_attr_getdetachstate(pthread_attr_t const * attr, int * state)
401{
402 *state = (attr->flags & PTHREAD_ATTR_FLAG_DETACHED)
403 ? PTHREAD_CREATE_DETACHED
404 : PTHREAD_CREATE_JOINABLE;
405 return 0;
406}
407
408int pthread_attr_setschedpolicy(pthread_attr_t * attr, int policy)
409{
410 attr->sched_policy = policy;
411 return 0;
412}
413
414int pthread_attr_getschedpolicy(pthread_attr_t const * attr, int * policy)
415{
416 *policy = attr->sched_policy;
417 return 0;
418}
419
420int pthread_attr_setschedparam(pthread_attr_t * attr, struct sched_param const * param)
421{
422 attr->sched_priority = param->sched_priority;
423 return 0;
424}
425
426int pthread_attr_getschedparam(pthread_attr_t const * attr, struct sched_param * param)
427{
428 param->sched_priority = attr->sched_priority;
429 return 0;
430}
431
432int pthread_attr_setstacksize(pthread_attr_t * attr, size_t stack_size)
433{
434 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
435 return EINVAL;
436 }
437 attr->stack_size = stack_size;
438 return 0;
439}
440
441int pthread_attr_getstacksize(pthread_attr_t const * attr, size_t * stack_size)
442{
443 *stack_size = attr->stack_size;
444 return 0;
445}
446
447int pthread_attr_setstackaddr(pthread_attr_t * attr, void * stack_addr)
448{
449#if 1
450 // It's not clear if this is setting the top or bottom of the stack, so don't handle it for now.
451 return ENOSYS;
452#else
453 if ((uint32_t)stack_addr & (PAGE_SIZE - 1)) {
454 return EINVAL;
455 }
456 attr->stack_base = stack_addr;
457 return 0;
458#endif
459}
460
461int pthread_attr_getstackaddr(pthread_attr_t const * attr, void ** stack_addr)
462{
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700463 *stack_addr = (char*)attr->stack_base + attr->stack_size;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800464 return 0;
465}
466
467int pthread_attr_setstack(pthread_attr_t * attr, void * stack_base, size_t stack_size)
468{
469 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
470 return EINVAL;
471 }
472 if ((uint32_t)stack_base & (PAGE_SIZE - 1)) {
473 return EINVAL;
474 }
475 attr->stack_base = stack_base;
476 attr->stack_size = stack_size;
477 return 0;
478}
479
480int pthread_attr_getstack(pthread_attr_t const * attr, void ** stack_base, size_t * stack_size)
481{
482 *stack_base = attr->stack_base;
483 *stack_size = attr->stack_size;
484 return 0;
485}
486
487int pthread_attr_setguardsize(pthread_attr_t * attr, size_t guard_size)
488{
489 if (guard_size & (PAGE_SIZE - 1) || guard_size < PAGE_SIZE) {
490 return EINVAL;
491 }
492
493 attr->guard_size = guard_size;
494 return 0;
495}
496
497int pthread_attr_getguardsize(pthread_attr_t const * attr, size_t * guard_size)
498{
499 *guard_size = attr->guard_size;
500 return 0;
501}
502
503int pthread_getattr_np(pthread_t thid, pthread_attr_t * attr)
504{
505 pthread_internal_t * thread = (pthread_internal_t *)thid;
506 *attr = thread->attr;
507 return 0;
508}
509
510int pthread_attr_setscope(pthread_attr_t *attr, int scope)
511{
512 if (scope == PTHREAD_SCOPE_SYSTEM)
513 return 0;
514 if (scope == PTHREAD_SCOPE_PROCESS)
515 return ENOTSUP;
516
517 return EINVAL;
518}
519
520int pthread_attr_getscope(pthread_attr_t const *attr)
521{
522 return PTHREAD_SCOPE_SYSTEM;
523}
524
525
526/* CAVEAT: our implementation of pthread_cleanup_push/pop doesn't support C++ exceptions
527 * and thread cancelation
528 */
529
530void __pthread_cleanup_push( __pthread_cleanup_t* c,
531 __pthread_cleanup_func_t routine,
532 void* arg )
533{
534 pthread_internal_t* thread = __get_thread();
535
536 c->__cleanup_routine = routine;
537 c->__cleanup_arg = arg;
538 c->__cleanup_prev = thread->cleanup_stack;
539 thread->cleanup_stack = c;
540}
541
542void __pthread_cleanup_pop( __pthread_cleanup_t* c, int execute )
543{
544 pthread_internal_t* thread = __get_thread();
545
546 thread->cleanup_stack = c->__cleanup_prev;
547 if (execute)
548 c->__cleanup_routine(c->__cleanup_arg);
549}
550
551/* used by pthread_exit() to clean all TLS keys of the current thread */
552static void pthread_key_clean_all(void);
553
554void pthread_exit(void * retval)
555{
556 pthread_internal_t* thread = __get_thread();
557 void* stack_base = thread->attr.stack_base;
558 int stack_size = thread->attr.stack_size;
559 int user_stack = (thread->attr.flags & PTHREAD_ATTR_FLAG_USER_STACK) != 0;
560
561 // call the cleanup handlers first
562 while (thread->cleanup_stack) {
563 __pthread_cleanup_t* c = thread->cleanup_stack;
564 thread->cleanup_stack = c->__cleanup_prev;
565 c->__cleanup_routine(c->__cleanup_arg);
566 }
567
568 // call the TLS destructors, it is important to do that before removing this
569 // thread from the global list. this will ensure that if someone else deletes
570 // a TLS key, the corresponding value will be set to NULL in this thread's TLS
571 // space (see pthread_key_delete)
572 pthread_key_clean_all();
573
574 // if the thread is detached, destroy the pthread_internal_t
575 // otherwise, keep it in memory and signal any joiners
576 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
577 _pthread_internal_remove(thread);
578 _pthread_internal_free(thread);
579 } else {
580 /* the join_count field is used to store the number of threads waiting for
581 * the termination of this thread with pthread_join(),
582 *
583 * if it is positive we need to signal the waiters, and we do not touch
584 * the count (it will be decremented by the waiters, the last one will
585 * also remove/free the thread structure
586 *
587 * if it is zero, we set the count value to -1 to indicate that the
588 * thread is in 'zombie' state: it has stopped executing, and its stack
589 * is gone (as well as its TLS area). when another thread calls pthread_join()
590 * on it, it will immediately free the thread and return.
591 */
592 pthread_mutex_lock(&gThreadListLock);
593 thread->return_value = retval;
594 if (thread->join_count > 0) {
595 pthread_cond_broadcast(&thread->join_cond);
596 } else {
597 thread->join_count = -1; /* zombie thread */
598 }
599 pthread_mutex_unlock(&gThreadListLock);
600 }
601
602 // destroy the thread stack
603 if (user_stack)
604 _exit_thread((int)retval);
605 else
606 _exit_with_stack_teardown(stack_base, stack_size, (int)retval);
607}
608
609int pthread_join(pthread_t thid, void ** ret_val)
610{
611 pthread_internal_t* thread = (pthread_internal_t*)thid;
612 int count;
613
614 // check that the thread still exists and is not detached
615 pthread_mutex_lock(&gThreadListLock);
616
617 for (thread = gThreadList; thread != NULL; thread = thread->next)
618 if (thread == (pthread_internal_t*)thid)
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200619 goto FoundIt;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800620
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200621 pthread_mutex_unlock(&gThreadListLock);
622 return ESRCH;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800623
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200624FoundIt:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800625 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
626 pthread_mutex_unlock(&gThreadListLock);
627 return EINVAL;
628 }
629
630 /* wait for thread death when needed
631 *
632 * if the 'join_count' is negative, this is a 'zombie' thread that
633 * is already dead and without stack/TLS
634 *
635 * otherwise, we need to increment 'join-count' and wait to be signaled
636 */
637 count = thread->join_count;
638 if (count >= 0) {
639 thread->join_count += 1;
640 pthread_cond_wait( &thread->join_cond, &gThreadListLock );
641 count = --thread->join_count;
642 }
643 if (ret_val)
644 *ret_val = thread->return_value;
645
646 /* remove thread descriptor when we're the last joiner or when the
647 * thread was already a zombie.
648 */
649 if (count <= 0) {
650 _pthread_internal_remove_locked(thread);
651 _pthread_internal_free(thread);
652 }
653 pthread_mutex_unlock(&gThreadListLock);
654 return 0;
655}
656
657int pthread_detach( pthread_t thid )
658{
659 pthread_internal_t* thread;
660 int result = 0;
661 int flags;
662
663 pthread_mutex_lock(&gThreadListLock);
664 for (thread = gThreadList; thread != NULL; thread = thread->next)
665 if (thread == (pthread_internal_t*)thid)
666 goto FoundIt;
667
668 result = ESRCH;
669 goto Exit;
670
671FoundIt:
672 do {
673 flags = thread->attr.flags;
674
675 if ( flags & PTHREAD_ATTR_FLAG_DETACHED ) {
676 /* thread is not joinable ! */
677 result = EINVAL;
678 goto Exit;
679 }
680 }
681 while ( __atomic_cmpxchg( flags, flags | PTHREAD_ATTR_FLAG_DETACHED,
682 (volatile int*)&thread->attr.flags ) != 0 );
683Exit:
684 pthread_mutex_unlock(&gThreadListLock);
685 return result;
686}
687
688pthread_t pthread_self(void)
689{
690 return (pthread_t)__get_thread();
691}
692
693int pthread_equal(pthread_t one, pthread_t two)
694{
695 return (one == two ? 1 : 0);
696}
697
698int pthread_getschedparam(pthread_t thid, int * policy,
699 struct sched_param * param)
700{
701 int old_errno = errno;
702
703 pthread_internal_t * thread = (pthread_internal_t *)thid;
704 int err = sched_getparam(thread->kernel_id, param);
705 if (!err) {
706 *policy = sched_getscheduler(thread->kernel_id);
707 } else {
708 err = errno;
709 errno = old_errno;
710 }
711 return err;
712}
713
714int pthread_setschedparam(pthread_t thid, int policy,
715 struct sched_param const * param)
716{
717 pthread_internal_t * thread = (pthread_internal_t *)thid;
718 int old_errno = errno;
719 int ret;
720
721 ret = sched_setscheduler(thread->kernel_id, policy, param);
722 if (ret < 0) {
723 ret = errno;
724 errno = old_errno;
725 }
726 return ret;
727}
728
729
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800730// mutex lock states
731//
732// 0: unlocked
733// 1: locked, no waiters
734// 2: locked, maybe waiters
735
736/* a mutex is implemented as a 32-bit integer holding the following fields
737 *
738 * bits: name description
739 * 31-16 tid owner thread's kernel id (recursive and errorcheck only)
740 * 15-14 type mutex type
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700741 * 13 shared process-shared flag
742 * 12-2 counter counter of recursive mutexes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800743 * 1-0 state lock state (0, 1 or 2)
744 */
745
746
747#define MUTEX_OWNER(m) (((m)->value >> 16) & 0xffff)
748#define MUTEX_COUNTER(m) (((m)->value >> 2) & 0xfff)
749
750#define MUTEX_TYPE_MASK 0xc000
751#define MUTEX_TYPE_NORMAL 0x0000
752#define MUTEX_TYPE_RECURSIVE 0x4000
753#define MUTEX_TYPE_ERRORCHECK 0x8000
754
755#define MUTEX_COUNTER_SHIFT 2
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700756#define MUTEX_COUNTER_MASK 0x1ffc
757#define MUTEX_SHARED_MASK 0x2000
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800758
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700759/* a mutex attribute holds the following fields
760 *
761 * bits: name description
762 * 0-3 type type of mutex
763 * 4 shared process-shared flag
764 */
765#define MUTEXATTR_TYPE_MASK 0x000f
766#define MUTEXATTR_SHARED_MASK 0x0010
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800767
768
769int pthread_mutexattr_init(pthread_mutexattr_t *attr)
770{
771 if (attr) {
772 *attr = PTHREAD_MUTEX_DEFAULT;
773 return 0;
774 } else {
775 return EINVAL;
776 }
777}
778
779int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
780{
781 if (attr) {
782 *attr = -1;
783 return 0;
784 } else {
785 return EINVAL;
786 }
787}
788
789int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
790{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700791 if (attr) {
792 int atype = (*attr & MUTEXATTR_TYPE_MASK);
793
794 if (atype >= PTHREAD_MUTEX_NORMAL &&
795 atype <= PTHREAD_MUTEX_ERRORCHECK) {
796 *type = atype;
797 return 0;
798 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800799 }
800 return EINVAL;
801}
802
803int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
804{
805 if (attr && type >= PTHREAD_MUTEX_NORMAL &&
806 type <= PTHREAD_MUTEX_ERRORCHECK ) {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700807 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800808 return 0;
809 }
810 return EINVAL;
811}
812
813/* process-shared mutexes are not supported at the moment */
814
815int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
816{
817 if (!attr)
818 return EINVAL;
819
Mathias Agopianb7681162009-07-13 22:00:33 -0700820 switch (pshared) {
821 case PTHREAD_PROCESS_PRIVATE:
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700822 *attr &= ~MUTEXATTR_SHARED_MASK;
823 return 0;
824
Mathias Agopianb7681162009-07-13 22:00:33 -0700825 case PTHREAD_PROCESS_SHARED:
826 /* our current implementation of pthread actually supports shared
827 * mutexes but won't cleanup if a process dies with the mutex held.
828 * Nevertheless, it's better than nothing. Shared mutexes are used
829 * by surfaceflinger and audioflinger.
830 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700831 *attr |= MUTEXATTR_SHARED_MASK;
Mathias Agopianb7681162009-07-13 22:00:33 -0700832 return 0;
833 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700834 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800835}
836
837int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
838{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700839 if (!attr || !pshared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800840 return EINVAL;
841
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700842 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED
843 : PTHREAD_PROCESS_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800844 return 0;
845}
846
847int pthread_mutex_init(pthread_mutex_t *mutex,
848 const pthread_mutexattr_t *attr)
849{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700850 int value = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800851
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700852 if (mutex == NULL)
853 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800854
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700855 if (__likely(attr == NULL)) {
856 mutex->value = MUTEX_TYPE_NORMAL;
857 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800858 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700859
860 if ((*attr & MUTEXATTR_SHARED_MASK) != 0)
861 value |= MUTEX_SHARED_MASK;
862
863 switch (*attr & MUTEXATTR_TYPE_MASK) {
864 case PTHREAD_MUTEX_NORMAL:
865 value |= MUTEX_TYPE_NORMAL;
866 break;
867 case PTHREAD_MUTEX_RECURSIVE:
868 value |= MUTEX_TYPE_RECURSIVE;
869 break;
870 case PTHREAD_MUTEX_ERRORCHECK:
871 value |= MUTEX_TYPE_ERRORCHECK;
872 break;
873 default:
874 return EINVAL;
875 }
876
877 mutex->value = value;
878 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800879}
880
881int pthread_mutex_destroy(pthread_mutex_t *mutex)
882{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700883 if (__unlikely(mutex == NULL))
884 return EINVAL;
885
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800886 mutex->value = 0xdead10cc;
887 return 0;
888}
889
890
891/*
892 * Lock a non-recursive mutex.
893 *
894 * As noted above, there are three states:
895 * 0 (unlocked, no contention)
896 * 1 (locked, no contention)
897 * 2 (locked, contention)
898 *
899 * Non-recursive mutexes don't use the thread-id or counter fields, and the
900 * "type" value is zero, so the only bits that will be set are the ones in
901 * the lock state field.
902 */
903static __inline__ void
904_normal_lock(pthread_mutex_t* mutex)
905{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700906 /* We need to preserve the shared flag during operations */
907 int shared = mutex->value & MUTEX_SHARED_MASK;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800908 /*
909 * The common case is an unlocked mutex, so we begin by trying to
910 * change the lock's state from 0 to 1. __atomic_cmpxchg() returns 0
911 * if it made the swap successfully. If the result is nonzero, this
912 * lock is already held by another thread.
913 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700914 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value ) != 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800915 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800916 * We want to go to sleep until the mutex is available, which
917 * requires promoting it to state 2. We need to swap in the new
918 * state value and then wait until somebody wakes us up.
919 *
920 * __atomic_swap() returns the previous value. We swap 2 in and
921 * see if we got zero back; if so, we have acquired the lock. If
922 * not, another thread still holds the lock and we wait again.
923 *
924 * The second argument to the __futex_wait() call is compared
925 * against the current value. If it doesn't match, __futex_wait()
926 * returns immediately (otherwise, it sleeps for a time specified
927 * by the third argument; 0 means sleep forever). This ensures
928 * that the mutex is in state 2 when we go to sleep on it, which
929 * guarantees a wake-up call.
930 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700931 while (__atomic_swap(shared|2, &mutex->value ) != (shared|0))
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -0700932 __futex_wait_ex(&mutex->value, shared, shared|2, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800933 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700934 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800935}
936
937/*
938 * Release a non-recursive mutex. The caller is responsible for determining
939 * that we are in fact the owner of this lock.
940 */
941static __inline__ void
942_normal_unlock(pthread_mutex_t* mutex)
943{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700944 ANDROID_MEMBAR_FULL();
945
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700946 /* We need to preserve the shared flag during operations */
947 int shared = mutex->value & MUTEX_SHARED_MASK;
948
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800949 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700950 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800951 * to release the lock. __atomic_dec() returns the previous value;
952 * if it wasn't 1 we have to do some additional work.
953 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700954 if (__atomic_dec(&mutex->value) != (shared|1)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800955 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800956 * Start by releasing the lock. The decrement changed it from
957 * "contended lock" to "uncontended lock", which means we still
958 * hold it, and anybody who tries to sneak in will push it back
959 * to state 2.
960 *
961 * Once we set it to zero the lock is up for grabs. We follow
962 * this with a __futex_wake() to ensure that one of the waiting
963 * threads has a chance to grab it.
964 *
965 * This doesn't cause a race with the swap/wait pair in
966 * _normal_lock(), because the __futex_wait() call there will
967 * return immediately if the mutex value isn't 2.
968 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700969 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800970
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800971 /*
972 * Wake up one waiting thread. We don't know which thread will be
973 * woken or when it'll start executing -- futexes make no guarantees
974 * here. There may not even be a thread waiting.
975 *
976 * The newly-woken thread will replace the 0 we just set above
977 * with 2, which means that when it eventually releases the mutex
978 * it will also call FUTEX_WAKE. This results in one extra wake
979 * call whenever a lock is contended, but lets us avoid forgetting
980 * anyone without requiring us to track the number of sleepers.
981 *
982 * It's possible for another thread to sneak in and grab the lock
983 * between the zero assignment above and the wake call below. If
984 * the new thread is "slow" and holds the lock for a while, we'll
985 * wake up a sleeper, which will swap in a 2 and then go back to
986 * sleep since the lock is still held. If the new thread is "fast",
987 * running to completion before we call wake, the thread we
988 * eventually wake will find an unlocked mutex and will execute.
989 * Either way we have correct behavior and nobody is orphaned on
990 * the wait queue.
991 */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -0700992 __futex_wake_ex(&mutex->value, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800993 }
994}
995
996static pthread_mutex_t __recursive_lock = PTHREAD_MUTEX_INITIALIZER;
997
998static void
999_recursive_lock(void)
1000{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001001 _normal_lock(&__recursive_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001002}
1003
1004static void
1005_recursive_unlock(void)
1006{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001007 _normal_unlock(&__recursive_lock );
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001008}
1009
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001010int pthread_mutex_lock(pthread_mutex_t *mutex)
1011{
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001012 int mtype, tid, new_lock_type, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001013
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001014 if (__unlikely(mutex == NULL))
1015 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001016
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001017 mtype = (mutex->value & MUTEX_TYPE_MASK);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001018 shared = (mutex->value & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001019
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001020 /* Handle normal case first */
1021 if ( __likely(mtype == MUTEX_TYPE_NORMAL) ) {
1022 _normal_lock(mutex);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001023 return 0;
1024 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001025
1026 /* Do we already own this recursive or error-check mutex ? */
1027 tid = __get_thread()->kernel_id;
1028 if ( tid == MUTEX_OWNER(mutex) )
1029 {
1030 int oldv, counter;
1031
1032 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1033 /* trying to re-lock a mutex we already acquired */
1034 return EDEADLK;
1035 }
1036 /*
1037 * We own the mutex, but other threads are able to change
1038 * the contents (e.g. promoting it to "contended"), so we
1039 * need to hold the global lock.
1040 */
1041 _recursive_lock();
1042 oldv = mutex->value;
1043 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1044 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1045 _recursive_unlock();
1046 return 0;
1047 }
1048
1049 /* We don't own the mutex, so try to get it.
1050 *
1051 * First, we try to change its state from 0 to 1, if this
1052 * doesn't work, try to change it to state 2.
1053 */
1054 new_lock_type = 1;
1055
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001056 /* compute futex wait opcode and restore shared flag in mtype */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001057 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001058
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001059 for (;;) {
1060 int oldv;
1061
1062 _recursive_lock();
1063 oldv = mutex->value;
1064 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1065 mutex->value = ((tid << 16) | mtype | new_lock_type);
1066 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1067 oldv ^= 3;
1068 mutex->value = oldv;
1069 }
1070 _recursive_unlock();
1071
1072 if (oldv == mtype)
1073 break;
1074
1075 /*
1076 * The lock was held, possibly contended by others. From
1077 * now on, if we manage to acquire the lock, we have to
1078 * assume that others are still contending for it so that
1079 * we'll wake them when we unlock it.
1080 */
1081 new_lock_type = 2;
1082
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001083 __futex_wait_ex(&mutex->value, shared, oldv, NULL);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001084 }
1085 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001086}
1087
1088
1089int pthread_mutex_unlock(pthread_mutex_t *mutex)
1090{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001091 int mtype, tid, oldv, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001092
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001093 if (__unlikely(mutex == NULL))
1094 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001095
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001096 mtype = (mutex->value & MUTEX_TYPE_MASK);
1097 shared = (mutex->value & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001098
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001099 /* Handle common case first */
1100 if (__likely(mtype == MUTEX_TYPE_NORMAL)) {
1101 _normal_unlock(mutex);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001102 return 0;
1103 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001104
1105 /* Do we already own this recursive or error-check mutex ? */
1106 tid = __get_thread()->kernel_id;
1107 if ( tid != MUTEX_OWNER(mutex) )
1108 return EPERM;
1109
1110 /* We do, decrement counter or release the mutex if it is 0 */
1111 _recursive_lock();
1112 oldv = mutex->value;
1113 if (oldv & MUTEX_COUNTER_MASK) {
1114 mutex->value = oldv - (1 << MUTEX_COUNTER_SHIFT);
1115 oldv = 0;
1116 } else {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001117 mutex->value = shared | mtype;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001118 }
1119 _recursive_unlock();
1120
1121 /* Wake one waiting thread, if any */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001122 if ((oldv & 3) == 2) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001123 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001124 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001125 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001126}
1127
1128
1129int pthread_mutex_trylock(pthread_mutex_t *mutex)
1130{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001131 int mtype, tid, oldv, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001132
1133 if (__unlikely(mutex == NULL))
1134 return EINVAL;
1135
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001136 mtype = (mutex->value & MUTEX_TYPE_MASK);
1137 shared = (mutex->value & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001138
1139 /* Handle common case first */
1140 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001141 {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001142 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
1143 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001144 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001145 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001146
1147 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001148 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001149
1150 /* Do we already own this recursive or error-check mutex ? */
1151 tid = __get_thread()->kernel_id;
1152 if ( tid == MUTEX_OWNER(mutex) )
1153 {
1154 int counter;
1155
1156 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1157 /* already locked by ourselves */
1158 return EDEADLK;
1159 }
1160
1161 _recursive_lock();
1162 oldv = mutex->value;
1163 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1164 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1165 _recursive_unlock();
1166 return 0;
1167 }
1168
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001169 /* Restore sharing bit in mtype */
1170 mtype |= shared;
1171
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001172 /* Try to lock it, just once. */
1173 _recursive_lock();
1174 oldv = mutex->value;
1175 if (oldv == mtype) /* uncontended released lock => state 1 */
1176 mutex->value = ((tid << 16) | mtype | 1);
1177 _recursive_unlock();
1178
1179 if (oldv != mtype)
1180 return EBUSY;
1181
1182 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001183}
1184
1185
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001186/* initialize 'ts' with the difference between 'abstime' and the current time
1187 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
1188 */
1189static int
1190__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
1191{
1192 clock_gettime(clock, ts);
1193 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
1194 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
1195 if (ts->tv_nsec < 0) {
1196 ts->tv_sec--;
1197 ts->tv_nsec += 1000000000;
1198 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001199 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001200 return -1;
1201
1202 return 0;
1203}
1204
1205/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1206 * milliseconds.
1207 */
1208static void
1209__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1210{
1211 clock_gettime(clock, abstime);
1212 abstime->tv_sec += msecs/1000;
1213 abstime->tv_nsec += (msecs%1000)*1000000;
1214 if (abstime->tv_nsec >= 1000000000) {
1215 abstime->tv_sec++;
1216 abstime->tv_nsec -= 1000000000;
1217 }
1218}
1219
1220int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1221{
1222 clockid_t clock = CLOCK_MONOTONIC;
1223 struct timespec abstime;
1224 struct timespec ts;
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001225 int mtype, tid, oldv, new_lock_type, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001226
1227 /* compute absolute expiration time */
1228 __timespec_to_relative_msec(&abstime, msecs, clock);
1229
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001230 if (__unlikely(mutex == NULL))
1231 return EINVAL;
1232
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001233 mtype = (mutex->value & MUTEX_TYPE_MASK);
1234 shared = (mutex->value & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001235
1236 /* Handle common case first */
1237 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001238 {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001239 /* fast path for uncontended lock */
1240 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
1241 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001242 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001243 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001244
1245 /* loop while needed */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001246 while (__atomic_swap(shared|2, &mutex->value) != (shared|0)) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001247 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1248 return EBUSY;
1249
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001250 __futex_wait_ex(&mutex->value, shared, shared|2, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001251 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001252 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001253 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001254 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001255
1256 /* Do we already own this recursive or error-check mutex ? */
1257 tid = __get_thread()->kernel_id;
1258 if ( tid == MUTEX_OWNER(mutex) )
1259 {
1260 int oldv, counter;
1261
1262 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1263 /* already locked by ourselves */
1264 return EDEADLK;
1265 }
1266
1267 _recursive_lock();
1268 oldv = mutex->value;
1269 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1270 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1271 _recursive_unlock();
1272 return 0;
1273 }
1274
1275 /* We don't own the mutex, so try to get it.
1276 *
1277 * First, we try to change its state from 0 to 1, if this
1278 * doesn't work, try to change it to state 2.
1279 */
1280 new_lock_type = 1;
1281
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001282 /* Compute wait op and restore sharing bit in mtype */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001283 mtype |= shared;
1284
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001285 for (;;) {
1286 int oldv;
1287 struct timespec ts;
1288
1289 _recursive_lock();
1290 oldv = mutex->value;
1291 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1292 mutex->value = ((tid << 16) | mtype | new_lock_type);
1293 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1294 oldv ^= 3;
1295 mutex->value = oldv;
1296 }
1297 _recursive_unlock();
1298
1299 if (oldv == mtype)
1300 break;
1301
1302 /*
1303 * The lock was held, possibly contended by others. From
1304 * now on, if we manage to acquire the lock, we have to
1305 * assume that others are still contending for it so that
1306 * we'll wake them when we unlock it.
1307 */
1308 new_lock_type = 2;
1309
1310 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1311 return EBUSY;
1312
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001313 __futex_wait_ex(&mutex->value, shared, oldv, &ts);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001314 }
1315 return 0;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001316}
1317
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001318int pthread_condattr_init(pthread_condattr_t *attr)
1319{
1320 if (attr == NULL)
1321 return EINVAL;
1322
1323 *attr = PTHREAD_PROCESS_PRIVATE;
1324 return 0;
1325}
1326
1327int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1328{
1329 if (attr == NULL || pshared == NULL)
1330 return EINVAL;
1331
1332 *pshared = *attr;
1333 return 0;
1334}
1335
1336int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1337{
1338 if (attr == NULL)
1339 return EINVAL;
1340
1341 if (pshared != PTHREAD_PROCESS_SHARED &&
1342 pshared != PTHREAD_PROCESS_PRIVATE)
1343 return EINVAL;
1344
1345 *attr = pshared;
1346 return 0;
1347}
1348
1349int pthread_condattr_destroy(pthread_condattr_t *attr)
1350{
1351 if (attr == NULL)
1352 return EINVAL;
1353
1354 *attr = 0xdeada11d;
1355 return 0;
1356}
1357
1358/* We use one bit in condition variable values as the 'shared' flag
1359 * The rest is a counter.
1360 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001361#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001362#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001363#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1364
1365#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001366
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001367/* XXX *technically* there is a race condition that could allow
1368 * XXX a signal to be missed. If thread A is preempted in _wait()
1369 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001370 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001371 * XXX before thread A is scheduled again and calls futex_wait(),
1372 * XXX then the signal will be lost.
1373 */
1374
1375int pthread_cond_init(pthread_cond_t *cond,
1376 const pthread_condattr_t *attr)
1377{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001378 if (cond == NULL)
1379 return EINVAL;
1380
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001381 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001382
1383 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001384 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001385
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001386 return 0;
1387}
1388
1389int pthread_cond_destroy(pthread_cond_t *cond)
1390{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001391 if (cond == NULL)
1392 return EINVAL;
1393
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001394 cond->value = 0xdeadc04d;
1395 return 0;
1396}
1397
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001398/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001399 * pthread_cond_signal to atomically decrement the counter
1400 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001401 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001402static int
1403__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001404{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001405 long flags;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001406
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001407 if (__unlikely(cond == NULL))
1408 return EINVAL;
1409
1410 flags = (cond->value & ~COND_COUNTER_MASK);
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001411 for (;;) {
1412 long oldval = cond->value;
1413 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1414 | flags;
1415 if (__atomic_cmpxchg(oldval, newval, &cond->value) == 0)
1416 break;
1417 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001418
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001419 __futex_wake_ex(&cond->value, COND_IS_SHARED(cond), counter);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001420 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001421}
1422
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001423int pthread_cond_broadcast(pthread_cond_t *cond)
1424{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001425 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001426}
1427
1428int pthread_cond_signal(pthread_cond_t *cond)
1429{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001430 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001431}
1432
1433int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1434{
1435 return pthread_cond_timedwait(cond, mutex, NULL);
1436}
1437
1438int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1439 pthread_mutex_t * mutex,
1440 const struct timespec *reltime)
1441{
1442 int status;
1443 int oldvalue = cond->value;
1444
1445 pthread_mutex_unlock(mutex);
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001446 status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond), oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001447 pthread_mutex_lock(mutex);
1448
1449 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1450 return 0;
1451}
1452
1453int __pthread_cond_timedwait(pthread_cond_t *cond,
1454 pthread_mutex_t * mutex,
1455 const struct timespec *abstime,
1456 clockid_t clock)
1457{
1458 struct timespec ts;
1459 struct timespec * tsp;
1460
1461 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001462 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001463 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001464 tsp = &ts;
1465 } else {
1466 tsp = NULL;
1467 }
1468
1469 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1470}
1471
1472int pthread_cond_timedwait(pthread_cond_t *cond,
1473 pthread_mutex_t * mutex,
1474 const struct timespec *abstime)
1475{
1476 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1477}
1478
1479
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001480/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001481int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1482 pthread_mutex_t * mutex,
1483 const struct timespec *abstime)
1484{
1485 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1486}
1487
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001488int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1489 pthread_mutex_t * mutex,
1490 const struct timespec *abstime)
1491{
1492 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1493}
1494
1495int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1496 pthread_mutex_t * mutex,
1497 const struct timespec *reltime)
1498{
1499 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1500}
1501
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001502int pthread_cond_timeout_np(pthread_cond_t *cond,
1503 pthread_mutex_t * mutex,
1504 unsigned msecs)
1505{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001506 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001507
1508 ts.tv_sec = msecs / 1000;
1509 ts.tv_nsec = (msecs % 1000) * 1000000;
1510
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001511 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001512}
1513
1514
1515
1516/* A technical note regarding our thread-local-storage (TLS) implementation:
1517 *
1518 * There can be up to TLSMAP_SIZE independent TLS keys in a given process,
1519 * though the first TLSMAP_START keys are reserved for Bionic to hold
1520 * special thread-specific variables like errno or a pointer to
1521 * the current thread's descriptor.
1522 *
1523 * while stored in the TLS area, these entries cannot be accessed through
1524 * pthread_getspecific() / pthread_setspecific() and pthread_key_delete()
1525 *
1526 * also, some entries in the key table are pre-allocated (see tlsmap_lock)
1527 * to greatly simplify and speedup some OpenGL-related operations. though the
1528 * initialy value will be NULL on all threads.
1529 *
1530 * you can use pthread_getspecific()/setspecific() on these, and in theory
1531 * you could also call pthread_key_delete() as well, though this would
1532 * probably break some apps.
1533 *
1534 * The 'tlsmap_t' type defined below implements a shared global map of
1535 * currently created/allocated TLS keys and the destructors associated
1536 * with them. You should use tlsmap_lock/unlock to access it to avoid
1537 * any race condition.
1538 *
1539 * the global TLS map simply contains a bitmap of allocated keys, and
1540 * an array of destructors.
1541 *
1542 * each thread has a TLS area that is a simple array of TLSMAP_SIZE void*
1543 * pointers. the TLS area of the main thread is stack-allocated in
1544 * __libc_init_common, while the TLS area of other threads is placed at
1545 * the top of their stack in pthread_create.
1546 *
1547 * when pthread_key_create() is called, it finds the first free key in the
1548 * bitmap, then set it to 1, saving the destructor altogether
1549 *
1550 * when pthread_key_delete() is called. it will erase the key's bitmap bit
1551 * and its destructor, and will also clear the key data in the TLS area of
1552 * all created threads. As mandated by Posix, it is the responsability of
1553 * the caller of pthread_key_delete() to properly reclaim the objects that
1554 * were pointed to by these data fields (either before or after the call).
1555 *
1556 */
1557
1558/* TLS Map implementation
1559 */
1560
1561#define TLSMAP_START (TLS_SLOT_MAX_WELL_KNOWN+1)
1562#define TLSMAP_SIZE BIONIC_TLS_SLOTS
1563#define TLSMAP_BITS 32
1564#define TLSMAP_WORDS ((TLSMAP_SIZE+TLSMAP_BITS-1)/TLSMAP_BITS)
1565#define TLSMAP_WORD(m,k) (m)->map[(k)/TLSMAP_BITS]
1566#define TLSMAP_MASK(k) (1U << ((k)&(TLSMAP_BITS-1)))
1567
1568/* this macro is used to quickly check that a key belongs to a reasonable range */
1569#define TLSMAP_VALIDATE_KEY(key) \
1570 ((key) >= TLSMAP_START && (key) < TLSMAP_SIZE)
1571
1572/* the type of tls key destructor functions */
1573typedef void (*tls_dtor_t)(void*);
1574
1575typedef struct {
1576 int init; /* see comment in tlsmap_lock() */
1577 uint32_t map[TLSMAP_WORDS]; /* bitmap of allocated keys */
1578 tls_dtor_t dtors[TLSMAP_SIZE]; /* key destructors */
1579} tlsmap_t;
1580
1581static pthread_mutex_t _tlsmap_lock = PTHREAD_MUTEX_INITIALIZER;
1582static tlsmap_t _tlsmap;
1583
1584/* lock the global TLS map lock and return a handle to it */
1585static __inline__ tlsmap_t* tlsmap_lock(void)
1586{
1587 tlsmap_t* m = &_tlsmap;
1588
1589 pthread_mutex_lock(&_tlsmap_lock);
1590 /* we need to initialize the first entry of the 'map' array
1591 * with the value TLS_DEFAULT_ALLOC_MAP. doing it statically
1592 * when declaring _tlsmap is a bit awkward and is going to
1593 * produce warnings, so do it the first time we use the map
1594 * instead
1595 */
1596 if (__unlikely(!m->init)) {
1597 TLSMAP_WORD(m,0) = TLS_DEFAULT_ALLOC_MAP;
1598 m->init = 1;
1599 }
1600 return m;
1601}
1602
1603/* unlock the global TLS map */
1604static __inline__ void tlsmap_unlock(tlsmap_t* m)
1605{
1606 pthread_mutex_unlock(&_tlsmap_lock);
1607 (void)m; /* a good compiler is a happy compiler */
1608}
1609
1610/* test to see wether a key is allocated */
1611static __inline__ int tlsmap_test(tlsmap_t* m, int key)
1612{
1613 return (TLSMAP_WORD(m,key) & TLSMAP_MASK(key)) != 0;
1614}
1615
1616/* set the destructor and bit flag on a newly allocated key */
1617static __inline__ void tlsmap_set(tlsmap_t* m, int key, tls_dtor_t dtor)
1618{
1619 TLSMAP_WORD(m,key) |= TLSMAP_MASK(key);
1620 m->dtors[key] = dtor;
1621}
1622
1623/* clear the destructor and bit flag on an existing key */
1624static __inline__ void tlsmap_clear(tlsmap_t* m, int key)
1625{
1626 TLSMAP_WORD(m,key) &= ~TLSMAP_MASK(key);
1627 m->dtors[key] = NULL;
1628}
1629
1630/* allocate a new TLS key, return -1 if no room left */
1631static int tlsmap_alloc(tlsmap_t* m, tls_dtor_t dtor)
1632{
1633 int key;
1634
1635 for ( key = TLSMAP_START; key < TLSMAP_SIZE; key++ ) {
1636 if ( !tlsmap_test(m, key) ) {
1637 tlsmap_set(m, key, dtor);
1638 return key;
1639 }
1640 }
1641 return -1;
1642}
1643
1644
1645int pthread_key_create(pthread_key_t *key, void (*destructor_function)(void *))
1646{
1647 uint32_t err = ENOMEM;
1648 tlsmap_t* map = tlsmap_lock();
1649 int k = tlsmap_alloc(map, destructor_function);
1650
1651 if (k >= 0) {
1652 *key = k;
1653 err = 0;
1654 }
1655 tlsmap_unlock(map);
1656 return err;
1657}
1658
1659
1660/* This deletes a pthread_key_t. note that the standard mandates that this does
1661 * not call the destructor of non-NULL key values. Instead, it is the
1662 * responsability of the caller to properly dispose of the corresponding data
1663 * and resources, using any mean it finds suitable.
1664 *
1665 * On the other hand, this function will clear the corresponding key data
1666 * values in all known threads. this prevents later (invalid) calls to
1667 * pthread_getspecific() to receive invalid/stale values.
1668 */
1669int pthread_key_delete(pthread_key_t key)
1670{
1671 uint32_t err;
1672 pthread_internal_t* thr;
1673 tlsmap_t* map;
1674
1675 if (!TLSMAP_VALIDATE_KEY(key)) {
1676 return EINVAL;
1677 }
1678
1679 map = tlsmap_lock();
1680
1681 if (!tlsmap_test(map, key)) {
1682 err = EINVAL;
1683 goto err1;
1684 }
1685
1686 /* clear value in all threads */
1687 pthread_mutex_lock(&gThreadListLock);
1688 for ( thr = gThreadList; thr != NULL; thr = thr->next ) {
1689 /* avoid zombie threads with a negative 'join_count'. these are really
1690 * already dead and don't have a TLS area anymore.
1691 *
1692 * similarly, it is possible to have thr->tls == NULL for threads that
1693 * were just recently created through pthread_create() but whose
1694 * startup trampoline (__thread_entry) hasn't been run yet by the
1695 * scheduler. so check for this too.
1696 */
1697 if (thr->join_count < 0 || !thr->tls)
1698 continue;
1699
1700 thr->tls[key] = NULL;
1701 }
1702 tlsmap_clear(map, key);
1703
1704 pthread_mutex_unlock(&gThreadListLock);
1705 err = 0;
1706
1707err1:
1708 tlsmap_unlock(map);
1709 return err;
1710}
1711
1712
1713int pthread_setspecific(pthread_key_t key, const void *ptr)
1714{
1715 int err = EINVAL;
1716 tlsmap_t* map;
1717
1718 if (TLSMAP_VALIDATE_KEY(key)) {
1719 /* check that we're trying to set data for an allocated key */
1720 map = tlsmap_lock();
1721 if (tlsmap_test(map, key)) {
1722 ((uint32_t *)__get_tls())[key] = (uint32_t)ptr;
1723 err = 0;
1724 }
1725 tlsmap_unlock(map);
1726 }
1727 return err;
1728}
1729
1730void * pthread_getspecific(pthread_key_t key)
1731{
1732 if (!TLSMAP_VALIDATE_KEY(key)) {
1733 return NULL;
1734 }
1735
1736 /* for performance reason, we do not lock/unlock the global TLS map
1737 * to check that the key is properly allocated. if the key was not
1738 * allocated, the value read from the TLS should always be NULL
1739 * due to pthread_key_delete() clearing the values for all threads.
1740 */
1741 return (void *)(((unsigned *)__get_tls())[key]);
1742}
1743
1744/* Posix mandates that this be defined in <limits.h> but we don't have
1745 * it just yet.
1746 */
1747#ifndef PTHREAD_DESTRUCTOR_ITERATIONS
1748# define PTHREAD_DESTRUCTOR_ITERATIONS 4
1749#endif
1750
1751/* this function is called from pthread_exit() to remove all TLS key data
1752 * from this thread's TLS area. this must call the destructor of all keys
1753 * that have a non-NULL data value (and a non-NULL destructor).
1754 *
1755 * because destructors can do funky things like deleting/creating other
1756 * keys, we need to implement this in a loop
1757 */
1758static void pthread_key_clean_all(void)
1759{
1760 tlsmap_t* map;
1761 void** tls = (void**)__get_tls();
1762 int rounds = PTHREAD_DESTRUCTOR_ITERATIONS;
1763
1764 map = tlsmap_lock();
1765
1766 for (rounds = PTHREAD_DESTRUCTOR_ITERATIONS; rounds > 0; rounds--)
1767 {
1768 int kk, count = 0;
1769
1770 for (kk = TLSMAP_START; kk < TLSMAP_SIZE; kk++) {
1771 if ( tlsmap_test(map, kk) )
1772 {
1773 void* data = tls[kk];
1774 tls_dtor_t dtor = map->dtors[kk];
1775
1776 if (data != NULL && dtor != NULL)
1777 {
1778 /* we need to clear the key data now, this will prevent the
1779 * destructor (or a later one) from seeing the old value if
1780 * it calls pthread_getspecific() for some odd reason
1781 *
1782 * we do not do this if 'dtor == NULL' just in case another
1783 * destructor function might be responsible for manually
1784 * releasing the corresponding data.
1785 */
1786 tls[kk] = NULL;
1787
1788 /* because the destructor is free to call pthread_key_create
1789 * and/or pthread_key_delete, we need to temporarily unlock
1790 * the TLS map
1791 */
1792 tlsmap_unlock(map);
1793 (*dtor)(data);
1794 map = tlsmap_lock();
1795
1796 count += 1;
1797 }
1798 }
1799 }
1800
1801 /* if we didn't call any destructor, there is no need to check the
1802 * TLS data again
1803 */
1804 if (count == 0)
1805 break;
1806 }
1807 tlsmap_unlock(map);
1808}
1809
1810// man says this should be in <linux/unistd.h>, but it isn't
1811extern int tkill(int tid, int sig);
1812
1813int pthread_kill(pthread_t tid, int sig)
1814{
1815 int ret;
1816 int old_errno = errno;
1817 pthread_internal_t * thread = (pthread_internal_t *)tid;
1818
1819 ret = tkill(thread->kernel_id, sig);
1820 if (ret < 0) {
1821 ret = errno;
1822 errno = old_errno;
1823 }
1824
1825 return ret;
1826}
1827
1828extern int __rt_sigprocmask(int, const sigset_t *, sigset_t *, size_t);
1829
1830int pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
1831{
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001832 /* pthread_sigmask must return the error code, but the syscall
1833 * will set errno instead and return 0/-1
1834 */
1835 int ret, old_errno = errno;
1836
1837 ret = __rt_sigprocmask(how, set, oset, _NSIG / 8);
1838 if (ret < 0)
1839 ret = errno;
1840
1841 errno = old_errno;
1842 return ret;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001843}
1844
1845
1846int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
1847{
1848 const int CLOCK_IDTYPE_BITS = 3;
1849 pthread_internal_t* thread = (pthread_internal_t*)tid;
1850
1851 if (!thread)
1852 return ESRCH;
1853
1854 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
1855 return 0;
1856}
1857
1858
1859/* NOTE: this implementation doesn't support a init function that throws a C++ exception
1860 * or calls fork()
1861 */
1862int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
1863{
1864 static pthread_mutex_t once_lock = PTHREAD_MUTEX_INITIALIZER;
1865
1866 if (*once_control == PTHREAD_ONCE_INIT) {
1867 _normal_lock( &once_lock );
1868 if (*once_control == PTHREAD_ONCE_INIT) {
1869 (*init_routine)();
1870 *once_control = ~PTHREAD_ONCE_INIT;
1871 }
1872 _normal_unlock( &once_lock );
1873 }
1874 return 0;
1875}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03001876
1877/* This value is not exported by kernel headers, so hardcode it here */
1878#define MAX_TASK_COMM_LEN 16
1879#define TASK_COMM_FMT "/proc/self/task/%u/comm"
1880
1881int pthread_setname_np(pthread_t thid, const char *thname)
1882{
1883 size_t thname_len;
1884 int saved_errno, ret;
1885
1886 if (thid == 0 || thname == NULL)
1887 return EINVAL;
1888
1889 thname_len = strlen(thname);
1890 if (thname_len >= MAX_TASK_COMM_LEN)
1891 return ERANGE;
1892
1893 saved_errno = errno;
1894 if (thid == pthread_self())
1895 {
1896 ret = prctl(PR_SET_NAME, (unsigned long)thname, 0, 0, 0) ? errno : 0;
1897 }
1898 else
1899 {
1900 /* Have to change another thread's name */
1901 pthread_internal_t *thread = (pthread_internal_t *)thid;
1902 char comm_name[sizeof(TASK_COMM_FMT) + 8];
1903 ssize_t n;
1904 int fd;
1905
1906 snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, (unsigned int)thread->kernel_id);
1907 fd = open(comm_name, O_RDWR);
1908 if (fd == -1)
1909 {
1910 ret = errno;
1911 goto exit;
1912 }
1913 n = TEMP_FAILURE_RETRY(write(fd, thname, thname_len));
1914 close(fd);
1915
1916 if (n < 0)
1917 ret = errno;
1918 else if ((size_t)n != thname_len)
1919 ret = EIO;
1920 else
1921 ret = 0;
1922 }
1923exit:
1924 errno = saved_errno;
1925 return ret;
1926}