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