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