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