io_uring: remove @nxt from handlers
[linux-2.6-block.git] / fs / io_uring.c
CommitLineData
2b188cc1
JA
1// SPDX-License-Identifier: GPL-2.0
2/*
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
5 *
6 * A note on the read/write ordering memory barriers that are matched between
1e84b97b
SB
7 * the application and kernel side.
8 *
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqring (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
16 * CQ entries.
17 *
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
23 * head will do).
24 *
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
28 * between.
2b188cc1
JA
29 *
30 * Also see the examples in the liburing library:
31 *
32 * git://git.kernel.dk/liburing
33 *
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
38 *
39 * Copyright (C) 2018-2019 Jens Axboe
c992fe29 40 * Copyright (c) 2018-2019 Christoph Hellwig
2b188cc1
JA
41 */
42#include <linux/kernel.h>
43#include <linux/init.h>
44#include <linux/errno.h>
45#include <linux/syscalls.h>
46#include <linux/compat.h>
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
def596e9
JA
1807static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1808{
9adbd45d 1809 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
def596e9 1810
491381ce
JA
1811 if (kiocb->ki_flags & IOCB_WRITE)
1812 kiocb_end_write(req);
def596e9 1813
4e88d6e7
JA
1814 if (res != req->result)
1815 req_set_fail_links(req);
9e645e11 1816 req->result = res;
def596e9
JA
1817 if (res != -EAGAIN)
1818 req->flags |= REQ_F_IOPOLL_COMPLETED;
1819}
1820
1821/*
1822 * After the iocb has been issued, it's safe to be found on the poll list.
1823 * Adding the kiocb to the list AFTER submission ensures that we don't
1824 * find it from a io_iopoll_getevents() thread before the issuer is done
1825 * accessing the kiocb cookie.
1826 */
1827static void io_iopoll_req_issued(struct io_kiocb *req)
1828{
1829 struct io_ring_ctx *ctx = req->ctx;
1830
1831 /*
1832 * Track whether we have multiple files in our lists. This will impact
1833 * how we do polling eventually, not spinning if we're on potentially
1834 * different devices.
1835 */
1836 if (list_empty(&ctx->poll_list)) {
1837 ctx->poll_multi_file = false;
1838 } else if (!ctx->poll_multi_file) {
1839 struct io_kiocb *list_req;
1840
1841 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1842 list);
9adbd45d 1843 if (list_req->file != req->file)
def596e9
JA
1844 ctx->poll_multi_file = true;
1845 }
1846
1847 /*
1848 * For fast devices, IO may have already completed. If it has, add
1849 * it to the front so we find it first.
1850 */
1851 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1852 list_add(&req->list, &ctx->poll_list);
1853 else
1854 list_add_tail(&req->list, &ctx->poll_list);
bdcd3eab
XW
1855
1856 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
1857 wq_has_sleeper(&ctx->sqo_wait))
1858 wake_up(&ctx->sqo_wait);
def596e9
JA
1859}
1860
3d6770fb 1861static void io_file_put(struct io_submit_state *state)
9a56a232 1862{
3d6770fb 1863 if (state->file) {
9a56a232
JA
1864 int diff = state->has_refs - state->used_refs;
1865
1866 if (diff)
1867 fput_many(state->file, diff);
1868 state->file = NULL;
1869 }
1870}
1871
1872/*
1873 * Get as many references to a file as we have IOs left in this submission,
1874 * assuming most submissions are for one file, or at least that each file
1875 * has more than one submission.
1876 */
8da11c19 1877static struct file *__io_file_get(struct io_submit_state *state, int fd)
9a56a232
JA
1878{
1879 if (!state)
1880 return fget(fd);
1881
1882 if (state->file) {
1883 if (state->fd == fd) {
1884 state->used_refs++;
1885 state->ios_left--;
1886 return state->file;
1887 }
3d6770fb 1888 io_file_put(state);
9a56a232
JA
1889 }
1890 state->file = fget_many(fd, state->ios_left);
1891 if (!state->file)
1892 return NULL;
1893
1894 state->fd = fd;
1895 state->has_refs = state->ios_left;
1896 state->used_refs = 1;
1897 state->ios_left--;
1898 return state->file;
1899}
1900
2b188cc1
JA
1901/*
1902 * If we tracked the file through the SCM inflight mechanism, we could support
1903 * any file. For now, just ensure that anything potentially problematic is done
1904 * inline.
1905 */
1906static bool io_file_supports_async(struct file *file)
1907{
1908 umode_t mode = file_inode(file)->i_mode;
1909
10d59345 1910 if (S_ISBLK(mode) || S_ISCHR(mode) || S_ISSOCK(mode))
2b188cc1
JA
1911 return true;
1912 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1913 return true;
1914
1915 return false;
1916}
1917
3529d8c2
JA
1918static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1919 bool force_nonblock)
2b188cc1 1920{
def596e9 1921 struct io_ring_ctx *ctx = req->ctx;
9adbd45d 1922 struct kiocb *kiocb = &req->rw.kiocb;
09bb8394
JA
1923 unsigned ioprio;
1924 int ret;
2b188cc1 1925
491381ce
JA
1926 if (S_ISREG(file_inode(req->file)->i_mode))
1927 req->flags |= REQ_F_ISREG;
1928
2b188cc1 1929 kiocb->ki_pos = READ_ONCE(sqe->off);
ba04291e
JA
1930 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
1931 req->flags |= REQ_F_CUR_POS;
1932 kiocb->ki_pos = req->file->f_pos;
1933 }
2b188cc1 1934 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
3e577dcd
PB
1935 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1936 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1937 if (unlikely(ret))
1938 return ret;
2b188cc1
JA
1939
1940 ioprio = READ_ONCE(sqe->ioprio);
1941 if (ioprio) {
1942 ret = ioprio_check_cap(ioprio);
1943 if (ret)
09bb8394 1944 return ret;
2b188cc1
JA
1945
1946 kiocb->ki_ioprio = ioprio;
1947 } else
1948 kiocb->ki_ioprio = get_current_ioprio();
1949
8449eeda 1950 /* don't allow async punt if RWF_NOWAIT was requested */
491381ce
JA
1951 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1952 (req->file->f_flags & O_NONBLOCK))
8449eeda
SB
1953 req->flags |= REQ_F_NOWAIT;
1954
1955 if (force_nonblock)
2b188cc1 1956 kiocb->ki_flags |= IOCB_NOWAIT;
8449eeda 1957
def596e9 1958 if (ctx->flags & IORING_SETUP_IOPOLL) {
def596e9
JA
1959 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1960 !kiocb->ki_filp->f_op->iopoll)
09bb8394 1961 return -EOPNOTSUPP;
2b188cc1 1962
def596e9
JA
1963 kiocb->ki_flags |= IOCB_HIPRI;
1964 kiocb->ki_complete = io_complete_rw_iopoll;
6873e0bd 1965 req->result = 0;
def596e9 1966 } else {
09bb8394
JA
1967 if (kiocb->ki_flags & IOCB_HIPRI)
1968 return -EINVAL;
def596e9
JA
1969 kiocb->ki_complete = io_complete_rw;
1970 }
9adbd45d 1971
3529d8c2
JA
1972 req->rw.addr = READ_ONCE(sqe->addr);
1973 req->rw.len = READ_ONCE(sqe->len);
9adbd45d
JA
1974 /* we own ->private, reuse it for the buffer index */
1975 req->rw.kiocb.private = (void *) (unsigned long)
3529d8c2 1976 READ_ONCE(sqe->buf_index);
2b188cc1 1977 return 0;
2b188cc1
JA
1978}
1979
1980static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1981{
1982 switch (ret) {
1983 case -EIOCBQUEUED:
1984 break;
1985 case -ERESTARTSYS:
1986 case -ERESTARTNOINTR:
1987 case -ERESTARTNOHAND:
1988 case -ERESTART_RESTARTBLOCK:
1989 /*
1990 * We can't just restart the syscall, since previously
1991 * submitted sqes may already be in progress. Just fail this
1992 * IO with EINTR.
1993 */
1994 ret = -EINTR;
1995 /* fall through */
1996 default:
1997 kiocb->ki_complete(kiocb, ret, 0);
1998 }
1999}
2000
014db007 2001static void kiocb_done(struct kiocb *kiocb, ssize_t ret)
ba816ad6 2002{
ba04291e
JA
2003 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2004
2005 if (req->flags & REQ_F_CUR_POS)
2006 req->file->f_pos = kiocb->ki_pos;
bcaec089 2007 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
014db007 2008 io_complete_rw(kiocb, ret, 0);
ba816ad6
JA
2009 else
2010 io_rw_done(kiocb, ret);
2011}
2012
9adbd45d 2013static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
7d009165 2014 struct iov_iter *iter)
edafccee 2015{
9adbd45d
JA
2016 struct io_ring_ctx *ctx = req->ctx;
2017 size_t len = req->rw.len;
edafccee
JA
2018 struct io_mapped_ubuf *imu;
2019 unsigned index, buf_index;
2020 size_t offset;
2021 u64 buf_addr;
2022
2023 /* attempt to use fixed buffers without having provided iovecs */
2024 if (unlikely(!ctx->user_bufs))
2025 return -EFAULT;
2026
9adbd45d 2027 buf_index = (unsigned long) req->rw.kiocb.private;
edafccee
JA
2028 if (unlikely(buf_index >= ctx->nr_user_bufs))
2029 return -EFAULT;
2030
2031 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2032 imu = &ctx->user_bufs[index];
9adbd45d 2033 buf_addr = req->rw.addr;
edafccee
JA
2034
2035 /* overflow */
2036 if (buf_addr + len < buf_addr)
2037 return -EFAULT;
2038 /* not inside the mapped region */
2039 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2040 return -EFAULT;
2041
2042 /*
2043 * May not be a start of buffer, set size appropriately
2044 * and advance us to the beginning.
2045 */
2046 offset = buf_addr - imu->ubuf;
2047 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
bd11b3a3
JA
2048
2049 if (offset) {
2050 /*
2051 * Don't use iov_iter_advance() here, as it's really slow for
2052 * using the latter parts of a big fixed buffer - it iterates
2053 * over each segment manually. We can cheat a bit here, because
2054 * we know that:
2055 *
2056 * 1) it's a BVEC iter, we set it up
2057 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2058 * first and last bvec
2059 *
2060 * So just find our index, and adjust the iterator afterwards.
2061 * If the offset is within the first bvec (or the whole first
2062 * bvec, just use iov_iter_advance(). This makes it easier
2063 * since we can just skip the first segment, which may not
2064 * be PAGE_SIZE aligned.
2065 */
2066 const struct bio_vec *bvec = imu->bvec;
2067
2068 if (offset <= bvec->bv_len) {
2069 iov_iter_advance(iter, offset);
2070 } else {
2071 unsigned long seg_skip;
2072
2073 /* skip first vec */
2074 offset -= bvec->bv_len;
2075 seg_skip = 1 + (offset >> PAGE_SHIFT);
2076
2077 iter->bvec = bvec + seg_skip;
2078 iter->nr_segs -= seg_skip;
99c79f66 2079 iter->count -= bvec->bv_len + offset;
bd11b3a3 2080 iter->iov_offset = offset & ~PAGE_MASK;
bd11b3a3
JA
2081 }
2082 }
2083
5e559561 2084 return len;
edafccee
JA
2085}
2086
cf6fd4bd
PB
2087static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
2088 struct iovec **iovec, struct iov_iter *iter)
2b188cc1 2089{
9adbd45d
JA
2090 void __user *buf = u64_to_user_ptr(req->rw.addr);
2091 size_t sqe_len = req->rw.len;
edafccee
JA
2092 u8 opcode;
2093
d625c6ee 2094 opcode = req->opcode;
7d009165 2095 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
edafccee 2096 *iovec = NULL;
9adbd45d 2097 return io_import_fixed(req, rw, iter);
edafccee 2098 }
2b188cc1 2099
9adbd45d
JA
2100 /* buffer index only valid with fixed read/write */
2101 if (req->rw.kiocb.private)
2102 return -EINVAL;
2103
3a6820f2
JA
2104 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2105 ssize_t ret;
2106 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2107 *iovec = NULL;
3a901598 2108 return ret < 0 ? ret : sqe_len;
3a6820f2
JA
2109 }
2110
f67676d1
JA
2111 if (req->io) {
2112 struct io_async_rw *iorw = &req->io->rw;
2113
2114 *iovec = iorw->iov;
2115 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
2116 if (iorw->iov == iorw->fast_iov)
2117 *iovec = NULL;
2118 return iorw->size;
2119 }
2120
2b188cc1 2121#ifdef CONFIG_COMPAT
cf6fd4bd 2122 if (req->ctx->compat)
2b188cc1
JA
2123 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
2124 iovec, iter);
2125#endif
2126
2127 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
2128}
2129
31b51510 2130/*
32960613
JA
2131 * For files that don't have ->read_iter() and ->write_iter(), handle them
2132 * by looping over ->read() or ->write() manually.
31b51510 2133 */
32960613
JA
2134static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2135 struct iov_iter *iter)
2136{
2137 ssize_t ret = 0;
2138
2139 /*
2140 * Don't support polled IO through this interface, and we can't
2141 * support non-blocking either. For the latter, this just causes
2142 * the kiocb to be handled from an async context.
2143 */
2144 if (kiocb->ki_flags & IOCB_HIPRI)
2145 return -EOPNOTSUPP;
2146 if (kiocb->ki_flags & IOCB_NOWAIT)
2147 return -EAGAIN;
2148
2149 while (iov_iter_count(iter)) {
311ae9e1 2150 struct iovec iovec;
32960613
JA
2151 ssize_t nr;
2152
311ae9e1
PB
2153 if (!iov_iter_is_bvec(iter)) {
2154 iovec = iov_iter_iovec(iter);
2155 } else {
2156 /* fixed buffers import bvec */
2157 iovec.iov_base = kmap(iter->bvec->bv_page)
2158 + iter->iov_offset;
2159 iovec.iov_len = min(iter->count,
2160 iter->bvec->bv_len - iter->iov_offset);
2161 }
2162
32960613
JA
2163 if (rw == READ) {
2164 nr = file->f_op->read(file, iovec.iov_base,
2165 iovec.iov_len, &kiocb->ki_pos);
2166 } else {
2167 nr = file->f_op->write(file, iovec.iov_base,
2168 iovec.iov_len, &kiocb->ki_pos);
2169 }
2170
311ae9e1
PB
2171 if (iov_iter_is_bvec(iter))
2172 kunmap(iter->bvec->bv_page);
2173
32960613
JA
2174 if (nr < 0) {
2175 if (!ret)
2176 ret = nr;
2177 break;
2178 }
2179 ret += nr;
2180 if (nr != iovec.iov_len)
2181 break;
2182 iov_iter_advance(iter, nr);
2183 }
2184
2185 return ret;
2186}
2187
b7bb4f7d 2188static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
f67676d1
JA
2189 struct iovec *iovec, struct iovec *fast_iov,
2190 struct iov_iter *iter)
2191{
2192 req->io->rw.nr_segs = iter->nr_segs;
2193 req->io->rw.size = io_size;
2194 req->io->rw.iov = iovec;
2195 if (!req->io->rw.iov) {
2196 req->io->rw.iov = req->io->rw.fast_iov;
2197 memcpy(req->io->rw.iov, fast_iov,
2198 sizeof(struct iovec) * iter->nr_segs);
99bc4c38
PB
2199 } else {
2200 req->flags |= REQ_F_NEED_CLEANUP;
f67676d1
JA
2201 }
2202}
2203
b7bb4f7d 2204static int io_alloc_async_ctx(struct io_kiocb *req)
f67676d1 2205{
d3656344
JA
2206 if (!io_op_defs[req->opcode].async_ctx)
2207 return 0;
f67676d1 2208 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
06b76d44 2209 return req->io == NULL;
b7bb4f7d
JA
2210}
2211
b7bb4f7d
JA
2212static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
2213 struct iovec *iovec, struct iovec *fast_iov,
2214 struct iov_iter *iter)
2215{
980ad263 2216 if (!io_op_defs[req->opcode].async_ctx)
74566df3 2217 return 0;
5d204bcf
JA
2218 if (!req->io) {
2219 if (io_alloc_async_ctx(req))
2220 return -ENOMEM;
b7bb4f7d 2221
5d204bcf
JA
2222 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
2223 }
b7bb4f7d 2224 return 0;
f67676d1
JA
2225}
2226
3529d8c2
JA
2227static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2228 bool force_nonblock)
f67676d1 2229{
3529d8c2
JA
2230 struct io_async_ctx *io;
2231 struct iov_iter iter;
f67676d1
JA
2232 ssize_t ret;
2233
3529d8c2
JA
2234 ret = io_prep_rw(req, sqe, force_nonblock);
2235 if (ret)
2236 return ret;
f67676d1 2237
3529d8c2
JA
2238 if (unlikely(!(req->file->f_mode & FMODE_READ)))
2239 return -EBADF;
f67676d1 2240
5f798bea
PB
2241 /* either don't need iovec imported or already have it */
2242 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
3529d8c2
JA
2243 return 0;
2244
2245 io = req->io;
2246 io->rw.iov = io->rw.fast_iov;
2247 req->io = NULL;
2248 ret = io_import_iovec(READ, req, &io->rw.iov, &iter);
2249 req->io = io;
2250 if (ret < 0)
2251 return ret;
2252
2253 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2254 return 0;
f67676d1
JA
2255}
2256
014db007 2257static int io_read(struct io_kiocb *req, bool force_nonblock)
2b188cc1
JA
2258{
2259 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
9adbd45d 2260 struct kiocb *kiocb = &req->rw.kiocb;
2b188cc1 2261 struct iov_iter iter;
31b51510 2262 size_t iov_count;
f67676d1 2263 ssize_t io_size, ret;
2b188cc1 2264
3529d8c2 2265 ret = io_import_iovec(READ, req, &iovec, &iter);
06b76d44
JA
2266 if (ret < 0)
2267 return ret;
2b188cc1 2268
fd6c2e4c
JA
2269 /* Ensure we clear previously set non-block flag */
2270 if (!force_nonblock)
29de5f6a 2271 kiocb->ki_flags &= ~IOCB_NOWAIT;
fd6c2e4c 2272
797f3f53 2273 req->result = 0;
f67676d1 2274 io_size = ret;
9e645e11 2275 if (req->flags & REQ_F_LINK)
f67676d1
JA
2276 req->result = io_size;
2277
2278 /*
2279 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2280 * we know to async punt it even if it was opened O_NONBLOCK
2281 */
29de5f6a 2282 if (force_nonblock && !io_file_supports_async(req->file))
f67676d1 2283 goto copy_iov;
9e645e11 2284
31b51510 2285 iov_count = iov_iter_count(&iter);
9adbd45d 2286 ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
2b188cc1
JA
2287 if (!ret) {
2288 ssize_t ret2;
2289
9adbd45d
JA
2290 if (req->file->f_op->read_iter)
2291 ret2 = call_read_iter(req->file, kiocb, &iter);
32960613 2292 else
9adbd45d 2293 ret2 = loop_rw_iter(READ, req->file, kiocb, &iter);
32960613 2294
9d93a3f5 2295 /* Catch -EAGAIN return for forced non-blocking submission */
f67676d1 2296 if (!force_nonblock || ret2 != -EAGAIN) {
014db007 2297 kiocb_done(kiocb, ret2);
f67676d1
JA
2298 } else {
2299copy_iov:
b7bb4f7d 2300 ret = io_setup_async_rw(req, io_size, iovec,
f67676d1
JA
2301 inline_vecs, &iter);
2302 if (ret)
2303 goto out_free;
29de5f6a
JA
2304 /* any defer here is final, must blocking retry */
2305 if (!(req->flags & REQ_F_NOWAIT))
2306 req->flags |= REQ_F_MUST_PUNT;
f67676d1
JA
2307 return -EAGAIN;
2308 }
2b188cc1 2309 }
f67676d1 2310out_free:
1e95081c 2311 kfree(iovec);
99bc4c38 2312 req->flags &= ~REQ_F_NEED_CLEANUP;
2b188cc1
JA
2313 return ret;
2314}
2315
3529d8c2
JA
2316static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2317 bool force_nonblock)
f67676d1 2318{
3529d8c2
JA
2319 struct io_async_ctx *io;
2320 struct iov_iter iter;
f67676d1
JA
2321 ssize_t ret;
2322
3529d8c2
JA
2323 ret = io_prep_rw(req, sqe, force_nonblock);
2324 if (ret)
2325 return ret;
f67676d1 2326
3529d8c2
JA
2327 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
2328 return -EBADF;
f67676d1 2329
5f798bea
PB
2330 /* either don't need iovec imported or already have it */
2331 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
3529d8c2
JA
2332 return 0;
2333
2334 io = req->io;
2335 io->rw.iov = io->rw.fast_iov;
2336 req->io = NULL;
2337 ret = io_import_iovec(WRITE, req, &io->rw.iov, &iter);
2338 req->io = io;
2339 if (ret < 0)
2340 return ret;
2341
2342 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2343 return 0;
f67676d1
JA
2344}
2345
014db007 2346static int io_write(struct io_kiocb *req, bool force_nonblock)
2b188cc1
JA
2347{
2348 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
9adbd45d 2349 struct kiocb *kiocb = &req->rw.kiocb;
2b188cc1 2350 struct iov_iter iter;
31b51510 2351 size_t iov_count;
f67676d1 2352 ssize_t ret, io_size;
2b188cc1 2353
3529d8c2 2354 ret = io_import_iovec(WRITE, req, &iovec, &iter);
06b76d44
JA
2355 if (ret < 0)
2356 return ret;
2b188cc1 2357
fd6c2e4c
JA
2358 /* Ensure we clear previously set non-block flag */
2359 if (!force_nonblock)
9adbd45d 2360 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
fd6c2e4c 2361
797f3f53 2362 req->result = 0;
f67676d1 2363 io_size = ret;
9e645e11 2364 if (req->flags & REQ_F_LINK)
f67676d1 2365 req->result = io_size;
9e645e11 2366
f67676d1
JA
2367 /*
2368 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2369 * we know to async punt it even if it was opened O_NONBLOCK
2370 */
29de5f6a 2371 if (force_nonblock && !io_file_supports_async(req->file))
f67676d1 2372 goto copy_iov;
31b51510 2373
10d59345
JA
2374 /* file path doesn't support NOWAIT for non-direct_IO */
2375 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
2376 (req->flags & REQ_F_ISREG))
f67676d1 2377 goto copy_iov;
31b51510 2378
f67676d1 2379 iov_count = iov_iter_count(&iter);
9adbd45d 2380 ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
2b188cc1 2381 if (!ret) {
9bf7933f
RP
2382 ssize_t ret2;
2383
2b188cc1
JA
2384 /*
2385 * Open-code file_start_write here to grab freeze protection,
2386 * which will be released by another thread in
2387 * io_complete_rw(). Fool lockdep by telling it the lock got
2388 * released so that it doesn't complain about the held lock when
2389 * we return to userspace.
2390 */
491381ce 2391 if (req->flags & REQ_F_ISREG) {
9adbd45d 2392 __sb_start_write(file_inode(req->file)->i_sb,
2b188cc1 2393 SB_FREEZE_WRITE, true);
9adbd45d 2394 __sb_writers_release(file_inode(req->file)->i_sb,
2b188cc1
JA
2395 SB_FREEZE_WRITE);
2396 }
2397 kiocb->ki_flags |= IOCB_WRITE;
9bf7933f 2398
9adbd45d
JA
2399 if (req->file->f_op->write_iter)
2400 ret2 = call_write_iter(req->file, kiocb, &iter);
32960613 2401 else
9adbd45d 2402 ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
faac996c
JA
2403 /*
2404 * Raw bdev writes will -EOPNOTSUPP for IOCB_NOWAIT. Just
2405 * retry them without IOCB_NOWAIT.
2406 */
2407 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
2408 ret2 = -EAGAIN;
f67676d1 2409 if (!force_nonblock || ret2 != -EAGAIN) {
014db007 2410 kiocb_done(kiocb, ret2);
f67676d1
JA
2411 } else {
2412copy_iov:
b7bb4f7d 2413 ret = io_setup_async_rw(req, io_size, iovec,
f67676d1
JA
2414 inline_vecs, &iter);
2415 if (ret)
2416 goto out_free;
29de5f6a
JA
2417 /* any defer here is final, must blocking retry */
2418 req->flags |= REQ_F_MUST_PUNT;
f67676d1
JA
2419 return -EAGAIN;
2420 }
2b188cc1 2421 }
31b51510 2422out_free:
99bc4c38 2423 req->flags &= ~REQ_F_NEED_CLEANUP;
1e95081c 2424 kfree(iovec);
2b188cc1
JA
2425 return ret;
2426}
2427
7d67af2c
PB
2428static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2429{
2430 struct io_splice* sp = &req->splice;
2431 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
2432 int ret;
2433
2434 if (req->flags & REQ_F_NEED_CLEANUP)
2435 return 0;
2436
2437 sp->file_in = NULL;
2438 sp->off_in = READ_ONCE(sqe->splice_off_in);
2439 sp->off_out = READ_ONCE(sqe->off);
2440 sp->len = READ_ONCE(sqe->len);
2441 sp->flags = READ_ONCE(sqe->splice_flags);
2442
2443 if (unlikely(sp->flags & ~valid_flags))
2444 return -EINVAL;
2445
2446 ret = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in), &sp->file_in,
2447 (sp->flags & SPLICE_F_FD_IN_FIXED));
2448 if (ret)
2449 return ret;
2450 req->flags |= REQ_F_NEED_CLEANUP;
2451
2452 if (!S_ISREG(file_inode(sp->file_in)->i_mode))
2453 req->work.flags |= IO_WQ_WORK_UNBOUND;
2454
2455 return 0;
2456}
2457
2458static bool io_splice_punt(struct file *file)
2459{
2460 if (get_pipe_info(file))
2461 return false;
2462 if (!io_file_supports_async(file))
2463 return true;
2464 return !(file->f_mode & O_NONBLOCK);
2465}
2466
014db007 2467static int io_splice(struct io_kiocb *req, bool force_nonblock)
7d67af2c
PB
2468{
2469 struct io_splice *sp = &req->splice;
2470 struct file *in = sp->file_in;
2471 struct file *out = sp->file_out;
2472 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
2473 loff_t *poff_in, *poff_out;
2474 long ret;
2475
2476 if (force_nonblock) {
2477 if (io_splice_punt(in) || io_splice_punt(out))
2478 return -EAGAIN;
2479 flags |= SPLICE_F_NONBLOCK;
2480 }
2481
2482 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
2483 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
2484 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
2485 if (force_nonblock && ret == -EAGAIN)
2486 return -EAGAIN;
2487
2488 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
2489 req->flags &= ~REQ_F_NEED_CLEANUP;
2490
2491 io_cqring_add_event(req, ret);
2492 if (ret != sp->len)
2493 req_set_fail_links(req);
014db007 2494 io_put_req(req);
7d67af2c
PB
2495 return 0;
2496}
2497
2b188cc1
JA
2498/*
2499 * IORING_OP_NOP just posts a completion event, nothing else.
2500 */
78e19bbe 2501static int io_nop(struct io_kiocb *req)
2b188cc1
JA
2502{
2503 struct io_ring_ctx *ctx = req->ctx;
2b188cc1 2504
def596e9
JA
2505 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2506 return -EINVAL;
2507
78e19bbe 2508 io_cqring_add_event(req, 0);
e65ef56d 2509 io_put_req(req);
2b188cc1
JA
2510 return 0;
2511}
2512
3529d8c2 2513static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
c992fe29 2514{
6b06314c 2515 struct io_ring_ctx *ctx = req->ctx;
c992fe29 2516
09bb8394
JA
2517 if (!req->file)
2518 return -EBADF;
c992fe29 2519
6b06314c 2520 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
def596e9 2521 return -EINVAL;
edafccee 2522 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
c992fe29
CH
2523 return -EINVAL;
2524
8ed8d3c3
JA
2525 req->sync.flags = READ_ONCE(sqe->fsync_flags);
2526 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
2527 return -EINVAL;
2528
2529 req->sync.off = READ_ONCE(sqe->off);
2530 req->sync.len = READ_ONCE(sqe->len);
c992fe29
CH
2531 return 0;
2532}
2533
8ed8d3c3
JA
2534static bool io_req_cancelled(struct io_kiocb *req)
2535{
2536 if (req->work.flags & IO_WQ_WORK_CANCEL) {
2537 req_set_fail_links(req);
2538 io_cqring_add_event(req, -ECANCELED);
594506fe 2539 io_double_put_req(req);
8ed8d3c3
JA
2540 return true;
2541 }
2542
2543 return false;
2544}
2545
78912934
JA
2546static void io_link_work_cb(struct io_wq_work **workptr)
2547{
2548 struct io_wq_work *work = *workptr;
2549 struct io_kiocb *link = work->data;
2550
2551 io_queue_linked_timeout(link);
5eae8619 2552 io_wq_submit_work(workptr);
78912934
JA
2553}
2554
2555static void io_wq_assign_next(struct io_wq_work **workptr, struct io_kiocb *nxt)
2556{
2557 struct io_kiocb *link;
2558
78912934 2559 *workptr = &nxt->work;
3b17cf5a 2560 link = io_prep_linked_timeout(nxt);
78912934 2561 if (link) {
78912934
JA
2562 nxt->work.func = io_link_work_cb;
2563 nxt->work.data = link;
2564 }
2565}
2566
014db007 2567static void __io_fsync(struct io_kiocb *req)
8ed8d3c3 2568{
8ed8d3c3 2569 loff_t end = req->sync.off + req->sync.len;
8ed8d3c3
JA
2570 int ret;
2571
9adbd45d 2572 ret = vfs_fsync_range(req->file, req->sync.off,
8ed8d3c3
JA
2573 end > 0 ? end : LLONG_MAX,
2574 req->sync.flags & IORING_FSYNC_DATASYNC);
2575 if (ret < 0)
2576 req_set_fail_links(req);
2577 io_cqring_add_event(req, ret);
014db007 2578 io_put_req(req);
5ea62161
PB
2579}
2580
2581static void io_fsync_finish(struct io_wq_work **workptr)
2582{
2583 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2584 struct io_kiocb *nxt = NULL;
2585
2586 if (io_req_cancelled(req))
2587 return;
014db007 2588 __io_fsync(req);
594506fe 2589 io_put_req(req); /* drop submission reference */
8ed8d3c3 2590 if (nxt)
78912934 2591 io_wq_assign_next(workptr, nxt);
8ed8d3c3
JA
2592}
2593
014db007 2594static int io_fsync(struct io_kiocb *req, bool force_nonblock)
c992fe29 2595{
c992fe29 2596 /* fsync always requires a blocking context */
8ed8d3c3 2597 if (force_nonblock) {
8ed8d3c3 2598 req->work.func = io_fsync_finish;
c992fe29 2599 return -EAGAIN;
8ed8d3c3 2600 }
014db007 2601 __io_fsync(req);
c992fe29
CH
2602 return 0;
2603}
2604
014db007 2605static void __io_fallocate(struct io_kiocb *req)
8ed8d3c3 2606{
8ed8d3c3
JA
2607 int ret;
2608
d63d1b5e
JA
2609 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
2610 req->sync.len);
8ed8d3c3
JA
2611 if (ret < 0)
2612 req_set_fail_links(req);
2613 io_cqring_add_event(req, ret);
014db007 2614 io_put_req(req);
5ea62161
PB
2615}
2616
2617static void io_fallocate_finish(struct io_wq_work **workptr)
2618{
2619 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2620 struct io_kiocb *nxt = NULL;
2621
594506fe
PB
2622 if (io_req_cancelled(req))
2623 return;
014db007 2624 __io_fallocate(req);
594506fe 2625 io_put_req(req); /* drop submission reference */
8ed8d3c3 2626 if (nxt)
78912934 2627 io_wq_assign_next(workptr, nxt);
5d17b4a4
JA
2628}
2629
d63d1b5e
JA
2630static int io_fallocate_prep(struct io_kiocb *req,
2631 const struct io_uring_sqe *sqe)
2632{
2633 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
2634 return -EINVAL;
2635
2636 req->sync.off = READ_ONCE(sqe->off);
2637 req->sync.len = READ_ONCE(sqe->addr);
2638 req->sync.mode = READ_ONCE(sqe->len);
2639 return 0;
2640}
2641
014db007 2642static int io_fallocate(struct io_kiocb *req, bool force_nonblock)
5d17b4a4 2643{
d63d1b5e 2644 /* fallocate always requiring blocking context */
8ed8d3c3 2645 if (force_nonblock) {
d63d1b5e 2646 req->work.func = io_fallocate_finish;
5d17b4a4 2647 return -EAGAIN;
8ed8d3c3 2648 }
5d17b4a4 2649
014db007 2650 __io_fallocate(req);
5d17b4a4
JA
2651 return 0;
2652}
2653
15b71abe 2654static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
b7bb4f7d 2655{
f8748881 2656 const char __user *fname;
15b71abe 2657 int ret;
b7bb4f7d 2658
15b71abe
JA
2659 if (sqe->ioprio || sqe->buf_index)
2660 return -EINVAL;
cf3040ca
JA
2661 if (sqe->flags & IOSQE_FIXED_FILE)
2662 return -EBADF;
0bdbdd08
PB
2663 if (req->flags & REQ_F_NEED_CLEANUP)
2664 return 0;
03b1230c 2665
15b71abe 2666 req->open.dfd = READ_ONCE(sqe->fd);
c12cedf2 2667 req->open.how.mode = READ_ONCE(sqe->len);
f8748881 2668 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
c12cedf2 2669 req->open.how.flags = READ_ONCE(sqe->open_flags);
3529d8c2 2670
f8748881 2671 req->open.filename = getname(fname);
15b71abe
JA
2672 if (IS_ERR(req->open.filename)) {
2673 ret = PTR_ERR(req->open.filename);
2674 req->open.filename = NULL;
2675 return ret;
2676 }
3529d8c2 2677
8fef80bf 2678 req->flags |= REQ_F_NEED_CLEANUP;
15b71abe 2679 return 0;
03b1230c
JA
2680}
2681
cebdb986 2682static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
aa1fa28f 2683{
cebdb986
JA
2684 struct open_how __user *how;
2685 const char __user *fname;
2686 size_t len;
0fa03c62
JA
2687 int ret;
2688
cebdb986 2689 if (sqe->ioprio || sqe->buf_index)
0fa03c62 2690 return -EINVAL;
cf3040ca
JA
2691 if (sqe->flags & IOSQE_FIXED_FILE)
2692 return -EBADF;
0bdbdd08
PB
2693 if (req->flags & REQ_F_NEED_CLEANUP)
2694 return 0;
0fa03c62 2695
cebdb986
JA
2696 req->open.dfd = READ_ONCE(sqe->fd);
2697 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2698 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2699 len = READ_ONCE(sqe->len);
0fa03c62 2700
cebdb986
JA
2701 if (len < OPEN_HOW_SIZE_VER0)
2702 return -EINVAL;
3529d8c2 2703
cebdb986
JA
2704 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
2705 len);
2706 if (ret)
2707 return ret;
3529d8c2 2708
cebdb986
JA
2709 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
2710 req->open.how.flags |= O_LARGEFILE;
0fa03c62 2711
cebdb986
JA
2712 req->open.filename = getname(fname);
2713 if (IS_ERR(req->open.filename)) {
2714 ret = PTR_ERR(req->open.filename);
2715 req->open.filename = NULL;
2716 return ret;
2717 }
2718
8fef80bf 2719 req->flags |= REQ_F_NEED_CLEANUP;
cebdb986
JA
2720 return 0;
2721}
2722
014db007 2723static int io_openat2(struct io_kiocb *req, bool force_nonblock)
15b71abe
JA
2724{
2725 struct open_flags op;
15b71abe
JA
2726 struct file *file;
2727 int ret;
2728
f86cd20c 2729 if (force_nonblock)
15b71abe 2730 return -EAGAIN;
15b71abe 2731
cebdb986 2732 ret = build_open_flags(&req->open.how, &op);
15b71abe
JA
2733 if (ret)
2734 goto err;
2735
cebdb986 2736 ret = get_unused_fd_flags(req->open.how.flags);
15b71abe
JA
2737 if (ret < 0)
2738 goto err;
2739
2740 file = do_filp_open(req->open.dfd, req->open.filename, &op);
2741 if (IS_ERR(file)) {
2742 put_unused_fd(ret);
2743 ret = PTR_ERR(file);
2744 } else {
2745 fsnotify_open(file);
2746 fd_install(ret, file);
2747 }
2748err:
2749 putname(req->open.filename);
8fef80bf 2750 req->flags &= ~REQ_F_NEED_CLEANUP;
15b71abe
JA
2751 if (ret < 0)
2752 req_set_fail_links(req);
2753 io_cqring_add_event(req, ret);
014db007 2754 io_put_req(req);
15b71abe
JA
2755 return 0;
2756}
2757
014db007 2758static int io_openat(struct io_kiocb *req, bool force_nonblock)
cebdb986
JA
2759{
2760 req->open.how = build_open_how(req->open.how.flags, req->open.how.mode);
014db007 2761 return io_openat2(req, force_nonblock);
cebdb986
JA
2762}
2763
3e4827b0
JA
2764static int io_epoll_ctl_prep(struct io_kiocb *req,
2765 const struct io_uring_sqe *sqe)
2766{
2767#if defined(CONFIG_EPOLL)
2768 if (sqe->ioprio || sqe->buf_index)
2769 return -EINVAL;
2770
2771 req->epoll.epfd = READ_ONCE(sqe->fd);
2772 req->epoll.op = READ_ONCE(sqe->len);
2773 req->epoll.fd = READ_ONCE(sqe->off);
2774
2775 if (ep_op_has_event(req->epoll.op)) {
2776 struct epoll_event __user *ev;
2777
2778 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
2779 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
2780 return -EFAULT;
2781 }
2782
2783 return 0;
2784#else
2785 return -EOPNOTSUPP;
2786#endif
2787}
2788
014db007 2789static int io_epoll_ctl(struct io_kiocb *req, bool force_nonblock)
3e4827b0
JA
2790{
2791#if defined(CONFIG_EPOLL)
2792 struct io_epoll *ie = &req->epoll;
2793 int ret;
2794
2795 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
2796 if (force_nonblock && ret == -EAGAIN)
2797 return -EAGAIN;
2798
2799 if (ret < 0)
2800 req_set_fail_links(req);
2801 io_cqring_add_event(req, ret);
014db007 2802 io_put_req(req);
3e4827b0
JA
2803 return 0;
2804#else
2805 return -EOPNOTSUPP;
2806#endif
2807}
2808
c1ca757b
JA
2809static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2810{
2811#if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
2812 if (sqe->ioprio || sqe->buf_index || sqe->off)
2813 return -EINVAL;
2814
2815 req->madvise.addr = READ_ONCE(sqe->addr);
2816 req->madvise.len = READ_ONCE(sqe->len);
2817 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
2818 return 0;
2819#else
2820 return -EOPNOTSUPP;
2821#endif
2822}
2823
014db007 2824static int io_madvise(struct io_kiocb *req, bool force_nonblock)
c1ca757b
JA
2825{
2826#if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
2827 struct io_madvise *ma = &req->madvise;
2828 int ret;
2829
2830 if (force_nonblock)
2831 return -EAGAIN;
2832
2833 ret = do_madvise(ma->addr, ma->len, ma->advice);
2834 if (ret < 0)
2835 req_set_fail_links(req);
2836 io_cqring_add_event(req, ret);
014db007 2837 io_put_req(req);
c1ca757b
JA
2838 return 0;
2839#else
2840 return -EOPNOTSUPP;
2841#endif
2842}
2843
4840e418
JA
2844static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2845{
2846 if (sqe->ioprio || sqe->buf_index || sqe->addr)
2847 return -EINVAL;
2848
2849 req->fadvise.offset = READ_ONCE(sqe->off);
2850 req->fadvise.len = READ_ONCE(sqe->len);
2851 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
2852 return 0;
2853}
2854
014db007 2855static int io_fadvise(struct io_kiocb *req, bool force_nonblock)
4840e418
JA
2856{
2857 struct io_fadvise *fa = &req->fadvise;
2858 int ret;
2859
3e69426d
JA
2860 if (force_nonblock) {
2861 switch (fa->advice) {
2862 case POSIX_FADV_NORMAL:
2863 case POSIX_FADV_RANDOM:
2864 case POSIX_FADV_SEQUENTIAL:
2865 break;
2866 default:
2867 return -EAGAIN;
2868 }
2869 }
4840e418
JA
2870
2871 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
2872 if (ret < 0)
2873 req_set_fail_links(req);
2874 io_cqring_add_event(req, ret);
014db007 2875 io_put_req(req);
4840e418
JA
2876 return 0;
2877}
2878
eddc7ef5
JA
2879static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2880{
f8748881 2881 const char __user *fname;
eddc7ef5
JA
2882 unsigned lookup_flags;
2883 int ret;
2884
2885 if (sqe->ioprio || sqe->buf_index)
2886 return -EINVAL;
cf3040ca
JA
2887 if (sqe->flags & IOSQE_FIXED_FILE)
2888 return -EBADF;
0bdbdd08
PB
2889 if (req->flags & REQ_F_NEED_CLEANUP)
2890 return 0;
eddc7ef5
JA
2891
2892 req->open.dfd = READ_ONCE(sqe->fd);
2893 req->open.mask = READ_ONCE(sqe->len);
f8748881 2894 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
eddc7ef5 2895 req->open.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
c12cedf2 2896 req->open.how.flags = READ_ONCE(sqe->statx_flags);
eddc7ef5 2897
c12cedf2 2898 if (vfs_stat_set_lookup_flags(&lookup_flags, req->open.how.flags))
eddc7ef5
JA
2899 return -EINVAL;
2900
f8748881 2901 req->open.filename = getname_flags(fname, lookup_flags, NULL);
eddc7ef5
JA
2902 if (IS_ERR(req->open.filename)) {
2903 ret = PTR_ERR(req->open.filename);
2904 req->open.filename = NULL;
2905 return ret;
2906 }
2907
8fef80bf 2908 req->flags |= REQ_F_NEED_CLEANUP;
eddc7ef5
JA
2909 return 0;
2910}
2911
014db007 2912static int io_statx(struct io_kiocb *req, bool force_nonblock)
eddc7ef5
JA
2913{
2914 struct io_open *ctx = &req->open;
2915 unsigned lookup_flags;
2916 struct path path;
2917 struct kstat stat;
2918 int ret;
2919
2920 if (force_nonblock)
2921 return -EAGAIN;
2922
c12cedf2 2923 if (vfs_stat_set_lookup_flags(&lookup_flags, ctx->how.flags))
eddc7ef5
JA
2924 return -EINVAL;
2925
2926retry:
2927 /* filename_lookup() drops it, keep a reference */
2928 ctx->filename->refcnt++;
2929
2930 ret = filename_lookup(ctx->dfd, ctx->filename, lookup_flags, &path,
2931 NULL);
2932 if (ret)
2933 goto err;
2934
c12cedf2 2935 ret = vfs_getattr(&path, &stat, ctx->mask, ctx->how.flags);
eddc7ef5
JA
2936 path_put(&path);
2937 if (retry_estale(ret, lookup_flags)) {
2938 lookup_flags |= LOOKUP_REVAL;
2939 goto retry;
2940 }
2941 if (!ret)
2942 ret = cp_statx(&stat, ctx->buffer);
2943err:
2944 putname(ctx->filename);
8fef80bf 2945 req->flags &= ~REQ_F_NEED_CLEANUP;
eddc7ef5
JA
2946 if (ret < 0)
2947 req_set_fail_links(req);
2948 io_cqring_add_event(req, ret);
014db007 2949 io_put_req(req);
eddc7ef5
JA
2950 return 0;
2951}
2952
b5dba59e
JA
2953static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2954{
2955 /*
2956 * If we queue this for async, it must not be cancellable. That would
2957 * leave the 'file' in an undeterminate state.
2958 */
2959 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
2960
2961 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
2962 sqe->rw_flags || sqe->buf_index)
2963 return -EINVAL;
2964 if (sqe->flags & IOSQE_FIXED_FILE)
cf3040ca 2965 return -EBADF;
b5dba59e
JA
2966
2967 req->close.fd = READ_ONCE(sqe->fd);
2968 if (req->file->f_op == &io_uring_fops ||
b14cca0c 2969 req->close.fd == req->ctx->ring_fd)
b5dba59e
JA
2970 return -EBADF;
2971
2972 return 0;
2973}
2974
a93b3331 2975/* only called when __close_fd_get_file() is done */
014db007 2976static void __io_close_finish(struct io_kiocb *req)
a93b3331
PB
2977{
2978 int ret;
2979
2980 ret = filp_close(req->close.put_file, req->work.files);
2981 if (ret < 0)
2982 req_set_fail_links(req);
2983 io_cqring_add_event(req, ret);
2984 fput(req->close.put_file);
014db007 2985 io_put_req(req);
a93b3331
PB
2986}
2987
b5dba59e
JA
2988static void io_close_finish(struct io_wq_work **workptr)
2989{
2990 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2991 struct io_kiocb *nxt = NULL;
2992
7fbeb95d 2993 /* not cancellable, don't do io_req_cancelled() */
014db007 2994 __io_close_finish(req);
594506fe 2995 io_put_req(req); /* drop submission reference */
b5dba59e
JA
2996 if (nxt)
2997 io_wq_assign_next(workptr, nxt);
2998}
2999
014db007 3000static int io_close(struct io_kiocb *req, bool force_nonblock)
b5dba59e
JA
3001{
3002 int ret;
3003
3004 req->close.put_file = NULL;
3005 ret = __close_fd_get_file(req->close.fd, &req->close.put_file);
3006 if (ret < 0)
3007 return ret;
3008
3009 /* if the file has a flush method, be safe and punt to async */
a2100672 3010 if (req->close.put_file->f_op->flush && force_nonblock) {
594506fe
PB
3011 /* submission ref will be dropped, take it for async */
3012 refcount_inc(&req->refs);
3013
a2100672
PB
3014 req->work.func = io_close_finish;
3015 /*
3016 * Do manual async queue here to avoid grabbing files - we don't
3017 * need the files, and it'll cause io_close_finish() to close
3018 * the file again and cause a double CQE entry for this request
3019 */
3020 io_queue_async_work(req);
3021 return 0;
3022 }
b5dba59e
JA
3023
3024 /*
3025 * No ->flush(), safely close from here and just punt the
3026 * fput() to async context.
3027 */
014db007 3028 __io_close_finish(req);
a93b3331 3029 return 0;
b5dba59e
JA
3030}
3031
3529d8c2 3032static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5d17b4a4
JA
3033{
3034 struct io_ring_ctx *ctx = req->ctx;
5d17b4a4
JA
3035
3036 if (!req->file)
3037 return -EBADF;
5d17b4a4
JA
3038
3039 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3040 return -EINVAL;
3041 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3042 return -EINVAL;
3043
8ed8d3c3
JA
3044 req->sync.off = READ_ONCE(sqe->off);
3045 req->sync.len = READ_ONCE(sqe->len);
3046 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
8ed8d3c3
JA
3047 return 0;
3048}
3049
014db007 3050static void __io_sync_file_range(struct io_kiocb *req)
8ed8d3c3 3051{
8ed8d3c3
JA
3052 int ret;
3053
9adbd45d 3054 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
8ed8d3c3
JA
3055 req->sync.flags);
3056 if (ret < 0)
3057 req_set_fail_links(req);
3058 io_cqring_add_event(req, ret);
014db007 3059 io_put_req(req);
5ea62161
PB
3060}
3061
3062
3063static void io_sync_file_range_finish(struct io_wq_work **workptr)
3064{
3065 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3066 struct io_kiocb *nxt = NULL;
3067
3068 if (io_req_cancelled(req))
3069 return;
014db007 3070 __io_sync_file_range(req);
594506fe 3071 io_put_req(req); /* put submission ref */
8ed8d3c3 3072 if (nxt)
78912934 3073 io_wq_assign_next(workptr, nxt);
5d17b4a4
JA
3074}
3075
014db007 3076static int io_sync_file_range(struct io_kiocb *req, bool force_nonblock)
5d17b4a4 3077{
5d17b4a4 3078 /* sync_file_range always requires a blocking context */
8ed8d3c3 3079 if (force_nonblock) {
8ed8d3c3 3080 req->work.func = io_sync_file_range_finish;
5d17b4a4 3081 return -EAGAIN;
8ed8d3c3 3082 }
5d17b4a4 3083
014db007 3084 __io_sync_file_range(req);
5d17b4a4
JA
3085 return 0;
3086}
3087
02d27d89
PB
3088static int io_setup_async_msg(struct io_kiocb *req,
3089 struct io_async_msghdr *kmsg)
3090{
3091 if (req->io)
3092 return -EAGAIN;
3093 if (io_alloc_async_ctx(req)) {
3094 if (kmsg->iov != kmsg->fast_iov)
3095 kfree(kmsg->iov);
3096 return -ENOMEM;
3097 }
3098 req->flags |= REQ_F_NEED_CLEANUP;
3099 memcpy(&req->io->msg, kmsg, sizeof(*kmsg));
3100 return -EAGAIN;
3101}
3102
3529d8c2 3103static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
03b1230c 3104{
0fa03c62 3105#if defined(CONFIG_NET)
e47293fd 3106 struct io_sr_msg *sr = &req->sr_msg;
3529d8c2 3107 struct io_async_ctx *io = req->io;
99bc4c38 3108 int ret;
03b1230c 3109
e47293fd
JA
3110 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3111 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
fddaface 3112 sr->len = READ_ONCE(sqe->len);
3529d8c2 3113
d8768362
JA
3114#ifdef CONFIG_COMPAT
3115 if (req->ctx->compat)
3116 sr->msg_flags |= MSG_CMSG_COMPAT;
3117#endif
3118
fddaface 3119 if (!io || req->opcode == IORING_OP_SEND)
3529d8c2 3120 return 0;
5f798bea
PB
3121 /* iovec is already imported */
3122 if (req->flags & REQ_F_NEED_CLEANUP)
3123 return 0;
3529d8c2 3124
d9688565 3125 io->msg.iov = io->msg.fast_iov;
99bc4c38 3126 ret = sendmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
e47293fd 3127 &io->msg.iov);
99bc4c38
PB
3128 if (!ret)
3129 req->flags |= REQ_F_NEED_CLEANUP;
3130 return ret;
03b1230c 3131#else
e47293fd 3132 return -EOPNOTSUPP;
03b1230c
JA
3133#endif
3134}
3135
014db007 3136static int io_sendmsg(struct io_kiocb *req, bool force_nonblock)
aa1fa28f 3137{
03b1230c 3138#if defined(CONFIG_NET)
0b416c3e 3139 struct io_async_msghdr *kmsg = NULL;
0fa03c62
JA
3140 struct socket *sock;
3141 int ret;
3142
3143 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3144 return -EINVAL;
3145
3146 sock = sock_from_file(req->file, &ret);
3147 if (sock) {
b7bb4f7d 3148 struct io_async_ctx io;
0fa03c62
JA
3149 unsigned flags;
3150
03b1230c 3151 if (req->io) {
0b416c3e 3152 kmsg = &req->io->msg;
b537916c 3153 kmsg->msg.msg_name = &req->io->msg.addr;
0b416c3e
JA
3154 /* if iov is set, it's allocated already */
3155 if (!kmsg->iov)
3156 kmsg->iov = kmsg->fast_iov;
3157 kmsg->msg.msg_iter.iov = kmsg->iov;
03b1230c 3158 } else {
3529d8c2
JA
3159 struct io_sr_msg *sr = &req->sr_msg;
3160
0b416c3e 3161 kmsg = &io.msg;
b537916c 3162 kmsg->msg.msg_name = &io.msg.addr;
3529d8c2
JA
3163
3164 io.msg.iov = io.msg.fast_iov;
3165 ret = sendmsg_copy_msghdr(&io.msg.msg, sr->msg,
3166 sr->msg_flags, &io.msg.iov);
03b1230c 3167 if (ret)
3529d8c2 3168 return ret;
03b1230c 3169 }
0fa03c62 3170
e47293fd
JA
3171 flags = req->sr_msg.msg_flags;
3172 if (flags & MSG_DONTWAIT)
3173 req->flags |= REQ_F_NOWAIT;
3174 else if (force_nonblock)
3175 flags |= MSG_DONTWAIT;
3176
0b416c3e 3177 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
02d27d89
PB
3178 if (force_nonblock && ret == -EAGAIN)
3179 return io_setup_async_msg(req, kmsg);
441cdbd5
JA
3180 if (ret == -ERESTARTSYS)
3181 ret = -EINTR;
0fa03c62
JA
3182 }
3183
1e95081c 3184 if (kmsg && kmsg->iov != kmsg->fast_iov)
0b416c3e 3185 kfree(kmsg->iov);
99bc4c38 3186 req->flags &= ~REQ_F_NEED_CLEANUP;
78e19bbe 3187 io_cqring_add_event(req, ret);
4e88d6e7
JA
3188 if (ret < 0)
3189 req_set_fail_links(req);
014db007 3190 io_put_req(req);
5d17b4a4 3191 return 0;
03b1230c
JA
3192#else
3193 return -EOPNOTSUPP;
aa1fa28f 3194#endif
03b1230c 3195}
aa1fa28f 3196
014db007 3197static int io_send(struct io_kiocb *req, bool force_nonblock)
fddaface
JA
3198{
3199#if defined(CONFIG_NET)
3200 struct socket *sock;
3201 int ret;
3202
3203 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3204 return -EINVAL;
3205
3206 sock = sock_from_file(req->file, &ret);
3207 if (sock) {
3208 struct io_sr_msg *sr = &req->sr_msg;
3209 struct msghdr msg;
3210 struct iovec iov;
3211 unsigned flags;
3212
3213 ret = import_single_range(WRITE, sr->buf, sr->len, &iov,
3214 &msg.msg_iter);
3215 if (ret)
3216 return ret;
3217
3218 msg.msg_name = NULL;
3219 msg.msg_control = NULL;
3220 msg.msg_controllen = 0;
3221 msg.msg_namelen = 0;
3222
3223 flags = req->sr_msg.msg_flags;
3224 if (flags & MSG_DONTWAIT)
3225 req->flags |= REQ_F_NOWAIT;
3226 else if (force_nonblock)
3227 flags |= MSG_DONTWAIT;
3228
0b7b21e4
JA
3229 msg.msg_flags = flags;
3230 ret = sock_sendmsg(sock, &msg);
fddaface
JA
3231 if (force_nonblock && ret == -EAGAIN)
3232 return -EAGAIN;
3233 if (ret == -ERESTARTSYS)
3234 ret = -EINTR;
3235 }
3236
3237 io_cqring_add_event(req, ret);
3238 if (ret < 0)
3239 req_set_fail_links(req);
014db007 3240 io_put_req(req);
fddaface
JA
3241 return 0;
3242#else
3243 return -EOPNOTSUPP;
3244#endif
3245}
3246
3529d8c2
JA
3247static int io_recvmsg_prep(struct io_kiocb *req,
3248 const struct io_uring_sqe *sqe)
aa1fa28f
JA
3249{
3250#if defined(CONFIG_NET)
e47293fd 3251 struct io_sr_msg *sr = &req->sr_msg;
3529d8c2 3252 struct io_async_ctx *io = req->io;
99bc4c38 3253 int ret;
3529d8c2
JA
3254
3255 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3256 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
0b7b21e4 3257 sr->len = READ_ONCE(sqe->len);
06b76d44 3258
d8768362
JA
3259#ifdef CONFIG_COMPAT
3260 if (req->ctx->compat)
3261 sr->msg_flags |= MSG_CMSG_COMPAT;
3262#endif
3263
fddaface 3264 if (!io || req->opcode == IORING_OP_RECV)
06b76d44 3265 return 0;
5f798bea
PB
3266 /* iovec is already imported */
3267 if (req->flags & REQ_F_NEED_CLEANUP)
3268 return 0;
03b1230c 3269
d9688565 3270 io->msg.iov = io->msg.fast_iov;
99bc4c38 3271 ret = recvmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
e47293fd 3272 &io->msg.uaddr, &io->msg.iov);
99bc4c38
PB
3273 if (!ret)
3274 req->flags |= REQ_F_NEED_CLEANUP;
3275 return ret;
aa1fa28f 3276#else
e47293fd 3277 return -EOPNOTSUPP;
aa1fa28f
JA
3278#endif
3279}
3280
014db007 3281static int io_recvmsg(struct io_kiocb *req, bool force_nonblock)
aa1fa28f
JA
3282{
3283#if defined(CONFIG_NET)
0b416c3e 3284 struct io_async_msghdr *kmsg = NULL;
03b1230c
JA
3285 struct socket *sock;
3286 int ret;
3287
3288 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3289 return -EINVAL;
3290
3291 sock = sock_from_file(req->file, &ret);
3292 if (sock) {
b7bb4f7d 3293 struct io_async_ctx io;
03b1230c
JA
3294 unsigned flags;
3295
03b1230c 3296 if (req->io) {
0b416c3e 3297 kmsg = &req->io->msg;
b537916c 3298 kmsg->msg.msg_name = &req->io->msg.addr;
0b416c3e
JA
3299 /* if iov is set, it's allocated already */
3300 if (!kmsg->iov)
3301 kmsg->iov = kmsg->fast_iov;
3302 kmsg->msg.msg_iter.iov = kmsg->iov;
03b1230c 3303 } else {
3529d8c2
JA
3304 struct io_sr_msg *sr = &req->sr_msg;
3305
0b416c3e 3306 kmsg = &io.msg;
b537916c 3307 kmsg->msg.msg_name = &io.msg.addr;
3529d8c2
JA
3308
3309 io.msg.iov = io.msg.fast_iov;
3310 ret = recvmsg_copy_msghdr(&io.msg.msg, sr->msg,
3311 sr->msg_flags, &io.msg.uaddr,
3312 &io.msg.iov);
03b1230c 3313 if (ret)
3529d8c2 3314 return ret;
03b1230c
JA
3315 }
3316
e47293fd
JA
3317 flags = req->sr_msg.msg_flags;
3318 if (flags & MSG_DONTWAIT)
3319 req->flags |= REQ_F_NOWAIT;
3320 else if (force_nonblock)
3321 flags |= MSG_DONTWAIT;
3322
3323 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.msg,
3324 kmsg->uaddr, flags);
02d27d89
PB
3325 if (force_nonblock && ret == -EAGAIN)
3326 return io_setup_async_msg(req, kmsg);
03b1230c
JA
3327 if (ret == -ERESTARTSYS)
3328 ret = -EINTR;
3329 }
3330
1e95081c 3331 if (kmsg && kmsg->iov != kmsg->fast_iov)
0b416c3e 3332 kfree(kmsg->iov);
99bc4c38 3333 req->flags &= ~REQ_F_NEED_CLEANUP;
03b1230c 3334 io_cqring_add_event(req, ret);
4e88d6e7
JA
3335 if (ret < 0)
3336 req_set_fail_links(req);
014db007 3337 io_put_req(req);
03b1230c 3338 return 0;
0fa03c62
JA
3339#else
3340 return -EOPNOTSUPP;
3341#endif
3342}
5d17b4a4 3343
014db007 3344static int io_recv(struct io_kiocb *req, bool force_nonblock)
fddaface
JA
3345{
3346#if defined(CONFIG_NET)
3347 struct socket *sock;
3348 int ret;
3349
3350 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3351 return -EINVAL;
3352
3353 sock = sock_from_file(req->file, &ret);
3354 if (sock) {
3355 struct io_sr_msg *sr = &req->sr_msg;
3356 struct msghdr msg;
3357 struct iovec iov;
3358 unsigned flags;
3359
3360 ret = import_single_range(READ, sr->buf, sr->len, &iov,
3361 &msg.msg_iter);
3362 if (ret)
3363 return ret;
3364
3365 msg.msg_name = NULL;
3366 msg.msg_control = NULL;
3367 msg.msg_controllen = 0;
3368 msg.msg_namelen = 0;
3369 msg.msg_iocb = NULL;
3370 msg.msg_flags = 0;
3371
3372 flags = req->sr_msg.msg_flags;
3373 if (flags & MSG_DONTWAIT)
3374 req->flags |= REQ_F_NOWAIT;
3375 else if (force_nonblock)
3376 flags |= MSG_DONTWAIT;
3377
0b7b21e4 3378 ret = sock_recvmsg(sock, &msg, flags);
fddaface
JA
3379 if (force_nonblock && ret == -EAGAIN)
3380 return -EAGAIN;
3381 if (ret == -ERESTARTSYS)
3382 ret = -EINTR;
3383 }
3384
3385 io_cqring_add_event(req, ret);
3386 if (ret < 0)
3387 req_set_fail_links(req);
014db007 3388 io_put_req(req);
fddaface
JA
3389 return 0;
3390#else
3391 return -EOPNOTSUPP;
3392#endif
3393}
3394
3395
3529d8c2 3396static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
17f2fe35
JA
3397{
3398#if defined(CONFIG_NET)
8ed8d3c3
JA
3399 struct io_accept *accept = &req->accept;
3400
17f2fe35
JA
3401 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3402 return -EINVAL;
8042d6ce 3403 if (sqe->ioprio || sqe->len || sqe->buf_index)
17f2fe35
JA
3404 return -EINVAL;
3405
d55e5f5b
JA
3406 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3407 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
8ed8d3c3 3408 accept->flags = READ_ONCE(sqe->accept_flags);
8ed8d3c3
JA
3409 return 0;
3410#else
3411 return -EOPNOTSUPP;
3412#endif
3413}
17f2fe35 3414
8ed8d3c3 3415#if defined(CONFIG_NET)
014db007 3416static int __io_accept(struct io_kiocb *req, bool force_nonblock)
8ed8d3c3
JA
3417{
3418 struct io_accept *accept = &req->accept;
3419 unsigned file_flags;
3420 int ret;
3421
3422 file_flags = force_nonblock ? O_NONBLOCK : 0;
3423 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
3424 accept->addr_len, accept->flags);
3425 if (ret == -EAGAIN && force_nonblock)
17f2fe35 3426 return -EAGAIN;
8e3cca12
JA
3427 if (ret == -ERESTARTSYS)
3428 ret = -EINTR;
4e88d6e7
JA
3429 if (ret < 0)
3430 req_set_fail_links(req);
78e19bbe 3431 io_cqring_add_event(req, ret);
014db007 3432 io_put_req(req);
17f2fe35 3433 return 0;
8ed8d3c3
JA
3434}
3435
3436static void io_accept_finish(struct io_wq_work **workptr)
3437{
3438 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3439 struct io_kiocb *nxt = NULL;
3440
3441 if (io_req_cancelled(req))
3442 return;
014db007 3443 __io_accept(req, false);
594506fe 3444 io_put_req(req); /* drop submission reference */
8ed8d3c3 3445 if (nxt)
78912934 3446 io_wq_assign_next(workptr, nxt);
8ed8d3c3
JA
3447}
3448#endif
3449
014db007 3450static int io_accept(struct io_kiocb *req, bool force_nonblock)
8ed8d3c3
JA
3451{
3452#if defined(CONFIG_NET)
3453 int ret;
3454
014db007 3455 ret = __io_accept(req, force_nonblock);
8ed8d3c3
JA
3456 if (ret == -EAGAIN && force_nonblock) {
3457 req->work.func = io_accept_finish;
8ed8d3c3
JA
3458 return -EAGAIN;
3459 }
3460 return 0;
0fa03c62
JA
3461#else
3462 return -EOPNOTSUPP;
3463#endif
3464}
5d17b4a4 3465
3529d8c2 3466static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
f499a021
JA
3467{
3468#if defined(CONFIG_NET)
3529d8c2
JA
3469 struct io_connect *conn = &req->connect;
3470 struct io_async_ctx *io = req->io;
f499a021 3471
3fbb51c1
JA
3472 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3473 return -EINVAL;
3474 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
3475 return -EINVAL;
3476
3529d8c2
JA
3477 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3478 conn->addr_len = READ_ONCE(sqe->addr2);
3479
3480 if (!io)
3481 return 0;
3482
3483 return move_addr_to_kernel(conn->addr, conn->addr_len,
3fbb51c1 3484 &io->connect.address);
f499a021 3485#else
3fbb51c1 3486 return -EOPNOTSUPP;
f499a021
JA
3487#endif
3488}
3489
014db007 3490static int io_connect(struct io_kiocb *req, bool force_nonblock)
f8e85cf2
JA
3491{
3492#if defined(CONFIG_NET)
f499a021 3493 struct io_async_ctx __io, *io;
f8e85cf2 3494 unsigned file_flags;
3fbb51c1 3495 int ret;
f8e85cf2 3496
f499a021
JA
3497 if (req->io) {
3498 io = req->io;
3499 } else {
3529d8c2
JA
3500 ret = move_addr_to_kernel(req->connect.addr,
3501 req->connect.addr_len,
3502 &__io.connect.address);
f499a021
JA
3503 if (ret)
3504 goto out;
3505 io = &__io;
3506 }
3507
3fbb51c1
JA
3508 file_flags = force_nonblock ? O_NONBLOCK : 0;
3509
3510 ret = __sys_connect_file(req->file, &io->connect.address,
3511 req->connect.addr_len, file_flags);
87f80d62 3512 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
b7bb4f7d
JA
3513 if (req->io)
3514 return -EAGAIN;
3515 if (io_alloc_async_ctx(req)) {
f499a021
JA
3516 ret = -ENOMEM;
3517 goto out;
3518 }
b7bb4f7d 3519 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
f8e85cf2 3520 return -EAGAIN;
f499a021 3521 }
f8e85cf2
JA
3522 if (ret == -ERESTARTSYS)
3523 ret = -EINTR;
f499a021 3524out:
4e88d6e7
JA
3525 if (ret < 0)
3526 req_set_fail_links(req);
f8e85cf2 3527 io_cqring_add_event(req, ret);
014db007 3528 io_put_req(req);
f8e85cf2
JA
3529 return 0;
3530#else
3531 return -EOPNOTSUPP;
3532#endif
3533}
3534
d7718a9d
JA
3535struct io_poll_table {
3536 struct poll_table_struct pt;
3537 struct io_kiocb *req;
3538 int error;
3539};
3540
3541static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
3542 struct wait_queue_head *head)
3543{
3544 if (unlikely(poll->head)) {
3545 pt->error = -EINVAL;
3546 return;
3547 }
3548
3549 pt->error = 0;
3550 poll->head = head;
3551 add_wait_queue(head, &poll->wait);
3552}
3553
3554static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
3555 struct poll_table_struct *p)
3556{
3557 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
3558
3559 __io_queue_proc(&pt->req->apoll->poll, pt, head);
3560}
3561
3562static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
3563 __poll_t mask, task_work_func_t func)
3564{
3565 struct task_struct *tsk;
3566
3567 /* for instances that support it check for an event match first: */
3568 if (mask && !(mask & poll->events))
3569 return 0;
3570
3571 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
3572
3573 list_del_init(&poll->wait.entry);
3574
3575 tsk = req->task;
3576 req->result = mask;
3577 init_task_work(&req->task_work, func);
3578 /*
3579 * If this fails, then the task is exiting. If that is the case, then
3580 * the exit check will ultimately cancel these work items. Hence we
3581 * don't need to check here and handle it specifically.
3582 */
3583 task_work_add(tsk, &req->task_work, true);
3584 wake_up_process(tsk);
3585 return 1;
3586}
3587
3588static void io_async_task_func(struct callback_head *cb)
3589{
3590 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
3591 struct async_poll *apoll = req->apoll;
3592 struct io_ring_ctx *ctx = req->ctx;
3593
3594 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
3595
3596 WARN_ON_ONCE(!list_empty(&req->apoll->poll.wait.entry));
3597
3598 if (hash_hashed(&req->hash_node)) {
3599 spin_lock_irq(&ctx->completion_lock);
3600 hash_del(&req->hash_node);
3601 spin_unlock_irq(&ctx->completion_lock);
3602 }
3603
3604 /* restore ->work in case we need to retry again */
3605 memcpy(&req->work, &apoll->work, sizeof(req->work));
3606
3607 __set_current_state(TASK_RUNNING);
3608 mutex_lock(&ctx->uring_lock);
3609 __io_queue_sqe(req, NULL);
3610 mutex_unlock(&ctx->uring_lock);
3611
3612 kfree(apoll);
3613}
3614
3615static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
3616 void *key)
3617{
3618 struct io_kiocb *req = wait->private;
3619 struct io_poll_iocb *poll = &req->apoll->poll;
3620
3621 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
3622 key_to_poll(key));
3623
3624 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
3625}
3626
3627static void io_poll_req_insert(struct io_kiocb *req)
3628{
3629 struct io_ring_ctx *ctx = req->ctx;
3630 struct hlist_head *list;
3631
3632 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
3633 hlist_add_head(&req->hash_node, list);
3634}
3635
3636static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
3637 struct io_poll_iocb *poll,
3638 struct io_poll_table *ipt, __poll_t mask,
3639 wait_queue_func_t wake_func)
3640 __acquires(&ctx->completion_lock)
3641{
3642 struct io_ring_ctx *ctx = req->ctx;
3643 bool cancel = false;
3644
3645 poll->file = req->file;
3646 poll->head = NULL;
3647 poll->done = poll->canceled = false;
3648 poll->events = mask;
3649
3650 ipt->pt._key = mask;
3651 ipt->req = req;
3652 ipt->error = -EINVAL;
3653
3654 INIT_LIST_HEAD(&poll->wait.entry);
3655 init_waitqueue_func_entry(&poll->wait, wake_func);
3656 poll->wait.private = req;
3657
3658 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
3659
3660 spin_lock_irq(&ctx->completion_lock);
3661 if (likely(poll->head)) {
3662 spin_lock(&poll->head->lock);
3663 if (unlikely(list_empty(&poll->wait.entry))) {
3664 if (ipt->error)
3665 cancel = true;
3666 ipt->error = 0;
3667 mask = 0;
3668 }
3669 if (mask || ipt->error)
3670 list_del_init(&poll->wait.entry);
3671 else if (cancel)
3672 WRITE_ONCE(poll->canceled, true);
3673 else if (!poll->done) /* actually waiting for an event */
3674 io_poll_req_insert(req);
3675 spin_unlock(&poll->head->lock);
3676 }
3677
3678 return mask;
3679}
3680
3681static bool io_arm_poll_handler(struct io_kiocb *req)
3682{
3683 const struct io_op_def *def = &io_op_defs[req->opcode];
3684 struct io_ring_ctx *ctx = req->ctx;
3685 struct async_poll *apoll;
3686 struct io_poll_table ipt;
3687 __poll_t mask, ret;
3688
3689 if (!req->file || !file_can_poll(req->file))
3690 return false;
3691 if (req->flags & (REQ_F_MUST_PUNT | REQ_F_POLLED))
3692 return false;
3693 if (!def->pollin && !def->pollout)
3694 return false;
3695
3696 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
3697 if (unlikely(!apoll))
3698 return false;
3699
3700 req->flags |= REQ_F_POLLED;
3701 memcpy(&apoll->work, &req->work, sizeof(req->work));
3702
3703 /*
3704 * Don't need a reference here, as we're adding it to the task
3705 * task_works list. If the task exits, the list is pruned.
3706 */
3707 req->task = current;
3708 req->apoll = apoll;
3709 INIT_HLIST_NODE(&req->hash_node);
3710
8755d97a 3711 mask = 0;
d7718a9d 3712 if (def->pollin)
8755d97a 3713 mask |= POLLIN | POLLRDNORM;
d7718a9d
JA
3714 if (def->pollout)
3715 mask |= POLLOUT | POLLWRNORM;
3716 mask |= POLLERR | POLLPRI;
3717
3718 ipt.pt._qproc = io_async_queue_proc;
3719
3720 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
3721 io_async_wake);
3722 if (ret) {
3723 ipt.error = 0;
3724 apoll->poll.done = true;
3725 spin_unlock_irq(&ctx->completion_lock);
3726 memcpy(&req->work, &apoll->work, sizeof(req->work));
3727 kfree(apoll);
3728 return false;
3729 }
3730 spin_unlock_irq(&ctx->completion_lock);
3731 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
3732 apoll->poll.events);
3733 return true;
3734}
3735
3736static bool __io_poll_remove_one(struct io_kiocb *req,
3737 struct io_poll_iocb *poll)
221c5eb2 3738{
b41e9852 3739 bool do_complete = false;
221c5eb2
JA
3740
3741 spin_lock(&poll->head->lock);
3742 WRITE_ONCE(poll->canceled, true);
392edb45
JA
3743 if (!list_empty(&poll->wait.entry)) {
3744 list_del_init(&poll->wait.entry);
b41e9852 3745 do_complete = true;
221c5eb2
JA
3746 }
3747 spin_unlock(&poll->head->lock);
d7718a9d
JA
3748 return do_complete;
3749}
3750
3751static bool io_poll_remove_one(struct io_kiocb *req)
3752{
3753 bool do_complete;
3754
3755 if (req->opcode == IORING_OP_POLL_ADD) {
3756 do_complete = __io_poll_remove_one(req, &req->poll);
3757 } else {
3758 /* non-poll requests have submit ref still */
3759 do_complete = __io_poll_remove_one(req, &req->apoll->poll);
3760 if (do_complete)
3761 io_put_req(req);
3762 }
3763
78076bb6 3764 hash_del(&req->hash_node);
d7718a9d 3765
b41e9852
JA
3766 if (do_complete) {
3767 io_cqring_fill_event(req, -ECANCELED);
3768 io_commit_cqring(req->ctx);
3769 req->flags |= REQ_F_COMP_LOCKED;
3770 io_put_req(req);
3771 }
3772
3773 return do_complete;
221c5eb2
JA
3774}
3775
3776static void io_poll_remove_all(struct io_ring_ctx *ctx)
3777{
78076bb6 3778 struct hlist_node *tmp;
221c5eb2 3779 struct io_kiocb *req;
78076bb6 3780 int i;
221c5eb2
JA
3781
3782 spin_lock_irq(&ctx->completion_lock);
78076bb6
JA
3783 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
3784 struct hlist_head *list;
3785
3786 list = &ctx->cancel_hash[i];
3787 hlist_for_each_entry_safe(req, tmp, list, hash_node)
3788 io_poll_remove_one(req);
221c5eb2
JA
3789 }
3790 spin_unlock_irq(&ctx->completion_lock);
b41e9852
JA
3791
3792 io_cqring_ev_posted(ctx);
221c5eb2
JA
3793}
3794
47f46768
JA
3795static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
3796{
78076bb6 3797 struct hlist_head *list;
47f46768
JA
3798 struct io_kiocb *req;
3799
78076bb6
JA
3800 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
3801 hlist_for_each_entry(req, list, hash_node) {
b41e9852
JA
3802 if (sqe_addr != req->user_data)
3803 continue;
3804 if (io_poll_remove_one(req))
eac406c6 3805 return 0;
b41e9852 3806 return -EALREADY;
47f46768
JA
3807 }
3808
3809 return -ENOENT;
3810}
3811
3529d8c2
JA
3812static int io_poll_remove_prep(struct io_kiocb *req,
3813 const struct io_uring_sqe *sqe)
0969e783 3814{
0969e783
JA
3815 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3816 return -EINVAL;
3817 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3818 sqe->poll_events)
3819 return -EINVAL;
3820
3821 req->poll.addr = READ_ONCE(sqe->addr);
0969e783
JA
3822 return 0;
3823}
3824
221c5eb2
JA
3825/*
3826 * Find a running poll command that matches one specified in sqe->addr,
3827 * and remove it if found.
3828 */
fc4df999 3829static int io_poll_remove(struct io_kiocb *req)
221c5eb2
JA
3830{
3831 struct io_ring_ctx *ctx = req->ctx;
0969e783 3832 u64 addr;
47f46768 3833 int ret;
221c5eb2 3834
0969e783 3835 addr = req->poll.addr;
221c5eb2 3836 spin_lock_irq(&ctx->completion_lock);
0969e783 3837 ret = io_poll_cancel(ctx, addr);
221c5eb2
JA
3838 spin_unlock_irq(&ctx->completion_lock);
3839
78e19bbe 3840 io_cqring_add_event(req, ret);
4e88d6e7
JA
3841 if (ret < 0)
3842 req_set_fail_links(req);
e65ef56d 3843 io_put_req(req);
221c5eb2
JA
3844 return 0;
3845}
3846
b0dd8a41 3847static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
221c5eb2 3848{
a197f664
JL
3849 struct io_ring_ctx *ctx = req->ctx;
3850
8c838788 3851 req->poll.done = true;
b0a20349 3852 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
8c838788 3853 io_commit_cqring(ctx);
221c5eb2
JA
3854}
3855
b41e9852 3856static void io_poll_task_handler(struct io_kiocb *req, struct io_kiocb **nxt)
221c5eb2 3857{
221c5eb2 3858 struct io_ring_ctx *ctx = req->ctx;
221c5eb2 3859
221c5eb2 3860 spin_lock_irq(&ctx->completion_lock);
78076bb6 3861 hash_del(&req->hash_node);
b41e9852
JA
3862 io_poll_complete(req, req->result, 0);
3863 req->flags |= REQ_F_COMP_LOCKED;
3864 io_put_req_find_next(req, nxt);
e94f141b
JA
3865 spin_unlock_irq(&ctx->completion_lock);
3866
3867 io_cqring_ev_posted(ctx);
e94f141b
JA
3868}
3869
b41e9852 3870static void io_poll_task_func(struct callback_head *cb)
f0b493e6 3871{
b41e9852
JA
3872 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
3873 struct io_kiocb *nxt = NULL;
f0b493e6 3874
b41e9852 3875 io_poll_task_handler(req, &nxt);
d7718a9d
JA
3876 if (nxt) {
3877 struct io_ring_ctx *ctx = nxt->ctx;
3878
3879 mutex_lock(&ctx->uring_lock);
b41e9852 3880 __io_queue_sqe(nxt, NULL);
d7718a9d
JA
3881 mutex_unlock(&ctx->uring_lock);
3882 }
f0b493e6
JA
3883}
3884
221c5eb2
JA
3885static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
3886 void *key)
3887{
c2f2eb7d
JA
3888 struct io_kiocb *req = wait->private;
3889 struct io_poll_iocb *poll = &req->poll;
221c5eb2 3890
d7718a9d 3891 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
221c5eb2
JA
3892}
3893
221c5eb2
JA
3894static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
3895 struct poll_table_struct *p)
3896{
3897 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
3898
d7718a9d 3899 __io_queue_proc(&pt->req->poll, pt, head);
eac406c6
JA
3900}
3901
3529d8c2 3902static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
221c5eb2
JA
3903{
3904 struct io_poll_iocb *poll = &req->poll;
221c5eb2 3905 u16 events;
221c5eb2
JA
3906
3907 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3908 return -EINVAL;
3909 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
3910 return -EINVAL;
09bb8394
JA
3911 if (!poll->file)
3912 return -EBADF;
221c5eb2 3913
221c5eb2
JA
3914 events = READ_ONCE(sqe->poll_events);
3915 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
b41e9852 3916
d7718a9d
JA
3917 /*
3918 * Don't need a reference here, as we're adding it to the task
3919 * task_works list. If the task exits, the list is pruned.
3920 */
b41e9852 3921 req->task = current;
0969e783
JA
3922 return 0;
3923}
3924
014db007 3925static int io_poll_add(struct io_kiocb *req)
0969e783
JA
3926{
3927 struct io_poll_iocb *poll = &req->poll;
3928 struct io_ring_ctx *ctx = req->ctx;
3929 struct io_poll_table ipt;
0969e783 3930 __poll_t mask;
0969e783 3931
78076bb6 3932 INIT_HLIST_NODE(&req->hash_node);
36703247 3933 INIT_LIST_HEAD(&req->list);
d7718a9d 3934 ipt.pt._qproc = io_poll_queue_proc;
36703247 3935
d7718a9d
JA
3936 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
3937 io_poll_wake);
221c5eb2 3938
8c838788 3939 if (mask) { /* no async, we'd stolen it */
221c5eb2 3940 ipt.error = 0;
b0dd8a41 3941 io_poll_complete(req, mask, 0);
221c5eb2 3942 }
221c5eb2
JA
3943 spin_unlock_irq(&ctx->completion_lock);
3944
8c838788
JA
3945 if (mask) {
3946 io_cqring_ev_posted(ctx);
014db007 3947 io_put_req(req);
221c5eb2 3948 }
8c838788 3949 return ipt.error;
221c5eb2
JA
3950}
3951
5262f567
JA
3952static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
3953{
ad8a48ac
JA
3954 struct io_timeout_data *data = container_of(timer,
3955 struct io_timeout_data, timer);
3956 struct io_kiocb *req = data->req;
3957 struct io_ring_ctx *ctx = req->ctx;
5262f567
JA
3958 unsigned long flags;
3959
5262f567
JA
3960 atomic_inc(&ctx->cq_timeouts);
3961
3962 spin_lock_irqsave(&ctx->completion_lock, flags);
ef03681a 3963 /*
11365043
JA
3964 * We could be racing with timeout deletion. If the list is empty,
3965 * then timeout lookup already found it and will be handling it.
ef03681a 3966 */
842f9612 3967 if (!list_empty(&req->list)) {
11365043 3968 struct io_kiocb *prev;
5262f567 3969
11365043
JA
3970 /*
3971 * Adjust the reqs sequence before the current one because it
d195a66e 3972 * will consume a slot in the cq_ring and the cq_tail
11365043
JA
3973 * pointer will be increased, otherwise other timeout reqs may
3974 * return in advance without waiting for enough wait_nr.
3975 */
3976 prev = req;
3977 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
3978 prev->sequence++;
11365043 3979 list_del_init(&req->list);
11365043 3980 }
5262f567 3981
78e19bbe 3982 io_cqring_fill_event(req, -ETIME);
5262f567
JA
3983 io_commit_cqring(ctx);
3984 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3985
3986 io_cqring_ev_posted(ctx);
4e88d6e7 3987 req_set_fail_links(req);
5262f567
JA
3988 io_put_req(req);
3989 return HRTIMER_NORESTART;
3990}
3991
47f46768
JA
3992static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
3993{
3994 struct io_kiocb *req;
3995 int ret = -ENOENT;
3996
3997 list_for_each_entry(req, &ctx->timeout_list, list) {
3998 if (user_data == req->user_data) {
3999 list_del_init(&req->list);
4000 ret = 0;
4001 break;
4002 }
4003 }
4004
4005 if (ret == -ENOENT)
4006 return ret;
4007
2d28390a 4008 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
47f46768
JA
4009 if (ret == -1)
4010 return -EALREADY;
4011
4e88d6e7 4012 req_set_fail_links(req);
47f46768
JA
4013 io_cqring_fill_event(req, -ECANCELED);
4014 io_put_req(req);
4015 return 0;
4016}
4017
3529d8c2
JA
4018static int io_timeout_remove_prep(struct io_kiocb *req,
4019 const struct io_uring_sqe *sqe)
b29472ee 4020{
b29472ee
JA
4021 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4022 return -EINVAL;
4023 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
4024 return -EINVAL;
4025
4026 req->timeout.addr = READ_ONCE(sqe->addr);
4027 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
4028 if (req->timeout.flags)
4029 return -EINVAL;
4030
b29472ee
JA
4031 return 0;
4032}
4033
11365043
JA
4034/*
4035 * Remove or update an existing timeout command
4036 */
fc4df999 4037static int io_timeout_remove(struct io_kiocb *req)
11365043
JA
4038{
4039 struct io_ring_ctx *ctx = req->ctx;
47f46768 4040 int ret;
11365043 4041
11365043 4042 spin_lock_irq(&ctx->completion_lock);
b29472ee 4043 ret = io_timeout_cancel(ctx, req->timeout.addr);
11365043 4044
47f46768 4045 io_cqring_fill_event(req, ret);
11365043
JA
4046 io_commit_cqring(ctx);
4047 spin_unlock_irq(&ctx->completion_lock);
5262f567 4048 io_cqring_ev_posted(ctx);
4e88d6e7
JA
4049 if (ret < 0)
4050 req_set_fail_links(req);
ec9c02ad 4051 io_put_req(req);
11365043 4052 return 0;
5262f567
JA
4053}
4054
3529d8c2 4055static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2d28390a 4056 bool is_timeout_link)
5262f567 4057{
ad8a48ac 4058 struct io_timeout_data *data;
a41525ab 4059 unsigned flags;
5262f567 4060
ad8a48ac 4061 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5262f567 4062 return -EINVAL;
ad8a48ac 4063 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
a41525ab 4064 return -EINVAL;
2d28390a
JA
4065 if (sqe->off && is_timeout_link)
4066 return -EINVAL;
a41525ab
JA
4067 flags = READ_ONCE(sqe->timeout_flags);
4068 if (flags & ~IORING_TIMEOUT_ABS)
5262f567 4069 return -EINVAL;
bdf20073 4070
26a61679
JA
4071 req->timeout.count = READ_ONCE(sqe->off);
4072
3529d8c2 4073 if (!req->io && io_alloc_async_ctx(req))
26a61679
JA
4074 return -ENOMEM;
4075
4076 data = &req->io->timeout;
ad8a48ac 4077 data->req = req;
ad8a48ac
JA
4078 req->flags |= REQ_F_TIMEOUT;
4079
4080 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5262f567
JA
4081 return -EFAULT;
4082
11365043 4083 if (flags & IORING_TIMEOUT_ABS)
ad8a48ac 4084 data->mode = HRTIMER_MODE_ABS;
11365043 4085 else
ad8a48ac 4086 data->mode = HRTIMER_MODE_REL;
11365043 4087
ad8a48ac
JA
4088 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
4089 return 0;
4090}
4091
fc4df999 4092static int io_timeout(struct io_kiocb *req)
ad8a48ac
JA
4093{
4094 unsigned count;
4095 struct io_ring_ctx *ctx = req->ctx;
4096 struct io_timeout_data *data;
4097 struct list_head *entry;
4098 unsigned span = 0;
ad8a48ac 4099
2d28390a 4100 data = &req->io->timeout;
93bd25bb 4101
5262f567
JA
4102 /*
4103 * sqe->off holds how many events that need to occur for this
93bd25bb
JA
4104 * timeout event to be satisfied. If it isn't set, then this is
4105 * a pure timeout request, sequence isn't used.
5262f567 4106 */
26a61679 4107 count = req->timeout.count;
93bd25bb
JA
4108 if (!count) {
4109 req->flags |= REQ_F_TIMEOUT_NOSEQ;
4110 spin_lock_irq(&ctx->completion_lock);
4111 entry = ctx->timeout_list.prev;
4112 goto add;
4113 }
5262f567
JA
4114
4115 req->sequence = ctx->cached_sq_head + count - 1;
2d28390a 4116 data->seq_offset = count;
5262f567
JA
4117
4118 /*
4119 * Insertion sort, ensuring the first entry in the list is always
4120 * the one we need first.
4121 */
5262f567
JA
4122 spin_lock_irq(&ctx->completion_lock);
4123 list_for_each_prev(entry, &ctx->timeout_list) {
4124 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
5da0fb1a 4125 unsigned nxt_sq_head;
4126 long long tmp, tmp_nxt;
2d28390a 4127 u32 nxt_offset = nxt->io->timeout.seq_offset;
5262f567 4128
93bd25bb
JA
4129 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
4130 continue;
4131
5da0fb1a 4132 /*
4133 * Since cached_sq_head + count - 1 can overflow, use type long
4134 * long to store it.
4135 */
4136 tmp = (long long)ctx->cached_sq_head + count - 1;
cc42e0ac
PB
4137 nxt_sq_head = nxt->sequence - nxt_offset + 1;
4138 tmp_nxt = (long long)nxt_sq_head + nxt_offset - 1;
5da0fb1a 4139
4140 /*
4141 * cached_sq_head may overflow, and it will never overflow twice
4142 * once there is some timeout req still be valid.
4143 */
4144 if (ctx->cached_sq_head < nxt_sq_head)
8b07a65a 4145 tmp += UINT_MAX;
5da0fb1a 4146
a1f58ba4 4147 if (tmp > tmp_nxt)
5262f567 4148 break;
a1f58ba4 4149
4150 /*
4151 * Sequence of reqs after the insert one and itself should
4152 * be adjusted because each timeout req consumes a slot.
4153 */
4154 span++;
4155 nxt->sequence++;
5262f567 4156 }
a1f58ba4 4157 req->sequence -= span;
93bd25bb 4158add:
5262f567 4159 list_add(&req->list, entry);
ad8a48ac
JA
4160 data->timer.function = io_timeout_fn;
4161 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5262f567 4162 spin_unlock_irq(&ctx->completion_lock);
5262f567
JA
4163 return 0;
4164}
5262f567 4165
62755e35
JA
4166static bool io_cancel_cb(struct io_wq_work *work, void *data)
4167{
4168 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4169
4170 return req->user_data == (unsigned long) data;
4171}
4172
e977d6d3 4173static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
62755e35 4174{
62755e35 4175 enum io_wq_cancel cancel_ret;
62755e35
JA
4176 int ret = 0;
4177
62755e35
JA
4178 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
4179 switch (cancel_ret) {
4180 case IO_WQ_CANCEL_OK:
4181 ret = 0;
4182 break;
4183 case IO_WQ_CANCEL_RUNNING:
4184 ret = -EALREADY;
4185 break;
4186 case IO_WQ_CANCEL_NOTFOUND:
4187 ret = -ENOENT;
4188 break;
4189 }
4190
e977d6d3
JA
4191 return ret;
4192}
4193
47f46768
JA
4194static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
4195 struct io_kiocb *req, __u64 sqe_addr,
014db007 4196 int success_ret)
47f46768
JA
4197{
4198 unsigned long flags;
4199 int ret;
4200
4201 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
4202 if (ret != -ENOENT) {
4203 spin_lock_irqsave(&ctx->completion_lock, flags);
4204 goto done;
4205 }
4206
4207 spin_lock_irqsave(&ctx->completion_lock, flags);
4208 ret = io_timeout_cancel(ctx, sqe_addr);
4209 if (ret != -ENOENT)
4210 goto done;
4211 ret = io_poll_cancel(ctx, sqe_addr);
4212done:
b0dd8a41
JA
4213 if (!ret)
4214 ret = success_ret;
47f46768
JA
4215 io_cqring_fill_event(req, ret);
4216 io_commit_cqring(ctx);
4217 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4218 io_cqring_ev_posted(ctx);
4219
4e88d6e7
JA
4220 if (ret < 0)
4221 req_set_fail_links(req);
014db007 4222 io_put_req(req);
47f46768
JA
4223}
4224
3529d8c2
JA
4225static int io_async_cancel_prep(struct io_kiocb *req,
4226 const struct io_uring_sqe *sqe)
e977d6d3 4227{
fbf23849 4228 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
e977d6d3
JA
4229 return -EINVAL;
4230 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
4231 sqe->cancel_flags)
4232 return -EINVAL;
4233
fbf23849
JA
4234 req->cancel.addr = READ_ONCE(sqe->addr);
4235 return 0;
4236}
4237
014db007 4238static int io_async_cancel(struct io_kiocb *req)
fbf23849
JA
4239{
4240 struct io_ring_ctx *ctx = req->ctx;
fbf23849 4241
014db007 4242 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
5262f567
JA
4243 return 0;
4244}
4245
05f3fb3c
JA
4246static int io_files_update_prep(struct io_kiocb *req,
4247 const struct io_uring_sqe *sqe)
4248{
4249 if (sqe->flags || sqe->ioprio || sqe->rw_flags)
4250 return -EINVAL;
4251
4252 req->files_update.offset = READ_ONCE(sqe->off);
4253 req->files_update.nr_args = READ_ONCE(sqe->len);
4254 if (!req->files_update.nr_args)
4255 return -EINVAL;
4256 req->files_update.arg = READ_ONCE(sqe->addr);
4257 return 0;
4258}
4259
4260static int io_files_update(struct io_kiocb *req, bool force_nonblock)
fbf23849
JA
4261{
4262 struct io_ring_ctx *ctx = req->ctx;
05f3fb3c
JA
4263 struct io_uring_files_update up;
4264 int ret;
fbf23849 4265
f86cd20c 4266 if (force_nonblock)
05f3fb3c 4267 return -EAGAIN;
05f3fb3c
JA
4268
4269 up.offset = req->files_update.offset;
4270 up.fds = req->files_update.arg;
4271
4272 mutex_lock(&ctx->uring_lock);
4273 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
4274 mutex_unlock(&ctx->uring_lock);
4275
4276 if (ret < 0)
4277 req_set_fail_links(req);
4278 io_cqring_add_event(req, ret);
4279 io_put_req(req);
5262f567
JA
4280 return 0;
4281}
4282
3529d8c2
JA
4283static int io_req_defer_prep(struct io_kiocb *req,
4284 const struct io_uring_sqe *sqe)
f67676d1 4285{
e781573e 4286 ssize_t ret = 0;
f67676d1 4287
f86cd20c
JA
4288 if (io_op_defs[req->opcode].file_table) {
4289 ret = io_grab_files(req);
4290 if (unlikely(ret))
4291 return ret;
4292 }
4293
cccf0ee8
JA
4294 io_req_work_grab_env(req, &io_op_defs[req->opcode]);
4295
d625c6ee 4296 switch (req->opcode) {
e781573e
JA
4297 case IORING_OP_NOP:
4298 break;
f67676d1
JA
4299 case IORING_OP_READV:
4300 case IORING_OP_READ_FIXED:
3a6820f2 4301 case IORING_OP_READ:
3529d8c2 4302 ret = io_read_prep(req, sqe, true);
f67676d1
JA
4303 break;
4304 case IORING_OP_WRITEV:
4305 case IORING_OP_WRITE_FIXED:
3a6820f2 4306 case IORING_OP_WRITE:
3529d8c2 4307 ret = io_write_prep(req, sqe, true);
f67676d1 4308 break;
0969e783 4309 case IORING_OP_POLL_ADD:
3529d8c2 4310 ret = io_poll_add_prep(req, sqe);
0969e783
JA
4311 break;
4312 case IORING_OP_POLL_REMOVE:
3529d8c2 4313 ret = io_poll_remove_prep(req, sqe);
0969e783 4314 break;
8ed8d3c3 4315 case IORING_OP_FSYNC:
3529d8c2 4316 ret = io_prep_fsync(req, sqe);
8ed8d3c3
JA
4317 break;
4318 case IORING_OP_SYNC_FILE_RANGE:
3529d8c2 4319 ret = io_prep_sfr(req, sqe);
8ed8d3c3 4320 break;
03b1230c 4321 case IORING_OP_SENDMSG:
fddaface 4322 case IORING_OP_SEND:
3529d8c2 4323 ret = io_sendmsg_prep(req, sqe);
03b1230c
JA
4324 break;
4325 case IORING_OP_RECVMSG:
fddaface 4326 case IORING_OP_RECV:
3529d8c2 4327 ret = io_recvmsg_prep(req, sqe);
03b1230c 4328 break;
f499a021 4329 case IORING_OP_CONNECT:
3529d8c2 4330 ret = io_connect_prep(req, sqe);
f499a021 4331 break;
2d28390a 4332 case IORING_OP_TIMEOUT:
3529d8c2 4333 ret = io_timeout_prep(req, sqe, false);
b7bb4f7d 4334 break;
b29472ee 4335 case IORING_OP_TIMEOUT_REMOVE:
3529d8c2 4336 ret = io_timeout_remove_prep(req, sqe);
b29472ee 4337 break;
fbf23849 4338 case IORING_OP_ASYNC_CANCEL:
3529d8c2 4339 ret = io_async_cancel_prep(req, sqe);
fbf23849 4340 break;
2d28390a 4341 case IORING_OP_LINK_TIMEOUT:
3529d8c2 4342 ret = io_timeout_prep(req, sqe, true);
b7bb4f7d 4343 break;
8ed8d3c3 4344 case IORING_OP_ACCEPT:
3529d8c2 4345 ret = io_accept_prep(req, sqe);
8ed8d3c3 4346 break;
d63d1b5e
JA
4347 case IORING_OP_FALLOCATE:
4348 ret = io_fallocate_prep(req, sqe);
4349 break;
15b71abe
JA
4350 case IORING_OP_OPENAT:
4351 ret = io_openat_prep(req, sqe);
4352 break;
b5dba59e
JA
4353 case IORING_OP_CLOSE:
4354 ret = io_close_prep(req, sqe);
4355 break;
05f3fb3c
JA
4356 case IORING_OP_FILES_UPDATE:
4357 ret = io_files_update_prep(req, sqe);
4358 break;
eddc7ef5
JA
4359 case IORING_OP_STATX:
4360 ret = io_statx_prep(req, sqe);
4361 break;
4840e418
JA
4362 case IORING_OP_FADVISE:
4363 ret = io_fadvise_prep(req, sqe);
4364 break;
c1ca757b
JA
4365 case IORING_OP_MADVISE:
4366 ret = io_madvise_prep(req, sqe);
4367 break;
cebdb986
JA
4368 case IORING_OP_OPENAT2:
4369 ret = io_openat2_prep(req, sqe);
4370 break;
3e4827b0
JA
4371 case IORING_OP_EPOLL_CTL:
4372 ret = io_epoll_ctl_prep(req, sqe);
4373 break;
7d67af2c
PB
4374 case IORING_OP_SPLICE:
4375 ret = io_splice_prep(req, sqe);
4376 break;
f67676d1 4377 default:
e781573e
JA
4378 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
4379 req->opcode);
4380 ret = -EINVAL;
b7bb4f7d 4381 break;
f67676d1
JA
4382 }
4383
b7bb4f7d 4384 return ret;
f67676d1
JA
4385}
4386
3529d8c2 4387static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
de0617e4 4388{
a197f664 4389 struct io_ring_ctx *ctx = req->ctx;
f67676d1 4390 int ret;
de0617e4 4391
9d858b21
BL
4392 /* Still need defer if there is pending req in defer list. */
4393 if (!req_need_defer(req) && list_empty(&ctx->defer_list))
de0617e4
JA
4394 return 0;
4395
3529d8c2 4396 if (!req->io && io_alloc_async_ctx(req))
de0617e4
JA
4397 return -EAGAIN;
4398
3529d8c2 4399 ret = io_req_defer_prep(req, sqe);
b7bb4f7d 4400 if (ret < 0)
2d28390a 4401 return ret;
2d28390a 4402
de0617e4 4403 spin_lock_irq(&ctx->completion_lock);
9d858b21 4404 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
de0617e4 4405 spin_unlock_irq(&ctx->completion_lock);
de0617e4
JA
4406 return 0;
4407 }
4408
915967f6 4409 trace_io_uring_defer(ctx, req, req->user_data);
de0617e4
JA
4410 list_add_tail(&req->list, &ctx->defer_list);
4411 spin_unlock_irq(&ctx->completion_lock);
4412 return -EIOCBQUEUED;
4413}
4414
99bc4c38
PB
4415static void io_cleanup_req(struct io_kiocb *req)
4416{
4417 struct io_async_ctx *io = req->io;
4418
4419 switch (req->opcode) {
4420 case IORING_OP_READV:
4421 case IORING_OP_READ_FIXED:
4422 case IORING_OP_READ:
4423 case IORING_OP_WRITEV:
4424 case IORING_OP_WRITE_FIXED:
4425 case IORING_OP_WRITE:
4426 if (io->rw.iov != io->rw.fast_iov)
4427 kfree(io->rw.iov);
4428 break;
4429 case IORING_OP_SENDMSG:
4430 case IORING_OP_RECVMSG:
4431 if (io->msg.iov != io->msg.fast_iov)
4432 kfree(io->msg.iov);
4433 break;
8fef80bf
PB
4434 case IORING_OP_OPENAT:
4435 case IORING_OP_OPENAT2:
4436 case IORING_OP_STATX:
4437 putname(req->open.filename);
4438 break;
7d67af2c
PB
4439 case IORING_OP_SPLICE:
4440 io_put_file(req, req->splice.file_in,
4441 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
4442 break;
99bc4c38
PB
4443 }
4444
4445 req->flags &= ~REQ_F_NEED_CLEANUP;
4446}
4447
3529d8c2 4448static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
014db007 4449 bool force_nonblock)
2b188cc1 4450{
a197f664 4451 struct io_ring_ctx *ctx = req->ctx;
d625c6ee 4452 int ret;
2b188cc1 4453
d625c6ee 4454 switch (req->opcode) {
2b188cc1 4455 case IORING_OP_NOP:
78e19bbe 4456 ret = io_nop(req);
2b188cc1
JA
4457 break;
4458 case IORING_OP_READV:
edafccee 4459 case IORING_OP_READ_FIXED:
3a6820f2 4460 case IORING_OP_READ:
3529d8c2
JA
4461 if (sqe) {
4462 ret = io_read_prep(req, sqe, force_nonblock);
4463 if (ret < 0)
4464 break;
4465 }
014db007 4466 ret = io_read(req, force_nonblock);
edafccee 4467 break;
3529d8c2 4468 case IORING_OP_WRITEV:
edafccee 4469 case IORING_OP_WRITE_FIXED:
3a6820f2 4470 case IORING_OP_WRITE:
3529d8c2
JA
4471 if (sqe) {
4472 ret = io_write_prep(req, sqe, force_nonblock);
4473 if (ret < 0)
4474 break;
4475 }
014db007 4476 ret = io_write(req, force_nonblock);
2b188cc1 4477 break;
c992fe29 4478 case IORING_OP_FSYNC:
3529d8c2
JA
4479 if (sqe) {
4480 ret = io_prep_fsync(req, sqe);
4481 if (ret < 0)
4482 break;
4483 }
014db007 4484 ret = io_fsync(req, force_nonblock);
c992fe29 4485 break;
221c5eb2 4486 case IORING_OP_POLL_ADD:
3529d8c2
JA
4487 if (sqe) {
4488 ret = io_poll_add_prep(req, sqe);
4489 if (ret)
4490 break;
4491 }
014db007 4492 ret = io_poll_add(req);
221c5eb2
JA
4493 break;
4494 case IORING_OP_POLL_REMOVE:
3529d8c2
JA
4495 if (sqe) {
4496 ret = io_poll_remove_prep(req, sqe);
4497 if (ret < 0)
4498 break;
4499 }
fc4df999 4500 ret = io_poll_remove(req);
221c5eb2 4501 break;
5d17b4a4 4502 case IORING_OP_SYNC_FILE_RANGE:
3529d8c2
JA
4503 if (sqe) {
4504 ret = io_prep_sfr(req, sqe);
4505 if (ret < 0)
4506 break;
4507 }
014db007 4508 ret = io_sync_file_range(req, force_nonblock);
5d17b4a4 4509 break;
0fa03c62 4510 case IORING_OP_SENDMSG:
fddaface 4511 case IORING_OP_SEND:
3529d8c2
JA
4512 if (sqe) {
4513 ret = io_sendmsg_prep(req, sqe);
4514 if (ret < 0)
4515 break;
4516 }
fddaface 4517 if (req->opcode == IORING_OP_SENDMSG)
014db007 4518 ret = io_sendmsg(req, force_nonblock);
fddaface 4519 else
014db007 4520 ret = io_send(req, force_nonblock);
0fa03c62 4521 break;
aa1fa28f 4522 case IORING_OP_RECVMSG:
fddaface 4523 case IORING_OP_RECV:
3529d8c2
JA
4524 if (sqe) {
4525 ret = io_recvmsg_prep(req, sqe);
4526 if (ret)
4527 break;
4528 }
fddaface 4529 if (req->opcode == IORING_OP_RECVMSG)
014db007 4530 ret = io_recvmsg(req, force_nonblock);
fddaface 4531 else
014db007 4532 ret = io_recv(req, force_nonblock);
aa1fa28f 4533 break;
5262f567 4534 case IORING_OP_TIMEOUT:
3529d8c2
JA
4535 if (sqe) {
4536 ret = io_timeout_prep(req, sqe, false);
4537 if (ret)
4538 break;
4539 }
fc4df999 4540 ret = io_timeout(req);
5262f567 4541 break;
11365043 4542 case IORING_OP_TIMEOUT_REMOVE:
3529d8c2
JA
4543 if (sqe) {
4544 ret = io_timeout_remove_prep(req, sqe);
4545 if (ret)
4546 break;
4547 }
fc4df999 4548 ret = io_timeout_remove(req);
11365043 4549 break;
17f2fe35 4550 case IORING_OP_ACCEPT:
3529d8c2
JA
4551 if (sqe) {
4552 ret = io_accept_prep(req, sqe);
4553 if (ret)
4554 break;
4555 }
014db007 4556 ret = io_accept(req, force_nonblock);
17f2fe35 4557 break;
f8e85cf2 4558 case IORING_OP_CONNECT:
3529d8c2
JA
4559 if (sqe) {
4560 ret = io_connect_prep(req, sqe);
4561 if (ret)
4562 break;
4563 }
014db007 4564 ret = io_connect(req, force_nonblock);
f8e85cf2 4565 break;
62755e35 4566 case IORING_OP_ASYNC_CANCEL:
3529d8c2
JA
4567 if (sqe) {
4568 ret = io_async_cancel_prep(req, sqe);
4569 if (ret)
4570 break;
4571 }
014db007 4572 ret = io_async_cancel(req);
62755e35 4573 break;
d63d1b5e
JA
4574 case IORING_OP_FALLOCATE:
4575 if (sqe) {
4576 ret = io_fallocate_prep(req, sqe);
4577 if (ret)
4578 break;
4579 }
014db007 4580 ret = io_fallocate(req, force_nonblock);
d63d1b5e 4581 break;
15b71abe
JA
4582 case IORING_OP_OPENAT:
4583 if (sqe) {
4584 ret = io_openat_prep(req, sqe);
4585 if (ret)
4586 break;
4587 }
014db007 4588 ret = io_openat(req, force_nonblock);
15b71abe 4589 break;
b5dba59e
JA
4590 case IORING_OP_CLOSE:
4591 if (sqe) {
4592 ret = io_close_prep(req, sqe);
4593 if (ret)
4594 break;
4595 }
014db007 4596 ret = io_close(req, force_nonblock);
b5dba59e 4597 break;
05f3fb3c
JA
4598 case IORING_OP_FILES_UPDATE:
4599 if (sqe) {
4600 ret = io_files_update_prep(req, sqe);
4601 if (ret)
4602 break;
4603 }
4604 ret = io_files_update(req, force_nonblock);
4605 break;
eddc7ef5
JA
4606 case IORING_OP_STATX:
4607 if (sqe) {
4608 ret = io_statx_prep(req, sqe);
4609 if (ret)
4610 break;
4611 }
014db007 4612 ret = io_statx(req, force_nonblock);
eddc7ef5 4613 break;
4840e418
JA
4614 case IORING_OP_FADVISE:
4615 if (sqe) {
4616 ret = io_fadvise_prep(req, sqe);
4617 if (ret)
4618 break;
4619 }
014db007 4620 ret = io_fadvise(req, force_nonblock);
4840e418 4621 break;
c1ca757b
JA
4622 case IORING_OP_MADVISE:
4623 if (sqe) {
4624 ret = io_madvise_prep(req, sqe);
4625 if (ret)
4626 break;
4627 }
014db007 4628 ret = io_madvise(req, force_nonblock);
c1ca757b 4629 break;
cebdb986
JA
4630 case IORING_OP_OPENAT2:
4631 if (sqe) {
4632 ret = io_openat2_prep(req, sqe);
4633 if (ret)
4634 break;
4635 }
014db007 4636 ret = io_openat2(req, force_nonblock);
cebdb986 4637 break;
3e4827b0
JA
4638 case IORING_OP_EPOLL_CTL:
4639 if (sqe) {
4640 ret = io_epoll_ctl_prep(req, sqe);
4641 if (ret)
4642 break;
4643 }
014db007 4644 ret = io_epoll_ctl(req, force_nonblock);
3e4827b0 4645 break;
7d67af2c
PB
4646 case IORING_OP_SPLICE:
4647 if (sqe) {
4648 ret = io_splice_prep(req, sqe);
4649 if (ret < 0)
4650 break;
4651 }
014db007 4652 ret = io_splice(req, force_nonblock);
7d67af2c 4653 break;
2b188cc1
JA
4654 default:
4655 ret = -EINVAL;
4656 break;
4657 }
4658
def596e9
JA
4659 if (ret)
4660 return ret;
4661
4662 if (ctx->flags & IORING_SETUP_IOPOLL) {
11ba820b
JA
4663 const bool in_async = io_wq_current_is_worker();
4664
9e645e11 4665 if (req->result == -EAGAIN)
def596e9
JA
4666 return -EAGAIN;
4667
11ba820b
JA
4668 /* workqueue context doesn't hold uring_lock, grab it now */
4669 if (in_async)
4670 mutex_lock(&ctx->uring_lock);
4671
def596e9 4672 io_iopoll_req_issued(req);
11ba820b
JA
4673
4674 if (in_async)
4675 mutex_unlock(&ctx->uring_lock);
def596e9
JA
4676 }
4677
4678 return 0;
2b188cc1
JA
4679}
4680
561fb04a 4681static void io_wq_submit_work(struct io_wq_work **workptr)
2b188cc1 4682{
561fb04a 4683 struct io_wq_work *work = *workptr;
2b188cc1 4684 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
561fb04a
JA
4685 struct io_kiocb *nxt = NULL;
4686 int ret = 0;
2b188cc1 4687
0c9d5ccd
JA
4688 /* if NO_CANCEL is set, we must still run the work */
4689 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
4690 IO_WQ_WORK_CANCEL) {
561fb04a 4691 ret = -ECANCELED;
0c9d5ccd 4692 }
31b51510 4693
561fb04a 4694 if (!ret) {
561fb04a 4695 do {
014db007 4696 ret = io_issue_sqe(req, NULL, false);
561fb04a
JA
4697 /*
4698 * We can get EAGAIN for polled IO even though we're
4699 * forcing a sync submission from here, since we can't
4700 * wait for request slots on the block side.
4701 */
4702 if (ret != -EAGAIN)
4703 break;
4704 cond_resched();
4705 } while (1);
4706 }
31b51510 4707
561fb04a 4708 if (ret) {
4e88d6e7 4709 req_set_fail_links(req);
78e19bbe 4710 io_cqring_add_event(req, ret);
817869d2 4711 io_put_req(req);
edafccee 4712 }
2b188cc1 4713
594506fe
PB
4714 io_put_req(req); /* drop submission reference */
4715 if (nxt)
78912934 4716 io_wq_assign_next(workptr, nxt);
2b188cc1
JA
4717}
4718
15b71abe 4719static int io_req_needs_file(struct io_kiocb *req, int fd)
9e3aa61a 4720{
d3656344 4721 if (!io_op_defs[req->opcode].needs_file)
9e3aa61a 4722 return 0;
0b5faf6b 4723 if ((fd == -1 || fd == AT_FDCWD) && io_op_defs[req->opcode].fd_non_neg)
d3656344
JA
4724 return 0;
4725 return 1;
09bb8394
JA
4726}
4727
65e19f54
JA
4728static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
4729 int index)
4730{
4731 struct fixed_file_table *table;
4732
05f3fb3c
JA
4733 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
4734 return table->files[index & IORING_FILE_TABLE_MASK];;
65e19f54
JA
4735}
4736
8da11c19
PB
4737static int io_file_get(struct io_submit_state *state, struct io_kiocb *req,
4738 int fd, struct file **out_file, bool fixed)
09bb8394 4739{
a197f664 4740 struct io_ring_ctx *ctx = req->ctx;
8da11c19 4741 struct file *file;
09bb8394 4742
8da11c19 4743 if (fixed) {
05f3fb3c 4744 if (unlikely(!ctx->file_data ||
09bb8394
JA
4745 (unsigned) fd >= ctx->nr_user_files))
4746 return -EBADF;
b7620121 4747 fd = array_index_nospec(fd, ctx->nr_user_files);
8da11c19
PB
4748 file = io_file_from_index(ctx, fd);
4749 if (!file)
08a45173 4750 return -EBADF;
05f3fb3c 4751 percpu_ref_get(&ctx->file_data->refs);
09bb8394 4752 } else {
c826bd7a 4753 trace_io_uring_file_get(ctx, fd);
8da11c19
PB
4754 file = __io_file_get(state, fd);
4755 if (unlikely(!file))
09bb8394
JA
4756 return -EBADF;
4757 }
4758
8da11c19 4759 *out_file = file;
09bb8394
JA
4760 return 0;
4761}
4762
8da11c19
PB
4763static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
4764 const struct io_uring_sqe *sqe)
4765{
4766 unsigned flags;
4767 int fd;
4768 bool fixed;
4769
4770 flags = READ_ONCE(sqe->flags);
4771 fd = READ_ONCE(sqe->fd);
4772
4773 if (!io_req_needs_file(req, fd))
4774 return 0;
4775
4776 fixed = (flags & IOSQE_FIXED_FILE);
4777 if (unlikely(!fixed && req->needs_fixed_file))
4778 return -EBADF;
4779
4780 return io_file_get(state, req, fd, &req->file, fixed);
4781}
4782
a197f664 4783static int io_grab_files(struct io_kiocb *req)
fcb323cc
JA
4784{
4785 int ret = -EBADF;
a197f664 4786 struct io_ring_ctx *ctx = req->ctx;
fcb323cc 4787
f86cd20c
JA
4788 if (req->work.files)
4789 return 0;
b14cca0c 4790 if (!ctx->ring_file)
b5dba59e
JA
4791 return -EBADF;
4792
fcb323cc
JA
4793 rcu_read_lock();
4794 spin_lock_irq(&ctx->inflight_lock);
4795 /*
4796 * We use the f_ops->flush() handler to ensure that we can flush
4797 * out work accessing these files if the fd is closed. Check if
4798 * the fd has changed since we started down this path, and disallow
4799 * this operation if it has.
4800 */
b14cca0c 4801 if (fcheck(ctx->ring_fd) == ctx->ring_file) {
fcb323cc
JA
4802 list_add(&req->inflight_entry, &ctx->inflight_list);
4803 req->flags |= REQ_F_INFLIGHT;
4804 req->work.files = current->files;
4805 ret = 0;
4806 }
4807 spin_unlock_irq(&ctx->inflight_lock);
4808 rcu_read_unlock();
4809
4810 return ret;
4811}
4812
2665abfd 4813static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
2b188cc1 4814{
ad8a48ac
JA
4815 struct io_timeout_data *data = container_of(timer,
4816 struct io_timeout_data, timer);
4817 struct io_kiocb *req = data->req;
2665abfd
JA
4818 struct io_ring_ctx *ctx = req->ctx;
4819 struct io_kiocb *prev = NULL;
4820 unsigned long flags;
2665abfd
JA
4821
4822 spin_lock_irqsave(&ctx->completion_lock, flags);
4823
4824 /*
4825 * We don't expect the list to be empty, that will only happen if we
4826 * race with the completion of the linked work.
4827 */
4493233e
PB
4828 if (!list_empty(&req->link_list)) {
4829 prev = list_entry(req->link_list.prev, struct io_kiocb,
4830 link_list);
5d960724 4831 if (refcount_inc_not_zero(&prev->refs)) {
4493233e 4832 list_del_init(&req->link_list);
5d960724
JA
4833 prev->flags &= ~REQ_F_LINK_TIMEOUT;
4834 } else
76a46e06 4835 prev = NULL;
2665abfd
JA
4836 }
4837
4838 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4839
4840 if (prev) {
4e88d6e7 4841 req_set_fail_links(prev);
014db007 4842 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
76a46e06 4843 io_put_req(prev);
47f46768
JA
4844 } else {
4845 io_cqring_add_event(req, -ETIME);
4846 io_put_req(req);
2665abfd 4847 }
2665abfd
JA
4848 return HRTIMER_NORESTART;
4849}
4850
ad8a48ac 4851static void io_queue_linked_timeout(struct io_kiocb *req)
2665abfd 4852{
76a46e06 4853 struct io_ring_ctx *ctx = req->ctx;
2665abfd 4854
76a46e06
JA
4855 /*
4856 * If the list is now empty, then our linked request finished before
4857 * we got a chance to setup the timer
4858 */
4859 spin_lock_irq(&ctx->completion_lock);
4493233e 4860 if (!list_empty(&req->link_list)) {
2d28390a 4861 struct io_timeout_data *data = &req->io->timeout;
94ae5e77 4862
ad8a48ac
JA
4863 data->timer.function = io_link_timeout_fn;
4864 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
4865 data->mode);
2665abfd 4866 }
76a46e06 4867 spin_unlock_irq(&ctx->completion_lock);
2665abfd 4868
2665abfd 4869 /* drop submission reference */
76a46e06
JA
4870 io_put_req(req);
4871}
2665abfd 4872
ad8a48ac 4873static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
2665abfd
JA
4874{
4875 struct io_kiocb *nxt;
4876
4877 if (!(req->flags & REQ_F_LINK))
4878 return NULL;
d7718a9d
JA
4879 /* for polled retry, if flag is set, we already went through here */
4880 if (req->flags & REQ_F_POLLED)
4881 return NULL;
2665abfd 4882
4493233e
PB
4883 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
4884 link_list);
d625c6ee 4885 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
76a46e06 4886 return NULL;
2665abfd 4887
76a46e06 4888 req->flags |= REQ_F_LINK_TIMEOUT;
76a46e06 4889 return nxt;
2665abfd
JA
4890}
4891
3529d8c2 4892static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2b188cc1 4893{
4a0a7a18 4894 struct io_kiocb *linked_timeout;
4bc4494e 4895 struct io_kiocb *nxt;
193155c8 4896 const struct cred *old_creds = NULL;
e0c5c576 4897 int ret;
2b188cc1 4898
4a0a7a18
JA
4899again:
4900 linked_timeout = io_prep_linked_timeout(req);
4901
193155c8
JA
4902 if (req->work.creds && req->work.creds != current_cred()) {
4903 if (old_creds)
4904 revert_creds(old_creds);
4905 if (old_creds == req->work.creds)
4906 old_creds = NULL; /* restored original creds */
4907 else
4908 old_creds = override_creds(req->work.creds);
4909 }
4910
014db007 4911 ret = io_issue_sqe(req, sqe, true);
491381ce
JA
4912
4913 /*
4914 * We async punt it if the file wasn't marked NOWAIT, or if the file
4915 * doesn't support non-blocking read/write attempts
4916 */
4917 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
4918 (req->flags & REQ_F_MUST_PUNT))) {
d7718a9d
JA
4919 if (io_arm_poll_handler(req)) {
4920 if (linked_timeout)
4921 io_queue_linked_timeout(linked_timeout);
4bc4494e 4922 goto exit;
d7718a9d 4923 }
86a761f8 4924punt:
f86cd20c 4925 if (io_op_defs[req->opcode].file_table) {
bbad27b2
PB
4926 ret = io_grab_files(req);
4927 if (ret)
4928 goto err;
2b188cc1 4929 }
bbad27b2
PB
4930
4931 /*
4932 * Queued up for async execution, worker will release
4933 * submit reference when the iocb is actually submitted.
4934 */
4935 io_queue_async_work(req);
4bc4494e 4936 goto exit;
2b188cc1 4937 }
e65ef56d 4938
fcb323cc 4939err:
4bc4494e 4940 nxt = NULL;
76a46e06 4941 /* drop submission reference */
2a44f467 4942 io_put_req_find_next(req, &nxt);
e65ef56d 4943
f9bd67f6 4944 if (linked_timeout) {
76a46e06 4945 if (!ret)
f9bd67f6 4946 io_queue_linked_timeout(linked_timeout);
76a46e06 4947 else
f9bd67f6 4948 io_put_req(linked_timeout);
76a46e06
JA
4949 }
4950
e65ef56d 4951 /* and drop final reference, if we failed */
9e645e11 4952 if (ret) {
78e19bbe 4953 io_cqring_add_event(req, ret);
4e88d6e7 4954 req_set_fail_links(req);
e65ef56d 4955 io_put_req(req);
9e645e11 4956 }
4a0a7a18
JA
4957 if (nxt) {
4958 req = nxt;
86a761f8
PB
4959
4960 if (req->flags & REQ_F_FORCE_ASYNC)
4961 goto punt;
4a0a7a18
JA
4962 goto again;
4963 }
4bc4494e 4964exit:
193155c8
JA
4965 if (old_creds)
4966 revert_creds(old_creds);
2b188cc1
JA
4967}
4968
3529d8c2 4969static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4fe2c963
JL
4970{
4971 int ret;
4972
3529d8c2 4973 ret = io_req_defer(req, sqe);
4fe2c963
JL
4974 if (ret) {
4975 if (ret != -EIOCBQUEUED) {
1118591a 4976fail_req:
78e19bbe 4977 io_cqring_add_event(req, ret);
4e88d6e7 4978 req_set_fail_links(req);
78e19bbe 4979 io_double_put_req(req);
4fe2c963 4980 }
2550878f 4981 } else if (req->flags & REQ_F_FORCE_ASYNC) {
1118591a
PB
4982 ret = io_req_defer_prep(req, sqe);
4983 if (unlikely(ret < 0))
4984 goto fail_req;
ce35a47a
JA
4985 /*
4986 * Never try inline submit of IOSQE_ASYNC is set, go straight
4987 * to async execution.
4988 */
4989 req->work.flags |= IO_WQ_WORK_CONCURRENT;
4990 io_queue_async_work(req);
4991 } else {
3529d8c2 4992 __io_queue_sqe(req, sqe);
ce35a47a 4993 }
4fe2c963
JL
4994}
4995
1b4a51b6 4996static inline void io_queue_link_head(struct io_kiocb *req)
4fe2c963 4997{
94ae5e77 4998 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
1b4a51b6
PB
4999 io_cqring_add_event(req, -ECANCELED);
5000 io_double_put_req(req);
5001 } else
3529d8c2 5002 io_queue_sqe(req, NULL);
4fe2c963
JL
5003}
5004
4e88d6e7 5005#define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
ce35a47a 5006 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
9e645e11 5007
3529d8c2
JA
5008static bool io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5009 struct io_submit_state *state, struct io_kiocb **link)
9e645e11 5010{
a197f664 5011 struct io_ring_ctx *ctx = req->ctx;
32fe525b 5012 unsigned int sqe_flags;
75c6a039 5013 int ret, id;
9e645e11 5014
32fe525b 5015 sqe_flags = READ_ONCE(sqe->flags);
9e645e11
JA
5016
5017 /* enforce forwards compatibility on users */
32fe525b 5018 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
9e645e11 5019 ret = -EINVAL;
196be95c 5020 goto err_req;
9e645e11
JA
5021 }
5022
75c6a039
JA
5023 id = READ_ONCE(sqe->personality);
5024 if (id) {
193155c8
JA
5025 req->work.creds = idr_find(&ctx->personality_idr, id);
5026 if (unlikely(!req->work.creds)) {
75c6a039
JA
5027 ret = -EINVAL;
5028 goto err_req;
5029 }
193155c8 5030 get_cred(req->work.creds);
75c6a039
JA
5031 }
5032
6b47ee6e 5033 /* same numerical values with corresponding REQ_F_*, safe to copy */
8da11c19
PB
5034 req->flags |= sqe_flags & (IOSQE_IO_DRAIN | IOSQE_IO_HARDLINK |
5035 IOSQE_ASYNC | IOSQE_FIXED_FILE);
9e645e11 5036
3529d8c2 5037 ret = io_req_set_file(state, req, sqe);
9e645e11
JA
5038 if (unlikely(ret)) {
5039err_req:
78e19bbe
JA
5040 io_cqring_add_event(req, ret);
5041 io_double_put_req(req);
2e6e1fde 5042 return false;
9e645e11
JA
5043 }
5044
9e645e11
JA
5045 /*
5046 * If we already have a head request, queue this one for async
5047 * submittal once the head completes. If we don't have a head but
5048 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
5049 * submitted sync once the chain is complete. If none of those
5050 * conditions are true (normal request), then just queue it.
5051 */
5052 if (*link) {
9d76377f 5053 struct io_kiocb *head = *link;
4e88d6e7 5054
8cdf2193
PB
5055 /*
5056 * Taking sequential execution of a link, draining both sides
5057 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
5058 * requests in the link. So, it drains the head and the
5059 * next after the link request. The last one is done via
5060 * drain_next flag to persist the effect across calls.
5061 */
711be031
PB
5062 if (sqe_flags & IOSQE_IO_DRAIN) {
5063 head->flags |= REQ_F_IO_DRAIN;
5064 ctx->drain_next = 1;
5065 }
b7bb4f7d 5066 if (io_alloc_async_ctx(req)) {
9e645e11
JA
5067 ret = -EAGAIN;
5068 goto err_req;
5069 }
5070
3529d8c2 5071 ret = io_req_defer_prep(req, sqe);
2d28390a 5072 if (ret) {
4e88d6e7 5073 /* fail even hard links since we don't submit */
9d76377f 5074 head->flags |= REQ_F_FAIL_LINK;
f67676d1 5075 goto err_req;
2d28390a 5076 }
9d76377f
PB
5077 trace_io_uring_link(ctx, req, head);
5078 list_add_tail(&req->link_list, &head->link_list);
32fe525b
PB
5079
5080 /* last request of a link, enqueue the link */
5081 if (!(sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK))) {
5082 io_queue_link_head(head);
5083 *link = NULL;
5084 }
9e645e11 5085 } else {
711be031
PB
5086 if (unlikely(ctx->drain_next)) {
5087 req->flags |= REQ_F_IO_DRAIN;
5088 req->ctx->drain_next = 0;
5089 }
5090 if (sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK)) {
5091 req->flags |= REQ_F_LINK;
711be031
PB
5092 INIT_LIST_HEAD(&req->link_list);
5093 ret = io_req_defer_prep(req, sqe);
5094 if (ret)
5095 req->flags |= REQ_F_FAIL_LINK;
5096 *link = req;
5097 } else {
5098 io_queue_sqe(req, sqe);
5099 }
9e645e11 5100 }
2e6e1fde
PB
5101
5102 return true;
9e645e11
JA
5103}
5104
9a56a232
JA
5105/*
5106 * Batched submission is done, ensure local IO is flushed out.
5107 */
5108static void io_submit_state_end(struct io_submit_state *state)
5109{
5110 blk_finish_plug(&state->plug);
3d6770fb 5111 io_file_put(state);
2579f913 5112 if (state->free_reqs)
6c8a3134 5113 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
9a56a232
JA
5114}
5115
5116/*
5117 * Start submission side cache.
5118 */
5119static void io_submit_state_start(struct io_submit_state *state,
22efde59 5120 unsigned int max_ios)
9a56a232
JA
5121{
5122 blk_start_plug(&state->plug);
2579f913 5123 state->free_reqs = 0;
9a56a232
JA
5124 state->file = NULL;
5125 state->ios_left = max_ios;
5126}
5127
2b188cc1
JA
5128static void io_commit_sqring(struct io_ring_ctx *ctx)
5129{
75b28aff 5130 struct io_rings *rings = ctx->rings;
2b188cc1 5131
caf582c6
PB
5132 /*
5133 * Ensure any loads from the SQEs are done at this point,
5134 * since once we write the new head, the application could
5135 * write new data to them.
5136 */
5137 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2b188cc1
JA
5138}
5139
2b188cc1 5140/*
3529d8c2 5141 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
2b188cc1
JA
5142 * that is mapped by userspace. This means that care needs to be taken to
5143 * ensure that reads are stable, as we cannot rely on userspace always
5144 * being a good citizen. If members of the sqe are validated and then later
5145 * used, it's important that those reads are done through READ_ONCE() to
5146 * prevent a re-load down the line.
5147 */
3529d8c2
JA
5148static bool io_get_sqring(struct io_ring_ctx *ctx, struct io_kiocb *req,
5149 const struct io_uring_sqe **sqe_ptr)
2b188cc1 5150{
75b28aff 5151 u32 *sq_array = ctx->sq_array;
2b188cc1
JA
5152 unsigned head;
5153
5154 /*
5155 * The cached sq head (or cq tail) serves two purposes:
5156 *
5157 * 1) allows us to batch the cost of updating the user visible
5158 * head updates.
5159 * 2) allows the kernel side to track the head on its own, even
5160 * though the application is the one updating it.
5161 */
ee7d46d9 5162 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
9835d6fa 5163 if (likely(head < ctx->sq_entries)) {
cf6fd4bd
PB
5164 /*
5165 * All io need record the previous position, if LINK vs DARIN,
5166 * it can be used to mark the position of the first IO in the
5167 * link list.
5168 */
5169 req->sequence = ctx->cached_sq_head;
3529d8c2
JA
5170 *sqe_ptr = &ctx->sq_sqes[head];
5171 req->opcode = READ_ONCE((*sqe_ptr)->opcode);
5172 req->user_data = READ_ONCE((*sqe_ptr)->user_data);
2b188cc1
JA
5173 ctx->cached_sq_head++;
5174 return true;
5175 }
5176
5177 /* drop invalid entries */
5178 ctx->cached_sq_head++;
498ccd9e 5179 ctx->cached_sq_dropped++;
ee7d46d9 5180 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
2b188cc1
JA
5181 return false;
5182}
5183
fb5ccc98 5184static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
ae9428ca
PB
5185 struct file *ring_file, int ring_fd,
5186 struct mm_struct **mm, bool async)
6c271ce2
JA
5187{
5188 struct io_submit_state state, *statep = NULL;
9e645e11 5189 struct io_kiocb *link = NULL;
9e645e11 5190 int i, submitted = 0;
95a1b3ff 5191 bool mm_fault = false;
6c271ce2 5192
c4a2ed72 5193 /* if we have a backlog and couldn't flush it all, return BUSY */
ad3eb2c8
JA
5194 if (test_bit(0, &ctx->sq_check_overflow)) {
5195 if (!list_empty(&ctx->cq_overflow_list) &&
5196 !io_cqring_overflow_flush(ctx, false))
5197 return -EBUSY;
5198 }
6c271ce2 5199
ee7d46d9
PB
5200 /* make sure SQ entry isn't read before tail */
5201 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
9ef4f124 5202
2b85edfc
PB
5203 if (!percpu_ref_tryget_many(&ctx->refs, nr))
5204 return -EAGAIN;
6c271ce2
JA
5205
5206 if (nr > IO_PLUG_THRESHOLD) {
22efde59 5207 io_submit_state_start(&state, nr);
6c271ce2
JA
5208 statep = &state;
5209 }
5210
b14cca0c
PB
5211 ctx->ring_fd = ring_fd;
5212 ctx->ring_file = ring_file;
5213
6c271ce2 5214 for (i = 0; i < nr; i++) {
3529d8c2 5215 const struct io_uring_sqe *sqe;
196be95c 5216 struct io_kiocb *req;
1cb1edb2 5217 int err;
fb5ccc98 5218
196be95c
PB
5219 req = io_get_req(ctx, statep);
5220 if (unlikely(!req)) {
5221 if (!submitted)
5222 submitted = -EAGAIN;
fb5ccc98 5223 break;
196be95c 5224 }
3529d8c2 5225 if (!io_get_sqring(ctx, req, &sqe)) {
2b85edfc 5226 __io_req_do_free(req);
196be95c
PB
5227 break;
5228 }
fb5ccc98 5229
d3656344
JA
5230 /* will complete beyond this point, count as submitted */
5231 submitted++;
5232
5233 if (unlikely(req->opcode >= IORING_OP_LAST)) {
1cb1edb2
PB
5234 err = -EINVAL;
5235fail_req:
5236 io_cqring_add_event(req, err);
d3656344 5237 io_double_put_req(req);
196be95c
PB
5238 break;
5239 }
fb5ccc98 5240
d3656344 5241 if (io_op_defs[req->opcode].needs_mm && !*mm) {
95a1b3ff 5242 mm_fault = mm_fault || !mmget_not_zero(ctx->sqo_mm);
1cb1edb2
PB
5243 if (unlikely(mm_fault)) {
5244 err = -EFAULT;
5245 goto fail_req;
95a1b3ff 5246 }
1cb1edb2
PB
5247 use_mm(ctx->sqo_mm);
5248 *mm = ctx->sqo_mm;
9e645e11 5249 }
9e645e11 5250
cf6fd4bd 5251 req->needs_fixed_file = async;
354420f7
JA
5252 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
5253 true, async);
3529d8c2 5254 if (!io_submit_sqe(req, sqe, statep, &link))
2e6e1fde 5255 break;
6c271ce2
JA
5256 }
5257
9466f437
PB
5258 if (unlikely(submitted != nr)) {
5259 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
5260
5261 percpu_ref_put_many(&ctx->refs, nr - ref_used);
5262 }
9e645e11 5263 if (link)
1b4a51b6 5264 io_queue_link_head(link);
6c271ce2
JA
5265 if (statep)
5266 io_submit_state_end(&state);
5267
ae9428ca
PB
5268 /* Commit SQ ring head once we've consumed and submitted all SQEs */
5269 io_commit_sqring(ctx);
5270
6c271ce2
JA
5271 return submitted;
5272}
5273
5274static int io_sq_thread(void *data)
5275{
6c271ce2
JA
5276 struct io_ring_ctx *ctx = data;
5277 struct mm_struct *cur_mm = NULL;
181e448d 5278 const struct cred *old_cred;
6c271ce2
JA
5279 mm_segment_t old_fs;
5280 DEFINE_WAIT(wait);
6c271ce2 5281 unsigned long timeout;
bdcd3eab 5282 int ret = 0;
6c271ce2 5283
206aefde 5284 complete(&ctx->completions[1]);
a4c0b3de 5285
6c271ce2
JA
5286 old_fs = get_fs();
5287 set_fs(USER_DS);
181e448d 5288 old_cred = override_creds(ctx->creds);
6c271ce2 5289
bdcd3eab 5290 timeout = jiffies + ctx->sq_thread_idle;
2bbcd6d3 5291 while (!kthread_should_park()) {
fb5ccc98 5292 unsigned int to_submit;
6c271ce2 5293
bdcd3eab 5294 if (!list_empty(&ctx->poll_list)) {
6c271ce2
JA
5295 unsigned nr_events = 0;
5296
bdcd3eab
XW
5297 mutex_lock(&ctx->uring_lock);
5298 if (!list_empty(&ctx->poll_list))
5299 io_iopoll_getevents(ctx, &nr_events, 0);
5300 else
6c271ce2 5301 timeout = jiffies + ctx->sq_thread_idle;
bdcd3eab 5302 mutex_unlock(&ctx->uring_lock);
6c271ce2
JA
5303 }
5304
fb5ccc98 5305 to_submit = io_sqring_entries(ctx);
c1edbf5f
JA
5306
5307 /*
5308 * If submit got -EBUSY, flag us as needing the application
5309 * to enter the kernel to reap and flush events.
5310 */
5311 if (!to_submit || ret == -EBUSY) {
7143b5ac
SG
5312 /*
5313 * Drop cur_mm before scheduling, we can't hold it for
5314 * long periods (or over schedule()). Do this before
5315 * adding ourselves to the waitqueue, as the unuse/drop
5316 * may sleep.
5317 */
5318 if (cur_mm) {
5319 unuse_mm(cur_mm);
5320 mmput(cur_mm);
5321 cur_mm = NULL;
5322 }
5323
6c271ce2
JA
5324 /*
5325 * We're polling. If we're within the defined idle
5326 * period, then let us spin without work before going
c1edbf5f
JA
5327 * to sleep. The exception is if we got EBUSY doing
5328 * more IO, we should wait for the application to
5329 * reap events and wake us up.
6c271ce2 5330 */
bdcd3eab 5331 if (!list_empty(&ctx->poll_list) ||
df069d80
JA
5332 (!time_after(jiffies, timeout) && ret != -EBUSY &&
5333 !percpu_ref_is_dying(&ctx->refs))) {
b41e9852
JA
5334 if (current->task_works)
5335 task_work_run();
9831a90c 5336 cond_resched();
6c271ce2
JA
5337 continue;
5338 }
5339
6c271ce2
JA
5340 prepare_to_wait(&ctx->sqo_wait, &wait,
5341 TASK_INTERRUPTIBLE);
5342
bdcd3eab
XW
5343 /*
5344 * While doing polled IO, before going to sleep, we need
5345 * to check if there are new reqs added to poll_list, it
5346 * is because reqs may have been punted to io worker and
5347 * will be added to poll_list later, hence check the
5348 * poll_list again.
5349 */
5350 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
5351 !list_empty_careful(&ctx->poll_list)) {
5352 finish_wait(&ctx->sqo_wait, &wait);
5353 continue;
5354 }
5355
6c271ce2 5356 /* Tell userspace we may need a wakeup call */
75b28aff 5357 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
0d7bae69
SB
5358 /* make sure to read SQ tail after writing flags */
5359 smp_mb();
6c271ce2 5360
fb5ccc98 5361 to_submit = io_sqring_entries(ctx);
c1edbf5f 5362 if (!to_submit || ret == -EBUSY) {
2bbcd6d3 5363 if (kthread_should_park()) {
6c271ce2
JA
5364 finish_wait(&ctx->sqo_wait, &wait);
5365 break;
5366 }
b41e9852
JA
5367 if (current->task_works) {
5368 task_work_run();
5369 continue;
5370 }
6c271ce2
JA
5371 if (signal_pending(current))
5372 flush_signals(current);
5373 schedule();
5374 finish_wait(&ctx->sqo_wait, &wait);
5375
75b28aff 5376 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6c271ce2
JA
5377 continue;
5378 }
5379 finish_wait(&ctx->sqo_wait, &wait);
5380
75b28aff 5381 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6c271ce2
JA
5382 }
5383
8a4955ff 5384 mutex_lock(&ctx->uring_lock);
1d7bb1d5 5385 ret = io_submit_sqes(ctx, to_submit, NULL, -1, &cur_mm, true);
8a4955ff 5386 mutex_unlock(&ctx->uring_lock);
bdcd3eab 5387 timeout = jiffies + ctx->sq_thread_idle;
6c271ce2
JA
5388 }
5389
b41e9852
JA
5390 if (current->task_works)
5391 task_work_run();
5392
6c271ce2
JA
5393 set_fs(old_fs);
5394 if (cur_mm) {
5395 unuse_mm(cur_mm);
5396 mmput(cur_mm);
5397 }
181e448d 5398 revert_creds(old_cred);
06058632 5399
2bbcd6d3 5400 kthread_parkme();
06058632 5401
6c271ce2
JA
5402 return 0;
5403}
5404
bda52162
JA
5405struct io_wait_queue {
5406 struct wait_queue_entry wq;
5407 struct io_ring_ctx *ctx;
5408 unsigned to_wait;
5409 unsigned nr_timeouts;
5410};
5411
1d7bb1d5 5412static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
bda52162
JA
5413{
5414 struct io_ring_ctx *ctx = iowq->ctx;
5415
5416 /*
d195a66e 5417 * Wake up if we have enough events, or if a timeout occurred since we
bda52162
JA
5418 * started waiting. For timeouts, we always want to return to userspace,
5419 * regardless of event count.
5420 */
1d7bb1d5 5421 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
bda52162
JA
5422 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
5423}
5424
5425static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
5426 int wake_flags, void *key)
5427{
5428 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
5429 wq);
5430
1d7bb1d5
JA
5431 /* use noflush == true, as we can't safely rely on locking context */
5432 if (!io_should_wake(iowq, true))
bda52162
JA
5433 return -1;
5434
5435 return autoremove_wake_function(curr, mode, wake_flags, key);
5436}
5437
2b188cc1
JA
5438/*
5439 * Wait until events become available, if we don't already have some. The
5440 * application must reap them itself, as they reside on the shared cq ring.
5441 */
5442static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
5443 const sigset_t __user *sig, size_t sigsz)
5444{
bda52162
JA
5445 struct io_wait_queue iowq = {
5446 .wq = {
5447 .private = current,
5448 .func = io_wake_function,
5449 .entry = LIST_HEAD_INIT(iowq.wq.entry),
5450 },
5451 .ctx = ctx,
5452 .to_wait = min_events,
5453 };
75b28aff 5454 struct io_rings *rings = ctx->rings;
e9ffa5c2 5455 int ret = 0;
2b188cc1 5456
b41e9852
JA
5457 do {
5458 if (io_cqring_events(ctx, false) >= min_events)
5459 return 0;
5460 if (!current->task_works)
5461 break;
5462 task_work_run();
5463 } while (1);
2b188cc1
JA
5464
5465 if (sig) {
9e75ad5d
AB
5466#ifdef CONFIG_COMPAT
5467 if (in_compat_syscall())
5468 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
b772434b 5469 sigsz);
9e75ad5d
AB
5470 else
5471#endif
b772434b 5472 ret = set_user_sigmask(sig, sigsz);
9e75ad5d 5473
2b188cc1
JA
5474 if (ret)
5475 return ret;
5476 }
5477
bda52162 5478 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
c826bd7a 5479 trace_io_uring_cqring_wait(ctx, min_events);
bda52162
JA
5480 do {
5481 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
5482 TASK_INTERRUPTIBLE);
b41e9852
JA
5483 if (current->task_works)
5484 task_work_run();
1d7bb1d5 5485 if (io_should_wake(&iowq, false))
bda52162
JA
5486 break;
5487 schedule();
5488 if (signal_pending(current)) {
e9ffa5c2 5489 ret = -EINTR;
bda52162
JA
5490 break;
5491 }
5492 } while (1);
5493 finish_wait(&ctx->wait, &iowq.wq);
5494
e9ffa5c2 5495 restore_saved_sigmask_unless(ret == -EINTR);
2b188cc1 5496
75b28aff 5497 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
2b188cc1
JA
5498}
5499
6b06314c
JA
5500static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
5501{
5502#if defined(CONFIG_UNIX)
5503 if (ctx->ring_sock) {
5504 struct sock *sock = ctx->ring_sock->sk;
5505 struct sk_buff *skb;
5506
5507 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
5508 kfree_skb(skb);
5509 }
5510#else
5511 int i;
5512
65e19f54
JA
5513 for (i = 0; i < ctx->nr_user_files; i++) {
5514 struct file *file;
5515
5516 file = io_file_from_index(ctx, i);
5517 if (file)
5518 fput(file);
5519 }
6b06314c
JA
5520#endif
5521}
5522
05f3fb3c
JA
5523static void io_file_ref_kill(struct percpu_ref *ref)
5524{
5525 struct fixed_file_data *data;
5526
5527 data = container_of(ref, struct fixed_file_data, refs);
5528 complete(&data->done);
5529}
5530
6b06314c
JA
5531static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
5532{
05f3fb3c 5533 struct fixed_file_data *data = ctx->file_data;
65e19f54
JA
5534 unsigned nr_tables, i;
5535
05f3fb3c 5536 if (!data)
6b06314c
JA
5537 return -ENXIO;
5538
05f3fb3c 5539 percpu_ref_kill_and_confirm(&data->refs, io_file_ref_kill);
e46a7950 5540 flush_work(&data->ref_work);
2faf852d
JA
5541 wait_for_completion(&data->done);
5542 io_ring_file_ref_flush(data);
05f3fb3c
JA
5543 percpu_ref_exit(&data->refs);
5544
6b06314c 5545 __io_sqe_files_unregister(ctx);
65e19f54
JA
5546 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
5547 for (i = 0; i < nr_tables; i++)
05f3fb3c
JA
5548 kfree(data->table[i].files);
5549 kfree(data->table);
5550 kfree(data);
5551 ctx->file_data = NULL;
6b06314c
JA
5552 ctx->nr_user_files = 0;
5553 return 0;
5554}
5555
6c271ce2
JA
5556static void io_sq_thread_stop(struct io_ring_ctx *ctx)
5557{
5558 if (ctx->sqo_thread) {
206aefde 5559 wait_for_completion(&ctx->completions[1]);
2bbcd6d3
RP
5560 /*
5561 * The park is a bit of a work-around, without it we get
5562 * warning spews on shutdown with SQPOLL set and affinity
5563 * set to a single CPU.
5564 */
06058632 5565 kthread_park(ctx->sqo_thread);
6c271ce2
JA
5566 kthread_stop(ctx->sqo_thread);
5567 ctx->sqo_thread = NULL;
5568 }
5569}
5570
6b06314c
JA
5571static void io_finish_async(struct io_ring_ctx *ctx)
5572{
6c271ce2
JA
5573 io_sq_thread_stop(ctx);
5574
561fb04a
JA
5575 if (ctx->io_wq) {
5576 io_wq_destroy(ctx->io_wq);
5577 ctx->io_wq = NULL;
6b06314c
JA
5578 }
5579}
5580
5581#if defined(CONFIG_UNIX)
6b06314c
JA
5582/*
5583 * Ensure the UNIX gc is aware of our file set, so we are certain that
5584 * the io_uring can be safely unregistered on process exit, even if we have
5585 * loops in the file referencing.
5586 */
5587static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
5588{
5589 struct sock *sk = ctx->ring_sock->sk;
5590 struct scm_fp_list *fpl;
5591 struct sk_buff *skb;
08a45173 5592 int i, nr_files;
6b06314c
JA
5593
5594 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
5595 unsigned long inflight = ctx->user->unix_inflight + nr;
5596
5597 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
5598 return -EMFILE;
5599 }
5600
5601 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
5602 if (!fpl)
5603 return -ENOMEM;
5604
5605 skb = alloc_skb(0, GFP_KERNEL);
5606 if (!skb) {
5607 kfree(fpl);
5608 return -ENOMEM;
5609 }
5610
5611 skb->sk = sk;
6b06314c 5612
08a45173 5613 nr_files = 0;
6b06314c
JA
5614 fpl->user = get_uid(ctx->user);
5615 for (i = 0; i < nr; i++) {
65e19f54
JA
5616 struct file *file = io_file_from_index(ctx, i + offset);
5617
5618 if (!file)
08a45173 5619 continue;
65e19f54 5620 fpl->fp[nr_files] = get_file(file);
08a45173
JA
5621 unix_inflight(fpl->user, fpl->fp[nr_files]);
5622 nr_files++;
6b06314c
JA
5623 }
5624
08a45173
JA
5625 if (nr_files) {
5626 fpl->max = SCM_MAX_FD;
5627 fpl->count = nr_files;
5628 UNIXCB(skb).fp = fpl;
05f3fb3c 5629 skb->destructor = unix_destruct_scm;
08a45173
JA
5630 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
5631 skb_queue_head(&sk->sk_receive_queue, skb);
6b06314c 5632
08a45173
JA
5633 for (i = 0; i < nr_files; i++)
5634 fput(fpl->fp[i]);
5635 } else {
5636 kfree_skb(skb);
5637 kfree(fpl);
5638 }
6b06314c
JA
5639
5640 return 0;
5641}
5642
5643/*
5644 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
5645 * causes regular reference counting to break down. We rely on the UNIX
5646 * garbage collection to take care of this problem for us.
5647 */
5648static int io_sqe_files_scm(struct io_ring_ctx *ctx)
5649{
5650 unsigned left, total;
5651 int ret = 0;
5652
5653 total = 0;
5654 left = ctx->nr_user_files;
5655 while (left) {
5656 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
6b06314c
JA
5657
5658 ret = __io_sqe_files_scm(ctx, this_files, total);
5659 if (ret)
5660 break;
5661 left -= this_files;
5662 total += this_files;
5663 }
5664
5665 if (!ret)
5666 return 0;
5667
5668 while (total < ctx->nr_user_files) {
65e19f54
JA
5669 struct file *file = io_file_from_index(ctx, total);
5670
5671 if (file)
5672 fput(file);
6b06314c
JA
5673 total++;
5674 }
5675
5676 return ret;
5677}
5678#else
5679static int io_sqe_files_scm(struct io_ring_ctx *ctx)
5680{
5681 return 0;
5682}
5683#endif
5684
65e19f54
JA
5685static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
5686 unsigned nr_files)
5687{
5688 int i;
5689
5690 for (i = 0; i < nr_tables; i++) {
05f3fb3c 5691 struct fixed_file_table *table = &ctx->file_data->table[i];
65e19f54
JA
5692 unsigned this_files;
5693
5694 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
5695 table->files = kcalloc(this_files, sizeof(struct file *),
5696 GFP_KERNEL);
5697 if (!table->files)
5698 break;
5699 nr_files -= this_files;
5700 }
5701
5702 if (i == nr_tables)
5703 return 0;
5704
5705 for (i = 0; i < nr_tables; i++) {
05f3fb3c 5706 struct fixed_file_table *table = &ctx->file_data->table[i];
65e19f54
JA
5707 kfree(table->files);
5708 }
5709 return 1;
5710}
5711
05f3fb3c
JA
5712static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
5713{
5714#if defined(CONFIG_UNIX)
5715 struct sock *sock = ctx->ring_sock->sk;
5716 struct sk_buff_head list, *head = &sock->sk_receive_queue;
5717 struct sk_buff *skb;
5718 int i;
5719
5720 __skb_queue_head_init(&list);
5721
5722 /*
5723 * Find the skb that holds this file in its SCM_RIGHTS. When found,
5724 * remove this entry and rearrange the file array.
5725 */
5726 skb = skb_dequeue(head);
5727 while (skb) {
5728 struct scm_fp_list *fp;
5729
5730 fp = UNIXCB(skb).fp;
5731 for (i = 0; i < fp->count; i++) {
5732 int left;
5733
5734 if (fp->fp[i] != file)
5735 continue;
5736
5737 unix_notinflight(fp->user, fp->fp[i]);
5738 left = fp->count - 1 - i;
5739 if (left) {
5740 memmove(&fp->fp[i], &fp->fp[i + 1],
5741 left * sizeof(struct file *));
5742 }
5743 fp->count--;
5744 if (!fp->count) {
5745 kfree_skb(skb);
5746 skb = NULL;
5747 } else {
5748 __skb_queue_tail(&list, skb);
5749 }
5750 fput(file);
5751 file = NULL;
5752 break;
5753 }
5754
5755 if (!file)
5756 break;
5757
5758 __skb_queue_tail(&list, skb);
5759
5760 skb = skb_dequeue(head);
5761 }
5762
5763 if (skb_peek(&list)) {
5764 spin_lock_irq(&head->lock);
5765 while ((skb = __skb_dequeue(&list)) != NULL)
5766 __skb_queue_tail(head, skb);
5767 spin_unlock_irq(&head->lock);
5768 }
5769#else
5770 fput(file);
5771#endif
5772}
5773
5774struct io_file_put {
5775 struct llist_node llist;
5776 struct file *file;
5777 struct completion *done;
5778};
5779
2faf852d 5780static void io_ring_file_ref_flush(struct fixed_file_data *data)
65e19f54 5781{
05f3fb3c 5782 struct io_file_put *pfile, *tmp;
05f3fb3c 5783 struct llist_node *node;
65e19f54 5784
05f3fb3c
JA
5785 while ((node = llist_del_all(&data->put_llist)) != NULL) {
5786 llist_for_each_entry_safe(pfile, tmp, node, llist) {
5787 io_ring_file_put(data->ctx, pfile->file);
5788 if (pfile->done)
5789 complete(pfile->done);
5790 else
5791 kfree(pfile);
5792 }
65e19f54 5793 }
2faf852d 5794}
65e19f54 5795
2faf852d
JA
5796static void io_ring_file_ref_switch(struct work_struct *work)
5797{
5798 struct fixed_file_data *data;
65e19f54 5799
2faf852d
JA
5800 data = container_of(work, struct fixed_file_data, ref_work);
5801 io_ring_file_ref_flush(data);
05f3fb3c
JA
5802 percpu_ref_switch_to_percpu(&data->refs);
5803}
65e19f54 5804
05f3fb3c
JA
5805static void io_file_data_ref_zero(struct percpu_ref *ref)
5806{
5807 struct fixed_file_data *data;
5808
5809 data = container_of(ref, struct fixed_file_data, refs);
5810
2faf852d
JA
5811 /*
5812 * We can't safely switch from inside this context, punt to wq. If
5813 * the table ref is going away, the table is being unregistered.
5814 * Don't queue up the async work for that case, the caller will
5815 * handle it.
5816 */
5817 if (!percpu_ref_is_dying(&data->refs))
5818 queue_work(system_wq, &data->ref_work);
65e19f54
JA
5819}
5820
6b06314c
JA
5821static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
5822 unsigned nr_args)
5823{
5824 __s32 __user *fds = (__s32 __user *) arg;
65e19f54 5825 unsigned nr_tables;
05f3fb3c 5826 struct file *file;
6b06314c
JA
5827 int fd, ret = 0;
5828 unsigned i;
5829
05f3fb3c 5830 if (ctx->file_data)
6b06314c
JA
5831 return -EBUSY;
5832 if (!nr_args)
5833 return -EINVAL;
5834 if (nr_args > IORING_MAX_FIXED_FILES)
5835 return -EMFILE;
5836
05f3fb3c
JA
5837 ctx->file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
5838 if (!ctx->file_data)
5839 return -ENOMEM;
5840 ctx->file_data->ctx = ctx;
5841 init_completion(&ctx->file_data->done);
5842
65e19f54 5843 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
05f3fb3c
JA
5844 ctx->file_data->table = kcalloc(nr_tables,
5845 sizeof(struct fixed_file_table),
65e19f54 5846 GFP_KERNEL);
05f3fb3c
JA
5847 if (!ctx->file_data->table) {
5848 kfree(ctx->file_data);
5849 ctx->file_data = NULL;
6b06314c 5850 return -ENOMEM;
05f3fb3c
JA
5851 }
5852
5853 if (percpu_ref_init(&ctx->file_data->refs, io_file_data_ref_zero,
5854 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
5855 kfree(ctx->file_data->table);
5856 kfree(ctx->file_data);
5857 ctx->file_data = NULL;
6b06314c 5858 return -ENOMEM;
05f3fb3c
JA
5859 }
5860 ctx->file_data->put_llist.first = NULL;
5861 INIT_WORK(&ctx->file_data->ref_work, io_ring_file_ref_switch);
6b06314c 5862
65e19f54 5863 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
05f3fb3c
JA
5864 percpu_ref_exit(&ctx->file_data->refs);
5865 kfree(ctx->file_data->table);
5866 kfree(ctx->file_data);
5867 ctx->file_data = NULL;
65e19f54
JA
5868 return -ENOMEM;
5869 }
5870
08a45173 5871 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
65e19f54
JA
5872 struct fixed_file_table *table;
5873 unsigned index;
5874
6b06314c
JA
5875 ret = -EFAULT;
5876 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
5877 break;
08a45173
JA
5878 /* allow sparse sets */
5879 if (fd == -1) {
5880 ret = 0;
5881 continue;
5882 }
6b06314c 5883
05f3fb3c 5884 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
65e19f54 5885 index = i & IORING_FILE_TABLE_MASK;
05f3fb3c 5886 file = fget(fd);
6b06314c
JA
5887
5888 ret = -EBADF;
05f3fb3c 5889 if (!file)
6b06314c 5890 break;
05f3fb3c 5891
6b06314c
JA
5892 /*
5893 * Don't allow io_uring instances to be registered. If UNIX
5894 * isn't enabled, then this causes a reference cycle and this
5895 * instance can never get freed. If UNIX is enabled we'll
5896 * handle it just fine, but there's still no point in allowing
5897 * a ring fd as it doesn't support regular read/write anyway.
5898 */
05f3fb3c
JA
5899 if (file->f_op == &io_uring_fops) {
5900 fput(file);
6b06314c
JA
5901 break;
5902 }
6b06314c 5903 ret = 0;
05f3fb3c 5904 table->files[index] = file;
6b06314c
JA
5905 }
5906
5907 if (ret) {
65e19f54 5908 for (i = 0; i < ctx->nr_user_files; i++) {
65e19f54
JA
5909 file = io_file_from_index(ctx, i);
5910 if (file)
5911 fput(file);
5912 }
5913 for (i = 0; i < nr_tables; i++)
05f3fb3c 5914 kfree(ctx->file_data->table[i].files);
6b06314c 5915
05f3fb3c
JA
5916 kfree(ctx->file_data->table);
5917 kfree(ctx->file_data);
5918 ctx->file_data = NULL;
6b06314c
JA
5919 ctx->nr_user_files = 0;
5920 return ret;
5921 }
5922
5923 ret = io_sqe_files_scm(ctx);
5924 if (ret)
5925 io_sqe_files_unregister(ctx);
5926
5927 return ret;
5928}
5929
c3a31e60
JA
5930static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
5931 int index)
5932{
5933#if defined(CONFIG_UNIX)
5934 struct sock *sock = ctx->ring_sock->sk;
5935 struct sk_buff_head *head = &sock->sk_receive_queue;
5936 struct sk_buff *skb;
5937
5938 /*
5939 * See if we can merge this file into an existing skb SCM_RIGHTS
5940 * file set. If there's no room, fall back to allocating a new skb
5941 * and filling it in.
5942 */
5943 spin_lock_irq(&head->lock);
5944 skb = skb_peek(head);
5945 if (skb) {
5946 struct scm_fp_list *fpl = UNIXCB(skb).fp;
5947
5948 if (fpl->count < SCM_MAX_FD) {
5949 __skb_unlink(skb, head);
5950 spin_unlock_irq(&head->lock);
5951 fpl->fp[fpl->count] = get_file(file);
5952 unix_inflight(fpl->user, fpl->fp[fpl->count]);
5953 fpl->count++;
5954 spin_lock_irq(&head->lock);
5955 __skb_queue_head(head, skb);
5956 } else {
5957 skb = NULL;
5958 }
5959 }
5960 spin_unlock_irq(&head->lock);
5961
5962 if (skb) {
5963 fput(file);
5964 return 0;
5965 }
5966
5967 return __io_sqe_files_scm(ctx, 1, index);
5968#else
5969 return 0;
5970#endif
5971}
5972
05f3fb3c 5973static void io_atomic_switch(struct percpu_ref *ref)
c3a31e60 5974{
05f3fb3c
JA
5975 struct fixed_file_data *data;
5976
dd3db2a3
JA
5977 /*
5978 * Juggle reference to ensure we hit zero, if needed, so we can
5979 * switch back to percpu mode
5980 */
05f3fb3c 5981 data = container_of(ref, struct fixed_file_data, refs);
dd3db2a3
JA
5982 percpu_ref_put(&data->refs);
5983 percpu_ref_get(&data->refs);
05f3fb3c
JA
5984}
5985
5986static bool io_queue_file_removal(struct fixed_file_data *data,
5987 struct file *file)
5988{
5989 struct io_file_put *pfile, pfile_stack;
5990 DECLARE_COMPLETION_ONSTACK(done);
5991
5992 /*
5993 * If we fail allocating the struct we need for doing async reomval
5994 * of this file, just punt to sync and wait for it.
5995 */
5996 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
5997 if (!pfile) {
5998 pfile = &pfile_stack;
5999 pfile->done = &done;
6000 }
6001
6002 pfile->file = file;
6003 llist_add(&pfile->llist, &data->put_llist);
6004
6005 if (pfile == &pfile_stack) {
dd3db2a3 6006 percpu_ref_switch_to_atomic(&data->refs, io_atomic_switch);
05f3fb3c
JA
6007 wait_for_completion(&done);
6008 flush_work(&data->ref_work);
6009 return false;
6010 }
6011
6012 return true;
6013}
6014
6015static int __io_sqe_files_update(struct io_ring_ctx *ctx,
6016 struct io_uring_files_update *up,
6017 unsigned nr_args)
6018{
6019 struct fixed_file_data *data = ctx->file_data;
6020 bool ref_switch = false;
6021 struct file *file;
c3a31e60
JA
6022 __s32 __user *fds;
6023 int fd, i, err;
6024 __u32 done;
6025
05f3fb3c 6026 if (check_add_overflow(up->offset, nr_args, &done))
c3a31e60
JA
6027 return -EOVERFLOW;
6028 if (done > ctx->nr_user_files)
6029 return -EINVAL;
6030
6031 done = 0;
05f3fb3c 6032 fds = u64_to_user_ptr(up->fds);
c3a31e60 6033 while (nr_args) {
65e19f54
JA
6034 struct fixed_file_table *table;
6035 unsigned index;
6036
c3a31e60
JA
6037 err = 0;
6038 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
6039 err = -EFAULT;
6040 break;
6041 }
05f3fb3c
JA
6042 i = array_index_nospec(up->offset, ctx->nr_user_files);
6043 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
65e19f54
JA
6044 index = i & IORING_FILE_TABLE_MASK;
6045 if (table->files[index]) {
05f3fb3c 6046 file = io_file_from_index(ctx, index);
65e19f54 6047 table->files[index] = NULL;
05f3fb3c
JA
6048 if (io_queue_file_removal(data, file))
6049 ref_switch = true;
c3a31e60
JA
6050 }
6051 if (fd != -1) {
c3a31e60
JA
6052 file = fget(fd);
6053 if (!file) {
6054 err = -EBADF;
6055 break;
6056 }
6057 /*
6058 * Don't allow io_uring instances to be registered. If
6059 * UNIX isn't enabled, then this causes a reference
6060 * cycle and this instance can never get freed. If UNIX
6061 * is enabled we'll handle it just fine, but there's
6062 * still no point in allowing a ring fd as it doesn't
6063 * support regular read/write anyway.
6064 */
6065 if (file->f_op == &io_uring_fops) {
6066 fput(file);
6067 err = -EBADF;
6068 break;
6069 }
65e19f54 6070 table->files[index] = file;
c3a31e60
JA
6071 err = io_sqe_file_register(ctx, file, i);
6072 if (err)
6073 break;
6074 }
6075 nr_args--;
6076 done++;
05f3fb3c
JA
6077 up->offset++;
6078 }
6079
dd3db2a3 6080 if (ref_switch)
05f3fb3c 6081 percpu_ref_switch_to_atomic(&data->refs, io_atomic_switch);
c3a31e60
JA
6082
6083 return done ? done : err;
6084}
05f3fb3c
JA
6085static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
6086 unsigned nr_args)
6087{
6088 struct io_uring_files_update up;
6089
6090 if (!ctx->file_data)
6091 return -ENXIO;
6092 if (!nr_args)
6093 return -EINVAL;
6094 if (copy_from_user(&up, arg, sizeof(up)))
6095 return -EFAULT;
6096 if (up.resv)
6097 return -EINVAL;
6098
6099 return __io_sqe_files_update(ctx, &up, nr_args);
6100}
c3a31e60 6101
7d723065
JA
6102static void io_put_work(struct io_wq_work *work)
6103{
6104 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6105
6106 io_put_req(req);
6107}
6108
6109static void io_get_work(struct io_wq_work *work)
6110{
6111 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6112
6113 refcount_inc(&req->refs);
6114}
6115
24369c2e
PB
6116static int io_init_wq_offload(struct io_ring_ctx *ctx,
6117 struct io_uring_params *p)
6118{
6119 struct io_wq_data data;
6120 struct fd f;
6121 struct io_ring_ctx *ctx_attach;
6122 unsigned int concurrency;
6123 int ret = 0;
6124
6125 data.user = ctx->user;
6126 data.get_work = io_get_work;
6127 data.put_work = io_put_work;
6128
6129 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
6130 /* Do QD, or 4 * CPUS, whatever is smallest */
6131 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
6132
6133 ctx->io_wq = io_wq_create(concurrency, &data);
6134 if (IS_ERR(ctx->io_wq)) {
6135 ret = PTR_ERR(ctx->io_wq);
6136 ctx->io_wq = NULL;
6137 }
6138 return ret;
6139 }
6140
6141 f = fdget(p->wq_fd);
6142 if (!f.file)
6143 return -EBADF;
6144
6145 if (f.file->f_op != &io_uring_fops) {
6146 ret = -EINVAL;
6147 goto out_fput;
6148 }
6149
6150 ctx_attach = f.file->private_data;
6151 /* @io_wq is protected by holding the fd */
6152 if (!io_wq_get(ctx_attach->io_wq, &data)) {
6153 ret = -EINVAL;
6154 goto out_fput;
6155 }
6156
6157 ctx->io_wq = ctx_attach->io_wq;
6158out_fput:
6159 fdput(f);
6160 return ret;
6161}
6162
6c271ce2
JA
6163static int io_sq_offload_start(struct io_ring_ctx *ctx,
6164 struct io_uring_params *p)
2b188cc1
JA
6165{
6166 int ret;
6167
6c271ce2 6168 init_waitqueue_head(&ctx->sqo_wait);
2b188cc1
JA
6169 mmgrab(current->mm);
6170 ctx->sqo_mm = current->mm;
6171
6c271ce2 6172 if (ctx->flags & IORING_SETUP_SQPOLL) {
3ec482d1
JA
6173 ret = -EPERM;
6174 if (!capable(CAP_SYS_ADMIN))
6175 goto err;
6176
917257da
JA
6177 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
6178 if (!ctx->sq_thread_idle)
6179 ctx->sq_thread_idle = HZ;
6180
6c271ce2 6181 if (p->flags & IORING_SETUP_SQ_AFF) {
44a9bd18 6182 int cpu = p->sq_thread_cpu;
6c271ce2 6183
917257da 6184 ret = -EINVAL;
44a9bd18
JA
6185 if (cpu >= nr_cpu_ids)
6186 goto err;
7889f44d 6187 if (!cpu_online(cpu))
917257da
JA
6188 goto err;
6189
6c271ce2
JA
6190 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
6191 ctx, cpu,
6192 "io_uring-sq");
6193 } else {
6194 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
6195 "io_uring-sq");
6196 }
6197 if (IS_ERR(ctx->sqo_thread)) {
6198 ret = PTR_ERR(ctx->sqo_thread);
6199 ctx->sqo_thread = NULL;
6200 goto err;
6201 }
6202 wake_up_process(ctx->sqo_thread);
6203 } else if (p->flags & IORING_SETUP_SQ_AFF) {
6204 /* Can't have SQ_AFF without SQPOLL */
6205 ret = -EINVAL;
6206 goto err;
6207 }
6208
24369c2e
PB
6209 ret = io_init_wq_offload(ctx, p);
6210 if (ret)
2b188cc1 6211 goto err;
2b188cc1
JA
6212
6213 return 0;
6214err:
54a91f3b 6215 io_finish_async(ctx);
2b188cc1
JA
6216 mmdrop(ctx->sqo_mm);
6217 ctx->sqo_mm = NULL;
6218 return ret;
6219}
6220
6221static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
6222{
6223 atomic_long_sub(nr_pages, &user->locked_vm);
6224}
6225
6226static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
6227{
6228 unsigned long page_limit, cur_pages, new_pages;
6229
6230 /* Don't allow more pages than we can safely lock */
6231 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
6232
6233 do {
6234 cur_pages = atomic_long_read(&user->locked_vm);
6235 new_pages = cur_pages + nr_pages;
6236 if (new_pages > page_limit)
6237 return -ENOMEM;
6238 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
6239 new_pages) != cur_pages);
6240
6241 return 0;
6242}
6243
6244static void io_mem_free(void *ptr)
6245{
52e04ef4
MR
6246 struct page *page;
6247
6248 if (!ptr)
6249 return;
2b188cc1 6250
52e04ef4 6251 page = virt_to_head_page(ptr);
2b188cc1
JA
6252 if (put_page_testzero(page))
6253 free_compound_page(page);
6254}
6255
6256static void *io_mem_alloc(size_t size)
6257{
6258 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
6259 __GFP_NORETRY;
6260
6261 return (void *) __get_free_pages(gfp_flags, get_order(size));
6262}
6263
75b28aff
HV
6264static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
6265 size_t *sq_offset)
6266{
6267 struct io_rings *rings;
6268 size_t off, sq_array_size;
6269
6270 off = struct_size(rings, cqes, cq_entries);
6271 if (off == SIZE_MAX)
6272 return SIZE_MAX;
6273
6274#ifdef CONFIG_SMP
6275 off = ALIGN(off, SMP_CACHE_BYTES);
6276 if (off == 0)
6277 return SIZE_MAX;
6278#endif
6279
6280 sq_array_size = array_size(sizeof(u32), sq_entries);
6281 if (sq_array_size == SIZE_MAX)
6282 return SIZE_MAX;
6283
6284 if (check_add_overflow(off, sq_array_size, &off))
6285 return SIZE_MAX;
6286
6287 if (sq_offset)
6288 *sq_offset = off;
6289
6290 return off;
6291}
6292
2b188cc1
JA
6293static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
6294{
75b28aff 6295 size_t pages;
2b188cc1 6296
75b28aff
HV
6297 pages = (size_t)1 << get_order(
6298 rings_size(sq_entries, cq_entries, NULL));
6299 pages += (size_t)1 << get_order(
6300 array_size(sizeof(struct io_uring_sqe), sq_entries));
2b188cc1 6301
75b28aff 6302 return pages;
2b188cc1
JA
6303}
6304
edafccee
JA
6305static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
6306{
6307 int i, j;
6308
6309 if (!ctx->user_bufs)
6310 return -ENXIO;
6311
6312 for (i = 0; i < ctx->nr_user_bufs; i++) {
6313 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
6314
6315 for (j = 0; j < imu->nr_bvecs; j++)
f1f6a7dd 6316 unpin_user_page(imu->bvec[j].bv_page);
edafccee
JA
6317
6318 if (ctx->account_mem)
6319 io_unaccount_mem(ctx->user, imu->nr_bvecs);
d4ef6475 6320 kvfree(imu->bvec);
edafccee
JA
6321 imu->nr_bvecs = 0;
6322 }
6323
6324 kfree(ctx->user_bufs);
6325 ctx->user_bufs = NULL;
6326 ctx->nr_user_bufs = 0;
6327 return 0;
6328}
6329
6330static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
6331 void __user *arg, unsigned index)
6332{
6333 struct iovec __user *src;
6334
6335#ifdef CONFIG_COMPAT
6336 if (ctx->compat) {
6337 struct compat_iovec __user *ciovs;
6338 struct compat_iovec ciov;
6339
6340 ciovs = (struct compat_iovec __user *) arg;
6341 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
6342 return -EFAULT;
6343
d55e5f5b 6344 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
edafccee
JA
6345 dst->iov_len = ciov.iov_len;
6346 return 0;
6347 }
6348#endif
6349 src = (struct iovec __user *) arg;
6350 if (copy_from_user(dst, &src[index], sizeof(*dst)))
6351 return -EFAULT;
6352 return 0;
6353}
6354
6355static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
6356 unsigned nr_args)
6357{
6358 struct vm_area_struct **vmas = NULL;
6359 struct page **pages = NULL;
6360 int i, j, got_pages = 0;
6361 int ret = -EINVAL;
6362
6363 if (ctx->user_bufs)
6364 return -EBUSY;
6365 if (!nr_args || nr_args > UIO_MAXIOV)
6366 return -EINVAL;
6367
6368 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
6369 GFP_KERNEL);
6370 if (!ctx->user_bufs)
6371 return -ENOMEM;
6372
6373 for (i = 0; i < nr_args; i++) {
6374 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
6375 unsigned long off, start, end, ubuf;
6376 int pret, nr_pages;
6377 struct iovec iov;
6378 size_t size;
6379
6380 ret = io_copy_iov(ctx, &iov, arg, i);
6381 if (ret)
a278682d 6382 goto err;
edafccee
JA
6383
6384 /*
6385 * Don't impose further limits on the size and buffer
6386 * constraints here, we'll -EINVAL later when IO is
6387 * submitted if they are wrong.
6388 */
6389 ret = -EFAULT;
6390 if (!iov.iov_base || !iov.iov_len)
6391 goto err;
6392
6393 /* arbitrary limit, but we need something */
6394 if (iov.iov_len > SZ_1G)
6395 goto err;
6396
6397 ubuf = (unsigned long) iov.iov_base;
6398 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
6399 start = ubuf >> PAGE_SHIFT;
6400 nr_pages = end - start;
6401
6402 if (ctx->account_mem) {
6403 ret = io_account_mem(ctx->user, nr_pages);
6404 if (ret)
6405 goto err;
6406 }
6407
6408 ret = 0;
6409 if (!pages || nr_pages > got_pages) {
6410 kfree(vmas);
6411 kfree(pages);
d4ef6475 6412 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
edafccee 6413 GFP_KERNEL);
d4ef6475 6414 vmas = kvmalloc_array(nr_pages,
edafccee
JA
6415 sizeof(struct vm_area_struct *),
6416 GFP_KERNEL);
6417 if (!pages || !vmas) {
6418 ret = -ENOMEM;
6419 if (ctx->account_mem)
6420 io_unaccount_mem(ctx->user, nr_pages);
6421 goto err;
6422 }
6423 got_pages = nr_pages;
6424 }
6425
d4ef6475 6426 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
edafccee
JA
6427 GFP_KERNEL);
6428 ret = -ENOMEM;
6429 if (!imu->bvec) {
6430 if (ctx->account_mem)
6431 io_unaccount_mem(ctx->user, nr_pages);
6432 goto err;
6433 }
6434
6435 ret = 0;
6436 down_read(&current->mm->mmap_sem);
2113b05d 6437 pret = pin_user_pages(ubuf, nr_pages,
932f4a63
IW
6438 FOLL_WRITE | FOLL_LONGTERM,
6439 pages, vmas);
edafccee
JA
6440 if (pret == nr_pages) {
6441 /* don't support file backed memory */
6442 for (j = 0; j < nr_pages; j++) {
6443 struct vm_area_struct *vma = vmas[j];
6444
6445 if (vma->vm_file &&
6446 !is_file_hugepages(vma->vm_file)) {
6447 ret = -EOPNOTSUPP;
6448 break;
6449 }
6450 }
6451 } else {
6452 ret = pret < 0 ? pret : -EFAULT;
6453 }
6454 up_read(&current->mm->mmap_sem);
6455 if (ret) {
6456 /*
6457 * if we did partial map, or found file backed vmas,
6458 * release any pages we did get
6459 */
27c4d3a3 6460 if (pret > 0)
f1f6a7dd 6461 unpin_user_pages(pages, pret);
edafccee
JA
6462 if (ctx->account_mem)
6463 io_unaccount_mem(ctx->user, nr_pages);
d4ef6475 6464 kvfree(imu->bvec);
edafccee
JA
6465 goto err;
6466 }
6467
6468 off = ubuf & ~PAGE_MASK;
6469 size = iov.iov_len;
6470 for (j = 0; j < nr_pages; j++) {
6471 size_t vec_len;
6472
6473 vec_len = min_t(size_t, size, PAGE_SIZE - off);
6474 imu->bvec[j].bv_page = pages[j];
6475 imu->bvec[j].bv_len = vec_len;
6476 imu->bvec[j].bv_offset = off;
6477 off = 0;
6478 size -= vec_len;
6479 }
6480 /* store original address for later verification */
6481 imu->ubuf = ubuf;
6482 imu->len = iov.iov_len;
6483 imu->nr_bvecs = nr_pages;
6484
6485 ctx->nr_user_bufs++;
6486 }
d4ef6475
MR
6487 kvfree(pages);
6488 kvfree(vmas);
edafccee
JA
6489 return 0;
6490err:
d4ef6475
MR
6491 kvfree(pages);
6492 kvfree(vmas);
edafccee
JA
6493 io_sqe_buffer_unregister(ctx);
6494 return ret;
6495}
6496
9b402849
JA
6497static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
6498{
6499 __s32 __user *fds = arg;
6500 int fd;
6501
6502 if (ctx->cq_ev_fd)
6503 return -EBUSY;
6504
6505 if (copy_from_user(&fd, fds, sizeof(*fds)))
6506 return -EFAULT;
6507
6508 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
6509 if (IS_ERR(ctx->cq_ev_fd)) {
6510 int ret = PTR_ERR(ctx->cq_ev_fd);
6511 ctx->cq_ev_fd = NULL;
6512 return ret;
6513 }
6514
6515 return 0;
6516}
6517
6518static int io_eventfd_unregister(struct io_ring_ctx *ctx)
6519{
6520 if (ctx->cq_ev_fd) {
6521 eventfd_ctx_put(ctx->cq_ev_fd);
6522 ctx->cq_ev_fd = NULL;
6523 return 0;
6524 }
6525
6526 return -ENXIO;
6527}
6528
2b188cc1
JA
6529static void io_ring_ctx_free(struct io_ring_ctx *ctx)
6530{
6b06314c 6531 io_finish_async(ctx);
2b188cc1
JA
6532 if (ctx->sqo_mm)
6533 mmdrop(ctx->sqo_mm);
def596e9
JA
6534
6535 io_iopoll_reap_events(ctx);
edafccee 6536 io_sqe_buffer_unregister(ctx);
6b06314c 6537 io_sqe_files_unregister(ctx);
9b402849 6538 io_eventfd_unregister(ctx);
41726c9a 6539 idr_destroy(&ctx->personality_idr);
def596e9 6540
2b188cc1 6541#if defined(CONFIG_UNIX)
355e8d26
EB
6542 if (ctx->ring_sock) {
6543 ctx->ring_sock->file = NULL; /* so that iput() is called */
2b188cc1 6544 sock_release(ctx->ring_sock);
355e8d26 6545 }
2b188cc1
JA
6546#endif
6547
75b28aff 6548 io_mem_free(ctx->rings);
2b188cc1 6549 io_mem_free(ctx->sq_sqes);
2b188cc1
JA
6550
6551 percpu_ref_exit(&ctx->refs);
6552 if (ctx->account_mem)
6553 io_unaccount_mem(ctx->user,
6554 ring_pages(ctx->sq_entries, ctx->cq_entries));
6555 free_uid(ctx->user);
181e448d 6556 put_cred(ctx->creds);
206aefde 6557 kfree(ctx->completions);
78076bb6 6558 kfree(ctx->cancel_hash);
0ddf92e8 6559 kmem_cache_free(req_cachep, ctx->fallback_req);
2b188cc1
JA
6560 kfree(ctx);
6561}
6562
6563static __poll_t io_uring_poll(struct file *file, poll_table *wait)
6564{
6565 struct io_ring_ctx *ctx = file->private_data;
6566 __poll_t mask = 0;
6567
6568 poll_wait(file, &ctx->cq_wait, wait);
4f7067c3
SB
6569 /*
6570 * synchronizes with barrier from wq_has_sleeper call in
6571 * io_commit_cqring
6572 */
2b188cc1 6573 smp_rmb();
75b28aff
HV
6574 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
6575 ctx->rings->sq_ring_entries)
2b188cc1 6576 mask |= EPOLLOUT | EPOLLWRNORM;
63e5d81f 6577 if (io_cqring_events(ctx, false))
2b188cc1
JA
6578 mask |= EPOLLIN | EPOLLRDNORM;
6579
6580 return mask;
6581}
6582
6583static int io_uring_fasync(int fd, struct file *file, int on)
6584{
6585 struct io_ring_ctx *ctx = file->private_data;
6586
6587 return fasync_helper(fd, file, on, &ctx->cq_fasync);
6588}
6589
071698e1
JA
6590static int io_remove_personalities(int id, void *p, void *data)
6591{
6592 struct io_ring_ctx *ctx = data;
6593 const struct cred *cred;
6594
6595 cred = idr_remove(&ctx->personality_idr, id);
6596 if (cred)
6597 put_cred(cred);
6598 return 0;
6599}
6600
2b188cc1
JA
6601static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
6602{
6603 mutex_lock(&ctx->uring_lock);
6604 percpu_ref_kill(&ctx->refs);
6605 mutex_unlock(&ctx->uring_lock);
6606
df069d80
JA
6607 /*
6608 * Wait for sq thread to idle, if we have one. It won't spin on new
6609 * work after we've killed the ctx ref above. This is important to do
6610 * before we cancel existing commands, as the thread could otherwise
6611 * be queueing new work post that. If that's work we need to cancel,
6612 * it could cause shutdown to hang.
6613 */
6614 while (ctx->sqo_thread && !wq_has_sleeper(&ctx->sqo_wait))
6615 cpu_relax();
6616
5262f567 6617 io_kill_timeouts(ctx);
221c5eb2 6618 io_poll_remove_all(ctx);
561fb04a
JA
6619
6620 if (ctx->io_wq)
6621 io_wq_cancel_all(ctx->io_wq);
6622
def596e9 6623 io_iopoll_reap_events(ctx);
15dff286
JA
6624 /* if we failed setting up the ctx, we might not have any rings */
6625 if (ctx->rings)
6626 io_cqring_overflow_flush(ctx, true);
071698e1 6627 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
206aefde 6628 wait_for_completion(&ctx->completions[0]);
2b188cc1
JA
6629 io_ring_ctx_free(ctx);
6630}
6631
6632static int io_uring_release(struct inode *inode, struct file *file)
6633{
6634 struct io_ring_ctx *ctx = file->private_data;
6635
6636 file->private_data = NULL;
6637 io_ring_ctx_wait_and_kill(ctx);
6638 return 0;
6639}
6640
fcb323cc
JA
6641static void io_uring_cancel_files(struct io_ring_ctx *ctx,
6642 struct files_struct *files)
6643{
6644 struct io_kiocb *req;
6645 DEFINE_WAIT(wait);
6646
6647 while (!list_empty_careful(&ctx->inflight_list)) {
768134d4 6648 struct io_kiocb *cancel_req = NULL;
fcb323cc
JA
6649
6650 spin_lock_irq(&ctx->inflight_lock);
6651 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
768134d4
JA
6652 if (req->work.files != files)
6653 continue;
6654 /* req is being completed, ignore */
6655 if (!refcount_inc_not_zero(&req->refs))
6656 continue;
6657 cancel_req = req;
6658 break;
fcb323cc 6659 }
768134d4 6660 if (cancel_req)
fcb323cc 6661 prepare_to_wait(&ctx->inflight_wait, &wait,
768134d4 6662 TASK_UNINTERRUPTIBLE);
fcb323cc
JA
6663 spin_unlock_irq(&ctx->inflight_lock);
6664
768134d4
JA
6665 /* We need to keep going until we don't find a matching req */
6666 if (!cancel_req)
fcb323cc 6667 break;
2f6d9b9d 6668
2ca10259
JA
6669 if (cancel_req->flags & REQ_F_OVERFLOW) {
6670 spin_lock_irq(&ctx->completion_lock);
6671 list_del(&cancel_req->list);
6672 cancel_req->flags &= ~REQ_F_OVERFLOW;
6673 if (list_empty(&ctx->cq_overflow_list)) {
6674 clear_bit(0, &ctx->sq_check_overflow);
6675 clear_bit(0, &ctx->cq_check_overflow);
6676 }
6677 spin_unlock_irq(&ctx->completion_lock);
6678
6679 WRITE_ONCE(ctx->rings->cq_overflow,
6680 atomic_inc_return(&ctx->cached_cq_overflow));
6681
6682 /*
6683 * Put inflight ref and overflow ref. If that's
6684 * all we had, then we're done with this request.
6685 */
6686 if (refcount_sub_and_test(2, &cancel_req->refs)) {
6687 io_put_req(cancel_req);
6688 continue;
6689 }
6690 }
6691
2f6d9b9d
BL
6692 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
6693 io_put_req(cancel_req);
fcb323cc
JA
6694 schedule();
6695 }
768134d4 6696 finish_wait(&ctx->inflight_wait, &wait);
fcb323cc
JA
6697}
6698
6699static int io_uring_flush(struct file *file, void *data)
6700{
6701 struct io_ring_ctx *ctx = file->private_data;
6702
6703 io_uring_cancel_files(ctx, data);
6ab23144
JA
6704
6705 /*
6706 * If the task is going away, cancel work it may have pending
6707 */
6708 if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
6709 io_wq_cancel_pid(ctx->io_wq, task_pid_vnr(current));
6710
fcb323cc
JA
6711 return 0;
6712}
6713
6c5c240e
RP
6714static void *io_uring_validate_mmap_request(struct file *file,
6715 loff_t pgoff, size_t sz)
2b188cc1 6716{
2b188cc1 6717 struct io_ring_ctx *ctx = file->private_data;
6c5c240e 6718 loff_t offset = pgoff << PAGE_SHIFT;
2b188cc1
JA
6719 struct page *page;
6720 void *ptr;
6721
6722 switch (offset) {
6723 case IORING_OFF_SQ_RING:
75b28aff
HV
6724 case IORING_OFF_CQ_RING:
6725 ptr = ctx->rings;
2b188cc1
JA
6726 break;
6727 case IORING_OFF_SQES:
6728 ptr = ctx->sq_sqes;
6729 break;
2b188cc1 6730 default:
6c5c240e 6731 return ERR_PTR(-EINVAL);
2b188cc1
JA
6732 }
6733
6734 page = virt_to_head_page(ptr);
a50b854e 6735 if (sz > page_size(page))
6c5c240e
RP
6736 return ERR_PTR(-EINVAL);
6737
6738 return ptr;
6739}
6740
6741#ifdef CONFIG_MMU
6742
6743static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6744{
6745 size_t sz = vma->vm_end - vma->vm_start;
6746 unsigned long pfn;
6747 void *ptr;
6748
6749 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
6750 if (IS_ERR(ptr))
6751 return PTR_ERR(ptr);
2b188cc1
JA
6752
6753 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
6754 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
6755}
6756
6c5c240e
RP
6757#else /* !CONFIG_MMU */
6758
6759static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6760{
6761 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
6762}
6763
6764static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
6765{
6766 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
6767}
6768
6769static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
6770 unsigned long addr, unsigned long len,
6771 unsigned long pgoff, unsigned long flags)
6772{
6773 void *ptr;
6774
6775 ptr = io_uring_validate_mmap_request(file, pgoff, len);
6776 if (IS_ERR(ptr))
6777 return PTR_ERR(ptr);
6778
6779 return (unsigned long) ptr;
6780}
6781
6782#endif /* !CONFIG_MMU */
6783
2b188cc1
JA
6784SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
6785 u32, min_complete, u32, flags, const sigset_t __user *, sig,
6786 size_t, sigsz)
6787{
6788 struct io_ring_ctx *ctx;
6789 long ret = -EBADF;
6790 int submitted = 0;
6791 struct fd f;
6792
b41e9852
JA
6793 if (current->task_works)
6794 task_work_run();
6795
6c271ce2 6796 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
2b188cc1
JA
6797 return -EINVAL;
6798
6799 f = fdget(fd);
6800 if (!f.file)
6801 return -EBADF;
6802
6803 ret = -EOPNOTSUPP;
6804 if (f.file->f_op != &io_uring_fops)
6805 goto out_fput;
6806
6807 ret = -ENXIO;
6808 ctx = f.file->private_data;
6809 if (!percpu_ref_tryget(&ctx->refs))
6810 goto out_fput;
6811
6c271ce2
JA
6812 /*
6813 * For SQ polling, the thread will do all submissions and completions.
6814 * Just return the requested submit count, and wake the thread if
6815 * we were asked to.
6816 */
b2a9eada 6817 ret = 0;
6c271ce2 6818 if (ctx->flags & IORING_SETUP_SQPOLL) {
c1edbf5f
JA
6819 if (!list_empty_careful(&ctx->cq_overflow_list))
6820 io_cqring_overflow_flush(ctx, false);
6c271ce2
JA
6821 if (flags & IORING_ENTER_SQ_WAKEUP)
6822 wake_up(&ctx->sqo_wait);
6823 submitted = to_submit;
b2a9eada 6824 } else if (to_submit) {
ae9428ca 6825 struct mm_struct *cur_mm;
2b188cc1
JA
6826
6827 mutex_lock(&ctx->uring_lock);
ae9428ca
PB
6828 /* already have mm, so io_submit_sqes() won't try to grab it */
6829 cur_mm = ctx->sqo_mm;
6830 submitted = io_submit_sqes(ctx, to_submit, f.file, fd,
6831 &cur_mm, false);
2b188cc1 6832 mutex_unlock(&ctx->uring_lock);
7c504e65
PB
6833
6834 if (submitted != to_submit)
6835 goto out;
2b188cc1
JA
6836 }
6837 if (flags & IORING_ENTER_GETEVENTS) {
def596e9
JA
6838 unsigned nr_events = 0;
6839
2b188cc1
JA
6840 min_complete = min(min_complete, ctx->cq_entries);
6841
def596e9 6842 if (ctx->flags & IORING_SETUP_IOPOLL) {
def596e9 6843 ret = io_iopoll_check(ctx, &nr_events, min_complete);
def596e9
JA
6844 } else {
6845 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
6846 }
2b188cc1
JA
6847 }
6848
7c504e65 6849out:
6805b32e 6850 percpu_ref_put(&ctx->refs);
2b188cc1
JA
6851out_fput:
6852 fdput(f);
6853 return submitted ? submitted : ret;
6854}
6855
bebdb65e 6856#ifdef CONFIG_PROC_FS
87ce955b
JA
6857static int io_uring_show_cred(int id, void *p, void *data)
6858{
6859 const struct cred *cred = p;
6860 struct seq_file *m = data;
6861 struct user_namespace *uns = seq_user_ns(m);
6862 struct group_info *gi;
6863 kernel_cap_t cap;
6864 unsigned __capi;
6865 int g;
6866
6867 seq_printf(m, "%5d\n", id);
6868 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
6869 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
6870 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
6871 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
6872 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
6873 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
6874 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
6875 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
6876 seq_puts(m, "\n\tGroups:\t");
6877 gi = cred->group_info;
6878 for (g = 0; g < gi->ngroups; g++) {
6879 seq_put_decimal_ull(m, g ? " " : "",
6880 from_kgid_munged(uns, gi->gid[g]));
6881 }
6882 seq_puts(m, "\n\tCapEff:\t");
6883 cap = cred->cap_effective;
6884 CAP_FOR_EACH_U32(__capi)
6885 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
6886 seq_putc(m, '\n');
6887 return 0;
6888}
6889
6890static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
6891{
6892 int i;
6893
6894 mutex_lock(&ctx->uring_lock);
6895 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
6896 for (i = 0; i < ctx->nr_user_files; i++) {
6897 struct fixed_file_table *table;
6898 struct file *f;
6899
6900 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
6901 f = table->files[i & IORING_FILE_TABLE_MASK];
6902 if (f)
6903 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
6904 else
6905 seq_printf(m, "%5u: <none>\n", i);
6906 }
6907 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
6908 for (i = 0; i < ctx->nr_user_bufs; i++) {
6909 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
6910
6911 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
6912 (unsigned int) buf->len);
6913 }
6914 if (!idr_is_empty(&ctx->personality_idr)) {
6915 seq_printf(m, "Personalities:\n");
6916 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
6917 }
d7718a9d
JA
6918 seq_printf(m, "PollList:\n");
6919 spin_lock_irq(&ctx->completion_lock);
6920 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
6921 struct hlist_head *list = &ctx->cancel_hash[i];
6922 struct io_kiocb *req;
6923
6924 hlist_for_each_entry(req, list, hash_node)
6925 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
6926 req->task->task_works != NULL);
6927 }
6928 spin_unlock_irq(&ctx->completion_lock);
87ce955b
JA
6929 mutex_unlock(&ctx->uring_lock);
6930}
6931
6932static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
6933{
6934 struct io_ring_ctx *ctx = f->private_data;
6935
6936 if (percpu_ref_tryget(&ctx->refs)) {
6937 __io_uring_show_fdinfo(ctx, m);
6938 percpu_ref_put(&ctx->refs);
6939 }
6940}
bebdb65e 6941#endif
87ce955b 6942
2b188cc1
JA
6943static const struct file_operations io_uring_fops = {
6944 .release = io_uring_release,
fcb323cc 6945 .flush = io_uring_flush,
2b188cc1 6946 .mmap = io_uring_mmap,
6c5c240e
RP
6947#ifndef CONFIG_MMU
6948 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
6949 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
6950#endif
2b188cc1
JA
6951 .poll = io_uring_poll,
6952 .fasync = io_uring_fasync,
bebdb65e 6953#ifdef CONFIG_PROC_FS
87ce955b 6954 .show_fdinfo = io_uring_show_fdinfo,
bebdb65e 6955#endif
2b188cc1
JA
6956};
6957
6958static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
6959 struct io_uring_params *p)
6960{
75b28aff
HV
6961 struct io_rings *rings;
6962 size_t size, sq_array_offset;
2b188cc1 6963
75b28aff
HV
6964 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
6965 if (size == SIZE_MAX)
6966 return -EOVERFLOW;
6967
6968 rings = io_mem_alloc(size);
6969 if (!rings)
2b188cc1
JA
6970 return -ENOMEM;
6971
75b28aff
HV
6972 ctx->rings = rings;
6973 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
6974 rings->sq_ring_mask = p->sq_entries - 1;
6975 rings->cq_ring_mask = p->cq_entries - 1;
6976 rings->sq_ring_entries = p->sq_entries;
6977 rings->cq_ring_entries = p->cq_entries;
6978 ctx->sq_mask = rings->sq_ring_mask;
6979 ctx->cq_mask = rings->cq_ring_mask;
6980 ctx->sq_entries = rings->sq_ring_entries;
6981 ctx->cq_entries = rings->cq_ring_entries;
2b188cc1
JA
6982
6983 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
eb065d30
JA
6984 if (size == SIZE_MAX) {
6985 io_mem_free(ctx->rings);
6986 ctx->rings = NULL;
2b188cc1 6987 return -EOVERFLOW;
eb065d30 6988 }
2b188cc1
JA
6989
6990 ctx->sq_sqes = io_mem_alloc(size);
eb065d30
JA
6991 if (!ctx->sq_sqes) {
6992 io_mem_free(ctx->rings);
6993 ctx->rings = NULL;
2b188cc1 6994 return -ENOMEM;
eb065d30 6995 }
2b188cc1 6996
2b188cc1
JA
6997 return 0;
6998}
6999
7000/*
7001 * Allocate an anonymous fd, this is what constitutes the application
7002 * visible backing of an io_uring instance. The application mmaps this
7003 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
7004 * we have to tie this fd to a socket for file garbage collection purposes.
7005 */
7006static int io_uring_get_fd(struct io_ring_ctx *ctx)
7007{
7008 struct file *file;
7009 int ret;
7010
7011#if defined(CONFIG_UNIX)
7012 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
7013 &ctx->ring_sock);
7014 if (ret)
7015 return ret;
7016#endif
7017
7018 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
7019 if (ret < 0)
7020 goto err;
7021
7022 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
7023 O_RDWR | O_CLOEXEC);
7024 if (IS_ERR(file)) {
7025 put_unused_fd(ret);
7026 ret = PTR_ERR(file);
7027 goto err;
7028 }
7029
7030#if defined(CONFIG_UNIX)
7031 ctx->ring_sock->file = file;
7032#endif
7033 fd_install(ret, file);
7034 return ret;
7035err:
7036#if defined(CONFIG_UNIX)
7037 sock_release(ctx->ring_sock);
7038 ctx->ring_sock = NULL;
7039#endif
7040 return ret;
7041}
7042
7043static int io_uring_create(unsigned entries, struct io_uring_params *p)
7044{
7045 struct user_struct *user = NULL;
7046 struct io_ring_ctx *ctx;
7047 bool account_mem;
7048 int ret;
7049
8110c1a6 7050 if (!entries)
2b188cc1 7051 return -EINVAL;
8110c1a6
JA
7052 if (entries > IORING_MAX_ENTRIES) {
7053 if (!(p->flags & IORING_SETUP_CLAMP))
7054 return -EINVAL;
7055 entries = IORING_MAX_ENTRIES;
7056 }
2b188cc1
JA
7057
7058 /*
7059 * Use twice as many entries for the CQ ring. It's possible for the
7060 * application to drive a higher depth than the size of the SQ ring,
7061 * since the sqes are only used at submission time. This allows for
33a107f0
JA
7062 * some flexibility in overcommitting a bit. If the application has
7063 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
7064 * of CQ ring entries manually.
2b188cc1
JA
7065 */
7066 p->sq_entries = roundup_pow_of_two(entries);
33a107f0
JA
7067 if (p->flags & IORING_SETUP_CQSIZE) {
7068 /*
7069 * If IORING_SETUP_CQSIZE is set, we do the same roundup
7070 * to a power-of-two, if it isn't already. We do NOT impose
7071 * any cq vs sq ring sizing.
7072 */
8110c1a6 7073 if (p->cq_entries < p->sq_entries)
33a107f0 7074 return -EINVAL;
8110c1a6
JA
7075 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
7076 if (!(p->flags & IORING_SETUP_CLAMP))
7077 return -EINVAL;
7078 p->cq_entries = IORING_MAX_CQ_ENTRIES;
7079 }
33a107f0
JA
7080 p->cq_entries = roundup_pow_of_two(p->cq_entries);
7081 } else {
7082 p->cq_entries = 2 * p->sq_entries;
7083 }
2b188cc1
JA
7084
7085 user = get_uid(current_user());
7086 account_mem = !capable(CAP_IPC_LOCK);
7087
7088 if (account_mem) {
7089 ret = io_account_mem(user,
7090 ring_pages(p->sq_entries, p->cq_entries));
7091 if (ret) {
7092 free_uid(user);
7093 return ret;
7094 }
7095 }
7096
7097 ctx = io_ring_ctx_alloc(p);
7098 if (!ctx) {
7099 if (account_mem)
7100 io_unaccount_mem(user, ring_pages(p->sq_entries,
7101 p->cq_entries));
7102 free_uid(user);
7103 return -ENOMEM;
7104 }
7105 ctx->compat = in_compat_syscall();
7106 ctx->account_mem = account_mem;
7107 ctx->user = user;
0b8c0ec7 7108 ctx->creds = get_current_cred();
2b188cc1
JA
7109
7110 ret = io_allocate_scq_urings(ctx, p);
7111 if (ret)
7112 goto err;
7113
6c271ce2 7114 ret = io_sq_offload_start(ctx, p);
2b188cc1
JA
7115 if (ret)
7116 goto err;
7117
2b188cc1 7118 memset(&p->sq_off, 0, sizeof(p->sq_off));
75b28aff
HV
7119 p->sq_off.head = offsetof(struct io_rings, sq.head);
7120 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
7121 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
7122 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
7123 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
7124 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
7125 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
2b188cc1
JA
7126
7127 memset(&p->cq_off, 0, sizeof(p->cq_off));
75b28aff
HV
7128 p->cq_off.head = offsetof(struct io_rings, cq.head);
7129 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
7130 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
7131 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
7132 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
7133 p->cq_off.cqes = offsetof(struct io_rings, cqes);
ac90f249 7134
044c1ab3
JA
7135 /*
7136 * Install ring fd as the very last thing, so we don't risk someone
7137 * having closed it before we finish setup
7138 */
7139 ret = io_uring_get_fd(ctx);
7140 if (ret < 0)
7141 goto err;
7142
da8c9690 7143 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
cccf0ee8 7144 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
d7718a9d 7145 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL;
c826bd7a 7146 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
2b188cc1
JA
7147 return ret;
7148err:
7149 io_ring_ctx_wait_and_kill(ctx);
7150 return ret;
7151}
7152
7153/*
7154 * Sets up an aio uring context, and returns the fd. Applications asks for a
7155 * ring size, we return the actual sq/cq ring sizes (among other things) in the
7156 * params structure passed in.
7157 */
7158static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
7159{
7160 struct io_uring_params p;
7161 long ret;
7162 int i;
7163
7164 if (copy_from_user(&p, params, sizeof(p)))
7165 return -EFAULT;
7166 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
7167 if (p.resv[i])
7168 return -EINVAL;
7169 }
7170
6c271ce2 7171 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
8110c1a6 7172 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
24369c2e 7173 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ))
2b188cc1
JA
7174 return -EINVAL;
7175
7176 ret = io_uring_create(entries, &p);
7177 if (ret < 0)
7178 return ret;
7179
7180 if (copy_to_user(params, &p, sizeof(p)))
7181 return -EFAULT;
7182
7183 return ret;
7184}
7185
7186SYSCALL_DEFINE2(io_uring_setup, u32, entries,
7187 struct io_uring_params __user *, params)
7188{
7189 return io_uring_setup(entries, params);
7190}
7191
66f4af93
JA
7192static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
7193{
7194 struct io_uring_probe *p;
7195 size_t size;
7196 int i, ret;
7197
7198 size = struct_size(p, ops, nr_args);
7199 if (size == SIZE_MAX)
7200 return -EOVERFLOW;
7201 p = kzalloc(size, GFP_KERNEL);
7202 if (!p)
7203 return -ENOMEM;
7204
7205 ret = -EFAULT;
7206 if (copy_from_user(p, arg, size))
7207 goto out;
7208 ret = -EINVAL;
7209 if (memchr_inv(p, 0, size))
7210 goto out;
7211
7212 p->last_op = IORING_OP_LAST - 1;
7213 if (nr_args > IORING_OP_LAST)
7214 nr_args = IORING_OP_LAST;
7215
7216 for (i = 0; i < nr_args; i++) {
7217 p->ops[i].op = i;
7218 if (!io_op_defs[i].not_supported)
7219 p->ops[i].flags = IO_URING_OP_SUPPORTED;
7220 }
7221 p->ops_len = i;
7222
7223 ret = 0;
7224 if (copy_to_user(arg, p, size))
7225 ret = -EFAULT;
7226out:
7227 kfree(p);
7228 return ret;
7229}
7230
071698e1
JA
7231static int io_register_personality(struct io_ring_ctx *ctx)
7232{
7233 const struct cred *creds = get_current_cred();
7234 int id;
7235
7236 id = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
7237 USHRT_MAX, GFP_KERNEL);
7238 if (id < 0)
7239 put_cred(creds);
7240 return id;
7241}
7242
7243static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
7244{
7245 const struct cred *old_creds;
7246
7247 old_creds = idr_remove(&ctx->personality_idr, id);
7248 if (old_creds) {
7249 put_cred(old_creds);
7250 return 0;
7251 }
7252
7253 return -EINVAL;
7254}
7255
7256static bool io_register_op_must_quiesce(int op)
7257{
7258 switch (op) {
7259 case IORING_UNREGISTER_FILES:
7260 case IORING_REGISTER_FILES_UPDATE:
7261 case IORING_REGISTER_PROBE:
7262 case IORING_REGISTER_PERSONALITY:
7263 case IORING_UNREGISTER_PERSONALITY:
7264 return false;
7265 default:
7266 return true;
7267 }
7268}
7269
edafccee
JA
7270static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
7271 void __user *arg, unsigned nr_args)
b19062a5
JA
7272 __releases(ctx->uring_lock)
7273 __acquires(ctx->uring_lock)
edafccee
JA
7274{
7275 int ret;
7276
35fa71a0
JA
7277 /*
7278 * We're inside the ring mutex, if the ref is already dying, then
7279 * someone else killed the ctx or is already going through
7280 * io_uring_register().
7281 */
7282 if (percpu_ref_is_dying(&ctx->refs))
7283 return -ENXIO;
7284
071698e1 7285 if (io_register_op_must_quiesce(opcode)) {
05f3fb3c 7286 percpu_ref_kill(&ctx->refs);
b19062a5 7287
05f3fb3c
JA
7288 /*
7289 * Drop uring mutex before waiting for references to exit. If
7290 * another thread is currently inside io_uring_enter() it might
7291 * need to grab the uring_lock to make progress. If we hold it
7292 * here across the drain wait, then we can deadlock. It's safe
7293 * to drop the mutex here, since no new references will come in
7294 * after we've killed the percpu ref.
7295 */
7296 mutex_unlock(&ctx->uring_lock);
c150368b 7297 ret = wait_for_completion_interruptible(&ctx->completions[0]);
05f3fb3c 7298 mutex_lock(&ctx->uring_lock);
c150368b
JA
7299 if (ret) {
7300 percpu_ref_resurrect(&ctx->refs);
7301 ret = -EINTR;
7302 goto out;
7303 }
05f3fb3c 7304 }
edafccee
JA
7305
7306 switch (opcode) {
7307 case IORING_REGISTER_BUFFERS:
7308 ret = io_sqe_buffer_register(ctx, arg, nr_args);
7309 break;
7310 case IORING_UNREGISTER_BUFFERS:
7311 ret = -EINVAL;
7312 if (arg || nr_args)
7313 break;
7314 ret = io_sqe_buffer_unregister(ctx);
7315 break;
6b06314c
JA
7316 case IORING_REGISTER_FILES:
7317 ret = io_sqe_files_register(ctx, arg, nr_args);
7318 break;
7319 case IORING_UNREGISTER_FILES:
7320 ret = -EINVAL;
7321 if (arg || nr_args)
7322 break;
7323 ret = io_sqe_files_unregister(ctx);
7324 break;
c3a31e60
JA
7325 case IORING_REGISTER_FILES_UPDATE:
7326 ret = io_sqe_files_update(ctx, arg, nr_args);
7327 break;
9b402849 7328 case IORING_REGISTER_EVENTFD:
f2842ab5 7329 case IORING_REGISTER_EVENTFD_ASYNC:
9b402849
JA
7330 ret = -EINVAL;
7331 if (nr_args != 1)
7332 break;
7333 ret = io_eventfd_register(ctx, arg);
f2842ab5
JA
7334 if (ret)
7335 break;
7336 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
7337 ctx->eventfd_async = 1;
7338 else
7339 ctx->eventfd_async = 0;
9b402849
JA
7340 break;
7341 case IORING_UNREGISTER_EVENTFD:
7342 ret = -EINVAL;
7343 if (arg || nr_args)
7344 break;
7345 ret = io_eventfd_unregister(ctx);
7346 break;
66f4af93
JA
7347 case IORING_REGISTER_PROBE:
7348 ret = -EINVAL;
7349 if (!arg || nr_args > 256)
7350 break;
7351 ret = io_probe(ctx, arg, nr_args);
7352 break;
071698e1
JA
7353 case IORING_REGISTER_PERSONALITY:
7354 ret = -EINVAL;
7355 if (arg || nr_args)
7356 break;
7357 ret = io_register_personality(ctx);
7358 break;
7359 case IORING_UNREGISTER_PERSONALITY:
7360 ret = -EINVAL;
7361 if (arg)
7362 break;
7363 ret = io_unregister_personality(ctx, nr_args);
7364 break;
edafccee
JA
7365 default:
7366 ret = -EINVAL;
7367 break;
7368 }
7369
071698e1 7370 if (io_register_op_must_quiesce(opcode)) {
05f3fb3c 7371 /* bring the ctx back to life */
05f3fb3c 7372 percpu_ref_reinit(&ctx->refs);
c150368b
JA
7373out:
7374 reinit_completion(&ctx->completions[0]);
05f3fb3c 7375 }
edafccee
JA
7376 return ret;
7377}
7378
7379SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
7380 void __user *, arg, unsigned int, nr_args)
7381{
7382 struct io_ring_ctx *ctx;
7383 long ret = -EBADF;
7384 struct fd f;
7385
7386 f = fdget(fd);
7387 if (!f.file)
7388 return -EBADF;
7389
7390 ret = -EOPNOTSUPP;
7391 if (f.file->f_op != &io_uring_fops)
7392 goto out_fput;
7393
7394 ctx = f.file->private_data;
7395
7396 mutex_lock(&ctx->uring_lock);
7397 ret = __io_uring_register(ctx, opcode, arg, nr_args);
7398 mutex_unlock(&ctx->uring_lock);
c826bd7a
DD
7399 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
7400 ctx->cq_ev_fd != NULL, ret);
edafccee
JA
7401out_fput:
7402 fdput(f);
7403 return ret;
7404}
7405
2b188cc1
JA
7406static int __init io_uring_init(void)
7407{
d7f62e82
SM
7408#define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
7409 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
7410 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
7411} while (0)
7412
7413#define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
7414 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
7415 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
7416 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
7417 BUILD_BUG_SQE_ELEM(1, __u8, flags);
7418 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
7419 BUILD_BUG_SQE_ELEM(4, __s32, fd);
7420 BUILD_BUG_SQE_ELEM(8, __u64, off);
7421 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
7422 BUILD_BUG_SQE_ELEM(16, __u64, addr);
7d67af2c 7423 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
d7f62e82
SM
7424 BUILD_BUG_SQE_ELEM(24, __u32, len);
7425 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
7426 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
7427 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
7428 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
7429 BUILD_BUG_SQE_ELEM(28, __u16, poll_events);
7430 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
7431 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
7432 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
7433 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
7434 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
7435 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
7436 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
7437 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
7d67af2c 7438 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
d7f62e82
SM
7439 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
7440 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
7441 BUILD_BUG_SQE_ELEM(42, __u16, personality);
7d67af2c 7442 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
d7f62e82 7443
d3656344 7444 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
2b188cc1
JA
7445 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
7446 return 0;
7447};
7448__initcall(io_uring_init);