blob: d3a6ec2c9627e1e58a769c93398f2a3787bdfda8 [file] [log] [blame]
Linus Torvalds1da177e2005-04-16 15:20:36 -07001/*
2 * An async IO implementation for Linux
3 * Written by Benjamin LaHaise <bcrl@kvack.org>
4 *
5 * Implements an efficient asynchronous io interface.
6 *
7 * Copyright 2000, 2001, 2002 Red Hat, Inc. All Rights Reserved.
8 *
9 * See ../COPYING for licensing terms.
10 */
11#include <linux/kernel.h>
12#include <linux/init.h>
13#include <linux/errno.h>
14#include <linux/time.h>
15#include <linux/aio_abi.h>
16#include <linux/module.h>
17#include <linux/syscalls.h>
Badari Pulavarty027445c2006-09-30 23:28:46 -070018#include <linux/uio.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070019
20#define DEBUG 0
21
22#include <linux/sched.h>
23#include <linux/fs.h>
24#include <linux/file.h>
25#include <linux/mm.h>
26#include <linux/mman.h>
27#include <linux/slab.h>
28#include <linux/timer.h>
29#include <linux/aio.h>
30#include <linux/highmem.h>
31#include <linux/workqueue.h>
32#include <linux/security.h>
33
34#include <asm/kmap_types.h>
35#include <asm/uaccess.h>
36#include <asm/mmu_context.h>
37
38#if DEBUG > 1
39#define dprintk printk
40#else
41#define dprintk(x...) do { ; } while (0)
42#endif
43
Linus Torvalds1da177e2005-04-16 15:20:36 -070044/*------ sysctl variables----*/
Zach Brownd55b5fd2005-11-07 00:59:31 -080045static DEFINE_SPINLOCK(aio_nr_lock);
46unsigned long aio_nr; /* current system wide number of aio requests */
47unsigned long aio_max_nr = 0x10000; /* system wide maximum number of aio requests */
Linus Torvalds1da177e2005-04-16 15:20:36 -070048/*----end sysctl variables---*/
49
Christoph Lametere18b8902006-12-06 20:33:20 -080050static struct kmem_cache *kiocb_cachep;
51static struct kmem_cache *kioctx_cachep;
Linus Torvalds1da177e2005-04-16 15:20:36 -070052
53static struct workqueue_struct *aio_wq;
54
55/* Used for rare fput completion. */
David Howells65f27f32006-11-22 14:55:48 +000056static void aio_fput_routine(struct work_struct *);
57static DECLARE_WORK(fput_work, aio_fput_routine);
Linus Torvalds1da177e2005-04-16 15:20:36 -070058
59static DEFINE_SPINLOCK(fput_lock);
Adrian Bunk25ee7e32005-04-25 08:18:14 -070060static LIST_HEAD(fput_head);
Linus Torvalds1da177e2005-04-16 15:20:36 -070061
David Howells65f27f32006-11-22 14:55:48 +000062static void aio_kick_handler(struct work_struct *);
Sébastien Duguc016e222005-06-28 20:44:59 -070063static void aio_queue_work(struct kioctx *);
Linus Torvalds1da177e2005-04-16 15:20:36 -070064
65/* aio_setup
66 * Creates the slab caches used by the aio routines, panic on
67 * failure as this is done early during the boot sequence.
68 */
69static int __init aio_setup(void)
70{
71 kiocb_cachep = kmem_cache_create("kiocb", sizeof(struct kiocb),
72 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
73 kioctx_cachep = kmem_cache_create("kioctx", sizeof(struct kioctx),
74 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
75
76 aio_wq = create_workqueue("aio");
77
78 pr_debug("aio_setup: sizeof(struct page) = %d\n", (int)sizeof(struct page));
79
80 return 0;
81}
82
83static void aio_free_ring(struct kioctx *ctx)
84{
85 struct aio_ring_info *info = &ctx->ring_info;
86 long i;
87
88 for (i=0; i<info->nr_pages; i++)
89 put_page(info->ring_pages[i]);
90
91 if (info->mmap_size) {
92 down_write(&ctx->mm->mmap_sem);
93 do_munmap(ctx->mm, info->mmap_base, info->mmap_size);
94 up_write(&ctx->mm->mmap_sem);
95 }
96
97 if (info->ring_pages && info->ring_pages != info->internal_pages)
98 kfree(info->ring_pages);
99 info->ring_pages = NULL;
100 info->nr = 0;
101}
102
103static int aio_setup_ring(struct kioctx *ctx)
104{
105 struct aio_ring *ring;
106 struct aio_ring_info *info = &ctx->ring_info;
107 unsigned nr_events = ctx->max_reqs;
108 unsigned long size;
109 int nr_pages;
110
111 /* Compensate for the ring buffer's head/tail overlap entry */
112 nr_events += 2; /* 1 is required, 2 for good luck */
113
114 size = sizeof(struct aio_ring);
115 size += sizeof(struct io_event) * nr_events;
116 nr_pages = (size + PAGE_SIZE-1) >> PAGE_SHIFT;
117
118 if (nr_pages < 0)
119 return -EINVAL;
120
121 nr_events = (PAGE_SIZE * nr_pages - sizeof(struct aio_ring)) / sizeof(struct io_event);
122
123 info->nr = 0;
124 info->ring_pages = info->internal_pages;
125 if (nr_pages > AIO_RING_PAGES) {
Oliver Neukum11b0b5a2006-03-25 03:08:13 -0800126 info->ring_pages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700127 if (!info->ring_pages)
128 return -ENOMEM;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700129 }
130
131 info->mmap_size = nr_pages * PAGE_SIZE;
132 dprintk("attempting mmap of %lu bytes\n", info->mmap_size);
133 down_write(&ctx->mm->mmap_sem);
134 info->mmap_base = do_mmap(NULL, 0, info->mmap_size,
135 PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE,
136 0);
137 if (IS_ERR((void *)info->mmap_base)) {
138 up_write(&ctx->mm->mmap_sem);
139 printk("mmap err: %ld\n", -info->mmap_base);
140 info->mmap_size = 0;
141 aio_free_ring(ctx);
142 return -EAGAIN;
143 }
144
145 dprintk("mmap address: 0x%08lx\n", info->mmap_base);
146 info->nr_pages = get_user_pages(current, ctx->mm,
147 info->mmap_base, nr_pages,
148 1, 0, info->ring_pages, NULL);
149 up_write(&ctx->mm->mmap_sem);
150
151 if (unlikely(info->nr_pages != nr_pages)) {
152 aio_free_ring(ctx);
153 return -EAGAIN;
154 }
155
156 ctx->user_id = info->mmap_base;
157
158 info->nr = nr_events; /* trusted copy */
159
160 ring = kmap_atomic(info->ring_pages[0], KM_USER0);
161 ring->nr = nr_events; /* user copy */
162 ring->id = ctx->user_id;
163 ring->head = ring->tail = 0;
164 ring->magic = AIO_RING_MAGIC;
165 ring->compat_features = AIO_RING_COMPAT_FEATURES;
166 ring->incompat_features = AIO_RING_INCOMPAT_FEATURES;
167 ring->header_length = sizeof(struct aio_ring);
168 kunmap_atomic(ring, KM_USER0);
169
170 return 0;
171}
172
173
174/* aio_ring_event: returns a pointer to the event at the given index from
175 * kmap_atomic(, km). Release the pointer with put_aio_ring_event();
176 */
177#define AIO_EVENTS_PER_PAGE (PAGE_SIZE / sizeof(struct io_event))
178#define AIO_EVENTS_FIRST_PAGE ((PAGE_SIZE - sizeof(struct aio_ring)) / sizeof(struct io_event))
179#define AIO_EVENTS_OFFSET (AIO_EVENTS_PER_PAGE - AIO_EVENTS_FIRST_PAGE)
180
181#define aio_ring_event(info, nr, km) ({ \
182 unsigned pos = (nr) + AIO_EVENTS_OFFSET; \
183 struct io_event *__event; \
184 __event = kmap_atomic( \
185 (info)->ring_pages[pos / AIO_EVENTS_PER_PAGE], km); \
186 __event += pos % AIO_EVENTS_PER_PAGE; \
187 __event; \
188})
189
190#define put_aio_ring_event(event, km) do { \
191 struct io_event *__event = (event); \
192 (void)__event; \
193 kunmap_atomic((void *)((unsigned long)__event & PAGE_MASK), km); \
194} while(0)
195
196/* ioctx_alloc
197 * Allocates and initializes an ioctx. Returns an ERR_PTR if it failed.
198 */
199static struct kioctx *ioctx_alloc(unsigned nr_events)
200{
201 struct mm_struct *mm;
202 struct kioctx *ctx;
203
204 /* Prevent overflows */
205 if ((nr_events > (0x10000000U / sizeof(struct io_event))) ||
206 (nr_events > (0x10000000U / sizeof(struct kiocb)))) {
207 pr_debug("ENOMEM: nr_events too high\n");
208 return ERR_PTR(-EINVAL);
209 }
210
Zach Brownd55b5fd2005-11-07 00:59:31 -0800211 if ((unsigned long)nr_events > aio_max_nr)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700212 return ERR_PTR(-EAGAIN);
213
214 ctx = kmem_cache_alloc(kioctx_cachep, GFP_KERNEL);
215 if (!ctx)
216 return ERR_PTR(-ENOMEM);
217
218 memset(ctx, 0, sizeof(*ctx));
219 ctx->max_reqs = nr_events;
220 mm = ctx->mm = current->mm;
221 atomic_inc(&mm->mm_count);
222
223 atomic_set(&ctx->users, 1);
224 spin_lock_init(&ctx->ctx_lock);
225 spin_lock_init(&ctx->ring_info.ring_lock);
226 init_waitqueue_head(&ctx->wait);
227
228 INIT_LIST_HEAD(&ctx->active_reqs);
229 INIT_LIST_HEAD(&ctx->run_list);
David Howells65f27f32006-11-22 14:55:48 +0000230 INIT_DELAYED_WORK(&ctx->wq, aio_kick_handler);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700231
232 if (aio_setup_ring(ctx) < 0)
233 goto out_freectx;
234
235 /* limit the number of system wide aios */
Zach Brownd55b5fd2005-11-07 00:59:31 -0800236 spin_lock(&aio_nr_lock);
237 if (aio_nr + ctx->max_reqs > aio_max_nr ||
238 aio_nr + ctx->max_reqs < aio_nr)
239 ctx->max_reqs = 0;
240 else
241 aio_nr += ctx->max_reqs;
242 spin_unlock(&aio_nr_lock);
243 if (ctx->max_reqs == 0)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700244 goto out_cleanup;
245
246 /* now link into global list. kludge. FIXME */
247 write_lock(&mm->ioctx_list_lock);
248 ctx->next = mm->ioctx_list;
249 mm->ioctx_list = ctx;
250 write_unlock(&mm->ioctx_list_lock);
251
252 dprintk("aio: allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
253 ctx, ctx->user_id, current->mm, ctx->ring_info.nr);
254 return ctx;
255
256out_cleanup:
Linus Torvalds1da177e2005-04-16 15:20:36 -0700257 __put_ioctx(ctx);
258 return ERR_PTR(-EAGAIN);
259
260out_freectx:
261 mmdrop(mm);
262 kmem_cache_free(kioctx_cachep, ctx);
263 ctx = ERR_PTR(-ENOMEM);
264
265 dprintk("aio: error allocating ioctx %p\n", ctx);
266 return ctx;
267}
268
269/* aio_cancel_all
270 * Cancels all outstanding aio requests on an aio context. Used
271 * when the processes owning a context have all exited to encourage
272 * the rapid destruction of the kioctx.
273 */
274static void aio_cancel_all(struct kioctx *ctx)
275{
276 int (*cancel)(struct kiocb *, struct io_event *);
277 struct io_event res;
278 spin_lock_irq(&ctx->ctx_lock);
279 ctx->dead = 1;
280 while (!list_empty(&ctx->active_reqs)) {
281 struct list_head *pos = ctx->active_reqs.next;
282 struct kiocb *iocb = list_kiocb(pos);
283 list_del_init(&iocb->ki_list);
284 cancel = iocb->ki_cancel;
285 kiocbSetCancelled(iocb);
286 if (cancel) {
287 iocb->ki_users++;
288 spin_unlock_irq(&ctx->ctx_lock);
289 cancel(iocb, &res);
290 spin_lock_irq(&ctx->ctx_lock);
291 }
292 }
293 spin_unlock_irq(&ctx->ctx_lock);
294}
295
Adrian Bunk25ee7e32005-04-25 08:18:14 -0700296static void wait_for_all_aios(struct kioctx *ctx)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700297{
298 struct task_struct *tsk = current;
299 DECLARE_WAITQUEUE(wait, tsk);
300
301 if (!ctx->reqs_active)
302 return;
303
304 add_wait_queue(&ctx->wait, &wait);
305 set_task_state(tsk, TASK_UNINTERRUPTIBLE);
306 while (ctx->reqs_active) {
307 schedule();
308 set_task_state(tsk, TASK_UNINTERRUPTIBLE);
309 }
310 __set_task_state(tsk, TASK_RUNNING);
311 remove_wait_queue(&ctx->wait, &wait);
312}
313
314/* wait_on_sync_kiocb:
315 * Waits on the given sync kiocb to complete.
316 */
317ssize_t fastcall wait_on_sync_kiocb(struct kiocb *iocb)
318{
319 while (iocb->ki_users) {
320 set_current_state(TASK_UNINTERRUPTIBLE);
321 if (!iocb->ki_users)
322 break;
323 schedule();
324 }
325 __set_current_state(TASK_RUNNING);
326 return iocb->ki_user_data;
327}
328
329/* exit_aio: called when the last user of mm goes away. At this point,
330 * there is no way for any new requests to be submited or any of the
331 * io_* syscalls to be called on the context. However, there may be
332 * outstanding requests which hold references to the context; as they
333 * go away, they will call put_ioctx and release any pinned memory
334 * associated with the request (held via struct page * references).
335 */
336void fastcall exit_aio(struct mm_struct *mm)
337{
338 struct kioctx *ctx = mm->ioctx_list;
339 mm->ioctx_list = NULL;
340 while (ctx) {
341 struct kioctx *next = ctx->next;
342 ctx->next = NULL;
343 aio_cancel_all(ctx);
344
345 wait_for_all_aios(ctx);
346 /*
347 * this is an overkill, but ensures we don't leave
348 * the ctx on the aio_wq
349 */
350 flush_workqueue(aio_wq);
351
352 if (1 != atomic_read(&ctx->users))
353 printk(KERN_DEBUG
354 "exit_aio:ioctx still alive: %d %d %d\n",
355 atomic_read(&ctx->users), ctx->dead,
356 ctx->reqs_active);
357 put_ioctx(ctx);
358 ctx = next;
359 }
360}
361
362/* __put_ioctx
363 * Called when the last user of an aio context has gone away,
364 * and the struct needs to be freed.
365 */
366void fastcall __put_ioctx(struct kioctx *ctx)
367{
368 unsigned nr_events = ctx->max_reqs;
369
Eric Sesterhenn93e06b42006-11-30 05:29:23 +0100370 BUG_ON(ctx->reqs_active);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700371
372 cancel_delayed_work(&ctx->wq);
373 flush_workqueue(aio_wq);
374 aio_free_ring(ctx);
375 mmdrop(ctx->mm);
376 ctx->mm = NULL;
377 pr_debug("__put_ioctx: freeing %p\n", ctx);
378 kmem_cache_free(kioctx_cachep, ctx);
379
Zach Brownd55b5fd2005-11-07 00:59:31 -0800380 if (nr_events) {
381 spin_lock(&aio_nr_lock);
382 BUG_ON(aio_nr - nr_events > aio_nr);
383 aio_nr -= nr_events;
384 spin_unlock(&aio_nr_lock);
385 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700386}
387
388/* aio_get_req
389 * Allocate a slot for an aio request. Increments the users count
390 * of the kioctx so that the kioctx stays around until all requests are
391 * complete. Returns NULL if no requests are free.
392 *
393 * Returns with kiocb->users set to 2. The io submit code path holds
394 * an extra reference while submitting the i/o.
395 * This prevents races between the aio code path referencing the
396 * req (after submitting it) and aio_complete() freeing the req.
397 */
398static struct kiocb *FASTCALL(__aio_get_req(struct kioctx *ctx));
399static struct kiocb fastcall *__aio_get_req(struct kioctx *ctx)
400{
401 struct kiocb *req = NULL;
402 struct aio_ring *ring;
403 int okay = 0;
404
405 req = kmem_cache_alloc(kiocb_cachep, GFP_KERNEL);
406 if (unlikely(!req))
407 return NULL;
408
Zach Brown4faa5282005-10-17 16:43:33 -0700409 req->ki_flags = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700410 req->ki_users = 2;
411 req->ki_key = 0;
412 req->ki_ctx = ctx;
413 req->ki_cancel = NULL;
414 req->ki_retry = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700415 req->ki_dtor = NULL;
416 req->private = NULL;
Badari Pulavartyeed4e512006-09-30 23:28:49 -0700417 req->ki_iovec = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700418 INIT_LIST_HEAD(&req->ki_run_list);
419
420 /* Check if the completion queue has enough free space to
421 * accept an event from this io.
422 */
423 spin_lock_irq(&ctx->ctx_lock);
424 ring = kmap_atomic(ctx->ring_info.ring_pages[0], KM_USER0);
425 if (ctx->reqs_active < aio_ring_avail(&ctx->ring_info, ring)) {
426 list_add(&req->ki_list, &ctx->active_reqs);
427 get_ioctx(ctx);
428 ctx->reqs_active++;
429 okay = 1;
430 }
431 kunmap_atomic(ring, KM_USER0);
432 spin_unlock_irq(&ctx->ctx_lock);
433
434 if (!okay) {
435 kmem_cache_free(kiocb_cachep, req);
436 req = NULL;
437 }
438
439 return req;
440}
441
442static inline struct kiocb *aio_get_req(struct kioctx *ctx)
443{
444 struct kiocb *req;
445 /* Handle a potential starvation case -- should be exceedingly rare as
446 * requests will be stuck on fput_head only if the aio_fput_routine is
447 * delayed and the requests were the last user of the struct file.
448 */
449 req = __aio_get_req(ctx);
450 if (unlikely(NULL == req)) {
451 aio_fput_routine(NULL);
452 req = __aio_get_req(ctx);
453 }
454 return req;
455}
456
457static inline void really_put_req(struct kioctx *ctx, struct kiocb *req)
458{
Zach Brownd00689a2005-11-13 16:07:34 -0800459 assert_spin_locked(&ctx->ctx_lock);
460
Linus Torvalds1da177e2005-04-16 15:20:36 -0700461 if (req->ki_dtor)
462 req->ki_dtor(req);
Badari Pulavartyeed4e512006-09-30 23:28:49 -0700463 if (req->ki_iovec != &req->ki_inline_vec)
464 kfree(req->ki_iovec);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700465 kmem_cache_free(kiocb_cachep, req);
466 ctx->reqs_active--;
467
468 if (unlikely(!ctx->reqs_active && ctx->dead))
469 wake_up(&ctx->wait);
470}
471
David Howells65f27f32006-11-22 14:55:48 +0000472static void aio_fput_routine(struct work_struct *data)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700473{
474 spin_lock_irq(&fput_lock);
475 while (likely(!list_empty(&fput_head))) {
476 struct kiocb *req = list_kiocb(fput_head.next);
477 struct kioctx *ctx = req->ki_ctx;
478
479 list_del(&req->ki_list);
480 spin_unlock_irq(&fput_lock);
481
482 /* Complete the fput */
483 __fput(req->ki_filp);
484
485 /* Link the iocb into the context's free list */
486 spin_lock_irq(&ctx->ctx_lock);
487 really_put_req(ctx, req);
488 spin_unlock_irq(&ctx->ctx_lock);
489
490 put_ioctx(ctx);
491 spin_lock_irq(&fput_lock);
492 }
493 spin_unlock_irq(&fput_lock);
494}
495
496/* __aio_put_req
497 * Returns true if this put was the last user of the request.
498 */
499static int __aio_put_req(struct kioctx *ctx, struct kiocb *req)
500{
501 dprintk(KERN_DEBUG "aio_put(%p): f_count=%d\n",
502 req, atomic_read(&req->ki_filp->f_count));
503
Zach Brownd00689a2005-11-13 16:07:34 -0800504 assert_spin_locked(&ctx->ctx_lock);
505
Linus Torvalds1da177e2005-04-16 15:20:36 -0700506 req->ki_users --;
Eric Sesterhenn93e06b42006-11-30 05:29:23 +0100507 BUG_ON(req->ki_users < 0);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700508 if (likely(req->ki_users))
509 return 0;
510 list_del(&req->ki_list); /* remove from active_reqs */
511 req->ki_cancel = NULL;
512 req->ki_retry = NULL;
513
514 /* Must be done under the lock to serialise against cancellation.
515 * Call this aio_fput as it duplicates fput via the fput_work.
516 */
Nick Piggin095975d2006-01-08 01:02:19 -0800517 if (unlikely(atomic_dec_and_test(&req->ki_filp->f_count))) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700518 get_ioctx(ctx);
519 spin_lock(&fput_lock);
520 list_add(&req->ki_list, &fput_head);
521 spin_unlock(&fput_lock);
522 queue_work(aio_wq, &fput_work);
523 } else
524 really_put_req(ctx, req);
525 return 1;
526}
527
528/* aio_put_req
529 * Returns true if this put was the last user of the kiocb,
530 * false if the request is still in use.
531 */
532int fastcall aio_put_req(struct kiocb *req)
533{
534 struct kioctx *ctx = req->ki_ctx;
535 int ret;
536 spin_lock_irq(&ctx->ctx_lock);
537 ret = __aio_put_req(ctx, req);
538 spin_unlock_irq(&ctx->ctx_lock);
539 if (ret)
540 put_ioctx(ctx);
541 return ret;
542}
543
544/* Lookup an ioctx id. ioctx_list is lockless for reads.
545 * FIXME: this is O(n) and is only suitable for development.
546 */
547struct kioctx *lookup_ioctx(unsigned long ctx_id)
548{
549 struct kioctx *ioctx;
550 struct mm_struct *mm;
551
552 mm = current->mm;
553 read_lock(&mm->ioctx_list_lock);
554 for (ioctx = mm->ioctx_list; ioctx; ioctx = ioctx->next)
555 if (likely(ioctx->user_id == ctx_id && !ioctx->dead)) {
556 get_ioctx(ioctx);
557 break;
558 }
559 read_unlock(&mm->ioctx_list_lock);
560
561 return ioctx;
562}
563
564/*
565 * use_mm
566 * Makes the calling kernel thread take on the specified
567 * mm context.
568 * Called by the retry thread execute retries within the
569 * iocb issuer's mm context, so that copy_from/to_user
570 * operations work seamlessly for aio.
571 * (Note: this routine is intended to be called only
572 * from a kernel thread context)
573 */
574static void use_mm(struct mm_struct *mm)
575{
576 struct mm_struct *active_mm;
577 struct task_struct *tsk = current;
578
579 task_lock(tsk);
580 tsk->flags |= PF_BORROWED_MM;
581 active_mm = tsk->active_mm;
582 atomic_inc(&mm->mm_count);
583 tsk->mm = mm;
584 tsk->active_mm = mm;
Paolo 'Blaisorblade' Giarrusso1e40cd32005-09-03 15:57:25 -0700585 /*
586 * Note that on UML this *requires* PF_BORROWED_MM to be set, otherwise
587 * it won't work. Update it accordingly if you change it here
588 */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700589 activate_mm(active_mm, mm);
590 task_unlock(tsk);
591
592 mmdrop(active_mm);
593}
594
595/*
596 * unuse_mm
597 * Reverses the effect of use_mm, i.e. releases the
598 * specified mm context which was earlier taken on
599 * by the calling kernel thread
600 * (Note: this routine is intended to be called only
601 * from a kernel thread context)
602 *
603 * Comments: Called with ctx->ctx_lock held. This nests
604 * task_lock instead ctx_lock.
605 */
Adrian Bunk25ee7e32005-04-25 08:18:14 -0700606static void unuse_mm(struct mm_struct *mm)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700607{
608 struct task_struct *tsk = current;
609
610 task_lock(tsk);
611 tsk->flags &= ~PF_BORROWED_MM;
612 tsk->mm = NULL;
613 /* active_mm is still 'mm' */
614 enter_lazy_tlb(mm, tsk);
615 task_unlock(tsk);
616}
617
618/*
619 * Queue up a kiocb to be retried. Assumes that the kiocb
620 * has already been marked as kicked, and places it on
621 * the retry run list for the corresponding ioctx, if it
622 * isn't already queued. Returns 1 if it actually queued
623 * the kiocb (to tell the caller to activate the work
624 * queue to process it), or 0, if it found that it was
625 * already queued.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700626 */
627static inline int __queue_kicked_iocb(struct kiocb *iocb)
628{
629 struct kioctx *ctx = iocb->ki_ctx;
630
Zach Brownd00689a2005-11-13 16:07:34 -0800631 assert_spin_locked(&ctx->ctx_lock);
632
Linus Torvalds1da177e2005-04-16 15:20:36 -0700633 if (list_empty(&iocb->ki_run_list)) {
634 list_add_tail(&iocb->ki_run_list,
635 &ctx->run_list);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700636 return 1;
637 }
638 return 0;
639}
640
641/* aio_run_iocb
642 * This is the core aio execution routine. It is
643 * invoked both for initial i/o submission and
644 * subsequent retries via the aio_kick_handler.
645 * Expects to be invoked with iocb->ki_ctx->lock
Andreas Mohrd6e05ed2006-06-26 18:35:02 +0200646 * already held. The lock is released and reacquired
Linus Torvalds1da177e2005-04-16 15:20:36 -0700647 * as needed during processing.
648 *
649 * Calls the iocb retry method (already setup for the
650 * iocb on initial submission) for operation specific
651 * handling, but takes care of most of common retry
652 * execution details for a given iocb. The retry method
653 * needs to be non-blocking as far as possible, to avoid
654 * holding up other iocbs waiting to be serviced by the
655 * retry kernel thread.
656 *
657 * The trickier parts in this code have to do with
658 * ensuring that only one retry instance is in progress
659 * for a given iocb at any time. Providing that guarantee
660 * simplifies the coding of individual aio operations as
661 * it avoids various potential races.
662 */
663static ssize_t aio_run_iocb(struct kiocb *iocb)
664{
665 struct kioctx *ctx = iocb->ki_ctx;
666 ssize_t (*retry)(struct kiocb *);
667 ssize_t ret;
668
Linus Torvalds1da177e2005-04-16 15:20:36 -0700669 if (!(retry = iocb->ki_retry)) {
670 printk("aio_run_iocb: iocb->ki_retry = NULL\n");
671 return 0;
672 }
673
674 /*
675 * We don't want the next retry iteration for this
676 * operation to start until this one has returned and
677 * updated the iocb state. However, wait_queue functions
678 * can trigger a kick_iocb from interrupt context in the
679 * meantime, indicating that data is available for the next
680 * iteration. We want to remember that and enable the
681 * next retry iteration _after_ we are through with
682 * this one.
683 *
684 * So, in order to be able to register a "kick", but
685 * prevent it from being queued now, we clear the kick
686 * flag, but make the kick code *think* that the iocb is
687 * still on the run list until we are actually done.
688 * When we are done with this iteration, we check if
689 * the iocb was kicked in the meantime and if so, queue
690 * it up afresh.
691 */
692
693 kiocbClearKicked(iocb);
694
695 /*
696 * This is so that aio_complete knows it doesn't need to
697 * pull the iocb off the run list (We can't just call
698 * INIT_LIST_HEAD because we don't want a kick_iocb to
699 * queue this on the run list yet)
700 */
701 iocb->ki_run_list.next = iocb->ki_run_list.prev = NULL;
702 spin_unlock_irq(&ctx->ctx_lock);
703
704 /* Quit retrying if the i/o has been cancelled */
705 if (kiocbIsCancelled(iocb)) {
706 ret = -EINTR;
707 aio_complete(iocb, ret, 0);
708 /* must not access the iocb after this */
709 goto out;
710 }
711
712 /*
713 * Now we are all set to call the retry method in async
714 * context. By setting this thread's io_wait context
715 * to point to the wait queue entry inside the currently
716 * running iocb for the duration of the retry, we ensure
717 * that async notification wakeups are queued by the
718 * operation instead of blocking waits, and when notified,
719 * cause the iocb to be kicked for continuation (through
720 * the aio_wake_function callback).
721 */
722 BUG_ON(current->io_wait != NULL);
723 current->io_wait = &iocb->ki_wait;
724 ret = retry(iocb);
725 current->io_wait = NULL;
726
Zach Brown897f15f2005-09-30 11:58:55 -0700727 if (ret != -EIOCBRETRY && ret != -EIOCBQUEUED) {
728 BUG_ON(!list_empty(&iocb->ki_wait.task_list));
729 aio_complete(iocb, ret, 0);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700730 }
731out:
732 spin_lock_irq(&ctx->ctx_lock);
733
734 if (-EIOCBRETRY == ret) {
735 /*
736 * OK, now that we are done with this iteration
737 * and know that there is more left to go,
738 * this is where we let go so that a subsequent
739 * "kick" can start the next iteration
740 */
741
742 /* will make __queue_kicked_iocb succeed from here on */
743 INIT_LIST_HEAD(&iocb->ki_run_list);
744 /* we must queue the next iteration ourselves, if it
745 * has already been kicked */
746 if (kiocbIsKicked(iocb)) {
747 __queue_kicked_iocb(iocb);
Sébastien Duguc016e222005-06-28 20:44:59 -0700748
749 /*
750 * __queue_kicked_iocb will always return 1 here, because
751 * iocb->ki_run_list is empty at this point so it should
752 * be safe to unconditionally queue the context into the
753 * work queue.
754 */
755 aio_queue_work(ctx);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700756 }
757 }
758 return ret;
759}
760
761/*
762 * __aio_run_iocbs:
763 * Process all pending retries queued on the ioctx
764 * run list.
765 * Assumes it is operating within the aio issuer's mm
Zach Brownd00689a2005-11-13 16:07:34 -0800766 * context.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700767 */
768static int __aio_run_iocbs(struct kioctx *ctx)
769{
770 struct kiocb *iocb;
Oleg Nesterov626ab0e2006-06-23 02:05:55 -0700771 struct list_head run_list;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700772
Zach Brownd00689a2005-11-13 16:07:34 -0800773 assert_spin_locked(&ctx->ctx_lock);
774
Oleg Nesterov626ab0e2006-06-23 02:05:55 -0700775 list_replace_init(&ctx->run_list, &run_list);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700776 while (!list_empty(&run_list)) {
777 iocb = list_entry(run_list.next, struct kiocb,
778 ki_run_list);
779 list_del(&iocb->ki_run_list);
780 /*
781 * Hold an extra reference while retrying i/o.
782 */
783 iocb->ki_users++; /* grab extra reference */
784 aio_run_iocb(iocb);
785 if (__aio_put_req(ctx, iocb)) /* drop extra ref */
786 put_ioctx(ctx);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700787 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700788 if (!list_empty(&ctx->run_list))
789 return 1;
790 return 0;
791}
792
793static void aio_queue_work(struct kioctx * ctx)
794{
795 unsigned long timeout;
796 /*
797 * if someone is waiting, get the work started right
798 * away, otherwise, use a longer delay
799 */
800 smp_mb();
801 if (waitqueue_active(&ctx->wait))
802 timeout = 1;
803 else
804 timeout = HZ/10;
805 queue_delayed_work(aio_wq, &ctx->wq, timeout);
806}
807
808
809/*
810 * aio_run_iocbs:
811 * Process all pending retries queued on the ioctx
812 * run list.
813 * Assumes it is operating within the aio issuer's mm
814 * context.
815 */
816static inline void aio_run_iocbs(struct kioctx *ctx)
817{
818 int requeue;
819
820 spin_lock_irq(&ctx->ctx_lock);
821
822 requeue = __aio_run_iocbs(ctx);
823 spin_unlock_irq(&ctx->ctx_lock);
824 if (requeue)
825 aio_queue_work(ctx);
826}
827
828/*
829 * just like aio_run_iocbs, but keeps running them until
830 * the list stays empty
831 */
832static inline void aio_run_all_iocbs(struct kioctx *ctx)
833{
834 spin_lock_irq(&ctx->ctx_lock);
835 while (__aio_run_iocbs(ctx))
836 ;
837 spin_unlock_irq(&ctx->ctx_lock);
838}
839
840/*
841 * aio_kick_handler:
842 * Work queue handler triggered to process pending
843 * retries on an ioctx. Takes on the aio issuer's
844 * mm context before running the iocbs, so that
845 * copy_xxx_user operates on the issuer's address
846 * space.
847 * Run on aiod's context.
848 */
David Howells65f27f32006-11-22 14:55:48 +0000849static void aio_kick_handler(struct work_struct *work)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700850{
David Howells65f27f32006-11-22 14:55:48 +0000851 struct kioctx *ctx = container_of(work, struct kioctx, wq.work);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700852 mm_segment_t oldfs = get_fs();
853 int requeue;
854
855 set_fs(USER_DS);
856 use_mm(ctx->mm);
857 spin_lock_irq(&ctx->ctx_lock);
858 requeue =__aio_run_iocbs(ctx);
859 unuse_mm(ctx->mm);
860 spin_unlock_irq(&ctx->ctx_lock);
861 set_fs(oldfs);
862 /*
863 * we're in a worker thread already, don't use queue_delayed_work,
864 */
865 if (requeue)
David Howells52bad642006-11-22 14:54:01 +0000866 queue_delayed_work(aio_wq, &ctx->wq, 0);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700867}
868
869
870/*
871 * Called by kick_iocb to queue the kiocb for retry
872 * and if required activate the aio work queue to process
873 * it
874 */
Zach Brown998765e2005-09-30 11:58:54 -0700875static void try_queue_kicked_iocb(struct kiocb *iocb)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700876{
877 struct kioctx *ctx = iocb->ki_ctx;
878 unsigned long flags;
879 int run = 0;
880
Zach Brown998765e2005-09-30 11:58:54 -0700881 /* We're supposed to be the only path putting the iocb back on the run
882 * list. If we find that the iocb is *back* on a wait queue already
883 * than retry has happened before we could queue the iocb. This also
884 * means that the retry could have completed and freed our iocb, no
885 * good. */
886 BUG_ON((!list_empty(&iocb->ki_wait.task_list)));
Linus Torvalds1da177e2005-04-16 15:20:36 -0700887
888 spin_lock_irqsave(&ctx->ctx_lock, flags);
Zach Brown998765e2005-09-30 11:58:54 -0700889 /* set this inside the lock so that we can't race with aio_run_iocb()
890 * testing it and putting the iocb on the run list under the lock */
891 if (!kiocbTryKick(iocb))
892 run = __queue_kicked_iocb(iocb);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700893 spin_unlock_irqrestore(&ctx->ctx_lock, flags);
Ken Chen644d3a02005-05-01 08:59:15 -0700894 if (run)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700895 aio_queue_work(ctx);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700896}
897
898/*
899 * kick_iocb:
900 * Called typically from a wait queue callback context
901 * (aio_wake_function) to trigger a retry of the iocb.
902 * The retry is usually executed by aio workqueue
903 * threads (See aio_kick_handler).
904 */
905void fastcall kick_iocb(struct kiocb *iocb)
906{
907 /* sync iocbs are easy: they can only ever be executing from a
908 * single context. */
909 if (is_sync_kiocb(iocb)) {
910 kiocbSetKicked(iocb);
911 wake_up_process(iocb->ki_obj.tsk);
912 return;
913 }
914
Zach Brown998765e2005-09-30 11:58:54 -0700915 try_queue_kicked_iocb(iocb);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700916}
917EXPORT_SYMBOL(kick_iocb);
918
919/* aio_complete
920 * Called when the io request on the given iocb is complete.
921 * Returns true if this is the last user of the request. The
922 * only other user of the request can be the cancellation code.
923 */
924int fastcall aio_complete(struct kiocb *iocb, long res, long res2)
925{
926 struct kioctx *ctx = iocb->ki_ctx;
927 struct aio_ring_info *info;
928 struct aio_ring *ring;
929 struct io_event *event;
930 unsigned long flags;
931 unsigned long tail;
932 int ret;
933
Zach Brown20dcae32005-11-13 16:07:33 -0800934 /*
935 * Special case handling for sync iocbs:
936 * - events go directly into the iocb for fast handling
937 * - the sync task with the iocb in its stack holds the single iocb
938 * ref, no other paths have a way to get another ref
939 * - the sync task helpfully left a reference to itself in the iocb
Linus Torvalds1da177e2005-04-16 15:20:36 -0700940 */
941 if (is_sync_kiocb(iocb)) {
Zach Brown20dcae32005-11-13 16:07:33 -0800942 BUG_ON(iocb->ki_users != 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700943 iocb->ki_user_data = res;
Zach Brown20dcae32005-11-13 16:07:33 -0800944 iocb->ki_users = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700945 wake_up_process(iocb->ki_obj.tsk);
Zach Brown20dcae32005-11-13 16:07:33 -0800946 return 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700947 }
948
949 info = &ctx->ring_info;
950
951 /* add a completion event to the ring buffer.
952 * must be done holding ctx->ctx_lock to prevent
953 * other code from messing with the tail
954 * pointer since we might be called from irq
955 * context.
956 */
957 spin_lock_irqsave(&ctx->ctx_lock, flags);
958
959 if (iocb->ki_run_list.prev && !list_empty(&iocb->ki_run_list))
960 list_del_init(&iocb->ki_run_list);
961
962 /*
963 * cancelled requests don't get events, userland was given one
964 * when the event got cancelled.
965 */
966 if (kiocbIsCancelled(iocb))
967 goto put_rq;
968
969 ring = kmap_atomic(info->ring_pages[0], KM_IRQ1);
970
971 tail = info->tail;
972 event = aio_ring_event(info, tail, KM_IRQ0);
Ken Chen4bf69b22005-05-01 08:59:15 -0700973 if (++tail >= info->nr)
974 tail = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700975
976 event->obj = (u64)(unsigned long)iocb->ki_obj.user;
977 event->data = iocb->ki_user_data;
978 event->res = res;
979 event->res2 = res2;
980
981 dprintk("aio_complete: %p[%lu]: %p: %p %Lx %lx %lx\n",
982 ctx, tail, iocb, iocb->ki_obj.user, iocb->ki_user_data,
983 res, res2);
984
985 /* after flagging the request as done, we
986 * must never even look at it again
987 */
988 smp_wmb(); /* make event visible before updating tail */
989
990 info->tail = tail;
991 ring->tail = tail;
992
993 put_aio_ring_event(event, KM_IRQ0);
994 kunmap_atomic(ring, KM_IRQ1);
995
996 pr_debug("added to ring %p at [%lu]\n", iocb, tail);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700997put_rq:
998 /* everything turned out well, dispose of the aiocb. */
999 ret = __aio_put_req(ctx, iocb);
1000
1001 spin_unlock_irqrestore(&ctx->ctx_lock, flags);
1002
1003 if (waitqueue_active(&ctx->wait))
1004 wake_up(&ctx->wait);
1005
1006 if (ret)
1007 put_ioctx(ctx);
1008
1009 return ret;
1010}
1011
1012/* aio_read_evt
1013 * Pull an event off of the ioctx's event ring. Returns the number of
1014 * events fetched (0 or 1 ;-)
1015 * FIXME: make this use cmpxchg.
1016 * TODO: make the ringbuffer user mmap()able (requires FIXME).
1017 */
1018static int aio_read_evt(struct kioctx *ioctx, struct io_event *ent)
1019{
1020 struct aio_ring_info *info = &ioctx->ring_info;
1021 struct aio_ring *ring;
1022 unsigned long head;
1023 int ret = 0;
1024
1025 ring = kmap_atomic(info->ring_pages[0], KM_USER0);
1026 dprintk("in aio_read_evt h%lu t%lu m%lu\n",
1027 (unsigned long)ring->head, (unsigned long)ring->tail,
1028 (unsigned long)ring->nr);
1029
1030 if (ring->head == ring->tail)
1031 goto out;
1032
1033 spin_lock(&info->ring_lock);
1034
1035 head = ring->head % info->nr;
1036 if (head != ring->tail) {
1037 struct io_event *evp = aio_ring_event(info, head, KM_USER1);
1038 *ent = *evp;
1039 head = (head + 1) % info->nr;
1040 smp_mb(); /* finish reading the event before updatng the head */
1041 ring->head = head;
1042 ret = 1;
1043 put_aio_ring_event(evp, KM_USER1);
1044 }
1045 spin_unlock(&info->ring_lock);
1046
1047out:
1048 kunmap_atomic(ring, KM_USER0);
1049 dprintk("leaving aio_read_evt: %d h%lu t%lu\n", ret,
1050 (unsigned long)ring->head, (unsigned long)ring->tail);
1051 return ret;
1052}
1053
1054struct aio_timeout {
1055 struct timer_list timer;
1056 int timed_out;
1057 struct task_struct *p;
1058};
1059
1060static void timeout_func(unsigned long data)
1061{
1062 struct aio_timeout *to = (struct aio_timeout *)data;
1063
1064 to->timed_out = 1;
1065 wake_up_process(to->p);
1066}
1067
1068static inline void init_timeout(struct aio_timeout *to)
1069{
1070 init_timer(&to->timer);
1071 to->timer.data = (unsigned long)to;
1072 to->timer.function = timeout_func;
1073 to->timed_out = 0;
1074 to->p = current;
1075}
1076
1077static inline void set_timeout(long start_jiffies, struct aio_timeout *to,
1078 const struct timespec *ts)
1079{
1080 to->timer.expires = start_jiffies + timespec_to_jiffies(ts);
1081 if (time_after(to->timer.expires, jiffies))
1082 add_timer(&to->timer);
1083 else
1084 to->timed_out = 1;
1085}
1086
1087static inline void clear_timeout(struct aio_timeout *to)
1088{
1089 del_singleshot_timer_sync(&to->timer);
1090}
1091
1092static int read_events(struct kioctx *ctx,
1093 long min_nr, long nr,
1094 struct io_event __user *event,
1095 struct timespec __user *timeout)
1096{
1097 long start_jiffies = jiffies;
1098 struct task_struct *tsk = current;
1099 DECLARE_WAITQUEUE(wait, tsk);
1100 int ret;
1101 int i = 0;
1102 struct io_event ent;
1103 struct aio_timeout to;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001104 int retry = 0;
1105
1106 /* needed to zero any padding within an entry (there shouldn't be
1107 * any, but C is fun!
1108 */
1109 memset(&ent, 0, sizeof(ent));
1110retry:
1111 ret = 0;
1112 while (likely(i < nr)) {
1113 ret = aio_read_evt(ctx, &ent);
1114 if (unlikely(ret <= 0))
1115 break;
1116
1117 dprintk("read event: %Lx %Lx %Lx %Lx\n",
1118 ent.data, ent.obj, ent.res, ent.res2);
1119
1120 /* Could we split the check in two? */
1121 ret = -EFAULT;
1122 if (unlikely(copy_to_user(event, &ent, sizeof(ent)))) {
1123 dprintk("aio: lost an event due to EFAULT.\n");
1124 break;
1125 }
1126 ret = 0;
1127
1128 /* Good, event copied to userland, update counts. */
1129 event ++;
1130 i ++;
1131 }
1132
1133 if (min_nr <= i)
1134 return i;
1135 if (ret)
1136 return ret;
1137
1138 /* End fast path */
1139
1140 /* racey check, but it gets redone */
1141 if (!retry && unlikely(!list_empty(&ctx->run_list))) {
1142 retry = 1;
1143 aio_run_all_iocbs(ctx);
1144 goto retry;
1145 }
1146
1147 init_timeout(&to);
1148 if (timeout) {
1149 struct timespec ts;
1150 ret = -EFAULT;
1151 if (unlikely(copy_from_user(&ts, timeout, sizeof(ts))))
1152 goto out;
1153
1154 set_timeout(start_jiffies, &to, &ts);
1155 }
1156
1157 while (likely(i < nr)) {
1158 add_wait_queue_exclusive(&ctx->wait, &wait);
1159 do {
1160 set_task_state(tsk, TASK_INTERRUPTIBLE);
1161 ret = aio_read_evt(ctx, &ent);
1162 if (ret)
1163 break;
1164 if (min_nr <= i)
1165 break;
1166 ret = 0;
1167 if (to.timed_out) /* Only check after read evt */
1168 break;
1169 schedule();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001170 if (signal_pending(tsk)) {
1171 ret = -EINTR;
1172 break;
1173 }
1174 /*ret = aio_read_evt(ctx, &ent);*/
1175 } while (1) ;
1176
1177 set_task_state(tsk, TASK_RUNNING);
1178 remove_wait_queue(&ctx->wait, &wait);
1179
1180 if (unlikely(ret <= 0))
1181 break;
1182
1183 ret = -EFAULT;
1184 if (unlikely(copy_to_user(event, &ent, sizeof(ent)))) {
1185 dprintk("aio: lost an event due to EFAULT.\n");
1186 break;
1187 }
1188
1189 /* Good, event copied to userland, update counts. */
1190 event ++;
1191 i ++;
1192 }
1193
1194 if (timeout)
1195 clear_timeout(&to);
1196out:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001197 return i ? i : ret;
1198}
1199
1200/* Take an ioctx and remove it from the list of ioctx's. Protects
1201 * against races with itself via ->dead.
1202 */
1203static void io_destroy(struct kioctx *ioctx)
1204{
1205 struct mm_struct *mm = current->mm;
1206 struct kioctx **tmp;
1207 int was_dead;
1208
1209 /* delete the entry from the list is someone else hasn't already */
1210 write_lock(&mm->ioctx_list_lock);
1211 was_dead = ioctx->dead;
1212 ioctx->dead = 1;
1213 for (tmp = &mm->ioctx_list; *tmp && *tmp != ioctx;
1214 tmp = &(*tmp)->next)
1215 ;
1216 if (*tmp)
1217 *tmp = ioctx->next;
1218 write_unlock(&mm->ioctx_list_lock);
1219
1220 dprintk("aio_release(%p)\n", ioctx);
1221 if (likely(!was_dead))
1222 put_ioctx(ioctx); /* twice for the list */
1223
1224 aio_cancel_all(ioctx);
1225 wait_for_all_aios(ioctx);
1226 put_ioctx(ioctx); /* once for the lookup */
1227}
1228
1229/* sys_io_setup:
1230 * Create an aio_context capable of receiving at least nr_events.
1231 * ctxp must not point to an aio_context that already exists, and
1232 * must be initialized to 0 prior to the call. On successful
1233 * creation of the aio_context, *ctxp is filled in with the resulting
1234 * handle. May fail with -EINVAL if *ctxp is not initialized,
1235 * if the specified nr_events exceeds internal limits. May fail
1236 * with -EAGAIN if the specified nr_events exceeds the user's limit
1237 * of available events. May fail with -ENOMEM if insufficient kernel
1238 * resources are available. May fail with -EFAULT if an invalid
1239 * pointer is passed for ctxp. Will fail with -ENOSYS if not
1240 * implemented.
1241 */
1242asmlinkage long sys_io_setup(unsigned nr_events, aio_context_t __user *ctxp)
1243{
1244 struct kioctx *ioctx = NULL;
1245 unsigned long ctx;
1246 long ret;
1247
1248 ret = get_user(ctx, ctxp);
1249 if (unlikely(ret))
1250 goto out;
1251
1252 ret = -EINVAL;
Zach Brownd55b5fd2005-11-07 00:59:31 -08001253 if (unlikely(ctx || nr_events == 0)) {
1254 pr_debug("EINVAL: io_setup: ctx %lu nr_events %u\n",
1255 ctx, nr_events);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001256 goto out;
1257 }
1258
1259 ioctx = ioctx_alloc(nr_events);
1260 ret = PTR_ERR(ioctx);
1261 if (!IS_ERR(ioctx)) {
1262 ret = put_user(ioctx->user_id, ctxp);
1263 if (!ret)
1264 return 0;
1265
1266 get_ioctx(ioctx); /* io_destroy() expects us to hold a ref */
1267 io_destroy(ioctx);
1268 }
1269
1270out:
1271 return ret;
1272}
1273
1274/* sys_io_destroy:
1275 * Destroy the aio_context specified. May cancel any outstanding
1276 * AIOs and block on completion. Will fail with -ENOSYS if not
1277 * implemented. May fail with -EFAULT if the context pointed to
1278 * is invalid.
1279 */
1280asmlinkage long sys_io_destroy(aio_context_t ctx)
1281{
1282 struct kioctx *ioctx = lookup_ioctx(ctx);
1283 if (likely(NULL != ioctx)) {
1284 io_destroy(ioctx);
1285 return 0;
1286 }
1287 pr_debug("EINVAL: io_destroy: invalid context id\n");
1288 return -EINVAL;
1289}
1290
Badari Pulavartyeed4e512006-09-30 23:28:49 -07001291static void aio_advance_iovec(struct kiocb *iocb, ssize_t ret)
1292{
1293 struct iovec *iov = &iocb->ki_iovec[iocb->ki_cur_seg];
1294
1295 BUG_ON(ret <= 0);
1296
1297 while (iocb->ki_cur_seg < iocb->ki_nr_segs && ret > 0) {
1298 ssize_t this = min((ssize_t)iov->iov_len, ret);
1299 iov->iov_base += this;
1300 iov->iov_len -= this;
1301 iocb->ki_left -= this;
1302 ret -= this;
1303 if (iov->iov_len == 0) {
1304 iocb->ki_cur_seg++;
1305 iov++;
1306 }
1307 }
1308
1309 /* the caller should not have done more io than what fit in
1310 * the remaining iovecs */
1311 BUG_ON(ret > 0 && iocb->ki_left == 0);
1312}
1313
1314static ssize_t aio_rw_vect_retry(struct kiocb *iocb)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001315{
1316 struct file *file = iocb->ki_filp;
1317 struct address_space *mapping = file->f_mapping;
1318 struct inode *inode = mapping->host;
Badari Pulavartyeed4e512006-09-30 23:28:49 -07001319 ssize_t (*rw_op)(struct kiocb *, const struct iovec *,
1320 unsigned long, loff_t);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001321 ssize_t ret = 0;
Badari Pulavartyeed4e512006-09-30 23:28:49 -07001322 unsigned short opcode;
1323
1324 if ((iocb->ki_opcode == IOCB_CMD_PREADV) ||
1325 (iocb->ki_opcode == IOCB_CMD_PREAD)) {
1326 rw_op = file->f_op->aio_read;
1327 opcode = IOCB_CMD_PREADV;
1328 } else {
1329 rw_op = file->f_op->aio_write;
1330 opcode = IOCB_CMD_PWRITEV;
1331 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001332
Zach Brown897f15f2005-09-30 11:58:55 -07001333 do {
Badari Pulavartyeed4e512006-09-30 23:28:49 -07001334 ret = rw_op(iocb, &iocb->ki_iovec[iocb->ki_cur_seg],
1335 iocb->ki_nr_segs - iocb->ki_cur_seg,
1336 iocb->ki_pos);
1337 if (ret > 0)
1338 aio_advance_iovec(iocb, ret);
Badari Pulavarty027445c2006-09-30 23:28:46 -07001339
Badari Pulavartyeed4e512006-09-30 23:28:49 -07001340 /* retry all partial writes. retry partial reads as long as its a
1341 * regular file. */
Zach Brown353fb072005-09-30 11:58:56 -07001342 } while (ret > 0 && iocb->ki_left > 0 &&
Badari Pulavartyeed4e512006-09-30 23:28:49 -07001343 (opcode == IOCB_CMD_PWRITEV ||
1344 (!S_ISFIFO(inode->i_mode) && !S_ISSOCK(inode->i_mode))));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001345
1346 /* This means we must have transferred all that we could */
1347 /* No need to retry anymore */
1348 if ((ret == 0) || (iocb->ki_left == 0))
1349 ret = iocb->ki_nbytes - iocb->ki_left;
1350
1351 return ret;
1352}
1353
Linus Torvalds1da177e2005-04-16 15:20:36 -07001354static ssize_t aio_fdsync(struct kiocb *iocb)
1355{
1356 struct file *file = iocb->ki_filp;
1357 ssize_t ret = -EINVAL;
1358
1359 if (file->f_op->aio_fsync)
1360 ret = file->f_op->aio_fsync(iocb, 1);
1361 return ret;
1362}
1363
1364static ssize_t aio_fsync(struct kiocb *iocb)
1365{
1366 struct file *file = iocb->ki_filp;
1367 ssize_t ret = -EINVAL;
1368
1369 if (file->f_op->aio_fsync)
1370 ret = file->f_op->aio_fsync(iocb, 0);
1371 return ret;
1372}
1373
Badari Pulavartyeed4e512006-09-30 23:28:49 -07001374static ssize_t aio_setup_vectored_rw(int type, struct kiocb *kiocb)
1375{
1376 ssize_t ret;
1377
1378 ret = rw_copy_check_uvector(type, (struct iovec __user *)kiocb->ki_buf,
1379 kiocb->ki_nbytes, 1,
1380 &kiocb->ki_inline_vec, &kiocb->ki_iovec);
1381 if (ret < 0)
1382 goto out;
1383
1384 kiocb->ki_nr_segs = kiocb->ki_nbytes;
1385 kiocb->ki_cur_seg = 0;
1386 /* ki_nbytes/left now reflect bytes instead of segs */
1387 kiocb->ki_nbytes = ret;
1388 kiocb->ki_left = ret;
1389
1390 ret = 0;
1391out:
1392 return ret;
1393}
1394
1395static ssize_t aio_setup_single_vector(struct kiocb *kiocb)
1396{
1397 kiocb->ki_iovec = &kiocb->ki_inline_vec;
1398 kiocb->ki_iovec->iov_base = kiocb->ki_buf;
1399 kiocb->ki_iovec->iov_len = kiocb->ki_left;
1400 kiocb->ki_nr_segs = 1;
1401 kiocb->ki_cur_seg = 0;
Badari Pulavartyeed4e512006-09-30 23:28:49 -07001402 return 0;
1403}
1404
Linus Torvalds1da177e2005-04-16 15:20:36 -07001405/*
1406 * aio_setup_iocb:
1407 * Performs the initial checks and aio retry method
1408 * setup for the kiocb at the time of io submission.
1409 */
Adrian Bunk25ee7e32005-04-25 08:18:14 -07001410static ssize_t aio_setup_iocb(struct kiocb *kiocb)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001411{
1412 struct file *file = kiocb->ki_filp;
1413 ssize_t ret = 0;
1414
1415 switch (kiocb->ki_opcode) {
1416 case IOCB_CMD_PREAD:
1417 ret = -EBADF;
1418 if (unlikely(!(file->f_mode & FMODE_READ)))
1419 break;
1420 ret = -EFAULT;
1421 if (unlikely(!access_ok(VERIFY_WRITE, kiocb->ki_buf,
1422 kiocb->ki_left)))
1423 break;
Kostik Belousov8766ce42005-10-23 12:57:13 -07001424 ret = security_file_permission(file, MAY_READ);
1425 if (unlikely(ret))
1426 break;
Badari Pulavartyeed4e512006-09-30 23:28:49 -07001427 ret = aio_setup_single_vector(kiocb);
1428 if (ret)
1429 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001430 ret = -EINVAL;
1431 if (file->f_op->aio_read)
Badari Pulavartyeed4e512006-09-30 23:28:49 -07001432 kiocb->ki_retry = aio_rw_vect_retry;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001433 break;
1434 case IOCB_CMD_PWRITE:
1435 ret = -EBADF;
1436 if (unlikely(!(file->f_mode & FMODE_WRITE)))
1437 break;
1438 ret = -EFAULT;
1439 if (unlikely(!access_ok(VERIFY_READ, kiocb->ki_buf,
1440 kiocb->ki_left)))
1441 break;
Kostik Belousov8766ce42005-10-23 12:57:13 -07001442 ret = security_file_permission(file, MAY_WRITE);
1443 if (unlikely(ret))
1444 break;
Badari Pulavartyeed4e512006-09-30 23:28:49 -07001445 ret = aio_setup_single_vector(kiocb);
1446 if (ret)
1447 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001448 ret = -EINVAL;
1449 if (file->f_op->aio_write)
Badari Pulavartyeed4e512006-09-30 23:28:49 -07001450 kiocb->ki_retry = aio_rw_vect_retry;
1451 break;
1452 case IOCB_CMD_PREADV:
1453 ret = -EBADF;
1454 if (unlikely(!(file->f_mode & FMODE_READ)))
1455 break;
1456 ret = security_file_permission(file, MAY_READ);
1457 if (unlikely(ret))
1458 break;
1459 ret = aio_setup_vectored_rw(READ, kiocb);
1460 if (ret)
1461 break;
1462 ret = -EINVAL;
1463 if (file->f_op->aio_read)
1464 kiocb->ki_retry = aio_rw_vect_retry;
1465 break;
1466 case IOCB_CMD_PWRITEV:
1467 ret = -EBADF;
1468 if (unlikely(!(file->f_mode & FMODE_WRITE)))
1469 break;
1470 ret = security_file_permission(file, MAY_WRITE);
1471 if (unlikely(ret))
1472 break;
1473 ret = aio_setup_vectored_rw(WRITE, kiocb);
1474 if (ret)
1475 break;
1476 ret = -EINVAL;
1477 if (file->f_op->aio_write)
1478 kiocb->ki_retry = aio_rw_vect_retry;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001479 break;
1480 case IOCB_CMD_FDSYNC:
1481 ret = -EINVAL;
1482 if (file->f_op->aio_fsync)
1483 kiocb->ki_retry = aio_fdsync;
1484 break;
1485 case IOCB_CMD_FSYNC:
1486 ret = -EINVAL;
1487 if (file->f_op->aio_fsync)
1488 kiocb->ki_retry = aio_fsync;
1489 break;
1490 default:
1491 dprintk("EINVAL: io_submit: no operation provided\n");
1492 ret = -EINVAL;
1493 }
1494
1495 if (!kiocb->ki_retry)
1496 return ret;
1497
1498 return 0;
1499}
1500
1501/*
1502 * aio_wake_function:
1503 * wait queue callback function for aio notification,
1504 * Simply triggers a retry of the operation via kick_iocb.
1505 *
1506 * This callback is specified in the wait queue entry in
1507 * a kiocb (current->io_wait points to this wait queue
1508 * entry when an aio operation executes; it is used
1509 * instead of a synchronous wait when an i/o blocking
1510 * condition is encountered during aio).
1511 *
1512 * Note:
1513 * This routine is executed with the wait queue lock held.
1514 * Since kick_iocb acquires iocb->ctx->ctx_lock, it nests
1515 * the ioctx lock inside the wait queue lock. This is safe
1516 * because this callback isn't used for wait queues which
1517 * are nested inside ioctx lock (i.e. ctx->wait)
1518 */
Adrian Bunk25ee7e32005-04-25 08:18:14 -07001519static int aio_wake_function(wait_queue_t *wait, unsigned mode,
1520 int sync, void *key)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001521{
1522 struct kiocb *iocb = container_of(wait, struct kiocb, ki_wait);
1523
1524 list_del_init(&wait->task_list);
1525 kick_iocb(iocb);
1526 return 1;
1527}
1528
1529int fastcall io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb,
1530 struct iocb *iocb)
1531{
1532 struct kiocb *req;
1533 struct file *file;
1534 ssize_t ret;
1535
1536 /* enforce forwards compatibility on users */
1537 if (unlikely(iocb->aio_reserved1 || iocb->aio_reserved2 ||
1538 iocb->aio_reserved3)) {
1539 pr_debug("EINVAL: io_submit: reserve field set\n");
1540 return -EINVAL;
1541 }
1542
1543 /* prevent overflows */
1544 if (unlikely(
1545 (iocb->aio_buf != (unsigned long)iocb->aio_buf) ||
1546 (iocb->aio_nbytes != (size_t)iocb->aio_nbytes) ||
1547 ((ssize_t)iocb->aio_nbytes < 0)
1548 )) {
1549 pr_debug("EINVAL: io_submit: overflow check\n");
1550 return -EINVAL;
1551 }
1552
1553 file = fget(iocb->aio_fildes);
1554 if (unlikely(!file))
1555 return -EBADF;
1556
1557 req = aio_get_req(ctx); /* returns with 2 references to req */
1558 if (unlikely(!req)) {
1559 fput(file);
1560 return -EAGAIN;
1561 }
1562
1563 req->ki_filp = file;
Ken Chen212079c2005-05-01 08:59:15 -07001564 ret = put_user(req->ki_key, &user_iocb->aio_key);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001565 if (unlikely(ret)) {
1566 dprintk("EFAULT: aio_key\n");
1567 goto out_put_req;
1568 }
1569
1570 req->ki_obj.user = user_iocb;
1571 req->ki_user_data = iocb->aio_data;
1572 req->ki_pos = iocb->aio_offset;
1573
1574 req->ki_buf = (char __user *)(unsigned long)iocb->aio_buf;
1575 req->ki_left = req->ki_nbytes = iocb->aio_nbytes;
1576 req->ki_opcode = iocb->aio_lio_opcode;
1577 init_waitqueue_func_entry(&req->ki_wait, aio_wake_function);
1578 INIT_LIST_HEAD(&req->ki_wait.task_list);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001579
1580 ret = aio_setup_iocb(req);
1581
1582 if (ret)
1583 goto out_put_req;
1584
1585 spin_lock_irq(&ctx->ctx_lock);
Benjamin LaHaiseac0b1bc2005-09-09 13:02:09 -07001586 aio_run_iocb(req);
Benjamin LaHaiseac0b1bc2005-09-09 13:02:09 -07001587 if (!list_empty(&ctx->run_list)) {
Ken Chen954d3e92005-05-01 08:59:16 -07001588 /* drain the run list */
1589 while (__aio_run_iocbs(ctx))
1590 ;
1591 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001592 spin_unlock_irq(&ctx->ctx_lock);
1593 aio_put_req(req); /* drop extra ref to req */
1594 return 0;
1595
1596out_put_req:
1597 aio_put_req(req); /* drop extra ref to req */
1598 aio_put_req(req); /* drop i/o ref to req */
1599 return ret;
1600}
1601
1602/* sys_io_submit:
1603 * Queue the nr iocbs pointed to by iocbpp for processing. Returns
1604 * the number of iocbs queued. May return -EINVAL if the aio_context
1605 * specified by ctx_id is invalid, if nr is < 0, if the iocb at
1606 * *iocbpp[0] is not properly initialized, if the operation specified
1607 * is invalid for the file descriptor in the iocb. May fail with
1608 * -EFAULT if any of the data structures point to invalid data. May
1609 * fail with -EBADF if the file descriptor specified in the first
1610 * iocb is invalid. May fail with -EAGAIN if insufficient resources
1611 * are available to queue any iocbs. Will return 0 if nr is 0. Will
1612 * fail with -ENOSYS if not implemented.
1613 */
1614asmlinkage long sys_io_submit(aio_context_t ctx_id, long nr,
1615 struct iocb __user * __user *iocbpp)
1616{
1617 struct kioctx *ctx;
1618 long ret = 0;
1619 int i;
1620
1621 if (unlikely(nr < 0))
1622 return -EINVAL;
1623
1624 if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))
1625 return -EFAULT;
1626
1627 ctx = lookup_ioctx(ctx_id);
1628 if (unlikely(!ctx)) {
1629 pr_debug("EINVAL: io_submit: invalid context id\n");
1630 return -EINVAL;
1631 }
1632
1633 /*
1634 * AKPM: should this return a partial result if some of the IOs were
1635 * successfully submitted?
1636 */
1637 for (i=0; i<nr; i++) {
1638 struct iocb __user *user_iocb;
1639 struct iocb tmp;
1640
1641 if (unlikely(__get_user(user_iocb, iocbpp + i))) {
1642 ret = -EFAULT;
1643 break;
1644 }
1645
1646 if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
1647 ret = -EFAULT;
1648 break;
1649 }
1650
1651 ret = io_submit_one(ctx, user_iocb, &tmp);
1652 if (ret)
1653 break;
1654 }
1655
1656 put_ioctx(ctx);
1657 return i ? i : ret;
1658}
1659
1660/* lookup_kiocb
1661 * Finds a given iocb for cancellation.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001662 */
Adrian Bunk25ee7e32005-04-25 08:18:14 -07001663static struct kiocb *lookup_kiocb(struct kioctx *ctx, struct iocb __user *iocb,
1664 u32 key)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001665{
1666 struct list_head *pos;
Zach Brownd00689a2005-11-13 16:07:34 -08001667
1668 assert_spin_locked(&ctx->ctx_lock);
1669
Linus Torvalds1da177e2005-04-16 15:20:36 -07001670 /* TODO: use a hash or array, this sucks. */
1671 list_for_each(pos, &ctx->active_reqs) {
1672 struct kiocb *kiocb = list_kiocb(pos);
1673 if (kiocb->ki_obj.user == iocb && kiocb->ki_key == key)
1674 return kiocb;
1675 }
1676 return NULL;
1677}
1678
1679/* sys_io_cancel:
1680 * Attempts to cancel an iocb previously passed to io_submit. If
1681 * the operation is successfully cancelled, the resulting event is
1682 * copied into the memory pointed to by result without being placed
1683 * into the completion queue and 0 is returned. May fail with
1684 * -EFAULT if any of the data structures pointed to are invalid.
1685 * May fail with -EINVAL if aio_context specified by ctx_id is
1686 * invalid. May fail with -EAGAIN if the iocb specified was not
1687 * cancelled. Will fail with -ENOSYS if not implemented.
1688 */
1689asmlinkage long sys_io_cancel(aio_context_t ctx_id, struct iocb __user *iocb,
1690 struct io_event __user *result)
1691{
1692 int (*cancel)(struct kiocb *iocb, struct io_event *res);
1693 struct kioctx *ctx;
1694 struct kiocb *kiocb;
1695 u32 key;
1696 int ret;
1697
1698 ret = get_user(key, &iocb->aio_key);
1699 if (unlikely(ret))
1700 return -EFAULT;
1701
1702 ctx = lookup_ioctx(ctx_id);
1703 if (unlikely(!ctx))
1704 return -EINVAL;
1705
1706 spin_lock_irq(&ctx->ctx_lock);
1707 ret = -EAGAIN;
1708 kiocb = lookup_kiocb(ctx, iocb, key);
1709 if (kiocb && kiocb->ki_cancel) {
1710 cancel = kiocb->ki_cancel;
1711 kiocb->ki_users ++;
1712 kiocbSetCancelled(kiocb);
1713 } else
1714 cancel = NULL;
1715 spin_unlock_irq(&ctx->ctx_lock);
1716
1717 if (NULL != cancel) {
1718 struct io_event tmp;
1719 pr_debug("calling cancel\n");
1720 memset(&tmp, 0, sizeof(tmp));
1721 tmp.obj = (u64)(unsigned long)kiocb->ki_obj.user;
1722 tmp.data = kiocb->ki_user_data;
1723 ret = cancel(kiocb, &tmp);
1724 if (!ret) {
1725 /* Cancellation succeeded -- copy the result
1726 * into the user's buffer.
1727 */
1728 if (copy_to_user(result, &tmp, sizeof(tmp)))
1729 ret = -EFAULT;
1730 }
1731 } else
Wendy Cheng8f582022005-09-09 13:02:08 -07001732 ret = -EINVAL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001733
1734 put_ioctx(ctx);
1735
1736 return ret;
1737}
1738
1739/* io_getevents:
1740 * Attempts to read at least min_nr events and up to nr events from
1741 * the completion queue for the aio_context specified by ctx_id. May
1742 * fail with -EINVAL if ctx_id is invalid, if min_nr is out of range,
1743 * if nr is out of range, if when is out of range. May fail with
1744 * -EFAULT if any of the memory specified to is invalid. May return
1745 * 0 or < min_nr if no events are available and the timeout specified
1746 * by when has elapsed, where when == NULL specifies an infinite
1747 * timeout. Note that the timeout pointed to by when is relative and
1748 * will be updated if not NULL and the operation blocks. Will fail
1749 * with -ENOSYS if not implemented.
1750 */
1751asmlinkage long sys_io_getevents(aio_context_t ctx_id,
1752 long min_nr,
1753 long nr,
1754 struct io_event __user *events,
1755 struct timespec __user *timeout)
1756{
1757 struct kioctx *ioctx = lookup_ioctx(ctx_id);
1758 long ret = -EINVAL;
1759
1760 if (likely(ioctx)) {
1761 if (likely(min_nr <= nr && min_nr >= 0 && nr >= 0))
1762 ret = read_events(ioctx, min_nr, nr, events, timeout);
1763 put_ioctx(ioctx);
1764 }
1765
1766 return ret;
1767}
1768
1769__initcall(aio_setup);
1770
1771EXPORT_SYMBOL(aio_complete);
1772EXPORT_SYMBOL(aio_put_req);
1773EXPORT_SYMBOL(wait_on_sync_kiocb);