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_INCOMPAT_FEATURES 0
53 unsigned id; /* kernel internal index number */
54 unsigned nr; /* number of io_events */
55 unsigned head; /* Written to by userland or under ring_lock
56 * mutex by aio_read_events_ring(). */
60 unsigned compat_features;
61 unsigned incompat_features;
62 unsigned header_length; /* size of aio_ring */
65 struct io_event io_events[0];
66 }; /* 128 bytes + ring size */
68 #define AIO_RING_PAGES 8
73 struct kioctx *table[];
77 unsigned reqs_available;
81 struct completion comp;
86 struct percpu_ref users;
89 struct percpu_ref reqs;
91 unsigned long user_id;
93 struct __percpu kioctx_cpu *cpu;
96 * For percpu reqs_available, number of slots we move to/from global
101 * This is what userspace passed to io_setup(), it's not used for
102 * anything but counting against the global max_reqs quota.
104 * The real limit is nr_events - 1, which will be larger (see
109 /* Size of ringbuffer, in units of struct io_event */
112 unsigned long mmap_base;
113 unsigned long mmap_size;
115 struct page **ring_pages;
118 struct work_struct free_work;
121 * signals when all in-flight requests are done
123 struct ctx_rq_wait *rq_wait;
127 * This counts the number of available slots in the ringbuffer,
128 * so we avoid overflowing it: it's decremented (if positive)
129 * when allocating a kiocb and incremented when the resulting
130 * io_event is pulled off the ringbuffer.
132 * We batch accesses to it with a percpu version.
134 atomic_t reqs_available;
135 } ____cacheline_aligned_in_smp;
139 struct list_head active_reqs; /* used for cancellation */
140 } ____cacheline_aligned_in_smp;
143 struct mutex ring_lock;
144 wait_queue_head_t wait;
145 } ____cacheline_aligned_in_smp;
149 unsigned completed_events;
150 spinlock_t completion_lock;
151 } ____cacheline_aligned_in_smp;
153 struct page *internal_pages[AIO_RING_PAGES];
154 struct file *aio_ring_file;
159 /*------ sysctl variables----*/
160 static DEFINE_SPINLOCK(aio_nr_lock);
161 unsigned long aio_nr; /* current system wide number of aio requests */
162 unsigned long aio_max_nr = 0x10000; /* system wide maximum number of aio requests */
163 /*----end sysctl variables---*/
165 static struct kmem_cache *kiocb_cachep;
166 static struct kmem_cache *kioctx_cachep;
168 static struct vfsmount *aio_mnt;
170 static const struct file_operations aio_ring_fops;
171 static const struct address_space_operations aio_ctx_aops;
173 static struct file *aio_private_file(struct kioctx *ctx, loff_t nr_pages)
175 struct qstr this = QSTR_INIT("[aio]", 5);
178 struct inode *inode = alloc_anon_inode(aio_mnt->mnt_sb);
180 return ERR_CAST(inode);
182 inode->i_mapping->a_ops = &aio_ctx_aops;
183 inode->i_mapping->private_data = ctx;
184 inode->i_size = PAGE_SIZE * nr_pages;
186 path.dentry = d_alloc_pseudo(aio_mnt->mnt_sb, &this);
189 return ERR_PTR(-ENOMEM);
191 path.mnt = mntget(aio_mnt);
193 d_instantiate(path.dentry, inode);
194 file = alloc_file(&path, FMODE_READ | FMODE_WRITE, &aio_ring_fops);
200 file->f_flags = O_RDWR;
204 static struct dentry *aio_mount(struct file_system_type *fs_type,
205 int flags, const char *dev_name, void *data)
207 static const struct dentry_operations ops = {
208 .d_dname = simple_dname,
210 return mount_pseudo(fs_type, "aio:", NULL, &ops, AIO_RING_MAGIC);
214 * Creates the slab caches used by the aio routines, panic on
215 * failure as this is done early during the boot sequence.
217 static int __init aio_setup(void)
219 static struct file_system_type aio_fs = {
222 .kill_sb = kill_anon_super,
224 aio_mnt = kern_mount(&aio_fs);
226 panic("Failed to create aio fs mount.");
228 kiocb_cachep = KMEM_CACHE(kiocb, SLAB_HWCACHE_ALIGN|SLAB_PANIC);
229 kioctx_cachep = KMEM_CACHE(kioctx,SLAB_HWCACHE_ALIGN|SLAB_PANIC);
231 pr_debug("sizeof(struct page) = %zu\n", sizeof(struct page));
235 __initcall(aio_setup);
237 static void put_aio_ring_file(struct kioctx *ctx)
239 struct file *aio_ring_file = ctx->aio_ring_file;
241 truncate_setsize(aio_ring_file->f_inode, 0);
243 /* Prevent further access to the kioctx from migratepages */
244 spin_lock(&aio_ring_file->f_inode->i_mapping->private_lock);
245 aio_ring_file->f_inode->i_mapping->private_data = NULL;
246 ctx->aio_ring_file = NULL;
247 spin_unlock(&aio_ring_file->f_inode->i_mapping->private_lock);
253 static void aio_free_ring(struct kioctx *ctx)
257 /* Disconnect the kiotx from the ring file. This prevents future
258 * accesses to the kioctx from page migration.
260 put_aio_ring_file(ctx);
262 for (i = 0; i < ctx->nr_pages; i++) {
264 pr_debug("pid(%d) [%d] page->count=%d\n", current->pid, i,
265 page_count(ctx->ring_pages[i]));
266 page = ctx->ring_pages[i];
269 ctx->ring_pages[i] = NULL;
273 if (ctx->ring_pages && ctx->ring_pages != ctx->internal_pages) {
274 kfree(ctx->ring_pages);
275 ctx->ring_pages = NULL;
279 static int aio_ring_mmap(struct file *file, struct vm_area_struct *vma)
281 vma->vm_flags |= VM_DONTEXPAND;
282 vma->vm_ops = &generic_file_vm_ops;
286 static int aio_ring_remap(struct file *file, struct vm_area_struct *vma)
288 struct mm_struct *mm = vma->vm_mm;
289 struct kioctx_table *table;
290 int i, res = -EINVAL;
292 spin_lock(&mm->ioctx_lock);
294 table = rcu_dereference(mm->ioctx_table);
295 for (i = 0; i < table->nr; i++) {
298 ctx = table->table[i];
299 if (ctx && ctx->aio_ring_file == file) {
300 if (!atomic_read(&ctx->dead)) {
301 ctx->user_id = ctx->mmap_base = vma->vm_start;
309 spin_unlock(&mm->ioctx_lock);
313 static const struct file_operations aio_ring_fops = {
314 .mmap = aio_ring_mmap,
315 .mremap = aio_ring_remap,
318 #if IS_ENABLED(CONFIG_MIGRATION)
319 static int aio_migratepage(struct address_space *mapping, struct page *new,
320 struct page *old, enum migrate_mode mode)
329 /* mapping->private_lock here protects against the kioctx teardown. */
330 spin_lock(&mapping->private_lock);
331 ctx = mapping->private_data;
337 /* The ring_lock mutex. The prevents aio_read_events() from writing
338 * to the ring's head, and prevents page migration from mucking in
339 * a partially initialized kiotx.
341 if (!mutex_trylock(&ctx->ring_lock)) {
347 if (idx < (pgoff_t)ctx->nr_pages) {
348 /* Make sure the old page hasn't already been changed */
349 if (ctx->ring_pages[idx] != old)
357 /* Writeback must be complete */
358 BUG_ON(PageWriteback(old));
361 rc = migrate_page_move_mapping(mapping, new, old, NULL, mode, 1);
362 if (rc != MIGRATEPAGE_SUCCESS) {
367 /* Take completion_lock to prevent other writes to the ring buffer
368 * while the old page is copied to the new. This prevents new
369 * events from being lost.
371 spin_lock_irqsave(&ctx->completion_lock, flags);
372 migrate_page_copy(new, old);
373 BUG_ON(ctx->ring_pages[idx] != old);
374 ctx->ring_pages[idx] = new;
375 spin_unlock_irqrestore(&ctx->completion_lock, flags);
377 /* The old page is no longer accessible. */
381 mutex_unlock(&ctx->ring_lock);
383 spin_unlock(&mapping->private_lock);
388 static const struct address_space_operations aio_ctx_aops = {
389 .set_page_dirty = __set_page_dirty_no_writeback,
390 #if IS_ENABLED(CONFIG_MIGRATION)
391 .migratepage = aio_migratepage,
395 static int aio_setup_ring(struct kioctx *ctx)
397 struct aio_ring *ring;
398 unsigned nr_events = ctx->max_reqs;
399 struct mm_struct *mm = current->mm;
400 unsigned long size, unused;
405 /* Compensate for the ring buffer's head/tail overlap entry */
406 nr_events += 2; /* 1 is required, 2 for good luck */
408 size = sizeof(struct aio_ring);
409 size += sizeof(struct io_event) * nr_events;
411 nr_pages = PFN_UP(size);
415 file = aio_private_file(ctx, nr_pages);
417 ctx->aio_ring_file = NULL;
421 ctx->aio_ring_file = file;
422 nr_events = (PAGE_SIZE * nr_pages - sizeof(struct aio_ring))
423 / sizeof(struct io_event);
425 ctx->ring_pages = ctx->internal_pages;
426 if (nr_pages > AIO_RING_PAGES) {
427 ctx->ring_pages = kcalloc(nr_pages, sizeof(struct page *),
429 if (!ctx->ring_pages) {
430 put_aio_ring_file(ctx);
435 for (i = 0; i < nr_pages; i++) {
437 page = find_or_create_page(file->f_inode->i_mapping,
438 i, GFP_HIGHUSER | __GFP_ZERO);
441 pr_debug("pid(%d) page[%d]->count=%d\n",
442 current->pid, i, page_count(page));
443 SetPageUptodate(page);
446 ctx->ring_pages[i] = page;
450 if (unlikely(i != nr_pages)) {
455 ctx->mmap_size = nr_pages * PAGE_SIZE;
456 pr_debug("attempting mmap of %lu bytes\n", ctx->mmap_size);
458 down_write(&mm->mmap_sem);
459 ctx->mmap_base = do_mmap_pgoff(ctx->aio_ring_file, 0, ctx->mmap_size,
460 PROT_READ | PROT_WRITE,
461 MAP_SHARED, 0, &unused);
462 up_write(&mm->mmap_sem);
463 if (IS_ERR((void *)ctx->mmap_base)) {
469 pr_debug("mmap address: 0x%08lx\n", ctx->mmap_base);
471 ctx->user_id = ctx->mmap_base;
472 ctx->nr_events = nr_events; /* trusted copy */
474 ring = kmap_atomic(ctx->ring_pages[0]);
475 ring->nr = nr_events; /* user copy */
477 ring->head = ring->tail = 0;
478 ring->magic = AIO_RING_MAGIC;
479 ring->compat_features = AIO_RING_COMPAT_FEATURES;
480 ring->incompat_features = AIO_RING_INCOMPAT_FEATURES;
481 ring->header_length = sizeof(struct aio_ring);
483 flush_dcache_page(ctx->ring_pages[0]);
488 #define AIO_EVENTS_PER_PAGE (PAGE_SIZE / sizeof(struct io_event))
489 #define AIO_EVENTS_FIRST_PAGE ((PAGE_SIZE - sizeof(struct aio_ring)) / sizeof(struct io_event))
490 #define AIO_EVENTS_OFFSET (AIO_EVENTS_PER_PAGE - AIO_EVENTS_FIRST_PAGE)
492 void kiocb_set_cancel_fn(struct kiocb *req, kiocb_cancel_fn *cancel)
494 struct kioctx *ctx = req->ki_ctx;
497 spin_lock_irqsave(&ctx->ctx_lock, flags);
499 if (!req->ki_list.next)
500 list_add(&req->ki_list, &ctx->active_reqs);
502 req->ki_cancel = cancel;
504 spin_unlock_irqrestore(&ctx->ctx_lock, flags);
506 EXPORT_SYMBOL(kiocb_set_cancel_fn);
508 static int kiocb_cancel(struct kiocb *kiocb)
510 kiocb_cancel_fn *old, *cancel;
513 * Don't want to set kiocb->ki_cancel = KIOCB_CANCELLED unless it
514 * actually has a cancel function, hence the cmpxchg()
517 cancel = ACCESS_ONCE(kiocb->ki_cancel);
519 if (!cancel || cancel == KIOCB_CANCELLED)
523 cancel = cmpxchg(&kiocb->ki_cancel, old, KIOCB_CANCELLED);
524 } while (cancel != old);
526 return cancel(kiocb);
529 static void free_ioctx(struct work_struct *work)
531 struct kioctx *ctx = container_of(work, struct kioctx, free_work);
533 pr_debug("freeing %p\n", ctx);
536 free_percpu(ctx->cpu);
537 percpu_ref_exit(&ctx->reqs);
538 percpu_ref_exit(&ctx->users);
539 kmem_cache_free(kioctx_cachep, ctx);
542 static void free_ioctx_reqs(struct percpu_ref *ref)
544 struct kioctx *ctx = container_of(ref, struct kioctx, reqs);
546 /* At this point we know that there are no any in-flight requests */
547 if (ctx->rq_wait && atomic_dec_and_test(&ctx->rq_wait->count))
548 complete(&ctx->rq_wait->comp);
550 INIT_WORK(&ctx->free_work, free_ioctx);
551 schedule_work(&ctx->free_work);
555 * When this function runs, the kioctx has been removed from the "hash table"
556 * and ctx->users has dropped to 0, so we know no more kiocbs can be submitted -
557 * now it's safe to cancel any that need to be.
559 static void free_ioctx_users(struct percpu_ref *ref)
561 struct kioctx *ctx = container_of(ref, struct kioctx, users);
564 spin_lock_irq(&ctx->ctx_lock);
566 while (!list_empty(&ctx->active_reqs)) {
567 req = list_first_entry(&ctx->active_reqs,
568 struct kiocb, ki_list);
570 list_del_init(&req->ki_list);
574 spin_unlock_irq(&ctx->ctx_lock);
576 percpu_ref_kill(&ctx->reqs);
577 percpu_ref_put(&ctx->reqs);
580 static int ioctx_add_table(struct kioctx *ctx, struct mm_struct *mm)
583 struct kioctx_table *table, *old;
584 struct aio_ring *ring;
586 spin_lock(&mm->ioctx_lock);
587 table = rcu_dereference_raw(mm->ioctx_table);
591 for (i = 0; i < table->nr; i++)
592 if (!table->table[i]) {
594 table->table[i] = ctx;
595 spin_unlock(&mm->ioctx_lock);
597 /* While kioctx setup is in progress,
598 * we are protected from page migration
599 * changes ring_pages by ->ring_lock.
601 ring = kmap_atomic(ctx->ring_pages[0]);
607 new_nr = (table ? table->nr : 1) * 4;
608 spin_unlock(&mm->ioctx_lock);
610 table = kzalloc(sizeof(*table) + sizeof(struct kioctx *) *
617 spin_lock(&mm->ioctx_lock);
618 old = rcu_dereference_raw(mm->ioctx_table);
621 rcu_assign_pointer(mm->ioctx_table, table);
622 } else if (table->nr > old->nr) {
623 memcpy(table->table, old->table,
624 old->nr * sizeof(struct kioctx *));
626 rcu_assign_pointer(mm->ioctx_table, table);
635 static void aio_nr_sub(unsigned nr)
637 spin_lock(&aio_nr_lock);
638 if (WARN_ON(aio_nr - nr > aio_nr))
642 spin_unlock(&aio_nr_lock);
646 * Allocates and initializes an ioctx. Returns an ERR_PTR if it failed.
648 static struct kioctx *ioctx_alloc(unsigned nr_events)
650 struct mm_struct *mm = current->mm;
655 * We keep track of the number of available ringbuffer slots, to prevent
656 * overflow (reqs_available), and we also use percpu counters for this.
658 * So since up to half the slots might be on other cpu's percpu counters
659 * and unavailable, double nr_events so userspace sees what they
660 * expected: additionally, we move req_batch slots to/from percpu
661 * counters at a time, so make sure that isn't 0:
663 nr_events = max(nr_events, num_possible_cpus() * 4);
666 /* Prevent overflows */
667 if ((nr_events > (0x10000000U / sizeof(struct io_event))) ||
668 (nr_events > (0x10000000U / sizeof(struct kiocb)))) {
669 pr_debug("ENOMEM: nr_events too high\n");
670 return ERR_PTR(-EINVAL);
673 if (!nr_events || (unsigned long)nr_events > (aio_max_nr * 2UL))
674 return ERR_PTR(-EAGAIN);
676 ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL);
678 return ERR_PTR(-ENOMEM);
680 ctx->max_reqs = nr_events;
682 spin_lock_init(&ctx->ctx_lock);
683 spin_lock_init(&ctx->completion_lock);
684 mutex_init(&ctx->ring_lock);
685 /* Protect against page migration throughout kiotx setup by keeping
686 * the ring_lock mutex held until setup is complete. */
687 mutex_lock(&ctx->ring_lock);
688 init_waitqueue_head(&ctx->wait);
690 INIT_LIST_HEAD(&ctx->active_reqs);
692 if (percpu_ref_init(&ctx->users, free_ioctx_users, 0, GFP_KERNEL))
695 if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs, 0, GFP_KERNEL))
698 ctx->cpu = alloc_percpu(struct kioctx_cpu);
702 err = aio_setup_ring(ctx);
706 atomic_set(&ctx->reqs_available, ctx->nr_events - 1);
707 ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4);
708 if (ctx->req_batch < 1)
711 /* limit the number of system wide aios */
712 spin_lock(&aio_nr_lock);
713 if (aio_nr + nr_events > (aio_max_nr * 2UL) ||
714 aio_nr + nr_events < aio_nr) {
715 spin_unlock(&aio_nr_lock);
719 aio_nr += ctx->max_reqs;
720 spin_unlock(&aio_nr_lock);
722 percpu_ref_get(&ctx->users); /* io_setup() will drop this ref */
723 percpu_ref_get(&ctx->reqs); /* free_ioctx_users() will drop this */
725 err = ioctx_add_table(ctx, mm);
729 /* Release the ring_lock mutex now that all setup is complete. */
730 mutex_unlock(&ctx->ring_lock);
732 pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
733 ctx, ctx->user_id, mm, ctx->nr_events);
737 aio_nr_sub(ctx->max_reqs);
739 atomic_set(&ctx->dead, 1);
741 vm_munmap(ctx->mmap_base, ctx->mmap_size);
744 mutex_unlock(&ctx->ring_lock);
745 free_percpu(ctx->cpu);
746 percpu_ref_exit(&ctx->reqs);
747 percpu_ref_exit(&ctx->users);
748 kmem_cache_free(kioctx_cachep, ctx);
749 pr_debug("error allocating ioctx %d\n", err);
754 * Cancels all outstanding aio requests on an aio context. Used
755 * when the processes owning a context have all exited to encourage
756 * the rapid destruction of the kioctx.
758 static int kill_ioctx(struct mm_struct *mm, struct kioctx *ctx,
759 struct ctx_rq_wait *wait)
761 struct kioctx_table *table;
763 spin_lock(&mm->ioctx_lock);
764 if (atomic_xchg(&ctx->dead, 1)) {
765 spin_unlock(&mm->ioctx_lock);
769 table = rcu_dereference_raw(mm->ioctx_table);
770 WARN_ON(ctx != table->table[ctx->id]);
771 table->table[ctx->id] = NULL;
772 spin_unlock(&mm->ioctx_lock);
774 /* percpu_ref_kill() will do the necessary call_rcu() */
775 wake_up_all(&ctx->wait);
778 * It'd be more correct to do this in free_ioctx(), after all
779 * the outstanding kiocbs have finished - but by then io_destroy
780 * has already returned, so io_setup() could potentially return
781 * -EAGAIN with no ioctxs actually in use (as far as userspace
784 aio_nr_sub(ctx->max_reqs);
787 vm_munmap(ctx->mmap_base, ctx->mmap_size);
790 percpu_ref_kill(&ctx->users);
794 /* wait_on_sync_kiocb:
795 * Waits on the given sync kiocb to complete.
797 ssize_t wait_on_sync_kiocb(struct kiocb *req)
799 while (!req->ki_ctx) {
800 set_current_state(TASK_UNINTERRUPTIBLE);
805 __set_current_state(TASK_RUNNING);
806 return req->ki_user_data;
808 EXPORT_SYMBOL(wait_on_sync_kiocb);
811 * exit_aio: called when the last user of mm goes away. At this point, there is
812 * no way for any new requests to be submited or any of the io_* syscalls to be
813 * called on the context.
815 * There may be outstanding kiocbs, but free_ioctx() will explicitly wait on
818 void exit_aio(struct mm_struct *mm)
820 struct kioctx_table *table = rcu_dereference_raw(mm->ioctx_table);
821 struct ctx_rq_wait wait;
827 atomic_set(&wait.count, table->nr);
828 init_completion(&wait.comp);
831 for (i = 0; i < table->nr; ++i) {
832 struct kioctx *ctx = table->table[i];
840 * We don't need to bother with munmap() here - exit_mmap(mm)
841 * is coming and it'll unmap everything. And we simply can't,
842 * this is not necessarily our ->mm.
843 * Since kill_ioctx() uses non-zero ->mmap_size as indicator
844 * that it needs to unmap the area, just set it to 0.
847 kill_ioctx(mm, ctx, &wait);
850 if (!atomic_sub_and_test(skipped, &wait.count)) {
851 /* Wait until all IO for the context are done. */
852 wait_for_completion(&wait.comp);
855 RCU_INIT_POINTER(mm->ioctx_table, NULL);
859 static void put_reqs_available(struct kioctx *ctx, unsigned nr)
861 struct kioctx_cpu *kcpu;
864 local_irq_save(flags);
865 kcpu = this_cpu_ptr(ctx->cpu);
866 kcpu->reqs_available += nr;
868 while (kcpu->reqs_available >= ctx->req_batch * 2) {
869 kcpu->reqs_available -= ctx->req_batch;
870 atomic_add(ctx->req_batch, &ctx->reqs_available);
873 local_irq_restore(flags);
876 static bool get_reqs_available(struct kioctx *ctx)
878 struct kioctx_cpu *kcpu;
882 local_irq_save(flags);
883 kcpu = this_cpu_ptr(ctx->cpu);
884 if (!kcpu->reqs_available) {
885 int old, avail = atomic_read(&ctx->reqs_available);
888 if (avail < ctx->req_batch)
892 avail = atomic_cmpxchg(&ctx->reqs_available,
893 avail, avail - ctx->req_batch);
894 } while (avail != old);
896 kcpu->reqs_available += ctx->req_batch;
900 kcpu->reqs_available--;
902 local_irq_restore(flags);
906 /* refill_reqs_available
907 * Updates the reqs_available reference counts used for tracking the
908 * number of free slots in the completion ring. This can be called
909 * from aio_complete() (to optimistically update reqs_available) or
910 * from aio_get_req() (the we're out of events case). It must be
911 * called holding ctx->completion_lock.
913 static void refill_reqs_available(struct kioctx *ctx, unsigned head,
916 unsigned events_in_ring, completed;
918 /* Clamp head since userland can write to it. */
919 head %= ctx->nr_events;
921 events_in_ring = tail - head;
923 events_in_ring = ctx->nr_events - (head - tail);
925 completed = ctx->completed_events;
926 if (events_in_ring < completed)
927 completed -= events_in_ring;
934 ctx->completed_events -= completed;
935 put_reqs_available(ctx, completed);
938 /* user_refill_reqs_available
939 * Called to refill reqs_available when aio_get_req() encounters an
940 * out of space in the completion ring.
942 static void user_refill_reqs_available(struct kioctx *ctx)
944 spin_lock_irq(&ctx->completion_lock);
945 if (ctx->completed_events) {
946 struct aio_ring *ring;
949 /* Access of ring->head may race with aio_read_events_ring()
950 * here, but that's okay since whether we read the old version
951 * or the new version, and either will be valid. The important
952 * part is that head cannot pass tail since we prevent
953 * aio_complete() from updating tail by holding
954 * ctx->completion_lock. Even if head is invalid, the check
955 * against ctx->completed_events below will make sure we do the
958 ring = kmap_atomic(ctx->ring_pages[0]);
962 refill_reqs_available(ctx, head, ctx->tail);
965 spin_unlock_irq(&ctx->completion_lock);
969 * Allocate a slot for an aio request.
970 * Returns NULL if no requests are free.
972 static inline struct kiocb *aio_get_req(struct kioctx *ctx)
976 if (!get_reqs_available(ctx)) {
977 user_refill_reqs_available(ctx);
978 if (!get_reqs_available(ctx))
982 req = kmem_cache_alloc(kiocb_cachep, GFP_KERNEL|__GFP_ZERO);
986 percpu_ref_get(&ctx->reqs);
991 put_reqs_available(ctx, 1);
995 static void kiocb_free(struct kiocb *req)
999 if (req->ki_eventfd != NULL)
1000 eventfd_ctx_put(req->ki_eventfd);
1001 kmem_cache_free(kiocb_cachep, req);
1004 static struct kioctx *lookup_ioctx(unsigned long ctx_id)
1006 struct aio_ring __user *ring = (void __user *)ctx_id;
1007 struct mm_struct *mm = current->mm;
1008 struct kioctx *ctx, *ret = NULL;
1009 struct kioctx_table *table;
1012 if (get_user(id, &ring->id))
1016 table = rcu_dereference(mm->ioctx_table);
1018 if (!table || id >= table->nr)
1021 ctx = table->table[id];
1022 if (ctx && ctx->user_id == ctx_id) {
1023 percpu_ref_get(&ctx->users);
1032 * Called when the io request on the given iocb is complete.
1034 void aio_complete(struct kiocb *iocb, long res, long res2)
1036 struct kioctx *ctx = iocb->ki_ctx;
1037 struct aio_ring *ring;
1038 struct io_event *ev_page, *event;
1039 unsigned tail, pos, head;
1040 unsigned long flags;
1043 * Special case handling for sync iocbs:
1044 * - events go directly into the iocb for fast handling
1045 * - the sync task with the iocb in its stack holds the single iocb
1046 * ref, no other paths have a way to get another ref
1047 * - the sync task helpfully left a reference to itself in the iocb
1049 if (is_sync_kiocb(iocb)) {
1050 iocb->ki_user_data = res;
1052 iocb->ki_ctx = ERR_PTR(-EXDEV);
1053 wake_up_process(iocb->ki_obj.tsk);
1057 if (iocb->ki_list.next) {
1058 unsigned long flags;
1060 spin_lock_irqsave(&ctx->ctx_lock, flags);
1061 list_del(&iocb->ki_list);
1062 spin_unlock_irqrestore(&ctx->ctx_lock, flags);
1066 * Add a completion event to the ring buffer. Must be done holding
1067 * ctx->completion_lock to prevent other code from messing with the tail
1068 * pointer since we might be called from irq context.
1070 spin_lock_irqsave(&ctx->completion_lock, flags);
1073 pos = tail + AIO_EVENTS_OFFSET;
1075 if (++tail >= ctx->nr_events)
1078 ev_page = kmap_atomic(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
1079 event = ev_page + pos % AIO_EVENTS_PER_PAGE;
1081 event->obj = (u64)(unsigned long)iocb->ki_obj.user;
1082 event->data = iocb->ki_user_data;
1086 kunmap_atomic(ev_page);
1087 flush_dcache_page(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
1089 pr_debug("%p[%u]: %p: %p %Lx %lx %lx\n",
1090 ctx, tail, iocb, iocb->ki_obj.user, iocb->ki_user_data,
1093 /* after flagging the request as done, we
1094 * must never even look at it again
1096 smp_wmb(); /* make event visible before updating tail */
1100 ring = kmap_atomic(ctx->ring_pages[0]);
1103 kunmap_atomic(ring);
1104 flush_dcache_page(ctx->ring_pages[0]);
1106 ctx->completed_events++;
1107 if (ctx->completed_events > 1)
1108 refill_reqs_available(ctx, head, tail);
1109 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1111 pr_debug("added to ring %p at [%u]\n", iocb, tail);
1114 * Check if the user asked us to deliver the result through an
1115 * eventfd. The eventfd_signal() function is safe to be called
1118 if (iocb->ki_eventfd != NULL)
1119 eventfd_signal(iocb->ki_eventfd, 1);
1121 /* everything turned out well, dispose of the aiocb. */
1125 * We have to order our ring_info tail store above and test
1126 * of the wait list below outside the wait lock. This is
1127 * like in wake_up_bit() where clearing a bit has to be
1128 * ordered with the unlocked test.
1132 if (waitqueue_active(&ctx->wait))
1133 wake_up(&ctx->wait);
1135 percpu_ref_put(&ctx->reqs);
1137 EXPORT_SYMBOL(aio_complete);
1139 /* aio_read_events_ring
1140 * Pull an event off of the ioctx's event ring. Returns the number of
1143 static long aio_read_events_ring(struct kioctx *ctx,
1144 struct io_event __user *event, long nr)
1146 struct aio_ring *ring;
1147 unsigned head, tail, pos;
1152 * The mutex can block and wake us up and that will cause
1153 * wait_event_interruptible_hrtimeout() to schedule without sleeping
1154 * and repeat. This should be rare enough that it doesn't cause
1155 * peformance issues. See the comment in read_events() for more detail.
1157 sched_annotate_sleep();
1158 mutex_lock(&ctx->ring_lock);
1160 /* Access to ->ring_pages here is protected by ctx->ring_lock. */
1161 ring = kmap_atomic(ctx->ring_pages[0]);
1164 kunmap_atomic(ring);
1167 * Ensure that once we've read the current tail pointer, that
1168 * we also see the events that were stored up to the tail.
1172 pr_debug("h%u t%u m%u\n", head, tail, ctx->nr_events);
1177 head %= ctx->nr_events;
1178 tail %= ctx->nr_events;
1182 struct io_event *ev;
1185 avail = (head <= tail ? tail : ctx->nr_events) - head;
1189 avail = min(avail, nr - ret);
1190 avail = min_t(long, avail, AIO_EVENTS_PER_PAGE -
1191 ((head + AIO_EVENTS_OFFSET) % AIO_EVENTS_PER_PAGE));
1193 pos = head + AIO_EVENTS_OFFSET;
1194 page = ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE];
1195 pos %= AIO_EVENTS_PER_PAGE;
1198 copy_ret = copy_to_user(event + ret, ev + pos,
1199 sizeof(*ev) * avail);
1202 if (unlikely(copy_ret)) {
1209 head %= ctx->nr_events;
1212 ring = kmap_atomic(ctx->ring_pages[0]);
1214 kunmap_atomic(ring);
1215 flush_dcache_page(ctx->ring_pages[0]);
1217 pr_debug("%li h%u t%u\n", ret, head, tail);
1219 mutex_unlock(&ctx->ring_lock);
1224 static bool aio_read_events(struct kioctx *ctx, long min_nr, long nr,
1225 struct io_event __user *event, long *i)
1227 long ret = aio_read_events_ring(ctx, event + *i, nr - *i);
1232 if (unlikely(atomic_read(&ctx->dead)))
1238 return ret < 0 || *i >= min_nr;
1241 static long read_events(struct kioctx *ctx, long min_nr, long nr,
1242 struct io_event __user *event,
1243 struct timespec __user *timeout)
1245 ktime_t until = { .tv64 = KTIME_MAX };
1251 if (unlikely(copy_from_user(&ts, timeout, sizeof(ts))))
1254 until = timespec_to_ktime(ts);
1258 * Note that aio_read_events() is being called as the conditional - i.e.
1259 * we're calling it after prepare_to_wait() has set task state to
1260 * TASK_INTERRUPTIBLE.
1262 * But aio_read_events() can block, and if it blocks it's going to flip
1263 * the task state back to TASK_RUNNING.
1265 * This should be ok, provided it doesn't flip the state back to
1266 * TASK_RUNNING and return 0 too much - that causes us to spin. That
1267 * will only happen if the mutex_lock() call blocks, and we then find
1268 * the ringbuffer empty. So in practice we should be ok, but it's
1269 * something to be aware of when touching this code.
1271 if (until.tv64 == 0)
1272 aio_read_events(ctx, min_nr, nr, event, &ret);
1274 wait_event_interruptible_hrtimeout(ctx->wait,
1275 aio_read_events(ctx, min_nr, nr, event, &ret),
1278 if (!ret && signal_pending(current))
1285 * Create an aio_context capable of receiving at least nr_events.
1286 * ctxp must not point to an aio_context that already exists, and
1287 * must be initialized to 0 prior to the call. On successful
1288 * creation of the aio_context, *ctxp is filled in with the resulting
1289 * handle. May fail with -EINVAL if *ctxp is not initialized,
1290 * if the specified nr_events exceeds internal limits. May fail
1291 * with -EAGAIN if the specified nr_events exceeds the user's limit
1292 * of available events. May fail with -ENOMEM if insufficient kernel
1293 * resources are available. May fail with -EFAULT if an invalid
1294 * pointer is passed for ctxp. Will fail with -ENOSYS if not
1297 SYSCALL_DEFINE2(io_setup, unsigned, nr_events, aio_context_t __user *, ctxp)
1299 struct kioctx *ioctx = NULL;
1303 ret = get_user(ctx, ctxp);
1308 if (unlikely(ctx || nr_events == 0)) {
1309 pr_debug("EINVAL: ctx %lu nr_events %u\n",
1314 ioctx = ioctx_alloc(nr_events);
1315 ret = PTR_ERR(ioctx);
1316 if (!IS_ERR(ioctx)) {
1317 ret = put_user(ioctx->user_id, ctxp);
1319 kill_ioctx(current->mm, ioctx, NULL);
1320 percpu_ref_put(&ioctx->users);
1328 * Destroy the aio_context specified. May cancel any outstanding
1329 * AIOs and block on completion. Will fail with -ENOSYS if not
1330 * implemented. May fail with -EINVAL if the context pointed to
1333 SYSCALL_DEFINE1(io_destroy, aio_context_t, ctx)
1335 struct kioctx *ioctx = lookup_ioctx(ctx);
1336 if (likely(NULL != ioctx)) {
1337 struct ctx_rq_wait wait;
1340 init_completion(&wait.comp);
1341 atomic_set(&wait.count, 1);
1343 /* Pass requests_done to kill_ioctx() where it can be set
1344 * in a thread-safe way. If we try to set it here then we have
1345 * a race condition if two io_destroy() called simultaneously.
1347 ret = kill_ioctx(current->mm, ioctx, &wait);
1348 percpu_ref_put(&ioctx->users);
1350 /* Wait until all IO for the context are done. Otherwise kernel
1351 * keep using user-space buffers even if user thinks the context
1355 wait_for_completion(&wait.comp);
1359 pr_debug("EINVAL: invalid context id\n");
1363 typedef ssize_t (aio_rw_op)(struct kiocb *, const struct iovec *,
1364 unsigned long, loff_t);
1365 typedef ssize_t (rw_iter_op)(struct kiocb *, struct iov_iter *);
1367 static ssize_t aio_setup_vectored_rw(struct kiocb *kiocb,
1368 int rw, char __user *buf,
1369 unsigned long *nr_segs,
1370 struct iovec **iovec,
1375 *nr_segs = kiocb->ki_nbytes;
1377 #ifdef CONFIG_COMPAT
1379 ret = compat_rw_copy_check_uvector(rw,
1380 (struct compat_iovec __user *)buf,
1381 *nr_segs, UIO_FASTIOV, *iovec, iovec);
1384 ret = rw_copy_check_uvector(rw,
1385 (struct iovec __user *)buf,
1386 *nr_segs, UIO_FASTIOV, *iovec, iovec);
1390 /* ki_nbytes now reflect bytes instead of segs */
1391 kiocb->ki_nbytes = ret;
1395 static ssize_t aio_setup_single_vector(struct kiocb *kiocb,
1396 int rw, char __user *buf,
1397 unsigned long *nr_segs,
1398 struct iovec *iovec)
1400 if (unlikely(!access_ok(!rw, buf, kiocb->ki_nbytes)))
1403 iovec->iov_base = buf;
1404 iovec->iov_len = kiocb->ki_nbytes;
1411 * Performs the initial checks and io submission.
1413 static ssize_t aio_run_iocb(struct kiocb *req, unsigned opcode,
1414 char __user *buf, bool compat)
1416 struct file *file = req->ki_filp;
1418 unsigned long nr_segs;
1422 rw_iter_op *iter_op;
1423 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1424 struct iov_iter iter;
1427 case IOCB_CMD_PREAD:
1428 case IOCB_CMD_PREADV:
1431 rw_op = file->f_op->aio_read;
1432 iter_op = file->f_op->read_iter;
1435 case IOCB_CMD_PWRITE:
1436 case IOCB_CMD_PWRITEV:
1439 rw_op = file->f_op->aio_write;
1440 iter_op = file->f_op->write_iter;
1443 if (unlikely(!(file->f_mode & mode)))
1446 if (!rw_op && !iter_op)
1449 ret = (opcode == IOCB_CMD_PREADV ||
1450 opcode == IOCB_CMD_PWRITEV)
1451 ? aio_setup_vectored_rw(req, rw, buf, &nr_segs,
1453 : aio_setup_single_vector(req, rw, buf, &nr_segs,
1456 ret = rw_verify_area(rw, file, &req->ki_pos, req->ki_nbytes);
1458 if (iovec != inline_vecs)
1463 req->ki_nbytes = ret;
1465 /* XXX: move/kill - rw_verify_area()? */
1466 /* This matches the pread()/pwrite() logic */
1467 if (req->ki_pos < 0) {
1473 file_start_write(file);
1476 iov_iter_init(&iter, rw, iovec, nr_segs, req->ki_nbytes);
1477 ret = iter_op(req, &iter);
1479 ret = rw_op(req, iovec, nr_segs, req->ki_pos);
1483 file_end_write(file);
1486 case IOCB_CMD_FDSYNC:
1487 if (!file->f_op->aio_fsync)
1490 ret = file->f_op->aio_fsync(req, 1);
1493 case IOCB_CMD_FSYNC:
1494 if (!file->f_op->aio_fsync)
1497 ret = file->f_op->aio_fsync(req, 0);
1501 pr_debug("EINVAL: no operation provided\n");
1505 if (iovec != inline_vecs)
1508 if (ret != -EIOCBQUEUED) {
1510 * There's no easy way to restart the syscall since other AIO's
1511 * may be already running. Just fail this IO with EINTR.
1513 if (unlikely(ret == -ERESTARTSYS || ret == -ERESTARTNOINTR ||
1514 ret == -ERESTARTNOHAND ||
1515 ret == -ERESTART_RESTARTBLOCK))
1517 aio_complete(req, ret, 0);
1523 static int io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb,
1524 struct iocb *iocb, bool compat)
1529 /* enforce forwards compatibility on users */
1530 if (unlikely(iocb->aio_reserved1 || iocb->aio_reserved2)) {
1531 pr_debug("EINVAL: reserve field set\n");
1535 /* prevent overflows */
1537 (iocb->aio_buf != (unsigned long)iocb->aio_buf) ||
1538 (iocb->aio_nbytes != (size_t)iocb->aio_nbytes) ||
1539 ((ssize_t)iocb->aio_nbytes < 0)
1541 pr_debug("EINVAL: overflow check\n");
1545 req = aio_get_req(ctx);
1549 req->ki_filp = fget(iocb->aio_fildes);
1550 if (unlikely(!req->ki_filp)) {
1555 if (iocb->aio_flags & IOCB_FLAG_RESFD) {
1557 * If the IOCB_FLAG_RESFD flag of aio_flags is set, get an
1558 * instance of the file* now. The file descriptor must be
1559 * an eventfd() fd, and will be signaled for each completed
1560 * event using the eventfd_signal() function.
1562 req->ki_eventfd = eventfd_ctx_fdget((int) iocb->aio_resfd);
1563 if (IS_ERR(req->ki_eventfd)) {
1564 ret = PTR_ERR(req->ki_eventfd);
1565 req->ki_eventfd = NULL;
1570 ret = put_user(KIOCB_KEY, &user_iocb->aio_key);
1571 if (unlikely(ret)) {
1572 pr_debug("EFAULT: aio_key\n");
1576 req->ki_obj.user = user_iocb;
1577 req->ki_user_data = iocb->aio_data;
1578 req->ki_pos = iocb->aio_offset;
1579 req->ki_nbytes = iocb->aio_nbytes;
1581 ret = aio_run_iocb(req, iocb->aio_lio_opcode,
1582 (char __user *)(unsigned long)iocb->aio_buf,
1589 put_reqs_available(ctx, 1);
1590 percpu_ref_put(&ctx->reqs);
1595 long do_io_submit(aio_context_t ctx_id, long nr,
1596 struct iocb __user *__user *iocbpp, bool compat)
1601 struct blk_plug plug;
1603 if (unlikely(nr < 0))
1606 if (unlikely(nr > LONG_MAX/sizeof(*iocbpp)))
1607 nr = LONG_MAX/sizeof(*iocbpp);
1609 if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))
1612 ctx = lookup_ioctx(ctx_id);
1613 if (unlikely(!ctx)) {
1614 pr_debug("EINVAL: invalid context id\n");
1618 blk_start_plug(&plug);
1621 * AKPM: should this return a partial result if some of the IOs were
1622 * successfully submitted?
1624 for (i=0; i<nr; i++) {
1625 struct iocb __user *user_iocb;
1628 if (unlikely(__get_user(user_iocb, iocbpp + i))) {
1633 if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
1638 ret = io_submit_one(ctx, user_iocb, &tmp, compat);
1642 blk_finish_plug(&plug);
1644 percpu_ref_put(&ctx->users);
1649 * Queue the nr iocbs pointed to by iocbpp for processing. Returns
1650 * the number of iocbs queued. May return -EINVAL if the aio_context
1651 * specified by ctx_id is invalid, if nr is < 0, if the iocb at
1652 * *iocbpp[0] is not properly initialized, if the operation specified
1653 * is invalid for the file descriptor in the iocb. May fail with
1654 * -EFAULT if any of the data structures point to invalid data. May
1655 * fail with -EBADF if the file descriptor specified in the first
1656 * iocb is invalid. May fail with -EAGAIN if insufficient resources
1657 * are available to queue any iocbs. Will return 0 if nr is 0. Will
1658 * fail with -ENOSYS if not implemented.
1660 SYSCALL_DEFINE3(io_submit, aio_context_t, ctx_id, long, nr,
1661 struct iocb __user * __user *, iocbpp)
1663 return do_io_submit(ctx_id, nr, iocbpp, 0);
1667 * Finds a given iocb for cancellation.
1669 static struct kiocb *lookup_kiocb(struct kioctx *ctx, struct iocb __user *iocb,
1672 struct list_head *pos;
1674 assert_spin_locked(&ctx->ctx_lock);
1676 if (key != KIOCB_KEY)
1679 /* TODO: use a hash or array, this sucks. */
1680 list_for_each(pos, &ctx->active_reqs) {
1681 struct kiocb *kiocb = list_kiocb(pos);
1682 if (kiocb->ki_obj.user == iocb)
1689 * Attempts to cancel an iocb previously passed to io_submit. If
1690 * the operation is successfully cancelled, the resulting event is
1691 * copied into the memory pointed to by result without being placed
1692 * into the completion queue and 0 is returned. May fail with
1693 * -EFAULT if any of the data structures pointed to are invalid.
1694 * May fail with -EINVAL if aio_context specified by ctx_id is
1695 * invalid. May fail with -EAGAIN if the iocb specified was not
1696 * cancelled. Will fail with -ENOSYS if not implemented.
1698 SYSCALL_DEFINE3(io_cancel, aio_context_t, ctx_id, struct iocb __user *, iocb,
1699 struct io_event __user *, result)
1702 struct kiocb *kiocb;
1706 ret = get_user(key, &iocb->aio_key);
1710 ctx = lookup_ioctx(ctx_id);
1714 spin_lock_irq(&ctx->ctx_lock);
1716 kiocb = lookup_kiocb(ctx, iocb, key);
1718 ret = kiocb_cancel(kiocb);
1722 spin_unlock_irq(&ctx->ctx_lock);
1726 * The result argument is no longer used - the io_event is
1727 * always delivered via the ring buffer. -EINPROGRESS indicates
1728 * cancellation is progress:
1733 percpu_ref_put(&ctx->users);
1739 * Attempts to read at least min_nr events and up to nr events from
1740 * the completion queue for the aio_context specified by ctx_id. If
1741 * it succeeds, the number of read events is returned. May fail with
1742 * -EINVAL if ctx_id is invalid, if min_nr is out of range, if nr is
1743 * out of range, if timeout is out of range. May fail with -EFAULT
1744 * if any of the memory specified is invalid. May return 0 or
1745 * < min_nr if the timeout specified by timeout has elapsed
1746 * before sufficient events are available, where timeout == NULL
1747 * specifies an infinite timeout. Note that the timeout pointed to by
1748 * timeout is relative. Will fail with -ENOSYS if not implemented.
1750 SYSCALL_DEFINE5(io_getevents, aio_context_t, ctx_id,
1753 struct io_event __user *, events,
1754 struct timespec __user *, timeout)
1756 struct kioctx *ioctx = lookup_ioctx(ctx_id);
1759 if (likely(ioctx)) {
1760 if (likely(min_nr <= nr && min_nr >= 0))
1761 ret = read_events(ioctx, min_nr, nr, events, timeout);
1762 percpu_ref_put(&ioctx->users);