Linux v2.6.13
[linux-2.6/next.git] / fs / aio.c
blob06d7d4390fe7dd8562e8433ce3a29b2b9ee4e241
1 /*
2 * An async IO implementation for Linux
3 * Written by Benjamin LaHaise <bcrl@kvack.org>
5 * Implements an efficient asynchronous io interface.
7 * Copyright 2000, 2001, 2002 Red Hat, Inc. All Rights Reserved.
9 * See ../COPYING for licensing terms.
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>
19 #define DEBUG 0
21 #include <linux/sched.h>
22 #include <linux/fs.h>
23 #include <linux/file.h>
24 #include <linux/mm.h>
25 #include <linux/mman.h>
26 #include <linux/slab.h>
27 #include <linux/timer.h>
28 #include <linux/aio.h>
29 #include <linux/highmem.h>
30 #include <linux/workqueue.h>
31 #include <linux/security.h>
33 #include <asm/kmap_types.h>
34 #include <asm/uaccess.h>
35 #include <asm/mmu_context.h>
37 #if DEBUG > 1
38 #define dprintk printk
39 #else
40 #define dprintk(x...) do { ; } while (0)
41 #endif
43 /*------ sysctl variables----*/
44 atomic_t aio_nr = ATOMIC_INIT(0); /* current system wide number of aio requests */
45 unsigned aio_max_nr = 0x10000; /* system wide maximum number of aio requests */
46 /*----end sysctl variables---*/
48 static kmem_cache_t *kiocb_cachep;
49 static kmem_cache_t *kioctx_cachep;
51 static struct workqueue_struct *aio_wq;
53 /* Used for rare fput completion. */
54 static void aio_fput_routine(void *);
55 static DECLARE_WORK(fput_work, aio_fput_routine, NULL);
57 static DEFINE_SPINLOCK(fput_lock);
58 static LIST_HEAD(fput_head);
60 static void aio_kick_handler(void *);
61 static void aio_queue_work(struct kioctx *);
63 /* aio_setup
64 * Creates the slab caches used by the aio routines, panic on
65 * failure as this is done early during the boot sequence.
67 static int __init aio_setup(void)
69 kiocb_cachep = kmem_cache_create("kiocb", sizeof(struct kiocb),
70 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
71 kioctx_cachep = kmem_cache_create("kioctx", sizeof(struct kioctx),
72 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
74 aio_wq = create_workqueue("aio");
76 pr_debug("aio_setup: sizeof(struct page) = %d\n", (int)sizeof(struct page));
78 return 0;
81 static void aio_free_ring(struct kioctx *ctx)
83 struct aio_ring_info *info = &ctx->ring_info;
84 long i;
86 for (i=0; i<info->nr_pages; i++)
87 put_page(info->ring_pages[i]);
89 if (info->mmap_size) {
90 down_write(&ctx->mm->mmap_sem);
91 do_munmap(ctx->mm, info->mmap_base, info->mmap_size);
92 up_write(&ctx->mm->mmap_sem);
95 if (info->ring_pages && info->ring_pages != info->internal_pages)
96 kfree(info->ring_pages);
97 info->ring_pages = NULL;
98 info->nr = 0;
101 static int aio_setup_ring(struct kioctx *ctx)
103 struct aio_ring *ring;
104 struct aio_ring_info *info = &ctx->ring_info;
105 unsigned nr_events = ctx->max_reqs;
106 unsigned long size;
107 int nr_pages;
109 /* Compensate for the ring buffer's head/tail overlap entry */
110 nr_events += 2; /* 1 is required, 2 for good luck */
112 size = sizeof(struct aio_ring);
113 size += sizeof(struct io_event) * nr_events;
114 nr_pages = (size + PAGE_SIZE-1) >> PAGE_SHIFT;
116 if (nr_pages < 0)
117 return -EINVAL;
119 nr_events = (PAGE_SIZE * nr_pages - sizeof(struct aio_ring)) / sizeof(struct io_event);
121 info->nr = 0;
122 info->ring_pages = info->internal_pages;
123 if (nr_pages > AIO_RING_PAGES) {
124 info->ring_pages = kmalloc(sizeof(struct page *) * nr_pages, GFP_KERNEL);
125 if (!info->ring_pages)
126 return -ENOMEM;
127 memset(info->ring_pages, 0, sizeof(struct page *) * nr_pages);
130 info->mmap_size = nr_pages * PAGE_SIZE;
131 dprintk("attempting mmap of %lu bytes\n", info->mmap_size);
132 down_write(&ctx->mm->mmap_sem);
133 info->mmap_base = do_mmap(NULL, 0, info->mmap_size,
134 PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE,
136 if (IS_ERR((void *)info->mmap_base)) {
137 up_write(&ctx->mm->mmap_sem);
138 printk("mmap err: %ld\n", -info->mmap_base);
139 info->mmap_size = 0;
140 aio_free_ring(ctx);
141 return -EAGAIN;
144 dprintk("mmap address: 0x%08lx\n", info->mmap_base);
145 info->nr_pages = get_user_pages(current, ctx->mm,
146 info->mmap_base, nr_pages,
147 1, 0, info->ring_pages, NULL);
148 up_write(&ctx->mm->mmap_sem);
150 if (unlikely(info->nr_pages != nr_pages)) {
151 aio_free_ring(ctx);
152 return -EAGAIN;
155 ctx->user_id = info->mmap_base;
157 info->nr = nr_events; /* trusted copy */
159 ring = kmap_atomic(info->ring_pages[0], KM_USER0);
160 ring->nr = nr_events; /* user copy */
161 ring->id = ctx->user_id;
162 ring->head = ring->tail = 0;
163 ring->magic = AIO_RING_MAGIC;
164 ring->compat_features = AIO_RING_COMPAT_FEATURES;
165 ring->incompat_features = AIO_RING_INCOMPAT_FEATURES;
166 ring->header_length = sizeof(struct aio_ring);
167 kunmap_atomic(ring, KM_USER0);
169 return 0;
173 /* aio_ring_event: returns a pointer to the event at the given index from
174 * kmap_atomic(, km). Release the pointer with put_aio_ring_event();
176 #define AIO_EVENTS_PER_PAGE (PAGE_SIZE / sizeof(struct io_event))
177 #define AIO_EVENTS_FIRST_PAGE ((PAGE_SIZE - sizeof(struct aio_ring)) / sizeof(struct io_event))
178 #define AIO_EVENTS_OFFSET (AIO_EVENTS_PER_PAGE - AIO_EVENTS_FIRST_PAGE)
180 #define aio_ring_event(info, nr, km) ({ \
181 unsigned pos = (nr) + AIO_EVENTS_OFFSET; \
182 struct io_event *__event; \
183 __event = kmap_atomic( \
184 (info)->ring_pages[pos / AIO_EVENTS_PER_PAGE], km); \
185 __event += pos % AIO_EVENTS_PER_PAGE; \
186 __event; \
189 #define put_aio_ring_event(event, km) do { \
190 struct io_event *__event = (event); \
191 (void)__event; \
192 kunmap_atomic((void *)((unsigned long)__event & PAGE_MASK), km); \
193 } while(0)
195 /* ioctx_alloc
196 * Allocates and initializes an ioctx. Returns an ERR_PTR if it failed.
198 static struct kioctx *ioctx_alloc(unsigned nr_events)
200 struct mm_struct *mm;
201 struct kioctx *ctx;
203 /* Prevent overflows */
204 if ((nr_events > (0x10000000U / sizeof(struct io_event))) ||
205 (nr_events > (0x10000000U / sizeof(struct kiocb)))) {
206 pr_debug("ENOMEM: nr_events too high\n");
207 return ERR_PTR(-EINVAL);
210 if (nr_events > aio_max_nr)
211 return ERR_PTR(-EAGAIN);
213 ctx = kmem_cache_alloc(kioctx_cachep, GFP_KERNEL);
214 if (!ctx)
215 return ERR_PTR(-ENOMEM);
217 memset(ctx, 0, sizeof(*ctx));
218 ctx->max_reqs = nr_events;
219 mm = ctx->mm = current->mm;
220 atomic_inc(&mm->mm_count);
222 atomic_set(&ctx->users, 1);
223 spin_lock_init(&ctx->ctx_lock);
224 spin_lock_init(&ctx->ring_info.ring_lock);
225 init_waitqueue_head(&ctx->wait);
227 INIT_LIST_HEAD(&ctx->active_reqs);
228 INIT_LIST_HEAD(&ctx->run_list);
229 INIT_WORK(&ctx->wq, aio_kick_handler, ctx);
231 if (aio_setup_ring(ctx) < 0)
232 goto out_freectx;
234 /* limit the number of system wide aios */
235 atomic_add(ctx->max_reqs, &aio_nr); /* undone by __put_ioctx */
236 if (unlikely(atomic_read(&aio_nr) > aio_max_nr))
237 goto out_cleanup;
239 /* now link into global list. kludge. FIXME */
240 write_lock(&mm->ioctx_list_lock);
241 ctx->next = mm->ioctx_list;
242 mm->ioctx_list = ctx;
243 write_unlock(&mm->ioctx_list_lock);
245 dprintk("aio: allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
246 ctx, ctx->user_id, current->mm, ctx->ring_info.nr);
247 return ctx;
249 out_cleanup:
250 atomic_sub(ctx->max_reqs, &aio_nr);
251 ctx->max_reqs = 0; /* prevent __put_ioctx from sub'ing aio_nr */
252 __put_ioctx(ctx);
253 return ERR_PTR(-EAGAIN);
255 out_freectx:
256 mmdrop(mm);
257 kmem_cache_free(kioctx_cachep, ctx);
258 ctx = ERR_PTR(-ENOMEM);
260 dprintk("aio: error allocating ioctx %p\n", ctx);
261 return ctx;
264 /* aio_cancel_all
265 * Cancels all outstanding aio requests on an aio context. Used
266 * when the processes owning a context have all exited to encourage
267 * the rapid destruction of the kioctx.
269 static void aio_cancel_all(struct kioctx *ctx)
271 int (*cancel)(struct kiocb *, struct io_event *);
272 struct io_event res;
273 spin_lock_irq(&ctx->ctx_lock);
274 ctx->dead = 1;
275 while (!list_empty(&ctx->active_reqs)) {
276 struct list_head *pos = ctx->active_reqs.next;
277 struct kiocb *iocb = list_kiocb(pos);
278 list_del_init(&iocb->ki_list);
279 cancel = iocb->ki_cancel;
280 kiocbSetCancelled(iocb);
281 if (cancel) {
282 iocb->ki_users++;
283 spin_unlock_irq(&ctx->ctx_lock);
284 cancel(iocb, &res);
285 spin_lock_irq(&ctx->ctx_lock);
288 spin_unlock_irq(&ctx->ctx_lock);
291 static void wait_for_all_aios(struct kioctx *ctx)
293 struct task_struct *tsk = current;
294 DECLARE_WAITQUEUE(wait, tsk);
296 if (!ctx->reqs_active)
297 return;
299 add_wait_queue(&ctx->wait, &wait);
300 set_task_state(tsk, TASK_UNINTERRUPTIBLE);
301 while (ctx->reqs_active) {
302 schedule();
303 set_task_state(tsk, TASK_UNINTERRUPTIBLE);
305 __set_task_state(tsk, TASK_RUNNING);
306 remove_wait_queue(&ctx->wait, &wait);
309 /* wait_on_sync_kiocb:
310 * Waits on the given sync kiocb to complete.
312 ssize_t fastcall wait_on_sync_kiocb(struct kiocb *iocb)
314 while (iocb->ki_users) {
315 set_current_state(TASK_UNINTERRUPTIBLE);
316 if (!iocb->ki_users)
317 break;
318 schedule();
320 __set_current_state(TASK_RUNNING);
321 return iocb->ki_user_data;
324 /* exit_aio: called when the last user of mm goes away. At this point,
325 * there is no way for any new requests to be submited or any of the
326 * io_* syscalls to be called on the context. However, there may be
327 * outstanding requests which hold references to the context; as they
328 * go away, they will call put_ioctx and release any pinned memory
329 * associated with the request (held via struct page * references).
331 void fastcall exit_aio(struct mm_struct *mm)
333 struct kioctx *ctx = mm->ioctx_list;
334 mm->ioctx_list = NULL;
335 while (ctx) {
336 struct kioctx *next = ctx->next;
337 ctx->next = NULL;
338 aio_cancel_all(ctx);
340 wait_for_all_aios(ctx);
342 * this is an overkill, but ensures we don't leave
343 * the ctx on the aio_wq
345 flush_workqueue(aio_wq);
347 if (1 != atomic_read(&ctx->users))
348 printk(KERN_DEBUG
349 "exit_aio:ioctx still alive: %d %d %d\n",
350 atomic_read(&ctx->users), ctx->dead,
351 ctx->reqs_active);
352 put_ioctx(ctx);
353 ctx = next;
357 /* __put_ioctx
358 * Called when the last user of an aio context has gone away,
359 * and the struct needs to be freed.
361 void fastcall __put_ioctx(struct kioctx *ctx)
363 unsigned nr_events = ctx->max_reqs;
365 if (unlikely(ctx->reqs_active))
366 BUG();
368 cancel_delayed_work(&ctx->wq);
369 flush_workqueue(aio_wq);
370 aio_free_ring(ctx);
371 mmdrop(ctx->mm);
372 ctx->mm = NULL;
373 pr_debug("__put_ioctx: freeing %p\n", ctx);
374 kmem_cache_free(kioctx_cachep, ctx);
376 atomic_sub(nr_events, &aio_nr);
379 /* aio_get_req
380 * Allocate a slot for an aio request. Increments the users count
381 * of the kioctx so that the kioctx stays around until all requests are
382 * complete. Returns NULL if no requests are free.
384 * Returns with kiocb->users set to 2. The io submit code path holds
385 * an extra reference while submitting the i/o.
386 * This prevents races between the aio code path referencing the
387 * req (after submitting it) and aio_complete() freeing the req.
389 static struct kiocb *FASTCALL(__aio_get_req(struct kioctx *ctx));
390 static struct kiocb fastcall *__aio_get_req(struct kioctx *ctx)
392 struct kiocb *req = NULL;
393 struct aio_ring *ring;
394 int okay = 0;
396 req = kmem_cache_alloc(kiocb_cachep, GFP_KERNEL);
397 if (unlikely(!req))
398 return NULL;
400 req->ki_flags = 1 << KIF_LOCKED;
401 req->ki_users = 2;
402 req->ki_key = 0;
403 req->ki_ctx = ctx;
404 req->ki_cancel = NULL;
405 req->ki_retry = NULL;
406 req->ki_dtor = NULL;
407 req->private = NULL;
408 INIT_LIST_HEAD(&req->ki_run_list);
410 /* Check if the completion queue has enough free space to
411 * accept an event from this io.
413 spin_lock_irq(&ctx->ctx_lock);
414 ring = kmap_atomic(ctx->ring_info.ring_pages[0], KM_USER0);
415 if (ctx->reqs_active < aio_ring_avail(&ctx->ring_info, ring)) {
416 list_add(&req->ki_list, &ctx->active_reqs);
417 get_ioctx(ctx);
418 ctx->reqs_active++;
419 okay = 1;
421 kunmap_atomic(ring, KM_USER0);
422 spin_unlock_irq(&ctx->ctx_lock);
424 if (!okay) {
425 kmem_cache_free(kiocb_cachep, req);
426 req = NULL;
429 return req;
432 static inline struct kiocb *aio_get_req(struct kioctx *ctx)
434 struct kiocb *req;
435 /* Handle a potential starvation case -- should be exceedingly rare as
436 * requests will be stuck on fput_head only if the aio_fput_routine is
437 * delayed and the requests were the last user of the struct file.
439 req = __aio_get_req(ctx);
440 if (unlikely(NULL == req)) {
441 aio_fput_routine(NULL);
442 req = __aio_get_req(ctx);
444 return req;
447 static inline void really_put_req(struct kioctx *ctx, struct kiocb *req)
449 if (req->ki_dtor)
450 req->ki_dtor(req);
451 kmem_cache_free(kiocb_cachep, req);
452 ctx->reqs_active--;
454 if (unlikely(!ctx->reqs_active && ctx->dead))
455 wake_up(&ctx->wait);
458 static void aio_fput_routine(void *data)
460 spin_lock_irq(&fput_lock);
461 while (likely(!list_empty(&fput_head))) {
462 struct kiocb *req = list_kiocb(fput_head.next);
463 struct kioctx *ctx = req->ki_ctx;
465 list_del(&req->ki_list);
466 spin_unlock_irq(&fput_lock);
468 /* Complete the fput */
469 __fput(req->ki_filp);
471 /* Link the iocb into the context's free list */
472 spin_lock_irq(&ctx->ctx_lock);
473 really_put_req(ctx, req);
474 spin_unlock_irq(&ctx->ctx_lock);
476 put_ioctx(ctx);
477 spin_lock_irq(&fput_lock);
479 spin_unlock_irq(&fput_lock);
482 /* __aio_put_req
483 * Returns true if this put was the last user of the request.
485 static int __aio_put_req(struct kioctx *ctx, struct kiocb *req)
487 dprintk(KERN_DEBUG "aio_put(%p): f_count=%d\n",
488 req, atomic_read(&req->ki_filp->f_count));
490 req->ki_users --;
491 if (unlikely(req->ki_users < 0))
492 BUG();
493 if (likely(req->ki_users))
494 return 0;
495 list_del(&req->ki_list); /* remove from active_reqs */
496 req->ki_cancel = NULL;
497 req->ki_retry = NULL;
499 /* Must be done under the lock to serialise against cancellation.
500 * Call this aio_fput as it duplicates fput via the fput_work.
502 if (unlikely(atomic_dec_and_test(&req->ki_filp->f_count))) {
503 get_ioctx(ctx);
504 spin_lock(&fput_lock);
505 list_add(&req->ki_list, &fput_head);
506 spin_unlock(&fput_lock);
507 queue_work(aio_wq, &fput_work);
508 } else
509 really_put_req(ctx, req);
510 return 1;
513 /* aio_put_req
514 * Returns true if this put was the last user of the kiocb,
515 * false if the request is still in use.
517 int fastcall aio_put_req(struct kiocb *req)
519 struct kioctx *ctx = req->ki_ctx;
520 int ret;
521 spin_lock_irq(&ctx->ctx_lock);
522 ret = __aio_put_req(ctx, req);
523 spin_unlock_irq(&ctx->ctx_lock);
524 if (ret)
525 put_ioctx(ctx);
526 return ret;
529 /* Lookup an ioctx id. ioctx_list is lockless for reads.
530 * FIXME: this is O(n) and is only suitable for development.
532 struct kioctx *lookup_ioctx(unsigned long ctx_id)
534 struct kioctx *ioctx;
535 struct mm_struct *mm;
537 mm = current->mm;
538 read_lock(&mm->ioctx_list_lock);
539 for (ioctx = mm->ioctx_list; ioctx; ioctx = ioctx->next)
540 if (likely(ioctx->user_id == ctx_id && !ioctx->dead)) {
541 get_ioctx(ioctx);
542 break;
544 read_unlock(&mm->ioctx_list_lock);
546 return ioctx;
550 * use_mm
551 * Makes the calling kernel thread take on the specified
552 * mm context.
553 * Called by the retry thread execute retries within the
554 * iocb issuer's mm context, so that copy_from/to_user
555 * operations work seamlessly for aio.
556 * (Note: this routine is intended to be called only
557 * from a kernel thread context)
559 static void use_mm(struct mm_struct *mm)
561 struct mm_struct *active_mm;
562 struct task_struct *tsk = current;
564 task_lock(tsk);
565 tsk->flags |= PF_BORROWED_MM;
566 active_mm = tsk->active_mm;
567 atomic_inc(&mm->mm_count);
568 tsk->mm = mm;
569 tsk->active_mm = mm;
570 activate_mm(active_mm, mm);
571 task_unlock(tsk);
573 mmdrop(active_mm);
577 * unuse_mm
578 * Reverses the effect of use_mm, i.e. releases the
579 * specified mm context which was earlier taken on
580 * by the calling kernel thread
581 * (Note: this routine is intended to be called only
582 * from a kernel thread context)
584 * Comments: Called with ctx->ctx_lock held. This nests
585 * task_lock instead ctx_lock.
587 static void unuse_mm(struct mm_struct *mm)
589 struct task_struct *tsk = current;
591 task_lock(tsk);
592 tsk->flags &= ~PF_BORROWED_MM;
593 tsk->mm = NULL;
594 /* active_mm is still 'mm' */
595 enter_lazy_tlb(mm, tsk);
596 task_unlock(tsk);
600 * Queue up a kiocb to be retried. Assumes that the kiocb
601 * has already been marked as kicked, and places it on
602 * the retry run list for the corresponding ioctx, if it
603 * isn't already queued. Returns 1 if it actually queued
604 * the kiocb (to tell the caller to activate the work
605 * queue to process it), or 0, if it found that it was
606 * already queued.
608 * Should be called with the spin lock iocb->ki_ctx->ctx_lock
609 * held
611 static inline int __queue_kicked_iocb(struct kiocb *iocb)
613 struct kioctx *ctx = iocb->ki_ctx;
615 if (list_empty(&iocb->ki_run_list)) {
616 list_add_tail(&iocb->ki_run_list,
617 &ctx->run_list);
618 return 1;
620 return 0;
623 /* aio_run_iocb
624 * This is the core aio execution routine. It is
625 * invoked both for initial i/o submission and
626 * subsequent retries via the aio_kick_handler.
627 * Expects to be invoked with iocb->ki_ctx->lock
628 * already held. The lock is released and reaquired
629 * as needed during processing.
631 * Calls the iocb retry method (already setup for the
632 * iocb on initial submission) for operation specific
633 * handling, but takes care of most of common retry
634 * execution details for a given iocb. The retry method
635 * needs to be non-blocking as far as possible, to avoid
636 * holding up other iocbs waiting to be serviced by the
637 * retry kernel thread.
639 * The trickier parts in this code have to do with
640 * ensuring that only one retry instance is in progress
641 * for a given iocb at any time. Providing that guarantee
642 * simplifies the coding of individual aio operations as
643 * it avoids various potential races.
645 static ssize_t aio_run_iocb(struct kiocb *iocb)
647 struct kioctx *ctx = iocb->ki_ctx;
648 ssize_t (*retry)(struct kiocb *);
649 ssize_t ret;
651 if (iocb->ki_retried++ > 1024*1024) {
652 printk("Maximal retry count. Bytes done %Zd\n",
653 iocb->ki_nbytes - iocb->ki_left);
654 return -EAGAIN;
657 if (!(iocb->ki_retried & 0xff)) {
658 pr_debug("%ld retry: %d of %d\n", iocb->ki_retried,
659 iocb->ki_nbytes - iocb->ki_left, iocb->ki_nbytes);
662 if (!(retry = iocb->ki_retry)) {
663 printk("aio_run_iocb: iocb->ki_retry = NULL\n");
664 return 0;
668 * We don't want the next retry iteration for this
669 * operation to start until this one has returned and
670 * updated the iocb state. However, wait_queue functions
671 * can trigger a kick_iocb from interrupt context in the
672 * meantime, indicating that data is available for the next
673 * iteration. We want to remember that and enable the
674 * next retry iteration _after_ we are through with
675 * this one.
677 * So, in order to be able to register a "kick", but
678 * prevent it from being queued now, we clear the kick
679 * flag, but make the kick code *think* that the iocb is
680 * still on the run list until we are actually done.
681 * When we are done with this iteration, we check if
682 * the iocb was kicked in the meantime and if so, queue
683 * it up afresh.
686 kiocbClearKicked(iocb);
689 * This is so that aio_complete knows it doesn't need to
690 * pull the iocb off the run list (We can't just call
691 * INIT_LIST_HEAD because we don't want a kick_iocb to
692 * queue this on the run list yet)
694 iocb->ki_run_list.next = iocb->ki_run_list.prev = NULL;
695 spin_unlock_irq(&ctx->ctx_lock);
697 /* Quit retrying if the i/o has been cancelled */
698 if (kiocbIsCancelled(iocb)) {
699 ret = -EINTR;
700 aio_complete(iocb, ret, 0);
701 /* must not access the iocb after this */
702 goto out;
706 * Now we are all set to call the retry method in async
707 * context. By setting this thread's io_wait context
708 * to point to the wait queue entry inside the currently
709 * running iocb for the duration of the retry, we ensure
710 * that async notification wakeups are queued by the
711 * operation instead of blocking waits, and when notified,
712 * cause the iocb to be kicked for continuation (through
713 * the aio_wake_function callback).
715 BUG_ON(current->io_wait != NULL);
716 current->io_wait = &iocb->ki_wait;
717 ret = retry(iocb);
718 current->io_wait = NULL;
720 if (-EIOCBRETRY != ret) {
721 if (-EIOCBQUEUED != ret) {
722 BUG_ON(!list_empty(&iocb->ki_wait.task_list));
723 aio_complete(iocb, ret, 0);
724 /* must not access the iocb after this */
726 } else {
728 * Issue an additional retry to avoid waiting forever if
729 * no waits were queued (e.g. in case of a short read).
731 if (list_empty(&iocb->ki_wait.task_list))
732 kiocbSetKicked(iocb);
734 out:
735 spin_lock_irq(&ctx->ctx_lock);
737 if (-EIOCBRETRY == ret) {
739 * OK, now that we are done with this iteration
740 * and know that there is more left to go,
741 * this is where we let go so that a subsequent
742 * "kick" can start the next iteration
745 /* will make __queue_kicked_iocb succeed from here on */
746 INIT_LIST_HEAD(&iocb->ki_run_list);
747 /* we must queue the next iteration ourselves, if it
748 * has already been kicked */
749 if (kiocbIsKicked(iocb)) {
750 __queue_kicked_iocb(iocb);
753 * __queue_kicked_iocb will always return 1 here, because
754 * iocb->ki_run_list is empty at this point so it should
755 * be safe to unconditionally queue the context into the
756 * work queue.
758 aio_queue_work(ctx);
761 return ret;
765 * __aio_run_iocbs:
766 * Process all pending retries queued on the ioctx
767 * run list.
768 * Assumes it is operating within the aio issuer's mm
769 * context. Expects to be called with ctx->ctx_lock held
771 static int __aio_run_iocbs(struct kioctx *ctx)
773 struct kiocb *iocb;
774 LIST_HEAD(run_list);
776 list_splice_init(&ctx->run_list, &run_list);
777 while (!list_empty(&run_list)) {
778 iocb = list_entry(run_list.next, struct kiocb,
779 ki_run_list);
780 list_del(&iocb->ki_run_list);
782 * Hold an extra reference while retrying i/o.
784 iocb->ki_users++; /* grab extra reference */
785 aio_run_iocb(iocb);
786 if (__aio_put_req(ctx, iocb)) /* drop extra ref */
787 put_ioctx(ctx);
789 if (!list_empty(&ctx->run_list))
790 return 1;
791 return 0;
794 static void aio_queue_work(struct kioctx * ctx)
796 unsigned long timeout;
798 * if someone is waiting, get the work started right
799 * away, otherwise, use a longer delay
801 smp_mb();
802 if (waitqueue_active(&ctx->wait))
803 timeout = 1;
804 else
805 timeout = HZ/10;
806 queue_delayed_work(aio_wq, &ctx->wq, timeout);
811 * aio_run_iocbs:
812 * Process all pending retries queued on the ioctx
813 * run list.
814 * Assumes it is operating within the aio issuer's mm
815 * context.
817 static inline void aio_run_iocbs(struct kioctx *ctx)
819 int requeue;
821 spin_lock_irq(&ctx->ctx_lock);
823 requeue = __aio_run_iocbs(ctx);
824 spin_unlock_irq(&ctx->ctx_lock);
825 if (requeue)
826 aio_queue_work(ctx);
830 * just like aio_run_iocbs, but keeps running them until
831 * the list stays empty
833 static inline void aio_run_all_iocbs(struct kioctx *ctx)
835 spin_lock_irq(&ctx->ctx_lock);
836 while (__aio_run_iocbs(ctx))
838 spin_unlock_irq(&ctx->ctx_lock);
842 * aio_kick_handler:
843 * Work queue handler triggered to process pending
844 * retries on an ioctx. Takes on the aio issuer's
845 * mm context before running the iocbs, so that
846 * copy_xxx_user operates on the issuer's address
847 * space.
848 * Run on aiod's context.
850 static void aio_kick_handler(void *data)
852 struct kioctx *ctx = data;
853 mm_segment_t oldfs = get_fs();
854 int requeue;
856 set_fs(USER_DS);
857 use_mm(ctx->mm);
858 spin_lock_irq(&ctx->ctx_lock);
859 requeue =__aio_run_iocbs(ctx);
860 unuse_mm(ctx->mm);
861 spin_unlock_irq(&ctx->ctx_lock);
862 set_fs(oldfs);
864 * we're in a worker thread already, don't use queue_delayed_work,
866 if (requeue)
867 queue_work(aio_wq, &ctx->wq);
872 * Called by kick_iocb to queue the kiocb for retry
873 * and if required activate the aio work queue to process
874 * it
876 static void queue_kicked_iocb(struct kiocb *iocb)
878 struct kioctx *ctx = iocb->ki_ctx;
879 unsigned long flags;
880 int run = 0;
882 WARN_ON((!list_empty(&iocb->ki_wait.task_list)));
884 spin_lock_irqsave(&ctx->ctx_lock, flags);
885 run = __queue_kicked_iocb(iocb);
886 spin_unlock_irqrestore(&ctx->ctx_lock, flags);
887 if (run)
888 aio_queue_work(ctx);
892 * kick_iocb:
893 * Called typically from a wait queue callback context
894 * (aio_wake_function) to trigger a retry of the iocb.
895 * The retry is usually executed by aio workqueue
896 * threads (See aio_kick_handler).
898 void fastcall kick_iocb(struct kiocb *iocb)
900 /* sync iocbs are easy: they can only ever be executing from a
901 * single context. */
902 if (is_sync_kiocb(iocb)) {
903 kiocbSetKicked(iocb);
904 wake_up_process(iocb->ki_obj.tsk);
905 return;
908 /* If its already kicked we shouldn't queue it again */
909 if (!kiocbTryKick(iocb)) {
910 queue_kicked_iocb(iocb);
913 EXPORT_SYMBOL(kick_iocb);
915 /* aio_complete
916 * Called when the io request on the given iocb is complete.
917 * Returns true if this is the last user of the request. The
918 * only other user of the request can be the cancellation code.
920 int fastcall aio_complete(struct kiocb *iocb, long res, long res2)
922 struct kioctx *ctx = iocb->ki_ctx;
923 struct aio_ring_info *info;
924 struct aio_ring *ring;
925 struct io_event *event;
926 unsigned long flags;
927 unsigned long tail;
928 int ret;
930 /* Special case handling for sync iocbs: events go directly
931 * into the iocb for fast handling. Note that this will not
932 * work if we allow sync kiocbs to be cancelled. in which
933 * case the usage count checks will have to move under ctx_lock
934 * for all cases.
936 if (is_sync_kiocb(iocb)) {
937 int ret;
939 iocb->ki_user_data = res;
940 if (iocb->ki_users == 1) {
941 iocb->ki_users = 0;
942 ret = 1;
943 } else {
944 spin_lock_irq(&ctx->ctx_lock);
945 iocb->ki_users--;
946 ret = (0 == iocb->ki_users);
947 spin_unlock_irq(&ctx->ctx_lock);
949 /* sync iocbs put the task here for us */
950 wake_up_process(iocb->ki_obj.tsk);
951 return ret;
954 info = &ctx->ring_info;
956 /* add a completion event to the ring buffer.
957 * must be done holding ctx->ctx_lock to prevent
958 * other code from messing with the tail
959 * pointer since we might be called from irq
960 * context.
962 spin_lock_irqsave(&ctx->ctx_lock, flags);
964 if (iocb->ki_run_list.prev && !list_empty(&iocb->ki_run_list))
965 list_del_init(&iocb->ki_run_list);
968 * cancelled requests don't get events, userland was given one
969 * when the event got cancelled.
971 if (kiocbIsCancelled(iocb))
972 goto put_rq;
974 ring = kmap_atomic(info->ring_pages[0], KM_IRQ1);
976 tail = info->tail;
977 event = aio_ring_event(info, tail, KM_IRQ0);
978 if (++tail >= info->nr)
979 tail = 0;
981 event->obj = (u64)(unsigned long)iocb->ki_obj.user;
982 event->data = iocb->ki_user_data;
983 event->res = res;
984 event->res2 = res2;
986 dprintk("aio_complete: %p[%lu]: %p: %p %Lx %lx %lx\n",
987 ctx, tail, iocb, iocb->ki_obj.user, iocb->ki_user_data,
988 res, res2);
990 /* after flagging the request as done, we
991 * must never even look at it again
993 smp_wmb(); /* make event visible before updating tail */
995 info->tail = tail;
996 ring->tail = tail;
998 put_aio_ring_event(event, KM_IRQ0);
999 kunmap_atomic(ring, KM_IRQ1);
1001 pr_debug("added to ring %p at [%lu]\n", iocb, tail);
1003 pr_debug("%ld retries: %d of %d\n", iocb->ki_retried,
1004 iocb->ki_nbytes - iocb->ki_left, iocb->ki_nbytes);
1005 put_rq:
1006 /* everything turned out well, dispose of the aiocb. */
1007 ret = __aio_put_req(ctx, iocb);
1009 spin_unlock_irqrestore(&ctx->ctx_lock, flags);
1011 if (waitqueue_active(&ctx->wait))
1012 wake_up(&ctx->wait);
1014 if (ret)
1015 put_ioctx(ctx);
1017 return ret;
1020 /* aio_read_evt
1021 * Pull an event off of the ioctx's event ring. Returns the number of
1022 * events fetched (0 or 1 ;-)
1023 * FIXME: make this use cmpxchg.
1024 * TODO: make the ringbuffer user mmap()able (requires FIXME).
1026 static int aio_read_evt(struct kioctx *ioctx, struct io_event *ent)
1028 struct aio_ring_info *info = &ioctx->ring_info;
1029 struct aio_ring *ring;
1030 unsigned long head;
1031 int ret = 0;
1033 ring = kmap_atomic(info->ring_pages[0], KM_USER0);
1034 dprintk("in aio_read_evt h%lu t%lu m%lu\n",
1035 (unsigned long)ring->head, (unsigned long)ring->tail,
1036 (unsigned long)ring->nr);
1038 if (ring->head == ring->tail)
1039 goto out;
1041 spin_lock(&info->ring_lock);
1043 head = ring->head % info->nr;
1044 if (head != ring->tail) {
1045 struct io_event *evp = aio_ring_event(info, head, KM_USER1);
1046 *ent = *evp;
1047 head = (head + 1) % info->nr;
1048 smp_mb(); /* finish reading the event before updatng the head */
1049 ring->head = head;
1050 ret = 1;
1051 put_aio_ring_event(evp, KM_USER1);
1053 spin_unlock(&info->ring_lock);
1055 out:
1056 kunmap_atomic(ring, KM_USER0);
1057 dprintk("leaving aio_read_evt: %d h%lu t%lu\n", ret,
1058 (unsigned long)ring->head, (unsigned long)ring->tail);
1059 return ret;
1062 struct aio_timeout {
1063 struct timer_list timer;
1064 int timed_out;
1065 struct task_struct *p;
1068 static void timeout_func(unsigned long data)
1070 struct aio_timeout *to = (struct aio_timeout *)data;
1072 to->timed_out = 1;
1073 wake_up_process(to->p);
1076 static inline void init_timeout(struct aio_timeout *to)
1078 init_timer(&to->timer);
1079 to->timer.data = (unsigned long)to;
1080 to->timer.function = timeout_func;
1081 to->timed_out = 0;
1082 to->p = current;
1085 static inline void set_timeout(long start_jiffies, struct aio_timeout *to,
1086 const struct timespec *ts)
1088 to->timer.expires = start_jiffies + timespec_to_jiffies(ts);
1089 if (time_after(to->timer.expires, jiffies))
1090 add_timer(&to->timer);
1091 else
1092 to->timed_out = 1;
1095 static inline void clear_timeout(struct aio_timeout *to)
1097 del_singleshot_timer_sync(&to->timer);
1100 static int read_events(struct kioctx *ctx,
1101 long min_nr, long nr,
1102 struct io_event __user *event,
1103 struct timespec __user *timeout)
1105 long start_jiffies = jiffies;
1106 struct task_struct *tsk = current;
1107 DECLARE_WAITQUEUE(wait, tsk);
1108 int ret;
1109 int i = 0;
1110 struct io_event ent;
1111 struct aio_timeout to;
1112 int retry = 0;
1114 /* needed to zero any padding within an entry (there shouldn't be
1115 * any, but C is fun!
1117 memset(&ent, 0, sizeof(ent));
1118 retry:
1119 ret = 0;
1120 while (likely(i < nr)) {
1121 ret = aio_read_evt(ctx, &ent);
1122 if (unlikely(ret <= 0))
1123 break;
1125 dprintk("read event: %Lx %Lx %Lx %Lx\n",
1126 ent.data, ent.obj, ent.res, ent.res2);
1128 /* Could we split the check in two? */
1129 ret = -EFAULT;
1130 if (unlikely(copy_to_user(event, &ent, sizeof(ent)))) {
1131 dprintk("aio: lost an event due to EFAULT.\n");
1132 break;
1134 ret = 0;
1136 /* Good, event copied to userland, update counts. */
1137 event ++;
1138 i ++;
1141 if (min_nr <= i)
1142 return i;
1143 if (ret)
1144 return ret;
1146 /* End fast path */
1148 /* racey check, but it gets redone */
1149 if (!retry && unlikely(!list_empty(&ctx->run_list))) {
1150 retry = 1;
1151 aio_run_all_iocbs(ctx);
1152 goto retry;
1155 init_timeout(&to);
1156 if (timeout) {
1157 struct timespec ts;
1158 ret = -EFAULT;
1159 if (unlikely(copy_from_user(&ts, timeout, sizeof(ts))))
1160 goto out;
1162 set_timeout(start_jiffies, &to, &ts);
1165 while (likely(i < nr)) {
1166 add_wait_queue_exclusive(&ctx->wait, &wait);
1167 do {
1168 set_task_state(tsk, TASK_INTERRUPTIBLE);
1169 ret = aio_read_evt(ctx, &ent);
1170 if (ret)
1171 break;
1172 if (min_nr <= i)
1173 break;
1174 ret = 0;
1175 if (to.timed_out) /* Only check after read evt */
1176 break;
1177 schedule();
1178 if (signal_pending(tsk)) {
1179 ret = -EINTR;
1180 break;
1182 /*ret = aio_read_evt(ctx, &ent);*/
1183 } while (1) ;
1185 set_task_state(tsk, TASK_RUNNING);
1186 remove_wait_queue(&ctx->wait, &wait);
1188 if (unlikely(ret <= 0))
1189 break;
1191 ret = -EFAULT;
1192 if (unlikely(copy_to_user(event, &ent, sizeof(ent)))) {
1193 dprintk("aio: lost an event due to EFAULT.\n");
1194 break;
1197 /* Good, event copied to userland, update counts. */
1198 event ++;
1199 i ++;
1202 if (timeout)
1203 clear_timeout(&to);
1204 out:
1205 return i ? i : ret;
1208 /* Take an ioctx and remove it from the list of ioctx's. Protects
1209 * against races with itself via ->dead.
1211 static void io_destroy(struct kioctx *ioctx)
1213 struct mm_struct *mm = current->mm;
1214 struct kioctx **tmp;
1215 int was_dead;
1217 /* delete the entry from the list is someone else hasn't already */
1218 write_lock(&mm->ioctx_list_lock);
1219 was_dead = ioctx->dead;
1220 ioctx->dead = 1;
1221 for (tmp = &mm->ioctx_list; *tmp && *tmp != ioctx;
1222 tmp = &(*tmp)->next)
1224 if (*tmp)
1225 *tmp = ioctx->next;
1226 write_unlock(&mm->ioctx_list_lock);
1228 dprintk("aio_release(%p)\n", ioctx);
1229 if (likely(!was_dead))
1230 put_ioctx(ioctx); /* twice for the list */
1232 aio_cancel_all(ioctx);
1233 wait_for_all_aios(ioctx);
1234 put_ioctx(ioctx); /* once for the lookup */
1237 /* sys_io_setup:
1238 * Create an aio_context capable of receiving at least nr_events.
1239 * ctxp must not point to an aio_context that already exists, and
1240 * must be initialized to 0 prior to the call. On successful
1241 * creation of the aio_context, *ctxp is filled in with the resulting
1242 * handle. May fail with -EINVAL if *ctxp is not initialized,
1243 * if the specified nr_events exceeds internal limits. May fail
1244 * with -EAGAIN if the specified nr_events exceeds the user's limit
1245 * of available events. May fail with -ENOMEM if insufficient kernel
1246 * resources are available. May fail with -EFAULT if an invalid
1247 * pointer is passed for ctxp. Will fail with -ENOSYS if not
1248 * implemented.
1250 asmlinkage long sys_io_setup(unsigned nr_events, aio_context_t __user *ctxp)
1252 struct kioctx *ioctx = NULL;
1253 unsigned long ctx;
1254 long ret;
1256 ret = get_user(ctx, ctxp);
1257 if (unlikely(ret))
1258 goto out;
1260 ret = -EINVAL;
1261 if (unlikely(ctx || (int)nr_events <= 0)) {
1262 pr_debug("EINVAL: io_setup: ctx or nr_events > max\n");
1263 goto out;
1266 ioctx = ioctx_alloc(nr_events);
1267 ret = PTR_ERR(ioctx);
1268 if (!IS_ERR(ioctx)) {
1269 ret = put_user(ioctx->user_id, ctxp);
1270 if (!ret)
1271 return 0;
1273 get_ioctx(ioctx); /* io_destroy() expects us to hold a ref */
1274 io_destroy(ioctx);
1277 out:
1278 return ret;
1281 /* sys_io_destroy:
1282 * Destroy the aio_context specified. May cancel any outstanding
1283 * AIOs and block on completion. Will fail with -ENOSYS if not
1284 * implemented. May fail with -EFAULT if the context pointed to
1285 * is invalid.
1287 asmlinkage long sys_io_destroy(aio_context_t ctx)
1289 struct kioctx *ioctx = lookup_ioctx(ctx);
1290 if (likely(NULL != ioctx)) {
1291 io_destroy(ioctx);
1292 return 0;
1294 pr_debug("EINVAL: io_destroy: invalid context id\n");
1295 return -EINVAL;
1299 * Default retry method for aio_read (also used for first time submit)
1300 * Responsible for updating iocb state as retries progress
1302 static ssize_t aio_pread(struct kiocb *iocb)
1304 struct file *file = iocb->ki_filp;
1305 struct address_space *mapping = file->f_mapping;
1306 struct inode *inode = mapping->host;
1307 ssize_t ret = 0;
1309 ret = file->f_op->aio_read(iocb, iocb->ki_buf,
1310 iocb->ki_left, iocb->ki_pos);
1313 * Can't just depend on iocb->ki_left to determine
1314 * whether we are done. This may have been a short read.
1316 if (ret > 0) {
1317 iocb->ki_buf += ret;
1318 iocb->ki_left -= ret;
1320 * For pipes and sockets we return once we have
1321 * some data; for regular files we retry till we
1322 * complete the entire read or find that we can't
1323 * read any more data (e.g short reads).
1325 if (!S_ISFIFO(inode->i_mode) && !S_ISSOCK(inode->i_mode))
1326 ret = -EIOCBRETRY;
1329 /* This means we must have transferred all that we could */
1330 /* No need to retry anymore */
1331 if ((ret == 0) || (iocb->ki_left == 0))
1332 ret = iocb->ki_nbytes - iocb->ki_left;
1334 return ret;
1338 * Default retry method for aio_write (also used for first time submit)
1339 * Responsible for updating iocb state as retries progress
1341 static ssize_t aio_pwrite(struct kiocb *iocb)
1343 struct file *file = iocb->ki_filp;
1344 ssize_t ret = 0;
1346 ret = file->f_op->aio_write(iocb, iocb->ki_buf,
1347 iocb->ki_left, iocb->ki_pos);
1349 if (ret > 0) {
1350 iocb->ki_buf += ret;
1351 iocb->ki_left -= ret;
1353 ret = -EIOCBRETRY;
1356 /* This means we must have transferred all that we could */
1357 /* No need to retry anymore */
1358 if ((ret == 0) || (iocb->ki_left == 0))
1359 ret = iocb->ki_nbytes - iocb->ki_left;
1361 return ret;
1364 static ssize_t aio_fdsync(struct kiocb *iocb)
1366 struct file *file = iocb->ki_filp;
1367 ssize_t ret = -EINVAL;
1369 if (file->f_op->aio_fsync)
1370 ret = file->f_op->aio_fsync(iocb, 1);
1371 return ret;
1374 static ssize_t aio_fsync(struct kiocb *iocb)
1376 struct file *file = iocb->ki_filp;
1377 ssize_t ret = -EINVAL;
1379 if (file->f_op->aio_fsync)
1380 ret = file->f_op->aio_fsync(iocb, 0);
1381 return ret;
1385 * aio_setup_iocb:
1386 * Performs the initial checks and aio retry method
1387 * setup for the kiocb at the time of io submission.
1389 static ssize_t aio_setup_iocb(struct kiocb *kiocb)
1391 struct file *file = kiocb->ki_filp;
1392 ssize_t ret = 0;
1394 switch (kiocb->ki_opcode) {
1395 case IOCB_CMD_PREAD:
1396 ret = -EBADF;
1397 if (unlikely(!(file->f_mode & FMODE_READ)))
1398 break;
1399 ret = -EFAULT;
1400 if (unlikely(!access_ok(VERIFY_WRITE, kiocb->ki_buf,
1401 kiocb->ki_left)))
1402 break;
1403 ret = -EINVAL;
1404 if (file->f_op->aio_read)
1405 kiocb->ki_retry = aio_pread;
1406 break;
1407 case IOCB_CMD_PWRITE:
1408 ret = -EBADF;
1409 if (unlikely(!(file->f_mode & FMODE_WRITE)))
1410 break;
1411 ret = -EFAULT;
1412 if (unlikely(!access_ok(VERIFY_READ, kiocb->ki_buf,
1413 kiocb->ki_left)))
1414 break;
1415 ret = -EINVAL;
1416 if (file->f_op->aio_write)
1417 kiocb->ki_retry = aio_pwrite;
1418 break;
1419 case IOCB_CMD_FDSYNC:
1420 ret = -EINVAL;
1421 if (file->f_op->aio_fsync)
1422 kiocb->ki_retry = aio_fdsync;
1423 break;
1424 case IOCB_CMD_FSYNC:
1425 ret = -EINVAL;
1426 if (file->f_op->aio_fsync)
1427 kiocb->ki_retry = aio_fsync;
1428 break;
1429 default:
1430 dprintk("EINVAL: io_submit: no operation provided\n");
1431 ret = -EINVAL;
1434 if (!kiocb->ki_retry)
1435 return ret;
1437 return 0;
1441 * aio_wake_function:
1442 * wait queue callback function for aio notification,
1443 * Simply triggers a retry of the operation via kick_iocb.
1445 * This callback is specified in the wait queue entry in
1446 * a kiocb (current->io_wait points to this wait queue
1447 * entry when an aio operation executes; it is used
1448 * instead of a synchronous wait when an i/o blocking
1449 * condition is encountered during aio).
1451 * Note:
1452 * This routine is executed with the wait queue lock held.
1453 * Since kick_iocb acquires iocb->ctx->ctx_lock, it nests
1454 * the ioctx lock inside the wait queue lock. This is safe
1455 * because this callback isn't used for wait queues which
1456 * are nested inside ioctx lock (i.e. ctx->wait)
1458 static int aio_wake_function(wait_queue_t *wait, unsigned mode,
1459 int sync, void *key)
1461 struct kiocb *iocb = container_of(wait, struct kiocb, ki_wait);
1463 list_del_init(&wait->task_list);
1464 kick_iocb(iocb);
1465 return 1;
1468 int fastcall io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb,
1469 struct iocb *iocb)
1471 struct kiocb *req;
1472 struct file *file;
1473 ssize_t ret;
1475 /* enforce forwards compatibility on users */
1476 if (unlikely(iocb->aio_reserved1 || iocb->aio_reserved2 ||
1477 iocb->aio_reserved3)) {
1478 pr_debug("EINVAL: io_submit: reserve field set\n");
1479 return -EINVAL;
1482 /* prevent overflows */
1483 if (unlikely(
1484 (iocb->aio_buf != (unsigned long)iocb->aio_buf) ||
1485 (iocb->aio_nbytes != (size_t)iocb->aio_nbytes) ||
1486 ((ssize_t)iocb->aio_nbytes < 0)
1487 )) {
1488 pr_debug("EINVAL: io_submit: overflow check\n");
1489 return -EINVAL;
1492 file = fget(iocb->aio_fildes);
1493 if (unlikely(!file))
1494 return -EBADF;
1496 req = aio_get_req(ctx); /* returns with 2 references to req */
1497 if (unlikely(!req)) {
1498 fput(file);
1499 return -EAGAIN;
1502 req->ki_filp = file;
1503 ret = put_user(req->ki_key, &user_iocb->aio_key);
1504 if (unlikely(ret)) {
1505 dprintk("EFAULT: aio_key\n");
1506 goto out_put_req;
1509 req->ki_obj.user = user_iocb;
1510 req->ki_user_data = iocb->aio_data;
1511 req->ki_pos = iocb->aio_offset;
1513 req->ki_buf = (char __user *)(unsigned long)iocb->aio_buf;
1514 req->ki_left = req->ki_nbytes = iocb->aio_nbytes;
1515 req->ki_opcode = iocb->aio_lio_opcode;
1516 init_waitqueue_func_entry(&req->ki_wait, aio_wake_function);
1517 INIT_LIST_HEAD(&req->ki_wait.task_list);
1518 req->ki_retried = 0;
1520 ret = aio_setup_iocb(req);
1522 if (ret)
1523 goto out_put_req;
1525 spin_lock_irq(&ctx->ctx_lock);
1526 if (likely(list_empty(&ctx->run_list))) {
1527 aio_run_iocb(req);
1528 } else {
1529 list_add_tail(&req->ki_run_list, &ctx->run_list);
1530 /* drain the run list */
1531 while (__aio_run_iocbs(ctx))
1534 spin_unlock_irq(&ctx->ctx_lock);
1535 aio_put_req(req); /* drop extra ref to req */
1536 return 0;
1538 out_put_req:
1539 aio_put_req(req); /* drop extra ref to req */
1540 aio_put_req(req); /* drop i/o ref to req */
1541 return ret;
1544 /* sys_io_submit:
1545 * Queue the nr iocbs pointed to by iocbpp for processing. Returns
1546 * the number of iocbs queued. May return -EINVAL if the aio_context
1547 * specified by ctx_id is invalid, if nr is < 0, if the iocb at
1548 * *iocbpp[0] is not properly initialized, if the operation specified
1549 * is invalid for the file descriptor in the iocb. May fail with
1550 * -EFAULT if any of the data structures point to invalid data. May
1551 * fail with -EBADF if the file descriptor specified in the first
1552 * iocb is invalid. May fail with -EAGAIN if insufficient resources
1553 * are available to queue any iocbs. Will return 0 if nr is 0. Will
1554 * fail with -ENOSYS if not implemented.
1556 asmlinkage long sys_io_submit(aio_context_t ctx_id, long nr,
1557 struct iocb __user * __user *iocbpp)
1559 struct kioctx *ctx;
1560 long ret = 0;
1561 int i;
1563 if (unlikely(nr < 0))
1564 return -EINVAL;
1566 if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))
1567 return -EFAULT;
1569 ctx = lookup_ioctx(ctx_id);
1570 if (unlikely(!ctx)) {
1571 pr_debug("EINVAL: io_submit: invalid context id\n");
1572 return -EINVAL;
1576 * AKPM: should this return a partial result if some of the IOs were
1577 * successfully submitted?
1579 for (i=0; i<nr; i++) {
1580 struct iocb __user *user_iocb;
1581 struct iocb tmp;
1583 if (unlikely(__get_user(user_iocb, iocbpp + i))) {
1584 ret = -EFAULT;
1585 break;
1588 if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
1589 ret = -EFAULT;
1590 break;
1593 ret = io_submit_one(ctx, user_iocb, &tmp);
1594 if (ret)
1595 break;
1598 put_ioctx(ctx);
1599 return i ? i : ret;
1602 /* lookup_kiocb
1603 * Finds a given iocb for cancellation.
1604 * MUST be called with ctx->ctx_lock held.
1606 static struct kiocb *lookup_kiocb(struct kioctx *ctx, struct iocb __user *iocb,
1607 u32 key)
1609 struct list_head *pos;
1610 /* TODO: use a hash or array, this sucks. */
1611 list_for_each(pos, &ctx->active_reqs) {
1612 struct kiocb *kiocb = list_kiocb(pos);
1613 if (kiocb->ki_obj.user == iocb && kiocb->ki_key == key)
1614 return kiocb;
1616 return NULL;
1619 /* sys_io_cancel:
1620 * Attempts to cancel an iocb previously passed to io_submit. If
1621 * the operation is successfully cancelled, the resulting event is
1622 * copied into the memory pointed to by result without being placed
1623 * into the completion queue and 0 is returned. May fail with
1624 * -EFAULT if any of the data structures pointed to are invalid.
1625 * May fail with -EINVAL if aio_context specified by ctx_id is
1626 * invalid. May fail with -EAGAIN if the iocb specified was not
1627 * cancelled. Will fail with -ENOSYS if not implemented.
1629 asmlinkage long sys_io_cancel(aio_context_t ctx_id, struct iocb __user *iocb,
1630 struct io_event __user *result)
1632 int (*cancel)(struct kiocb *iocb, struct io_event *res);
1633 struct kioctx *ctx;
1634 struct kiocb *kiocb;
1635 u32 key;
1636 int ret;
1638 ret = get_user(key, &iocb->aio_key);
1639 if (unlikely(ret))
1640 return -EFAULT;
1642 ctx = lookup_ioctx(ctx_id);
1643 if (unlikely(!ctx))
1644 return -EINVAL;
1646 spin_lock_irq(&ctx->ctx_lock);
1647 ret = -EAGAIN;
1648 kiocb = lookup_kiocb(ctx, iocb, key);
1649 if (kiocb && kiocb->ki_cancel) {
1650 cancel = kiocb->ki_cancel;
1651 kiocb->ki_users ++;
1652 kiocbSetCancelled(kiocb);
1653 } else
1654 cancel = NULL;
1655 spin_unlock_irq(&ctx->ctx_lock);
1657 if (NULL != cancel) {
1658 struct io_event tmp;
1659 pr_debug("calling cancel\n");
1660 memset(&tmp, 0, sizeof(tmp));
1661 tmp.obj = (u64)(unsigned long)kiocb->ki_obj.user;
1662 tmp.data = kiocb->ki_user_data;
1663 ret = cancel(kiocb, &tmp);
1664 if (!ret) {
1665 /* Cancellation succeeded -- copy the result
1666 * into the user's buffer.
1668 if (copy_to_user(result, &tmp, sizeof(tmp)))
1669 ret = -EFAULT;
1671 } else
1672 printk(KERN_DEBUG "iocb has no cancel operation\n");
1674 put_ioctx(ctx);
1676 return ret;
1679 /* io_getevents:
1680 * Attempts to read at least min_nr events and up to nr events from
1681 * the completion queue for the aio_context specified by ctx_id. May
1682 * fail with -EINVAL if ctx_id is invalid, if min_nr is out of range,
1683 * if nr is out of range, if when is out of range. May fail with
1684 * -EFAULT if any of the memory specified to is invalid. May return
1685 * 0 or < min_nr if no events are available and the timeout specified
1686 * by when has elapsed, where when == NULL specifies an infinite
1687 * timeout. Note that the timeout pointed to by when is relative and
1688 * will be updated if not NULL and the operation blocks. Will fail
1689 * with -ENOSYS if not implemented.
1691 asmlinkage long sys_io_getevents(aio_context_t ctx_id,
1692 long min_nr,
1693 long nr,
1694 struct io_event __user *events,
1695 struct timespec __user *timeout)
1697 struct kioctx *ioctx = lookup_ioctx(ctx_id);
1698 long ret = -EINVAL;
1700 if (likely(ioctx)) {
1701 if (likely(min_nr <= nr && min_nr >= 0 && nr >= 0))
1702 ret = read_events(ioctx, min_nr, nr, events, timeout);
1703 put_ioctx(ioctx);
1706 return ret;
1709 __initcall(aio_setup);
1711 EXPORT_SYMBOL(aio_complete);
1712 EXPORT_SYMBOL(aio_put_req);
1713 EXPORT_SYMBOL(wait_on_sync_kiocb);