io_uring: reduce/pack size of io_ring_ctx
[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>
6c271ce2 59#include <linux/kthread.h>
2b188cc1 60#include <linux/blkdev.h>
edafccee 61#include <linux/bvec.h>
2b188cc1
JA
62#include <linux/net.h>
63#include <net/sock.h>
64#include <net/af_unix.h>
6b06314c 65#include <net/scm.h>
2b188cc1
JA
66#include <linux/anon_inodes.h>
67#include <linux/sched/mm.h>
68#include <linux/uaccess.h>
69#include <linux/nospec.h>
edafccee
JA
70#include <linux/sizes.h>
71#include <linux/hugetlb.h>
2b188cc1 72
c826bd7a
DD
73#define CREATE_TRACE_POINTS
74#include <trace/events/io_uring.h>
75
2b188cc1
JA
76#include <uapi/linux/io_uring.h>
77
78#include "internal.h"
561fb04a 79#include "io-wq.h"
2b188cc1 80
5277deaa 81#define IORING_MAX_ENTRIES 32768
33a107f0 82#define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
65e19f54
JA
83
84/*
85 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
86 */
87#define IORING_FILE_TABLE_SHIFT 9
88#define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
89#define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
90#define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
2b188cc1
JA
91
92struct io_uring {
93 u32 head ____cacheline_aligned_in_smp;
94 u32 tail ____cacheline_aligned_in_smp;
95};
96
1e84b97b 97/*
75b28aff
HV
98 * This data is shared with the application through the mmap at offsets
99 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
1e84b97b
SB
100 *
101 * The offsets to the member fields are published through struct
102 * io_sqring_offsets when calling io_uring_setup.
103 */
75b28aff 104struct io_rings {
1e84b97b
SB
105 /*
106 * Head and tail offsets into the ring; the offsets need to be
107 * masked to get valid indices.
108 *
75b28aff
HV
109 * The kernel controls head of the sq ring and the tail of the cq ring,
110 * and the application controls tail of the sq ring and the head of the
111 * cq ring.
1e84b97b 112 */
75b28aff 113 struct io_uring sq, cq;
1e84b97b 114 /*
75b28aff 115 * Bitmasks to apply to head and tail offsets (constant, equals
1e84b97b
SB
116 * ring_entries - 1)
117 */
75b28aff
HV
118 u32 sq_ring_mask, cq_ring_mask;
119 /* Ring sizes (constant, power of 2) */
120 u32 sq_ring_entries, cq_ring_entries;
1e84b97b
SB
121 /*
122 * Number of invalid entries dropped by the kernel due to
123 * invalid index stored in array
124 *
125 * Written by the kernel, shouldn't be modified by the
126 * application (i.e. get number of "new events" by comparing to
127 * cached value).
128 *
129 * After a new SQ head value was read by the application this
130 * counter includes all submissions that were dropped reaching
131 * the new SQ head (and possibly more).
132 */
75b28aff 133 u32 sq_dropped;
1e84b97b
SB
134 /*
135 * Runtime flags
136 *
137 * Written by the kernel, shouldn't be modified by the
138 * application.
139 *
140 * The application needs a full memory barrier before checking
141 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
142 */
75b28aff 143 u32 sq_flags;
1e84b97b
SB
144 /*
145 * Number of completion events lost because the queue was full;
146 * this should be avoided by the application by making sure
147 * there are not more requests pending thatn there is space in
148 * the completion queue.
149 *
150 * Written by the kernel, shouldn't be modified by the
151 * application (i.e. get number of "new events" by comparing to
152 * cached value).
153 *
154 * As completion events come in out of order this counter is not
155 * ordered with any other data.
156 */
75b28aff 157 u32 cq_overflow;
1e84b97b
SB
158 /*
159 * Ring buffer of completion events.
160 *
161 * The kernel writes completion events fresh every time they are
162 * produced, so the application is allowed to modify pending
163 * entries.
164 */
75b28aff 165 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
2b188cc1
JA
166};
167
edafccee
JA
168struct io_mapped_ubuf {
169 u64 ubuf;
170 size_t len;
171 struct bio_vec *bvec;
172 unsigned int nr_bvecs;
173};
174
65e19f54
JA
175struct fixed_file_table {
176 struct file **files;
177};
178
2b188cc1
JA
179struct io_ring_ctx {
180 struct {
181 struct percpu_ref refs;
182 } ____cacheline_aligned_in_smp;
183
184 struct {
185 unsigned int flags;
186 bool compat;
187 bool account_mem;
1d7bb1d5 188 bool cq_overflow_flushed;
2b188cc1 189
75b28aff
HV
190 /*
191 * Ring buffer of indices into array of io_uring_sqe, which is
192 * mmapped by the application using the IORING_OFF_SQES offset.
193 *
194 * This indirection could e.g. be used to assign fixed
195 * io_uring_sqe entries to operations and only submit them to
196 * the queue when needed.
197 *
198 * The kernel modifies neither the indices array nor the entries
199 * array.
200 */
201 u32 *sq_array;
2b188cc1
JA
202 unsigned cached_sq_head;
203 unsigned sq_entries;
204 unsigned sq_mask;
6c271ce2 205 unsigned sq_thread_idle;
498ccd9e 206 unsigned cached_sq_dropped;
206aefde 207 atomic_t cached_cq_overflow;
2b188cc1 208 struct io_uring_sqe *sq_sqes;
de0617e4
JA
209
210 struct list_head defer_list;
5262f567 211 struct list_head timeout_list;
1d7bb1d5 212 struct list_head cq_overflow_list;
fcb323cc
JA
213
214 wait_queue_head_t inflight_wait;
2b188cc1
JA
215 } ____cacheline_aligned_in_smp;
216
206aefde
JA
217 struct io_rings *rings;
218
2b188cc1 219 /* IO offload */
561fb04a 220 struct io_wq *io_wq;
6c271ce2 221 struct task_struct *sqo_thread; /* if using sq thread polling */
2b188cc1 222 struct mm_struct *sqo_mm;
6c271ce2 223 wait_queue_head_t sqo_wait;
75b28aff 224
6b06314c
JA
225 /*
226 * If used, fixed file set. Writers must ensure that ->refs is dead,
227 * readers must ensure that ->refs is alive as long as the file* is
228 * used. Only updated through io_uring_register(2).
229 */
65e19f54 230 struct fixed_file_table *file_table;
6b06314c
JA
231 unsigned nr_user_files;
232
edafccee
JA
233 /* if used, fixed mapped user buffers */
234 unsigned nr_user_bufs;
235 struct io_mapped_ubuf *user_bufs;
236
2b188cc1
JA
237 struct user_struct *user;
238
206aefde
JA
239 /* 0 is for ctx quiesce/reinit/free, 1 is for sqo_thread started */
240 struct completion *completions;
241
242#if defined(CONFIG_UNIX)
243 struct socket *ring_sock;
244#endif
245
246 struct {
247 unsigned cached_cq_tail;
248 unsigned cq_entries;
249 unsigned cq_mask;
250 atomic_t cq_timeouts;
251 struct wait_queue_head cq_wait;
252 struct fasync_struct *cq_fasync;
253 struct eventfd_ctx *cq_ev_fd;
254 } ____cacheline_aligned_in_smp;
2b188cc1
JA
255
256 struct {
257 struct mutex uring_lock;
258 wait_queue_head_t wait;
259 } ____cacheline_aligned_in_smp;
260
261 struct {
262 spinlock_t completion_lock;
def596e9
JA
263 bool poll_multi_file;
264 /*
265 * ->poll_list is protected by the ctx->uring_lock for
266 * io_uring instances that don't use IORING_SETUP_SQPOLL.
267 * For SQPOLL, only the single threaded io_sq_thread() will
268 * manipulate the list, hence no extra locking is needed there.
269 */
270 struct list_head poll_list;
221c5eb2 271 struct list_head cancel_list;
fcb323cc
JA
272
273 spinlock_t inflight_lock;
274 struct list_head inflight_list;
2b188cc1 275 } ____cacheline_aligned_in_smp;
2b188cc1
JA
276};
277
278struct sqe_submit {
279 const struct io_uring_sqe *sqe;
fcb323cc
JA
280 struct file *ring_file;
281 int ring_fd;
8776f3fa 282 u32 sequence;
2b188cc1 283 bool has_user;
ba5290cc 284 bool in_async;
6c271ce2 285 bool needs_fixed_file;
2b188cc1
JA
286};
287
09bb8394
JA
288/*
289 * First field must be the file pointer in all the
290 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
291 */
221c5eb2
JA
292struct io_poll_iocb {
293 struct file *file;
294 struct wait_queue_head *head;
295 __poll_t events;
8c838788 296 bool done;
221c5eb2
JA
297 bool canceled;
298 struct wait_queue_entry wait;
299};
300
5262f567
JA
301struct io_timeout {
302 struct file *file;
303 struct hrtimer timer;
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;
5262f567 317 struct io_timeout timeout;
221c5eb2 318 };
2b188cc1
JA
319
320 struct sqe_submit submit;
321
322 struct io_ring_ctx *ctx;
323 struct list_head list;
9e645e11 324 struct list_head link_list;
2b188cc1 325 unsigned int flags;
c16361c1 326 refcount_t refs;
8449eeda 327#define REQ_F_NOWAIT 1 /* must not punt to workers */
def596e9 328#define REQ_F_IOPOLL_COMPLETED 2 /* polled IO has completed */
6b06314c 329#define REQ_F_FIXED_FILE 4 /* ctx owns file */
31b51510 330#define REQ_F_SEQ_PREV 8 /* sequential with previous */
e2033e33
SB
331#define REQ_F_IO_DRAIN 16 /* drain existing IO first */
332#define REQ_F_IO_DRAINED 32 /* drain done */
9e645e11 333#define REQ_F_LINK 64 /* linked sqes */
2665abfd 334#define REQ_F_LINK_TIMEOUT 128 /* has linked timeout */
f7b76ac9 335#define REQ_F_FAIL_LINK 256 /* fail rest of links */
4fe2c963 336#define REQ_F_SHADOW_DRAIN 512 /* link-drain shadow req */
5262f567 337#define REQ_F_TIMEOUT 1024 /* timeout request */
491381ce
JA
338#define REQ_F_ISREG 2048 /* regular file */
339#define REQ_F_MUST_PUNT 4096 /* must be punted even for NONBLOCK */
fcb323cc 340#define REQ_F_INFLIGHT 8192 /* on inflight list */
2b188cc1 341 u64 user_data;
9e645e11 342 u32 result;
de0617e4 343 u32 sequence;
2b188cc1 344
fcb323cc
JA
345 struct list_head inflight_entry;
346
561fb04a 347 struct io_wq_work work;
2b188cc1
JA
348};
349
350#define IO_PLUG_THRESHOLD 2
def596e9 351#define IO_IOPOLL_BATCH 8
2b188cc1 352
9a56a232
JA
353struct io_submit_state {
354 struct blk_plug plug;
355
2579f913
JA
356 /*
357 * io_kiocb alloc cache
358 */
359 void *reqs[IO_IOPOLL_BATCH];
360 unsigned int free_reqs;
361 unsigned int cur_req;
362
9a56a232
JA
363 /*
364 * File reference cache
365 */
366 struct file *file;
367 unsigned int fd;
368 unsigned int has_refs;
369 unsigned int used_refs;
370 unsigned int ios_left;
371};
372
561fb04a 373static void io_wq_submit_work(struct io_wq_work **workptr);
78e19bbe 374static void io_cqring_fill_event(struct io_kiocb *req, long res);
4fe2c963 375static void __io_free_req(struct io_kiocb *req);
2665abfd 376static void io_put_req(struct io_kiocb *req, struct io_kiocb **nxtptr);
78e19bbe 377static void io_double_put_req(struct io_kiocb *req);
de0617e4 378
2b188cc1
JA
379static struct kmem_cache *req_cachep;
380
381static const struct file_operations io_uring_fops;
382
383struct sock *io_uring_get_socket(struct file *file)
384{
385#if defined(CONFIG_UNIX)
386 if (file->f_op == &io_uring_fops) {
387 struct io_ring_ctx *ctx = file->private_data;
388
389 return ctx->ring_sock->sk;
390 }
391#endif
392 return NULL;
393}
394EXPORT_SYMBOL(io_uring_get_socket);
395
396static void io_ring_ctx_ref_free(struct percpu_ref *ref)
397{
398 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
399
206aefde 400 complete(&ctx->completions[0]);
2b188cc1
JA
401}
402
403static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
404{
405 struct io_ring_ctx *ctx;
406
407 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
408 if (!ctx)
409 return NULL;
410
206aefde
JA
411 ctx->completions = kmalloc(2 * sizeof(struct completion), GFP_KERNEL);
412 if (!ctx->completions)
413 goto err;
414
21482896 415 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
206aefde
JA
416 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
417 goto err;
2b188cc1
JA
418
419 ctx->flags = p->flags;
420 init_waitqueue_head(&ctx->cq_wait);
1d7bb1d5 421 INIT_LIST_HEAD(&ctx->cq_overflow_list);
206aefde
JA
422 init_completion(&ctx->completions[0]);
423 init_completion(&ctx->completions[1]);
2b188cc1
JA
424 mutex_init(&ctx->uring_lock);
425 init_waitqueue_head(&ctx->wait);
426 spin_lock_init(&ctx->completion_lock);
def596e9 427 INIT_LIST_HEAD(&ctx->poll_list);
221c5eb2 428 INIT_LIST_HEAD(&ctx->cancel_list);
de0617e4 429 INIT_LIST_HEAD(&ctx->defer_list);
5262f567 430 INIT_LIST_HEAD(&ctx->timeout_list);
fcb323cc
JA
431 init_waitqueue_head(&ctx->inflight_wait);
432 spin_lock_init(&ctx->inflight_lock);
433 INIT_LIST_HEAD(&ctx->inflight_list);
2b188cc1 434 return ctx;
206aefde
JA
435err:
436 kfree(ctx->completions);
437 kfree(ctx);
438 return NULL;
2b188cc1
JA
439}
440
7adf4eaf
JA
441static inline bool __io_sequence_defer(struct io_ring_ctx *ctx,
442 struct io_kiocb *req)
443{
498ccd9e
JA
444 return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
445 + atomic_read(&ctx->cached_cq_overflow);
7adf4eaf
JA
446}
447
de0617e4
JA
448static inline bool io_sequence_defer(struct io_ring_ctx *ctx,
449 struct io_kiocb *req)
450{
7adf4eaf 451 if ((req->flags & (REQ_F_IO_DRAIN|REQ_F_IO_DRAINED)) != REQ_F_IO_DRAIN)
de0617e4
JA
452 return false;
453
7adf4eaf 454 return __io_sequence_defer(ctx, req);
de0617e4
JA
455}
456
7adf4eaf 457static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
de0617e4
JA
458{
459 struct io_kiocb *req;
460
7adf4eaf
JA
461 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
462 if (req && !io_sequence_defer(ctx, req)) {
de0617e4
JA
463 list_del_init(&req->list);
464 return req;
465 }
466
467 return NULL;
468}
469
5262f567
JA
470static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
471{
7adf4eaf
JA
472 struct io_kiocb *req;
473
474 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
475 if (req && !__io_sequence_defer(ctx, req)) {
476 list_del_init(&req->list);
477 return req;
478 }
479
480 return NULL;
5262f567
JA
481}
482
de0617e4 483static void __io_commit_cqring(struct io_ring_ctx *ctx)
2b188cc1 484{
75b28aff 485 struct io_rings *rings = ctx->rings;
2b188cc1 486
75b28aff 487 if (ctx->cached_cq_tail != READ_ONCE(rings->cq.tail)) {
2b188cc1 488 /* order cqe stores with ring update */
75b28aff 489 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
2b188cc1 490
2b188cc1
JA
491 if (wq_has_sleeper(&ctx->cq_wait)) {
492 wake_up_interruptible(&ctx->cq_wait);
493 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
494 }
495 }
496}
497
561fb04a 498static inline bool io_sqe_needs_user(const struct io_uring_sqe *sqe)
18d9be1a 499{
561fb04a
JA
500 u8 opcode = READ_ONCE(sqe->opcode);
501
502 return !(opcode == IORING_OP_READ_FIXED ||
503 opcode == IORING_OP_WRITE_FIXED);
504}
505
506static inline bool io_prep_async_work(struct io_kiocb *req)
507{
508 bool do_hashed = false;
54a91f3b 509
6cc47d1d
JA
510 if (req->submit.sqe) {
511 switch (req->submit.sqe->opcode) {
512 case IORING_OP_WRITEV:
513 case IORING_OP_WRITE_FIXED:
561fb04a 514 do_hashed = true;
5f8fd2d3
JA
515 /* fall-through */
516 case IORING_OP_READV:
517 case IORING_OP_READ_FIXED:
518 case IORING_OP_SENDMSG:
519 case IORING_OP_RECVMSG:
520 case IORING_OP_ACCEPT:
521 case IORING_OP_POLL_ADD:
522 /*
523 * We know REQ_F_ISREG is not set on some of these
524 * opcodes, but this enables us to keep the check in
525 * just one place.
526 */
527 if (!(req->flags & REQ_F_ISREG))
528 req->work.flags |= IO_WQ_WORK_UNBOUND;
6cc47d1d
JA
529 break;
530 }
561fb04a
JA
531 if (io_sqe_needs_user(req->submit.sqe))
532 req->work.flags |= IO_WQ_WORK_NEEDS_USER;
54a91f3b
JA
533 }
534
561fb04a
JA
535 return do_hashed;
536}
537
538static inline void io_queue_async_work(struct io_ring_ctx *ctx,
539 struct io_kiocb *req)
540{
541 bool do_hashed = io_prep_async_work(req);
542
543 trace_io_uring_queue_async_work(ctx, do_hashed, req, &req->work,
544 req->flags);
545 if (!do_hashed) {
546 io_wq_enqueue(ctx->io_wq, &req->work);
547 } else {
548 io_wq_enqueue_hashed(ctx->io_wq, &req->work,
549 file_inode(req->file));
550 }
18d9be1a
JA
551}
552
5262f567
JA
553static void io_kill_timeout(struct io_kiocb *req)
554{
555 int ret;
556
557 ret = hrtimer_try_to_cancel(&req->timeout.timer);
558 if (ret != -1) {
559 atomic_inc(&req->ctx->cq_timeouts);
842f9612 560 list_del_init(&req->list);
78e19bbe
JA
561 io_cqring_fill_event(req, 0);
562 io_put_req(req, NULL);
5262f567
JA
563 }
564}
565
566static void io_kill_timeouts(struct io_ring_ctx *ctx)
567{
568 struct io_kiocb *req, *tmp;
569
570 spin_lock_irq(&ctx->completion_lock);
571 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
572 io_kill_timeout(req);
573 spin_unlock_irq(&ctx->completion_lock);
574}
575
de0617e4
JA
576static void io_commit_cqring(struct io_ring_ctx *ctx)
577{
578 struct io_kiocb *req;
579
5262f567
JA
580 while ((req = io_get_timeout_req(ctx)) != NULL)
581 io_kill_timeout(req);
582
de0617e4
JA
583 __io_commit_cqring(ctx);
584
585 while ((req = io_get_deferred_req(ctx)) != NULL) {
4fe2c963
JL
586 if (req->flags & REQ_F_SHADOW_DRAIN) {
587 /* Just for drain, free it. */
588 __io_free_req(req);
589 continue;
590 }
de0617e4 591 req->flags |= REQ_F_IO_DRAINED;
18d9be1a 592 io_queue_async_work(ctx, req);
de0617e4
JA
593 }
594}
595
2b188cc1
JA
596static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
597{
75b28aff 598 struct io_rings *rings = ctx->rings;
2b188cc1
JA
599 unsigned tail;
600
601 tail = ctx->cached_cq_tail;
115e12e5
SB
602 /*
603 * writes to the cq entry need to come after reading head; the
604 * control dependency is enough as we're using WRITE_ONCE to
605 * fill the cq entry
606 */
75b28aff 607 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
2b188cc1
JA
608 return NULL;
609
610 ctx->cached_cq_tail++;
75b28aff 611 return &rings->cqes[tail & ctx->cq_mask];
2b188cc1
JA
612}
613
1d7bb1d5
JA
614static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
615{
616 if (waitqueue_active(&ctx->wait))
617 wake_up(&ctx->wait);
618 if (waitqueue_active(&ctx->sqo_wait))
619 wake_up(&ctx->sqo_wait);
620 if (ctx->cq_ev_fd)
621 eventfd_signal(ctx->cq_ev_fd, 1);
622}
623
624static void io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
625{
626 struct io_rings *rings = ctx->rings;
627 struct io_uring_cqe *cqe;
628 struct io_kiocb *req;
629 unsigned long flags;
630 LIST_HEAD(list);
631
632 if (!force) {
633 if (list_empty_careful(&ctx->cq_overflow_list))
634 return;
635 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
636 rings->cq_ring_entries))
637 return;
638 }
639
640 spin_lock_irqsave(&ctx->completion_lock, flags);
641
642 /* if force is set, the ring is going away. always drop after that */
643 if (force)
644 ctx->cq_overflow_flushed = true;
645
646 while (!list_empty(&ctx->cq_overflow_list)) {
647 cqe = io_get_cqring(ctx);
648 if (!cqe && !force)
649 break;
650
651 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
652 list);
653 list_move(&req->list, &list);
654 if (cqe) {
655 WRITE_ONCE(cqe->user_data, req->user_data);
656 WRITE_ONCE(cqe->res, req->result);
657 WRITE_ONCE(cqe->flags, 0);
658 } else {
659 WRITE_ONCE(ctx->rings->cq_overflow,
660 atomic_inc_return(&ctx->cached_cq_overflow));
661 }
662 }
663
664 io_commit_cqring(ctx);
665 spin_unlock_irqrestore(&ctx->completion_lock, flags);
666 io_cqring_ev_posted(ctx);
667
668 while (!list_empty(&list)) {
669 req = list_first_entry(&list, struct io_kiocb, list);
670 list_del(&req->list);
671 io_put_req(req, NULL);
672 }
673}
674
78e19bbe 675static void io_cqring_fill_event(struct io_kiocb *req, long res)
2b188cc1 676{
78e19bbe 677 struct io_ring_ctx *ctx = req->ctx;
2b188cc1
JA
678 struct io_uring_cqe *cqe;
679
78e19bbe 680 trace_io_uring_complete(ctx, req->user_data, res);
51c3ff62 681
2b188cc1
JA
682 /*
683 * If we can't get a cq entry, userspace overflowed the
684 * submission (by quite a lot). Increment the overflow count in
685 * the ring.
686 */
687 cqe = io_get_cqring(ctx);
1d7bb1d5 688 if (likely(cqe)) {
78e19bbe 689 WRITE_ONCE(cqe->user_data, req->user_data);
2b188cc1 690 WRITE_ONCE(cqe->res, res);
c71ffb67 691 WRITE_ONCE(cqe->flags, 0);
1d7bb1d5 692 } else if (ctx->cq_overflow_flushed) {
498ccd9e
JA
693 WRITE_ONCE(ctx->rings->cq_overflow,
694 atomic_inc_return(&ctx->cached_cq_overflow));
1d7bb1d5
JA
695 } else {
696 refcount_inc(&req->refs);
697 req->result = res;
698 list_add_tail(&req->list, &ctx->cq_overflow_list);
2b188cc1
JA
699 }
700}
701
78e19bbe 702static void io_cqring_add_event(struct io_kiocb *req, long res)
2b188cc1 703{
78e19bbe 704 struct io_ring_ctx *ctx = req->ctx;
2b188cc1
JA
705 unsigned long flags;
706
707 spin_lock_irqsave(&ctx->completion_lock, flags);
78e19bbe 708 io_cqring_fill_event(req, res);
2b188cc1
JA
709 io_commit_cqring(ctx);
710 spin_unlock_irqrestore(&ctx->completion_lock, flags);
711
8c838788 712 io_cqring_ev_posted(ctx);
2b188cc1
JA
713}
714
2579f913
JA
715static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
716 struct io_submit_state *state)
2b188cc1 717{
fd6fab2c 718 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2b188cc1
JA
719 struct io_kiocb *req;
720
721 if (!percpu_ref_tryget(&ctx->refs))
722 return NULL;
723
2579f913 724 if (!state) {
fd6fab2c 725 req = kmem_cache_alloc(req_cachep, gfp);
2579f913
JA
726 if (unlikely(!req))
727 goto out;
728 } else if (!state->free_reqs) {
729 size_t sz;
730 int ret;
731
732 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
fd6fab2c
JA
733 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
734
735 /*
736 * Bulk alloc is all-or-nothing. If we fail to get a batch,
737 * retry single alloc to be on the safe side.
738 */
739 if (unlikely(ret <= 0)) {
740 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
741 if (!state->reqs[0])
742 goto out;
743 ret = 1;
744 }
2579f913
JA
745 state->free_reqs = ret - 1;
746 state->cur_req = 1;
747 req = state->reqs[0];
748 } else {
749 req = state->reqs[state->cur_req];
750 state->free_reqs--;
751 state->cur_req++;
2b188cc1
JA
752 }
753
60c112b0 754 req->file = NULL;
2579f913
JA
755 req->ctx = ctx;
756 req->flags = 0;
e65ef56d
JA
757 /* one is dropped after submission, the other at completion */
758 refcount_set(&req->refs, 2);
9e645e11 759 req->result = 0;
561fb04a 760 INIT_IO_WORK(&req->work, io_wq_submit_work);
2579f913
JA
761 return req;
762out:
6805b32e 763 percpu_ref_put(&ctx->refs);
2b188cc1
JA
764 return NULL;
765}
766
def596e9
JA
767static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
768{
769 if (*nr) {
770 kmem_cache_free_bulk(req_cachep, *nr, reqs);
6805b32e 771 percpu_ref_put_many(&ctx->refs, *nr);
def596e9
JA
772 *nr = 0;
773 }
774}
775
9e645e11 776static void __io_free_req(struct io_kiocb *req)
2b188cc1 777{
fcb323cc
JA
778 struct io_ring_ctx *ctx = req->ctx;
779
09bb8394
JA
780 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
781 fput(req->file);
fcb323cc
JA
782 if (req->flags & REQ_F_INFLIGHT) {
783 unsigned long flags;
784
785 spin_lock_irqsave(&ctx->inflight_lock, flags);
786 list_del(&req->inflight_entry);
787 if (waitqueue_active(&ctx->inflight_wait))
788 wake_up(&ctx->inflight_wait);
789 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
790 }
791 percpu_ref_put(&ctx->refs);
e65ef56d
JA
792 kmem_cache_free(req_cachep, req);
793}
794
2665abfd
JA
795static bool io_link_cancel_timeout(struct io_ring_ctx *ctx,
796 struct io_kiocb *req)
797{
798 int ret;
799
800 ret = hrtimer_try_to_cancel(&req->timeout.timer);
801 if (ret != -1) {
78e19bbe 802 io_cqring_fill_event(req, -ECANCELED);
2665abfd
JA
803 io_commit_cqring(ctx);
804 req->flags &= ~REQ_F_LINK;
78e19bbe 805 io_put_req(req, NULL);
2665abfd
JA
806 return true;
807 }
808
809 return false;
810}
811
ba816ad6 812static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
9e645e11 813{
2665abfd 814 struct io_ring_ctx *ctx = req->ctx;
9e645e11 815 struct io_kiocb *nxt;
2665abfd 816 bool wake_ev = false;
9e645e11
JA
817
818 /*
819 * The list should never be empty when we are called here. But could
820 * potentially happen if the chain is messed up, check to be on the
821 * safe side.
822 */
823 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb, list);
2665abfd 824 while (nxt) {
9e645e11
JA
825 list_del(&nxt->list);
826 if (!list_empty(&req->link_list)) {
827 INIT_LIST_HEAD(&nxt->link_list);
828 list_splice(&req->link_list, &nxt->link_list);
829 nxt->flags |= REQ_F_LINK;
830 }
831
ba816ad6
JA
832 /*
833 * If we're in async work, we can continue processing the chain
834 * in this context instead of having to queue up new async work.
835 */
2665abfd
JA
836 if (req->flags & REQ_F_LINK_TIMEOUT) {
837 wake_ev = io_link_cancel_timeout(ctx, nxt);
838
839 /* we dropped this link, get next */
840 nxt = list_first_entry_or_null(&req->link_list,
841 struct io_kiocb, list);
842 } else if (nxtptr && current_work()) {
ba816ad6 843 *nxtptr = nxt;
2665abfd
JA
844 break;
845 } else {
ba816ad6 846 io_queue_async_work(req->ctx, nxt);
2665abfd
JA
847 break;
848 }
9e645e11 849 }
2665abfd
JA
850
851 if (wake_ev)
852 io_cqring_ev_posted(ctx);
9e645e11
JA
853}
854
855/*
856 * Called if REQ_F_LINK is set, and we fail the head request
857 */
858static void io_fail_links(struct io_kiocb *req)
859{
2665abfd 860 struct io_ring_ctx *ctx = req->ctx;
9e645e11 861 struct io_kiocb *link;
2665abfd
JA
862 unsigned long flags;
863
864 spin_lock_irqsave(&ctx->completion_lock, flags);
9e645e11
JA
865
866 while (!list_empty(&req->link_list)) {
867 link = list_first_entry(&req->link_list, struct io_kiocb, list);
2665abfd 868 list_del_init(&link->list);
9e645e11 869
c826bd7a 870 trace_io_uring_fail_link(req, link);
2665abfd
JA
871
872 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
873 link->submit.sqe->opcode == IORING_OP_LINK_TIMEOUT) {
874 io_link_cancel_timeout(ctx, link);
875 } else {
78e19bbe
JA
876 io_cqring_fill_event(link, -ECANCELED);
877 io_double_put_req(link);
2665abfd 878 }
9e645e11 879 }
2665abfd
JA
880
881 io_commit_cqring(ctx);
882 spin_unlock_irqrestore(&ctx->completion_lock, flags);
883 io_cqring_ev_posted(ctx);
9e645e11
JA
884}
885
ba816ad6 886static void io_free_req(struct io_kiocb *req, struct io_kiocb **nxt)
9e645e11 887{
2665abfd
JA
888 if (likely(!(req->flags & REQ_F_LINK))) {
889 __io_free_req(req);
890 return;
891 }
892
9e645e11
JA
893 /*
894 * If LINK is set, we have dependent requests in this chain. If we
895 * didn't fail this request, queue the first one up, moving any other
896 * dependencies to the next request. In case of failure, fail the rest
897 * of the chain.
898 */
2665abfd
JA
899 if (req->flags & REQ_F_FAIL_LINK) {
900 io_fail_links(req);
901 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
902 struct io_ring_ctx *ctx = req->ctx;
903 unsigned long flags;
904
905 /*
906 * If this is a timeout link, we could be racing with the
907 * timeout timer. Grab the completion lock for this case to
908 * protection against that.
909 */
910 spin_lock_irqsave(&ctx->completion_lock, flags);
911 io_req_link_next(req, nxt);
912 spin_unlock_irqrestore(&ctx->completion_lock, flags);
913 } else {
914 io_req_link_next(req, nxt);
9e645e11
JA
915 }
916
917 __io_free_req(req);
918}
919
ba816ad6
JA
920/*
921 * Drop reference to request, return next in chain (if there is one) if this
922 * was the last reference to this request.
923 */
924static struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
e65ef56d 925{
ba816ad6
JA
926 struct io_kiocb *nxt = NULL;
927
e65ef56d 928 if (refcount_dec_and_test(&req->refs))
ba816ad6
JA
929 io_free_req(req, &nxt);
930
931 return nxt;
932}
933
934static void io_put_req(struct io_kiocb *req, struct io_kiocb **nxtptr)
935{
936 struct io_kiocb *nxt;
937
938 nxt = io_put_req_find_next(req);
939 if (nxt) {
561fb04a 940 if (nxtptr)
ba816ad6 941 *nxtptr = nxt;
561fb04a 942 else
ba816ad6 943 io_queue_async_work(nxt->ctx, nxt);
ba816ad6 944 }
2b188cc1
JA
945}
946
78e19bbe
JA
947static void io_double_put_req(struct io_kiocb *req)
948{
949 /* drop both submit and complete references */
950 if (refcount_sub_and_test(2, &req->refs))
951 __io_free_req(req);
952}
953
1d7bb1d5 954static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
a3a0e43f 955{
84f97dc2
JA
956 struct io_rings *rings = ctx->rings;
957
1d7bb1d5
JA
958 /*
959 * noflush == true is from the waitqueue handler, just ensure we wake
960 * up the task, and the next invocation will flush the entries. We
961 * cannot safely to it from here.
962 */
963 if (noflush && !list_empty(&ctx->cq_overflow_list))
964 return -1U;
965
966 io_cqring_overflow_flush(ctx, false);
967
a3a0e43f
JA
968 /* See comment at the top of this file */
969 smp_rmb();
75b28aff 970 return READ_ONCE(rings->cq.tail) - READ_ONCE(rings->cq.head);
a3a0e43f
JA
971}
972
fb5ccc98
PB
973static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
974{
975 struct io_rings *rings = ctx->rings;
976
977 /* make sure SQ entry isn't read before tail */
978 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
979}
980
def596e9
JA
981/*
982 * Find and free completed poll iocbs
983 */
984static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
985 struct list_head *done)
986{
987 void *reqs[IO_IOPOLL_BATCH];
988 struct io_kiocb *req;
09bb8394 989 int to_free;
def596e9 990
09bb8394 991 to_free = 0;
def596e9
JA
992 while (!list_empty(done)) {
993 req = list_first_entry(done, struct io_kiocb, list);
994 list_del(&req->list);
995
78e19bbe 996 io_cqring_fill_event(req, req->result);
def596e9
JA
997 (*nr_events)++;
998
09bb8394
JA
999 if (refcount_dec_and_test(&req->refs)) {
1000 /* If we're not using fixed files, we have to pair the
1001 * completion part with the file put. Use regular
1002 * completions for those, only batch free for fixed
9e645e11 1003 * file and non-linked commands.
09bb8394 1004 */
9e645e11
JA
1005 if ((req->flags & (REQ_F_FIXED_FILE|REQ_F_LINK)) ==
1006 REQ_F_FIXED_FILE) {
09bb8394
JA
1007 reqs[to_free++] = req;
1008 if (to_free == ARRAY_SIZE(reqs))
1009 io_free_req_many(ctx, reqs, &to_free);
6b06314c 1010 } else {
ba816ad6 1011 io_free_req(req, NULL);
6b06314c 1012 }
9a56a232 1013 }
def596e9 1014 }
def596e9 1015
09bb8394 1016 io_commit_cqring(ctx);
def596e9
JA
1017 io_free_req_many(ctx, reqs, &to_free);
1018}
1019
1020static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1021 long min)
1022{
1023 struct io_kiocb *req, *tmp;
1024 LIST_HEAD(done);
1025 bool spin;
1026 int ret;
1027
1028 /*
1029 * Only spin for completions if we don't have multiple devices hanging
1030 * off our complete list, and we're under the requested amount.
1031 */
1032 spin = !ctx->poll_multi_file && *nr_events < min;
1033
1034 ret = 0;
1035 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1036 struct kiocb *kiocb = &req->rw;
1037
1038 /*
1039 * Move completed entries to our local list. If we find a
1040 * request that requires polling, break out and complete
1041 * the done list first, if we have entries there.
1042 */
1043 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
1044 list_move_tail(&req->list, &done);
1045 continue;
1046 }
1047 if (!list_empty(&done))
1048 break;
1049
1050 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1051 if (ret < 0)
1052 break;
1053
1054 if (ret && spin)
1055 spin = false;
1056 ret = 0;
1057 }
1058
1059 if (!list_empty(&done))
1060 io_iopoll_complete(ctx, nr_events, &done);
1061
1062 return ret;
1063}
1064
1065/*
1066 * Poll for a mininum of 'min' events. Note that if min == 0 we consider that a
1067 * non-spinning poll check - we'll still enter the driver poll loop, but only
1068 * as a non-spinning completion check.
1069 */
1070static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1071 long min)
1072{
08f5439f 1073 while (!list_empty(&ctx->poll_list) && !need_resched()) {
def596e9
JA
1074 int ret;
1075
1076 ret = io_do_iopoll(ctx, nr_events, min);
1077 if (ret < 0)
1078 return ret;
1079 if (!min || *nr_events >= min)
1080 return 0;
1081 }
1082
1083 return 1;
1084}
1085
1086/*
1087 * We can't just wait for polled events to come to us, we have to actively
1088 * find and complete them.
1089 */
1090static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1091{
1092 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1093 return;
1094
1095 mutex_lock(&ctx->uring_lock);
1096 while (!list_empty(&ctx->poll_list)) {
1097 unsigned int nr_events = 0;
1098
1099 io_iopoll_getevents(ctx, &nr_events, 1);
08f5439f
JA
1100
1101 /*
1102 * Ensure we allow local-to-the-cpu processing to take place,
1103 * in this case we need to ensure that we reap all events.
1104 */
1105 cond_resched();
def596e9
JA
1106 }
1107 mutex_unlock(&ctx->uring_lock);
1108}
1109
2b2ed975
JA
1110static int __io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1111 long min)
def596e9 1112{
2b2ed975 1113 int iters = 0, ret = 0;
500f9fba 1114
def596e9
JA
1115 do {
1116 int tmin = 0;
1117
a3a0e43f
JA
1118 /*
1119 * Don't enter poll loop if we already have events pending.
1120 * If we do, we can potentially be spinning for commands that
1121 * already triggered a CQE (eg in error).
1122 */
1d7bb1d5 1123 if (io_cqring_events(ctx, false))
a3a0e43f
JA
1124 break;
1125
500f9fba
JA
1126 /*
1127 * If a submit got punted to a workqueue, we can have the
1128 * application entering polling for a command before it gets
1129 * issued. That app will hold the uring_lock for the duration
1130 * of the poll right here, so we need to take a breather every
1131 * now and then to ensure that the issue has a chance to add
1132 * the poll to the issued list. Otherwise we can spin here
1133 * forever, while the workqueue is stuck trying to acquire the
1134 * very same mutex.
1135 */
1136 if (!(++iters & 7)) {
1137 mutex_unlock(&ctx->uring_lock);
1138 mutex_lock(&ctx->uring_lock);
1139 }
1140
def596e9
JA
1141 if (*nr_events < min)
1142 tmin = min - *nr_events;
1143
1144 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1145 if (ret <= 0)
1146 break;
1147 ret = 0;
1148 } while (min && !*nr_events && !need_resched());
1149
2b2ed975
JA
1150 return ret;
1151}
1152
1153static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1154 long min)
1155{
1156 int ret;
1157
1158 /*
1159 * We disallow the app entering submit/complete with polling, but we
1160 * still need to lock the ring to prevent racing with polled issue
1161 * that got punted to a workqueue.
1162 */
1163 mutex_lock(&ctx->uring_lock);
1164 ret = __io_iopoll_check(ctx, nr_events, min);
500f9fba 1165 mutex_unlock(&ctx->uring_lock);
def596e9
JA
1166 return ret;
1167}
1168
491381ce 1169static void kiocb_end_write(struct io_kiocb *req)
2b188cc1 1170{
491381ce
JA
1171 /*
1172 * Tell lockdep we inherited freeze protection from submission
1173 * thread.
1174 */
1175 if (req->flags & REQ_F_ISREG) {
1176 struct inode *inode = file_inode(req->file);
2b188cc1 1177
491381ce 1178 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2b188cc1 1179 }
491381ce 1180 file_end_write(req->file);
2b188cc1
JA
1181}
1182
ba816ad6 1183static void io_complete_rw_common(struct kiocb *kiocb, long res)
2b188cc1
JA
1184{
1185 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1186
491381ce
JA
1187 if (kiocb->ki_flags & IOCB_WRITE)
1188 kiocb_end_write(req);
2b188cc1 1189
9e645e11
JA
1190 if ((req->flags & REQ_F_LINK) && res != req->result)
1191 req->flags |= REQ_F_FAIL_LINK;
78e19bbe 1192 io_cqring_add_event(req, res);
ba816ad6
JA
1193}
1194
1195static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1196{
1197 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1198
1199 io_complete_rw_common(kiocb, res);
1200 io_put_req(req, NULL);
1201}
1202
1203static struct io_kiocb *__io_complete_rw(struct kiocb *kiocb, long res)
1204{
1205 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1206
1207 io_complete_rw_common(kiocb, res);
1208 return io_put_req_find_next(req);
2b188cc1
JA
1209}
1210
def596e9
JA
1211static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1212{
1213 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1214
491381ce
JA
1215 if (kiocb->ki_flags & IOCB_WRITE)
1216 kiocb_end_write(req);
def596e9 1217
9e645e11
JA
1218 if ((req->flags & REQ_F_LINK) && res != req->result)
1219 req->flags |= REQ_F_FAIL_LINK;
1220 req->result = res;
def596e9
JA
1221 if (res != -EAGAIN)
1222 req->flags |= REQ_F_IOPOLL_COMPLETED;
1223}
1224
1225/*
1226 * After the iocb has been issued, it's safe to be found on the poll list.
1227 * Adding the kiocb to the list AFTER submission ensures that we don't
1228 * find it from a io_iopoll_getevents() thread before the issuer is done
1229 * accessing the kiocb cookie.
1230 */
1231static void io_iopoll_req_issued(struct io_kiocb *req)
1232{
1233 struct io_ring_ctx *ctx = req->ctx;
1234
1235 /*
1236 * Track whether we have multiple files in our lists. This will impact
1237 * how we do polling eventually, not spinning if we're on potentially
1238 * different devices.
1239 */
1240 if (list_empty(&ctx->poll_list)) {
1241 ctx->poll_multi_file = false;
1242 } else if (!ctx->poll_multi_file) {
1243 struct io_kiocb *list_req;
1244
1245 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1246 list);
1247 if (list_req->rw.ki_filp != req->rw.ki_filp)
1248 ctx->poll_multi_file = true;
1249 }
1250
1251 /*
1252 * For fast devices, IO may have already completed. If it has, add
1253 * it to the front so we find it first.
1254 */
1255 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1256 list_add(&req->list, &ctx->poll_list);
1257 else
1258 list_add_tail(&req->list, &ctx->poll_list);
1259}
1260
3d6770fb 1261static void io_file_put(struct io_submit_state *state)
9a56a232 1262{
3d6770fb 1263 if (state->file) {
9a56a232
JA
1264 int diff = state->has_refs - state->used_refs;
1265
1266 if (diff)
1267 fput_many(state->file, diff);
1268 state->file = NULL;
1269 }
1270}
1271
1272/*
1273 * Get as many references to a file as we have IOs left in this submission,
1274 * assuming most submissions are for one file, or at least that each file
1275 * has more than one submission.
1276 */
1277static struct file *io_file_get(struct io_submit_state *state, int fd)
1278{
1279 if (!state)
1280 return fget(fd);
1281
1282 if (state->file) {
1283 if (state->fd == fd) {
1284 state->used_refs++;
1285 state->ios_left--;
1286 return state->file;
1287 }
3d6770fb 1288 io_file_put(state);
9a56a232
JA
1289 }
1290 state->file = fget_many(fd, state->ios_left);
1291 if (!state->file)
1292 return NULL;
1293
1294 state->fd = fd;
1295 state->has_refs = state->ios_left;
1296 state->used_refs = 1;
1297 state->ios_left--;
1298 return state->file;
1299}
1300
2b188cc1
JA
1301/*
1302 * If we tracked the file through the SCM inflight mechanism, we could support
1303 * any file. For now, just ensure that anything potentially problematic is done
1304 * inline.
1305 */
1306static bool io_file_supports_async(struct file *file)
1307{
1308 umode_t mode = file_inode(file)->i_mode;
1309
1310 if (S_ISBLK(mode) || S_ISCHR(mode))
1311 return true;
1312 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1313 return true;
1314
1315 return false;
1316}
1317
267bc904 1318static int io_prep_rw(struct io_kiocb *req, bool force_nonblock)
2b188cc1 1319{
267bc904 1320 const struct io_uring_sqe *sqe = req->submit.sqe;
def596e9 1321 struct io_ring_ctx *ctx = req->ctx;
2b188cc1 1322 struct kiocb *kiocb = &req->rw;
09bb8394
JA
1323 unsigned ioprio;
1324 int ret;
2b188cc1 1325
09bb8394
JA
1326 if (!req->file)
1327 return -EBADF;
2b188cc1 1328
491381ce
JA
1329 if (S_ISREG(file_inode(req->file)->i_mode))
1330 req->flags |= REQ_F_ISREG;
1331
1332 /*
1333 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
1334 * we know to async punt it even if it was opened O_NONBLOCK
1335 */
1336 if (force_nonblock && !io_file_supports_async(req->file)) {
1337 req->flags |= REQ_F_MUST_PUNT;
1338 return -EAGAIN;
1339 }
6b06314c 1340
2b188cc1
JA
1341 kiocb->ki_pos = READ_ONCE(sqe->off);
1342 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1343 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1344
1345 ioprio = READ_ONCE(sqe->ioprio);
1346 if (ioprio) {
1347 ret = ioprio_check_cap(ioprio);
1348 if (ret)
09bb8394 1349 return ret;
2b188cc1
JA
1350
1351 kiocb->ki_ioprio = ioprio;
1352 } else
1353 kiocb->ki_ioprio = get_current_ioprio();
1354
1355 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1356 if (unlikely(ret))
09bb8394 1357 return ret;
8449eeda
SB
1358
1359 /* don't allow async punt if RWF_NOWAIT was requested */
491381ce
JA
1360 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1361 (req->file->f_flags & O_NONBLOCK))
8449eeda
SB
1362 req->flags |= REQ_F_NOWAIT;
1363
1364 if (force_nonblock)
2b188cc1 1365 kiocb->ki_flags |= IOCB_NOWAIT;
8449eeda 1366
def596e9 1367 if (ctx->flags & IORING_SETUP_IOPOLL) {
def596e9
JA
1368 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1369 !kiocb->ki_filp->f_op->iopoll)
09bb8394 1370 return -EOPNOTSUPP;
2b188cc1 1371
def596e9
JA
1372 kiocb->ki_flags |= IOCB_HIPRI;
1373 kiocb->ki_complete = io_complete_rw_iopoll;
1374 } else {
09bb8394
JA
1375 if (kiocb->ki_flags & IOCB_HIPRI)
1376 return -EINVAL;
def596e9
JA
1377 kiocb->ki_complete = io_complete_rw;
1378 }
2b188cc1 1379 return 0;
2b188cc1
JA
1380}
1381
1382static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1383{
1384 switch (ret) {
1385 case -EIOCBQUEUED:
1386 break;
1387 case -ERESTARTSYS:
1388 case -ERESTARTNOINTR:
1389 case -ERESTARTNOHAND:
1390 case -ERESTART_RESTARTBLOCK:
1391 /*
1392 * We can't just restart the syscall, since previously
1393 * submitted sqes may already be in progress. Just fail this
1394 * IO with EINTR.
1395 */
1396 ret = -EINTR;
1397 /* fall through */
1398 default:
1399 kiocb->ki_complete(kiocb, ret, 0);
1400 }
1401}
1402
ba816ad6
JA
1403static void kiocb_done(struct kiocb *kiocb, ssize_t ret, struct io_kiocb **nxt,
1404 bool in_async)
1405{
1406 if (in_async && ret >= 0 && nxt && kiocb->ki_complete == io_complete_rw)
1407 *nxt = __io_complete_rw(kiocb, ret);
1408 else
1409 io_rw_done(kiocb, ret);
1410}
1411
edafccee
JA
1412static int io_import_fixed(struct io_ring_ctx *ctx, int rw,
1413 const struct io_uring_sqe *sqe,
1414 struct iov_iter *iter)
1415{
1416 size_t len = READ_ONCE(sqe->len);
1417 struct io_mapped_ubuf *imu;
1418 unsigned index, buf_index;
1419 size_t offset;
1420 u64 buf_addr;
1421
1422 /* attempt to use fixed buffers without having provided iovecs */
1423 if (unlikely(!ctx->user_bufs))
1424 return -EFAULT;
1425
1426 buf_index = READ_ONCE(sqe->buf_index);
1427 if (unlikely(buf_index >= ctx->nr_user_bufs))
1428 return -EFAULT;
1429
1430 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1431 imu = &ctx->user_bufs[index];
1432 buf_addr = READ_ONCE(sqe->addr);
1433
1434 /* overflow */
1435 if (buf_addr + len < buf_addr)
1436 return -EFAULT;
1437 /* not inside the mapped region */
1438 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1439 return -EFAULT;
1440
1441 /*
1442 * May not be a start of buffer, set size appropriately
1443 * and advance us to the beginning.
1444 */
1445 offset = buf_addr - imu->ubuf;
1446 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
bd11b3a3
JA
1447
1448 if (offset) {
1449 /*
1450 * Don't use iov_iter_advance() here, as it's really slow for
1451 * using the latter parts of a big fixed buffer - it iterates
1452 * over each segment manually. We can cheat a bit here, because
1453 * we know that:
1454 *
1455 * 1) it's a BVEC iter, we set it up
1456 * 2) all bvecs are PAGE_SIZE in size, except potentially the
1457 * first and last bvec
1458 *
1459 * So just find our index, and adjust the iterator afterwards.
1460 * If the offset is within the first bvec (or the whole first
1461 * bvec, just use iov_iter_advance(). This makes it easier
1462 * since we can just skip the first segment, which may not
1463 * be PAGE_SIZE aligned.
1464 */
1465 const struct bio_vec *bvec = imu->bvec;
1466
1467 if (offset <= bvec->bv_len) {
1468 iov_iter_advance(iter, offset);
1469 } else {
1470 unsigned long seg_skip;
1471
1472 /* skip first vec */
1473 offset -= bvec->bv_len;
1474 seg_skip = 1 + (offset >> PAGE_SHIFT);
1475
1476 iter->bvec = bvec + seg_skip;
1477 iter->nr_segs -= seg_skip;
99c79f66 1478 iter->count -= bvec->bv_len + offset;
bd11b3a3 1479 iter->iov_offset = offset & ~PAGE_MASK;
bd11b3a3
JA
1480 }
1481 }
1482
edafccee
JA
1483 return 0;
1484}
1485
87e5e6da
JA
1486static ssize_t io_import_iovec(struct io_ring_ctx *ctx, int rw,
1487 const struct sqe_submit *s, struct iovec **iovec,
1488 struct iov_iter *iter)
2b188cc1
JA
1489{
1490 const struct io_uring_sqe *sqe = s->sqe;
1491 void __user *buf = u64_to_user_ptr(READ_ONCE(sqe->addr));
1492 size_t sqe_len = READ_ONCE(sqe->len);
edafccee
JA
1493 u8 opcode;
1494
1495 /*
1496 * We're reading ->opcode for the second time, but the first read
1497 * doesn't care whether it's _FIXED or not, so it doesn't matter
1498 * whether ->opcode changes concurrently. The first read does care
1499 * about whether it is a READ or a WRITE, so we don't trust this read
1500 * for that purpose and instead let the caller pass in the read/write
1501 * flag.
1502 */
1503 opcode = READ_ONCE(sqe->opcode);
1504 if (opcode == IORING_OP_READ_FIXED ||
1505 opcode == IORING_OP_WRITE_FIXED) {
87e5e6da 1506 ssize_t ret = io_import_fixed(ctx, rw, sqe, iter);
edafccee
JA
1507 *iovec = NULL;
1508 return ret;
1509 }
2b188cc1
JA
1510
1511 if (!s->has_user)
1512 return -EFAULT;
1513
1514#ifdef CONFIG_COMPAT
1515 if (ctx->compat)
1516 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
1517 iovec, iter);
1518#endif
1519
1520 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
1521}
1522
32960613
JA
1523/*
1524 * For files that don't have ->read_iter() and ->write_iter(), handle them
1525 * by looping over ->read() or ->write() manually.
1526 */
1527static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
1528 struct iov_iter *iter)
1529{
1530 ssize_t ret = 0;
1531
1532 /*
1533 * Don't support polled IO through this interface, and we can't
1534 * support non-blocking either. For the latter, this just causes
1535 * the kiocb to be handled from an async context.
1536 */
1537 if (kiocb->ki_flags & IOCB_HIPRI)
1538 return -EOPNOTSUPP;
1539 if (kiocb->ki_flags & IOCB_NOWAIT)
1540 return -EAGAIN;
1541
1542 while (iov_iter_count(iter)) {
1543 struct iovec iovec = iov_iter_iovec(iter);
1544 ssize_t nr;
1545
1546 if (rw == READ) {
1547 nr = file->f_op->read(file, iovec.iov_base,
1548 iovec.iov_len, &kiocb->ki_pos);
1549 } else {
1550 nr = file->f_op->write(file, iovec.iov_base,
1551 iovec.iov_len, &kiocb->ki_pos);
1552 }
1553
1554 if (nr < 0) {
1555 if (!ret)
1556 ret = nr;
1557 break;
1558 }
1559 ret += nr;
1560 if (nr != iovec.iov_len)
1561 break;
1562 iov_iter_advance(iter, nr);
1563 }
1564
1565 return ret;
1566}
1567
267bc904
PB
1568static int io_read(struct io_kiocb *req, struct io_kiocb **nxt,
1569 bool force_nonblock)
2b188cc1
JA
1570{
1571 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1572 struct kiocb *kiocb = &req->rw;
1573 struct iov_iter iter;
1574 struct file *file;
31b51510 1575 size_t iov_count;
9d93a3f5 1576 ssize_t read_size, ret;
2b188cc1 1577
267bc904 1578 ret = io_prep_rw(req, force_nonblock);
2b188cc1
JA
1579 if (ret)
1580 return ret;
1581 file = kiocb->ki_filp;
1582
2b188cc1 1583 if (unlikely(!(file->f_mode & FMODE_READ)))
09bb8394 1584 return -EBADF;
2b188cc1 1585
267bc904 1586 ret = io_import_iovec(req->ctx, READ, &req->submit, &iovec, &iter);
87e5e6da 1587 if (ret < 0)
09bb8394 1588 return ret;
2b188cc1 1589
9d93a3f5 1590 read_size = ret;
9e645e11
JA
1591 if (req->flags & REQ_F_LINK)
1592 req->result = read_size;
1593
31b51510
JA
1594 iov_count = iov_iter_count(&iter);
1595 ret = rw_verify_area(READ, file, &kiocb->ki_pos, iov_count);
2b188cc1
JA
1596 if (!ret) {
1597 ssize_t ret2;
1598
32960613
JA
1599 if (file->f_op->read_iter)
1600 ret2 = call_read_iter(file, kiocb, &iter);
1601 else
1602 ret2 = loop_rw_iter(READ, file, kiocb, &iter);
1603
9d93a3f5
JA
1604 /*
1605 * In case of a short read, punt to async. This can happen
1606 * if we have data partially cached. Alternatively we can
1607 * return the short read, in which case the application will
1608 * need to issue another SQE and wait for it. That SQE will
1609 * need async punt anyway, so it's more efficient to do it
1610 * here.
1611 */
491381ce
JA
1612 if (force_nonblock && !(req->flags & REQ_F_NOWAIT) &&
1613 (req->flags & REQ_F_ISREG) &&
1614 ret2 > 0 && ret2 < read_size)
9d93a3f5
JA
1615 ret2 = -EAGAIN;
1616 /* Catch -EAGAIN return for forced non-blocking submission */
561fb04a 1617 if (!force_nonblock || ret2 != -EAGAIN)
267bc904 1618 kiocb_done(kiocb, ret2, nxt, req->submit.in_async);
561fb04a 1619 else
2b188cc1
JA
1620 ret = -EAGAIN;
1621 }
1622 kfree(iovec);
2b188cc1
JA
1623 return ret;
1624}
1625
267bc904
PB
1626static int io_write(struct io_kiocb *req, struct io_kiocb **nxt,
1627 bool force_nonblock)
2b188cc1
JA
1628{
1629 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1630 struct kiocb *kiocb = &req->rw;
1631 struct iov_iter iter;
1632 struct file *file;
31b51510 1633 size_t iov_count;
87e5e6da 1634 ssize_t ret;
2b188cc1 1635
267bc904 1636 ret = io_prep_rw(req, force_nonblock);
2b188cc1
JA
1637 if (ret)
1638 return ret;
2b188cc1 1639
2b188cc1
JA
1640 file = kiocb->ki_filp;
1641 if (unlikely(!(file->f_mode & FMODE_WRITE)))
09bb8394 1642 return -EBADF;
2b188cc1 1643
267bc904 1644 ret = io_import_iovec(req->ctx, WRITE, &req->submit, &iovec, &iter);
87e5e6da 1645 if (ret < 0)
09bb8394 1646 return ret;
2b188cc1 1647
9e645e11
JA
1648 if (req->flags & REQ_F_LINK)
1649 req->result = ret;
1650
31b51510
JA
1651 iov_count = iov_iter_count(&iter);
1652
1653 ret = -EAGAIN;
561fb04a 1654 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT))
31b51510 1655 goto out_free;
31b51510
JA
1656
1657 ret = rw_verify_area(WRITE, file, &kiocb->ki_pos, iov_count);
2b188cc1 1658 if (!ret) {
9bf7933f
RP
1659 ssize_t ret2;
1660
2b188cc1
JA
1661 /*
1662 * Open-code file_start_write here to grab freeze protection,
1663 * which will be released by another thread in
1664 * io_complete_rw(). Fool lockdep by telling it the lock got
1665 * released so that it doesn't complain about the held lock when
1666 * we return to userspace.
1667 */
491381ce 1668 if (req->flags & REQ_F_ISREG) {
2b188cc1
JA
1669 __sb_start_write(file_inode(file)->i_sb,
1670 SB_FREEZE_WRITE, true);
1671 __sb_writers_release(file_inode(file)->i_sb,
1672 SB_FREEZE_WRITE);
1673 }
1674 kiocb->ki_flags |= IOCB_WRITE;
9bf7933f 1675
32960613
JA
1676 if (file->f_op->write_iter)
1677 ret2 = call_write_iter(file, kiocb, &iter);
1678 else
1679 ret2 = loop_rw_iter(WRITE, file, kiocb, &iter);
561fb04a 1680 if (!force_nonblock || ret2 != -EAGAIN)
267bc904 1681 kiocb_done(kiocb, ret2, nxt, req->submit.in_async);
561fb04a 1682 else
9bf7933f 1683 ret = -EAGAIN;
2b188cc1 1684 }
31b51510 1685out_free:
2b188cc1 1686 kfree(iovec);
2b188cc1
JA
1687 return ret;
1688}
1689
1690/*
1691 * IORING_OP_NOP just posts a completion event, nothing else.
1692 */
78e19bbe 1693static int io_nop(struct io_kiocb *req)
2b188cc1
JA
1694{
1695 struct io_ring_ctx *ctx = req->ctx;
2b188cc1 1696
def596e9
JA
1697 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1698 return -EINVAL;
1699
78e19bbe 1700 io_cqring_add_event(req, 0);
ba816ad6 1701 io_put_req(req, NULL);
2b188cc1
JA
1702 return 0;
1703}
1704
c992fe29
CH
1705static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1706{
6b06314c 1707 struct io_ring_ctx *ctx = req->ctx;
c992fe29 1708
09bb8394
JA
1709 if (!req->file)
1710 return -EBADF;
c992fe29 1711
6b06314c 1712 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
def596e9 1713 return -EINVAL;
edafccee 1714 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
c992fe29
CH
1715 return -EINVAL;
1716
c992fe29
CH
1717 return 0;
1718}
1719
1720static int io_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe,
ba816ad6 1721 struct io_kiocb **nxt, bool force_nonblock)
c992fe29
CH
1722{
1723 loff_t sqe_off = READ_ONCE(sqe->off);
1724 loff_t sqe_len = READ_ONCE(sqe->len);
1725 loff_t end = sqe_off + sqe_len;
1726 unsigned fsync_flags;
1727 int ret;
1728
1729 fsync_flags = READ_ONCE(sqe->fsync_flags);
1730 if (unlikely(fsync_flags & ~IORING_FSYNC_DATASYNC))
1731 return -EINVAL;
1732
1733 ret = io_prep_fsync(req, sqe);
1734 if (ret)
1735 return ret;
1736
1737 /* fsync always requires a blocking context */
1738 if (force_nonblock)
1739 return -EAGAIN;
1740
1741 ret = vfs_fsync_range(req->rw.ki_filp, sqe_off,
1742 end > 0 ? end : LLONG_MAX,
1743 fsync_flags & IORING_FSYNC_DATASYNC);
1744
9e645e11
JA
1745 if (ret < 0 && (req->flags & REQ_F_LINK))
1746 req->flags |= REQ_F_FAIL_LINK;
78e19bbe 1747 io_cqring_add_event(req, ret);
ba816ad6 1748 io_put_req(req, nxt);
c992fe29
CH
1749 return 0;
1750}
1751
5d17b4a4
JA
1752static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1753{
1754 struct io_ring_ctx *ctx = req->ctx;
1755 int ret = 0;
1756
1757 if (!req->file)
1758 return -EBADF;
5d17b4a4
JA
1759
1760 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1761 return -EINVAL;
1762 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1763 return -EINVAL;
1764
5d17b4a4
JA
1765 return ret;
1766}
1767
1768static int io_sync_file_range(struct io_kiocb *req,
1769 const struct io_uring_sqe *sqe,
ba816ad6 1770 struct io_kiocb **nxt,
5d17b4a4
JA
1771 bool force_nonblock)
1772{
1773 loff_t sqe_off;
1774 loff_t sqe_len;
1775 unsigned flags;
1776 int ret;
1777
1778 ret = io_prep_sfr(req, sqe);
1779 if (ret)
1780 return ret;
1781
1782 /* sync_file_range always requires a blocking context */
1783 if (force_nonblock)
1784 return -EAGAIN;
1785
1786 sqe_off = READ_ONCE(sqe->off);
1787 sqe_len = READ_ONCE(sqe->len);
1788 flags = READ_ONCE(sqe->sync_range_flags);
1789
1790 ret = sync_file_range(req->rw.ki_filp, sqe_off, sqe_len, flags);
1791
9e645e11
JA
1792 if (ret < 0 && (req->flags & REQ_F_LINK))
1793 req->flags |= REQ_F_FAIL_LINK;
78e19bbe 1794 io_cqring_add_event(req, ret);
ba816ad6 1795 io_put_req(req, nxt);
5d17b4a4
JA
1796 return 0;
1797}
1798
0fa03c62 1799#if defined(CONFIG_NET)
aa1fa28f 1800static int io_send_recvmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
ba816ad6 1801 struct io_kiocb **nxt, bool force_nonblock,
aa1fa28f
JA
1802 long (*fn)(struct socket *, struct user_msghdr __user *,
1803 unsigned int))
1804{
0fa03c62
JA
1805 struct socket *sock;
1806 int ret;
1807
1808 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1809 return -EINVAL;
1810
1811 sock = sock_from_file(req->file, &ret);
1812 if (sock) {
1813 struct user_msghdr __user *msg;
1814 unsigned flags;
1815
1816 flags = READ_ONCE(sqe->msg_flags);
1817 if (flags & MSG_DONTWAIT)
1818 req->flags |= REQ_F_NOWAIT;
1819 else if (force_nonblock)
1820 flags |= MSG_DONTWAIT;
1821
1822 msg = (struct user_msghdr __user *) (unsigned long)
1823 READ_ONCE(sqe->addr);
1824
aa1fa28f 1825 ret = fn(sock, msg, flags);
0fa03c62
JA
1826 if (force_nonblock && ret == -EAGAIN)
1827 return ret;
1828 }
1829
78e19bbe 1830 io_cqring_add_event(req, ret);
f1f40853
JA
1831 if (ret < 0 && (req->flags & REQ_F_LINK))
1832 req->flags |= REQ_F_FAIL_LINK;
ba816ad6 1833 io_put_req(req, nxt);
5d17b4a4
JA
1834 return 0;
1835}
aa1fa28f
JA
1836#endif
1837
1838static int io_sendmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
ba816ad6 1839 struct io_kiocb **nxt, bool force_nonblock)
aa1fa28f
JA
1840{
1841#if defined(CONFIG_NET)
ba816ad6
JA
1842 return io_send_recvmsg(req, sqe, nxt, force_nonblock,
1843 __sys_sendmsg_sock);
aa1fa28f
JA
1844#else
1845 return -EOPNOTSUPP;
1846#endif
1847}
1848
1849static int io_recvmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
ba816ad6 1850 struct io_kiocb **nxt, bool force_nonblock)
aa1fa28f
JA
1851{
1852#if defined(CONFIG_NET)
ba816ad6
JA
1853 return io_send_recvmsg(req, sqe, nxt, force_nonblock,
1854 __sys_recvmsg_sock);
0fa03c62
JA
1855#else
1856 return -EOPNOTSUPP;
1857#endif
1858}
5d17b4a4 1859
17f2fe35
JA
1860static int io_accept(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1861 struct io_kiocb **nxt, bool force_nonblock)
1862{
1863#if defined(CONFIG_NET)
1864 struct sockaddr __user *addr;
1865 int __user *addr_len;
1866 unsigned file_flags;
1867 int flags, ret;
1868
1869 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
1870 return -EINVAL;
1871 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
1872 return -EINVAL;
1873
1874 addr = (struct sockaddr __user *) (unsigned long) READ_ONCE(sqe->addr);
1875 addr_len = (int __user *) (unsigned long) READ_ONCE(sqe->addr2);
1876 flags = READ_ONCE(sqe->accept_flags);
1877 file_flags = force_nonblock ? O_NONBLOCK : 0;
1878
1879 ret = __sys_accept4_file(req->file, file_flags, addr, addr_len, flags);
1880 if (ret == -EAGAIN && force_nonblock) {
1881 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
1882 return -EAGAIN;
1883 }
1884 if (ret < 0 && (req->flags & REQ_F_LINK))
1885 req->flags |= REQ_F_FAIL_LINK;
78e19bbe 1886 io_cqring_add_event(req, ret);
17f2fe35
JA
1887 io_put_req(req, nxt);
1888 return 0;
1889#else
1890 return -EOPNOTSUPP;
1891#endif
1892}
1893
221c5eb2
JA
1894static void io_poll_remove_one(struct io_kiocb *req)
1895{
1896 struct io_poll_iocb *poll = &req->poll;
1897
1898 spin_lock(&poll->head->lock);
1899 WRITE_ONCE(poll->canceled, true);
1900 if (!list_empty(&poll->wait.entry)) {
1901 list_del_init(&poll->wait.entry);
18d9be1a 1902 io_queue_async_work(req->ctx, req);
221c5eb2
JA
1903 }
1904 spin_unlock(&poll->head->lock);
1905
1906 list_del_init(&req->list);
1907}
1908
1909static void io_poll_remove_all(struct io_ring_ctx *ctx)
1910{
1911 struct io_kiocb *req;
1912
1913 spin_lock_irq(&ctx->completion_lock);
1914 while (!list_empty(&ctx->cancel_list)) {
1915 req = list_first_entry(&ctx->cancel_list, struct io_kiocb,list);
1916 io_poll_remove_one(req);
1917 }
1918 spin_unlock_irq(&ctx->completion_lock);
1919}
1920
1921/*
1922 * Find a running poll command that matches one specified in sqe->addr,
1923 * and remove it if found.
1924 */
1925static int io_poll_remove(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1926{
1927 struct io_ring_ctx *ctx = req->ctx;
1928 struct io_kiocb *poll_req, *next;
1929 int ret = -ENOENT;
1930
1931 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1932 return -EINVAL;
1933 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
1934 sqe->poll_events)
1935 return -EINVAL;
1936
1937 spin_lock_irq(&ctx->completion_lock);
1938 list_for_each_entry_safe(poll_req, next, &ctx->cancel_list, list) {
1939 if (READ_ONCE(sqe->addr) == poll_req->user_data) {
1940 io_poll_remove_one(poll_req);
1941 ret = 0;
1942 break;
1943 }
1944 }
1945 spin_unlock_irq(&ctx->completion_lock);
1946
78e19bbe 1947 io_cqring_add_event(req, ret);
f1f40853
JA
1948 if (ret < 0 && (req->flags & REQ_F_LINK))
1949 req->flags |= REQ_F_FAIL_LINK;
ba816ad6 1950 io_put_req(req, NULL);
221c5eb2
JA
1951 return 0;
1952}
1953
8c838788
JA
1954static void io_poll_complete(struct io_ring_ctx *ctx, struct io_kiocb *req,
1955 __poll_t mask)
221c5eb2 1956{
8c838788 1957 req->poll.done = true;
78e19bbe 1958 io_cqring_fill_event(req, mangle_poll(mask));
8c838788 1959 io_commit_cqring(ctx);
221c5eb2
JA
1960}
1961
561fb04a 1962static void io_poll_complete_work(struct io_wq_work **workptr)
221c5eb2 1963{
561fb04a 1964 struct io_wq_work *work = *workptr;
221c5eb2
JA
1965 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1966 struct io_poll_iocb *poll = &req->poll;
1967 struct poll_table_struct pt = { ._key = poll->events };
1968 struct io_ring_ctx *ctx = req->ctx;
89723d0b 1969 struct io_kiocb *nxt = NULL;
221c5eb2
JA
1970 __poll_t mask = 0;
1971
561fb04a
JA
1972 if (work->flags & IO_WQ_WORK_CANCEL)
1973 WRITE_ONCE(poll->canceled, true);
1974
221c5eb2
JA
1975 if (!READ_ONCE(poll->canceled))
1976 mask = vfs_poll(poll->file, &pt) & poll->events;
1977
1978 /*
1979 * Note that ->ki_cancel callers also delete iocb from active_reqs after
1980 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
1981 * synchronize with them. In the cancellation case the list_del_init
1982 * itself is not actually needed, but harmless so we keep it in to
1983 * avoid further branches in the fast path.
1984 */
1985 spin_lock_irq(&ctx->completion_lock);
1986 if (!mask && !READ_ONCE(poll->canceled)) {
1987 add_wait_queue(poll->head, &poll->wait);
1988 spin_unlock_irq(&ctx->completion_lock);
1989 return;
1990 }
1991 list_del_init(&req->list);
8c838788 1992 io_poll_complete(ctx, req, mask);
221c5eb2
JA
1993 spin_unlock_irq(&ctx->completion_lock);
1994
8c838788 1995 io_cqring_ev_posted(ctx);
89723d0b
JA
1996
1997 io_put_req(req, &nxt);
1998 if (nxt)
1999 *workptr = &nxt->work;
221c5eb2
JA
2000}
2001
2002static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
2003 void *key)
2004{
2005 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
2006 wait);
2007 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
2008 struct io_ring_ctx *ctx = req->ctx;
2009 __poll_t mask = key_to_poll(key);
8c838788 2010 unsigned long flags;
221c5eb2
JA
2011
2012 /* for instances that support it check for an event match first: */
8c838788
JA
2013 if (mask && !(mask & poll->events))
2014 return 0;
221c5eb2 2015
8c838788 2016 list_del_init(&poll->wait.entry);
221c5eb2 2017
8c838788
JA
2018 if (mask && spin_trylock_irqsave(&ctx->completion_lock, flags)) {
2019 list_del(&req->list);
2020 io_poll_complete(ctx, req, mask);
2021 spin_unlock_irqrestore(&ctx->completion_lock, flags);
221c5eb2 2022
8c838788 2023 io_cqring_ev_posted(ctx);
ba816ad6 2024 io_put_req(req, NULL);
8c838788 2025 } else {
18d9be1a 2026 io_queue_async_work(ctx, req);
221c5eb2
JA
2027 }
2028
221c5eb2
JA
2029 return 1;
2030}
2031
2032struct io_poll_table {
2033 struct poll_table_struct pt;
2034 struct io_kiocb *req;
2035 int error;
2036};
2037
2038static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
2039 struct poll_table_struct *p)
2040{
2041 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
2042
2043 if (unlikely(pt->req->poll.head)) {
2044 pt->error = -EINVAL;
2045 return;
2046 }
2047
2048 pt->error = 0;
2049 pt->req->poll.head = head;
2050 add_wait_queue(head, &pt->req->poll.wait);
2051}
2052
89723d0b
JA
2053static int io_poll_add(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2054 struct io_kiocb **nxt)
221c5eb2
JA
2055{
2056 struct io_poll_iocb *poll = &req->poll;
2057 struct io_ring_ctx *ctx = req->ctx;
2058 struct io_poll_table ipt;
8c838788 2059 bool cancel = false;
221c5eb2
JA
2060 __poll_t mask;
2061 u16 events;
221c5eb2
JA
2062
2063 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2064 return -EINVAL;
2065 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
2066 return -EINVAL;
09bb8394
JA
2067 if (!poll->file)
2068 return -EBADF;
221c5eb2 2069
6cc47d1d 2070 req->submit.sqe = NULL;
561fb04a 2071 INIT_IO_WORK(&req->work, io_poll_complete_work);
221c5eb2
JA
2072 events = READ_ONCE(sqe->poll_events);
2073 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
2074
221c5eb2 2075 poll->head = NULL;
8c838788 2076 poll->done = false;
221c5eb2
JA
2077 poll->canceled = false;
2078
2079 ipt.pt._qproc = io_poll_queue_proc;
2080 ipt.pt._key = poll->events;
2081 ipt.req = req;
2082 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
2083
2084 /* initialized the list so that we can do list_empty checks */
2085 INIT_LIST_HEAD(&poll->wait.entry);
2086 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
2087
36703247
JA
2088 INIT_LIST_HEAD(&req->list);
2089
221c5eb2 2090 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
221c5eb2
JA
2091
2092 spin_lock_irq(&ctx->completion_lock);
8c838788
JA
2093 if (likely(poll->head)) {
2094 spin_lock(&poll->head->lock);
2095 if (unlikely(list_empty(&poll->wait.entry))) {
2096 if (ipt.error)
2097 cancel = true;
2098 ipt.error = 0;
2099 mask = 0;
2100 }
2101 if (mask || ipt.error)
2102 list_del_init(&poll->wait.entry);
2103 else if (cancel)
2104 WRITE_ONCE(poll->canceled, true);
2105 else if (!poll->done) /* actually waiting for an event */
2106 list_add_tail(&req->list, &ctx->cancel_list);
2107 spin_unlock(&poll->head->lock);
2108 }
2109 if (mask) { /* no async, we'd stolen it */
221c5eb2 2110 ipt.error = 0;
8c838788 2111 io_poll_complete(ctx, req, mask);
221c5eb2 2112 }
221c5eb2
JA
2113 spin_unlock_irq(&ctx->completion_lock);
2114
8c838788
JA
2115 if (mask) {
2116 io_cqring_ev_posted(ctx);
89723d0b 2117 io_put_req(req, nxt);
221c5eb2 2118 }
8c838788 2119 return ipt.error;
221c5eb2
JA
2120}
2121
5262f567
JA
2122static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
2123{
2124 struct io_ring_ctx *ctx;
11365043 2125 struct io_kiocb *req;
5262f567
JA
2126 unsigned long flags;
2127
2128 req = container_of(timer, struct io_kiocb, timeout.timer);
2129 ctx = req->ctx;
2130 atomic_inc(&ctx->cq_timeouts);
2131
2132 spin_lock_irqsave(&ctx->completion_lock, flags);
ef03681a 2133 /*
11365043
JA
2134 * We could be racing with timeout deletion. If the list is empty,
2135 * then timeout lookup already found it and will be handling it.
ef03681a 2136 */
842f9612 2137 if (!list_empty(&req->list)) {
11365043 2138 struct io_kiocb *prev;
5262f567 2139
11365043
JA
2140 /*
2141 * Adjust the reqs sequence before the current one because it
2142 * will consume a slot in the cq_ring and the the cq_tail
2143 * pointer will be increased, otherwise other timeout reqs may
2144 * return in advance without waiting for enough wait_nr.
2145 */
2146 prev = req;
2147 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
2148 prev->sequence++;
11365043 2149 list_del_init(&req->list);
11365043 2150 }
842f9612 2151
78e19bbe 2152 io_cqring_fill_event(req, -ETIME);
842f9612 2153 io_commit_cqring(ctx);
5262f567
JA
2154 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2155
842f9612 2156 io_cqring_ev_posted(ctx);
f1f40853
JA
2157 if (req->flags & REQ_F_LINK)
2158 req->flags |= REQ_F_FAIL_LINK;
842f9612 2159 io_put_req(req, NULL);
11365043
JA
2160 return HRTIMER_NORESTART;
2161}
2162
2163/*
2164 * Remove or update an existing timeout command
2165 */
2166static int io_timeout_remove(struct io_kiocb *req,
2167 const struct io_uring_sqe *sqe)
2168{
2169 struct io_ring_ctx *ctx = req->ctx;
2170 struct io_kiocb *treq;
2171 int ret = -ENOENT;
2172 __u64 user_data;
2173 unsigned flags;
2174
2175 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2176 return -EINVAL;
2177 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
2178 return -EINVAL;
2179 flags = READ_ONCE(sqe->timeout_flags);
2180 if (flags)
2181 return -EINVAL;
2182
2183 user_data = READ_ONCE(sqe->addr);
2184 spin_lock_irq(&ctx->completion_lock);
2185 list_for_each_entry(treq, &ctx->timeout_list, list) {
2186 if (user_data == treq->user_data) {
2187 list_del_init(&treq->list);
2188 ret = 0;
2189 break;
2190 }
2191 }
2192
2193 /* didn't find timeout */
2194 if (ret) {
2195fill_ev:
78e19bbe 2196 io_cqring_fill_event(req, ret);
11365043
JA
2197 io_commit_cqring(ctx);
2198 spin_unlock_irq(&ctx->completion_lock);
2199 io_cqring_ev_posted(ctx);
f1f40853
JA
2200 if (req->flags & REQ_F_LINK)
2201 req->flags |= REQ_F_FAIL_LINK;
11365043
JA
2202 io_put_req(req, NULL);
2203 return 0;
2204 }
2205
2206 ret = hrtimer_try_to_cancel(&treq->timeout.timer);
2207 if (ret == -1) {
2208 ret = -EBUSY;
2209 goto fill_ev;
2210 }
2211
78e19bbe
JA
2212 io_cqring_fill_event(req, 0);
2213 io_cqring_fill_event(treq, -ECANCELED);
11365043
JA
2214 io_commit_cqring(ctx);
2215 spin_unlock_irq(&ctx->completion_lock);
5262f567
JA
2216 io_cqring_ev_posted(ctx);
2217
11365043 2218 io_put_req(treq, NULL);
ba816ad6 2219 io_put_req(req, NULL);
11365043 2220 return 0;
5262f567
JA
2221}
2222
2223static int io_timeout(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2224{
5da0fb1a 2225 unsigned count;
5262f567
JA
2226 struct io_ring_ctx *ctx = req->ctx;
2227 struct list_head *entry;
a41525ab 2228 enum hrtimer_mode mode;
bdf20073 2229 struct timespec64 ts;
a1f58ba4 2230 unsigned span = 0;
a41525ab 2231 unsigned flags;
5262f567
JA
2232
2233 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2234 return -EINVAL;
a41525ab
JA
2235 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len != 1)
2236 return -EINVAL;
2237 flags = READ_ONCE(sqe->timeout_flags);
2238 if (flags & ~IORING_TIMEOUT_ABS)
5262f567 2239 return -EINVAL;
bdf20073
AB
2240
2241 if (get_timespec64(&ts, u64_to_user_ptr(sqe->addr)))
5262f567
JA
2242 return -EFAULT;
2243
11365043
JA
2244 if (flags & IORING_TIMEOUT_ABS)
2245 mode = HRTIMER_MODE_ABS;
2246 else
2247 mode = HRTIMER_MODE_REL;
2248
2249 hrtimer_init(&req->timeout.timer, CLOCK_MONOTONIC, mode);
2250
5262f567
JA
2251 /*
2252 * sqe->off holds how many events that need to occur for this
2253 * timeout event to be satisfied.
2254 */
2255 count = READ_ONCE(sqe->off);
2256 if (!count)
2257 count = 1;
2258
2259 req->sequence = ctx->cached_sq_head + count - 1;
5da0fb1a 2260 /* reuse it to store the count */
2261 req->submit.sequence = count;
5262f567
JA
2262 req->flags |= REQ_F_TIMEOUT;
2263
2264 /*
2265 * Insertion sort, ensuring the first entry in the list is always
2266 * the one we need first.
2267 */
5262f567
JA
2268 spin_lock_irq(&ctx->completion_lock);
2269 list_for_each_prev(entry, &ctx->timeout_list) {
2270 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
5da0fb1a 2271 unsigned nxt_sq_head;
2272 long long tmp, tmp_nxt;
5262f567 2273
5da0fb1a 2274 /*
2275 * Since cached_sq_head + count - 1 can overflow, use type long
2276 * long to store it.
2277 */
2278 tmp = (long long)ctx->cached_sq_head + count - 1;
2279 nxt_sq_head = nxt->sequence - nxt->submit.sequence + 1;
2280 tmp_nxt = (long long)nxt_sq_head + nxt->submit.sequence - 1;
2281
2282 /*
2283 * cached_sq_head may overflow, and it will never overflow twice
2284 * once there is some timeout req still be valid.
2285 */
2286 if (ctx->cached_sq_head < nxt_sq_head)
8b07a65a 2287 tmp += UINT_MAX;
5da0fb1a 2288
a1f58ba4 2289 if (tmp > tmp_nxt)
5262f567 2290 break;
a1f58ba4 2291
2292 /*
2293 * Sequence of reqs after the insert one and itself should
2294 * be adjusted because each timeout req consumes a slot.
2295 */
2296 span++;
2297 nxt->sequence++;
5262f567 2298 }
a1f58ba4 2299 req->sequence -= span;
5262f567 2300 list_add(&req->list, entry);
5262f567 2301 req->timeout.timer.function = io_timeout_fn;
a41525ab 2302 hrtimer_start(&req->timeout.timer, timespec64_to_ktime(ts), mode);
842f9612 2303 spin_unlock_irq(&ctx->completion_lock);
5262f567
JA
2304 return 0;
2305}
2306
62755e35
JA
2307static bool io_cancel_cb(struct io_wq_work *work, void *data)
2308{
2309 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2310
2311 return req->user_data == (unsigned long) data;
2312}
2313
e977d6d3 2314static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
62755e35 2315{
62755e35 2316 enum io_wq_cancel cancel_ret;
62755e35
JA
2317 int ret = 0;
2318
62755e35
JA
2319 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
2320 switch (cancel_ret) {
2321 case IO_WQ_CANCEL_OK:
2322 ret = 0;
2323 break;
2324 case IO_WQ_CANCEL_RUNNING:
2325 ret = -EALREADY;
2326 break;
2327 case IO_WQ_CANCEL_NOTFOUND:
2328 ret = -ENOENT;
2329 break;
2330 }
2331
e977d6d3
JA
2332 return ret;
2333}
2334
2335static int io_async_cancel(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2336 struct io_kiocb **nxt)
2337{
2338 struct io_ring_ctx *ctx = req->ctx;
2339 void *sqe_addr;
2340 int ret;
2341
2342 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2343 return -EINVAL;
2344 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
2345 sqe->cancel_flags)
2346 return -EINVAL;
2347
2348 sqe_addr = (void *) (unsigned long) READ_ONCE(sqe->addr);
2349 ret = io_async_cancel_one(ctx, sqe_addr);
2350
62755e35
JA
2351 if (ret < 0 && (req->flags & REQ_F_LINK))
2352 req->flags |= REQ_F_FAIL_LINK;
78e19bbe 2353 io_cqring_add_event(req, ret);
62755e35
JA
2354 io_put_req(req, nxt);
2355 return 0;
2356}
2357
267bc904 2358static int io_req_defer(struct io_ring_ctx *ctx, struct io_kiocb *req)
de0617e4 2359{
267bc904 2360 const struct io_uring_sqe *sqe = req->submit.sqe;
de0617e4
JA
2361 struct io_uring_sqe *sqe_copy;
2362
2363 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list))
2364 return 0;
2365
2366 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
2367 if (!sqe_copy)
2368 return -EAGAIN;
2369
2370 spin_lock_irq(&ctx->completion_lock);
2371 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list)) {
2372 spin_unlock_irq(&ctx->completion_lock);
2373 kfree(sqe_copy);
2374 return 0;
2375 }
2376
2377 memcpy(sqe_copy, sqe, sizeof(*sqe_copy));
2378 req->submit.sqe = sqe_copy;
2379
c826bd7a 2380 trace_io_uring_defer(ctx, req, false);
de0617e4
JA
2381 list_add_tail(&req->list, &ctx->defer_list);
2382 spin_unlock_irq(&ctx->completion_lock);
2383 return -EIOCBQUEUED;
2384}
2385
2b188cc1 2386static int __io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
267bc904 2387 struct io_kiocb **nxt, bool force_nonblock)
2b188cc1 2388{
e0c5c576 2389 int ret, opcode;
267bc904 2390 struct sqe_submit *s = &req->submit;
2b188cc1 2391
2b188cc1
JA
2392 opcode = READ_ONCE(s->sqe->opcode);
2393 switch (opcode) {
2394 case IORING_OP_NOP:
78e19bbe 2395 ret = io_nop(req);
2b188cc1
JA
2396 break;
2397 case IORING_OP_READV:
edafccee
JA
2398 if (unlikely(s->sqe->buf_index))
2399 return -EINVAL;
267bc904 2400 ret = io_read(req, nxt, force_nonblock);
2b188cc1
JA
2401 break;
2402 case IORING_OP_WRITEV:
edafccee
JA
2403 if (unlikely(s->sqe->buf_index))
2404 return -EINVAL;
267bc904 2405 ret = io_write(req, nxt, force_nonblock);
edafccee
JA
2406 break;
2407 case IORING_OP_READ_FIXED:
267bc904 2408 ret = io_read(req, nxt, force_nonblock);
edafccee
JA
2409 break;
2410 case IORING_OP_WRITE_FIXED:
267bc904 2411 ret = io_write(req, nxt, force_nonblock);
2b188cc1 2412 break;
c992fe29 2413 case IORING_OP_FSYNC:
ba816ad6 2414 ret = io_fsync(req, s->sqe, nxt, force_nonblock);
c992fe29 2415 break;
221c5eb2 2416 case IORING_OP_POLL_ADD:
89723d0b 2417 ret = io_poll_add(req, s->sqe, nxt);
221c5eb2
JA
2418 break;
2419 case IORING_OP_POLL_REMOVE:
2420 ret = io_poll_remove(req, s->sqe);
2421 break;
5d17b4a4 2422 case IORING_OP_SYNC_FILE_RANGE:
ba816ad6 2423 ret = io_sync_file_range(req, s->sqe, nxt, force_nonblock);
5d17b4a4 2424 break;
0fa03c62 2425 case IORING_OP_SENDMSG:
ba816ad6 2426 ret = io_sendmsg(req, s->sqe, nxt, force_nonblock);
0fa03c62 2427 break;
aa1fa28f 2428 case IORING_OP_RECVMSG:
ba816ad6 2429 ret = io_recvmsg(req, s->sqe, nxt, force_nonblock);
aa1fa28f 2430 break;
5262f567
JA
2431 case IORING_OP_TIMEOUT:
2432 ret = io_timeout(req, s->sqe);
2433 break;
11365043
JA
2434 case IORING_OP_TIMEOUT_REMOVE:
2435 ret = io_timeout_remove(req, s->sqe);
2436 break;
17f2fe35
JA
2437 case IORING_OP_ACCEPT:
2438 ret = io_accept(req, s->sqe, nxt, force_nonblock);
2439 break;
62755e35
JA
2440 case IORING_OP_ASYNC_CANCEL:
2441 ret = io_async_cancel(req, s->sqe, nxt);
2442 break;
2b188cc1
JA
2443 default:
2444 ret = -EINVAL;
2445 break;
2446 }
2447
def596e9
JA
2448 if (ret)
2449 return ret;
2450
2451 if (ctx->flags & IORING_SETUP_IOPOLL) {
9e645e11 2452 if (req->result == -EAGAIN)
def596e9
JA
2453 return -EAGAIN;
2454
2455 /* workqueue context doesn't hold uring_lock, grab it now */
ba5290cc 2456 if (s->in_async)
def596e9
JA
2457 mutex_lock(&ctx->uring_lock);
2458 io_iopoll_req_issued(req);
ba5290cc 2459 if (s->in_async)
def596e9
JA
2460 mutex_unlock(&ctx->uring_lock);
2461 }
2462
2463 return 0;
2b188cc1
JA
2464}
2465
561fb04a 2466static void io_wq_submit_work(struct io_wq_work **workptr)
2b188cc1 2467{
561fb04a 2468 struct io_wq_work *work = *workptr;
2b188cc1 2469 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2b188cc1 2470 struct io_ring_ctx *ctx = req->ctx;
561fb04a
JA
2471 struct sqe_submit *s = &req->submit;
2472 const struct io_uring_sqe *sqe = s->sqe;
2473 struct io_kiocb *nxt = NULL;
2474 int ret = 0;
2b188cc1 2475
561fb04a
JA
2476 /* Ensure we clear previously set non-block flag */
2477 req->rw.ki_flags &= ~IOCB_NOWAIT;
2b188cc1 2478
561fb04a
JA
2479 if (work->flags & IO_WQ_WORK_CANCEL)
2480 ret = -ECANCELED;
31b51510 2481
561fb04a
JA
2482 if (!ret) {
2483 s->has_user = (work->flags & IO_WQ_WORK_HAS_MM) != 0;
2484 s->in_async = true;
2485 do {
267bc904 2486 ret = __io_submit_sqe(ctx, req, &nxt, false);
561fb04a
JA
2487 /*
2488 * We can get EAGAIN for polled IO even though we're
2489 * forcing a sync submission from here, since we can't
2490 * wait for request slots on the block side.
2491 */
2492 if (ret != -EAGAIN)
2493 break;
2494 cond_resched();
2495 } while (1);
2496 }
31b51510 2497
561fb04a
JA
2498 /* drop submission reference */
2499 io_put_req(req, NULL);
817869d2 2500
561fb04a 2501 if (ret) {
f1f40853
JA
2502 if (req->flags & REQ_F_LINK)
2503 req->flags |= REQ_F_FAIL_LINK;
78e19bbe 2504 io_cqring_add_event(req, ret);
ba816ad6 2505 io_put_req(req, NULL);
2b188cc1 2506 }
31b51510 2507
561fb04a
JA
2508 /* async context always use a copy of the sqe */
2509 kfree(sqe);
31b51510 2510
561fb04a
JA
2511 /* if a dependent link is ready, pass it back */
2512 if (!ret && nxt) {
2513 io_prep_async_work(nxt);
2514 *workptr = &nxt->work;
31b51510 2515 }
2b188cc1
JA
2516}
2517
09bb8394
JA
2518static bool io_op_needs_file(const struct io_uring_sqe *sqe)
2519{
2520 int op = READ_ONCE(sqe->opcode);
2521
2522 switch (op) {
2523 case IORING_OP_NOP:
2524 case IORING_OP_POLL_REMOVE:
2525 return false;
2526 default:
2527 return true;
2528 }
2529}
2530
65e19f54
JA
2531static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
2532 int index)
2533{
2534 struct fixed_file_table *table;
2535
2536 table = &ctx->file_table[index >> IORING_FILE_TABLE_SHIFT];
2537 return table->files[index & IORING_FILE_TABLE_MASK];
2538}
2539
267bc904 2540static int io_req_set_file(struct io_ring_ctx *ctx,
09bb8394
JA
2541 struct io_submit_state *state, struct io_kiocb *req)
2542{
267bc904 2543 struct sqe_submit *s = &req->submit;
09bb8394
JA
2544 unsigned flags;
2545 int fd;
2546
2547 flags = READ_ONCE(s->sqe->flags);
2548 fd = READ_ONCE(s->sqe->fd);
2549
4fe2c963 2550 if (flags & IOSQE_IO_DRAIN)
de0617e4 2551 req->flags |= REQ_F_IO_DRAIN;
4fe2c963
JL
2552 /*
2553 * All io need record the previous position, if LINK vs DARIN,
2554 * it can be used to mark the position of the first IO in the
2555 * link list.
2556 */
2557 req->sequence = s->sequence;
de0617e4 2558
60c112b0 2559 if (!io_op_needs_file(s->sqe))
09bb8394 2560 return 0;
09bb8394
JA
2561
2562 if (flags & IOSQE_FIXED_FILE) {
65e19f54 2563 if (unlikely(!ctx->file_table ||
09bb8394
JA
2564 (unsigned) fd >= ctx->nr_user_files))
2565 return -EBADF;
b7620121 2566 fd = array_index_nospec(fd, ctx->nr_user_files);
65e19f54
JA
2567 req->file = io_file_from_index(ctx, fd);
2568 if (!req->file)
08a45173 2569 return -EBADF;
09bb8394
JA
2570 req->flags |= REQ_F_FIXED_FILE;
2571 } else {
2572 if (s->needs_fixed_file)
2573 return -EBADF;
c826bd7a 2574 trace_io_uring_file_get(ctx, fd);
09bb8394
JA
2575 req->file = io_file_get(state, fd);
2576 if (unlikely(!req->file))
2577 return -EBADF;
2578 }
2579
2580 return 0;
2581}
2582
fcb323cc
JA
2583static int io_grab_files(struct io_ring_ctx *ctx, struct io_kiocb *req)
2584{
2585 int ret = -EBADF;
2586
2587 rcu_read_lock();
2588 spin_lock_irq(&ctx->inflight_lock);
2589 /*
2590 * We use the f_ops->flush() handler to ensure that we can flush
2591 * out work accessing these files if the fd is closed. Check if
2592 * the fd has changed since we started down this path, and disallow
2593 * this operation if it has.
2594 */
2595 if (fcheck(req->submit.ring_fd) == req->submit.ring_file) {
2596 list_add(&req->inflight_entry, &ctx->inflight_list);
2597 req->flags |= REQ_F_INFLIGHT;
2598 req->work.files = current->files;
2599 ret = 0;
2600 }
2601 spin_unlock_irq(&ctx->inflight_lock);
2602 rcu_read_unlock();
2603
2604 return ret;
2605}
2606
2665abfd
JA
2607static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
2608{
2609 struct io_kiocb *req = container_of(timer, struct io_kiocb,
2610 timeout.timer);
2611 struct io_ring_ctx *ctx = req->ctx;
2612 struct io_kiocb *prev = NULL;
2613 unsigned long flags;
2614 int ret = -ETIME;
2615
2616 spin_lock_irqsave(&ctx->completion_lock, flags);
2617
2618 /*
2619 * We don't expect the list to be empty, that will only happen if we
2620 * race with the completion of the linked work.
2621 */
2622 if (!list_empty(&req->list)) {
2623 prev = list_entry(req->list.prev, struct io_kiocb, link_list);
2624 list_del_init(&req->list);
2625 }
2626
2627 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2628
2629 if (prev) {
2630 void *user_data = (void *) (unsigned long) prev->user_data;
2631 ret = io_async_cancel_one(ctx, user_data);
2632 }
2633
78e19bbe 2634 io_cqring_add_event(req, ret);
2665abfd
JA
2635 io_put_req(req, NULL);
2636 return HRTIMER_NORESTART;
2637}
2638
2639static int io_queue_linked_timeout(struct io_kiocb *req, struct io_kiocb *nxt)
2640{
2641 const struct io_uring_sqe *sqe = nxt->submit.sqe;
2642 enum hrtimer_mode mode;
2643 struct timespec64 ts;
2644 int ret = -EINVAL;
2645
2646 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 || sqe->off)
2647 goto err;
2648 if (sqe->timeout_flags & ~IORING_TIMEOUT_ABS)
2649 goto err;
2650 if (get_timespec64(&ts, u64_to_user_ptr(sqe->addr))) {
2651 ret = -EFAULT;
2652 goto err;
2653 }
2654
2655 req->flags |= REQ_F_LINK_TIMEOUT;
2656
2657 if (sqe->timeout_flags & IORING_TIMEOUT_ABS)
2658 mode = HRTIMER_MODE_ABS;
2659 else
2660 mode = HRTIMER_MODE_REL;
2661 hrtimer_init(&nxt->timeout.timer, CLOCK_MONOTONIC, mode);
2662 nxt->timeout.timer.function = io_link_timeout_fn;
2663 hrtimer_start(&nxt->timeout.timer, timespec64_to_ktime(ts), mode);
2664 ret = 0;
2665err:
2666 /* drop submission reference */
2667 io_put_req(nxt, NULL);
2668
2669 if (ret) {
2670 struct io_ring_ctx *ctx = req->ctx;
2671
2672 /*
2673 * Break the link and fail linked timeout, parent will get
2674 * failed by the regular submission path.
2675 */
2676 list_del(&nxt->list);
78e19bbe 2677 io_cqring_fill_event(nxt, ret);
2665abfd
JA
2678 trace_io_uring_fail_link(req, nxt);
2679 io_commit_cqring(ctx);
2680 io_put_req(nxt, NULL);
2681 ret = -ECANCELED;
2682 }
2683
2684 return ret;
2685}
2686
2687static inline struct io_kiocb *io_get_linked_timeout(struct io_kiocb *req)
2688{
2689 struct io_kiocb *nxt;
2690
2691 if (!(req->flags & REQ_F_LINK))
2692 return NULL;
2693
2694 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb, list);
2695 if (nxt && nxt->submit.sqe->opcode == IORING_OP_LINK_TIMEOUT)
2696 return nxt;
2697
2698 return NULL;
2699}
2700
267bc904 2701static int __io_queue_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req)
2b188cc1 2702{
2665abfd 2703 struct io_kiocb *nxt;
e0c5c576 2704 int ret;
2b188cc1 2705
2665abfd
JA
2706 nxt = io_get_linked_timeout(req);
2707 if (unlikely(nxt)) {
2708 ret = io_queue_linked_timeout(req, nxt);
2709 if (ret)
2710 goto err;
2711 }
2712
267bc904 2713 ret = __io_submit_sqe(ctx, req, NULL, true);
491381ce
JA
2714
2715 /*
2716 * We async punt it if the file wasn't marked NOWAIT, or if the file
2717 * doesn't support non-blocking read/write attempts
2718 */
2719 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
2720 (req->flags & REQ_F_MUST_PUNT))) {
267bc904 2721 struct sqe_submit *s = &req->submit;
2b188cc1
JA
2722 struct io_uring_sqe *sqe_copy;
2723
954dab19 2724 sqe_copy = kmemdup(s->sqe, sizeof(*sqe_copy), GFP_KERNEL);
2b188cc1 2725 if (sqe_copy) {
2b188cc1 2726 s->sqe = sqe_copy;
fcb323cc
JA
2727 if (req->work.flags & IO_WQ_WORK_NEEDS_FILES) {
2728 ret = io_grab_files(ctx, req);
2729 if (ret) {
2730 kfree(sqe_copy);
2731 goto err;
2732 }
2733 }
e65ef56d
JA
2734
2735 /*
2736 * Queued up for async execution, worker will release
9e645e11 2737 * submit reference when the iocb is actually submitted.
e65ef56d 2738 */
fcb323cc 2739 io_queue_async_work(ctx, req);
e65ef56d 2740 return 0;
2b188cc1
JA
2741 }
2742 }
e65ef56d
JA
2743
2744 /* drop submission reference */
fcb323cc 2745err:
ba816ad6 2746 io_put_req(req, NULL);
e65ef56d
JA
2747
2748 /* and drop final reference, if we failed */
9e645e11 2749 if (ret) {
78e19bbe 2750 io_cqring_add_event(req, ret);
9e645e11
JA
2751 if (req->flags & REQ_F_LINK)
2752 req->flags |= REQ_F_FAIL_LINK;
ba816ad6 2753 io_put_req(req, NULL);
9e645e11 2754 }
2b188cc1
JA
2755
2756 return ret;
2757}
2758
267bc904 2759static int io_queue_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req)
4fe2c963
JL
2760{
2761 int ret;
2762
267bc904 2763 ret = io_req_defer(ctx, req);
4fe2c963
JL
2764 if (ret) {
2765 if (ret != -EIOCBQUEUED) {
78e19bbe
JA
2766 io_cqring_add_event(req, ret);
2767 io_double_put_req(req);
4fe2c963
JL
2768 }
2769 return 0;
2770 }
2771
267bc904 2772 return __io_queue_sqe(ctx, req);
4fe2c963
JL
2773}
2774
2775static int io_queue_link_head(struct io_ring_ctx *ctx, struct io_kiocb *req,
267bc904 2776 struct io_kiocb *shadow)
4fe2c963
JL
2777{
2778 int ret;
2779 int need_submit = false;
2780
2781 if (!shadow)
267bc904 2782 return io_queue_sqe(ctx, req);
4fe2c963
JL
2783
2784 /*
2785 * Mark the first IO in link list as DRAIN, let all the following
2786 * IOs enter the defer list. all IO needs to be completed before link
2787 * list.
2788 */
2789 req->flags |= REQ_F_IO_DRAIN;
267bc904 2790 ret = io_req_defer(ctx, req);
4fe2c963
JL
2791 if (ret) {
2792 if (ret != -EIOCBQUEUED) {
78e19bbe
JA
2793 io_cqring_add_event(req, ret);
2794 io_double_put_req(req);
7b20238d 2795 __io_free_req(shadow);
4fe2c963
JL
2796 return 0;
2797 }
2798 } else {
2799 /*
2800 * If ret == 0 means that all IOs in front of link io are
2801 * running done. let's queue link head.
2802 */
2803 need_submit = true;
2804 }
2805
2806 /* Insert shadow req to defer_list, blocking next IOs */
2807 spin_lock_irq(&ctx->completion_lock);
c826bd7a 2808 trace_io_uring_defer(ctx, shadow, true);
4fe2c963
JL
2809 list_add_tail(&shadow->list, &ctx->defer_list);
2810 spin_unlock_irq(&ctx->completion_lock);
2811
2812 if (need_submit)
267bc904 2813 return __io_queue_sqe(ctx, req);
4fe2c963
JL
2814
2815 return 0;
2816}
2817
9e645e11
JA
2818#define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK)
2819
196be95c 2820static void io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
267bc904 2821 struct io_submit_state *state, struct io_kiocb **link)
9e645e11
JA
2822{
2823 struct io_uring_sqe *sqe_copy;
267bc904 2824 struct sqe_submit *s = &req->submit;
9e645e11
JA
2825 int ret;
2826
78e19bbe
JA
2827 req->user_data = s->sqe->user_data;
2828
9e645e11
JA
2829 /* enforce forwards compatibility on users */
2830 if (unlikely(s->sqe->flags & ~SQE_VALID_FLAGS)) {
2831 ret = -EINVAL;
196be95c 2832 goto err_req;
9e645e11
JA
2833 }
2834
267bc904 2835 ret = io_req_set_file(ctx, state, req);
9e645e11
JA
2836 if (unlikely(ret)) {
2837err_req:
78e19bbe
JA
2838 io_cqring_add_event(req, ret);
2839 io_double_put_req(req);
9e645e11
JA
2840 return;
2841 }
2842
9e645e11
JA
2843 /*
2844 * If we already have a head request, queue this one for async
2845 * submittal once the head completes. If we don't have a head but
2846 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
2847 * submitted sync once the chain is complete. If none of those
2848 * conditions are true (normal request), then just queue it.
2849 */
2850 if (*link) {
2851 struct io_kiocb *prev = *link;
2852
2853 sqe_copy = kmemdup(s->sqe, sizeof(*sqe_copy), GFP_KERNEL);
2854 if (!sqe_copy) {
2855 ret = -EAGAIN;
2856 goto err_req;
2857 }
2858
2859 s->sqe = sqe_copy;
c826bd7a 2860 trace_io_uring_link(ctx, req, prev);
9e645e11
JA
2861 list_add_tail(&req->list, &prev->link_list);
2862 } else if (s->sqe->flags & IOSQE_IO_LINK) {
2863 req->flags |= REQ_F_LINK;
2864
9e645e11
JA
2865 INIT_LIST_HEAD(&req->link_list);
2866 *link = req;
2665abfd
JA
2867 } else if (READ_ONCE(s->sqe->opcode) == IORING_OP_LINK_TIMEOUT) {
2868 /* Only valid as a linked SQE */
2869 ret = -EINVAL;
2870 goto err_req;
9e645e11 2871 } else {
267bc904 2872 io_queue_sqe(ctx, req);
9e645e11
JA
2873 }
2874}
2875
9a56a232
JA
2876/*
2877 * Batched submission is done, ensure local IO is flushed out.
2878 */
2879static void io_submit_state_end(struct io_submit_state *state)
2880{
2881 blk_finish_plug(&state->plug);
3d6770fb 2882 io_file_put(state);
2579f913
JA
2883 if (state->free_reqs)
2884 kmem_cache_free_bulk(req_cachep, state->free_reqs,
2885 &state->reqs[state->cur_req]);
9a56a232
JA
2886}
2887
2888/*
2889 * Start submission side cache.
2890 */
2891static void io_submit_state_start(struct io_submit_state *state,
2892 struct io_ring_ctx *ctx, unsigned max_ios)
2893{
2894 blk_start_plug(&state->plug);
2579f913 2895 state->free_reqs = 0;
9a56a232
JA
2896 state->file = NULL;
2897 state->ios_left = max_ios;
2898}
2899
2b188cc1
JA
2900static void io_commit_sqring(struct io_ring_ctx *ctx)
2901{
75b28aff 2902 struct io_rings *rings = ctx->rings;
2b188cc1 2903
75b28aff 2904 if (ctx->cached_sq_head != READ_ONCE(rings->sq.head)) {
2b188cc1
JA
2905 /*
2906 * Ensure any loads from the SQEs are done at this point,
2907 * since once we write the new head, the application could
2908 * write new data to them.
2909 */
75b28aff 2910 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2b188cc1
JA
2911 }
2912}
2913
2b188cc1
JA
2914/*
2915 * Fetch an sqe, if one is available. Note that s->sqe will point to memory
2916 * that is mapped by userspace. This means that care needs to be taken to
2917 * ensure that reads are stable, as we cannot rely on userspace always
2918 * being a good citizen. If members of the sqe are validated and then later
2919 * used, it's important that those reads are done through READ_ONCE() to
2920 * prevent a re-load down the line.
2921 */
2922static bool io_get_sqring(struct io_ring_ctx *ctx, struct sqe_submit *s)
2923{
75b28aff
HV
2924 struct io_rings *rings = ctx->rings;
2925 u32 *sq_array = ctx->sq_array;
2b188cc1
JA
2926 unsigned head;
2927
2928 /*
2929 * The cached sq head (or cq tail) serves two purposes:
2930 *
2931 * 1) allows us to batch the cost of updating the user visible
2932 * head updates.
2933 * 2) allows the kernel side to track the head on its own, even
2934 * though the application is the one updating it.
2935 */
2936 head = ctx->cached_sq_head;
e523a29c 2937 /* make sure SQ entry isn't read before tail */
75b28aff 2938 if (head == smp_load_acquire(&rings->sq.tail))
2b188cc1
JA
2939 return false;
2940
75b28aff 2941 head = READ_ONCE(sq_array[head & ctx->sq_mask]);
2b188cc1 2942 if (head < ctx->sq_entries) {
fcb323cc 2943 s->ring_file = NULL;
2b188cc1 2944 s->sqe = &ctx->sq_sqes[head];
8776f3fa 2945 s->sequence = ctx->cached_sq_head;
2b188cc1
JA
2946 ctx->cached_sq_head++;
2947 return true;
2948 }
2949
2950 /* drop invalid entries */
2951 ctx->cached_sq_head++;
498ccd9e
JA
2952 ctx->cached_sq_dropped++;
2953 WRITE_ONCE(rings->sq_dropped, ctx->cached_sq_dropped);
2b188cc1
JA
2954 return false;
2955}
2956
fb5ccc98 2957static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
ae9428ca
PB
2958 struct file *ring_file, int ring_fd,
2959 struct mm_struct **mm, bool async)
6c271ce2
JA
2960{
2961 struct io_submit_state state, *statep = NULL;
9e645e11 2962 struct io_kiocb *link = NULL;
4fe2c963 2963 struct io_kiocb *shadow_req = NULL;
9e645e11 2964 int i, submitted = 0;
95a1b3ff 2965 bool mm_fault = false;
6c271ce2 2966
1d7bb1d5
JA
2967 if (!list_empty(&ctx->cq_overflow_list)) {
2968 io_cqring_overflow_flush(ctx, false);
2969 return -EBUSY;
2970 }
2971
6c271ce2
JA
2972 if (nr > IO_PLUG_THRESHOLD) {
2973 io_submit_state_start(&state, ctx, nr);
2974 statep = &state;
2975 }
2976
2977 for (i = 0; i < nr; i++) {
196be95c 2978 struct io_kiocb *req;
50585b9a 2979 unsigned int sqe_flags;
fb5ccc98 2980
196be95c
PB
2981 req = io_get_req(ctx, statep);
2982 if (unlikely(!req)) {
2983 if (!submitted)
2984 submitted = -EAGAIN;
fb5ccc98 2985 break;
196be95c 2986 }
50585b9a 2987 if (!io_get_sqring(ctx, &req->submit)) {
196be95c
PB
2988 __io_free_req(req);
2989 break;
2990 }
fb5ccc98 2991
50585b9a 2992 if (io_sqe_needs_user(req->submit.sqe) && !*mm) {
95a1b3ff
PB
2993 mm_fault = mm_fault || !mmget_not_zero(ctx->sqo_mm);
2994 if (!mm_fault) {
2995 use_mm(ctx->sqo_mm);
2996 *mm = ctx->sqo_mm;
2997 }
2998 }
2999
50585b9a
PB
3000 sqe_flags = req->submit.sqe->flags;
3001
3002 if (link && (sqe_flags & IOSQE_IO_DRAIN)) {
4fe2c963
JL
3003 if (!shadow_req) {
3004 shadow_req = io_get_req(ctx, NULL);
a1041c27
JL
3005 if (unlikely(!shadow_req))
3006 goto out;
4fe2c963
JL
3007 shadow_req->flags |= (REQ_F_IO_DRAIN | REQ_F_SHADOW_DRAIN);
3008 refcount_dec(&shadow_req->refs);
3009 }
50585b9a 3010 shadow_req->sequence = req->submit.sequence;
4fe2c963
JL
3011 }
3012
a1041c27 3013out:
50585b9a
PB
3014 req->submit.ring_file = ring_file;
3015 req->submit.ring_fd = ring_fd;
3016 req->submit.has_user = *mm != NULL;
3017 req->submit.in_async = async;
3018 req->submit.needs_fixed_file = async;
3019 trace_io_uring_submit_sqe(ctx, req->submit.sqe->user_data,
3020 true, async);
267bc904 3021 io_submit_sqe(ctx, req, statep, &link);
95a1b3ff 3022 submitted++;
e5eb6366
PB
3023
3024 /*
3025 * If previous wasn't linked and we have a linked command,
3026 * that's the end of the chain. Submit the previous link.
3027 */
50585b9a 3028 if (!(sqe_flags & IOSQE_IO_LINK) && link) {
267bc904 3029 io_queue_link_head(ctx, link, shadow_req);
e5eb6366
PB
3030 link = NULL;
3031 shadow_req = NULL;
3032 }
6c271ce2
JA
3033 }
3034
9e645e11 3035 if (link)
267bc904 3036 io_queue_link_head(ctx, link, shadow_req);
6c271ce2
JA
3037 if (statep)
3038 io_submit_state_end(&state);
3039
ae9428ca
PB
3040 /* Commit SQ ring head once we've consumed and submitted all SQEs */
3041 io_commit_sqring(ctx);
3042
6c271ce2
JA
3043 return submitted;
3044}
3045
3046static int io_sq_thread(void *data)
3047{
6c271ce2
JA
3048 struct io_ring_ctx *ctx = data;
3049 struct mm_struct *cur_mm = NULL;
3050 mm_segment_t old_fs;
3051 DEFINE_WAIT(wait);
3052 unsigned inflight;
3053 unsigned long timeout;
3054
206aefde 3055 complete(&ctx->completions[1]);
a4c0b3de 3056
6c271ce2
JA
3057 old_fs = get_fs();
3058 set_fs(USER_DS);
3059
3060 timeout = inflight = 0;
2bbcd6d3 3061 while (!kthread_should_park()) {
fb5ccc98 3062 unsigned int to_submit;
1d7bb1d5 3063 int ret;
6c271ce2
JA
3064
3065 if (inflight) {
3066 unsigned nr_events = 0;
3067
3068 if (ctx->flags & IORING_SETUP_IOPOLL) {
2b2ed975
JA
3069 /*
3070 * inflight is the count of the maximum possible
3071 * entries we submitted, but it can be smaller
3072 * if we dropped some of them. If we don't have
3073 * poll entries available, then we know that we
3074 * have nothing left to poll for. Reset the
3075 * inflight count to zero in that case.
3076 */
3077 mutex_lock(&ctx->uring_lock);
3078 if (!list_empty(&ctx->poll_list))
3079 __io_iopoll_check(ctx, &nr_events, 0);
3080 else
3081 inflight = 0;
3082 mutex_unlock(&ctx->uring_lock);
6c271ce2
JA
3083 } else {
3084 /*
3085 * Normal IO, just pretend everything completed.
3086 * We don't have to poll completions for that.
3087 */
3088 nr_events = inflight;
3089 }
3090
3091 inflight -= nr_events;
3092 if (!inflight)
3093 timeout = jiffies + ctx->sq_thread_idle;
3094 }
3095
fb5ccc98
PB
3096 to_submit = io_sqring_entries(ctx);
3097 if (!to_submit) {
6c271ce2
JA
3098 /*
3099 * We're polling. If we're within the defined idle
3100 * period, then let us spin without work before going
3101 * to sleep.
3102 */
3103 if (inflight || !time_after(jiffies, timeout)) {
9831a90c 3104 cond_resched();
6c271ce2
JA
3105 continue;
3106 }
3107
3108 /*
3109 * Drop cur_mm before scheduling, we can't hold it for
3110 * long periods (or over schedule()). Do this before
3111 * adding ourselves to the waitqueue, as the unuse/drop
3112 * may sleep.
3113 */
3114 if (cur_mm) {
3115 unuse_mm(cur_mm);
3116 mmput(cur_mm);
3117 cur_mm = NULL;
3118 }
3119
3120 prepare_to_wait(&ctx->sqo_wait, &wait,
3121 TASK_INTERRUPTIBLE);
3122
3123 /* Tell userspace we may need a wakeup call */
75b28aff 3124 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
0d7bae69
SB
3125 /* make sure to read SQ tail after writing flags */
3126 smp_mb();
6c271ce2 3127
fb5ccc98
PB
3128 to_submit = io_sqring_entries(ctx);
3129 if (!to_submit) {
2bbcd6d3 3130 if (kthread_should_park()) {
6c271ce2
JA
3131 finish_wait(&ctx->sqo_wait, &wait);
3132 break;
3133 }
3134 if (signal_pending(current))
3135 flush_signals(current);
3136 schedule();
3137 finish_wait(&ctx->sqo_wait, &wait);
3138
75b28aff 3139 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6c271ce2
JA
3140 continue;
3141 }
3142 finish_wait(&ctx->sqo_wait, &wait);
3143
75b28aff 3144 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6c271ce2
JA
3145 }
3146
fb5ccc98 3147 to_submit = min(to_submit, ctx->sq_entries);
1d7bb1d5
JA
3148 ret = io_submit_sqes(ctx, to_submit, NULL, -1, &cur_mm, true);
3149 if (ret > 0)
3150 inflight += ret;
6c271ce2
JA
3151 }
3152
3153 set_fs(old_fs);
3154 if (cur_mm) {
3155 unuse_mm(cur_mm);
3156 mmput(cur_mm);
3157 }
06058632 3158
2bbcd6d3 3159 kthread_parkme();
06058632 3160
6c271ce2
JA
3161 return 0;
3162}
3163
bda52162
JA
3164struct io_wait_queue {
3165 struct wait_queue_entry wq;
3166 struct io_ring_ctx *ctx;
3167 unsigned to_wait;
3168 unsigned nr_timeouts;
3169};
3170
1d7bb1d5 3171static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
bda52162
JA
3172{
3173 struct io_ring_ctx *ctx = iowq->ctx;
3174
3175 /*
3176 * Wake up if we have enough events, or if a timeout occured since we
3177 * started waiting. For timeouts, we always want to return to userspace,
3178 * regardless of event count.
3179 */
1d7bb1d5 3180 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
bda52162
JA
3181 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
3182}
3183
3184static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
3185 int wake_flags, void *key)
3186{
3187 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
3188 wq);
3189
1d7bb1d5
JA
3190 /* use noflush == true, as we can't safely rely on locking context */
3191 if (!io_should_wake(iowq, true))
bda52162
JA
3192 return -1;
3193
3194 return autoremove_wake_function(curr, mode, wake_flags, key);
3195}
3196
2b188cc1
JA
3197/*
3198 * Wait until events become available, if we don't already have some. The
3199 * application must reap them itself, as they reside on the shared cq ring.
3200 */
3201static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
3202 const sigset_t __user *sig, size_t sigsz)
3203{
bda52162
JA
3204 struct io_wait_queue iowq = {
3205 .wq = {
3206 .private = current,
3207 .func = io_wake_function,
3208 .entry = LIST_HEAD_INIT(iowq.wq.entry),
3209 },
3210 .ctx = ctx,
3211 .to_wait = min_events,
3212 };
75b28aff 3213 struct io_rings *rings = ctx->rings;
e9ffa5c2 3214 int ret = 0;
2b188cc1 3215
1d7bb1d5 3216 if (io_cqring_events(ctx, false) >= min_events)
2b188cc1
JA
3217 return 0;
3218
3219 if (sig) {
9e75ad5d
AB
3220#ifdef CONFIG_COMPAT
3221 if (in_compat_syscall())
3222 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
b772434b 3223 sigsz);
9e75ad5d
AB
3224 else
3225#endif
b772434b 3226 ret = set_user_sigmask(sig, sigsz);
9e75ad5d 3227
2b188cc1
JA
3228 if (ret)
3229 return ret;
3230 }
3231
bda52162 3232 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
c826bd7a 3233 trace_io_uring_cqring_wait(ctx, min_events);
bda52162
JA
3234 do {
3235 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
3236 TASK_INTERRUPTIBLE);
1d7bb1d5 3237 if (io_should_wake(&iowq, false))
bda52162
JA
3238 break;
3239 schedule();
3240 if (signal_pending(current)) {
e9ffa5c2 3241 ret = -EINTR;
bda52162
JA
3242 break;
3243 }
3244 } while (1);
3245 finish_wait(&ctx->wait, &iowq.wq);
3246
e9ffa5c2 3247 restore_saved_sigmask_unless(ret == -EINTR);
2b188cc1 3248
75b28aff 3249 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
2b188cc1
JA
3250}
3251
6b06314c
JA
3252static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
3253{
3254#if defined(CONFIG_UNIX)
3255 if (ctx->ring_sock) {
3256 struct sock *sock = ctx->ring_sock->sk;
3257 struct sk_buff *skb;
3258
3259 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
3260 kfree_skb(skb);
3261 }
3262#else
3263 int i;
3264
65e19f54
JA
3265 for (i = 0; i < ctx->nr_user_files; i++) {
3266 struct file *file;
3267
3268 file = io_file_from_index(ctx, i);
3269 if (file)
3270 fput(file);
3271 }
6b06314c
JA
3272#endif
3273}
3274
3275static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
3276{
65e19f54
JA
3277 unsigned nr_tables, i;
3278
3279 if (!ctx->file_table)
6b06314c
JA
3280 return -ENXIO;
3281
3282 __io_sqe_files_unregister(ctx);
65e19f54
JA
3283 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
3284 for (i = 0; i < nr_tables; i++)
3285 kfree(ctx->file_table[i].files);
3286 kfree(ctx->file_table);
3287 ctx->file_table = NULL;
6b06314c
JA
3288 ctx->nr_user_files = 0;
3289 return 0;
3290}
3291
6c271ce2
JA
3292static void io_sq_thread_stop(struct io_ring_ctx *ctx)
3293{
3294 if (ctx->sqo_thread) {
206aefde 3295 wait_for_completion(&ctx->completions[1]);
2bbcd6d3
RP
3296 /*
3297 * The park is a bit of a work-around, without it we get
3298 * warning spews on shutdown with SQPOLL set and affinity
3299 * set to a single CPU.
3300 */
06058632 3301 kthread_park(ctx->sqo_thread);
6c271ce2
JA
3302 kthread_stop(ctx->sqo_thread);
3303 ctx->sqo_thread = NULL;
3304 }
3305}
3306
6b06314c
JA
3307static void io_finish_async(struct io_ring_ctx *ctx)
3308{
6c271ce2
JA
3309 io_sq_thread_stop(ctx);
3310
561fb04a
JA
3311 if (ctx->io_wq) {
3312 io_wq_destroy(ctx->io_wq);
3313 ctx->io_wq = NULL;
6b06314c
JA
3314 }
3315}
3316
3317#if defined(CONFIG_UNIX)
3318static void io_destruct_skb(struct sk_buff *skb)
3319{
3320 struct io_ring_ctx *ctx = skb->sk->sk_user_data;
8a997340 3321
561fb04a
JA
3322 if (ctx->io_wq)
3323 io_wq_flush(ctx->io_wq);
6b06314c 3324
6b06314c
JA
3325 unix_destruct_scm(skb);
3326}
3327
3328/*
3329 * Ensure the UNIX gc is aware of our file set, so we are certain that
3330 * the io_uring can be safely unregistered on process exit, even if we have
3331 * loops in the file referencing.
3332 */
3333static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
3334{
3335 struct sock *sk = ctx->ring_sock->sk;
3336 struct scm_fp_list *fpl;
3337 struct sk_buff *skb;
08a45173 3338 int i, nr_files;
6b06314c
JA
3339
3340 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
3341 unsigned long inflight = ctx->user->unix_inflight + nr;
3342
3343 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
3344 return -EMFILE;
3345 }
3346
3347 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
3348 if (!fpl)
3349 return -ENOMEM;
3350
3351 skb = alloc_skb(0, GFP_KERNEL);
3352 if (!skb) {
3353 kfree(fpl);
3354 return -ENOMEM;
3355 }
3356
3357 skb->sk = sk;
6b06314c 3358
08a45173 3359 nr_files = 0;
6b06314c
JA
3360 fpl->user = get_uid(ctx->user);
3361 for (i = 0; i < nr; i++) {
65e19f54
JA
3362 struct file *file = io_file_from_index(ctx, i + offset);
3363
3364 if (!file)
08a45173 3365 continue;
65e19f54 3366 fpl->fp[nr_files] = get_file(file);
08a45173
JA
3367 unix_inflight(fpl->user, fpl->fp[nr_files]);
3368 nr_files++;
6b06314c
JA
3369 }
3370
08a45173
JA
3371 if (nr_files) {
3372 fpl->max = SCM_MAX_FD;
3373 fpl->count = nr_files;
3374 UNIXCB(skb).fp = fpl;
3375 skb->destructor = io_destruct_skb;
3376 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
3377 skb_queue_head(&sk->sk_receive_queue, skb);
6b06314c 3378
08a45173
JA
3379 for (i = 0; i < nr_files; i++)
3380 fput(fpl->fp[i]);
3381 } else {
3382 kfree_skb(skb);
3383 kfree(fpl);
3384 }
6b06314c
JA
3385
3386 return 0;
3387}
3388
3389/*
3390 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
3391 * causes regular reference counting to break down. We rely on the UNIX
3392 * garbage collection to take care of this problem for us.
3393 */
3394static int io_sqe_files_scm(struct io_ring_ctx *ctx)
3395{
3396 unsigned left, total;
3397 int ret = 0;
3398
3399 total = 0;
3400 left = ctx->nr_user_files;
3401 while (left) {
3402 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
6b06314c
JA
3403
3404 ret = __io_sqe_files_scm(ctx, this_files, total);
3405 if (ret)
3406 break;
3407 left -= this_files;
3408 total += this_files;
3409 }
3410
3411 if (!ret)
3412 return 0;
3413
3414 while (total < ctx->nr_user_files) {
65e19f54
JA
3415 struct file *file = io_file_from_index(ctx, total);
3416
3417 if (file)
3418 fput(file);
6b06314c
JA
3419 total++;
3420 }
3421
3422 return ret;
3423}
3424#else
3425static int io_sqe_files_scm(struct io_ring_ctx *ctx)
3426{
3427 return 0;
3428}
3429#endif
3430
65e19f54
JA
3431static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
3432 unsigned nr_files)
3433{
3434 int i;
3435
3436 for (i = 0; i < nr_tables; i++) {
3437 struct fixed_file_table *table = &ctx->file_table[i];
3438 unsigned this_files;
3439
3440 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
3441 table->files = kcalloc(this_files, sizeof(struct file *),
3442 GFP_KERNEL);
3443 if (!table->files)
3444 break;
3445 nr_files -= this_files;
3446 }
3447
3448 if (i == nr_tables)
3449 return 0;
3450
3451 for (i = 0; i < nr_tables; i++) {
3452 struct fixed_file_table *table = &ctx->file_table[i];
3453 kfree(table->files);
3454 }
3455 return 1;
3456}
3457
6b06314c
JA
3458static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
3459 unsigned nr_args)
3460{
3461 __s32 __user *fds = (__s32 __user *) arg;
65e19f54 3462 unsigned nr_tables;
6b06314c
JA
3463 int fd, ret = 0;
3464 unsigned i;
3465
65e19f54 3466 if (ctx->file_table)
6b06314c
JA
3467 return -EBUSY;
3468 if (!nr_args)
3469 return -EINVAL;
3470 if (nr_args > IORING_MAX_FIXED_FILES)
3471 return -EMFILE;
3472
65e19f54
JA
3473 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
3474 ctx->file_table = kcalloc(nr_tables, sizeof(struct fixed_file_table),
3475 GFP_KERNEL);
3476 if (!ctx->file_table)
6b06314c
JA
3477 return -ENOMEM;
3478
65e19f54
JA
3479 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
3480 kfree(ctx->file_table);
3481 return -ENOMEM;
3482 }
3483
08a45173 3484 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
65e19f54
JA
3485 struct fixed_file_table *table;
3486 unsigned index;
3487
6b06314c
JA
3488 ret = -EFAULT;
3489 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
3490 break;
08a45173
JA
3491 /* allow sparse sets */
3492 if (fd == -1) {
3493 ret = 0;
3494 continue;
3495 }
6b06314c 3496
65e19f54
JA
3497 table = &ctx->file_table[i >> IORING_FILE_TABLE_SHIFT];
3498 index = i & IORING_FILE_TABLE_MASK;
3499 table->files[index] = fget(fd);
6b06314c
JA
3500
3501 ret = -EBADF;
65e19f54 3502 if (!table->files[index])
6b06314c
JA
3503 break;
3504 /*
3505 * Don't allow io_uring instances to be registered. If UNIX
3506 * isn't enabled, then this causes a reference cycle and this
3507 * instance can never get freed. If UNIX is enabled we'll
3508 * handle it just fine, but there's still no point in allowing
3509 * a ring fd as it doesn't support regular read/write anyway.
3510 */
65e19f54
JA
3511 if (table->files[index]->f_op == &io_uring_fops) {
3512 fput(table->files[index]);
6b06314c
JA
3513 break;
3514 }
6b06314c
JA
3515 ret = 0;
3516 }
3517
3518 if (ret) {
65e19f54
JA
3519 for (i = 0; i < ctx->nr_user_files; i++) {
3520 struct file *file;
6b06314c 3521
65e19f54
JA
3522 file = io_file_from_index(ctx, i);
3523 if (file)
3524 fput(file);
3525 }
3526 for (i = 0; i < nr_tables; i++)
3527 kfree(ctx->file_table[i].files);
3528
3529 kfree(ctx->file_table);
3530 ctx->file_table = NULL;
6b06314c
JA
3531 ctx->nr_user_files = 0;
3532 return ret;
3533 }
3534
3535 ret = io_sqe_files_scm(ctx);
3536 if (ret)
3537 io_sqe_files_unregister(ctx);
3538
3539 return ret;
3540}
3541
c3a31e60
JA
3542static void io_sqe_file_unregister(struct io_ring_ctx *ctx, int index)
3543{
3544#if defined(CONFIG_UNIX)
65e19f54 3545 struct file *file = io_file_from_index(ctx, index);
c3a31e60
JA
3546 struct sock *sock = ctx->ring_sock->sk;
3547 struct sk_buff_head list, *head = &sock->sk_receive_queue;
3548 struct sk_buff *skb;
3549 int i;
3550
3551 __skb_queue_head_init(&list);
3552
3553 /*
3554 * Find the skb that holds this file in its SCM_RIGHTS. When found,
3555 * remove this entry and rearrange the file array.
3556 */
3557 skb = skb_dequeue(head);
3558 while (skb) {
3559 struct scm_fp_list *fp;
3560
3561 fp = UNIXCB(skb).fp;
3562 for (i = 0; i < fp->count; i++) {
3563 int left;
3564
3565 if (fp->fp[i] != file)
3566 continue;
3567
3568 unix_notinflight(fp->user, fp->fp[i]);
3569 left = fp->count - 1 - i;
3570 if (left) {
3571 memmove(&fp->fp[i], &fp->fp[i + 1],
3572 left * sizeof(struct file *));
3573 }
3574 fp->count--;
3575 if (!fp->count) {
3576 kfree_skb(skb);
3577 skb = NULL;
3578 } else {
3579 __skb_queue_tail(&list, skb);
3580 }
3581 fput(file);
3582 file = NULL;
3583 break;
3584 }
3585
3586 if (!file)
3587 break;
3588
3589 __skb_queue_tail(&list, skb);
3590
3591 skb = skb_dequeue(head);
3592 }
3593
3594 if (skb_peek(&list)) {
3595 spin_lock_irq(&head->lock);
3596 while ((skb = __skb_dequeue(&list)) != NULL)
3597 __skb_queue_tail(head, skb);
3598 spin_unlock_irq(&head->lock);
3599 }
3600#else
65e19f54 3601 fput(io_file_from_index(ctx, index));
c3a31e60
JA
3602#endif
3603}
3604
3605static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
3606 int index)
3607{
3608#if defined(CONFIG_UNIX)
3609 struct sock *sock = ctx->ring_sock->sk;
3610 struct sk_buff_head *head = &sock->sk_receive_queue;
3611 struct sk_buff *skb;
3612
3613 /*
3614 * See if we can merge this file into an existing skb SCM_RIGHTS
3615 * file set. If there's no room, fall back to allocating a new skb
3616 * and filling it in.
3617 */
3618 spin_lock_irq(&head->lock);
3619 skb = skb_peek(head);
3620 if (skb) {
3621 struct scm_fp_list *fpl = UNIXCB(skb).fp;
3622
3623 if (fpl->count < SCM_MAX_FD) {
3624 __skb_unlink(skb, head);
3625 spin_unlock_irq(&head->lock);
3626 fpl->fp[fpl->count] = get_file(file);
3627 unix_inflight(fpl->user, fpl->fp[fpl->count]);
3628 fpl->count++;
3629 spin_lock_irq(&head->lock);
3630 __skb_queue_head(head, skb);
3631 } else {
3632 skb = NULL;
3633 }
3634 }
3635 spin_unlock_irq(&head->lock);
3636
3637 if (skb) {
3638 fput(file);
3639 return 0;
3640 }
3641
3642 return __io_sqe_files_scm(ctx, 1, index);
3643#else
3644 return 0;
3645#endif
3646}
3647
3648static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
3649 unsigned nr_args)
3650{
3651 struct io_uring_files_update up;
3652 __s32 __user *fds;
3653 int fd, i, err;
3654 __u32 done;
3655
65e19f54 3656 if (!ctx->file_table)
c3a31e60
JA
3657 return -ENXIO;
3658 if (!nr_args)
3659 return -EINVAL;
3660 if (copy_from_user(&up, arg, sizeof(up)))
3661 return -EFAULT;
3662 if (check_add_overflow(up.offset, nr_args, &done))
3663 return -EOVERFLOW;
3664 if (done > ctx->nr_user_files)
3665 return -EINVAL;
3666
3667 done = 0;
3668 fds = (__s32 __user *) up.fds;
3669 while (nr_args) {
65e19f54
JA
3670 struct fixed_file_table *table;
3671 unsigned index;
3672
c3a31e60
JA
3673 err = 0;
3674 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
3675 err = -EFAULT;
3676 break;
3677 }
3678 i = array_index_nospec(up.offset, ctx->nr_user_files);
65e19f54
JA
3679 table = &ctx->file_table[i >> IORING_FILE_TABLE_SHIFT];
3680 index = i & IORING_FILE_TABLE_MASK;
3681 if (table->files[index]) {
c3a31e60 3682 io_sqe_file_unregister(ctx, i);
65e19f54 3683 table->files[index] = NULL;
c3a31e60
JA
3684 }
3685 if (fd != -1) {
3686 struct file *file;
3687
3688 file = fget(fd);
3689 if (!file) {
3690 err = -EBADF;
3691 break;
3692 }
3693 /*
3694 * Don't allow io_uring instances to be registered. If
3695 * UNIX isn't enabled, then this causes a reference
3696 * cycle and this instance can never get freed. If UNIX
3697 * is enabled we'll handle it just fine, but there's
3698 * still no point in allowing a ring fd as it doesn't
3699 * support regular read/write anyway.
3700 */
3701 if (file->f_op == &io_uring_fops) {
3702 fput(file);
3703 err = -EBADF;
3704 break;
3705 }
65e19f54 3706 table->files[index] = file;
c3a31e60
JA
3707 err = io_sqe_file_register(ctx, file, i);
3708 if (err)
3709 break;
3710 }
3711 nr_args--;
3712 done++;
3713 up.offset++;
3714 }
3715
3716 return done ? done : err;
3717}
3718
6c271ce2
JA
3719static int io_sq_offload_start(struct io_ring_ctx *ctx,
3720 struct io_uring_params *p)
2b188cc1 3721{
561fb04a 3722 unsigned concurrency;
2b188cc1
JA
3723 int ret;
3724
6c271ce2 3725 init_waitqueue_head(&ctx->sqo_wait);
2b188cc1
JA
3726 mmgrab(current->mm);
3727 ctx->sqo_mm = current->mm;
3728
6c271ce2 3729 if (ctx->flags & IORING_SETUP_SQPOLL) {
3ec482d1
JA
3730 ret = -EPERM;
3731 if (!capable(CAP_SYS_ADMIN))
3732 goto err;
3733
917257da
JA
3734 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
3735 if (!ctx->sq_thread_idle)
3736 ctx->sq_thread_idle = HZ;
3737
6c271ce2 3738 if (p->flags & IORING_SETUP_SQ_AFF) {
44a9bd18 3739 int cpu = p->sq_thread_cpu;
6c271ce2 3740
917257da 3741 ret = -EINVAL;
44a9bd18
JA
3742 if (cpu >= nr_cpu_ids)
3743 goto err;
7889f44d 3744 if (!cpu_online(cpu))
917257da
JA
3745 goto err;
3746
6c271ce2
JA
3747 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
3748 ctx, cpu,
3749 "io_uring-sq");
3750 } else {
3751 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
3752 "io_uring-sq");
3753 }
3754 if (IS_ERR(ctx->sqo_thread)) {
3755 ret = PTR_ERR(ctx->sqo_thread);
3756 ctx->sqo_thread = NULL;
3757 goto err;
3758 }
3759 wake_up_process(ctx->sqo_thread);
3760 } else if (p->flags & IORING_SETUP_SQ_AFF) {
3761 /* Can't have SQ_AFF without SQPOLL */
3762 ret = -EINVAL;
3763 goto err;
3764 }
3765
561fb04a
JA
3766 /* Do QD, or 4 * CPUS, whatever is smallest */
3767 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
5f8fd2d3 3768 ctx->io_wq = io_wq_create(concurrency, ctx->sqo_mm, ctx->user);
975c99a5
JA
3769 if (IS_ERR(ctx->io_wq)) {
3770 ret = PTR_ERR(ctx->io_wq);
3771 ctx->io_wq = NULL;
2b188cc1
JA
3772 goto err;
3773 }
3774
3775 return 0;
3776err:
54a91f3b 3777 io_finish_async(ctx);
2b188cc1
JA
3778 mmdrop(ctx->sqo_mm);
3779 ctx->sqo_mm = NULL;
3780 return ret;
3781}
3782
3783static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
3784{
3785 atomic_long_sub(nr_pages, &user->locked_vm);
3786}
3787
3788static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
3789{
3790 unsigned long page_limit, cur_pages, new_pages;
3791
3792 /* Don't allow more pages than we can safely lock */
3793 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
3794
3795 do {
3796 cur_pages = atomic_long_read(&user->locked_vm);
3797 new_pages = cur_pages + nr_pages;
3798 if (new_pages > page_limit)
3799 return -ENOMEM;
3800 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
3801 new_pages) != cur_pages);
3802
3803 return 0;
3804}
3805
3806static void io_mem_free(void *ptr)
3807{
52e04ef4
MR
3808 struct page *page;
3809
3810 if (!ptr)
3811 return;
2b188cc1 3812
52e04ef4 3813 page = virt_to_head_page(ptr);
2b188cc1
JA
3814 if (put_page_testzero(page))
3815 free_compound_page(page);
3816}
3817
3818static void *io_mem_alloc(size_t size)
3819{
3820 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
3821 __GFP_NORETRY;
3822
3823 return (void *) __get_free_pages(gfp_flags, get_order(size));
3824}
3825
75b28aff
HV
3826static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
3827 size_t *sq_offset)
3828{
3829 struct io_rings *rings;
3830 size_t off, sq_array_size;
3831
3832 off = struct_size(rings, cqes, cq_entries);
3833 if (off == SIZE_MAX)
3834 return SIZE_MAX;
3835
3836#ifdef CONFIG_SMP
3837 off = ALIGN(off, SMP_CACHE_BYTES);
3838 if (off == 0)
3839 return SIZE_MAX;
3840#endif
3841
3842 sq_array_size = array_size(sizeof(u32), sq_entries);
3843 if (sq_array_size == SIZE_MAX)
3844 return SIZE_MAX;
3845
3846 if (check_add_overflow(off, sq_array_size, &off))
3847 return SIZE_MAX;
3848
3849 if (sq_offset)
3850 *sq_offset = off;
3851
3852 return off;
3853}
3854
2b188cc1
JA
3855static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
3856{
75b28aff 3857 size_t pages;
2b188cc1 3858
75b28aff
HV
3859 pages = (size_t)1 << get_order(
3860 rings_size(sq_entries, cq_entries, NULL));
3861 pages += (size_t)1 << get_order(
3862 array_size(sizeof(struct io_uring_sqe), sq_entries));
2b188cc1 3863
75b28aff 3864 return pages;
2b188cc1
JA
3865}
3866
edafccee
JA
3867static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
3868{
3869 int i, j;
3870
3871 if (!ctx->user_bufs)
3872 return -ENXIO;
3873
3874 for (i = 0; i < ctx->nr_user_bufs; i++) {
3875 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
3876
3877 for (j = 0; j < imu->nr_bvecs; j++)
27c4d3a3 3878 put_user_page(imu->bvec[j].bv_page);
edafccee
JA
3879
3880 if (ctx->account_mem)
3881 io_unaccount_mem(ctx->user, imu->nr_bvecs);
d4ef6475 3882 kvfree(imu->bvec);
edafccee
JA
3883 imu->nr_bvecs = 0;
3884 }
3885
3886 kfree(ctx->user_bufs);
3887 ctx->user_bufs = NULL;
3888 ctx->nr_user_bufs = 0;
3889 return 0;
3890}
3891
3892static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
3893 void __user *arg, unsigned index)
3894{
3895 struct iovec __user *src;
3896
3897#ifdef CONFIG_COMPAT
3898 if (ctx->compat) {
3899 struct compat_iovec __user *ciovs;
3900 struct compat_iovec ciov;
3901
3902 ciovs = (struct compat_iovec __user *) arg;
3903 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
3904 return -EFAULT;
3905
3906 dst->iov_base = (void __user *) (unsigned long) ciov.iov_base;
3907 dst->iov_len = ciov.iov_len;
3908 return 0;
3909 }
3910#endif
3911 src = (struct iovec __user *) arg;
3912 if (copy_from_user(dst, &src[index], sizeof(*dst)))
3913 return -EFAULT;
3914 return 0;
3915}
3916
3917static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
3918 unsigned nr_args)
3919{
3920 struct vm_area_struct **vmas = NULL;
3921 struct page **pages = NULL;
3922 int i, j, got_pages = 0;
3923 int ret = -EINVAL;
3924
3925 if (ctx->user_bufs)
3926 return -EBUSY;
3927 if (!nr_args || nr_args > UIO_MAXIOV)
3928 return -EINVAL;
3929
3930 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
3931 GFP_KERNEL);
3932 if (!ctx->user_bufs)
3933 return -ENOMEM;
3934
3935 for (i = 0; i < nr_args; i++) {
3936 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
3937 unsigned long off, start, end, ubuf;
3938 int pret, nr_pages;
3939 struct iovec iov;
3940 size_t size;
3941
3942 ret = io_copy_iov(ctx, &iov, arg, i);
3943 if (ret)
a278682d 3944 goto err;
edafccee
JA
3945
3946 /*
3947 * Don't impose further limits on the size and buffer
3948 * constraints here, we'll -EINVAL later when IO is
3949 * submitted if they are wrong.
3950 */
3951 ret = -EFAULT;
3952 if (!iov.iov_base || !iov.iov_len)
3953 goto err;
3954
3955 /* arbitrary limit, but we need something */
3956 if (iov.iov_len > SZ_1G)
3957 goto err;
3958
3959 ubuf = (unsigned long) iov.iov_base;
3960 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
3961 start = ubuf >> PAGE_SHIFT;
3962 nr_pages = end - start;
3963
3964 if (ctx->account_mem) {
3965 ret = io_account_mem(ctx->user, nr_pages);
3966 if (ret)
3967 goto err;
3968 }
3969
3970 ret = 0;
3971 if (!pages || nr_pages > got_pages) {
3972 kfree(vmas);
3973 kfree(pages);
d4ef6475 3974 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
edafccee 3975 GFP_KERNEL);
d4ef6475 3976 vmas = kvmalloc_array(nr_pages,
edafccee
JA
3977 sizeof(struct vm_area_struct *),
3978 GFP_KERNEL);
3979 if (!pages || !vmas) {
3980 ret = -ENOMEM;
3981 if (ctx->account_mem)
3982 io_unaccount_mem(ctx->user, nr_pages);
3983 goto err;
3984 }
3985 got_pages = nr_pages;
3986 }
3987
d4ef6475 3988 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
edafccee
JA
3989 GFP_KERNEL);
3990 ret = -ENOMEM;
3991 if (!imu->bvec) {
3992 if (ctx->account_mem)
3993 io_unaccount_mem(ctx->user, nr_pages);
3994 goto err;
3995 }
3996
3997 ret = 0;
3998 down_read(&current->mm->mmap_sem);
932f4a63
IW
3999 pret = get_user_pages(ubuf, nr_pages,
4000 FOLL_WRITE | FOLL_LONGTERM,
4001 pages, vmas);
edafccee
JA
4002 if (pret == nr_pages) {
4003 /* don't support file backed memory */
4004 for (j = 0; j < nr_pages; j++) {
4005 struct vm_area_struct *vma = vmas[j];
4006
4007 if (vma->vm_file &&
4008 !is_file_hugepages(vma->vm_file)) {
4009 ret = -EOPNOTSUPP;
4010 break;
4011 }
4012 }
4013 } else {
4014 ret = pret < 0 ? pret : -EFAULT;
4015 }
4016 up_read(&current->mm->mmap_sem);
4017 if (ret) {
4018 /*
4019 * if we did partial map, or found file backed vmas,
4020 * release any pages we did get
4021 */
27c4d3a3
JH
4022 if (pret > 0)
4023 put_user_pages(pages, pret);
edafccee
JA
4024 if (ctx->account_mem)
4025 io_unaccount_mem(ctx->user, nr_pages);
d4ef6475 4026 kvfree(imu->bvec);
edafccee
JA
4027 goto err;
4028 }
4029
4030 off = ubuf & ~PAGE_MASK;
4031 size = iov.iov_len;
4032 for (j = 0; j < nr_pages; j++) {
4033 size_t vec_len;
4034
4035 vec_len = min_t(size_t, size, PAGE_SIZE - off);
4036 imu->bvec[j].bv_page = pages[j];
4037 imu->bvec[j].bv_len = vec_len;
4038 imu->bvec[j].bv_offset = off;
4039 off = 0;
4040 size -= vec_len;
4041 }
4042 /* store original address for later verification */
4043 imu->ubuf = ubuf;
4044 imu->len = iov.iov_len;
4045 imu->nr_bvecs = nr_pages;
4046
4047 ctx->nr_user_bufs++;
4048 }
d4ef6475
MR
4049 kvfree(pages);
4050 kvfree(vmas);
edafccee
JA
4051 return 0;
4052err:
d4ef6475
MR
4053 kvfree(pages);
4054 kvfree(vmas);
edafccee
JA
4055 io_sqe_buffer_unregister(ctx);
4056 return ret;
4057}
4058
9b402849
JA
4059static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
4060{
4061 __s32 __user *fds = arg;
4062 int fd;
4063
4064 if (ctx->cq_ev_fd)
4065 return -EBUSY;
4066
4067 if (copy_from_user(&fd, fds, sizeof(*fds)))
4068 return -EFAULT;
4069
4070 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
4071 if (IS_ERR(ctx->cq_ev_fd)) {
4072 int ret = PTR_ERR(ctx->cq_ev_fd);
4073 ctx->cq_ev_fd = NULL;
4074 return ret;
4075 }
4076
4077 return 0;
4078}
4079
4080static int io_eventfd_unregister(struct io_ring_ctx *ctx)
4081{
4082 if (ctx->cq_ev_fd) {
4083 eventfd_ctx_put(ctx->cq_ev_fd);
4084 ctx->cq_ev_fd = NULL;
4085 return 0;
4086 }
4087
4088 return -ENXIO;
4089}
4090
2b188cc1
JA
4091static void io_ring_ctx_free(struct io_ring_ctx *ctx)
4092{
6b06314c 4093 io_finish_async(ctx);
2b188cc1
JA
4094 if (ctx->sqo_mm)
4095 mmdrop(ctx->sqo_mm);
def596e9
JA
4096
4097 io_iopoll_reap_events(ctx);
edafccee 4098 io_sqe_buffer_unregister(ctx);
6b06314c 4099 io_sqe_files_unregister(ctx);
9b402849 4100 io_eventfd_unregister(ctx);
def596e9 4101
2b188cc1 4102#if defined(CONFIG_UNIX)
355e8d26
EB
4103 if (ctx->ring_sock) {
4104 ctx->ring_sock->file = NULL; /* so that iput() is called */
2b188cc1 4105 sock_release(ctx->ring_sock);
355e8d26 4106 }
2b188cc1
JA
4107#endif
4108
75b28aff 4109 io_mem_free(ctx->rings);
2b188cc1 4110 io_mem_free(ctx->sq_sqes);
2b188cc1
JA
4111
4112 percpu_ref_exit(&ctx->refs);
4113 if (ctx->account_mem)
4114 io_unaccount_mem(ctx->user,
4115 ring_pages(ctx->sq_entries, ctx->cq_entries));
4116 free_uid(ctx->user);
206aefde 4117 kfree(ctx->completions);
2b188cc1
JA
4118 kfree(ctx);
4119}
4120
4121static __poll_t io_uring_poll(struct file *file, poll_table *wait)
4122{
4123 struct io_ring_ctx *ctx = file->private_data;
4124 __poll_t mask = 0;
4125
4126 poll_wait(file, &ctx->cq_wait, wait);
4f7067c3
SB
4127 /*
4128 * synchronizes with barrier from wq_has_sleeper call in
4129 * io_commit_cqring
4130 */
2b188cc1 4131 smp_rmb();
75b28aff
HV
4132 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
4133 ctx->rings->sq_ring_entries)
2b188cc1 4134 mask |= EPOLLOUT | EPOLLWRNORM;
daa5de54 4135 if (READ_ONCE(ctx->rings->cq.head) != ctx->cached_cq_tail)
2b188cc1
JA
4136 mask |= EPOLLIN | EPOLLRDNORM;
4137
4138 return mask;
4139}
4140
4141static int io_uring_fasync(int fd, struct file *file, int on)
4142{
4143 struct io_ring_ctx *ctx = file->private_data;
4144
4145 return fasync_helper(fd, file, on, &ctx->cq_fasync);
4146}
4147
4148static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
4149{
4150 mutex_lock(&ctx->uring_lock);
4151 percpu_ref_kill(&ctx->refs);
4152 mutex_unlock(&ctx->uring_lock);
4153
5262f567 4154 io_kill_timeouts(ctx);
221c5eb2 4155 io_poll_remove_all(ctx);
561fb04a
JA
4156
4157 if (ctx->io_wq)
4158 io_wq_cancel_all(ctx->io_wq);
4159
def596e9 4160 io_iopoll_reap_events(ctx);
1d7bb1d5 4161 io_cqring_overflow_flush(ctx, true);
206aefde 4162 wait_for_completion(&ctx->completions[0]);
2b188cc1
JA
4163 io_ring_ctx_free(ctx);
4164}
4165
4166static int io_uring_release(struct inode *inode, struct file *file)
4167{
4168 struct io_ring_ctx *ctx = file->private_data;
4169
4170 file->private_data = NULL;
4171 io_ring_ctx_wait_and_kill(ctx);
4172 return 0;
4173}
4174
fcb323cc
JA
4175static void io_uring_cancel_files(struct io_ring_ctx *ctx,
4176 struct files_struct *files)
4177{
4178 struct io_kiocb *req;
4179 DEFINE_WAIT(wait);
4180
4181 while (!list_empty_careful(&ctx->inflight_list)) {
4182 enum io_wq_cancel ret = IO_WQ_CANCEL_NOTFOUND;
4183
4184 spin_lock_irq(&ctx->inflight_lock);
4185 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
4186 if (req->work.files == files) {
4187 ret = io_wq_cancel_work(ctx->io_wq, &req->work);
4188 break;
4189 }
4190 }
4191 if (ret == IO_WQ_CANCEL_RUNNING)
4192 prepare_to_wait(&ctx->inflight_wait, &wait,
4193 TASK_UNINTERRUPTIBLE);
4194
4195 spin_unlock_irq(&ctx->inflight_lock);
4196
4197 /*
4198 * We need to keep going until we get NOTFOUND. We only cancel
4199 * one work at the time.
4200 *
4201 * If we get CANCEL_RUNNING, then wait for a work to complete
4202 * before continuing.
4203 */
4204 if (ret == IO_WQ_CANCEL_OK)
4205 continue;
4206 else if (ret != IO_WQ_CANCEL_RUNNING)
4207 break;
4208 schedule();
4209 }
4210}
4211
4212static int io_uring_flush(struct file *file, void *data)
4213{
4214 struct io_ring_ctx *ctx = file->private_data;
4215
4216 io_uring_cancel_files(ctx, data);
1d7bb1d5
JA
4217 if (fatal_signal_pending(current) || (current->flags & PF_EXITING)) {
4218 io_cqring_overflow_flush(ctx, true);
fcb323cc 4219 io_wq_cancel_all(ctx->io_wq);
1d7bb1d5 4220 }
fcb323cc
JA
4221 return 0;
4222}
4223
2b188cc1
JA
4224static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
4225{
4226 loff_t offset = (loff_t) vma->vm_pgoff << PAGE_SHIFT;
4227 unsigned long sz = vma->vm_end - vma->vm_start;
4228 struct io_ring_ctx *ctx = file->private_data;
4229 unsigned long pfn;
4230 struct page *page;
4231 void *ptr;
4232
4233 switch (offset) {
4234 case IORING_OFF_SQ_RING:
75b28aff
HV
4235 case IORING_OFF_CQ_RING:
4236 ptr = ctx->rings;
2b188cc1
JA
4237 break;
4238 case IORING_OFF_SQES:
4239 ptr = ctx->sq_sqes;
4240 break;
2b188cc1
JA
4241 default:
4242 return -EINVAL;
4243 }
4244
4245 page = virt_to_head_page(ptr);
a50b854e 4246 if (sz > page_size(page))
2b188cc1
JA
4247 return -EINVAL;
4248
4249 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
4250 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
4251}
4252
4253SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
4254 u32, min_complete, u32, flags, const sigset_t __user *, sig,
4255 size_t, sigsz)
4256{
4257 struct io_ring_ctx *ctx;
4258 long ret = -EBADF;
4259 int submitted = 0;
4260 struct fd f;
4261
6c271ce2 4262 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
2b188cc1
JA
4263 return -EINVAL;
4264
4265 f = fdget(fd);
4266 if (!f.file)
4267 return -EBADF;
4268
4269 ret = -EOPNOTSUPP;
4270 if (f.file->f_op != &io_uring_fops)
4271 goto out_fput;
4272
4273 ret = -ENXIO;
4274 ctx = f.file->private_data;
4275 if (!percpu_ref_tryget(&ctx->refs))
4276 goto out_fput;
4277
6c271ce2
JA
4278 /*
4279 * For SQ polling, the thread will do all submissions and completions.
4280 * Just return the requested submit count, and wake the thread if
4281 * we were asked to.
4282 */
b2a9eada 4283 ret = 0;
6c271ce2
JA
4284 if (ctx->flags & IORING_SETUP_SQPOLL) {
4285 if (flags & IORING_ENTER_SQ_WAKEUP)
4286 wake_up(&ctx->sqo_wait);
4287 submitted = to_submit;
b2a9eada 4288 } else if (to_submit) {
ae9428ca 4289 struct mm_struct *cur_mm;
2b188cc1 4290
ae9428ca 4291 to_submit = min(to_submit, ctx->sq_entries);
2b188cc1 4292 mutex_lock(&ctx->uring_lock);
ae9428ca
PB
4293 /* already have mm, so io_submit_sqes() won't try to grab it */
4294 cur_mm = ctx->sqo_mm;
4295 submitted = io_submit_sqes(ctx, to_submit, f.file, fd,
4296 &cur_mm, false);
2b188cc1 4297 mutex_unlock(&ctx->uring_lock);
2b188cc1
JA
4298 }
4299 if (flags & IORING_ENTER_GETEVENTS) {
def596e9
JA
4300 unsigned nr_events = 0;
4301
2b188cc1
JA
4302 min_complete = min(min_complete, ctx->cq_entries);
4303
def596e9 4304 if (ctx->flags & IORING_SETUP_IOPOLL) {
def596e9 4305 ret = io_iopoll_check(ctx, &nr_events, min_complete);
def596e9
JA
4306 } else {
4307 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
4308 }
2b188cc1
JA
4309 }
4310
6805b32e 4311 percpu_ref_put(&ctx->refs);
2b188cc1
JA
4312out_fput:
4313 fdput(f);
4314 return submitted ? submitted : ret;
4315}
4316
4317static const struct file_operations io_uring_fops = {
4318 .release = io_uring_release,
fcb323cc 4319 .flush = io_uring_flush,
2b188cc1
JA
4320 .mmap = io_uring_mmap,
4321 .poll = io_uring_poll,
4322 .fasync = io_uring_fasync,
4323};
4324
4325static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
4326 struct io_uring_params *p)
4327{
75b28aff
HV
4328 struct io_rings *rings;
4329 size_t size, sq_array_offset;
2b188cc1 4330
75b28aff
HV
4331 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
4332 if (size == SIZE_MAX)
4333 return -EOVERFLOW;
4334
4335 rings = io_mem_alloc(size);
4336 if (!rings)
2b188cc1
JA
4337 return -ENOMEM;
4338
75b28aff
HV
4339 ctx->rings = rings;
4340 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
4341 rings->sq_ring_mask = p->sq_entries - 1;
4342 rings->cq_ring_mask = p->cq_entries - 1;
4343 rings->sq_ring_entries = p->sq_entries;
4344 rings->cq_ring_entries = p->cq_entries;
4345 ctx->sq_mask = rings->sq_ring_mask;
4346 ctx->cq_mask = rings->cq_ring_mask;
4347 ctx->sq_entries = rings->sq_ring_entries;
4348 ctx->cq_entries = rings->cq_ring_entries;
2b188cc1
JA
4349
4350 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
4351 if (size == SIZE_MAX)
4352 return -EOVERFLOW;
4353
4354 ctx->sq_sqes = io_mem_alloc(size);
52e04ef4 4355 if (!ctx->sq_sqes)
2b188cc1 4356 return -ENOMEM;
2b188cc1 4357
2b188cc1
JA
4358 return 0;
4359}
4360
4361/*
4362 * Allocate an anonymous fd, this is what constitutes the application
4363 * visible backing of an io_uring instance. The application mmaps this
4364 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
4365 * we have to tie this fd to a socket for file garbage collection purposes.
4366 */
4367static int io_uring_get_fd(struct io_ring_ctx *ctx)
4368{
4369 struct file *file;
4370 int ret;
4371
4372#if defined(CONFIG_UNIX)
4373 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
4374 &ctx->ring_sock);
4375 if (ret)
4376 return ret;
4377#endif
4378
4379 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
4380 if (ret < 0)
4381 goto err;
4382
4383 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
4384 O_RDWR | O_CLOEXEC);
4385 if (IS_ERR(file)) {
4386 put_unused_fd(ret);
4387 ret = PTR_ERR(file);
4388 goto err;
4389 }
4390
4391#if defined(CONFIG_UNIX)
4392 ctx->ring_sock->file = file;
6b06314c 4393 ctx->ring_sock->sk->sk_user_data = ctx;
2b188cc1
JA
4394#endif
4395 fd_install(ret, file);
4396 return ret;
4397err:
4398#if defined(CONFIG_UNIX)
4399 sock_release(ctx->ring_sock);
4400 ctx->ring_sock = NULL;
4401#endif
4402 return ret;
4403}
4404
4405static int io_uring_create(unsigned entries, struct io_uring_params *p)
4406{
4407 struct user_struct *user = NULL;
4408 struct io_ring_ctx *ctx;
4409 bool account_mem;
4410 int ret;
4411
4412 if (!entries || entries > IORING_MAX_ENTRIES)
4413 return -EINVAL;
4414
4415 /*
4416 * Use twice as many entries for the CQ ring. It's possible for the
4417 * application to drive a higher depth than the size of the SQ ring,
4418 * since the sqes are only used at submission time. This allows for
33a107f0
JA
4419 * some flexibility in overcommitting a bit. If the application has
4420 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
4421 * of CQ ring entries manually.
2b188cc1
JA
4422 */
4423 p->sq_entries = roundup_pow_of_two(entries);
33a107f0
JA
4424 if (p->flags & IORING_SETUP_CQSIZE) {
4425 /*
4426 * If IORING_SETUP_CQSIZE is set, we do the same roundup
4427 * to a power-of-two, if it isn't already. We do NOT impose
4428 * any cq vs sq ring sizing.
4429 */
4430 if (p->cq_entries < p->sq_entries || p->cq_entries > IORING_MAX_CQ_ENTRIES)
4431 return -EINVAL;
4432 p->cq_entries = roundup_pow_of_two(p->cq_entries);
4433 } else {
4434 p->cq_entries = 2 * p->sq_entries;
4435 }
2b188cc1
JA
4436
4437 user = get_uid(current_user());
4438 account_mem = !capable(CAP_IPC_LOCK);
4439
4440 if (account_mem) {
4441 ret = io_account_mem(user,
4442 ring_pages(p->sq_entries, p->cq_entries));
4443 if (ret) {
4444 free_uid(user);
4445 return ret;
4446 }
4447 }
4448
4449 ctx = io_ring_ctx_alloc(p);
4450 if (!ctx) {
4451 if (account_mem)
4452 io_unaccount_mem(user, ring_pages(p->sq_entries,
4453 p->cq_entries));
4454 free_uid(user);
4455 return -ENOMEM;
4456 }
4457 ctx->compat = in_compat_syscall();
4458 ctx->account_mem = account_mem;
4459 ctx->user = user;
4460
4461 ret = io_allocate_scq_urings(ctx, p);
4462 if (ret)
4463 goto err;
4464
6c271ce2 4465 ret = io_sq_offload_start(ctx, p);
2b188cc1
JA
4466 if (ret)
4467 goto err;
4468
2b188cc1 4469 memset(&p->sq_off, 0, sizeof(p->sq_off));
75b28aff
HV
4470 p->sq_off.head = offsetof(struct io_rings, sq.head);
4471 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
4472 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
4473 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
4474 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
4475 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
4476 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
2b188cc1
JA
4477
4478 memset(&p->cq_off, 0, sizeof(p->cq_off));
75b28aff
HV
4479 p->cq_off.head = offsetof(struct io_rings, cq.head);
4480 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
4481 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
4482 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
4483 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
4484 p->cq_off.cqes = offsetof(struct io_rings, cqes);
ac90f249 4485
044c1ab3
JA
4486 /*
4487 * Install ring fd as the very last thing, so we don't risk someone
4488 * having closed it before we finish setup
4489 */
4490 ret = io_uring_get_fd(ctx);
4491 if (ret < 0)
4492 goto err;
4493
1d7bb1d5 4494 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP;
c826bd7a 4495 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
2b188cc1
JA
4496 return ret;
4497err:
4498 io_ring_ctx_wait_and_kill(ctx);
4499 return ret;
4500}
4501
4502/*
4503 * Sets up an aio uring context, and returns the fd. Applications asks for a
4504 * ring size, we return the actual sq/cq ring sizes (among other things) in the
4505 * params structure passed in.
4506 */
4507static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
4508{
4509 struct io_uring_params p;
4510 long ret;
4511 int i;
4512
4513 if (copy_from_user(&p, params, sizeof(p)))
4514 return -EFAULT;
4515 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
4516 if (p.resv[i])
4517 return -EINVAL;
4518 }
4519
6c271ce2 4520 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
33a107f0 4521 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE))
2b188cc1
JA
4522 return -EINVAL;
4523
4524 ret = io_uring_create(entries, &p);
4525 if (ret < 0)
4526 return ret;
4527
4528 if (copy_to_user(params, &p, sizeof(p)))
4529 return -EFAULT;
4530
4531 return ret;
4532}
4533
4534SYSCALL_DEFINE2(io_uring_setup, u32, entries,
4535 struct io_uring_params __user *, params)
4536{
4537 return io_uring_setup(entries, params);
4538}
4539
edafccee
JA
4540static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
4541 void __user *arg, unsigned nr_args)
b19062a5
JA
4542 __releases(ctx->uring_lock)
4543 __acquires(ctx->uring_lock)
edafccee
JA
4544{
4545 int ret;
4546
35fa71a0
JA
4547 /*
4548 * We're inside the ring mutex, if the ref is already dying, then
4549 * someone else killed the ctx or is already going through
4550 * io_uring_register().
4551 */
4552 if (percpu_ref_is_dying(&ctx->refs))
4553 return -ENXIO;
4554
edafccee 4555 percpu_ref_kill(&ctx->refs);
b19062a5
JA
4556
4557 /*
4558 * Drop uring mutex before waiting for references to exit. If another
4559 * thread is currently inside io_uring_enter() it might need to grab
4560 * the uring_lock to make progress. If we hold it here across the drain
4561 * wait, then we can deadlock. It's safe to drop the mutex here, since
4562 * no new references will come in after we've killed the percpu ref.
4563 */
4564 mutex_unlock(&ctx->uring_lock);
206aefde 4565 wait_for_completion(&ctx->completions[0]);
b19062a5 4566 mutex_lock(&ctx->uring_lock);
edafccee
JA
4567
4568 switch (opcode) {
4569 case IORING_REGISTER_BUFFERS:
4570 ret = io_sqe_buffer_register(ctx, arg, nr_args);
4571 break;
4572 case IORING_UNREGISTER_BUFFERS:
4573 ret = -EINVAL;
4574 if (arg || nr_args)
4575 break;
4576 ret = io_sqe_buffer_unregister(ctx);
4577 break;
6b06314c
JA
4578 case IORING_REGISTER_FILES:
4579 ret = io_sqe_files_register(ctx, arg, nr_args);
4580 break;
4581 case IORING_UNREGISTER_FILES:
4582 ret = -EINVAL;
4583 if (arg || nr_args)
4584 break;
4585 ret = io_sqe_files_unregister(ctx);
4586 break;
c3a31e60
JA
4587 case IORING_REGISTER_FILES_UPDATE:
4588 ret = io_sqe_files_update(ctx, arg, nr_args);
4589 break;
9b402849
JA
4590 case IORING_REGISTER_EVENTFD:
4591 ret = -EINVAL;
4592 if (nr_args != 1)
4593 break;
4594 ret = io_eventfd_register(ctx, arg);
4595 break;
4596 case IORING_UNREGISTER_EVENTFD:
4597 ret = -EINVAL;
4598 if (arg || nr_args)
4599 break;
4600 ret = io_eventfd_unregister(ctx);
4601 break;
edafccee
JA
4602 default:
4603 ret = -EINVAL;
4604 break;
4605 }
4606
4607 /* bring the ctx back to life */
206aefde 4608 reinit_completion(&ctx->completions[0]);
edafccee
JA
4609 percpu_ref_reinit(&ctx->refs);
4610 return ret;
4611}
4612
4613SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
4614 void __user *, arg, unsigned int, nr_args)
4615{
4616 struct io_ring_ctx *ctx;
4617 long ret = -EBADF;
4618 struct fd f;
4619
4620 f = fdget(fd);
4621 if (!f.file)
4622 return -EBADF;
4623
4624 ret = -EOPNOTSUPP;
4625 if (f.file->f_op != &io_uring_fops)
4626 goto out_fput;
4627
4628 ctx = f.file->private_data;
4629
4630 mutex_lock(&ctx->uring_lock);
4631 ret = __io_uring_register(ctx, opcode, arg, nr_args);
4632 mutex_unlock(&ctx->uring_lock);
c826bd7a
DD
4633 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
4634 ctx->cq_ev_fd != NULL, ret);
edafccee
JA
4635out_fput:
4636 fdput(f);
4637 return ret;
4638}
4639
2b188cc1
JA
4640static int __init io_uring_init(void)
4641{
4642 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
4643 return 0;
4644};
4645__initcall(io_uring_init);