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