blob: a1950183db7d07e846ddbcc6346d2b11e716f80b [file] [log] [blame]
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28#include <sys/types.h>
29#include <unistd.h>
30#include <signal.h>
31#include <stdint.h>
32#include <stdio.h>
33#include <stdlib.h>
34#include <errno.h>
35#include <sys/atomics.h>
36#include <bionic_tls.h>
37#include <sys/mman.h>
38#include <pthread.h>
39#include <time.h>
40#include "pthread_internal.h"
41#include "thread_private.h"
42#include <limits.h>
43#include <memory.h>
44#include <assert.h>
45#include <malloc.h>
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -070046#include <bionic_futex.h>
David 'Digit' Turner6c8a2f22010-06-10 23:34:24 -070047#include <bionic_atomic_inline.h>
André Goddard Rosa78c1c042010-05-19 23:17:16 -030048#include <sys/prctl.h>
49#include <sys/stat.h>
50#include <fcntl.h>
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -070051#include <stdio.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080052
53extern int __pthread_clone(int (*fn)(void*), void *child_stack, int flags, void *arg);
54extern void _exit_with_stack_teardown(void * stackBase, int stackSize, int retCode);
55extern void _exit_thread(int retCode);
56extern int __set_errno(int);
57
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -070058int __futex_wake_ex(volatile void *ftx, int pshared, int val)
59{
60 return __futex_syscall3(ftx, pshared ? FUTEX_WAKE : FUTEX_WAKE_PRIVATE, val);
61}
62
63int __futex_wait_ex(volatile void *ftx, int pshared, int val, const struct timespec *timeout)
64{
65 return __futex_syscall4(ftx, pshared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE, val, timeout);
66}
67
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -070068#define __likely(cond) __builtin_expect(!!(cond), 1)
69#define __unlikely(cond) __builtin_expect(!!(cond), 0)
70
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080071void _thread_created_hook(pid_t thread_id) __attribute__((noinline));
72
73#define PTHREAD_ATTR_FLAG_DETACHED 0x00000001
74#define PTHREAD_ATTR_FLAG_USER_STACK 0x00000002
75
76#define DEFAULT_STACKSIZE (1024 * 1024)
77#define STACKBASE 0x10000000
78
79static uint8_t * gStackBase = (uint8_t *)STACKBASE;
80
81static pthread_mutex_t mmap_lock = PTHREAD_MUTEX_INITIALIZER;
82
83
84static const pthread_attr_t gDefaultPthreadAttr = {
85 .flags = 0,
86 .stack_base = NULL,
87 .stack_size = DEFAULT_STACKSIZE,
88 .guard_size = PAGE_SIZE,
89 .sched_policy = SCHED_NORMAL,
90 .sched_priority = 0
91};
92
93#define INIT_THREADS 1
94
95static pthread_internal_t* gThreadList = NULL;
96static pthread_mutex_t gThreadListLock = PTHREAD_MUTEX_INITIALIZER;
97static pthread_mutex_t gDebuggerNotificationLock = PTHREAD_MUTEX_INITIALIZER;
98
99
100/* we simply malloc/free the internal pthread_internal_t structures. we may
101 * want to use a different allocation scheme in the future, but this one should
102 * be largely enough
103 */
104static pthread_internal_t*
105_pthread_internal_alloc(void)
106{
107 pthread_internal_t* thread;
108
109 thread = calloc( sizeof(*thread), 1 );
110 if (thread)
111 thread->intern = 1;
112
113 return thread;
114}
115
116static void
117_pthread_internal_free( pthread_internal_t* thread )
118{
119 if (thread && thread->intern) {
120 thread->intern = 0; /* just in case */
121 free (thread);
122 }
123}
124
125
126static void
127_pthread_internal_remove_locked( pthread_internal_t* thread )
128{
129 thread->next->pref = thread->pref;
130 thread->pref[0] = thread->next;
131}
132
133static void
134_pthread_internal_remove( pthread_internal_t* thread )
135{
136 pthread_mutex_lock(&gThreadListLock);
137 _pthread_internal_remove_locked(thread);
138 pthread_mutex_unlock(&gThreadListLock);
139}
140
141static void
142_pthread_internal_add( pthread_internal_t* thread )
143{
144 pthread_mutex_lock(&gThreadListLock);
145 thread->pref = &gThreadList;
146 thread->next = thread->pref[0];
147 if (thread->next)
148 thread->next->pref = &thread->next;
149 thread->pref[0] = thread;
150 pthread_mutex_unlock(&gThreadListLock);
151}
152
153pthread_internal_t*
154__get_thread(void)
155{
156 void** tls = (void**)__get_tls();
157
158 return (pthread_internal_t*) tls[TLS_SLOT_THREAD_ID];
159}
160
161
162void*
163__get_stack_base(int *p_stack_size)
164{
165 pthread_internal_t* thread = __get_thread();
166
167 *p_stack_size = thread->attr.stack_size;
168 return thread->attr.stack_base;
169}
170
171
172void __init_tls(void** tls, void* thread)
173{
174 int nn;
175
176 ((pthread_internal_t*)thread)->tls = tls;
177
178 // slot 0 must point to the tls area, this is required by the implementation
179 // of the x86 Linux kernel thread-local-storage
180 tls[TLS_SLOT_SELF] = (void*)tls;
181 tls[TLS_SLOT_THREAD_ID] = thread;
182 for (nn = TLS_SLOT_ERRNO; nn < BIONIC_TLS_SLOTS; nn++)
183 tls[nn] = 0;
184
185 __set_tls( (void*)tls );
186}
187
188
189/*
190 * This trampoline is called from the assembly clone() function
191 */
192void __thread_entry(int (*func)(void*), void *arg, void **tls)
193{
194 int retValue;
195 pthread_internal_t * thrInfo;
196
197 // Wait for our creating thread to release us. This lets it have time to
198 // notify gdb about this thread before it starts doing anything.
Andy McFaddene2ac8982010-09-02 13:34:53 -0700199 //
200 // This also provides the memory barrier needed to ensure that all memory
201 // accesses previously made by the creating thread are visible to us.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800202 pthread_mutex_t * start_mutex = (pthread_mutex_t *)&tls[TLS_SLOT_SELF];
203 pthread_mutex_lock(start_mutex);
204 pthread_mutex_destroy(start_mutex);
205
206 thrInfo = (pthread_internal_t *) tls[TLS_SLOT_THREAD_ID];
207
208 __init_tls( tls, thrInfo );
209
210 pthread_exit( (void*)func(arg) );
211}
212
213void _init_thread(pthread_internal_t * thread, pid_t kernel_id, pthread_attr_t * attr, void * stack_base)
214{
215 if (attr == NULL) {
216 thread->attr = gDefaultPthreadAttr;
217 } else {
218 thread->attr = *attr;
219 }
220 thread->attr.stack_base = stack_base;
221 thread->kernel_id = kernel_id;
222
223 // set the scheduling policy/priority of the thread
224 if (thread->attr.sched_policy != SCHED_NORMAL) {
225 struct sched_param param;
226 param.sched_priority = thread->attr.sched_priority;
227 sched_setscheduler(kernel_id, thread->attr.sched_policy, &param);
228 }
229
230 pthread_cond_init(&thread->join_cond, NULL);
231 thread->join_count = 0;
232
233 thread->cleanup_stack = NULL;
234
235 _pthread_internal_add(thread);
236}
237
238
239/* XXX stacks not reclaimed if thread spawn fails */
240/* XXX stacks address spaces should be reused if available again */
241
242static void *mkstack(size_t size, size_t guard_size)
243{
244 void * stack;
245
246 pthread_mutex_lock(&mmap_lock);
247
248 stack = mmap((void *)gStackBase, size,
249 PROT_READ | PROT_WRITE,
250 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
251 -1, 0);
252
253 if(stack == MAP_FAILED) {
254 stack = NULL;
255 goto done;
256 }
257
258 if(mprotect(stack, guard_size, PROT_NONE)){
259 munmap(stack, size);
260 stack = NULL;
261 goto done;
262 }
263
264done:
265 pthread_mutex_unlock(&mmap_lock);
266 return stack;
267}
268
269/*
Andy McFaddene2ac8982010-09-02 13:34:53 -0700270 * Create a new thread. The thread's stack is laid out like so:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800271 *
272 * +---------------------------+
273 * | pthread_internal_t |
274 * +---------------------------+
275 * | |
276 * | TLS area |
277 * | |
278 * +---------------------------+
279 * | |
280 * . .
281 * . stack area .
282 * . .
283 * | |
284 * +---------------------------+
285 * | guard page |
286 * +---------------------------+
287 *
288 * note that TLS[0] must be a pointer to itself, this is required
289 * by the thread-local storage implementation of the x86 Linux
290 * kernel, where the TLS pointer is read by reading fs:[0]
291 */
292int pthread_create(pthread_t *thread_out, pthread_attr_t const * attr,
293 void *(*start_routine)(void *), void * arg)
294{
295 char* stack;
296 void** tls;
297 int tid;
298 pthread_mutex_t * start_mutex;
299 pthread_internal_t * thread;
300 int madestack = 0;
301 int old_errno = errno;
302
303 /* this will inform the rest of the C library that at least one thread
304 * was created. this will enforce certain functions to acquire/release
305 * locks (e.g. atexit()) to protect shared global structures.
306 *
307 * this works because pthread_create() is not called by the C library
308 * initialization routine that sets up the main thread's data structures.
309 */
310 __isthreaded = 1;
311
312 thread = _pthread_internal_alloc();
313 if (thread == NULL)
314 return ENOMEM;
315
316 if (attr == NULL) {
317 attr = &gDefaultPthreadAttr;
318 }
319
320 // make sure the stack is PAGE_SIZE aligned
321 size_t stackSize = (attr->stack_size +
322 (PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
323
324 if (!attr->stack_base) {
325 stack = mkstack(stackSize, attr->guard_size);
326 if(stack == NULL) {
327 _pthread_internal_free(thread);
328 return ENOMEM;
329 }
330 madestack = 1;
331 } else {
332 stack = attr->stack_base;
333 }
334
335 // Make room for TLS
336 tls = (void**)(stack + stackSize - BIONIC_TLS_SLOTS*sizeof(void*));
337
338 // Create a mutex for the thread in TLS_SLOT_SELF to wait on once it starts so we can keep
339 // it from doing anything until after we notify the debugger about it
Andy McFaddene2ac8982010-09-02 13:34:53 -0700340 //
341 // This also provides the memory barrier we need to ensure that all
342 // memory accesses previously performed by this thread are visible to
343 // the new thread.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800344 start_mutex = (pthread_mutex_t *) &tls[TLS_SLOT_SELF];
345 pthread_mutex_init(start_mutex, NULL);
346 pthread_mutex_lock(start_mutex);
347
348 tls[TLS_SLOT_THREAD_ID] = thread;
349
350 tid = __pthread_clone((int(*)(void*))start_routine, tls,
351 CLONE_FILES | CLONE_FS | CLONE_VM | CLONE_SIGHAND
352 | CLONE_THREAD | CLONE_SYSVSEM | CLONE_DETACHED,
353 arg);
354
355 if(tid < 0) {
356 int result;
357 if (madestack)
358 munmap(stack, stackSize);
359 _pthread_internal_free(thread);
360 result = errno;
361 errno = old_errno;
362 return result;
363 }
364
365 _init_thread(thread, tid, (pthread_attr_t*)attr, stack);
366
367 if (!madestack)
368 thread->attr.flags |= PTHREAD_ATTR_FLAG_USER_STACK;
369
370 // Notify any debuggers about the new thread
371 pthread_mutex_lock(&gDebuggerNotificationLock);
372 _thread_created_hook(tid);
373 pthread_mutex_unlock(&gDebuggerNotificationLock);
374
375 // Let the thread do it's thing
376 pthread_mutex_unlock(start_mutex);
377
378 *thread_out = (pthread_t)thread;
379 return 0;
380}
381
382
383int pthread_attr_init(pthread_attr_t * attr)
384{
385 *attr = gDefaultPthreadAttr;
386 return 0;
387}
388
389int pthread_attr_destroy(pthread_attr_t * attr)
390{
391 memset(attr, 0x42, sizeof(pthread_attr_t));
392 return 0;
393}
394
395int pthread_attr_setdetachstate(pthread_attr_t * attr, int state)
396{
397 if (state == PTHREAD_CREATE_DETACHED) {
398 attr->flags |= PTHREAD_ATTR_FLAG_DETACHED;
399 } else if (state == PTHREAD_CREATE_JOINABLE) {
400 attr->flags &= ~PTHREAD_ATTR_FLAG_DETACHED;
401 } else {
402 return EINVAL;
403 }
404 return 0;
405}
406
407int pthread_attr_getdetachstate(pthread_attr_t const * attr, int * state)
408{
409 *state = (attr->flags & PTHREAD_ATTR_FLAG_DETACHED)
410 ? PTHREAD_CREATE_DETACHED
411 : PTHREAD_CREATE_JOINABLE;
412 return 0;
413}
414
415int pthread_attr_setschedpolicy(pthread_attr_t * attr, int policy)
416{
417 attr->sched_policy = policy;
418 return 0;
419}
420
421int pthread_attr_getschedpolicy(pthread_attr_t const * attr, int * policy)
422{
423 *policy = attr->sched_policy;
424 return 0;
425}
426
427int pthread_attr_setschedparam(pthread_attr_t * attr, struct sched_param const * param)
428{
429 attr->sched_priority = param->sched_priority;
430 return 0;
431}
432
433int pthread_attr_getschedparam(pthread_attr_t const * attr, struct sched_param * param)
434{
435 param->sched_priority = attr->sched_priority;
436 return 0;
437}
438
439int pthread_attr_setstacksize(pthread_attr_t * attr, size_t stack_size)
440{
441 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
442 return EINVAL;
443 }
444 attr->stack_size = stack_size;
445 return 0;
446}
447
448int pthread_attr_getstacksize(pthread_attr_t const * attr, size_t * stack_size)
449{
450 *stack_size = attr->stack_size;
451 return 0;
452}
453
454int pthread_attr_setstackaddr(pthread_attr_t * attr, void * stack_addr)
455{
456#if 1
457 // It's not clear if this is setting the top or bottom of the stack, so don't handle it for now.
458 return ENOSYS;
459#else
460 if ((uint32_t)stack_addr & (PAGE_SIZE - 1)) {
461 return EINVAL;
462 }
463 attr->stack_base = stack_addr;
464 return 0;
465#endif
466}
467
468int pthread_attr_getstackaddr(pthread_attr_t const * attr, void ** stack_addr)
469{
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700470 *stack_addr = (char*)attr->stack_base + attr->stack_size;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800471 return 0;
472}
473
474int pthread_attr_setstack(pthread_attr_t * attr, void * stack_base, size_t stack_size)
475{
476 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
477 return EINVAL;
478 }
479 if ((uint32_t)stack_base & (PAGE_SIZE - 1)) {
480 return EINVAL;
481 }
482 attr->stack_base = stack_base;
483 attr->stack_size = stack_size;
484 return 0;
485}
486
487int pthread_attr_getstack(pthread_attr_t const * attr, void ** stack_base, size_t * stack_size)
488{
489 *stack_base = attr->stack_base;
490 *stack_size = attr->stack_size;
491 return 0;
492}
493
494int pthread_attr_setguardsize(pthread_attr_t * attr, size_t guard_size)
495{
496 if (guard_size & (PAGE_SIZE - 1) || guard_size < PAGE_SIZE) {
497 return EINVAL;
498 }
499
500 attr->guard_size = guard_size;
501 return 0;
502}
503
504int pthread_attr_getguardsize(pthread_attr_t const * attr, size_t * guard_size)
505{
506 *guard_size = attr->guard_size;
507 return 0;
508}
509
510int pthread_getattr_np(pthread_t thid, pthread_attr_t * attr)
511{
512 pthread_internal_t * thread = (pthread_internal_t *)thid;
513 *attr = thread->attr;
514 return 0;
515}
516
517int pthread_attr_setscope(pthread_attr_t *attr, int scope)
518{
519 if (scope == PTHREAD_SCOPE_SYSTEM)
520 return 0;
521 if (scope == PTHREAD_SCOPE_PROCESS)
522 return ENOTSUP;
523
524 return EINVAL;
525}
526
527int pthread_attr_getscope(pthread_attr_t const *attr)
528{
529 return PTHREAD_SCOPE_SYSTEM;
530}
531
532
533/* CAVEAT: our implementation of pthread_cleanup_push/pop doesn't support C++ exceptions
534 * and thread cancelation
535 */
536
537void __pthread_cleanup_push( __pthread_cleanup_t* c,
538 __pthread_cleanup_func_t routine,
539 void* arg )
540{
541 pthread_internal_t* thread = __get_thread();
542
543 c->__cleanup_routine = routine;
544 c->__cleanup_arg = arg;
545 c->__cleanup_prev = thread->cleanup_stack;
546 thread->cleanup_stack = c;
547}
548
549void __pthread_cleanup_pop( __pthread_cleanup_t* c, int execute )
550{
551 pthread_internal_t* thread = __get_thread();
552
553 thread->cleanup_stack = c->__cleanup_prev;
554 if (execute)
555 c->__cleanup_routine(c->__cleanup_arg);
556}
557
558/* used by pthread_exit() to clean all TLS keys of the current thread */
559static void pthread_key_clean_all(void);
560
561void pthread_exit(void * retval)
562{
563 pthread_internal_t* thread = __get_thread();
564 void* stack_base = thread->attr.stack_base;
565 int stack_size = thread->attr.stack_size;
566 int user_stack = (thread->attr.flags & PTHREAD_ATTR_FLAG_USER_STACK) != 0;
567
568 // call the cleanup handlers first
569 while (thread->cleanup_stack) {
570 __pthread_cleanup_t* c = thread->cleanup_stack;
571 thread->cleanup_stack = c->__cleanup_prev;
572 c->__cleanup_routine(c->__cleanup_arg);
573 }
574
575 // call the TLS destructors, it is important to do that before removing this
576 // thread from the global list. this will ensure that if someone else deletes
577 // a TLS key, the corresponding value will be set to NULL in this thread's TLS
578 // space (see pthread_key_delete)
579 pthread_key_clean_all();
580
581 // if the thread is detached, destroy the pthread_internal_t
582 // otherwise, keep it in memory and signal any joiners
583 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
584 _pthread_internal_remove(thread);
585 _pthread_internal_free(thread);
586 } else {
587 /* the join_count field is used to store the number of threads waiting for
588 * the termination of this thread with pthread_join(),
589 *
590 * if it is positive we need to signal the waiters, and we do not touch
591 * the count (it will be decremented by the waiters, the last one will
592 * also remove/free the thread structure
593 *
594 * if it is zero, we set the count value to -1 to indicate that the
595 * thread is in 'zombie' state: it has stopped executing, and its stack
596 * is gone (as well as its TLS area). when another thread calls pthread_join()
597 * on it, it will immediately free the thread and return.
598 */
599 pthread_mutex_lock(&gThreadListLock);
600 thread->return_value = retval;
601 if (thread->join_count > 0) {
602 pthread_cond_broadcast(&thread->join_cond);
603 } else {
604 thread->join_count = -1; /* zombie thread */
605 }
606 pthread_mutex_unlock(&gThreadListLock);
607 }
608
609 // destroy the thread stack
610 if (user_stack)
611 _exit_thread((int)retval);
612 else
613 _exit_with_stack_teardown(stack_base, stack_size, (int)retval);
614}
615
616int pthread_join(pthread_t thid, void ** ret_val)
617{
618 pthread_internal_t* thread = (pthread_internal_t*)thid;
619 int count;
620
621 // check that the thread still exists and is not detached
622 pthread_mutex_lock(&gThreadListLock);
623
624 for (thread = gThreadList; thread != NULL; thread = thread->next)
625 if (thread == (pthread_internal_t*)thid)
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200626 goto FoundIt;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800627
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200628 pthread_mutex_unlock(&gThreadListLock);
629 return ESRCH;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800630
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200631FoundIt:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800632 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
633 pthread_mutex_unlock(&gThreadListLock);
634 return EINVAL;
635 }
636
637 /* wait for thread death when needed
638 *
639 * if the 'join_count' is negative, this is a 'zombie' thread that
640 * is already dead and without stack/TLS
641 *
642 * otherwise, we need to increment 'join-count' and wait to be signaled
643 */
644 count = thread->join_count;
645 if (count >= 0) {
646 thread->join_count += 1;
647 pthread_cond_wait( &thread->join_cond, &gThreadListLock );
648 count = --thread->join_count;
649 }
650 if (ret_val)
651 *ret_val = thread->return_value;
652
653 /* remove thread descriptor when we're the last joiner or when the
654 * thread was already a zombie.
655 */
656 if (count <= 0) {
657 _pthread_internal_remove_locked(thread);
658 _pthread_internal_free(thread);
659 }
660 pthread_mutex_unlock(&gThreadListLock);
661 return 0;
662}
663
664int pthread_detach( pthread_t thid )
665{
666 pthread_internal_t* thread;
667 int result = 0;
668 int flags;
669
670 pthread_mutex_lock(&gThreadListLock);
671 for (thread = gThreadList; thread != NULL; thread = thread->next)
672 if (thread == (pthread_internal_t*)thid)
673 goto FoundIt;
674
675 result = ESRCH;
676 goto Exit;
677
678FoundIt:
679 do {
680 flags = thread->attr.flags;
681
682 if ( flags & PTHREAD_ATTR_FLAG_DETACHED ) {
683 /* thread is not joinable ! */
684 result = EINVAL;
685 goto Exit;
686 }
687 }
688 while ( __atomic_cmpxchg( flags, flags | PTHREAD_ATTR_FLAG_DETACHED,
689 (volatile int*)&thread->attr.flags ) != 0 );
690Exit:
691 pthread_mutex_unlock(&gThreadListLock);
692 return result;
693}
694
695pthread_t pthread_self(void)
696{
697 return (pthread_t)__get_thread();
698}
699
700int pthread_equal(pthread_t one, pthread_t two)
701{
702 return (one == two ? 1 : 0);
703}
704
705int pthread_getschedparam(pthread_t thid, int * policy,
706 struct sched_param * param)
707{
708 int old_errno = errno;
709
710 pthread_internal_t * thread = (pthread_internal_t *)thid;
711 int err = sched_getparam(thread->kernel_id, param);
712 if (!err) {
713 *policy = sched_getscheduler(thread->kernel_id);
714 } else {
715 err = errno;
716 errno = old_errno;
717 }
718 return err;
719}
720
721int pthread_setschedparam(pthread_t thid, int policy,
722 struct sched_param const * param)
723{
724 pthread_internal_t * thread = (pthread_internal_t *)thid;
725 int old_errno = errno;
726 int ret;
727
728 ret = sched_setscheduler(thread->kernel_id, policy, param);
729 if (ret < 0) {
730 ret = errno;
731 errno = old_errno;
732 }
733 return ret;
734}
735
736
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800737// mutex lock states
738//
739// 0: unlocked
740// 1: locked, no waiters
741// 2: locked, maybe waiters
742
743/* a mutex is implemented as a 32-bit integer holding the following fields
744 *
745 * bits: name description
746 * 31-16 tid owner thread's kernel id (recursive and errorcheck only)
747 * 15-14 type mutex type
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700748 * 13 shared process-shared flag
749 * 12-2 counter counter of recursive mutexes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800750 * 1-0 state lock state (0, 1 or 2)
751 */
752
753
754#define MUTEX_OWNER(m) (((m)->value >> 16) & 0xffff)
755#define MUTEX_COUNTER(m) (((m)->value >> 2) & 0xfff)
756
757#define MUTEX_TYPE_MASK 0xc000
758#define MUTEX_TYPE_NORMAL 0x0000
759#define MUTEX_TYPE_RECURSIVE 0x4000
760#define MUTEX_TYPE_ERRORCHECK 0x8000
761
762#define MUTEX_COUNTER_SHIFT 2
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700763#define MUTEX_COUNTER_MASK 0x1ffc
764#define MUTEX_SHARED_MASK 0x2000
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800765
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700766/* a mutex attribute holds the following fields
767 *
768 * bits: name description
769 * 0-3 type type of mutex
770 * 4 shared process-shared flag
771 */
772#define MUTEXATTR_TYPE_MASK 0x000f
773#define MUTEXATTR_SHARED_MASK 0x0010
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800774
775
776int pthread_mutexattr_init(pthread_mutexattr_t *attr)
777{
778 if (attr) {
779 *attr = PTHREAD_MUTEX_DEFAULT;
780 return 0;
781 } else {
782 return EINVAL;
783 }
784}
785
786int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
787{
788 if (attr) {
789 *attr = -1;
790 return 0;
791 } else {
792 return EINVAL;
793 }
794}
795
796int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
797{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700798 if (attr) {
799 int atype = (*attr & MUTEXATTR_TYPE_MASK);
800
801 if (atype >= PTHREAD_MUTEX_NORMAL &&
802 atype <= PTHREAD_MUTEX_ERRORCHECK) {
803 *type = atype;
804 return 0;
805 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800806 }
807 return EINVAL;
808}
809
810int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
811{
812 if (attr && type >= PTHREAD_MUTEX_NORMAL &&
813 type <= PTHREAD_MUTEX_ERRORCHECK ) {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700814 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800815 return 0;
816 }
817 return EINVAL;
818}
819
820/* process-shared mutexes are not supported at the moment */
821
822int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
823{
824 if (!attr)
825 return EINVAL;
826
Mathias Agopianb7681162009-07-13 22:00:33 -0700827 switch (pshared) {
828 case PTHREAD_PROCESS_PRIVATE:
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700829 *attr &= ~MUTEXATTR_SHARED_MASK;
830 return 0;
831
Mathias Agopianb7681162009-07-13 22:00:33 -0700832 case PTHREAD_PROCESS_SHARED:
833 /* our current implementation of pthread actually supports shared
834 * mutexes but won't cleanup if a process dies with the mutex held.
835 * Nevertheless, it's better than nothing. Shared mutexes are used
836 * by surfaceflinger and audioflinger.
837 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700838 *attr |= MUTEXATTR_SHARED_MASK;
Mathias Agopianb7681162009-07-13 22:00:33 -0700839 return 0;
840 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700841 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800842}
843
844int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
845{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700846 if (!attr || !pshared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800847 return EINVAL;
848
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700849 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED
850 : PTHREAD_PROCESS_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800851 return 0;
852}
853
854int pthread_mutex_init(pthread_mutex_t *mutex,
855 const pthread_mutexattr_t *attr)
856{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700857 int value = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800858
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700859 if (mutex == NULL)
860 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800861
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700862 if (__likely(attr == NULL)) {
863 mutex->value = MUTEX_TYPE_NORMAL;
864 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800865 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700866
867 if ((*attr & MUTEXATTR_SHARED_MASK) != 0)
868 value |= MUTEX_SHARED_MASK;
869
870 switch (*attr & MUTEXATTR_TYPE_MASK) {
871 case PTHREAD_MUTEX_NORMAL:
872 value |= MUTEX_TYPE_NORMAL;
873 break;
874 case PTHREAD_MUTEX_RECURSIVE:
875 value |= MUTEX_TYPE_RECURSIVE;
876 break;
877 case PTHREAD_MUTEX_ERRORCHECK:
878 value |= MUTEX_TYPE_ERRORCHECK;
879 break;
880 default:
881 return EINVAL;
882 }
883
884 mutex->value = value;
885 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800886}
887
888int pthread_mutex_destroy(pthread_mutex_t *mutex)
889{
David 'Digit' Turnera02b93b2010-06-28 14:20:22 -0700890 int ret;
891
892 /* use trylock to ensure that the mutex value is
893 * valid and is not already locked. */
894 ret = pthread_mutex_trylock(mutex);
895 if (ret != 0)
896 return ret;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700897
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800898 mutex->value = 0xdead10cc;
899 return 0;
900}
901
902
903/*
904 * Lock a non-recursive mutex.
905 *
906 * As noted above, there are three states:
907 * 0 (unlocked, no contention)
908 * 1 (locked, no contention)
909 * 2 (locked, contention)
910 *
911 * Non-recursive mutexes don't use the thread-id or counter fields, and the
912 * "type" value is zero, so the only bits that will be set are the ones in
913 * the lock state field.
914 */
915static __inline__ void
916_normal_lock(pthread_mutex_t* mutex)
917{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700918 /* We need to preserve the shared flag during operations */
919 int shared = mutex->value & MUTEX_SHARED_MASK;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800920 /*
921 * The common case is an unlocked mutex, so we begin by trying to
922 * change the lock's state from 0 to 1. __atomic_cmpxchg() returns 0
923 * if it made the swap successfully. If the result is nonzero, this
924 * lock is already held by another thread.
925 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700926 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value ) != 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800927 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800928 * We want to go to sleep until the mutex is available, which
929 * requires promoting it to state 2. We need to swap in the new
930 * state value and then wait until somebody wakes us up.
931 *
932 * __atomic_swap() returns the previous value. We swap 2 in and
933 * see if we got zero back; if so, we have acquired the lock. If
934 * not, another thread still holds the lock and we wait again.
935 *
936 * The second argument to the __futex_wait() call is compared
937 * against the current value. If it doesn't match, __futex_wait()
938 * returns immediately (otherwise, it sleeps for a time specified
939 * by the third argument; 0 means sleep forever). This ensures
940 * that the mutex is in state 2 when we go to sleep on it, which
941 * guarantees a wake-up call.
942 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700943 while (__atomic_swap(shared|2, &mutex->value ) != (shared|0))
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -0700944 __futex_wait_ex(&mutex->value, shared, shared|2, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800945 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700946 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800947}
948
949/*
950 * Release a non-recursive mutex. The caller is responsible for determining
951 * that we are in fact the owner of this lock.
952 */
953static __inline__ void
954_normal_unlock(pthread_mutex_t* mutex)
955{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700956 ANDROID_MEMBAR_FULL();
957
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700958 /* We need to preserve the shared flag during operations */
959 int shared = mutex->value & MUTEX_SHARED_MASK;
960
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800961 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700962 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800963 * to release the lock. __atomic_dec() returns the previous value;
964 * if it wasn't 1 we have to do some additional work.
965 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700966 if (__atomic_dec(&mutex->value) != (shared|1)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800967 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800968 * Start by releasing the lock. The decrement changed it from
969 * "contended lock" to "uncontended lock", which means we still
970 * hold it, and anybody who tries to sneak in will push it back
971 * to state 2.
972 *
973 * Once we set it to zero the lock is up for grabs. We follow
974 * this with a __futex_wake() to ensure that one of the waiting
975 * threads has a chance to grab it.
976 *
977 * This doesn't cause a race with the swap/wait pair in
978 * _normal_lock(), because the __futex_wait() call there will
979 * return immediately if the mutex value isn't 2.
980 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700981 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800982
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800983 /*
984 * Wake up one waiting thread. We don't know which thread will be
985 * woken or when it'll start executing -- futexes make no guarantees
986 * here. There may not even be a thread waiting.
987 *
988 * The newly-woken thread will replace the 0 we just set above
989 * with 2, which means that when it eventually releases the mutex
990 * it will also call FUTEX_WAKE. This results in one extra wake
991 * call whenever a lock is contended, but lets us avoid forgetting
992 * anyone without requiring us to track the number of sleepers.
993 *
994 * It's possible for another thread to sneak in and grab the lock
995 * between the zero assignment above and the wake call below. If
996 * the new thread is "slow" and holds the lock for a while, we'll
997 * wake up a sleeper, which will swap in a 2 and then go back to
998 * sleep since the lock is still held. If the new thread is "fast",
999 * running to completion before we call wake, the thread we
1000 * eventually wake will find an unlocked mutex and will execute.
1001 * Either way we have correct behavior and nobody is orphaned on
1002 * the wait queue.
1003 */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001004 __futex_wake_ex(&mutex->value, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001005 }
1006}
1007
1008static pthread_mutex_t __recursive_lock = PTHREAD_MUTEX_INITIALIZER;
1009
1010static void
1011_recursive_lock(void)
1012{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001013 _normal_lock(&__recursive_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001014}
1015
1016static void
1017_recursive_unlock(void)
1018{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001019 _normal_unlock(&__recursive_lock );
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001020}
1021
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001022int pthread_mutex_lock(pthread_mutex_t *mutex)
1023{
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001024 int mtype, tid, new_lock_type, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001025
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001026 if (__unlikely(mutex == NULL))
1027 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001028
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001029 mtype = (mutex->value & MUTEX_TYPE_MASK);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001030 shared = (mutex->value & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001031
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001032 /* Handle normal case first */
1033 if ( __likely(mtype == MUTEX_TYPE_NORMAL) ) {
1034 _normal_lock(mutex);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001035 return 0;
1036 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001037
1038 /* Do we already own this recursive or error-check mutex ? */
1039 tid = __get_thread()->kernel_id;
1040 if ( tid == MUTEX_OWNER(mutex) )
1041 {
1042 int oldv, counter;
1043
1044 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1045 /* trying to re-lock a mutex we already acquired */
1046 return EDEADLK;
1047 }
1048 /*
1049 * We own the mutex, but other threads are able to change
1050 * the contents (e.g. promoting it to "contended"), so we
1051 * need to hold the global lock.
1052 */
1053 _recursive_lock();
1054 oldv = mutex->value;
1055 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1056 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1057 _recursive_unlock();
1058 return 0;
1059 }
1060
1061 /* We don't own the mutex, so try to get it.
1062 *
1063 * First, we try to change its state from 0 to 1, if this
1064 * doesn't work, try to change it to state 2.
1065 */
1066 new_lock_type = 1;
1067
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001068 /* compute futex wait opcode and restore shared flag in mtype */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001069 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001070
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001071 for (;;) {
1072 int oldv;
1073
1074 _recursive_lock();
1075 oldv = mutex->value;
1076 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1077 mutex->value = ((tid << 16) | mtype | new_lock_type);
1078 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1079 oldv ^= 3;
1080 mutex->value = oldv;
1081 }
1082 _recursive_unlock();
1083
1084 if (oldv == mtype)
1085 break;
1086
1087 /*
1088 * The lock was held, possibly contended by others. From
1089 * now on, if we manage to acquire the lock, we have to
1090 * assume that others are still contending for it so that
1091 * we'll wake them when we unlock it.
1092 */
1093 new_lock_type = 2;
1094
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001095 __futex_wait_ex(&mutex->value, shared, oldv, NULL);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001096 }
1097 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001098}
1099
1100
1101int pthread_mutex_unlock(pthread_mutex_t *mutex)
1102{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001103 int mtype, tid, oldv, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001104
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001105 if (__unlikely(mutex == NULL))
1106 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001107
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001108 mtype = (mutex->value & MUTEX_TYPE_MASK);
1109 shared = (mutex->value & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001110
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001111 /* Handle common case first */
1112 if (__likely(mtype == MUTEX_TYPE_NORMAL)) {
1113 _normal_unlock(mutex);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001114 return 0;
1115 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001116
1117 /* Do we already own this recursive or error-check mutex ? */
1118 tid = __get_thread()->kernel_id;
1119 if ( tid != MUTEX_OWNER(mutex) )
1120 return EPERM;
1121
1122 /* We do, decrement counter or release the mutex if it is 0 */
1123 _recursive_lock();
1124 oldv = mutex->value;
1125 if (oldv & MUTEX_COUNTER_MASK) {
1126 mutex->value = oldv - (1 << MUTEX_COUNTER_SHIFT);
1127 oldv = 0;
1128 } else {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001129 mutex->value = shared | mtype;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001130 }
1131 _recursive_unlock();
1132
1133 /* Wake one waiting thread, if any */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001134 if ((oldv & 3) == 2) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001135 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001136 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001137 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001138}
1139
1140
1141int pthread_mutex_trylock(pthread_mutex_t *mutex)
1142{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001143 int mtype, tid, oldv, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001144
1145 if (__unlikely(mutex == NULL))
1146 return EINVAL;
1147
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001148 mtype = (mutex->value & MUTEX_TYPE_MASK);
1149 shared = (mutex->value & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001150
1151 /* Handle common case first */
1152 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001153 {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001154 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
1155 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001156 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001157 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001158
1159 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001160 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001161
1162 /* Do we already own this recursive or error-check mutex ? */
1163 tid = __get_thread()->kernel_id;
1164 if ( tid == MUTEX_OWNER(mutex) )
1165 {
1166 int counter;
1167
1168 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1169 /* already locked by ourselves */
1170 return EDEADLK;
1171 }
1172
1173 _recursive_lock();
1174 oldv = mutex->value;
1175 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1176 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1177 _recursive_unlock();
1178 return 0;
1179 }
1180
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001181 /* Restore sharing bit in mtype */
1182 mtype |= shared;
1183
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001184 /* Try to lock it, just once. */
1185 _recursive_lock();
1186 oldv = mutex->value;
1187 if (oldv == mtype) /* uncontended released lock => state 1 */
1188 mutex->value = ((tid << 16) | mtype | 1);
1189 _recursive_unlock();
1190
1191 if (oldv != mtype)
1192 return EBUSY;
1193
1194 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001195}
1196
1197
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001198/* initialize 'ts' with the difference between 'abstime' and the current time
1199 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
1200 */
1201static int
1202__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
1203{
1204 clock_gettime(clock, ts);
1205 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
1206 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
1207 if (ts->tv_nsec < 0) {
1208 ts->tv_sec--;
1209 ts->tv_nsec += 1000000000;
1210 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001211 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001212 return -1;
1213
1214 return 0;
1215}
1216
1217/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1218 * milliseconds.
1219 */
1220static void
1221__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1222{
1223 clock_gettime(clock, abstime);
1224 abstime->tv_sec += msecs/1000;
1225 abstime->tv_nsec += (msecs%1000)*1000000;
1226 if (abstime->tv_nsec >= 1000000000) {
1227 abstime->tv_sec++;
1228 abstime->tv_nsec -= 1000000000;
1229 }
1230}
1231
1232int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1233{
1234 clockid_t clock = CLOCK_MONOTONIC;
1235 struct timespec abstime;
1236 struct timespec ts;
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001237 int mtype, tid, oldv, new_lock_type, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001238
1239 /* compute absolute expiration time */
1240 __timespec_to_relative_msec(&abstime, msecs, clock);
1241
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001242 if (__unlikely(mutex == NULL))
1243 return EINVAL;
1244
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001245 mtype = (mutex->value & MUTEX_TYPE_MASK);
1246 shared = (mutex->value & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001247
1248 /* Handle common case first */
1249 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001250 {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001251 /* fast path for uncontended lock */
1252 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
1253 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001254 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001255 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001256
1257 /* loop while needed */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001258 while (__atomic_swap(shared|2, &mutex->value) != (shared|0)) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001259 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1260 return EBUSY;
1261
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001262 __futex_wait_ex(&mutex->value, shared, shared|2, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001263 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001264 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001265 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001266 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001267
1268 /* Do we already own this recursive or error-check mutex ? */
1269 tid = __get_thread()->kernel_id;
1270 if ( tid == MUTEX_OWNER(mutex) )
1271 {
1272 int oldv, counter;
1273
1274 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1275 /* already locked by ourselves */
1276 return EDEADLK;
1277 }
1278
1279 _recursive_lock();
1280 oldv = mutex->value;
1281 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1282 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1283 _recursive_unlock();
1284 return 0;
1285 }
1286
1287 /* We don't own the mutex, so try to get it.
1288 *
1289 * First, we try to change its state from 0 to 1, if this
1290 * doesn't work, try to change it to state 2.
1291 */
1292 new_lock_type = 1;
1293
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001294 /* Compute wait op and restore sharing bit in mtype */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001295 mtype |= shared;
1296
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001297 for (;;) {
1298 int oldv;
1299 struct timespec ts;
1300
1301 _recursive_lock();
1302 oldv = mutex->value;
1303 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1304 mutex->value = ((tid << 16) | mtype | new_lock_type);
1305 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1306 oldv ^= 3;
1307 mutex->value = oldv;
1308 }
1309 _recursive_unlock();
1310
1311 if (oldv == mtype)
1312 break;
1313
1314 /*
1315 * The lock was held, possibly contended by others. From
1316 * now on, if we manage to acquire the lock, we have to
1317 * assume that others are still contending for it so that
1318 * we'll wake them when we unlock it.
1319 */
1320 new_lock_type = 2;
1321
1322 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1323 return EBUSY;
1324
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001325 __futex_wait_ex(&mutex->value, shared, oldv, &ts);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001326 }
1327 return 0;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001328}
1329
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001330int pthread_condattr_init(pthread_condattr_t *attr)
1331{
1332 if (attr == NULL)
1333 return EINVAL;
1334
1335 *attr = PTHREAD_PROCESS_PRIVATE;
1336 return 0;
1337}
1338
1339int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1340{
1341 if (attr == NULL || pshared == NULL)
1342 return EINVAL;
1343
1344 *pshared = *attr;
1345 return 0;
1346}
1347
1348int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1349{
1350 if (attr == NULL)
1351 return EINVAL;
1352
1353 if (pshared != PTHREAD_PROCESS_SHARED &&
1354 pshared != PTHREAD_PROCESS_PRIVATE)
1355 return EINVAL;
1356
1357 *attr = pshared;
1358 return 0;
1359}
1360
1361int pthread_condattr_destroy(pthread_condattr_t *attr)
1362{
1363 if (attr == NULL)
1364 return EINVAL;
1365
1366 *attr = 0xdeada11d;
1367 return 0;
1368}
1369
1370/* We use one bit in condition variable values as the 'shared' flag
1371 * The rest is a counter.
1372 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001373#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001374#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001375#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1376
1377#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001378
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001379/* XXX *technically* there is a race condition that could allow
1380 * XXX a signal to be missed. If thread A is preempted in _wait()
1381 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001382 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001383 * XXX before thread A is scheduled again and calls futex_wait(),
1384 * XXX then the signal will be lost.
1385 */
1386
1387int pthread_cond_init(pthread_cond_t *cond,
1388 const pthread_condattr_t *attr)
1389{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001390 if (cond == NULL)
1391 return EINVAL;
1392
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001393 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001394
1395 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001396 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001397
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001398 return 0;
1399}
1400
1401int pthread_cond_destroy(pthread_cond_t *cond)
1402{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001403 if (cond == NULL)
1404 return EINVAL;
1405
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001406 cond->value = 0xdeadc04d;
1407 return 0;
1408}
1409
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001410/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001411 * pthread_cond_signal to atomically decrement the counter
1412 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001413 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001414static int
1415__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001416{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001417 long flags;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001418
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001419 if (__unlikely(cond == NULL))
1420 return EINVAL;
1421
1422 flags = (cond->value & ~COND_COUNTER_MASK);
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001423 for (;;) {
1424 long oldval = cond->value;
1425 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1426 | flags;
1427 if (__atomic_cmpxchg(oldval, newval, &cond->value) == 0)
1428 break;
1429 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001430
Andy McFaddene2ac8982010-09-02 13:34:53 -07001431 /*
1432 * Ensure that all memory accesses previously made by this thread are
1433 * visible to the woken thread(s). On the other side, the "wait"
1434 * code will issue any necessary barriers when locking the mutex.
1435 *
1436 * This may not strictly be necessary -- if the caller follows
1437 * recommended practice and holds the mutex before signaling the cond
1438 * var, the mutex ops will provide correct semantics. If they don't
1439 * hold the mutex, they're subject to race conditions anyway.
1440 */
1441 ANDROID_MEMBAR_FULL();
1442
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001443 __futex_wake_ex(&cond->value, COND_IS_SHARED(cond), counter);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001444 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001445}
1446
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001447int pthread_cond_broadcast(pthread_cond_t *cond)
1448{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001449 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001450}
1451
1452int pthread_cond_signal(pthread_cond_t *cond)
1453{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001454 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001455}
1456
1457int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1458{
1459 return pthread_cond_timedwait(cond, mutex, NULL);
1460}
1461
1462int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1463 pthread_mutex_t * mutex,
1464 const struct timespec *reltime)
1465{
1466 int status;
1467 int oldvalue = cond->value;
1468
1469 pthread_mutex_unlock(mutex);
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001470 status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond), oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001471 pthread_mutex_lock(mutex);
1472
1473 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1474 return 0;
1475}
1476
1477int __pthread_cond_timedwait(pthread_cond_t *cond,
1478 pthread_mutex_t * mutex,
1479 const struct timespec *abstime,
1480 clockid_t clock)
1481{
1482 struct timespec ts;
1483 struct timespec * tsp;
1484
1485 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001486 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001487 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001488 tsp = &ts;
1489 } else {
1490 tsp = NULL;
1491 }
1492
1493 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1494}
1495
1496int pthread_cond_timedwait(pthread_cond_t *cond,
1497 pthread_mutex_t * mutex,
1498 const struct timespec *abstime)
1499{
1500 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1501}
1502
1503
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001504/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001505int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1506 pthread_mutex_t * mutex,
1507 const struct timespec *abstime)
1508{
1509 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1510}
1511
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001512int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1513 pthread_mutex_t * mutex,
1514 const struct timespec *abstime)
1515{
1516 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1517}
1518
1519int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1520 pthread_mutex_t * mutex,
1521 const struct timespec *reltime)
1522{
1523 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1524}
1525
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001526int pthread_cond_timeout_np(pthread_cond_t *cond,
1527 pthread_mutex_t * mutex,
1528 unsigned msecs)
1529{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001530 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001531
1532 ts.tv_sec = msecs / 1000;
1533 ts.tv_nsec = (msecs % 1000) * 1000000;
1534
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001535 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001536}
1537
1538
1539
1540/* A technical note regarding our thread-local-storage (TLS) implementation:
1541 *
1542 * There can be up to TLSMAP_SIZE independent TLS keys in a given process,
1543 * though the first TLSMAP_START keys are reserved for Bionic to hold
1544 * special thread-specific variables like errno or a pointer to
1545 * the current thread's descriptor.
1546 *
1547 * while stored in the TLS area, these entries cannot be accessed through
1548 * pthread_getspecific() / pthread_setspecific() and pthread_key_delete()
1549 *
1550 * also, some entries in the key table are pre-allocated (see tlsmap_lock)
1551 * to greatly simplify and speedup some OpenGL-related operations. though the
1552 * initialy value will be NULL on all threads.
1553 *
1554 * you can use pthread_getspecific()/setspecific() on these, and in theory
1555 * you could also call pthread_key_delete() as well, though this would
1556 * probably break some apps.
1557 *
1558 * The 'tlsmap_t' type defined below implements a shared global map of
1559 * currently created/allocated TLS keys and the destructors associated
1560 * with them. You should use tlsmap_lock/unlock to access it to avoid
1561 * any race condition.
1562 *
1563 * the global TLS map simply contains a bitmap of allocated keys, and
1564 * an array of destructors.
1565 *
1566 * each thread has a TLS area that is a simple array of TLSMAP_SIZE void*
1567 * pointers. the TLS area of the main thread is stack-allocated in
1568 * __libc_init_common, while the TLS area of other threads is placed at
1569 * the top of their stack in pthread_create.
1570 *
1571 * when pthread_key_create() is called, it finds the first free key in the
1572 * bitmap, then set it to 1, saving the destructor altogether
1573 *
1574 * when pthread_key_delete() is called. it will erase the key's bitmap bit
1575 * and its destructor, and will also clear the key data in the TLS area of
1576 * all created threads. As mandated by Posix, it is the responsability of
1577 * the caller of pthread_key_delete() to properly reclaim the objects that
1578 * were pointed to by these data fields (either before or after the call).
1579 *
1580 */
1581
1582/* TLS Map implementation
1583 */
1584
1585#define TLSMAP_START (TLS_SLOT_MAX_WELL_KNOWN+1)
1586#define TLSMAP_SIZE BIONIC_TLS_SLOTS
1587#define TLSMAP_BITS 32
1588#define TLSMAP_WORDS ((TLSMAP_SIZE+TLSMAP_BITS-1)/TLSMAP_BITS)
1589#define TLSMAP_WORD(m,k) (m)->map[(k)/TLSMAP_BITS]
1590#define TLSMAP_MASK(k) (1U << ((k)&(TLSMAP_BITS-1)))
1591
1592/* this macro is used to quickly check that a key belongs to a reasonable range */
1593#define TLSMAP_VALIDATE_KEY(key) \
1594 ((key) >= TLSMAP_START && (key) < TLSMAP_SIZE)
1595
1596/* the type of tls key destructor functions */
1597typedef void (*tls_dtor_t)(void*);
1598
1599typedef struct {
1600 int init; /* see comment in tlsmap_lock() */
1601 uint32_t map[TLSMAP_WORDS]; /* bitmap of allocated keys */
1602 tls_dtor_t dtors[TLSMAP_SIZE]; /* key destructors */
1603} tlsmap_t;
1604
1605static pthread_mutex_t _tlsmap_lock = PTHREAD_MUTEX_INITIALIZER;
1606static tlsmap_t _tlsmap;
1607
1608/* lock the global TLS map lock and return a handle to it */
1609static __inline__ tlsmap_t* tlsmap_lock(void)
1610{
1611 tlsmap_t* m = &_tlsmap;
1612
1613 pthread_mutex_lock(&_tlsmap_lock);
1614 /* we need to initialize the first entry of the 'map' array
1615 * with the value TLS_DEFAULT_ALLOC_MAP. doing it statically
1616 * when declaring _tlsmap is a bit awkward and is going to
1617 * produce warnings, so do it the first time we use the map
1618 * instead
1619 */
1620 if (__unlikely(!m->init)) {
1621 TLSMAP_WORD(m,0) = TLS_DEFAULT_ALLOC_MAP;
1622 m->init = 1;
1623 }
1624 return m;
1625}
1626
1627/* unlock the global TLS map */
1628static __inline__ void tlsmap_unlock(tlsmap_t* m)
1629{
1630 pthread_mutex_unlock(&_tlsmap_lock);
1631 (void)m; /* a good compiler is a happy compiler */
1632}
1633
1634/* test to see wether a key is allocated */
1635static __inline__ int tlsmap_test(tlsmap_t* m, int key)
1636{
1637 return (TLSMAP_WORD(m,key) & TLSMAP_MASK(key)) != 0;
1638}
1639
1640/* set the destructor and bit flag on a newly allocated key */
1641static __inline__ void tlsmap_set(tlsmap_t* m, int key, tls_dtor_t dtor)
1642{
1643 TLSMAP_WORD(m,key) |= TLSMAP_MASK(key);
1644 m->dtors[key] = dtor;
1645}
1646
1647/* clear the destructor and bit flag on an existing key */
1648static __inline__ void tlsmap_clear(tlsmap_t* m, int key)
1649{
1650 TLSMAP_WORD(m,key) &= ~TLSMAP_MASK(key);
1651 m->dtors[key] = NULL;
1652}
1653
1654/* allocate a new TLS key, return -1 if no room left */
1655static int tlsmap_alloc(tlsmap_t* m, tls_dtor_t dtor)
1656{
1657 int key;
1658
1659 for ( key = TLSMAP_START; key < TLSMAP_SIZE; key++ ) {
1660 if ( !tlsmap_test(m, key) ) {
1661 tlsmap_set(m, key, dtor);
1662 return key;
1663 }
1664 }
1665 return -1;
1666}
1667
1668
1669int pthread_key_create(pthread_key_t *key, void (*destructor_function)(void *))
1670{
1671 uint32_t err = ENOMEM;
1672 tlsmap_t* map = tlsmap_lock();
1673 int k = tlsmap_alloc(map, destructor_function);
1674
1675 if (k >= 0) {
1676 *key = k;
1677 err = 0;
1678 }
1679 tlsmap_unlock(map);
1680 return err;
1681}
1682
1683
1684/* This deletes a pthread_key_t. note that the standard mandates that this does
1685 * not call the destructor of non-NULL key values. Instead, it is the
1686 * responsability of the caller to properly dispose of the corresponding data
1687 * and resources, using any mean it finds suitable.
1688 *
1689 * On the other hand, this function will clear the corresponding key data
1690 * values in all known threads. this prevents later (invalid) calls to
1691 * pthread_getspecific() to receive invalid/stale values.
1692 */
1693int pthread_key_delete(pthread_key_t key)
1694{
1695 uint32_t err;
1696 pthread_internal_t* thr;
1697 tlsmap_t* map;
1698
1699 if (!TLSMAP_VALIDATE_KEY(key)) {
1700 return EINVAL;
1701 }
1702
1703 map = tlsmap_lock();
1704
1705 if (!tlsmap_test(map, key)) {
1706 err = EINVAL;
1707 goto err1;
1708 }
1709
1710 /* clear value in all threads */
1711 pthread_mutex_lock(&gThreadListLock);
1712 for ( thr = gThreadList; thr != NULL; thr = thr->next ) {
1713 /* avoid zombie threads with a negative 'join_count'. these are really
1714 * already dead and don't have a TLS area anymore.
1715 *
1716 * similarly, it is possible to have thr->tls == NULL for threads that
1717 * were just recently created through pthread_create() but whose
1718 * startup trampoline (__thread_entry) hasn't been run yet by the
1719 * scheduler. so check for this too.
1720 */
1721 if (thr->join_count < 0 || !thr->tls)
1722 continue;
1723
1724 thr->tls[key] = NULL;
1725 }
1726 tlsmap_clear(map, key);
1727
1728 pthread_mutex_unlock(&gThreadListLock);
1729 err = 0;
1730
1731err1:
1732 tlsmap_unlock(map);
1733 return err;
1734}
1735
1736
1737int pthread_setspecific(pthread_key_t key, const void *ptr)
1738{
1739 int err = EINVAL;
1740 tlsmap_t* map;
1741
1742 if (TLSMAP_VALIDATE_KEY(key)) {
1743 /* check that we're trying to set data for an allocated key */
1744 map = tlsmap_lock();
1745 if (tlsmap_test(map, key)) {
1746 ((uint32_t *)__get_tls())[key] = (uint32_t)ptr;
1747 err = 0;
1748 }
1749 tlsmap_unlock(map);
1750 }
1751 return err;
1752}
1753
1754void * pthread_getspecific(pthread_key_t key)
1755{
1756 if (!TLSMAP_VALIDATE_KEY(key)) {
1757 return NULL;
1758 }
1759
1760 /* for performance reason, we do not lock/unlock the global TLS map
1761 * to check that the key is properly allocated. if the key was not
1762 * allocated, the value read from the TLS should always be NULL
1763 * due to pthread_key_delete() clearing the values for all threads.
1764 */
1765 return (void *)(((unsigned *)__get_tls())[key]);
1766}
1767
1768/* Posix mandates that this be defined in <limits.h> but we don't have
1769 * it just yet.
1770 */
1771#ifndef PTHREAD_DESTRUCTOR_ITERATIONS
1772# define PTHREAD_DESTRUCTOR_ITERATIONS 4
1773#endif
1774
1775/* this function is called from pthread_exit() to remove all TLS key data
1776 * from this thread's TLS area. this must call the destructor of all keys
1777 * that have a non-NULL data value (and a non-NULL destructor).
1778 *
1779 * because destructors can do funky things like deleting/creating other
1780 * keys, we need to implement this in a loop
1781 */
1782static void pthread_key_clean_all(void)
1783{
1784 tlsmap_t* map;
1785 void** tls = (void**)__get_tls();
1786 int rounds = PTHREAD_DESTRUCTOR_ITERATIONS;
1787
1788 map = tlsmap_lock();
1789
1790 for (rounds = PTHREAD_DESTRUCTOR_ITERATIONS; rounds > 0; rounds--)
1791 {
1792 int kk, count = 0;
1793
1794 for (kk = TLSMAP_START; kk < TLSMAP_SIZE; kk++) {
1795 if ( tlsmap_test(map, kk) )
1796 {
1797 void* data = tls[kk];
1798 tls_dtor_t dtor = map->dtors[kk];
1799
1800 if (data != NULL && dtor != NULL)
1801 {
1802 /* we need to clear the key data now, this will prevent the
1803 * destructor (or a later one) from seeing the old value if
1804 * it calls pthread_getspecific() for some odd reason
1805 *
1806 * we do not do this if 'dtor == NULL' just in case another
1807 * destructor function might be responsible for manually
1808 * releasing the corresponding data.
1809 */
1810 tls[kk] = NULL;
1811
1812 /* because the destructor is free to call pthread_key_create
1813 * and/or pthread_key_delete, we need to temporarily unlock
1814 * the TLS map
1815 */
1816 tlsmap_unlock(map);
1817 (*dtor)(data);
1818 map = tlsmap_lock();
1819
1820 count += 1;
1821 }
1822 }
1823 }
1824
1825 /* if we didn't call any destructor, there is no need to check the
1826 * TLS data again
1827 */
1828 if (count == 0)
1829 break;
1830 }
1831 tlsmap_unlock(map);
1832}
1833
1834// man says this should be in <linux/unistd.h>, but it isn't
1835extern int tkill(int tid, int sig);
1836
1837int pthread_kill(pthread_t tid, int sig)
1838{
1839 int ret;
1840 int old_errno = errno;
1841 pthread_internal_t * thread = (pthread_internal_t *)tid;
1842
1843 ret = tkill(thread->kernel_id, sig);
1844 if (ret < 0) {
1845 ret = errno;
1846 errno = old_errno;
1847 }
1848
1849 return ret;
1850}
1851
1852extern int __rt_sigprocmask(int, const sigset_t *, sigset_t *, size_t);
1853
1854int pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
1855{
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001856 /* pthread_sigmask must return the error code, but the syscall
1857 * will set errno instead and return 0/-1
1858 */
1859 int ret, old_errno = errno;
1860
1861 ret = __rt_sigprocmask(how, set, oset, _NSIG / 8);
1862 if (ret < 0)
1863 ret = errno;
1864
1865 errno = old_errno;
1866 return ret;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001867}
1868
1869
1870int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
1871{
1872 const int CLOCK_IDTYPE_BITS = 3;
1873 pthread_internal_t* thread = (pthread_internal_t*)tid;
1874
1875 if (!thread)
1876 return ESRCH;
1877
1878 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
1879 return 0;
1880}
1881
1882
1883/* NOTE: this implementation doesn't support a init function that throws a C++ exception
1884 * or calls fork()
1885 */
1886int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
1887{
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001888 static pthread_mutex_t once_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001889 volatile pthread_once_t* ocptr = once_control;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001890
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001891 pthread_once_t tmp = *ocptr;
1892 ANDROID_MEMBAR_FULL();
1893 if (tmp == PTHREAD_ONCE_INIT) {
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001894 pthread_mutex_lock( &once_lock );
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001895 if (*ocptr == PTHREAD_ONCE_INIT) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001896 (*init_routine)();
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001897 ANDROID_MEMBAR_FULL();
1898 *ocptr = ~PTHREAD_ONCE_INIT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001899 }
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001900 pthread_mutex_unlock( &once_lock );
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001901 }
1902 return 0;
1903}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03001904
1905/* This value is not exported by kernel headers, so hardcode it here */
1906#define MAX_TASK_COMM_LEN 16
1907#define TASK_COMM_FMT "/proc/self/task/%u/comm"
1908
1909int pthread_setname_np(pthread_t thid, const char *thname)
1910{
1911 size_t thname_len;
1912 int saved_errno, ret;
1913
1914 if (thid == 0 || thname == NULL)
1915 return EINVAL;
1916
1917 thname_len = strlen(thname);
1918 if (thname_len >= MAX_TASK_COMM_LEN)
1919 return ERANGE;
1920
1921 saved_errno = errno;
1922 if (thid == pthread_self())
1923 {
1924 ret = prctl(PR_SET_NAME, (unsigned long)thname, 0, 0, 0) ? errno : 0;
1925 }
1926 else
1927 {
1928 /* Have to change another thread's name */
1929 pthread_internal_t *thread = (pthread_internal_t *)thid;
1930 char comm_name[sizeof(TASK_COMM_FMT) + 8];
1931 ssize_t n;
1932 int fd;
1933
1934 snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, (unsigned int)thread->kernel_id);
1935 fd = open(comm_name, O_RDWR);
1936 if (fd == -1)
1937 {
1938 ret = errno;
1939 goto exit;
1940 }
1941 n = TEMP_FAILURE_RETRY(write(fd, thname, thname_len));
1942 close(fd);
1943
1944 if (n < 0)
1945 ret = errno;
1946 else if ((size_t)n != thname_len)
1947 ret = EIO;
1948 else
1949 ret = 0;
1950 }
1951exit:
1952 errno = saved_errno;
1953 return ret;
1954}