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 * Copyright 2018 Christoph Hellwig.
9 *
10 * See ../COPYING for licensing terms.
11 */
12 #define pr_fmt(fmt) "%s: " fmt, __func__
13
14 #include <linux/kernel.h>
15 #include <linux/init.h>
16 #include <linux/errno.h>
17 #include <linux/time.h>
18 #include <linux/aio_abi.h>
19 #include <linux/export.h>
20 #include <linux/syscalls.h>
21 #include <linux/backing-dev.h>
22 #include <linux/refcount.h>
23 #include <linux/uio.h>
24
25 #include <linux/sched/signal.h>
26 #include <linux/fs.h>
27 #include <linux/file.h>
28 #include <linux/mm.h>
29 #include <linux/mman.h>
30 #include <linux/percpu.h>
31 #include <linux/slab.h>
32 #include <linux/timer.h>
33 #include <linux/aio.h>
34 #include <linux/highmem.h>
35 #include <linux/workqueue.h>
36 #include <linux/security.h>
37 #include <linux/eventfd.h>
38 #include <linux/blkdev.h>
39 #include <linux/compat.h>
40 #include <linux/migrate.h>
41 #include <linux/ramfs.h>
42 #include <linux/percpu-refcount.h>
43 #include <linux/mount.h>
44 #include <linux/pseudo_fs.h>
45
46 #include <linux/uaccess.h>
47 #include <linux/nospec.h>
48
49 #include "internal.h"
50
51 #define KIOCB_KEY 0
52
53 #define AIO_RING_MAGIC 0xa10a10a1
54 #define AIO_RING_COMPAT_FEATURES 1
55 #define AIO_RING_INCOMPAT_FEATURES 0
56 struct aio_ring {
57 unsigned id; /* kernel internal index number */
58 unsigned nr; /* number of io_events */
59 unsigned head; /* Written to by userland or under ring_lock
60 * mutex by aio_read_events_ring(). */
61 unsigned tail;
62
63 unsigned magic;
64 unsigned compat_features;
65 unsigned incompat_features;
66 unsigned header_length; /* size of aio_ring */
67
68
69 struct io_event io_events[];
70 }; /* 128 bytes + ring size */
71
72 /*
73 * Plugging is meant to work with larger batches of IOs. If we don't
74 * have more than the below, then don't bother setting up a plug.
75 */
76 #define AIO_PLUG_THRESHOLD 2
77
78 #define AIO_RING_PAGES 8
79
80 struct kioctx_table {
81 struct rcu_head rcu;
82 unsigned nr;
83 struct kioctx __rcu *table[];
84 };
85
86 struct kioctx_cpu {
87 unsigned reqs_available;
88 };
89
90 struct ctx_rq_wait {
91 struct completion comp;
92 atomic_t count;
93 };
94
95 struct kioctx {
96 struct percpu_ref users;
97 atomic_t dead;
98
99 struct percpu_ref reqs;
100
101 unsigned long user_id;
102
103 struct __percpu kioctx_cpu *cpu;
104
105 /*
106 * For percpu reqs_available, number of slots we move to/from global
107 * counter at a time:
108 */
109 unsigned req_batch;
110 /*
111 * This is what userspace passed to io_setup(), it's not used for
112 * anything but counting against the global max_reqs quota.
113 *
114 * The real limit is nr_events - 1, which will be larger (see
115 * aio_setup_ring())
116 */
117 unsigned max_reqs;
118
119 /* Size of ringbuffer, in units of struct io_event */
120 unsigned nr_events;
121
122 unsigned long mmap_base;
123 unsigned long mmap_size;
124
125 struct page **ring_pages;
126 long nr_pages;
127
128 struct rcu_work free_rwork; /* see free_ioctx() */
129
130 /*
131 * signals when all in-flight requests are done
132 */
133 struct ctx_rq_wait *rq_wait;
134
135 struct {
136 /*
137 * This counts the number of available slots in the ringbuffer,
138 * so we avoid overflowing it: it's decremented (if positive)
139 * when allocating a kiocb and incremented when the resulting
140 * io_event is pulled off the ringbuffer.
141 *
142 * We batch accesses to it with a percpu version.
143 */
144 atomic_t reqs_available;
145 } ____cacheline_aligned_in_smp;
146
147 struct {
148 spinlock_t ctx_lock;
149 struct list_head active_reqs; /* used for cancellation */
150 } ____cacheline_aligned_in_smp;
151
152 struct {
153 struct mutex ring_lock;
154 wait_queue_head_t wait;
155 } ____cacheline_aligned_in_smp;
156
157 struct {
158 unsigned tail;
159 unsigned completed_events;
160 spinlock_t completion_lock;
161 } ____cacheline_aligned_in_smp;
162
163 struct page *internal_pages[AIO_RING_PAGES];
164 struct file *aio_ring_file;
165
166 unsigned id;
167 };
168
169 /*
170 * First field must be the file pointer in all the
171 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
172 */
173 struct fsync_iocb {
174 struct file *file;
175 struct work_struct work;
176 bool datasync;
177 struct cred *creds;
178 };
179
180 struct poll_iocb {
181 struct file *file;
182 struct wait_queue_head *head;
183 __poll_t events;
184 bool cancelled;
185 bool work_scheduled;
186 bool work_need_resched;
187 struct wait_queue_entry wait;
188 struct work_struct work;
189 };
190
191 /*
192 * NOTE! Each of the iocb union members has the file pointer
193 * as the first entry in their struct definition. So you can
194 * access the file pointer through any of the sub-structs,
195 * or directly as just 'ki_filp' in this struct.
196 */
197 struct aio_kiocb {
198 union {
199 struct file *ki_filp;
200 struct kiocb rw;
201 struct fsync_iocb fsync;
202 struct poll_iocb poll;
203 };
204
205 struct kioctx *ki_ctx;
206 kiocb_cancel_fn *ki_cancel;
207
208 struct io_event ki_res;
209
210 struct list_head ki_list; /* the aio core uses this
211 * for cancellation */
212 refcount_t ki_refcnt;
213
214 /*
215 * If the aio_resfd field of the userspace iocb is not zero,
216 * this is the underlying eventfd context to deliver events to.
217 */
218 struct eventfd_ctx *ki_eventfd;
219 };
220
221 /*------ sysctl variables----*/
222 static DEFINE_SPINLOCK(aio_nr_lock);
223 static unsigned long aio_nr; /* current system wide number of aio requests */
224 static unsigned long aio_max_nr = 0x10000; /* system wide maximum number of aio requests */
225 /*----end sysctl variables---*/
226 #ifdef CONFIG_SYSCTL
227 static struct ctl_table aio_sysctls[] = {
228 {
229 .procname = "aio-nr",
230 .data = &aio_nr,
231 .maxlen = sizeof(aio_nr),
232 .mode = 0444,
233 .proc_handler = proc_doulongvec_minmax,
234 },
235 {
236 .procname = "aio-max-nr",
237 .data = &aio_max_nr,
238 .maxlen = sizeof(aio_max_nr),
239 .mode = 0644,
240 .proc_handler = proc_doulongvec_minmax,
241 },
242 {}
243 };
244
aio_sysctl_init(void)245 static void __init aio_sysctl_init(void)
246 {
247 register_sysctl_init("fs", aio_sysctls);
248 }
249 #else
250 #define aio_sysctl_init() do { } while (0)
251 #endif
252
253 static struct kmem_cache *kiocb_cachep;
254 static struct kmem_cache *kioctx_cachep;
255
256 static struct vfsmount *aio_mnt;
257
258 static const struct file_operations aio_ring_fops;
259 static const struct address_space_operations aio_ctx_aops;
260
aio_private_file(struct kioctx * ctx,loff_t nr_pages)261 static struct file *aio_private_file(struct kioctx *ctx, loff_t nr_pages)
262 {
263 struct file *file;
264 struct inode *inode = alloc_anon_inode(aio_mnt->mnt_sb);
265 if (IS_ERR(inode))
266 return ERR_CAST(inode);
267
268 inode->i_mapping->a_ops = &aio_ctx_aops;
269 inode->i_mapping->private_data = ctx;
270 inode->i_size = PAGE_SIZE * nr_pages;
271
272 file = alloc_file_pseudo(inode, aio_mnt, "[aio]",
273 O_RDWR, &aio_ring_fops);
274 if (IS_ERR(file))
275 iput(inode);
276 return file;
277 }
278
aio_init_fs_context(struct fs_context * fc)279 static int aio_init_fs_context(struct fs_context *fc)
280 {
281 if (!init_pseudo(fc, AIO_RING_MAGIC))
282 return -ENOMEM;
283 fc->s_iflags |= SB_I_NOEXEC;
284 return 0;
285 }
286
287 /* aio_setup
288 * Creates the slab caches used by the aio routines, panic on
289 * failure as this is done early during the boot sequence.
290 */
aio_setup(void)291 static int __init aio_setup(void)
292 {
293 static struct file_system_type aio_fs = {
294 .name = "aio",
295 .init_fs_context = aio_init_fs_context,
296 .kill_sb = kill_anon_super,
297 };
298 aio_mnt = kern_mount(&aio_fs);
299 if (IS_ERR(aio_mnt))
300 panic("Failed to create aio fs mount.");
301
302 kiocb_cachep = KMEM_CACHE(aio_kiocb, SLAB_HWCACHE_ALIGN|SLAB_PANIC);
303 kioctx_cachep = KMEM_CACHE(kioctx,SLAB_HWCACHE_ALIGN|SLAB_PANIC);
304 aio_sysctl_init();
305 return 0;
306 }
307 __initcall(aio_setup);
308
put_aio_ring_file(struct kioctx * ctx)309 static void put_aio_ring_file(struct kioctx *ctx)
310 {
311 struct file *aio_ring_file = ctx->aio_ring_file;
312 struct address_space *i_mapping;
313
314 if (aio_ring_file) {
315 truncate_setsize(file_inode(aio_ring_file), 0);
316
317 /* Prevent further access to the kioctx from migratepages */
318 i_mapping = aio_ring_file->f_mapping;
319 spin_lock(&i_mapping->private_lock);
320 i_mapping->private_data = NULL;
321 ctx->aio_ring_file = NULL;
322 spin_unlock(&i_mapping->private_lock);
323
324 fput(aio_ring_file);
325 }
326 }
327
aio_free_ring(struct kioctx * ctx)328 static void aio_free_ring(struct kioctx *ctx)
329 {
330 int i;
331
332 /* Disconnect the kiotx from the ring file. This prevents future
333 * accesses to the kioctx from page migration.
334 */
335 put_aio_ring_file(ctx);
336
337 for (i = 0; i < ctx->nr_pages; i++) {
338 struct page *page;
339 pr_debug("pid(%d) [%d] page->count=%d\n", current->pid, i,
340 page_count(ctx->ring_pages[i]));
341 page = ctx->ring_pages[i];
342 if (!page)
343 continue;
344 ctx->ring_pages[i] = NULL;
345 put_page(page);
346 }
347
348 if (ctx->ring_pages && ctx->ring_pages != ctx->internal_pages) {
349 kfree(ctx->ring_pages);
350 ctx->ring_pages = NULL;
351 }
352 }
353
aio_ring_mremap(struct vm_area_struct * vma)354 static int aio_ring_mremap(struct vm_area_struct *vma)
355 {
356 struct file *file = vma->vm_file;
357 struct mm_struct *mm = vma->vm_mm;
358 struct kioctx_table *table;
359 int i, res = -EINVAL;
360
361 spin_lock(&mm->ioctx_lock);
362 rcu_read_lock();
363 table = rcu_dereference(mm->ioctx_table);
364 if (!table)
365 goto out_unlock;
366
367 for (i = 0; i < table->nr; i++) {
368 struct kioctx *ctx;
369
370 ctx = rcu_dereference(table->table[i]);
371 if (ctx && ctx->aio_ring_file == file) {
372 if (!atomic_read(&ctx->dead)) {
373 ctx->user_id = ctx->mmap_base = vma->vm_start;
374 res = 0;
375 }
376 break;
377 }
378 }
379
380 out_unlock:
381 rcu_read_unlock();
382 spin_unlock(&mm->ioctx_lock);
383 return res;
384 }
385
386 static const struct vm_operations_struct aio_ring_vm_ops = {
387 .mremap = aio_ring_mremap,
388 #if IS_ENABLED(CONFIG_MMU)
389 .fault = filemap_fault,
390 .map_pages = filemap_map_pages,
391 .page_mkwrite = filemap_page_mkwrite,
392 #endif
393 };
394
aio_ring_mmap(struct file * file,struct vm_area_struct * vma)395 static int aio_ring_mmap(struct file *file, struct vm_area_struct *vma)
396 {
397 vm_flags_set(vma, VM_DONTEXPAND);
398 vma->vm_ops = &aio_ring_vm_ops;
399 return 0;
400 }
401
402 static const struct file_operations aio_ring_fops = {
403 .mmap = aio_ring_mmap,
404 };
405
406 #if IS_ENABLED(CONFIG_MIGRATION)
aio_migrate_folio(struct address_space * mapping,struct folio * dst,struct folio * src,enum migrate_mode mode)407 static int aio_migrate_folio(struct address_space *mapping, struct folio *dst,
408 struct folio *src, enum migrate_mode mode)
409 {
410 struct kioctx *ctx;
411 unsigned long flags;
412 pgoff_t idx;
413 int rc;
414
415 /*
416 * We cannot support the _NO_COPY case here, because copy needs to
417 * happen under the ctx->completion_lock. That does not work with the
418 * migration workflow of MIGRATE_SYNC_NO_COPY.
419 */
420 if (mode == MIGRATE_SYNC_NO_COPY)
421 return -EINVAL;
422
423 rc = 0;
424
425 /* mapping->private_lock here protects against the kioctx teardown. */
426 spin_lock(&mapping->private_lock);
427 ctx = mapping->private_data;
428 if (!ctx) {
429 rc = -EINVAL;
430 goto out;
431 }
432
433 /* The ring_lock mutex. The prevents aio_read_events() from writing
434 * to the ring's head, and prevents page migration from mucking in
435 * a partially initialized kiotx.
436 */
437 if (!mutex_trylock(&ctx->ring_lock)) {
438 rc = -EAGAIN;
439 goto out;
440 }
441
442 idx = src->index;
443 if (idx < (pgoff_t)ctx->nr_pages) {
444 /* Make sure the old folio hasn't already been changed */
445 if (ctx->ring_pages[idx] != &src->page)
446 rc = -EAGAIN;
447 } else
448 rc = -EINVAL;
449
450 if (rc != 0)
451 goto out_unlock;
452
453 /* Writeback must be complete */
454 BUG_ON(folio_test_writeback(src));
455 folio_get(dst);
456
457 rc = folio_migrate_mapping(mapping, dst, src, 1);
458 if (rc != MIGRATEPAGE_SUCCESS) {
459 folio_put(dst);
460 goto out_unlock;
461 }
462
463 /* Take completion_lock to prevent other writes to the ring buffer
464 * while the old folio is copied to the new. This prevents new
465 * events from being lost.
466 */
467 spin_lock_irqsave(&ctx->completion_lock, flags);
468 folio_migrate_copy(dst, src);
469 BUG_ON(ctx->ring_pages[idx] != &src->page);
470 ctx->ring_pages[idx] = &dst->page;
471 spin_unlock_irqrestore(&ctx->completion_lock, flags);
472
473 /* The old folio is no longer accessible. */
474 folio_put(src);
475
476 out_unlock:
477 mutex_unlock(&ctx->ring_lock);
478 out:
479 spin_unlock(&mapping->private_lock);
480 return rc;
481 }
482 #else
483 #define aio_migrate_folio NULL
484 #endif
485
486 static const struct address_space_operations aio_ctx_aops = {
487 .dirty_folio = noop_dirty_folio,
488 .migrate_folio = aio_migrate_folio,
489 };
490
aio_setup_ring(struct kioctx * ctx,unsigned int nr_events)491 static int aio_setup_ring(struct kioctx *ctx, unsigned int nr_events)
492 {
493 struct aio_ring *ring;
494 struct mm_struct *mm = current->mm;
495 unsigned long size, unused;
496 int nr_pages;
497 int i;
498 struct file *file;
499
500 /* Compensate for the ring buffer's head/tail overlap entry */
501 nr_events += 2; /* 1 is required, 2 for good luck */
502
503 size = sizeof(struct aio_ring);
504 size += sizeof(struct io_event) * nr_events;
505
506 nr_pages = PFN_UP(size);
507 if (nr_pages < 0)
508 return -EINVAL;
509
510 file = aio_private_file(ctx, nr_pages);
511 if (IS_ERR(file)) {
512 ctx->aio_ring_file = NULL;
513 return -ENOMEM;
514 }
515
516 ctx->aio_ring_file = file;
517 nr_events = (PAGE_SIZE * nr_pages - sizeof(struct aio_ring))
518 / sizeof(struct io_event);
519
520 ctx->ring_pages = ctx->internal_pages;
521 if (nr_pages > AIO_RING_PAGES) {
522 ctx->ring_pages = kcalloc(nr_pages, sizeof(struct page *),
523 GFP_KERNEL);
524 if (!ctx->ring_pages) {
525 put_aio_ring_file(ctx);
526 return -ENOMEM;
527 }
528 }
529
530 for (i = 0; i < nr_pages; i++) {
531 struct page *page;
532 page = find_or_create_page(file->f_mapping,
533 i, GFP_HIGHUSER | __GFP_ZERO);
534 if (!page)
535 break;
536 pr_debug("pid(%d) page[%d]->count=%d\n",
537 current->pid, i, page_count(page));
538 SetPageUptodate(page);
539 unlock_page(page);
540
541 ctx->ring_pages[i] = page;
542 }
543 ctx->nr_pages = i;
544
545 if (unlikely(i != nr_pages)) {
546 aio_free_ring(ctx);
547 return -ENOMEM;
548 }
549
550 ctx->mmap_size = nr_pages * PAGE_SIZE;
551 pr_debug("attempting mmap of %lu bytes\n", ctx->mmap_size);
552
553 if (mmap_write_lock_killable(mm)) {
554 ctx->mmap_size = 0;
555 aio_free_ring(ctx);
556 return -EINTR;
557 }
558
559 ctx->mmap_base = do_mmap(ctx->aio_ring_file, 0, ctx->mmap_size,
560 PROT_READ | PROT_WRITE,
561 MAP_SHARED, 0, &unused, NULL);
562 mmap_write_unlock(mm);
563 if (IS_ERR((void *)ctx->mmap_base)) {
564 ctx->mmap_size = 0;
565 aio_free_ring(ctx);
566 return -ENOMEM;
567 }
568
569 pr_debug("mmap address: 0x%08lx\n", ctx->mmap_base);
570
571 ctx->user_id = ctx->mmap_base;
572 ctx->nr_events = nr_events; /* trusted copy */
573
574 ring = kmap_atomic(ctx->ring_pages[0]);
575 ring->nr = nr_events; /* user copy */
576 ring->id = ~0U;
577 ring->head = ring->tail = 0;
578 ring->magic = AIO_RING_MAGIC;
579 ring->compat_features = AIO_RING_COMPAT_FEATURES;
580 ring->incompat_features = AIO_RING_INCOMPAT_FEATURES;
581 ring->header_length = sizeof(struct aio_ring);
582 kunmap_atomic(ring);
583 flush_dcache_page(ctx->ring_pages[0]);
584
585 return 0;
586 }
587
588 #define AIO_EVENTS_PER_PAGE (PAGE_SIZE / sizeof(struct io_event))
589 #define AIO_EVENTS_FIRST_PAGE ((PAGE_SIZE - sizeof(struct aio_ring)) / sizeof(struct io_event))
590 #define AIO_EVENTS_OFFSET (AIO_EVENTS_PER_PAGE - AIO_EVENTS_FIRST_PAGE)
591
kiocb_set_cancel_fn(struct kiocb * iocb,kiocb_cancel_fn * cancel)592 void kiocb_set_cancel_fn(struct kiocb *iocb, kiocb_cancel_fn *cancel)
593 {
594 struct aio_kiocb *req = container_of(iocb, struct aio_kiocb, rw);
595 struct kioctx *ctx = req->ki_ctx;
596 unsigned long flags;
597
598 /*
599 * kiocb didn't come from aio or is neither a read nor a write, hence
600 * ignore it.
601 */
602 if (!(iocb->ki_flags & IOCB_AIO_RW))
603 return;
604
605 if (WARN_ON_ONCE(!list_empty(&req->ki_list)))
606 return;
607
608 spin_lock_irqsave(&ctx->ctx_lock, flags);
609 list_add_tail(&req->ki_list, &ctx->active_reqs);
610 req->ki_cancel = cancel;
611 spin_unlock_irqrestore(&ctx->ctx_lock, flags);
612 }
613 EXPORT_SYMBOL(kiocb_set_cancel_fn);
614
615 /*
616 * free_ioctx() should be RCU delayed to synchronize against the RCU
617 * protected lookup_ioctx() and also needs process context to call
618 * aio_free_ring(). Use rcu_work.
619 */
free_ioctx(struct work_struct * work)620 static void free_ioctx(struct work_struct *work)
621 {
622 struct kioctx *ctx = container_of(to_rcu_work(work), struct kioctx,
623 free_rwork);
624 pr_debug("freeing %p\n", ctx);
625
626 aio_free_ring(ctx);
627 free_percpu(ctx->cpu);
628 percpu_ref_exit(&ctx->reqs);
629 percpu_ref_exit(&ctx->users);
630 kmem_cache_free(kioctx_cachep, ctx);
631 }
632
free_ioctx_reqs(struct percpu_ref * ref)633 static void free_ioctx_reqs(struct percpu_ref *ref)
634 {
635 struct kioctx *ctx = container_of(ref, struct kioctx, reqs);
636
637 /* At this point we know that there are no any in-flight requests */
638 if (ctx->rq_wait && atomic_dec_and_test(&ctx->rq_wait->count))
639 complete(&ctx->rq_wait->comp);
640
641 /* Synchronize against RCU protected table->table[] dereferences */
642 INIT_RCU_WORK(&ctx->free_rwork, free_ioctx);
643 queue_rcu_work(system_wq, &ctx->free_rwork);
644 }
645
646 /*
647 * When this function runs, the kioctx has been removed from the "hash table"
648 * and ctx->users has dropped to 0, so we know no more kiocbs can be submitted -
649 * now it's safe to cancel any that need to be.
650 */
free_ioctx_users(struct percpu_ref * ref)651 static void free_ioctx_users(struct percpu_ref *ref)
652 {
653 struct kioctx *ctx = container_of(ref, struct kioctx, users);
654 struct aio_kiocb *req;
655
656 spin_lock_irq(&ctx->ctx_lock);
657
658 while (!list_empty(&ctx->active_reqs)) {
659 req = list_first_entry(&ctx->active_reqs,
660 struct aio_kiocb, ki_list);
661 req->ki_cancel(&req->rw);
662 list_del_init(&req->ki_list);
663 }
664
665 spin_unlock_irq(&ctx->ctx_lock);
666
667 percpu_ref_kill(&ctx->reqs);
668 percpu_ref_put(&ctx->reqs);
669 }
670
ioctx_add_table(struct kioctx * ctx,struct mm_struct * mm)671 static int ioctx_add_table(struct kioctx *ctx, struct mm_struct *mm)
672 {
673 unsigned i, new_nr;
674 struct kioctx_table *table, *old;
675 struct aio_ring *ring;
676
677 spin_lock(&mm->ioctx_lock);
678 table = rcu_dereference_raw(mm->ioctx_table);
679
680 while (1) {
681 if (table)
682 for (i = 0; i < table->nr; i++)
683 if (!rcu_access_pointer(table->table[i])) {
684 ctx->id = i;
685 rcu_assign_pointer(table->table[i], ctx);
686 spin_unlock(&mm->ioctx_lock);
687
688 /* While kioctx setup is in progress,
689 * we are protected from page migration
690 * changes ring_pages by ->ring_lock.
691 */
692 ring = kmap_atomic(ctx->ring_pages[0]);
693 ring->id = ctx->id;
694 kunmap_atomic(ring);
695 return 0;
696 }
697
698 new_nr = (table ? table->nr : 1) * 4;
699 spin_unlock(&mm->ioctx_lock);
700
701 table = kzalloc(struct_size(table, table, new_nr), GFP_KERNEL);
702 if (!table)
703 return -ENOMEM;
704
705 table->nr = new_nr;
706
707 spin_lock(&mm->ioctx_lock);
708 old = rcu_dereference_raw(mm->ioctx_table);
709
710 if (!old) {
711 rcu_assign_pointer(mm->ioctx_table, table);
712 } else if (table->nr > old->nr) {
713 memcpy(table->table, old->table,
714 old->nr * sizeof(struct kioctx *));
715
716 rcu_assign_pointer(mm->ioctx_table, table);
717 kfree_rcu(old, rcu);
718 } else {
719 kfree(table);
720 table = old;
721 }
722 }
723 }
724
aio_nr_sub(unsigned nr)725 static void aio_nr_sub(unsigned nr)
726 {
727 spin_lock(&aio_nr_lock);
728 if (WARN_ON(aio_nr - nr > aio_nr))
729 aio_nr = 0;
730 else
731 aio_nr -= nr;
732 spin_unlock(&aio_nr_lock);
733 }
734
735 /* ioctx_alloc
736 * Allocates and initializes an ioctx. Returns an ERR_PTR if it failed.
737 */
ioctx_alloc(unsigned nr_events)738 static struct kioctx *ioctx_alloc(unsigned nr_events)
739 {
740 struct mm_struct *mm = current->mm;
741 struct kioctx *ctx;
742 int err = -ENOMEM;
743
744 /*
745 * Store the original nr_events -- what userspace passed to io_setup(),
746 * for counting against the global limit -- before it changes.
747 */
748 unsigned int max_reqs = nr_events;
749
750 /*
751 * We keep track of the number of available ringbuffer slots, to prevent
752 * overflow (reqs_available), and we also use percpu counters for this.
753 *
754 * So since up to half the slots might be on other cpu's percpu counters
755 * and unavailable, double nr_events so userspace sees what they
756 * expected: additionally, we move req_batch slots to/from percpu
757 * counters at a time, so make sure that isn't 0:
758 */
759 nr_events = max(nr_events, num_possible_cpus() * 4);
760 nr_events *= 2;
761
762 /* Prevent overflows */
763 if (nr_events > (0x10000000U / sizeof(struct io_event))) {
764 pr_debug("ENOMEM: nr_events too high\n");
765 return ERR_PTR(-EINVAL);
766 }
767
768 if (!nr_events || (unsigned long)max_reqs > aio_max_nr)
769 return ERR_PTR(-EAGAIN);
770
771 ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL);
772 if (!ctx)
773 return ERR_PTR(-ENOMEM);
774
775 ctx->max_reqs = max_reqs;
776
777 spin_lock_init(&ctx->ctx_lock);
778 spin_lock_init(&ctx->completion_lock);
779 mutex_init(&ctx->ring_lock);
780 /* Protect against page migration throughout kiotx setup by keeping
781 * the ring_lock mutex held until setup is complete. */
782 mutex_lock(&ctx->ring_lock);
783 init_waitqueue_head(&ctx->wait);
784
785 INIT_LIST_HEAD(&ctx->active_reqs);
786
787 if (percpu_ref_init(&ctx->users, free_ioctx_users, 0, GFP_KERNEL))
788 goto err;
789
790 if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs, 0, GFP_KERNEL))
791 goto err;
792
793 ctx->cpu = alloc_percpu(struct kioctx_cpu);
794 if (!ctx->cpu)
795 goto err;
796
797 err = aio_setup_ring(ctx, nr_events);
798 if (err < 0)
799 goto err;
800
801 atomic_set(&ctx->reqs_available, ctx->nr_events - 1);
802 ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4);
803 if (ctx->req_batch < 1)
804 ctx->req_batch = 1;
805
806 /* limit the number of system wide aios */
807 spin_lock(&aio_nr_lock);
808 if (aio_nr + ctx->max_reqs > aio_max_nr ||
809 aio_nr + ctx->max_reqs < aio_nr) {
810 spin_unlock(&aio_nr_lock);
811 err = -EAGAIN;
812 goto err_ctx;
813 }
814 aio_nr += ctx->max_reqs;
815 spin_unlock(&aio_nr_lock);
816
817 percpu_ref_get(&ctx->users); /* io_setup() will drop this ref */
818 percpu_ref_get(&ctx->reqs); /* free_ioctx_users() will drop this */
819
820 err = ioctx_add_table(ctx, mm);
821 if (err)
822 goto err_cleanup;
823
824 /* Release the ring_lock mutex now that all setup is complete. */
825 mutex_unlock(&ctx->ring_lock);
826
827 pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
828 ctx, ctx->user_id, mm, ctx->nr_events);
829 return ctx;
830
831 err_cleanup:
832 aio_nr_sub(ctx->max_reqs);
833 err_ctx:
834 atomic_set(&ctx->dead, 1);
835 if (ctx->mmap_size)
836 vm_munmap(ctx->mmap_base, ctx->mmap_size);
837 aio_free_ring(ctx);
838 err:
839 mutex_unlock(&ctx->ring_lock);
840 free_percpu(ctx->cpu);
841 percpu_ref_exit(&ctx->reqs);
842 percpu_ref_exit(&ctx->users);
843 kmem_cache_free(kioctx_cachep, ctx);
844 pr_debug("error allocating ioctx %d\n", err);
845 return ERR_PTR(err);
846 }
847
848 /* kill_ioctx
849 * Cancels all outstanding aio requests on an aio context. Used
850 * when the processes owning a context have all exited to encourage
851 * the rapid destruction of the kioctx.
852 */
kill_ioctx(struct mm_struct * mm,struct kioctx * ctx,struct ctx_rq_wait * wait)853 static int kill_ioctx(struct mm_struct *mm, struct kioctx *ctx,
854 struct ctx_rq_wait *wait)
855 {
856 struct kioctx_table *table;
857
858 spin_lock(&mm->ioctx_lock);
859 if (atomic_xchg(&ctx->dead, 1)) {
860 spin_unlock(&mm->ioctx_lock);
861 return -EINVAL;
862 }
863
864 table = rcu_dereference_raw(mm->ioctx_table);
865 WARN_ON(ctx != rcu_access_pointer(table->table[ctx->id]));
866 RCU_INIT_POINTER(table->table[ctx->id], NULL);
867 spin_unlock(&mm->ioctx_lock);
868
869 /* free_ioctx_reqs() will do the necessary RCU synchronization */
870 wake_up_all(&ctx->wait);
871
872 /*
873 * It'd be more correct to do this in free_ioctx(), after all
874 * the outstanding kiocbs have finished - but by then io_destroy
875 * has already returned, so io_setup() could potentially return
876 * -EAGAIN with no ioctxs actually in use (as far as userspace
877 * could tell).
878 */
879 aio_nr_sub(ctx->max_reqs);
880
881 if (ctx->mmap_size)
882 vm_munmap(ctx->mmap_base, ctx->mmap_size);
883
884 ctx->rq_wait = wait;
885 percpu_ref_kill(&ctx->users);
886 return 0;
887 }
888
889 /*
890 * exit_aio: called when the last user of mm goes away. At this point, there is
891 * no way for any new requests to be submited or any of the io_* syscalls to be
892 * called on the context.
893 *
894 * There may be outstanding kiocbs, but free_ioctx() will explicitly wait on
895 * them.
896 */
exit_aio(struct mm_struct * mm)897 void exit_aio(struct mm_struct *mm)
898 {
899 struct kioctx_table *table = rcu_dereference_raw(mm->ioctx_table);
900 struct ctx_rq_wait wait;
901 int i, skipped;
902
903 if (!table)
904 return;
905
906 atomic_set(&wait.count, table->nr);
907 init_completion(&wait.comp);
908
909 skipped = 0;
910 for (i = 0; i < table->nr; ++i) {
911 struct kioctx *ctx =
912 rcu_dereference_protected(table->table[i], true);
913
914 if (!ctx) {
915 skipped++;
916 continue;
917 }
918
919 /*
920 * We don't need to bother with munmap() here - exit_mmap(mm)
921 * is coming and it'll unmap everything. And we simply can't,
922 * this is not necessarily our ->mm.
923 * Since kill_ioctx() uses non-zero ->mmap_size as indicator
924 * that it needs to unmap the area, just set it to 0.
925 */
926 ctx->mmap_size = 0;
927 kill_ioctx(mm, ctx, &wait);
928 }
929
930 if (!atomic_sub_and_test(skipped, &wait.count)) {
931 /* Wait until all IO for the context are done. */
932 wait_for_completion(&wait.comp);
933 }
934
935 RCU_INIT_POINTER(mm->ioctx_table, NULL);
936 kfree(table);
937 }
938
put_reqs_available(struct kioctx * ctx,unsigned nr)939 static void put_reqs_available(struct kioctx *ctx, unsigned nr)
940 {
941 struct kioctx_cpu *kcpu;
942 unsigned long flags;
943
944 local_irq_save(flags);
945 kcpu = this_cpu_ptr(ctx->cpu);
946 kcpu->reqs_available += nr;
947
948 while (kcpu->reqs_available >= ctx->req_batch * 2) {
949 kcpu->reqs_available -= ctx->req_batch;
950 atomic_add(ctx->req_batch, &ctx->reqs_available);
951 }
952
953 local_irq_restore(flags);
954 }
955
__get_reqs_available(struct kioctx * ctx)956 static bool __get_reqs_available(struct kioctx *ctx)
957 {
958 struct kioctx_cpu *kcpu;
959 bool ret = false;
960 unsigned long flags;
961
962 local_irq_save(flags);
963 kcpu = this_cpu_ptr(ctx->cpu);
964 if (!kcpu->reqs_available) {
965 int avail = atomic_read(&ctx->reqs_available);
966
967 do {
968 if (avail < ctx->req_batch)
969 goto out;
970 } while (!atomic_try_cmpxchg(&ctx->reqs_available,
971 &avail, avail - ctx->req_batch));
972
973 kcpu->reqs_available += ctx->req_batch;
974 }
975
976 ret = true;
977 kcpu->reqs_available--;
978 out:
979 local_irq_restore(flags);
980 return ret;
981 }
982
983 /* refill_reqs_available
984 * Updates the reqs_available reference counts used for tracking the
985 * number of free slots in the completion ring. This can be called
986 * from aio_complete() (to optimistically update reqs_available) or
987 * from aio_get_req() (the we're out of events case). It must be
988 * called holding ctx->completion_lock.
989 */
refill_reqs_available(struct kioctx * ctx,unsigned head,unsigned tail)990 static void refill_reqs_available(struct kioctx *ctx, unsigned head,
991 unsigned tail)
992 {
993 unsigned events_in_ring, completed;
994
995 /* Clamp head since userland can write to it. */
996 head %= ctx->nr_events;
997 if (head <= tail)
998 events_in_ring = tail - head;
999 else
1000 events_in_ring = ctx->nr_events - (head - tail);
1001
1002 completed = ctx->completed_events;
1003 if (events_in_ring < completed)
1004 completed -= events_in_ring;
1005 else
1006 completed = 0;
1007
1008 if (!completed)
1009 return;
1010
1011 ctx->completed_events -= completed;
1012 put_reqs_available(ctx, completed);
1013 }
1014
1015 /* user_refill_reqs_available
1016 * Called to refill reqs_available when aio_get_req() encounters an
1017 * out of space in the completion ring.
1018 */
user_refill_reqs_available(struct kioctx * ctx)1019 static void user_refill_reqs_available(struct kioctx *ctx)
1020 {
1021 spin_lock_irq(&ctx->completion_lock);
1022 if (ctx->completed_events) {
1023 struct aio_ring *ring;
1024 unsigned head;
1025
1026 /* Access of ring->head may race with aio_read_events_ring()
1027 * here, but that's okay since whether we read the old version
1028 * or the new version, and either will be valid. The important
1029 * part is that head cannot pass tail since we prevent
1030 * aio_complete() from updating tail by holding
1031 * ctx->completion_lock. Even if head is invalid, the check
1032 * against ctx->completed_events below will make sure we do the
1033 * safe/right thing.
1034 */
1035 ring = kmap_atomic(ctx->ring_pages[0]);
1036 head = ring->head;
1037 kunmap_atomic(ring);
1038
1039 refill_reqs_available(ctx, head, ctx->tail);
1040 }
1041
1042 spin_unlock_irq(&ctx->completion_lock);
1043 }
1044
get_reqs_available(struct kioctx * ctx)1045 static bool get_reqs_available(struct kioctx *ctx)
1046 {
1047 if (__get_reqs_available(ctx))
1048 return true;
1049 user_refill_reqs_available(ctx);
1050 return __get_reqs_available(ctx);
1051 }
1052
1053 /* aio_get_req
1054 * Allocate a slot for an aio request.
1055 * Returns NULL if no requests are free.
1056 *
1057 * The refcount is initialized to 2 - one for the async op completion,
1058 * one for the synchronous code that does this.
1059 */
aio_get_req(struct kioctx * ctx)1060 static inline struct aio_kiocb *aio_get_req(struct kioctx *ctx)
1061 {
1062 struct aio_kiocb *req;
1063
1064 req = kmem_cache_alloc(kiocb_cachep, GFP_KERNEL);
1065 if (unlikely(!req))
1066 return NULL;
1067
1068 if (unlikely(!get_reqs_available(ctx))) {
1069 kmem_cache_free(kiocb_cachep, req);
1070 return NULL;
1071 }
1072
1073 percpu_ref_get(&ctx->reqs);
1074 req->ki_ctx = ctx;
1075 INIT_LIST_HEAD(&req->ki_list);
1076 refcount_set(&req->ki_refcnt, 2);
1077 req->ki_eventfd = NULL;
1078 return req;
1079 }
1080
lookup_ioctx(unsigned long ctx_id)1081 static struct kioctx *lookup_ioctx(unsigned long ctx_id)
1082 {
1083 struct aio_ring __user *ring = (void __user *)ctx_id;
1084 struct mm_struct *mm = current->mm;
1085 struct kioctx *ctx, *ret = NULL;
1086 struct kioctx_table *table;
1087 unsigned id;
1088
1089 if (get_user(id, &ring->id))
1090 return NULL;
1091
1092 rcu_read_lock();
1093 table = rcu_dereference(mm->ioctx_table);
1094
1095 if (!table || id >= table->nr)
1096 goto out;
1097
1098 id = array_index_nospec(id, table->nr);
1099 ctx = rcu_dereference(table->table[id]);
1100 if (ctx && ctx->user_id == ctx_id) {
1101 if (percpu_ref_tryget_live(&ctx->users))
1102 ret = ctx;
1103 }
1104 out:
1105 rcu_read_unlock();
1106 return ret;
1107 }
1108
iocb_destroy(struct aio_kiocb * iocb)1109 static inline void iocb_destroy(struct aio_kiocb *iocb)
1110 {
1111 if (iocb->ki_eventfd)
1112 eventfd_ctx_put(iocb->ki_eventfd);
1113 if (iocb->ki_filp)
1114 fput(iocb->ki_filp);
1115 percpu_ref_put(&iocb->ki_ctx->reqs);
1116 kmem_cache_free(kiocb_cachep, iocb);
1117 }
1118
1119 /* aio_complete
1120 * Called when the io request on the given iocb is complete.
1121 */
aio_complete(struct aio_kiocb * iocb)1122 static void aio_complete(struct aio_kiocb *iocb)
1123 {
1124 struct kioctx *ctx = iocb->ki_ctx;
1125 struct aio_ring *ring;
1126 struct io_event *ev_page, *event;
1127 unsigned tail, pos, head;
1128 unsigned long flags;
1129
1130 /*
1131 * Add a completion event to the ring buffer. Must be done holding
1132 * ctx->completion_lock to prevent other code from messing with the tail
1133 * pointer since we might be called from irq context.
1134 */
1135 spin_lock_irqsave(&ctx->completion_lock, flags);
1136
1137 tail = ctx->tail;
1138 pos = tail + AIO_EVENTS_OFFSET;
1139
1140 if (++tail >= ctx->nr_events)
1141 tail = 0;
1142
1143 ev_page = kmap_atomic(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
1144 event = ev_page + pos % AIO_EVENTS_PER_PAGE;
1145
1146 *event = iocb->ki_res;
1147
1148 kunmap_atomic(ev_page);
1149 flush_dcache_page(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
1150
1151 pr_debug("%p[%u]: %p: %p %Lx %Lx %Lx\n", ctx, tail, iocb,
1152 (void __user *)(unsigned long)iocb->ki_res.obj,
1153 iocb->ki_res.data, iocb->ki_res.res, iocb->ki_res.res2);
1154
1155 /* after flagging the request as done, we
1156 * must never even look at it again
1157 */
1158 smp_wmb(); /* make event visible before updating tail */
1159
1160 ctx->tail = tail;
1161
1162 ring = kmap_atomic(ctx->ring_pages[0]);
1163 head = ring->head;
1164 ring->tail = tail;
1165 kunmap_atomic(ring);
1166 flush_dcache_page(ctx->ring_pages[0]);
1167
1168 ctx->completed_events++;
1169 if (ctx->completed_events > 1)
1170 refill_reqs_available(ctx, head, tail);
1171 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1172
1173 pr_debug("added to ring %p at [%u]\n", iocb, tail);
1174
1175 /*
1176 * Check if the user asked us to deliver the result through an
1177 * eventfd. The eventfd_signal() function is safe to be called
1178 * from IRQ context.
1179 */
1180 if (iocb->ki_eventfd)
1181 eventfd_signal(iocb->ki_eventfd, 1);
1182
1183 /*
1184 * We have to order our ring_info tail store above and test
1185 * of the wait list below outside the wait lock. This is
1186 * like in wake_up_bit() where clearing a bit has to be
1187 * ordered with the unlocked test.
1188 */
1189 smp_mb();
1190
1191 if (waitqueue_active(&ctx->wait))
1192 wake_up(&ctx->wait);
1193 }
1194
iocb_put(struct aio_kiocb * iocb)1195 static inline void iocb_put(struct aio_kiocb *iocb)
1196 {
1197 if (refcount_dec_and_test(&iocb->ki_refcnt)) {
1198 aio_complete(iocb);
1199 iocb_destroy(iocb);
1200 }
1201 }
1202
1203 /* aio_read_events_ring
1204 * Pull an event off of the ioctx's event ring. Returns the number of
1205 * events fetched
1206 */
aio_read_events_ring(struct kioctx * ctx,struct io_event __user * event,long nr)1207 static long aio_read_events_ring(struct kioctx *ctx,
1208 struct io_event __user *event, long nr)
1209 {
1210 struct aio_ring *ring;
1211 unsigned head, tail, pos;
1212 long ret = 0;
1213 int copy_ret;
1214
1215 /*
1216 * The mutex can block and wake us up and that will cause
1217 * wait_event_interruptible_hrtimeout() to schedule without sleeping
1218 * and repeat. This should be rare enough that it doesn't cause
1219 * peformance issues. See the comment in read_events() for more detail.
1220 */
1221 sched_annotate_sleep();
1222 mutex_lock(&ctx->ring_lock);
1223
1224 /* Access to ->ring_pages here is protected by ctx->ring_lock. */
1225 ring = kmap_atomic(ctx->ring_pages[0]);
1226 head = ring->head;
1227 tail = ring->tail;
1228 kunmap_atomic(ring);
1229
1230 /*
1231 * Ensure that once we've read the current tail pointer, that
1232 * we also see the events that were stored up to the tail.
1233 */
1234 smp_rmb();
1235
1236 pr_debug("h%u t%u m%u\n", head, tail, ctx->nr_events);
1237
1238 if (head == tail)
1239 goto out;
1240
1241 head %= ctx->nr_events;
1242 tail %= ctx->nr_events;
1243
1244 while (ret < nr) {
1245 long avail;
1246 struct io_event *ev;
1247 struct page *page;
1248
1249 avail = (head <= tail ? tail : ctx->nr_events) - head;
1250 if (head == tail)
1251 break;
1252
1253 pos = head + AIO_EVENTS_OFFSET;
1254 page = ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE];
1255 pos %= AIO_EVENTS_PER_PAGE;
1256
1257 avail = min(avail, nr - ret);
1258 avail = min_t(long, avail, AIO_EVENTS_PER_PAGE - pos);
1259
1260 ev = kmap(page);
1261 copy_ret = copy_to_user(event + ret, ev + pos,
1262 sizeof(*ev) * avail);
1263 kunmap(page);
1264
1265 if (unlikely(copy_ret)) {
1266 ret = -EFAULT;
1267 goto out;
1268 }
1269
1270 ret += avail;
1271 head += avail;
1272 head %= ctx->nr_events;
1273 }
1274
1275 ring = kmap_atomic(ctx->ring_pages[0]);
1276 ring->head = head;
1277 kunmap_atomic(ring);
1278 flush_dcache_page(ctx->ring_pages[0]);
1279
1280 pr_debug("%li h%u t%u\n", ret, head, tail);
1281 out:
1282 mutex_unlock(&ctx->ring_lock);
1283
1284 return ret;
1285 }
1286
aio_read_events(struct kioctx * ctx,long min_nr,long nr,struct io_event __user * event,long * i)1287 static bool aio_read_events(struct kioctx *ctx, long min_nr, long nr,
1288 struct io_event __user *event, long *i)
1289 {
1290 long ret = aio_read_events_ring(ctx, event + *i, nr - *i);
1291
1292 if (ret > 0)
1293 *i += ret;
1294
1295 if (unlikely(atomic_read(&ctx->dead)))
1296 ret = -EINVAL;
1297
1298 if (!*i)
1299 *i = ret;
1300
1301 return ret < 0 || *i >= min_nr;
1302 }
1303
read_events(struct kioctx * ctx,long min_nr,long nr,struct io_event __user * event,ktime_t until)1304 static long read_events(struct kioctx *ctx, long min_nr, long nr,
1305 struct io_event __user *event,
1306 ktime_t until)
1307 {
1308 long ret = 0;
1309
1310 /*
1311 * Note that aio_read_events() is being called as the conditional - i.e.
1312 * we're calling it after prepare_to_wait() has set task state to
1313 * TASK_INTERRUPTIBLE.
1314 *
1315 * But aio_read_events() can block, and if it blocks it's going to flip
1316 * the task state back to TASK_RUNNING.
1317 *
1318 * This should be ok, provided it doesn't flip the state back to
1319 * TASK_RUNNING and return 0 too much - that causes us to spin. That
1320 * will only happen if the mutex_lock() call blocks, and we then find
1321 * the ringbuffer empty. So in practice we should be ok, but it's
1322 * something to be aware of when touching this code.
1323 */
1324 if (until == 0)
1325 aio_read_events(ctx, min_nr, nr, event, &ret);
1326 else
1327 wait_event_interruptible_hrtimeout(ctx->wait,
1328 aio_read_events(ctx, min_nr, nr, event, &ret),
1329 until);
1330 return ret;
1331 }
1332
1333 /* sys_io_setup:
1334 * Create an aio_context capable of receiving at least nr_events.
1335 * ctxp must not point to an aio_context that already exists, and
1336 * must be initialized to 0 prior to the call. On successful
1337 * creation of the aio_context, *ctxp is filled in with the resulting
1338 * handle. May fail with -EINVAL if *ctxp is not initialized,
1339 * if the specified nr_events exceeds internal limits. May fail
1340 * with -EAGAIN if the specified nr_events exceeds the user's limit
1341 * of available events. May fail with -ENOMEM if insufficient kernel
1342 * resources are available. May fail with -EFAULT if an invalid
1343 * pointer is passed for ctxp. Will fail with -ENOSYS if not
1344 * implemented.
1345 */
SYSCALL_DEFINE2(io_setup,unsigned,nr_events,aio_context_t __user *,ctxp)1346 SYSCALL_DEFINE2(io_setup, unsigned, nr_events, aio_context_t __user *, ctxp)
1347 {
1348 struct kioctx *ioctx = NULL;
1349 unsigned long ctx;
1350 long ret;
1351
1352 ret = get_user(ctx, ctxp);
1353 if (unlikely(ret))
1354 goto out;
1355
1356 ret = -EINVAL;
1357 if (unlikely(ctx || nr_events == 0)) {
1358 pr_debug("EINVAL: ctx %lu nr_events %u\n",
1359 ctx, nr_events);
1360 goto out;
1361 }
1362
1363 ioctx = ioctx_alloc(nr_events);
1364 ret = PTR_ERR(ioctx);
1365 if (!IS_ERR(ioctx)) {
1366 ret = put_user(ioctx->user_id, ctxp);
1367 if (ret)
1368 kill_ioctx(current->mm, ioctx, NULL);
1369 percpu_ref_put(&ioctx->users);
1370 }
1371
1372 out:
1373 return ret;
1374 }
1375
1376 #ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE2(io_setup,unsigned,nr_events,u32 __user *,ctx32p)1377 COMPAT_SYSCALL_DEFINE2(io_setup, unsigned, nr_events, u32 __user *, ctx32p)
1378 {
1379 struct kioctx *ioctx = NULL;
1380 unsigned long ctx;
1381 long ret;
1382
1383 ret = get_user(ctx, ctx32p);
1384 if (unlikely(ret))
1385 goto out;
1386
1387 ret = -EINVAL;
1388 if (unlikely(ctx || nr_events == 0)) {
1389 pr_debug("EINVAL: ctx %lu nr_events %u\n",
1390 ctx, nr_events);
1391 goto out;
1392 }
1393
1394 ioctx = ioctx_alloc(nr_events);
1395 ret = PTR_ERR(ioctx);
1396 if (!IS_ERR(ioctx)) {
1397 /* truncating is ok because it's a user address */
1398 ret = put_user((u32)ioctx->user_id, ctx32p);
1399 if (ret)
1400 kill_ioctx(current->mm, ioctx, NULL);
1401 percpu_ref_put(&ioctx->users);
1402 }
1403
1404 out:
1405 return ret;
1406 }
1407 #endif
1408
1409 /* sys_io_destroy:
1410 * Destroy the aio_context specified. May cancel any outstanding
1411 * AIOs and block on completion. Will fail with -ENOSYS if not
1412 * implemented. May fail with -EINVAL if the context pointed to
1413 * is invalid.
1414 */
SYSCALL_DEFINE1(io_destroy,aio_context_t,ctx)1415 SYSCALL_DEFINE1(io_destroy, aio_context_t, ctx)
1416 {
1417 struct kioctx *ioctx = lookup_ioctx(ctx);
1418 if (likely(NULL != ioctx)) {
1419 struct ctx_rq_wait wait;
1420 int ret;
1421
1422 init_completion(&wait.comp);
1423 atomic_set(&wait.count, 1);
1424
1425 /* Pass requests_done to kill_ioctx() where it can be set
1426 * in a thread-safe way. If we try to set it here then we have
1427 * a race condition if two io_destroy() called simultaneously.
1428 */
1429 ret = kill_ioctx(current->mm, ioctx, &wait);
1430 percpu_ref_put(&ioctx->users);
1431
1432 /* Wait until all IO for the context are done. Otherwise kernel
1433 * keep using user-space buffers even if user thinks the context
1434 * is destroyed.
1435 */
1436 if (!ret)
1437 wait_for_completion(&wait.comp);
1438
1439 return ret;
1440 }
1441 pr_debug("EINVAL: invalid context id\n");
1442 return -EINVAL;
1443 }
1444
aio_remove_iocb(struct aio_kiocb * iocb)1445 static void aio_remove_iocb(struct aio_kiocb *iocb)
1446 {
1447 struct kioctx *ctx = iocb->ki_ctx;
1448 unsigned long flags;
1449
1450 spin_lock_irqsave(&ctx->ctx_lock, flags);
1451 list_del(&iocb->ki_list);
1452 spin_unlock_irqrestore(&ctx->ctx_lock, flags);
1453 }
1454
aio_complete_rw(struct kiocb * kiocb,long res)1455 static void aio_complete_rw(struct kiocb *kiocb, long res)
1456 {
1457 struct aio_kiocb *iocb = container_of(kiocb, struct aio_kiocb, rw);
1458
1459 if (!list_empty_careful(&iocb->ki_list))
1460 aio_remove_iocb(iocb);
1461
1462 if (kiocb->ki_flags & IOCB_WRITE) {
1463 struct inode *inode = file_inode(kiocb->ki_filp);
1464
1465 /*
1466 * Tell lockdep we inherited freeze protection from submission
1467 * thread.
1468 */
1469 if (S_ISREG(inode->i_mode))
1470 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
1471 file_end_write(kiocb->ki_filp);
1472 }
1473
1474 iocb->ki_res.res = res;
1475 iocb->ki_res.res2 = 0;
1476 iocb_put(iocb);
1477 }
1478
aio_prep_rw(struct kiocb * req,const struct iocb * iocb)1479 static int aio_prep_rw(struct kiocb *req, const struct iocb *iocb)
1480 {
1481 int ret;
1482
1483 req->ki_complete = aio_complete_rw;
1484 req->private = NULL;
1485 req->ki_pos = iocb->aio_offset;
1486 req->ki_flags = req->ki_filp->f_iocb_flags | IOCB_AIO_RW;
1487 if (iocb->aio_flags & IOCB_FLAG_RESFD)
1488 req->ki_flags |= IOCB_EVENTFD;
1489 if (iocb->aio_flags & IOCB_FLAG_IOPRIO) {
1490 /*
1491 * If the IOCB_FLAG_IOPRIO flag of aio_flags is set, then
1492 * aio_reqprio is interpreted as an I/O scheduling
1493 * class and priority.
1494 */
1495 ret = ioprio_check_cap(iocb->aio_reqprio);
1496 if (ret) {
1497 pr_debug("aio ioprio check cap error: %d\n", ret);
1498 return ret;
1499 }
1500
1501 req->ki_ioprio = iocb->aio_reqprio;
1502 } else
1503 req->ki_ioprio = get_current_ioprio();
1504
1505 ret = kiocb_set_rw_flags(req, iocb->aio_rw_flags);
1506 if (unlikely(ret))
1507 return ret;
1508
1509 req->ki_flags &= ~IOCB_HIPRI; /* no one is going to poll for this I/O */
1510 return 0;
1511 }
1512
aio_setup_rw(int rw,const struct iocb * iocb,struct iovec ** iovec,bool vectored,bool compat,struct iov_iter * iter)1513 static ssize_t aio_setup_rw(int rw, const struct iocb *iocb,
1514 struct iovec **iovec, bool vectored, bool compat,
1515 struct iov_iter *iter)
1516 {
1517 void __user *buf = (void __user *)(uintptr_t)iocb->aio_buf;
1518 size_t len = iocb->aio_nbytes;
1519
1520 if (!vectored) {
1521 ssize_t ret = import_single_range(rw, buf, len, *iovec, iter);
1522 *iovec = NULL;
1523 return ret;
1524 }
1525
1526 return __import_iovec(rw, buf, len, UIO_FASTIOV, iovec, iter, compat);
1527 }
1528
aio_rw_done(struct kiocb * req,ssize_t ret)1529 static inline void aio_rw_done(struct kiocb *req, ssize_t ret)
1530 {
1531 switch (ret) {
1532 case -EIOCBQUEUED:
1533 break;
1534 case -ERESTARTSYS:
1535 case -ERESTARTNOINTR:
1536 case -ERESTARTNOHAND:
1537 case -ERESTART_RESTARTBLOCK:
1538 /*
1539 * There's no easy way to restart the syscall since other AIO's
1540 * may be already running. Just fail this IO with EINTR.
1541 */
1542 ret = -EINTR;
1543 fallthrough;
1544 default:
1545 req->ki_complete(req, ret);
1546 }
1547 }
1548
aio_read(struct kiocb * req,const struct iocb * iocb,bool vectored,bool compat)1549 static int aio_read(struct kiocb *req, const struct iocb *iocb,
1550 bool vectored, bool compat)
1551 {
1552 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1553 struct iov_iter iter;
1554 struct file *file;
1555 int ret;
1556
1557 ret = aio_prep_rw(req, iocb);
1558 if (ret)
1559 return ret;
1560 file = req->ki_filp;
1561 if (unlikely(!(file->f_mode & FMODE_READ)))
1562 return -EBADF;
1563 if (unlikely(!file->f_op->read_iter))
1564 return -EINVAL;
1565
1566 ret = aio_setup_rw(ITER_DEST, iocb, &iovec, vectored, compat, &iter);
1567 if (ret < 0)
1568 return ret;
1569 ret = rw_verify_area(READ, file, &req->ki_pos, iov_iter_count(&iter));
1570 if (!ret)
1571 aio_rw_done(req, call_read_iter(file, req, &iter));
1572 kfree(iovec);
1573 return ret;
1574 }
1575
aio_write(struct kiocb * req,const struct iocb * iocb,bool vectored,bool compat)1576 static int aio_write(struct kiocb *req, const struct iocb *iocb,
1577 bool vectored, bool compat)
1578 {
1579 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1580 struct iov_iter iter;
1581 struct file *file;
1582 int ret;
1583
1584 ret = aio_prep_rw(req, iocb);
1585 if (ret)
1586 return ret;
1587 file = req->ki_filp;
1588
1589 if (unlikely(!(file->f_mode & FMODE_WRITE)))
1590 return -EBADF;
1591 if (unlikely(!file->f_op->write_iter))
1592 return -EINVAL;
1593
1594 ret = aio_setup_rw(ITER_SOURCE, iocb, &iovec, vectored, compat, &iter);
1595 if (ret < 0)
1596 return ret;
1597 ret = rw_verify_area(WRITE, file, &req->ki_pos, iov_iter_count(&iter));
1598 if (!ret) {
1599 /*
1600 * Open-code file_start_write here to grab freeze protection,
1601 * which will be released by another thread in
1602 * aio_complete_rw(). Fool lockdep by telling it the lock got
1603 * released so that it doesn't complain about the held lock when
1604 * we return to userspace.
1605 */
1606 if (S_ISREG(file_inode(file)->i_mode)) {
1607 sb_start_write(file_inode(file)->i_sb);
1608 __sb_writers_release(file_inode(file)->i_sb, SB_FREEZE_WRITE);
1609 }
1610 req->ki_flags |= IOCB_WRITE;
1611 aio_rw_done(req, call_write_iter(file, req, &iter));
1612 }
1613 kfree(iovec);
1614 return ret;
1615 }
1616
aio_fsync_work(struct work_struct * work)1617 static void aio_fsync_work(struct work_struct *work)
1618 {
1619 struct aio_kiocb *iocb = container_of(work, struct aio_kiocb, fsync.work);
1620 const struct cred *old_cred = override_creds(iocb->fsync.creds);
1621
1622 iocb->ki_res.res = vfs_fsync(iocb->fsync.file, iocb->fsync.datasync);
1623 revert_creds(old_cred);
1624 put_cred(iocb->fsync.creds);
1625 iocb_put(iocb);
1626 }
1627
aio_fsync(struct fsync_iocb * req,const struct iocb * iocb,bool datasync)1628 static int aio_fsync(struct fsync_iocb *req, const struct iocb *iocb,
1629 bool datasync)
1630 {
1631 if (unlikely(iocb->aio_buf || iocb->aio_offset || iocb->aio_nbytes ||
1632 iocb->aio_rw_flags))
1633 return -EINVAL;
1634
1635 if (unlikely(!req->file->f_op->fsync))
1636 return -EINVAL;
1637
1638 req->creds = prepare_creds();
1639 if (!req->creds)
1640 return -ENOMEM;
1641
1642 req->datasync = datasync;
1643 INIT_WORK(&req->work, aio_fsync_work);
1644 schedule_work(&req->work);
1645 return 0;
1646 }
1647
aio_poll_put_work(struct work_struct * work)1648 static void aio_poll_put_work(struct work_struct *work)
1649 {
1650 struct poll_iocb *req = container_of(work, struct poll_iocb, work);
1651 struct aio_kiocb *iocb = container_of(req, struct aio_kiocb, poll);
1652
1653 iocb_put(iocb);
1654 }
1655
1656 /*
1657 * Safely lock the waitqueue which the request is on, synchronizing with the
1658 * case where the ->poll() provider decides to free its waitqueue early.
1659 *
1660 * Returns true on success, meaning that req->head->lock was locked, req->wait
1661 * is on req->head, and an RCU read lock was taken. Returns false if the
1662 * request was already removed from its waitqueue (which might no longer exist).
1663 */
poll_iocb_lock_wq(struct poll_iocb * req)1664 static bool poll_iocb_lock_wq(struct poll_iocb *req)
1665 {
1666 wait_queue_head_t *head;
1667
1668 /*
1669 * While we hold the waitqueue lock and the waitqueue is nonempty,
1670 * wake_up_pollfree() will wait for us. However, taking the waitqueue
1671 * lock in the first place can race with the waitqueue being freed.
1672 *
1673 * We solve this as eventpoll does: by taking advantage of the fact that
1674 * all users of wake_up_pollfree() will RCU-delay the actual free. If
1675 * we enter rcu_read_lock() and see that the pointer to the queue is
1676 * non-NULL, we can then lock it without the memory being freed out from
1677 * under us, then check whether the request is still on the queue.
1678 *
1679 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
1680 * case the caller deletes the entry from the queue, leaving it empty.
1681 * In that case, only RCU prevents the queue memory from being freed.
1682 */
1683 rcu_read_lock();
1684 head = smp_load_acquire(&req->head);
1685 if (head) {
1686 spin_lock(&head->lock);
1687 if (!list_empty(&req->wait.entry))
1688 return true;
1689 spin_unlock(&head->lock);
1690 }
1691 rcu_read_unlock();
1692 return false;
1693 }
1694
poll_iocb_unlock_wq(struct poll_iocb * req)1695 static void poll_iocb_unlock_wq(struct poll_iocb *req)
1696 {
1697 spin_unlock(&req->head->lock);
1698 rcu_read_unlock();
1699 }
1700
aio_poll_complete_work(struct work_struct * work)1701 static void aio_poll_complete_work(struct work_struct *work)
1702 {
1703 struct poll_iocb *req = container_of(work, struct poll_iocb, work);
1704 struct aio_kiocb *iocb = container_of(req, struct aio_kiocb, poll);
1705 struct poll_table_struct pt = { ._key = req->events };
1706 struct kioctx *ctx = iocb->ki_ctx;
1707 __poll_t mask = 0;
1708
1709 if (!READ_ONCE(req->cancelled))
1710 mask = vfs_poll(req->file, &pt) & req->events;
1711
1712 /*
1713 * Note that ->ki_cancel callers also delete iocb from active_reqs after
1714 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
1715 * synchronize with them. In the cancellation case the list_del_init
1716 * itself is not actually needed, but harmless so we keep it in to
1717 * avoid further branches in the fast path.
1718 */
1719 spin_lock_irq(&ctx->ctx_lock);
1720 if (poll_iocb_lock_wq(req)) {
1721 if (!mask && !READ_ONCE(req->cancelled)) {
1722 /*
1723 * The request isn't actually ready to be completed yet.
1724 * Reschedule completion if another wakeup came in.
1725 */
1726 if (req->work_need_resched) {
1727 schedule_work(&req->work);
1728 req->work_need_resched = false;
1729 } else {
1730 req->work_scheduled = false;
1731 }
1732 poll_iocb_unlock_wq(req);
1733 spin_unlock_irq(&ctx->ctx_lock);
1734 return;
1735 }
1736 list_del_init(&req->wait.entry);
1737 poll_iocb_unlock_wq(req);
1738 } /* else, POLLFREE has freed the waitqueue, so we must complete */
1739 list_del_init(&iocb->ki_list);
1740 iocb->ki_res.res = mangle_poll(mask);
1741 spin_unlock_irq(&ctx->ctx_lock);
1742
1743 iocb_put(iocb);
1744 }
1745
1746 /* assumes we are called with irqs disabled */
aio_poll_cancel(struct kiocb * iocb)1747 static int aio_poll_cancel(struct kiocb *iocb)
1748 {
1749 struct aio_kiocb *aiocb = container_of(iocb, struct aio_kiocb, rw);
1750 struct poll_iocb *req = &aiocb->poll;
1751
1752 if (poll_iocb_lock_wq(req)) {
1753 WRITE_ONCE(req->cancelled, true);
1754 if (!req->work_scheduled) {
1755 schedule_work(&aiocb->poll.work);
1756 req->work_scheduled = true;
1757 }
1758 poll_iocb_unlock_wq(req);
1759 } /* else, the request was force-cancelled by POLLFREE already */
1760
1761 return 0;
1762 }
1763
aio_poll_wake(struct wait_queue_entry * wait,unsigned mode,int sync,void * key)1764 static int aio_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
1765 void *key)
1766 {
1767 struct poll_iocb *req = container_of(wait, struct poll_iocb, wait);
1768 struct aio_kiocb *iocb = container_of(req, struct aio_kiocb, poll);
1769 __poll_t mask = key_to_poll(key);
1770 unsigned long flags;
1771
1772 /* for instances that support it check for an event match first: */
1773 if (mask && !(mask & req->events))
1774 return 0;
1775
1776 /*
1777 * Complete the request inline if possible. This requires that three
1778 * conditions be met:
1779 * 1. An event mask must have been passed. If a plain wakeup was done
1780 * instead, then mask == 0 and we have to call vfs_poll() to get
1781 * the events, so inline completion isn't possible.
1782 * 2. The completion work must not have already been scheduled.
1783 * 3. ctx_lock must not be busy. We have to use trylock because we
1784 * already hold the waitqueue lock, so this inverts the normal
1785 * locking order. Use irqsave/irqrestore because not all
1786 * filesystems (e.g. fuse) call this function with IRQs disabled,
1787 * yet IRQs have to be disabled before ctx_lock is obtained.
1788 */
1789 if (mask && !req->work_scheduled &&
1790 spin_trylock_irqsave(&iocb->ki_ctx->ctx_lock, flags)) {
1791 struct kioctx *ctx = iocb->ki_ctx;
1792
1793 list_del_init(&req->wait.entry);
1794 list_del(&iocb->ki_list);
1795 iocb->ki_res.res = mangle_poll(mask);
1796 if (iocb->ki_eventfd && !eventfd_signal_allowed()) {
1797 iocb = NULL;
1798 INIT_WORK(&req->work, aio_poll_put_work);
1799 schedule_work(&req->work);
1800 }
1801 spin_unlock_irqrestore(&ctx->ctx_lock, flags);
1802 if (iocb)
1803 iocb_put(iocb);
1804 } else {
1805 /*
1806 * Schedule the completion work if needed. If it was already
1807 * scheduled, record that another wakeup came in.
1808 *
1809 * Don't remove the request from the waitqueue here, as it might
1810 * not actually be complete yet (we won't know until vfs_poll()
1811 * is called), and we must not miss any wakeups. POLLFREE is an
1812 * exception to this; see below.
1813 */
1814 if (req->work_scheduled) {
1815 req->work_need_resched = true;
1816 } else {
1817 schedule_work(&req->work);
1818 req->work_scheduled = true;
1819 }
1820
1821 /*
1822 * If the waitqueue is being freed early but we can't complete
1823 * the request inline, we have to tear down the request as best
1824 * we can. That means immediately removing the request from its
1825 * waitqueue and preventing all further accesses to the
1826 * waitqueue via the request. We also need to schedule the
1827 * completion work (done above). Also mark the request as
1828 * cancelled, to potentially skip an unneeded call to ->poll().
1829 */
1830 if (mask & POLLFREE) {
1831 WRITE_ONCE(req->cancelled, true);
1832 list_del_init(&req->wait.entry);
1833
1834 /*
1835 * Careful: this *must* be the last step, since as soon
1836 * as req->head is NULL'ed out, the request can be
1837 * completed and freed, since aio_poll_complete_work()
1838 * will no longer need to take the waitqueue lock.
1839 */
1840 smp_store_release(&req->head, NULL);
1841 }
1842 }
1843 return 1;
1844 }
1845
1846 struct aio_poll_table {
1847 struct poll_table_struct pt;
1848 struct aio_kiocb *iocb;
1849 bool queued;
1850 int error;
1851 };
1852
1853 static void
aio_poll_queue_proc(struct file * file,struct wait_queue_head * head,struct poll_table_struct * p)1854 aio_poll_queue_proc(struct file *file, struct wait_queue_head *head,
1855 struct poll_table_struct *p)
1856 {
1857 struct aio_poll_table *pt = container_of(p, struct aio_poll_table, pt);
1858
1859 /* multiple wait queues per file are not supported */
1860 if (unlikely(pt->queued)) {
1861 pt->error = -EINVAL;
1862 return;
1863 }
1864
1865 pt->queued = true;
1866 pt->error = 0;
1867 pt->iocb->poll.head = head;
1868 add_wait_queue(head, &pt->iocb->poll.wait);
1869 }
1870
aio_poll(struct aio_kiocb * aiocb,const struct iocb * iocb)1871 static int aio_poll(struct aio_kiocb *aiocb, const struct iocb *iocb)
1872 {
1873 struct kioctx *ctx = aiocb->ki_ctx;
1874 struct poll_iocb *req = &aiocb->poll;
1875 struct aio_poll_table apt;
1876 bool cancel = false;
1877 __poll_t mask;
1878
1879 /* reject any unknown events outside the normal event mask. */
1880 if ((u16)iocb->aio_buf != iocb->aio_buf)
1881 return -EINVAL;
1882 /* reject fields that are not defined for poll */
1883 if (iocb->aio_offset || iocb->aio_nbytes || iocb->aio_rw_flags)
1884 return -EINVAL;
1885
1886 INIT_WORK(&req->work, aio_poll_complete_work);
1887 req->events = demangle_poll(iocb->aio_buf) | EPOLLERR | EPOLLHUP;
1888
1889 req->head = NULL;
1890 req->cancelled = false;
1891 req->work_scheduled = false;
1892 req->work_need_resched = false;
1893
1894 apt.pt._qproc = aio_poll_queue_proc;
1895 apt.pt._key = req->events;
1896 apt.iocb = aiocb;
1897 apt.queued = false;
1898 apt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
1899
1900 /* initialized the list so that we can do list_empty checks */
1901 INIT_LIST_HEAD(&req->wait.entry);
1902 init_waitqueue_func_entry(&req->wait, aio_poll_wake);
1903
1904 mask = vfs_poll(req->file, &apt.pt) & req->events;
1905 spin_lock_irq(&ctx->ctx_lock);
1906 if (likely(apt.queued)) {
1907 bool on_queue = poll_iocb_lock_wq(req);
1908
1909 if (!on_queue || req->work_scheduled) {
1910 /*
1911 * aio_poll_wake() already either scheduled the async
1912 * completion work, or completed the request inline.
1913 */
1914 if (apt.error) /* unsupported case: multiple queues */
1915 cancel = true;
1916 apt.error = 0;
1917 mask = 0;
1918 }
1919 if (mask || apt.error) {
1920 /* Steal to complete synchronously. */
1921 list_del_init(&req->wait.entry);
1922 } else if (cancel) {
1923 /* Cancel if possible (may be too late though). */
1924 WRITE_ONCE(req->cancelled, true);
1925 } else if (on_queue) {
1926 /*
1927 * Actually waiting for an event, so add the request to
1928 * active_reqs so that it can be cancelled if needed.
1929 */
1930 list_add_tail(&aiocb->ki_list, &ctx->active_reqs);
1931 aiocb->ki_cancel = aio_poll_cancel;
1932 }
1933 if (on_queue)
1934 poll_iocb_unlock_wq(req);
1935 }
1936 if (mask) { /* no async, we'd stolen it */
1937 aiocb->ki_res.res = mangle_poll(mask);
1938 apt.error = 0;
1939 }
1940 spin_unlock_irq(&ctx->ctx_lock);
1941 if (mask)
1942 iocb_put(aiocb);
1943 return apt.error;
1944 }
1945
__io_submit_one(struct kioctx * ctx,const struct iocb * iocb,struct iocb __user * user_iocb,struct aio_kiocb * req,bool compat)1946 static int __io_submit_one(struct kioctx *ctx, const struct iocb *iocb,
1947 struct iocb __user *user_iocb, struct aio_kiocb *req,
1948 bool compat)
1949 {
1950 req->ki_filp = fget(iocb->aio_fildes);
1951 if (unlikely(!req->ki_filp))
1952 return -EBADF;
1953
1954 if (iocb->aio_flags & IOCB_FLAG_RESFD) {
1955 struct eventfd_ctx *eventfd;
1956 /*
1957 * If the IOCB_FLAG_RESFD flag of aio_flags is set, get an
1958 * instance of the file* now. The file descriptor must be
1959 * an eventfd() fd, and will be signaled for each completed
1960 * event using the eventfd_signal() function.
1961 */
1962 eventfd = eventfd_ctx_fdget(iocb->aio_resfd);
1963 if (IS_ERR(eventfd))
1964 return PTR_ERR(eventfd);
1965
1966 req->ki_eventfd = eventfd;
1967 }
1968
1969 if (unlikely(put_user(KIOCB_KEY, &user_iocb->aio_key))) {
1970 pr_debug("EFAULT: aio_key\n");
1971 return -EFAULT;
1972 }
1973
1974 req->ki_res.obj = (u64)(unsigned long)user_iocb;
1975 req->ki_res.data = iocb->aio_data;
1976 req->ki_res.res = 0;
1977 req->ki_res.res2 = 0;
1978
1979 switch (iocb->aio_lio_opcode) {
1980 case IOCB_CMD_PREAD:
1981 return aio_read(&req->rw, iocb, false, compat);
1982 case IOCB_CMD_PWRITE:
1983 return aio_write(&req->rw, iocb, false, compat);
1984 case IOCB_CMD_PREADV:
1985 return aio_read(&req->rw, iocb, true, compat);
1986 case IOCB_CMD_PWRITEV:
1987 return aio_write(&req->rw, iocb, true, compat);
1988 case IOCB_CMD_FSYNC:
1989 return aio_fsync(&req->fsync, iocb, false);
1990 case IOCB_CMD_FDSYNC:
1991 return aio_fsync(&req->fsync, iocb, true);
1992 case IOCB_CMD_POLL:
1993 return aio_poll(req, iocb);
1994 default:
1995 pr_debug("invalid aio operation %d\n", iocb->aio_lio_opcode);
1996 return -EINVAL;
1997 }
1998 }
1999
io_submit_one(struct kioctx * ctx,struct iocb __user * user_iocb,bool compat)2000 static int io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb,
2001 bool compat)
2002 {
2003 struct aio_kiocb *req;
2004 struct iocb iocb;
2005 int err;
2006
2007 if (unlikely(copy_from_user(&iocb, user_iocb, sizeof(iocb))))
2008 return -EFAULT;
2009
2010 /* enforce forwards compatibility on users */
2011 if (unlikely(iocb.aio_reserved2)) {
2012 pr_debug("EINVAL: reserve field set\n");
2013 return -EINVAL;
2014 }
2015
2016 /* prevent overflows */
2017 if (unlikely(
2018 (iocb.aio_buf != (unsigned long)iocb.aio_buf) ||
2019 (iocb.aio_nbytes != (size_t)iocb.aio_nbytes) ||
2020 ((ssize_t)iocb.aio_nbytes < 0)
2021 )) {
2022 pr_debug("EINVAL: overflow check\n");
2023 return -EINVAL;
2024 }
2025
2026 req = aio_get_req(ctx);
2027 if (unlikely(!req))
2028 return -EAGAIN;
2029
2030 err = __io_submit_one(ctx, &iocb, user_iocb, req, compat);
2031
2032 /* Done with the synchronous reference */
2033 iocb_put(req);
2034
2035 /*
2036 * If err is 0, we'd either done aio_complete() ourselves or have
2037 * arranged for that to be done asynchronously. Anything non-zero
2038 * means that we need to destroy req ourselves.
2039 */
2040 if (unlikely(err)) {
2041 iocb_destroy(req);
2042 put_reqs_available(ctx, 1);
2043 }
2044 return err;
2045 }
2046
2047 /* sys_io_submit:
2048 * Queue the nr iocbs pointed to by iocbpp for processing. Returns
2049 * the number of iocbs queued. May return -EINVAL if the aio_context
2050 * specified by ctx_id is invalid, if nr is < 0, if the iocb at
2051 * *iocbpp[0] is not properly initialized, if the operation specified
2052 * is invalid for the file descriptor in the iocb. May fail with
2053 * -EFAULT if any of the data structures point to invalid data. May
2054 * fail with -EBADF if the file descriptor specified in the first
2055 * iocb is invalid. May fail with -EAGAIN if insufficient resources
2056 * are available to queue any iocbs. Will return 0 if nr is 0. Will
2057 * fail with -ENOSYS if not implemented.
2058 */
SYSCALL_DEFINE3(io_submit,aio_context_t,ctx_id,long,nr,struct iocb __user * __user *,iocbpp)2059 SYSCALL_DEFINE3(io_submit, aio_context_t, ctx_id, long, nr,
2060 struct iocb __user * __user *, iocbpp)
2061 {
2062 struct kioctx *ctx;
2063 long ret = 0;
2064 int i = 0;
2065 struct blk_plug plug;
2066
2067 if (unlikely(nr < 0))
2068 return -EINVAL;
2069
2070 ctx = lookup_ioctx(ctx_id);
2071 if (unlikely(!ctx)) {
2072 pr_debug("EINVAL: invalid context id\n");
2073 return -EINVAL;
2074 }
2075
2076 if (nr > ctx->nr_events)
2077 nr = ctx->nr_events;
2078
2079 if (nr > AIO_PLUG_THRESHOLD)
2080 blk_start_plug(&plug);
2081 for (i = 0; i < nr; i++) {
2082 struct iocb __user *user_iocb;
2083
2084 if (unlikely(get_user(user_iocb, iocbpp + i))) {
2085 ret = -EFAULT;
2086 break;
2087 }
2088
2089 ret = io_submit_one(ctx, user_iocb, false);
2090 if (ret)
2091 break;
2092 }
2093 if (nr > AIO_PLUG_THRESHOLD)
2094 blk_finish_plug(&plug);
2095
2096 percpu_ref_put(&ctx->users);
2097 return i ? i : ret;
2098 }
2099
2100 #ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE3(io_submit,compat_aio_context_t,ctx_id,int,nr,compat_uptr_t __user *,iocbpp)2101 COMPAT_SYSCALL_DEFINE3(io_submit, compat_aio_context_t, ctx_id,
2102 int, nr, compat_uptr_t __user *, iocbpp)
2103 {
2104 struct kioctx *ctx;
2105 long ret = 0;
2106 int i = 0;
2107 struct blk_plug plug;
2108
2109 if (unlikely(nr < 0))
2110 return -EINVAL;
2111
2112 ctx = lookup_ioctx(ctx_id);
2113 if (unlikely(!ctx)) {
2114 pr_debug("EINVAL: invalid context id\n");
2115 return -EINVAL;
2116 }
2117
2118 if (nr > ctx->nr_events)
2119 nr = ctx->nr_events;
2120
2121 if (nr > AIO_PLUG_THRESHOLD)
2122 blk_start_plug(&plug);
2123 for (i = 0; i < nr; i++) {
2124 compat_uptr_t user_iocb;
2125
2126 if (unlikely(get_user(user_iocb, iocbpp + i))) {
2127 ret = -EFAULT;
2128 break;
2129 }
2130
2131 ret = io_submit_one(ctx, compat_ptr(user_iocb), true);
2132 if (ret)
2133 break;
2134 }
2135 if (nr > AIO_PLUG_THRESHOLD)
2136 blk_finish_plug(&plug);
2137
2138 percpu_ref_put(&ctx->users);
2139 return i ? i : ret;
2140 }
2141 #endif
2142
2143 /* sys_io_cancel:
2144 * Attempts to cancel an iocb previously passed to io_submit. If
2145 * the operation is successfully cancelled, the resulting event is
2146 * copied into the memory pointed to by result without being placed
2147 * into the completion queue and 0 is returned. May fail with
2148 * -EFAULT if any of the data structures pointed to are invalid.
2149 * May fail with -EINVAL if aio_context specified by ctx_id is
2150 * invalid. May fail with -EAGAIN if the iocb specified was not
2151 * cancelled. Will fail with -ENOSYS if not implemented.
2152 */
SYSCALL_DEFINE3(io_cancel,aio_context_t,ctx_id,struct iocb __user *,iocb,struct io_event __user *,result)2153 SYSCALL_DEFINE3(io_cancel, aio_context_t, ctx_id, struct iocb __user *, iocb,
2154 struct io_event __user *, result)
2155 {
2156 struct kioctx *ctx;
2157 struct aio_kiocb *kiocb;
2158 int ret = -EINVAL;
2159 u32 key;
2160 u64 obj = (u64)(unsigned long)iocb;
2161
2162 if (unlikely(get_user(key, &iocb->aio_key)))
2163 return -EFAULT;
2164 if (unlikely(key != KIOCB_KEY))
2165 return -EINVAL;
2166
2167 ctx = lookup_ioctx(ctx_id);
2168 if (unlikely(!ctx))
2169 return -EINVAL;
2170
2171 spin_lock_irq(&ctx->ctx_lock);
2172 /* TODO: use a hash or array, this sucks. */
2173 list_for_each_entry(kiocb, &ctx->active_reqs, ki_list) {
2174 if (kiocb->ki_res.obj == obj) {
2175 ret = kiocb->ki_cancel(&kiocb->rw);
2176 list_del_init(&kiocb->ki_list);
2177 break;
2178 }
2179 }
2180 spin_unlock_irq(&ctx->ctx_lock);
2181
2182 if (!ret) {
2183 /*
2184 * The result argument is no longer used - the io_event is
2185 * always delivered via the ring buffer. -EINPROGRESS indicates
2186 * cancellation is progress:
2187 */
2188 ret = -EINPROGRESS;
2189 }
2190
2191 percpu_ref_put(&ctx->users);
2192
2193 return ret;
2194 }
2195
do_io_getevents(aio_context_t ctx_id,long min_nr,long nr,struct io_event __user * events,struct timespec64 * ts)2196 static long do_io_getevents(aio_context_t ctx_id,
2197 long min_nr,
2198 long nr,
2199 struct io_event __user *events,
2200 struct timespec64 *ts)
2201 {
2202 ktime_t until = ts ? timespec64_to_ktime(*ts) : KTIME_MAX;
2203 struct kioctx *ioctx = lookup_ioctx(ctx_id);
2204 long ret = -EINVAL;
2205
2206 if (likely(ioctx)) {
2207 if (likely(min_nr <= nr && min_nr >= 0))
2208 ret = read_events(ioctx, min_nr, nr, events, until);
2209 percpu_ref_put(&ioctx->users);
2210 }
2211
2212 return ret;
2213 }
2214
2215 /* io_getevents:
2216 * Attempts to read at least min_nr events and up to nr events from
2217 * the completion queue for the aio_context specified by ctx_id. If
2218 * it succeeds, the number of read events is returned. May fail with
2219 * -EINVAL if ctx_id is invalid, if min_nr is out of range, if nr is
2220 * out of range, if timeout is out of range. May fail with -EFAULT
2221 * if any of the memory specified is invalid. May return 0 or
2222 * < min_nr if the timeout specified by timeout has elapsed
2223 * before sufficient events are available, where timeout == NULL
2224 * specifies an infinite timeout. Note that the timeout pointed to by
2225 * timeout is relative. Will fail with -ENOSYS if not implemented.
2226 */
2227 #ifdef CONFIG_64BIT
2228
SYSCALL_DEFINE5(io_getevents,aio_context_t,ctx_id,long,min_nr,long,nr,struct io_event __user *,events,struct __kernel_timespec __user *,timeout)2229 SYSCALL_DEFINE5(io_getevents, aio_context_t, ctx_id,
2230 long, min_nr,
2231 long, nr,
2232 struct io_event __user *, events,
2233 struct __kernel_timespec __user *, timeout)
2234 {
2235 struct timespec64 ts;
2236 int ret;
2237
2238 if (timeout && unlikely(get_timespec64(&ts, timeout)))
2239 return -EFAULT;
2240
2241 ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &ts : NULL);
2242 if (!ret && signal_pending(current))
2243 ret = -EINTR;
2244 return ret;
2245 }
2246
2247 #endif
2248
2249 struct __aio_sigset {
2250 const sigset_t __user *sigmask;
2251 size_t sigsetsize;
2252 };
2253
SYSCALL_DEFINE6(io_pgetevents,aio_context_t,ctx_id,long,min_nr,long,nr,struct io_event __user *,events,struct __kernel_timespec __user *,timeout,const struct __aio_sigset __user *,usig)2254 SYSCALL_DEFINE6(io_pgetevents,
2255 aio_context_t, ctx_id,
2256 long, min_nr,
2257 long, nr,
2258 struct io_event __user *, events,
2259 struct __kernel_timespec __user *, timeout,
2260 const struct __aio_sigset __user *, usig)
2261 {
2262 struct __aio_sigset ksig = { NULL, };
2263 struct timespec64 ts;
2264 bool interrupted;
2265 int ret;
2266
2267 if (timeout && unlikely(get_timespec64(&ts, timeout)))
2268 return -EFAULT;
2269
2270 if (usig && copy_from_user(&ksig, usig, sizeof(ksig)))
2271 return -EFAULT;
2272
2273 ret = set_user_sigmask(ksig.sigmask, ksig.sigsetsize);
2274 if (ret)
2275 return ret;
2276
2277 ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &ts : NULL);
2278
2279 interrupted = signal_pending(current);
2280 restore_saved_sigmask_unless(interrupted);
2281 if (interrupted && !ret)
2282 ret = -ERESTARTNOHAND;
2283
2284 return ret;
2285 }
2286
2287 #if defined(CONFIG_COMPAT_32BIT_TIME) && !defined(CONFIG_64BIT)
2288
SYSCALL_DEFINE6(io_pgetevents_time32,aio_context_t,ctx_id,long,min_nr,long,nr,struct io_event __user *,events,struct old_timespec32 __user *,timeout,const struct __aio_sigset __user *,usig)2289 SYSCALL_DEFINE6(io_pgetevents_time32,
2290 aio_context_t, ctx_id,
2291 long, min_nr,
2292 long, nr,
2293 struct io_event __user *, events,
2294 struct old_timespec32 __user *, timeout,
2295 const struct __aio_sigset __user *, usig)
2296 {
2297 struct __aio_sigset ksig = { NULL, };
2298 struct timespec64 ts;
2299 bool interrupted;
2300 int ret;
2301
2302 if (timeout && unlikely(get_old_timespec32(&ts, timeout)))
2303 return -EFAULT;
2304
2305 if (usig && copy_from_user(&ksig, usig, sizeof(ksig)))
2306 return -EFAULT;
2307
2308
2309 ret = set_user_sigmask(ksig.sigmask, ksig.sigsetsize);
2310 if (ret)
2311 return ret;
2312
2313 ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &ts : NULL);
2314
2315 interrupted = signal_pending(current);
2316 restore_saved_sigmask_unless(interrupted);
2317 if (interrupted && !ret)
2318 ret = -ERESTARTNOHAND;
2319
2320 return ret;
2321 }
2322
2323 #endif
2324
2325 #if defined(CONFIG_COMPAT_32BIT_TIME)
2326
SYSCALL_DEFINE5(io_getevents_time32,__u32,ctx_id,__s32,min_nr,__s32,nr,struct io_event __user *,events,struct old_timespec32 __user *,timeout)2327 SYSCALL_DEFINE5(io_getevents_time32, __u32, ctx_id,
2328 __s32, min_nr,
2329 __s32, nr,
2330 struct io_event __user *, events,
2331 struct old_timespec32 __user *, timeout)
2332 {
2333 struct timespec64 t;
2334 int ret;
2335
2336 if (timeout && get_old_timespec32(&t, timeout))
2337 return -EFAULT;
2338
2339 ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &t : NULL);
2340 if (!ret && signal_pending(current))
2341 ret = -EINTR;
2342 return ret;
2343 }
2344
2345 #endif
2346
2347 #ifdef CONFIG_COMPAT
2348
2349 struct __compat_aio_sigset {
2350 compat_uptr_t sigmask;
2351 compat_size_t sigsetsize;
2352 };
2353
2354 #if defined(CONFIG_COMPAT_32BIT_TIME)
2355
COMPAT_SYSCALL_DEFINE6(io_pgetevents,compat_aio_context_t,ctx_id,compat_long_t,min_nr,compat_long_t,nr,struct io_event __user *,events,struct old_timespec32 __user *,timeout,const struct __compat_aio_sigset __user *,usig)2356 COMPAT_SYSCALL_DEFINE6(io_pgetevents,
2357 compat_aio_context_t, ctx_id,
2358 compat_long_t, min_nr,
2359 compat_long_t, nr,
2360 struct io_event __user *, events,
2361 struct old_timespec32 __user *, timeout,
2362 const struct __compat_aio_sigset __user *, usig)
2363 {
2364 struct __compat_aio_sigset ksig = { 0, };
2365 struct timespec64 t;
2366 bool interrupted;
2367 int ret;
2368
2369 if (timeout && get_old_timespec32(&t, timeout))
2370 return -EFAULT;
2371
2372 if (usig && copy_from_user(&ksig, usig, sizeof(ksig)))
2373 return -EFAULT;
2374
2375 ret = set_compat_user_sigmask(compat_ptr(ksig.sigmask), ksig.sigsetsize);
2376 if (ret)
2377 return ret;
2378
2379 ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &t : NULL);
2380
2381 interrupted = signal_pending(current);
2382 restore_saved_sigmask_unless(interrupted);
2383 if (interrupted && !ret)
2384 ret = -ERESTARTNOHAND;
2385
2386 return ret;
2387 }
2388
2389 #endif
2390
COMPAT_SYSCALL_DEFINE6(io_pgetevents_time64,compat_aio_context_t,ctx_id,compat_long_t,min_nr,compat_long_t,nr,struct io_event __user *,events,struct __kernel_timespec __user *,timeout,const struct __compat_aio_sigset __user *,usig)2391 COMPAT_SYSCALL_DEFINE6(io_pgetevents_time64,
2392 compat_aio_context_t, ctx_id,
2393 compat_long_t, min_nr,
2394 compat_long_t, nr,
2395 struct io_event __user *, events,
2396 struct __kernel_timespec __user *, timeout,
2397 const struct __compat_aio_sigset __user *, usig)
2398 {
2399 struct __compat_aio_sigset ksig = { 0, };
2400 struct timespec64 t;
2401 bool interrupted;
2402 int ret;
2403
2404 if (timeout && get_timespec64(&t, timeout))
2405 return -EFAULT;
2406
2407 if (usig && copy_from_user(&ksig, usig, sizeof(ksig)))
2408 return -EFAULT;
2409
2410 ret = set_compat_user_sigmask(compat_ptr(ksig.sigmask), ksig.sigsetsize);
2411 if (ret)
2412 return ret;
2413
2414 ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &t : NULL);
2415
2416 interrupted = signal_pending(current);
2417 restore_saved_sigmask_unless(interrupted);
2418 if (interrupted && !ret)
2419 ret = -ERESTARTNOHAND;
2420
2421 return ret;
2422 }
2423 #endif
2424