]> git.karo-electronics.de Git - karo-tx-linux.git/blob - fs/aio.c
clk: imx: whitespace cleanup; no functional change
[karo-tx-linux.git] / fs / aio.c
1 /*
2  *      An async IO implementation for Linux
3  *      Written by Benjamin LaHaise <bcrl@kvack.org>
4  *
5  *      Implements an efficient asynchronous io interface.
6  *
7  *      Copyright 2000, 2001, 2002 Red Hat, Inc.  All Rights Reserved.
8  *
9  *      See ../COPYING for licensing terms.
10  */
11 #define pr_fmt(fmt) "%s: " fmt, __func__
12
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>
22
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>
43
44 #include <asm/kmap_types.h>
45 #include <asm/uaccess.h>
46
47 #include "internal.h"
48
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
53 struct aio_ring {
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(). */
58         unsigned        tail;
59
60         unsigned        magic;
61         unsigned        compat_features;
62         unsigned        incompat_features;
63         unsigned        header_length;  /* size of aio_ring */
64
65
66         struct io_event         io_events[0];
67 }; /* 128 bytes + ring size */
68
69 #define AIO_RING_PAGES  8
70
71 struct kioctx_table {
72         struct rcu_head rcu;
73         unsigned        nr;
74         struct kioctx   *table[];
75 };
76
77 struct kioctx_cpu {
78         unsigned                reqs_available;
79 };
80
81 struct ctx_rq_wait {
82         struct completion comp;
83         atomic_t count;
84 };
85
86 struct kioctx {
87         struct percpu_ref       users;
88         atomic_t                dead;
89
90         struct percpu_ref       reqs;
91
92         unsigned long           user_id;
93
94         struct __percpu kioctx_cpu *cpu;
95
96         /*
97          * For percpu reqs_available, number of slots we move to/from global
98          * counter at a time:
99          */
100         unsigned                req_batch;
101         /*
102          * This is what userspace passed to io_setup(), it's not used for
103          * anything but counting against the global max_reqs quota.
104          *
105          * The real limit is nr_events - 1, which will be larger (see
106          * aio_setup_ring())
107          */
108         unsigned                max_reqs;
109
110         /* Size of ringbuffer, in units of struct io_event */
111         unsigned                nr_events;
112
113         unsigned long           mmap_base;
114         unsigned long           mmap_size;
115
116         struct page             **ring_pages;
117         long                    nr_pages;
118
119         struct work_struct      free_work;
120
121         /*
122          * signals when all in-flight requests are done
123          */
124         struct ctx_rq_wait      *rq_wait;
125
126         struct {
127                 /*
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.
132                  *
133                  * We batch accesses to it with a percpu version.
134                  */
135                 atomic_t        reqs_available;
136         } ____cacheline_aligned_in_smp;
137
138         struct {
139                 spinlock_t      ctx_lock;
140                 struct list_head active_reqs;   /* used for cancellation */
141         } ____cacheline_aligned_in_smp;
142
143         struct {
144                 struct mutex    ring_lock;
145                 wait_queue_head_t wait;
146         } ____cacheline_aligned_in_smp;
147
148         struct {
149                 unsigned        tail;
150                 unsigned        completed_events;
151                 spinlock_t      completion_lock;
152         } ____cacheline_aligned_in_smp;
153
154         struct page             *internal_pages[AIO_RING_PAGES];
155         struct file             *aio_ring_file;
156
157         unsigned                id;
158         struct mm_struct        *mm;
159 };
160
161 struct aio_kiocb;
162 typedef long (*aio_thread_work_fn_t)(struct aio_kiocb *iocb);
163
164 /*
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
168  * userspace).
169  *
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().
174  */
175 #define KIOCB_CANCELLED         ((void *) (~0ULL))
176
177 struct aio_kiocb {
178         struct kiocb            common;
179
180         struct kioctx           *ki_ctx;
181         kiocb_cancel_fn         *ki_cancel;
182
183         struct iocb __user      *ki_user_iocb;  /* user's aiocb */
184         __u64                   ki_user_data;   /* user's data for completion */
185
186         struct list_head        ki_list;        /* the aio core uses this
187                                                  * for cancellation */
188
189         /*
190          * If the aio_resfd field of the userspace iocb is not zero,
191          * this is the underlying eventfd context to deliver events to.
192          */
193         struct eventfd_ctx      *ki_eventfd;
194
195         struct iov_iter         ki_iter;
196         struct iovec            *ki_iovec;
197         struct iovec            ki_inline_vecs[UIO_FASTIOV];
198
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;
207 #endif
208 };
209
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 */
216 #endif
217 /*----end sysctl variables---*/
218
219 static struct kmem_cache        *kiocb_cachep;
220 static struct kmem_cache        *kioctx_cachep;
221
222 static struct vfsmount *aio_mnt;
223
224 static const struct file_operations aio_ring_fops;
225 static const struct address_space_operations aio_ctx_aops;
226
227 static void aio_complete(struct kiocb *kiocb, long res, long res2);
228
229 static struct file *aio_private_file(struct kioctx *ctx, loff_t nr_pages)
230 {
231         struct qstr this = QSTR_INIT("[aio]", 5);
232         struct file *file;
233         struct path path;
234         struct inode *inode = alloc_anon_inode(aio_mnt->mnt_sb);
235         if (IS_ERR(inode))
236                 return ERR_CAST(inode);
237
238         inode->i_mapping->a_ops = &aio_ctx_aops;
239         inode->i_mapping->private_data = ctx;
240         inode->i_size = PAGE_SIZE * nr_pages;
241
242         path.dentry = d_alloc_pseudo(aio_mnt->mnt_sb, &this);
243         if (!path.dentry) {
244                 iput(inode);
245                 return ERR_PTR(-ENOMEM);
246         }
247         path.mnt = mntget(aio_mnt);
248
249         d_instantiate(path.dentry, inode);
250         file = alloc_file(&path, FMODE_READ | FMODE_WRITE, &aio_ring_fops);
251         if (IS_ERR(file)) {
252                 path_put(&path);
253                 return file;
254         }
255
256         file->f_flags = O_RDWR;
257         return file;
258 }
259
260 static struct dentry *aio_mount(struct file_system_type *fs_type,
261                                 int flags, const char *dev_name, void *data)
262 {
263         static const struct dentry_operations ops = {
264                 .d_dname        = simple_dname,
265         };
266         return mount_pseudo(fs_type, "aio:", NULL, &ops, AIO_RING_MAGIC);
267 }
268
269 /* aio_setup
270  *      Creates the slab caches used by the aio routines, panic on
271  *      failure as this is done early during the boot sequence.
272  */
273 static int __init aio_setup(void)
274 {
275         static struct file_system_type aio_fs = {
276                 .name           = "aio",
277                 .mount          = aio_mount,
278                 .kill_sb        = kill_anon_super,
279         };
280         aio_mnt = kern_mount(&aio_fs);
281         if (IS_ERR(aio_mnt))
282                 panic("Failed to create aio fs mount.");
283
284         kiocb_cachep = KMEM_CACHE(aio_kiocb, SLAB_HWCACHE_ALIGN|SLAB_PANIC);
285         kioctx_cachep = KMEM_CACHE(kioctx,SLAB_HWCACHE_ALIGN|SLAB_PANIC);
286
287         pr_debug("sizeof(struct page) = %zu\n", sizeof(struct page));
288
289         return 0;
290 }
291 __initcall(aio_setup);
292
293 static void put_aio_ring_file(struct kioctx *ctx)
294 {
295         struct file *aio_ring_file = ctx->aio_ring_file;
296         if (aio_ring_file) {
297                 truncate_setsize(aio_ring_file->f_inode, 0);
298
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);
304
305                 fput(aio_ring_file);
306         }
307 }
308
309 static void aio_free_ring(struct kioctx *ctx)
310 {
311         int i;
312
313         /* Disconnect the kiotx from the ring file.  This prevents future
314          * accesses to the kioctx from page migration.
315          */
316         put_aio_ring_file(ctx);
317
318         for (i = 0; i < ctx->nr_pages; i++) {
319                 struct page *page;
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];
323                 if (!page)
324                         continue;
325                 ctx->ring_pages[i] = NULL;
326                 put_page(page);
327         }
328
329         if (ctx->ring_pages && ctx->ring_pages != ctx->internal_pages) {
330                 kfree(ctx->ring_pages);
331                 ctx->ring_pages = NULL;
332         }
333 }
334
335 static int aio_ring_mremap(struct vm_area_struct *vma)
336 {
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;
341
342         spin_lock(&mm->ioctx_lock);
343         rcu_read_lock();
344         table = rcu_dereference(mm->ioctx_table);
345         for (i = 0; i < table->nr; i++) {
346                 struct kioctx *ctx;
347
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;
352                                 res = 0;
353                         }
354                         break;
355                 }
356         }
357
358         rcu_read_unlock();
359         spin_unlock(&mm->ioctx_lock);
360         return res;
361 }
362
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,
369 #endif
370 };
371
372 static int aio_ring_mmap(struct file *file, struct vm_area_struct *vma)
373 {
374         vma->vm_flags |= VM_DONTEXPAND;
375         vma->vm_ops = &aio_ring_vm_ops;
376         return 0;
377 }
378
379 static const struct file_operations aio_ring_fops = {
380         .mmap = aio_ring_mmap,
381 };
382
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)
386 {
387         struct kioctx *ctx;
388         unsigned long flags;
389         pgoff_t idx;
390         int rc;
391
392         rc = 0;
393
394         /* mapping->private_lock here protects against the kioctx teardown.  */
395         spin_lock(&mapping->private_lock);
396         ctx = mapping->private_data;
397         if (!ctx) {
398                 rc = -EINVAL;
399                 goto out;
400         }
401
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.
405          */
406         if (!mutex_trylock(&ctx->ring_lock)) {
407                 rc = -EAGAIN;
408                 goto out;
409         }
410
411         idx = old->index;
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)
415                         rc = -EAGAIN;
416         } else
417                 rc = -EINVAL;
418
419         if (rc != 0)
420                 goto out_unlock;
421
422         /* Writeback must be complete */
423         BUG_ON(PageWriteback(old));
424         get_page(new);
425
426         rc = migrate_page_move_mapping(mapping, new, old, NULL, mode, 1);
427         if (rc != MIGRATEPAGE_SUCCESS) {
428                 put_page(new);
429                 goto out_unlock;
430         }
431
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.
435          */
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);
441
442         /* The old page is no longer accessible. */
443         put_page(old);
444
445 out_unlock:
446         mutex_unlock(&ctx->ring_lock);
447 out:
448         spin_unlock(&mapping->private_lock);
449         return rc;
450 }
451 #endif
452
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,
457 #endif
458 };
459
460 static int aio_setup_ring(struct kioctx *ctx)
461 {
462         struct aio_ring *ring;
463         unsigned nr_events = ctx->max_reqs;
464         struct mm_struct *mm = current->mm;
465         unsigned long size, unused;
466         int nr_pages;
467         int i;
468         struct file *file;
469
470         /* Compensate for the ring buffer's head/tail overlap entry */
471         nr_events += 2; /* 1 is required, 2 for good luck */
472
473         size = sizeof(struct aio_ring);
474         size += sizeof(struct io_event) * nr_events;
475
476         nr_pages = PFN_UP(size);
477         if (nr_pages < 0)
478                 return -EINVAL;
479
480         file = aio_private_file(ctx, nr_pages);
481         if (IS_ERR(file)) {
482                 ctx->aio_ring_file = NULL;
483                 return -ENOMEM;
484         }
485
486         ctx->aio_ring_file = file;
487         nr_events = (PAGE_SIZE * nr_pages - sizeof(struct aio_ring))
488                         / sizeof(struct io_event);
489
490         ctx->ring_pages = ctx->internal_pages;
491         if (nr_pages > AIO_RING_PAGES) {
492                 ctx->ring_pages = kcalloc(nr_pages, sizeof(struct page *),
493                                           GFP_KERNEL);
494                 if (!ctx->ring_pages) {
495                         put_aio_ring_file(ctx);
496                         return -ENOMEM;
497                 }
498         }
499
500         for (i = 0; i < nr_pages; i++) {
501                 struct page *page;
502                 page = find_or_create_page(file->f_inode->i_mapping,
503                                            i, GFP_HIGHUSER | __GFP_ZERO);
504                 if (!page)
505                         break;
506                 pr_debug("pid(%d) page[%d]->count=%d\n",
507                          current->pid, i, page_count(page));
508                 SetPageUptodate(page);
509                 unlock_page(page);
510
511                 ctx->ring_pages[i] = page;
512         }
513         ctx->nr_pages = i;
514
515         if (unlikely(i != nr_pages)) {
516                 aio_free_ring(ctx);
517                 return -ENOMEM;
518         }
519
520         ctx->mmap_size = nr_pages * PAGE_SIZE;
521         pr_debug("attempting mmap of %lu bytes\n", ctx->mmap_size);
522
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)) {
529                 ctx->mmap_size = 0;
530                 aio_free_ring(ctx);
531                 return -ENOMEM;
532         }
533
534         pr_debug("mmap address: 0x%08lx\n", ctx->mmap_base);
535
536         ctx->user_id = ctx->mmap_base;
537         ctx->nr_events = nr_events; /* trusted copy */
538
539         ring = kmap_atomic(ctx->ring_pages[0]);
540         ring->nr = nr_events;   /* user copy */
541         ring->id = ~0U;
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;
548 #endif
549         ring->incompat_features = AIO_RING_INCOMPAT_FEATURES;
550         ring->header_length = sizeof(struct aio_ring);
551         kunmap_atomic(ring);
552         flush_dcache_page(ctx->ring_pages[0]);
553
554         return 0;
555 }
556
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)
560
561 void kiocb_set_cancel_fn(struct kiocb *iocb, kiocb_cancel_fn *cancel)
562 {
563         struct aio_kiocb *req = container_of(iocb, struct aio_kiocb, common);
564         struct kioctx *ctx = req->ki_ctx;
565         unsigned long flags;
566
567         spin_lock_irqsave(&ctx->ctx_lock, flags);
568
569         if (!req->ki_list.next)
570                 list_add(&req->ki_list, &ctx->active_reqs);
571
572         req->ki_cancel = cancel;
573
574         spin_unlock_irqrestore(&ctx->ctx_lock, flags);
575 }
576 EXPORT_SYMBOL(kiocb_set_cancel_fn);
577
578 static int kiocb_cancel(struct aio_kiocb *kiocb)
579 {
580         kiocb_cancel_fn *old, *cancel;
581
582         /*
583          * Don't want to set kiocb->ki_cancel = KIOCB_CANCELLED unless it
584          * actually has a cancel function, hence the cmpxchg()
585          */
586
587         cancel = ACCESS_ONCE(kiocb->ki_cancel);
588         do {
589                 if (!cancel || cancel == KIOCB_CANCELLED)
590                         return -EINVAL;
591
592                 old = cancel;
593                 cancel = cmpxchg(&kiocb->ki_cancel, old, KIOCB_CANCELLED);
594         } while (cancel != old);
595
596         return cancel(&kiocb->common);
597 }
598
599 struct mm_struct *aio_get_mm(struct kiocb *req)
600 {
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;
605         }
606         return NULL;
607 }
608
609 struct task_struct *aio_get_task(struct kiocb *req)
610 {
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;
615         }
616         return current;
617 }
618
619 static void free_ioctx(struct work_struct *work)
620 {
621         struct kioctx *ctx = container_of(work, struct kioctx, free_work);
622
623         pr_debug("freeing %p\n", ctx);
624
625         aio_free_ring(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);
630 }
631
632 static void free_ioctx_reqs(struct percpu_ref *ref)
633 {
634         struct kioctx *ctx = container_of(ref, struct kioctx, reqs);
635
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);
639
640         INIT_WORK(&ctx->free_work, free_ioctx);
641         schedule_work(&ctx->free_work);
642 }
643
644 /*
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.
648  */
649 static void free_ioctx_users(struct percpu_ref *ref)
650 {
651         struct kioctx *ctx = container_of(ref, struct kioctx, users);
652         struct aio_kiocb *req;
653
654         spin_lock_irq(&ctx->ctx_lock);
655
656         while (!list_empty(&ctx->active_reqs)) {
657                 req = list_first_entry(&ctx->active_reqs,
658                                        struct aio_kiocb, ki_list);
659
660                 list_del_init(&req->ki_list);
661                 kiocb_cancel(req);
662         }
663
664         spin_unlock_irq(&ctx->ctx_lock);
665
666         percpu_ref_kill(&ctx->reqs);
667         percpu_ref_put(&ctx->reqs);
668 }
669
670 static int ioctx_add_table(struct kioctx *ctx, struct mm_struct *mm)
671 {
672         unsigned i, new_nr;
673         struct kioctx_table *table, *old;
674         struct aio_ring *ring;
675
676         spin_lock(&mm->ioctx_lock);
677         table = rcu_dereference_raw(mm->ioctx_table);
678
679         while (1) {
680                 if (table)
681                         for (i = 0; i < table->nr; i++)
682                                 if (!table->table[i]) {
683                                         ctx->id = i;
684                                         table->table[i] = ctx;
685                                         spin_unlock(&mm->ioctx_lock);
686
687                                         /* While kioctx setup is in progress,
688                                          * we are protected from page migration
689                                          * changes ring_pages by ->ring_lock.
690                                          */
691                                         ring = kmap_atomic(ctx->ring_pages[0]);
692                                         ring->id = ctx->id;
693                                         kunmap_atomic(ring);
694                                         return 0;
695                                 }
696
697                 new_nr = (table ? table->nr : 1) * 4;
698                 spin_unlock(&mm->ioctx_lock);
699
700                 table = kzalloc(sizeof(*table) + sizeof(struct kioctx *) *
701                                 new_nr, GFP_KERNEL);
702                 if (!table)
703                         return -ENOMEM;
704
705                 table->nr = new_nr;
706
707                 spin_lock(&mm->ioctx_lock);
708                 old = rcu_dereference_raw(mm->ioctx_table);
709
710                 if (!old) {
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 *));
715
716                         rcu_assign_pointer(mm->ioctx_table, table);
717                         kfree_rcu(old, rcu);
718                 } else {
719                         kfree(table);
720                         table = old;
721                 }
722         }
723 }
724
725 static void aio_nr_sub(unsigned nr)
726 {
727         spin_lock(&aio_nr_lock);
728         if (WARN_ON(aio_nr - nr > aio_nr))
729                 aio_nr = 0;
730         else
731                 aio_nr -= nr;
732         spin_unlock(&aio_nr_lock);
733 }
734
735 /* ioctx_alloc
736  *      Allocates and initializes an ioctx.  Returns an ERR_PTR if it failed.
737  */
738 static struct kioctx *ioctx_alloc(unsigned nr_events)
739 {
740         struct mm_struct *mm = current->mm;
741         struct kioctx *ctx;
742         int err = -ENOMEM;
743
744         /*
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.
747          *
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:
752          */
753         nr_events = max(nr_events, num_possible_cpus() * 4);
754         nr_events *= 2;
755
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);
760         }
761
762         if (!nr_events || (unsigned long)nr_events > (aio_max_nr * 2UL))
763                 return ERR_PTR(-EAGAIN);
764
765         ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL);
766         if (!ctx)
767                 return ERR_PTR(-ENOMEM);
768
769         ctx->max_reqs = nr_events;
770         ctx->mm = mm;
771
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);
779
780         INIT_LIST_HEAD(&ctx->active_reqs);
781
782         if (percpu_ref_init(&ctx->users, free_ioctx_users, 0, GFP_KERNEL))
783                 goto err;
784
785         if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs, 0, GFP_KERNEL))
786                 goto err;
787
788         ctx->cpu = alloc_percpu(struct kioctx_cpu);
789         if (!ctx->cpu)
790                 goto err;
791
792         err = aio_setup_ring(ctx);
793         if (err < 0)
794                 goto err;
795
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)
799                 ctx->req_batch = 1;
800
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);
806                 err = -EAGAIN;
807                 goto err_ctx;
808         }
809         aio_nr += ctx->max_reqs;
810         spin_unlock(&aio_nr_lock);
811
812         percpu_ref_get(&ctx->users);    /* io_setup() will drop this ref */
813         percpu_ref_get(&ctx->reqs);     /* free_ioctx_users() will drop this */
814
815         err = ioctx_add_table(ctx, mm);
816         if (err)
817                 goto err_cleanup;
818
819         /* Release the ring_lock mutex now that all setup is complete. */
820         mutex_unlock(&ctx->ring_lock);
821
822         pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
823                  ctx, ctx->user_id, mm, ctx->nr_events);
824         return ctx;
825
826 err_cleanup:
827         aio_nr_sub(ctx->max_reqs);
828 err_ctx:
829         atomic_set(&ctx->dead, 1);
830         if (ctx->mmap_size)
831                 vm_munmap(ctx->mmap_base, ctx->mmap_size);
832         aio_free_ring(ctx);
833 err:
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);
840         return ERR_PTR(err);
841 }
842
843 /* kill_ioctx
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.
847  */
848 static int kill_ioctx(struct mm_struct *mm, struct kioctx *ctx,
849                       struct ctx_rq_wait *wait)
850 {
851         struct kioctx_table *table;
852
853         spin_lock(&mm->ioctx_lock);
854         if (atomic_xchg(&ctx->dead, 1)) {
855                 spin_unlock(&mm->ioctx_lock);
856                 return -EINVAL;
857         }
858
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);
863
864         /* percpu_ref_kill() will do the necessary call_rcu() */
865         wake_up_all(&ctx->wait);
866
867         /*
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
872          *  could tell).
873          */
874         aio_nr_sub(ctx->max_reqs);
875
876         if (ctx->mmap_size)
877                 vm_munmap(ctx->mmap_base, ctx->mmap_size);
878
879         ctx->rq_wait = wait;
880         percpu_ref_kill(&ctx->users);
881         return 0;
882 }
883
884 /*
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.
888  *
889  * There may be outstanding kiocbs, but free_ioctx() will explicitly wait on
890  * them.
891  */
892 void exit_aio(struct mm_struct *mm)
893 {
894         struct kioctx_table *table = rcu_dereference_raw(mm->ioctx_table);
895         struct ctx_rq_wait wait;
896         int i, skipped;
897
898         if (!table)
899                 return;
900
901         atomic_set(&wait.count, table->nr);
902         init_completion(&wait.comp);
903
904         skipped = 0;
905         for (i = 0; i < table->nr; ++i) {
906                 struct kioctx *ctx = table->table[i];
907
908                 if (!ctx) {
909                         skipped++;
910                         continue;
911                 }
912
913                 /*
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.
919                  */
920                 ctx->mmap_size = 0;
921                 kill_ioctx(mm, ctx, &wait);
922         }
923
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);
927         }
928
929         RCU_INIT_POINTER(mm->ioctx_table, NULL);
930         kfree(table);
931 }
932
933 static void put_reqs_available(struct kioctx *ctx, unsigned nr)
934 {
935         struct kioctx_cpu *kcpu;
936         unsigned long flags;
937
938         local_irq_save(flags);
939         kcpu = this_cpu_ptr(ctx->cpu);
940         kcpu->reqs_available += nr;
941
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);
945         }
946
947         local_irq_restore(flags);
948 }
949
950 static bool get_reqs_available(struct kioctx *ctx)
951 {
952         struct kioctx_cpu *kcpu;
953         bool ret = false;
954         unsigned long flags;
955
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);
960
961                 do {
962                         if (avail < ctx->req_batch)
963                                 goto out;
964
965                         old = avail;
966                         avail = atomic_cmpxchg(&ctx->reqs_available,
967                                                avail, avail - ctx->req_batch);
968                 } while (avail != old);
969
970                 kcpu->reqs_available += ctx->req_batch;
971         }
972
973         ret = true;
974         kcpu->reqs_available--;
975 out:
976         local_irq_restore(flags);
977         return ret;
978 }
979
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.
986  */
987 static void refill_reqs_available(struct kioctx *ctx, unsigned head,
988                                   unsigned tail)
989 {
990         unsigned events_in_ring, completed;
991
992         /* Clamp head since userland can write to it. */
993         head %= ctx->nr_events;
994         if (head <= tail)
995                 events_in_ring = tail - head;
996         else
997                 events_in_ring = ctx->nr_events - (head - tail);
998
999         completed = ctx->completed_events;
1000         if (events_in_ring < completed)
1001                 completed -= events_in_ring;
1002         else
1003                 completed = 0;
1004
1005         if (!completed)
1006                 return;
1007
1008         ctx->completed_events -= completed;
1009         put_reqs_available(ctx, completed);
1010 }
1011
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.
1015  */
1016 static void user_refill_reqs_available(struct kioctx *ctx)
1017 {
1018         spin_lock_irq(&ctx->completion_lock);
1019         if (ctx->completed_events) {
1020                 struct aio_ring *ring;
1021                 unsigned head;
1022
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
1030                  * safe/right thing.
1031                  */
1032                 ring = kmap_atomic(ctx->ring_pages[0]);
1033                 head = ring->head;
1034                 kunmap_atomic(ring);
1035
1036                 refill_reqs_available(ctx, head, ctx->tail);
1037         }
1038
1039         spin_unlock_irq(&ctx->completion_lock);
1040 }
1041
1042 /* aio_get_req
1043  *      Allocate a slot for an aio request.
1044  * Returns NULL if no requests are free.
1045  */
1046 static inline struct aio_kiocb *aio_get_req(struct kioctx *ctx)
1047 {
1048         struct aio_kiocb *req;
1049
1050         if (!get_reqs_available(ctx)) {
1051                 user_refill_reqs_available(ctx);
1052                 if (!get_reqs_available(ctx))
1053                         return NULL;
1054         }
1055
1056         req = kmem_cache_alloc(kiocb_cachep, GFP_KERNEL|__GFP_ZERO);
1057         if (unlikely(!req))
1058                 goto out_put;
1059
1060         percpu_ref_get(&ctx->reqs);
1061
1062         req->ki_ctx = ctx;
1063         req->ki_iovec = req->ki_inline_vecs;
1064         return req;
1065 out_put:
1066         put_reqs_available(ctx, 1);
1067         return NULL;
1068 }
1069
1070 static void kiocb_free(struct aio_kiocb *req)
1071 {
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);
1081 }
1082
1083 static struct kioctx *lookup_ioctx(unsigned long ctx_id)
1084 {
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;
1089         unsigned id;
1090
1091         if (get_user(id, &ring->id))
1092                 return NULL;
1093
1094         rcu_read_lock();
1095         table = rcu_dereference(mm->ioctx_table);
1096
1097         if (!table || id >= table->nr)
1098                 goto out;
1099
1100         ctx = table->table[id];
1101         if (ctx && ctx->user_id == ctx_id) {
1102                 percpu_ref_get(&ctx->users);
1103                 ret = ctx;
1104         }
1105 out:
1106         rcu_read_unlock();
1107         return ret;
1108 }
1109
1110 /* aio_complete
1111  *      Called when the io request on the given iocb is complete.
1112  */
1113 static void aio_complete(struct kiocb *kiocb, long res, long res2)
1114 {
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;
1121
1122         /*
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
1128          */
1129         BUG_ON(is_sync_kiocb(kiocb));
1130
1131         if (iocb->ki_list.next) {
1132                 unsigned long flags;
1133
1134                 spin_lock_irqsave(&ctx->ctx_lock, flags);
1135                 list_del(&iocb->ki_list);
1136                 spin_unlock_irqrestore(&ctx->ctx_lock, flags);
1137         }
1138
1139         /*
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.
1143          */
1144         spin_lock_irqsave(&ctx->completion_lock, flags);
1145
1146         tail = ctx->tail;
1147         pos = tail + AIO_EVENTS_OFFSET;
1148
1149         if (++tail >= ctx->nr_events)
1150                 tail = 0;
1151
1152         ev_page = kmap_atomic(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
1153         event = ev_page + pos % AIO_EVENTS_PER_PAGE;
1154
1155         event->obj = (u64)(unsigned long)iocb->ki_user_iocb;
1156         event->data = iocb->ki_user_data;
1157         event->res = res;
1158         event->res2 = res2;
1159
1160         kunmap_atomic(ev_page);
1161         flush_dcache_page(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
1162
1163         pr_debug("%p[%u]: %p: %p %Lx %lx %lx\n",
1164                  ctx, tail, iocb, iocb->ki_user_iocb, iocb->ki_user_data,
1165                  res, res2);
1166
1167         /* after flagging the request as done, we
1168          * must never even look at it again
1169          */
1170         smp_wmb();      /* make event visible before updating tail */
1171
1172         ctx->tail = tail;
1173
1174         ring = kmap_atomic(ctx->ring_pages[0]);
1175         head = ring->head;
1176         ring->tail = tail;
1177         kunmap_atomic(ring);
1178         flush_dcache_page(ctx->ring_pages[0]);
1179
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);
1184
1185         pr_debug("added to ring %p at [%u]\n", iocb, tail);
1186
1187         /*
1188          * Check if the user asked us to deliver the result through an
1189          * eventfd. The eventfd_signal() function is safe to be called
1190          * from IRQ context.
1191          */
1192         if (iocb->ki_eventfd != NULL)
1193                 eventfd_signal(iocb->ki_eventfd, 1);
1194
1195         /* everything turned out well, dispose of the aiocb. */
1196         kiocb_free(iocb);
1197
1198         /*
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.
1203          */
1204         smp_mb();
1205
1206         if (waitqueue_active(&ctx->wait))
1207                 wake_up(&ctx->wait);
1208
1209         percpu_ref_put(&ctx->reqs);
1210 }
1211
1212 /* aio_read_events_ring
1213  *      Pull an event off of the ioctx's event ring.  Returns the number of
1214  *      events fetched
1215  */
1216 static long aio_read_events_ring(struct kioctx *ctx,
1217                                  struct io_event __user *event, long nr)
1218 {
1219         struct aio_ring *ring;
1220         unsigned head, tail, pos;
1221         long ret = 0;
1222         int copy_ret;
1223
1224         /*
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.
1229          */
1230         sched_annotate_sleep();
1231         mutex_lock(&ctx->ring_lock);
1232
1233         /* Access to ->ring_pages here is protected by ctx->ring_lock. */
1234         ring = kmap_atomic(ctx->ring_pages[0]);
1235         head = ring->head;
1236         tail = ring->tail;
1237         kunmap_atomic(ring);
1238
1239         /*
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.
1242          */
1243         smp_rmb();
1244
1245         pr_debug("h%u t%u m%u\n", head, tail, ctx->nr_events);
1246
1247         if (head == tail)
1248                 goto out;
1249
1250         head %= ctx->nr_events;
1251         tail %= ctx->nr_events;
1252
1253         while (ret < nr) {
1254                 long avail;
1255                 struct io_event *ev;
1256                 struct page *page;
1257
1258                 avail = (head <= tail ?  tail : ctx->nr_events) - head;
1259                 if (head == tail)
1260                         break;
1261
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));
1265
1266                 pos = head + AIO_EVENTS_OFFSET;
1267                 page = ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE];
1268                 pos %= AIO_EVENTS_PER_PAGE;
1269
1270                 ev = kmap(page);
1271                 copy_ret = copy_to_user(event + ret, ev + pos,
1272                                         sizeof(*ev) * avail);
1273                 kunmap(page);
1274
1275                 if (unlikely(copy_ret)) {
1276                         ret = -EFAULT;
1277                         goto out;
1278                 }
1279
1280                 ret += avail;
1281                 head += avail;
1282                 head %= ctx->nr_events;
1283         }
1284
1285         ring = kmap_atomic(ctx->ring_pages[0]);
1286         ring->head = head;
1287         kunmap_atomic(ring);
1288         flush_dcache_page(ctx->ring_pages[0]);
1289
1290         pr_debug("%li  h%u t%u\n", ret, head, tail);
1291 out:
1292         mutex_unlock(&ctx->ring_lock);
1293
1294         return ret;
1295 }
1296
1297 static bool aio_read_events(struct kioctx *ctx, long min_nr, long nr,
1298                             struct io_event __user *event, long *i)
1299 {
1300         long ret = aio_read_events_ring(ctx, event + *i, nr - *i);
1301
1302         if (ret > 0)
1303                 *i += ret;
1304
1305         if (unlikely(atomic_read(&ctx->dead)))
1306                 ret = -EINVAL;
1307
1308         if (!*i)
1309                 *i = ret;
1310
1311         return ret < 0 || *i >= min_nr;
1312 }
1313
1314 static long read_events(struct kioctx *ctx, long min_nr, long nr,
1315                         struct io_event __user *event,
1316                         struct timespec __user *timeout)
1317 {
1318         ktime_t until = { .tv64 = KTIME_MAX };
1319         long ret = 0;
1320
1321         if (timeout) {
1322                 struct timespec ts;
1323
1324                 if (unlikely(copy_from_user(&ts, timeout, sizeof(ts))))
1325                         return -EFAULT;
1326                 if (!timespec_valid(&ts))
1327                         return -EINVAL;
1328
1329                 until = timespec_to_ktime(ts);
1330         }
1331
1332         /*
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.
1336          *
1337          * But aio_read_events() can block, and if it blocks it's going to flip
1338          * the task state back to TASK_RUNNING.
1339          *
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.
1345          */
1346         if (until.tv64 == 0)
1347                 aio_read_events(ctx, min_nr, nr, event, &ret);
1348         else
1349                 wait_event_interruptible_hrtimeout(ctx->wait,
1350                                 aio_read_events(ctx, min_nr, nr, event, &ret),
1351                                 until);
1352
1353         if (!ret && signal_pending(current))
1354                 ret = -EINTR;
1355
1356         return ret;
1357 }
1358
1359 /* sys_io_setup:
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
1370  *      implemented.
1371  */
1372 SYSCALL_DEFINE2(io_setup, unsigned, nr_events, aio_context_t __user *, ctxp)
1373 {
1374         struct kioctx *ioctx = NULL;
1375         unsigned long ctx;
1376         long ret;
1377
1378         ret = get_user(ctx, ctxp);
1379         if (unlikely(ret))
1380                 goto out;
1381
1382         ret = -EINVAL;
1383         if (unlikely(ctx || nr_events == 0)) {
1384                 pr_debug("EINVAL: ctx %lu nr_events %u\n",
1385                          ctx, nr_events);
1386                 goto out;
1387         }
1388
1389         ioctx = ioctx_alloc(nr_events);
1390         ret = PTR_ERR(ioctx);
1391         if (!IS_ERR(ioctx)) {
1392                 ret = put_user(ioctx->user_id, ctxp);
1393                 if (ret)
1394                         kill_ioctx(current->mm, ioctx, NULL);
1395                 percpu_ref_put(&ioctx->users);
1396         }
1397
1398 out:
1399         return ret;
1400 }
1401
1402 /* sys_io_destroy:
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
1406  *      is invalid.
1407  */
1408 SYSCALL_DEFINE1(io_destroy, aio_context_t, ctx)
1409 {
1410         struct kioctx *ioctx = lookup_ioctx(ctx);
1411         if (likely(NULL != ioctx)) {
1412                 struct ctx_rq_wait wait;
1413                 int ret;
1414
1415                 init_completion(&wait.comp);
1416                 atomic_set(&wait.count, 1);
1417
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.
1421                  */
1422                 ret = kill_ioctx(current->mm, ioctx, &wait);
1423                 percpu_ref_put(&ioctx->users);
1424
1425                 /* Wait until all IO for the context are done. Otherwise kernel
1426                  * keep using user-space buffers even if user thinks the context
1427                  * is destroyed.
1428                  */
1429                 if (!ret)
1430                         wait_for_completion(&wait.comp);
1431
1432                 return ret;
1433         }
1434         pr_debug("EINVAL: invalid context id\n");
1435         return -EINVAL;
1436 }
1437
1438 typedef ssize_t (rw_iter_op)(struct kiocb *, struct iov_iter *);
1439
1440 static int aio_setup_vectored_rw(int rw, char __user *buf, size_t len,
1441                                  struct iovec **iovec,
1442                                  bool compat,
1443                                  struct iov_iter *iter)
1444 {
1445 #ifdef CONFIG_COMPAT
1446         if (compat)
1447                 return compat_import_iovec(rw,
1448                                 (struct compat_iovec __user *)buf,
1449                                 len, UIO_FASTIOV, iovec, iter);
1450 #endif
1451         return import_iovec(rw, (struct iovec __user *)buf,
1452                                 len, UIO_FASTIOV, iovec, iter);
1453 }
1454
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.
1459  */
1460 static int aio_thread_queue_iocb_cancel_early(struct kiocb *iocb)
1461 {
1462         return 0;
1463 }
1464
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.
1469  */
1470 static int aio_thread_queue_iocb_cancel(struct kiocb *kiocb)
1471 {
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);
1475                 return 0;
1476         }
1477         return -EAGAIN;
1478 }
1479
1480 /* aio_thread_fn:
1481  *      Entry point for worker to perform threaded aio.  Handles issues
1482  *      arising due to cancellation using signals.
1483  */
1484 static void aio_thread_fn(struct work_struct *work)
1485 {
1486         struct aio_kiocb *iocb = container_of(work, struct aio_kiocb, ki_work);
1487         kiocb_cancel_fn *old_cancel;
1488         long ret;
1489
1490         iocb->ki_cancel_task = current;
1491         current->kiocb = &iocb->common;         /* For io_send_sig(). */
1492         BUG_ON(atomic_read(&current->signal->sigcnt) != 1);
1493
1494         /* Check for early stage cancellation and switch to late stage
1495          * cancellation if it has not already occurred.
1496          */
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);
1502         else
1503                 ret = -EINTR;
1504
1505         current->kiocb = NULL;
1506         if (unlikely(ret == -ERESTARTSYS || ret == -ERESTARTNOINTR ||
1507                      ret == -ERESTARTNOHAND || ret == -ERESTART_RESTARTBLOCK))
1508                 ret = -EINTR;
1509
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.
1514          */
1515         aio_complete(&iocb->common, ret, 0);
1516         if (fatal_signal_pending(current))
1517                 flush_signals(current);
1518 }
1519
1520 #define AIO_THREAD_NEED_TASK    0x0001  /* Need aio_kiocb->ki_submit_task */
1521
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.
1527  */
1528 static ssize_t aio_thread_queue_iocb(struct aio_kiocb *iocb,
1529                                      aio_thread_work_fn_t work_fn,
1530                                      unsigned flags)
1531 {
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);
1537         }
1538
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
1543          * ki_cancel.
1544          */
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;
1548 }
1549
1550 static long aio_thread_op_read_iter(struct aio_kiocb *iocb)
1551 {
1552         struct file *filp;
1553         long ret;
1554
1555         use_mm(iocb->ki_ctx->mm);
1556         filp = iocb->common.ki_filp;
1557
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,
1566                                            filp->f_op->read);
1567         else
1568                 ret = -EINVAL;
1569         unuse_mm(iocb->ki_ctx->mm);
1570         return ret;
1571 }
1572
1573 ssize_t generic_async_read_iter_non_direct(struct kiocb *iocb,
1574                                            struct iov_iter *iter)
1575 {
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);
1580 }
1581 EXPORT_SYMBOL(generic_async_read_iter_non_direct);
1582
1583 ssize_t generic_async_read_iter(struct kiocb *iocb, struct iov_iter *iter)
1584 {
1585         struct aio_kiocb *req;
1586
1587         req = container_of(iocb, struct aio_kiocb, common);
1588         BUG_ON(iter != &req->ki_iter);
1589
1590         return aio_thread_queue_iocb(req, aio_thread_op_read_iter,
1591                                      AIO_THREAD_NEED_TASK);
1592 }
1593 EXPORT_SYMBOL(generic_async_read_iter);
1594
1595 static long aio_thread_op_write_iter(struct aio_kiocb *iocb)
1596 {
1597         u64 saved_rlim_fsize;
1598         struct file *filp;
1599         long ret;
1600
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;
1605
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);
1615         else
1616                 ret = -EINVAL;
1617         current->signal->rlim[RLIMIT_FSIZE].rlim_cur = saved_rlim_fsize;
1618         unuse_mm(iocb->ki_ctx->mm);
1619         return ret;
1620 }
1621
1622 ssize_t generic_async_write_iter_non_direct(struct kiocb *iocb,
1623                                             struct iov_iter *iter)
1624 {
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);
1629 }
1630 EXPORT_SYMBOL(generic_async_write_iter_non_direct);
1631
1632 ssize_t generic_async_write_iter(struct kiocb *iocb, struct iov_iter *iter)
1633 {
1634         struct aio_kiocb *req;
1635
1636         req = container_of(iocb, struct aio_kiocb, common);
1637         BUG_ON(iter != &req->ki_iter);
1638         req->ki_rlimit_fsize = rlimit(RLIMIT_FSIZE);
1639
1640         return aio_thread_queue_iocb(req, aio_thread_op_write_iter,
1641                                      AIO_THREAD_NEED_TASK);
1642 }
1643 EXPORT_SYMBOL(generic_async_write_iter);
1644
1645 static long aio_thread_op_fsync(struct aio_kiocb *iocb)
1646 {
1647         return vfs_fsync(iocb->common.ki_filp, 0);
1648 }
1649
1650 static long aio_thread_op_fdatasync(struct aio_kiocb *iocb)
1651 {
1652         return vfs_fsync(iocb->common.ki_filp, 1);
1653 }
1654
1655 ssize_t generic_async_fsync(struct kiocb *iocb, int datasync)
1656 {
1657         struct aio_kiocb *req;
1658
1659         BUG_ON(iocb->ki_complete != aio_complete);
1660         req = container_of(iocb, struct aio_kiocb, common);
1661
1662         return aio_thread_queue_iocb(req, datasync ? aio_thread_op_fdatasync
1663                                                    : aio_thread_op_fsync, 0);
1664 }
1665 EXPORT_SYMBOL(generic_async_fsync);
1666
1667 static long aio_thread_op_poll(struct aio_kiocb *iocb)
1668 {
1669         struct file *file = iocb->common.ki_filp;
1670         short events = iocb->ki_data;
1671         struct poll_wqueues table;
1672         unsigned int mask;
1673         ssize_t ret = 0;
1674
1675         poll_initwait(&table);
1676         events |= POLLERR | POLLHUP;
1677
1678         for (;;) {
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);
1683                 }
1684                 /* Mask out unneeded events. */
1685                 mask &= events;
1686                 ret = mask;
1687                 if (mask)
1688                         break;
1689
1690                 ret = -EINTR;
1691                 if (signal_pending(current))
1692                         break;
1693
1694                 poll_schedule_timeout(&table, TASK_INTERRUPTIBLE, NULL, 0);
1695         }
1696
1697         poll_freewait(&table);
1698         return ret;
1699 }
1700 #endif /* IS_ENABLED(CONFIG_AIO_THREAD) */
1701
1702 /*
1703  * aio_run_iocb:
1704  *      Performs the initial checks and io submission.
1705  */
1706 static ssize_t aio_run_iocb(struct aio_kiocb *req, unsigned opcode,
1707                             char __user *buf, size_t len, bool compat)
1708 {
1709         struct file *file = req->common.ki_filp;
1710         ssize_t ret = -EINVAL;
1711         int rw;
1712         fmode_t mode;
1713         rw_iter_op *iter_op;
1714
1715         switch (opcode) {
1716         case IOCB_CMD_PREAD:
1717         case IOCB_CMD_PREADV:
1718                 mode    = FMODE_READ;
1719                 rw      = READ;
1720                 iter_op = file->f_op->async_read_iter;
1721                 if (iter_op)
1722                         goto rw_common;
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;
1727                         goto rw_common;
1728                 }
1729 #endif
1730                 iter_op = file->f_op->read_iter;
1731                 goto rw_common;
1732
1733         case IOCB_CMD_PWRITE:
1734         case IOCB_CMD_PWRITEV:
1735                 mode    = FMODE_WRITE;
1736                 rw      = WRITE;
1737                 iter_op = file->f_op->async_write_iter;
1738                 if (iter_op)
1739                         goto rw_common;
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;
1744                         goto rw_common;
1745                 }
1746 #endif
1747                 iter_op = file->f_op->write_iter;
1748                 goto rw_common;
1749 rw_common:
1750                 if (unlikely(!(file->f_mode & mode)))
1751                         return -EBADF;
1752
1753                 if (!iter_op)
1754                         return -EINVAL;
1755
1756                 if (opcode == IOCB_CMD_PREADV || opcode == IOCB_CMD_PWRITEV)
1757                         ret = aio_setup_vectored_rw(rw, buf, len,
1758                                                     &req->ki_iovec, compat,
1759                                                     &req->ki_iter);
1760                 else {
1761                         ret = import_single_range(rw, buf, len, req->ki_iovec,
1762                                                   &req->ki_iter);
1763                 }
1764                 if (!ret)
1765                         ret = rw_verify_area(rw, file, &req->common.ki_pos,
1766                                              iov_iter_count(&req->ki_iter));
1767                 if (ret < 0)
1768                         return ret;
1769
1770                 if (rw == WRITE)
1771                         file_start_write(file);
1772
1773                 ret = iter_op(&req->common, &req->ki_iter);
1774
1775                 if (rw == WRITE)
1776                         file_end_write(file);
1777                 break;
1778
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);
1785 #endif
1786                 break;
1787
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);
1794 #endif
1795                 break;
1796
1797         case IOCB_CMD_POLL:
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);
1801 #endif
1802                 break;
1803
1804         default:
1805                 pr_debug("EINVAL: no operation provided\n");
1806                 break;
1807         }
1808
1809         if (ret != -EIOCBQUEUED) {
1810                 /*
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.
1813                  */
1814                 if (unlikely(ret == -ERESTARTSYS || ret == -ERESTARTNOINTR ||
1815                              ret == -ERESTARTNOHAND ||
1816                              ret == -ERESTART_RESTARTBLOCK))
1817                         ret = -EINTR;
1818                 aio_complete(&req->common, ret, 0);
1819         }
1820
1821         return 0;
1822 }
1823
1824 static int io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb,
1825                          struct iocb *iocb, bool compat)
1826 {
1827         struct aio_kiocb *req;
1828         ssize_t ret;
1829
1830         /* enforce forwards compatibility on users */
1831         if (unlikely(iocb->aio_reserved1 || iocb->aio_reserved2)) {
1832                 pr_debug("EINVAL: reserve field set\n");
1833                 return -EINVAL;
1834         }
1835
1836         /* prevent overflows */
1837         if (unlikely(
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)
1841            )) {
1842                 pr_debug("EINVAL: overflow check\n");
1843                 return -EINVAL;
1844         }
1845
1846         req = aio_get_req(ctx);
1847         if (unlikely(!req))
1848                 return -EAGAIN;
1849
1850         req->common.ki_filp = fget(iocb->aio_fildes);
1851         if (unlikely(!req->common.ki_filp)) {
1852                 ret = -EBADF;
1853                 goto out_put_req;
1854         }
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);
1858
1859         if (iocb->aio_flags & IOCB_FLAG_RESFD) {
1860                 /*
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.
1865                  */
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;
1870                         goto out_put_req;
1871                 }
1872
1873                 req->common.ki_flags |= IOCB_EVENTFD;
1874         }
1875
1876         ret = put_user(KIOCB_KEY, &user_iocb->aio_key);
1877         if (unlikely(ret)) {
1878                 pr_debug("EFAULT: aio_key\n");
1879                 goto out_put_req;
1880         }
1881
1882         req->ki_user_iocb = user_iocb;
1883         req->ki_user_data = iocb->aio_data;
1884
1885         ret = aio_run_iocb(req, iocb->aio_lio_opcode,
1886                            (char __user *)(unsigned long)iocb->aio_buf,
1887                            iocb->aio_nbytes,
1888                            compat);
1889         if (ret)
1890                 goto out_put_req;
1891
1892         return 0;
1893 out_put_req:
1894         put_reqs_available(ctx, 1);
1895         percpu_ref_put(&ctx->reqs);
1896         kiocb_free(req);
1897         return ret;
1898 }
1899
1900 long do_io_submit(aio_context_t ctx_id, long nr,
1901                   struct iocb __user *__user *iocbpp, bool compat)
1902 {
1903         struct kioctx *ctx;
1904         long ret = 0;
1905         int i = 0;
1906         struct blk_plug plug;
1907
1908         if (unlikely(nr < 0))
1909                 return -EINVAL;
1910
1911         if (unlikely(nr > LONG_MAX/sizeof(*iocbpp)))
1912                 nr = LONG_MAX/sizeof(*iocbpp);
1913
1914         if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))
1915                 return -EFAULT;
1916
1917         ctx = lookup_ioctx(ctx_id);
1918         if (unlikely(!ctx)) {
1919                 pr_debug("EINVAL: invalid context id\n");
1920                 return -EINVAL;
1921         }
1922
1923         blk_start_plug(&plug);
1924
1925         /*
1926          * AKPM: should this return a partial result if some of the IOs were
1927          * successfully submitted?
1928          */
1929         for (i=0; i<nr; i++) {
1930                 struct iocb __user *user_iocb;
1931                 struct iocb tmp;
1932
1933                 if (unlikely(__get_user(user_iocb, iocbpp + i))) {
1934                         ret = -EFAULT;
1935                         break;
1936                 }
1937
1938                 if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
1939                         ret = -EFAULT;
1940                         break;
1941                 }
1942
1943                 ret = io_submit_one(ctx, user_iocb, &tmp, compat);
1944                 if (ret)
1945                         break;
1946         }
1947         blk_finish_plug(&plug);
1948
1949         percpu_ref_put(&ctx->users);
1950         return i ? i : ret;
1951 }
1952
1953 /* sys_io_submit:
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.
1964  */
1965 SYSCALL_DEFINE3(io_submit, aio_context_t, ctx_id, long, nr,
1966                 struct iocb __user * __user *, iocbpp)
1967 {
1968         return do_io_submit(ctx_id, nr, iocbpp, 0);
1969 }
1970
1971 /* lookup_kiocb
1972  *      Finds a given iocb for cancellation.
1973  */
1974 static struct aio_kiocb *
1975 lookup_kiocb(struct kioctx *ctx, struct iocb __user *iocb, u32 key)
1976 {
1977         struct aio_kiocb *kiocb;
1978
1979         assert_spin_locked(&ctx->ctx_lock);
1980
1981         if (key != KIOCB_KEY)
1982                 return NULL;
1983
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)
1987                         return kiocb;
1988         }
1989         return NULL;
1990 }
1991
1992 /* sys_io_cancel:
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.
2001  */
2002 SYSCALL_DEFINE3(io_cancel, aio_context_t, ctx_id, struct iocb __user *, iocb,
2003                 struct io_event __user *, result)
2004 {
2005         struct kioctx *ctx;
2006         struct aio_kiocb *kiocb;
2007         u32 key;
2008         int ret;
2009
2010         ret = get_user(key, &iocb->aio_key);
2011         if (unlikely(ret))
2012                 return -EFAULT;
2013
2014         ctx = lookup_ioctx(ctx_id);
2015         if (unlikely(!ctx))
2016                 return -EINVAL;
2017
2018         spin_lock_irq(&ctx->ctx_lock);
2019
2020         kiocb = lookup_kiocb(ctx, iocb, key);
2021         if (kiocb)
2022                 ret = kiocb_cancel(kiocb);
2023         else
2024                 ret = -EINVAL;
2025
2026         spin_unlock_irq(&ctx->ctx_lock);
2027
2028         if (!ret) {
2029                 /*
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:
2033                  */
2034                 ret = -EINPROGRESS;
2035         }
2036
2037         percpu_ref_put(&ctx->users);
2038
2039         return ret;
2040 }
2041
2042 /* io_getevents:
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.
2053  */
2054 SYSCALL_DEFINE5(io_getevents, aio_context_t, ctx_id,
2055                 long, min_nr,
2056                 long, nr,
2057                 struct io_event __user *, events,
2058                 struct timespec __user *, timeout)
2059 {
2060         struct kioctx *ioctx = lookup_ioctx(ctx_id);
2061         long ret = -EINVAL;
2062
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);
2067         }
2068         return ret;
2069 }