]> git.ipfire.org Git - thirdparty/linux.git/blame - fs/io_uring.c
io_uring: use poll driven retry for files that support it
[thirdparty/linux.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>
47#include <linux/refcount.h>
48#include <linux/uio.h>
6b47ee6e 49#include <linux/bits.h>
2b188cc1
JA
50
51#include <linux/sched/signal.h>
52#include <linux/fs.h>
53#include <linux/file.h>
54#include <linux/fdtable.h>
55#include <linux/mm.h>
56#include <linux/mman.h>
57#include <linux/mmu_context.h>
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>
2b188cc1 81
c826bd7a
DD
82#define CREATE_TRACE_POINTS
83#include <trace/events/io_uring.h>
84
2b188cc1
JA
85#include <uapi/linux/io_uring.h>
86
87#include "internal.h"
561fb04a 88#include "io-wq.h"
2b188cc1 89
5277deaa 90#define IORING_MAX_ENTRIES 32768
33a107f0 91#define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
65e19f54
JA
92
93/*
94 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
95 */
96#define IORING_FILE_TABLE_SHIFT 9
97#define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
98#define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
99#define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
2b188cc1
JA
100
101struct io_uring {
102 u32 head ____cacheline_aligned_in_smp;
103 u32 tail ____cacheline_aligned_in_smp;
104};
105
1e84b97b 106/*
75b28aff
HV
107 * This data is shared with the application through the mmap at offsets
108 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
1e84b97b
SB
109 *
110 * The offsets to the member fields are published through struct
111 * io_sqring_offsets when calling io_uring_setup.
112 */
75b28aff 113struct io_rings {
1e84b97b
SB
114 /*
115 * Head and tail offsets into the ring; the offsets need to be
116 * masked to get valid indices.
117 *
75b28aff
HV
118 * The kernel controls head of the sq ring and the tail of the cq ring,
119 * and the application controls tail of the sq ring and the head of the
120 * cq ring.
1e84b97b 121 */
75b28aff 122 struct io_uring sq, cq;
1e84b97b 123 /*
75b28aff 124 * Bitmasks to apply to head and tail offsets (constant, equals
1e84b97b
SB
125 * ring_entries - 1)
126 */
75b28aff
HV
127 u32 sq_ring_mask, cq_ring_mask;
128 /* Ring sizes (constant, power of 2) */
129 u32 sq_ring_entries, cq_ring_entries;
1e84b97b
SB
130 /*
131 * Number of invalid entries dropped by the kernel due to
132 * invalid index stored in array
133 *
134 * Written by the kernel, shouldn't be modified by the
135 * application (i.e. get number of "new events" by comparing to
136 * cached value).
137 *
138 * After a new SQ head value was read by the application this
139 * counter includes all submissions that were dropped reaching
140 * the new SQ head (and possibly more).
141 */
75b28aff 142 u32 sq_dropped;
1e84b97b
SB
143 /*
144 * Runtime flags
145 *
146 * Written by the kernel, shouldn't be modified by the
147 * application.
148 *
149 * The application needs a full memory barrier before checking
150 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
151 */
75b28aff 152 u32 sq_flags;
1e84b97b
SB
153 /*
154 * Number of completion events lost because the queue was full;
155 * this should be avoided by the application by making sure
0b4295b5 156 * there are not more requests pending than there is space in
1e84b97b
SB
157 * the completion queue.
158 *
159 * Written by the kernel, shouldn't be modified by the
160 * application (i.e. get number of "new events" by comparing to
161 * cached value).
162 *
163 * As completion events come in out of order this counter is not
164 * ordered with any other data.
165 */
75b28aff 166 u32 cq_overflow;
1e84b97b
SB
167 /*
168 * Ring buffer of completion events.
169 *
170 * The kernel writes completion events fresh every time they are
171 * produced, so the application is allowed to modify pending
172 * entries.
173 */
75b28aff 174 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
2b188cc1
JA
175};
176
edafccee
JA
177struct io_mapped_ubuf {
178 u64 ubuf;
179 size_t len;
180 struct bio_vec *bvec;
181 unsigned int nr_bvecs;
182};
183
65e19f54
JA
184struct fixed_file_table {
185 struct file **files;
31b51510
JA
186};
187
05f3fb3c
JA
188struct fixed_file_data {
189 struct fixed_file_table *table;
190 struct io_ring_ctx *ctx;
191
192 struct percpu_ref refs;
193 struct llist_head put_llist;
05f3fb3c
JA
194 struct work_struct ref_work;
195 struct completion done;
196};
197
2b188cc1
JA
198struct io_ring_ctx {
199 struct {
200 struct percpu_ref refs;
201 } ____cacheline_aligned_in_smp;
202
203 struct {
204 unsigned int flags;
e1d85334
RD
205 unsigned int compat: 1;
206 unsigned int account_mem: 1;
207 unsigned int cq_overflow_flushed: 1;
208 unsigned int drain_next: 1;
209 unsigned int eventfd_async: 1;
2b188cc1 210
75b28aff
HV
211 /*
212 * Ring buffer of indices into array of io_uring_sqe, which is
213 * mmapped by the application using the IORING_OFF_SQES offset.
214 *
215 * This indirection could e.g. be used to assign fixed
216 * io_uring_sqe entries to operations and only submit them to
217 * the queue when needed.
218 *
219 * The kernel modifies neither the indices array nor the entries
220 * array.
221 */
222 u32 *sq_array;
2b188cc1
JA
223 unsigned cached_sq_head;
224 unsigned sq_entries;
225 unsigned sq_mask;
6c271ce2 226 unsigned sq_thread_idle;
498ccd9e 227 unsigned cached_sq_dropped;
206aefde 228 atomic_t cached_cq_overflow;
ad3eb2c8 229 unsigned long sq_check_overflow;
de0617e4
JA
230
231 struct list_head defer_list;
5262f567 232 struct list_head timeout_list;
1d7bb1d5 233 struct list_head cq_overflow_list;
fcb323cc
JA
234
235 wait_queue_head_t inflight_wait;
ad3eb2c8 236 struct io_uring_sqe *sq_sqes;
2b188cc1
JA
237 } ____cacheline_aligned_in_smp;
238
206aefde
JA
239 struct io_rings *rings;
240
2b188cc1 241 /* IO offload */
561fb04a 242 struct io_wq *io_wq;
6c271ce2 243 struct task_struct *sqo_thread; /* if using sq thread polling */
2b188cc1 244 struct mm_struct *sqo_mm;
6c271ce2 245 wait_queue_head_t sqo_wait;
75b28aff 246
6b06314c
JA
247 /*
248 * If used, fixed file set. Writers must ensure that ->refs is dead,
249 * readers must ensure that ->refs is alive as long as the file* is
250 * used. Only updated through io_uring_register(2).
251 */
05f3fb3c 252 struct fixed_file_data *file_data;
6b06314c 253 unsigned nr_user_files;
b14cca0c
PB
254 int ring_fd;
255 struct file *ring_file;
6b06314c 256
edafccee
JA
257 /* if used, fixed mapped user buffers */
258 unsigned nr_user_bufs;
259 struct io_mapped_ubuf *user_bufs;
260
2b188cc1
JA
261 struct user_struct *user;
262
0b8c0ec7 263 const struct cred *creds;
181e448d 264
206aefde
JA
265 /* 0 is for ctx quiesce/reinit/free, 1 is for sqo_thread started */
266 struct completion *completions;
267
0ddf92e8
JA
268 /* if all else fails... */
269 struct io_kiocb *fallback_req;
270
206aefde
JA
271#if defined(CONFIG_UNIX)
272 struct socket *ring_sock;
273#endif
274
071698e1
JA
275 struct idr personality_idr;
276
206aefde
JA
277 struct {
278 unsigned cached_cq_tail;
279 unsigned cq_entries;
280 unsigned cq_mask;
281 atomic_t cq_timeouts;
ad3eb2c8 282 unsigned long cq_check_overflow;
206aefde
JA
283 struct wait_queue_head cq_wait;
284 struct fasync_struct *cq_fasync;
285 struct eventfd_ctx *cq_ev_fd;
286 } ____cacheline_aligned_in_smp;
2b188cc1
JA
287
288 struct {
289 struct mutex uring_lock;
290 wait_queue_head_t wait;
291 } ____cacheline_aligned_in_smp;
292
293 struct {
294 spinlock_t completion_lock;
e94f141b 295
def596e9
JA
296 /*
297 * ->poll_list is protected by the ctx->uring_lock for
298 * io_uring instances that don't use IORING_SETUP_SQPOLL.
299 * For SQPOLL, only the single threaded io_sq_thread() will
300 * manipulate the list, hence no extra locking is needed there.
301 */
302 struct list_head poll_list;
78076bb6
JA
303 struct hlist_head *cancel_hash;
304 unsigned cancel_hash_bits;
e94f141b 305 bool poll_multi_file;
31b51510 306
fcb323cc
JA
307 spinlock_t inflight_lock;
308 struct list_head inflight_list;
2b188cc1 309 } ____cacheline_aligned_in_smp;
2b188cc1
JA
310};
311
09bb8394
JA
312/*
313 * First field must be the file pointer in all the
314 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
315 */
221c5eb2
JA
316struct io_poll_iocb {
317 struct file *file;
0969e783
JA
318 union {
319 struct wait_queue_head *head;
320 u64 addr;
321 };
221c5eb2 322 __poll_t events;
8c838788 323 bool done;
221c5eb2 324 bool canceled;
392edb45 325 struct wait_queue_entry wait;
221c5eb2
JA
326};
327
b5dba59e
JA
328struct io_close {
329 struct file *file;
330 struct file *put_file;
331 int fd;
332};
333
ad8a48ac
JA
334struct io_timeout_data {
335 struct io_kiocb *req;
336 struct hrtimer timer;
337 struct timespec64 ts;
338 enum hrtimer_mode mode;
cc42e0ac 339 u32 seq_offset;
ad8a48ac
JA
340};
341
8ed8d3c3
JA
342struct io_accept {
343 struct file *file;
344 struct sockaddr __user *addr;
345 int __user *addr_len;
346 int flags;
347};
348
349struct io_sync {
350 struct file *file;
351 loff_t len;
352 loff_t off;
353 int flags;
d63d1b5e 354 int mode;
8ed8d3c3
JA
355};
356
fbf23849
JA
357struct io_cancel {
358 struct file *file;
359 u64 addr;
360};
361
b29472ee
JA
362struct io_timeout {
363 struct file *file;
364 u64 addr;
365 int flags;
26a61679 366 unsigned count;
b29472ee
JA
367};
368
9adbd45d
JA
369struct io_rw {
370 /* NOTE: kiocb has the file as the first member, so don't do it here */
371 struct kiocb kiocb;
372 u64 addr;
373 u64 len;
374};
375
3fbb51c1
JA
376struct io_connect {
377 struct file *file;
378 struct sockaddr __user *addr;
379 int addr_len;
380};
381
e47293fd
JA
382struct io_sr_msg {
383 struct file *file;
fddaface
JA
384 union {
385 struct user_msghdr __user *msg;
386 void __user *buf;
387 };
e47293fd 388 int msg_flags;
fddaface 389 size_t len;
e47293fd
JA
390};
391
15b71abe
JA
392struct io_open {
393 struct file *file;
394 int dfd;
eddc7ef5 395 union {
eddc7ef5
JA
396 unsigned mask;
397 };
15b71abe 398 struct filename *filename;
eddc7ef5 399 struct statx __user *buffer;
c12cedf2 400 struct open_how how;
15b71abe
JA
401};
402
05f3fb3c
JA
403struct io_files_update {
404 struct file *file;
405 u64 arg;
406 u32 nr_args;
407 u32 offset;
408};
409
4840e418
JA
410struct io_fadvise {
411 struct file *file;
412 u64 offset;
413 u32 len;
414 u32 advice;
415};
416
c1ca757b
JA
417struct io_madvise {
418 struct file *file;
419 u64 addr;
420 u32 len;
421 u32 advice;
422};
423
3e4827b0
JA
424struct io_epoll {
425 struct file *file;
426 int epfd;
427 int op;
428 int fd;
429 struct epoll_event event;
e47293fd
JA
430};
431
7d67af2c
PB
432struct io_splice {
433 struct file *file_out;
434 struct file *file_in;
435 loff_t off_out;
436 loff_t off_in;
437 u64 len;
438 unsigned int flags;
439};
440
f499a021
JA
441struct io_async_connect {
442 struct sockaddr_storage address;
443};
444
03b1230c
JA
445struct io_async_msghdr {
446 struct iovec fast_iov[UIO_FASTIOV];
447 struct iovec *iov;
448 struct sockaddr __user *uaddr;
449 struct msghdr msg;
b537916c 450 struct sockaddr_storage addr;
03b1230c
JA
451};
452
f67676d1
JA
453struct io_async_rw {
454 struct iovec fast_iov[UIO_FASTIOV];
455 struct iovec *iov;
456 ssize_t nr_segs;
457 ssize_t size;
458};
459
1a6b74fc 460struct io_async_ctx {
f67676d1
JA
461 union {
462 struct io_async_rw rw;
03b1230c 463 struct io_async_msghdr msg;
f499a021 464 struct io_async_connect connect;
2d28390a 465 struct io_timeout_data timeout;
f67676d1 466 };
1a6b74fc
JA
467};
468
6b47ee6e
PB
469enum {
470 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
471 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
472 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
473 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
474 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
475
476 REQ_F_LINK_NEXT_BIT,
477 REQ_F_FAIL_LINK_BIT,
478 REQ_F_INFLIGHT_BIT,
479 REQ_F_CUR_POS_BIT,
480 REQ_F_NOWAIT_BIT,
481 REQ_F_IOPOLL_COMPLETED_BIT,
482 REQ_F_LINK_TIMEOUT_BIT,
483 REQ_F_TIMEOUT_BIT,
484 REQ_F_ISREG_BIT,
485 REQ_F_MUST_PUNT_BIT,
486 REQ_F_TIMEOUT_NOSEQ_BIT,
487 REQ_F_COMP_LOCKED_BIT,
99bc4c38 488 REQ_F_NEED_CLEANUP_BIT,
2ca10259 489 REQ_F_OVERFLOW_BIT,
d7718a9d 490 REQ_F_POLLED_BIT,
6b47ee6e
PB
491};
492
493enum {
494 /* ctx owns file */
495 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
496 /* drain existing IO first */
497 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
498 /* linked sqes */
499 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
500 /* doesn't sever on completion < 0 */
501 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
502 /* IOSQE_ASYNC */
503 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
504
505 /* already grabbed next link */
506 REQ_F_LINK_NEXT = BIT(REQ_F_LINK_NEXT_BIT),
507 /* fail rest of links */
508 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
509 /* on inflight list */
510 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
511 /* read/write uses file position */
512 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
513 /* must not punt to workers */
514 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
515 /* polled IO has completed */
516 REQ_F_IOPOLL_COMPLETED = BIT(REQ_F_IOPOLL_COMPLETED_BIT),
517 /* has linked timeout */
518 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
519 /* timeout request */
520 REQ_F_TIMEOUT = BIT(REQ_F_TIMEOUT_BIT),
521 /* regular file */
522 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
523 /* must be punted even for NONBLOCK */
524 REQ_F_MUST_PUNT = BIT(REQ_F_MUST_PUNT_BIT),
525 /* no timeout sequence */
526 REQ_F_TIMEOUT_NOSEQ = BIT(REQ_F_TIMEOUT_NOSEQ_BIT),
527 /* completion under lock */
528 REQ_F_COMP_LOCKED = BIT(REQ_F_COMP_LOCKED_BIT),
99bc4c38
PB
529 /* needs cleanup */
530 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
2ca10259
JA
531 /* in overflow list */
532 REQ_F_OVERFLOW = BIT(REQ_F_OVERFLOW_BIT),
d7718a9d
JA
533 /* already went through poll handler */
534 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
535};
536
537struct async_poll {
538 struct io_poll_iocb poll;
539 struct io_wq_work work;
6b47ee6e
PB
540};
541
09bb8394
JA
542/*
543 * NOTE! Each of the iocb union members has the file pointer
544 * as the first entry in their struct definition. So you can
545 * access the file pointer through any of the sub-structs,
546 * or directly as just 'ki_filp' in this struct.
547 */
2b188cc1 548struct io_kiocb {
221c5eb2 549 union {
09bb8394 550 struct file *file;
9adbd45d 551 struct io_rw rw;
221c5eb2 552 struct io_poll_iocb poll;
8ed8d3c3
JA
553 struct io_accept accept;
554 struct io_sync sync;
fbf23849 555 struct io_cancel cancel;
b29472ee 556 struct io_timeout timeout;
3fbb51c1 557 struct io_connect connect;
e47293fd 558 struct io_sr_msg sr_msg;
15b71abe 559 struct io_open open;
b5dba59e 560 struct io_close close;
05f3fb3c 561 struct io_files_update files_update;
4840e418 562 struct io_fadvise fadvise;
c1ca757b 563 struct io_madvise madvise;
3e4827b0 564 struct io_epoll epoll;
7d67af2c 565 struct io_splice splice;
221c5eb2 566 };
2b188cc1 567
1a6b74fc 568 struct io_async_ctx *io;
cf6fd4bd 569 bool needs_fixed_file;
d625c6ee 570 u8 opcode;
2b188cc1
JA
571
572 struct io_ring_ctx *ctx;
d7718a9d 573 struct list_head list;
2b188cc1 574 unsigned int flags;
c16361c1 575 refcount_t refs;
d7718a9d 576 struct task_struct *task;
2b188cc1 577 u64 user_data;
9e645e11 578 u32 result;
de0617e4 579 u32 sequence;
2b188cc1 580
d7718a9d
JA
581 struct list_head link_list;
582
fcb323cc
JA
583 struct list_head inflight_entry;
584
b41e9852
JA
585 union {
586 /*
587 * Only commands that never go async can use the below fields,
d7718a9d
JA
588 * obviously. Right now only IORING_OP_POLL_ADD uses them, and
589 * async armed poll handlers for regular commands. The latter
590 * restore the work, if needed.
b41e9852
JA
591 */
592 struct {
b41e9852 593 struct callback_head task_work;
d7718a9d
JA
594 struct hlist_node hash_node;
595 struct async_poll *apoll;
b41e9852
JA
596 };
597 struct io_wq_work work;
598 };
2b188cc1
JA
599};
600
601#define IO_PLUG_THRESHOLD 2
def596e9 602#define IO_IOPOLL_BATCH 8
2b188cc1 603
9a56a232
JA
604struct io_submit_state {
605 struct blk_plug plug;
606
2579f913
JA
607 /*
608 * io_kiocb alloc cache
609 */
610 void *reqs[IO_IOPOLL_BATCH];
6c8a3134 611 unsigned int free_reqs;
2579f913 612
9a56a232
JA
613 /*
614 * File reference cache
615 */
616 struct file *file;
617 unsigned int fd;
618 unsigned int has_refs;
619 unsigned int used_refs;
620 unsigned int ios_left;
621};
622
d3656344
JA
623struct io_op_def {
624 /* needs req->io allocated for deferral/async */
625 unsigned async_ctx : 1;
626 /* needs current->mm setup, does mm access */
627 unsigned needs_mm : 1;
628 /* needs req->file assigned */
629 unsigned needs_file : 1;
630 /* needs req->file assigned IFF fd is >= 0 */
631 unsigned fd_non_neg : 1;
632 /* hash wq insertion if file is a regular file */
633 unsigned hash_reg_file : 1;
634 /* unbound wq insertion if file is a non-regular file */
635 unsigned unbound_nonreg_file : 1;
66f4af93
JA
636 /* opcode is not supported by this kernel */
637 unsigned not_supported : 1;
f86cd20c
JA
638 /* needs file table */
639 unsigned file_table : 1;
ff002b30
JA
640 /* needs ->fs */
641 unsigned needs_fs : 1;
8a72758c
JA
642 /* set if opcode supports polled "wait" */
643 unsigned pollin : 1;
644 unsigned pollout : 1;
d3656344
JA
645};
646
647static const struct io_op_def io_op_defs[] = {
0463b6c5
PB
648 [IORING_OP_NOP] = {},
649 [IORING_OP_READV] = {
d3656344
JA
650 .async_ctx = 1,
651 .needs_mm = 1,
652 .needs_file = 1,
653 .unbound_nonreg_file = 1,
8a72758c 654 .pollin = 1,
d3656344 655 },
0463b6c5 656 [IORING_OP_WRITEV] = {
d3656344
JA
657 .async_ctx = 1,
658 .needs_mm = 1,
659 .needs_file = 1,
660 .hash_reg_file = 1,
661 .unbound_nonreg_file = 1,
8a72758c 662 .pollout = 1,
d3656344 663 },
0463b6c5 664 [IORING_OP_FSYNC] = {
d3656344
JA
665 .needs_file = 1,
666 },
0463b6c5 667 [IORING_OP_READ_FIXED] = {
d3656344
JA
668 .needs_file = 1,
669 .unbound_nonreg_file = 1,
8a72758c 670 .pollin = 1,
d3656344 671 },
0463b6c5 672 [IORING_OP_WRITE_FIXED] = {
d3656344
JA
673 .needs_file = 1,
674 .hash_reg_file = 1,
675 .unbound_nonreg_file = 1,
8a72758c 676 .pollout = 1,
d3656344 677 },
0463b6c5 678 [IORING_OP_POLL_ADD] = {
d3656344
JA
679 .needs_file = 1,
680 .unbound_nonreg_file = 1,
681 },
0463b6c5
PB
682 [IORING_OP_POLL_REMOVE] = {},
683 [IORING_OP_SYNC_FILE_RANGE] = {
d3656344
JA
684 .needs_file = 1,
685 },
0463b6c5 686 [IORING_OP_SENDMSG] = {
d3656344
JA
687 .async_ctx = 1,
688 .needs_mm = 1,
689 .needs_file = 1,
690 .unbound_nonreg_file = 1,
ff002b30 691 .needs_fs = 1,
8a72758c 692 .pollout = 1,
d3656344 693 },
0463b6c5 694 [IORING_OP_RECVMSG] = {
d3656344
JA
695 .async_ctx = 1,
696 .needs_mm = 1,
697 .needs_file = 1,
698 .unbound_nonreg_file = 1,
ff002b30 699 .needs_fs = 1,
8a72758c 700 .pollin = 1,
d3656344 701 },
0463b6c5 702 [IORING_OP_TIMEOUT] = {
d3656344
JA
703 .async_ctx = 1,
704 .needs_mm = 1,
705 },
0463b6c5
PB
706 [IORING_OP_TIMEOUT_REMOVE] = {},
707 [IORING_OP_ACCEPT] = {
d3656344
JA
708 .needs_mm = 1,
709 .needs_file = 1,
710 .unbound_nonreg_file = 1,
f86cd20c 711 .file_table = 1,
8a72758c 712 .pollin = 1,
d3656344 713 },
0463b6c5
PB
714 [IORING_OP_ASYNC_CANCEL] = {},
715 [IORING_OP_LINK_TIMEOUT] = {
d3656344
JA
716 .async_ctx = 1,
717 .needs_mm = 1,
718 },
0463b6c5 719 [IORING_OP_CONNECT] = {
d3656344
JA
720 .async_ctx = 1,
721 .needs_mm = 1,
722 .needs_file = 1,
723 .unbound_nonreg_file = 1,
8a72758c 724 .pollout = 1,
d3656344 725 },
0463b6c5 726 [IORING_OP_FALLOCATE] = {
d3656344
JA
727 .needs_file = 1,
728 },
0463b6c5 729 [IORING_OP_OPENAT] = {
d3656344
JA
730 .needs_file = 1,
731 .fd_non_neg = 1,
f86cd20c 732 .file_table = 1,
ff002b30 733 .needs_fs = 1,
d3656344 734 },
0463b6c5 735 [IORING_OP_CLOSE] = {
d3656344 736 .needs_file = 1,
f86cd20c 737 .file_table = 1,
d3656344 738 },
0463b6c5 739 [IORING_OP_FILES_UPDATE] = {
d3656344 740 .needs_mm = 1,
f86cd20c 741 .file_table = 1,
d3656344 742 },
0463b6c5 743 [IORING_OP_STATX] = {
d3656344
JA
744 .needs_mm = 1,
745 .needs_file = 1,
746 .fd_non_neg = 1,
ff002b30 747 .needs_fs = 1,
d3656344 748 },
0463b6c5 749 [IORING_OP_READ] = {
3a6820f2
JA
750 .needs_mm = 1,
751 .needs_file = 1,
752 .unbound_nonreg_file = 1,
8a72758c 753 .pollin = 1,
3a6820f2 754 },
0463b6c5 755 [IORING_OP_WRITE] = {
3a6820f2
JA
756 .needs_mm = 1,
757 .needs_file = 1,
758 .unbound_nonreg_file = 1,
8a72758c 759 .pollout = 1,
3a6820f2 760 },
0463b6c5 761 [IORING_OP_FADVISE] = {
4840e418
JA
762 .needs_file = 1,
763 },
0463b6c5 764 [IORING_OP_MADVISE] = {
c1ca757b
JA
765 .needs_mm = 1,
766 },
0463b6c5 767 [IORING_OP_SEND] = {
fddaface
JA
768 .needs_mm = 1,
769 .needs_file = 1,
770 .unbound_nonreg_file = 1,
8a72758c 771 .pollout = 1,
fddaface 772 },
0463b6c5 773 [IORING_OP_RECV] = {
fddaface
JA
774 .needs_mm = 1,
775 .needs_file = 1,
776 .unbound_nonreg_file = 1,
8a72758c 777 .pollin = 1,
fddaface 778 },
0463b6c5 779 [IORING_OP_OPENAT2] = {
cebdb986
JA
780 .needs_file = 1,
781 .fd_non_neg = 1,
f86cd20c 782 .file_table = 1,
ff002b30 783 .needs_fs = 1,
cebdb986 784 },
3e4827b0
JA
785 [IORING_OP_EPOLL_CTL] = {
786 .unbound_nonreg_file = 1,
787 .file_table = 1,
788 },
7d67af2c
PB
789 [IORING_OP_SPLICE] = {
790 .needs_file = 1,
791 .hash_reg_file = 1,
792 .unbound_nonreg_file = 1,
793 }
d3656344
JA
794};
795
561fb04a 796static void io_wq_submit_work(struct io_wq_work **workptr);
78e19bbe 797static void io_cqring_fill_event(struct io_kiocb *req, long res);
ec9c02ad 798static void io_put_req(struct io_kiocb *req);
978db57e 799static void __io_double_put_req(struct io_kiocb *req);
94ae5e77
JA
800static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
801static void io_queue_linked_timeout(struct io_kiocb *req);
05f3fb3c
JA
802static int __io_sqe_files_update(struct io_ring_ctx *ctx,
803 struct io_uring_files_update *ip,
804 unsigned nr_args);
f86cd20c 805static int io_grab_files(struct io_kiocb *req);
2faf852d 806static void io_ring_file_ref_flush(struct fixed_file_data *data);
99bc4c38 807static void io_cleanup_req(struct io_kiocb *req);
b41e9852
JA
808static int io_file_get(struct io_submit_state *state, struct io_kiocb *req,
809 int fd, struct file **out_file, bool fixed);
810static void __io_queue_sqe(struct io_kiocb *req,
811 const struct io_uring_sqe *sqe);
de0617e4 812
2b188cc1
JA
813static struct kmem_cache *req_cachep;
814
815static const struct file_operations io_uring_fops;
816
817struct sock *io_uring_get_socket(struct file *file)
818{
819#if defined(CONFIG_UNIX)
820 if (file->f_op == &io_uring_fops) {
821 struct io_ring_ctx *ctx = file->private_data;
822
823 return ctx->ring_sock->sk;
824 }
825#endif
826 return NULL;
827}
828EXPORT_SYMBOL(io_uring_get_socket);
829
830static void io_ring_ctx_ref_free(struct percpu_ref *ref)
831{
832 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
833
206aefde 834 complete(&ctx->completions[0]);
2b188cc1
JA
835}
836
837static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
838{
839 struct io_ring_ctx *ctx;
78076bb6 840 int hash_bits;
2b188cc1
JA
841
842 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
843 if (!ctx)
844 return NULL;
845
0ddf92e8
JA
846 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
847 if (!ctx->fallback_req)
848 goto err;
849
206aefde
JA
850 ctx->completions = kmalloc(2 * sizeof(struct completion), GFP_KERNEL);
851 if (!ctx->completions)
852 goto err;
853
78076bb6
JA
854 /*
855 * Use 5 bits less than the max cq entries, that should give us around
856 * 32 entries per hash list if totally full and uniformly spread.
857 */
858 hash_bits = ilog2(p->cq_entries);
859 hash_bits -= 5;
860 if (hash_bits <= 0)
861 hash_bits = 1;
862 ctx->cancel_hash_bits = hash_bits;
863 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
864 GFP_KERNEL);
865 if (!ctx->cancel_hash)
866 goto err;
867 __hash_init(ctx->cancel_hash, 1U << hash_bits);
868
21482896 869 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
206aefde
JA
870 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
871 goto err;
2b188cc1
JA
872
873 ctx->flags = p->flags;
874 init_waitqueue_head(&ctx->cq_wait);
1d7bb1d5 875 INIT_LIST_HEAD(&ctx->cq_overflow_list);
206aefde
JA
876 init_completion(&ctx->completions[0]);
877 init_completion(&ctx->completions[1]);
071698e1 878 idr_init(&ctx->personality_idr);
2b188cc1
JA
879 mutex_init(&ctx->uring_lock);
880 init_waitqueue_head(&ctx->wait);
881 spin_lock_init(&ctx->completion_lock);
def596e9 882 INIT_LIST_HEAD(&ctx->poll_list);
de0617e4 883 INIT_LIST_HEAD(&ctx->defer_list);
5262f567 884 INIT_LIST_HEAD(&ctx->timeout_list);
fcb323cc
JA
885 init_waitqueue_head(&ctx->inflight_wait);
886 spin_lock_init(&ctx->inflight_lock);
887 INIT_LIST_HEAD(&ctx->inflight_list);
2b188cc1 888 return ctx;
206aefde 889err:
0ddf92e8
JA
890 if (ctx->fallback_req)
891 kmem_cache_free(req_cachep, ctx->fallback_req);
206aefde 892 kfree(ctx->completions);
78076bb6 893 kfree(ctx->cancel_hash);
206aefde
JA
894 kfree(ctx);
895 return NULL;
2b188cc1
JA
896}
897
9d858b21 898static inline bool __req_need_defer(struct io_kiocb *req)
7adf4eaf 899{
a197f664
JL
900 struct io_ring_ctx *ctx = req->ctx;
901
498ccd9e
JA
902 return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
903 + atomic_read(&ctx->cached_cq_overflow);
7adf4eaf
JA
904}
905
9d858b21 906static inline bool req_need_defer(struct io_kiocb *req)
de0617e4 907{
87987898 908 if (unlikely(req->flags & REQ_F_IO_DRAIN))
9d858b21 909 return __req_need_defer(req);
de0617e4 910
9d858b21 911 return false;
de0617e4
JA
912}
913
7adf4eaf 914static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
de0617e4
JA
915{
916 struct io_kiocb *req;
917
7adf4eaf 918 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
9d858b21 919 if (req && !req_need_defer(req)) {
de0617e4
JA
920 list_del_init(&req->list);
921 return req;
922 }
923
924 return NULL;
925}
926
5262f567
JA
927static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
928{
7adf4eaf
JA
929 struct io_kiocb *req;
930
931 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
93bd25bb
JA
932 if (req) {
933 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
934 return NULL;
fb4b3d3f 935 if (!__req_need_defer(req)) {
93bd25bb
JA
936 list_del_init(&req->list);
937 return req;
938 }
7adf4eaf
JA
939 }
940
941 return NULL;
5262f567
JA
942}
943
de0617e4 944static void __io_commit_cqring(struct io_ring_ctx *ctx)
2b188cc1 945{
75b28aff 946 struct io_rings *rings = ctx->rings;
2b188cc1 947
07910158
PB
948 /* order cqe stores with ring update */
949 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
2b188cc1 950
07910158
PB
951 if (wq_has_sleeper(&ctx->cq_wait)) {
952 wake_up_interruptible(&ctx->cq_wait);
953 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
2b188cc1
JA
954 }
955}
956
cccf0ee8
JA
957static inline void io_req_work_grab_env(struct io_kiocb *req,
958 const struct io_op_def *def)
959{
960 if (!req->work.mm && def->needs_mm) {
961 mmgrab(current->mm);
962 req->work.mm = current->mm;
2b188cc1 963 }
cccf0ee8
JA
964 if (!req->work.creds)
965 req->work.creds = get_current_cred();
ff002b30
JA
966 if (!req->work.fs && def->needs_fs) {
967 spin_lock(&current->fs->lock);
968 if (!current->fs->in_exec) {
969 req->work.fs = current->fs;
970 req->work.fs->users++;
971 } else {
972 req->work.flags |= IO_WQ_WORK_CANCEL;
973 }
974 spin_unlock(&current->fs->lock);
975 }
6ab23144
JA
976 if (!req->work.task_pid)
977 req->work.task_pid = task_pid_vnr(current);
2b188cc1
JA
978}
979
cccf0ee8 980static inline void io_req_work_drop_env(struct io_kiocb *req)
18d9be1a 981{
cccf0ee8
JA
982 if (req->work.mm) {
983 mmdrop(req->work.mm);
984 req->work.mm = NULL;
985 }
986 if (req->work.creds) {
987 put_cred(req->work.creds);
988 req->work.creds = NULL;
989 }
ff002b30
JA
990 if (req->work.fs) {
991 struct fs_struct *fs = req->work.fs;
992
993 spin_lock(&req->work.fs->lock);
994 if (--fs->users)
995 fs = NULL;
996 spin_unlock(&req->work.fs->lock);
997 if (fs)
998 free_fs_struct(fs);
999 }
561fb04a
JA
1000}
1001
deb6dc05
PB
1002static inline void io_prep_next_work(struct io_kiocb *req,
1003 struct io_kiocb **link)
1004{
1005 const struct io_op_def *def = &io_op_defs[req->opcode];
1006
1007 if (!(req->flags & REQ_F_ISREG) && def->unbound_nonreg_file)
1008 req->work.flags |= IO_WQ_WORK_UNBOUND;
1009
1010 *link = io_prep_linked_timeout(req);
1011}
1012
94ae5e77
JA
1013static inline bool io_prep_async_work(struct io_kiocb *req,
1014 struct io_kiocb **link)
18d9be1a 1015{
d3656344 1016 const struct io_op_def *def = &io_op_defs[req->opcode];
561fb04a 1017 bool do_hashed = false;
54a91f3b 1018
d3656344
JA
1019 if (req->flags & REQ_F_ISREG) {
1020 if (def->hash_reg_file)
3529d8c2 1021 do_hashed = true;
d3656344
JA
1022 } else {
1023 if (def->unbound_nonreg_file)
3529d8c2 1024 req->work.flags |= IO_WQ_WORK_UNBOUND;
54a91f3b 1025 }
cccf0ee8
JA
1026
1027 io_req_work_grab_env(req, def);
54a91f3b 1028
94ae5e77 1029 *link = io_prep_linked_timeout(req);
561fb04a
JA
1030 return do_hashed;
1031}
1032
a197f664 1033static inline void io_queue_async_work(struct io_kiocb *req)
561fb04a 1034{
a197f664 1035 struct io_ring_ctx *ctx = req->ctx;
94ae5e77
JA
1036 struct io_kiocb *link;
1037 bool do_hashed;
1038
1039 do_hashed = io_prep_async_work(req, &link);
561fb04a
JA
1040
1041 trace_io_uring_queue_async_work(ctx, do_hashed, req, &req->work,
1042 req->flags);
1043 if (!do_hashed) {
1044 io_wq_enqueue(ctx->io_wq, &req->work);
1045 } else {
1046 io_wq_enqueue_hashed(ctx->io_wq, &req->work,
1047 file_inode(req->file));
1048 }
94ae5e77
JA
1049
1050 if (link)
1051 io_queue_linked_timeout(link);
18d9be1a
JA
1052}
1053
5262f567
JA
1054static void io_kill_timeout(struct io_kiocb *req)
1055{
1056 int ret;
1057
2d28390a 1058 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
5262f567
JA
1059 if (ret != -1) {
1060 atomic_inc(&req->ctx->cq_timeouts);
842f9612 1061 list_del_init(&req->list);
78e19bbe 1062 io_cqring_fill_event(req, 0);
ec9c02ad 1063 io_put_req(req);
5262f567
JA
1064 }
1065}
1066
1067static void io_kill_timeouts(struct io_ring_ctx *ctx)
1068{
1069 struct io_kiocb *req, *tmp;
1070
1071 spin_lock_irq(&ctx->completion_lock);
1072 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
1073 io_kill_timeout(req);
1074 spin_unlock_irq(&ctx->completion_lock);
1075}
1076
de0617e4
JA
1077static void io_commit_cqring(struct io_ring_ctx *ctx)
1078{
1079 struct io_kiocb *req;
1080
5262f567
JA
1081 while ((req = io_get_timeout_req(ctx)) != NULL)
1082 io_kill_timeout(req);
1083
de0617e4
JA
1084 __io_commit_cqring(ctx);
1085
87987898 1086 while ((req = io_get_deferred_req(ctx)) != NULL)
a197f664 1087 io_queue_async_work(req);
de0617e4
JA
1088}
1089
2b188cc1
JA
1090static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1091{
75b28aff 1092 struct io_rings *rings = ctx->rings;
2b188cc1
JA
1093 unsigned tail;
1094
1095 tail = ctx->cached_cq_tail;
115e12e5
SB
1096 /*
1097 * writes to the cq entry need to come after reading head; the
1098 * control dependency is enough as we're using WRITE_ONCE to
1099 * fill the cq entry
1100 */
75b28aff 1101 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
2b188cc1
JA
1102 return NULL;
1103
1104 ctx->cached_cq_tail++;
75b28aff 1105 return &rings->cqes[tail & ctx->cq_mask];
2b188cc1
JA
1106}
1107
f2842ab5
JA
1108static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1109{
f0b493e6
JA
1110 if (!ctx->cq_ev_fd)
1111 return false;
f2842ab5
JA
1112 if (!ctx->eventfd_async)
1113 return true;
b41e9852 1114 return io_wq_current_is_worker();
f2842ab5
JA
1115}
1116
b41e9852 1117static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1d7bb1d5
JA
1118{
1119 if (waitqueue_active(&ctx->wait))
1120 wake_up(&ctx->wait);
1121 if (waitqueue_active(&ctx->sqo_wait))
1122 wake_up(&ctx->sqo_wait);
b41e9852 1123 if (io_should_trigger_evfd(ctx))
1d7bb1d5
JA
1124 eventfd_signal(ctx->cq_ev_fd, 1);
1125}
1126
c4a2ed72
JA
1127/* Returns true if there are no backlogged entries after the flush */
1128static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1d7bb1d5
JA
1129{
1130 struct io_rings *rings = ctx->rings;
1131 struct io_uring_cqe *cqe;
1132 struct io_kiocb *req;
1133 unsigned long flags;
1134 LIST_HEAD(list);
1135
1136 if (!force) {
1137 if (list_empty_careful(&ctx->cq_overflow_list))
c4a2ed72 1138 return true;
1d7bb1d5
JA
1139 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
1140 rings->cq_ring_entries))
c4a2ed72 1141 return false;
1d7bb1d5
JA
1142 }
1143
1144 spin_lock_irqsave(&ctx->completion_lock, flags);
1145
1146 /* if force is set, the ring is going away. always drop after that */
1147 if (force)
69b3e546 1148 ctx->cq_overflow_flushed = 1;
1d7bb1d5 1149
c4a2ed72 1150 cqe = NULL;
1d7bb1d5
JA
1151 while (!list_empty(&ctx->cq_overflow_list)) {
1152 cqe = io_get_cqring(ctx);
1153 if (!cqe && !force)
1154 break;
1155
1156 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
1157 list);
1158 list_move(&req->list, &list);
2ca10259 1159 req->flags &= ~REQ_F_OVERFLOW;
1d7bb1d5
JA
1160 if (cqe) {
1161 WRITE_ONCE(cqe->user_data, req->user_data);
1162 WRITE_ONCE(cqe->res, req->result);
1163 WRITE_ONCE(cqe->flags, 0);
1164 } else {
1165 WRITE_ONCE(ctx->rings->cq_overflow,
1166 atomic_inc_return(&ctx->cached_cq_overflow));
1167 }
1168 }
1169
1170 io_commit_cqring(ctx);
ad3eb2c8
JA
1171 if (cqe) {
1172 clear_bit(0, &ctx->sq_check_overflow);
1173 clear_bit(0, &ctx->cq_check_overflow);
1174 }
1d7bb1d5
JA
1175 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1176 io_cqring_ev_posted(ctx);
1177
1178 while (!list_empty(&list)) {
1179 req = list_first_entry(&list, struct io_kiocb, list);
1180 list_del(&req->list);
ec9c02ad 1181 io_put_req(req);
1d7bb1d5 1182 }
c4a2ed72
JA
1183
1184 return cqe != NULL;
1d7bb1d5
JA
1185}
1186
78e19bbe 1187static void io_cqring_fill_event(struct io_kiocb *req, long res)
2b188cc1 1188{
78e19bbe 1189 struct io_ring_ctx *ctx = req->ctx;
2b188cc1
JA
1190 struct io_uring_cqe *cqe;
1191
78e19bbe 1192 trace_io_uring_complete(ctx, req->user_data, res);
51c3ff62 1193
2b188cc1
JA
1194 /*
1195 * If we can't get a cq entry, userspace overflowed the
1196 * submission (by quite a lot). Increment the overflow count in
1197 * the ring.
1198 */
1199 cqe = io_get_cqring(ctx);
1d7bb1d5 1200 if (likely(cqe)) {
78e19bbe 1201 WRITE_ONCE(cqe->user_data, req->user_data);
2b188cc1 1202 WRITE_ONCE(cqe->res, res);
c71ffb67 1203 WRITE_ONCE(cqe->flags, 0);
1d7bb1d5 1204 } else if (ctx->cq_overflow_flushed) {
498ccd9e
JA
1205 WRITE_ONCE(ctx->rings->cq_overflow,
1206 atomic_inc_return(&ctx->cached_cq_overflow));
1d7bb1d5 1207 } else {
ad3eb2c8
JA
1208 if (list_empty(&ctx->cq_overflow_list)) {
1209 set_bit(0, &ctx->sq_check_overflow);
1210 set_bit(0, &ctx->cq_check_overflow);
1211 }
2ca10259 1212 req->flags |= REQ_F_OVERFLOW;
1d7bb1d5
JA
1213 refcount_inc(&req->refs);
1214 req->result = res;
1215 list_add_tail(&req->list, &ctx->cq_overflow_list);
2b188cc1
JA
1216 }
1217}
1218
78e19bbe 1219static void io_cqring_add_event(struct io_kiocb *req, long res)
2b188cc1 1220{
78e19bbe 1221 struct io_ring_ctx *ctx = req->ctx;
2b188cc1
JA
1222 unsigned long flags;
1223
1224 spin_lock_irqsave(&ctx->completion_lock, flags);
78e19bbe 1225 io_cqring_fill_event(req, res);
2b188cc1
JA
1226 io_commit_cqring(ctx);
1227 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1228
8c838788 1229 io_cqring_ev_posted(ctx);
2b188cc1
JA
1230}
1231
0ddf92e8
JA
1232static inline bool io_is_fallback_req(struct io_kiocb *req)
1233{
1234 return req == (struct io_kiocb *)
1235 ((unsigned long) req->ctx->fallback_req & ~1UL);
1236}
1237
1238static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1239{
1240 struct io_kiocb *req;
1241
1242 req = ctx->fallback_req;
1243 if (!test_and_set_bit_lock(0, (unsigned long *) ctx->fallback_req))
1244 return req;
1245
1246 return NULL;
1247}
1248
2579f913
JA
1249static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
1250 struct io_submit_state *state)
2b188cc1 1251{
fd6fab2c 1252 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2b188cc1
JA
1253 struct io_kiocb *req;
1254
2579f913 1255 if (!state) {
fd6fab2c 1256 req = kmem_cache_alloc(req_cachep, gfp);
2579f913 1257 if (unlikely(!req))
0ddf92e8 1258 goto fallback;
2579f913
JA
1259 } else if (!state->free_reqs) {
1260 size_t sz;
1261 int ret;
1262
1263 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
fd6fab2c
JA
1264 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1265
1266 /*
1267 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1268 * retry single alloc to be on the safe side.
1269 */
1270 if (unlikely(ret <= 0)) {
1271 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1272 if (!state->reqs[0])
0ddf92e8 1273 goto fallback;
fd6fab2c
JA
1274 ret = 1;
1275 }
2579f913 1276 state->free_reqs = ret - 1;
6c8a3134 1277 req = state->reqs[ret - 1];
2579f913 1278 } else {
2579f913 1279 state->free_reqs--;
6c8a3134 1280 req = state->reqs[state->free_reqs];
2b188cc1
JA
1281 }
1282
0ddf92e8 1283got_it:
1a6b74fc 1284 req->io = NULL;
60c112b0 1285 req->file = NULL;
2579f913
JA
1286 req->ctx = ctx;
1287 req->flags = 0;
e65ef56d
JA
1288 /* one is dropped after submission, the other at completion */
1289 refcount_set(&req->refs, 2);
9e645e11 1290 req->result = 0;
561fb04a 1291 INIT_IO_WORK(&req->work, io_wq_submit_work);
2579f913 1292 return req;
0ddf92e8
JA
1293fallback:
1294 req = io_get_fallback_req(ctx);
1295 if (req)
1296 goto got_it;
6805b32e 1297 percpu_ref_put(&ctx->refs);
2b188cc1
JA
1298 return NULL;
1299}
1300
8da11c19
PB
1301static inline void io_put_file(struct io_kiocb *req, struct file *file,
1302 bool fixed)
1303{
1304 if (fixed)
1305 percpu_ref_put(&req->ctx->file_data->refs);
1306 else
1307 fput(file);
1308}
1309
2b85edfc 1310static void __io_req_do_free(struct io_kiocb *req)
def596e9 1311{
2b85edfc
PB
1312 if (likely(!io_is_fallback_req(req)))
1313 kmem_cache_free(req_cachep, req);
1314 else
1315 clear_bit_unlock(0, (unsigned long *) req->ctx->fallback_req);
1316}
1317
c6ca97b3 1318static void __io_req_aux_free(struct io_kiocb *req)
2b188cc1 1319{
929a3af9
PB
1320 if (req->flags & REQ_F_NEED_CLEANUP)
1321 io_cleanup_req(req);
1322
96fd84d8 1323 kfree(req->io);
8da11c19
PB
1324 if (req->file)
1325 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
cccf0ee8
JA
1326
1327 io_req_work_drop_env(req);
def596e9
JA
1328}
1329
9e645e11 1330static void __io_free_req(struct io_kiocb *req)
2b188cc1 1331{
c6ca97b3 1332 __io_req_aux_free(req);
fcb323cc 1333
fcb323cc 1334 if (req->flags & REQ_F_INFLIGHT) {
c6ca97b3 1335 struct io_ring_ctx *ctx = req->ctx;
fcb323cc
JA
1336 unsigned long flags;
1337
1338 spin_lock_irqsave(&ctx->inflight_lock, flags);
1339 list_del(&req->inflight_entry);
1340 if (waitqueue_active(&ctx->inflight_wait))
1341 wake_up(&ctx->inflight_wait);
1342 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1343 }
2b85edfc
PB
1344
1345 percpu_ref_put(&req->ctx->refs);
1346 __io_req_do_free(req);
e65ef56d
JA
1347}
1348
c6ca97b3
JA
1349struct req_batch {
1350 void *reqs[IO_IOPOLL_BATCH];
1351 int to_free;
1352 int need_iter;
1353};
1354
1355static void io_free_req_many(struct io_ring_ctx *ctx, struct req_batch *rb)
1356{
10fef4be
JA
1357 int fixed_refs = rb->to_free;
1358
c6ca97b3
JA
1359 if (!rb->to_free)
1360 return;
1361 if (rb->need_iter) {
1362 int i, inflight = 0;
1363 unsigned long flags;
1364
10fef4be 1365 fixed_refs = 0;
c6ca97b3
JA
1366 for (i = 0; i < rb->to_free; i++) {
1367 struct io_kiocb *req = rb->reqs[i];
1368
10fef4be 1369 if (req->flags & REQ_F_FIXED_FILE) {
c6ca97b3 1370 req->file = NULL;
10fef4be
JA
1371 fixed_refs++;
1372 }
c6ca97b3
JA
1373 if (req->flags & REQ_F_INFLIGHT)
1374 inflight++;
c6ca97b3
JA
1375 __io_req_aux_free(req);
1376 }
1377 if (!inflight)
1378 goto do_free;
1379
1380 spin_lock_irqsave(&ctx->inflight_lock, flags);
1381 for (i = 0; i < rb->to_free; i++) {
1382 struct io_kiocb *req = rb->reqs[i];
1383
10fef4be 1384 if (req->flags & REQ_F_INFLIGHT) {
c6ca97b3
JA
1385 list_del(&req->inflight_entry);
1386 if (!--inflight)
1387 break;
1388 }
1389 }
1390 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1391
1392 if (waitqueue_active(&ctx->inflight_wait))
1393 wake_up(&ctx->inflight_wait);
1394 }
1395do_free:
1396 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
10fef4be
JA
1397 if (fixed_refs)
1398 percpu_ref_put_many(&ctx->file_data->refs, fixed_refs);
c6ca97b3 1399 percpu_ref_put_many(&ctx->refs, rb->to_free);
c6ca97b3 1400 rb->to_free = rb->need_iter = 0;
e65ef56d
JA
1401}
1402
a197f664 1403static bool io_link_cancel_timeout(struct io_kiocb *req)
2665abfd 1404{
a197f664 1405 struct io_ring_ctx *ctx = req->ctx;
2665abfd
JA
1406 int ret;
1407
2d28390a 1408 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
2665abfd 1409 if (ret != -1) {
78e19bbe 1410 io_cqring_fill_event(req, -ECANCELED);
2665abfd
JA
1411 io_commit_cqring(ctx);
1412 req->flags &= ~REQ_F_LINK;
ec9c02ad 1413 io_put_req(req);
2665abfd
JA
1414 return true;
1415 }
1416
1417 return false;
e65ef56d
JA
1418}
1419
ba816ad6 1420static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
9e645e11 1421{
2665abfd 1422 struct io_ring_ctx *ctx = req->ctx;
2665abfd 1423 bool wake_ev = false;
9e645e11 1424
4d7dd462
JA
1425 /* Already got next link */
1426 if (req->flags & REQ_F_LINK_NEXT)
1427 return;
1428
9e645e11
JA
1429 /*
1430 * The list should never be empty when we are called here. But could
1431 * potentially happen if the chain is messed up, check to be on the
1432 * safe side.
1433 */
4493233e
PB
1434 while (!list_empty(&req->link_list)) {
1435 struct io_kiocb *nxt = list_first_entry(&req->link_list,
1436 struct io_kiocb, link_list);
94ae5e77 1437
4493233e
PB
1438 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
1439 (nxt->flags & REQ_F_TIMEOUT))) {
1440 list_del_init(&nxt->link_list);
94ae5e77 1441 wake_ev |= io_link_cancel_timeout(nxt);
94ae5e77
JA
1442 req->flags &= ~REQ_F_LINK_TIMEOUT;
1443 continue;
1444 }
9e645e11 1445
4493233e
PB
1446 list_del_init(&req->link_list);
1447 if (!list_empty(&nxt->link_list))
1448 nxt->flags |= REQ_F_LINK;
b18fdf71 1449 *nxtptr = nxt;
94ae5e77 1450 break;
9e645e11 1451 }
2665abfd 1452
4d7dd462 1453 req->flags |= REQ_F_LINK_NEXT;
2665abfd
JA
1454 if (wake_ev)
1455 io_cqring_ev_posted(ctx);
9e645e11
JA
1456}
1457
1458/*
1459 * Called if REQ_F_LINK is set, and we fail the head request
1460 */
1461static void io_fail_links(struct io_kiocb *req)
1462{
2665abfd 1463 struct io_ring_ctx *ctx = req->ctx;
2665abfd
JA
1464 unsigned long flags;
1465
1466 spin_lock_irqsave(&ctx->completion_lock, flags);
9e645e11
JA
1467
1468 while (!list_empty(&req->link_list)) {
4493233e
PB
1469 struct io_kiocb *link = list_first_entry(&req->link_list,
1470 struct io_kiocb, link_list);
9e645e11 1471
4493233e 1472 list_del_init(&link->link_list);
c826bd7a 1473 trace_io_uring_fail_link(req, link);
2665abfd
JA
1474
1475 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
d625c6ee 1476 link->opcode == IORING_OP_LINK_TIMEOUT) {
a197f664 1477 io_link_cancel_timeout(link);
2665abfd 1478 } else {
78e19bbe 1479 io_cqring_fill_event(link, -ECANCELED);
978db57e 1480 __io_double_put_req(link);
2665abfd 1481 }
5d960724 1482 req->flags &= ~REQ_F_LINK_TIMEOUT;
9e645e11 1483 }
2665abfd
JA
1484
1485 io_commit_cqring(ctx);
1486 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1487 io_cqring_ev_posted(ctx);
9e645e11
JA
1488}
1489
4d7dd462 1490static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
9e645e11 1491{
4d7dd462 1492 if (likely(!(req->flags & REQ_F_LINK)))
2665abfd 1493 return;
2665abfd 1494
9e645e11
JA
1495 /*
1496 * If LINK is set, we have dependent requests in this chain. If we
1497 * didn't fail this request, queue the first one up, moving any other
1498 * dependencies to the next request. In case of failure, fail the rest
1499 * of the chain.
1500 */
2665abfd
JA
1501 if (req->flags & REQ_F_FAIL_LINK) {
1502 io_fail_links(req);
7c9e7f0f
JA
1503 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1504 REQ_F_LINK_TIMEOUT) {
2665abfd
JA
1505 struct io_ring_ctx *ctx = req->ctx;
1506 unsigned long flags;
1507
1508 /*
1509 * If this is a timeout link, we could be racing with the
1510 * timeout timer. Grab the completion lock for this case to
7c9e7f0f 1511 * protect against that.
2665abfd
JA
1512 */
1513 spin_lock_irqsave(&ctx->completion_lock, flags);
1514 io_req_link_next(req, nxt);
1515 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1516 } else {
1517 io_req_link_next(req, nxt);
9e645e11 1518 }
4d7dd462 1519}
9e645e11 1520
c69f8dbe
JL
1521static void io_free_req(struct io_kiocb *req)
1522{
944e58bf
PB
1523 struct io_kiocb *nxt = NULL;
1524
1525 io_req_find_next(req, &nxt);
70cf9f32 1526 __io_free_req(req);
944e58bf
PB
1527
1528 if (nxt)
1529 io_queue_async_work(nxt);
c69f8dbe
JL
1530}
1531
ba816ad6
JA
1532/*
1533 * Drop reference to request, return next in chain (if there is one) if this
1534 * was the last reference to this request.
1535 */
f9bd67f6 1536__attribute__((nonnull))
ec9c02ad 1537static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
e65ef56d 1538{
2a44f467
JA
1539 if (refcount_dec_and_test(&req->refs)) {
1540 io_req_find_next(req, nxtptr);
4d7dd462 1541 __io_free_req(req);
2a44f467 1542 }
2b188cc1
JA
1543}
1544
e65ef56d
JA
1545static void io_put_req(struct io_kiocb *req)
1546{
1547 if (refcount_dec_and_test(&req->refs))
1548 io_free_req(req);
2b188cc1
JA
1549}
1550
978db57e
JA
1551/*
1552 * Must only be used if we don't need to care about links, usually from
1553 * within the completion handling itself.
1554 */
1555static void __io_double_put_req(struct io_kiocb *req)
78e19bbe
JA
1556{
1557 /* drop both submit and complete references */
1558 if (refcount_sub_and_test(2, &req->refs))
1559 __io_free_req(req);
1560}
1561
978db57e
JA
1562static void io_double_put_req(struct io_kiocb *req)
1563{
1564 /* drop both submit and complete references */
1565 if (refcount_sub_and_test(2, &req->refs))
1566 io_free_req(req);
1567}
1568
1d7bb1d5 1569static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
a3a0e43f 1570{
84f97dc2
JA
1571 struct io_rings *rings = ctx->rings;
1572
ad3eb2c8
JA
1573 if (test_bit(0, &ctx->cq_check_overflow)) {
1574 /*
1575 * noflush == true is from the waitqueue handler, just ensure
1576 * we wake up the task, and the next invocation will flush the
1577 * entries. We cannot safely to it from here.
1578 */
1579 if (noflush && !list_empty(&ctx->cq_overflow_list))
1580 return -1U;
1d7bb1d5 1581
ad3eb2c8
JA
1582 io_cqring_overflow_flush(ctx, false);
1583 }
1d7bb1d5 1584
a3a0e43f
JA
1585 /* See comment at the top of this file */
1586 smp_rmb();
ad3eb2c8 1587 return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
a3a0e43f
JA
1588}
1589
fb5ccc98
PB
1590static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1591{
1592 struct io_rings *rings = ctx->rings;
1593
1594 /* make sure SQ entry isn't read before tail */
1595 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1596}
1597
8237e045 1598static inline bool io_req_multi_free(struct req_batch *rb, struct io_kiocb *req)
e94f141b 1599{
c6ca97b3
JA
1600 if ((req->flags & REQ_F_LINK) || io_is_fallback_req(req))
1601 return false;
e94f141b 1602
c6ca97b3
JA
1603 if (!(req->flags & REQ_F_FIXED_FILE) || req->io)
1604 rb->need_iter++;
1605
1606 rb->reqs[rb->to_free++] = req;
1607 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
1608 io_free_req_many(req->ctx, rb);
1609 return true;
e94f141b
JA
1610}
1611
def596e9
JA
1612/*
1613 * Find and free completed poll iocbs
1614 */
1615static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1616 struct list_head *done)
1617{
8237e045 1618 struct req_batch rb;
def596e9 1619 struct io_kiocb *req;
def596e9 1620
c6ca97b3 1621 rb.to_free = rb.need_iter = 0;
def596e9
JA
1622 while (!list_empty(done)) {
1623 req = list_first_entry(done, struct io_kiocb, list);
1624 list_del(&req->list);
1625
78e19bbe 1626 io_cqring_fill_event(req, req->result);
def596e9
JA
1627 (*nr_events)++;
1628
8237e045
JA
1629 if (refcount_dec_and_test(&req->refs) &&
1630 !io_req_multi_free(&rb, req))
1631 io_free_req(req);
def596e9 1632 }
def596e9 1633
09bb8394 1634 io_commit_cqring(ctx);
8237e045 1635 io_free_req_many(ctx, &rb);
def596e9
JA
1636}
1637
1638static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1639 long min)
1640{
1641 struct io_kiocb *req, *tmp;
1642 LIST_HEAD(done);
1643 bool spin;
1644 int ret;
1645
1646 /*
1647 * Only spin for completions if we don't have multiple devices hanging
1648 * off our complete list, and we're under the requested amount.
1649 */
1650 spin = !ctx->poll_multi_file && *nr_events < min;
1651
1652 ret = 0;
1653 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
9adbd45d 1654 struct kiocb *kiocb = &req->rw.kiocb;
def596e9
JA
1655
1656 /*
1657 * Move completed entries to our local list. If we find a
1658 * request that requires polling, break out and complete
1659 * the done list first, if we have entries there.
1660 */
1661 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
1662 list_move_tail(&req->list, &done);
1663 continue;
1664 }
1665 if (!list_empty(&done))
1666 break;
1667
1668 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1669 if (ret < 0)
1670 break;
1671
1672 if (ret && spin)
1673 spin = false;
1674 ret = 0;
1675 }
1676
1677 if (!list_empty(&done))
1678 io_iopoll_complete(ctx, nr_events, &done);
1679
1680 return ret;
1681}
1682
1683/*
d195a66e 1684 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
def596e9
JA
1685 * non-spinning poll check - we'll still enter the driver poll loop, but only
1686 * as a non-spinning completion check.
1687 */
1688static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1689 long min)
1690{
08f5439f 1691 while (!list_empty(&ctx->poll_list) && !need_resched()) {
def596e9
JA
1692 int ret;
1693
1694 ret = io_do_iopoll(ctx, nr_events, min);
1695 if (ret < 0)
1696 return ret;
1697 if (!min || *nr_events >= min)
1698 return 0;
1699 }
1700
1701 return 1;
1702}
1703
1704/*
1705 * We can't just wait for polled events to come to us, we have to actively
1706 * find and complete them.
1707 */
1708static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1709{
1710 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1711 return;
1712
1713 mutex_lock(&ctx->uring_lock);
1714 while (!list_empty(&ctx->poll_list)) {
1715 unsigned int nr_events = 0;
1716
1717 io_iopoll_getevents(ctx, &nr_events, 1);
08f5439f
JA
1718
1719 /*
1720 * Ensure we allow local-to-the-cpu processing to take place,
1721 * in this case we need to ensure that we reap all events.
1722 */
1723 cond_resched();
def596e9
JA
1724 }
1725 mutex_unlock(&ctx->uring_lock);
1726}
1727
c7849be9
XW
1728static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1729 long min)
def596e9 1730{
2b2ed975 1731 int iters = 0, ret = 0;
500f9fba 1732
c7849be9
XW
1733 /*
1734 * We disallow the app entering submit/complete with polling, but we
1735 * still need to lock the ring to prevent racing with polled issue
1736 * that got punted to a workqueue.
1737 */
1738 mutex_lock(&ctx->uring_lock);
def596e9
JA
1739 do {
1740 int tmin = 0;
1741
a3a0e43f
JA
1742 /*
1743 * Don't enter poll loop if we already have events pending.
1744 * If we do, we can potentially be spinning for commands that
1745 * already triggered a CQE (eg in error).
1746 */
1d7bb1d5 1747 if (io_cqring_events(ctx, false))
a3a0e43f
JA
1748 break;
1749
500f9fba
JA
1750 /*
1751 * If a submit got punted to a workqueue, we can have the
1752 * application entering polling for a command before it gets
1753 * issued. That app will hold the uring_lock for the duration
1754 * of the poll right here, so we need to take a breather every
1755 * now and then to ensure that the issue has a chance to add
1756 * the poll to the issued list. Otherwise we can spin here
1757 * forever, while the workqueue is stuck trying to acquire the
1758 * very same mutex.
1759 */
1760 if (!(++iters & 7)) {
1761 mutex_unlock(&ctx->uring_lock);
1762 mutex_lock(&ctx->uring_lock);
1763 }
1764
def596e9
JA
1765 if (*nr_events < min)
1766 tmin = min - *nr_events;
1767
1768 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1769 if (ret <= 0)
1770 break;
1771 ret = 0;
1772 } while (min && !*nr_events && !need_resched());
1773
500f9fba 1774 mutex_unlock(&ctx->uring_lock);
def596e9
JA
1775 return ret;
1776}
1777
491381ce 1778static void kiocb_end_write(struct io_kiocb *req)
2b188cc1 1779{
491381ce
JA
1780 /*
1781 * Tell lockdep we inherited freeze protection from submission
1782 * thread.
1783 */
1784 if (req->flags & REQ_F_ISREG) {
1785 struct inode *inode = file_inode(req->file);
2b188cc1 1786
491381ce 1787 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2b188cc1 1788 }
491381ce 1789 file_end_write(req->file);
2b188cc1
JA
1790}
1791
4e88d6e7
JA
1792static inline void req_set_fail_links(struct io_kiocb *req)
1793{
1794 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1795 req->flags |= REQ_F_FAIL_LINK;
1796}
1797
ba816ad6 1798static void io_complete_rw_common(struct kiocb *kiocb, long res)
2b188cc1 1799{
9adbd45d 1800 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2b188cc1 1801
491381ce
JA
1802 if (kiocb->ki_flags & IOCB_WRITE)
1803 kiocb_end_write(req);
2b188cc1 1804
4e88d6e7
JA
1805 if (res != req->result)
1806 req_set_fail_links(req);
78e19bbe 1807 io_cqring_add_event(req, res);
ba816ad6
JA
1808}
1809
1810static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1811{
9adbd45d 1812 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
ba816ad6
JA
1813
1814 io_complete_rw_common(kiocb, res);
e65ef56d 1815 io_put_req(req);
2b188cc1
JA
1816}
1817
ba816ad6
JA
1818static struct io_kiocb *__io_complete_rw(struct kiocb *kiocb, long res)
1819{
9adbd45d 1820 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
ec9c02ad 1821 struct io_kiocb *nxt = NULL;
ba816ad6
JA
1822
1823 io_complete_rw_common(kiocb, res);
ec9c02ad
JL
1824 io_put_req_find_next(req, &nxt);
1825
1826 return nxt;
2b188cc1
JA
1827}
1828
def596e9
JA
1829static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1830{
9adbd45d 1831 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
def596e9 1832
491381ce
JA
1833 if (kiocb->ki_flags & IOCB_WRITE)
1834 kiocb_end_write(req);
def596e9 1835
4e88d6e7
JA
1836 if (res != req->result)
1837 req_set_fail_links(req);
9e645e11 1838 req->result = res;
def596e9
JA
1839 if (res != -EAGAIN)
1840 req->flags |= REQ_F_IOPOLL_COMPLETED;
1841}
1842
1843/*
1844 * After the iocb has been issued, it's safe to be found on the poll list.
1845 * Adding the kiocb to the list AFTER submission ensures that we don't
1846 * find it from a io_iopoll_getevents() thread before the issuer is done
1847 * accessing the kiocb cookie.
1848 */
1849static void io_iopoll_req_issued(struct io_kiocb *req)
1850{
1851 struct io_ring_ctx *ctx = req->ctx;
1852
1853 /*
1854 * Track whether we have multiple files in our lists. This will impact
1855 * how we do polling eventually, not spinning if we're on potentially
1856 * different devices.
1857 */
1858 if (list_empty(&ctx->poll_list)) {
1859 ctx->poll_multi_file = false;
1860 } else if (!ctx->poll_multi_file) {
1861 struct io_kiocb *list_req;
1862
1863 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1864 list);
9adbd45d 1865 if (list_req->file != req->file)
def596e9
JA
1866 ctx->poll_multi_file = true;
1867 }
1868
1869 /*
1870 * For fast devices, IO may have already completed. If it has, add
1871 * it to the front so we find it first.
1872 */
1873 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1874 list_add(&req->list, &ctx->poll_list);
1875 else
1876 list_add_tail(&req->list, &ctx->poll_list);
bdcd3eab
XW
1877
1878 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
1879 wq_has_sleeper(&ctx->sqo_wait))
1880 wake_up(&ctx->sqo_wait);
def596e9
JA
1881}
1882
3d6770fb 1883static void io_file_put(struct io_submit_state *state)
9a56a232 1884{
3d6770fb 1885 if (state->file) {
9a56a232
JA
1886 int diff = state->has_refs - state->used_refs;
1887
1888 if (diff)
1889 fput_many(state->file, diff);
1890 state->file = NULL;
1891 }
1892}
1893
1894/*
1895 * Get as many references to a file as we have IOs left in this submission,
1896 * assuming most submissions are for one file, or at least that each file
1897 * has more than one submission.
1898 */
8da11c19 1899static struct file *__io_file_get(struct io_submit_state *state, int fd)
9a56a232
JA
1900{
1901 if (!state)
1902 return fget(fd);
1903
1904 if (state->file) {
1905 if (state->fd == fd) {
1906 state->used_refs++;
1907 state->ios_left--;
1908 return state->file;
1909 }
3d6770fb 1910 io_file_put(state);
9a56a232
JA
1911 }
1912 state->file = fget_many(fd, state->ios_left);
1913 if (!state->file)
1914 return NULL;
1915
1916 state->fd = fd;
1917 state->has_refs = state->ios_left;
1918 state->used_refs = 1;
1919 state->ios_left--;
1920 return state->file;
1921}
1922
2b188cc1
JA
1923/*
1924 * If we tracked the file through the SCM inflight mechanism, we could support
1925 * any file. For now, just ensure that anything potentially problematic is done
1926 * inline.
1927 */
1928static bool io_file_supports_async(struct file *file)
1929{
1930 umode_t mode = file_inode(file)->i_mode;
1931
10d59345 1932 if (S_ISBLK(mode) || S_ISCHR(mode) || S_ISSOCK(mode))
2b188cc1
JA
1933 return true;
1934 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1935 return true;
1936
1937 return false;
1938}
1939
3529d8c2
JA
1940static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1941 bool force_nonblock)
2b188cc1 1942{
def596e9 1943 struct io_ring_ctx *ctx = req->ctx;
9adbd45d 1944 struct kiocb *kiocb = &req->rw.kiocb;
09bb8394
JA
1945 unsigned ioprio;
1946 int ret;
2b188cc1 1947
491381ce
JA
1948 if (S_ISREG(file_inode(req->file)->i_mode))
1949 req->flags |= REQ_F_ISREG;
1950
2b188cc1 1951 kiocb->ki_pos = READ_ONCE(sqe->off);
ba04291e
JA
1952 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
1953 req->flags |= REQ_F_CUR_POS;
1954 kiocb->ki_pos = req->file->f_pos;
1955 }
2b188cc1 1956 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
3e577dcd
PB
1957 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1958 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1959 if (unlikely(ret))
1960 return ret;
2b188cc1
JA
1961
1962 ioprio = READ_ONCE(sqe->ioprio);
1963 if (ioprio) {
1964 ret = ioprio_check_cap(ioprio);
1965 if (ret)
09bb8394 1966 return ret;
2b188cc1
JA
1967
1968 kiocb->ki_ioprio = ioprio;
1969 } else
1970 kiocb->ki_ioprio = get_current_ioprio();
1971
8449eeda 1972 /* don't allow async punt if RWF_NOWAIT was requested */
491381ce
JA
1973 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1974 (req->file->f_flags & O_NONBLOCK))
8449eeda
SB
1975 req->flags |= REQ_F_NOWAIT;
1976
1977 if (force_nonblock)
2b188cc1 1978 kiocb->ki_flags |= IOCB_NOWAIT;
8449eeda 1979
def596e9 1980 if (ctx->flags & IORING_SETUP_IOPOLL) {
def596e9
JA
1981 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1982 !kiocb->ki_filp->f_op->iopoll)
09bb8394 1983 return -EOPNOTSUPP;
2b188cc1 1984
def596e9
JA
1985 kiocb->ki_flags |= IOCB_HIPRI;
1986 kiocb->ki_complete = io_complete_rw_iopoll;
6873e0bd 1987 req->result = 0;
def596e9 1988 } else {
09bb8394
JA
1989 if (kiocb->ki_flags & IOCB_HIPRI)
1990 return -EINVAL;
def596e9
JA
1991 kiocb->ki_complete = io_complete_rw;
1992 }
9adbd45d 1993
3529d8c2
JA
1994 req->rw.addr = READ_ONCE(sqe->addr);
1995 req->rw.len = READ_ONCE(sqe->len);
9adbd45d
JA
1996 /* we own ->private, reuse it for the buffer index */
1997 req->rw.kiocb.private = (void *) (unsigned long)
3529d8c2 1998 READ_ONCE(sqe->buf_index);
2b188cc1 1999 return 0;
2b188cc1
JA
2000}
2001
2002static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2003{
2004 switch (ret) {
2005 case -EIOCBQUEUED:
2006 break;
2007 case -ERESTARTSYS:
2008 case -ERESTARTNOINTR:
2009 case -ERESTARTNOHAND:
2010 case -ERESTART_RESTARTBLOCK:
2011 /*
2012 * We can't just restart the syscall, since previously
2013 * submitted sqes may already be in progress. Just fail this
2014 * IO with EINTR.
2015 */
2016 ret = -EINTR;
2017 /* fall through */
2018 default:
2019 kiocb->ki_complete(kiocb, ret, 0);
2020 }
2021}
2022
bcaec089 2023static void kiocb_done(struct kiocb *kiocb, ssize_t ret, struct io_kiocb **nxt)
ba816ad6 2024{
ba04291e
JA
2025 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2026
2027 if (req->flags & REQ_F_CUR_POS)
2028 req->file->f_pos = kiocb->ki_pos;
bcaec089 2029 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
ba816ad6
JA
2030 *nxt = __io_complete_rw(kiocb, ret);
2031 else
2032 io_rw_done(kiocb, ret);
2033}
2034
9adbd45d 2035static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
7d009165 2036 struct iov_iter *iter)
edafccee 2037{
9adbd45d
JA
2038 struct io_ring_ctx *ctx = req->ctx;
2039 size_t len = req->rw.len;
edafccee
JA
2040 struct io_mapped_ubuf *imu;
2041 unsigned index, buf_index;
2042 size_t offset;
2043 u64 buf_addr;
2044
2045 /* attempt to use fixed buffers without having provided iovecs */
2046 if (unlikely(!ctx->user_bufs))
2047 return -EFAULT;
2048
9adbd45d 2049 buf_index = (unsigned long) req->rw.kiocb.private;
edafccee
JA
2050 if (unlikely(buf_index >= ctx->nr_user_bufs))
2051 return -EFAULT;
2052
2053 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2054 imu = &ctx->user_bufs[index];
9adbd45d 2055 buf_addr = req->rw.addr;
edafccee
JA
2056
2057 /* overflow */
2058 if (buf_addr + len < buf_addr)
2059 return -EFAULT;
2060 /* not inside the mapped region */
2061 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2062 return -EFAULT;
2063
2064 /*
2065 * May not be a start of buffer, set size appropriately
2066 * and advance us to the beginning.
2067 */
2068 offset = buf_addr - imu->ubuf;
2069 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
bd11b3a3
JA
2070
2071 if (offset) {
2072 /*
2073 * Don't use iov_iter_advance() here, as it's really slow for
2074 * using the latter parts of a big fixed buffer - it iterates
2075 * over each segment manually. We can cheat a bit here, because
2076 * we know that:
2077 *
2078 * 1) it's a BVEC iter, we set it up
2079 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2080 * first and last bvec
2081 *
2082 * So just find our index, and adjust the iterator afterwards.
2083 * If the offset is within the first bvec (or the whole first
2084 * bvec, just use iov_iter_advance(). This makes it easier
2085 * since we can just skip the first segment, which may not
2086 * be PAGE_SIZE aligned.
2087 */
2088 const struct bio_vec *bvec = imu->bvec;
2089
2090 if (offset <= bvec->bv_len) {
2091 iov_iter_advance(iter, offset);
2092 } else {
2093 unsigned long seg_skip;
2094
2095 /* skip first vec */
2096 offset -= bvec->bv_len;
2097 seg_skip = 1 + (offset >> PAGE_SHIFT);
2098
2099 iter->bvec = bvec + seg_skip;
2100 iter->nr_segs -= seg_skip;
99c79f66 2101 iter->count -= bvec->bv_len + offset;
bd11b3a3 2102 iter->iov_offset = offset & ~PAGE_MASK;
bd11b3a3
JA
2103 }
2104 }
2105
5e559561 2106 return len;
edafccee
JA
2107}
2108
cf6fd4bd
PB
2109static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
2110 struct iovec **iovec, struct iov_iter *iter)
2b188cc1 2111{
9adbd45d
JA
2112 void __user *buf = u64_to_user_ptr(req->rw.addr);
2113 size_t sqe_len = req->rw.len;
edafccee
JA
2114 u8 opcode;
2115
d625c6ee 2116 opcode = req->opcode;
7d009165 2117 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
edafccee 2118 *iovec = NULL;
9adbd45d 2119 return io_import_fixed(req, rw, iter);
edafccee 2120 }
2b188cc1 2121
9adbd45d
JA
2122 /* buffer index only valid with fixed read/write */
2123 if (req->rw.kiocb.private)
2124 return -EINVAL;
2125
3a6820f2
JA
2126 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2127 ssize_t ret;
2128 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2129 *iovec = NULL;
3a901598 2130 return ret < 0 ? ret : sqe_len;
3a6820f2
JA
2131 }
2132
f67676d1
JA
2133 if (req->io) {
2134 struct io_async_rw *iorw = &req->io->rw;
2135
2136 *iovec = iorw->iov;
2137 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
2138 if (iorw->iov == iorw->fast_iov)
2139 *iovec = NULL;
2140 return iorw->size;
2141 }
2142
2b188cc1 2143#ifdef CONFIG_COMPAT
cf6fd4bd 2144 if (req->ctx->compat)
2b188cc1
JA
2145 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
2146 iovec, iter);
2147#endif
2148
2149 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
2150}
2151
31b51510 2152/*
32960613
JA
2153 * For files that don't have ->read_iter() and ->write_iter(), handle them
2154 * by looping over ->read() or ->write() manually.
31b51510 2155 */
32960613
JA
2156static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2157 struct iov_iter *iter)
2158{
2159 ssize_t ret = 0;
2160
2161 /*
2162 * Don't support polled IO through this interface, and we can't
2163 * support non-blocking either. For the latter, this just causes
2164 * the kiocb to be handled from an async context.
2165 */
2166 if (kiocb->ki_flags & IOCB_HIPRI)
2167 return -EOPNOTSUPP;
2168 if (kiocb->ki_flags & IOCB_NOWAIT)
2169 return -EAGAIN;
2170
2171 while (iov_iter_count(iter)) {
311ae9e1 2172 struct iovec iovec;
32960613
JA
2173 ssize_t nr;
2174
311ae9e1
PB
2175 if (!iov_iter_is_bvec(iter)) {
2176 iovec = iov_iter_iovec(iter);
2177 } else {
2178 /* fixed buffers import bvec */
2179 iovec.iov_base = kmap(iter->bvec->bv_page)
2180 + iter->iov_offset;
2181 iovec.iov_len = min(iter->count,
2182 iter->bvec->bv_len - iter->iov_offset);
2183 }
2184
32960613
JA
2185 if (rw == READ) {
2186 nr = file->f_op->read(file, iovec.iov_base,
2187 iovec.iov_len, &kiocb->ki_pos);
2188 } else {
2189 nr = file->f_op->write(file, iovec.iov_base,
2190 iovec.iov_len, &kiocb->ki_pos);
2191 }
2192
311ae9e1
PB
2193 if (iov_iter_is_bvec(iter))
2194 kunmap(iter->bvec->bv_page);
2195
32960613
JA
2196 if (nr < 0) {
2197 if (!ret)
2198 ret = nr;
2199 break;
2200 }
2201 ret += nr;
2202 if (nr != iovec.iov_len)
2203 break;
2204 iov_iter_advance(iter, nr);
2205 }
2206
2207 return ret;
2208}
2209
b7bb4f7d 2210static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
f67676d1
JA
2211 struct iovec *iovec, struct iovec *fast_iov,
2212 struct iov_iter *iter)
2213{
2214 req->io->rw.nr_segs = iter->nr_segs;
2215 req->io->rw.size = io_size;
2216 req->io->rw.iov = iovec;
2217 if (!req->io->rw.iov) {
2218 req->io->rw.iov = req->io->rw.fast_iov;
2219 memcpy(req->io->rw.iov, fast_iov,
2220 sizeof(struct iovec) * iter->nr_segs);
99bc4c38
PB
2221 } else {
2222 req->flags |= REQ_F_NEED_CLEANUP;
f67676d1
JA
2223 }
2224}
2225
b7bb4f7d 2226static int io_alloc_async_ctx(struct io_kiocb *req)
f67676d1 2227{
d3656344
JA
2228 if (!io_op_defs[req->opcode].async_ctx)
2229 return 0;
f67676d1 2230 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
06b76d44 2231 return req->io == NULL;
b7bb4f7d
JA
2232}
2233
b7bb4f7d
JA
2234static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
2235 struct iovec *iovec, struct iovec *fast_iov,
2236 struct iov_iter *iter)
2237{
980ad263 2238 if (!io_op_defs[req->opcode].async_ctx)
74566df3 2239 return 0;
5d204bcf
JA
2240 if (!req->io) {
2241 if (io_alloc_async_ctx(req))
2242 return -ENOMEM;
b7bb4f7d 2243
5d204bcf
JA
2244 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
2245 }
b7bb4f7d 2246 return 0;
f67676d1
JA
2247}
2248
3529d8c2
JA
2249static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2250 bool force_nonblock)
f67676d1 2251{
3529d8c2
JA
2252 struct io_async_ctx *io;
2253 struct iov_iter iter;
f67676d1
JA
2254 ssize_t ret;
2255
3529d8c2
JA
2256 ret = io_prep_rw(req, sqe, force_nonblock);
2257 if (ret)
2258 return ret;
f67676d1 2259
3529d8c2
JA
2260 if (unlikely(!(req->file->f_mode & FMODE_READ)))
2261 return -EBADF;
f67676d1 2262
5f798bea
PB
2263 /* either don't need iovec imported or already have it */
2264 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
3529d8c2
JA
2265 return 0;
2266
2267 io = req->io;
2268 io->rw.iov = io->rw.fast_iov;
2269 req->io = NULL;
2270 ret = io_import_iovec(READ, req, &io->rw.iov, &iter);
2271 req->io = io;
2272 if (ret < 0)
2273 return ret;
2274
2275 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2276 return 0;
f67676d1
JA
2277}
2278
267bc904 2279static int io_read(struct io_kiocb *req, struct io_kiocb **nxt,
8358e3a8 2280 bool force_nonblock)
2b188cc1
JA
2281{
2282 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
9adbd45d 2283 struct kiocb *kiocb = &req->rw.kiocb;
2b188cc1 2284 struct iov_iter iter;
31b51510 2285 size_t iov_count;
f67676d1 2286 ssize_t io_size, ret;
2b188cc1 2287
3529d8c2 2288 ret = io_import_iovec(READ, req, &iovec, &iter);
06b76d44
JA
2289 if (ret < 0)
2290 return ret;
2b188cc1 2291
fd6c2e4c
JA
2292 /* Ensure we clear previously set non-block flag */
2293 if (!force_nonblock)
29de5f6a 2294 kiocb->ki_flags &= ~IOCB_NOWAIT;
fd6c2e4c 2295
797f3f53 2296 req->result = 0;
f67676d1 2297 io_size = ret;
9e645e11 2298 if (req->flags & REQ_F_LINK)
f67676d1
JA
2299 req->result = io_size;
2300
2301 /*
2302 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2303 * we know to async punt it even if it was opened O_NONBLOCK
2304 */
29de5f6a 2305 if (force_nonblock && !io_file_supports_async(req->file))
f67676d1 2306 goto copy_iov;
9e645e11 2307
31b51510 2308 iov_count = iov_iter_count(&iter);
9adbd45d 2309 ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
2b188cc1
JA
2310 if (!ret) {
2311 ssize_t ret2;
2312
9adbd45d
JA
2313 if (req->file->f_op->read_iter)
2314 ret2 = call_read_iter(req->file, kiocb, &iter);
32960613 2315 else
9adbd45d 2316 ret2 = loop_rw_iter(READ, req->file, kiocb, &iter);
32960613 2317
9d93a3f5 2318 /* Catch -EAGAIN return for forced non-blocking submission */
f67676d1 2319 if (!force_nonblock || ret2 != -EAGAIN) {
bcaec089 2320 kiocb_done(kiocb, ret2, nxt);
f67676d1
JA
2321 } else {
2322copy_iov:
b7bb4f7d 2323 ret = io_setup_async_rw(req, io_size, iovec,
f67676d1
JA
2324 inline_vecs, &iter);
2325 if (ret)
2326 goto out_free;
29de5f6a
JA
2327 /* any defer here is final, must blocking retry */
2328 if (!(req->flags & REQ_F_NOWAIT))
2329 req->flags |= REQ_F_MUST_PUNT;
f67676d1
JA
2330 return -EAGAIN;
2331 }
2b188cc1 2332 }
f67676d1 2333out_free:
1e95081c 2334 kfree(iovec);
99bc4c38 2335 req->flags &= ~REQ_F_NEED_CLEANUP;
2b188cc1
JA
2336 return ret;
2337}
2338
3529d8c2
JA
2339static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2340 bool force_nonblock)
f67676d1 2341{
3529d8c2
JA
2342 struct io_async_ctx *io;
2343 struct iov_iter iter;
f67676d1
JA
2344 ssize_t ret;
2345
3529d8c2
JA
2346 ret = io_prep_rw(req, sqe, force_nonblock);
2347 if (ret)
2348 return ret;
f67676d1 2349
3529d8c2
JA
2350 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
2351 return -EBADF;
f67676d1 2352
5f798bea
PB
2353 /* either don't need iovec imported or already have it */
2354 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
3529d8c2
JA
2355 return 0;
2356
2357 io = req->io;
2358 io->rw.iov = io->rw.fast_iov;
2359 req->io = NULL;
2360 ret = io_import_iovec(WRITE, req, &io->rw.iov, &iter);
2361 req->io = io;
2362 if (ret < 0)
2363 return ret;
2364
2365 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2366 return 0;
f67676d1
JA
2367}
2368
267bc904 2369static int io_write(struct io_kiocb *req, struct io_kiocb **nxt,
8358e3a8 2370 bool force_nonblock)
2b188cc1
JA
2371{
2372 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
9adbd45d 2373 struct kiocb *kiocb = &req->rw.kiocb;
2b188cc1 2374 struct iov_iter iter;
31b51510 2375 size_t iov_count;
f67676d1 2376 ssize_t ret, io_size;
2b188cc1 2377
3529d8c2 2378 ret = io_import_iovec(WRITE, req, &iovec, &iter);
06b76d44
JA
2379 if (ret < 0)
2380 return ret;
2b188cc1 2381
fd6c2e4c
JA
2382 /* Ensure we clear previously set non-block flag */
2383 if (!force_nonblock)
9adbd45d 2384 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
fd6c2e4c 2385
797f3f53 2386 req->result = 0;
f67676d1 2387 io_size = ret;
9e645e11 2388 if (req->flags & REQ_F_LINK)
f67676d1 2389 req->result = io_size;
9e645e11 2390
f67676d1
JA
2391 /*
2392 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2393 * we know to async punt it even if it was opened O_NONBLOCK
2394 */
29de5f6a 2395 if (force_nonblock && !io_file_supports_async(req->file))
f67676d1 2396 goto copy_iov;
31b51510 2397
10d59345
JA
2398 /* file path doesn't support NOWAIT for non-direct_IO */
2399 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
2400 (req->flags & REQ_F_ISREG))
f67676d1 2401 goto copy_iov;
31b51510 2402
f67676d1 2403 iov_count = iov_iter_count(&iter);
9adbd45d 2404 ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
2b188cc1 2405 if (!ret) {
9bf7933f
RP
2406 ssize_t ret2;
2407
2b188cc1
JA
2408 /*
2409 * Open-code file_start_write here to grab freeze protection,
2410 * which will be released by another thread in
2411 * io_complete_rw(). Fool lockdep by telling it the lock got
2412 * released so that it doesn't complain about the held lock when
2413 * we return to userspace.
2414 */
491381ce 2415 if (req->flags & REQ_F_ISREG) {
9adbd45d 2416 __sb_start_write(file_inode(req->file)->i_sb,
2b188cc1 2417 SB_FREEZE_WRITE, true);
9adbd45d 2418 __sb_writers_release(file_inode(req->file)->i_sb,
2b188cc1
JA
2419 SB_FREEZE_WRITE);
2420 }
2421 kiocb->ki_flags |= IOCB_WRITE;
9bf7933f 2422
9adbd45d
JA
2423 if (req->file->f_op->write_iter)
2424 ret2 = call_write_iter(req->file, kiocb, &iter);
32960613 2425 else
9adbd45d 2426 ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
faac996c
JA
2427 /*
2428 * Raw bdev writes will -EOPNOTSUPP for IOCB_NOWAIT. Just
2429 * retry them without IOCB_NOWAIT.
2430 */
2431 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
2432 ret2 = -EAGAIN;
f67676d1 2433 if (!force_nonblock || ret2 != -EAGAIN) {
bcaec089 2434 kiocb_done(kiocb, ret2, nxt);
f67676d1
JA
2435 } else {
2436copy_iov:
b7bb4f7d 2437 ret = io_setup_async_rw(req, io_size, iovec,
f67676d1
JA
2438 inline_vecs, &iter);
2439 if (ret)
2440 goto out_free;
29de5f6a
JA
2441 /* any defer here is final, must blocking retry */
2442 req->flags |= REQ_F_MUST_PUNT;
f67676d1
JA
2443 return -EAGAIN;
2444 }
2b188cc1 2445 }
31b51510 2446out_free:
99bc4c38 2447 req->flags &= ~REQ_F_NEED_CLEANUP;
1e95081c 2448 kfree(iovec);
2b188cc1
JA
2449 return ret;
2450}
2451
7d67af2c
PB
2452static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2453{
2454 struct io_splice* sp = &req->splice;
2455 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
2456 int ret;
2457
2458 if (req->flags & REQ_F_NEED_CLEANUP)
2459 return 0;
2460
2461 sp->file_in = NULL;
2462 sp->off_in = READ_ONCE(sqe->splice_off_in);
2463 sp->off_out = READ_ONCE(sqe->off);
2464 sp->len = READ_ONCE(sqe->len);
2465 sp->flags = READ_ONCE(sqe->splice_flags);
2466
2467 if (unlikely(sp->flags & ~valid_flags))
2468 return -EINVAL;
2469
2470 ret = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in), &sp->file_in,
2471 (sp->flags & SPLICE_F_FD_IN_FIXED));
2472 if (ret)
2473 return ret;
2474 req->flags |= REQ_F_NEED_CLEANUP;
2475
2476 if (!S_ISREG(file_inode(sp->file_in)->i_mode))
2477 req->work.flags |= IO_WQ_WORK_UNBOUND;
2478
2479 return 0;
2480}
2481
2482static bool io_splice_punt(struct file *file)
2483{
2484 if (get_pipe_info(file))
2485 return false;
2486 if (!io_file_supports_async(file))
2487 return true;
2488 return !(file->f_mode & O_NONBLOCK);
2489}
2490
2491static int io_splice(struct io_kiocb *req, struct io_kiocb **nxt,
2492 bool force_nonblock)
2493{
2494 struct io_splice *sp = &req->splice;
2495 struct file *in = sp->file_in;
2496 struct file *out = sp->file_out;
2497 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
2498 loff_t *poff_in, *poff_out;
2499 long ret;
2500
2501 if (force_nonblock) {
2502 if (io_splice_punt(in) || io_splice_punt(out))
2503 return -EAGAIN;
2504 flags |= SPLICE_F_NONBLOCK;
2505 }
2506
2507 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
2508 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
2509 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
2510 if (force_nonblock && ret == -EAGAIN)
2511 return -EAGAIN;
2512
2513 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
2514 req->flags &= ~REQ_F_NEED_CLEANUP;
2515
2516 io_cqring_add_event(req, ret);
2517 if (ret != sp->len)
2518 req_set_fail_links(req);
2519 io_put_req_find_next(req, nxt);
2520 return 0;
2521}
2522
2b188cc1
JA
2523/*
2524 * IORING_OP_NOP just posts a completion event, nothing else.
2525 */
78e19bbe 2526static int io_nop(struct io_kiocb *req)
2b188cc1
JA
2527{
2528 struct io_ring_ctx *ctx = req->ctx;
2b188cc1 2529
def596e9
JA
2530 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2531 return -EINVAL;
2532
78e19bbe 2533 io_cqring_add_event(req, 0);
e65ef56d 2534 io_put_req(req);
2b188cc1
JA
2535 return 0;
2536}
2537
3529d8c2 2538static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
c992fe29 2539{
6b06314c 2540 struct io_ring_ctx *ctx = req->ctx;
c992fe29 2541
09bb8394
JA
2542 if (!req->file)
2543 return -EBADF;
c992fe29 2544
6b06314c 2545 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
def596e9 2546 return -EINVAL;
edafccee 2547 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
c992fe29
CH
2548 return -EINVAL;
2549
8ed8d3c3
JA
2550 req->sync.flags = READ_ONCE(sqe->fsync_flags);
2551 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
2552 return -EINVAL;
2553
2554 req->sync.off = READ_ONCE(sqe->off);
2555 req->sync.len = READ_ONCE(sqe->len);
c992fe29
CH
2556 return 0;
2557}
2558
8ed8d3c3
JA
2559static bool io_req_cancelled(struct io_kiocb *req)
2560{
2561 if (req->work.flags & IO_WQ_WORK_CANCEL) {
2562 req_set_fail_links(req);
2563 io_cqring_add_event(req, -ECANCELED);
2564 io_put_req(req);
2565 return true;
2566 }
2567
2568 return false;
2569}
2570
78912934
JA
2571static void io_link_work_cb(struct io_wq_work **workptr)
2572{
2573 struct io_wq_work *work = *workptr;
2574 struct io_kiocb *link = work->data;
2575
2576 io_queue_linked_timeout(link);
5eae8619 2577 io_wq_submit_work(workptr);
78912934
JA
2578}
2579
2580static void io_wq_assign_next(struct io_wq_work **workptr, struct io_kiocb *nxt)
2581{
2582 struct io_kiocb *link;
2583
deb6dc05 2584 io_prep_next_work(nxt, &link);
78912934
JA
2585 *workptr = &nxt->work;
2586 if (link) {
78912934
JA
2587 nxt->work.func = io_link_work_cb;
2588 nxt->work.data = link;
2589 }
2590}
2591
5ea62161 2592static void __io_fsync(struct io_kiocb *req, struct io_kiocb **nxt)
8ed8d3c3 2593{
8ed8d3c3 2594 loff_t end = req->sync.off + req->sync.len;
8ed8d3c3
JA
2595 int ret;
2596
9adbd45d 2597 ret = vfs_fsync_range(req->file, req->sync.off,
8ed8d3c3
JA
2598 end > 0 ? end : LLONG_MAX,
2599 req->sync.flags & IORING_FSYNC_DATASYNC);
2600 if (ret < 0)
2601 req_set_fail_links(req);
2602 io_cqring_add_event(req, ret);
5ea62161
PB
2603 io_put_req_find_next(req, nxt);
2604}
2605
2606static void io_fsync_finish(struct io_wq_work **workptr)
2607{
2608 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2609 struct io_kiocb *nxt = NULL;
2610
2611 if (io_req_cancelled(req))
2612 return;
2613 __io_fsync(req, &nxt);
8ed8d3c3 2614 if (nxt)
78912934 2615 io_wq_assign_next(workptr, nxt);
8ed8d3c3
JA
2616}
2617
fc4df999
JA
2618static int io_fsync(struct io_kiocb *req, struct io_kiocb **nxt,
2619 bool force_nonblock)
c992fe29 2620{
c992fe29 2621 /* fsync always requires a blocking context */
8ed8d3c3
JA
2622 if (force_nonblock) {
2623 io_put_req(req);
2624 req->work.func = io_fsync_finish;
c992fe29 2625 return -EAGAIN;
8ed8d3c3 2626 }
5ea62161 2627 __io_fsync(req, nxt);
c992fe29
CH
2628 return 0;
2629}
2630
5ea62161 2631static void __io_fallocate(struct io_kiocb *req, struct io_kiocb **nxt)
8ed8d3c3 2632{
8ed8d3c3
JA
2633 int ret;
2634
7fbeb95d
PB
2635 if (io_req_cancelled(req))
2636 return;
2637
d63d1b5e
JA
2638 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
2639 req->sync.len);
8ed8d3c3
JA
2640 if (ret < 0)
2641 req_set_fail_links(req);
2642 io_cqring_add_event(req, ret);
5ea62161
PB
2643 io_put_req_find_next(req, nxt);
2644}
2645
2646static void io_fallocate_finish(struct io_wq_work **workptr)
2647{
2648 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2649 struct io_kiocb *nxt = NULL;
2650
2651 __io_fallocate(req, &nxt);
8ed8d3c3 2652 if (nxt)
78912934 2653 io_wq_assign_next(workptr, nxt);
5d17b4a4
JA
2654}
2655
d63d1b5e
JA
2656static int io_fallocate_prep(struct io_kiocb *req,
2657 const struct io_uring_sqe *sqe)
2658{
2659 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
2660 return -EINVAL;
2661
2662 req->sync.off = READ_ONCE(sqe->off);
2663 req->sync.len = READ_ONCE(sqe->addr);
2664 req->sync.mode = READ_ONCE(sqe->len);
2665 return 0;
2666}
2667
2668static int io_fallocate(struct io_kiocb *req, struct io_kiocb **nxt,
2669 bool force_nonblock)
5d17b4a4 2670{
d63d1b5e 2671 /* fallocate always requiring blocking context */
8ed8d3c3
JA
2672 if (force_nonblock) {
2673 io_put_req(req);
d63d1b5e 2674 req->work.func = io_fallocate_finish;
5d17b4a4 2675 return -EAGAIN;
8ed8d3c3 2676 }
5d17b4a4 2677
5ea62161 2678 __io_fallocate(req, nxt);
5d17b4a4
JA
2679 return 0;
2680}
2681
15b71abe 2682static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
b7bb4f7d 2683{
f8748881 2684 const char __user *fname;
15b71abe 2685 int ret;
b7bb4f7d 2686
15b71abe
JA
2687 if (sqe->ioprio || sqe->buf_index)
2688 return -EINVAL;
cf3040ca
JA
2689 if (sqe->flags & IOSQE_FIXED_FILE)
2690 return -EBADF;
0bdbdd08
PB
2691 if (req->flags & REQ_F_NEED_CLEANUP)
2692 return 0;
03b1230c 2693
15b71abe 2694 req->open.dfd = READ_ONCE(sqe->fd);
c12cedf2 2695 req->open.how.mode = READ_ONCE(sqe->len);
f8748881 2696 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
c12cedf2 2697 req->open.how.flags = READ_ONCE(sqe->open_flags);
3529d8c2 2698
f8748881 2699 req->open.filename = getname(fname);
15b71abe
JA
2700 if (IS_ERR(req->open.filename)) {
2701 ret = PTR_ERR(req->open.filename);
2702 req->open.filename = NULL;
2703 return ret;
2704 }
3529d8c2 2705
8fef80bf 2706 req->flags |= REQ_F_NEED_CLEANUP;
15b71abe 2707 return 0;
03b1230c
JA
2708}
2709
cebdb986 2710static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
aa1fa28f 2711{
cebdb986
JA
2712 struct open_how __user *how;
2713 const char __user *fname;
2714 size_t len;
0fa03c62
JA
2715 int ret;
2716
cebdb986 2717 if (sqe->ioprio || sqe->buf_index)
0fa03c62 2718 return -EINVAL;
cf3040ca
JA
2719 if (sqe->flags & IOSQE_FIXED_FILE)
2720 return -EBADF;
0bdbdd08
PB
2721 if (req->flags & REQ_F_NEED_CLEANUP)
2722 return 0;
0fa03c62 2723
cebdb986
JA
2724 req->open.dfd = READ_ONCE(sqe->fd);
2725 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2726 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2727 len = READ_ONCE(sqe->len);
0fa03c62 2728
cebdb986
JA
2729 if (len < OPEN_HOW_SIZE_VER0)
2730 return -EINVAL;
3529d8c2 2731
cebdb986
JA
2732 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
2733 len);
2734 if (ret)
2735 return ret;
3529d8c2 2736
cebdb986
JA
2737 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
2738 req->open.how.flags |= O_LARGEFILE;
0fa03c62 2739
cebdb986
JA
2740 req->open.filename = getname(fname);
2741 if (IS_ERR(req->open.filename)) {
2742 ret = PTR_ERR(req->open.filename);
2743 req->open.filename = NULL;
2744 return ret;
2745 }
2746
8fef80bf 2747 req->flags |= REQ_F_NEED_CLEANUP;
cebdb986
JA
2748 return 0;
2749}
2750
2751static int io_openat2(struct io_kiocb *req, struct io_kiocb **nxt,
2752 bool force_nonblock)
15b71abe
JA
2753{
2754 struct open_flags op;
15b71abe
JA
2755 struct file *file;
2756 int ret;
2757
f86cd20c 2758 if (force_nonblock)
15b71abe 2759 return -EAGAIN;
15b71abe 2760
cebdb986 2761 ret = build_open_flags(&req->open.how, &op);
15b71abe
JA
2762 if (ret)
2763 goto err;
2764
cebdb986 2765 ret = get_unused_fd_flags(req->open.how.flags);
15b71abe
JA
2766 if (ret < 0)
2767 goto err;
2768
2769 file = do_filp_open(req->open.dfd, req->open.filename, &op);
2770 if (IS_ERR(file)) {
2771 put_unused_fd(ret);
2772 ret = PTR_ERR(file);
2773 } else {
2774 fsnotify_open(file);
2775 fd_install(ret, file);
2776 }
2777err:
2778 putname(req->open.filename);
8fef80bf 2779 req->flags &= ~REQ_F_NEED_CLEANUP;
15b71abe
JA
2780 if (ret < 0)
2781 req_set_fail_links(req);
2782 io_cqring_add_event(req, ret);
2783 io_put_req_find_next(req, nxt);
2784 return 0;
2785}
2786
cebdb986
JA
2787static int io_openat(struct io_kiocb *req, struct io_kiocb **nxt,
2788 bool force_nonblock)
2789{
2790 req->open.how = build_open_how(req->open.how.flags, req->open.how.mode);
2791 return io_openat2(req, nxt, force_nonblock);
2792}
2793
3e4827b0
JA
2794static int io_epoll_ctl_prep(struct io_kiocb *req,
2795 const struct io_uring_sqe *sqe)
2796{
2797#if defined(CONFIG_EPOLL)
2798 if (sqe->ioprio || sqe->buf_index)
2799 return -EINVAL;
2800
2801 req->epoll.epfd = READ_ONCE(sqe->fd);
2802 req->epoll.op = READ_ONCE(sqe->len);
2803 req->epoll.fd = READ_ONCE(sqe->off);
2804
2805 if (ep_op_has_event(req->epoll.op)) {
2806 struct epoll_event __user *ev;
2807
2808 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
2809 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
2810 return -EFAULT;
2811 }
2812
2813 return 0;
2814#else
2815 return -EOPNOTSUPP;
2816#endif
2817}
2818
2819static int io_epoll_ctl(struct io_kiocb *req, struct io_kiocb **nxt,
2820 bool force_nonblock)
2821{
2822#if defined(CONFIG_EPOLL)
2823 struct io_epoll *ie = &req->epoll;
2824 int ret;
2825
2826 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
2827 if (force_nonblock && ret == -EAGAIN)
2828 return -EAGAIN;
2829
2830 if (ret < 0)
2831 req_set_fail_links(req);
2832 io_cqring_add_event(req, ret);
2833 io_put_req_find_next(req, nxt);
2834 return 0;
2835#else
2836 return -EOPNOTSUPP;
2837#endif
2838}
2839
c1ca757b
JA
2840static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2841{
2842#if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
2843 if (sqe->ioprio || sqe->buf_index || sqe->off)
2844 return -EINVAL;
2845
2846 req->madvise.addr = READ_ONCE(sqe->addr);
2847 req->madvise.len = READ_ONCE(sqe->len);
2848 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
2849 return 0;
2850#else
2851 return -EOPNOTSUPP;
2852#endif
2853}
2854
2855static int io_madvise(struct io_kiocb *req, struct io_kiocb **nxt,
2856 bool force_nonblock)
2857{
2858#if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
2859 struct io_madvise *ma = &req->madvise;
2860 int ret;
2861
2862 if (force_nonblock)
2863 return -EAGAIN;
2864
2865 ret = do_madvise(ma->addr, ma->len, ma->advice);
2866 if (ret < 0)
2867 req_set_fail_links(req);
2868 io_cqring_add_event(req, ret);
2869 io_put_req_find_next(req, nxt);
2870 return 0;
2871#else
2872 return -EOPNOTSUPP;
2873#endif
2874}
2875
4840e418
JA
2876static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2877{
2878 if (sqe->ioprio || sqe->buf_index || sqe->addr)
2879 return -EINVAL;
2880
2881 req->fadvise.offset = READ_ONCE(sqe->off);
2882 req->fadvise.len = READ_ONCE(sqe->len);
2883 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
2884 return 0;
2885}
2886
2887static int io_fadvise(struct io_kiocb *req, struct io_kiocb **nxt,
2888 bool force_nonblock)
2889{
2890 struct io_fadvise *fa = &req->fadvise;
2891 int ret;
2892
3e69426d
JA
2893 if (force_nonblock) {
2894 switch (fa->advice) {
2895 case POSIX_FADV_NORMAL:
2896 case POSIX_FADV_RANDOM:
2897 case POSIX_FADV_SEQUENTIAL:
2898 break;
2899 default:
2900 return -EAGAIN;
2901 }
2902 }
4840e418
JA
2903
2904 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
2905 if (ret < 0)
2906 req_set_fail_links(req);
2907 io_cqring_add_event(req, ret);
2908 io_put_req_find_next(req, nxt);
2909 return 0;
2910}
2911
eddc7ef5
JA
2912static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2913{
f8748881 2914 const char __user *fname;
eddc7ef5
JA
2915 unsigned lookup_flags;
2916 int ret;
2917
2918 if (sqe->ioprio || sqe->buf_index)
2919 return -EINVAL;
cf3040ca
JA
2920 if (sqe->flags & IOSQE_FIXED_FILE)
2921 return -EBADF;
0bdbdd08
PB
2922 if (req->flags & REQ_F_NEED_CLEANUP)
2923 return 0;
eddc7ef5
JA
2924
2925 req->open.dfd = READ_ONCE(sqe->fd);
2926 req->open.mask = READ_ONCE(sqe->len);
f8748881 2927 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
eddc7ef5 2928 req->open.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
c12cedf2 2929 req->open.how.flags = READ_ONCE(sqe->statx_flags);
eddc7ef5 2930
c12cedf2 2931 if (vfs_stat_set_lookup_flags(&lookup_flags, req->open.how.flags))
eddc7ef5
JA
2932 return -EINVAL;
2933
f8748881 2934 req->open.filename = getname_flags(fname, lookup_flags, NULL);
eddc7ef5
JA
2935 if (IS_ERR(req->open.filename)) {
2936 ret = PTR_ERR(req->open.filename);
2937 req->open.filename = NULL;
2938 return ret;
2939 }
2940
8fef80bf 2941 req->flags |= REQ_F_NEED_CLEANUP;
eddc7ef5
JA
2942 return 0;
2943}
2944
2945static int io_statx(struct io_kiocb *req, struct io_kiocb **nxt,
2946 bool force_nonblock)
2947{
2948 struct io_open *ctx = &req->open;
2949 unsigned lookup_flags;
2950 struct path path;
2951 struct kstat stat;
2952 int ret;
2953
2954 if (force_nonblock)
2955 return -EAGAIN;
2956
c12cedf2 2957 if (vfs_stat_set_lookup_flags(&lookup_flags, ctx->how.flags))
eddc7ef5
JA
2958 return -EINVAL;
2959
2960retry:
2961 /* filename_lookup() drops it, keep a reference */
2962 ctx->filename->refcnt++;
2963
2964 ret = filename_lookup(ctx->dfd, ctx->filename, lookup_flags, &path,
2965 NULL);
2966 if (ret)
2967 goto err;
2968
c12cedf2 2969 ret = vfs_getattr(&path, &stat, ctx->mask, ctx->how.flags);
eddc7ef5
JA
2970 path_put(&path);
2971 if (retry_estale(ret, lookup_flags)) {
2972 lookup_flags |= LOOKUP_REVAL;
2973 goto retry;
2974 }
2975 if (!ret)
2976 ret = cp_statx(&stat, ctx->buffer);
2977err:
2978 putname(ctx->filename);
8fef80bf 2979 req->flags &= ~REQ_F_NEED_CLEANUP;
eddc7ef5
JA
2980 if (ret < 0)
2981 req_set_fail_links(req);
2982 io_cqring_add_event(req, ret);
2983 io_put_req_find_next(req, nxt);
2984 return 0;
2985}
2986
b5dba59e
JA
2987static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2988{
2989 /*
2990 * If we queue this for async, it must not be cancellable. That would
2991 * leave the 'file' in an undeterminate state.
2992 */
2993 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
2994
2995 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
2996 sqe->rw_flags || sqe->buf_index)
2997 return -EINVAL;
2998 if (sqe->flags & IOSQE_FIXED_FILE)
cf3040ca 2999 return -EBADF;
b5dba59e
JA
3000
3001 req->close.fd = READ_ONCE(sqe->fd);
3002 if (req->file->f_op == &io_uring_fops ||
b14cca0c 3003 req->close.fd == req->ctx->ring_fd)
b5dba59e
JA
3004 return -EBADF;
3005
3006 return 0;
3007}
3008
a93b3331
PB
3009/* only called when __close_fd_get_file() is done */
3010static void __io_close_finish(struct io_kiocb *req, struct io_kiocb **nxt)
3011{
3012 int ret;
3013
3014 ret = filp_close(req->close.put_file, req->work.files);
3015 if (ret < 0)
3016 req_set_fail_links(req);
3017 io_cqring_add_event(req, ret);
3018 fput(req->close.put_file);
3019 io_put_req_find_next(req, nxt);
3020}
3021
b5dba59e
JA
3022static void io_close_finish(struct io_wq_work **workptr)
3023{
3024 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3025 struct io_kiocb *nxt = NULL;
3026
7fbeb95d 3027 /* not cancellable, don't do io_req_cancelled() */
a93b3331 3028 __io_close_finish(req, &nxt);
b5dba59e
JA
3029 if (nxt)
3030 io_wq_assign_next(workptr, nxt);
3031}
3032
3033static int io_close(struct io_kiocb *req, struct io_kiocb **nxt,
3034 bool force_nonblock)
3035{
3036 int ret;
3037
3038 req->close.put_file = NULL;
3039 ret = __close_fd_get_file(req->close.fd, &req->close.put_file);
3040 if (ret < 0)
3041 return ret;
3042
3043 /* if the file has a flush method, be safe and punt to async */
f86cd20c 3044 if (req->close.put_file->f_op->flush && !io_wq_current_is_worker())
b5dba59e 3045 goto eagain;
b5dba59e
JA
3046
3047 /*
3048 * No ->flush(), safely close from here and just punt the
3049 * fput() to async context.
3050 */
a93b3331
PB
3051 __io_close_finish(req, nxt);
3052 return 0;
b5dba59e
JA
3053eagain:
3054 req->work.func = io_close_finish;
1a417f4e
JA
3055 /*
3056 * Do manual async queue here to avoid grabbing files - we don't
3057 * need the files, and it'll cause io_close_finish() to close
3058 * the file again and cause a double CQE entry for this request
3059 */
3060 io_queue_async_work(req);
3061 return 0;
b5dba59e
JA
3062}
3063
3529d8c2 3064static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5d17b4a4
JA
3065{
3066 struct io_ring_ctx *ctx = req->ctx;
5d17b4a4
JA
3067
3068 if (!req->file)
3069 return -EBADF;
5d17b4a4
JA
3070
3071 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3072 return -EINVAL;
3073 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3074 return -EINVAL;
3075
8ed8d3c3
JA
3076 req->sync.off = READ_ONCE(sqe->off);
3077 req->sync.len = READ_ONCE(sqe->len);
3078 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
8ed8d3c3
JA
3079 return 0;
3080}
3081
5ea62161 3082static void __io_sync_file_range(struct io_kiocb *req, struct io_kiocb **nxt)
8ed8d3c3 3083{
8ed8d3c3
JA
3084 int ret;
3085
9adbd45d 3086 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
8ed8d3c3
JA
3087 req->sync.flags);
3088 if (ret < 0)
3089 req_set_fail_links(req);
3090 io_cqring_add_event(req, ret);
5ea62161
PB
3091 io_put_req_find_next(req, nxt);
3092}
3093
3094
3095static void io_sync_file_range_finish(struct io_wq_work **workptr)
3096{
3097 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3098 struct io_kiocb *nxt = NULL;
3099
3100 if (io_req_cancelled(req))
3101 return;
3102 __io_sync_file_range(req, &nxt);
8ed8d3c3 3103 if (nxt)
78912934 3104 io_wq_assign_next(workptr, nxt);
5d17b4a4
JA
3105}
3106
fc4df999 3107static int io_sync_file_range(struct io_kiocb *req, struct io_kiocb **nxt,
5d17b4a4
JA
3108 bool force_nonblock)
3109{
5d17b4a4 3110 /* sync_file_range always requires a blocking context */
8ed8d3c3
JA
3111 if (force_nonblock) {
3112 io_put_req(req);
3113 req->work.func = io_sync_file_range_finish;
5d17b4a4 3114 return -EAGAIN;
8ed8d3c3 3115 }
5d17b4a4 3116
5ea62161 3117 __io_sync_file_range(req, nxt);
5d17b4a4
JA
3118 return 0;
3119}
3120
02d27d89
PB
3121static int io_setup_async_msg(struct io_kiocb *req,
3122 struct io_async_msghdr *kmsg)
3123{
3124 if (req->io)
3125 return -EAGAIN;
3126 if (io_alloc_async_ctx(req)) {
3127 if (kmsg->iov != kmsg->fast_iov)
3128 kfree(kmsg->iov);
3129 return -ENOMEM;
3130 }
3131 req->flags |= REQ_F_NEED_CLEANUP;
3132 memcpy(&req->io->msg, kmsg, sizeof(*kmsg));
3133 return -EAGAIN;
3134}
3135
3529d8c2 3136static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
03b1230c 3137{
0fa03c62 3138#if defined(CONFIG_NET)
e47293fd 3139 struct io_sr_msg *sr = &req->sr_msg;
3529d8c2 3140 struct io_async_ctx *io = req->io;
99bc4c38 3141 int ret;
03b1230c 3142
e47293fd
JA
3143 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3144 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
fddaface 3145 sr->len = READ_ONCE(sqe->len);
3529d8c2 3146
d8768362
JA
3147#ifdef CONFIG_COMPAT
3148 if (req->ctx->compat)
3149 sr->msg_flags |= MSG_CMSG_COMPAT;
3150#endif
3151
fddaface 3152 if (!io || req->opcode == IORING_OP_SEND)
3529d8c2 3153 return 0;
5f798bea
PB
3154 /* iovec is already imported */
3155 if (req->flags & REQ_F_NEED_CLEANUP)
3156 return 0;
3529d8c2 3157
d9688565 3158 io->msg.iov = io->msg.fast_iov;
99bc4c38 3159 ret = sendmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
e47293fd 3160 &io->msg.iov);
99bc4c38
PB
3161 if (!ret)
3162 req->flags |= REQ_F_NEED_CLEANUP;
3163 return ret;
03b1230c 3164#else
e47293fd 3165 return -EOPNOTSUPP;
03b1230c
JA
3166#endif
3167}
3168
fc4df999
JA
3169static int io_sendmsg(struct io_kiocb *req, struct io_kiocb **nxt,
3170 bool force_nonblock)
aa1fa28f 3171{
03b1230c 3172#if defined(CONFIG_NET)
0b416c3e 3173 struct io_async_msghdr *kmsg = NULL;
0fa03c62
JA
3174 struct socket *sock;
3175 int ret;
3176
3177 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3178 return -EINVAL;
3179
3180 sock = sock_from_file(req->file, &ret);
3181 if (sock) {
b7bb4f7d 3182 struct io_async_ctx io;
0fa03c62
JA
3183 unsigned flags;
3184
03b1230c 3185 if (req->io) {
0b416c3e 3186 kmsg = &req->io->msg;
b537916c 3187 kmsg->msg.msg_name = &req->io->msg.addr;
0b416c3e
JA
3188 /* if iov is set, it's allocated already */
3189 if (!kmsg->iov)
3190 kmsg->iov = kmsg->fast_iov;
3191 kmsg->msg.msg_iter.iov = kmsg->iov;
03b1230c 3192 } else {
3529d8c2
JA
3193 struct io_sr_msg *sr = &req->sr_msg;
3194
0b416c3e 3195 kmsg = &io.msg;
b537916c 3196 kmsg->msg.msg_name = &io.msg.addr;
3529d8c2
JA
3197
3198 io.msg.iov = io.msg.fast_iov;
3199 ret = sendmsg_copy_msghdr(&io.msg.msg, sr->msg,
3200 sr->msg_flags, &io.msg.iov);
03b1230c 3201 if (ret)
3529d8c2 3202 return ret;
03b1230c 3203 }
0fa03c62 3204
e47293fd
JA
3205 flags = req->sr_msg.msg_flags;
3206 if (flags & MSG_DONTWAIT)
3207 req->flags |= REQ_F_NOWAIT;
3208 else if (force_nonblock)
3209 flags |= MSG_DONTWAIT;
3210
0b416c3e 3211 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
02d27d89
PB
3212 if (force_nonblock && ret == -EAGAIN)
3213 return io_setup_async_msg(req, kmsg);
441cdbd5
JA
3214 if (ret == -ERESTARTSYS)
3215 ret = -EINTR;
0fa03c62
JA
3216 }
3217
1e95081c 3218 if (kmsg && kmsg->iov != kmsg->fast_iov)
0b416c3e 3219 kfree(kmsg->iov);
99bc4c38 3220 req->flags &= ~REQ_F_NEED_CLEANUP;
78e19bbe 3221 io_cqring_add_event(req, ret);
4e88d6e7
JA
3222 if (ret < 0)
3223 req_set_fail_links(req);
ec9c02ad 3224 io_put_req_find_next(req, nxt);
5d17b4a4 3225 return 0;
03b1230c
JA
3226#else
3227 return -EOPNOTSUPP;
aa1fa28f 3228#endif
03b1230c 3229}
aa1fa28f 3230
fddaface
JA
3231static int io_send(struct io_kiocb *req, struct io_kiocb **nxt,
3232 bool force_nonblock)
3233{
3234#if defined(CONFIG_NET)
3235 struct socket *sock;
3236 int ret;
3237
3238 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3239 return -EINVAL;
3240
3241 sock = sock_from_file(req->file, &ret);
3242 if (sock) {
3243 struct io_sr_msg *sr = &req->sr_msg;
3244 struct msghdr msg;
3245 struct iovec iov;
3246 unsigned flags;
3247
3248 ret = import_single_range(WRITE, sr->buf, sr->len, &iov,
3249 &msg.msg_iter);
3250 if (ret)
3251 return ret;
3252
3253 msg.msg_name = NULL;
3254 msg.msg_control = NULL;
3255 msg.msg_controllen = 0;
3256 msg.msg_namelen = 0;
3257
3258 flags = req->sr_msg.msg_flags;
3259 if (flags & MSG_DONTWAIT)
3260 req->flags |= REQ_F_NOWAIT;
3261 else if (force_nonblock)
3262 flags |= MSG_DONTWAIT;
3263
0b7b21e4
JA
3264 msg.msg_flags = flags;
3265 ret = sock_sendmsg(sock, &msg);
fddaface
JA
3266 if (force_nonblock && ret == -EAGAIN)
3267 return -EAGAIN;
3268 if (ret == -ERESTARTSYS)
3269 ret = -EINTR;
3270 }
3271
3272 io_cqring_add_event(req, ret);
3273 if (ret < 0)
3274 req_set_fail_links(req);
3275 io_put_req_find_next(req, nxt);
3276 return 0;
3277#else
3278 return -EOPNOTSUPP;
3279#endif
3280}
3281
3529d8c2
JA
3282static int io_recvmsg_prep(struct io_kiocb *req,
3283 const struct io_uring_sqe *sqe)
aa1fa28f
JA
3284{
3285#if defined(CONFIG_NET)
e47293fd 3286 struct io_sr_msg *sr = &req->sr_msg;
3529d8c2 3287 struct io_async_ctx *io = req->io;
99bc4c38 3288 int ret;
3529d8c2
JA
3289
3290 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3291 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
0b7b21e4 3292 sr->len = READ_ONCE(sqe->len);
06b76d44 3293
d8768362
JA
3294#ifdef CONFIG_COMPAT
3295 if (req->ctx->compat)
3296 sr->msg_flags |= MSG_CMSG_COMPAT;
3297#endif
3298
fddaface 3299 if (!io || req->opcode == IORING_OP_RECV)
06b76d44 3300 return 0;
5f798bea
PB
3301 /* iovec is already imported */
3302 if (req->flags & REQ_F_NEED_CLEANUP)
3303 return 0;
03b1230c 3304
d9688565 3305 io->msg.iov = io->msg.fast_iov;
99bc4c38 3306 ret = recvmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
e47293fd 3307 &io->msg.uaddr, &io->msg.iov);
99bc4c38
PB
3308 if (!ret)
3309 req->flags |= REQ_F_NEED_CLEANUP;
3310 return ret;
aa1fa28f 3311#else
e47293fd 3312 return -EOPNOTSUPP;
aa1fa28f
JA
3313#endif
3314}
3315
fc4df999
JA
3316static int io_recvmsg(struct io_kiocb *req, struct io_kiocb **nxt,
3317 bool force_nonblock)
aa1fa28f
JA
3318{
3319#if defined(CONFIG_NET)
0b416c3e 3320 struct io_async_msghdr *kmsg = NULL;
03b1230c
JA
3321 struct socket *sock;
3322 int ret;
3323
3324 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3325 return -EINVAL;
3326
3327 sock = sock_from_file(req->file, &ret);
3328 if (sock) {
b7bb4f7d 3329 struct io_async_ctx io;
03b1230c
JA
3330 unsigned flags;
3331
03b1230c 3332 if (req->io) {
0b416c3e 3333 kmsg = &req->io->msg;
b537916c 3334 kmsg->msg.msg_name = &req->io->msg.addr;
0b416c3e
JA
3335 /* if iov is set, it's allocated already */
3336 if (!kmsg->iov)
3337 kmsg->iov = kmsg->fast_iov;
3338 kmsg->msg.msg_iter.iov = kmsg->iov;
03b1230c 3339 } else {
3529d8c2
JA
3340 struct io_sr_msg *sr = &req->sr_msg;
3341
0b416c3e 3342 kmsg = &io.msg;
b537916c 3343 kmsg->msg.msg_name = &io.msg.addr;
3529d8c2
JA
3344
3345 io.msg.iov = io.msg.fast_iov;
3346 ret = recvmsg_copy_msghdr(&io.msg.msg, sr->msg,
3347 sr->msg_flags, &io.msg.uaddr,
3348 &io.msg.iov);
03b1230c 3349 if (ret)
3529d8c2 3350 return ret;
03b1230c
JA
3351 }
3352
e47293fd
JA
3353 flags = req->sr_msg.msg_flags;
3354 if (flags & MSG_DONTWAIT)
3355 req->flags |= REQ_F_NOWAIT;
3356 else if (force_nonblock)
3357 flags |= MSG_DONTWAIT;
3358
3359 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.msg,
3360 kmsg->uaddr, flags);
02d27d89
PB
3361 if (force_nonblock && ret == -EAGAIN)
3362 return io_setup_async_msg(req, kmsg);
03b1230c
JA
3363 if (ret == -ERESTARTSYS)
3364 ret = -EINTR;
3365 }
3366
1e95081c 3367 if (kmsg && kmsg->iov != kmsg->fast_iov)
0b416c3e 3368 kfree(kmsg->iov);
99bc4c38 3369 req->flags &= ~REQ_F_NEED_CLEANUP;
03b1230c 3370 io_cqring_add_event(req, ret);
4e88d6e7
JA
3371 if (ret < 0)
3372 req_set_fail_links(req);
03b1230c
JA
3373 io_put_req_find_next(req, nxt);
3374 return 0;
0fa03c62
JA
3375#else
3376 return -EOPNOTSUPP;
3377#endif
3378}
5d17b4a4 3379
fddaface
JA
3380static int io_recv(struct io_kiocb *req, struct io_kiocb **nxt,
3381 bool force_nonblock)
3382{
3383#if defined(CONFIG_NET)
3384 struct socket *sock;
3385 int ret;
3386
3387 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3388 return -EINVAL;
3389
3390 sock = sock_from_file(req->file, &ret);
3391 if (sock) {
3392 struct io_sr_msg *sr = &req->sr_msg;
3393 struct msghdr msg;
3394 struct iovec iov;
3395 unsigned flags;
3396
3397 ret = import_single_range(READ, sr->buf, sr->len, &iov,
3398 &msg.msg_iter);
3399 if (ret)
3400 return ret;
3401
3402 msg.msg_name = NULL;
3403 msg.msg_control = NULL;
3404 msg.msg_controllen = 0;
3405 msg.msg_namelen = 0;
3406 msg.msg_iocb = NULL;
3407 msg.msg_flags = 0;
3408
3409 flags = req->sr_msg.msg_flags;
3410 if (flags & MSG_DONTWAIT)
3411 req->flags |= REQ_F_NOWAIT;
3412 else if (force_nonblock)
3413 flags |= MSG_DONTWAIT;
3414
0b7b21e4 3415 ret = sock_recvmsg(sock, &msg, flags);
fddaface
JA
3416 if (force_nonblock && ret == -EAGAIN)
3417 return -EAGAIN;
3418 if (ret == -ERESTARTSYS)
3419 ret = -EINTR;
3420 }
3421
3422 io_cqring_add_event(req, ret);
3423 if (ret < 0)
3424 req_set_fail_links(req);
3425 io_put_req_find_next(req, nxt);
3426 return 0;
3427#else
3428 return -EOPNOTSUPP;
3429#endif
3430}
3431
3432
3529d8c2 3433static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
17f2fe35
JA
3434{
3435#if defined(CONFIG_NET)
8ed8d3c3
JA
3436 struct io_accept *accept = &req->accept;
3437
17f2fe35
JA
3438 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3439 return -EINVAL;
8042d6ce 3440 if (sqe->ioprio || sqe->len || sqe->buf_index)
17f2fe35
JA
3441 return -EINVAL;
3442
d55e5f5b
JA
3443 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3444 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
8ed8d3c3 3445 accept->flags = READ_ONCE(sqe->accept_flags);
8ed8d3c3
JA
3446 return 0;
3447#else
3448 return -EOPNOTSUPP;
3449#endif
3450}
17f2fe35 3451
8ed8d3c3
JA
3452#if defined(CONFIG_NET)
3453static int __io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
3454 bool force_nonblock)
3455{
3456 struct io_accept *accept = &req->accept;
3457 unsigned file_flags;
3458 int ret;
3459
3460 file_flags = force_nonblock ? O_NONBLOCK : 0;
3461 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
3462 accept->addr_len, accept->flags);
3463 if (ret == -EAGAIN && force_nonblock)
17f2fe35 3464 return -EAGAIN;
8e3cca12
JA
3465 if (ret == -ERESTARTSYS)
3466 ret = -EINTR;
4e88d6e7
JA
3467 if (ret < 0)
3468 req_set_fail_links(req);
78e19bbe 3469 io_cqring_add_event(req, ret);
ec9c02ad 3470 io_put_req_find_next(req, nxt);
17f2fe35 3471 return 0;
8ed8d3c3
JA
3472}
3473
3474static void io_accept_finish(struct io_wq_work **workptr)
3475{
3476 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3477 struct io_kiocb *nxt = NULL;
3478
e441d1cf
JA
3479 io_put_req(req);
3480
8ed8d3c3
JA
3481 if (io_req_cancelled(req))
3482 return;
3483 __io_accept(req, &nxt, false);
3484 if (nxt)
78912934 3485 io_wq_assign_next(workptr, nxt);
8ed8d3c3
JA
3486}
3487#endif
3488
3489static int io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
3490 bool force_nonblock)
3491{
3492#if defined(CONFIG_NET)
3493 int ret;
3494
8ed8d3c3
JA
3495 ret = __io_accept(req, nxt, force_nonblock);
3496 if (ret == -EAGAIN && force_nonblock) {
3497 req->work.func = io_accept_finish;
8ed8d3c3
JA
3498 return -EAGAIN;
3499 }
3500 return 0;
0fa03c62
JA
3501#else
3502 return -EOPNOTSUPP;
3503#endif
3504}
5d17b4a4 3505
3529d8c2 3506static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
f499a021
JA
3507{
3508#if defined(CONFIG_NET)
3529d8c2
JA
3509 struct io_connect *conn = &req->connect;
3510 struct io_async_ctx *io = req->io;
f499a021 3511
3fbb51c1
JA
3512 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3513 return -EINVAL;
3514 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
3515 return -EINVAL;
3516
3529d8c2
JA
3517 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3518 conn->addr_len = READ_ONCE(sqe->addr2);
3519
3520 if (!io)
3521 return 0;
3522
3523 return move_addr_to_kernel(conn->addr, conn->addr_len,
3fbb51c1 3524 &io->connect.address);
f499a021 3525#else
3fbb51c1 3526 return -EOPNOTSUPP;
f499a021
JA
3527#endif
3528}
3529
fc4df999
JA
3530static int io_connect(struct io_kiocb *req, struct io_kiocb **nxt,
3531 bool force_nonblock)
f8e85cf2
JA
3532{
3533#if defined(CONFIG_NET)
f499a021 3534 struct io_async_ctx __io, *io;
f8e85cf2 3535 unsigned file_flags;
3fbb51c1 3536 int ret;
f8e85cf2 3537
f499a021
JA
3538 if (req->io) {
3539 io = req->io;
3540 } else {
3529d8c2
JA
3541 ret = move_addr_to_kernel(req->connect.addr,
3542 req->connect.addr_len,
3543 &__io.connect.address);
f499a021
JA
3544 if (ret)
3545 goto out;
3546 io = &__io;
3547 }
3548
3fbb51c1
JA
3549 file_flags = force_nonblock ? O_NONBLOCK : 0;
3550
3551 ret = __sys_connect_file(req->file, &io->connect.address,
3552 req->connect.addr_len, file_flags);
87f80d62 3553 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
b7bb4f7d
JA
3554 if (req->io)
3555 return -EAGAIN;
3556 if (io_alloc_async_ctx(req)) {
f499a021
JA
3557 ret = -ENOMEM;
3558 goto out;
3559 }
b7bb4f7d 3560 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
f8e85cf2 3561 return -EAGAIN;
f499a021 3562 }
f8e85cf2
JA
3563 if (ret == -ERESTARTSYS)
3564 ret = -EINTR;
f499a021 3565out:
4e88d6e7
JA
3566 if (ret < 0)
3567 req_set_fail_links(req);
f8e85cf2
JA
3568 io_cqring_add_event(req, ret);
3569 io_put_req_find_next(req, nxt);
3570 return 0;
3571#else
3572 return -EOPNOTSUPP;
3573#endif
3574}
3575
d7718a9d
JA
3576struct io_poll_table {
3577 struct poll_table_struct pt;
3578 struct io_kiocb *req;
3579 int error;
3580};
3581
3582static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
3583 struct wait_queue_head *head)
3584{
3585 if (unlikely(poll->head)) {
3586 pt->error = -EINVAL;
3587 return;
3588 }
3589
3590 pt->error = 0;
3591 poll->head = head;
3592 add_wait_queue(head, &poll->wait);
3593}
3594
3595static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
3596 struct poll_table_struct *p)
3597{
3598 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
3599
3600 __io_queue_proc(&pt->req->apoll->poll, pt, head);
3601}
3602
3603static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
3604 __poll_t mask, task_work_func_t func)
3605{
3606 struct task_struct *tsk;
3607
3608 /* for instances that support it check for an event match first: */
3609 if (mask && !(mask & poll->events))
3610 return 0;
3611
3612 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
3613
3614 list_del_init(&poll->wait.entry);
3615
3616 tsk = req->task;
3617 req->result = mask;
3618 init_task_work(&req->task_work, func);
3619 /*
3620 * If this fails, then the task is exiting. If that is the case, then
3621 * the exit check will ultimately cancel these work items. Hence we
3622 * don't need to check here and handle it specifically.
3623 */
3624 task_work_add(tsk, &req->task_work, true);
3625 wake_up_process(tsk);
3626 return 1;
3627}
3628
3629static void io_async_task_func(struct callback_head *cb)
3630{
3631 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
3632 struct async_poll *apoll = req->apoll;
3633 struct io_ring_ctx *ctx = req->ctx;
3634
3635 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
3636
3637 WARN_ON_ONCE(!list_empty(&req->apoll->poll.wait.entry));
3638
3639 if (hash_hashed(&req->hash_node)) {
3640 spin_lock_irq(&ctx->completion_lock);
3641 hash_del(&req->hash_node);
3642 spin_unlock_irq(&ctx->completion_lock);
3643 }
3644
3645 /* restore ->work in case we need to retry again */
3646 memcpy(&req->work, &apoll->work, sizeof(req->work));
3647
3648 __set_current_state(TASK_RUNNING);
3649 mutex_lock(&ctx->uring_lock);
3650 __io_queue_sqe(req, NULL);
3651 mutex_unlock(&ctx->uring_lock);
3652
3653 kfree(apoll);
3654}
3655
3656static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
3657 void *key)
3658{
3659 struct io_kiocb *req = wait->private;
3660 struct io_poll_iocb *poll = &req->apoll->poll;
3661
3662 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
3663 key_to_poll(key));
3664
3665 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
3666}
3667
3668static void io_poll_req_insert(struct io_kiocb *req)
3669{
3670 struct io_ring_ctx *ctx = req->ctx;
3671 struct hlist_head *list;
3672
3673 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
3674 hlist_add_head(&req->hash_node, list);
3675}
3676
3677static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
3678 struct io_poll_iocb *poll,
3679 struct io_poll_table *ipt, __poll_t mask,
3680 wait_queue_func_t wake_func)
3681 __acquires(&ctx->completion_lock)
3682{
3683 struct io_ring_ctx *ctx = req->ctx;
3684 bool cancel = false;
3685
3686 poll->file = req->file;
3687 poll->head = NULL;
3688 poll->done = poll->canceled = false;
3689 poll->events = mask;
3690
3691 ipt->pt._key = mask;
3692 ipt->req = req;
3693 ipt->error = -EINVAL;
3694
3695 INIT_LIST_HEAD(&poll->wait.entry);
3696 init_waitqueue_func_entry(&poll->wait, wake_func);
3697 poll->wait.private = req;
3698
3699 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
3700
3701 spin_lock_irq(&ctx->completion_lock);
3702 if (likely(poll->head)) {
3703 spin_lock(&poll->head->lock);
3704 if (unlikely(list_empty(&poll->wait.entry))) {
3705 if (ipt->error)
3706 cancel = true;
3707 ipt->error = 0;
3708 mask = 0;
3709 }
3710 if (mask || ipt->error)
3711 list_del_init(&poll->wait.entry);
3712 else if (cancel)
3713 WRITE_ONCE(poll->canceled, true);
3714 else if (!poll->done) /* actually waiting for an event */
3715 io_poll_req_insert(req);
3716 spin_unlock(&poll->head->lock);
3717 }
3718
3719 return mask;
3720}
3721
3722static bool io_arm_poll_handler(struct io_kiocb *req)
3723{
3724 const struct io_op_def *def = &io_op_defs[req->opcode];
3725 struct io_ring_ctx *ctx = req->ctx;
3726 struct async_poll *apoll;
3727 struct io_poll_table ipt;
3728 __poll_t mask, ret;
3729
3730 if (!req->file || !file_can_poll(req->file))
3731 return false;
3732 if (req->flags & (REQ_F_MUST_PUNT | REQ_F_POLLED))
3733 return false;
3734 if (!def->pollin && !def->pollout)
3735 return false;
3736
3737 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
3738 if (unlikely(!apoll))
3739 return false;
3740
3741 req->flags |= REQ_F_POLLED;
3742 memcpy(&apoll->work, &req->work, sizeof(req->work));
3743
3744 /*
3745 * Don't need a reference here, as we're adding it to the task
3746 * task_works list. If the task exits, the list is pruned.
3747 */
3748 req->task = current;
3749 req->apoll = apoll;
3750 INIT_HLIST_NODE(&req->hash_node);
3751
3752 if (def->pollin)
3753 mask = POLLIN | POLLRDNORM;
3754 if (def->pollout)
3755 mask |= POLLOUT | POLLWRNORM;
3756 mask |= POLLERR | POLLPRI;
3757
3758 ipt.pt._qproc = io_async_queue_proc;
3759
3760 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
3761 io_async_wake);
3762 if (ret) {
3763 ipt.error = 0;
3764 apoll->poll.done = true;
3765 spin_unlock_irq(&ctx->completion_lock);
3766 memcpy(&req->work, &apoll->work, sizeof(req->work));
3767 kfree(apoll);
3768 return false;
3769 }
3770 spin_unlock_irq(&ctx->completion_lock);
3771 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
3772 apoll->poll.events);
3773 return true;
3774}
3775
3776static bool __io_poll_remove_one(struct io_kiocb *req,
3777 struct io_poll_iocb *poll)
221c5eb2 3778{
b41e9852 3779 bool do_complete = false;
221c5eb2
JA
3780
3781 spin_lock(&poll->head->lock);
3782 WRITE_ONCE(poll->canceled, true);
392edb45
JA
3783 if (!list_empty(&poll->wait.entry)) {
3784 list_del_init(&poll->wait.entry);
b41e9852 3785 do_complete = true;
221c5eb2
JA
3786 }
3787 spin_unlock(&poll->head->lock);
d7718a9d
JA
3788 return do_complete;
3789}
3790
3791static bool io_poll_remove_one(struct io_kiocb *req)
3792{
3793 bool do_complete;
3794
3795 if (req->opcode == IORING_OP_POLL_ADD) {
3796 do_complete = __io_poll_remove_one(req, &req->poll);
3797 } else {
3798 /* non-poll requests have submit ref still */
3799 do_complete = __io_poll_remove_one(req, &req->apoll->poll);
3800 if (do_complete)
3801 io_put_req(req);
3802 }
3803
78076bb6 3804 hash_del(&req->hash_node);
d7718a9d 3805
b41e9852
JA
3806 if (do_complete) {
3807 io_cqring_fill_event(req, -ECANCELED);
3808 io_commit_cqring(req->ctx);
3809 req->flags |= REQ_F_COMP_LOCKED;
3810 io_put_req(req);
3811 }
3812
3813 return do_complete;
221c5eb2
JA
3814}
3815
3816static void io_poll_remove_all(struct io_ring_ctx *ctx)
3817{
78076bb6 3818 struct hlist_node *tmp;
221c5eb2 3819 struct io_kiocb *req;
78076bb6 3820 int i;
221c5eb2
JA
3821
3822 spin_lock_irq(&ctx->completion_lock);
78076bb6
JA
3823 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
3824 struct hlist_head *list;
3825
3826 list = &ctx->cancel_hash[i];
3827 hlist_for_each_entry_safe(req, tmp, list, hash_node)
3828 io_poll_remove_one(req);
221c5eb2
JA
3829 }
3830 spin_unlock_irq(&ctx->completion_lock);
b41e9852
JA
3831
3832 io_cqring_ev_posted(ctx);
221c5eb2
JA
3833}
3834
47f46768
JA
3835static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
3836{
78076bb6 3837 struct hlist_head *list;
47f46768
JA
3838 struct io_kiocb *req;
3839
78076bb6
JA
3840 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
3841 hlist_for_each_entry(req, list, hash_node) {
b41e9852
JA
3842 if (sqe_addr != req->user_data)
3843 continue;
3844 if (io_poll_remove_one(req))
eac406c6 3845 return 0;
b41e9852 3846 return -EALREADY;
47f46768
JA
3847 }
3848
3849 return -ENOENT;
3850}
3851
3529d8c2
JA
3852static int io_poll_remove_prep(struct io_kiocb *req,
3853 const struct io_uring_sqe *sqe)
0969e783 3854{
0969e783
JA
3855 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3856 return -EINVAL;
3857 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3858 sqe->poll_events)
3859 return -EINVAL;
3860
3861 req->poll.addr = READ_ONCE(sqe->addr);
0969e783
JA
3862 return 0;
3863}
3864
221c5eb2
JA
3865/*
3866 * Find a running poll command that matches one specified in sqe->addr,
3867 * and remove it if found.
3868 */
fc4df999 3869static int io_poll_remove(struct io_kiocb *req)
221c5eb2
JA
3870{
3871 struct io_ring_ctx *ctx = req->ctx;
0969e783 3872 u64 addr;
47f46768 3873 int ret;
221c5eb2 3874
0969e783 3875 addr = req->poll.addr;
221c5eb2 3876 spin_lock_irq(&ctx->completion_lock);
0969e783 3877 ret = io_poll_cancel(ctx, addr);
221c5eb2
JA
3878 spin_unlock_irq(&ctx->completion_lock);
3879
78e19bbe 3880 io_cqring_add_event(req, ret);
4e88d6e7
JA
3881 if (ret < 0)
3882 req_set_fail_links(req);
e65ef56d 3883 io_put_req(req);
221c5eb2
JA
3884 return 0;
3885}
3886
b0dd8a41 3887static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
221c5eb2 3888{
a197f664
JL
3889 struct io_ring_ctx *ctx = req->ctx;
3890
8c838788 3891 req->poll.done = true;
b0a20349 3892 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
8c838788 3893 io_commit_cqring(ctx);
221c5eb2
JA
3894}
3895
b41e9852 3896static void io_poll_task_handler(struct io_kiocb *req, struct io_kiocb **nxt)
221c5eb2 3897{
221c5eb2 3898 struct io_ring_ctx *ctx = req->ctx;
221c5eb2 3899
221c5eb2 3900 spin_lock_irq(&ctx->completion_lock);
78076bb6 3901 hash_del(&req->hash_node);
b41e9852
JA
3902 io_poll_complete(req, req->result, 0);
3903 req->flags |= REQ_F_COMP_LOCKED;
3904 io_put_req_find_next(req, nxt);
e94f141b
JA
3905 spin_unlock_irq(&ctx->completion_lock);
3906
3907 io_cqring_ev_posted(ctx);
e94f141b
JA
3908}
3909
b41e9852 3910static void io_poll_task_func(struct callback_head *cb)
f0b493e6 3911{
b41e9852
JA
3912 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
3913 struct io_kiocb *nxt = NULL;
f0b493e6 3914
b41e9852 3915 io_poll_task_handler(req, &nxt);
d7718a9d
JA
3916 if (nxt) {
3917 struct io_ring_ctx *ctx = nxt->ctx;
3918
3919 mutex_lock(&ctx->uring_lock);
b41e9852 3920 __io_queue_sqe(nxt, NULL);
d7718a9d
JA
3921 mutex_unlock(&ctx->uring_lock);
3922 }
f0b493e6
JA
3923}
3924
221c5eb2
JA
3925static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
3926 void *key)
3927{
c2f2eb7d
JA
3928 struct io_kiocb *req = wait->private;
3929 struct io_poll_iocb *poll = &req->poll;
221c5eb2 3930
d7718a9d 3931 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
221c5eb2
JA
3932}
3933
221c5eb2
JA
3934static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
3935 struct poll_table_struct *p)
3936{
3937 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
3938
d7718a9d 3939 __io_queue_proc(&pt->req->poll, pt, head);
eac406c6
JA
3940}
3941
3529d8c2 3942static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
221c5eb2
JA
3943{
3944 struct io_poll_iocb *poll = &req->poll;
221c5eb2 3945 u16 events;
221c5eb2
JA
3946
3947 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3948 return -EINVAL;
3949 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
3950 return -EINVAL;
09bb8394
JA
3951 if (!poll->file)
3952 return -EBADF;
221c5eb2 3953
221c5eb2
JA
3954 events = READ_ONCE(sqe->poll_events);
3955 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
b41e9852 3956
d7718a9d
JA
3957 /*
3958 * Don't need a reference here, as we're adding it to the task
3959 * task_works list. If the task exits, the list is pruned.
3960 */
b41e9852 3961 req->task = current;
0969e783
JA
3962 return 0;
3963}
3964
3965static int io_poll_add(struct io_kiocb *req, struct io_kiocb **nxt)
3966{
3967 struct io_poll_iocb *poll = &req->poll;
3968 struct io_ring_ctx *ctx = req->ctx;
3969 struct io_poll_table ipt;
0969e783 3970 __poll_t mask;
0969e783 3971
78076bb6 3972 INIT_HLIST_NODE(&req->hash_node);
36703247 3973 INIT_LIST_HEAD(&req->list);
d7718a9d 3974 ipt.pt._qproc = io_poll_queue_proc;
36703247 3975
d7718a9d
JA
3976 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
3977 io_poll_wake);
221c5eb2 3978
8c838788 3979 if (mask) { /* no async, we'd stolen it */
221c5eb2 3980 ipt.error = 0;
b0dd8a41 3981 io_poll_complete(req, mask, 0);
221c5eb2 3982 }
221c5eb2
JA
3983 spin_unlock_irq(&ctx->completion_lock);
3984
8c838788
JA
3985 if (mask) {
3986 io_cqring_ev_posted(ctx);
ec9c02ad 3987 io_put_req_find_next(req, nxt);
221c5eb2 3988 }
8c838788 3989 return ipt.error;
221c5eb2
JA
3990}
3991
5262f567
JA
3992static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
3993{
ad8a48ac
JA
3994 struct io_timeout_data *data = container_of(timer,
3995 struct io_timeout_data, timer);
3996 struct io_kiocb *req = data->req;
3997 struct io_ring_ctx *ctx = req->ctx;
5262f567
JA
3998 unsigned long flags;
3999
5262f567
JA
4000 atomic_inc(&ctx->cq_timeouts);
4001
4002 spin_lock_irqsave(&ctx->completion_lock, flags);
ef03681a 4003 /*
11365043
JA
4004 * We could be racing with timeout deletion. If the list is empty,
4005 * then timeout lookup already found it and will be handling it.
ef03681a 4006 */
842f9612 4007 if (!list_empty(&req->list)) {
11365043 4008 struct io_kiocb *prev;
5262f567 4009
11365043
JA
4010 /*
4011 * Adjust the reqs sequence before the current one because it
d195a66e 4012 * will consume a slot in the cq_ring and the cq_tail
11365043
JA
4013 * pointer will be increased, otherwise other timeout reqs may
4014 * return in advance without waiting for enough wait_nr.
4015 */
4016 prev = req;
4017 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
4018 prev->sequence++;
11365043 4019 list_del_init(&req->list);
11365043 4020 }
5262f567 4021
78e19bbe 4022 io_cqring_fill_event(req, -ETIME);
5262f567
JA
4023 io_commit_cqring(ctx);
4024 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4025
4026 io_cqring_ev_posted(ctx);
4e88d6e7 4027 req_set_fail_links(req);
5262f567
JA
4028 io_put_req(req);
4029 return HRTIMER_NORESTART;
4030}
4031
47f46768
JA
4032static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
4033{
4034 struct io_kiocb *req;
4035 int ret = -ENOENT;
4036
4037 list_for_each_entry(req, &ctx->timeout_list, list) {
4038 if (user_data == req->user_data) {
4039 list_del_init(&req->list);
4040 ret = 0;
4041 break;
4042 }
4043 }
4044
4045 if (ret == -ENOENT)
4046 return ret;
4047
2d28390a 4048 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
47f46768
JA
4049 if (ret == -1)
4050 return -EALREADY;
4051
4e88d6e7 4052 req_set_fail_links(req);
47f46768
JA
4053 io_cqring_fill_event(req, -ECANCELED);
4054 io_put_req(req);
4055 return 0;
4056}
4057
3529d8c2
JA
4058static int io_timeout_remove_prep(struct io_kiocb *req,
4059 const struct io_uring_sqe *sqe)
b29472ee 4060{
b29472ee
JA
4061 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4062 return -EINVAL;
4063 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
4064 return -EINVAL;
4065
4066 req->timeout.addr = READ_ONCE(sqe->addr);
4067 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
4068 if (req->timeout.flags)
4069 return -EINVAL;
4070
b29472ee
JA
4071 return 0;
4072}
4073
11365043
JA
4074/*
4075 * Remove or update an existing timeout command
4076 */
fc4df999 4077static int io_timeout_remove(struct io_kiocb *req)
11365043
JA
4078{
4079 struct io_ring_ctx *ctx = req->ctx;
47f46768 4080 int ret;
11365043 4081
11365043 4082 spin_lock_irq(&ctx->completion_lock);
b29472ee 4083 ret = io_timeout_cancel(ctx, req->timeout.addr);
11365043 4084
47f46768 4085 io_cqring_fill_event(req, ret);
11365043
JA
4086 io_commit_cqring(ctx);
4087 spin_unlock_irq(&ctx->completion_lock);
5262f567 4088 io_cqring_ev_posted(ctx);
4e88d6e7
JA
4089 if (ret < 0)
4090 req_set_fail_links(req);
ec9c02ad 4091 io_put_req(req);
11365043 4092 return 0;
5262f567
JA
4093}
4094
3529d8c2 4095static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2d28390a 4096 bool is_timeout_link)
5262f567 4097{
ad8a48ac 4098 struct io_timeout_data *data;
a41525ab 4099 unsigned flags;
5262f567 4100
ad8a48ac 4101 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5262f567 4102 return -EINVAL;
ad8a48ac 4103 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
a41525ab 4104 return -EINVAL;
2d28390a
JA
4105 if (sqe->off && is_timeout_link)
4106 return -EINVAL;
a41525ab
JA
4107 flags = READ_ONCE(sqe->timeout_flags);
4108 if (flags & ~IORING_TIMEOUT_ABS)
5262f567 4109 return -EINVAL;
bdf20073 4110
26a61679
JA
4111 req->timeout.count = READ_ONCE(sqe->off);
4112
3529d8c2 4113 if (!req->io && io_alloc_async_ctx(req))
26a61679
JA
4114 return -ENOMEM;
4115
4116 data = &req->io->timeout;
ad8a48ac 4117 data->req = req;
ad8a48ac
JA
4118 req->flags |= REQ_F_TIMEOUT;
4119
4120 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5262f567
JA
4121 return -EFAULT;
4122
11365043 4123 if (flags & IORING_TIMEOUT_ABS)
ad8a48ac 4124 data->mode = HRTIMER_MODE_ABS;
11365043 4125 else
ad8a48ac 4126 data->mode = HRTIMER_MODE_REL;
11365043 4127
ad8a48ac
JA
4128 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
4129 return 0;
4130}
4131
fc4df999 4132static int io_timeout(struct io_kiocb *req)
ad8a48ac
JA
4133{
4134 unsigned count;
4135 struct io_ring_ctx *ctx = req->ctx;
4136 struct io_timeout_data *data;
4137 struct list_head *entry;
4138 unsigned span = 0;
ad8a48ac 4139
2d28390a 4140 data = &req->io->timeout;
93bd25bb 4141
5262f567
JA
4142 /*
4143 * sqe->off holds how many events that need to occur for this
93bd25bb
JA
4144 * timeout event to be satisfied. If it isn't set, then this is
4145 * a pure timeout request, sequence isn't used.
5262f567 4146 */
26a61679 4147 count = req->timeout.count;
93bd25bb
JA
4148 if (!count) {
4149 req->flags |= REQ_F_TIMEOUT_NOSEQ;
4150 spin_lock_irq(&ctx->completion_lock);
4151 entry = ctx->timeout_list.prev;
4152 goto add;
4153 }
5262f567
JA
4154
4155 req->sequence = ctx->cached_sq_head + count - 1;
2d28390a 4156 data->seq_offset = count;
5262f567
JA
4157
4158 /*
4159 * Insertion sort, ensuring the first entry in the list is always
4160 * the one we need first.
4161 */
5262f567
JA
4162 spin_lock_irq(&ctx->completion_lock);
4163 list_for_each_prev(entry, &ctx->timeout_list) {
4164 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
5da0fb1a 4165 unsigned nxt_sq_head;
4166 long long tmp, tmp_nxt;
2d28390a 4167 u32 nxt_offset = nxt->io->timeout.seq_offset;
5262f567 4168
93bd25bb
JA
4169 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
4170 continue;
4171
5da0fb1a 4172 /*
4173 * Since cached_sq_head + count - 1 can overflow, use type long
4174 * long to store it.
4175 */
4176 tmp = (long long)ctx->cached_sq_head + count - 1;
cc42e0ac
PB
4177 nxt_sq_head = nxt->sequence - nxt_offset + 1;
4178 tmp_nxt = (long long)nxt_sq_head + nxt_offset - 1;
5da0fb1a 4179
4180 /*
4181 * cached_sq_head may overflow, and it will never overflow twice
4182 * once there is some timeout req still be valid.
4183 */
4184 if (ctx->cached_sq_head < nxt_sq_head)
8b07a65a 4185 tmp += UINT_MAX;
5da0fb1a 4186
a1f58ba4 4187 if (tmp > tmp_nxt)
5262f567 4188 break;
a1f58ba4 4189
4190 /*
4191 * Sequence of reqs after the insert one and itself should
4192 * be adjusted because each timeout req consumes a slot.
4193 */
4194 span++;
4195 nxt->sequence++;
5262f567 4196 }
a1f58ba4 4197 req->sequence -= span;
93bd25bb 4198add:
5262f567 4199 list_add(&req->list, entry);
ad8a48ac
JA
4200 data->timer.function = io_timeout_fn;
4201 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5262f567 4202 spin_unlock_irq(&ctx->completion_lock);
5262f567
JA
4203 return 0;
4204}
5262f567 4205
62755e35
JA
4206static bool io_cancel_cb(struct io_wq_work *work, void *data)
4207{
4208 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4209
4210 return req->user_data == (unsigned long) data;
4211}
4212
e977d6d3 4213static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
62755e35 4214{
62755e35 4215 enum io_wq_cancel cancel_ret;
62755e35
JA
4216 int ret = 0;
4217
62755e35
JA
4218 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
4219 switch (cancel_ret) {
4220 case IO_WQ_CANCEL_OK:
4221 ret = 0;
4222 break;
4223 case IO_WQ_CANCEL_RUNNING:
4224 ret = -EALREADY;
4225 break;
4226 case IO_WQ_CANCEL_NOTFOUND:
4227 ret = -ENOENT;
4228 break;
4229 }
4230
e977d6d3
JA
4231 return ret;
4232}
4233
47f46768
JA
4234static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
4235 struct io_kiocb *req, __u64 sqe_addr,
b0dd8a41 4236 struct io_kiocb **nxt, int success_ret)
47f46768
JA
4237{
4238 unsigned long flags;
4239 int ret;
4240
4241 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
4242 if (ret != -ENOENT) {
4243 spin_lock_irqsave(&ctx->completion_lock, flags);
4244 goto done;
4245 }
4246
4247 spin_lock_irqsave(&ctx->completion_lock, flags);
4248 ret = io_timeout_cancel(ctx, sqe_addr);
4249 if (ret != -ENOENT)
4250 goto done;
4251 ret = io_poll_cancel(ctx, sqe_addr);
4252done:
b0dd8a41
JA
4253 if (!ret)
4254 ret = success_ret;
47f46768
JA
4255 io_cqring_fill_event(req, ret);
4256 io_commit_cqring(ctx);
4257 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4258 io_cqring_ev_posted(ctx);
4259
4e88d6e7
JA
4260 if (ret < 0)
4261 req_set_fail_links(req);
47f46768
JA
4262 io_put_req_find_next(req, nxt);
4263}
4264
3529d8c2
JA
4265static int io_async_cancel_prep(struct io_kiocb *req,
4266 const struct io_uring_sqe *sqe)
e977d6d3 4267{
fbf23849 4268 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
e977d6d3
JA
4269 return -EINVAL;
4270 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
4271 sqe->cancel_flags)
4272 return -EINVAL;
4273
fbf23849
JA
4274 req->cancel.addr = READ_ONCE(sqe->addr);
4275 return 0;
4276}
4277
4278static int io_async_cancel(struct io_kiocb *req, struct io_kiocb **nxt)
4279{
4280 struct io_ring_ctx *ctx = req->ctx;
fbf23849
JA
4281
4282 io_async_find_and_cancel(ctx, req, req->cancel.addr, nxt, 0);
5262f567
JA
4283 return 0;
4284}
4285
05f3fb3c
JA
4286static int io_files_update_prep(struct io_kiocb *req,
4287 const struct io_uring_sqe *sqe)
4288{
4289 if (sqe->flags || sqe->ioprio || sqe->rw_flags)
4290 return -EINVAL;
4291
4292 req->files_update.offset = READ_ONCE(sqe->off);
4293 req->files_update.nr_args = READ_ONCE(sqe->len);
4294 if (!req->files_update.nr_args)
4295 return -EINVAL;
4296 req->files_update.arg = READ_ONCE(sqe->addr);
4297 return 0;
4298}
4299
4300static int io_files_update(struct io_kiocb *req, bool force_nonblock)
fbf23849
JA
4301{
4302 struct io_ring_ctx *ctx = req->ctx;
05f3fb3c
JA
4303 struct io_uring_files_update up;
4304 int ret;
fbf23849 4305
f86cd20c 4306 if (force_nonblock)
05f3fb3c 4307 return -EAGAIN;
05f3fb3c
JA
4308
4309 up.offset = req->files_update.offset;
4310 up.fds = req->files_update.arg;
4311
4312 mutex_lock(&ctx->uring_lock);
4313 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
4314 mutex_unlock(&ctx->uring_lock);
4315
4316 if (ret < 0)
4317 req_set_fail_links(req);
4318 io_cqring_add_event(req, ret);
4319 io_put_req(req);
5262f567
JA
4320 return 0;
4321}
4322
3529d8c2
JA
4323static int io_req_defer_prep(struct io_kiocb *req,
4324 const struct io_uring_sqe *sqe)
f67676d1 4325{
e781573e 4326 ssize_t ret = 0;
f67676d1 4327
f86cd20c
JA
4328 if (io_op_defs[req->opcode].file_table) {
4329 ret = io_grab_files(req);
4330 if (unlikely(ret))
4331 return ret;
4332 }
4333
cccf0ee8
JA
4334 io_req_work_grab_env(req, &io_op_defs[req->opcode]);
4335
d625c6ee 4336 switch (req->opcode) {
e781573e
JA
4337 case IORING_OP_NOP:
4338 break;
f67676d1
JA
4339 case IORING_OP_READV:
4340 case IORING_OP_READ_FIXED:
3a6820f2 4341 case IORING_OP_READ:
3529d8c2 4342 ret = io_read_prep(req, sqe, true);
f67676d1
JA
4343 break;
4344 case IORING_OP_WRITEV:
4345 case IORING_OP_WRITE_FIXED:
3a6820f2 4346 case IORING_OP_WRITE:
3529d8c2 4347 ret = io_write_prep(req, sqe, true);
f67676d1 4348 break;
0969e783 4349 case IORING_OP_POLL_ADD:
3529d8c2 4350 ret = io_poll_add_prep(req, sqe);
0969e783
JA
4351 break;
4352 case IORING_OP_POLL_REMOVE:
3529d8c2 4353 ret = io_poll_remove_prep(req, sqe);
0969e783 4354 break;
8ed8d3c3 4355 case IORING_OP_FSYNC:
3529d8c2 4356 ret = io_prep_fsync(req, sqe);
8ed8d3c3
JA
4357 break;
4358 case IORING_OP_SYNC_FILE_RANGE:
3529d8c2 4359 ret = io_prep_sfr(req, sqe);
8ed8d3c3 4360 break;
03b1230c 4361 case IORING_OP_SENDMSG:
fddaface 4362 case IORING_OP_SEND:
3529d8c2 4363 ret = io_sendmsg_prep(req, sqe);
03b1230c
JA
4364 break;
4365 case IORING_OP_RECVMSG:
fddaface 4366 case IORING_OP_RECV:
3529d8c2 4367 ret = io_recvmsg_prep(req, sqe);
03b1230c 4368 break;
f499a021 4369 case IORING_OP_CONNECT:
3529d8c2 4370 ret = io_connect_prep(req, sqe);
f499a021 4371 break;
2d28390a 4372 case IORING_OP_TIMEOUT:
3529d8c2 4373 ret = io_timeout_prep(req, sqe, false);
b7bb4f7d 4374 break;
b29472ee 4375 case IORING_OP_TIMEOUT_REMOVE:
3529d8c2 4376 ret = io_timeout_remove_prep(req, sqe);
b29472ee 4377 break;
fbf23849 4378 case IORING_OP_ASYNC_CANCEL:
3529d8c2 4379 ret = io_async_cancel_prep(req, sqe);
fbf23849 4380 break;
2d28390a 4381 case IORING_OP_LINK_TIMEOUT:
3529d8c2 4382 ret = io_timeout_prep(req, sqe, true);
b7bb4f7d 4383 break;
8ed8d3c3 4384 case IORING_OP_ACCEPT:
3529d8c2 4385 ret = io_accept_prep(req, sqe);
8ed8d3c3 4386 break;
d63d1b5e
JA
4387 case IORING_OP_FALLOCATE:
4388 ret = io_fallocate_prep(req, sqe);
4389 break;
15b71abe
JA
4390 case IORING_OP_OPENAT:
4391 ret = io_openat_prep(req, sqe);
4392 break;
b5dba59e
JA
4393 case IORING_OP_CLOSE:
4394 ret = io_close_prep(req, sqe);
4395 break;
05f3fb3c
JA
4396 case IORING_OP_FILES_UPDATE:
4397 ret = io_files_update_prep(req, sqe);
4398 break;
eddc7ef5
JA
4399 case IORING_OP_STATX:
4400 ret = io_statx_prep(req, sqe);
4401 break;
4840e418
JA
4402 case IORING_OP_FADVISE:
4403 ret = io_fadvise_prep(req, sqe);
4404 break;
c1ca757b
JA
4405 case IORING_OP_MADVISE:
4406 ret = io_madvise_prep(req, sqe);
4407 break;
cebdb986
JA
4408 case IORING_OP_OPENAT2:
4409 ret = io_openat2_prep(req, sqe);
4410 break;
3e4827b0
JA
4411 case IORING_OP_EPOLL_CTL:
4412 ret = io_epoll_ctl_prep(req, sqe);
4413 break;
7d67af2c
PB
4414 case IORING_OP_SPLICE:
4415 ret = io_splice_prep(req, sqe);
4416 break;
f67676d1 4417 default:
e781573e
JA
4418 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
4419 req->opcode);
4420 ret = -EINVAL;
b7bb4f7d 4421 break;
f67676d1
JA
4422 }
4423
b7bb4f7d 4424 return ret;
f67676d1
JA
4425}
4426
3529d8c2 4427static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
de0617e4 4428{
a197f664 4429 struct io_ring_ctx *ctx = req->ctx;
f67676d1 4430 int ret;
de0617e4 4431
9d858b21
BL
4432 /* Still need defer if there is pending req in defer list. */
4433 if (!req_need_defer(req) && list_empty(&ctx->defer_list))
de0617e4
JA
4434 return 0;
4435
3529d8c2 4436 if (!req->io && io_alloc_async_ctx(req))
de0617e4
JA
4437 return -EAGAIN;
4438
3529d8c2 4439 ret = io_req_defer_prep(req, sqe);
b7bb4f7d 4440 if (ret < 0)
2d28390a 4441 return ret;
2d28390a 4442
de0617e4 4443 spin_lock_irq(&ctx->completion_lock);
9d858b21 4444 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
de0617e4 4445 spin_unlock_irq(&ctx->completion_lock);
de0617e4
JA
4446 return 0;
4447 }
4448
915967f6 4449 trace_io_uring_defer(ctx, req, req->user_data);
de0617e4
JA
4450 list_add_tail(&req->list, &ctx->defer_list);
4451 spin_unlock_irq(&ctx->completion_lock);
4452 return -EIOCBQUEUED;
4453}
4454
99bc4c38
PB
4455static void io_cleanup_req(struct io_kiocb *req)
4456{
4457 struct io_async_ctx *io = req->io;
4458
4459 switch (req->opcode) {
4460 case IORING_OP_READV:
4461 case IORING_OP_READ_FIXED:
4462 case IORING_OP_READ:
4463 case IORING_OP_WRITEV:
4464 case IORING_OP_WRITE_FIXED:
4465 case IORING_OP_WRITE:
4466 if (io->rw.iov != io->rw.fast_iov)
4467 kfree(io->rw.iov);
4468 break;
4469 case IORING_OP_SENDMSG:
4470 case IORING_OP_RECVMSG:
4471 if (io->msg.iov != io->msg.fast_iov)
4472 kfree(io->msg.iov);
4473 break;
8fef80bf
PB
4474 case IORING_OP_OPENAT:
4475 case IORING_OP_OPENAT2:
4476 case IORING_OP_STATX:
4477 putname(req->open.filename);
4478 break;
7d67af2c
PB
4479 case IORING_OP_SPLICE:
4480 io_put_file(req, req->splice.file_in,
4481 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
4482 break;
99bc4c38
PB
4483 }
4484
4485 req->flags &= ~REQ_F_NEED_CLEANUP;
4486}
4487
3529d8c2
JA
4488static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4489 struct io_kiocb **nxt, bool force_nonblock)
2b188cc1 4490{
a197f664 4491 struct io_ring_ctx *ctx = req->ctx;
d625c6ee 4492 int ret;
2b188cc1 4493
d625c6ee 4494 switch (req->opcode) {
2b188cc1 4495 case IORING_OP_NOP:
78e19bbe 4496 ret = io_nop(req);
2b188cc1
JA
4497 break;
4498 case IORING_OP_READV:
edafccee 4499 case IORING_OP_READ_FIXED:
3a6820f2 4500 case IORING_OP_READ:
3529d8c2
JA
4501 if (sqe) {
4502 ret = io_read_prep(req, sqe, force_nonblock);
4503 if (ret < 0)
4504 break;
4505 }
267bc904 4506 ret = io_read(req, nxt, force_nonblock);
edafccee 4507 break;
3529d8c2 4508 case IORING_OP_WRITEV:
edafccee 4509 case IORING_OP_WRITE_FIXED:
3a6820f2 4510 case IORING_OP_WRITE:
3529d8c2
JA
4511 if (sqe) {
4512 ret = io_write_prep(req, sqe, force_nonblock);
4513 if (ret < 0)
4514 break;
4515 }
267bc904 4516 ret = io_write(req, nxt, force_nonblock);
2b188cc1 4517 break;
c992fe29 4518 case IORING_OP_FSYNC:
3529d8c2
JA
4519 if (sqe) {
4520 ret = io_prep_fsync(req, sqe);
4521 if (ret < 0)
4522 break;
4523 }
fc4df999 4524 ret = io_fsync(req, nxt, force_nonblock);
c992fe29 4525 break;
221c5eb2 4526 case IORING_OP_POLL_ADD:
3529d8c2
JA
4527 if (sqe) {
4528 ret = io_poll_add_prep(req, sqe);
4529 if (ret)
4530 break;
4531 }
fc4df999 4532 ret = io_poll_add(req, nxt);
221c5eb2
JA
4533 break;
4534 case IORING_OP_POLL_REMOVE:
3529d8c2
JA
4535 if (sqe) {
4536 ret = io_poll_remove_prep(req, sqe);
4537 if (ret < 0)
4538 break;
4539 }
fc4df999 4540 ret = io_poll_remove(req);
221c5eb2 4541 break;
5d17b4a4 4542 case IORING_OP_SYNC_FILE_RANGE:
3529d8c2
JA
4543 if (sqe) {
4544 ret = io_prep_sfr(req, sqe);
4545 if (ret < 0)
4546 break;
4547 }
fc4df999 4548 ret = io_sync_file_range(req, nxt, force_nonblock);
5d17b4a4 4549 break;
0fa03c62 4550 case IORING_OP_SENDMSG:
fddaface 4551 case IORING_OP_SEND:
3529d8c2
JA
4552 if (sqe) {
4553 ret = io_sendmsg_prep(req, sqe);
4554 if (ret < 0)
4555 break;
4556 }
fddaface
JA
4557 if (req->opcode == IORING_OP_SENDMSG)
4558 ret = io_sendmsg(req, nxt, force_nonblock);
4559 else
4560 ret = io_send(req, nxt, force_nonblock);
0fa03c62 4561 break;
aa1fa28f 4562 case IORING_OP_RECVMSG:
fddaface 4563 case IORING_OP_RECV:
3529d8c2
JA
4564 if (sqe) {
4565 ret = io_recvmsg_prep(req, sqe);
4566 if (ret)
4567 break;
4568 }
fddaface
JA
4569 if (req->opcode == IORING_OP_RECVMSG)
4570 ret = io_recvmsg(req, nxt, force_nonblock);
4571 else
4572 ret = io_recv(req, nxt, force_nonblock);
aa1fa28f 4573 break;
5262f567 4574 case IORING_OP_TIMEOUT:
3529d8c2
JA
4575 if (sqe) {
4576 ret = io_timeout_prep(req, sqe, false);
4577 if (ret)
4578 break;
4579 }
fc4df999 4580 ret = io_timeout(req);
5262f567 4581 break;
11365043 4582 case IORING_OP_TIMEOUT_REMOVE:
3529d8c2
JA
4583 if (sqe) {
4584 ret = io_timeout_remove_prep(req, sqe);
4585 if (ret)
4586 break;
4587 }
fc4df999 4588 ret = io_timeout_remove(req);
11365043 4589 break;
17f2fe35 4590 case IORING_OP_ACCEPT:
3529d8c2
JA
4591 if (sqe) {
4592 ret = io_accept_prep(req, sqe);
4593 if (ret)
4594 break;
4595 }
fc4df999 4596 ret = io_accept(req, nxt, force_nonblock);
17f2fe35 4597 break;
f8e85cf2 4598 case IORING_OP_CONNECT:
3529d8c2
JA
4599 if (sqe) {
4600 ret = io_connect_prep(req, sqe);
4601 if (ret)
4602 break;
4603 }
fc4df999 4604 ret = io_connect(req, nxt, force_nonblock);
f8e85cf2 4605 break;
62755e35 4606 case IORING_OP_ASYNC_CANCEL:
3529d8c2
JA
4607 if (sqe) {
4608 ret = io_async_cancel_prep(req, sqe);
4609 if (ret)
4610 break;
4611 }
fc4df999 4612 ret = io_async_cancel(req, nxt);
62755e35 4613 break;
d63d1b5e
JA
4614 case IORING_OP_FALLOCATE:
4615 if (sqe) {
4616 ret = io_fallocate_prep(req, sqe);
4617 if (ret)
4618 break;
4619 }
4620 ret = io_fallocate(req, nxt, force_nonblock);
4621 break;
15b71abe
JA
4622 case IORING_OP_OPENAT:
4623 if (sqe) {
4624 ret = io_openat_prep(req, sqe);
4625 if (ret)
4626 break;
4627 }
4628 ret = io_openat(req, nxt, force_nonblock);
4629 break;
b5dba59e
JA
4630 case IORING_OP_CLOSE:
4631 if (sqe) {
4632 ret = io_close_prep(req, sqe);
4633 if (ret)
4634 break;
4635 }
4636 ret = io_close(req, nxt, force_nonblock);
4637 break;
05f3fb3c
JA
4638 case IORING_OP_FILES_UPDATE:
4639 if (sqe) {
4640 ret = io_files_update_prep(req, sqe);
4641 if (ret)
4642 break;
4643 }
4644 ret = io_files_update(req, force_nonblock);
4645 break;
eddc7ef5
JA
4646 case IORING_OP_STATX:
4647 if (sqe) {
4648 ret = io_statx_prep(req, sqe);
4649 if (ret)
4650 break;
4651 }
4652 ret = io_statx(req, nxt, force_nonblock);
4653 break;
4840e418
JA
4654 case IORING_OP_FADVISE:
4655 if (sqe) {
4656 ret = io_fadvise_prep(req, sqe);
4657 if (ret)
4658 break;
4659 }
4660 ret = io_fadvise(req, nxt, force_nonblock);
4661 break;
c1ca757b
JA
4662 case IORING_OP_MADVISE:
4663 if (sqe) {
4664 ret = io_madvise_prep(req, sqe);
4665 if (ret)
4666 break;
4667 }
4668 ret = io_madvise(req, nxt, force_nonblock);
4669 break;
cebdb986
JA
4670 case IORING_OP_OPENAT2:
4671 if (sqe) {
4672 ret = io_openat2_prep(req, sqe);
4673 if (ret)
4674 break;
4675 }
4676 ret = io_openat2(req, nxt, force_nonblock);
4677 break;
3e4827b0
JA
4678 case IORING_OP_EPOLL_CTL:
4679 if (sqe) {
4680 ret = io_epoll_ctl_prep(req, sqe);
4681 if (ret)
4682 break;
4683 }
4684 ret = io_epoll_ctl(req, nxt, force_nonblock);
4685 break;
7d67af2c
PB
4686 case IORING_OP_SPLICE:
4687 if (sqe) {
4688 ret = io_splice_prep(req, sqe);
4689 if (ret < 0)
4690 break;
4691 }
4692 ret = io_splice(req, nxt, force_nonblock);
4693 break;
2b188cc1
JA
4694 default:
4695 ret = -EINVAL;
4696 break;
4697 }
4698
def596e9
JA
4699 if (ret)
4700 return ret;
4701
4702 if (ctx->flags & IORING_SETUP_IOPOLL) {
11ba820b
JA
4703 const bool in_async = io_wq_current_is_worker();
4704
9e645e11 4705 if (req->result == -EAGAIN)
def596e9
JA
4706 return -EAGAIN;
4707
11ba820b
JA
4708 /* workqueue context doesn't hold uring_lock, grab it now */
4709 if (in_async)
4710 mutex_lock(&ctx->uring_lock);
4711
def596e9 4712 io_iopoll_req_issued(req);
11ba820b
JA
4713
4714 if (in_async)
4715 mutex_unlock(&ctx->uring_lock);
def596e9
JA
4716 }
4717
4718 return 0;
2b188cc1
JA
4719}
4720
561fb04a 4721static void io_wq_submit_work(struct io_wq_work **workptr)
2b188cc1 4722{
561fb04a 4723 struct io_wq_work *work = *workptr;
2b188cc1 4724 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
561fb04a
JA
4725 struct io_kiocb *nxt = NULL;
4726 int ret = 0;
2b188cc1 4727
0c9d5ccd
JA
4728 /* if NO_CANCEL is set, we must still run the work */
4729 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
4730 IO_WQ_WORK_CANCEL) {
561fb04a 4731 ret = -ECANCELED;
0c9d5ccd 4732 }
31b51510 4733
561fb04a 4734 if (!ret) {
561fb04a 4735 do {
3529d8c2 4736 ret = io_issue_sqe(req, NULL, &nxt, false);
561fb04a
JA
4737 /*
4738 * We can get EAGAIN for polled IO even though we're
4739 * forcing a sync submission from here, since we can't
4740 * wait for request slots on the block side.
4741 */
4742 if (ret != -EAGAIN)
4743 break;
4744 cond_resched();
4745 } while (1);
4746 }
31b51510 4747
561fb04a 4748 /* drop submission reference */
ec9c02ad 4749 io_put_req(req);
817869d2 4750
561fb04a 4751 if (ret) {
4e88d6e7 4752 req_set_fail_links(req);
78e19bbe 4753 io_cqring_add_event(req, ret);
817869d2 4754 io_put_req(req);
edafccee 4755 }
2b188cc1 4756
561fb04a 4757 /* if a dependent link is ready, pass it back */
78912934
JA
4758 if (!ret && nxt)
4759 io_wq_assign_next(workptr, nxt);
2b188cc1
JA
4760}
4761
15b71abe 4762static int io_req_needs_file(struct io_kiocb *req, int fd)
9e3aa61a 4763{
d3656344 4764 if (!io_op_defs[req->opcode].needs_file)
9e3aa61a 4765 return 0;
0b5faf6b 4766 if ((fd == -1 || fd == AT_FDCWD) && io_op_defs[req->opcode].fd_non_neg)
d3656344
JA
4767 return 0;
4768 return 1;
09bb8394
JA
4769}
4770
65e19f54
JA
4771static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
4772 int index)
4773{
4774 struct fixed_file_table *table;
4775
05f3fb3c
JA
4776 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
4777 return table->files[index & IORING_FILE_TABLE_MASK];;
65e19f54
JA
4778}
4779
8da11c19
PB
4780static int io_file_get(struct io_submit_state *state, struct io_kiocb *req,
4781 int fd, struct file **out_file, bool fixed)
09bb8394 4782{
a197f664 4783 struct io_ring_ctx *ctx = req->ctx;
8da11c19 4784 struct file *file;
09bb8394 4785
8da11c19 4786 if (fixed) {
05f3fb3c 4787 if (unlikely(!ctx->file_data ||
09bb8394
JA
4788 (unsigned) fd >= ctx->nr_user_files))
4789 return -EBADF;
b7620121 4790 fd = array_index_nospec(fd, ctx->nr_user_files);
8da11c19
PB
4791 file = io_file_from_index(ctx, fd);
4792 if (!file)
08a45173 4793 return -EBADF;
05f3fb3c 4794 percpu_ref_get(&ctx->file_data->refs);
09bb8394 4795 } else {
c826bd7a 4796 trace_io_uring_file_get(ctx, fd);
8da11c19
PB
4797 file = __io_file_get(state, fd);
4798 if (unlikely(!file))
09bb8394
JA
4799 return -EBADF;
4800 }
4801
8da11c19 4802 *out_file = file;
09bb8394
JA
4803 return 0;
4804}
4805
8da11c19
PB
4806static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
4807 const struct io_uring_sqe *sqe)
4808{
4809 unsigned flags;
4810 int fd;
4811 bool fixed;
4812
4813 flags = READ_ONCE(sqe->flags);
4814 fd = READ_ONCE(sqe->fd);
4815
4816 if (!io_req_needs_file(req, fd))
4817 return 0;
4818
4819 fixed = (flags & IOSQE_FIXED_FILE);
4820 if (unlikely(!fixed && req->needs_fixed_file))
4821 return -EBADF;
4822
4823 return io_file_get(state, req, fd, &req->file, fixed);
4824}
4825
a197f664 4826static int io_grab_files(struct io_kiocb *req)
fcb323cc
JA
4827{
4828 int ret = -EBADF;
a197f664 4829 struct io_ring_ctx *ctx = req->ctx;
fcb323cc 4830
f86cd20c
JA
4831 if (req->work.files)
4832 return 0;
b14cca0c 4833 if (!ctx->ring_file)
b5dba59e
JA
4834 return -EBADF;
4835
fcb323cc
JA
4836 rcu_read_lock();
4837 spin_lock_irq(&ctx->inflight_lock);
4838 /*
4839 * We use the f_ops->flush() handler to ensure that we can flush
4840 * out work accessing these files if the fd is closed. Check if
4841 * the fd has changed since we started down this path, and disallow
4842 * this operation if it has.
4843 */
b14cca0c 4844 if (fcheck(ctx->ring_fd) == ctx->ring_file) {
fcb323cc
JA
4845 list_add(&req->inflight_entry, &ctx->inflight_list);
4846 req->flags |= REQ_F_INFLIGHT;
4847 req->work.files = current->files;
4848 ret = 0;
4849 }
4850 spin_unlock_irq(&ctx->inflight_lock);
4851 rcu_read_unlock();
4852
4853 return ret;
4854}
4855
2665abfd 4856static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
2b188cc1 4857{
ad8a48ac
JA
4858 struct io_timeout_data *data = container_of(timer,
4859 struct io_timeout_data, timer);
4860 struct io_kiocb *req = data->req;
2665abfd
JA
4861 struct io_ring_ctx *ctx = req->ctx;
4862 struct io_kiocb *prev = NULL;
4863 unsigned long flags;
2665abfd
JA
4864
4865 spin_lock_irqsave(&ctx->completion_lock, flags);
4866
4867 /*
4868 * We don't expect the list to be empty, that will only happen if we
4869 * race with the completion of the linked work.
4870 */
4493233e
PB
4871 if (!list_empty(&req->link_list)) {
4872 prev = list_entry(req->link_list.prev, struct io_kiocb,
4873 link_list);
5d960724 4874 if (refcount_inc_not_zero(&prev->refs)) {
4493233e 4875 list_del_init(&req->link_list);
5d960724
JA
4876 prev->flags &= ~REQ_F_LINK_TIMEOUT;
4877 } else
76a46e06 4878 prev = NULL;
2665abfd
JA
4879 }
4880
4881 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4882
4883 if (prev) {
4e88d6e7 4884 req_set_fail_links(prev);
b0dd8a41
JA
4885 io_async_find_and_cancel(ctx, req, prev->user_data, NULL,
4886 -ETIME);
76a46e06 4887 io_put_req(prev);
47f46768
JA
4888 } else {
4889 io_cqring_add_event(req, -ETIME);
4890 io_put_req(req);
2665abfd 4891 }
2665abfd
JA
4892 return HRTIMER_NORESTART;
4893}
4894
ad8a48ac 4895static void io_queue_linked_timeout(struct io_kiocb *req)
2665abfd 4896{
76a46e06 4897 struct io_ring_ctx *ctx = req->ctx;
2665abfd 4898
76a46e06
JA
4899 /*
4900 * If the list is now empty, then our linked request finished before
4901 * we got a chance to setup the timer
4902 */
4903 spin_lock_irq(&ctx->completion_lock);
4493233e 4904 if (!list_empty(&req->link_list)) {
2d28390a 4905 struct io_timeout_data *data = &req->io->timeout;
94ae5e77 4906
ad8a48ac
JA
4907 data->timer.function = io_link_timeout_fn;
4908 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
4909 data->mode);
2665abfd 4910 }
76a46e06 4911 spin_unlock_irq(&ctx->completion_lock);
2665abfd 4912
2665abfd 4913 /* drop submission reference */
76a46e06
JA
4914 io_put_req(req);
4915}
2665abfd 4916
ad8a48ac 4917static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
2665abfd
JA
4918{
4919 struct io_kiocb *nxt;
4920
4921 if (!(req->flags & REQ_F_LINK))
4922 return NULL;
d7718a9d
JA
4923 /* for polled retry, if flag is set, we already went through here */
4924 if (req->flags & REQ_F_POLLED)
4925 return NULL;
2665abfd 4926
4493233e
PB
4927 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
4928 link_list);
d625c6ee 4929 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
76a46e06 4930 return NULL;
2665abfd 4931
76a46e06 4932 req->flags |= REQ_F_LINK_TIMEOUT;
76a46e06 4933 return nxt;
2665abfd
JA
4934}
4935
3529d8c2 4936static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2b188cc1 4937{
4a0a7a18 4938 struct io_kiocb *linked_timeout;
f9bd67f6 4939 struct io_kiocb *nxt = NULL;
193155c8 4940 const struct cred *old_creds = NULL;
e0c5c576 4941 int ret;
2b188cc1 4942
4a0a7a18
JA
4943again:
4944 linked_timeout = io_prep_linked_timeout(req);
4945
193155c8
JA
4946 if (req->work.creds && req->work.creds != current_cred()) {
4947 if (old_creds)
4948 revert_creds(old_creds);
4949 if (old_creds == req->work.creds)
4950 old_creds = NULL; /* restored original creds */
4951 else
4952 old_creds = override_creds(req->work.creds);
4953 }
4954
3529d8c2 4955 ret = io_issue_sqe(req, sqe, &nxt, true);
491381ce
JA
4956
4957 /*
4958 * We async punt it if the file wasn't marked NOWAIT, or if the file
4959 * doesn't support non-blocking read/write attempts
4960 */
4961 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
4962 (req->flags & REQ_F_MUST_PUNT))) {
d7718a9d
JA
4963 if (io_arm_poll_handler(req)) {
4964 if (linked_timeout)
4965 io_queue_linked_timeout(linked_timeout);
4966 goto done_req;
4967 }
86a761f8 4968punt:
f86cd20c 4969 if (io_op_defs[req->opcode].file_table) {
bbad27b2
PB
4970 ret = io_grab_files(req);
4971 if (ret)
4972 goto err;
2b188cc1 4973 }
bbad27b2
PB
4974
4975 /*
4976 * Queued up for async execution, worker will release
4977 * submit reference when the iocb is actually submitted.
4978 */
4979 io_queue_async_work(req);
4a0a7a18 4980 goto done_req;
2b188cc1 4981 }
e65ef56d 4982
fcb323cc 4983err:
76a46e06 4984 /* drop submission reference */
2a44f467 4985 io_put_req_find_next(req, &nxt);
e65ef56d 4986
f9bd67f6 4987 if (linked_timeout) {
76a46e06 4988 if (!ret)
f9bd67f6 4989 io_queue_linked_timeout(linked_timeout);
76a46e06 4990 else
f9bd67f6 4991 io_put_req(linked_timeout);
76a46e06
JA
4992 }
4993
e65ef56d 4994 /* and drop final reference, if we failed */
9e645e11 4995 if (ret) {
78e19bbe 4996 io_cqring_add_event(req, ret);
4e88d6e7 4997 req_set_fail_links(req);
e65ef56d 4998 io_put_req(req);
9e645e11 4999 }
4a0a7a18
JA
5000done_req:
5001 if (nxt) {
5002 req = nxt;
5003 nxt = NULL;
86a761f8
PB
5004
5005 if (req->flags & REQ_F_FORCE_ASYNC)
5006 goto punt;
4a0a7a18
JA
5007 goto again;
5008 }
193155c8
JA
5009 if (old_creds)
5010 revert_creds(old_creds);
2b188cc1
JA
5011}
5012
3529d8c2 5013static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4fe2c963
JL
5014{
5015 int ret;
5016
3529d8c2 5017 ret = io_req_defer(req, sqe);
4fe2c963
JL
5018 if (ret) {
5019 if (ret != -EIOCBQUEUED) {
1118591a 5020fail_req:
78e19bbe 5021 io_cqring_add_event(req, ret);
4e88d6e7 5022 req_set_fail_links(req);
78e19bbe 5023 io_double_put_req(req);
4fe2c963 5024 }
2550878f 5025 } else if (req->flags & REQ_F_FORCE_ASYNC) {
1118591a
PB
5026 ret = io_req_defer_prep(req, sqe);
5027 if (unlikely(ret < 0))
5028 goto fail_req;
ce35a47a
JA
5029 /*
5030 * Never try inline submit of IOSQE_ASYNC is set, go straight
5031 * to async execution.
5032 */
5033 req->work.flags |= IO_WQ_WORK_CONCURRENT;
5034 io_queue_async_work(req);
5035 } else {
3529d8c2 5036 __io_queue_sqe(req, sqe);
ce35a47a 5037 }
4fe2c963
JL
5038}
5039
1b4a51b6 5040static inline void io_queue_link_head(struct io_kiocb *req)
4fe2c963 5041{
94ae5e77 5042 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
1b4a51b6
PB
5043 io_cqring_add_event(req, -ECANCELED);
5044 io_double_put_req(req);
5045 } else
3529d8c2 5046 io_queue_sqe(req, NULL);
4fe2c963
JL
5047}
5048
4e88d6e7 5049#define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
ce35a47a 5050 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
9e645e11 5051
3529d8c2
JA
5052static bool io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5053 struct io_submit_state *state, struct io_kiocb **link)
9e645e11 5054{
a197f664 5055 struct io_ring_ctx *ctx = req->ctx;
32fe525b 5056 unsigned int sqe_flags;
75c6a039 5057 int ret, id;
9e645e11 5058
32fe525b 5059 sqe_flags = READ_ONCE(sqe->flags);
9e645e11
JA
5060
5061 /* enforce forwards compatibility on users */
32fe525b 5062 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
9e645e11 5063 ret = -EINVAL;
196be95c 5064 goto err_req;
9e645e11
JA
5065 }
5066
75c6a039
JA
5067 id = READ_ONCE(sqe->personality);
5068 if (id) {
193155c8
JA
5069 req->work.creds = idr_find(&ctx->personality_idr, id);
5070 if (unlikely(!req->work.creds)) {
75c6a039
JA
5071 ret = -EINVAL;
5072 goto err_req;
5073 }
193155c8 5074 get_cred(req->work.creds);
75c6a039
JA
5075 }
5076
6b47ee6e 5077 /* same numerical values with corresponding REQ_F_*, safe to copy */
8da11c19
PB
5078 req->flags |= sqe_flags & (IOSQE_IO_DRAIN | IOSQE_IO_HARDLINK |
5079 IOSQE_ASYNC | IOSQE_FIXED_FILE);
9e645e11 5080
3529d8c2 5081 ret = io_req_set_file(state, req, sqe);
9e645e11
JA
5082 if (unlikely(ret)) {
5083err_req:
78e19bbe
JA
5084 io_cqring_add_event(req, ret);
5085 io_double_put_req(req);
2e6e1fde 5086 return false;
9e645e11
JA
5087 }
5088
9e645e11
JA
5089 /*
5090 * If we already have a head request, queue this one for async
5091 * submittal once the head completes. If we don't have a head but
5092 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
5093 * submitted sync once the chain is complete. If none of those
5094 * conditions are true (normal request), then just queue it.
5095 */
5096 if (*link) {
9d76377f 5097 struct io_kiocb *head = *link;
4e88d6e7 5098
8cdf2193
PB
5099 /*
5100 * Taking sequential execution of a link, draining both sides
5101 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
5102 * requests in the link. So, it drains the head and the
5103 * next after the link request. The last one is done via
5104 * drain_next flag to persist the effect across calls.
5105 */
711be031
PB
5106 if (sqe_flags & IOSQE_IO_DRAIN) {
5107 head->flags |= REQ_F_IO_DRAIN;
5108 ctx->drain_next = 1;
5109 }
b7bb4f7d 5110 if (io_alloc_async_ctx(req)) {
9e645e11
JA
5111 ret = -EAGAIN;
5112 goto err_req;
5113 }
5114
3529d8c2 5115 ret = io_req_defer_prep(req, sqe);
2d28390a 5116 if (ret) {
4e88d6e7 5117 /* fail even hard links since we don't submit */
9d76377f 5118 head->flags |= REQ_F_FAIL_LINK;
f67676d1 5119 goto err_req;
2d28390a 5120 }
9d76377f
PB
5121 trace_io_uring_link(ctx, req, head);
5122 list_add_tail(&req->link_list, &head->link_list);
32fe525b
PB
5123
5124 /* last request of a link, enqueue the link */
5125 if (!(sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK))) {
5126 io_queue_link_head(head);
5127 *link = NULL;
5128 }
9e645e11 5129 } else {
711be031
PB
5130 if (unlikely(ctx->drain_next)) {
5131 req->flags |= REQ_F_IO_DRAIN;
5132 req->ctx->drain_next = 0;
5133 }
5134 if (sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK)) {
5135 req->flags |= REQ_F_LINK;
711be031
PB
5136 INIT_LIST_HEAD(&req->link_list);
5137 ret = io_req_defer_prep(req, sqe);
5138 if (ret)
5139 req->flags |= REQ_F_FAIL_LINK;
5140 *link = req;
5141 } else {
5142 io_queue_sqe(req, sqe);
5143 }
9e645e11 5144 }
2e6e1fde
PB
5145
5146 return true;
9e645e11
JA
5147}
5148
9a56a232
JA
5149/*
5150 * Batched submission is done, ensure local IO is flushed out.
5151 */
5152static void io_submit_state_end(struct io_submit_state *state)
5153{
5154 blk_finish_plug(&state->plug);
3d6770fb 5155 io_file_put(state);
2579f913 5156 if (state->free_reqs)
6c8a3134 5157 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
9a56a232
JA
5158}
5159
5160/*
5161 * Start submission side cache.
5162 */
5163static void io_submit_state_start(struct io_submit_state *state,
22efde59 5164 unsigned int max_ios)
9a56a232
JA
5165{
5166 blk_start_plug(&state->plug);
2579f913 5167 state->free_reqs = 0;
9a56a232
JA
5168 state->file = NULL;
5169 state->ios_left = max_ios;
5170}
5171
2b188cc1
JA
5172static void io_commit_sqring(struct io_ring_ctx *ctx)
5173{
75b28aff 5174 struct io_rings *rings = ctx->rings;
2b188cc1 5175
caf582c6
PB
5176 /*
5177 * Ensure any loads from the SQEs are done at this point,
5178 * since once we write the new head, the application could
5179 * write new data to them.
5180 */
5181 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2b188cc1
JA
5182}
5183
2b188cc1 5184/*
3529d8c2 5185 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
2b188cc1
JA
5186 * that is mapped by userspace. This means that care needs to be taken to
5187 * ensure that reads are stable, as we cannot rely on userspace always
5188 * being a good citizen. If members of the sqe are validated and then later
5189 * used, it's important that those reads are done through READ_ONCE() to
5190 * prevent a re-load down the line.
5191 */
3529d8c2
JA
5192static bool io_get_sqring(struct io_ring_ctx *ctx, struct io_kiocb *req,
5193 const struct io_uring_sqe **sqe_ptr)
2b188cc1 5194{
75b28aff 5195 u32 *sq_array = ctx->sq_array;
2b188cc1
JA
5196 unsigned head;
5197
5198 /*
5199 * The cached sq head (or cq tail) serves two purposes:
5200 *
5201 * 1) allows us to batch the cost of updating the user visible
5202 * head updates.
5203 * 2) allows the kernel side to track the head on its own, even
5204 * though the application is the one updating it.
5205 */
ee7d46d9 5206 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
9835d6fa 5207 if (likely(head < ctx->sq_entries)) {
cf6fd4bd
PB
5208 /*
5209 * All io need record the previous position, if LINK vs DARIN,
5210 * it can be used to mark the position of the first IO in the
5211 * link list.
5212 */
5213 req->sequence = ctx->cached_sq_head;
3529d8c2
JA
5214 *sqe_ptr = &ctx->sq_sqes[head];
5215 req->opcode = READ_ONCE((*sqe_ptr)->opcode);
5216 req->user_data = READ_ONCE((*sqe_ptr)->user_data);
2b188cc1
JA
5217 ctx->cached_sq_head++;
5218 return true;
5219 }
5220
5221 /* drop invalid entries */
5222 ctx->cached_sq_head++;
498ccd9e 5223 ctx->cached_sq_dropped++;
ee7d46d9 5224 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
2b188cc1
JA
5225 return false;
5226}
5227
fb5ccc98 5228static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
ae9428ca
PB
5229 struct file *ring_file, int ring_fd,
5230 struct mm_struct **mm, bool async)
6c271ce2
JA
5231{
5232 struct io_submit_state state, *statep = NULL;
9e645e11 5233 struct io_kiocb *link = NULL;
9e645e11 5234 int i, submitted = 0;
95a1b3ff 5235 bool mm_fault = false;
6c271ce2 5236
c4a2ed72 5237 /* if we have a backlog and couldn't flush it all, return BUSY */
ad3eb2c8
JA
5238 if (test_bit(0, &ctx->sq_check_overflow)) {
5239 if (!list_empty(&ctx->cq_overflow_list) &&
5240 !io_cqring_overflow_flush(ctx, false))
5241 return -EBUSY;
5242 }
6c271ce2 5243
ee7d46d9
PB
5244 /* make sure SQ entry isn't read before tail */
5245 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
9ef4f124 5246
2b85edfc
PB
5247 if (!percpu_ref_tryget_many(&ctx->refs, nr))
5248 return -EAGAIN;
6c271ce2
JA
5249
5250 if (nr > IO_PLUG_THRESHOLD) {
22efde59 5251 io_submit_state_start(&state, nr);
6c271ce2
JA
5252 statep = &state;
5253 }
5254
b14cca0c
PB
5255 ctx->ring_fd = ring_fd;
5256 ctx->ring_file = ring_file;
5257
6c271ce2 5258 for (i = 0; i < nr; i++) {
3529d8c2 5259 const struct io_uring_sqe *sqe;
196be95c 5260 struct io_kiocb *req;
1cb1edb2 5261 int err;
fb5ccc98 5262
196be95c
PB
5263 req = io_get_req(ctx, statep);
5264 if (unlikely(!req)) {
5265 if (!submitted)
5266 submitted = -EAGAIN;
fb5ccc98 5267 break;
196be95c 5268 }
3529d8c2 5269 if (!io_get_sqring(ctx, req, &sqe)) {
2b85edfc 5270 __io_req_do_free(req);
196be95c
PB
5271 break;
5272 }
fb5ccc98 5273
d3656344
JA
5274 /* will complete beyond this point, count as submitted */
5275 submitted++;
5276
5277 if (unlikely(req->opcode >= IORING_OP_LAST)) {
1cb1edb2
PB
5278 err = -EINVAL;
5279fail_req:
5280 io_cqring_add_event(req, err);
d3656344 5281 io_double_put_req(req);
196be95c
PB
5282 break;
5283 }
fb5ccc98 5284
d3656344 5285 if (io_op_defs[req->opcode].needs_mm && !*mm) {
95a1b3ff 5286 mm_fault = mm_fault || !mmget_not_zero(ctx->sqo_mm);
1cb1edb2
PB
5287 if (unlikely(mm_fault)) {
5288 err = -EFAULT;
5289 goto fail_req;
95a1b3ff 5290 }
1cb1edb2
PB
5291 use_mm(ctx->sqo_mm);
5292 *mm = ctx->sqo_mm;
9e645e11 5293 }
9e645e11 5294
cf6fd4bd 5295 req->needs_fixed_file = async;
354420f7
JA
5296 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
5297 true, async);
3529d8c2 5298 if (!io_submit_sqe(req, sqe, statep, &link))
2e6e1fde 5299 break;
6c271ce2
JA
5300 }
5301
9466f437
PB
5302 if (unlikely(submitted != nr)) {
5303 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
5304
5305 percpu_ref_put_many(&ctx->refs, nr - ref_used);
5306 }
9e645e11 5307 if (link)
1b4a51b6 5308 io_queue_link_head(link);
6c271ce2
JA
5309 if (statep)
5310 io_submit_state_end(&state);
5311
ae9428ca
PB
5312 /* Commit SQ ring head once we've consumed and submitted all SQEs */
5313 io_commit_sqring(ctx);
5314
6c271ce2
JA
5315 return submitted;
5316}
5317
5318static int io_sq_thread(void *data)
5319{
6c271ce2
JA
5320 struct io_ring_ctx *ctx = data;
5321 struct mm_struct *cur_mm = NULL;
181e448d 5322 const struct cred *old_cred;
6c271ce2
JA
5323 mm_segment_t old_fs;
5324 DEFINE_WAIT(wait);
6c271ce2 5325 unsigned long timeout;
bdcd3eab 5326 int ret = 0;
6c271ce2 5327
206aefde 5328 complete(&ctx->completions[1]);
a4c0b3de 5329
6c271ce2
JA
5330 old_fs = get_fs();
5331 set_fs(USER_DS);
181e448d 5332 old_cred = override_creds(ctx->creds);
6c271ce2 5333
bdcd3eab 5334 timeout = jiffies + ctx->sq_thread_idle;
2bbcd6d3 5335 while (!kthread_should_park()) {
fb5ccc98 5336 unsigned int to_submit;
6c271ce2 5337
bdcd3eab 5338 if (!list_empty(&ctx->poll_list)) {
6c271ce2
JA
5339 unsigned nr_events = 0;
5340
bdcd3eab
XW
5341 mutex_lock(&ctx->uring_lock);
5342 if (!list_empty(&ctx->poll_list))
5343 io_iopoll_getevents(ctx, &nr_events, 0);
5344 else
6c271ce2 5345 timeout = jiffies + ctx->sq_thread_idle;
bdcd3eab 5346 mutex_unlock(&ctx->uring_lock);
6c271ce2
JA
5347 }
5348
fb5ccc98 5349 to_submit = io_sqring_entries(ctx);
c1edbf5f
JA
5350
5351 /*
5352 * If submit got -EBUSY, flag us as needing the application
5353 * to enter the kernel to reap and flush events.
5354 */
5355 if (!to_submit || ret == -EBUSY) {
7143b5ac
SG
5356 /*
5357 * Drop cur_mm before scheduling, we can't hold it for
5358 * long periods (or over schedule()). Do this before
5359 * adding ourselves to the waitqueue, as the unuse/drop
5360 * may sleep.
5361 */
5362 if (cur_mm) {
5363 unuse_mm(cur_mm);
5364 mmput(cur_mm);
5365 cur_mm = NULL;
5366 }
5367
6c271ce2
JA
5368 /*
5369 * We're polling. If we're within the defined idle
5370 * period, then let us spin without work before going
c1edbf5f
JA
5371 * to sleep. The exception is if we got EBUSY doing
5372 * more IO, we should wait for the application to
5373 * reap events and wake us up.
6c271ce2 5374 */
bdcd3eab 5375 if (!list_empty(&ctx->poll_list) ||
df069d80
JA
5376 (!time_after(jiffies, timeout) && ret != -EBUSY &&
5377 !percpu_ref_is_dying(&ctx->refs))) {
b41e9852
JA
5378 if (current->task_works)
5379 task_work_run();
9831a90c 5380 cond_resched();
6c271ce2
JA
5381 continue;
5382 }
5383
6c271ce2
JA
5384 prepare_to_wait(&ctx->sqo_wait, &wait,
5385 TASK_INTERRUPTIBLE);
5386
bdcd3eab
XW
5387 /*
5388 * While doing polled IO, before going to sleep, we need
5389 * to check if there are new reqs added to poll_list, it
5390 * is because reqs may have been punted to io worker and
5391 * will be added to poll_list later, hence check the
5392 * poll_list again.
5393 */
5394 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
5395 !list_empty_careful(&ctx->poll_list)) {
5396 finish_wait(&ctx->sqo_wait, &wait);
5397 continue;
5398 }
5399
6c271ce2 5400 /* Tell userspace we may need a wakeup call */
75b28aff 5401 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
0d7bae69
SB
5402 /* make sure to read SQ tail after writing flags */
5403 smp_mb();
6c271ce2 5404
fb5ccc98 5405 to_submit = io_sqring_entries(ctx);
c1edbf5f 5406 if (!to_submit || ret == -EBUSY) {
2bbcd6d3 5407 if (kthread_should_park()) {
6c271ce2
JA
5408 finish_wait(&ctx->sqo_wait, &wait);
5409 break;
5410 }
b41e9852
JA
5411 if (current->task_works) {
5412 task_work_run();
5413 continue;
5414 }
6c271ce2
JA
5415 if (signal_pending(current))
5416 flush_signals(current);
5417 schedule();
5418 finish_wait(&ctx->sqo_wait, &wait);
5419
75b28aff 5420 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6c271ce2
JA
5421 continue;
5422 }
5423 finish_wait(&ctx->sqo_wait, &wait);
5424
75b28aff 5425 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6c271ce2
JA
5426 }
5427
8a4955ff 5428 mutex_lock(&ctx->uring_lock);
1d7bb1d5 5429 ret = io_submit_sqes(ctx, to_submit, NULL, -1, &cur_mm, true);
8a4955ff 5430 mutex_unlock(&ctx->uring_lock);
bdcd3eab 5431 timeout = jiffies + ctx->sq_thread_idle;
6c271ce2
JA
5432 }
5433
b41e9852
JA
5434 if (current->task_works)
5435 task_work_run();
5436
6c271ce2
JA
5437 set_fs(old_fs);
5438 if (cur_mm) {
5439 unuse_mm(cur_mm);
5440 mmput(cur_mm);
5441 }
181e448d 5442 revert_creds(old_cred);
06058632 5443
2bbcd6d3 5444 kthread_parkme();
06058632 5445
6c271ce2
JA
5446 return 0;
5447}
5448
bda52162
JA
5449struct io_wait_queue {
5450 struct wait_queue_entry wq;
5451 struct io_ring_ctx *ctx;
5452 unsigned to_wait;
5453 unsigned nr_timeouts;
5454};
5455
1d7bb1d5 5456static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
bda52162
JA
5457{
5458 struct io_ring_ctx *ctx = iowq->ctx;
5459
5460 /*
d195a66e 5461 * Wake up if we have enough events, or if a timeout occurred since we
bda52162
JA
5462 * started waiting. For timeouts, we always want to return to userspace,
5463 * regardless of event count.
5464 */
1d7bb1d5 5465 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
bda52162
JA
5466 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
5467}
5468
5469static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
5470 int wake_flags, void *key)
5471{
5472 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
5473 wq);
5474
1d7bb1d5
JA
5475 /* use noflush == true, as we can't safely rely on locking context */
5476 if (!io_should_wake(iowq, true))
bda52162
JA
5477 return -1;
5478
5479 return autoremove_wake_function(curr, mode, wake_flags, key);
5480}
5481
2b188cc1
JA
5482/*
5483 * Wait until events become available, if we don't already have some. The
5484 * application must reap them itself, as they reside on the shared cq ring.
5485 */
5486static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
5487 const sigset_t __user *sig, size_t sigsz)
5488{
bda52162
JA
5489 struct io_wait_queue iowq = {
5490 .wq = {
5491 .private = current,
5492 .func = io_wake_function,
5493 .entry = LIST_HEAD_INIT(iowq.wq.entry),
5494 },
5495 .ctx = ctx,
5496 .to_wait = min_events,
5497 };
75b28aff 5498 struct io_rings *rings = ctx->rings;
e9ffa5c2 5499 int ret = 0;
2b188cc1 5500
b41e9852
JA
5501 do {
5502 if (io_cqring_events(ctx, false) >= min_events)
5503 return 0;
5504 if (!current->task_works)
5505 break;
5506 task_work_run();
5507 } while (1);
2b188cc1
JA
5508
5509 if (sig) {
9e75ad5d
AB
5510#ifdef CONFIG_COMPAT
5511 if (in_compat_syscall())
5512 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
b772434b 5513 sigsz);
9e75ad5d
AB
5514 else
5515#endif
b772434b 5516 ret = set_user_sigmask(sig, sigsz);
9e75ad5d 5517
2b188cc1
JA
5518 if (ret)
5519 return ret;
5520 }
5521
bda52162 5522 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
c826bd7a 5523 trace_io_uring_cqring_wait(ctx, min_events);
bda52162
JA
5524 do {
5525 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
5526 TASK_INTERRUPTIBLE);
b41e9852
JA
5527 if (current->task_works)
5528 task_work_run();
1d7bb1d5 5529 if (io_should_wake(&iowq, false))
bda52162
JA
5530 break;
5531 schedule();
5532 if (signal_pending(current)) {
e9ffa5c2 5533 ret = -EINTR;
bda52162
JA
5534 break;
5535 }
5536 } while (1);
5537 finish_wait(&ctx->wait, &iowq.wq);
5538
e9ffa5c2 5539 restore_saved_sigmask_unless(ret == -EINTR);
2b188cc1 5540
75b28aff 5541 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
2b188cc1
JA
5542}
5543
6b06314c
JA
5544static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
5545{
5546#if defined(CONFIG_UNIX)
5547 if (ctx->ring_sock) {
5548 struct sock *sock = ctx->ring_sock->sk;
5549 struct sk_buff *skb;
5550
5551 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
5552 kfree_skb(skb);
5553 }
5554#else
5555 int i;
5556
65e19f54
JA
5557 for (i = 0; i < ctx->nr_user_files; i++) {
5558 struct file *file;
5559
5560 file = io_file_from_index(ctx, i);
5561 if (file)
5562 fput(file);
5563 }
6b06314c
JA
5564#endif
5565}
5566
05f3fb3c
JA
5567static void io_file_ref_kill(struct percpu_ref *ref)
5568{
5569 struct fixed_file_data *data;
5570
5571 data = container_of(ref, struct fixed_file_data, refs);
5572 complete(&data->done);
5573}
5574
6b06314c
JA
5575static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
5576{
05f3fb3c 5577 struct fixed_file_data *data = ctx->file_data;
65e19f54
JA
5578 unsigned nr_tables, i;
5579
05f3fb3c 5580 if (!data)
6b06314c
JA
5581 return -ENXIO;
5582
05f3fb3c 5583 percpu_ref_kill_and_confirm(&data->refs, io_file_ref_kill);
e46a7950 5584 flush_work(&data->ref_work);
2faf852d
JA
5585 wait_for_completion(&data->done);
5586 io_ring_file_ref_flush(data);
05f3fb3c
JA
5587 percpu_ref_exit(&data->refs);
5588
6b06314c 5589 __io_sqe_files_unregister(ctx);
65e19f54
JA
5590 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
5591 for (i = 0; i < nr_tables; i++)
05f3fb3c
JA
5592 kfree(data->table[i].files);
5593 kfree(data->table);
5594 kfree(data);
5595 ctx->file_data = NULL;
6b06314c
JA
5596 ctx->nr_user_files = 0;
5597 return 0;
5598}
5599
6c271ce2
JA
5600static void io_sq_thread_stop(struct io_ring_ctx *ctx)
5601{
5602 if (ctx->sqo_thread) {
206aefde 5603 wait_for_completion(&ctx->completions[1]);
2bbcd6d3
RP
5604 /*
5605 * The park is a bit of a work-around, without it we get
5606 * warning spews on shutdown with SQPOLL set and affinity
5607 * set to a single CPU.
5608 */
06058632 5609 kthread_park(ctx->sqo_thread);
6c271ce2
JA
5610 kthread_stop(ctx->sqo_thread);
5611 ctx->sqo_thread = NULL;
5612 }
5613}
5614
6b06314c
JA
5615static void io_finish_async(struct io_ring_ctx *ctx)
5616{
6c271ce2
JA
5617 io_sq_thread_stop(ctx);
5618
561fb04a
JA
5619 if (ctx->io_wq) {
5620 io_wq_destroy(ctx->io_wq);
5621 ctx->io_wq = NULL;
6b06314c
JA
5622 }
5623}
5624
5625#if defined(CONFIG_UNIX)
6b06314c
JA
5626/*
5627 * Ensure the UNIX gc is aware of our file set, so we are certain that
5628 * the io_uring can be safely unregistered on process exit, even if we have
5629 * loops in the file referencing.
5630 */
5631static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
5632{
5633 struct sock *sk = ctx->ring_sock->sk;
5634 struct scm_fp_list *fpl;
5635 struct sk_buff *skb;
08a45173 5636 int i, nr_files;
6b06314c
JA
5637
5638 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
5639 unsigned long inflight = ctx->user->unix_inflight + nr;
5640
5641 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
5642 return -EMFILE;
5643 }
5644
5645 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
5646 if (!fpl)
5647 return -ENOMEM;
5648
5649 skb = alloc_skb(0, GFP_KERNEL);
5650 if (!skb) {
5651 kfree(fpl);
5652 return -ENOMEM;
5653 }
5654
5655 skb->sk = sk;
6b06314c 5656
08a45173 5657 nr_files = 0;
6b06314c
JA
5658 fpl->user = get_uid(ctx->user);
5659 for (i = 0; i < nr; i++) {
65e19f54
JA
5660 struct file *file = io_file_from_index(ctx, i + offset);
5661
5662 if (!file)
08a45173 5663 continue;
65e19f54 5664 fpl->fp[nr_files] = get_file(file);
08a45173
JA
5665 unix_inflight(fpl->user, fpl->fp[nr_files]);
5666 nr_files++;
6b06314c
JA
5667 }
5668
08a45173
JA
5669 if (nr_files) {
5670 fpl->max = SCM_MAX_FD;
5671 fpl->count = nr_files;
5672 UNIXCB(skb).fp = fpl;
05f3fb3c 5673 skb->destructor = unix_destruct_scm;
08a45173
JA
5674 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
5675 skb_queue_head(&sk->sk_receive_queue, skb);
6b06314c 5676
08a45173
JA
5677 for (i = 0; i < nr_files; i++)
5678 fput(fpl->fp[i]);
5679 } else {
5680 kfree_skb(skb);
5681 kfree(fpl);
5682 }
6b06314c
JA
5683
5684 return 0;
5685}
5686
5687/*
5688 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
5689 * causes regular reference counting to break down. We rely on the UNIX
5690 * garbage collection to take care of this problem for us.
5691 */
5692static int io_sqe_files_scm(struct io_ring_ctx *ctx)
5693{
5694 unsigned left, total;
5695 int ret = 0;
5696
5697 total = 0;
5698 left = ctx->nr_user_files;
5699 while (left) {
5700 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
6b06314c
JA
5701
5702 ret = __io_sqe_files_scm(ctx, this_files, total);
5703 if (ret)
5704 break;
5705 left -= this_files;
5706 total += this_files;
5707 }
5708
5709 if (!ret)
5710 return 0;
5711
5712 while (total < ctx->nr_user_files) {
65e19f54
JA
5713 struct file *file = io_file_from_index(ctx, total);
5714
5715 if (file)
5716 fput(file);
6b06314c
JA
5717 total++;
5718 }
5719
5720 return ret;
5721}
5722#else
5723static int io_sqe_files_scm(struct io_ring_ctx *ctx)
5724{
5725 return 0;
5726}
5727#endif
5728
65e19f54
JA
5729static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
5730 unsigned nr_files)
5731{
5732 int i;
5733
5734 for (i = 0; i < nr_tables; i++) {
05f3fb3c 5735 struct fixed_file_table *table = &ctx->file_data->table[i];
65e19f54
JA
5736 unsigned this_files;
5737
5738 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
5739 table->files = kcalloc(this_files, sizeof(struct file *),
5740 GFP_KERNEL);
5741 if (!table->files)
5742 break;
5743 nr_files -= this_files;
5744 }
5745
5746 if (i == nr_tables)
5747 return 0;
5748
5749 for (i = 0; i < nr_tables; i++) {
05f3fb3c 5750 struct fixed_file_table *table = &ctx->file_data->table[i];
65e19f54
JA
5751 kfree(table->files);
5752 }
5753 return 1;
5754}
5755
05f3fb3c
JA
5756static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
5757{
5758#if defined(CONFIG_UNIX)
5759 struct sock *sock = ctx->ring_sock->sk;
5760 struct sk_buff_head list, *head = &sock->sk_receive_queue;
5761 struct sk_buff *skb;
5762 int i;
5763
5764 __skb_queue_head_init(&list);
5765
5766 /*
5767 * Find the skb that holds this file in its SCM_RIGHTS. When found,
5768 * remove this entry and rearrange the file array.
5769 */
5770 skb = skb_dequeue(head);
5771 while (skb) {
5772 struct scm_fp_list *fp;
5773
5774 fp = UNIXCB(skb).fp;
5775 for (i = 0; i < fp->count; i++) {
5776 int left;
5777
5778 if (fp->fp[i] != file)
5779 continue;
5780
5781 unix_notinflight(fp->user, fp->fp[i]);
5782 left = fp->count - 1 - i;
5783 if (left) {
5784 memmove(&fp->fp[i], &fp->fp[i + 1],
5785 left * sizeof(struct file *));
5786 }
5787 fp->count--;
5788 if (!fp->count) {
5789 kfree_skb(skb);
5790 skb = NULL;
5791 } else {
5792 __skb_queue_tail(&list, skb);
5793 }
5794 fput(file);
5795 file = NULL;
5796 break;
5797 }
5798
5799 if (!file)
5800 break;
5801
5802 __skb_queue_tail(&list, skb);
5803
5804 skb = skb_dequeue(head);
5805 }
5806
5807 if (skb_peek(&list)) {
5808 spin_lock_irq(&head->lock);
5809 while ((skb = __skb_dequeue(&list)) != NULL)
5810 __skb_queue_tail(head, skb);
5811 spin_unlock_irq(&head->lock);
5812 }
5813#else
5814 fput(file);
5815#endif
5816}
5817
5818struct io_file_put {
5819 struct llist_node llist;
5820 struct file *file;
5821 struct completion *done;
5822};
5823
2faf852d 5824static void io_ring_file_ref_flush(struct fixed_file_data *data)
65e19f54 5825{
05f3fb3c 5826 struct io_file_put *pfile, *tmp;
05f3fb3c 5827 struct llist_node *node;
65e19f54 5828
05f3fb3c
JA
5829 while ((node = llist_del_all(&data->put_llist)) != NULL) {
5830 llist_for_each_entry_safe(pfile, tmp, node, llist) {
5831 io_ring_file_put(data->ctx, pfile->file);
5832 if (pfile->done)
5833 complete(pfile->done);
5834 else
5835 kfree(pfile);
5836 }
65e19f54 5837 }
2faf852d 5838}
65e19f54 5839
2faf852d
JA
5840static void io_ring_file_ref_switch(struct work_struct *work)
5841{
5842 struct fixed_file_data *data;
65e19f54 5843
2faf852d
JA
5844 data = container_of(work, struct fixed_file_data, ref_work);
5845 io_ring_file_ref_flush(data);
05f3fb3c
JA
5846 percpu_ref_switch_to_percpu(&data->refs);
5847}
65e19f54 5848
05f3fb3c
JA
5849static void io_file_data_ref_zero(struct percpu_ref *ref)
5850{
5851 struct fixed_file_data *data;
5852
5853 data = container_of(ref, struct fixed_file_data, refs);
5854
2faf852d
JA
5855 /*
5856 * We can't safely switch from inside this context, punt to wq. If
5857 * the table ref is going away, the table is being unregistered.
5858 * Don't queue up the async work for that case, the caller will
5859 * handle it.
5860 */
5861 if (!percpu_ref_is_dying(&data->refs))
5862 queue_work(system_wq, &data->ref_work);
65e19f54
JA
5863}
5864
6b06314c
JA
5865static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
5866 unsigned nr_args)
5867{
5868 __s32 __user *fds = (__s32 __user *) arg;
65e19f54 5869 unsigned nr_tables;
05f3fb3c 5870 struct file *file;
6b06314c
JA
5871 int fd, ret = 0;
5872 unsigned i;
5873
05f3fb3c 5874 if (ctx->file_data)
6b06314c
JA
5875 return -EBUSY;
5876 if (!nr_args)
5877 return -EINVAL;
5878 if (nr_args > IORING_MAX_FIXED_FILES)
5879 return -EMFILE;
5880
05f3fb3c
JA
5881 ctx->file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
5882 if (!ctx->file_data)
5883 return -ENOMEM;
5884 ctx->file_data->ctx = ctx;
5885 init_completion(&ctx->file_data->done);
5886
65e19f54 5887 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
05f3fb3c
JA
5888 ctx->file_data->table = kcalloc(nr_tables,
5889 sizeof(struct fixed_file_table),
65e19f54 5890 GFP_KERNEL);
05f3fb3c
JA
5891 if (!ctx->file_data->table) {
5892 kfree(ctx->file_data);
5893 ctx->file_data = NULL;
6b06314c 5894 return -ENOMEM;
05f3fb3c
JA
5895 }
5896
5897 if (percpu_ref_init(&ctx->file_data->refs, io_file_data_ref_zero,
5898 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
5899 kfree(ctx->file_data->table);
5900 kfree(ctx->file_data);
5901 ctx->file_data = NULL;
6b06314c 5902 return -ENOMEM;
05f3fb3c
JA
5903 }
5904 ctx->file_data->put_llist.first = NULL;
5905 INIT_WORK(&ctx->file_data->ref_work, io_ring_file_ref_switch);
6b06314c 5906
65e19f54 5907 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
05f3fb3c
JA
5908 percpu_ref_exit(&ctx->file_data->refs);
5909 kfree(ctx->file_data->table);
5910 kfree(ctx->file_data);
5911 ctx->file_data = NULL;
65e19f54
JA
5912 return -ENOMEM;
5913 }
5914
08a45173 5915 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
65e19f54
JA
5916 struct fixed_file_table *table;
5917 unsigned index;
5918
6b06314c
JA
5919 ret = -EFAULT;
5920 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
5921 break;
08a45173
JA
5922 /* allow sparse sets */
5923 if (fd == -1) {
5924 ret = 0;
5925 continue;
5926 }
6b06314c 5927
05f3fb3c 5928 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
65e19f54 5929 index = i & IORING_FILE_TABLE_MASK;
05f3fb3c 5930 file = fget(fd);
6b06314c
JA
5931
5932 ret = -EBADF;
05f3fb3c 5933 if (!file)
6b06314c 5934 break;
05f3fb3c 5935
6b06314c
JA
5936 /*
5937 * Don't allow io_uring instances to be registered. If UNIX
5938 * isn't enabled, then this causes a reference cycle and this
5939 * instance can never get freed. If UNIX is enabled we'll
5940 * handle it just fine, but there's still no point in allowing
5941 * a ring fd as it doesn't support regular read/write anyway.
5942 */
05f3fb3c
JA
5943 if (file->f_op == &io_uring_fops) {
5944 fput(file);
6b06314c
JA
5945 break;
5946 }
6b06314c 5947 ret = 0;
05f3fb3c 5948 table->files[index] = file;
6b06314c
JA
5949 }
5950
5951 if (ret) {
65e19f54 5952 for (i = 0; i < ctx->nr_user_files; i++) {
65e19f54
JA
5953 file = io_file_from_index(ctx, i);
5954 if (file)
5955 fput(file);
5956 }
5957 for (i = 0; i < nr_tables; i++)
05f3fb3c 5958 kfree(ctx->file_data->table[i].files);
6b06314c 5959
05f3fb3c
JA
5960 kfree(ctx->file_data->table);
5961 kfree(ctx->file_data);
5962 ctx->file_data = NULL;
6b06314c
JA
5963 ctx->nr_user_files = 0;
5964 return ret;
5965 }
5966
5967 ret = io_sqe_files_scm(ctx);
5968 if (ret)
5969 io_sqe_files_unregister(ctx);
5970
5971 return ret;
5972}
5973
c3a31e60
JA
5974static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
5975 int index)
5976{
5977#if defined(CONFIG_UNIX)
5978 struct sock *sock = ctx->ring_sock->sk;
5979 struct sk_buff_head *head = &sock->sk_receive_queue;
5980 struct sk_buff *skb;
5981
5982 /*
5983 * See if we can merge this file into an existing skb SCM_RIGHTS
5984 * file set. If there's no room, fall back to allocating a new skb
5985 * and filling it in.
5986 */
5987 spin_lock_irq(&head->lock);
5988 skb = skb_peek(head);
5989 if (skb) {
5990 struct scm_fp_list *fpl = UNIXCB(skb).fp;
5991
5992 if (fpl->count < SCM_MAX_FD) {
5993 __skb_unlink(skb, head);
5994 spin_unlock_irq(&head->lock);
5995 fpl->fp[fpl->count] = get_file(file);
5996 unix_inflight(fpl->user, fpl->fp[fpl->count]);
5997 fpl->count++;
5998 spin_lock_irq(&head->lock);
5999 __skb_queue_head(head, skb);
6000 } else {
6001 skb = NULL;
6002 }
6003 }
6004 spin_unlock_irq(&head->lock);
6005
6006 if (skb) {
6007 fput(file);
6008 return 0;
6009 }
6010
6011 return __io_sqe_files_scm(ctx, 1, index);
6012#else
6013 return 0;
6014#endif
6015}
6016
05f3fb3c 6017static void io_atomic_switch(struct percpu_ref *ref)
c3a31e60 6018{
05f3fb3c
JA
6019 struct fixed_file_data *data;
6020
dd3db2a3
JA
6021 /*
6022 * Juggle reference to ensure we hit zero, if needed, so we can
6023 * switch back to percpu mode
6024 */
05f3fb3c 6025 data = container_of(ref, struct fixed_file_data, refs);
dd3db2a3
JA
6026 percpu_ref_put(&data->refs);
6027 percpu_ref_get(&data->refs);
05f3fb3c
JA
6028}
6029
6030static bool io_queue_file_removal(struct fixed_file_data *data,
6031 struct file *file)
6032{
6033 struct io_file_put *pfile, pfile_stack;
6034 DECLARE_COMPLETION_ONSTACK(done);
6035
6036 /*
6037 * If we fail allocating the struct we need for doing async reomval
6038 * of this file, just punt to sync and wait for it.
6039 */
6040 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
6041 if (!pfile) {
6042 pfile = &pfile_stack;
6043 pfile->done = &done;
6044 }
6045
6046 pfile->file = file;
6047 llist_add(&pfile->llist, &data->put_llist);
6048
6049 if (pfile == &pfile_stack) {
dd3db2a3 6050 percpu_ref_switch_to_atomic(&data->refs, io_atomic_switch);
05f3fb3c
JA
6051 wait_for_completion(&done);
6052 flush_work(&data->ref_work);
6053 return false;
6054 }
6055
6056 return true;
6057}
6058
6059static int __io_sqe_files_update(struct io_ring_ctx *ctx,
6060 struct io_uring_files_update *up,
6061 unsigned nr_args)
6062{
6063 struct fixed_file_data *data = ctx->file_data;
6064 bool ref_switch = false;
6065 struct file *file;
c3a31e60
JA
6066 __s32 __user *fds;
6067 int fd, i, err;
6068 __u32 done;
6069
05f3fb3c 6070 if (check_add_overflow(up->offset, nr_args, &done))
c3a31e60
JA
6071 return -EOVERFLOW;
6072 if (done > ctx->nr_user_files)
6073 return -EINVAL;
6074
6075 done = 0;
05f3fb3c 6076 fds = u64_to_user_ptr(up->fds);
c3a31e60 6077 while (nr_args) {
65e19f54
JA
6078 struct fixed_file_table *table;
6079 unsigned index;
6080
c3a31e60
JA
6081 err = 0;
6082 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
6083 err = -EFAULT;
6084 break;
6085 }
05f3fb3c
JA
6086 i = array_index_nospec(up->offset, ctx->nr_user_files);
6087 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
65e19f54
JA
6088 index = i & IORING_FILE_TABLE_MASK;
6089 if (table->files[index]) {
05f3fb3c 6090 file = io_file_from_index(ctx, index);
65e19f54 6091 table->files[index] = NULL;
05f3fb3c
JA
6092 if (io_queue_file_removal(data, file))
6093 ref_switch = true;
c3a31e60
JA
6094 }
6095 if (fd != -1) {
c3a31e60
JA
6096 file = fget(fd);
6097 if (!file) {
6098 err = -EBADF;
6099 break;
6100 }
6101 /*
6102 * Don't allow io_uring instances to be registered. If
6103 * UNIX isn't enabled, then this causes a reference
6104 * cycle and this instance can never get freed. If UNIX
6105 * is enabled we'll handle it just fine, but there's
6106 * still no point in allowing a ring fd as it doesn't
6107 * support regular read/write anyway.
6108 */
6109 if (file->f_op == &io_uring_fops) {
6110 fput(file);
6111 err = -EBADF;
6112 break;
6113 }
65e19f54 6114 table->files[index] = file;
c3a31e60
JA
6115 err = io_sqe_file_register(ctx, file, i);
6116 if (err)
6117 break;
6118 }
6119 nr_args--;
6120 done++;
05f3fb3c
JA
6121 up->offset++;
6122 }
6123
dd3db2a3 6124 if (ref_switch)
05f3fb3c 6125 percpu_ref_switch_to_atomic(&data->refs, io_atomic_switch);
c3a31e60
JA
6126
6127 return done ? done : err;
6128}
05f3fb3c
JA
6129static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
6130 unsigned nr_args)
6131{
6132 struct io_uring_files_update up;
6133
6134 if (!ctx->file_data)
6135 return -ENXIO;
6136 if (!nr_args)
6137 return -EINVAL;
6138 if (copy_from_user(&up, arg, sizeof(up)))
6139 return -EFAULT;
6140 if (up.resv)
6141 return -EINVAL;
6142
6143 return __io_sqe_files_update(ctx, &up, nr_args);
6144}
c3a31e60 6145
7d723065
JA
6146static void io_put_work(struct io_wq_work *work)
6147{
6148 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6149
6150 io_put_req(req);
6151}
6152
6153static void io_get_work(struct io_wq_work *work)
6154{
6155 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6156
6157 refcount_inc(&req->refs);
6158}
6159
24369c2e
PB
6160static int io_init_wq_offload(struct io_ring_ctx *ctx,
6161 struct io_uring_params *p)
6162{
6163 struct io_wq_data data;
6164 struct fd f;
6165 struct io_ring_ctx *ctx_attach;
6166 unsigned int concurrency;
6167 int ret = 0;
6168
6169 data.user = ctx->user;
6170 data.get_work = io_get_work;
6171 data.put_work = io_put_work;
6172
6173 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
6174 /* Do QD, or 4 * CPUS, whatever is smallest */
6175 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
6176
6177 ctx->io_wq = io_wq_create(concurrency, &data);
6178 if (IS_ERR(ctx->io_wq)) {
6179 ret = PTR_ERR(ctx->io_wq);
6180 ctx->io_wq = NULL;
6181 }
6182 return ret;
6183 }
6184
6185 f = fdget(p->wq_fd);
6186 if (!f.file)
6187 return -EBADF;
6188
6189 if (f.file->f_op != &io_uring_fops) {
6190 ret = -EINVAL;
6191 goto out_fput;
6192 }
6193
6194 ctx_attach = f.file->private_data;
6195 /* @io_wq is protected by holding the fd */
6196 if (!io_wq_get(ctx_attach->io_wq, &data)) {
6197 ret = -EINVAL;
6198 goto out_fput;
6199 }
6200
6201 ctx->io_wq = ctx_attach->io_wq;
6202out_fput:
6203 fdput(f);
6204 return ret;
6205}
6206
6c271ce2
JA
6207static int io_sq_offload_start(struct io_ring_ctx *ctx,
6208 struct io_uring_params *p)
2b188cc1
JA
6209{
6210 int ret;
6211
6c271ce2 6212 init_waitqueue_head(&ctx->sqo_wait);
2b188cc1
JA
6213 mmgrab(current->mm);
6214 ctx->sqo_mm = current->mm;
6215
6c271ce2 6216 if (ctx->flags & IORING_SETUP_SQPOLL) {
3ec482d1
JA
6217 ret = -EPERM;
6218 if (!capable(CAP_SYS_ADMIN))
6219 goto err;
6220
917257da
JA
6221 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
6222 if (!ctx->sq_thread_idle)
6223 ctx->sq_thread_idle = HZ;
6224
6c271ce2 6225 if (p->flags & IORING_SETUP_SQ_AFF) {
44a9bd18 6226 int cpu = p->sq_thread_cpu;
6c271ce2 6227
917257da 6228 ret = -EINVAL;
44a9bd18
JA
6229 if (cpu >= nr_cpu_ids)
6230 goto err;
7889f44d 6231 if (!cpu_online(cpu))
917257da
JA
6232 goto err;
6233
6c271ce2
JA
6234 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
6235 ctx, cpu,
6236 "io_uring-sq");
6237 } else {
6238 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
6239 "io_uring-sq");
6240 }
6241 if (IS_ERR(ctx->sqo_thread)) {
6242 ret = PTR_ERR(ctx->sqo_thread);
6243 ctx->sqo_thread = NULL;
6244 goto err;
6245 }
6246 wake_up_process(ctx->sqo_thread);
6247 } else if (p->flags & IORING_SETUP_SQ_AFF) {
6248 /* Can't have SQ_AFF without SQPOLL */
6249 ret = -EINVAL;
6250 goto err;
6251 }
6252
24369c2e
PB
6253 ret = io_init_wq_offload(ctx, p);
6254 if (ret)
2b188cc1 6255 goto err;
2b188cc1
JA
6256
6257 return 0;
6258err:
54a91f3b 6259 io_finish_async(ctx);
2b188cc1
JA
6260 mmdrop(ctx->sqo_mm);
6261 ctx->sqo_mm = NULL;
6262 return ret;
6263}
6264
6265static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
6266{
6267 atomic_long_sub(nr_pages, &user->locked_vm);
6268}
6269
6270static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
6271{
6272 unsigned long page_limit, cur_pages, new_pages;
6273
6274 /* Don't allow more pages than we can safely lock */
6275 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
6276
6277 do {
6278 cur_pages = atomic_long_read(&user->locked_vm);
6279 new_pages = cur_pages + nr_pages;
6280 if (new_pages > page_limit)
6281 return -ENOMEM;
6282 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
6283 new_pages) != cur_pages);
6284
6285 return 0;
6286}
6287
6288static void io_mem_free(void *ptr)
6289{
52e04ef4
MR
6290 struct page *page;
6291
6292 if (!ptr)
6293 return;
2b188cc1 6294
52e04ef4 6295 page = virt_to_head_page(ptr);
2b188cc1
JA
6296 if (put_page_testzero(page))
6297 free_compound_page(page);
6298}
6299
6300static void *io_mem_alloc(size_t size)
6301{
6302 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
6303 __GFP_NORETRY;
6304
6305 return (void *) __get_free_pages(gfp_flags, get_order(size));
6306}
6307
75b28aff
HV
6308static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
6309 size_t *sq_offset)
6310{
6311 struct io_rings *rings;
6312 size_t off, sq_array_size;
6313
6314 off = struct_size(rings, cqes, cq_entries);
6315 if (off == SIZE_MAX)
6316 return SIZE_MAX;
6317
6318#ifdef CONFIG_SMP
6319 off = ALIGN(off, SMP_CACHE_BYTES);
6320 if (off == 0)
6321 return SIZE_MAX;
6322#endif
6323
6324 sq_array_size = array_size(sizeof(u32), sq_entries);
6325 if (sq_array_size == SIZE_MAX)
6326 return SIZE_MAX;
6327
6328 if (check_add_overflow(off, sq_array_size, &off))
6329 return SIZE_MAX;
6330
6331 if (sq_offset)
6332 *sq_offset = off;
6333
6334 return off;
6335}
6336
2b188cc1
JA
6337static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
6338{
75b28aff 6339 size_t pages;
2b188cc1 6340
75b28aff
HV
6341 pages = (size_t)1 << get_order(
6342 rings_size(sq_entries, cq_entries, NULL));
6343 pages += (size_t)1 << get_order(
6344 array_size(sizeof(struct io_uring_sqe), sq_entries));
2b188cc1 6345
75b28aff 6346 return pages;
2b188cc1
JA
6347}
6348
edafccee
JA
6349static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
6350{
6351 int i, j;
6352
6353 if (!ctx->user_bufs)
6354 return -ENXIO;
6355
6356 for (i = 0; i < ctx->nr_user_bufs; i++) {
6357 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
6358
6359 for (j = 0; j < imu->nr_bvecs; j++)
f1f6a7dd 6360 unpin_user_page(imu->bvec[j].bv_page);
edafccee
JA
6361
6362 if (ctx->account_mem)
6363 io_unaccount_mem(ctx->user, imu->nr_bvecs);
d4ef6475 6364 kvfree(imu->bvec);
edafccee
JA
6365 imu->nr_bvecs = 0;
6366 }
6367
6368 kfree(ctx->user_bufs);
6369 ctx->user_bufs = NULL;
6370 ctx->nr_user_bufs = 0;
6371 return 0;
6372}
6373
6374static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
6375 void __user *arg, unsigned index)
6376{
6377 struct iovec __user *src;
6378
6379#ifdef CONFIG_COMPAT
6380 if (ctx->compat) {
6381 struct compat_iovec __user *ciovs;
6382 struct compat_iovec ciov;
6383
6384 ciovs = (struct compat_iovec __user *) arg;
6385 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
6386 return -EFAULT;
6387
d55e5f5b 6388 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
edafccee
JA
6389 dst->iov_len = ciov.iov_len;
6390 return 0;
6391 }
6392#endif
6393 src = (struct iovec __user *) arg;
6394 if (copy_from_user(dst, &src[index], sizeof(*dst)))
6395 return -EFAULT;
6396 return 0;
6397}
6398
6399static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
6400 unsigned nr_args)
6401{
6402 struct vm_area_struct **vmas = NULL;
6403 struct page **pages = NULL;
6404 int i, j, got_pages = 0;
6405 int ret = -EINVAL;
6406
6407 if (ctx->user_bufs)
6408 return -EBUSY;
6409 if (!nr_args || nr_args > UIO_MAXIOV)
6410 return -EINVAL;
6411
6412 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
6413 GFP_KERNEL);
6414 if (!ctx->user_bufs)
6415 return -ENOMEM;
6416
6417 for (i = 0; i < nr_args; i++) {
6418 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
6419 unsigned long off, start, end, ubuf;
6420 int pret, nr_pages;
6421 struct iovec iov;
6422 size_t size;
6423
6424 ret = io_copy_iov(ctx, &iov, arg, i);
6425 if (ret)
a278682d 6426 goto err;
edafccee
JA
6427
6428 /*
6429 * Don't impose further limits on the size and buffer
6430 * constraints here, we'll -EINVAL later when IO is
6431 * submitted if they are wrong.
6432 */
6433 ret = -EFAULT;
6434 if (!iov.iov_base || !iov.iov_len)
6435 goto err;
6436
6437 /* arbitrary limit, but we need something */
6438 if (iov.iov_len > SZ_1G)
6439 goto err;
6440
6441 ubuf = (unsigned long) iov.iov_base;
6442 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
6443 start = ubuf >> PAGE_SHIFT;
6444 nr_pages = end - start;
6445
6446 if (ctx->account_mem) {
6447 ret = io_account_mem(ctx->user, nr_pages);
6448 if (ret)
6449 goto err;
6450 }
6451
6452 ret = 0;
6453 if (!pages || nr_pages > got_pages) {
6454 kfree(vmas);
6455 kfree(pages);
d4ef6475 6456 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
edafccee 6457 GFP_KERNEL);
d4ef6475 6458 vmas = kvmalloc_array(nr_pages,
edafccee
JA
6459 sizeof(struct vm_area_struct *),
6460 GFP_KERNEL);
6461 if (!pages || !vmas) {
6462 ret = -ENOMEM;
6463 if (ctx->account_mem)
6464 io_unaccount_mem(ctx->user, nr_pages);
6465 goto err;
6466 }
6467 got_pages = nr_pages;
6468 }
6469
d4ef6475 6470 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
edafccee
JA
6471 GFP_KERNEL);
6472 ret = -ENOMEM;
6473 if (!imu->bvec) {
6474 if (ctx->account_mem)
6475 io_unaccount_mem(ctx->user, nr_pages);
6476 goto err;
6477 }
6478
6479 ret = 0;
6480 down_read(&current->mm->mmap_sem);
2113b05d 6481 pret = pin_user_pages(ubuf, nr_pages,
932f4a63
IW
6482 FOLL_WRITE | FOLL_LONGTERM,
6483 pages, vmas);
edafccee
JA
6484 if (pret == nr_pages) {
6485 /* don't support file backed memory */
6486 for (j = 0; j < nr_pages; j++) {
6487 struct vm_area_struct *vma = vmas[j];
6488
6489 if (vma->vm_file &&
6490 !is_file_hugepages(vma->vm_file)) {
6491 ret = -EOPNOTSUPP;
6492 break;
6493 }
6494 }
6495 } else {
6496 ret = pret < 0 ? pret : -EFAULT;
6497 }
6498 up_read(&current->mm->mmap_sem);
6499 if (ret) {
6500 /*
6501 * if we did partial map, or found file backed vmas,
6502 * release any pages we did get
6503 */
27c4d3a3 6504 if (pret > 0)
f1f6a7dd 6505 unpin_user_pages(pages, pret);
edafccee
JA
6506 if (ctx->account_mem)
6507 io_unaccount_mem(ctx->user, nr_pages);
d4ef6475 6508 kvfree(imu->bvec);
edafccee
JA
6509 goto err;
6510 }
6511
6512 off = ubuf & ~PAGE_MASK;
6513 size = iov.iov_len;
6514 for (j = 0; j < nr_pages; j++) {
6515 size_t vec_len;
6516
6517 vec_len = min_t(size_t, size, PAGE_SIZE - off);
6518 imu->bvec[j].bv_page = pages[j];
6519 imu->bvec[j].bv_len = vec_len;
6520 imu->bvec[j].bv_offset = off;
6521 off = 0;
6522 size -= vec_len;
6523 }
6524 /* store original address for later verification */
6525 imu->ubuf = ubuf;
6526 imu->len = iov.iov_len;
6527 imu->nr_bvecs = nr_pages;
6528
6529 ctx->nr_user_bufs++;
6530 }
d4ef6475
MR
6531 kvfree(pages);
6532 kvfree(vmas);
edafccee
JA
6533 return 0;
6534err:
d4ef6475
MR
6535 kvfree(pages);
6536 kvfree(vmas);
edafccee
JA
6537 io_sqe_buffer_unregister(ctx);
6538 return ret;
6539}
6540
9b402849
JA
6541static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
6542{
6543 __s32 __user *fds = arg;
6544 int fd;
6545
6546 if (ctx->cq_ev_fd)
6547 return -EBUSY;
6548
6549 if (copy_from_user(&fd, fds, sizeof(*fds)))
6550 return -EFAULT;
6551
6552 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
6553 if (IS_ERR(ctx->cq_ev_fd)) {
6554 int ret = PTR_ERR(ctx->cq_ev_fd);
6555 ctx->cq_ev_fd = NULL;
6556 return ret;
6557 }
6558
6559 return 0;
6560}
6561
6562static int io_eventfd_unregister(struct io_ring_ctx *ctx)
6563{
6564 if (ctx->cq_ev_fd) {
6565 eventfd_ctx_put(ctx->cq_ev_fd);
6566 ctx->cq_ev_fd = NULL;
6567 return 0;
6568 }
6569
6570 return -ENXIO;
6571}
6572
2b188cc1
JA
6573static void io_ring_ctx_free(struct io_ring_ctx *ctx)
6574{
6b06314c 6575 io_finish_async(ctx);
2b188cc1
JA
6576 if (ctx->sqo_mm)
6577 mmdrop(ctx->sqo_mm);
def596e9
JA
6578
6579 io_iopoll_reap_events(ctx);
edafccee 6580 io_sqe_buffer_unregister(ctx);
6b06314c 6581 io_sqe_files_unregister(ctx);
9b402849 6582 io_eventfd_unregister(ctx);
41726c9a 6583 idr_destroy(&ctx->personality_idr);
def596e9 6584
2b188cc1 6585#if defined(CONFIG_UNIX)
355e8d26
EB
6586 if (ctx->ring_sock) {
6587 ctx->ring_sock->file = NULL; /* so that iput() is called */
2b188cc1 6588 sock_release(ctx->ring_sock);
355e8d26 6589 }
2b188cc1
JA
6590#endif
6591
75b28aff 6592 io_mem_free(ctx->rings);
2b188cc1 6593 io_mem_free(ctx->sq_sqes);
2b188cc1
JA
6594
6595 percpu_ref_exit(&ctx->refs);
6596 if (ctx->account_mem)
6597 io_unaccount_mem(ctx->user,
6598 ring_pages(ctx->sq_entries, ctx->cq_entries));
6599 free_uid(ctx->user);
181e448d 6600 put_cred(ctx->creds);
206aefde 6601 kfree(ctx->completions);
78076bb6 6602 kfree(ctx->cancel_hash);
0ddf92e8 6603 kmem_cache_free(req_cachep, ctx->fallback_req);
2b188cc1
JA
6604 kfree(ctx);
6605}
6606
6607static __poll_t io_uring_poll(struct file *file, poll_table *wait)
6608{
6609 struct io_ring_ctx *ctx = file->private_data;
6610 __poll_t mask = 0;
6611
6612 poll_wait(file, &ctx->cq_wait, wait);
4f7067c3
SB
6613 /*
6614 * synchronizes with barrier from wq_has_sleeper call in
6615 * io_commit_cqring
6616 */
2b188cc1 6617 smp_rmb();
75b28aff
HV
6618 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
6619 ctx->rings->sq_ring_entries)
2b188cc1 6620 mask |= EPOLLOUT | EPOLLWRNORM;
63e5d81f 6621 if (io_cqring_events(ctx, false))
2b188cc1
JA
6622 mask |= EPOLLIN | EPOLLRDNORM;
6623
6624 return mask;
6625}
6626
6627static int io_uring_fasync(int fd, struct file *file, int on)
6628{
6629 struct io_ring_ctx *ctx = file->private_data;
6630
6631 return fasync_helper(fd, file, on, &ctx->cq_fasync);
6632}
6633
071698e1
JA
6634static int io_remove_personalities(int id, void *p, void *data)
6635{
6636 struct io_ring_ctx *ctx = data;
6637 const struct cred *cred;
6638
6639 cred = idr_remove(&ctx->personality_idr, id);
6640 if (cred)
6641 put_cred(cred);
6642 return 0;
6643}
6644
2b188cc1
JA
6645static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
6646{
6647 mutex_lock(&ctx->uring_lock);
6648 percpu_ref_kill(&ctx->refs);
6649 mutex_unlock(&ctx->uring_lock);
6650
df069d80
JA
6651 /*
6652 * Wait for sq thread to idle, if we have one. It won't spin on new
6653 * work after we've killed the ctx ref above. This is important to do
6654 * before we cancel existing commands, as the thread could otherwise
6655 * be queueing new work post that. If that's work we need to cancel,
6656 * it could cause shutdown to hang.
6657 */
6658 while (ctx->sqo_thread && !wq_has_sleeper(&ctx->sqo_wait))
6659 cpu_relax();
6660
5262f567 6661 io_kill_timeouts(ctx);
221c5eb2 6662 io_poll_remove_all(ctx);
561fb04a
JA
6663
6664 if (ctx->io_wq)
6665 io_wq_cancel_all(ctx->io_wq);
6666
def596e9 6667 io_iopoll_reap_events(ctx);
15dff286
JA
6668 /* if we failed setting up the ctx, we might not have any rings */
6669 if (ctx->rings)
6670 io_cqring_overflow_flush(ctx, true);
071698e1 6671 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
206aefde 6672 wait_for_completion(&ctx->completions[0]);
2b188cc1
JA
6673 io_ring_ctx_free(ctx);
6674}
6675
6676static int io_uring_release(struct inode *inode, struct file *file)
6677{
6678 struct io_ring_ctx *ctx = file->private_data;
6679
6680 file->private_data = NULL;
6681 io_ring_ctx_wait_and_kill(ctx);
6682 return 0;
6683}
6684
fcb323cc
JA
6685static void io_uring_cancel_files(struct io_ring_ctx *ctx,
6686 struct files_struct *files)
6687{
6688 struct io_kiocb *req;
6689 DEFINE_WAIT(wait);
6690
6691 while (!list_empty_careful(&ctx->inflight_list)) {
768134d4 6692 struct io_kiocb *cancel_req = NULL;
fcb323cc
JA
6693
6694 spin_lock_irq(&ctx->inflight_lock);
6695 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
768134d4
JA
6696 if (req->work.files != files)
6697 continue;
6698 /* req is being completed, ignore */
6699 if (!refcount_inc_not_zero(&req->refs))
6700 continue;
6701 cancel_req = req;
6702 break;
fcb323cc 6703 }
768134d4 6704 if (cancel_req)
fcb323cc 6705 prepare_to_wait(&ctx->inflight_wait, &wait,
768134d4 6706 TASK_UNINTERRUPTIBLE);
fcb323cc
JA
6707 spin_unlock_irq(&ctx->inflight_lock);
6708
768134d4
JA
6709 /* We need to keep going until we don't find a matching req */
6710 if (!cancel_req)
fcb323cc 6711 break;
2f6d9b9d 6712
2ca10259
JA
6713 if (cancel_req->flags & REQ_F_OVERFLOW) {
6714 spin_lock_irq(&ctx->completion_lock);
6715 list_del(&cancel_req->list);
6716 cancel_req->flags &= ~REQ_F_OVERFLOW;
6717 if (list_empty(&ctx->cq_overflow_list)) {
6718 clear_bit(0, &ctx->sq_check_overflow);
6719 clear_bit(0, &ctx->cq_check_overflow);
6720 }
6721 spin_unlock_irq(&ctx->completion_lock);
6722
6723 WRITE_ONCE(ctx->rings->cq_overflow,
6724 atomic_inc_return(&ctx->cached_cq_overflow));
6725
6726 /*
6727 * Put inflight ref and overflow ref. If that's
6728 * all we had, then we're done with this request.
6729 */
6730 if (refcount_sub_and_test(2, &cancel_req->refs)) {
6731 io_put_req(cancel_req);
6732 continue;
6733 }
6734 }
6735
2f6d9b9d
BL
6736 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
6737 io_put_req(cancel_req);
fcb323cc
JA
6738 schedule();
6739 }
768134d4 6740 finish_wait(&ctx->inflight_wait, &wait);
fcb323cc
JA
6741}
6742
6743static int io_uring_flush(struct file *file, void *data)
6744{
6745 struct io_ring_ctx *ctx = file->private_data;
6746
6747 io_uring_cancel_files(ctx, data);
6ab23144
JA
6748
6749 /*
6750 * If the task is going away, cancel work it may have pending
6751 */
6752 if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
6753 io_wq_cancel_pid(ctx->io_wq, task_pid_vnr(current));
6754
fcb323cc
JA
6755 return 0;
6756}
6757
6c5c240e
RP
6758static void *io_uring_validate_mmap_request(struct file *file,
6759 loff_t pgoff, size_t sz)
2b188cc1 6760{
2b188cc1 6761 struct io_ring_ctx *ctx = file->private_data;
6c5c240e 6762 loff_t offset = pgoff << PAGE_SHIFT;
2b188cc1
JA
6763 struct page *page;
6764 void *ptr;
6765
6766 switch (offset) {
6767 case IORING_OFF_SQ_RING:
75b28aff
HV
6768 case IORING_OFF_CQ_RING:
6769 ptr = ctx->rings;
2b188cc1
JA
6770 break;
6771 case IORING_OFF_SQES:
6772 ptr = ctx->sq_sqes;
6773 break;
2b188cc1 6774 default:
6c5c240e 6775 return ERR_PTR(-EINVAL);
2b188cc1
JA
6776 }
6777
6778 page = virt_to_head_page(ptr);
a50b854e 6779 if (sz > page_size(page))
6c5c240e
RP
6780 return ERR_PTR(-EINVAL);
6781
6782 return ptr;
6783}
6784
6785#ifdef CONFIG_MMU
6786
6787static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6788{
6789 size_t sz = vma->vm_end - vma->vm_start;
6790 unsigned long pfn;
6791 void *ptr;
6792
6793 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
6794 if (IS_ERR(ptr))
6795 return PTR_ERR(ptr);
2b188cc1
JA
6796
6797 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
6798 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
6799}
6800
6c5c240e
RP
6801#else /* !CONFIG_MMU */
6802
6803static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6804{
6805 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
6806}
6807
6808static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
6809{
6810 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
6811}
6812
6813static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
6814 unsigned long addr, unsigned long len,
6815 unsigned long pgoff, unsigned long flags)
6816{
6817 void *ptr;
6818
6819 ptr = io_uring_validate_mmap_request(file, pgoff, len);
6820 if (IS_ERR(ptr))
6821 return PTR_ERR(ptr);
6822
6823 return (unsigned long) ptr;
6824}
6825
6826#endif /* !CONFIG_MMU */
6827
2b188cc1
JA
6828SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
6829 u32, min_complete, u32, flags, const sigset_t __user *, sig,
6830 size_t, sigsz)
6831{
6832 struct io_ring_ctx *ctx;
6833 long ret = -EBADF;
6834 int submitted = 0;
6835 struct fd f;
6836
b41e9852
JA
6837 if (current->task_works)
6838 task_work_run();
6839
6c271ce2 6840 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
2b188cc1
JA
6841 return -EINVAL;
6842
6843 f = fdget(fd);
6844 if (!f.file)
6845 return -EBADF;
6846
6847 ret = -EOPNOTSUPP;
6848 if (f.file->f_op != &io_uring_fops)
6849 goto out_fput;
6850
6851 ret = -ENXIO;
6852 ctx = f.file->private_data;
6853 if (!percpu_ref_tryget(&ctx->refs))
6854 goto out_fput;
6855
6c271ce2
JA
6856 /*
6857 * For SQ polling, the thread will do all submissions and completions.
6858 * Just return the requested submit count, and wake the thread if
6859 * we were asked to.
6860 */
b2a9eada 6861 ret = 0;
6c271ce2 6862 if (ctx->flags & IORING_SETUP_SQPOLL) {
c1edbf5f
JA
6863 if (!list_empty_careful(&ctx->cq_overflow_list))
6864 io_cqring_overflow_flush(ctx, false);
6c271ce2
JA
6865 if (flags & IORING_ENTER_SQ_WAKEUP)
6866 wake_up(&ctx->sqo_wait);
6867 submitted = to_submit;
b2a9eada 6868 } else if (to_submit) {
ae9428ca 6869 struct mm_struct *cur_mm;
2b188cc1
JA
6870
6871 mutex_lock(&ctx->uring_lock);
ae9428ca
PB
6872 /* already have mm, so io_submit_sqes() won't try to grab it */
6873 cur_mm = ctx->sqo_mm;
6874 submitted = io_submit_sqes(ctx, to_submit, f.file, fd,
6875 &cur_mm, false);
2b188cc1 6876 mutex_unlock(&ctx->uring_lock);
7c504e65
PB
6877
6878 if (submitted != to_submit)
6879 goto out;
2b188cc1
JA
6880 }
6881 if (flags & IORING_ENTER_GETEVENTS) {
def596e9
JA
6882 unsigned nr_events = 0;
6883
2b188cc1
JA
6884 min_complete = min(min_complete, ctx->cq_entries);
6885
def596e9 6886 if (ctx->flags & IORING_SETUP_IOPOLL) {
def596e9 6887 ret = io_iopoll_check(ctx, &nr_events, min_complete);
def596e9
JA
6888 } else {
6889 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
6890 }
2b188cc1
JA
6891 }
6892
7c504e65 6893out:
6805b32e 6894 percpu_ref_put(&ctx->refs);
2b188cc1
JA
6895out_fput:
6896 fdput(f);
6897 return submitted ? submitted : ret;
6898}
6899
bebdb65e 6900#ifdef CONFIG_PROC_FS
87ce955b
JA
6901static int io_uring_show_cred(int id, void *p, void *data)
6902{
6903 const struct cred *cred = p;
6904 struct seq_file *m = data;
6905 struct user_namespace *uns = seq_user_ns(m);
6906 struct group_info *gi;
6907 kernel_cap_t cap;
6908 unsigned __capi;
6909 int g;
6910
6911 seq_printf(m, "%5d\n", id);
6912 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
6913 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
6914 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
6915 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
6916 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
6917 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
6918 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
6919 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
6920 seq_puts(m, "\n\tGroups:\t");
6921 gi = cred->group_info;
6922 for (g = 0; g < gi->ngroups; g++) {
6923 seq_put_decimal_ull(m, g ? " " : "",
6924 from_kgid_munged(uns, gi->gid[g]));
6925 }
6926 seq_puts(m, "\n\tCapEff:\t");
6927 cap = cred->cap_effective;
6928 CAP_FOR_EACH_U32(__capi)
6929 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
6930 seq_putc(m, '\n');
6931 return 0;
6932}
6933
6934static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
6935{
6936 int i;
6937
6938 mutex_lock(&ctx->uring_lock);
6939 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
6940 for (i = 0; i < ctx->nr_user_files; i++) {
6941 struct fixed_file_table *table;
6942 struct file *f;
6943
6944 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
6945 f = table->files[i & IORING_FILE_TABLE_MASK];
6946 if (f)
6947 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
6948 else
6949 seq_printf(m, "%5u: <none>\n", i);
6950 }
6951 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
6952 for (i = 0; i < ctx->nr_user_bufs; i++) {
6953 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
6954
6955 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
6956 (unsigned int) buf->len);
6957 }
6958 if (!idr_is_empty(&ctx->personality_idr)) {
6959 seq_printf(m, "Personalities:\n");
6960 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
6961 }
d7718a9d
JA
6962 seq_printf(m, "PollList:\n");
6963 spin_lock_irq(&ctx->completion_lock);
6964 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
6965 struct hlist_head *list = &ctx->cancel_hash[i];
6966 struct io_kiocb *req;
6967
6968 hlist_for_each_entry(req, list, hash_node)
6969 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
6970 req->task->task_works != NULL);
6971 }
6972 spin_unlock_irq(&ctx->completion_lock);
87ce955b
JA
6973 mutex_unlock(&ctx->uring_lock);
6974}
6975
6976static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
6977{
6978 struct io_ring_ctx *ctx = f->private_data;
6979
6980 if (percpu_ref_tryget(&ctx->refs)) {
6981 __io_uring_show_fdinfo(ctx, m);
6982 percpu_ref_put(&ctx->refs);
6983 }
6984}
bebdb65e 6985#endif
87ce955b 6986
2b188cc1
JA
6987static const struct file_operations io_uring_fops = {
6988 .release = io_uring_release,
fcb323cc 6989 .flush = io_uring_flush,
2b188cc1 6990 .mmap = io_uring_mmap,
6c5c240e
RP
6991#ifndef CONFIG_MMU
6992 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
6993 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
6994#endif
2b188cc1
JA
6995 .poll = io_uring_poll,
6996 .fasync = io_uring_fasync,
bebdb65e 6997#ifdef CONFIG_PROC_FS
87ce955b 6998 .show_fdinfo = io_uring_show_fdinfo,
bebdb65e 6999#endif
2b188cc1
JA
7000};
7001
7002static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
7003 struct io_uring_params *p)
7004{
75b28aff
HV
7005 struct io_rings *rings;
7006 size_t size, sq_array_offset;
2b188cc1 7007
75b28aff
HV
7008 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
7009 if (size == SIZE_MAX)
7010 return -EOVERFLOW;
7011
7012 rings = io_mem_alloc(size);
7013 if (!rings)
2b188cc1
JA
7014 return -ENOMEM;
7015
75b28aff
HV
7016 ctx->rings = rings;
7017 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
7018 rings->sq_ring_mask = p->sq_entries - 1;
7019 rings->cq_ring_mask = p->cq_entries - 1;
7020 rings->sq_ring_entries = p->sq_entries;
7021 rings->cq_ring_entries = p->cq_entries;
7022 ctx->sq_mask = rings->sq_ring_mask;
7023 ctx->cq_mask = rings->cq_ring_mask;
7024 ctx->sq_entries = rings->sq_ring_entries;
7025 ctx->cq_entries = rings->cq_ring_entries;
2b188cc1
JA
7026
7027 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
eb065d30
JA
7028 if (size == SIZE_MAX) {
7029 io_mem_free(ctx->rings);
7030 ctx->rings = NULL;
2b188cc1 7031 return -EOVERFLOW;
eb065d30 7032 }
2b188cc1
JA
7033
7034 ctx->sq_sqes = io_mem_alloc(size);
eb065d30
JA
7035 if (!ctx->sq_sqes) {
7036 io_mem_free(ctx->rings);
7037 ctx->rings = NULL;
2b188cc1 7038 return -ENOMEM;
eb065d30 7039 }
2b188cc1 7040
2b188cc1
JA
7041 return 0;
7042}
7043
7044/*
7045 * Allocate an anonymous fd, this is what constitutes the application
7046 * visible backing of an io_uring instance. The application mmaps this
7047 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
7048 * we have to tie this fd to a socket for file garbage collection purposes.
7049 */
7050static int io_uring_get_fd(struct io_ring_ctx *ctx)
7051{
7052 struct file *file;
7053 int ret;
7054
7055#if defined(CONFIG_UNIX)
7056 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
7057 &ctx->ring_sock);
7058 if (ret)
7059 return ret;
7060#endif
7061
7062 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
7063 if (ret < 0)
7064 goto err;
7065
7066 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
7067 O_RDWR | O_CLOEXEC);
7068 if (IS_ERR(file)) {
7069 put_unused_fd(ret);
7070 ret = PTR_ERR(file);
7071 goto err;
7072 }
7073
7074#if defined(CONFIG_UNIX)
7075 ctx->ring_sock->file = file;
7076#endif
7077 fd_install(ret, file);
7078 return ret;
7079err:
7080#if defined(CONFIG_UNIX)
7081 sock_release(ctx->ring_sock);
7082 ctx->ring_sock = NULL;
7083#endif
7084 return ret;
7085}
7086
7087static int io_uring_create(unsigned entries, struct io_uring_params *p)
7088{
7089 struct user_struct *user = NULL;
7090 struct io_ring_ctx *ctx;
7091 bool account_mem;
7092 int ret;
7093
8110c1a6 7094 if (!entries)
2b188cc1 7095 return -EINVAL;
8110c1a6
JA
7096 if (entries > IORING_MAX_ENTRIES) {
7097 if (!(p->flags & IORING_SETUP_CLAMP))
7098 return -EINVAL;
7099 entries = IORING_MAX_ENTRIES;
7100 }
2b188cc1
JA
7101
7102 /*
7103 * Use twice as many entries for the CQ ring. It's possible for the
7104 * application to drive a higher depth than the size of the SQ ring,
7105 * since the sqes are only used at submission time. This allows for
33a107f0
JA
7106 * some flexibility in overcommitting a bit. If the application has
7107 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
7108 * of CQ ring entries manually.
2b188cc1
JA
7109 */
7110 p->sq_entries = roundup_pow_of_two(entries);
33a107f0
JA
7111 if (p->flags & IORING_SETUP_CQSIZE) {
7112 /*
7113 * If IORING_SETUP_CQSIZE is set, we do the same roundup
7114 * to a power-of-two, if it isn't already. We do NOT impose
7115 * any cq vs sq ring sizing.
7116 */
8110c1a6 7117 if (p->cq_entries < p->sq_entries)
33a107f0 7118 return -EINVAL;
8110c1a6
JA
7119 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
7120 if (!(p->flags & IORING_SETUP_CLAMP))
7121 return -EINVAL;
7122 p->cq_entries = IORING_MAX_CQ_ENTRIES;
7123 }
33a107f0
JA
7124 p->cq_entries = roundup_pow_of_two(p->cq_entries);
7125 } else {
7126 p->cq_entries = 2 * p->sq_entries;
7127 }
2b188cc1
JA
7128
7129 user = get_uid(current_user());
7130 account_mem = !capable(CAP_IPC_LOCK);
7131
7132 if (account_mem) {
7133 ret = io_account_mem(user,
7134 ring_pages(p->sq_entries, p->cq_entries));
7135 if (ret) {
7136 free_uid(user);
7137 return ret;
7138 }
7139 }
7140
7141 ctx = io_ring_ctx_alloc(p);
7142 if (!ctx) {
7143 if (account_mem)
7144 io_unaccount_mem(user, ring_pages(p->sq_entries,
7145 p->cq_entries));
7146 free_uid(user);
7147 return -ENOMEM;
7148 }
7149 ctx->compat = in_compat_syscall();
7150 ctx->account_mem = account_mem;
7151 ctx->user = user;
0b8c0ec7 7152 ctx->creds = get_current_cred();
2b188cc1
JA
7153
7154 ret = io_allocate_scq_urings(ctx, p);
7155 if (ret)
7156 goto err;
7157
6c271ce2 7158 ret = io_sq_offload_start(ctx, p);
2b188cc1
JA
7159 if (ret)
7160 goto err;
7161
2b188cc1 7162 memset(&p->sq_off, 0, sizeof(p->sq_off));
75b28aff
HV
7163 p->sq_off.head = offsetof(struct io_rings, sq.head);
7164 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
7165 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
7166 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
7167 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
7168 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
7169 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
2b188cc1
JA
7170
7171 memset(&p->cq_off, 0, sizeof(p->cq_off));
75b28aff
HV
7172 p->cq_off.head = offsetof(struct io_rings, cq.head);
7173 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
7174 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
7175 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
7176 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
7177 p->cq_off.cqes = offsetof(struct io_rings, cqes);
ac90f249 7178
044c1ab3
JA
7179 /*
7180 * Install ring fd as the very last thing, so we don't risk someone
7181 * having closed it before we finish setup
7182 */
7183 ret = io_uring_get_fd(ctx);
7184 if (ret < 0)
7185 goto err;
7186
da8c9690 7187 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
cccf0ee8 7188 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
d7718a9d 7189 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL;
c826bd7a 7190 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
2b188cc1
JA
7191 return ret;
7192err:
7193 io_ring_ctx_wait_and_kill(ctx);
7194 return ret;
7195}
7196
7197/*
7198 * Sets up an aio uring context, and returns the fd. Applications asks for a
7199 * ring size, we return the actual sq/cq ring sizes (among other things) in the
7200 * params structure passed in.
7201 */
7202static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
7203{
7204 struct io_uring_params p;
7205 long ret;
7206 int i;
7207
7208 if (copy_from_user(&p, params, sizeof(p)))
7209 return -EFAULT;
7210 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
7211 if (p.resv[i])
7212 return -EINVAL;
7213 }
7214
6c271ce2 7215 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
8110c1a6 7216 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
24369c2e 7217 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ))
2b188cc1
JA
7218 return -EINVAL;
7219
7220 ret = io_uring_create(entries, &p);
7221 if (ret < 0)
7222 return ret;
7223
7224 if (copy_to_user(params, &p, sizeof(p)))
7225 return -EFAULT;
7226
7227 return ret;
7228}
7229
7230SYSCALL_DEFINE2(io_uring_setup, u32, entries,
7231 struct io_uring_params __user *, params)
7232{
7233 return io_uring_setup(entries, params);
7234}
7235
66f4af93
JA
7236static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
7237{
7238 struct io_uring_probe *p;
7239 size_t size;
7240 int i, ret;
7241
7242 size = struct_size(p, ops, nr_args);
7243 if (size == SIZE_MAX)
7244 return -EOVERFLOW;
7245 p = kzalloc(size, GFP_KERNEL);
7246 if (!p)
7247 return -ENOMEM;
7248
7249 ret = -EFAULT;
7250 if (copy_from_user(p, arg, size))
7251 goto out;
7252 ret = -EINVAL;
7253 if (memchr_inv(p, 0, size))
7254 goto out;
7255
7256 p->last_op = IORING_OP_LAST - 1;
7257 if (nr_args > IORING_OP_LAST)
7258 nr_args = IORING_OP_LAST;
7259
7260 for (i = 0; i < nr_args; i++) {
7261 p->ops[i].op = i;
7262 if (!io_op_defs[i].not_supported)
7263 p->ops[i].flags = IO_URING_OP_SUPPORTED;
7264 }
7265 p->ops_len = i;
7266
7267 ret = 0;
7268 if (copy_to_user(arg, p, size))
7269 ret = -EFAULT;
7270out:
7271 kfree(p);
7272 return ret;
7273}
7274
071698e1
JA
7275static int io_register_personality(struct io_ring_ctx *ctx)
7276{
7277 const struct cred *creds = get_current_cred();
7278 int id;
7279
7280 id = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
7281 USHRT_MAX, GFP_KERNEL);
7282 if (id < 0)
7283 put_cred(creds);
7284 return id;
7285}
7286
7287static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
7288{
7289 const struct cred *old_creds;
7290
7291 old_creds = idr_remove(&ctx->personality_idr, id);
7292 if (old_creds) {
7293 put_cred(old_creds);
7294 return 0;
7295 }
7296
7297 return -EINVAL;
7298}
7299
7300static bool io_register_op_must_quiesce(int op)
7301{
7302 switch (op) {
7303 case IORING_UNREGISTER_FILES:
7304 case IORING_REGISTER_FILES_UPDATE:
7305 case IORING_REGISTER_PROBE:
7306 case IORING_REGISTER_PERSONALITY:
7307 case IORING_UNREGISTER_PERSONALITY:
7308 return false;
7309 default:
7310 return true;
7311 }
7312}
7313
edafccee
JA
7314static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
7315 void __user *arg, unsigned nr_args)
b19062a5
JA
7316 __releases(ctx->uring_lock)
7317 __acquires(ctx->uring_lock)
edafccee
JA
7318{
7319 int ret;
7320
35fa71a0
JA
7321 /*
7322 * We're inside the ring mutex, if the ref is already dying, then
7323 * someone else killed the ctx or is already going through
7324 * io_uring_register().
7325 */
7326 if (percpu_ref_is_dying(&ctx->refs))
7327 return -ENXIO;
7328
071698e1 7329 if (io_register_op_must_quiesce(opcode)) {
05f3fb3c 7330 percpu_ref_kill(&ctx->refs);
b19062a5 7331
05f3fb3c
JA
7332 /*
7333 * Drop uring mutex before waiting for references to exit. If
7334 * another thread is currently inside io_uring_enter() it might
7335 * need to grab the uring_lock to make progress. If we hold it
7336 * here across the drain wait, then we can deadlock. It's safe
7337 * to drop the mutex here, since no new references will come in
7338 * after we've killed the percpu ref.
7339 */
7340 mutex_unlock(&ctx->uring_lock);
c150368b 7341 ret = wait_for_completion_interruptible(&ctx->completions[0]);
05f3fb3c 7342 mutex_lock(&ctx->uring_lock);
c150368b
JA
7343 if (ret) {
7344 percpu_ref_resurrect(&ctx->refs);
7345 ret = -EINTR;
7346 goto out;
7347 }
05f3fb3c 7348 }
edafccee
JA
7349
7350 switch (opcode) {
7351 case IORING_REGISTER_BUFFERS:
7352 ret = io_sqe_buffer_register(ctx, arg, nr_args);
7353 break;
7354 case IORING_UNREGISTER_BUFFERS:
7355 ret = -EINVAL;
7356 if (arg || nr_args)
7357 break;
7358 ret = io_sqe_buffer_unregister(ctx);
7359 break;
6b06314c
JA
7360 case IORING_REGISTER_FILES:
7361 ret = io_sqe_files_register(ctx, arg, nr_args);
7362 break;
7363 case IORING_UNREGISTER_FILES:
7364 ret = -EINVAL;
7365 if (arg || nr_args)
7366 break;
7367 ret = io_sqe_files_unregister(ctx);
7368 break;
c3a31e60
JA
7369 case IORING_REGISTER_FILES_UPDATE:
7370 ret = io_sqe_files_update(ctx, arg, nr_args);
7371 break;
9b402849 7372 case IORING_REGISTER_EVENTFD:
f2842ab5 7373 case IORING_REGISTER_EVENTFD_ASYNC:
9b402849
JA
7374 ret = -EINVAL;
7375 if (nr_args != 1)
7376 break;
7377 ret = io_eventfd_register(ctx, arg);
f2842ab5
JA
7378 if (ret)
7379 break;
7380 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
7381 ctx->eventfd_async = 1;
7382 else
7383 ctx->eventfd_async = 0;
9b402849
JA
7384 break;
7385 case IORING_UNREGISTER_EVENTFD:
7386 ret = -EINVAL;
7387 if (arg || nr_args)
7388 break;
7389 ret = io_eventfd_unregister(ctx);
7390 break;
66f4af93
JA
7391 case IORING_REGISTER_PROBE:
7392 ret = -EINVAL;
7393 if (!arg || nr_args > 256)
7394 break;
7395 ret = io_probe(ctx, arg, nr_args);
7396 break;
071698e1
JA
7397 case IORING_REGISTER_PERSONALITY:
7398 ret = -EINVAL;
7399 if (arg || nr_args)
7400 break;
7401 ret = io_register_personality(ctx);
7402 break;
7403 case IORING_UNREGISTER_PERSONALITY:
7404 ret = -EINVAL;
7405 if (arg)
7406 break;
7407 ret = io_unregister_personality(ctx, nr_args);
7408 break;
edafccee
JA
7409 default:
7410 ret = -EINVAL;
7411 break;
7412 }
7413
071698e1 7414 if (io_register_op_must_quiesce(opcode)) {
05f3fb3c 7415 /* bring the ctx back to life */
05f3fb3c 7416 percpu_ref_reinit(&ctx->refs);
c150368b
JA
7417out:
7418 reinit_completion(&ctx->completions[0]);
05f3fb3c 7419 }
edafccee
JA
7420 return ret;
7421}
7422
7423SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
7424 void __user *, arg, unsigned int, nr_args)
7425{
7426 struct io_ring_ctx *ctx;
7427 long ret = -EBADF;
7428 struct fd f;
7429
7430 f = fdget(fd);
7431 if (!f.file)
7432 return -EBADF;
7433
7434 ret = -EOPNOTSUPP;
7435 if (f.file->f_op != &io_uring_fops)
7436 goto out_fput;
7437
7438 ctx = f.file->private_data;
7439
7440 mutex_lock(&ctx->uring_lock);
7441 ret = __io_uring_register(ctx, opcode, arg, nr_args);
7442 mutex_unlock(&ctx->uring_lock);
c826bd7a
DD
7443 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
7444 ctx->cq_ev_fd != NULL, ret);
edafccee
JA
7445out_fput:
7446 fdput(f);
7447 return ret;
7448}
7449
2b188cc1
JA
7450static int __init io_uring_init(void)
7451{
d7f62e82
SM
7452#define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
7453 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
7454 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
7455} while (0)
7456
7457#define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
7458 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
7459 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
7460 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
7461 BUILD_BUG_SQE_ELEM(1, __u8, flags);
7462 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
7463 BUILD_BUG_SQE_ELEM(4, __s32, fd);
7464 BUILD_BUG_SQE_ELEM(8, __u64, off);
7465 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
7466 BUILD_BUG_SQE_ELEM(16, __u64, addr);
7d67af2c 7467 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
d7f62e82
SM
7468 BUILD_BUG_SQE_ELEM(24, __u32, len);
7469 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
7470 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
7471 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
7472 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
7473 BUILD_BUG_SQE_ELEM(28, __u16, poll_events);
7474 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
7475 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
7476 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
7477 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
7478 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
7479 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
7480 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
7481 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
7d67af2c 7482 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
d7f62e82
SM
7483 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
7484 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
7485 BUILD_BUG_SQE_ELEM(42, __u16, personality);
7d67af2c 7486 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
d7f62e82 7487
d3656344 7488 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
2b188cc1
JA
7489 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
7490 return 0;
7491};
7492__initcall(io_uring_init);