fix possible failure-to-wake deadlock with robust mutexes
[musl] / src / thread / pthread_mutex_trylock.c
1 #include "pthread_impl.h"
2
3 int __pthread_mutex_trylock_owner(pthread_mutex_t *m)
4 {
5         int old, own;
6         int type = m->_m_type & 15;
7         pthread_t self = __pthread_self();
8         int tid = self->tid;
9
10         if (!self->robust_list.off) {
11                 __syscall(SYS_set_robust_list, &self->robust_list, 3*sizeof(long));
12                 self->robust_list.head = &self->robust_list.head;
13                 self->robust_list.off = (char*)&m->_m_lock-(char *)&m->_m_next;
14         }
15
16         old = m->_m_lock;
17         own = old & 0x7fffffff;
18         if (own == tid && (type&3) == PTHREAD_MUTEX_RECURSIVE) {
19                 if ((unsigned)m->_m_count >= INT_MAX) return EAGAIN;
20                 m->_m_count++;
21                 return 0;
22         }
23         if (own == 0x40000000) return ENOTRECOVERABLE;
24
25         if (m->_m_type & 128) {
26                 if (m->_m_waiters) tid |= 0x80000000;
27                 self->robust_list.pending = &m->_m_next;
28         }
29
30         if ((own && (!(own & 0x40000000) || !(type & 4)))
31             || a_cas(&m->_m_lock, old, tid) != old) {
32                 self->robust_list.pending = 0;
33                 return EBUSY;
34         }
35
36         volatile void *next = self->robust_list.head;
37         m->_m_next = next;
38         m->_m_prev = &self->robust_list.head;
39         if (next != &self->robust_list.head) *(volatile void *volatile *)
40                 ((char *)next - sizeof(void *)) = &m->_m_next;
41         self->robust_list.head = &m->_m_next;
42         self->robust_list.pending = 0;
43
44         if (own) {
45                 m->_m_count = 0;
46                 m->_m_type |= 8;
47                 return EOWNERDEAD;
48         }
49
50         return 0;
51 }
52
53 int pthread_mutex_trylock(pthread_mutex_t *m)
54 {
55         if ((m->_m_type&15) == PTHREAD_MUTEX_NORMAL)
56                 return a_cas(&m->_m_lock, 0, EBUSY) & EBUSY;
57         return __pthread_mutex_trylock_owner(m);
58 }