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