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 #define pr_fmt(fmt) "%s: " fmt, __func__
13 #include <linux/kernel.h>
14 #include <linux/init.h>
15 #include <linux/errno.h>
16 #include <linux/time.h>
17 #include <linux/aio_abi.h>
18 #include <linux/export.h>
19 #include <linux/syscalls.h>
20 #include <linux/backing-dev.h>
21 #include <linux/uio.h>
23 #include <linux/sched.h>
25 #include <linux/file.h>
27 #include <linux/mman.h>
28 #include <linux/mmu_context.h>
29 #include <linux/slab.h>
30 #include <linux/timer.h>
31 #include <linux/aio.h>
32 #include <linux/highmem.h>
33 #include <linux/workqueue.h>
34 #include <linux/security.h>
35 #include <linux/eventfd.h>
36 #include <linux/blkdev.h>
37 #include <linux/compat.h>
39 #include <asm/kmap_types.h>
40 #include <asm/uaccess.h>
42 #define AIO_RING_MAGIC 0xa10a10a1
43 #define AIO_RING_COMPAT_FEATURES 1
44 #define AIO_RING_INCOMPAT_FEATURES 0
46 unsigned id; /* kernel internal index number */
47 unsigned nr; /* number of io_events */
52 unsigned compat_features;
53 unsigned incompat_features;
54 unsigned header_length; /* size of aio_ring */
57 struct io_event io_events[0];
58 }; /* 128 bytes + ring size */
60 #define AIO_RING_PAGES 8
66 /* This needs improving */
67 unsigned long user_id;
68 struct hlist_node list;
70 wait_queue_head_t wait;
75 struct list_head active_reqs; /* used for cancellation */
79 /* sys_io_setup currently limits this to an unsigned int */
82 unsigned long mmap_base;
83 unsigned long mmap_size;
85 struct page **ring_pages;
89 struct mutex ring_lock;
90 } ____cacheline_aligned;
94 spinlock_t completion_lock;
95 } ____cacheline_aligned;
97 struct page *internal_pages[AIO_RING_PAGES];
99 struct rcu_head rcu_head;
100 struct work_struct rcu_work;
103 /*------ sysctl variables----*/
104 static DEFINE_SPINLOCK(aio_nr_lock);
105 unsigned long aio_nr; /* current system wide number of aio requests */
106 unsigned long aio_max_nr = 0x10000; /* system wide maximum number of aio requests */
107 /*----end sysctl variables---*/
109 static struct kmem_cache *kiocb_cachep;
110 static struct kmem_cache *kioctx_cachep;
113 * Creates the slab caches used by the aio routines, panic on
114 * failure as this is done early during the boot sequence.
116 static int __init aio_setup(void)
118 kiocb_cachep = KMEM_CACHE(kiocb, SLAB_HWCACHE_ALIGN|SLAB_PANIC);
119 kioctx_cachep = KMEM_CACHE(kioctx,SLAB_HWCACHE_ALIGN|SLAB_PANIC);
121 pr_debug("sizeof(struct page) = %zu\n", sizeof(struct page));
125 __initcall(aio_setup);
127 static void aio_free_ring(struct kioctx *ctx)
131 for (i = 0; i < ctx->nr_pages; i++)
132 put_page(ctx->ring_pages[i]);
135 vm_munmap(ctx->mmap_base, ctx->mmap_size);
137 if (ctx->ring_pages && ctx->ring_pages != ctx->internal_pages)
138 kfree(ctx->ring_pages);
141 static int aio_setup_ring(struct kioctx *ctx)
143 struct aio_ring *ring;
144 unsigned nr_events = ctx->max_reqs;
145 struct mm_struct *mm = current->mm;
146 unsigned long size, populate;
149 /* Compensate for the ring buffer's head/tail overlap entry */
150 nr_events += 2; /* 1 is required, 2 for good luck */
152 size = sizeof(struct aio_ring);
153 size += sizeof(struct io_event) * nr_events;
154 nr_pages = (size + PAGE_SIZE-1) >> PAGE_SHIFT;
159 nr_events = (PAGE_SIZE * nr_pages - sizeof(struct aio_ring)) / sizeof(struct io_event);
162 ctx->ring_pages = ctx->internal_pages;
163 if (nr_pages > AIO_RING_PAGES) {
164 ctx->ring_pages = kcalloc(nr_pages, sizeof(struct page *),
166 if (!ctx->ring_pages)
170 ctx->mmap_size = nr_pages * PAGE_SIZE;
171 pr_debug("attempting mmap of %lu bytes\n", ctx->mmap_size);
172 down_write(&mm->mmap_sem);
173 ctx->mmap_base = do_mmap_pgoff(NULL, 0, ctx->mmap_size,
174 PROT_READ|PROT_WRITE,
175 MAP_ANONYMOUS|MAP_PRIVATE, 0, &populate);
176 if (IS_ERR((void *)ctx->mmap_base)) {
177 up_write(&mm->mmap_sem);
183 pr_debug("mmap address: 0x%08lx\n", ctx->mmap_base);
184 ctx->nr_pages = get_user_pages(current, mm, ctx->mmap_base, nr_pages,
185 1, 0, ctx->ring_pages, NULL);
186 up_write(&mm->mmap_sem);
188 if (unlikely(ctx->nr_pages != nr_pages)) {
193 mm_populate(ctx->mmap_base, populate);
195 ctx->user_id = ctx->mmap_base;
196 ctx->nr = nr_events; /* trusted copy */
198 ring = kmap_atomic(ctx->ring_pages[0]);
199 ring->nr = nr_events; /* user copy */
200 ring->id = ctx->user_id;
201 ring->head = ring->tail = 0;
202 ring->magic = AIO_RING_MAGIC;
203 ring->compat_features = AIO_RING_COMPAT_FEATURES;
204 ring->incompat_features = AIO_RING_INCOMPAT_FEATURES;
205 ring->header_length = sizeof(struct aio_ring);
207 flush_dcache_page(ctx->ring_pages[0]);
212 #define AIO_EVENTS_PER_PAGE (PAGE_SIZE / sizeof(struct io_event))
213 #define AIO_EVENTS_FIRST_PAGE ((PAGE_SIZE - sizeof(struct aio_ring)) / sizeof(struct io_event))
214 #define AIO_EVENTS_OFFSET (AIO_EVENTS_PER_PAGE - AIO_EVENTS_FIRST_PAGE)
216 void kiocb_set_cancel_fn(struct kiocb *req, kiocb_cancel_fn *cancel)
218 struct kioctx *ctx = req->ki_ctx;
221 spin_lock_irqsave(&ctx->ctx_lock, flags);
223 if (!req->ki_list.next)
224 list_add(&req->ki_list, &ctx->active_reqs);
226 req->ki_cancel = cancel;
228 spin_unlock_irqrestore(&ctx->ctx_lock, flags);
230 EXPORT_SYMBOL(kiocb_set_cancel_fn);
232 static int kiocb_cancel(struct kioctx *ctx, struct kiocb *kiocb,
233 struct io_event *res)
235 kiocb_cancel_fn *old, *cancel;
239 * Don't want to set kiocb->ki_cancel = KIOCB_CANCELLED unless it
240 * actually has a cancel function, hence the cmpxchg()
243 cancel = ACCESS_ONCE(kiocb->ki_cancel);
245 if (!cancel || cancel == KIOCB_CANCELLED)
249 cancel = cmpxchg(&kiocb->ki_cancel, old, KIOCB_CANCELLED);
250 } while (cancel != old);
252 atomic_inc(&kiocb->ki_users);
253 spin_unlock_irq(&ctx->ctx_lock);
255 memset(res, 0, sizeof(*res));
256 res->obj = (u64)(unsigned long)kiocb->ki_obj.user;
257 res->data = kiocb->ki_user_data;
258 ret = cancel(kiocb, res);
260 spin_lock_irq(&ctx->ctx_lock);
265 static void free_ioctx_rcu(struct rcu_head *head)
267 struct kioctx *ctx = container_of(head, struct kioctx, rcu_head);
268 kmem_cache_free(kioctx_cachep, ctx);
272 * When this function runs, the kioctx has been removed from the "hash table"
273 * and ctx->users has dropped to 0, so we know no more kiocbs can be submitted -
274 * now it's safe to cancel any that need to be.
276 static void free_ioctx(struct kioctx *ctx)
278 struct aio_ring *ring;
281 unsigned head, avail;
283 spin_lock_irq(&ctx->ctx_lock);
285 while (!list_empty(&ctx->active_reqs)) {
286 req = list_first_entry(&ctx->active_reqs,
287 struct kiocb, ki_list);
289 list_del_init(&req->ki_list);
290 kiocb_cancel(ctx, req, &res);
293 spin_unlock_irq(&ctx->ctx_lock);
295 ring = kmap_atomic(ctx->ring_pages[0]);
299 while (atomic_read(&ctx->reqs_active) > 0) {
300 wait_event(ctx->wait, head != ctx->tail);
302 avail = (head < ctx->tail ? ctx->tail : ctx->nr) - head;
304 atomic_sub(avail, &ctx->reqs_active);
309 WARN_ON(atomic_read(&ctx->reqs_active) < 0);
313 spin_lock(&aio_nr_lock);
314 BUG_ON(aio_nr - ctx->max_reqs > aio_nr);
315 aio_nr -= ctx->max_reqs;
316 spin_unlock(&aio_nr_lock);
318 pr_debug("freeing %p\n", ctx);
321 * Here the call_rcu() is between the wait_event() for reqs_active to
322 * hit 0, and freeing the ioctx.
324 * aio_complete() decrements reqs_active, but it has to touch the ioctx
325 * after to issue a wakeup so we use rcu.
327 call_rcu(&ctx->rcu_head, free_ioctx_rcu);
330 static void put_ioctx(struct kioctx *ctx)
332 if (unlikely(atomic_dec_and_test(&ctx->users)))
337 * Allocates and initializes an ioctx. Returns an ERR_PTR if it failed.
339 static struct kioctx *ioctx_alloc(unsigned nr_events)
341 struct mm_struct *mm = current->mm;
345 /* Prevent overflows */
346 if ((nr_events > (0x10000000U / sizeof(struct io_event))) ||
347 (nr_events > (0x10000000U / sizeof(struct kiocb)))) {
348 pr_debug("ENOMEM: nr_events too high\n");
349 return ERR_PTR(-EINVAL);
352 if (!nr_events || (unsigned long)nr_events > aio_max_nr)
353 return ERR_PTR(-EAGAIN);
355 ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL);
357 return ERR_PTR(-ENOMEM);
359 ctx->max_reqs = nr_events;
361 atomic_set(&ctx->users, 2);
362 atomic_set(&ctx->dead, 0);
363 spin_lock_init(&ctx->ctx_lock);
364 spin_lock_init(&ctx->completion_lock);
365 mutex_init(&ctx->ring_lock);
366 init_waitqueue_head(&ctx->wait);
368 INIT_LIST_HEAD(&ctx->active_reqs);
370 if (aio_setup_ring(ctx) < 0)
373 /* limit the number of system wide aios */
374 spin_lock(&aio_nr_lock);
375 if (aio_nr + nr_events > aio_max_nr ||
376 aio_nr + nr_events < aio_nr) {
377 spin_unlock(&aio_nr_lock);
380 aio_nr += ctx->max_reqs;
381 spin_unlock(&aio_nr_lock);
383 /* now link into global list. */
384 spin_lock(&mm->ioctx_lock);
385 hlist_add_head_rcu(&ctx->list, &mm->ioctx_list);
386 spin_unlock(&mm->ioctx_lock);
388 pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
389 ctx, ctx->user_id, mm, ctx->nr);
396 kmem_cache_free(kioctx_cachep, ctx);
397 pr_debug("error allocating ioctx %d\n", err);
401 static void kill_ioctx_work(struct work_struct *work)
403 struct kioctx *ctx = container_of(work, struct kioctx, rcu_work);
405 wake_up_all(&ctx->wait);
409 static void kill_ioctx_rcu(struct rcu_head *head)
411 struct kioctx *ctx = container_of(head, struct kioctx, rcu_head);
413 INIT_WORK(&ctx->rcu_work, kill_ioctx_work);
414 schedule_work(&ctx->rcu_work);
418 * Cancels all outstanding aio requests on an aio context. Used
419 * when the processes owning a context have all exited to encourage
420 * the rapid destruction of the kioctx.
422 static void kill_ioctx(struct kioctx *ctx)
424 if (!atomic_xchg(&ctx->dead, 1)) {
425 hlist_del_rcu(&ctx->list);
426 /* Between hlist_del_rcu() and dropping the initial ref */
430 * We can't punt to workqueue here because put_ioctx() ->
431 * free_ioctx() will unmap the ringbuffer, and that has to be
432 * done in the original process's context. kill_ioctx_rcu/work()
433 * exist for exit_aio(), as in that path free_ioctx() won't do
436 kill_ioctx_work(&ctx->rcu_work);
440 /* wait_on_sync_kiocb:
441 * Waits on the given sync kiocb to complete.
443 ssize_t wait_on_sync_kiocb(struct kiocb *iocb)
445 while (atomic_read(&iocb->ki_users)) {
446 set_current_state(TASK_UNINTERRUPTIBLE);
447 if (!atomic_read(&iocb->ki_users))
451 __set_current_state(TASK_RUNNING);
452 return iocb->ki_user_data;
454 EXPORT_SYMBOL(wait_on_sync_kiocb);
457 * exit_aio: called when the last user of mm goes away. At this point, there is
458 * no way for any new requests to be submited or any of the io_* syscalls to be
459 * called on the context.
461 * There may be outstanding kiocbs, but free_ioctx() will explicitly wait on
464 void exit_aio(struct mm_struct *mm)
467 struct hlist_node *n;
469 hlist_for_each_entry_safe(ctx, n, &mm->ioctx_list, list) {
470 if (1 != atomic_read(&ctx->users))
472 "exit_aio:ioctx still alive: %d %d %d\n",
473 atomic_read(&ctx->users),
474 atomic_read(&ctx->dead),
475 atomic_read(&ctx->reqs_active));
477 * We don't need to bother with munmap() here -
478 * exit_mmap(mm) is coming and it'll unmap everything.
479 * Since aio_free_ring() uses non-zero ->mmap_size
480 * as indicator that it needs to unmap the area,
481 * just set it to 0; aio_free_ring() is the only
482 * place that uses ->mmap_size, so it's safe.
486 if (!atomic_xchg(&ctx->dead, 1)) {
487 hlist_del_rcu(&ctx->list);
488 call_rcu(&ctx->rcu_head, kill_ioctx_rcu);
494 * Allocate a slot for an aio request. Increments the ki_users count
495 * of the kioctx so that the kioctx stays around until all requests are
496 * complete. Returns NULL if no requests are free.
498 * Returns with kiocb->ki_users set to 2. The io submit code path holds
499 * an extra reference while submitting the i/o.
500 * This prevents races between the aio code path referencing the
501 * req (after submitting it) and aio_complete() freeing the req.
503 static inline struct kiocb *aio_get_req(struct kioctx *ctx)
507 if (atomic_read(&ctx->reqs_active) >= ctx->nr)
510 if (atomic_inc_return(&ctx->reqs_active) > ctx->nr)
513 req = kmem_cache_alloc(kiocb_cachep, GFP_KERNEL|__GFP_ZERO);
517 atomic_set(&req->ki_users, 2);
522 atomic_dec(&ctx->reqs_active);
526 static void kiocb_free(struct kiocb *req)
530 if (req->ki_eventfd != NULL)
531 eventfd_ctx_put(req->ki_eventfd);
534 if (req->ki_iovec != &req->ki_inline_vec)
535 kfree(req->ki_iovec);
536 kmem_cache_free(kiocb_cachep, req);
539 void aio_put_req(struct kiocb *req)
541 if (atomic_dec_and_test(&req->ki_users))
544 EXPORT_SYMBOL(aio_put_req);
546 static struct kioctx *lookup_ioctx(unsigned long ctx_id)
548 struct mm_struct *mm = current->mm;
549 struct kioctx *ctx, *ret = NULL;
553 hlist_for_each_entry_rcu(ctx, &mm->ioctx_list, list) {
554 if (ctx->user_id == ctx_id){
555 atomic_inc(&ctx->users);
566 * Called when the io request on the given iocb is complete.
568 void aio_complete(struct kiocb *iocb, long res, long res2)
570 struct kioctx *ctx = iocb->ki_ctx;
571 struct aio_ring *ring;
572 struct io_event *ev_page, *event;
577 * Special case handling for sync iocbs:
578 * - events go directly into the iocb for fast handling
579 * - the sync task with the iocb in its stack holds the single iocb
580 * ref, no other paths have a way to get another ref
581 * - the sync task helpfully left a reference to itself in the iocb
583 if (is_sync_kiocb(iocb)) {
584 BUG_ON(atomic_read(&iocb->ki_users) != 1);
585 iocb->ki_user_data = res;
586 atomic_set(&iocb->ki_users, 0);
587 wake_up_process(iocb->ki_obj.tsk);
592 * Take rcu_read_lock() in case the kioctx is being destroyed, as we
593 * need to issue a wakeup after decrementing reqs_active.
597 if (iocb->ki_list.next) {
600 spin_lock_irqsave(&ctx->ctx_lock, flags);
601 list_del(&iocb->ki_list);
602 spin_unlock_irqrestore(&ctx->ctx_lock, flags);
606 * cancelled requests don't get events, userland was given one
607 * when the event got cancelled.
609 if (unlikely(xchg(&iocb->ki_cancel,
610 KIOCB_CANCELLED) == KIOCB_CANCELLED)) {
611 atomic_dec(&ctx->reqs_active);
612 /* Still need the wake_up in case free_ioctx is waiting */
617 * Add a completion event to the ring buffer. Must be done holding
618 * ctx->ctx_lock to prevent other code from messing with the tail
619 * pointer since we might be called from irq context.
621 spin_lock_irqsave(&ctx->completion_lock, flags);
624 pos = tail + AIO_EVENTS_OFFSET;
626 if (++tail >= ctx->nr)
629 ev_page = kmap_atomic(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
630 event = ev_page + pos % AIO_EVENTS_PER_PAGE;
632 event->obj = (u64)(unsigned long)iocb->ki_obj.user;
633 event->data = iocb->ki_user_data;
637 kunmap_atomic(ev_page);
638 flush_dcache_page(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
640 pr_debug("%p[%u]: %p: %p %Lx %lx %lx\n",
641 ctx, tail, iocb, iocb->ki_obj.user, iocb->ki_user_data,
644 /* after flagging the request as done, we
645 * must never even look at it again
647 smp_wmb(); /* make event visible before updating tail */
651 ring = kmap_atomic(ctx->ring_pages[0]);
654 flush_dcache_page(ctx->ring_pages[0]);
656 spin_unlock_irqrestore(&ctx->completion_lock, flags);
658 pr_debug("added to ring %p at [%u]\n", iocb, tail);
661 * Check if the user asked us to deliver the result through an
662 * eventfd. The eventfd_signal() function is safe to be called
665 if (iocb->ki_eventfd != NULL)
666 eventfd_signal(iocb->ki_eventfd, 1);
669 /* everything turned out well, dispose of the aiocb. */
673 * We have to order our ring_info tail store above and test
674 * of the wait list below outside the wait lock. This is
675 * like in wake_up_bit() where clearing a bit has to be
676 * ordered with the unlocked test.
680 if (waitqueue_active(&ctx->wait))
685 EXPORT_SYMBOL(aio_complete);
688 * Pull an event off of the ioctx's event ring. Returns the number of
691 static int aio_read_events_ring(struct kioctx *ctx,
692 struct io_event __user *event, long nr)
694 struct aio_ring *ring;
696 int ret = 0, copy_ret;
698 if (!mutex_trylock(&ctx->ring_lock)) {
699 __set_current_state(TASK_RUNNING);
700 mutex_lock(&ctx->ring_lock);
703 ring = kmap_atomic(ctx->ring_pages[0]);
707 pr_debug("h%u t%u m%u\n", head, ctx->tail, ctx->nr);
709 if (head == ctx->tail)
712 __set_current_state(TASK_RUNNING);
715 unsigned i = (head < ctx->tail ? ctx->tail : ctx->nr) - head;
719 if (head == ctx->tail)
722 i = min_t(int, i, nr - ret);
723 i = min_t(int, i, AIO_EVENTS_PER_PAGE -
724 ((head + AIO_EVENTS_OFFSET) % AIO_EVENTS_PER_PAGE));
726 pos = head + AIO_EVENTS_OFFSET;
727 page = ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE];
728 pos %= AIO_EVENTS_PER_PAGE;
731 copy_ret = copy_to_user(event + ret, ev + pos, sizeof(*ev) * i);
734 if (unlikely(copy_ret)) {
744 ring = kmap_atomic(ctx->ring_pages[0]);
747 flush_dcache_page(ctx->ring_pages[0]);
749 pr_debug("%d h%u t%u\n", ret, head, ctx->tail);
751 atomic_sub(ret, &ctx->reqs_active);
753 mutex_unlock(&ctx->ring_lock);
758 static bool aio_read_events(struct kioctx *ctx, long min_nr, long nr,
759 struct io_event __user *event, long *i)
761 long ret = aio_read_events_ring(ctx, event + *i, nr - *i);
766 if (unlikely(atomic_read(&ctx->dead)))
772 return ret < 0 || *i >= min_nr;
775 static long read_events(struct kioctx *ctx, long min_nr, long nr,
776 struct io_event __user *event,
777 struct timespec __user *timeout)
779 ktime_t until = { .tv64 = KTIME_MAX };
785 if (unlikely(copy_from_user(&ts, timeout, sizeof(ts))))
788 until = timespec_to_ktime(ts);
791 wait_event_interruptible_hrtimeout(ctx->wait,
792 aio_read_events(ctx, min_nr, nr, event, &ret), until);
794 if (!ret && signal_pending(current))
801 * Create an aio_context capable of receiving at least nr_events.
802 * ctxp must not point to an aio_context that already exists, and
803 * must be initialized to 0 prior to the call. On successful
804 * creation of the aio_context, *ctxp is filled in with the resulting
805 * handle. May fail with -EINVAL if *ctxp is not initialized,
806 * if the specified nr_events exceeds internal limits. May fail
807 * with -EAGAIN if the specified nr_events exceeds the user's limit
808 * of available events. May fail with -ENOMEM if insufficient kernel
809 * resources are available. May fail with -EFAULT if an invalid
810 * pointer is passed for ctxp. Will fail with -ENOSYS if not
813 SYSCALL_DEFINE2(io_setup, unsigned, nr_events, aio_context_t __user *, ctxp)
815 struct kioctx *ioctx = NULL;
819 ret = get_user(ctx, ctxp);
824 if (unlikely(ctx || nr_events == 0)) {
825 pr_debug("EINVAL: io_setup: ctx %lu nr_events %u\n",
830 ioctx = ioctx_alloc(nr_events);
831 ret = PTR_ERR(ioctx);
832 if (!IS_ERR(ioctx)) {
833 ret = put_user(ioctx->user_id, ctxp);
844 * Destroy the aio_context specified. May cancel any outstanding
845 * AIOs and block on completion. Will fail with -ENOSYS if not
846 * implemented. May fail with -EINVAL if the context pointed to
849 SYSCALL_DEFINE1(io_destroy, aio_context_t, ctx)
851 struct kioctx *ioctx = lookup_ioctx(ctx);
852 if (likely(NULL != ioctx)) {
857 pr_debug("EINVAL: io_destroy: invalid context id\n");
861 static void aio_advance_iovec(struct kiocb *iocb, ssize_t ret)
863 struct iovec *iov = &iocb->ki_iovec[iocb->ki_cur_seg];
867 while (iocb->ki_cur_seg < iocb->ki_nr_segs && ret > 0) {
868 ssize_t this = min((ssize_t)iov->iov_len, ret);
869 iov->iov_base += this;
870 iov->iov_len -= this;
871 iocb->ki_left -= this;
873 if (iov->iov_len == 0) {
879 /* the caller should not have done more io than what fit in
880 * the remaining iovecs */
881 BUG_ON(ret > 0 && iocb->ki_left == 0);
884 static ssize_t aio_rw_vect_retry(struct kiocb *iocb)
886 struct file *file = iocb->ki_filp;
887 struct address_space *mapping = file->f_mapping;
888 struct inode *inode = mapping->host;
889 ssize_t (*rw_op)(struct kiocb *, const struct iovec *,
890 unsigned long, loff_t);
892 unsigned short opcode;
894 if ((iocb->ki_opcode == IOCB_CMD_PREADV) ||
895 (iocb->ki_opcode == IOCB_CMD_PREAD)) {
896 rw_op = file->f_op->aio_read;
897 opcode = IOCB_CMD_PREADV;
899 rw_op = file->f_op->aio_write;
900 opcode = IOCB_CMD_PWRITEV;
903 /* This matches the pread()/pwrite() logic */
904 if (iocb->ki_pos < 0)
908 ret = rw_op(iocb, &iocb->ki_iovec[iocb->ki_cur_seg],
909 iocb->ki_nr_segs - iocb->ki_cur_seg,
912 aio_advance_iovec(iocb, ret);
914 /* retry all partial writes. retry partial reads as long as its a
916 } while (ret > 0 && iocb->ki_left > 0 &&
917 (opcode == IOCB_CMD_PWRITEV ||
918 (!S_ISFIFO(inode->i_mode) && !S_ISSOCK(inode->i_mode))));
920 /* This means we must have transferred all that we could */
921 /* No need to retry anymore */
922 if ((ret == 0) || (iocb->ki_left == 0))
923 ret = iocb->ki_nbytes - iocb->ki_left;
925 /* If we managed to write some out we return that, rather than
926 * the eventual error. */
927 if (opcode == IOCB_CMD_PWRITEV
928 && ret < 0 && ret != -EIOCBQUEUED
929 && iocb->ki_nbytes - iocb->ki_left)
930 ret = iocb->ki_nbytes - iocb->ki_left;
935 static ssize_t aio_fdsync(struct kiocb *iocb)
937 struct file *file = iocb->ki_filp;
938 ssize_t ret = -EINVAL;
940 if (file->f_op->aio_fsync)
941 ret = file->f_op->aio_fsync(iocb, 1);
945 static ssize_t aio_fsync(struct kiocb *iocb)
947 struct file *file = iocb->ki_filp;
948 ssize_t ret = -EINVAL;
950 if (file->f_op->aio_fsync)
951 ret = file->f_op->aio_fsync(iocb, 0);
955 static ssize_t aio_setup_vectored_rw(int type, struct kiocb *kiocb, bool compat)
961 ret = compat_rw_copy_check_uvector(type,
962 (struct compat_iovec __user *)kiocb->ki_buf,
963 kiocb->ki_nbytes, 1, &kiocb->ki_inline_vec,
967 ret = rw_copy_check_uvector(type,
968 (struct iovec __user *)kiocb->ki_buf,
969 kiocb->ki_nbytes, 1, &kiocb->ki_inline_vec,
974 ret = rw_verify_area(type, kiocb->ki_filp, &kiocb->ki_pos, ret);
978 kiocb->ki_nr_segs = kiocb->ki_nbytes;
979 kiocb->ki_cur_seg = 0;
980 /* ki_nbytes/left now reflect bytes instead of segs */
981 kiocb->ki_nbytes = ret;
982 kiocb->ki_left = ret;
989 static ssize_t aio_setup_single_vector(int type, struct file * file, struct kiocb *kiocb)
993 bytes = rw_verify_area(type, file, &kiocb->ki_pos, kiocb->ki_left);
997 kiocb->ki_iovec = &kiocb->ki_inline_vec;
998 kiocb->ki_iovec->iov_base = kiocb->ki_buf;
999 kiocb->ki_iovec->iov_len = bytes;
1000 kiocb->ki_nr_segs = 1;
1001 kiocb->ki_cur_seg = 0;
1007 * Performs the initial checks and aio retry method
1008 * setup for the kiocb at the time of io submission.
1010 static ssize_t aio_setup_iocb(struct kiocb *kiocb, bool compat)
1012 struct file *file = kiocb->ki_filp;
1015 switch (kiocb->ki_opcode) {
1016 case IOCB_CMD_PREAD:
1018 if (unlikely(!(file->f_mode & FMODE_READ)))
1021 if (unlikely(!access_ok(VERIFY_WRITE, kiocb->ki_buf,
1024 ret = aio_setup_single_vector(READ, file, kiocb);
1028 if (file->f_op->aio_read)
1029 kiocb->ki_retry = aio_rw_vect_retry;
1031 case IOCB_CMD_PWRITE:
1033 if (unlikely(!(file->f_mode & FMODE_WRITE)))
1036 if (unlikely(!access_ok(VERIFY_READ, kiocb->ki_buf,
1039 ret = aio_setup_single_vector(WRITE, file, kiocb);
1043 if (file->f_op->aio_write)
1044 kiocb->ki_retry = aio_rw_vect_retry;
1046 case IOCB_CMD_PREADV:
1048 if (unlikely(!(file->f_mode & FMODE_READ)))
1050 ret = aio_setup_vectored_rw(READ, kiocb, compat);
1054 if (file->f_op->aio_read)
1055 kiocb->ki_retry = aio_rw_vect_retry;
1057 case IOCB_CMD_PWRITEV:
1059 if (unlikely(!(file->f_mode & FMODE_WRITE)))
1061 ret = aio_setup_vectored_rw(WRITE, kiocb, compat);
1065 if (file->f_op->aio_write)
1066 kiocb->ki_retry = aio_rw_vect_retry;
1068 case IOCB_CMD_FDSYNC:
1070 if (file->f_op->aio_fsync)
1071 kiocb->ki_retry = aio_fdsync;
1073 case IOCB_CMD_FSYNC:
1075 if (file->f_op->aio_fsync)
1076 kiocb->ki_retry = aio_fsync;
1079 pr_debug("EINVAL: no operation provided\n");
1083 if (!kiocb->ki_retry)
1089 static int io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb,
1090 struct iocb *iocb, bool compat)
1095 /* enforce forwards compatibility on users */
1096 if (unlikely(iocb->aio_reserved1 || iocb->aio_reserved2)) {
1097 pr_debug("EINVAL: reserve field set\n");
1101 /* prevent overflows */
1103 (iocb->aio_buf != (unsigned long)iocb->aio_buf) ||
1104 (iocb->aio_nbytes != (size_t)iocb->aio_nbytes) ||
1105 ((ssize_t)iocb->aio_nbytes < 0)
1107 pr_debug("EINVAL: io_submit: overflow check\n");
1111 req = aio_get_req(ctx); /* returns with 2 references to req */
1115 req->ki_filp = fget(iocb->aio_fildes);
1116 if (unlikely(!req->ki_filp)) {
1121 if (iocb->aio_flags & IOCB_FLAG_RESFD) {
1123 * If the IOCB_FLAG_RESFD flag of aio_flags is set, get an
1124 * instance of the file* now. The file descriptor must be
1125 * an eventfd() fd, and will be signaled for each completed
1126 * event using the eventfd_signal() function.
1128 req->ki_eventfd = eventfd_ctx_fdget((int) iocb->aio_resfd);
1129 if (IS_ERR(req->ki_eventfd)) {
1130 ret = PTR_ERR(req->ki_eventfd);
1131 req->ki_eventfd = NULL;
1136 ret = put_user(req->ki_key, &user_iocb->aio_key);
1137 if (unlikely(ret)) {
1138 pr_debug("EFAULT: aio_key\n");
1142 req->ki_obj.user = user_iocb;
1143 req->ki_user_data = iocb->aio_data;
1144 req->ki_pos = iocb->aio_offset;
1146 req->ki_buf = (char __user *)(unsigned long)iocb->aio_buf;
1147 req->ki_left = req->ki_nbytes = iocb->aio_nbytes;
1148 req->ki_opcode = iocb->aio_lio_opcode;
1150 ret = aio_setup_iocb(req, compat);
1154 ret = req->ki_retry(req);
1155 if (ret != -EIOCBQUEUED) {
1157 * There's no easy way to restart the syscall since other AIO's
1158 * may be already running. Just fail this IO with EINTR.
1160 if (unlikely(ret == -ERESTARTSYS || ret == -ERESTARTNOINTR ||
1161 ret == -ERESTARTNOHAND || ret == -ERESTART_RESTARTBLOCK))
1163 aio_complete(req, ret, 0);
1166 aio_put_req(req); /* drop extra ref to req */
1170 atomic_dec(&ctx->reqs_active);
1171 aio_put_req(req); /* drop extra ref to req */
1172 aio_put_req(req); /* drop i/o ref to req */
1176 long do_io_submit(aio_context_t ctx_id, long nr,
1177 struct iocb __user *__user *iocbpp, bool compat)
1182 struct blk_plug plug;
1184 if (unlikely(nr < 0))
1187 if (unlikely(nr > LONG_MAX/sizeof(*iocbpp)))
1188 nr = LONG_MAX/sizeof(*iocbpp);
1190 if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))
1193 ctx = lookup_ioctx(ctx_id);
1194 if (unlikely(!ctx)) {
1195 pr_debug("EINVAL: invalid context id\n");
1199 blk_start_plug(&plug);
1202 * AKPM: should this return a partial result if some of the IOs were
1203 * successfully submitted?
1205 for (i=0; i<nr; i++) {
1206 struct iocb __user *user_iocb;
1209 if (unlikely(__get_user(user_iocb, iocbpp + i))) {
1214 if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
1219 ret = io_submit_one(ctx, user_iocb, &tmp, compat);
1223 blk_finish_plug(&plug);
1230 * Queue the nr iocbs pointed to by iocbpp for processing. Returns
1231 * the number of iocbs queued. May return -EINVAL if the aio_context
1232 * specified by ctx_id is invalid, if nr is < 0, if the iocb at
1233 * *iocbpp[0] is not properly initialized, if the operation specified
1234 * is invalid for the file descriptor in the iocb. May fail with
1235 * -EFAULT if any of the data structures point to invalid data. May
1236 * fail with -EBADF if the file descriptor specified in the first
1237 * iocb is invalid. May fail with -EAGAIN if insufficient resources
1238 * are available to queue any iocbs. Will return 0 if nr is 0. Will
1239 * fail with -ENOSYS if not implemented.
1241 SYSCALL_DEFINE3(io_submit, aio_context_t, ctx_id, long, nr,
1242 struct iocb __user * __user *, iocbpp)
1244 return do_io_submit(ctx_id, nr, iocbpp, 0);
1248 * Finds a given iocb for cancellation.
1250 static struct kiocb *lookup_kiocb(struct kioctx *ctx, struct iocb __user *iocb,
1253 struct list_head *pos;
1255 assert_spin_locked(&ctx->ctx_lock);
1257 /* TODO: use a hash or array, this sucks. */
1258 list_for_each(pos, &ctx->active_reqs) {
1259 struct kiocb *kiocb = list_kiocb(pos);
1260 if (kiocb->ki_obj.user == iocb && kiocb->ki_key == key)
1267 * Attempts to cancel an iocb previously passed to io_submit. If
1268 * the operation is successfully cancelled, the resulting event is
1269 * copied into the memory pointed to by result without being placed
1270 * into the completion queue and 0 is returned. May fail with
1271 * -EFAULT if any of the data structures pointed to are invalid.
1272 * May fail with -EINVAL if aio_context specified by ctx_id is
1273 * invalid. May fail with -EAGAIN if the iocb specified was not
1274 * cancelled. Will fail with -ENOSYS if not implemented.
1276 SYSCALL_DEFINE3(io_cancel, aio_context_t, ctx_id, struct iocb __user *, iocb,
1277 struct io_event __user *, result)
1279 struct io_event res;
1281 struct kiocb *kiocb;
1285 ret = get_user(key, &iocb->aio_key);
1289 ctx = lookup_ioctx(ctx_id);
1293 spin_lock_irq(&ctx->ctx_lock);
1295 kiocb = lookup_kiocb(ctx, iocb, key);
1297 ret = kiocb_cancel(ctx, kiocb, &res);
1301 spin_unlock_irq(&ctx->ctx_lock);
1304 /* Cancellation succeeded -- copy the result
1305 * into the user's buffer.
1307 if (copy_to_user(result, &res, sizeof(res)))
1317 * Attempts to read at least min_nr events and up to nr events from
1318 * the completion queue for the aio_context specified by ctx_id. If
1319 * it succeeds, the number of read events is returned. May fail with
1320 * -EINVAL if ctx_id is invalid, if min_nr is out of range, if nr is
1321 * out of range, if timeout is out of range. May fail with -EFAULT
1322 * if any of the memory specified is invalid. May return 0 or
1323 * < min_nr if the timeout specified by timeout has elapsed
1324 * before sufficient events are available, where timeout == NULL
1325 * specifies an infinite timeout. Note that the timeout pointed to by
1326 * timeout is relative and will be updated if not NULL and the
1327 * operation blocks. Will fail with -ENOSYS if not implemented.
1329 SYSCALL_DEFINE5(io_getevents, aio_context_t, ctx_id,
1332 struct io_event __user *, events,
1333 struct timespec __user *, timeout)
1335 struct kioctx *ioctx = lookup_ioctx(ctx_id);
1338 if (likely(ioctx)) {
1339 if (likely(min_nr <= nr && min_nr >= 0))
1340 ret = read_events(ioctx, min_nr, nr, events, timeout);