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