]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - fs/io_uring.c
io_uring: mark io_uring_fops/io_op_defs as __read_mostly
[mirror_ubuntu-jammy-kernel.git] / fs / io_uring.c
CommitLineData
2b188cc1
JA
1// SPDX-License-Identifier: GPL-2.0
2/*
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
5 *
6 * A note on the read/write ordering memory barriers that are matched between
1e84b97b
SB
7 * the application and kernel side.
8 *
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqring (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
16 * CQ entries.
17 *
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
23 * head will do).
24 *
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
28 * between.
2b188cc1
JA
29 *
30 * Also see the examples in the liburing library:
31 *
32 * git://git.kernel.dk/liburing
33 *
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
38 *
39 * Copyright (C) 2018-2019 Jens Axboe
c992fe29 40 * Copyright (c) 2018-2019 Christoph Hellwig
2b188cc1
JA
41 */
42#include <linux/kernel.h>
43#include <linux/init.h>
44#include <linux/errno.h>
45#include <linux/syscalls.h>
46#include <linux/compat.h>
52de1fe1 47#include <net/compat.h>
2b188cc1
JA
48#include <linux/refcount.h>
49#include <linux/uio.h>
6b47ee6e 50#include <linux/bits.h>
2b188cc1
JA
51
52#include <linux/sched/signal.h>
53#include <linux/fs.h>
54#include <linux/file.h>
55#include <linux/fdtable.h>
56#include <linux/mm.h>
57#include <linux/mman.h>
2b188cc1
JA
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>
ff002b30 78#include <linux/fs_struct.h>
7d67af2c 79#include <linux/splice.h>
b41e9852 80#include <linux/task_work.h>
bcf5a063 81#include <linux/pagemap.h>
0f212204 82#include <linux/io_uring.h>
2b188cc1 83
c826bd7a
DD
84#define CREATE_TRACE_POINTS
85#include <trace/events/io_uring.h>
86
2b188cc1
JA
87#include <uapi/linux/io_uring.h>
88
89#include "internal.h"
561fb04a 90#include "io-wq.h"
2b188cc1 91
5277deaa 92#define IORING_MAX_ENTRIES 32768
33a107f0 93#define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
65e19f54
JA
94
95/*
96 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
97 */
98#define IORING_FILE_TABLE_SHIFT 9
99#define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
100#define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
101#define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
21b55dbc
SG
102#define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
103 IORING_REGISTER_LAST + IORING_OP_LAST)
2b188cc1
JA
104
105struct io_uring {
106 u32 head ____cacheline_aligned_in_smp;
107 u32 tail ____cacheline_aligned_in_smp;
108};
109
1e84b97b 110/*
75b28aff
HV
111 * This data is shared with the application through the mmap at offsets
112 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
1e84b97b
SB
113 *
114 * The offsets to the member fields are published through struct
115 * io_sqring_offsets when calling io_uring_setup.
116 */
75b28aff 117struct io_rings {
1e84b97b
SB
118 /*
119 * Head and tail offsets into the ring; the offsets need to be
120 * masked to get valid indices.
121 *
75b28aff
HV
122 * The kernel controls head of the sq ring and the tail of the cq ring,
123 * and the application controls tail of the sq ring and the head of the
124 * cq ring.
1e84b97b 125 */
75b28aff 126 struct io_uring sq, cq;
1e84b97b 127 /*
75b28aff 128 * Bitmasks to apply to head and tail offsets (constant, equals
1e84b97b
SB
129 * ring_entries - 1)
130 */
75b28aff
HV
131 u32 sq_ring_mask, cq_ring_mask;
132 /* Ring sizes (constant, power of 2) */
133 u32 sq_ring_entries, cq_ring_entries;
1e84b97b
SB
134 /*
135 * Number of invalid entries dropped by the kernel due to
136 * invalid index stored in array
137 *
138 * Written by the kernel, shouldn't be modified by the
139 * application (i.e. get number of "new events" by comparing to
140 * cached value).
141 *
142 * After a new SQ head value was read by the application this
143 * counter includes all submissions that were dropped reaching
144 * the new SQ head (and possibly more).
145 */
75b28aff 146 u32 sq_dropped;
1e84b97b 147 /*
0d9b5b3a 148 * Runtime SQ flags
1e84b97b
SB
149 *
150 * Written by the kernel, shouldn't be modified by the
151 * application.
152 *
153 * The application needs a full memory barrier before checking
154 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
155 */
75b28aff 156 u32 sq_flags;
0d9b5b3a
SG
157 /*
158 * Runtime CQ flags
159 *
160 * Written by the application, shouldn't be modified by the
161 * kernel.
162 */
163 u32 cq_flags;
1e84b97b
SB
164 /*
165 * Number of completion events lost because the queue was full;
166 * this should be avoided by the application by making sure
0b4295b5 167 * there are not more requests pending than there is space in
1e84b97b
SB
168 * the completion queue.
169 *
170 * Written by the kernel, shouldn't be modified by the
171 * application (i.e. get number of "new events" by comparing to
172 * cached value).
173 *
174 * As completion events come in out of order this counter is not
175 * ordered with any other data.
176 */
75b28aff 177 u32 cq_overflow;
1e84b97b
SB
178 /*
179 * Ring buffer of completion events.
180 *
181 * The kernel writes completion events fresh every time they are
182 * produced, so the application is allowed to modify pending
183 * entries.
184 */
75b28aff 185 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
2b188cc1
JA
186};
187
edafccee
JA
188struct io_mapped_ubuf {
189 u64 ubuf;
190 size_t len;
191 struct bio_vec *bvec;
192 unsigned int nr_bvecs;
193};
194
65e19f54
JA
195struct fixed_file_table {
196 struct file **files;
31b51510
JA
197};
198
05589553
XW
199struct fixed_file_ref_node {
200 struct percpu_ref refs;
201 struct list_head node;
202 struct list_head file_list;
203 struct fixed_file_data *file_data;
4a38aed2 204 struct llist_node llist;
05589553
XW
205};
206
05f3fb3c
JA
207struct fixed_file_data {
208 struct fixed_file_table *table;
209 struct io_ring_ctx *ctx;
210
05589553 211 struct percpu_ref *cur_refs;
05f3fb3c 212 struct percpu_ref refs;
05f3fb3c 213 struct completion done;
05589553
XW
214 struct list_head ref_list;
215 spinlock_t lock;
05f3fb3c
JA
216};
217
5a2e745d
JA
218struct io_buffer {
219 struct list_head list;
220 __u64 addr;
221 __s32 len;
222 __u16 bid;
223};
224
21b55dbc
SG
225struct io_restriction {
226 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
227 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
228 u8 sqe_flags_allowed;
229 u8 sqe_flags_required;
7e84e1c7 230 bool registered;
21b55dbc
SG
231};
232
534ca6d6
JA
233struct io_sq_data {
234 refcount_t refs;
69fb2131
JA
235 struct mutex lock;
236
237 /* ctx's that are using this sqd */
238 struct list_head ctx_list;
239 struct list_head ctx_new_list;
240 struct mutex ctx_lock;
241
534ca6d6
JA
242 struct task_struct *thread;
243 struct wait_queue_head wait;
244};
245
2b188cc1
JA
246struct io_ring_ctx {
247 struct {
248 struct percpu_ref refs;
249 } ____cacheline_aligned_in_smp;
250
251 struct {
252 unsigned int flags;
e1d85334 253 unsigned int compat: 1;
aad5d8da 254 unsigned int limit_mem: 1;
e1d85334
RD
255 unsigned int cq_overflow_flushed: 1;
256 unsigned int drain_next: 1;
257 unsigned int eventfd_async: 1;
21b55dbc 258 unsigned int restricted: 1;
2b188cc1 259
75b28aff
HV
260 /*
261 * Ring buffer of indices into array of io_uring_sqe, which is
262 * mmapped by the application using the IORING_OFF_SQES offset.
263 *
264 * This indirection could e.g. be used to assign fixed
265 * io_uring_sqe entries to operations and only submit them to
266 * the queue when needed.
267 *
268 * The kernel modifies neither the indices array nor the entries
269 * array.
270 */
271 u32 *sq_array;
2b188cc1
JA
272 unsigned cached_sq_head;
273 unsigned sq_entries;
274 unsigned sq_mask;
6c271ce2 275 unsigned sq_thread_idle;
498ccd9e 276 unsigned cached_sq_dropped;
206aefde 277 atomic_t cached_cq_overflow;
ad3eb2c8 278 unsigned long sq_check_overflow;
de0617e4
JA
279
280 struct list_head defer_list;
5262f567 281 struct list_head timeout_list;
1d7bb1d5 282 struct list_head cq_overflow_list;
fcb323cc
JA
283
284 wait_queue_head_t inflight_wait;
ad3eb2c8 285 struct io_uring_sqe *sq_sqes;
2b188cc1
JA
286 } ____cacheline_aligned_in_smp;
287
206aefde
JA
288 struct io_rings *rings;
289
2b188cc1 290 /* IO offload */
561fb04a 291 struct io_wq *io_wq;
2aede0e4
JA
292
293 /*
294 * For SQPOLL usage - we hold a reference to the parent task, so we
295 * have access to the ->files
296 */
297 struct task_struct *sqo_task;
298
299 /* Only used for accounting purposes */
300 struct mm_struct *mm_account;
301
534ca6d6
JA
302 struct io_sq_data *sq_data; /* if using sq thread polling */
303
6a779382 304 struct wait_queue_entry sqo_wait_entry;
69fb2131 305 struct list_head sqd_list;
75b28aff 306
6b06314c
JA
307 /*
308 * If used, fixed file set. Writers must ensure that ->refs is dead,
309 * readers must ensure that ->refs is alive as long as the file* is
310 * used. Only updated through io_uring_register(2).
311 */
05f3fb3c 312 struct fixed_file_data *file_data;
6b06314c
JA
313 unsigned nr_user_files;
314
edafccee
JA
315 /* if used, fixed mapped user buffers */
316 unsigned nr_user_bufs;
317 struct io_mapped_ubuf *user_bufs;
318
2b188cc1
JA
319 struct user_struct *user;
320
0b8c0ec7 321 const struct cred *creds;
181e448d 322
0f158b4c
JA
323 struct completion ref_comp;
324 struct completion sq_thread_comp;
206aefde 325
0ddf92e8
JA
326 /* if all else fails... */
327 struct io_kiocb *fallback_req;
328
206aefde
JA
329#if defined(CONFIG_UNIX)
330 struct socket *ring_sock;
331#endif
332
5a2e745d
JA
333 struct idr io_buffer_idr;
334
071698e1
JA
335 struct idr personality_idr;
336
206aefde
JA
337 struct {
338 unsigned cached_cq_tail;
339 unsigned cq_entries;
340 unsigned cq_mask;
341 atomic_t cq_timeouts;
ad3eb2c8 342 unsigned long cq_check_overflow;
206aefde
JA
343 struct wait_queue_head cq_wait;
344 struct fasync_struct *cq_fasync;
345 struct eventfd_ctx *cq_ev_fd;
346 } ____cacheline_aligned_in_smp;
2b188cc1
JA
347
348 struct {
349 struct mutex uring_lock;
350 wait_queue_head_t wait;
351 } ____cacheline_aligned_in_smp;
352
353 struct {
354 spinlock_t completion_lock;
e94f141b 355
def596e9 356 /*
540e32a0 357 * ->iopoll_list is protected by the ctx->uring_lock for
def596e9
JA
358 * io_uring instances that don't use IORING_SETUP_SQPOLL.
359 * For SQPOLL, only the single threaded io_sq_thread() will
360 * manipulate the list, hence no extra locking is needed there.
361 */
540e32a0 362 struct list_head iopoll_list;
78076bb6
JA
363 struct hlist_head *cancel_hash;
364 unsigned cancel_hash_bits;
e94f141b 365 bool poll_multi_file;
31b51510 366
fcb323cc
JA
367 spinlock_t inflight_lock;
368 struct list_head inflight_list;
2b188cc1 369 } ____cacheline_aligned_in_smp;
85faa7b8 370
4a38aed2
JA
371 struct delayed_work file_put_work;
372 struct llist_head file_put_llist;
373
85faa7b8 374 struct work_struct exit_work;
21b55dbc 375 struct io_restriction restrictions;
2b188cc1
JA
376};
377
09bb8394
JA
378/*
379 * First field must be the file pointer in all the
380 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
381 */
221c5eb2
JA
382struct io_poll_iocb {
383 struct file *file;
0969e783
JA
384 union {
385 struct wait_queue_head *head;
386 u64 addr;
387 };
221c5eb2 388 __poll_t events;
8c838788 389 bool done;
221c5eb2 390 bool canceled;
392edb45 391 struct wait_queue_entry wait;
221c5eb2
JA
392};
393
b5dba59e
JA
394struct io_close {
395 struct file *file;
396 struct file *put_file;
397 int fd;
398};
399
ad8a48ac
JA
400struct io_timeout_data {
401 struct io_kiocb *req;
402 struct hrtimer timer;
403 struct timespec64 ts;
404 enum hrtimer_mode mode;
405};
406
8ed8d3c3
JA
407struct io_accept {
408 struct file *file;
409 struct sockaddr __user *addr;
410 int __user *addr_len;
411 int flags;
09952e3e 412 unsigned long nofile;
8ed8d3c3
JA
413};
414
415struct io_sync {
416 struct file *file;
417 loff_t len;
418 loff_t off;
419 int flags;
d63d1b5e 420 int mode;
8ed8d3c3
JA
421};
422
fbf23849
JA
423struct io_cancel {
424 struct file *file;
425 u64 addr;
426};
427
b29472ee
JA
428struct io_timeout {
429 struct file *file;
430 u64 addr;
431 int flags;
bfe68a22
PB
432 u32 off;
433 u32 target_seq;
135fcde8 434 struct list_head list;
b29472ee
JA
435};
436
9adbd45d
JA
437struct io_rw {
438 /* NOTE: kiocb has the file as the first member, so don't do it here */
439 struct kiocb kiocb;
440 u64 addr;
441 u64 len;
442};
443
3fbb51c1
JA
444struct io_connect {
445 struct file *file;
446 struct sockaddr __user *addr;
447 int addr_len;
448};
449
e47293fd
JA
450struct io_sr_msg {
451 struct file *file;
fddaface 452 union {
270a5940 453 struct user_msghdr __user *umsg;
fddaface
JA
454 void __user *buf;
455 };
e47293fd 456 int msg_flags;
bcda7baa 457 int bgid;
fddaface 458 size_t len;
bcda7baa 459 struct io_buffer *kbuf;
e47293fd
JA
460};
461
15b71abe
JA
462struct io_open {
463 struct file *file;
464 int dfd;
15b71abe 465 struct filename *filename;
c12cedf2 466 struct open_how how;
4022e7af 467 unsigned long nofile;
15b71abe
JA
468};
469
05f3fb3c
JA
470struct io_files_update {
471 struct file *file;
472 u64 arg;
473 u32 nr_args;
474 u32 offset;
475};
476
4840e418
JA
477struct io_fadvise {
478 struct file *file;
479 u64 offset;
480 u32 len;
481 u32 advice;
482};
483
c1ca757b
JA
484struct io_madvise {
485 struct file *file;
486 u64 addr;
487 u32 len;
488 u32 advice;
489};
490
3e4827b0
JA
491struct io_epoll {
492 struct file *file;
493 int epfd;
494 int op;
495 int fd;
496 struct epoll_event event;
e47293fd
JA
497};
498
7d67af2c
PB
499struct io_splice {
500 struct file *file_out;
501 struct file *file_in;
502 loff_t off_out;
503 loff_t off_in;
504 u64 len;
505 unsigned int flags;
506};
507
ddf0322d
JA
508struct io_provide_buf {
509 struct file *file;
510 __u64 addr;
511 __s32 len;
512 __u32 bgid;
513 __u16 nbufs;
514 __u16 bid;
515};
516
1d9e1288
BM
517struct io_statx {
518 struct file *file;
519 int dfd;
520 unsigned int mask;
521 unsigned int flags;
e62753e4 522 const char __user *filename;
1d9e1288
BM
523 struct statx __user *buffer;
524};
525
3ca405eb
PB
526struct io_completion {
527 struct file *file;
528 struct list_head list;
0f7e466b 529 int cflags;
3ca405eb
PB
530};
531
f499a021
JA
532struct io_async_connect {
533 struct sockaddr_storage address;
534};
535
03b1230c
JA
536struct io_async_msghdr {
537 struct iovec fast_iov[UIO_FASTIOV];
538 struct iovec *iov;
539 struct sockaddr __user *uaddr;
540 struct msghdr msg;
b537916c 541 struct sockaddr_storage addr;
03b1230c
JA
542};
543
f67676d1
JA
544struct io_async_rw {
545 struct iovec fast_iov[UIO_FASTIOV];
ff6165b2
JA
546 const struct iovec *free_iovec;
547 struct iov_iter iter;
227c0c96 548 size_t bytes_done;
bcf5a063 549 struct wait_page_queue wpq;
f67676d1
JA
550};
551
1a6b74fc 552struct io_async_ctx {
f67676d1
JA
553 union {
554 struct io_async_rw rw;
03b1230c 555 struct io_async_msghdr msg;
f499a021 556 struct io_async_connect connect;
2d28390a 557 struct io_timeout_data timeout;
f67676d1 558 };
1a6b74fc
JA
559};
560
6b47ee6e
PB
561enum {
562 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
563 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
564 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
565 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
566 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
bcda7baa 567 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
6b47ee6e 568
dea3b49c 569 REQ_F_LINK_HEAD_BIT,
6b47ee6e
PB
570 REQ_F_FAIL_LINK_BIT,
571 REQ_F_INFLIGHT_BIT,
572 REQ_F_CUR_POS_BIT,
573 REQ_F_NOWAIT_BIT,
6b47ee6e 574 REQ_F_LINK_TIMEOUT_BIT,
6b47ee6e 575 REQ_F_ISREG_BIT,
6b47ee6e 576 REQ_F_COMP_LOCKED_BIT,
99bc4c38 577 REQ_F_NEED_CLEANUP_BIT,
d7718a9d 578 REQ_F_POLLED_BIT,
bcda7baa 579 REQ_F_BUFFER_SELECTED_BIT,
5b0bbee4 580 REQ_F_NO_FILE_TABLE_BIT,
7cdaf587 581 REQ_F_WORK_INITIALIZED_BIT,
84557871
JA
582
583 /* not a real bit, just to check we're not overflowing the space */
584 __REQ_F_LAST_BIT,
6b47ee6e
PB
585};
586
587enum {
588 /* ctx owns file */
589 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
590 /* drain existing IO first */
591 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
592 /* linked sqes */
593 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
594 /* doesn't sever on completion < 0 */
595 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
596 /* IOSQE_ASYNC */
597 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
bcda7baa
JA
598 /* IOSQE_BUFFER_SELECT */
599 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
6b47ee6e 600
dea3b49c
PB
601 /* head of a link */
602 REQ_F_LINK_HEAD = BIT(REQ_F_LINK_HEAD_BIT),
6b47ee6e
PB
603 /* fail rest of links */
604 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
605 /* on inflight list */
606 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
607 /* read/write uses file position */
608 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
609 /* must not punt to workers */
610 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
6b47ee6e
PB
611 /* has linked timeout */
612 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
6b47ee6e
PB
613 /* regular file */
614 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
6b47ee6e
PB
615 /* completion under lock */
616 REQ_F_COMP_LOCKED = BIT(REQ_F_COMP_LOCKED_BIT),
99bc4c38
PB
617 /* needs cleanup */
618 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
d7718a9d
JA
619 /* already went through poll handler */
620 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
bcda7baa
JA
621 /* buffer already selected */
622 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
5b0bbee4
JA
623 /* doesn't need file table for this request */
624 REQ_F_NO_FILE_TABLE = BIT(REQ_F_NO_FILE_TABLE_BIT),
7cdaf587
XW
625 /* io_wq_work is initialized */
626 REQ_F_WORK_INITIALIZED = BIT(REQ_F_WORK_INITIALIZED_BIT),
d7718a9d
JA
627};
628
629struct async_poll {
630 struct io_poll_iocb poll;
807abcb0 631 struct io_poll_iocb *double_poll;
6b47ee6e
PB
632};
633
09bb8394
JA
634/*
635 * NOTE! Each of the iocb union members has the file pointer
636 * as the first entry in their struct definition. So you can
637 * access the file pointer through any of the sub-structs,
638 * or directly as just 'ki_filp' in this struct.
639 */
2b188cc1 640struct io_kiocb {
221c5eb2 641 union {
09bb8394 642 struct file *file;
9adbd45d 643 struct io_rw rw;
221c5eb2 644 struct io_poll_iocb poll;
8ed8d3c3
JA
645 struct io_accept accept;
646 struct io_sync sync;
fbf23849 647 struct io_cancel cancel;
b29472ee 648 struct io_timeout timeout;
3fbb51c1 649 struct io_connect connect;
e47293fd 650 struct io_sr_msg sr_msg;
15b71abe 651 struct io_open open;
b5dba59e 652 struct io_close close;
05f3fb3c 653 struct io_files_update files_update;
4840e418 654 struct io_fadvise fadvise;
c1ca757b 655 struct io_madvise madvise;
3e4827b0 656 struct io_epoll epoll;
7d67af2c 657 struct io_splice splice;
ddf0322d 658 struct io_provide_buf pbuf;
1d9e1288 659 struct io_statx statx;
3ca405eb
PB
660 /* use only after cleaning per-op data, see io_clean_op() */
661 struct io_completion compl;
221c5eb2 662 };
2b188cc1 663
1a6b74fc 664 struct io_async_ctx *io;
d625c6ee 665 u8 opcode;
65a6543d
XW
666 /* polled IO has completed */
667 u8 iopoll_completed;
2b188cc1 668
4f4eeba8 669 u16 buf_index;
9cf7c104 670 u32 result;
4f4eeba8 671
010e8e6b
PB
672 struct io_ring_ctx *ctx;
673 unsigned int flags;
674 refcount_t refs;
675 struct task_struct *task;
676 u64 user_data;
d7718a9d 677
010e8e6b 678 struct list_head link_list;
fcb323cc 679
d21ffe7e
PB
680 /*
681 * 1. used with ctx->iopoll_list with reads/writes
682 * 2. to track reqs with ->files (see io_op_def::file_table)
683 */
010e8e6b
PB
684 struct list_head inflight_entry;
685
686 struct percpu_ref *fixed_file_refs;
687 struct callback_head task_work;
688 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
689 struct hlist_node hash_node;
690 struct async_poll *apoll;
691 struct io_wq_work work;
2b188cc1 692};
05589553 693
27dc8338
PB
694struct io_defer_entry {
695 struct list_head list;
696 struct io_kiocb *req;
9cf7c104 697 u32 seq;
2b188cc1
JA
698};
699
def596e9 700#define IO_IOPOLL_BATCH 8
2b188cc1 701
013538bd
JA
702struct io_comp_state {
703 unsigned int nr;
704 struct list_head list;
705 struct io_ring_ctx *ctx;
706};
707
9a56a232
JA
708struct io_submit_state {
709 struct blk_plug plug;
710
2579f913
JA
711 /*
712 * io_kiocb alloc cache
713 */
714 void *reqs[IO_IOPOLL_BATCH];
6c8a3134 715 unsigned int free_reqs;
2579f913 716
013538bd
JA
717 /*
718 * Batch completion logic
719 */
720 struct io_comp_state comp;
721
9a56a232
JA
722 /*
723 * File reference cache
724 */
725 struct file *file;
726 unsigned int fd;
727 unsigned int has_refs;
9a56a232
JA
728 unsigned int ios_left;
729};
730
d3656344
JA
731struct io_op_def {
732 /* needs req->io allocated for deferral/async */
733 unsigned async_ctx : 1;
734 /* needs current->mm setup, does mm access */
735 unsigned needs_mm : 1;
736 /* needs req->file assigned */
737 unsigned needs_file : 1;
fd2206e4
JA
738 /* don't fail if file grab fails */
739 unsigned needs_file_no_error : 1;
d3656344
JA
740 /* hash wq insertion if file is a regular file */
741 unsigned hash_reg_file : 1;
742 /* unbound wq insertion if file is a non-regular file */
743 unsigned unbound_nonreg_file : 1;
66f4af93
JA
744 /* opcode is not supported by this kernel */
745 unsigned not_supported : 1;
f86cd20c
JA
746 /* needs file table */
747 unsigned file_table : 1;
ff002b30
JA
748 /* needs ->fs */
749 unsigned needs_fs : 1;
8a72758c
JA
750 /* set if opcode supports polled "wait" */
751 unsigned pollin : 1;
752 unsigned pollout : 1;
bcda7baa
JA
753 /* op supports buffer selection */
754 unsigned buffer_select : 1;
57f1a649 755 unsigned needs_fsize : 1;
d3656344
JA
756};
757
738277ad 758static const struct io_op_def io_op_defs[] __read_mostly = {
0463b6c5
PB
759 [IORING_OP_NOP] = {},
760 [IORING_OP_READV] = {
d3656344
JA
761 .async_ctx = 1,
762 .needs_mm = 1,
763 .needs_file = 1,
764 .unbound_nonreg_file = 1,
8a72758c 765 .pollin = 1,
4d954c25 766 .buffer_select = 1,
d3656344 767 },
0463b6c5 768 [IORING_OP_WRITEV] = {
d3656344
JA
769 .async_ctx = 1,
770 .needs_mm = 1,
771 .needs_file = 1,
772 .hash_reg_file = 1,
773 .unbound_nonreg_file = 1,
8a72758c 774 .pollout = 1,
57f1a649 775 .needs_fsize = 1,
d3656344 776 },
0463b6c5 777 [IORING_OP_FSYNC] = {
d3656344
JA
778 .needs_file = 1,
779 },
0463b6c5 780 [IORING_OP_READ_FIXED] = {
d3656344
JA
781 .needs_file = 1,
782 .unbound_nonreg_file = 1,
8a72758c 783 .pollin = 1,
d3656344 784 },
0463b6c5 785 [IORING_OP_WRITE_FIXED] = {
d3656344
JA
786 .needs_file = 1,
787 .hash_reg_file = 1,
788 .unbound_nonreg_file = 1,
8a72758c 789 .pollout = 1,
57f1a649 790 .needs_fsize = 1,
d3656344 791 },
0463b6c5 792 [IORING_OP_POLL_ADD] = {
d3656344
JA
793 .needs_file = 1,
794 .unbound_nonreg_file = 1,
795 },
0463b6c5
PB
796 [IORING_OP_POLL_REMOVE] = {},
797 [IORING_OP_SYNC_FILE_RANGE] = {
d3656344
JA
798 .needs_file = 1,
799 },
0463b6c5 800 [IORING_OP_SENDMSG] = {
d3656344
JA
801 .async_ctx = 1,
802 .needs_mm = 1,
803 .needs_file = 1,
804 .unbound_nonreg_file = 1,
ff002b30 805 .needs_fs = 1,
8a72758c 806 .pollout = 1,
d3656344 807 },
0463b6c5 808 [IORING_OP_RECVMSG] = {
d3656344
JA
809 .async_ctx = 1,
810 .needs_mm = 1,
811 .needs_file = 1,
812 .unbound_nonreg_file = 1,
ff002b30 813 .needs_fs = 1,
8a72758c 814 .pollin = 1,
52de1fe1 815 .buffer_select = 1,
d3656344 816 },
0463b6c5 817 [IORING_OP_TIMEOUT] = {
d3656344
JA
818 .async_ctx = 1,
819 .needs_mm = 1,
820 },
0463b6c5
PB
821 [IORING_OP_TIMEOUT_REMOVE] = {},
822 [IORING_OP_ACCEPT] = {
d3656344
JA
823 .needs_mm = 1,
824 .needs_file = 1,
825 .unbound_nonreg_file = 1,
f86cd20c 826 .file_table = 1,
8a72758c 827 .pollin = 1,
d3656344 828 },
0463b6c5
PB
829 [IORING_OP_ASYNC_CANCEL] = {},
830 [IORING_OP_LINK_TIMEOUT] = {
d3656344
JA
831 .async_ctx = 1,
832 .needs_mm = 1,
833 },
0463b6c5 834 [IORING_OP_CONNECT] = {
d3656344
JA
835 .async_ctx = 1,
836 .needs_mm = 1,
837 .needs_file = 1,
838 .unbound_nonreg_file = 1,
8a72758c 839 .pollout = 1,
d3656344 840 },
0463b6c5 841 [IORING_OP_FALLOCATE] = {
d3656344 842 .needs_file = 1,
57f1a649 843 .needs_fsize = 1,
d3656344 844 },
0463b6c5 845 [IORING_OP_OPENAT] = {
f86cd20c 846 .file_table = 1,
ff002b30 847 .needs_fs = 1,
d3656344 848 },
0463b6c5 849 [IORING_OP_CLOSE] = {
fd2206e4
JA
850 .needs_file = 1,
851 .needs_file_no_error = 1,
f86cd20c 852 .file_table = 1,
d3656344 853 },
0463b6c5 854 [IORING_OP_FILES_UPDATE] = {
d3656344 855 .needs_mm = 1,
f86cd20c 856 .file_table = 1,
d3656344 857 },
0463b6c5 858 [IORING_OP_STATX] = {
d3656344 859 .needs_mm = 1,
ff002b30 860 .needs_fs = 1,
5b0bbee4 861 .file_table = 1,
d3656344 862 },
0463b6c5 863 [IORING_OP_READ] = {
3a6820f2
JA
864 .needs_mm = 1,
865 .needs_file = 1,
866 .unbound_nonreg_file = 1,
8a72758c 867 .pollin = 1,
bcda7baa 868 .buffer_select = 1,
3a6820f2 869 },
0463b6c5 870 [IORING_OP_WRITE] = {
3a6820f2
JA
871 .needs_mm = 1,
872 .needs_file = 1,
873 .unbound_nonreg_file = 1,
8a72758c 874 .pollout = 1,
57f1a649 875 .needs_fsize = 1,
3a6820f2 876 },
0463b6c5 877 [IORING_OP_FADVISE] = {
4840e418
JA
878 .needs_file = 1,
879 },
0463b6c5 880 [IORING_OP_MADVISE] = {
c1ca757b
JA
881 .needs_mm = 1,
882 },
0463b6c5 883 [IORING_OP_SEND] = {
fddaface
JA
884 .needs_mm = 1,
885 .needs_file = 1,
886 .unbound_nonreg_file = 1,
8a72758c 887 .pollout = 1,
fddaface 888 },
0463b6c5 889 [IORING_OP_RECV] = {
fddaface
JA
890 .needs_mm = 1,
891 .needs_file = 1,
892 .unbound_nonreg_file = 1,
8a72758c 893 .pollin = 1,
bcda7baa 894 .buffer_select = 1,
fddaface 895 },
0463b6c5 896 [IORING_OP_OPENAT2] = {
f86cd20c 897 .file_table = 1,
ff002b30 898 .needs_fs = 1,
cebdb986 899 },
3e4827b0
JA
900 [IORING_OP_EPOLL_CTL] = {
901 .unbound_nonreg_file = 1,
902 .file_table = 1,
903 },
7d67af2c
PB
904 [IORING_OP_SPLICE] = {
905 .needs_file = 1,
906 .hash_reg_file = 1,
907 .unbound_nonreg_file = 1,
ddf0322d
JA
908 },
909 [IORING_OP_PROVIDE_BUFFERS] = {},
067524e9 910 [IORING_OP_REMOVE_BUFFERS] = {},
f2a8d5c7
PB
911 [IORING_OP_TEE] = {
912 .needs_file = 1,
913 .hash_reg_file = 1,
914 .unbound_nonreg_file = 1,
915 },
d3656344
JA
916};
917
2e0464d4
BM
918enum io_mem_account {
919 ACCT_LOCKED,
920 ACCT_PINNED,
921};
922
81b68a5c
PB
923static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
924 struct io_comp_state *cs);
78e19bbe 925static void io_cqring_fill_event(struct io_kiocb *req, long res);
ec9c02ad 926static void io_put_req(struct io_kiocb *req);
c40f6379 927static void io_double_put_req(struct io_kiocb *req);
978db57e 928static void __io_double_put_req(struct io_kiocb *req);
94ae5e77 929static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
7271ef3a 930static void __io_queue_linked_timeout(struct io_kiocb *req);
94ae5e77 931static void io_queue_linked_timeout(struct io_kiocb *req);
05f3fb3c
JA
932static int __io_sqe_files_update(struct io_ring_ctx *ctx,
933 struct io_uring_files_update *ip,
934 unsigned nr_args);
f56040b8 935static int io_prep_work_files(struct io_kiocb *req);
3ca405eb 936static void __io_clean_op(struct io_kiocb *req);
b41e9852
JA
937static int io_file_get(struct io_submit_state *state, struct io_kiocb *req,
938 int fd, struct file **out_file, bool fixed);
939static void __io_queue_sqe(struct io_kiocb *req,
f13fad7b
JA
940 const struct io_uring_sqe *sqe,
941 struct io_comp_state *cs);
4349f30e 942static void io_file_put_work(struct work_struct *work);
de0617e4 943
b63534c4
JA
944static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
945 struct iovec **iovec, struct iov_iter *iter,
946 bool needs_lock);
ff6165b2
JA
947static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
948 const struct iovec *fast_iov,
227c0c96 949 struct iov_iter *iter, bool force);
de0617e4 950
2b188cc1
JA
951static struct kmem_cache *req_cachep;
952
738277ad 953static const struct file_operations io_uring_fops __read_mostly;
2b188cc1
JA
954
955struct sock *io_uring_get_socket(struct file *file)
956{
957#if defined(CONFIG_UNIX)
958 if (file->f_op == &io_uring_fops) {
959 struct io_ring_ctx *ctx = file->private_data;
960
961 return ctx->ring_sock->sk;
962 }
963#endif
964 return NULL;
965}
966EXPORT_SYMBOL(io_uring_get_socket);
967
3ca405eb
PB
968static inline void io_clean_op(struct io_kiocb *req)
969{
bb175342
PB
970 if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED |
971 REQ_F_INFLIGHT))
3ca405eb
PB
972 __io_clean_op(req);
973}
974
4349f30e 975static void io_sq_thread_drop_mm(void)
c40f6379
JA
976{
977 struct mm_struct *mm = current->mm;
978
979 if (mm) {
980 kthread_unuse_mm(mm);
981 mmput(mm);
982 }
983}
984
985static int __io_sq_thread_acquire_mm(struct io_ring_ctx *ctx)
986{
987 if (!current->mm) {
cbcf7214 988 if (unlikely(!(ctx->flags & IORING_SETUP_SQPOLL) ||
2aede0e4
JA
989 !ctx->sqo_task->mm ||
990 !mmget_not_zero(ctx->sqo_task->mm)))
c40f6379 991 return -EFAULT;
2aede0e4 992 kthread_use_mm(ctx->sqo_task->mm);
c40f6379
JA
993 }
994
995 return 0;
996}
997
998static int io_sq_thread_acquire_mm(struct io_ring_ctx *ctx,
999 struct io_kiocb *req)
1000{
1001 if (!io_op_defs[req->opcode].needs_mm)
1002 return 0;
1003 return __io_sq_thread_acquire_mm(ctx);
1004}
1005
1006static inline void req_set_fail_links(struct io_kiocb *req)
1007{
1008 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1009 req->flags |= REQ_F_FAIL_LINK;
1010}
4a38aed2 1011
7cdaf587
XW
1012/*
1013 * Note: must call io_req_init_async() for the first time you
1014 * touch any members of io_wq_work.
1015 */
1016static inline void io_req_init_async(struct io_kiocb *req)
1017{
1018 if (req->flags & REQ_F_WORK_INITIALIZED)
1019 return;
1020
1021 memset(&req->work, 0, sizeof(req->work));
1022 req->flags |= REQ_F_WORK_INITIALIZED;
1023}
1024
0cdaf760
PB
1025static inline bool io_async_submit(struct io_ring_ctx *ctx)
1026{
1027 return ctx->flags & IORING_SETUP_SQPOLL;
1028}
1029
2b188cc1
JA
1030static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1031{
1032 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1033
0f158b4c 1034 complete(&ctx->ref_comp);
2b188cc1
JA
1035}
1036
8eb7e2d0
PB
1037static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1038{
1039 return !req->timeout.off;
1040}
1041
2b188cc1
JA
1042static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1043{
1044 struct io_ring_ctx *ctx;
78076bb6 1045 int hash_bits;
2b188cc1
JA
1046
1047 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1048 if (!ctx)
1049 return NULL;
1050
0ddf92e8
JA
1051 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
1052 if (!ctx->fallback_req)
1053 goto err;
1054
78076bb6
JA
1055 /*
1056 * Use 5 bits less than the max cq entries, that should give us around
1057 * 32 entries per hash list if totally full and uniformly spread.
1058 */
1059 hash_bits = ilog2(p->cq_entries);
1060 hash_bits -= 5;
1061 if (hash_bits <= 0)
1062 hash_bits = 1;
1063 ctx->cancel_hash_bits = hash_bits;
1064 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1065 GFP_KERNEL);
1066 if (!ctx->cancel_hash)
1067 goto err;
1068 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1069
21482896 1070 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
206aefde
JA
1071 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1072 goto err;
2b188cc1
JA
1073
1074 ctx->flags = p->flags;
69fb2131 1075 INIT_LIST_HEAD(&ctx->sqd_list);
2b188cc1 1076 init_waitqueue_head(&ctx->cq_wait);
1d7bb1d5 1077 INIT_LIST_HEAD(&ctx->cq_overflow_list);
0f158b4c
JA
1078 init_completion(&ctx->ref_comp);
1079 init_completion(&ctx->sq_thread_comp);
5a2e745d 1080 idr_init(&ctx->io_buffer_idr);
071698e1 1081 idr_init(&ctx->personality_idr);
2b188cc1
JA
1082 mutex_init(&ctx->uring_lock);
1083 init_waitqueue_head(&ctx->wait);
1084 spin_lock_init(&ctx->completion_lock);
540e32a0 1085 INIT_LIST_HEAD(&ctx->iopoll_list);
de0617e4 1086 INIT_LIST_HEAD(&ctx->defer_list);
5262f567 1087 INIT_LIST_HEAD(&ctx->timeout_list);
fcb323cc
JA
1088 init_waitqueue_head(&ctx->inflight_wait);
1089 spin_lock_init(&ctx->inflight_lock);
1090 INIT_LIST_HEAD(&ctx->inflight_list);
4a38aed2
JA
1091 INIT_DELAYED_WORK(&ctx->file_put_work, io_file_put_work);
1092 init_llist_head(&ctx->file_put_llist);
2b188cc1 1093 return ctx;
206aefde 1094err:
0ddf92e8
JA
1095 if (ctx->fallback_req)
1096 kmem_cache_free(req_cachep, ctx->fallback_req);
78076bb6 1097 kfree(ctx->cancel_hash);
206aefde
JA
1098 kfree(ctx);
1099 return NULL;
2b188cc1
JA
1100}
1101
9cf7c104 1102static bool req_need_defer(struct io_kiocb *req, u32 seq)
7adf4eaf 1103{
2bc9930e
JA
1104 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1105 struct io_ring_ctx *ctx = req->ctx;
a197f664 1106
9cf7c104 1107 return seq != ctx->cached_cq_tail
31af27c7 1108 + atomic_read(&ctx->cached_cq_overflow);
2bc9930e 1109 }
de0617e4 1110
9d858b21 1111 return false;
de0617e4
JA
1112}
1113
de0617e4 1114static void __io_commit_cqring(struct io_ring_ctx *ctx)
2b188cc1 1115{
75b28aff 1116 struct io_rings *rings = ctx->rings;
2b188cc1 1117
07910158
PB
1118 /* order cqe stores with ring update */
1119 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
2b188cc1 1120
07910158
PB
1121 if (wq_has_sleeper(&ctx->cq_wait)) {
1122 wake_up_interruptible(&ctx->cq_wait);
1123 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
2b188cc1
JA
1124 }
1125}
1126
51a4cc11
JA
1127/*
1128 * Returns true if we need to defer file table putting. This can only happen
1129 * from the error path with REQ_F_COMP_LOCKED set.
1130 */
1131static bool io_req_clean_work(struct io_kiocb *req)
18d9be1a 1132{
7cdaf587 1133 if (!(req->flags & REQ_F_WORK_INITIALIZED))
51a4cc11
JA
1134 return false;
1135
1136 req->flags &= ~REQ_F_WORK_INITIALIZED;
7cdaf587 1137
cccf0ee8
JA
1138 if (req->work.mm) {
1139 mmdrop(req->work.mm);
1140 req->work.mm = NULL;
1141 }
1142 if (req->work.creds) {
1143 put_cred(req->work.creds);
1144 req->work.creds = NULL;
1145 }
ff002b30
JA
1146 if (req->work.fs) {
1147 struct fs_struct *fs = req->work.fs;
1148
51a4cc11
JA
1149 if (req->flags & REQ_F_COMP_LOCKED)
1150 return true;
1151
ff002b30
JA
1152 spin_lock(&req->work.fs->lock);
1153 if (--fs->users)
1154 fs = NULL;
1155 spin_unlock(&req->work.fs->lock);
1156 if (fs)
1157 free_fs_struct(fs);
b65e0dd6 1158 req->work.fs = NULL;
ff002b30 1159 }
51a4cc11
JA
1160
1161 return false;
561fb04a
JA
1162}
1163
cbdcb435 1164static void io_prep_async_work(struct io_kiocb *req)
18d9be1a 1165{
d3656344 1166 const struct io_op_def *def = &io_op_defs[req->opcode];
54a91f3b 1167
16d59803
PB
1168 io_req_init_async(req);
1169
d3656344 1170 if (req->flags & REQ_F_ISREG) {
eefdf30f 1171 if (def->hash_reg_file || (req->ctx->flags & IORING_SETUP_IOPOLL))
8766dd51 1172 io_wq_hash_work(&req->work, file_inode(req->file));
d3656344
JA
1173 } else {
1174 if (def->unbound_nonreg_file)
3529d8c2 1175 req->work.flags |= IO_WQ_WORK_UNBOUND;
54a91f3b 1176 }
dca9cf8b
PB
1177 if (!req->work.mm && def->needs_mm) {
1178 mmgrab(current->mm);
1179 req->work.mm = current->mm;
1180 }
1181 if (!req->work.creds)
1182 req->work.creds = get_current_cred();
1183 if (!req->work.fs && def->needs_fs) {
1184 spin_lock(&current->fs->lock);
1185 if (!current->fs->in_exec) {
1186 req->work.fs = current->fs;
1187 req->work.fs->users++;
1188 } else {
1189 req->work.flags |= IO_WQ_WORK_CANCEL;
1190 }
1191 spin_unlock(&current->fs->lock);
1192 }
57f1a649
PB
1193 if (def->needs_fsize)
1194 req->work.fsize = rlimit(RLIMIT_FSIZE);
1195 else
1196 req->work.fsize = RLIM_INFINITY;
561fb04a 1197}
cccf0ee8 1198
cbdcb435 1199static void io_prep_async_link(struct io_kiocb *req)
561fb04a 1200{
cbdcb435 1201 struct io_kiocb *cur;
54a91f3b 1202
cbdcb435
PB
1203 io_prep_async_work(req);
1204 if (req->flags & REQ_F_LINK_HEAD)
1205 list_for_each_entry(cur, &req->link_list, link_list)
1206 io_prep_async_work(cur);
561fb04a
JA
1207}
1208
7271ef3a 1209static struct io_kiocb *__io_queue_async_work(struct io_kiocb *req)
561fb04a 1210{
a197f664 1211 struct io_ring_ctx *ctx = req->ctx;
cbdcb435 1212 struct io_kiocb *link = io_prep_linked_timeout(req);
561fb04a 1213
8766dd51
PB
1214 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1215 &req->work, req->flags);
1216 io_wq_enqueue(ctx->io_wq, &req->work);
7271ef3a 1217 return link;
18d9be1a
JA
1218}
1219
cbdcb435
PB
1220static void io_queue_async_work(struct io_kiocb *req)
1221{
7271ef3a
JA
1222 struct io_kiocb *link;
1223
cbdcb435
PB
1224 /* init ->work of the whole link before punting */
1225 io_prep_async_link(req);
7271ef3a
JA
1226 link = __io_queue_async_work(req);
1227
1228 if (link)
1229 io_queue_linked_timeout(link);
cbdcb435
PB
1230}
1231
5262f567
JA
1232static void io_kill_timeout(struct io_kiocb *req)
1233{
1234 int ret;
1235
2d28390a 1236 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
5262f567 1237 if (ret != -1) {
01cec8c1
PB
1238 atomic_set(&req->ctx->cq_timeouts,
1239 atomic_read(&req->ctx->cq_timeouts) + 1);
135fcde8 1240 list_del_init(&req->timeout.list);
f0e20b89 1241 req->flags |= REQ_F_COMP_LOCKED;
78e19bbe 1242 io_cqring_fill_event(req, 0);
ec9c02ad 1243 io_put_req(req);
5262f567
JA
1244 }
1245}
1246
f3606e3a
JA
1247static bool io_task_match(struct io_kiocb *req, struct task_struct *tsk)
1248{
1249 struct io_ring_ctx *ctx = req->ctx;
1250
1251 if (!tsk || req->task == tsk)
1252 return true;
534ca6d6
JA
1253 if (ctx->flags & IORING_SETUP_SQPOLL) {
1254 if (ctx->sq_data && req->task == ctx->sq_data->thread)
1255 return true;
1256 }
f3606e3a
JA
1257 return false;
1258}
1259
76e1b642
JA
1260/*
1261 * Returns true if we found and killed one or more timeouts
1262 */
1263static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk)
5262f567
JA
1264{
1265 struct io_kiocb *req, *tmp;
76e1b642 1266 int canceled = 0;
5262f567
JA
1267
1268 spin_lock_irq(&ctx->completion_lock);
f3606e3a 1269 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
76e1b642 1270 if (io_task_match(req, tsk)) {
f3606e3a 1271 io_kill_timeout(req);
76e1b642
JA
1272 canceled++;
1273 }
f3606e3a 1274 }
5262f567 1275 spin_unlock_irq(&ctx->completion_lock);
76e1b642 1276 return canceled != 0;
5262f567
JA
1277}
1278
04518945 1279static void __io_queue_deferred(struct io_ring_ctx *ctx)
de0617e4 1280{
04518945 1281 do {
27dc8338
PB
1282 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1283 struct io_defer_entry, list);
7271ef3a 1284 struct io_kiocb *link;
de0617e4 1285
9cf7c104 1286 if (req_need_defer(de->req, de->seq))
04518945 1287 break;
27dc8338 1288 list_del_init(&de->list);
cbdcb435 1289 /* punt-init is done before queueing for defer */
7271ef3a
JA
1290 link = __io_queue_async_work(de->req);
1291 if (link) {
1292 __io_queue_linked_timeout(link);
1293 /* drop submission reference */
1294 link->flags |= REQ_F_COMP_LOCKED;
1295 io_put_req(link);
1296 }
27dc8338 1297 kfree(de);
04518945
PB
1298 } while (!list_empty(&ctx->defer_list));
1299}
1300
360428f8 1301static void io_flush_timeouts(struct io_ring_ctx *ctx)
de0617e4 1302{
360428f8
PB
1303 while (!list_empty(&ctx->timeout_list)) {
1304 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
135fcde8 1305 struct io_kiocb, timeout.list);
de0617e4 1306
8eb7e2d0 1307 if (io_is_timeout_noseq(req))
360428f8 1308 break;
bfe68a22
PB
1309 if (req->timeout.target_seq != ctx->cached_cq_tail
1310 - atomic_read(&ctx->cq_timeouts))
360428f8 1311 break;
bfe68a22 1312
135fcde8 1313 list_del_init(&req->timeout.list);
5262f567 1314 io_kill_timeout(req);
360428f8
PB
1315 }
1316}
5262f567 1317
360428f8
PB
1318static void io_commit_cqring(struct io_ring_ctx *ctx)
1319{
1320 io_flush_timeouts(ctx);
de0617e4
JA
1321 __io_commit_cqring(ctx);
1322
04518945
PB
1323 if (unlikely(!list_empty(&ctx->defer_list)))
1324 __io_queue_deferred(ctx);
de0617e4
JA
1325}
1326
2b188cc1
JA
1327static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1328{
75b28aff 1329 struct io_rings *rings = ctx->rings;
2b188cc1
JA
1330 unsigned tail;
1331
1332 tail = ctx->cached_cq_tail;
115e12e5
SB
1333 /*
1334 * writes to the cq entry need to come after reading head; the
1335 * control dependency is enough as we're using WRITE_ONCE to
1336 * fill the cq entry
1337 */
75b28aff 1338 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
2b188cc1
JA
1339 return NULL;
1340
1341 ctx->cached_cq_tail++;
75b28aff 1342 return &rings->cqes[tail & ctx->cq_mask];
2b188cc1
JA
1343}
1344
f2842ab5
JA
1345static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1346{
f0b493e6
JA
1347 if (!ctx->cq_ev_fd)
1348 return false;
7e55a19c
SG
1349 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1350 return false;
f2842ab5
JA
1351 if (!ctx->eventfd_async)
1352 return true;
b41e9852 1353 return io_wq_current_is_worker();
f2842ab5
JA
1354}
1355
b41e9852 1356static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1d7bb1d5
JA
1357{
1358 if (waitqueue_active(&ctx->wait))
1359 wake_up(&ctx->wait);
534ca6d6
JA
1360 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1361 wake_up(&ctx->sq_data->wait);
b41e9852 1362 if (io_should_trigger_evfd(ctx))
1d7bb1d5
JA
1363 eventfd_signal(ctx->cq_ev_fd, 1);
1364}
1365
46930143
PB
1366static void io_cqring_mark_overflow(struct io_ring_ctx *ctx)
1367{
1368 if (list_empty(&ctx->cq_overflow_list)) {
1369 clear_bit(0, &ctx->sq_check_overflow);
1370 clear_bit(0, &ctx->cq_check_overflow);
1371 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1372 }
1373}
1374
e6c8aa9a
JA
1375static inline bool io_match_files(struct io_kiocb *req,
1376 struct files_struct *files)
1377{
1378 if (!files)
1379 return true;
1380 if (req->flags & REQ_F_WORK_INITIALIZED)
1381 return req->work.files == files;
1382 return false;
1383}
1384
c4a2ed72 1385/* Returns true if there are no backlogged entries after the flush */
e6c8aa9a
JA
1386static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1387 struct task_struct *tsk,
1388 struct files_struct *files)
1d7bb1d5
JA
1389{
1390 struct io_rings *rings = ctx->rings;
e6c8aa9a 1391 struct io_kiocb *req, *tmp;
1d7bb1d5 1392 struct io_uring_cqe *cqe;
1d7bb1d5
JA
1393 unsigned long flags;
1394 LIST_HEAD(list);
1395
1396 if (!force) {
1397 if (list_empty_careful(&ctx->cq_overflow_list))
c4a2ed72 1398 return true;
1d7bb1d5
JA
1399 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
1400 rings->cq_ring_entries))
c4a2ed72 1401 return false;
1d7bb1d5
JA
1402 }
1403
1404 spin_lock_irqsave(&ctx->completion_lock, flags);
1405
1406 /* if force is set, the ring is going away. always drop after that */
1407 if (force)
69b3e546 1408 ctx->cq_overflow_flushed = 1;
1d7bb1d5 1409
c4a2ed72 1410 cqe = NULL;
e6c8aa9a
JA
1411 list_for_each_entry_safe(req, tmp, &ctx->cq_overflow_list, compl.list) {
1412 if (tsk && req->task != tsk)
1413 continue;
1414 if (!io_match_files(req, files))
1415 continue;
1416
1d7bb1d5
JA
1417 cqe = io_get_cqring(ctx);
1418 if (!cqe && !force)
1419 break;
1420
40d8ddd4 1421 list_move(&req->compl.list, &list);
1d7bb1d5
JA
1422 if (cqe) {
1423 WRITE_ONCE(cqe->user_data, req->user_data);
1424 WRITE_ONCE(cqe->res, req->result);
0f7e466b 1425 WRITE_ONCE(cqe->flags, req->compl.cflags);
1d7bb1d5
JA
1426 } else {
1427 WRITE_ONCE(ctx->rings->cq_overflow,
1428 atomic_inc_return(&ctx->cached_cq_overflow));
1429 }
1430 }
1431
1432 io_commit_cqring(ctx);
46930143
PB
1433 io_cqring_mark_overflow(ctx);
1434
1d7bb1d5
JA
1435 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1436 io_cqring_ev_posted(ctx);
1437
1438 while (!list_empty(&list)) {
40d8ddd4
PB
1439 req = list_first_entry(&list, struct io_kiocb, compl.list);
1440 list_del(&req->compl.list);
ec9c02ad 1441 io_put_req(req);
1d7bb1d5 1442 }
c4a2ed72
JA
1443
1444 return cqe != NULL;
1d7bb1d5
JA
1445}
1446
bcda7baa 1447static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
2b188cc1 1448{
78e19bbe 1449 struct io_ring_ctx *ctx = req->ctx;
2b188cc1
JA
1450 struct io_uring_cqe *cqe;
1451
78e19bbe 1452 trace_io_uring_complete(ctx, req->user_data, res);
51c3ff62 1453
2b188cc1
JA
1454 /*
1455 * If we can't get a cq entry, userspace overflowed the
1456 * submission (by quite a lot). Increment the overflow count in
1457 * the ring.
1458 */
1459 cqe = io_get_cqring(ctx);
1d7bb1d5 1460 if (likely(cqe)) {
78e19bbe 1461 WRITE_ONCE(cqe->user_data, req->user_data);
2b188cc1 1462 WRITE_ONCE(cqe->res, res);
bcda7baa 1463 WRITE_ONCE(cqe->flags, cflags);
0f212204
JA
1464 } else if (ctx->cq_overflow_flushed || req->task->io_uring->in_idle) {
1465 /*
1466 * If we're in ring overflow flush mode, or in task cancel mode,
1467 * then we cannot store the request for later flushing, we need
1468 * to drop it on the floor.
1469 */
498ccd9e
JA
1470 WRITE_ONCE(ctx->rings->cq_overflow,
1471 atomic_inc_return(&ctx->cached_cq_overflow));
1d7bb1d5 1472 } else {
ad3eb2c8
JA
1473 if (list_empty(&ctx->cq_overflow_list)) {
1474 set_bit(0, &ctx->sq_check_overflow);
1475 set_bit(0, &ctx->cq_check_overflow);
6d5f9049 1476 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
ad3eb2c8 1477 }
40d8ddd4 1478 io_clean_op(req);
1d7bb1d5 1479 req->result = res;
0f7e466b 1480 req->compl.cflags = cflags;
40d8ddd4
PB
1481 refcount_inc(&req->refs);
1482 list_add_tail(&req->compl.list, &ctx->cq_overflow_list);
2b188cc1
JA
1483 }
1484}
1485
bcda7baa
JA
1486static void io_cqring_fill_event(struct io_kiocb *req, long res)
1487{
1488 __io_cqring_fill_event(req, res, 0);
1489}
1490
e1e16097 1491static void io_cqring_add_event(struct io_kiocb *req, long res, long cflags)
2b188cc1 1492{
78e19bbe 1493 struct io_ring_ctx *ctx = req->ctx;
2b188cc1
JA
1494 unsigned long flags;
1495
1496 spin_lock_irqsave(&ctx->completion_lock, flags);
bcda7baa 1497 __io_cqring_fill_event(req, res, cflags);
2b188cc1
JA
1498 io_commit_cqring(ctx);
1499 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1500
8c838788 1501 io_cqring_ev_posted(ctx);
2b188cc1
JA
1502}
1503
229a7b63 1504static void io_submit_flush_completions(struct io_comp_state *cs)
bcda7baa 1505{
229a7b63
JA
1506 struct io_ring_ctx *ctx = cs->ctx;
1507
1508 spin_lock_irq(&ctx->completion_lock);
1509 while (!list_empty(&cs->list)) {
1510 struct io_kiocb *req;
1511
3ca405eb
PB
1512 req = list_first_entry(&cs->list, struct io_kiocb, compl.list);
1513 list_del(&req->compl.list);
0f7e466b 1514 __io_cqring_fill_event(req, req->result, req->compl.cflags);
229a7b63
JA
1515 if (!(req->flags & REQ_F_LINK_HEAD)) {
1516 req->flags |= REQ_F_COMP_LOCKED;
1517 io_put_req(req);
1518 } else {
1519 spin_unlock_irq(&ctx->completion_lock);
1520 io_put_req(req);
1521 spin_lock_irq(&ctx->completion_lock);
1522 }
1523 }
1524 io_commit_cqring(ctx);
1525 spin_unlock_irq(&ctx->completion_lock);
1526
1527 io_cqring_ev_posted(ctx);
1528 cs->nr = 0;
1529}
1530
1531static void __io_req_complete(struct io_kiocb *req, long res, unsigned cflags,
1532 struct io_comp_state *cs)
1533{
1534 if (!cs) {
1535 io_cqring_add_event(req, res, cflags);
1536 io_put_req(req);
1537 } else {
3ca405eb 1538 io_clean_op(req);
229a7b63 1539 req->result = res;
0f7e466b 1540 req->compl.cflags = cflags;
3ca405eb 1541 list_add_tail(&req->compl.list, &cs->list);
229a7b63
JA
1542 if (++cs->nr >= 32)
1543 io_submit_flush_completions(cs);
1544 }
e1e16097
JA
1545}
1546
1547static void io_req_complete(struct io_kiocb *req, long res)
bcda7baa 1548{
229a7b63 1549 __io_req_complete(req, res, 0, NULL);
bcda7baa
JA
1550}
1551
0ddf92e8
JA
1552static inline bool io_is_fallback_req(struct io_kiocb *req)
1553{
1554 return req == (struct io_kiocb *)
1555 ((unsigned long) req->ctx->fallback_req & ~1UL);
1556}
1557
1558static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1559{
1560 struct io_kiocb *req;
1561
1562 req = ctx->fallback_req;
dd461af6 1563 if (!test_and_set_bit_lock(0, (unsigned long *) &ctx->fallback_req))
0ddf92e8
JA
1564 return req;
1565
1566 return NULL;
1567}
1568
0553b8bd
PB
1569static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx,
1570 struct io_submit_state *state)
2b188cc1 1571{
fd6fab2c 1572 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2b188cc1
JA
1573 struct io_kiocb *req;
1574
f6b6c7d6 1575 if (!state->free_reqs) {
2579f913
JA
1576 size_t sz;
1577 int ret;
1578
1579 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
fd6fab2c
JA
1580 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1581
1582 /*
1583 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1584 * retry single alloc to be on the safe side.
1585 */
1586 if (unlikely(ret <= 0)) {
1587 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1588 if (!state->reqs[0])
0ddf92e8 1589 goto fallback;
fd6fab2c
JA
1590 ret = 1;
1591 }
2579f913 1592 state->free_reqs = ret - 1;
6c8a3134 1593 req = state->reqs[ret - 1];
2579f913 1594 } else {
2579f913 1595 state->free_reqs--;
6c8a3134 1596 req = state->reqs[state->free_reqs];
2b188cc1
JA
1597 }
1598
2579f913 1599 return req;
0ddf92e8 1600fallback:
0553b8bd 1601 return io_get_fallback_req(ctx);
2b188cc1
JA
1602}
1603
8da11c19
PB
1604static inline void io_put_file(struct io_kiocb *req, struct file *file,
1605 bool fixed)
1606{
1607 if (fixed)
05589553 1608 percpu_ref_put(req->fixed_file_refs);
8da11c19
PB
1609 else
1610 fput(file);
1611}
1612
51a4cc11 1613static bool io_dismantle_req(struct io_kiocb *req)
2b188cc1 1614{
3ca405eb 1615 io_clean_op(req);
929a3af9 1616
5acbbc8e
JA
1617 if (req->io)
1618 kfree(req->io);
8da11c19
PB
1619 if (req->file)
1620 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
fcb323cc 1621
51a4cc11 1622 return io_req_clean_work(req);
e65ef56d
JA
1623}
1624
51a4cc11 1625static void __io_free_req_finish(struct io_kiocb *req)
c6ca97b3 1626{
0f212204 1627 struct io_uring_task *tctx = req->task->io_uring;
51a4cc11 1628 struct io_ring_ctx *ctx = req->ctx;
c6ca97b3 1629
0f212204
JA
1630 atomic_long_inc(&tctx->req_complete);
1631 if (tctx->in_idle)
1632 wake_up(&tctx->wait);
e3bc8e9d
JA
1633 put_task_struct(req->task);
1634
b1e50e54
PB
1635 if (likely(!io_is_fallback_req(req)))
1636 kmem_cache_free(req_cachep, req);
1637 else
ecfc5177
PB
1638 clear_bit_unlock(0, (unsigned long *) &ctx->fallback_req);
1639 percpu_ref_put(&ctx->refs);
e65ef56d
JA
1640}
1641
51a4cc11
JA
1642static void io_req_task_file_table_put(struct callback_head *cb)
1643{
1644 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
1645 struct fs_struct *fs = req->work.fs;
1646
1647 spin_lock(&req->work.fs->lock);
1648 if (--fs->users)
1649 fs = NULL;
1650 spin_unlock(&req->work.fs->lock);
1651 if (fs)
1652 free_fs_struct(fs);
1653 req->work.fs = NULL;
1654 __io_free_req_finish(req);
1655}
1656
1657static void __io_free_req(struct io_kiocb *req)
1658{
1659 if (!io_dismantle_req(req)) {
1660 __io_free_req_finish(req);
1661 } else {
1662 int ret;
1663
1664 init_task_work(&req->task_work, io_req_task_file_table_put);
1665 ret = task_work_add(req->task, &req->task_work, TWA_RESUME);
1666 if (unlikely(ret)) {
1667 struct task_struct *tsk;
1668
1669 tsk = io_wq_get_task(req->ctx->io_wq);
1670 task_work_add(tsk, &req->task_work, 0);
1671 }
1672 }
1673}
1674
a197f664 1675static bool io_link_cancel_timeout(struct io_kiocb *req)
2665abfd 1676{
a197f664 1677 struct io_ring_ctx *ctx = req->ctx;
2665abfd
JA
1678 int ret;
1679
2d28390a 1680 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
2665abfd 1681 if (ret != -1) {
78e19bbe 1682 io_cqring_fill_event(req, -ECANCELED);
2665abfd 1683 io_commit_cqring(ctx);
dea3b49c 1684 req->flags &= ~REQ_F_LINK_HEAD;
ec9c02ad 1685 io_put_req(req);
2665abfd
JA
1686 return true;
1687 }
1688
1689 return false;
e65ef56d
JA
1690}
1691
ab0b6451 1692static bool __io_kill_linked_timeout(struct io_kiocb *req)
9e645e11 1693{
7c86ffee 1694 struct io_kiocb *link;
ab0b6451 1695 bool wake_ev;
7c86ffee
PB
1696
1697 if (list_empty(&req->link_list))
ab0b6451 1698 return false;
7c86ffee
PB
1699 link = list_first_entry(&req->link_list, struct io_kiocb, link_list);
1700 if (link->opcode != IORING_OP_LINK_TIMEOUT)
ab0b6451 1701 return false;
7c86ffee
PB
1702
1703 list_del_init(&link->link_list);
9b7adba9 1704 link->flags |= REQ_F_COMP_LOCKED;
7c86ffee
PB
1705 wake_ev = io_link_cancel_timeout(link);
1706 req->flags &= ~REQ_F_LINK_TIMEOUT;
ab0b6451
JA
1707 return wake_ev;
1708}
1709
1710static void io_kill_linked_timeout(struct io_kiocb *req)
9e645e11 1711{
2665abfd 1712 struct io_ring_ctx *ctx = req->ctx;
ab0b6451 1713 bool wake_ev;
9e645e11 1714
ab0b6451
JA
1715 if (!(req->flags & REQ_F_COMP_LOCKED)) {
1716 unsigned long flags;
1717
1718 spin_lock_irqsave(&ctx->completion_lock, flags);
1719 wake_ev = __io_kill_linked_timeout(req);
7c86ffee 1720 spin_unlock_irqrestore(&ctx->completion_lock, flags);
ab0b6451
JA
1721 } else {
1722 wake_ev = __io_kill_linked_timeout(req);
1723 }
1724
7c86ffee
PB
1725 if (wake_ev)
1726 io_cqring_ev_posted(ctx);
1727}
1728
9b5f7bd9 1729static struct io_kiocb *io_req_link_next(struct io_kiocb *req)
7c86ffee
PB
1730{
1731 struct io_kiocb *nxt;
4d7dd462 1732
9e645e11
JA
1733 /*
1734 * The list should never be empty when we are called here. But could
1735 * potentially happen if the chain is messed up, check to be on the
1736 * safe side.
1737 */
7c86ffee 1738 if (unlikely(list_empty(&req->link_list)))
9b5f7bd9 1739 return NULL;
2665abfd 1740
7c86ffee
PB
1741 nxt = list_first_entry(&req->link_list, struct io_kiocb, link_list);
1742 list_del_init(&req->link_list);
1743 if (!list_empty(&nxt->link_list))
1744 nxt->flags |= REQ_F_LINK_HEAD;
9b5f7bd9 1745 return nxt;
9e645e11
JA
1746}
1747
1748/*
dea3b49c 1749 * Called if REQ_F_LINK_HEAD is set, and we fail the head request
9e645e11 1750 */
7c86ffee 1751static void __io_fail_links(struct io_kiocb *req)
9e645e11 1752{
2665abfd 1753 struct io_ring_ctx *ctx = req->ctx;
9e645e11
JA
1754
1755 while (!list_empty(&req->link_list)) {
4493233e
PB
1756 struct io_kiocb *link = list_first_entry(&req->link_list,
1757 struct io_kiocb, link_list);
9e645e11 1758
4493233e 1759 list_del_init(&link->link_list);
c826bd7a 1760 trace_io_uring_fail_link(req, link);
2665abfd 1761
7c86ffee 1762 io_cqring_fill_event(link, -ECANCELED);
9b7adba9 1763 link->flags |= REQ_F_COMP_LOCKED;
7c86ffee 1764 __io_double_put_req(link);
5d960724 1765 req->flags &= ~REQ_F_LINK_TIMEOUT;
9e645e11 1766 }
2665abfd
JA
1767
1768 io_commit_cqring(ctx);
2665abfd 1769 io_cqring_ev_posted(ctx);
9e645e11
JA
1770}
1771
7c86ffee 1772static void io_fail_links(struct io_kiocb *req)
9e645e11 1773{
7c86ffee 1774 struct io_ring_ctx *ctx = req->ctx;
2665abfd 1775
7c86ffee 1776 if (!(req->flags & REQ_F_COMP_LOCKED)) {
2665abfd
JA
1777 unsigned long flags;
1778
2665abfd 1779 spin_lock_irqsave(&ctx->completion_lock, flags);
7c86ffee 1780 __io_fail_links(req);
2665abfd
JA
1781 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1782 } else {
7c86ffee 1783 __io_fail_links(req);
9e645e11
JA
1784 }
1785
2665abfd 1786 io_cqring_ev_posted(ctx);
9e645e11
JA
1787}
1788
3fa5e0f3 1789static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
c69f8dbe 1790{
9b0d911a 1791 req->flags &= ~REQ_F_LINK_HEAD;
7c86ffee
PB
1792 if (req->flags & REQ_F_LINK_TIMEOUT)
1793 io_kill_linked_timeout(req);
944e58bf 1794
9e645e11
JA
1795 /*
1796 * If LINK is set, we have dependent requests in this chain. If we
1797 * didn't fail this request, queue the first one up, moving any other
1798 * dependencies to the next request. In case of failure, fail the rest
1799 * of the chain.
1800 */
9b5f7bd9
PB
1801 if (likely(!(req->flags & REQ_F_FAIL_LINK)))
1802 return io_req_link_next(req);
1803 io_fail_links(req);
1804 return NULL;
4d7dd462 1805}
9e645e11 1806
3fa5e0f3
PB
1807static struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1808{
1809 if (likely(!(req->flags & REQ_F_LINK_HEAD)))
1810 return NULL;
1811 return __io_req_find_next(req);
1812}
1813
fd7d6de2
JA
1814static int io_req_task_work_add(struct io_kiocb *req, struct callback_head *cb,
1815 bool twa_signal_ok)
c2c4c83c
JA
1816{
1817 struct task_struct *tsk = req->task;
1818 struct io_ring_ctx *ctx = req->ctx;
0ba9c9ed 1819 int ret, notify;
c2c4c83c 1820
6200b0ae
JA
1821 if (tsk->flags & PF_EXITING)
1822 return -ESRCH;
1823
c2c4c83c 1824 /*
0ba9c9ed
JA
1825 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
1826 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
1827 * processing task_work. There's no reliable way to tell if TWA_RESUME
1828 * will do the job.
c2c4c83c 1829 */
0ba9c9ed 1830 notify = 0;
fd7d6de2 1831 if (!(ctx->flags & IORING_SETUP_SQPOLL) && twa_signal_ok)
c2c4c83c
JA
1832 notify = TWA_SIGNAL;
1833
1834 ret = task_work_add(tsk, cb, notify);
1835 if (!ret)
1836 wake_up_process(tsk);
0ba9c9ed 1837
c2c4c83c
JA
1838 return ret;
1839}
1840
c40f6379
JA
1841static void __io_req_task_cancel(struct io_kiocb *req, int error)
1842{
1843 struct io_ring_ctx *ctx = req->ctx;
1844
1845 spin_lock_irq(&ctx->completion_lock);
1846 io_cqring_fill_event(req, error);
1847 io_commit_cqring(ctx);
1848 spin_unlock_irq(&ctx->completion_lock);
1849
1850 io_cqring_ev_posted(ctx);
1851 req_set_fail_links(req);
1852 io_double_put_req(req);
1853}
1854
1855static void io_req_task_cancel(struct callback_head *cb)
1856{
1857 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
87ceb6a6 1858 struct io_ring_ctx *ctx = req->ctx;
c40f6379
JA
1859
1860 __io_req_task_cancel(req, -ECANCELED);
87ceb6a6 1861 percpu_ref_put(&ctx->refs);
c40f6379
JA
1862}
1863
1864static void __io_req_task_submit(struct io_kiocb *req)
1865{
1866 struct io_ring_ctx *ctx = req->ctx;
1867
c40f6379
JA
1868 if (!__io_sq_thread_acquire_mm(ctx)) {
1869 mutex_lock(&ctx->uring_lock);
1870 __io_queue_sqe(req, NULL, NULL);
1871 mutex_unlock(&ctx->uring_lock);
1872 } else {
1873 __io_req_task_cancel(req, -EFAULT);
1874 }
1875}
1876
1877static void io_req_task_submit(struct callback_head *cb)
1878{
1879 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
6d816e08 1880 struct io_ring_ctx *ctx = req->ctx;
c40f6379
JA
1881
1882 __io_req_task_submit(req);
6d816e08 1883 percpu_ref_put(&ctx->refs);
c40f6379
JA
1884}
1885
1886static void io_req_task_queue(struct io_kiocb *req)
1887{
c40f6379
JA
1888 int ret;
1889
1890 init_task_work(&req->task_work, io_req_task_submit);
6d816e08 1891 percpu_ref_get(&req->ctx->refs);
c40f6379 1892
fd7d6de2 1893 ret = io_req_task_work_add(req, &req->task_work, true);
c40f6379 1894 if (unlikely(ret)) {
c2c4c83c
JA
1895 struct task_struct *tsk;
1896
c40f6379
JA
1897 init_task_work(&req->task_work, io_req_task_cancel);
1898 tsk = io_wq_get_task(req->ctx->io_wq);
c2c4c83c
JA
1899 task_work_add(tsk, &req->task_work, 0);
1900 wake_up_process(tsk);
c40f6379 1901 }
c40f6379
JA
1902}
1903
c3524383 1904static void io_queue_next(struct io_kiocb *req)
c69f8dbe 1905{
9b5f7bd9 1906 struct io_kiocb *nxt = io_req_find_next(req);
944e58bf
PB
1907
1908 if (nxt)
906a8c3f 1909 io_req_task_queue(nxt);
c69f8dbe
JL
1910}
1911
c3524383 1912static void io_free_req(struct io_kiocb *req)
7a743e22 1913{
c3524383
PB
1914 io_queue_next(req);
1915 __io_free_req(req);
1916}
8766dd51 1917
2d6500d4
PB
1918struct req_batch {
1919 void *reqs[IO_IOPOLL_BATCH];
1920 int to_free;
7a743e22 1921
5af1d13e
PB
1922 struct task_struct *task;
1923 int task_refs;
2d6500d4
PB
1924};
1925
5af1d13e
PB
1926static inline void io_init_req_batch(struct req_batch *rb)
1927{
1928 rb->to_free = 0;
1929 rb->task_refs = 0;
1930 rb->task = NULL;
1931}
1932
2d6500d4
PB
1933static void __io_req_free_batch_flush(struct io_ring_ctx *ctx,
1934 struct req_batch *rb)
1935{
1936 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
1937 percpu_ref_put_many(&ctx->refs, rb->to_free);
1938 rb->to_free = 0;
1939}
1940
1941static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
1942 struct req_batch *rb)
1943{
1944 if (rb->to_free)
1945 __io_req_free_batch_flush(ctx, rb);
5af1d13e 1946 if (rb->task) {
0f212204 1947 atomic_long_add(rb->task_refs, &rb->task->io_uring->req_complete);
5af1d13e
PB
1948 put_task_struct_many(rb->task, rb->task_refs);
1949 rb->task = NULL;
1950 }
2d6500d4
PB
1951}
1952
1953static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req)
1954{
1955 if (unlikely(io_is_fallback_req(req))) {
1956 io_free_req(req);
1957 return;
1958 }
1959 if (req->flags & REQ_F_LINK_HEAD)
1960 io_queue_next(req);
1961
e3bc8e9d 1962 if (req->task != rb->task) {
0f212204
JA
1963 if (rb->task) {
1964 atomic_long_add(rb->task_refs, &rb->task->io_uring->req_complete);
e3bc8e9d 1965 put_task_struct_many(rb->task, rb->task_refs);
0f212204 1966 }
e3bc8e9d
JA
1967 rb->task = req->task;
1968 rb->task_refs = 0;
5af1d13e 1969 }
e3bc8e9d 1970 rb->task_refs++;
5af1d13e 1971
51a4cc11 1972 WARN_ON_ONCE(io_dismantle_req(req));
2d6500d4
PB
1973 rb->reqs[rb->to_free++] = req;
1974 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
1975 __io_req_free_batch_flush(req->ctx, rb);
7a743e22
PB
1976}
1977
ba816ad6
JA
1978/*
1979 * Drop reference to request, return next in chain (if there is one) if this
1980 * was the last reference to this request.
1981 */
9b5f7bd9 1982static struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
e65ef56d 1983{
9b5f7bd9
PB
1984 struct io_kiocb *nxt = NULL;
1985
2a44f467 1986 if (refcount_dec_and_test(&req->refs)) {
9b5f7bd9 1987 nxt = io_req_find_next(req);
4d7dd462 1988 __io_free_req(req);
2a44f467 1989 }
9b5f7bd9 1990 return nxt;
2b188cc1
JA
1991}
1992
e65ef56d
JA
1993static void io_put_req(struct io_kiocb *req)
1994{
1995 if (refcount_dec_and_test(&req->refs))
1996 io_free_req(req);
2b188cc1
JA
1997}
1998
f4db7182 1999static struct io_wq_work *io_steal_work(struct io_kiocb *req)
7a743e22 2000{
6df1db6b 2001 struct io_kiocb *nxt;
f4db7182 2002
7a743e22 2003 /*
f4db7182
PB
2004 * A ref is owned by io-wq in which context we're. So, if that's the
2005 * last one, it's safe to steal next work. False negatives are Ok,
2006 * it just will be re-punted async in io_put_work()
7a743e22 2007 */
f4db7182
PB
2008 if (refcount_read(&req->refs) != 1)
2009 return NULL;
7a743e22 2010
9b5f7bd9 2011 nxt = io_req_find_next(req);
6df1db6b 2012 return nxt ? &nxt->work : NULL;
7a743e22
PB
2013}
2014
978db57e
JA
2015/*
2016 * Must only be used if we don't need to care about links, usually from
2017 * within the completion handling itself.
2018 */
2019static void __io_double_put_req(struct io_kiocb *req)
78e19bbe
JA
2020{
2021 /* drop both submit and complete references */
2022 if (refcount_sub_and_test(2, &req->refs))
2023 __io_free_req(req);
2024}
2025
978db57e
JA
2026static void io_double_put_req(struct io_kiocb *req)
2027{
2028 /* drop both submit and complete references */
2029 if (refcount_sub_and_test(2, &req->refs))
2030 io_free_req(req);
2031}
2032
1d7bb1d5 2033static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
a3a0e43f 2034{
84f97dc2
JA
2035 struct io_rings *rings = ctx->rings;
2036
ad3eb2c8
JA
2037 if (test_bit(0, &ctx->cq_check_overflow)) {
2038 /*
2039 * noflush == true is from the waitqueue handler, just ensure
2040 * we wake up the task, and the next invocation will flush the
2041 * entries. We cannot safely to it from here.
2042 */
2043 if (noflush && !list_empty(&ctx->cq_overflow_list))
2044 return -1U;
1d7bb1d5 2045
e6c8aa9a 2046 io_cqring_overflow_flush(ctx, false, NULL, NULL);
ad3eb2c8 2047 }
1d7bb1d5 2048
a3a0e43f
JA
2049 /* See comment at the top of this file */
2050 smp_rmb();
ad3eb2c8 2051 return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
a3a0e43f
JA
2052}
2053
fb5ccc98
PB
2054static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2055{
2056 struct io_rings *rings = ctx->rings;
2057
2058 /* make sure SQ entry isn't read before tail */
2059 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2060}
2061
8ff069bf 2062static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
e94f141b 2063{
8ff069bf 2064 unsigned int cflags;
e94f141b 2065
bcda7baa
JA
2066 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2067 cflags |= IORING_CQE_F_BUFFER;
0e1b6fe3 2068 req->flags &= ~REQ_F_BUFFER_SELECTED;
bcda7baa
JA
2069 kfree(kbuf);
2070 return cflags;
e94f141b
JA
2071}
2072
8ff069bf 2073static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
bcda7baa 2074{
4d954c25 2075 struct io_buffer *kbuf;
bcda7baa 2076
4d954c25 2077 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
8ff069bf
PB
2078 return io_put_kbuf(req, kbuf);
2079}
2080
4c6e277c
JA
2081static inline bool io_run_task_work(void)
2082{
6200b0ae
JA
2083 /*
2084 * Not safe to run on exiting task, and the task_work handling will
2085 * not add work to such a task.
2086 */
2087 if (unlikely(current->flags & PF_EXITING))
2088 return false;
4c6e277c
JA
2089 if (current->task_works) {
2090 __set_current_state(TASK_RUNNING);
2091 task_work_run();
2092 return true;
2093 }
2094
2095 return false;
bcda7baa
JA
2096}
2097
bbde017a
XW
2098static void io_iopoll_queue(struct list_head *again)
2099{
2100 struct io_kiocb *req;
2101
2102 do {
d21ffe7e
PB
2103 req = list_first_entry(again, struct io_kiocb, inflight_entry);
2104 list_del(&req->inflight_entry);
81b68a5c 2105 __io_complete_rw(req, -EAGAIN, 0, NULL);
bbde017a
XW
2106 } while (!list_empty(again));
2107}
2108
def596e9
JA
2109/*
2110 * Find and free completed poll iocbs
2111 */
2112static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2113 struct list_head *done)
2114{
8237e045 2115 struct req_batch rb;
def596e9 2116 struct io_kiocb *req;
bbde017a
XW
2117 LIST_HEAD(again);
2118
2119 /* order with ->result store in io_complete_rw_iopoll() */
2120 smp_rmb();
def596e9 2121
5af1d13e 2122 io_init_req_batch(&rb);
def596e9 2123 while (!list_empty(done)) {
bcda7baa
JA
2124 int cflags = 0;
2125
d21ffe7e 2126 req = list_first_entry(done, struct io_kiocb, inflight_entry);
bbde017a 2127 if (READ_ONCE(req->result) == -EAGAIN) {
56450c20 2128 req->result = 0;
bbde017a 2129 req->iopoll_completed = 0;
d21ffe7e 2130 list_move_tail(&req->inflight_entry, &again);
bbde017a
XW
2131 continue;
2132 }
d21ffe7e 2133 list_del(&req->inflight_entry);
def596e9 2134
bcda7baa 2135 if (req->flags & REQ_F_BUFFER_SELECTED)
8ff069bf 2136 cflags = io_put_rw_kbuf(req);
bcda7baa
JA
2137
2138 __io_cqring_fill_event(req, req->result, cflags);
def596e9
JA
2139 (*nr_events)++;
2140
c3524383 2141 if (refcount_dec_and_test(&req->refs))
2d6500d4 2142 io_req_free_batch(&rb, req);
def596e9 2143 }
def596e9 2144
09bb8394 2145 io_commit_cqring(ctx);
32b2244a
XW
2146 if (ctx->flags & IORING_SETUP_SQPOLL)
2147 io_cqring_ev_posted(ctx);
2d6500d4 2148 io_req_free_batch_finish(ctx, &rb);
581f9810 2149
bbde017a
XW
2150 if (!list_empty(&again))
2151 io_iopoll_queue(&again);
581f9810
BM
2152}
2153
def596e9
JA
2154static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2155 long min)
2156{
2157 struct io_kiocb *req, *tmp;
2158 LIST_HEAD(done);
2159 bool spin;
2160 int ret;
2161
2162 /*
2163 * Only spin for completions if we don't have multiple devices hanging
2164 * off our complete list, and we're under the requested amount.
2165 */
2166 spin = !ctx->poll_multi_file && *nr_events < min;
2167
2168 ret = 0;
d21ffe7e 2169 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
9adbd45d 2170 struct kiocb *kiocb = &req->rw.kiocb;
def596e9
JA
2171
2172 /*
581f9810
BM
2173 * Move completed and retryable entries to our local lists.
2174 * If we find a request that requires polling, break out
2175 * and complete those lists first, if we have entries there.
def596e9 2176 */
65a6543d 2177 if (READ_ONCE(req->iopoll_completed)) {
d21ffe7e 2178 list_move_tail(&req->inflight_entry, &done);
def596e9
JA
2179 continue;
2180 }
2181 if (!list_empty(&done))
2182 break;
2183
2184 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2185 if (ret < 0)
2186 break;
2187
3aadc23e
PB
2188 /* iopoll may have completed current req */
2189 if (READ_ONCE(req->iopoll_completed))
d21ffe7e 2190 list_move_tail(&req->inflight_entry, &done);
3aadc23e 2191
def596e9
JA
2192 if (ret && spin)
2193 spin = false;
2194 ret = 0;
2195 }
2196
2197 if (!list_empty(&done))
2198 io_iopoll_complete(ctx, nr_events, &done);
2199
2200 return ret;
2201}
2202
2203/*
d195a66e 2204 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
def596e9
JA
2205 * non-spinning poll check - we'll still enter the driver poll loop, but only
2206 * as a non-spinning completion check.
2207 */
2208static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2209 long min)
2210{
540e32a0 2211 while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
def596e9
JA
2212 int ret;
2213
2214 ret = io_do_iopoll(ctx, nr_events, min);
2215 if (ret < 0)
2216 return ret;
eba0a4dd 2217 if (*nr_events >= min)
def596e9
JA
2218 return 0;
2219 }
2220
2221 return 1;
2222}
2223
2224/*
2225 * We can't just wait for polled events to come to us, we have to actively
2226 * find and complete them.
2227 */
b2edc0a7 2228static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
def596e9
JA
2229{
2230 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2231 return;
2232
2233 mutex_lock(&ctx->uring_lock);
540e32a0 2234 while (!list_empty(&ctx->iopoll_list)) {
def596e9
JA
2235 unsigned int nr_events = 0;
2236
b2edc0a7 2237 io_do_iopoll(ctx, &nr_events, 0);
08f5439f 2238
b2edc0a7
PB
2239 /* let it sleep and repeat later if can't complete a request */
2240 if (nr_events == 0)
2241 break;
08f5439f
JA
2242 /*
2243 * Ensure we allow local-to-the-cpu processing to take place,
2244 * in this case we need to ensure that we reap all events.
3fcee5a6 2245 * Also let task_work, etc. to progress by releasing the mutex
08f5439f 2246 */
3fcee5a6
PB
2247 if (need_resched()) {
2248 mutex_unlock(&ctx->uring_lock);
2249 cond_resched();
2250 mutex_lock(&ctx->uring_lock);
2251 }
def596e9
JA
2252 }
2253 mutex_unlock(&ctx->uring_lock);
2254}
2255
7668b92a 2256static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
def596e9 2257{
7668b92a 2258 unsigned int nr_events = 0;
2b2ed975 2259 int iters = 0, ret = 0;
500f9fba 2260
c7849be9
XW
2261 /*
2262 * We disallow the app entering submit/complete with polling, but we
2263 * still need to lock the ring to prevent racing with polled issue
2264 * that got punted to a workqueue.
2265 */
2266 mutex_lock(&ctx->uring_lock);
def596e9 2267 do {
a3a0e43f
JA
2268 /*
2269 * Don't enter poll loop if we already have events pending.
2270 * If we do, we can potentially be spinning for commands that
2271 * already triggered a CQE (eg in error).
2272 */
1d7bb1d5 2273 if (io_cqring_events(ctx, false))
a3a0e43f
JA
2274 break;
2275
500f9fba
JA
2276 /*
2277 * If a submit got punted to a workqueue, we can have the
2278 * application entering polling for a command before it gets
2279 * issued. That app will hold the uring_lock for the duration
2280 * of the poll right here, so we need to take a breather every
2281 * now and then to ensure that the issue has a chance to add
2282 * the poll to the issued list. Otherwise we can spin here
2283 * forever, while the workqueue is stuck trying to acquire the
2284 * very same mutex.
2285 */
2286 if (!(++iters & 7)) {
2287 mutex_unlock(&ctx->uring_lock);
4c6e277c 2288 io_run_task_work();
500f9fba
JA
2289 mutex_lock(&ctx->uring_lock);
2290 }
2291
7668b92a 2292 ret = io_iopoll_getevents(ctx, &nr_events, min);
def596e9
JA
2293 if (ret <= 0)
2294 break;
2295 ret = 0;
7668b92a 2296 } while (min && !nr_events && !need_resched());
def596e9 2297
500f9fba 2298 mutex_unlock(&ctx->uring_lock);
def596e9
JA
2299 return ret;
2300}
2301
491381ce 2302static void kiocb_end_write(struct io_kiocb *req)
2b188cc1 2303{
491381ce
JA
2304 /*
2305 * Tell lockdep we inherited freeze protection from submission
2306 * thread.
2307 */
2308 if (req->flags & REQ_F_ISREG) {
2309 struct inode *inode = file_inode(req->file);
2b188cc1 2310
491381ce 2311 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2b188cc1 2312 }
491381ce 2313 file_end_write(req->file);
2b188cc1
JA
2314}
2315
a1d7c393
JA
2316static void io_complete_rw_common(struct kiocb *kiocb, long res,
2317 struct io_comp_state *cs)
2b188cc1 2318{
9adbd45d 2319 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
bcda7baa 2320 int cflags = 0;
2b188cc1 2321
491381ce
JA
2322 if (kiocb->ki_flags & IOCB_WRITE)
2323 kiocb_end_write(req);
2b188cc1 2324
4e88d6e7
JA
2325 if (res != req->result)
2326 req_set_fail_links(req);
bcda7baa 2327 if (req->flags & REQ_F_BUFFER_SELECTED)
8ff069bf 2328 cflags = io_put_rw_kbuf(req);
a1d7c393 2329 __io_req_complete(req, res, cflags, cs);
ba816ad6
JA
2330}
2331
b63534c4
JA
2332#ifdef CONFIG_BLOCK
2333static bool io_resubmit_prep(struct io_kiocb *req, int error)
2334{
2335 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2336 ssize_t ret = -ECANCELED;
2337 struct iov_iter iter;
2338 int rw;
2339
2340 if (error) {
2341 ret = error;
2342 goto end_req;
2343 }
2344
2345 switch (req->opcode) {
2346 case IORING_OP_READV:
2347 case IORING_OP_READ_FIXED:
2348 case IORING_OP_READ:
2349 rw = READ;
2350 break;
2351 case IORING_OP_WRITEV:
2352 case IORING_OP_WRITE_FIXED:
2353 case IORING_OP_WRITE:
2354 rw = WRITE;
2355 break;
2356 default:
2357 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2358 req->opcode);
2359 goto end_req;
2360 }
2361
8f3d7496
JA
2362 if (!req->io) {
2363 ret = io_import_iovec(rw, req, &iovec, &iter, false);
2364 if (ret < 0)
2365 goto end_req;
2366 ret = io_setup_async_rw(req, iovec, inline_vecs, &iter, false);
2367 if (!ret)
2368 return true;
2369 kfree(iovec);
2370 } else {
b63534c4 2371 return true;
8f3d7496 2372 }
b63534c4 2373end_req:
b63534c4 2374 req_set_fail_links(req);
e1e16097 2375 io_req_complete(req, ret);
b63534c4
JA
2376 return false;
2377}
b63534c4
JA
2378#endif
2379
2380static bool io_rw_reissue(struct io_kiocb *req, long res)
2381{
2382#ifdef CONFIG_BLOCK
355afaeb 2383 umode_t mode = file_inode(req->file)->i_mode;
b63534c4
JA
2384 int ret;
2385
355afaeb
JA
2386 if (!S_ISBLK(mode) && !S_ISREG(mode))
2387 return false;
b63534c4
JA
2388 if ((res != -EAGAIN && res != -EOPNOTSUPP) || io_wq_current_is_worker())
2389 return false;
2390
fdee946d 2391 ret = io_sq_thread_acquire_mm(req->ctx, req);
6d816e08 2392
fdee946d
JA
2393 if (io_resubmit_prep(req, ret)) {
2394 refcount_inc(&req->refs);
2395 io_queue_async_work(req);
b63534c4 2396 return true;
fdee946d
JA
2397 }
2398
b63534c4
JA
2399#endif
2400 return false;
2401}
2402
a1d7c393
JA
2403static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2404 struct io_comp_state *cs)
2405{
2406 if (!io_rw_reissue(req, res))
2407 io_complete_rw_common(&req->rw.kiocb, res, cs);
ba816ad6
JA
2408}
2409
2410static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2411{
9adbd45d 2412 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
ba816ad6 2413
a1d7c393 2414 __io_complete_rw(req, res, res2, NULL);
2b188cc1
JA
2415}
2416
def596e9
JA
2417static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2418{
9adbd45d 2419 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
def596e9 2420
491381ce
JA
2421 if (kiocb->ki_flags & IOCB_WRITE)
2422 kiocb_end_write(req);
def596e9 2423
2d7d6792 2424 if (res != -EAGAIN && res != req->result)
4e88d6e7 2425 req_set_fail_links(req);
bbde017a
XW
2426
2427 WRITE_ONCE(req->result, res);
2428 /* order with io_poll_complete() checking ->result */
cd664b0e
PB
2429 smp_wmb();
2430 WRITE_ONCE(req->iopoll_completed, 1);
def596e9
JA
2431}
2432
2433/*
2434 * After the iocb has been issued, it's safe to be found on the poll list.
2435 * Adding the kiocb to the list AFTER submission ensures that we don't
2436 * find it from a io_iopoll_getevents() thread before the issuer is done
2437 * accessing the kiocb cookie.
2438 */
2439static void io_iopoll_req_issued(struct io_kiocb *req)
2440{
2441 struct io_ring_ctx *ctx = req->ctx;
2442
2443 /*
2444 * Track whether we have multiple files in our lists. This will impact
2445 * how we do polling eventually, not spinning if we're on potentially
2446 * different devices.
2447 */
540e32a0 2448 if (list_empty(&ctx->iopoll_list)) {
def596e9
JA
2449 ctx->poll_multi_file = false;
2450 } else if (!ctx->poll_multi_file) {
2451 struct io_kiocb *list_req;
2452
540e32a0 2453 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
d21ffe7e 2454 inflight_entry);
9adbd45d 2455 if (list_req->file != req->file)
def596e9
JA
2456 ctx->poll_multi_file = true;
2457 }
2458
2459 /*
2460 * For fast devices, IO may have already completed. If it has, add
2461 * it to the front so we find it first.
2462 */
65a6543d 2463 if (READ_ONCE(req->iopoll_completed))
d21ffe7e 2464 list_add(&req->inflight_entry, &ctx->iopoll_list);
def596e9 2465 else
d21ffe7e 2466 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
bdcd3eab 2467
534ca6d6
JA
2468 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2469 wq_has_sleeper(&ctx->sq_data->wait))
2470 wake_up(&ctx->sq_data->wait);
def596e9
JA
2471}
2472
9f13c35b 2473static void __io_state_file_put(struct io_submit_state *state)
9a56a232 2474{
06ef3608
PB
2475 if (state->has_refs)
2476 fput_many(state->file, state->has_refs);
9f13c35b
PB
2477 state->file = NULL;
2478}
2479
2480static inline void io_state_file_put(struct io_submit_state *state)
2481{
2482 if (state->file)
2483 __io_state_file_put(state);
9a56a232
JA
2484}
2485
2486/*
2487 * Get as many references to a file as we have IOs left in this submission,
2488 * assuming most submissions are for one file, or at least that each file
2489 * has more than one submission.
2490 */
8da11c19 2491static struct file *__io_file_get(struct io_submit_state *state, int fd)
9a56a232
JA
2492{
2493 if (!state)
2494 return fget(fd);
2495
2496 if (state->file) {
2497 if (state->fd == fd) {
06ef3608 2498 state->has_refs--;
9a56a232
JA
2499 state->ios_left--;
2500 return state->file;
2501 }
9f13c35b 2502 __io_state_file_put(state);
9a56a232
JA
2503 }
2504 state->file = fget_many(fd, state->ios_left);
2505 if (!state->file)
2506 return NULL;
2507
2508 state->fd = fd;
9a56a232 2509 state->ios_left--;
06ef3608 2510 state->has_refs = state->ios_left;
9a56a232
JA
2511 return state->file;
2512}
2513
4503b767
JA
2514static bool io_bdev_nowait(struct block_device *bdev)
2515{
2516#ifdef CONFIG_BLOCK
2517 return !bdev || queue_is_mq(bdev_get_queue(bdev));
2518#else
2519 return true;
2520#endif
2521}
2522
2b188cc1
JA
2523/*
2524 * If we tracked the file through the SCM inflight mechanism, we could support
2525 * any file. For now, just ensure that anything potentially problematic is done
2526 * inline.
2527 */
af197f50 2528static bool io_file_supports_async(struct file *file, int rw)
2b188cc1
JA
2529{
2530 umode_t mode = file_inode(file)->i_mode;
2531
4503b767
JA
2532 if (S_ISBLK(mode)) {
2533 if (io_bdev_nowait(file->f_inode->i_bdev))
2534 return true;
2535 return false;
2536 }
2537 if (S_ISCHR(mode) || S_ISSOCK(mode))
2b188cc1 2538 return true;
4503b767
JA
2539 if (S_ISREG(mode)) {
2540 if (io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2541 file->f_op != &io_uring_fops)
2542 return true;
2543 return false;
2544 }
2b188cc1 2545
c5b85625
JA
2546 /* any ->read/write should understand O_NONBLOCK */
2547 if (file->f_flags & O_NONBLOCK)
2548 return true;
2549
af197f50
JA
2550 if (!(file->f_mode & FMODE_NOWAIT))
2551 return false;
2552
2553 if (rw == READ)
2554 return file->f_op->read_iter != NULL;
2555
2556 return file->f_op->write_iter != NULL;
2b188cc1
JA
2557}
2558
3529d8c2
JA
2559static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2560 bool force_nonblock)
2b188cc1 2561{
def596e9 2562 struct io_ring_ctx *ctx = req->ctx;
9adbd45d 2563 struct kiocb *kiocb = &req->rw.kiocb;
09bb8394
JA
2564 unsigned ioprio;
2565 int ret;
2b188cc1 2566
491381ce
JA
2567 if (S_ISREG(file_inode(req->file)->i_mode))
2568 req->flags |= REQ_F_ISREG;
2569
2b188cc1 2570 kiocb->ki_pos = READ_ONCE(sqe->off);
ba04291e
JA
2571 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
2572 req->flags |= REQ_F_CUR_POS;
2573 kiocb->ki_pos = req->file->f_pos;
2574 }
2b188cc1 2575 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
3e577dcd
PB
2576 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2577 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2578 if (unlikely(ret))
2579 return ret;
2b188cc1
JA
2580
2581 ioprio = READ_ONCE(sqe->ioprio);
2582 if (ioprio) {
2583 ret = ioprio_check_cap(ioprio);
2584 if (ret)
09bb8394 2585 return ret;
2b188cc1
JA
2586
2587 kiocb->ki_ioprio = ioprio;
2588 } else
2589 kiocb->ki_ioprio = get_current_ioprio();
2590
8449eeda 2591 /* don't allow async punt if RWF_NOWAIT was requested */
c5b85625 2592 if (kiocb->ki_flags & IOCB_NOWAIT)
8449eeda
SB
2593 req->flags |= REQ_F_NOWAIT;
2594
2595 if (force_nonblock)
2b188cc1 2596 kiocb->ki_flags |= IOCB_NOWAIT;
8449eeda 2597
def596e9 2598 if (ctx->flags & IORING_SETUP_IOPOLL) {
def596e9
JA
2599 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2600 !kiocb->ki_filp->f_op->iopoll)
09bb8394 2601 return -EOPNOTSUPP;
2b188cc1 2602
def596e9
JA
2603 kiocb->ki_flags |= IOCB_HIPRI;
2604 kiocb->ki_complete = io_complete_rw_iopoll;
65a6543d 2605 req->iopoll_completed = 0;
def596e9 2606 } else {
09bb8394
JA
2607 if (kiocb->ki_flags & IOCB_HIPRI)
2608 return -EINVAL;
def596e9
JA
2609 kiocb->ki_complete = io_complete_rw;
2610 }
9adbd45d 2611
3529d8c2
JA
2612 req->rw.addr = READ_ONCE(sqe->addr);
2613 req->rw.len = READ_ONCE(sqe->len);
4f4eeba8 2614 req->buf_index = READ_ONCE(sqe->buf_index);
2b188cc1 2615 return 0;
2b188cc1
JA
2616}
2617
2618static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2619{
2620 switch (ret) {
2621 case -EIOCBQUEUED:
2622 break;
2623 case -ERESTARTSYS:
2624 case -ERESTARTNOINTR:
2625 case -ERESTARTNOHAND:
2626 case -ERESTART_RESTARTBLOCK:
2627 /*
2628 * We can't just restart the syscall, since previously
2629 * submitted sqes may already be in progress. Just fail this
2630 * IO with EINTR.
2631 */
2632 ret = -EINTR;
df561f66 2633 fallthrough;
2b188cc1
JA
2634 default:
2635 kiocb->ki_complete(kiocb, ret, 0);
2636 }
2637}
2638
a1d7c393
JA
2639static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2640 struct io_comp_state *cs)
ba816ad6 2641{
ba04291e
JA
2642 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2643
227c0c96
JA
2644 /* add previously done IO, if any */
2645 if (req->io && req->io->rw.bytes_done > 0) {
2646 if (ret < 0)
2647 ret = req->io->rw.bytes_done;
2648 else
2649 ret += req->io->rw.bytes_done;
2650 }
2651
ba04291e
JA
2652 if (req->flags & REQ_F_CUR_POS)
2653 req->file->f_pos = kiocb->ki_pos;
bcaec089 2654 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
a1d7c393 2655 __io_complete_rw(req, ret, 0, cs);
ba816ad6
JA
2656 else
2657 io_rw_done(kiocb, ret);
2658}
2659
9adbd45d 2660static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
7d009165 2661 struct iov_iter *iter)
edafccee 2662{
9adbd45d
JA
2663 struct io_ring_ctx *ctx = req->ctx;
2664 size_t len = req->rw.len;
edafccee 2665 struct io_mapped_ubuf *imu;
4f4eeba8 2666 u16 index, buf_index;
edafccee
JA
2667 size_t offset;
2668 u64 buf_addr;
2669
2670 /* attempt to use fixed buffers without having provided iovecs */
2671 if (unlikely(!ctx->user_bufs))
2672 return -EFAULT;
2673
4f4eeba8 2674 buf_index = req->buf_index;
edafccee
JA
2675 if (unlikely(buf_index >= ctx->nr_user_bufs))
2676 return -EFAULT;
2677
2678 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2679 imu = &ctx->user_bufs[index];
9adbd45d 2680 buf_addr = req->rw.addr;
edafccee
JA
2681
2682 /* overflow */
2683 if (buf_addr + len < buf_addr)
2684 return -EFAULT;
2685 /* not inside the mapped region */
2686 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2687 return -EFAULT;
2688
2689 /*
2690 * May not be a start of buffer, set size appropriately
2691 * and advance us to the beginning.
2692 */
2693 offset = buf_addr - imu->ubuf;
2694 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
bd11b3a3
JA
2695
2696 if (offset) {
2697 /*
2698 * Don't use iov_iter_advance() here, as it's really slow for
2699 * using the latter parts of a big fixed buffer - it iterates
2700 * over each segment manually. We can cheat a bit here, because
2701 * we know that:
2702 *
2703 * 1) it's a BVEC iter, we set it up
2704 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2705 * first and last bvec
2706 *
2707 * So just find our index, and adjust the iterator afterwards.
2708 * If the offset is within the first bvec (or the whole first
2709 * bvec, just use iov_iter_advance(). This makes it easier
2710 * since we can just skip the first segment, which may not
2711 * be PAGE_SIZE aligned.
2712 */
2713 const struct bio_vec *bvec = imu->bvec;
2714
2715 if (offset <= bvec->bv_len) {
2716 iov_iter_advance(iter, offset);
2717 } else {
2718 unsigned long seg_skip;
2719
2720 /* skip first vec */
2721 offset -= bvec->bv_len;
2722 seg_skip = 1 + (offset >> PAGE_SHIFT);
2723
2724 iter->bvec = bvec + seg_skip;
2725 iter->nr_segs -= seg_skip;
99c79f66 2726 iter->count -= bvec->bv_len + offset;
bd11b3a3 2727 iter->iov_offset = offset & ~PAGE_MASK;
bd11b3a3
JA
2728 }
2729 }
2730
5e559561 2731 return len;
edafccee
JA
2732}
2733
bcda7baa
JA
2734static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2735{
2736 if (needs_lock)
2737 mutex_unlock(&ctx->uring_lock);
2738}
2739
2740static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2741{
2742 /*
2743 * "Normal" inline submissions always hold the uring_lock, since we
2744 * grab it from the system call. Same is true for the SQPOLL offload.
2745 * The only exception is when we've detached the request and issue it
2746 * from an async worker thread, grab the lock for that case.
2747 */
2748 if (needs_lock)
2749 mutex_lock(&ctx->uring_lock);
2750}
2751
2752static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2753 int bgid, struct io_buffer *kbuf,
2754 bool needs_lock)
2755{
2756 struct io_buffer *head;
2757
2758 if (req->flags & REQ_F_BUFFER_SELECTED)
2759 return kbuf;
2760
2761 io_ring_submit_lock(req->ctx, needs_lock);
2762
2763 lockdep_assert_held(&req->ctx->uring_lock);
2764
2765 head = idr_find(&req->ctx->io_buffer_idr, bgid);
2766 if (head) {
2767 if (!list_empty(&head->list)) {
2768 kbuf = list_last_entry(&head->list, struct io_buffer,
2769 list);
2770 list_del(&kbuf->list);
2771 } else {
2772 kbuf = head;
2773 idr_remove(&req->ctx->io_buffer_idr, bgid);
2774 }
2775 if (*len > kbuf->len)
2776 *len = kbuf->len;
2777 } else {
2778 kbuf = ERR_PTR(-ENOBUFS);
2779 }
2780
2781 io_ring_submit_unlock(req->ctx, needs_lock);
2782
2783 return kbuf;
2784}
2785
4d954c25
JA
2786static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2787 bool needs_lock)
2788{
2789 struct io_buffer *kbuf;
4f4eeba8 2790 u16 bgid;
4d954c25
JA
2791
2792 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
4f4eeba8 2793 bgid = req->buf_index;
4d954c25
JA
2794 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2795 if (IS_ERR(kbuf))
2796 return kbuf;
2797 req->rw.addr = (u64) (unsigned long) kbuf;
2798 req->flags |= REQ_F_BUFFER_SELECTED;
2799 return u64_to_user_ptr(kbuf->addr);
2800}
2801
2802#ifdef CONFIG_COMPAT
2803static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2804 bool needs_lock)
2805{
2806 struct compat_iovec __user *uiov;
2807 compat_ssize_t clen;
2808 void __user *buf;
2809 ssize_t len;
2810
2811 uiov = u64_to_user_ptr(req->rw.addr);
2812 if (!access_ok(uiov, sizeof(*uiov)))
2813 return -EFAULT;
2814 if (__get_user(clen, &uiov->iov_len))
2815 return -EFAULT;
2816 if (clen < 0)
2817 return -EINVAL;
2818
2819 len = clen;
2820 buf = io_rw_buffer_select(req, &len, needs_lock);
2821 if (IS_ERR(buf))
2822 return PTR_ERR(buf);
2823 iov[0].iov_base = buf;
2824 iov[0].iov_len = (compat_size_t) len;
2825 return 0;
2826}
2827#endif
2828
2829static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2830 bool needs_lock)
2831{
2832 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2833 void __user *buf;
2834 ssize_t len;
2835
2836 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2837 return -EFAULT;
2838
2839 len = iov[0].iov_len;
2840 if (len < 0)
2841 return -EINVAL;
2842 buf = io_rw_buffer_select(req, &len, needs_lock);
2843 if (IS_ERR(buf))
2844 return PTR_ERR(buf);
2845 iov[0].iov_base = buf;
2846 iov[0].iov_len = len;
2847 return 0;
2848}
2849
2850static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2851 bool needs_lock)
2852{
dddb3e26
JA
2853 if (req->flags & REQ_F_BUFFER_SELECTED) {
2854 struct io_buffer *kbuf;
2855
2856 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2857 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2858 iov[0].iov_len = kbuf->len;
4d954c25 2859 return 0;
dddb3e26 2860 }
4d954c25
JA
2861 if (!req->rw.len)
2862 return 0;
2863 else if (req->rw.len > 1)
2864 return -EINVAL;
2865
2866#ifdef CONFIG_COMPAT
2867 if (req->ctx->compat)
2868 return io_compat_import(req, iov, needs_lock);
2869#endif
2870
2871 return __io_iov_buffer_select(req, iov, needs_lock);
2872}
2873
8452fd0c
JA
2874static ssize_t __io_import_iovec(int rw, struct io_kiocb *req,
2875 struct iovec **iovec, struct iov_iter *iter,
2876 bool needs_lock)
2b188cc1 2877{
9adbd45d
JA
2878 void __user *buf = u64_to_user_ptr(req->rw.addr);
2879 size_t sqe_len = req->rw.len;
4d954c25 2880 ssize_t ret;
edafccee
JA
2881 u8 opcode;
2882
d625c6ee 2883 opcode = req->opcode;
7d009165 2884 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
edafccee 2885 *iovec = NULL;
9adbd45d 2886 return io_import_fixed(req, rw, iter);
edafccee 2887 }
2b188cc1 2888
bcda7baa 2889 /* buffer index only valid with fixed read/write, or buffer select */
4f4eeba8 2890 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
9adbd45d
JA
2891 return -EINVAL;
2892
3a6820f2 2893 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
bcda7baa 2894 if (req->flags & REQ_F_BUFFER_SELECT) {
4d954c25 2895 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
867a23ea 2896 if (IS_ERR(buf))
4d954c25 2897 return PTR_ERR(buf);
3f9d6441 2898 req->rw.len = sqe_len;
bcda7baa
JA
2899 }
2900
3a6820f2
JA
2901 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2902 *iovec = NULL;
3a901598 2903 return ret < 0 ? ret : sqe_len;
3a6820f2
JA
2904 }
2905
4d954c25
JA
2906 if (req->flags & REQ_F_BUFFER_SELECT) {
2907 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3f9d6441
JA
2908 if (!ret) {
2909 ret = (*iovec)->iov_len;
2910 iov_iter_init(iter, rw, *iovec, 1, ret);
2911 }
4d954c25
JA
2912 *iovec = NULL;
2913 return ret;
2914 }
2915
2b188cc1 2916#ifdef CONFIG_COMPAT
cf6fd4bd 2917 if (req->ctx->compat)
2b188cc1
JA
2918 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
2919 iovec, iter);
2920#endif
2921
2922 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
2923}
2924
8452fd0c
JA
2925static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
2926 struct iovec **iovec, struct iov_iter *iter,
2927 bool needs_lock)
2928{
2929 if (!req->io)
2930 return __io_import_iovec(rw, req, iovec, iter, needs_lock);
2931 *iovec = NULL;
2932 return iov_iter_count(&req->io->rw.iter);
2933}
2934
0fef9483
JA
2935static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
2936{
2937 return kiocb->ki_filp->f_mode & FMODE_STREAM ? NULL : &kiocb->ki_pos;
2938}
2939
31b51510 2940/*
32960613
JA
2941 * For files that don't have ->read_iter() and ->write_iter(), handle them
2942 * by looping over ->read() or ->write() manually.
31b51510 2943 */
32960613
JA
2944static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2945 struct iov_iter *iter)
2946{
2947 ssize_t ret = 0;
2948
2949 /*
2950 * Don't support polled IO through this interface, and we can't
2951 * support non-blocking either. For the latter, this just causes
2952 * the kiocb to be handled from an async context.
2953 */
2954 if (kiocb->ki_flags & IOCB_HIPRI)
2955 return -EOPNOTSUPP;
2956 if (kiocb->ki_flags & IOCB_NOWAIT)
2957 return -EAGAIN;
2958
2959 while (iov_iter_count(iter)) {
311ae9e1 2960 struct iovec iovec;
32960613
JA
2961 ssize_t nr;
2962
311ae9e1
PB
2963 if (!iov_iter_is_bvec(iter)) {
2964 iovec = iov_iter_iovec(iter);
2965 } else {
2966 /* fixed buffers import bvec */
2967 iovec.iov_base = kmap(iter->bvec->bv_page)
2968 + iter->iov_offset;
2969 iovec.iov_len = min(iter->count,
2970 iter->bvec->bv_len - iter->iov_offset);
2971 }
2972
32960613
JA
2973 if (rw == READ) {
2974 nr = file->f_op->read(file, iovec.iov_base,
0fef9483 2975 iovec.iov_len, io_kiocb_ppos(kiocb));
32960613
JA
2976 } else {
2977 nr = file->f_op->write(file, iovec.iov_base,
0fef9483 2978 iovec.iov_len, io_kiocb_ppos(kiocb));
32960613
JA
2979 }
2980
311ae9e1
PB
2981 if (iov_iter_is_bvec(iter))
2982 kunmap(iter->bvec->bv_page);
2983
32960613
JA
2984 if (nr < 0) {
2985 if (!ret)
2986 ret = nr;
2987 break;
2988 }
2989 ret += nr;
2990 if (nr != iovec.iov_len)
2991 break;
2992 iov_iter_advance(iter, nr);
2993 }
2994
2995 return ret;
2996}
2997
ff6165b2
JA
2998static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
2999 const struct iovec *fast_iov, struct iov_iter *iter)
f67676d1 3000{
b64e3444
PB
3001 struct io_async_rw *rw = &req->io->rw;
3002
ff6165b2
JA
3003 memcpy(&rw->iter, iter, sizeof(*iter));
3004 rw->free_iovec = NULL;
227c0c96 3005 rw->bytes_done = 0;
ff6165b2
JA
3006 /* can only be fixed buffers, no need to do anything */
3007 if (iter->type == ITER_BVEC)
3008 return;
b64e3444 3009 if (!iovec) {
ff6165b2
JA
3010 unsigned iov_off = 0;
3011
3012 rw->iter.iov = rw->fast_iov;
3013 if (iter->iov != fast_iov) {
3014 iov_off = iter->iov - fast_iov;
3015 rw->iter.iov += iov_off;
3016 }
3017 if (rw->fast_iov != fast_iov)
3018 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
45097dae 3019 sizeof(struct iovec) * iter->nr_segs);
99bc4c38 3020 } else {
ff6165b2 3021 rw->free_iovec = iovec;
99bc4c38 3022 req->flags |= REQ_F_NEED_CLEANUP;
f67676d1
JA
3023 }
3024}
3025
3d9932a8
XW
3026static inline int __io_alloc_async_ctx(struct io_kiocb *req)
3027{
3028 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
3029 return req->io == NULL;
3030}
3031
b7bb4f7d 3032static int io_alloc_async_ctx(struct io_kiocb *req)
f67676d1 3033{
d3656344
JA
3034 if (!io_op_defs[req->opcode].async_ctx)
3035 return 0;
3d9932a8
XW
3036
3037 return __io_alloc_async_ctx(req);
b7bb4f7d
JA
3038}
3039
ff6165b2
JA
3040static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3041 const struct iovec *fast_iov,
227c0c96 3042 struct iov_iter *iter, bool force)
b7bb4f7d 3043{
227c0c96 3044 if (!force && !io_op_defs[req->opcode].async_ctx)
74566df3 3045 return 0;
5d204bcf 3046 if (!req->io) {
3d9932a8 3047 if (__io_alloc_async_ctx(req))
5d204bcf 3048 return -ENOMEM;
b7bb4f7d 3049
ff6165b2 3050 io_req_map_rw(req, iovec, fast_iov, iter);
5d204bcf 3051 }
b7bb4f7d 3052 return 0;
f67676d1
JA
3053}
3054
c3e330a4
PB
3055static inline int io_rw_prep_async(struct io_kiocb *req, int rw,
3056 bool force_nonblock)
3057{
ff6165b2 3058 struct io_async_rw *iorw = &req->io->rw;
c183edff 3059 struct iovec *iov;
c3e330a4
PB
3060 ssize_t ret;
3061
c183edff
JA
3062 iorw->iter.iov = iov = iorw->fast_iov;
3063 ret = __io_import_iovec(rw, req, &iov, &iorw->iter, !force_nonblock);
c3e330a4
PB
3064 if (unlikely(ret < 0))
3065 return ret;
3066
c183edff 3067 iorw->iter.iov = iov;
ff6165b2 3068 io_req_map_rw(req, iorw->iter.iov, iorw->fast_iov, &iorw->iter);
c3e330a4
PB
3069 return 0;
3070}
3071
3529d8c2
JA
3072static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3073 bool force_nonblock)
f67676d1
JA
3074{
3075 ssize_t ret;
3076
3529d8c2
JA
3077 ret = io_prep_rw(req, sqe, force_nonblock);
3078 if (ret)
3079 return ret;
f67676d1 3080
3529d8c2
JA
3081 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3082 return -EBADF;
f67676d1 3083
5f798bea
PB
3084 /* either don't need iovec imported or already have it */
3085 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
3529d8c2 3086 return 0;
c3e330a4 3087 return io_rw_prep_async(req, READ, force_nonblock);
f67676d1
JA
3088}
3089
c1dd91d1
JA
3090/*
3091 * This is our waitqueue callback handler, registered through lock_page_async()
3092 * when we initially tried to do the IO with the iocb armed our waitqueue.
3093 * This gets called when the page is unlocked, and we generally expect that to
3094 * happen when the page IO is completed and the page is now uptodate. This will
3095 * queue a task_work based retry of the operation, attempting to copy the data
3096 * again. If the latter fails because the page was NOT uptodate, then we will
3097 * do a thread based blocking retry of the operation. That's the unexpected
3098 * slow path.
3099 */
bcf5a063
JA
3100static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3101 int sync, void *arg)
3102{
3103 struct wait_page_queue *wpq;
3104 struct io_kiocb *req = wait->private;
bcf5a063 3105 struct wait_page_key *key = arg;
bcf5a063
JA
3106 int ret;
3107
3108 wpq = container_of(wait, struct wait_page_queue, wait);
3109
cdc8fcb4
LT
3110 if (!wake_page_match(wpq, key))
3111 return 0;
3112
c8d317aa 3113 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
bcf5a063
JA
3114 list_del_init(&wait->entry);
3115
e7375122 3116 init_task_work(&req->task_work, io_req_task_submit);
6d816e08
JA
3117 percpu_ref_get(&req->ctx->refs);
3118
bcf5a063
JA
3119 /* submit ref gets dropped, acquire a new one */
3120 refcount_inc(&req->refs);
fd7d6de2 3121 ret = io_req_task_work_add(req, &req->task_work, true);
bcf5a063 3122 if (unlikely(ret)) {
c2c4c83c
JA
3123 struct task_struct *tsk;
3124
bcf5a063 3125 /* queue just for cancelation */
e7375122 3126 init_task_work(&req->task_work, io_req_task_cancel);
bcf5a063 3127 tsk = io_wq_get_task(req->ctx->io_wq);
e7375122 3128 task_work_add(tsk, &req->task_work, 0);
c2c4c83c 3129 wake_up_process(tsk);
bcf5a063 3130 }
bcf5a063
JA
3131 return 1;
3132}
3133
c1dd91d1
JA
3134/*
3135 * This controls whether a given IO request should be armed for async page
3136 * based retry. If we return false here, the request is handed to the async
3137 * worker threads for retry. If we're doing buffered reads on a regular file,
3138 * we prepare a private wait_page_queue entry and retry the operation. This
3139 * will either succeed because the page is now uptodate and unlocked, or it
3140 * will register a callback when the page is unlocked at IO completion. Through
3141 * that callback, io_uring uses task_work to setup a retry of the operation.
3142 * That retry will attempt the buffered read again. The retry will generally
3143 * succeed, or in rare cases where it fails, we then fall back to using the
3144 * async worker threads for a blocking retry.
3145 */
227c0c96 3146static bool io_rw_should_retry(struct io_kiocb *req)
f67676d1 3147{
3b2a4439 3148 struct wait_page_queue *wait = &req->io->rw.wpq;
bcf5a063 3149 struct kiocb *kiocb = &req->rw.kiocb;
f67676d1 3150
bcf5a063
JA
3151 /* never retry for NOWAIT, we just complete with -EAGAIN */
3152 if (req->flags & REQ_F_NOWAIT)
3153 return false;
f67676d1 3154
227c0c96 3155 /* Only for buffered IO */
3b2a4439 3156 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
bcf5a063 3157 return false;
3b2a4439 3158
bcf5a063
JA
3159 /*
3160 * just use poll if we can, and don't attempt if the fs doesn't
3161 * support callback based unlocks
3162 */
3163 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3164 return false;
f67676d1 3165
3b2a4439
JA
3166 wait->wait.func = io_async_buf_func;
3167 wait->wait.private = req;
3168 wait->wait.flags = 0;
3169 INIT_LIST_HEAD(&wait->wait.entry);
3170 kiocb->ki_flags |= IOCB_WAITQ;
c8d317aa 3171 kiocb->ki_flags &= ~IOCB_NOWAIT;
3b2a4439 3172 kiocb->ki_waitq = wait;
3b2a4439 3173 return true;
bcf5a063
JA
3174}
3175
3176static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3177{
3178 if (req->file->f_op->read_iter)
3179 return call_read_iter(req->file, &req->rw.kiocb, iter);
2dd2111d
GH
3180 else if (req->file->f_op->read)
3181 return loop_rw_iter(READ, req->file, &req->rw.kiocb, iter);
3182 else
3183 return -EINVAL;
f67676d1
JA
3184}
3185
a1d7c393
JA
3186static int io_read(struct io_kiocb *req, bool force_nonblock,
3187 struct io_comp_state *cs)
2b188cc1
JA
3188{
3189 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
9adbd45d 3190 struct kiocb *kiocb = &req->rw.kiocb;
ff6165b2 3191 struct iov_iter __iter, *iter = &__iter;
227c0c96 3192 ssize_t io_size, ret, ret2;
31b51510 3193 size_t iov_count;
f5cac8b1 3194 bool no_async;
ff6165b2
JA
3195
3196 if (req->io)
3197 iter = &req->io->rw.iter;
2b188cc1 3198
ff6165b2 3199 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
06b76d44
JA
3200 if (ret < 0)
3201 return ret;
eefdf30f 3202 iov_count = iov_iter_count(iter);
fa15bafb
PB
3203 io_size = ret;
3204 req->result = io_size;
227c0c96 3205 ret = 0;
2b188cc1 3206
fd6c2e4c
JA
3207 /* Ensure we clear previously set non-block flag */
3208 if (!force_nonblock)
29de5f6a 3209 kiocb->ki_flags &= ~IOCB_NOWAIT;
fd6c2e4c 3210
24c74678 3211 /* If the file doesn't support async, just async punt */
f5cac8b1
JA
3212 no_async = force_nonblock && !io_file_supports_async(req->file, READ);
3213 if (no_async)
f67676d1 3214 goto copy_iov;
9e645e11 3215
0fef9483 3216 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), iov_count);
fa15bafb
PB
3217 if (unlikely(ret))
3218 goto out_free;
2b188cc1 3219
227c0c96 3220 ret = io_iter_do_read(req, iter);
32960613 3221
227c0c96
JA
3222 if (!ret) {
3223 goto done;
3224 } else if (ret == -EIOCBQUEUED) {
3225 ret = 0;
3226 goto out_free;
3227 } else if (ret == -EAGAIN) {
eefdf30f
JA
3228 /* IOPOLL retry should happen for io-wq threads */
3229 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
f91daf56 3230 goto done;
355afaeb
JA
3231 /* no retry on NONBLOCK marked file */
3232 if (req->file->f_flags & O_NONBLOCK)
3233 goto done;
84216315
JA
3234 /* some cases will consume bytes even on error returns */
3235 iov_iter_revert(iter, iov_count - iov_iter_count(iter));
f38c7e3a
JA
3236 ret = 0;
3237 goto copy_iov;
227c0c96 3238 } else if (ret < 0) {
00d23d51
JA
3239 /* make sure -ERESTARTSYS -> -EINTR is done */
3240 goto done;
227c0c96
JA
3241 }
3242
3243 /* read it all, or we did blocking attempt. no retry. */
f91daf56
JA
3244 if (!iov_iter_count(iter) || !force_nonblock ||
3245 (req->file->f_flags & O_NONBLOCK))
227c0c96
JA
3246 goto done;
3247
3248 io_size -= ret;
3249copy_iov:
3250 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3251 if (ret2) {
3252 ret = ret2;
3253 goto out_free;
3254 }
f5cac8b1
JA
3255 if (no_async)
3256 return -EAGAIN;
227c0c96
JA
3257 /* it's copied and will be cleaned with ->io */
3258 iovec = NULL;
3259 /* now use our persistent iterator, if we aren't already */
3260 iter = &req->io->rw.iter;
3261retry:
3262 req->io->rw.bytes_done += ret;
3263 /* if we can retry, do so with the callbacks armed */
3264 if (!io_rw_should_retry(req)) {
fa15bafb
PB
3265 kiocb->ki_flags &= ~IOCB_WAITQ;
3266 return -EAGAIN;
2b188cc1 3267 }
227c0c96
JA
3268
3269 /*
3270 * Now retry read with the IOCB_WAITQ parts set in the iocb. If we
3271 * get -EIOCBQUEUED, then we'll get a notification when the desired
3272 * page gets unlocked. We can also get a partial read here, and if we
3273 * do, then just retry at the new offset.
3274 */
3275 ret = io_iter_do_read(req, iter);
3276 if (ret == -EIOCBQUEUED) {
3277 ret = 0;
3278 goto out_free;
3279 } else if (ret > 0 && ret < io_size) {
3280 /* we got some bytes, but not all. retry. */
3281 goto retry;
3282 }
3283done:
3284 kiocb_done(kiocb, ret, cs);
3285 ret = 0;
f67676d1 3286out_free:
f261c168 3287 /* it's reportedly faster than delegating the null check to kfree() */
252917c3 3288 if (iovec)
6f2cc166 3289 kfree(iovec);
2b188cc1
JA
3290 return ret;
3291}
3292
3529d8c2
JA
3293static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3294 bool force_nonblock)
f67676d1
JA
3295{
3296 ssize_t ret;
3297
3529d8c2
JA
3298 ret = io_prep_rw(req, sqe, force_nonblock);
3299 if (ret)
3300 return ret;
f67676d1 3301
3529d8c2
JA
3302 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3303 return -EBADF;
f67676d1 3304
5f798bea
PB
3305 /* either don't need iovec imported or already have it */
3306 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
3529d8c2 3307 return 0;
c3e330a4 3308 return io_rw_prep_async(req, WRITE, force_nonblock);
f67676d1
JA
3309}
3310
a1d7c393
JA
3311static int io_write(struct io_kiocb *req, bool force_nonblock,
3312 struct io_comp_state *cs)
2b188cc1
JA
3313{
3314 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
9adbd45d 3315 struct kiocb *kiocb = &req->rw.kiocb;
ff6165b2 3316 struct iov_iter __iter, *iter = &__iter;
31b51510 3317 size_t iov_count;
fa15bafb 3318 ssize_t ret, ret2, io_size;
2b188cc1 3319
ff6165b2
JA
3320 if (req->io)
3321 iter = &req->io->rw.iter;
3322
3323 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
06b76d44
JA
3324 if (ret < 0)
3325 return ret;
eefdf30f 3326 iov_count = iov_iter_count(iter);
fa15bafb
PB
3327 io_size = ret;
3328 req->result = io_size;
2b188cc1 3329
fd6c2e4c
JA
3330 /* Ensure we clear previously set non-block flag */
3331 if (!force_nonblock)
9adbd45d 3332 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
fd6c2e4c 3333
24c74678 3334 /* If the file doesn't support async, just async punt */
af197f50 3335 if (force_nonblock && !io_file_supports_async(req->file, WRITE))
f67676d1 3336 goto copy_iov;
31b51510 3337
10d59345
JA
3338 /* file path doesn't support NOWAIT for non-direct_IO */
3339 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3340 (req->flags & REQ_F_ISREG))
f67676d1 3341 goto copy_iov;
31b51510 3342
0fef9483 3343 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), iov_count);
fa15bafb
PB
3344 if (unlikely(ret))
3345 goto out_free;
4ed734b0 3346
fa15bafb
PB
3347 /*
3348 * Open-code file_start_write here to grab freeze protection,
3349 * which will be released by another thread in
3350 * io_complete_rw(). Fool lockdep by telling it the lock got
3351 * released so that it doesn't complain about the held lock when
3352 * we return to userspace.
3353 */
3354 if (req->flags & REQ_F_ISREG) {
3355 __sb_start_write(file_inode(req->file)->i_sb,
3356 SB_FREEZE_WRITE, true);
3357 __sb_writers_release(file_inode(req->file)->i_sb,
3358 SB_FREEZE_WRITE);
3359 }
3360 kiocb->ki_flags |= IOCB_WRITE;
4ed734b0 3361
fa15bafb 3362 if (req->file->f_op->write_iter)
ff6165b2 3363 ret2 = call_write_iter(req->file, kiocb, iter);
2dd2111d 3364 else if (req->file->f_op->write)
ff6165b2 3365 ret2 = loop_rw_iter(WRITE, req->file, kiocb, iter);
2dd2111d
GH
3366 else
3367 ret2 = -EINVAL;
4ed734b0 3368
fa15bafb
PB
3369 /*
3370 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3371 * retry them without IOCB_NOWAIT.
3372 */
3373 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3374 ret2 = -EAGAIN;
355afaeb
JA
3375 /* no retry on NONBLOCK marked file */
3376 if (ret2 == -EAGAIN && (req->file->f_flags & O_NONBLOCK))
3377 goto done;
fa15bafb 3378 if (!force_nonblock || ret2 != -EAGAIN) {
eefdf30f
JA
3379 /* IOPOLL retry should happen for io-wq threads */
3380 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3381 goto copy_iov;
355afaeb 3382done:
fa15bafb
PB
3383 kiocb_done(kiocb, ret2, cs);
3384 } else {
f67676d1 3385copy_iov:
84216315
JA
3386 /* some cases will consume bytes even on error returns */
3387 iov_iter_revert(iter, iov_count - iov_iter_count(iter));
227c0c96 3388 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
ff6165b2
JA
3389 if (!ret)
3390 return -EAGAIN;
2b188cc1 3391 }
31b51510 3392out_free:
f261c168 3393 /* it's reportedly faster than delegating the null check to kfree() */
252917c3 3394 if (iovec)
6f2cc166 3395 kfree(iovec);
2b188cc1
JA
3396 return ret;
3397}
3398
f2a8d5c7
PB
3399static int __io_splice_prep(struct io_kiocb *req,
3400 const struct io_uring_sqe *sqe)
7d67af2c
PB
3401{
3402 struct io_splice* sp = &req->splice;
3403 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3404 int ret;
3405
3406 if (req->flags & REQ_F_NEED_CLEANUP)
3407 return 0;
3232dd02
PB
3408 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3409 return -EINVAL;
7d67af2c
PB
3410
3411 sp->file_in = NULL;
7d67af2c
PB
3412 sp->len = READ_ONCE(sqe->len);
3413 sp->flags = READ_ONCE(sqe->splice_flags);
3414
3415 if (unlikely(sp->flags & ~valid_flags))
3416 return -EINVAL;
3417
3418 ret = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in), &sp->file_in,
3419 (sp->flags & SPLICE_F_FD_IN_FIXED));
3420 if (ret)
3421 return ret;
3422 req->flags |= REQ_F_NEED_CLEANUP;
3423
7cdaf587
XW
3424 if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3425 /*
3426 * Splice operation will be punted aync, and here need to
3427 * modify io_wq_work.flags, so initialize io_wq_work firstly.
3428 */
3429 io_req_init_async(req);
7d67af2c 3430 req->work.flags |= IO_WQ_WORK_UNBOUND;
7cdaf587 3431 }
7d67af2c
PB
3432
3433 return 0;
3434}
3435
f2a8d5c7
PB
3436static int io_tee_prep(struct io_kiocb *req,
3437 const struct io_uring_sqe *sqe)
3438{
3439 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3440 return -EINVAL;
3441 return __io_splice_prep(req, sqe);
3442}
3443
3444static int io_tee(struct io_kiocb *req, bool force_nonblock)
3445{
3446 struct io_splice *sp = &req->splice;
3447 struct file *in = sp->file_in;
3448 struct file *out = sp->file_out;
3449 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3450 long ret = 0;
3451
3452 if (force_nonblock)
3453 return -EAGAIN;
3454 if (sp->len)
3455 ret = do_tee(in, out, sp->len, flags);
3456
3457 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3458 req->flags &= ~REQ_F_NEED_CLEANUP;
3459
f2a8d5c7
PB
3460 if (ret != sp->len)
3461 req_set_fail_links(req);
e1e16097 3462 io_req_complete(req, ret);
f2a8d5c7
PB
3463 return 0;
3464}
3465
3466static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3467{
3468 struct io_splice* sp = &req->splice;
3469
3470 sp->off_in = READ_ONCE(sqe->splice_off_in);
3471 sp->off_out = READ_ONCE(sqe->off);
3472 return __io_splice_prep(req, sqe);
3473}
3474
014db007 3475static int io_splice(struct io_kiocb *req, bool force_nonblock)
7d67af2c
PB
3476{
3477 struct io_splice *sp = &req->splice;
3478 struct file *in = sp->file_in;
3479 struct file *out = sp->file_out;
3480 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3481 loff_t *poff_in, *poff_out;
c9687426 3482 long ret = 0;
7d67af2c 3483
2fb3e822
PB
3484 if (force_nonblock)
3485 return -EAGAIN;
7d67af2c
PB
3486
3487 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3488 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
c9687426 3489
948a7749 3490 if (sp->len)
c9687426 3491 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
7d67af2c
PB
3492
3493 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3494 req->flags &= ~REQ_F_NEED_CLEANUP;
3495
7d67af2c
PB
3496 if (ret != sp->len)
3497 req_set_fail_links(req);
e1e16097 3498 io_req_complete(req, ret);
7d67af2c
PB
3499 return 0;
3500}
3501
2b188cc1
JA
3502/*
3503 * IORING_OP_NOP just posts a completion event, nothing else.
3504 */
229a7b63 3505static int io_nop(struct io_kiocb *req, struct io_comp_state *cs)
2b188cc1
JA
3506{
3507 struct io_ring_ctx *ctx = req->ctx;
2b188cc1 3508
def596e9
JA
3509 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3510 return -EINVAL;
3511
229a7b63 3512 __io_req_complete(req, 0, 0, cs);
2b188cc1
JA
3513 return 0;
3514}
3515
3529d8c2 3516static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
c992fe29 3517{
6b06314c 3518 struct io_ring_ctx *ctx = req->ctx;
c992fe29 3519
09bb8394
JA
3520 if (!req->file)
3521 return -EBADF;
c992fe29 3522
6b06314c 3523 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
def596e9 3524 return -EINVAL;
edafccee 3525 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
c992fe29
CH
3526 return -EINVAL;
3527
8ed8d3c3
JA
3528 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3529 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3530 return -EINVAL;
3531
3532 req->sync.off = READ_ONCE(sqe->off);
3533 req->sync.len = READ_ONCE(sqe->len);
c992fe29
CH
3534 return 0;
3535}
3536
ac45abc0 3537static int io_fsync(struct io_kiocb *req, bool force_nonblock)
8ed8d3c3 3538{
8ed8d3c3 3539 loff_t end = req->sync.off + req->sync.len;
8ed8d3c3
JA
3540 int ret;
3541
ac45abc0
PB
3542 /* fsync always requires a blocking context */
3543 if (force_nonblock)
3544 return -EAGAIN;
3545
9adbd45d 3546 ret = vfs_fsync_range(req->file, req->sync.off,
8ed8d3c3
JA
3547 end > 0 ? end : LLONG_MAX,
3548 req->sync.flags & IORING_FSYNC_DATASYNC);
3549 if (ret < 0)
3550 req_set_fail_links(req);
e1e16097 3551 io_req_complete(req, ret);
c992fe29
CH
3552 return 0;
3553}
3554
d63d1b5e
JA
3555static int io_fallocate_prep(struct io_kiocb *req,
3556 const struct io_uring_sqe *sqe)
3557{
3558 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3559 return -EINVAL;
3232dd02
PB
3560 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3561 return -EINVAL;
d63d1b5e
JA
3562
3563 req->sync.off = READ_ONCE(sqe->off);
3564 req->sync.len = READ_ONCE(sqe->addr);
3565 req->sync.mode = READ_ONCE(sqe->len);
3566 return 0;
3567}
3568
014db007 3569static int io_fallocate(struct io_kiocb *req, bool force_nonblock)
5d17b4a4 3570{
ac45abc0
PB
3571 int ret;
3572
d63d1b5e 3573 /* fallocate always requiring blocking context */
ac45abc0 3574 if (force_nonblock)
5d17b4a4 3575 return -EAGAIN;
ac45abc0
PB
3576 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3577 req->sync.len);
ac45abc0
PB
3578 if (ret < 0)
3579 req_set_fail_links(req);
e1e16097 3580 io_req_complete(req, ret);
5d17b4a4
JA
3581 return 0;
3582}
3583
ec65fea5 3584static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
b7bb4f7d 3585{
f8748881 3586 const char __user *fname;
15b71abe 3587 int ret;
b7bb4f7d 3588
ec65fea5 3589 if (unlikely(sqe->ioprio || sqe->buf_index))
15b71abe 3590 return -EINVAL;
ec65fea5 3591 if (unlikely(req->flags & REQ_F_FIXED_FILE))
cf3040ca 3592 return -EBADF;
03b1230c 3593
ec65fea5
PB
3594 /* open.how should be already initialised */
3595 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
08a1d26e 3596 req->open.how.flags |= O_LARGEFILE;
3529d8c2 3597
25e72d10
PB
3598 req->open.dfd = READ_ONCE(sqe->fd);
3599 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
f8748881 3600 req->open.filename = getname(fname);
15b71abe
JA
3601 if (IS_ERR(req->open.filename)) {
3602 ret = PTR_ERR(req->open.filename);
3603 req->open.filename = NULL;
3604 return ret;
3605 }
4022e7af 3606 req->open.nofile = rlimit(RLIMIT_NOFILE);
8fef80bf 3607 req->flags |= REQ_F_NEED_CLEANUP;
15b71abe 3608 return 0;
03b1230c
JA
3609}
3610
ec65fea5
PB
3611static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3612{
3613 u64 flags, mode;
3614
4eb8dded
JA
3615 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3616 return -EINVAL;
ec65fea5
PB
3617 if (req->flags & REQ_F_NEED_CLEANUP)
3618 return 0;
3619 mode = READ_ONCE(sqe->len);
3620 flags = READ_ONCE(sqe->open_flags);
3621 req->open.how = build_open_how(flags, mode);
3622 return __io_openat_prep(req, sqe);
3623}
3624
cebdb986 3625static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
aa1fa28f 3626{
cebdb986 3627 struct open_how __user *how;
cebdb986 3628 size_t len;
0fa03c62
JA
3629 int ret;
3630
4eb8dded
JA
3631 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3632 return -EINVAL;
0bdbdd08
PB
3633 if (req->flags & REQ_F_NEED_CLEANUP)
3634 return 0;
cebdb986
JA
3635 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3636 len = READ_ONCE(sqe->len);
cebdb986
JA
3637 if (len < OPEN_HOW_SIZE_VER0)
3638 return -EINVAL;
3529d8c2 3639
cebdb986
JA
3640 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3641 len);
3642 if (ret)
3643 return ret;
3529d8c2 3644
ec65fea5 3645 return __io_openat_prep(req, sqe);
cebdb986
JA
3646}
3647
014db007 3648static int io_openat2(struct io_kiocb *req, bool force_nonblock)
15b71abe
JA
3649{
3650 struct open_flags op;
15b71abe
JA
3651 struct file *file;
3652 int ret;
3653
f86cd20c 3654 if (force_nonblock)
15b71abe 3655 return -EAGAIN;
15b71abe 3656
cebdb986 3657 ret = build_open_flags(&req->open.how, &op);
15b71abe
JA
3658 if (ret)
3659 goto err;
3660
4022e7af 3661 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
15b71abe
JA
3662 if (ret < 0)
3663 goto err;
3664
3665 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3666 if (IS_ERR(file)) {
3667 put_unused_fd(ret);
3668 ret = PTR_ERR(file);
3669 } else {
3670 fsnotify_open(file);
3671 fd_install(ret, file);
3672 }
3673err:
3674 putname(req->open.filename);
8fef80bf 3675 req->flags &= ~REQ_F_NEED_CLEANUP;
15b71abe
JA
3676 if (ret < 0)
3677 req_set_fail_links(req);
e1e16097 3678 io_req_complete(req, ret);
15b71abe
JA
3679 return 0;
3680}
3681
014db007 3682static int io_openat(struct io_kiocb *req, bool force_nonblock)
cebdb986 3683{
014db007 3684 return io_openat2(req, force_nonblock);
cebdb986
JA
3685}
3686
067524e9
JA
3687static int io_remove_buffers_prep(struct io_kiocb *req,
3688 const struct io_uring_sqe *sqe)
3689{
3690 struct io_provide_buf *p = &req->pbuf;
3691 u64 tmp;
3692
3693 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3694 return -EINVAL;
3695
3696 tmp = READ_ONCE(sqe->fd);
3697 if (!tmp || tmp > USHRT_MAX)
3698 return -EINVAL;
3699
3700 memset(p, 0, sizeof(*p));
3701 p->nbufs = tmp;
3702 p->bgid = READ_ONCE(sqe->buf_group);
3703 return 0;
3704}
3705
3706static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3707 int bgid, unsigned nbufs)
3708{
3709 unsigned i = 0;
3710
3711 /* shouldn't happen */
3712 if (!nbufs)
3713 return 0;
3714
3715 /* the head kbuf is the list itself */
3716 while (!list_empty(&buf->list)) {
3717 struct io_buffer *nxt;
3718
3719 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3720 list_del(&nxt->list);
3721 kfree(nxt);
3722 if (++i == nbufs)
3723 return i;
3724 }
3725 i++;
3726 kfree(buf);
3727 idr_remove(&ctx->io_buffer_idr, bgid);
3728
3729 return i;
3730}
3731
229a7b63
JA
3732static int io_remove_buffers(struct io_kiocb *req, bool force_nonblock,
3733 struct io_comp_state *cs)
067524e9
JA
3734{
3735 struct io_provide_buf *p = &req->pbuf;
3736 struct io_ring_ctx *ctx = req->ctx;
3737 struct io_buffer *head;
3738 int ret = 0;
3739
3740 io_ring_submit_lock(ctx, !force_nonblock);
3741
3742 lockdep_assert_held(&ctx->uring_lock);
3743
3744 ret = -ENOENT;
3745 head = idr_find(&ctx->io_buffer_idr, p->bgid);
3746 if (head)
3747 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3748
3749 io_ring_submit_lock(ctx, !force_nonblock);
3750 if (ret < 0)
3751 req_set_fail_links(req);
229a7b63 3752 __io_req_complete(req, ret, 0, cs);
067524e9
JA
3753 return 0;
3754}
3755
ddf0322d
JA
3756static int io_provide_buffers_prep(struct io_kiocb *req,
3757 const struct io_uring_sqe *sqe)
3758{
3759 struct io_provide_buf *p = &req->pbuf;
3760 u64 tmp;
3761
3762 if (sqe->ioprio || sqe->rw_flags)
3763 return -EINVAL;
3764
3765 tmp = READ_ONCE(sqe->fd);
3766 if (!tmp || tmp > USHRT_MAX)
3767 return -E2BIG;
3768 p->nbufs = tmp;
3769 p->addr = READ_ONCE(sqe->addr);
3770 p->len = READ_ONCE(sqe->len);
3771
efe68c1c 3772 if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
ddf0322d
JA
3773 return -EFAULT;
3774
3775 p->bgid = READ_ONCE(sqe->buf_group);
3776 tmp = READ_ONCE(sqe->off);
3777 if (tmp > USHRT_MAX)
3778 return -E2BIG;
3779 p->bid = tmp;
3780 return 0;
3781}
3782
3783static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3784{
3785 struct io_buffer *buf;
3786 u64 addr = pbuf->addr;
3787 int i, bid = pbuf->bid;
3788
3789 for (i = 0; i < pbuf->nbufs; i++) {
3790 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3791 if (!buf)
3792 break;
3793
3794 buf->addr = addr;
3795 buf->len = pbuf->len;
3796 buf->bid = bid;
3797 addr += pbuf->len;
3798 bid++;
3799 if (!*head) {
3800 INIT_LIST_HEAD(&buf->list);
3801 *head = buf;
3802 } else {
3803 list_add_tail(&buf->list, &(*head)->list);
3804 }
3805 }
3806
3807 return i ? i : -ENOMEM;
3808}
3809
229a7b63
JA
3810static int io_provide_buffers(struct io_kiocb *req, bool force_nonblock,
3811 struct io_comp_state *cs)
ddf0322d
JA
3812{
3813 struct io_provide_buf *p = &req->pbuf;
3814 struct io_ring_ctx *ctx = req->ctx;
3815 struct io_buffer *head, *list;
3816 int ret = 0;
3817
3818 io_ring_submit_lock(ctx, !force_nonblock);
3819
3820 lockdep_assert_held(&ctx->uring_lock);
3821
3822 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
3823
3824 ret = io_add_buffers(p, &head);
3825 if (ret < 0)
3826 goto out;
3827
3828 if (!list) {
3829 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
3830 GFP_KERNEL);
3831 if (ret < 0) {
067524e9 3832 __io_remove_buffers(ctx, head, p->bgid, -1U);
ddf0322d
JA
3833 goto out;
3834 }
3835 }
3836out:
3837 io_ring_submit_unlock(ctx, !force_nonblock);
3838 if (ret < 0)
3839 req_set_fail_links(req);
229a7b63 3840 __io_req_complete(req, ret, 0, cs);
ddf0322d 3841 return 0;
cebdb986
JA
3842}
3843
3e4827b0
JA
3844static int io_epoll_ctl_prep(struct io_kiocb *req,
3845 const struct io_uring_sqe *sqe)
3846{
3847#if defined(CONFIG_EPOLL)
3848 if (sqe->ioprio || sqe->buf_index)
3849 return -EINVAL;
6ca56f84 3850 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
3232dd02 3851 return -EINVAL;
3e4827b0
JA
3852
3853 req->epoll.epfd = READ_ONCE(sqe->fd);
3854 req->epoll.op = READ_ONCE(sqe->len);
3855 req->epoll.fd = READ_ONCE(sqe->off);
3856
3857 if (ep_op_has_event(req->epoll.op)) {
3858 struct epoll_event __user *ev;
3859
3860 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
3861 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
3862 return -EFAULT;
3863 }
3864
3865 return 0;
3866#else
3867 return -EOPNOTSUPP;
3868#endif
3869}
3870
229a7b63
JA
3871static int io_epoll_ctl(struct io_kiocb *req, bool force_nonblock,
3872 struct io_comp_state *cs)
3e4827b0
JA
3873{
3874#if defined(CONFIG_EPOLL)
3875 struct io_epoll *ie = &req->epoll;
3876 int ret;
3877
3878 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
3879 if (force_nonblock && ret == -EAGAIN)
3880 return -EAGAIN;
3881
3882 if (ret < 0)
3883 req_set_fail_links(req);
229a7b63 3884 __io_req_complete(req, ret, 0, cs);
3e4827b0
JA
3885 return 0;
3886#else
3887 return -EOPNOTSUPP;
3888#endif
3889}
3890
c1ca757b
JA
3891static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3892{
3893#if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3894 if (sqe->ioprio || sqe->buf_index || sqe->off)
3895 return -EINVAL;
3232dd02
PB
3896 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3897 return -EINVAL;
c1ca757b
JA
3898
3899 req->madvise.addr = READ_ONCE(sqe->addr);
3900 req->madvise.len = READ_ONCE(sqe->len);
3901 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
3902 return 0;
3903#else
3904 return -EOPNOTSUPP;
3905#endif
3906}
3907
014db007 3908static int io_madvise(struct io_kiocb *req, bool force_nonblock)
c1ca757b
JA
3909{
3910#if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3911 struct io_madvise *ma = &req->madvise;
3912 int ret;
3913
3914 if (force_nonblock)
3915 return -EAGAIN;
3916
3917 ret = do_madvise(ma->addr, ma->len, ma->advice);
3918 if (ret < 0)
3919 req_set_fail_links(req);
e1e16097 3920 io_req_complete(req, ret);
c1ca757b
JA
3921 return 0;
3922#else
3923 return -EOPNOTSUPP;
3924#endif
3925}
3926
4840e418
JA
3927static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3928{
3929 if (sqe->ioprio || sqe->buf_index || sqe->addr)
3930 return -EINVAL;
3232dd02
PB
3931 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3932 return -EINVAL;
4840e418
JA
3933
3934 req->fadvise.offset = READ_ONCE(sqe->off);
3935 req->fadvise.len = READ_ONCE(sqe->len);
3936 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
3937 return 0;
3938}
3939
014db007 3940static int io_fadvise(struct io_kiocb *req, bool force_nonblock)
4840e418
JA
3941{
3942 struct io_fadvise *fa = &req->fadvise;
3943 int ret;
3944
3e69426d
JA
3945 if (force_nonblock) {
3946 switch (fa->advice) {
3947 case POSIX_FADV_NORMAL:
3948 case POSIX_FADV_RANDOM:
3949 case POSIX_FADV_SEQUENTIAL:
3950 break;
3951 default:
3952 return -EAGAIN;
3953 }
3954 }
4840e418
JA
3955
3956 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
3957 if (ret < 0)
3958 req_set_fail_links(req);
e1e16097 3959 io_req_complete(req, ret);
4840e418
JA
3960 return 0;
3961}
3962
eddc7ef5
JA
3963static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3964{
6ca56f84 3965 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
3232dd02 3966 return -EINVAL;
eddc7ef5
JA
3967 if (sqe->ioprio || sqe->buf_index)
3968 return -EINVAL;
9c280f90 3969 if (req->flags & REQ_F_FIXED_FILE)
cf3040ca 3970 return -EBADF;
eddc7ef5 3971
1d9e1288
BM
3972 req->statx.dfd = READ_ONCE(sqe->fd);
3973 req->statx.mask = READ_ONCE(sqe->len);
e62753e4 3974 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
1d9e1288
BM
3975 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3976 req->statx.flags = READ_ONCE(sqe->statx_flags);
eddc7ef5
JA
3977
3978 return 0;
3979}
3980
014db007 3981static int io_statx(struct io_kiocb *req, bool force_nonblock)
eddc7ef5 3982{
1d9e1288 3983 struct io_statx *ctx = &req->statx;
eddc7ef5
JA
3984 int ret;
3985
5b0bbee4
JA
3986 if (force_nonblock) {
3987 /* only need file table for an actual valid fd */
3988 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
3989 req->flags |= REQ_F_NO_FILE_TABLE;
eddc7ef5 3990 return -EAGAIN;
5b0bbee4 3991 }
eddc7ef5 3992
e62753e4
BM
3993 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
3994 ctx->buffer);
eddc7ef5 3995
eddc7ef5
JA
3996 if (ret < 0)
3997 req_set_fail_links(req);
e1e16097 3998 io_req_complete(req, ret);
eddc7ef5
JA
3999 return 0;
4000}
4001
b5dba59e
JA
4002static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4003{
4004 /*
4005 * If we queue this for async, it must not be cancellable. That would
7cdaf587
XW
4006 * leave the 'file' in an undeterminate state, and here need to modify
4007 * io_wq_work.flags, so initialize io_wq_work firstly.
b5dba59e 4008 */
7cdaf587 4009 io_req_init_async(req);
b5dba59e
JA
4010 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
4011
3232dd02
PB
4012 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4013 return -EINVAL;
b5dba59e
JA
4014 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4015 sqe->rw_flags || sqe->buf_index)
4016 return -EINVAL;
9c280f90 4017 if (req->flags & REQ_F_FIXED_FILE)
cf3040ca 4018 return -EBADF;
b5dba59e
JA
4019
4020 req->close.fd = READ_ONCE(sqe->fd);
0f212204 4021 if ((req->file && req->file->f_op == &io_uring_fops))
fd2206e4 4022 return -EBADF;
b5dba59e 4023
3af73b28 4024 req->close.put_file = NULL;
b5dba59e 4025 return 0;
b5dba59e
JA
4026}
4027
229a7b63
JA
4028static int io_close(struct io_kiocb *req, bool force_nonblock,
4029 struct io_comp_state *cs)
b5dba59e 4030{
3af73b28 4031 struct io_close *close = &req->close;
b5dba59e
JA
4032 int ret;
4033
3af73b28
PB
4034 /* might be already done during nonblock submission */
4035 if (!close->put_file) {
4036 ret = __close_fd_get_file(close->fd, &close->put_file);
4037 if (ret < 0)
4038 return (ret == -ENOENT) ? -EBADF : ret;
4039 }
b5dba59e
JA
4040
4041 /* if the file has a flush method, be safe and punt to async */
3af73b28 4042 if (close->put_file->f_op->flush && force_nonblock) {
24c74678
PB
4043 /* was never set, but play safe */
4044 req->flags &= ~REQ_F_NOWAIT;
0bf0eefd 4045 /* avoid grabbing files - we don't need the files */
24c74678 4046 req->flags |= REQ_F_NO_FILE_TABLE;
0bf0eefd 4047 return -EAGAIN;
a2100672 4048 }
b5dba59e 4049
3af73b28
PB
4050 /* No ->flush() or already async, safely close from here */
4051 ret = filp_close(close->put_file, req->work.files);
4052 if (ret < 0)
4053 req_set_fail_links(req);
3af73b28
PB
4054 fput(close->put_file);
4055 close->put_file = NULL;
229a7b63 4056 __io_req_complete(req, ret, 0, cs);
1a417f4e 4057 return 0;
b5dba59e
JA
4058}
4059
3529d8c2 4060static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5d17b4a4
JA
4061{
4062 struct io_ring_ctx *ctx = req->ctx;
5d17b4a4
JA
4063
4064 if (!req->file)
4065 return -EBADF;
5d17b4a4
JA
4066
4067 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4068 return -EINVAL;
4069 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4070 return -EINVAL;
4071
8ed8d3c3
JA
4072 req->sync.off = READ_ONCE(sqe->off);
4073 req->sync.len = READ_ONCE(sqe->len);
4074 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
8ed8d3c3
JA
4075 return 0;
4076}
4077
ac45abc0 4078static int io_sync_file_range(struct io_kiocb *req, bool force_nonblock)
8ed8d3c3 4079{
8ed8d3c3
JA
4080 int ret;
4081
ac45abc0
PB
4082 /* sync_file_range always requires a blocking context */
4083 if (force_nonblock)
4084 return -EAGAIN;
4085
9adbd45d 4086 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
8ed8d3c3
JA
4087 req->sync.flags);
4088 if (ret < 0)
4089 req_set_fail_links(req);
e1e16097 4090 io_req_complete(req, ret);
5d17b4a4
JA
4091 return 0;
4092}
4093
469956e8 4094#if defined(CONFIG_NET)
02d27d89
PB
4095static int io_setup_async_msg(struct io_kiocb *req,
4096 struct io_async_msghdr *kmsg)
4097{
4098 if (req->io)
4099 return -EAGAIN;
4100 if (io_alloc_async_ctx(req)) {
4101 if (kmsg->iov != kmsg->fast_iov)
4102 kfree(kmsg->iov);
4103 return -ENOMEM;
4104 }
4105 req->flags |= REQ_F_NEED_CLEANUP;
4106 memcpy(&req->io->msg, kmsg, sizeof(*kmsg));
4107 return -EAGAIN;
4108}
4109
2ae523ed
PB
4110static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4111 struct io_async_msghdr *iomsg)
4112{
4113 iomsg->iov = iomsg->fast_iov;
4114 iomsg->msg.msg_name = &iomsg->addr;
4115 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4116 req->sr_msg.msg_flags, &iomsg->iov);
4117}
4118
3529d8c2 4119static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
03b1230c 4120{
e47293fd 4121 struct io_sr_msg *sr = &req->sr_msg;
3529d8c2 4122 struct io_async_ctx *io = req->io;
99bc4c38 4123 int ret;
03b1230c 4124
d2b6f48b
PB
4125 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4126 return -EINVAL;
4127
e47293fd 4128 sr->msg_flags = READ_ONCE(sqe->msg_flags);
270a5940 4129 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
fddaface 4130 sr->len = READ_ONCE(sqe->len);
3529d8c2 4131
d8768362
JA
4132#ifdef CONFIG_COMPAT
4133 if (req->ctx->compat)
4134 sr->msg_flags |= MSG_CMSG_COMPAT;
4135#endif
4136
fddaface 4137 if (!io || req->opcode == IORING_OP_SEND)
3529d8c2 4138 return 0;
5f798bea
PB
4139 /* iovec is already imported */
4140 if (req->flags & REQ_F_NEED_CLEANUP)
4141 return 0;
3529d8c2 4142
2ae523ed 4143 ret = io_sendmsg_copy_hdr(req, &io->msg);
99bc4c38
PB
4144 if (!ret)
4145 req->flags |= REQ_F_NEED_CLEANUP;
4146 return ret;
03b1230c
JA
4147}
4148
229a7b63
JA
4149static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
4150 struct io_comp_state *cs)
aa1fa28f 4151{
6b754c8b 4152 struct io_async_msghdr iomsg, *kmsg;
0fa03c62 4153 struct socket *sock;
7a7cacba 4154 unsigned flags;
0fa03c62
JA
4155 int ret;
4156
0fa03c62 4157 sock = sock_from_file(req->file, &ret);
7a7cacba
PB
4158 if (unlikely(!sock))
4159 return ret;
3529d8c2 4160
7a7cacba
PB
4161 if (req->io) {
4162 kmsg = &req->io->msg;
4163 kmsg->msg.msg_name = &req->io->msg.addr;
4164 /* if iov is set, it's allocated already */
4165 if (!kmsg->iov)
4166 kmsg->iov = kmsg->fast_iov;
4167 kmsg->msg.msg_iter.iov = kmsg->iov;
4168 } else {
4169 ret = io_sendmsg_copy_hdr(req, &iomsg);
4170 if (ret)
4171 return ret;
4172 kmsg = &iomsg;
0fa03c62 4173 }
0fa03c62 4174
7a7cacba
PB
4175 flags = req->sr_msg.msg_flags;
4176 if (flags & MSG_DONTWAIT)
4177 req->flags |= REQ_F_NOWAIT;
4178 else if (force_nonblock)
4179 flags |= MSG_DONTWAIT;
e47293fd 4180
7a7cacba
PB
4181 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4182 if (force_nonblock && ret == -EAGAIN)
4183 return io_setup_async_msg(req, kmsg);
4184 if (ret == -ERESTARTSYS)
4185 ret = -EINTR;
0fa03c62 4186
6b754c8b 4187 if (kmsg->iov != kmsg->fast_iov)
0b416c3e 4188 kfree(kmsg->iov);
99bc4c38 4189 req->flags &= ~REQ_F_NEED_CLEANUP;
4e88d6e7
JA
4190 if (ret < 0)
4191 req_set_fail_links(req);
229a7b63 4192 __io_req_complete(req, ret, 0, cs);
5d17b4a4 4193 return 0;
03b1230c 4194}
aa1fa28f 4195
229a7b63
JA
4196static int io_send(struct io_kiocb *req, bool force_nonblock,
4197 struct io_comp_state *cs)
fddaface 4198{
7a7cacba
PB
4199 struct io_sr_msg *sr = &req->sr_msg;
4200 struct msghdr msg;
4201 struct iovec iov;
fddaface 4202 struct socket *sock;
7a7cacba 4203 unsigned flags;
fddaface
JA
4204 int ret;
4205
fddaface 4206 sock = sock_from_file(req->file, &ret);
7a7cacba
PB
4207 if (unlikely(!sock))
4208 return ret;
fddaface 4209
7a7cacba
PB
4210 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4211 if (unlikely(ret))
14c32eee 4212 return ret;;
fddaface 4213
7a7cacba
PB
4214 msg.msg_name = NULL;
4215 msg.msg_control = NULL;
4216 msg.msg_controllen = 0;
4217 msg.msg_namelen = 0;
fddaface 4218
7a7cacba
PB
4219 flags = req->sr_msg.msg_flags;
4220 if (flags & MSG_DONTWAIT)
4221 req->flags |= REQ_F_NOWAIT;
4222 else if (force_nonblock)
4223 flags |= MSG_DONTWAIT;
fddaface 4224
7a7cacba
PB
4225 msg.msg_flags = flags;
4226 ret = sock_sendmsg(sock, &msg);
4227 if (force_nonblock && ret == -EAGAIN)
4228 return -EAGAIN;
4229 if (ret == -ERESTARTSYS)
4230 ret = -EINTR;
fddaface 4231
fddaface
JA
4232 if (ret < 0)
4233 req_set_fail_links(req);
229a7b63 4234 __io_req_complete(req, ret, 0, cs);
fddaface 4235 return 0;
fddaface
JA
4236}
4237
1400e697
PB
4238static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4239 struct io_async_msghdr *iomsg)
52de1fe1
JA
4240{
4241 struct io_sr_msg *sr = &req->sr_msg;
4242 struct iovec __user *uiov;
4243 size_t iov_len;
4244 int ret;
4245
1400e697
PB
4246 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4247 &iomsg->uaddr, &uiov, &iov_len);
52de1fe1
JA
4248 if (ret)
4249 return ret;
4250
4251 if (req->flags & REQ_F_BUFFER_SELECT) {
4252 if (iov_len > 1)
4253 return -EINVAL;
1400e697 4254 if (copy_from_user(iomsg->iov, uiov, sizeof(*uiov)))
52de1fe1 4255 return -EFAULT;
1400e697
PB
4256 sr->len = iomsg->iov[0].iov_len;
4257 iov_iter_init(&iomsg->msg.msg_iter, READ, iomsg->iov, 1,
52de1fe1 4258 sr->len);
1400e697 4259 iomsg->iov = NULL;
52de1fe1
JA
4260 } else {
4261 ret = import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
1400e697 4262 &iomsg->iov, &iomsg->msg.msg_iter);
52de1fe1
JA
4263 if (ret > 0)
4264 ret = 0;
4265 }
4266
4267 return ret;
4268}
4269
4270#ifdef CONFIG_COMPAT
4271static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
1400e697 4272 struct io_async_msghdr *iomsg)
52de1fe1
JA
4273{
4274 struct compat_msghdr __user *msg_compat;
4275 struct io_sr_msg *sr = &req->sr_msg;
4276 struct compat_iovec __user *uiov;
4277 compat_uptr_t ptr;
4278 compat_size_t len;
4279 int ret;
4280
270a5940 4281 msg_compat = (struct compat_msghdr __user *) sr->umsg;
1400e697 4282 ret = __get_compat_msghdr(&iomsg->msg, msg_compat, &iomsg->uaddr,
52de1fe1
JA
4283 &ptr, &len);
4284 if (ret)
4285 return ret;
4286
4287 uiov = compat_ptr(ptr);
4288 if (req->flags & REQ_F_BUFFER_SELECT) {
4289 compat_ssize_t clen;
4290
4291 if (len > 1)
4292 return -EINVAL;
4293 if (!access_ok(uiov, sizeof(*uiov)))
4294 return -EFAULT;
4295 if (__get_user(clen, &uiov->iov_len))
4296 return -EFAULT;
4297 if (clen < 0)
4298 return -EINVAL;
1400e697
PB
4299 sr->len = iomsg->iov[0].iov_len;
4300 iomsg->iov = NULL;
52de1fe1
JA
4301 } else {
4302 ret = compat_import_iovec(READ, uiov, len, UIO_FASTIOV,
1400e697
PB
4303 &iomsg->iov,
4304 &iomsg->msg.msg_iter);
52de1fe1
JA
4305 if (ret < 0)
4306 return ret;
4307 }
4308
4309 return 0;
4310}
4311#endif
4312
1400e697
PB
4313static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4314 struct io_async_msghdr *iomsg)
52de1fe1 4315{
1400e697
PB
4316 iomsg->msg.msg_name = &iomsg->addr;
4317 iomsg->iov = iomsg->fast_iov;
52de1fe1
JA
4318
4319#ifdef CONFIG_COMPAT
4320 if (req->ctx->compat)
1400e697 4321 return __io_compat_recvmsg_copy_hdr(req, iomsg);
fddaface 4322#endif
52de1fe1 4323
1400e697 4324 return __io_recvmsg_copy_hdr(req, iomsg);
52de1fe1
JA
4325}
4326
bcda7baa 4327static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
7fbb1b54 4328 bool needs_lock)
bcda7baa
JA
4329{
4330 struct io_sr_msg *sr = &req->sr_msg;
4331 struct io_buffer *kbuf;
4332
bcda7baa
JA
4333 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4334 if (IS_ERR(kbuf))
4335 return kbuf;
4336
4337 sr->kbuf = kbuf;
4338 req->flags |= REQ_F_BUFFER_SELECTED;
bcda7baa 4339 return kbuf;
fddaface
JA
4340}
4341
7fbb1b54
PB
4342static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4343{
4344 return io_put_kbuf(req, req->sr_msg.kbuf);
4345}
4346
3529d8c2
JA
4347static int io_recvmsg_prep(struct io_kiocb *req,
4348 const struct io_uring_sqe *sqe)
aa1fa28f 4349{
e47293fd 4350 struct io_sr_msg *sr = &req->sr_msg;
3529d8c2 4351 struct io_async_ctx *io = req->io;
99bc4c38 4352 int ret;
3529d8c2 4353
d2b6f48b
PB
4354 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4355 return -EINVAL;
4356
3529d8c2 4357 sr->msg_flags = READ_ONCE(sqe->msg_flags);
270a5940 4358 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
0b7b21e4 4359 sr->len = READ_ONCE(sqe->len);
bcda7baa 4360 sr->bgid = READ_ONCE(sqe->buf_group);
06b76d44 4361
d8768362
JA
4362#ifdef CONFIG_COMPAT
4363 if (req->ctx->compat)
4364 sr->msg_flags |= MSG_CMSG_COMPAT;
4365#endif
4366
fddaface 4367 if (!io || req->opcode == IORING_OP_RECV)
06b76d44 4368 return 0;
5f798bea
PB
4369 /* iovec is already imported */
4370 if (req->flags & REQ_F_NEED_CLEANUP)
4371 return 0;
03b1230c 4372
1400e697 4373 ret = io_recvmsg_copy_hdr(req, &io->msg);
99bc4c38
PB
4374 if (!ret)
4375 req->flags |= REQ_F_NEED_CLEANUP;
4376 return ret;
aa1fa28f
JA
4377}
4378
229a7b63
JA
4379static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
4380 struct io_comp_state *cs)
aa1fa28f 4381{
6b754c8b 4382 struct io_async_msghdr iomsg, *kmsg;
03b1230c 4383 struct socket *sock;
7fbb1b54 4384 struct io_buffer *kbuf;
7a7cacba 4385 unsigned flags;
52de1fe1 4386 int ret, cflags = 0;
03b1230c 4387
03b1230c 4388 sock = sock_from_file(req->file, &ret);
7a7cacba
PB
4389 if (unlikely(!sock))
4390 return ret;
3529d8c2 4391
7a7cacba
PB
4392 if (req->io) {
4393 kmsg = &req->io->msg;
4394 kmsg->msg.msg_name = &req->io->msg.addr;
4395 /* if iov is set, it's allocated already */
4396 if (!kmsg->iov)
4397 kmsg->iov = kmsg->fast_iov;
4398 kmsg->msg.msg_iter.iov = kmsg->iov;
4399 } else {
4400 ret = io_recvmsg_copy_hdr(req, &iomsg);
4401 if (ret)
681fda8d 4402 return ret;
7a7cacba
PB
4403 kmsg = &iomsg;
4404 }
03b1230c 4405
bc02ef33 4406 if (req->flags & REQ_F_BUFFER_SELECT) {
7fbb1b54 4407 kbuf = io_recv_buffer_select(req, !force_nonblock);
bc02ef33 4408 if (IS_ERR(kbuf))
52de1fe1 4409 return PTR_ERR(kbuf);
7a7cacba
PB
4410 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4411 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->iov,
4412 1, req->sr_msg.len);
4413 }
52de1fe1 4414
7a7cacba
PB
4415 flags = req->sr_msg.msg_flags;
4416 if (flags & MSG_DONTWAIT)
4417 req->flags |= REQ_F_NOWAIT;
4418 else if (force_nonblock)
4419 flags |= MSG_DONTWAIT;
e47293fd 4420
7a7cacba
PB
4421 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4422 kmsg->uaddr, flags);
0e1b6fe3
PB
4423 if (force_nonblock && ret == -EAGAIN)
4424 return io_setup_async_msg(req, kmsg);
7a7cacba
PB
4425 if (ret == -ERESTARTSYS)
4426 ret = -EINTR;
03b1230c 4427
7fbb1b54
PB
4428 if (req->flags & REQ_F_BUFFER_SELECTED)
4429 cflags = io_put_recv_kbuf(req);
6b754c8b 4430 if (kmsg->iov != kmsg->fast_iov)
0b416c3e 4431 kfree(kmsg->iov);
99bc4c38 4432 req->flags &= ~REQ_F_NEED_CLEANUP;
4e88d6e7
JA
4433 if (ret < 0)
4434 req_set_fail_links(req);
229a7b63 4435 __io_req_complete(req, ret, cflags, cs);
03b1230c 4436 return 0;
0fa03c62 4437}
5d17b4a4 4438
229a7b63
JA
4439static int io_recv(struct io_kiocb *req, bool force_nonblock,
4440 struct io_comp_state *cs)
fddaface 4441{
6b754c8b 4442 struct io_buffer *kbuf;
7a7cacba
PB
4443 struct io_sr_msg *sr = &req->sr_msg;
4444 struct msghdr msg;
4445 void __user *buf = sr->buf;
fddaface 4446 struct socket *sock;
7a7cacba
PB
4447 struct iovec iov;
4448 unsigned flags;
bcda7baa 4449 int ret, cflags = 0;
fddaface 4450
fddaface 4451 sock = sock_from_file(req->file, &ret);
7a7cacba
PB
4452 if (unlikely(!sock))
4453 return ret;
fddaface 4454
bc02ef33 4455 if (req->flags & REQ_F_BUFFER_SELECT) {
7fbb1b54 4456 kbuf = io_recv_buffer_select(req, !force_nonblock);
bcda7baa
JA
4457 if (IS_ERR(kbuf))
4458 return PTR_ERR(kbuf);
7a7cacba 4459 buf = u64_to_user_ptr(kbuf->addr);
bc02ef33 4460 }
bcda7baa 4461
7a7cacba 4462 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
14c32eee
PB
4463 if (unlikely(ret))
4464 goto out_free;
fddaface 4465
7a7cacba
PB
4466 msg.msg_name = NULL;
4467 msg.msg_control = NULL;
4468 msg.msg_controllen = 0;
4469 msg.msg_namelen = 0;
4470 msg.msg_iocb = NULL;
4471 msg.msg_flags = 0;
fddaface 4472
7a7cacba
PB
4473 flags = req->sr_msg.msg_flags;
4474 if (flags & MSG_DONTWAIT)
4475 req->flags |= REQ_F_NOWAIT;
4476 else if (force_nonblock)
4477 flags |= MSG_DONTWAIT;
4478
4479 ret = sock_recvmsg(sock, &msg, flags);
4480 if (force_nonblock && ret == -EAGAIN)
4481 return -EAGAIN;
4482 if (ret == -ERESTARTSYS)
4483 ret = -EINTR;
14c32eee 4484out_free:
7fbb1b54
PB
4485 if (req->flags & REQ_F_BUFFER_SELECTED)
4486 cflags = io_put_recv_kbuf(req);
fddaface
JA
4487 if (ret < 0)
4488 req_set_fail_links(req);
229a7b63 4489 __io_req_complete(req, ret, cflags, cs);
fddaface 4490 return 0;
fddaface
JA
4491}
4492
3529d8c2 4493static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
17f2fe35 4494{
8ed8d3c3
JA
4495 struct io_accept *accept = &req->accept;
4496
17f2fe35
JA
4497 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4498 return -EINVAL;
8042d6ce 4499 if (sqe->ioprio || sqe->len || sqe->buf_index)
17f2fe35
JA
4500 return -EINVAL;
4501
d55e5f5b
JA
4502 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4503 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
8ed8d3c3 4504 accept->flags = READ_ONCE(sqe->accept_flags);
09952e3e 4505 accept->nofile = rlimit(RLIMIT_NOFILE);
8ed8d3c3 4506 return 0;
8ed8d3c3 4507}
17f2fe35 4508
229a7b63
JA
4509static int io_accept(struct io_kiocb *req, bool force_nonblock,
4510 struct io_comp_state *cs)
8ed8d3c3
JA
4511{
4512 struct io_accept *accept = &req->accept;
ac45abc0 4513 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
8ed8d3c3
JA
4514 int ret;
4515
e697deed
JX
4516 if (req->file->f_flags & O_NONBLOCK)
4517 req->flags |= REQ_F_NOWAIT;
4518
8ed8d3c3 4519 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
09952e3e
JA
4520 accept->addr_len, accept->flags,
4521 accept->nofile);
8ed8d3c3 4522 if (ret == -EAGAIN && force_nonblock)
17f2fe35 4523 return -EAGAIN;
ac45abc0
PB
4524 if (ret < 0) {
4525 if (ret == -ERESTARTSYS)
4526 ret = -EINTR;
4e88d6e7 4527 req_set_fail_links(req);
ac45abc0 4528 }
229a7b63 4529 __io_req_complete(req, ret, 0, cs);
17f2fe35 4530 return 0;
8ed8d3c3
JA
4531}
4532
3529d8c2 4533static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
f499a021 4534{
3529d8c2
JA
4535 struct io_connect *conn = &req->connect;
4536 struct io_async_ctx *io = req->io;
f499a021 4537
3fbb51c1
JA
4538 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4539 return -EINVAL;
4540 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4541 return -EINVAL;
4542
3529d8c2
JA
4543 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4544 conn->addr_len = READ_ONCE(sqe->addr2);
4545
4546 if (!io)
4547 return 0;
4548
4549 return move_addr_to_kernel(conn->addr, conn->addr_len,
3fbb51c1 4550 &io->connect.address);
f499a021
JA
4551}
4552
229a7b63
JA
4553static int io_connect(struct io_kiocb *req, bool force_nonblock,
4554 struct io_comp_state *cs)
f8e85cf2 4555{
f499a021 4556 struct io_async_ctx __io, *io;
f8e85cf2 4557 unsigned file_flags;
3fbb51c1 4558 int ret;
f8e85cf2 4559
f499a021
JA
4560 if (req->io) {
4561 io = req->io;
4562 } else {
3529d8c2
JA
4563 ret = move_addr_to_kernel(req->connect.addr,
4564 req->connect.addr_len,
4565 &__io.connect.address);
f499a021
JA
4566 if (ret)
4567 goto out;
4568 io = &__io;
4569 }
4570
3fbb51c1
JA
4571 file_flags = force_nonblock ? O_NONBLOCK : 0;
4572
4573 ret = __sys_connect_file(req->file, &io->connect.address,
4574 req->connect.addr_len, file_flags);
87f80d62 4575 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
b7bb4f7d
JA
4576 if (req->io)
4577 return -EAGAIN;
4578 if (io_alloc_async_ctx(req)) {
f499a021
JA
4579 ret = -ENOMEM;
4580 goto out;
4581 }
b7bb4f7d 4582 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
f8e85cf2 4583 return -EAGAIN;
f499a021 4584 }
f8e85cf2
JA
4585 if (ret == -ERESTARTSYS)
4586 ret = -EINTR;
f499a021 4587out:
4e88d6e7
JA
4588 if (ret < 0)
4589 req_set_fail_links(req);
229a7b63 4590 __io_req_complete(req, ret, 0, cs);
f8e85cf2 4591 return 0;
469956e8
Y
4592}
4593#else /* !CONFIG_NET */
4594static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4595{
f8e85cf2 4596 return -EOPNOTSUPP;
f8e85cf2
JA
4597}
4598
1e16c2f9
RD
4599static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
4600 struct io_comp_state *cs)
469956e8
Y
4601{
4602 return -EOPNOTSUPP;
4603}
4604
1e16c2f9
RD
4605static int io_send(struct io_kiocb *req, bool force_nonblock,
4606 struct io_comp_state *cs)
469956e8
Y
4607{
4608 return -EOPNOTSUPP;
4609}
4610
4611static int io_recvmsg_prep(struct io_kiocb *req,
4612 const struct io_uring_sqe *sqe)
4613{
4614 return -EOPNOTSUPP;
4615}
4616
1e16c2f9
RD
4617static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
4618 struct io_comp_state *cs)
469956e8
Y
4619{
4620 return -EOPNOTSUPP;
4621}
4622
1e16c2f9
RD
4623static int io_recv(struct io_kiocb *req, bool force_nonblock,
4624 struct io_comp_state *cs)
469956e8
Y
4625{
4626 return -EOPNOTSUPP;
4627}
4628
4629static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4630{
4631 return -EOPNOTSUPP;
4632}
4633
1e16c2f9
RD
4634static int io_accept(struct io_kiocb *req, bool force_nonblock,
4635 struct io_comp_state *cs)
469956e8
Y
4636{
4637 return -EOPNOTSUPP;
4638}
ce593a6c 4639
469956e8
Y
4640static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4641{
4642 return -EOPNOTSUPP;
4643}
4644
1e16c2f9
RD
4645static int io_connect(struct io_kiocb *req, bool force_nonblock,
4646 struct io_comp_state *cs)
469956e8 4647{
f8e85cf2 4648 return -EOPNOTSUPP;
ce593a6c 4649}
469956e8 4650#endif /* CONFIG_NET */
f8e85cf2 4651
d7718a9d
JA
4652struct io_poll_table {
4653 struct poll_table_struct pt;
4654 struct io_kiocb *req;
4655 int error;
4656};
ce593a6c 4657
d7718a9d
JA
4658static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4659 __poll_t mask, task_work_func_t func)
4660{
fd7d6de2 4661 bool twa_signal_ok;
aa96bf8a 4662 int ret;
d7718a9d
JA
4663
4664 /* for instances that support it check for an event match first: */
4665 if (mask && !(mask & poll->events))
4666 return 0;
4667
4668 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4669
4670 list_del_init(&poll->wait.entry);
4671
d7718a9d
JA
4672 req->result = mask;
4673 init_task_work(&req->task_work, func);
6d816e08
JA
4674 percpu_ref_get(&req->ctx->refs);
4675
fd7d6de2
JA
4676 /*
4677 * If we using the signalfd wait_queue_head for this wakeup, then
4678 * it's not safe to use TWA_SIGNAL as we could be recursing on the
4679 * tsk->sighand->siglock on doing the wakeup. Should not be needed
4680 * either, as the normal wakeup will suffice.
4681 */
4682 twa_signal_ok = (poll->head != &req->task->sighand->signalfd_wqh);
4683
d7718a9d 4684 /*
e3aabf95
JA
4685 * If this fails, then the task is exiting. When a task exits, the
4686 * work gets canceled, so just cancel this request as well instead
4687 * of executing it. We can't safely execute it anyway, as we may not
4688 * have the needed state needed for it anyway.
d7718a9d 4689 */
fd7d6de2 4690 ret = io_req_task_work_add(req, &req->task_work, twa_signal_ok);
aa96bf8a 4691 if (unlikely(ret)) {
c2c4c83c
JA
4692 struct task_struct *tsk;
4693
e3aabf95 4694 WRITE_ONCE(poll->canceled, true);
aa96bf8a 4695 tsk = io_wq_get_task(req->ctx->io_wq);
ce593a6c
JA
4696 task_work_add(tsk, &req->task_work, 0);
4697 wake_up_process(tsk);
aa96bf8a 4698 }
d7718a9d
JA
4699 return 1;
4700}
4701
74ce6ce4
JA
4702static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4703 __acquires(&req->ctx->completion_lock)
4704{
4705 struct io_ring_ctx *ctx = req->ctx;
4706
4707 if (!req->result && !READ_ONCE(poll->canceled)) {
4708 struct poll_table_struct pt = { ._key = poll->events };
4709
4710 req->result = vfs_poll(req->file, &pt) & poll->events;
4711 }
4712
4713 spin_lock_irq(&ctx->completion_lock);
4714 if (!req->result && !READ_ONCE(poll->canceled)) {
4715 add_wait_queue(poll->head, &poll->wait);
4716 return true;
4717 }
4718
4719 return false;
4720}
4721
d4e7cd36 4722static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
18bceab1 4723{
d4e7cd36
JA
4724 /* pure poll stashes this in ->io, poll driven retry elsewhere */
4725 if (req->opcode == IORING_OP_POLL_ADD)
4726 return (struct io_poll_iocb *) req->io;
4727 return req->apoll->double_poll;
4728}
4729
4730static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4731{
4732 if (req->opcode == IORING_OP_POLL_ADD)
4733 return &req->poll;
4734 return &req->apoll->poll;
4735}
4736
4737static void io_poll_remove_double(struct io_kiocb *req)
4738{
4739 struct io_poll_iocb *poll = io_poll_get_double(req);
18bceab1
JA
4740
4741 lockdep_assert_held(&req->ctx->completion_lock);
4742
4743 if (poll && poll->head) {
4744 struct wait_queue_head *head = poll->head;
4745
4746 spin_lock(&head->lock);
4747 list_del_init(&poll->wait.entry);
4748 if (poll->wait.private)
4749 refcount_dec(&req->refs);
4750 poll->head = NULL;
4751 spin_unlock(&head->lock);
4752 }
4753}
4754
4755static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
4756{
4757 struct io_ring_ctx *ctx = req->ctx;
4758
d4e7cd36 4759 io_poll_remove_double(req);
18bceab1
JA
4760 req->poll.done = true;
4761 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
4762 io_commit_cqring(ctx);
4763}
4764
4765static void io_poll_task_handler(struct io_kiocb *req, struct io_kiocb **nxt)
4766{
4767 struct io_ring_ctx *ctx = req->ctx;
4768
4769 if (io_poll_rewait(req, &req->poll)) {
4770 spin_unlock_irq(&ctx->completion_lock);
4771 return;
4772 }
4773
4774 hash_del(&req->hash_node);
4775 io_poll_complete(req, req->result, 0);
4776 req->flags |= REQ_F_COMP_LOCKED;
9b5f7bd9 4777 *nxt = io_put_req_find_next(req);
18bceab1
JA
4778 spin_unlock_irq(&ctx->completion_lock);
4779
4780 io_cqring_ev_posted(ctx);
4781}
4782
4783static void io_poll_task_func(struct callback_head *cb)
4784{
4785 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
6d816e08 4786 struct io_ring_ctx *ctx = req->ctx;
18bceab1
JA
4787 struct io_kiocb *nxt = NULL;
4788
4789 io_poll_task_handler(req, &nxt);
ea1164e5
PB
4790 if (nxt)
4791 __io_req_task_submit(nxt);
6d816e08 4792 percpu_ref_put(&ctx->refs);
18bceab1
JA
4793}
4794
4795static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4796 int sync, void *key)
4797{
4798 struct io_kiocb *req = wait->private;
d4e7cd36 4799 struct io_poll_iocb *poll = io_poll_get_single(req);
18bceab1
JA
4800 __poll_t mask = key_to_poll(key);
4801
4802 /* for instances that support it check for an event match first: */
4803 if (mask && !(mask & poll->events))
4804 return 0;
4805
8706e04e
JA
4806 list_del_init(&wait->entry);
4807
807abcb0 4808 if (poll && poll->head) {
18bceab1
JA
4809 bool done;
4810
807abcb0
JA
4811 spin_lock(&poll->head->lock);
4812 done = list_empty(&poll->wait.entry);
18bceab1 4813 if (!done)
807abcb0 4814 list_del_init(&poll->wait.entry);
d4e7cd36
JA
4815 /* make sure double remove sees this as being gone */
4816 wait->private = NULL;
807abcb0 4817 spin_unlock(&poll->head->lock);
18bceab1
JA
4818 if (!done)
4819 __io_async_wake(req, poll, mask, io_poll_task_func);
4820 }
4821 refcount_dec(&req->refs);
4822 return 1;
4823}
4824
4825static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4826 wait_queue_func_t wake_func)
4827{
4828 poll->head = NULL;
4829 poll->done = false;
4830 poll->canceled = false;
4831 poll->events = events;
4832 INIT_LIST_HEAD(&poll->wait.entry);
4833 init_waitqueue_func_entry(&poll->wait, wake_func);
4834}
4835
4836static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
807abcb0
JA
4837 struct wait_queue_head *head,
4838 struct io_poll_iocb **poll_ptr)
18bceab1
JA
4839{
4840 struct io_kiocb *req = pt->req;
4841
4842 /*
4843 * If poll->head is already set, it's because the file being polled
4844 * uses multiple waitqueues for poll handling (eg one for read, one
4845 * for write). Setup a separate io_poll_iocb if this happens.
4846 */
4847 if (unlikely(poll->head)) {
4848 /* already have a 2nd entry, fail a third attempt */
807abcb0 4849 if (*poll_ptr) {
18bceab1
JA
4850 pt->error = -EINVAL;
4851 return;
4852 }
4853 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
4854 if (!poll) {
4855 pt->error = -ENOMEM;
4856 return;
4857 }
4858 io_init_poll_iocb(poll, req->poll.events, io_poll_double_wake);
4859 refcount_inc(&req->refs);
4860 poll->wait.private = req;
807abcb0 4861 *poll_ptr = poll;
18bceab1
JA
4862 }
4863
4864 pt->error = 0;
4865 poll->head = head;
a31eb4a2
JX
4866
4867 if (poll->events & EPOLLEXCLUSIVE)
4868 add_wait_queue_exclusive(head, &poll->wait);
4869 else
4870 add_wait_queue(head, &poll->wait);
18bceab1
JA
4871}
4872
4873static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
4874 struct poll_table_struct *p)
4875{
4876 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
807abcb0 4877 struct async_poll *apoll = pt->req->apoll;
18bceab1 4878
807abcb0 4879 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
18bceab1
JA
4880}
4881
d7718a9d
JA
4882static void io_async_task_func(struct callback_head *cb)
4883{
4884 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4885 struct async_poll *apoll = req->apoll;
4886 struct io_ring_ctx *ctx = req->ctx;
4887
4888 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
4889
74ce6ce4 4890 if (io_poll_rewait(req, &apoll->poll)) {
d7718a9d 4891 spin_unlock_irq(&ctx->completion_lock);
6d816e08 4892 percpu_ref_put(&ctx->refs);
74ce6ce4 4893 return;
d7718a9d
JA
4894 }
4895
31067255 4896 /* If req is still hashed, it cannot have been canceled. Don't check. */
0be0b0e3 4897 if (hash_hashed(&req->hash_node))
74ce6ce4 4898 hash_del(&req->hash_node);
2bae047e 4899
d4e7cd36 4900 io_poll_remove_double(req);
74ce6ce4
JA
4901 spin_unlock_irq(&ctx->completion_lock);
4902
0be0b0e3
PB
4903 if (!READ_ONCE(apoll->poll.canceled))
4904 __io_req_task_submit(req);
4905 else
4906 __io_req_task_cancel(req, -ECANCELED);
aa340845 4907
6d816e08 4908 percpu_ref_put(&ctx->refs);
807abcb0 4909 kfree(apoll->double_poll);
31067255 4910 kfree(apoll);
d7718a9d
JA
4911}
4912
4913static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
4914 void *key)
4915{
4916 struct io_kiocb *req = wait->private;
4917 struct io_poll_iocb *poll = &req->apoll->poll;
4918
4919 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
4920 key_to_poll(key));
4921
4922 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
4923}
4924
4925static void io_poll_req_insert(struct io_kiocb *req)
4926{
4927 struct io_ring_ctx *ctx = req->ctx;
4928 struct hlist_head *list;
4929
4930 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
4931 hlist_add_head(&req->hash_node, list);
4932}
4933
4934static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
4935 struct io_poll_iocb *poll,
4936 struct io_poll_table *ipt, __poll_t mask,
4937 wait_queue_func_t wake_func)
4938 __acquires(&ctx->completion_lock)
4939{
4940 struct io_ring_ctx *ctx = req->ctx;
4941 bool cancel = false;
4942
18bceab1 4943 io_init_poll_iocb(poll, mask, wake_func);
b90cd197 4944 poll->file = req->file;
18bceab1 4945 poll->wait.private = req;
d7718a9d
JA
4946
4947 ipt->pt._key = mask;
4948 ipt->req = req;
4949 ipt->error = -EINVAL;
4950
d7718a9d
JA
4951 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
4952
4953 spin_lock_irq(&ctx->completion_lock);
4954 if (likely(poll->head)) {
4955 spin_lock(&poll->head->lock);
4956 if (unlikely(list_empty(&poll->wait.entry))) {
4957 if (ipt->error)
4958 cancel = true;
4959 ipt->error = 0;
4960 mask = 0;
4961 }
4962 if (mask || ipt->error)
4963 list_del_init(&poll->wait.entry);
4964 else if (cancel)
4965 WRITE_ONCE(poll->canceled, true);
4966 else if (!poll->done) /* actually waiting for an event */
4967 io_poll_req_insert(req);
4968 spin_unlock(&poll->head->lock);
4969 }
4970
4971 return mask;
4972}
4973
4974static bool io_arm_poll_handler(struct io_kiocb *req)
4975{
4976 const struct io_op_def *def = &io_op_defs[req->opcode];
4977 struct io_ring_ctx *ctx = req->ctx;
4978 struct async_poll *apoll;
4979 struct io_poll_table ipt;
4980 __poll_t mask, ret;
9dab14b8 4981 int rw;
d7718a9d
JA
4982
4983 if (!req->file || !file_can_poll(req->file))
4984 return false;
24c74678 4985 if (req->flags & REQ_F_POLLED)
d7718a9d 4986 return false;
9dab14b8
JA
4987 if (def->pollin)
4988 rw = READ;
4989 else if (def->pollout)
4990 rw = WRITE;
4991 else
4992 return false;
4993 /* if we can't nonblock try, then no point in arming a poll handler */
4994 if (!io_file_supports_async(req->file, rw))
d7718a9d
JA
4995 return false;
4996
4997 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
4998 if (unlikely(!apoll))
4999 return false;
807abcb0 5000 apoll->double_poll = NULL;
d7718a9d
JA
5001
5002 req->flags |= REQ_F_POLLED;
d7718a9d
JA
5003 req->apoll = apoll;
5004 INIT_HLIST_NODE(&req->hash_node);
5005
8755d97a 5006 mask = 0;
d7718a9d 5007 if (def->pollin)
8755d97a 5008 mask |= POLLIN | POLLRDNORM;
d7718a9d
JA
5009 if (def->pollout)
5010 mask |= POLLOUT | POLLWRNORM;
5011 mask |= POLLERR | POLLPRI;
5012
5013 ipt.pt._qproc = io_async_queue_proc;
5014
5015 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5016 io_async_wake);
a36da65c 5017 if (ret || ipt.error) {
d4e7cd36 5018 io_poll_remove_double(req);
d7718a9d 5019 spin_unlock_irq(&ctx->completion_lock);
807abcb0 5020 kfree(apoll->double_poll);
d7718a9d
JA
5021 kfree(apoll);
5022 return false;
5023 }
5024 spin_unlock_irq(&ctx->completion_lock);
5025 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5026 apoll->poll.events);
5027 return true;
5028}
5029
5030static bool __io_poll_remove_one(struct io_kiocb *req,
5031 struct io_poll_iocb *poll)
221c5eb2 5032{
b41e9852 5033 bool do_complete = false;
221c5eb2
JA
5034
5035 spin_lock(&poll->head->lock);
5036 WRITE_ONCE(poll->canceled, true);
392edb45
JA
5037 if (!list_empty(&poll->wait.entry)) {
5038 list_del_init(&poll->wait.entry);
b41e9852 5039 do_complete = true;
221c5eb2
JA
5040 }
5041 spin_unlock(&poll->head->lock);
3bfa5bcb 5042 hash_del(&req->hash_node);
d7718a9d
JA
5043 return do_complete;
5044}
5045
5046static bool io_poll_remove_one(struct io_kiocb *req)
5047{
5048 bool do_complete;
5049
d4e7cd36
JA
5050 io_poll_remove_double(req);
5051
d7718a9d
JA
5052 if (req->opcode == IORING_OP_POLL_ADD) {
5053 do_complete = __io_poll_remove_one(req, &req->poll);
5054 } else {
3bfa5bcb
JA
5055 struct async_poll *apoll = req->apoll;
5056
d7718a9d 5057 /* non-poll requests have submit ref still */
3bfa5bcb
JA
5058 do_complete = __io_poll_remove_one(req, &apoll->poll);
5059 if (do_complete) {
d7718a9d 5060 io_put_req(req);
807abcb0 5061 kfree(apoll->double_poll);
3bfa5bcb
JA
5062 kfree(apoll);
5063 }
b1f573bd
XW
5064 }
5065
b41e9852
JA
5066 if (do_complete) {
5067 io_cqring_fill_event(req, -ECANCELED);
5068 io_commit_cqring(req->ctx);
5069 req->flags |= REQ_F_COMP_LOCKED;
f254ac04 5070 req_set_fail_links(req);
b41e9852
JA
5071 io_put_req(req);
5072 }
5073
5074 return do_complete;
221c5eb2
JA
5075}
5076
76e1b642
JA
5077/*
5078 * Returns true if we found and killed one or more poll requests
5079 */
5080static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk)
221c5eb2 5081{
78076bb6 5082 struct hlist_node *tmp;
221c5eb2 5083 struct io_kiocb *req;
8e2e1faf 5084 int posted = 0, i;
221c5eb2
JA
5085
5086 spin_lock_irq(&ctx->completion_lock);
78076bb6
JA
5087 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5088 struct hlist_head *list;
5089
5090 list = &ctx->cancel_hash[i];
f3606e3a
JA
5091 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5092 if (io_task_match(req, tsk))
5093 posted += io_poll_remove_one(req);
5094 }
221c5eb2
JA
5095 }
5096 spin_unlock_irq(&ctx->completion_lock);
b41e9852 5097
8e2e1faf
JA
5098 if (posted)
5099 io_cqring_ev_posted(ctx);
76e1b642
JA
5100
5101 return posted != 0;
221c5eb2
JA
5102}
5103
47f46768
JA
5104static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5105{
78076bb6 5106 struct hlist_head *list;
47f46768
JA
5107 struct io_kiocb *req;
5108
78076bb6
JA
5109 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5110 hlist_for_each_entry(req, list, hash_node) {
b41e9852
JA
5111 if (sqe_addr != req->user_data)
5112 continue;
5113 if (io_poll_remove_one(req))
eac406c6 5114 return 0;
b41e9852 5115 return -EALREADY;
47f46768
JA
5116 }
5117
5118 return -ENOENT;
5119}
5120
3529d8c2
JA
5121static int io_poll_remove_prep(struct io_kiocb *req,
5122 const struct io_uring_sqe *sqe)
0969e783 5123{
0969e783
JA
5124 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5125 return -EINVAL;
5126 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5127 sqe->poll_events)
5128 return -EINVAL;
5129
5130 req->poll.addr = READ_ONCE(sqe->addr);
0969e783
JA
5131 return 0;
5132}
5133
221c5eb2
JA
5134/*
5135 * Find a running poll command that matches one specified in sqe->addr,
5136 * and remove it if found.
5137 */
fc4df999 5138static int io_poll_remove(struct io_kiocb *req)
221c5eb2
JA
5139{
5140 struct io_ring_ctx *ctx = req->ctx;
0969e783 5141 u64 addr;
47f46768 5142 int ret;
221c5eb2 5143
0969e783 5144 addr = req->poll.addr;
221c5eb2 5145 spin_lock_irq(&ctx->completion_lock);
0969e783 5146 ret = io_poll_cancel(ctx, addr);
221c5eb2
JA
5147 spin_unlock_irq(&ctx->completion_lock);
5148
4e88d6e7
JA
5149 if (ret < 0)
5150 req_set_fail_links(req);
e1e16097 5151 io_req_complete(req, ret);
221c5eb2
JA
5152 return 0;
5153}
5154
221c5eb2
JA
5155static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5156 void *key)
5157{
c2f2eb7d
JA
5158 struct io_kiocb *req = wait->private;
5159 struct io_poll_iocb *poll = &req->poll;
221c5eb2 5160
d7718a9d 5161 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
221c5eb2
JA
5162}
5163
221c5eb2
JA
5164static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5165 struct poll_table_struct *p)
5166{
5167 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5168
807abcb0 5169 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->io);
eac406c6
JA
5170}
5171
3529d8c2 5172static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
221c5eb2
JA
5173{
5174 struct io_poll_iocb *poll = &req->poll;
5769a351 5175 u32 events;
221c5eb2
JA
5176
5177 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5178 return -EINVAL;
5179 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
5180 return -EINVAL;
09bb8394
JA
5181 if (!poll->file)
5182 return -EBADF;
221c5eb2 5183
5769a351
JX
5184 events = READ_ONCE(sqe->poll32_events);
5185#ifdef __BIG_ENDIAN
5186 events = swahw32(events);
5187#endif
a31eb4a2
JX
5188 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
5189 (events & EPOLLEXCLUSIVE);
0969e783
JA
5190 return 0;
5191}
5192
014db007 5193static int io_poll_add(struct io_kiocb *req)
0969e783
JA
5194{
5195 struct io_poll_iocb *poll = &req->poll;
5196 struct io_ring_ctx *ctx = req->ctx;
5197 struct io_poll_table ipt;
0969e783 5198 __poll_t mask;
0969e783 5199
78076bb6 5200 INIT_HLIST_NODE(&req->hash_node);
d7718a9d 5201 ipt.pt._qproc = io_poll_queue_proc;
36703247 5202
d7718a9d
JA
5203 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5204 io_poll_wake);
221c5eb2 5205
8c838788 5206 if (mask) { /* no async, we'd stolen it */
221c5eb2 5207 ipt.error = 0;
b0dd8a41 5208 io_poll_complete(req, mask, 0);
221c5eb2 5209 }
221c5eb2
JA
5210 spin_unlock_irq(&ctx->completion_lock);
5211
8c838788
JA
5212 if (mask) {
5213 io_cqring_ev_posted(ctx);
014db007 5214 io_put_req(req);
221c5eb2 5215 }
8c838788 5216 return ipt.error;
221c5eb2
JA
5217}
5218
5262f567
JA
5219static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5220{
ad8a48ac
JA
5221 struct io_timeout_data *data = container_of(timer,
5222 struct io_timeout_data, timer);
5223 struct io_kiocb *req = data->req;
5224 struct io_ring_ctx *ctx = req->ctx;
5262f567
JA
5225 unsigned long flags;
5226
5262f567 5227 spin_lock_irqsave(&ctx->completion_lock, flags);
01cec8c1
PB
5228 atomic_set(&req->ctx->cq_timeouts,
5229 atomic_read(&req->ctx->cq_timeouts) + 1);
5230
ef03681a 5231 /*
11365043
JA
5232 * We could be racing with timeout deletion. If the list is empty,
5233 * then timeout lookup already found it and will be handling it.
ef03681a 5234 */
135fcde8
PB
5235 if (!list_empty(&req->timeout.list))
5236 list_del_init(&req->timeout.list);
5262f567 5237
78e19bbe 5238 io_cqring_fill_event(req, -ETIME);
5262f567
JA
5239 io_commit_cqring(ctx);
5240 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5241
5242 io_cqring_ev_posted(ctx);
4e88d6e7 5243 req_set_fail_links(req);
5262f567
JA
5244 io_put_req(req);
5245 return HRTIMER_NORESTART;
5246}
5247
f254ac04
JA
5248static int __io_timeout_cancel(struct io_kiocb *req)
5249{
5250 int ret;
5251
5252 list_del_init(&req->timeout.list);
5253
5254 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
5255 if (ret == -1)
5256 return -EALREADY;
5257
5258 req_set_fail_links(req);
5259 req->flags |= REQ_F_COMP_LOCKED;
5260 io_cqring_fill_event(req, -ECANCELED);
5261 io_put_req(req);
5262 return 0;
5263}
5264
47f46768
JA
5265static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5266{
5267 struct io_kiocb *req;
5268 int ret = -ENOENT;
5269
135fcde8 5270 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
47f46768 5271 if (user_data == req->user_data) {
47f46768
JA
5272 ret = 0;
5273 break;
5274 }
5275 }
5276
5277 if (ret == -ENOENT)
5278 return ret;
5279
f254ac04 5280 return __io_timeout_cancel(req);
47f46768
JA
5281}
5282
3529d8c2
JA
5283static int io_timeout_remove_prep(struct io_kiocb *req,
5284 const struct io_uring_sqe *sqe)
b29472ee 5285{
b29472ee
JA
5286 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5287 return -EINVAL;
61710e43
DA
5288 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5289 return -EINVAL;
5290 if (sqe->ioprio || sqe->buf_index || sqe->len)
b29472ee
JA
5291 return -EINVAL;
5292
5293 req->timeout.addr = READ_ONCE(sqe->addr);
5294 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
5295 if (req->timeout.flags)
5296 return -EINVAL;
5297
b29472ee
JA
5298 return 0;
5299}
5300
11365043
JA
5301/*
5302 * Remove or update an existing timeout command
5303 */
fc4df999 5304static int io_timeout_remove(struct io_kiocb *req)
11365043
JA
5305{
5306 struct io_ring_ctx *ctx = req->ctx;
47f46768 5307 int ret;
11365043 5308
11365043 5309 spin_lock_irq(&ctx->completion_lock);
b29472ee 5310 ret = io_timeout_cancel(ctx, req->timeout.addr);
11365043 5311
47f46768 5312 io_cqring_fill_event(req, ret);
11365043
JA
5313 io_commit_cqring(ctx);
5314 spin_unlock_irq(&ctx->completion_lock);
5262f567 5315 io_cqring_ev_posted(ctx);
4e88d6e7
JA
5316 if (ret < 0)
5317 req_set_fail_links(req);
ec9c02ad 5318 io_put_req(req);
11365043 5319 return 0;
5262f567
JA
5320}
5321
3529d8c2 5322static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2d28390a 5323 bool is_timeout_link)
5262f567 5324{
ad8a48ac 5325 struct io_timeout_data *data;
a41525ab 5326 unsigned flags;
56080b02 5327 u32 off = READ_ONCE(sqe->off);
5262f567 5328
ad8a48ac 5329 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5262f567 5330 return -EINVAL;
ad8a48ac 5331 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
a41525ab 5332 return -EINVAL;
56080b02 5333 if (off && is_timeout_link)
2d28390a 5334 return -EINVAL;
a41525ab
JA
5335 flags = READ_ONCE(sqe->timeout_flags);
5336 if (flags & ~IORING_TIMEOUT_ABS)
5262f567 5337 return -EINVAL;
bdf20073 5338
bfe68a22 5339 req->timeout.off = off;
26a61679 5340
3529d8c2 5341 if (!req->io && io_alloc_async_ctx(req))
26a61679
JA
5342 return -ENOMEM;
5343
5344 data = &req->io->timeout;
ad8a48ac 5345 data->req = req;
ad8a48ac
JA
5346
5347 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5262f567
JA
5348 return -EFAULT;
5349
11365043 5350 if (flags & IORING_TIMEOUT_ABS)
ad8a48ac 5351 data->mode = HRTIMER_MODE_ABS;
11365043 5352 else
ad8a48ac 5353 data->mode = HRTIMER_MODE_REL;
11365043 5354
ad8a48ac
JA
5355 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5356 return 0;
5357}
5358
fc4df999 5359static int io_timeout(struct io_kiocb *req)
ad8a48ac 5360{
ad8a48ac 5361 struct io_ring_ctx *ctx = req->ctx;
bfe68a22 5362 struct io_timeout_data *data = &req->io->timeout;
ad8a48ac 5363 struct list_head *entry;
bfe68a22 5364 u32 tail, off = req->timeout.off;
ad8a48ac 5365
733f5c95 5366 spin_lock_irq(&ctx->completion_lock);
93bd25bb 5367
5262f567
JA
5368 /*
5369 * sqe->off holds how many events that need to occur for this
93bd25bb
JA
5370 * timeout event to be satisfied. If it isn't set, then this is
5371 * a pure timeout request, sequence isn't used.
5262f567 5372 */
8eb7e2d0 5373 if (io_is_timeout_noseq(req)) {
93bd25bb
JA
5374 entry = ctx->timeout_list.prev;
5375 goto add;
5376 }
5262f567 5377
bfe68a22
PB
5378 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5379 req->timeout.target_seq = tail + off;
5262f567
JA
5380
5381 /*
5382 * Insertion sort, ensuring the first entry in the list is always
5383 * the one we need first.
5384 */
5262f567 5385 list_for_each_prev(entry, &ctx->timeout_list) {
135fcde8
PB
5386 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5387 timeout.list);
5262f567 5388
8eb7e2d0 5389 if (io_is_timeout_noseq(nxt))
93bd25bb 5390 continue;
bfe68a22
PB
5391 /* nxt.seq is behind @tail, otherwise would've been completed */
5392 if (off >= nxt->timeout.target_seq - tail)
5262f567
JA
5393 break;
5394 }
93bd25bb 5395add:
135fcde8 5396 list_add(&req->timeout.list, entry);
ad8a48ac
JA
5397 data->timer.function = io_timeout_fn;
5398 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5262f567 5399 spin_unlock_irq(&ctx->completion_lock);
5262f567
JA
5400 return 0;
5401}
5262f567 5402
62755e35
JA
5403static bool io_cancel_cb(struct io_wq_work *work, void *data)
5404{
5405 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5406
5407 return req->user_data == (unsigned long) data;
5408}
5409
e977d6d3 5410static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
62755e35 5411{
62755e35 5412 enum io_wq_cancel cancel_ret;
62755e35
JA
5413 int ret = 0;
5414
4f26bda1 5415 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr, false);
62755e35
JA
5416 switch (cancel_ret) {
5417 case IO_WQ_CANCEL_OK:
5418 ret = 0;
5419 break;
5420 case IO_WQ_CANCEL_RUNNING:
5421 ret = -EALREADY;
5422 break;
5423 case IO_WQ_CANCEL_NOTFOUND:
5424 ret = -ENOENT;
5425 break;
5426 }
5427
e977d6d3
JA
5428 return ret;
5429}
5430
47f46768
JA
5431static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5432 struct io_kiocb *req, __u64 sqe_addr,
014db007 5433 int success_ret)
47f46768
JA
5434{
5435 unsigned long flags;
5436 int ret;
5437
5438 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
5439 if (ret != -ENOENT) {
5440 spin_lock_irqsave(&ctx->completion_lock, flags);
5441 goto done;
5442 }
5443
5444 spin_lock_irqsave(&ctx->completion_lock, flags);
5445 ret = io_timeout_cancel(ctx, sqe_addr);
5446 if (ret != -ENOENT)
5447 goto done;
5448 ret = io_poll_cancel(ctx, sqe_addr);
5449done:
b0dd8a41
JA
5450 if (!ret)
5451 ret = success_ret;
47f46768
JA
5452 io_cqring_fill_event(req, ret);
5453 io_commit_cqring(ctx);
5454 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5455 io_cqring_ev_posted(ctx);
5456
4e88d6e7
JA
5457 if (ret < 0)
5458 req_set_fail_links(req);
014db007 5459 io_put_req(req);
47f46768
JA
5460}
5461
3529d8c2
JA
5462static int io_async_cancel_prep(struct io_kiocb *req,
5463 const struct io_uring_sqe *sqe)
e977d6d3 5464{
fbf23849 5465 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
e977d6d3 5466 return -EINVAL;
61710e43
DA
5467 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5468 return -EINVAL;
5469 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
e977d6d3
JA
5470 return -EINVAL;
5471
fbf23849
JA
5472 req->cancel.addr = READ_ONCE(sqe->addr);
5473 return 0;
5474}
5475
014db007 5476static int io_async_cancel(struct io_kiocb *req)
fbf23849
JA
5477{
5478 struct io_ring_ctx *ctx = req->ctx;
fbf23849 5479
014db007 5480 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
5262f567
JA
5481 return 0;
5482}
5483
05f3fb3c
JA
5484static int io_files_update_prep(struct io_kiocb *req,
5485 const struct io_uring_sqe *sqe)
5486{
6ca56f84
JA
5487 if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
5488 return -EINVAL;
61710e43
DA
5489 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5490 return -EINVAL;
5491 if (sqe->ioprio || sqe->rw_flags)
05f3fb3c
JA
5492 return -EINVAL;
5493
5494 req->files_update.offset = READ_ONCE(sqe->off);
5495 req->files_update.nr_args = READ_ONCE(sqe->len);
5496 if (!req->files_update.nr_args)
5497 return -EINVAL;
5498 req->files_update.arg = READ_ONCE(sqe->addr);
5499 return 0;
5500}
5501
229a7b63
JA
5502static int io_files_update(struct io_kiocb *req, bool force_nonblock,
5503 struct io_comp_state *cs)
fbf23849
JA
5504{
5505 struct io_ring_ctx *ctx = req->ctx;
05f3fb3c
JA
5506 struct io_uring_files_update up;
5507 int ret;
fbf23849 5508
f86cd20c 5509 if (force_nonblock)
05f3fb3c 5510 return -EAGAIN;
05f3fb3c
JA
5511
5512 up.offset = req->files_update.offset;
5513 up.fds = req->files_update.arg;
5514
5515 mutex_lock(&ctx->uring_lock);
5516 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
5517 mutex_unlock(&ctx->uring_lock);
5518
5519 if (ret < 0)
5520 req_set_fail_links(req);
229a7b63 5521 __io_req_complete(req, ret, 0, cs);
5262f567
JA
5522 return 0;
5523}
5524
3529d8c2
JA
5525static int io_req_defer_prep(struct io_kiocb *req,
5526 const struct io_uring_sqe *sqe)
f67676d1 5527{
e781573e 5528 ssize_t ret = 0;
f67676d1 5529
f1d96a8f
PB
5530 if (!sqe)
5531 return 0;
5532
327d6d96
PB
5533 if (io_alloc_async_ctx(req))
5534 return -EAGAIN;
f56040b8
PB
5535 ret = io_prep_work_files(req);
5536 if (unlikely(ret))
5537 return ret;
cccf0ee8 5538
202700e1
JA
5539 io_prep_async_work(req);
5540
d625c6ee 5541 switch (req->opcode) {
e781573e
JA
5542 case IORING_OP_NOP:
5543 break;
f67676d1
JA
5544 case IORING_OP_READV:
5545 case IORING_OP_READ_FIXED:
3a6820f2 5546 case IORING_OP_READ:
3529d8c2 5547 ret = io_read_prep(req, sqe, true);
f67676d1
JA
5548 break;
5549 case IORING_OP_WRITEV:
5550 case IORING_OP_WRITE_FIXED:
3a6820f2 5551 case IORING_OP_WRITE:
3529d8c2 5552 ret = io_write_prep(req, sqe, true);
f67676d1 5553 break;
0969e783 5554 case IORING_OP_POLL_ADD:
3529d8c2 5555 ret = io_poll_add_prep(req, sqe);
0969e783
JA
5556 break;
5557 case IORING_OP_POLL_REMOVE:
3529d8c2 5558 ret = io_poll_remove_prep(req, sqe);
0969e783 5559 break;
8ed8d3c3 5560 case IORING_OP_FSYNC:
3529d8c2 5561 ret = io_prep_fsync(req, sqe);
8ed8d3c3
JA
5562 break;
5563 case IORING_OP_SYNC_FILE_RANGE:
3529d8c2 5564 ret = io_prep_sfr(req, sqe);
8ed8d3c3 5565 break;
03b1230c 5566 case IORING_OP_SENDMSG:
fddaface 5567 case IORING_OP_SEND:
3529d8c2 5568 ret = io_sendmsg_prep(req, sqe);
03b1230c
JA
5569 break;
5570 case IORING_OP_RECVMSG:
fddaface 5571 case IORING_OP_RECV:
3529d8c2 5572 ret = io_recvmsg_prep(req, sqe);
03b1230c 5573 break;
f499a021 5574 case IORING_OP_CONNECT:
3529d8c2 5575 ret = io_connect_prep(req, sqe);
f499a021 5576 break;
2d28390a 5577 case IORING_OP_TIMEOUT:
3529d8c2 5578 ret = io_timeout_prep(req, sqe, false);
b7bb4f7d 5579 break;
b29472ee 5580 case IORING_OP_TIMEOUT_REMOVE:
3529d8c2 5581 ret = io_timeout_remove_prep(req, sqe);
b29472ee 5582 break;
fbf23849 5583 case IORING_OP_ASYNC_CANCEL:
3529d8c2 5584 ret = io_async_cancel_prep(req, sqe);
fbf23849 5585 break;
2d28390a 5586 case IORING_OP_LINK_TIMEOUT:
3529d8c2 5587 ret = io_timeout_prep(req, sqe, true);
b7bb4f7d 5588 break;
8ed8d3c3 5589 case IORING_OP_ACCEPT:
3529d8c2 5590 ret = io_accept_prep(req, sqe);
8ed8d3c3 5591 break;
d63d1b5e
JA
5592 case IORING_OP_FALLOCATE:
5593 ret = io_fallocate_prep(req, sqe);
5594 break;
15b71abe
JA
5595 case IORING_OP_OPENAT:
5596 ret = io_openat_prep(req, sqe);
5597 break;
b5dba59e
JA
5598 case IORING_OP_CLOSE:
5599 ret = io_close_prep(req, sqe);
5600 break;
05f3fb3c
JA
5601 case IORING_OP_FILES_UPDATE:
5602 ret = io_files_update_prep(req, sqe);
5603 break;
eddc7ef5
JA
5604 case IORING_OP_STATX:
5605 ret = io_statx_prep(req, sqe);
5606 break;
4840e418
JA
5607 case IORING_OP_FADVISE:
5608 ret = io_fadvise_prep(req, sqe);
5609 break;
c1ca757b
JA
5610 case IORING_OP_MADVISE:
5611 ret = io_madvise_prep(req, sqe);
5612 break;
cebdb986
JA
5613 case IORING_OP_OPENAT2:
5614 ret = io_openat2_prep(req, sqe);
5615 break;
3e4827b0
JA
5616 case IORING_OP_EPOLL_CTL:
5617 ret = io_epoll_ctl_prep(req, sqe);
5618 break;
7d67af2c
PB
5619 case IORING_OP_SPLICE:
5620 ret = io_splice_prep(req, sqe);
5621 break;
ddf0322d
JA
5622 case IORING_OP_PROVIDE_BUFFERS:
5623 ret = io_provide_buffers_prep(req, sqe);
5624 break;
067524e9
JA
5625 case IORING_OP_REMOVE_BUFFERS:
5626 ret = io_remove_buffers_prep(req, sqe);
5627 break;
f2a8d5c7
PB
5628 case IORING_OP_TEE:
5629 ret = io_tee_prep(req, sqe);
5630 break;
f67676d1 5631 default:
e781573e
JA
5632 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5633 req->opcode);
5634 ret = -EINVAL;
b7bb4f7d 5635 break;
f67676d1
JA
5636 }
5637
b7bb4f7d 5638 return ret;
f67676d1
JA
5639}
5640
9cf7c104
PB
5641static u32 io_get_sequence(struct io_kiocb *req)
5642{
5643 struct io_kiocb *pos;
5644 struct io_ring_ctx *ctx = req->ctx;
5645 u32 total_submitted, nr_reqs = 1;
5646
5647 if (req->flags & REQ_F_LINK_HEAD)
5648 list_for_each_entry(pos, &req->link_list, link_list)
5649 nr_reqs++;
5650
5651 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
5652 return total_submitted - nr_reqs;
5653}
5654
3529d8c2 5655static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
de0617e4 5656{
a197f664 5657 struct io_ring_ctx *ctx = req->ctx;
27dc8338 5658 struct io_defer_entry *de;
f67676d1 5659 int ret;
9cf7c104 5660 u32 seq;
de0617e4 5661
9d858b21 5662 /* Still need defer if there is pending req in defer list. */
9cf7c104
PB
5663 if (likely(list_empty_careful(&ctx->defer_list) &&
5664 !(req->flags & REQ_F_IO_DRAIN)))
5665 return 0;
5666
5667 seq = io_get_sequence(req);
5668 /* Still a chance to pass the sequence check */
5669 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
de0617e4
JA
5670 return 0;
5671
650b5481 5672 if (!req->io) {
650b5481 5673 ret = io_req_defer_prep(req, sqe);
327d6d96 5674 if (ret)
650b5481
PB
5675 return ret;
5676 }
cbdcb435 5677 io_prep_async_link(req);
27dc8338
PB
5678 de = kmalloc(sizeof(*de), GFP_KERNEL);
5679 if (!de)
5680 return -ENOMEM;
2d28390a 5681
de0617e4 5682 spin_lock_irq(&ctx->completion_lock);
9cf7c104 5683 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
de0617e4 5684 spin_unlock_irq(&ctx->completion_lock);
27dc8338 5685 kfree(de);
ae34817b
PB
5686 io_queue_async_work(req);
5687 return -EIOCBQUEUED;
de0617e4
JA
5688 }
5689
915967f6 5690 trace_io_uring_defer(ctx, req, req->user_data);
27dc8338 5691 de->req = req;
9cf7c104 5692 de->seq = seq;
27dc8338 5693 list_add_tail(&de->list, &ctx->defer_list);
de0617e4
JA
5694 spin_unlock_irq(&ctx->completion_lock);
5695 return -EIOCBQUEUED;
5696}
5697
f573d384
JA
5698static void io_req_drop_files(struct io_kiocb *req)
5699{
5700 struct io_ring_ctx *ctx = req->ctx;
5701 unsigned long flags;
5702
5703 spin_lock_irqsave(&ctx->inflight_lock, flags);
5704 list_del(&req->inflight_entry);
5705 if (waitqueue_active(&ctx->inflight_wait))
5706 wake_up(&ctx->inflight_wait);
5707 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
5708 req->flags &= ~REQ_F_INFLIGHT;
0f212204 5709 put_files_struct(req->work.files);
9b828492 5710 put_nsproxy(req->work.nsproxy);
f573d384
JA
5711 req->work.files = NULL;
5712}
5713
3ca405eb 5714static void __io_clean_op(struct io_kiocb *req)
99bc4c38
PB
5715{
5716 struct io_async_ctx *io = req->io;
5717
0e1b6fe3
PB
5718 if (req->flags & REQ_F_BUFFER_SELECTED) {
5719 switch (req->opcode) {
5720 case IORING_OP_READV:
5721 case IORING_OP_READ_FIXED:
5722 case IORING_OP_READ:
bcda7baa 5723 kfree((void *)(unsigned long)req->rw.addr);
0e1b6fe3
PB
5724 break;
5725 case IORING_OP_RECVMSG:
5726 case IORING_OP_RECV:
bcda7baa 5727 kfree(req->sr_msg.kbuf);
0e1b6fe3
PB
5728 break;
5729 }
5730 req->flags &= ~REQ_F_BUFFER_SELECTED;
99bc4c38
PB
5731 }
5732
0e1b6fe3
PB
5733 if (req->flags & REQ_F_NEED_CLEANUP) {
5734 switch (req->opcode) {
5735 case IORING_OP_READV:
5736 case IORING_OP_READ_FIXED:
5737 case IORING_OP_READ:
5738 case IORING_OP_WRITEV:
5739 case IORING_OP_WRITE_FIXED:
5740 case IORING_OP_WRITE:
ff6165b2
JA
5741 if (io->rw.free_iovec)
5742 kfree(io->rw.free_iovec);
0e1b6fe3
PB
5743 break;
5744 case IORING_OP_RECVMSG:
5745 case IORING_OP_SENDMSG:
5746 if (io->msg.iov != io->msg.fast_iov)
5747 kfree(io->msg.iov);
5748 break;
5749 case IORING_OP_SPLICE:
5750 case IORING_OP_TEE:
5751 io_put_file(req, req->splice.file_in,
5752 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
5753 break;
f3cd4850
JA
5754 case IORING_OP_OPENAT:
5755 case IORING_OP_OPENAT2:
5756 if (req->open.filename)
5757 putname(req->open.filename);
5758 break;
0e1b6fe3
PB
5759 }
5760 req->flags &= ~REQ_F_NEED_CLEANUP;
99bc4c38 5761 }
bb175342 5762
f573d384
JA
5763 if (req->flags & REQ_F_INFLIGHT)
5764 io_req_drop_files(req);
99bc4c38
PB
5765}
5766
3529d8c2 5767static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
f13fad7b 5768 bool force_nonblock, struct io_comp_state *cs)
2b188cc1 5769{
a197f664 5770 struct io_ring_ctx *ctx = req->ctx;
d625c6ee 5771 int ret;
2b188cc1 5772
d625c6ee 5773 switch (req->opcode) {
2b188cc1 5774 case IORING_OP_NOP:
229a7b63 5775 ret = io_nop(req, cs);
2b188cc1
JA
5776 break;
5777 case IORING_OP_READV:
edafccee 5778 case IORING_OP_READ_FIXED:
3a6820f2 5779 case IORING_OP_READ:
3529d8c2
JA
5780 if (sqe) {
5781 ret = io_read_prep(req, sqe, force_nonblock);
5782 if (ret < 0)
5783 break;
5784 }
a1d7c393 5785 ret = io_read(req, force_nonblock, cs);
edafccee 5786 break;
3529d8c2 5787 case IORING_OP_WRITEV:
edafccee 5788 case IORING_OP_WRITE_FIXED:
3a6820f2 5789 case IORING_OP_WRITE:
3529d8c2
JA
5790 if (sqe) {
5791 ret = io_write_prep(req, sqe, force_nonblock);
5792 if (ret < 0)
5793 break;
5794 }
a1d7c393 5795 ret = io_write(req, force_nonblock, cs);
2b188cc1 5796 break;
c992fe29 5797 case IORING_OP_FSYNC:
3529d8c2
JA
5798 if (sqe) {
5799 ret = io_prep_fsync(req, sqe);
5800 if (ret < 0)
5801 break;
5802 }
014db007 5803 ret = io_fsync(req, force_nonblock);
c992fe29 5804 break;
221c5eb2 5805 case IORING_OP_POLL_ADD:
3529d8c2
JA
5806 if (sqe) {
5807 ret = io_poll_add_prep(req, sqe);
5808 if (ret)
5809 break;
5810 }
014db007 5811 ret = io_poll_add(req);
221c5eb2
JA
5812 break;
5813 case IORING_OP_POLL_REMOVE:
3529d8c2
JA
5814 if (sqe) {
5815 ret = io_poll_remove_prep(req, sqe);
5816 if (ret < 0)
5817 break;
5818 }
fc4df999 5819 ret = io_poll_remove(req);
221c5eb2 5820 break;
5d17b4a4 5821 case IORING_OP_SYNC_FILE_RANGE:
3529d8c2
JA
5822 if (sqe) {
5823 ret = io_prep_sfr(req, sqe);
5824 if (ret < 0)
5825 break;
5826 }
014db007 5827 ret = io_sync_file_range(req, force_nonblock);
5d17b4a4 5828 break;
0fa03c62 5829 case IORING_OP_SENDMSG:
fddaface 5830 case IORING_OP_SEND:
3529d8c2
JA
5831 if (sqe) {
5832 ret = io_sendmsg_prep(req, sqe);
5833 if (ret < 0)
5834 break;
5835 }
fddaface 5836 if (req->opcode == IORING_OP_SENDMSG)
229a7b63 5837 ret = io_sendmsg(req, force_nonblock, cs);
fddaface 5838 else
229a7b63 5839 ret = io_send(req, force_nonblock, cs);
0fa03c62 5840 break;
aa1fa28f 5841 case IORING_OP_RECVMSG:
fddaface 5842 case IORING_OP_RECV:
3529d8c2
JA
5843 if (sqe) {
5844 ret = io_recvmsg_prep(req, sqe);
5845 if (ret)
5846 break;
5847 }
fddaface 5848 if (req->opcode == IORING_OP_RECVMSG)
229a7b63 5849 ret = io_recvmsg(req, force_nonblock, cs);
fddaface 5850 else
229a7b63 5851 ret = io_recv(req, force_nonblock, cs);
aa1fa28f 5852 break;
5262f567 5853 case IORING_OP_TIMEOUT:
3529d8c2
JA
5854 if (sqe) {
5855 ret = io_timeout_prep(req, sqe, false);
5856 if (ret)
5857 break;
5858 }
fc4df999 5859 ret = io_timeout(req);
5262f567 5860 break;
11365043 5861 case IORING_OP_TIMEOUT_REMOVE:
3529d8c2
JA
5862 if (sqe) {
5863 ret = io_timeout_remove_prep(req, sqe);
5864 if (ret)
5865 break;
5866 }
fc4df999 5867 ret = io_timeout_remove(req);
11365043 5868 break;
17f2fe35 5869 case IORING_OP_ACCEPT:
3529d8c2
JA
5870 if (sqe) {
5871 ret = io_accept_prep(req, sqe);
5872 if (ret)
5873 break;
5874 }
229a7b63 5875 ret = io_accept(req, force_nonblock, cs);
17f2fe35 5876 break;
f8e85cf2 5877 case IORING_OP_CONNECT:
3529d8c2
JA
5878 if (sqe) {
5879 ret = io_connect_prep(req, sqe);
5880 if (ret)
5881 break;
5882 }
229a7b63 5883 ret = io_connect(req, force_nonblock, cs);
f8e85cf2 5884 break;
62755e35 5885 case IORING_OP_ASYNC_CANCEL:
3529d8c2
JA
5886 if (sqe) {
5887 ret = io_async_cancel_prep(req, sqe);
5888 if (ret)
5889 break;
5890 }
014db007 5891 ret = io_async_cancel(req);
62755e35 5892 break;
d63d1b5e
JA
5893 case IORING_OP_FALLOCATE:
5894 if (sqe) {
5895 ret = io_fallocate_prep(req, sqe);
5896 if (ret)
5897 break;
5898 }
014db007 5899 ret = io_fallocate(req, force_nonblock);
d63d1b5e 5900 break;
15b71abe
JA
5901 case IORING_OP_OPENAT:
5902 if (sqe) {
5903 ret = io_openat_prep(req, sqe);
5904 if (ret)
5905 break;
5906 }
014db007 5907 ret = io_openat(req, force_nonblock);
15b71abe 5908 break;
b5dba59e
JA
5909 case IORING_OP_CLOSE:
5910 if (sqe) {
5911 ret = io_close_prep(req, sqe);
5912 if (ret)
5913 break;
5914 }
229a7b63 5915 ret = io_close(req, force_nonblock, cs);
b5dba59e 5916 break;
05f3fb3c
JA
5917 case IORING_OP_FILES_UPDATE:
5918 if (sqe) {
5919 ret = io_files_update_prep(req, sqe);
5920 if (ret)
5921 break;
5922 }
229a7b63 5923 ret = io_files_update(req, force_nonblock, cs);
05f3fb3c 5924 break;
eddc7ef5
JA
5925 case IORING_OP_STATX:
5926 if (sqe) {
5927 ret = io_statx_prep(req, sqe);
5928 if (ret)
5929 break;
5930 }
014db007 5931 ret = io_statx(req, force_nonblock);
eddc7ef5 5932 break;
4840e418
JA
5933 case IORING_OP_FADVISE:
5934 if (sqe) {
5935 ret = io_fadvise_prep(req, sqe);
5936 if (ret)
5937 break;
5938 }
014db007 5939 ret = io_fadvise(req, force_nonblock);
4840e418 5940 break;
c1ca757b
JA
5941 case IORING_OP_MADVISE:
5942 if (sqe) {
5943 ret = io_madvise_prep(req, sqe);
5944 if (ret)
5945 break;
5946 }
014db007 5947 ret = io_madvise(req, force_nonblock);
c1ca757b 5948 break;
cebdb986
JA
5949 case IORING_OP_OPENAT2:
5950 if (sqe) {
5951 ret = io_openat2_prep(req, sqe);
5952 if (ret)
5953 break;
5954 }
014db007 5955 ret = io_openat2(req, force_nonblock);
cebdb986 5956 break;
3e4827b0
JA
5957 case IORING_OP_EPOLL_CTL:
5958 if (sqe) {
5959 ret = io_epoll_ctl_prep(req, sqe);
5960 if (ret)
5961 break;
5962 }
229a7b63 5963 ret = io_epoll_ctl(req, force_nonblock, cs);
3e4827b0 5964 break;
7d67af2c
PB
5965 case IORING_OP_SPLICE:
5966 if (sqe) {
5967 ret = io_splice_prep(req, sqe);
5968 if (ret < 0)
5969 break;
5970 }
014db007 5971 ret = io_splice(req, force_nonblock);
7d67af2c 5972 break;
ddf0322d
JA
5973 case IORING_OP_PROVIDE_BUFFERS:
5974 if (sqe) {
5975 ret = io_provide_buffers_prep(req, sqe);
5976 if (ret)
5977 break;
5978 }
229a7b63 5979 ret = io_provide_buffers(req, force_nonblock, cs);
ddf0322d 5980 break;
067524e9
JA
5981 case IORING_OP_REMOVE_BUFFERS:
5982 if (sqe) {
5983 ret = io_remove_buffers_prep(req, sqe);
5984 if (ret)
5985 break;
5986 }
229a7b63 5987 ret = io_remove_buffers(req, force_nonblock, cs);
3e4827b0 5988 break;
f2a8d5c7
PB
5989 case IORING_OP_TEE:
5990 if (sqe) {
5991 ret = io_tee_prep(req, sqe);
5992 if (ret < 0)
5993 break;
5994 }
5995 ret = io_tee(req, force_nonblock);
5996 break;
2b188cc1
JA
5997 default:
5998 ret = -EINVAL;
5999 break;
6000 }
6001
def596e9
JA
6002 if (ret)
6003 return ret;
6004
b532576e
JA
6005 /* If the op doesn't have a file, we're not polling for it */
6006 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
11ba820b
JA
6007 const bool in_async = io_wq_current_is_worker();
6008
11ba820b
JA
6009 /* workqueue context doesn't hold uring_lock, grab it now */
6010 if (in_async)
6011 mutex_lock(&ctx->uring_lock);
6012
def596e9 6013 io_iopoll_req_issued(req);
11ba820b
JA
6014
6015 if (in_async)
6016 mutex_unlock(&ctx->uring_lock);
def596e9
JA
6017 }
6018
6019 return 0;
2b188cc1
JA
6020}
6021
f4db7182 6022static struct io_wq_work *io_wq_submit_work(struct io_wq_work *work)
2b188cc1
JA
6023{
6024 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6df1db6b 6025 struct io_kiocb *timeout;
561fb04a 6026 int ret = 0;
2b188cc1 6027
6df1db6b
PB
6028 timeout = io_prep_linked_timeout(req);
6029 if (timeout)
6030 io_queue_linked_timeout(timeout);
d4c81f38 6031
0c9d5ccd
JA
6032 /* if NO_CANCEL is set, we must still run the work */
6033 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
6034 IO_WQ_WORK_CANCEL) {
561fb04a 6035 ret = -ECANCELED;
0c9d5ccd 6036 }
31b51510 6037
561fb04a 6038 if (!ret) {
561fb04a 6039 do {
f13fad7b 6040 ret = io_issue_sqe(req, NULL, false, NULL);
561fb04a
JA
6041 /*
6042 * We can get EAGAIN for polled IO even though we're
6043 * forcing a sync submission from here, since we can't
6044 * wait for request slots on the block side.
6045 */
6046 if (ret != -EAGAIN)
6047 break;
6048 cond_resched();
6049 } while (1);
6050 }
31b51510 6051
561fb04a 6052 if (ret) {
4e88d6e7 6053 req_set_fail_links(req);
e1e16097 6054 io_req_complete(req, ret);
edafccee 6055 }
2b188cc1 6056
f4db7182 6057 return io_steal_work(req);
2b188cc1
JA
6058}
6059
65e19f54
JA
6060static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6061 int index)
6062{
6063 struct fixed_file_table *table;
6064
05f3fb3c 6065 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
84695089 6066 return table->files[index & IORING_FILE_TABLE_MASK];
65e19f54
JA
6067}
6068
8da11c19
PB
6069static int io_file_get(struct io_submit_state *state, struct io_kiocb *req,
6070 int fd, struct file **out_file, bool fixed)
09bb8394 6071{
a197f664 6072 struct io_ring_ctx *ctx = req->ctx;
8da11c19 6073 struct file *file;
09bb8394 6074
8da11c19 6075 if (fixed) {
05f3fb3c 6076 if (unlikely(!ctx->file_data ||
09bb8394
JA
6077 (unsigned) fd >= ctx->nr_user_files))
6078 return -EBADF;
b7620121 6079 fd = array_index_nospec(fd, ctx->nr_user_files);
8da11c19 6080 file = io_file_from_index(ctx, fd);
fd2206e4
JA
6081 if (file) {
6082 req->fixed_file_refs = ctx->file_data->cur_refs;
6083 percpu_ref_get(req->fixed_file_refs);
6084 }
09bb8394 6085 } else {
c826bd7a 6086 trace_io_uring_file_get(ctx, fd);
8da11c19 6087 file = __io_file_get(state, fd);
09bb8394
JA
6088 }
6089
fd2206e4
JA
6090 if (file || io_op_defs[req->opcode].needs_file_no_error) {
6091 *out_file = file;
6092 return 0;
6093 }
6094 return -EBADF;
09bb8394
JA
6095}
6096
8da11c19 6097static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
63ff8223 6098 int fd)
8da11c19 6099{
8da11c19
PB
6100 bool fixed;
6101
63ff8223 6102 fixed = (req->flags & REQ_F_FIXED_FILE) != 0;
0cdaf760 6103 if (unlikely(!fixed && io_async_submit(req->ctx)))
8da11c19
PB
6104 return -EBADF;
6105
6106 return io_file_get(state, req, fd, &req->file, fixed);
6107}
6108
a197f664 6109static int io_grab_files(struct io_kiocb *req)
fcb323cc 6110{
a197f664 6111 struct io_ring_ctx *ctx = req->ctx;
fcb323cc 6112
f56040b8
PB
6113 io_req_init_async(req);
6114
5b0bbee4 6115 if (req->work.files || (req->flags & REQ_F_NO_FILE_TABLE))
f86cd20c 6116 return 0;
b5dba59e 6117
0f212204 6118 req->work.files = get_files_struct(current);
9b828492
JA
6119 get_nsproxy(current->nsproxy);
6120 req->work.nsproxy = current->nsproxy;
0f212204
JA
6121 req->flags |= REQ_F_INFLIGHT;
6122
fcb323cc 6123 spin_lock_irq(&ctx->inflight_lock);
0f212204 6124 list_add(&req->inflight_entry, &ctx->inflight_list);
fcb323cc 6125 spin_unlock_irq(&ctx->inflight_lock);
0f212204 6126 return 0;
fcb323cc
JA
6127}
6128
f56040b8
PB
6129static inline int io_prep_work_files(struct io_kiocb *req)
6130{
6131 if (!io_op_defs[req->opcode].file_table)
6132 return 0;
6133 return io_grab_files(req);
6134}
6135
2665abfd 6136static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
2b188cc1 6137{
ad8a48ac
JA
6138 struct io_timeout_data *data = container_of(timer,
6139 struct io_timeout_data, timer);
6140 struct io_kiocb *req = data->req;
2665abfd
JA
6141 struct io_ring_ctx *ctx = req->ctx;
6142 struct io_kiocb *prev = NULL;
6143 unsigned long flags;
2665abfd
JA
6144
6145 spin_lock_irqsave(&ctx->completion_lock, flags);
6146
6147 /*
6148 * We don't expect the list to be empty, that will only happen if we
6149 * race with the completion of the linked work.
6150 */
4493233e
PB
6151 if (!list_empty(&req->link_list)) {
6152 prev = list_entry(req->link_list.prev, struct io_kiocb,
6153 link_list);
5d960724 6154 if (refcount_inc_not_zero(&prev->refs)) {
4493233e 6155 list_del_init(&req->link_list);
5d960724
JA
6156 prev->flags &= ~REQ_F_LINK_TIMEOUT;
6157 } else
76a46e06 6158 prev = NULL;
2665abfd
JA
6159 }
6160
6161 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6162
6163 if (prev) {
4e88d6e7 6164 req_set_fail_links(prev);
014db007 6165 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
76a46e06 6166 io_put_req(prev);
47f46768 6167 } else {
e1e16097 6168 io_req_complete(req, -ETIME);
2665abfd 6169 }
2665abfd
JA
6170 return HRTIMER_NORESTART;
6171}
6172
7271ef3a 6173static void __io_queue_linked_timeout(struct io_kiocb *req)
2665abfd 6174{
76a46e06
JA
6175 /*
6176 * If the list is now empty, then our linked request finished before
6177 * we got a chance to setup the timer
6178 */
4493233e 6179 if (!list_empty(&req->link_list)) {
2d28390a 6180 struct io_timeout_data *data = &req->io->timeout;
94ae5e77 6181
ad8a48ac
JA
6182 data->timer.function = io_link_timeout_fn;
6183 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6184 data->mode);
2665abfd 6185 }
7271ef3a
JA
6186}
6187
6188static void io_queue_linked_timeout(struct io_kiocb *req)
6189{
6190 struct io_ring_ctx *ctx = req->ctx;
6191
6192 spin_lock_irq(&ctx->completion_lock);
6193 __io_queue_linked_timeout(req);
76a46e06 6194 spin_unlock_irq(&ctx->completion_lock);
2665abfd 6195
2665abfd 6196 /* drop submission reference */
76a46e06
JA
6197 io_put_req(req);
6198}
2665abfd 6199
ad8a48ac 6200static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
2665abfd
JA
6201{
6202 struct io_kiocb *nxt;
6203
dea3b49c 6204 if (!(req->flags & REQ_F_LINK_HEAD))
2665abfd 6205 return NULL;
6df1db6b 6206 if (req->flags & REQ_F_LINK_TIMEOUT)
d7718a9d 6207 return NULL;
2665abfd 6208
4493233e
PB
6209 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
6210 link_list);
d625c6ee 6211 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
76a46e06 6212 return NULL;
2665abfd 6213
76a46e06 6214 req->flags |= REQ_F_LINK_TIMEOUT;
76a46e06 6215 return nxt;
2665abfd
JA
6216}
6217
f13fad7b
JA
6218static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6219 struct io_comp_state *cs)
2b188cc1 6220{
4a0a7a18 6221 struct io_kiocb *linked_timeout;
4bc4494e 6222 struct io_kiocb *nxt;
193155c8 6223 const struct cred *old_creds = NULL;
e0c5c576 6224 int ret;
2b188cc1 6225
4a0a7a18
JA
6226again:
6227 linked_timeout = io_prep_linked_timeout(req);
6228
7cdaf587
XW
6229 if ((req->flags & REQ_F_WORK_INITIALIZED) && req->work.creds &&
6230 req->work.creds != current_cred()) {
193155c8
JA
6231 if (old_creds)
6232 revert_creds(old_creds);
6233 if (old_creds == req->work.creds)
6234 old_creds = NULL; /* restored original creds */
6235 else
6236 old_creds = override_creds(req->work.creds);
6237 }
6238
f13fad7b 6239 ret = io_issue_sqe(req, sqe, true, cs);
491381ce
JA
6240
6241 /*
6242 * We async punt it if the file wasn't marked NOWAIT, or if the file
6243 * doesn't support non-blocking read/write attempts
6244 */
24c74678 6245 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
f063c547 6246 if (!io_arm_poll_handler(req)) {
86a761f8 6247punt:
f063c547
PB
6248 ret = io_prep_work_files(req);
6249 if (unlikely(ret))
bbad27b2 6250 goto err;
f063c547
PB
6251 /*
6252 * Queued up for async execution, worker will release
6253 * submit reference when the iocb is actually submitted.
6254 */
6255 io_queue_async_work(req);
2b188cc1 6256 }
bbad27b2 6257
f063c547
PB
6258 if (linked_timeout)
6259 io_queue_linked_timeout(linked_timeout);
4bc4494e 6260 goto exit;
2b188cc1 6261 }
e65ef56d 6262
652532ad 6263 if (unlikely(ret)) {
fcb323cc 6264err:
652532ad
PB
6265 /* un-prep timeout, so it'll be killed as any other linked */
6266 req->flags &= ~REQ_F_LINK_TIMEOUT;
4e88d6e7 6267 req_set_fail_links(req);
e65ef56d 6268 io_put_req(req);
e1e16097 6269 io_req_complete(req, ret);
652532ad 6270 goto exit;
9e645e11 6271 }
652532ad
PB
6272
6273 /* drop submission reference */
6274 nxt = io_put_req_find_next(req);
6275 if (linked_timeout)
6276 io_queue_linked_timeout(linked_timeout);
6277
4a0a7a18
JA
6278 if (nxt) {
6279 req = nxt;
86a761f8
PB
6280
6281 if (req->flags & REQ_F_FORCE_ASYNC)
6282 goto punt;
4a0a7a18
JA
6283 goto again;
6284 }
4bc4494e 6285exit:
193155c8
JA
6286 if (old_creds)
6287 revert_creds(old_creds);
2b188cc1
JA
6288}
6289
f13fad7b
JA
6290static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6291 struct io_comp_state *cs)
4fe2c963
JL
6292{
6293 int ret;
6294
3529d8c2 6295 ret = io_req_defer(req, sqe);
4fe2c963
JL
6296 if (ret) {
6297 if (ret != -EIOCBQUEUED) {
1118591a 6298fail_req:
4e88d6e7 6299 req_set_fail_links(req);
e1e16097
JA
6300 io_put_req(req);
6301 io_req_complete(req, ret);
4fe2c963 6302 }
2550878f 6303 } else if (req->flags & REQ_F_FORCE_ASYNC) {
bd2ab18a 6304 if (!req->io) {
bd2ab18a 6305 ret = io_req_defer_prep(req, sqe);
327d6d96 6306 if (unlikely(ret))
bd2ab18a
PB
6307 goto fail_req;
6308 }
6309
ce35a47a
JA
6310 /*
6311 * Never try inline submit of IOSQE_ASYNC is set, go straight
6312 * to async execution.
6313 */
3e863ea3 6314 io_req_init_async(req);
ce35a47a
JA
6315 req->work.flags |= IO_WQ_WORK_CONCURRENT;
6316 io_queue_async_work(req);
6317 } else {
f13fad7b 6318 __io_queue_sqe(req, sqe, cs);
ce35a47a 6319 }
4fe2c963
JL
6320}
6321
f13fad7b
JA
6322static inline void io_queue_link_head(struct io_kiocb *req,
6323 struct io_comp_state *cs)
4fe2c963 6324{
94ae5e77 6325 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
e1e16097
JA
6326 io_put_req(req);
6327 io_req_complete(req, -ECANCELED);
1b4a51b6 6328 } else
f13fad7b 6329 io_queue_sqe(req, NULL, cs);
4fe2c963
JL
6330}
6331
1d4240cc 6332static int io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
f13fad7b 6333 struct io_kiocb **link, struct io_comp_state *cs)
9e645e11 6334{
a197f664 6335 struct io_ring_ctx *ctx = req->ctx;
ef4ff581 6336 int ret;
9e645e11 6337
9e645e11
JA
6338 /*
6339 * If we already have a head request, queue this one for async
6340 * submittal once the head completes. If we don't have a head but
6341 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6342 * submitted sync once the chain is complete. If none of those
6343 * conditions are true (normal request), then just queue it.
6344 */
6345 if (*link) {
9d76377f 6346 struct io_kiocb *head = *link;
4e88d6e7 6347
8cdf2193
PB
6348 /*
6349 * Taking sequential execution of a link, draining both sides
6350 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6351 * requests in the link. So, it drains the head and the
6352 * next after the link request. The last one is done via
6353 * drain_next flag to persist the effect across calls.
6354 */
ef4ff581 6355 if (req->flags & REQ_F_IO_DRAIN) {
711be031
PB
6356 head->flags |= REQ_F_IO_DRAIN;
6357 ctx->drain_next = 1;
6358 }
3529d8c2 6359 ret = io_req_defer_prep(req, sqe);
327d6d96 6360 if (unlikely(ret)) {
4e88d6e7 6361 /* fail even hard links since we don't submit */
9d76377f 6362 head->flags |= REQ_F_FAIL_LINK;
1d4240cc 6363 return ret;
2d28390a 6364 }
9d76377f
PB
6365 trace_io_uring_link(ctx, req, head);
6366 list_add_tail(&req->link_list, &head->link_list);
32fe525b
PB
6367
6368 /* last request of a link, enqueue the link */
ef4ff581 6369 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
f13fad7b 6370 io_queue_link_head(head, cs);
32fe525b
PB
6371 *link = NULL;
6372 }
9e645e11 6373 } else {
711be031
PB
6374 if (unlikely(ctx->drain_next)) {
6375 req->flags |= REQ_F_IO_DRAIN;
ef4ff581 6376 ctx->drain_next = 0;
711be031 6377 }
ef4ff581 6378 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
dea3b49c 6379 req->flags |= REQ_F_LINK_HEAD;
711be031 6380 INIT_LIST_HEAD(&req->link_list);
f1d96a8f 6381
711be031 6382 ret = io_req_defer_prep(req, sqe);
327d6d96 6383 if (unlikely(ret))
711be031
PB
6384 req->flags |= REQ_F_FAIL_LINK;
6385 *link = req;
6386 } else {
f13fad7b 6387 io_queue_sqe(req, sqe, cs);
711be031 6388 }
9e645e11 6389 }
2e6e1fde 6390
1d4240cc 6391 return 0;
9e645e11
JA
6392}
6393
9a56a232
JA
6394/*
6395 * Batched submission is done, ensure local IO is flushed out.
6396 */
6397static void io_submit_state_end(struct io_submit_state *state)
6398{
f13fad7b
JA
6399 if (!list_empty(&state->comp.list))
6400 io_submit_flush_completions(&state->comp);
9a56a232 6401 blk_finish_plug(&state->plug);
9f13c35b 6402 io_state_file_put(state);
2579f913 6403 if (state->free_reqs)
6c8a3134 6404 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
9a56a232
JA
6405}
6406
6407/*
6408 * Start submission side cache.
6409 */
6410static void io_submit_state_start(struct io_submit_state *state,
013538bd 6411 struct io_ring_ctx *ctx, unsigned int max_ios)
9a56a232
JA
6412{
6413 blk_start_plug(&state->plug);
013538bd
JA
6414 state->comp.nr = 0;
6415 INIT_LIST_HEAD(&state->comp.list);
6416 state->comp.ctx = ctx;
2579f913 6417 state->free_reqs = 0;
9a56a232
JA
6418 state->file = NULL;
6419 state->ios_left = max_ios;
6420}
6421
2b188cc1
JA
6422static void io_commit_sqring(struct io_ring_ctx *ctx)
6423{
75b28aff 6424 struct io_rings *rings = ctx->rings;
2b188cc1 6425
caf582c6
PB
6426 /*
6427 * Ensure any loads from the SQEs are done at this point,
6428 * since once we write the new head, the application could
6429 * write new data to them.
6430 */
6431 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2b188cc1
JA
6432}
6433
2b188cc1 6434/*
3529d8c2 6435 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
2b188cc1
JA
6436 * that is mapped by userspace. This means that care needs to be taken to
6437 * ensure that reads are stable, as we cannot rely on userspace always
6438 * being a good citizen. If members of the sqe are validated and then later
6439 * used, it's important that those reads are done through READ_ONCE() to
6440 * prevent a re-load down the line.
6441 */
709b302f 6442static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
2b188cc1 6443{
75b28aff 6444 u32 *sq_array = ctx->sq_array;
2b188cc1
JA
6445 unsigned head;
6446
6447 /*
6448 * The cached sq head (or cq tail) serves two purposes:
6449 *
6450 * 1) allows us to batch the cost of updating the user visible
6451 * head updates.
6452 * 2) allows the kernel side to track the head on its own, even
6453 * though the application is the one updating it.
6454 */
ee7d46d9 6455 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
709b302f
PB
6456 if (likely(head < ctx->sq_entries))
6457 return &ctx->sq_sqes[head];
2b188cc1
JA
6458
6459 /* drop invalid entries */
498ccd9e 6460 ctx->cached_sq_dropped++;
ee7d46d9 6461 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
709b302f
PB
6462 return NULL;
6463}
6464
6465static inline void io_consume_sqe(struct io_ring_ctx *ctx)
6466{
6467 ctx->cached_sq_head++;
2b188cc1
JA
6468}
6469
21b55dbc
SG
6470/*
6471 * Check SQE restrictions (opcode and flags).
6472 *
6473 * Returns 'true' if SQE is allowed, 'false' otherwise.
6474 */
6475static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6476 struct io_kiocb *req,
6477 unsigned int sqe_flags)
6478{
6479 if (!ctx->restricted)
6480 return true;
6481
6482 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6483 return false;
6484
6485 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6486 ctx->restrictions.sqe_flags_required)
6487 return false;
6488
6489 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6490 ctx->restrictions.sqe_flags_required))
6491 return false;
6492
6493 return true;
6494}
6495
ef4ff581
PB
6496#define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
6497 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
6498 IOSQE_BUFFER_SELECT)
6499
6500static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6501 const struct io_uring_sqe *sqe,
0cdaf760 6502 struct io_submit_state *state)
0553b8bd 6503{
ef4ff581 6504 unsigned int sqe_flags;
63ff8223 6505 int id;
ef4ff581 6506
0553b8bd
PB
6507 req->opcode = READ_ONCE(sqe->opcode);
6508 req->user_data = READ_ONCE(sqe->user_data);
6509 req->io = NULL;
6510 req->file = NULL;
6511 req->ctx = ctx;
6512 req->flags = 0;
6513 /* one is dropped after submission, the other at completion */
6514 refcount_set(&req->refs, 2);
4dd2824d 6515 req->task = current;
e3bc8e9d 6516 get_task_struct(req->task);
0f212204 6517 atomic_long_inc(&req->task->io_uring->req_issue);
0553b8bd 6518 req->result = 0;
ef4ff581
PB
6519
6520 if (unlikely(req->opcode >= IORING_OP_LAST))
6521 return -EINVAL;
6522
9d8426a0
JA
6523 if (unlikely(io_sq_thread_acquire_mm(ctx, req)))
6524 return -EFAULT;
ef4ff581
PB
6525
6526 sqe_flags = READ_ONCE(sqe->flags);
6527 /* enforce forwards compatibility on users */
6528 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6529 return -EINVAL;
6530
21b55dbc
SG
6531 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6532 return -EACCES;
6533
ef4ff581
PB
6534 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6535 !io_op_defs[req->opcode].buffer_select)
6536 return -EOPNOTSUPP;
6537
6538 id = READ_ONCE(sqe->personality);
6539 if (id) {
7cdaf587 6540 io_req_init_async(req);
ef4ff581
PB
6541 req->work.creds = idr_find(&ctx->personality_idr, id);
6542 if (unlikely(!req->work.creds))
6543 return -EINVAL;
6544 get_cred(req->work.creds);
6545 }
6546
6547 /* same numerical values with corresponding REQ_F_*, safe to copy */
c11368a5 6548 req->flags |= sqe_flags;
ef4ff581 6549
63ff8223
JA
6550 if (!io_op_defs[req->opcode].needs_file)
6551 return 0;
6552
6553 return io_req_set_file(state, req, READ_ONCE(sqe->fd));
0553b8bd
PB
6554}
6555
0f212204 6556static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6c271ce2 6557{
ac8691c4 6558 struct io_submit_state state;
9e645e11 6559 struct io_kiocb *link = NULL;
9e645e11 6560 int i, submitted = 0;
6c271ce2 6561
c4a2ed72 6562 /* if we have a backlog and couldn't flush it all, return BUSY */
ad3eb2c8
JA
6563 if (test_bit(0, &ctx->sq_check_overflow)) {
6564 if (!list_empty(&ctx->cq_overflow_list) &&
e6c8aa9a 6565 !io_cqring_overflow_flush(ctx, false, NULL, NULL))
ad3eb2c8
JA
6566 return -EBUSY;
6567 }
6c271ce2 6568
ee7d46d9
PB
6569 /* make sure SQ entry isn't read before tail */
6570 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
9ef4f124 6571
2b85edfc
PB
6572 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6573 return -EAGAIN;
6c271ce2 6574
013538bd 6575 io_submit_state_start(&state, ctx, nr);
6c271ce2
JA
6576
6577 for (i = 0; i < nr; i++) {
3529d8c2 6578 const struct io_uring_sqe *sqe;
196be95c 6579 struct io_kiocb *req;
1cb1edb2 6580 int err;
fb5ccc98 6581
b1e50e54
PB
6582 sqe = io_get_sqe(ctx);
6583 if (unlikely(!sqe)) {
6584 io_consume_sqe(ctx);
6585 break;
6586 }
ac8691c4 6587 req = io_alloc_req(ctx, &state);
196be95c
PB
6588 if (unlikely(!req)) {
6589 if (!submitted)
6590 submitted = -EAGAIN;
fb5ccc98 6591 break;
196be95c 6592 }
fb5ccc98 6593
ac8691c4 6594 err = io_init_req(ctx, req, sqe, &state);
709b302f 6595 io_consume_sqe(ctx);
d3656344
JA
6596 /* will complete beyond this point, count as submitted */
6597 submitted++;
6598
ef4ff581 6599 if (unlikely(err)) {
1cb1edb2 6600fail_req:
e1e16097
JA
6601 io_put_req(req);
6602 io_req_complete(req, err);
196be95c
PB
6603 break;
6604 }
fb5ccc98 6605
354420f7 6606 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
0cdaf760 6607 true, io_async_submit(ctx));
f13fad7b 6608 err = io_submit_sqe(req, sqe, &link, &state.comp);
1d4240cc
PB
6609 if (err)
6610 goto fail_req;
6c271ce2
JA
6611 }
6612
9466f437
PB
6613 if (unlikely(submitted != nr)) {
6614 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6615
6616 percpu_ref_put_many(&ctx->refs, nr - ref_used);
6617 }
9e645e11 6618 if (link)
f13fad7b 6619 io_queue_link_head(link, &state.comp);
ac8691c4 6620 io_submit_state_end(&state);
6c271ce2 6621
ae9428ca
PB
6622 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6623 io_commit_sqring(ctx);
6624
6c271ce2
JA
6625 return submitted;
6626}
6627
23b3628e
XW
6628static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6629{
6630 /* Tell userspace we may need a wakeup call */
6631 spin_lock_irq(&ctx->completion_lock);
6632 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6633 spin_unlock_irq(&ctx->completion_lock);
6634}
6635
6636static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6637{
6638 spin_lock_irq(&ctx->completion_lock);
6639 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6640 spin_unlock_irq(&ctx->completion_lock);
6641}
6642
3f0e64d0
JA
6643static int io_sq_wake_function(struct wait_queue_entry *wqe, unsigned mode,
6644 int sync, void *key)
6645{
6646 struct io_ring_ctx *ctx = container_of(wqe, struct io_ring_ctx, sqo_wait_entry);
6647 int ret;
6648
6649 ret = autoremove_wake_function(wqe, mode, sync, key);
6650 if (ret) {
6651 unsigned long flags;
6652
6653 spin_lock_irqsave(&ctx->completion_lock, flags);
6654 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6655 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6656 }
6657 return ret;
6658}
6659
c8d1ba58
JA
6660enum sq_ret {
6661 SQT_IDLE = 1,
6662 SQT_SPIN = 2,
6663 SQT_DID_WORK = 4,
6664};
6665
6666static enum sq_ret __io_sq_thread(struct io_ring_ctx *ctx,
6667 unsigned long start_jiffies)
6c271ce2 6668{
c8d1ba58 6669 unsigned long timeout = start_jiffies + ctx->sq_thread_idle;
534ca6d6 6670 struct io_sq_data *sqd = ctx->sq_data;
c8d1ba58 6671 unsigned int to_submit;
bdcd3eab 6672 int ret = 0;
6c271ce2 6673
c8d1ba58
JA
6674again:
6675 if (!list_empty(&ctx->iopoll_list)) {
6676 unsigned nr_events = 0;
6a779382 6677
c8d1ba58
JA
6678 mutex_lock(&ctx->uring_lock);
6679 if (!list_empty(&ctx->iopoll_list) && !need_resched())
6680 io_do_iopoll(ctx, &nr_events, 0);
6681 mutex_unlock(&ctx->uring_lock);
6682 }
a4c0b3de 6683
c8d1ba58 6684 to_submit = io_sqring_entries(ctx);
6c271ce2 6685
c8d1ba58
JA
6686 /*
6687 * If submit got -EBUSY, flag us as needing the application
6688 * to enter the kernel to reap and flush events.
6689 */
6690 if (!to_submit || ret == -EBUSY || need_resched()) {
6691 /*
6692 * Drop cur_mm before scheduling, we can't hold it for
6693 * long periods (or over schedule()). Do this before
6694 * adding ourselves to the waitqueue, as the unuse/drop
6695 * may sleep.
6696 */
6697 io_sq_thread_drop_mm();
6698
6699 /*
6700 * We're polling. If we're within the defined idle
6701 * period, then let us spin without work before going
6702 * to sleep. The exception is if we got EBUSY doing
6703 * more IO, we should wait for the application to
6704 * reap events and wake us up.
6705 */
6706 if (!list_empty(&ctx->iopoll_list) || need_resched() ||
6707 (!time_after(jiffies, timeout) && ret != -EBUSY &&
6708 !percpu_ref_is_dying(&ctx->refs)))
6709 return SQT_SPIN;
6c271ce2 6710
534ca6d6 6711 prepare_to_wait(&sqd->wait, &ctx->sqo_wait_entry,
c8d1ba58 6712 TASK_INTERRUPTIBLE);
6c271ce2 6713
c8d1ba58
JA
6714 /*
6715 * While doing polled IO, before going to sleep, we need
6716 * to check if there are new reqs added to iopoll_list,
6717 * it is because reqs may have been punted to io worker
6718 * and will be added to iopoll_list later, hence check
6719 * the iopoll_list again.
6720 */
6721 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6722 !list_empty_careful(&ctx->iopoll_list)) {
534ca6d6 6723 finish_wait(&sqd->wait, &ctx->sqo_wait_entry);
c8d1ba58 6724 goto again;
6c271ce2
JA
6725 }
6726
fb5ccc98 6727 to_submit = io_sqring_entries(ctx);
c8d1ba58
JA
6728 if (!to_submit || ret == -EBUSY)
6729 return SQT_IDLE;
6730 }
c1edbf5f 6731
534ca6d6 6732 finish_wait(&sqd->wait, &ctx->sqo_wait_entry);
c8d1ba58 6733 io_ring_clear_wakeup_flag(ctx);
7143b5ac 6734
c8d1ba58
JA
6735 mutex_lock(&ctx->uring_lock);
6736 if (likely(!percpu_ref_is_dying(&ctx->refs)))
6737 ret = io_submit_sqes(ctx, to_submit);
6738 mutex_unlock(&ctx->uring_lock);
6739 return SQT_DID_WORK;
6740}
6c271ce2 6741
69fb2131
JA
6742static void io_sqd_init_new(struct io_sq_data *sqd)
6743{
6744 struct io_ring_ctx *ctx;
6745
6746 while (!list_empty(&sqd->ctx_new_list)) {
6747 ctx = list_first_entry(&sqd->ctx_new_list, struct io_ring_ctx, sqd_list);
6748 init_wait(&ctx->sqo_wait_entry);
6749 ctx->sqo_wait_entry.func = io_sq_wake_function;
6750 list_move_tail(&ctx->sqd_list, &sqd->ctx_list);
6751 complete(&ctx->sq_thread_comp);
6752 }
6753}
6754
c8d1ba58
JA
6755static int io_sq_thread(void *data)
6756{
69fb2131
JA
6757 const struct cred *old_cred = NULL;
6758 struct io_sq_data *sqd = data;
6759 struct io_ring_ctx *ctx;
c8d1ba58 6760 unsigned long start_jiffies;
6c271ce2 6761
69fb2131
JA
6762 start_jiffies = jiffies;
6763 while (!kthread_should_stop()) {
6764 enum sq_ret ret = 0;
6c271ce2 6765
69fb2131
JA
6766 /*
6767 * Any changes to the sqd lists are synchronized through the
6768 * kthread parking. This synchronizes the thread vs users,
6769 * the users are synchronized on the sqd->ctx_lock.
6770 */
6771 if (kthread_should_park())
6772 kthread_parkme();
6c271ce2 6773
69fb2131
JA
6774 if (unlikely(!list_empty(&sqd->ctx_new_list)))
6775 io_sqd_init_new(sqd);
c8d1ba58 6776
69fb2131
JA
6777 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6778 if (current->cred != ctx->creds) {
6779 if (old_cred)
6780 revert_creds(old_cred);
6781 old_cred = override_creds(ctx->creds);
6782 }
c8d1ba58 6783
69fb2131
JA
6784 ret |= __io_sq_thread(ctx, start_jiffies);
6785
6786 io_sq_thread_drop_mm();
6787 }
6788
6789 if (ret & SQT_SPIN) {
c8d1ba58
JA
6790 io_run_task_work();
6791 cond_resched();
69fb2131
JA
6792 } else if (ret == SQT_IDLE) {
6793 if (kthread_should_park())
6794 continue;
6795 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6796 io_ring_set_wakeup_flag(ctx);
6797 schedule();
6798 start_jiffies = jiffies;
6799 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6800 io_ring_clear_wakeup_flag(ctx);
c8d1ba58 6801 }
6c271ce2
JA
6802 }
6803
4c6e277c 6804 io_run_task_work();
b41e9852 6805
69fb2131
JA
6806 if (old_cred)
6807 revert_creds(old_cred);
06058632 6808
2bbcd6d3 6809 kthread_parkme();
06058632 6810
6c271ce2
JA
6811 return 0;
6812}
6813
bda52162
JA
6814struct io_wait_queue {
6815 struct wait_queue_entry wq;
6816 struct io_ring_ctx *ctx;
6817 unsigned to_wait;
6818 unsigned nr_timeouts;
6819};
6820
1d7bb1d5 6821static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
bda52162
JA
6822{
6823 struct io_ring_ctx *ctx = iowq->ctx;
6824
6825 /*
d195a66e 6826 * Wake up if we have enough events, or if a timeout occurred since we
bda52162
JA
6827 * started waiting. For timeouts, we always want to return to userspace,
6828 * regardless of event count.
6829 */
1d7bb1d5 6830 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
bda52162
JA
6831 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6832}
6833
6834static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6835 int wake_flags, void *key)
6836{
6837 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6838 wq);
6839
1d7bb1d5
JA
6840 /* use noflush == true, as we can't safely rely on locking context */
6841 if (!io_should_wake(iowq, true))
bda52162
JA
6842 return -1;
6843
6844 return autoremove_wake_function(curr, mode, wake_flags, key);
6845}
6846
2b188cc1
JA
6847/*
6848 * Wait until events become available, if we don't already have some. The
6849 * application must reap them itself, as they reside on the shared cq ring.
6850 */
6851static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6852 const sigset_t __user *sig, size_t sigsz)
6853{
bda52162
JA
6854 struct io_wait_queue iowq = {
6855 .wq = {
6856 .private = current,
6857 .func = io_wake_function,
6858 .entry = LIST_HEAD_INIT(iowq.wq.entry),
6859 },
6860 .ctx = ctx,
6861 .to_wait = min_events,
6862 };
75b28aff 6863 struct io_rings *rings = ctx->rings;
e9ffa5c2 6864 int ret = 0;
2b188cc1 6865
b41e9852
JA
6866 do {
6867 if (io_cqring_events(ctx, false) >= min_events)
6868 return 0;
4c6e277c 6869 if (!io_run_task_work())
b41e9852 6870 break;
b41e9852 6871 } while (1);
2b188cc1
JA
6872
6873 if (sig) {
9e75ad5d
AB
6874#ifdef CONFIG_COMPAT
6875 if (in_compat_syscall())
6876 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
b772434b 6877 sigsz);
9e75ad5d
AB
6878 else
6879#endif
b772434b 6880 ret = set_user_sigmask(sig, sigsz);
9e75ad5d 6881
2b188cc1
JA
6882 if (ret)
6883 return ret;
6884 }
6885
bda52162 6886 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
c826bd7a 6887 trace_io_uring_cqring_wait(ctx, min_events);
bda52162
JA
6888 do {
6889 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
6890 TASK_INTERRUPTIBLE);
ce593a6c 6891 /* make sure we run task_work before checking for signals */
4c6e277c
JA
6892 if (io_run_task_work())
6893 continue;
bda52162 6894 if (signal_pending(current)) {
b7db41c9
JA
6895 if (current->jobctl & JOBCTL_TASK_WORK) {
6896 spin_lock_irq(&current->sighand->siglock);
6897 current->jobctl &= ~JOBCTL_TASK_WORK;
6898 recalc_sigpending();
6899 spin_unlock_irq(&current->sighand->siglock);
6900 continue;
6901 }
6902 ret = -EINTR;
bda52162
JA
6903 break;
6904 }
ce593a6c
JA
6905 if (io_should_wake(&iowq, false))
6906 break;
6907 schedule();
bda52162
JA
6908 } while (1);
6909 finish_wait(&ctx->wait, &iowq.wq);
6910
b7db41c9 6911 restore_saved_sigmask_unless(ret == -EINTR);
2b188cc1 6912
75b28aff 6913 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
2b188cc1
JA
6914}
6915
6b06314c
JA
6916static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
6917{
6918#if defined(CONFIG_UNIX)
6919 if (ctx->ring_sock) {
6920 struct sock *sock = ctx->ring_sock->sk;
6921 struct sk_buff *skb;
6922
6923 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
6924 kfree_skb(skb);
6925 }
6926#else
6927 int i;
6928
65e19f54
JA
6929 for (i = 0; i < ctx->nr_user_files; i++) {
6930 struct file *file;
6931
6932 file = io_file_from_index(ctx, i);
6933 if (file)
6934 fput(file);
6935 }
6b06314c
JA
6936#endif
6937}
6938
05f3fb3c
JA
6939static void io_file_ref_kill(struct percpu_ref *ref)
6940{
6941 struct fixed_file_data *data;
6942
6943 data = container_of(ref, struct fixed_file_data, refs);
6944 complete(&data->done);
6945}
6946
6b06314c
JA
6947static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
6948{
05f3fb3c 6949 struct fixed_file_data *data = ctx->file_data;
05589553 6950 struct fixed_file_ref_node *ref_node = NULL;
65e19f54
JA
6951 unsigned nr_tables, i;
6952
05f3fb3c 6953 if (!data)
6b06314c
JA
6954 return -ENXIO;
6955
6a4d07cd 6956 spin_lock(&data->lock);
05589553
XW
6957 if (!list_empty(&data->ref_list))
6958 ref_node = list_first_entry(&data->ref_list,
6959 struct fixed_file_ref_node, node);
6a4d07cd 6960 spin_unlock(&data->lock);
05589553
XW
6961 if (ref_node)
6962 percpu_ref_kill(&ref_node->refs);
6963
6964 percpu_ref_kill(&data->refs);
6965
6966 /* wait for all refs nodes to complete */
4a38aed2 6967 flush_delayed_work(&ctx->file_put_work);
2faf852d 6968 wait_for_completion(&data->done);
05f3fb3c 6969
6b06314c 6970 __io_sqe_files_unregister(ctx);
65e19f54
JA
6971 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
6972 for (i = 0; i < nr_tables; i++)
05f3fb3c
JA
6973 kfree(data->table[i].files);
6974 kfree(data->table);
05589553
XW
6975 percpu_ref_exit(&data->refs);
6976 kfree(data);
05f3fb3c 6977 ctx->file_data = NULL;
6b06314c
JA
6978 ctx->nr_user_files = 0;
6979 return 0;
6980}
6981
534ca6d6 6982static void io_put_sq_data(struct io_sq_data *sqd)
6c271ce2 6983{
534ca6d6 6984 if (refcount_dec_and_test(&sqd->refs)) {
2bbcd6d3
RP
6985 /*
6986 * The park is a bit of a work-around, without it we get
6987 * warning spews on shutdown with SQPOLL set and affinity
6988 * set to a single CPU.
6989 */
534ca6d6
JA
6990 if (sqd->thread) {
6991 kthread_park(sqd->thread);
6992 kthread_stop(sqd->thread);
6993 }
6994
6995 kfree(sqd);
6996 }
6997}
6998
aa06165d
JA
6999static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7000{
7001 struct io_ring_ctx *ctx_attach;
7002 struct io_sq_data *sqd;
7003 struct fd f;
7004
7005 f = fdget(p->wq_fd);
7006 if (!f.file)
7007 return ERR_PTR(-ENXIO);
7008 if (f.file->f_op != &io_uring_fops) {
7009 fdput(f);
7010 return ERR_PTR(-EINVAL);
7011 }
7012
7013 ctx_attach = f.file->private_data;
7014 sqd = ctx_attach->sq_data;
7015 if (!sqd) {
7016 fdput(f);
7017 return ERR_PTR(-EINVAL);
7018 }
7019
7020 refcount_inc(&sqd->refs);
7021 fdput(f);
7022 return sqd;
7023}
7024
534ca6d6
JA
7025static struct io_sq_data *io_get_sq_data(struct io_uring_params *p)
7026{
7027 struct io_sq_data *sqd;
7028
aa06165d
JA
7029 if (p->flags & IORING_SETUP_ATTACH_WQ)
7030 return io_attach_sq_data(p);
7031
534ca6d6
JA
7032 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7033 if (!sqd)
7034 return ERR_PTR(-ENOMEM);
7035
7036 refcount_set(&sqd->refs, 1);
69fb2131
JA
7037 INIT_LIST_HEAD(&sqd->ctx_list);
7038 INIT_LIST_HEAD(&sqd->ctx_new_list);
7039 mutex_init(&sqd->ctx_lock);
7040 mutex_init(&sqd->lock);
534ca6d6
JA
7041 init_waitqueue_head(&sqd->wait);
7042 return sqd;
7043}
7044
69fb2131
JA
7045static void io_sq_thread_unpark(struct io_sq_data *sqd)
7046 __releases(&sqd->lock)
7047{
7048 if (!sqd->thread)
7049 return;
7050 kthread_unpark(sqd->thread);
7051 mutex_unlock(&sqd->lock);
7052}
7053
7054static void io_sq_thread_park(struct io_sq_data *sqd)
7055 __acquires(&sqd->lock)
7056{
7057 if (!sqd->thread)
7058 return;
7059 mutex_lock(&sqd->lock);
7060 kthread_park(sqd->thread);
7061}
7062
534ca6d6
JA
7063static void io_sq_thread_stop(struct io_ring_ctx *ctx)
7064{
7065 struct io_sq_data *sqd = ctx->sq_data;
7066
7067 if (sqd) {
7068 if (sqd->thread) {
7069 /*
7070 * We may arrive here from the error branch in
7071 * io_sq_offload_create() where the kthread is created
7072 * without being waked up, thus wake it up now to make
7073 * sure the wait will complete.
7074 */
7075 wake_up_process(sqd->thread);
7076 wait_for_completion(&ctx->sq_thread_comp);
69fb2131
JA
7077
7078 io_sq_thread_park(sqd);
7079 }
7080
7081 mutex_lock(&sqd->ctx_lock);
7082 list_del(&ctx->sqd_list);
7083 mutex_unlock(&sqd->ctx_lock);
7084
7085 if (sqd->thread) {
7086 finish_wait(&sqd->wait, &ctx->sqo_wait_entry);
7087 io_sq_thread_unpark(sqd);
534ca6d6
JA
7088 }
7089
7090 io_put_sq_data(sqd);
7091 ctx->sq_data = NULL;
6c271ce2
JA
7092 }
7093}
7094
6b06314c
JA
7095static void io_finish_async(struct io_ring_ctx *ctx)
7096{
6c271ce2
JA
7097 io_sq_thread_stop(ctx);
7098
561fb04a
JA
7099 if (ctx->io_wq) {
7100 io_wq_destroy(ctx->io_wq);
7101 ctx->io_wq = NULL;
6b06314c
JA
7102 }
7103}
7104
7105#if defined(CONFIG_UNIX)
6b06314c
JA
7106/*
7107 * Ensure the UNIX gc is aware of our file set, so we are certain that
7108 * the io_uring can be safely unregistered on process exit, even if we have
7109 * loops in the file referencing.
7110 */
7111static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7112{
7113 struct sock *sk = ctx->ring_sock->sk;
7114 struct scm_fp_list *fpl;
7115 struct sk_buff *skb;
08a45173 7116 int i, nr_files;
6b06314c 7117
6b06314c
JA
7118 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7119 if (!fpl)
7120 return -ENOMEM;
7121
7122 skb = alloc_skb(0, GFP_KERNEL);
7123 if (!skb) {
7124 kfree(fpl);
7125 return -ENOMEM;
7126 }
7127
7128 skb->sk = sk;
6b06314c 7129
08a45173 7130 nr_files = 0;
6b06314c
JA
7131 fpl->user = get_uid(ctx->user);
7132 for (i = 0; i < nr; i++) {
65e19f54
JA
7133 struct file *file = io_file_from_index(ctx, i + offset);
7134
7135 if (!file)
08a45173 7136 continue;
65e19f54 7137 fpl->fp[nr_files] = get_file(file);
08a45173
JA
7138 unix_inflight(fpl->user, fpl->fp[nr_files]);
7139 nr_files++;
6b06314c
JA
7140 }
7141
08a45173
JA
7142 if (nr_files) {
7143 fpl->max = SCM_MAX_FD;
7144 fpl->count = nr_files;
7145 UNIXCB(skb).fp = fpl;
05f3fb3c 7146 skb->destructor = unix_destruct_scm;
08a45173
JA
7147 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7148 skb_queue_head(&sk->sk_receive_queue, skb);
6b06314c 7149
08a45173
JA
7150 for (i = 0; i < nr_files; i++)
7151 fput(fpl->fp[i]);
7152 } else {
7153 kfree_skb(skb);
7154 kfree(fpl);
7155 }
6b06314c
JA
7156
7157 return 0;
7158}
7159
7160/*
7161 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7162 * causes regular reference counting to break down. We rely on the UNIX
7163 * garbage collection to take care of this problem for us.
7164 */
7165static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7166{
7167 unsigned left, total;
7168 int ret = 0;
7169
7170 total = 0;
7171 left = ctx->nr_user_files;
7172 while (left) {
7173 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
6b06314c
JA
7174
7175 ret = __io_sqe_files_scm(ctx, this_files, total);
7176 if (ret)
7177 break;
7178 left -= this_files;
7179 total += this_files;
7180 }
7181
7182 if (!ret)
7183 return 0;
7184
7185 while (total < ctx->nr_user_files) {
65e19f54
JA
7186 struct file *file = io_file_from_index(ctx, total);
7187
7188 if (file)
7189 fput(file);
6b06314c
JA
7190 total++;
7191 }
7192
7193 return ret;
7194}
7195#else
7196static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7197{
7198 return 0;
7199}
7200#endif
7201
65e19f54
JA
7202static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
7203 unsigned nr_files)
7204{
7205 int i;
7206
7207 for (i = 0; i < nr_tables; i++) {
05f3fb3c 7208 struct fixed_file_table *table = &ctx->file_data->table[i];
65e19f54
JA
7209 unsigned this_files;
7210
7211 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7212 table->files = kcalloc(this_files, sizeof(struct file *),
7213 GFP_KERNEL);
7214 if (!table->files)
7215 break;
7216 nr_files -= this_files;
7217 }
7218
7219 if (i == nr_tables)
7220 return 0;
7221
7222 for (i = 0; i < nr_tables; i++) {
05f3fb3c 7223 struct fixed_file_table *table = &ctx->file_data->table[i];
65e19f54
JA
7224 kfree(table->files);
7225 }
7226 return 1;
7227}
7228
05f3fb3c
JA
7229static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
7230{
7231#if defined(CONFIG_UNIX)
7232 struct sock *sock = ctx->ring_sock->sk;
7233 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7234 struct sk_buff *skb;
7235 int i;
7236
7237 __skb_queue_head_init(&list);
7238
7239 /*
7240 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7241 * remove this entry and rearrange the file array.
7242 */
7243 skb = skb_dequeue(head);
7244 while (skb) {
7245 struct scm_fp_list *fp;
7246
7247 fp = UNIXCB(skb).fp;
7248 for (i = 0; i < fp->count; i++) {
7249 int left;
7250
7251 if (fp->fp[i] != file)
7252 continue;
7253
7254 unix_notinflight(fp->user, fp->fp[i]);
7255 left = fp->count - 1 - i;
7256 if (left) {
7257 memmove(&fp->fp[i], &fp->fp[i + 1],
7258 left * sizeof(struct file *));
7259 }
7260 fp->count--;
7261 if (!fp->count) {
7262 kfree_skb(skb);
7263 skb = NULL;
7264 } else {
7265 __skb_queue_tail(&list, skb);
7266 }
7267 fput(file);
7268 file = NULL;
7269 break;
7270 }
7271
7272 if (!file)
7273 break;
7274
7275 __skb_queue_tail(&list, skb);
7276
7277 skb = skb_dequeue(head);
7278 }
7279
7280 if (skb_peek(&list)) {
7281 spin_lock_irq(&head->lock);
7282 while ((skb = __skb_dequeue(&list)) != NULL)
7283 __skb_queue_tail(head, skb);
7284 spin_unlock_irq(&head->lock);
7285 }
7286#else
7287 fput(file);
7288#endif
7289}
7290
7291struct io_file_put {
05589553 7292 struct list_head list;
05f3fb3c 7293 struct file *file;
05f3fb3c
JA
7294};
7295
4a38aed2 7296static void __io_file_put_work(struct fixed_file_ref_node *ref_node)
65e19f54 7297{
4a38aed2
JA
7298 struct fixed_file_data *file_data = ref_node->file_data;
7299 struct io_ring_ctx *ctx = file_data->ctx;
05f3fb3c 7300 struct io_file_put *pfile, *tmp;
05589553
XW
7301
7302 list_for_each_entry_safe(pfile, tmp, &ref_node->file_list, list) {
6a4d07cd 7303 list_del(&pfile->list);
05589553
XW
7304 io_ring_file_put(ctx, pfile->file);
7305 kfree(pfile);
65e19f54 7306 }
05589553 7307
6a4d07cd
JA
7308 spin_lock(&file_data->lock);
7309 list_del(&ref_node->node);
7310 spin_unlock(&file_data->lock);
05589553
XW
7311
7312 percpu_ref_exit(&ref_node->refs);
7313 kfree(ref_node);
7314 percpu_ref_put(&file_data->refs);
2faf852d 7315}
65e19f54 7316
4a38aed2
JA
7317static void io_file_put_work(struct work_struct *work)
7318{
7319 struct io_ring_ctx *ctx;
7320 struct llist_node *node;
7321
7322 ctx = container_of(work, struct io_ring_ctx, file_put_work.work);
7323 node = llist_del_all(&ctx->file_put_llist);
7324
7325 while (node) {
7326 struct fixed_file_ref_node *ref_node;
7327 struct llist_node *next = node->next;
7328
7329 ref_node = llist_entry(node, struct fixed_file_ref_node, llist);
7330 __io_file_put_work(ref_node);
7331 node = next;
7332 }
7333}
7334
05589553 7335static void io_file_data_ref_zero(struct percpu_ref *ref)
2faf852d 7336{
05589553 7337 struct fixed_file_ref_node *ref_node;
4a38aed2
JA
7338 struct io_ring_ctx *ctx;
7339 bool first_add;
7340 int delay = HZ;
65e19f54 7341
05589553 7342 ref_node = container_of(ref, struct fixed_file_ref_node, refs);
4a38aed2 7343 ctx = ref_node->file_data->ctx;
05589553 7344
4a38aed2
JA
7345 if (percpu_ref_is_dying(&ctx->file_data->refs))
7346 delay = 0;
05589553 7347
4a38aed2
JA
7348 first_add = llist_add(&ref_node->llist, &ctx->file_put_llist);
7349 if (!delay)
7350 mod_delayed_work(system_wq, &ctx->file_put_work, 0);
7351 else if (first_add)
7352 queue_delayed_work(system_wq, &ctx->file_put_work, delay);
05f3fb3c 7353}
65e19f54 7354
05589553
XW
7355static struct fixed_file_ref_node *alloc_fixed_file_ref_node(
7356 struct io_ring_ctx *ctx)
05f3fb3c 7357{
05589553 7358 struct fixed_file_ref_node *ref_node;
05f3fb3c 7359
05589553
XW
7360 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7361 if (!ref_node)
7362 return ERR_PTR(-ENOMEM);
05f3fb3c 7363
05589553
XW
7364 if (percpu_ref_init(&ref_node->refs, io_file_data_ref_zero,
7365 0, GFP_KERNEL)) {
7366 kfree(ref_node);
7367 return ERR_PTR(-ENOMEM);
7368 }
7369 INIT_LIST_HEAD(&ref_node->node);
7370 INIT_LIST_HEAD(&ref_node->file_list);
05589553
XW
7371 ref_node->file_data = ctx->file_data;
7372 return ref_node;
05589553
XW
7373}
7374
7375static void destroy_fixed_file_ref_node(struct fixed_file_ref_node *ref_node)
7376{
7377 percpu_ref_exit(&ref_node->refs);
7378 kfree(ref_node);
65e19f54
JA
7379}
7380
6b06314c
JA
7381static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7382 unsigned nr_args)
7383{
7384 __s32 __user *fds = (__s32 __user *) arg;
65e19f54 7385 unsigned nr_tables;
05f3fb3c 7386 struct file *file;
6b06314c
JA
7387 int fd, ret = 0;
7388 unsigned i;
05589553 7389 struct fixed_file_ref_node *ref_node;
6b06314c 7390
05f3fb3c 7391 if (ctx->file_data)
6b06314c
JA
7392 return -EBUSY;
7393 if (!nr_args)
7394 return -EINVAL;
7395 if (nr_args > IORING_MAX_FIXED_FILES)
7396 return -EMFILE;
7397
05f3fb3c
JA
7398 ctx->file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
7399 if (!ctx->file_data)
7400 return -ENOMEM;
7401 ctx->file_data->ctx = ctx;
7402 init_completion(&ctx->file_data->done);
05589553 7403 INIT_LIST_HEAD(&ctx->file_data->ref_list);
f7fe9346 7404 spin_lock_init(&ctx->file_data->lock);
05f3fb3c 7405
65e19f54 7406 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
05f3fb3c
JA
7407 ctx->file_data->table = kcalloc(nr_tables,
7408 sizeof(struct fixed_file_table),
65e19f54 7409 GFP_KERNEL);
05f3fb3c
JA
7410 if (!ctx->file_data->table) {
7411 kfree(ctx->file_data);
7412 ctx->file_data = NULL;
6b06314c 7413 return -ENOMEM;
05f3fb3c
JA
7414 }
7415
05589553 7416 if (percpu_ref_init(&ctx->file_data->refs, io_file_ref_kill,
05f3fb3c
JA
7417 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
7418 kfree(ctx->file_data->table);
7419 kfree(ctx->file_data);
7420 ctx->file_data = NULL;
6b06314c 7421 return -ENOMEM;
05f3fb3c 7422 }
6b06314c 7423
65e19f54 7424 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
05f3fb3c
JA
7425 percpu_ref_exit(&ctx->file_data->refs);
7426 kfree(ctx->file_data->table);
7427 kfree(ctx->file_data);
7428 ctx->file_data = NULL;
65e19f54
JA
7429 return -ENOMEM;
7430 }
7431
08a45173 7432 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
65e19f54
JA
7433 struct fixed_file_table *table;
7434 unsigned index;
7435
6b06314c
JA
7436 ret = -EFAULT;
7437 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
7438 break;
08a45173
JA
7439 /* allow sparse sets */
7440 if (fd == -1) {
7441 ret = 0;
7442 continue;
7443 }
6b06314c 7444
05f3fb3c 7445 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
65e19f54 7446 index = i & IORING_FILE_TABLE_MASK;
05f3fb3c 7447 file = fget(fd);
6b06314c
JA
7448
7449 ret = -EBADF;
05f3fb3c 7450 if (!file)
6b06314c 7451 break;
05f3fb3c 7452
6b06314c
JA
7453 /*
7454 * Don't allow io_uring instances to be registered. If UNIX
7455 * isn't enabled, then this causes a reference cycle and this
7456 * instance can never get freed. If UNIX is enabled we'll
7457 * handle it just fine, but there's still no point in allowing
7458 * a ring fd as it doesn't support regular read/write anyway.
7459 */
05f3fb3c
JA
7460 if (file->f_op == &io_uring_fops) {
7461 fput(file);
6b06314c
JA
7462 break;
7463 }
6b06314c 7464 ret = 0;
05f3fb3c 7465 table->files[index] = file;
6b06314c
JA
7466 }
7467
7468 if (ret) {
65e19f54 7469 for (i = 0; i < ctx->nr_user_files; i++) {
65e19f54
JA
7470 file = io_file_from_index(ctx, i);
7471 if (file)
7472 fput(file);
7473 }
7474 for (i = 0; i < nr_tables; i++)
05f3fb3c 7475 kfree(ctx->file_data->table[i].files);
6b06314c 7476
667e57da 7477 percpu_ref_exit(&ctx->file_data->refs);
05f3fb3c
JA
7478 kfree(ctx->file_data->table);
7479 kfree(ctx->file_data);
7480 ctx->file_data = NULL;
6b06314c
JA
7481 ctx->nr_user_files = 0;
7482 return ret;
7483 }
7484
7485 ret = io_sqe_files_scm(ctx);
05589553 7486 if (ret) {
6b06314c 7487 io_sqe_files_unregister(ctx);
05589553
XW
7488 return ret;
7489 }
6b06314c 7490
05589553
XW
7491 ref_node = alloc_fixed_file_ref_node(ctx);
7492 if (IS_ERR(ref_node)) {
7493 io_sqe_files_unregister(ctx);
7494 return PTR_ERR(ref_node);
7495 }
7496
7497 ctx->file_data->cur_refs = &ref_node->refs;
6a4d07cd 7498 spin_lock(&ctx->file_data->lock);
05589553 7499 list_add(&ref_node->node, &ctx->file_data->ref_list);
6a4d07cd 7500 spin_unlock(&ctx->file_data->lock);
05589553 7501 percpu_ref_get(&ctx->file_data->refs);
6b06314c
JA
7502 return ret;
7503}
7504
c3a31e60
JA
7505static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7506 int index)
7507{
7508#if defined(CONFIG_UNIX)
7509 struct sock *sock = ctx->ring_sock->sk;
7510 struct sk_buff_head *head = &sock->sk_receive_queue;
7511 struct sk_buff *skb;
7512
7513 /*
7514 * See if we can merge this file into an existing skb SCM_RIGHTS
7515 * file set. If there's no room, fall back to allocating a new skb
7516 * and filling it in.
7517 */
7518 spin_lock_irq(&head->lock);
7519 skb = skb_peek(head);
7520 if (skb) {
7521 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7522
7523 if (fpl->count < SCM_MAX_FD) {
7524 __skb_unlink(skb, head);
7525 spin_unlock_irq(&head->lock);
7526 fpl->fp[fpl->count] = get_file(file);
7527 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7528 fpl->count++;
7529 spin_lock_irq(&head->lock);
7530 __skb_queue_head(head, skb);
7531 } else {
7532 skb = NULL;
7533 }
7534 }
7535 spin_unlock_irq(&head->lock);
7536
7537 if (skb) {
7538 fput(file);
7539 return 0;
7540 }
7541
7542 return __io_sqe_files_scm(ctx, 1, index);
7543#else
7544 return 0;
7545#endif
7546}
7547
a5318d3c 7548static int io_queue_file_removal(struct fixed_file_data *data,
05589553 7549 struct file *file)
05f3fb3c 7550{
a5318d3c 7551 struct io_file_put *pfile;
05589553
XW
7552 struct percpu_ref *refs = data->cur_refs;
7553 struct fixed_file_ref_node *ref_node;
05f3fb3c 7554
05f3fb3c 7555 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
a5318d3c
HD
7556 if (!pfile)
7557 return -ENOMEM;
05f3fb3c 7558
05589553 7559 ref_node = container_of(refs, struct fixed_file_ref_node, refs);
05f3fb3c 7560 pfile->file = file;
05589553
XW
7561 list_add(&pfile->list, &ref_node->file_list);
7562
a5318d3c 7563 return 0;
05f3fb3c
JA
7564}
7565
7566static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7567 struct io_uring_files_update *up,
7568 unsigned nr_args)
7569{
7570 struct fixed_file_data *data = ctx->file_data;
05589553 7571 struct fixed_file_ref_node *ref_node;
05f3fb3c 7572 struct file *file;
c3a31e60
JA
7573 __s32 __user *fds;
7574 int fd, i, err;
7575 __u32 done;
05589553 7576 bool needs_switch = false;
c3a31e60 7577
05f3fb3c 7578 if (check_add_overflow(up->offset, nr_args, &done))
c3a31e60
JA
7579 return -EOVERFLOW;
7580 if (done > ctx->nr_user_files)
7581 return -EINVAL;
7582
05589553
XW
7583 ref_node = alloc_fixed_file_ref_node(ctx);
7584 if (IS_ERR(ref_node))
7585 return PTR_ERR(ref_node);
7586
c3a31e60 7587 done = 0;
05f3fb3c 7588 fds = u64_to_user_ptr(up->fds);
c3a31e60 7589 while (nr_args) {
65e19f54
JA
7590 struct fixed_file_table *table;
7591 unsigned index;
7592
c3a31e60
JA
7593 err = 0;
7594 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7595 err = -EFAULT;
7596 break;
7597 }
05f3fb3c
JA
7598 i = array_index_nospec(up->offset, ctx->nr_user_files);
7599 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
65e19f54
JA
7600 index = i & IORING_FILE_TABLE_MASK;
7601 if (table->files[index]) {
98dfd502 7602 file = table->files[index];
a5318d3c
HD
7603 err = io_queue_file_removal(data, file);
7604 if (err)
7605 break;
65e19f54 7606 table->files[index] = NULL;
05589553 7607 needs_switch = true;
c3a31e60
JA
7608 }
7609 if (fd != -1) {
c3a31e60
JA
7610 file = fget(fd);
7611 if (!file) {
7612 err = -EBADF;
7613 break;
7614 }
7615 /*
7616 * Don't allow io_uring instances to be registered. If
7617 * UNIX isn't enabled, then this causes a reference
7618 * cycle and this instance can never get freed. If UNIX
7619 * is enabled we'll handle it just fine, but there's
7620 * still no point in allowing a ring fd as it doesn't
7621 * support regular read/write anyway.
7622 */
7623 if (file->f_op == &io_uring_fops) {
7624 fput(file);
7625 err = -EBADF;
7626 break;
7627 }
65e19f54 7628 table->files[index] = file;
c3a31e60 7629 err = io_sqe_file_register(ctx, file, i);
f3bd9dae 7630 if (err) {
95d1c8e5 7631 table->files[index] = NULL;
f3bd9dae 7632 fput(file);
c3a31e60 7633 break;
f3bd9dae 7634 }
c3a31e60
JA
7635 }
7636 nr_args--;
7637 done++;
05f3fb3c
JA
7638 up->offset++;
7639 }
7640
05589553
XW
7641 if (needs_switch) {
7642 percpu_ref_kill(data->cur_refs);
6a4d07cd 7643 spin_lock(&data->lock);
05589553
XW
7644 list_add(&ref_node->node, &data->ref_list);
7645 data->cur_refs = &ref_node->refs;
6a4d07cd 7646 spin_unlock(&data->lock);
05589553
XW
7647 percpu_ref_get(&ctx->file_data->refs);
7648 } else
7649 destroy_fixed_file_ref_node(ref_node);
c3a31e60
JA
7650
7651 return done ? done : err;
7652}
05589553 7653
05f3fb3c
JA
7654static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7655 unsigned nr_args)
7656{
7657 struct io_uring_files_update up;
7658
7659 if (!ctx->file_data)
7660 return -ENXIO;
7661 if (!nr_args)
7662 return -EINVAL;
7663 if (copy_from_user(&up, arg, sizeof(up)))
7664 return -EFAULT;
7665 if (up.resv)
7666 return -EINVAL;
7667
7668 return __io_sqe_files_update(ctx, &up, nr_args);
7669}
c3a31e60 7670
e9fd9396 7671static void io_free_work(struct io_wq_work *work)
7d723065
JA
7672{
7673 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7674
e9fd9396 7675 /* Consider that io_steal_work() relies on this ref */
7d723065
JA
7676 io_put_req(req);
7677}
7678
24369c2e
PB
7679static int io_init_wq_offload(struct io_ring_ctx *ctx,
7680 struct io_uring_params *p)
7681{
7682 struct io_wq_data data;
7683 struct fd f;
7684 struct io_ring_ctx *ctx_attach;
7685 unsigned int concurrency;
7686 int ret = 0;
7687
7688 data.user = ctx->user;
e9fd9396 7689 data.free_work = io_free_work;
f5fa38c5 7690 data.do_work = io_wq_submit_work;
24369c2e
PB
7691
7692 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
7693 /* Do QD, or 4 * CPUS, whatever is smallest */
7694 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7695
7696 ctx->io_wq = io_wq_create(concurrency, &data);
7697 if (IS_ERR(ctx->io_wq)) {
7698 ret = PTR_ERR(ctx->io_wq);
7699 ctx->io_wq = NULL;
7700 }
7701 return ret;
7702 }
7703
7704 f = fdget(p->wq_fd);
7705 if (!f.file)
7706 return -EBADF;
7707
7708 if (f.file->f_op != &io_uring_fops) {
7709 ret = -EINVAL;
7710 goto out_fput;
7711 }
7712
7713 ctx_attach = f.file->private_data;
7714 /* @io_wq is protected by holding the fd */
7715 if (!io_wq_get(ctx_attach->io_wq, &data)) {
7716 ret = -EINVAL;
7717 goto out_fput;
7718 }
7719
7720 ctx->io_wq = ctx_attach->io_wq;
7721out_fput:
7722 fdput(f);
7723 return ret;
7724}
7725
0f212204
JA
7726static int io_uring_alloc_task_context(struct task_struct *task)
7727{
7728 struct io_uring_task *tctx;
7729
7730 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
7731 if (unlikely(!tctx))
7732 return -ENOMEM;
7733
7734 xa_init(&tctx->xa);
7735 init_waitqueue_head(&tctx->wait);
7736 tctx->last = NULL;
7737 tctx->in_idle = 0;
7738 atomic_long_set(&tctx->req_issue, 0);
7739 atomic_long_set(&tctx->req_complete, 0);
7740 task->io_uring = tctx;
7741 return 0;
7742}
7743
7744void __io_uring_free(struct task_struct *tsk)
7745{
7746 struct io_uring_task *tctx = tsk->io_uring;
7747
7748 WARN_ON_ONCE(!xa_empty(&tctx->xa));
7749 xa_destroy(&tctx->xa);
7750 kfree(tctx);
7751 tsk->io_uring = NULL;
7752}
7753
7e84e1c7
SG
7754static int io_sq_offload_create(struct io_ring_ctx *ctx,
7755 struct io_uring_params *p)
2b188cc1
JA
7756{
7757 int ret;
7758
6c271ce2 7759 if (ctx->flags & IORING_SETUP_SQPOLL) {
534ca6d6
JA
7760 struct io_sq_data *sqd;
7761
3ec482d1
JA
7762 ret = -EPERM;
7763 if (!capable(CAP_SYS_ADMIN))
7764 goto err;
7765
534ca6d6
JA
7766 sqd = io_get_sq_data(p);
7767 if (IS_ERR(sqd)) {
7768 ret = PTR_ERR(sqd);
7769 goto err;
7770 }
69fb2131 7771
534ca6d6 7772 ctx->sq_data = sqd;
69fb2131
JA
7773 io_sq_thread_park(sqd);
7774 mutex_lock(&sqd->ctx_lock);
7775 list_add(&ctx->sqd_list, &sqd->ctx_new_list);
7776 mutex_unlock(&sqd->ctx_lock);
7777 io_sq_thread_unpark(sqd);
534ca6d6 7778
917257da
JA
7779 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7780 if (!ctx->sq_thread_idle)
7781 ctx->sq_thread_idle = HZ;
7782
aa06165d
JA
7783 if (sqd->thread)
7784 goto done;
7785
6c271ce2 7786 if (p->flags & IORING_SETUP_SQ_AFF) {
44a9bd18 7787 int cpu = p->sq_thread_cpu;
6c271ce2 7788
917257da 7789 ret = -EINVAL;
44a9bd18
JA
7790 if (cpu >= nr_cpu_ids)
7791 goto err;
7889f44d 7792 if (!cpu_online(cpu))
917257da
JA
7793 goto err;
7794
69fb2131 7795 sqd->thread = kthread_create_on_cpu(io_sq_thread, sqd,
534ca6d6 7796 cpu, "io_uring-sq");
6c271ce2 7797 } else {
69fb2131 7798 sqd->thread = kthread_create(io_sq_thread, sqd,
6c271ce2
JA
7799 "io_uring-sq");
7800 }
534ca6d6
JA
7801 if (IS_ERR(sqd->thread)) {
7802 ret = PTR_ERR(sqd->thread);
7803 sqd->thread = NULL;
6c271ce2
JA
7804 goto err;
7805 }
534ca6d6 7806 ret = io_uring_alloc_task_context(sqd->thread);
0f212204
JA
7807 if (ret)
7808 goto err;
6c271ce2
JA
7809 } else if (p->flags & IORING_SETUP_SQ_AFF) {
7810 /* Can't have SQ_AFF without SQPOLL */
7811 ret = -EINVAL;
7812 goto err;
7813 }
7814
aa06165d 7815done:
24369c2e
PB
7816 ret = io_init_wq_offload(ctx, p);
7817 if (ret)
2b188cc1 7818 goto err;
2b188cc1
JA
7819
7820 return 0;
7821err:
54a91f3b 7822 io_finish_async(ctx);
2b188cc1
JA
7823 return ret;
7824}
7825
7e84e1c7
SG
7826static void io_sq_offload_start(struct io_ring_ctx *ctx)
7827{
534ca6d6
JA
7828 struct io_sq_data *sqd = ctx->sq_data;
7829
7830 if ((ctx->flags & IORING_SETUP_SQPOLL) && sqd->thread)
7831 wake_up_process(sqd->thread);
7e84e1c7
SG
7832}
7833
a087e2b5
BM
7834static inline void __io_unaccount_mem(struct user_struct *user,
7835 unsigned long nr_pages)
2b188cc1
JA
7836{
7837 atomic_long_sub(nr_pages, &user->locked_vm);
7838}
7839
a087e2b5
BM
7840static inline int __io_account_mem(struct user_struct *user,
7841 unsigned long nr_pages)
2b188cc1
JA
7842{
7843 unsigned long page_limit, cur_pages, new_pages;
7844
7845 /* Don't allow more pages than we can safely lock */
7846 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
7847
7848 do {
7849 cur_pages = atomic_long_read(&user->locked_vm);
7850 new_pages = cur_pages + nr_pages;
7851 if (new_pages > page_limit)
7852 return -ENOMEM;
7853 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
7854 new_pages) != cur_pages);
7855
7856 return 0;
7857}
7858
2e0464d4
BM
7859static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
7860 enum io_mem_account acct)
a087e2b5 7861{
aad5d8da 7862 if (ctx->limit_mem)
a087e2b5 7863 __io_unaccount_mem(ctx->user, nr_pages);
30975825 7864
2aede0e4 7865 if (ctx->mm_account) {
2e0464d4 7866 if (acct == ACCT_LOCKED)
2aede0e4 7867 ctx->mm_account->locked_vm -= nr_pages;
2e0464d4 7868 else if (acct == ACCT_PINNED)
2aede0e4 7869 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
2e0464d4 7870 }
a087e2b5
BM
7871}
7872
2e0464d4
BM
7873static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
7874 enum io_mem_account acct)
a087e2b5 7875{
30975825
BM
7876 int ret;
7877
7878 if (ctx->limit_mem) {
7879 ret = __io_account_mem(ctx->user, nr_pages);
7880 if (ret)
7881 return ret;
7882 }
7883
2aede0e4 7884 if (ctx->mm_account) {
2e0464d4 7885 if (acct == ACCT_LOCKED)
2aede0e4 7886 ctx->mm_account->locked_vm += nr_pages;
2e0464d4 7887 else if (acct == ACCT_PINNED)
2aede0e4 7888 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
2e0464d4 7889 }
a087e2b5
BM
7890
7891 return 0;
7892}
7893
2b188cc1
JA
7894static void io_mem_free(void *ptr)
7895{
52e04ef4
MR
7896 struct page *page;
7897
7898 if (!ptr)
7899 return;
2b188cc1 7900
52e04ef4 7901 page = virt_to_head_page(ptr);
2b188cc1
JA
7902 if (put_page_testzero(page))
7903 free_compound_page(page);
7904}
7905
7906static void *io_mem_alloc(size_t size)
7907{
7908 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
7909 __GFP_NORETRY;
7910
7911 return (void *) __get_free_pages(gfp_flags, get_order(size));
7912}
7913
75b28aff
HV
7914static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
7915 size_t *sq_offset)
7916{
7917 struct io_rings *rings;
7918 size_t off, sq_array_size;
7919
7920 off = struct_size(rings, cqes, cq_entries);
7921 if (off == SIZE_MAX)
7922 return SIZE_MAX;
7923
7924#ifdef CONFIG_SMP
7925 off = ALIGN(off, SMP_CACHE_BYTES);
7926 if (off == 0)
7927 return SIZE_MAX;
7928#endif
7929
b36200f5
DV
7930 if (sq_offset)
7931 *sq_offset = off;
7932
75b28aff
HV
7933 sq_array_size = array_size(sizeof(u32), sq_entries);
7934 if (sq_array_size == SIZE_MAX)
7935 return SIZE_MAX;
7936
7937 if (check_add_overflow(off, sq_array_size, &off))
7938 return SIZE_MAX;
7939
75b28aff
HV
7940 return off;
7941}
7942
2b188cc1
JA
7943static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
7944{
75b28aff 7945 size_t pages;
2b188cc1 7946
75b28aff
HV
7947 pages = (size_t)1 << get_order(
7948 rings_size(sq_entries, cq_entries, NULL));
7949 pages += (size_t)1 << get_order(
7950 array_size(sizeof(struct io_uring_sqe), sq_entries));
2b188cc1 7951
75b28aff 7952 return pages;
2b188cc1
JA
7953}
7954
edafccee
JA
7955static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
7956{
7957 int i, j;
7958
7959 if (!ctx->user_bufs)
7960 return -ENXIO;
7961
7962 for (i = 0; i < ctx->nr_user_bufs; i++) {
7963 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7964
7965 for (j = 0; j < imu->nr_bvecs; j++)
f1f6a7dd 7966 unpin_user_page(imu->bvec[j].bv_page);
edafccee 7967
2e0464d4 7968 io_unaccount_mem(ctx, imu->nr_bvecs, ACCT_PINNED);
d4ef6475 7969 kvfree(imu->bvec);
edafccee
JA
7970 imu->nr_bvecs = 0;
7971 }
7972
7973 kfree(ctx->user_bufs);
7974 ctx->user_bufs = NULL;
7975 ctx->nr_user_bufs = 0;
7976 return 0;
7977}
7978
7979static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
7980 void __user *arg, unsigned index)
7981{
7982 struct iovec __user *src;
7983
7984#ifdef CONFIG_COMPAT
7985 if (ctx->compat) {
7986 struct compat_iovec __user *ciovs;
7987 struct compat_iovec ciov;
7988
7989 ciovs = (struct compat_iovec __user *) arg;
7990 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
7991 return -EFAULT;
7992
d55e5f5b 7993 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
edafccee
JA
7994 dst->iov_len = ciov.iov_len;
7995 return 0;
7996 }
7997#endif
7998 src = (struct iovec __user *) arg;
7999 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8000 return -EFAULT;
8001 return 0;
8002}
8003
8004static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
8005 unsigned nr_args)
8006{
8007 struct vm_area_struct **vmas = NULL;
8008 struct page **pages = NULL;
8009 int i, j, got_pages = 0;
8010 int ret = -EINVAL;
8011
8012 if (ctx->user_bufs)
8013 return -EBUSY;
8014 if (!nr_args || nr_args > UIO_MAXIOV)
8015 return -EINVAL;
8016
8017 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
8018 GFP_KERNEL);
8019 if (!ctx->user_bufs)
8020 return -ENOMEM;
8021
8022 for (i = 0; i < nr_args; i++) {
8023 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8024 unsigned long off, start, end, ubuf;
8025 int pret, nr_pages;
8026 struct iovec iov;
8027 size_t size;
8028
8029 ret = io_copy_iov(ctx, &iov, arg, i);
8030 if (ret)
a278682d 8031 goto err;
edafccee
JA
8032
8033 /*
8034 * Don't impose further limits on the size and buffer
8035 * constraints here, we'll -EINVAL later when IO is
8036 * submitted if they are wrong.
8037 */
8038 ret = -EFAULT;
8039 if (!iov.iov_base || !iov.iov_len)
8040 goto err;
8041
8042 /* arbitrary limit, but we need something */
8043 if (iov.iov_len > SZ_1G)
8044 goto err;
8045
8046 ubuf = (unsigned long) iov.iov_base;
8047 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8048 start = ubuf >> PAGE_SHIFT;
8049 nr_pages = end - start;
8050
2e0464d4 8051 ret = io_account_mem(ctx, nr_pages, ACCT_PINNED);
a087e2b5
BM
8052 if (ret)
8053 goto err;
edafccee
JA
8054
8055 ret = 0;
8056 if (!pages || nr_pages > got_pages) {
a8c73c1a
DE
8057 kvfree(vmas);
8058 kvfree(pages);
d4ef6475 8059 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
edafccee 8060 GFP_KERNEL);
d4ef6475 8061 vmas = kvmalloc_array(nr_pages,
edafccee
JA
8062 sizeof(struct vm_area_struct *),
8063 GFP_KERNEL);
8064 if (!pages || !vmas) {
8065 ret = -ENOMEM;
2e0464d4 8066 io_unaccount_mem(ctx, nr_pages, ACCT_PINNED);
edafccee
JA
8067 goto err;
8068 }
8069 got_pages = nr_pages;
8070 }
8071
d4ef6475 8072 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
edafccee
JA
8073 GFP_KERNEL);
8074 ret = -ENOMEM;
8075 if (!imu->bvec) {
2e0464d4 8076 io_unaccount_mem(ctx, nr_pages, ACCT_PINNED);
edafccee
JA
8077 goto err;
8078 }
8079
8080 ret = 0;
d8ed45c5 8081 mmap_read_lock(current->mm);
2113b05d 8082 pret = pin_user_pages(ubuf, nr_pages,
932f4a63
IW
8083 FOLL_WRITE | FOLL_LONGTERM,
8084 pages, vmas);
edafccee
JA
8085 if (pret == nr_pages) {
8086 /* don't support file backed memory */
8087 for (j = 0; j < nr_pages; j++) {
8088 struct vm_area_struct *vma = vmas[j];
8089
8090 if (vma->vm_file &&
8091 !is_file_hugepages(vma->vm_file)) {
8092 ret = -EOPNOTSUPP;
8093 break;
8094 }
8095 }
8096 } else {
8097 ret = pret < 0 ? pret : -EFAULT;
8098 }
d8ed45c5 8099 mmap_read_unlock(current->mm);
edafccee
JA
8100 if (ret) {
8101 /*
8102 * if we did partial map, or found file backed vmas,
8103 * release any pages we did get
8104 */
27c4d3a3 8105 if (pret > 0)
f1f6a7dd 8106 unpin_user_pages(pages, pret);
2e0464d4 8107 io_unaccount_mem(ctx, nr_pages, ACCT_PINNED);
d4ef6475 8108 kvfree(imu->bvec);
edafccee
JA
8109 goto err;
8110 }
8111
8112 off = ubuf & ~PAGE_MASK;
8113 size = iov.iov_len;
8114 for (j = 0; j < nr_pages; j++) {
8115 size_t vec_len;
8116
8117 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8118 imu->bvec[j].bv_page = pages[j];
8119 imu->bvec[j].bv_len = vec_len;
8120 imu->bvec[j].bv_offset = off;
8121 off = 0;
8122 size -= vec_len;
8123 }
8124 /* store original address for later verification */
8125 imu->ubuf = ubuf;
8126 imu->len = iov.iov_len;
8127 imu->nr_bvecs = nr_pages;
8128
8129 ctx->nr_user_bufs++;
8130 }
d4ef6475
MR
8131 kvfree(pages);
8132 kvfree(vmas);
edafccee
JA
8133 return 0;
8134err:
d4ef6475
MR
8135 kvfree(pages);
8136 kvfree(vmas);
edafccee
JA
8137 io_sqe_buffer_unregister(ctx);
8138 return ret;
8139}
8140
9b402849
JA
8141static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8142{
8143 __s32 __user *fds = arg;
8144 int fd;
8145
8146 if (ctx->cq_ev_fd)
8147 return -EBUSY;
8148
8149 if (copy_from_user(&fd, fds, sizeof(*fds)))
8150 return -EFAULT;
8151
8152 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8153 if (IS_ERR(ctx->cq_ev_fd)) {
8154 int ret = PTR_ERR(ctx->cq_ev_fd);
8155 ctx->cq_ev_fd = NULL;
8156 return ret;
8157 }
8158
8159 return 0;
8160}
8161
8162static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8163{
8164 if (ctx->cq_ev_fd) {
8165 eventfd_ctx_put(ctx->cq_ev_fd);
8166 ctx->cq_ev_fd = NULL;
8167 return 0;
8168 }
8169
8170 return -ENXIO;
8171}
8172
5a2e745d
JA
8173static int __io_destroy_buffers(int id, void *p, void *data)
8174{
8175 struct io_ring_ctx *ctx = data;
8176 struct io_buffer *buf = p;
8177
067524e9 8178 __io_remove_buffers(ctx, buf, id, -1U);
5a2e745d
JA
8179 return 0;
8180}
8181
8182static void io_destroy_buffers(struct io_ring_ctx *ctx)
8183{
8184 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
8185 idr_destroy(&ctx->io_buffer_idr);
8186}
8187
2b188cc1
JA
8188static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8189{
6b06314c 8190 io_finish_async(ctx);
5dbcad51 8191 io_sqe_buffer_unregister(ctx);
2aede0e4
JA
8192
8193 if (ctx->sqo_task) {
8194 put_task_struct(ctx->sqo_task);
8195 ctx->sqo_task = NULL;
8196 mmdrop(ctx->mm_account);
8197 ctx->mm_account = NULL;
30975825 8198 }
def596e9 8199
6b06314c 8200 io_sqe_files_unregister(ctx);
9b402849 8201 io_eventfd_unregister(ctx);
5a2e745d 8202 io_destroy_buffers(ctx);
41726c9a 8203 idr_destroy(&ctx->personality_idr);
def596e9 8204
2b188cc1 8205#if defined(CONFIG_UNIX)
355e8d26
EB
8206 if (ctx->ring_sock) {
8207 ctx->ring_sock->file = NULL; /* so that iput() is called */
2b188cc1 8208 sock_release(ctx->ring_sock);
355e8d26 8209 }
2b188cc1
JA
8210#endif
8211
75b28aff 8212 io_mem_free(ctx->rings);
2b188cc1 8213 io_mem_free(ctx->sq_sqes);
2b188cc1
JA
8214
8215 percpu_ref_exit(&ctx->refs);
2b188cc1 8216 free_uid(ctx->user);
181e448d 8217 put_cred(ctx->creds);
78076bb6 8218 kfree(ctx->cancel_hash);
0ddf92e8 8219 kmem_cache_free(req_cachep, ctx->fallback_req);
2b188cc1
JA
8220 kfree(ctx);
8221}
8222
8223static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8224{
8225 struct io_ring_ctx *ctx = file->private_data;
8226 __poll_t mask = 0;
8227
8228 poll_wait(file, &ctx->cq_wait, wait);
4f7067c3
SB
8229 /*
8230 * synchronizes with barrier from wq_has_sleeper call in
8231 * io_commit_cqring
8232 */
2b188cc1 8233 smp_rmb();
75b28aff
HV
8234 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
8235 ctx->rings->sq_ring_entries)
2b188cc1 8236 mask |= EPOLLOUT | EPOLLWRNORM;
63e5d81f 8237 if (io_cqring_events(ctx, false))
2b188cc1
JA
8238 mask |= EPOLLIN | EPOLLRDNORM;
8239
8240 return mask;
8241}
8242
8243static int io_uring_fasync(int fd, struct file *file, int on)
8244{
8245 struct io_ring_ctx *ctx = file->private_data;
8246
8247 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8248}
8249
071698e1
JA
8250static int io_remove_personalities(int id, void *p, void *data)
8251{
8252 struct io_ring_ctx *ctx = data;
8253 const struct cred *cred;
8254
8255 cred = idr_remove(&ctx->personality_idr, id);
8256 if (cred)
8257 put_cred(cred);
8258 return 0;
8259}
8260
85faa7b8
JA
8261static void io_ring_exit_work(struct work_struct *work)
8262{
b2edc0a7
PB
8263 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
8264 exit_work);
85faa7b8 8265
56952e91
JA
8266 /*
8267 * If we're doing polled IO and end up having requests being
8268 * submitted async (out-of-line), then completions can come in while
8269 * we're waiting for refs to drop. We need to reap these manually,
8270 * as nobody else will be looking for them.
8271 */
b2edc0a7 8272 do {
56952e91 8273 if (ctx->rings)
e6c8aa9a 8274 io_cqring_overflow_flush(ctx, true, NULL, NULL);
b2edc0a7
PB
8275 io_iopoll_try_reap_events(ctx);
8276 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
85faa7b8
JA
8277 io_ring_ctx_free(ctx);
8278}
8279
2b188cc1
JA
8280static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8281{
8282 mutex_lock(&ctx->uring_lock);
8283 percpu_ref_kill(&ctx->refs);
8284 mutex_unlock(&ctx->uring_lock);
8285
f3606e3a
JA
8286 io_kill_timeouts(ctx, NULL);
8287 io_poll_remove_all(ctx, NULL);
561fb04a
JA
8288
8289 if (ctx->io_wq)
8290 io_wq_cancel_all(ctx->io_wq);
8291
15dff286
JA
8292 /* if we failed setting up the ctx, we might not have any rings */
8293 if (ctx->rings)
e6c8aa9a 8294 io_cqring_overflow_flush(ctx, true, NULL, NULL);
b2edc0a7 8295 io_iopoll_try_reap_events(ctx);
071698e1 8296 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
309fc03a
JA
8297
8298 /*
8299 * Do this upfront, so we won't have a grace period where the ring
8300 * is closed but resources aren't reaped yet. This can cause
8301 * spurious failure in setting up a new ring.
8302 */
760618f7
JA
8303 io_unaccount_mem(ctx, ring_pages(ctx->sq_entries, ctx->cq_entries),
8304 ACCT_LOCKED);
309fc03a 8305
85faa7b8 8306 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
fc666777
JA
8307 /*
8308 * Use system_unbound_wq to avoid spawning tons of event kworkers
8309 * if we're exiting a ton of rings at the same time. It just adds
8310 * noise and overhead, there's no discernable change in runtime
8311 * over using system_wq.
8312 */
8313 queue_work(system_unbound_wq, &ctx->exit_work);
2b188cc1
JA
8314}
8315
8316static int io_uring_release(struct inode *inode, struct file *file)
8317{
8318 struct io_ring_ctx *ctx = file->private_data;
8319
8320 file->private_data = NULL;
8321 io_ring_ctx_wait_and_kill(ctx);
8322 return 0;
8323}
8324
67c4d9e6
PB
8325static bool io_wq_files_match(struct io_wq_work *work, void *data)
8326{
8327 struct files_struct *files = data;
8328
0f212204 8329 return !files || work->files == files;
67c4d9e6
PB
8330}
8331
f254ac04
JA
8332/*
8333 * Returns true if 'preq' is the link parent of 'req'
8334 */
8335static bool io_match_link(struct io_kiocb *preq, struct io_kiocb *req)
8336{
8337 struct io_kiocb *link;
8338
8339 if (!(preq->flags & REQ_F_LINK_HEAD))
8340 return false;
8341
8342 list_for_each_entry(link, &preq->link_list, link_list) {
8343 if (link == req)
8344 return true;
8345 }
8346
8347 return false;
8348}
8349
c127a2a1
PB
8350static bool io_match_link_files(struct io_kiocb *req,
8351 struct files_struct *files)
8352{
8353 struct io_kiocb *link;
8354
8355 if (io_match_files(req, files))
8356 return true;
8357 if (req->flags & REQ_F_LINK_HEAD) {
8358 list_for_each_entry(link, &req->link_list, link_list) {
8359 if (io_match_files(link, files))
8360 return true;
8361 }
8362 }
8363 return false;
8364}
8365
f254ac04
JA
8366/*
8367 * We're looking to cancel 'req' because it's holding on to our files, but
8368 * 'req' could be a link to another request. See if it is, and cancel that
8369 * parent request if so.
8370 */
8371static bool io_poll_remove_link(struct io_ring_ctx *ctx, struct io_kiocb *req)
8372{
8373 struct hlist_node *tmp;
8374 struct io_kiocb *preq;
8375 bool found = false;
8376 int i;
8377
8378 spin_lock_irq(&ctx->completion_lock);
8379 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
8380 struct hlist_head *list;
8381
8382 list = &ctx->cancel_hash[i];
8383 hlist_for_each_entry_safe(preq, tmp, list, hash_node) {
8384 found = io_match_link(preq, req);
8385 if (found) {
8386 io_poll_remove_one(preq);
8387 break;
8388 }
8389 }
8390 }
8391 spin_unlock_irq(&ctx->completion_lock);
8392 return found;
8393}
8394
8395static bool io_timeout_remove_link(struct io_ring_ctx *ctx,
8396 struct io_kiocb *req)
8397{
8398 struct io_kiocb *preq;
8399 bool found = false;
8400
8401 spin_lock_irq(&ctx->completion_lock);
8402 list_for_each_entry(preq, &ctx->timeout_list, timeout.list) {
8403 found = io_match_link(preq, req);
8404 if (found) {
8405 __io_timeout_cancel(preq);
8406 break;
8407 }
8408 }
8409 spin_unlock_irq(&ctx->completion_lock);
8410 return found;
8411}
8412
b711d4ea
JA
8413static bool io_cancel_link_cb(struct io_wq_work *work, void *data)
8414{
8415 return io_match_link(container_of(work, struct io_kiocb, work), data);
8416}
8417
8418static void io_attempt_cancel(struct io_ring_ctx *ctx, struct io_kiocb *req)
8419{
8420 enum io_wq_cancel cret;
8421
8422 /* cancel this particular work, if it's running */
8423 cret = io_wq_cancel_work(ctx->io_wq, &req->work);
8424 if (cret != IO_WQ_CANCEL_NOTFOUND)
8425 return;
8426
8427 /* find links that hold this pending, cancel those */
8428 cret = io_wq_cancel_cb(ctx->io_wq, io_cancel_link_cb, req, true);
8429 if (cret != IO_WQ_CANCEL_NOTFOUND)
8430 return;
8431
8432 /* if we have a poll link holding this pending, cancel that */
8433 if (io_poll_remove_link(ctx, req))
8434 return;
8435
8436 /* final option, timeout link is holding this req pending */
8437 io_timeout_remove_link(ctx, req);
8438}
8439
b7ddce3c
PB
8440static void io_cancel_defer_files(struct io_ring_ctx *ctx,
8441 struct files_struct *files)
8442{
8443 struct io_defer_entry *de = NULL;
8444 LIST_HEAD(list);
8445
8446 spin_lock_irq(&ctx->completion_lock);
8447 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
c127a2a1 8448 if (io_match_link_files(de->req, files)) {
b7ddce3c
PB
8449 list_cut_position(&list, &ctx->defer_list, &de->list);
8450 break;
8451 }
8452 }
8453 spin_unlock_irq(&ctx->completion_lock);
8454
8455 while (!list_empty(&list)) {
8456 de = list_first_entry(&list, struct io_defer_entry, list);
8457 list_del_init(&de->list);
8458 req_set_fail_links(de->req);
8459 io_put_req(de->req);
8460 io_req_complete(de->req, -ECANCELED);
8461 kfree(de);
8462 }
8463}
8464
76e1b642
JA
8465/*
8466 * Returns true if we found and killed one or more files pinning requests
8467 */
8468static bool io_uring_cancel_files(struct io_ring_ctx *ctx,
fcb323cc
JA
8469 struct files_struct *files)
8470{
67c4d9e6 8471 if (list_empty_careful(&ctx->inflight_list))
76e1b642 8472 return false;
67c4d9e6 8473
b7ddce3c 8474 io_cancel_defer_files(ctx, files);
67c4d9e6
PB
8475 /* cancel all at once, should be faster than doing it one by one*/
8476 io_wq_cancel_cb(ctx->io_wq, io_wq_files_match, files, true);
8477
fcb323cc 8478 while (!list_empty_careful(&ctx->inflight_list)) {
d8f1b971
XW
8479 struct io_kiocb *cancel_req = NULL, *req;
8480 DEFINE_WAIT(wait);
fcb323cc
JA
8481
8482 spin_lock_irq(&ctx->inflight_lock);
8483 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
0f212204 8484 if (files && req->work.files != files)
768134d4
JA
8485 continue;
8486 /* req is being completed, ignore */
8487 if (!refcount_inc_not_zero(&req->refs))
8488 continue;
8489 cancel_req = req;
8490 break;
fcb323cc 8491 }
768134d4 8492 if (cancel_req)
fcb323cc 8493 prepare_to_wait(&ctx->inflight_wait, &wait,
768134d4 8494 TASK_UNINTERRUPTIBLE);
fcb323cc
JA
8495 spin_unlock_irq(&ctx->inflight_lock);
8496
768134d4
JA
8497 /* We need to keep going until we don't find a matching req */
8498 if (!cancel_req)
fcb323cc 8499 break;
bb175342
PB
8500 /* cancel this request, or head link requests */
8501 io_attempt_cancel(ctx, cancel_req);
8502 io_put_req(cancel_req);
6200b0ae
JA
8503 /* cancellations _may_ trigger task work */
8504 io_run_task_work();
fcb323cc 8505 schedule();
d8f1b971 8506 finish_wait(&ctx->inflight_wait, &wait);
fcb323cc 8507 }
76e1b642
JA
8508
8509 return true;
fcb323cc
JA
8510}
8511
801dd57b 8512static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
44e728b8 8513{
801dd57b
PB
8514 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8515 struct task_struct *task = data;
44e728b8 8516
f3606e3a 8517 return io_task_match(req, task);
44e728b8
PB
8518}
8519
0f212204
JA
8520static bool __io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
8521 struct task_struct *task,
8522 struct files_struct *files)
8523{
8524 bool ret;
8525
8526 ret = io_uring_cancel_files(ctx, files);
8527 if (!files) {
8528 enum io_wq_cancel cret;
8529
8530 cret = io_wq_cancel_cb(ctx->io_wq, io_cancel_task_cb, task, true);
8531 if (cret != IO_WQ_CANCEL_NOTFOUND)
8532 ret = true;
8533
8534 /* SQPOLL thread does its own polling */
8535 if (!(ctx->flags & IORING_SETUP_SQPOLL)) {
8536 while (!list_empty_careful(&ctx->iopoll_list)) {
8537 io_iopoll_try_reap_events(ctx);
8538 ret = true;
8539 }
8540 }
8541
8542 ret |= io_poll_remove_all(ctx, task);
8543 ret |= io_kill_timeouts(ctx, task);
8544 }
8545
8546 return ret;
8547}
8548
8549/*
8550 * We need to iteratively cancel requests, in case a request has dependent
8551 * hard links. These persist even for failure of cancelations, hence keep
8552 * looping until none are found.
8553 */
8554static void io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
8555 struct files_struct *files)
8556{
8557 struct task_struct *task = current;
8558
534ca6d6
JA
8559 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data)
8560 task = ctx->sq_data->thread;
0f212204
JA
8561
8562 io_cqring_overflow_flush(ctx, true, task, files);
8563
8564 while (__io_uring_cancel_task_requests(ctx, task, files)) {
8565 io_run_task_work();
8566 cond_resched();
8567 }
8568}
8569
8570/*
8571 * Note that this task has used io_uring. We use it for cancelation purposes.
8572 */
8573static int io_uring_add_task_file(struct file *file)
8574{
8575 if (unlikely(!current->io_uring)) {
8576 int ret;
8577
8578 ret = io_uring_alloc_task_context(current);
8579 if (unlikely(ret))
8580 return ret;
8581 }
8582 if (current->io_uring->last != file) {
8583 XA_STATE(xas, &current->io_uring->xa, (unsigned long) file);
8584 void *old;
8585
8586 rcu_read_lock();
8587 old = xas_load(&xas);
8588 if (old != file) {
8589 get_file(file);
8590 xas_lock(&xas);
8591 xas_store(&xas, file);
8592 xas_unlock(&xas);
8593 }
8594 rcu_read_unlock();
8595 current->io_uring->last = file;
8596 }
8597
8598 return 0;
8599}
8600
8601/*
8602 * Remove this io_uring_file -> task mapping.
8603 */
8604static void io_uring_del_task_file(struct file *file)
8605{
8606 struct io_uring_task *tctx = current->io_uring;
8607 XA_STATE(xas, &tctx->xa, (unsigned long) file);
8608
8609 if (tctx->last == file)
8610 tctx->last = NULL;
8611
8612 xas_lock(&xas);
8613 file = xas_store(&xas, NULL);
8614 xas_unlock(&xas);
8615
8616 if (file)
8617 fput(file);
8618}
8619
8620static void __io_uring_attempt_task_drop(struct file *file)
8621{
8622 XA_STATE(xas, &current->io_uring->xa, (unsigned long) file);
8623 struct file *old;
8624
8625 rcu_read_lock();
8626 old = xas_load(&xas);
8627 rcu_read_unlock();
8628
8629 if (old == file)
8630 io_uring_del_task_file(file);
8631}
8632
8633/*
8634 * Drop task note for this file if we're the only ones that hold it after
8635 * pending fput()
8636 */
8637static void io_uring_attempt_task_drop(struct file *file, bool exiting)
8638{
8639 if (!current->io_uring)
8640 return;
8641 /*
8642 * fput() is pending, will be 2 if the only other ref is our potential
8643 * task file note. If the task is exiting, drop regardless of count.
8644 */
8645 if (!exiting && atomic_long_read(&file->f_count) != 2)
8646 return;
8647
8648 __io_uring_attempt_task_drop(file);
8649}
8650
8651void __io_uring_files_cancel(struct files_struct *files)
8652{
8653 struct io_uring_task *tctx = current->io_uring;
8654 XA_STATE(xas, &tctx->xa, 0);
8655
8656 /* make sure overflow events are dropped */
8657 tctx->in_idle = true;
8658
8659 do {
8660 struct io_ring_ctx *ctx;
8661 struct file *file;
8662
8663 xas_lock(&xas);
8664 file = xas_next_entry(&xas, ULONG_MAX);
8665 xas_unlock(&xas);
8666
8667 if (!file)
8668 break;
8669
8670 ctx = file->private_data;
8671
8672 io_uring_cancel_task_requests(ctx, files);
8673 if (files)
8674 io_uring_del_task_file(file);
8675 } while (1);
8676}
8677
8678static inline bool io_uring_task_idle(struct io_uring_task *tctx)
8679{
8680 return atomic_long_read(&tctx->req_issue) ==
8681 atomic_long_read(&tctx->req_complete);
8682}
8683
8684/*
8685 * Find any io_uring fd that this task has registered or done IO on, and cancel
8686 * requests.
8687 */
8688void __io_uring_task_cancel(void)
8689{
8690 struct io_uring_task *tctx = current->io_uring;
8691 DEFINE_WAIT(wait);
8692 long completions;
8693
8694 /* make sure overflow events are dropped */
8695 tctx->in_idle = true;
8696
8697 while (!io_uring_task_idle(tctx)) {
8698 /* read completions before cancelations */
8699 completions = atomic_long_read(&tctx->req_complete);
8700 __io_uring_files_cancel(NULL);
8701
8702 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
8703
8704 /*
8705 * If we've seen completions, retry. This avoids a race where
8706 * a completion comes in before we did prepare_to_wait().
8707 */
8708 if (completions != atomic_long_read(&tctx->req_complete))
8709 continue;
8710 if (io_uring_task_idle(tctx))
8711 break;
8712 schedule();
8713 }
8714
8715 finish_wait(&tctx->wait, &wait);
8716 tctx->in_idle = false;
8717}
8718
fcb323cc
JA
8719static int io_uring_flush(struct file *file, void *data)
8720{
8721 struct io_ring_ctx *ctx = file->private_data;
8722
6ab23144
JA
8723 /*
8724 * If the task is going away, cancel work it may have pending
8725 */
801dd57b 8726 if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
0f212204 8727 data = NULL;
6ab23144 8728
0f212204
JA
8729 io_uring_cancel_task_requests(ctx, data);
8730 io_uring_attempt_task_drop(file, !data);
fcb323cc
JA
8731 return 0;
8732}
8733
6c5c240e
RP
8734static void *io_uring_validate_mmap_request(struct file *file,
8735 loff_t pgoff, size_t sz)
2b188cc1 8736{
2b188cc1 8737 struct io_ring_ctx *ctx = file->private_data;
6c5c240e 8738 loff_t offset = pgoff << PAGE_SHIFT;
2b188cc1
JA
8739 struct page *page;
8740 void *ptr;
8741
8742 switch (offset) {
8743 case IORING_OFF_SQ_RING:
75b28aff
HV
8744 case IORING_OFF_CQ_RING:
8745 ptr = ctx->rings;
2b188cc1
JA
8746 break;
8747 case IORING_OFF_SQES:
8748 ptr = ctx->sq_sqes;
8749 break;
2b188cc1 8750 default:
6c5c240e 8751 return ERR_PTR(-EINVAL);
2b188cc1
JA
8752 }
8753
8754 page = virt_to_head_page(ptr);
a50b854e 8755 if (sz > page_size(page))
6c5c240e
RP
8756 return ERR_PTR(-EINVAL);
8757
8758 return ptr;
8759}
8760
8761#ifdef CONFIG_MMU
8762
8763static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
8764{
8765 size_t sz = vma->vm_end - vma->vm_start;
8766 unsigned long pfn;
8767 void *ptr;
8768
8769 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
8770 if (IS_ERR(ptr))
8771 return PTR_ERR(ptr);
2b188cc1
JA
8772
8773 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
8774 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
8775}
8776
6c5c240e
RP
8777#else /* !CONFIG_MMU */
8778
8779static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
8780{
8781 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
8782}
8783
8784static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
8785{
8786 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
8787}
8788
8789static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
8790 unsigned long addr, unsigned long len,
8791 unsigned long pgoff, unsigned long flags)
8792{
8793 void *ptr;
8794
8795 ptr = io_uring_validate_mmap_request(file, pgoff, len);
8796 if (IS_ERR(ptr))
8797 return PTR_ERR(ptr);
8798
8799 return (unsigned long) ptr;
8800}
8801
8802#endif /* !CONFIG_MMU */
8803
2b188cc1
JA
8804SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
8805 u32, min_complete, u32, flags, const sigset_t __user *, sig,
8806 size_t, sigsz)
8807{
8808 struct io_ring_ctx *ctx;
8809 long ret = -EBADF;
8810 int submitted = 0;
8811 struct fd f;
8812
4c6e277c 8813 io_run_task_work();
b41e9852 8814
6c271ce2 8815 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
2b188cc1
JA
8816 return -EINVAL;
8817
8818 f = fdget(fd);
8819 if (!f.file)
8820 return -EBADF;
8821
8822 ret = -EOPNOTSUPP;
8823 if (f.file->f_op != &io_uring_fops)
8824 goto out_fput;
8825
8826 ret = -ENXIO;
8827 ctx = f.file->private_data;
8828 if (!percpu_ref_tryget(&ctx->refs))
8829 goto out_fput;
8830
7e84e1c7
SG
8831 ret = -EBADFD;
8832 if (ctx->flags & IORING_SETUP_R_DISABLED)
8833 goto out;
8834
6c271ce2
JA
8835 /*
8836 * For SQ polling, the thread will do all submissions and completions.
8837 * Just return the requested submit count, and wake the thread if
8838 * we were asked to.
8839 */
b2a9eada 8840 ret = 0;
6c271ce2 8841 if (ctx->flags & IORING_SETUP_SQPOLL) {
c1edbf5f 8842 if (!list_empty_careful(&ctx->cq_overflow_list))
e6c8aa9a 8843 io_cqring_overflow_flush(ctx, false, NULL, NULL);
6c271ce2 8844 if (flags & IORING_ENTER_SQ_WAKEUP)
534ca6d6 8845 wake_up(&ctx->sq_data->wait);
6c271ce2 8846 submitted = to_submit;
b2a9eada 8847 } else if (to_submit) {
0f212204
JA
8848 ret = io_uring_add_task_file(f.file);
8849 if (unlikely(ret))
8850 goto out;
2b188cc1 8851 mutex_lock(&ctx->uring_lock);
0f212204 8852 submitted = io_submit_sqes(ctx, to_submit);
2b188cc1 8853 mutex_unlock(&ctx->uring_lock);
7c504e65
PB
8854
8855 if (submitted != to_submit)
8856 goto out;
2b188cc1
JA
8857 }
8858 if (flags & IORING_ENTER_GETEVENTS) {
8859 min_complete = min(min_complete, ctx->cq_entries);
8860
32b2244a
XW
8861 /*
8862 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
8863 * space applications don't need to do io completion events
8864 * polling again, they can rely on io_sq_thread to do polling
8865 * work, which can reduce cpu usage and uring_lock contention.
8866 */
8867 if (ctx->flags & IORING_SETUP_IOPOLL &&
8868 !(ctx->flags & IORING_SETUP_SQPOLL)) {
7668b92a 8869 ret = io_iopoll_check(ctx, min_complete);
def596e9
JA
8870 } else {
8871 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
8872 }
2b188cc1
JA
8873 }
8874
7c504e65 8875out:
6805b32e 8876 percpu_ref_put(&ctx->refs);
2b188cc1
JA
8877out_fput:
8878 fdput(f);
8879 return submitted ? submitted : ret;
8880}
8881
bebdb65e 8882#ifdef CONFIG_PROC_FS
87ce955b
JA
8883static int io_uring_show_cred(int id, void *p, void *data)
8884{
8885 const struct cred *cred = p;
8886 struct seq_file *m = data;
8887 struct user_namespace *uns = seq_user_ns(m);
8888 struct group_info *gi;
8889 kernel_cap_t cap;
8890 unsigned __capi;
8891 int g;
8892
8893 seq_printf(m, "%5d\n", id);
8894 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
8895 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
8896 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
8897 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
8898 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
8899 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
8900 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
8901 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
8902 seq_puts(m, "\n\tGroups:\t");
8903 gi = cred->group_info;
8904 for (g = 0; g < gi->ngroups; g++) {
8905 seq_put_decimal_ull(m, g ? " " : "",
8906 from_kgid_munged(uns, gi->gid[g]));
8907 }
8908 seq_puts(m, "\n\tCapEff:\t");
8909 cap = cred->cap_effective;
8910 CAP_FOR_EACH_U32(__capi)
8911 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
8912 seq_putc(m, '\n');
8913 return 0;
8914}
8915
8916static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
8917{
fad8e0de 8918 bool has_lock;
87ce955b
JA
8919 int i;
8920
fad8e0de
JA
8921 /*
8922 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
8923 * since fdinfo case grabs it in the opposite direction of normal use
8924 * cases. If we fail to get the lock, we just don't iterate any
8925 * structures that could be going away outside the io_uring mutex.
8926 */
8927 has_lock = mutex_trylock(&ctx->uring_lock);
8928
87ce955b 8929 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
fad8e0de 8930 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
87ce955b
JA
8931 struct fixed_file_table *table;
8932 struct file *f;
8933
8934 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
8935 f = table->files[i & IORING_FILE_TABLE_MASK];
8936 if (f)
8937 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
8938 else
8939 seq_printf(m, "%5u: <none>\n", i);
8940 }
8941 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
fad8e0de 8942 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
87ce955b
JA
8943 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
8944
8945 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
8946 (unsigned int) buf->len);
8947 }
fad8e0de 8948 if (has_lock && !idr_is_empty(&ctx->personality_idr)) {
87ce955b
JA
8949 seq_printf(m, "Personalities:\n");
8950 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
8951 }
d7718a9d
JA
8952 seq_printf(m, "PollList:\n");
8953 spin_lock_irq(&ctx->completion_lock);
8954 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
8955 struct hlist_head *list = &ctx->cancel_hash[i];
8956 struct io_kiocb *req;
8957
8958 hlist_for_each_entry(req, list, hash_node)
8959 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
8960 req->task->task_works != NULL);
8961 }
8962 spin_unlock_irq(&ctx->completion_lock);
fad8e0de
JA
8963 if (has_lock)
8964 mutex_unlock(&ctx->uring_lock);
87ce955b
JA
8965}
8966
8967static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
8968{
8969 struct io_ring_ctx *ctx = f->private_data;
8970
8971 if (percpu_ref_tryget(&ctx->refs)) {
8972 __io_uring_show_fdinfo(ctx, m);
8973 percpu_ref_put(&ctx->refs);
8974 }
8975}
bebdb65e 8976#endif
87ce955b 8977
2b188cc1
JA
8978static const struct file_operations io_uring_fops = {
8979 .release = io_uring_release,
fcb323cc 8980 .flush = io_uring_flush,
2b188cc1 8981 .mmap = io_uring_mmap,
6c5c240e
RP
8982#ifndef CONFIG_MMU
8983 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
8984 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
8985#endif
2b188cc1
JA
8986 .poll = io_uring_poll,
8987 .fasync = io_uring_fasync,
bebdb65e 8988#ifdef CONFIG_PROC_FS
87ce955b 8989 .show_fdinfo = io_uring_show_fdinfo,
bebdb65e 8990#endif
2b188cc1
JA
8991};
8992
8993static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
8994 struct io_uring_params *p)
8995{
75b28aff
HV
8996 struct io_rings *rings;
8997 size_t size, sq_array_offset;
2b188cc1 8998
bd740481
JA
8999 /* make sure these are sane, as we already accounted them */
9000 ctx->sq_entries = p->sq_entries;
9001 ctx->cq_entries = p->cq_entries;
9002
75b28aff
HV
9003 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9004 if (size == SIZE_MAX)
9005 return -EOVERFLOW;
9006
9007 rings = io_mem_alloc(size);
9008 if (!rings)
2b188cc1
JA
9009 return -ENOMEM;
9010
75b28aff
HV
9011 ctx->rings = rings;
9012 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9013 rings->sq_ring_mask = p->sq_entries - 1;
9014 rings->cq_ring_mask = p->cq_entries - 1;
9015 rings->sq_ring_entries = p->sq_entries;
9016 rings->cq_ring_entries = p->cq_entries;
9017 ctx->sq_mask = rings->sq_ring_mask;
9018 ctx->cq_mask = rings->cq_ring_mask;
2b188cc1
JA
9019
9020 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
eb065d30
JA
9021 if (size == SIZE_MAX) {
9022 io_mem_free(ctx->rings);
9023 ctx->rings = NULL;
2b188cc1 9024 return -EOVERFLOW;
eb065d30 9025 }
2b188cc1
JA
9026
9027 ctx->sq_sqes = io_mem_alloc(size);
eb065d30
JA
9028 if (!ctx->sq_sqes) {
9029 io_mem_free(ctx->rings);
9030 ctx->rings = NULL;
2b188cc1 9031 return -ENOMEM;
eb065d30 9032 }
2b188cc1 9033
2b188cc1
JA
9034 return 0;
9035}
9036
9037/*
9038 * Allocate an anonymous fd, this is what constitutes the application
9039 * visible backing of an io_uring instance. The application mmaps this
9040 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9041 * we have to tie this fd to a socket for file garbage collection purposes.
9042 */
9043static int io_uring_get_fd(struct io_ring_ctx *ctx)
9044{
9045 struct file *file;
9046 int ret;
9047
9048#if defined(CONFIG_UNIX)
9049 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9050 &ctx->ring_sock);
9051 if (ret)
9052 return ret;
9053#endif
9054
9055 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9056 if (ret < 0)
9057 goto err;
9058
9059 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9060 O_RDWR | O_CLOEXEC);
9061 if (IS_ERR(file)) {
0f212204 9062err_fd:
2b188cc1
JA
9063 put_unused_fd(ret);
9064 ret = PTR_ERR(file);
9065 goto err;
9066 }
9067
9068#if defined(CONFIG_UNIX)
9069 ctx->ring_sock->file = file;
9070#endif
0f212204
JA
9071 if (unlikely(io_uring_add_task_file(file))) {
9072 file = ERR_PTR(-ENOMEM);
9073 goto err_fd;
9074 }
2b188cc1
JA
9075 fd_install(ret, file);
9076 return ret;
9077err:
9078#if defined(CONFIG_UNIX)
9079 sock_release(ctx->ring_sock);
9080 ctx->ring_sock = NULL;
9081#endif
9082 return ret;
9083}
9084
7f13657d
XW
9085static int io_uring_create(unsigned entries, struct io_uring_params *p,
9086 struct io_uring_params __user *params)
2b188cc1
JA
9087{
9088 struct user_struct *user = NULL;
9089 struct io_ring_ctx *ctx;
aad5d8da 9090 bool limit_mem;
2b188cc1
JA
9091 int ret;
9092
8110c1a6 9093 if (!entries)
2b188cc1 9094 return -EINVAL;
8110c1a6
JA
9095 if (entries > IORING_MAX_ENTRIES) {
9096 if (!(p->flags & IORING_SETUP_CLAMP))
9097 return -EINVAL;
9098 entries = IORING_MAX_ENTRIES;
9099 }
2b188cc1
JA
9100
9101 /*
9102 * Use twice as many entries for the CQ ring. It's possible for the
9103 * application to drive a higher depth than the size of the SQ ring,
9104 * since the sqes are only used at submission time. This allows for
33a107f0
JA
9105 * some flexibility in overcommitting a bit. If the application has
9106 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9107 * of CQ ring entries manually.
2b188cc1
JA
9108 */
9109 p->sq_entries = roundup_pow_of_two(entries);
33a107f0
JA
9110 if (p->flags & IORING_SETUP_CQSIZE) {
9111 /*
9112 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9113 * to a power-of-two, if it isn't already. We do NOT impose
9114 * any cq vs sq ring sizing.
9115 */
8110c1a6 9116 if (p->cq_entries < p->sq_entries)
33a107f0 9117 return -EINVAL;
8110c1a6
JA
9118 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9119 if (!(p->flags & IORING_SETUP_CLAMP))
9120 return -EINVAL;
9121 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9122 }
33a107f0
JA
9123 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9124 } else {
9125 p->cq_entries = 2 * p->sq_entries;
9126 }
2b188cc1
JA
9127
9128 user = get_uid(current_user());
aad5d8da 9129 limit_mem = !capable(CAP_IPC_LOCK);
2b188cc1 9130
aad5d8da 9131 if (limit_mem) {
a087e2b5 9132 ret = __io_account_mem(user,
2b188cc1
JA
9133 ring_pages(p->sq_entries, p->cq_entries));
9134 if (ret) {
9135 free_uid(user);
9136 return ret;
9137 }
9138 }
9139
9140 ctx = io_ring_ctx_alloc(p);
9141 if (!ctx) {
aad5d8da 9142 if (limit_mem)
a087e2b5 9143 __io_unaccount_mem(user, ring_pages(p->sq_entries,
2b188cc1
JA
9144 p->cq_entries));
9145 free_uid(user);
9146 return -ENOMEM;
9147 }
9148 ctx->compat = in_compat_syscall();
2b188cc1 9149 ctx->user = user;
0b8c0ec7 9150 ctx->creds = get_current_cred();
2b188cc1 9151
2aede0e4
JA
9152 ctx->sqo_task = get_task_struct(current);
9153
9154 /*
9155 * This is just grabbed for accounting purposes. When a process exits,
9156 * the mm is exited and dropped before the files, hence we need to hang
9157 * on to this mm purely for the purposes of being able to unaccount
9158 * memory (locked/pinned vm). It's not used for anything else.
9159 */
6b7898eb 9160 mmgrab(current->mm);
2aede0e4 9161 ctx->mm_account = current->mm;
6b7898eb 9162
f74441e6
JA
9163 /*
9164 * Account memory _before_ installing the file descriptor. Once
9165 * the descriptor is installed, it can get closed at any time. Also
9166 * do this before hitting the general error path, as ring freeing
9167 * will un-account as well.
9168 */
9169 io_account_mem(ctx, ring_pages(p->sq_entries, p->cq_entries),
9170 ACCT_LOCKED);
9171 ctx->limit_mem = limit_mem;
9172
2b188cc1
JA
9173 ret = io_allocate_scq_urings(ctx, p);
9174 if (ret)
9175 goto err;
9176
7e84e1c7 9177 ret = io_sq_offload_create(ctx, p);
2b188cc1
JA
9178 if (ret)
9179 goto err;
9180
7e84e1c7
SG
9181 if (!(p->flags & IORING_SETUP_R_DISABLED))
9182 io_sq_offload_start(ctx);
9183
2b188cc1 9184 memset(&p->sq_off, 0, sizeof(p->sq_off));
75b28aff
HV
9185 p->sq_off.head = offsetof(struct io_rings, sq.head);
9186 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9187 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9188 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9189 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9190 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9191 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
2b188cc1
JA
9192
9193 memset(&p->cq_off, 0, sizeof(p->cq_off));
75b28aff
HV
9194 p->cq_off.head = offsetof(struct io_rings, cq.head);
9195 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9196 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9197 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9198 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9199 p->cq_off.cqes = offsetof(struct io_rings, cqes);
0d9b5b3a 9200 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
ac90f249 9201
7f13657d
XW
9202 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9203 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
5769a351
JX
9204 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9205 IORING_FEAT_POLL_32BITS;
7f13657d
XW
9206
9207 if (copy_to_user(params, p, sizeof(*p))) {
9208 ret = -EFAULT;
9209 goto err;
9210 }
d1719f70 9211
044c1ab3
JA
9212 /*
9213 * Install ring fd as the very last thing, so we don't risk someone
9214 * having closed it before we finish setup
9215 */
9216 ret = io_uring_get_fd(ctx);
9217 if (ret < 0)
9218 goto err;
9219
c826bd7a 9220 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
2b188cc1
JA
9221 return ret;
9222err:
9223 io_ring_ctx_wait_and_kill(ctx);
9224 return ret;
9225}
9226
9227/*
9228 * Sets up an aio uring context, and returns the fd. Applications asks for a
9229 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9230 * params structure passed in.
9231 */
9232static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9233{
9234 struct io_uring_params p;
2b188cc1
JA
9235 int i;
9236
9237 if (copy_from_user(&p, params, sizeof(p)))
9238 return -EFAULT;
9239 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9240 if (p.resv[i])
9241 return -EINVAL;
9242 }
9243
6c271ce2 9244 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
8110c1a6 9245 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
7e84e1c7
SG
9246 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9247 IORING_SETUP_R_DISABLED))
2b188cc1
JA
9248 return -EINVAL;
9249
7f13657d 9250 return io_uring_create(entries, &p, params);
2b188cc1
JA
9251}
9252
9253SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9254 struct io_uring_params __user *, params)
9255{
9256 return io_uring_setup(entries, params);
9257}
9258
66f4af93
JA
9259static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9260{
9261 struct io_uring_probe *p;
9262 size_t size;
9263 int i, ret;
9264
9265 size = struct_size(p, ops, nr_args);
9266 if (size == SIZE_MAX)
9267 return -EOVERFLOW;
9268 p = kzalloc(size, GFP_KERNEL);
9269 if (!p)
9270 return -ENOMEM;
9271
9272 ret = -EFAULT;
9273 if (copy_from_user(p, arg, size))
9274 goto out;
9275 ret = -EINVAL;
9276 if (memchr_inv(p, 0, size))
9277 goto out;
9278
9279 p->last_op = IORING_OP_LAST - 1;
9280 if (nr_args > IORING_OP_LAST)
9281 nr_args = IORING_OP_LAST;
9282
9283 for (i = 0; i < nr_args; i++) {
9284 p->ops[i].op = i;
9285 if (!io_op_defs[i].not_supported)
9286 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9287 }
9288 p->ops_len = i;
9289
9290 ret = 0;
9291 if (copy_to_user(arg, p, size))
9292 ret = -EFAULT;
9293out:
9294 kfree(p);
9295 return ret;
9296}
9297
071698e1
JA
9298static int io_register_personality(struct io_ring_ctx *ctx)
9299{
9300 const struct cred *creds = get_current_cred();
9301 int id;
9302
9303 id = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
9304 USHRT_MAX, GFP_KERNEL);
9305 if (id < 0)
9306 put_cred(creds);
9307 return id;
9308}
9309
9310static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9311{
9312 const struct cred *old_creds;
9313
9314 old_creds = idr_remove(&ctx->personality_idr, id);
9315 if (old_creds) {
9316 put_cred(old_creds);
9317 return 0;
9318 }
9319
9320 return -EINVAL;
9321}
9322
21b55dbc
SG
9323static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9324 unsigned int nr_args)
9325{
9326 struct io_uring_restriction *res;
9327 size_t size;
9328 int i, ret;
9329
7e84e1c7
SG
9330 /* Restrictions allowed only if rings started disabled */
9331 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9332 return -EBADFD;
9333
21b55dbc 9334 /* We allow only a single restrictions registration */
7e84e1c7 9335 if (ctx->restrictions.registered)
21b55dbc
SG
9336 return -EBUSY;
9337
9338 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9339 return -EINVAL;
9340
9341 size = array_size(nr_args, sizeof(*res));
9342 if (size == SIZE_MAX)
9343 return -EOVERFLOW;
9344
9345 res = memdup_user(arg, size);
9346 if (IS_ERR(res))
9347 return PTR_ERR(res);
9348
9349 ret = 0;
9350
9351 for (i = 0; i < nr_args; i++) {
9352 switch (res[i].opcode) {
9353 case IORING_RESTRICTION_REGISTER_OP:
9354 if (res[i].register_op >= IORING_REGISTER_LAST) {
9355 ret = -EINVAL;
9356 goto out;
9357 }
9358
9359 __set_bit(res[i].register_op,
9360 ctx->restrictions.register_op);
9361 break;
9362 case IORING_RESTRICTION_SQE_OP:
9363 if (res[i].sqe_op >= IORING_OP_LAST) {
9364 ret = -EINVAL;
9365 goto out;
9366 }
9367
9368 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9369 break;
9370 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9371 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9372 break;
9373 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9374 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9375 break;
9376 default:
9377 ret = -EINVAL;
9378 goto out;
9379 }
9380 }
9381
9382out:
9383 /* Reset all restrictions if an error happened */
9384 if (ret != 0)
9385 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9386 else
7e84e1c7 9387 ctx->restrictions.registered = true;
21b55dbc
SG
9388
9389 kfree(res);
9390 return ret;
9391}
9392
7e84e1c7
SG
9393static int io_register_enable_rings(struct io_ring_ctx *ctx)
9394{
9395 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9396 return -EBADFD;
9397
9398 if (ctx->restrictions.registered)
9399 ctx->restricted = 1;
9400
9401 ctx->flags &= ~IORING_SETUP_R_DISABLED;
9402
9403 io_sq_offload_start(ctx);
9404
9405 return 0;
9406}
9407
071698e1
JA
9408static bool io_register_op_must_quiesce(int op)
9409{
9410 switch (op) {
9411 case IORING_UNREGISTER_FILES:
9412 case IORING_REGISTER_FILES_UPDATE:
9413 case IORING_REGISTER_PROBE:
9414 case IORING_REGISTER_PERSONALITY:
9415 case IORING_UNREGISTER_PERSONALITY:
9416 return false;
9417 default:
9418 return true;
9419 }
9420}
9421
edafccee
JA
9422static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
9423 void __user *arg, unsigned nr_args)
b19062a5
JA
9424 __releases(ctx->uring_lock)
9425 __acquires(ctx->uring_lock)
edafccee
JA
9426{
9427 int ret;
9428
35fa71a0
JA
9429 /*
9430 * We're inside the ring mutex, if the ref is already dying, then
9431 * someone else killed the ctx or is already going through
9432 * io_uring_register().
9433 */
9434 if (percpu_ref_is_dying(&ctx->refs))
9435 return -ENXIO;
9436
071698e1 9437 if (io_register_op_must_quiesce(opcode)) {
05f3fb3c 9438 percpu_ref_kill(&ctx->refs);
b19062a5 9439
05f3fb3c
JA
9440 /*
9441 * Drop uring mutex before waiting for references to exit. If
9442 * another thread is currently inside io_uring_enter() it might
9443 * need to grab the uring_lock to make progress. If we hold it
9444 * here across the drain wait, then we can deadlock. It's safe
9445 * to drop the mutex here, since no new references will come in
9446 * after we've killed the percpu ref.
9447 */
9448 mutex_unlock(&ctx->uring_lock);
0f158b4c 9449 ret = wait_for_completion_interruptible(&ctx->ref_comp);
05f3fb3c 9450 mutex_lock(&ctx->uring_lock);
c150368b
JA
9451 if (ret) {
9452 percpu_ref_resurrect(&ctx->refs);
9453 ret = -EINTR;
21b55dbc
SG
9454 goto out_quiesce;
9455 }
9456 }
9457
9458 if (ctx->restricted) {
9459 if (opcode >= IORING_REGISTER_LAST) {
9460 ret = -EINVAL;
9461 goto out;
9462 }
9463
9464 if (!test_bit(opcode, ctx->restrictions.register_op)) {
9465 ret = -EACCES;
c150368b
JA
9466 goto out;
9467 }
05f3fb3c 9468 }
edafccee
JA
9469
9470 switch (opcode) {
9471 case IORING_REGISTER_BUFFERS:
9472 ret = io_sqe_buffer_register(ctx, arg, nr_args);
9473 break;
9474 case IORING_UNREGISTER_BUFFERS:
9475 ret = -EINVAL;
9476 if (arg || nr_args)
9477 break;
9478 ret = io_sqe_buffer_unregister(ctx);
9479 break;
6b06314c
JA
9480 case IORING_REGISTER_FILES:
9481 ret = io_sqe_files_register(ctx, arg, nr_args);
9482 break;
9483 case IORING_UNREGISTER_FILES:
9484 ret = -EINVAL;
9485 if (arg || nr_args)
9486 break;
9487 ret = io_sqe_files_unregister(ctx);
9488 break;
c3a31e60
JA
9489 case IORING_REGISTER_FILES_UPDATE:
9490 ret = io_sqe_files_update(ctx, arg, nr_args);
9491 break;
9b402849 9492 case IORING_REGISTER_EVENTFD:
f2842ab5 9493 case IORING_REGISTER_EVENTFD_ASYNC:
9b402849
JA
9494 ret = -EINVAL;
9495 if (nr_args != 1)
9496 break;
9497 ret = io_eventfd_register(ctx, arg);
f2842ab5
JA
9498 if (ret)
9499 break;
9500 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
9501 ctx->eventfd_async = 1;
9502 else
9503 ctx->eventfd_async = 0;
9b402849
JA
9504 break;
9505 case IORING_UNREGISTER_EVENTFD:
9506 ret = -EINVAL;
9507 if (arg || nr_args)
9508 break;
9509 ret = io_eventfd_unregister(ctx);
9510 break;
66f4af93
JA
9511 case IORING_REGISTER_PROBE:
9512 ret = -EINVAL;
9513 if (!arg || nr_args > 256)
9514 break;
9515 ret = io_probe(ctx, arg, nr_args);
9516 break;
071698e1
JA
9517 case IORING_REGISTER_PERSONALITY:
9518 ret = -EINVAL;
9519 if (arg || nr_args)
9520 break;
9521 ret = io_register_personality(ctx);
9522 break;
9523 case IORING_UNREGISTER_PERSONALITY:
9524 ret = -EINVAL;
9525 if (arg)
9526 break;
9527 ret = io_unregister_personality(ctx, nr_args);
9528 break;
7e84e1c7
SG
9529 case IORING_REGISTER_ENABLE_RINGS:
9530 ret = -EINVAL;
9531 if (arg || nr_args)
9532 break;
9533 ret = io_register_enable_rings(ctx);
9534 break;
21b55dbc
SG
9535 case IORING_REGISTER_RESTRICTIONS:
9536 ret = io_register_restrictions(ctx, arg, nr_args);
9537 break;
edafccee
JA
9538 default:
9539 ret = -EINVAL;
9540 break;
9541 }
9542
21b55dbc 9543out:
071698e1 9544 if (io_register_op_must_quiesce(opcode)) {
05f3fb3c 9545 /* bring the ctx back to life */
05f3fb3c 9546 percpu_ref_reinit(&ctx->refs);
21b55dbc 9547out_quiesce:
0f158b4c 9548 reinit_completion(&ctx->ref_comp);
05f3fb3c 9549 }
edafccee
JA
9550 return ret;
9551}
9552
9553SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
9554 void __user *, arg, unsigned int, nr_args)
9555{
9556 struct io_ring_ctx *ctx;
9557 long ret = -EBADF;
9558 struct fd f;
9559
9560 f = fdget(fd);
9561 if (!f.file)
9562 return -EBADF;
9563
9564 ret = -EOPNOTSUPP;
9565 if (f.file->f_op != &io_uring_fops)
9566 goto out_fput;
9567
9568 ctx = f.file->private_data;
9569
9570 mutex_lock(&ctx->uring_lock);
9571 ret = __io_uring_register(ctx, opcode, arg, nr_args);
9572 mutex_unlock(&ctx->uring_lock);
c826bd7a
DD
9573 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
9574 ctx->cq_ev_fd != NULL, ret);
edafccee
JA
9575out_fput:
9576 fdput(f);
9577 return ret;
9578}
9579
2b188cc1
JA
9580static int __init io_uring_init(void)
9581{
d7f62e82
SM
9582#define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
9583 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
9584 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
9585} while (0)
9586
9587#define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
9588 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
9589 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
9590 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
9591 BUILD_BUG_SQE_ELEM(1, __u8, flags);
9592 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
9593 BUILD_BUG_SQE_ELEM(4, __s32, fd);
9594 BUILD_BUG_SQE_ELEM(8, __u64, off);
9595 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
9596 BUILD_BUG_SQE_ELEM(16, __u64, addr);
7d67af2c 9597 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
d7f62e82
SM
9598 BUILD_BUG_SQE_ELEM(24, __u32, len);
9599 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
9600 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
9601 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
9602 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
5769a351
JX
9603 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
9604 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
d7f62e82
SM
9605 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
9606 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
9607 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
9608 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
9609 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
9610 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
9611 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
9612 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
7d67af2c 9613 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
d7f62e82
SM
9614 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
9615 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
9616 BUILD_BUG_SQE_ELEM(42, __u16, personality);
7d67af2c 9617 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
d7f62e82 9618
d3656344 9619 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
84557871 9620 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
2b188cc1
JA
9621 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
9622 return 0;
9623};
9624__initcall(io_uring_init);