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