• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include "pthread_impl.h"
2 
__pthread_mutex_trylock_owner(pthread_mutex_t * m)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 #ifdef __LITEOS_A__
13 	if (own == tid) {
14 		if ((type&PTHREAD_MUTEX_TYPE_MASK) == PTHREAD_MUTEX_RECURSIVE) {
15 			if ((unsigned)m->_m_count >= INT_MAX) return EAGAIN;
16 			m->_m_count++;
17 			return 0;
18 		}
19 	}
20 #else
21 	if (__is_mutex_destroyed(m->_m_type))
22 		__handle_using_destroyed_mutex(m, __FUNCTION__);
23 	if (own == tid) {
24 		if ((type&8) && m->_m_count<0) {
25 			old &= 0x40000000;
26 			m->_m_count = 0;
27 			goto success;
28 		}
29 		if ((type&3) == PTHREAD_MUTEX_RECURSIVE) {
30 			if ((unsigned)m->_m_count >= INT_MAX) return EAGAIN;
31 			m->_m_count++;
32 			return 0;
33 		}
34 	}
35 #endif
36 	if (own == 0x3fffffff) return ENOTRECOVERABLE;
37 	if (own || (old && !(type & 4))) return EBUSY;
38 
39 	if (type & 128) {
40 		if (!self->robust_list.off) {
41 			self->robust_list.off = (char*)&m->_m_lock-(char *)&m->_m_next;
42 #ifndef __LITEOS_A__
43 			__syscall(SYS_set_robust_list, &self->robust_list, 3*sizeof(long));
44 #endif
45 		}
46 		if (m->_m_waiters) tid |= 0x80000000;
47 		self->robust_list.pending = &m->_m_next;
48 	}
49 	tid |= old & 0x40000000;
50 
51 	if (a_cas(&m->_m_lock, old, tid) != old) {
52 		self->robust_list.pending = 0;
53 #ifndef __LITEOS_A__
54 		if ((type&12)==12 && m->_m_waiters) return ENOTRECOVERABLE;
55 #endif
56 		return EBUSY;
57 	}
58 
59 #ifndef __LITEOS_A__
60 success:
61 	if ((type&8) && m->_m_waiters) {
62 		int priv = (type & 128) ^ 128;
63 		__syscall(SYS_futex, &m->_m_lock, FUTEX_UNLOCK_PI|priv);
64 		self->robust_list.pending = 0;
65 		return (type&4) ? ENOTRECOVERABLE : EBUSY;
66 	}
67 #endif
68 
69 	volatile void *next = self->robust_list.head;
70 	m->_m_next = next;
71 	m->_m_prev = &self->robust_list.head;
72 	if (next != &self->robust_list.head) *(volatile void *volatile *)
73 		((char *)next - sizeof(void *)) = &m->_m_next;
74 	self->robust_list.head = &m->_m_next;
75 	self->robust_list.pending = 0;
76 
77 	if (old) {
78 		m->_m_count = 0;
79 		return EOWNERDEAD;
80 	}
81 
82 	return 0;
83 }
84 
__pthread_mutex_trylock(pthread_mutex_t * m)85 int __pthread_mutex_trylock(pthread_mutex_t *m)
86 {
87 	if ((m->_m_type&15) == PTHREAD_MUTEX_NORMAL)
88 		return a_cas(&m->_m_lock, 0, EBUSY) & EBUSY;
89 	return __pthread_mutex_trylock_owner(m);
90 }
91 
92 weak_alias(__pthread_mutex_trylock, pthread_mutex_trylock);
93