Debian Codegraph @

libc-top-half/musl/src/thread/pthread_mutex_trylock.c

raw
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;
7 pthread_t self = __pthread_self();
8 int tid = self->tid;
9
10 old = m->_m_lock;
11 own = old & 0x3fffffff;
12 if (own == tid) {
13 if ((type&8) && m->_m_count<0) {
14 old &= 0x40000000;
15 m->_m_count = 0;
16 goto success;
17 }
18 if ((type&3) == PTHREAD_MUTEX_RECURSIVE) {
19 if ((unsigned)m->_m_count >= INT_MAX) return EAGAIN;
20 m->_m_count++;
21 return 0;
22 }
23 }
24 #ifdef __wasilibc_unmodified_upstream
25 if (own == 0x3fffffff) return ENOTRECOVERABLE;
26 #endif
27 if (own || (old && !(type & 4))) return EBUSY;
28
29 if (type & 128) {
30 if (!self->robust_list.off) {
31 self->robust_list.off = (char*)&m->_m_lock-(char *)&m->_m_next;
32 #ifdef __wasilibc_unmodified_upstream
33 __syscall(SYS_set_robust_list, &self->robust_list, 3*sizeof(long));
34 #endif
35 }
36 if (m->_m_waiters) tid |= 0x80000000;
37 self->robust_list.pending = &m->_m_next;
38 }
39 tid |= old & 0x40000000;
40
41 if (a_cas(&m->_m_lock, old, tid) != old) {
42 self->robust_list.pending = 0;
43 if ((type&12)==12 && m->_m_waiters) return ENOTRECOVERABLE;
44 return EBUSY;
45 }
46
47 success:
48 if ((type&8) && m->_m_waiters) {
49 int priv = (type & 128) ^ 128;
50 #ifdef __wasilibc_unmodified_upstream
51 __syscall(SYS_futex, &m->_m_lock, FUTEX_UNLOCK_PI|priv);
52 #endif
53 self->robust_list.pending = 0;
54 return (type&4) ? ENOTRECOVERABLE : EBUSY;
55 }
56
57 volatile void *next = self->robust_list.head;
58 m->_m_next = next;
59 m->_m_prev = &self->robust_list.head;
60 if (next != &self->robust_list.head) *(volatile void *volatile *)
61 ((char *)next - sizeof(void *)) = &m->_m_next;
62 self->robust_list.head = &m->_m_next;
63 self->robust_list.pending = 0;
64
65 if (old) {
66 m->_m_count = 0;
67 return EOWNERDEAD;
68 }
69
70 return 0;
71 }
72
73 int __pthread_mutex_trylock(pthread_mutex_t *m)
74 {
75 if ((m->_m_type&15) == PTHREAD_MUTEX_NORMAL)
76 return a_cas(&m->_m_lock, 0, EBUSY) & EBUSY;
77 return __pthread_mutex_trylock_owner(m);
78 }
79
80 weak_alias(__pthread_mutex_trylock, pthread_mutex_trylock);