f871e9e0afdd35d48a60a5abc0786cf73525bfde
[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.off = (char*)&m->_m_lock-(char *)&m->_m_next;
13         }
14
15         old = m->_m_lock;
16         own = old & 0x7fffffff;
17         if (own == tid && (type&3) == PTHREAD_MUTEX_RECURSIVE) {
18                 if ((unsigned)m->_m_count >= INT_MAX) return EAGAIN;
19                 m->_m_count++;
20                 return 0;
21         }
22
23         self->robust_list.pending = &m->_m_next;
24
25         if ((own && (!(own & 0x40000000) || !(type & 4)))
26             || a_cas(&m->_m_lock, old, tid) != old) {
27                 self->robust_list.pending = 0;
28                 return EBUSY;
29         }
30
31         m->_m_next = self->robust_list.head;
32         m->_m_prev = &self->robust_list.head;
33         if (self->robust_list.head)
34                 self->robust_list.head[-1] = &m->_m_next;
35         self->robust_list.head = &m->_m_next;
36         self->robust_list.pending = 0;
37
38         if (type < 4) return 0;
39
40         if (type >= 8) {
41                 m->_m_lock = 0;
42                 return ENOTRECOVERABLE;
43         }
44
45         if (own) {
46                 m->_m_count = 0;
47                 m->_m_type += 8;
48                 return EOWNERDEAD;
49         }
50
51         return 0;
52 }
53
54 int pthread_mutex_trylock(pthread_mutex_t *m)
55 {
56         if ((m->_m_type&15) == PTHREAD_MUTEX_NORMAL)
57                 return a_cas(&m->_m_lock, 0, EBUSY) & EBUSY;
58         return __pthread_mutex_trylock_owner(m);
59 }