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