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