fix pthread_cond_wait cancellation race
[musl] / src / thread / pthread_cond_timedwait.c
1 #include "pthread_impl.h"
2
3 void __pthread_testcancel(void);
4 int __pthread_mutex_lock(pthread_mutex_t *);
5 int __pthread_mutex_unlock(pthread_mutex_t *);
6
7 /*
8  * struct waiter
9  *
10  * Waiter objects have automatic storage on the waiting thread, and
11  * are used in building a linked list representing waiters currently
12  * waiting on the condition variable or a group of waiters woken
13  * together by a broadcast or signal; in the case of signal, this is a
14  * degenerate list of one member.
15  *
16  * Waiter lists attached to the condition variable itself are
17  * protected by the lock on the cv. Detached waiter lists are never
18  * modified again, but can only be traversed in reverse order, and are
19  * protected by the "barrier" locks in each node, which are unlocked
20  * in turn to control wake order.
21  *
22  * Since process-shared cond var semantics do not necessarily allow
23  * one thread to see another's automatic storage (they may be in
24  * different processes), the waiter list is not used for the
25  * process-shared case, but the structure is still used to store data
26  * needed by the cancellation cleanup handler.
27  */
28
29 struct waiter {
30         struct waiter *prev, *next;
31         int state, barrier, mutex_ret;
32         int *notify;
33         pthread_mutex_t *mutex;
34         pthread_cond_t *cond;
35         int shared, err;
36 };
37
38 /* Self-synchronized-destruction-safe lock functions */
39
40 static inline void lock(volatile int *l)
41 {
42         if (a_cas(l, 0, 1)) {
43                 a_cas(l, 1, 2);
44                 do __wait(l, 0, 2, 1);
45                 while (a_cas(l, 0, 2));
46         }
47 }
48
49 static inline void unlock(volatile int *l)
50 {
51         if (a_swap(l, 0)==2)
52                 __wake(l, 1, 1);
53 }
54
55 static inline void unlock_requeue(volatile int *l, volatile int *r, int w)
56 {
57         a_store(l, 0);
58         if (w) __wake(l, 1, 1);
59         else __syscall(SYS_futex, l, FUTEX_REQUEUE|128, 0, 1, r) != -ENOSYS
60                 || __syscall(SYS_futex, l, FUTEX_REQUEUE, 0, 1, r);
61 }
62
63 enum {
64         WAITING,
65         SIGNALED,
66         LEAVING,
67 };
68
69 static void unwait(void *arg)
70 {
71         struct waiter *node = arg;
72
73         if (node->shared) {
74                 pthread_cond_t *c = node->cond;
75                 pthread_mutex_t *m = node->mutex;
76                 /* Suppress cancellation if a signal was potentially
77                  * consumed; this is a legitimate form of spurious
78                  * wake even if not. */
79                 if (node->err == ECANCELED && c->_c_seq != node->state)
80                         node->err = 0;
81                 if (a_fetch_add(&c->_c_waiters, -1) == -0x7fffffff)
82                         __wake(&c->_c_waiters, 1, 0);
83                 node->mutex_ret = pthread_mutex_lock(m);
84                 return;
85         }
86
87         int oldstate = a_cas(&node->state, WAITING, LEAVING);
88
89         if (oldstate == WAITING) {
90                 /* Access to cv object is valid because this waiter was not
91                  * yet signaled and a new signal/broadcast cannot return
92                  * after seeing a LEAVING waiter without getting notified
93                  * via the futex notify below. */
94
95                 pthread_cond_t *c = node->cond;
96                 lock(&c->_c_lock);
97                 
98                 if (c->_c_head == node) c->_c_head = node->next;
99                 else if (node->prev) node->prev->next = node->next;
100                 if (c->_c_tail == node) c->_c_tail = node->prev;
101                 else if (node->next) node->next->prev = node->prev;
102                 
103                 unlock(&c->_c_lock);
104
105                 if (node->notify) {
106                         if (a_fetch_add(node->notify, -1)==1)
107                                 __wake(node->notify, 1, 1);
108                 }
109         } else {
110                 /* Lock barrier first to control wake order. */
111                 lock(&node->barrier);
112         }
113
114         node->mutex_ret = pthread_mutex_lock(node->mutex);
115
116         if (oldstate == WAITING) return;
117
118         if (!node->next) a_inc(&node->mutex->_m_waiters);
119
120         /* Unlock the barrier that's holding back the next waiter, and
121          * either wake it or requeue it to the mutex. */
122         if (node->prev) {
123                 unlock_requeue(&node->prev->barrier,
124                         &node->mutex->_m_lock,
125                         node->mutex->_m_type & 128);
126         } else {
127                 a_dec(&node->mutex->_m_waiters);
128         }
129
130         /* Since a signal was consumed, acting on cancellation is not
131          * permitted. The only other error possible at this stage,
132          * ETIMEDOUT, is permitted even if a signal was consumed. */
133         if (node->err = ECANCELED) node->err = 0;
134 }
135
136 static void dummy(void *arg)
137 {
138 }
139
140 int __pthread_setcancelstate(int, int *);
141
142 int __pthread_cond_timedwait(pthread_cond_t *restrict c, pthread_mutex_t *restrict m, const struct timespec *restrict ts)
143 {
144         struct waiter node = { .cond = c, .mutex = m };
145         int e, seq, *fut, clock = c->_c_clock, cs;
146
147         if ((m->_m_type&15) && (m->_m_lock&INT_MAX) != __pthread_self()->tid)
148                 return EPERM;
149
150         if (ts && ts->tv_nsec >= 1000000000UL)
151                 return EINVAL;
152
153         __pthread_testcancel();
154
155         if (c->_c_shared) {
156                 node.shared = 1;
157                 fut = &c->_c_seq;
158                 seq = node.state = c->_c_seq;
159                 a_inc(&c->_c_waiters);
160         } else {
161                 lock(&c->_c_lock);
162
163                 seq = node.barrier = 2;
164                 fut = &node.barrier;
165                 node.state = WAITING;
166                 node.next = c->_c_head;
167                 c->_c_head = &node;
168                 if (!c->_c_tail) c->_c_tail = &node;
169                 else node.next->prev = &node;
170
171                 unlock(&c->_c_lock);
172         }
173
174         __pthread_mutex_unlock(m);
175
176         __pthread_setcancelstate(PTHREAD_CANCEL_MASKED, &cs);
177
178         do e = __timedwait(fut, seq, clock, ts, dummy, 0, !node.shared);
179         while (*fut==seq && (!e || e==EINTR));
180         if (e == EINTR) e = 0;
181
182         node.err = e;
183         unwait(&node);
184         e = node.err;
185
186         /* Suppress cancellation if there was an error locking the mutex,
187          * since the contract for cancellation requires the mutex to be
188          * locked when the cleanup handler is called, and there is no
189          * way to report an error. */
190         if (node.mutex_ret) e = node.mutex_ret;
191
192         __pthread_setcancelstate(cs, 0);
193
194         if (e == ECANCELED) {
195                 __pthread_testcancel();
196                 __pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0);
197         }
198
199         return e;
200 }
201
202 int __private_cond_signal(pthread_cond_t *c, int n)
203 {
204         struct waiter *p, *first=0;
205         int ref = 0, cur;
206
207         lock(&c->_c_lock);
208         for (p=c->_c_tail; n && p; p=p->prev) {
209                 if (a_cas(&p->state, WAITING, SIGNALED) != WAITING) {
210                         ref++;
211                         p->notify = &ref;
212                 } else {
213                         n--;
214                         if (!first) first=p;
215                 }
216         }
217         /* Split the list, leaving any remainder on the cv. */
218         if (p) {
219                 if (p->next) p->next->prev = 0;
220                 p->next = 0;
221         } else {
222                 c->_c_head = 0;
223         }
224         c->_c_tail = p;
225         unlock(&c->_c_lock);
226
227         /* Wait for any waiters in the LEAVING state to remove
228          * themselves from the list before returning or allowing
229          * signaled threads to proceed. */
230         while ((cur = ref)) __wait(&ref, 0, cur, 1);
231
232         /* Allow first signaled waiter, if any, to proceed. */
233         if (first) unlock(&first->barrier);
234
235         return 0;
236 }
237
238 weak_alias(__pthread_cond_timedwait, pthread_cond_timedwait);