clean up access to mutex type in pthread_mutex_trylock
[musl.git] / src / thread / pthread_mutex_trylock.c
blob29622ff9b0350ef6e704fe7a2ff728f90928c9ed
1 #include "pthread_impl.h"
3 int __pthread_mutex_trylock_owner(pthread_mutex_t *m)
5 int old, own;
6 int type = m->_m_type;
7 pthread_t self = __pthread_self();
8 int tid = self->tid;
10 old = m->_m_lock;
11 own = old & 0x3fffffff;
12 if (own == tid && (type&3) == PTHREAD_MUTEX_RECURSIVE) {
13 if ((unsigned)m->_m_count >= INT_MAX) return EAGAIN;
14 m->_m_count++;
15 return 0;
17 if (own == 0x3fffffff) return ENOTRECOVERABLE;
18 if (own || (old && !(type & 4))) return EBUSY;
20 if (type & 128) {
21 if (!self->robust_list.off) {
22 self->robust_list.off = (char*)&m->_m_lock-(char *)&m->_m_next;
23 __syscall(SYS_set_robust_list, &self->robust_list, 3*sizeof(long));
25 if (m->_m_waiters) tid |= 0x80000000;
26 self->robust_list.pending = &m->_m_next;
28 tid |= old & 0x40000000;
30 if (a_cas(&m->_m_lock, old, tid) != old) {
31 self->robust_list.pending = 0;
32 return EBUSY;
35 volatile void *next = self->robust_list.head;
36 m->_m_next = next;
37 m->_m_prev = &self->robust_list.head;
38 if (next != &self->robust_list.head) *(volatile void *volatile *)
39 ((char *)next - sizeof(void *)) = &m->_m_next;
40 self->robust_list.head = &m->_m_next;
41 self->robust_list.pending = 0;
43 if (old) {
44 m->_m_count = 0;
45 return EOWNERDEAD;
48 return 0;
51 int __pthread_mutex_trylock(pthread_mutex_t *m)
53 if ((m->_m_type&15) == PTHREAD_MUTEX_NORMAL)
54 return a_cas(&m->_m_lock, 0, EBUSY) & EBUSY;
55 return __pthread_mutex_trylock_owner(m);
58 weak_alias(__pthread_mutex_trylock, pthread_mutex_trylock);