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