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