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