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