remove spurious inclusion of libc.h for LFS64 ABI aliases
[musl] / src / aio / aio.c
1 #include <aio.h>
2 #include <pthread.h>
3 #include <semaphore.h>
4 #include <limits.h>
5 #include <errno.h>
6 #include <unistd.h>
7 #include <stdlib.h>
8 #include "syscall.h"
9 #include "atomic.h"
10 #include "pthread_impl.h"
11
12 /* The following is a threads-based implementation of AIO with minimal
13  * dependence on implementation details. Most synchronization is
14  * performed with pthread primitives, but atomics and futex operations
15  * are used for notification in a couple places where the pthread
16  * primitives would be inefficient or impractical.
17  *
18  * For each fd with outstanding aio operations, an aio_queue structure
19  * is maintained. These are reference-counted and destroyed by the last
20  * aio worker thread to exit. Accessing any member of the aio_queue
21  * structure requires a lock on the aio_queue. Adding and removing aio
22  * queues themselves requires a write lock on the global map object,
23  * a 4-level table mapping file descriptor numbers to aio queues. A
24  * read lock on the map is used to obtain locks on existing queues by
25  * excluding destruction of the queue by a different thread while it is
26  * being locked.
27  *
28  * Each aio queue has a list of active threads/operations. Presently there
29  * is a one to one relationship between threads and operations. The only
30  * members of the aio_thread structure which are accessed by other threads
31  * are the linked list pointers, op (which is immutable), running (which
32  * is updated atomically), and err (which is synchronized via running),
33  * so no locking is necessary. Most of the other other members are used
34  * for sharing data between the main flow of execution and cancellation
35  * cleanup handler.
36  *
37  * Taking any aio locks requires having all signals blocked. This is
38  * necessary because aio_cancel is needed by close, and close is required
39  * to be async-signal safe. All aio worker threads run with all signals
40  * blocked permanently.
41  */
42
43 struct aio_args {
44         struct aiocb *cb;
45         int op;
46         int err;
47         sem_t sem;
48 };
49
50 struct aio_thread {
51         pthread_t td;
52         struct aiocb *cb;
53         struct aio_thread *next, *prev;
54         struct aio_queue *q;
55         volatile int running;
56         int err, op;
57         ssize_t ret;
58 };
59
60 struct aio_queue {
61         int fd, seekable, append, ref, init;
62         pthread_mutex_t lock;
63         pthread_cond_t cond;
64         struct aio_thread *head;
65 };
66
67 static pthread_rwlock_t maplock = PTHREAD_RWLOCK_INITIALIZER;
68 static struct aio_queue *****map;
69 static volatile int aio_fd_cnt;
70 volatile int __aio_fut;
71
72 static struct aio_queue *__aio_get_queue(int fd, int need)
73 {
74         if (fd < 0) return 0;
75         int a=fd>>24;
76         unsigned char b=fd>>16, c=fd>>8, d=fd;
77         struct aio_queue *q = 0;
78         pthread_rwlock_rdlock(&maplock);
79         if ((!map || !map[a] || !map[a][b] || !map[a][b][c] || !(q=map[a][b][c][d])) && need) {
80                 pthread_rwlock_unlock(&maplock);
81                 pthread_rwlock_wrlock(&maplock);
82                 if (!map) map = calloc(sizeof *map, (-1U/2+1)>>24);
83                 if (!map) goto out;
84                 if (!map[a]) map[a] = calloc(sizeof **map, 256);
85                 if (!map[a]) goto out;
86                 if (!map[a][b]) map[a][b] = calloc(sizeof ***map, 256);
87                 if (!map[a][b]) goto out;
88                 if (!map[a][b][c]) map[a][b][c] = calloc(sizeof ****map, 256);
89                 if (!map[a][b][c]) goto out;
90                 if (!(q = map[a][b][c][d])) {
91                         map[a][b][c][d] = q = calloc(sizeof *****map, 1);
92                         if (q) {
93                                 q->fd = fd;
94                                 pthread_mutex_init(&q->lock, 0);
95                                 pthread_cond_init(&q->cond, 0);
96                                 a_inc(&aio_fd_cnt);
97                         }
98                 }
99         }
100         if (q) pthread_mutex_lock(&q->lock);
101 out:
102         pthread_rwlock_unlock(&maplock);
103         return q;
104 }
105
106 static void __aio_unref_queue(struct aio_queue *q)
107 {
108         if (q->ref > 1) {
109                 q->ref--;
110                 pthread_mutex_unlock(&q->lock);
111                 return;
112         }
113
114         /* This is potentially the last reference, but a new reference
115          * may arrive since we cannot free the queue object without first
116          * taking the maplock, which requires releasing the queue lock. */
117         pthread_mutex_unlock(&q->lock);
118         pthread_rwlock_wrlock(&maplock);
119         pthread_mutex_lock(&q->lock);
120         if (q->ref == 1) {
121                 int fd=q->fd;
122                 int a=fd>>24;
123                 unsigned char b=fd>>16, c=fd>>8, d=fd;
124                 map[a][b][c][d] = 0;
125                 a_dec(&aio_fd_cnt);
126                 pthread_rwlock_unlock(&maplock);
127                 pthread_mutex_unlock(&q->lock);
128                 free(q);
129         } else {
130                 q->ref--;
131                 pthread_rwlock_unlock(&maplock);
132                 pthread_mutex_unlock(&q->lock);
133         }
134 }
135
136 static void cleanup(void *ctx)
137 {
138         struct aio_thread *at = ctx;
139         struct aio_queue *q = at->q;
140         struct aiocb *cb = at->cb;
141         struct sigevent sev = cb->aio_sigevent;
142
143         /* There are four potential types of waiters we could need to wake:
144          *   1. Callers of aio_cancel/close.
145          *   2. Callers of aio_suspend with a single aiocb.
146          *   3. Callers of aio_suspend with a list.
147          *   4. AIO worker threads waiting for sequenced operations.
148          * Types 1-3 are notified via atomics/futexes, mainly for AS-safety
149          * considerations. Type 4 is notified later via a cond var. */
150
151         cb->__ret = at->ret;
152         if (a_swap(&at->running, 0) < 0)
153                 __wake(&at->running, -1, 1);
154         if (a_swap(&cb->__err, at->err) != EINPROGRESS)
155                 __wake(&cb->__err, -1, 1);
156         if (a_swap(&__aio_fut, 0))
157                 __wake(&__aio_fut, -1, 1);
158
159         pthread_mutex_lock(&q->lock);
160
161         if (at->next) at->next->prev = at->prev;
162         if (at->prev) at->prev->next = at->next;
163         else q->head = at->next;
164
165         /* Signal aio worker threads waiting for sequenced operations. */
166         pthread_cond_broadcast(&q->cond);
167
168         __aio_unref_queue(q);
169
170         if (sev.sigev_notify == SIGEV_SIGNAL) {
171                 siginfo_t si = {
172                         .si_signo = sev.sigev_signo,
173                         .si_value = sev.sigev_value,
174                         .si_code = SI_ASYNCIO,
175                         .si_pid = getpid(),
176                         .si_uid = getuid()
177                 };
178                 __syscall(SYS_rt_sigqueueinfo, si.si_pid, si.si_signo, &si);
179         }
180         if (sev.sigev_notify == SIGEV_THREAD) {
181                 a_store(&__pthread_self()->cancel, 0);
182                 sev.sigev_notify_function(sev.sigev_value);
183         }
184 }
185
186 static void *io_thread_func(void *ctx)
187 {
188         struct aio_thread at, *p;
189
190         struct aio_args *args = ctx;
191         struct aiocb *cb = args->cb;
192         int fd = cb->aio_fildes;
193         int op = args->op;
194         void *buf = (void *)cb->aio_buf;
195         size_t len = cb->aio_nbytes;
196         off_t off = cb->aio_offset;
197
198         struct aio_queue *q = __aio_get_queue(fd, 1);
199         ssize_t ret;
200
201         args->err = q ? 0 : EAGAIN;
202         sem_post(&args->sem);
203         if (!q) return 0;
204
205         at.op = op;
206         at.running = 1;
207         at.ret = -1;
208         at.err = ECANCELED;
209         at.q = q;
210         at.td = __pthread_self();
211         at.cb = cb;
212         at.prev = 0;
213         if ((at.next = q->head)) at.next->prev = &at;
214         q->head = &at;
215         q->ref++;
216
217         if (!q->init) {
218                 int seekable = lseek(fd, 0, SEEK_CUR) >= 0;
219                 q->seekable = seekable;
220                 q->append = !seekable || (fcntl(fd, F_GETFL) & O_APPEND);
221                 q->init = 1;
222         }
223
224         pthread_cleanup_push(cleanup, &at);
225
226         /* Wait for sequenced operations. */
227         if (op!=LIO_READ && (op!=LIO_WRITE || q->append)) {
228                 for (;;) {
229                         for (p=at.next; p && p->op!=LIO_WRITE; p=p->next);
230                         if (!p) break;
231                         pthread_cond_wait(&q->cond, &q->lock);
232                 }
233         }
234
235         pthread_mutex_unlock(&q->lock);
236
237         switch (op) {
238         case LIO_WRITE:
239                 ret = q->append ? write(fd, buf, len) : pwrite(fd, buf, len, off);
240                 break;
241         case LIO_READ:
242                 ret = !q->seekable ? read(fd, buf, len) : pread(fd, buf, len, off);
243                 break;
244         case O_SYNC:
245                 ret = fsync(fd);
246                 break;
247         case O_DSYNC:
248                 ret = fdatasync(fd);
249                 break;
250         }
251         at.ret = ret;
252         at.err = ret<0 ? errno : 0;
253         
254         pthread_cleanup_pop(1);
255
256         return 0;
257 }
258
259 static int submit(struct aiocb *cb, int op)
260 {
261         int ret = 0;
262         pthread_attr_t a;
263         sigset_t allmask, origmask;
264         pthread_t td;
265         struct aio_args args = { .cb = cb, .op = op };
266         sem_init(&args.sem, 0, 0);
267
268         if (cb->aio_sigevent.sigev_notify == SIGEV_THREAD) {
269                 if (cb->aio_sigevent.sigev_notify_attributes)
270                         a = *cb->aio_sigevent.sigev_notify_attributes;
271                 else
272                         pthread_attr_init(&a);
273         } else {
274                 pthread_attr_init(&a);
275                 pthread_attr_setstacksize(&a, PTHREAD_STACK_MIN);
276                 pthread_attr_setguardsize(&a, 0);
277         }
278         pthread_attr_setdetachstate(&a, PTHREAD_CREATE_DETACHED);
279         sigfillset(&allmask);
280         pthread_sigmask(SIG_BLOCK, &allmask, &origmask);
281         cb->__err = EINPROGRESS;
282         if (pthread_create(&td, &a, io_thread_func, &args)) {
283                 errno = EAGAIN;
284                 ret = -1;
285         }
286         pthread_sigmask(SIG_SETMASK, &origmask, 0);
287
288         if (!ret) {
289                 while (sem_wait(&args.sem));
290                 if (args.err) {
291                         errno = args.err;
292                         ret = -1;
293                 }
294         }
295
296         return ret;
297 }
298
299 int aio_read(struct aiocb *cb)
300 {
301         return submit(cb, LIO_READ);
302 }
303
304 int aio_write(struct aiocb *cb)
305 {
306         return submit(cb, LIO_WRITE);
307 }
308
309 int aio_fsync(int op, struct aiocb *cb)
310 {
311         if (op != O_SYNC && op != O_DSYNC) {
312                 errno = EINVAL;
313                 return -1;
314         }
315         return submit(cb, op);
316 }
317
318 ssize_t aio_return(struct aiocb *cb)
319 {
320         return cb->__ret;
321 }
322
323 int aio_error(const struct aiocb *cb)
324 {
325         a_barrier();
326         return cb->__err & 0x7fffffff;
327 }
328
329 int aio_cancel(int fd, struct aiocb *cb)
330 {
331         sigset_t allmask, origmask;
332         int ret = AIO_ALLDONE;
333         struct aio_thread *p;
334         struct aio_queue *q;
335
336         /* Unspecified behavior case. Report an error. */
337         if (cb && fd != cb->aio_fildes) {
338                 errno = EINVAL;
339                 return -1;
340         }
341
342         sigfillset(&allmask);
343         pthread_sigmask(SIG_BLOCK, &allmask, &origmask);
344
345         if (!(q = __aio_get_queue(fd, 0))) {
346                 if (fcntl(fd, F_GETFD) < 0) ret = -1;
347                 goto done;
348         }
349
350         for (p = q->head; p; p = p->next) {
351                 if (cb && cb != p->cb) continue;
352                 /* Transition target from running to running-with-waiters */
353                 if (a_cas(&p->running, 1, -1)) {
354                         pthread_cancel(p->td);
355                         __wait(&p->running, 0, -1, 1);
356                         if (p->err == ECANCELED) ret = AIO_CANCELED;
357                 }
358         }
359
360         pthread_mutex_unlock(&q->lock);
361 done:
362         pthread_sigmask(SIG_SETMASK, &origmask, 0);
363         return ret;
364 }
365
366 int __aio_close(int fd)
367 {
368         a_barrier();
369         if (aio_fd_cnt) aio_cancel(fd, 0);
370         return fd;
371 }
372
373 weak_alias(aio_cancel, aio_cancel64);
374 weak_alias(aio_error, aio_error64);
375 weak_alias(aio_fsync, aio_fsync64);
376 weak_alias(aio_read, aio_read64);
377 weak_alias(aio_write, aio_write64);
378 weak_alias(aio_return, aio_return64);