OSDN Git Service

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