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