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