OSDN Git Service

mm, thp: respect MPOL_PREFERRED policy with non-local node
[android-x86/kernel.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_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;
58
59         unsigned        magic;
60         unsigned        compat_features;
61         unsigned        incompat_features;
62         unsigned        header_length;  /* size of aio_ring */
63
64
65         struct io_event         io_events[0];
66 }; /* 128 bytes + ring size */
67
68 #define AIO_RING_PAGES  8
69
70 struct kioctx_table {
71         struct rcu_head rcu;
72         unsigned        nr;
73         struct kioctx   *table[];
74 };
75
76 struct kioctx_cpu {
77         unsigned                reqs_available;
78 };
79
80 struct ctx_rq_wait {
81         struct completion comp;
82         atomic_t count;
83 };
84
85 struct kioctx {
86         struct percpu_ref       users;
87         atomic_t                dead;
88
89         struct percpu_ref       reqs;
90
91         unsigned long           user_id;
92
93         struct __percpu kioctx_cpu *cpu;
94
95         /*
96          * For percpu reqs_available, number of slots we move to/from global
97          * counter at a time:
98          */
99         unsigned                req_batch;
100         /*
101          * This is what userspace passed to io_setup(), it's not used for
102          * anything but counting against the global max_reqs quota.
103          *
104          * The real limit is nr_events - 1, which will be larger (see
105          * aio_setup_ring())
106          */
107         unsigned                max_reqs;
108
109         /* Size of ringbuffer, in units of struct io_event */
110         unsigned                nr_events;
111
112         unsigned long           mmap_base;
113         unsigned long           mmap_size;
114
115         struct page             **ring_pages;
116         long                    nr_pages;
117
118         struct work_struct      free_work;
119
120         /*
121          * signals when all in-flight requests are done
122          */
123         struct ctx_rq_wait      *rq_wait;
124
125         struct {
126                 /*
127                  * This counts the number of available slots in the ringbuffer,
128                  * so we avoid overflowing it: it's decremented (if positive)
129                  * when allocating a kiocb and incremented when the resulting
130                  * io_event is pulled off the ringbuffer.
131                  *
132                  * We batch accesses to it with a percpu version.
133                  */
134                 atomic_t        reqs_available;
135         } ____cacheline_aligned_in_smp;
136
137         struct {
138                 spinlock_t      ctx_lock;
139                 struct list_head active_reqs;   /* used for cancellation */
140         } ____cacheline_aligned_in_smp;
141
142         struct {
143                 struct mutex    ring_lock;
144                 wait_queue_head_t wait;
145         } ____cacheline_aligned_in_smp;
146
147         struct {
148                 unsigned        tail;
149                 unsigned        completed_events;
150                 spinlock_t      completion_lock;
151         } ____cacheline_aligned_in_smp;
152
153         struct page             *internal_pages[AIO_RING_PAGES];
154         struct file             *aio_ring_file;
155
156         unsigned                id;
157 };
158
159 /*------ sysctl variables----*/
160 static DEFINE_SPINLOCK(aio_nr_lock);
161 unsigned long aio_nr;           /* current system wide number of aio requests */
162 unsigned long aio_max_nr = 0x10000; /* system wide maximum number of aio requests */
163 /*----end sysctl variables---*/
164
165 static struct kmem_cache        *kiocb_cachep;
166 static struct kmem_cache        *kioctx_cachep;
167
168 static struct vfsmount *aio_mnt;
169
170 static const struct file_operations aio_ring_fops;
171 static const struct address_space_operations aio_ctx_aops;
172
173 static struct file *aio_private_file(struct kioctx *ctx, loff_t nr_pages)
174 {
175         struct qstr this = QSTR_INIT("[aio]", 5);
176         struct file *file;
177         struct path path;
178         struct inode *inode = alloc_anon_inode(aio_mnt->mnt_sb);
179         if (IS_ERR(inode))
180                 return ERR_CAST(inode);
181
182         inode->i_mapping->a_ops = &aio_ctx_aops;
183         inode->i_mapping->private_data = ctx;
184         inode->i_size = PAGE_SIZE * nr_pages;
185
186         path.dentry = d_alloc_pseudo(aio_mnt->mnt_sb, &this);
187         if (!path.dentry) {
188                 iput(inode);
189                 return ERR_PTR(-ENOMEM);
190         }
191         path.mnt = mntget(aio_mnt);
192
193         d_instantiate(path.dentry, inode);
194         file = alloc_file(&path, FMODE_READ | FMODE_WRITE, &aio_ring_fops);
195         if (IS_ERR(file)) {
196                 path_put(&path);
197                 return file;
198         }
199
200         file->f_flags = O_RDWR;
201         return file;
202 }
203
204 static struct dentry *aio_mount(struct file_system_type *fs_type,
205                                 int flags, const char *dev_name, void *data)
206 {
207         static const struct dentry_operations ops = {
208                 .d_dname        = simple_dname,
209         };
210         return mount_pseudo(fs_type, "aio:", NULL, &ops, AIO_RING_MAGIC);
211 }
212
213 /* aio_setup
214  *      Creates the slab caches used by the aio routines, panic on
215  *      failure as this is done early during the boot sequence.
216  */
217 static int __init aio_setup(void)
218 {
219         static struct file_system_type aio_fs = {
220                 .name           = "aio",
221                 .mount          = aio_mount,
222                 .kill_sb        = kill_anon_super,
223         };
224         aio_mnt = kern_mount(&aio_fs);
225         if (IS_ERR(aio_mnt))
226                 panic("Failed to create aio fs mount.");
227
228         kiocb_cachep = KMEM_CACHE(kiocb, SLAB_HWCACHE_ALIGN|SLAB_PANIC);
229         kioctx_cachep = KMEM_CACHE(kioctx,SLAB_HWCACHE_ALIGN|SLAB_PANIC);
230
231         pr_debug("sizeof(struct page) = %zu\n", sizeof(struct page));
232
233         return 0;
234 }
235 __initcall(aio_setup);
236
237 static void put_aio_ring_file(struct kioctx *ctx)
238 {
239         struct file *aio_ring_file = ctx->aio_ring_file;
240         if (aio_ring_file) {
241                 truncate_setsize(aio_ring_file->f_inode, 0);
242
243                 /* Prevent further access to the kioctx from migratepages */
244                 spin_lock(&aio_ring_file->f_inode->i_mapping->private_lock);
245                 aio_ring_file->f_inode->i_mapping->private_data = NULL;
246                 ctx->aio_ring_file = NULL;
247                 spin_unlock(&aio_ring_file->f_inode->i_mapping->private_lock);
248
249                 fput(aio_ring_file);
250         }
251 }
252
253 static void aio_free_ring(struct kioctx *ctx)
254 {
255         int i;
256
257         /* Disconnect the kiotx from the ring file.  This prevents future
258          * accesses to the kioctx from page migration.
259          */
260         put_aio_ring_file(ctx);
261
262         for (i = 0; i < ctx->nr_pages; i++) {
263                 struct page *page;
264                 pr_debug("pid(%d) [%d] page->count=%d\n", current->pid, i,
265                                 page_count(ctx->ring_pages[i]));
266                 page = ctx->ring_pages[i];
267                 if (!page)
268                         continue;
269                 ctx->ring_pages[i] = NULL;
270                 put_page(page);
271         }
272
273         if (ctx->ring_pages && ctx->ring_pages != ctx->internal_pages) {
274                 kfree(ctx->ring_pages);
275                 ctx->ring_pages = NULL;
276         }
277 }
278
279 static int aio_ring_mmap(struct file *file, struct vm_area_struct *vma)
280 {
281         vma->vm_flags |= VM_DONTEXPAND;
282         vma->vm_ops = &generic_file_vm_ops;
283         return 0;
284 }
285
286 static int aio_ring_remap(struct file *file, struct vm_area_struct *vma)
287 {
288         struct mm_struct *mm = vma->vm_mm;
289         struct kioctx_table *table;
290         int i, res = -EINVAL;
291
292         spin_lock(&mm->ioctx_lock);
293         rcu_read_lock();
294         table = rcu_dereference(mm->ioctx_table);
295         for (i = 0; i < table->nr; i++) {
296                 struct kioctx *ctx;
297
298                 ctx = table->table[i];
299                 if (ctx && ctx->aio_ring_file == file) {
300                         if (!atomic_read(&ctx->dead)) {
301                                 ctx->user_id = ctx->mmap_base = vma->vm_start;
302                                 res = 0;
303                         }
304                         break;
305                 }
306         }
307
308         rcu_read_unlock();
309         spin_unlock(&mm->ioctx_lock);
310         return res;
311 }
312
313 static const struct file_operations aio_ring_fops = {
314         .mmap = aio_ring_mmap,
315         .mremap = aio_ring_remap,
316 };
317
318 #if IS_ENABLED(CONFIG_MIGRATION)
319 static int aio_migratepage(struct address_space *mapping, struct page *new,
320                         struct page *old, enum migrate_mode mode)
321 {
322         struct kioctx *ctx;
323         unsigned long flags;
324         pgoff_t idx;
325         int rc;
326
327         rc = 0;
328
329         /* mapping->private_lock here protects against the kioctx teardown.  */
330         spin_lock(&mapping->private_lock);
331         ctx = mapping->private_data;
332         if (!ctx) {
333                 rc = -EINVAL;
334                 goto out;
335         }
336
337         /* The ring_lock mutex.  The prevents aio_read_events() from writing
338          * to the ring's head, and prevents page migration from mucking in
339          * a partially initialized kiotx.
340          */
341         if (!mutex_trylock(&ctx->ring_lock)) {
342                 rc = -EAGAIN;
343                 goto out;
344         }
345
346         idx = old->index;
347         if (idx < (pgoff_t)ctx->nr_pages) {
348                 /* Make sure the old page hasn't already been changed */
349                 if (ctx->ring_pages[idx] != old)
350                         rc = -EAGAIN;
351         } else
352                 rc = -EINVAL;
353
354         if (rc != 0)
355                 goto out_unlock;
356
357         /* Writeback must be complete */
358         BUG_ON(PageWriteback(old));
359         get_page(new);
360
361         rc = migrate_page_move_mapping(mapping, new, old, NULL, mode, 1);
362         if (rc != MIGRATEPAGE_SUCCESS) {
363                 put_page(new);
364                 goto out_unlock;
365         }
366
367         /* Take completion_lock to prevent other writes to the ring buffer
368          * while the old page is copied to the new.  This prevents new
369          * events from being lost.
370          */
371         spin_lock_irqsave(&ctx->completion_lock, flags);
372         migrate_page_copy(new, old);
373         BUG_ON(ctx->ring_pages[idx] != old);
374         ctx->ring_pages[idx] = new;
375         spin_unlock_irqrestore(&ctx->completion_lock, flags);
376
377         /* The old page is no longer accessible. */
378         put_page(old);
379
380 out_unlock:
381         mutex_unlock(&ctx->ring_lock);
382 out:
383         spin_unlock(&mapping->private_lock);
384         return rc;
385 }
386 #endif
387
388 static const struct address_space_operations aio_ctx_aops = {
389         .set_page_dirty = __set_page_dirty_no_writeback,
390 #if IS_ENABLED(CONFIG_MIGRATION)
391         .migratepage    = aio_migratepage,
392 #endif
393 };
394
395 static int aio_setup_ring(struct kioctx *ctx)
396 {
397         struct aio_ring *ring;
398         unsigned nr_events = ctx->max_reqs;
399         struct mm_struct *mm = current->mm;
400         unsigned long size, unused;
401         int nr_pages;
402         int i;
403         struct file *file;
404
405         /* Compensate for the ring buffer's head/tail overlap entry */
406         nr_events += 2; /* 1 is required, 2 for good luck */
407
408         size = sizeof(struct aio_ring);
409         size += sizeof(struct io_event) * nr_events;
410
411         nr_pages = PFN_UP(size);
412         if (nr_pages < 0)
413                 return -EINVAL;
414
415         file = aio_private_file(ctx, nr_pages);
416         if (IS_ERR(file)) {
417                 ctx->aio_ring_file = NULL;
418                 return -ENOMEM;
419         }
420
421         ctx->aio_ring_file = file;
422         nr_events = (PAGE_SIZE * nr_pages - sizeof(struct aio_ring))
423                         / sizeof(struct io_event);
424
425         ctx->ring_pages = ctx->internal_pages;
426         if (nr_pages > AIO_RING_PAGES) {
427                 ctx->ring_pages = kcalloc(nr_pages, sizeof(struct page *),
428                                           GFP_KERNEL);
429                 if (!ctx->ring_pages) {
430                         put_aio_ring_file(ctx);
431                         return -ENOMEM;
432                 }
433         }
434
435         for (i = 0; i < nr_pages; i++) {
436                 struct page *page;
437                 page = find_or_create_page(file->f_inode->i_mapping,
438                                            i, GFP_HIGHUSER | __GFP_ZERO);
439                 if (!page)
440                         break;
441                 pr_debug("pid(%d) page[%d]->count=%d\n",
442                          current->pid, i, page_count(page));
443                 SetPageUptodate(page);
444                 unlock_page(page);
445
446                 ctx->ring_pages[i] = page;
447         }
448         ctx->nr_pages = i;
449
450         if (unlikely(i != nr_pages)) {
451                 aio_free_ring(ctx);
452                 return -ENOMEM;
453         }
454
455         ctx->mmap_size = nr_pages * PAGE_SIZE;
456         pr_debug("attempting mmap of %lu bytes\n", ctx->mmap_size);
457
458         down_write(&mm->mmap_sem);
459         ctx->mmap_base = do_mmap_pgoff(ctx->aio_ring_file, 0, ctx->mmap_size,
460                                        PROT_READ | PROT_WRITE,
461                                        MAP_SHARED, 0, &unused);
462         up_write(&mm->mmap_sem);
463         if (IS_ERR((void *)ctx->mmap_base)) {
464                 ctx->mmap_size = 0;
465                 aio_free_ring(ctx);
466                 return -ENOMEM;
467         }
468
469         pr_debug("mmap address: 0x%08lx\n", ctx->mmap_base);
470
471         ctx->user_id = ctx->mmap_base;
472         ctx->nr_events = nr_events; /* trusted copy */
473
474         ring = kmap_atomic(ctx->ring_pages[0]);
475         ring->nr = nr_events;   /* user copy */
476         ring->id = ~0U;
477         ring->head = ring->tail = 0;
478         ring->magic = AIO_RING_MAGIC;
479         ring->compat_features = AIO_RING_COMPAT_FEATURES;
480         ring->incompat_features = AIO_RING_INCOMPAT_FEATURES;
481         ring->header_length = sizeof(struct aio_ring);
482         kunmap_atomic(ring);
483         flush_dcache_page(ctx->ring_pages[0]);
484
485         return 0;
486 }
487
488 #define AIO_EVENTS_PER_PAGE     (PAGE_SIZE / sizeof(struct io_event))
489 #define AIO_EVENTS_FIRST_PAGE   ((PAGE_SIZE - sizeof(struct aio_ring)) / sizeof(struct io_event))
490 #define AIO_EVENTS_OFFSET       (AIO_EVENTS_PER_PAGE - AIO_EVENTS_FIRST_PAGE)
491
492 void kiocb_set_cancel_fn(struct kiocb *req, kiocb_cancel_fn *cancel)
493 {
494         struct kioctx *ctx = req->ki_ctx;
495         unsigned long flags;
496
497         spin_lock_irqsave(&ctx->ctx_lock, flags);
498
499         if (!req->ki_list.next)
500                 list_add(&req->ki_list, &ctx->active_reqs);
501
502         req->ki_cancel = cancel;
503
504         spin_unlock_irqrestore(&ctx->ctx_lock, flags);
505 }
506 EXPORT_SYMBOL(kiocb_set_cancel_fn);
507
508 static int kiocb_cancel(struct kiocb *kiocb)
509 {
510         kiocb_cancel_fn *old, *cancel;
511
512         /*
513          * Don't want to set kiocb->ki_cancel = KIOCB_CANCELLED unless it
514          * actually has a cancel function, hence the cmpxchg()
515          */
516
517         cancel = ACCESS_ONCE(kiocb->ki_cancel);
518         do {
519                 if (!cancel || cancel == KIOCB_CANCELLED)
520                         return -EINVAL;
521
522                 old = cancel;
523                 cancel = cmpxchg(&kiocb->ki_cancel, old, KIOCB_CANCELLED);
524         } while (cancel != old);
525
526         return cancel(kiocb);
527 }
528
529 static void free_ioctx(struct work_struct *work)
530 {
531         struct kioctx *ctx = container_of(work, struct kioctx, free_work);
532
533         pr_debug("freeing %p\n", ctx);
534
535         aio_free_ring(ctx);
536         free_percpu(ctx->cpu);
537         percpu_ref_exit(&ctx->reqs);
538         percpu_ref_exit(&ctx->users);
539         kmem_cache_free(kioctx_cachep, ctx);
540 }
541
542 static void free_ioctx_reqs(struct percpu_ref *ref)
543 {
544         struct kioctx *ctx = container_of(ref, struct kioctx, reqs);
545
546         /* At this point we know that there are no any in-flight requests */
547         if (ctx->rq_wait && atomic_dec_and_test(&ctx->rq_wait->count))
548                 complete(&ctx->rq_wait->comp);
549
550         INIT_WORK(&ctx->free_work, free_ioctx);
551         schedule_work(&ctx->free_work);
552 }
553
554 /*
555  * When this function runs, the kioctx has been removed from the "hash table"
556  * and ctx->users has dropped to 0, so we know no more kiocbs can be submitted -
557  * now it's safe to cancel any that need to be.
558  */
559 static void free_ioctx_users(struct percpu_ref *ref)
560 {
561         struct kioctx *ctx = container_of(ref, struct kioctx, users);
562         struct kiocb *req;
563
564         spin_lock_irq(&ctx->ctx_lock);
565
566         while (!list_empty(&ctx->active_reqs)) {
567                 req = list_first_entry(&ctx->active_reqs,
568                                        struct kiocb, ki_list);
569
570                 list_del_init(&req->ki_list);
571                 kiocb_cancel(req);
572         }
573
574         spin_unlock_irq(&ctx->ctx_lock);
575
576         percpu_ref_kill(&ctx->reqs);
577         percpu_ref_put(&ctx->reqs);
578 }
579
580 static int ioctx_add_table(struct kioctx *ctx, struct mm_struct *mm)
581 {
582         unsigned i, new_nr;
583         struct kioctx_table *table, *old;
584         struct aio_ring *ring;
585
586         spin_lock(&mm->ioctx_lock);
587         table = rcu_dereference_raw(mm->ioctx_table);
588
589         while (1) {
590                 if (table)
591                         for (i = 0; i < table->nr; i++)
592                                 if (!table->table[i]) {
593                                         ctx->id = i;
594                                         table->table[i] = ctx;
595                                         spin_unlock(&mm->ioctx_lock);
596
597                                         /* While kioctx setup is in progress,
598                                          * we are protected from page migration
599                                          * changes ring_pages by ->ring_lock.
600                                          */
601                                         ring = kmap_atomic(ctx->ring_pages[0]);
602                                         ring->id = ctx->id;
603                                         kunmap_atomic(ring);
604                                         return 0;
605                                 }
606
607                 new_nr = (table ? table->nr : 1) * 4;
608                 spin_unlock(&mm->ioctx_lock);
609
610                 table = kzalloc(sizeof(*table) + sizeof(struct kioctx *) *
611                                 new_nr, GFP_KERNEL);
612                 if (!table)
613                         return -ENOMEM;
614
615                 table->nr = new_nr;
616
617                 spin_lock(&mm->ioctx_lock);
618                 old = rcu_dereference_raw(mm->ioctx_table);
619
620                 if (!old) {
621                         rcu_assign_pointer(mm->ioctx_table, table);
622                 } else if (table->nr > old->nr) {
623                         memcpy(table->table, old->table,
624                                old->nr * sizeof(struct kioctx *));
625
626                         rcu_assign_pointer(mm->ioctx_table, table);
627                         kfree_rcu(old, rcu);
628                 } else {
629                         kfree(table);
630                         table = old;
631                 }
632         }
633 }
634
635 static void aio_nr_sub(unsigned nr)
636 {
637         spin_lock(&aio_nr_lock);
638         if (WARN_ON(aio_nr - nr > aio_nr))
639                 aio_nr = 0;
640         else
641                 aio_nr -= nr;
642         spin_unlock(&aio_nr_lock);
643 }
644
645 /* ioctx_alloc
646  *      Allocates and initializes an ioctx.  Returns an ERR_PTR if it failed.
647  */
648 static struct kioctx *ioctx_alloc(unsigned nr_events)
649 {
650         struct mm_struct *mm = current->mm;
651         struct kioctx *ctx;
652         int err = -ENOMEM;
653
654         /*
655          * We keep track of the number of available ringbuffer slots, to prevent
656          * overflow (reqs_available), and we also use percpu counters for this.
657          *
658          * So since up to half the slots might be on other cpu's percpu counters
659          * and unavailable, double nr_events so userspace sees what they
660          * expected: additionally, we move req_batch slots to/from percpu
661          * counters at a time, so make sure that isn't 0:
662          */
663         nr_events = max(nr_events, num_possible_cpus() * 4);
664         nr_events *= 2;
665
666         /* Prevent overflows */
667         if ((nr_events > (0x10000000U / sizeof(struct io_event))) ||
668             (nr_events > (0x10000000U / sizeof(struct kiocb)))) {
669                 pr_debug("ENOMEM: nr_events too high\n");
670                 return ERR_PTR(-EINVAL);
671         }
672
673         if (!nr_events || (unsigned long)nr_events > (aio_max_nr * 2UL))
674                 return ERR_PTR(-EAGAIN);
675
676         ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL);
677         if (!ctx)
678                 return ERR_PTR(-ENOMEM);
679
680         ctx->max_reqs = nr_events;
681
682         spin_lock_init(&ctx->ctx_lock);
683         spin_lock_init(&ctx->completion_lock);
684         mutex_init(&ctx->ring_lock);
685         /* Protect against page migration throughout kiotx setup by keeping
686          * the ring_lock mutex held until setup is complete. */
687         mutex_lock(&ctx->ring_lock);
688         init_waitqueue_head(&ctx->wait);
689
690         INIT_LIST_HEAD(&ctx->active_reqs);
691
692         if (percpu_ref_init(&ctx->users, free_ioctx_users, 0, GFP_KERNEL))
693                 goto err;
694
695         if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs, 0, GFP_KERNEL))
696                 goto err;
697
698         ctx->cpu = alloc_percpu(struct kioctx_cpu);
699         if (!ctx->cpu)
700                 goto err;
701
702         err = aio_setup_ring(ctx);
703         if (err < 0)
704                 goto err;
705
706         atomic_set(&ctx->reqs_available, ctx->nr_events - 1);
707         ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4);
708         if (ctx->req_batch < 1)
709                 ctx->req_batch = 1;
710
711         /* limit the number of system wide aios */
712         spin_lock(&aio_nr_lock);
713         if (aio_nr + nr_events > (aio_max_nr * 2UL) ||
714             aio_nr + nr_events < aio_nr) {
715                 spin_unlock(&aio_nr_lock);
716                 err = -EAGAIN;
717                 goto err_ctx;
718         }
719         aio_nr += ctx->max_reqs;
720         spin_unlock(&aio_nr_lock);
721
722         percpu_ref_get(&ctx->users);    /* io_setup() will drop this ref */
723         percpu_ref_get(&ctx->reqs);     /* free_ioctx_users() will drop this */
724
725         err = ioctx_add_table(ctx, mm);
726         if (err)
727                 goto err_cleanup;
728
729         /* Release the ring_lock mutex now that all setup is complete. */
730         mutex_unlock(&ctx->ring_lock);
731
732         pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
733                  ctx, ctx->user_id, mm, ctx->nr_events);
734         return ctx;
735
736 err_cleanup:
737         aio_nr_sub(ctx->max_reqs);
738 err_ctx:
739         atomic_set(&ctx->dead, 1);
740         if (ctx->mmap_size)
741                 vm_munmap(ctx->mmap_base, ctx->mmap_size);
742         aio_free_ring(ctx);
743 err:
744         mutex_unlock(&ctx->ring_lock);
745         free_percpu(ctx->cpu);
746         percpu_ref_exit(&ctx->reqs);
747         percpu_ref_exit(&ctx->users);
748         kmem_cache_free(kioctx_cachep, ctx);
749         pr_debug("error allocating ioctx %d\n", err);
750         return ERR_PTR(err);
751 }
752
753 /* kill_ioctx
754  *      Cancels all outstanding aio requests on an aio context.  Used
755  *      when the processes owning a context have all exited to encourage
756  *      the rapid destruction of the kioctx.
757  */
758 static int kill_ioctx(struct mm_struct *mm, struct kioctx *ctx,
759                       struct ctx_rq_wait *wait)
760 {
761         struct kioctx_table *table;
762
763         spin_lock(&mm->ioctx_lock);
764         if (atomic_xchg(&ctx->dead, 1)) {
765                 spin_unlock(&mm->ioctx_lock);
766                 return -EINVAL;
767         }
768
769         table = rcu_dereference_raw(mm->ioctx_table);
770         WARN_ON(ctx != table->table[ctx->id]);
771         table->table[ctx->id] = NULL;
772         spin_unlock(&mm->ioctx_lock);
773
774         /* percpu_ref_kill() will do the necessary call_rcu() */
775         wake_up_all(&ctx->wait);
776
777         /*
778          * It'd be more correct to do this in free_ioctx(), after all
779          * the outstanding kiocbs have finished - but by then io_destroy
780          * has already returned, so io_setup() could potentially return
781          * -EAGAIN with no ioctxs actually in use (as far as userspace
782          *  could tell).
783          */
784         aio_nr_sub(ctx->max_reqs);
785
786         if (ctx->mmap_size)
787                 vm_munmap(ctx->mmap_base, ctx->mmap_size);
788
789         ctx->rq_wait = wait;
790         percpu_ref_kill(&ctx->users);
791         return 0;
792 }
793
794 /* wait_on_sync_kiocb:
795  *      Waits on the given sync kiocb to complete.
796  */
797 ssize_t wait_on_sync_kiocb(struct kiocb *req)
798 {
799         while (!req->ki_ctx) {
800                 set_current_state(TASK_UNINTERRUPTIBLE);
801                 if (req->ki_ctx)
802                         break;
803                 io_schedule();
804         }
805         __set_current_state(TASK_RUNNING);
806         return req->ki_user_data;
807 }
808 EXPORT_SYMBOL(wait_on_sync_kiocb);
809
810 /*
811  * exit_aio: called when the last user of mm goes away.  At this point, there is
812  * no way for any new requests to be submited or any of the io_* syscalls to be
813  * called on the context.
814  *
815  * There may be outstanding kiocbs, but free_ioctx() will explicitly wait on
816  * them.
817  */
818 void exit_aio(struct mm_struct *mm)
819 {
820         struct kioctx_table *table = rcu_dereference_raw(mm->ioctx_table);
821         struct ctx_rq_wait wait;
822         int i, skipped;
823
824         if (!table)
825                 return;
826
827         atomic_set(&wait.count, table->nr);
828         init_completion(&wait.comp);
829
830         skipped = 0;
831         for (i = 0; i < table->nr; ++i) {
832                 struct kioctx *ctx = table->table[i];
833
834                 if (!ctx) {
835                         skipped++;
836                         continue;
837                 }
838
839                 /*
840                  * We don't need to bother with munmap() here - exit_mmap(mm)
841                  * is coming and it'll unmap everything. And we simply can't,
842                  * this is not necessarily our ->mm.
843                  * Since kill_ioctx() uses non-zero ->mmap_size as indicator
844                  * that it needs to unmap the area, just set it to 0.
845                  */
846                 ctx->mmap_size = 0;
847                 kill_ioctx(mm, ctx, &wait);
848         }
849
850         if (!atomic_sub_and_test(skipped, &wait.count)) {
851                 /* Wait until all IO for the context are done. */
852                 wait_for_completion(&wait.comp);
853         }
854
855         RCU_INIT_POINTER(mm->ioctx_table, NULL);
856         kfree(table);
857 }
858
859 static void put_reqs_available(struct kioctx *ctx, unsigned nr)
860 {
861         struct kioctx_cpu *kcpu;
862         unsigned long flags;
863
864         local_irq_save(flags);
865         kcpu = this_cpu_ptr(ctx->cpu);
866         kcpu->reqs_available += nr;
867
868         while (kcpu->reqs_available >= ctx->req_batch * 2) {
869                 kcpu->reqs_available -= ctx->req_batch;
870                 atomic_add(ctx->req_batch, &ctx->reqs_available);
871         }
872
873         local_irq_restore(flags);
874 }
875
876 static bool get_reqs_available(struct kioctx *ctx)
877 {
878         struct kioctx_cpu *kcpu;
879         bool ret = false;
880         unsigned long flags;
881
882         local_irq_save(flags);
883         kcpu = this_cpu_ptr(ctx->cpu);
884         if (!kcpu->reqs_available) {
885                 int old, avail = atomic_read(&ctx->reqs_available);
886
887                 do {
888                         if (avail < ctx->req_batch)
889                                 goto out;
890
891                         old = avail;
892                         avail = atomic_cmpxchg(&ctx->reqs_available,
893                                                avail, avail - ctx->req_batch);
894                 } while (avail != old);
895
896                 kcpu->reqs_available += ctx->req_batch;
897         }
898
899         ret = true;
900         kcpu->reqs_available--;
901 out:
902         local_irq_restore(flags);
903         return ret;
904 }
905
906 /* refill_reqs_available
907  *      Updates the reqs_available reference counts used for tracking the
908  *      number of free slots in the completion ring.  This can be called
909  *      from aio_complete() (to optimistically update reqs_available) or
910  *      from aio_get_req() (the we're out of events case).  It must be
911  *      called holding ctx->completion_lock.
912  */
913 static void refill_reqs_available(struct kioctx *ctx, unsigned head,
914                                   unsigned tail)
915 {
916         unsigned events_in_ring, completed;
917
918         /* Clamp head since userland can write to it. */
919         head %= ctx->nr_events;
920         if (head <= tail)
921                 events_in_ring = tail - head;
922         else
923                 events_in_ring = ctx->nr_events - (head - tail);
924
925         completed = ctx->completed_events;
926         if (events_in_ring < completed)
927                 completed -= events_in_ring;
928         else
929                 completed = 0;
930
931         if (!completed)
932                 return;
933
934         ctx->completed_events -= completed;
935         put_reqs_available(ctx, completed);
936 }
937
938 /* user_refill_reqs_available
939  *      Called to refill reqs_available when aio_get_req() encounters an
940  *      out of space in the completion ring.
941  */
942 static void user_refill_reqs_available(struct kioctx *ctx)
943 {
944         spin_lock_irq(&ctx->completion_lock);
945         if (ctx->completed_events) {
946                 struct aio_ring *ring;
947                 unsigned head;
948
949                 /* Access of ring->head may race with aio_read_events_ring()
950                  * here, but that's okay since whether we read the old version
951                  * or the new version, and either will be valid.  The important
952                  * part is that head cannot pass tail since we prevent
953                  * aio_complete() from updating tail by holding
954                  * ctx->completion_lock.  Even if head is invalid, the check
955                  * against ctx->completed_events below will make sure we do the
956                  * safe/right thing.
957                  */
958                 ring = kmap_atomic(ctx->ring_pages[0]);
959                 head = ring->head;
960                 kunmap_atomic(ring);
961
962                 refill_reqs_available(ctx, head, ctx->tail);
963         }
964
965         spin_unlock_irq(&ctx->completion_lock);
966 }
967
968 /* aio_get_req
969  *      Allocate a slot for an aio request.
970  * Returns NULL if no requests are free.
971  */
972 static inline struct kiocb *aio_get_req(struct kioctx *ctx)
973 {
974         struct kiocb *req;
975
976         if (!get_reqs_available(ctx)) {
977                 user_refill_reqs_available(ctx);
978                 if (!get_reqs_available(ctx))
979                         return NULL;
980         }
981
982         req = kmem_cache_alloc(kiocb_cachep, GFP_KERNEL|__GFP_ZERO);
983         if (unlikely(!req))
984                 goto out_put;
985
986         percpu_ref_get(&ctx->reqs);
987
988         req->ki_ctx = ctx;
989         return req;
990 out_put:
991         put_reqs_available(ctx, 1);
992         return NULL;
993 }
994
995 static void kiocb_free(struct kiocb *req)
996 {
997         if (req->ki_filp)
998                 fput(req->ki_filp);
999         if (req->ki_eventfd != NULL)
1000                 eventfd_ctx_put(req->ki_eventfd);
1001         kmem_cache_free(kiocb_cachep, req);
1002 }
1003
1004 static struct kioctx *lookup_ioctx(unsigned long ctx_id)
1005 {
1006         struct aio_ring __user *ring  = (void __user *)ctx_id;
1007         struct mm_struct *mm = current->mm;
1008         struct kioctx *ctx, *ret = NULL;
1009         struct kioctx_table *table;
1010         unsigned id;
1011
1012         if (get_user(id, &ring->id))
1013                 return NULL;
1014
1015         rcu_read_lock();
1016         table = rcu_dereference(mm->ioctx_table);
1017
1018         if (!table || id >= table->nr)
1019                 goto out;
1020
1021         ctx = table->table[id];
1022         if (ctx && ctx->user_id == ctx_id) {
1023                 percpu_ref_get(&ctx->users);
1024                 ret = ctx;
1025         }
1026 out:
1027         rcu_read_unlock();
1028         return ret;
1029 }
1030
1031 /* aio_complete
1032  *      Called when the io request on the given iocb is complete.
1033  */
1034 void aio_complete(struct kiocb *iocb, long res, long res2)
1035 {
1036         struct kioctx   *ctx = iocb->ki_ctx;
1037         struct aio_ring *ring;
1038         struct io_event *ev_page, *event;
1039         unsigned tail, pos, head;
1040         unsigned long   flags;
1041
1042         /*
1043          * Special case handling for sync iocbs:
1044          *  - events go directly into the iocb for fast handling
1045          *  - the sync task with the iocb in its stack holds the single iocb
1046          *    ref, no other paths have a way to get another ref
1047          *  - the sync task helpfully left a reference to itself in the iocb
1048          */
1049         if (is_sync_kiocb(iocb)) {
1050                 iocb->ki_user_data = res;
1051                 smp_wmb();
1052                 iocb->ki_ctx = ERR_PTR(-EXDEV);
1053                 wake_up_process(iocb->ki_obj.tsk);
1054                 return;
1055         }
1056
1057         if (iocb->ki_list.next) {
1058                 unsigned long flags;
1059
1060                 spin_lock_irqsave(&ctx->ctx_lock, flags);
1061                 list_del(&iocb->ki_list);
1062                 spin_unlock_irqrestore(&ctx->ctx_lock, flags);
1063         }
1064
1065         /*
1066          * Add a completion event to the ring buffer. Must be done holding
1067          * ctx->completion_lock to prevent other code from messing with the tail
1068          * pointer since we might be called from irq context.
1069          */
1070         spin_lock_irqsave(&ctx->completion_lock, flags);
1071
1072         tail = ctx->tail;
1073         pos = tail + AIO_EVENTS_OFFSET;
1074
1075         if (++tail >= ctx->nr_events)
1076                 tail = 0;
1077
1078         ev_page = kmap_atomic(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
1079         event = ev_page + pos % AIO_EVENTS_PER_PAGE;
1080
1081         event->obj = (u64)(unsigned long)iocb->ki_obj.user;
1082         event->data = iocb->ki_user_data;
1083         event->res = res;
1084         event->res2 = res2;
1085
1086         kunmap_atomic(ev_page);
1087         flush_dcache_page(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
1088
1089         pr_debug("%p[%u]: %p: %p %Lx %lx %lx\n",
1090                  ctx, tail, iocb, iocb->ki_obj.user, iocb->ki_user_data,
1091                  res, res2);
1092
1093         /* after flagging the request as done, we
1094          * must never even look at it again
1095          */
1096         smp_wmb();      /* make event visible before updating tail */
1097
1098         ctx->tail = tail;
1099
1100         ring = kmap_atomic(ctx->ring_pages[0]);
1101         head = ring->head;
1102         ring->tail = tail;
1103         kunmap_atomic(ring);
1104         flush_dcache_page(ctx->ring_pages[0]);
1105
1106         ctx->completed_events++;
1107         if (ctx->completed_events > 1)
1108                 refill_reqs_available(ctx, head, tail);
1109         spin_unlock_irqrestore(&ctx->completion_lock, flags);
1110
1111         pr_debug("added to ring %p at [%u]\n", iocb, tail);
1112
1113         /*
1114          * Check if the user asked us to deliver the result through an
1115          * eventfd. The eventfd_signal() function is safe to be called
1116          * from IRQ context.
1117          */
1118         if (iocb->ki_eventfd != NULL)
1119                 eventfd_signal(iocb->ki_eventfd, 1);
1120
1121         /* everything turned out well, dispose of the aiocb. */
1122         kiocb_free(iocb);
1123
1124         /*
1125          * We have to order our ring_info tail store above and test
1126          * of the wait list below outside the wait lock.  This is
1127          * like in wake_up_bit() where clearing a bit has to be
1128          * ordered with the unlocked test.
1129          */
1130         smp_mb();
1131
1132         if (waitqueue_active(&ctx->wait))
1133                 wake_up(&ctx->wait);
1134
1135         percpu_ref_put(&ctx->reqs);
1136 }
1137 EXPORT_SYMBOL(aio_complete);
1138
1139 /* aio_read_events_ring
1140  *      Pull an event off of the ioctx's event ring.  Returns the number of
1141  *      events fetched
1142  */
1143 static long aio_read_events_ring(struct kioctx *ctx,
1144                                  struct io_event __user *event, long nr)
1145 {
1146         struct aio_ring *ring;
1147         unsigned head, tail, pos;
1148         long ret = 0;
1149         int copy_ret;
1150
1151         /*
1152          * The mutex can block and wake us up and that will cause
1153          * wait_event_interruptible_hrtimeout() to schedule without sleeping
1154          * and repeat. This should be rare enough that it doesn't cause
1155          * peformance issues. See the comment in read_events() for more detail.
1156          */
1157         sched_annotate_sleep();
1158         mutex_lock(&ctx->ring_lock);
1159
1160         /* Access to ->ring_pages here is protected by ctx->ring_lock. */
1161         ring = kmap_atomic(ctx->ring_pages[0]);
1162         head = ring->head;
1163         tail = ring->tail;
1164         kunmap_atomic(ring);
1165
1166         /*
1167          * Ensure that once we've read the current tail pointer, that
1168          * we also see the events that were stored up to the tail.
1169          */
1170         smp_rmb();
1171
1172         pr_debug("h%u t%u m%u\n", head, tail, ctx->nr_events);
1173
1174         if (head == tail)
1175                 goto out;
1176
1177         head %= ctx->nr_events;
1178         tail %= ctx->nr_events;
1179
1180         while (ret < nr) {
1181                 long avail;
1182                 struct io_event *ev;
1183                 struct page *page;
1184
1185                 avail = (head <= tail ?  tail : ctx->nr_events) - head;
1186                 if (head == tail)
1187                         break;
1188
1189                 avail = min(avail, nr - ret);
1190                 avail = min_t(long, avail, AIO_EVENTS_PER_PAGE -
1191                             ((head + AIO_EVENTS_OFFSET) % AIO_EVENTS_PER_PAGE));
1192
1193                 pos = head + AIO_EVENTS_OFFSET;
1194                 page = ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE];
1195                 pos %= AIO_EVENTS_PER_PAGE;
1196
1197                 ev = kmap(page);
1198                 copy_ret = copy_to_user(event + ret, ev + pos,
1199                                         sizeof(*ev) * avail);
1200                 kunmap(page);
1201
1202                 if (unlikely(copy_ret)) {
1203                         ret = -EFAULT;
1204                         goto out;
1205                 }
1206
1207                 ret += avail;
1208                 head += avail;
1209                 head %= ctx->nr_events;
1210         }
1211
1212         ring = kmap_atomic(ctx->ring_pages[0]);
1213         ring->head = head;
1214         kunmap_atomic(ring);
1215         flush_dcache_page(ctx->ring_pages[0]);
1216
1217         pr_debug("%li  h%u t%u\n", ret, head, tail);
1218 out:
1219         mutex_unlock(&ctx->ring_lock);
1220
1221         return ret;
1222 }
1223
1224 static bool aio_read_events(struct kioctx *ctx, long min_nr, long nr,
1225                             struct io_event __user *event, long *i)
1226 {
1227         long ret = aio_read_events_ring(ctx, event + *i, nr - *i);
1228
1229         if (ret > 0)
1230                 *i += ret;
1231
1232         if (unlikely(atomic_read(&ctx->dead)))
1233                 ret = -EINVAL;
1234
1235         if (!*i)
1236                 *i = ret;
1237
1238         return ret < 0 || *i >= min_nr;
1239 }
1240
1241 static long read_events(struct kioctx *ctx, long min_nr, long nr,
1242                         struct io_event __user *event,
1243                         struct timespec __user *timeout)
1244 {
1245         ktime_t until = { .tv64 = KTIME_MAX };
1246         long ret = 0;
1247
1248         if (timeout) {
1249                 struct timespec ts;
1250
1251                 if (unlikely(copy_from_user(&ts, timeout, sizeof(ts))))
1252                         return -EFAULT;
1253
1254                 until = timespec_to_ktime(ts);
1255         }
1256
1257         /*
1258          * Note that aio_read_events() is being called as the conditional - i.e.
1259          * we're calling it after prepare_to_wait() has set task state to
1260          * TASK_INTERRUPTIBLE.
1261          *
1262          * But aio_read_events() can block, and if it blocks it's going to flip
1263          * the task state back to TASK_RUNNING.
1264          *
1265          * This should be ok, provided it doesn't flip the state back to
1266          * TASK_RUNNING and return 0 too much - that causes us to spin. That
1267          * will only happen if the mutex_lock() call blocks, and we then find
1268          * the ringbuffer empty. So in practice we should be ok, but it's
1269          * something to be aware of when touching this code.
1270          */
1271         if (until.tv64 == 0)
1272                 aio_read_events(ctx, min_nr, nr, event, &ret);
1273         else
1274                 wait_event_interruptible_hrtimeout(ctx->wait,
1275                                 aio_read_events(ctx, min_nr, nr, event, &ret),
1276                                 until);
1277
1278         if (!ret && signal_pending(current))
1279                 ret = -EINTR;
1280
1281         return ret;
1282 }
1283
1284 /* sys_io_setup:
1285  *      Create an aio_context capable of receiving at least nr_events.
1286  *      ctxp must not point to an aio_context that already exists, and
1287  *      must be initialized to 0 prior to the call.  On successful
1288  *      creation of the aio_context, *ctxp is filled in with the resulting 
1289  *      handle.  May fail with -EINVAL if *ctxp is not initialized,
1290  *      if the specified nr_events exceeds internal limits.  May fail 
1291  *      with -EAGAIN if the specified nr_events exceeds the user's limit 
1292  *      of available events.  May fail with -ENOMEM if insufficient kernel
1293  *      resources are available.  May fail with -EFAULT if an invalid
1294  *      pointer is passed for ctxp.  Will fail with -ENOSYS if not
1295  *      implemented.
1296  */
1297 SYSCALL_DEFINE2(io_setup, unsigned, nr_events, aio_context_t __user *, ctxp)
1298 {
1299         struct kioctx *ioctx = NULL;
1300         unsigned long ctx;
1301         long ret;
1302
1303         ret = get_user(ctx, ctxp);
1304         if (unlikely(ret))
1305                 goto out;
1306
1307         ret = -EINVAL;
1308         if (unlikely(ctx || nr_events == 0)) {
1309                 pr_debug("EINVAL: ctx %lu nr_events %u\n",
1310                          ctx, nr_events);
1311                 goto out;
1312         }
1313
1314         ioctx = ioctx_alloc(nr_events);
1315         ret = PTR_ERR(ioctx);
1316         if (!IS_ERR(ioctx)) {
1317                 ret = put_user(ioctx->user_id, ctxp);
1318                 if (ret)
1319                         kill_ioctx(current->mm, ioctx, NULL);
1320                 percpu_ref_put(&ioctx->users);
1321         }
1322
1323 out:
1324         return ret;
1325 }
1326
1327 /* sys_io_destroy:
1328  *      Destroy the aio_context specified.  May cancel any outstanding 
1329  *      AIOs and block on completion.  Will fail with -ENOSYS if not
1330  *      implemented.  May fail with -EINVAL if the context pointed to
1331  *      is invalid.
1332  */
1333 SYSCALL_DEFINE1(io_destroy, aio_context_t, ctx)
1334 {
1335         struct kioctx *ioctx = lookup_ioctx(ctx);
1336         if (likely(NULL != ioctx)) {
1337                 struct ctx_rq_wait wait;
1338                 int ret;
1339
1340                 init_completion(&wait.comp);
1341                 atomic_set(&wait.count, 1);
1342
1343                 /* Pass requests_done to kill_ioctx() where it can be set
1344                  * in a thread-safe way. If we try to set it here then we have
1345                  * a race condition if two io_destroy() called simultaneously.
1346                  */
1347                 ret = kill_ioctx(current->mm, ioctx, &wait);
1348                 percpu_ref_put(&ioctx->users);
1349
1350                 /* Wait until all IO for the context are done. Otherwise kernel
1351                  * keep using user-space buffers even if user thinks the context
1352                  * is destroyed.
1353                  */
1354                 if (!ret)
1355                         wait_for_completion(&wait.comp);
1356
1357                 return ret;
1358         }
1359         pr_debug("EINVAL: invalid context id\n");
1360         return -EINVAL;
1361 }
1362
1363 typedef ssize_t (aio_rw_op)(struct kiocb *, const struct iovec *,
1364                             unsigned long, loff_t);
1365 typedef ssize_t (rw_iter_op)(struct kiocb *, struct iov_iter *);
1366
1367 static ssize_t aio_setup_vectored_rw(struct kiocb *kiocb,
1368                                      int rw, char __user *buf,
1369                                      unsigned long *nr_segs,
1370                                      struct iovec **iovec,
1371                                      bool compat)
1372 {
1373         ssize_t ret;
1374
1375         *nr_segs = kiocb->ki_nbytes;
1376
1377 #ifdef CONFIG_COMPAT
1378         if (compat)
1379                 ret = compat_rw_copy_check_uvector(rw,
1380                                 (struct compat_iovec __user *)buf,
1381                                 *nr_segs, UIO_FASTIOV, *iovec, iovec);
1382         else
1383 #endif
1384                 ret = rw_copy_check_uvector(rw,
1385                                 (struct iovec __user *)buf,
1386                                 *nr_segs, UIO_FASTIOV, *iovec, iovec);
1387         if (ret < 0)
1388                 return ret;
1389
1390         /* ki_nbytes now reflect bytes instead of segs */
1391         kiocb->ki_nbytes = ret;
1392         return 0;
1393 }
1394
1395 static ssize_t aio_setup_single_vector(struct kiocb *kiocb,
1396                                        int rw, char __user *buf,
1397                                        unsigned long *nr_segs,
1398                                        struct iovec *iovec)
1399 {
1400         if (unlikely(!access_ok(!rw, buf, kiocb->ki_nbytes)))
1401                 return -EFAULT;
1402
1403         iovec->iov_base = buf;
1404         iovec->iov_len = kiocb->ki_nbytes;
1405         *nr_segs = 1;
1406         return 0;
1407 }
1408
1409 /*
1410  * aio_run_iocb:
1411  *      Performs the initial checks and io submission.
1412  */
1413 static ssize_t aio_run_iocb(struct kiocb *req, unsigned opcode,
1414                             char __user *buf, bool compat)
1415 {
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_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1424         struct iov_iter iter;
1425
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;
1434
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;
1445
1446                 if (!rw_op && !iter_op)
1447                         return -EINVAL;
1448
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_vecs)
1459                                 kfree(iovec);
1460                         return ret;
1461                 }
1462
1463                 req->ki_nbytes = ret;
1464
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;
1470                 }
1471
1472                 if (rw == WRITE)
1473                         file_start_write(file);
1474
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);
1480                 }
1481
1482                 if (rw == WRITE)
1483                         file_end_write(file);
1484                 break;
1485
1486         case IOCB_CMD_FDSYNC:
1487                 if (!file->f_op->aio_fsync)
1488                         return -EINVAL;
1489
1490                 ret = file->f_op->aio_fsync(req, 1);
1491                 break;
1492
1493         case IOCB_CMD_FSYNC:
1494                 if (!file->f_op->aio_fsync)
1495                         return -EINVAL;
1496
1497                 ret = file->f_op->aio_fsync(req, 0);
1498                 break;
1499
1500         default:
1501                 pr_debug("EINVAL: no operation provided\n");
1502                 return -EINVAL;
1503         }
1504
1505         if (iovec != inline_vecs)
1506                 kfree(iovec);
1507
1508         if (ret != -EIOCBQUEUED) {
1509                 /*
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.
1512                  */
1513                 if (unlikely(ret == -ERESTARTSYS || ret == -ERESTARTNOINTR ||
1514                              ret == -ERESTARTNOHAND ||
1515                              ret == -ERESTART_RESTARTBLOCK))
1516                         ret = -EINTR;
1517                 aio_complete(req, ret, 0);
1518         }
1519
1520         return 0;
1521 }
1522
1523 static int io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb,
1524                          struct iocb *iocb, bool compat)
1525 {
1526         struct kiocb *req;
1527         ssize_t ret;
1528
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;
1533         }
1534
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: overflow check\n");
1542                 return -EINVAL;
1543         }
1544
1545         req = aio_get_req(ctx);
1546         if (unlikely(!req))
1547                 return -EAGAIN;
1548
1549         req->ki_filp = fget(iocb->aio_fildes);
1550         if (unlikely(!req->ki_filp)) {
1551                 ret = -EBADF;
1552                 goto out_put_req;
1553         }
1554
1555         if (iocb->aio_flags & IOCB_FLAG_RESFD) {
1556                 /*
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.
1561                  */
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;
1567                 }
1568         }
1569
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;
1574         }
1575
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;
1580
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;
1586
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;
1593 }
1594
1595 long do_io_submit(aio_context_t ctx_id, long nr,
1596                   struct iocb __user *__user *iocbpp, bool compat)
1597 {
1598         struct kioctx *ctx;
1599         long ret = 0;
1600         int i = 0;
1601         struct blk_plug plug;
1602
1603         if (unlikely(nr < 0))
1604                 return -EINVAL;
1605
1606         if (unlikely(nr > LONG_MAX/sizeof(*iocbpp)))
1607                 nr = LONG_MAX/sizeof(*iocbpp);
1608
1609         if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))
1610                 return -EFAULT;
1611
1612         ctx = lookup_ioctx(ctx_id);
1613         if (unlikely(!ctx)) {
1614                 pr_debug("EINVAL: invalid context id\n");
1615                 return -EINVAL;
1616         }
1617
1618         blk_start_plug(&plug);
1619
1620         /*
1621          * AKPM: should this return a partial result if some of the IOs were
1622          * successfully submitted?
1623          */
1624         for (i=0; i<nr; i++) {
1625                 struct iocb __user *user_iocb;
1626                 struct iocb tmp;
1627
1628                 if (unlikely(__get_user(user_iocb, iocbpp + i))) {
1629                         ret = -EFAULT;
1630                         break;
1631                 }
1632
1633                 if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
1634                         ret = -EFAULT;
1635                         break;
1636                 }
1637
1638                 ret = io_submit_one(ctx, user_iocb, &tmp, compat);
1639                 if (ret)
1640                         break;
1641         }
1642         blk_finish_plug(&plug);
1643
1644         percpu_ref_put(&ctx->users);
1645         return i ? i : ret;
1646 }
1647
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.
1659  */
1660 SYSCALL_DEFINE3(io_submit, aio_context_t, ctx_id, long, nr,
1661                 struct iocb __user * __user *, iocbpp)
1662 {
1663         return do_io_submit(ctx_id, nr, iocbpp, 0);
1664 }
1665
1666 /* lookup_kiocb
1667  *      Finds a given iocb for cancellation.
1668  */
1669 static struct kiocb *lookup_kiocb(struct kioctx *ctx, struct iocb __user *iocb,
1670                                   u32 key)
1671 {
1672         struct list_head *pos;
1673
1674         assert_spin_locked(&ctx->ctx_lock);
1675
1676         if (key != KIOCB_KEY)
1677                 return NULL;
1678
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;
1684         }
1685         return NULL;
1686 }
1687
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.
1697  */
1698 SYSCALL_DEFINE3(io_cancel, aio_context_t, ctx_id, struct iocb __user *, iocb,
1699                 struct io_event __user *, result)
1700 {
1701         struct kioctx *ctx;
1702         struct kiocb *kiocb;
1703         u32 key;
1704         int ret;
1705
1706         ret = get_user(key, &iocb->aio_key);
1707         if (unlikely(ret))
1708                 return -EFAULT;
1709
1710         ctx = lookup_ioctx(ctx_id);
1711         if (unlikely(!ctx))
1712                 return -EINVAL;
1713
1714         spin_lock_irq(&ctx->ctx_lock);
1715
1716         kiocb = lookup_kiocb(ctx, iocb, key);
1717         if (kiocb)
1718                 ret = kiocb_cancel(kiocb);
1719         else
1720                 ret = -EINVAL;
1721
1722         spin_unlock_irq(&ctx->ctx_lock);
1723
1724         if (!ret) {
1725                 /*
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:
1729                  */
1730                 ret = -EINPROGRESS;
1731         }
1732
1733         percpu_ref_put(&ctx->users);
1734
1735         return ret;
1736 }
1737
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.
1749  */
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)
1755 {
1756         struct kioctx *ioctx = lookup_ioctx(ctx_id);
1757         long ret = -EINVAL;
1758
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);
1763         }
1764         return ret;
1765 }