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