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