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