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