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