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