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