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