]> git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blame - fs/io_uring.c
io_uring: remove unused struct io_async_open
[mirror_ubuntu-hirsute-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>
6b47ee6e 49#include <linux/bits.h>
2b188cc1
JA
50
51#include <linux/sched/signal.h>
52#include <linux/fs.h>
53#include <linux/file.h>
54#include <linux/fdtable.h>
55#include <linux/mm.h>
56#include <linux/mman.h>
57#include <linux/mmu_context.h>
58#include <linux/percpu.h>
59#include <linux/slab.h>
6c271ce2 60#include <linux/kthread.h>
2b188cc1 61#include <linux/blkdev.h>
edafccee 62#include <linux/bvec.h>
2b188cc1
JA
63#include <linux/net.h>
64#include <net/sock.h>
65#include <net/af_unix.h>
6b06314c 66#include <net/scm.h>
2b188cc1
JA
67#include <linux/anon_inodes.h>
68#include <linux/sched/mm.h>
69#include <linux/uaccess.h>
70#include <linux/nospec.h>
edafccee
JA
71#include <linux/sizes.h>
72#include <linux/hugetlb.h>
aa4c3967 73#include <linux/highmem.h>
15b71abe
JA
74#include <linux/namei.h>
75#include <linux/fsnotify.h>
4840e418 76#include <linux/fadvise.h>
3e4827b0 77#include <linux/eventpoll.h>
2b188cc1 78
c826bd7a
DD
79#define CREATE_TRACE_POINTS
80#include <trace/events/io_uring.h>
81
2b188cc1
JA
82#include <uapi/linux/io_uring.h>
83
84#include "internal.h"
561fb04a 85#include "io-wq.h"
2b188cc1 86
5277deaa 87#define IORING_MAX_ENTRIES 32768
33a107f0 88#define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
65e19f54
JA
89
90/*
91 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
92 */
93#define IORING_FILE_TABLE_SHIFT 9
94#define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
95#define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
96#define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
2b188cc1
JA
97
98struct io_uring {
99 u32 head ____cacheline_aligned_in_smp;
100 u32 tail ____cacheline_aligned_in_smp;
101};
102
1e84b97b 103/*
75b28aff
HV
104 * This data is shared with the application through the mmap at offsets
105 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
1e84b97b
SB
106 *
107 * The offsets to the member fields are published through struct
108 * io_sqring_offsets when calling io_uring_setup.
109 */
75b28aff 110struct io_rings {
1e84b97b
SB
111 /*
112 * Head and tail offsets into the ring; the offsets need to be
113 * masked to get valid indices.
114 *
75b28aff
HV
115 * The kernel controls head of the sq ring and the tail of the cq ring,
116 * and the application controls tail of the sq ring and the head of the
117 * cq ring.
1e84b97b 118 */
75b28aff 119 struct io_uring sq, cq;
1e84b97b 120 /*
75b28aff 121 * Bitmasks to apply to head and tail offsets (constant, equals
1e84b97b
SB
122 * ring_entries - 1)
123 */
75b28aff
HV
124 u32 sq_ring_mask, cq_ring_mask;
125 /* Ring sizes (constant, power of 2) */
126 u32 sq_ring_entries, cq_ring_entries;
1e84b97b
SB
127 /*
128 * Number of invalid entries dropped by the kernel due to
129 * invalid index stored in array
130 *
131 * Written by the kernel, shouldn't be modified by the
132 * application (i.e. get number of "new events" by comparing to
133 * cached value).
134 *
135 * After a new SQ head value was read by the application this
136 * counter includes all submissions that were dropped reaching
137 * the new SQ head (and possibly more).
138 */
75b28aff 139 u32 sq_dropped;
1e84b97b
SB
140 /*
141 * Runtime flags
142 *
143 * Written by the kernel, shouldn't be modified by the
144 * application.
145 *
146 * The application needs a full memory barrier before checking
147 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
148 */
75b28aff 149 u32 sq_flags;
1e84b97b
SB
150 /*
151 * Number of completion events lost because the queue was full;
152 * this should be avoided by the application by making sure
0b4295b5 153 * there are not more requests pending than there is space in
1e84b97b
SB
154 * the completion queue.
155 *
156 * Written by the kernel, shouldn't be modified by the
157 * application (i.e. get number of "new events" by comparing to
158 * cached value).
159 *
160 * As completion events come in out of order this counter is not
161 * ordered with any other data.
162 */
75b28aff 163 u32 cq_overflow;
1e84b97b
SB
164 /*
165 * Ring buffer of completion events.
166 *
167 * The kernel writes completion events fresh every time they are
168 * produced, so the application is allowed to modify pending
169 * entries.
170 */
75b28aff 171 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
2b188cc1
JA
172};
173
edafccee
JA
174struct io_mapped_ubuf {
175 u64 ubuf;
176 size_t len;
177 struct bio_vec *bvec;
178 unsigned int nr_bvecs;
179};
180
65e19f54
JA
181struct fixed_file_table {
182 struct file **files;
31b51510
JA
183};
184
05f3fb3c
JA
185enum {
186 FFD_F_ATOMIC,
187};
188
189struct fixed_file_data {
190 struct fixed_file_table *table;
191 struct io_ring_ctx *ctx;
192
193 struct percpu_ref refs;
194 struct llist_head put_llist;
195 unsigned long state;
196 struct work_struct ref_work;
197 struct completion done;
198};
199
2b188cc1
JA
200struct io_ring_ctx {
201 struct {
202 struct percpu_ref refs;
203 } ____cacheline_aligned_in_smp;
204
205 struct {
206 unsigned int flags;
e1d85334
RD
207 unsigned int compat: 1;
208 unsigned int account_mem: 1;
209 unsigned int cq_overflow_flushed: 1;
210 unsigned int drain_next: 1;
211 unsigned int eventfd_async: 1;
2b188cc1 212
75b28aff
HV
213 /*
214 * Ring buffer of indices into array of io_uring_sqe, which is
215 * mmapped by the application using the IORING_OFF_SQES offset.
216 *
217 * This indirection could e.g. be used to assign fixed
218 * io_uring_sqe entries to operations and only submit them to
219 * the queue when needed.
220 *
221 * The kernel modifies neither the indices array nor the entries
222 * array.
223 */
224 u32 *sq_array;
2b188cc1
JA
225 unsigned cached_sq_head;
226 unsigned sq_entries;
227 unsigned sq_mask;
6c271ce2 228 unsigned sq_thread_idle;
498ccd9e 229 unsigned cached_sq_dropped;
206aefde 230 atomic_t cached_cq_overflow;
ad3eb2c8 231 unsigned long sq_check_overflow;
de0617e4
JA
232
233 struct list_head defer_list;
5262f567 234 struct list_head timeout_list;
1d7bb1d5 235 struct list_head cq_overflow_list;
fcb323cc
JA
236
237 wait_queue_head_t inflight_wait;
ad3eb2c8 238 struct io_uring_sqe *sq_sqes;
2b188cc1
JA
239 } ____cacheline_aligned_in_smp;
240
206aefde
JA
241 struct io_rings *rings;
242
2b188cc1 243 /* IO offload */
561fb04a 244 struct io_wq *io_wq;
6c271ce2 245 struct task_struct *sqo_thread; /* if using sq thread polling */
2b188cc1 246 struct mm_struct *sqo_mm;
6c271ce2 247 wait_queue_head_t sqo_wait;
75b28aff 248
6b06314c
JA
249 /*
250 * If used, fixed file set. Writers must ensure that ->refs is dead,
251 * readers must ensure that ->refs is alive as long as the file* is
252 * used. Only updated through io_uring_register(2).
253 */
05f3fb3c 254 struct fixed_file_data *file_data;
6b06314c 255 unsigned nr_user_files;
b14cca0c
PB
256 int ring_fd;
257 struct file *ring_file;
6b06314c 258
edafccee
JA
259 /* if used, fixed mapped user buffers */
260 unsigned nr_user_bufs;
261 struct io_mapped_ubuf *user_bufs;
262
2b188cc1
JA
263 struct user_struct *user;
264
0b8c0ec7 265 const struct cred *creds;
181e448d 266
206aefde
JA
267 /* 0 is for ctx quiesce/reinit/free, 1 is for sqo_thread started */
268 struct completion *completions;
269
0ddf92e8
JA
270 /* if all else fails... */
271 struct io_kiocb *fallback_req;
272
206aefde
JA
273#if defined(CONFIG_UNIX)
274 struct socket *ring_sock;
275#endif
276
071698e1
JA
277 struct idr personality_idr;
278
206aefde
JA
279 struct {
280 unsigned cached_cq_tail;
281 unsigned cq_entries;
282 unsigned cq_mask;
283 atomic_t cq_timeouts;
ad3eb2c8 284 unsigned long cq_check_overflow;
206aefde
JA
285 struct wait_queue_head cq_wait;
286 struct fasync_struct *cq_fasync;
287 struct eventfd_ctx *cq_ev_fd;
288 } ____cacheline_aligned_in_smp;
2b188cc1
JA
289
290 struct {
291 struct mutex uring_lock;
292 wait_queue_head_t wait;
293 } ____cacheline_aligned_in_smp;
294
295 struct {
296 spinlock_t completion_lock;
e94f141b
JA
297 struct llist_head poll_llist;
298
def596e9
JA
299 /*
300 * ->poll_list is protected by the ctx->uring_lock for
301 * io_uring instances that don't use IORING_SETUP_SQPOLL.
302 * For SQPOLL, only the single threaded io_sq_thread() will
303 * manipulate the list, hence no extra locking is needed there.
304 */
305 struct list_head poll_list;
78076bb6
JA
306 struct hlist_head *cancel_hash;
307 unsigned cancel_hash_bits;
e94f141b 308 bool poll_multi_file;
31b51510 309
fcb323cc
JA
310 spinlock_t inflight_lock;
311 struct list_head inflight_list;
2b188cc1 312 } ____cacheline_aligned_in_smp;
2b188cc1
JA
313};
314
09bb8394
JA
315/*
316 * First field must be the file pointer in all the
317 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
318 */
221c5eb2
JA
319struct io_poll_iocb {
320 struct file *file;
0969e783
JA
321 union {
322 struct wait_queue_head *head;
323 u64 addr;
324 };
221c5eb2 325 __poll_t events;
8c838788 326 bool done;
221c5eb2 327 bool canceled;
392edb45 328 struct wait_queue_entry wait;
221c5eb2
JA
329};
330
b5dba59e
JA
331struct io_close {
332 struct file *file;
333 struct file *put_file;
334 int fd;
335};
336
ad8a48ac
JA
337struct io_timeout_data {
338 struct io_kiocb *req;
339 struct hrtimer timer;
340 struct timespec64 ts;
341 enum hrtimer_mode mode;
cc42e0ac 342 u32 seq_offset;
ad8a48ac
JA
343};
344
8ed8d3c3
JA
345struct io_accept {
346 struct file *file;
347 struct sockaddr __user *addr;
348 int __user *addr_len;
349 int flags;
350};
351
352struct io_sync {
353 struct file *file;
354 loff_t len;
355 loff_t off;
356 int flags;
d63d1b5e 357 int mode;
8ed8d3c3
JA
358};
359
fbf23849
JA
360struct io_cancel {
361 struct file *file;
362 u64 addr;
363};
364
b29472ee
JA
365struct io_timeout {
366 struct file *file;
367 u64 addr;
368 int flags;
26a61679 369 unsigned count;
b29472ee
JA
370};
371
9adbd45d
JA
372struct io_rw {
373 /* NOTE: kiocb has the file as the first member, so don't do it here */
374 struct kiocb kiocb;
375 u64 addr;
376 u64 len;
377};
378
3fbb51c1
JA
379struct io_connect {
380 struct file *file;
381 struct sockaddr __user *addr;
382 int addr_len;
383};
384
e47293fd
JA
385struct io_sr_msg {
386 struct file *file;
fddaface
JA
387 union {
388 struct user_msghdr __user *msg;
389 void __user *buf;
390 };
e47293fd 391 int msg_flags;
fddaface 392 size_t len;
e47293fd
JA
393};
394
15b71abe
JA
395struct io_open {
396 struct file *file;
397 int dfd;
eddc7ef5 398 union {
eddc7ef5
JA
399 unsigned mask;
400 };
15b71abe 401 struct filename *filename;
eddc7ef5 402 struct statx __user *buffer;
c12cedf2 403 struct open_how how;
15b71abe
JA
404};
405
05f3fb3c
JA
406struct io_files_update {
407 struct file *file;
408 u64 arg;
409 u32 nr_args;
410 u32 offset;
411};
412
4840e418
JA
413struct io_fadvise {
414 struct file *file;
415 u64 offset;
416 u32 len;
417 u32 advice;
418};
419
c1ca757b
JA
420struct io_madvise {
421 struct file *file;
422 u64 addr;
423 u32 len;
424 u32 advice;
425};
426
3e4827b0
JA
427struct io_epoll {
428 struct file *file;
429 int epfd;
430 int op;
431 int fd;
432 struct epoll_event event;
e47293fd
JA
433};
434
f499a021
JA
435struct io_async_connect {
436 struct sockaddr_storage address;
437};
438
03b1230c
JA
439struct io_async_msghdr {
440 struct iovec fast_iov[UIO_FASTIOV];
441 struct iovec *iov;
442 struct sockaddr __user *uaddr;
443 struct msghdr msg;
444};
445
f67676d1
JA
446struct io_async_rw {
447 struct iovec fast_iov[UIO_FASTIOV];
448 struct iovec *iov;
449 ssize_t nr_segs;
450 ssize_t size;
451};
452
1a6b74fc 453struct io_async_ctx {
f67676d1
JA
454 union {
455 struct io_async_rw rw;
03b1230c 456 struct io_async_msghdr msg;
f499a021 457 struct io_async_connect connect;
2d28390a 458 struct io_timeout_data timeout;
f67676d1 459 };
1a6b74fc
JA
460};
461
6b47ee6e
PB
462enum {
463 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
464 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
465 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
466 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
467 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
468
469 REQ_F_LINK_NEXT_BIT,
470 REQ_F_FAIL_LINK_BIT,
471 REQ_F_INFLIGHT_BIT,
472 REQ_F_CUR_POS_BIT,
473 REQ_F_NOWAIT_BIT,
474 REQ_F_IOPOLL_COMPLETED_BIT,
475 REQ_F_LINK_TIMEOUT_BIT,
476 REQ_F_TIMEOUT_BIT,
477 REQ_F_ISREG_BIT,
478 REQ_F_MUST_PUNT_BIT,
479 REQ_F_TIMEOUT_NOSEQ_BIT,
480 REQ_F_COMP_LOCKED_BIT,
481};
482
483enum {
484 /* ctx owns file */
485 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
486 /* drain existing IO first */
487 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
488 /* linked sqes */
489 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
490 /* doesn't sever on completion < 0 */
491 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
492 /* IOSQE_ASYNC */
493 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
494
495 /* already grabbed next link */
496 REQ_F_LINK_NEXT = BIT(REQ_F_LINK_NEXT_BIT),
497 /* fail rest of links */
498 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
499 /* on inflight list */
500 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
501 /* read/write uses file position */
502 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
503 /* must not punt to workers */
504 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
505 /* polled IO has completed */
506 REQ_F_IOPOLL_COMPLETED = BIT(REQ_F_IOPOLL_COMPLETED_BIT),
507 /* has linked timeout */
508 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
509 /* timeout request */
510 REQ_F_TIMEOUT = BIT(REQ_F_TIMEOUT_BIT),
511 /* regular file */
512 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
513 /* must be punted even for NONBLOCK */
514 REQ_F_MUST_PUNT = BIT(REQ_F_MUST_PUNT_BIT),
515 /* no timeout sequence */
516 REQ_F_TIMEOUT_NOSEQ = BIT(REQ_F_TIMEOUT_NOSEQ_BIT),
517 /* completion under lock */
518 REQ_F_COMP_LOCKED = BIT(REQ_F_COMP_LOCKED_BIT),
519};
520
09bb8394
JA
521/*
522 * NOTE! Each of the iocb union members has the file pointer
523 * as the first entry in their struct definition. So you can
524 * access the file pointer through any of the sub-structs,
525 * or directly as just 'ki_filp' in this struct.
526 */
2b188cc1 527struct io_kiocb {
221c5eb2 528 union {
09bb8394 529 struct file *file;
9adbd45d 530 struct io_rw rw;
221c5eb2 531 struct io_poll_iocb poll;
8ed8d3c3
JA
532 struct io_accept accept;
533 struct io_sync sync;
fbf23849 534 struct io_cancel cancel;
b29472ee 535 struct io_timeout timeout;
3fbb51c1 536 struct io_connect connect;
e47293fd 537 struct io_sr_msg sr_msg;
15b71abe 538 struct io_open open;
b5dba59e 539 struct io_close close;
05f3fb3c 540 struct io_files_update files_update;
4840e418 541 struct io_fadvise fadvise;
c1ca757b 542 struct io_madvise madvise;
3e4827b0 543 struct io_epoll epoll;
221c5eb2 544 };
2b188cc1 545
1a6b74fc 546 struct io_async_ctx *io;
b14cca0c
PB
547 /*
548 * llist_node is only used for poll deferred completions
549 */
550 struct llist_node llist_node;
cf6fd4bd
PB
551 bool in_async;
552 bool needs_fixed_file;
d625c6ee 553 u8 opcode;
2b188cc1
JA
554
555 struct io_ring_ctx *ctx;
eac406c6
JA
556 union {
557 struct list_head list;
78076bb6 558 struct hlist_node hash_node;
eac406c6 559 };
9e645e11 560 struct list_head link_list;
2b188cc1 561 unsigned int flags;
c16361c1 562 refcount_t refs;
2b188cc1 563 u64 user_data;
9e645e11 564 u32 result;
de0617e4 565 u32 sequence;
2b188cc1 566
fcb323cc
JA
567 struct list_head inflight_entry;
568
561fb04a 569 struct io_wq_work work;
2b188cc1
JA
570};
571
572#define IO_PLUG_THRESHOLD 2
def596e9 573#define IO_IOPOLL_BATCH 8
2b188cc1 574
9a56a232
JA
575struct io_submit_state {
576 struct blk_plug plug;
577
2579f913
JA
578 /*
579 * io_kiocb alloc cache
580 */
581 void *reqs[IO_IOPOLL_BATCH];
6c8a3134 582 unsigned int free_reqs;
2579f913 583
9a56a232
JA
584 /*
585 * File reference cache
586 */
587 struct file *file;
588 unsigned int fd;
589 unsigned int has_refs;
590 unsigned int used_refs;
591 unsigned int ios_left;
592};
593
d3656344
JA
594struct io_op_def {
595 /* needs req->io allocated for deferral/async */
596 unsigned async_ctx : 1;
597 /* needs current->mm setup, does mm access */
598 unsigned needs_mm : 1;
599 /* needs req->file assigned */
600 unsigned needs_file : 1;
601 /* needs req->file assigned IFF fd is >= 0 */
602 unsigned fd_non_neg : 1;
603 /* hash wq insertion if file is a regular file */
604 unsigned hash_reg_file : 1;
605 /* unbound wq insertion if file is a non-regular file */
606 unsigned unbound_nonreg_file : 1;
66f4af93
JA
607 /* opcode is not supported by this kernel */
608 unsigned not_supported : 1;
f86cd20c
JA
609 /* needs file table */
610 unsigned file_table : 1;
d3656344
JA
611};
612
613static const struct io_op_def io_op_defs[] = {
0463b6c5
PB
614 [IORING_OP_NOP] = {},
615 [IORING_OP_READV] = {
d3656344
JA
616 .async_ctx = 1,
617 .needs_mm = 1,
618 .needs_file = 1,
619 .unbound_nonreg_file = 1,
620 },
0463b6c5 621 [IORING_OP_WRITEV] = {
d3656344
JA
622 .async_ctx = 1,
623 .needs_mm = 1,
624 .needs_file = 1,
625 .hash_reg_file = 1,
626 .unbound_nonreg_file = 1,
627 },
0463b6c5 628 [IORING_OP_FSYNC] = {
d3656344
JA
629 .needs_file = 1,
630 },
0463b6c5 631 [IORING_OP_READ_FIXED] = {
d3656344
JA
632 .needs_file = 1,
633 .unbound_nonreg_file = 1,
634 },
0463b6c5 635 [IORING_OP_WRITE_FIXED] = {
d3656344
JA
636 .needs_file = 1,
637 .hash_reg_file = 1,
638 .unbound_nonreg_file = 1,
639 },
0463b6c5 640 [IORING_OP_POLL_ADD] = {
d3656344
JA
641 .needs_file = 1,
642 .unbound_nonreg_file = 1,
643 },
0463b6c5
PB
644 [IORING_OP_POLL_REMOVE] = {},
645 [IORING_OP_SYNC_FILE_RANGE] = {
d3656344
JA
646 .needs_file = 1,
647 },
0463b6c5 648 [IORING_OP_SENDMSG] = {
d3656344
JA
649 .async_ctx = 1,
650 .needs_mm = 1,
651 .needs_file = 1,
652 .unbound_nonreg_file = 1,
653 },
0463b6c5 654 [IORING_OP_RECVMSG] = {
d3656344
JA
655 .async_ctx = 1,
656 .needs_mm = 1,
657 .needs_file = 1,
658 .unbound_nonreg_file = 1,
659 },
0463b6c5 660 [IORING_OP_TIMEOUT] = {
d3656344
JA
661 .async_ctx = 1,
662 .needs_mm = 1,
663 },
0463b6c5
PB
664 [IORING_OP_TIMEOUT_REMOVE] = {},
665 [IORING_OP_ACCEPT] = {
d3656344
JA
666 .needs_mm = 1,
667 .needs_file = 1,
668 .unbound_nonreg_file = 1,
f86cd20c 669 .file_table = 1,
d3656344 670 },
0463b6c5
PB
671 [IORING_OP_ASYNC_CANCEL] = {},
672 [IORING_OP_LINK_TIMEOUT] = {
d3656344
JA
673 .async_ctx = 1,
674 .needs_mm = 1,
675 },
0463b6c5 676 [IORING_OP_CONNECT] = {
d3656344
JA
677 .async_ctx = 1,
678 .needs_mm = 1,
679 .needs_file = 1,
680 .unbound_nonreg_file = 1,
681 },
0463b6c5 682 [IORING_OP_FALLOCATE] = {
d3656344
JA
683 .needs_file = 1,
684 },
0463b6c5 685 [IORING_OP_OPENAT] = {
d3656344
JA
686 .needs_file = 1,
687 .fd_non_neg = 1,
f86cd20c 688 .file_table = 1,
d3656344 689 },
0463b6c5 690 [IORING_OP_CLOSE] = {
d3656344 691 .needs_file = 1,
f86cd20c 692 .file_table = 1,
d3656344 693 },
0463b6c5 694 [IORING_OP_FILES_UPDATE] = {
d3656344 695 .needs_mm = 1,
f86cd20c 696 .file_table = 1,
d3656344 697 },
0463b6c5 698 [IORING_OP_STATX] = {
d3656344
JA
699 .needs_mm = 1,
700 .needs_file = 1,
701 .fd_non_neg = 1,
702 },
0463b6c5 703 [IORING_OP_READ] = {
3a6820f2
JA
704 .needs_mm = 1,
705 .needs_file = 1,
706 .unbound_nonreg_file = 1,
707 },
0463b6c5 708 [IORING_OP_WRITE] = {
3a6820f2
JA
709 .needs_mm = 1,
710 .needs_file = 1,
711 .unbound_nonreg_file = 1,
712 },
0463b6c5 713 [IORING_OP_FADVISE] = {
4840e418
JA
714 .needs_file = 1,
715 },
0463b6c5 716 [IORING_OP_MADVISE] = {
c1ca757b
JA
717 .needs_mm = 1,
718 },
0463b6c5 719 [IORING_OP_SEND] = {
fddaface
JA
720 .needs_mm = 1,
721 .needs_file = 1,
722 .unbound_nonreg_file = 1,
723 },
0463b6c5 724 [IORING_OP_RECV] = {
fddaface
JA
725 .needs_mm = 1,
726 .needs_file = 1,
727 .unbound_nonreg_file = 1,
728 },
0463b6c5 729 [IORING_OP_OPENAT2] = {
cebdb986
JA
730 .needs_file = 1,
731 .fd_non_neg = 1,
f86cd20c 732 .file_table = 1,
cebdb986 733 },
3e4827b0
JA
734 [IORING_OP_EPOLL_CTL] = {
735 .unbound_nonreg_file = 1,
736 .file_table = 1,
737 },
d3656344
JA
738};
739
561fb04a 740static void io_wq_submit_work(struct io_wq_work **workptr);
78e19bbe 741static void io_cqring_fill_event(struct io_kiocb *req, long res);
ec9c02ad 742static void io_put_req(struct io_kiocb *req);
978db57e 743static void __io_double_put_req(struct io_kiocb *req);
94ae5e77
JA
744static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
745static void io_queue_linked_timeout(struct io_kiocb *req);
05f3fb3c
JA
746static int __io_sqe_files_update(struct io_ring_ctx *ctx,
747 struct io_uring_files_update *ip,
748 unsigned nr_args);
f86cd20c 749static int io_grab_files(struct io_kiocb *req);
2faf852d 750static void io_ring_file_ref_flush(struct fixed_file_data *data);
de0617e4 751
2b188cc1
JA
752static struct kmem_cache *req_cachep;
753
754static const struct file_operations io_uring_fops;
755
756struct sock *io_uring_get_socket(struct file *file)
757{
758#if defined(CONFIG_UNIX)
759 if (file->f_op == &io_uring_fops) {
760 struct io_ring_ctx *ctx = file->private_data;
761
762 return ctx->ring_sock->sk;
763 }
764#endif
765 return NULL;
766}
767EXPORT_SYMBOL(io_uring_get_socket);
768
769static void io_ring_ctx_ref_free(struct percpu_ref *ref)
770{
771 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
772
206aefde 773 complete(&ctx->completions[0]);
2b188cc1
JA
774}
775
776static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
777{
778 struct io_ring_ctx *ctx;
78076bb6 779 int hash_bits;
2b188cc1
JA
780
781 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
782 if (!ctx)
783 return NULL;
784
0ddf92e8
JA
785 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
786 if (!ctx->fallback_req)
787 goto err;
788
206aefde
JA
789 ctx->completions = kmalloc(2 * sizeof(struct completion), GFP_KERNEL);
790 if (!ctx->completions)
791 goto err;
792
78076bb6
JA
793 /*
794 * Use 5 bits less than the max cq entries, that should give us around
795 * 32 entries per hash list if totally full and uniformly spread.
796 */
797 hash_bits = ilog2(p->cq_entries);
798 hash_bits -= 5;
799 if (hash_bits <= 0)
800 hash_bits = 1;
801 ctx->cancel_hash_bits = hash_bits;
802 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
803 GFP_KERNEL);
804 if (!ctx->cancel_hash)
805 goto err;
806 __hash_init(ctx->cancel_hash, 1U << hash_bits);
807
21482896 808 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
206aefde
JA
809 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
810 goto err;
2b188cc1
JA
811
812 ctx->flags = p->flags;
813 init_waitqueue_head(&ctx->cq_wait);
1d7bb1d5 814 INIT_LIST_HEAD(&ctx->cq_overflow_list);
206aefde
JA
815 init_completion(&ctx->completions[0]);
816 init_completion(&ctx->completions[1]);
071698e1 817 idr_init(&ctx->personality_idr);
2b188cc1
JA
818 mutex_init(&ctx->uring_lock);
819 init_waitqueue_head(&ctx->wait);
820 spin_lock_init(&ctx->completion_lock);
e94f141b 821 init_llist_head(&ctx->poll_llist);
def596e9 822 INIT_LIST_HEAD(&ctx->poll_list);
de0617e4 823 INIT_LIST_HEAD(&ctx->defer_list);
5262f567 824 INIT_LIST_HEAD(&ctx->timeout_list);
fcb323cc
JA
825 init_waitqueue_head(&ctx->inflight_wait);
826 spin_lock_init(&ctx->inflight_lock);
827 INIT_LIST_HEAD(&ctx->inflight_list);
2b188cc1 828 return ctx;
206aefde 829err:
0ddf92e8
JA
830 if (ctx->fallback_req)
831 kmem_cache_free(req_cachep, ctx->fallback_req);
206aefde 832 kfree(ctx->completions);
78076bb6 833 kfree(ctx->cancel_hash);
206aefde
JA
834 kfree(ctx);
835 return NULL;
2b188cc1
JA
836}
837
9d858b21 838static inline bool __req_need_defer(struct io_kiocb *req)
7adf4eaf 839{
a197f664
JL
840 struct io_ring_ctx *ctx = req->ctx;
841
498ccd9e
JA
842 return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
843 + atomic_read(&ctx->cached_cq_overflow);
7adf4eaf
JA
844}
845
9d858b21 846static inline bool req_need_defer(struct io_kiocb *req)
de0617e4 847{
87987898 848 if (unlikely(req->flags & REQ_F_IO_DRAIN))
9d858b21 849 return __req_need_defer(req);
de0617e4 850
9d858b21 851 return false;
de0617e4
JA
852}
853
7adf4eaf 854static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
de0617e4
JA
855{
856 struct io_kiocb *req;
857
7adf4eaf 858 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
9d858b21 859 if (req && !req_need_defer(req)) {
de0617e4
JA
860 list_del_init(&req->list);
861 return req;
862 }
863
864 return NULL;
865}
866
5262f567
JA
867static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
868{
7adf4eaf
JA
869 struct io_kiocb *req;
870
871 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
93bd25bb
JA
872 if (req) {
873 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
874 return NULL;
fb4b3d3f 875 if (!__req_need_defer(req)) {
93bd25bb
JA
876 list_del_init(&req->list);
877 return req;
878 }
7adf4eaf
JA
879 }
880
881 return NULL;
5262f567
JA
882}
883
de0617e4 884static void __io_commit_cqring(struct io_ring_ctx *ctx)
2b188cc1 885{
75b28aff 886 struct io_rings *rings = ctx->rings;
2b188cc1 887
07910158
PB
888 /* order cqe stores with ring update */
889 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
2b188cc1 890
07910158
PB
891 if (wq_has_sleeper(&ctx->cq_wait)) {
892 wake_up_interruptible(&ctx->cq_wait);
893 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
2b188cc1
JA
894 }
895}
896
cccf0ee8
JA
897static inline void io_req_work_grab_env(struct io_kiocb *req,
898 const struct io_op_def *def)
899{
900 if (!req->work.mm && def->needs_mm) {
901 mmgrab(current->mm);
902 req->work.mm = current->mm;
2b188cc1 903 }
cccf0ee8
JA
904 if (!req->work.creds)
905 req->work.creds = get_current_cred();
2b188cc1
JA
906}
907
cccf0ee8 908static inline void io_req_work_drop_env(struct io_kiocb *req)
18d9be1a 909{
cccf0ee8
JA
910 if (req->work.mm) {
911 mmdrop(req->work.mm);
912 req->work.mm = NULL;
913 }
914 if (req->work.creds) {
915 put_cred(req->work.creds);
916 req->work.creds = NULL;
917 }
561fb04a
JA
918}
919
94ae5e77
JA
920static inline bool io_prep_async_work(struct io_kiocb *req,
921 struct io_kiocb **link)
18d9be1a 922{
d3656344 923 const struct io_op_def *def = &io_op_defs[req->opcode];
561fb04a 924 bool do_hashed = false;
54a91f3b 925
d3656344
JA
926 if (req->flags & REQ_F_ISREG) {
927 if (def->hash_reg_file)
3529d8c2 928 do_hashed = true;
d3656344
JA
929 } else {
930 if (def->unbound_nonreg_file)
3529d8c2 931 req->work.flags |= IO_WQ_WORK_UNBOUND;
54a91f3b 932 }
cccf0ee8
JA
933
934 io_req_work_grab_env(req, def);
54a91f3b 935
94ae5e77 936 *link = io_prep_linked_timeout(req);
561fb04a
JA
937 return do_hashed;
938}
939
a197f664 940static inline void io_queue_async_work(struct io_kiocb *req)
561fb04a 941{
a197f664 942 struct io_ring_ctx *ctx = req->ctx;
94ae5e77
JA
943 struct io_kiocb *link;
944 bool do_hashed;
945
946 do_hashed = io_prep_async_work(req, &link);
561fb04a
JA
947
948 trace_io_uring_queue_async_work(ctx, do_hashed, req, &req->work,
949 req->flags);
950 if (!do_hashed) {
951 io_wq_enqueue(ctx->io_wq, &req->work);
952 } else {
953 io_wq_enqueue_hashed(ctx->io_wq, &req->work,
954 file_inode(req->file));
955 }
94ae5e77
JA
956
957 if (link)
958 io_queue_linked_timeout(link);
18d9be1a
JA
959}
960
5262f567
JA
961static void io_kill_timeout(struct io_kiocb *req)
962{
963 int ret;
964
2d28390a 965 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
5262f567
JA
966 if (ret != -1) {
967 atomic_inc(&req->ctx->cq_timeouts);
842f9612 968 list_del_init(&req->list);
78e19bbe 969 io_cqring_fill_event(req, 0);
ec9c02ad 970 io_put_req(req);
5262f567
JA
971 }
972}
973
974static void io_kill_timeouts(struct io_ring_ctx *ctx)
975{
976 struct io_kiocb *req, *tmp;
977
978 spin_lock_irq(&ctx->completion_lock);
979 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
980 io_kill_timeout(req);
981 spin_unlock_irq(&ctx->completion_lock);
982}
983
de0617e4
JA
984static void io_commit_cqring(struct io_ring_ctx *ctx)
985{
986 struct io_kiocb *req;
987
5262f567
JA
988 while ((req = io_get_timeout_req(ctx)) != NULL)
989 io_kill_timeout(req);
990
de0617e4
JA
991 __io_commit_cqring(ctx);
992
87987898 993 while ((req = io_get_deferred_req(ctx)) != NULL)
a197f664 994 io_queue_async_work(req);
de0617e4
JA
995}
996
2b188cc1
JA
997static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
998{
75b28aff 999 struct io_rings *rings = ctx->rings;
2b188cc1
JA
1000 unsigned tail;
1001
1002 tail = ctx->cached_cq_tail;
115e12e5
SB
1003 /*
1004 * writes to the cq entry need to come after reading head; the
1005 * control dependency is enough as we're using WRITE_ONCE to
1006 * fill the cq entry
1007 */
75b28aff 1008 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
2b188cc1
JA
1009 return NULL;
1010
1011 ctx->cached_cq_tail++;
75b28aff 1012 return &rings->cqes[tail & ctx->cq_mask];
2b188cc1
JA
1013}
1014
f2842ab5
JA
1015static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1016{
f0b493e6
JA
1017 if (!ctx->cq_ev_fd)
1018 return false;
f2842ab5
JA
1019 if (!ctx->eventfd_async)
1020 return true;
1021 return io_wq_current_is_worker() || in_interrupt();
1022}
1023
f0b493e6 1024static void __io_cqring_ev_posted(struct io_ring_ctx *ctx, bool trigger_ev)
1d7bb1d5
JA
1025{
1026 if (waitqueue_active(&ctx->wait))
1027 wake_up(&ctx->wait);
1028 if (waitqueue_active(&ctx->sqo_wait))
1029 wake_up(&ctx->sqo_wait);
f0b493e6 1030 if (trigger_ev)
1d7bb1d5
JA
1031 eventfd_signal(ctx->cq_ev_fd, 1);
1032}
1033
f0b493e6
JA
1034static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1035{
1036 __io_cqring_ev_posted(ctx, io_should_trigger_evfd(ctx));
1037}
1038
c4a2ed72
JA
1039/* Returns true if there are no backlogged entries after the flush */
1040static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1d7bb1d5
JA
1041{
1042 struct io_rings *rings = ctx->rings;
1043 struct io_uring_cqe *cqe;
1044 struct io_kiocb *req;
1045 unsigned long flags;
1046 LIST_HEAD(list);
1047
1048 if (!force) {
1049 if (list_empty_careful(&ctx->cq_overflow_list))
c4a2ed72 1050 return true;
1d7bb1d5
JA
1051 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
1052 rings->cq_ring_entries))
c4a2ed72 1053 return false;
1d7bb1d5
JA
1054 }
1055
1056 spin_lock_irqsave(&ctx->completion_lock, flags);
1057
1058 /* if force is set, the ring is going away. always drop after that */
1059 if (force)
69b3e546 1060 ctx->cq_overflow_flushed = 1;
1d7bb1d5 1061
c4a2ed72 1062 cqe = NULL;
1d7bb1d5
JA
1063 while (!list_empty(&ctx->cq_overflow_list)) {
1064 cqe = io_get_cqring(ctx);
1065 if (!cqe && !force)
1066 break;
1067
1068 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
1069 list);
1070 list_move(&req->list, &list);
1071 if (cqe) {
1072 WRITE_ONCE(cqe->user_data, req->user_data);
1073 WRITE_ONCE(cqe->res, req->result);
1074 WRITE_ONCE(cqe->flags, 0);
1075 } else {
1076 WRITE_ONCE(ctx->rings->cq_overflow,
1077 atomic_inc_return(&ctx->cached_cq_overflow));
1078 }
1079 }
1080
1081 io_commit_cqring(ctx);
ad3eb2c8
JA
1082 if (cqe) {
1083 clear_bit(0, &ctx->sq_check_overflow);
1084 clear_bit(0, &ctx->cq_check_overflow);
1085 }
1d7bb1d5
JA
1086 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1087 io_cqring_ev_posted(ctx);
1088
1089 while (!list_empty(&list)) {
1090 req = list_first_entry(&list, struct io_kiocb, list);
1091 list_del(&req->list);
ec9c02ad 1092 io_put_req(req);
1d7bb1d5 1093 }
c4a2ed72
JA
1094
1095 return cqe != NULL;
1d7bb1d5
JA
1096}
1097
78e19bbe 1098static void io_cqring_fill_event(struct io_kiocb *req, long res)
2b188cc1 1099{
78e19bbe 1100 struct io_ring_ctx *ctx = req->ctx;
2b188cc1
JA
1101 struct io_uring_cqe *cqe;
1102
78e19bbe 1103 trace_io_uring_complete(ctx, req->user_data, res);
51c3ff62 1104
2b188cc1
JA
1105 /*
1106 * If we can't get a cq entry, userspace overflowed the
1107 * submission (by quite a lot). Increment the overflow count in
1108 * the ring.
1109 */
1110 cqe = io_get_cqring(ctx);
1d7bb1d5 1111 if (likely(cqe)) {
78e19bbe 1112 WRITE_ONCE(cqe->user_data, req->user_data);
2b188cc1 1113 WRITE_ONCE(cqe->res, res);
c71ffb67 1114 WRITE_ONCE(cqe->flags, 0);
1d7bb1d5 1115 } else if (ctx->cq_overflow_flushed) {
498ccd9e
JA
1116 WRITE_ONCE(ctx->rings->cq_overflow,
1117 atomic_inc_return(&ctx->cached_cq_overflow));
1d7bb1d5 1118 } else {
ad3eb2c8
JA
1119 if (list_empty(&ctx->cq_overflow_list)) {
1120 set_bit(0, &ctx->sq_check_overflow);
1121 set_bit(0, &ctx->cq_check_overflow);
1122 }
1d7bb1d5
JA
1123 refcount_inc(&req->refs);
1124 req->result = res;
1125 list_add_tail(&req->list, &ctx->cq_overflow_list);
2b188cc1
JA
1126 }
1127}
1128
78e19bbe 1129static void io_cqring_add_event(struct io_kiocb *req, long res)
2b188cc1 1130{
78e19bbe 1131 struct io_ring_ctx *ctx = req->ctx;
2b188cc1
JA
1132 unsigned long flags;
1133
1134 spin_lock_irqsave(&ctx->completion_lock, flags);
78e19bbe 1135 io_cqring_fill_event(req, res);
2b188cc1
JA
1136 io_commit_cqring(ctx);
1137 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1138
8c838788 1139 io_cqring_ev_posted(ctx);
2b188cc1
JA
1140}
1141
0ddf92e8
JA
1142static inline bool io_is_fallback_req(struct io_kiocb *req)
1143{
1144 return req == (struct io_kiocb *)
1145 ((unsigned long) req->ctx->fallback_req & ~1UL);
1146}
1147
1148static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1149{
1150 struct io_kiocb *req;
1151
1152 req = ctx->fallback_req;
1153 if (!test_and_set_bit_lock(0, (unsigned long *) ctx->fallback_req))
1154 return req;
1155
1156 return NULL;
1157}
1158
2579f913
JA
1159static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
1160 struct io_submit_state *state)
2b188cc1 1161{
fd6fab2c 1162 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2b188cc1
JA
1163 struct io_kiocb *req;
1164
2579f913 1165 if (!state) {
fd6fab2c 1166 req = kmem_cache_alloc(req_cachep, gfp);
2579f913 1167 if (unlikely(!req))
0ddf92e8 1168 goto fallback;
2579f913
JA
1169 } else if (!state->free_reqs) {
1170 size_t sz;
1171 int ret;
1172
1173 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
fd6fab2c
JA
1174 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1175
1176 /*
1177 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1178 * retry single alloc to be on the safe side.
1179 */
1180 if (unlikely(ret <= 0)) {
1181 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1182 if (!state->reqs[0])
0ddf92e8 1183 goto fallback;
fd6fab2c
JA
1184 ret = 1;
1185 }
2579f913 1186 state->free_reqs = ret - 1;
6c8a3134 1187 req = state->reqs[ret - 1];
2579f913 1188 } else {
2579f913 1189 state->free_reqs--;
6c8a3134 1190 req = state->reqs[state->free_reqs];
2b188cc1
JA
1191 }
1192
0ddf92e8 1193got_it:
1a6b74fc 1194 req->io = NULL;
60c112b0 1195 req->file = NULL;
2579f913
JA
1196 req->ctx = ctx;
1197 req->flags = 0;
e65ef56d
JA
1198 /* one is dropped after submission, the other at completion */
1199 refcount_set(&req->refs, 2);
9e645e11 1200 req->result = 0;
561fb04a 1201 INIT_IO_WORK(&req->work, io_wq_submit_work);
2579f913 1202 return req;
0ddf92e8
JA
1203fallback:
1204 req = io_get_fallback_req(ctx);
1205 if (req)
1206 goto got_it;
6805b32e 1207 percpu_ref_put(&ctx->refs);
2b188cc1
JA
1208 return NULL;
1209}
1210
2b85edfc 1211static void __io_req_do_free(struct io_kiocb *req)
def596e9 1212{
2b85edfc
PB
1213 if (likely(!io_is_fallback_req(req)))
1214 kmem_cache_free(req_cachep, req);
1215 else
1216 clear_bit_unlock(0, (unsigned long *) req->ctx->fallback_req);
1217}
1218
c6ca97b3 1219static void __io_req_aux_free(struct io_kiocb *req)
2b188cc1 1220{
fcb323cc
JA
1221 struct io_ring_ctx *ctx = req->ctx;
1222
96fd84d8 1223 kfree(req->io);
05f3fb3c
JA
1224 if (req->file) {
1225 if (req->flags & REQ_F_FIXED_FILE)
1226 percpu_ref_put(&ctx->file_data->refs);
1227 else
1228 fput(req->file);
def596e9 1229 }
cccf0ee8
JA
1230
1231 io_req_work_drop_env(req);
def596e9
JA
1232}
1233
9e645e11 1234static void __io_free_req(struct io_kiocb *req)
2b188cc1 1235{
c6ca97b3 1236 __io_req_aux_free(req);
fcb323cc 1237
fcb323cc 1238 if (req->flags & REQ_F_INFLIGHT) {
c6ca97b3 1239 struct io_ring_ctx *ctx = req->ctx;
fcb323cc
JA
1240 unsigned long flags;
1241
1242 spin_lock_irqsave(&ctx->inflight_lock, flags);
1243 list_del(&req->inflight_entry);
1244 if (waitqueue_active(&ctx->inflight_wait))
1245 wake_up(&ctx->inflight_wait);
1246 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1247 }
2b85edfc
PB
1248
1249 percpu_ref_put(&req->ctx->refs);
1250 __io_req_do_free(req);
e65ef56d
JA
1251}
1252
c6ca97b3
JA
1253struct req_batch {
1254 void *reqs[IO_IOPOLL_BATCH];
1255 int to_free;
1256 int need_iter;
1257};
1258
1259static void io_free_req_many(struct io_ring_ctx *ctx, struct req_batch *rb)
1260{
10fef4be
JA
1261 int fixed_refs = rb->to_free;
1262
c6ca97b3
JA
1263 if (!rb->to_free)
1264 return;
1265 if (rb->need_iter) {
1266 int i, inflight = 0;
1267 unsigned long flags;
1268
10fef4be 1269 fixed_refs = 0;
c6ca97b3
JA
1270 for (i = 0; i < rb->to_free; i++) {
1271 struct io_kiocb *req = rb->reqs[i];
1272
10fef4be 1273 if (req->flags & REQ_F_FIXED_FILE) {
c6ca97b3 1274 req->file = NULL;
10fef4be
JA
1275 fixed_refs++;
1276 }
c6ca97b3
JA
1277 if (req->flags & REQ_F_INFLIGHT)
1278 inflight++;
c6ca97b3
JA
1279 __io_req_aux_free(req);
1280 }
1281 if (!inflight)
1282 goto do_free;
1283
1284 spin_lock_irqsave(&ctx->inflight_lock, flags);
1285 for (i = 0; i < rb->to_free; i++) {
1286 struct io_kiocb *req = rb->reqs[i];
1287
10fef4be 1288 if (req->flags & REQ_F_INFLIGHT) {
c6ca97b3
JA
1289 list_del(&req->inflight_entry);
1290 if (!--inflight)
1291 break;
1292 }
1293 }
1294 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1295
1296 if (waitqueue_active(&ctx->inflight_wait))
1297 wake_up(&ctx->inflight_wait);
1298 }
1299do_free:
1300 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
10fef4be
JA
1301 if (fixed_refs)
1302 percpu_ref_put_many(&ctx->file_data->refs, fixed_refs);
c6ca97b3 1303 percpu_ref_put_many(&ctx->refs, rb->to_free);
c6ca97b3 1304 rb->to_free = rb->need_iter = 0;
e65ef56d
JA
1305}
1306
a197f664 1307static bool io_link_cancel_timeout(struct io_kiocb *req)
2665abfd 1308{
a197f664 1309 struct io_ring_ctx *ctx = req->ctx;
2665abfd
JA
1310 int ret;
1311
2d28390a 1312 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
2665abfd 1313 if (ret != -1) {
78e19bbe 1314 io_cqring_fill_event(req, -ECANCELED);
2665abfd
JA
1315 io_commit_cqring(ctx);
1316 req->flags &= ~REQ_F_LINK;
ec9c02ad 1317 io_put_req(req);
2665abfd
JA
1318 return true;
1319 }
1320
1321 return false;
e65ef56d
JA
1322}
1323
ba816ad6 1324static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
9e645e11 1325{
2665abfd 1326 struct io_ring_ctx *ctx = req->ctx;
2665abfd 1327 bool wake_ev = false;
9e645e11 1328
4d7dd462
JA
1329 /* Already got next link */
1330 if (req->flags & REQ_F_LINK_NEXT)
1331 return;
1332
9e645e11
JA
1333 /*
1334 * The list should never be empty when we are called here. But could
1335 * potentially happen if the chain is messed up, check to be on the
1336 * safe side.
1337 */
4493233e
PB
1338 while (!list_empty(&req->link_list)) {
1339 struct io_kiocb *nxt = list_first_entry(&req->link_list,
1340 struct io_kiocb, link_list);
94ae5e77 1341
4493233e
PB
1342 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
1343 (nxt->flags & REQ_F_TIMEOUT))) {
1344 list_del_init(&nxt->link_list);
94ae5e77 1345 wake_ev |= io_link_cancel_timeout(nxt);
94ae5e77
JA
1346 req->flags &= ~REQ_F_LINK_TIMEOUT;
1347 continue;
1348 }
9e645e11 1349
4493233e
PB
1350 list_del_init(&req->link_list);
1351 if (!list_empty(&nxt->link_list))
1352 nxt->flags |= REQ_F_LINK;
b18fdf71 1353 *nxtptr = nxt;
94ae5e77 1354 break;
9e645e11 1355 }
2665abfd 1356
4d7dd462 1357 req->flags |= REQ_F_LINK_NEXT;
2665abfd
JA
1358 if (wake_ev)
1359 io_cqring_ev_posted(ctx);
9e645e11
JA
1360}
1361
1362/*
1363 * Called if REQ_F_LINK is set, and we fail the head request
1364 */
1365static void io_fail_links(struct io_kiocb *req)
1366{
2665abfd 1367 struct io_ring_ctx *ctx = req->ctx;
2665abfd
JA
1368 unsigned long flags;
1369
1370 spin_lock_irqsave(&ctx->completion_lock, flags);
9e645e11
JA
1371
1372 while (!list_empty(&req->link_list)) {
4493233e
PB
1373 struct io_kiocb *link = list_first_entry(&req->link_list,
1374 struct io_kiocb, link_list);
9e645e11 1375
4493233e 1376 list_del_init(&link->link_list);
c826bd7a 1377 trace_io_uring_fail_link(req, link);
2665abfd
JA
1378
1379 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
d625c6ee 1380 link->opcode == IORING_OP_LINK_TIMEOUT) {
a197f664 1381 io_link_cancel_timeout(link);
2665abfd 1382 } else {
78e19bbe 1383 io_cqring_fill_event(link, -ECANCELED);
978db57e 1384 __io_double_put_req(link);
2665abfd 1385 }
5d960724 1386 req->flags &= ~REQ_F_LINK_TIMEOUT;
9e645e11 1387 }
2665abfd
JA
1388
1389 io_commit_cqring(ctx);
1390 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1391 io_cqring_ev_posted(ctx);
9e645e11
JA
1392}
1393
4d7dd462 1394static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
9e645e11 1395{
4d7dd462 1396 if (likely(!(req->flags & REQ_F_LINK)))
2665abfd 1397 return;
2665abfd 1398
9e645e11
JA
1399 /*
1400 * If LINK is set, we have dependent requests in this chain. If we
1401 * didn't fail this request, queue the first one up, moving any other
1402 * dependencies to the next request. In case of failure, fail the rest
1403 * of the chain.
1404 */
2665abfd
JA
1405 if (req->flags & REQ_F_FAIL_LINK) {
1406 io_fail_links(req);
7c9e7f0f
JA
1407 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1408 REQ_F_LINK_TIMEOUT) {
2665abfd
JA
1409 struct io_ring_ctx *ctx = req->ctx;
1410 unsigned long flags;
1411
1412 /*
1413 * If this is a timeout link, we could be racing with the
1414 * timeout timer. Grab the completion lock for this case to
7c9e7f0f 1415 * protect against that.
2665abfd
JA
1416 */
1417 spin_lock_irqsave(&ctx->completion_lock, flags);
1418 io_req_link_next(req, nxt);
1419 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1420 } else {
1421 io_req_link_next(req, nxt);
9e645e11 1422 }
4d7dd462 1423}
9e645e11 1424
c69f8dbe
JL
1425static void io_free_req(struct io_kiocb *req)
1426{
944e58bf
PB
1427 struct io_kiocb *nxt = NULL;
1428
1429 io_req_find_next(req, &nxt);
70cf9f32 1430 __io_free_req(req);
944e58bf
PB
1431
1432 if (nxt)
1433 io_queue_async_work(nxt);
c69f8dbe
JL
1434}
1435
ba816ad6
JA
1436/*
1437 * Drop reference to request, return next in chain (if there is one) if this
1438 * was the last reference to this request.
1439 */
f9bd67f6 1440__attribute__((nonnull))
ec9c02ad 1441static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
e65ef56d 1442{
f9bd67f6 1443 io_req_find_next(req, nxtptr);
4d7dd462 1444
e65ef56d 1445 if (refcount_dec_and_test(&req->refs))
4d7dd462 1446 __io_free_req(req);
2b188cc1
JA
1447}
1448
e65ef56d
JA
1449static void io_put_req(struct io_kiocb *req)
1450{
1451 if (refcount_dec_and_test(&req->refs))
1452 io_free_req(req);
2b188cc1
JA
1453}
1454
978db57e
JA
1455/*
1456 * Must only be used if we don't need to care about links, usually from
1457 * within the completion handling itself.
1458 */
1459static void __io_double_put_req(struct io_kiocb *req)
78e19bbe
JA
1460{
1461 /* drop both submit and complete references */
1462 if (refcount_sub_and_test(2, &req->refs))
1463 __io_free_req(req);
1464}
1465
978db57e
JA
1466static void io_double_put_req(struct io_kiocb *req)
1467{
1468 /* drop both submit and complete references */
1469 if (refcount_sub_and_test(2, &req->refs))
1470 io_free_req(req);
1471}
1472
1d7bb1d5 1473static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
a3a0e43f 1474{
84f97dc2
JA
1475 struct io_rings *rings = ctx->rings;
1476
ad3eb2c8
JA
1477 if (test_bit(0, &ctx->cq_check_overflow)) {
1478 /*
1479 * noflush == true is from the waitqueue handler, just ensure
1480 * we wake up the task, and the next invocation will flush the
1481 * entries. We cannot safely to it from here.
1482 */
1483 if (noflush && !list_empty(&ctx->cq_overflow_list))
1484 return -1U;
1d7bb1d5 1485
ad3eb2c8
JA
1486 io_cqring_overflow_flush(ctx, false);
1487 }
1d7bb1d5 1488
a3a0e43f
JA
1489 /* See comment at the top of this file */
1490 smp_rmb();
ad3eb2c8 1491 return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
a3a0e43f
JA
1492}
1493
fb5ccc98
PB
1494static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1495{
1496 struct io_rings *rings = ctx->rings;
1497
1498 /* make sure SQ entry isn't read before tail */
1499 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1500}
1501
8237e045 1502static inline bool io_req_multi_free(struct req_batch *rb, struct io_kiocb *req)
e94f141b 1503{
c6ca97b3
JA
1504 if ((req->flags & REQ_F_LINK) || io_is_fallback_req(req))
1505 return false;
e94f141b 1506
c6ca97b3
JA
1507 if (!(req->flags & REQ_F_FIXED_FILE) || req->io)
1508 rb->need_iter++;
1509
1510 rb->reqs[rb->to_free++] = req;
1511 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
1512 io_free_req_many(req->ctx, rb);
1513 return true;
e94f141b
JA
1514}
1515
def596e9
JA
1516/*
1517 * Find and free completed poll iocbs
1518 */
1519static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1520 struct list_head *done)
1521{
8237e045 1522 struct req_batch rb;
def596e9 1523 struct io_kiocb *req;
def596e9 1524
c6ca97b3 1525 rb.to_free = rb.need_iter = 0;
def596e9
JA
1526 while (!list_empty(done)) {
1527 req = list_first_entry(done, struct io_kiocb, list);
1528 list_del(&req->list);
1529
78e19bbe 1530 io_cqring_fill_event(req, req->result);
def596e9
JA
1531 (*nr_events)++;
1532
8237e045
JA
1533 if (refcount_dec_and_test(&req->refs) &&
1534 !io_req_multi_free(&rb, req))
1535 io_free_req(req);
def596e9 1536 }
def596e9 1537
09bb8394 1538 io_commit_cqring(ctx);
8237e045 1539 io_free_req_many(ctx, &rb);
def596e9
JA
1540}
1541
1542static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1543 long min)
1544{
1545 struct io_kiocb *req, *tmp;
1546 LIST_HEAD(done);
1547 bool spin;
1548 int ret;
1549
1550 /*
1551 * Only spin for completions if we don't have multiple devices hanging
1552 * off our complete list, and we're under the requested amount.
1553 */
1554 spin = !ctx->poll_multi_file && *nr_events < min;
1555
1556 ret = 0;
1557 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
9adbd45d 1558 struct kiocb *kiocb = &req->rw.kiocb;
def596e9
JA
1559
1560 /*
1561 * Move completed entries to our local list. If we find a
1562 * request that requires polling, break out and complete
1563 * the done list first, if we have entries there.
1564 */
1565 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
1566 list_move_tail(&req->list, &done);
1567 continue;
1568 }
1569 if (!list_empty(&done))
1570 break;
1571
1572 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1573 if (ret < 0)
1574 break;
1575
1576 if (ret && spin)
1577 spin = false;
1578 ret = 0;
1579 }
1580
1581 if (!list_empty(&done))
1582 io_iopoll_complete(ctx, nr_events, &done);
1583
1584 return ret;
1585}
1586
1587/*
d195a66e 1588 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
def596e9
JA
1589 * non-spinning poll check - we'll still enter the driver poll loop, but only
1590 * as a non-spinning completion check.
1591 */
1592static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1593 long min)
1594{
08f5439f 1595 while (!list_empty(&ctx->poll_list) && !need_resched()) {
def596e9
JA
1596 int ret;
1597
1598 ret = io_do_iopoll(ctx, nr_events, min);
1599 if (ret < 0)
1600 return ret;
1601 if (!min || *nr_events >= min)
1602 return 0;
1603 }
1604
1605 return 1;
1606}
1607
1608/*
1609 * We can't just wait for polled events to come to us, we have to actively
1610 * find and complete them.
1611 */
1612static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1613{
1614 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1615 return;
1616
1617 mutex_lock(&ctx->uring_lock);
1618 while (!list_empty(&ctx->poll_list)) {
1619 unsigned int nr_events = 0;
1620
1621 io_iopoll_getevents(ctx, &nr_events, 1);
08f5439f
JA
1622
1623 /*
1624 * Ensure we allow local-to-the-cpu processing to take place,
1625 * in this case we need to ensure that we reap all events.
1626 */
1627 cond_resched();
def596e9
JA
1628 }
1629 mutex_unlock(&ctx->uring_lock);
1630}
1631
2b2ed975
JA
1632static int __io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1633 long min)
def596e9 1634{
2b2ed975 1635 int iters = 0, ret = 0;
500f9fba 1636
def596e9
JA
1637 do {
1638 int tmin = 0;
1639
a3a0e43f
JA
1640 /*
1641 * Don't enter poll loop if we already have events pending.
1642 * If we do, we can potentially be spinning for commands that
1643 * already triggered a CQE (eg in error).
1644 */
1d7bb1d5 1645 if (io_cqring_events(ctx, false))
a3a0e43f
JA
1646 break;
1647
500f9fba
JA
1648 /*
1649 * If a submit got punted to a workqueue, we can have the
1650 * application entering polling for a command before it gets
1651 * issued. That app will hold the uring_lock for the duration
1652 * of the poll right here, so we need to take a breather every
1653 * now and then to ensure that the issue has a chance to add
1654 * the poll to the issued list. Otherwise we can spin here
1655 * forever, while the workqueue is stuck trying to acquire the
1656 * very same mutex.
1657 */
1658 if (!(++iters & 7)) {
1659 mutex_unlock(&ctx->uring_lock);
1660 mutex_lock(&ctx->uring_lock);
1661 }
1662
def596e9
JA
1663 if (*nr_events < min)
1664 tmin = min - *nr_events;
1665
1666 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1667 if (ret <= 0)
1668 break;
1669 ret = 0;
1670 } while (min && !*nr_events && !need_resched());
1671
2b2ed975
JA
1672 return ret;
1673}
1674
1675static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1676 long min)
1677{
1678 int ret;
1679
1680 /*
1681 * We disallow the app entering submit/complete with polling, but we
1682 * still need to lock the ring to prevent racing with polled issue
1683 * that got punted to a workqueue.
1684 */
1685 mutex_lock(&ctx->uring_lock);
1686 ret = __io_iopoll_check(ctx, nr_events, min);
500f9fba 1687 mutex_unlock(&ctx->uring_lock);
def596e9
JA
1688 return ret;
1689}
1690
491381ce 1691static void kiocb_end_write(struct io_kiocb *req)
2b188cc1 1692{
491381ce
JA
1693 /*
1694 * Tell lockdep we inherited freeze protection from submission
1695 * thread.
1696 */
1697 if (req->flags & REQ_F_ISREG) {
1698 struct inode *inode = file_inode(req->file);
2b188cc1 1699
491381ce 1700 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2b188cc1 1701 }
491381ce 1702 file_end_write(req->file);
2b188cc1
JA
1703}
1704
4e88d6e7
JA
1705static inline void req_set_fail_links(struct io_kiocb *req)
1706{
1707 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1708 req->flags |= REQ_F_FAIL_LINK;
1709}
1710
ba816ad6 1711static void io_complete_rw_common(struct kiocb *kiocb, long res)
2b188cc1 1712{
9adbd45d 1713 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2b188cc1 1714
491381ce
JA
1715 if (kiocb->ki_flags & IOCB_WRITE)
1716 kiocb_end_write(req);
2b188cc1 1717
4e88d6e7
JA
1718 if (res != req->result)
1719 req_set_fail_links(req);
78e19bbe 1720 io_cqring_add_event(req, res);
ba816ad6
JA
1721}
1722
1723static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1724{
9adbd45d 1725 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
ba816ad6
JA
1726
1727 io_complete_rw_common(kiocb, res);
e65ef56d 1728 io_put_req(req);
2b188cc1
JA
1729}
1730
ba816ad6
JA
1731static struct io_kiocb *__io_complete_rw(struct kiocb *kiocb, long res)
1732{
9adbd45d 1733 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
ec9c02ad 1734 struct io_kiocb *nxt = NULL;
ba816ad6
JA
1735
1736 io_complete_rw_common(kiocb, res);
ec9c02ad
JL
1737 io_put_req_find_next(req, &nxt);
1738
1739 return nxt;
2b188cc1
JA
1740}
1741
def596e9
JA
1742static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1743{
9adbd45d 1744 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
def596e9 1745
491381ce
JA
1746 if (kiocb->ki_flags & IOCB_WRITE)
1747 kiocb_end_write(req);
def596e9 1748
4e88d6e7
JA
1749 if (res != req->result)
1750 req_set_fail_links(req);
9e645e11 1751 req->result = res;
def596e9
JA
1752 if (res != -EAGAIN)
1753 req->flags |= REQ_F_IOPOLL_COMPLETED;
1754}
1755
1756/*
1757 * After the iocb has been issued, it's safe to be found on the poll list.
1758 * Adding the kiocb to the list AFTER submission ensures that we don't
1759 * find it from a io_iopoll_getevents() thread before the issuer is done
1760 * accessing the kiocb cookie.
1761 */
1762static void io_iopoll_req_issued(struct io_kiocb *req)
1763{
1764 struct io_ring_ctx *ctx = req->ctx;
1765
1766 /*
1767 * Track whether we have multiple files in our lists. This will impact
1768 * how we do polling eventually, not spinning if we're on potentially
1769 * different devices.
1770 */
1771 if (list_empty(&ctx->poll_list)) {
1772 ctx->poll_multi_file = false;
1773 } else if (!ctx->poll_multi_file) {
1774 struct io_kiocb *list_req;
1775
1776 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1777 list);
9adbd45d 1778 if (list_req->file != req->file)
def596e9
JA
1779 ctx->poll_multi_file = true;
1780 }
1781
1782 /*
1783 * For fast devices, IO may have already completed. If it has, add
1784 * it to the front so we find it first.
1785 */
1786 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1787 list_add(&req->list, &ctx->poll_list);
1788 else
1789 list_add_tail(&req->list, &ctx->poll_list);
1790}
1791
3d6770fb 1792static void io_file_put(struct io_submit_state *state)
9a56a232 1793{
3d6770fb 1794 if (state->file) {
9a56a232
JA
1795 int diff = state->has_refs - state->used_refs;
1796
1797 if (diff)
1798 fput_many(state->file, diff);
1799 state->file = NULL;
1800 }
1801}
1802
1803/*
1804 * Get as many references to a file as we have IOs left in this submission,
1805 * assuming most submissions are for one file, or at least that each file
1806 * has more than one submission.
1807 */
1808static struct file *io_file_get(struct io_submit_state *state, int fd)
1809{
1810 if (!state)
1811 return fget(fd);
1812
1813 if (state->file) {
1814 if (state->fd == fd) {
1815 state->used_refs++;
1816 state->ios_left--;
1817 return state->file;
1818 }
3d6770fb 1819 io_file_put(state);
9a56a232
JA
1820 }
1821 state->file = fget_many(fd, state->ios_left);
1822 if (!state->file)
1823 return NULL;
1824
1825 state->fd = fd;
1826 state->has_refs = state->ios_left;
1827 state->used_refs = 1;
1828 state->ios_left--;
1829 return state->file;
1830}
1831
2b188cc1
JA
1832/*
1833 * If we tracked the file through the SCM inflight mechanism, we could support
1834 * any file. For now, just ensure that anything potentially problematic is done
1835 * inline.
1836 */
1837static bool io_file_supports_async(struct file *file)
1838{
1839 umode_t mode = file_inode(file)->i_mode;
1840
10d59345 1841 if (S_ISBLK(mode) || S_ISCHR(mode) || S_ISSOCK(mode))
2b188cc1
JA
1842 return true;
1843 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1844 return true;
1845
1846 return false;
1847}
1848
3529d8c2
JA
1849static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1850 bool force_nonblock)
2b188cc1 1851{
def596e9 1852 struct io_ring_ctx *ctx = req->ctx;
9adbd45d 1853 struct kiocb *kiocb = &req->rw.kiocb;
09bb8394
JA
1854 unsigned ioprio;
1855 int ret;
2b188cc1 1856
491381ce
JA
1857 if (S_ISREG(file_inode(req->file)->i_mode))
1858 req->flags |= REQ_F_ISREG;
1859
2b188cc1 1860 kiocb->ki_pos = READ_ONCE(sqe->off);
ba04291e
JA
1861 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
1862 req->flags |= REQ_F_CUR_POS;
1863 kiocb->ki_pos = req->file->f_pos;
1864 }
2b188cc1 1865 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
3e577dcd
PB
1866 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1867 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1868 if (unlikely(ret))
1869 return ret;
2b188cc1
JA
1870
1871 ioprio = READ_ONCE(sqe->ioprio);
1872 if (ioprio) {
1873 ret = ioprio_check_cap(ioprio);
1874 if (ret)
09bb8394 1875 return ret;
2b188cc1
JA
1876
1877 kiocb->ki_ioprio = ioprio;
1878 } else
1879 kiocb->ki_ioprio = get_current_ioprio();
1880
8449eeda 1881 /* don't allow async punt if RWF_NOWAIT was requested */
491381ce
JA
1882 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1883 (req->file->f_flags & O_NONBLOCK))
8449eeda
SB
1884 req->flags |= REQ_F_NOWAIT;
1885
1886 if (force_nonblock)
2b188cc1 1887 kiocb->ki_flags |= IOCB_NOWAIT;
8449eeda 1888
def596e9 1889 if (ctx->flags & IORING_SETUP_IOPOLL) {
def596e9
JA
1890 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1891 !kiocb->ki_filp->f_op->iopoll)
09bb8394 1892 return -EOPNOTSUPP;
2b188cc1 1893
def596e9
JA
1894 kiocb->ki_flags |= IOCB_HIPRI;
1895 kiocb->ki_complete = io_complete_rw_iopoll;
6873e0bd 1896 req->result = 0;
def596e9 1897 } else {
09bb8394
JA
1898 if (kiocb->ki_flags & IOCB_HIPRI)
1899 return -EINVAL;
def596e9
JA
1900 kiocb->ki_complete = io_complete_rw;
1901 }
9adbd45d 1902
3529d8c2
JA
1903 req->rw.addr = READ_ONCE(sqe->addr);
1904 req->rw.len = READ_ONCE(sqe->len);
9adbd45d
JA
1905 /* we own ->private, reuse it for the buffer index */
1906 req->rw.kiocb.private = (void *) (unsigned long)
3529d8c2 1907 READ_ONCE(sqe->buf_index);
2b188cc1 1908 return 0;
2b188cc1
JA
1909}
1910
1911static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1912{
1913 switch (ret) {
1914 case -EIOCBQUEUED:
1915 break;
1916 case -ERESTARTSYS:
1917 case -ERESTARTNOINTR:
1918 case -ERESTARTNOHAND:
1919 case -ERESTART_RESTARTBLOCK:
1920 /*
1921 * We can't just restart the syscall, since previously
1922 * submitted sqes may already be in progress. Just fail this
1923 * IO with EINTR.
1924 */
1925 ret = -EINTR;
1926 /* fall through */
1927 default:
1928 kiocb->ki_complete(kiocb, ret, 0);
1929 }
1930}
1931
ba816ad6
JA
1932static void kiocb_done(struct kiocb *kiocb, ssize_t ret, struct io_kiocb **nxt,
1933 bool in_async)
1934{
ba04291e
JA
1935 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1936
1937 if (req->flags & REQ_F_CUR_POS)
1938 req->file->f_pos = kiocb->ki_pos;
f9bd67f6 1939 if (in_async && ret >= 0 && kiocb->ki_complete == io_complete_rw)
ba816ad6
JA
1940 *nxt = __io_complete_rw(kiocb, ret);
1941 else
1942 io_rw_done(kiocb, ret);
1943}
1944
9adbd45d 1945static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
7d009165 1946 struct iov_iter *iter)
edafccee 1947{
9adbd45d
JA
1948 struct io_ring_ctx *ctx = req->ctx;
1949 size_t len = req->rw.len;
edafccee
JA
1950 struct io_mapped_ubuf *imu;
1951 unsigned index, buf_index;
1952 size_t offset;
1953 u64 buf_addr;
1954
1955 /* attempt to use fixed buffers without having provided iovecs */
1956 if (unlikely(!ctx->user_bufs))
1957 return -EFAULT;
1958
9adbd45d 1959 buf_index = (unsigned long) req->rw.kiocb.private;
edafccee
JA
1960 if (unlikely(buf_index >= ctx->nr_user_bufs))
1961 return -EFAULT;
1962
1963 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1964 imu = &ctx->user_bufs[index];
9adbd45d 1965 buf_addr = req->rw.addr;
edafccee
JA
1966
1967 /* overflow */
1968 if (buf_addr + len < buf_addr)
1969 return -EFAULT;
1970 /* not inside the mapped region */
1971 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1972 return -EFAULT;
1973
1974 /*
1975 * May not be a start of buffer, set size appropriately
1976 * and advance us to the beginning.
1977 */
1978 offset = buf_addr - imu->ubuf;
1979 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
bd11b3a3
JA
1980
1981 if (offset) {
1982 /*
1983 * Don't use iov_iter_advance() here, as it's really slow for
1984 * using the latter parts of a big fixed buffer - it iterates
1985 * over each segment manually. We can cheat a bit here, because
1986 * we know that:
1987 *
1988 * 1) it's a BVEC iter, we set it up
1989 * 2) all bvecs are PAGE_SIZE in size, except potentially the
1990 * first and last bvec
1991 *
1992 * So just find our index, and adjust the iterator afterwards.
1993 * If the offset is within the first bvec (or the whole first
1994 * bvec, just use iov_iter_advance(). This makes it easier
1995 * since we can just skip the first segment, which may not
1996 * be PAGE_SIZE aligned.
1997 */
1998 const struct bio_vec *bvec = imu->bvec;
1999
2000 if (offset <= bvec->bv_len) {
2001 iov_iter_advance(iter, offset);
2002 } else {
2003 unsigned long seg_skip;
2004
2005 /* skip first vec */
2006 offset -= bvec->bv_len;
2007 seg_skip = 1 + (offset >> PAGE_SHIFT);
2008
2009 iter->bvec = bvec + seg_skip;
2010 iter->nr_segs -= seg_skip;
99c79f66 2011 iter->count -= bvec->bv_len + offset;
bd11b3a3 2012 iter->iov_offset = offset & ~PAGE_MASK;
bd11b3a3
JA
2013 }
2014 }
2015
5e559561 2016 return len;
edafccee
JA
2017}
2018
cf6fd4bd
PB
2019static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
2020 struct iovec **iovec, struct iov_iter *iter)
2b188cc1 2021{
9adbd45d
JA
2022 void __user *buf = u64_to_user_ptr(req->rw.addr);
2023 size_t sqe_len = req->rw.len;
edafccee
JA
2024 u8 opcode;
2025
d625c6ee 2026 opcode = req->opcode;
7d009165 2027 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
edafccee 2028 *iovec = NULL;
9adbd45d 2029 return io_import_fixed(req, rw, iter);
edafccee 2030 }
2b188cc1 2031
9adbd45d
JA
2032 /* buffer index only valid with fixed read/write */
2033 if (req->rw.kiocb.private)
2034 return -EINVAL;
2035
3a6820f2
JA
2036 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2037 ssize_t ret;
2038 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2039 *iovec = NULL;
2040 return ret;
2041 }
2042
f67676d1
JA
2043 if (req->io) {
2044 struct io_async_rw *iorw = &req->io->rw;
2045
2046 *iovec = iorw->iov;
2047 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
2048 if (iorw->iov == iorw->fast_iov)
2049 *iovec = NULL;
2050 return iorw->size;
2051 }
2052
2b188cc1 2053#ifdef CONFIG_COMPAT
cf6fd4bd 2054 if (req->ctx->compat)
2b188cc1
JA
2055 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
2056 iovec, iter);
2057#endif
2058
2059 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
2060}
2061
31b51510 2062/*
32960613
JA
2063 * For files that don't have ->read_iter() and ->write_iter(), handle them
2064 * by looping over ->read() or ->write() manually.
31b51510 2065 */
32960613
JA
2066static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2067 struct iov_iter *iter)
2068{
2069 ssize_t ret = 0;
2070
2071 /*
2072 * Don't support polled IO through this interface, and we can't
2073 * support non-blocking either. For the latter, this just causes
2074 * the kiocb to be handled from an async context.
2075 */
2076 if (kiocb->ki_flags & IOCB_HIPRI)
2077 return -EOPNOTSUPP;
2078 if (kiocb->ki_flags & IOCB_NOWAIT)
2079 return -EAGAIN;
2080
2081 while (iov_iter_count(iter)) {
311ae9e1 2082 struct iovec iovec;
32960613
JA
2083 ssize_t nr;
2084
311ae9e1
PB
2085 if (!iov_iter_is_bvec(iter)) {
2086 iovec = iov_iter_iovec(iter);
2087 } else {
2088 /* fixed buffers import bvec */
2089 iovec.iov_base = kmap(iter->bvec->bv_page)
2090 + iter->iov_offset;
2091 iovec.iov_len = min(iter->count,
2092 iter->bvec->bv_len - iter->iov_offset);
2093 }
2094
32960613
JA
2095 if (rw == READ) {
2096 nr = file->f_op->read(file, iovec.iov_base,
2097 iovec.iov_len, &kiocb->ki_pos);
2098 } else {
2099 nr = file->f_op->write(file, iovec.iov_base,
2100 iovec.iov_len, &kiocb->ki_pos);
2101 }
2102
311ae9e1
PB
2103 if (iov_iter_is_bvec(iter))
2104 kunmap(iter->bvec->bv_page);
2105
32960613
JA
2106 if (nr < 0) {
2107 if (!ret)
2108 ret = nr;
2109 break;
2110 }
2111 ret += nr;
2112 if (nr != iovec.iov_len)
2113 break;
2114 iov_iter_advance(iter, nr);
2115 }
2116
2117 return ret;
2118}
2119
b7bb4f7d 2120static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
f67676d1
JA
2121 struct iovec *iovec, struct iovec *fast_iov,
2122 struct iov_iter *iter)
2123{
2124 req->io->rw.nr_segs = iter->nr_segs;
2125 req->io->rw.size = io_size;
2126 req->io->rw.iov = iovec;
2127 if (!req->io->rw.iov) {
2128 req->io->rw.iov = req->io->rw.fast_iov;
2129 memcpy(req->io->rw.iov, fast_iov,
2130 sizeof(struct iovec) * iter->nr_segs);
2131 }
2132}
2133
b7bb4f7d 2134static int io_alloc_async_ctx(struct io_kiocb *req)
f67676d1 2135{
d3656344
JA
2136 if (!io_op_defs[req->opcode].async_ctx)
2137 return 0;
f67676d1 2138 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
06b76d44 2139 return req->io == NULL;
b7bb4f7d
JA
2140}
2141
b7bb4f7d
JA
2142static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
2143 struct iovec *iovec, struct iovec *fast_iov,
2144 struct iov_iter *iter)
2145{
980ad263 2146 if (!io_op_defs[req->opcode].async_ctx)
74566df3 2147 return 0;
5d204bcf
JA
2148 if (!req->io) {
2149 if (io_alloc_async_ctx(req))
2150 return -ENOMEM;
b7bb4f7d 2151
5d204bcf
JA
2152 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
2153 }
b7bb4f7d 2154 return 0;
f67676d1
JA
2155}
2156
3529d8c2
JA
2157static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2158 bool force_nonblock)
f67676d1 2159{
3529d8c2
JA
2160 struct io_async_ctx *io;
2161 struct iov_iter iter;
f67676d1
JA
2162 ssize_t ret;
2163
3529d8c2
JA
2164 ret = io_prep_rw(req, sqe, force_nonblock);
2165 if (ret)
2166 return ret;
f67676d1 2167
3529d8c2
JA
2168 if (unlikely(!(req->file->f_mode & FMODE_READ)))
2169 return -EBADF;
f67676d1 2170
3529d8c2
JA
2171 if (!req->io)
2172 return 0;
2173
2174 io = req->io;
2175 io->rw.iov = io->rw.fast_iov;
2176 req->io = NULL;
2177 ret = io_import_iovec(READ, req, &io->rw.iov, &iter);
2178 req->io = io;
2179 if (ret < 0)
2180 return ret;
2181
2182 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2183 return 0;
f67676d1
JA
2184}
2185
267bc904 2186static int io_read(struct io_kiocb *req, struct io_kiocb **nxt,
8358e3a8 2187 bool force_nonblock)
2b188cc1
JA
2188{
2189 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
9adbd45d 2190 struct kiocb *kiocb = &req->rw.kiocb;
2b188cc1 2191 struct iov_iter iter;
31b51510 2192 size_t iov_count;
f67676d1 2193 ssize_t io_size, ret;
2b188cc1 2194
3529d8c2 2195 ret = io_import_iovec(READ, req, &iovec, &iter);
06b76d44
JA
2196 if (ret < 0)
2197 return ret;
2b188cc1 2198
fd6c2e4c
JA
2199 /* Ensure we clear previously set non-block flag */
2200 if (!force_nonblock)
9adbd45d 2201 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
fd6c2e4c 2202
797f3f53 2203 req->result = 0;
f67676d1 2204 io_size = ret;
9e645e11 2205 if (req->flags & REQ_F_LINK)
f67676d1
JA
2206 req->result = io_size;
2207
2208 /*
2209 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2210 * we know to async punt it even if it was opened O_NONBLOCK
2211 */
9adbd45d 2212 if (force_nonblock && !io_file_supports_async(req->file)) {
f67676d1
JA
2213 req->flags |= REQ_F_MUST_PUNT;
2214 goto copy_iov;
2215 }
9e645e11 2216
31b51510 2217 iov_count = iov_iter_count(&iter);
9adbd45d 2218 ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
2b188cc1
JA
2219 if (!ret) {
2220 ssize_t ret2;
2221
9adbd45d
JA
2222 if (req->file->f_op->read_iter)
2223 ret2 = call_read_iter(req->file, kiocb, &iter);
32960613 2224 else
9adbd45d 2225 ret2 = loop_rw_iter(READ, req->file, kiocb, &iter);
32960613 2226
9d93a3f5 2227 /* Catch -EAGAIN return for forced non-blocking submission */
f67676d1 2228 if (!force_nonblock || ret2 != -EAGAIN) {
cf6fd4bd 2229 kiocb_done(kiocb, ret2, nxt, req->in_async);
f67676d1
JA
2230 } else {
2231copy_iov:
b7bb4f7d 2232 ret = io_setup_async_rw(req, io_size, iovec,
f67676d1
JA
2233 inline_vecs, &iter);
2234 if (ret)
2235 goto out_free;
2236 return -EAGAIN;
2237 }
2b188cc1 2238 }
f67676d1 2239out_free:
1e95081c 2240 kfree(iovec);
2b188cc1
JA
2241 return ret;
2242}
2243
3529d8c2
JA
2244static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2245 bool force_nonblock)
f67676d1 2246{
3529d8c2
JA
2247 struct io_async_ctx *io;
2248 struct iov_iter iter;
f67676d1
JA
2249 ssize_t ret;
2250
3529d8c2
JA
2251 ret = io_prep_rw(req, sqe, force_nonblock);
2252 if (ret)
2253 return ret;
f67676d1 2254
3529d8c2
JA
2255 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
2256 return -EBADF;
f67676d1 2257
3529d8c2
JA
2258 if (!req->io)
2259 return 0;
2260
2261 io = req->io;
2262 io->rw.iov = io->rw.fast_iov;
2263 req->io = NULL;
2264 ret = io_import_iovec(WRITE, req, &io->rw.iov, &iter);
2265 req->io = io;
2266 if (ret < 0)
2267 return ret;
2268
2269 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2270 return 0;
f67676d1
JA
2271}
2272
267bc904 2273static int io_write(struct io_kiocb *req, struct io_kiocb **nxt,
8358e3a8 2274 bool force_nonblock)
2b188cc1
JA
2275{
2276 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
9adbd45d 2277 struct kiocb *kiocb = &req->rw.kiocb;
2b188cc1 2278 struct iov_iter iter;
31b51510 2279 size_t iov_count;
f67676d1 2280 ssize_t ret, io_size;
2b188cc1 2281
3529d8c2 2282 ret = io_import_iovec(WRITE, req, &iovec, &iter);
06b76d44
JA
2283 if (ret < 0)
2284 return ret;
2b188cc1 2285
fd6c2e4c
JA
2286 /* Ensure we clear previously set non-block flag */
2287 if (!force_nonblock)
9adbd45d 2288 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
fd6c2e4c 2289
797f3f53 2290 req->result = 0;
f67676d1 2291 io_size = ret;
9e645e11 2292 if (req->flags & REQ_F_LINK)
f67676d1 2293 req->result = io_size;
9e645e11 2294
f67676d1
JA
2295 /*
2296 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2297 * we know to async punt it even if it was opened O_NONBLOCK
2298 */
2299 if (force_nonblock && !io_file_supports_async(req->file)) {
2300 req->flags |= REQ_F_MUST_PUNT;
2301 goto copy_iov;
2302 }
31b51510 2303
10d59345
JA
2304 /* file path doesn't support NOWAIT for non-direct_IO */
2305 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
2306 (req->flags & REQ_F_ISREG))
f67676d1 2307 goto copy_iov;
31b51510 2308
f67676d1 2309 iov_count = iov_iter_count(&iter);
9adbd45d 2310 ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
2b188cc1 2311 if (!ret) {
9bf7933f
RP
2312 ssize_t ret2;
2313
2b188cc1
JA
2314 /*
2315 * Open-code file_start_write here to grab freeze protection,
2316 * which will be released by another thread in
2317 * io_complete_rw(). Fool lockdep by telling it the lock got
2318 * released so that it doesn't complain about the held lock when
2319 * we return to userspace.
2320 */
491381ce 2321 if (req->flags & REQ_F_ISREG) {
9adbd45d 2322 __sb_start_write(file_inode(req->file)->i_sb,
2b188cc1 2323 SB_FREEZE_WRITE, true);
9adbd45d 2324 __sb_writers_release(file_inode(req->file)->i_sb,
2b188cc1
JA
2325 SB_FREEZE_WRITE);
2326 }
2327 kiocb->ki_flags |= IOCB_WRITE;
9bf7933f 2328
9adbd45d
JA
2329 if (req->file->f_op->write_iter)
2330 ret2 = call_write_iter(req->file, kiocb, &iter);
32960613 2331 else
9adbd45d 2332 ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
f67676d1 2333 if (!force_nonblock || ret2 != -EAGAIN) {
cf6fd4bd 2334 kiocb_done(kiocb, ret2, nxt, req->in_async);
f67676d1
JA
2335 } else {
2336copy_iov:
b7bb4f7d 2337 ret = io_setup_async_rw(req, io_size, iovec,
f67676d1
JA
2338 inline_vecs, &iter);
2339 if (ret)
2340 goto out_free;
2341 return -EAGAIN;
2342 }
2b188cc1 2343 }
31b51510 2344out_free:
1e95081c 2345 kfree(iovec);
2b188cc1
JA
2346 return ret;
2347}
2348
2349/*
2350 * IORING_OP_NOP just posts a completion event, nothing else.
2351 */
78e19bbe 2352static int io_nop(struct io_kiocb *req)
2b188cc1
JA
2353{
2354 struct io_ring_ctx *ctx = req->ctx;
2b188cc1 2355
def596e9
JA
2356 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2357 return -EINVAL;
2358
78e19bbe 2359 io_cqring_add_event(req, 0);
e65ef56d 2360 io_put_req(req);
2b188cc1
JA
2361 return 0;
2362}
2363
3529d8c2 2364static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
c992fe29 2365{
6b06314c 2366 struct io_ring_ctx *ctx = req->ctx;
c992fe29 2367
09bb8394
JA
2368 if (!req->file)
2369 return -EBADF;
c992fe29 2370
6b06314c 2371 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
def596e9 2372 return -EINVAL;
edafccee 2373 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
c992fe29
CH
2374 return -EINVAL;
2375
8ed8d3c3
JA
2376 req->sync.flags = READ_ONCE(sqe->fsync_flags);
2377 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
2378 return -EINVAL;
2379
2380 req->sync.off = READ_ONCE(sqe->off);
2381 req->sync.len = READ_ONCE(sqe->len);
c992fe29
CH
2382 return 0;
2383}
2384
8ed8d3c3
JA
2385static bool io_req_cancelled(struct io_kiocb *req)
2386{
2387 if (req->work.flags & IO_WQ_WORK_CANCEL) {
2388 req_set_fail_links(req);
2389 io_cqring_add_event(req, -ECANCELED);
2390 io_put_req(req);
2391 return true;
2392 }
2393
2394 return false;
2395}
2396
78912934
JA
2397static void io_link_work_cb(struct io_wq_work **workptr)
2398{
2399 struct io_wq_work *work = *workptr;
2400 struct io_kiocb *link = work->data;
2401
2402 io_queue_linked_timeout(link);
2403 work->func = io_wq_submit_work;
2404}
2405
2406static void io_wq_assign_next(struct io_wq_work **workptr, struct io_kiocb *nxt)
2407{
2408 struct io_kiocb *link;
2409
2410 io_prep_async_work(nxt, &link);
2411 *workptr = &nxt->work;
2412 if (link) {
2413 nxt->work.flags |= IO_WQ_WORK_CB;
2414 nxt->work.func = io_link_work_cb;
2415 nxt->work.data = link;
2416 }
2417}
2418
8ed8d3c3
JA
2419static void io_fsync_finish(struct io_wq_work **workptr)
2420{
2421 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2422 loff_t end = req->sync.off + req->sync.len;
2423 struct io_kiocb *nxt = NULL;
2424 int ret;
2425
2426 if (io_req_cancelled(req))
2427 return;
2428
9adbd45d 2429 ret = vfs_fsync_range(req->file, req->sync.off,
8ed8d3c3
JA
2430 end > 0 ? end : LLONG_MAX,
2431 req->sync.flags & IORING_FSYNC_DATASYNC);
2432 if (ret < 0)
2433 req_set_fail_links(req);
2434 io_cqring_add_event(req, ret);
2435 io_put_req_find_next(req, &nxt);
2436 if (nxt)
78912934 2437 io_wq_assign_next(workptr, nxt);
8ed8d3c3
JA
2438}
2439
fc4df999
JA
2440static int io_fsync(struct io_kiocb *req, struct io_kiocb **nxt,
2441 bool force_nonblock)
c992fe29 2442{
8ed8d3c3 2443 struct io_wq_work *work, *old_work;
c992fe29
CH
2444
2445 /* fsync always requires a blocking context */
8ed8d3c3
JA
2446 if (force_nonblock) {
2447 io_put_req(req);
2448 req->work.func = io_fsync_finish;
c992fe29 2449 return -EAGAIN;
8ed8d3c3 2450 }
c992fe29 2451
8ed8d3c3
JA
2452 work = old_work = &req->work;
2453 io_fsync_finish(&work);
2454 if (work && work != old_work)
2455 *nxt = container_of(work, struct io_kiocb, work);
c992fe29
CH
2456 return 0;
2457}
2458
d63d1b5e 2459static void io_fallocate_finish(struct io_wq_work **workptr)
8ed8d3c3
JA
2460{
2461 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2462 struct io_kiocb *nxt = NULL;
2463 int ret;
2464
d63d1b5e
JA
2465 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
2466 req->sync.len);
8ed8d3c3
JA
2467 if (ret < 0)
2468 req_set_fail_links(req);
2469 io_cqring_add_event(req, ret);
2470 io_put_req_find_next(req, &nxt);
2471 if (nxt)
78912934 2472 io_wq_assign_next(workptr, nxt);
5d17b4a4
JA
2473}
2474
d63d1b5e
JA
2475static int io_fallocate_prep(struct io_kiocb *req,
2476 const struct io_uring_sqe *sqe)
2477{
2478 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
2479 return -EINVAL;
2480
2481 req->sync.off = READ_ONCE(sqe->off);
2482 req->sync.len = READ_ONCE(sqe->addr);
2483 req->sync.mode = READ_ONCE(sqe->len);
2484 return 0;
2485}
2486
2487static int io_fallocate(struct io_kiocb *req, struct io_kiocb **nxt,
2488 bool force_nonblock)
5d17b4a4 2489{
8ed8d3c3 2490 struct io_wq_work *work, *old_work;
5d17b4a4 2491
d63d1b5e 2492 /* fallocate always requiring blocking context */
8ed8d3c3
JA
2493 if (force_nonblock) {
2494 io_put_req(req);
d63d1b5e 2495 req->work.func = io_fallocate_finish;
5d17b4a4 2496 return -EAGAIN;
8ed8d3c3 2497 }
5d17b4a4 2498
8ed8d3c3 2499 work = old_work = &req->work;
d63d1b5e 2500 io_fallocate_finish(&work);
8ed8d3c3
JA
2501 if (work && work != old_work)
2502 *nxt = container_of(work, struct io_kiocb, work);
d63d1b5e 2503
5d17b4a4
JA
2504 return 0;
2505}
2506
15b71abe 2507static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
b7bb4f7d 2508{
f8748881 2509 const char __user *fname;
15b71abe 2510 int ret;
b7bb4f7d 2511
15b71abe
JA
2512 if (sqe->ioprio || sqe->buf_index)
2513 return -EINVAL;
cf3040ca
JA
2514 if (sqe->flags & IOSQE_FIXED_FILE)
2515 return -EBADF;
03b1230c 2516
15b71abe 2517 req->open.dfd = READ_ONCE(sqe->fd);
c12cedf2 2518 req->open.how.mode = READ_ONCE(sqe->len);
f8748881 2519 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
c12cedf2 2520 req->open.how.flags = READ_ONCE(sqe->open_flags);
3529d8c2 2521
f8748881 2522 req->open.filename = getname(fname);
15b71abe
JA
2523 if (IS_ERR(req->open.filename)) {
2524 ret = PTR_ERR(req->open.filename);
2525 req->open.filename = NULL;
2526 return ret;
2527 }
3529d8c2 2528
15b71abe 2529 return 0;
03b1230c
JA
2530}
2531
cebdb986 2532static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
aa1fa28f 2533{
cebdb986
JA
2534 struct open_how __user *how;
2535 const char __user *fname;
2536 size_t len;
0fa03c62
JA
2537 int ret;
2538
cebdb986 2539 if (sqe->ioprio || sqe->buf_index)
0fa03c62 2540 return -EINVAL;
cf3040ca
JA
2541 if (sqe->flags & IOSQE_FIXED_FILE)
2542 return -EBADF;
0fa03c62 2543
cebdb986
JA
2544 req->open.dfd = READ_ONCE(sqe->fd);
2545 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2546 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2547 len = READ_ONCE(sqe->len);
0fa03c62 2548
cebdb986
JA
2549 if (len < OPEN_HOW_SIZE_VER0)
2550 return -EINVAL;
3529d8c2 2551
cebdb986
JA
2552 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
2553 len);
2554 if (ret)
2555 return ret;
3529d8c2 2556
cebdb986
JA
2557 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
2558 req->open.how.flags |= O_LARGEFILE;
0fa03c62 2559
cebdb986
JA
2560 req->open.filename = getname(fname);
2561 if (IS_ERR(req->open.filename)) {
2562 ret = PTR_ERR(req->open.filename);
2563 req->open.filename = NULL;
2564 return ret;
2565 }
2566
2567 return 0;
2568}
2569
2570static int io_openat2(struct io_kiocb *req, struct io_kiocb **nxt,
2571 bool force_nonblock)
15b71abe
JA
2572{
2573 struct open_flags op;
15b71abe
JA
2574 struct file *file;
2575 int ret;
2576
f86cd20c 2577 if (force_nonblock)
15b71abe 2578 return -EAGAIN;
15b71abe 2579
cebdb986 2580 ret = build_open_flags(&req->open.how, &op);
15b71abe
JA
2581 if (ret)
2582 goto err;
2583
cebdb986 2584 ret = get_unused_fd_flags(req->open.how.flags);
15b71abe
JA
2585 if (ret < 0)
2586 goto err;
2587
2588 file = do_filp_open(req->open.dfd, req->open.filename, &op);
2589 if (IS_ERR(file)) {
2590 put_unused_fd(ret);
2591 ret = PTR_ERR(file);
2592 } else {
2593 fsnotify_open(file);
2594 fd_install(ret, file);
2595 }
2596err:
2597 putname(req->open.filename);
2598 if (ret < 0)
2599 req_set_fail_links(req);
2600 io_cqring_add_event(req, ret);
2601 io_put_req_find_next(req, nxt);
2602 return 0;
2603}
2604
cebdb986
JA
2605static int io_openat(struct io_kiocb *req, struct io_kiocb **nxt,
2606 bool force_nonblock)
2607{
2608 req->open.how = build_open_how(req->open.how.flags, req->open.how.mode);
2609 return io_openat2(req, nxt, force_nonblock);
2610}
2611
3e4827b0
JA
2612static int io_epoll_ctl_prep(struct io_kiocb *req,
2613 const struct io_uring_sqe *sqe)
2614{
2615#if defined(CONFIG_EPOLL)
2616 if (sqe->ioprio || sqe->buf_index)
2617 return -EINVAL;
2618
2619 req->epoll.epfd = READ_ONCE(sqe->fd);
2620 req->epoll.op = READ_ONCE(sqe->len);
2621 req->epoll.fd = READ_ONCE(sqe->off);
2622
2623 if (ep_op_has_event(req->epoll.op)) {
2624 struct epoll_event __user *ev;
2625
2626 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
2627 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
2628 return -EFAULT;
2629 }
2630
2631 return 0;
2632#else
2633 return -EOPNOTSUPP;
2634#endif
2635}
2636
2637static int io_epoll_ctl(struct io_kiocb *req, struct io_kiocb **nxt,
2638 bool force_nonblock)
2639{
2640#if defined(CONFIG_EPOLL)
2641 struct io_epoll *ie = &req->epoll;
2642 int ret;
2643
2644 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
2645 if (force_nonblock && ret == -EAGAIN)
2646 return -EAGAIN;
2647
2648 if (ret < 0)
2649 req_set_fail_links(req);
2650 io_cqring_add_event(req, ret);
2651 io_put_req_find_next(req, nxt);
2652 return 0;
2653#else
2654 return -EOPNOTSUPP;
2655#endif
2656}
2657
c1ca757b
JA
2658static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2659{
2660#if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
2661 if (sqe->ioprio || sqe->buf_index || sqe->off)
2662 return -EINVAL;
2663
2664 req->madvise.addr = READ_ONCE(sqe->addr);
2665 req->madvise.len = READ_ONCE(sqe->len);
2666 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
2667 return 0;
2668#else
2669 return -EOPNOTSUPP;
2670#endif
2671}
2672
2673static int io_madvise(struct io_kiocb *req, struct io_kiocb **nxt,
2674 bool force_nonblock)
2675{
2676#if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
2677 struct io_madvise *ma = &req->madvise;
2678 int ret;
2679
2680 if (force_nonblock)
2681 return -EAGAIN;
2682
2683 ret = do_madvise(ma->addr, ma->len, ma->advice);
2684 if (ret < 0)
2685 req_set_fail_links(req);
2686 io_cqring_add_event(req, ret);
2687 io_put_req_find_next(req, nxt);
2688 return 0;
2689#else
2690 return -EOPNOTSUPP;
2691#endif
2692}
2693
4840e418
JA
2694static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2695{
2696 if (sqe->ioprio || sqe->buf_index || sqe->addr)
2697 return -EINVAL;
2698
2699 req->fadvise.offset = READ_ONCE(sqe->off);
2700 req->fadvise.len = READ_ONCE(sqe->len);
2701 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
2702 return 0;
2703}
2704
2705static int io_fadvise(struct io_kiocb *req, struct io_kiocb **nxt,
2706 bool force_nonblock)
2707{
2708 struct io_fadvise *fa = &req->fadvise;
2709 int ret;
2710
3e69426d
JA
2711 if (force_nonblock) {
2712 switch (fa->advice) {
2713 case POSIX_FADV_NORMAL:
2714 case POSIX_FADV_RANDOM:
2715 case POSIX_FADV_SEQUENTIAL:
2716 break;
2717 default:
2718 return -EAGAIN;
2719 }
2720 }
4840e418
JA
2721
2722 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
2723 if (ret < 0)
2724 req_set_fail_links(req);
2725 io_cqring_add_event(req, ret);
2726 io_put_req_find_next(req, nxt);
2727 return 0;
2728}
2729
eddc7ef5
JA
2730static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2731{
f8748881 2732 const char __user *fname;
eddc7ef5
JA
2733 unsigned lookup_flags;
2734 int ret;
2735
2736 if (sqe->ioprio || sqe->buf_index)
2737 return -EINVAL;
cf3040ca
JA
2738 if (sqe->flags & IOSQE_FIXED_FILE)
2739 return -EBADF;
eddc7ef5
JA
2740
2741 req->open.dfd = READ_ONCE(sqe->fd);
2742 req->open.mask = READ_ONCE(sqe->len);
f8748881 2743 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
eddc7ef5 2744 req->open.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
c12cedf2 2745 req->open.how.flags = READ_ONCE(sqe->statx_flags);
eddc7ef5 2746
c12cedf2 2747 if (vfs_stat_set_lookup_flags(&lookup_flags, req->open.how.flags))
eddc7ef5
JA
2748 return -EINVAL;
2749
f8748881 2750 req->open.filename = getname_flags(fname, lookup_flags, NULL);
eddc7ef5
JA
2751 if (IS_ERR(req->open.filename)) {
2752 ret = PTR_ERR(req->open.filename);
2753 req->open.filename = NULL;
2754 return ret;
2755 }
2756
2757 return 0;
2758}
2759
2760static int io_statx(struct io_kiocb *req, struct io_kiocb **nxt,
2761 bool force_nonblock)
2762{
2763 struct io_open *ctx = &req->open;
2764 unsigned lookup_flags;
2765 struct path path;
2766 struct kstat stat;
2767 int ret;
2768
2769 if (force_nonblock)
2770 return -EAGAIN;
2771
c12cedf2 2772 if (vfs_stat_set_lookup_flags(&lookup_flags, ctx->how.flags))
eddc7ef5
JA
2773 return -EINVAL;
2774
2775retry:
2776 /* filename_lookup() drops it, keep a reference */
2777 ctx->filename->refcnt++;
2778
2779 ret = filename_lookup(ctx->dfd, ctx->filename, lookup_flags, &path,
2780 NULL);
2781 if (ret)
2782 goto err;
2783
c12cedf2 2784 ret = vfs_getattr(&path, &stat, ctx->mask, ctx->how.flags);
eddc7ef5
JA
2785 path_put(&path);
2786 if (retry_estale(ret, lookup_flags)) {
2787 lookup_flags |= LOOKUP_REVAL;
2788 goto retry;
2789 }
2790 if (!ret)
2791 ret = cp_statx(&stat, ctx->buffer);
2792err:
2793 putname(ctx->filename);
2794 if (ret < 0)
2795 req_set_fail_links(req);
2796 io_cqring_add_event(req, ret);
2797 io_put_req_find_next(req, nxt);
2798 return 0;
2799}
2800
b5dba59e
JA
2801static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2802{
2803 /*
2804 * If we queue this for async, it must not be cancellable. That would
2805 * leave the 'file' in an undeterminate state.
2806 */
2807 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
2808
2809 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
2810 sqe->rw_flags || sqe->buf_index)
2811 return -EINVAL;
2812 if (sqe->flags & IOSQE_FIXED_FILE)
cf3040ca 2813 return -EBADF;
b5dba59e
JA
2814
2815 req->close.fd = READ_ONCE(sqe->fd);
2816 if (req->file->f_op == &io_uring_fops ||
b14cca0c 2817 req->close.fd == req->ctx->ring_fd)
b5dba59e
JA
2818 return -EBADF;
2819
2820 return 0;
2821}
2822
2823static void io_close_finish(struct io_wq_work **workptr)
2824{
2825 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2826 struct io_kiocb *nxt = NULL;
2827
2828 /* Invoked with files, we need to do the close */
2829 if (req->work.files) {
2830 int ret;
2831
2832 ret = filp_close(req->close.put_file, req->work.files);
1a417f4e 2833 if (ret < 0)
b5dba59e 2834 req_set_fail_links(req);
b5dba59e
JA
2835 io_cqring_add_event(req, ret);
2836 }
2837
2838 fput(req->close.put_file);
2839
b5dba59e
JA
2840 io_put_req_find_next(req, &nxt);
2841 if (nxt)
2842 io_wq_assign_next(workptr, nxt);
2843}
2844
2845static int io_close(struct io_kiocb *req, struct io_kiocb **nxt,
2846 bool force_nonblock)
2847{
2848 int ret;
2849
2850 req->close.put_file = NULL;
2851 ret = __close_fd_get_file(req->close.fd, &req->close.put_file);
2852 if (ret < 0)
2853 return ret;
2854
2855 /* if the file has a flush method, be safe and punt to async */
f86cd20c 2856 if (req->close.put_file->f_op->flush && !io_wq_current_is_worker())
b5dba59e 2857 goto eagain;
b5dba59e
JA
2858
2859 /*
2860 * No ->flush(), safely close from here and just punt the
2861 * fput() to async context.
2862 */
2863 ret = filp_close(req->close.put_file, current->files);
2864
2865 if (ret < 0)
2866 req_set_fail_links(req);
2867 io_cqring_add_event(req, ret);
2868
2869 if (io_wq_current_is_worker()) {
2870 struct io_wq_work *old_work, *work;
2871
2872 old_work = work = &req->work;
2873 io_close_finish(&work);
2874 if (work && work != old_work)
2875 *nxt = container_of(work, struct io_kiocb, work);
2876 return 0;
2877 }
2878
2879eagain:
2880 req->work.func = io_close_finish;
1a417f4e
JA
2881 /*
2882 * Do manual async queue here to avoid grabbing files - we don't
2883 * need the files, and it'll cause io_close_finish() to close
2884 * the file again and cause a double CQE entry for this request
2885 */
2886 io_queue_async_work(req);
2887 return 0;
b5dba59e
JA
2888}
2889
3529d8c2 2890static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5d17b4a4
JA
2891{
2892 struct io_ring_ctx *ctx = req->ctx;
5d17b4a4
JA
2893
2894 if (!req->file)
2895 return -EBADF;
5d17b4a4
JA
2896
2897 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2898 return -EINVAL;
2899 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2900 return -EINVAL;
2901
8ed8d3c3
JA
2902 req->sync.off = READ_ONCE(sqe->off);
2903 req->sync.len = READ_ONCE(sqe->len);
2904 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
8ed8d3c3
JA
2905 return 0;
2906}
2907
2908static void io_sync_file_range_finish(struct io_wq_work **workptr)
2909{
2910 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2911 struct io_kiocb *nxt = NULL;
2912 int ret;
2913
2914 if (io_req_cancelled(req))
2915 return;
2916
9adbd45d 2917 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
8ed8d3c3
JA
2918 req->sync.flags);
2919 if (ret < 0)
2920 req_set_fail_links(req);
2921 io_cqring_add_event(req, ret);
2922 io_put_req_find_next(req, &nxt);
2923 if (nxt)
78912934 2924 io_wq_assign_next(workptr, nxt);
5d17b4a4
JA
2925}
2926
fc4df999 2927static int io_sync_file_range(struct io_kiocb *req, struct io_kiocb **nxt,
5d17b4a4
JA
2928 bool force_nonblock)
2929{
8ed8d3c3 2930 struct io_wq_work *work, *old_work;
5d17b4a4
JA
2931
2932 /* sync_file_range always requires a blocking context */
8ed8d3c3
JA
2933 if (force_nonblock) {
2934 io_put_req(req);
2935 req->work.func = io_sync_file_range_finish;
5d17b4a4 2936 return -EAGAIN;
8ed8d3c3 2937 }
5d17b4a4 2938
8ed8d3c3
JA
2939 work = old_work = &req->work;
2940 io_sync_file_range_finish(&work);
2941 if (work && work != old_work)
2942 *nxt = container_of(work, struct io_kiocb, work);
5d17b4a4
JA
2943 return 0;
2944}
2945
3529d8c2 2946static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
03b1230c 2947{
0fa03c62 2948#if defined(CONFIG_NET)
e47293fd 2949 struct io_sr_msg *sr = &req->sr_msg;
3529d8c2 2950 struct io_async_ctx *io = req->io;
03b1230c 2951
e47293fd
JA
2952 sr->msg_flags = READ_ONCE(sqe->msg_flags);
2953 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
fddaface 2954 sr->len = READ_ONCE(sqe->len);
3529d8c2 2955
fddaface 2956 if (!io || req->opcode == IORING_OP_SEND)
3529d8c2
JA
2957 return 0;
2958
d9688565 2959 io->msg.iov = io->msg.fast_iov;
3529d8c2 2960 return sendmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
e47293fd 2961 &io->msg.iov);
03b1230c 2962#else
e47293fd 2963 return -EOPNOTSUPP;
03b1230c
JA
2964#endif
2965}
2966
fc4df999
JA
2967static int io_sendmsg(struct io_kiocb *req, struct io_kiocb **nxt,
2968 bool force_nonblock)
aa1fa28f 2969{
03b1230c 2970#if defined(CONFIG_NET)
0b416c3e 2971 struct io_async_msghdr *kmsg = NULL;
0fa03c62
JA
2972 struct socket *sock;
2973 int ret;
2974
2975 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2976 return -EINVAL;
2977
2978 sock = sock_from_file(req->file, &ret);
2979 if (sock) {
b7bb4f7d 2980 struct io_async_ctx io;
03b1230c 2981 struct sockaddr_storage addr;
0fa03c62
JA
2982 unsigned flags;
2983
03b1230c 2984 if (req->io) {
0b416c3e
JA
2985 kmsg = &req->io->msg;
2986 kmsg->msg.msg_name = &addr;
2987 /* if iov is set, it's allocated already */
2988 if (!kmsg->iov)
2989 kmsg->iov = kmsg->fast_iov;
2990 kmsg->msg.msg_iter.iov = kmsg->iov;
03b1230c 2991 } else {
3529d8c2
JA
2992 struct io_sr_msg *sr = &req->sr_msg;
2993
0b416c3e
JA
2994 kmsg = &io.msg;
2995 kmsg->msg.msg_name = &addr;
3529d8c2
JA
2996
2997 io.msg.iov = io.msg.fast_iov;
2998 ret = sendmsg_copy_msghdr(&io.msg.msg, sr->msg,
2999 sr->msg_flags, &io.msg.iov);
03b1230c 3000 if (ret)
3529d8c2 3001 return ret;
03b1230c 3002 }
0fa03c62 3003
e47293fd
JA
3004 flags = req->sr_msg.msg_flags;
3005 if (flags & MSG_DONTWAIT)
3006 req->flags |= REQ_F_NOWAIT;
3007 else if (force_nonblock)
3008 flags |= MSG_DONTWAIT;
3009
0b416c3e 3010 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
03b1230c 3011 if (force_nonblock && ret == -EAGAIN) {
b7bb4f7d
JA
3012 if (req->io)
3013 return -EAGAIN;
1e95081c
PB
3014 if (io_alloc_async_ctx(req)) {
3015 if (kmsg && kmsg->iov != kmsg->fast_iov)
3016 kfree(kmsg->iov);
b7bb4f7d 3017 return -ENOMEM;
1e95081c 3018 }
b7bb4f7d 3019 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
0b416c3e 3020 return -EAGAIN;
03b1230c 3021 }
441cdbd5
JA
3022 if (ret == -ERESTARTSYS)
3023 ret = -EINTR;
0fa03c62
JA
3024 }
3025
1e95081c 3026 if (kmsg && kmsg->iov != kmsg->fast_iov)
0b416c3e 3027 kfree(kmsg->iov);
78e19bbe 3028 io_cqring_add_event(req, ret);
4e88d6e7
JA
3029 if (ret < 0)
3030 req_set_fail_links(req);
ec9c02ad 3031 io_put_req_find_next(req, nxt);
5d17b4a4 3032 return 0;
03b1230c
JA
3033#else
3034 return -EOPNOTSUPP;
aa1fa28f 3035#endif
03b1230c 3036}
aa1fa28f 3037
fddaface
JA
3038static int io_send(struct io_kiocb *req, struct io_kiocb **nxt,
3039 bool force_nonblock)
3040{
3041#if defined(CONFIG_NET)
3042 struct socket *sock;
3043 int ret;
3044
3045 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3046 return -EINVAL;
3047
3048 sock = sock_from_file(req->file, &ret);
3049 if (sock) {
3050 struct io_sr_msg *sr = &req->sr_msg;
3051 struct msghdr msg;
3052 struct iovec iov;
3053 unsigned flags;
3054
3055 ret = import_single_range(WRITE, sr->buf, sr->len, &iov,
3056 &msg.msg_iter);
3057 if (ret)
3058 return ret;
3059
3060 msg.msg_name = NULL;
3061 msg.msg_control = NULL;
3062 msg.msg_controllen = 0;
3063 msg.msg_namelen = 0;
3064
3065 flags = req->sr_msg.msg_flags;
3066 if (flags & MSG_DONTWAIT)
3067 req->flags |= REQ_F_NOWAIT;
3068 else if (force_nonblock)
3069 flags |= MSG_DONTWAIT;
3070
0b7b21e4
JA
3071 msg.msg_flags = flags;
3072 ret = sock_sendmsg(sock, &msg);
fddaface
JA
3073 if (force_nonblock && ret == -EAGAIN)
3074 return -EAGAIN;
3075 if (ret == -ERESTARTSYS)
3076 ret = -EINTR;
3077 }
3078
3079 io_cqring_add_event(req, ret);
3080 if (ret < 0)
3081 req_set_fail_links(req);
3082 io_put_req_find_next(req, nxt);
3083 return 0;
3084#else
3085 return -EOPNOTSUPP;
3086#endif
3087}
3088
3529d8c2
JA
3089static int io_recvmsg_prep(struct io_kiocb *req,
3090 const struct io_uring_sqe *sqe)
aa1fa28f
JA
3091{
3092#if defined(CONFIG_NET)
e47293fd 3093 struct io_sr_msg *sr = &req->sr_msg;
3529d8c2
JA
3094 struct io_async_ctx *io = req->io;
3095
3096 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3097 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
0b7b21e4 3098 sr->len = READ_ONCE(sqe->len);
06b76d44 3099
fddaface 3100 if (!io || req->opcode == IORING_OP_RECV)
06b76d44 3101 return 0;
03b1230c 3102
d9688565 3103 io->msg.iov = io->msg.fast_iov;
3529d8c2 3104 return recvmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
e47293fd 3105 &io->msg.uaddr, &io->msg.iov);
aa1fa28f 3106#else
e47293fd 3107 return -EOPNOTSUPP;
aa1fa28f
JA
3108#endif
3109}
3110
fc4df999
JA
3111static int io_recvmsg(struct io_kiocb *req, struct io_kiocb **nxt,
3112 bool force_nonblock)
aa1fa28f
JA
3113{
3114#if defined(CONFIG_NET)
0b416c3e 3115 struct io_async_msghdr *kmsg = NULL;
03b1230c
JA
3116 struct socket *sock;
3117 int ret;
3118
3119 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3120 return -EINVAL;
3121
3122 sock = sock_from_file(req->file, &ret);
3123 if (sock) {
b7bb4f7d 3124 struct io_async_ctx io;
03b1230c 3125 struct sockaddr_storage addr;
03b1230c
JA
3126 unsigned flags;
3127
03b1230c 3128 if (req->io) {
0b416c3e
JA
3129 kmsg = &req->io->msg;
3130 kmsg->msg.msg_name = &addr;
3131 /* if iov is set, it's allocated already */
3132 if (!kmsg->iov)
3133 kmsg->iov = kmsg->fast_iov;
3134 kmsg->msg.msg_iter.iov = kmsg->iov;
03b1230c 3135 } else {
3529d8c2
JA
3136 struct io_sr_msg *sr = &req->sr_msg;
3137
0b416c3e
JA
3138 kmsg = &io.msg;
3139 kmsg->msg.msg_name = &addr;
3529d8c2
JA
3140
3141 io.msg.iov = io.msg.fast_iov;
3142 ret = recvmsg_copy_msghdr(&io.msg.msg, sr->msg,
3143 sr->msg_flags, &io.msg.uaddr,
3144 &io.msg.iov);
03b1230c 3145 if (ret)
3529d8c2 3146 return ret;
03b1230c
JA
3147 }
3148
e47293fd
JA
3149 flags = req->sr_msg.msg_flags;
3150 if (flags & MSG_DONTWAIT)
3151 req->flags |= REQ_F_NOWAIT;
3152 else if (force_nonblock)
3153 flags |= MSG_DONTWAIT;
3154
3155 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.msg,
3156 kmsg->uaddr, flags);
03b1230c 3157 if (force_nonblock && ret == -EAGAIN) {
b7bb4f7d
JA
3158 if (req->io)
3159 return -EAGAIN;
1e95081c
PB
3160 if (io_alloc_async_ctx(req)) {
3161 if (kmsg && kmsg->iov != kmsg->fast_iov)
3162 kfree(kmsg->iov);
b7bb4f7d 3163 return -ENOMEM;
1e95081c 3164 }
b7bb4f7d 3165 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
0b416c3e 3166 return -EAGAIN;
03b1230c
JA
3167 }
3168 if (ret == -ERESTARTSYS)
3169 ret = -EINTR;
3170 }
3171
1e95081c 3172 if (kmsg && kmsg->iov != kmsg->fast_iov)
0b416c3e 3173 kfree(kmsg->iov);
03b1230c 3174 io_cqring_add_event(req, ret);
4e88d6e7
JA
3175 if (ret < 0)
3176 req_set_fail_links(req);
03b1230c
JA
3177 io_put_req_find_next(req, nxt);
3178 return 0;
0fa03c62
JA
3179#else
3180 return -EOPNOTSUPP;
3181#endif
3182}
5d17b4a4 3183
fddaface
JA
3184static int io_recv(struct io_kiocb *req, struct io_kiocb **nxt,
3185 bool force_nonblock)
3186{
3187#if defined(CONFIG_NET)
3188 struct socket *sock;
3189 int ret;
3190
3191 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3192 return -EINVAL;
3193
3194 sock = sock_from_file(req->file, &ret);
3195 if (sock) {
3196 struct io_sr_msg *sr = &req->sr_msg;
3197 struct msghdr msg;
3198 struct iovec iov;
3199 unsigned flags;
3200
3201 ret = import_single_range(READ, sr->buf, sr->len, &iov,
3202 &msg.msg_iter);
3203 if (ret)
3204 return ret;
3205
3206 msg.msg_name = NULL;
3207 msg.msg_control = NULL;
3208 msg.msg_controllen = 0;
3209 msg.msg_namelen = 0;
3210 msg.msg_iocb = NULL;
3211 msg.msg_flags = 0;
3212
3213 flags = req->sr_msg.msg_flags;
3214 if (flags & MSG_DONTWAIT)
3215 req->flags |= REQ_F_NOWAIT;
3216 else if (force_nonblock)
3217 flags |= MSG_DONTWAIT;
3218
0b7b21e4 3219 ret = sock_recvmsg(sock, &msg, flags);
fddaface
JA
3220 if (force_nonblock && ret == -EAGAIN)
3221 return -EAGAIN;
3222 if (ret == -ERESTARTSYS)
3223 ret = -EINTR;
3224 }
3225
3226 io_cqring_add_event(req, ret);
3227 if (ret < 0)
3228 req_set_fail_links(req);
3229 io_put_req_find_next(req, nxt);
3230 return 0;
3231#else
3232 return -EOPNOTSUPP;
3233#endif
3234}
3235
3236
3529d8c2 3237static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
17f2fe35
JA
3238{
3239#if defined(CONFIG_NET)
8ed8d3c3
JA
3240 struct io_accept *accept = &req->accept;
3241
17f2fe35
JA
3242 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3243 return -EINVAL;
8042d6ce 3244 if (sqe->ioprio || sqe->len || sqe->buf_index)
17f2fe35
JA
3245 return -EINVAL;
3246
d55e5f5b
JA
3247 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3248 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
8ed8d3c3 3249 accept->flags = READ_ONCE(sqe->accept_flags);
8ed8d3c3
JA
3250 return 0;
3251#else
3252 return -EOPNOTSUPP;
3253#endif
3254}
17f2fe35 3255
8ed8d3c3
JA
3256#if defined(CONFIG_NET)
3257static int __io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
3258 bool force_nonblock)
3259{
3260 struct io_accept *accept = &req->accept;
3261 unsigned file_flags;
3262 int ret;
3263
3264 file_flags = force_nonblock ? O_NONBLOCK : 0;
3265 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
3266 accept->addr_len, accept->flags);
3267 if (ret == -EAGAIN && force_nonblock)
17f2fe35 3268 return -EAGAIN;
8e3cca12
JA
3269 if (ret == -ERESTARTSYS)
3270 ret = -EINTR;
4e88d6e7
JA
3271 if (ret < 0)
3272 req_set_fail_links(req);
78e19bbe 3273 io_cqring_add_event(req, ret);
ec9c02ad 3274 io_put_req_find_next(req, nxt);
17f2fe35 3275 return 0;
8ed8d3c3
JA
3276}
3277
3278static void io_accept_finish(struct io_wq_work **workptr)
3279{
3280 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3281 struct io_kiocb *nxt = NULL;
3282
3283 if (io_req_cancelled(req))
3284 return;
3285 __io_accept(req, &nxt, false);
3286 if (nxt)
78912934 3287 io_wq_assign_next(workptr, nxt);
8ed8d3c3
JA
3288}
3289#endif
3290
3291static int io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
3292 bool force_nonblock)
3293{
3294#if defined(CONFIG_NET)
3295 int ret;
3296
8ed8d3c3
JA
3297 ret = __io_accept(req, nxt, force_nonblock);
3298 if (ret == -EAGAIN && force_nonblock) {
3299 req->work.func = io_accept_finish;
8ed8d3c3
JA
3300 io_put_req(req);
3301 return -EAGAIN;
3302 }
3303 return 0;
0fa03c62
JA
3304#else
3305 return -EOPNOTSUPP;
3306#endif
3307}
5d17b4a4 3308
3529d8c2 3309static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
f499a021
JA
3310{
3311#if defined(CONFIG_NET)
3529d8c2
JA
3312 struct io_connect *conn = &req->connect;
3313 struct io_async_ctx *io = req->io;
f499a021 3314
3fbb51c1
JA
3315 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3316 return -EINVAL;
3317 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
3318 return -EINVAL;
3319
3529d8c2
JA
3320 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3321 conn->addr_len = READ_ONCE(sqe->addr2);
3322
3323 if (!io)
3324 return 0;
3325
3326 return move_addr_to_kernel(conn->addr, conn->addr_len,
3fbb51c1 3327 &io->connect.address);
f499a021 3328#else
3fbb51c1 3329 return -EOPNOTSUPP;
f499a021
JA
3330#endif
3331}
3332
fc4df999
JA
3333static int io_connect(struct io_kiocb *req, struct io_kiocb **nxt,
3334 bool force_nonblock)
f8e85cf2
JA
3335{
3336#if defined(CONFIG_NET)
f499a021 3337 struct io_async_ctx __io, *io;
f8e85cf2 3338 unsigned file_flags;
3fbb51c1 3339 int ret;
f8e85cf2 3340
f499a021
JA
3341 if (req->io) {
3342 io = req->io;
3343 } else {
3529d8c2
JA
3344 ret = move_addr_to_kernel(req->connect.addr,
3345 req->connect.addr_len,
3346 &__io.connect.address);
f499a021
JA
3347 if (ret)
3348 goto out;
3349 io = &__io;
3350 }
3351
3fbb51c1
JA
3352 file_flags = force_nonblock ? O_NONBLOCK : 0;
3353
3354 ret = __sys_connect_file(req->file, &io->connect.address,
3355 req->connect.addr_len, file_flags);
87f80d62 3356 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
b7bb4f7d
JA
3357 if (req->io)
3358 return -EAGAIN;
3359 if (io_alloc_async_ctx(req)) {
f499a021
JA
3360 ret = -ENOMEM;
3361 goto out;
3362 }
b7bb4f7d 3363 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
f8e85cf2 3364 return -EAGAIN;
f499a021 3365 }
f8e85cf2
JA
3366 if (ret == -ERESTARTSYS)
3367 ret = -EINTR;
f499a021 3368out:
4e88d6e7
JA
3369 if (ret < 0)
3370 req_set_fail_links(req);
f8e85cf2
JA
3371 io_cqring_add_event(req, ret);
3372 io_put_req_find_next(req, nxt);
3373 return 0;
3374#else
3375 return -EOPNOTSUPP;
3376#endif
3377}
3378
221c5eb2
JA
3379static void io_poll_remove_one(struct io_kiocb *req)
3380{
3381 struct io_poll_iocb *poll = &req->poll;
3382
3383 spin_lock(&poll->head->lock);
3384 WRITE_ONCE(poll->canceled, true);
392edb45
JA
3385 if (!list_empty(&poll->wait.entry)) {
3386 list_del_init(&poll->wait.entry);
a197f664 3387 io_queue_async_work(req);
221c5eb2
JA
3388 }
3389 spin_unlock(&poll->head->lock);
78076bb6 3390 hash_del(&req->hash_node);
221c5eb2
JA
3391}
3392
3393static void io_poll_remove_all(struct io_ring_ctx *ctx)
3394{
78076bb6 3395 struct hlist_node *tmp;
221c5eb2 3396 struct io_kiocb *req;
78076bb6 3397 int i;
221c5eb2
JA
3398
3399 spin_lock_irq(&ctx->completion_lock);
78076bb6
JA
3400 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
3401 struct hlist_head *list;
3402
3403 list = &ctx->cancel_hash[i];
3404 hlist_for_each_entry_safe(req, tmp, list, hash_node)
3405 io_poll_remove_one(req);
221c5eb2
JA
3406 }
3407 spin_unlock_irq(&ctx->completion_lock);
3408}
3409
47f46768
JA
3410static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
3411{
78076bb6 3412 struct hlist_head *list;
47f46768
JA
3413 struct io_kiocb *req;
3414
78076bb6
JA
3415 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
3416 hlist_for_each_entry(req, list, hash_node) {
3417 if (sqe_addr == req->user_data) {
eac406c6
JA
3418 io_poll_remove_one(req);
3419 return 0;
3420 }
47f46768
JA
3421 }
3422
3423 return -ENOENT;
3424}
3425
3529d8c2
JA
3426static int io_poll_remove_prep(struct io_kiocb *req,
3427 const struct io_uring_sqe *sqe)
0969e783 3428{
0969e783
JA
3429 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3430 return -EINVAL;
3431 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3432 sqe->poll_events)
3433 return -EINVAL;
3434
3435 req->poll.addr = READ_ONCE(sqe->addr);
0969e783
JA
3436 return 0;
3437}
3438
221c5eb2
JA
3439/*
3440 * Find a running poll command that matches one specified in sqe->addr,
3441 * and remove it if found.
3442 */
fc4df999 3443static int io_poll_remove(struct io_kiocb *req)
221c5eb2
JA
3444{
3445 struct io_ring_ctx *ctx = req->ctx;
0969e783 3446 u64 addr;
47f46768 3447 int ret;
221c5eb2 3448
0969e783 3449 addr = req->poll.addr;
221c5eb2 3450 spin_lock_irq(&ctx->completion_lock);
0969e783 3451 ret = io_poll_cancel(ctx, addr);
221c5eb2
JA
3452 spin_unlock_irq(&ctx->completion_lock);
3453
78e19bbe 3454 io_cqring_add_event(req, ret);
4e88d6e7
JA
3455 if (ret < 0)
3456 req_set_fail_links(req);
e65ef56d 3457 io_put_req(req);
221c5eb2
JA
3458 return 0;
3459}
3460
b0dd8a41 3461static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
221c5eb2 3462{
a197f664
JL
3463 struct io_ring_ctx *ctx = req->ctx;
3464
8c838788 3465 req->poll.done = true;
b0dd8a41
JA
3466 if (error)
3467 io_cqring_fill_event(req, error);
3468 else
3469 io_cqring_fill_event(req, mangle_poll(mask));
8c838788 3470 io_commit_cqring(ctx);
221c5eb2
JA
3471}
3472
561fb04a 3473static void io_poll_complete_work(struct io_wq_work **workptr)
221c5eb2 3474{
561fb04a 3475 struct io_wq_work *work = *workptr;
221c5eb2
JA
3476 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3477 struct io_poll_iocb *poll = &req->poll;
3478 struct poll_table_struct pt = { ._key = poll->events };
3479 struct io_ring_ctx *ctx = req->ctx;
89723d0b 3480 struct io_kiocb *nxt = NULL;
221c5eb2 3481 __poll_t mask = 0;
b0dd8a41 3482 int ret = 0;
221c5eb2 3483
b0dd8a41 3484 if (work->flags & IO_WQ_WORK_CANCEL) {
561fb04a 3485 WRITE_ONCE(poll->canceled, true);
b0dd8a41
JA
3486 ret = -ECANCELED;
3487 } else if (READ_ONCE(poll->canceled)) {
3488 ret = -ECANCELED;
3489 }
561fb04a 3490
b0dd8a41 3491 if (ret != -ECANCELED)
221c5eb2
JA
3492 mask = vfs_poll(poll->file, &pt) & poll->events;
3493
3494 /*
3495 * Note that ->ki_cancel callers also delete iocb from active_reqs after
3496 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
3497 * synchronize with them. In the cancellation case the list_del_init
3498 * itself is not actually needed, but harmless so we keep it in to
3499 * avoid further branches in the fast path.
3500 */
3501 spin_lock_irq(&ctx->completion_lock);
b0dd8a41 3502 if (!mask && ret != -ECANCELED) {
392edb45 3503 add_wait_queue(poll->head, &poll->wait);
221c5eb2
JA
3504 spin_unlock_irq(&ctx->completion_lock);
3505 return;
3506 }
78076bb6 3507 hash_del(&req->hash_node);
b0dd8a41 3508 io_poll_complete(req, mask, ret);
221c5eb2
JA
3509 spin_unlock_irq(&ctx->completion_lock);
3510
8c838788 3511 io_cqring_ev_posted(ctx);
89723d0b 3512
4e88d6e7
JA
3513 if (ret < 0)
3514 req_set_fail_links(req);
ec9c02ad 3515 io_put_req_find_next(req, &nxt);
89723d0b 3516 if (nxt)
78912934 3517 io_wq_assign_next(workptr, nxt);
221c5eb2
JA
3518}
3519
e94f141b
JA
3520static void __io_poll_flush(struct io_ring_ctx *ctx, struct llist_node *nodes)
3521{
e94f141b 3522 struct io_kiocb *req, *tmp;
8237e045 3523 struct req_batch rb;
e94f141b 3524
c6ca97b3 3525 rb.to_free = rb.need_iter = 0;
e94f141b
JA
3526 spin_lock_irq(&ctx->completion_lock);
3527 llist_for_each_entry_safe(req, tmp, nodes, llist_node) {
3528 hash_del(&req->hash_node);
3529 io_poll_complete(req, req->result, 0);
3530
8237e045
JA
3531 if (refcount_dec_and_test(&req->refs) &&
3532 !io_req_multi_free(&rb, req)) {
3533 req->flags |= REQ_F_COMP_LOCKED;
3534 io_free_req(req);
e94f141b
JA
3535 }
3536 }
3537 spin_unlock_irq(&ctx->completion_lock);
3538
3539 io_cqring_ev_posted(ctx);
8237e045 3540 io_free_req_many(ctx, &rb);
e94f141b
JA
3541}
3542
3543static void io_poll_flush(struct io_wq_work **workptr)
3544{
3545 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3546 struct llist_node *nodes;
3547
3548 nodes = llist_del_all(&req->ctx->poll_llist);
3549 if (nodes)
3550 __io_poll_flush(req->ctx, nodes);
3551}
3552
f0b493e6
JA
3553static void io_poll_trigger_evfd(struct io_wq_work **workptr)
3554{
3555 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3556
3557 eventfd_signal(req->ctx->cq_ev_fd, 1);
3558 io_put_req(req);
3559}
3560
221c5eb2
JA
3561static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
3562 void *key)
3563{
e944475e 3564 struct io_poll_iocb *poll = wait->private;
221c5eb2
JA
3565 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
3566 struct io_ring_ctx *ctx = req->ctx;
3567 __poll_t mask = key_to_poll(key);
221c5eb2
JA
3568
3569 /* for instances that support it check for an event match first: */
8c838788
JA
3570 if (mask && !(mask & poll->events))
3571 return 0;
221c5eb2 3572
392edb45 3573 list_del_init(&poll->wait.entry);
221c5eb2 3574
7c9e7f0f
JA
3575 /*
3576 * Run completion inline if we can. We're using trylock here because
3577 * we are violating the completion_lock -> poll wq lock ordering.
3578 * If we have a link timeout we're going to need the completion_lock
3579 * for finalizing the request, mark us as having grabbed that already.
3580 */
e94f141b
JA
3581 if (mask) {
3582 unsigned long flags;
221c5eb2 3583
e94f141b
JA
3584 if (llist_empty(&ctx->poll_llist) &&
3585 spin_trylock_irqsave(&ctx->completion_lock, flags)) {
f0b493e6
JA
3586 bool trigger_ev;
3587
e94f141b
JA
3588 hash_del(&req->hash_node);
3589 io_poll_complete(req, mask, 0);
e94f141b 3590
f0b493e6
JA
3591 trigger_ev = io_should_trigger_evfd(ctx);
3592 if (trigger_ev && eventfd_signal_count()) {
3593 trigger_ev = false;
3594 req->work.func = io_poll_trigger_evfd;
3595 } else {
3596 req->flags |= REQ_F_COMP_LOCKED;
3597 io_put_req(req);
3598 req = NULL;
3599 }
3600 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3601 __io_cqring_ev_posted(ctx, trigger_ev);
e94f141b
JA
3602 } else {
3603 req->result = mask;
3604 req->llist_node.next = NULL;
3605 /* if the list wasn't empty, we're done */
3606 if (!llist_add(&req->llist_node, &ctx->poll_llist))
3607 req = NULL;
3608 else
3609 req->work.func = io_poll_flush;
3610 }
221c5eb2 3611 }
e94f141b
JA
3612 if (req)
3613 io_queue_async_work(req);
221c5eb2 3614
221c5eb2
JA
3615 return 1;
3616}
3617
3618struct io_poll_table {
3619 struct poll_table_struct pt;
3620 struct io_kiocb *req;
3621 int error;
3622};
3623
3624static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
3625 struct poll_table_struct *p)
3626{
3627 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
3628
3629 if (unlikely(pt->req->poll.head)) {
3630 pt->error = -EINVAL;
3631 return;
3632 }
3633
3634 pt->error = 0;
3635 pt->req->poll.head = head;
392edb45 3636 add_wait_queue(head, &pt->req->poll.wait);
221c5eb2
JA
3637}
3638
eac406c6
JA
3639static void io_poll_req_insert(struct io_kiocb *req)
3640{
3641 struct io_ring_ctx *ctx = req->ctx;
78076bb6
JA
3642 struct hlist_head *list;
3643
3644 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
3645 hlist_add_head(&req->hash_node, list);
eac406c6
JA
3646}
3647
3529d8c2 3648static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
221c5eb2
JA
3649{
3650 struct io_poll_iocb *poll = &req->poll;
221c5eb2 3651 u16 events;
221c5eb2
JA
3652
3653 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3654 return -EINVAL;
3655 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
3656 return -EINVAL;
09bb8394
JA
3657 if (!poll->file)
3658 return -EBADF;
221c5eb2 3659
221c5eb2
JA
3660 events = READ_ONCE(sqe->poll_events);
3661 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
0969e783
JA
3662 return 0;
3663}
3664
3665static int io_poll_add(struct io_kiocb *req, struct io_kiocb **nxt)
3666{
3667 struct io_poll_iocb *poll = &req->poll;
3668 struct io_ring_ctx *ctx = req->ctx;
3669 struct io_poll_table ipt;
3670 bool cancel = false;
3671 __poll_t mask;
0969e783
JA
3672
3673 INIT_IO_WORK(&req->work, io_poll_complete_work);
78076bb6 3674 INIT_HLIST_NODE(&req->hash_node);
221c5eb2 3675
221c5eb2 3676 poll->head = NULL;
8c838788 3677 poll->done = false;
221c5eb2
JA
3678 poll->canceled = false;
3679
3680 ipt.pt._qproc = io_poll_queue_proc;
3681 ipt.pt._key = poll->events;
3682 ipt.req = req;
3683 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
3684
3685 /* initialized the list so that we can do list_empty checks */
392edb45
JA
3686 INIT_LIST_HEAD(&poll->wait.entry);
3687 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
3688 poll->wait.private = poll;
221c5eb2 3689
36703247
JA
3690 INIT_LIST_HEAD(&req->list);
3691
221c5eb2 3692 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
221c5eb2
JA
3693
3694 spin_lock_irq(&ctx->completion_lock);
8c838788
JA
3695 if (likely(poll->head)) {
3696 spin_lock(&poll->head->lock);
392edb45 3697 if (unlikely(list_empty(&poll->wait.entry))) {
8c838788
JA
3698 if (ipt.error)
3699 cancel = true;
3700 ipt.error = 0;
3701 mask = 0;
3702 }
3703 if (mask || ipt.error)
392edb45 3704 list_del_init(&poll->wait.entry);
8c838788
JA
3705 else if (cancel)
3706 WRITE_ONCE(poll->canceled, true);
3707 else if (!poll->done) /* actually waiting for an event */
eac406c6 3708 io_poll_req_insert(req);
8c838788
JA
3709 spin_unlock(&poll->head->lock);
3710 }
3711 if (mask) { /* no async, we'd stolen it */
221c5eb2 3712 ipt.error = 0;
b0dd8a41 3713 io_poll_complete(req, mask, 0);
221c5eb2 3714 }
221c5eb2
JA
3715 spin_unlock_irq(&ctx->completion_lock);
3716
8c838788
JA
3717 if (mask) {
3718 io_cqring_ev_posted(ctx);
ec9c02ad 3719 io_put_req_find_next(req, nxt);
221c5eb2 3720 }
8c838788 3721 return ipt.error;
221c5eb2
JA
3722}
3723
5262f567
JA
3724static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
3725{
ad8a48ac
JA
3726 struct io_timeout_data *data = container_of(timer,
3727 struct io_timeout_data, timer);
3728 struct io_kiocb *req = data->req;
3729 struct io_ring_ctx *ctx = req->ctx;
5262f567
JA
3730 unsigned long flags;
3731
5262f567
JA
3732 atomic_inc(&ctx->cq_timeouts);
3733
3734 spin_lock_irqsave(&ctx->completion_lock, flags);
ef03681a 3735 /*
11365043
JA
3736 * We could be racing with timeout deletion. If the list is empty,
3737 * then timeout lookup already found it and will be handling it.
ef03681a 3738 */
842f9612 3739 if (!list_empty(&req->list)) {
11365043 3740 struct io_kiocb *prev;
5262f567 3741
11365043
JA
3742 /*
3743 * Adjust the reqs sequence before the current one because it
d195a66e 3744 * will consume a slot in the cq_ring and the cq_tail
11365043
JA
3745 * pointer will be increased, otherwise other timeout reqs may
3746 * return in advance without waiting for enough wait_nr.
3747 */
3748 prev = req;
3749 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
3750 prev->sequence++;
11365043 3751 list_del_init(&req->list);
11365043 3752 }
5262f567 3753
78e19bbe 3754 io_cqring_fill_event(req, -ETIME);
5262f567
JA
3755 io_commit_cqring(ctx);
3756 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3757
3758 io_cqring_ev_posted(ctx);
4e88d6e7 3759 req_set_fail_links(req);
5262f567
JA
3760 io_put_req(req);
3761 return HRTIMER_NORESTART;
3762}
3763
47f46768
JA
3764static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
3765{
3766 struct io_kiocb *req;
3767 int ret = -ENOENT;
3768
3769 list_for_each_entry(req, &ctx->timeout_list, list) {
3770 if (user_data == req->user_data) {
3771 list_del_init(&req->list);
3772 ret = 0;
3773 break;
3774 }
3775 }
3776
3777 if (ret == -ENOENT)
3778 return ret;
3779
2d28390a 3780 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
47f46768
JA
3781 if (ret == -1)
3782 return -EALREADY;
3783
4e88d6e7 3784 req_set_fail_links(req);
47f46768
JA
3785 io_cqring_fill_event(req, -ECANCELED);
3786 io_put_req(req);
3787 return 0;
3788}
3789
3529d8c2
JA
3790static int io_timeout_remove_prep(struct io_kiocb *req,
3791 const struct io_uring_sqe *sqe)
b29472ee 3792{
b29472ee
JA
3793 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3794 return -EINVAL;
3795 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
3796 return -EINVAL;
3797
3798 req->timeout.addr = READ_ONCE(sqe->addr);
3799 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
3800 if (req->timeout.flags)
3801 return -EINVAL;
3802
b29472ee
JA
3803 return 0;
3804}
3805
11365043
JA
3806/*
3807 * Remove or update an existing timeout command
3808 */
fc4df999 3809static int io_timeout_remove(struct io_kiocb *req)
11365043
JA
3810{
3811 struct io_ring_ctx *ctx = req->ctx;
47f46768 3812 int ret;
11365043 3813
11365043 3814 spin_lock_irq(&ctx->completion_lock);
b29472ee 3815 ret = io_timeout_cancel(ctx, req->timeout.addr);
11365043 3816
47f46768 3817 io_cqring_fill_event(req, ret);
11365043
JA
3818 io_commit_cqring(ctx);
3819 spin_unlock_irq(&ctx->completion_lock);
5262f567 3820 io_cqring_ev_posted(ctx);
4e88d6e7
JA
3821 if (ret < 0)
3822 req_set_fail_links(req);
ec9c02ad 3823 io_put_req(req);
11365043 3824 return 0;
5262f567
JA
3825}
3826
3529d8c2 3827static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2d28390a 3828 bool is_timeout_link)
5262f567 3829{
ad8a48ac 3830 struct io_timeout_data *data;
a41525ab 3831 unsigned flags;
5262f567 3832
ad8a48ac 3833 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5262f567 3834 return -EINVAL;
ad8a48ac 3835 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
a41525ab 3836 return -EINVAL;
2d28390a
JA
3837 if (sqe->off && is_timeout_link)
3838 return -EINVAL;
a41525ab
JA
3839 flags = READ_ONCE(sqe->timeout_flags);
3840 if (flags & ~IORING_TIMEOUT_ABS)
5262f567 3841 return -EINVAL;
bdf20073 3842
26a61679
JA
3843 req->timeout.count = READ_ONCE(sqe->off);
3844
3529d8c2 3845 if (!req->io && io_alloc_async_ctx(req))
26a61679
JA
3846 return -ENOMEM;
3847
3848 data = &req->io->timeout;
ad8a48ac 3849 data->req = req;
ad8a48ac
JA
3850 req->flags |= REQ_F_TIMEOUT;
3851
3852 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5262f567
JA
3853 return -EFAULT;
3854
11365043 3855 if (flags & IORING_TIMEOUT_ABS)
ad8a48ac 3856 data->mode = HRTIMER_MODE_ABS;
11365043 3857 else
ad8a48ac 3858 data->mode = HRTIMER_MODE_REL;
11365043 3859
ad8a48ac
JA
3860 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
3861 return 0;
3862}
3863
fc4df999 3864static int io_timeout(struct io_kiocb *req)
ad8a48ac
JA
3865{
3866 unsigned count;
3867 struct io_ring_ctx *ctx = req->ctx;
3868 struct io_timeout_data *data;
3869 struct list_head *entry;
3870 unsigned span = 0;
ad8a48ac 3871
2d28390a 3872 data = &req->io->timeout;
93bd25bb 3873
5262f567
JA
3874 /*
3875 * sqe->off holds how many events that need to occur for this
93bd25bb
JA
3876 * timeout event to be satisfied. If it isn't set, then this is
3877 * a pure timeout request, sequence isn't used.
5262f567 3878 */
26a61679 3879 count = req->timeout.count;
93bd25bb
JA
3880 if (!count) {
3881 req->flags |= REQ_F_TIMEOUT_NOSEQ;
3882 spin_lock_irq(&ctx->completion_lock);
3883 entry = ctx->timeout_list.prev;
3884 goto add;
3885 }
5262f567
JA
3886
3887 req->sequence = ctx->cached_sq_head + count - 1;
2d28390a 3888 data->seq_offset = count;
5262f567
JA
3889
3890 /*
3891 * Insertion sort, ensuring the first entry in the list is always
3892 * the one we need first.
3893 */
5262f567
JA
3894 spin_lock_irq(&ctx->completion_lock);
3895 list_for_each_prev(entry, &ctx->timeout_list) {
3896 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
5da0fb1a 3897 unsigned nxt_sq_head;
3898 long long tmp, tmp_nxt;
2d28390a 3899 u32 nxt_offset = nxt->io->timeout.seq_offset;
5262f567 3900
93bd25bb
JA
3901 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
3902 continue;
3903
5da0fb1a 3904 /*
3905 * Since cached_sq_head + count - 1 can overflow, use type long
3906 * long to store it.
3907 */
3908 tmp = (long long)ctx->cached_sq_head + count - 1;
cc42e0ac
PB
3909 nxt_sq_head = nxt->sequence - nxt_offset + 1;
3910 tmp_nxt = (long long)nxt_sq_head + nxt_offset - 1;
5da0fb1a 3911
3912 /*
3913 * cached_sq_head may overflow, and it will never overflow twice
3914 * once there is some timeout req still be valid.
3915 */
3916 if (ctx->cached_sq_head < nxt_sq_head)
8b07a65a 3917 tmp += UINT_MAX;
5da0fb1a 3918
a1f58ba4 3919 if (tmp > tmp_nxt)
5262f567 3920 break;
a1f58ba4 3921
3922 /*
3923 * Sequence of reqs after the insert one and itself should
3924 * be adjusted because each timeout req consumes a slot.
3925 */
3926 span++;
3927 nxt->sequence++;
5262f567 3928 }
a1f58ba4 3929 req->sequence -= span;
93bd25bb 3930add:
5262f567 3931 list_add(&req->list, entry);
ad8a48ac
JA
3932 data->timer.function = io_timeout_fn;
3933 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5262f567 3934 spin_unlock_irq(&ctx->completion_lock);
5262f567
JA
3935 return 0;
3936}
5262f567 3937
62755e35
JA
3938static bool io_cancel_cb(struct io_wq_work *work, void *data)
3939{
3940 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3941
3942 return req->user_data == (unsigned long) data;
3943}
3944
e977d6d3 3945static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
62755e35 3946{
62755e35 3947 enum io_wq_cancel cancel_ret;
62755e35
JA
3948 int ret = 0;
3949
62755e35
JA
3950 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
3951 switch (cancel_ret) {
3952 case IO_WQ_CANCEL_OK:
3953 ret = 0;
3954 break;
3955 case IO_WQ_CANCEL_RUNNING:
3956 ret = -EALREADY;
3957 break;
3958 case IO_WQ_CANCEL_NOTFOUND:
3959 ret = -ENOENT;
3960 break;
3961 }
3962
e977d6d3
JA
3963 return ret;
3964}
3965
47f46768
JA
3966static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
3967 struct io_kiocb *req, __u64 sqe_addr,
b0dd8a41 3968 struct io_kiocb **nxt, int success_ret)
47f46768
JA
3969{
3970 unsigned long flags;
3971 int ret;
3972
3973 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
3974 if (ret != -ENOENT) {
3975 spin_lock_irqsave(&ctx->completion_lock, flags);
3976 goto done;
3977 }
3978
3979 spin_lock_irqsave(&ctx->completion_lock, flags);
3980 ret = io_timeout_cancel(ctx, sqe_addr);
3981 if (ret != -ENOENT)
3982 goto done;
3983 ret = io_poll_cancel(ctx, sqe_addr);
3984done:
b0dd8a41
JA
3985 if (!ret)
3986 ret = success_ret;
47f46768
JA
3987 io_cqring_fill_event(req, ret);
3988 io_commit_cqring(ctx);
3989 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3990 io_cqring_ev_posted(ctx);
3991
4e88d6e7
JA
3992 if (ret < 0)
3993 req_set_fail_links(req);
47f46768
JA
3994 io_put_req_find_next(req, nxt);
3995}
3996
3529d8c2
JA
3997static int io_async_cancel_prep(struct io_kiocb *req,
3998 const struct io_uring_sqe *sqe)
e977d6d3 3999{
fbf23849 4000 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
e977d6d3
JA
4001 return -EINVAL;
4002 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
4003 sqe->cancel_flags)
4004 return -EINVAL;
4005
fbf23849
JA
4006 req->cancel.addr = READ_ONCE(sqe->addr);
4007 return 0;
4008}
4009
4010static int io_async_cancel(struct io_kiocb *req, struct io_kiocb **nxt)
4011{
4012 struct io_ring_ctx *ctx = req->ctx;
fbf23849
JA
4013
4014 io_async_find_and_cancel(ctx, req, req->cancel.addr, nxt, 0);
5262f567
JA
4015 return 0;
4016}
4017
05f3fb3c
JA
4018static int io_files_update_prep(struct io_kiocb *req,
4019 const struct io_uring_sqe *sqe)
4020{
4021 if (sqe->flags || sqe->ioprio || sqe->rw_flags)
4022 return -EINVAL;
4023
4024 req->files_update.offset = READ_ONCE(sqe->off);
4025 req->files_update.nr_args = READ_ONCE(sqe->len);
4026 if (!req->files_update.nr_args)
4027 return -EINVAL;
4028 req->files_update.arg = READ_ONCE(sqe->addr);
4029 return 0;
4030}
4031
4032static int io_files_update(struct io_kiocb *req, bool force_nonblock)
fbf23849
JA
4033{
4034 struct io_ring_ctx *ctx = req->ctx;
05f3fb3c
JA
4035 struct io_uring_files_update up;
4036 int ret;
fbf23849 4037
f86cd20c 4038 if (force_nonblock)
05f3fb3c 4039 return -EAGAIN;
05f3fb3c
JA
4040
4041 up.offset = req->files_update.offset;
4042 up.fds = req->files_update.arg;
4043
4044 mutex_lock(&ctx->uring_lock);
4045 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
4046 mutex_unlock(&ctx->uring_lock);
4047
4048 if (ret < 0)
4049 req_set_fail_links(req);
4050 io_cqring_add_event(req, ret);
4051 io_put_req(req);
5262f567
JA
4052 return 0;
4053}
4054
3529d8c2
JA
4055static int io_req_defer_prep(struct io_kiocb *req,
4056 const struct io_uring_sqe *sqe)
f67676d1 4057{
e781573e 4058 ssize_t ret = 0;
f67676d1 4059
f86cd20c
JA
4060 if (io_op_defs[req->opcode].file_table) {
4061 ret = io_grab_files(req);
4062 if (unlikely(ret))
4063 return ret;
4064 }
4065
cccf0ee8
JA
4066 io_req_work_grab_env(req, &io_op_defs[req->opcode]);
4067
d625c6ee 4068 switch (req->opcode) {
e781573e
JA
4069 case IORING_OP_NOP:
4070 break;
f67676d1
JA
4071 case IORING_OP_READV:
4072 case IORING_OP_READ_FIXED:
3a6820f2 4073 case IORING_OP_READ:
3529d8c2 4074 ret = io_read_prep(req, sqe, true);
f67676d1
JA
4075 break;
4076 case IORING_OP_WRITEV:
4077 case IORING_OP_WRITE_FIXED:
3a6820f2 4078 case IORING_OP_WRITE:
3529d8c2 4079 ret = io_write_prep(req, sqe, true);
f67676d1 4080 break;
0969e783 4081 case IORING_OP_POLL_ADD:
3529d8c2 4082 ret = io_poll_add_prep(req, sqe);
0969e783
JA
4083 break;
4084 case IORING_OP_POLL_REMOVE:
3529d8c2 4085 ret = io_poll_remove_prep(req, sqe);
0969e783 4086 break;
8ed8d3c3 4087 case IORING_OP_FSYNC:
3529d8c2 4088 ret = io_prep_fsync(req, sqe);
8ed8d3c3
JA
4089 break;
4090 case IORING_OP_SYNC_FILE_RANGE:
3529d8c2 4091 ret = io_prep_sfr(req, sqe);
8ed8d3c3 4092 break;
03b1230c 4093 case IORING_OP_SENDMSG:
fddaface 4094 case IORING_OP_SEND:
3529d8c2 4095 ret = io_sendmsg_prep(req, sqe);
03b1230c
JA
4096 break;
4097 case IORING_OP_RECVMSG:
fddaface 4098 case IORING_OP_RECV:
3529d8c2 4099 ret = io_recvmsg_prep(req, sqe);
03b1230c 4100 break;
f499a021 4101 case IORING_OP_CONNECT:
3529d8c2 4102 ret = io_connect_prep(req, sqe);
f499a021 4103 break;
2d28390a 4104 case IORING_OP_TIMEOUT:
3529d8c2 4105 ret = io_timeout_prep(req, sqe, false);
b7bb4f7d 4106 break;
b29472ee 4107 case IORING_OP_TIMEOUT_REMOVE:
3529d8c2 4108 ret = io_timeout_remove_prep(req, sqe);
b29472ee 4109 break;
fbf23849 4110 case IORING_OP_ASYNC_CANCEL:
3529d8c2 4111 ret = io_async_cancel_prep(req, sqe);
fbf23849 4112 break;
2d28390a 4113 case IORING_OP_LINK_TIMEOUT:
3529d8c2 4114 ret = io_timeout_prep(req, sqe, true);
b7bb4f7d 4115 break;
8ed8d3c3 4116 case IORING_OP_ACCEPT:
3529d8c2 4117 ret = io_accept_prep(req, sqe);
8ed8d3c3 4118 break;
d63d1b5e
JA
4119 case IORING_OP_FALLOCATE:
4120 ret = io_fallocate_prep(req, sqe);
4121 break;
15b71abe
JA
4122 case IORING_OP_OPENAT:
4123 ret = io_openat_prep(req, sqe);
4124 break;
b5dba59e
JA
4125 case IORING_OP_CLOSE:
4126 ret = io_close_prep(req, sqe);
4127 break;
05f3fb3c
JA
4128 case IORING_OP_FILES_UPDATE:
4129 ret = io_files_update_prep(req, sqe);
4130 break;
eddc7ef5
JA
4131 case IORING_OP_STATX:
4132 ret = io_statx_prep(req, sqe);
4133 break;
4840e418
JA
4134 case IORING_OP_FADVISE:
4135 ret = io_fadvise_prep(req, sqe);
4136 break;
c1ca757b
JA
4137 case IORING_OP_MADVISE:
4138 ret = io_madvise_prep(req, sqe);
4139 break;
cebdb986
JA
4140 case IORING_OP_OPENAT2:
4141 ret = io_openat2_prep(req, sqe);
4142 break;
3e4827b0
JA
4143 case IORING_OP_EPOLL_CTL:
4144 ret = io_epoll_ctl_prep(req, sqe);
4145 break;
f67676d1 4146 default:
e781573e
JA
4147 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
4148 req->opcode);
4149 ret = -EINVAL;
b7bb4f7d 4150 break;
f67676d1
JA
4151 }
4152
b7bb4f7d 4153 return ret;
f67676d1
JA
4154}
4155
3529d8c2 4156static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
de0617e4 4157{
a197f664 4158 struct io_ring_ctx *ctx = req->ctx;
f67676d1 4159 int ret;
de0617e4 4160
9d858b21
BL
4161 /* Still need defer if there is pending req in defer list. */
4162 if (!req_need_defer(req) && list_empty(&ctx->defer_list))
de0617e4
JA
4163 return 0;
4164
3529d8c2 4165 if (!req->io && io_alloc_async_ctx(req))
de0617e4
JA
4166 return -EAGAIN;
4167
3529d8c2 4168 ret = io_req_defer_prep(req, sqe);
b7bb4f7d 4169 if (ret < 0)
2d28390a 4170 return ret;
2d28390a 4171
de0617e4 4172 spin_lock_irq(&ctx->completion_lock);
9d858b21 4173 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
de0617e4 4174 spin_unlock_irq(&ctx->completion_lock);
de0617e4
JA
4175 return 0;
4176 }
4177
915967f6 4178 trace_io_uring_defer(ctx, req, req->user_data);
de0617e4
JA
4179 list_add_tail(&req->list, &ctx->defer_list);
4180 spin_unlock_irq(&ctx->completion_lock);
4181 return -EIOCBQUEUED;
4182}
4183
3529d8c2
JA
4184static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4185 struct io_kiocb **nxt, bool force_nonblock)
2b188cc1 4186{
a197f664 4187 struct io_ring_ctx *ctx = req->ctx;
d625c6ee 4188 int ret;
2b188cc1 4189
d625c6ee 4190 switch (req->opcode) {
2b188cc1 4191 case IORING_OP_NOP:
78e19bbe 4192 ret = io_nop(req);
2b188cc1
JA
4193 break;
4194 case IORING_OP_READV:
edafccee 4195 case IORING_OP_READ_FIXED:
3a6820f2 4196 case IORING_OP_READ:
3529d8c2
JA
4197 if (sqe) {
4198 ret = io_read_prep(req, sqe, force_nonblock);
4199 if (ret < 0)
4200 break;
4201 }
267bc904 4202 ret = io_read(req, nxt, force_nonblock);
edafccee 4203 break;
3529d8c2 4204 case IORING_OP_WRITEV:
edafccee 4205 case IORING_OP_WRITE_FIXED:
3a6820f2 4206 case IORING_OP_WRITE:
3529d8c2
JA
4207 if (sqe) {
4208 ret = io_write_prep(req, sqe, force_nonblock);
4209 if (ret < 0)
4210 break;
4211 }
267bc904 4212 ret = io_write(req, nxt, force_nonblock);
2b188cc1 4213 break;
c992fe29 4214 case IORING_OP_FSYNC:
3529d8c2
JA
4215 if (sqe) {
4216 ret = io_prep_fsync(req, sqe);
4217 if (ret < 0)
4218 break;
4219 }
fc4df999 4220 ret = io_fsync(req, nxt, force_nonblock);
c992fe29 4221 break;
221c5eb2 4222 case IORING_OP_POLL_ADD:
3529d8c2
JA
4223 if (sqe) {
4224 ret = io_poll_add_prep(req, sqe);
4225 if (ret)
4226 break;
4227 }
fc4df999 4228 ret = io_poll_add(req, nxt);
221c5eb2
JA
4229 break;
4230 case IORING_OP_POLL_REMOVE:
3529d8c2
JA
4231 if (sqe) {
4232 ret = io_poll_remove_prep(req, sqe);
4233 if (ret < 0)
4234 break;
4235 }
fc4df999 4236 ret = io_poll_remove(req);
221c5eb2 4237 break;
5d17b4a4 4238 case IORING_OP_SYNC_FILE_RANGE:
3529d8c2
JA
4239 if (sqe) {
4240 ret = io_prep_sfr(req, sqe);
4241 if (ret < 0)
4242 break;
4243 }
fc4df999 4244 ret = io_sync_file_range(req, nxt, force_nonblock);
5d17b4a4 4245 break;
0fa03c62 4246 case IORING_OP_SENDMSG:
fddaface 4247 case IORING_OP_SEND:
3529d8c2
JA
4248 if (sqe) {
4249 ret = io_sendmsg_prep(req, sqe);
4250 if (ret < 0)
4251 break;
4252 }
fddaface
JA
4253 if (req->opcode == IORING_OP_SENDMSG)
4254 ret = io_sendmsg(req, nxt, force_nonblock);
4255 else
4256 ret = io_send(req, nxt, force_nonblock);
0fa03c62 4257 break;
aa1fa28f 4258 case IORING_OP_RECVMSG:
fddaface 4259 case IORING_OP_RECV:
3529d8c2
JA
4260 if (sqe) {
4261 ret = io_recvmsg_prep(req, sqe);
4262 if (ret)
4263 break;
4264 }
fddaface
JA
4265 if (req->opcode == IORING_OP_RECVMSG)
4266 ret = io_recvmsg(req, nxt, force_nonblock);
4267 else
4268 ret = io_recv(req, nxt, force_nonblock);
aa1fa28f 4269 break;
5262f567 4270 case IORING_OP_TIMEOUT:
3529d8c2
JA
4271 if (sqe) {
4272 ret = io_timeout_prep(req, sqe, false);
4273 if (ret)
4274 break;
4275 }
fc4df999 4276 ret = io_timeout(req);
5262f567 4277 break;
11365043 4278 case IORING_OP_TIMEOUT_REMOVE:
3529d8c2
JA
4279 if (sqe) {
4280 ret = io_timeout_remove_prep(req, sqe);
4281 if (ret)
4282 break;
4283 }
fc4df999 4284 ret = io_timeout_remove(req);
11365043 4285 break;
17f2fe35 4286 case IORING_OP_ACCEPT:
3529d8c2
JA
4287 if (sqe) {
4288 ret = io_accept_prep(req, sqe);
4289 if (ret)
4290 break;
4291 }
fc4df999 4292 ret = io_accept(req, nxt, force_nonblock);
17f2fe35 4293 break;
f8e85cf2 4294 case IORING_OP_CONNECT:
3529d8c2
JA
4295 if (sqe) {
4296 ret = io_connect_prep(req, sqe);
4297 if (ret)
4298 break;
4299 }
fc4df999 4300 ret = io_connect(req, nxt, force_nonblock);
f8e85cf2 4301 break;
62755e35 4302 case IORING_OP_ASYNC_CANCEL:
3529d8c2
JA
4303 if (sqe) {
4304 ret = io_async_cancel_prep(req, sqe);
4305 if (ret)
4306 break;
4307 }
fc4df999 4308 ret = io_async_cancel(req, nxt);
62755e35 4309 break;
d63d1b5e
JA
4310 case IORING_OP_FALLOCATE:
4311 if (sqe) {
4312 ret = io_fallocate_prep(req, sqe);
4313 if (ret)
4314 break;
4315 }
4316 ret = io_fallocate(req, nxt, force_nonblock);
4317 break;
15b71abe
JA
4318 case IORING_OP_OPENAT:
4319 if (sqe) {
4320 ret = io_openat_prep(req, sqe);
4321 if (ret)
4322 break;
4323 }
4324 ret = io_openat(req, nxt, force_nonblock);
4325 break;
b5dba59e
JA
4326 case IORING_OP_CLOSE:
4327 if (sqe) {
4328 ret = io_close_prep(req, sqe);
4329 if (ret)
4330 break;
4331 }
4332 ret = io_close(req, nxt, force_nonblock);
4333 break;
05f3fb3c
JA
4334 case IORING_OP_FILES_UPDATE:
4335 if (sqe) {
4336 ret = io_files_update_prep(req, sqe);
4337 if (ret)
4338 break;
4339 }
4340 ret = io_files_update(req, force_nonblock);
4341 break;
eddc7ef5
JA
4342 case IORING_OP_STATX:
4343 if (sqe) {
4344 ret = io_statx_prep(req, sqe);
4345 if (ret)
4346 break;
4347 }
4348 ret = io_statx(req, nxt, force_nonblock);
4349 break;
4840e418
JA
4350 case IORING_OP_FADVISE:
4351 if (sqe) {
4352 ret = io_fadvise_prep(req, sqe);
4353 if (ret)
4354 break;
4355 }
4356 ret = io_fadvise(req, nxt, force_nonblock);
4357 break;
c1ca757b
JA
4358 case IORING_OP_MADVISE:
4359 if (sqe) {
4360 ret = io_madvise_prep(req, sqe);
4361 if (ret)
4362 break;
4363 }
4364 ret = io_madvise(req, nxt, force_nonblock);
4365 break;
cebdb986
JA
4366 case IORING_OP_OPENAT2:
4367 if (sqe) {
4368 ret = io_openat2_prep(req, sqe);
4369 if (ret)
4370 break;
4371 }
4372 ret = io_openat2(req, nxt, force_nonblock);
4373 break;
3e4827b0
JA
4374 case IORING_OP_EPOLL_CTL:
4375 if (sqe) {
4376 ret = io_epoll_ctl_prep(req, sqe);
4377 if (ret)
4378 break;
4379 }
4380 ret = io_epoll_ctl(req, nxt, force_nonblock);
4381 break;
2b188cc1
JA
4382 default:
4383 ret = -EINVAL;
4384 break;
4385 }
4386
def596e9
JA
4387 if (ret)
4388 return ret;
4389
4390 if (ctx->flags & IORING_SETUP_IOPOLL) {
11ba820b
JA
4391 const bool in_async = io_wq_current_is_worker();
4392
9e645e11 4393 if (req->result == -EAGAIN)
def596e9
JA
4394 return -EAGAIN;
4395
11ba820b
JA
4396 /* workqueue context doesn't hold uring_lock, grab it now */
4397 if (in_async)
4398 mutex_lock(&ctx->uring_lock);
4399
def596e9 4400 io_iopoll_req_issued(req);
11ba820b
JA
4401
4402 if (in_async)
4403 mutex_unlock(&ctx->uring_lock);
def596e9
JA
4404 }
4405
4406 return 0;
2b188cc1
JA
4407}
4408
561fb04a 4409static void io_wq_submit_work(struct io_wq_work **workptr)
2b188cc1 4410{
561fb04a 4411 struct io_wq_work *work = *workptr;
2b188cc1 4412 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
561fb04a
JA
4413 struct io_kiocb *nxt = NULL;
4414 int ret = 0;
2b188cc1 4415
0c9d5ccd
JA
4416 /* if NO_CANCEL is set, we must still run the work */
4417 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
4418 IO_WQ_WORK_CANCEL) {
561fb04a 4419 ret = -ECANCELED;
0c9d5ccd 4420 }
31b51510 4421
561fb04a 4422 if (!ret) {
cf6fd4bd 4423 req->in_async = true;
561fb04a 4424 do {
3529d8c2 4425 ret = io_issue_sqe(req, NULL, &nxt, false);
561fb04a
JA
4426 /*
4427 * We can get EAGAIN for polled IO even though we're
4428 * forcing a sync submission from here, since we can't
4429 * wait for request slots on the block side.
4430 */
4431 if (ret != -EAGAIN)
4432 break;
4433 cond_resched();
4434 } while (1);
4435 }
31b51510 4436
561fb04a 4437 /* drop submission reference */
ec9c02ad 4438 io_put_req(req);
817869d2 4439
561fb04a 4440 if (ret) {
4e88d6e7 4441 req_set_fail_links(req);
78e19bbe 4442 io_cqring_add_event(req, ret);
817869d2 4443 io_put_req(req);
edafccee 4444 }
2b188cc1 4445
561fb04a 4446 /* if a dependent link is ready, pass it back */
78912934
JA
4447 if (!ret && nxt)
4448 io_wq_assign_next(workptr, nxt);
2b188cc1
JA
4449}
4450
15b71abe 4451static int io_req_needs_file(struct io_kiocb *req, int fd)
9e3aa61a 4452{
d3656344 4453 if (!io_op_defs[req->opcode].needs_file)
9e3aa61a 4454 return 0;
d3656344
JA
4455 if (fd == -1 && io_op_defs[req->opcode].fd_non_neg)
4456 return 0;
4457 return 1;
09bb8394
JA
4458}
4459
65e19f54
JA
4460static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
4461 int index)
4462{
4463 struct fixed_file_table *table;
4464
05f3fb3c
JA
4465 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
4466 return table->files[index & IORING_FILE_TABLE_MASK];;
65e19f54
JA
4467}
4468
3529d8c2
JA
4469static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
4470 const struct io_uring_sqe *sqe)
09bb8394 4471{
a197f664 4472 struct io_ring_ctx *ctx = req->ctx;
09bb8394 4473 unsigned flags;
d3656344 4474 int fd;
09bb8394 4475
3529d8c2
JA
4476 flags = READ_ONCE(sqe->flags);
4477 fd = READ_ONCE(sqe->fd);
09bb8394 4478
d3656344
JA
4479 if (!io_req_needs_file(req, fd))
4480 return 0;
09bb8394
JA
4481
4482 if (flags & IOSQE_FIXED_FILE) {
05f3fb3c 4483 if (unlikely(!ctx->file_data ||
09bb8394
JA
4484 (unsigned) fd >= ctx->nr_user_files))
4485 return -EBADF;
b7620121 4486 fd = array_index_nospec(fd, ctx->nr_user_files);
65e19f54
JA
4487 req->file = io_file_from_index(ctx, fd);
4488 if (!req->file)
08a45173 4489 return -EBADF;
09bb8394 4490 req->flags |= REQ_F_FIXED_FILE;
05f3fb3c 4491 percpu_ref_get(&ctx->file_data->refs);
09bb8394 4492 } else {
cf6fd4bd 4493 if (req->needs_fixed_file)
09bb8394 4494 return -EBADF;
c826bd7a 4495 trace_io_uring_file_get(ctx, fd);
09bb8394
JA
4496 req->file = io_file_get(state, fd);
4497 if (unlikely(!req->file))
4498 return -EBADF;
4499 }
4500
4501 return 0;
4502}
4503
a197f664 4504static int io_grab_files(struct io_kiocb *req)
fcb323cc
JA
4505{
4506 int ret = -EBADF;
a197f664 4507 struct io_ring_ctx *ctx = req->ctx;
fcb323cc 4508
f86cd20c
JA
4509 if (req->work.files)
4510 return 0;
b14cca0c 4511 if (!ctx->ring_file)
b5dba59e
JA
4512 return -EBADF;
4513
fcb323cc
JA
4514 rcu_read_lock();
4515 spin_lock_irq(&ctx->inflight_lock);
4516 /*
4517 * We use the f_ops->flush() handler to ensure that we can flush
4518 * out work accessing these files if the fd is closed. Check if
4519 * the fd has changed since we started down this path, and disallow
4520 * this operation if it has.
4521 */
b14cca0c 4522 if (fcheck(ctx->ring_fd) == ctx->ring_file) {
fcb323cc
JA
4523 list_add(&req->inflight_entry, &ctx->inflight_list);
4524 req->flags |= REQ_F_INFLIGHT;
4525 req->work.files = current->files;
4526 ret = 0;
4527 }
4528 spin_unlock_irq(&ctx->inflight_lock);
4529 rcu_read_unlock();
4530
4531 return ret;
4532}
4533
2665abfd 4534static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
2b188cc1 4535{
ad8a48ac
JA
4536 struct io_timeout_data *data = container_of(timer,
4537 struct io_timeout_data, timer);
4538 struct io_kiocb *req = data->req;
2665abfd
JA
4539 struct io_ring_ctx *ctx = req->ctx;
4540 struct io_kiocb *prev = NULL;
4541 unsigned long flags;
2665abfd
JA
4542
4543 spin_lock_irqsave(&ctx->completion_lock, flags);
4544
4545 /*
4546 * We don't expect the list to be empty, that will only happen if we
4547 * race with the completion of the linked work.
4548 */
4493233e
PB
4549 if (!list_empty(&req->link_list)) {
4550 prev = list_entry(req->link_list.prev, struct io_kiocb,
4551 link_list);
5d960724 4552 if (refcount_inc_not_zero(&prev->refs)) {
4493233e 4553 list_del_init(&req->link_list);
5d960724
JA
4554 prev->flags &= ~REQ_F_LINK_TIMEOUT;
4555 } else
76a46e06 4556 prev = NULL;
2665abfd
JA
4557 }
4558
4559 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4560
4561 if (prev) {
4e88d6e7 4562 req_set_fail_links(prev);
b0dd8a41
JA
4563 io_async_find_and_cancel(ctx, req, prev->user_data, NULL,
4564 -ETIME);
76a46e06 4565 io_put_req(prev);
47f46768
JA
4566 } else {
4567 io_cqring_add_event(req, -ETIME);
4568 io_put_req(req);
2665abfd 4569 }
2665abfd
JA
4570 return HRTIMER_NORESTART;
4571}
4572
ad8a48ac 4573static void io_queue_linked_timeout(struct io_kiocb *req)
2665abfd 4574{
76a46e06 4575 struct io_ring_ctx *ctx = req->ctx;
2665abfd 4576
76a46e06
JA
4577 /*
4578 * If the list is now empty, then our linked request finished before
4579 * we got a chance to setup the timer
4580 */
4581 spin_lock_irq(&ctx->completion_lock);
4493233e 4582 if (!list_empty(&req->link_list)) {
2d28390a 4583 struct io_timeout_data *data = &req->io->timeout;
94ae5e77 4584
ad8a48ac
JA
4585 data->timer.function = io_link_timeout_fn;
4586 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
4587 data->mode);
2665abfd 4588 }
76a46e06 4589 spin_unlock_irq(&ctx->completion_lock);
2665abfd 4590
2665abfd 4591 /* drop submission reference */
76a46e06
JA
4592 io_put_req(req);
4593}
2665abfd 4594
ad8a48ac 4595static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
2665abfd
JA
4596{
4597 struct io_kiocb *nxt;
4598
4599 if (!(req->flags & REQ_F_LINK))
4600 return NULL;
4601
4493233e
PB
4602 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
4603 link_list);
d625c6ee 4604 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
76a46e06 4605 return NULL;
2665abfd 4606
76a46e06 4607 req->flags |= REQ_F_LINK_TIMEOUT;
76a46e06 4608 return nxt;
2665abfd
JA
4609}
4610
3529d8c2 4611static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2b188cc1 4612{
4a0a7a18 4613 struct io_kiocb *linked_timeout;
f9bd67f6 4614 struct io_kiocb *nxt = NULL;
e0c5c576 4615 int ret;
2b188cc1 4616
4a0a7a18
JA
4617again:
4618 linked_timeout = io_prep_linked_timeout(req);
4619
3529d8c2 4620 ret = io_issue_sqe(req, sqe, &nxt, true);
491381ce
JA
4621
4622 /*
4623 * We async punt it if the file wasn't marked NOWAIT, or if the file
4624 * doesn't support non-blocking read/write attempts
4625 */
4626 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
4627 (req->flags & REQ_F_MUST_PUNT))) {
86a761f8 4628punt:
f86cd20c 4629 if (io_op_defs[req->opcode].file_table) {
bbad27b2
PB
4630 ret = io_grab_files(req);
4631 if (ret)
4632 goto err;
2b188cc1 4633 }
bbad27b2
PB
4634
4635 /*
4636 * Queued up for async execution, worker will release
4637 * submit reference when the iocb is actually submitted.
4638 */
4639 io_queue_async_work(req);
4a0a7a18 4640 goto done_req;
2b188cc1 4641 }
e65ef56d 4642
fcb323cc 4643err:
76a46e06 4644 /* drop submission reference */
ec9c02ad 4645 io_put_req(req);
e65ef56d 4646
f9bd67f6 4647 if (linked_timeout) {
76a46e06 4648 if (!ret)
f9bd67f6 4649 io_queue_linked_timeout(linked_timeout);
76a46e06 4650 else
f9bd67f6 4651 io_put_req(linked_timeout);
76a46e06
JA
4652 }
4653
e65ef56d 4654 /* and drop final reference, if we failed */
9e645e11 4655 if (ret) {
78e19bbe 4656 io_cqring_add_event(req, ret);
4e88d6e7 4657 req_set_fail_links(req);
e65ef56d 4658 io_put_req(req);
9e645e11 4659 }
4a0a7a18
JA
4660done_req:
4661 if (nxt) {
4662 req = nxt;
4663 nxt = NULL;
86a761f8
PB
4664
4665 if (req->flags & REQ_F_FORCE_ASYNC)
4666 goto punt;
4a0a7a18
JA
4667 goto again;
4668 }
2b188cc1
JA
4669}
4670
3529d8c2 4671static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4fe2c963
JL
4672{
4673 int ret;
4674
3529d8c2 4675 ret = io_req_defer(req, sqe);
4fe2c963
JL
4676 if (ret) {
4677 if (ret != -EIOCBQUEUED) {
1118591a 4678fail_req:
78e19bbe 4679 io_cqring_add_event(req, ret);
4e88d6e7 4680 req_set_fail_links(req);
78e19bbe 4681 io_double_put_req(req);
4fe2c963 4682 }
2550878f 4683 } else if (req->flags & REQ_F_FORCE_ASYNC) {
1118591a
PB
4684 ret = io_req_defer_prep(req, sqe);
4685 if (unlikely(ret < 0))
4686 goto fail_req;
ce35a47a
JA
4687 /*
4688 * Never try inline submit of IOSQE_ASYNC is set, go straight
4689 * to async execution.
4690 */
4691 req->work.flags |= IO_WQ_WORK_CONCURRENT;
4692 io_queue_async_work(req);
4693 } else {
3529d8c2 4694 __io_queue_sqe(req, sqe);
ce35a47a 4695 }
4fe2c963
JL
4696}
4697
1b4a51b6 4698static inline void io_queue_link_head(struct io_kiocb *req)
4fe2c963 4699{
94ae5e77 4700 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
1b4a51b6
PB
4701 io_cqring_add_event(req, -ECANCELED);
4702 io_double_put_req(req);
4703 } else
3529d8c2 4704 io_queue_sqe(req, NULL);
4fe2c963
JL
4705}
4706
4e88d6e7 4707#define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
ce35a47a 4708 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
9e645e11 4709
3529d8c2
JA
4710static bool io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4711 struct io_submit_state *state, struct io_kiocb **link)
9e645e11 4712{
75c6a039 4713 const struct cred *old_creds = NULL;
a197f664 4714 struct io_ring_ctx *ctx = req->ctx;
32fe525b 4715 unsigned int sqe_flags;
75c6a039 4716 int ret, id;
9e645e11 4717
32fe525b 4718 sqe_flags = READ_ONCE(sqe->flags);
9e645e11
JA
4719
4720 /* enforce forwards compatibility on users */
32fe525b 4721 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
9e645e11 4722 ret = -EINVAL;
196be95c 4723 goto err_req;
9e645e11
JA
4724 }
4725
75c6a039
JA
4726 id = READ_ONCE(sqe->personality);
4727 if (id) {
4728 const struct cred *personality_creds;
4729
4730 personality_creds = idr_find(&ctx->personality_idr, id);
4731 if (unlikely(!personality_creds)) {
4732 ret = -EINVAL;
4733 goto err_req;
4734 }
4735 old_creds = override_creds(personality_creds);
4736 }
4737
6b47ee6e
PB
4738 /* same numerical values with corresponding REQ_F_*, safe to copy */
4739 req->flags |= sqe_flags & (IOSQE_IO_DRAIN|IOSQE_IO_HARDLINK|
4740 IOSQE_ASYNC);
9e645e11 4741
3529d8c2 4742 ret = io_req_set_file(state, req, sqe);
9e645e11
JA
4743 if (unlikely(ret)) {
4744err_req:
78e19bbe
JA
4745 io_cqring_add_event(req, ret);
4746 io_double_put_req(req);
75c6a039
JA
4747 if (old_creds)
4748 revert_creds(old_creds);
2e6e1fde 4749 return false;
9e645e11
JA
4750 }
4751
9e645e11
JA
4752 /*
4753 * If we already have a head request, queue this one for async
4754 * submittal once the head completes. If we don't have a head but
4755 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
4756 * submitted sync once the chain is complete. If none of those
4757 * conditions are true (normal request), then just queue it.
4758 */
4759 if (*link) {
9d76377f 4760 struct io_kiocb *head = *link;
4e88d6e7 4761
8cdf2193
PB
4762 /*
4763 * Taking sequential execution of a link, draining both sides
4764 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
4765 * requests in the link. So, it drains the head and the
4766 * next after the link request. The last one is done via
4767 * drain_next flag to persist the effect across calls.
4768 */
711be031
PB
4769 if (sqe_flags & IOSQE_IO_DRAIN) {
4770 head->flags |= REQ_F_IO_DRAIN;
4771 ctx->drain_next = 1;
4772 }
b7bb4f7d 4773 if (io_alloc_async_ctx(req)) {
9e645e11
JA
4774 ret = -EAGAIN;
4775 goto err_req;
4776 }
4777
3529d8c2 4778 ret = io_req_defer_prep(req, sqe);
2d28390a 4779 if (ret) {
4e88d6e7 4780 /* fail even hard links since we don't submit */
9d76377f 4781 head->flags |= REQ_F_FAIL_LINK;
f67676d1 4782 goto err_req;
2d28390a 4783 }
9d76377f
PB
4784 trace_io_uring_link(ctx, req, head);
4785 list_add_tail(&req->link_list, &head->link_list);
32fe525b
PB
4786
4787 /* last request of a link, enqueue the link */
4788 if (!(sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK))) {
4789 io_queue_link_head(head);
4790 *link = NULL;
4791 }
9e645e11 4792 } else {
711be031
PB
4793 if (unlikely(ctx->drain_next)) {
4794 req->flags |= REQ_F_IO_DRAIN;
4795 req->ctx->drain_next = 0;
4796 }
4797 if (sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK)) {
4798 req->flags |= REQ_F_LINK;
711be031
PB
4799 INIT_LIST_HEAD(&req->link_list);
4800 ret = io_req_defer_prep(req, sqe);
4801 if (ret)
4802 req->flags |= REQ_F_FAIL_LINK;
4803 *link = req;
4804 } else {
4805 io_queue_sqe(req, sqe);
4806 }
9e645e11 4807 }
2e6e1fde 4808
75c6a039
JA
4809 if (old_creds)
4810 revert_creds(old_creds);
2e6e1fde 4811 return true;
9e645e11
JA
4812}
4813
9a56a232
JA
4814/*
4815 * Batched submission is done, ensure local IO is flushed out.
4816 */
4817static void io_submit_state_end(struct io_submit_state *state)
4818{
4819 blk_finish_plug(&state->plug);
3d6770fb 4820 io_file_put(state);
2579f913 4821 if (state->free_reqs)
6c8a3134 4822 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
9a56a232
JA
4823}
4824
4825/*
4826 * Start submission side cache.
4827 */
4828static void io_submit_state_start(struct io_submit_state *state,
22efde59 4829 unsigned int max_ios)
9a56a232
JA
4830{
4831 blk_start_plug(&state->plug);
2579f913 4832 state->free_reqs = 0;
9a56a232
JA
4833 state->file = NULL;
4834 state->ios_left = max_ios;
4835}
4836
2b188cc1
JA
4837static void io_commit_sqring(struct io_ring_ctx *ctx)
4838{
75b28aff 4839 struct io_rings *rings = ctx->rings;
2b188cc1 4840
caf582c6
PB
4841 /*
4842 * Ensure any loads from the SQEs are done at this point,
4843 * since once we write the new head, the application could
4844 * write new data to them.
4845 */
4846 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2b188cc1
JA
4847}
4848
2b188cc1 4849/*
3529d8c2 4850 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
2b188cc1
JA
4851 * that is mapped by userspace. This means that care needs to be taken to
4852 * ensure that reads are stable, as we cannot rely on userspace always
4853 * being a good citizen. If members of the sqe are validated and then later
4854 * used, it's important that those reads are done through READ_ONCE() to
4855 * prevent a re-load down the line.
4856 */
3529d8c2
JA
4857static bool io_get_sqring(struct io_ring_ctx *ctx, struct io_kiocb *req,
4858 const struct io_uring_sqe **sqe_ptr)
2b188cc1 4859{
75b28aff 4860 u32 *sq_array = ctx->sq_array;
2b188cc1
JA
4861 unsigned head;
4862
4863 /*
4864 * The cached sq head (or cq tail) serves two purposes:
4865 *
4866 * 1) allows us to batch the cost of updating the user visible
4867 * head updates.
4868 * 2) allows the kernel side to track the head on its own, even
4869 * though the application is the one updating it.
4870 */
ee7d46d9 4871 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
9835d6fa 4872 if (likely(head < ctx->sq_entries)) {
cf6fd4bd
PB
4873 /*
4874 * All io need record the previous position, if LINK vs DARIN,
4875 * it can be used to mark the position of the first IO in the
4876 * link list.
4877 */
4878 req->sequence = ctx->cached_sq_head;
3529d8c2
JA
4879 *sqe_ptr = &ctx->sq_sqes[head];
4880 req->opcode = READ_ONCE((*sqe_ptr)->opcode);
4881 req->user_data = READ_ONCE((*sqe_ptr)->user_data);
2b188cc1
JA
4882 ctx->cached_sq_head++;
4883 return true;
4884 }
4885
4886 /* drop invalid entries */
4887 ctx->cached_sq_head++;
498ccd9e 4888 ctx->cached_sq_dropped++;
ee7d46d9 4889 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
2b188cc1
JA
4890 return false;
4891}
4892
fb5ccc98 4893static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
ae9428ca
PB
4894 struct file *ring_file, int ring_fd,
4895 struct mm_struct **mm, bool async)
6c271ce2
JA
4896{
4897 struct io_submit_state state, *statep = NULL;
9e645e11 4898 struct io_kiocb *link = NULL;
9e645e11 4899 int i, submitted = 0;
95a1b3ff 4900 bool mm_fault = false;
6c271ce2 4901
c4a2ed72 4902 /* if we have a backlog and couldn't flush it all, return BUSY */
ad3eb2c8
JA
4903 if (test_bit(0, &ctx->sq_check_overflow)) {
4904 if (!list_empty(&ctx->cq_overflow_list) &&
4905 !io_cqring_overflow_flush(ctx, false))
4906 return -EBUSY;
4907 }
6c271ce2 4908
ee7d46d9
PB
4909 /* make sure SQ entry isn't read before tail */
4910 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
9ef4f124 4911
2b85edfc
PB
4912 if (!percpu_ref_tryget_many(&ctx->refs, nr))
4913 return -EAGAIN;
6c271ce2
JA
4914
4915 if (nr > IO_PLUG_THRESHOLD) {
22efde59 4916 io_submit_state_start(&state, nr);
6c271ce2
JA
4917 statep = &state;
4918 }
4919
b14cca0c
PB
4920 ctx->ring_fd = ring_fd;
4921 ctx->ring_file = ring_file;
4922
6c271ce2 4923 for (i = 0; i < nr; i++) {
3529d8c2 4924 const struct io_uring_sqe *sqe;
196be95c 4925 struct io_kiocb *req;
1cb1edb2 4926 int err;
fb5ccc98 4927
196be95c
PB
4928 req = io_get_req(ctx, statep);
4929 if (unlikely(!req)) {
4930 if (!submitted)
4931 submitted = -EAGAIN;
fb5ccc98 4932 break;
196be95c 4933 }
3529d8c2 4934 if (!io_get_sqring(ctx, req, &sqe)) {
2b85edfc 4935 __io_req_do_free(req);
196be95c
PB
4936 break;
4937 }
fb5ccc98 4938
d3656344
JA
4939 /* will complete beyond this point, count as submitted */
4940 submitted++;
4941
4942 if (unlikely(req->opcode >= IORING_OP_LAST)) {
1cb1edb2
PB
4943 err = -EINVAL;
4944fail_req:
4945 io_cqring_add_event(req, err);
d3656344 4946 io_double_put_req(req);
196be95c
PB
4947 break;
4948 }
fb5ccc98 4949
d3656344 4950 if (io_op_defs[req->opcode].needs_mm && !*mm) {
95a1b3ff 4951 mm_fault = mm_fault || !mmget_not_zero(ctx->sqo_mm);
1cb1edb2
PB
4952 if (unlikely(mm_fault)) {
4953 err = -EFAULT;
4954 goto fail_req;
95a1b3ff 4955 }
1cb1edb2
PB
4956 use_mm(ctx->sqo_mm);
4957 *mm = ctx->sqo_mm;
9e645e11 4958 }
9e645e11 4959
cf6fd4bd
PB
4960 req->in_async = async;
4961 req->needs_fixed_file = async;
354420f7
JA
4962 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
4963 true, async);
3529d8c2 4964 if (!io_submit_sqe(req, sqe, statep, &link))
2e6e1fde 4965 break;
6c271ce2
JA
4966 }
4967
9466f437
PB
4968 if (unlikely(submitted != nr)) {
4969 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
4970
4971 percpu_ref_put_many(&ctx->refs, nr - ref_used);
4972 }
9e645e11 4973 if (link)
1b4a51b6 4974 io_queue_link_head(link);
6c271ce2
JA
4975 if (statep)
4976 io_submit_state_end(&state);
4977
ae9428ca
PB
4978 /* Commit SQ ring head once we've consumed and submitted all SQEs */
4979 io_commit_sqring(ctx);
4980
6c271ce2
JA
4981 return submitted;
4982}
4983
4984static int io_sq_thread(void *data)
4985{
6c271ce2
JA
4986 struct io_ring_ctx *ctx = data;
4987 struct mm_struct *cur_mm = NULL;
181e448d 4988 const struct cred *old_cred;
6c271ce2
JA
4989 mm_segment_t old_fs;
4990 DEFINE_WAIT(wait);
4991 unsigned inflight;
4992 unsigned long timeout;
c1edbf5f 4993 int ret;
6c271ce2 4994
206aefde 4995 complete(&ctx->completions[1]);
a4c0b3de 4996
6c271ce2
JA
4997 old_fs = get_fs();
4998 set_fs(USER_DS);
181e448d 4999 old_cred = override_creds(ctx->creds);
6c271ce2 5000
c1edbf5f 5001 ret = timeout = inflight = 0;
2bbcd6d3 5002 while (!kthread_should_park()) {
fb5ccc98 5003 unsigned int to_submit;
6c271ce2
JA
5004
5005 if (inflight) {
5006 unsigned nr_events = 0;
5007
5008 if (ctx->flags & IORING_SETUP_IOPOLL) {
2b2ed975
JA
5009 /*
5010 * inflight is the count of the maximum possible
5011 * entries we submitted, but it can be smaller
5012 * if we dropped some of them. If we don't have
5013 * poll entries available, then we know that we
5014 * have nothing left to poll for. Reset the
5015 * inflight count to zero in that case.
5016 */
5017 mutex_lock(&ctx->uring_lock);
5018 if (!list_empty(&ctx->poll_list))
5019 __io_iopoll_check(ctx, &nr_events, 0);
5020 else
5021 inflight = 0;
5022 mutex_unlock(&ctx->uring_lock);
6c271ce2
JA
5023 } else {
5024 /*
5025 * Normal IO, just pretend everything completed.
5026 * We don't have to poll completions for that.
5027 */
5028 nr_events = inflight;
5029 }
5030
5031 inflight -= nr_events;
5032 if (!inflight)
5033 timeout = jiffies + ctx->sq_thread_idle;
5034 }
5035
fb5ccc98 5036 to_submit = io_sqring_entries(ctx);
c1edbf5f
JA
5037
5038 /*
5039 * If submit got -EBUSY, flag us as needing the application
5040 * to enter the kernel to reap and flush events.
5041 */
5042 if (!to_submit || ret == -EBUSY) {
6c271ce2
JA
5043 /*
5044 * We're polling. If we're within the defined idle
5045 * period, then let us spin without work before going
c1edbf5f
JA
5046 * to sleep. The exception is if we got EBUSY doing
5047 * more IO, we should wait for the application to
5048 * reap events and wake us up.
6c271ce2 5049 */
c1edbf5f 5050 if (inflight ||
df069d80
JA
5051 (!time_after(jiffies, timeout) && ret != -EBUSY &&
5052 !percpu_ref_is_dying(&ctx->refs))) {
9831a90c 5053 cond_resched();
6c271ce2
JA
5054 continue;
5055 }
5056
5057 /*
5058 * Drop cur_mm before scheduling, we can't hold it for
5059 * long periods (or over schedule()). Do this before
5060 * adding ourselves to the waitqueue, as the unuse/drop
5061 * may sleep.
5062 */
5063 if (cur_mm) {
5064 unuse_mm(cur_mm);
5065 mmput(cur_mm);
5066 cur_mm = NULL;
5067 }
5068
5069 prepare_to_wait(&ctx->sqo_wait, &wait,
5070 TASK_INTERRUPTIBLE);
5071
5072 /* Tell userspace we may need a wakeup call */
75b28aff 5073 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
0d7bae69
SB
5074 /* make sure to read SQ tail after writing flags */
5075 smp_mb();
6c271ce2 5076
fb5ccc98 5077 to_submit = io_sqring_entries(ctx);
c1edbf5f 5078 if (!to_submit || ret == -EBUSY) {
2bbcd6d3 5079 if (kthread_should_park()) {
6c271ce2
JA
5080 finish_wait(&ctx->sqo_wait, &wait);
5081 break;
5082 }
5083 if (signal_pending(current))
5084 flush_signals(current);
5085 schedule();
5086 finish_wait(&ctx->sqo_wait, &wait);
5087
75b28aff 5088 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6c271ce2
JA
5089 continue;
5090 }
5091 finish_wait(&ctx->sqo_wait, &wait);
5092
75b28aff 5093 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6c271ce2
JA
5094 }
5095
8a4955ff 5096 mutex_lock(&ctx->uring_lock);
1d7bb1d5 5097 ret = io_submit_sqes(ctx, to_submit, NULL, -1, &cur_mm, true);
8a4955ff 5098 mutex_unlock(&ctx->uring_lock);
1d7bb1d5
JA
5099 if (ret > 0)
5100 inflight += ret;
6c271ce2
JA
5101 }
5102
5103 set_fs(old_fs);
5104 if (cur_mm) {
5105 unuse_mm(cur_mm);
5106 mmput(cur_mm);
5107 }
181e448d 5108 revert_creds(old_cred);
06058632 5109
2bbcd6d3 5110 kthread_parkme();
06058632 5111
6c271ce2
JA
5112 return 0;
5113}
5114
bda52162
JA
5115struct io_wait_queue {
5116 struct wait_queue_entry wq;
5117 struct io_ring_ctx *ctx;
5118 unsigned to_wait;
5119 unsigned nr_timeouts;
5120};
5121
1d7bb1d5 5122static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
bda52162
JA
5123{
5124 struct io_ring_ctx *ctx = iowq->ctx;
5125
5126 /*
d195a66e 5127 * Wake up if we have enough events, or if a timeout occurred since we
bda52162
JA
5128 * started waiting. For timeouts, we always want to return to userspace,
5129 * regardless of event count.
5130 */
1d7bb1d5 5131 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
bda52162
JA
5132 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
5133}
5134
5135static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
5136 int wake_flags, void *key)
5137{
5138 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
5139 wq);
5140
1d7bb1d5
JA
5141 /* use noflush == true, as we can't safely rely on locking context */
5142 if (!io_should_wake(iowq, true))
bda52162
JA
5143 return -1;
5144
5145 return autoremove_wake_function(curr, mode, wake_flags, key);
5146}
5147
2b188cc1
JA
5148/*
5149 * Wait until events become available, if we don't already have some. The
5150 * application must reap them itself, as they reside on the shared cq ring.
5151 */
5152static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
5153 const sigset_t __user *sig, size_t sigsz)
5154{
bda52162
JA
5155 struct io_wait_queue iowq = {
5156 .wq = {
5157 .private = current,
5158 .func = io_wake_function,
5159 .entry = LIST_HEAD_INIT(iowq.wq.entry),
5160 },
5161 .ctx = ctx,
5162 .to_wait = min_events,
5163 };
75b28aff 5164 struct io_rings *rings = ctx->rings;
e9ffa5c2 5165 int ret = 0;
2b188cc1 5166
1d7bb1d5 5167 if (io_cqring_events(ctx, false) >= min_events)
2b188cc1
JA
5168 return 0;
5169
5170 if (sig) {
9e75ad5d
AB
5171#ifdef CONFIG_COMPAT
5172 if (in_compat_syscall())
5173 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
b772434b 5174 sigsz);
9e75ad5d
AB
5175 else
5176#endif
b772434b 5177 ret = set_user_sigmask(sig, sigsz);
9e75ad5d 5178
2b188cc1
JA
5179 if (ret)
5180 return ret;
5181 }
5182
bda52162 5183 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
c826bd7a 5184 trace_io_uring_cqring_wait(ctx, min_events);
bda52162
JA
5185 do {
5186 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
5187 TASK_INTERRUPTIBLE);
1d7bb1d5 5188 if (io_should_wake(&iowq, false))
bda52162
JA
5189 break;
5190 schedule();
5191 if (signal_pending(current)) {
e9ffa5c2 5192 ret = -EINTR;
bda52162
JA
5193 break;
5194 }
5195 } while (1);
5196 finish_wait(&ctx->wait, &iowq.wq);
5197
e9ffa5c2 5198 restore_saved_sigmask_unless(ret == -EINTR);
2b188cc1 5199
75b28aff 5200 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
2b188cc1
JA
5201}
5202
6b06314c
JA
5203static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
5204{
5205#if defined(CONFIG_UNIX)
5206 if (ctx->ring_sock) {
5207 struct sock *sock = ctx->ring_sock->sk;
5208 struct sk_buff *skb;
5209
5210 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
5211 kfree_skb(skb);
5212 }
5213#else
5214 int i;
5215
65e19f54
JA
5216 for (i = 0; i < ctx->nr_user_files; i++) {
5217 struct file *file;
5218
5219 file = io_file_from_index(ctx, i);
5220 if (file)
5221 fput(file);
5222 }
6b06314c
JA
5223#endif
5224}
5225
05f3fb3c
JA
5226static void io_file_ref_kill(struct percpu_ref *ref)
5227{
5228 struct fixed_file_data *data;
5229
5230 data = container_of(ref, struct fixed_file_data, refs);
5231 complete(&data->done);
5232}
5233
6b06314c
JA
5234static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
5235{
05f3fb3c 5236 struct fixed_file_data *data = ctx->file_data;
65e19f54
JA
5237 unsigned nr_tables, i;
5238
05f3fb3c 5239 if (!data)
6b06314c
JA
5240 return -ENXIO;
5241
05f3fb3c 5242 percpu_ref_kill_and_confirm(&data->refs, io_file_ref_kill);
e46a7950 5243 flush_work(&data->ref_work);
2faf852d
JA
5244 wait_for_completion(&data->done);
5245 io_ring_file_ref_flush(data);
05f3fb3c
JA
5246 percpu_ref_exit(&data->refs);
5247
6b06314c 5248 __io_sqe_files_unregister(ctx);
65e19f54
JA
5249 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
5250 for (i = 0; i < nr_tables; i++)
05f3fb3c
JA
5251 kfree(data->table[i].files);
5252 kfree(data->table);
5253 kfree(data);
5254 ctx->file_data = NULL;
6b06314c
JA
5255 ctx->nr_user_files = 0;
5256 return 0;
5257}
5258
6c271ce2
JA
5259static void io_sq_thread_stop(struct io_ring_ctx *ctx)
5260{
5261 if (ctx->sqo_thread) {
206aefde 5262 wait_for_completion(&ctx->completions[1]);
2bbcd6d3
RP
5263 /*
5264 * The park is a bit of a work-around, without it we get
5265 * warning spews on shutdown with SQPOLL set and affinity
5266 * set to a single CPU.
5267 */
06058632 5268 kthread_park(ctx->sqo_thread);
6c271ce2
JA
5269 kthread_stop(ctx->sqo_thread);
5270 ctx->sqo_thread = NULL;
5271 }
5272}
5273
6b06314c
JA
5274static void io_finish_async(struct io_ring_ctx *ctx)
5275{
6c271ce2
JA
5276 io_sq_thread_stop(ctx);
5277
561fb04a
JA
5278 if (ctx->io_wq) {
5279 io_wq_destroy(ctx->io_wq);
5280 ctx->io_wq = NULL;
6b06314c
JA
5281 }
5282}
5283
5284#if defined(CONFIG_UNIX)
6b06314c
JA
5285/*
5286 * Ensure the UNIX gc is aware of our file set, so we are certain that
5287 * the io_uring can be safely unregistered on process exit, even if we have
5288 * loops in the file referencing.
5289 */
5290static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
5291{
5292 struct sock *sk = ctx->ring_sock->sk;
5293 struct scm_fp_list *fpl;
5294 struct sk_buff *skb;
08a45173 5295 int i, nr_files;
6b06314c
JA
5296
5297 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
5298 unsigned long inflight = ctx->user->unix_inflight + nr;
5299
5300 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
5301 return -EMFILE;
5302 }
5303
5304 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
5305 if (!fpl)
5306 return -ENOMEM;
5307
5308 skb = alloc_skb(0, GFP_KERNEL);
5309 if (!skb) {
5310 kfree(fpl);
5311 return -ENOMEM;
5312 }
5313
5314 skb->sk = sk;
6b06314c 5315
08a45173 5316 nr_files = 0;
6b06314c
JA
5317 fpl->user = get_uid(ctx->user);
5318 for (i = 0; i < nr; i++) {
65e19f54
JA
5319 struct file *file = io_file_from_index(ctx, i + offset);
5320
5321 if (!file)
08a45173 5322 continue;
65e19f54 5323 fpl->fp[nr_files] = get_file(file);
08a45173
JA
5324 unix_inflight(fpl->user, fpl->fp[nr_files]);
5325 nr_files++;
6b06314c
JA
5326 }
5327
08a45173
JA
5328 if (nr_files) {
5329 fpl->max = SCM_MAX_FD;
5330 fpl->count = nr_files;
5331 UNIXCB(skb).fp = fpl;
05f3fb3c 5332 skb->destructor = unix_destruct_scm;
08a45173
JA
5333 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
5334 skb_queue_head(&sk->sk_receive_queue, skb);
6b06314c 5335
08a45173
JA
5336 for (i = 0; i < nr_files; i++)
5337 fput(fpl->fp[i]);
5338 } else {
5339 kfree_skb(skb);
5340 kfree(fpl);
5341 }
6b06314c
JA
5342
5343 return 0;
5344}
5345
5346/*
5347 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
5348 * causes regular reference counting to break down. We rely on the UNIX
5349 * garbage collection to take care of this problem for us.
5350 */
5351static int io_sqe_files_scm(struct io_ring_ctx *ctx)
5352{
5353 unsigned left, total;
5354 int ret = 0;
5355
5356 total = 0;
5357 left = ctx->nr_user_files;
5358 while (left) {
5359 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
6b06314c
JA
5360
5361 ret = __io_sqe_files_scm(ctx, this_files, total);
5362 if (ret)
5363 break;
5364 left -= this_files;
5365 total += this_files;
5366 }
5367
5368 if (!ret)
5369 return 0;
5370
5371 while (total < ctx->nr_user_files) {
65e19f54
JA
5372 struct file *file = io_file_from_index(ctx, total);
5373
5374 if (file)
5375 fput(file);
6b06314c
JA
5376 total++;
5377 }
5378
5379 return ret;
5380}
5381#else
5382static int io_sqe_files_scm(struct io_ring_ctx *ctx)
5383{
5384 return 0;
5385}
5386#endif
5387
65e19f54
JA
5388static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
5389 unsigned nr_files)
5390{
5391 int i;
5392
5393 for (i = 0; i < nr_tables; i++) {
05f3fb3c 5394 struct fixed_file_table *table = &ctx->file_data->table[i];
65e19f54
JA
5395 unsigned this_files;
5396
5397 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
5398 table->files = kcalloc(this_files, sizeof(struct file *),
5399 GFP_KERNEL);
5400 if (!table->files)
5401 break;
5402 nr_files -= this_files;
5403 }
5404
5405 if (i == nr_tables)
5406 return 0;
5407
5408 for (i = 0; i < nr_tables; i++) {
05f3fb3c 5409 struct fixed_file_table *table = &ctx->file_data->table[i];
65e19f54
JA
5410 kfree(table->files);
5411 }
5412 return 1;
5413}
5414
05f3fb3c
JA
5415static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
5416{
5417#if defined(CONFIG_UNIX)
5418 struct sock *sock = ctx->ring_sock->sk;
5419 struct sk_buff_head list, *head = &sock->sk_receive_queue;
5420 struct sk_buff *skb;
5421 int i;
5422
5423 __skb_queue_head_init(&list);
5424
5425 /*
5426 * Find the skb that holds this file in its SCM_RIGHTS. When found,
5427 * remove this entry and rearrange the file array.
5428 */
5429 skb = skb_dequeue(head);
5430 while (skb) {
5431 struct scm_fp_list *fp;
5432
5433 fp = UNIXCB(skb).fp;
5434 for (i = 0; i < fp->count; i++) {
5435 int left;
5436
5437 if (fp->fp[i] != file)
5438 continue;
5439
5440 unix_notinflight(fp->user, fp->fp[i]);
5441 left = fp->count - 1 - i;
5442 if (left) {
5443 memmove(&fp->fp[i], &fp->fp[i + 1],
5444 left * sizeof(struct file *));
5445 }
5446 fp->count--;
5447 if (!fp->count) {
5448 kfree_skb(skb);
5449 skb = NULL;
5450 } else {
5451 __skb_queue_tail(&list, skb);
5452 }
5453 fput(file);
5454 file = NULL;
5455 break;
5456 }
5457
5458 if (!file)
5459 break;
5460
5461 __skb_queue_tail(&list, skb);
5462
5463 skb = skb_dequeue(head);
5464 }
5465
5466 if (skb_peek(&list)) {
5467 spin_lock_irq(&head->lock);
5468 while ((skb = __skb_dequeue(&list)) != NULL)
5469 __skb_queue_tail(head, skb);
5470 spin_unlock_irq(&head->lock);
5471 }
5472#else
5473 fput(file);
5474#endif
5475}
5476
5477struct io_file_put {
5478 struct llist_node llist;
5479 struct file *file;
5480 struct completion *done;
5481};
5482
2faf852d 5483static void io_ring_file_ref_flush(struct fixed_file_data *data)
65e19f54 5484{
05f3fb3c 5485 struct io_file_put *pfile, *tmp;
05f3fb3c 5486 struct llist_node *node;
65e19f54 5487
05f3fb3c
JA
5488 while ((node = llist_del_all(&data->put_llist)) != NULL) {
5489 llist_for_each_entry_safe(pfile, tmp, node, llist) {
5490 io_ring_file_put(data->ctx, pfile->file);
5491 if (pfile->done)
5492 complete(pfile->done);
5493 else
5494 kfree(pfile);
5495 }
65e19f54 5496 }
2faf852d 5497}
65e19f54 5498
2faf852d
JA
5499static void io_ring_file_ref_switch(struct work_struct *work)
5500{
5501 struct fixed_file_data *data;
65e19f54 5502
2faf852d
JA
5503 data = container_of(work, struct fixed_file_data, ref_work);
5504 io_ring_file_ref_flush(data);
05f3fb3c
JA
5505 percpu_ref_get(&data->refs);
5506 percpu_ref_switch_to_percpu(&data->refs);
5507}
65e19f54 5508
05f3fb3c
JA
5509static void io_file_data_ref_zero(struct percpu_ref *ref)
5510{
5511 struct fixed_file_data *data;
5512
5513 data = container_of(ref, struct fixed_file_data, refs);
5514
2faf852d
JA
5515 /*
5516 * We can't safely switch from inside this context, punt to wq. If
5517 * the table ref is going away, the table is being unregistered.
5518 * Don't queue up the async work for that case, the caller will
5519 * handle it.
5520 */
5521 if (!percpu_ref_is_dying(&data->refs))
5522 queue_work(system_wq, &data->ref_work);
65e19f54
JA
5523}
5524
6b06314c
JA
5525static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
5526 unsigned nr_args)
5527{
5528 __s32 __user *fds = (__s32 __user *) arg;
65e19f54 5529 unsigned nr_tables;
05f3fb3c 5530 struct file *file;
6b06314c
JA
5531 int fd, ret = 0;
5532 unsigned i;
5533
05f3fb3c 5534 if (ctx->file_data)
6b06314c
JA
5535 return -EBUSY;
5536 if (!nr_args)
5537 return -EINVAL;
5538 if (nr_args > IORING_MAX_FIXED_FILES)
5539 return -EMFILE;
5540
05f3fb3c
JA
5541 ctx->file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
5542 if (!ctx->file_data)
5543 return -ENOMEM;
5544 ctx->file_data->ctx = ctx;
5545 init_completion(&ctx->file_data->done);
5546
65e19f54 5547 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
05f3fb3c
JA
5548 ctx->file_data->table = kcalloc(nr_tables,
5549 sizeof(struct fixed_file_table),
65e19f54 5550 GFP_KERNEL);
05f3fb3c
JA
5551 if (!ctx->file_data->table) {
5552 kfree(ctx->file_data);
5553 ctx->file_data = NULL;
6b06314c 5554 return -ENOMEM;
05f3fb3c
JA
5555 }
5556
5557 if (percpu_ref_init(&ctx->file_data->refs, io_file_data_ref_zero,
5558 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
5559 kfree(ctx->file_data->table);
5560 kfree(ctx->file_data);
5561 ctx->file_data = NULL;
6b06314c 5562 return -ENOMEM;
05f3fb3c
JA
5563 }
5564 ctx->file_data->put_llist.first = NULL;
5565 INIT_WORK(&ctx->file_data->ref_work, io_ring_file_ref_switch);
6b06314c 5566
65e19f54 5567 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
05f3fb3c
JA
5568 percpu_ref_exit(&ctx->file_data->refs);
5569 kfree(ctx->file_data->table);
5570 kfree(ctx->file_data);
5571 ctx->file_data = NULL;
65e19f54
JA
5572 return -ENOMEM;
5573 }
5574
08a45173 5575 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
65e19f54
JA
5576 struct fixed_file_table *table;
5577 unsigned index;
5578
6b06314c
JA
5579 ret = -EFAULT;
5580 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
5581 break;
08a45173
JA
5582 /* allow sparse sets */
5583 if (fd == -1) {
5584 ret = 0;
5585 continue;
5586 }
6b06314c 5587
05f3fb3c 5588 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
65e19f54 5589 index = i & IORING_FILE_TABLE_MASK;
05f3fb3c 5590 file = fget(fd);
6b06314c
JA
5591
5592 ret = -EBADF;
05f3fb3c 5593 if (!file)
6b06314c 5594 break;
05f3fb3c 5595
6b06314c
JA
5596 /*
5597 * Don't allow io_uring instances to be registered. If UNIX
5598 * isn't enabled, then this causes a reference cycle and this
5599 * instance can never get freed. If UNIX is enabled we'll
5600 * handle it just fine, but there's still no point in allowing
5601 * a ring fd as it doesn't support regular read/write anyway.
5602 */
05f3fb3c
JA
5603 if (file->f_op == &io_uring_fops) {
5604 fput(file);
6b06314c
JA
5605 break;
5606 }
6b06314c 5607 ret = 0;
05f3fb3c 5608 table->files[index] = file;
6b06314c
JA
5609 }
5610
5611 if (ret) {
65e19f54 5612 for (i = 0; i < ctx->nr_user_files; i++) {
65e19f54
JA
5613 file = io_file_from_index(ctx, i);
5614 if (file)
5615 fput(file);
5616 }
5617 for (i = 0; i < nr_tables; i++)
05f3fb3c 5618 kfree(ctx->file_data->table[i].files);
6b06314c 5619
05f3fb3c
JA
5620 kfree(ctx->file_data->table);
5621 kfree(ctx->file_data);
5622 ctx->file_data = NULL;
6b06314c
JA
5623 ctx->nr_user_files = 0;
5624 return ret;
5625 }
5626
5627 ret = io_sqe_files_scm(ctx);
5628 if (ret)
5629 io_sqe_files_unregister(ctx);
5630
5631 return ret;
5632}
5633
c3a31e60
JA
5634static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
5635 int index)
5636{
5637#if defined(CONFIG_UNIX)
5638 struct sock *sock = ctx->ring_sock->sk;
5639 struct sk_buff_head *head = &sock->sk_receive_queue;
5640 struct sk_buff *skb;
5641
5642 /*
5643 * See if we can merge this file into an existing skb SCM_RIGHTS
5644 * file set. If there's no room, fall back to allocating a new skb
5645 * and filling it in.
5646 */
5647 spin_lock_irq(&head->lock);
5648 skb = skb_peek(head);
5649 if (skb) {
5650 struct scm_fp_list *fpl = UNIXCB(skb).fp;
5651
5652 if (fpl->count < SCM_MAX_FD) {
5653 __skb_unlink(skb, head);
5654 spin_unlock_irq(&head->lock);
5655 fpl->fp[fpl->count] = get_file(file);
5656 unix_inflight(fpl->user, fpl->fp[fpl->count]);
5657 fpl->count++;
5658 spin_lock_irq(&head->lock);
5659 __skb_queue_head(head, skb);
5660 } else {
5661 skb = NULL;
5662 }
5663 }
5664 spin_unlock_irq(&head->lock);
5665
5666 if (skb) {
5667 fput(file);
5668 return 0;
5669 }
5670
5671 return __io_sqe_files_scm(ctx, 1, index);
5672#else
5673 return 0;
5674#endif
5675}
5676
05f3fb3c 5677static void io_atomic_switch(struct percpu_ref *ref)
c3a31e60 5678{
05f3fb3c
JA
5679 struct fixed_file_data *data;
5680
5681 data = container_of(ref, struct fixed_file_data, refs);
5682 clear_bit(FFD_F_ATOMIC, &data->state);
5683}
5684
5685static bool io_queue_file_removal(struct fixed_file_data *data,
5686 struct file *file)
5687{
5688 struct io_file_put *pfile, pfile_stack;
5689 DECLARE_COMPLETION_ONSTACK(done);
5690
5691 /*
5692 * If we fail allocating the struct we need for doing async reomval
5693 * of this file, just punt to sync and wait for it.
5694 */
5695 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
5696 if (!pfile) {
5697 pfile = &pfile_stack;
5698 pfile->done = &done;
5699 }
5700
5701 pfile->file = file;
5702 llist_add(&pfile->llist, &data->put_llist);
5703
5704 if (pfile == &pfile_stack) {
5705 if (!test_and_set_bit(FFD_F_ATOMIC, &data->state)) {
5706 percpu_ref_put(&data->refs);
5707 percpu_ref_switch_to_atomic(&data->refs,
5708 io_atomic_switch);
5709 }
5710 wait_for_completion(&done);
5711 flush_work(&data->ref_work);
5712 return false;
5713 }
5714
5715 return true;
5716}
5717
5718static int __io_sqe_files_update(struct io_ring_ctx *ctx,
5719 struct io_uring_files_update *up,
5720 unsigned nr_args)
5721{
5722 struct fixed_file_data *data = ctx->file_data;
5723 bool ref_switch = false;
5724 struct file *file;
c3a31e60
JA
5725 __s32 __user *fds;
5726 int fd, i, err;
5727 __u32 done;
5728
05f3fb3c 5729 if (check_add_overflow(up->offset, nr_args, &done))
c3a31e60
JA
5730 return -EOVERFLOW;
5731 if (done > ctx->nr_user_files)
5732 return -EINVAL;
5733
5734 done = 0;
05f3fb3c 5735 fds = u64_to_user_ptr(up->fds);
c3a31e60 5736 while (nr_args) {
65e19f54
JA
5737 struct fixed_file_table *table;
5738 unsigned index;
5739
c3a31e60
JA
5740 err = 0;
5741 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
5742 err = -EFAULT;
5743 break;
5744 }
05f3fb3c
JA
5745 i = array_index_nospec(up->offset, ctx->nr_user_files);
5746 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
65e19f54
JA
5747 index = i & IORING_FILE_TABLE_MASK;
5748 if (table->files[index]) {
05f3fb3c 5749 file = io_file_from_index(ctx, index);
65e19f54 5750 table->files[index] = NULL;
05f3fb3c
JA
5751 if (io_queue_file_removal(data, file))
5752 ref_switch = true;
c3a31e60
JA
5753 }
5754 if (fd != -1) {
c3a31e60
JA
5755 file = fget(fd);
5756 if (!file) {
5757 err = -EBADF;
5758 break;
5759 }
5760 /*
5761 * Don't allow io_uring instances to be registered. If
5762 * UNIX isn't enabled, then this causes a reference
5763 * cycle and this instance can never get freed. If UNIX
5764 * is enabled we'll handle it just fine, but there's
5765 * still no point in allowing a ring fd as it doesn't
5766 * support regular read/write anyway.
5767 */
5768 if (file->f_op == &io_uring_fops) {
5769 fput(file);
5770 err = -EBADF;
5771 break;
5772 }
65e19f54 5773 table->files[index] = file;
c3a31e60
JA
5774 err = io_sqe_file_register(ctx, file, i);
5775 if (err)
5776 break;
5777 }
5778 nr_args--;
5779 done++;
05f3fb3c
JA
5780 up->offset++;
5781 }
5782
5783 if (ref_switch && !test_and_set_bit(FFD_F_ATOMIC, &data->state)) {
5784 percpu_ref_put(&data->refs);
5785 percpu_ref_switch_to_atomic(&data->refs, io_atomic_switch);
c3a31e60
JA
5786 }
5787
5788 return done ? done : err;
5789}
05f3fb3c
JA
5790static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
5791 unsigned nr_args)
5792{
5793 struct io_uring_files_update up;
5794
5795 if (!ctx->file_data)
5796 return -ENXIO;
5797 if (!nr_args)
5798 return -EINVAL;
5799 if (copy_from_user(&up, arg, sizeof(up)))
5800 return -EFAULT;
5801 if (up.resv)
5802 return -EINVAL;
5803
5804 return __io_sqe_files_update(ctx, &up, nr_args);
5805}
c3a31e60 5806
7d723065
JA
5807static void io_put_work(struct io_wq_work *work)
5808{
5809 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5810
5811 io_put_req(req);
5812}
5813
5814static void io_get_work(struct io_wq_work *work)
5815{
5816 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5817
5818 refcount_inc(&req->refs);
5819}
5820
24369c2e
PB
5821static int io_init_wq_offload(struct io_ring_ctx *ctx,
5822 struct io_uring_params *p)
5823{
5824 struct io_wq_data data;
5825 struct fd f;
5826 struct io_ring_ctx *ctx_attach;
5827 unsigned int concurrency;
5828 int ret = 0;
5829
5830 data.user = ctx->user;
5831 data.get_work = io_get_work;
5832 data.put_work = io_put_work;
5833
5834 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
5835 /* Do QD, or 4 * CPUS, whatever is smallest */
5836 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
5837
5838 ctx->io_wq = io_wq_create(concurrency, &data);
5839 if (IS_ERR(ctx->io_wq)) {
5840 ret = PTR_ERR(ctx->io_wq);
5841 ctx->io_wq = NULL;
5842 }
5843 return ret;
5844 }
5845
5846 f = fdget(p->wq_fd);
5847 if (!f.file)
5848 return -EBADF;
5849
5850 if (f.file->f_op != &io_uring_fops) {
5851 ret = -EINVAL;
5852 goto out_fput;
5853 }
5854
5855 ctx_attach = f.file->private_data;
5856 /* @io_wq is protected by holding the fd */
5857 if (!io_wq_get(ctx_attach->io_wq, &data)) {
5858 ret = -EINVAL;
5859 goto out_fput;
5860 }
5861
5862 ctx->io_wq = ctx_attach->io_wq;
5863out_fput:
5864 fdput(f);
5865 return ret;
5866}
5867
6c271ce2
JA
5868static int io_sq_offload_start(struct io_ring_ctx *ctx,
5869 struct io_uring_params *p)
2b188cc1
JA
5870{
5871 int ret;
5872
6c271ce2 5873 init_waitqueue_head(&ctx->sqo_wait);
2b188cc1
JA
5874 mmgrab(current->mm);
5875 ctx->sqo_mm = current->mm;
5876
6c271ce2 5877 if (ctx->flags & IORING_SETUP_SQPOLL) {
3ec482d1
JA
5878 ret = -EPERM;
5879 if (!capable(CAP_SYS_ADMIN))
5880 goto err;
5881
917257da
JA
5882 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
5883 if (!ctx->sq_thread_idle)
5884 ctx->sq_thread_idle = HZ;
5885
6c271ce2 5886 if (p->flags & IORING_SETUP_SQ_AFF) {
44a9bd18 5887 int cpu = p->sq_thread_cpu;
6c271ce2 5888
917257da 5889 ret = -EINVAL;
44a9bd18
JA
5890 if (cpu >= nr_cpu_ids)
5891 goto err;
7889f44d 5892 if (!cpu_online(cpu))
917257da
JA
5893 goto err;
5894
6c271ce2
JA
5895 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
5896 ctx, cpu,
5897 "io_uring-sq");
5898 } else {
5899 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
5900 "io_uring-sq");
5901 }
5902 if (IS_ERR(ctx->sqo_thread)) {
5903 ret = PTR_ERR(ctx->sqo_thread);
5904 ctx->sqo_thread = NULL;
5905 goto err;
5906 }
5907 wake_up_process(ctx->sqo_thread);
5908 } else if (p->flags & IORING_SETUP_SQ_AFF) {
5909 /* Can't have SQ_AFF without SQPOLL */
5910 ret = -EINVAL;
5911 goto err;
5912 }
5913
24369c2e
PB
5914 ret = io_init_wq_offload(ctx, p);
5915 if (ret)
2b188cc1 5916 goto err;
2b188cc1
JA
5917
5918 return 0;
5919err:
54a91f3b 5920 io_finish_async(ctx);
2b188cc1
JA
5921 mmdrop(ctx->sqo_mm);
5922 ctx->sqo_mm = NULL;
5923 return ret;
5924}
5925
5926static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
5927{
5928 atomic_long_sub(nr_pages, &user->locked_vm);
5929}
5930
5931static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
5932{
5933 unsigned long page_limit, cur_pages, new_pages;
5934
5935 /* Don't allow more pages than we can safely lock */
5936 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
5937
5938 do {
5939 cur_pages = atomic_long_read(&user->locked_vm);
5940 new_pages = cur_pages + nr_pages;
5941 if (new_pages > page_limit)
5942 return -ENOMEM;
5943 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
5944 new_pages) != cur_pages);
5945
5946 return 0;
5947}
5948
5949static void io_mem_free(void *ptr)
5950{
52e04ef4
MR
5951 struct page *page;
5952
5953 if (!ptr)
5954 return;
2b188cc1 5955
52e04ef4 5956 page = virt_to_head_page(ptr);
2b188cc1
JA
5957 if (put_page_testzero(page))
5958 free_compound_page(page);
5959}
5960
5961static void *io_mem_alloc(size_t size)
5962{
5963 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
5964 __GFP_NORETRY;
5965
5966 return (void *) __get_free_pages(gfp_flags, get_order(size));
5967}
5968
75b28aff
HV
5969static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
5970 size_t *sq_offset)
5971{
5972 struct io_rings *rings;
5973 size_t off, sq_array_size;
5974
5975 off = struct_size(rings, cqes, cq_entries);
5976 if (off == SIZE_MAX)
5977 return SIZE_MAX;
5978
5979#ifdef CONFIG_SMP
5980 off = ALIGN(off, SMP_CACHE_BYTES);
5981 if (off == 0)
5982 return SIZE_MAX;
5983#endif
5984
5985 sq_array_size = array_size(sizeof(u32), sq_entries);
5986 if (sq_array_size == SIZE_MAX)
5987 return SIZE_MAX;
5988
5989 if (check_add_overflow(off, sq_array_size, &off))
5990 return SIZE_MAX;
5991
5992 if (sq_offset)
5993 *sq_offset = off;
5994
5995 return off;
5996}
5997
2b188cc1
JA
5998static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
5999{
75b28aff 6000 size_t pages;
2b188cc1 6001
75b28aff
HV
6002 pages = (size_t)1 << get_order(
6003 rings_size(sq_entries, cq_entries, NULL));
6004 pages += (size_t)1 << get_order(
6005 array_size(sizeof(struct io_uring_sqe), sq_entries));
2b188cc1 6006
75b28aff 6007 return pages;
2b188cc1
JA
6008}
6009
edafccee
JA
6010static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
6011{
6012 int i, j;
6013
6014 if (!ctx->user_bufs)
6015 return -ENXIO;
6016
6017 for (i = 0; i < ctx->nr_user_bufs; i++) {
6018 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
6019
6020 for (j = 0; j < imu->nr_bvecs; j++)
f1f6a7dd 6021 unpin_user_page(imu->bvec[j].bv_page);
edafccee
JA
6022
6023 if (ctx->account_mem)
6024 io_unaccount_mem(ctx->user, imu->nr_bvecs);
d4ef6475 6025 kvfree(imu->bvec);
edafccee
JA
6026 imu->nr_bvecs = 0;
6027 }
6028
6029 kfree(ctx->user_bufs);
6030 ctx->user_bufs = NULL;
6031 ctx->nr_user_bufs = 0;
6032 return 0;
6033}
6034
6035static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
6036 void __user *arg, unsigned index)
6037{
6038 struct iovec __user *src;
6039
6040#ifdef CONFIG_COMPAT
6041 if (ctx->compat) {
6042 struct compat_iovec __user *ciovs;
6043 struct compat_iovec ciov;
6044
6045 ciovs = (struct compat_iovec __user *) arg;
6046 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
6047 return -EFAULT;
6048
d55e5f5b 6049 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
edafccee
JA
6050 dst->iov_len = ciov.iov_len;
6051 return 0;
6052 }
6053#endif
6054 src = (struct iovec __user *) arg;
6055 if (copy_from_user(dst, &src[index], sizeof(*dst)))
6056 return -EFAULT;
6057 return 0;
6058}
6059
6060static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
6061 unsigned nr_args)
6062{
6063 struct vm_area_struct **vmas = NULL;
6064 struct page **pages = NULL;
6065 int i, j, got_pages = 0;
6066 int ret = -EINVAL;
6067
6068 if (ctx->user_bufs)
6069 return -EBUSY;
6070 if (!nr_args || nr_args > UIO_MAXIOV)
6071 return -EINVAL;
6072
6073 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
6074 GFP_KERNEL);
6075 if (!ctx->user_bufs)
6076 return -ENOMEM;
6077
6078 for (i = 0; i < nr_args; i++) {
6079 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
6080 unsigned long off, start, end, ubuf;
6081 int pret, nr_pages;
6082 struct iovec iov;
6083 size_t size;
6084
6085 ret = io_copy_iov(ctx, &iov, arg, i);
6086 if (ret)
a278682d 6087 goto err;
edafccee
JA
6088
6089 /*
6090 * Don't impose further limits on the size and buffer
6091 * constraints here, we'll -EINVAL later when IO is
6092 * submitted if they are wrong.
6093 */
6094 ret = -EFAULT;
6095 if (!iov.iov_base || !iov.iov_len)
6096 goto err;
6097
6098 /* arbitrary limit, but we need something */
6099 if (iov.iov_len > SZ_1G)
6100 goto err;
6101
6102 ubuf = (unsigned long) iov.iov_base;
6103 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
6104 start = ubuf >> PAGE_SHIFT;
6105 nr_pages = end - start;
6106
6107 if (ctx->account_mem) {
6108 ret = io_account_mem(ctx->user, nr_pages);
6109 if (ret)
6110 goto err;
6111 }
6112
6113 ret = 0;
6114 if (!pages || nr_pages > got_pages) {
6115 kfree(vmas);
6116 kfree(pages);
d4ef6475 6117 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
edafccee 6118 GFP_KERNEL);
d4ef6475 6119 vmas = kvmalloc_array(nr_pages,
edafccee
JA
6120 sizeof(struct vm_area_struct *),
6121 GFP_KERNEL);
6122 if (!pages || !vmas) {
6123 ret = -ENOMEM;
6124 if (ctx->account_mem)
6125 io_unaccount_mem(ctx->user, nr_pages);
6126 goto err;
6127 }
6128 got_pages = nr_pages;
6129 }
6130
d4ef6475 6131 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
edafccee
JA
6132 GFP_KERNEL);
6133 ret = -ENOMEM;
6134 if (!imu->bvec) {
6135 if (ctx->account_mem)
6136 io_unaccount_mem(ctx->user, nr_pages);
6137 goto err;
6138 }
6139
6140 ret = 0;
6141 down_read(&current->mm->mmap_sem);
2113b05d 6142 pret = pin_user_pages(ubuf, nr_pages,
932f4a63
IW
6143 FOLL_WRITE | FOLL_LONGTERM,
6144 pages, vmas);
edafccee
JA
6145 if (pret == nr_pages) {
6146 /* don't support file backed memory */
6147 for (j = 0; j < nr_pages; j++) {
6148 struct vm_area_struct *vma = vmas[j];
6149
6150 if (vma->vm_file &&
6151 !is_file_hugepages(vma->vm_file)) {
6152 ret = -EOPNOTSUPP;
6153 break;
6154 }
6155 }
6156 } else {
6157 ret = pret < 0 ? pret : -EFAULT;
6158 }
6159 up_read(&current->mm->mmap_sem);
6160 if (ret) {
6161 /*
6162 * if we did partial map, or found file backed vmas,
6163 * release any pages we did get
6164 */
27c4d3a3 6165 if (pret > 0)
f1f6a7dd 6166 unpin_user_pages(pages, pret);
edafccee
JA
6167 if (ctx->account_mem)
6168 io_unaccount_mem(ctx->user, nr_pages);
d4ef6475 6169 kvfree(imu->bvec);
edafccee
JA
6170 goto err;
6171 }
6172
6173 off = ubuf & ~PAGE_MASK;
6174 size = iov.iov_len;
6175 for (j = 0; j < nr_pages; j++) {
6176 size_t vec_len;
6177
6178 vec_len = min_t(size_t, size, PAGE_SIZE - off);
6179 imu->bvec[j].bv_page = pages[j];
6180 imu->bvec[j].bv_len = vec_len;
6181 imu->bvec[j].bv_offset = off;
6182 off = 0;
6183 size -= vec_len;
6184 }
6185 /* store original address for later verification */
6186 imu->ubuf = ubuf;
6187 imu->len = iov.iov_len;
6188 imu->nr_bvecs = nr_pages;
6189
6190 ctx->nr_user_bufs++;
6191 }
d4ef6475
MR
6192 kvfree(pages);
6193 kvfree(vmas);
edafccee
JA
6194 return 0;
6195err:
d4ef6475
MR
6196 kvfree(pages);
6197 kvfree(vmas);
edafccee
JA
6198 io_sqe_buffer_unregister(ctx);
6199 return ret;
6200}
6201
9b402849
JA
6202static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
6203{
6204 __s32 __user *fds = arg;
6205 int fd;
6206
6207 if (ctx->cq_ev_fd)
6208 return -EBUSY;
6209
6210 if (copy_from_user(&fd, fds, sizeof(*fds)))
6211 return -EFAULT;
6212
6213 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
6214 if (IS_ERR(ctx->cq_ev_fd)) {
6215 int ret = PTR_ERR(ctx->cq_ev_fd);
6216 ctx->cq_ev_fd = NULL;
6217 return ret;
6218 }
6219
6220 return 0;
6221}
6222
6223static int io_eventfd_unregister(struct io_ring_ctx *ctx)
6224{
6225 if (ctx->cq_ev_fd) {
6226 eventfd_ctx_put(ctx->cq_ev_fd);
6227 ctx->cq_ev_fd = NULL;
6228 return 0;
6229 }
6230
6231 return -ENXIO;
6232}
6233
2b188cc1
JA
6234static void io_ring_ctx_free(struct io_ring_ctx *ctx)
6235{
6b06314c 6236 io_finish_async(ctx);
2b188cc1
JA
6237 if (ctx->sqo_mm)
6238 mmdrop(ctx->sqo_mm);
def596e9
JA
6239
6240 io_iopoll_reap_events(ctx);
edafccee 6241 io_sqe_buffer_unregister(ctx);
6b06314c 6242 io_sqe_files_unregister(ctx);
9b402849 6243 io_eventfd_unregister(ctx);
def596e9 6244
2b188cc1 6245#if defined(CONFIG_UNIX)
355e8d26
EB
6246 if (ctx->ring_sock) {
6247 ctx->ring_sock->file = NULL; /* so that iput() is called */
2b188cc1 6248 sock_release(ctx->ring_sock);
355e8d26 6249 }
2b188cc1
JA
6250#endif
6251
75b28aff 6252 io_mem_free(ctx->rings);
2b188cc1 6253 io_mem_free(ctx->sq_sqes);
2b188cc1
JA
6254
6255 percpu_ref_exit(&ctx->refs);
6256 if (ctx->account_mem)
6257 io_unaccount_mem(ctx->user,
6258 ring_pages(ctx->sq_entries, ctx->cq_entries));
6259 free_uid(ctx->user);
181e448d 6260 put_cred(ctx->creds);
206aefde 6261 kfree(ctx->completions);
78076bb6 6262 kfree(ctx->cancel_hash);
0ddf92e8 6263 kmem_cache_free(req_cachep, ctx->fallback_req);
2b188cc1
JA
6264 kfree(ctx);
6265}
6266
6267static __poll_t io_uring_poll(struct file *file, poll_table *wait)
6268{
6269 struct io_ring_ctx *ctx = file->private_data;
6270 __poll_t mask = 0;
6271
6272 poll_wait(file, &ctx->cq_wait, wait);
4f7067c3
SB
6273 /*
6274 * synchronizes with barrier from wq_has_sleeper call in
6275 * io_commit_cqring
6276 */
2b188cc1 6277 smp_rmb();
75b28aff
HV
6278 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
6279 ctx->rings->sq_ring_entries)
2b188cc1 6280 mask |= EPOLLOUT | EPOLLWRNORM;
63e5d81f 6281 if (io_cqring_events(ctx, false))
2b188cc1
JA
6282 mask |= EPOLLIN | EPOLLRDNORM;
6283
6284 return mask;
6285}
6286
6287static int io_uring_fasync(int fd, struct file *file, int on)
6288{
6289 struct io_ring_ctx *ctx = file->private_data;
6290
6291 return fasync_helper(fd, file, on, &ctx->cq_fasync);
6292}
6293
071698e1
JA
6294static int io_remove_personalities(int id, void *p, void *data)
6295{
6296 struct io_ring_ctx *ctx = data;
6297 const struct cred *cred;
6298
6299 cred = idr_remove(&ctx->personality_idr, id);
6300 if (cred)
6301 put_cred(cred);
6302 return 0;
6303}
6304
2b188cc1
JA
6305static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
6306{
6307 mutex_lock(&ctx->uring_lock);
6308 percpu_ref_kill(&ctx->refs);
6309 mutex_unlock(&ctx->uring_lock);
6310
df069d80
JA
6311 /*
6312 * Wait for sq thread to idle, if we have one. It won't spin on new
6313 * work after we've killed the ctx ref above. This is important to do
6314 * before we cancel existing commands, as the thread could otherwise
6315 * be queueing new work post that. If that's work we need to cancel,
6316 * it could cause shutdown to hang.
6317 */
6318 while (ctx->sqo_thread && !wq_has_sleeper(&ctx->sqo_wait))
6319 cpu_relax();
6320
5262f567 6321 io_kill_timeouts(ctx);
221c5eb2 6322 io_poll_remove_all(ctx);
561fb04a
JA
6323
6324 if (ctx->io_wq)
6325 io_wq_cancel_all(ctx->io_wq);
6326
def596e9 6327 io_iopoll_reap_events(ctx);
15dff286
JA
6328 /* if we failed setting up the ctx, we might not have any rings */
6329 if (ctx->rings)
6330 io_cqring_overflow_flush(ctx, true);
071698e1 6331 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
206aefde 6332 wait_for_completion(&ctx->completions[0]);
2b188cc1
JA
6333 io_ring_ctx_free(ctx);
6334}
6335
6336static int io_uring_release(struct inode *inode, struct file *file)
6337{
6338 struct io_ring_ctx *ctx = file->private_data;
6339
6340 file->private_data = NULL;
6341 io_ring_ctx_wait_and_kill(ctx);
6342 return 0;
6343}
6344
fcb323cc
JA
6345static void io_uring_cancel_files(struct io_ring_ctx *ctx,
6346 struct files_struct *files)
6347{
6348 struct io_kiocb *req;
6349 DEFINE_WAIT(wait);
6350
6351 while (!list_empty_careful(&ctx->inflight_list)) {
768134d4 6352 struct io_kiocb *cancel_req = NULL;
fcb323cc
JA
6353
6354 spin_lock_irq(&ctx->inflight_lock);
6355 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
768134d4
JA
6356 if (req->work.files != files)
6357 continue;
6358 /* req is being completed, ignore */
6359 if (!refcount_inc_not_zero(&req->refs))
6360 continue;
6361 cancel_req = req;
6362 break;
fcb323cc 6363 }
768134d4 6364 if (cancel_req)
fcb323cc 6365 prepare_to_wait(&ctx->inflight_wait, &wait,
768134d4 6366 TASK_UNINTERRUPTIBLE);
fcb323cc
JA
6367 spin_unlock_irq(&ctx->inflight_lock);
6368
768134d4
JA
6369 /* We need to keep going until we don't find a matching req */
6370 if (!cancel_req)
fcb323cc 6371 break;
2f6d9b9d
BL
6372
6373 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
6374 io_put_req(cancel_req);
fcb323cc
JA
6375 schedule();
6376 }
768134d4 6377 finish_wait(&ctx->inflight_wait, &wait);
fcb323cc
JA
6378}
6379
6380static int io_uring_flush(struct file *file, void *data)
6381{
6382 struct io_ring_ctx *ctx = file->private_data;
6383
6384 io_uring_cancel_files(ctx, data);
fcb323cc
JA
6385 return 0;
6386}
6387
6c5c240e
RP
6388static void *io_uring_validate_mmap_request(struct file *file,
6389 loff_t pgoff, size_t sz)
2b188cc1 6390{
2b188cc1 6391 struct io_ring_ctx *ctx = file->private_data;
6c5c240e 6392 loff_t offset = pgoff << PAGE_SHIFT;
2b188cc1
JA
6393 struct page *page;
6394 void *ptr;
6395
6396 switch (offset) {
6397 case IORING_OFF_SQ_RING:
75b28aff
HV
6398 case IORING_OFF_CQ_RING:
6399 ptr = ctx->rings;
2b188cc1
JA
6400 break;
6401 case IORING_OFF_SQES:
6402 ptr = ctx->sq_sqes;
6403 break;
2b188cc1 6404 default:
6c5c240e 6405 return ERR_PTR(-EINVAL);
2b188cc1
JA
6406 }
6407
6408 page = virt_to_head_page(ptr);
a50b854e 6409 if (sz > page_size(page))
6c5c240e
RP
6410 return ERR_PTR(-EINVAL);
6411
6412 return ptr;
6413}
6414
6415#ifdef CONFIG_MMU
6416
6417static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6418{
6419 size_t sz = vma->vm_end - vma->vm_start;
6420 unsigned long pfn;
6421 void *ptr;
6422
6423 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
6424 if (IS_ERR(ptr))
6425 return PTR_ERR(ptr);
2b188cc1
JA
6426
6427 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
6428 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
6429}
6430
6c5c240e
RP
6431#else /* !CONFIG_MMU */
6432
6433static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6434{
6435 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
6436}
6437
6438static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
6439{
6440 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
6441}
6442
6443static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
6444 unsigned long addr, unsigned long len,
6445 unsigned long pgoff, unsigned long flags)
6446{
6447 void *ptr;
6448
6449 ptr = io_uring_validate_mmap_request(file, pgoff, len);
6450 if (IS_ERR(ptr))
6451 return PTR_ERR(ptr);
6452
6453 return (unsigned long) ptr;
6454}
6455
6456#endif /* !CONFIG_MMU */
6457
2b188cc1
JA
6458SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
6459 u32, min_complete, u32, flags, const sigset_t __user *, sig,
6460 size_t, sigsz)
6461{
6462 struct io_ring_ctx *ctx;
6463 long ret = -EBADF;
6464 int submitted = 0;
6465 struct fd f;
6466
6c271ce2 6467 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
2b188cc1
JA
6468 return -EINVAL;
6469
6470 f = fdget(fd);
6471 if (!f.file)
6472 return -EBADF;
6473
6474 ret = -EOPNOTSUPP;
6475 if (f.file->f_op != &io_uring_fops)
6476 goto out_fput;
6477
6478 ret = -ENXIO;
6479 ctx = f.file->private_data;
6480 if (!percpu_ref_tryget(&ctx->refs))
6481 goto out_fput;
6482
6c271ce2
JA
6483 /*
6484 * For SQ polling, the thread will do all submissions and completions.
6485 * Just return the requested submit count, and wake the thread if
6486 * we were asked to.
6487 */
b2a9eada 6488 ret = 0;
6c271ce2 6489 if (ctx->flags & IORING_SETUP_SQPOLL) {
c1edbf5f
JA
6490 if (!list_empty_careful(&ctx->cq_overflow_list))
6491 io_cqring_overflow_flush(ctx, false);
6c271ce2
JA
6492 if (flags & IORING_ENTER_SQ_WAKEUP)
6493 wake_up(&ctx->sqo_wait);
6494 submitted = to_submit;
b2a9eada 6495 } else if (to_submit) {
ae9428ca 6496 struct mm_struct *cur_mm;
2b188cc1
JA
6497
6498 mutex_lock(&ctx->uring_lock);
ae9428ca
PB
6499 /* already have mm, so io_submit_sqes() won't try to grab it */
6500 cur_mm = ctx->sqo_mm;
6501 submitted = io_submit_sqes(ctx, to_submit, f.file, fd,
6502 &cur_mm, false);
2b188cc1 6503 mutex_unlock(&ctx->uring_lock);
7c504e65
PB
6504
6505 if (submitted != to_submit)
6506 goto out;
2b188cc1
JA
6507 }
6508 if (flags & IORING_ENTER_GETEVENTS) {
def596e9
JA
6509 unsigned nr_events = 0;
6510
2b188cc1
JA
6511 min_complete = min(min_complete, ctx->cq_entries);
6512
def596e9 6513 if (ctx->flags & IORING_SETUP_IOPOLL) {
def596e9 6514 ret = io_iopoll_check(ctx, &nr_events, min_complete);
def596e9
JA
6515 } else {
6516 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
6517 }
2b188cc1
JA
6518 }
6519
7c504e65 6520out:
6805b32e 6521 percpu_ref_put(&ctx->refs);
2b188cc1
JA
6522out_fput:
6523 fdput(f);
6524 return submitted ? submitted : ret;
6525}
6526
87ce955b
JA
6527static int io_uring_show_cred(int id, void *p, void *data)
6528{
6529 const struct cred *cred = p;
6530 struct seq_file *m = data;
6531 struct user_namespace *uns = seq_user_ns(m);
6532 struct group_info *gi;
6533 kernel_cap_t cap;
6534 unsigned __capi;
6535 int g;
6536
6537 seq_printf(m, "%5d\n", id);
6538 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
6539 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
6540 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
6541 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
6542 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
6543 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
6544 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
6545 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
6546 seq_puts(m, "\n\tGroups:\t");
6547 gi = cred->group_info;
6548 for (g = 0; g < gi->ngroups; g++) {
6549 seq_put_decimal_ull(m, g ? " " : "",
6550 from_kgid_munged(uns, gi->gid[g]));
6551 }
6552 seq_puts(m, "\n\tCapEff:\t");
6553 cap = cred->cap_effective;
6554 CAP_FOR_EACH_U32(__capi)
6555 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
6556 seq_putc(m, '\n');
6557 return 0;
6558}
6559
6560static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
6561{
6562 int i;
6563
6564 mutex_lock(&ctx->uring_lock);
6565 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
6566 for (i = 0; i < ctx->nr_user_files; i++) {
6567 struct fixed_file_table *table;
6568 struct file *f;
6569
6570 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
6571 f = table->files[i & IORING_FILE_TABLE_MASK];
6572 if (f)
6573 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
6574 else
6575 seq_printf(m, "%5u: <none>\n", i);
6576 }
6577 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
6578 for (i = 0; i < ctx->nr_user_bufs; i++) {
6579 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
6580
6581 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
6582 (unsigned int) buf->len);
6583 }
6584 if (!idr_is_empty(&ctx->personality_idr)) {
6585 seq_printf(m, "Personalities:\n");
6586 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
6587 }
6588 mutex_unlock(&ctx->uring_lock);
6589}
6590
6591static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
6592{
6593 struct io_ring_ctx *ctx = f->private_data;
6594
6595 if (percpu_ref_tryget(&ctx->refs)) {
6596 __io_uring_show_fdinfo(ctx, m);
6597 percpu_ref_put(&ctx->refs);
6598 }
6599}
6600
2b188cc1
JA
6601static const struct file_operations io_uring_fops = {
6602 .release = io_uring_release,
fcb323cc 6603 .flush = io_uring_flush,
2b188cc1 6604 .mmap = io_uring_mmap,
6c5c240e
RP
6605#ifndef CONFIG_MMU
6606 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
6607 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
6608#endif
2b188cc1
JA
6609 .poll = io_uring_poll,
6610 .fasync = io_uring_fasync,
87ce955b 6611 .show_fdinfo = io_uring_show_fdinfo,
2b188cc1
JA
6612};
6613
6614static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
6615 struct io_uring_params *p)
6616{
75b28aff
HV
6617 struct io_rings *rings;
6618 size_t size, sq_array_offset;
2b188cc1 6619
75b28aff
HV
6620 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
6621 if (size == SIZE_MAX)
6622 return -EOVERFLOW;
6623
6624 rings = io_mem_alloc(size);
6625 if (!rings)
2b188cc1
JA
6626 return -ENOMEM;
6627
75b28aff
HV
6628 ctx->rings = rings;
6629 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
6630 rings->sq_ring_mask = p->sq_entries - 1;
6631 rings->cq_ring_mask = p->cq_entries - 1;
6632 rings->sq_ring_entries = p->sq_entries;
6633 rings->cq_ring_entries = p->cq_entries;
6634 ctx->sq_mask = rings->sq_ring_mask;
6635 ctx->cq_mask = rings->cq_ring_mask;
6636 ctx->sq_entries = rings->sq_ring_entries;
6637 ctx->cq_entries = rings->cq_ring_entries;
2b188cc1
JA
6638
6639 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
eb065d30
JA
6640 if (size == SIZE_MAX) {
6641 io_mem_free(ctx->rings);
6642 ctx->rings = NULL;
2b188cc1 6643 return -EOVERFLOW;
eb065d30 6644 }
2b188cc1
JA
6645
6646 ctx->sq_sqes = io_mem_alloc(size);
eb065d30
JA
6647 if (!ctx->sq_sqes) {
6648 io_mem_free(ctx->rings);
6649 ctx->rings = NULL;
2b188cc1 6650 return -ENOMEM;
eb065d30 6651 }
2b188cc1 6652
2b188cc1
JA
6653 return 0;
6654}
6655
6656/*
6657 * Allocate an anonymous fd, this is what constitutes the application
6658 * visible backing of an io_uring instance. The application mmaps this
6659 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
6660 * we have to tie this fd to a socket for file garbage collection purposes.
6661 */
6662static int io_uring_get_fd(struct io_ring_ctx *ctx)
6663{
6664 struct file *file;
6665 int ret;
6666
6667#if defined(CONFIG_UNIX)
6668 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
6669 &ctx->ring_sock);
6670 if (ret)
6671 return ret;
6672#endif
6673
6674 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
6675 if (ret < 0)
6676 goto err;
6677
6678 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
6679 O_RDWR | O_CLOEXEC);
6680 if (IS_ERR(file)) {
6681 put_unused_fd(ret);
6682 ret = PTR_ERR(file);
6683 goto err;
6684 }
6685
6686#if defined(CONFIG_UNIX)
6687 ctx->ring_sock->file = file;
6688#endif
6689 fd_install(ret, file);
6690 return ret;
6691err:
6692#if defined(CONFIG_UNIX)
6693 sock_release(ctx->ring_sock);
6694 ctx->ring_sock = NULL;
6695#endif
6696 return ret;
6697}
6698
6699static int io_uring_create(unsigned entries, struct io_uring_params *p)
6700{
6701 struct user_struct *user = NULL;
6702 struct io_ring_ctx *ctx;
6703 bool account_mem;
6704 int ret;
6705
8110c1a6 6706 if (!entries)
2b188cc1 6707 return -EINVAL;
8110c1a6
JA
6708 if (entries > IORING_MAX_ENTRIES) {
6709 if (!(p->flags & IORING_SETUP_CLAMP))
6710 return -EINVAL;
6711 entries = IORING_MAX_ENTRIES;
6712 }
2b188cc1
JA
6713
6714 /*
6715 * Use twice as many entries for the CQ ring. It's possible for the
6716 * application to drive a higher depth than the size of the SQ ring,
6717 * since the sqes are only used at submission time. This allows for
33a107f0
JA
6718 * some flexibility in overcommitting a bit. If the application has
6719 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
6720 * of CQ ring entries manually.
2b188cc1
JA
6721 */
6722 p->sq_entries = roundup_pow_of_two(entries);
33a107f0
JA
6723 if (p->flags & IORING_SETUP_CQSIZE) {
6724 /*
6725 * If IORING_SETUP_CQSIZE is set, we do the same roundup
6726 * to a power-of-two, if it isn't already. We do NOT impose
6727 * any cq vs sq ring sizing.
6728 */
8110c1a6 6729 if (p->cq_entries < p->sq_entries)
33a107f0 6730 return -EINVAL;
8110c1a6
JA
6731 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
6732 if (!(p->flags & IORING_SETUP_CLAMP))
6733 return -EINVAL;
6734 p->cq_entries = IORING_MAX_CQ_ENTRIES;
6735 }
33a107f0
JA
6736 p->cq_entries = roundup_pow_of_two(p->cq_entries);
6737 } else {
6738 p->cq_entries = 2 * p->sq_entries;
6739 }
2b188cc1
JA
6740
6741 user = get_uid(current_user());
6742 account_mem = !capable(CAP_IPC_LOCK);
6743
6744 if (account_mem) {
6745 ret = io_account_mem(user,
6746 ring_pages(p->sq_entries, p->cq_entries));
6747 if (ret) {
6748 free_uid(user);
6749 return ret;
6750 }
6751 }
6752
6753 ctx = io_ring_ctx_alloc(p);
6754 if (!ctx) {
6755 if (account_mem)
6756 io_unaccount_mem(user, ring_pages(p->sq_entries,
6757 p->cq_entries));
6758 free_uid(user);
6759 return -ENOMEM;
6760 }
6761 ctx->compat = in_compat_syscall();
6762 ctx->account_mem = account_mem;
6763 ctx->user = user;
0b8c0ec7 6764 ctx->creds = get_current_cred();
2b188cc1
JA
6765
6766 ret = io_allocate_scq_urings(ctx, p);
6767 if (ret)
6768 goto err;
6769
6c271ce2 6770 ret = io_sq_offload_start(ctx, p);
2b188cc1
JA
6771 if (ret)
6772 goto err;
6773
2b188cc1 6774 memset(&p->sq_off, 0, sizeof(p->sq_off));
75b28aff
HV
6775 p->sq_off.head = offsetof(struct io_rings, sq.head);
6776 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
6777 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
6778 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
6779 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
6780 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
6781 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
2b188cc1
JA
6782
6783 memset(&p->cq_off, 0, sizeof(p->cq_off));
75b28aff
HV
6784 p->cq_off.head = offsetof(struct io_rings, cq.head);
6785 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
6786 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
6787 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
6788 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
6789 p->cq_off.cqes = offsetof(struct io_rings, cqes);
ac90f249 6790
044c1ab3
JA
6791 /*
6792 * Install ring fd as the very last thing, so we don't risk someone
6793 * having closed it before we finish setup
6794 */
6795 ret = io_uring_get_fd(ctx);
6796 if (ret < 0)
6797 goto err;
6798
da8c9690 6799 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
cccf0ee8
JA
6800 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
6801 IORING_FEAT_CUR_PERSONALITY;
c826bd7a 6802 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
2b188cc1
JA
6803 return ret;
6804err:
6805 io_ring_ctx_wait_and_kill(ctx);
6806 return ret;
6807}
6808
6809/*
6810 * Sets up an aio uring context, and returns the fd. Applications asks for a
6811 * ring size, we return the actual sq/cq ring sizes (among other things) in the
6812 * params structure passed in.
6813 */
6814static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
6815{
6816 struct io_uring_params p;
6817 long ret;
6818 int i;
6819
6820 if (copy_from_user(&p, params, sizeof(p)))
6821 return -EFAULT;
6822 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
6823 if (p.resv[i])
6824 return -EINVAL;
6825 }
6826
6c271ce2 6827 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
8110c1a6 6828 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
24369c2e 6829 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ))
2b188cc1
JA
6830 return -EINVAL;
6831
6832 ret = io_uring_create(entries, &p);
6833 if (ret < 0)
6834 return ret;
6835
6836 if (copy_to_user(params, &p, sizeof(p)))
6837 return -EFAULT;
6838
6839 return ret;
6840}
6841
6842SYSCALL_DEFINE2(io_uring_setup, u32, entries,
6843 struct io_uring_params __user *, params)
6844{
6845 return io_uring_setup(entries, params);
6846}
6847
66f4af93
JA
6848static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
6849{
6850 struct io_uring_probe *p;
6851 size_t size;
6852 int i, ret;
6853
6854 size = struct_size(p, ops, nr_args);
6855 if (size == SIZE_MAX)
6856 return -EOVERFLOW;
6857 p = kzalloc(size, GFP_KERNEL);
6858 if (!p)
6859 return -ENOMEM;
6860
6861 ret = -EFAULT;
6862 if (copy_from_user(p, arg, size))
6863 goto out;
6864 ret = -EINVAL;
6865 if (memchr_inv(p, 0, size))
6866 goto out;
6867
6868 p->last_op = IORING_OP_LAST - 1;
6869 if (nr_args > IORING_OP_LAST)
6870 nr_args = IORING_OP_LAST;
6871
6872 for (i = 0; i < nr_args; i++) {
6873 p->ops[i].op = i;
6874 if (!io_op_defs[i].not_supported)
6875 p->ops[i].flags = IO_URING_OP_SUPPORTED;
6876 }
6877 p->ops_len = i;
6878
6879 ret = 0;
6880 if (copy_to_user(arg, p, size))
6881 ret = -EFAULT;
6882out:
6883 kfree(p);
6884 return ret;
6885}
6886
071698e1
JA
6887static int io_register_personality(struct io_ring_ctx *ctx)
6888{
6889 const struct cred *creds = get_current_cred();
6890 int id;
6891
6892 id = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
6893 USHRT_MAX, GFP_KERNEL);
6894 if (id < 0)
6895 put_cred(creds);
6896 return id;
6897}
6898
6899static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
6900{
6901 const struct cred *old_creds;
6902
6903 old_creds = idr_remove(&ctx->personality_idr, id);
6904 if (old_creds) {
6905 put_cred(old_creds);
6906 return 0;
6907 }
6908
6909 return -EINVAL;
6910}
6911
6912static bool io_register_op_must_quiesce(int op)
6913{
6914 switch (op) {
6915 case IORING_UNREGISTER_FILES:
6916 case IORING_REGISTER_FILES_UPDATE:
6917 case IORING_REGISTER_PROBE:
6918 case IORING_REGISTER_PERSONALITY:
6919 case IORING_UNREGISTER_PERSONALITY:
6920 return false;
6921 default:
6922 return true;
6923 }
6924}
6925
edafccee
JA
6926static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
6927 void __user *arg, unsigned nr_args)
b19062a5
JA
6928 __releases(ctx->uring_lock)
6929 __acquires(ctx->uring_lock)
edafccee
JA
6930{
6931 int ret;
6932
35fa71a0
JA
6933 /*
6934 * We're inside the ring mutex, if the ref is already dying, then
6935 * someone else killed the ctx or is already going through
6936 * io_uring_register().
6937 */
6938 if (percpu_ref_is_dying(&ctx->refs))
6939 return -ENXIO;
6940
071698e1 6941 if (io_register_op_must_quiesce(opcode)) {
05f3fb3c 6942 percpu_ref_kill(&ctx->refs);
b19062a5 6943
05f3fb3c
JA
6944 /*
6945 * Drop uring mutex before waiting for references to exit. If
6946 * another thread is currently inside io_uring_enter() it might
6947 * need to grab the uring_lock to make progress. If we hold it
6948 * here across the drain wait, then we can deadlock. It's safe
6949 * to drop the mutex here, since no new references will come in
6950 * after we've killed the percpu ref.
6951 */
6952 mutex_unlock(&ctx->uring_lock);
c150368b 6953 ret = wait_for_completion_interruptible(&ctx->completions[0]);
05f3fb3c 6954 mutex_lock(&ctx->uring_lock);
c150368b
JA
6955 if (ret) {
6956 percpu_ref_resurrect(&ctx->refs);
6957 ret = -EINTR;
6958 goto out;
6959 }
05f3fb3c 6960 }
edafccee
JA
6961
6962 switch (opcode) {
6963 case IORING_REGISTER_BUFFERS:
6964 ret = io_sqe_buffer_register(ctx, arg, nr_args);
6965 break;
6966 case IORING_UNREGISTER_BUFFERS:
6967 ret = -EINVAL;
6968 if (arg || nr_args)
6969 break;
6970 ret = io_sqe_buffer_unregister(ctx);
6971 break;
6b06314c
JA
6972 case IORING_REGISTER_FILES:
6973 ret = io_sqe_files_register(ctx, arg, nr_args);
6974 break;
6975 case IORING_UNREGISTER_FILES:
6976 ret = -EINVAL;
6977 if (arg || nr_args)
6978 break;
6979 ret = io_sqe_files_unregister(ctx);
6980 break;
c3a31e60
JA
6981 case IORING_REGISTER_FILES_UPDATE:
6982 ret = io_sqe_files_update(ctx, arg, nr_args);
6983 break;
9b402849 6984 case IORING_REGISTER_EVENTFD:
f2842ab5 6985 case IORING_REGISTER_EVENTFD_ASYNC:
9b402849
JA
6986 ret = -EINVAL;
6987 if (nr_args != 1)
6988 break;
6989 ret = io_eventfd_register(ctx, arg);
f2842ab5
JA
6990 if (ret)
6991 break;
6992 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
6993 ctx->eventfd_async = 1;
6994 else
6995 ctx->eventfd_async = 0;
9b402849
JA
6996 break;
6997 case IORING_UNREGISTER_EVENTFD:
6998 ret = -EINVAL;
6999 if (arg || nr_args)
7000 break;
7001 ret = io_eventfd_unregister(ctx);
7002 break;
66f4af93
JA
7003 case IORING_REGISTER_PROBE:
7004 ret = -EINVAL;
7005 if (!arg || nr_args > 256)
7006 break;
7007 ret = io_probe(ctx, arg, nr_args);
7008 break;
071698e1
JA
7009 case IORING_REGISTER_PERSONALITY:
7010 ret = -EINVAL;
7011 if (arg || nr_args)
7012 break;
7013 ret = io_register_personality(ctx);
7014 break;
7015 case IORING_UNREGISTER_PERSONALITY:
7016 ret = -EINVAL;
7017 if (arg)
7018 break;
7019 ret = io_unregister_personality(ctx, nr_args);
7020 break;
edafccee
JA
7021 default:
7022 ret = -EINVAL;
7023 break;
7024 }
7025
071698e1 7026 if (io_register_op_must_quiesce(opcode)) {
05f3fb3c 7027 /* bring the ctx back to life */
05f3fb3c 7028 percpu_ref_reinit(&ctx->refs);
c150368b
JA
7029out:
7030 reinit_completion(&ctx->completions[0]);
05f3fb3c 7031 }
edafccee
JA
7032 return ret;
7033}
7034
7035SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
7036 void __user *, arg, unsigned int, nr_args)
7037{
7038 struct io_ring_ctx *ctx;
7039 long ret = -EBADF;
7040 struct fd f;
7041
7042 f = fdget(fd);
7043 if (!f.file)
7044 return -EBADF;
7045
7046 ret = -EOPNOTSUPP;
7047 if (f.file->f_op != &io_uring_fops)
7048 goto out_fput;
7049
7050 ctx = f.file->private_data;
7051
7052 mutex_lock(&ctx->uring_lock);
7053 ret = __io_uring_register(ctx, opcode, arg, nr_args);
7054 mutex_unlock(&ctx->uring_lock);
c826bd7a
DD
7055 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
7056 ctx->cq_ev_fd != NULL, ret);
edafccee
JA
7057out_fput:
7058 fdput(f);
7059 return ret;
7060}
7061
2b188cc1
JA
7062static int __init io_uring_init(void)
7063{
d7f62e82
SM
7064#define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
7065 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
7066 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
7067} while (0)
7068
7069#define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
7070 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
7071 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
7072 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
7073 BUILD_BUG_SQE_ELEM(1, __u8, flags);
7074 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
7075 BUILD_BUG_SQE_ELEM(4, __s32, fd);
7076 BUILD_BUG_SQE_ELEM(8, __u64, off);
7077 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
7078 BUILD_BUG_SQE_ELEM(16, __u64, addr);
7079 BUILD_BUG_SQE_ELEM(24, __u32, len);
7080 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
7081 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
7082 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
7083 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
7084 BUILD_BUG_SQE_ELEM(28, __u16, poll_events);
7085 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
7086 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
7087 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
7088 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
7089 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
7090 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
7091 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
7092 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
7093 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
7094 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
7095 BUILD_BUG_SQE_ELEM(42, __u16, personality);
7096
d3656344 7097 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
2b188cc1
JA
7098 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
7099 return 0;
7100};
7101__initcall(io_uring_init);