fs: introduce new ->get_poll_head and ->poll_mask methods
[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);
d52a8f9e 642 kiocb_cancel(req);
4faa9996 643 list_del_init(&req->ki_list);
36f55889
KO
644 }
645
646 spin_unlock_irq(&ctx->ctx_lock);
647
e34ecee2
KO
648 percpu_ref_kill(&ctx->reqs);
649 percpu_ref_put(&ctx->reqs);
36f55889
KO
650}
651
db446a08
BL
652static int ioctx_add_table(struct kioctx *ctx, struct mm_struct *mm)
653{
654 unsigned i, new_nr;
655 struct kioctx_table *table, *old;
656 struct aio_ring *ring;
657
658 spin_lock(&mm->ioctx_lock);
855ef0de 659 table = rcu_dereference_raw(mm->ioctx_table);
db446a08
BL
660
661 while (1) {
662 if (table)
663 for (i = 0; i < table->nr; i++)
d0264c01 664 if (!rcu_access_pointer(table->table[i])) {
db446a08 665 ctx->id = i;
d0264c01 666 rcu_assign_pointer(table->table[i], ctx);
db446a08
BL
667 spin_unlock(&mm->ioctx_lock);
668
fa8a53c3
BL
669 /* While kioctx setup is in progress,
670 * we are protected from page migration
671 * changes ring_pages by ->ring_lock.
672 */
db446a08
BL
673 ring = kmap_atomic(ctx->ring_pages[0]);
674 ring->id = ctx->id;
675 kunmap_atomic(ring);
676 return 0;
677 }
678
679 new_nr = (table ? table->nr : 1) * 4;
db446a08
BL
680 spin_unlock(&mm->ioctx_lock);
681
682 table = kzalloc(sizeof(*table) + sizeof(struct kioctx *) *
683 new_nr, GFP_KERNEL);
684 if (!table)
685 return -ENOMEM;
686
687 table->nr = new_nr;
688
689 spin_lock(&mm->ioctx_lock);
855ef0de 690 old = rcu_dereference_raw(mm->ioctx_table);
db446a08
BL
691
692 if (!old) {
693 rcu_assign_pointer(mm->ioctx_table, table);
694 } else if (table->nr > old->nr) {
695 memcpy(table->table, old->table,
696 old->nr * sizeof(struct kioctx *));
697
698 rcu_assign_pointer(mm->ioctx_table, table);
699 kfree_rcu(old, rcu);
700 } else {
701 kfree(table);
702 table = old;
703 }
704 }
705}
706
e34ecee2
KO
707static void aio_nr_sub(unsigned nr)
708{
709 spin_lock(&aio_nr_lock);
710 if (WARN_ON(aio_nr - nr > aio_nr))
711 aio_nr = 0;
712 else
713 aio_nr -= nr;
714 spin_unlock(&aio_nr_lock);
715}
716
1da177e4
LT
717/* ioctx_alloc
718 * Allocates and initializes an ioctx. Returns an ERR_PTR if it failed.
719 */
720static struct kioctx *ioctx_alloc(unsigned nr_events)
721{
41003a7b 722 struct mm_struct *mm = current->mm;
1da177e4 723 struct kioctx *ctx;
e23754f8 724 int err = -ENOMEM;
1da177e4 725
2a8a9867
MFO
726 /*
727 * Store the original nr_events -- what userspace passed to io_setup(),
728 * for counting against the global limit -- before it changes.
729 */
730 unsigned int max_reqs = nr_events;
731
e1bdd5f2
KO
732 /*
733 * We keep track of the number of available ringbuffer slots, to prevent
734 * overflow (reqs_available), and we also use percpu counters for this.
735 *
736 * So since up to half the slots might be on other cpu's percpu counters
737 * and unavailable, double nr_events so userspace sees what they
738 * expected: additionally, we move req_batch slots to/from percpu
739 * counters at a time, so make sure that isn't 0:
740 */
741 nr_events = max(nr_events, num_possible_cpus() * 4);
742 nr_events *= 2;
743
1da177e4 744 /* Prevent overflows */
08397acd 745 if (nr_events > (0x10000000U / sizeof(struct io_event))) {
1da177e4
LT
746 pr_debug("ENOMEM: nr_events too high\n");
747 return ERR_PTR(-EINVAL);
748 }
749
2a8a9867 750 if (!nr_events || (unsigned long)max_reqs > aio_max_nr)
1da177e4
LT
751 return ERR_PTR(-EAGAIN);
752
c3762229 753 ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL);
1da177e4
LT
754 if (!ctx)
755 return ERR_PTR(-ENOMEM);
756
2a8a9867 757 ctx->max_reqs = max_reqs;
1da177e4 758
1da177e4 759 spin_lock_init(&ctx->ctx_lock);
0460fef2 760 spin_lock_init(&ctx->completion_lock);
58c85dc2 761 mutex_init(&ctx->ring_lock);
fa8a53c3
BL
762 /* Protect against page migration throughout kiotx setup by keeping
763 * the ring_lock mutex held until setup is complete. */
764 mutex_lock(&ctx->ring_lock);
1da177e4
LT
765 init_waitqueue_head(&ctx->wait);
766
767 INIT_LIST_HEAD(&ctx->active_reqs);
1da177e4 768
2aad2a86 769 if (percpu_ref_init(&ctx->users, free_ioctx_users, 0, GFP_KERNEL))
fa8a53c3
BL
770 goto err;
771
2aad2a86 772 if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs, 0, GFP_KERNEL))
fa8a53c3
BL
773 goto err;
774
e1bdd5f2
KO
775 ctx->cpu = alloc_percpu(struct kioctx_cpu);
776 if (!ctx->cpu)
e34ecee2 777 goto err;
1da177e4 778
2a8a9867 779 err = aio_setup_ring(ctx, nr_events);
fa8a53c3 780 if (err < 0)
e34ecee2 781 goto err;
e1bdd5f2 782
34e83fc6 783 atomic_set(&ctx->reqs_available, ctx->nr_events - 1);
e1bdd5f2 784 ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4);
6878ea72
BL
785 if (ctx->req_batch < 1)
786 ctx->req_batch = 1;
34e83fc6 787
1da177e4 788 /* limit the number of system wide aios */
9fa1cb39 789 spin_lock(&aio_nr_lock);
2a8a9867
MFO
790 if (aio_nr + ctx->max_reqs > aio_max_nr ||
791 aio_nr + ctx->max_reqs < aio_nr) {
9fa1cb39 792 spin_unlock(&aio_nr_lock);
e34ecee2 793 err = -EAGAIN;
d1b94327 794 goto err_ctx;
2dd542b7
AV
795 }
796 aio_nr += ctx->max_reqs;
9fa1cb39 797 spin_unlock(&aio_nr_lock);
1da177e4 798
1881686f
BL
799 percpu_ref_get(&ctx->users); /* io_setup() will drop this ref */
800 percpu_ref_get(&ctx->reqs); /* free_ioctx_users() will drop this */
723be6e3 801
da90382c
BL
802 err = ioctx_add_table(ctx, mm);
803 if (err)
e34ecee2 804 goto err_cleanup;
da90382c 805
fa8a53c3
BL
806 /* Release the ring_lock mutex now that all setup is complete. */
807 mutex_unlock(&ctx->ring_lock);
808
caf4167a 809 pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
58c85dc2 810 ctx, ctx->user_id, mm, ctx->nr_events);
1da177e4
LT
811 return ctx;
812
e34ecee2
KO
813err_cleanup:
814 aio_nr_sub(ctx->max_reqs);
d1b94327 815err_ctx:
deeb8525
AV
816 atomic_set(&ctx->dead, 1);
817 if (ctx->mmap_size)
818 vm_munmap(ctx->mmap_base, ctx->mmap_size);
d1b94327 819 aio_free_ring(ctx);
e34ecee2 820err:
fa8a53c3 821 mutex_unlock(&ctx->ring_lock);
e1bdd5f2 822 free_percpu(ctx->cpu);
9a1049da
TH
823 percpu_ref_exit(&ctx->reqs);
824 percpu_ref_exit(&ctx->users);
1da177e4 825 kmem_cache_free(kioctx_cachep, ctx);
caf4167a 826 pr_debug("error allocating ioctx %d\n", err);
e23754f8 827 return ERR_PTR(err);
1da177e4
LT
828}
829
36f55889
KO
830/* kill_ioctx
831 * Cancels all outstanding aio requests on an aio context. Used
832 * when the processes owning a context have all exited to encourage
833 * the rapid destruction of the kioctx.
834 */
fb2d4483 835static int kill_ioctx(struct mm_struct *mm, struct kioctx *ctx,
dc48e56d 836 struct ctx_rq_wait *wait)
36f55889 837{
fa88b6f8 838 struct kioctx_table *table;
db446a08 839
b2edffdd
AV
840 spin_lock(&mm->ioctx_lock);
841 if (atomic_xchg(&ctx->dead, 1)) {
842 spin_unlock(&mm->ioctx_lock);
fa88b6f8 843 return -EINVAL;
b2edffdd 844 }
db446a08 845
855ef0de 846 table = rcu_dereference_raw(mm->ioctx_table);
d0264c01
TH
847 WARN_ON(ctx != rcu_access_pointer(table->table[ctx->id]));
848 RCU_INIT_POINTER(table->table[ctx->id], NULL);
fa88b6f8 849 spin_unlock(&mm->ioctx_lock);
4fcc712f 850
a6d7cff4 851 /* free_ioctx_reqs() will do the necessary RCU synchronization */
fa88b6f8 852 wake_up_all(&ctx->wait);
4fcc712f 853
fa88b6f8
BL
854 /*
855 * It'd be more correct to do this in free_ioctx(), after all
856 * the outstanding kiocbs have finished - but by then io_destroy
857 * has already returned, so io_setup() could potentially return
858 * -EAGAIN with no ioctxs actually in use (as far as userspace
859 * could tell).
860 */
861 aio_nr_sub(ctx->max_reqs);
4fcc712f 862
fa88b6f8
BL
863 if (ctx->mmap_size)
864 vm_munmap(ctx->mmap_base, ctx->mmap_size);
fb2d4483 865
dc48e56d 866 ctx->rq_wait = wait;
fa88b6f8
BL
867 percpu_ref_kill(&ctx->users);
868 return 0;
1da177e4
LT
869}
870
36f55889
KO
871/*
872 * exit_aio: called when the last user of mm goes away. At this point, there is
873 * no way for any new requests to be submited or any of the io_* syscalls to be
874 * called on the context.
875 *
876 * There may be outstanding kiocbs, but free_ioctx() will explicitly wait on
877 * them.
1da177e4 878 */
fc9b52cd 879void exit_aio(struct mm_struct *mm)
1da177e4 880{
4b70ac5f 881 struct kioctx_table *table = rcu_dereference_raw(mm->ioctx_table);
dc48e56d
JA
882 struct ctx_rq_wait wait;
883 int i, skipped;
db446a08 884
4b70ac5f
ON
885 if (!table)
886 return;
db446a08 887
dc48e56d
JA
888 atomic_set(&wait.count, table->nr);
889 init_completion(&wait.comp);
890
891 skipped = 0;
4b70ac5f 892 for (i = 0; i < table->nr; ++i) {
d0264c01
TH
893 struct kioctx *ctx =
894 rcu_dereference_protected(table->table[i], true);
abf137dd 895
dc48e56d
JA
896 if (!ctx) {
897 skipped++;
4b70ac5f 898 continue;
dc48e56d
JA
899 }
900
936af157 901 /*
4b70ac5f
ON
902 * We don't need to bother with munmap() here - exit_mmap(mm)
903 * is coming and it'll unmap everything. And we simply can't,
904 * this is not necessarily our ->mm.
905 * Since kill_ioctx() uses non-zero ->mmap_size as indicator
906 * that it needs to unmap the area, just set it to 0.
936af157 907 */
58c85dc2 908 ctx->mmap_size = 0;
dc48e56d
JA
909 kill_ioctx(mm, ctx, &wait);
910 }
36f55889 911
dc48e56d 912 if (!atomic_sub_and_test(skipped, &wait.count)) {
6098b45b 913 /* Wait until all IO for the context are done. */
dc48e56d 914 wait_for_completion(&wait.comp);
1da177e4 915 }
4b70ac5f
ON
916
917 RCU_INIT_POINTER(mm->ioctx_table, NULL);
918 kfree(table);
1da177e4
LT
919}
920
e1bdd5f2
KO
921static void put_reqs_available(struct kioctx *ctx, unsigned nr)
922{
923 struct kioctx_cpu *kcpu;
263782c1 924 unsigned long flags;
e1bdd5f2 925
263782c1 926 local_irq_save(flags);
be6fb451 927 kcpu = this_cpu_ptr(ctx->cpu);
e1bdd5f2 928 kcpu->reqs_available += nr;
263782c1 929
e1bdd5f2
KO
930 while (kcpu->reqs_available >= ctx->req_batch * 2) {
931 kcpu->reqs_available -= ctx->req_batch;
932 atomic_add(ctx->req_batch, &ctx->reqs_available);
933 }
934
263782c1 935 local_irq_restore(flags);
e1bdd5f2
KO
936}
937
938static bool get_reqs_available(struct kioctx *ctx)
939{
940 struct kioctx_cpu *kcpu;
941 bool ret = false;
263782c1 942 unsigned long flags;
e1bdd5f2 943
263782c1 944 local_irq_save(flags);
be6fb451 945 kcpu = this_cpu_ptr(ctx->cpu);
e1bdd5f2
KO
946 if (!kcpu->reqs_available) {
947 int old, avail = atomic_read(&ctx->reqs_available);
948
949 do {
950 if (avail < ctx->req_batch)
951 goto out;
952
953 old = avail;
954 avail = atomic_cmpxchg(&ctx->reqs_available,
955 avail, avail - ctx->req_batch);
956 } while (avail != old);
957
958 kcpu->reqs_available += ctx->req_batch;
959 }
960
961 ret = true;
962 kcpu->reqs_available--;
963out:
263782c1 964 local_irq_restore(flags);
e1bdd5f2
KO
965 return ret;
966}
967
d856f32a
BL
968/* refill_reqs_available
969 * Updates the reqs_available reference counts used for tracking the
970 * number of free slots in the completion ring. This can be called
971 * from aio_complete() (to optimistically update reqs_available) or
972 * from aio_get_req() (the we're out of events case). It must be
973 * called holding ctx->completion_lock.
974 */
975static void refill_reqs_available(struct kioctx *ctx, unsigned head,
976 unsigned tail)
977{
978 unsigned events_in_ring, completed;
979
980 /* Clamp head since userland can write to it. */
981 head %= ctx->nr_events;
982 if (head <= tail)
983 events_in_ring = tail - head;
984 else
985 events_in_ring = ctx->nr_events - (head - tail);
986
987 completed = ctx->completed_events;
988 if (events_in_ring < completed)
989 completed -= events_in_ring;
990 else
991 completed = 0;
992
993 if (!completed)
994 return;
995
996 ctx->completed_events -= completed;
997 put_reqs_available(ctx, completed);
998}
999
1000/* user_refill_reqs_available
1001 * Called to refill reqs_available when aio_get_req() encounters an
1002 * out of space in the completion ring.
1003 */
1004static void user_refill_reqs_available(struct kioctx *ctx)
1005{
1006 spin_lock_irq(&ctx->completion_lock);
1007 if (ctx->completed_events) {
1008 struct aio_ring *ring;
1009 unsigned head;
1010
1011 /* Access of ring->head may race with aio_read_events_ring()
1012 * here, but that's okay since whether we read the old version
1013 * or the new version, and either will be valid. The important
1014 * part is that head cannot pass tail since we prevent
1015 * aio_complete() from updating tail by holding
1016 * ctx->completion_lock. Even if head is invalid, the check
1017 * against ctx->completed_events below will make sure we do the
1018 * safe/right thing.
1019 */
1020 ring = kmap_atomic(ctx->ring_pages[0]);
1021 head = ring->head;
1022 kunmap_atomic(ring);
1023
1024 refill_reqs_available(ctx, head, ctx->tail);
1025 }
1026
1027 spin_unlock_irq(&ctx->completion_lock);
1028}
1029
1da177e4 1030/* aio_get_req
57282d8f
KO
1031 * Allocate a slot for an aio request.
1032 * Returns NULL if no requests are free.
1da177e4 1033 */
04b2fa9f 1034static inline struct aio_kiocb *aio_get_req(struct kioctx *ctx)
1da177e4 1035{
04b2fa9f 1036 struct aio_kiocb *req;
a1c8eae7 1037
d856f32a
BL
1038 if (!get_reqs_available(ctx)) {
1039 user_refill_reqs_available(ctx);
1040 if (!get_reqs_available(ctx))
1041 return NULL;
1042 }
a1c8eae7 1043
0460fef2 1044 req = kmem_cache_alloc(kiocb_cachep, GFP_KERNEL|__GFP_ZERO);
1da177e4 1045 if (unlikely(!req))
a1c8eae7 1046 goto out_put;
1da177e4 1047
e34ecee2 1048 percpu_ref_get(&ctx->reqs);
75321b50 1049 INIT_LIST_HEAD(&req->ki_list);
1da177e4 1050 req->ki_ctx = ctx;
080d676d 1051 return req;
a1c8eae7 1052out_put:
e1bdd5f2 1053 put_reqs_available(ctx, 1);
a1c8eae7 1054 return NULL;
1da177e4
LT
1055}
1056
d5470b59 1057static struct kioctx *lookup_ioctx(unsigned long ctx_id)
1da177e4 1058{
db446a08 1059 struct aio_ring __user *ring = (void __user *)ctx_id;
abf137dd 1060 struct mm_struct *mm = current->mm;
65c24491 1061 struct kioctx *ctx, *ret = NULL;
db446a08
BL
1062 struct kioctx_table *table;
1063 unsigned id;
1064
1065 if (get_user(id, &ring->id))
1066 return NULL;
1da177e4 1067
abf137dd 1068 rcu_read_lock();
db446a08 1069 table = rcu_dereference(mm->ioctx_table);
abf137dd 1070
db446a08
BL
1071 if (!table || id >= table->nr)
1072 goto out;
1da177e4 1073
d0264c01 1074 ctx = rcu_dereference(table->table[id]);
f30d704f 1075 if (ctx && ctx->user_id == ctx_id) {
baf10564
AV
1076 if (percpu_ref_tryget_live(&ctx->users))
1077 ret = ctx;
db446a08
BL
1078 }
1079out:
abf137dd 1080 rcu_read_unlock();
65c24491 1081 return ret;
1da177e4
LT
1082}
1083
1da177e4
LT
1084/* aio_complete
1085 * Called when the io request on the given iocb is complete.
1da177e4 1086 */
54843f87 1087static void aio_complete(struct aio_kiocb *iocb, long res, long res2)
1da177e4
LT
1088{
1089 struct kioctx *ctx = iocb->ki_ctx;
1da177e4 1090 struct aio_ring *ring;
21b40200 1091 struct io_event *ev_page, *event;
d856f32a 1092 unsigned tail, pos, head;
1da177e4 1093 unsigned long flags;
1da177e4 1094
75321b50 1095 if (!list_empty_careful(&iocb->ki_list)) {
0460fef2
KO
1096 unsigned long flags;
1097
1098 spin_lock_irqsave(&ctx->ctx_lock, flags);
1099 list_del(&iocb->ki_list);
1100 spin_unlock_irqrestore(&ctx->ctx_lock, flags);
1101 }
11599eba 1102
0460fef2
KO
1103 /*
1104 * Add a completion event to the ring buffer. Must be done holding
4b30f07e 1105 * ctx->completion_lock to prevent other code from messing with the tail
0460fef2
KO
1106 * pointer since we might be called from irq context.
1107 */
1108 spin_lock_irqsave(&ctx->completion_lock, flags);
1109
58c85dc2 1110 tail = ctx->tail;
21b40200
KO
1111 pos = tail + AIO_EVENTS_OFFSET;
1112
58c85dc2 1113 if (++tail >= ctx->nr_events)
4bf69b2a 1114 tail = 0;
1da177e4 1115
58c85dc2 1116 ev_page = kmap_atomic(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
21b40200
KO
1117 event = ev_page + pos % AIO_EVENTS_PER_PAGE;
1118
04b2fa9f 1119 event->obj = (u64)(unsigned long)iocb->ki_user_iocb;
1da177e4
LT
1120 event->data = iocb->ki_user_data;
1121 event->res = res;
1122 event->res2 = res2;
1123
21b40200 1124 kunmap_atomic(ev_page);
58c85dc2 1125 flush_dcache_page(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
21b40200
KO
1126
1127 pr_debug("%p[%u]: %p: %p %Lx %lx %lx\n",
04b2fa9f 1128 ctx, tail, iocb, iocb->ki_user_iocb, iocb->ki_user_data,
caf4167a 1129 res, res2);
1da177e4
LT
1130
1131 /* after flagging the request as done, we
1132 * must never even look at it again
1133 */
1134 smp_wmb(); /* make event visible before updating tail */
1135
58c85dc2 1136 ctx->tail = tail;
1da177e4 1137
58c85dc2 1138 ring = kmap_atomic(ctx->ring_pages[0]);
d856f32a 1139 head = ring->head;
21b40200 1140 ring->tail = tail;
e8e3c3d6 1141 kunmap_atomic(ring);
58c85dc2 1142 flush_dcache_page(ctx->ring_pages[0]);
1da177e4 1143
d856f32a
BL
1144 ctx->completed_events++;
1145 if (ctx->completed_events > 1)
1146 refill_reqs_available(ctx, head, tail);
0460fef2
KO
1147 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1148
21b40200 1149 pr_debug("added to ring %p at [%u]\n", iocb, tail);
8d1c98b0
DL
1150
1151 /*
1152 * Check if the user asked us to deliver the result through an
1153 * eventfd. The eventfd_signal() function is safe to be called
1154 * from IRQ context.
1155 */
54843f87 1156 if (iocb->ki_eventfd) {
8d1c98b0 1157 eventfd_signal(iocb->ki_eventfd, 1);
54843f87
CH
1158 eventfd_ctx_put(iocb->ki_eventfd);
1159 }
8d1c98b0 1160
54843f87 1161 kmem_cache_free(kiocb_cachep, iocb);
1da177e4 1162
6cb2a210
QB
1163 /*
1164 * We have to order our ring_info tail store above and test
1165 * of the wait list below outside the wait lock. This is
1166 * like in wake_up_bit() where clearing a bit has to be
1167 * ordered with the unlocked test.
1168 */
1169 smp_mb();
1170
1da177e4
LT
1171 if (waitqueue_active(&ctx->wait))
1172 wake_up(&ctx->wait);
1173
e34ecee2 1174 percpu_ref_put(&ctx->reqs);
1da177e4
LT
1175}
1176
2be4e7de 1177/* aio_read_events_ring
a31ad380
KO
1178 * Pull an event off of the ioctx's event ring. Returns the number of
1179 * events fetched
1da177e4 1180 */
a31ad380
KO
1181static long aio_read_events_ring(struct kioctx *ctx,
1182 struct io_event __user *event, long nr)
1da177e4 1183{
1da177e4 1184 struct aio_ring *ring;
5ffac122 1185 unsigned head, tail, pos;
a31ad380
KO
1186 long ret = 0;
1187 int copy_ret;
1188
9c9ce763
DC
1189 /*
1190 * The mutex can block and wake us up and that will cause
1191 * wait_event_interruptible_hrtimeout() to schedule without sleeping
1192 * and repeat. This should be rare enough that it doesn't cause
1193 * peformance issues. See the comment in read_events() for more detail.
1194 */
1195 sched_annotate_sleep();
58c85dc2 1196 mutex_lock(&ctx->ring_lock);
1da177e4 1197
fa8a53c3 1198 /* Access to ->ring_pages here is protected by ctx->ring_lock. */
58c85dc2 1199 ring = kmap_atomic(ctx->ring_pages[0]);
a31ad380 1200 head = ring->head;
5ffac122 1201 tail = ring->tail;
a31ad380
KO
1202 kunmap_atomic(ring);
1203
2ff396be
JM
1204 /*
1205 * Ensure that once we've read the current tail pointer, that
1206 * we also see the events that were stored up to the tail.
1207 */
1208 smp_rmb();
1209
5ffac122 1210 pr_debug("h%u t%u m%u\n", head, tail, ctx->nr_events);
1da177e4 1211
5ffac122 1212 if (head == tail)
1da177e4
LT
1213 goto out;
1214
edfbbf38
BL
1215 head %= ctx->nr_events;
1216 tail %= ctx->nr_events;
1217
a31ad380
KO
1218 while (ret < nr) {
1219 long avail;
1220 struct io_event *ev;
1221 struct page *page;
1222
5ffac122
KO
1223 avail = (head <= tail ? tail : ctx->nr_events) - head;
1224 if (head == tail)
a31ad380
KO
1225 break;
1226
1227 avail = min(avail, nr - ret);
1228 avail = min_t(long, avail, AIO_EVENTS_PER_PAGE -
1229 ((head + AIO_EVENTS_OFFSET) % AIO_EVENTS_PER_PAGE));
1230
1231 pos = head + AIO_EVENTS_OFFSET;
58c85dc2 1232 page = ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE];
a31ad380
KO
1233 pos %= AIO_EVENTS_PER_PAGE;
1234
1235 ev = kmap(page);
1236 copy_ret = copy_to_user(event + ret, ev + pos,
1237 sizeof(*ev) * avail);
1238 kunmap(page);
1239
1240 if (unlikely(copy_ret)) {
1241 ret = -EFAULT;
1242 goto out;
1243 }
1244
1245 ret += avail;
1246 head += avail;
58c85dc2 1247 head %= ctx->nr_events;
1da177e4 1248 }
1da177e4 1249
58c85dc2 1250 ring = kmap_atomic(ctx->ring_pages[0]);
a31ad380 1251 ring->head = head;
91d80a84 1252 kunmap_atomic(ring);
58c85dc2 1253 flush_dcache_page(ctx->ring_pages[0]);
a31ad380 1254
5ffac122 1255 pr_debug("%li h%u t%u\n", ret, head, tail);
a31ad380 1256out:
58c85dc2 1257 mutex_unlock(&ctx->ring_lock);
a31ad380 1258
1da177e4
LT
1259 return ret;
1260}
1261
a31ad380
KO
1262static bool aio_read_events(struct kioctx *ctx, long min_nr, long nr,
1263 struct io_event __user *event, long *i)
1da177e4 1264{
a31ad380 1265 long ret = aio_read_events_ring(ctx, event + *i, nr - *i);
1da177e4 1266
a31ad380
KO
1267 if (ret > 0)
1268 *i += ret;
1da177e4 1269
a31ad380
KO
1270 if (unlikely(atomic_read(&ctx->dead)))
1271 ret = -EINVAL;
1da177e4 1272
a31ad380
KO
1273 if (!*i)
1274 *i = ret;
1da177e4 1275
a31ad380 1276 return ret < 0 || *i >= min_nr;
1da177e4
LT
1277}
1278
a31ad380 1279static long read_events(struct kioctx *ctx, long min_nr, long nr,
1da177e4 1280 struct io_event __user *event,
fa2e62a5 1281 ktime_t until)
1da177e4 1282{
a31ad380 1283 long ret = 0;
1da177e4 1284
a31ad380
KO
1285 /*
1286 * Note that aio_read_events() is being called as the conditional - i.e.
1287 * we're calling it after prepare_to_wait() has set task state to
1288 * TASK_INTERRUPTIBLE.
1289 *
1290 * But aio_read_events() can block, and if it blocks it's going to flip
1291 * the task state back to TASK_RUNNING.
1292 *
1293 * This should be ok, provided it doesn't flip the state back to
1294 * TASK_RUNNING and return 0 too much - that causes us to spin. That
1295 * will only happen if the mutex_lock() call blocks, and we then find
1296 * the ringbuffer empty. So in practice we should be ok, but it's
1297 * something to be aware of when touching this code.
1298 */
2456e855 1299 if (until == 0)
5f785de5
FZ
1300 aio_read_events(ctx, min_nr, nr, event, &ret);
1301 else
1302 wait_event_interruptible_hrtimeout(ctx->wait,
1303 aio_read_events(ctx, min_nr, nr, event, &ret),
1304 until);
a31ad380 1305 return ret;
1da177e4
LT
1306}
1307
1da177e4
LT
1308/* sys_io_setup:
1309 * Create an aio_context capable of receiving at least nr_events.
1310 * ctxp must not point to an aio_context that already exists, and
1311 * must be initialized to 0 prior to the call. On successful
1312 * creation of the aio_context, *ctxp is filled in with the resulting
1313 * handle. May fail with -EINVAL if *ctxp is not initialized,
1314 * if the specified nr_events exceeds internal limits. May fail
1315 * with -EAGAIN if the specified nr_events exceeds the user's limit
1316 * of available events. May fail with -ENOMEM if insufficient kernel
1317 * resources are available. May fail with -EFAULT if an invalid
1318 * pointer is passed for ctxp. Will fail with -ENOSYS if not
1319 * implemented.
1320 */
002c8976 1321SYSCALL_DEFINE2(io_setup, unsigned, nr_events, aio_context_t __user *, ctxp)
1da177e4
LT
1322{
1323 struct kioctx *ioctx = NULL;
1324 unsigned long ctx;
1325 long ret;
1326
1327 ret = get_user(ctx, ctxp);
1328 if (unlikely(ret))
1329 goto out;
1330
1331 ret = -EINVAL;
d55b5fda 1332 if (unlikely(ctx || nr_events == 0)) {
acd88d4e 1333 pr_debug("EINVAL: ctx %lu nr_events %u\n",
d55b5fda 1334 ctx, nr_events);
1da177e4
LT
1335 goto out;
1336 }
1337
1338 ioctx = ioctx_alloc(nr_events);
1339 ret = PTR_ERR(ioctx);
1340 if (!IS_ERR(ioctx)) {
1341 ret = put_user(ioctx->user_id, ctxp);
a2e1859a 1342 if (ret)
e02ba72a 1343 kill_ioctx(current->mm, ioctx, NULL);
723be6e3 1344 percpu_ref_put(&ioctx->users);
1da177e4
LT
1345 }
1346
1347out:
1348 return ret;
1349}
1350
c00d2c7e
AV
1351#ifdef CONFIG_COMPAT
1352COMPAT_SYSCALL_DEFINE2(io_setup, unsigned, nr_events, u32 __user *, ctx32p)
1353{
1354 struct kioctx *ioctx = NULL;
1355 unsigned long ctx;
1356 long ret;
1357
1358 ret = get_user(ctx, ctx32p);
1359 if (unlikely(ret))
1360 goto out;
1361
1362 ret = -EINVAL;
1363 if (unlikely(ctx || nr_events == 0)) {
1364 pr_debug("EINVAL: ctx %lu nr_events %u\n",
1365 ctx, nr_events);
1366 goto out;
1367 }
1368
1369 ioctx = ioctx_alloc(nr_events);
1370 ret = PTR_ERR(ioctx);
1371 if (!IS_ERR(ioctx)) {
1372 /* truncating is ok because it's a user address */
1373 ret = put_user((u32)ioctx->user_id, ctx32p);
1374 if (ret)
1375 kill_ioctx(current->mm, ioctx, NULL);
1376 percpu_ref_put(&ioctx->users);
1377 }
1378
1379out:
1380 return ret;
1381}
1382#endif
1383
1da177e4
LT
1384/* sys_io_destroy:
1385 * Destroy the aio_context specified. May cancel any outstanding
1386 * AIOs and block on completion. Will fail with -ENOSYS if not
642b5123 1387 * implemented. May fail with -EINVAL if the context pointed to
1da177e4
LT
1388 * is invalid.
1389 */
002c8976 1390SYSCALL_DEFINE1(io_destroy, aio_context_t, ctx)
1da177e4
LT
1391{
1392 struct kioctx *ioctx = lookup_ioctx(ctx);
1393 if (likely(NULL != ioctx)) {
dc48e56d 1394 struct ctx_rq_wait wait;
fb2d4483 1395 int ret;
e02ba72a 1396
dc48e56d
JA
1397 init_completion(&wait.comp);
1398 atomic_set(&wait.count, 1);
1399
e02ba72a
AP
1400 /* Pass requests_done to kill_ioctx() where it can be set
1401 * in a thread-safe way. If we try to set it here then we have
1402 * a race condition if two io_destroy() called simultaneously.
1403 */
dc48e56d 1404 ret = kill_ioctx(current->mm, ioctx, &wait);
723be6e3 1405 percpu_ref_put(&ioctx->users);
e02ba72a
AP
1406
1407 /* Wait until all IO for the context are done. Otherwise kernel
1408 * keep using user-space buffers even if user thinks the context
1409 * is destroyed.
1410 */
fb2d4483 1411 if (!ret)
dc48e56d 1412 wait_for_completion(&wait.comp);
e02ba72a 1413
fb2d4483 1414 return ret;
1da177e4 1415 }
acd88d4e 1416 pr_debug("EINVAL: invalid context id\n");
1da177e4
LT
1417 return -EINVAL;
1418}
1419
54843f87
CH
1420static void aio_complete_rw(struct kiocb *kiocb, long res, long res2)
1421{
1422 struct aio_kiocb *iocb = container_of(kiocb, struct aio_kiocb, rw);
1423
1424 if (kiocb->ki_flags & IOCB_WRITE) {
1425 struct inode *inode = file_inode(kiocb->ki_filp);
1426
1427 /*
1428 * Tell lockdep we inherited freeze protection from submission
1429 * thread.
1430 */
1431 if (S_ISREG(inode->i_mode))
1432 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
1433 file_end_write(kiocb->ki_filp);
1434 }
1435
1436 fput(kiocb->ki_filp);
1437 aio_complete(iocb, res, res2);
1438}
1439
1440static int aio_prep_rw(struct kiocb *req, struct iocb *iocb)
1441{
1442 int ret;
1443
1444 req->ki_filp = fget(iocb->aio_fildes);
1445 if (unlikely(!req->ki_filp))
1446 return -EBADF;
1447 req->ki_complete = aio_complete_rw;
1448 req->ki_pos = iocb->aio_offset;
1449 req->ki_flags = iocb_flags(req->ki_filp);
1450 if (iocb->aio_flags & IOCB_FLAG_RESFD)
1451 req->ki_flags |= IOCB_EVENTFD;
1452 req->ki_hint = file_write_hint(req->ki_filp);
1453 ret = kiocb_set_rw_flags(req, iocb->aio_rw_flags);
1454 if (unlikely(ret))
1455 fput(req->ki_filp);
1456 return ret;
1457}
1458
89319d31
CH
1459static int aio_setup_rw(int rw, struct iocb *iocb, struct iovec **iovec,
1460 bool vectored, bool compat, struct iov_iter *iter)
eed4e51f 1461{
89319d31
CH
1462 void __user *buf = (void __user *)(uintptr_t)iocb->aio_buf;
1463 size_t len = iocb->aio_nbytes;
1464
1465 if (!vectored) {
1466 ssize_t ret = import_single_range(rw, buf, len, *iovec, iter);
1467 *iovec = NULL;
1468 return ret;
1469 }
9d85cba7
JM
1470#ifdef CONFIG_COMPAT
1471 if (compat)
89319d31
CH
1472 return compat_import_iovec(rw, buf, len, UIO_FASTIOV, iovec,
1473 iter);
9d85cba7 1474#endif
89319d31 1475 return import_iovec(rw, buf, len, UIO_FASTIOV, iovec, iter);
eed4e51f
BP
1476}
1477
54843f87 1478static inline ssize_t aio_rw_ret(struct kiocb *req, ssize_t ret)
89319d31
CH
1479{
1480 switch (ret) {
1481 case -EIOCBQUEUED:
1482 return ret;
1483 case -ERESTARTSYS:
1484 case -ERESTARTNOINTR:
1485 case -ERESTARTNOHAND:
1486 case -ERESTART_RESTARTBLOCK:
1487 /*
1488 * There's no easy way to restart the syscall since other AIO's
1489 * may be already running. Just fail this IO with EINTR.
1490 */
1491 ret = -EINTR;
1492 /*FALLTHRU*/
1493 default:
54843f87 1494 aio_complete_rw(req, ret, 0);
89319d31
CH
1495 return 0;
1496 }
1497}
1498
1499static ssize_t aio_read(struct kiocb *req, struct iocb *iocb, bool vectored,
1500 bool compat)
1da177e4 1501{
00fefb9c 1502 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
293bc982 1503 struct iov_iter iter;
54843f87 1504 struct file *file;
89319d31 1505 ssize_t ret;
1da177e4 1506
54843f87
CH
1507 ret = aio_prep_rw(req, iocb);
1508 if (ret)
1509 return ret;
1510 file = req->ki_filp;
1511
1512 ret = -EBADF;
89319d31 1513 if (unlikely(!(file->f_mode & FMODE_READ)))
54843f87
CH
1514 goto out_fput;
1515 ret = -EINVAL;
89319d31 1516 if (unlikely(!file->f_op->read_iter))
54843f87 1517 goto out_fput;
73a7075e 1518
89319d31
CH
1519 ret = aio_setup_rw(READ, iocb, &iovec, vectored, compat, &iter);
1520 if (ret)
54843f87 1521 goto out_fput;
89319d31
CH
1522 ret = rw_verify_area(READ, file, &req->ki_pos, iov_iter_count(&iter));
1523 if (!ret)
54843f87 1524 ret = aio_rw_ret(req, call_read_iter(file, req, &iter));
89319d31 1525 kfree(iovec);
54843f87
CH
1526out_fput:
1527 if (unlikely(ret && ret != -EIOCBQUEUED))
1528 fput(file);
89319d31
CH
1529 return ret;
1530}
73a7075e 1531
89319d31
CH
1532static ssize_t aio_write(struct kiocb *req, struct iocb *iocb, bool vectored,
1533 bool compat)
1534{
89319d31
CH
1535 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1536 struct iov_iter iter;
54843f87 1537 struct file *file;
89319d31 1538 ssize_t ret;
41ef4eb8 1539
54843f87
CH
1540 ret = aio_prep_rw(req, iocb);
1541 if (ret)
1542 return ret;
1543 file = req->ki_filp;
1544
1545 ret = -EBADF;
89319d31 1546 if (unlikely(!(file->f_mode & FMODE_WRITE)))
54843f87
CH
1547 goto out_fput;
1548 ret = -EINVAL;
89319d31 1549 if (unlikely(!file->f_op->write_iter))
54843f87 1550 goto out_fput;
1da177e4 1551
89319d31
CH
1552 ret = aio_setup_rw(WRITE, iocb, &iovec, vectored, compat, &iter);
1553 if (ret)
54843f87 1554 goto out_fput;
89319d31
CH
1555 ret = rw_verify_area(WRITE, file, &req->ki_pos, iov_iter_count(&iter));
1556 if (!ret) {
70fe2f48 1557 /*
92ce4728 1558 * Open-code file_start_write here to grab freeze protection,
54843f87
CH
1559 * which will be released by another thread in
1560 * aio_complete_rw(). Fool lockdep by telling it the lock got
1561 * released so that it doesn't complain about the held lock when
1562 * we return to userspace.
70fe2f48 1563 */
92ce4728
CH
1564 if (S_ISREG(file_inode(file)->i_mode)) {
1565 __sb_start_write(file_inode(file)->i_sb, SB_FREEZE_WRITE, true);
a12f1ae6 1566 __sb_writers_release(file_inode(file)->i_sb, SB_FREEZE_WRITE);
92ce4728
CH
1567 }
1568 req->ki_flags |= IOCB_WRITE;
54843f87 1569 ret = aio_rw_ret(req, call_write_iter(file, req, &iter));
41ef4eb8 1570 }
89319d31 1571 kfree(iovec);
54843f87
CH
1572out_fput:
1573 if (unlikely(ret && ret != -EIOCBQUEUED))
1574 fput(file);
89319d31 1575 return ret;
1da177e4
LT
1576}
1577
a3c0d439
CH
1578static void aio_fsync_work(struct work_struct *work)
1579{
1580 struct fsync_iocb *req = container_of(work, struct fsync_iocb, work);
1581 int ret;
1582
1583 ret = vfs_fsync(req->file, req->datasync);
1584 fput(req->file);
1585 aio_complete(container_of(req, struct aio_kiocb, fsync), ret, 0);
1586}
1587
1588static int aio_fsync(struct fsync_iocb *req, struct iocb *iocb, bool datasync)
1589{
1590 if (unlikely(iocb->aio_buf || iocb->aio_offset || iocb->aio_nbytes ||
1591 iocb->aio_rw_flags))
1592 return -EINVAL;
1593
1594 req->file = fget(iocb->aio_fildes);
1595 if (unlikely(!req->file))
1596 return -EBADF;
1597 if (unlikely(!req->file->f_op->fsync)) {
1598 fput(req->file);
1599 return -EINVAL;
1600 }
1601
1602 req->datasync = datasync;
1603 INIT_WORK(&req->work, aio_fsync_work);
1604 schedule_work(&req->work);
1605 return -EIOCBQUEUED;
1606}
1607
d5470b59 1608static int io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb,
a1c8eae7 1609 struct iocb *iocb, bool compat)
1da177e4 1610{
04b2fa9f 1611 struct aio_kiocb *req;
1da177e4
LT
1612 ssize_t ret;
1613
1614 /* enforce forwards compatibility on users */
9830f4be 1615 if (unlikely(iocb->aio_reserved2)) {
caf4167a 1616 pr_debug("EINVAL: reserve field set\n");
1da177e4
LT
1617 return -EINVAL;
1618 }
1619
1620 /* prevent overflows */
1621 if (unlikely(
1622 (iocb->aio_buf != (unsigned long)iocb->aio_buf) ||
1623 (iocb->aio_nbytes != (size_t)iocb->aio_nbytes) ||
1624 ((ssize_t)iocb->aio_nbytes < 0)
1625 )) {
acd88d4e 1626 pr_debug("EINVAL: overflow check\n");
1da177e4
LT
1627 return -EINVAL;
1628 }
1629
41ef4eb8 1630 req = aio_get_req(ctx);
1d98ebfc 1631 if (unlikely(!req))
1da177e4 1632 return -EAGAIN;
1d98ebfc 1633
9c3060be
DL
1634 if (iocb->aio_flags & IOCB_FLAG_RESFD) {
1635 /*
1636 * If the IOCB_FLAG_RESFD flag of aio_flags is set, get an
1637 * instance of the file* now. The file descriptor must be
1638 * an eventfd() fd, and will be signaled for each completed
1639 * event using the eventfd_signal() function.
1640 */
13389010 1641 req->ki_eventfd = eventfd_ctx_fdget((int) iocb->aio_resfd);
801678c5 1642 if (IS_ERR(req->ki_eventfd)) {
9c3060be 1643 ret = PTR_ERR(req->ki_eventfd);
87c3a86e 1644 req->ki_eventfd = NULL;
9c3060be
DL
1645 goto out_put_req;
1646 }
9830f4be
GR
1647 }
1648
8a660890 1649 ret = put_user(KIOCB_KEY, &user_iocb->aio_key);
1da177e4 1650 if (unlikely(ret)) {
caf4167a 1651 pr_debug("EFAULT: aio_key\n");
1da177e4
LT
1652 goto out_put_req;
1653 }
1654
04b2fa9f 1655 req->ki_user_iocb = user_iocb;
1da177e4 1656 req->ki_user_data = iocb->aio_data;
1da177e4 1657
89319d31
CH
1658 switch (iocb->aio_lio_opcode) {
1659 case IOCB_CMD_PREAD:
54843f87 1660 ret = aio_read(&req->rw, iocb, false, compat);
89319d31
CH
1661 break;
1662 case IOCB_CMD_PWRITE:
54843f87 1663 ret = aio_write(&req->rw, iocb, false, compat);
89319d31
CH
1664 break;
1665 case IOCB_CMD_PREADV:
54843f87 1666 ret = aio_read(&req->rw, iocb, true, compat);
89319d31
CH
1667 break;
1668 case IOCB_CMD_PWRITEV:
54843f87 1669 ret = aio_write(&req->rw, iocb, true, compat);
89319d31 1670 break;
a3c0d439
CH
1671 case IOCB_CMD_FSYNC:
1672 ret = aio_fsync(&req->fsync, iocb, false);
1673 break;
1674 case IOCB_CMD_FDSYNC:
1675 ret = aio_fsync(&req->fsync, iocb, true);
1676 break;
89319d31
CH
1677 default:
1678 pr_debug("invalid aio operation %d\n", iocb->aio_lio_opcode);
1679 ret = -EINVAL;
1680 break;
1681 }
41003a7b 1682
92ce4728
CH
1683 /*
1684 * If ret is -EIOCBQUEUED, ownership of the file reference acquired
1685 * above passed to the file system, which at this point might have
1686 * dropped the reference, so we must be careful to not reference it
1687 * once we have called into the file system.
1688 */
89319d31
CH
1689 if (ret && ret != -EIOCBQUEUED)
1690 goto out_put_req;
1da177e4 1691 return 0;
1da177e4 1692out_put_req:
e1bdd5f2 1693 put_reqs_available(ctx, 1);
e34ecee2 1694 percpu_ref_put(&ctx->reqs);
54843f87
CH
1695 if (req->ki_eventfd)
1696 eventfd_ctx_put(req->ki_eventfd);
1697 kmem_cache_free(kiocb_cachep, req);
1da177e4
LT
1698 return ret;
1699}
1700
c00d2c7e
AV
1701static long do_io_submit(aio_context_t ctx_id, long nr,
1702 struct iocb __user *__user *iocbpp, bool compat)
1da177e4
LT
1703{
1704 struct kioctx *ctx;
1705 long ret = 0;
080d676d 1706 int i = 0;
9f5b9425 1707 struct blk_plug plug;
1da177e4
LT
1708
1709 if (unlikely(nr < 0))
1710 return -EINVAL;
1711
75e1c70f
JM
1712 if (unlikely(nr > LONG_MAX/sizeof(*iocbpp)))
1713 nr = LONG_MAX/sizeof(*iocbpp);
1714
1da177e4
LT
1715 if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))
1716 return -EFAULT;
1717
1718 ctx = lookup_ioctx(ctx_id);
1719 if (unlikely(!ctx)) {
caf4167a 1720 pr_debug("EINVAL: invalid context id\n");
1da177e4
LT
1721 return -EINVAL;
1722 }
1723
9f5b9425
SL
1724 blk_start_plug(&plug);
1725
1da177e4
LT
1726 /*
1727 * AKPM: should this return a partial result if some of the IOs were
1728 * successfully submitted?
1729 */
1730 for (i=0; i<nr; i++) {
1731 struct iocb __user *user_iocb;
1732 struct iocb tmp;
1733
1734 if (unlikely(__get_user(user_iocb, iocbpp + i))) {
1735 ret = -EFAULT;
1736 break;
1737 }
1738
1739 if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
1740 ret = -EFAULT;
1741 break;
1742 }
1743
a1c8eae7 1744 ret = io_submit_one(ctx, user_iocb, &tmp, compat);
1da177e4
LT
1745 if (ret)
1746 break;
1747 }
9f5b9425 1748 blk_finish_plug(&plug);
1da177e4 1749
723be6e3 1750 percpu_ref_put(&ctx->users);
1da177e4
LT
1751 return i ? i : ret;
1752}
1753
9d85cba7
JM
1754/* sys_io_submit:
1755 * Queue the nr iocbs pointed to by iocbpp for processing. Returns
1756 * the number of iocbs queued. May return -EINVAL if the aio_context
1757 * specified by ctx_id is invalid, if nr is < 0, if the iocb at
1758 * *iocbpp[0] is not properly initialized, if the operation specified
1759 * is invalid for the file descriptor in the iocb. May fail with
1760 * -EFAULT if any of the data structures point to invalid data. May
1761 * fail with -EBADF if the file descriptor specified in the first
1762 * iocb is invalid. May fail with -EAGAIN if insufficient resources
1763 * are available to queue any iocbs. Will return 0 if nr is 0. Will
1764 * fail with -ENOSYS if not implemented.
1765 */
1766SYSCALL_DEFINE3(io_submit, aio_context_t, ctx_id, long, nr,
1767 struct iocb __user * __user *, iocbpp)
1768{
1769 return do_io_submit(ctx_id, nr, iocbpp, 0);
1770}
1771
c00d2c7e
AV
1772#ifdef CONFIG_COMPAT
1773static inline long
1774copy_iocb(long nr, u32 __user *ptr32, struct iocb __user * __user *ptr64)
1775{
1776 compat_uptr_t uptr;
1777 int i;
1778
1779 for (i = 0; i < nr; ++i) {
1780 if (get_user(uptr, ptr32 + i))
1781 return -EFAULT;
1782 if (put_user(compat_ptr(uptr), ptr64 + i))
1783 return -EFAULT;
1784 }
1785 return 0;
1786}
1787
1788#define MAX_AIO_SUBMITS (PAGE_SIZE/sizeof(struct iocb *))
1789
1790COMPAT_SYSCALL_DEFINE3(io_submit, compat_aio_context_t, ctx_id,
1791 int, nr, u32 __user *, iocb)
1792{
1793 struct iocb __user * __user *iocb64;
1794 long ret;
1795
1796 if (unlikely(nr < 0))
1797 return -EINVAL;
1798
1799 if (nr > MAX_AIO_SUBMITS)
1800 nr = MAX_AIO_SUBMITS;
1801
1802 iocb64 = compat_alloc_user_space(nr * sizeof(*iocb64));
1803 ret = copy_iocb(nr, iocb, iocb64);
1804 if (!ret)
1805 ret = do_io_submit(ctx_id, nr, iocb64, 1);
1806 return ret;
1807}
1808#endif
1809
1da177e4
LT
1810/* lookup_kiocb
1811 * Finds a given iocb for cancellation.
1da177e4 1812 */
04b2fa9f
CH
1813static struct aio_kiocb *
1814lookup_kiocb(struct kioctx *ctx, struct iocb __user *iocb, u32 key)
1da177e4 1815{
04b2fa9f 1816 struct aio_kiocb *kiocb;
d00689af
ZB
1817
1818 assert_spin_locked(&ctx->ctx_lock);
1819
8a660890
KO
1820 if (key != KIOCB_KEY)
1821 return NULL;
1822
1da177e4 1823 /* TODO: use a hash or array, this sucks. */
04b2fa9f
CH
1824 list_for_each_entry(kiocb, &ctx->active_reqs, ki_list) {
1825 if (kiocb->ki_user_iocb == iocb)
1da177e4
LT
1826 return kiocb;
1827 }
1828 return NULL;
1829}
1830
1831/* sys_io_cancel:
1832 * Attempts to cancel an iocb previously passed to io_submit. If
1833 * the operation is successfully cancelled, the resulting event is
1834 * copied into the memory pointed to by result without being placed
1835 * into the completion queue and 0 is returned. May fail with
1836 * -EFAULT if any of the data structures pointed to are invalid.
1837 * May fail with -EINVAL if aio_context specified by ctx_id is
1838 * invalid. May fail with -EAGAIN if the iocb specified was not
1839 * cancelled. Will fail with -ENOSYS if not implemented.
1840 */
002c8976
HC
1841SYSCALL_DEFINE3(io_cancel, aio_context_t, ctx_id, struct iocb __user *, iocb,
1842 struct io_event __user *, result)
1da177e4 1843{
1da177e4 1844 struct kioctx *ctx;
04b2fa9f 1845 struct aio_kiocb *kiocb;
1da177e4
LT
1846 u32 key;
1847 int ret;
1848
1849 ret = get_user(key, &iocb->aio_key);
1850 if (unlikely(ret))
1851 return -EFAULT;
1852
1853 ctx = lookup_ioctx(ctx_id);
1854 if (unlikely(!ctx))
1855 return -EINVAL;
1856
1857 spin_lock_irq(&ctx->ctx_lock);
906b973c 1858
1da177e4 1859 kiocb = lookup_kiocb(ctx, iocb, key);
906b973c 1860 if (kiocb)
d52a8f9e 1861 ret = kiocb_cancel(kiocb);
906b973c
KO
1862 else
1863 ret = -EINVAL;
1864
1da177e4
LT
1865 spin_unlock_irq(&ctx->ctx_lock);
1866
906b973c 1867 if (!ret) {
bec68faa
KO
1868 /*
1869 * The result argument is no longer used - the io_event is
1870 * always delivered via the ring buffer. -EINPROGRESS indicates
1871 * cancellation is progress:
906b973c 1872 */
bec68faa 1873 ret = -EINPROGRESS;
906b973c 1874 }
1da177e4 1875
723be6e3 1876 percpu_ref_put(&ctx->users);
1da177e4
LT
1877
1878 return ret;
1879}
1880
fa2e62a5
DD
1881static long do_io_getevents(aio_context_t ctx_id,
1882 long min_nr,
1883 long nr,
1884 struct io_event __user *events,
1885 struct timespec64 *ts)
1886{
1887 ktime_t until = ts ? timespec64_to_ktime(*ts) : KTIME_MAX;
1888 struct kioctx *ioctx = lookup_ioctx(ctx_id);
1889 long ret = -EINVAL;
1890
1891 if (likely(ioctx)) {
1892 if (likely(min_nr <= nr && min_nr >= 0))
1893 ret = read_events(ioctx, min_nr, nr, events, until);
1894 percpu_ref_put(&ioctx->users);
1895 }
1896
1897 return ret;
1898}
1899
1da177e4
LT
1900/* io_getevents:
1901 * Attempts to read at least min_nr events and up to nr events from
642b5123
ST
1902 * the completion queue for the aio_context specified by ctx_id. If
1903 * it succeeds, the number of read events is returned. May fail with
1904 * -EINVAL if ctx_id is invalid, if min_nr is out of range, if nr is
1905 * out of range, if timeout is out of range. May fail with -EFAULT
1906 * if any of the memory specified is invalid. May return 0 or
1907 * < min_nr if the timeout specified by timeout has elapsed
1908 * before sufficient events are available, where timeout == NULL
1909 * specifies an infinite timeout. Note that the timeout pointed to by
6900807c 1910 * timeout is relative. Will fail with -ENOSYS if not implemented.
1da177e4 1911 */
002c8976
HC
1912SYSCALL_DEFINE5(io_getevents, aio_context_t, ctx_id,
1913 long, min_nr,
1914 long, nr,
1915 struct io_event __user *, events,
1916 struct timespec __user *, timeout)
1da177e4 1917{
fa2e62a5 1918 struct timespec64 ts;
7a074e96
CH
1919 int ret;
1920
1921 if (timeout && unlikely(get_timespec64(&ts, timeout)))
1922 return -EFAULT;
1923
1924 ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &ts : NULL);
1925 if (!ret && signal_pending(current))
1926 ret = -EINTR;
1927 return ret;
1928}
1da177e4 1929
7a074e96
CH
1930SYSCALL_DEFINE6(io_pgetevents,
1931 aio_context_t, ctx_id,
1932 long, min_nr,
1933 long, nr,
1934 struct io_event __user *, events,
1935 struct timespec __user *, timeout,
1936 const struct __aio_sigset __user *, usig)
1937{
1938 struct __aio_sigset ksig = { NULL, };
1939 sigset_t ksigmask, sigsaved;
1940 struct timespec64 ts;
1941 int ret;
1942
1943 if (timeout && unlikely(get_timespec64(&ts, timeout)))
1944 return -EFAULT;
1945
1946 if (usig && copy_from_user(&ksig, usig, sizeof(ksig)))
1947 return -EFAULT;
1948
1949 if (ksig.sigmask) {
1950 if (ksig.sigsetsize != sizeof(sigset_t))
1951 return -EINVAL;
1952 if (copy_from_user(&ksigmask, ksig.sigmask, sizeof(ksigmask)))
fa2e62a5 1953 return -EFAULT;
7a074e96
CH
1954 sigdelsetmask(&ksigmask, sigmask(SIGKILL) | sigmask(SIGSTOP));
1955 sigprocmask(SIG_SETMASK, &ksigmask, &sigsaved);
1956 }
1957
1958 ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &ts : NULL);
1959 if (signal_pending(current)) {
1960 if (ksig.sigmask) {
1961 current->saved_sigmask = sigsaved;
1962 set_restore_sigmask();
1963 }
1964
1965 if (!ret)
1966 ret = -ERESTARTNOHAND;
1967 } else {
1968 if (ksig.sigmask)
1969 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
1da177e4 1970 }
fa2e62a5 1971
7a074e96 1972 return ret;
1da177e4 1973}
c00d2c7e
AV
1974
1975#ifdef CONFIG_COMPAT
1976COMPAT_SYSCALL_DEFINE5(io_getevents, compat_aio_context_t, ctx_id,
1977 compat_long_t, min_nr,
1978 compat_long_t, nr,
1979 struct io_event __user *, events,
1980 struct compat_timespec __user *, timeout)
1981{
fa2e62a5 1982 struct timespec64 t;
7a074e96
CH
1983 int ret;
1984
1985 if (timeout && compat_get_timespec64(&t, timeout))
1986 return -EFAULT;
1987
1988 ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &t : NULL);
1989 if (!ret && signal_pending(current))
1990 ret = -EINTR;
1991 return ret;
1992}
1993
c00d2c7e 1994
7a074e96
CH
1995struct __compat_aio_sigset {
1996 compat_sigset_t __user *sigmask;
1997 compat_size_t sigsetsize;
1998};
1999
2000COMPAT_SYSCALL_DEFINE6(io_pgetevents,
2001 compat_aio_context_t, ctx_id,
2002 compat_long_t, min_nr,
2003 compat_long_t, nr,
2004 struct io_event __user *, events,
2005 struct compat_timespec __user *, timeout,
2006 const struct __compat_aio_sigset __user *, usig)
2007{
2008 struct __compat_aio_sigset ksig = { NULL, };
2009 sigset_t ksigmask, sigsaved;
2010 struct timespec64 t;
2011 int ret;
2012
2013 if (timeout && compat_get_timespec64(&t, timeout))
2014 return -EFAULT;
2015
2016 if (usig && copy_from_user(&ksig, usig, sizeof(ksig)))
2017 return -EFAULT;
2018
2019 if (ksig.sigmask) {
2020 if (ksig.sigsetsize != sizeof(compat_sigset_t))
2021 return -EINVAL;
2022 if (get_compat_sigset(&ksigmask, ksig.sigmask))
c00d2c7e 2023 return -EFAULT;
7a074e96
CH
2024 sigdelsetmask(&ksigmask, sigmask(SIGKILL) | sigmask(SIGSTOP));
2025 sigprocmask(SIG_SETMASK, &ksigmask, &sigsaved);
2026 }
c00d2c7e 2027
7a074e96
CH
2028 ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &t : NULL);
2029 if (signal_pending(current)) {
2030 if (ksig.sigmask) {
2031 current->saved_sigmask = sigsaved;
2032 set_restore_sigmask();
2033 }
2034 if (!ret)
2035 ret = -ERESTARTNOHAND;
2036 } else {
2037 if (ksig.sigmask)
2038 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
c00d2c7e 2039 }
fa2e62a5 2040
7a074e96 2041 return ret;
c00d2c7e
AV
2042}
2043#endif