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