x86/speculation/l1tf: Protect NUMA-balance entries against L1TF
[linux/fpc-iii.git] / fs / aio.c
blobd01069c5e4b5c13e98f811eba5d328661089afb0
1 /*
2 * An async IO implementation for Linux
3 * Written by Benjamin LaHaise <bcrl@kvack.org>
5 * Implements an efficient asynchronous io interface.
7 * Copyright 2000, 2001, 2002 Red Hat, Inc. All Rights Reserved.
9 * See ../COPYING for licensing terms.
11 #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>
24 #include <linux/fs.h>
25 #include <linux/file.h>
26 #include <linux/mm.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>
47 #include "internal.h"
49 #define AIO_RING_MAGIC 0xa10a10a1
50 #define AIO_RING_COMPAT_FEATURES 1
51 #define AIO_RING_INCOMPAT_FEATURES 0
52 struct aio_ring {
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(). */
57 unsigned tail;
59 unsigned magic;
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
70 struct kioctx_table {
71 struct rcu_head rcu;
72 unsigned nr;
73 struct kioctx __rcu *table[];
76 struct kioctx_cpu {
77 unsigned reqs_available;
80 struct ctx_rq_wait {
81 struct completion comp;
82 atomic_t count;
85 struct kioctx {
86 struct percpu_ref users;
87 atomic_t dead;
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
97 * counter at a time:
99 unsigned req_batch;
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
105 * aio_setup_ring())
107 unsigned max_reqs;
109 /* Size of ringbuffer, in units of struct io_event */
110 unsigned nr_events;
112 unsigned long mmap_base;
113 unsigned long mmap_size;
115 struct page **ring_pages;
116 long nr_pages;
118 struct rcu_head free_rcu;
119 struct work_struct free_work; /* see free_ioctx() */
122 * signals when all in-flight requests are done
124 struct ctx_rq_wait *rq_wait;
126 struct {
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;
138 struct {
139 spinlock_t ctx_lock;
140 struct list_head active_reqs; /* used for cancellation */
141 } ____cacheline_aligned_in_smp;
143 struct {
144 struct mutex ring_lock;
145 wait_queue_head_t wait;
146 } ____cacheline_aligned_in_smp;
148 struct {
149 unsigned tail;
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;
157 unsigned id;
160 /*------ sysctl variables----*/
161 static DEFINE_SPINLOCK(aio_nr_lock);
162 unsigned long aio_nr; /* current system wide number of aio requests */
163 unsigned long aio_max_nr = 0x10000; /* system wide maximum number of aio requests */
164 /*----end sysctl variables---*/
166 static struct kmem_cache *kiocb_cachep;
167 static struct kmem_cache *kioctx_cachep;
169 static struct vfsmount *aio_mnt;
171 static const struct file_operations aio_ring_fops;
172 static const struct address_space_operations aio_ctx_aops;
174 /* Backing dev info for aio fs.
175 * -no dirty page accounting or writeback happens
177 static struct backing_dev_info aio_fs_backing_dev_info = {
178 .name = "aiofs",
179 .state = 0,
180 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK | BDI_CAP_MAP_COPY,
183 static struct file *aio_private_file(struct kioctx *ctx, loff_t nr_pages)
185 struct qstr this = QSTR_INIT("[aio]", 5);
186 struct file *file;
187 struct path path;
188 struct inode *inode = alloc_anon_inode(aio_mnt->mnt_sb);
189 if (IS_ERR(inode))
190 return ERR_CAST(inode);
192 inode->i_mapping->a_ops = &aio_ctx_aops;
193 inode->i_mapping->private_data = ctx;
194 inode->i_mapping->backing_dev_info = &aio_fs_backing_dev_info;
195 inode->i_size = PAGE_SIZE * nr_pages;
197 path.dentry = d_alloc_pseudo(aio_mnt->mnt_sb, &this);
198 if (!path.dentry) {
199 iput(inode);
200 return ERR_PTR(-ENOMEM);
202 path.mnt = mntget(aio_mnt);
204 d_instantiate(path.dentry, inode);
205 file = alloc_file(&path, FMODE_READ | FMODE_WRITE, &aio_ring_fops);
206 if (IS_ERR(file)) {
207 path_put(&path);
208 return file;
211 file->f_flags = O_RDWR;
212 file->private_data = ctx;
213 return file;
216 static struct dentry *aio_mount(struct file_system_type *fs_type,
217 int flags, const char *dev_name, void *data)
219 static const struct dentry_operations ops = {
220 .d_dname = simple_dname,
222 return mount_pseudo(fs_type, "aio:", NULL, &ops, 0xa10a10a1);
225 /* aio_setup
226 * Creates the slab caches used by the aio routines, panic on
227 * failure as this is done early during the boot sequence.
229 static int __init aio_setup(void)
231 static struct file_system_type aio_fs = {
232 .name = "aio",
233 .mount = aio_mount,
234 .kill_sb = kill_anon_super,
235 .fs_flags = FS_NOEXEC,
237 aio_mnt = kern_mount(&aio_fs);
238 if (IS_ERR(aio_mnt))
239 panic("Failed to create aio fs mount.");
241 if (bdi_init(&aio_fs_backing_dev_info))
242 panic("Failed to init aio fs backing dev info.");
244 kiocb_cachep = KMEM_CACHE(kiocb, SLAB_HWCACHE_ALIGN|SLAB_PANIC);
245 kioctx_cachep = KMEM_CACHE(kioctx,SLAB_HWCACHE_ALIGN|SLAB_PANIC);
247 pr_debug("sizeof(struct page) = %zu\n", sizeof(struct page));
249 return 0;
251 __initcall(aio_setup);
253 static void put_aio_ring_file(struct kioctx *ctx)
255 struct file *aio_ring_file = ctx->aio_ring_file;
256 if (aio_ring_file) {
257 truncate_setsize(aio_ring_file->f_inode, 0);
259 /* Prevent further access to the kioctx from migratepages */
260 spin_lock(&aio_ring_file->f_inode->i_mapping->private_lock);
261 aio_ring_file->f_inode->i_mapping->private_data = NULL;
262 ctx->aio_ring_file = NULL;
263 spin_unlock(&aio_ring_file->f_inode->i_mapping->private_lock);
265 fput(aio_ring_file);
269 static void aio_free_ring(struct kioctx *ctx)
271 int i;
273 /* Disconnect the kiotx from the ring file. This prevents future
274 * accesses to the kioctx from page migration.
276 put_aio_ring_file(ctx);
278 for (i = 0; i < ctx->nr_pages; i++) {
279 struct page *page;
280 pr_debug("pid(%d) [%d] page->count=%d\n", current->pid, i,
281 page_count(ctx->ring_pages[i]));
282 page = ctx->ring_pages[i];
283 if (!page)
284 continue;
285 ctx->ring_pages[i] = NULL;
286 put_page(page);
289 if (ctx->ring_pages && ctx->ring_pages != ctx->internal_pages) {
290 kfree(ctx->ring_pages);
291 ctx->ring_pages = NULL;
295 static int aio_ring_mmap(struct file *file, struct vm_area_struct *vma)
297 vma->vm_ops = &generic_file_vm_ops;
298 return 0;
301 static const struct file_operations aio_ring_fops = {
302 .mmap = aio_ring_mmap,
305 #if IS_ENABLED(CONFIG_MIGRATION)
306 static int aio_migratepage(struct address_space *mapping, struct page *new,
307 struct page *old, enum migrate_mode mode)
309 struct kioctx *ctx;
310 unsigned long flags;
311 pgoff_t idx;
312 int rc;
314 rc = 0;
316 /* mapping->private_lock here protects against the kioctx teardown. */
317 spin_lock(&mapping->private_lock);
318 ctx = mapping->private_data;
319 if (!ctx) {
320 rc = -EINVAL;
321 goto out;
324 /* The ring_lock mutex. The prevents aio_read_events() from writing
325 * to the ring's head, and prevents page migration from mucking in
326 * a partially initialized kiotx.
328 if (!mutex_trylock(&ctx->ring_lock)) {
329 rc = -EAGAIN;
330 goto out;
333 idx = old->index;
334 if (idx < (pgoff_t)ctx->nr_pages) {
335 /* Make sure the old page hasn't already been changed */
336 if (ctx->ring_pages[idx] != old)
337 rc = -EAGAIN;
338 } else
339 rc = -EINVAL;
341 if (rc != 0)
342 goto out_unlock;
344 /* Writeback must be complete */
345 BUG_ON(PageWriteback(old));
346 get_page(new);
348 rc = migrate_page_move_mapping(mapping, new, old, NULL, mode, 1);
349 if (rc != MIGRATEPAGE_SUCCESS) {
350 put_page(new);
351 goto out_unlock;
354 /* Take completion_lock to prevent other writes to the ring buffer
355 * while the old page is copied to the new. This prevents new
356 * events from being lost.
358 spin_lock_irqsave(&ctx->completion_lock, flags);
359 migrate_page_copy(new, old);
360 BUG_ON(ctx->ring_pages[idx] != old);
361 ctx->ring_pages[idx] = new;
362 spin_unlock_irqrestore(&ctx->completion_lock, flags);
364 /* The old page is no longer accessible. */
365 put_page(old);
367 out_unlock:
368 mutex_unlock(&ctx->ring_lock);
369 out:
370 spin_unlock(&mapping->private_lock);
371 return rc;
373 #endif
375 static const struct address_space_operations aio_ctx_aops = {
376 .set_page_dirty = __set_page_dirty_no_writeback,
377 #if IS_ENABLED(CONFIG_MIGRATION)
378 .migratepage = aio_migratepage,
379 #endif
382 static int aio_setup_ring(struct kioctx *ctx)
384 struct aio_ring *ring;
385 unsigned nr_events = ctx->max_reqs;
386 struct mm_struct *mm = current->mm;
387 unsigned long size, unused;
388 int nr_pages;
389 int i;
390 struct file *file;
392 /* Compensate for the ring buffer's head/tail overlap entry */
393 nr_events += 2; /* 1 is required, 2 for good luck */
395 size = sizeof(struct aio_ring);
396 size += sizeof(struct io_event) * nr_events;
398 nr_pages = PFN_UP(size);
399 if (nr_pages < 0)
400 return -EINVAL;
402 file = aio_private_file(ctx, nr_pages);
403 if (IS_ERR(file)) {
404 ctx->aio_ring_file = NULL;
405 return -ENOMEM;
408 ctx->aio_ring_file = file;
409 nr_events = (PAGE_SIZE * nr_pages - sizeof(struct aio_ring))
410 / sizeof(struct io_event);
412 ctx->ring_pages = ctx->internal_pages;
413 if (nr_pages > AIO_RING_PAGES) {
414 ctx->ring_pages = kcalloc(nr_pages, sizeof(struct page *),
415 GFP_KERNEL);
416 if (!ctx->ring_pages) {
417 put_aio_ring_file(ctx);
418 return -ENOMEM;
422 for (i = 0; i < nr_pages; i++) {
423 struct page *page;
424 page = find_or_create_page(file->f_inode->i_mapping,
425 i, GFP_HIGHUSER | __GFP_ZERO);
426 if (!page)
427 break;
428 pr_debug("pid(%d) page[%d]->count=%d\n",
429 current->pid, i, page_count(page));
430 SetPageUptodate(page);
431 unlock_page(page);
433 ctx->ring_pages[i] = page;
435 ctx->nr_pages = i;
437 if (unlikely(i != nr_pages)) {
438 aio_free_ring(ctx);
439 return -ENOMEM;
442 ctx->mmap_size = nr_pages * PAGE_SIZE;
443 pr_debug("attempting mmap of %lu bytes\n", ctx->mmap_size);
445 down_write(&mm->mmap_sem);
446 ctx->mmap_base = do_mmap_pgoff(ctx->aio_ring_file, 0, ctx->mmap_size,
447 PROT_READ | PROT_WRITE,
448 MAP_SHARED, 0, &unused);
449 up_write(&mm->mmap_sem);
450 if (IS_ERR((void *)ctx->mmap_base)) {
451 ctx->mmap_size = 0;
452 aio_free_ring(ctx);
453 return -ENOMEM;
456 pr_debug("mmap address: 0x%08lx\n", ctx->mmap_base);
458 ctx->user_id = ctx->mmap_base;
459 ctx->nr_events = nr_events; /* trusted copy */
461 ring = kmap_atomic(ctx->ring_pages[0]);
462 ring->nr = nr_events; /* user copy */
463 ring->id = ~0U;
464 ring->head = ring->tail = 0;
465 ring->magic = AIO_RING_MAGIC;
466 ring->compat_features = AIO_RING_COMPAT_FEATURES;
467 ring->incompat_features = AIO_RING_INCOMPAT_FEATURES;
468 ring->header_length = sizeof(struct aio_ring);
469 kunmap_atomic(ring);
470 flush_dcache_page(ctx->ring_pages[0]);
472 return 0;
475 #define AIO_EVENTS_PER_PAGE (PAGE_SIZE / sizeof(struct io_event))
476 #define AIO_EVENTS_FIRST_PAGE ((PAGE_SIZE - sizeof(struct aio_ring)) / sizeof(struct io_event))
477 #define AIO_EVENTS_OFFSET (AIO_EVENTS_PER_PAGE - AIO_EVENTS_FIRST_PAGE)
479 void kiocb_set_cancel_fn(struct kiocb *req, kiocb_cancel_fn *cancel)
481 struct kioctx *ctx = req->ki_ctx;
482 unsigned long flags;
484 spin_lock_irqsave(&ctx->ctx_lock, flags);
486 if (!req->ki_list.next)
487 list_add(&req->ki_list, &ctx->active_reqs);
489 req->ki_cancel = cancel;
491 spin_unlock_irqrestore(&ctx->ctx_lock, flags);
493 EXPORT_SYMBOL(kiocb_set_cancel_fn);
495 static int kiocb_cancel(struct kiocb *kiocb)
497 kiocb_cancel_fn *old, *cancel;
500 * Don't want to set kiocb->ki_cancel = KIOCB_CANCELLED unless it
501 * actually has a cancel function, hence the cmpxchg()
504 cancel = ACCESS_ONCE(kiocb->ki_cancel);
505 do {
506 if (!cancel || cancel == KIOCB_CANCELLED)
507 return -EINVAL;
509 old = cancel;
510 cancel = cmpxchg(&kiocb->ki_cancel, old, KIOCB_CANCELLED);
511 } while (cancel != old);
513 return cancel(kiocb);
517 * free_ioctx() should be RCU delayed to synchronize against the RCU
518 * protected lookup_ioctx() and also needs process context to call
519 * aio_free_ring(), so the double bouncing through kioctx->free_rcu and
520 * ->free_work.
522 static void free_ioctx(struct work_struct *work)
524 struct kioctx *ctx = container_of(work, struct kioctx, free_work);
526 pr_debug("freeing %p\n", ctx);
528 aio_free_ring(ctx);
529 free_percpu(ctx->cpu);
530 kmem_cache_free(kioctx_cachep, ctx);
533 static void free_ioctx_rcufn(struct rcu_head *head)
535 struct kioctx *ctx = container_of(head, struct kioctx, free_rcu);
537 INIT_WORK(&ctx->free_work, free_ioctx);
538 schedule_work(&ctx->free_work);
541 static void free_ioctx_reqs(struct percpu_ref *ref)
543 struct kioctx *ctx = container_of(ref, struct kioctx, reqs);
545 /* At this point we know that there are no any in-flight requests */
546 if (ctx->rq_wait && atomic_dec_and_test(&ctx->rq_wait->count))
547 complete(&ctx->rq_wait->comp);
549 /* Synchronize against RCU protected table->table[] dereferences */
550 call_rcu(&ctx->free_rcu, free_ioctx_rcufn);
554 * When this function runs, the kioctx has been removed from the "hash table"
555 * and ctx->users has dropped to 0, so we know no more kiocbs can be submitted -
556 * now it's safe to cancel any that need to be.
558 static void free_ioctx_users(struct percpu_ref *ref)
560 struct kioctx *ctx = container_of(ref, struct kioctx, users);
561 struct kiocb *req;
563 spin_lock_irq(&ctx->ctx_lock);
565 while (!list_empty(&ctx->active_reqs)) {
566 req = list_first_entry(&ctx->active_reqs,
567 struct kiocb, ki_list);
569 list_del_init(&req->ki_list);
570 kiocb_cancel(req);
573 spin_unlock_irq(&ctx->ctx_lock);
575 percpu_ref_kill(&ctx->reqs);
576 percpu_ref_put(&ctx->reqs);
579 static int ioctx_add_table(struct kioctx *ctx, struct mm_struct *mm)
581 unsigned i, new_nr;
582 struct kioctx_table *table, *old;
583 struct aio_ring *ring;
585 spin_lock(&mm->ioctx_lock);
586 table = rcu_dereference_raw(mm->ioctx_table);
588 while (1) {
589 if (table)
590 for (i = 0; i < table->nr; i++)
591 if (!rcu_access_pointer(table->table[i])) {
592 ctx->id = i;
593 rcu_assign_pointer(table->table[i], ctx);
594 spin_unlock(&mm->ioctx_lock);
596 /* While kioctx setup is in progress,
597 * we are protected from page migration
598 * changes ring_pages by ->ring_lock.
600 ring = kmap_atomic(ctx->ring_pages[0]);
601 ring->id = ctx->id;
602 kunmap_atomic(ring);
603 return 0;
606 new_nr = (table ? table->nr : 1) * 4;
607 spin_unlock(&mm->ioctx_lock);
609 table = kzalloc(sizeof(*table) + sizeof(struct kioctx *) *
610 new_nr, GFP_KERNEL);
611 if (!table)
612 return -ENOMEM;
614 table->nr = new_nr;
616 spin_lock(&mm->ioctx_lock);
617 old = rcu_dereference_raw(mm->ioctx_table);
619 if (!old) {
620 rcu_assign_pointer(mm->ioctx_table, table);
621 } else if (table->nr > old->nr) {
622 memcpy(table->table, old->table,
623 old->nr * sizeof(struct kioctx *));
625 rcu_assign_pointer(mm->ioctx_table, table);
626 kfree_rcu(old, rcu);
627 } else {
628 kfree(table);
629 table = old;
634 static void aio_nr_sub(unsigned nr)
636 spin_lock(&aio_nr_lock);
637 if (WARN_ON(aio_nr - nr > aio_nr))
638 aio_nr = 0;
639 else
640 aio_nr -= nr;
641 spin_unlock(&aio_nr_lock);
644 /* ioctx_alloc
645 * Allocates and initializes an ioctx. Returns an ERR_PTR if it failed.
647 static struct kioctx *ioctx_alloc(unsigned nr_events)
649 struct mm_struct *mm = current->mm;
650 struct kioctx *ctx;
651 int err = -ENOMEM;
654 * We keep track of the number of available ringbuffer slots, to prevent
655 * overflow (reqs_available), and we also use percpu counters for this.
657 * So since up to half the slots might be on other cpu's percpu counters
658 * and unavailable, double nr_events so userspace sees what they
659 * expected: additionally, we move req_batch slots to/from percpu
660 * counters at a time, so make sure that isn't 0:
662 nr_events = max(nr_events, num_possible_cpus() * 4);
663 nr_events *= 2;
665 /* Prevent overflows */
666 if ((nr_events > (0x10000000U / sizeof(struct io_event))) ||
667 (nr_events > (0x10000000U / sizeof(struct kiocb)))) {
668 pr_debug("ENOMEM: nr_events too high\n");
669 return ERR_PTR(-EINVAL);
672 if (!nr_events || (unsigned long)nr_events > (aio_max_nr * 2UL))
673 return ERR_PTR(-EAGAIN);
675 ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL);
676 if (!ctx)
677 return ERR_PTR(-ENOMEM);
679 ctx->max_reqs = nr_events;
681 spin_lock_init(&ctx->ctx_lock);
682 spin_lock_init(&ctx->completion_lock);
683 mutex_init(&ctx->ring_lock);
684 /* Protect against page migration throughout kiotx setup by keeping
685 * the ring_lock mutex held until setup is complete. */
686 mutex_lock(&ctx->ring_lock);
687 init_waitqueue_head(&ctx->wait);
689 INIT_LIST_HEAD(&ctx->active_reqs);
691 if (percpu_ref_init(&ctx->users, free_ioctx_users))
692 goto err;
694 if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs))
695 goto err;
697 ctx->cpu = alloc_percpu(struct kioctx_cpu);
698 if (!ctx->cpu)
699 goto err;
701 err = aio_setup_ring(ctx);
702 if (err < 0)
703 goto err;
705 atomic_set(&ctx->reqs_available, ctx->nr_events - 1);
706 ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4);
707 if (ctx->req_batch < 1)
708 ctx->req_batch = 1;
710 /* limit the number of system wide aios */
711 spin_lock(&aio_nr_lock);
712 if (aio_nr + nr_events > (aio_max_nr * 2UL) ||
713 aio_nr + nr_events < aio_nr) {
714 spin_unlock(&aio_nr_lock);
715 err = -EAGAIN;
716 goto err_ctx;
718 aio_nr += ctx->max_reqs;
719 spin_unlock(&aio_nr_lock);
721 percpu_ref_get(&ctx->users); /* io_setup() will drop this ref */
722 percpu_ref_get(&ctx->reqs); /* free_ioctx_users() will drop this */
724 err = ioctx_add_table(ctx, mm);
725 if (err)
726 goto err_cleanup;
728 /* Release the ring_lock mutex now that all setup is complete. */
729 mutex_unlock(&ctx->ring_lock);
731 pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
732 ctx, ctx->user_id, mm, ctx->nr_events);
733 return ctx;
735 err_cleanup:
736 aio_nr_sub(ctx->max_reqs);
737 err_ctx:
738 atomic_set(&ctx->dead, 1);
739 if (ctx->mmap_size)
740 vm_munmap(ctx->mmap_base, ctx->mmap_size);
741 aio_free_ring(ctx);
742 err:
743 mutex_unlock(&ctx->ring_lock);
744 free_percpu(ctx->cpu);
745 free_percpu(ctx->reqs.pcpu_count);
746 free_percpu(ctx->users.pcpu_count);
747 kmem_cache_free(kioctx_cachep, ctx);
748 pr_debug("error allocating ioctx %d\n", err);
749 return ERR_PTR(err);
752 /* kill_ioctx
753 * Cancels all outstanding aio requests on an aio context. Used
754 * when the processes owning a context have all exited to encourage
755 * the rapid destruction of the kioctx.
757 static int kill_ioctx(struct mm_struct *mm, struct kioctx *ctx,
758 struct ctx_rq_wait *wait)
760 struct kioctx_table *table;
762 if (atomic_xchg(&ctx->dead, 1))
763 return -EINVAL;
766 spin_lock(&mm->ioctx_lock);
767 table = rcu_dereference_raw(mm->ioctx_table);
768 WARN_ON(ctx != rcu_access_pointer(table->table[ctx->id]));
769 RCU_INIT_POINTER(table->table[ctx->id], NULL);
770 spin_unlock(&mm->ioctx_lock);
772 /* free_ioctx_reqs() will do the necessary RCU synchronization */
773 wake_up_all(&ctx->wait);
776 * It'd be more correct to do this in free_ioctx(), after all
777 * the outstanding kiocbs have finished - but by then io_destroy
778 * has already returned, so io_setup() could potentially return
779 * -EAGAIN with no ioctxs actually in use (as far as userspace
780 * could tell).
782 aio_nr_sub(ctx->max_reqs);
784 if (ctx->mmap_size)
785 vm_munmap(ctx->mmap_base, ctx->mmap_size);
787 ctx->rq_wait = wait;
788 percpu_ref_kill(&ctx->users);
789 return 0;
792 /* wait_on_sync_kiocb:
793 * Waits on the given sync kiocb to complete.
795 ssize_t wait_on_sync_kiocb(struct kiocb *req)
797 while (!req->ki_ctx) {
798 set_current_state(TASK_UNINTERRUPTIBLE);
799 if (req->ki_ctx)
800 break;
801 io_schedule();
803 __set_current_state(TASK_RUNNING);
804 return req->ki_user_data;
806 EXPORT_SYMBOL(wait_on_sync_kiocb);
809 * exit_aio: called when the last user of mm goes away. At this point, there is
810 * no way for any new requests to be submited or any of the io_* syscalls to be
811 * called on the context.
813 * There may be outstanding kiocbs, but free_ioctx() will explicitly wait on
814 * them.
816 void exit_aio(struct mm_struct *mm)
818 struct kioctx_table *table = rcu_dereference_raw(mm->ioctx_table);
819 struct ctx_rq_wait wait;
820 int i, skipped;
822 if (!table)
823 return;
825 atomic_set(&wait.count, table->nr);
826 init_completion(&wait.comp);
828 skipped = 0;
829 for (i = 0; i < table->nr; ++i) {
830 struct kioctx *ctx =
831 rcu_dereference_protected(table->table[i], true);
833 if (!ctx) {
834 skipped++;
835 continue;
839 * We don't need to bother with munmap() here - exit_mmap(mm)
840 * is coming and it'll unmap everything. And we simply can't,
841 * this is not necessarily our ->mm.
842 * Since kill_ioctx() uses non-zero ->mmap_size as indicator
843 * that it needs to unmap the area, just set it to 0.
845 ctx->mmap_size = 0;
846 kill_ioctx(mm, ctx, &wait);
849 if (!atomic_sub_and_test(skipped, &wait.count)) {
850 /* Wait until all IO for the context are done. */
851 wait_for_completion(&wait.comp);
854 RCU_INIT_POINTER(mm->ioctx_table, NULL);
855 kfree(table);
858 static void put_reqs_available(struct kioctx *ctx, unsigned nr)
860 struct kioctx_cpu *kcpu;
861 unsigned long flags;
863 preempt_disable();
864 kcpu = this_cpu_ptr(ctx->cpu);
866 local_irq_save(flags);
867 kcpu->reqs_available += nr;
869 while (kcpu->reqs_available >= ctx->req_batch * 2) {
870 kcpu->reqs_available -= ctx->req_batch;
871 atomic_add(ctx->req_batch, &ctx->reqs_available);
874 local_irq_restore(flags);
875 preempt_enable();
878 static bool get_reqs_available(struct kioctx *ctx)
880 struct kioctx_cpu *kcpu;
881 bool ret = false;
882 unsigned long flags;
884 preempt_disable();
885 kcpu = this_cpu_ptr(ctx->cpu);
887 local_irq_save(flags);
888 if (!kcpu->reqs_available) {
889 int old, avail = atomic_read(&ctx->reqs_available);
891 do {
892 if (avail < ctx->req_batch)
893 goto out;
895 old = avail;
896 avail = atomic_cmpxchg(&ctx->reqs_available,
897 avail, avail - ctx->req_batch);
898 } while (avail != old);
900 kcpu->reqs_available += ctx->req_batch;
903 ret = true;
904 kcpu->reqs_available--;
905 out:
906 local_irq_restore(flags);
907 preempt_enable();
908 return ret;
911 /* refill_reqs_available
912 * Updates the reqs_available reference counts used for tracking the
913 * number of free slots in the completion ring. This can be called
914 * from aio_complete() (to optimistically update reqs_available) or
915 * from aio_get_req() (the we're out of events case). It must be
916 * called holding ctx->completion_lock.
918 static void refill_reqs_available(struct kioctx *ctx, unsigned head,
919 unsigned tail)
921 unsigned events_in_ring, completed;
923 /* Clamp head since userland can write to it. */
924 head %= ctx->nr_events;
925 if (head <= tail)
926 events_in_ring = tail - head;
927 else
928 events_in_ring = ctx->nr_events - (head - tail);
930 completed = ctx->completed_events;
931 if (events_in_ring < completed)
932 completed -= events_in_ring;
933 else
934 completed = 0;
936 if (!completed)
937 return;
939 ctx->completed_events -= completed;
940 put_reqs_available(ctx, completed);
943 /* user_refill_reqs_available
944 * Called to refill reqs_available when aio_get_req() encounters an
945 * out of space in the completion ring.
947 static void user_refill_reqs_available(struct kioctx *ctx)
949 spin_lock_irq(&ctx->completion_lock);
950 if (ctx->completed_events) {
951 struct aio_ring *ring;
952 unsigned head;
954 /* Access of ring->head may race with aio_read_events_ring()
955 * here, but that's okay since whether we read the old version
956 * or the new version, and either will be valid. The important
957 * part is that head cannot pass tail since we prevent
958 * aio_complete() from updating tail by holding
959 * ctx->completion_lock. Even if head is invalid, the check
960 * against ctx->completed_events below will make sure we do the
961 * safe/right thing.
963 ring = kmap_atomic(ctx->ring_pages[0]);
964 head = ring->head;
965 kunmap_atomic(ring);
967 refill_reqs_available(ctx, head, ctx->tail);
970 spin_unlock_irq(&ctx->completion_lock);
973 /* aio_get_req
974 * Allocate a slot for an aio request.
975 * Returns NULL if no requests are free.
977 static inline struct kiocb *aio_get_req(struct kioctx *ctx)
979 struct kiocb *req;
981 if (!get_reqs_available(ctx)) {
982 user_refill_reqs_available(ctx);
983 if (!get_reqs_available(ctx))
984 return NULL;
987 req = kmem_cache_alloc(kiocb_cachep, GFP_KERNEL|__GFP_ZERO);
988 if (unlikely(!req))
989 goto out_put;
991 percpu_ref_get(&ctx->reqs);
993 req->ki_ctx = ctx;
994 return req;
995 out_put:
996 put_reqs_available(ctx, 1);
997 return NULL;
1000 static void kiocb_free(struct kiocb *req)
1002 if (req->ki_filp)
1003 fput(req->ki_filp);
1004 if (req->ki_eventfd != NULL)
1005 eventfd_ctx_put(req->ki_eventfd);
1006 kmem_cache_free(kiocb_cachep, req);
1009 static struct kioctx *lookup_ioctx(unsigned long ctx_id)
1011 struct aio_ring __user *ring = (void __user *)ctx_id;
1012 struct mm_struct *mm = current->mm;
1013 struct kioctx *ctx, *ret = NULL;
1014 struct kioctx_table *table;
1015 unsigned id;
1017 if (get_user(id, &ring->id))
1018 return NULL;
1020 rcu_read_lock();
1021 table = rcu_dereference(mm->ioctx_table);
1023 if (!table || id >= table->nr)
1024 goto out;
1026 ctx = rcu_dereference(table->table[id]);
1027 if (ctx && ctx->user_id == ctx_id) {
1028 percpu_ref_get(&ctx->users);
1029 ret = ctx;
1031 out:
1032 rcu_read_unlock();
1033 return ret;
1036 /* aio_complete
1037 * Called when the io request on the given iocb is complete.
1039 void aio_complete(struct kiocb *iocb, long res, long res2)
1041 struct kioctx *ctx = iocb->ki_ctx;
1042 struct aio_ring *ring;
1043 struct io_event *ev_page, *event;
1044 unsigned tail, pos, head;
1045 unsigned long flags;
1048 * Special case handling for sync iocbs:
1049 * - events go directly into the iocb for fast handling
1050 * - the sync task with the iocb in its stack holds the single iocb
1051 * ref, no other paths have a way to get another ref
1052 * - the sync task helpfully left a reference to itself in the iocb
1054 if (is_sync_kiocb(iocb)) {
1055 iocb->ki_user_data = res;
1056 smp_wmb();
1057 iocb->ki_ctx = ERR_PTR(-EXDEV);
1058 wake_up_process(iocb->ki_obj.tsk);
1059 return;
1062 if (iocb->ki_list.next) {
1063 unsigned long flags;
1065 spin_lock_irqsave(&ctx->ctx_lock, flags);
1066 list_del(&iocb->ki_list);
1067 spin_unlock_irqrestore(&ctx->ctx_lock, flags);
1071 * Add a completion event to the ring buffer. Must be done holding
1072 * ctx->completion_lock to prevent other code from messing with the tail
1073 * pointer since we might be called from irq context.
1075 spin_lock_irqsave(&ctx->completion_lock, flags);
1077 tail = ctx->tail;
1078 pos = tail + AIO_EVENTS_OFFSET;
1080 if (++tail >= ctx->nr_events)
1081 tail = 0;
1083 ev_page = kmap_atomic(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
1084 event = ev_page + pos % AIO_EVENTS_PER_PAGE;
1086 event->obj = (u64)(unsigned long)iocb->ki_obj.user;
1087 event->data = iocb->ki_user_data;
1088 event->res = res;
1089 event->res2 = res2;
1091 kunmap_atomic(ev_page);
1092 flush_dcache_page(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
1094 pr_debug("%p[%u]: %p: %p %Lx %lx %lx\n",
1095 ctx, tail, iocb, iocb->ki_obj.user, iocb->ki_user_data,
1096 res, res2);
1098 /* after flagging the request as done, we
1099 * must never even look at it again
1101 smp_wmb(); /* make event visible before updating tail */
1103 ctx->tail = tail;
1105 ring = kmap_atomic(ctx->ring_pages[0]);
1106 head = ring->head;
1107 ring->tail = tail;
1108 kunmap_atomic(ring);
1109 flush_dcache_page(ctx->ring_pages[0]);
1111 ctx->completed_events++;
1112 if (ctx->completed_events > 1)
1113 refill_reqs_available(ctx, head, tail);
1114 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1116 pr_debug("added to ring %p at [%u]\n", iocb, tail);
1119 * Check if the user asked us to deliver the result through an
1120 * eventfd. The eventfd_signal() function is safe to be called
1121 * from IRQ context.
1123 if (iocb->ki_eventfd != NULL)
1124 eventfd_signal(iocb->ki_eventfd, 1);
1126 /* everything turned out well, dispose of the aiocb. */
1127 kiocb_free(iocb);
1130 * We have to order our ring_info tail store above and test
1131 * of the wait list below outside the wait lock. This is
1132 * like in wake_up_bit() where clearing a bit has to be
1133 * ordered with the unlocked test.
1135 smp_mb();
1137 if (waitqueue_active(&ctx->wait))
1138 wake_up(&ctx->wait);
1140 percpu_ref_put(&ctx->reqs);
1142 EXPORT_SYMBOL(aio_complete);
1144 /* aio_read_events
1145 * Pull an event off of the ioctx's event ring. Returns the number of
1146 * events fetched
1148 static long aio_read_events_ring(struct kioctx *ctx,
1149 struct io_event __user *event, long nr)
1151 struct aio_ring *ring;
1152 unsigned head, tail, pos;
1153 long ret = 0;
1154 int copy_ret;
1156 mutex_lock(&ctx->ring_lock);
1158 /* Access to ->ring_pages here is protected by ctx->ring_lock. */
1159 ring = kmap_atomic(ctx->ring_pages[0]);
1160 head = ring->head;
1161 tail = ring->tail;
1162 kunmap_atomic(ring);
1165 * Ensure that once we've read the current tail pointer, that
1166 * we also see the events that were stored up to the tail.
1168 smp_rmb();
1170 pr_debug("h%u t%u m%u\n", head, tail, ctx->nr_events);
1172 if (head == tail)
1173 goto out;
1175 head %= ctx->nr_events;
1176 tail %= ctx->nr_events;
1178 while (ret < nr) {
1179 long avail;
1180 struct io_event *ev;
1181 struct page *page;
1183 avail = (head <= tail ? tail : ctx->nr_events) - head;
1184 if (head == tail)
1185 break;
1187 avail = min(avail, nr - ret);
1188 avail = min_t(long, avail, AIO_EVENTS_PER_PAGE -
1189 ((head + AIO_EVENTS_OFFSET) % AIO_EVENTS_PER_PAGE));
1191 pos = head + AIO_EVENTS_OFFSET;
1192 page = ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE];
1193 pos %= AIO_EVENTS_PER_PAGE;
1195 ev = kmap(page);
1196 copy_ret = copy_to_user(event + ret, ev + pos,
1197 sizeof(*ev) * avail);
1198 kunmap(page);
1200 if (unlikely(copy_ret)) {
1201 ret = -EFAULT;
1202 goto out;
1205 ret += avail;
1206 head += avail;
1207 head %= ctx->nr_events;
1210 ring = kmap_atomic(ctx->ring_pages[0]);
1211 ring->head = head;
1212 kunmap_atomic(ring);
1213 flush_dcache_page(ctx->ring_pages[0]);
1215 pr_debug("%li h%u t%u\n", ret, head, tail);
1216 out:
1217 mutex_unlock(&ctx->ring_lock);
1219 return ret;
1222 static bool aio_read_events(struct kioctx *ctx, long min_nr, long nr,
1223 struct io_event __user *event, long *i)
1225 long ret = aio_read_events_ring(ctx, event + *i, nr - *i);
1227 if (ret > 0)
1228 *i += ret;
1230 if (unlikely(atomic_read(&ctx->dead)))
1231 ret = -EINVAL;
1233 if (!*i)
1234 *i = ret;
1236 return ret < 0 || *i >= min_nr;
1239 static long read_events(struct kioctx *ctx, long min_nr, long nr,
1240 struct io_event __user *event,
1241 struct timespec __user *timeout)
1243 ktime_t until = { .tv64 = KTIME_MAX };
1244 long ret = 0;
1246 if (timeout) {
1247 struct timespec ts;
1249 if (unlikely(copy_from_user(&ts, timeout, sizeof(ts))))
1250 return -EFAULT;
1252 until = timespec_to_ktime(ts);
1256 * Note that aio_read_events() is being called as the conditional - i.e.
1257 * we're calling it after prepare_to_wait() has set task state to
1258 * TASK_INTERRUPTIBLE.
1260 * But aio_read_events() can block, and if it blocks it's going to flip
1261 * the task state back to TASK_RUNNING.
1263 * This should be ok, provided it doesn't flip the state back to
1264 * TASK_RUNNING and return 0 too much - that causes us to spin. That
1265 * will only happen if the mutex_lock() call blocks, and we then find
1266 * the ringbuffer empty. So in practice we should be ok, but it's
1267 * something to be aware of when touching this code.
1269 wait_event_interruptible_hrtimeout(ctx->wait,
1270 aio_read_events(ctx, min_nr, nr, event, &ret), until);
1272 if (!ret && signal_pending(current))
1273 ret = -EINTR;
1275 return ret;
1278 /* sys_io_setup:
1279 * Create an aio_context capable of receiving at least nr_events.
1280 * ctxp must not point to an aio_context that already exists, and
1281 * must be initialized to 0 prior to the call. On successful
1282 * creation of the aio_context, *ctxp is filled in with the resulting
1283 * handle. May fail with -EINVAL if *ctxp is not initialized,
1284 * if the specified nr_events exceeds internal limits. May fail
1285 * with -EAGAIN if the specified nr_events exceeds the user's limit
1286 * of available events. May fail with -ENOMEM if insufficient kernel
1287 * resources are available. May fail with -EFAULT if an invalid
1288 * pointer is passed for ctxp. Will fail with -ENOSYS if not
1289 * implemented.
1291 SYSCALL_DEFINE2(io_setup, unsigned, nr_events, aio_context_t __user *, ctxp)
1293 struct kioctx *ioctx = NULL;
1294 unsigned long ctx;
1295 long ret;
1297 ret = get_user(ctx, ctxp);
1298 if (unlikely(ret))
1299 goto out;
1301 ret = -EINVAL;
1302 if (unlikely(ctx || nr_events == 0)) {
1303 pr_debug("EINVAL: io_setup: ctx %lu nr_events %u\n",
1304 ctx, nr_events);
1305 goto out;
1308 ioctx = ioctx_alloc(nr_events);
1309 ret = PTR_ERR(ioctx);
1310 if (!IS_ERR(ioctx)) {
1311 ret = put_user(ioctx->user_id, ctxp);
1312 if (ret)
1313 kill_ioctx(current->mm, ioctx, NULL);
1314 percpu_ref_put(&ioctx->users);
1317 out:
1318 return ret;
1321 /* sys_io_destroy:
1322 * Destroy the aio_context specified. May cancel any outstanding
1323 * AIOs and block on completion. Will fail with -ENOSYS if not
1324 * implemented. May fail with -EINVAL if the context pointed to
1325 * is invalid.
1327 SYSCALL_DEFINE1(io_destroy, aio_context_t, ctx)
1329 struct kioctx *ioctx = lookup_ioctx(ctx);
1330 if (likely(NULL != ioctx)) {
1331 struct ctx_rq_wait wait;
1332 int ret;
1334 init_completion(&wait.comp);
1335 atomic_set(&wait.count, 1);
1337 /* Pass requests_done to kill_ioctx() where it can be set
1338 * in a thread-safe way. If we try to set it here then we have
1339 * a race condition if two io_destroy() called simultaneously.
1341 ret = kill_ioctx(current->mm, ioctx, &wait);
1342 percpu_ref_put(&ioctx->users);
1344 /* Wait until all IO for the context are done. Otherwise kernel
1345 * keep using user-space buffers even if user thinks the context
1346 * is destroyed.
1348 if (!ret)
1349 wait_for_completion(&wait.comp);
1351 return ret;
1353 pr_debug("EINVAL: io_destroy: invalid context id\n");
1354 return -EINVAL;
1357 typedef ssize_t (aio_rw_op)(struct kiocb *, const struct iovec *,
1358 unsigned long, loff_t);
1359 typedef ssize_t (rw_iter_op)(struct kiocb *, struct iov_iter *);
1361 static ssize_t aio_setup_vectored_rw(struct kiocb *kiocb,
1362 int rw, char __user *buf,
1363 unsigned long *nr_segs,
1364 struct iovec **iovec,
1365 bool compat)
1367 ssize_t ret;
1369 *nr_segs = kiocb->ki_nbytes;
1371 #ifdef CONFIG_COMPAT
1372 if (compat)
1373 ret = compat_rw_copy_check_uvector(rw,
1374 (struct compat_iovec __user *)buf,
1375 *nr_segs, 1, *iovec, iovec);
1376 else
1377 #endif
1378 ret = rw_copy_check_uvector(rw,
1379 (struct iovec __user *)buf,
1380 *nr_segs, 1, *iovec, iovec);
1381 if (ret < 0)
1382 return ret;
1384 /* ki_nbytes now reflect bytes instead of segs */
1385 kiocb->ki_nbytes = ret;
1386 return 0;
1389 static ssize_t aio_setup_single_vector(struct kiocb *kiocb,
1390 int rw, char __user *buf,
1391 unsigned long *nr_segs,
1392 struct iovec *iovec)
1394 size_t len = kiocb->ki_nbytes;
1396 if (len > MAX_RW_COUNT)
1397 len = MAX_RW_COUNT;
1399 if (unlikely(!access_ok(!rw, buf, len)))
1400 return -EFAULT;
1402 iovec->iov_base = buf;
1403 iovec->iov_len = len;
1404 *nr_segs = 1;
1405 return 0;
1409 * aio_setup_iocb:
1410 * Performs the initial checks and aio retry method
1411 * setup for the kiocb at the time of 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;
1417 ssize_t ret;
1418 unsigned long nr_segs;
1419 int rw;
1420 fmode_t mode;
1421 aio_rw_op *rw_op;
1422 rw_iter_op *iter_op;
1423 struct iovec inline_vec, *iovec = &inline_vec;
1424 struct iov_iter iter;
1426 switch (opcode) {
1427 case IOCB_CMD_PREAD:
1428 case IOCB_CMD_PREADV:
1429 mode = FMODE_READ;
1430 rw = READ;
1431 rw_op = file->f_op->aio_read;
1432 iter_op = file->f_op->read_iter;
1433 goto rw_common;
1435 case IOCB_CMD_PWRITE:
1436 case IOCB_CMD_PWRITEV:
1437 mode = FMODE_WRITE;
1438 rw = WRITE;
1439 rw_op = file->f_op->aio_write;
1440 iter_op = file->f_op->write_iter;
1441 goto rw_common;
1442 rw_common:
1443 if (unlikely(!(file->f_mode & mode)))
1444 return -EBADF;
1446 if (!rw_op && !iter_op)
1447 return -EINVAL;
1449 ret = (opcode == IOCB_CMD_PREADV ||
1450 opcode == IOCB_CMD_PWRITEV)
1451 ? aio_setup_vectored_rw(req, rw, buf, &nr_segs,
1452 &iovec, compat)
1453 : aio_setup_single_vector(req, rw, buf, &nr_segs,
1454 iovec);
1455 if (!ret)
1456 ret = rw_verify_area(rw, file, &req->ki_pos, req->ki_nbytes);
1457 if (ret < 0) {
1458 if (iovec != &inline_vec)
1459 kfree(iovec);
1460 return ret;
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) {
1468 ret = -EINVAL;
1469 break;
1472 if (rw == WRITE)
1473 file_start_write(file);
1475 if (iter_op) {
1476 iov_iter_init(&iter, rw, iovec, nr_segs, req->ki_nbytes);
1477 ret = iter_op(req, &iter);
1478 } else {
1479 ret = rw_op(req, iovec, nr_segs, req->ki_pos);
1482 if (rw == WRITE)
1483 file_end_write(file);
1484 break;
1486 case IOCB_CMD_FDSYNC:
1487 if (!file->f_op->aio_fsync)
1488 return -EINVAL;
1490 ret = file->f_op->aio_fsync(req, 1);
1491 break;
1493 case IOCB_CMD_FSYNC:
1494 if (!file->f_op->aio_fsync)
1495 return -EINVAL;
1497 ret = file->f_op->aio_fsync(req, 0);
1498 break;
1500 default:
1501 pr_debug("EINVAL: no operation provided\n");
1502 return -EINVAL;
1505 if (iovec != &inline_vec)
1506 kfree(iovec);
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))
1516 ret = -EINTR;
1517 aio_complete(req, ret, 0);
1520 return 0;
1523 static int io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb,
1524 struct iocb *iocb, bool compat)
1526 struct kiocb *req;
1527 ssize_t ret;
1529 /* enforce forwards compatibility on users */
1530 if (unlikely(iocb->aio_reserved1 || iocb->aio_reserved2)) {
1531 pr_debug("EINVAL: reserve field set\n");
1532 return -EINVAL;
1535 /* prevent overflows */
1536 if (unlikely(
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)
1540 )) {
1541 pr_debug("EINVAL: io_submit: overflow check\n");
1542 return -EINVAL;
1545 req = aio_get_req(ctx);
1546 if (unlikely(!req))
1547 return -EAGAIN;
1549 req->ki_filp = fget(iocb->aio_fildes);
1550 if (unlikely(!req->ki_filp)) {
1551 ret = -EBADF;
1552 goto out_put_req;
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;
1566 goto out_put_req;
1570 ret = put_user(KIOCB_KEY, &user_iocb->aio_key);
1571 if (unlikely(ret)) {
1572 pr_debug("EFAULT: aio_key\n");
1573 goto out_put_req;
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,
1583 compat);
1584 if (ret)
1585 goto out_put_req;
1587 return 0;
1588 out_put_req:
1589 put_reqs_available(ctx, 1);
1590 percpu_ref_put(&ctx->reqs);
1591 kiocb_free(req);
1592 return ret;
1595 long do_io_submit(aio_context_t ctx_id, long nr,
1596 struct iocb __user *__user *iocbpp, bool compat)
1598 struct kioctx *ctx;
1599 long ret = 0;
1600 int i = 0;
1601 struct blk_plug plug;
1603 if (unlikely(nr < 0))
1604 return -EINVAL;
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)))))
1610 return -EFAULT;
1612 ctx = lookup_ioctx(ctx_id);
1613 if (unlikely(!ctx)) {
1614 pr_debug("EINVAL: invalid context id\n");
1615 return -EINVAL;
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;
1626 struct iocb tmp;
1628 if (unlikely(__get_user(user_iocb, iocbpp + i))) {
1629 ret = -EFAULT;
1630 break;
1633 if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
1634 ret = -EFAULT;
1635 break;
1638 ret = io_submit_one(ctx, user_iocb, &tmp, compat);
1639 if (ret)
1640 break;
1642 blk_finish_plug(&plug);
1644 percpu_ref_put(&ctx->users);
1645 return i ? i : ret;
1648 /* sys_io_submit:
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);
1666 /* lookup_kiocb
1667 * Finds a given iocb for cancellation.
1669 static struct kiocb *lookup_kiocb(struct kioctx *ctx, struct iocb __user *iocb,
1670 u32 key)
1672 struct list_head *pos;
1674 assert_spin_locked(&ctx->ctx_lock);
1676 if (key != KIOCB_KEY)
1677 return NULL;
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)
1683 return kiocb;
1685 return NULL;
1688 /* sys_io_cancel:
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)
1701 struct kioctx *ctx;
1702 struct kiocb *kiocb;
1703 u32 key;
1704 int ret;
1706 ret = get_user(key, &iocb->aio_key);
1707 if (unlikely(ret))
1708 return -EFAULT;
1710 ctx = lookup_ioctx(ctx_id);
1711 if (unlikely(!ctx))
1712 return -EINVAL;
1714 spin_lock_irq(&ctx->ctx_lock);
1716 kiocb = lookup_kiocb(ctx, iocb, key);
1717 if (kiocb)
1718 ret = kiocb_cancel(kiocb);
1719 else
1720 ret = -EINVAL;
1722 spin_unlock_irq(&ctx->ctx_lock);
1724 if (!ret) {
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:
1730 ret = -EINPROGRESS;
1733 percpu_ref_put(&ctx->users);
1735 return ret;
1738 /* io_getevents:
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,
1751 long, min_nr,
1752 long, nr,
1753 struct io_event __user *, events,
1754 struct timespec __user *, timeout)
1756 struct kioctx *ioctx = lookup_ioctx(ctx_id);
1757 long ret = -EINVAL;
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);
1764 return ret;