blob: 180914e2fbfbdbaafcc019398339c03ccdcbbd15 [file] [log] [blame]
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28#include <sys/types.h>
29#include <unistd.h>
30#include <signal.h>
31#include <stdint.h>
32#include <stdio.h>
33#include <stdlib.h>
34#include <errno.h>
35#include <sys/atomics.h>
36#include <bionic_tls.h>
37#include <sys/mman.h>
38#include <pthread.h>
39#include <time.h>
40#include "pthread_internal.h"
41#include "thread_private.h"
42#include <limits.h>
43#include <memory.h>
44#include <assert.h>
45#include <malloc.h>
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -070046#include <bionic_futex.h>
David 'Digit' Turner6c8a2f22010-06-10 23:34:24 -070047#include <bionic_atomic_inline.h>
André Goddard Rosa78c1c042010-05-19 23:17:16 -030048#include <sys/prctl.h>
49#include <sys/stat.h>
50#include <fcntl.h>
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -070051#include <stdio.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080052
53extern int __pthread_clone(int (*fn)(void*), void *child_stack, int flags, void *arg);
54extern void _exit_with_stack_teardown(void * stackBase, int stackSize, int retCode);
55extern void _exit_thread(int retCode);
56extern int __set_errno(int);
57
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -070058int __futex_wake_ex(volatile void *ftx, int pshared, int val)
59{
60 return __futex_syscall3(ftx, pshared ? FUTEX_WAKE : FUTEX_WAKE_PRIVATE, val);
61}
62
63int __futex_wait_ex(volatile void *ftx, int pshared, int val, const struct timespec *timeout)
64{
65 return __futex_syscall4(ftx, pshared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE, val, timeout);
66}
67
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -070068#define __likely(cond) __builtin_expect(!!(cond), 1)
69#define __unlikely(cond) __builtin_expect(!!(cond), 0)
70
James Rose3435fc62011-05-31 10:20:42 -070071#ifdef __i386__
72#define ATTRIBUTES __attribute__((noinline)) __attribute__((fastcall))
73#else
74#define ATTRIBUTES __attribute__((noinline))
75#endif
76
77void ATTRIBUTES _thread_created_hook(pid_t thread_id);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080078
79#define PTHREAD_ATTR_FLAG_DETACHED 0x00000001
80#define PTHREAD_ATTR_FLAG_USER_STACK 0x00000002
81
82#define DEFAULT_STACKSIZE (1024 * 1024)
83#define STACKBASE 0x10000000
84
85static uint8_t * gStackBase = (uint8_t *)STACKBASE;
86
87static pthread_mutex_t mmap_lock = PTHREAD_MUTEX_INITIALIZER;
88
89
90static const pthread_attr_t gDefaultPthreadAttr = {
91 .flags = 0,
92 .stack_base = NULL,
93 .stack_size = DEFAULT_STACKSIZE,
94 .guard_size = PAGE_SIZE,
95 .sched_policy = SCHED_NORMAL,
96 .sched_priority = 0
97};
98
99#define INIT_THREADS 1
100
101static pthread_internal_t* gThreadList = NULL;
102static pthread_mutex_t gThreadListLock = PTHREAD_MUTEX_INITIALIZER;
103static pthread_mutex_t gDebuggerNotificationLock = PTHREAD_MUTEX_INITIALIZER;
104
105
106/* we simply malloc/free the internal pthread_internal_t structures. we may
107 * want to use a different allocation scheme in the future, but this one should
108 * be largely enough
109 */
110static pthread_internal_t*
111_pthread_internal_alloc(void)
112{
113 pthread_internal_t* thread;
114
115 thread = calloc( sizeof(*thread), 1 );
116 if (thread)
117 thread->intern = 1;
118
119 return thread;
120}
121
122static void
123_pthread_internal_free( pthread_internal_t* thread )
124{
125 if (thread && thread->intern) {
126 thread->intern = 0; /* just in case */
127 free (thread);
128 }
129}
130
131
132static void
133_pthread_internal_remove_locked( pthread_internal_t* thread )
134{
135 thread->next->pref = thread->pref;
136 thread->pref[0] = thread->next;
137}
138
139static void
140_pthread_internal_remove( pthread_internal_t* thread )
141{
142 pthread_mutex_lock(&gThreadListLock);
143 _pthread_internal_remove_locked(thread);
144 pthread_mutex_unlock(&gThreadListLock);
145}
146
147static void
148_pthread_internal_add( pthread_internal_t* thread )
149{
150 pthread_mutex_lock(&gThreadListLock);
151 thread->pref = &gThreadList;
152 thread->next = thread->pref[0];
153 if (thread->next)
154 thread->next->pref = &thread->next;
155 thread->pref[0] = thread;
156 pthread_mutex_unlock(&gThreadListLock);
157}
158
159pthread_internal_t*
160__get_thread(void)
161{
162 void** tls = (void**)__get_tls();
163
164 return (pthread_internal_t*) tls[TLS_SLOT_THREAD_ID];
165}
166
167
168void*
169__get_stack_base(int *p_stack_size)
170{
171 pthread_internal_t* thread = __get_thread();
172
173 *p_stack_size = thread->attr.stack_size;
174 return thread->attr.stack_base;
175}
176
177
178void __init_tls(void** tls, void* thread)
179{
180 int nn;
181
182 ((pthread_internal_t*)thread)->tls = tls;
183
184 // slot 0 must point to the tls area, this is required by the implementation
185 // of the x86 Linux kernel thread-local-storage
186 tls[TLS_SLOT_SELF] = (void*)tls;
187 tls[TLS_SLOT_THREAD_ID] = thread;
188 for (nn = TLS_SLOT_ERRNO; nn < BIONIC_TLS_SLOTS; nn++)
189 tls[nn] = 0;
190
191 __set_tls( (void*)tls );
192}
193
194
195/*
196 * This trampoline is called from the assembly clone() function
197 */
198void __thread_entry(int (*func)(void*), void *arg, void **tls)
199{
200 int retValue;
201 pthread_internal_t * thrInfo;
202
203 // Wait for our creating thread to release us. This lets it have time to
204 // notify gdb about this thread before it starts doing anything.
205 pthread_mutex_t * start_mutex = (pthread_mutex_t *)&tls[TLS_SLOT_SELF];
206 pthread_mutex_lock(start_mutex);
207 pthread_mutex_destroy(start_mutex);
208
209 thrInfo = (pthread_internal_t *) tls[TLS_SLOT_THREAD_ID];
210
211 __init_tls( tls, thrInfo );
212
213 pthread_exit( (void*)func(arg) );
214}
215
216void _init_thread(pthread_internal_t * thread, pid_t kernel_id, pthread_attr_t * attr, void * stack_base)
217{
218 if (attr == NULL) {
219 thread->attr = gDefaultPthreadAttr;
220 } else {
221 thread->attr = *attr;
222 }
223 thread->attr.stack_base = stack_base;
224 thread->kernel_id = kernel_id;
225
226 // set the scheduling policy/priority of the thread
227 if (thread->attr.sched_policy != SCHED_NORMAL) {
228 struct sched_param param;
229 param.sched_priority = thread->attr.sched_priority;
230 sched_setscheduler(kernel_id, thread->attr.sched_policy, &param);
231 }
232
233 pthread_cond_init(&thread->join_cond, NULL);
234 thread->join_count = 0;
235
236 thread->cleanup_stack = NULL;
237
238 _pthread_internal_add(thread);
239}
240
241
242/* XXX stacks not reclaimed if thread spawn fails */
243/* XXX stacks address spaces should be reused if available again */
244
245static void *mkstack(size_t size, size_t guard_size)
246{
247 void * stack;
248
249 pthread_mutex_lock(&mmap_lock);
250
251 stack = mmap((void *)gStackBase, size,
252 PROT_READ | PROT_WRITE,
253 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
254 -1, 0);
255
256 if(stack == MAP_FAILED) {
257 stack = NULL;
258 goto done;
259 }
260
261 if(mprotect(stack, guard_size, PROT_NONE)){
262 munmap(stack, size);
263 stack = NULL;
264 goto done;
265 }
266
267done:
268 pthread_mutex_unlock(&mmap_lock);
269 return stack;
270}
271
272/*
273 * Create a new thread. The thread's stack is layed out like so:
274 *
275 * +---------------------------+
276 * | pthread_internal_t |
277 * +---------------------------+
278 * | |
279 * | TLS area |
280 * | |
281 * +---------------------------+
282 * | |
283 * . .
284 * . stack area .
285 * . .
286 * | |
287 * +---------------------------+
288 * | guard page |
289 * +---------------------------+
290 *
291 * note that TLS[0] must be a pointer to itself, this is required
292 * by the thread-local storage implementation of the x86 Linux
293 * kernel, where the TLS pointer is read by reading fs:[0]
294 */
295int pthread_create(pthread_t *thread_out, pthread_attr_t const * attr,
296 void *(*start_routine)(void *), void * arg)
297{
298 char* stack;
299 void** tls;
300 int tid;
301 pthread_mutex_t * start_mutex;
302 pthread_internal_t * thread;
303 int madestack = 0;
304 int old_errno = errno;
305
306 /* this will inform the rest of the C library that at least one thread
307 * was created. this will enforce certain functions to acquire/release
308 * locks (e.g. atexit()) to protect shared global structures.
309 *
310 * this works because pthread_create() is not called by the C library
311 * initialization routine that sets up the main thread's data structures.
312 */
313 __isthreaded = 1;
314
315 thread = _pthread_internal_alloc();
316 if (thread == NULL)
317 return ENOMEM;
318
319 if (attr == NULL) {
320 attr = &gDefaultPthreadAttr;
321 }
322
323 // make sure the stack is PAGE_SIZE aligned
324 size_t stackSize = (attr->stack_size +
325 (PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
326
327 if (!attr->stack_base) {
328 stack = mkstack(stackSize, attr->guard_size);
329 if(stack == NULL) {
330 _pthread_internal_free(thread);
331 return ENOMEM;
332 }
333 madestack = 1;
334 } else {
335 stack = attr->stack_base;
336 }
337
338 // Make room for TLS
339 tls = (void**)(stack + stackSize - BIONIC_TLS_SLOTS*sizeof(void*));
340
341 // Create a mutex for the thread in TLS_SLOT_SELF to wait on once it starts so we can keep
342 // it from doing anything until after we notify the debugger about it
343 start_mutex = (pthread_mutex_t *) &tls[TLS_SLOT_SELF];
344 pthread_mutex_init(start_mutex, NULL);
345 pthread_mutex_lock(start_mutex);
346
347 tls[TLS_SLOT_THREAD_ID] = thread;
348
349 tid = __pthread_clone((int(*)(void*))start_routine, tls,
350 CLONE_FILES | CLONE_FS | CLONE_VM | CLONE_SIGHAND
351 | CLONE_THREAD | CLONE_SYSVSEM | CLONE_DETACHED,
352 arg);
353
354 if(tid < 0) {
355 int result;
356 if (madestack)
357 munmap(stack, stackSize);
358 _pthread_internal_free(thread);
359 result = errno;
360 errno = old_errno;
361 return result;
362 }
363
364 _init_thread(thread, tid, (pthread_attr_t*)attr, stack);
365
366 if (!madestack)
367 thread->attr.flags |= PTHREAD_ATTR_FLAG_USER_STACK;
368
369 // Notify any debuggers about the new thread
370 pthread_mutex_lock(&gDebuggerNotificationLock);
371 _thread_created_hook(tid);
372 pthread_mutex_unlock(&gDebuggerNotificationLock);
373
374 // Let the thread do it's thing
375 pthread_mutex_unlock(start_mutex);
376
377 *thread_out = (pthread_t)thread;
378 return 0;
379}
380
381
382int pthread_attr_init(pthread_attr_t * attr)
383{
384 *attr = gDefaultPthreadAttr;
385 return 0;
386}
387
388int pthread_attr_destroy(pthread_attr_t * attr)
389{
390 memset(attr, 0x42, sizeof(pthread_attr_t));
391 return 0;
392}
393
394int pthread_attr_setdetachstate(pthread_attr_t * attr, int state)
395{
396 if (state == PTHREAD_CREATE_DETACHED) {
397 attr->flags |= PTHREAD_ATTR_FLAG_DETACHED;
398 } else if (state == PTHREAD_CREATE_JOINABLE) {
399 attr->flags &= ~PTHREAD_ATTR_FLAG_DETACHED;
400 } else {
401 return EINVAL;
402 }
403 return 0;
404}
405
406int pthread_attr_getdetachstate(pthread_attr_t const * attr, int * state)
407{
408 *state = (attr->flags & PTHREAD_ATTR_FLAG_DETACHED)
409 ? PTHREAD_CREATE_DETACHED
410 : PTHREAD_CREATE_JOINABLE;
411 return 0;
412}
413
414int pthread_attr_setschedpolicy(pthread_attr_t * attr, int policy)
415{
416 attr->sched_policy = policy;
417 return 0;
418}
419
420int pthread_attr_getschedpolicy(pthread_attr_t const * attr, int * policy)
421{
422 *policy = attr->sched_policy;
423 return 0;
424}
425
426int pthread_attr_setschedparam(pthread_attr_t * attr, struct sched_param const * param)
427{
428 attr->sched_priority = param->sched_priority;
429 return 0;
430}
431
432int pthread_attr_getschedparam(pthread_attr_t const * attr, struct sched_param * param)
433{
434 param->sched_priority = attr->sched_priority;
435 return 0;
436}
437
438int pthread_attr_setstacksize(pthread_attr_t * attr, size_t stack_size)
439{
440 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
441 return EINVAL;
442 }
443 attr->stack_size = stack_size;
444 return 0;
445}
446
447int pthread_attr_getstacksize(pthread_attr_t const * attr, size_t * stack_size)
448{
449 *stack_size = attr->stack_size;
450 return 0;
451}
452
453int pthread_attr_setstackaddr(pthread_attr_t * attr, void * stack_addr)
454{
455#if 1
456 // It's not clear if this is setting the top or bottom of the stack, so don't handle it for now.
457 return ENOSYS;
458#else
459 if ((uint32_t)stack_addr & (PAGE_SIZE - 1)) {
460 return EINVAL;
461 }
462 attr->stack_base = stack_addr;
463 return 0;
464#endif
465}
466
467int pthread_attr_getstackaddr(pthread_attr_t const * attr, void ** stack_addr)
468{
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700469 *stack_addr = (char*)attr->stack_base + attr->stack_size;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800470 return 0;
471}
472
473int pthread_attr_setstack(pthread_attr_t * attr, void * stack_base, size_t stack_size)
474{
475 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
476 return EINVAL;
477 }
478 if ((uint32_t)stack_base & (PAGE_SIZE - 1)) {
479 return EINVAL;
480 }
481 attr->stack_base = stack_base;
482 attr->stack_size = stack_size;
483 return 0;
484}
485
486int pthread_attr_getstack(pthread_attr_t const * attr, void ** stack_base, size_t * stack_size)
487{
488 *stack_base = attr->stack_base;
489 *stack_size = attr->stack_size;
490 return 0;
491}
492
493int pthread_attr_setguardsize(pthread_attr_t * attr, size_t guard_size)
494{
495 if (guard_size & (PAGE_SIZE - 1) || guard_size < PAGE_SIZE) {
496 return EINVAL;
497 }
498
499 attr->guard_size = guard_size;
500 return 0;
501}
502
503int pthread_attr_getguardsize(pthread_attr_t const * attr, size_t * guard_size)
504{
505 *guard_size = attr->guard_size;
506 return 0;
507}
508
509int pthread_getattr_np(pthread_t thid, pthread_attr_t * attr)
510{
511 pthread_internal_t * thread = (pthread_internal_t *)thid;
512 *attr = thread->attr;
513 return 0;
514}
515
516int pthread_attr_setscope(pthread_attr_t *attr, int scope)
517{
518 if (scope == PTHREAD_SCOPE_SYSTEM)
519 return 0;
520 if (scope == PTHREAD_SCOPE_PROCESS)
521 return ENOTSUP;
522
523 return EINVAL;
524}
525
526int pthread_attr_getscope(pthread_attr_t const *attr)
527{
528 return PTHREAD_SCOPE_SYSTEM;
529}
530
531
532/* CAVEAT: our implementation of pthread_cleanup_push/pop doesn't support C++ exceptions
533 * and thread cancelation
534 */
535
536void __pthread_cleanup_push( __pthread_cleanup_t* c,
537 __pthread_cleanup_func_t routine,
538 void* arg )
539{
540 pthread_internal_t* thread = __get_thread();
541
542 c->__cleanup_routine = routine;
543 c->__cleanup_arg = arg;
544 c->__cleanup_prev = thread->cleanup_stack;
545 thread->cleanup_stack = c;
546}
547
548void __pthread_cleanup_pop( __pthread_cleanup_t* c, int execute )
549{
550 pthread_internal_t* thread = __get_thread();
551
552 thread->cleanup_stack = c->__cleanup_prev;
553 if (execute)
554 c->__cleanup_routine(c->__cleanup_arg);
555}
556
557/* used by pthread_exit() to clean all TLS keys of the current thread */
558static void pthread_key_clean_all(void);
559
560void pthread_exit(void * retval)
561{
562 pthread_internal_t* thread = __get_thread();
563 void* stack_base = thread->attr.stack_base;
564 int stack_size = thread->attr.stack_size;
565 int user_stack = (thread->attr.flags & PTHREAD_ATTR_FLAG_USER_STACK) != 0;
566
567 // call the cleanup handlers first
568 while (thread->cleanup_stack) {
569 __pthread_cleanup_t* c = thread->cleanup_stack;
570 thread->cleanup_stack = c->__cleanup_prev;
571 c->__cleanup_routine(c->__cleanup_arg);
572 }
573
574 // call the TLS destructors, it is important to do that before removing this
575 // thread from the global list. this will ensure that if someone else deletes
576 // a TLS key, the corresponding value will be set to NULL in this thread's TLS
577 // space (see pthread_key_delete)
578 pthread_key_clean_all();
579
580 // if the thread is detached, destroy the pthread_internal_t
581 // otherwise, keep it in memory and signal any joiners
582 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
583 _pthread_internal_remove(thread);
584 _pthread_internal_free(thread);
585 } else {
586 /* the join_count field is used to store the number of threads waiting for
587 * the termination of this thread with pthread_join(),
588 *
589 * if it is positive we need to signal the waiters, and we do not touch
590 * the count (it will be decremented by the waiters, the last one will
591 * also remove/free the thread structure
592 *
593 * if it is zero, we set the count value to -1 to indicate that the
594 * thread is in 'zombie' state: it has stopped executing, and its stack
595 * is gone (as well as its TLS area). when another thread calls pthread_join()
596 * on it, it will immediately free the thread and return.
597 */
598 pthread_mutex_lock(&gThreadListLock);
599 thread->return_value = retval;
600 if (thread->join_count > 0) {
601 pthread_cond_broadcast(&thread->join_cond);
602 } else {
603 thread->join_count = -1; /* zombie thread */
604 }
605 pthread_mutex_unlock(&gThreadListLock);
606 }
607
608 // destroy the thread stack
609 if (user_stack)
610 _exit_thread((int)retval);
611 else
612 _exit_with_stack_teardown(stack_base, stack_size, (int)retval);
613}
614
615int pthread_join(pthread_t thid, void ** ret_val)
616{
617 pthread_internal_t* thread = (pthread_internal_t*)thid;
618 int count;
619
620 // check that the thread still exists and is not detached
621 pthread_mutex_lock(&gThreadListLock);
622
623 for (thread = gThreadList; thread != NULL; thread = thread->next)
624 if (thread == (pthread_internal_t*)thid)
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200625 goto FoundIt;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800626
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200627 pthread_mutex_unlock(&gThreadListLock);
628 return ESRCH;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800629
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200630FoundIt:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800631 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
632 pthread_mutex_unlock(&gThreadListLock);
633 return EINVAL;
634 }
635
636 /* wait for thread death when needed
637 *
638 * if the 'join_count' is negative, this is a 'zombie' thread that
639 * is already dead and without stack/TLS
640 *
641 * otherwise, we need to increment 'join-count' and wait to be signaled
642 */
643 count = thread->join_count;
644 if (count >= 0) {
645 thread->join_count += 1;
646 pthread_cond_wait( &thread->join_cond, &gThreadListLock );
647 count = --thread->join_count;
648 }
649 if (ret_val)
650 *ret_val = thread->return_value;
651
652 /* remove thread descriptor when we're the last joiner or when the
653 * thread was already a zombie.
654 */
655 if (count <= 0) {
656 _pthread_internal_remove_locked(thread);
657 _pthread_internal_free(thread);
658 }
659 pthread_mutex_unlock(&gThreadListLock);
660 return 0;
661}
662
663int pthread_detach( pthread_t thid )
664{
665 pthread_internal_t* thread;
666 int result = 0;
667 int flags;
668
669 pthread_mutex_lock(&gThreadListLock);
670 for (thread = gThreadList; thread != NULL; thread = thread->next)
671 if (thread == (pthread_internal_t*)thid)
672 goto FoundIt;
673
674 result = ESRCH;
675 goto Exit;
676
677FoundIt:
678 do {
679 flags = thread->attr.flags;
680
681 if ( flags & PTHREAD_ATTR_FLAG_DETACHED ) {
682 /* thread is not joinable ! */
683 result = EINVAL;
684 goto Exit;
685 }
686 }
687 while ( __atomic_cmpxchg( flags, flags | PTHREAD_ATTR_FLAG_DETACHED,
688 (volatile int*)&thread->attr.flags ) != 0 );
689Exit:
690 pthread_mutex_unlock(&gThreadListLock);
691 return result;
692}
693
694pthread_t pthread_self(void)
695{
696 return (pthread_t)__get_thread();
697}
698
699int pthread_equal(pthread_t one, pthread_t two)
700{
701 return (one == two ? 1 : 0);
702}
703
704int pthread_getschedparam(pthread_t thid, int * policy,
705 struct sched_param * param)
706{
707 int old_errno = errno;
708
709 pthread_internal_t * thread = (pthread_internal_t *)thid;
710 int err = sched_getparam(thread->kernel_id, param);
711 if (!err) {
712 *policy = sched_getscheduler(thread->kernel_id);
713 } else {
714 err = errno;
715 errno = old_errno;
716 }
717 return err;
718}
719
720int pthread_setschedparam(pthread_t thid, int policy,
721 struct sched_param const * param)
722{
723 pthread_internal_t * thread = (pthread_internal_t *)thid;
724 int old_errno = errno;
725 int ret;
726
727 ret = sched_setscheduler(thread->kernel_id, policy, param);
728 if (ret < 0) {
729 ret = errno;
730 errno = old_errno;
731 }
732 return ret;
733}
734
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' Turnera02b93b2010-06-28 14:20:22 -0700889 int ret;
890
891 /* use trylock to ensure that the mutex value is
892 * valid and is not already locked. */
893 ret = pthread_mutex_trylock(mutex);
894 if (ret != 0)
895 return ret;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700896
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800897 mutex->value = 0xdead10cc;
898 return 0;
899}
900
901
902/*
903 * Lock a non-recursive mutex.
904 *
905 * As noted above, there are three states:
906 * 0 (unlocked, no contention)
907 * 1 (locked, no contention)
908 * 2 (locked, contention)
909 *
910 * Non-recursive mutexes don't use the thread-id or counter fields, and the
911 * "type" value is zero, so the only bits that will be set are the ones in
912 * the lock state field.
913 */
914static __inline__ void
915_normal_lock(pthread_mutex_t* mutex)
916{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700917 /* We need to preserve the shared flag during operations */
918 int shared = mutex->value & MUTEX_SHARED_MASK;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800919 /*
920 * The common case is an unlocked mutex, so we begin by trying to
921 * change the lock's state from 0 to 1. __atomic_cmpxchg() returns 0
922 * if it made the swap successfully. If the result is nonzero, this
923 * lock is already held by another thread.
924 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700925 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value ) != 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800926 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800927 * We want to go to sleep until the mutex is available, which
928 * requires promoting it to state 2. We need to swap in the new
929 * state value and then wait until somebody wakes us up.
930 *
931 * __atomic_swap() returns the previous value. We swap 2 in and
932 * see if we got zero back; if so, we have acquired the lock. If
933 * not, another thread still holds the lock and we wait again.
934 *
935 * The second argument to the __futex_wait() call is compared
936 * against the current value. If it doesn't match, __futex_wait()
937 * returns immediately (otherwise, it sleeps for a time specified
938 * by the third argument; 0 means sleep forever). This ensures
939 * that the mutex is in state 2 when we go to sleep on it, which
940 * guarantees a wake-up call.
941 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700942 while (__atomic_swap(shared|2, &mutex->value ) != (shared|0))
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -0700943 __futex_wait_ex(&mutex->value, shared, shared|2, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800944 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700945 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800946}
947
948/*
949 * Release a non-recursive mutex. The caller is responsible for determining
950 * that we are in fact the owner of this lock.
951 */
952static __inline__ void
953_normal_unlock(pthread_mutex_t* mutex)
954{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700955 ANDROID_MEMBAR_FULL();
956
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700957 /* We need to preserve the shared flag during operations */
958 int shared = mutex->value & MUTEX_SHARED_MASK;
959
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800960 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700961 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800962 * to release the lock. __atomic_dec() returns the previous value;
963 * if it wasn't 1 we have to do some additional work.
964 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700965 if (__atomic_dec(&mutex->value) != (shared|1)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800966 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800967 * Start by releasing the lock. The decrement changed it from
968 * "contended lock" to "uncontended lock", which means we still
969 * hold it, and anybody who tries to sneak in will push it back
970 * to state 2.
971 *
972 * Once we set it to zero the lock is up for grabs. We follow
973 * this with a __futex_wake() to ensure that one of the waiting
974 * threads has a chance to grab it.
975 *
976 * This doesn't cause a race with the swap/wait pair in
977 * _normal_lock(), because the __futex_wait() call there will
978 * return immediately if the mutex value isn't 2.
979 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700980 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800981
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800982 /*
983 * Wake up one waiting thread. We don't know which thread will be
984 * woken or when it'll start executing -- futexes make no guarantees
985 * here. There may not even be a thread waiting.
986 *
987 * The newly-woken thread will replace the 0 we just set above
988 * with 2, which means that when it eventually releases the mutex
989 * it will also call FUTEX_WAKE. This results in one extra wake
990 * call whenever a lock is contended, but lets us avoid forgetting
991 * anyone without requiring us to track the number of sleepers.
992 *
993 * It's possible for another thread to sneak in and grab the lock
994 * between the zero assignment above and the wake call below. If
995 * the new thread is "slow" and holds the lock for a while, we'll
996 * wake up a sleeper, which will swap in a 2 and then go back to
997 * sleep since the lock is still held. If the new thread is "fast",
998 * running to completion before we call wake, the thread we
999 * eventually wake will find an unlocked mutex and will execute.
1000 * Either way we have correct behavior and nobody is orphaned on
1001 * the wait queue.
1002 */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001003 __futex_wake_ex(&mutex->value, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001004 }
1005}
1006
1007static pthread_mutex_t __recursive_lock = PTHREAD_MUTEX_INITIALIZER;
1008
1009static void
1010_recursive_lock(void)
1011{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001012 _normal_lock(&__recursive_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001013}
1014
1015static void
1016_recursive_unlock(void)
1017{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001018 _normal_unlock(&__recursive_lock );
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001019}
1020
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001021int pthread_mutex_lock(pthread_mutex_t *mutex)
1022{
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001023 int mtype, tid, new_lock_type, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001024
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001025 if (__unlikely(mutex == NULL))
1026 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001027
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001028 mtype = (mutex->value & MUTEX_TYPE_MASK);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001029 shared = (mutex->value & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001030
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001031 /* Handle normal case first */
1032 if ( __likely(mtype == MUTEX_TYPE_NORMAL) ) {
1033 _normal_lock(mutex);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001034 return 0;
1035 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001036
1037 /* Do we already own this recursive or error-check mutex ? */
1038 tid = __get_thread()->kernel_id;
1039 if ( tid == MUTEX_OWNER(mutex) )
1040 {
1041 int oldv, counter;
1042
1043 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1044 /* trying to re-lock a mutex we already acquired */
1045 return EDEADLK;
1046 }
1047 /*
1048 * We own the mutex, but other threads are able to change
1049 * the contents (e.g. promoting it to "contended"), so we
1050 * need to hold the global lock.
1051 */
1052 _recursive_lock();
1053 oldv = mutex->value;
1054 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1055 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1056 _recursive_unlock();
1057 return 0;
1058 }
1059
1060 /* We don't own the mutex, so try to get it.
1061 *
1062 * First, we try to change its state from 0 to 1, if this
1063 * doesn't work, try to change it to state 2.
1064 */
1065 new_lock_type = 1;
1066
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001067 /* compute futex wait opcode and restore shared flag in mtype */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001068 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001069
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001070 for (;;) {
1071 int oldv;
1072
1073 _recursive_lock();
1074 oldv = mutex->value;
1075 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1076 mutex->value = ((tid << 16) | mtype | new_lock_type);
1077 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1078 oldv ^= 3;
1079 mutex->value = oldv;
1080 }
1081 _recursive_unlock();
1082
1083 if (oldv == mtype)
1084 break;
1085
1086 /*
1087 * The lock was held, possibly contended by others. From
1088 * now on, if we manage to acquire the lock, we have to
1089 * assume that others are still contending for it so that
1090 * we'll wake them when we unlock it.
1091 */
1092 new_lock_type = 2;
1093
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001094 __futex_wait_ex(&mutex->value, shared, oldv, NULL);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001095 }
1096 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001097}
1098
1099
1100int pthread_mutex_unlock(pthread_mutex_t *mutex)
1101{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001102 int mtype, tid, oldv, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001103
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001104 if (__unlikely(mutex == NULL))
1105 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001106
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001107 mtype = (mutex->value & MUTEX_TYPE_MASK);
1108 shared = (mutex->value & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001109
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001110 /* Handle common case first */
1111 if (__likely(mtype == MUTEX_TYPE_NORMAL)) {
1112 _normal_unlock(mutex);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001113 return 0;
1114 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001115
1116 /* Do we already own this recursive or error-check mutex ? */
1117 tid = __get_thread()->kernel_id;
1118 if ( tid != MUTEX_OWNER(mutex) )
1119 return EPERM;
1120
1121 /* We do, decrement counter or release the mutex if it is 0 */
1122 _recursive_lock();
1123 oldv = mutex->value;
1124 if (oldv & MUTEX_COUNTER_MASK) {
1125 mutex->value = oldv - (1 << MUTEX_COUNTER_SHIFT);
1126 oldv = 0;
1127 } else {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001128 mutex->value = shared | mtype;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001129 }
1130 _recursive_unlock();
1131
1132 /* Wake one waiting thread, if any */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001133 if ((oldv & 3) == 2) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001134 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001135 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001136 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001137}
1138
1139
1140int pthread_mutex_trylock(pthread_mutex_t *mutex)
1141{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001142 int mtype, tid, oldv, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001143
1144 if (__unlikely(mutex == NULL))
1145 return EINVAL;
1146
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001147 mtype = (mutex->value & MUTEX_TYPE_MASK);
1148 shared = (mutex->value & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001149
1150 /* Handle common case first */
1151 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001152 {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001153 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
1154 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001155 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001156 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001157
1158 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001159 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001160
1161 /* Do we already own this recursive or error-check mutex ? */
1162 tid = __get_thread()->kernel_id;
1163 if ( tid == MUTEX_OWNER(mutex) )
1164 {
1165 int counter;
1166
1167 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1168 /* already locked by ourselves */
1169 return EDEADLK;
1170 }
1171
1172 _recursive_lock();
1173 oldv = mutex->value;
1174 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1175 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1176 _recursive_unlock();
1177 return 0;
1178 }
1179
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001180 /* Restore sharing bit in mtype */
1181 mtype |= shared;
1182
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001183 /* Try to lock it, just once. */
1184 _recursive_lock();
1185 oldv = mutex->value;
1186 if (oldv == mtype) /* uncontended released lock => state 1 */
1187 mutex->value = ((tid << 16) | mtype | 1);
1188 _recursive_unlock();
1189
1190 if (oldv != mtype)
1191 return EBUSY;
1192
1193 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001194}
1195
1196
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001197/* initialize 'ts' with the difference between 'abstime' and the current time
1198 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
1199 */
1200static int
1201__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
1202{
1203 clock_gettime(clock, ts);
1204 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
1205 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
1206 if (ts->tv_nsec < 0) {
1207 ts->tv_sec--;
1208 ts->tv_nsec += 1000000000;
1209 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001210 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001211 return -1;
1212
1213 return 0;
1214}
1215
1216/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1217 * milliseconds.
1218 */
1219static void
1220__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1221{
1222 clock_gettime(clock, abstime);
1223 abstime->tv_sec += msecs/1000;
1224 abstime->tv_nsec += (msecs%1000)*1000000;
1225 if (abstime->tv_nsec >= 1000000000) {
1226 abstime->tv_sec++;
1227 abstime->tv_nsec -= 1000000000;
1228 }
1229}
1230
1231int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1232{
1233 clockid_t clock = CLOCK_MONOTONIC;
1234 struct timespec abstime;
1235 struct timespec ts;
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001236 int mtype, tid, oldv, new_lock_type, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001237
1238 /* compute absolute expiration time */
1239 __timespec_to_relative_msec(&abstime, msecs, clock);
1240
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001241 if (__unlikely(mutex == NULL))
1242 return EINVAL;
1243
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001244 mtype = (mutex->value & MUTEX_TYPE_MASK);
1245 shared = (mutex->value & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001246
1247 /* Handle common case first */
1248 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001249 {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001250 /* fast path for uncontended lock */
1251 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
1252 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001253 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001254 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001255
1256 /* loop while needed */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001257 while (__atomic_swap(shared|2, &mutex->value) != (shared|0)) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001258 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1259 return EBUSY;
1260
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001261 __futex_wait_ex(&mutex->value, shared, shared|2, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001262 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001263 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001264 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001265 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001266
1267 /* Do we already own this recursive or error-check mutex ? */
1268 tid = __get_thread()->kernel_id;
1269 if ( tid == MUTEX_OWNER(mutex) )
1270 {
1271 int oldv, counter;
1272
1273 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1274 /* already locked by ourselves */
1275 return EDEADLK;
1276 }
1277
1278 _recursive_lock();
1279 oldv = mutex->value;
1280 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1281 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1282 _recursive_unlock();
1283 return 0;
1284 }
1285
1286 /* We don't own the mutex, so try to get it.
1287 *
1288 * First, we try to change its state from 0 to 1, if this
1289 * doesn't work, try to change it to state 2.
1290 */
1291 new_lock_type = 1;
1292
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001293 /* Compute wait op and restore sharing bit in mtype */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001294 mtype |= shared;
1295
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001296 for (;;) {
1297 int oldv;
1298 struct timespec ts;
1299
1300 _recursive_lock();
1301 oldv = mutex->value;
1302 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1303 mutex->value = ((tid << 16) | mtype | new_lock_type);
1304 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1305 oldv ^= 3;
1306 mutex->value = oldv;
1307 }
1308 _recursive_unlock();
1309
1310 if (oldv == mtype)
1311 break;
1312
1313 /*
1314 * The lock was held, possibly contended by others. From
1315 * now on, if we manage to acquire the lock, we have to
1316 * assume that others are still contending for it so that
1317 * we'll wake them when we unlock it.
1318 */
1319 new_lock_type = 2;
1320
1321 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1322 return EBUSY;
1323
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001324 __futex_wait_ex(&mutex->value, shared, oldv, &ts);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001325 }
1326 return 0;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001327}
1328
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001329int pthread_condattr_init(pthread_condattr_t *attr)
1330{
1331 if (attr == NULL)
1332 return EINVAL;
1333
1334 *attr = PTHREAD_PROCESS_PRIVATE;
1335 return 0;
1336}
1337
1338int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1339{
1340 if (attr == NULL || pshared == NULL)
1341 return EINVAL;
1342
1343 *pshared = *attr;
1344 return 0;
1345}
1346
1347int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1348{
1349 if (attr == NULL)
1350 return EINVAL;
1351
1352 if (pshared != PTHREAD_PROCESS_SHARED &&
1353 pshared != PTHREAD_PROCESS_PRIVATE)
1354 return EINVAL;
1355
1356 *attr = pshared;
1357 return 0;
1358}
1359
1360int pthread_condattr_destroy(pthread_condattr_t *attr)
1361{
1362 if (attr == NULL)
1363 return EINVAL;
1364
1365 *attr = 0xdeada11d;
1366 return 0;
1367}
1368
1369/* We use one bit in condition variable values as the 'shared' flag
1370 * The rest is a counter.
1371 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001372#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001373#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001374#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1375
1376#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001377
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001378/* XXX *technically* there is a race condition that could allow
1379 * XXX a signal to be missed. If thread A is preempted in _wait()
1380 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001381 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001382 * XXX before thread A is scheduled again and calls futex_wait(),
1383 * XXX then the signal will be lost.
1384 */
1385
1386int pthread_cond_init(pthread_cond_t *cond,
1387 const pthread_condattr_t *attr)
1388{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001389 if (cond == NULL)
1390 return EINVAL;
1391
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001392 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001393
1394 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001395 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001396
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001397 return 0;
1398}
1399
1400int pthread_cond_destroy(pthread_cond_t *cond)
1401{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001402 if (cond == NULL)
1403 return EINVAL;
1404
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001405 cond->value = 0xdeadc04d;
1406 return 0;
1407}
1408
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001409/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001410 * pthread_cond_signal to atomically decrement the counter
1411 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001412 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001413static int
1414__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001415{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001416 long flags;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001417
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001418 if (__unlikely(cond == NULL))
1419 return EINVAL;
1420
1421 flags = (cond->value & ~COND_COUNTER_MASK);
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001422 for (;;) {
1423 long oldval = cond->value;
1424 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1425 | flags;
1426 if (__atomic_cmpxchg(oldval, newval, &cond->value) == 0)
1427 break;
1428 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001429
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001430 __futex_wake_ex(&cond->value, COND_IS_SHARED(cond), counter);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001431 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001432}
1433
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001434int pthread_cond_broadcast(pthread_cond_t *cond)
1435{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001436 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001437}
1438
1439int pthread_cond_signal(pthread_cond_t *cond)
1440{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001441 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001442}
1443
1444int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1445{
1446 return pthread_cond_timedwait(cond, mutex, NULL);
1447}
1448
1449int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1450 pthread_mutex_t * mutex,
1451 const struct timespec *reltime)
1452{
1453 int status;
1454 int oldvalue = cond->value;
1455
1456 pthread_mutex_unlock(mutex);
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001457 status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond), oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001458 pthread_mutex_lock(mutex);
1459
1460 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1461 return 0;
1462}
1463
1464int __pthread_cond_timedwait(pthread_cond_t *cond,
1465 pthread_mutex_t * mutex,
1466 const struct timespec *abstime,
1467 clockid_t clock)
1468{
1469 struct timespec ts;
1470 struct timespec * tsp;
1471
1472 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001473 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001474 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001475 tsp = &ts;
1476 } else {
1477 tsp = NULL;
1478 }
1479
1480 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1481}
1482
1483int pthread_cond_timedwait(pthread_cond_t *cond,
1484 pthread_mutex_t * mutex,
1485 const struct timespec *abstime)
1486{
1487 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1488}
1489
1490
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001491/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001492int pthread_cond_timedwait_monotonic(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
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001499int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1500 pthread_mutex_t * mutex,
1501 const struct timespec *abstime)
1502{
1503 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1504}
1505
1506int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1507 pthread_mutex_t * mutex,
1508 const struct timespec *reltime)
1509{
1510 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1511}
1512
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001513int pthread_cond_timeout_np(pthread_cond_t *cond,
1514 pthread_mutex_t * mutex,
1515 unsigned msecs)
1516{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001517 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001518
1519 ts.tv_sec = msecs / 1000;
1520 ts.tv_nsec = (msecs % 1000) * 1000000;
1521
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001522 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001523}
1524
1525
1526
1527/* A technical note regarding our thread-local-storage (TLS) implementation:
1528 *
1529 * There can be up to TLSMAP_SIZE independent TLS keys in a given process,
1530 * though the first TLSMAP_START keys are reserved for Bionic to hold
1531 * special thread-specific variables like errno or a pointer to
1532 * the current thread's descriptor.
1533 *
1534 * while stored in the TLS area, these entries cannot be accessed through
1535 * pthread_getspecific() / pthread_setspecific() and pthread_key_delete()
1536 *
1537 * also, some entries in the key table are pre-allocated (see tlsmap_lock)
1538 * to greatly simplify and speedup some OpenGL-related operations. though the
1539 * initialy value will be NULL on all threads.
1540 *
1541 * you can use pthread_getspecific()/setspecific() on these, and in theory
1542 * you could also call pthread_key_delete() as well, though this would
1543 * probably break some apps.
1544 *
1545 * The 'tlsmap_t' type defined below implements a shared global map of
1546 * currently created/allocated TLS keys and the destructors associated
1547 * with them. You should use tlsmap_lock/unlock to access it to avoid
1548 * any race condition.
1549 *
1550 * the global TLS map simply contains a bitmap of allocated keys, and
1551 * an array of destructors.
1552 *
1553 * each thread has a TLS area that is a simple array of TLSMAP_SIZE void*
1554 * pointers. the TLS area of the main thread is stack-allocated in
1555 * __libc_init_common, while the TLS area of other threads is placed at
1556 * the top of their stack in pthread_create.
1557 *
1558 * when pthread_key_create() is called, it finds the first free key in the
1559 * bitmap, then set it to 1, saving the destructor altogether
1560 *
1561 * when pthread_key_delete() is called. it will erase the key's bitmap bit
1562 * and its destructor, and will also clear the key data in the TLS area of
1563 * all created threads. As mandated by Posix, it is the responsability of
1564 * the caller of pthread_key_delete() to properly reclaim the objects that
1565 * were pointed to by these data fields (either before or after the call).
1566 *
1567 */
1568
1569/* TLS Map implementation
1570 */
1571
1572#define TLSMAP_START (TLS_SLOT_MAX_WELL_KNOWN+1)
1573#define TLSMAP_SIZE BIONIC_TLS_SLOTS
1574#define TLSMAP_BITS 32
1575#define TLSMAP_WORDS ((TLSMAP_SIZE+TLSMAP_BITS-1)/TLSMAP_BITS)
1576#define TLSMAP_WORD(m,k) (m)->map[(k)/TLSMAP_BITS]
1577#define TLSMAP_MASK(k) (1U << ((k)&(TLSMAP_BITS-1)))
1578
1579/* this macro is used to quickly check that a key belongs to a reasonable range */
1580#define TLSMAP_VALIDATE_KEY(key) \
1581 ((key) >= TLSMAP_START && (key) < TLSMAP_SIZE)
1582
1583/* the type of tls key destructor functions */
1584typedef void (*tls_dtor_t)(void*);
1585
1586typedef struct {
1587 int init; /* see comment in tlsmap_lock() */
1588 uint32_t map[TLSMAP_WORDS]; /* bitmap of allocated keys */
1589 tls_dtor_t dtors[TLSMAP_SIZE]; /* key destructors */
1590} tlsmap_t;
1591
1592static pthread_mutex_t _tlsmap_lock = PTHREAD_MUTEX_INITIALIZER;
1593static tlsmap_t _tlsmap;
1594
1595/* lock the global TLS map lock and return a handle to it */
1596static __inline__ tlsmap_t* tlsmap_lock(void)
1597{
1598 tlsmap_t* m = &_tlsmap;
1599
1600 pthread_mutex_lock(&_tlsmap_lock);
1601 /* we need to initialize the first entry of the 'map' array
1602 * with the value TLS_DEFAULT_ALLOC_MAP. doing it statically
1603 * when declaring _tlsmap is a bit awkward and is going to
1604 * produce warnings, so do it the first time we use the map
1605 * instead
1606 */
1607 if (__unlikely(!m->init)) {
1608 TLSMAP_WORD(m,0) = TLS_DEFAULT_ALLOC_MAP;
1609 m->init = 1;
1610 }
1611 return m;
1612}
1613
1614/* unlock the global TLS map */
1615static __inline__ void tlsmap_unlock(tlsmap_t* m)
1616{
1617 pthread_mutex_unlock(&_tlsmap_lock);
1618 (void)m; /* a good compiler is a happy compiler */
1619}
1620
1621/* test to see wether a key is allocated */
1622static __inline__ int tlsmap_test(tlsmap_t* m, int key)
1623{
1624 return (TLSMAP_WORD(m,key) & TLSMAP_MASK(key)) != 0;
1625}
1626
1627/* set the destructor and bit flag on a newly allocated key */
1628static __inline__ void tlsmap_set(tlsmap_t* m, int key, tls_dtor_t dtor)
1629{
1630 TLSMAP_WORD(m,key) |= TLSMAP_MASK(key);
1631 m->dtors[key] = dtor;
1632}
1633
1634/* clear the destructor and bit flag on an existing key */
1635static __inline__ void tlsmap_clear(tlsmap_t* m, int key)
1636{
1637 TLSMAP_WORD(m,key) &= ~TLSMAP_MASK(key);
1638 m->dtors[key] = NULL;
1639}
1640
1641/* allocate a new TLS key, return -1 if no room left */
1642static int tlsmap_alloc(tlsmap_t* m, tls_dtor_t dtor)
1643{
1644 int key;
1645
1646 for ( key = TLSMAP_START; key < TLSMAP_SIZE; key++ ) {
1647 if ( !tlsmap_test(m, key) ) {
1648 tlsmap_set(m, key, dtor);
1649 return key;
1650 }
1651 }
1652 return -1;
1653}
1654
1655
1656int pthread_key_create(pthread_key_t *key, void (*destructor_function)(void *))
1657{
1658 uint32_t err = ENOMEM;
1659 tlsmap_t* map = tlsmap_lock();
1660 int k = tlsmap_alloc(map, destructor_function);
1661
1662 if (k >= 0) {
1663 *key = k;
1664 err = 0;
1665 }
1666 tlsmap_unlock(map);
1667 return err;
1668}
1669
1670
1671/* This deletes a pthread_key_t. note that the standard mandates that this does
1672 * not call the destructor of non-NULL key values. Instead, it is the
1673 * responsability of the caller to properly dispose of the corresponding data
1674 * and resources, using any mean it finds suitable.
1675 *
1676 * On the other hand, this function will clear the corresponding key data
1677 * values in all known threads. this prevents later (invalid) calls to
1678 * pthread_getspecific() to receive invalid/stale values.
1679 */
1680int pthread_key_delete(pthread_key_t key)
1681{
1682 uint32_t err;
1683 pthread_internal_t* thr;
1684 tlsmap_t* map;
1685
1686 if (!TLSMAP_VALIDATE_KEY(key)) {
1687 return EINVAL;
1688 }
1689
1690 map = tlsmap_lock();
1691
1692 if (!tlsmap_test(map, key)) {
1693 err = EINVAL;
1694 goto err1;
1695 }
1696
1697 /* clear value in all threads */
1698 pthread_mutex_lock(&gThreadListLock);
1699 for ( thr = gThreadList; thr != NULL; thr = thr->next ) {
1700 /* avoid zombie threads with a negative 'join_count'. these are really
1701 * already dead and don't have a TLS area anymore.
1702 *
1703 * similarly, it is possible to have thr->tls == NULL for threads that
1704 * were just recently created through pthread_create() but whose
1705 * startup trampoline (__thread_entry) hasn't been run yet by the
1706 * scheduler. so check for this too.
1707 */
1708 if (thr->join_count < 0 || !thr->tls)
1709 continue;
1710
1711 thr->tls[key] = NULL;
1712 }
1713 tlsmap_clear(map, key);
1714
1715 pthread_mutex_unlock(&gThreadListLock);
1716 err = 0;
1717
1718err1:
1719 tlsmap_unlock(map);
1720 return err;
1721}
1722
1723
1724int pthread_setspecific(pthread_key_t key, const void *ptr)
1725{
1726 int err = EINVAL;
1727 tlsmap_t* map;
1728
1729 if (TLSMAP_VALIDATE_KEY(key)) {
1730 /* check that we're trying to set data for an allocated key */
1731 map = tlsmap_lock();
1732 if (tlsmap_test(map, key)) {
1733 ((uint32_t *)__get_tls())[key] = (uint32_t)ptr;
1734 err = 0;
1735 }
1736 tlsmap_unlock(map);
1737 }
1738 return err;
1739}
1740
1741void * pthread_getspecific(pthread_key_t key)
1742{
1743 if (!TLSMAP_VALIDATE_KEY(key)) {
1744 return NULL;
1745 }
1746
1747 /* for performance reason, we do not lock/unlock the global TLS map
1748 * to check that the key is properly allocated. if the key was not
1749 * allocated, the value read from the TLS should always be NULL
1750 * due to pthread_key_delete() clearing the values for all threads.
1751 */
1752 return (void *)(((unsigned *)__get_tls())[key]);
1753}
1754
1755/* Posix mandates that this be defined in <limits.h> but we don't have
1756 * it just yet.
1757 */
1758#ifndef PTHREAD_DESTRUCTOR_ITERATIONS
1759# define PTHREAD_DESTRUCTOR_ITERATIONS 4
1760#endif
1761
1762/* this function is called from pthread_exit() to remove all TLS key data
1763 * from this thread's TLS area. this must call the destructor of all keys
1764 * that have a non-NULL data value (and a non-NULL destructor).
1765 *
1766 * because destructors can do funky things like deleting/creating other
1767 * keys, we need to implement this in a loop
1768 */
1769static void pthread_key_clean_all(void)
1770{
1771 tlsmap_t* map;
1772 void** tls = (void**)__get_tls();
1773 int rounds = PTHREAD_DESTRUCTOR_ITERATIONS;
1774
1775 map = tlsmap_lock();
1776
1777 for (rounds = PTHREAD_DESTRUCTOR_ITERATIONS; rounds > 0; rounds--)
1778 {
1779 int kk, count = 0;
1780
1781 for (kk = TLSMAP_START; kk < TLSMAP_SIZE; kk++) {
1782 if ( tlsmap_test(map, kk) )
1783 {
1784 void* data = tls[kk];
1785 tls_dtor_t dtor = map->dtors[kk];
1786
1787 if (data != NULL && dtor != NULL)
1788 {
1789 /* we need to clear the key data now, this will prevent the
1790 * destructor (or a later one) from seeing the old value if
1791 * it calls pthread_getspecific() for some odd reason
1792 *
1793 * we do not do this if 'dtor == NULL' just in case another
1794 * destructor function might be responsible for manually
1795 * releasing the corresponding data.
1796 */
1797 tls[kk] = NULL;
1798
1799 /* because the destructor is free to call pthread_key_create
1800 * and/or pthread_key_delete, we need to temporarily unlock
1801 * the TLS map
1802 */
1803 tlsmap_unlock(map);
1804 (*dtor)(data);
1805 map = tlsmap_lock();
1806
1807 count += 1;
1808 }
1809 }
1810 }
1811
1812 /* if we didn't call any destructor, there is no need to check the
1813 * TLS data again
1814 */
1815 if (count == 0)
1816 break;
1817 }
1818 tlsmap_unlock(map);
1819}
1820
1821// man says this should be in <linux/unistd.h>, but it isn't
1822extern int tkill(int tid, int sig);
1823
1824int pthread_kill(pthread_t tid, int sig)
1825{
1826 int ret;
1827 int old_errno = errno;
1828 pthread_internal_t * thread = (pthread_internal_t *)tid;
1829
1830 ret = tkill(thread->kernel_id, sig);
1831 if (ret < 0) {
1832 ret = errno;
1833 errno = old_errno;
1834 }
1835
1836 return ret;
1837}
1838
1839extern int __rt_sigprocmask(int, const sigset_t *, sigset_t *, size_t);
1840
1841int pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
1842{
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001843 /* pthread_sigmask must return the error code, but the syscall
1844 * will set errno instead and return 0/-1
1845 */
1846 int ret, old_errno = errno;
1847
1848 ret = __rt_sigprocmask(how, set, oset, _NSIG / 8);
1849 if (ret < 0)
1850 ret = errno;
1851
1852 errno = old_errno;
1853 return ret;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001854}
1855
1856
1857int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
1858{
1859 const int CLOCK_IDTYPE_BITS = 3;
1860 pthread_internal_t* thread = (pthread_internal_t*)tid;
1861
1862 if (!thread)
1863 return ESRCH;
1864
1865 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
1866 return 0;
1867}
1868
1869
1870/* NOTE: this implementation doesn't support a init function that throws a C++ exception
1871 * or calls fork()
1872 */
1873int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
1874{
Wink Savilleb9e49ad2010-09-22 14:51:53 -07001875 static pthread_mutex_t once_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001876
1877 if (*once_control == PTHREAD_ONCE_INIT) {
Wink Savilleb9e49ad2010-09-22 14:51:53 -07001878 pthread_mutex_lock( &once_lock );
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001879 if (*once_control == PTHREAD_ONCE_INIT) {
1880 (*init_routine)();
1881 *once_control = ~PTHREAD_ONCE_INIT;
1882 }
Wink Savilleb9e49ad2010-09-22 14:51:53 -07001883 pthread_mutex_unlock( &once_lock );
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001884 }
1885 return 0;
1886}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03001887
1888/* This value is not exported by kernel headers, so hardcode it here */
1889#define MAX_TASK_COMM_LEN 16
1890#define TASK_COMM_FMT "/proc/self/task/%u/comm"
1891
1892int pthread_setname_np(pthread_t thid, const char *thname)
1893{
1894 size_t thname_len;
1895 int saved_errno, ret;
1896
1897 if (thid == 0 || thname == NULL)
1898 return EINVAL;
1899
1900 thname_len = strlen(thname);
1901 if (thname_len >= MAX_TASK_COMM_LEN)
1902 return ERANGE;
1903
1904 saved_errno = errno;
1905 if (thid == pthread_self())
1906 {
1907 ret = prctl(PR_SET_NAME, (unsigned long)thname, 0, 0, 0) ? errno : 0;
1908 }
1909 else
1910 {
1911 /* Have to change another thread's name */
1912 pthread_internal_t *thread = (pthread_internal_t *)thid;
1913 char comm_name[sizeof(TASK_COMM_FMT) + 8];
1914 ssize_t n;
1915 int fd;
1916
1917 snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, (unsigned int)thread->kernel_id);
1918 fd = open(comm_name, O_RDWR);
1919 if (fd == -1)
1920 {
1921 ret = errno;
1922 goto exit;
1923 }
1924 n = TEMP_FAILURE_RETRY(write(fd, thname, thname_len));
1925 close(fd);
1926
1927 if (n < 0)
1928 ret = errno;
1929 else if ((size_t)n != thname_len)
1930 ret = EIO;
1931 else
1932 ret = 0;
1933 }
1934exit:
1935 errno = saved_errno;
1936 return ret;
1937}