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