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