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