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