blob: 0a0854dd7d4892dc4272c534363d1c143b7a4828 [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
Bruce Beare8e551a62011-03-28 09:47:35 -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.
Andy McFaddene2ac8982010-09-02 13:34:53 -0700205 //
206 // This also provides the memory barrier needed to ensure that all memory
207 // accesses previously made by the creating thread are visible to us.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800208 pthread_mutex_t * start_mutex = (pthread_mutex_t *)&tls[TLS_SLOT_SELF];
209 pthread_mutex_lock(start_mutex);
210 pthread_mutex_destroy(start_mutex);
211
212 thrInfo = (pthread_internal_t *) tls[TLS_SLOT_THREAD_ID];
213
214 __init_tls( tls, thrInfo );
215
216 pthread_exit( (void*)func(arg) );
217}
218
219void _init_thread(pthread_internal_t * thread, pid_t kernel_id, pthread_attr_t * attr, void * stack_base)
220{
221 if (attr == NULL) {
222 thread->attr = gDefaultPthreadAttr;
223 } else {
224 thread->attr = *attr;
225 }
226 thread->attr.stack_base = stack_base;
227 thread->kernel_id = kernel_id;
228
229 // set the scheduling policy/priority of the thread
230 if (thread->attr.sched_policy != SCHED_NORMAL) {
231 struct sched_param param;
232 param.sched_priority = thread->attr.sched_priority;
233 sched_setscheduler(kernel_id, thread->attr.sched_policy, &param);
234 }
235
236 pthread_cond_init(&thread->join_cond, NULL);
237 thread->join_count = 0;
238
239 thread->cleanup_stack = NULL;
240
241 _pthread_internal_add(thread);
242}
243
244
245/* XXX stacks not reclaimed if thread spawn fails */
246/* XXX stacks address spaces should be reused if available again */
247
248static void *mkstack(size_t size, size_t guard_size)
249{
250 void * stack;
251
252 pthread_mutex_lock(&mmap_lock);
253
254 stack = mmap((void *)gStackBase, size,
255 PROT_READ | PROT_WRITE,
256 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
257 -1, 0);
258
259 if(stack == MAP_FAILED) {
260 stack = NULL;
261 goto done;
262 }
263
264 if(mprotect(stack, guard_size, PROT_NONE)){
265 munmap(stack, size);
266 stack = NULL;
267 goto done;
268 }
269
270done:
271 pthread_mutex_unlock(&mmap_lock);
272 return stack;
273}
274
275/*
Andy McFaddene2ac8982010-09-02 13:34:53 -0700276 * Create a new thread. The thread's stack is laid out like so:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800277 *
278 * +---------------------------+
279 * | pthread_internal_t |
280 * +---------------------------+
281 * | |
282 * | TLS area |
283 * | |
284 * +---------------------------+
285 * | |
286 * . .
287 * . stack area .
288 * . .
289 * | |
290 * +---------------------------+
291 * | guard page |
292 * +---------------------------+
293 *
294 * note that TLS[0] must be a pointer to itself, this is required
295 * by the thread-local storage implementation of the x86 Linux
296 * kernel, where the TLS pointer is read by reading fs:[0]
297 */
298int pthread_create(pthread_t *thread_out, pthread_attr_t const * attr,
299 void *(*start_routine)(void *), void * arg)
300{
301 char* stack;
302 void** tls;
303 int tid;
304 pthread_mutex_t * start_mutex;
305 pthread_internal_t * thread;
306 int madestack = 0;
307 int old_errno = errno;
308
309 /* this will inform the rest of the C library that at least one thread
310 * was created. this will enforce certain functions to acquire/release
311 * locks (e.g. atexit()) to protect shared global structures.
312 *
313 * this works because pthread_create() is not called by the C library
314 * initialization routine that sets up the main thread's data structures.
315 */
316 __isthreaded = 1;
317
318 thread = _pthread_internal_alloc();
319 if (thread == NULL)
320 return ENOMEM;
321
322 if (attr == NULL) {
323 attr = &gDefaultPthreadAttr;
324 }
325
326 // make sure the stack is PAGE_SIZE aligned
327 size_t stackSize = (attr->stack_size +
328 (PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
329
330 if (!attr->stack_base) {
331 stack = mkstack(stackSize, attr->guard_size);
332 if(stack == NULL) {
333 _pthread_internal_free(thread);
334 return ENOMEM;
335 }
336 madestack = 1;
337 } else {
338 stack = attr->stack_base;
339 }
340
341 // Make room for TLS
342 tls = (void**)(stack + stackSize - BIONIC_TLS_SLOTS*sizeof(void*));
343
344 // Create a mutex for the thread in TLS_SLOT_SELF to wait on once it starts so we can keep
345 // it from doing anything until after we notify the debugger about it
Andy McFaddene2ac8982010-09-02 13:34:53 -0700346 //
347 // This also provides the memory barrier we need to ensure that all
348 // memory accesses previously performed by this thread are visible to
349 // the new thread.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800350 start_mutex = (pthread_mutex_t *) &tls[TLS_SLOT_SELF];
351 pthread_mutex_init(start_mutex, NULL);
352 pthread_mutex_lock(start_mutex);
353
354 tls[TLS_SLOT_THREAD_ID] = thread;
355
356 tid = __pthread_clone((int(*)(void*))start_routine, tls,
357 CLONE_FILES | CLONE_FS | CLONE_VM | CLONE_SIGHAND
358 | CLONE_THREAD | CLONE_SYSVSEM | CLONE_DETACHED,
359 arg);
360
361 if(tid < 0) {
362 int result;
363 if (madestack)
364 munmap(stack, stackSize);
365 _pthread_internal_free(thread);
366 result = errno;
367 errno = old_errno;
368 return result;
369 }
370
371 _init_thread(thread, tid, (pthread_attr_t*)attr, stack);
372
373 if (!madestack)
374 thread->attr.flags |= PTHREAD_ATTR_FLAG_USER_STACK;
375
376 // Notify any debuggers about the new thread
377 pthread_mutex_lock(&gDebuggerNotificationLock);
378 _thread_created_hook(tid);
379 pthread_mutex_unlock(&gDebuggerNotificationLock);
380
381 // Let the thread do it's thing
382 pthread_mutex_unlock(start_mutex);
383
384 *thread_out = (pthread_t)thread;
385 return 0;
386}
387
388
389int pthread_attr_init(pthread_attr_t * attr)
390{
391 *attr = gDefaultPthreadAttr;
392 return 0;
393}
394
395int pthread_attr_destroy(pthread_attr_t * attr)
396{
397 memset(attr, 0x42, sizeof(pthread_attr_t));
398 return 0;
399}
400
401int pthread_attr_setdetachstate(pthread_attr_t * attr, int state)
402{
403 if (state == PTHREAD_CREATE_DETACHED) {
404 attr->flags |= PTHREAD_ATTR_FLAG_DETACHED;
405 } else if (state == PTHREAD_CREATE_JOINABLE) {
406 attr->flags &= ~PTHREAD_ATTR_FLAG_DETACHED;
407 } else {
408 return EINVAL;
409 }
410 return 0;
411}
412
413int pthread_attr_getdetachstate(pthread_attr_t const * attr, int * state)
414{
415 *state = (attr->flags & PTHREAD_ATTR_FLAG_DETACHED)
416 ? PTHREAD_CREATE_DETACHED
417 : PTHREAD_CREATE_JOINABLE;
418 return 0;
419}
420
421int pthread_attr_setschedpolicy(pthread_attr_t * attr, int policy)
422{
423 attr->sched_policy = policy;
424 return 0;
425}
426
427int pthread_attr_getschedpolicy(pthread_attr_t const * attr, int * policy)
428{
429 *policy = attr->sched_policy;
430 return 0;
431}
432
433int pthread_attr_setschedparam(pthread_attr_t * attr, struct sched_param const * param)
434{
435 attr->sched_priority = param->sched_priority;
436 return 0;
437}
438
439int pthread_attr_getschedparam(pthread_attr_t const * attr, struct sched_param * param)
440{
441 param->sched_priority = attr->sched_priority;
442 return 0;
443}
444
445int pthread_attr_setstacksize(pthread_attr_t * attr, size_t stack_size)
446{
447 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
448 return EINVAL;
449 }
450 attr->stack_size = stack_size;
451 return 0;
452}
453
454int pthread_attr_getstacksize(pthread_attr_t const * attr, size_t * stack_size)
455{
456 *stack_size = attr->stack_size;
457 return 0;
458}
459
460int pthread_attr_setstackaddr(pthread_attr_t * attr, void * stack_addr)
461{
462#if 1
463 // It's not clear if this is setting the top or bottom of the stack, so don't handle it for now.
464 return ENOSYS;
465#else
466 if ((uint32_t)stack_addr & (PAGE_SIZE - 1)) {
467 return EINVAL;
468 }
469 attr->stack_base = stack_addr;
470 return 0;
471#endif
472}
473
474int pthread_attr_getstackaddr(pthread_attr_t const * attr, void ** stack_addr)
475{
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -0700476 *stack_addr = (char*)attr->stack_base + attr->stack_size;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800477 return 0;
478}
479
480int pthread_attr_setstack(pthread_attr_t * attr, void * stack_base, size_t stack_size)
481{
482 if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
483 return EINVAL;
484 }
485 if ((uint32_t)stack_base & (PAGE_SIZE - 1)) {
486 return EINVAL;
487 }
488 attr->stack_base = stack_base;
489 attr->stack_size = stack_size;
490 return 0;
491}
492
493int pthread_attr_getstack(pthread_attr_t const * attr, void ** stack_base, size_t * stack_size)
494{
495 *stack_base = attr->stack_base;
496 *stack_size = attr->stack_size;
497 return 0;
498}
499
500int pthread_attr_setguardsize(pthread_attr_t * attr, size_t guard_size)
501{
502 if (guard_size & (PAGE_SIZE - 1) || guard_size < PAGE_SIZE) {
503 return EINVAL;
504 }
505
506 attr->guard_size = guard_size;
507 return 0;
508}
509
510int pthread_attr_getguardsize(pthread_attr_t const * attr, size_t * guard_size)
511{
512 *guard_size = attr->guard_size;
513 return 0;
514}
515
516int pthread_getattr_np(pthread_t thid, pthread_attr_t * attr)
517{
518 pthread_internal_t * thread = (pthread_internal_t *)thid;
519 *attr = thread->attr;
520 return 0;
521}
522
523int pthread_attr_setscope(pthread_attr_t *attr, int scope)
524{
525 if (scope == PTHREAD_SCOPE_SYSTEM)
526 return 0;
527 if (scope == PTHREAD_SCOPE_PROCESS)
528 return ENOTSUP;
529
530 return EINVAL;
531}
532
533int pthread_attr_getscope(pthread_attr_t const *attr)
534{
535 return PTHREAD_SCOPE_SYSTEM;
536}
537
538
539/* CAVEAT: our implementation of pthread_cleanup_push/pop doesn't support C++ exceptions
540 * and thread cancelation
541 */
542
543void __pthread_cleanup_push( __pthread_cleanup_t* c,
544 __pthread_cleanup_func_t routine,
545 void* arg )
546{
547 pthread_internal_t* thread = __get_thread();
548
549 c->__cleanup_routine = routine;
550 c->__cleanup_arg = arg;
551 c->__cleanup_prev = thread->cleanup_stack;
552 thread->cleanup_stack = c;
553}
554
555void __pthread_cleanup_pop( __pthread_cleanup_t* c, int execute )
556{
557 pthread_internal_t* thread = __get_thread();
558
559 thread->cleanup_stack = c->__cleanup_prev;
560 if (execute)
561 c->__cleanup_routine(c->__cleanup_arg);
562}
563
564/* used by pthread_exit() to clean all TLS keys of the current thread */
565static void pthread_key_clean_all(void);
566
567void pthread_exit(void * retval)
568{
569 pthread_internal_t* thread = __get_thread();
570 void* stack_base = thread->attr.stack_base;
571 int stack_size = thread->attr.stack_size;
572 int user_stack = (thread->attr.flags & PTHREAD_ATTR_FLAG_USER_STACK) != 0;
573
574 // call the cleanup handlers first
575 while (thread->cleanup_stack) {
576 __pthread_cleanup_t* c = thread->cleanup_stack;
577 thread->cleanup_stack = c->__cleanup_prev;
578 c->__cleanup_routine(c->__cleanup_arg);
579 }
580
581 // call the TLS destructors, it is important to do that before removing this
582 // thread from the global list. this will ensure that if someone else deletes
583 // a TLS key, the corresponding value will be set to NULL in this thread's TLS
584 // space (see pthread_key_delete)
585 pthread_key_clean_all();
586
587 // if the thread is detached, destroy the pthread_internal_t
588 // otherwise, keep it in memory and signal any joiners
589 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
590 _pthread_internal_remove(thread);
591 _pthread_internal_free(thread);
592 } else {
593 /* the join_count field is used to store the number of threads waiting for
594 * the termination of this thread with pthread_join(),
595 *
596 * if it is positive we need to signal the waiters, and we do not touch
597 * the count (it will be decremented by the waiters, the last one will
598 * also remove/free the thread structure
599 *
600 * if it is zero, we set the count value to -1 to indicate that the
601 * thread is in 'zombie' state: it has stopped executing, and its stack
602 * is gone (as well as its TLS area). when another thread calls pthread_join()
603 * on it, it will immediately free the thread and return.
604 */
605 pthread_mutex_lock(&gThreadListLock);
606 thread->return_value = retval;
607 if (thread->join_count > 0) {
608 pthread_cond_broadcast(&thread->join_cond);
609 } else {
610 thread->join_count = -1; /* zombie thread */
611 }
612 pthread_mutex_unlock(&gThreadListLock);
613 }
614
615 // destroy the thread stack
616 if (user_stack)
617 _exit_thread((int)retval);
618 else
619 _exit_with_stack_teardown(stack_base, stack_size, (int)retval);
620}
621
622int pthread_join(pthread_t thid, void ** ret_val)
623{
624 pthread_internal_t* thread = (pthread_internal_t*)thid;
625 int count;
626
627 // check that the thread still exists and is not detached
628 pthread_mutex_lock(&gThreadListLock);
629
630 for (thread = gThreadList; thread != NULL; thread = thread->next)
631 if (thread == (pthread_internal_t*)thid)
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200632 goto FoundIt;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800633
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200634 pthread_mutex_unlock(&gThreadListLock);
635 return ESRCH;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800636
André Goddard Rosaa28336c2010-02-05 16:21:07 -0200637FoundIt:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800638 if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
639 pthread_mutex_unlock(&gThreadListLock);
640 return EINVAL;
641 }
642
643 /* wait for thread death when needed
644 *
645 * if the 'join_count' is negative, this is a 'zombie' thread that
646 * is already dead and without stack/TLS
647 *
648 * otherwise, we need to increment 'join-count' and wait to be signaled
649 */
650 count = thread->join_count;
651 if (count >= 0) {
652 thread->join_count += 1;
653 pthread_cond_wait( &thread->join_cond, &gThreadListLock );
654 count = --thread->join_count;
655 }
656 if (ret_val)
657 *ret_val = thread->return_value;
658
659 /* remove thread descriptor when we're the last joiner or when the
660 * thread was already a zombie.
661 */
662 if (count <= 0) {
663 _pthread_internal_remove_locked(thread);
664 _pthread_internal_free(thread);
665 }
666 pthread_mutex_unlock(&gThreadListLock);
667 return 0;
668}
669
670int pthread_detach( pthread_t thid )
671{
672 pthread_internal_t* thread;
673 int result = 0;
674 int flags;
675
676 pthread_mutex_lock(&gThreadListLock);
677 for (thread = gThreadList; thread != NULL; thread = thread->next)
678 if (thread == (pthread_internal_t*)thid)
679 goto FoundIt;
680
681 result = ESRCH;
682 goto Exit;
683
684FoundIt:
685 do {
686 flags = thread->attr.flags;
687
688 if ( flags & PTHREAD_ATTR_FLAG_DETACHED ) {
689 /* thread is not joinable ! */
690 result = EINVAL;
691 goto Exit;
692 }
693 }
694 while ( __atomic_cmpxchg( flags, flags | PTHREAD_ATTR_FLAG_DETACHED,
695 (volatile int*)&thread->attr.flags ) != 0 );
696Exit:
697 pthread_mutex_unlock(&gThreadListLock);
698 return result;
699}
700
701pthread_t pthread_self(void)
702{
703 return (pthread_t)__get_thread();
704}
705
706int pthread_equal(pthread_t one, pthread_t two)
707{
708 return (one == two ? 1 : 0);
709}
710
711int pthread_getschedparam(pthread_t thid, int * policy,
712 struct sched_param * param)
713{
714 int old_errno = errno;
715
716 pthread_internal_t * thread = (pthread_internal_t *)thid;
717 int err = sched_getparam(thread->kernel_id, param);
718 if (!err) {
719 *policy = sched_getscheduler(thread->kernel_id);
720 } else {
721 err = errno;
722 errno = old_errno;
723 }
724 return err;
725}
726
727int pthread_setschedparam(pthread_t thid, int policy,
728 struct sched_param const * param)
729{
730 pthread_internal_t * thread = (pthread_internal_t *)thid;
731 int old_errno = errno;
732 int ret;
733
734 ret = sched_setscheduler(thread->kernel_id, policy, param);
735 if (ret < 0) {
736 ret = errno;
737 errno = old_errno;
738 }
739 return ret;
740}
741
742
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800743// mutex lock states
744//
745// 0: unlocked
746// 1: locked, no waiters
747// 2: locked, maybe waiters
748
749/* a mutex is implemented as a 32-bit integer holding the following fields
750 *
751 * bits: name description
752 * 31-16 tid owner thread's kernel id (recursive and errorcheck only)
753 * 15-14 type mutex type
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700754 * 13 shared process-shared flag
755 * 12-2 counter counter of recursive mutexes
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800756 * 1-0 state lock state (0, 1 or 2)
757 */
758
759
760#define MUTEX_OWNER(m) (((m)->value >> 16) & 0xffff)
761#define MUTEX_COUNTER(m) (((m)->value >> 2) & 0xfff)
762
763#define MUTEX_TYPE_MASK 0xc000
764#define MUTEX_TYPE_NORMAL 0x0000
765#define MUTEX_TYPE_RECURSIVE 0x4000
766#define MUTEX_TYPE_ERRORCHECK 0x8000
767
768#define MUTEX_COUNTER_SHIFT 2
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700769#define MUTEX_COUNTER_MASK 0x1ffc
770#define MUTEX_SHARED_MASK 0x2000
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800771
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700772/* a mutex attribute holds the following fields
773 *
774 * bits: name description
775 * 0-3 type type of mutex
776 * 4 shared process-shared flag
777 */
778#define MUTEXATTR_TYPE_MASK 0x000f
779#define MUTEXATTR_SHARED_MASK 0x0010
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800780
781
782int pthread_mutexattr_init(pthread_mutexattr_t *attr)
783{
784 if (attr) {
785 *attr = PTHREAD_MUTEX_DEFAULT;
786 return 0;
787 } else {
788 return EINVAL;
789 }
790}
791
792int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
793{
794 if (attr) {
795 *attr = -1;
796 return 0;
797 } else {
798 return EINVAL;
799 }
800}
801
802int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
803{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700804 if (attr) {
805 int atype = (*attr & MUTEXATTR_TYPE_MASK);
806
807 if (atype >= PTHREAD_MUTEX_NORMAL &&
808 atype <= PTHREAD_MUTEX_ERRORCHECK) {
809 *type = atype;
810 return 0;
811 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800812 }
813 return EINVAL;
814}
815
816int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
817{
818 if (attr && type >= PTHREAD_MUTEX_NORMAL &&
819 type <= PTHREAD_MUTEX_ERRORCHECK ) {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700820 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800821 return 0;
822 }
823 return EINVAL;
824}
825
826/* process-shared mutexes are not supported at the moment */
827
828int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
829{
830 if (!attr)
831 return EINVAL;
832
Mathias Agopianb7681162009-07-13 22:00:33 -0700833 switch (pshared) {
834 case PTHREAD_PROCESS_PRIVATE:
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700835 *attr &= ~MUTEXATTR_SHARED_MASK;
836 return 0;
837
Mathias Agopianb7681162009-07-13 22:00:33 -0700838 case PTHREAD_PROCESS_SHARED:
839 /* our current implementation of pthread actually supports shared
840 * mutexes but won't cleanup if a process dies with the mutex held.
841 * Nevertheless, it's better than nothing. Shared mutexes are used
842 * by surfaceflinger and audioflinger.
843 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700844 *attr |= MUTEXATTR_SHARED_MASK;
Mathias Agopianb7681162009-07-13 22:00:33 -0700845 return 0;
846 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700847 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800848}
849
850int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
851{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700852 if (!attr || !pshared)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800853 return EINVAL;
854
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700855 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED
856 : PTHREAD_PROCESS_PRIVATE;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800857 return 0;
858}
859
860int pthread_mutex_init(pthread_mutex_t *mutex,
861 const pthread_mutexattr_t *attr)
862{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700863 int value = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800864
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700865 if (mutex == NULL)
866 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800867
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700868 if (__likely(attr == NULL)) {
869 mutex->value = MUTEX_TYPE_NORMAL;
870 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800871 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700872
873 if ((*attr & MUTEXATTR_SHARED_MASK) != 0)
874 value |= MUTEX_SHARED_MASK;
875
876 switch (*attr & MUTEXATTR_TYPE_MASK) {
877 case PTHREAD_MUTEX_NORMAL:
878 value |= MUTEX_TYPE_NORMAL;
879 break;
880 case PTHREAD_MUTEX_RECURSIVE:
881 value |= MUTEX_TYPE_RECURSIVE;
882 break;
883 case PTHREAD_MUTEX_ERRORCHECK:
884 value |= MUTEX_TYPE_ERRORCHECK;
885 break;
886 default:
887 return EINVAL;
888 }
889
890 mutex->value = value;
891 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800892}
893
894int pthread_mutex_destroy(pthread_mutex_t *mutex)
895{
David 'Digit' Turnera02b93b2010-06-28 14:20:22 -0700896 int ret;
897
898 /* use trylock to ensure that the mutex value is
899 * valid and is not already locked. */
900 ret = pthread_mutex_trylock(mutex);
901 if (ret != 0)
902 return ret;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700903
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800904 mutex->value = 0xdead10cc;
905 return 0;
906}
907
908
909/*
910 * Lock a non-recursive mutex.
911 *
912 * As noted above, there are three states:
913 * 0 (unlocked, no contention)
914 * 1 (locked, no contention)
915 * 2 (locked, contention)
916 *
917 * Non-recursive mutexes don't use the thread-id or counter fields, and the
918 * "type" value is zero, so the only bits that will be set are the ones in
919 * the lock state field.
920 */
921static __inline__ void
922_normal_lock(pthread_mutex_t* mutex)
923{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700924 /* We need to preserve the shared flag during operations */
925 int shared = mutex->value & MUTEX_SHARED_MASK;
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800926 /*
927 * The common case is an unlocked mutex, so we begin by trying to
928 * change the lock's state from 0 to 1. __atomic_cmpxchg() returns 0
929 * if it made the swap successfully. If the result is nonzero, this
930 * lock is already held by another thread.
931 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700932 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value ) != 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800933 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800934 * We want to go to sleep until the mutex is available, which
935 * requires promoting it to state 2. We need to swap in the new
936 * state value and then wait until somebody wakes us up.
937 *
938 * __atomic_swap() returns the previous value. We swap 2 in and
939 * see if we got zero back; if so, we have acquired the lock. If
940 * not, another thread still holds the lock and we wait again.
941 *
942 * The second argument to the __futex_wait() call is compared
943 * against the current value. If it doesn't match, __futex_wait()
944 * returns immediately (otherwise, it sleeps for a time specified
945 * by the third argument; 0 means sleep forever). This ensures
946 * that the mutex is in state 2 when we go to sleep on it, which
947 * guarantees a wake-up call.
948 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700949 while (__atomic_swap(shared|2, &mutex->value ) != (shared|0))
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -0700950 __futex_wait_ex(&mutex->value, shared, shared|2, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800951 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700952 ANDROID_MEMBAR_FULL();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800953}
954
955/*
956 * Release a non-recursive mutex. The caller is responsible for determining
957 * that we are in fact the owner of this lock.
958 */
959static __inline__ void
960_normal_unlock(pthread_mutex_t* mutex)
961{
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700962 ANDROID_MEMBAR_FULL();
963
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700964 /* We need to preserve the shared flag during operations */
965 int shared = mutex->value & MUTEX_SHARED_MASK;
966
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800967 /*
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700968 * The mutex state will be 1 or (rarely) 2. We use an atomic decrement
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800969 * to release the lock. __atomic_dec() returns the previous value;
970 * if it wasn't 1 we have to do some additional work.
971 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700972 if (__atomic_dec(&mutex->value) != (shared|1)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800973 /*
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800974 * Start by releasing the lock. The decrement changed it from
975 * "contended lock" to "uncontended lock", which means we still
976 * hold it, and anybody who tries to sneak in will push it back
977 * to state 2.
978 *
979 * Once we set it to zero the lock is up for grabs. We follow
980 * this with a __futex_wake() to ensure that one of the waiting
981 * threads has a chance to grab it.
982 *
983 * This doesn't cause a race with the swap/wait pair in
984 * _normal_lock(), because the __futex_wait() call there will
985 * return immediately if the mutex value isn't 2.
986 */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700987 mutex->value = shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800988
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800989 /*
990 * Wake up one waiting thread. We don't know which thread will be
991 * woken or when it'll start executing -- futexes make no guarantees
992 * here. There may not even be a thread waiting.
993 *
994 * The newly-woken thread will replace the 0 we just set above
995 * with 2, which means that when it eventually releases the mutex
996 * it will also call FUTEX_WAKE. This results in one extra wake
997 * call whenever a lock is contended, but lets us avoid forgetting
998 * anyone without requiring us to track the number of sleepers.
999 *
1000 * It's possible for another thread to sneak in and grab the lock
1001 * between the zero assignment above and the wake call below. If
1002 * the new thread is "slow" and holds the lock for a while, we'll
1003 * wake up a sleeper, which will swap in a 2 and then go back to
1004 * sleep since the lock is still held. If the new thread is "fast",
1005 * running to completion before we call wake, the thread we
1006 * eventually wake will find an unlocked mutex and will execute.
1007 * Either way we have correct behavior and nobody is orphaned on
1008 * the wait queue.
1009 */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001010 __futex_wake_ex(&mutex->value, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001011 }
1012}
1013
1014static pthread_mutex_t __recursive_lock = PTHREAD_MUTEX_INITIALIZER;
1015
1016static void
1017_recursive_lock(void)
1018{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001019 _normal_lock(&__recursive_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001020}
1021
1022static void
1023_recursive_unlock(void)
1024{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001025 _normal_unlock(&__recursive_lock );
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001026}
1027
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001028int pthread_mutex_lock(pthread_mutex_t *mutex)
1029{
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001030 int mtype, tid, new_lock_type, shared;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001031
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001032 if (__unlikely(mutex == NULL))
1033 return EINVAL;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001034
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001035 mtype = (mutex->value & MUTEX_TYPE_MASK);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001036 shared = (mutex->value & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001037
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001038 /* Handle normal case first */
1039 if ( __likely(mtype == MUTEX_TYPE_NORMAL) ) {
1040 _normal_lock(mutex);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001041 return 0;
1042 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001043
1044 /* Do we already own this recursive or error-check mutex ? */
1045 tid = __get_thread()->kernel_id;
1046 if ( tid == MUTEX_OWNER(mutex) )
1047 {
1048 int oldv, counter;
1049
1050 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1051 /* trying to re-lock a mutex we already acquired */
1052 return EDEADLK;
1053 }
1054 /*
1055 * We own the mutex, but other threads are able to change
1056 * the contents (e.g. promoting it to "contended"), so we
1057 * need to hold the global lock.
1058 */
1059 _recursive_lock();
1060 oldv = mutex->value;
1061 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1062 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1063 _recursive_unlock();
1064 return 0;
1065 }
1066
1067 /* We don't own the mutex, so try to get it.
1068 *
1069 * First, we try to change its state from 0 to 1, if this
1070 * doesn't work, try to change it to state 2.
1071 */
1072 new_lock_type = 1;
1073
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001074 /* compute futex wait opcode and restore shared flag in mtype */
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001075 mtype |= shared;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001076
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001077 for (;;) {
1078 int oldv;
1079
1080 _recursive_lock();
1081 oldv = mutex->value;
1082 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1083 mutex->value = ((tid << 16) | mtype | new_lock_type);
1084 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1085 oldv ^= 3;
1086 mutex->value = oldv;
1087 }
1088 _recursive_unlock();
1089
1090 if (oldv == mtype)
1091 break;
1092
1093 /*
1094 * The lock was held, possibly contended by others. From
1095 * now on, if we manage to acquire the lock, we have to
1096 * assume that others are still contending for it so that
1097 * we'll wake them when we unlock it.
1098 */
1099 new_lock_type = 2;
1100
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001101 __futex_wait_ex(&mutex->value, shared, oldv, NULL);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001102 }
1103 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001104}
1105
1106
1107int pthread_mutex_unlock(pthread_mutex_t *mutex)
1108{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001109 int mtype, tid, oldv, shared;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001110
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001111 if (__unlikely(mutex == NULL))
1112 return EINVAL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001113
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001114 mtype = (mutex->value & MUTEX_TYPE_MASK);
1115 shared = (mutex->value & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001116
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001117 /* Handle common case first */
1118 if (__likely(mtype == MUTEX_TYPE_NORMAL)) {
1119 _normal_unlock(mutex);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001120 return 0;
1121 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001122
1123 /* Do we already own this recursive or error-check mutex ? */
1124 tid = __get_thread()->kernel_id;
1125 if ( tid != MUTEX_OWNER(mutex) )
1126 return EPERM;
1127
1128 /* We do, decrement counter or release the mutex if it is 0 */
1129 _recursive_lock();
1130 oldv = mutex->value;
1131 if (oldv & MUTEX_COUNTER_MASK) {
1132 mutex->value = oldv - (1 << MUTEX_COUNTER_SHIFT);
1133 oldv = 0;
1134 } else {
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001135 mutex->value = shared | mtype;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001136 }
1137 _recursive_unlock();
1138
1139 /* Wake one waiting thread, if any */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001140 if ((oldv & 3) == 2) {
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001141 __futex_wake_ex(&mutex->value, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001142 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001143 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001144}
1145
1146
1147int pthread_mutex_trylock(pthread_mutex_t *mutex)
1148{
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001149 int mtype, tid, oldv, shared;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001150
1151 if (__unlikely(mutex == NULL))
1152 return EINVAL;
1153
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001154 mtype = (mutex->value & MUTEX_TYPE_MASK);
1155 shared = (mutex->value & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001156
1157 /* Handle common case first */
1158 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001159 {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001160 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
1161 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001162 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001163 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001164
1165 return EBUSY;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001166 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001167
1168 /* Do we already own this recursive or error-check mutex ? */
1169 tid = __get_thread()->kernel_id;
1170 if ( tid == MUTEX_OWNER(mutex) )
1171 {
1172 int counter;
1173
1174 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1175 /* already locked by ourselves */
1176 return EDEADLK;
1177 }
1178
1179 _recursive_lock();
1180 oldv = mutex->value;
1181 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1182 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1183 _recursive_unlock();
1184 return 0;
1185 }
1186
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001187 /* Restore sharing bit in mtype */
1188 mtype |= shared;
1189
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001190 /* Try to lock it, just once. */
1191 _recursive_lock();
1192 oldv = mutex->value;
1193 if (oldv == mtype) /* uncontended released lock => state 1 */
1194 mutex->value = ((tid << 16) | mtype | 1);
1195 _recursive_unlock();
1196
1197 if (oldv != mtype)
1198 return EBUSY;
1199
1200 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001201}
1202
1203
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001204/* initialize 'ts' with the difference between 'abstime' and the current time
1205 * according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
1206 */
1207static int
1208__timespec_to_absolute(struct timespec* ts, const struct timespec* abstime, clockid_t clock)
1209{
1210 clock_gettime(clock, ts);
1211 ts->tv_sec = abstime->tv_sec - ts->tv_sec;
1212 ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;
1213 if (ts->tv_nsec < 0) {
1214 ts->tv_sec--;
1215 ts->tv_nsec += 1000000000;
1216 }
David 'Digit' Turnerbc10cd22009-09-23 15:56:50 -07001217 if ((ts->tv_nsec < 0) || (ts->tv_sec < 0))
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001218 return -1;
1219
1220 return 0;
1221}
1222
1223/* initialize 'abstime' to the current time according to 'clock' plus 'msecs'
1224 * milliseconds.
1225 */
1226static void
1227__timespec_to_relative_msec(struct timespec* abstime, unsigned msecs, clockid_t clock)
1228{
1229 clock_gettime(clock, abstime);
1230 abstime->tv_sec += msecs/1000;
1231 abstime->tv_nsec += (msecs%1000)*1000000;
1232 if (abstime->tv_nsec >= 1000000000) {
1233 abstime->tv_sec++;
1234 abstime->tv_nsec -= 1000000000;
1235 }
1236}
1237
1238int pthread_mutex_lock_timeout_np(pthread_mutex_t *mutex, unsigned msecs)
1239{
1240 clockid_t clock = CLOCK_MONOTONIC;
1241 struct timespec abstime;
1242 struct timespec ts;
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001243 int mtype, tid, oldv, new_lock_type, shared;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001244
1245 /* compute absolute expiration time */
1246 __timespec_to_relative_msec(&abstime, msecs, clock);
1247
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001248 if (__unlikely(mutex == NULL))
1249 return EINVAL;
1250
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001251 mtype = (mutex->value & MUTEX_TYPE_MASK);
1252 shared = (mutex->value & MUTEX_SHARED_MASK);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001253
1254 /* Handle common case first */
1255 if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001256 {
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001257 /* fast path for uncontended lock */
1258 if (__atomic_cmpxchg(shared|0, shared|1, &mutex->value) == 0) {
1259 ANDROID_MEMBAR_FULL();
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001260 return 0;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001261 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001262
1263 /* loop while needed */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001264 while (__atomic_swap(shared|2, &mutex->value) != (shared|0)) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001265 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1266 return EBUSY;
1267
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001268 __futex_wait_ex(&mutex->value, shared, shared|2, &ts);
Fabrice Di Meglio86418332010-03-11 14:47:47 -08001269 }
Andy McFaddenfcd00eb2010-05-28 13:31:45 -07001270 ANDROID_MEMBAR_FULL();
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001271 return 0;
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -08001272 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001273
1274 /* Do we already own this recursive or error-check mutex ? */
1275 tid = __get_thread()->kernel_id;
1276 if ( tid == MUTEX_OWNER(mutex) )
1277 {
1278 int oldv, counter;
1279
1280 if (mtype == MUTEX_TYPE_ERRORCHECK) {
1281 /* already locked by ourselves */
1282 return EDEADLK;
1283 }
1284
1285 _recursive_lock();
1286 oldv = mutex->value;
1287 counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
1288 mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
1289 _recursive_unlock();
1290 return 0;
1291 }
1292
1293 /* We don't own the mutex, so try to get it.
1294 *
1295 * First, we try to change its state from 0 to 1, if this
1296 * doesn't work, try to change it to state 2.
1297 */
1298 new_lock_type = 1;
1299
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001300 /* Compute wait op and restore sharing bit in mtype */
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -07001301 mtype |= shared;
1302
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001303 for (;;) {
1304 int oldv;
1305 struct timespec ts;
1306
1307 _recursive_lock();
1308 oldv = mutex->value;
1309 if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
1310 mutex->value = ((tid << 16) | mtype | new_lock_type);
1311 } else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
1312 oldv ^= 3;
1313 mutex->value = oldv;
1314 }
1315 _recursive_unlock();
1316
1317 if (oldv == mtype)
1318 break;
1319
1320 /*
1321 * The lock was held, possibly contended by others. From
1322 * now on, if we manage to acquire the lock, we have to
1323 * assume that others are still contending for it so that
1324 * we'll wake them when we unlock it.
1325 */
1326 new_lock_type = 2;
1327
1328 if (__timespec_to_absolute(&ts, &abstime, clock) < 0)
1329 return EBUSY;
1330
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001331 __futex_wait_ex(&mutex->value, shared, oldv, &ts);
David 'Digit' Turner40e6b822010-03-17 11:25:46 -07001332 }
1333 return 0;
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001334}
1335
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001336int pthread_condattr_init(pthread_condattr_t *attr)
1337{
1338 if (attr == NULL)
1339 return EINVAL;
1340
1341 *attr = PTHREAD_PROCESS_PRIVATE;
1342 return 0;
1343}
1344
1345int pthread_condattr_getpshared(pthread_condattr_t *attr, int *pshared)
1346{
1347 if (attr == NULL || pshared == NULL)
1348 return EINVAL;
1349
1350 *pshared = *attr;
1351 return 0;
1352}
1353
1354int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
1355{
1356 if (attr == NULL)
1357 return EINVAL;
1358
1359 if (pshared != PTHREAD_PROCESS_SHARED &&
1360 pshared != PTHREAD_PROCESS_PRIVATE)
1361 return EINVAL;
1362
1363 *attr = pshared;
1364 return 0;
1365}
1366
1367int pthread_condattr_destroy(pthread_condattr_t *attr)
1368{
1369 if (attr == NULL)
1370 return EINVAL;
1371
1372 *attr = 0xdeada11d;
1373 return 0;
1374}
1375
1376/* We use one bit in condition variable values as the 'shared' flag
1377 * The rest is a counter.
1378 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001379#define COND_SHARED_MASK 0x0001
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001380#define COND_COUNTER_INCREMENT 0x0002
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001381#define COND_COUNTER_MASK (~COND_SHARED_MASK)
1382
1383#define COND_IS_SHARED(c) (((c)->value & COND_SHARED_MASK) != 0)
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001384
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001385/* XXX *technically* there is a race condition that could allow
1386 * XXX a signal to be missed. If thread A is preempted in _wait()
1387 * XXX after unlocking the mutex and before waiting, and if other
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001388 * XXX threads call signal or broadcast UINT_MAX/2 times (exactly),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001389 * XXX before thread A is scheduled again and calls futex_wait(),
1390 * XXX then the signal will be lost.
1391 */
1392
1393int pthread_cond_init(pthread_cond_t *cond,
1394 const pthread_condattr_t *attr)
1395{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001396 if (cond == NULL)
1397 return EINVAL;
1398
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001399 cond->value = 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001400
1401 if (attr != NULL && *attr == PTHREAD_PROCESS_SHARED)
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001402 cond->value |= COND_SHARED_MASK;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001403
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001404 return 0;
1405}
1406
1407int pthread_cond_destroy(pthread_cond_t *cond)
1408{
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001409 if (cond == NULL)
1410 return EINVAL;
1411
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001412 cond->value = 0xdeadc04d;
1413 return 0;
1414}
1415
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001416/* This function is used by pthread_cond_broadcast and
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001417 * pthread_cond_signal to atomically decrement the counter
1418 * then wake-up 'counter' threads.
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001419 */
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001420static int
1421__pthread_cond_pulse(pthread_cond_t *cond, int counter)
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001422{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001423 long flags;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001424
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001425 if (__unlikely(cond == NULL))
1426 return EINVAL;
1427
1428 flags = (cond->value & ~COND_COUNTER_MASK);
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001429 for (;;) {
1430 long oldval = cond->value;
1431 long newval = ((oldval - COND_COUNTER_INCREMENT) & COND_COUNTER_MASK)
1432 | flags;
1433 if (__atomic_cmpxchg(oldval, newval, &cond->value) == 0)
1434 break;
1435 }
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001436
Andy McFaddene2ac8982010-09-02 13:34:53 -07001437 /*
1438 * Ensure that all memory accesses previously made by this thread are
1439 * visible to the woken thread(s). On the other side, the "wait"
1440 * code will issue any necessary barriers when locking the mutex.
1441 *
1442 * This may not strictly be necessary -- if the caller follows
1443 * recommended practice and holds the mutex before signaling the cond
1444 * var, the mutex ops will provide correct semantics. If they don't
1445 * hold the mutex, they're subject to race conditions anyway.
1446 */
1447 ANDROID_MEMBAR_FULL();
1448
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001449 __futex_wake_ex(&cond->value, COND_IS_SHARED(cond), counter);
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001450 return 0;
David 'Digit' Turneree7b0772010-03-18 14:07:42 -07001451}
1452
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001453int pthread_cond_broadcast(pthread_cond_t *cond)
1454{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001455 return __pthread_cond_pulse(cond, INT_MAX);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001456}
1457
1458int pthread_cond_signal(pthread_cond_t *cond)
1459{
David 'Digit' Turnerb5e4a412010-03-19 17:59:23 -07001460 return __pthread_cond_pulse(cond, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001461}
1462
1463int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
1464{
1465 return pthread_cond_timedwait(cond, mutex, NULL);
1466}
1467
1468int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
1469 pthread_mutex_t * mutex,
1470 const struct timespec *reltime)
1471{
1472 int status;
1473 int oldvalue = cond->value;
1474
1475 pthread_mutex_unlock(mutex);
David 'Digit' Turner6304d8b2010-06-02 18:12:12 -07001476 status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond), oldvalue, reltime);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001477 pthread_mutex_lock(mutex);
1478
1479 if (status == (-ETIMEDOUT)) return ETIMEDOUT;
1480 return 0;
1481}
1482
1483int __pthread_cond_timedwait(pthread_cond_t *cond,
1484 pthread_mutex_t * mutex,
1485 const struct timespec *abstime,
1486 clockid_t clock)
1487{
1488 struct timespec ts;
1489 struct timespec * tsp;
1490
1491 if (abstime != NULL) {
David 'Digit' Turner3f56b7f2009-09-22 12:40:22 -07001492 if (__timespec_to_absolute(&ts, abstime, clock) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001493 return ETIMEDOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001494 tsp = &ts;
1495 } else {
1496 tsp = NULL;
1497 }
1498
1499 return __pthread_cond_timedwait_relative(cond, mutex, tsp);
1500}
1501
1502int pthread_cond_timedwait(pthread_cond_t *cond,
1503 pthread_mutex_t * mutex,
1504 const struct timespec *abstime)
1505{
1506 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
1507}
1508
1509
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001510/* this one exists only for backward binary compatibility */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001511int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
1512 pthread_mutex_t * mutex,
1513 const struct timespec *abstime)
1514{
1515 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1516}
1517
Mathias Agopiana2f5e212009-07-13 15:00:46 -07001518int pthread_cond_timedwait_monotonic_np(pthread_cond_t *cond,
1519 pthread_mutex_t * mutex,
1520 const struct timespec *abstime)
1521{
1522 return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
1523}
1524
1525int pthread_cond_timedwait_relative_np(pthread_cond_t *cond,
1526 pthread_mutex_t * mutex,
1527 const struct timespec *reltime)
1528{
1529 return __pthread_cond_timedwait_relative(cond, mutex, reltime);
1530}
1531
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001532int pthread_cond_timeout_np(pthread_cond_t *cond,
1533 pthread_mutex_t * mutex,
1534 unsigned msecs)
1535{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001536 struct timespec ts;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001537
1538 ts.tv_sec = msecs / 1000;
1539 ts.tv_nsec = (msecs % 1000) * 1000000;
1540
Matthieu CASTETa4e67f42008-12-27 00:04:10 +01001541 return __pthread_cond_timedwait_relative(cond, mutex, &ts);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001542}
1543
1544
1545
1546/* A technical note regarding our thread-local-storage (TLS) implementation:
1547 *
1548 * There can be up to TLSMAP_SIZE independent TLS keys in a given process,
1549 * though the first TLSMAP_START keys are reserved for Bionic to hold
1550 * special thread-specific variables like errno or a pointer to
1551 * the current thread's descriptor.
1552 *
1553 * while stored in the TLS area, these entries cannot be accessed through
1554 * pthread_getspecific() / pthread_setspecific() and pthread_key_delete()
1555 *
1556 * also, some entries in the key table are pre-allocated (see tlsmap_lock)
1557 * to greatly simplify and speedup some OpenGL-related operations. though the
1558 * initialy value will be NULL on all threads.
1559 *
1560 * you can use pthread_getspecific()/setspecific() on these, and in theory
1561 * you could also call pthread_key_delete() as well, though this would
1562 * probably break some apps.
1563 *
1564 * The 'tlsmap_t' type defined below implements a shared global map of
1565 * currently created/allocated TLS keys and the destructors associated
1566 * with them. You should use tlsmap_lock/unlock to access it to avoid
1567 * any race condition.
1568 *
1569 * the global TLS map simply contains a bitmap of allocated keys, and
1570 * an array of destructors.
1571 *
1572 * each thread has a TLS area that is a simple array of TLSMAP_SIZE void*
1573 * pointers. the TLS area of the main thread is stack-allocated in
1574 * __libc_init_common, while the TLS area of other threads is placed at
1575 * the top of their stack in pthread_create.
1576 *
1577 * when pthread_key_create() is called, it finds the first free key in the
1578 * bitmap, then set it to 1, saving the destructor altogether
1579 *
1580 * when pthread_key_delete() is called. it will erase the key's bitmap bit
1581 * and its destructor, and will also clear the key data in the TLS area of
1582 * all created threads. As mandated by Posix, it is the responsability of
1583 * the caller of pthread_key_delete() to properly reclaim the objects that
1584 * were pointed to by these data fields (either before or after the call).
1585 *
1586 */
1587
1588/* TLS Map implementation
1589 */
1590
1591#define TLSMAP_START (TLS_SLOT_MAX_WELL_KNOWN+1)
1592#define TLSMAP_SIZE BIONIC_TLS_SLOTS
1593#define TLSMAP_BITS 32
1594#define TLSMAP_WORDS ((TLSMAP_SIZE+TLSMAP_BITS-1)/TLSMAP_BITS)
1595#define TLSMAP_WORD(m,k) (m)->map[(k)/TLSMAP_BITS]
1596#define TLSMAP_MASK(k) (1U << ((k)&(TLSMAP_BITS-1)))
1597
1598/* this macro is used to quickly check that a key belongs to a reasonable range */
1599#define TLSMAP_VALIDATE_KEY(key) \
1600 ((key) >= TLSMAP_START && (key) < TLSMAP_SIZE)
1601
1602/* the type of tls key destructor functions */
1603typedef void (*tls_dtor_t)(void*);
1604
1605typedef struct {
1606 int init; /* see comment in tlsmap_lock() */
1607 uint32_t map[TLSMAP_WORDS]; /* bitmap of allocated keys */
1608 tls_dtor_t dtors[TLSMAP_SIZE]; /* key destructors */
1609} tlsmap_t;
1610
1611static pthread_mutex_t _tlsmap_lock = PTHREAD_MUTEX_INITIALIZER;
1612static tlsmap_t _tlsmap;
1613
1614/* lock the global TLS map lock and return a handle to it */
1615static __inline__ tlsmap_t* tlsmap_lock(void)
1616{
1617 tlsmap_t* m = &_tlsmap;
1618
1619 pthread_mutex_lock(&_tlsmap_lock);
1620 /* we need to initialize the first entry of the 'map' array
1621 * with the value TLS_DEFAULT_ALLOC_MAP. doing it statically
1622 * when declaring _tlsmap is a bit awkward and is going to
1623 * produce warnings, so do it the first time we use the map
1624 * instead
1625 */
1626 if (__unlikely(!m->init)) {
1627 TLSMAP_WORD(m,0) = TLS_DEFAULT_ALLOC_MAP;
1628 m->init = 1;
1629 }
1630 return m;
1631}
1632
1633/* unlock the global TLS map */
1634static __inline__ void tlsmap_unlock(tlsmap_t* m)
1635{
1636 pthread_mutex_unlock(&_tlsmap_lock);
1637 (void)m; /* a good compiler is a happy compiler */
1638}
1639
1640/* test to see wether a key is allocated */
1641static __inline__ int tlsmap_test(tlsmap_t* m, int key)
1642{
1643 return (TLSMAP_WORD(m,key) & TLSMAP_MASK(key)) != 0;
1644}
1645
1646/* set the destructor and bit flag on a newly allocated key */
1647static __inline__ void tlsmap_set(tlsmap_t* m, int key, tls_dtor_t dtor)
1648{
1649 TLSMAP_WORD(m,key) |= TLSMAP_MASK(key);
1650 m->dtors[key] = dtor;
1651}
1652
1653/* clear the destructor and bit flag on an existing key */
1654static __inline__ void tlsmap_clear(tlsmap_t* m, int key)
1655{
1656 TLSMAP_WORD(m,key) &= ~TLSMAP_MASK(key);
1657 m->dtors[key] = NULL;
1658}
1659
1660/* allocate a new TLS key, return -1 if no room left */
1661static int tlsmap_alloc(tlsmap_t* m, tls_dtor_t dtor)
1662{
1663 int key;
1664
1665 for ( key = TLSMAP_START; key < TLSMAP_SIZE; key++ ) {
1666 if ( !tlsmap_test(m, key) ) {
1667 tlsmap_set(m, key, dtor);
1668 return key;
1669 }
1670 }
1671 return -1;
1672}
1673
1674
1675int pthread_key_create(pthread_key_t *key, void (*destructor_function)(void *))
1676{
1677 uint32_t err = ENOMEM;
1678 tlsmap_t* map = tlsmap_lock();
1679 int k = tlsmap_alloc(map, destructor_function);
1680
1681 if (k >= 0) {
1682 *key = k;
1683 err = 0;
1684 }
1685 tlsmap_unlock(map);
1686 return err;
1687}
1688
1689
1690/* This deletes a pthread_key_t. note that the standard mandates that this does
1691 * not call the destructor of non-NULL key values. Instead, it is the
1692 * responsability of the caller to properly dispose of the corresponding data
1693 * and resources, using any mean it finds suitable.
1694 *
1695 * On the other hand, this function will clear the corresponding key data
1696 * values in all known threads. this prevents later (invalid) calls to
1697 * pthread_getspecific() to receive invalid/stale values.
1698 */
1699int pthread_key_delete(pthread_key_t key)
1700{
1701 uint32_t err;
1702 pthread_internal_t* thr;
1703 tlsmap_t* map;
1704
1705 if (!TLSMAP_VALIDATE_KEY(key)) {
1706 return EINVAL;
1707 }
1708
1709 map = tlsmap_lock();
1710
1711 if (!tlsmap_test(map, key)) {
1712 err = EINVAL;
1713 goto err1;
1714 }
1715
1716 /* clear value in all threads */
1717 pthread_mutex_lock(&gThreadListLock);
1718 for ( thr = gThreadList; thr != NULL; thr = thr->next ) {
1719 /* avoid zombie threads with a negative 'join_count'. these are really
1720 * already dead and don't have a TLS area anymore.
1721 *
1722 * similarly, it is possible to have thr->tls == NULL for threads that
1723 * were just recently created through pthread_create() but whose
1724 * startup trampoline (__thread_entry) hasn't been run yet by the
1725 * scheduler. so check for this too.
1726 */
1727 if (thr->join_count < 0 || !thr->tls)
1728 continue;
1729
1730 thr->tls[key] = NULL;
1731 }
1732 tlsmap_clear(map, key);
1733
1734 pthread_mutex_unlock(&gThreadListLock);
1735 err = 0;
1736
1737err1:
1738 tlsmap_unlock(map);
1739 return err;
1740}
1741
1742
1743int pthread_setspecific(pthread_key_t key, const void *ptr)
1744{
1745 int err = EINVAL;
1746 tlsmap_t* map;
1747
1748 if (TLSMAP_VALIDATE_KEY(key)) {
1749 /* check that we're trying to set data for an allocated key */
1750 map = tlsmap_lock();
1751 if (tlsmap_test(map, key)) {
1752 ((uint32_t *)__get_tls())[key] = (uint32_t)ptr;
1753 err = 0;
1754 }
1755 tlsmap_unlock(map);
1756 }
1757 return err;
1758}
1759
1760void * pthread_getspecific(pthread_key_t key)
1761{
1762 if (!TLSMAP_VALIDATE_KEY(key)) {
1763 return NULL;
1764 }
1765
1766 /* for performance reason, we do not lock/unlock the global TLS map
1767 * to check that the key is properly allocated. if the key was not
1768 * allocated, the value read from the TLS should always be NULL
1769 * due to pthread_key_delete() clearing the values for all threads.
1770 */
1771 return (void *)(((unsigned *)__get_tls())[key]);
1772}
1773
1774/* Posix mandates that this be defined in <limits.h> but we don't have
1775 * it just yet.
1776 */
1777#ifndef PTHREAD_DESTRUCTOR_ITERATIONS
1778# define PTHREAD_DESTRUCTOR_ITERATIONS 4
1779#endif
1780
1781/* this function is called from pthread_exit() to remove all TLS key data
1782 * from this thread's TLS area. this must call the destructor of all keys
1783 * that have a non-NULL data value (and a non-NULL destructor).
1784 *
1785 * because destructors can do funky things like deleting/creating other
1786 * keys, we need to implement this in a loop
1787 */
1788static void pthread_key_clean_all(void)
1789{
1790 tlsmap_t* map;
1791 void** tls = (void**)__get_tls();
1792 int rounds = PTHREAD_DESTRUCTOR_ITERATIONS;
1793
1794 map = tlsmap_lock();
1795
1796 for (rounds = PTHREAD_DESTRUCTOR_ITERATIONS; rounds > 0; rounds--)
1797 {
1798 int kk, count = 0;
1799
1800 for (kk = TLSMAP_START; kk < TLSMAP_SIZE; kk++) {
1801 if ( tlsmap_test(map, kk) )
1802 {
1803 void* data = tls[kk];
1804 tls_dtor_t dtor = map->dtors[kk];
1805
1806 if (data != NULL && dtor != NULL)
1807 {
1808 /* we need to clear the key data now, this will prevent the
1809 * destructor (or a later one) from seeing the old value if
1810 * it calls pthread_getspecific() for some odd reason
1811 *
1812 * we do not do this if 'dtor == NULL' just in case another
1813 * destructor function might be responsible for manually
1814 * releasing the corresponding data.
1815 */
1816 tls[kk] = NULL;
1817
1818 /* because the destructor is free to call pthread_key_create
1819 * and/or pthread_key_delete, we need to temporarily unlock
1820 * the TLS map
1821 */
1822 tlsmap_unlock(map);
1823 (*dtor)(data);
1824 map = tlsmap_lock();
1825
1826 count += 1;
1827 }
1828 }
1829 }
1830
1831 /* if we didn't call any destructor, there is no need to check the
1832 * TLS data again
1833 */
1834 if (count == 0)
1835 break;
1836 }
1837 tlsmap_unlock(map);
1838}
1839
1840// man says this should be in <linux/unistd.h>, but it isn't
1841extern int tkill(int tid, int sig);
1842
1843int pthread_kill(pthread_t tid, int sig)
1844{
1845 int ret;
1846 int old_errno = errno;
1847 pthread_internal_t * thread = (pthread_internal_t *)tid;
1848
1849 ret = tkill(thread->kernel_id, sig);
1850 if (ret < 0) {
1851 ret = errno;
1852 errno = old_errno;
1853 }
1854
1855 return ret;
1856}
1857
1858extern int __rt_sigprocmask(int, const sigset_t *, sigset_t *, size_t);
1859
1860int pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
1861{
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001862 /* pthread_sigmask must return the error code, but the syscall
1863 * will set errno instead and return 0/-1
1864 */
1865 int ret, old_errno = errno;
1866
David 'Digit' Turner5c8c00a2010-12-20 15:58:06 +01001867 /* Use NSIG which corresponds to the number of signals in
1868 * our 32-bit sigset_t implementation. As such, this function, or
1869 * anything that deals with sigset_t cannot manage real-time signals
1870 * (signo >= 32). We might want to introduce sigset_rt_t as an
1871 * extension to do so in the future.
1872 */
1873 ret = __rt_sigprocmask(how, set, oset, NSIG / 8);
David 'Digit' Turner8f8b5312010-03-01 11:30:40 -08001874 if (ret < 0)
1875 ret = errno;
1876
1877 errno = old_errno;
1878 return ret;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001879}
1880
1881
1882int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
1883{
1884 const int CLOCK_IDTYPE_BITS = 3;
1885 pthread_internal_t* thread = (pthread_internal_t*)tid;
1886
1887 if (!thread)
1888 return ESRCH;
1889
1890 *clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
1891 return 0;
1892}
1893
1894
1895/* NOTE: this implementation doesn't support a init function that throws a C++ exception
1896 * or calls fork()
1897 */
1898int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
1899{
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001900 static pthread_mutex_t once_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001901 volatile pthread_once_t* ocptr = once_control;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001902
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001903 pthread_once_t tmp = *ocptr;
1904 ANDROID_MEMBAR_FULL();
1905 if (tmp == PTHREAD_ONCE_INIT) {
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001906 pthread_mutex_lock( &once_lock );
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001907 if (*ocptr == PTHREAD_ONCE_INIT) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001908 (*init_routine)();
Andy McFaddenb1c9cc22010-09-23 12:30:12 -07001909 ANDROID_MEMBAR_FULL();
1910 *ocptr = ~PTHREAD_ONCE_INIT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001911 }
Wink Savilleccc3d1e2010-06-28 11:41:16 -07001912 pthread_mutex_unlock( &once_lock );
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001913 }
1914 return 0;
1915}
André Goddard Rosa78c1c042010-05-19 23:17:16 -03001916
1917/* This value is not exported by kernel headers, so hardcode it here */
1918#define MAX_TASK_COMM_LEN 16
1919#define TASK_COMM_FMT "/proc/self/task/%u/comm"
1920
1921int pthread_setname_np(pthread_t thid, const char *thname)
1922{
1923 size_t thname_len;
1924 int saved_errno, ret;
1925
1926 if (thid == 0 || thname == NULL)
1927 return EINVAL;
1928
1929 thname_len = strlen(thname);
1930 if (thname_len >= MAX_TASK_COMM_LEN)
1931 return ERANGE;
1932
1933 saved_errno = errno;
1934 if (thid == pthread_self())
1935 {
1936 ret = prctl(PR_SET_NAME, (unsigned long)thname, 0, 0, 0) ? errno : 0;
1937 }
1938 else
1939 {
1940 /* Have to change another thread's name */
1941 pthread_internal_t *thread = (pthread_internal_t *)thid;
1942 char comm_name[sizeof(TASK_COMM_FMT) + 8];
1943 ssize_t n;
1944 int fd;
1945
1946 snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, (unsigned int)thread->kernel_id);
1947 fd = open(comm_name, O_RDWR);
1948 if (fd == -1)
1949 {
1950 ret = errno;
1951 goto exit;
1952 }
1953 n = TEMP_FAILURE_RETRY(write(fd, thname, thname_len));
1954 close(fd);
1955
1956 if (n < 0)
1957 ret = errno;
1958 else if ((size_t)n != thname_len)
1959 ret = EIO;
1960 else
1961 ret = 0;
1962 }
1963exit:
1964 errno = saved_errno;
1965 return ret;
1966}