blob: 3294ceafe80d1ffbf7473555c230576c568c8258 [file] [log] [blame]
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28#include <sys/types.h>
29#include <unistd.h>
30#include <signal.h>
31#include <stdint.h>
32#include <stdio.h>
33#include <stdlib.h>
34#include <errno.h>
35#include <sys/atomics.h>
36#include <bionic_tls.h>
37#include <sys/mman.h>
38#include <pthread.h>
39#include <time.h>
40#include "pthread_internal.h"
41#include "thread_private.h"
42#include <limits.h>
43#include <memory.h>
44#include <assert.h>
45#include <malloc.h>
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -070046#include <linux/futex.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080047
48extern int __pthread_clone(int (*fn)(void*), void *child_stack, int flags, void *arg);
49extern void _exit_with_stack_teardown(void * stackBase, int stackSize, int retCode);
50extern void _exit_thread(int retCode);
51extern int __set_errno(int);
52
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -070053#define __likely(cond) __builtin_expect(!!(cond), 1)
54#define __unlikely(cond) __builtin_expect(!!(cond), 0)
55
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080056void _thread_created_hook(pid_t thread_id) __attribute__((noinline));
57
58#define PTHREAD_ATTR_FLAG_DETACHED 0x00000001
59#define PTHREAD_ATTR_FLAG_USER_STACK 0x00000002
60
61#define DEFAULT_STACKSIZE (1024 * 1024)
62#define STACKBASE 0x10000000
63
64static uint8_t * gStackBase = (uint8_t *)STACKBASE;
65
66static pthread_mutex_t mmap_lock = PTHREAD_MUTEX_INITIALIZER;
67
68
69static const pthread_attr_t gDefaultPthreadAttr = {
70 .flags = 0,
71 .stack_base = NULL,
72 .stack_size = DEFAULT_STACKSIZE,
73 .guard_size = PAGE_SIZE,
74 .sched_policy = SCHED_NORMAL,
75 .sched_priority = 0
76};
77
78#define INIT_THREADS 1
79
80static pthread_internal_t* gThreadList = NULL;
81static pthread_mutex_t gThreadListLock = PTHREAD_MUTEX_INITIALIZER;
82static pthread_mutex_t gDebuggerNotificationLock = PTHREAD_MUTEX_INITIALIZER;
83
84
85/* we simply malloc/free the internal pthread_internal_t structures. we may
86 * want to use a different allocation scheme in the future, but this one should
87 * be largely enough
88 */
89static pthread_internal_t*
90_pthread_internal_alloc(void)
91{
92 pthread_internal_t* thread;
93
94 thread = calloc( sizeof(*thread), 1 );
95 if (thread)
96 thread->intern = 1;
97
98 return thread;
99}
100
101static void
102_pthread_internal_free( pthread_internal_t* thread )
103{
104 if (thread && thread->intern) {
105 thread->intern = 0; /* just in case */
106 free (thread);
107 }
108}
109
110
111static void
112_pthread_internal_remove_locked( pthread_internal_t* thread )
113{
114 thread->next->pref = thread->pref;
115 thread->pref[0] = thread->next;
116}
117
118static void
119_pthread_internal_remove( pthread_internal_t* thread )
120{
121 pthread_mutex_lock(&gThreadListLock);
122 _pthread_internal_remove_locked(thread);
123 pthread_mutex_unlock(&gThreadListLock);
124}
125
126static void
127_pthread_internal_add( pthread_internal_t* thread )
128{
129 pthread_mutex_lock(&gThreadListLock);
130 thread->pref = &gThreadList;
131 thread->next = thread->pref[0];
132 if (thread->next)
133 thread->next->pref = &thread->next;
134 thread->pref[0] = thread;
135 pthread_mutex_unlock(&gThreadListLock);
136}
137
138pthread_internal_t*
139__get_thread(void)
140{
141 void** tls = (void**)__get_tls();
142
143 return (pthread_internal_t*) tls[TLS_SLOT_THREAD_ID];
144}
145
146
147void*
148__get_stack_base(int *p_stack_size)
149{
150 pthread_internal_t* thread = __get_thread();
151
152 *p_stack_size = thread->attr.stack_size;
153 return thread->attr.stack_base;
154}
155
156
157void __init_tls(void** tls, void* thread)
158{
159 int nn;
160
161 ((pthread_internal_t*)thread)->tls = tls;
162
163 // slot 0 must point to the tls area, this is required by the implementation
164 // of the x86 Linux kernel thread-local-storage
165 tls[TLS_SLOT_SELF] = (void*)tls;
166 tls[TLS_SLOT_THREAD_ID] = thread;
167 for (nn = TLS_SLOT_ERRNO; nn < BIONIC_TLS_SLOTS; nn++)
168 tls[nn] = 0;
169
170 __set_tls( (void*)tls );
171}
172
173
174/*
175 * This trampoline is called from the assembly clone() function
176 */
177void __thread_entry(int (*func)(void*), void *arg, void **tls)
178{
179 int retValue;
180 pthread_internal_t * thrInfo;
181
182 // Wait for our creating thread to release us. This lets it have time to
183 // notify gdb about this thread before it starts doing anything.
184 pthread_mutex_t * start_mutex = (pthread_mutex_t *)&tls[TLS_SLOT_SELF];
185 pthread_mutex_lock(start_mutex);
186 pthread_mutex_destroy(start_mutex);
187
188 thrInfo = (pthread_internal_t *) tls[TLS_SLOT_THREAD_ID];
189
190 __init_tls( tls, thrInfo );
191
192 pthread_exit( (void*)func(arg) );
193}
194
195void _init_thread(pthread_internal_t * thread, pid_t kernel_id, pthread_attr_t * attr, void * stack_base)
196{
197 if (attr == NULL) {
198 thread->attr = gDefaultPthreadAttr;
199 } else {
200 thread->attr = *attr;
201 }
202 thread->attr.stack_base = stack_base;
203 thread->kernel_id = kernel_id;
204
205 // set the scheduling policy/priority of the thread
206 if (thread->attr.sched_policy != SCHED_NORMAL) {
207 struct sched_param param;
208 param.sched_priority = thread->attr.sched_priority;
209 sched_setscheduler(kernel_id, thread->attr.sched_policy, &param);
210 }
211
212 pthread_cond_init(&thread->join_cond, NULL);
213 thread->join_count = 0;
214
215 thread->cleanup_stack = NULL;
216
217 _pthread_internal_add(thread);
218}
219
220
221/* XXX stacks not reclaimed if thread spawn fails */
222/* XXX stacks address spaces should be reused if available again */
223
224static void *mkstack(size_t size, size_t guard_size)
225{
226 void * stack;
227
228 pthread_mutex_lock(&mmap_lock);
229
230 stack = mmap((void *)gStackBase, size,
231 PROT_READ | PROT_WRITE,
232 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
233 -1, 0);
234
235 if(stack == MAP_FAILED) {
236 stack = NULL;
237 goto done;
238 }
239
240 if(mprotect(stack, guard_size, PROT_NONE)){
241 munmap(stack, size);
242 stack = NULL;
243 goto done;
244 }
245
246done:
247 pthread_mutex_unlock(&mmap_lock);
248 return stack;
249}
250
251/*
252 * Create a new thread. The thread's stack is layed out like so:
253 *
254 * +---------------------------+
255 * | pthread_internal_t |
256 * +---------------------------+
257 * | |
258 * | TLS area |
259 * | |
260 * +---------------------------+
261 * | |
262 * . .
263 * . stack area .
264 * . .
265 * | |
266 * +---------------------------+
267 * | guard page |
268 * +---------------------------+
269 *
270 * note that TLS[0] must be a pointer to itself, this is required
271 * by the thread-local storage implementation of the x86 Linux
272 * kernel, where the TLS pointer is read by reading fs:[0]
273 */
274int pthread_create(pthread_t *thread_out, pthread_attr_t const * attr,
275 void *(*start_routine)(void *), void * arg)
276{
277 char* stack;
278 void** tls;
279 int tid;
280 pthread_mutex_t * start_mutex;
281 pthread_internal_t * thread;
282 int madestack = 0;
283 int old_errno = errno;
284
285 /* this will inform the rest of the C library that at least one thread
286 * was created. this will enforce certain functions to acquire/release
287 * locks (e.g. atexit()) to protect shared global structures.
288 *
289 * this works because pthread_create() is not called by the C library
290 * initialization routine that sets up the main thread's data structures.
291 */
292 __isthreaded = 1;
293
294 thread = _pthread_internal_alloc();
295 if (thread == NULL)
296 return ENOMEM;
297
298 if (attr == NULL) {
299 attr = &gDefaultPthreadAttr;
300 }
301
302 // make sure the stack is PAGE_SIZE aligned
303 size_t stackSize = (attr->stack_size +
304 (PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
305
306 if (!attr->stack_base) {
307 stack = mkstack(stackSize, attr->guard_size);
308 if(stack == NULL) {
309 _pthread_internal_free(thread);
310 return ENOMEM;
311 }
312 madestack = 1;
313 } else {
314 stack = attr->stack_base;
315 }
316
317 // Make room for TLS
318 tls = (void**)(stack + stackSize - BIONIC_TLS_SLOTS*sizeof(void*));
319
320 // Create a mutex for the thread in TLS_SLOT_SELF to wait on once it starts so we can keep
321 // it from doing anything until after we notify the debugger about it
322 start_mutex = (pthread_mutex_t *) &tls[TLS_SLOT_SELF];
323 pthread_mutex_init(start_mutex, NULL);
324 pthread_mutex_lock(start_mutex);
325
326 tls[TLS_SLOT_THREAD_ID] = thread;
327
328 tid = __pthread_clone((int(*)(void*))start_routine, tls,
329 CLONE_FILES | CLONE_FS | CLONE_VM | CLONE_SIGHAND
330 | CLONE_THREAD | CLONE_SYSVSEM | CLONE_DETACHED,
331 arg);
332
333 if(tid < 0) {
334 int result;
335 if (madestack)
336 munmap(stack, stackSize);
337 _pthread_internal_free(thread);
338 result = errno;
339 errno = old_errno;
340 return result;
341 }
342
343 _init_thread(thread, tid, (pthread_attr_t*)attr, stack);
344
345 if (!madestack)
346 thread->attr.flags |= PTHREAD_ATTR_FLAG_USER_STACK;
347
348 // Notify any debuggers about the new thread
349 pthread_mutex_lock(&gDebuggerNotificationLock);
350 _thread_created_hook(tid);
351 pthread_mutex_unlock(&gDebuggerNotificationLock);
352
353 // Let the thread do it's thing
354 pthread_mutex_unlock(start_mutex);
355
356 *thread_out = (pthread_t)thread;
357 return 0;
358}
359
360
361int pthread_attr_init(pthread_attr_t * attr)
362{
363 *attr = gDefaultPthreadAttr;
364 return 0;
365}
366
367int pthread_attr_destroy(pthread_attr_t * attr)
368{
369 memset(attr, 0x42, sizeof(pthread_attr_t));
370 return 0;
371}
372
373int pthread_attr_setdetachstate(pthread_attr_t * attr, int state)
374{
375 if (state == PTHREAD_CREATE_DETACHED) {
376 attr->flags |= PTHREAD_ATTR_FLAG_DETACHED;
377 } else if (state == PTHREAD_CREATE_JOINABLE) {
378 attr->flags &= ~PTHREAD_ATTR_FLAG_DETACHED;
379 } else {
380 return EINVAL;
381 }
382 return 0;
383}
384
385int pthread_attr_getdetachstate(pthread_attr_t const * attr, int * state)
386{
387 *state = (attr->flags & PTHREAD_ATTR_FLAG_DETACHED)
388 ? PTHREAD_CREATE_DETACHED
389 : PTHREAD_CREATE_JOINABLE;
390 return 0;
391}
392
393int pthread_attr_setschedpolicy(pthread_attr_t * attr, int policy)
394{
395 attr->sched_policy = policy;
396 return 0;
397}
398
399int pthread_attr_getschedpolicy(pthread_attr_t const * attr, int * policy)
400{
401 *policy = attr->sched_policy;
402 return 0;
403}
404
405int pthread_attr_setschedparam(pthread_attr_t * attr, struct sched_param const * param)
406{
407 attr->sched_priority = param->sched_priority;
408 return 0;
409}
410
411int pthread_attr_getschedparam(pthread_attr_t const * attr, struct sched_param * param)
412{
413 param->sched_priority = attr->sched_priority;
414 return 0;
415}
416
417int pthread_attr_setstacksize(pthread_attr_t * attr, size_t stack_size)
418{
419 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
420 return EINVAL;
421 }
422 attr->stack_size = stack_size;
423 return 0;
424}
425
426int pthread_attr_getstacksize(pthread_attr_t const * attr, size_t * stack_size)
427{
428 *stack_size = attr->stack_size;
429 return 0;
430}
431
432int pthread_attr_setstackaddr(pthread_attr_t * attr, void * stack_addr)
433{
434#if 1
435 // It's not clear if this is setting the top or bottom of the stack, so don't handle it for now.
436 return ENOSYS;
437#else
438 if ((uint32_t)stack_addr & (PAGE_SIZE - 1)) {
439 return EINVAL;
440 }
441 attr->stack_base = stack_addr;
442 return 0;
443#endif
444}
445
446int pthread_attr_getstackaddr(pthread_attr_t const * attr, void ** stack_addr)
447{
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700448 *stack_addr = (char*)attr->stack_base + attr->stack_size;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800449 return 0;
450}
451
452int pthread_attr_setstack(pthread_attr_t * attr, void * stack_base, size_t stack_size)
453{
454 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
455 return EINVAL;
456 }
457 if ((uint32_t)stack_base & (PAGE_SIZE - 1)) {
458 return EINVAL;
459 }
460 attr->stack_base = stack_base;
461 attr->stack_size = stack_size;
462 return 0;
463}
464
465int pthread_attr_getstack(pthread_attr_t const * attr, void ** stack_base, size_t * stack_size)
466{
467 *stack_base = attr->stack_base;
468 *stack_size = attr->stack_size;
469 return 0;
470}
471
472int pthread_attr_setguardsize(pthread_attr_t * attr, size_t guard_size)
473{
474 if (guard_size & (PAGE_SIZE - 1) || guard_size < PAGE_SIZE) {
475 return EINVAL;
476 }
477
478 attr->guard_size = guard_size;
479 return 0;
480}
481
482int pthread_attr_getguardsize(pthread_attr_t const * attr, size_t * guard_size)
483{
484 *guard_size = attr->guard_size;
485 return 0;
486}
487
488int pthread_getattr_np(pthread_t thid, pthread_attr_t * attr)
489{
490 pthread_internal_t * thread = (pthread_internal_t *)thid;
491 *attr = thread->attr;
492 return 0;
493}
494
495int pthread_attr_setscope(pthread_attr_t *attr, int scope)
496{
497 if (scope == PTHREAD_SCOPE_SYSTEM)
498 return 0;
499 if (scope == PTHREAD_SCOPE_PROCESS)
500 return ENOTSUP;
501
502 return EINVAL;
503}
504
505int pthread_attr_getscope(pthread_attr_t const *attr)
506{
507 return PTHREAD_SCOPE_SYSTEM;
508}
509
510
511/* CAVEAT: our implementation of pthread_cleanup_push/pop doesn't support C++ exceptions
512 * and thread cancelation
513 */
514
515void __pthread_cleanup_push( __pthread_cleanup_t* c,
516 __pthread_cleanup_func_t routine,
517 void* arg )
518{
519 pthread_internal_t* thread = __get_thread();
520
521 c->__cleanup_routine = routine;
522 c->__cleanup_arg = arg;
523 c->__cleanup_prev = thread->cleanup_stack;
524 thread->cleanup_stack = c;
525}
526
527void __pthread_cleanup_pop( __pthread_cleanup_t* c, int execute )
528{
529 pthread_internal_t* thread = __get_thread();
530
531 thread->cleanup_stack = c->__cleanup_prev;
532 if (execute)
533 c->__cleanup_routine(c->__cleanup_arg);
534}
535
536/* used by pthread_exit() to clean all TLS keys of the current thread */
537static void pthread_key_clean_all(void);
538
539void pthread_exit(void * retval)
540{
541 pthread_internal_t* thread = __get_thread();
542 void* stack_base = thread->attr.stack_base;
543 int stack_size = thread->attr.stack_size;
544 int user_stack = (thread->attr.flags & PTHREAD_ATTR_FLAG_USER_STACK) != 0;
545
546 // call the cleanup handlers first
547 while (thread->cleanup_stack) {
548 __pthread_cleanup_t* c = thread->cleanup_stack;
549 thread->cleanup_stack = c->__cleanup_prev;
550 c->__cleanup_routine(c->__cleanup_arg);
551 }
552
553 // call the TLS destructors, it is important to do that before removing this
554 // thread from the global list. this will ensure that if someone else deletes
555 // a TLS key, the corresponding value will be set to NULL in this thread's TLS
556 // space (see pthread_key_delete)
557 pthread_key_clean_all();
558
559 // if the thread is detached, destroy the pthread_internal_t
560 // otherwise, keep it in memory and signal any joiners
561 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
562 _pthread_internal_remove(thread);
563 _pthread_internal_free(thread);
564 } else {
565 /* the join_count field is used to store the number of threads waiting for
566 * the termination of this thread with pthread_join(),
567 *
568 * if it is positive we need to signal the waiters, and we do not touch
569 * the count (it will be decremented by the waiters, the last one will
570 * also remove/free the thread structure
571 *
572 * if it is zero, we set the count value to -1 to indicate that the
573 * thread is in 'zombie' state: it has stopped executing, and its stack
574 * is gone (as well as its TLS area). when another thread calls pthread_join()
575 * on it, it will immediately free the thread and return.
576 */
577 pthread_mutex_lock(&gThreadListLock);
578 thread->return_value = retval;
579 if (thread->join_count > 0) {
580 pthread_cond_broadcast(&thread->join_cond);
581 } else {
582 thread->join_count = -1; /* zombie thread */
583 }
584 pthread_mutex_unlock(&gThreadListLock);
585 }
586
587 // destroy the thread stack
588 if (user_stack)
589 _exit_thread((int)retval);
590 else
591 _exit_with_stack_teardown(stack_base, stack_size, (int)retval);
592}
593
594int pthread_join(pthread_t thid, void ** ret_val)
595{
596 pthread_internal_t* thread = (pthread_internal_t*)thid;
597 int count;
598
599 // check that the thread still exists and is not detached
600 pthread_mutex_lock(&gThreadListLock);
601
602 for (thread = gThreadList; thread != NULL; thread = thread->next)
603 if (thread == (pthread_internal_t*)thid)
604 break;
605
606 if (!thread) {
607 pthread_mutex_unlock(&gThreadListLock);
608 return ESRCH;
609 }
610
611 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
612 pthread_mutex_unlock(&gThreadListLock);
613 return EINVAL;
614 }
615
616 /* wait for thread death when needed
617 *
618 * if the 'join_count' is negative, this is a 'zombie' thread that
619 * is already dead and without stack/TLS
620 *
621 * otherwise, we need to increment 'join-count' and wait to be signaled
622 */
623 count = thread->join_count;
624 if (count >= 0) {
625 thread->join_count += 1;
626 pthread_cond_wait( &thread->join_cond, &gThreadListLock );
627 count = --thread->join_count;
628 }
629 if (ret_val)
630 *ret_val = thread->return_value;
631
632 /* remove thread descriptor when we're the last joiner or when the
633 * thread was already a zombie.
634 */
635 if (count <= 0) {
636 _pthread_internal_remove_locked(thread);
637 _pthread_internal_free(thread);
638 }
639 pthread_mutex_unlock(&gThreadListLock);
640 return 0;
641}
642
643int pthread_detach( pthread_t thid )
644{
645 pthread_internal_t* thread;
646 int result = 0;
647 int flags;
648
649 pthread_mutex_lock(&gThreadListLock);
650 for (thread = gThreadList; thread != NULL; thread = thread->next)
651 if (thread == (pthread_internal_t*)thid)
652 goto FoundIt;
653
654 result = ESRCH;
655 goto Exit;
656
657FoundIt:
658 do {
659 flags = thread->attr.flags;
660
661 if ( flags & PTHREAD_ATTR_FLAG_DETACHED ) {
662 /* thread is not joinable ! */
663 result = EINVAL;
664 goto Exit;
665 }
666 }
667 while ( __atomic_cmpxchg( flags, flags | PTHREAD_ATTR_FLAG_DETACHED,
668 (volatile int*)&thread->attr.flags ) != 0 );
669Exit:
670 pthread_mutex_unlock(&gThreadListLock);
671 return result;
672}
673
674pthread_t pthread_self(void)
675{
676 return (pthread_t)__get_thread();
677}
678
679int pthread_equal(pthread_t one, pthread_t two)
680{
681 return (one == two ? 1 : 0);
682}
683
684int pthread_getschedparam(pthread_t thid, int * policy,
685 struct sched_param * param)
686{
687 int old_errno = errno;
688
689 pthread_internal_t * thread = (pthread_internal_t *)thid;
690 int err = sched_getparam(thread->kernel_id, param);
691 if (!err) {
692 *policy = sched_getscheduler(thread->kernel_id);
693 } else {
694 err = errno;
695 errno = old_errno;
696 }
697 return err;
698}
699
700int pthread_setschedparam(pthread_t thid, int policy,
701 struct sched_param const * param)
702{
703 pthread_internal_t * thread = (pthread_internal_t *)thid;
704 int old_errno = errno;
705 int ret;
706
707 ret = sched_setscheduler(thread->kernel_id, policy, param);
708 if (ret < 0) {
709 ret = errno;
710 errno = old_errno;
711 }
712 return ret;
713}
714
715
716int __futex_wait(volatile void *ftx, int val, const struct timespec *timeout);
717int __futex_wake(volatile void *ftx, int count);
718
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700719int __futex_syscall3(volatile void *ftx, int op, int val);
720int __futex_syscall4(volatile void *ftx, int op, int val, const struct timespec *timeout);
721
722#ifndef FUTEX_PRIVATE_FLAG
723#define FUTEX_PRIVATE_FLAG 128
724#endif
725
726#ifndef FUTEX_WAIT_PRIVATE
727#define FUTEX_WAIT_PRIVATE (FUTEX_WAIT|FUTEX_PRIVATE_FLAG)
728#endif
729
730#ifndef FUTEX_WAKE_PRIVATE
731#define FUTEX_WAKE_PRIVATE (FUTEX_WAKE|FUTEX_PRIVATE_FLAG)
732#endif
733
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800734// mutex lock states
735//
736// 0: unlocked
737// 1: locked, no waiters
738// 2: locked, maybe waiters
739
740/* a mutex is implemented as a 32-bit integer holding the following fields
741 *
742 * bits: name description
743 * 31-16 tid owner thread's kernel id (recursive and errorcheck only)
744 * 15-14 type mutex type
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700745 * 13 shared process-shared flag
746 * 12-2 counter counter of recursive mutexes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800747 * 1-0 state lock state (0, 1 or 2)
748 */
749
750
751#define MUTEX_OWNER(m) (((m)->value >> 16) & 0xffff)
752#define MUTEX_COUNTER(m) (((m)->value >> 2) & 0xfff)
753
754#define MUTEX_TYPE_MASK 0xc000
755#define MUTEX_TYPE_NORMAL 0x0000
756#define MUTEX_TYPE_RECURSIVE 0x4000
757#define MUTEX_TYPE_ERRORCHECK 0x8000
758
759#define MUTEX_COUNTER_SHIFT 2
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700760#define MUTEX_COUNTER_MASK 0x1ffc
761#define MUTEX_SHARED_MASK 0x2000
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800762
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700763/* a mutex attribute holds the following fields
764 *
765 * bits: name description
766 * 0-3 type type of mutex
767 * 4 shared process-shared flag
768 */
769#define MUTEXATTR_TYPE_MASK 0x000f
770#define MUTEXATTR_SHARED_MASK 0x0010
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800771
772
773int pthread_mutexattr_init(pthread_mutexattr_t *attr)
774{
775 if (attr) {
776 *attr = PTHREAD_MUTEX_DEFAULT;
777 return 0;
778 } else {
779 return EINVAL;
780 }
781}
782
783int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
784{
785 if (attr) {
786 *attr = -1;
787 return 0;
788 } else {
789 return EINVAL;
790 }
791}
792
793int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
794{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700795 if (attr) {
796 int atype = (*attr & MUTEXATTR_TYPE_MASK);
797
798 if (atype >= PTHREAD_MUTEX_NORMAL &&
799 atype <= PTHREAD_MUTEX_ERRORCHECK) {
800 *type = atype;
801 return 0;
802 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800803 }
804 return EINVAL;
805}
806
807int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
808{
809 if (attr && type >= PTHREAD_MUTEX_NORMAL &&
810 type <= PTHREAD_MUTEX_ERRORCHECK ) {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700811 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800812 return 0;
813 }
814 return EINVAL;
815}
816
817/* process-shared mutexes are not supported at the moment */
818
819int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
820{
821 if (!attr)
822 return EINVAL;
823
Mathias Agopianb7681162009-07-13 22:00:33 -0700824 switch (pshared) {
825 case PTHREAD_PROCESS_PRIVATE:
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700826 *attr &= ~MUTEXATTR_SHARED_MASK;
827 return 0;
828
Mathias Agopianb7681162009-07-13 22:00:33 -0700829 case PTHREAD_PROCESS_SHARED:
830 /* our current implementation of pthread actually supports shared
831 * mutexes but won't cleanup if a process dies with the mutex held.
832 * Nevertheless, it's better than nothing. Shared mutexes are used
833 * by surfaceflinger and audioflinger.
834 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700835 *attr |= MUTEXATTR_SHARED_MASK;
Mathias Agopianb7681162009-07-13 22:00:33 -0700836 return 0;
837 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700838 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800839}
840
841int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
842{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700843 if (!attr || !pshared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800844 return EINVAL;
845
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700846 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED
847 : PTHREAD_PROCESS_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800848 return 0;
849}
850
851int pthread_mutex_init(pthread_mutex_t *mutex,
852 const pthread_mutexattr_t *attr)
853{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700854 int value = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800855
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700856 if (mutex == NULL)
857 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800858
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700859 if (__likely(attr == NULL)) {
860 mutex->value = MUTEX_TYPE_NORMAL;
861 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800862 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700863
864 if ((*attr & MUTEXATTR_SHARED_MASK) != 0)
865 value |= MUTEX_SHARED_MASK;
866
867 switch (*attr & MUTEXATTR_TYPE_MASK) {
868 case PTHREAD_MUTEX_NORMAL:
869 value |= MUTEX_TYPE_NORMAL;
870 break;
871 case PTHREAD_MUTEX_RECURSIVE:
872 value |= MUTEX_TYPE_RECURSIVE;
873 break;
874 case PTHREAD_MUTEX_ERRORCHECK:
875 value |= MUTEX_TYPE_ERRORCHECK;
876 break;
877 default:
878 return EINVAL;
879 }
880
881 mutex->value = value;
882 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800883}
884
885int pthread_mutex_destroy(pthread_mutex_t *mutex)
886{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700887 if (__unlikely(mutex == NULL))
888 return EINVAL;
889
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800890 mutex->value = 0xdead10cc;
891 return 0;
892}
893
894
895/*
896 * Lock a non-recursive mutex.
897 *
898 * As noted above, there are three states:
899 * 0 (unlocked, no contention)
900 * 1 (locked, no contention)
901 * 2 (locked, contention)
902 *
903 * Non-recursive mutexes don't use the thread-id or counter fields, and the
904 * "type" value is zero, so the only bits that will be set are the ones in
905 * the lock state field.
906 */
907static __inline__ void
908_normal_lock(pthread_mutex_t* mutex)
909{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700910 /* We need to preserve the shared flag during operations */
911 int shared = mutex->value & MUTEX_SHARED_MASK;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800912 /*
913 * The common case is an unlocked mutex, so we begin by trying to
914 * change the lock's state from 0 to 1. __atomic_cmpxchg() returns 0
915 * if it made the swap successfully. If the result is nonzero, this
916 * lock is already held by another thread.
917 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700918 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value ) != 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800919 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800920 * We want to go to sleep until the mutex is available, which
921 * requires promoting it to state 2. We need to swap in the new
922 * state value and then wait until somebody wakes us up.
923 *
924 * __atomic_swap() returns the previous value. We swap 2 in and
925 * see if we got zero back; if so, we have acquired the lock. If
926 * not, another thread still holds the lock and we wait again.
927 *
928 * The second argument to the __futex_wait() call is compared
929 * against the current value. If it doesn't match, __futex_wait()
930 * returns immediately (otherwise, it sleeps for a time specified
931 * by the third argument; 0 means sleep forever). This ensures
932 * that the mutex is in state 2 when we go to sleep on it, which
933 * guarantees a wake-up call.
934 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700935 int wait_op = shared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE;
936
937 while (__atomic_swap(shared|2, &mutex->value ) != (shared|0))
938 __futex_syscall4(&mutex->value, wait_op, shared|2, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800939 }
940}
941
942/*
943 * Release a non-recursive mutex. The caller is responsible for determining
944 * that we are in fact the owner of this lock.
945 */
946static __inline__ void
947_normal_unlock(pthread_mutex_t* mutex)
948{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700949 /* We need to preserve the shared flag during operations */
950 int shared = mutex->value & MUTEX_SHARED_MASK;
951
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800952 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700953 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800954 * to release the lock. __atomic_dec() returns the previous value;
955 * if it wasn't 1 we have to do some additional work.
956 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700957 if (__atomic_dec(&mutex->value) != (shared|1)) {
958 int wake_op = shared ? FUTEX_WAKE : FUTEX_WAKE_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800959 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800960 * Start by releasing the lock. The decrement changed it from
961 * "contended lock" to "uncontended lock", which means we still
962 * hold it, and anybody who tries to sneak in will push it back
963 * to state 2.
964 *
965 * Once we set it to zero the lock is up for grabs. We follow
966 * this with a __futex_wake() to ensure that one of the waiting
967 * threads has a chance to grab it.
968 *
969 * This doesn't cause a race with the swap/wait pair in
970 * _normal_lock(), because the __futex_wait() call there will
971 * return immediately if the mutex value isn't 2.
972 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700973 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800974
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800975 /*
976 * Wake up one waiting thread. We don't know which thread will be
977 * woken or when it'll start executing -- futexes make no guarantees
978 * here. There may not even be a thread waiting.
979 *
980 * The newly-woken thread will replace the 0 we just set above
981 * with 2, which means that when it eventually releases the mutex
982 * it will also call FUTEX_WAKE. This results in one extra wake
983 * call whenever a lock is contended, but lets us avoid forgetting
984 * anyone without requiring us to track the number of sleepers.
985 *
986 * It's possible for another thread to sneak in and grab the lock
987 * between the zero assignment above and the wake call below. If
988 * the new thread is "slow" and holds the lock for a while, we'll
989 * wake up a sleeper, which will swap in a 2 and then go back to
990 * sleep since the lock is still held. If the new thread is "fast",
991 * running to completion before we call wake, the thread we
992 * eventually wake will find an unlocked mutex and will execute.
993 * Either way we have correct behavior and nobody is orphaned on
994 * the wait queue.
995 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700996 __futex_syscall3(&mutex->value, wake_op, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800997 }
998}
999
1000static pthread_mutex_t __recursive_lock = PTHREAD_MUTEX_INITIALIZER;
1001
1002static void
1003_recursive_lock(void)
1004{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001005 _normal_lock(&__recursive_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001006}
1007
1008static void
1009_recursive_unlock(void)
1010{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001011 _normal_unlock(&__recursive_lock );
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001012}
1013
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001014int pthread_mutex_lock(pthread_mutex_t *mutex)
1015{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001016 int mtype, tid, new_lock_type, shared, wait_op;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001017
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001018 if (__unlikely(mutex == NULL))
1019 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001020
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001021 mtype = (mutex->value & MUTEX_TYPE_MASK);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001022 shared = (mutex->value & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001023
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001024 /* Handle normal case first */
1025 if ( __likely(mtype == MUTEX_TYPE_NORMAL) ) {
1026 _normal_lock(mutex);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001027 return 0;
1028 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001029
1030 /* Do we already own this recursive or error-check mutex ? */
1031 tid = __get_thread()->kernel_id;
1032 if ( tid == MUTEX_OWNER(mutex) )
1033 {
1034 int oldv, counter;
1035
1036 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1037 /* trying to re-lock a mutex we already acquired */
1038 return EDEADLK;
1039 }
1040 /*
1041 * We own the mutex, but other threads are able to change
1042 * the contents (e.g. promoting it to "contended"), so we
1043 * need to hold the global lock.
1044 */
1045 _recursive_lock();
1046 oldv = mutex->value;
1047 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1048 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1049 _recursive_unlock();
1050 return 0;
1051 }
1052
1053 /* We don't own the mutex, so try to get it.
1054 *
1055 * First, we try to change its state from 0 to 1, if this
1056 * doesn't work, try to change it to state 2.
1057 */
1058 new_lock_type = 1;
1059
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001060 /* compute futex wait opcode and restore shared flag in mtype */
1061 wait_op = shared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE;
1062 mtype |= shared;
1063
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001064 for (;;) {
1065 int oldv;
1066
1067 _recursive_lock();
1068 oldv = mutex->value;
1069 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1070 mutex->value = ((tid << 16) | mtype | new_lock_type);
1071 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1072 oldv ^= 3;
1073 mutex->value = oldv;
1074 }
1075 _recursive_unlock();
1076
1077 if (oldv == mtype)
1078 break;
1079
1080 /*
1081 * The lock was held, possibly contended by others. From
1082 * now on, if we manage to acquire the lock, we have to
1083 * assume that others are still contending for it so that
1084 * we'll wake them when we unlock it.
1085 */
1086 new_lock_type = 2;
1087
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001088 __futex_syscall4(&mutex->value, wait_op, oldv, NULL);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001089 }
1090 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001091}
1092
1093
1094int pthread_mutex_unlock(pthread_mutex_t *mutex)
1095{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001096 int mtype, tid, oldv, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001097
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001098 if (__unlikely(mutex == NULL))
1099 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001100
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001101 mtype = (mutex->value & MUTEX_TYPE_MASK);
1102 shared = (mutex->value & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001103
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001104 /* Handle common case first */
1105 if (__likely(mtype == MUTEX_TYPE_NORMAL)) {
1106 _normal_unlock(mutex);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001107 return 0;
1108 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001109
1110 /* Do we already own this recursive or error-check mutex ? */
1111 tid = __get_thread()->kernel_id;
1112 if ( tid != MUTEX_OWNER(mutex) )
1113 return EPERM;
1114
1115 /* We do, decrement counter or release the mutex if it is 0 */
1116 _recursive_lock();
1117 oldv = mutex->value;
1118 if (oldv & MUTEX_COUNTER_MASK) {
1119 mutex->value = oldv - (1 << MUTEX_COUNTER_SHIFT);
1120 oldv = 0;
1121 } else {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001122 mutex->value = shared | mtype;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001123 }
1124 _recursive_unlock();
1125
1126 /* Wake one waiting thread, if any */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001127 if ((oldv & 3) == 2) {
1128 int wake_op = shared ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT;
1129 __futex_syscall3(&mutex->value, wake_op, 1);
1130 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001131 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001132}
1133
1134
1135int pthread_mutex_trylock(pthread_mutex_t *mutex)
1136{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001137 int mtype, tid, oldv, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001138
1139 if (__unlikely(mutex == NULL))
1140 return EINVAL;
1141
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001142 mtype = (mutex->value & MUTEX_TYPE_MASK);
1143 shared = (mutex->value & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001144
1145 /* Handle common case first */
1146 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001147 {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001148 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value) == 0)
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001149 return 0;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001150
1151 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001152 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001153
1154 /* Do we already own this recursive or error-check mutex ? */
1155 tid = __get_thread()->kernel_id;
1156 if ( tid == MUTEX_OWNER(mutex) )
1157 {
1158 int counter;
1159
1160 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1161 /* already locked by ourselves */
1162 return EDEADLK;
1163 }
1164
1165 _recursive_lock();
1166 oldv = mutex->value;
1167 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1168 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1169 _recursive_unlock();
1170 return 0;
1171 }
1172
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001173 /* Restore sharing bit in mtype */
1174 mtype |= shared;
1175
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001176 /* Try to lock it, just once. */
1177 _recursive_lock();
1178 oldv = mutex->value;
1179 if (oldv == mtype) /* uncontended released lock => state 1 */
1180 mutex->value = ((tid << 16) | mtype | 1);
1181 _recursive_unlock();
1182
1183 if (oldv != mtype)
1184 return EBUSY;
1185
1186 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001187}
1188
1189
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001190/* initialize 'ts' with the difference between 'abstime' and the current time
1191 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
1192 */
1193static int
1194__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
1195{
1196 clock_gettime(clock, ts);
1197 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
1198 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
1199 if (ts->tv_nsec < 0) {
1200 ts->tv_sec--;
1201 ts->tv_nsec += 1000000000;
1202 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001203 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001204 return -1;
1205
1206 return 0;
1207}
1208
1209/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1210 * milliseconds.
1211 */
1212static void
1213__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1214{
1215 clock_gettime(clock, abstime);
1216 abstime->tv_sec += msecs/1000;
1217 abstime->tv_nsec += (msecs%1000)*1000000;
1218 if (abstime->tv_nsec >= 1000000000) {
1219 abstime->tv_sec++;
1220 abstime->tv_nsec -= 1000000000;
1221 }
1222}
1223
1224int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1225{
1226 clockid_t clock = CLOCK_MONOTONIC;
1227 struct timespec abstime;
1228 struct timespec ts;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001229 int mtype, tid, oldv, new_lock_type, shared, wait_op;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001230
1231 /* compute absolute expiration time */
1232 __timespec_to_relative_msec(&abstime, msecs, clock);
1233
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001234 if (__unlikely(mutex == NULL))
1235 return EINVAL;
1236
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001237 mtype = (mutex->value & MUTEX_TYPE_MASK);
1238 shared = (mutex->value & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001239
1240 /* Handle common case first */
1241 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001242 {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001243 int wait_op = shared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE;
1244
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001245 /* fast path for unconteded lock */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001246 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value) == 0)
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001247 return 0;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001248
1249 /* loop while needed */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001250 while (__atomic_swap(shared|2, &mutex->value) != (shared|0)) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001251 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1252 return EBUSY;
1253
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001254 __futex_syscall4(&mutex->value, wait_op, shared|2, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001255 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001256 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001257 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001258
1259 /* Do we already own this recursive or error-check mutex ? */
1260 tid = __get_thread()->kernel_id;
1261 if ( tid == MUTEX_OWNER(mutex) )
1262 {
1263 int oldv, counter;
1264
1265 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1266 /* already locked by ourselves */
1267 return EDEADLK;
1268 }
1269
1270 _recursive_lock();
1271 oldv = mutex->value;
1272 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1273 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1274 _recursive_unlock();
1275 return 0;
1276 }
1277
1278 /* We don't own the mutex, so try to get it.
1279 *
1280 * First, we try to change its state from 0 to 1, if this
1281 * doesn't work, try to change it to state 2.
1282 */
1283 new_lock_type = 1;
1284
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001285 /* Compute wait op and restore sharing bit in mtype */
1286 wait_op = shared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE;
1287 mtype |= shared;
1288
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001289 for (;;) {
1290 int oldv;
1291 struct timespec ts;
1292
1293 _recursive_lock();
1294 oldv = mutex->value;
1295 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1296 mutex->value = ((tid << 16) | mtype | new_lock_type);
1297 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1298 oldv ^= 3;
1299 mutex->value = oldv;
1300 }
1301 _recursive_unlock();
1302
1303 if (oldv == mtype)
1304 break;
1305
1306 /*
1307 * The lock was held, possibly contended by others. From
1308 * now on, if we manage to acquire the lock, we have to
1309 * assume that others are still contending for it so that
1310 * we'll wake them when we unlock it.
1311 */
1312 new_lock_type = 2;
1313
1314 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1315 return EBUSY;
1316
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001317 __futex_syscall4(&mutex->value, wait_op, oldv, &ts);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001318 }
1319 return 0;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001320}
1321
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001322int pthread_condattr_init(pthread_condattr_t *attr)
1323{
1324 if (attr == NULL)
1325 return EINVAL;
1326
1327 *attr = PTHREAD_PROCESS_PRIVATE;
1328 return 0;
1329}
1330
1331int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1332{
1333 if (attr == NULL || pshared == NULL)
1334 return EINVAL;
1335
1336 *pshared = *attr;
1337 return 0;
1338}
1339
1340int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1341{
1342 if (attr == NULL)
1343 return EINVAL;
1344
1345 if (pshared != PTHREAD_PROCESS_SHARED &&
1346 pshared != PTHREAD_PROCESS_PRIVATE)
1347 return EINVAL;
1348
1349 *attr = pshared;
1350 return 0;
1351}
1352
1353int pthread_condattr_destroy(pthread_condattr_t *attr)
1354{
1355 if (attr == NULL)
1356 return EINVAL;
1357
1358 *attr = 0xdeada11d;
1359 return 0;
1360}
1361
1362/* We use one bit in condition variable values as the 'shared' flag
1363 * The rest is a counter.
1364 */
1365#define COND_SHARING_MASK 0x0001
1366#define COND_COUNTER_INCREMENT 0x0002
1367#define COND_COUNTER_MASK (~COND_SHARING_MASK)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001368
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001369/* XXX *technically* there is a race condition that could allow
1370 * XXX a signal to be missed. If thread A is preempted in _wait()
1371 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001372 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001373 * XXX before thread A is scheduled again and calls futex_wait(),
1374 * XXX then the signal will be lost.
1375 */
1376
1377int pthread_cond_init(pthread_cond_t *cond,
1378 const pthread_condattr_t *attr)
1379{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001380 if (cond == NULL)
1381 return EINVAL;
1382
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001383 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001384
1385 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
1386 cond->value |= COND_SHARING_MASK;
1387
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001388 return 0;
1389}
1390
1391int pthread_cond_destroy(pthread_cond_t *cond)
1392{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001393 if (cond == NULL)
1394 return EINVAL;
1395
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001396 cond->value = 0xdeadc04d;
1397 return 0;
1398}
1399
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001400/* This function is used by pthread_cond_broadcast and
1401 * pthread_cond_signal to atomically decrement the counter.
1402 */
1403static void
1404__pthread_cond_pulse(pthread_cond_t *cond)
1405{
1406 long flags = (cond->value & ~COND_COUNTER_MASK);
1407
1408 for (;;) {
1409 long oldval = cond->value;
1410 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1411 | flags;
1412 if (__atomic_cmpxchg(oldval, newval, &cond->value) == 0)
1413 break;
1414 }
1415}
1416
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001417int pthread_cond_broadcast(pthread_cond_t *cond)
1418{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001419 if (__unlikely(cond == NULL))
1420 return EINVAL;
1421
1422 __pthread_cond_pulse(cond);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001423 __futex_wake(&cond->value, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001424 return 0;
1425}
1426
1427int pthread_cond_signal(pthread_cond_t *cond)
1428{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001429 if (__unlikely(cond == NULL))
1430 return EINVAL;
1431
1432 __pthread_cond_pulse(cond);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001433 __futex_wake(&cond->value, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001434 return 0;
1435}
1436
1437int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1438{
1439 return pthread_cond_timedwait(cond, mutex, NULL);
1440}
1441
1442int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1443 pthread_mutex_t * mutex,
1444 const struct timespec *reltime)
1445{
1446 int status;
1447 int oldvalue = cond->value;
1448
1449 pthread_mutex_unlock(mutex);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001450 status = __futex_wait(&cond->value, oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001451 pthread_mutex_lock(mutex);
1452
1453 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1454 return 0;
1455}
1456
1457int __pthread_cond_timedwait(pthread_cond_t *cond,
1458 pthread_mutex_t * mutex,
1459 const struct timespec *abstime,
1460 clockid_t clock)
1461{
1462 struct timespec ts;
1463 struct timespec * tsp;
1464
1465 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001466 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001467 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001468 tsp = &ts;
1469 } else {
1470 tsp = NULL;
1471 }
1472
1473 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1474}
1475
1476int pthread_cond_timedwait(pthread_cond_t *cond,
1477 pthread_mutex_t * mutex,
1478 const struct timespec *abstime)
1479{
1480 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1481}
1482
1483
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001484/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001485int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1486 pthread_mutex_t * mutex,
1487 const struct timespec *abstime)
1488{
1489 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1490}
1491
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001492int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1493 pthread_mutex_t * mutex,
1494 const struct timespec *abstime)
1495{
1496 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1497}
1498
1499int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1500 pthread_mutex_t * mutex,
1501 const struct timespec *reltime)
1502{
1503 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1504}
1505
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001506int pthread_cond_timeout_np(pthread_cond_t *cond,
1507 pthread_mutex_t * mutex,
1508 unsigned msecs)
1509{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001510 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001511
1512 ts.tv_sec = msecs / 1000;
1513 ts.tv_nsec = (msecs % 1000) * 1000000;
1514
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001515 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001516}
1517
1518
1519
1520/* A technical note regarding our thread-local-storage (TLS) implementation:
1521 *
1522 * There can be up to TLSMAP_SIZE independent TLS keys in a given process,
1523 * though the first TLSMAP_START keys are reserved for Bionic to hold
1524 * special thread-specific variables like errno or a pointer to
1525 * the current thread's descriptor.
1526 *
1527 * while stored in the TLS area, these entries cannot be accessed through
1528 * pthread_getspecific() / pthread_setspecific() and pthread_key_delete()
1529 *
1530 * also, some entries in the key table are pre-allocated (see tlsmap_lock)
1531 * to greatly simplify and speedup some OpenGL-related operations. though the
1532 * initialy value will be NULL on all threads.
1533 *
1534 * you can use pthread_getspecific()/setspecific() on these, and in theory
1535 * you could also call pthread_key_delete() as well, though this would
1536 * probably break some apps.
1537 *
1538 * The 'tlsmap_t' type defined below implements a shared global map of
1539 * currently created/allocated TLS keys and the destructors associated
1540 * with them. You should use tlsmap_lock/unlock to access it to avoid
1541 * any race condition.
1542 *
1543 * the global TLS map simply contains a bitmap of allocated keys, and
1544 * an array of destructors.
1545 *
1546 * each thread has a TLS area that is a simple array of TLSMAP_SIZE void*
1547 * pointers. the TLS area of the main thread is stack-allocated in
1548 * __libc_init_common, while the TLS area of other threads is placed at
1549 * the top of their stack in pthread_create.
1550 *
1551 * when pthread_key_create() is called, it finds the first free key in the
1552 * bitmap, then set it to 1, saving the destructor altogether
1553 *
1554 * when pthread_key_delete() is called. it will erase the key's bitmap bit
1555 * and its destructor, and will also clear the key data in the TLS area of
1556 * all created threads. As mandated by Posix, it is the responsability of
1557 * the caller of pthread_key_delete() to properly reclaim the objects that
1558 * were pointed to by these data fields (either before or after the call).
1559 *
1560 */
1561
1562/* TLS Map implementation
1563 */
1564
1565#define TLSMAP_START (TLS_SLOT_MAX_WELL_KNOWN+1)
1566#define TLSMAP_SIZE BIONIC_TLS_SLOTS
1567#define TLSMAP_BITS 32
1568#define TLSMAP_WORDS ((TLSMAP_SIZE+TLSMAP_BITS-1)/TLSMAP_BITS)
1569#define TLSMAP_WORD(m,k) (m)->map[(k)/TLSMAP_BITS]
1570#define TLSMAP_MASK(k) (1U << ((k)&(TLSMAP_BITS-1)))
1571
1572/* this macro is used to quickly check that a key belongs to a reasonable range */
1573#define TLSMAP_VALIDATE_KEY(key) \
1574 ((key) >= TLSMAP_START && (key) < TLSMAP_SIZE)
1575
1576/* the type of tls key destructor functions */
1577typedef void (*tls_dtor_t)(void*);
1578
1579typedef struct {
1580 int init; /* see comment in tlsmap_lock() */
1581 uint32_t map[TLSMAP_WORDS]; /* bitmap of allocated keys */
1582 tls_dtor_t dtors[TLSMAP_SIZE]; /* key destructors */
1583} tlsmap_t;
1584
1585static pthread_mutex_t _tlsmap_lock = PTHREAD_MUTEX_INITIALIZER;
1586static tlsmap_t _tlsmap;
1587
1588/* lock the global TLS map lock and return a handle to it */
1589static __inline__ tlsmap_t* tlsmap_lock(void)
1590{
1591 tlsmap_t* m = &_tlsmap;
1592
1593 pthread_mutex_lock(&_tlsmap_lock);
1594 /* we need to initialize the first entry of the 'map' array
1595 * with the value TLS_DEFAULT_ALLOC_MAP. doing it statically
1596 * when declaring _tlsmap is a bit awkward and is going to
1597 * produce warnings, so do it the first time we use the map
1598 * instead
1599 */
1600 if (__unlikely(!m->init)) {
1601 TLSMAP_WORD(m,0) = TLS_DEFAULT_ALLOC_MAP;
1602 m->init = 1;
1603 }
1604 return m;
1605}
1606
1607/* unlock the global TLS map */
1608static __inline__ void tlsmap_unlock(tlsmap_t* m)
1609{
1610 pthread_mutex_unlock(&_tlsmap_lock);
1611 (void)m; /* a good compiler is a happy compiler */
1612}
1613
1614/* test to see wether a key is allocated */
1615static __inline__ int tlsmap_test(tlsmap_t* m, int key)
1616{
1617 return (TLSMAP_WORD(m,key) & TLSMAP_MASK(key)) != 0;
1618}
1619
1620/* set the destructor and bit flag on a newly allocated key */
1621static __inline__ void tlsmap_set(tlsmap_t* m, int key, tls_dtor_t dtor)
1622{
1623 TLSMAP_WORD(m,key) |= TLSMAP_MASK(key);
1624 m->dtors[key] = dtor;
1625}
1626
1627/* clear the destructor and bit flag on an existing key */
1628static __inline__ void tlsmap_clear(tlsmap_t* m, int key)
1629{
1630 TLSMAP_WORD(m,key) &= ~TLSMAP_MASK(key);
1631 m->dtors[key] = NULL;
1632}
1633
1634/* allocate a new TLS key, return -1 if no room left */
1635static int tlsmap_alloc(tlsmap_t* m, tls_dtor_t dtor)
1636{
1637 int key;
1638
1639 for ( key = TLSMAP_START; key < TLSMAP_SIZE; key++ ) {
1640 if ( !tlsmap_test(m, key) ) {
1641 tlsmap_set(m, key, dtor);
1642 return key;
1643 }
1644 }
1645 return -1;
1646}
1647
1648
1649int pthread_key_create(pthread_key_t *key, void (*destructor_function)(void *))
1650{
1651 uint32_t err = ENOMEM;
1652 tlsmap_t* map = tlsmap_lock();
1653 int k = tlsmap_alloc(map, destructor_function);
1654
1655 if (k >= 0) {
1656 *key = k;
1657 err = 0;
1658 }
1659 tlsmap_unlock(map);
1660 return err;
1661}
1662
1663
1664/* This deletes a pthread_key_t. note that the standard mandates that this does
1665 * not call the destructor of non-NULL key values. Instead, it is the
1666 * responsability of the caller to properly dispose of the corresponding data
1667 * and resources, using any mean it finds suitable.
1668 *
1669 * On the other hand, this function will clear the corresponding key data
1670 * values in all known threads. this prevents later (invalid) calls to
1671 * pthread_getspecific() to receive invalid/stale values.
1672 */
1673int pthread_key_delete(pthread_key_t key)
1674{
1675 uint32_t err;
1676 pthread_internal_t* thr;
1677 tlsmap_t* map;
1678
1679 if (!TLSMAP_VALIDATE_KEY(key)) {
1680 return EINVAL;
1681 }
1682
1683 map = tlsmap_lock();
1684
1685 if (!tlsmap_test(map, key)) {
1686 err = EINVAL;
1687 goto err1;
1688 }
1689
1690 /* clear value in all threads */
1691 pthread_mutex_lock(&gThreadListLock);
1692 for ( thr = gThreadList; thr != NULL; thr = thr->next ) {
1693 /* avoid zombie threads with a negative 'join_count'. these are really
1694 * already dead and don't have a TLS area anymore.
1695 *
1696 * similarly, it is possible to have thr->tls == NULL for threads that
1697 * were just recently created through pthread_create() but whose
1698 * startup trampoline (__thread_entry) hasn't been run yet by the
1699 * scheduler. so check for this too.
1700 */
1701 if (thr->join_count < 0 || !thr->tls)
1702 continue;
1703
1704 thr->tls[key] = NULL;
1705 }
1706 tlsmap_clear(map, key);
1707
1708 pthread_mutex_unlock(&gThreadListLock);
1709 err = 0;
1710
1711err1:
1712 tlsmap_unlock(map);
1713 return err;
1714}
1715
1716
1717int pthread_setspecific(pthread_key_t key, const void *ptr)
1718{
1719 int err = EINVAL;
1720 tlsmap_t* map;
1721
1722 if (TLSMAP_VALIDATE_KEY(key)) {
1723 /* check that we're trying to set data for an allocated key */
1724 map = tlsmap_lock();
1725 if (tlsmap_test(map, key)) {
1726 ((uint32_t *)__get_tls())[key] = (uint32_t)ptr;
1727 err = 0;
1728 }
1729 tlsmap_unlock(map);
1730 }
1731 return err;
1732}
1733
1734void * pthread_getspecific(pthread_key_t key)
1735{
1736 if (!TLSMAP_VALIDATE_KEY(key)) {
1737 return NULL;
1738 }
1739
1740 /* for performance reason, we do not lock/unlock the global TLS map
1741 * to check that the key is properly allocated. if the key was not
1742 * allocated, the value read from the TLS should always be NULL
1743 * due to pthread_key_delete() clearing the values for all threads.
1744 */
1745 return (void *)(((unsigned *)__get_tls())[key]);
1746}
1747
1748/* Posix mandates that this be defined in <limits.h> but we don't have
1749 * it just yet.
1750 */
1751#ifndef PTHREAD_DESTRUCTOR_ITERATIONS
1752# define PTHREAD_DESTRUCTOR_ITERATIONS 4
1753#endif
1754
1755/* this function is called from pthread_exit() to remove all TLS key data
1756 * from this thread's TLS area. this must call the destructor of all keys
1757 * that have a non-NULL data value (and a non-NULL destructor).
1758 *
1759 * because destructors can do funky things like deleting/creating other
1760 * keys, we need to implement this in a loop
1761 */
1762static void pthread_key_clean_all(void)
1763{
1764 tlsmap_t* map;
1765 void** tls = (void**)__get_tls();
1766 int rounds = PTHREAD_DESTRUCTOR_ITERATIONS;
1767
1768 map = tlsmap_lock();
1769
1770 for (rounds = PTHREAD_DESTRUCTOR_ITERATIONS; rounds > 0; rounds--)
1771 {
1772 int kk, count = 0;
1773
1774 for (kk = TLSMAP_START; kk < TLSMAP_SIZE; kk++) {
1775 if ( tlsmap_test(map, kk) )
1776 {
1777 void* data = tls[kk];
1778 tls_dtor_t dtor = map->dtors[kk];
1779
1780 if (data != NULL && dtor != NULL)
1781 {
1782 /* we need to clear the key data now, this will prevent the
1783 * destructor (or a later one) from seeing the old value if
1784 * it calls pthread_getspecific() for some odd reason
1785 *
1786 * we do not do this if 'dtor == NULL' just in case another
1787 * destructor function might be responsible for manually
1788 * releasing the corresponding data.
1789 */
1790 tls[kk] = NULL;
1791
1792 /* because the destructor is free to call pthread_key_create
1793 * and/or pthread_key_delete, we need to temporarily unlock
1794 * the TLS map
1795 */
1796 tlsmap_unlock(map);
1797 (*dtor)(data);
1798 map = tlsmap_lock();
1799
1800 count += 1;
1801 }
1802 }
1803 }
1804
1805 /* if we didn't call any destructor, there is no need to check the
1806 * TLS data again
1807 */
1808 if (count == 0)
1809 break;
1810 }
1811 tlsmap_unlock(map);
1812}
1813
1814// man says this should be in <linux/unistd.h>, but it isn't
1815extern int tkill(int tid, int sig);
1816
1817int pthread_kill(pthread_t tid, int sig)
1818{
1819 int ret;
1820 int old_errno = errno;
1821 pthread_internal_t * thread = (pthread_internal_t *)tid;
1822
1823 ret = tkill(thread->kernel_id, sig);
1824 if (ret < 0) {
1825 ret = errno;
1826 errno = old_errno;
1827 }
1828
1829 return ret;
1830}
1831
1832extern int __rt_sigprocmask(int, const sigset_t *, sigset_t *, size_t);
1833
1834int pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
1835{
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001836 /* pthread_sigmask must return the error code, but the syscall
1837 * will set errno instead and return 0/-1
1838 */
1839 int ret, old_errno = errno;
1840
1841 ret = __rt_sigprocmask(how, set, oset, _NSIG / 8);
1842 if (ret < 0)
1843 ret = errno;
1844
1845 errno = old_errno;
1846 return ret;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001847}
1848
1849
1850int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
1851{
1852 const int CLOCK_IDTYPE_BITS = 3;
1853 pthread_internal_t* thread = (pthread_internal_t*)tid;
1854
1855 if (!thread)
1856 return ESRCH;
1857
1858 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
1859 return 0;
1860}
1861
1862
1863/* NOTE: this implementation doesn't support a init function that throws a C++ exception
1864 * or calls fork()
1865 */
1866int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
1867{
1868 static pthread_mutex_t once_lock = PTHREAD_MUTEX_INITIALIZER;
1869
1870 if (*once_control == PTHREAD_ONCE_INIT) {
1871 _normal_lock( &once_lock );
1872 if (*once_control == PTHREAD_ONCE_INIT) {
1873 (*init_routine)();
1874 *once_control = ~PTHREAD_ONCE_INIT;
1875 }
1876 _normal_unlock( &once_lock );
1877 }
1878 return 0;
1879}