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/percpu.h>
30 #include <linux/slab.h>
31 #include <linux/timer.h>
32 #include <linux/aio.h>
33 #include <linux/highmem.h>
34 #include <linux/workqueue.h>
35 #include <linux/security.h>
36 #include <linux/eventfd.h>
37 #include <linux/blkdev.h>
38 #include <linux/compat.h>
39 #include <linux/migrate.h>
40 #include <linux/ramfs.h>
41 #include <linux/percpu-refcount.h>
42 #include <linux/mount.h>
44 #include <asm/kmap_types.h>
45 #include <asm/uaccess.h>
49 #define AIO_RING_MAGIC 0xa10a10a1
50 #define AIO_RING_COMPAT_FEATURES 1
51 #define AIO_RING_COMPAT_THREADED 2
52 #define AIO_RING_INCOMPAT_FEATURES 0
54 unsigned id; /* kernel internal index number */
55 unsigned nr; /* number of io_events */
56 unsigned head; /* Written to by userland or under ring_lock
57 * mutex by aio_read_events_ring(). */
61 unsigned compat_features;
62 unsigned incompat_features;
63 unsigned header_length; /* size of aio_ring */
66 struct io_event io_events[0];
67 }; /* 128 bytes + ring size */
69 #define AIO_RING_PAGES 8
74 struct kioctx *table[];
78 unsigned reqs_available;
82 struct completion comp;
87 struct percpu_ref users;
90 struct percpu_ref reqs;
92 unsigned long user_id;
94 struct __percpu kioctx_cpu *cpu;
97 * For percpu reqs_available, number of slots we move to/from global
102 * This is what userspace passed to io_setup(), it's not used for
103 * anything but counting against the global max_reqs quota.
105 * The real limit is nr_events - 1, which will be larger (see
110 /* Size of ringbuffer, in units of struct io_event */
113 unsigned long mmap_base;
114 unsigned long mmap_size;
116 struct page **ring_pages;
119 struct work_struct free_work;
122 * signals when all in-flight requests are done
124 struct ctx_rq_wait *rq_wait;
128 * This counts the number of available slots in the ringbuffer,
129 * so we avoid overflowing it: it's decremented (if positive)
130 * when allocating a kiocb and incremented when the resulting
131 * io_event is pulled off the ringbuffer.
133 * We batch accesses to it with a percpu version.
135 atomic_t reqs_available;
136 } ____cacheline_aligned_in_smp;
140 struct list_head active_reqs; /* used for cancellation */
141 } ____cacheline_aligned_in_smp;
144 struct mutex ring_lock;
145 wait_queue_head_t wait;
146 } ____cacheline_aligned_in_smp;
150 unsigned completed_events;
151 spinlock_t completion_lock;
152 } ____cacheline_aligned_in_smp;
154 struct page *internal_pages[AIO_RING_PAGES];
155 struct file *aio_ring_file;
158 struct mm_struct *mm;
162 typedef long (*aio_thread_work_fn_t)(struct aio_kiocb *iocb);
165 * We use ki_cancel == KIOCB_CANCELLED to indicate that a kiocb has been either
166 * cancelled or completed (this makes a certain amount of sense because
167 * successful cancellation - io_cancel() - does deliver the completion to
170 * And since most things don't implement kiocb cancellation and we'd really like
171 * kiocb completion to be lockless when possible, we use ki_cancel to
172 * synchronize cancellation and completion - we only set it to KIOCB_CANCELLED
173 * with xchg() or cmpxchg(), see batch_complete_aio() and kiocb_cancel().
175 #define KIOCB_CANCELLED ((void *) (~0ULL))
180 struct kioctx *ki_ctx;
181 kiocb_cancel_fn *ki_cancel;
183 struct iocb __user *ki_user_iocb; /* user's aiocb */
184 __u64 ki_user_data; /* user's data for completion */
186 struct list_head ki_list; /* the aio core uses this
187 * for cancellation */
190 * If the aio_resfd field of the userspace iocb is not zero,
191 * this is the underlying eventfd context to deliver events to.
193 struct eventfd_ctx *ki_eventfd;
195 struct iov_iter ki_iter;
196 struct iovec *ki_iovec;
197 struct iovec ki_inline_vecs[UIO_FASTIOV];
199 // Fields used for threaded aio helper.
200 struct task_struct *ki_submit_task;
201 #if IS_ENABLED(CONFIG_AIO_THREAD)
202 struct task_struct *ki_cancel_task;
203 unsigned long ki_data;
204 unsigned long ki_rlimit_fsize;
205 aio_thread_work_fn_t ki_work_fn;
206 struct work_struct ki_work;
210 /*------ sysctl variables----*/
211 static DEFINE_SPINLOCK(aio_nr_lock);
212 unsigned long aio_nr; /* current system wide number of aio requests */
213 unsigned long aio_max_nr = 0x10000; /* system wide maximum number of aio requests */
214 #if IS_ENABLED(CONFIG_AIO_THREAD)
215 unsigned long aio_auto_threads = 0; /* Currently disabled by default */
217 /*----end sysctl variables---*/
219 static struct kmem_cache *kiocb_cachep;
220 static struct kmem_cache *kioctx_cachep;
222 static struct vfsmount *aio_mnt;
224 static const struct file_operations aio_ring_fops;
225 static const struct address_space_operations aio_ctx_aops;
227 static void aio_complete(struct kiocb *kiocb, long res, long res2);
229 static struct file *aio_private_file(struct kioctx *ctx, loff_t nr_pages)
231 struct qstr this = QSTR_INIT("[aio]", 5);
234 struct inode *inode = alloc_anon_inode(aio_mnt->mnt_sb);
236 return ERR_CAST(inode);
238 inode->i_mapping->a_ops = &aio_ctx_aops;
239 inode->i_mapping->private_data = ctx;
240 inode->i_size = PAGE_SIZE * nr_pages;
242 path.dentry = d_alloc_pseudo(aio_mnt->mnt_sb, &this);
245 return ERR_PTR(-ENOMEM);
247 path.mnt = mntget(aio_mnt);
249 d_instantiate(path.dentry, inode);
250 file = alloc_file(&path, FMODE_READ | FMODE_WRITE, &aio_ring_fops);
256 file->f_flags = O_RDWR;
260 static struct dentry *aio_mount(struct file_system_type *fs_type,
261 int flags, const char *dev_name, void *data)
263 static const struct dentry_operations ops = {
264 .d_dname = simple_dname,
266 return mount_pseudo(fs_type, "aio:", NULL, &ops, AIO_RING_MAGIC);
270 * Creates the slab caches used by the aio routines, panic on
271 * failure as this is done early during the boot sequence.
273 static int __init aio_setup(void)
275 static struct file_system_type aio_fs = {
278 .kill_sb = kill_anon_super,
280 aio_mnt = kern_mount(&aio_fs);
282 panic("Failed to create aio fs mount.");
284 kiocb_cachep = KMEM_CACHE(aio_kiocb, SLAB_HWCACHE_ALIGN|SLAB_PANIC);
285 kioctx_cachep = KMEM_CACHE(kioctx,SLAB_HWCACHE_ALIGN|SLAB_PANIC);
287 pr_debug("sizeof(struct page) = %zu\n", sizeof(struct page));
291 __initcall(aio_setup);
293 static void put_aio_ring_file(struct kioctx *ctx)
295 struct file *aio_ring_file = ctx->aio_ring_file;
297 truncate_setsize(aio_ring_file->f_inode, 0);
299 /* Prevent further access to the kioctx from migratepages */
300 spin_lock(&aio_ring_file->f_inode->i_mapping->private_lock);
301 aio_ring_file->f_inode->i_mapping->private_data = NULL;
302 ctx->aio_ring_file = NULL;
303 spin_unlock(&aio_ring_file->f_inode->i_mapping->private_lock);
309 static void aio_free_ring(struct kioctx *ctx)
313 /* Disconnect the kiotx from the ring file. This prevents future
314 * accesses to the kioctx from page migration.
316 put_aio_ring_file(ctx);
318 for (i = 0; i < ctx->nr_pages; i++) {
320 pr_debug("pid(%d) [%d] page->count=%d\n", current->pid, i,
321 page_count(ctx->ring_pages[i]));
322 page = ctx->ring_pages[i];
325 ctx->ring_pages[i] = NULL;
329 if (ctx->ring_pages && ctx->ring_pages != ctx->internal_pages) {
330 kfree(ctx->ring_pages);
331 ctx->ring_pages = NULL;
335 static int aio_ring_mremap(struct vm_area_struct *vma)
337 struct file *file = vma->vm_file;
338 struct mm_struct *mm = vma->vm_mm;
339 struct kioctx_table *table;
340 int i, res = -EINVAL;
342 spin_lock(&mm->ioctx_lock);
344 table = rcu_dereference(mm->ioctx_table);
345 for (i = 0; i < table->nr; i++) {
348 ctx = table->table[i];
349 if (ctx && ctx->aio_ring_file == file) {
350 if (!atomic_read(&ctx->dead)) {
351 ctx->user_id = ctx->mmap_base = vma->vm_start;
359 spin_unlock(&mm->ioctx_lock);
363 static const struct vm_operations_struct aio_ring_vm_ops = {
364 .mremap = aio_ring_mremap,
365 #if IS_ENABLED(CONFIG_MMU)
366 .fault = filemap_fault,
367 .map_pages = filemap_map_pages,
368 .page_mkwrite = filemap_page_mkwrite,
372 static int aio_ring_mmap(struct file *file, struct vm_area_struct *vma)
374 vma->vm_flags |= VM_DONTEXPAND;
375 vma->vm_ops = &aio_ring_vm_ops;
379 static const struct file_operations aio_ring_fops = {
380 .mmap = aio_ring_mmap,
383 #if IS_ENABLED(CONFIG_MIGRATION)
384 static int aio_migratepage(struct address_space *mapping, struct page *new,
385 struct page *old, enum migrate_mode mode)
394 /* mapping->private_lock here protects against the kioctx teardown. */
395 spin_lock(&mapping->private_lock);
396 ctx = mapping->private_data;
402 /* The ring_lock mutex. The prevents aio_read_events() from writing
403 * to the ring's head, and prevents page migration from mucking in
404 * a partially initialized kiotx.
406 if (!mutex_trylock(&ctx->ring_lock)) {
412 if (idx < (pgoff_t)ctx->nr_pages) {
413 /* Make sure the old page hasn't already been changed */
414 if (ctx->ring_pages[idx] != old)
422 /* Writeback must be complete */
423 BUG_ON(PageWriteback(old));
426 rc = migrate_page_move_mapping(mapping, new, old, NULL, mode, 1);
427 if (rc != MIGRATEPAGE_SUCCESS) {
432 /* Take completion_lock to prevent other writes to the ring buffer
433 * while the old page is copied to the new. This prevents new
434 * events from being lost.
436 spin_lock_irqsave(&ctx->completion_lock, flags);
437 migrate_page_copy(new, old);
438 BUG_ON(ctx->ring_pages[idx] != old);
439 ctx->ring_pages[idx] = new;
440 spin_unlock_irqrestore(&ctx->completion_lock, flags);
442 /* The old page is no longer accessible. */
446 mutex_unlock(&ctx->ring_lock);
448 spin_unlock(&mapping->private_lock);
453 static const struct address_space_operations aio_ctx_aops = {
454 .set_page_dirty = __set_page_dirty_no_writeback,
455 #if IS_ENABLED(CONFIG_MIGRATION)
456 .migratepage = aio_migratepage,
460 static int aio_setup_ring(struct kioctx *ctx)
462 struct aio_ring *ring;
463 unsigned nr_events = ctx->max_reqs;
464 struct mm_struct *mm = current->mm;
465 unsigned long size, unused;
470 /* Compensate for the ring buffer's head/tail overlap entry */
471 nr_events += 2; /* 1 is required, 2 for good luck */
473 size = sizeof(struct aio_ring);
474 size += sizeof(struct io_event) * nr_events;
476 nr_pages = PFN_UP(size);
480 file = aio_private_file(ctx, nr_pages);
482 ctx->aio_ring_file = NULL;
486 ctx->aio_ring_file = file;
487 nr_events = (PAGE_SIZE * nr_pages - sizeof(struct aio_ring))
488 / sizeof(struct io_event);
490 ctx->ring_pages = ctx->internal_pages;
491 if (nr_pages > AIO_RING_PAGES) {
492 ctx->ring_pages = kcalloc(nr_pages, sizeof(struct page *),
494 if (!ctx->ring_pages) {
495 put_aio_ring_file(ctx);
500 for (i = 0; i < nr_pages; i++) {
502 page = find_or_create_page(file->f_inode->i_mapping,
503 i, GFP_HIGHUSER | __GFP_ZERO);
506 pr_debug("pid(%d) page[%d]->count=%d\n",
507 current->pid, i, page_count(page));
508 SetPageUptodate(page);
511 ctx->ring_pages[i] = page;
515 if (unlikely(i != nr_pages)) {
520 ctx->mmap_size = nr_pages * PAGE_SIZE;
521 pr_debug("attempting mmap of %lu bytes\n", ctx->mmap_size);
523 down_write(&mm->mmap_sem);
524 ctx->mmap_base = do_mmap_pgoff(ctx->aio_ring_file, 0, ctx->mmap_size,
525 PROT_READ | PROT_WRITE,
526 MAP_SHARED, 0, &unused);
527 up_write(&mm->mmap_sem);
528 if (IS_ERR((void *)ctx->mmap_base)) {
534 pr_debug("mmap address: 0x%08lx\n", ctx->mmap_base);
536 ctx->user_id = ctx->mmap_base;
537 ctx->nr_events = nr_events; /* trusted copy */
539 ring = kmap_atomic(ctx->ring_pages[0]);
540 ring->nr = nr_events; /* user copy */
542 ring->head = ring->tail = 0;
543 ring->magic = AIO_RING_MAGIC;
544 ring->compat_features = AIO_RING_COMPAT_FEATURES;
545 #if IS_ENABLED(CONFIG_AIO_THREAD)
546 if (aio_auto_threads & 1)
547 ring->compat_features |= AIO_RING_COMPAT_THREADED;
549 ring->incompat_features = AIO_RING_INCOMPAT_FEATURES;
550 ring->header_length = sizeof(struct aio_ring);
552 flush_dcache_page(ctx->ring_pages[0]);
557 #define AIO_EVENTS_PER_PAGE (PAGE_SIZE / sizeof(struct io_event))
558 #define AIO_EVENTS_FIRST_PAGE ((PAGE_SIZE - sizeof(struct aio_ring)) / sizeof(struct io_event))
559 #define AIO_EVENTS_OFFSET (AIO_EVENTS_PER_PAGE - AIO_EVENTS_FIRST_PAGE)
561 void kiocb_set_cancel_fn(struct kiocb *iocb, kiocb_cancel_fn *cancel)
563 struct aio_kiocb *req = container_of(iocb, struct aio_kiocb, common);
564 struct kioctx *ctx = req->ki_ctx;
567 spin_lock_irqsave(&ctx->ctx_lock, flags);
569 if (!req->ki_list.next)
570 list_add(&req->ki_list, &ctx->active_reqs);
572 req->ki_cancel = cancel;
574 spin_unlock_irqrestore(&ctx->ctx_lock, flags);
576 EXPORT_SYMBOL(kiocb_set_cancel_fn);
578 static int kiocb_cancel(struct aio_kiocb *kiocb)
580 kiocb_cancel_fn *old, *cancel;
583 * Don't want to set kiocb->ki_cancel = KIOCB_CANCELLED unless it
584 * actually has a cancel function, hence the cmpxchg()
587 cancel = ACCESS_ONCE(kiocb->ki_cancel);
589 if (!cancel || cancel == KIOCB_CANCELLED)
593 cancel = cmpxchg(&kiocb->ki_cancel, old, KIOCB_CANCELLED);
594 } while (cancel != old);
596 return cancel(&kiocb->common);
599 struct mm_struct *aio_get_mm(struct kiocb *req)
601 if (req->ki_complete == aio_complete) {
602 struct aio_kiocb *iocb;
603 iocb = container_of(req, struct aio_kiocb, common);
604 return iocb->ki_ctx->mm;
609 struct task_struct *aio_get_task(struct kiocb *req)
611 if (req->ki_complete == aio_complete) {
612 struct aio_kiocb *iocb;
613 iocb = container_of(req, struct aio_kiocb, common);
614 return iocb->ki_submit_task;
619 static void free_ioctx(struct work_struct *work)
621 struct kioctx *ctx = container_of(work, struct kioctx, free_work);
623 pr_debug("freeing %p\n", ctx);
626 free_percpu(ctx->cpu);
627 percpu_ref_exit(&ctx->reqs);
628 percpu_ref_exit(&ctx->users);
629 kmem_cache_free(kioctx_cachep, ctx);
632 static void free_ioctx_reqs(struct percpu_ref *ref)
634 struct kioctx *ctx = container_of(ref, struct kioctx, reqs);
636 /* At this point we know that there are no any in-flight requests */
637 if (ctx->rq_wait && atomic_dec_and_test(&ctx->rq_wait->count))
638 complete(&ctx->rq_wait->comp);
640 INIT_WORK(&ctx->free_work, free_ioctx);
641 schedule_work(&ctx->free_work);
645 * When this function runs, the kioctx has been removed from the "hash table"
646 * and ctx->users has dropped to 0, so we know no more kiocbs can be submitted -
647 * now it's safe to cancel any that need to be.
649 static void free_ioctx_users(struct percpu_ref *ref)
651 struct kioctx *ctx = container_of(ref, struct kioctx, users);
652 struct aio_kiocb *req;
654 spin_lock_irq(&ctx->ctx_lock);
656 while (!list_empty(&ctx->active_reqs)) {
657 req = list_first_entry(&ctx->active_reqs,
658 struct aio_kiocb, ki_list);
660 list_del_init(&req->ki_list);
664 spin_unlock_irq(&ctx->ctx_lock);
666 percpu_ref_kill(&ctx->reqs);
667 percpu_ref_put(&ctx->reqs);
670 static int ioctx_add_table(struct kioctx *ctx, struct mm_struct *mm)
673 struct kioctx_table *table, *old;
674 struct aio_ring *ring;
676 spin_lock(&mm->ioctx_lock);
677 table = rcu_dereference_raw(mm->ioctx_table);
681 for (i = 0; i < table->nr; i++)
682 if (!table->table[i]) {
684 table->table[i] = ctx;
685 spin_unlock(&mm->ioctx_lock);
687 /* While kioctx setup is in progress,
688 * we are protected from page migration
689 * changes ring_pages by ->ring_lock.
691 ring = kmap_atomic(ctx->ring_pages[0]);
697 new_nr = (table ? table->nr : 1) * 4;
698 spin_unlock(&mm->ioctx_lock);
700 table = kzalloc(sizeof(*table) + sizeof(struct kioctx *) *
707 spin_lock(&mm->ioctx_lock);
708 old = rcu_dereference_raw(mm->ioctx_table);
711 rcu_assign_pointer(mm->ioctx_table, table);
712 } else if (table->nr > old->nr) {
713 memcpy(table->table, old->table,
714 old->nr * sizeof(struct kioctx *));
716 rcu_assign_pointer(mm->ioctx_table, table);
725 static void aio_nr_sub(unsigned nr)
727 spin_lock(&aio_nr_lock);
728 if (WARN_ON(aio_nr - nr > aio_nr))
732 spin_unlock(&aio_nr_lock);
736 * Allocates and initializes an ioctx. Returns an ERR_PTR if it failed.
738 static struct kioctx *ioctx_alloc(unsigned nr_events)
740 struct mm_struct *mm = current->mm;
745 * We keep track of the number of available ringbuffer slots, to prevent
746 * overflow (reqs_available), and we also use percpu counters for this.
748 * So since up to half the slots might be on other cpu's percpu counters
749 * and unavailable, double nr_events so userspace sees what they
750 * expected: additionally, we move req_batch slots to/from percpu
751 * counters at a time, so make sure that isn't 0:
753 nr_events = max(nr_events, num_possible_cpus() * 4);
756 /* Prevent overflows */
757 if (nr_events > (0x10000000U / sizeof(struct io_event))) {
758 pr_debug("ENOMEM: nr_events too high\n");
759 return ERR_PTR(-EINVAL);
762 if (!nr_events || (unsigned long)nr_events > (aio_max_nr * 2UL))
763 return ERR_PTR(-EAGAIN);
765 ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL);
767 return ERR_PTR(-ENOMEM);
769 ctx->max_reqs = nr_events;
772 spin_lock_init(&ctx->ctx_lock);
773 spin_lock_init(&ctx->completion_lock);
774 mutex_init(&ctx->ring_lock);
775 /* Protect against page migration throughout kiotx setup by keeping
776 * the ring_lock mutex held until setup is complete. */
777 mutex_lock(&ctx->ring_lock);
778 init_waitqueue_head(&ctx->wait);
780 INIT_LIST_HEAD(&ctx->active_reqs);
782 if (percpu_ref_init(&ctx->users, free_ioctx_users, 0, GFP_KERNEL))
785 if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs, 0, GFP_KERNEL))
788 ctx->cpu = alloc_percpu(struct kioctx_cpu);
792 err = aio_setup_ring(ctx);
796 atomic_set(&ctx->reqs_available, ctx->nr_events - 1);
797 ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4);
798 if (ctx->req_batch < 1)
801 /* limit the number of system wide aios */
802 spin_lock(&aio_nr_lock);
803 if (aio_nr + nr_events > (aio_max_nr * 2UL) ||
804 aio_nr + nr_events < aio_nr) {
805 spin_unlock(&aio_nr_lock);
809 aio_nr += ctx->max_reqs;
810 spin_unlock(&aio_nr_lock);
812 percpu_ref_get(&ctx->users); /* io_setup() will drop this ref */
813 percpu_ref_get(&ctx->reqs); /* free_ioctx_users() will drop this */
815 err = ioctx_add_table(ctx, mm);
819 /* Release the ring_lock mutex now that all setup is complete. */
820 mutex_unlock(&ctx->ring_lock);
822 pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
823 ctx, ctx->user_id, mm, ctx->nr_events);
827 aio_nr_sub(ctx->max_reqs);
829 atomic_set(&ctx->dead, 1);
831 vm_munmap(ctx->mmap_base, ctx->mmap_size);
834 mutex_unlock(&ctx->ring_lock);
835 free_percpu(ctx->cpu);
836 percpu_ref_exit(&ctx->reqs);
837 percpu_ref_exit(&ctx->users);
838 kmem_cache_free(kioctx_cachep, ctx);
839 pr_debug("error allocating ioctx %d\n", err);
844 * Cancels all outstanding aio requests on an aio context. Used
845 * when the processes owning a context have all exited to encourage
846 * the rapid destruction of the kioctx.
848 static int kill_ioctx(struct mm_struct *mm, struct kioctx *ctx,
849 struct ctx_rq_wait *wait)
851 struct kioctx_table *table;
853 spin_lock(&mm->ioctx_lock);
854 if (atomic_xchg(&ctx->dead, 1)) {
855 spin_unlock(&mm->ioctx_lock);
859 table = rcu_dereference_raw(mm->ioctx_table);
860 WARN_ON(ctx != table->table[ctx->id]);
861 table->table[ctx->id] = NULL;
862 spin_unlock(&mm->ioctx_lock);
864 /* percpu_ref_kill() will do the necessary call_rcu() */
865 wake_up_all(&ctx->wait);
868 * It'd be more correct to do this in free_ioctx(), after all
869 * the outstanding kiocbs have finished - but by then io_destroy
870 * has already returned, so io_setup() could potentially return
871 * -EAGAIN with no ioctxs actually in use (as far as userspace
874 aio_nr_sub(ctx->max_reqs);
877 vm_munmap(ctx->mmap_base, ctx->mmap_size);
880 percpu_ref_kill(&ctx->users);
885 * exit_aio: called when the last user of mm goes away. At this point, there is
886 * no way for any new requests to be submited or any of the io_* syscalls to be
887 * called on the context.
889 * There may be outstanding kiocbs, but free_ioctx() will explicitly wait on
892 void exit_aio(struct mm_struct *mm)
894 struct kioctx_table *table = rcu_dereference_raw(mm->ioctx_table);
895 struct ctx_rq_wait wait;
901 atomic_set(&wait.count, table->nr);
902 init_completion(&wait.comp);
905 for (i = 0; i < table->nr; ++i) {
906 struct kioctx *ctx = table->table[i];
914 * We don't need to bother with munmap() here - exit_mmap(mm)
915 * is coming and it'll unmap everything. And we simply can't,
916 * this is not necessarily our ->mm.
917 * Since kill_ioctx() uses non-zero ->mmap_size as indicator
918 * that it needs to unmap the area, just set it to 0.
921 kill_ioctx(mm, ctx, &wait);
924 if (!atomic_sub_and_test(skipped, &wait.count)) {
925 /* Wait until all IO for the context are done. */
926 wait_for_completion(&wait.comp);
929 RCU_INIT_POINTER(mm->ioctx_table, NULL);
933 static void put_reqs_available(struct kioctx *ctx, unsigned nr)
935 struct kioctx_cpu *kcpu;
938 local_irq_save(flags);
939 kcpu = this_cpu_ptr(ctx->cpu);
940 kcpu->reqs_available += nr;
942 while (kcpu->reqs_available >= ctx->req_batch * 2) {
943 kcpu->reqs_available -= ctx->req_batch;
944 atomic_add(ctx->req_batch, &ctx->reqs_available);
947 local_irq_restore(flags);
950 static bool get_reqs_available(struct kioctx *ctx)
952 struct kioctx_cpu *kcpu;
956 local_irq_save(flags);
957 kcpu = this_cpu_ptr(ctx->cpu);
958 if (!kcpu->reqs_available) {
959 int old, avail = atomic_read(&ctx->reqs_available);
962 if (avail < ctx->req_batch)
966 avail = atomic_cmpxchg(&ctx->reqs_available,
967 avail, avail - ctx->req_batch);
968 } while (avail != old);
970 kcpu->reqs_available += ctx->req_batch;
974 kcpu->reqs_available--;
976 local_irq_restore(flags);
980 /* refill_reqs_available
981 * Updates the reqs_available reference counts used for tracking the
982 * number of free slots in the completion ring. This can be called
983 * from aio_complete() (to optimistically update reqs_available) or
984 * from aio_get_req() (the we're out of events case). It must be
985 * called holding ctx->completion_lock.
987 static void refill_reqs_available(struct kioctx *ctx, unsigned head,
990 unsigned events_in_ring, completed;
992 /* Clamp head since userland can write to it. */
993 head %= ctx->nr_events;
995 events_in_ring = tail - head;
997 events_in_ring = ctx->nr_events - (head - tail);
999 completed = ctx->completed_events;
1000 if (events_in_ring < completed)
1001 completed -= events_in_ring;
1008 ctx->completed_events -= completed;
1009 put_reqs_available(ctx, completed);
1012 /* user_refill_reqs_available
1013 * Called to refill reqs_available when aio_get_req() encounters an
1014 * out of space in the completion ring.
1016 static void user_refill_reqs_available(struct kioctx *ctx)
1018 spin_lock_irq(&ctx->completion_lock);
1019 if (ctx->completed_events) {
1020 struct aio_ring *ring;
1023 /* Access of ring->head may race with aio_read_events_ring()
1024 * here, but that's okay since whether we read the old version
1025 * or the new version, and either will be valid. The important
1026 * part is that head cannot pass tail since we prevent
1027 * aio_complete() from updating tail by holding
1028 * ctx->completion_lock. Even if head is invalid, the check
1029 * against ctx->completed_events below will make sure we do the
1032 ring = kmap_atomic(ctx->ring_pages[0]);
1034 kunmap_atomic(ring);
1036 refill_reqs_available(ctx, head, ctx->tail);
1039 spin_unlock_irq(&ctx->completion_lock);
1043 * Allocate a slot for an aio request.
1044 * Returns NULL if no requests are free.
1046 static inline struct aio_kiocb *aio_get_req(struct kioctx *ctx)
1048 struct aio_kiocb *req;
1050 if (!get_reqs_available(ctx)) {
1051 user_refill_reqs_available(ctx);
1052 if (!get_reqs_available(ctx))
1056 req = kmem_cache_alloc(kiocb_cachep, GFP_KERNEL|__GFP_ZERO);
1060 percpu_ref_get(&ctx->reqs);
1063 req->ki_iovec = req->ki_inline_vecs;
1066 put_reqs_available(ctx, 1);
1070 static void kiocb_free(struct aio_kiocb *req)
1072 if (req->common.ki_filp)
1073 fput(req->common.ki_filp);
1074 if (req->ki_eventfd != NULL)
1075 eventfd_ctx_put(req->ki_eventfd);
1076 if (req->ki_iovec != req->ki_inline_vecs)
1077 kfree(req->ki_iovec);
1078 if (req->ki_submit_task)
1079 put_task_struct(req->ki_submit_task);
1080 kmem_cache_free(kiocb_cachep, req);
1083 static struct kioctx *lookup_ioctx(unsigned long ctx_id)
1085 struct aio_ring __user *ring = (void __user *)ctx_id;
1086 struct mm_struct *mm = current->mm;
1087 struct kioctx *ctx, *ret = NULL;
1088 struct kioctx_table *table;
1091 if (get_user(id, &ring->id))
1095 table = rcu_dereference(mm->ioctx_table);
1097 if (!table || id >= table->nr)
1100 ctx = table->table[id];
1101 if (ctx && ctx->user_id == ctx_id) {
1102 percpu_ref_get(&ctx->users);
1111 * Called when the io request on the given iocb is complete.
1113 static void aio_complete(struct kiocb *kiocb, long res, long res2)
1115 struct aio_kiocb *iocb = container_of(kiocb, struct aio_kiocb, common);
1116 struct kioctx *ctx = iocb->ki_ctx;
1117 struct aio_ring *ring;
1118 struct io_event *ev_page, *event;
1119 unsigned tail, pos, head;
1120 unsigned long flags;
1123 * Special case handling for sync iocbs:
1124 * - events go directly into the iocb for fast handling
1125 * - the sync task with the iocb in its stack holds the single iocb
1126 * ref, no other paths have a way to get another ref
1127 * - the sync task helpfully left a reference to itself in the iocb
1129 BUG_ON(is_sync_kiocb(kiocb));
1131 if (iocb->ki_list.next) {
1132 unsigned long flags;
1134 spin_lock_irqsave(&ctx->ctx_lock, flags);
1135 list_del(&iocb->ki_list);
1136 spin_unlock_irqrestore(&ctx->ctx_lock, flags);
1140 * Add a completion event to the ring buffer. Must be done holding
1141 * ctx->completion_lock to prevent other code from messing with the tail
1142 * pointer since we might be called from irq context.
1144 spin_lock_irqsave(&ctx->completion_lock, flags);
1147 pos = tail + AIO_EVENTS_OFFSET;
1149 if (++tail >= ctx->nr_events)
1152 ev_page = kmap_atomic(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
1153 event = ev_page + pos % AIO_EVENTS_PER_PAGE;
1155 event->obj = (u64)(unsigned long)iocb->ki_user_iocb;
1156 event->data = iocb->ki_user_data;
1160 kunmap_atomic(ev_page);
1161 flush_dcache_page(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
1163 pr_debug("%p[%u]: %p: %p %Lx %lx %lx\n",
1164 ctx, tail, iocb, iocb->ki_user_iocb, iocb->ki_user_data,
1167 /* after flagging the request as done, we
1168 * must never even look at it again
1170 smp_wmb(); /* make event visible before updating tail */
1174 ring = kmap_atomic(ctx->ring_pages[0]);
1177 kunmap_atomic(ring);
1178 flush_dcache_page(ctx->ring_pages[0]);
1180 ctx->completed_events++;
1181 if (ctx->completed_events > 1)
1182 refill_reqs_available(ctx, head, tail);
1183 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1185 pr_debug("added to ring %p at [%u]\n", iocb, tail);
1188 * Check if the user asked us to deliver the result through an
1189 * eventfd. The eventfd_signal() function is safe to be called
1192 if (iocb->ki_eventfd != NULL)
1193 eventfd_signal(iocb->ki_eventfd, 1);
1195 /* everything turned out well, dispose of the aiocb. */
1199 * We have to order our ring_info tail store above and test
1200 * of the wait list below outside the wait lock. This is
1201 * like in wake_up_bit() where clearing a bit has to be
1202 * ordered with the unlocked test.
1206 if (waitqueue_active(&ctx->wait))
1207 wake_up(&ctx->wait);
1209 percpu_ref_put(&ctx->reqs);
1212 /* aio_read_events_ring
1213 * Pull an event off of the ioctx's event ring. Returns the number of
1216 static long aio_read_events_ring(struct kioctx *ctx,
1217 struct io_event __user *event, long nr)
1219 struct aio_ring *ring;
1220 unsigned head, tail, pos;
1225 * The mutex can block and wake us up and that will cause
1226 * wait_event_interruptible_hrtimeout() to schedule without sleeping
1227 * and repeat. This should be rare enough that it doesn't cause
1228 * peformance issues. See the comment in read_events() for more detail.
1230 sched_annotate_sleep();
1231 mutex_lock(&ctx->ring_lock);
1233 /* Access to ->ring_pages here is protected by ctx->ring_lock. */
1234 ring = kmap_atomic(ctx->ring_pages[0]);
1237 kunmap_atomic(ring);
1240 * Ensure that once we've read the current tail pointer, that
1241 * we also see the events that were stored up to the tail.
1245 pr_debug("h%u t%u m%u\n", head, tail, ctx->nr_events);
1250 head %= ctx->nr_events;
1251 tail %= ctx->nr_events;
1255 struct io_event *ev;
1258 avail = (head <= tail ? tail : ctx->nr_events) - head;
1262 avail = min(avail, nr - ret);
1263 avail = min_t(long, avail, AIO_EVENTS_PER_PAGE -
1264 ((head + AIO_EVENTS_OFFSET) % AIO_EVENTS_PER_PAGE));
1266 pos = head + AIO_EVENTS_OFFSET;
1267 page = ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE];
1268 pos %= AIO_EVENTS_PER_PAGE;
1271 copy_ret = copy_to_user(event + ret, ev + pos,
1272 sizeof(*ev) * avail);
1275 if (unlikely(copy_ret)) {
1282 head %= ctx->nr_events;
1285 ring = kmap_atomic(ctx->ring_pages[0]);
1287 kunmap_atomic(ring);
1288 flush_dcache_page(ctx->ring_pages[0]);
1290 pr_debug("%li h%u t%u\n", ret, head, tail);
1292 mutex_unlock(&ctx->ring_lock);
1297 static bool aio_read_events(struct kioctx *ctx, long min_nr, long nr,
1298 struct io_event __user *event, long *i)
1300 long ret = aio_read_events_ring(ctx, event + *i, nr - *i);
1305 if (unlikely(atomic_read(&ctx->dead)))
1311 return ret < 0 || *i >= min_nr;
1314 static long read_events(struct kioctx *ctx, long min_nr, long nr,
1315 struct io_event __user *event,
1316 struct timespec __user *timeout)
1318 ktime_t until = { .tv64 = KTIME_MAX };
1324 if (unlikely(copy_from_user(&ts, timeout, sizeof(ts))))
1326 if (!timespec_valid(&ts))
1329 until = timespec_to_ktime(ts);
1333 * Note that aio_read_events() is being called as the conditional - i.e.
1334 * we're calling it after prepare_to_wait() has set task state to
1335 * TASK_INTERRUPTIBLE.
1337 * But aio_read_events() can block, and if it blocks it's going to flip
1338 * the task state back to TASK_RUNNING.
1340 * This should be ok, provided it doesn't flip the state back to
1341 * TASK_RUNNING and return 0 too much - that causes us to spin. That
1342 * will only happen if the mutex_lock() call blocks, and we then find
1343 * the ringbuffer empty. So in practice we should be ok, but it's
1344 * something to be aware of when touching this code.
1346 if (until.tv64 == 0)
1347 aio_read_events(ctx, min_nr, nr, event, &ret);
1349 wait_event_interruptible_hrtimeout(ctx->wait,
1350 aio_read_events(ctx, min_nr, nr, event, &ret),
1353 if (!ret && signal_pending(current))
1360 * Create an aio_context capable of receiving at least nr_events.
1361 * ctxp must not point to an aio_context that already exists, and
1362 * must be initialized to 0 prior to the call. On successful
1363 * creation of the aio_context, *ctxp is filled in with the resulting
1364 * handle. May fail with -EINVAL if *ctxp is not initialized,
1365 * if the specified nr_events exceeds internal limits. May fail
1366 * with -EAGAIN if the specified nr_events exceeds the user's limit
1367 * of available events. May fail with -ENOMEM if insufficient kernel
1368 * resources are available. May fail with -EFAULT if an invalid
1369 * pointer is passed for ctxp. Will fail with -ENOSYS if not
1372 SYSCALL_DEFINE2(io_setup, unsigned, nr_events, aio_context_t __user *, ctxp)
1374 struct kioctx *ioctx = NULL;
1378 ret = get_user(ctx, ctxp);
1383 if (unlikely(ctx || nr_events == 0)) {
1384 pr_debug("EINVAL: ctx %lu nr_events %u\n",
1389 ioctx = ioctx_alloc(nr_events);
1390 ret = PTR_ERR(ioctx);
1391 if (!IS_ERR(ioctx)) {
1392 ret = put_user(ioctx->user_id, ctxp);
1394 kill_ioctx(current->mm, ioctx, NULL);
1395 percpu_ref_put(&ioctx->users);
1403 * Destroy the aio_context specified. May cancel any outstanding
1404 * AIOs and block on completion. Will fail with -ENOSYS if not
1405 * implemented. May fail with -EINVAL if the context pointed to
1408 SYSCALL_DEFINE1(io_destroy, aio_context_t, ctx)
1410 struct kioctx *ioctx = lookup_ioctx(ctx);
1411 if (likely(NULL != ioctx)) {
1412 struct ctx_rq_wait wait;
1415 init_completion(&wait.comp);
1416 atomic_set(&wait.count, 1);
1418 /* Pass requests_done to kill_ioctx() where it can be set
1419 * in a thread-safe way. If we try to set it here then we have
1420 * a race condition if two io_destroy() called simultaneously.
1422 ret = kill_ioctx(current->mm, ioctx, &wait);
1423 percpu_ref_put(&ioctx->users);
1425 /* Wait until all IO for the context are done. Otherwise kernel
1426 * keep using user-space buffers even if user thinks the context
1430 wait_for_completion(&wait.comp);
1434 pr_debug("EINVAL: invalid context id\n");
1438 typedef ssize_t (rw_iter_op)(struct kiocb *, struct iov_iter *);
1440 static int aio_setup_vectored_rw(int rw, char __user *buf, size_t len,
1441 struct iovec **iovec,
1443 struct iov_iter *iter)
1445 #ifdef CONFIG_COMPAT
1447 return compat_import_iovec(rw,
1448 (struct compat_iovec __user *)buf,
1449 len, UIO_FASTIOV, iovec, iter);
1451 return import_iovec(rw, (struct iovec __user *)buf,
1452 len, UIO_FASTIOV, iovec, iter);
1455 #if IS_ENABLED(CONFIG_AIO_THREAD)
1456 /* aio_thread_queue_iocb_cancel_early:
1457 * Early stage cancellation helper function for threaded aios. This
1458 * is used prior to the iocb being assigned to a worker thread.
1460 static int aio_thread_queue_iocb_cancel_early(struct kiocb *iocb)
1465 /* aio_thread_queue_iocb_cancel:
1466 * Late stage cancellation method for threaded aios. Once an iocb is
1467 * assigned to a worker thread, we use a fatal signal to interrupt an
1468 * in-progress operation.
1470 static int aio_thread_queue_iocb_cancel(struct kiocb *kiocb)
1472 struct aio_kiocb *iocb = container_of(kiocb, struct aio_kiocb, common);
1473 if (iocb->ki_cancel_task) {
1474 force_sig(SIGKILL, iocb->ki_cancel_task);
1481 * Entry point for worker to perform threaded aio. Handles issues
1482 * arising due to cancellation using signals.
1484 static void aio_thread_fn(struct work_struct *work)
1486 struct aio_kiocb *iocb = container_of(work, struct aio_kiocb, ki_work);
1487 kiocb_cancel_fn *old_cancel;
1490 iocb->ki_cancel_task = current;
1491 current->kiocb = &iocb->common; /* For io_send_sig(). */
1492 BUG_ON(atomic_read(¤t->signal->sigcnt) != 1);
1494 /* Check for early stage cancellation and switch to late stage
1495 * cancellation if it has not already occurred.
1497 old_cancel = cmpxchg(&iocb->ki_cancel,
1498 aio_thread_queue_iocb_cancel_early,
1499 aio_thread_queue_iocb_cancel);
1500 if (old_cancel != KIOCB_CANCELLED)
1501 ret = iocb->ki_work_fn(iocb);
1505 current->kiocb = NULL;
1506 if (unlikely(ret == -ERESTARTSYS || ret == -ERESTARTNOINTR ||
1507 ret == -ERESTARTNOHAND || ret == -ERESTART_RESTARTBLOCK))
1510 /* Completion serializes cancellation by taking ctx_lock, so
1511 * aio_complete() will not return until after force_sig() in
1512 * aio_thread_queue_iocb_cancel(). This should ensure that
1513 * the signal is pending before being flushed in this thread.
1515 aio_complete(&iocb->common, ret, 0);
1516 if (fatal_signal_pending(current))
1517 flush_signals(current);
1520 #define AIO_THREAD_NEED_TASK 0x0001 /* Need aio_kiocb->ki_submit_task */
1522 /* aio_thread_queue_iocb
1523 * Queues an aio_kiocb for dispatch to a worker thread. Prepares the
1524 * aio_kiocb for cancellation. The caller must provide a function to
1525 * execute the operation in work_fn. The flags may be provided as an
1526 * ored set AIO_THREAD_xxx.
1528 static ssize_t aio_thread_queue_iocb(struct aio_kiocb *iocb,
1529 aio_thread_work_fn_t work_fn,
1532 INIT_WORK(&iocb->ki_work, aio_thread_fn);
1533 iocb->ki_work_fn = work_fn;
1534 if (flags & AIO_THREAD_NEED_TASK) {
1535 iocb->ki_submit_task = current;
1536 get_task_struct(iocb->ki_submit_task);
1539 /* Cancellation needs to be always available for operations performed
1540 * using helper threads. Prior to the iocb being assigned to a worker
1541 * thread, we need to record that a cancellation has occurred. We
1542 * can do this by having a minimal helper function that is recorded in
1545 kiocb_set_cancel_fn(&iocb->common, aio_thread_queue_iocb_cancel_early);
1546 queue_work(system_long_wq, &iocb->ki_work);
1547 return -EIOCBQUEUED;
1550 static long aio_thread_op_read_iter(struct aio_kiocb *iocb)
1555 use_mm(iocb->ki_ctx->mm);
1556 filp = iocb->common.ki_filp;
1558 if (filp->f_op->read_iter) {
1559 struct kiocb sync_kiocb;
1560 init_sync_kiocb(&sync_kiocb, filp);
1561 sync_kiocb.ki_pos = iocb->common.ki_pos;
1562 ret = filp->f_op->read_iter(&sync_kiocb, &iocb->ki_iter);
1563 } else if (filp->f_op->read)
1564 ret = do_loop_readv_writev(filp, &iocb->ki_iter,
1565 &iocb->common.ki_pos,
1569 unuse_mm(iocb->ki_ctx->mm);
1573 ssize_t generic_async_read_iter_non_direct(struct kiocb *iocb,
1574 struct iov_iter *iter)
1576 if ((iocb->ki_flags & IOCB_DIRECT) ||
1577 (iocb->ki_complete != aio_complete))
1578 return iocb->ki_filp->f_op->read_iter(iocb, iter);
1579 return generic_async_read_iter(iocb, iter);
1581 EXPORT_SYMBOL(generic_async_read_iter_non_direct);
1583 ssize_t generic_async_read_iter(struct kiocb *iocb, struct iov_iter *iter)
1585 struct aio_kiocb *req;
1587 req = container_of(iocb, struct aio_kiocb, common);
1588 BUG_ON(iter != &req->ki_iter);
1590 return aio_thread_queue_iocb(req, aio_thread_op_read_iter,
1591 AIO_THREAD_NEED_TASK);
1593 EXPORT_SYMBOL(generic_async_read_iter);
1595 static long aio_thread_op_write_iter(struct aio_kiocb *iocb)
1597 u64 saved_rlim_fsize;
1601 use_mm(iocb->ki_ctx->mm);
1602 filp = iocb->common.ki_filp;
1603 saved_rlim_fsize = rlimit(RLIMIT_FSIZE);
1604 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = iocb->ki_rlimit_fsize;
1606 if (filp->f_op->write_iter) {
1607 struct kiocb sync_kiocb;
1608 init_sync_kiocb(&sync_kiocb, filp);
1609 sync_kiocb.ki_pos = iocb->common.ki_pos;
1610 ret = filp->f_op->write_iter(&sync_kiocb, &iocb->ki_iter);
1611 } else if (filp->f_op->write)
1612 ret = do_loop_readv_writev(filp, &iocb->ki_iter,
1613 &iocb->common.ki_pos,
1614 (io_fn_t)filp->f_op->write);
1617 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = saved_rlim_fsize;
1618 unuse_mm(iocb->ki_ctx->mm);
1622 ssize_t generic_async_write_iter_non_direct(struct kiocb *iocb,
1623 struct iov_iter *iter)
1625 if ((iocb->ki_flags & IOCB_DIRECT) ||
1626 (iocb->ki_complete != aio_complete))
1627 return iocb->ki_filp->f_op->write_iter(iocb, iter);
1628 return generic_async_write_iter(iocb, iter);
1630 EXPORT_SYMBOL(generic_async_write_iter_non_direct);
1632 ssize_t generic_async_write_iter(struct kiocb *iocb, struct iov_iter *iter)
1634 struct aio_kiocb *req;
1636 req = container_of(iocb, struct aio_kiocb, common);
1637 BUG_ON(iter != &req->ki_iter);
1638 req->ki_rlimit_fsize = rlimit(RLIMIT_FSIZE);
1640 return aio_thread_queue_iocb(req, aio_thread_op_write_iter,
1641 AIO_THREAD_NEED_TASK);
1643 EXPORT_SYMBOL(generic_async_write_iter);
1645 static long aio_thread_op_fsync(struct aio_kiocb *iocb)
1647 return vfs_fsync(iocb->common.ki_filp, 0);
1650 static long aio_thread_op_fdatasync(struct aio_kiocb *iocb)
1652 return vfs_fsync(iocb->common.ki_filp, 1);
1655 ssize_t generic_async_fsync(struct kiocb *iocb, int datasync)
1657 struct aio_kiocb *req;
1659 BUG_ON(iocb->ki_complete != aio_complete);
1660 req = container_of(iocb, struct aio_kiocb, common);
1662 return aio_thread_queue_iocb(req, datasync ? aio_thread_op_fdatasync
1663 : aio_thread_op_fsync, 0);
1665 EXPORT_SYMBOL(generic_async_fsync);
1667 static long aio_thread_op_poll(struct aio_kiocb *iocb)
1669 struct file *file = iocb->common.ki_filp;
1670 short events = iocb->ki_data;
1671 struct poll_wqueues table;
1675 poll_initwait(&table);
1676 events |= POLLERR | POLLHUP;
1679 mask = DEFAULT_POLLMASK;
1680 if (file->f_op && file->f_op->poll) {
1681 table.pt._key = events;
1682 mask = file->f_op->poll(file, &table.pt);
1684 /* Mask out unneeded events. */
1691 if (signal_pending(current))
1694 poll_schedule_timeout(&table, TASK_INTERRUPTIBLE, NULL, 0);
1697 poll_freewait(&table);
1700 #endif /* IS_ENABLED(CONFIG_AIO_THREAD) */
1704 * Performs the initial checks and io submission.
1706 static ssize_t aio_run_iocb(struct aio_kiocb *req, unsigned opcode,
1707 char __user *buf, size_t len, bool compat)
1709 struct file *file = req->common.ki_filp;
1710 ssize_t ret = -EINVAL;
1713 rw_iter_op *iter_op;
1716 case IOCB_CMD_PREAD:
1717 case IOCB_CMD_PREADV:
1720 iter_op = file->f_op->async_read_iter;
1723 #if IS_ENABLED(CONFIG_AIO_THREAD)
1724 if ((aio_auto_threads & 1) &&
1725 (file->f_op->read_iter || file->f_op->read)) {
1726 iter_op = generic_async_read_iter;
1730 iter_op = file->f_op->read_iter;
1733 case IOCB_CMD_PWRITE:
1734 case IOCB_CMD_PWRITEV:
1737 iter_op = file->f_op->async_write_iter;
1740 #if IS_ENABLED(CONFIG_AIO_THREAD)
1741 if ((aio_auto_threads & 1) &&
1742 (file->f_op->write_iter || file->f_op->write)) {
1743 iter_op = generic_async_write_iter;
1747 iter_op = file->f_op->write_iter;
1750 if (unlikely(!(file->f_mode & mode)))
1756 if (opcode == IOCB_CMD_PREADV || opcode == IOCB_CMD_PWRITEV)
1757 ret = aio_setup_vectored_rw(rw, buf, len,
1758 &req->ki_iovec, compat,
1761 ret = import_single_range(rw, buf, len, req->ki_iovec,
1765 ret = rw_verify_area(rw, file, &req->common.ki_pos,
1766 iov_iter_count(&req->ki_iter));
1771 file_start_write(file);
1773 ret = iter_op(&req->common, &req->ki_iter);
1776 file_end_write(file);
1779 case IOCB_CMD_FDSYNC:
1780 if (file->f_op->aio_fsync)
1781 ret = file->f_op->aio_fsync(&req->common, 1);
1782 #if IS_ENABLED(CONFIG_AIO_THREAD)
1783 else if (file->f_op->fsync && (aio_auto_threads & 1))
1784 ret = generic_async_fsync(&req->common, 1);
1788 case IOCB_CMD_FSYNC:
1789 if (file->f_op->aio_fsync)
1790 ret = file->f_op->aio_fsync(&req->common, 0);
1791 #if IS_ENABLED(CONFIG_AIO_THREAD)
1792 else if (file->f_op->fsync && (aio_auto_threads & 1))
1793 ret = generic_async_fsync(&req->common, 0);
1798 #if IS_ENABLED(CONFIG_AIO_THREAD)
1799 if (aio_auto_threads & 1)
1800 ret = aio_thread_queue_iocb(req, aio_thread_op_poll, 0);
1805 pr_debug("EINVAL: no operation provided\n");
1809 if (ret != -EIOCBQUEUED) {
1811 * There's no easy way to restart the syscall since other AIO's
1812 * may be already running. Just fail this IO with EINTR.
1814 if (unlikely(ret == -ERESTARTSYS || ret == -ERESTARTNOINTR ||
1815 ret == -ERESTARTNOHAND ||
1816 ret == -ERESTART_RESTARTBLOCK))
1818 aio_complete(&req->common, ret, 0);
1824 static int io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb,
1825 struct iocb *iocb, bool compat)
1827 struct aio_kiocb *req;
1830 /* enforce forwards compatibility on users */
1831 if (unlikely(iocb->aio_reserved1 || iocb->aio_reserved2)) {
1832 pr_debug("EINVAL: reserve field set\n");
1836 /* prevent overflows */
1838 (iocb->aio_buf != (unsigned long)iocb->aio_buf) ||
1839 (iocb->aio_nbytes != (size_t)iocb->aio_nbytes) ||
1840 ((ssize_t)iocb->aio_nbytes < 0)
1842 pr_debug("EINVAL: overflow check\n");
1846 req = aio_get_req(ctx);
1850 req->common.ki_filp = fget(iocb->aio_fildes);
1851 if (unlikely(!req->common.ki_filp)) {
1855 req->common.ki_pos = iocb->aio_offset;
1856 req->common.ki_complete = aio_complete;
1857 req->common.ki_flags = iocb_flags(req->common.ki_filp);
1859 if (iocb->aio_flags & IOCB_FLAG_RESFD) {
1861 * If the IOCB_FLAG_RESFD flag of aio_flags is set, get an
1862 * instance of the file* now. The file descriptor must be
1863 * an eventfd() fd, and will be signaled for each completed
1864 * event using the eventfd_signal() function.
1866 req->ki_eventfd = eventfd_ctx_fdget((int) iocb->aio_resfd);
1867 if (IS_ERR(req->ki_eventfd)) {
1868 ret = PTR_ERR(req->ki_eventfd);
1869 req->ki_eventfd = NULL;
1873 req->common.ki_flags |= IOCB_EVENTFD;
1876 ret = put_user(KIOCB_KEY, &user_iocb->aio_key);
1877 if (unlikely(ret)) {
1878 pr_debug("EFAULT: aio_key\n");
1882 req->ki_user_iocb = user_iocb;
1883 req->ki_user_data = iocb->aio_data;
1885 ret = aio_run_iocb(req, iocb->aio_lio_opcode,
1886 (char __user *)(unsigned long)iocb->aio_buf,
1894 put_reqs_available(ctx, 1);
1895 percpu_ref_put(&ctx->reqs);
1900 long do_io_submit(aio_context_t ctx_id, long nr,
1901 struct iocb __user *__user *iocbpp, bool compat)
1906 struct blk_plug plug;
1908 if (unlikely(nr < 0))
1911 if (unlikely(nr > LONG_MAX/sizeof(*iocbpp)))
1912 nr = LONG_MAX/sizeof(*iocbpp);
1914 if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))
1917 ctx = lookup_ioctx(ctx_id);
1918 if (unlikely(!ctx)) {
1919 pr_debug("EINVAL: invalid context id\n");
1923 blk_start_plug(&plug);
1926 * AKPM: should this return a partial result if some of the IOs were
1927 * successfully submitted?
1929 for (i=0; i<nr; i++) {
1930 struct iocb __user *user_iocb;
1933 if (unlikely(__get_user(user_iocb, iocbpp + i))) {
1938 if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
1943 ret = io_submit_one(ctx, user_iocb, &tmp, compat);
1947 blk_finish_plug(&plug);
1949 percpu_ref_put(&ctx->users);
1954 * Queue the nr iocbs pointed to by iocbpp for processing. Returns
1955 * the number of iocbs queued. May return -EINVAL if the aio_context
1956 * specified by ctx_id is invalid, if nr is < 0, if the iocb at
1957 * *iocbpp[0] is not properly initialized, if the operation specified
1958 * is invalid for the file descriptor in the iocb. May fail with
1959 * -EFAULT if any of the data structures point to invalid data. May
1960 * fail with -EBADF if the file descriptor specified in the first
1961 * iocb is invalid. May fail with -EAGAIN if insufficient resources
1962 * are available to queue any iocbs. Will return 0 if nr is 0. Will
1963 * fail with -ENOSYS if not implemented.
1965 SYSCALL_DEFINE3(io_submit, aio_context_t, ctx_id, long, nr,
1966 struct iocb __user * __user *, iocbpp)
1968 return do_io_submit(ctx_id, nr, iocbpp, 0);
1972 * Finds a given iocb for cancellation.
1974 static struct aio_kiocb *
1975 lookup_kiocb(struct kioctx *ctx, struct iocb __user *iocb, u32 key)
1977 struct aio_kiocb *kiocb;
1979 assert_spin_locked(&ctx->ctx_lock);
1981 if (key != KIOCB_KEY)
1984 /* TODO: use a hash or array, this sucks. */
1985 list_for_each_entry(kiocb, &ctx->active_reqs, ki_list) {
1986 if (kiocb->ki_user_iocb == iocb)
1993 * Attempts to cancel an iocb previously passed to io_submit. If
1994 * the operation is successfully cancelled, the resulting event is
1995 * copied into the memory pointed to by result without being placed
1996 * into the completion queue and 0 is returned. May fail with
1997 * -EFAULT if any of the data structures pointed to are invalid.
1998 * May fail with -EINVAL if aio_context specified by ctx_id is
1999 * invalid. May fail with -EAGAIN if the iocb specified was not
2000 * cancelled. Will fail with -ENOSYS if not implemented.
2002 SYSCALL_DEFINE3(io_cancel, aio_context_t, ctx_id, struct iocb __user *, iocb,
2003 struct io_event __user *, result)
2006 struct aio_kiocb *kiocb;
2010 ret = get_user(key, &iocb->aio_key);
2014 ctx = lookup_ioctx(ctx_id);
2018 spin_lock_irq(&ctx->ctx_lock);
2020 kiocb = lookup_kiocb(ctx, iocb, key);
2022 ret = kiocb_cancel(kiocb);
2026 spin_unlock_irq(&ctx->ctx_lock);
2030 * The result argument is no longer used - the io_event is
2031 * always delivered via the ring buffer. -EINPROGRESS indicates
2032 * cancellation is progress:
2037 percpu_ref_put(&ctx->users);
2043 * Attempts to read at least min_nr events and up to nr events from
2044 * the completion queue for the aio_context specified by ctx_id. If
2045 * it succeeds, the number of read events is returned. May fail with
2046 * -EINVAL if ctx_id is invalid, if min_nr is out of range, if nr is
2047 * out of range, if timeout is out of range. May fail with -EFAULT
2048 * if any of the memory specified is invalid. May return 0 or
2049 * < min_nr if the timeout specified by timeout has elapsed
2050 * before sufficient events are available, where timeout == NULL
2051 * specifies an infinite timeout. Note that the timeout pointed to by
2052 * timeout is relative. Will fail with -ENOSYS if not implemented.
2054 SYSCALL_DEFINE5(io_getevents, aio_context_t, ctx_id,
2057 struct io_event __user *, events,
2058 struct timespec __user *, timeout)
2060 struct kioctx *ioctx = lookup_ioctx(ctx_id);
2063 if (likely(ioctx)) {
2064 if (likely(min_nr <= nr && min_nr >= 0))
2065 ret = read_events(ioctx, min_nr, nr, events, timeout);
2066 percpu_ref_put(&ioctx->users);