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