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