]> git.ipfire.org Git - thirdparty/kernel/stable.git/blame - fs/io_uring.c
KVM: nVMX: Clear pending KVM_REQ_GET_VMCS12_PAGES when leaving nested
[thirdparty/kernel/stable.git] / fs / io_uring.c
CommitLineData
2b188cc1
JA
1// SPDX-License-Identifier: GPL-2.0
2/*
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
5 *
6 * A note on the read/write ordering memory barriers that are matched between
1e84b97b
SB
7 * the application and kernel side.
8 *
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqring (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
16 * CQ entries.
17 *
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
23 * head will do).
24 *
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
28 * between.
2b188cc1
JA
29 *
30 * Also see the examples in the liburing library:
31 *
32 * git://git.kernel.dk/liburing
33 *
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
38 *
39 * Copyright (C) 2018-2019 Jens Axboe
c992fe29 40 * Copyright (c) 2018-2019 Christoph Hellwig
2b188cc1
JA
41 */
42#include <linux/kernel.h>
43#include <linux/init.h>
44#include <linux/errno.h>
45#include <linux/syscalls.h>
46#include <linux/compat.h>
47#include <linux/refcount.h>
48#include <linux/uio.h>
49
50#include <linux/sched/signal.h>
51#include <linux/fs.h>
52#include <linux/file.h>
53#include <linux/fdtable.h>
54#include <linux/mm.h>
55#include <linux/mman.h>
56#include <linux/mmu_context.h>
57#include <linux/percpu.h>
58#include <linux/slab.h>
59#include <linux/workqueue.h>
6c271ce2 60#include <linux/kthread.h>
2b188cc1 61#include <linux/blkdev.h>
edafccee 62#include <linux/bvec.h>
2b188cc1
JA
63#include <linux/net.h>
64#include <net/sock.h>
65#include <net/af_unix.h>
6b06314c 66#include <net/scm.h>
2b188cc1
JA
67#include <linux/anon_inodes.h>
68#include <linux/sched/mm.h>
69#include <linux/uaccess.h>
70#include <linux/nospec.h>
edafccee
JA
71#include <linux/sizes.h>
72#include <linux/hugetlb.h>
2b188cc1
JA
73
74#include <uapi/linux/io_uring.h>
75
76#include "internal.h"
77
78#define IORING_MAX_ENTRIES 4096
6b06314c 79#define IORING_MAX_FIXED_FILES 1024
2b188cc1
JA
80
81struct io_uring {
82 u32 head ____cacheline_aligned_in_smp;
83 u32 tail ____cacheline_aligned_in_smp;
84};
85
1e84b97b
SB
86/*
87 * This data is shared with the application through the mmap at offset
88 * IORING_OFF_SQ_RING.
89 *
90 * The offsets to the member fields are published through struct
91 * io_sqring_offsets when calling io_uring_setup.
92 */
2b188cc1 93struct io_sq_ring {
1e84b97b
SB
94 /*
95 * Head and tail offsets into the ring; the offsets need to be
96 * masked to get valid indices.
97 *
98 * The kernel controls head and the application controls tail.
99 */
2b188cc1 100 struct io_uring r;
1e84b97b
SB
101 /*
102 * Bitmask to apply to head and tail offsets (constant, equals
103 * ring_entries - 1)
104 */
2b188cc1 105 u32 ring_mask;
1e84b97b 106 /* Ring size (constant, power of 2) */
2b188cc1 107 u32 ring_entries;
1e84b97b
SB
108 /*
109 * Number of invalid entries dropped by the kernel due to
110 * invalid index stored in array
111 *
112 * Written by the kernel, shouldn't be modified by the
113 * application (i.e. get number of "new events" by comparing to
114 * cached value).
115 *
116 * After a new SQ head value was read by the application this
117 * counter includes all submissions that were dropped reaching
118 * the new SQ head (and possibly more).
119 */
2b188cc1 120 u32 dropped;
1e84b97b
SB
121 /*
122 * Runtime flags
123 *
124 * Written by the kernel, shouldn't be modified by the
125 * application.
126 *
127 * The application needs a full memory barrier before checking
128 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
129 */
2b188cc1 130 u32 flags;
1e84b97b
SB
131 /*
132 * Ring buffer of indices into array of io_uring_sqe, which is
133 * mmapped by the application using the IORING_OFF_SQES offset.
134 *
135 * This indirection could e.g. be used to assign fixed
136 * io_uring_sqe entries to operations and only submit them to
137 * the queue when needed.
138 *
139 * The kernel modifies neither the indices array nor the entries
140 * array.
141 */
2b188cc1
JA
142 u32 array[];
143};
144
1e84b97b
SB
145/*
146 * This data is shared with the application through the mmap at offset
147 * IORING_OFF_CQ_RING.
148 *
149 * The offsets to the member fields are published through struct
150 * io_cqring_offsets when calling io_uring_setup.
151 */
2b188cc1 152struct io_cq_ring {
1e84b97b
SB
153 /*
154 * Head and tail offsets into the ring; the offsets need to be
155 * masked to get valid indices.
156 *
157 * The application controls head and the kernel tail.
158 */
2b188cc1 159 struct io_uring r;
1e84b97b
SB
160 /*
161 * Bitmask to apply to head and tail offsets (constant, equals
162 * ring_entries - 1)
163 */
2b188cc1 164 u32 ring_mask;
1e84b97b 165 /* Ring size (constant, power of 2) */
2b188cc1 166 u32 ring_entries;
1e84b97b
SB
167 /*
168 * Number of completion events lost because the queue was full;
169 * this should be avoided by the application by making sure
170 * there are not more requests pending thatn there is space in
171 * the completion queue.
172 *
173 * Written by the kernel, shouldn't be modified by the
174 * application (i.e. get number of "new events" by comparing to
175 * cached value).
176 *
177 * As completion events come in out of order this counter is not
178 * ordered with any other data.
179 */
2b188cc1 180 u32 overflow;
1e84b97b
SB
181 /*
182 * Ring buffer of completion events.
183 *
184 * The kernel writes completion events fresh every time they are
185 * produced, so the application is allowed to modify pending
186 * entries.
187 */
2b188cc1
JA
188 struct io_uring_cqe cqes[];
189};
190
edafccee
JA
191struct io_mapped_ubuf {
192 u64 ubuf;
193 size_t len;
194 struct bio_vec *bvec;
195 unsigned int nr_bvecs;
196};
197
31b51510
JA
198struct async_list {
199 spinlock_t lock;
200 atomic_t cnt;
201 struct list_head list;
202
203 struct file *file;
204 off_t io_end;
205 size_t io_pages;
206};
207
2b188cc1
JA
208struct io_ring_ctx {
209 struct {
210 struct percpu_ref refs;
211 } ____cacheline_aligned_in_smp;
212
213 struct {
214 unsigned int flags;
215 bool compat;
216 bool account_mem;
217
218 /* SQ ring */
219 struct io_sq_ring *sq_ring;
220 unsigned cached_sq_head;
221 unsigned sq_entries;
222 unsigned sq_mask;
6c271ce2 223 unsigned sq_thread_idle;
2b188cc1
JA
224 struct io_uring_sqe *sq_sqes;
225 } ____cacheline_aligned_in_smp;
226
227 /* IO offload */
228 struct workqueue_struct *sqo_wq;
6c271ce2 229 struct task_struct *sqo_thread; /* if using sq thread polling */
2b188cc1 230 struct mm_struct *sqo_mm;
6c271ce2
JA
231 wait_queue_head_t sqo_wait;
232 unsigned sqo_stop;
2b188cc1
JA
233
234 struct {
235 /* CQ ring */
236 struct io_cq_ring *cq_ring;
237 unsigned cached_cq_tail;
238 unsigned cq_entries;
239 unsigned cq_mask;
240 struct wait_queue_head cq_wait;
241 struct fasync_struct *cq_fasync;
242 } ____cacheline_aligned_in_smp;
243
6b06314c
JA
244 /*
245 * If used, fixed file set. Writers must ensure that ->refs is dead,
246 * readers must ensure that ->refs is alive as long as the file* is
247 * used. Only updated through io_uring_register(2).
248 */
249 struct file **user_files;
250 unsigned nr_user_files;
251
edafccee
JA
252 /* if used, fixed mapped user buffers */
253 unsigned nr_user_bufs;
254 struct io_mapped_ubuf *user_bufs;
255
2b188cc1
JA
256 struct user_struct *user;
257
258 struct completion ctx_done;
259
260 struct {
261 struct mutex uring_lock;
262 wait_queue_head_t wait;
263 } ____cacheline_aligned_in_smp;
264
265 struct {
266 spinlock_t completion_lock;
def596e9
JA
267 bool poll_multi_file;
268 /*
269 * ->poll_list is protected by the ctx->uring_lock for
270 * io_uring instances that don't use IORING_SETUP_SQPOLL.
271 * For SQPOLL, only the single threaded io_sq_thread() will
272 * manipulate the list, hence no extra locking is needed there.
273 */
274 struct list_head poll_list;
221c5eb2 275 struct list_head cancel_list;
2b188cc1
JA
276 } ____cacheline_aligned_in_smp;
277
31b51510
JA
278 struct async_list pending_async[2];
279
2b188cc1
JA
280#if defined(CONFIG_UNIX)
281 struct socket *ring_sock;
282#endif
283};
284
285struct sqe_submit {
286 const struct io_uring_sqe *sqe;
287 unsigned short index;
288 bool has_user;
def596e9 289 bool needs_lock;
6c271ce2 290 bool needs_fixed_file;
2b188cc1
JA
291};
292
09bb8394
JA
293/*
294 * First field must be the file pointer in all the
295 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
296 */
221c5eb2
JA
297struct io_poll_iocb {
298 struct file *file;
299 struct wait_queue_head *head;
300 __poll_t events;
8c838788 301 bool done;
221c5eb2
JA
302 bool canceled;
303 struct wait_queue_entry wait;
304};
305
09bb8394
JA
306/*
307 * NOTE! Each of the iocb union members has the file pointer
308 * as the first entry in their struct definition. So you can
309 * access the file pointer through any of the sub-structs,
310 * or directly as just 'ki_filp' in this struct.
311 */
2b188cc1 312struct io_kiocb {
221c5eb2 313 union {
09bb8394 314 struct file *file;
221c5eb2
JA
315 struct kiocb rw;
316 struct io_poll_iocb poll;
317 };
2b188cc1
JA
318
319 struct sqe_submit submit;
320
321 struct io_ring_ctx *ctx;
322 struct list_head list;
323 unsigned int flags;
c16361c1 324 refcount_t refs;
8449eeda 325#define REQ_F_NOWAIT 1 /* must not punt to workers */
def596e9 326#define REQ_F_IOPOLL_COMPLETED 2 /* polled IO has completed */
6b06314c 327#define REQ_F_FIXED_FILE 4 /* ctx owns file */
31b51510 328#define REQ_F_SEQ_PREV 8 /* sequential with previous */
d530a402 329#define REQ_F_PREPPED 16 /* prep already done */
2b188cc1 330 u64 user_data;
def596e9 331 u64 error;
2b188cc1
JA
332
333 struct work_struct work;
334};
335
336#define IO_PLUG_THRESHOLD 2
def596e9 337#define IO_IOPOLL_BATCH 8
2b188cc1 338
9a56a232
JA
339struct io_submit_state {
340 struct blk_plug plug;
341
2579f913
JA
342 /*
343 * io_kiocb alloc cache
344 */
345 void *reqs[IO_IOPOLL_BATCH];
346 unsigned int free_reqs;
347 unsigned int cur_req;
348
9a56a232
JA
349 /*
350 * File reference cache
351 */
352 struct file *file;
353 unsigned int fd;
354 unsigned int has_refs;
355 unsigned int used_refs;
356 unsigned int ios_left;
357};
358
2b188cc1
JA
359static struct kmem_cache *req_cachep;
360
361static const struct file_operations io_uring_fops;
362
363struct sock *io_uring_get_socket(struct file *file)
364{
365#if defined(CONFIG_UNIX)
366 if (file->f_op == &io_uring_fops) {
367 struct io_ring_ctx *ctx = file->private_data;
368
369 return ctx->ring_sock->sk;
370 }
371#endif
372 return NULL;
373}
374EXPORT_SYMBOL(io_uring_get_socket);
375
376static void io_ring_ctx_ref_free(struct percpu_ref *ref)
377{
378 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
379
380 complete(&ctx->ctx_done);
381}
382
383static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
384{
385 struct io_ring_ctx *ctx;
31b51510 386 int i;
2b188cc1
JA
387
388 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
389 if (!ctx)
390 return NULL;
391
392 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free, 0, GFP_KERNEL)) {
393 kfree(ctx);
394 return NULL;
395 }
396
397 ctx->flags = p->flags;
398 init_waitqueue_head(&ctx->cq_wait);
399 init_completion(&ctx->ctx_done);
400 mutex_init(&ctx->uring_lock);
401 init_waitqueue_head(&ctx->wait);
31b51510
JA
402 for (i = 0; i < ARRAY_SIZE(ctx->pending_async); i++) {
403 spin_lock_init(&ctx->pending_async[i].lock);
404 INIT_LIST_HEAD(&ctx->pending_async[i].list);
405 atomic_set(&ctx->pending_async[i].cnt, 0);
406 }
2b188cc1 407 spin_lock_init(&ctx->completion_lock);
def596e9 408 INIT_LIST_HEAD(&ctx->poll_list);
221c5eb2 409 INIT_LIST_HEAD(&ctx->cancel_list);
2b188cc1
JA
410 return ctx;
411}
412
413static void io_commit_cqring(struct io_ring_ctx *ctx)
414{
415 struct io_cq_ring *ring = ctx->cq_ring;
416
417 if (ctx->cached_cq_tail != READ_ONCE(ring->r.tail)) {
418 /* order cqe stores with ring update */
419 smp_store_release(&ring->r.tail, ctx->cached_cq_tail);
420
2b188cc1
JA
421 if (wq_has_sleeper(&ctx->cq_wait)) {
422 wake_up_interruptible(&ctx->cq_wait);
423 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
424 }
425 }
426}
427
428static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
429{
430 struct io_cq_ring *ring = ctx->cq_ring;
431 unsigned tail;
432
433 tail = ctx->cached_cq_tail;
115e12e5
SB
434 /*
435 * writes to the cq entry need to come after reading head; the
436 * control dependency is enough as we're using WRITE_ONCE to
437 * fill the cq entry
438 */
74f464e9 439 if (tail - READ_ONCE(ring->r.head) == ring->ring_entries)
2b188cc1
JA
440 return NULL;
441
442 ctx->cached_cq_tail++;
443 return &ring->cqes[tail & ctx->cq_mask];
444}
445
446static void io_cqring_fill_event(struct io_ring_ctx *ctx, u64 ki_user_data,
447 long res, unsigned ev_flags)
448{
449 struct io_uring_cqe *cqe;
450
451 /*
452 * If we can't get a cq entry, userspace overflowed the
453 * submission (by quite a lot). Increment the overflow count in
454 * the ring.
455 */
456 cqe = io_get_cqring(ctx);
457 if (cqe) {
458 WRITE_ONCE(cqe->user_data, ki_user_data);
459 WRITE_ONCE(cqe->res, res);
460 WRITE_ONCE(cqe->flags, ev_flags);
461 } else {
462 unsigned overflow = READ_ONCE(ctx->cq_ring->overflow);
463
464 WRITE_ONCE(ctx->cq_ring->overflow, overflow + 1);
465 }
466}
467
8c838788
JA
468static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
469{
470 if (waitqueue_active(&ctx->wait))
471 wake_up(&ctx->wait);
472 if (waitqueue_active(&ctx->sqo_wait))
473 wake_up(&ctx->sqo_wait);
474}
475
476static void io_cqring_add_event(struct io_ring_ctx *ctx, u64 user_data,
2b188cc1
JA
477 long res, unsigned ev_flags)
478{
479 unsigned long flags;
480
481 spin_lock_irqsave(&ctx->completion_lock, flags);
8c838788 482 io_cqring_fill_event(ctx, user_data, res, ev_flags);
2b188cc1
JA
483 io_commit_cqring(ctx);
484 spin_unlock_irqrestore(&ctx->completion_lock, flags);
485
8c838788 486 io_cqring_ev_posted(ctx);
2b188cc1
JA
487}
488
489static void io_ring_drop_ctx_refs(struct io_ring_ctx *ctx, unsigned refs)
490{
491 percpu_ref_put_many(&ctx->refs, refs);
492
493 if (waitqueue_active(&ctx->wait))
494 wake_up(&ctx->wait);
495}
496
2579f913
JA
497static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
498 struct io_submit_state *state)
2b188cc1 499{
fd6fab2c 500 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2b188cc1
JA
501 struct io_kiocb *req;
502
503 if (!percpu_ref_tryget(&ctx->refs))
504 return NULL;
505
2579f913 506 if (!state) {
fd6fab2c 507 req = kmem_cache_alloc(req_cachep, gfp);
2579f913
JA
508 if (unlikely(!req))
509 goto out;
510 } else if (!state->free_reqs) {
511 size_t sz;
512 int ret;
513
514 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
fd6fab2c
JA
515 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
516
517 /*
518 * Bulk alloc is all-or-nothing. If we fail to get a batch,
519 * retry single alloc to be on the safe side.
520 */
521 if (unlikely(ret <= 0)) {
522 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
523 if (!state->reqs[0])
524 goto out;
525 ret = 1;
526 }
2579f913
JA
527 state->free_reqs = ret - 1;
528 state->cur_req = 1;
529 req = state->reqs[0];
530 } else {
531 req = state->reqs[state->cur_req];
532 state->free_reqs--;
533 state->cur_req++;
2b188cc1
JA
534 }
535
ddae0798 536 req->file = NULL;
2579f913
JA
537 req->ctx = ctx;
538 req->flags = 0;
e65ef56d
JA
539 /* one is dropped after submission, the other at completion */
540 refcount_set(&req->refs, 2);
2579f913
JA
541 return req;
542out:
2b188cc1
JA
543 io_ring_drop_ctx_refs(ctx, 1);
544 return NULL;
545}
546
def596e9
JA
547static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
548{
549 if (*nr) {
550 kmem_cache_free_bulk(req_cachep, *nr, reqs);
551 io_ring_drop_ctx_refs(ctx, *nr);
552 *nr = 0;
553 }
554}
555
2b188cc1
JA
556static void io_free_req(struct io_kiocb *req)
557{
09bb8394
JA
558 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
559 fput(req->file);
e65ef56d
JA
560 io_ring_drop_ctx_refs(req->ctx, 1);
561 kmem_cache_free(req_cachep, req);
562}
563
564static void io_put_req(struct io_kiocb *req)
565{
566 if (refcount_dec_and_test(&req->refs))
567 io_free_req(req);
2b188cc1
JA
568}
569
def596e9
JA
570/*
571 * Find and free completed poll iocbs
572 */
573static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
574 struct list_head *done)
575{
576 void *reqs[IO_IOPOLL_BATCH];
577 struct io_kiocb *req;
09bb8394 578 int to_free;
def596e9 579
09bb8394 580 to_free = 0;
def596e9
JA
581 while (!list_empty(done)) {
582 req = list_first_entry(done, struct io_kiocb, list);
583 list_del(&req->list);
584
585 io_cqring_fill_event(ctx, req->user_data, req->error, 0);
def596e9
JA
586 (*nr_events)++;
587
09bb8394
JA
588 if (refcount_dec_and_test(&req->refs)) {
589 /* If we're not using fixed files, we have to pair the
590 * completion part with the file put. Use regular
591 * completions for those, only batch free for fixed
592 * file.
593 */
594 if (req->flags & REQ_F_FIXED_FILE) {
595 reqs[to_free++] = req;
596 if (to_free == ARRAY_SIZE(reqs))
597 io_free_req_many(ctx, reqs, &to_free);
6b06314c 598 } else {
09bb8394 599 io_free_req(req);
6b06314c 600 }
9a56a232 601 }
def596e9 602 }
def596e9 603
09bb8394 604 io_commit_cqring(ctx);
def596e9
JA
605 io_free_req_many(ctx, reqs, &to_free);
606}
607
608static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
609 long min)
610{
611 struct io_kiocb *req, *tmp;
612 LIST_HEAD(done);
613 bool spin;
614 int ret;
615
616 /*
617 * Only spin for completions if we don't have multiple devices hanging
618 * off our complete list, and we're under the requested amount.
619 */
620 spin = !ctx->poll_multi_file && *nr_events < min;
621
622 ret = 0;
623 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
624 struct kiocb *kiocb = &req->rw;
625
626 /*
627 * Move completed entries to our local list. If we find a
628 * request that requires polling, break out and complete
629 * the done list first, if we have entries there.
630 */
631 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
632 list_move_tail(&req->list, &done);
633 continue;
634 }
635 if (!list_empty(&done))
636 break;
637
638 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
639 if (ret < 0)
640 break;
641
642 if (ret && spin)
643 spin = false;
644 ret = 0;
645 }
646
647 if (!list_empty(&done))
648 io_iopoll_complete(ctx, nr_events, &done);
649
650 return ret;
651}
652
653/*
654 * Poll for a mininum of 'min' events. Note that if min == 0 we consider that a
655 * non-spinning poll check - we'll still enter the driver poll loop, but only
656 * as a non-spinning completion check.
657 */
658static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
659 long min)
660{
661 while (!list_empty(&ctx->poll_list)) {
662 int ret;
663
664 ret = io_do_iopoll(ctx, nr_events, min);
665 if (ret < 0)
666 return ret;
667 if (!min || *nr_events >= min)
668 return 0;
669 }
670
671 return 1;
672}
673
674/*
675 * We can't just wait for polled events to come to us, we have to actively
676 * find and complete them.
677 */
678static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
679{
680 if (!(ctx->flags & IORING_SETUP_IOPOLL))
681 return;
682
683 mutex_lock(&ctx->uring_lock);
684 while (!list_empty(&ctx->poll_list)) {
685 unsigned int nr_events = 0;
686
687 io_iopoll_getevents(ctx, &nr_events, 1);
688 }
689 mutex_unlock(&ctx->uring_lock);
690}
691
692static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
693 long min)
694{
695 int ret = 0;
696
697 do {
698 int tmin = 0;
699
700 if (*nr_events < min)
701 tmin = min - *nr_events;
702
703 ret = io_iopoll_getevents(ctx, nr_events, tmin);
704 if (ret <= 0)
705 break;
706 ret = 0;
707 } while (min && !*nr_events && !need_resched());
708
709 return ret;
710}
711
2b188cc1
JA
712static void kiocb_end_write(struct kiocb *kiocb)
713{
714 if (kiocb->ki_flags & IOCB_WRITE) {
715 struct inode *inode = file_inode(kiocb->ki_filp);
716
717 /*
718 * Tell lockdep we inherited freeze protection from submission
719 * thread.
720 */
721 if (S_ISREG(inode->i_mode))
722 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
723 file_end_write(kiocb->ki_filp);
724 }
725}
726
727static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
728{
729 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
730
731 kiocb_end_write(kiocb);
732
2b188cc1 733 io_cqring_add_event(req->ctx, req->user_data, res, 0);
e65ef56d 734 io_put_req(req);
2b188cc1
JA
735}
736
def596e9
JA
737static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
738{
739 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
740
741 kiocb_end_write(kiocb);
742
743 req->error = res;
744 if (res != -EAGAIN)
745 req->flags |= REQ_F_IOPOLL_COMPLETED;
746}
747
748/*
749 * After the iocb has been issued, it's safe to be found on the poll list.
750 * Adding the kiocb to the list AFTER submission ensures that we don't
751 * find it from a io_iopoll_getevents() thread before the issuer is done
752 * accessing the kiocb cookie.
753 */
754static void io_iopoll_req_issued(struct io_kiocb *req)
755{
756 struct io_ring_ctx *ctx = req->ctx;
757
758 /*
759 * Track whether we have multiple files in our lists. This will impact
760 * how we do polling eventually, not spinning if we're on potentially
761 * different devices.
762 */
763 if (list_empty(&ctx->poll_list)) {
764 ctx->poll_multi_file = false;
765 } else if (!ctx->poll_multi_file) {
766 struct io_kiocb *list_req;
767
768 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
769 list);
770 if (list_req->rw.ki_filp != req->rw.ki_filp)
771 ctx->poll_multi_file = true;
772 }
773
774 /*
775 * For fast devices, IO may have already completed. If it has, add
776 * it to the front so we find it first.
777 */
778 if (req->flags & REQ_F_IOPOLL_COMPLETED)
779 list_add(&req->list, &ctx->poll_list);
780 else
781 list_add_tail(&req->list, &ctx->poll_list);
782}
783
3d6770fb 784static void io_file_put(struct io_submit_state *state)
9a56a232 785{
3d6770fb 786 if (state->file) {
9a56a232
JA
787 int diff = state->has_refs - state->used_refs;
788
789 if (diff)
790 fput_many(state->file, diff);
791 state->file = NULL;
792 }
793}
794
795/*
796 * Get as many references to a file as we have IOs left in this submission,
797 * assuming most submissions are for one file, or at least that each file
798 * has more than one submission.
799 */
800static struct file *io_file_get(struct io_submit_state *state, int fd)
801{
802 if (!state)
803 return fget(fd);
804
805 if (state->file) {
806 if (state->fd == fd) {
807 state->used_refs++;
808 state->ios_left--;
809 return state->file;
810 }
3d6770fb 811 io_file_put(state);
9a56a232
JA
812 }
813 state->file = fget_many(fd, state->ios_left);
814 if (!state->file)
815 return NULL;
816
817 state->fd = fd;
818 state->has_refs = state->ios_left;
819 state->used_refs = 1;
820 state->ios_left--;
821 return state->file;
822}
823
2b188cc1
JA
824/*
825 * If we tracked the file through the SCM inflight mechanism, we could support
826 * any file. For now, just ensure that anything potentially problematic is done
827 * inline.
828 */
829static bool io_file_supports_async(struct file *file)
830{
831 umode_t mode = file_inode(file)->i_mode;
832
833 if (S_ISBLK(mode) || S_ISCHR(mode))
834 return true;
835 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
836 return true;
837
838 return false;
839}
840
6c271ce2 841static int io_prep_rw(struct io_kiocb *req, const struct sqe_submit *s,
8358e3a8 842 bool force_nonblock)
2b188cc1 843{
6c271ce2 844 const struct io_uring_sqe *sqe = s->sqe;
def596e9 845 struct io_ring_ctx *ctx = req->ctx;
2b188cc1 846 struct kiocb *kiocb = &req->rw;
09bb8394
JA
847 unsigned ioprio;
848 int ret;
2b188cc1 849
09bb8394
JA
850 if (!req->file)
851 return -EBADF;
2b188cc1 852 /* For -EAGAIN retry, everything is already prepped */
d530a402 853 if (req->flags & REQ_F_PREPPED)
2b188cc1
JA
854 return 0;
855
09bb8394
JA
856 if (force_nonblock && !io_file_supports_async(req->file))
857 force_nonblock = false;
6b06314c 858
2b188cc1
JA
859 kiocb->ki_pos = READ_ONCE(sqe->off);
860 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
861 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
862
863 ioprio = READ_ONCE(sqe->ioprio);
864 if (ioprio) {
865 ret = ioprio_check_cap(ioprio);
866 if (ret)
09bb8394 867 return ret;
2b188cc1
JA
868
869 kiocb->ki_ioprio = ioprio;
870 } else
871 kiocb->ki_ioprio = get_current_ioprio();
872
873 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
874 if (unlikely(ret))
09bb8394 875 return ret;
8449eeda
SB
876
877 /* don't allow async punt if RWF_NOWAIT was requested */
878 if (kiocb->ki_flags & IOCB_NOWAIT)
879 req->flags |= REQ_F_NOWAIT;
880
881 if (force_nonblock)
2b188cc1 882 kiocb->ki_flags |= IOCB_NOWAIT;
8449eeda 883
def596e9 884 if (ctx->flags & IORING_SETUP_IOPOLL) {
def596e9
JA
885 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
886 !kiocb->ki_filp->f_op->iopoll)
09bb8394 887 return -EOPNOTSUPP;
2b188cc1 888
def596e9
JA
889 req->error = 0;
890 kiocb->ki_flags |= IOCB_HIPRI;
891 kiocb->ki_complete = io_complete_rw_iopoll;
892 } else {
09bb8394
JA
893 if (kiocb->ki_flags & IOCB_HIPRI)
894 return -EINVAL;
def596e9
JA
895 kiocb->ki_complete = io_complete_rw;
896 }
d530a402 897 req->flags |= REQ_F_PREPPED;
2b188cc1 898 return 0;
2b188cc1
JA
899}
900
901static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
902{
903 switch (ret) {
904 case -EIOCBQUEUED:
905 break;
906 case -ERESTARTSYS:
907 case -ERESTARTNOINTR:
908 case -ERESTARTNOHAND:
909 case -ERESTART_RESTARTBLOCK:
910 /*
911 * We can't just restart the syscall, since previously
912 * submitted sqes may already be in progress. Just fail this
913 * IO with EINTR.
914 */
915 ret = -EINTR;
916 /* fall through */
917 default:
918 kiocb->ki_complete(kiocb, ret, 0);
919 }
920}
921
edafccee
JA
922static int io_import_fixed(struct io_ring_ctx *ctx, int rw,
923 const struct io_uring_sqe *sqe,
924 struct iov_iter *iter)
925{
926 size_t len = READ_ONCE(sqe->len);
927 struct io_mapped_ubuf *imu;
928 unsigned index, buf_index;
929 size_t offset;
930 u64 buf_addr;
931
932 /* attempt to use fixed buffers without having provided iovecs */
933 if (unlikely(!ctx->user_bufs))
934 return -EFAULT;
935
936 buf_index = READ_ONCE(sqe->buf_index);
937 if (unlikely(buf_index >= ctx->nr_user_bufs))
938 return -EFAULT;
939
940 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
941 imu = &ctx->user_bufs[index];
942 buf_addr = READ_ONCE(sqe->addr);
943
944 /* overflow */
945 if (buf_addr + len < buf_addr)
946 return -EFAULT;
947 /* not inside the mapped region */
948 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
949 return -EFAULT;
950
951 /*
952 * May not be a start of buffer, set size appropriately
953 * and advance us to the beginning.
954 */
955 offset = buf_addr - imu->ubuf;
956 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
957 if (offset)
958 iov_iter_advance(iter, offset);
875f1d07
JA
959
960 /* don't drop a reference to these pages */
961 iter->type |= ITER_BVEC_FLAG_NO_REF;
edafccee
JA
962 return 0;
963}
964
2b188cc1
JA
965static int io_import_iovec(struct io_ring_ctx *ctx, int rw,
966 const struct sqe_submit *s, struct iovec **iovec,
967 struct iov_iter *iter)
968{
969 const struct io_uring_sqe *sqe = s->sqe;
970 void __user *buf = u64_to_user_ptr(READ_ONCE(sqe->addr));
971 size_t sqe_len = READ_ONCE(sqe->len);
edafccee
JA
972 u8 opcode;
973
974 /*
975 * We're reading ->opcode for the second time, but the first read
976 * doesn't care whether it's _FIXED or not, so it doesn't matter
977 * whether ->opcode changes concurrently. The first read does care
978 * about whether it is a READ or a WRITE, so we don't trust this read
979 * for that purpose and instead let the caller pass in the read/write
980 * flag.
981 */
982 opcode = READ_ONCE(sqe->opcode);
983 if (opcode == IORING_OP_READ_FIXED ||
984 opcode == IORING_OP_WRITE_FIXED) {
e0c5c576 985 int ret = io_import_fixed(ctx, rw, sqe, iter);
edafccee
JA
986 *iovec = NULL;
987 return ret;
988 }
2b188cc1
JA
989
990 if (!s->has_user)
991 return -EFAULT;
992
993#ifdef CONFIG_COMPAT
994 if (ctx->compat)
995 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
996 iovec, iter);
997#endif
998
999 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
1000}
1001
31b51510
JA
1002/*
1003 * Make a note of the last file/offset/direction we punted to async
1004 * context. We'll use this information to see if we can piggy back a
1005 * sequential request onto the previous one, if it's still hasn't been
1006 * completed by the async worker.
1007 */
1008static void io_async_list_note(int rw, struct io_kiocb *req, size_t len)
1009{
1010 struct async_list *async_list = &req->ctx->pending_async[rw];
1011 struct kiocb *kiocb = &req->rw;
1012 struct file *filp = kiocb->ki_filp;
1013 off_t io_end = kiocb->ki_pos + len;
1014
1015 if (filp == async_list->file && kiocb->ki_pos == async_list->io_end) {
1016 unsigned long max_pages;
1017
1018 /* Use 8x RA size as a decent limiter for both reads/writes */
1019 max_pages = filp->f_ra.ra_pages;
1020 if (!max_pages)
b5420237 1021 max_pages = VM_READAHEAD_PAGES;
31b51510
JA
1022 max_pages *= 8;
1023
1024 /* If max pages are exceeded, reset the state */
1025 len >>= PAGE_SHIFT;
1026 if (async_list->io_pages + len <= max_pages) {
1027 req->flags |= REQ_F_SEQ_PREV;
1028 async_list->io_pages += len;
1029 } else {
1030 io_end = 0;
1031 async_list->io_pages = 0;
1032 }
1033 }
1034
1035 /* New file? Reset state. */
1036 if (async_list->file != filp) {
1037 async_list->io_pages = 0;
1038 async_list->file = filp;
1039 }
1040 async_list->io_end = io_end;
1041}
1042
e0c5c576 1043static int io_read(struct io_kiocb *req, const struct sqe_submit *s,
8358e3a8 1044 bool force_nonblock)
2b188cc1
JA
1045{
1046 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1047 struct kiocb *kiocb = &req->rw;
1048 struct iov_iter iter;
1049 struct file *file;
31b51510 1050 size_t iov_count;
e0c5c576 1051 int ret;
2b188cc1 1052
8358e3a8 1053 ret = io_prep_rw(req, s, force_nonblock);
2b188cc1
JA
1054 if (ret)
1055 return ret;
1056 file = kiocb->ki_filp;
1057
2b188cc1 1058 if (unlikely(!(file->f_mode & FMODE_READ)))
09bb8394 1059 return -EBADF;
2b188cc1 1060 if (unlikely(!file->f_op->read_iter))
09bb8394 1061 return -EINVAL;
2b188cc1
JA
1062
1063 ret = io_import_iovec(req->ctx, READ, s, &iovec, &iter);
1064 if (ret)
09bb8394 1065 return ret;
2b188cc1 1066
31b51510
JA
1067 iov_count = iov_iter_count(&iter);
1068 ret = rw_verify_area(READ, file, &kiocb->ki_pos, iov_count);
2b188cc1
JA
1069 if (!ret) {
1070 ssize_t ret2;
1071
1072 /* Catch -EAGAIN return for forced non-blocking submission */
1073 ret2 = call_read_iter(file, kiocb, &iter);
31b51510 1074 if (!force_nonblock || ret2 != -EAGAIN) {
2b188cc1 1075 io_rw_done(kiocb, ret2);
31b51510
JA
1076 } else {
1077 /*
1078 * If ->needs_lock is true, we're already in async
1079 * context.
1080 */
1081 if (!s->needs_lock)
1082 io_async_list_note(READ, req, iov_count);
2b188cc1 1083 ret = -EAGAIN;
31b51510 1084 }
2b188cc1
JA
1085 }
1086 kfree(iovec);
2b188cc1
JA
1087 return ret;
1088}
1089
e0c5c576 1090static int io_write(struct io_kiocb *req, const struct sqe_submit *s,
8358e3a8 1091 bool force_nonblock)
2b188cc1
JA
1092{
1093 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1094 struct kiocb *kiocb = &req->rw;
1095 struct iov_iter iter;
1096 struct file *file;
31b51510 1097 size_t iov_count;
e0c5c576 1098 int ret;
2b188cc1 1099
8358e3a8 1100 ret = io_prep_rw(req, s, force_nonblock);
2b188cc1
JA
1101 if (ret)
1102 return ret;
2b188cc1 1103
2b188cc1
JA
1104 file = kiocb->ki_filp;
1105 if (unlikely(!(file->f_mode & FMODE_WRITE)))
09bb8394 1106 return -EBADF;
2b188cc1 1107 if (unlikely(!file->f_op->write_iter))
09bb8394 1108 return -EINVAL;
2b188cc1
JA
1109
1110 ret = io_import_iovec(req->ctx, WRITE, s, &iovec, &iter);
1111 if (ret)
09bb8394 1112 return ret;
2b188cc1 1113
31b51510
JA
1114 iov_count = iov_iter_count(&iter);
1115
1116 ret = -EAGAIN;
1117 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT)) {
1118 /* If ->needs_lock is true, we're already in async context. */
1119 if (!s->needs_lock)
1120 io_async_list_note(WRITE, req, iov_count);
1121 goto out_free;
1122 }
1123
1124 ret = rw_verify_area(WRITE, file, &kiocb->ki_pos, iov_count);
2b188cc1 1125 if (!ret) {
9bf7933f
RP
1126 ssize_t ret2;
1127
2b188cc1
JA
1128 /*
1129 * Open-code file_start_write here to grab freeze protection,
1130 * which will be released by another thread in
1131 * io_complete_rw(). Fool lockdep by telling it the lock got
1132 * released so that it doesn't complain about the held lock when
1133 * we return to userspace.
1134 */
1135 if (S_ISREG(file_inode(file)->i_mode)) {
1136 __sb_start_write(file_inode(file)->i_sb,
1137 SB_FREEZE_WRITE, true);
1138 __sb_writers_release(file_inode(file)->i_sb,
1139 SB_FREEZE_WRITE);
1140 }
1141 kiocb->ki_flags |= IOCB_WRITE;
9bf7933f
RP
1142
1143 ret2 = call_write_iter(file, kiocb, &iter);
1144 if (!force_nonblock || ret2 != -EAGAIN) {
1145 io_rw_done(kiocb, ret2);
1146 } else {
1147 /*
1148 * If ->needs_lock is true, we're already in async
1149 * context.
1150 */
1151 if (!s->needs_lock)
1152 io_async_list_note(WRITE, req, iov_count);
1153 ret = -EAGAIN;
1154 }
2b188cc1 1155 }
31b51510 1156out_free:
2b188cc1 1157 kfree(iovec);
2b188cc1
JA
1158 return ret;
1159}
1160
1161/*
1162 * IORING_OP_NOP just posts a completion event, nothing else.
1163 */
1164static int io_nop(struct io_kiocb *req, u64 user_data)
1165{
1166 struct io_ring_ctx *ctx = req->ctx;
1167 long err = 0;
1168
def596e9
JA
1169 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1170 return -EINVAL;
1171
2b188cc1 1172 io_cqring_add_event(ctx, user_data, err, 0);
e65ef56d 1173 io_put_req(req);
2b188cc1
JA
1174 return 0;
1175}
1176
c992fe29
CH
1177static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1178{
6b06314c 1179 struct io_ring_ctx *ctx = req->ctx;
c992fe29 1180
09bb8394
JA
1181 if (!req->file)
1182 return -EBADF;
d530a402
JA
1183 /* Prep already done (EAGAIN retry) */
1184 if (req->flags & REQ_F_PREPPED)
c992fe29
CH
1185 return 0;
1186
6b06314c 1187 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
def596e9 1188 return -EINVAL;
edafccee 1189 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
c992fe29
CH
1190 return -EINVAL;
1191
d530a402 1192 req->flags |= REQ_F_PREPPED;
c992fe29
CH
1193 return 0;
1194}
1195
1196static int io_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1197 bool force_nonblock)
1198{
1199 loff_t sqe_off = READ_ONCE(sqe->off);
1200 loff_t sqe_len = READ_ONCE(sqe->len);
1201 loff_t end = sqe_off + sqe_len;
1202 unsigned fsync_flags;
1203 int ret;
1204
1205 fsync_flags = READ_ONCE(sqe->fsync_flags);
1206 if (unlikely(fsync_flags & ~IORING_FSYNC_DATASYNC))
1207 return -EINVAL;
1208
1209 ret = io_prep_fsync(req, sqe);
1210 if (ret)
1211 return ret;
1212
1213 /* fsync always requires a blocking context */
1214 if (force_nonblock)
1215 return -EAGAIN;
1216
1217 ret = vfs_fsync_range(req->rw.ki_filp, sqe_off,
1218 end > 0 ? end : LLONG_MAX,
1219 fsync_flags & IORING_FSYNC_DATASYNC);
1220
c992fe29 1221 io_cqring_add_event(req->ctx, sqe->user_data, ret, 0);
e65ef56d 1222 io_put_req(req);
c992fe29
CH
1223 return 0;
1224}
1225
221c5eb2
JA
1226static void io_poll_remove_one(struct io_kiocb *req)
1227{
1228 struct io_poll_iocb *poll = &req->poll;
1229
1230 spin_lock(&poll->head->lock);
1231 WRITE_ONCE(poll->canceled, true);
1232 if (!list_empty(&poll->wait.entry)) {
1233 list_del_init(&poll->wait.entry);
1234 queue_work(req->ctx->sqo_wq, &req->work);
1235 }
1236 spin_unlock(&poll->head->lock);
1237
1238 list_del_init(&req->list);
1239}
1240
1241static void io_poll_remove_all(struct io_ring_ctx *ctx)
1242{
1243 struct io_kiocb *req;
1244
1245 spin_lock_irq(&ctx->completion_lock);
1246 while (!list_empty(&ctx->cancel_list)) {
1247 req = list_first_entry(&ctx->cancel_list, struct io_kiocb,list);
1248 io_poll_remove_one(req);
1249 }
1250 spin_unlock_irq(&ctx->completion_lock);
1251}
1252
1253/*
1254 * Find a running poll command that matches one specified in sqe->addr,
1255 * and remove it if found.
1256 */
1257static int io_poll_remove(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1258{
1259 struct io_ring_ctx *ctx = req->ctx;
1260 struct io_kiocb *poll_req, *next;
1261 int ret = -ENOENT;
1262
1263 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1264 return -EINVAL;
1265 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
1266 sqe->poll_events)
1267 return -EINVAL;
1268
1269 spin_lock_irq(&ctx->completion_lock);
1270 list_for_each_entry_safe(poll_req, next, &ctx->cancel_list, list) {
1271 if (READ_ONCE(sqe->addr) == poll_req->user_data) {
1272 io_poll_remove_one(poll_req);
1273 ret = 0;
1274 break;
1275 }
1276 }
1277 spin_unlock_irq(&ctx->completion_lock);
1278
1279 io_cqring_add_event(req->ctx, sqe->user_data, ret, 0);
e65ef56d 1280 io_put_req(req);
221c5eb2
JA
1281 return 0;
1282}
1283
8c838788
JA
1284static void io_poll_complete(struct io_ring_ctx *ctx, struct io_kiocb *req,
1285 __poll_t mask)
221c5eb2 1286{
8c838788
JA
1287 req->poll.done = true;
1288 io_cqring_fill_event(ctx, req->user_data, mangle_poll(mask), 0);
1289 io_commit_cqring(ctx);
221c5eb2
JA
1290}
1291
1292static void io_poll_complete_work(struct work_struct *work)
1293{
1294 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1295 struct io_poll_iocb *poll = &req->poll;
1296 struct poll_table_struct pt = { ._key = poll->events };
1297 struct io_ring_ctx *ctx = req->ctx;
1298 __poll_t mask = 0;
1299
1300 if (!READ_ONCE(poll->canceled))
1301 mask = vfs_poll(poll->file, &pt) & poll->events;
1302
1303 /*
1304 * Note that ->ki_cancel callers also delete iocb from active_reqs after
1305 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
1306 * synchronize with them. In the cancellation case the list_del_init
1307 * itself is not actually needed, but harmless so we keep it in to
1308 * avoid further branches in the fast path.
1309 */
1310 spin_lock_irq(&ctx->completion_lock);
1311 if (!mask && !READ_ONCE(poll->canceled)) {
1312 add_wait_queue(poll->head, &poll->wait);
1313 spin_unlock_irq(&ctx->completion_lock);
1314 return;
1315 }
1316 list_del_init(&req->list);
8c838788 1317 io_poll_complete(ctx, req, mask);
221c5eb2
JA
1318 spin_unlock_irq(&ctx->completion_lock);
1319
8c838788
JA
1320 io_cqring_ev_posted(ctx);
1321 io_put_req(req);
221c5eb2
JA
1322}
1323
1324static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
1325 void *key)
1326{
1327 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
1328 wait);
1329 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
1330 struct io_ring_ctx *ctx = req->ctx;
1331 __poll_t mask = key_to_poll(key);
8c838788 1332 unsigned long flags;
221c5eb2
JA
1333
1334 /* for instances that support it check for an event match first: */
8c838788
JA
1335 if (mask && !(mask & poll->events))
1336 return 0;
221c5eb2 1337
8c838788 1338 list_del_init(&poll->wait.entry);
221c5eb2 1339
8c838788
JA
1340 if (mask && spin_trylock_irqsave(&ctx->completion_lock, flags)) {
1341 list_del(&req->list);
1342 io_poll_complete(ctx, req, mask);
1343 spin_unlock_irqrestore(&ctx->completion_lock, flags);
221c5eb2 1344
8c838788
JA
1345 io_cqring_ev_posted(ctx);
1346 io_put_req(req);
1347 } else {
1348 queue_work(ctx->sqo_wq, &req->work);
221c5eb2
JA
1349 }
1350
221c5eb2
JA
1351 return 1;
1352}
1353
1354struct io_poll_table {
1355 struct poll_table_struct pt;
1356 struct io_kiocb *req;
1357 int error;
1358};
1359
1360static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
1361 struct poll_table_struct *p)
1362{
1363 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
1364
1365 if (unlikely(pt->req->poll.head)) {
1366 pt->error = -EINVAL;
1367 return;
1368 }
1369
1370 pt->error = 0;
1371 pt->req->poll.head = head;
1372 add_wait_queue(head, &pt->req->poll.wait);
1373}
1374
1375static int io_poll_add(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1376{
1377 struct io_poll_iocb *poll = &req->poll;
1378 struct io_ring_ctx *ctx = req->ctx;
1379 struct io_poll_table ipt;
8c838788 1380 bool cancel = false;
221c5eb2
JA
1381 __poll_t mask;
1382 u16 events;
221c5eb2
JA
1383
1384 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1385 return -EINVAL;
1386 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
1387 return -EINVAL;
09bb8394
JA
1388 if (!poll->file)
1389 return -EBADF;
221c5eb2
JA
1390
1391 INIT_WORK(&req->work, io_poll_complete_work);
1392 events = READ_ONCE(sqe->poll_events);
1393 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
1394
221c5eb2 1395 poll->head = NULL;
8c838788 1396 poll->done = false;
221c5eb2
JA
1397 poll->canceled = false;
1398
1399 ipt.pt._qproc = io_poll_queue_proc;
1400 ipt.pt._key = poll->events;
1401 ipt.req = req;
1402 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
1403
1404 /* initialized the list so that we can do list_empty checks */
1405 INIT_LIST_HEAD(&poll->wait.entry);
1406 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
1407
221c5eb2 1408 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
221c5eb2
JA
1409
1410 spin_lock_irq(&ctx->completion_lock);
8c838788
JA
1411 if (likely(poll->head)) {
1412 spin_lock(&poll->head->lock);
1413 if (unlikely(list_empty(&poll->wait.entry))) {
1414 if (ipt.error)
1415 cancel = true;
1416 ipt.error = 0;
1417 mask = 0;
1418 }
1419 if (mask || ipt.error)
1420 list_del_init(&poll->wait.entry);
1421 else if (cancel)
1422 WRITE_ONCE(poll->canceled, true);
1423 else if (!poll->done) /* actually waiting for an event */
1424 list_add_tail(&req->list, &ctx->cancel_list);
1425 spin_unlock(&poll->head->lock);
1426 }
1427 if (mask) { /* no async, we'd stolen it */
1428 req->error = mangle_poll(mask);
221c5eb2 1429 ipt.error = 0;
8c838788 1430 io_poll_complete(ctx, req, mask);
221c5eb2 1431 }
221c5eb2
JA
1432 spin_unlock_irq(&ctx->completion_lock);
1433
8c838788
JA
1434 if (mask) {
1435 io_cqring_ev_posted(ctx);
e65ef56d 1436 io_put_req(req);
221c5eb2 1437 }
8c838788 1438 return ipt.error;
221c5eb2
JA
1439}
1440
2b188cc1 1441static int __io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
8358e3a8 1442 const struct sqe_submit *s, bool force_nonblock)
2b188cc1 1443{
e0c5c576 1444 int ret, opcode;
2b188cc1
JA
1445
1446 if (unlikely(s->index >= ctx->sq_entries))
1447 return -EINVAL;
1448 req->user_data = READ_ONCE(s->sqe->user_data);
1449
1450 opcode = READ_ONCE(s->sqe->opcode);
1451 switch (opcode) {
1452 case IORING_OP_NOP:
1453 ret = io_nop(req, req->user_data);
1454 break;
1455 case IORING_OP_READV:
edafccee
JA
1456 if (unlikely(s->sqe->buf_index))
1457 return -EINVAL;
8358e3a8 1458 ret = io_read(req, s, force_nonblock);
2b188cc1
JA
1459 break;
1460 case IORING_OP_WRITEV:
edafccee
JA
1461 if (unlikely(s->sqe->buf_index))
1462 return -EINVAL;
8358e3a8 1463 ret = io_write(req, s, force_nonblock);
edafccee
JA
1464 break;
1465 case IORING_OP_READ_FIXED:
8358e3a8 1466 ret = io_read(req, s, force_nonblock);
edafccee
JA
1467 break;
1468 case IORING_OP_WRITE_FIXED:
8358e3a8 1469 ret = io_write(req, s, force_nonblock);
2b188cc1 1470 break;
c992fe29
CH
1471 case IORING_OP_FSYNC:
1472 ret = io_fsync(req, s->sqe, force_nonblock);
1473 break;
221c5eb2
JA
1474 case IORING_OP_POLL_ADD:
1475 ret = io_poll_add(req, s->sqe);
1476 break;
1477 case IORING_OP_POLL_REMOVE:
1478 ret = io_poll_remove(req, s->sqe);
1479 break;
2b188cc1
JA
1480 default:
1481 ret = -EINVAL;
1482 break;
1483 }
1484
def596e9
JA
1485 if (ret)
1486 return ret;
1487
1488 if (ctx->flags & IORING_SETUP_IOPOLL) {
1489 if (req->error == -EAGAIN)
1490 return -EAGAIN;
1491
1492 /* workqueue context doesn't hold uring_lock, grab it now */
1493 if (s->needs_lock)
1494 mutex_lock(&ctx->uring_lock);
1495 io_iopoll_req_issued(req);
1496 if (s->needs_lock)
1497 mutex_unlock(&ctx->uring_lock);
1498 }
1499
1500 return 0;
2b188cc1
JA
1501}
1502
31b51510
JA
1503static struct async_list *io_async_list_from_sqe(struct io_ring_ctx *ctx,
1504 const struct io_uring_sqe *sqe)
1505{
1506 switch (sqe->opcode) {
1507 case IORING_OP_READV:
1508 case IORING_OP_READ_FIXED:
1509 return &ctx->pending_async[READ];
1510 case IORING_OP_WRITEV:
1511 case IORING_OP_WRITE_FIXED:
1512 return &ctx->pending_async[WRITE];
1513 default:
1514 return NULL;
1515 }
1516}
1517
edafccee
JA
1518static inline bool io_sqe_needs_user(const struct io_uring_sqe *sqe)
1519{
1520 u8 opcode = READ_ONCE(sqe->opcode);
1521
1522 return !(opcode == IORING_OP_READ_FIXED ||
1523 opcode == IORING_OP_WRITE_FIXED);
1524}
1525
2b188cc1
JA
1526static void io_sq_wq_submit_work(struct work_struct *work)
1527{
1528 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2b188cc1 1529 struct io_ring_ctx *ctx = req->ctx;
31b51510
JA
1530 struct mm_struct *cur_mm = NULL;
1531 struct async_list *async_list;
1532 LIST_HEAD(req_list);
edafccee 1533 mm_segment_t old_fs;
2b188cc1
JA
1534 int ret;
1535
31b51510
JA
1536 async_list = io_async_list_from_sqe(ctx, req->submit.sqe);
1537restart:
1538 do {
1539 struct sqe_submit *s = &req->submit;
1540 const struct io_uring_sqe *sqe = s->sqe;
2b188cc1 1541
8449eeda 1542 /* Ensure we clear previously set non-block flag */
31b51510
JA
1543 req->rw.ki_flags &= ~IOCB_NOWAIT;
1544
1545 ret = 0;
1546 if (io_sqe_needs_user(sqe) && !cur_mm) {
1547 if (!mmget_not_zero(ctx->sqo_mm)) {
1548 ret = -EFAULT;
1549 } else {
1550 cur_mm = ctx->sqo_mm;
1551 use_mm(cur_mm);
1552 old_fs = get_fs();
1553 set_fs(USER_DS);
1554 }
1555 }
1556
1557 if (!ret) {
1558 s->has_user = cur_mm != NULL;
1559 s->needs_lock = true;
1560 do {
8358e3a8 1561 ret = __io_submit_sqe(ctx, req, s, false);
31b51510
JA
1562 /*
1563 * We can get EAGAIN for polled IO even though
1564 * we're forcing a sync submission from here,
1565 * since we can't wait for request slots on the
1566 * block side.
1567 */
1568 if (ret != -EAGAIN)
1569 break;
1570 cond_resched();
1571 } while (1);
1572 }
817869d2
JA
1573
1574 /* drop submission reference */
1575 io_put_req(req);
1576
31b51510
JA
1577 if (ret) {
1578 io_cqring_add_event(ctx, sqe->user_data, ret, 0);
e65ef56d 1579 io_put_req(req);
31b51510
JA
1580 }
1581
1582 /* async context always use a copy of the sqe */
1583 kfree(sqe);
1584
1585 if (!async_list)
1586 break;
1587 if (!list_empty(&req_list)) {
1588 req = list_first_entry(&req_list, struct io_kiocb,
1589 list);
1590 list_del(&req->list);
1591 continue;
1592 }
1593 if (list_empty(&async_list->list))
1594 break;
1595
1596 req = NULL;
1597 spin_lock(&async_list->lock);
1598 if (list_empty(&async_list->list)) {
1599 spin_unlock(&async_list->lock);
1600 break;
1601 }
1602 list_splice_init(&async_list->list, &req_list);
1603 spin_unlock(&async_list->lock);
1604
1605 req = list_first_entry(&req_list, struct io_kiocb, list);
1606 list_del(&req->list);
1607 } while (req);
edafccee
JA
1608
1609 /*
31b51510
JA
1610 * Rare case of racing with a submitter. If we find the count has
1611 * dropped to zero AND we have pending work items, then restart
1612 * the processing. This is a tiny race window.
edafccee 1613 */
31b51510
JA
1614 if (async_list) {
1615 ret = atomic_dec_return(&async_list->cnt);
1616 while (!ret && !list_empty(&async_list->list)) {
1617 spin_lock(&async_list->lock);
1618 atomic_inc(&async_list->cnt);
1619 list_splice_init(&async_list->list, &req_list);
1620 spin_unlock(&async_list->lock);
1621
1622 if (!list_empty(&req_list)) {
1623 req = list_first_entry(&req_list,
1624 struct io_kiocb, list);
1625 list_del(&req->list);
1626 goto restart;
1627 }
1628 ret = atomic_dec_return(&async_list->cnt);
edafccee 1629 }
edafccee 1630 }
2b188cc1 1631
31b51510 1632 if (cur_mm) {
edafccee 1633 set_fs(old_fs);
31b51510
JA
1634 unuse_mm(cur_mm);
1635 mmput(cur_mm);
2b188cc1 1636 }
31b51510 1637}
2b188cc1 1638
31b51510
JA
1639/*
1640 * See if we can piggy back onto previously submitted work, that is still
1641 * running. We currently only allow this if the new request is sequential
1642 * to the previous one we punted.
1643 */
1644static bool io_add_to_prev_work(struct async_list *list, struct io_kiocb *req)
1645{
1646 bool ret = false;
1647
1648 if (!list)
1649 return false;
1650 if (!(req->flags & REQ_F_SEQ_PREV))
1651 return false;
1652 if (!atomic_read(&list->cnt))
1653 return false;
1654
1655 ret = true;
1656 spin_lock(&list->lock);
1657 list_add_tail(&req->list, &list->list);
1658 if (!atomic_read(&list->cnt)) {
1659 list_del_init(&req->list);
1660 ret = false;
1661 }
1662 spin_unlock(&list->lock);
1663 return ret;
2b188cc1
JA
1664}
1665
09bb8394
JA
1666static bool io_op_needs_file(const struct io_uring_sqe *sqe)
1667{
1668 int op = READ_ONCE(sqe->opcode);
1669
1670 switch (op) {
1671 case IORING_OP_NOP:
1672 case IORING_OP_POLL_REMOVE:
1673 return false;
1674 default:
1675 return true;
1676 }
1677}
1678
1679static int io_req_set_file(struct io_ring_ctx *ctx, const struct sqe_submit *s,
1680 struct io_submit_state *state, struct io_kiocb *req)
1681{
1682 unsigned flags;
1683 int fd;
1684
1685 flags = READ_ONCE(s->sqe->flags);
1686 fd = READ_ONCE(s->sqe->fd);
1687
ddae0798 1688 if (!io_op_needs_file(s->sqe))
09bb8394 1689 return 0;
09bb8394
JA
1690
1691 if (flags & IOSQE_FIXED_FILE) {
1692 if (unlikely(!ctx->user_files ||
1693 (unsigned) fd >= ctx->nr_user_files))
1694 return -EBADF;
1695 req->file = ctx->user_files[fd];
1696 req->flags |= REQ_F_FIXED_FILE;
1697 } else {
1698 if (s->needs_fixed_file)
1699 return -EBADF;
1700 req->file = io_file_get(state, fd);
1701 if (unlikely(!req->file))
1702 return -EBADF;
1703 }
1704
1705 return 0;
1706}
1707
9a56a232
JA
1708static int io_submit_sqe(struct io_ring_ctx *ctx, struct sqe_submit *s,
1709 struct io_submit_state *state)
2b188cc1
JA
1710{
1711 struct io_kiocb *req;
e0c5c576 1712 int ret;
2b188cc1
JA
1713
1714 /* enforce forwards compatibility on users */
6b06314c 1715 if (unlikely(s->sqe->flags & ~IOSQE_FIXED_FILE))
2b188cc1
JA
1716 return -EINVAL;
1717
2579f913 1718 req = io_get_req(ctx, state);
2b188cc1
JA
1719 if (unlikely(!req))
1720 return -EAGAIN;
1721
09bb8394
JA
1722 ret = io_req_set_file(ctx, s, state, req);
1723 if (unlikely(ret))
1724 goto out;
2b188cc1 1725
8358e3a8 1726 ret = __io_submit_sqe(ctx, req, s, true);
8449eeda 1727 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
2b188cc1
JA
1728 struct io_uring_sqe *sqe_copy;
1729
1730 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
1731 if (sqe_copy) {
31b51510
JA
1732 struct async_list *list;
1733
2b188cc1
JA
1734 memcpy(sqe_copy, s->sqe, sizeof(*sqe_copy));
1735 s->sqe = sqe_copy;
1736
1737 memcpy(&req->submit, s, sizeof(*s));
31b51510
JA
1738 list = io_async_list_from_sqe(ctx, s->sqe);
1739 if (!io_add_to_prev_work(list, req)) {
1740 if (list)
1741 atomic_inc(&list->cnt);
1742 INIT_WORK(&req->work, io_sq_wq_submit_work);
1743 queue_work(ctx->sqo_wq, &req->work);
1744 }
e65ef56d
JA
1745
1746 /*
1747 * Queued up for async execution, worker will release
1748 * submit reference when the iocb is actually
1749 * submitted.
1750 */
1751 return 0;
2b188cc1
JA
1752 }
1753 }
e65ef56d 1754
09bb8394 1755out:
e65ef56d
JA
1756 /* drop submission reference */
1757 io_put_req(req);
1758
1759 /* and drop final reference, if we failed */
2b188cc1 1760 if (ret)
e65ef56d 1761 io_put_req(req);
2b188cc1
JA
1762
1763 return ret;
1764}
1765
9a56a232
JA
1766/*
1767 * Batched submission is done, ensure local IO is flushed out.
1768 */
1769static void io_submit_state_end(struct io_submit_state *state)
1770{
1771 blk_finish_plug(&state->plug);
3d6770fb 1772 io_file_put(state);
2579f913
JA
1773 if (state->free_reqs)
1774 kmem_cache_free_bulk(req_cachep, state->free_reqs,
1775 &state->reqs[state->cur_req]);
9a56a232
JA
1776}
1777
1778/*
1779 * Start submission side cache.
1780 */
1781static void io_submit_state_start(struct io_submit_state *state,
1782 struct io_ring_ctx *ctx, unsigned max_ios)
1783{
1784 blk_start_plug(&state->plug);
2579f913 1785 state->free_reqs = 0;
9a56a232
JA
1786 state->file = NULL;
1787 state->ios_left = max_ios;
1788}
1789
2b188cc1
JA
1790static void io_commit_sqring(struct io_ring_ctx *ctx)
1791{
1792 struct io_sq_ring *ring = ctx->sq_ring;
1793
1794 if (ctx->cached_sq_head != READ_ONCE(ring->r.head)) {
1795 /*
1796 * Ensure any loads from the SQEs are done at this point,
1797 * since once we write the new head, the application could
1798 * write new data to them.
1799 */
1800 smp_store_release(&ring->r.head, ctx->cached_sq_head);
2b188cc1
JA
1801 }
1802}
1803
2b188cc1
JA
1804/*
1805 * Fetch an sqe, if one is available. Note that s->sqe will point to memory
1806 * that is mapped by userspace. This means that care needs to be taken to
1807 * ensure that reads are stable, as we cannot rely on userspace always
1808 * being a good citizen. If members of the sqe are validated and then later
1809 * used, it's important that those reads are done through READ_ONCE() to
1810 * prevent a re-load down the line.
1811 */
1812static bool io_get_sqring(struct io_ring_ctx *ctx, struct sqe_submit *s)
1813{
1814 struct io_sq_ring *ring = ctx->sq_ring;
1815 unsigned head;
1816
1817 /*
1818 * The cached sq head (or cq tail) serves two purposes:
1819 *
1820 * 1) allows us to batch the cost of updating the user visible
1821 * head updates.
1822 * 2) allows the kernel side to track the head on its own, even
1823 * though the application is the one updating it.
1824 */
1825 head = ctx->cached_sq_head;
e523a29c
SB
1826 /* make sure SQ entry isn't read before tail */
1827 if (head == smp_load_acquire(&ring->r.tail))
2b188cc1
JA
1828 return false;
1829
1830 head = READ_ONCE(ring->array[head & ctx->sq_mask]);
1831 if (head < ctx->sq_entries) {
1832 s->index = head;
1833 s->sqe = &ctx->sq_sqes[head];
1834 ctx->cached_sq_head++;
1835 return true;
1836 }
1837
1838 /* drop invalid entries */
1839 ctx->cached_sq_head++;
1840 ring->dropped++;
2b188cc1
JA
1841 return false;
1842}
1843
6c271ce2
JA
1844static int io_submit_sqes(struct io_ring_ctx *ctx, struct sqe_submit *sqes,
1845 unsigned int nr, bool has_user, bool mm_fault)
1846{
1847 struct io_submit_state state, *statep = NULL;
1848 int ret, i, submitted = 0;
1849
1850 if (nr > IO_PLUG_THRESHOLD) {
1851 io_submit_state_start(&state, ctx, nr);
1852 statep = &state;
1853 }
1854
1855 for (i = 0; i < nr; i++) {
1856 if (unlikely(mm_fault)) {
1857 ret = -EFAULT;
1858 } else {
1859 sqes[i].has_user = has_user;
1860 sqes[i].needs_lock = true;
1861 sqes[i].needs_fixed_file = true;
1862 ret = io_submit_sqe(ctx, &sqes[i], statep);
1863 }
1864 if (!ret) {
1865 submitted++;
1866 continue;
1867 }
1868
1869 io_cqring_add_event(ctx, sqes[i].sqe->user_data, ret, 0);
1870 }
1871
1872 if (statep)
1873 io_submit_state_end(&state);
1874
1875 return submitted;
1876}
1877
1878static int io_sq_thread(void *data)
1879{
1880 struct sqe_submit sqes[IO_IOPOLL_BATCH];
1881 struct io_ring_ctx *ctx = data;
1882 struct mm_struct *cur_mm = NULL;
1883 mm_segment_t old_fs;
1884 DEFINE_WAIT(wait);
1885 unsigned inflight;
1886 unsigned long timeout;
1887
1888 old_fs = get_fs();
1889 set_fs(USER_DS);
1890
1891 timeout = inflight = 0;
1892 while (!kthread_should_stop() && !ctx->sqo_stop) {
1893 bool all_fixed, mm_fault = false;
1894 int i;
1895
1896 if (inflight) {
1897 unsigned nr_events = 0;
1898
1899 if (ctx->flags & IORING_SETUP_IOPOLL) {
1900 /*
1901 * We disallow the app entering submit/complete
1902 * with polling, but we still need to lock the
1903 * ring to prevent racing with polled issue
1904 * that got punted to a workqueue.
1905 */
1906 mutex_lock(&ctx->uring_lock);
1907 io_iopoll_check(ctx, &nr_events, 0);
1908 mutex_unlock(&ctx->uring_lock);
1909 } else {
1910 /*
1911 * Normal IO, just pretend everything completed.
1912 * We don't have to poll completions for that.
1913 */
1914 nr_events = inflight;
1915 }
1916
1917 inflight -= nr_events;
1918 if (!inflight)
1919 timeout = jiffies + ctx->sq_thread_idle;
1920 }
1921
1922 if (!io_get_sqring(ctx, &sqes[0])) {
1923 /*
1924 * We're polling. If we're within the defined idle
1925 * period, then let us spin without work before going
1926 * to sleep.
1927 */
1928 if (inflight || !time_after(jiffies, timeout)) {
1929 cpu_relax();
1930 continue;
1931 }
1932
1933 /*
1934 * Drop cur_mm before scheduling, we can't hold it for
1935 * long periods (or over schedule()). Do this before
1936 * adding ourselves to the waitqueue, as the unuse/drop
1937 * may sleep.
1938 */
1939 if (cur_mm) {
1940 unuse_mm(cur_mm);
1941 mmput(cur_mm);
1942 cur_mm = NULL;
1943 }
1944
1945 prepare_to_wait(&ctx->sqo_wait, &wait,
1946 TASK_INTERRUPTIBLE);
1947
1948 /* Tell userspace we may need a wakeup call */
1949 ctx->sq_ring->flags |= IORING_SQ_NEED_WAKEUP;
0d7bae69
SB
1950 /* make sure to read SQ tail after writing flags */
1951 smp_mb();
6c271ce2
JA
1952
1953 if (!io_get_sqring(ctx, &sqes[0])) {
1954 if (kthread_should_stop()) {
1955 finish_wait(&ctx->sqo_wait, &wait);
1956 break;
1957 }
1958 if (signal_pending(current))
1959 flush_signals(current);
1960 schedule();
1961 finish_wait(&ctx->sqo_wait, &wait);
1962
1963 ctx->sq_ring->flags &= ~IORING_SQ_NEED_WAKEUP;
6c271ce2
JA
1964 continue;
1965 }
1966 finish_wait(&ctx->sqo_wait, &wait);
1967
1968 ctx->sq_ring->flags &= ~IORING_SQ_NEED_WAKEUP;
6c271ce2
JA
1969 }
1970
1971 i = 0;
1972 all_fixed = true;
1973 do {
1974 if (all_fixed && io_sqe_needs_user(sqes[i].sqe))
1975 all_fixed = false;
1976
1977 i++;
1978 if (i == ARRAY_SIZE(sqes))
1979 break;
1980 } while (io_get_sqring(ctx, &sqes[i]));
1981
1982 /* Unless all new commands are FIXED regions, grab mm */
1983 if (!all_fixed && !cur_mm) {
1984 mm_fault = !mmget_not_zero(ctx->sqo_mm);
1985 if (!mm_fault) {
1986 use_mm(ctx->sqo_mm);
1987 cur_mm = ctx->sqo_mm;
1988 }
1989 }
1990
1991 inflight += io_submit_sqes(ctx, sqes, i, cur_mm != NULL,
1992 mm_fault);
1993
1994 /* Commit SQ ring head once we've consumed all SQEs */
1995 io_commit_sqring(ctx);
1996 }
1997
1998 set_fs(old_fs);
1999 if (cur_mm) {
2000 unuse_mm(cur_mm);
2001 mmput(cur_mm);
2002 }
06058632
JA
2003
2004 if (kthread_should_park())
2005 kthread_parkme();
2006
6c271ce2
JA
2007 return 0;
2008}
2009
2b188cc1
JA
2010static int io_ring_submit(struct io_ring_ctx *ctx, unsigned int to_submit)
2011{
9a56a232 2012 struct io_submit_state state, *statep = NULL;
5c8b0b54 2013 int i, submit = 0;
2b188cc1 2014
9a56a232
JA
2015 if (to_submit > IO_PLUG_THRESHOLD) {
2016 io_submit_state_start(&state, ctx, to_submit);
2017 statep = &state;
2018 }
2b188cc1
JA
2019
2020 for (i = 0; i < to_submit; i++) {
2021 struct sqe_submit s;
5c8b0b54 2022 int ret;
2b188cc1
JA
2023
2024 if (!io_get_sqring(ctx, &s))
2025 break;
2026
2027 s.has_user = true;
def596e9 2028 s.needs_lock = false;
6c271ce2 2029 s.needs_fixed_file = false;
5c8b0b54 2030 submit++;
def596e9 2031
9a56a232 2032 ret = io_submit_sqe(ctx, &s, statep);
5c8b0b54
JA
2033 if (ret)
2034 io_cqring_add_event(ctx, s.sqe->user_data, ret, 0);
2b188cc1
JA
2035 }
2036 io_commit_sqring(ctx);
2037
9a56a232
JA
2038 if (statep)
2039 io_submit_state_end(statep);
2b188cc1 2040
5c8b0b54 2041 return submit;
2b188cc1
JA
2042}
2043
2044static unsigned io_cqring_events(struct io_cq_ring *ring)
2045{
2046 return READ_ONCE(ring->r.tail) - READ_ONCE(ring->r.head);
2047}
2048
2049/*
2050 * Wait until events become available, if we don't already have some. The
2051 * application must reap them itself, as they reside on the shared cq ring.
2052 */
2053static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
2054 const sigset_t __user *sig, size_t sigsz)
2055{
2056 struct io_cq_ring *ring = ctx->cq_ring;
2057 sigset_t ksigmask, sigsaved;
2058 DEFINE_WAIT(wait);
2059 int ret;
2060
2061 /* See comment at the top of this file */
2062 smp_rmb();
2063 if (io_cqring_events(ring) >= min_events)
2064 return 0;
2065
2066 if (sig) {
9e75ad5d
AB
2067#ifdef CONFIG_COMPAT
2068 if (in_compat_syscall())
2069 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
2070 &ksigmask, &sigsaved, sigsz);
2071 else
2072#endif
2073 ret = set_user_sigmask(sig, &ksigmask,
2074 &sigsaved, sigsz);
2075
2b188cc1
JA
2076 if (ret)
2077 return ret;
2078 }
2079
2080 do {
2081 prepare_to_wait(&ctx->wait, &wait, TASK_INTERRUPTIBLE);
2082
2083 ret = 0;
2084 /* See comment at the top of this file */
2085 smp_rmb();
2086 if (io_cqring_events(ring) >= min_events)
2087 break;
2088
2089 schedule();
2090
2091 ret = -EINTR;
2092 if (signal_pending(current))
2093 break;
2094 } while (1);
2095
2096 finish_wait(&ctx->wait, &wait);
2097
2098 if (sig)
50c5095a 2099 restore_user_sigmask(sig, &sigsaved, ret == -EINTR);
2b188cc1
JA
2100
2101 return READ_ONCE(ring->r.head) == READ_ONCE(ring->r.tail) ? ret : 0;
2102}
2103
6b06314c
JA
2104static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
2105{
2106#if defined(CONFIG_UNIX)
2107 if (ctx->ring_sock) {
2108 struct sock *sock = ctx->ring_sock->sk;
2109 struct sk_buff *skb;
2110
2111 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
2112 kfree_skb(skb);
2113 }
2114#else
2115 int i;
2116
2117 for (i = 0; i < ctx->nr_user_files; i++)
2118 fput(ctx->user_files[i]);
2119#endif
2120}
2121
2122static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
2123{
2124 if (!ctx->user_files)
2125 return -ENXIO;
2126
2127 __io_sqe_files_unregister(ctx);
2128 kfree(ctx->user_files);
2129 ctx->user_files = NULL;
2130 ctx->nr_user_files = 0;
2131 return 0;
2132}
2133
6c271ce2
JA
2134static void io_sq_thread_stop(struct io_ring_ctx *ctx)
2135{
2136 if (ctx->sqo_thread) {
2137 ctx->sqo_stop = 1;
2138 mb();
06058632 2139 kthread_park(ctx->sqo_thread);
6c271ce2
JA
2140 kthread_stop(ctx->sqo_thread);
2141 ctx->sqo_thread = NULL;
2142 }
2143}
2144
6b06314c
JA
2145static void io_finish_async(struct io_ring_ctx *ctx)
2146{
6c271ce2
JA
2147 io_sq_thread_stop(ctx);
2148
6b06314c
JA
2149 if (ctx->sqo_wq) {
2150 destroy_workqueue(ctx->sqo_wq);
2151 ctx->sqo_wq = NULL;
2152 }
2153}
2154
2155#if defined(CONFIG_UNIX)
2156static void io_destruct_skb(struct sk_buff *skb)
2157{
2158 struct io_ring_ctx *ctx = skb->sk->sk_user_data;
2159
2160 io_finish_async(ctx);
2161 unix_destruct_scm(skb);
2162}
2163
2164/*
2165 * Ensure the UNIX gc is aware of our file set, so we are certain that
2166 * the io_uring can be safely unregistered on process exit, even if we have
2167 * loops in the file referencing.
2168 */
2169static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
2170{
2171 struct sock *sk = ctx->ring_sock->sk;
2172 struct scm_fp_list *fpl;
2173 struct sk_buff *skb;
2174 int i;
2175
2176 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
2177 unsigned long inflight = ctx->user->unix_inflight + nr;
2178
2179 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
2180 return -EMFILE;
2181 }
2182
2183 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
2184 if (!fpl)
2185 return -ENOMEM;
2186
2187 skb = alloc_skb(0, GFP_KERNEL);
2188 if (!skb) {
2189 kfree(fpl);
2190 return -ENOMEM;
2191 }
2192
2193 skb->sk = sk;
2194 skb->destructor = io_destruct_skb;
2195
2196 fpl->user = get_uid(ctx->user);
2197 for (i = 0; i < nr; i++) {
2198 fpl->fp[i] = get_file(ctx->user_files[i + offset]);
2199 unix_inflight(fpl->user, fpl->fp[i]);
2200 }
2201
2202 fpl->max = fpl->count = nr;
2203 UNIXCB(skb).fp = fpl;
2204 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
2205 skb_queue_head(&sk->sk_receive_queue, skb);
2206
2207 for (i = 0; i < nr; i++)
2208 fput(fpl->fp[i]);
2209
2210 return 0;
2211}
2212
2213/*
2214 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
2215 * causes regular reference counting to break down. We rely on the UNIX
2216 * garbage collection to take care of this problem for us.
2217 */
2218static int io_sqe_files_scm(struct io_ring_ctx *ctx)
2219{
2220 unsigned left, total;
2221 int ret = 0;
2222
2223 total = 0;
2224 left = ctx->nr_user_files;
2225 while (left) {
2226 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
2227 int ret;
2228
2229 ret = __io_sqe_files_scm(ctx, this_files, total);
2230 if (ret)
2231 break;
2232 left -= this_files;
2233 total += this_files;
2234 }
2235
2236 if (!ret)
2237 return 0;
2238
2239 while (total < ctx->nr_user_files) {
2240 fput(ctx->user_files[total]);
2241 total++;
2242 }
2243
2244 return ret;
2245}
2246#else
2247static int io_sqe_files_scm(struct io_ring_ctx *ctx)
2248{
2249 return 0;
2250}
2251#endif
2252
2253static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
2254 unsigned nr_args)
2255{
2256 __s32 __user *fds = (__s32 __user *) arg;
2257 int fd, ret = 0;
2258 unsigned i;
2259
2260 if (ctx->user_files)
2261 return -EBUSY;
2262 if (!nr_args)
2263 return -EINVAL;
2264 if (nr_args > IORING_MAX_FIXED_FILES)
2265 return -EMFILE;
2266
2267 ctx->user_files = kcalloc(nr_args, sizeof(struct file *), GFP_KERNEL);
2268 if (!ctx->user_files)
2269 return -ENOMEM;
2270
2271 for (i = 0; i < nr_args; i++) {
2272 ret = -EFAULT;
2273 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
2274 break;
2275
2276 ctx->user_files[i] = fget(fd);
2277
2278 ret = -EBADF;
2279 if (!ctx->user_files[i])
2280 break;
2281 /*
2282 * Don't allow io_uring instances to be registered. If UNIX
2283 * isn't enabled, then this causes a reference cycle and this
2284 * instance can never get freed. If UNIX is enabled we'll
2285 * handle it just fine, but there's still no point in allowing
2286 * a ring fd as it doesn't support regular read/write anyway.
2287 */
2288 if (ctx->user_files[i]->f_op == &io_uring_fops) {
2289 fput(ctx->user_files[i]);
2290 break;
2291 }
2292 ctx->nr_user_files++;
2293 ret = 0;
2294 }
2295
2296 if (ret) {
2297 for (i = 0; i < ctx->nr_user_files; i++)
2298 fput(ctx->user_files[i]);
2299
2300 kfree(ctx->user_files);
25adf50f 2301 ctx->user_files = NULL;
6b06314c
JA
2302 ctx->nr_user_files = 0;
2303 return ret;
2304 }
2305
2306 ret = io_sqe_files_scm(ctx);
2307 if (ret)
2308 io_sqe_files_unregister(ctx);
2309
2310 return ret;
2311}
2312
6c271ce2
JA
2313static int io_sq_offload_start(struct io_ring_ctx *ctx,
2314 struct io_uring_params *p)
2b188cc1
JA
2315{
2316 int ret;
2317
6c271ce2 2318 init_waitqueue_head(&ctx->sqo_wait);
2b188cc1
JA
2319 mmgrab(current->mm);
2320 ctx->sqo_mm = current->mm;
2321
6c271ce2 2322 if (ctx->flags & IORING_SETUP_SQPOLL) {
3ec482d1
JA
2323 ret = -EPERM;
2324 if (!capable(CAP_SYS_ADMIN))
2325 goto err;
2326
917257da
JA
2327 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
2328 if (!ctx->sq_thread_idle)
2329 ctx->sq_thread_idle = HZ;
2330
6c271ce2 2331 if (p->flags & IORING_SETUP_SQ_AFF) {
cf1fa8c9 2332 int cpu = p->sq_thread_cpu;
6c271ce2 2333
917257da 2334 ret = -EINVAL;
cf1fa8c9
JA
2335 if (cpu >= nr_cpu_ids)
2336 goto err;
b6e7eed8 2337 if (!cpu_online(cpu))
917257da
JA
2338 goto err;
2339
6c271ce2
JA
2340 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
2341 ctx, cpu,
2342 "io_uring-sq");
2343 } else {
2344 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
2345 "io_uring-sq");
2346 }
2347 if (IS_ERR(ctx->sqo_thread)) {
2348 ret = PTR_ERR(ctx->sqo_thread);
2349 ctx->sqo_thread = NULL;
2350 goto err;
2351 }
2352 wake_up_process(ctx->sqo_thread);
2353 } else if (p->flags & IORING_SETUP_SQ_AFF) {
2354 /* Can't have SQ_AFF without SQPOLL */
2355 ret = -EINVAL;
2356 goto err;
2357 }
2358
2b188cc1
JA
2359 /* Do QD, or 2 * CPUS, whatever is smallest */
2360 ctx->sqo_wq = alloc_workqueue("io_ring-wq", WQ_UNBOUND | WQ_FREEZABLE,
2361 min(ctx->sq_entries - 1, 2 * num_online_cpus()));
2362 if (!ctx->sqo_wq) {
2363 ret = -ENOMEM;
2364 goto err;
2365 }
2366
2367 return 0;
2368err:
6c271ce2 2369 io_sq_thread_stop(ctx);
2b188cc1
JA
2370 mmdrop(ctx->sqo_mm);
2371 ctx->sqo_mm = NULL;
2372 return ret;
2373}
2374
2375static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
2376{
2377 atomic_long_sub(nr_pages, &user->locked_vm);
2378}
2379
2380static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
2381{
2382 unsigned long page_limit, cur_pages, new_pages;
2383
2384 /* Don't allow more pages than we can safely lock */
2385 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
2386
2387 do {
2388 cur_pages = atomic_long_read(&user->locked_vm);
2389 new_pages = cur_pages + nr_pages;
2390 if (new_pages > page_limit)
2391 return -ENOMEM;
2392 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
2393 new_pages) != cur_pages);
2394
2395 return 0;
2396}
2397
2398static void io_mem_free(void *ptr)
2399{
52e04ef4
MR
2400 struct page *page;
2401
2402 if (!ptr)
2403 return;
2b188cc1 2404
52e04ef4 2405 page = virt_to_head_page(ptr);
2b188cc1
JA
2406 if (put_page_testzero(page))
2407 free_compound_page(page);
2408}
2409
2410static void *io_mem_alloc(size_t size)
2411{
2412 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
2413 __GFP_NORETRY;
2414
2415 return (void *) __get_free_pages(gfp_flags, get_order(size));
2416}
2417
2418static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
2419{
2420 struct io_sq_ring *sq_ring;
2421 struct io_cq_ring *cq_ring;
2422 size_t bytes;
2423
2424 bytes = struct_size(sq_ring, array, sq_entries);
2425 bytes += array_size(sizeof(struct io_uring_sqe), sq_entries);
2426 bytes += struct_size(cq_ring, cqes, cq_entries);
2427
2428 return (bytes + PAGE_SIZE - 1) / PAGE_SIZE;
2429}
2430
edafccee
JA
2431static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
2432{
2433 int i, j;
2434
2435 if (!ctx->user_bufs)
2436 return -ENXIO;
2437
2438 for (i = 0; i < ctx->nr_user_bufs; i++) {
2439 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
2440
2441 for (j = 0; j < imu->nr_bvecs; j++)
2442 put_page(imu->bvec[j].bv_page);
2443
2444 if (ctx->account_mem)
2445 io_unaccount_mem(ctx->user, imu->nr_bvecs);
d4ef6475 2446 kvfree(imu->bvec);
edafccee
JA
2447 imu->nr_bvecs = 0;
2448 }
2449
2450 kfree(ctx->user_bufs);
2451 ctx->user_bufs = NULL;
2452 ctx->nr_user_bufs = 0;
2453 return 0;
2454}
2455
2456static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
2457 void __user *arg, unsigned index)
2458{
2459 struct iovec __user *src;
2460
2461#ifdef CONFIG_COMPAT
2462 if (ctx->compat) {
2463 struct compat_iovec __user *ciovs;
2464 struct compat_iovec ciov;
2465
2466 ciovs = (struct compat_iovec __user *) arg;
2467 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
2468 return -EFAULT;
2469
2470 dst->iov_base = (void __user *) (unsigned long) ciov.iov_base;
2471 dst->iov_len = ciov.iov_len;
2472 return 0;
2473 }
2474#endif
2475 src = (struct iovec __user *) arg;
2476 if (copy_from_user(dst, &src[index], sizeof(*dst)))
2477 return -EFAULT;
2478 return 0;
2479}
2480
2481static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
2482 unsigned nr_args)
2483{
2484 struct vm_area_struct **vmas = NULL;
2485 struct page **pages = NULL;
2486 int i, j, got_pages = 0;
2487 int ret = -EINVAL;
2488
2489 if (ctx->user_bufs)
2490 return -EBUSY;
2491 if (!nr_args || nr_args > UIO_MAXIOV)
2492 return -EINVAL;
2493
2494 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
2495 GFP_KERNEL);
2496 if (!ctx->user_bufs)
2497 return -ENOMEM;
2498
2499 for (i = 0; i < nr_args; i++) {
2500 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
2501 unsigned long off, start, end, ubuf;
2502 int pret, nr_pages;
2503 struct iovec iov;
2504 size_t size;
2505
2506 ret = io_copy_iov(ctx, &iov, arg, i);
2507 if (ret)
fd670f49 2508 goto err;
edafccee
JA
2509
2510 /*
2511 * Don't impose further limits on the size and buffer
2512 * constraints here, we'll -EINVAL later when IO is
2513 * submitted if they are wrong.
2514 */
2515 ret = -EFAULT;
2516 if (!iov.iov_base || !iov.iov_len)
2517 goto err;
2518
2519 /* arbitrary limit, but we need something */
2520 if (iov.iov_len > SZ_1G)
2521 goto err;
2522
2523 ubuf = (unsigned long) iov.iov_base;
2524 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
2525 start = ubuf >> PAGE_SHIFT;
2526 nr_pages = end - start;
2527
2528 if (ctx->account_mem) {
2529 ret = io_account_mem(ctx->user, nr_pages);
2530 if (ret)
2531 goto err;
2532 }
2533
2534 ret = 0;
2535 if (!pages || nr_pages > got_pages) {
2536 kfree(vmas);
2537 kfree(pages);
d4ef6475 2538 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
edafccee 2539 GFP_KERNEL);
d4ef6475 2540 vmas = kvmalloc_array(nr_pages,
edafccee
JA
2541 sizeof(struct vm_area_struct *),
2542 GFP_KERNEL);
2543 if (!pages || !vmas) {
2544 ret = -ENOMEM;
2545 if (ctx->account_mem)
2546 io_unaccount_mem(ctx->user, nr_pages);
2547 goto err;
2548 }
2549 got_pages = nr_pages;
2550 }
2551
d4ef6475 2552 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
edafccee
JA
2553 GFP_KERNEL);
2554 ret = -ENOMEM;
2555 if (!imu->bvec) {
2556 if (ctx->account_mem)
2557 io_unaccount_mem(ctx->user, nr_pages);
2558 goto err;
2559 }
2560
2561 ret = 0;
2562 down_read(&current->mm->mmap_sem);
2563 pret = get_user_pages_longterm(ubuf, nr_pages, FOLL_WRITE,
2564 pages, vmas);
2565 if (pret == nr_pages) {
2566 /* don't support file backed memory */
2567 for (j = 0; j < nr_pages; j++) {
2568 struct vm_area_struct *vma = vmas[j];
2569
2570 if (vma->vm_file &&
2571 !is_file_hugepages(vma->vm_file)) {
2572 ret = -EOPNOTSUPP;
2573 break;
2574 }
2575 }
2576 } else {
2577 ret = pret < 0 ? pret : -EFAULT;
2578 }
2579 up_read(&current->mm->mmap_sem);
2580 if (ret) {
2581 /*
2582 * if we did partial map, or found file backed vmas,
2583 * release any pages we did get
2584 */
2585 if (pret > 0) {
2586 for (j = 0; j < pret; j++)
2587 put_page(pages[j]);
2588 }
2589 if (ctx->account_mem)
2590 io_unaccount_mem(ctx->user, nr_pages);
d4ef6475 2591 kvfree(imu->bvec);
edafccee
JA
2592 goto err;
2593 }
2594
2595 off = ubuf & ~PAGE_MASK;
2596 size = iov.iov_len;
2597 for (j = 0; j < nr_pages; j++) {
2598 size_t vec_len;
2599
2600 vec_len = min_t(size_t, size, PAGE_SIZE - off);
2601 imu->bvec[j].bv_page = pages[j];
2602 imu->bvec[j].bv_len = vec_len;
2603 imu->bvec[j].bv_offset = off;
2604 off = 0;
2605 size -= vec_len;
2606 }
2607 /* store original address for later verification */
2608 imu->ubuf = ubuf;
2609 imu->len = iov.iov_len;
2610 imu->nr_bvecs = nr_pages;
2611
2612 ctx->nr_user_bufs++;
2613 }
d4ef6475
MR
2614 kvfree(pages);
2615 kvfree(vmas);
edafccee
JA
2616 return 0;
2617err:
d4ef6475
MR
2618 kvfree(pages);
2619 kvfree(vmas);
edafccee
JA
2620 io_sqe_buffer_unregister(ctx);
2621 return ret;
2622}
2623
2b188cc1
JA
2624static void io_ring_ctx_free(struct io_ring_ctx *ctx)
2625{
6b06314c 2626 io_finish_async(ctx);
2b188cc1
JA
2627 if (ctx->sqo_mm)
2628 mmdrop(ctx->sqo_mm);
def596e9
JA
2629
2630 io_iopoll_reap_events(ctx);
edafccee 2631 io_sqe_buffer_unregister(ctx);
6b06314c 2632 io_sqe_files_unregister(ctx);
def596e9 2633
2b188cc1 2634#if defined(CONFIG_UNIX)
3d61202e
EB
2635 if (ctx->ring_sock) {
2636 ctx->ring_sock->file = NULL; /* so that iput() is called */
2b188cc1 2637 sock_release(ctx->ring_sock);
3d61202e 2638 }
2b188cc1
JA
2639#endif
2640
2641 io_mem_free(ctx->sq_ring);
2642 io_mem_free(ctx->sq_sqes);
2643 io_mem_free(ctx->cq_ring);
2644
2645 percpu_ref_exit(&ctx->refs);
2646 if (ctx->account_mem)
2647 io_unaccount_mem(ctx->user,
2648 ring_pages(ctx->sq_entries, ctx->cq_entries));
2649 free_uid(ctx->user);
2650 kfree(ctx);
2651}
2652
2653static __poll_t io_uring_poll(struct file *file, poll_table *wait)
2654{
2655 struct io_ring_ctx *ctx = file->private_data;
2656 __poll_t mask = 0;
2657
2658 poll_wait(file, &ctx->cq_wait, wait);
4f7067c3
SB
2659 /*
2660 * synchronizes with barrier from wq_has_sleeper call in
2661 * io_commit_cqring
2662 */
2b188cc1 2663 smp_rmb();
fb775faa
SB
2664 if (READ_ONCE(ctx->sq_ring->r.tail) - ctx->cached_sq_head !=
2665 ctx->sq_ring->ring_entries)
2b188cc1
JA
2666 mask |= EPOLLOUT | EPOLLWRNORM;
2667 if (READ_ONCE(ctx->cq_ring->r.head) != ctx->cached_cq_tail)
2668 mask |= EPOLLIN | EPOLLRDNORM;
2669
2670 return mask;
2671}
2672
2673static int io_uring_fasync(int fd, struct file *file, int on)
2674{
2675 struct io_ring_ctx *ctx = file->private_data;
2676
2677 return fasync_helper(fd, file, on, &ctx->cq_fasync);
2678}
2679
2680static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
2681{
2682 mutex_lock(&ctx->uring_lock);
2683 percpu_ref_kill(&ctx->refs);
2684 mutex_unlock(&ctx->uring_lock);
2685
221c5eb2 2686 io_poll_remove_all(ctx);
def596e9 2687 io_iopoll_reap_events(ctx);
2b188cc1
JA
2688 wait_for_completion(&ctx->ctx_done);
2689 io_ring_ctx_free(ctx);
2690}
2691
2692static int io_uring_release(struct inode *inode, struct file *file)
2693{
2694 struct io_ring_ctx *ctx = file->private_data;
2695
2696 file->private_data = NULL;
2697 io_ring_ctx_wait_and_kill(ctx);
2698 return 0;
2699}
2700
2701static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
2702{
2703 loff_t offset = (loff_t) vma->vm_pgoff << PAGE_SHIFT;
2704 unsigned long sz = vma->vm_end - vma->vm_start;
2705 struct io_ring_ctx *ctx = file->private_data;
2706 unsigned long pfn;
2707 struct page *page;
2708 void *ptr;
2709
2710 switch (offset) {
2711 case IORING_OFF_SQ_RING:
2712 ptr = ctx->sq_ring;
2713 break;
2714 case IORING_OFF_SQES:
2715 ptr = ctx->sq_sqes;
2716 break;
2717 case IORING_OFF_CQ_RING:
2718 ptr = ctx->cq_ring;
2719 break;
2720 default:
2721 return -EINVAL;
2722 }
2723
2724 page = virt_to_head_page(ptr);
2725 if (sz > (PAGE_SIZE << compound_order(page)))
2726 return -EINVAL;
2727
2728 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
2729 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
2730}
2731
2732SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
2733 u32, min_complete, u32, flags, const sigset_t __user *, sig,
2734 size_t, sigsz)
2735{
2736 struct io_ring_ctx *ctx;
2737 long ret = -EBADF;
2738 int submitted = 0;
2739 struct fd f;
2740
6c271ce2 2741 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
2b188cc1
JA
2742 return -EINVAL;
2743
2744 f = fdget(fd);
2745 if (!f.file)
2746 return -EBADF;
2747
2748 ret = -EOPNOTSUPP;
2749 if (f.file->f_op != &io_uring_fops)
2750 goto out_fput;
2751
2752 ret = -ENXIO;
2753 ctx = f.file->private_data;
2754 if (!percpu_ref_tryget(&ctx->refs))
2755 goto out_fput;
2756
6c271ce2
JA
2757 /*
2758 * For SQ polling, the thread will do all submissions and completions.
2759 * Just return the requested submit count, and wake the thread if
2760 * we were asked to.
2761 */
2762 if (ctx->flags & IORING_SETUP_SQPOLL) {
2763 if (flags & IORING_ENTER_SQ_WAKEUP)
2764 wake_up(&ctx->sqo_wait);
2765 submitted = to_submit;
2766 goto out_ctx;
2767 }
2768
2b188cc1
JA
2769 ret = 0;
2770 if (to_submit) {
2771 to_submit = min(to_submit, ctx->sq_entries);
2772
2773 mutex_lock(&ctx->uring_lock);
2774 submitted = io_ring_submit(ctx, to_submit);
2775 mutex_unlock(&ctx->uring_lock);
2b188cc1
JA
2776 }
2777 if (flags & IORING_ENTER_GETEVENTS) {
def596e9
JA
2778 unsigned nr_events = 0;
2779
2b188cc1
JA
2780 min_complete = min(min_complete, ctx->cq_entries);
2781
def596e9
JA
2782 if (ctx->flags & IORING_SETUP_IOPOLL) {
2783 mutex_lock(&ctx->uring_lock);
2784 ret = io_iopoll_check(ctx, &nr_events, min_complete);
2785 mutex_unlock(&ctx->uring_lock);
2786 } else {
2787 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
2788 }
2b188cc1
JA
2789 }
2790
2791out_ctx:
2792 io_ring_drop_ctx_refs(ctx, 1);
2793out_fput:
2794 fdput(f);
2795 return submitted ? submitted : ret;
2796}
2797
2798static const struct file_operations io_uring_fops = {
2799 .release = io_uring_release,
2800 .mmap = io_uring_mmap,
2801 .poll = io_uring_poll,
2802 .fasync = io_uring_fasync,
2803};
2804
2805static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
2806 struct io_uring_params *p)
2807{
2808 struct io_sq_ring *sq_ring;
2809 struct io_cq_ring *cq_ring;
2810 size_t size;
2811
2812 sq_ring = io_mem_alloc(struct_size(sq_ring, array, p->sq_entries));
2813 if (!sq_ring)
2814 return -ENOMEM;
2815
2816 ctx->sq_ring = sq_ring;
2817 sq_ring->ring_mask = p->sq_entries - 1;
2818 sq_ring->ring_entries = p->sq_entries;
2819 ctx->sq_mask = sq_ring->ring_mask;
2820 ctx->sq_entries = sq_ring->ring_entries;
2821
2822 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
2823 if (size == SIZE_MAX)
2824 return -EOVERFLOW;
2825
2826 ctx->sq_sqes = io_mem_alloc(size);
52e04ef4 2827 if (!ctx->sq_sqes)
2b188cc1 2828 return -ENOMEM;
2b188cc1
JA
2829
2830 cq_ring = io_mem_alloc(struct_size(cq_ring, cqes, p->cq_entries));
52e04ef4 2831 if (!cq_ring)
2b188cc1 2832 return -ENOMEM;
2b188cc1
JA
2833
2834 ctx->cq_ring = cq_ring;
2835 cq_ring->ring_mask = p->cq_entries - 1;
2836 cq_ring->ring_entries = p->cq_entries;
2837 ctx->cq_mask = cq_ring->ring_mask;
2838 ctx->cq_entries = cq_ring->ring_entries;
2839 return 0;
2840}
2841
2842/*
2843 * Allocate an anonymous fd, this is what constitutes the application
2844 * visible backing of an io_uring instance. The application mmaps this
2845 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
2846 * we have to tie this fd to a socket for file garbage collection purposes.
2847 */
2848static int io_uring_get_fd(struct io_ring_ctx *ctx)
2849{
2850 struct file *file;
2851 int ret;
2852
2853#if defined(CONFIG_UNIX)
2854 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
2855 &ctx->ring_sock);
2856 if (ret)
2857 return ret;
2858#endif
2859
2860 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
2861 if (ret < 0)
2862 goto err;
2863
2864 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
2865 O_RDWR | O_CLOEXEC);
2866 if (IS_ERR(file)) {
2867 put_unused_fd(ret);
2868 ret = PTR_ERR(file);
2869 goto err;
2870 }
2871
2872#if defined(CONFIG_UNIX)
2873 ctx->ring_sock->file = file;
6b06314c 2874 ctx->ring_sock->sk->sk_user_data = ctx;
2b188cc1
JA
2875#endif
2876 fd_install(ret, file);
2877 return ret;
2878err:
2879#if defined(CONFIG_UNIX)
2880 sock_release(ctx->ring_sock);
2881 ctx->ring_sock = NULL;
2882#endif
2883 return ret;
2884}
2885
2886static int io_uring_create(unsigned entries, struct io_uring_params *p)
2887{
2888 struct user_struct *user = NULL;
2889 struct io_ring_ctx *ctx;
2890 bool account_mem;
2891 int ret;
2892
2893 if (!entries || entries > IORING_MAX_ENTRIES)
2894 return -EINVAL;
2895
2896 /*
2897 * Use twice as many entries for the CQ ring. It's possible for the
2898 * application to drive a higher depth than the size of the SQ ring,
2899 * since the sqes are only used at submission time. This allows for
2900 * some flexibility in overcommitting a bit.
2901 */
2902 p->sq_entries = roundup_pow_of_two(entries);
2903 p->cq_entries = 2 * p->sq_entries;
2904
2905 user = get_uid(current_user());
2906 account_mem = !capable(CAP_IPC_LOCK);
2907
2908 if (account_mem) {
2909 ret = io_account_mem(user,
2910 ring_pages(p->sq_entries, p->cq_entries));
2911 if (ret) {
2912 free_uid(user);
2913 return ret;
2914 }
2915 }
2916
2917 ctx = io_ring_ctx_alloc(p);
2918 if (!ctx) {
2919 if (account_mem)
2920 io_unaccount_mem(user, ring_pages(p->sq_entries,
2921 p->cq_entries));
2922 free_uid(user);
2923 return -ENOMEM;
2924 }
2925 ctx->compat = in_compat_syscall();
2926 ctx->account_mem = account_mem;
2927 ctx->user = user;
2928
2929 ret = io_allocate_scq_urings(ctx, p);
2930 if (ret)
2931 goto err;
2932
6c271ce2 2933 ret = io_sq_offload_start(ctx, p);
2b188cc1
JA
2934 if (ret)
2935 goto err;
2936
2937 ret = io_uring_get_fd(ctx);
2938 if (ret < 0)
2939 goto err;
2940
2941 memset(&p->sq_off, 0, sizeof(p->sq_off));
2942 p->sq_off.head = offsetof(struct io_sq_ring, r.head);
2943 p->sq_off.tail = offsetof(struct io_sq_ring, r.tail);
2944 p->sq_off.ring_mask = offsetof(struct io_sq_ring, ring_mask);
2945 p->sq_off.ring_entries = offsetof(struct io_sq_ring, ring_entries);
2946 p->sq_off.flags = offsetof(struct io_sq_ring, flags);
2947 p->sq_off.dropped = offsetof(struct io_sq_ring, dropped);
2948 p->sq_off.array = offsetof(struct io_sq_ring, array);
2949
2950 memset(&p->cq_off, 0, sizeof(p->cq_off));
2951 p->cq_off.head = offsetof(struct io_cq_ring, r.head);
2952 p->cq_off.tail = offsetof(struct io_cq_ring, r.tail);
2953 p->cq_off.ring_mask = offsetof(struct io_cq_ring, ring_mask);
2954 p->cq_off.ring_entries = offsetof(struct io_cq_ring, ring_entries);
2955 p->cq_off.overflow = offsetof(struct io_cq_ring, overflow);
2956 p->cq_off.cqes = offsetof(struct io_cq_ring, cqes);
2957 return ret;
2958err:
2959 io_ring_ctx_wait_and_kill(ctx);
2960 return ret;
2961}
2962
2963/*
2964 * Sets up an aio uring context, and returns the fd. Applications asks for a
2965 * ring size, we return the actual sq/cq ring sizes (among other things) in the
2966 * params structure passed in.
2967 */
2968static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
2969{
2970 struct io_uring_params p;
2971 long ret;
2972 int i;
2973
2974 if (copy_from_user(&p, params, sizeof(p)))
2975 return -EFAULT;
2976 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
2977 if (p.resv[i])
2978 return -EINVAL;
2979 }
2980
6c271ce2
JA
2981 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
2982 IORING_SETUP_SQ_AFF))
2b188cc1
JA
2983 return -EINVAL;
2984
2985 ret = io_uring_create(entries, &p);
2986 if (ret < 0)
2987 return ret;
2988
2989 if (copy_to_user(params, &p, sizeof(p)))
2990 return -EFAULT;
2991
2992 return ret;
2993}
2994
2995SYSCALL_DEFINE2(io_uring_setup, u32, entries,
2996 struct io_uring_params __user *, params)
2997{
2998 return io_uring_setup(entries, params);
2999}
3000
edafccee
JA
3001static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
3002 void __user *arg, unsigned nr_args)
b19062a5
JA
3003 __releases(ctx->uring_lock)
3004 __acquires(ctx->uring_lock)
edafccee
JA
3005{
3006 int ret;
3007
35fa71a0
JA
3008 /*
3009 * We're inside the ring mutex, if the ref is already dying, then
3010 * someone else killed the ctx or is already going through
3011 * io_uring_register().
3012 */
3013 if (percpu_ref_is_dying(&ctx->refs))
3014 return -ENXIO;
3015
edafccee 3016 percpu_ref_kill(&ctx->refs);
b19062a5
JA
3017
3018 /*
3019 * Drop uring mutex before waiting for references to exit. If another
3020 * thread is currently inside io_uring_enter() it might need to grab
3021 * the uring_lock to make progress. If we hold it here across the drain
3022 * wait, then we can deadlock. It's safe to drop the mutex here, since
3023 * no new references will come in after we've killed the percpu ref.
3024 */
3025 mutex_unlock(&ctx->uring_lock);
edafccee 3026 wait_for_completion(&ctx->ctx_done);
b19062a5 3027 mutex_lock(&ctx->uring_lock);
edafccee
JA
3028
3029 switch (opcode) {
3030 case IORING_REGISTER_BUFFERS:
3031 ret = io_sqe_buffer_register(ctx, arg, nr_args);
3032 break;
3033 case IORING_UNREGISTER_BUFFERS:
3034 ret = -EINVAL;
3035 if (arg || nr_args)
3036 break;
3037 ret = io_sqe_buffer_unregister(ctx);
3038 break;
6b06314c
JA
3039 case IORING_REGISTER_FILES:
3040 ret = io_sqe_files_register(ctx, arg, nr_args);
3041 break;
3042 case IORING_UNREGISTER_FILES:
3043 ret = -EINVAL;
3044 if (arg || nr_args)
3045 break;
3046 ret = io_sqe_files_unregister(ctx);
3047 break;
edafccee
JA
3048 default:
3049 ret = -EINVAL;
3050 break;
3051 }
3052
3053 /* bring the ctx back to life */
3054 reinit_completion(&ctx->ctx_done);
3055 percpu_ref_reinit(&ctx->refs);
3056 return ret;
3057}
3058
3059SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
3060 void __user *, arg, unsigned int, nr_args)
3061{
3062 struct io_ring_ctx *ctx;
3063 long ret = -EBADF;
3064 struct fd f;
3065
3066 f = fdget(fd);
3067 if (!f.file)
3068 return -EBADF;
3069
3070 ret = -EOPNOTSUPP;
3071 if (f.file->f_op != &io_uring_fops)
3072 goto out_fput;
3073
3074 ctx = f.file->private_data;
3075
3076 mutex_lock(&ctx->uring_lock);
3077 ret = __io_uring_register(ctx, opcode, arg, nr_args);
3078 mutex_unlock(&ctx->uring_lock);
3079out_fput:
3080 fdput(f);
3081 return ret;
3082}
3083
2b188cc1
JA
3084static int __init io_uring_init(void)
3085{
3086 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
3087 return 0;
3088};
3089__initcall(io_uring_init);