xref: /linux/fs/aio.c (revision b85d45947951d23cb22d90caecf4c1eb81342c96)
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  *
9  *	See ../COPYING for licensing terms.
10  */
11 #define pr_fmt(fmt) "%s: " fmt, __func__
12 
13 #include <linux/kernel.h>
14 #include <linux/init.h>
15 #include <linux/errno.h>
16 #include <linux/time.h>
17 #include <linux/aio_abi.h>
18 #include <linux/export.h>
19 #include <linux/syscalls.h>
20 #include <linux/backing-dev.h>
21 #include <linux/uio.h>
22 
23 #include <linux/sched.h>
24 #include <linux/fs.h>
25 #include <linux/file.h>
26 #include <linux/mm.h>
27 #include <linux/mman.h>
28 #include <linux/mmu_context.h>
29 #include <linux/percpu.h>
30 #include <linux/slab.h>
31 #include <linux/timer.h>
32 #include <linux/aio.h>
33 #include <linux/highmem.h>
34 #include <linux/workqueue.h>
35 #include <linux/security.h>
36 #include <linux/eventfd.h>
37 #include <linux/blkdev.h>
38 #include <linux/compat.h>
39 #include <linux/migrate.h>
40 #include <linux/ramfs.h>
41 #include <linux/percpu-refcount.h>
42 #include <linux/mount.h>
43 
44 #include <asm/kmap_types.h>
45 #include <asm/uaccess.h>
46 
47 #include "internal.h"
48 
49 #define AIO_RING_MAGIC			0xa10a10a1
50 #define AIO_RING_COMPAT_FEATURES	1
51 #define AIO_RING_INCOMPAT_FEATURES	0
52 struct aio_ring {
53 	unsigned	id;	/* kernel internal index number */
54 	unsigned	nr;	/* number of io_events */
55 	unsigned	head;	/* Written to by userland or under ring_lock
56 				 * mutex by aio_read_events_ring(). */
57 	unsigned	tail;
58 
59 	unsigned	magic;
60 	unsigned	compat_features;
61 	unsigned	incompat_features;
62 	unsigned	header_length;	/* size of aio_ring */
63 
64 
65 	struct io_event		io_events[0];
66 }; /* 128 bytes + ring size */
67 
68 #define AIO_RING_PAGES	8
69 
70 struct kioctx_table {
71 	struct rcu_head	rcu;
72 	unsigned	nr;
73 	struct kioctx	*table[];
74 };
75 
76 struct kioctx_cpu {
77 	unsigned		reqs_available;
78 };
79 
80 struct ctx_rq_wait {
81 	struct completion comp;
82 	atomic_t count;
83 };
84 
85 struct kioctx {
86 	struct percpu_ref	users;
87 	atomic_t		dead;
88 
89 	struct percpu_ref	reqs;
90 
91 	unsigned long		user_id;
92 
93 	struct __percpu kioctx_cpu *cpu;
94 
95 	/*
96 	 * For percpu reqs_available, number of slots we move to/from global
97 	 * counter at a time:
98 	 */
99 	unsigned		req_batch;
100 	/*
101 	 * This is what userspace passed to io_setup(), it's not used for
102 	 * anything but counting against the global max_reqs quota.
103 	 *
104 	 * The real limit is nr_events - 1, which will be larger (see
105 	 * aio_setup_ring())
106 	 */
107 	unsigned		max_reqs;
108 
109 	/* Size of ringbuffer, in units of struct io_event */
110 	unsigned		nr_events;
111 
112 	unsigned long		mmap_base;
113 	unsigned long		mmap_size;
114 
115 	struct page		**ring_pages;
116 	long			nr_pages;
117 
118 	struct work_struct	free_work;
119 
120 	/*
121 	 * signals when all in-flight requests are done
122 	 */
123 	struct ctx_rq_wait	*rq_wait;
124 
125 	struct {
126 		/*
127 		 * This counts the number of available slots in the ringbuffer,
128 		 * so we avoid overflowing it: it's decremented (if positive)
129 		 * when allocating a kiocb and incremented when the resulting
130 		 * io_event is pulled off the ringbuffer.
131 		 *
132 		 * We batch accesses to it with a percpu version.
133 		 */
134 		atomic_t	reqs_available;
135 	} ____cacheline_aligned_in_smp;
136 
137 	struct {
138 		spinlock_t	ctx_lock;
139 		struct list_head active_reqs;	/* used for cancellation */
140 	} ____cacheline_aligned_in_smp;
141 
142 	struct {
143 		struct mutex	ring_lock;
144 		wait_queue_head_t wait;
145 	} ____cacheline_aligned_in_smp;
146 
147 	struct {
148 		unsigned	tail;
149 		unsigned	completed_events;
150 		spinlock_t	completion_lock;
151 	} ____cacheline_aligned_in_smp;
152 
153 	struct page		*internal_pages[AIO_RING_PAGES];
154 	struct file		*aio_ring_file;
155 
156 	unsigned		id;
157 };
158 
159 /*
160  * We use ki_cancel == KIOCB_CANCELLED to indicate that a kiocb has been either
161  * cancelled or completed (this makes a certain amount of sense because
162  * successful cancellation - io_cancel() - does deliver the completion to
163  * userspace).
164  *
165  * And since most things don't implement kiocb cancellation and we'd really like
166  * kiocb completion to be lockless when possible, we use ki_cancel to
167  * synchronize cancellation and completion - we only set it to KIOCB_CANCELLED
168  * with xchg() or cmpxchg(), see batch_complete_aio() and kiocb_cancel().
169  */
170 #define KIOCB_CANCELLED		((void *) (~0ULL))
171 
172 struct aio_kiocb {
173 	struct kiocb		common;
174 
175 	struct kioctx		*ki_ctx;
176 	kiocb_cancel_fn		*ki_cancel;
177 
178 	struct iocb __user	*ki_user_iocb;	/* user's aiocb */
179 	__u64			ki_user_data;	/* user's data for completion */
180 
181 	struct list_head	ki_list;	/* the aio core uses this
182 						 * for cancellation */
183 
184 	/*
185 	 * If the aio_resfd field of the userspace iocb is not zero,
186 	 * this is the underlying eventfd context to deliver events to.
187 	 */
188 	struct eventfd_ctx	*ki_eventfd;
189 };
190 
191 /*------ sysctl variables----*/
192 static DEFINE_SPINLOCK(aio_nr_lock);
193 unsigned long aio_nr;		/* current system wide number of aio requests */
194 unsigned long aio_max_nr = 0x10000; /* system wide maximum number of aio requests */
195 /*----end sysctl variables---*/
196 
197 static struct kmem_cache	*kiocb_cachep;
198 static struct kmem_cache	*kioctx_cachep;
199 
200 static struct vfsmount *aio_mnt;
201 
202 static const struct file_operations aio_ring_fops;
203 static const struct address_space_operations aio_ctx_aops;
204 
205 static struct file *aio_private_file(struct kioctx *ctx, loff_t nr_pages)
206 {
207 	struct qstr this = QSTR_INIT("[aio]", 5);
208 	struct file *file;
209 	struct path path;
210 	struct inode *inode = alloc_anon_inode(aio_mnt->mnt_sb);
211 	if (IS_ERR(inode))
212 		return ERR_CAST(inode);
213 
214 	inode->i_mapping->a_ops = &aio_ctx_aops;
215 	inode->i_mapping->private_data = ctx;
216 	inode->i_size = PAGE_SIZE * nr_pages;
217 
218 	path.dentry = d_alloc_pseudo(aio_mnt->mnt_sb, &this);
219 	if (!path.dentry) {
220 		iput(inode);
221 		return ERR_PTR(-ENOMEM);
222 	}
223 	path.mnt = mntget(aio_mnt);
224 
225 	d_instantiate(path.dentry, inode);
226 	file = alloc_file(&path, FMODE_READ | FMODE_WRITE, &aio_ring_fops);
227 	if (IS_ERR(file)) {
228 		path_put(&path);
229 		return file;
230 	}
231 
232 	file->f_flags = O_RDWR;
233 	return file;
234 }
235 
236 static struct dentry *aio_mount(struct file_system_type *fs_type,
237 				int flags, const char *dev_name, void *data)
238 {
239 	static const struct dentry_operations ops = {
240 		.d_dname	= simple_dname,
241 	};
242 	return mount_pseudo(fs_type, "aio:", NULL, &ops, AIO_RING_MAGIC);
243 }
244 
245 /* aio_setup
246  *	Creates the slab caches used by the aio routines, panic on
247  *	failure as this is done early during the boot sequence.
248  */
249 static int __init aio_setup(void)
250 {
251 	static struct file_system_type aio_fs = {
252 		.name		= "aio",
253 		.mount		= aio_mount,
254 		.kill_sb	= kill_anon_super,
255 	};
256 	aio_mnt = kern_mount(&aio_fs);
257 	if (IS_ERR(aio_mnt))
258 		panic("Failed to create aio fs mount.");
259 
260 	kiocb_cachep = KMEM_CACHE(aio_kiocb, SLAB_HWCACHE_ALIGN|SLAB_PANIC);
261 	kioctx_cachep = KMEM_CACHE(kioctx,SLAB_HWCACHE_ALIGN|SLAB_PANIC);
262 
263 	pr_debug("sizeof(struct page) = %zu\n", sizeof(struct page));
264 
265 	return 0;
266 }
267 __initcall(aio_setup);
268 
269 static void put_aio_ring_file(struct kioctx *ctx)
270 {
271 	struct file *aio_ring_file = ctx->aio_ring_file;
272 	if (aio_ring_file) {
273 		truncate_setsize(aio_ring_file->f_inode, 0);
274 
275 		/* Prevent further access to the kioctx from migratepages */
276 		spin_lock(&aio_ring_file->f_inode->i_mapping->private_lock);
277 		aio_ring_file->f_inode->i_mapping->private_data = NULL;
278 		ctx->aio_ring_file = NULL;
279 		spin_unlock(&aio_ring_file->f_inode->i_mapping->private_lock);
280 
281 		fput(aio_ring_file);
282 	}
283 }
284 
285 static void aio_free_ring(struct kioctx *ctx)
286 {
287 	int i;
288 
289 	/* Disconnect the kiotx from the ring file.  This prevents future
290 	 * accesses to the kioctx from page migration.
291 	 */
292 	put_aio_ring_file(ctx);
293 
294 	for (i = 0; i < ctx->nr_pages; i++) {
295 		struct page *page;
296 		pr_debug("pid(%d) [%d] page->count=%d\n", current->pid, i,
297 				page_count(ctx->ring_pages[i]));
298 		page = ctx->ring_pages[i];
299 		if (!page)
300 			continue;
301 		ctx->ring_pages[i] = NULL;
302 		put_page(page);
303 	}
304 
305 	if (ctx->ring_pages && ctx->ring_pages != ctx->internal_pages) {
306 		kfree(ctx->ring_pages);
307 		ctx->ring_pages = NULL;
308 	}
309 }
310 
311 static int aio_ring_mremap(struct vm_area_struct *vma)
312 {
313 	struct file *file = vma->vm_file;
314 	struct mm_struct *mm = vma->vm_mm;
315 	struct kioctx_table *table;
316 	int i, res = -EINVAL;
317 
318 	spin_lock(&mm->ioctx_lock);
319 	rcu_read_lock();
320 	table = rcu_dereference(mm->ioctx_table);
321 	for (i = 0; i < table->nr; i++) {
322 		struct kioctx *ctx;
323 
324 		ctx = table->table[i];
325 		if (ctx && ctx->aio_ring_file == file) {
326 			if (!atomic_read(&ctx->dead)) {
327 				ctx->user_id = ctx->mmap_base = vma->vm_start;
328 				res = 0;
329 			}
330 			break;
331 		}
332 	}
333 
334 	rcu_read_unlock();
335 	spin_unlock(&mm->ioctx_lock);
336 	return res;
337 }
338 
339 static const struct vm_operations_struct aio_ring_vm_ops = {
340 	.mremap		= aio_ring_mremap,
341 #if IS_ENABLED(CONFIG_MMU)
342 	.fault		= filemap_fault,
343 	.map_pages	= filemap_map_pages,
344 	.page_mkwrite	= filemap_page_mkwrite,
345 #endif
346 };
347 
348 static int aio_ring_mmap(struct file *file, struct vm_area_struct *vma)
349 {
350 	vma->vm_flags |= VM_DONTEXPAND;
351 	vma->vm_ops = &aio_ring_vm_ops;
352 	return 0;
353 }
354 
355 static const struct file_operations aio_ring_fops = {
356 	.mmap = aio_ring_mmap,
357 };
358 
359 #if IS_ENABLED(CONFIG_MIGRATION)
360 static int aio_migratepage(struct address_space *mapping, struct page *new,
361 			struct page *old, enum migrate_mode mode)
362 {
363 	struct kioctx *ctx;
364 	unsigned long flags;
365 	pgoff_t idx;
366 	int rc;
367 
368 	rc = 0;
369 
370 	/* mapping->private_lock here protects against the kioctx teardown.  */
371 	spin_lock(&mapping->private_lock);
372 	ctx = mapping->private_data;
373 	if (!ctx) {
374 		rc = -EINVAL;
375 		goto out;
376 	}
377 
378 	/* The ring_lock mutex.  The prevents aio_read_events() from writing
379 	 * to the ring's head, and prevents page migration from mucking in
380 	 * a partially initialized kiotx.
381 	 */
382 	if (!mutex_trylock(&ctx->ring_lock)) {
383 		rc = -EAGAIN;
384 		goto out;
385 	}
386 
387 	idx = old->index;
388 	if (idx < (pgoff_t)ctx->nr_pages) {
389 		/* Make sure the old page hasn't already been changed */
390 		if (ctx->ring_pages[idx] != old)
391 			rc = -EAGAIN;
392 	} else
393 		rc = -EINVAL;
394 
395 	if (rc != 0)
396 		goto out_unlock;
397 
398 	/* Writeback must be complete */
399 	BUG_ON(PageWriteback(old));
400 	get_page(new);
401 
402 	rc = migrate_page_move_mapping(mapping, new, old, NULL, mode, 1);
403 	if (rc != MIGRATEPAGE_SUCCESS) {
404 		put_page(new);
405 		goto out_unlock;
406 	}
407 
408 	/* Take completion_lock to prevent other writes to the ring buffer
409 	 * while the old page is copied to the new.  This prevents new
410 	 * events from being lost.
411 	 */
412 	spin_lock_irqsave(&ctx->completion_lock, flags);
413 	migrate_page_copy(new, old);
414 	BUG_ON(ctx->ring_pages[idx] != old);
415 	ctx->ring_pages[idx] = new;
416 	spin_unlock_irqrestore(&ctx->completion_lock, flags);
417 
418 	/* The old page is no longer accessible. */
419 	put_page(old);
420 
421 out_unlock:
422 	mutex_unlock(&ctx->ring_lock);
423 out:
424 	spin_unlock(&mapping->private_lock);
425 	return rc;
426 }
427 #endif
428 
429 static const struct address_space_operations aio_ctx_aops = {
430 	.set_page_dirty = __set_page_dirty_no_writeback,
431 #if IS_ENABLED(CONFIG_MIGRATION)
432 	.migratepage	= aio_migratepage,
433 #endif
434 };
435 
436 static int aio_setup_ring(struct kioctx *ctx)
437 {
438 	struct aio_ring *ring;
439 	unsigned nr_events = ctx->max_reqs;
440 	struct mm_struct *mm = current->mm;
441 	unsigned long size, unused;
442 	int nr_pages;
443 	int i;
444 	struct file *file;
445 
446 	/* Compensate for the ring buffer's head/tail overlap entry */
447 	nr_events += 2;	/* 1 is required, 2 for good luck */
448 
449 	size = sizeof(struct aio_ring);
450 	size += sizeof(struct io_event) * nr_events;
451 
452 	nr_pages = PFN_UP(size);
453 	if (nr_pages < 0)
454 		return -EINVAL;
455 
456 	file = aio_private_file(ctx, nr_pages);
457 	if (IS_ERR(file)) {
458 		ctx->aio_ring_file = NULL;
459 		return -ENOMEM;
460 	}
461 
462 	ctx->aio_ring_file = file;
463 	nr_events = (PAGE_SIZE * nr_pages - sizeof(struct aio_ring))
464 			/ sizeof(struct io_event);
465 
466 	ctx->ring_pages = ctx->internal_pages;
467 	if (nr_pages > AIO_RING_PAGES) {
468 		ctx->ring_pages = kcalloc(nr_pages, sizeof(struct page *),
469 					  GFP_KERNEL);
470 		if (!ctx->ring_pages) {
471 			put_aio_ring_file(ctx);
472 			return -ENOMEM;
473 		}
474 	}
475 
476 	for (i = 0; i < nr_pages; i++) {
477 		struct page *page;
478 		page = find_or_create_page(file->f_inode->i_mapping,
479 					   i, GFP_HIGHUSER | __GFP_ZERO);
480 		if (!page)
481 			break;
482 		pr_debug("pid(%d) page[%d]->count=%d\n",
483 			 current->pid, i, page_count(page));
484 		SetPageUptodate(page);
485 		unlock_page(page);
486 
487 		ctx->ring_pages[i] = page;
488 	}
489 	ctx->nr_pages = i;
490 
491 	if (unlikely(i != nr_pages)) {
492 		aio_free_ring(ctx);
493 		return -ENOMEM;
494 	}
495 
496 	ctx->mmap_size = nr_pages * PAGE_SIZE;
497 	pr_debug("attempting mmap of %lu bytes\n", ctx->mmap_size);
498 
499 	down_write(&mm->mmap_sem);
500 	ctx->mmap_base = do_mmap_pgoff(ctx->aio_ring_file, 0, ctx->mmap_size,
501 				       PROT_READ | PROT_WRITE,
502 				       MAP_SHARED, 0, &unused);
503 	up_write(&mm->mmap_sem);
504 	if (IS_ERR((void *)ctx->mmap_base)) {
505 		ctx->mmap_size = 0;
506 		aio_free_ring(ctx);
507 		return -ENOMEM;
508 	}
509 
510 	pr_debug("mmap address: 0x%08lx\n", ctx->mmap_base);
511 
512 	ctx->user_id = ctx->mmap_base;
513 	ctx->nr_events = nr_events; /* trusted copy */
514 
515 	ring = kmap_atomic(ctx->ring_pages[0]);
516 	ring->nr = nr_events;	/* user copy */
517 	ring->id = ~0U;
518 	ring->head = ring->tail = 0;
519 	ring->magic = AIO_RING_MAGIC;
520 	ring->compat_features = AIO_RING_COMPAT_FEATURES;
521 	ring->incompat_features = AIO_RING_INCOMPAT_FEATURES;
522 	ring->header_length = sizeof(struct aio_ring);
523 	kunmap_atomic(ring);
524 	flush_dcache_page(ctx->ring_pages[0]);
525 
526 	return 0;
527 }
528 
529 #define AIO_EVENTS_PER_PAGE	(PAGE_SIZE / sizeof(struct io_event))
530 #define AIO_EVENTS_FIRST_PAGE	((PAGE_SIZE - sizeof(struct aio_ring)) / sizeof(struct io_event))
531 #define AIO_EVENTS_OFFSET	(AIO_EVENTS_PER_PAGE - AIO_EVENTS_FIRST_PAGE)
532 
533 void kiocb_set_cancel_fn(struct kiocb *iocb, kiocb_cancel_fn *cancel)
534 {
535 	struct aio_kiocb *req = container_of(iocb, struct aio_kiocb, common);
536 	struct kioctx *ctx = req->ki_ctx;
537 	unsigned long flags;
538 
539 	spin_lock_irqsave(&ctx->ctx_lock, flags);
540 
541 	if (!req->ki_list.next)
542 		list_add(&req->ki_list, &ctx->active_reqs);
543 
544 	req->ki_cancel = cancel;
545 
546 	spin_unlock_irqrestore(&ctx->ctx_lock, flags);
547 }
548 EXPORT_SYMBOL(kiocb_set_cancel_fn);
549 
550 static int kiocb_cancel(struct aio_kiocb *kiocb)
551 {
552 	kiocb_cancel_fn *old, *cancel;
553 
554 	/*
555 	 * Don't want to set kiocb->ki_cancel = KIOCB_CANCELLED unless it
556 	 * actually has a cancel function, hence the cmpxchg()
557 	 */
558 
559 	cancel = ACCESS_ONCE(kiocb->ki_cancel);
560 	do {
561 		if (!cancel || cancel == KIOCB_CANCELLED)
562 			return -EINVAL;
563 
564 		old = cancel;
565 		cancel = cmpxchg(&kiocb->ki_cancel, old, KIOCB_CANCELLED);
566 	} while (cancel != old);
567 
568 	return cancel(&kiocb->common);
569 }
570 
571 static void free_ioctx(struct work_struct *work)
572 {
573 	struct kioctx *ctx = container_of(work, struct kioctx, free_work);
574 
575 	pr_debug("freeing %p\n", ctx);
576 
577 	aio_free_ring(ctx);
578 	free_percpu(ctx->cpu);
579 	percpu_ref_exit(&ctx->reqs);
580 	percpu_ref_exit(&ctx->users);
581 	kmem_cache_free(kioctx_cachep, ctx);
582 }
583 
584 static void free_ioctx_reqs(struct percpu_ref *ref)
585 {
586 	struct kioctx *ctx = container_of(ref, struct kioctx, reqs);
587 
588 	/* At this point we know that there are no any in-flight requests */
589 	if (ctx->rq_wait && atomic_dec_and_test(&ctx->rq_wait->count))
590 		complete(&ctx->rq_wait->comp);
591 
592 	INIT_WORK(&ctx->free_work, free_ioctx);
593 	schedule_work(&ctx->free_work);
594 }
595 
596 /*
597  * When this function runs, the kioctx has been removed from the "hash table"
598  * and ctx->users has dropped to 0, so we know no more kiocbs can be submitted -
599  * now it's safe to cancel any that need to be.
600  */
601 static void free_ioctx_users(struct percpu_ref *ref)
602 {
603 	struct kioctx *ctx = container_of(ref, struct kioctx, users);
604 	struct aio_kiocb *req;
605 
606 	spin_lock_irq(&ctx->ctx_lock);
607 
608 	while (!list_empty(&ctx->active_reqs)) {
609 		req = list_first_entry(&ctx->active_reqs,
610 				       struct aio_kiocb, ki_list);
611 
612 		list_del_init(&req->ki_list);
613 		kiocb_cancel(req);
614 	}
615 
616 	spin_unlock_irq(&ctx->ctx_lock);
617 
618 	percpu_ref_kill(&ctx->reqs);
619 	percpu_ref_put(&ctx->reqs);
620 }
621 
622 static int ioctx_add_table(struct kioctx *ctx, struct mm_struct *mm)
623 {
624 	unsigned i, new_nr;
625 	struct kioctx_table *table, *old;
626 	struct aio_ring *ring;
627 
628 	spin_lock(&mm->ioctx_lock);
629 	table = rcu_dereference_raw(mm->ioctx_table);
630 
631 	while (1) {
632 		if (table)
633 			for (i = 0; i < table->nr; i++)
634 				if (!table->table[i]) {
635 					ctx->id = i;
636 					table->table[i] = ctx;
637 					spin_unlock(&mm->ioctx_lock);
638 
639 					/* While kioctx setup is in progress,
640 					 * we are protected from page migration
641 					 * changes ring_pages by ->ring_lock.
642 					 */
643 					ring = kmap_atomic(ctx->ring_pages[0]);
644 					ring->id = ctx->id;
645 					kunmap_atomic(ring);
646 					return 0;
647 				}
648 
649 		new_nr = (table ? table->nr : 1) * 4;
650 		spin_unlock(&mm->ioctx_lock);
651 
652 		table = kzalloc(sizeof(*table) + sizeof(struct kioctx *) *
653 				new_nr, GFP_KERNEL);
654 		if (!table)
655 			return -ENOMEM;
656 
657 		table->nr = new_nr;
658 
659 		spin_lock(&mm->ioctx_lock);
660 		old = rcu_dereference_raw(mm->ioctx_table);
661 
662 		if (!old) {
663 			rcu_assign_pointer(mm->ioctx_table, table);
664 		} else if (table->nr > old->nr) {
665 			memcpy(table->table, old->table,
666 			       old->nr * sizeof(struct kioctx *));
667 
668 			rcu_assign_pointer(mm->ioctx_table, table);
669 			kfree_rcu(old, rcu);
670 		} else {
671 			kfree(table);
672 			table = old;
673 		}
674 	}
675 }
676 
677 static void aio_nr_sub(unsigned nr)
678 {
679 	spin_lock(&aio_nr_lock);
680 	if (WARN_ON(aio_nr - nr > aio_nr))
681 		aio_nr = 0;
682 	else
683 		aio_nr -= nr;
684 	spin_unlock(&aio_nr_lock);
685 }
686 
687 /* ioctx_alloc
688  *	Allocates and initializes an ioctx.  Returns an ERR_PTR if it failed.
689  */
690 static struct kioctx *ioctx_alloc(unsigned nr_events)
691 {
692 	struct mm_struct *mm = current->mm;
693 	struct kioctx *ctx;
694 	int err = -ENOMEM;
695 
696 	/*
697 	 * We keep track of the number of available ringbuffer slots, to prevent
698 	 * overflow (reqs_available), and we also use percpu counters for this.
699 	 *
700 	 * So since up to half the slots might be on other cpu's percpu counters
701 	 * and unavailable, double nr_events so userspace sees what they
702 	 * expected: additionally, we move req_batch slots to/from percpu
703 	 * counters at a time, so make sure that isn't 0:
704 	 */
705 	nr_events = max(nr_events, num_possible_cpus() * 4);
706 	nr_events *= 2;
707 
708 	/* Prevent overflows */
709 	if (nr_events > (0x10000000U / sizeof(struct io_event))) {
710 		pr_debug("ENOMEM: nr_events too high\n");
711 		return ERR_PTR(-EINVAL);
712 	}
713 
714 	if (!nr_events || (unsigned long)nr_events > (aio_max_nr * 2UL))
715 		return ERR_PTR(-EAGAIN);
716 
717 	ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL);
718 	if (!ctx)
719 		return ERR_PTR(-ENOMEM);
720 
721 	ctx->max_reqs = nr_events;
722 
723 	spin_lock_init(&ctx->ctx_lock);
724 	spin_lock_init(&ctx->completion_lock);
725 	mutex_init(&ctx->ring_lock);
726 	/* Protect against page migration throughout kiotx setup by keeping
727 	 * the ring_lock mutex held until setup is complete. */
728 	mutex_lock(&ctx->ring_lock);
729 	init_waitqueue_head(&ctx->wait);
730 
731 	INIT_LIST_HEAD(&ctx->active_reqs);
732 
733 	if (percpu_ref_init(&ctx->users, free_ioctx_users, 0, GFP_KERNEL))
734 		goto err;
735 
736 	if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs, 0, GFP_KERNEL))
737 		goto err;
738 
739 	ctx->cpu = alloc_percpu(struct kioctx_cpu);
740 	if (!ctx->cpu)
741 		goto err;
742 
743 	err = aio_setup_ring(ctx);
744 	if (err < 0)
745 		goto err;
746 
747 	atomic_set(&ctx->reqs_available, ctx->nr_events - 1);
748 	ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4);
749 	if (ctx->req_batch < 1)
750 		ctx->req_batch = 1;
751 
752 	/* limit the number of system wide aios */
753 	spin_lock(&aio_nr_lock);
754 	if (aio_nr + nr_events > (aio_max_nr * 2UL) ||
755 	    aio_nr + nr_events < aio_nr) {
756 		spin_unlock(&aio_nr_lock);
757 		err = -EAGAIN;
758 		goto err_ctx;
759 	}
760 	aio_nr += ctx->max_reqs;
761 	spin_unlock(&aio_nr_lock);
762 
763 	percpu_ref_get(&ctx->users);	/* io_setup() will drop this ref */
764 	percpu_ref_get(&ctx->reqs);	/* free_ioctx_users() will drop this */
765 
766 	err = ioctx_add_table(ctx, mm);
767 	if (err)
768 		goto err_cleanup;
769 
770 	/* Release the ring_lock mutex now that all setup is complete. */
771 	mutex_unlock(&ctx->ring_lock);
772 
773 	pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
774 		 ctx, ctx->user_id, mm, ctx->nr_events);
775 	return ctx;
776 
777 err_cleanup:
778 	aio_nr_sub(ctx->max_reqs);
779 err_ctx:
780 	atomic_set(&ctx->dead, 1);
781 	if (ctx->mmap_size)
782 		vm_munmap(ctx->mmap_base, ctx->mmap_size);
783 	aio_free_ring(ctx);
784 err:
785 	mutex_unlock(&ctx->ring_lock);
786 	free_percpu(ctx->cpu);
787 	percpu_ref_exit(&ctx->reqs);
788 	percpu_ref_exit(&ctx->users);
789 	kmem_cache_free(kioctx_cachep, ctx);
790 	pr_debug("error allocating ioctx %d\n", err);
791 	return ERR_PTR(err);
792 }
793 
794 /* kill_ioctx
795  *	Cancels all outstanding aio requests on an aio context.  Used
796  *	when the processes owning a context have all exited to encourage
797  *	the rapid destruction of the kioctx.
798  */
799 static int kill_ioctx(struct mm_struct *mm, struct kioctx *ctx,
800 		      struct ctx_rq_wait *wait)
801 {
802 	struct kioctx_table *table;
803 
804 	spin_lock(&mm->ioctx_lock);
805 	if (atomic_xchg(&ctx->dead, 1)) {
806 		spin_unlock(&mm->ioctx_lock);
807 		return -EINVAL;
808 	}
809 
810 	table = rcu_dereference_raw(mm->ioctx_table);
811 	WARN_ON(ctx != table->table[ctx->id]);
812 	table->table[ctx->id] = NULL;
813 	spin_unlock(&mm->ioctx_lock);
814 
815 	/* percpu_ref_kill() will do the necessary call_rcu() */
816 	wake_up_all(&ctx->wait);
817 
818 	/*
819 	 * It'd be more correct to do this in free_ioctx(), after all
820 	 * the outstanding kiocbs have finished - but by then io_destroy
821 	 * has already returned, so io_setup() could potentially return
822 	 * -EAGAIN with no ioctxs actually in use (as far as userspace
823 	 *  could tell).
824 	 */
825 	aio_nr_sub(ctx->max_reqs);
826 
827 	if (ctx->mmap_size)
828 		vm_munmap(ctx->mmap_base, ctx->mmap_size);
829 
830 	ctx->rq_wait = wait;
831 	percpu_ref_kill(&ctx->users);
832 	return 0;
833 }
834 
835 /*
836  * exit_aio: called when the last user of mm goes away.  At this point, there is
837  * no way for any new requests to be submited or any of the io_* syscalls to be
838  * called on the context.
839  *
840  * There may be outstanding kiocbs, but free_ioctx() will explicitly wait on
841  * them.
842  */
843 void exit_aio(struct mm_struct *mm)
844 {
845 	struct kioctx_table *table = rcu_dereference_raw(mm->ioctx_table);
846 	struct ctx_rq_wait wait;
847 	int i, skipped;
848 
849 	if (!table)
850 		return;
851 
852 	atomic_set(&wait.count, table->nr);
853 	init_completion(&wait.comp);
854 
855 	skipped = 0;
856 	for (i = 0; i < table->nr; ++i) {
857 		struct kioctx *ctx = table->table[i];
858 
859 		if (!ctx) {
860 			skipped++;
861 			continue;
862 		}
863 
864 		/*
865 		 * We don't need to bother with munmap() here - exit_mmap(mm)
866 		 * is coming and it'll unmap everything. And we simply can't,
867 		 * this is not necessarily our ->mm.
868 		 * Since kill_ioctx() uses non-zero ->mmap_size as indicator
869 		 * that it needs to unmap the area, just set it to 0.
870 		 */
871 		ctx->mmap_size = 0;
872 		kill_ioctx(mm, ctx, &wait);
873 	}
874 
875 	if (!atomic_sub_and_test(skipped, &wait.count)) {
876 		/* Wait until all IO for the context are done. */
877 		wait_for_completion(&wait.comp);
878 	}
879 
880 	RCU_INIT_POINTER(mm->ioctx_table, NULL);
881 	kfree(table);
882 }
883 
884 static void put_reqs_available(struct kioctx *ctx, unsigned nr)
885 {
886 	struct kioctx_cpu *kcpu;
887 	unsigned long flags;
888 
889 	local_irq_save(flags);
890 	kcpu = this_cpu_ptr(ctx->cpu);
891 	kcpu->reqs_available += nr;
892 
893 	while (kcpu->reqs_available >= ctx->req_batch * 2) {
894 		kcpu->reqs_available -= ctx->req_batch;
895 		atomic_add(ctx->req_batch, &ctx->reqs_available);
896 	}
897 
898 	local_irq_restore(flags);
899 }
900 
901 static bool get_reqs_available(struct kioctx *ctx)
902 {
903 	struct kioctx_cpu *kcpu;
904 	bool ret = false;
905 	unsigned long flags;
906 
907 	local_irq_save(flags);
908 	kcpu = this_cpu_ptr(ctx->cpu);
909 	if (!kcpu->reqs_available) {
910 		int old, avail = atomic_read(&ctx->reqs_available);
911 
912 		do {
913 			if (avail < ctx->req_batch)
914 				goto out;
915 
916 			old = avail;
917 			avail = atomic_cmpxchg(&ctx->reqs_available,
918 					       avail, avail - ctx->req_batch);
919 		} while (avail != old);
920 
921 		kcpu->reqs_available += ctx->req_batch;
922 	}
923 
924 	ret = true;
925 	kcpu->reqs_available--;
926 out:
927 	local_irq_restore(flags);
928 	return ret;
929 }
930 
931 /* refill_reqs_available
932  *	Updates the reqs_available reference counts used for tracking the
933  *	number of free slots in the completion ring.  This can be called
934  *	from aio_complete() (to optimistically update reqs_available) or
935  *	from aio_get_req() (the we're out of events case).  It must be
936  *	called holding ctx->completion_lock.
937  */
938 static void refill_reqs_available(struct kioctx *ctx, unsigned head,
939                                   unsigned tail)
940 {
941 	unsigned events_in_ring, completed;
942 
943 	/* Clamp head since userland can write to it. */
944 	head %= ctx->nr_events;
945 	if (head <= tail)
946 		events_in_ring = tail - head;
947 	else
948 		events_in_ring = ctx->nr_events - (head - tail);
949 
950 	completed = ctx->completed_events;
951 	if (events_in_ring < completed)
952 		completed -= events_in_ring;
953 	else
954 		completed = 0;
955 
956 	if (!completed)
957 		return;
958 
959 	ctx->completed_events -= completed;
960 	put_reqs_available(ctx, completed);
961 }
962 
963 /* user_refill_reqs_available
964  *	Called to refill reqs_available when aio_get_req() encounters an
965  *	out of space in the completion ring.
966  */
967 static void user_refill_reqs_available(struct kioctx *ctx)
968 {
969 	spin_lock_irq(&ctx->completion_lock);
970 	if (ctx->completed_events) {
971 		struct aio_ring *ring;
972 		unsigned head;
973 
974 		/* Access of ring->head may race with aio_read_events_ring()
975 		 * here, but that's okay since whether we read the old version
976 		 * or the new version, and either will be valid.  The important
977 		 * part is that head cannot pass tail since we prevent
978 		 * aio_complete() from updating tail by holding
979 		 * ctx->completion_lock.  Even if head is invalid, the check
980 		 * against ctx->completed_events below will make sure we do the
981 		 * safe/right thing.
982 		 */
983 		ring = kmap_atomic(ctx->ring_pages[0]);
984 		head = ring->head;
985 		kunmap_atomic(ring);
986 
987 		refill_reqs_available(ctx, head, ctx->tail);
988 	}
989 
990 	spin_unlock_irq(&ctx->completion_lock);
991 }
992 
993 /* aio_get_req
994  *	Allocate a slot for an aio request.
995  * Returns NULL if no requests are free.
996  */
997 static inline struct aio_kiocb *aio_get_req(struct kioctx *ctx)
998 {
999 	struct aio_kiocb *req;
1000 
1001 	if (!get_reqs_available(ctx)) {
1002 		user_refill_reqs_available(ctx);
1003 		if (!get_reqs_available(ctx))
1004 			return NULL;
1005 	}
1006 
1007 	req = kmem_cache_alloc(kiocb_cachep, GFP_KERNEL|__GFP_ZERO);
1008 	if (unlikely(!req))
1009 		goto out_put;
1010 
1011 	percpu_ref_get(&ctx->reqs);
1012 
1013 	req->ki_ctx = ctx;
1014 	return req;
1015 out_put:
1016 	put_reqs_available(ctx, 1);
1017 	return NULL;
1018 }
1019 
1020 static void kiocb_free(struct aio_kiocb *req)
1021 {
1022 	if (req->common.ki_filp)
1023 		fput(req->common.ki_filp);
1024 	if (req->ki_eventfd != NULL)
1025 		eventfd_ctx_put(req->ki_eventfd);
1026 	kmem_cache_free(kiocb_cachep, req);
1027 }
1028 
1029 static struct kioctx *lookup_ioctx(unsigned long ctx_id)
1030 {
1031 	struct aio_ring __user *ring  = (void __user *)ctx_id;
1032 	struct mm_struct *mm = current->mm;
1033 	struct kioctx *ctx, *ret = NULL;
1034 	struct kioctx_table *table;
1035 	unsigned id;
1036 
1037 	if (get_user(id, &ring->id))
1038 		return NULL;
1039 
1040 	rcu_read_lock();
1041 	table = rcu_dereference(mm->ioctx_table);
1042 
1043 	if (!table || id >= table->nr)
1044 		goto out;
1045 
1046 	ctx = table->table[id];
1047 	if (ctx && ctx->user_id == ctx_id) {
1048 		percpu_ref_get(&ctx->users);
1049 		ret = ctx;
1050 	}
1051 out:
1052 	rcu_read_unlock();
1053 	return ret;
1054 }
1055 
1056 /* aio_complete
1057  *	Called when the io request on the given iocb is complete.
1058  */
1059 static void aio_complete(struct kiocb *kiocb, long res, long res2)
1060 {
1061 	struct aio_kiocb *iocb = container_of(kiocb, struct aio_kiocb, common);
1062 	struct kioctx	*ctx = iocb->ki_ctx;
1063 	struct aio_ring	*ring;
1064 	struct io_event	*ev_page, *event;
1065 	unsigned tail, pos, head;
1066 	unsigned long	flags;
1067 
1068 	/*
1069 	 * Special case handling for sync iocbs:
1070 	 *  - events go directly into the iocb for fast handling
1071 	 *  - the sync task with the iocb in its stack holds the single iocb
1072 	 *    ref, no other paths have a way to get another ref
1073 	 *  - the sync task helpfully left a reference to itself in the iocb
1074 	 */
1075 	BUG_ON(is_sync_kiocb(kiocb));
1076 
1077 	if (iocb->ki_list.next) {
1078 		unsigned long flags;
1079 
1080 		spin_lock_irqsave(&ctx->ctx_lock, flags);
1081 		list_del(&iocb->ki_list);
1082 		spin_unlock_irqrestore(&ctx->ctx_lock, flags);
1083 	}
1084 
1085 	/*
1086 	 * Add a completion event to the ring buffer. Must be done holding
1087 	 * ctx->completion_lock to prevent other code from messing with the tail
1088 	 * pointer since we might be called from irq context.
1089 	 */
1090 	spin_lock_irqsave(&ctx->completion_lock, flags);
1091 
1092 	tail = ctx->tail;
1093 	pos = tail + AIO_EVENTS_OFFSET;
1094 
1095 	if (++tail >= ctx->nr_events)
1096 		tail = 0;
1097 
1098 	ev_page = kmap_atomic(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
1099 	event = ev_page + pos % AIO_EVENTS_PER_PAGE;
1100 
1101 	event->obj = (u64)(unsigned long)iocb->ki_user_iocb;
1102 	event->data = iocb->ki_user_data;
1103 	event->res = res;
1104 	event->res2 = res2;
1105 
1106 	kunmap_atomic(ev_page);
1107 	flush_dcache_page(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
1108 
1109 	pr_debug("%p[%u]: %p: %p %Lx %lx %lx\n",
1110 		 ctx, tail, iocb, iocb->ki_user_iocb, iocb->ki_user_data,
1111 		 res, res2);
1112 
1113 	/* after flagging the request as done, we
1114 	 * must never even look at it again
1115 	 */
1116 	smp_wmb();	/* make event visible before updating tail */
1117 
1118 	ctx->tail = tail;
1119 
1120 	ring = kmap_atomic(ctx->ring_pages[0]);
1121 	head = ring->head;
1122 	ring->tail = tail;
1123 	kunmap_atomic(ring);
1124 	flush_dcache_page(ctx->ring_pages[0]);
1125 
1126 	ctx->completed_events++;
1127 	if (ctx->completed_events > 1)
1128 		refill_reqs_available(ctx, head, tail);
1129 	spin_unlock_irqrestore(&ctx->completion_lock, flags);
1130 
1131 	pr_debug("added to ring %p at [%u]\n", iocb, tail);
1132 
1133 	/*
1134 	 * Check if the user asked us to deliver the result through an
1135 	 * eventfd. The eventfd_signal() function is safe to be called
1136 	 * from IRQ context.
1137 	 */
1138 	if (iocb->ki_eventfd != NULL)
1139 		eventfd_signal(iocb->ki_eventfd, 1);
1140 
1141 	/* everything turned out well, dispose of the aiocb. */
1142 	kiocb_free(iocb);
1143 
1144 	/*
1145 	 * We have to order our ring_info tail store above and test
1146 	 * of the wait list below outside the wait lock.  This is
1147 	 * like in wake_up_bit() where clearing a bit has to be
1148 	 * ordered with the unlocked test.
1149 	 */
1150 	smp_mb();
1151 
1152 	if (waitqueue_active(&ctx->wait))
1153 		wake_up(&ctx->wait);
1154 
1155 	percpu_ref_put(&ctx->reqs);
1156 }
1157 
1158 /* aio_read_events_ring
1159  *	Pull an event off of the ioctx's event ring.  Returns the number of
1160  *	events fetched
1161  */
1162 static long aio_read_events_ring(struct kioctx *ctx,
1163 				 struct io_event __user *event, long nr)
1164 {
1165 	struct aio_ring *ring;
1166 	unsigned head, tail, pos;
1167 	long ret = 0;
1168 	int copy_ret;
1169 
1170 	/*
1171 	 * The mutex can block and wake us up and that will cause
1172 	 * wait_event_interruptible_hrtimeout() to schedule without sleeping
1173 	 * and repeat. This should be rare enough that it doesn't cause
1174 	 * peformance issues. See the comment in read_events() for more detail.
1175 	 */
1176 	sched_annotate_sleep();
1177 	mutex_lock(&ctx->ring_lock);
1178 
1179 	/* Access to ->ring_pages here is protected by ctx->ring_lock. */
1180 	ring = kmap_atomic(ctx->ring_pages[0]);
1181 	head = ring->head;
1182 	tail = ring->tail;
1183 	kunmap_atomic(ring);
1184 
1185 	/*
1186 	 * Ensure that once we've read the current tail pointer, that
1187 	 * we also see the events that were stored up to the tail.
1188 	 */
1189 	smp_rmb();
1190 
1191 	pr_debug("h%u t%u m%u\n", head, tail, ctx->nr_events);
1192 
1193 	if (head == tail)
1194 		goto out;
1195 
1196 	head %= ctx->nr_events;
1197 	tail %= ctx->nr_events;
1198 
1199 	while (ret < nr) {
1200 		long avail;
1201 		struct io_event *ev;
1202 		struct page *page;
1203 
1204 		avail = (head <= tail ?  tail : ctx->nr_events) - head;
1205 		if (head == tail)
1206 			break;
1207 
1208 		avail = min(avail, nr - ret);
1209 		avail = min_t(long, avail, AIO_EVENTS_PER_PAGE -
1210 			    ((head + AIO_EVENTS_OFFSET) % AIO_EVENTS_PER_PAGE));
1211 
1212 		pos = head + AIO_EVENTS_OFFSET;
1213 		page = ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE];
1214 		pos %= AIO_EVENTS_PER_PAGE;
1215 
1216 		ev = kmap(page);
1217 		copy_ret = copy_to_user(event + ret, ev + pos,
1218 					sizeof(*ev) * avail);
1219 		kunmap(page);
1220 
1221 		if (unlikely(copy_ret)) {
1222 			ret = -EFAULT;
1223 			goto out;
1224 		}
1225 
1226 		ret += avail;
1227 		head += avail;
1228 		head %= ctx->nr_events;
1229 	}
1230 
1231 	ring = kmap_atomic(ctx->ring_pages[0]);
1232 	ring->head = head;
1233 	kunmap_atomic(ring);
1234 	flush_dcache_page(ctx->ring_pages[0]);
1235 
1236 	pr_debug("%li  h%u t%u\n", ret, head, tail);
1237 out:
1238 	mutex_unlock(&ctx->ring_lock);
1239 
1240 	return ret;
1241 }
1242 
1243 static bool aio_read_events(struct kioctx *ctx, long min_nr, long nr,
1244 			    struct io_event __user *event, long *i)
1245 {
1246 	long ret = aio_read_events_ring(ctx, event + *i, nr - *i);
1247 
1248 	if (ret > 0)
1249 		*i += ret;
1250 
1251 	if (unlikely(atomic_read(&ctx->dead)))
1252 		ret = -EINVAL;
1253 
1254 	if (!*i)
1255 		*i = ret;
1256 
1257 	return ret < 0 || *i >= min_nr;
1258 }
1259 
1260 static long read_events(struct kioctx *ctx, long min_nr, long nr,
1261 			struct io_event __user *event,
1262 			struct timespec __user *timeout)
1263 {
1264 	ktime_t until = { .tv64 = KTIME_MAX };
1265 	long ret = 0;
1266 
1267 	if (timeout) {
1268 		struct timespec	ts;
1269 
1270 		if (unlikely(copy_from_user(&ts, timeout, sizeof(ts))))
1271 			return -EFAULT;
1272 
1273 		until = timespec_to_ktime(ts);
1274 	}
1275 
1276 	/*
1277 	 * Note that aio_read_events() is being called as the conditional - i.e.
1278 	 * we're calling it after prepare_to_wait() has set task state to
1279 	 * TASK_INTERRUPTIBLE.
1280 	 *
1281 	 * But aio_read_events() can block, and if it blocks it's going to flip
1282 	 * the task state back to TASK_RUNNING.
1283 	 *
1284 	 * This should be ok, provided it doesn't flip the state back to
1285 	 * TASK_RUNNING and return 0 too much - that causes us to spin. That
1286 	 * will only happen if the mutex_lock() call blocks, and we then find
1287 	 * the ringbuffer empty. So in practice we should be ok, but it's
1288 	 * something to be aware of when touching this code.
1289 	 */
1290 	if (until.tv64 == 0)
1291 		aio_read_events(ctx, min_nr, nr, event, &ret);
1292 	else
1293 		wait_event_interruptible_hrtimeout(ctx->wait,
1294 				aio_read_events(ctx, min_nr, nr, event, &ret),
1295 				until);
1296 
1297 	if (!ret && signal_pending(current))
1298 		ret = -EINTR;
1299 
1300 	return ret;
1301 }
1302 
1303 /* sys_io_setup:
1304  *	Create an aio_context capable of receiving at least nr_events.
1305  *	ctxp must not point to an aio_context that already exists, and
1306  *	must be initialized to 0 prior to the call.  On successful
1307  *	creation of the aio_context, *ctxp is filled in with the resulting
1308  *	handle.  May fail with -EINVAL if *ctxp is not initialized,
1309  *	if the specified nr_events exceeds internal limits.  May fail
1310  *	with -EAGAIN if the specified nr_events exceeds the user's limit
1311  *	of available events.  May fail with -ENOMEM if insufficient kernel
1312  *	resources are available.  May fail with -EFAULT if an invalid
1313  *	pointer is passed for ctxp.  Will fail with -ENOSYS if not
1314  *	implemented.
1315  */
1316 SYSCALL_DEFINE2(io_setup, unsigned, nr_events, aio_context_t __user *, ctxp)
1317 {
1318 	struct kioctx *ioctx = NULL;
1319 	unsigned long ctx;
1320 	long ret;
1321 
1322 	ret = get_user(ctx, ctxp);
1323 	if (unlikely(ret))
1324 		goto out;
1325 
1326 	ret = -EINVAL;
1327 	if (unlikely(ctx || nr_events == 0)) {
1328 		pr_debug("EINVAL: ctx %lu nr_events %u\n",
1329 		         ctx, nr_events);
1330 		goto out;
1331 	}
1332 
1333 	ioctx = ioctx_alloc(nr_events);
1334 	ret = PTR_ERR(ioctx);
1335 	if (!IS_ERR(ioctx)) {
1336 		ret = put_user(ioctx->user_id, ctxp);
1337 		if (ret)
1338 			kill_ioctx(current->mm, ioctx, NULL);
1339 		percpu_ref_put(&ioctx->users);
1340 	}
1341 
1342 out:
1343 	return ret;
1344 }
1345 
1346 /* sys_io_destroy:
1347  *	Destroy the aio_context specified.  May cancel any outstanding
1348  *	AIOs and block on completion.  Will fail with -ENOSYS if not
1349  *	implemented.  May fail with -EINVAL if the context pointed to
1350  *	is invalid.
1351  */
1352 SYSCALL_DEFINE1(io_destroy, aio_context_t, ctx)
1353 {
1354 	struct kioctx *ioctx = lookup_ioctx(ctx);
1355 	if (likely(NULL != ioctx)) {
1356 		struct ctx_rq_wait wait;
1357 		int ret;
1358 
1359 		init_completion(&wait.comp);
1360 		atomic_set(&wait.count, 1);
1361 
1362 		/* Pass requests_done to kill_ioctx() where it can be set
1363 		 * in a thread-safe way. If we try to set it here then we have
1364 		 * a race condition if two io_destroy() called simultaneously.
1365 		 */
1366 		ret = kill_ioctx(current->mm, ioctx, &wait);
1367 		percpu_ref_put(&ioctx->users);
1368 
1369 		/* Wait until all IO for the context are done. Otherwise kernel
1370 		 * keep using user-space buffers even if user thinks the context
1371 		 * is destroyed.
1372 		 */
1373 		if (!ret)
1374 			wait_for_completion(&wait.comp);
1375 
1376 		return ret;
1377 	}
1378 	pr_debug("EINVAL: invalid context id\n");
1379 	return -EINVAL;
1380 }
1381 
1382 typedef ssize_t (rw_iter_op)(struct kiocb *, struct iov_iter *);
1383 
1384 static int aio_setup_vectored_rw(int rw, char __user *buf, size_t len,
1385 				 struct iovec **iovec,
1386 				 bool compat,
1387 				 struct iov_iter *iter)
1388 {
1389 #ifdef CONFIG_COMPAT
1390 	if (compat)
1391 		return compat_import_iovec(rw,
1392 				(struct compat_iovec __user *)buf,
1393 				len, UIO_FASTIOV, iovec, iter);
1394 #endif
1395 	return import_iovec(rw, (struct iovec __user *)buf,
1396 				len, UIO_FASTIOV, iovec, iter);
1397 }
1398 
1399 /*
1400  * aio_run_iocb:
1401  *	Performs the initial checks and io submission.
1402  */
1403 static ssize_t aio_run_iocb(struct kiocb *req, unsigned opcode,
1404 			    char __user *buf, size_t len, bool compat)
1405 {
1406 	struct file *file = req->ki_filp;
1407 	ssize_t ret;
1408 	int rw;
1409 	fmode_t mode;
1410 	rw_iter_op *iter_op;
1411 	struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1412 	struct iov_iter iter;
1413 
1414 	switch (opcode) {
1415 	case IOCB_CMD_PREAD:
1416 	case IOCB_CMD_PREADV:
1417 		mode	= FMODE_READ;
1418 		rw	= READ;
1419 		iter_op	= file->f_op->read_iter;
1420 		goto rw_common;
1421 
1422 	case IOCB_CMD_PWRITE:
1423 	case IOCB_CMD_PWRITEV:
1424 		mode	= FMODE_WRITE;
1425 		rw	= WRITE;
1426 		iter_op	= file->f_op->write_iter;
1427 		goto rw_common;
1428 rw_common:
1429 		if (unlikely(!(file->f_mode & mode)))
1430 			return -EBADF;
1431 
1432 		if (!iter_op)
1433 			return -EINVAL;
1434 
1435 		if (opcode == IOCB_CMD_PREADV || opcode == IOCB_CMD_PWRITEV)
1436 			ret = aio_setup_vectored_rw(rw, buf, len,
1437 						&iovec, compat, &iter);
1438 		else {
1439 			ret = import_single_range(rw, buf, len, iovec, &iter);
1440 			iovec = NULL;
1441 		}
1442 		if (!ret)
1443 			ret = rw_verify_area(rw, file, &req->ki_pos,
1444 					     iov_iter_count(&iter));
1445 		if (ret < 0) {
1446 			kfree(iovec);
1447 			return ret;
1448 		}
1449 
1450 		len = ret;
1451 
1452 		if (rw == WRITE)
1453 			file_start_write(file);
1454 
1455 		ret = iter_op(req, &iter);
1456 
1457 		if (rw == WRITE)
1458 			file_end_write(file);
1459 		kfree(iovec);
1460 		break;
1461 
1462 	case IOCB_CMD_FDSYNC:
1463 		if (!file->f_op->aio_fsync)
1464 			return -EINVAL;
1465 
1466 		ret = file->f_op->aio_fsync(req, 1);
1467 		break;
1468 
1469 	case IOCB_CMD_FSYNC:
1470 		if (!file->f_op->aio_fsync)
1471 			return -EINVAL;
1472 
1473 		ret = file->f_op->aio_fsync(req, 0);
1474 		break;
1475 
1476 	default:
1477 		pr_debug("EINVAL: no operation provided\n");
1478 		return -EINVAL;
1479 	}
1480 
1481 	if (ret != -EIOCBQUEUED) {
1482 		/*
1483 		 * There's no easy way to restart the syscall since other AIO's
1484 		 * may be already running. Just fail this IO with EINTR.
1485 		 */
1486 		if (unlikely(ret == -ERESTARTSYS || ret == -ERESTARTNOINTR ||
1487 			     ret == -ERESTARTNOHAND ||
1488 			     ret == -ERESTART_RESTARTBLOCK))
1489 			ret = -EINTR;
1490 		aio_complete(req, ret, 0);
1491 	}
1492 
1493 	return 0;
1494 }
1495 
1496 static int io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb,
1497 			 struct iocb *iocb, bool compat)
1498 {
1499 	struct aio_kiocb *req;
1500 	ssize_t ret;
1501 
1502 	/* enforce forwards compatibility on users */
1503 	if (unlikely(iocb->aio_reserved1 || iocb->aio_reserved2)) {
1504 		pr_debug("EINVAL: reserve field set\n");
1505 		return -EINVAL;
1506 	}
1507 
1508 	/* prevent overflows */
1509 	if (unlikely(
1510 	    (iocb->aio_buf != (unsigned long)iocb->aio_buf) ||
1511 	    (iocb->aio_nbytes != (size_t)iocb->aio_nbytes) ||
1512 	    ((ssize_t)iocb->aio_nbytes < 0)
1513 	   )) {
1514 		pr_debug("EINVAL: overflow check\n");
1515 		return -EINVAL;
1516 	}
1517 
1518 	req = aio_get_req(ctx);
1519 	if (unlikely(!req))
1520 		return -EAGAIN;
1521 
1522 	req->common.ki_filp = fget(iocb->aio_fildes);
1523 	if (unlikely(!req->common.ki_filp)) {
1524 		ret = -EBADF;
1525 		goto out_put_req;
1526 	}
1527 	req->common.ki_pos = iocb->aio_offset;
1528 	req->common.ki_complete = aio_complete;
1529 	req->common.ki_flags = iocb_flags(req->common.ki_filp);
1530 
1531 	if (iocb->aio_flags & IOCB_FLAG_RESFD) {
1532 		/*
1533 		 * If the IOCB_FLAG_RESFD flag of aio_flags is set, get an
1534 		 * instance of the file* now. The file descriptor must be
1535 		 * an eventfd() fd, and will be signaled for each completed
1536 		 * event using the eventfd_signal() function.
1537 		 */
1538 		req->ki_eventfd = eventfd_ctx_fdget((int) iocb->aio_resfd);
1539 		if (IS_ERR(req->ki_eventfd)) {
1540 			ret = PTR_ERR(req->ki_eventfd);
1541 			req->ki_eventfd = NULL;
1542 			goto out_put_req;
1543 		}
1544 
1545 		req->common.ki_flags |= IOCB_EVENTFD;
1546 	}
1547 
1548 	ret = put_user(KIOCB_KEY, &user_iocb->aio_key);
1549 	if (unlikely(ret)) {
1550 		pr_debug("EFAULT: aio_key\n");
1551 		goto out_put_req;
1552 	}
1553 
1554 	req->ki_user_iocb = user_iocb;
1555 	req->ki_user_data = iocb->aio_data;
1556 
1557 	ret = aio_run_iocb(&req->common, iocb->aio_lio_opcode,
1558 			   (char __user *)(unsigned long)iocb->aio_buf,
1559 			   iocb->aio_nbytes,
1560 			   compat);
1561 	if (ret)
1562 		goto out_put_req;
1563 
1564 	return 0;
1565 out_put_req:
1566 	put_reqs_available(ctx, 1);
1567 	percpu_ref_put(&ctx->reqs);
1568 	kiocb_free(req);
1569 	return ret;
1570 }
1571 
1572 long do_io_submit(aio_context_t ctx_id, long nr,
1573 		  struct iocb __user *__user *iocbpp, bool compat)
1574 {
1575 	struct kioctx *ctx;
1576 	long ret = 0;
1577 	int i = 0;
1578 	struct blk_plug plug;
1579 
1580 	if (unlikely(nr < 0))
1581 		return -EINVAL;
1582 
1583 	if (unlikely(nr > LONG_MAX/sizeof(*iocbpp)))
1584 		nr = LONG_MAX/sizeof(*iocbpp);
1585 
1586 	if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))
1587 		return -EFAULT;
1588 
1589 	ctx = lookup_ioctx(ctx_id);
1590 	if (unlikely(!ctx)) {
1591 		pr_debug("EINVAL: invalid context id\n");
1592 		return -EINVAL;
1593 	}
1594 
1595 	blk_start_plug(&plug);
1596 
1597 	/*
1598 	 * AKPM: should this return a partial result if some of the IOs were
1599 	 * successfully submitted?
1600 	 */
1601 	for (i=0; i<nr; i++) {
1602 		struct iocb __user *user_iocb;
1603 		struct iocb tmp;
1604 
1605 		if (unlikely(__get_user(user_iocb, iocbpp + i))) {
1606 			ret = -EFAULT;
1607 			break;
1608 		}
1609 
1610 		if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
1611 			ret = -EFAULT;
1612 			break;
1613 		}
1614 
1615 		ret = io_submit_one(ctx, user_iocb, &tmp, compat);
1616 		if (ret)
1617 			break;
1618 	}
1619 	blk_finish_plug(&plug);
1620 
1621 	percpu_ref_put(&ctx->users);
1622 	return i ? i : ret;
1623 }
1624 
1625 /* sys_io_submit:
1626  *	Queue the nr iocbs pointed to by iocbpp for processing.  Returns
1627  *	the number of iocbs queued.  May return -EINVAL if the aio_context
1628  *	specified by ctx_id is invalid, if nr is < 0, if the iocb at
1629  *	*iocbpp[0] is not properly initialized, if the operation specified
1630  *	is invalid for the file descriptor in the iocb.  May fail with
1631  *	-EFAULT if any of the data structures point to invalid data.  May
1632  *	fail with -EBADF if the file descriptor specified in the first
1633  *	iocb is invalid.  May fail with -EAGAIN if insufficient resources
1634  *	are available to queue any iocbs.  Will return 0 if nr is 0.  Will
1635  *	fail with -ENOSYS if not implemented.
1636  */
1637 SYSCALL_DEFINE3(io_submit, aio_context_t, ctx_id, long, nr,
1638 		struct iocb __user * __user *, iocbpp)
1639 {
1640 	return do_io_submit(ctx_id, nr, iocbpp, 0);
1641 }
1642 
1643 /* lookup_kiocb
1644  *	Finds a given iocb for cancellation.
1645  */
1646 static struct aio_kiocb *
1647 lookup_kiocb(struct kioctx *ctx, struct iocb __user *iocb, u32 key)
1648 {
1649 	struct aio_kiocb *kiocb;
1650 
1651 	assert_spin_locked(&ctx->ctx_lock);
1652 
1653 	if (key != KIOCB_KEY)
1654 		return NULL;
1655 
1656 	/* TODO: use a hash or array, this sucks. */
1657 	list_for_each_entry(kiocb, &ctx->active_reqs, ki_list) {
1658 		if (kiocb->ki_user_iocb == iocb)
1659 			return kiocb;
1660 	}
1661 	return NULL;
1662 }
1663 
1664 /* sys_io_cancel:
1665  *	Attempts to cancel an iocb previously passed to io_submit.  If
1666  *	the operation is successfully cancelled, the resulting event is
1667  *	copied into the memory pointed to by result without being placed
1668  *	into the completion queue and 0 is returned.  May fail with
1669  *	-EFAULT if any of the data structures pointed to are invalid.
1670  *	May fail with -EINVAL if aio_context specified by ctx_id is
1671  *	invalid.  May fail with -EAGAIN if the iocb specified was not
1672  *	cancelled.  Will fail with -ENOSYS if not implemented.
1673  */
1674 SYSCALL_DEFINE3(io_cancel, aio_context_t, ctx_id, struct iocb __user *, iocb,
1675 		struct io_event __user *, result)
1676 {
1677 	struct kioctx *ctx;
1678 	struct aio_kiocb *kiocb;
1679 	u32 key;
1680 	int ret;
1681 
1682 	ret = get_user(key, &iocb->aio_key);
1683 	if (unlikely(ret))
1684 		return -EFAULT;
1685 
1686 	ctx = lookup_ioctx(ctx_id);
1687 	if (unlikely(!ctx))
1688 		return -EINVAL;
1689 
1690 	spin_lock_irq(&ctx->ctx_lock);
1691 
1692 	kiocb = lookup_kiocb(ctx, iocb, key);
1693 	if (kiocb)
1694 		ret = kiocb_cancel(kiocb);
1695 	else
1696 		ret = -EINVAL;
1697 
1698 	spin_unlock_irq(&ctx->ctx_lock);
1699 
1700 	if (!ret) {
1701 		/*
1702 		 * The result argument is no longer used - the io_event is
1703 		 * always delivered via the ring buffer. -EINPROGRESS indicates
1704 		 * cancellation is progress:
1705 		 */
1706 		ret = -EINPROGRESS;
1707 	}
1708 
1709 	percpu_ref_put(&ctx->users);
1710 
1711 	return ret;
1712 }
1713 
1714 /* io_getevents:
1715  *	Attempts to read at least min_nr events and up to nr events from
1716  *	the completion queue for the aio_context specified by ctx_id. If
1717  *	it succeeds, the number of read events is returned. May fail with
1718  *	-EINVAL if ctx_id is invalid, if min_nr is out of range, if nr is
1719  *	out of range, if timeout is out of range.  May fail with -EFAULT
1720  *	if any of the memory specified is invalid.  May return 0 or
1721  *	< min_nr if the timeout specified by timeout has elapsed
1722  *	before sufficient events are available, where timeout == NULL
1723  *	specifies an infinite timeout. Note that the timeout pointed to by
1724  *	timeout is relative.  Will fail with -ENOSYS if not implemented.
1725  */
1726 SYSCALL_DEFINE5(io_getevents, aio_context_t, ctx_id,
1727 		long, min_nr,
1728 		long, nr,
1729 		struct io_event __user *, events,
1730 		struct timespec __user *, timeout)
1731 {
1732 	struct kioctx *ioctx = lookup_ioctx(ctx_id);
1733 	long ret = -EINVAL;
1734 
1735 	if (likely(ioctx)) {
1736 		if (likely(min_nr <= nr && min_nr >= 0))
1737 			ret = read_events(ioctx, min_nr, nr, events, timeout);
1738 		percpu_ref_put(&ioctx->users);
1739 	}
1740 	return ret;
1741 }
1742