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