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