• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include "pthread_impl.h"
2 
pthread_mutex_timedlock_pi(pthread_mutex_t * restrict m,const struct timespec * restrict at)3 static int pthread_mutex_timedlock_pi(pthread_mutex_t *restrict m, const struct timespec *restrict at)
4 {
5 	int type = m->_m_type;
6 	int priv = (type & 128) ^ 128;
7 	pthread_t self = __pthread_self();
8 	int e;
9 
10 	if (!priv) self->robust_list.pending = &m->_m_next;
11 
12 	do e = -__syscall(SYS_futex, &m->_m_lock, FUTEX_LOCK_PI|priv, 0, at);
13 	while (e==EINTR);
14 	if (e) self->robust_list.pending = 0;
15 
16 	switch (e) {
17 	case 0:
18 		/* Catch spurious success for non-robust mutexes. */
19 		if (!(type&4) && ((m->_m_lock & 0x40000000) || m->_m_waiters)) {
20 			a_store(&m->_m_waiters, -1);
21 			__syscall(SYS_futex, &m->_m_lock, FUTEX_UNLOCK_PI|priv);
22 			self->robust_list.pending = 0;
23 			break;
24 		}
25 		/* Signal to trylock that we already have the lock. */
26 		m->_m_count = -1;
27 		return __pthread_mutex_trylock(m);
28 	case ETIMEDOUT:
29 		return e;
30 	case EDEADLK:
31 		if ((type&3) == PTHREAD_MUTEX_ERRORCHECK) return e;
32 	}
33 	do e = __timedwait(&(int){0}, 0, CLOCK_REALTIME, at, 1);
34 	while (e != ETIMEDOUT);
35 	return e;
36 }
37 
__pthread_mutex_timedlock(pthread_mutex_t * restrict m,const struct timespec * restrict at)38 int __pthread_mutex_timedlock(pthread_mutex_t *restrict m, const struct timespec *restrict at)
39 {
40 	if ((m->_m_type&15) == PTHREAD_MUTEX_NORMAL
41 	    && !a_cas(&m->_m_lock, 0, EBUSY))
42 		return 0;
43 
44 	int type = m->_m_type;
45 	int r, t, priv = (type & 128) ^ 128;
46 
47 	r = __pthread_mutex_trylock(m);
48 	if (r != EBUSY) return r;
49 
50 	if (type&8) return pthread_mutex_timedlock_pi(m, at);
51 
52 	int spins = 100;
53 	while (spins-- && m->_m_lock && !m->_m_waiters) a_spin();
54 
55 	while ((r=__pthread_mutex_trylock(m)) == EBUSY) {
56 		r = m->_m_lock;
57 		int own = r & 0x3fffffff;
58 		if (!own && (!r || (type&4)))
59 			continue;
60 		if ((type&3) == PTHREAD_MUTEX_ERRORCHECK
61 		    && own == __pthread_self()->tid)
62 			return EDEADLK;
63 
64 		a_inc(&m->_m_waiters);
65 		t = r | 0x80000000;
66 		a_cas(&m->_m_lock, r, t);
67 		r = __timedwait(&m->_m_lock, t, CLOCK_REALTIME, at, priv);
68 		a_dec(&m->_m_waiters);
69 		if (r && r != EINTR) break;
70 	}
71 	return r;
72 }
73 
74 weak_alias(__pthread_mutex_timedlock, pthread_mutex_timedlock);
75