Linux 5.7.6
[linux/fpc-iii.git] / fs / io_uring.c
blob1829be7f63a35f44d7690ffc0c60b4790d4642eb
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
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.
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).
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.
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
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.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
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 <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
52 #include <linux/sched/signal.h>
53 #include <linux/fs.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
56 #include <linux/mm.h>
57 #include <linux/mman.h>
58 #include <linux/mmu_context.h>
59 #include <linux/percpu.h>
60 #include <linux/slab.h>
61 #include <linux/kthread.h>
62 #include <linux/blkdev.h>
63 #include <linux/bvec.h>
64 #include <linux/net.h>
65 #include <net/sock.h>
66 #include <net/af_unix.h>
67 #include <net/scm.h>
68 #include <linux/anon_inodes.h>
69 #include <linux/sched/mm.h>
70 #include <linux/uaccess.h>
71 #include <linux/nospec.h>
72 #include <linux/sizes.h>
73 #include <linux/hugetlb.h>
74 #include <linux/highmem.h>
75 #include <linux/namei.h>
76 #include <linux/fsnotify.h>
77 #include <linux/fadvise.h>
78 #include <linux/eventpoll.h>
79 #include <linux/fs_struct.h>
80 #include <linux/splice.h>
81 #include <linux/task_work.h>
83 #define CREATE_TRACE_POINTS
84 #include <trace/events/io_uring.h>
86 #include <uapi/linux/io_uring.h>
88 #include "internal.h"
89 #include "io-wq.h"
91 #define IORING_MAX_ENTRIES 32768
92 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
95 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
97 #define IORING_FILE_TABLE_SHIFT 9
98 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
99 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
100 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
102 struct io_uring {
103 u32 head ____cacheline_aligned_in_smp;
104 u32 tail ____cacheline_aligned_in_smp;
108 * This data is shared with the application through the mmap at offsets
109 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
111 * The offsets to the member fields are published through struct
112 * io_sqring_offsets when calling io_uring_setup.
114 struct io_rings {
116 * Head and tail offsets into the ring; the offsets need to be
117 * masked to get valid indices.
119 * The kernel controls head of the sq ring and the tail of the cq ring,
120 * and the application controls tail of the sq ring and the head of the
121 * cq ring.
123 struct io_uring sq, cq;
125 * Bitmasks to apply to head and tail offsets (constant, equals
126 * ring_entries - 1)
128 u32 sq_ring_mask, cq_ring_mask;
129 /* Ring sizes (constant, power of 2) */
130 u32 sq_ring_entries, cq_ring_entries;
132 * Number of invalid entries dropped by the kernel due to
133 * invalid index stored in array
135 * Written by the kernel, shouldn't be modified by the
136 * application (i.e. get number of "new events" by comparing to
137 * cached value).
139 * After a new SQ head value was read by the application this
140 * counter includes all submissions that were dropped reaching
141 * the new SQ head (and possibly more).
143 u32 sq_dropped;
145 * Runtime flags
147 * Written by the kernel, shouldn't be modified by the
148 * application.
150 * The application needs a full memory barrier before checking
151 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
153 u32 sq_flags;
155 * Number of completion events lost because the queue was full;
156 * this should be avoided by the application by making sure
157 * there are not more requests pending than there is space in
158 * the completion queue.
160 * Written by the kernel, shouldn't be modified by the
161 * application (i.e. get number of "new events" by comparing to
162 * cached value).
164 * As completion events come in out of order this counter is not
165 * ordered with any other data.
167 u32 cq_overflow;
169 * Ring buffer of completion events.
171 * The kernel writes completion events fresh every time they are
172 * produced, so the application is allowed to modify pending
173 * entries.
175 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
178 struct io_mapped_ubuf {
179 u64 ubuf;
180 size_t len;
181 struct bio_vec *bvec;
182 unsigned int nr_bvecs;
185 struct fixed_file_table {
186 struct file **files;
189 struct fixed_file_ref_node {
190 struct percpu_ref refs;
191 struct list_head node;
192 struct list_head file_list;
193 struct fixed_file_data *file_data;
194 struct work_struct work;
197 struct fixed_file_data {
198 struct fixed_file_table *table;
199 struct io_ring_ctx *ctx;
201 struct percpu_ref *cur_refs;
202 struct percpu_ref refs;
203 struct completion done;
204 struct list_head ref_list;
205 spinlock_t lock;
208 struct io_buffer {
209 struct list_head list;
210 __u64 addr;
211 __s32 len;
212 __u16 bid;
215 struct io_ring_ctx {
216 struct {
217 struct percpu_ref refs;
218 } ____cacheline_aligned_in_smp;
220 struct {
221 unsigned int flags;
222 unsigned int compat: 1;
223 unsigned int account_mem: 1;
224 unsigned int cq_overflow_flushed: 1;
225 unsigned int drain_next: 1;
226 unsigned int eventfd_async: 1;
229 * Ring buffer of indices into array of io_uring_sqe, which is
230 * mmapped by the application using the IORING_OFF_SQES offset.
232 * This indirection could e.g. be used to assign fixed
233 * io_uring_sqe entries to operations and only submit them to
234 * the queue when needed.
236 * The kernel modifies neither the indices array nor the entries
237 * array.
239 u32 *sq_array;
240 unsigned cached_sq_head;
241 unsigned sq_entries;
242 unsigned sq_mask;
243 unsigned sq_thread_idle;
244 unsigned cached_sq_dropped;
245 atomic_t cached_cq_overflow;
246 unsigned long sq_check_overflow;
248 struct list_head defer_list;
249 struct list_head timeout_list;
250 struct list_head cq_overflow_list;
252 wait_queue_head_t inflight_wait;
253 struct io_uring_sqe *sq_sqes;
254 } ____cacheline_aligned_in_smp;
256 struct io_rings *rings;
258 /* IO offload */
259 struct io_wq *io_wq;
260 struct task_struct *sqo_thread; /* if using sq thread polling */
261 struct mm_struct *sqo_mm;
262 wait_queue_head_t sqo_wait;
265 * If used, fixed file set. Writers must ensure that ->refs is dead,
266 * readers must ensure that ->refs is alive as long as the file* is
267 * used. Only updated through io_uring_register(2).
269 struct fixed_file_data *file_data;
270 unsigned nr_user_files;
271 int ring_fd;
272 struct file *ring_file;
274 /* if used, fixed mapped user buffers */
275 unsigned nr_user_bufs;
276 struct io_mapped_ubuf *user_bufs;
278 struct user_struct *user;
280 const struct cred *creds;
282 /* 0 is for ctx quiesce/reinit/free, 1 is for sqo_thread started */
283 struct completion *completions;
285 /* if all else fails... */
286 struct io_kiocb *fallback_req;
288 #if defined(CONFIG_UNIX)
289 struct socket *ring_sock;
290 #endif
292 struct idr io_buffer_idr;
294 struct idr personality_idr;
296 struct {
297 unsigned cached_cq_tail;
298 unsigned cq_entries;
299 unsigned cq_mask;
300 atomic_t cq_timeouts;
301 unsigned long cq_check_overflow;
302 struct wait_queue_head cq_wait;
303 struct fasync_struct *cq_fasync;
304 struct eventfd_ctx *cq_ev_fd;
305 } ____cacheline_aligned_in_smp;
307 struct {
308 struct mutex uring_lock;
309 wait_queue_head_t wait;
310 } ____cacheline_aligned_in_smp;
312 struct {
313 spinlock_t completion_lock;
316 * ->poll_list is protected by the ctx->uring_lock for
317 * io_uring instances that don't use IORING_SETUP_SQPOLL.
318 * For SQPOLL, only the single threaded io_sq_thread() will
319 * manipulate the list, hence no extra locking is needed there.
321 struct list_head poll_list;
322 struct hlist_head *cancel_hash;
323 unsigned cancel_hash_bits;
324 bool poll_multi_file;
326 spinlock_t inflight_lock;
327 struct list_head inflight_list;
328 } ____cacheline_aligned_in_smp;
330 struct work_struct exit_work;
334 * First field must be the file pointer in all the
335 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
337 struct io_poll_iocb {
338 struct file *file;
339 union {
340 struct wait_queue_head *head;
341 u64 addr;
343 __poll_t events;
344 bool done;
345 bool canceled;
346 struct wait_queue_entry wait;
349 struct io_close {
350 struct file *file;
351 struct file *put_file;
352 int fd;
355 struct io_timeout_data {
356 struct io_kiocb *req;
357 struct hrtimer timer;
358 struct timespec64 ts;
359 enum hrtimer_mode mode;
362 struct io_accept {
363 struct file *file;
364 struct sockaddr __user *addr;
365 int __user *addr_len;
366 int flags;
367 unsigned long nofile;
370 struct io_sync {
371 struct file *file;
372 loff_t len;
373 loff_t off;
374 int flags;
375 int mode;
378 struct io_cancel {
379 struct file *file;
380 u64 addr;
383 struct io_timeout {
384 struct file *file;
385 u64 addr;
386 int flags;
387 u32 count;
390 struct io_rw {
391 /* NOTE: kiocb has the file as the first member, so don't do it here */
392 struct kiocb kiocb;
393 u64 addr;
394 u64 len;
397 struct io_connect {
398 struct file *file;
399 struct sockaddr __user *addr;
400 int addr_len;
403 struct io_sr_msg {
404 struct file *file;
405 union {
406 struct user_msghdr __user *msg;
407 void __user *buf;
409 int msg_flags;
410 int bgid;
411 size_t len;
412 struct io_buffer *kbuf;
415 struct io_open {
416 struct file *file;
417 int dfd;
418 union {
419 unsigned mask;
421 struct filename *filename;
422 struct statx __user *buffer;
423 struct open_how how;
424 unsigned long nofile;
427 struct io_files_update {
428 struct file *file;
429 u64 arg;
430 u32 nr_args;
431 u32 offset;
434 struct io_fadvise {
435 struct file *file;
436 u64 offset;
437 u32 len;
438 u32 advice;
441 struct io_madvise {
442 struct file *file;
443 u64 addr;
444 u32 len;
445 u32 advice;
448 struct io_epoll {
449 struct file *file;
450 int epfd;
451 int op;
452 int fd;
453 struct epoll_event event;
456 struct io_splice {
457 struct file *file_out;
458 struct file *file_in;
459 loff_t off_out;
460 loff_t off_in;
461 u64 len;
462 unsigned int flags;
465 struct io_provide_buf {
466 struct file *file;
467 __u64 addr;
468 __s32 len;
469 __u32 bgid;
470 __u16 nbufs;
471 __u16 bid;
474 struct io_async_connect {
475 struct sockaddr_storage address;
478 struct io_async_msghdr {
479 struct iovec fast_iov[UIO_FASTIOV];
480 struct iovec *iov;
481 struct sockaddr __user *uaddr;
482 struct msghdr msg;
483 struct sockaddr_storage addr;
486 struct io_async_rw {
487 struct iovec fast_iov[UIO_FASTIOV];
488 struct iovec *iov;
489 ssize_t nr_segs;
490 ssize_t size;
493 struct io_async_ctx {
494 union {
495 struct io_async_rw rw;
496 struct io_async_msghdr msg;
497 struct io_async_connect connect;
498 struct io_timeout_data timeout;
502 enum {
503 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
504 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
505 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
506 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
507 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
508 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
510 REQ_F_LINK_HEAD_BIT,
511 REQ_F_LINK_NEXT_BIT,
512 REQ_F_FAIL_LINK_BIT,
513 REQ_F_INFLIGHT_BIT,
514 REQ_F_CUR_POS_BIT,
515 REQ_F_NOWAIT_BIT,
516 REQ_F_LINK_TIMEOUT_BIT,
517 REQ_F_TIMEOUT_BIT,
518 REQ_F_ISREG_BIT,
519 REQ_F_MUST_PUNT_BIT,
520 REQ_F_TIMEOUT_NOSEQ_BIT,
521 REQ_F_COMP_LOCKED_BIT,
522 REQ_F_NEED_CLEANUP_BIT,
523 REQ_F_OVERFLOW_BIT,
524 REQ_F_POLLED_BIT,
525 REQ_F_BUFFER_SELECTED_BIT,
526 REQ_F_NO_FILE_TABLE_BIT,
528 /* not a real bit, just to check we're not overflowing the space */
529 __REQ_F_LAST_BIT,
532 enum {
533 /* ctx owns file */
534 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
535 /* drain existing IO first */
536 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
537 /* linked sqes */
538 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
539 /* doesn't sever on completion < 0 */
540 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
541 /* IOSQE_ASYNC */
542 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
543 /* IOSQE_BUFFER_SELECT */
544 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
546 /* head of a link */
547 REQ_F_LINK_HEAD = BIT(REQ_F_LINK_HEAD_BIT),
548 /* already grabbed next link */
549 REQ_F_LINK_NEXT = BIT(REQ_F_LINK_NEXT_BIT),
550 /* fail rest of links */
551 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
552 /* on inflight list */
553 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
554 /* read/write uses file position */
555 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
556 /* must not punt to workers */
557 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
558 /* has linked timeout */
559 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
560 /* timeout request */
561 REQ_F_TIMEOUT = BIT(REQ_F_TIMEOUT_BIT),
562 /* regular file */
563 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
564 /* must be punted even for NONBLOCK */
565 REQ_F_MUST_PUNT = BIT(REQ_F_MUST_PUNT_BIT),
566 /* no timeout sequence */
567 REQ_F_TIMEOUT_NOSEQ = BIT(REQ_F_TIMEOUT_NOSEQ_BIT),
568 /* completion under lock */
569 REQ_F_COMP_LOCKED = BIT(REQ_F_COMP_LOCKED_BIT),
570 /* needs cleanup */
571 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
572 /* in overflow list */
573 REQ_F_OVERFLOW = BIT(REQ_F_OVERFLOW_BIT),
574 /* already went through poll handler */
575 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
576 /* buffer already selected */
577 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
578 /* doesn't need file table for this request */
579 REQ_F_NO_FILE_TABLE = BIT(REQ_F_NO_FILE_TABLE_BIT),
582 struct async_poll {
583 struct io_poll_iocb poll;
584 struct io_wq_work work;
588 * NOTE! Each of the iocb union members has the file pointer
589 * as the first entry in their struct definition. So you can
590 * access the file pointer through any of the sub-structs,
591 * or directly as just 'ki_filp' in this struct.
593 struct io_kiocb {
594 union {
595 struct file *file;
596 struct io_rw rw;
597 struct io_poll_iocb poll;
598 struct io_accept accept;
599 struct io_sync sync;
600 struct io_cancel cancel;
601 struct io_timeout timeout;
602 struct io_connect connect;
603 struct io_sr_msg sr_msg;
604 struct io_open open;
605 struct io_close close;
606 struct io_files_update files_update;
607 struct io_fadvise fadvise;
608 struct io_madvise madvise;
609 struct io_epoll epoll;
610 struct io_splice splice;
611 struct io_provide_buf pbuf;
614 struct io_async_ctx *io;
615 int cflags;
616 bool needs_fixed_file;
617 u8 opcode;
618 /* polled IO has completed */
619 u8 iopoll_completed;
621 u16 buf_index;
623 struct io_ring_ctx *ctx;
624 struct list_head list;
625 unsigned int flags;
626 refcount_t refs;
627 struct task_struct *task;
628 unsigned long fsize;
629 u64 user_data;
630 u32 result;
631 u32 sequence;
633 struct list_head link_list;
635 struct list_head inflight_entry;
637 struct percpu_ref *fixed_file_refs;
639 union {
641 * Only commands that never go async can use the below fields,
642 * obviously. Right now only IORING_OP_POLL_ADD uses them, and
643 * async armed poll handlers for regular commands. The latter
644 * restore the work, if needed.
646 struct {
647 struct callback_head task_work;
648 struct hlist_node hash_node;
649 struct async_poll *apoll;
651 struct io_wq_work work;
655 #define IO_PLUG_THRESHOLD 2
656 #define IO_IOPOLL_BATCH 8
658 struct io_submit_state {
659 struct blk_plug plug;
662 * io_kiocb alloc cache
664 void *reqs[IO_IOPOLL_BATCH];
665 unsigned int free_reqs;
668 * File reference cache
670 struct file *file;
671 unsigned int fd;
672 unsigned int has_refs;
673 unsigned int used_refs;
674 unsigned int ios_left;
677 struct io_op_def {
678 /* needs req->io allocated for deferral/async */
679 unsigned async_ctx : 1;
680 /* needs current->mm setup, does mm access */
681 unsigned needs_mm : 1;
682 /* needs req->file assigned */
683 unsigned needs_file : 1;
684 /* hash wq insertion if file is a regular file */
685 unsigned hash_reg_file : 1;
686 /* unbound wq insertion if file is a non-regular file */
687 unsigned unbound_nonreg_file : 1;
688 /* opcode is not supported by this kernel */
689 unsigned not_supported : 1;
690 /* needs file table */
691 unsigned file_table : 1;
692 /* needs ->fs */
693 unsigned needs_fs : 1;
694 /* set if opcode supports polled "wait" */
695 unsigned pollin : 1;
696 unsigned pollout : 1;
697 /* op supports buffer selection */
698 unsigned buffer_select : 1;
701 static const struct io_op_def io_op_defs[] = {
702 [IORING_OP_NOP] = {},
703 [IORING_OP_READV] = {
704 .async_ctx = 1,
705 .needs_mm = 1,
706 .needs_file = 1,
707 .unbound_nonreg_file = 1,
708 .pollin = 1,
709 .buffer_select = 1,
711 [IORING_OP_WRITEV] = {
712 .async_ctx = 1,
713 .needs_mm = 1,
714 .needs_file = 1,
715 .hash_reg_file = 1,
716 .unbound_nonreg_file = 1,
717 .pollout = 1,
719 [IORING_OP_FSYNC] = {
720 .needs_file = 1,
722 [IORING_OP_READ_FIXED] = {
723 .needs_file = 1,
724 .unbound_nonreg_file = 1,
725 .pollin = 1,
727 [IORING_OP_WRITE_FIXED] = {
728 .needs_file = 1,
729 .hash_reg_file = 1,
730 .unbound_nonreg_file = 1,
731 .pollout = 1,
733 [IORING_OP_POLL_ADD] = {
734 .needs_file = 1,
735 .unbound_nonreg_file = 1,
737 [IORING_OP_POLL_REMOVE] = {},
738 [IORING_OP_SYNC_FILE_RANGE] = {
739 .needs_file = 1,
741 [IORING_OP_SENDMSG] = {
742 .async_ctx = 1,
743 .needs_mm = 1,
744 .needs_file = 1,
745 .unbound_nonreg_file = 1,
746 .needs_fs = 1,
747 .pollout = 1,
749 [IORING_OP_RECVMSG] = {
750 .async_ctx = 1,
751 .needs_mm = 1,
752 .needs_file = 1,
753 .unbound_nonreg_file = 1,
754 .needs_fs = 1,
755 .pollin = 1,
756 .buffer_select = 1,
758 [IORING_OP_TIMEOUT] = {
759 .async_ctx = 1,
760 .needs_mm = 1,
762 [IORING_OP_TIMEOUT_REMOVE] = {},
763 [IORING_OP_ACCEPT] = {
764 .needs_mm = 1,
765 .needs_file = 1,
766 .unbound_nonreg_file = 1,
767 .file_table = 1,
768 .pollin = 1,
770 [IORING_OP_ASYNC_CANCEL] = {},
771 [IORING_OP_LINK_TIMEOUT] = {
772 .async_ctx = 1,
773 .needs_mm = 1,
775 [IORING_OP_CONNECT] = {
776 .async_ctx = 1,
777 .needs_mm = 1,
778 .needs_file = 1,
779 .unbound_nonreg_file = 1,
780 .pollout = 1,
782 [IORING_OP_FALLOCATE] = {
783 .needs_file = 1,
785 [IORING_OP_OPENAT] = {
786 .file_table = 1,
787 .needs_fs = 1,
789 [IORING_OP_CLOSE] = {
790 .needs_file = 1,
791 .file_table = 1,
793 [IORING_OP_FILES_UPDATE] = {
794 .needs_mm = 1,
795 .file_table = 1,
797 [IORING_OP_STATX] = {
798 .needs_mm = 1,
799 .needs_fs = 1,
800 .file_table = 1,
802 [IORING_OP_READ] = {
803 .needs_mm = 1,
804 .needs_file = 1,
805 .unbound_nonreg_file = 1,
806 .pollin = 1,
807 .buffer_select = 1,
809 [IORING_OP_WRITE] = {
810 .needs_mm = 1,
811 .needs_file = 1,
812 .unbound_nonreg_file = 1,
813 .pollout = 1,
815 [IORING_OP_FADVISE] = {
816 .needs_file = 1,
818 [IORING_OP_MADVISE] = {
819 .needs_mm = 1,
821 [IORING_OP_SEND] = {
822 .needs_mm = 1,
823 .needs_file = 1,
824 .unbound_nonreg_file = 1,
825 .pollout = 1,
827 [IORING_OP_RECV] = {
828 .needs_mm = 1,
829 .needs_file = 1,
830 .unbound_nonreg_file = 1,
831 .pollin = 1,
832 .buffer_select = 1,
834 [IORING_OP_OPENAT2] = {
835 .file_table = 1,
836 .needs_fs = 1,
838 [IORING_OP_EPOLL_CTL] = {
839 .unbound_nonreg_file = 1,
840 .file_table = 1,
842 [IORING_OP_SPLICE] = {
843 .needs_file = 1,
844 .hash_reg_file = 1,
845 .unbound_nonreg_file = 1,
847 [IORING_OP_PROVIDE_BUFFERS] = {},
848 [IORING_OP_REMOVE_BUFFERS] = {},
851 static void io_wq_submit_work(struct io_wq_work **workptr);
852 static void io_cqring_fill_event(struct io_kiocb *req, long res);
853 static void io_put_req(struct io_kiocb *req);
854 static void __io_double_put_req(struct io_kiocb *req);
855 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
856 static void io_queue_linked_timeout(struct io_kiocb *req);
857 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
858 struct io_uring_files_update *ip,
859 unsigned nr_args);
860 static int io_grab_files(struct io_kiocb *req);
861 static void io_cleanup_req(struct io_kiocb *req);
862 static int io_file_get(struct io_submit_state *state, struct io_kiocb *req,
863 int fd, struct file **out_file, bool fixed);
864 static void __io_queue_sqe(struct io_kiocb *req,
865 const struct io_uring_sqe *sqe);
867 static struct kmem_cache *req_cachep;
869 static const struct file_operations io_uring_fops;
871 struct sock *io_uring_get_socket(struct file *file)
873 #if defined(CONFIG_UNIX)
874 if (file->f_op == &io_uring_fops) {
875 struct io_ring_ctx *ctx = file->private_data;
877 return ctx->ring_sock->sk;
879 #endif
880 return NULL;
882 EXPORT_SYMBOL(io_uring_get_socket);
884 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
886 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
888 complete(&ctx->completions[0]);
891 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
893 struct io_ring_ctx *ctx;
894 int hash_bits;
896 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
897 if (!ctx)
898 return NULL;
900 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
901 if (!ctx->fallback_req)
902 goto err;
904 ctx->completions = kmalloc(2 * sizeof(struct completion), GFP_KERNEL);
905 if (!ctx->completions)
906 goto err;
909 * Use 5 bits less than the max cq entries, that should give us around
910 * 32 entries per hash list if totally full and uniformly spread.
912 hash_bits = ilog2(p->cq_entries);
913 hash_bits -= 5;
914 if (hash_bits <= 0)
915 hash_bits = 1;
916 ctx->cancel_hash_bits = hash_bits;
917 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
918 GFP_KERNEL);
919 if (!ctx->cancel_hash)
920 goto err;
921 __hash_init(ctx->cancel_hash, 1U << hash_bits);
923 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
924 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
925 goto err;
927 ctx->flags = p->flags;
928 init_waitqueue_head(&ctx->sqo_wait);
929 init_waitqueue_head(&ctx->cq_wait);
930 INIT_LIST_HEAD(&ctx->cq_overflow_list);
931 init_completion(&ctx->completions[0]);
932 init_completion(&ctx->completions[1]);
933 idr_init(&ctx->io_buffer_idr);
934 idr_init(&ctx->personality_idr);
935 mutex_init(&ctx->uring_lock);
936 init_waitqueue_head(&ctx->wait);
937 spin_lock_init(&ctx->completion_lock);
938 INIT_LIST_HEAD(&ctx->poll_list);
939 INIT_LIST_HEAD(&ctx->defer_list);
940 INIT_LIST_HEAD(&ctx->timeout_list);
941 init_waitqueue_head(&ctx->inflight_wait);
942 spin_lock_init(&ctx->inflight_lock);
943 INIT_LIST_HEAD(&ctx->inflight_list);
944 return ctx;
945 err:
946 if (ctx->fallback_req)
947 kmem_cache_free(req_cachep, ctx->fallback_req);
948 kfree(ctx->completions);
949 kfree(ctx->cancel_hash);
950 kfree(ctx);
951 return NULL;
954 static inline bool __req_need_defer(struct io_kiocb *req)
956 struct io_ring_ctx *ctx = req->ctx;
958 return req->sequence != ctx->cached_cq_tail
959 + atomic_read(&ctx->cached_cq_overflow);
962 static inline bool req_need_defer(struct io_kiocb *req)
964 if (unlikely(req->flags & REQ_F_IO_DRAIN))
965 return __req_need_defer(req);
967 return false;
970 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
972 struct io_kiocb *req;
974 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
975 if (req && !req_need_defer(req)) {
976 list_del_init(&req->list);
977 return req;
980 return NULL;
983 static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
985 struct io_kiocb *req;
987 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
988 if (req) {
989 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
990 return NULL;
991 if (!__req_need_defer(req)) {
992 list_del_init(&req->list);
993 return req;
997 return NULL;
1000 static void __io_commit_cqring(struct io_ring_ctx *ctx)
1002 struct io_rings *rings = ctx->rings;
1004 /* order cqe stores with ring update */
1005 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
1007 if (wq_has_sleeper(&ctx->cq_wait)) {
1008 wake_up_interruptible(&ctx->cq_wait);
1009 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1013 static inline void io_req_work_grab_env(struct io_kiocb *req,
1014 const struct io_op_def *def)
1016 if (!req->work.mm && def->needs_mm) {
1017 mmgrab(current->mm);
1018 req->work.mm = current->mm;
1020 if (!req->work.creds)
1021 req->work.creds = get_current_cred();
1022 if (!req->work.fs && def->needs_fs) {
1023 spin_lock(&current->fs->lock);
1024 if (!current->fs->in_exec) {
1025 req->work.fs = current->fs;
1026 req->work.fs->users++;
1027 } else {
1028 req->work.flags |= IO_WQ_WORK_CANCEL;
1030 spin_unlock(&current->fs->lock);
1032 if (!req->work.task_pid)
1033 req->work.task_pid = task_pid_vnr(current);
1036 static inline void io_req_work_drop_env(struct io_kiocb *req)
1038 if (req->work.mm) {
1039 mmdrop(req->work.mm);
1040 req->work.mm = NULL;
1042 if (req->work.creds) {
1043 put_cred(req->work.creds);
1044 req->work.creds = NULL;
1046 if (req->work.fs) {
1047 struct fs_struct *fs = req->work.fs;
1049 spin_lock(&req->work.fs->lock);
1050 if (--fs->users)
1051 fs = NULL;
1052 spin_unlock(&req->work.fs->lock);
1053 if (fs)
1054 free_fs_struct(fs);
1058 static inline void io_prep_async_work(struct io_kiocb *req,
1059 struct io_kiocb **link)
1061 const struct io_op_def *def = &io_op_defs[req->opcode];
1063 if (req->flags & REQ_F_ISREG) {
1064 if (def->hash_reg_file)
1065 io_wq_hash_work(&req->work, file_inode(req->file));
1066 } else {
1067 if (def->unbound_nonreg_file)
1068 req->work.flags |= IO_WQ_WORK_UNBOUND;
1071 io_req_work_grab_env(req, def);
1073 *link = io_prep_linked_timeout(req);
1076 static inline void io_queue_async_work(struct io_kiocb *req)
1078 struct io_ring_ctx *ctx = req->ctx;
1079 struct io_kiocb *link;
1081 io_prep_async_work(req, &link);
1083 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1084 &req->work, req->flags);
1085 io_wq_enqueue(ctx->io_wq, &req->work);
1087 if (link)
1088 io_queue_linked_timeout(link);
1091 static void io_kill_timeout(struct io_kiocb *req)
1093 int ret;
1095 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1096 if (ret != -1) {
1097 atomic_inc(&req->ctx->cq_timeouts);
1098 list_del_init(&req->list);
1099 req->flags |= REQ_F_COMP_LOCKED;
1100 io_cqring_fill_event(req, 0);
1101 io_put_req(req);
1105 static void io_kill_timeouts(struct io_ring_ctx *ctx)
1107 struct io_kiocb *req, *tmp;
1109 spin_lock_irq(&ctx->completion_lock);
1110 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
1111 io_kill_timeout(req);
1112 spin_unlock_irq(&ctx->completion_lock);
1115 static void io_commit_cqring(struct io_ring_ctx *ctx)
1117 struct io_kiocb *req;
1119 while ((req = io_get_timeout_req(ctx)) != NULL)
1120 io_kill_timeout(req);
1122 __io_commit_cqring(ctx);
1124 while ((req = io_get_deferred_req(ctx)) != NULL)
1125 io_queue_async_work(req);
1128 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1130 struct io_rings *rings = ctx->rings;
1131 unsigned tail;
1133 tail = ctx->cached_cq_tail;
1135 * writes to the cq entry need to come after reading head; the
1136 * control dependency is enough as we're using WRITE_ONCE to
1137 * fill the cq entry
1139 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
1140 return NULL;
1142 ctx->cached_cq_tail++;
1143 return &rings->cqes[tail & ctx->cq_mask];
1146 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1148 if (!ctx->cq_ev_fd)
1149 return false;
1150 if (!ctx->eventfd_async)
1151 return true;
1152 return io_wq_current_is_worker();
1155 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1157 if (waitqueue_active(&ctx->wait))
1158 wake_up(&ctx->wait);
1159 if (waitqueue_active(&ctx->sqo_wait))
1160 wake_up(&ctx->sqo_wait);
1161 if (io_should_trigger_evfd(ctx))
1162 eventfd_signal(ctx->cq_ev_fd, 1);
1165 /* Returns true if there are no backlogged entries after the flush */
1166 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1168 struct io_rings *rings = ctx->rings;
1169 struct io_uring_cqe *cqe;
1170 struct io_kiocb *req;
1171 unsigned long flags;
1172 LIST_HEAD(list);
1174 if (!force) {
1175 if (list_empty_careful(&ctx->cq_overflow_list))
1176 return true;
1177 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
1178 rings->cq_ring_entries))
1179 return false;
1182 spin_lock_irqsave(&ctx->completion_lock, flags);
1184 /* if force is set, the ring is going away. always drop after that */
1185 if (force)
1186 ctx->cq_overflow_flushed = 1;
1188 cqe = NULL;
1189 while (!list_empty(&ctx->cq_overflow_list)) {
1190 cqe = io_get_cqring(ctx);
1191 if (!cqe && !force)
1192 break;
1194 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
1195 list);
1196 list_move(&req->list, &list);
1197 req->flags &= ~REQ_F_OVERFLOW;
1198 if (cqe) {
1199 WRITE_ONCE(cqe->user_data, req->user_data);
1200 WRITE_ONCE(cqe->res, req->result);
1201 WRITE_ONCE(cqe->flags, req->cflags);
1202 } else {
1203 WRITE_ONCE(ctx->rings->cq_overflow,
1204 atomic_inc_return(&ctx->cached_cq_overflow));
1208 io_commit_cqring(ctx);
1209 if (cqe) {
1210 clear_bit(0, &ctx->sq_check_overflow);
1211 clear_bit(0, &ctx->cq_check_overflow);
1213 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1214 io_cqring_ev_posted(ctx);
1216 while (!list_empty(&list)) {
1217 req = list_first_entry(&list, struct io_kiocb, list);
1218 list_del(&req->list);
1219 io_put_req(req);
1222 return cqe != NULL;
1225 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1227 struct io_ring_ctx *ctx = req->ctx;
1228 struct io_uring_cqe *cqe;
1230 trace_io_uring_complete(ctx, req->user_data, res);
1233 * If we can't get a cq entry, userspace overflowed the
1234 * submission (by quite a lot). Increment the overflow count in
1235 * the ring.
1237 cqe = io_get_cqring(ctx);
1238 if (likely(cqe)) {
1239 WRITE_ONCE(cqe->user_data, req->user_data);
1240 WRITE_ONCE(cqe->res, res);
1241 WRITE_ONCE(cqe->flags, cflags);
1242 } else if (ctx->cq_overflow_flushed) {
1243 WRITE_ONCE(ctx->rings->cq_overflow,
1244 atomic_inc_return(&ctx->cached_cq_overflow));
1245 } else {
1246 if (list_empty(&ctx->cq_overflow_list)) {
1247 set_bit(0, &ctx->sq_check_overflow);
1248 set_bit(0, &ctx->cq_check_overflow);
1250 req->flags |= REQ_F_OVERFLOW;
1251 refcount_inc(&req->refs);
1252 req->result = res;
1253 req->cflags = cflags;
1254 list_add_tail(&req->list, &ctx->cq_overflow_list);
1258 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1260 __io_cqring_fill_event(req, res, 0);
1263 static void __io_cqring_add_event(struct io_kiocb *req, long res, long cflags)
1265 struct io_ring_ctx *ctx = req->ctx;
1266 unsigned long flags;
1268 spin_lock_irqsave(&ctx->completion_lock, flags);
1269 __io_cqring_fill_event(req, res, cflags);
1270 io_commit_cqring(ctx);
1271 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1273 io_cqring_ev_posted(ctx);
1276 static void io_cqring_add_event(struct io_kiocb *req, long res)
1278 __io_cqring_add_event(req, res, 0);
1281 static inline bool io_is_fallback_req(struct io_kiocb *req)
1283 return req == (struct io_kiocb *)
1284 ((unsigned long) req->ctx->fallback_req & ~1UL);
1287 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1289 struct io_kiocb *req;
1291 req = ctx->fallback_req;
1292 if (!test_and_set_bit_lock(0, (unsigned long *) &ctx->fallback_req))
1293 return req;
1295 return NULL;
1298 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx,
1299 struct io_submit_state *state)
1301 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1302 struct io_kiocb *req;
1304 if (!state) {
1305 req = kmem_cache_alloc(req_cachep, gfp);
1306 if (unlikely(!req))
1307 goto fallback;
1308 } else if (!state->free_reqs) {
1309 size_t sz;
1310 int ret;
1312 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1313 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1316 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1317 * retry single alloc to be on the safe side.
1319 if (unlikely(ret <= 0)) {
1320 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1321 if (!state->reqs[0])
1322 goto fallback;
1323 ret = 1;
1325 state->free_reqs = ret - 1;
1326 req = state->reqs[ret - 1];
1327 } else {
1328 state->free_reqs--;
1329 req = state->reqs[state->free_reqs];
1332 return req;
1333 fallback:
1334 return io_get_fallback_req(ctx);
1337 static inline void io_put_file(struct io_kiocb *req, struct file *file,
1338 bool fixed)
1340 if (fixed)
1341 percpu_ref_put(req->fixed_file_refs);
1342 else
1343 fput(file);
1346 static void __io_req_aux_free(struct io_kiocb *req)
1348 if (req->flags & REQ_F_NEED_CLEANUP)
1349 io_cleanup_req(req);
1351 kfree(req->io);
1352 if (req->file)
1353 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
1354 if (req->task)
1355 put_task_struct(req->task);
1357 io_req_work_drop_env(req);
1360 static void __io_free_req(struct io_kiocb *req)
1362 __io_req_aux_free(req);
1364 if (req->flags & REQ_F_INFLIGHT) {
1365 struct io_ring_ctx *ctx = req->ctx;
1366 unsigned long flags;
1368 spin_lock_irqsave(&ctx->inflight_lock, flags);
1369 list_del(&req->inflight_entry);
1370 if (waitqueue_active(&ctx->inflight_wait))
1371 wake_up(&ctx->inflight_wait);
1372 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1375 percpu_ref_put(&req->ctx->refs);
1376 if (likely(!io_is_fallback_req(req)))
1377 kmem_cache_free(req_cachep, req);
1378 else
1379 clear_bit_unlock(0, (unsigned long *) &req->ctx->fallback_req);
1382 struct req_batch {
1383 void *reqs[IO_IOPOLL_BATCH];
1384 int to_free;
1385 int need_iter;
1388 static void io_free_req_many(struct io_ring_ctx *ctx, struct req_batch *rb)
1390 if (!rb->to_free)
1391 return;
1392 if (rb->need_iter) {
1393 int i, inflight = 0;
1394 unsigned long flags;
1396 for (i = 0; i < rb->to_free; i++) {
1397 struct io_kiocb *req = rb->reqs[i];
1399 if (req->flags & REQ_F_INFLIGHT)
1400 inflight++;
1401 __io_req_aux_free(req);
1403 if (!inflight)
1404 goto do_free;
1406 spin_lock_irqsave(&ctx->inflight_lock, flags);
1407 for (i = 0; i < rb->to_free; i++) {
1408 struct io_kiocb *req = rb->reqs[i];
1410 if (req->flags & REQ_F_INFLIGHT) {
1411 list_del(&req->inflight_entry);
1412 if (!--inflight)
1413 break;
1416 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1418 if (waitqueue_active(&ctx->inflight_wait))
1419 wake_up(&ctx->inflight_wait);
1421 do_free:
1422 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
1423 percpu_ref_put_many(&ctx->refs, rb->to_free);
1424 rb->to_free = rb->need_iter = 0;
1427 static bool io_link_cancel_timeout(struct io_kiocb *req)
1429 struct io_ring_ctx *ctx = req->ctx;
1430 int ret;
1432 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1433 if (ret != -1) {
1434 io_cqring_fill_event(req, -ECANCELED);
1435 io_commit_cqring(ctx);
1436 req->flags &= ~REQ_F_LINK_HEAD;
1437 io_put_req(req);
1438 return true;
1441 return false;
1444 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1446 struct io_ring_ctx *ctx = req->ctx;
1447 bool wake_ev = false;
1449 /* Already got next link */
1450 if (req->flags & REQ_F_LINK_NEXT)
1451 return;
1454 * The list should never be empty when we are called here. But could
1455 * potentially happen if the chain is messed up, check to be on the
1456 * safe side.
1458 while (!list_empty(&req->link_list)) {
1459 struct io_kiocb *nxt = list_first_entry(&req->link_list,
1460 struct io_kiocb, link_list);
1462 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
1463 (nxt->flags & REQ_F_TIMEOUT))) {
1464 list_del_init(&nxt->link_list);
1465 wake_ev |= io_link_cancel_timeout(nxt);
1466 req->flags &= ~REQ_F_LINK_TIMEOUT;
1467 continue;
1470 list_del_init(&req->link_list);
1471 if (!list_empty(&nxt->link_list))
1472 nxt->flags |= REQ_F_LINK_HEAD;
1473 *nxtptr = nxt;
1474 break;
1477 req->flags |= REQ_F_LINK_NEXT;
1478 if (wake_ev)
1479 io_cqring_ev_posted(ctx);
1483 * Called if REQ_F_LINK_HEAD is set, and we fail the head request
1485 static void io_fail_links(struct io_kiocb *req)
1487 struct io_ring_ctx *ctx = req->ctx;
1488 unsigned long flags;
1490 spin_lock_irqsave(&ctx->completion_lock, flags);
1492 while (!list_empty(&req->link_list)) {
1493 struct io_kiocb *link = list_first_entry(&req->link_list,
1494 struct io_kiocb, link_list);
1496 list_del_init(&link->link_list);
1497 trace_io_uring_fail_link(req, link);
1499 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
1500 link->opcode == IORING_OP_LINK_TIMEOUT) {
1501 io_link_cancel_timeout(link);
1502 } else {
1503 io_cqring_fill_event(link, -ECANCELED);
1504 __io_double_put_req(link);
1506 req->flags &= ~REQ_F_LINK_TIMEOUT;
1509 io_commit_cqring(ctx);
1510 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1511 io_cqring_ev_posted(ctx);
1514 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
1516 if (likely(!(req->flags & REQ_F_LINK_HEAD)))
1517 return;
1520 * If LINK is set, we have dependent requests in this chain. If we
1521 * didn't fail this request, queue the first one up, moving any other
1522 * dependencies to the next request. In case of failure, fail the rest
1523 * of the chain.
1525 if (req->flags & REQ_F_FAIL_LINK) {
1526 io_fail_links(req);
1527 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1528 REQ_F_LINK_TIMEOUT) {
1529 struct io_ring_ctx *ctx = req->ctx;
1530 unsigned long flags;
1533 * If this is a timeout link, we could be racing with the
1534 * timeout timer. Grab the completion lock for this case to
1535 * protect against that.
1537 spin_lock_irqsave(&ctx->completion_lock, flags);
1538 io_req_link_next(req, nxt);
1539 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1540 } else {
1541 io_req_link_next(req, nxt);
1545 static void io_free_req(struct io_kiocb *req)
1547 struct io_kiocb *nxt = NULL;
1549 io_req_find_next(req, &nxt);
1550 __io_free_req(req);
1552 if (nxt)
1553 io_queue_async_work(nxt);
1556 static void io_link_work_cb(struct io_wq_work **workptr)
1558 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
1559 struct io_kiocb *link;
1561 link = list_first_entry(&req->link_list, struct io_kiocb, link_list);
1562 io_queue_linked_timeout(link);
1563 io_wq_submit_work(workptr);
1566 static void io_wq_assign_next(struct io_wq_work **workptr, struct io_kiocb *nxt)
1568 struct io_kiocb *link;
1569 const struct io_op_def *def = &io_op_defs[nxt->opcode];
1571 if ((nxt->flags & REQ_F_ISREG) && def->hash_reg_file)
1572 io_wq_hash_work(&nxt->work, file_inode(nxt->file));
1574 *workptr = &nxt->work;
1575 link = io_prep_linked_timeout(nxt);
1576 if (link)
1577 nxt->work.func = io_link_work_cb;
1581 * Drop reference to request, return next in chain (if there is one) if this
1582 * was the last reference to this request.
1584 __attribute__((nonnull))
1585 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1587 if (refcount_dec_and_test(&req->refs)) {
1588 io_req_find_next(req, nxtptr);
1589 __io_free_req(req);
1593 static void io_put_req(struct io_kiocb *req)
1595 if (refcount_dec_and_test(&req->refs))
1596 io_free_req(req);
1599 static void io_steal_work(struct io_kiocb *req,
1600 struct io_wq_work **workptr)
1603 * It's in an io-wq worker, so there always should be at least
1604 * one reference, which will be dropped in io_put_work() just
1605 * after the current handler returns.
1607 * It also means, that if the counter dropped to 1, then there is
1608 * no asynchronous users left, so it's safe to steal the next work.
1610 if (refcount_read(&req->refs) == 1) {
1611 struct io_kiocb *nxt = NULL;
1613 io_req_find_next(req, &nxt);
1614 if (nxt)
1615 io_wq_assign_next(workptr, nxt);
1620 * Must only be used if we don't need to care about links, usually from
1621 * within the completion handling itself.
1623 static void __io_double_put_req(struct io_kiocb *req)
1625 /* drop both submit and complete references */
1626 if (refcount_sub_and_test(2, &req->refs))
1627 __io_free_req(req);
1630 static void io_double_put_req(struct io_kiocb *req)
1632 /* drop both submit and complete references */
1633 if (refcount_sub_and_test(2, &req->refs))
1634 io_free_req(req);
1637 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1639 struct io_rings *rings = ctx->rings;
1641 if (test_bit(0, &ctx->cq_check_overflow)) {
1643 * noflush == true is from the waitqueue handler, just ensure
1644 * we wake up the task, and the next invocation will flush the
1645 * entries. We cannot safely to it from here.
1647 if (noflush && !list_empty(&ctx->cq_overflow_list))
1648 return -1U;
1650 io_cqring_overflow_flush(ctx, false);
1653 /* See comment at the top of this file */
1654 smp_rmb();
1655 return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
1658 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1660 struct io_rings *rings = ctx->rings;
1662 /* make sure SQ entry isn't read before tail */
1663 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1666 static inline bool io_req_multi_free(struct req_batch *rb, struct io_kiocb *req)
1668 if ((req->flags & REQ_F_LINK_HEAD) || io_is_fallback_req(req))
1669 return false;
1671 if (req->file || req->io)
1672 rb->need_iter++;
1674 rb->reqs[rb->to_free++] = req;
1675 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
1676 io_free_req_many(req->ctx, rb);
1677 return true;
1680 static int io_put_kbuf(struct io_kiocb *req)
1682 struct io_buffer *kbuf;
1683 int cflags;
1685 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
1686 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
1687 cflags |= IORING_CQE_F_BUFFER;
1688 req->rw.addr = 0;
1689 kfree(kbuf);
1690 return cflags;
1693 static void io_iopoll_queue(struct list_head *again)
1695 struct io_kiocb *req;
1697 do {
1698 req = list_first_entry(again, struct io_kiocb, list);
1699 list_del(&req->list);
1700 refcount_inc(&req->refs);
1701 io_queue_async_work(req);
1702 } while (!list_empty(again));
1706 * Find and free completed poll iocbs
1708 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1709 struct list_head *done)
1711 struct req_batch rb;
1712 struct io_kiocb *req;
1713 LIST_HEAD(again);
1715 /* order with ->result store in io_complete_rw_iopoll() */
1716 smp_rmb();
1718 rb.to_free = rb.need_iter = 0;
1719 while (!list_empty(done)) {
1720 int cflags = 0;
1722 req = list_first_entry(done, struct io_kiocb, list);
1723 if (READ_ONCE(req->result) == -EAGAIN) {
1724 req->iopoll_completed = 0;
1725 list_move_tail(&req->list, &again);
1726 continue;
1728 list_del(&req->list);
1730 if (req->flags & REQ_F_BUFFER_SELECTED)
1731 cflags = io_put_kbuf(req);
1733 __io_cqring_fill_event(req, req->result, cflags);
1734 (*nr_events)++;
1736 if (refcount_dec_and_test(&req->refs) &&
1737 !io_req_multi_free(&rb, req))
1738 io_free_req(req);
1741 io_commit_cqring(ctx);
1742 if (ctx->flags & IORING_SETUP_SQPOLL)
1743 io_cqring_ev_posted(ctx);
1744 io_free_req_many(ctx, &rb);
1746 if (!list_empty(&again))
1747 io_iopoll_queue(&again);
1750 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1751 long min)
1753 struct io_kiocb *req, *tmp;
1754 LIST_HEAD(done);
1755 bool spin;
1756 int ret;
1759 * Only spin for completions if we don't have multiple devices hanging
1760 * off our complete list, and we're under the requested amount.
1762 spin = !ctx->poll_multi_file && *nr_events < min;
1764 ret = 0;
1765 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1766 struct kiocb *kiocb = &req->rw.kiocb;
1769 * Move completed and retryable entries to our local lists.
1770 * If we find a request that requires polling, break out
1771 * and complete those lists first, if we have entries there.
1773 if (READ_ONCE(req->iopoll_completed)) {
1774 list_move_tail(&req->list, &done);
1775 continue;
1777 if (!list_empty(&done))
1778 break;
1780 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1781 if (ret < 0)
1782 break;
1784 if (ret && spin)
1785 spin = false;
1786 ret = 0;
1789 if (!list_empty(&done))
1790 io_iopoll_complete(ctx, nr_events, &done);
1792 return ret;
1796 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
1797 * non-spinning poll check - we'll still enter the driver poll loop, but only
1798 * as a non-spinning completion check.
1800 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1801 long min)
1803 while (!list_empty(&ctx->poll_list) && !need_resched()) {
1804 int ret;
1806 ret = io_do_iopoll(ctx, nr_events, min);
1807 if (ret < 0)
1808 return ret;
1809 if (!min || *nr_events >= min)
1810 return 0;
1813 return 1;
1817 * We can't just wait for polled events to come to us, we have to actively
1818 * find and complete them.
1820 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1822 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1823 return;
1825 mutex_lock(&ctx->uring_lock);
1826 while (!list_empty(&ctx->poll_list)) {
1827 unsigned int nr_events = 0;
1829 io_iopoll_getevents(ctx, &nr_events, 1);
1832 * Ensure we allow local-to-the-cpu processing to take place,
1833 * in this case we need to ensure that we reap all events.
1835 cond_resched();
1837 mutex_unlock(&ctx->uring_lock);
1840 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1841 long min)
1843 int iters = 0, ret = 0;
1846 * We disallow the app entering submit/complete with polling, but we
1847 * still need to lock the ring to prevent racing with polled issue
1848 * that got punted to a workqueue.
1850 mutex_lock(&ctx->uring_lock);
1851 do {
1852 int tmin = 0;
1855 * Don't enter poll loop if we already have events pending.
1856 * If we do, we can potentially be spinning for commands that
1857 * already triggered a CQE (eg in error).
1859 if (io_cqring_events(ctx, false))
1860 break;
1863 * If a submit got punted to a workqueue, we can have the
1864 * application entering polling for a command before it gets
1865 * issued. That app will hold the uring_lock for the duration
1866 * of the poll right here, so we need to take a breather every
1867 * now and then to ensure that the issue has a chance to add
1868 * the poll to the issued list. Otherwise we can spin here
1869 * forever, while the workqueue is stuck trying to acquire the
1870 * very same mutex.
1872 if (!(++iters & 7)) {
1873 mutex_unlock(&ctx->uring_lock);
1874 mutex_lock(&ctx->uring_lock);
1877 if (*nr_events < min)
1878 tmin = min - *nr_events;
1880 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1881 if (ret <= 0)
1882 break;
1883 ret = 0;
1884 } while (min && !*nr_events && !need_resched());
1886 mutex_unlock(&ctx->uring_lock);
1887 return ret;
1890 static void kiocb_end_write(struct io_kiocb *req)
1893 * Tell lockdep we inherited freeze protection from submission
1894 * thread.
1896 if (req->flags & REQ_F_ISREG) {
1897 struct inode *inode = file_inode(req->file);
1899 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
1901 file_end_write(req->file);
1904 static inline void req_set_fail_links(struct io_kiocb *req)
1906 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1907 req->flags |= REQ_F_FAIL_LINK;
1910 static void io_complete_rw_common(struct kiocb *kiocb, long res)
1912 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1913 int cflags = 0;
1915 if (kiocb->ki_flags & IOCB_WRITE)
1916 kiocb_end_write(req);
1918 if (res != req->result)
1919 req_set_fail_links(req);
1920 if (req->flags & REQ_F_BUFFER_SELECTED)
1921 cflags = io_put_kbuf(req);
1922 __io_cqring_add_event(req, res, cflags);
1925 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1927 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1929 io_complete_rw_common(kiocb, res);
1930 io_put_req(req);
1933 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1935 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1937 if (kiocb->ki_flags & IOCB_WRITE)
1938 kiocb_end_write(req);
1940 if (res != -EAGAIN && res != req->result)
1941 req_set_fail_links(req);
1943 WRITE_ONCE(req->result, res);
1944 /* order with io_poll_complete() checking ->result */
1945 if (res != -EAGAIN) {
1946 smp_wmb();
1947 WRITE_ONCE(req->iopoll_completed, 1);
1952 * After the iocb has been issued, it's safe to be found on the poll list.
1953 * Adding the kiocb to the list AFTER submission ensures that we don't
1954 * find it from a io_iopoll_getevents() thread before the issuer is done
1955 * accessing the kiocb cookie.
1957 static void io_iopoll_req_issued(struct io_kiocb *req)
1959 struct io_ring_ctx *ctx = req->ctx;
1962 * Track whether we have multiple files in our lists. This will impact
1963 * how we do polling eventually, not spinning if we're on potentially
1964 * different devices.
1966 if (list_empty(&ctx->poll_list)) {
1967 ctx->poll_multi_file = false;
1968 } else if (!ctx->poll_multi_file) {
1969 struct io_kiocb *list_req;
1971 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1972 list);
1973 if (list_req->file != req->file)
1974 ctx->poll_multi_file = true;
1978 * For fast devices, IO may have already completed. If it has, add
1979 * it to the front so we find it first.
1981 if (READ_ONCE(req->iopoll_completed))
1982 list_add(&req->list, &ctx->poll_list);
1983 else
1984 list_add_tail(&req->list, &ctx->poll_list);
1986 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
1987 wq_has_sleeper(&ctx->sqo_wait))
1988 wake_up(&ctx->sqo_wait);
1991 static void io_file_put(struct io_submit_state *state)
1993 if (state->file) {
1994 int diff = state->has_refs - state->used_refs;
1996 if (diff)
1997 fput_many(state->file, diff);
1998 state->file = NULL;
2003 * Get as many references to a file as we have IOs left in this submission,
2004 * assuming most submissions are for one file, or at least that each file
2005 * has more than one submission.
2007 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2009 if (!state)
2010 return fget(fd);
2012 if (state->file) {
2013 if (state->fd == fd) {
2014 state->used_refs++;
2015 state->ios_left--;
2016 return state->file;
2018 io_file_put(state);
2020 state->file = fget_many(fd, state->ios_left);
2021 if (!state->file)
2022 return NULL;
2024 state->fd = fd;
2025 state->has_refs = state->ios_left;
2026 state->used_refs = 1;
2027 state->ios_left--;
2028 return state->file;
2032 * If we tracked the file through the SCM inflight mechanism, we could support
2033 * any file. For now, just ensure that anything potentially problematic is done
2034 * inline.
2036 static bool io_file_supports_async(struct file *file, int rw)
2038 umode_t mode = file_inode(file)->i_mode;
2040 if (S_ISBLK(mode) || S_ISCHR(mode) || S_ISSOCK(mode))
2041 return true;
2042 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
2043 return true;
2045 /* any ->read/write should understand O_NONBLOCK */
2046 if (file->f_flags & O_NONBLOCK)
2047 return true;
2049 if (!(file->f_mode & FMODE_NOWAIT))
2050 return false;
2052 if (rw == READ)
2053 return file->f_op->read_iter != NULL;
2055 return file->f_op->write_iter != NULL;
2058 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2059 bool force_nonblock)
2061 struct io_ring_ctx *ctx = req->ctx;
2062 struct kiocb *kiocb = &req->rw.kiocb;
2063 unsigned ioprio;
2064 int ret;
2066 if (S_ISREG(file_inode(req->file)->i_mode))
2067 req->flags |= REQ_F_ISREG;
2069 kiocb->ki_pos = READ_ONCE(sqe->off);
2070 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
2071 req->flags |= REQ_F_CUR_POS;
2072 kiocb->ki_pos = req->file->f_pos;
2074 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2075 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2076 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2077 if (unlikely(ret))
2078 return ret;
2080 ioprio = READ_ONCE(sqe->ioprio);
2081 if (ioprio) {
2082 ret = ioprio_check_cap(ioprio);
2083 if (ret)
2084 return ret;
2086 kiocb->ki_ioprio = ioprio;
2087 } else
2088 kiocb->ki_ioprio = get_current_ioprio();
2090 /* don't allow async punt if RWF_NOWAIT was requested */
2091 if (kiocb->ki_flags & IOCB_NOWAIT)
2092 req->flags |= REQ_F_NOWAIT;
2094 if (force_nonblock)
2095 kiocb->ki_flags |= IOCB_NOWAIT;
2097 if (ctx->flags & IORING_SETUP_IOPOLL) {
2098 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2099 !kiocb->ki_filp->f_op->iopoll)
2100 return -EOPNOTSUPP;
2102 kiocb->ki_flags |= IOCB_HIPRI;
2103 kiocb->ki_complete = io_complete_rw_iopoll;
2104 req->result = 0;
2105 req->iopoll_completed = 0;
2106 } else {
2107 if (kiocb->ki_flags & IOCB_HIPRI)
2108 return -EINVAL;
2109 kiocb->ki_complete = io_complete_rw;
2112 req->rw.addr = READ_ONCE(sqe->addr);
2113 req->rw.len = READ_ONCE(sqe->len);
2114 req->buf_index = READ_ONCE(sqe->buf_index);
2115 return 0;
2118 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2120 switch (ret) {
2121 case -EIOCBQUEUED:
2122 break;
2123 case -ERESTARTSYS:
2124 case -ERESTARTNOINTR:
2125 case -ERESTARTNOHAND:
2126 case -ERESTART_RESTARTBLOCK:
2128 * We can't just restart the syscall, since previously
2129 * submitted sqes may already be in progress. Just fail this
2130 * IO with EINTR.
2132 ret = -EINTR;
2133 /* fall through */
2134 default:
2135 kiocb->ki_complete(kiocb, ret, 0);
2139 static void kiocb_done(struct kiocb *kiocb, ssize_t ret)
2141 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2143 if (req->flags & REQ_F_CUR_POS)
2144 req->file->f_pos = kiocb->ki_pos;
2145 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2146 io_complete_rw(kiocb, ret, 0);
2147 else
2148 io_rw_done(kiocb, ret);
2151 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
2152 struct iov_iter *iter)
2154 struct io_ring_ctx *ctx = req->ctx;
2155 size_t len = req->rw.len;
2156 struct io_mapped_ubuf *imu;
2157 u16 index, buf_index;
2158 size_t offset;
2159 u64 buf_addr;
2161 /* attempt to use fixed buffers without having provided iovecs */
2162 if (unlikely(!ctx->user_bufs))
2163 return -EFAULT;
2165 buf_index = req->buf_index;
2166 if (unlikely(buf_index >= ctx->nr_user_bufs))
2167 return -EFAULT;
2169 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2170 imu = &ctx->user_bufs[index];
2171 buf_addr = req->rw.addr;
2173 /* overflow */
2174 if (buf_addr + len < buf_addr)
2175 return -EFAULT;
2176 /* not inside the mapped region */
2177 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2178 return -EFAULT;
2181 * May not be a start of buffer, set size appropriately
2182 * and advance us to the beginning.
2184 offset = buf_addr - imu->ubuf;
2185 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2187 if (offset) {
2189 * Don't use iov_iter_advance() here, as it's really slow for
2190 * using the latter parts of a big fixed buffer - it iterates
2191 * over each segment manually. We can cheat a bit here, because
2192 * we know that:
2194 * 1) it's a BVEC iter, we set it up
2195 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2196 * first and last bvec
2198 * So just find our index, and adjust the iterator afterwards.
2199 * If the offset is within the first bvec (or the whole first
2200 * bvec, just use iov_iter_advance(). This makes it easier
2201 * since we can just skip the first segment, which may not
2202 * be PAGE_SIZE aligned.
2204 const struct bio_vec *bvec = imu->bvec;
2206 if (offset <= bvec->bv_len) {
2207 iov_iter_advance(iter, offset);
2208 } else {
2209 unsigned long seg_skip;
2211 /* skip first vec */
2212 offset -= bvec->bv_len;
2213 seg_skip = 1 + (offset >> PAGE_SHIFT);
2215 iter->bvec = bvec + seg_skip;
2216 iter->nr_segs -= seg_skip;
2217 iter->count -= bvec->bv_len + offset;
2218 iter->iov_offset = offset & ~PAGE_MASK;
2222 return len;
2225 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2227 if (needs_lock)
2228 mutex_unlock(&ctx->uring_lock);
2231 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2234 * "Normal" inline submissions always hold the uring_lock, since we
2235 * grab it from the system call. Same is true for the SQPOLL offload.
2236 * The only exception is when we've detached the request and issue it
2237 * from an async worker thread, grab the lock for that case.
2239 if (needs_lock)
2240 mutex_lock(&ctx->uring_lock);
2243 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2244 int bgid, struct io_buffer *kbuf,
2245 bool needs_lock)
2247 struct io_buffer *head;
2249 if (req->flags & REQ_F_BUFFER_SELECTED)
2250 return kbuf;
2252 io_ring_submit_lock(req->ctx, needs_lock);
2254 lockdep_assert_held(&req->ctx->uring_lock);
2256 head = idr_find(&req->ctx->io_buffer_idr, bgid);
2257 if (head) {
2258 if (!list_empty(&head->list)) {
2259 kbuf = list_last_entry(&head->list, struct io_buffer,
2260 list);
2261 list_del(&kbuf->list);
2262 } else {
2263 kbuf = head;
2264 idr_remove(&req->ctx->io_buffer_idr, bgid);
2266 if (*len > kbuf->len)
2267 *len = kbuf->len;
2268 } else {
2269 kbuf = ERR_PTR(-ENOBUFS);
2272 io_ring_submit_unlock(req->ctx, needs_lock);
2274 return kbuf;
2277 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2278 bool needs_lock)
2280 struct io_buffer *kbuf;
2281 u16 bgid;
2283 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2284 bgid = req->buf_index;
2285 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2286 if (IS_ERR(kbuf))
2287 return kbuf;
2288 req->rw.addr = (u64) (unsigned long) kbuf;
2289 req->flags |= REQ_F_BUFFER_SELECTED;
2290 return u64_to_user_ptr(kbuf->addr);
2293 #ifdef CONFIG_COMPAT
2294 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2295 bool needs_lock)
2297 struct compat_iovec __user *uiov;
2298 compat_ssize_t clen;
2299 void __user *buf;
2300 ssize_t len;
2302 uiov = u64_to_user_ptr(req->rw.addr);
2303 if (!access_ok(uiov, sizeof(*uiov)))
2304 return -EFAULT;
2305 if (__get_user(clen, &uiov->iov_len))
2306 return -EFAULT;
2307 if (clen < 0)
2308 return -EINVAL;
2310 len = clen;
2311 buf = io_rw_buffer_select(req, &len, needs_lock);
2312 if (IS_ERR(buf))
2313 return PTR_ERR(buf);
2314 iov[0].iov_base = buf;
2315 iov[0].iov_len = (compat_size_t) len;
2316 return 0;
2318 #endif
2320 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2321 bool needs_lock)
2323 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2324 void __user *buf;
2325 ssize_t len;
2327 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2328 return -EFAULT;
2330 len = iov[0].iov_len;
2331 if (len < 0)
2332 return -EINVAL;
2333 buf = io_rw_buffer_select(req, &len, needs_lock);
2334 if (IS_ERR(buf))
2335 return PTR_ERR(buf);
2336 iov[0].iov_base = buf;
2337 iov[0].iov_len = len;
2338 return 0;
2341 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2342 bool needs_lock)
2344 if (req->flags & REQ_F_BUFFER_SELECTED) {
2345 struct io_buffer *kbuf;
2347 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2348 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2349 iov[0].iov_len = kbuf->len;
2350 return 0;
2352 if (!req->rw.len)
2353 return 0;
2354 else if (req->rw.len > 1)
2355 return -EINVAL;
2357 #ifdef CONFIG_COMPAT
2358 if (req->ctx->compat)
2359 return io_compat_import(req, iov, needs_lock);
2360 #endif
2362 return __io_iov_buffer_select(req, iov, needs_lock);
2365 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
2366 struct iovec **iovec, struct iov_iter *iter,
2367 bool needs_lock)
2369 void __user *buf = u64_to_user_ptr(req->rw.addr);
2370 size_t sqe_len = req->rw.len;
2371 ssize_t ret;
2372 u8 opcode;
2374 opcode = req->opcode;
2375 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2376 *iovec = NULL;
2377 return io_import_fixed(req, rw, iter);
2380 /* buffer index only valid with fixed read/write, or buffer select */
2381 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
2382 return -EINVAL;
2384 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2385 if (req->flags & REQ_F_BUFFER_SELECT) {
2386 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
2387 if (IS_ERR(buf)) {
2388 *iovec = NULL;
2389 return PTR_ERR(buf);
2391 req->rw.len = sqe_len;
2394 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2395 *iovec = NULL;
2396 return ret < 0 ? ret : sqe_len;
2399 if (req->io) {
2400 struct io_async_rw *iorw = &req->io->rw;
2402 *iovec = iorw->iov;
2403 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
2404 if (iorw->iov == iorw->fast_iov)
2405 *iovec = NULL;
2406 return iorw->size;
2409 if (req->flags & REQ_F_BUFFER_SELECT) {
2410 ret = io_iov_buffer_select(req, *iovec, needs_lock);
2411 if (!ret) {
2412 ret = (*iovec)->iov_len;
2413 iov_iter_init(iter, rw, *iovec, 1, ret);
2415 *iovec = NULL;
2416 return ret;
2419 #ifdef CONFIG_COMPAT
2420 if (req->ctx->compat)
2421 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
2422 iovec, iter);
2423 #endif
2425 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
2429 * For files that don't have ->read_iter() and ->write_iter(), handle them
2430 * by looping over ->read() or ->write() manually.
2432 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2433 struct iov_iter *iter)
2435 ssize_t ret = 0;
2438 * Don't support polled IO through this interface, and we can't
2439 * support non-blocking either. For the latter, this just causes
2440 * the kiocb to be handled from an async context.
2442 if (kiocb->ki_flags & IOCB_HIPRI)
2443 return -EOPNOTSUPP;
2444 if (kiocb->ki_flags & IOCB_NOWAIT)
2445 return -EAGAIN;
2447 while (iov_iter_count(iter)) {
2448 struct iovec iovec;
2449 ssize_t nr;
2451 if (!iov_iter_is_bvec(iter)) {
2452 iovec = iov_iter_iovec(iter);
2453 } else {
2454 /* fixed buffers import bvec */
2455 iovec.iov_base = kmap(iter->bvec->bv_page)
2456 + iter->iov_offset;
2457 iovec.iov_len = min(iter->count,
2458 iter->bvec->bv_len - iter->iov_offset);
2461 if (rw == READ) {
2462 nr = file->f_op->read(file, iovec.iov_base,
2463 iovec.iov_len, &kiocb->ki_pos);
2464 } else {
2465 nr = file->f_op->write(file, iovec.iov_base,
2466 iovec.iov_len, &kiocb->ki_pos);
2469 if (iov_iter_is_bvec(iter))
2470 kunmap(iter->bvec->bv_page);
2472 if (nr < 0) {
2473 if (!ret)
2474 ret = nr;
2475 break;
2477 ret += nr;
2478 if (nr != iovec.iov_len)
2479 break;
2480 iov_iter_advance(iter, nr);
2483 return ret;
2486 static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
2487 struct iovec *iovec, struct iovec *fast_iov,
2488 struct iov_iter *iter)
2490 req->io->rw.nr_segs = iter->nr_segs;
2491 req->io->rw.size = io_size;
2492 req->io->rw.iov = iovec;
2493 if (!req->io->rw.iov) {
2494 req->io->rw.iov = req->io->rw.fast_iov;
2495 if (req->io->rw.iov != fast_iov)
2496 memcpy(req->io->rw.iov, fast_iov,
2497 sizeof(struct iovec) * iter->nr_segs);
2498 } else {
2499 req->flags |= REQ_F_NEED_CLEANUP;
2503 static inline int __io_alloc_async_ctx(struct io_kiocb *req)
2505 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
2506 return req->io == NULL;
2509 static int io_alloc_async_ctx(struct io_kiocb *req)
2511 if (!io_op_defs[req->opcode].async_ctx)
2512 return 0;
2514 return __io_alloc_async_ctx(req);
2517 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
2518 struct iovec *iovec, struct iovec *fast_iov,
2519 struct iov_iter *iter)
2521 if (!io_op_defs[req->opcode].async_ctx)
2522 return 0;
2523 if (!req->io) {
2524 if (__io_alloc_async_ctx(req))
2525 return -ENOMEM;
2527 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
2529 return 0;
2532 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2533 bool force_nonblock)
2535 struct io_async_ctx *io;
2536 struct iov_iter iter;
2537 ssize_t ret;
2539 ret = io_prep_rw(req, sqe, force_nonblock);
2540 if (ret)
2541 return ret;
2543 if (unlikely(!(req->file->f_mode & FMODE_READ)))
2544 return -EBADF;
2546 /* either don't need iovec imported or already have it */
2547 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
2548 return 0;
2550 io = req->io;
2551 io->rw.iov = io->rw.fast_iov;
2552 req->io = NULL;
2553 ret = io_import_iovec(READ, req, &io->rw.iov, &iter, !force_nonblock);
2554 req->io = io;
2555 if (ret < 0)
2556 return ret;
2558 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2559 return 0;
2562 static int io_read(struct io_kiocb *req, bool force_nonblock)
2564 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2565 struct kiocb *kiocb = &req->rw.kiocb;
2566 struct iov_iter iter;
2567 size_t iov_count;
2568 ssize_t io_size, ret;
2570 ret = io_import_iovec(READ, req, &iovec, &iter, !force_nonblock);
2571 if (ret < 0)
2572 return ret;
2574 /* Ensure we clear previously set non-block flag */
2575 if (!force_nonblock)
2576 kiocb->ki_flags &= ~IOCB_NOWAIT;
2578 req->result = 0;
2579 io_size = ret;
2580 if (req->flags & REQ_F_LINK_HEAD)
2581 req->result = io_size;
2584 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2585 * we know to async punt it even if it was opened O_NONBLOCK
2587 if (force_nonblock && !io_file_supports_async(req->file, READ))
2588 goto copy_iov;
2590 iov_count = iov_iter_count(&iter);
2591 ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
2592 if (!ret) {
2593 ssize_t ret2;
2595 if (req->file->f_op->read_iter)
2596 ret2 = call_read_iter(req->file, kiocb, &iter);
2597 else
2598 ret2 = loop_rw_iter(READ, req->file, kiocb, &iter);
2600 /* Catch -EAGAIN return for forced non-blocking submission */
2601 if (!force_nonblock || ret2 != -EAGAIN) {
2602 kiocb_done(kiocb, ret2);
2603 } else {
2604 copy_iov:
2605 ret = io_setup_async_rw(req, io_size, iovec,
2606 inline_vecs, &iter);
2607 if (ret)
2608 goto out_free;
2609 /* any defer here is final, must blocking retry */
2610 if (!(req->flags & REQ_F_NOWAIT) &&
2611 !file_can_poll(req->file))
2612 req->flags |= REQ_F_MUST_PUNT;
2613 return -EAGAIN;
2616 out_free:
2617 if (!(req->flags & REQ_F_NEED_CLEANUP))
2618 kfree(iovec);
2619 return ret;
2622 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2623 bool force_nonblock)
2625 struct io_async_ctx *io;
2626 struct iov_iter iter;
2627 ssize_t ret;
2629 ret = io_prep_rw(req, sqe, force_nonblock);
2630 if (ret)
2631 return ret;
2633 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
2634 return -EBADF;
2636 req->fsize = rlimit(RLIMIT_FSIZE);
2638 /* either don't need iovec imported or already have it */
2639 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
2640 return 0;
2642 io = req->io;
2643 io->rw.iov = io->rw.fast_iov;
2644 req->io = NULL;
2645 ret = io_import_iovec(WRITE, req, &io->rw.iov, &iter, !force_nonblock);
2646 req->io = io;
2647 if (ret < 0)
2648 return ret;
2650 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2651 return 0;
2654 static int io_write(struct io_kiocb *req, bool force_nonblock)
2656 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2657 struct kiocb *kiocb = &req->rw.kiocb;
2658 struct iov_iter iter;
2659 size_t iov_count;
2660 ssize_t ret, io_size;
2662 ret = io_import_iovec(WRITE, req, &iovec, &iter, !force_nonblock);
2663 if (ret < 0)
2664 return ret;
2666 /* Ensure we clear previously set non-block flag */
2667 if (!force_nonblock)
2668 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
2670 req->result = 0;
2671 io_size = ret;
2672 if (req->flags & REQ_F_LINK_HEAD)
2673 req->result = io_size;
2676 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
2677 * we know to async punt it even if it was opened O_NONBLOCK
2679 if (force_nonblock && !io_file_supports_async(req->file, WRITE))
2680 goto copy_iov;
2682 /* file path doesn't support NOWAIT for non-direct_IO */
2683 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
2684 (req->flags & REQ_F_ISREG))
2685 goto copy_iov;
2687 iov_count = iov_iter_count(&iter);
2688 ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
2689 if (!ret) {
2690 ssize_t ret2;
2693 * Open-code file_start_write here to grab freeze protection,
2694 * which will be released by another thread in
2695 * io_complete_rw(). Fool lockdep by telling it the lock got
2696 * released so that it doesn't complain about the held lock when
2697 * we return to userspace.
2699 if (req->flags & REQ_F_ISREG) {
2700 __sb_start_write(file_inode(req->file)->i_sb,
2701 SB_FREEZE_WRITE, true);
2702 __sb_writers_release(file_inode(req->file)->i_sb,
2703 SB_FREEZE_WRITE);
2705 kiocb->ki_flags |= IOCB_WRITE;
2707 if (!force_nonblock)
2708 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = req->fsize;
2710 if (req->file->f_op->write_iter)
2711 ret2 = call_write_iter(req->file, kiocb, &iter);
2712 else
2713 ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
2715 if (!force_nonblock)
2716 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
2719 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
2720 * retry them without IOCB_NOWAIT.
2722 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
2723 ret2 = -EAGAIN;
2724 if (!force_nonblock || ret2 != -EAGAIN) {
2725 kiocb_done(kiocb, ret2);
2726 } else {
2727 copy_iov:
2728 ret = io_setup_async_rw(req, io_size, iovec,
2729 inline_vecs, &iter);
2730 if (ret)
2731 goto out_free;
2732 /* any defer here is final, must blocking retry */
2733 if (!(req->flags & REQ_F_NOWAIT) &&
2734 !file_can_poll(req->file))
2735 req->flags |= REQ_F_MUST_PUNT;
2736 return -EAGAIN;
2739 out_free:
2740 if (!(req->flags & REQ_F_NEED_CLEANUP))
2741 kfree(iovec);
2742 return ret;
2745 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2747 struct io_splice* sp = &req->splice;
2748 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
2749 int ret;
2751 if (req->flags & REQ_F_NEED_CLEANUP)
2752 return 0;
2754 sp->file_in = NULL;
2755 sp->off_in = READ_ONCE(sqe->splice_off_in);
2756 sp->off_out = READ_ONCE(sqe->off);
2757 sp->len = READ_ONCE(sqe->len);
2758 sp->flags = READ_ONCE(sqe->splice_flags);
2760 if (unlikely(sp->flags & ~valid_flags))
2761 return -EINVAL;
2763 ret = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in), &sp->file_in,
2764 (sp->flags & SPLICE_F_FD_IN_FIXED));
2765 if (ret)
2766 return ret;
2767 req->flags |= REQ_F_NEED_CLEANUP;
2769 if (!S_ISREG(file_inode(sp->file_in)->i_mode))
2770 req->work.flags |= IO_WQ_WORK_UNBOUND;
2772 return 0;
2775 static int io_splice(struct io_kiocb *req, bool force_nonblock)
2777 struct io_splice *sp = &req->splice;
2778 struct file *in = sp->file_in;
2779 struct file *out = sp->file_out;
2780 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
2781 loff_t *poff_in, *poff_out;
2782 long ret = 0;
2784 if (force_nonblock)
2785 return -EAGAIN;
2787 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
2788 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
2790 if (sp->len)
2791 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
2793 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
2794 req->flags &= ~REQ_F_NEED_CLEANUP;
2796 io_cqring_add_event(req, ret);
2797 if (ret != sp->len)
2798 req_set_fail_links(req);
2799 io_put_req(req);
2800 return 0;
2804 * IORING_OP_NOP just posts a completion event, nothing else.
2806 static int io_nop(struct io_kiocb *req)
2808 struct io_ring_ctx *ctx = req->ctx;
2810 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2811 return -EINVAL;
2813 io_cqring_add_event(req, 0);
2814 io_put_req(req);
2815 return 0;
2818 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2820 struct io_ring_ctx *ctx = req->ctx;
2822 if (!req->file)
2823 return -EBADF;
2825 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2826 return -EINVAL;
2827 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2828 return -EINVAL;
2830 req->sync.flags = READ_ONCE(sqe->fsync_flags);
2831 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
2832 return -EINVAL;
2834 req->sync.off = READ_ONCE(sqe->off);
2835 req->sync.len = READ_ONCE(sqe->len);
2836 return 0;
2839 static bool io_req_cancelled(struct io_kiocb *req)
2841 if (req->work.flags & IO_WQ_WORK_CANCEL) {
2842 req_set_fail_links(req);
2843 io_cqring_add_event(req, -ECANCELED);
2844 io_put_req(req);
2845 return true;
2848 return false;
2851 static void __io_fsync(struct io_kiocb *req)
2853 loff_t end = req->sync.off + req->sync.len;
2854 int ret;
2856 ret = vfs_fsync_range(req->file, req->sync.off,
2857 end > 0 ? end : LLONG_MAX,
2858 req->sync.flags & IORING_FSYNC_DATASYNC);
2859 if (ret < 0)
2860 req_set_fail_links(req);
2861 io_cqring_add_event(req, ret);
2862 io_put_req(req);
2865 static void io_fsync_finish(struct io_wq_work **workptr)
2867 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2869 if (io_req_cancelled(req))
2870 return;
2871 __io_fsync(req);
2872 io_steal_work(req, workptr);
2875 static int io_fsync(struct io_kiocb *req, bool force_nonblock)
2877 /* fsync always requires a blocking context */
2878 if (force_nonblock) {
2879 req->work.func = io_fsync_finish;
2880 return -EAGAIN;
2882 __io_fsync(req);
2883 return 0;
2886 static void __io_fallocate(struct io_kiocb *req)
2888 int ret;
2890 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = req->fsize;
2891 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
2892 req->sync.len);
2893 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
2894 if (ret < 0)
2895 req_set_fail_links(req);
2896 io_cqring_add_event(req, ret);
2897 io_put_req(req);
2900 static void io_fallocate_finish(struct io_wq_work **workptr)
2902 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2904 if (io_req_cancelled(req))
2905 return;
2906 __io_fallocate(req);
2907 io_steal_work(req, workptr);
2910 static int io_fallocate_prep(struct io_kiocb *req,
2911 const struct io_uring_sqe *sqe)
2913 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
2914 return -EINVAL;
2916 req->sync.off = READ_ONCE(sqe->off);
2917 req->sync.len = READ_ONCE(sqe->addr);
2918 req->sync.mode = READ_ONCE(sqe->len);
2919 req->fsize = rlimit(RLIMIT_FSIZE);
2920 return 0;
2923 static int io_fallocate(struct io_kiocb *req, bool force_nonblock)
2925 /* fallocate always requiring blocking context */
2926 if (force_nonblock) {
2927 req->work.func = io_fallocate_finish;
2928 return -EAGAIN;
2931 __io_fallocate(req);
2932 return 0;
2935 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2937 const char __user *fname;
2938 int ret;
2940 if (sqe->ioprio || sqe->buf_index)
2941 return -EINVAL;
2942 if (req->flags & REQ_F_FIXED_FILE)
2943 return -EBADF;
2944 if (req->flags & REQ_F_NEED_CLEANUP)
2945 return 0;
2947 req->open.dfd = READ_ONCE(sqe->fd);
2948 req->open.how.mode = READ_ONCE(sqe->len);
2949 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2950 req->open.how.flags = READ_ONCE(sqe->open_flags);
2951 if (force_o_largefile())
2952 req->open.how.flags |= O_LARGEFILE;
2954 req->open.filename = getname(fname);
2955 if (IS_ERR(req->open.filename)) {
2956 ret = PTR_ERR(req->open.filename);
2957 req->open.filename = NULL;
2958 return ret;
2961 req->open.nofile = rlimit(RLIMIT_NOFILE);
2962 req->flags |= REQ_F_NEED_CLEANUP;
2963 return 0;
2966 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2968 struct open_how __user *how;
2969 const char __user *fname;
2970 size_t len;
2971 int ret;
2973 if (sqe->ioprio || sqe->buf_index)
2974 return -EINVAL;
2975 if (req->flags & REQ_F_FIXED_FILE)
2976 return -EBADF;
2977 if (req->flags & REQ_F_NEED_CLEANUP)
2978 return 0;
2980 req->open.dfd = READ_ONCE(sqe->fd);
2981 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2982 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2983 len = READ_ONCE(sqe->len);
2985 if (len < OPEN_HOW_SIZE_VER0)
2986 return -EINVAL;
2988 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
2989 len);
2990 if (ret)
2991 return ret;
2993 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
2994 req->open.how.flags |= O_LARGEFILE;
2996 req->open.filename = getname(fname);
2997 if (IS_ERR(req->open.filename)) {
2998 ret = PTR_ERR(req->open.filename);
2999 req->open.filename = NULL;
3000 return ret;
3003 req->open.nofile = rlimit(RLIMIT_NOFILE);
3004 req->flags |= REQ_F_NEED_CLEANUP;
3005 return 0;
3008 static int io_openat2(struct io_kiocb *req, bool force_nonblock)
3010 struct open_flags op;
3011 struct file *file;
3012 int ret;
3014 if (force_nonblock)
3015 return -EAGAIN;
3017 ret = build_open_flags(&req->open.how, &op);
3018 if (ret)
3019 goto err;
3021 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3022 if (ret < 0)
3023 goto err;
3025 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3026 if (IS_ERR(file)) {
3027 put_unused_fd(ret);
3028 ret = PTR_ERR(file);
3029 } else {
3030 fsnotify_open(file);
3031 fd_install(ret, file);
3033 err:
3034 putname(req->open.filename);
3035 req->flags &= ~REQ_F_NEED_CLEANUP;
3036 if (ret < 0)
3037 req_set_fail_links(req);
3038 io_cqring_add_event(req, ret);
3039 io_put_req(req);
3040 return 0;
3043 static int io_openat(struct io_kiocb *req, bool force_nonblock)
3045 req->open.how = build_open_how(req->open.how.flags, req->open.how.mode);
3046 return io_openat2(req, force_nonblock);
3049 static int io_remove_buffers_prep(struct io_kiocb *req,
3050 const struct io_uring_sqe *sqe)
3052 struct io_provide_buf *p = &req->pbuf;
3053 u64 tmp;
3055 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3056 return -EINVAL;
3058 tmp = READ_ONCE(sqe->fd);
3059 if (!tmp || tmp > USHRT_MAX)
3060 return -EINVAL;
3062 memset(p, 0, sizeof(*p));
3063 p->nbufs = tmp;
3064 p->bgid = READ_ONCE(sqe->buf_group);
3065 return 0;
3068 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3069 int bgid, unsigned nbufs)
3071 unsigned i = 0;
3073 /* shouldn't happen */
3074 if (!nbufs)
3075 return 0;
3077 /* the head kbuf is the list itself */
3078 while (!list_empty(&buf->list)) {
3079 struct io_buffer *nxt;
3081 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3082 list_del(&nxt->list);
3083 kfree(nxt);
3084 if (++i == nbufs)
3085 return i;
3087 i++;
3088 kfree(buf);
3089 idr_remove(&ctx->io_buffer_idr, bgid);
3091 return i;
3094 static int io_remove_buffers(struct io_kiocb *req, bool force_nonblock)
3096 struct io_provide_buf *p = &req->pbuf;
3097 struct io_ring_ctx *ctx = req->ctx;
3098 struct io_buffer *head;
3099 int ret = 0;
3101 io_ring_submit_lock(ctx, !force_nonblock);
3103 lockdep_assert_held(&ctx->uring_lock);
3105 ret = -ENOENT;
3106 head = idr_find(&ctx->io_buffer_idr, p->bgid);
3107 if (head)
3108 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3110 io_ring_submit_lock(ctx, !force_nonblock);
3111 if (ret < 0)
3112 req_set_fail_links(req);
3113 io_cqring_add_event(req, ret);
3114 io_put_req(req);
3115 return 0;
3118 static int io_provide_buffers_prep(struct io_kiocb *req,
3119 const struct io_uring_sqe *sqe)
3121 struct io_provide_buf *p = &req->pbuf;
3122 u64 tmp;
3124 if (sqe->ioprio || sqe->rw_flags)
3125 return -EINVAL;
3127 tmp = READ_ONCE(sqe->fd);
3128 if (!tmp || tmp > USHRT_MAX)
3129 return -E2BIG;
3130 p->nbufs = tmp;
3131 p->addr = READ_ONCE(sqe->addr);
3132 p->len = READ_ONCE(sqe->len);
3134 if (!access_ok(u64_to_user_ptr(p->addr), p->len))
3135 return -EFAULT;
3137 p->bgid = READ_ONCE(sqe->buf_group);
3138 tmp = READ_ONCE(sqe->off);
3139 if (tmp > USHRT_MAX)
3140 return -E2BIG;
3141 p->bid = tmp;
3142 return 0;
3145 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3147 struct io_buffer *buf;
3148 u64 addr = pbuf->addr;
3149 int i, bid = pbuf->bid;
3151 for (i = 0; i < pbuf->nbufs; i++) {
3152 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3153 if (!buf)
3154 break;
3156 buf->addr = addr;
3157 buf->len = pbuf->len;
3158 buf->bid = bid;
3159 addr += pbuf->len;
3160 bid++;
3161 if (!*head) {
3162 INIT_LIST_HEAD(&buf->list);
3163 *head = buf;
3164 } else {
3165 list_add_tail(&buf->list, &(*head)->list);
3169 return i ? i : -ENOMEM;
3172 static int io_provide_buffers(struct io_kiocb *req, bool force_nonblock)
3174 struct io_provide_buf *p = &req->pbuf;
3175 struct io_ring_ctx *ctx = req->ctx;
3176 struct io_buffer *head, *list;
3177 int ret = 0;
3179 io_ring_submit_lock(ctx, !force_nonblock);
3181 lockdep_assert_held(&ctx->uring_lock);
3183 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
3185 ret = io_add_buffers(p, &head);
3186 if (ret < 0)
3187 goto out;
3189 if (!list) {
3190 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
3191 GFP_KERNEL);
3192 if (ret < 0) {
3193 __io_remove_buffers(ctx, head, p->bgid, -1U);
3194 goto out;
3197 out:
3198 io_ring_submit_unlock(ctx, !force_nonblock);
3199 if (ret < 0)
3200 req_set_fail_links(req);
3201 io_cqring_add_event(req, ret);
3202 io_put_req(req);
3203 return 0;
3206 static int io_epoll_ctl_prep(struct io_kiocb *req,
3207 const struct io_uring_sqe *sqe)
3209 #if defined(CONFIG_EPOLL)
3210 if (sqe->ioprio || sqe->buf_index)
3211 return -EINVAL;
3213 req->epoll.epfd = READ_ONCE(sqe->fd);
3214 req->epoll.op = READ_ONCE(sqe->len);
3215 req->epoll.fd = READ_ONCE(sqe->off);
3217 if (ep_op_has_event(req->epoll.op)) {
3218 struct epoll_event __user *ev;
3220 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
3221 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
3222 return -EFAULT;
3225 return 0;
3226 #else
3227 return -EOPNOTSUPP;
3228 #endif
3231 static int io_epoll_ctl(struct io_kiocb *req, bool force_nonblock)
3233 #if defined(CONFIG_EPOLL)
3234 struct io_epoll *ie = &req->epoll;
3235 int ret;
3237 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
3238 if (force_nonblock && ret == -EAGAIN)
3239 return -EAGAIN;
3241 if (ret < 0)
3242 req_set_fail_links(req);
3243 io_cqring_add_event(req, ret);
3244 io_put_req(req);
3245 return 0;
3246 #else
3247 return -EOPNOTSUPP;
3248 #endif
3251 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3253 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3254 if (sqe->ioprio || sqe->buf_index || sqe->off)
3255 return -EINVAL;
3257 req->madvise.addr = READ_ONCE(sqe->addr);
3258 req->madvise.len = READ_ONCE(sqe->len);
3259 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
3260 return 0;
3261 #else
3262 return -EOPNOTSUPP;
3263 #endif
3266 static int io_madvise(struct io_kiocb *req, bool force_nonblock)
3268 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3269 struct io_madvise *ma = &req->madvise;
3270 int ret;
3272 if (force_nonblock)
3273 return -EAGAIN;
3275 ret = do_madvise(ma->addr, ma->len, ma->advice);
3276 if (ret < 0)
3277 req_set_fail_links(req);
3278 io_cqring_add_event(req, ret);
3279 io_put_req(req);
3280 return 0;
3281 #else
3282 return -EOPNOTSUPP;
3283 #endif
3286 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3288 if (sqe->ioprio || sqe->buf_index || sqe->addr)
3289 return -EINVAL;
3291 req->fadvise.offset = READ_ONCE(sqe->off);
3292 req->fadvise.len = READ_ONCE(sqe->len);
3293 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
3294 return 0;
3297 static int io_fadvise(struct io_kiocb *req, bool force_nonblock)
3299 struct io_fadvise *fa = &req->fadvise;
3300 int ret;
3302 if (force_nonblock) {
3303 switch (fa->advice) {
3304 case POSIX_FADV_NORMAL:
3305 case POSIX_FADV_RANDOM:
3306 case POSIX_FADV_SEQUENTIAL:
3307 break;
3308 default:
3309 return -EAGAIN;
3313 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
3314 if (ret < 0)
3315 req_set_fail_links(req);
3316 io_cqring_add_event(req, ret);
3317 io_put_req(req);
3318 return 0;
3321 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3323 const char __user *fname;
3324 unsigned lookup_flags;
3325 int ret;
3327 if (sqe->ioprio || sqe->buf_index)
3328 return -EINVAL;
3329 if (req->flags & REQ_F_FIXED_FILE)
3330 return -EBADF;
3331 if (req->flags & REQ_F_NEED_CLEANUP)
3332 return 0;
3334 req->open.dfd = READ_ONCE(sqe->fd);
3335 req->open.mask = READ_ONCE(sqe->len);
3336 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3337 req->open.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3338 req->open.how.flags = READ_ONCE(sqe->statx_flags);
3340 if (vfs_stat_set_lookup_flags(&lookup_flags, req->open.how.flags))
3341 return -EINVAL;
3343 req->open.filename = getname_flags(fname, lookup_flags, NULL);
3344 if (IS_ERR(req->open.filename)) {
3345 ret = PTR_ERR(req->open.filename);
3346 req->open.filename = NULL;
3347 return ret;
3350 req->flags |= REQ_F_NEED_CLEANUP;
3351 return 0;
3354 static int io_statx(struct io_kiocb *req, bool force_nonblock)
3356 struct io_open *ctx = &req->open;
3357 unsigned lookup_flags;
3358 struct path path;
3359 struct kstat stat;
3360 int ret;
3362 if (force_nonblock) {
3363 /* only need file table for an actual valid fd */
3364 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
3365 req->flags |= REQ_F_NO_FILE_TABLE;
3366 return -EAGAIN;
3369 if (vfs_stat_set_lookup_flags(&lookup_flags, ctx->how.flags))
3370 return -EINVAL;
3372 retry:
3373 /* filename_lookup() drops it, keep a reference */
3374 ctx->filename->refcnt++;
3376 ret = filename_lookup(ctx->dfd, ctx->filename, lookup_flags, &path,
3377 NULL);
3378 if (ret)
3379 goto err;
3381 ret = vfs_getattr(&path, &stat, ctx->mask, ctx->how.flags);
3382 path_put(&path);
3383 if (retry_estale(ret, lookup_flags)) {
3384 lookup_flags |= LOOKUP_REVAL;
3385 goto retry;
3387 if (!ret)
3388 ret = cp_statx(&stat, ctx->buffer);
3389 err:
3390 putname(ctx->filename);
3391 req->flags &= ~REQ_F_NEED_CLEANUP;
3392 if (ret < 0)
3393 req_set_fail_links(req);
3394 io_cqring_add_event(req, ret);
3395 io_put_req(req);
3396 return 0;
3399 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3402 * If we queue this for async, it must not be cancellable. That would
3403 * leave the 'file' in an undeterminate state.
3405 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
3407 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
3408 sqe->rw_flags || sqe->buf_index)
3409 return -EINVAL;
3410 if (req->flags & REQ_F_FIXED_FILE)
3411 return -EBADF;
3413 req->close.fd = READ_ONCE(sqe->fd);
3414 if (req->file->f_op == &io_uring_fops ||
3415 req->close.fd == req->ctx->ring_fd)
3416 return -EBADF;
3418 return 0;
3421 /* only called when __close_fd_get_file() is done */
3422 static void __io_close_finish(struct io_kiocb *req)
3424 int ret;
3426 ret = filp_close(req->close.put_file, req->work.files);
3427 if (ret < 0)
3428 req_set_fail_links(req);
3429 io_cqring_add_event(req, ret);
3430 fput(req->close.put_file);
3431 io_put_req(req);
3434 static void io_close_finish(struct io_wq_work **workptr)
3436 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3438 /* not cancellable, don't do io_req_cancelled() */
3439 __io_close_finish(req);
3440 io_steal_work(req, workptr);
3443 static int io_close(struct io_kiocb *req, bool force_nonblock)
3445 int ret;
3447 req->close.put_file = NULL;
3448 ret = __close_fd_get_file(req->close.fd, &req->close.put_file);
3449 if (ret < 0)
3450 return ret;
3452 /* if the file has a flush method, be safe and punt to async */
3453 if (req->close.put_file->f_op->flush && force_nonblock) {
3454 /* submission ref will be dropped, take it for async */
3455 refcount_inc(&req->refs);
3457 req->work.func = io_close_finish;
3459 * Do manual async queue here to avoid grabbing files - we don't
3460 * need the files, and it'll cause io_close_finish() to close
3461 * the file again and cause a double CQE entry for this request
3463 io_queue_async_work(req);
3464 return 0;
3468 * No ->flush(), safely close from here and just punt the
3469 * fput() to async context.
3471 __io_close_finish(req);
3472 return 0;
3475 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3477 struct io_ring_ctx *ctx = req->ctx;
3479 if (!req->file)
3480 return -EBADF;
3482 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3483 return -EINVAL;
3484 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3485 return -EINVAL;
3487 req->sync.off = READ_ONCE(sqe->off);
3488 req->sync.len = READ_ONCE(sqe->len);
3489 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
3490 return 0;
3493 static void __io_sync_file_range(struct io_kiocb *req)
3495 int ret;
3497 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
3498 req->sync.flags);
3499 if (ret < 0)
3500 req_set_fail_links(req);
3501 io_cqring_add_event(req, ret);
3502 io_put_req(req);
3506 static void io_sync_file_range_finish(struct io_wq_work **workptr)
3508 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3510 if (io_req_cancelled(req))
3511 return;
3512 __io_sync_file_range(req);
3513 io_steal_work(req, workptr);
3516 static int io_sync_file_range(struct io_kiocb *req, bool force_nonblock)
3518 /* sync_file_range always requires a blocking context */
3519 if (force_nonblock) {
3520 req->work.func = io_sync_file_range_finish;
3521 return -EAGAIN;
3524 __io_sync_file_range(req);
3525 return 0;
3528 #if defined(CONFIG_NET)
3529 static int io_setup_async_msg(struct io_kiocb *req,
3530 struct io_async_msghdr *kmsg)
3532 if (req->io)
3533 return -EAGAIN;
3534 if (io_alloc_async_ctx(req)) {
3535 if (kmsg->iov != kmsg->fast_iov)
3536 kfree(kmsg->iov);
3537 return -ENOMEM;
3539 req->flags |= REQ_F_NEED_CLEANUP;
3540 memcpy(&req->io->msg, kmsg, sizeof(*kmsg));
3541 return -EAGAIN;
3544 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3546 struct io_sr_msg *sr = &req->sr_msg;
3547 struct io_async_ctx *io = req->io;
3548 int ret;
3550 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3551 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
3552 sr->len = READ_ONCE(sqe->len);
3554 #ifdef CONFIG_COMPAT
3555 if (req->ctx->compat)
3556 sr->msg_flags |= MSG_CMSG_COMPAT;
3557 #endif
3559 if (!io || req->opcode == IORING_OP_SEND)
3560 return 0;
3561 /* iovec is already imported */
3562 if (req->flags & REQ_F_NEED_CLEANUP)
3563 return 0;
3565 io->msg.iov = io->msg.fast_iov;
3566 ret = sendmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
3567 &io->msg.iov);
3568 if (!ret)
3569 req->flags |= REQ_F_NEED_CLEANUP;
3570 return ret;
3573 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock)
3575 struct io_async_msghdr *kmsg = NULL;
3576 struct socket *sock;
3577 int ret;
3579 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3580 return -EINVAL;
3582 sock = sock_from_file(req->file, &ret);
3583 if (sock) {
3584 struct io_async_ctx io;
3585 unsigned flags;
3587 if (req->io) {
3588 kmsg = &req->io->msg;
3589 kmsg->msg.msg_name = &req->io->msg.addr;
3590 /* if iov is set, it's allocated already */
3591 if (!kmsg->iov)
3592 kmsg->iov = kmsg->fast_iov;
3593 kmsg->msg.msg_iter.iov = kmsg->iov;
3594 } else {
3595 struct io_sr_msg *sr = &req->sr_msg;
3597 kmsg = &io.msg;
3598 kmsg->msg.msg_name = &io.msg.addr;
3600 io.msg.iov = io.msg.fast_iov;
3601 ret = sendmsg_copy_msghdr(&io.msg.msg, sr->msg,
3602 sr->msg_flags, &io.msg.iov);
3603 if (ret)
3604 return ret;
3607 flags = req->sr_msg.msg_flags;
3608 if (flags & MSG_DONTWAIT)
3609 req->flags |= REQ_F_NOWAIT;
3610 else if (force_nonblock)
3611 flags |= MSG_DONTWAIT;
3613 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
3614 if (force_nonblock && ret == -EAGAIN)
3615 return io_setup_async_msg(req, kmsg);
3616 if (ret == -ERESTARTSYS)
3617 ret = -EINTR;
3620 if (kmsg && kmsg->iov != kmsg->fast_iov)
3621 kfree(kmsg->iov);
3622 req->flags &= ~REQ_F_NEED_CLEANUP;
3623 io_cqring_add_event(req, ret);
3624 if (ret < 0)
3625 req_set_fail_links(req);
3626 io_put_req(req);
3627 return 0;
3630 static int io_send(struct io_kiocb *req, bool force_nonblock)
3632 struct socket *sock;
3633 int ret;
3635 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3636 return -EINVAL;
3638 sock = sock_from_file(req->file, &ret);
3639 if (sock) {
3640 struct io_sr_msg *sr = &req->sr_msg;
3641 struct msghdr msg;
3642 struct iovec iov;
3643 unsigned flags;
3645 ret = import_single_range(WRITE, sr->buf, sr->len, &iov,
3646 &msg.msg_iter);
3647 if (ret)
3648 return ret;
3650 msg.msg_name = NULL;
3651 msg.msg_control = NULL;
3652 msg.msg_controllen = 0;
3653 msg.msg_namelen = 0;
3655 flags = req->sr_msg.msg_flags;
3656 if (flags & MSG_DONTWAIT)
3657 req->flags |= REQ_F_NOWAIT;
3658 else if (force_nonblock)
3659 flags |= MSG_DONTWAIT;
3661 msg.msg_flags = flags;
3662 ret = sock_sendmsg(sock, &msg);
3663 if (force_nonblock && ret == -EAGAIN)
3664 return -EAGAIN;
3665 if (ret == -ERESTARTSYS)
3666 ret = -EINTR;
3669 io_cqring_add_event(req, ret);
3670 if (ret < 0)
3671 req_set_fail_links(req);
3672 io_put_req(req);
3673 return 0;
3676 static int __io_recvmsg_copy_hdr(struct io_kiocb *req, struct io_async_ctx *io)
3678 struct io_sr_msg *sr = &req->sr_msg;
3679 struct iovec __user *uiov;
3680 size_t iov_len;
3681 int ret;
3683 ret = __copy_msghdr_from_user(&io->msg.msg, sr->msg, &io->msg.uaddr,
3684 &uiov, &iov_len);
3685 if (ret)
3686 return ret;
3688 if (req->flags & REQ_F_BUFFER_SELECT) {
3689 if (iov_len > 1)
3690 return -EINVAL;
3691 if (copy_from_user(io->msg.iov, uiov, sizeof(*uiov)))
3692 return -EFAULT;
3693 sr->len = io->msg.iov[0].iov_len;
3694 iov_iter_init(&io->msg.msg.msg_iter, READ, io->msg.iov, 1,
3695 sr->len);
3696 io->msg.iov = NULL;
3697 } else {
3698 ret = import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
3699 &io->msg.iov, &io->msg.msg.msg_iter);
3700 if (ret > 0)
3701 ret = 0;
3704 return ret;
3707 #ifdef CONFIG_COMPAT
3708 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
3709 struct io_async_ctx *io)
3711 struct compat_msghdr __user *msg_compat;
3712 struct io_sr_msg *sr = &req->sr_msg;
3713 struct compat_iovec __user *uiov;
3714 compat_uptr_t ptr;
3715 compat_size_t len;
3716 int ret;
3718 msg_compat = (struct compat_msghdr __user *) sr->msg;
3719 ret = __get_compat_msghdr(&io->msg.msg, msg_compat, &io->msg.uaddr,
3720 &ptr, &len);
3721 if (ret)
3722 return ret;
3724 uiov = compat_ptr(ptr);
3725 if (req->flags & REQ_F_BUFFER_SELECT) {
3726 compat_ssize_t clen;
3728 if (len > 1)
3729 return -EINVAL;
3730 if (!access_ok(uiov, sizeof(*uiov)))
3731 return -EFAULT;
3732 if (__get_user(clen, &uiov->iov_len))
3733 return -EFAULT;
3734 if (clen < 0)
3735 return -EINVAL;
3736 sr->len = io->msg.iov[0].iov_len;
3737 io->msg.iov = NULL;
3738 } else {
3739 ret = compat_import_iovec(READ, uiov, len, UIO_FASTIOV,
3740 &io->msg.iov,
3741 &io->msg.msg.msg_iter);
3742 if (ret < 0)
3743 return ret;
3746 return 0;
3748 #endif
3750 static int io_recvmsg_copy_hdr(struct io_kiocb *req, struct io_async_ctx *io)
3752 io->msg.iov = io->msg.fast_iov;
3754 #ifdef CONFIG_COMPAT
3755 if (req->ctx->compat)
3756 return __io_compat_recvmsg_copy_hdr(req, io);
3757 #endif
3759 return __io_recvmsg_copy_hdr(req, io);
3762 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
3763 int *cflags, bool needs_lock)
3765 struct io_sr_msg *sr = &req->sr_msg;
3766 struct io_buffer *kbuf;
3768 if (!(req->flags & REQ_F_BUFFER_SELECT))
3769 return NULL;
3771 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
3772 if (IS_ERR(kbuf))
3773 return kbuf;
3775 sr->kbuf = kbuf;
3776 req->flags |= REQ_F_BUFFER_SELECTED;
3778 *cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
3779 *cflags |= IORING_CQE_F_BUFFER;
3780 return kbuf;
3783 static int io_recvmsg_prep(struct io_kiocb *req,
3784 const struct io_uring_sqe *sqe)
3786 struct io_sr_msg *sr = &req->sr_msg;
3787 struct io_async_ctx *io = req->io;
3788 int ret;
3790 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3791 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
3792 sr->len = READ_ONCE(sqe->len);
3793 sr->bgid = READ_ONCE(sqe->buf_group);
3795 #ifdef CONFIG_COMPAT
3796 if (req->ctx->compat)
3797 sr->msg_flags |= MSG_CMSG_COMPAT;
3798 #endif
3800 if (!io || req->opcode == IORING_OP_RECV)
3801 return 0;
3802 /* iovec is already imported */
3803 if (req->flags & REQ_F_NEED_CLEANUP)
3804 return 0;
3806 ret = io_recvmsg_copy_hdr(req, io);
3807 if (!ret)
3808 req->flags |= REQ_F_NEED_CLEANUP;
3809 return ret;
3812 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock)
3814 struct io_async_msghdr *kmsg = NULL;
3815 struct socket *sock;
3816 int ret, cflags = 0;
3818 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3819 return -EINVAL;
3821 sock = sock_from_file(req->file, &ret);
3822 if (sock) {
3823 struct io_buffer *kbuf;
3824 struct io_async_ctx io;
3825 unsigned flags;
3827 if (req->io) {
3828 kmsg = &req->io->msg;
3829 kmsg->msg.msg_name = &req->io->msg.addr;
3830 /* if iov is set, it's allocated already */
3831 if (!kmsg->iov)
3832 kmsg->iov = kmsg->fast_iov;
3833 kmsg->msg.msg_iter.iov = kmsg->iov;
3834 } else {
3835 kmsg = &io.msg;
3836 kmsg->msg.msg_name = &io.msg.addr;
3838 ret = io_recvmsg_copy_hdr(req, &io);
3839 if (ret)
3840 return ret;
3843 kbuf = io_recv_buffer_select(req, &cflags, !force_nonblock);
3844 if (IS_ERR(kbuf)) {
3845 return PTR_ERR(kbuf);
3846 } else if (kbuf) {
3847 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3848 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->iov,
3849 1, req->sr_msg.len);
3852 flags = req->sr_msg.msg_flags;
3853 if (flags & MSG_DONTWAIT)
3854 req->flags |= REQ_F_NOWAIT;
3855 else if (force_nonblock)
3856 flags |= MSG_DONTWAIT;
3858 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.msg,
3859 kmsg->uaddr, flags);
3860 if (force_nonblock && ret == -EAGAIN)
3861 return io_setup_async_msg(req, kmsg);
3862 if (ret == -ERESTARTSYS)
3863 ret = -EINTR;
3866 if (kmsg && kmsg->iov != kmsg->fast_iov)
3867 kfree(kmsg->iov);
3868 req->flags &= ~REQ_F_NEED_CLEANUP;
3869 __io_cqring_add_event(req, ret, cflags);
3870 if (ret < 0)
3871 req_set_fail_links(req);
3872 io_put_req(req);
3873 return 0;
3876 static int io_recv(struct io_kiocb *req, bool force_nonblock)
3878 struct io_buffer *kbuf = NULL;
3879 struct socket *sock;
3880 int ret, cflags = 0;
3882 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3883 return -EINVAL;
3885 sock = sock_from_file(req->file, &ret);
3886 if (sock) {
3887 struct io_sr_msg *sr = &req->sr_msg;
3888 void __user *buf = sr->buf;
3889 struct msghdr msg;
3890 struct iovec iov;
3891 unsigned flags;
3893 kbuf = io_recv_buffer_select(req, &cflags, !force_nonblock);
3894 if (IS_ERR(kbuf))
3895 return PTR_ERR(kbuf);
3896 else if (kbuf)
3897 buf = u64_to_user_ptr(kbuf->addr);
3899 ret = import_single_range(READ, buf, sr->len, &iov,
3900 &msg.msg_iter);
3901 if (ret) {
3902 kfree(kbuf);
3903 return ret;
3906 req->flags |= REQ_F_NEED_CLEANUP;
3907 msg.msg_name = NULL;
3908 msg.msg_control = NULL;
3909 msg.msg_controllen = 0;
3910 msg.msg_namelen = 0;
3911 msg.msg_iocb = NULL;
3912 msg.msg_flags = 0;
3914 flags = req->sr_msg.msg_flags;
3915 if (flags & MSG_DONTWAIT)
3916 req->flags |= REQ_F_NOWAIT;
3917 else if (force_nonblock)
3918 flags |= MSG_DONTWAIT;
3920 ret = sock_recvmsg(sock, &msg, flags);
3921 if (force_nonblock && ret == -EAGAIN)
3922 return -EAGAIN;
3923 if (ret == -ERESTARTSYS)
3924 ret = -EINTR;
3927 kfree(kbuf);
3928 req->flags &= ~REQ_F_NEED_CLEANUP;
3929 __io_cqring_add_event(req, ret, cflags);
3930 if (ret < 0)
3931 req_set_fail_links(req);
3932 io_put_req(req);
3933 return 0;
3936 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3938 struct io_accept *accept = &req->accept;
3940 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3941 return -EINVAL;
3942 if (sqe->ioprio || sqe->len || sqe->buf_index)
3943 return -EINVAL;
3945 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
3946 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3947 accept->flags = READ_ONCE(sqe->accept_flags);
3948 accept->nofile = rlimit(RLIMIT_NOFILE);
3949 return 0;
3952 static int __io_accept(struct io_kiocb *req, bool force_nonblock)
3954 struct io_accept *accept = &req->accept;
3955 unsigned file_flags;
3956 int ret;
3958 file_flags = force_nonblock ? O_NONBLOCK : 0;
3959 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
3960 accept->addr_len, accept->flags,
3961 accept->nofile);
3962 if (ret == -EAGAIN && force_nonblock)
3963 return -EAGAIN;
3964 if (ret == -ERESTARTSYS)
3965 ret = -EINTR;
3966 if (ret < 0)
3967 req_set_fail_links(req);
3968 io_cqring_add_event(req, ret);
3969 io_put_req(req);
3970 return 0;
3973 static void io_accept_finish(struct io_wq_work **workptr)
3975 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
3977 if (io_req_cancelled(req))
3978 return;
3979 __io_accept(req, false);
3980 io_steal_work(req, workptr);
3983 static int io_accept(struct io_kiocb *req, bool force_nonblock)
3985 int ret;
3987 ret = __io_accept(req, force_nonblock);
3988 if (ret == -EAGAIN && force_nonblock) {
3989 req->work.func = io_accept_finish;
3990 return -EAGAIN;
3992 return 0;
3995 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3997 struct io_connect *conn = &req->connect;
3998 struct io_async_ctx *io = req->io;
4000 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4001 return -EINVAL;
4002 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4003 return -EINVAL;
4005 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4006 conn->addr_len = READ_ONCE(sqe->addr2);
4008 if (!io)
4009 return 0;
4011 return move_addr_to_kernel(conn->addr, conn->addr_len,
4012 &io->connect.address);
4015 static int io_connect(struct io_kiocb *req, bool force_nonblock)
4017 struct io_async_ctx __io, *io;
4018 unsigned file_flags;
4019 int ret;
4021 if (req->io) {
4022 io = req->io;
4023 } else {
4024 ret = move_addr_to_kernel(req->connect.addr,
4025 req->connect.addr_len,
4026 &__io.connect.address);
4027 if (ret)
4028 goto out;
4029 io = &__io;
4032 file_flags = force_nonblock ? O_NONBLOCK : 0;
4034 ret = __sys_connect_file(req->file, &io->connect.address,
4035 req->connect.addr_len, file_flags);
4036 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4037 if (req->io)
4038 return -EAGAIN;
4039 if (io_alloc_async_ctx(req)) {
4040 ret = -ENOMEM;
4041 goto out;
4043 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
4044 return -EAGAIN;
4046 if (ret == -ERESTARTSYS)
4047 ret = -EINTR;
4048 out:
4049 if (ret < 0)
4050 req_set_fail_links(req);
4051 io_cqring_add_event(req, ret);
4052 io_put_req(req);
4053 return 0;
4055 #else /* !CONFIG_NET */
4056 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4058 return -EOPNOTSUPP;
4061 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock)
4063 return -EOPNOTSUPP;
4066 static int io_send(struct io_kiocb *req, bool force_nonblock)
4068 return -EOPNOTSUPP;
4071 static int io_recvmsg_prep(struct io_kiocb *req,
4072 const struct io_uring_sqe *sqe)
4074 return -EOPNOTSUPP;
4077 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock)
4079 return -EOPNOTSUPP;
4082 static int io_recv(struct io_kiocb *req, bool force_nonblock)
4084 return -EOPNOTSUPP;
4087 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4089 return -EOPNOTSUPP;
4092 static int io_accept(struct io_kiocb *req, bool force_nonblock)
4094 return -EOPNOTSUPP;
4097 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4099 return -EOPNOTSUPP;
4102 static int io_connect(struct io_kiocb *req, bool force_nonblock)
4104 return -EOPNOTSUPP;
4106 #endif /* CONFIG_NET */
4108 struct io_poll_table {
4109 struct poll_table_struct pt;
4110 struct io_kiocb *req;
4111 int error;
4114 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4115 __poll_t mask, task_work_func_t func)
4117 struct task_struct *tsk;
4118 int ret;
4120 /* for instances that support it check for an event match first: */
4121 if (mask && !(mask & poll->events))
4122 return 0;
4124 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4126 list_del_init(&poll->wait.entry);
4128 tsk = req->task;
4129 req->result = mask;
4130 init_task_work(&req->task_work, func);
4132 * If this fails, then the task is exiting. When a task exits, the
4133 * work gets canceled, so just cancel this request as well instead
4134 * of executing it. We can't safely execute it anyway, as we may not
4135 * have the needed state needed for it anyway.
4137 ret = task_work_add(tsk, &req->task_work, true);
4138 if (unlikely(ret)) {
4139 WRITE_ONCE(poll->canceled, true);
4140 tsk = io_wq_get_task(req->ctx->io_wq);
4141 task_work_add(tsk, &req->task_work, true);
4143 wake_up_process(tsk);
4144 return 1;
4147 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4148 __acquires(&req->ctx->completion_lock)
4150 struct io_ring_ctx *ctx = req->ctx;
4152 if (!req->result && !READ_ONCE(poll->canceled)) {
4153 struct poll_table_struct pt = { ._key = poll->events };
4155 req->result = vfs_poll(req->file, &pt) & poll->events;
4158 spin_lock_irq(&ctx->completion_lock);
4159 if (!req->result && !READ_ONCE(poll->canceled)) {
4160 add_wait_queue(poll->head, &poll->wait);
4161 return true;
4164 return false;
4167 static void io_poll_remove_double(struct io_kiocb *req)
4169 struct io_poll_iocb *poll = (struct io_poll_iocb *) req->io;
4171 lockdep_assert_held(&req->ctx->completion_lock);
4173 if (poll && poll->head) {
4174 struct wait_queue_head *head = poll->head;
4176 spin_lock(&head->lock);
4177 list_del_init(&poll->wait.entry);
4178 if (poll->wait.private)
4179 refcount_dec(&req->refs);
4180 poll->head = NULL;
4181 spin_unlock(&head->lock);
4185 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
4187 struct io_ring_ctx *ctx = req->ctx;
4189 io_poll_remove_double(req);
4190 req->poll.done = true;
4191 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
4192 io_commit_cqring(ctx);
4195 static void io_poll_task_handler(struct io_kiocb *req, struct io_kiocb **nxt)
4197 struct io_ring_ctx *ctx = req->ctx;
4199 if (io_poll_rewait(req, &req->poll)) {
4200 spin_unlock_irq(&ctx->completion_lock);
4201 return;
4204 hash_del(&req->hash_node);
4205 io_poll_complete(req, req->result, 0);
4206 req->flags |= REQ_F_COMP_LOCKED;
4207 io_put_req_find_next(req, nxt);
4208 spin_unlock_irq(&ctx->completion_lock);
4210 io_cqring_ev_posted(ctx);
4213 static void io_poll_task_func(struct callback_head *cb)
4215 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4216 struct io_kiocb *nxt = NULL;
4218 io_poll_task_handler(req, &nxt);
4219 if (nxt) {
4220 struct io_ring_ctx *ctx = nxt->ctx;
4222 mutex_lock(&ctx->uring_lock);
4223 __io_queue_sqe(nxt, NULL);
4224 mutex_unlock(&ctx->uring_lock);
4228 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4229 int sync, void *key)
4231 struct io_kiocb *req = wait->private;
4232 struct io_poll_iocb *poll = (struct io_poll_iocb *) req->io;
4233 __poll_t mask = key_to_poll(key);
4235 /* for instances that support it check for an event match first: */
4236 if (mask && !(mask & poll->events))
4237 return 0;
4239 if (req->poll.head) {
4240 bool done;
4242 spin_lock(&req->poll.head->lock);
4243 done = list_empty(&req->poll.wait.entry);
4244 if (!done)
4245 list_del_init(&req->poll.wait.entry);
4246 spin_unlock(&req->poll.head->lock);
4247 if (!done)
4248 __io_async_wake(req, poll, mask, io_poll_task_func);
4250 refcount_dec(&req->refs);
4251 return 1;
4254 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4255 wait_queue_func_t wake_func)
4257 poll->head = NULL;
4258 poll->done = false;
4259 poll->canceled = false;
4260 poll->events = events;
4261 INIT_LIST_HEAD(&poll->wait.entry);
4262 init_waitqueue_func_entry(&poll->wait, wake_func);
4265 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
4266 struct wait_queue_head *head)
4268 struct io_kiocb *req = pt->req;
4271 * If poll->head is already set, it's because the file being polled
4272 * uses multiple waitqueues for poll handling (eg one for read, one
4273 * for write). Setup a separate io_poll_iocb if this happens.
4275 if (unlikely(poll->head)) {
4276 /* already have a 2nd entry, fail a third attempt */
4277 if (req->io) {
4278 pt->error = -EINVAL;
4279 return;
4281 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
4282 if (!poll) {
4283 pt->error = -ENOMEM;
4284 return;
4286 io_init_poll_iocb(poll, req->poll.events, io_poll_double_wake);
4287 refcount_inc(&req->refs);
4288 poll->wait.private = req;
4289 req->io = (void *) poll;
4292 pt->error = 0;
4293 poll->head = head;
4294 add_wait_queue(head, &poll->wait);
4297 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
4298 struct poll_table_struct *p)
4300 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
4302 __io_queue_proc(&pt->req->apoll->poll, pt, head);
4305 static void io_sq_thread_drop_mm(struct io_ring_ctx *ctx)
4307 struct mm_struct *mm = current->mm;
4309 if (mm) {
4310 unuse_mm(mm);
4311 mmput(mm);
4315 static int io_sq_thread_acquire_mm(struct io_ring_ctx *ctx,
4316 struct io_kiocb *req)
4318 if (io_op_defs[req->opcode].needs_mm && !current->mm) {
4319 if (unlikely(!mmget_not_zero(ctx->sqo_mm)))
4320 return -EFAULT;
4321 use_mm(ctx->sqo_mm);
4324 return 0;
4327 static void io_async_task_func(struct callback_head *cb)
4329 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4330 struct async_poll *apoll = req->apoll;
4331 struct io_ring_ctx *ctx = req->ctx;
4332 bool canceled;
4334 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
4336 if (io_poll_rewait(req, &apoll->poll)) {
4337 spin_unlock_irq(&ctx->completion_lock);
4338 return;
4341 if (hash_hashed(&req->hash_node))
4342 hash_del(&req->hash_node);
4344 canceled = READ_ONCE(apoll->poll.canceled);
4345 if (canceled) {
4346 io_cqring_fill_event(req, -ECANCELED);
4347 io_commit_cqring(ctx);
4350 spin_unlock_irq(&ctx->completion_lock);
4352 /* restore ->work in case we need to retry again */
4353 memcpy(&req->work, &apoll->work, sizeof(req->work));
4355 if (canceled) {
4356 kfree(apoll);
4357 io_cqring_ev_posted(ctx);
4358 end_req:
4359 req_set_fail_links(req);
4360 io_double_put_req(req);
4361 return;
4364 __set_current_state(TASK_RUNNING);
4365 if (io_sq_thread_acquire_mm(ctx, req)) {
4366 io_cqring_add_event(req, -EFAULT);
4367 goto end_req;
4369 mutex_lock(&ctx->uring_lock);
4370 __io_queue_sqe(req, NULL);
4371 mutex_unlock(&ctx->uring_lock);
4373 kfree(apoll);
4376 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
4377 void *key)
4379 struct io_kiocb *req = wait->private;
4380 struct io_poll_iocb *poll = &req->apoll->poll;
4382 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
4383 key_to_poll(key));
4385 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
4388 static void io_poll_req_insert(struct io_kiocb *req)
4390 struct io_ring_ctx *ctx = req->ctx;
4391 struct hlist_head *list;
4393 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
4394 hlist_add_head(&req->hash_node, list);
4397 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
4398 struct io_poll_iocb *poll,
4399 struct io_poll_table *ipt, __poll_t mask,
4400 wait_queue_func_t wake_func)
4401 __acquires(&ctx->completion_lock)
4403 struct io_ring_ctx *ctx = req->ctx;
4404 bool cancel = false;
4406 poll->file = req->file;
4407 io_init_poll_iocb(poll, mask, wake_func);
4408 poll->wait.private = req;
4410 ipt->pt._key = mask;
4411 ipt->req = req;
4412 ipt->error = -EINVAL;
4414 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
4416 spin_lock_irq(&ctx->completion_lock);
4417 if (likely(poll->head)) {
4418 spin_lock(&poll->head->lock);
4419 if (unlikely(list_empty(&poll->wait.entry))) {
4420 if (ipt->error)
4421 cancel = true;
4422 ipt->error = 0;
4423 mask = 0;
4425 if (mask || ipt->error)
4426 list_del_init(&poll->wait.entry);
4427 else if (cancel)
4428 WRITE_ONCE(poll->canceled, true);
4429 else if (!poll->done) /* actually waiting for an event */
4430 io_poll_req_insert(req);
4431 spin_unlock(&poll->head->lock);
4434 return mask;
4437 static bool io_arm_poll_handler(struct io_kiocb *req)
4439 const struct io_op_def *def = &io_op_defs[req->opcode];
4440 struct io_ring_ctx *ctx = req->ctx;
4441 struct async_poll *apoll;
4442 struct io_poll_table ipt;
4443 __poll_t mask, ret;
4444 bool had_io;
4446 if (!req->file || !file_can_poll(req->file))
4447 return false;
4448 if (req->flags & (REQ_F_MUST_PUNT | REQ_F_POLLED))
4449 return false;
4450 if (!def->pollin && !def->pollout)
4451 return false;
4453 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
4454 if (unlikely(!apoll))
4455 return false;
4457 req->flags |= REQ_F_POLLED;
4458 memcpy(&apoll->work, &req->work, sizeof(req->work));
4459 had_io = req->io != NULL;
4461 get_task_struct(current);
4462 req->task = current;
4463 req->apoll = apoll;
4464 INIT_HLIST_NODE(&req->hash_node);
4466 mask = 0;
4467 if (def->pollin)
4468 mask |= POLLIN | POLLRDNORM;
4469 if (def->pollout)
4470 mask |= POLLOUT | POLLWRNORM;
4471 mask |= POLLERR | POLLPRI;
4473 ipt.pt._qproc = io_async_queue_proc;
4475 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
4476 io_async_wake);
4477 if (ret) {
4478 ipt.error = 0;
4479 /* only remove double add if we did it here */
4480 if (!had_io)
4481 io_poll_remove_double(req);
4482 spin_unlock_irq(&ctx->completion_lock);
4483 memcpy(&req->work, &apoll->work, sizeof(req->work));
4484 kfree(apoll);
4485 return false;
4487 spin_unlock_irq(&ctx->completion_lock);
4488 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
4489 apoll->poll.events);
4490 return true;
4493 static bool __io_poll_remove_one(struct io_kiocb *req,
4494 struct io_poll_iocb *poll)
4496 bool do_complete = false;
4498 spin_lock(&poll->head->lock);
4499 WRITE_ONCE(poll->canceled, true);
4500 if (!list_empty(&poll->wait.entry)) {
4501 list_del_init(&poll->wait.entry);
4502 do_complete = true;
4504 spin_unlock(&poll->head->lock);
4505 hash_del(&req->hash_node);
4506 return do_complete;
4509 static bool io_poll_remove_one(struct io_kiocb *req)
4511 bool do_complete;
4513 if (req->opcode == IORING_OP_POLL_ADD) {
4514 io_poll_remove_double(req);
4515 do_complete = __io_poll_remove_one(req, &req->poll);
4516 } else {
4517 struct async_poll *apoll = req->apoll;
4519 /* non-poll requests have submit ref still */
4520 do_complete = __io_poll_remove_one(req, &apoll->poll);
4521 if (do_complete) {
4522 io_put_req(req);
4524 * restore ->work because we will call
4525 * io_req_work_drop_env below when dropping the
4526 * final reference.
4528 memcpy(&req->work, &apoll->work, sizeof(req->work));
4529 kfree(apoll);
4533 if (do_complete) {
4534 io_cqring_fill_event(req, -ECANCELED);
4535 io_commit_cqring(req->ctx);
4536 req->flags |= REQ_F_COMP_LOCKED;
4537 io_put_req(req);
4540 return do_complete;
4543 static void io_poll_remove_all(struct io_ring_ctx *ctx)
4545 struct hlist_node *tmp;
4546 struct io_kiocb *req;
4547 int posted = 0, i;
4549 spin_lock_irq(&ctx->completion_lock);
4550 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
4551 struct hlist_head *list;
4553 list = &ctx->cancel_hash[i];
4554 hlist_for_each_entry_safe(req, tmp, list, hash_node)
4555 posted += io_poll_remove_one(req);
4557 spin_unlock_irq(&ctx->completion_lock);
4559 if (posted)
4560 io_cqring_ev_posted(ctx);
4563 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
4565 struct hlist_head *list;
4566 struct io_kiocb *req;
4568 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
4569 hlist_for_each_entry(req, list, hash_node) {
4570 if (sqe_addr != req->user_data)
4571 continue;
4572 if (io_poll_remove_one(req))
4573 return 0;
4574 return -EALREADY;
4577 return -ENOENT;
4580 static int io_poll_remove_prep(struct io_kiocb *req,
4581 const struct io_uring_sqe *sqe)
4583 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4584 return -EINVAL;
4585 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
4586 sqe->poll_events)
4587 return -EINVAL;
4589 req->poll.addr = READ_ONCE(sqe->addr);
4590 return 0;
4594 * Find a running poll command that matches one specified in sqe->addr,
4595 * and remove it if found.
4597 static int io_poll_remove(struct io_kiocb *req)
4599 struct io_ring_ctx *ctx = req->ctx;
4600 u64 addr;
4601 int ret;
4603 addr = req->poll.addr;
4604 spin_lock_irq(&ctx->completion_lock);
4605 ret = io_poll_cancel(ctx, addr);
4606 spin_unlock_irq(&ctx->completion_lock);
4608 io_cqring_add_event(req, ret);
4609 if (ret < 0)
4610 req_set_fail_links(req);
4611 io_put_req(req);
4612 return 0;
4615 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
4616 void *key)
4618 struct io_kiocb *req = wait->private;
4619 struct io_poll_iocb *poll = &req->poll;
4621 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
4624 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
4625 struct poll_table_struct *p)
4627 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
4629 __io_queue_proc(&pt->req->poll, pt, head);
4632 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4634 struct io_poll_iocb *poll = &req->poll;
4635 u16 events;
4637 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4638 return -EINVAL;
4639 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
4640 return -EINVAL;
4641 if (!poll->file)
4642 return -EBADF;
4644 events = READ_ONCE(sqe->poll_events);
4645 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
4647 get_task_struct(current);
4648 req->task = current;
4649 return 0;
4652 static int io_poll_add(struct io_kiocb *req)
4654 struct io_poll_iocb *poll = &req->poll;
4655 struct io_ring_ctx *ctx = req->ctx;
4656 struct io_poll_table ipt;
4657 __poll_t mask;
4659 INIT_HLIST_NODE(&req->hash_node);
4660 INIT_LIST_HEAD(&req->list);
4661 ipt.pt._qproc = io_poll_queue_proc;
4663 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
4664 io_poll_wake);
4666 if (mask) { /* no async, we'd stolen it */
4667 ipt.error = 0;
4668 io_poll_complete(req, mask, 0);
4670 spin_unlock_irq(&ctx->completion_lock);
4672 if (mask) {
4673 io_cqring_ev_posted(ctx);
4674 io_put_req(req);
4676 return ipt.error;
4679 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
4681 struct io_timeout_data *data = container_of(timer,
4682 struct io_timeout_data, timer);
4683 struct io_kiocb *req = data->req;
4684 struct io_ring_ctx *ctx = req->ctx;
4685 unsigned long flags;
4687 atomic_inc(&ctx->cq_timeouts);
4689 spin_lock_irqsave(&ctx->completion_lock, flags);
4691 * We could be racing with timeout deletion. If the list is empty,
4692 * then timeout lookup already found it and will be handling it.
4694 if (!list_empty(&req->list)) {
4695 struct io_kiocb *prev;
4698 * Adjust the reqs sequence before the current one because it
4699 * will consume a slot in the cq_ring and the cq_tail
4700 * pointer will be increased, otherwise other timeout reqs may
4701 * return in advance without waiting for enough wait_nr.
4703 prev = req;
4704 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
4705 prev->sequence++;
4706 list_del_init(&req->list);
4709 io_cqring_fill_event(req, -ETIME);
4710 io_commit_cqring(ctx);
4711 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4713 io_cqring_ev_posted(ctx);
4714 req_set_fail_links(req);
4715 io_put_req(req);
4716 return HRTIMER_NORESTART;
4719 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
4721 struct io_kiocb *req;
4722 int ret = -ENOENT;
4724 list_for_each_entry(req, &ctx->timeout_list, list) {
4725 if (user_data == req->user_data) {
4726 list_del_init(&req->list);
4727 ret = 0;
4728 break;
4732 if (ret == -ENOENT)
4733 return ret;
4735 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
4736 if (ret == -1)
4737 return -EALREADY;
4739 req_set_fail_links(req);
4740 io_cqring_fill_event(req, -ECANCELED);
4741 io_put_req(req);
4742 return 0;
4745 static int io_timeout_remove_prep(struct io_kiocb *req,
4746 const struct io_uring_sqe *sqe)
4748 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4749 return -EINVAL;
4750 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
4751 return -EINVAL;
4753 req->timeout.addr = READ_ONCE(sqe->addr);
4754 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
4755 if (req->timeout.flags)
4756 return -EINVAL;
4758 return 0;
4762 * Remove or update an existing timeout command
4764 static int io_timeout_remove(struct io_kiocb *req)
4766 struct io_ring_ctx *ctx = req->ctx;
4767 int ret;
4769 spin_lock_irq(&ctx->completion_lock);
4770 ret = io_timeout_cancel(ctx, req->timeout.addr);
4772 io_cqring_fill_event(req, ret);
4773 io_commit_cqring(ctx);
4774 spin_unlock_irq(&ctx->completion_lock);
4775 io_cqring_ev_posted(ctx);
4776 if (ret < 0)
4777 req_set_fail_links(req);
4778 io_put_req(req);
4779 return 0;
4782 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
4783 bool is_timeout_link)
4785 struct io_timeout_data *data;
4786 unsigned flags;
4788 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4789 return -EINVAL;
4790 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
4791 return -EINVAL;
4792 if (sqe->off && is_timeout_link)
4793 return -EINVAL;
4794 flags = READ_ONCE(sqe->timeout_flags);
4795 if (flags & ~IORING_TIMEOUT_ABS)
4796 return -EINVAL;
4798 req->timeout.count = READ_ONCE(sqe->off);
4800 if (!req->io && io_alloc_async_ctx(req))
4801 return -ENOMEM;
4803 data = &req->io->timeout;
4804 data->req = req;
4805 req->flags |= REQ_F_TIMEOUT;
4807 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
4808 return -EFAULT;
4810 if (flags & IORING_TIMEOUT_ABS)
4811 data->mode = HRTIMER_MODE_ABS;
4812 else
4813 data->mode = HRTIMER_MODE_REL;
4815 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
4816 return 0;
4819 static int io_timeout(struct io_kiocb *req)
4821 struct io_ring_ctx *ctx = req->ctx;
4822 struct io_timeout_data *data;
4823 struct list_head *entry;
4824 unsigned span = 0;
4825 u32 count = req->timeout.count;
4826 u32 seq = req->sequence;
4828 data = &req->io->timeout;
4831 * sqe->off holds how many events that need to occur for this
4832 * timeout event to be satisfied. If it isn't set, then this is
4833 * a pure timeout request, sequence isn't used.
4835 if (!count) {
4836 req->flags |= REQ_F_TIMEOUT_NOSEQ;
4837 spin_lock_irq(&ctx->completion_lock);
4838 entry = ctx->timeout_list.prev;
4839 goto add;
4842 req->sequence = seq + count;
4845 * Insertion sort, ensuring the first entry in the list is always
4846 * the one we need first.
4848 spin_lock_irq(&ctx->completion_lock);
4849 list_for_each_prev(entry, &ctx->timeout_list) {
4850 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
4851 unsigned nxt_seq;
4852 long long tmp, tmp_nxt;
4853 u32 nxt_offset = nxt->timeout.count;
4855 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
4856 continue;
4859 * Since seq + count can overflow, use type long
4860 * long to store it.
4862 tmp = (long long)seq + count;
4863 nxt_seq = nxt->sequence - nxt_offset;
4864 tmp_nxt = (long long)nxt_seq + nxt_offset;
4867 * cached_sq_head may overflow, and it will never overflow twice
4868 * once there is some timeout req still be valid.
4870 if (seq < nxt_seq)
4871 tmp += UINT_MAX;
4873 if (tmp > tmp_nxt)
4874 break;
4877 * Sequence of reqs after the insert one and itself should
4878 * be adjusted because each timeout req consumes a slot.
4880 span++;
4881 nxt->sequence++;
4883 req->sequence -= span;
4884 add:
4885 list_add(&req->list, entry);
4886 data->timer.function = io_timeout_fn;
4887 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
4888 spin_unlock_irq(&ctx->completion_lock);
4889 return 0;
4892 static bool io_cancel_cb(struct io_wq_work *work, void *data)
4894 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4896 return req->user_data == (unsigned long) data;
4899 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
4901 enum io_wq_cancel cancel_ret;
4902 int ret = 0;
4904 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
4905 switch (cancel_ret) {
4906 case IO_WQ_CANCEL_OK:
4907 ret = 0;
4908 break;
4909 case IO_WQ_CANCEL_RUNNING:
4910 ret = -EALREADY;
4911 break;
4912 case IO_WQ_CANCEL_NOTFOUND:
4913 ret = -ENOENT;
4914 break;
4917 return ret;
4920 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
4921 struct io_kiocb *req, __u64 sqe_addr,
4922 int success_ret)
4924 unsigned long flags;
4925 int ret;
4927 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
4928 if (ret != -ENOENT) {
4929 spin_lock_irqsave(&ctx->completion_lock, flags);
4930 goto done;
4933 spin_lock_irqsave(&ctx->completion_lock, flags);
4934 ret = io_timeout_cancel(ctx, sqe_addr);
4935 if (ret != -ENOENT)
4936 goto done;
4937 ret = io_poll_cancel(ctx, sqe_addr);
4938 done:
4939 if (!ret)
4940 ret = success_ret;
4941 io_cqring_fill_event(req, ret);
4942 io_commit_cqring(ctx);
4943 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4944 io_cqring_ev_posted(ctx);
4946 if (ret < 0)
4947 req_set_fail_links(req);
4948 io_put_req(req);
4951 static int io_async_cancel_prep(struct io_kiocb *req,
4952 const struct io_uring_sqe *sqe)
4954 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4955 return -EINVAL;
4956 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
4957 sqe->cancel_flags)
4958 return -EINVAL;
4960 req->cancel.addr = READ_ONCE(sqe->addr);
4961 return 0;
4964 static int io_async_cancel(struct io_kiocb *req)
4966 struct io_ring_ctx *ctx = req->ctx;
4968 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
4969 return 0;
4972 static int io_files_update_prep(struct io_kiocb *req,
4973 const struct io_uring_sqe *sqe)
4975 if (sqe->flags || sqe->ioprio || sqe->rw_flags)
4976 return -EINVAL;
4978 req->files_update.offset = READ_ONCE(sqe->off);
4979 req->files_update.nr_args = READ_ONCE(sqe->len);
4980 if (!req->files_update.nr_args)
4981 return -EINVAL;
4982 req->files_update.arg = READ_ONCE(sqe->addr);
4983 return 0;
4986 static int io_files_update(struct io_kiocb *req, bool force_nonblock)
4988 struct io_ring_ctx *ctx = req->ctx;
4989 struct io_uring_files_update up;
4990 int ret;
4992 if (force_nonblock)
4993 return -EAGAIN;
4995 up.offset = req->files_update.offset;
4996 up.fds = req->files_update.arg;
4998 mutex_lock(&ctx->uring_lock);
4999 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
5000 mutex_unlock(&ctx->uring_lock);
5002 if (ret < 0)
5003 req_set_fail_links(req);
5004 io_cqring_add_event(req, ret);
5005 io_put_req(req);
5006 return 0;
5009 static int io_req_defer_prep(struct io_kiocb *req,
5010 const struct io_uring_sqe *sqe)
5012 ssize_t ret = 0;
5014 if (!sqe)
5015 return 0;
5017 if (io_op_defs[req->opcode].file_table) {
5018 ret = io_grab_files(req);
5019 if (unlikely(ret))
5020 return ret;
5023 io_req_work_grab_env(req, &io_op_defs[req->opcode]);
5025 switch (req->opcode) {
5026 case IORING_OP_NOP:
5027 break;
5028 case IORING_OP_READV:
5029 case IORING_OP_READ_FIXED:
5030 case IORING_OP_READ:
5031 ret = io_read_prep(req, sqe, true);
5032 break;
5033 case IORING_OP_WRITEV:
5034 case IORING_OP_WRITE_FIXED:
5035 case IORING_OP_WRITE:
5036 ret = io_write_prep(req, sqe, true);
5037 break;
5038 case IORING_OP_POLL_ADD:
5039 ret = io_poll_add_prep(req, sqe);
5040 break;
5041 case IORING_OP_POLL_REMOVE:
5042 ret = io_poll_remove_prep(req, sqe);
5043 break;
5044 case IORING_OP_FSYNC:
5045 ret = io_prep_fsync(req, sqe);
5046 break;
5047 case IORING_OP_SYNC_FILE_RANGE:
5048 ret = io_prep_sfr(req, sqe);
5049 break;
5050 case IORING_OP_SENDMSG:
5051 case IORING_OP_SEND:
5052 ret = io_sendmsg_prep(req, sqe);
5053 break;
5054 case IORING_OP_RECVMSG:
5055 case IORING_OP_RECV:
5056 ret = io_recvmsg_prep(req, sqe);
5057 break;
5058 case IORING_OP_CONNECT:
5059 ret = io_connect_prep(req, sqe);
5060 break;
5061 case IORING_OP_TIMEOUT:
5062 ret = io_timeout_prep(req, sqe, false);
5063 break;
5064 case IORING_OP_TIMEOUT_REMOVE:
5065 ret = io_timeout_remove_prep(req, sqe);
5066 break;
5067 case IORING_OP_ASYNC_CANCEL:
5068 ret = io_async_cancel_prep(req, sqe);
5069 break;
5070 case IORING_OP_LINK_TIMEOUT:
5071 ret = io_timeout_prep(req, sqe, true);
5072 break;
5073 case IORING_OP_ACCEPT:
5074 ret = io_accept_prep(req, sqe);
5075 break;
5076 case IORING_OP_FALLOCATE:
5077 ret = io_fallocate_prep(req, sqe);
5078 break;
5079 case IORING_OP_OPENAT:
5080 ret = io_openat_prep(req, sqe);
5081 break;
5082 case IORING_OP_CLOSE:
5083 ret = io_close_prep(req, sqe);
5084 break;
5085 case IORING_OP_FILES_UPDATE:
5086 ret = io_files_update_prep(req, sqe);
5087 break;
5088 case IORING_OP_STATX:
5089 ret = io_statx_prep(req, sqe);
5090 break;
5091 case IORING_OP_FADVISE:
5092 ret = io_fadvise_prep(req, sqe);
5093 break;
5094 case IORING_OP_MADVISE:
5095 ret = io_madvise_prep(req, sqe);
5096 break;
5097 case IORING_OP_OPENAT2:
5098 ret = io_openat2_prep(req, sqe);
5099 break;
5100 case IORING_OP_EPOLL_CTL:
5101 ret = io_epoll_ctl_prep(req, sqe);
5102 break;
5103 case IORING_OP_SPLICE:
5104 ret = io_splice_prep(req, sqe);
5105 break;
5106 case IORING_OP_PROVIDE_BUFFERS:
5107 ret = io_provide_buffers_prep(req, sqe);
5108 break;
5109 case IORING_OP_REMOVE_BUFFERS:
5110 ret = io_remove_buffers_prep(req, sqe);
5111 break;
5112 default:
5113 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5114 req->opcode);
5115 ret = -EINVAL;
5116 break;
5119 return ret;
5122 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5124 struct io_ring_ctx *ctx = req->ctx;
5125 int ret;
5127 /* Still need defer if there is pending req in defer list. */
5128 if (!req_need_defer(req) && list_empty_careful(&ctx->defer_list))
5129 return 0;
5131 if (!req->io) {
5132 if (io_alloc_async_ctx(req))
5133 return -EAGAIN;
5134 ret = io_req_defer_prep(req, sqe);
5135 if (ret < 0)
5136 return ret;
5139 spin_lock_irq(&ctx->completion_lock);
5140 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
5141 spin_unlock_irq(&ctx->completion_lock);
5142 return 0;
5145 trace_io_uring_defer(ctx, req, req->user_data);
5146 list_add_tail(&req->list, &ctx->defer_list);
5147 spin_unlock_irq(&ctx->completion_lock);
5148 return -EIOCBQUEUED;
5151 static void io_cleanup_req(struct io_kiocb *req)
5153 struct io_async_ctx *io = req->io;
5155 switch (req->opcode) {
5156 case IORING_OP_READV:
5157 case IORING_OP_READ_FIXED:
5158 case IORING_OP_READ:
5159 if (req->flags & REQ_F_BUFFER_SELECTED)
5160 kfree((void *)(unsigned long)req->rw.addr);
5161 /* fallthrough */
5162 case IORING_OP_WRITEV:
5163 case IORING_OP_WRITE_FIXED:
5164 case IORING_OP_WRITE:
5165 if (io->rw.iov != io->rw.fast_iov)
5166 kfree(io->rw.iov);
5167 break;
5168 case IORING_OP_RECVMSG:
5169 if (req->flags & REQ_F_BUFFER_SELECTED)
5170 kfree(req->sr_msg.kbuf);
5171 /* fallthrough */
5172 case IORING_OP_SENDMSG:
5173 if (io->msg.iov != io->msg.fast_iov)
5174 kfree(io->msg.iov);
5175 break;
5176 case IORING_OP_RECV:
5177 if (req->flags & REQ_F_BUFFER_SELECTED)
5178 kfree(req->sr_msg.kbuf);
5179 break;
5180 case IORING_OP_OPENAT:
5181 case IORING_OP_OPENAT2:
5182 case IORING_OP_STATX:
5183 putname(req->open.filename);
5184 break;
5185 case IORING_OP_SPLICE:
5186 io_put_file(req, req->splice.file_in,
5187 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
5188 break;
5191 req->flags &= ~REQ_F_NEED_CLEANUP;
5194 static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5195 bool force_nonblock)
5197 struct io_ring_ctx *ctx = req->ctx;
5198 int ret;
5200 switch (req->opcode) {
5201 case IORING_OP_NOP:
5202 ret = io_nop(req);
5203 break;
5204 case IORING_OP_READV:
5205 case IORING_OP_READ_FIXED:
5206 case IORING_OP_READ:
5207 if (sqe) {
5208 ret = io_read_prep(req, sqe, force_nonblock);
5209 if (ret < 0)
5210 break;
5212 ret = io_read(req, force_nonblock);
5213 break;
5214 case IORING_OP_WRITEV:
5215 case IORING_OP_WRITE_FIXED:
5216 case IORING_OP_WRITE:
5217 if (sqe) {
5218 ret = io_write_prep(req, sqe, force_nonblock);
5219 if (ret < 0)
5220 break;
5222 ret = io_write(req, force_nonblock);
5223 break;
5224 case IORING_OP_FSYNC:
5225 if (sqe) {
5226 ret = io_prep_fsync(req, sqe);
5227 if (ret < 0)
5228 break;
5230 ret = io_fsync(req, force_nonblock);
5231 break;
5232 case IORING_OP_POLL_ADD:
5233 if (sqe) {
5234 ret = io_poll_add_prep(req, sqe);
5235 if (ret)
5236 break;
5238 ret = io_poll_add(req);
5239 break;
5240 case IORING_OP_POLL_REMOVE:
5241 if (sqe) {
5242 ret = io_poll_remove_prep(req, sqe);
5243 if (ret < 0)
5244 break;
5246 ret = io_poll_remove(req);
5247 break;
5248 case IORING_OP_SYNC_FILE_RANGE:
5249 if (sqe) {
5250 ret = io_prep_sfr(req, sqe);
5251 if (ret < 0)
5252 break;
5254 ret = io_sync_file_range(req, force_nonblock);
5255 break;
5256 case IORING_OP_SENDMSG:
5257 case IORING_OP_SEND:
5258 if (sqe) {
5259 ret = io_sendmsg_prep(req, sqe);
5260 if (ret < 0)
5261 break;
5263 if (req->opcode == IORING_OP_SENDMSG)
5264 ret = io_sendmsg(req, force_nonblock);
5265 else
5266 ret = io_send(req, force_nonblock);
5267 break;
5268 case IORING_OP_RECVMSG:
5269 case IORING_OP_RECV:
5270 if (sqe) {
5271 ret = io_recvmsg_prep(req, sqe);
5272 if (ret)
5273 break;
5275 if (req->opcode == IORING_OP_RECVMSG)
5276 ret = io_recvmsg(req, force_nonblock);
5277 else
5278 ret = io_recv(req, force_nonblock);
5279 break;
5280 case IORING_OP_TIMEOUT:
5281 if (sqe) {
5282 ret = io_timeout_prep(req, sqe, false);
5283 if (ret)
5284 break;
5286 ret = io_timeout(req);
5287 break;
5288 case IORING_OP_TIMEOUT_REMOVE:
5289 if (sqe) {
5290 ret = io_timeout_remove_prep(req, sqe);
5291 if (ret)
5292 break;
5294 ret = io_timeout_remove(req);
5295 break;
5296 case IORING_OP_ACCEPT:
5297 if (sqe) {
5298 ret = io_accept_prep(req, sqe);
5299 if (ret)
5300 break;
5302 ret = io_accept(req, force_nonblock);
5303 break;
5304 case IORING_OP_CONNECT:
5305 if (sqe) {
5306 ret = io_connect_prep(req, sqe);
5307 if (ret)
5308 break;
5310 ret = io_connect(req, force_nonblock);
5311 break;
5312 case IORING_OP_ASYNC_CANCEL:
5313 if (sqe) {
5314 ret = io_async_cancel_prep(req, sqe);
5315 if (ret)
5316 break;
5318 ret = io_async_cancel(req);
5319 break;
5320 case IORING_OP_FALLOCATE:
5321 if (sqe) {
5322 ret = io_fallocate_prep(req, sqe);
5323 if (ret)
5324 break;
5326 ret = io_fallocate(req, force_nonblock);
5327 break;
5328 case IORING_OP_OPENAT:
5329 if (sqe) {
5330 ret = io_openat_prep(req, sqe);
5331 if (ret)
5332 break;
5334 ret = io_openat(req, force_nonblock);
5335 break;
5336 case IORING_OP_CLOSE:
5337 if (sqe) {
5338 ret = io_close_prep(req, sqe);
5339 if (ret)
5340 break;
5342 ret = io_close(req, force_nonblock);
5343 break;
5344 case IORING_OP_FILES_UPDATE:
5345 if (sqe) {
5346 ret = io_files_update_prep(req, sqe);
5347 if (ret)
5348 break;
5350 ret = io_files_update(req, force_nonblock);
5351 break;
5352 case IORING_OP_STATX:
5353 if (sqe) {
5354 ret = io_statx_prep(req, sqe);
5355 if (ret)
5356 break;
5358 ret = io_statx(req, force_nonblock);
5359 break;
5360 case IORING_OP_FADVISE:
5361 if (sqe) {
5362 ret = io_fadvise_prep(req, sqe);
5363 if (ret)
5364 break;
5366 ret = io_fadvise(req, force_nonblock);
5367 break;
5368 case IORING_OP_MADVISE:
5369 if (sqe) {
5370 ret = io_madvise_prep(req, sqe);
5371 if (ret)
5372 break;
5374 ret = io_madvise(req, force_nonblock);
5375 break;
5376 case IORING_OP_OPENAT2:
5377 if (sqe) {
5378 ret = io_openat2_prep(req, sqe);
5379 if (ret)
5380 break;
5382 ret = io_openat2(req, force_nonblock);
5383 break;
5384 case IORING_OP_EPOLL_CTL:
5385 if (sqe) {
5386 ret = io_epoll_ctl_prep(req, sqe);
5387 if (ret)
5388 break;
5390 ret = io_epoll_ctl(req, force_nonblock);
5391 break;
5392 case IORING_OP_SPLICE:
5393 if (sqe) {
5394 ret = io_splice_prep(req, sqe);
5395 if (ret < 0)
5396 break;
5398 ret = io_splice(req, force_nonblock);
5399 break;
5400 case IORING_OP_PROVIDE_BUFFERS:
5401 if (sqe) {
5402 ret = io_provide_buffers_prep(req, sqe);
5403 if (ret)
5404 break;
5406 ret = io_provide_buffers(req, force_nonblock);
5407 break;
5408 case IORING_OP_REMOVE_BUFFERS:
5409 if (sqe) {
5410 ret = io_remove_buffers_prep(req, sqe);
5411 if (ret)
5412 break;
5414 ret = io_remove_buffers(req, force_nonblock);
5415 break;
5416 default:
5417 ret = -EINVAL;
5418 break;
5421 if (ret)
5422 return ret;
5424 /* If the op doesn't have a file, we're not polling for it */
5425 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
5426 const bool in_async = io_wq_current_is_worker();
5428 if (req->result == -EAGAIN)
5429 return -EAGAIN;
5431 /* workqueue context doesn't hold uring_lock, grab it now */
5432 if (in_async)
5433 mutex_lock(&ctx->uring_lock);
5435 io_iopoll_req_issued(req);
5437 if (in_async)
5438 mutex_unlock(&ctx->uring_lock);
5441 return 0;
5444 static void io_wq_submit_work(struct io_wq_work **workptr)
5446 struct io_wq_work *work = *workptr;
5447 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5448 int ret = 0;
5450 /* if NO_CANCEL is set, we must still run the work */
5451 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
5452 IO_WQ_WORK_CANCEL) {
5453 ret = -ECANCELED;
5456 if (!ret) {
5457 do {
5458 ret = io_issue_sqe(req, NULL, false);
5460 * We can get EAGAIN for polled IO even though we're
5461 * forcing a sync submission from here, since we can't
5462 * wait for request slots on the block side.
5464 if (ret != -EAGAIN)
5465 break;
5466 cond_resched();
5467 } while (1);
5470 if (ret) {
5471 req_set_fail_links(req);
5472 io_cqring_add_event(req, ret);
5473 io_put_req(req);
5476 io_steal_work(req, workptr);
5479 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
5480 int index)
5482 struct fixed_file_table *table;
5484 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
5485 return table->files[index & IORING_FILE_TABLE_MASK];;
5488 static int io_file_get(struct io_submit_state *state, struct io_kiocb *req,
5489 int fd, struct file **out_file, bool fixed)
5491 struct io_ring_ctx *ctx = req->ctx;
5492 struct file *file;
5494 if (fixed) {
5495 if (unlikely(!ctx->file_data ||
5496 (unsigned) fd >= ctx->nr_user_files))
5497 return -EBADF;
5498 fd = array_index_nospec(fd, ctx->nr_user_files);
5499 file = io_file_from_index(ctx, fd);
5500 if (!file)
5501 return -EBADF;
5502 req->fixed_file_refs = ctx->file_data->cur_refs;
5503 percpu_ref_get(req->fixed_file_refs);
5504 } else {
5505 trace_io_uring_file_get(ctx, fd);
5506 file = __io_file_get(state, fd);
5507 if (unlikely(!file))
5508 return -EBADF;
5511 *out_file = file;
5512 return 0;
5515 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
5516 int fd)
5518 bool fixed;
5520 fixed = (req->flags & REQ_F_FIXED_FILE) != 0;
5521 if (unlikely(!fixed && req->needs_fixed_file))
5522 return -EBADF;
5524 return io_file_get(state, req, fd, &req->file, fixed);
5527 static int io_grab_files(struct io_kiocb *req)
5529 int ret = -EBADF;
5530 struct io_ring_ctx *ctx = req->ctx;
5532 if (req->work.files || (req->flags & REQ_F_NO_FILE_TABLE))
5533 return 0;
5534 if (!ctx->ring_file)
5535 return -EBADF;
5537 rcu_read_lock();
5538 spin_lock_irq(&ctx->inflight_lock);
5540 * We use the f_ops->flush() handler to ensure that we can flush
5541 * out work accessing these files if the fd is closed. Check if
5542 * the fd has changed since we started down this path, and disallow
5543 * this operation if it has.
5545 if (fcheck(ctx->ring_fd) == ctx->ring_file) {
5546 list_add(&req->inflight_entry, &ctx->inflight_list);
5547 req->flags |= REQ_F_INFLIGHT;
5548 req->work.files = current->files;
5549 ret = 0;
5551 spin_unlock_irq(&ctx->inflight_lock);
5552 rcu_read_unlock();
5554 return ret;
5557 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
5559 struct io_timeout_data *data = container_of(timer,
5560 struct io_timeout_data, timer);
5561 struct io_kiocb *req = data->req;
5562 struct io_ring_ctx *ctx = req->ctx;
5563 struct io_kiocb *prev = NULL;
5564 unsigned long flags;
5566 spin_lock_irqsave(&ctx->completion_lock, flags);
5569 * We don't expect the list to be empty, that will only happen if we
5570 * race with the completion of the linked work.
5572 if (!list_empty(&req->link_list)) {
5573 prev = list_entry(req->link_list.prev, struct io_kiocb,
5574 link_list);
5575 if (refcount_inc_not_zero(&prev->refs)) {
5576 list_del_init(&req->link_list);
5577 prev->flags &= ~REQ_F_LINK_TIMEOUT;
5578 } else
5579 prev = NULL;
5582 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5584 if (prev) {
5585 req_set_fail_links(prev);
5586 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
5587 io_put_req(prev);
5588 } else {
5589 io_cqring_add_event(req, -ETIME);
5590 io_put_req(req);
5592 return HRTIMER_NORESTART;
5595 static void io_queue_linked_timeout(struct io_kiocb *req)
5597 struct io_ring_ctx *ctx = req->ctx;
5600 * If the list is now empty, then our linked request finished before
5601 * we got a chance to setup the timer
5603 spin_lock_irq(&ctx->completion_lock);
5604 if (!list_empty(&req->link_list)) {
5605 struct io_timeout_data *data = &req->io->timeout;
5607 data->timer.function = io_link_timeout_fn;
5608 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
5609 data->mode);
5611 spin_unlock_irq(&ctx->completion_lock);
5613 /* drop submission reference */
5614 io_put_req(req);
5617 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
5619 struct io_kiocb *nxt;
5621 if (!(req->flags & REQ_F_LINK_HEAD))
5622 return NULL;
5623 /* for polled retry, if flag is set, we already went through here */
5624 if (req->flags & REQ_F_POLLED)
5625 return NULL;
5627 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
5628 link_list);
5629 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
5630 return NULL;
5632 req->flags |= REQ_F_LINK_TIMEOUT;
5633 return nxt;
5636 static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5638 struct io_kiocb *linked_timeout;
5639 struct io_kiocb *nxt;
5640 const struct cred *old_creds = NULL;
5641 int ret;
5643 again:
5644 linked_timeout = io_prep_linked_timeout(req);
5646 if (req->work.creds && req->work.creds != current_cred()) {
5647 if (old_creds)
5648 revert_creds(old_creds);
5649 if (old_creds == req->work.creds)
5650 old_creds = NULL; /* restored original creds */
5651 else
5652 old_creds = override_creds(req->work.creds);
5655 ret = io_issue_sqe(req, sqe, true);
5658 * We async punt it if the file wasn't marked NOWAIT, or if the file
5659 * doesn't support non-blocking read/write attempts
5661 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
5662 (req->flags & REQ_F_MUST_PUNT))) {
5663 if (io_arm_poll_handler(req)) {
5664 if (linked_timeout)
5665 io_queue_linked_timeout(linked_timeout);
5666 goto exit;
5668 punt:
5669 if (io_op_defs[req->opcode].file_table) {
5670 ret = io_grab_files(req);
5671 if (ret)
5672 goto err;
5676 * Queued up for async execution, worker will release
5677 * submit reference when the iocb is actually submitted.
5679 io_queue_async_work(req);
5680 goto exit;
5683 err:
5684 nxt = NULL;
5685 /* drop submission reference */
5686 io_put_req_find_next(req, &nxt);
5688 if (linked_timeout) {
5689 if (!ret)
5690 io_queue_linked_timeout(linked_timeout);
5691 else
5692 io_put_req(linked_timeout);
5695 /* and drop final reference, if we failed */
5696 if (ret) {
5697 io_cqring_add_event(req, ret);
5698 req_set_fail_links(req);
5699 io_put_req(req);
5701 if (nxt) {
5702 req = nxt;
5704 if (req->flags & REQ_F_FORCE_ASYNC)
5705 goto punt;
5706 goto again;
5708 exit:
5709 if (old_creds)
5710 revert_creds(old_creds);
5713 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5715 int ret;
5717 ret = io_req_defer(req, sqe);
5718 if (ret) {
5719 if (ret != -EIOCBQUEUED) {
5720 fail_req:
5721 io_cqring_add_event(req, ret);
5722 req_set_fail_links(req);
5723 io_double_put_req(req);
5725 } else if (req->flags & REQ_F_FORCE_ASYNC) {
5726 if (!req->io) {
5727 ret = -EAGAIN;
5728 if (io_alloc_async_ctx(req))
5729 goto fail_req;
5730 ret = io_req_defer_prep(req, sqe);
5731 if (unlikely(ret < 0))
5732 goto fail_req;
5736 * Never try inline submit of IOSQE_ASYNC is set, go straight
5737 * to async execution.
5739 req->work.flags |= IO_WQ_WORK_CONCURRENT;
5740 io_queue_async_work(req);
5741 } else {
5742 __io_queue_sqe(req, sqe);
5746 static inline void io_queue_link_head(struct io_kiocb *req)
5748 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
5749 io_cqring_add_event(req, -ECANCELED);
5750 io_double_put_req(req);
5751 } else
5752 io_queue_sqe(req, NULL);
5755 static int io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5756 struct io_submit_state *state, struct io_kiocb **link)
5758 struct io_ring_ctx *ctx = req->ctx;
5759 int ret;
5762 * If we already have a head request, queue this one for async
5763 * submittal once the head completes. If we don't have a head but
5764 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
5765 * submitted sync once the chain is complete. If none of those
5766 * conditions are true (normal request), then just queue it.
5768 if (*link) {
5769 struct io_kiocb *head = *link;
5772 * Taking sequential execution of a link, draining both sides
5773 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
5774 * requests in the link. So, it drains the head and the
5775 * next after the link request. The last one is done via
5776 * drain_next flag to persist the effect across calls.
5778 if (req->flags & REQ_F_IO_DRAIN) {
5779 head->flags |= REQ_F_IO_DRAIN;
5780 ctx->drain_next = 1;
5782 if (io_alloc_async_ctx(req))
5783 return -EAGAIN;
5785 ret = io_req_defer_prep(req, sqe);
5786 if (ret) {
5787 /* fail even hard links since we don't submit */
5788 head->flags |= REQ_F_FAIL_LINK;
5789 return ret;
5791 trace_io_uring_link(ctx, req, head);
5792 list_add_tail(&req->link_list, &head->link_list);
5794 /* last request of a link, enqueue the link */
5795 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
5796 io_queue_link_head(head);
5797 *link = NULL;
5799 } else {
5800 if (unlikely(ctx->drain_next)) {
5801 req->flags |= REQ_F_IO_DRAIN;
5802 ctx->drain_next = 0;
5804 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
5805 req->flags |= REQ_F_LINK_HEAD;
5806 INIT_LIST_HEAD(&req->link_list);
5808 if (io_alloc_async_ctx(req))
5809 return -EAGAIN;
5811 ret = io_req_defer_prep(req, sqe);
5812 if (ret)
5813 req->flags |= REQ_F_FAIL_LINK;
5814 *link = req;
5815 } else {
5816 io_queue_sqe(req, sqe);
5820 return 0;
5824 * Batched submission is done, ensure local IO is flushed out.
5826 static void io_submit_state_end(struct io_submit_state *state)
5828 blk_finish_plug(&state->plug);
5829 io_file_put(state);
5830 if (state->free_reqs)
5831 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
5835 * Start submission side cache.
5837 static void io_submit_state_start(struct io_submit_state *state,
5838 unsigned int max_ios)
5840 blk_start_plug(&state->plug);
5841 state->free_reqs = 0;
5842 state->file = NULL;
5843 state->ios_left = max_ios;
5846 static void io_commit_sqring(struct io_ring_ctx *ctx)
5848 struct io_rings *rings = ctx->rings;
5851 * Ensure any loads from the SQEs are done at this point,
5852 * since once we write the new head, the application could
5853 * write new data to them.
5855 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
5859 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
5860 * that is mapped by userspace. This means that care needs to be taken to
5861 * ensure that reads are stable, as we cannot rely on userspace always
5862 * being a good citizen. If members of the sqe are validated and then later
5863 * used, it's important that those reads are done through READ_ONCE() to
5864 * prevent a re-load down the line.
5866 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
5868 u32 *sq_array = ctx->sq_array;
5869 unsigned head;
5872 * The cached sq head (or cq tail) serves two purposes:
5874 * 1) allows us to batch the cost of updating the user visible
5875 * head updates.
5876 * 2) allows the kernel side to track the head on its own, even
5877 * though the application is the one updating it.
5879 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
5880 if (likely(head < ctx->sq_entries))
5881 return &ctx->sq_sqes[head];
5883 /* drop invalid entries */
5884 ctx->cached_sq_dropped++;
5885 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
5886 return NULL;
5889 static inline void io_consume_sqe(struct io_ring_ctx *ctx)
5891 ctx->cached_sq_head++;
5894 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
5895 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
5896 IOSQE_BUFFER_SELECT)
5898 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
5899 const struct io_uring_sqe *sqe,
5900 struct io_submit_state *state, bool async)
5902 unsigned int sqe_flags;
5903 int id;
5906 * All io need record the previous position, if LINK vs DARIN,
5907 * it can be used to mark the position of the first IO in the
5908 * link list.
5910 req->sequence = ctx->cached_sq_head - ctx->cached_sq_dropped;
5911 req->opcode = READ_ONCE(sqe->opcode);
5912 req->user_data = READ_ONCE(sqe->user_data);
5913 req->io = NULL;
5914 req->file = NULL;
5915 req->ctx = ctx;
5916 req->flags = 0;
5917 /* one is dropped after submission, the other at completion */
5918 refcount_set(&req->refs, 2);
5919 req->task = NULL;
5920 req->result = 0;
5921 req->needs_fixed_file = async;
5922 INIT_IO_WORK(&req->work, io_wq_submit_work);
5924 if (unlikely(req->opcode >= IORING_OP_LAST))
5925 return -EINVAL;
5927 if (unlikely(io_sq_thread_acquire_mm(ctx, req)))
5928 return -EFAULT;
5930 sqe_flags = READ_ONCE(sqe->flags);
5931 /* enforce forwards compatibility on users */
5932 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
5933 return -EINVAL;
5935 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
5936 !io_op_defs[req->opcode].buffer_select)
5937 return -EOPNOTSUPP;
5939 id = READ_ONCE(sqe->personality);
5940 if (id) {
5941 req->work.creds = idr_find(&ctx->personality_idr, id);
5942 if (unlikely(!req->work.creds))
5943 return -EINVAL;
5944 get_cred(req->work.creds);
5947 /* same numerical values with corresponding REQ_F_*, safe to copy */
5948 req->flags |= sqe_flags & (IOSQE_IO_DRAIN | IOSQE_IO_HARDLINK |
5949 IOSQE_ASYNC | IOSQE_FIXED_FILE |
5950 IOSQE_BUFFER_SELECT | IOSQE_IO_LINK);
5952 if (!io_op_defs[req->opcode].needs_file)
5953 return 0;
5955 return io_req_set_file(state, req, READ_ONCE(sqe->fd));
5958 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
5959 struct file *ring_file, int ring_fd, bool async)
5961 struct io_submit_state state, *statep = NULL;
5962 struct io_kiocb *link = NULL;
5963 int i, submitted = 0;
5965 /* if we have a backlog and couldn't flush it all, return BUSY */
5966 if (test_bit(0, &ctx->sq_check_overflow)) {
5967 if (!list_empty(&ctx->cq_overflow_list) &&
5968 !io_cqring_overflow_flush(ctx, false))
5969 return -EBUSY;
5972 /* make sure SQ entry isn't read before tail */
5973 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
5975 if (!percpu_ref_tryget_many(&ctx->refs, nr))
5976 return -EAGAIN;
5978 if (nr > IO_PLUG_THRESHOLD) {
5979 io_submit_state_start(&state, nr);
5980 statep = &state;
5983 ctx->ring_fd = ring_fd;
5984 ctx->ring_file = ring_file;
5986 for (i = 0; i < nr; i++) {
5987 const struct io_uring_sqe *sqe;
5988 struct io_kiocb *req;
5989 int err;
5991 sqe = io_get_sqe(ctx);
5992 if (unlikely(!sqe)) {
5993 io_consume_sqe(ctx);
5994 break;
5996 req = io_alloc_req(ctx, statep);
5997 if (unlikely(!req)) {
5998 if (!submitted)
5999 submitted = -EAGAIN;
6000 break;
6003 err = io_init_req(ctx, req, sqe, statep, async);
6004 io_consume_sqe(ctx);
6005 /* will complete beyond this point, count as submitted */
6006 submitted++;
6008 if (unlikely(err)) {
6009 fail_req:
6010 io_cqring_add_event(req, err);
6011 io_double_put_req(req);
6012 break;
6015 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6016 true, async);
6017 err = io_submit_sqe(req, sqe, statep, &link);
6018 if (err)
6019 goto fail_req;
6022 if (unlikely(submitted != nr)) {
6023 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6025 percpu_ref_put_many(&ctx->refs, nr - ref_used);
6027 if (link)
6028 io_queue_link_head(link);
6029 if (statep)
6030 io_submit_state_end(&state);
6032 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6033 io_commit_sqring(ctx);
6035 return submitted;
6038 static int io_sq_thread(void *data)
6040 struct io_ring_ctx *ctx = data;
6041 const struct cred *old_cred;
6042 mm_segment_t old_fs;
6043 DEFINE_WAIT(wait);
6044 unsigned long timeout;
6045 int ret = 0;
6047 complete(&ctx->completions[1]);
6049 old_fs = get_fs();
6050 set_fs(USER_DS);
6051 old_cred = override_creds(ctx->creds);
6053 timeout = jiffies + ctx->sq_thread_idle;
6054 while (!kthread_should_park()) {
6055 unsigned int to_submit;
6057 if (!list_empty(&ctx->poll_list)) {
6058 unsigned nr_events = 0;
6060 mutex_lock(&ctx->uring_lock);
6061 if (!list_empty(&ctx->poll_list))
6062 io_iopoll_getevents(ctx, &nr_events, 0);
6063 else
6064 timeout = jiffies + ctx->sq_thread_idle;
6065 mutex_unlock(&ctx->uring_lock);
6068 to_submit = io_sqring_entries(ctx);
6071 * If submit got -EBUSY, flag us as needing the application
6072 * to enter the kernel to reap and flush events.
6074 if (!to_submit || ret == -EBUSY) {
6076 * Drop cur_mm before scheduling, we can't hold it for
6077 * long periods (or over schedule()). Do this before
6078 * adding ourselves to the waitqueue, as the unuse/drop
6079 * may sleep.
6081 io_sq_thread_drop_mm(ctx);
6084 * We're polling. If we're within the defined idle
6085 * period, then let us spin without work before going
6086 * to sleep. The exception is if we got EBUSY doing
6087 * more IO, we should wait for the application to
6088 * reap events and wake us up.
6090 if (!list_empty(&ctx->poll_list) ||
6091 (!time_after(jiffies, timeout) && ret != -EBUSY &&
6092 !percpu_ref_is_dying(&ctx->refs))) {
6093 if (current->task_works)
6094 task_work_run();
6095 cond_resched();
6096 continue;
6099 prepare_to_wait(&ctx->sqo_wait, &wait,
6100 TASK_INTERRUPTIBLE);
6103 * While doing polled IO, before going to sleep, we need
6104 * to check if there are new reqs added to poll_list, it
6105 * is because reqs may have been punted to io worker and
6106 * will be added to poll_list later, hence check the
6107 * poll_list again.
6109 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6110 !list_empty_careful(&ctx->poll_list)) {
6111 finish_wait(&ctx->sqo_wait, &wait);
6112 continue;
6115 /* Tell userspace we may need a wakeup call */
6116 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6117 /* make sure to read SQ tail after writing flags */
6118 smp_mb();
6120 to_submit = io_sqring_entries(ctx);
6121 if (!to_submit || ret == -EBUSY) {
6122 if (kthread_should_park()) {
6123 finish_wait(&ctx->sqo_wait, &wait);
6124 break;
6126 if (current->task_works) {
6127 task_work_run();
6128 finish_wait(&ctx->sqo_wait, &wait);
6129 continue;
6131 if (signal_pending(current))
6132 flush_signals(current);
6133 schedule();
6134 finish_wait(&ctx->sqo_wait, &wait);
6136 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6137 ret = 0;
6138 continue;
6140 finish_wait(&ctx->sqo_wait, &wait);
6142 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6145 mutex_lock(&ctx->uring_lock);
6146 ret = io_submit_sqes(ctx, to_submit, NULL, -1, true);
6147 mutex_unlock(&ctx->uring_lock);
6148 timeout = jiffies + ctx->sq_thread_idle;
6151 if (current->task_works)
6152 task_work_run();
6154 set_fs(old_fs);
6155 io_sq_thread_drop_mm(ctx);
6156 revert_creds(old_cred);
6158 kthread_parkme();
6160 return 0;
6163 struct io_wait_queue {
6164 struct wait_queue_entry wq;
6165 struct io_ring_ctx *ctx;
6166 unsigned to_wait;
6167 unsigned nr_timeouts;
6170 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
6172 struct io_ring_ctx *ctx = iowq->ctx;
6175 * Wake up if we have enough events, or if a timeout occurred since we
6176 * started waiting. For timeouts, we always want to return to userspace,
6177 * regardless of event count.
6179 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
6180 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6183 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6184 int wake_flags, void *key)
6186 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6187 wq);
6189 /* use noflush == true, as we can't safely rely on locking context */
6190 if (!io_should_wake(iowq, true))
6191 return -1;
6193 return autoremove_wake_function(curr, mode, wake_flags, key);
6197 * Wait until events become available, if we don't already have some. The
6198 * application must reap them itself, as they reside on the shared cq ring.
6200 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6201 const sigset_t __user *sig, size_t sigsz)
6203 struct io_wait_queue iowq = {
6204 .wq = {
6205 .private = current,
6206 .func = io_wake_function,
6207 .entry = LIST_HEAD_INIT(iowq.wq.entry),
6209 .ctx = ctx,
6210 .to_wait = min_events,
6212 struct io_rings *rings = ctx->rings;
6213 int ret = 0;
6215 do {
6216 if (io_cqring_events(ctx, false) >= min_events)
6217 return 0;
6218 if (!current->task_works)
6219 break;
6220 task_work_run();
6221 } while (1);
6223 if (sig) {
6224 #ifdef CONFIG_COMPAT
6225 if (in_compat_syscall())
6226 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
6227 sigsz);
6228 else
6229 #endif
6230 ret = set_user_sigmask(sig, sigsz);
6232 if (ret)
6233 return ret;
6236 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
6237 trace_io_uring_cqring_wait(ctx, min_events);
6238 do {
6239 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
6240 TASK_INTERRUPTIBLE);
6241 if (current->task_works)
6242 task_work_run();
6243 if (io_should_wake(&iowq, false))
6244 break;
6245 schedule();
6246 if (signal_pending(current)) {
6247 ret = -EINTR;
6248 break;
6250 } while (1);
6251 finish_wait(&ctx->wait, &iowq.wq);
6253 restore_saved_sigmask_unless(ret == -EINTR);
6255 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
6258 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
6260 #if defined(CONFIG_UNIX)
6261 if (ctx->ring_sock) {
6262 struct sock *sock = ctx->ring_sock->sk;
6263 struct sk_buff *skb;
6265 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
6266 kfree_skb(skb);
6268 #else
6269 int i;
6271 for (i = 0; i < ctx->nr_user_files; i++) {
6272 struct file *file;
6274 file = io_file_from_index(ctx, i);
6275 if (file)
6276 fput(file);
6278 #endif
6281 static void io_file_ref_kill(struct percpu_ref *ref)
6283 struct fixed_file_data *data;
6285 data = container_of(ref, struct fixed_file_data, refs);
6286 complete(&data->done);
6289 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
6291 struct fixed_file_data *data = ctx->file_data;
6292 struct fixed_file_ref_node *ref_node = NULL;
6293 unsigned nr_tables, i;
6294 unsigned long flags;
6296 if (!data)
6297 return -ENXIO;
6299 spin_lock_irqsave(&data->lock, flags);
6300 if (!list_empty(&data->ref_list))
6301 ref_node = list_first_entry(&data->ref_list,
6302 struct fixed_file_ref_node, node);
6303 spin_unlock_irqrestore(&data->lock, flags);
6304 if (ref_node)
6305 percpu_ref_kill(&ref_node->refs);
6307 percpu_ref_kill(&data->refs);
6309 /* wait for all refs nodes to complete */
6310 wait_for_completion(&data->done);
6312 __io_sqe_files_unregister(ctx);
6313 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
6314 for (i = 0; i < nr_tables; i++)
6315 kfree(data->table[i].files);
6316 kfree(data->table);
6317 percpu_ref_exit(&data->refs);
6318 kfree(data);
6319 ctx->file_data = NULL;
6320 ctx->nr_user_files = 0;
6321 return 0;
6324 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
6326 if (ctx->sqo_thread) {
6327 wait_for_completion(&ctx->completions[1]);
6329 * The park is a bit of a work-around, without it we get
6330 * warning spews on shutdown with SQPOLL set and affinity
6331 * set to a single CPU.
6333 kthread_park(ctx->sqo_thread);
6334 kthread_stop(ctx->sqo_thread);
6335 ctx->sqo_thread = NULL;
6339 static void io_finish_async(struct io_ring_ctx *ctx)
6341 io_sq_thread_stop(ctx);
6343 if (ctx->io_wq) {
6344 io_wq_destroy(ctx->io_wq);
6345 ctx->io_wq = NULL;
6349 #if defined(CONFIG_UNIX)
6351 * Ensure the UNIX gc is aware of our file set, so we are certain that
6352 * the io_uring can be safely unregistered on process exit, even if we have
6353 * loops in the file referencing.
6355 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
6357 struct sock *sk = ctx->ring_sock->sk;
6358 struct scm_fp_list *fpl;
6359 struct sk_buff *skb;
6360 int i, nr_files;
6362 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
6363 if (!fpl)
6364 return -ENOMEM;
6366 skb = alloc_skb(0, GFP_KERNEL);
6367 if (!skb) {
6368 kfree(fpl);
6369 return -ENOMEM;
6372 skb->sk = sk;
6374 nr_files = 0;
6375 fpl->user = get_uid(ctx->user);
6376 for (i = 0; i < nr; i++) {
6377 struct file *file = io_file_from_index(ctx, i + offset);
6379 if (!file)
6380 continue;
6381 fpl->fp[nr_files] = get_file(file);
6382 unix_inflight(fpl->user, fpl->fp[nr_files]);
6383 nr_files++;
6386 if (nr_files) {
6387 fpl->max = SCM_MAX_FD;
6388 fpl->count = nr_files;
6389 UNIXCB(skb).fp = fpl;
6390 skb->destructor = unix_destruct_scm;
6391 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
6392 skb_queue_head(&sk->sk_receive_queue, skb);
6394 for (i = 0; i < nr_files; i++)
6395 fput(fpl->fp[i]);
6396 } else {
6397 kfree_skb(skb);
6398 kfree(fpl);
6401 return 0;
6405 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
6406 * causes regular reference counting to break down. We rely on the UNIX
6407 * garbage collection to take care of this problem for us.
6409 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
6411 unsigned left, total;
6412 int ret = 0;
6414 total = 0;
6415 left = ctx->nr_user_files;
6416 while (left) {
6417 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
6419 ret = __io_sqe_files_scm(ctx, this_files, total);
6420 if (ret)
6421 break;
6422 left -= this_files;
6423 total += this_files;
6426 if (!ret)
6427 return 0;
6429 while (total < ctx->nr_user_files) {
6430 struct file *file = io_file_from_index(ctx, total);
6432 if (file)
6433 fput(file);
6434 total++;
6437 return ret;
6439 #else
6440 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
6442 return 0;
6444 #endif
6446 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
6447 unsigned nr_files)
6449 int i;
6451 for (i = 0; i < nr_tables; i++) {
6452 struct fixed_file_table *table = &ctx->file_data->table[i];
6453 unsigned this_files;
6455 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
6456 table->files = kcalloc(this_files, sizeof(struct file *),
6457 GFP_KERNEL);
6458 if (!table->files)
6459 break;
6460 nr_files -= this_files;
6463 if (i == nr_tables)
6464 return 0;
6466 for (i = 0; i < nr_tables; i++) {
6467 struct fixed_file_table *table = &ctx->file_data->table[i];
6468 kfree(table->files);
6470 return 1;
6473 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
6475 #if defined(CONFIG_UNIX)
6476 struct sock *sock = ctx->ring_sock->sk;
6477 struct sk_buff_head list, *head = &sock->sk_receive_queue;
6478 struct sk_buff *skb;
6479 int i;
6481 __skb_queue_head_init(&list);
6484 * Find the skb that holds this file in its SCM_RIGHTS. When found,
6485 * remove this entry and rearrange the file array.
6487 skb = skb_dequeue(head);
6488 while (skb) {
6489 struct scm_fp_list *fp;
6491 fp = UNIXCB(skb).fp;
6492 for (i = 0; i < fp->count; i++) {
6493 int left;
6495 if (fp->fp[i] != file)
6496 continue;
6498 unix_notinflight(fp->user, fp->fp[i]);
6499 left = fp->count - 1 - i;
6500 if (left) {
6501 memmove(&fp->fp[i], &fp->fp[i + 1],
6502 left * sizeof(struct file *));
6504 fp->count--;
6505 if (!fp->count) {
6506 kfree_skb(skb);
6507 skb = NULL;
6508 } else {
6509 __skb_queue_tail(&list, skb);
6511 fput(file);
6512 file = NULL;
6513 break;
6516 if (!file)
6517 break;
6519 __skb_queue_tail(&list, skb);
6521 skb = skb_dequeue(head);
6524 if (skb_peek(&list)) {
6525 spin_lock_irq(&head->lock);
6526 while ((skb = __skb_dequeue(&list)) != NULL)
6527 __skb_queue_tail(head, skb);
6528 spin_unlock_irq(&head->lock);
6530 #else
6531 fput(file);
6532 #endif
6535 struct io_file_put {
6536 struct list_head list;
6537 struct file *file;
6540 static void io_file_put_work(struct work_struct *work)
6542 struct fixed_file_ref_node *ref_node;
6543 struct fixed_file_data *file_data;
6544 struct io_ring_ctx *ctx;
6545 struct io_file_put *pfile, *tmp;
6546 unsigned long flags;
6548 ref_node = container_of(work, struct fixed_file_ref_node, work);
6549 file_data = ref_node->file_data;
6550 ctx = file_data->ctx;
6552 list_for_each_entry_safe(pfile, tmp, &ref_node->file_list, list) {
6553 list_del_init(&pfile->list);
6554 io_ring_file_put(ctx, pfile->file);
6555 kfree(pfile);
6558 spin_lock_irqsave(&file_data->lock, flags);
6559 list_del_init(&ref_node->node);
6560 spin_unlock_irqrestore(&file_data->lock, flags);
6562 percpu_ref_exit(&ref_node->refs);
6563 kfree(ref_node);
6564 percpu_ref_put(&file_data->refs);
6567 static void io_file_data_ref_zero(struct percpu_ref *ref)
6569 struct fixed_file_ref_node *ref_node;
6571 ref_node = container_of(ref, struct fixed_file_ref_node, refs);
6573 queue_work(system_wq, &ref_node->work);
6576 static struct fixed_file_ref_node *alloc_fixed_file_ref_node(
6577 struct io_ring_ctx *ctx)
6579 struct fixed_file_ref_node *ref_node;
6581 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
6582 if (!ref_node)
6583 return ERR_PTR(-ENOMEM);
6585 if (percpu_ref_init(&ref_node->refs, io_file_data_ref_zero,
6586 0, GFP_KERNEL)) {
6587 kfree(ref_node);
6588 return ERR_PTR(-ENOMEM);
6590 INIT_LIST_HEAD(&ref_node->node);
6591 INIT_LIST_HEAD(&ref_node->file_list);
6592 INIT_WORK(&ref_node->work, io_file_put_work);
6593 ref_node->file_data = ctx->file_data;
6594 return ref_node;
6598 static void destroy_fixed_file_ref_node(struct fixed_file_ref_node *ref_node)
6600 percpu_ref_exit(&ref_node->refs);
6601 kfree(ref_node);
6604 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
6605 unsigned nr_args)
6607 __s32 __user *fds = (__s32 __user *) arg;
6608 unsigned nr_tables;
6609 struct file *file;
6610 int fd, ret = 0;
6611 unsigned i;
6612 struct fixed_file_ref_node *ref_node;
6613 unsigned long flags;
6615 if (ctx->file_data)
6616 return -EBUSY;
6617 if (!nr_args)
6618 return -EINVAL;
6619 if (nr_args > IORING_MAX_FIXED_FILES)
6620 return -EMFILE;
6622 ctx->file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
6623 if (!ctx->file_data)
6624 return -ENOMEM;
6625 ctx->file_data->ctx = ctx;
6626 init_completion(&ctx->file_data->done);
6627 INIT_LIST_HEAD(&ctx->file_data->ref_list);
6628 spin_lock_init(&ctx->file_data->lock);
6630 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
6631 ctx->file_data->table = kcalloc(nr_tables,
6632 sizeof(struct fixed_file_table),
6633 GFP_KERNEL);
6634 if (!ctx->file_data->table) {
6635 kfree(ctx->file_data);
6636 ctx->file_data = NULL;
6637 return -ENOMEM;
6640 if (percpu_ref_init(&ctx->file_data->refs, io_file_ref_kill,
6641 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
6642 kfree(ctx->file_data->table);
6643 kfree(ctx->file_data);
6644 ctx->file_data = NULL;
6645 return -ENOMEM;
6648 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
6649 percpu_ref_exit(&ctx->file_data->refs);
6650 kfree(ctx->file_data->table);
6651 kfree(ctx->file_data);
6652 ctx->file_data = NULL;
6653 return -ENOMEM;
6656 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
6657 struct fixed_file_table *table;
6658 unsigned index;
6660 ret = -EFAULT;
6661 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
6662 break;
6663 /* allow sparse sets */
6664 if (fd == -1) {
6665 ret = 0;
6666 continue;
6669 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
6670 index = i & IORING_FILE_TABLE_MASK;
6671 file = fget(fd);
6673 ret = -EBADF;
6674 if (!file)
6675 break;
6678 * Don't allow io_uring instances to be registered. If UNIX
6679 * isn't enabled, then this causes a reference cycle and this
6680 * instance can never get freed. If UNIX is enabled we'll
6681 * handle it just fine, but there's still no point in allowing
6682 * a ring fd as it doesn't support regular read/write anyway.
6684 if (file->f_op == &io_uring_fops) {
6685 fput(file);
6686 break;
6688 ret = 0;
6689 table->files[index] = file;
6692 if (ret) {
6693 for (i = 0; i < ctx->nr_user_files; i++) {
6694 file = io_file_from_index(ctx, i);
6695 if (file)
6696 fput(file);
6698 for (i = 0; i < nr_tables; i++)
6699 kfree(ctx->file_data->table[i].files);
6701 kfree(ctx->file_data->table);
6702 kfree(ctx->file_data);
6703 ctx->file_data = NULL;
6704 ctx->nr_user_files = 0;
6705 return ret;
6708 ret = io_sqe_files_scm(ctx);
6709 if (ret) {
6710 io_sqe_files_unregister(ctx);
6711 return ret;
6714 ref_node = alloc_fixed_file_ref_node(ctx);
6715 if (IS_ERR(ref_node)) {
6716 io_sqe_files_unregister(ctx);
6717 return PTR_ERR(ref_node);
6720 ctx->file_data->cur_refs = &ref_node->refs;
6721 spin_lock_irqsave(&ctx->file_data->lock, flags);
6722 list_add(&ref_node->node, &ctx->file_data->ref_list);
6723 spin_unlock_irqrestore(&ctx->file_data->lock, flags);
6724 percpu_ref_get(&ctx->file_data->refs);
6725 return ret;
6728 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
6729 int index)
6731 #if defined(CONFIG_UNIX)
6732 struct sock *sock = ctx->ring_sock->sk;
6733 struct sk_buff_head *head = &sock->sk_receive_queue;
6734 struct sk_buff *skb;
6737 * See if we can merge this file into an existing skb SCM_RIGHTS
6738 * file set. If there's no room, fall back to allocating a new skb
6739 * and filling it in.
6741 spin_lock_irq(&head->lock);
6742 skb = skb_peek(head);
6743 if (skb) {
6744 struct scm_fp_list *fpl = UNIXCB(skb).fp;
6746 if (fpl->count < SCM_MAX_FD) {
6747 __skb_unlink(skb, head);
6748 spin_unlock_irq(&head->lock);
6749 fpl->fp[fpl->count] = get_file(file);
6750 unix_inflight(fpl->user, fpl->fp[fpl->count]);
6751 fpl->count++;
6752 spin_lock_irq(&head->lock);
6753 __skb_queue_head(head, skb);
6754 } else {
6755 skb = NULL;
6758 spin_unlock_irq(&head->lock);
6760 if (skb) {
6761 fput(file);
6762 return 0;
6765 return __io_sqe_files_scm(ctx, 1, index);
6766 #else
6767 return 0;
6768 #endif
6771 static int io_queue_file_removal(struct fixed_file_data *data,
6772 struct file *file)
6774 struct io_file_put *pfile;
6775 struct percpu_ref *refs = data->cur_refs;
6776 struct fixed_file_ref_node *ref_node;
6778 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
6779 if (!pfile)
6780 return -ENOMEM;
6782 ref_node = container_of(refs, struct fixed_file_ref_node, refs);
6783 pfile->file = file;
6784 list_add(&pfile->list, &ref_node->file_list);
6786 return 0;
6789 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
6790 struct io_uring_files_update *up,
6791 unsigned nr_args)
6793 struct fixed_file_data *data = ctx->file_data;
6794 struct fixed_file_ref_node *ref_node;
6795 struct file *file;
6796 __s32 __user *fds;
6797 int fd, i, err;
6798 __u32 done;
6799 unsigned long flags;
6800 bool needs_switch = false;
6802 if (check_add_overflow(up->offset, nr_args, &done))
6803 return -EOVERFLOW;
6804 if (done > ctx->nr_user_files)
6805 return -EINVAL;
6807 ref_node = alloc_fixed_file_ref_node(ctx);
6808 if (IS_ERR(ref_node))
6809 return PTR_ERR(ref_node);
6811 done = 0;
6812 fds = u64_to_user_ptr(up->fds);
6813 while (nr_args) {
6814 struct fixed_file_table *table;
6815 unsigned index;
6817 err = 0;
6818 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
6819 err = -EFAULT;
6820 break;
6822 i = array_index_nospec(up->offset, ctx->nr_user_files);
6823 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
6824 index = i & IORING_FILE_TABLE_MASK;
6825 if (table->files[index]) {
6826 file = io_file_from_index(ctx, index);
6827 err = io_queue_file_removal(data, file);
6828 if (err)
6829 break;
6830 table->files[index] = NULL;
6831 needs_switch = true;
6833 if (fd != -1) {
6834 file = fget(fd);
6835 if (!file) {
6836 err = -EBADF;
6837 break;
6840 * Don't allow io_uring instances to be registered. If
6841 * UNIX isn't enabled, then this causes a reference
6842 * cycle and this instance can never get freed. If UNIX
6843 * is enabled we'll handle it just fine, but there's
6844 * still no point in allowing a ring fd as it doesn't
6845 * support regular read/write anyway.
6847 if (file->f_op == &io_uring_fops) {
6848 fput(file);
6849 err = -EBADF;
6850 break;
6852 table->files[index] = file;
6853 err = io_sqe_file_register(ctx, file, i);
6854 if (err)
6855 break;
6857 nr_args--;
6858 done++;
6859 up->offset++;
6862 if (needs_switch) {
6863 percpu_ref_kill(data->cur_refs);
6864 spin_lock_irqsave(&data->lock, flags);
6865 list_add(&ref_node->node, &data->ref_list);
6866 data->cur_refs = &ref_node->refs;
6867 spin_unlock_irqrestore(&data->lock, flags);
6868 percpu_ref_get(&ctx->file_data->refs);
6869 } else
6870 destroy_fixed_file_ref_node(ref_node);
6872 return done ? done : err;
6875 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
6876 unsigned nr_args)
6878 struct io_uring_files_update up;
6880 if (!ctx->file_data)
6881 return -ENXIO;
6882 if (!nr_args)
6883 return -EINVAL;
6884 if (copy_from_user(&up, arg, sizeof(up)))
6885 return -EFAULT;
6886 if (up.resv)
6887 return -EINVAL;
6889 return __io_sqe_files_update(ctx, &up, nr_args);
6892 static void io_free_work(struct io_wq_work *work)
6894 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6896 /* Consider that io_steal_work() relies on this ref */
6897 io_put_req(req);
6900 static int io_init_wq_offload(struct io_ring_ctx *ctx,
6901 struct io_uring_params *p)
6903 struct io_wq_data data;
6904 struct fd f;
6905 struct io_ring_ctx *ctx_attach;
6906 unsigned int concurrency;
6907 int ret = 0;
6909 data.user = ctx->user;
6910 data.free_work = io_free_work;
6912 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
6913 /* Do QD, or 4 * CPUS, whatever is smallest */
6914 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
6916 ctx->io_wq = io_wq_create(concurrency, &data);
6917 if (IS_ERR(ctx->io_wq)) {
6918 ret = PTR_ERR(ctx->io_wq);
6919 ctx->io_wq = NULL;
6921 return ret;
6924 f = fdget(p->wq_fd);
6925 if (!f.file)
6926 return -EBADF;
6928 if (f.file->f_op != &io_uring_fops) {
6929 ret = -EINVAL;
6930 goto out_fput;
6933 ctx_attach = f.file->private_data;
6934 /* @io_wq is protected by holding the fd */
6935 if (!io_wq_get(ctx_attach->io_wq, &data)) {
6936 ret = -EINVAL;
6937 goto out_fput;
6940 ctx->io_wq = ctx_attach->io_wq;
6941 out_fput:
6942 fdput(f);
6943 return ret;
6946 static int io_sq_offload_start(struct io_ring_ctx *ctx,
6947 struct io_uring_params *p)
6949 int ret;
6951 mmgrab(current->mm);
6952 ctx->sqo_mm = current->mm;
6954 if (ctx->flags & IORING_SETUP_SQPOLL) {
6955 ret = -EPERM;
6956 if (!capable(CAP_SYS_ADMIN))
6957 goto err;
6959 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
6960 if (!ctx->sq_thread_idle)
6961 ctx->sq_thread_idle = HZ;
6963 if (p->flags & IORING_SETUP_SQ_AFF) {
6964 int cpu = p->sq_thread_cpu;
6966 ret = -EINVAL;
6967 if (cpu >= nr_cpu_ids)
6968 goto err;
6969 if (!cpu_online(cpu))
6970 goto err;
6972 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
6973 ctx, cpu,
6974 "io_uring-sq");
6975 } else {
6976 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
6977 "io_uring-sq");
6979 if (IS_ERR(ctx->sqo_thread)) {
6980 ret = PTR_ERR(ctx->sqo_thread);
6981 ctx->sqo_thread = NULL;
6982 goto err;
6984 wake_up_process(ctx->sqo_thread);
6985 } else if (p->flags & IORING_SETUP_SQ_AFF) {
6986 /* Can't have SQ_AFF without SQPOLL */
6987 ret = -EINVAL;
6988 goto err;
6991 ret = io_init_wq_offload(ctx, p);
6992 if (ret)
6993 goto err;
6995 return 0;
6996 err:
6997 io_finish_async(ctx);
6998 mmdrop(ctx->sqo_mm);
6999 ctx->sqo_mm = NULL;
7000 return ret;
7003 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
7005 atomic_long_sub(nr_pages, &user->locked_vm);
7008 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
7010 unsigned long page_limit, cur_pages, new_pages;
7012 /* Don't allow more pages than we can safely lock */
7013 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
7015 do {
7016 cur_pages = atomic_long_read(&user->locked_vm);
7017 new_pages = cur_pages + nr_pages;
7018 if (new_pages > page_limit)
7019 return -ENOMEM;
7020 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
7021 new_pages) != cur_pages);
7023 return 0;
7026 static void io_mem_free(void *ptr)
7028 struct page *page;
7030 if (!ptr)
7031 return;
7033 page = virt_to_head_page(ptr);
7034 if (put_page_testzero(page))
7035 free_compound_page(page);
7038 static void *io_mem_alloc(size_t size)
7040 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
7041 __GFP_NORETRY;
7043 return (void *) __get_free_pages(gfp_flags, get_order(size));
7046 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
7047 size_t *sq_offset)
7049 struct io_rings *rings;
7050 size_t off, sq_array_size;
7052 off = struct_size(rings, cqes, cq_entries);
7053 if (off == SIZE_MAX)
7054 return SIZE_MAX;
7056 #ifdef CONFIG_SMP
7057 off = ALIGN(off, SMP_CACHE_BYTES);
7058 if (off == 0)
7059 return SIZE_MAX;
7060 #endif
7062 sq_array_size = array_size(sizeof(u32), sq_entries);
7063 if (sq_array_size == SIZE_MAX)
7064 return SIZE_MAX;
7066 if (check_add_overflow(off, sq_array_size, &off))
7067 return SIZE_MAX;
7069 if (sq_offset)
7070 *sq_offset = off;
7072 return off;
7075 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
7077 size_t pages;
7079 pages = (size_t)1 << get_order(
7080 rings_size(sq_entries, cq_entries, NULL));
7081 pages += (size_t)1 << get_order(
7082 array_size(sizeof(struct io_uring_sqe), sq_entries));
7084 return pages;
7087 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
7089 int i, j;
7091 if (!ctx->user_bufs)
7092 return -ENXIO;
7094 for (i = 0; i < ctx->nr_user_bufs; i++) {
7095 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7097 for (j = 0; j < imu->nr_bvecs; j++)
7098 unpin_user_page(imu->bvec[j].bv_page);
7100 if (ctx->account_mem)
7101 io_unaccount_mem(ctx->user, imu->nr_bvecs);
7102 kvfree(imu->bvec);
7103 imu->nr_bvecs = 0;
7106 kfree(ctx->user_bufs);
7107 ctx->user_bufs = NULL;
7108 ctx->nr_user_bufs = 0;
7109 return 0;
7112 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
7113 void __user *arg, unsigned index)
7115 struct iovec __user *src;
7117 #ifdef CONFIG_COMPAT
7118 if (ctx->compat) {
7119 struct compat_iovec __user *ciovs;
7120 struct compat_iovec ciov;
7122 ciovs = (struct compat_iovec __user *) arg;
7123 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
7124 return -EFAULT;
7126 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
7127 dst->iov_len = ciov.iov_len;
7128 return 0;
7130 #endif
7131 src = (struct iovec __user *) arg;
7132 if (copy_from_user(dst, &src[index], sizeof(*dst)))
7133 return -EFAULT;
7134 return 0;
7137 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
7138 unsigned nr_args)
7140 struct vm_area_struct **vmas = NULL;
7141 struct page **pages = NULL;
7142 int i, j, got_pages = 0;
7143 int ret = -EINVAL;
7145 if (ctx->user_bufs)
7146 return -EBUSY;
7147 if (!nr_args || nr_args > UIO_MAXIOV)
7148 return -EINVAL;
7150 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
7151 GFP_KERNEL);
7152 if (!ctx->user_bufs)
7153 return -ENOMEM;
7155 for (i = 0; i < nr_args; i++) {
7156 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7157 unsigned long off, start, end, ubuf;
7158 int pret, nr_pages;
7159 struct iovec iov;
7160 size_t size;
7162 ret = io_copy_iov(ctx, &iov, arg, i);
7163 if (ret)
7164 goto err;
7167 * Don't impose further limits on the size and buffer
7168 * constraints here, we'll -EINVAL later when IO is
7169 * submitted if they are wrong.
7171 ret = -EFAULT;
7172 if (!iov.iov_base || !iov.iov_len)
7173 goto err;
7175 /* arbitrary limit, but we need something */
7176 if (iov.iov_len > SZ_1G)
7177 goto err;
7179 ubuf = (unsigned long) iov.iov_base;
7180 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
7181 start = ubuf >> PAGE_SHIFT;
7182 nr_pages = end - start;
7184 if (ctx->account_mem) {
7185 ret = io_account_mem(ctx->user, nr_pages);
7186 if (ret)
7187 goto err;
7190 ret = 0;
7191 if (!pages || nr_pages > got_pages) {
7192 kvfree(vmas);
7193 kvfree(pages);
7194 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
7195 GFP_KERNEL);
7196 vmas = kvmalloc_array(nr_pages,
7197 sizeof(struct vm_area_struct *),
7198 GFP_KERNEL);
7199 if (!pages || !vmas) {
7200 ret = -ENOMEM;
7201 if (ctx->account_mem)
7202 io_unaccount_mem(ctx->user, nr_pages);
7203 goto err;
7205 got_pages = nr_pages;
7208 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
7209 GFP_KERNEL);
7210 ret = -ENOMEM;
7211 if (!imu->bvec) {
7212 if (ctx->account_mem)
7213 io_unaccount_mem(ctx->user, nr_pages);
7214 goto err;
7217 ret = 0;
7218 down_read(&current->mm->mmap_sem);
7219 pret = pin_user_pages(ubuf, nr_pages,
7220 FOLL_WRITE | FOLL_LONGTERM,
7221 pages, vmas);
7222 if (pret == nr_pages) {
7223 /* don't support file backed memory */
7224 for (j = 0; j < nr_pages; j++) {
7225 struct vm_area_struct *vma = vmas[j];
7227 if (vma->vm_file &&
7228 !is_file_hugepages(vma->vm_file)) {
7229 ret = -EOPNOTSUPP;
7230 break;
7233 } else {
7234 ret = pret < 0 ? pret : -EFAULT;
7236 up_read(&current->mm->mmap_sem);
7237 if (ret) {
7239 * if we did partial map, or found file backed vmas,
7240 * release any pages we did get
7242 if (pret > 0)
7243 unpin_user_pages(pages, pret);
7244 if (ctx->account_mem)
7245 io_unaccount_mem(ctx->user, nr_pages);
7246 kvfree(imu->bvec);
7247 goto err;
7250 off = ubuf & ~PAGE_MASK;
7251 size = iov.iov_len;
7252 for (j = 0; j < nr_pages; j++) {
7253 size_t vec_len;
7255 vec_len = min_t(size_t, size, PAGE_SIZE - off);
7256 imu->bvec[j].bv_page = pages[j];
7257 imu->bvec[j].bv_len = vec_len;
7258 imu->bvec[j].bv_offset = off;
7259 off = 0;
7260 size -= vec_len;
7262 /* store original address for later verification */
7263 imu->ubuf = ubuf;
7264 imu->len = iov.iov_len;
7265 imu->nr_bvecs = nr_pages;
7267 ctx->nr_user_bufs++;
7269 kvfree(pages);
7270 kvfree(vmas);
7271 return 0;
7272 err:
7273 kvfree(pages);
7274 kvfree(vmas);
7275 io_sqe_buffer_unregister(ctx);
7276 return ret;
7279 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
7281 __s32 __user *fds = arg;
7282 int fd;
7284 if (ctx->cq_ev_fd)
7285 return -EBUSY;
7287 if (copy_from_user(&fd, fds, sizeof(*fds)))
7288 return -EFAULT;
7290 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
7291 if (IS_ERR(ctx->cq_ev_fd)) {
7292 int ret = PTR_ERR(ctx->cq_ev_fd);
7293 ctx->cq_ev_fd = NULL;
7294 return ret;
7297 return 0;
7300 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
7302 if (ctx->cq_ev_fd) {
7303 eventfd_ctx_put(ctx->cq_ev_fd);
7304 ctx->cq_ev_fd = NULL;
7305 return 0;
7308 return -ENXIO;
7311 static int __io_destroy_buffers(int id, void *p, void *data)
7313 struct io_ring_ctx *ctx = data;
7314 struct io_buffer *buf = p;
7316 __io_remove_buffers(ctx, buf, id, -1U);
7317 return 0;
7320 static void io_destroy_buffers(struct io_ring_ctx *ctx)
7322 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
7323 idr_destroy(&ctx->io_buffer_idr);
7326 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
7328 io_finish_async(ctx);
7329 if (ctx->sqo_mm)
7330 mmdrop(ctx->sqo_mm);
7332 io_iopoll_reap_events(ctx);
7333 io_sqe_buffer_unregister(ctx);
7334 io_sqe_files_unregister(ctx);
7335 io_eventfd_unregister(ctx);
7336 io_destroy_buffers(ctx);
7337 idr_destroy(&ctx->personality_idr);
7339 #if defined(CONFIG_UNIX)
7340 if (ctx->ring_sock) {
7341 ctx->ring_sock->file = NULL; /* so that iput() is called */
7342 sock_release(ctx->ring_sock);
7344 #endif
7346 io_mem_free(ctx->rings);
7347 io_mem_free(ctx->sq_sqes);
7349 percpu_ref_exit(&ctx->refs);
7350 if (ctx->account_mem)
7351 io_unaccount_mem(ctx->user,
7352 ring_pages(ctx->sq_entries, ctx->cq_entries));
7353 free_uid(ctx->user);
7354 put_cred(ctx->creds);
7355 kfree(ctx->completions);
7356 kfree(ctx->cancel_hash);
7357 kmem_cache_free(req_cachep, ctx->fallback_req);
7358 kfree(ctx);
7361 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
7363 struct io_ring_ctx *ctx = file->private_data;
7364 __poll_t mask = 0;
7366 poll_wait(file, &ctx->cq_wait, wait);
7368 * synchronizes with barrier from wq_has_sleeper call in
7369 * io_commit_cqring
7371 smp_rmb();
7372 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
7373 ctx->rings->sq_ring_entries)
7374 mask |= EPOLLOUT | EPOLLWRNORM;
7375 if (io_cqring_events(ctx, false))
7376 mask |= EPOLLIN | EPOLLRDNORM;
7378 return mask;
7381 static int io_uring_fasync(int fd, struct file *file, int on)
7383 struct io_ring_ctx *ctx = file->private_data;
7385 return fasync_helper(fd, file, on, &ctx->cq_fasync);
7388 static int io_remove_personalities(int id, void *p, void *data)
7390 struct io_ring_ctx *ctx = data;
7391 const struct cred *cred;
7393 cred = idr_remove(&ctx->personality_idr, id);
7394 if (cred)
7395 put_cred(cred);
7396 return 0;
7399 static void io_ring_exit_work(struct work_struct *work)
7401 struct io_ring_ctx *ctx;
7403 ctx = container_of(work, struct io_ring_ctx, exit_work);
7404 if (ctx->rings)
7405 io_cqring_overflow_flush(ctx, true);
7408 * If we're doing polled IO and end up having requests being
7409 * submitted async (out-of-line), then completions can come in while
7410 * we're waiting for refs to drop. We need to reap these manually,
7411 * as nobody else will be looking for them.
7413 while (!wait_for_completion_timeout(&ctx->completions[0], HZ/20)) {
7414 io_iopoll_reap_events(ctx);
7415 if (ctx->rings)
7416 io_cqring_overflow_flush(ctx, true);
7418 io_ring_ctx_free(ctx);
7421 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
7423 mutex_lock(&ctx->uring_lock);
7424 percpu_ref_kill(&ctx->refs);
7425 mutex_unlock(&ctx->uring_lock);
7428 * Wait for sq thread to idle, if we have one. It won't spin on new
7429 * work after we've killed the ctx ref above. This is important to do
7430 * before we cancel existing commands, as the thread could otherwise
7431 * be queueing new work post that. If that's work we need to cancel,
7432 * it could cause shutdown to hang.
7434 while (ctx->sqo_thread && !wq_has_sleeper(&ctx->sqo_wait))
7435 cond_resched();
7437 io_kill_timeouts(ctx);
7438 io_poll_remove_all(ctx);
7440 if (ctx->io_wq)
7441 io_wq_cancel_all(ctx->io_wq);
7443 io_iopoll_reap_events(ctx);
7444 /* if we failed setting up the ctx, we might not have any rings */
7445 if (ctx->rings)
7446 io_cqring_overflow_flush(ctx, true);
7447 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
7448 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
7449 queue_work(system_wq, &ctx->exit_work);
7452 static int io_uring_release(struct inode *inode, struct file *file)
7454 struct io_ring_ctx *ctx = file->private_data;
7456 file->private_data = NULL;
7457 io_ring_ctx_wait_and_kill(ctx);
7458 return 0;
7461 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
7462 struct files_struct *files)
7464 while (!list_empty_careful(&ctx->inflight_list)) {
7465 struct io_kiocb *cancel_req = NULL, *req;
7466 DEFINE_WAIT(wait);
7468 spin_lock_irq(&ctx->inflight_lock);
7469 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
7470 if (req->work.files != files)
7471 continue;
7472 /* req is being completed, ignore */
7473 if (!refcount_inc_not_zero(&req->refs))
7474 continue;
7475 cancel_req = req;
7476 break;
7478 if (cancel_req)
7479 prepare_to_wait(&ctx->inflight_wait, &wait,
7480 TASK_UNINTERRUPTIBLE);
7481 spin_unlock_irq(&ctx->inflight_lock);
7483 /* We need to keep going until we don't find a matching req */
7484 if (!cancel_req)
7485 break;
7487 if (cancel_req->flags & REQ_F_OVERFLOW) {
7488 spin_lock_irq(&ctx->completion_lock);
7489 list_del(&cancel_req->list);
7490 cancel_req->flags &= ~REQ_F_OVERFLOW;
7491 if (list_empty(&ctx->cq_overflow_list)) {
7492 clear_bit(0, &ctx->sq_check_overflow);
7493 clear_bit(0, &ctx->cq_check_overflow);
7495 spin_unlock_irq(&ctx->completion_lock);
7497 WRITE_ONCE(ctx->rings->cq_overflow,
7498 atomic_inc_return(&ctx->cached_cq_overflow));
7501 * Put inflight ref and overflow ref. If that's
7502 * all we had, then we're done with this request.
7504 if (refcount_sub_and_test(2, &cancel_req->refs)) {
7505 io_free_req(cancel_req);
7506 finish_wait(&ctx->inflight_wait, &wait);
7507 continue;
7509 } else {
7510 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
7511 io_put_req(cancel_req);
7514 schedule();
7515 finish_wait(&ctx->inflight_wait, &wait);
7519 static int io_uring_flush(struct file *file, void *data)
7521 struct io_ring_ctx *ctx = file->private_data;
7523 io_uring_cancel_files(ctx, data);
7526 * If the task is going away, cancel work it may have pending
7528 if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
7529 io_wq_cancel_pid(ctx->io_wq, task_pid_vnr(current));
7531 return 0;
7534 static void *io_uring_validate_mmap_request(struct file *file,
7535 loff_t pgoff, size_t sz)
7537 struct io_ring_ctx *ctx = file->private_data;
7538 loff_t offset = pgoff << PAGE_SHIFT;
7539 struct page *page;
7540 void *ptr;
7542 switch (offset) {
7543 case IORING_OFF_SQ_RING:
7544 case IORING_OFF_CQ_RING:
7545 ptr = ctx->rings;
7546 break;
7547 case IORING_OFF_SQES:
7548 ptr = ctx->sq_sqes;
7549 break;
7550 default:
7551 return ERR_PTR(-EINVAL);
7554 page = virt_to_head_page(ptr);
7555 if (sz > page_size(page))
7556 return ERR_PTR(-EINVAL);
7558 return ptr;
7561 #ifdef CONFIG_MMU
7563 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
7565 size_t sz = vma->vm_end - vma->vm_start;
7566 unsigned long pfn;
7567 void *ptr;
7569 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
7570 if (IS_ERR(ptr))
7571 return PTR_ERR(ptr);
7573 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
7574 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
7577 #else /* !CONFIG_MMU */
7579 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
7581 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
7584 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
7586 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
7589 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
7590 unsigned long addr, unsigned long len,
7591 unsigned long pgoff, unsigned long flags)
7593 void *ptr;
7595 ptr = io_uring_validate_mmap_request(file, pgoff, len);
7596 if (IS_ERR(ptr))
7597 return PTR_ERR(ptr);
7599 return (unsigned long) ptr;
7602 #endif /* !CONFIG_MMU */
7604 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
7605 u32, min_complete, u32, flags, const sigset_t __user *, sig,
7606 size_t, sigsz)
7608 struct io_ring_ctx *ctx;
7609 long ret = -EBADF;
7610 int submitted = 0;
7611 struct fd f;
7613 if (current->task_works)
7614 task_work_run();
7616 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
7617 return -EINVAL;
7619 f = fdget(fd);
7620 if (!f.file)
7621 return -EBADF;
7623 ret = -EOPNOTSUPP;
7624 if (f.file->f_op != &io_uring_fops)
7625 goto out_fput;
7627 ret = -ENXIO;
7628 ctx = f.file->private_data;
7629 if (!percpu_ref_tryget(&ctx->refs))
7630 goto out_fput;
7633 * For SQ polling, the thread will do all submissions and completions.
7634 * Just return the requested submit count, and wake the thread if
7635 * we were asked to.
7637 ret = 0;
7638 if (ctx->flags & IORING_SETUP_SQPOLL) {
7639 if (!list_empty_careful(&ctx->cq_overflow_list))
7640 io_cqring_overflow_flush(ctx, false);
7641 if (flags & IORING_ENTER_SQ_WAKEUP)
7642 wake_up(&ctx->sqo_wait);
7643 submitted = to_submit;
7644 } else if (to_submit) {
7645 mutex_lock(&ctx->uring_lock);
7646 submitted = io_submit_sqes(ctx, to_submit, f.file, fd, false);
7647 mutex_unlock(&ctx->uring_lock);
7649 if (submitted != to_submit)
7650 goto out;
7652 if (flags & IORING_ENTER_GETEVENTS) {
7653 unsigned nr_events = 0;
7655 min_complete = min(min_complete, ctx->cq_entries);
7658 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
7659 * space applications don't need to do io completion events
7660 * polling again, they can rely on io_sq_thread to do polling
7661 * work, which can reduce cpu usage and uring_lock contention.
7663 if (ctx->flags & IORING_SETUP_IOPOLL &&
7664 !(ctx->flags & IORING_SETUP_SQPOLL)) {
7665 ret = io_iopoll_check(ctx, &nr_events, min_complete);
7666 } else {
7667 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
7671 out:
7672 percpu_ref_put(&ctx->refs);
7673 out_fput:
7674 fdput(f);
7675 return submitted ? submitted : ret;
7678 #ifdef CONFIG_PROC_FS
7679 static int io_uring_show_cred(int id, void *p, void *data)
7681 const struct cred *cred = p;
7682 struct seq_file *m = data;
7683 struct user_namespace *uns = seq_user_ns(m);
7684 struct group_info *gi;
7685 kernel_cap_t cap;
7686 unsigned __capi;
7687 int g;
7689 seq_printf(m, "%5d\n", id);
7690 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
7691 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
7692 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
7693 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
7694 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
7695 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
7696 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
7697 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
7698 seq_puts(m, "\n\tGroups:\t");
7699 gi = cred->group_info;
7700 for (g = 0; g < gi->ngroups; g++) {
7701 seq_put_decimal_ull(m, g ? " " : "",
7702 from_kgid_munged(uns, gi->gid[g]));
7704 seq_puts(m, "\n\tCapEff:\t");
7705 cap = cred->cap_effective;
7706 CAP_FOR_EACH_U32(__capi)
7707 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
7708 seq_putc(m, '\n');
7709 return 0;
7712 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
7714 int i;
7716 mutex_lock(&ctx->uring_lock);
7717 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
7718 for (i = 0; i < ctx->nr_user_files; i++) {
7719 struct fixed_file_table *table;
7720 struct file *f;
7722 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7723 f = table->files[i & IORING_FILE_TABLE_MASK];
7724 if (f)
7725 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
7726 else
7727 seq_printf(m, "%5u: <none>\n", i);
7729 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
7730 for (i = 0; i < ctx->nr_user_bufs; i++) {
7731 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
7733 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
7734 (unsigned int) buf->len);
7736 if (!idr_is_empty(&ctx->personality_idr)) {
7737 seq_printf(m, "Personalities:\n");
7738 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
7740 seq_printf(m, "PollList:\n");
7741 spin_lock_irq(&ctx->completion_lock);
7742 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7743 struct hlist_head *list = &ctx->cancel_hash[i];
7744 struct io_kiocb *req;
7746 hlist_for_each_entry(req, list, hash_node)
7747 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
7748 req->task->task_works != NULL);
7750 spin_unlock_irq(&ctx->completion_lock);
7751 mutex_unlock(&ctx->uring_lock);
7754 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
7756 struct io_ring_ctx *ctx = f->private_data;
7758 if (percpu_ref_tryget(&ctx->refs)) {
7759 __io_uring_show_fdinfo(ctx, m);
7760 percpu_ref_put(&ctx->refs);
7763 #endif
7765 static const struct file_operations io_uring_fops = {
7766 .release = io_uring_release,
7767 .flush = io_uring_flush,
7768 .mmap = io_uring_mmap,
7769 #ifndef CONFIG_MMU
7770 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
7771 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
7772 #endif
7773 .poll = io_uring_poll,
7774 .fasync = io_uring_fasync,
7775 #ifdef CONFIG_PROC_FS
7776 .show_fdinfo = io_uring_show_fdinfo,
7777 #endif
7780 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
7781 struct io_uring_params *p)
7783 struct io_rings *rings;
7784 size_t size, sq_array_offset;
7786 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
7787 if (size == SIZE_MAX)
7788 return -EOVERFLOW;
7790 rings = io_mem_alloc(size);
7791 if (!rings)
7792 return -ENOMEM;
7794 ctx->rings = rings;
7795 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
7796 rings->sq_ring_mask = p->sq_entries - 1;
7797 rings->cq_ring_mask = p->cq_entries - 1;
7798 rings->sq_ring_entries = p->sq_entries;
7799 rings->cq_ring_entries = p->cq_entries;
7800 ctx->sq_mask = rings->sq_ring_mask;
7801 ctx->cq_mask = rings->cq_ring_mask;
7802 ctx->sq_entries = rings->sq_ring_entries;
7803 ctx->cq_entries = rings->cq_ring_entries;
7805 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
7806 if (size == SIZE_MAX) {
7807 io_mem_free(ctx->rings);
7808 ctx->rings = NULL;
7809 return -EOVERFLOW;
7812 ctx->sq_sqes = io_mem_alloc(size);
7813 if (!ctx->sq_sqes) {
7814 io_mem_free(ctx->rings);
7815 ctx->rings = NULL;
7816 return -ENOMEM;
7819 return 0;
7823 * Allocate an anonymous fd, this is what constitutes the application
7824 * visible backing of an io_uring instance. The application mmaps this
7825 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
7826 * we have to tie this fd to a socket for file garbage collection purposes.
7828 static int io_uring_get_fd(struct io_ring_ctx *ctx)
7830 struct file *file;
7831 int ret;
7833 #if defined(CONFIG_UNIX)
7834 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
7835 &ctx->ring_sock);
7836 if (ret)
7837 return ret;
7838 #endif
7840 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
7841 if (ret < 0)
7842 goto err;
7844 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
7845 O_RDWR | O_CLOEXEC);
7846 if (IS_ERR(file)) {
7847 put_unused_fd(ret);
7848 ret = PTR_ERR(file);
7849 goto err;
7852 #if defined(CONFIG_UNIX)
7853 ctx->ring_sock->file = file;
7854 #endif
7855 fd_install(ret, file);
7856 return ret;
7857 err:
7858 #if defined(CONFIG_UNIX)
7859 sock_release(ctx->ring_sock);
7860 ctx->ring_sock = NULL;
7861 #endif
7862 return ret;
7865 static int io_uring_create(unsigned entries, struct io_uring_params *p,
7866 struct io_uring_params __user *params)
7868 struct user_struct *user = NULL;
7869 struct io_ring_ctx *ctx;
7870 bool account_mem;
7871 int ret;
7873 if (!entries)
7874 return -EINVAL;
7875 if (entries > IORING_MAX_ENTRIES) {
7876 if (!(p->flags & IORING_SETUP_CLAMP))
7877 return -EINVAL;
7878 entries = IORING_MAX_ENTRIES;
7882 * Use twice as many entries for the CQ ring. It's possible for the
7883 * application to drive a higher depth than the size of the SQ ring,
7884 * since the sqes are only used at submission time. This allows for
7885 * some flexibility in overcommitting a bit. If the application has
7886 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
7887 * of CQ ring entries manually.
7889 p->sq_entries = roundup_pow_of_two(entries);
7890 if (p->flags & IORING_SETUP_CQSIZE) {
7892 * If IORING_SETUP_CQSIZE is set, we do the same roundup
7893 * to a power-of-two, if it isn't already. We do NOT impose
7894 * any cq vs sq ring sizing.
7896 if (p->cq_entries < p->sq_entries)
7897 return -EINVAL;
7898 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
7899 if (!(p->flags & IORING_SETUP_CLAMP))
7900 return -EINVAL;
7901 p->cq_entries = IORING_MAX_CQ_ENTRIES;
7903 p->cq_entries = roundup_pow_of_two(p->cq_entries);
7904 } else {
7905 p->cq_entries = 2 * p->sq_entries;
7908 user = get_uid(current_user());
7909 account_mem = !capable(CAP_IPC_LOCK);
7911 if (account_mem) {
7912 ret = io_account_mem(user,
7913 ring_pages(p->sq_entries, p->cq_entries));
7914 if (ret) {
7915 free_uid(user);
7916 return ret;
7920 ctx = io_ring_ctx_alloc(p);
7921 if (!ctx) {
7922 if (account_mem)
7923 io_unaccount_mem(user, ring_pages(p->sq_entries,
7924 p->cq_entries));
7925 free_uid(user);
7926 return -ENOMEM;
7928 ctx->compat = in_compat_syscall();
7929 ctx->account_mem = account_mem;
7930 ctx->user = user;
7931 ctx->creds = get_current_cred();
7933 ret = io_allocate_scq_urings(ctx, p);
7934 if (ret)
7935 goto err;
7937 ret = io_sq_offload_start(ctx, p);
7938 if (ret)
7939 goto err;
7941 memset(&p->sq_off, 0, sizeof(p->sq_off));
7942 p->sq_off.head = offsetof(struct io_rings, sq.head);
7943 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
7944 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
7945 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
7946 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
7947 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
7948 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
7950 memset(&p->cq_off, 0, sizeof(p->cq_off));
7951 p->cq_off.head = offsetof(struct io_rings, cq.head);
7952 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
7953 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
7954 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
7955 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
7956 p->cq_off.cqes = offsetof(struct io_rings, cqes);
7958 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
7959 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
7960 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL;
7962 if (copy_to_user(params, p, sizeof(*p))) {
7963 ret = -EFAULT;
7964 goto err;
7967 * Install ring fd as the very last thing, so we don't risk someone
7968 * having closed it before we finish setup
7970 ret = io_uring_get_fd(ctx);
7971 if (ret < 0)
7972 goto err;
7974 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
7975 return ret;
7976 err:
7977 io_ring_ctx_wait_and_kill(ctx);
7978 return ret;
7982 * Sets up an aio uring context, and returns the fd. Applications asks for a
7983 * ring size, we return the actual sq/cq ring sizes (among other things) in the
7984 * params structure passed in.
7986 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
7988 struct io_uring_params p;
7989 int i;
7991 if (copy_from_user(&p, params, sizeof(p)))
7992 return -EFAULT;
7993 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
7994 if (p.resv[i])
7995 return -EINVAL;
7998 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
7999 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
8000 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ))
8001 return -EINVAL;
8003 return io_uring_create(entries, &p, params);
8006 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
8007 struct io_uring_params __user *, params)
8009 return io_uring_setup(entries, params);
8012 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
8014 struct io_uring_probe *p;
8015 size_t size;
8016 int i, ret;
8018 size = struct_size(p, ops, nr_args);
8019 if (size == SIZE_MAX)
8020 return -EOVERFLOW;
8021 p = kzalloc(size, GFP_KERNEL);
8022 if (!p)
8023 return -ENOMEM;
8025 ret = -EFAULT;
8026 if (copy_from_user(p, arg, size))
8027 goto out;
8028 ret = -EINVAL;
8029 if (memchr_inv(p, 0, size))
8030 goto out;
8032 p->last_op = IORING_OP_LAST - 1;
8033 if (nr_args > IORING_OP_LAST)
8034 nr_args = IORING_OP_LAST;
8036 for (i = 0; i < nr_args; i++) {
8037 p->ops[i].op = i;
8038 if (!io_op_defs[i].not_supported)
8039 p->ops[i].flags = IO_URING_OP_SUPPORTED;
8041 p->ops_len = i;
8043 ret = 0;
8044 if (copy_to_user(arg, p, size))
8045 ret = -EFAULT;
8046 out:
8047 kfree(p);
8048 return ret;
8051 static int io_register_personality(struct io_ring_ctx *ctx)
8053 const struct cred *creds = get_current_cred();
8054 int id;
8056 id = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
8057 USHRT_MAX, GFP_KERNEL);
8058 if (id < 0)
8059 put_cred(creds);
8060 return id;
8063 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8065 const struct cred *old_creds;
8067 old_creds = idr_remove(&ctx->personality_idr, id);
8068 if (old_creds) {
8069 put_cred(old_creds);
8070 return 0;
8073 return -EINVAL;
8076 static bool io_register_op_must_quiesce(int op)
8078 switch (op) {
8079 case IORING_UNREGISTER_FILES:
8080 case IORING_REGISTER_FILES_UPDATE:
8081 case IORING_REGISTER_PROBE:
8082 case IORING_REGISTER_PERSONALITY:
8083 case IORING_UNREGISTER_PERSONALITY:
8084 return false;
8085 default:
8086 return true;
8090 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
8091 void __user *arg, unsigned nr_args)
8092 __releases(ctx->uring_lock)
8093 __acquires(ctx->uring_lock)
8095 int ret;
8098 * We're inside the ring mutex, if the ref is already dying, then
8099 * someone else killed the ctx or is already going through
8100 * io_uring_register().
8102 if (percpu_ref_is_dying(&ctx->refs))
8103 return -ENXIO;
8105 if (io_register_op_must_quiesce(opcode)) {
8106 percpu_ref_kill(&ctx->refs);
8109 * Drop uring mutex before waiting for references to exit. If
8110 * another thread is currently inside io_uring_enter() it might
8111 * need to grab the uring_lock to make progress. If we hold it
8112 * here across the drain wait, then we can deadlock. It's safe
8113 * to drop the mutex here, since no new references will come in
8114 * after we've killed the percpu ref.
8116 mutex_unlock(&ctx->uring_lock);
8117 ret = wait_for_completion_interruptible(&ctx->completions[0]);
8118 mutex_lock(&ctx->uring_lock);
8119 if (ret) {
8120 percpu_ref_resurrect(&ctx->refs);
8121 ret = -EINTR;
8122 goto out;
8126 switch (opcode) {
8127 case IORING_REGISTER_BUFFERS:
8128 ret = io_sqe_buffer_register(ctx, arg, nr_args);
8129 break;
8130 case IORING_UNREGISTER_BUFFERS:
8131 ret = -EINVAL;
8132 if (arg || nr_args)
8133 break;
8134 ret = io_sqe_buffer_unregister(ctx);
8135 break;
8136 case IORING_REGISTER_FILES:
8137 ret = io_sqe_files_register(ctx, arg, nr_args);
8138 break;
8139 case IORING_UNREGISTER_FILES:
8140 ret = -EINVAL;
8141 if (arg || nr_args)
8142 break;
8143 ret = io_sqe_files_unregister(ctx);
8144 break;
8145 case IORING_REGISTER_FILES_UPDATE:
8146 ret = io_sqe_files_update(ctx, arg, nr_args);
8147 break;
8148 case IORING_REGISTER_EVENTFD:
8149 case IORING_REGISTER_EVENTFD_ASYNC:
8150 ret = -EINVAL;
8151 if (nr_args != 1)
8152 break;
8153 ret = io_eventfd_register(ctx, arg);
8154 if (ret)
8155 break;
8156 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
8157 ctx->eventfd_async = 1;
8158 else
8159 ctx->eventfd_async = 0;
8160 break;
8161 case IORING_UNREGISTER_EVENTFD:
8162 ret = -EINVAL;
8163 if (arg || nr_args)
8164 break;
8165 ret = io_eventfd_unregister(ctx);
8166 break;
8167 case IORING_REGISTER_PROBE:
8168 ret = -EINVAL;
8169 if (!arg || nr_args > 256)
8170 break;
8171 ret = io_probe(ctx, arg, nr_args);
8172 break;
8173 case IORING_REGISTER_PERSONALITY:
8174 ret = -EINVAL;
8175 if (arg || nr_args)
8176 break;
8177 ret = io_register_personality(ctx);
8178 break;
8179 case IORING_UNREGISTER_PERSONALITY:
8180 ret = -EINVAL;
8181 if (arg)
8182 break;
8183 ret = io_unregister_personality(ctx, nr_args);
8184 break;
8185 default:
8186 ret = -EINVAL;
8187 break;
8190 if (io_register_op_must_quiesce(opcode)) {
8191 /* bring the ctx back to life */
8192 percpu_ref_reinit(&ctx->refs);
8193 out:
8194 reinit_completion(&ctx->completions[0]);
8196 return ret;
8199 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
8200 void __user *, arg, unsigned int, nr_args)
8202 struct io_ring_ctx *ctx;
8203 long ret = -EBADF;
8204 struct fd f;
8206 f = fdget(fd);
8207 if (!f.file)
8208 return -EBADF;
8210 ret = -EOPNOTSUPP;
8211 if (f.file->f_op != &io_uring_fops)
8212 goto out_fput;
8214 ctx = f.file->private_data;
8216 mutex_lock(&ctx->uring_lock);
8217 ret = __io_uring_register(ctx, opcode, arg, nr_args);
8218 mutex_unlock(&ctx->uring_lock);
8219 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
8220 ctx->cq_ev_fd != NULL, ret);
8221 out_fput:
8222 fdput(f);
8223 return ret;
8226 static int __init io_uring_init(void)
8228 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
8229 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
8230 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
8231 } while (0)
8233 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
8234 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
8235 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
8236 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
8237 BUILD_BUG_SQE_ELEM(1, __u8, flags);
8238 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
8239 BUILD_BUG_SQE_ELEM(4, __s32, fd);
8240 BUILD_BUG_SQE_ELEM(8, __u64, off);
8241 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
8242 BUILD_BUG_SQE_ELEM(16, __u64, addr);
8243 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
8244 BUILD_BUG_SQE_ELEM(24, __u32, len);
8245 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
8246 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
8247 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
8248 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
8249 BUILD_BUG_SQE_ELEM(28, __u16, poll_events);
8250 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
8251 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
8252 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
8253 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
8254 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
8255 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
8256 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
8257 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
8258 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
8259 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
8260 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
8261 BUILD_BUG_SQE_ELEM(42, __u16, personality);
8262 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
8264 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
8265 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
8266 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
8267 return 0;
8269 __initcall(io_uring_init);