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