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