Merge branch 'work.open3' of git://git.kernel.org/pub/scm/linux/kernel/git/viro/vfs
[linux-2.6-microblaze.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/signal.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 <linux/uaccess.h>
46
47 #include "internal.h"
48
49 #define KIOCB_KEY               0
50
51 #define AIO_RING_MAGIC                  0xa10a10a1
52 #define AIO_RING_COMPAT_FEATURES        1
53 #define AIO_RING_INCOMPAT_FEATURES      0
54 struct aio_ring {
55         unsigned        id;     /* kernel internal index number */
56         unsigned        nr;     /* number of io_events */
57         unsigned        head;   /* Written to by userland or under ring_lock
58                                  * mutex by aio_read_events_ring(). */
59         unsigned        tail;
60
61         unsigned        magic;
62         unsigned        compat_features;
63         unsigned        incompat_features;
64         unsigned        header_length;  /* size of aio_ring */
65
66
67         struct io_event         io_events[0];
68 }; /* 128 bytes + ring size */
69
70 #define AIO_RING_PAGES  8
71
72 struct kioctx_table {
73         struct rcu_head         rcu;
74         unsigned                nr;
75         struct kioctx __rcu     *table[];
76 };
77
78 struct kioctx_cpu {
79         unsigned                reqs_available;
80 };
81
82 struct ctx_rq_wait {
83         struct completion comp;
84         atomic_t count;
85 };
86
87 struct kioctx {
88         struct percpu_ref       users;
89         atomic_t                dead;
90
91         struct percpu_ref       reqs;
92
93         unsigned long           user_id;
94
95         struct __percpu kioctx_cpu *cpu;
96
97         /*
98          * For percpu reqs_available, number of slots we move to/from global
99          * counter at a time:
100          */
101         unsigned                req_batch;
102         /*
103          * This is what userspace passed to io_setup(), it's not used for
104          * anything but counting against the global max_reqs quota.
105          *
106          * The real limit is nr_events - 1, which will be larger (see
107          * aio_setup_ring())
108          */
109         unsigned                max_reqs;
110
111         /* Size of ringbuffer, in units of struct io_event */
112         unsigned                nr_events;
113
114         unsigned long           mmap_base;
115         unsigned long           mmap_size;
116
117         struct page             **ring_pages;
118         long                    nr_pages;
119
120         struct rcu_work         free_rwork;     /* see free_ioctx() */
121
122         /*
123          * signals when all in-flight requests are done
124          */
125         struct ctx_rq_wait      *rq_wait;
126
127         struct {
128                 /*
129                  * This counts the number of available slots in the ringbuffer,
130                  * so we avoid overflowing it: it's decremented (if positive)
131                  * when allocating a kiocb and incremented when the resulting
132                  * io_event is pulled off the ringbuffer.
133                  *
134                  * We batch accesses to it with a percpu version.
135                  */
136                 atomic_t        reqs_available;
137         } ____cacheline_aligned_in_smp;
138
139         struct {
140                 spinlock_t      ctx_lock;
141                 struct list_head active_reqs;   /* used for cancellation */
142         } ____cacheline_aligned_in_smp;
143
144         struct {
145                 struct mutex    ring_lock;
146                 wait_queue_head_t wait;
147         } ____cacheline_aligned_in_smp;
148
149         struct {
150                 unsigned        tail;
151                 unsigned        completed_events;
152                 spinlock_t      completion_lock;
153         } ____cacheline_aligned_in_smp;
154
155         struct page             *internal_pages[AIO_RING_PAGES];
156         struct file             *aio_ring_file;
157
158         unsigned                id;
159 };
160
161 struct fsync_iocb {
162         struct work_struct      work;
163         struct file             *file;
164         bool                    datasync;
165 };
166
167 struct aio_kiocb {
168         union {
169                 struct kiocb            rw;
170                 struct fsync_iocb       fsync;
171         };
172
173         struct kioctx           *ki_ctx;
174         kiocb_cancel_fn         *ki_cancel;
175
176         struct iocb __user      *ki_user_iocb;  /* user's aiocb */
177         __u64                   ki_user_data;   /* user's data for completion */
178
179         struct list_head        ki_list;        /* the aio core uses this
180                                                  * for cancellation */
181
182         /*
183          * If the aio_resfd field of the userspace iocb is not zero,
184          * this is the underlying eventfd context to deliver events to.
185          */
186         struct eventfd_ctx      *ki_eventfd;
187 };
188
189 /*------ sysctl variables----*/
190 static DEFINE_SPINLOCK(aio_nr_lock);
191 unsigned long aio_nr;           /* current system wide number of aio requests */
192 unsigned long aio_max_nr = 0x10000; /* system wide maximum number of aio requests */
193 /*----end sysctl variables---*/
194
195 static struct kmem_cache        *kiocb_cachep;
196 static struct kmem_cache        *kioctx_cachep;
197
198 static struct vfsmount *aio_mnt;
199
200 static const struct file_operations aio_ring_fops;
201 static const struct address_space_operations aio_ctx_aops;
202
203 static struct file *aio_private_file(struct kioctx *ctx, loff_t nr_pages)
204 {
205         struct file *file;
206         struct inode *inode = alloc_anon_inode(aio_mnt->mnt_sb);
207         if (IS_ERR(inode))
208                 return ERR_CAST(inode);
209
210         inode->i_mapping->a_ops = &aio_ctx_aops;
211         inode->i_mapping->private_data = ctx;
212         inode->i_size = PAGE_SIZE * nr_pages;
213
214         file = alloc_file_pseudo(inode, aio_mnt, "[aio]",
215                                 O_RDWR, &aio_ring_fops);
216         if (IS_ERR(file))
217                 iput(inode);
218         return file;
219 }
220
221 static struct dentry *aio_mount(struct file_system_type *fs_type,
222                                 int flags, const char *dev_name, void *data)
223 {
224         struct dentry *root = mount_pseudo(fs_type, "aio:", NULL, NULL,
225                                            AIO_RING_MAGIC);
226
227         if (!IS_ERR(root))
228                 root->d_sb->s_iflags |= SB_I_NOEXEC;
229         return root;
230 }
231
232 /* aio_setup
233  *      Creates the slab caches used by the aio routines, panic on
234  *      failure as this is done early during the boot sequence.
235  */
236 static int __init aio_setup(void)
237 {
238         static struct file_system_type aio_fs = {
239                 .name           = "aio",
240                 .mount          = aio_mount,
241                 .kill_sb        = kill_anon_super,
242         };
243         aio_mnt = kern_mount(&aio_fs);
244         if (IS_ERR(aio_mnt))
245                 panic("Failed to create aio fs mount.");
246
247         kiocb_cachep = KMEM_CACHE(aio_kiocb, SLAB_HWCACHE_ALIGN|SLAB_PANIC);
248         kioctx_cachep = KMEM_CACHE(kioctx,SLAB_HWCACHE_ALIGN|SLAB_PANIC);
249         return 0;
250 }
251 __initcall(aio_setup);
252
253 static void put_aio_ring_file(struct kioctx *ctx)
254 {
255         struct file *aio_ring_file = ctx->aio_ring_file;
256         struct address_space *i_mapping;
257
258         if (aio_ring_file) {
259                 truncate_setsize(file_inode(aio_ring_file), 0);
260
261                 /* Prevent further access to the kioctx from migratepages */
262                 i_mapping = aio_ring_file->f_mapping;
263                 spin_lock(&i_mapping->private_lock);
264                 i_mapping->private_data = NULL;
265                 ctx->aio_ring_file = NULL;
266                 spin_unlock(&i_mapping->private_lock);
267
268                 fput(aio_ring_file);
269         }
270 }
271
272 static void aio_free_ring(struct kioctx *ctx)
273 {
274         int i;
275
276         /* Disconnect the kiotx from the ring file.  This prevents future
277          * accesses to the kioctx from page migration.
278          */
279         put_aio_ring_file(ctx);
280
281         for (i = 0; i < ctx->nr_pages; i++) {
282                 struct page *page;
283                 pr_debug("pid(%d) [%d] page->count=%d\n", current->pid, i,
284                                 page_count(ctx->ring_pages[i]));
285                 page = ctx->ring_pages[i];
286                 if (!page)
287                         continue;
288                 ctx->ring_pages[i] = NULL;
289                 put_page(page);
290         }
291
292         if (ctx->ring_pages && ctx->ring_pages != ctx->internal_pages) {
293                 kfree(ctx->ring_pages);
294                 ctx->ring_pages = NULL;
295         }
296 }
297
298 static int aio_ring_mremap(struct vm_area_struct *vma)
299 {
300         struct file *file = vma->vm_file;
301         struct mm_struct *mm = vma->vm_mm;
302         struct kioctx_table *table;
303         int i, res = -EINVAL;
304
305         spin_lock(&mm->ioctx_lock);
306         rcu_read_lock();
307         table = rcu_dereference(mm->ioctx_table);
308         for (i = 0; i < table->nr; i++) {
309                 struct kioctx *ctx;
310
311                 ctx = rcu_dereference(table->table[i]);
312                 if (ctx && ctx->aio_ring_file == file) {
313                         if (!atomic_read(&ctx->dead)) {
314                                 ctx->user_id = ctx->mmap_base = vma->vm_start;
315                                 res = 0;
316                         }
317                         break;
318                 }
319         }
320
321         rcu_read_unlock();
322         spin_unlock(&mm->ioctx_lock);
323         return res;
324 }
325
326 static const struct vm_operations_struct aio_ring_vm_ops = {
327         .mremap         = aio_ring_mremap,
328 #if IS_ENABLED(CONFIG_MMU)
329         .fault          = filemap_fault,
330         .map_pages      = filemap_map_pages,
331         .page_mkwrite   = filemap_page_mkwrite,
332 #endif
333 };
334
335 static int aio_ring_mmap(struct file *file, struct vm_area_struct *vma)
336 {
337         vma->vm_flags |= VM_DONTEXPAND;
338         vma->vm_ops = &aio_ring_vm_ops;
339         return 0;
340 }
341
342 static const struct file_operations aio_ring_fops = {
343         .mmap = aio_ring_mmap,
344 };
345
346 #if IS_ENABLED(CONFIG_MIGRATION)
347 static int aio_migratepage(struct address_space *mapping, struct page *new,
348                         struct page *old, enum migrate_mode mode)
349 {
350         struct kioctx *ctx;
351         unsigned long flags;
352         pgoff_t idx;
353         int rc;
354
355         /*
356          * We cannot support the _NO_COPY case here, because copy needs to
357          * happen under the ctx->completion_lock. That does not work with the
358          * migration workflow of MIGRATE_SYNC_NO_COPY.
359          */
360         if (mode == MIGRATE_SYNC_NO_COPY)
361                 return -EINVAL;
362
363         rc = 0;
364
365         /* mapping->private_lock here protects against the kioctx teardown.  */
366         spin_lock(&mapping->private_lock);
367         ctx = mapping->private_data;
368         if (!ctx) {
369                 rc = -EINVAL;
370                 goto out;
371         }
372
373         /* The ring_lock mutex.  The prevents aio_read_events() from writing
374          * to the ring's head, and prevents page migration from mucking in
375          * a partially initialized kiotx.
376          */
377         if (!mutex_trylock(&ctx->ring_lock)) {
378                 rc = -EAGAIN;
379                 goto out;
380         }
381
382         idx = old->index;
383         if (idx < (pgoff_t)ctx->nr_pages) {
384                 /* Make sure the old page hasn't already been changed */
385                 if (ctx->ring_pages[idx] != old)
386                         rc = -EAGAIN;
387         } else
388                 rc = -EINVAL;
389
390         if (rc != 0)
391                 goto out_unlock;
392
393         /* Writeback must be complete */
394         BUG_ON(PageWriteback(old));
395         get_page(new);
396
397         rc = migrate_page_move_mapping(mapping, new, old, NULL, mode, 1);
398         if (rc != MIGRATEPAGE_SUCCESS) {
399                 put_page(new);
400                 goto out_unlock;
401         }
402
403         /* Take completion_lock to prevent other writes to the ring buffer
404          * while the old page is copied to the new.  This prevents new
405          * events from being lost.
406          */
407         spin_lock_irqsave(&ctx->completion_lock, flags);
408         migrate_page_copy(new, old);
409         BUG_ON(ctx->ring_pages[idx] != old);
410         ctx->ring_pages[idx] = new;
411         spin_unlock_irqrestore(&ctx->completion_lock, flags);
412
413         /* The old page is no longer accessible. */
414         put_page(old);
415
416 out_unlock:
417         mutex_unlock(&ctx->ring_lock);
418 out:
419         spin_unlock(&mapping->private_lock);
420         return rc;
421 }
422 #endif
423
424 static const struct address_space_operations aio_ctx_aops = {
425         .set_page_dirty = __set_page_dirty_no_writeback,
426 #if IS_ENABLED(CONFIG_MIGRATION)
427         .migratepage    = aio_migratepage,
428 #endif
429 };
430
431 static int aio_setup_ring(struct kioctx *ctx, unsigned int nr_events)
432 {
433         struct aio_ring *ring;
434         struct mm_struct *mm = current->mm;
435         unsigned long size, unused;
436         int nr_pages;
437         int i;
438         struct file *file;
439
440         /* Compensate for the ring buffer's head/tail overlap entry */
441         nr_events += 2; /* 1 is required, 2 for good luck */
442
443         size = sizeof(struct aio_ring);
444         size += sizeof(struct io_event) * nr_events;
445
446         nr_pages = PFN_UP(size);
447         if (nr_pages < 0)
448                 return -EINVAL;
449
450         file = aio_private_file(ctx, nr_pages);
451         if (IS_ERR(file)) {
452                 ctx->aio_ring_file = NULL;
453                 return -ENOMEM;
454         }
455
456         ctx->aio_ring_file = file;
457         nr_events = (PAGE_SIZE * nr_pages - sizeof(struct aio_ring))
458                         / sizeof(struct io_event);
459
460         ctx->ring_pages = ctx->internal_pages;
461         if (nr_pages > AIO_RING_PAGES) {
462                 ctx->ring_pages = kcalloc(nr_pages, sizeof(struct page *),
463                                           GFP_KERNEL);
464                 if (!ctx->ring_pages) {
465                         put_aio_ring_file(ctx);
466                         return -ENOMEM;
467                 }
468         }
469
470         for (i = 0; i < nr_pages; i++) {
471                 struct page *page;
472                 page = find_or_create_page(file->f_mapping,
473                                            i, GFP_HIGHUSER | __GFP_ZERO);
474                 if (!page)
475                         break;
476                 pr_debug("pid(%d) page[%d]->count=%d\n",
477                          current->pid, i, page_count(page));
478                 SetPageUptodate(page);
479                 unlock_page(page);
480
481                 ctx->ring_pages[i] = page;
482         }
483         ctx->nr_pages = i;
484
485         if (unlikely(i != nr_pages)) {
486                 aio_free_ring(ctx);
487                 return -ENOMEM;
488         }
489
490         ctx->mmap_size = nr_pages * PAGE_SIZE;
491         pr_debug("attempting mmap of %lu bytes\n", ctx->mmap_size);
492
493         if (down_write_killable(&mm->mmap_sem)) {
494                 ctx->mmap_size = 0;
495                 aio_free_ring(ctx);
496                 return -EINTR;
497         }
498
499         ctx->mmap_base = do_mmap_pgoff(ctx->aio_ring_file, 0, ctx->mmap_size,
500                                        PROT_READ | PROT_WRITE,
501                                        MAP_SHARED, 0, &unused, NULL);
502         up_write(&mm->mmap_sem);
503         if (IS_ERR((void *)ctx->mmap_base)) {
504                 ctx->mmap_size = 0;
505                 aio_free_ring(ctx);
506                 return -ENOMEM;
507         }
508
509         pr_debug("mmap address: 0x%08lx\n", ctx->mmap_base);
510
511         ctx->user_id = ctx->mmap_base;
512         ctx->nr_events = nr_events; /* trusted copy */
513
514         ring = kmap_atomic(ctx->ring_pages[0]);
515         ring->nr = nr_events;   /* user copy */
516         ring->id = ~0U;
517         ring->head = ring->tail = 0;
518         ring->magic = AIO_RING_MAGIC;
519         ring->compat_features = AIO_RING_COMPAT_FEATURES;
520         ring->incompat_features = AIO_RING_INCOMPAT_FEATURES;
521         ring->header_length = sizeof(struct aio_ring);
522         kunmap_atomic(ring);
523         flush_dcache_page(ctx->ring_pages[0]);
524
525         return 0;
526 }
527
528 #define AIO_EVENTS_PER_PAGE     (PAGE_SIZE / sizeof(struct io_event))
529 #define AIO_EVENTS_FIRST_PAGE   ((PAGE_SIZE - sizeof(struct aio_ring)) / sizeof(struct io_event))
530 #define AIO_EVENTS_OFFSET       (AIO_EVENTS_PER_PAGE - AIO_EVENTS_FIRST_PAGE)
531
532 void kiocb_set_cancel_fn(struct kiocb *iocb, kiocb_cancel_fn *cancel)
533 {
534         struct aio_kiocb *req = container_of(iocb, struct aio_kiocb, rw);
535         struct kioctx *ctx = req->ki_ctx;
536         unsigned long flags;
537
538         if (WARN_ON_ONCE(!list_empty(&req->ki_list)))
539                 return;
540
541         spin_lock_irqsave(&ctx->ctx_lock, flags);
542         list_add_tail(&req->ki_list, &ctx->active_reqs);
543         req->ki_cancel = cancel;
544         spin_unlock_irqrestore(&ctx->ctx_lock, flags);
545 }
546 EXPORT_SYMBOL(kiocb_set_cancel_fn);
547
548 /*
549  * free_ioctx() should be RCU delayed to synchronize against the RCU
550  * protected lookup_ioctx() and also needs process context to call
551  * aio_free_ring().  Use rcu_work.
552  */
553 static void free_ioctx(struct work_struct *work)
554 {
555         struct kioctx *ctx = container_of(to_rcu_work(work), struct kioctx,
556                                           free_rwork);
557         pr_debug("freeing %p\n", ctx);
558
559         aio_free_ring(ctx);
560         free_percpu(ctx->cpu);
561         percpu_ref_exit(&ctx->reqs);
562         percpu_ref_exit(&ctx->users);
563         kmem_cache_free(kioctx_cachep, ctx);
564 }
565
566 static void free_ioctx_reqs(struct percpu_ref *ref)
567 {
568         struct kioctx *ctx = container_of(ref, struct kioctx, reqs);
569
570         /* At this point we know that there are no any in-flight requests */
571         if (ctx->rq_wait && atomic_dec_and_test(&ctx->rq_wait->count))
572                 complete(&ctx->rq_wait->comp);
573
574         /* Synchronize against RCU protected table->table[] dereferences */
575         INIT_RCU_WORK(&ctx->free_rwork, free_ioctx);
576         queue_rcu_work(system_wq, &ctx->free_rwork);
577 }
578
579 /*
580  * When this function runs, the kioctx has been removed from the "hash table"
581  * and ctx->users has dropped to 0, so we know no more kiocbs can be submitted -
582  * now it's safe to cancel any that need to be.
583  */
584 static void free_ioctx_users(struct percpu_ref *ref)
585 {
586         struct kioctx *ctx = container_of(ref, struct kioctx, users);
587         struct aio_kiocb *req;
588
589         spin_lock_irq(&ctx->ctx_lock);
590
591         while (!list_empty(&ctx->active_reqs)) {
592                 req = list_first_entry(&ctx->active_reqs,
593                                        struct aio_kiocb, ki_list);
594                 req->ki_cancel(&req->rw);
595                 list_del_init(&req->ki_list);
596         }
597
598         spin_unlock_irq(&ctx->ctx_lock);
599
600         percpu_ref_kill(&ctx->reqs);
601         percpu_ref_put(&ctx->reqs);
602 }
603
604 static int ioctx_add_table(struct kioctx *ctx, struct mm_struct *mm)
605 {
606         unsigned i, new_nr;
607         struct kioctx_table *table, *old;
608         struct aio_ring *ring;
609
610         spin_lock(&mm->ioctx_lock);
611         table = rcu_dereference_raw(mm->ioctx_table);
612
613         while (1) {
614                 if (table)
615                         for (i = 0; i < table->nr; i++)
616                                 if (!rcu_access_pointer(table->table[i])) {
617                                         ctx->id = i;
618                                         rcu_assign_pointer(table->table[i], ctx);
619                                         spin_unlock(&mm->ioctx_lock);
620
621                                         /* While kioctx setup is in progress,
622                                          * we are protected from page migration
623                                          * changes ring_pages by ->ring_lock.
624                                          */
625                                         ring = kmap_atomic(ctx->ring_pages[0]);
626                                         ring->id = ctx->id;
627                                         kunmap_atomic(ring);
628                                         return 0;
629                                 }
630
631                 new_nr = (table ? table->nr : 1) * 4;
632                 spin_unlock(&mm->ioctx_lock);
633
634                 table = kzalloc(sizeof(*table) + sizeof(struct kioctx *) *
635                                 new_nr, GFP_KERNEL);
636                 if (!table)
637                         return -ENOMEM;
638
639                 table->nr = new_nr;
640
641                 spin_lock(&mm->ioctx_lock);
642                 old = rcu_dereference_raw(mm->ioctx_table);
643
644                 if (!old) {
645                         rcu_assign_pointer(mm->ioctx_table, table);
646                 } else if (table->nr > old->nr) {
647                         memcpy(table->table, old->table,
648                                old->nr * sizeof(struct kioctx *));
649
650                         rcu_assign_pointer(mm->ioctx_table, table);
651                         kfree_rcu(old, rcu);
652                 } else {
653                         kfree(table);
654                         table = old;
655                 }
656         }
657 }
658
659 static void aio_nr_sub(unsigned nr)
660 {
661         spin_lock(&aio_nr_lock);
662         if (WARN_ON(aio_nr - nr > aio_nr))
663                 aio_nr = 0;
664         else
665                 aio_nr -= nr;
666         spin_unlock(&aio_nr_lock);
667 }
668
669 /* ioctx_alloc
670  *      Allocates and initializes an ioctx.  Returns an ERR_PTR if it failed.
671  */
672 static struct kioctx *ioctx_alloc(unsigned nr_events)
673 {
674         struct mm_struct *mm = current->mm;
675         struct kioctx *ctx;
676         int err = -ENOMEM;
677
678         /*
679          * Store the original nr_events -- what userspace passed to io_setup(),
680          * for counting against the global limit -- before it changes.
681          */
682         unsigned int max_reqs = nr_events;
683
684         /*
685          * We keep track of the number of available ringbuffer slots, to prevent
686          * overflow (reqs_available), and we also use percpu counters for this.
687          *
688          * So since up to half the slots might be on other cpu's percpu counters
689          * and unavailable, double nr_events so userspace sees what they
690          * expected: additionally, we move req_batch slots to/from percpu
691          * counters at a time, so make sure that isn't 0:
692          */
693         nr_events = max(nr_events, num_possible_cpus() * 4);
694         nr_events *= 2;
695
696         /* Prevent overflows */
697         if (nr_events > (0x10000000U / sizeof(struct io_event))) {
698                 pr_debug("ENOMEM: nr_events too high\n");
699                 return ERR_PTR(-EINVAL);
700         }
701
702         if (!nr_events || (unsigned long)max_reqs > aio_max_nr)
703                 return ERR_PTR(-EAGAIN);
704
705         ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL);
706         if (!ctx)
707                 return ERR_PTR(-ENOMEM);
708
709         ctx->max_reqs = max_reqs;
710
711         spin_lock_init(&ctx->ctx_lock);
712         spin_lock_init(&ctx->completion_lock);
713         mutex_init(&ctx->ring_lock);
714         /* Protect against page migration throughout kiotx setup by keeping
715          * the ring_lock mutex held until setup is complete. */
716         mutex_lock(&ctx->ring_lock);
717         init_waitqueue_head(&ctx->wait);
718
719         INIT_LIST_HEAD(&ctx->active_reqs);
720
721         if (percpu_ref_init(&ctx->users, free_ioctx_users, 0, GFP_KERNEL))
722                 goto err;
723
724         if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs, 0, GFP_KERNEL))
725                 goto err;
726
727         ctx->cpu = alloc_percpu(struct kioctx_cpu);
728         if (!ctx->cpu)
729                 goto err;
730
731         err = aio_setup_ring(ctx, nr_events);
732         if (err < 0)
733                 goto err;
734
735         atomic_set(&ctx->reqs_available, ctx->nr_events - 1);
736         ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4);
737         if (ctx->req_batch < 1)
738                 ctx->req_batch = 1;
739
740         /* limit the number of system wide aios */
741         spin_lock(&aio_nr_lock);
742         if (aio_nr + ctx->max_reqs > aio_max_nr ||
743             aio_nr + ctx->max_reqs < aio_nr) {
744                 spin_unlock(&aio_nr_lock);
745                 err = -EAGAIN;
746                 goto err_ctx;
747         }
748         aio_nr += ctx->max_reqs;
749         spin_unlock(&aio_nr_lock);
750
751         percpu_ref_get(&ctx->users);    /* io_setup() will drop this ref */
752         percpu_ref_get(&ctx->reqs);     /* free_ioctx_users() will drop this */
753
754         err = ioctx_add_table(ctx, mm);
755         if (err)
756                 goto err_cleanup;
757
758         /* Release the ring_lock mutex now that all setup is complete. */
759         mutex_unlock(&ctx->ring_lock);
760
761         pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
762                  ctx, ctx->user_id, mm, ctx->nr_events);
763         return ctx;
764
765 err_cleanup:
766         aio_nr_sub(ctx->max_reqs);
767 err_ctx:
768         atomic_set(&ctx->dead, 1);
769         if (ctx->mmap_size)
770                 vm_munmap(ctx->mmap_base, ctx->mmap_size);
771         aio_free_ring(ctx);
772 err:
773         mutex_unlock(&ctx->ring_lock);
774         free_percpu(ctx->cpu);
775         percpu_ref_exit(&ctx->reqs);
776         percpu_ref_exit(&ctx->users);
777         kmem_cache_free(kioctx_cachep, ctx);
778         pr_debug("error allocating ioctx %d\n", err);
779         return ERR_PTR(err);
780 }
781
782 /* kill_ioctx
783  *      Cancels all outstanding aio requests on an aio context.  Used
784  *      when the processes owning a context have all exited to encourage
785  *      the rapid destruction of the kioctx.
786  */
787 static int kill_ioctx(struct mm_struct *mm, struct kioctx *ctx,
788                       struct ctx_rq_wait *wait)
789 {
790         struct kioctx_table *table;
791
792         spin_lock(&mm->ioctx_lock);
793         if (atomic_xchg(&ctx->dead, 1)) {
794                 spin_unlock(&mm->ioctx_lock);
795                 return -EINVAL;
796         }
797
798         table = rcu_dereference_raw(mm->ioctx_table);
799         WARN_ON(ctx != rcu_access_pointer(table->table[ctx->id]));
800         RCU_INIT_POINTER(table->table[ctx->id], NULL);
801         spin_unlock(&mm->ioctx_lock);
802
803         /* free_ioctx_reqs() will do the necessary RCU synchronization */
804         wake_up_all(&ctx->wait);
805
806         /*
807          * It'd be more correct to do this in free_ioctx(), after all
808          * the outstanding kiocbs have finished - but by then io_destroy
809          * has already returned, so io_setup() could potentially return
810          * -EAGAIN with no ioctxs actually in use (as far as userspace
811          *  could tell).
812          */
813         aio_nr_sub(ctx->max_reqs);
814
815         if (ctx->mmap_size)
816                 vm_munmap(ctx->mmap_base, ctx->mmap_size);
817
818         ctx->rq_wait = wait;
819         percpu_ref_kill(&ctx->users);
820         return 0;
821 }
822
823 /*
824  * exit_aio: called when the last user of mm goes away.  At this point, there is
825  * no way for any new requests to be submited or any of the io_* syscalls to be
826  * called on the context.
827  *
828  * There may be outstanding kiocbs, but free_ioctx() will explicitly wait on
829  * them.
830  */
831 void exit_aio(struct mm_struct *mm)
832 {
833         struct kioctx_table *table = rcu_dereference_raw(mm->ioctx_table);
834         struct ctx_rq_wait wait;
835         int i, skipped;
836
837         if (!table)
838                 return;
839
840         atomic_set(&wait.count, table->nr);
841         init_completion(&wait.comp);
842
843         skipped = 0;
844         for (i = 0; i < table->nr; ++i) {
845                 struct kioctx *ctx =
846                         rcu_dereference_protected(table->table[i], true);
847
848                 if (!ctx) {
849                         skipped++;
850                         continue;
851                 }
852
853                 /*
854                  * We don't need to bother with munmap() here - exit_mmap(mm)
855                  * is coming and it'll unmap everything. And we simply can't,
856                  * this is not necessarily our ->mm.
857                  * Since kill_ioctx() uses non-zero ->mmap_size as indicator
858                  * that it needs to unmap the area, just set it to 0.
859                  */
860                 ctx->mmap_size = 0;
861                 kill_ioctx(mm, ctx, &wait);
862         }
863
864         if (!atomic_sub_and_test(skipped, &wait.count)) {
865                 /* Wait until all IO for the context are done. */
866                 wait_for_completion(&wait.comp);
867         }
868
869         RCU_INIT_POINTER(mm->ioctx_table, NULL);
870         kfree(table);
871 }
872
873 static void put_reqs_available(struct kioctx *ctx, unsigned nr)
874 {
875         struct kioctx_cpu *kcpu;
876         unsigned long flags;
877
878         local_irq_save(flags);
879         kcpu = this_cpu_ptr(ctx->cpu);
880         kcpu->reqs_available += nr;
881
882         while (kcpu->reqs_available >= ctx->req_batch * 2) {
883                 kcpu->reqs_available -= ctx->req_batch;
884                 atomic_add(ctx->req_batch, &ctx->reqs_available);
885         }
886
887         local_irq_restore(flags);
888 }
889
890 static bool get_reqs_available(struct kioctx *ctx)
891 {
892         struct kioctx_cpu *kcpu;
893         bool ret = false;
894         unsigned long flags;
895
896         local_irq_save(flags);
897         kcpu = this_cpu_ptr(ctx->cpu);
898         if (!kcpu->reqs_available) {
899                 int old, avail = atomic_read(&ctx->reqs_available);
900
901                 do {
902                         if (avail < ctx->req_batch)
903                                 goto out;
904
905                         old = avail;
906                         avail = atomic_cmpxchg(&ctx->reqs_available,
907                                                avail, avail - ctx->req_batch);
908                 } while (avail != old);
909
910                 kcpu->reqs_available += ctx->req_batch;
911         }
912
913         ret = true;
914         kcpu->reqs_available--;
915 out:
916         local_irq_restore(flags);
917         return ret;
918 }
919
920 /* refill_reqs_available
921  *      Updates the reqs_available reference counts used for tracking the
922  *      number of free slots in the completion ring.  This can be called
923  *      from aio_complete() (to optimistically update reqs_available) or
924  *      from aio_get_req() (the we're out of events case).  It must be
925  *      called holding ctx->completion_lock.
926  */
927 static void refill_reqs_available(struct kioctx *ctx, unsigned head,
928                                   unsigned tail)
929 {
930         unsigned events_in_ring, completed;
931
932         /* Clamp head since userland can write to it. */
933         head %= ctx->nr_events;
934         if (head <= tail)
935                 events_in_ring = tail - head;
936         else
937                 events_in_ring = ctx->nr_events - (head - tail);
938
939         completed = ctx->completed_events;
940         if (events_in_ring < completed)
941                 completed -= events_in_ring;
942         else
943                 completed = 0;
944
945         if (!completed)
946                 return;
947
948         ctx->completed_events -= completed;
949         put_reqs_available(ctx, completed);
950 }
951
952 /* user_refill_reqs_available
953  *      Called to refill reqs_available when aio_get_req() encounters an
954  *      out of space in the completion ring.
955  */
956 static void user_refill_reqs_available(struct kioctx *ctx)
957 {
958         spin_lock_irq(&ctx->completion_lock);
959         if (ctx->completed_events) {
960                 struct aio_ring *ring;
961                 unsigned head;
962
963                 /* Access of ring->head may race with aio_read_events_ring()
964                  * here, but that's okay since whether we read the old version
965                  * or the new version, and either will be valid.  The important
966                  * part is that head cannot pass tail since we prevent
967                  * aio_complete() from updating tail by holding
968                  * ctx->completion_lock.  Even if head is invalid, the check
969                  * against ctx->completed_events below will make sure we do the
970                  * safe/right thing.
971                  */
972                 ring = kmap_atomic(ctx->ring_pages[0]);
973                 head = ring->head;
974                 kunmap_atomic(ring);
975
976                 refill_reqs_available(ctx, head, ctx->tail);
977         }
978
979         spin_unlock_irq(&ctx->completion_lock);
980 }
981
982 /* aio_get_req
983  *      Allocate a slot for an aio request.
984  * Returns NULL if no requests are free.
985  */
986 static inline struct aio_kiocb *aio_get_req(struct kioctx *ctx)
987 {
988         struct aio_kiocb *req;
989
990         if (!get_reqs_available(ctx)) {
991                 user_refill_reqs_available(ctx);
992                 if (!get_reqs_available(ctx))
993                         return NULL;
994         }
995
996         req = kmem_cache_alloc(kiocb_cachep, GFP_KERNEL|__GFP_ZERO);
997         if (unlikely(!req))
998                 goto out_put;
999
1000         percpu_ref_get(&ctx->reqs);
1001         INIT_LIST_HEAD(&req->ki_list);
1002         req->ki_ctx = ctx;
1003         return req;
1004 out_put:
1005         put_reqs_available(ctx, 1);
1006         return NULL;
1007 }
1008
1009 static struct kioctx *lookup_ioctx(unsigned long ctx_id)
1010 {
1011         struct aio_ring __user *ring  = (void __user *)ctx_id;
1012         struct mm_struct *mm = current->mm;
1013         struct kioctx *ctx, *ret = NULL;
1014         struct kioctx_table *table;
1015         unsigned id;
1016
1017         if (get_user(id, &ring->id))
1018                 return NULL;
1019
1020         rcu_read_lock();
1021         table = rcu_dereference(mm->ioctx_table);
1022
1023         if (!table || id >= table->nr)
1024                 goto out;
1025
1026         ctx = rcu_dereference(table->table[id]);
1027         if (ctx && ctx->user_id == ctx_id) {
1028                 if (percpu_ref_tryget_live(&ctx->users))
1029                         ret = ctx;
1030         }
1031 out:
1032         rcu_read_unlock();
1033         return ret;
1034 }
1035
1036 /* aio_complete
1037  *      Called when the io request on the given iocb is complete.
1038  */
1039 static void aio_complete(struct aio_kiocb *iocb, long res, long res2)
1040 {
1041         struct kioctx   *ctx = iocb->ki_ctx;
1042         struct aio_ring *ring;
1043         struct io_event *ev_page, *event;
1044         unsigned tail, pos, head;
1045         unsigned long   flags;
1046
1047         /*
1048          * Add a completion event to the ring buffer. Must be done holding
1049          * ctx->completion_lock to prevent other code from messing with the tail
1050          * pointer since we might be called from irq context.
1051          */
1052         spin_lock_irqsave(&ctx->completion_lock, flags);
1053
1054         tail = ctx->tail;
1055         pos = tail + AIO_EVENTS_OFFSET;
1056
1057         if (++tail >= ctx->nr_events)
1058                 tail = 0;
1059
1060         ev_page = kmap_atomic(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
1061         event = ev_page + pos % AIO_EVENTS_PER_PAGE;
1062
1063         event->obj = (u64)(unsigned long)iocb->ki_user_iocb;
1064         event->data = iocb->ki_user_data;
1065         event->res = res;
1066         event->res2 = res2;
1067
1068         kunmap_atomic(ev_page);
1069         flush_dcache_page(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
1070
1071         pr_debug("%p[%u]: %p: %p %Lx %lx %lx\n",
1072                  ctx, tail, iocb, iocb->ki_user_iocb, iocb->ki_user_data,
1073                  res, res2);
1074
1075         /* after flagging the request as done, we
1076          * must never even look at it again
1077          */
1078         smp_wmb();      /* make event visible before updating tail */
1079
1080         ctx->tail = tail;
1081
1082         ring = kmap_atomic(ctx->ring_pages[0]);
1083         head = ring->head;
1084         ring->tail = tail;
1085         kunmap_atomic(ring);
1086         flush_dcache_page(ctx->ring_pages[0]);
1087
1088         ctx->completed_events++;
1089         if (ctx->completed_events > 1)
1090                 refill_reqs_available(ctx, head, tail);
1091         spin_unlock_irqrestore(&ctx->completion_lock, flags);
1092
1093         pr_debug("added to ring %p at [%u]\n", iocb, tail);
1094
1095         /*
1096          * Check if the user asked us to deliver the result through an
1097          * eventfd. The eventfd_signal() function is safe to be called
1098          * from IRQ context.
1099          */
1100         if (iocb->ki_eventfd) {
1101                 eventfd_signal(iocb->ki_eventfd, 1);
1102                 eventfd_ctx_put(iocb->ki_eventfd);
1103         }
1104
1105         kmem_cache_free(kiocb_cachep, iocb);
1106
1107         /*
1108          * We have to order our ring_info tail store above and test
1109          * of the wait list below outside the wait lock.  This is
1110          * like in wake_up_bit() where clearing a bit has to be
1111          * ordered with the unlocked test.
1112          */
1113         smp_mb();
1114
1115         if (waitqueue_active(&ctx->wait))
1116                 wake_up(&ctx->wait);
1117
1118         percpu_ref_put(&ctx->reqs);
1119 }
1120
1121 /* aio_read_events_ring
1122  *      Pull an event off of the ioctx's event ring.  Returns the number of
1123  *      events fetched
1124  */
1125 static long aio_read_events_ring(struct kioctx *ctx,
1126                                  struct io_event __user *event, long nr)
1127 {
1128         struct aio_ring *ring;
1129         unsigned head, tail, pos;
1130         long ret = 0;
1131         int copy_ret;
1132
1133         /*
1134          * The mutex can block and wake us up and that will cause
1135          * wait_event_interruptible_hrtimeout() to schedule without sleeping
1136          * and repeat. This should be rare enough that it doesn't cause
1137          * peformance issues. See the comment in read_events() for more detail.
1138          */
1139         sched_annotate_sleep();
1140         mutex_lock(&ctx->ring_lock);
1141
1142         /* Access to ->ring_pages here is protected by ctx->ring_lock. */
1143         ring = kmap_atomic(ctx->ring_pages[0]);
1144         head = ring->head;
1145         tail = ring->tail;
1146         kunmap_atomic(ring);
1147
1148         /*
1149          * Ensure that once we've read the current tail pointer, that
1150          * we also see the events that were stored up to the tail.
1151          */
1152         smp_rmb();
1153
1154         pr_debug("h%u t%u m%u\n", head, tail, ctx->nr_events);
1155
1156         if (head == tail)
1157                 goto out;
1158
1159         head %= ctx->nr_events;
1160         tail %= ctx->nr_events;
1161
1162         while (ret < nr) {
1163                 long avail;
1164                 struct io_event *ev;
1165                 struct page *page;
1166
1167                 avail = (head <= tail ?  tail : ctx->nr_events) - head;
1168                 if (head == tail)
1169                         break;
1170
1171                 pos = head + AIO_EVENTS_OFFSET;
1172                 page = ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE];
1173                 pos %= AIO_EVENTS_PER_PAGE;
1174
1175                 avail = min(avail, nr - ret);
1176                 avail = min_t(long, avail, AIO_EVENTS_PER_PAGE - pos);
1177
1178                 ev = kmap(page);
1179                 copy_ret = copy_to_user(event + ret, ev + pos,
1180                                         sizeof(*ev) * avail);
1181                 kunmap(page);
1182
1183                 if (unlikely(copy_ret)) {
1184                         ret = -EFAULT;
1185                         goto out;
1186                 }
1187
1188                 ret += avail;
1189                 head += avail;
1190                 head %= ctx->nr_events;
1191         }
1192
1193         ring = kmap_atomic(ctx->ring_pages[0]);
1194         ring->head = head;
1195         kunmap_atomic(ring);
1196         flush_dcache_page(ctx->ring_pages[0]);
1197
1198         pr_debug("%li  h%u t%u\n", ret, head, tail);
1199 out:
1200         mutex_unlock(&ctx->ring_lock);
1201
1202         return ret;
1203 }
1204
1205 static bool aio_read_events(struct kioctx *ctx, long min_nr, long nr,
1206                             struct io_event __user *event, long *i)
1207 {
1208         long ret = aio_read_events_ring(ctx, event + *i, nr - *i);
1209
1210         if (ret > 0)
1211                 *i += ret;
1212
1213         if (unlikely(atomic_read(&ctx->dead)))
1214                 ret = -EINVAL;
1215
1216         if (!*i)
1217                 *i = ret;
1218
1219         return ret < 0 || *i >= min_nr;
1220 }
1221
1222 static long read_events(struct kioctx *ctx, long min_nr, long nr,
1223                         struct io_event __user *event,
1224                         ktime_t until)
1225 {
1226         long ret = 0;
1227
1228         /*
1229          * Note that aio_read_events() is being called as the conditional - i.e.
1230          * we're calling it after prepare_to_wait() has set task state to
1231          * TASK_INTERRUPTIBLE.
1232          *
1233          * But aio_read_events() can block, and if it blocks it's going to flip
1234          * the task state back to TASK_RUNNING.
1235          *
1236          * This should be ok, provided it doesn't flip the state back to
1237          * TASK_RUNNING and return 0 too much - that causes us to spin. That
1238          * will only happen if the mutex_lock() call blocks, and we then find
1239          * the ringbuffer empty. So in practice we should be ok, but it's
1240          * something to be aware of when touching this code.
1241          */
1242         if (until == 0)
1243                 aio_read_events(ctx, min_nr, nr, event, &ret);
1244         else
1245                 wait_event_interruptible_hrtimeout(ctx->wait,
1246                                 aio_read_events(ctx, min_nr, nr, event, &ret),
1247                                 until);
1248         return ret;
1249 }
1250
1251 /* sys_io_setup:
1252  *      Create an aio_context capable of receiving at least nr_events.
1253  *      ctxp must not point to an aio_context that already exists, and
1254  *      must be initialized to 0 prior to the call.  On successful
1255  *      creation of the aio_context, *ctxp is filled in with the resulting 
1256  *      handle.  May fail with -EINVAL if *ctxp is not initialized,
1257  *      if the specified nr_events exceeds internal limits.  May fail 
1258  *      with -EAGAIN if the specified nr_events exceeds the user's limit 
1259  *      of available events.  May fail with -ENOMEM if insufficient kernel
1260  *      resources are available.  May fail with -EFAULT if an invalid
1261  *      pointer is passed for ctxp.  Will fail with -ENOSYS if not
1262  *      implemented.
1263  */
1264 SYSCALL_DEFINE2(io_setup, unsigned, nr_events, aio_context_t __user *, ctxp)
1265 {
1266         struct kioctx *ioctx = NULL;
1267         unsigned long ctx;
1268         long ret;
1269
1270         ret = get_user(ctx, ctxp);
1271         if (unlikely(ret))
1272                 goto out;
1273
1274         ret = -EINVAL;
1275         if (unlikely(ctx || nr_events == 0)) {
1276                 pr_debug("EINVAL: ctx %lu nr_events %u\n",
1277                          ctx, nr_events);
1278                 goto out;
1279         }
1280
1281         ioctx = ioctx_alloc(nr_events);
1282         ret = PTR_ERR(ioctx);
1283         if (!IS_ERR(ioctx)) {
1284                 ret = put_user(ioctx->user_id, ctxp);
1285                 if (ret)
1286                         kill_ioctx(current->mm, ioctx, NULL);
1287                 percpu_ref_put(&ioctx->users);
1288         }
1289
1290 out:
1291         return ret;
1292 }
1293
1294 #ifdef CONFIG_COMPAT
1295 COMPAT_SYSCALL_DEFINE2(io_setup, unsigned, nr_events, u32 __user *, ctx32p)
1296 {
1297         struct kioctx *ioctx = NULL;
1298         unsigned long ctx;
1299         long ret;
1300
1301         ret = get_user(ctx, ctx32p);
1302         if (unlikely(ret))
1303                 goto out;
1304
1305         ret = -EINVAL;
1306         if (unlikely(ctx || nr_events == 0)) {
1307                 pr_debug("EINVAL: ctx %lu nr_events %u\n",
1308                          ctx, nr_events);
1309                 goto out;
1310         }
1311
1312         ioctx = ioctx_alloc(nr_events);
1313         ret = PTR_ERR(ioctx);
1314         if (!IS_ERR(ioctx)) {
1315                 /* truncating is ok because it's a user address */
1316                 ret = put_user((u32)ioctx->user_id, ctx32p);
1317                 if (ret)
1318                         kill_ioctx(current->mm, ioctx, NULL);
1319                 percpu_ref_put(&ioctx->users);
1320         }
1321
1322 out:
1323         return ret;
1324 }
1325 #endif
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 static void aio_remove_iocb(struct aio_kiocb *iocb)
1364 {
1365         struct kioctx *ctx = iocb->ki_ctx;
1366         unsigned long flags;
1367
1368         spin_lock_irqsave(&ctx->ctx_lock, flags);
1369         list_del(&iocb->ki_list);
1370         spin_unlock_irqrestore(&ctx->ctx_lock, flags);
1371 }
1372
1373 static void aio_complete_rw(struct kiocb *kiocb, long res, long res2)
1374 {
1375         struct aio_kiocb *iocb = container_of(kiocb, struct aio_kiocb, rw);
1376
1377         if (!list_empty_careful(&iocb->ki_list))
1378                 aio_remove_iocb(iocb);
1379
1380         if (kiocb->ki_flags & IOCB_WRITE) {
1381                 struct inode *inode = file_inode(kiocb->ki_filp);
1382
1383                 /*
1384                  * Tell lockdep we inherited freeze protection from submission
1385                  * thread.
1386                  */
1387                 if (S_ISREG(inode->i_mode))
1388                         __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
1389                 file_end_write(kiocb->ki_filp);
1390         }
1391
1392         fput(kiocb->ki_filp);
1393         aio_complete(iocb, res, res2);
1394 }
1395
1396 static int aio_prep_rw(struct kiocb *req, struct iocb *iocb)
1397 {
1398         int ret;
1399
1400         req->ki_filp = fget(iocb->aio_fildes);
1401         if (unlikely(!req->ki_filp))
1402                 return -EBADF;
1403         req->ki_complete = aio_complete_rw;
1404         req->ki_pos = iocb->aio_offset;
1405         req->ki_flags = iocb_flags(req->ki_filp);
1406         if (iocb->aio_flags & IOCB_FLAG_RESFD)
1407                 req->ki_flags |= IOCB_EVENTFD;
1408         req->ki_hint = ki_hint_validate(file_write_hint(req->ki_filp));
1409         if (iocb->aio_flags & IOCB_FLAG_IOPRIO) {
1410                 /*
1411                  * If the IOCB_FLAG_IOPRIO flag of aio_flags is set, then
1412                  * aio_reqprio is interpreted as an I/O scheduling
1413                  * class and priority.
1414                  */
1415                 ret = ioprio_check_cap(iocb->aio_reqprio);
1416                 if (ret) {
1417                         pr_debug("aio ioprio check cap error: %d\n", ret);
1418                         return ret;
1419                 }
1420
1421                 req->ki_ioprio = iocb->aio_reqprio;
1422         } else
1423                 req->ki_ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, 0);
1424
1425         ret = kiocb_set_rw_flags(req, iocb->aio_rw_flags);
1426         if (unlikely(ret))
1427                 fput(req->ki_filp);
1428         return ret;
1429 }
1430
1431 static int aio_setup_rw(int rw, struct iocb *iocb, struct iovec **iovec,
1432                 bool vectored, bool compat, struct iov_iter *iter)
1433 {
1434         void __user *buf = (void __user *)(uintptr_t)iocb->aio_buf;
1435         size_t len = iocb->aio_nbytes;
1436
1437         if (!vectored) {
1438                 ssize_t ret = import_single_range(rw, buf, len, *iovec, iter);
1439                 *iovec = NULL;
1440                 return ret;
1441         }
1442 #ifdef CONFIG_COMPAT
1443         if (compat)
1444                 return compat_import_iovec(rw, buf, len, UIO_FASTIOV, iovec,
1445                                 iter);
1446 #endif
1447         return import_iovec(rw, buf, len, UIO_FASTIOV, iovec, iter);
1448 }
1449
1450 static inline void aio_rw_done(struct kiocb *req, ssize_t ret)
1451 {
1452         switch (ret) {
1453         case -EIOCBQUEUED:
1454                 break;
1455         case -ERESTARTSYS:
1456         case -ERESTARTNOINTR:
1457         case -ERESTARTNOHAND:
1458         case -ERESTART_RESTARTBLOCK:
1459                 /*
1460                  * There's no easy way to restart the syscall since other AIO's
1461                  * may be already running. Just fail this IO with EINTR.
1462                  */
1463                 ret = -EINTR;
1464                 /*FALLTHRU*/
1465         default:
1466                 aio_complete_rw(req, ret, 0);
1467         }
1468 }
1469
1470 static ssize_t aio_read(struct kiocb *req, struct iocb *iocb, bool vectored,
1471                 bool compat)
1472 {
1473         struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1474         struct iov_iter iter;
1475         struct file *file;
1476         ssize_t ret;
1477
1478         ret = aio_prep_rw(req, iocb);
1479         if (ret)
1480                 return ret;
1481         file = req->ki_filp;
1482
1483         ret = -EBADF;
1484         if (unlikely(!(file->f_mode & FMODE_READ)))
1485                 goto out_fput;
1486         ret = -EINVAL;
1487         if (unlikely(!file->f_op->read_iter))
1488                 goto out_fput;
1489
1490         ret = aio_setup_rw(READ, iocb, &iovec, vectored, compat, &iter);
1491         if (ret)
1492                 goto out_fput;
1493         ret = rw_verify_area(READ, file, &req->ki_pos, iov_iter_count(&iter));
1494         if (!ret)
1495                 aio_rw_done(req, call_read_iter(file, req, &iter));
1496         kfree(iovec);
1497 out_fput:
1498         if (unlikely(ret))
1499                 fput(file);
1500         return ret;
1501 }
1502
1503 static ssize_t aio_write(struct kiocb *req, struct iocb *iocb, bool vectored,
1504                 bool compat)
1505 {
1506         struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1507         struct iov_iter iter;
1508         struct file *file;
1509         ssize_t ret;
1510
1511         ret = aio_prep_rw(req, iocb);
1512         if (ret)
1513                 return ret;
1514         file = req->ki_filp;
1515
1516         ret = -EBADF;
1517         if (unlikely(!(file->f_mode & FMODE_WRITE)))
1518                 goto out_fput;
1519         ret = -EINVAL;
1520         if (unlikely(!file->f_op->write_iter))
1521                 goto out_fput;
1522
1523         ret = aio_setup_rw(WRITE, iocb, &iovec, vectored, compat, &iter);
1524         if (ret)
1525                 goto out_fput;
1526         ret = rw_verify_area(WRITE, file, &req->ki_pos, iov_iter_count(&iter));
1527         if (!ret) {
1528                 /*
1529                  * Open-code file_start_write here to grab freeze protection,
1530                  * which will be released by another thread in
1531                  * aio_complete_rw().  Fool lockdep by telling it the lock got
1532                  * released so that it doesn't complain about the held lock when
1533                  * we return to userspace.
1534                  */
1535                 if (S_ISREG(file_inode(file)->i_mode)) {
1536                         __sb_start_write(file_inode(file)->i_sb, SB_FREEZE_WRITE, true);
1537                         __sb_writers_release(file_inode(file)->i_sb, SB_FREEZE_WRITE);
1538                 }
1539                 req->ki_flags |= IOCB_WRITE;
1540                 aio_rw_done(req, call_write_iter(file, req, &iter));
1541         }
1542         kfree(iovec);
1543 out_fput:
1544         if (unlikely(ret))
1545                 fput(file);
1546         return ret;
1547 }
1548
1549 static void aio_fsync_work(struct work_struct *work)
1550 {
1551         struct fsync_iocb *req = container_of(work, struct fsync_iocb, work);
1552         int ret;
1553
1554         ret = vfs_fsync(req->file, req->datasync);
1555         fput(req->file);
1556         aio_complete(container_of(req, struct aio_kiocb, fsync), ret, 0);
1557 }
1558
1559 static int aio_fsync(struct fsync_iocb *req, struct iocb *iocb, bool datasync)
1560 {
1561         if (unlikely(iocb->aio_buf || iocb->aio_offset || iocb->aio_nbytes ||
1562                         iocb->aio_rw_flags))
1563                 return -EINVAL;
1564
1565         req->file = fget(iocb->aio_fildes);
1566         if (unlikely(!req->file))
1567                 return -EBADF;
1568         if (unlikely(!req->file->f_op->fsync)) {
1569                 fput(req->file);
1570                 return -EINVAL;
1571         }
1572
1573         req->datasync = datasync;
1574         INIT_WORK(&req->work, aio_fsync_work);
1575         schedule_work(&req->work);
1576         return 0;
1577 }
1578
1579 static int io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb,
1580                          bool compat)
1581 {
1582         struct aio_kiocb *req;
1583         struct iocb iocb;
1584         ssize_t ret;
1585
1586         if (unlikely(copy_from_user(&iocb, user_iocb, sizeof(iocb))))
1587                 return -EFAULT;
1588
1589         /* enforce forwards compatibility on users */
1590         if (unlikely(iocb.aio_reserved2)) {
1591                 pr_debug("EINVAL: reserve field set\n");
1592                 return -EINVAL;
1593         }
1594
1595         /* prevent overflows */
1596         if (unlikely(
1597             (iocb.aio_buf != (unsigned long)iocb.aio_buf) ||
1598             (iocb.aio_nbytes != (size_t)iocb.aio_nbytes) ||
1599             ((ssize_t)iocb.aio_nbytes < 0)
1600            )) {
1601                 pr_debug("EINVAL: overflow check\n");
1602                 return -EINVAL;
1603         }
1604
1605         req = aio_get_req(ctx);
1606         if (unlikely(!req))
1607                 return -EAGAIN;
1608
1609         if (iocb.aio_flags & IOCB_FLAG_RESFD) {
1610                 /*
1611                  * If the IOCB_FLAG_RESFD flag of aio_flags is set, get an
1612                  * instance of the file* now. The file descriptor must be
1613                  * an eventfd() fd, and will be signaled for each completed
1614                  * event using the eventfd_signal() function.
1615                  */
1616                 req->ki_eventfd = eventfd_ctx_fdget((int) iocb.aio_resfd);
1617                 if (IS_ERR(req->ki_eventfd)) {
1618                         ret = PTR_ERR(req->ki_eventfd);
1619                         req->ki_eventfd = NULL;
1620                         goto out_put_req;
1621                 }
1622         }
1623
1624         ret = put_user(KIOCB_KEY, &user_iocb->aio_key);
1625         if (unlikely(ret)) {
1626                 pr_debug("EFAULT: aio_key\n");
1627                 goto out_put_req;
1628         }
1629
1630         req->ki_user_iocb = user_iocb;
1631         req->ki_user_data = iocb.aio_data;
1632
1633         switch (iocb.aio_lio_opcode) {
1634         case IOCB_CMD_PREAD:
1635                 ret = aio_read(&req->rw, &iocb, false, compat);
1636                 break;
1637         case IOCB_CMD_PWRITE:
1638                 ret = aio_write(&req->rw, &iocb, false, compat);
1639                 break;
1640         case IOCB_CMD_PREADV:
1641                 ret = aio_read(&req->rw, &iocb, true, compat);
1642                 break;
1643         case IOCB_CMD_PWRITEV:
1644                 ret = aio_write(&req->rw, &iocb, true, compat);
1645                 break;
1646         case IOCB_CMD_FSYNC:
1647                 ret = aio_fsync(&req->fsync, &iocb, false);
1648                 break;
1649         case IOCB_CMD_FDSYNC:
1650                 ret = aio_fsync(&req->fsync, &iocb, true);
1651                 break;
1652         default:
1653                 pr_debug("invalid aio operation %d\n", iocb.aio_lio_opcode);
1654                 ret = -EINVAL;
1655                 break;
1656         }
1657
1658         /*
1659          * If ret is 0, we'd either done aio_complete() ourselves or have
1660          * arranged for that to be done asynchronously.  Anything non-zero
1661          * means that we need to destroy req ourselves.
1662          */
1663         if (ret)
1664                 goto out_put_req;
1665         return 0;
1666 out_put_req:
1667         put_reqs_available(ctx, 1);
1668         percpu_ref_put(&ctx->reqs);
1669         if (req->ki_eventfd)
1670                 eventfd_ctx_put(req->ki_eventfd);
1671         kmem_cache_free(kiocb_cachep, req);
1672         return ret;
1673 }
1674
1675 /* sys_io_submit:
1676  *      Queue the nr iocbs pointed to by iocbpp for processing.  Returns
1677  *      the number of iocbs queued.  May return -EINVAL if the aio_context
1678  *      specified by ctx_id is invalid, if nr is < 0, if the iocb at
1679  *      *iocbpp[0] is not properly initialized, if the operation specified
1680  *      is invalid for the file descriptor in the iocb.  May fail with
1681  *      -EFAULT if any of the data structures point to invalid data.  May
1682  *      fail with -EBADF if the file descriptor specified in the first
1683  *      iocb is invalid.  May fail with -EAGAIN if insufficient resources
1684  *      are available to queue any iocbs.  Will return 0 if nr is 0.  Will
1685  *      fail with -ENOSYS if not implemented.
1686  */
1687 SYSCALL_DEFINE3(io_submit, aio_context_t, ctx_id, long, nr,
1688                 struct iocb __user * __user *, iocbpp)
1689 {
1690         struct kioctx *ctx;
1691         long ret = 0;
1692         int i = 0;
1693         struct blk_plug plug;
1694
1695         if (unlikely(nr < 0))
1696                 return -EINVAL;
1697
1698         ctx = lookup_ioctx(ctx_id);
1699         if (unlikely(!ctx)) {
1700                 pr_debug("EINVAL: invalid context id\n");
1701                 return -EINVAL;
1702         }
1703
1704         if (nr > ctx->nr_events)
1705                 nr = ctx->nr_events;
1706
1707         blk_start_plug(&plug);
1708         for (i = 0; i < nr; i++) {
1709                 struct iocb __user *user_iocb;
1710
1711                 if (unlikely(get_user(user_iocb, iocbpp + i))) {
1712                         ret = -EFAULT;
1713                         break;
1714                 }
1715
1716                 ret = io_submit_one(ctx, user_iocb, false);
1717                 if (ret)
1718                         break;
1719         }
1720         blk_finish_plug(&plug);
1721
1722         percpu_ref_put(&ctx->users);
1723         return i ? i : ret;
1724 }
1725
1726 #ifdef CONFIG_COMPAT
1727 COMPAT_SYSCALL_DEFINE3(io_submit, compat_aio_context_t, ctx_id,
1728                        int, nr, compat_uptr_t __user *, iocbpp)
1729 {
1730         struct kioctx *ctx;
1731         long ret = 0;
1732         int i = 0;
1733         struct blk_plug plug;
1734
1735         if (unlikely(nr < 0))
1736                 return -EINVAL;
1737
1738         ctx = lookup_ioctx(ctx_id);
1739         if (unlikely(!ctx)) {
1740                 pr_debug("EINVAL: invalid context id\n");
1741                 return -EINVAL;
1742         }
1743
1744         if (nr > ctx->nr_events)
1745                 nr = ctx->nr_events;
1746
1747         blk_start_plug(&plug);
1748         for (i = 0; i < nr; i++) {
1749                 compat_uptr_t user_iocb;
1750
1751                 if (unlikely(get_user(user_iocb, iocbpp + i))) {
1752                         ret = -EFAULT;
1753                         break;
1754                 }
1755
1756                 ret = io_submit_one(ctx, compat_ptr(user_iocb), true);
1757                 if (ret)
1758                         break;
1759         }
1760         blk_finish_plug(&plug);
1761
1762         percpu_ref_put(&ctx->users);
1763         return i ? i : ret;
1764 }
1765 #endif
1766
1767 /* lookup_kiocb
1768  *      Finds a given iocb for cancellation.
1769  */
1770 static struct aio_kiocb *
1771 lookup_kiocb(struct kioctx *ctx, struct iocb __user *iocb)
1772 {
1773         struct aio_kiocb *kiocb;
1774
1775         assert_spin_locked(&ctx->ctx_lock);
1776
1777         /* TODO: use a hash or array, this sucks. */
1778         list_for_each_entry(kiocb, &ctx->active_reqs, ki_list) {
1779                 if (kiocb->ki_user_iocb == iocb)
1780                         return kiocb;
1781         }
1782         return NULL;
1783 }
1784
1785 /* sys_io_cancel:
1786  *      Attempts to cancel an iocb previously passed to io_submit.  If
1787  *      the operation is successfully cancelled, the resulting event is
1788  *      copied into the memory pointed to by result without being placed
1789  *      into the completion queue and 0 is returned.  May fail with
1790  *      -EFAULT if any of the data structures pointed to are invalid.
1791  *      May fail with -EINVAL if aio_context specified by ctx_id is
1792  *      invalid.  May fail with -EAGAIN if the iocb specified was not
1793  *      cancelled.  Will fail with -ENOSYS if not implemented.
1794  */
1795 SYSCALL_DEFINE3(io_cancel, aio_context_t, ctx_id, struct iocb __user *, iocb,
1796                 struct io_event __user *, result)
1797 {
1798         struct kioctx *ctx;
1799         struct aio_kiocb *kiocb;
1800         int ret = -EINVAL;
1801         u32 key;
1802
1803         if (unlikely(get_user(key, &iocb->aio_key)))
1804                 return -EFAULT;
1805         if (unlikely(key != KIOCB_KEY))
1806                 return -EINVAL;
1807
1808         ctx = lookup_ioctx(ctx_id);
1809         if (unlikely(!ctx))
1810                 return -EINVAL;
1811
1812         spin_lock_irq(&ctx->ctx_lock);
1813         kiocb = lookup_kiocb(ctx, iocb);
1814         if (kiocb) {
1815                 ret = kiocb->ki_cancel(&kiocb->rw);
1816                 list_del_init(&kiocb->ki_list);
1817         }
1818         spin_unlock_irq(&ctx->ctx_lock);
1819
1820         if (!ret) {
1821                 /*
1822                  * The result argument is no longer used - the io_event is
1823                  * always delivered via the ring buffer. -EINPROGRESS indicates
1824                  * cancellation is progress:
1825                  */
1826                 ret = -EINPROGRESS;
1827         }
1828
1829         percpu_ref_put(&ctx->users);
1830
1831         return ret;
1832 }
1833
1834 static long do_io_getevents(aio_context_t ctx_id,
1835                 long min_nr,
1836                 long nr,
1837                 struct io_event __user *events,
1838                 struct timespec64 *ts)
1839 {
1840         ktime_t until = ts ? timespec64_to_ktime(*ts) : KTIME_MAX;
1841         struct kioctx *ioctx = lookup_ioctx(ctx_id);
1842         long ret = -EINVAL;
1843
1844         if (likely(ioctx)) {
1845                 if (likely(min_nr <= nr && min_nr >= 0))
1846                         ret = read_events(ioctx, min_nr, nr, events, until);
1847                 percpu_ref_put(&ioctx->users);
1848         }
1849
1850         return ret;
1851 }
1852
1853 /* io_getevents:
1854  *      Attempts to read at least min_nr events and up to nr events from
1855  *      the completion queue for the aio_context specified by ctx_id. If
1856  *      it succeeds, the number of read events is returned. May fail with
1857  *      -EINVAL if ctx_id is invalid, if min_nr is out of range, if nr is
1858  *      out of range, if timeout is out of range.  May fail with -EFAULT
1859  *      if any of the memory specified is invalid.  May return 0 or
1860  *      < min_nr if the timeout specified by timeout has elapsed
1861  *      before sufficient events are available, where timeout == NULL
1862  *      specifies an infinite timeout. Note that the timeout pointed to by
1863  *      timeout is relative.  Will fail with -ENOSYS if not implemented.
1864  */
1865 SYSCALL_DEFINE5(io_getevents, aio_context_t, ctx_id,
1866                 long, min_nr,
1867                 long, nr,
1868                 struct io_event __user *, events,
1869                 struct timespec __user *, timeout)
1870 {
1871         struct timespec64       ts;
1872         int                     ret;
1873
1874         if (timeout && unlikely(get_timespec64(&ts, timeout)))
1875                 return -EFAULT;
1876
1877         ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &ts : NULL);
1878         if (!ret && signal_pending(current))
1879                 ret = -EINTR;
1880         return ret;
1881 }
1882
1883 struct __aio_sigset {
1884         const sigset_t __user   *sigmask;
1885         size_t          sigsetsize;
1886 };
1887
1888 SYSCALL_DEFINE6(io_pgetevents,
1889                 aio_context_t, ctx_id,
1890                 long, min_nr,
1891                 long, nr,
1892                 struct io_event __user *, events,
1893                 struct timespec __user *, timeout,
1894                 const struct __aio_sigset __user *, usig)
1895 {
1896         struct __aio_sigset     ksig = { NULL, };
1897         sigset_t                ksigmask, sigsaved;
1898         struct timespec64       ts;
1899         int ret;
1900
1901         if (timeout && unlikely(get_timespec64(&ts, timeout)))
1902                 return -EFAULT;
1903
1904         if (usig && copy_from_user(&ksig, usig, sizeof(ksig)))
1905                 return -EFAULT;
1906
1907         if (ksig.sigmask) {
1908                 if (ksig.sigsetsize != sizeof(sigset_t))
1909                         return -EINVAL;
1910                 if (copy_from_user(&ksigmask, ksig.sigmask, sizeof(ksigmask)))
1911                         return -EFAULT;
1912                 sigdelsetmask(&ksigmask, sigmask(SIGKILL) | sigmask(SIGSTOP));
1913                 sigprocmask(SIG_SETMASK, &ksigmask, &sigsaved);
1914         }
1915
1916         ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &ts : NULL);
1917         if (signal_pending(current)) {
1918                 if (ksig.sigmask) {
1919                         current->saved_sigmask = sigsaved;
1920                         set_restore_sigmask();
1921                 }
1922
1923                 if (!ret)
1924                         ret = -ERESTARTNOHAND;
1925         } else {
1926                 if (ksig.sigmask)
1927                         sigprocmask(SIG_SETMASK, &sigsaved, NULL);
1928         }
1929
1930         return ret;
1931 }
1932
1933 #ifdef CONFIG_COMPAT
1934 COMPAT_SYSCALL_DEFINE5(io_getevents, compat_aio_context_t, ctx_id,
1935                        compat_long_t, min_nr,
1936                        compat_long_t, nr,
1937                        struct io_event __user *, events,
1938                        struct compat_timespec __user *, timeout)
1939 {
1940         struct timespec64 t;
1941         int ret;
1942
1943         if (timeout && compat_get_timespec64(&t, timeout))
1944                 return -EFAULT;
1945
1946         ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &t : NULL);
1947         if (!ret && signal_pending(current))
1948                 ret = -EINTR;
1949         return ret;
1950 }
1951
1952
1953 struct __compat_aio_sigset {
1954         compat_sigset_t __user  *sigmask;
1955         compat_size_t           sigsetsize;
1956 };
1957
1958 COMPAT_SYSCALL_DEFINE6(io_pgetevents,
1959                 compat_aio_context_t, ctx_id,
1960                 compat_long_t, min_nr,
1961                 compat_long_t, nr,
1962                 struct io_event __user *, events,
1963                 struct compat_timespec __user *, timeout,
1964                 const struct __compat_aio_sigset __user *, usig)
1965 {
1966         struct __compat_aio_sigset ksig = { NULL, };
1967         sigset_t ksigmask, sigsaved;
1968         struct timespec64 t;
1969         int ret;
1970
1971         if (timeout && compat_get_timespec64(&t, timeout))
1972                 return -EFAULT;
1973
1974         if (usig && copy_from_user(&ksig, usig, sizeof(ksig)))
1975                 return -EFAULT;
1976
1977         if (ksig.sigmask) {
1978                 if (ksig.sigsetsize != sizeof(compat_sigset_t))
1979                         return -EINVAL;
1980                 if (get_compat_sigset(&ksigmask, ksig.sigmask))
1981                         return -EFAULT;
1982                 sigdelsetmask(&ksigmask, sigmask(SIGKILL) | sigmask(SIGSTOP));
1983                 sigprocmask(SIG_SETMASK, &ksigmask, &sigsaved);
1984         }
1985
1986         ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &t : NULL);
1987         if (signal_pending(current)) {
1988                 if (ksig.sigmask) {
1989                         current->saved_sigmask = sigsaved;
1990                         set_restore_sigmask();
1991                 }
1992                 if (!ret)
1993                         ret = -ERESTARTNOHAND;
1994         } else {
1995                 if (ksig.sigmask)
1996                         sigprocmask(SIG_SETMASK, &sigsaved, NULL);
1997         }
1998
1999         return ret;
2000 }
2001 #endif