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