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