1 // SPDX-License-Identifier: GPL-2.0
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
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
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
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>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/kthread.h>
61 #include <linux/blkdev.h>
62 #include <linux/bvec.h>
63 #include <linux/net.h>
65 #include <net/af_unix.h>
67 #include <linux/anon_inodes.h>
68 #include <linux/sched/mm.h>
69 #include <linux/uaccess.h>
70 #include <linux/nospec.h>
71 #include <linux/sizes.h>
72 #include <linux/hugetlb.h>
73 #include <linux/highmem.h>
74 #include <linux/namei.h>
75 #include <linux/fsnotify.h>
76 #include <linux/fadvise.h>
77 #include <linux/eventpoll.h>
78 #include <linux/fs_struct.h>
79 #include <linux/splice.h>
80 #include <linux/task_work.h>
81 #include <linux/pagemap.h>
82 #include <linux/io_uring.h>
83 #include <linux/blk-cgroup.h>
84 #include <linux/audit.h>
86 #define CREATE_TRACE_POINTS
87 #include <trace/events/io_uring.h>
89 #include <uapi/linux/io_uring.h>
94 #define IORING_MAX_ENTRIES 32768
95 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
98 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
100 #define IORING_FILE_TABLE_SHIFT 9
101 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
102 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
103 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
104 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
105 IORING_REGISTER_LAST + IORING_OP_LAST)
108 u32 head ____cacheline_aligned_in_smp;
109 u32 tail ____cacheline_aligned_in_smp;
113 * This data is shared with the application through the mmap at offsets
114 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
116 * The offsets to the member fields are published through struct
117 * io_sqring_offsets when calling io_uring_setup.
121 * Head and tail offsets into the ring; the offsets need to be
122 * masked to get valid indices.
124 * The kernel controls head of the sq ring and the tail of the cq ring,
125 * and the application controls tail of the sq ring and the head of the
128 struct io_uring sq, cq;
130 * Bitmasks to apply to head and tail offsets (constant, equals
133 u32 sq_ring_mask, cq_ring_mask;
134 /* Ring sizes (constant, power of 2) */
135 u32 sq_ring_entries, cq_ring_entries;
137 * Number of invalid entries dropped by the kernel due to
138 * invalid index stored in array
140 * Written by the kernel, shouldn't be modified by the
141 * application (i.e. get number of "new events" by comparing to
144 * After a new SQ head value was read by the application this
145 * counter includes all submissions that were dropped reaching
146 * the new SQ head (and possibly more).
152 * Written by the kernel, shouldn't be modified by the
155 * The application needs a full memory barrier before checking
156 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
162 * Written by the application, shouldn't be modified by the
167 * Number of completion events lost because the queue was full;
168 * this should be avoided by the application by making sure
169 * there are not more requests pending than there is space in
170 * the completion queue.
172 * Written by the kernel, shouldn't be modified by the
173 * application (i.e. get number of "new events" by comparing to
176 * As completion events come in out of order this counter is not
177 * ordered with any other data.
181 * Ring buffer of completion events.
183 * The kernel writes completion events fresh every time they are
184 * produced, so the application is allowed to modify pending
187 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
190 struct io_mapped_ubuf {
193 struct bio_vec *bvec;
194 unsigned int nr_bvecs;
195 unsigned long acct_pages;
199 struct list_head list;
203 struct fixed_rsrc_table {
207 struct fixed_rsrc_ref_node {
208 struct percpu_ref refs;
209 struct list_head node;
210 struct list_head rsrc_list;
211 struct fixed_rsrc_data *rsrc_data;
212 struct llist_node llist;
216 struct fixed_rsrc_data {
217 struct fixed_rsrc_table *table;
218 struct io_ring_ctx *ctx;
220 struct fixed_rsrc_ref_node *node;
221 struct percpu_ref refs;
222 struct completion done;
223 struct list_head ref_list;
228 struct list_head list;
234 struct io_restriction {
235 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
236 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
237 u8 sqe_flags_allowed;
238 u8 sqe_flags_required;
246 /* ctx's that are using this sqd */
247 struct list_head ctx_list;
248 struct list_head ctx_new_list;
249 struct mutex ctx_lock;
251 struct task_struct *thread;
252 struct wait_queue_head wait;
254 unsigned sq_thread_idle;
259 struct percpu_ref refs;
260 } ____cacheline_aligned_in_smp;
264 unsigned int compat: 1;
265 unsigned int limit_mem: 1;
266 unsigned int cq_overflow_flushed: 1;
267 unsigned int drain_next: 1;
268 unsigned int eventfd_async: 1;
269 unsigned int restricted: 1;
270 unsigned int sqo_dead: 1;
273 * Ring buffer of indices into array of io_uring_sqe, which is
274 * mmapped by the application using the IORING_OFF_SQES offset.
276 * This indirection could e.g. be used to assign fixed
277 * io_uring_sqe entries to operations and only submit them to
278 * the queue when needed.
280 * The kernel modifies neither the indices array nor the entries
284 unsigned cached_sq_head;
287 unsigned sq_thread_idle;
288 unsigned cached_sq_dropped;
289 unsigned cached_cq_overflow;
290 unsigned long sq_check_overflow;
292 struct list_head defer_list;
293 struct list_head timeout_list;
294 struct list_head cq_overflow_list;
296 struct io_uring_sqe *sq_sqes;
297 } ____cacheline_aligned_in_smp;
299 struct io_rings *rings;
305 * For SQPOLL usage - we hold a reference to the parent task, so we
306 * have access to the ->files
308 struct task_struct *sqo_task;
310 /* Only used for accounting purposes */
311 struct mm_struct *mm_account;
313 #ifdef CONFIG_BLK_CGROUP
314 struct cgroup_subsys_state *sqo_blkcg_css;
317 struct io_sq_data *sq_data; /* if using sq thread polling */
319 struct wait_queue_head sqo_sq_wait;
320 struct list_head sqd_list;
323 * If used, fixed file set. Writers must ensure that ->refs is dead,
324 * readers must ensure that ->refs is alive as long as the file* is
325 * used. Only updated through io_uring_register(2).
327 struct fixed_rsrc_data *file_data;
328 unsigned nr_user_files;
330 /* if used, fixed mapped user buffers */
331 unsigned nr_user_bufs;
332 struct io_mapped_ubuf *user_bufs;
334 struct user_struct *user;
336 const struct cred *creds;
340 unsigned int sessionid;
343 struct completion ref_comp;
344 struct completion sq_thread_comp;
346 /* if all else fails... */
347 struct io_kiocb *fallback_req;
349 #if defined(CONFIG_UNIX)
350 struct socket *ring_sock;
353 struct idr io_buffer_idr;
355 struct idr personality_idr;
358 unsigned cached_cq_tail;
361 atomic_t cq_timeouts;
362 unsigned cq_last_tm_flush;
363 unsigned long cq_check_overflow;
364 struct wait_queue_head cq_wait;
365 struct fasync_struct *cq_fasync;
366 struct eventfd_ctx *cq_ev_fd;
367 } ____cacheline_aligned_in_smp;
370 struct mutex uring_lock;
371 wait_queue_head_t wait;
372 } ____cacheline_aligned_in_smp;
375 spinlock_t completion_lock;
378 * ->iopoll_list is protected by the ctx->uring_lock for
379 * io_uring instances that don't use IORING_SETUP_SQPOLL.
380 * For SQPOLL, only the single threaded io_sq_thread() will
381 * manipulate the list, hence no extra locking is needed there.
383 struct list_head iopoll_list;
384 struct hlist_head *cancel_hash;
385 unsigned cancel_hash_bits;
386 bool poll_multi_file;
388 spinlock_t inflight_lock;
389 struct list_head inflight_list;
390 } ____cacheline_aligned_in_smp;
392 struct delayed_work rsrc_put_work;
393 struct llist_head rsrc_put_llist;
395 struct work_struct exit_work;
396 struct io_restriction restrictions;
400 * First field must be the file pointer in all the
401 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
403 struct io_poll_iocb {
405 struct wait_queue_head *head;
409 struct wait_queue_entry wait;
412 struct io_poll_remove {
419 struct file *put_file;
423 struct io_timeout_data {
424 struct io_kiocb *req;
425 struct hrtimer timer;
426 struct timespec64 ts;
427 enum hrtimer_mode mode;
432 struct sockaddr __user *addr;
433 int __user *addr_len;
435 unsigned long nofile;
455 struct list_head list;
456 /* head of the link, used by linked timeouts only */
457 struct io_kiocb *head;
460 struct io_timeout_rem {
465 struct timespec64 ts;
470 /* NOTE: kiocb has the file as the first member, so don't do it here */
478 struct sockaddr __user *addr;
485 struct user_msghdr __user *umsg;
491 struct io_buffer *kbuf;
497 struct filename *filename;
499 unsigned long nofile;
502 struct io_rsrc_update {
528 struct epoll_event event;
532 struct file *file_out;
533 struct file *file_in;
540 struct io_provide_buf {
554 const char __user *filename;
555 struct statx __user *buffer;
567 struct filename *oldpath;
568 struct filename *newpath;
576 struct filename *filename;
579 struct io_completion {
581 struct list_head list;
585 struct io_async_connect {
586 struct sockaddr_storage address;
589 struct io_async_msghdr {
590 struct iovec fast_iov[UIO_FASTIOV];
592 struct sockaddr __user *uaddr;
594 struct sockaddr_storage addr;
598 struct iovec fast_iov[UIO_FASTIOV];
599 const struct iovec *free_iovec;
600 struct iov_iter iter;
602 struct wait_page_queue wpq;
606 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
607 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
608 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
609 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
610 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
611 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
617 REQ_F_LINK_TIMEOUT_BIT,
619 REQ_F_NEED_CLEANUP_BIT,
621 REQ_F_BUFFER_SELECTED_BIT,
622 REQ_F_NO_FILE_TABLE_BIT,
623 REQ_F_WORK_INITIALIZED_BIT,
624 REQ_F_LTIMEOUT_ACTIVE_BIT,
626 /* not a real bit, just to check we're not overflowing the space */
632 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
633 /* drain existing IO first */
634 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
636 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
637 /* doesn't sever on completion < 0 */
638 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
640 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
641 /* IOSQE_BUFFER_SELECT */
642 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
644 /* fail rest of links */
645 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
646 /* on inflight list */
647 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
648 /* read/write uses file position */
649 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
650 /* must not punt to workers */
651 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
652 /* has or had linked timeout */
653 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
655 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
657 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
658 /* already went through poll handler */
659 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
660 /* buffer already selected */
661 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
662 /* doesn't need file table for this request */
663 REQ_F_NO_FILE_TABLE = BIT(REQ_F_NO_FILE_TABLE_BIT),
664 /* io_wq_work is initialized */
665 REQ_F_WORK_INITIALIZED = BIT(REQ_F_WORK_INITIALIZED_BIT),
666 /* linked timeout is active, i.e. prepared by link's head */
667 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
671 struct io_poll_iocb poll;
672 struct io_poll_iocb *double_poll;
676 * NOTE! Each of the iocb union members has the file pointer
677 * as the first entry in their struct definition. So you can
678 * access the file pointer through any of the sub-structs,
679 * or directly as just 'ki_filp' in this struct.
685 struct io_poll_iocb poll;
686 struct io_poll_remove poll_remove;
687 struct io_accept accept;
689 struct io_cancel cancel;
690 struct io_timeout timeout;
691 struct io_timeout_rem timeout_rem;
692 struct io_connect connect;
693 struct io_sr_msg sr_msg;
695 struct io_close close;
696 struct io_rsrc_update rsrc_update;
697 struct io_fadvise fadvise;
698 struct io_madvise madvise;
699 struct io_epoll epoll;
700 struct io_splice splice;
701 struct io_provide_buf pbuf;
702 struct io_statx statx;
703 struct io_shutdown shutdown;
704 struct io_rename rename;
705 struct io_unlink unlink;
706 /* use only after cleaning per-op data, see io_clean_op() */
707 struct io_completion compl;
710 /* opcode allocated if it needs to store data for async defer */
713 /* polled IO has completed */
719 struct io_ring_ctx *ctx;
722 struct task_struct *task;
725 struct io_kiocb *link;
726 struct percpu_ref *fixed_rsrc_refs;
729 * 1. used with ctx->iopoll_list with reads/writes
730 * 2. to track reqs with ->files (see io_op_def::file_table)
732 struct list_head inflight_entry;
733 struct callback_head task_work;
734 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
735 struct hlist_node hash_node;
736 struct async_poll *apoll;
737 struct io_wq_work work;
740 struct io_defer_entry {
741 struct list_head list;
742 struct io_kiocb *req;
746 #define IO_IOPOLL_BATCH 8
748 struct io_comp_state {
750 struct list_head list;
751 struct io_ring_ctx *ctx;
754 struct io_submit_state {
755 struct blk_plug plug;
758 * io_kiocb alloc cache
760 void *reqs[IO_IOPOLL_BATCH];
761 unsigned int free_reqs;
766 * Batch completion logic
768 struct io_comp_state comp;
771 * File reference cache
775 unsigned int file_refs;
776 unsigned int ios_left;
780 /* needs req->file assigned */
781 unsigned needs_file : 1;
782 /* don't fail if file grab fails */
783 unsigned needs_file_no_error : 1;
784 /* hash wq insertion if file is a regular file */
785 unsigned hash_reg_file : 1;
786 /* unbound wq insertion if file is a non-regular file */
787 unsigned unbound_nonreg_file : 1;
788 /* opcode is not supported by this kernel */
789 unsigned not_supported : 1;
790 /* set if opcode supports polled "wait" */
792 unsigned pollout : 1;
793 /* op supports buffer selection */
794 unsigned buffer_select : 1;
795 /* must always have async data allocated */
796 unsigned needs_async_data : 1;
797 /* should block plug */
799 /* size of async data needed, if any */
800 unsigned short async_size;
804 static const struct io_op_def io_op_defs[] = {
805 [IORING_OP_NOP] = {},
806 [IORING_OP_READV] = {
808 .unbound_nonreg_file = 1,
811 .needs_async_data = 1,
813 .async_size = sizeof(struct io_async_rw),
814 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
816 [IORING_OP_WRITEV] = {
819 .unbound_nonreg_file = 1,
821 .needs_async_data = 1,
823 .async_size = sizeof(struct io_async_rw),
824 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG |
827 [IORING_OP_FSYNC] = {
829 .work_flags = IO_WQ_WORK_BLKCG,
831 [IORING_OP_READ_FIXED] = {
833 .unbound_nonreg_file = 1,
836 .async_size = sizeof(struct io_async_rw),
837 .work_flags = IO_WQ_WORK_BLKCG | IO_WQ_WORK_MM,
839 [IORING_OP_WRITE_FIXED] = {
842 .unbound_nonreg_file = 1,
845 .async_size = sizeof(struct io_async_rw),
846 .work_flags = IO_WQ_WORK_BLKCG | IO_WQ_WORK_FSIZE |
849 [IORING_OP_POLL_ADD] = {
851 .unbound_nonreg_file = 1,
853 [IORING_OP_POLL_REMOVE] = {},
854 [IORING_OP_SYNC_FILE_RANGE] = {
856 .work_flags = IO_WQ_WORK_BLKCG,
858 [IORING_OP_SENDMSG] = {
860 .unbound_nonreg_file = 1,
862 .needs_async_data = 1,
863 .async_size = sizeof(struct io_async_msghdr),
864 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
866 [IORING_OP_RECVMSG] = {
868 .unbound_nonreg_file = 1,
871 .needs_async_data = 1,
872 .async_size = sizeof(struct io_async_msghdr),
873 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
875 [IORING_OP_TIMEOUT] = {
876 .needs_async_data = 1,
877 .async_size = sizeof(struct io_timeout_data),
878 .work_flags = IO_WQ_WORK_MM,
880 [IORING_OP_TIMEOUT_REMOVE] = {
881 /* used by timeout updates' prep() */
882 .work_flags = IO_WQ_WORK_MM,
884 [IORING_OP_ACCEPT] = {
886 .unbound_nonreg_file = 1,
888 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_FILES,
890 [IORING_OP_ASYNC_CANCEL] = {},
891 [IORING_OP_LINK_TIMEOUT] = {
892 .needs_async_data = 1,
893 .async_size = sizeof(struct io_timeout_data),
894 .work_flags = IO_WQ_WORK_MM,
896 [IORING_OP_CONNECT] = {
898 .unbound_nonreg_file = 1,
900 .needs_async_data = 1,
901 .async_size = sizeof(struct io_async_connect),
902 .work_flags = IO_WQ_WORK_MM,
904 [IORING_OP_FALLOCATE] = {
906 .work_flags = IO_WQ_WORK_BLKCG | IO_WQ_WORK_FSIZE,
908 [IORING_OP_OPENAT] = {
909 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_BLKCG |
910 IO_WQ_WORK_FS | IO_WQ_WORK_MM,
912 [IORING_OP_CLOSE] = {
914 .needs_file_no_error = 1,
915 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_BLKCG,
917 [IORING_OP_FILES_UPDATE] = {
918 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_MM,
920 [IORING_OP_STATX] = {
921 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_MM |
922 IO_WQ_WORK_FS | IO_WQ_WORK_BLKCG,
926 .unbound_nonreg_file = 1,
930 .async_size = sizeof(struct io_async_rw),
931 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
933 [IORING_OP_WRITE] = {
935 .unbound_nonreg_file = 1,
938 .async_size = sizeof(struct io_async_rw),
939 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG |
942 [IORING_OP_FADVISE] = {
944 .work_flags = IO_WQ_WORK_BLKCG,
946 [IORING_OP_MADVISE] = {
947 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
951 .unbound_nonreg_file = 1,
953 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
957 .unbound_nonreg_file = 1,
960 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
962 [IORING_OP_OPENAT2] = {
963 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_FS |
964 IO_WQ_WORK_BLKCG | IO_WQ_WORK_MM,
966 [IORING_OP_EPOLL_CTL] = {
967 .unbound_nonreg_file = 1,
968 .work_flags = IO_WQ_WORK_FILES,
970 [IORING_OP_SPLICE] = {
973 .unbound_nonreg_file = 1,
974 .work_flags = IO_WQ_WORK_BLKCG,
976 [IORING_OP_PROVIDE_BUFFERS] = {},
977 [IORING_OP_REMOVE_BUFFERS] = {},
981 .unbound_nonreg_file = 1,
983 [IORING_OP_SHUTDOWN] = {
986 [IORING_OP_RENAMEAT] = {
987 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_FILES |
988 IO_WQ_WORK_FS | IO_WQ_WORK_BLKCG,
990 [IORING_OP_UNLINKAT] = {
991 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_FILES |
992 IO_WQ_WORK_FS | IO_WQ_WORK_BLKCG,
996 enum io_mem_account {
1001 static void __io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
1002 struct task_struct *task);
1004 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node);
1005 static struct fixed_rsrc_ref_node *alloc_fixed_file_ref_node(
1006 struct io_ring_ctx *ctx);
1008 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
1009 struct io_comp_state *cs);
1010 static void io_cqring_fill_event(struct io_kiocb *req, long res);
1011 static void io_put_req(struct io_kiocb *req);
1012 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1013 static void io_double_put_req(struct io_kiocb *req);
1014 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1015 static void __io_queue_linked_timeout(struct io_kiocb *req);
1016 static void io_queue_linked_timeout(struct io_kiocb *req);
1017 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
1018 struct io_uring_rsrc_update *ip,
1020 static void __io_clean_op(struct io_kiocb *req);
1021 static struct file *io_file_get(struct io_submit_state *state,
1022 struct io_kiocb *req, int fd, bool fixed);
1023 static void __io_queue_sqe(struct io_kiocb *req, struct io_comp_state *cs);
1024 static void io_rsrc_put_work(struct work_struct *work);
1026 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
1027 struct iovec **iovec, struct iov_iter *iter,
1029 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
1030 const struct iovec *fast_iov,
1031 struct iov_iter *iter, bool force);
1032 static void io_req_drop_files(struct io_kiocb *req);
1033 static void io_req_task_queue(struct io_kiocb *req);
1035 static struct kmem_cache *req_cachep;
1037 static const struct file_operations io_uring_fops;
1039 struct sock *io_uring_get_socket(struct file *file)
1041 #if defined(CONFIG_UNIX)
1042 if (file->f_op == &io_uring_fops) {
1043 struct io_ring_ctx *ctx = file->private_data;
1045 return ctx->ring_sock->sk;
1050 EXPORT_SYMBOL(io_uring_get_socket);
1052 #define io_for_each_link(pos, head) \
1053 for (pos = (head); pos; pos = pos->link)
1055 static inline void io_clean_op(struct io_kiocb *req)
1057 if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED))
1061 static inline void io_set_resource_node(struct io_kiocb *req)
1063 struct io_ring_ctx *ctx = req->ctx;
1065 if (!req->fixed_rsrc_refs) {
1066 req->fixed_rsrc_refs = &ctx->file_data->node->refs;
1067 percpu_ref_get(req->fixed_rsrc_refs);
1071 static bool io_match_task(struct io_kiocb *head,
1072 struct task_struct *task,
1073 struct files_struct *files)
1075 struct io_kiocb *req;
1077 if (task && head->task != task) {
1078 /* in terms of cancelation, always match if req task is dead */
1079 if (head->task->flags & PF_EXITING)
1086 io_for_each_link(req, head) {
1087 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1089 if (req->file && req->file->f_op == &io_uring_fops)
1091 if ((req->work.flags & IO_WQ_WORK_FILES) &&
1092 req->work.identity->files == files)
1098 static void io_sq_thread_drop_mm_files(void)
1100 struct files_struct *files = current->files;
1101 struct mm_struct *mm = current->mm;
1104 kthread_unuse_mm(mm);
1109 struct nsproxy *nsproxy = current->nsproxy;
1112 current->files = NULL;
1113 current->nsproxy = NULL;
1114 task_unlock(current);
1115 put_files_struct(files);
1116 put_nsproxy(nsproxy);
1120 static int __io_sq_thread_acquire_files(struct io_ring_ctx *ctx)
1122 if (current->flags & PF_EXITING)
1125 if (!current->files) {
1126 struct files_struct *files;
1127 struct nsproxy *nsproxy;
1129 task_lock(ctx->sqo_task);
1130 files = ctx->sqo_task->files;
1132 task_unlock(ctx->sqo_task);
1135 atomic_inc(&files->count);
1136 get_nsproxy(ctx->sqo_task->nsproxy);
1137 nsproxy = ctx->sqo_task->nsproxy;
1138 task_unlock(ctx->sqo_task);
1141 current->files = files;
1142 current->nsproxy = nsproxy;
1143 task_unlock(current);
1148 static int __io_sq_thread_acquire_mm(struct io_ring_ctx *ctx)
1150 struct mm_struct *mm;
1152 if (current->flags & PF_EXITING)
1157 /* Should never happen */
1158 if (unlikely(!(ctx->flags & IORING_SETUP_SQPOLL)))
1161 task_lock(ctx->sqo_task);
1162 mm = ctx->sqo_task->mm;
1163 if (unlikely(!mm || !mmget_not_zero(mm)))
1165 task_unlock(ctx->sqo_task);
1175 static int io_sq_thread_acquire_mm_files(struct io_ring_ctx *ctx,
1176 struct io_kiocb *req)
1178 const struct io_op_def *def = &io_op_defs[req->opcode];
1181 if (def->work_flags & IO_WQ_WORK_MM) {
1182 ret = __io_sq_thread_acquire_mm(ctx);
1187 if (def->needs_file || (def->work_flags & IO_WQ_WORK_FILES)) {
1188 ret = __io_sq_thread_acquire_files(ctx);
1196 static void io_sq_thread_associate_blkcg(struct io_ring_ctx *ctx,
1197 struct cgroup_subsys_state **cur_css)
1200 #ifdef CONFIG_BLK_CGROUP
1201 /* puts the old one when swapping */
1202 if (*cur_css != ctx->sqo_blkcg_css) {
1203 kthread_associate_blkcg(ctx->sqo_blkcg_css);
1204 *cur_css = ctx->sqo_blkcg_css;
1209 static void io_sq_thread_unassociate_blkcg(void)
1211 #ifdef CONFIG_BLK_CGROUP
1212 kthread_associate_blkcg(NULL);
1216 static inline void req_set_fail_links(struct io_kiocb *req)
1218 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1219 req->flags |= REQ_F_FAIL_LINK;
1223 * None of these are dereferenced, they are simply used to check if any of
1224 * them have changed. If we're under current and check they are still the
1225 * same, we're fine to grab references to them for actual out-of-line use.
1227 static void io_init_identity(struct io_identity *id)
1229 id->files = current->files;
1230 id->mm = current->mm;
1231 #ifdef CONFIG_BLK_CGROUP
1233 id->blkcg_css = blkcg_css();
1236 id->creds = current_cred();
1237 id->nsproxy = current->nsproxy;
1238 id->fs = current->fs;
1239 id->fsize = rlimit(RLIMIT_FSIZE);
1241 id->loginuid = current->loginuid;
1242 id->sessionid = current->sessionid;
1244 refcount_set(&id->count, 1);
1247 static inline void __io_req_init_async(struct io_kiocb *req)
1249 memset(&req->work, 0, sizeof(req->work));
1250 req->flags |= REQ_F_WORK_INITIALIZED;
1254 * Note: must call io_req_init_async() for the first time you
1255 * touch any members of io_wq_work.
1257 static inline void io_req_init_async(struct io_kiocb *req)
1259 struct io_uring_task *tctx = current->io_uring;
1261 if (req->flags & REQ_F_WORK_INITIALIZED)
1264 __io_req_init_async(req);
1266 /* Grab a ref if this isn't our static identity */
1267 req->work.identity = tctx->identity;
1268 if (tctx->identity != &tctx->__identity)
1269 refcount_inc(&req->work.identity->count);
1272 static inline bool io_async_submit(struct io_ring_ctx *ctx)
1274 return ctx->flags & IORING_SETUP_SQPOLL;
1277 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1279 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1281 complete(&ctx->ref_comp);
1284 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1286 return !req->timeout.off;
1289 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1291 struct io_ring_ctx *ctx;
1294 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1298 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
1299 if (!ctx->fallback_req)
1303 * Use 5 bits less than the max cq entries, that should give us around
1304 * 32 entries per hash list if totally full and uniformly spread.
1306 hash_bits = ilog2(p->cq_entries);
1310 ctx->cancel_hash_bits = hash_bits;
1311 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1313 if (!ctx->cancel_hash)
1315 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1317 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1318 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1321 ctx->flags = p->flags;
1322 init_waitqueue_head(&ctx->sqo_sq_wait);
1323 INIT_LIST_HEAD(&ctx->sqd_list);
1324 init_waitqueue_head(&ctx->cq_wait);
1325 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1326 init_completion(&ctx->ref_comp);
1327 init_completion(&ctx->sq_thread_comp);
1328 idr_init(&ctx->io_buffer_idr);
1329 idr_init(&ctx->personality_idr);
1330 mutex_init(&ctx->uring_lock);
1331 init_waitqueue_head(&ctx->wait);
1332 spin_lock_init(&ctx->completion_lock);
1333 INIT_LIST_HEAD(&ctx->iopoll_list);
1334 INIT_LIST_HEAD(&ctx->defer_list);
1335 INIT_LIST_HEAD(&ctx->timeout_list);
1336 spin_lock_init(&ctx->inflight_lock);
1337 INIT_LIST_HEAD(&ctx->inflight_list);
1338 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1339 init_llist_head(&ctx->rsrc_put_llist);
1342 if (ctx->fallback_req)
1343 kmem_cache_free(req_cachep, ctx->fallback_req);
1344 kfree(ctx->cancel_hash);
1349 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1351 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1352 struct io_ring_ctx *ctx = req->ctx;
1354 return seq != ctx->cached_cq_tail
1355 + READ_ONCE(ctx->cached_cq_overflow);
1361 static void __io_commit_cqring(struct io_ring_ctx *ctx)
1363 struct io_rings *rings = ctx->rings;
1365 /* order cqe stores with ring update */
1366 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
1369 static void io_put_identity(struct io_uring_task *tctx, struct io_kiocb *req)
1371 if (req->work.identity == &tctx->__identity)
1373 if (refcount_dec_and_test(&req->work.identity->count))
1374 kfree(req->work.identity);
1377 static void io_req_clean_work(struct io_kiocb *req)
1379 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1382 req->flags &= ~REQ_F_WORK_INITIALIZED;
1384 if (req->work.flags & IO_WQ_WORK_MM) {
1385 mmdrop(req->work.identity->mm);
1386 req->work.flags &= ~IO_WQ_WORK_MM;
1388 #ifdef CONFIG_BLK_CGROUP
1389 if (req->work.flags & IO_WQ_WORK_BLKCG) {
1390 css_put(req->work.identity->blkcg_css);
1391 req->work.flags &= ~IO_WQ_WORK_BLKCG;
1394 if (req->work.flags & IO_WQ_WORK_CREDS) {
1395 put_cred(req->work.identity->creds);
1396 req->work.flags &= ~IO_WQ_WORK_CREDS;
1398 if (req->work.flags & IO_WQ_WORK_FS) {
1399 struct fs_struct *fs = req->work.identity->fs;
1401 spin_lock(&req->work.identity->fs->lock);
1404 spin_unlock(&req->work.identity->fs->lock);
1407 req->work.flags &= ~IO_WQ_WORK_FS;
1409 if (req->flags & REQ_F_INFLIGHT)
1410 io_req_drop_files(req);
1412 io_put_identity(req->task->io_uring, req);
1416 * Create a private copy of io_identity, since some fields don't match
1417 * the current context.
1419 static bool io_identity_cow(struct io_kiocb *req)
1421 struct io_uring_task *tctx = current->io_uring;
1422 const struct cred *creds = NULL;
1423 struct io_identity *id;
1425 if (req->work.flags & IO_WQ_WORK_CREDS)
1426 creds = req->work.identity->creds;
1428 id = kmemdup(req->work.identity, sizeof(*id), GFP_KERNEL);
1429 if (unlikely(!id)) {
1430 req->work.flags |= IO_WQ_WORK_CANCEL;
1435 * We can safely just re-init the creds we copied Either the field
1436 * matches the current one, or we haven't grabbed it yet. The only
1437 * exception is ->creds, through registered personalities, so handle
1438 * that one separately.
1440 io_init_identity(id);
1444 /* add one for this request */
1445 refcount_inc(&id->count);
1447 /* drop tctx and req identity references, if needed */
1448 if (tctx->identity != &tctx->__identity &&
1449 refcount_dec_and_test(&tctx->identity->count))
1450 kfree(tctx->identity);
1451 if (req->work.identity != &tctx->__identity &&
1452 refcount_dec_and_test(&req->work.identity->count))
1453 kfree(req->work.identity);
1455 req->work.identity = id;
1456 tctx->identity = id;
1460 static bool io_grab_identity(struct io_kiocb *req)
1462 const struct io_op_def *def = &io_op_defs[req->opcode];
1463 struct io_identity *id = req->work.identity;
1464 struct io_ring_ctx *ctx = req->ctx;
1466 if (def->work_flags & IO_WQ_WORK_FSIZE) {
1467 if (id->fsize != rlimit(RLIMIT_FSIZE))
1469 req->work.flags |= IO_WQ_WORK_FSIZE;
1471 #ifdef CONFIG_BLK_CGROUP
1472 if (!(req->work.flags & IO_WQ_WORK_BLKCG) &&
1473 (def->work_flags & IO_WQ_WORK_BLKCG)) {
1475 if (id->blkcg_css != blkcg_css()) {
1480 * This should be rare, either the cgroup is dying or the task
1481 * is moving cgroups. Just punt to root for the handful of ios.
1483 if (css_tryget_online(id->blkcg_css))
1484 req->work.flags |= IO_WQ_WORK_BLKCG;
1488 if (!(req->work.flags & IO_WQ_WORK_CREDS)) {
1489 if (id->creds != current_cred())
1491 get_cred(id->creds);
1492 req->work.flags |= IO_WQ_WORK_CREDS;
1495 if (!uid_eq(current->loginuid, id->loginuid) ||
1496 current->sessionid != id->sessionid)
1499 if (!(req->work.flags & IO_WQ_WORK_FS) &&
1500 (def->work_flags & IO_WQ_WORK_FS)) {
1501 if (current->fs != id->fs)
1503 spin_lock(&id->fs->lock);
1504 if (!id->fs->in_exec) {
1506 req->work.flags |= IO_WQ_WORK_FS;
1508 req->work.flags |= IO_WQ_WORK_CANCEL;
1510 spin_unlock(¤t->fs->lock);
1512 if (!(req->work.flags & IO_WQ_WORK_FILES) &&
1513 (def->work_flags & IO_WQ_WORK_FILES) &&
1514 !(req->flags & REQ_F_NO_FILE_TABLE)) {
1515 if (id->files != current->files ||
1516 id->nsproxy != current->nsproxy)
1518 atomic_inc(&id->files->count);
1519 get_nsproxy(id->nsproxy);
1521 if (!(req->flags & REQ_F_INFLIGHT)) {
1522 req->flags |= REQ_F_INFLIGHT;
1524 spin_lock_irq(&ctx->inflight_lock);
1525 list_add(&req->inflight_entry, &ctx->inflight_list);
1526 spin_unlock_irq(&ctx->inflight_lock);
1528 req->work.flags |= IO_WQ_WORK_FILES;
1530 if (!(req->work.flags & IO_WQ_WORK_MM) &&
1531 (def->work_flags & IO_WQ_WORK_MM)) {
1532 if (id->mm != current->mm)
1535 req->work.flags |= IO_WQ_WORK_MM;
1541 static void io_prep_async_work(struct io_kiocb *req)
1543 const struct io_op_def *def = &io_op_defs[req->opcode];
1544 struct io_ring_ctx *ctx = req->ctx;
1546 io_req_init_async(req);
1548 if (req->flags & REQ_F_FORCE_ASYNC)
1549 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1551 if (req->flags & REQ_F_ISREG) {
1552 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1553 io_wq_hash_work(&req->work, file_inode(req->file));
1555 if (def->unbound_nonreg_file)
1556 req->work.flags |= IO_WQ_WORK_UNBOUND;
1559 /* if we fail grabbing identity, we must COW, regrab, and retry */
1560 if (io_grab_identity(req))
1563 if (!io_identity_cow(req))
1566 /* can't fail at this point */
1567 if (!io_grab_identity(req))
1571 static void io_prep_async_link(struct io_kiocb *req)
1573 struct io_kiocb *cur;
1575 io_for_each_link(cur, req)
1576 io_prep_async_work(cur);
1579 static struct io_kiocb *__io_queue_async_work(struct io_kiocb *req)
1581 struct io_ring_ctx *ctx = req->ctx;
1582 struct io_kiocb *link = io_prep_linked_timeout(req);
1584 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1585 &req->work, req->flags);
1586 io_wq_enqueue(ctx->io_wq, &req->work);
1590 static void io_queue_async_work(struct io_kiocb *req)
1592 struct io_kiocb *link;
1594 /* init ->work of the whole link before punting */
1595 io_prep_async_link(req);
1596 link = __io_queue_async_work(req);
1599 io_queue_linked_timeout(link);
1602 static void io_kill_timeout(struct io_kiocb *req)
1604 struct io_timeout_data *io = req->async_data;
1607 ret = hrtimer_try_to_cancel(&io->timer);
1609 atomic_set(&req->ctx->cq_timeouts,
1610 atomic_read(&req->ctx->cq_timeouts) + 1);
1611 list_del_init(&req->timeout.list);
1612 io_cqring_fill_event(req, 0);
1613 io_put_req_deferred(req, 1);
1618 * Returns true if we found and killed one or more timeouts
1620 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
1621 struct files_struct *files)
1623 struct io_kiocb *req, *tmp;
1626 spin_lock_irq(&ctx->completion_lock);
1627 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1628 if (io_match_task(req, tsk, files)) {
1629 io_kill_timeout(req);
1633 spin_unlock_irq(&ctx->completion_lock);
1634 return canceled != 0;
1637 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1640 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1641 struct io_defer_entry, list);
1643 if (req_need_defer(de->req, de->seq))
1645 list_del_init(&de->list);
1646 io_req_task_queue(de->req);
1648 } while (!list_empty(&ctx->defer_list));
1651 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1655 if (list_empty(&ctx->timeout_list))
1658 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1661 u32 events_needed, events_got;
1662 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1663 struct io_kiocb, timeout.list);
1665 if (io_is_timeout_noseq(req))
1669 * Since seq can easily wrap around over time, subtract
1670 * the last seq at which timeouts were flushed before comparing.
1671 * Assuming not more than 2^31-1 events have happened since,
1672 * these subtractions won't have wrapped, so we can check if
1673 * target is in [last_seq, current_seq] by comparing the two.
1675 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1676 events_got = seq - ctx->cq_last_tm_flush;
1677 if (events_got < events_needed)
1680 list_del_init(&req->timeout.list);
1681 io_kill_timeout(req);
1682 } while (!list_empty(&ctx->timeout_list));
1684 ctx->cq_last_tm_flush = seq;
1687 static void io_commit_cqring(struct io_ring_ctx *ctx)
1689 io_flush_timeouts(ctx);
1690 __io_commit_cqring(ctx);
1692 if (unlikely(!list_empty(&ctx->defer_list)))
1693 __io_queue_deferred(ctx);
1696 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1698 struct io_rings *r = ctx->rings;
1700 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1703 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1705 struct io_rings *rings = ctx->rings;
1708 tail = ctx->cached_cq_tail;
1710 * writes to the cq entry need to come after reading head; the
1711 * control dependency is enough as we're using WRITE_ONCE to
1714 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
1717 ctx->cached_cq_tail++;
1718 return &rings->cqes[tail & ctx->cq_mask];
1721 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1725 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1727 if (!ctx->eventfd_async)
1729 return io_wq_current_is_worker();
1732 static inline unsigned __io_cqring_events(struct io_ring_ctx *ctx)
1734 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1737 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1739 /* see waitqueue_active() comment */
1742 if (waitqueue_active(&ctx->wait))
1743 wake_up(&ctx->wait);
1744 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1745 wake_up(&ctx->sq_data->wait);
1746 if (io_should_trigger_evfd(ctx))
1747 eventfd_signal(ctx->cq_ev_fd, 1);
1748 if (waitqueue_active(&ctx->cq_wait)) {
1749 wake_up_interruptible(&ctx->cq_wait);
1750 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1754 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1756 /* see waitqueue_active() comment */
1759 if (ctx->flags & IORING_SETUP_SQPOLL) {
1760 if (waitqueue_active(&ctx->wait))
1761 wake_up(&ctx->wait);
1763 if (io_should_trigger_evfd(ctx))
1764 eventfd_signal(ctx->cq_ev_fd, 1);
1765 if (waitqueue_active(&ctx->cq_wait)) {
1766 wake_up_interruptible(&ctx->cq_wait);
1767 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1771 /* Returns true if there are no backlogged entries after the flush */
1772 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1773 struct task_struct *tsk,
1774 struct files_struct *files)
1776 struct io_rings *rings = ctx->rings;
1777 struct io_kiocb *req, *tmp;
1778 struct io_uring_cqe *cqe;
1779 unsigned long flags;
1780 bool all_flushed, posted;
1783 if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
1787 spin_lock_irqsave(&ctx->completion_lock, flags);
1788 list_for_each_entry_safe(req, tmp, &ctx->cq_overflow_list, compl.list) {
1789 if (!io_match_task(req, tsk, files))
1792 cqe = io_get_cqring(ctx);
1796 list_move(&req->compl.list, &list);
1798 WRITE_ONCE(cqe->user_data, req->user_data);
1799 WRITE_ONCE(cqe->res, req->result);
1800 WRITE_ONCE(cqe->flags, req->compl.cflags);
1802 ctx->cached_cq_overflow++;
1803 WRITE_ONCE(ctx->rings->cq_overflow,
1804 ctx->cached_cq_overflow);
1809 all_flushed = list_empty(&ctx->cq_overflow_list);
1811 clear_bit(0, &ctx->sq_check_overflow);
1812 clear_bit(0, &ctx->cq_check_overflow);
1813 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1817 io_commit_cqring(ctx);
1818 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1820 io_cqring_ev_posted(ctx);
1822 while (!list_empty(&list)) {
1823 req = list_first_entry(&list, struct io_kiocb, compl.list);
1824 list_del(&req->compl.list);
1831 static void io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1832 struct task_struct *tsk,
1833 struct files_struct *files)
1835 if (test_bit(0, &ctx->cq_check_overflow)) {
1836 /* iopoll syncs against uring_lock, not completion_lock */
1837 if (ctx->flags & IORING_SETUP_IOPOLL)
1838 mutex_lock(&ctx->uring_lock);
1839 __io_cqring_overflow_flush(ctx, force, tsk, files);
1840 if (ctx->flags & IORING_SETUP_IOPOLL)
1841 mutex_unlock(&ctx->uring_lock);
1845 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1847 struct io_ring_ctx *ctx = req->ctx;
1848 struct io_uring_cqe *cqe;
1850 trace_io_uring_complete(ctx, req->user_data, res);
1853 * If we can't get a cq entry, userspace overflowed the
1854 * submission (by quite a lot). Increment the overflow count in
1857 cqe = io_get_cqring(ctx);
1859 WRITE_ONCE(cqe->user_data, req->user_data);
1860 WRITE_ONCE(cqe->res, res);
1861 WRITE_ONCE(cqe->flags, cflags);
1862 } else if (ctx->cq_overflow_flushed ||
1863 atomic_read(&req->task->io_uring->in_idle)) {
1865 * If we're in ring overflow flush mode, or in task cancel mode,
1866 * then we cannot store the request for later flushing, we need
1867 * to drop it on the floor.
1869 ctx->cached_cq_overflow++;
1870 WRITE_ONCE(ctx->rings->cq_overflow, ctx->cached_cq_overflow);
1872 if (list_empty(&ctx->cq_overflow_list)) {
1873 set_bit(0, &ctx->sq_check_overflow);
1874 set_bit(0, &ctx->cq_check_overflow);
1875 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1879 req->compl.cflags = cflags;
1880 refcount_inc(&req->refs);
1881 list_add_tail(&req->compl.list, &ctx->cq_overflow_list);
1885 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1887 __io_cqring_fill_event(req, res, 0);
1890 static void io_cqring_add_event(struct io_kiocb *req, long res, long cflags)
1892 struct io_ring_ctx *ctx = req->ctx;
1893 unsigned long flags;
1895 spin_lock_irqsave(&ctx->completion_lock, flags);
1896 __io_cqring_fill_event(req, res, cflags);
1897 io_commit_cqring(ctx);
1898 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1900 io_cqring_ev_posted(ctx);
1903 static void io_submit_flush_completions(struct io_comp_state *cs)
1905 struct io_ring_ctx *ctx = cs->ctx;
1907 spin_lock_irq(&ctx->completion_lock);
1908 while (!list_empty(&cs->list)) {
1909 struct io_kiocb *req;
1911 req = list_first_entry(&cs->list, struct io_kiocb, compl.list);
1912 list_del(&req->compl.list);
1913 __io_cqring_fill_event(req, req->result, req->compl.cflags);
1916 * io_free_req() doesn't care about completion_lock unless one
1917 * of these flags is set. REQ_F_WORK_INITIALIZED is in the list
1918 * because of a potential deadlock with req->work.fs->lock
1920 if (req->flags & (REQ_F_FAIL_LINK|REQ_F_LINK_TIMEOUT
1921 |REQ_F_WORK_INITIALIZED)) {
1922 spin_unlock_irq(&ctx->completion_lock);
1924 spin_lock_irq(&ctx->completion_lock);
1929 io_commit_cqring(ctx);
1930 spin_unlock_irq(&ctx->completion_lock);
1932 io_cqring_ev_posted(ctx);
1936 static void __io_req_complete(struct io_kiocb *req, long res, unsigned cflags,
1937 struct io_comp_state *cs)
1940 io_cqring_add_event(req, res, cflags);
1945 req->compl.cflags = cflags;
1946 list_add_tail(&req->compl.list, &cs->list);
1948 io_submit_flush_completions(cs);
1952 static void io_req_complete(struct io_kiocb *req, long res)
1954 __io_req_complete(req, res, 0, NULL);
1957 static inline bool io_is_fallback_req(struct io_kiocb *req)
1959 return req == (struct io_kiocb *)
1960 ((unsigned long) req->ctx->fallback_req & ~1UL);
1963 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1965 struct io_kiocb *req;
1967 req = ctx->fallback_req;
1968 if (!test_and_set_bit_lock(0, (unsigned long *) &ctx->fallback_req))
1974 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx,
1975 struct io_submit_state *state)
1977 if (!state->free_reqs) {
1978 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1982 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1983 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1986 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1987 * retry single alloc to be on the safe side.
1989 if (unlikely(ret <= 0)) {
1990 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1991 if (!state->reqs[0])
1995 state->free_reqs = ret;
1999 return state->reqs[state->free_reqs];
2001 return io_get_fallback_req(ctx);
2004 static inline void io_put_file(struct io_kiocb *req, struct file *file,
2011 static void io_dismantle_req(struct io_kiocb *req)
2015 if (req->async_data)
2016 kfree(req->async_data);
2018 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
2019 if (req->fixed_rsrc_refs)
2020 percpu_ref_put(req->fixed_rsrc_refs);
2021 io_req_clean_work(req);
2024 static void __io_free_req(struct io_kiocb *req)
2026 struct io_uring_task *tctx = req->task->io_uring;
2027 struct io_ring_ctx *ctx = req->ctx;
2029 io_dismantle_req(req);
2031 percpu_counter_dec(&tctx->inflight);
2032 if (atomic_read(&tctx->in_idle))
2033 wake_up(&tctx->wait);
2034 put_task_struct(req->task);
2036 if (likely(!io_is_fallback_req(req)))
2037 kmem_cache_free(req_cachep, req);
2039 clear_bit_unlock(0, (unsigned long *) &ctx->fallback_req);
2040 percpu_ref_put(&ctx->refs);
2043 static inline void io_remove_next_linked(struct io_kiocb *req)
2045 struct io_kiocb *nxt = req->link;
2047 req->link = nxt->link;
2051 static void io_kill_linked_timeout(struct io_kiocb *req)
2053 struct io_ring_ctx *ctx = req->ctx;
2054 struct io_kiocb *link;
2055 bool cancelled = false;
2056 unsigned long flags;
2058 spin_lock_irqsave(&ctx->completion_lock, flags);
2062 * Can happen if a linked timeout fired and link had been like
2063 * req -> link t-out -> link t-out [-> ...]
2065 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
2066 struct io_timeout_data *io = link->async_data;
2069 io_remove_next_linked(req);
2070 link->timeout.head = NULL;
2071 ret = hrtimer_try_to_cancel(&io->timer);
2073 io_cqring_fill_event(link, -ECANCELED);
2074 io_commit_cqring(ctx);
2078 req->flags &= ~REQ_F_LINK_TIMEOUT;
2079 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2082 io_cqring_ev_posted(ctx);
2088 static void io_fail_links(struct io_kiocb *req)
2090 struct io_kiocb *link, *nxt;
2091 struct io_ring_ctx *ctx = req->ctx;
2092 unsigned long flags;
2094 spin_lock_irqsave(&ctx->completion_lock, flags);
2102 trace_io_uring_fail_link(req, link);
2103 io_cqring_fill_event(link, -ECANCELED);
2106 * It's ok to free under spinlock as they're not linked anymore,
2107 * but avoid REQ_F_WORK_INITIALIZED because it may deadlock on
2110 if (link->flags & REQ_F_WORK_INITIALIZED)
2111 io_put_req_deferred(link, 2);
2113 io_double_put_req(link);
2116 io_commit_cqring(ctx);
2117 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2119 io_cqring_ev_posted(ctx);
2122 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
2124 if (req->flags & REQ_F_LINK_TIMEOUT)
2125 io_kill_linked_timeout(req);
2128 * If LINK is set, we have dependent requests in this chain. If we
2129 * didn't fail this request, queue the first one up, moving any other
2130 * dependencies to the next request. In case of failure, fail the rest
2133 if (likely(!(req->flags & REQ_F_FAIL_LINK))) {
2134 struct io_kiocb *nxt = req->link;
2143 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2145 if (likely(!(req->link) && !(req->flags & REQ_F_LINK_TIMEOUT)))
2147 return __io_req_find_next(req);
2150 static int io_req_task_work_add(struct io_kiocb *req)
2152 struct task_struct *tsk = req->task;
2153 struct io_ring_ctx *ctx = req->ctx;
2154 enum task_work_notify_mode notify;
2157 if (tsk->flags & PF_EXITING)
2161 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2162 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2163 * processing task_work. There's no reliable way to tell if TWA_RESUME
2167 if (!(ctx->flags & IORING_SETUP_SQPOLL))
2168 notify = TWA_SIGNAL;
2170 ret = task_work_add(tsk, &req->task_work, notify);
2172 wake_up_process(tsk);
2177 static void __io_req_task_cancel(struct io_kiocb *req, int error)
2179 struct io_ring_ctx *ctx = req->ctx;
2181 spin_lock_irq(&ctx->completion_lock);
2182 io_cqring_fill_event(req, error);
2183 io_commit_cqring(ctx);
2184 spin_unlock_irq(&ctx->completion_lock);
2186 io_cqring_ev_posted(ctx);
2187 req_set_fail_links(req);
2188 io_double_put_req(req);
2191 static void io_req_task_cancel(struct callback_head *cb)
2193 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2194 struct io_ring_ctx *ctx = req->ctx;
2196 __io_req_task_cancel(req, -ECANCELED);
2197 percpu_ref_put(&ctx->refs);
2200 static void __io_req_task_submit(struct io_kiocb *req)
2202 struct io_ring_ctx *ctx = req->ctx;
2204 mutex_lock(&ctx->uring_lock);
2205 if (!ctx->sqo_dead &&
2206 !__io_sq_thread_acquire_mm(ctx) &&
2207 !__io_sq_thread_acquire_files(ctx))
2208 __io_queue_sqe(req, NULL);
2210 __io_req_task_cancel(req, -EFAULT);
2211 mutex_unlock(&ctx->uring_lock);
2214 static void io_req_task_submit(struct callback_head *cb)
2216 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2217 struct io_ring_ctx *ctx = req->ctx;
2219 __io_req_task_submit(req);
2220 percpu_ref_put(&ctx->refs);
2223 static void io_req_task_queue(struct io_kiocb *req)
2227 init_task_work(&req->task_work, io_req_task_submit);
2228 percpu_ref_get(&req->ctx->refs);
2230 ret = io_req_task_work_add(req);
2231 if (unlikely(ret)) {
2232 struct task_struct *tsk;
2234 init_task_work(&req->task_work, io_req_task_cancel);
2235 tsk = io_wq_get_task(req->ctx->io_wq);
2236 task_work_add(tsk, &req->task_work, TWA_NONE);
2237 wake_up_process(tsk);
2241 static inline void io_queue_next(struct io_kiocb *req)
2243 struct io_kiocb *nxt = io_req_find_next(req);
2246 io_req_task_queue(nxt);
2249 static void io_free_req(struct io_kiocb *req)
2256 void *reqs[IO_IOPOLL_BATCH];
2259 struct task_struct *task;
2263 static inline void io_init_req_batch(struct req_batch *rb)
2270 static void __io_req_free_batch_flush(struct io_ring_ctx *ctx,
2271 struct req_batch *rb)
2273 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
2274 percpu_ref_put_many(&ctx->refs, rb->to_free);
2278 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2279 struct req_batch *rb)
2282 __io_req_free_batch_flush(ctx, rb);
2284 struct io_uring_task *tctx = rb->task->io_uring;
2286 percpu_counter_sub(&tctx->inflight, rb->task_refs);
2287 if (atomic_read(&tctx->in_idle))
2288 wake_up(&tctx->wait);
2289 put_task_struct_many(rb->task, rb->task_refs);
2294 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req)
2296 if (unlikely(io_is_fallback_req(req))) {
2302 if (req->task != rb->task) {
2304 struct io_uring_task *tctx = rb->task->io_uring;
2306 percpu_counter_sub(&tctx->inflight, rb->task_refs);
2307 if (atomic_read(&tctx->in_idle))
2308 wake_up(&tctx->wait);
2309 put_task_struct_many(rb->task, rb->task_refs);
2311 rb->task = req->task;
2316 io_dismantle_req(req);
2317 rb->reqs[rb->to_free++] = req;
2318 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
2319 __io_req_free_batch_flush(req->ctx, rb);
2323 * Drop reference to request, return next in chain (if there is one) if this
2324 * was the last reference to this request.
2326 static struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2328 struct io_kiocb *nxt = NULL;
2330 if (refcount_dec_and_test(&req->refs)) {
2331 nxt = io_req_find_next(req);
2337 static void io_put_req(struct io_kiocb *req)
2339 if (refcount_dec_and_test(&req->refs))
2343 static void io_put_req_deferred_cb(struct callback_head *cb)
2345 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2350 static void io_free_req_deferred(struct io_kiocb *req)
2354 init_task_work(&req->task_work, io_put_req_deferred_cb);
2355 ret = io_req_task_work_add(req);
2356 if (unlikely(ret)) {
2357 struct task_struct *tsk;
2359 tsk = io_wq_get_task(req->ctx->io_wq);
2360 task_work_add(tsk, &req->task_work, TWA_NONE);
2361 wake_up_process(tsk);
2365 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2367 if (refcount_sub_and_test(refs, &req->refs))
2368 io_free_req_deferred(req);
2371 static struct io_wq_work *io_steal_work(struct io_kiocb *req)
2373 struct io_kiocb *nxt;
2376 * A ref is owned by io-wq in which context we're. So, if that's the
2377 * last one, it's safe to steal next work. False negatives are Ok,
2378 * it just will be re-punted async in io_put_work()
2380 if (refcount_read(&req->refs) != 1)
2383 nxt = io_req_find_next(req);
2384 return nxt ? &nxt->work : NULL;
2387 static void io_double_put_req(struct io_kiocb *req)
2389 /* drop both submit and complete references */
2390 if (refcount_sub_and_test(2, &req->refs))
2394 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2396 /* See comment at the top of this file */
2398 return __io_cqring_events(ctx);
2401 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2403 struct io_rings *rings = ctx->rings;
2405 /* make sure SQ entry isn't read before tail */
2406 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2409 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2411 unsigned int cflags;
2413 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2414 cflags |= IORING_CQE_F_BUFFER;
2415 req->flags &= ~REQ_F_BUFFER_SELECTED;
2420 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2422 struct io_buffer *kbuf;
2424 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2425 return io_put_kbuf(req, kbuf);
2428 static inline bool io_run_task_work(void)
2431 * Not safe to run on exiting task, and the task_work handling will
2432 * not add work to such a task.
2434 if (unlikely(current->flags & PF_EXITING))
2436 if (current->task_works) {
2437 __set_current_state(TASK_RUNNING);
2445 static void io_iopoll_queue(struct list_head *again)
2447 struct io_kiocb *req;
2450 req = list_first_entry(again, struct io_kiocb, inflight_entry);
2451 list_del(&req->inflight_entry);
2452 __io_complete_rw(req, -EAGAIN, 0, NULL);
2453 } while (!list_empty(again));
2457 * Find and free completed poll iocbs
2459 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2460 struct list_head *done)
2462 struct req_batch rb;
2463 struct io_kiocb *req;
2466 /* order with ->result store in io_complete_rw_iopoll() */
2469 io_init_req_batch(&rb);
2470 while (!list_empty(done)) {
2473 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2474 if (READ_ONCE(req->result) == -EAGAIN) {
2476 req->iopoll_completed = 0;
2477 list_move_tail(&req->inflight_entry, &again);
2480 list_del(&req->inflight_entry);
2482 if (req->flags & REQ_F_BUFFER_SELECTED)
2483 cflags = io_put_rw_kbuf(req);
2485 __io_cqring_fill_event(req, req->result, cflags);
2488 if (refcount_dec_and_test(&req->refs))
2489 io_req_free_batch(&rb, req);
2492 io_commit_cqring(ctx);
2493 io_cqring_ev_posted_iopoll(ctx);
2494 io_req_free_batch_finish(ctx, &rb);
2496 if (!list_empty(&again))
2497 io_iopoll_queue(&again);
2500 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2503 struct io_kiocb *req, *tmp;
2509 * Only spin for completions if we don't have multiple devices hanging
2510 * off our complete list, and we're under the requested amount.
2512 spin = !ctx->poll_multi_file && *nr_events < min;
2515 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2516 struct kiocb *kiocb = &req->rw.kiocb;
2519 * Move completed and retryable entries to our local lists.
2520 * If we find a request that requires polling, break out
2521 * and complete those lists first, if we have entries there.
2523 if (READ_ONCE(req->iopoll_completed)) {
2524 list_move_tail(&req->inflight_entry, &done);
2527 if (!list_empty(&done))
2530 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2534 /* iopoll may have completed current req */
2535 if (READ_ONCE(req->iopoll_completed))
2536 list_move_tail(&req->inflight_entry, &done);
2543 if (!list_empty(&done))
2544 io_iopoll_complete(ctx, nr_events, &done);
2550 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2551 * non-spinning poll check - we'll still enter the driver poll loop, but only
2552 * as a non-spinning completion check.
2554 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2557 while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2560 ret = io_do_iopoll(ctx, nr_events, min);
2563 if (*nr_events >= min)
2571 * We can't just wait for polled events to come to us, we have to actively
2572 * find and complete them.
2574 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2576 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2579 mutex_lock(&ctx->uring_lock);
2580 while (!list_empty(&ctx->iopoll_list)) {
2581 unsigned int nr_events = 0;
2583 io_do_iopoll(ctx, &nr_events, 0);
2585 /* let it sleep and repeat later if can't complete a request */
2589 * Ensure we allow local-to-the-cpu processing to take place,
2590 * in this case we need to ensure that we reap all events.
2591 * Also let task_work, etc. to progress by releasing the mutex
2593 if (need_resched()) {
2594 mutex_unlock(&ctx->uring_lock);
2596 mutex_lock(&ctx->uring_lock);
2599 mutex_unlock(&ctx->uring_lock);
2602 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2604 unsigned int nr_events = 0;
2605 int iters = 0, ret = 0;
2608 * We disallow the app entering submit/complete with polling, but we
2609 * still need to lock the ring to prevent racing with polled issue
2610 * that got punted to a workqueue.
2612 mutex_lock(&ctx->uring_lock);
2615 * Don't enter poll loop if we already have events pending.
2616 * If we do, we can potentially be spinning for commands that
2617 * already triggered a CQE (eg in error).
2619 if (test_bit(0, &ctx->cq_check_overflow))
2620 __io_cqring_overflow_flush(ctx, false, NULL, NULL);
2621 if (io_cqring_events(ctx))
2625 * If a submit got punted to a workqueue, we can have the
2626 * application entering polling for a command before it gets
2627 * issued. That app will hold the uring_lock for the duration
2628 * of the poll right here, so we need to take a breather every
2629 * now and then to ensure that the issue has a chance to add
2630 * the poll to the issued list. Otherwise we can spin here
2631 * forever, while the workqueue is stuck trying to acquire the
2634 if (!(++iters & 7)) {
2635 mutex_unlock(&ctx->uring_lock);
2637 mutex_lock(&ctx->uring_lock);
2640 ret = io_iopoll_getevents(ctx, &nr_events, min);
2644 } while (min && !nr_events && !need_resched());
2646 mutex_unlock(&ctx->uring_lock);
2650 static void kiocb_end_write(struct io_kiocb *req)
2653 * Tell lockdep we inherited freeze protection from submission
2656 if (req->flags & REQ_F_ISREG) {
2657 struct inode *inode = file_inode(req->file);
2659 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2661 file_end_write(req->file);
2664 static void io_complete_rw_common(struct kiocb *kiocb, long res,
2665 struct io_comp_state *cs)
2667 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2670 if (kiocb->ki_flags & IOCB_WRITE)
2671 kiocb_end_write(req);
2673 if (res != req->result)
2674 req_set_fail_links(req);
2675 if (req->flags & REQ_F_BUFFER_SELECTED)
2676 cflags = io_put_rw_kbuf(req);
2677 __io_req_complete(req, res, cflags, cs);
2681 static bool io_resubmit_prep(struct io_kiocb *req, int error)
2683 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2684 ssize_t ret = -ECANCELED;
2685 struct iov_iter iter;
2693 switch (req->opcode) {
2694 case IORING_OP_READV:
2695 case IORING_OP_READ_FIXED:
2696 case IORING_OP_READ:
2699 case IORING_OP_WRITEV:
2700 case IORING_OP_WRITE_FIXED:
2701 case IORING_OP_WRITE:
2705 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2710 if (!req->async_data) {
2711 ret = io_import_iovec(rw, req, &iovec, &iter, false);
2714 ret = io_setup_async_rw(req, iovec, inline_vecs, &iter, false);
2722 req_set_fail_links(req);
2727 static bool io_rw_reissue(struct io_kiocb *req, long res)
2730 umode_t mode = file_inode(req->file)->i_mode;
2733 if (!S_ISBLK(mode) && !S_ISREG(mode))
2735 if ((res != -EAGAIN && res != -EOPNOTSUPP) || io_wq_current_is_worker())
2738 lockdep_assert_held(&req->ctx->uring_lock);
2740 ret = io_sq_thread_acquire_mm_files(req->ctx, req);
2742 if (io_resubmit_prep(req, ret)) {
2743 refcount_inc(&req->refs);
2744 io_queue_async_work(req);
2752 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2753 struct io_comp_state *cs)
2755 if (!io_rw_reissue(req, res))
2756 io_complete_rw_common(&req->rw.kiocb, res, cs);
2759 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2761 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2763 __io_complete_rw(req, res, res2, NULL);
2766 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2768 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2770 if (kiocb->ki_flags & IOCB_WRITE)
2771 kiocb_end_write(req);
2773 if (res != -EAGAIN && res != req->result)
2774 req_set_fail_links(req);
2776 WRITE_ONCE(req->result, res);
2777 /* order with io_poll_complete() checking ->result */
2779 WRITE_ONCE(req->iopoll_completed, 1);
2783 * After the iocb has been issued, it's safe to be found on the poll list.
2784 * Adding the kiocb to the list AFTER submission ensures that we don't
2785 * find it from a io_iopoll_getevents() thread before the issuer is done
2786 * accessing the kiocb cookie.
2788 static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
2790 struct io_ring_ctx *ctx = req->ctx;
2793 * Track whether we have multiple files in our lists. This will impact
2794 * how we do polling eventually, not spinning if we're on potentially
2795 * different devices.
2797 if (list_empty(&ctx->iopoll_list)) {
2798 ctx->poll_multi_file = false;
2799 } else if (!ctx->poll_multi_file) {
2800 struct io_kiocb *list_req;
2802 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2804 if (list_req->file != req->file)
2805 ctx->poll_multi_file = true;
2809 * For fast devices, IO may have already completed. If it has, add
2810 * it to the front so we find it first.
2812 if (READ_ONCE(req->iopoll_completed))
2813 list_add(&req->inflight_entry, &ctx->iopoll_list);
2815 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2818 * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
2819 * task context or in io worker task context. If current task context is
2820 * sq thread, we don't need to check whether should wake up sq thread.
2822 if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
2823 wq_has_sleeper(&ctx->sq_data->wait))
2824 wake_up(&ctx->sq_data->wait);
2827 static inline void __io_state_file_put(struct io_submit_state *state)
2829 fput_many(state->file, state->file_refs);
2830 state->file_refs = 0;
2833 static inline void io_state_file_put(struct io_submit_state *state)
2835 if (state->file_refs)
2836 __io_state_file_put(state);
2840 * Get as many references to a file as we have IOs left in this submission,
2841 * assuming most submissions are for one file, or at least that each file
2842 * has more than one submission.
2844 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2849 if (state->file_refs) {
2850 if (state->fd == fd) {
2854 __io_state_file_put(state);
2856 state->file = fget_many(fd, state->ios_left);
2857 if (unlikely(!state->file))
2861 state->file_refs = state->ios_left - 1;
2865 static bool io_bdev_nowait(struct block_device *bdev)
2867 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2871 * If we tracked the file through the SCM inflight mechanism, we could support
2872 * any file. For now, just ensure that anything potentially problematic is done
2875 static bool io_file_supports_async(struct file *file, int rw)
2877 umode_t mode = file_inode(file)->i_mode;
2879 if (S_ISBLK(mode)) {
2880 if (IS_ENABLED(CONFIG_BLOCK) &&
2881 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2885 if (S_ISCHR(mode) || S_ISSOCK(mode))
2887 if (S_ISREG(mode)) {
2888 if (IS_ENABLED(CONFIG_BLOCK) &&
2889 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2890 file->f_op != &io_uring_fops)
2895 /* any ->read/write should understand O_NONBLOCK */
2896 if (file->f_flags & O_NONBLOCK)
2899 if (!(file->f_mode & FMODE_NOWAIT))
2903 return file->f_op->read_iter != NULL;
2905 return file->f_op->write_iter != NULL;
2908 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2910 struct io_ring_ctx *ctx = req->ctx;
2911 struct kiocb *kiocb = &req->rw.kiocb;
2915 if (S_ISREG(file_inode(req->file)->i_mode))
2916 req->flags |= REQ_F_ISREG;
2918 kiocb->ki_pos = READ_ONCE(sqe->off);
2919 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
2920 req->flags |= REQ_F_CUR_POS;
2921 kiocb->ki_pos = req->file->f_pos;
2923 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2924 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2925 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2929 ioprio = READ_ONCE(sqe->ioprio);
2931 ret = ioprio_check_cap(ioprio);
2935 kiocb->ki_ioprio = ioprio;
2937 kiocb->ki_ioprio = get_current_ioprio();
2939 /* don't allow async punt if RWF_NOWAIT was requested */
2940 if (kiocb->ki_flags & IOCB_NOWAIT)
2941 req->flags |= REQ_F_NOWAIT;
2943 if (ctx->flags & IORING_SETUP_IOPOLL) {
2944 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2945 !kiocb->ki_filp->f_op->iopoll)
2948 kiocb->ki_flags |= IOCB_HIPRI;
2949 kiocb->ki_complete = io_complete_rw_iopoll;
2950 req->iopoll_completed = 0;
2952 if (kiocb->ki_flags & IOCB_HIPRI)
2954 kiocb->ki_complete = io_complete_rw;
2957 req->rw.addr = READ_ONCE(sqe->addr);
2958 req->rw.len = READ_ONCE(sqe->len);
2959 req->buf_index = READ_ONCE(sqe->buf_index);
2963 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2969 case -ERESTARTNOINTR:
2970 case -ERESTARTNOHAND:
2971 case -ERESTART_RESTARTBLOCK:
2973 * We can't just restart the syscall, since previously
2974 * submitted sqes may already be in progress. Just fail this
2980 kiocb->ki_complete(kiocb, ret, 0);
2984 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2985 struct io_comp_state *cs)
2987 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2988 struct io_async_rw *io = req->async_data;
2990 /* add previously done IO, if any */
2991 if (io && io->bytes_done > 0) {
2993 ret = io->bytes_done;
2995 ret += io->bytes_done;
2998 if (req->flags & REQ_F_CUR_POS)
2999 req->file->f_pos = kiocb->ki_pos;
3000 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
3001 __io_complete_rw(req, ret, 0, cs);
3003 io_rw_done(kiocb, ret);
3006 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
3007 struct iov_iter *iter)
3009 struct io_ring_ctx *ctx = req->ctx;
3010 size_t len = req->rw.len;
3011 struct io_mapped_ubuf *imu;
3012 u16 index, buf_index = req->buf_index;
3016 if (unlikely(buf_index >= ctx->nr_user_bufs))
3018 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3019 imu = &ctx->user_bufs[index];
3020 buf_addr = req->rw.addr;
3023 if (buf_addr + len < buf_addr)
3025 /* not inside the mapped region */
3026 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
3030 * May not be a start of buffer, set size appropriately
3031 * and advance us to the beginning.
3033 offset = buf_addr - imu->ubuf;
3034 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3038 * Don't use iov_iter_advance() here, as it's really slow for
3039 * using the latter parts of a big fixed buffer - it iterates
3040 * over each segment manually. We can cheat a bit here, because
3043 * 1) it's a BVEC iter, we set it up
3044 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3045 * first and last bvec
3047 * So just find our index, and adjust the iterator afterwards.
3048 * If the offset is within the first bvec (or the whole first
3049 * bvec, just use iov_iter_advance(). This makes it easier
3050 * since we can just skip the first segment, which may not
3051 * be PAGE_SIZE aligned.
3053 const struct bio_vec *bvec = imu->bvec;
3055 if (offset <= bvec->bv_len) {
3056 iov_iter_advance(iter, offset);
3058 unsigned long seg_skip;
3060 /* skip first vec */
3061 offset -= bvec->bv_len;
3062 seg_skip = 1 + (offset >> PAGE_SHIFT);
3064 iter->bvec = bvec + seg_skip;
3065 iter->nr_segs -= seg_skip;
3066 iter->count -= bvec->bv_len + offset;
3067 iter->iov_offset = offset & ~PAGE_MASK;
3074 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3077 mutex_unlock(&ctx->uring_lock);
3080 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3083 * "Normal" inline submissions always hold the uring_lock, since we
3084 * grab it from the system call. Same is true for the SQPOLL offload.
3085 * The only exception is when we've detached the request and issue it
3086 * from an async worker thread, grab the lock for that case.
3089 mutex_lock(&ctx->uring_lock);
3092 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3093 int bgid, struct io_buffer *kbuf,
3096 struct io_buffer *head;
3098 if (req->flags & REQ_F_BUFFER_SELECTED)
3101 io_ring_submit_lock(req->ctx, needs_lock);
3103 lockdep_assert_held(&req->ctx->uring_lock);
3105 head = idr_find(&req->ctx->io_buffer_idr, bgid);
3107 if (!list_empty(&head->list)) {
3108 kbuf = list_last_entry(&head->list, struct io_buffer,
3110 list_del(&kbuf->list);
3113 idr_remove(&req->ctx->io_buffer_idr, bgid);
3115 if (*len > kbuf->len)
3118 kbuf = ERR_PTR(-ENOBUFS);
3121 io_ring_submit_unlock(req->ctx, needs_lock);
3126 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3129 struct io_buffer *kbuf;
3132 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3133 bgid = req->buf_index;
3134 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3137 req->rw.addr = (u64) (unsigned long) kbuf;
3138 req->flags |= REQ_F_BUFFER_SELECTED;
3139 return u64_to_user_ptr(kbuf->addr);
3142 #ifdef CONFIG_COMPAT
3143 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3146 struct compat_iovec __user *uiov;
3147 compat_ssize_t clen;
3151 uiov = u64_to_user_ptr(req->rw.addr);
3152 if (!access_ok(uiov, sizeof(*uiov)))
3154 if (__get_user(clen, &uiov->iov_len))
3160 buf = io_rw_buffer_select(req, &len, needs_lock);
3162 return PTR_ERR(buf);
3163 iov[0].iov_base = buf;
3164 iov[0].iov_len = (compat_size_t) len;
3169 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3172 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3176 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3179 len = iov[0].iov_len;
3182 buf = io_rw_buffer_select(req, &len, needs_lock);
3184 return PTR_ERR(buf);
3185 iov[0].iov_base = buf;
3186 iov[0].iov_len = len;
3190 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3193 if (req->flags & REQ_F_BUFFER_SELECTED) {
3194 struct io_buffer *kbuf;
3196 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3197 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3198 iov[0].iov_len = kbuf->len;
3201 if (req->rw.len != 1)
3204 #ifdef CONFIG_COMPAT
3205 if (req->ctx->compat)
3206 return io_compat_import(req, iov, needs_lock);
3209 return __io_iov_buffer_select(req, iov, needs_lock);
3212 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
3213 struct iovec **iovec, struct iov_iter *iter,
3216 void __user *buf = u64_to_user_ptr(req->rw.addr);
3217 size_t sqe_len = req->rw.len;
3221 opcode = req->opcode;
3222 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3224 return io_import_fixed(req, rw, iter);
3227 /* buffer index only valid with fixed read/write, or buffer select */
3228 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3231 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3232 if (req->flags & REQ_F_BUFFER_SELECT) {
3233 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3235 return PTR_ERR(buf);
3236 req->rw.len = sqe_len;
3239 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3244 if (req->flags & REQ_F_BUFFER_SELECT) {
3245 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3247 ret = (*iovec)->iov_len;
3248 iov_iter_init(iter, rw, *iovec, 1, ret);
3254 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3258 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3260 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3264 * For files that don't have ->read_iter() and ->write_iter(), handle them
3265 * by looping over ->read() or ->write() manually.
3267 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3269 struct kiocb *kiocb = &req->rw.kiocb;
3270 struct file *file = req->file;
3274 * Don't support polled IO through this interface, and we can't
3275 * support non-blocking either. For the latter, this just causes
3276 * the kiocb to be handled from an async context.
3278 if (kiocb->ki_flags & IOCB_HIPRI)
3280 if (kiocb->ki_flags & IOCB_NOWAIT)
3283 while (iov_iter_count(iter)) {
3287 if (!iov_iter_is_bvec(iter)) {
3288 iovec = iov_iter_iovec(iter);
3290 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3291 iovec.iov_len = req->rw.len;
3295 nr = file->f_op->read(file, iovec.iov_base,
3296 iovec.iov_len, io_kiocb_ppos(kiocb));
3298 nr = file->f_op->write(file, iovec.iov_base,
3299 iovec.iov_len, io_kiocb_ppos(kiocb));
3308 if (nr != iovec.iov_len)
3312 iov_iter_advance(iter, nr);
3318 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3319 const struct iovec *fast_iov, struct iov_iter *iter)
3321 struct io_async_rw *rw = req->async_data;
3323 memcpy(&rw->iter, iter, sizeof(*iter));
3324 rw->free_iovec = iovec;
3326 /* can only be fixed buffers, no need to do anything */
3327 if (iov_iter_is_bvec(iter))
3330 unsigned iov_off = 0;
3332 rw->iter.iov = rw->fast_iov;
3333 if (iter->iov != fast_iov) {
3334 iov_off = iter->iov - fast_iov;
3335 rw->iter.iov += iov_off;
3337 if (rw->fast_iov != fast_iov)
3338 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3339 sizeof(struct iovec) * iter->nr_segs);
3341 req->flags |= REQ_F_NEED_CLEANUP;
3345 static inline int __io_alloc_async_data(struct io_kiocb *req)
3347 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3348 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3349 return req->async_data == NULL;
3352 static int io_alloc_async_data(struct io_kiocb *req)
3354 if (!io_op_defs[req->opcode].needs_async_data)
3357 return __io_alloc_async_data(req);
3360 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3361 const struct iovec *fast_iov,
3362 struct iov_iter *iter, bool force)
3364 if (!force && !io_op_defs[req->opcode].needs_async_data)
3366 if (!req->async_data) {
3367 if (__io_alloc_async_data(req))
3370 io_req_map_rw(req, iovec, fast_iov, iter);
3375 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3377 struct io_async_rw *iorw = req->async_data;
3378 struct iovec *iov = iorw->fast_iov;
3381 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3382 if (unlikely(ret < 0))
3385 iorw->bytes_done = 0;
3386 iorw->free_iovec = iov;
3388 req->flags |= REQ_F_NEED_CLEANUP;
3392 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3396 ret = io_prep_rw(req, sqe);
3400 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3403 /* either don't need iovec imported or already have it */
3404 if (!req->async_data)
3406 return io_rw_prep_async(req, READ);
3410 * This is our waitqueue callback handler, registered through lock_page_async()
3411 * when we initially tried to do the IO with the iocb armed our waitqueue.
3412 * This gets called when the page is unlocked, and we generally expect that to
3413 * happen when the page IO is completed and the page is now uptodate. This will
3414 * queue a task_work based retry of the operation, attempting to copy the data
3415 * again. If the latter fails because the page was NOT uptodate, then we will
3416 * do a thread based blocking retry of the operation. That's the unexpected
3419 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3420 int sync, void *arg)
3422 struct wait_page_queue *wpq;
3423 struct io_kiocb *req = wait->private;
3424 struct wait_page_key *key = arg;
3427 wpq = container_of(wait, struct wait_page_queue, wait);
3429 if (!wake_page_match(wpq, key))
3432 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3433 list_del_init(&wait->entry);
3435 init_task_work(&req->task_work, io_req_task_submit);
3436 percpu_ref_get(&req->ctx->refs);
3438 /* submit ref gets dropped, acquire a new one */
3439 refcount_inc(&req->refs);
3440 ret = io_req_task_work_add(req);
3441 if (unlikely(ret)) {
3442 struct task_struct *tsk;
3444 /* queue just for cancelation */
3445 init_task_work(&req->task_work, io_req_task_cancel);
3446 tsk = io_wq_get_task(req->ctx->io_wq);
3447 task_work_add(tsk, &req->task_work, TWA_NONE);
3448 wake_up_process(tsk);
3454 * This controls whether a given IO request should be armed for async page
3455 * based retry. If we return false here, the request is handed to the async
3456 * worker threads for retry. If we're doing buffered reads on a regular file,
3457 * we prepare a private wait_page_queue entry and retry the operation. This
3458 * will either succeed because the page is now uptodate and unlocked, or it
3459 * will register a callback when the page is unlocked at IO completion. Through
3460 * that callback, io_uring uses task_work to setup a retry of the operation.
3461 * That retry will attempt the buffered read again. The retry will generally
3462 * succeed, or in rare cases where it fails, we then fall back to using the
3463 * async worker threads for a blocking retry.
3465 static bool io_rw_should_retry(struct io_kiocb *req)
3467 struct io_async_rw *rw = req->async_data;
3468 struct wait_page_queue *wait = &rw->wpq;
3469 struct kiocb *kiocb = &req->rw.kiocb;
3471 /* never retry for NOWAIT, we just complete with -EAGAIN */
3472 if (req->flags & REQ_F_NOWAIT)
3475 /* Only for buffered IO */
3476 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3480 * just use poll if we can, and don't attempt if the fs doesn't
3481 * support callback based unlocks
3483 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3486 wait->wait.func = io_async_buf_func;
3487 wait->wait.private = req;
3488 wait->wait.flags = 0;
3489 INIT_LIST_HEAD(&wait->wait.entry);
3490 kiocb->ki_flags |= IOCB_WAITQ;
3491 kiocb->ki_flags &= ~IOCB_NOWAIT;
3492 kiocb->ki_waitq = wait;
3496 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3498 if (req->file->f_op->read_iter)
3499 return call_read_iter(req->file, &req->rw.kiocb, iter);
3500 else if (req->file->f_op->read)
3501 return loop_rw_iter(READ, req, iter);
3506 static int io_read(struct io_kiocb *req, bool force_nonblock,
3507 struct io_comp_state *cs)
3509 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3510 struct kiocb *kiocb = &req->rw.kiocb;
3511 struct iov_iter __iter, *iter = &__iter;
3512 struct io_async_rw *rw = req->async_data;
3513 ssize_t io_size, ret, ret2;
3520 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3524 io_size = iov_iter_count(iter);
3525 req->result = io_size;
3528 /* Ensure we clear previously set non-block flag */
3529 if (!force_nonblock)
3530 kiocb->ki_flags &= ~IOCB_NOWAIT;
3532 kiocb->ki_flags |= IOCB_NOWAIT;
3535 /* If the file doesn't support async, just async punt */
3536 no_async = force_nonblock && !io_file_supports_async(req->file, READ);
3540 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3544 ret = io_iter_do_read(req, iter);
3548 } else if (ret == -EIOCBQUEUED) {
3551 } else if (ret == -EAGAIN) {
3552 /* IOPOLL retry should happen for io-wq threads */
3553 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3555 /* no retry on NONBLOCK marked file */
3556 if (req->file->f_flags & O_NONBLOCK)
3558 /* some cases will consume bytes even on error returns */
3559 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3562 } else if (ret < 0) {
3563 /* make sure -ERESTARTSYS -> -EINTR is done */
3567 /* read it all, or we did blocking attempt. no retry. */
3568 if (!iov_iter_count(iter) || !force_nonblock ||
3569 (req->file->f_flags & O_NONBLOCK) || !(req->flags & REQ_F_ISREG))
3574 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3581 rw = req->async_data;
3582 /* it's copied and will be cleaned with ->io */
3584 /* now use our persistent iterator, if we aren't already */
3587 rw->bytes_done += ret;
3588 /* if we can retry, do so with the callbacks armed */
3589 if (!io_rw_should_retry(req)) {
3590 kiocb->ki_flags &= ~IOCB_WAITQ;
3595 * Now retry read with the IOCB_WAITQ parts set in the iocb. If we
3596 * get -EIOCBQUEUED, then we'll get a notification when the desired
3597 * page gets unlocked. We can also get a partial read here, and if we
3598 * do, then just retry at the new offset.
3600 ret = io_iter_do_read(req, iter);
3601 if (ret == -EIOCBQUEUED) {
3604 } else if (ret > 0 && ret < io_size) {
3605 /* we got some bytes, but not all. retry. */
3609 kiocb_done(kiocb, ret, cs);
3612 /* it's reportedly faster than delegating the null check to kfree() */
3618 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3622 ret = io_prep_rw(req, sqe);
3626 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3629 /* either don't need iovec imported or already have it */
3630 if (!req->async_data)
3632 return io_rw_prep_async(req, WRITE);
3635 static int io_write(struct io_kiocb *req, bool force_nonblock,
3636 struct io_comp_state *cs)
3638 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3639 struct kiocb *kiocb = &req->rw.kiocb;
3640 struct iov_iter __iter, *iter = &__iter;
3641 struct io_async_rw *rw = req->async_data;
3642 ssize_t ret, ret2, io_size;
3648 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3652 io_size = iov_iter_count(iter);
3653 req->result = io_size;
3655 /* Ensure we clear previously set non-block flag */
3656 if (!force_nonblock)
3657 kiocb->ki_flags &= ~IOCB_NOWAIT;
3659 kiocb->ki_flags |= IOCB_NOWAIT;
3661 /* If the file doesn't support async, just async punt */
3662 if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3665 /* file path doesn't support NOWAIT for non-direct_IO */
3666 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3667 (req->flags & REQ_F_ISREG))
3670 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3675 * Open-code file_start_write here to grab freeze protection,
3676 * which will be released by another thread in
3677 * io_complete_rw(). Fool lockdep by telling it the lock got
3678 * released so that it doesn't complain about the held lock when
3679 * we return to userspace.
3681 if (req->flags & REQ_F_ISREG) {
3682 sb_start_write(file_inode(req->file)->i_sb);
3683 __sb_writers_release(file_inode(req->file)->i_sb,
3686 kiocb->ki_flags |= IOCB_WRITE;
3688 if (req->file->f_op->write_iter)
3689 ret2 = call_write_iter(req->file, kiocb, iter);
3690 else if (req->file->f_op->write)
3691 ret2 = loop_rw_iter(WRITE, req, iter);
3696 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3697 * retry them without IOCB_NOWAIT.
3699 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3701 /* no retry on NONBLOCK marked file */
3702 if (ret2 == -EAGAIN && (req->file->f_flags & O_NONBLOCK))
3704 if (!force_nonblock || ret2 != -EAGAIN) {
3705 /* IOPOLL retry should happen for io-wq threads */
3706 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3709 kiocb_done(kiocb, ret2, cs);
3712 /* some cases will consume bytes even on error returns */
3713 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3714 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3719 /* it's reportedly faster than delegating the null check to kfree() */
3725 static int io_renameat_prep(struct io_kiocb *req,
3726 const struct io_uring_sqe *sqe)
3728 struct io_rename *ren = &req->rename;
3729 const char __user *oldf, *newf;
3731 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3734 ren->old_dfd = READ_ONCE(sqe->fd);
3735 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3736 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3737 ren->new_dfd = READ_ONCE(sqe->len);
3738 ren->flags = READ_ONCE(sqe->rename_flags);
3740 ren->oldpath = getname(oldf);
3741 if (IS_ERR(ren->oldpath))
3742 return PTR_ERR(ren->oldpath);
3744 ren->newpath = getname(newf);
3745 if (IS_ERR(ren->newpath)) {
3746 putname(ren->oldpath);
3747 return PTR_ERR(ren->newpath);
3750 req->flags |= REQ_F_NEED_CLEANUP;
3754 static int io_renameat(struct io_kiocb *req, bool force_nonblock)
3756 struct io_rename *ren = &req->rename;
3762 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3763 ren->newpath, ren->flags);
3765 req->flags &= ~REQ_F_NEED_CLEANUP;
3767 req_set_fail_links(req);
3768 io_req_complete(req, ret);
3772 static int io_unlinkat_prep(struct io_kiocb *req,
3773 const struct io_uring_sqe *sqe)
3775 struct io_unlink *un = &req->unlink;
3776 const char __user *fname;
3778 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3781 un->dfd = READ_ONCE(sqe->fd);
3783 un->flags = READ_ONCE(sqe->unlink_flags);
3784 if (un->flags & ~AT_REMOVEDIR)
3787 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3788 un->filename = getname(fname);
3789 if (IS_ERR(un->filename))
3790 return PTR_ERR(un->filename);
3792 req->flags |= REQ_F_NEED_CLEANUP;
3796 static int io_unlinkat(struct io_kiocb *req, bool force_nonblock)
3798 struct io_unlink *un = &req->unlink;
3804 if (un->flags & AT_REMOVEDIR)
3805 ret = do_rmdir(un->dfd, un->filename);
3807 ret = do_unlinkat(un->dfd, un->filename);
3809 req->flags &= ~REQ_F_NEED_CLEANUP;
3811 req_set_fail_links(req);
3812 io_req_complete(req, ret);
3816 static int io_shutdown_prep(struct io_kiocb *req,
3817 const struct io_uring_sqe *sqe)
3819 #if defined(CONFIG_NET)
3820 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3822 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3826 req->shutdown.how = READ_ONCE(sqe->len);
3833 static int io_shutdown(struct io_kiocb *req, bool force_nonblock)
3835 #if defined(CONFIG_NET)
3836 struct socket *sock;
3842 sock = sock_from_file(req->file);
3843 if (unlikely(!sock))
3846 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3848 req_set_fail_links(req);
3849 io_req_complete(req, ret);
3856 static int __io_splice_prep(struct io_kiocb *req,
3857 const struct io_uring_sqe *sqe)
3859 struct io_splice* sp = &req->splice;
3860 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3862 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3866 sp->len = READ_ONCE(sqe->len);
3867 sp->flags = READ_ONCE(sqe->splice_flags);
3869 if (unlikely(sp->flags & ~valid_flags))
3872 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3873 (sp->flags & SPLICE_F_FD_IN_FIXED));
3876 req->flags |= REQ_F_NEED_CLEANUP;
3878 if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3880 * Splice operation will be punted aync, and here need to
3881 * modify io_wq_work.flags, so initialize io_wq_work firstly.
3883 io_req_init_async(req);
3884 req->work.flags |= IO_WQ_WORK_UNBOUND;
3890 static int io_tee_prep(struct io_kiocb *req,
3891 const struct io_uring_sqe *sqe)
3893 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3895 return __io_splice_prep(req, sqe);
3898 static int io_tee(struct io_kiocb *req, bool force_nonblock)
3900 struct io_splice *sp = &req->splice;
3901 struct file *in = sp->file_in;
3902 struct file *out = sp->file_out;
3903 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3909 ret = do_tee(in, out, sp->len, flags);
3911 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3912 req->flags &= ~REQ_F_NEED_CLEANUP;
3915 req_set_fail_links(req);
3916 io_req_complete(req, ret);
3920 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3922 struct io_splice* sp = &req->splice;
3924 sp->off_in = READ_ONCE(sqe->splice_off_in);
3925 sp->off_out = READ_ONCE(sqe->off);
3926 return __io_splice_prep(req, sqe);
3929 static int io_splice(struct io_kiocb *req, bool force_nonblock)
3931 struct io_splice *sp = &req->splice;
3932 struct file *in = sp->file_in;
3933 struct file *out = sp->file_out;
3934 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3935 loff_t *poff_in, *poff_out;
3941 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3942 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3945 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3947 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3948 req->flags &= ~REQ_F_NEED_CLEANUP;
3951 req_set_fail_links(req);
3952 io_req_complete(req, ret);
3957 * IORING_OP_NOP just posts a completion event, nothing else.
3959 static int io_nop(struct io_kiocb *req, struct io_comp_state *cs)
3961 struct io_ring_ctx *ctx = req->ctx;
3963 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3966 __io_req_complete(req, 0, 0, cs);
3970 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3972 struct io_ring_ctx *ctx = req->ctx;
3977 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3979 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3982 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3983 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3986 req->sync.off = READ_ONCE(sqe->off);
3987 req->sync.len = READ_ONCE(sqe->len);
3991 static int io_fsync(struct io_kiocb *req, bool force_nonblock)
3993 loff_t end = req->sync.off + req->sync.len;
3996 /* fsync always requires a blocking context */
4000 ret = vfs_fsync_range(req->file, req->sync.off,
4001 end > 0 ? end : LLONG_MAX,
4002 req->sync.flags & IORING_FSYNC_DATASYNC);
4004 req_set_fail_links(req);
4005 io_req_complete(req, ret);
4009 static int io_fallocate_prep(struct io_kiocb *req,
4010 const struct io_uring_sqe *sqe)
4012 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
4014 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4017 req->sync.off = READ_ONCE(sqe->off);
4018 req->sync.len = READ_ONCE(sqe->addr);
4019 req->sync.mode = READ_ONCE(sqe->len);
4023 static int io_fallocate(struct io_kiocb *req, bool force_nonblock)
4027 /* fallocate always requiring blocking context */
4030 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4033 req_set_fail_links(req);
4034 io_req_complete(req, ret);
4038 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4040 const char __user *fname;
4043 if (unlikely(sqe->ioprio || sqe->buf_index))
4045 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4048 /* open.how should be already initialised */
4049 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4050 req->open.how.flags |= O_LARGEFILE;
4052 req->open.dfd = READ_ONCE(sqe->fd);
4053 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4054 req->open.filename = getname(fname);
4055 if (IS_ERR(req->open.filename)) {
4056 ret = PTR_ERR(req->open.filename);
4057 req->open.filename = NULL;
4060 req->open.nofile = rlimit(RLIMIT_NOFILE);
4061 req->flags |= REQ_F_NEED_CLEANUP;
4065 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4069 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4071 mode = READ_ONCE(sqe->len);
4072 flags = READ_ONCE(sqe->open_flags);
4073 req->open.how = build_open_how(flags, mode);
4074 return __io_openat_prep(req, sqe);
4077 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4079 struct open_how __user *how;
4083 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4085 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4086 len = READ_ONCE(sqe->len);
4087 if (len < OPEN_HOW_SIZE_VER0)
4090 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4095 return __io_openat_prep(req, sqe);
4098 static int io_openat2(struct io_kiocb *req, bool force_nonblock)
4100 struct open_flags op;
4103 bool resolve_nonblock;
4106 ret = build_open_flags(&req->open.how, &op);
4109 nonblock_set = op.open_flag & O_NONBLOCK;
4110 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4111 if (force_nonblock) {
4113 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4114 * it'll always -EAGAIN
4116 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4118 op.lookup_flags |= LOOKUP_CACHED;
4119 op.open_flag |= O_NONBLOCK;
4122 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4126 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4127 /* only retry if RESOLVE_CACHED wasn't already set by application */
4128 if ((!resolve_nonblock && force_nonblock) && file == ERR_PTR(-EAGAIN)) {
4130 * We could hang on to this 'fd', but seems like marginal
4131 * gain for something that is now known to be a slower path.
4132 * So just put it, and we'll get a new one when we retry.
4140 ret = PTR_ERR(file);
4142 if (force_nonblock && !nonblock_set)
4143 file->f_flags &= ~O_NONBLOCK;
4144 fsnotify_open(file);
4145 fd_install(ret, file);
4148 putname(req->open.filename);
4149 req->flags &= ~REQ_F_NEED_CLEANUP;
4151 req_set_fail_links(req);
4152 io_req_complete(req, ret);
4156 static int io_openat(struct io_kiocb *req, bool force_nonblock)
4158 return io_openat2(req, force_nonblock);
4161 static int io_remove_buffers_prep(struct io_kiocb *req,
4162 const struct io_uring_sqe *sqe)
4164 struct io_provide_buf *p = &req->pbuf;
4167 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
4170 tmp = READ_ONCE(sqe->fd);
4171 if (!tmp || tmp > USHRT_MAX)
4174 memset(p, 0, sizeof(*p));
4176 p->bgid = READ_ONCE(sqe->buf_group);
4180 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4181 int bgid, unsigned nbufs)
4185 /* shouldn't happen */
4189 /* the head kbuf is the list itself */
4190 while (!list_empty(&buf->list)) {
4191 struct io_buffer *nxt;
4193 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4194 list_del(&nxt->list);
4201 idr_remove(&ctx->io_buffer_idr, bgid);
4206 static int io_remove_buffers(struct io_kiocb *req, bool force_nonblock,
4207 struct io_comp_state *cs)
4209 struct io_provide_buf *p = &req->pbuf;
4210 struct io_ring_ctx *ctx = req->ctx;
4211 struct io_buffer *head;
4214 io_ring_submit_lock(ctx, !force_nonblock);
4216 lockdep_assert_held(&ctx->uring_lock);
4219 head = idr_find(&ctx->io_buffer_idr, p->bgid);
4221 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4223 req_set_fail_links(req);
4225 /* need to hold the lock to complete IOPOLL requests */
4226 if (ctx->flags & IORING_SETUP_IOPOLL) {
4227 __io_req_complete(req, ret, 0, cs);
4228 io_ring_submit_unlock(ctx, !force_nonblock);
4230 io_ring_submit_unlock(ctx, !force_nonblock);
4231 __io_req_complete(req, ret, 0, cs);
4236 static int io_provide_buffers_prep(struct io_kiocb *req,
4237 const struct io_uring_sqe *sqe)
4239 struct io_provide_buf *p = &req->pbuf;
4242 if (sqe->ioprio || sqe->rw_flags)
4245 tmp = READ_ONCE(sqe->fd);
4246 if (!tmp || tmp > USHRT_MAX)
4249 p->addr = READ_ONCE(sqe->addr);
4250 p->len = READ_ONCE(sqe->len);
4252 if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
4255 p->bgid = READ_ONCE(sqe->buf_group);
4256 tmp = READ_ONCE(sqe->off);
4257 if (tmp > USHRT_MAX)
4263 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4265 struct io_buffer *buf;
4266 u64 addr = pbuf->addr;
4267 int i, bid = pbuf->bid;
4269 for (i = 0; i < pbuf->nbufs; i++) {
4270 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
4275 buf->len = pbuf->len;
4280 INIT_LIST_HEAD(&buf->list);
4283 list_add_tail(&buf->list, &(*head)->list);
4287 return i ? i : -ENOMEM;
4290 static int io_provide_buffers(struct io_kiocb *req, bool force_nonblock,
4291 struct io_comp_state *cs)
4293 struct io_provide_buf *p = &req->pbuf;
4294 struct io_ring_ctx *ctx = req->ctx;
4295 struct io_buffer *head, *list;
4298 io_ring_submit_lock(ctx, !force_nonblock);
4300 lockdep_assert_held(&ctx->uring_lock);
4302 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
4304 ret = io_add_buffers(p, &head);
4309 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
4312 __io_remove_buffers(ctx, head, p->bgid, -1U);
4318 req_set_fail_links(req);
4320 /* need to hold the lock to complete IOPOLL requests */
4321 if (ctx->flags & IORING_SETUP_IOPOLL) {
4322 __io_req_complete(req, ret, 0, cs);
4323 io_ring_submit_unlock(ctx, !force_nonblock);
4325 io_ring_submit_unlock(ctx, !force_nonblock);
4326 __io_req_complete(req, ret, 0, cs);
4331 static int io_epoll_ctl_prep(struct io_kiocb *req,
4332 const struct io_uring_sqe *sqe)
4334 #if defined(CONFIG_EPOLL)
4335 if (sqe->ioprio || sqe->buf_index)
4337 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4340 req->epoll.epfd = READ_ONCE(sqe->fd);
4341 req->epoll.op = READ_ONCE(sqe->len);
4342 req->epoll.fd = READ_ONCE(sqe->off);
4344 if (ep_op_has_event(req->epoll.op)) {
4345 struct epoll_event __user *ev;
4347 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4348 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4358 static int io_epoll_ctl(struct io_kiocb *req, bool force_nonblock,
4359 struct io_comp_state *cs)
4361 #if defined(CONFIG_EPOLL)
4362 struct io_epoll *ie = &req->epoll;
4365 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4366 if (force_nonblock && ret == -EAGAIN)
4370 req_set_fail_links(req);
4371 __io_req_complete(req, ret, 0, cs);
4378 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4380 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4381 if (sqe->ioprio || sqe->buf_index || sqe->off)
4383 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4386 req->madvise.addr = READ_ONCE(sqe->addr);
4387 req->madvise.len = READ_ONCE(sqe->len);
4388 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4395 static int io_madvise(struct io_kiocb *req, bool force_nonblock)
4397 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4398 struct io_madvise *ma = &req->madvise;
4404 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4406 req_set_fail_links(req);
4407 io_req_complete(req, ret);
4414 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4416 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4418 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4421 req->fadvise.offset = READ_ONCE(sqe->off);
4422 req->fadvise.len = READ_ONCE(sqe->len);
4423 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4427 static int io_fadvise(struct io_kiocb *req, bool force_nonblock)
4429 struct io_fadvise *fa = &req->fadvise;
4432 if (force_nonblock) {
4433 switch (fa->advice) {
4434 case POSIX_FADV_NORMAL:
4435 case POSIX_FADV_RANDOM:
4436 case POSIX_FADV_SEQUENTIAL:
4443 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4445 req_set_fail_links(req);
4446 io_req_complete(req, ret);
4450 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4452 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4454 if (sqe->ioprio || sqe->buf_index)
4456 if (req->flags & REQ_F_FIXED_FILE)
4459 req->statx.dfd = READ_ONCE(sqe->fd);
4460 req->statx.mask = READ_ONCE(sqe->len);
4461 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4462 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4463 req->statx.flags = READ_ONCE(sqe->statx_flags);
4468 static int io_statx(struct io_kiocb *req, bool force_nonblock)
4470 struct io_statx *ctx = &req->statx;
4473 if (force_nonblock) {
4474 /* only need file table for an actual valid fd */
4475 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
4476 req->flags |= REQ_F_NO_FILE_TABLE;
4480 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4484 req_set_fail_links(req);
4485 io_req_complete(req, ret);
4489 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4492 * If we queue this for async, it must not be cancellable. That would
4493 * leave the 'file' in an undeterminate state, and here need to modify
4494 * io_wq_work.flags, so initialize io_wq_work firstly.
4496 io_req_init_async(req);
4498 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4500 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4501 sqe->rw_flags || sqe->buf_index)
4503 if (req->flags & REQ_F_FIXED_FILE)
4506 req->close.fd = READ_ONCE(sqe->fd);
4507 if ((req->file && req->file->f_op == &io_uring_fops))
4510 req->close.put_file = NULL;
4514 static int io_close(struct io_kiocb *req, bool force_nonblock,
4515 struct io_comp_state *cs)
4517 struct io_close *close = &req->close;
4520 /* might be already done during nonblock submission */
4521 if (!close->put_file) {
4522 ret = close_fd_get_file(close->fd, &close->put_file);
4524 return (ret == -ENOENT) ? -EBADF : ret;
4527 /* if the file has a flush method, be safe and punt to async */
4528 if (close->put_file->f_op->flush && force_nonblock) {
4529 /* not safe to cancel at this point */
4530 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
4531 /* was never set, but play safe */
4532 req->flags &= ~REQ_F_NOWAIT;
4533 /* avoid grabbing files - we don't need the files */
4534 req->flags |= REQ_F_NO_FILE_TABLE;
4538 /* No ->flush() or already async, safely close from here */
4539 ret = filp_close(close->put_file, req->work.identity->files);
4541 req_set_fail_links(req);
4542 fput(close->put_file);
4543 close->put_file = NULL;
4544 __io_req_complete(req, ret, 0, cs);
4548 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4550 struct io_ring_ctx *ctx = req->ctx;
4555 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4557 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4560 req->sync.off = READ_ONCE(sqe->off);
4561 req->sync.len = READ_ONCE(sqe->len);
4562 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4566 static int io_sync_file_range(struct io_kiocb *req, bool force_nonblock)
4570 /* sync_file_range always requires a blocking context */
4574 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4577 req_set_fail_links(req);
4578 io_req_complete(req, ret);
4582 #if defined(CONFIG_NET)
4583 static int io_setup_async_msg(struct io_kiocb *req,
4584 struct io_async_msghdr *kmsg)
4586 struct io_async_msghdr *async_msg = req->async_data;
4590 if (io_alloc_async_data(req)) {
4591 if (kmsg->iov != kmsg->fast_iov)
4595 async_msg = req->async_data;
4596 req->flags |= REQ_F_NEED_CLEANUP;
4597 memcpy(async_msg, kmsg, sizeof(*kmsg));
4601 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4602 struct io_async_msghdr *iomsg)
4604 iomsg->iov = iomsg->fast_iov;
4605 iomsg->msg.msg_name = &iomsg->addr;
4606 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4607 req->sr_msg.msg_flags, &iomsg->iov);
4610 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4612 struct io_async_msghdr *async_msg = req->async_data;
4613 struct io_sr_msg *sr = &req->sr_msg;
4616 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4619 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4620 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4621 sr->len = READ_ONCE(sqe->len);
4623 #ifdef CONFIG_COMPAT
4624 if (req->ctx->compat)
4625 sr->msg_flags |= MSG_CMSG_COMPAT;
4628 if (!async_msg || !io_op_defs[req->opcode].needs_async_data)
4630 ret = io_sendmsg_copy_hdr(req, async_msg);
4632 req->flags |= REQ_F_NEED_CLEANUP;
4636 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
4637 struct io_comp_state *cs)
4639 struct io_async_msghdr iomsg, *kmsg;
4640 struct socket *sock;
4644 sock = sock_from_file(req->file);
4645 if (unlikely(!sock))
4648 if (req->async_data) {
4649 kmsg = req->async_data;
4650 kmsg->msg.msg_name = &kmsg->addr;
4651 /* if iov is set, it's allocated already */
4653 kmsg->iov = kmsg->fast_iov;
4654 kmsg->msg.msg_iter.iov = kmsg->iov;
4656 ret = io_sendmsg_copy_hdr(req, &iomsg);
4662 flags = req->sr_msg.msg_flags;
4663 if (flags & MSG_DONTWAIT)
4664 req->flags |= REQ_F_NOWAIT;
4665 else if (force_nonblock)
4666 flags |= MSG_DONTWAIT;
4668 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4669 if (force_nonblock && ret == -EAGAIN)
4670 return io_setup_async_msg(req, kmsg);
4671 if (ret == -ERESTARTSYS)
4674 if (kmsg->iov != kmsg->fast_iov)
4676 req->flags &= ~REQ_F_NEED_CLEANUP;
4678 req_set_fail_links(req);
4679 __io_req_complete(req, ret, 0, cs);
4683 static int io_send(struct io_kiocb *req, bool force_nonblock,
4684 struct io_comp_state *cs)
4686 struct io_sr_msg *sr = &req->sr_msg;
4689 struct socket *sock;
4693 sock = sock_from_file(req->file);
4694 if (unlikely(!sock))
4697 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4701 msg.msg_name = NULL;
4702 msg.msg_control = NULL;
4703 msg.msg_controllen = 0;
4704 msg.msg_namelen = 0;
4706 flags = req->sr_msg.msg_flags;
4707 if (flags & MSG_DONTWAIT)
4708 req->flags |= REQ_F_NOWAIT;
4709 else if (force_nonblock)
4710 flags |= MSG_DONTWAIT;
4712 msg.msg_flags = flags;
4713 ret = sock_sendmsg(sock, &msg);
4714 if (force_nonblock && ret == -EAGAIN)
4716 if (ret == -ERESTARTSYS)
4720 req_set_fail_links(req);
4721 __io_req_complete(req, ret, 0, cs);
4725 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4726 struct io_async_msghdr *iomsg)
4728 struct io_sr_msg *sr = &req->sr_msg;
4729 struct iovec __user *uiov;
4733 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4734 &iomsg->uaddr, &uiov, &iov_len);
4738 if (req->flags & REQ_F_BUFFER_SELECT) {
4741 if (copy_from_user(iomsg->iov, uiov, sizeof(*uiov)))
4743 sr->len = iomsg->iov[0].iov_len;
4744 iov_iter_init(&iomsg->msg.msg_iter, READ, iomsg->iov, 1,
4748 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4749 &iomsg->iov, &iomsg->msg.msg_iter,
4758 #ifdef CONFIG_COMPAT
4759 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4760 struct io_async_msghdr *iomsg)
4762 struct compat_msghdr __user *msg_compat;
4763 struct io_sr_msg *sr = &req->sr_msg;
4764 struct compat_iovec __user *uiov;
4769 msg_compat = (struct compat_msghdr __user *) sr->umsg;
4770 ret = __get_compat_msghdr(&iomsg->msg, msg_compat, &iomsg->uaddr,
4775 uiov = compat_ptr(ptr);
4776 if (req->flags & REQ_F_BUFFER_SELECT) {
4777 compat_ssize_t clen;
4781 if (!access_ok(uiov, sizeof(*uiov)))
4783 if (__get_user(clen, &uiov->iov_len))
4788 iomsg->iov[0].iov_len = clen;
4791 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4792 UIO_FASTIOV, &iomsg->iov,
4793 &iomsg->msg.msg_iter, true);
4802 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4803 struct io_async_msghdr *iomsg)
4805 iomsg->msg.msg_name = &iomsg->addr;
4806 iomsg->iov = iomsg->fast_iov;
4808 #ifdef CONFIG_COMPAT
4809 if (req->ctx->compat)
4810 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4813 return __io_recvmsg_copy_hdr(req, iomsg);
4816 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4819 struct io_sr_msg *sr = &req->sr_msg;
4820 struct io_buffer *kbuf;
4822 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4827 req->flags |= REQ_F_BUFFER_SELECTED;
4831 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4833 return io_put_kbuf(req, req->sr_msg.kbuf);
4836 static int io_recvmsg_prep(struct io_kiocb *req,
4837 const struct io_uring_sqe *sqe)
4839 struct io_async_msghdr *async_msg = req->async_data;
4840 struct io_sr_msg *sr = &req->sr_msg;
4843 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4846 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4847 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4848 sr->len = READ_ONCE(sqe->len);
4849 sr->bgid = READ_ONCE(sqe->buf_group);
4851 #ifdef CONFIG_COMPAT
4852 if (req->ctx->compat)
4853 sr->msg_flags |= MSG_CMSG_COMPAT;
4856 if (!async_msg || !io_op_defs[req->opcode].needs_async_data)
4858 ret = io_recvmsg_copy_hdr(req, async_msg);
4860 req->flags |= REQ_F_NEED_CLEANUP;
4864 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
4865 struct io_comp_state *cs)
4867 struct io_async_msghdr iomsg, *kmsg;
4868 struct socket *sock;
4869 struct io_buffer *kbuf;
4871 int ret, cflags = 0;
4873 sock = sock_from_file(req->file);
4874 if (unlikely(!sock))
4877 if (req->async_data) {
4878 kmsg = req->async_data;
4879 kmsg->msg.msg_name = &kmsg->addr;
4880 /* if iov is set, it's allocated already */
4882 kmsg->iov = kmsg->fast_iov;
4883 kmsg->msg.msg_iter.iov = kmsg->iov;
4885 ret = io_recvmsg_copy_hdr(req, &iomsg);
4891 if (req->flags & REQ_F_BUFFER_SELECT) {
4892 kbuf = io_recv_buffer_select(req, !force_nonblock);
4894 return PTR_ERR(kbuf);
4895 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4896 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->iov,
4897 1, req->sr_msg.len);
4900 flags = req->sr_msg.msg_flags;
4901 if (flags & MSG_DONTWAIT)
4902 req->flags |= REQ_F_NOWAIT;
4903 else if (force_nonblock)
4904 flags |= MSG_DONTWAIT;
4906 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4907 kmsg->uaddr, flags);
4908 if (force_nonblock && ret == -EAGAIN)
4909 return io_setup_async_msg(req, kmsg);
4910 if (ret == -ERESTARTSYS)
4913 if (req->flags & REQ_F_BUFFER_SELECTED)
4914 cflags = io_put_recv_kbuf(req);
4915 if (kmsg->iov != kmsg->fast_iov)
4917 req->flags &= ~REQ_F_NEED_CLEANUP;
4919 req_set_fail_links(req);
4920 __io_req_complete(req, ret, cflags, cs);
4924 static int io_recv(struct io_kiocb *req, bool force_nonblock,
4925 struct io_comp_state *cs)
4927 struct io_buffer *kbuf;
4928 struct io_sr_msg *sr = &req->sr_msg;
4930 void __user *buf = sr->buf;
4931 struct socket *sock;
4934 int ret, cflags = 0;
4936 sock = sock_from_file(req->file);
4937 if (unlikely(!sock))
4940 if (req->flags & REQ_F_BUFFER_SELECT) {
4941 kbuf = io_recv_buffer_select(req, !force_nonblock);
4943 return PTR_ERR(kbuf);
4944 buf = u64_to_user_ptr(kbuf->addr);
4947 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4951 msg.msg_name = NULL;
4952 msg.msg_control = NULL;
4953 msg.msg_controllen = 0;
4954 msg.msg_namelen = 0;
4955 msg.msg_iocb = NULL;
4958 flags = req->sr_msg.msg_flags;
4959 if (flags & MSG_DONTWAIT)
4960 req->flags |= REQ_F_NOWAIT;
4961 else if (force_nonblock)
4962 flags |= MSG_DONTWAIT;
4964 ret = sock_recvmsg(sock, &msg, flags);
4965 if (force_nonblock && ret == -EAGAIN)
4967 if (ret == -ERESTARTSYS)
4970 if (req->flags & REQ_F_BUFFER_SELECTED)
4971 cflags = io_put_recv_kbuf(req);
4973 req_set_fail_links(req);
4974 __io_req_complete(req, ret, cflags, cs);
4978 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4980 struct io_accept *accept = &req->accept;
4982 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4984 if (sqe->ioprio || sqe->len || sqe->buf_index)
4987 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4988 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4989 accept->flags = READ_ONCE(sqe->accept_flags);
4990 accept->nofile = rlimit(RLIMIT_NOFILE);
4994 static int io_accept(struct io_kiocb *req, bool force_nonblock,
4995 struct io_comp_state *cs)
4997 struct io_accept *accept = &req->accept;
4998 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5001 if (req->file->f_flags & O_NONBLOCK)
5002 req->flags |= REQ_F_NOWAIT;
5004 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
5005 accept->addr_len, accept->flags,
5007 if (ret == -EAGAIN && force_nonblock)
5010 if (ret == -ERESTARTSYS)
5012 req_set_fail_links(req);
5014 __io_req_complete(req, ret, 0, cs);
5018 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5020 struct io_connect *conn = &req->connect;
5021 struct io_async_connect *io = req->async_data;
5023 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5025 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
5028 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5029 conn->addr_len = READ_ONCE(sqe->addr2);
5034 return move_addr_to_kernel(conn->addr, conn->addr_len,
5038 static int io_connect(struct io_kiocb *req, bool force_nonblock,
5039 struct io_comp_state *cs)
5041 struct io_async_connect __io, *io;
5042 unsigned file_flags;
5045 if (req->async_data) {
5046 io = req->async_data;
5048 ret = move_addr_to_kernel(req->connect.addr,
5049 req->connect.addr_len,
5056 file_flags = force_nonblock ? O_NONBLOCK : 0;
5058 ret = __sys_connect_file(req->file, &io->address,
5059 req->connect.addr_len, file_flags);
5060 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5061 if (req->async_data)
5063 if (io_alloc_async_data(req)) {
5067 io = req->async_data;
5068 memcpy(req->async_data, &__io, sizeof(__io));
5071 if (ret == -ERESTARTSYS)
5075 req_set_fail_links(req);
5076 __io_req_complete(req, ret, 0, cs);
5079 #else /* !CONFIG_NET */
5080 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5085 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
5086 struct io_comp_state *cs)
5091 static int io_send(struct io_kiocb *req, bool force_nonblock,
5092 struct io_comp_state *cs)
5097 static int io_recvmsg_prep(struct io_kiocb *req,
5098 const struct io_uring_sqe *sqe)
5103 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
5104 struct io_comp_state *cs)
5109 static int io_recv(struct io_kiocb *req, bool force_nonblock,
5110 struct io_comp_state *cs)
5115 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5120 static int io_accept(struct io_kiocb *req, bool force_nonblock,
5121 struct io_comp_state *cs)
5126 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5131 static int io_connect(struct io_kiocb *req, bool force_nonblock,
5132 struct io_comp_state *cs)
5136 #endif /* CONFIG_NET */
5138 struct io_poll_table {
5139 struct poll_table_struct pt;
5140 struct io_kiocb *req;
5144 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
5145 __poll_t mask, task_work_func_t func)
5149 /* for instances that support it check for an event match first: */
5150 if (mask && !(mask & poll->events))
5153 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
5155 list_del_init(&poll->wait.entry);
5158 init_task_work(&req->task_work, func);
5159 percpu_ref_get(&req->ctx->refs);
5162 * If this fails, then the task is exiting. When a task exits, the
5163 * work gets canceled, so just cancel this request as well instead
5164 * of executing it. We can't safely execute it anyway, as we may not
5165 * have the needed state needed for it anyway.
5167 ret = io_req_task_work_add(req);
5168 if (unlikely(ret)) {
5169 struct task_struct *tsk;
5171 WRITE_ONCE(poll->canceled, true);
5172 tsk = io_wq_get_task(req->ctx->io_wq);
5173 task_work_add(tsk, &req->task_work, TWA_NONE);
5174 wake_up_process(tsk);
5179 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
5180 __acquires(&req->ctx->completion_lock)
5182 struct io_ring_ctx *ctx = req->ctx;
5184 if (!req->result && !READ_ONCE(poll->canceled)) {
5185 struct poll_table_struct pt = { ._key = poll->events };
5187 req->result = vfs_poll(req->file, &pt) & poll->events;
5190 spin_lock_irq(&ctx->completion_lock);
5191 if (!req->result && !READ_ONCE(poll->canceled)) {
5192 add_wait_queue(poll->head, &poll->wait);
5199 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5201 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5202 if (req->opcode == IORING_OP_POLL_ADD)
5203 return req->async_data;
5204 return req->apoll->double_poll;
5207 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5209 if (req->opcode == IORING_OP_POLL_ADD)
5211 return &req->apoll->poll;
5214 static void io_poll_remove_double(struct io_kiocb *req)
5216 struct io_poll_iocb *poll = io_poll_get_double(req);
5218 lockdep_assert_held(&req->ctx->completion_lock);
5220 if (poll && poll->head) {
5221 struct wait_queue_head *head = poll->head;
5223 spin_lock(&head->lock);
5224 list_del_init(&poll->wait.entry);
5225 if (poll->wait.private)
5226 refcount_dec(&req->refs);
5228 spin_unlock(&head->lock);
5232 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
5234 struct io_ring_ctx *ctx = req->ctx;
5236 io_poll_remove_double(req);
5237 req->poll.done = true;
5238 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
5239 io_commit_cqring(ctx);
5242 static void io_poll_task_func(struct callback_head *cb)
5244 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5245 struct io_ring_ctx *ctx = req->ctx;
5246 struct io_kiocb *nxt;
5248 if (io_poll_rewait(req, &req->poll)) {
5249 spin_unlock_irq(&ctx->completion_lock);
5251 hash_del(&req->hash_node);
5252 io_poll_complete(req, req->result, 0);
5253 spin_unlock_irq(&ctx->completion_lock);
5255 nxt = io_put_req_find_next(req);
5256 io_cqring_ev_posted(ctx);
5258 __io_req_task_submit(nxt);
5261 percpu_ref_put(&ctx->refs);
5264 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
5265 int sync, void *key)
5267 struct io_kiocb *req = wait->private;
5268 struct io_poll_iocb *poll = io_poll_get_single(req);
5269 __poll_t mask = key_to_poll(key);
5271 /* for instances that support it check for an event match first: */
5272 if (mask && !(mask & poll->events))
5275 list_del_init(&wait->entry);
5277 if (poll && poll->head) {
5280 spin_lock(&poll->head->lock);
5281 done = list_empty(&poll->wait.entry);
5283 list_del_init(&poll->wait.entry);
5284 /* make sure double remove sees this as being gone */
5285 wait->private = NULL;
5286 spin_unlock(&poll->head->lock);
5288 /* use wait func handler, so it matches the rq type */
5289 poll->wait.func(&poll->wait, mode, sync, key);
5292 refcount_dec(&req->refs);
5296 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5297 wait_queue_func_t wake_func)
5301 poll->canceled = false;
5302 poll->events = events;
5303 INIT_LIST_HEAD(&poll->wait.entry);
5304 init_waitqueue_func_entry(&poll->wait, wake_func);
5307 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5308 struct wait_queue_head *head,
5309 struct io_poll_iocb **poll_ptr)
5311 struct io_kiocb *req = pt->req;
5314 * If poll->head is already set, it's because the file being polled
5315 * uses multiple waitqueues for poll handling (eg one for read, one
5316 * for write). Setup a separate io_poll_iocb if this happens.
5318 if (unlikely(poll->head)) {
5319 struct io_poll_iocb *poll_one = poll;
5321 /* already have a 2nd entry, fail a third attempt */
5323 pt->error = -EINVAL;
5326 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5328 pt->error = -ENOMEM;
5331 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5332 refcount_inc(&req->refs);
5333 poll->wait.private = req;
5340 if (poll->events & EPOLLEXCLUSIVE)
5341 add_wait_queue_exclusive(head, &poll->wait);
5343 add_wait_queue(head, &poll->wait);
5346 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5347 struct poll_table_struct *p)
5349 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5350 struct async_poll *apoll = pt->req->apoll;
5352 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5355 static void io_async_task_func(struct callback_head *cb)
5357 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5358 struct async_poll *apoll = req->apoll;
5359 struct io_ring_ctx *ctx = req->ctx;
5361 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
5363 if (io_poll_rewait(req, &apoll->poll)) {
5364 spin_unlock_irq(&ctx->completion_lock);
5365 percpu_ref_put(&ctx->refs);
5369 /* If req is still hashed, it cannot have been canceled. Don't check. */
5370 if (hash_hashed(&req->hash_node))
5371 hash_del(&req->hash_node);
5373 io_poll_remove_double(req);
5374 spin_unlock_irq(&ctx->completion_lock);
5376 if (!READ_ONCE(apoll->poll.canceled))
5377 __io_req_task_submit(req);
5379 __io_req_task_cancel(req, -ECANCELED);
5381 percpu_ref_put(&ctx->refs);
5382 kfree(apoll->double_poll);
5386 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5389 struct io_kiocb *req = wait->private;
5390 struct io_poll_iocb *poll = &req->apoll->poll;
5392 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5395 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5398 static void io_poll_req_insert(struct io_kiocb *req)
5400 struct io_ring_ctx *ctx = req->ctx;
5401 struct hlist_head *list;
5403 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5404 hlist_add_head(&req->hash_node, list);
5407 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5408 struct io_poll_iocb *poll,
5409 struct io_poll_table *ipt, __poll_t mask,
5410 wait_queue_func_t wake_func)
5411 __acquires(&ctx->completion_lock)
5413 struct io_ring_ctx *ctx = req->ctx;
5414 bool cancel = false;
5416 INIT_HLIST_NODE(&req->hash_node);
5417 io_init_poll_iocb(poll, mask, wake_func);
5418 poll->file = req->file;
5419 poll->wait.private = req;
5421 ipt->pt._key = mask;
5423 ipt->error = -EINVAL;
5425 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5427 spin_lock_irq(&ctx->completion_lock);
5428 if (likely(poll->head)) {
5429 spin_lock(&poll->head->lock);
5430 if (unlikely(list_empty(&poll->wait.entry))) {
5436 if (mask || ipt->error)
5437 list_del_init(&poll->wait.entry);
5439 WRITE_ONCE(poll->canceled, true);
5440 else if (!poll->done) /* actually waiting for an event */
5441 io_poll_req_insert(req);
5442 spin_unlock(&poll->head->lock);
5448 static bool io_arm_poll_handler(struct io_kiocb *req)
5450 const struct io_op_def *def = &io_op_defs[req->opcode];
5451 struct io_ring_ctx *ctx = req->ctx;
5452 struct async_poll *apoll;
5453 struct io_poll_table ipt;
5457 if (!req->file || !file_can_poll(req->file))
5459 if (req->flags & REQ_F_POLLED)
5463 else if (def->pollout)
5467 /* if we can't nonblock try, then no point in arming a poll handler */
5468 if (!io_file_supports_async(req->file, rw))
5471 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5472 if (unlikely(!apoll))
5474 apoll->double_poll = NULL;
5476 req->flags |= REQ_F_POLLED;
5481 mask |= POLLIN | POLLRDNORM;
5483 mask |= POLLOUT | POLLWRNORM;
5485 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5486 if ((req->opcode == IORING_OP_RECVMSG) &&
5487 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5490 mask |= POLLERR | POLLPRI;
5492 ipt.pt._qproc = io_async_queue_proc;
5494 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5496 if (ret || ipt.error) {
5497 io_poll_remove_double(req);
5498 spin_unlock_irq(&ctx->completion_lock);
5499 kfree(apoll->double_poll);
5503 spin_unlock_irq(&ctx->completion_lock);
5504 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5505 apoll->poll.events);
5509 static bool __io_poll_remove_one(struct io_kiocb *req,
5510 struct io_poll_iocb *poll)
5512 bool do_complete = false;
5514 spin_lock(&poll->head->lock);
5515 WRITE_ONCE(poll->canceled, true);
5516 if (!list_empty(&poll->wait.entry)) {
5517 list_del_init(&poll->wait.entry);
5520 spin_unlock(&poll->head->lock);
5521 hash_del(&req->hash_node);
5525 static bool io_poll_remove_one(struct io_kiocb *req)
5529 io_poll_remove_double(req);
5531 if (req->opcode == IORING_OP_POLL_ADD) {
5532 do_complete = __io_poll_remove_one(req, &req->poll);
5534 struct async_poll *apoll = req->apoll;
5536 /* non-poll requests have submit ref still */
5537 do_complete = __io_poll_remove_one(req, &apoll->poll);
5540 kfree(apoll->double_poll);
5546 io_cqring_fill_event(req, -ECANCELED);
5547 io_commit_cqring(req->ctx);
5548 req_set_fail_links(req);
5549 io_put_req_deferred(req, 1);
5556 * Returns true if we found and killed one or more poll requests
5558 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5559 struct files_struct *files)
5561 struct hlist_node *tmp;
5562 struct io_kiocb *req;
5565 spin_lock_irq(&ctx->completion_lock);
5566 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5567 struct hlist_head *list;
5569 list = &ctx->cancel_hash[i];
5570 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5571 if (io_match_task(req, tsk, files))
5572 posted += io_poll_remove_one(req);
5575 spin_unlock_irq(&ctx->completion_lock);
5578 io_cqring_ev_posted(ctx);
5583 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5585 struct hlist_head *list;
5586 struct io_kiocb *req;
5588 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5589 hlist_for_each_entry(req, list, hash_node) {
5590 if (sqe_addr != req->user_data)
5592 if (io_poll_remove_one(req))
5600 static int io_poll_remove_prep(struct io_kiocb *req,
5601 const struct io_uring_sqe *sqe)
5603 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5605 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5609 req->poll_remove.addr = READ_ONCE(sqe->addr);
5614 * Find a running poll command that matches one specified in sqe->addr,
5615 * and remove it if found.
5617 static int io_poll_remove(struct io_kiocb *req)
5619 struct io_ring_ctx *ctx = req->ctx;
5622 spin_lock_irq(&ctx->completion_lock);
5623 ret = io_poll_cancel(ctx, req->poll_remove.addr);
5624 spin_unlock_irq(&ctx->completion_lock);
5627 req_set_fail_links(req);
5628 io_req_complete(req, ret);
5632 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5635 struct io_kiocb *req = wait->private;
5636 struct io_poll_iocb *poll = &req->poll;
5638 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5641 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5642 struct poll_table_struct *p)
5644 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5646 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5649 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5651 struct io_poll_iocb *poll = &req->poll;
5654 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5656 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
5659 events = READ_ONCE(sqe->poll32_events);
5661 events = swahw32(events);
5663 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
5664 (events & EPOLLEXCLUSIVE);
5668 static int io_poll_add(struct io_kiocb *req)
5670 struct io_poll_iocb *poll = &req->poll;
5671 struct io_ring_ctx *ctx = req->ctx;
5672 struct io_poll_table ipt;
5675 ipt.pt._qproc = io_poll_queue_proc;
5677 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5680 if (mask) { /* no async, we'd stolen it */
5682 io_poll_complete(req, mask, 0);
5684 spin_unlock_irq(&ctx->completion_lock);
5687 io_cqring_ev_posted(ctx);
5693 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5695 struct io_timeout_data *data = container_of(timer,
5696 struct io_timeout_data, timer);
5697 struct io_kiocb *req = data->req;
5698 struct io_ring_ctx *ctx = req->ctx;
5699 unsigned long flags;
5701 spin_lock_irqsave(&ctx->completion_lock, flags);
5702 list_del_init(&req->timeout.list);
5703 atomic_set(&req->ctx->cq_timeouts,
5704 atomic_read(&req->ctx->cq_timeouts) + 1);
5706 io_cqring_fill_event(req, -ETIME);
5707 io_commit_cqring(ctx);
5708 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5710 io_cqring_ev_posted(ctx);
5711 req_set_fail_links(req);
5713 return HRTIMER_NORESTART;
5716 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5719 struct io_timeout_data *io;
5720 struct io_kiocb *req;
5723 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5724 if (user_data == req->user_data) {
5731 return ERR_PTR(ret);
5733 io = req->async_data;
5734 ret = hrtimer_try_to_cancel(&io->timer);
5736 return ERR_PTR(-EALREADY);
5737 list_del_init(&req->timeout.list);
5741 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5743 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5746 return PTR_ERR(req);
5748 req_set_fail_links(req);
5749 io_cqring_fill_event(req, -ECANCELED);
5750 io_put_req_deferred(req, 1);
5754 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5755 struct timespec64 *ts, enum hrtimer_mode mode)
5757 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5758 struct io_timeout_data *data;
5761 return PTR_ERR(req);
5763 req->timeout.off = 0; /* noseq */
5764 data = req->async_data;
5765 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5766 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5767 data->timer.function = io_timeout_fn;
5768 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5772 static int io_timeout_remove_prep(struct io_kiocb *req,
5773 const struct io_uring_sqe *sqe)
5775 struct io_timeout_rem *tr = &req->timeout_rem;
5777 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5779 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5781 if (sqe->ioprio || sqe->buf_index || sqe->len)
5784 tr->addr = READ_ONCE(sqe->addr);
5785 tr->flags = READ_ONCE(sqe->timeout_flags);
5786 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5787 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5789 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5791 } else if (tr->flags) {
5792 /* timeout removal doesn't support flags */
5800 * Remove or update an existing timeout command
5802 static int io_timeout_remove(struct io_kiocb *req)
5804 struct io_timeout_rem *tr = &req->timeout_rem;
5805 struct io_ring_ctx *ctx = req->ctx;
5808 spin_lock_irq(&ctx->completion_lock);
5809 if (req->timeout_rem.flags & IORING_TIMEOUT_UPDATE) {
5810 enum hrtimer_mode mode = (tr->flags & IORING_TIMEOUT_ABS)
5811 ? HRTIMER_MODE_ABS : HRTIMER_MODE_REL;
5813 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
5815 ret = io_timeout_cancel(ctx, tr->addr);
5818 io_cqring_fill_event(req, ret);
5819 io_commit_cqring(ctx);
5820 spin_unlock_irq(&ctx->completion_lock);
5821 io_cqring_ev_posted(ctx);
5823 req_set_fail_links(req);
5828 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5829 bool is_timeout_link)
5831 struct io_timeout_data *data;
5833 u32 off = READ_ONCE(sqe->off);
5835 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5837 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5839 if (off && is_timeout_link)
5841 flags = READ_ONCE(sqe->timeout_flags);
5842 if (flags & ~IORING_TIMEOUT_ABS)
5845 req->timeout.off = off;
5847 if (!req->async_data && io_alloc_async_data(req))
5850 data = req->async_data;
5853 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5856 if (flags & IORING_TIMEOUT_ABS)
5857 data->mode = HRTIMER_MODE_ABS;
5859 data->mode = HRTIMER_MODE_REL;
5861 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5865 static int io_timeout(struct io_kiocb *req)
5867 struct io_ring_ctx *ctx = req->ctx;
5868 struct io_timeout_data *data = req->async_data;
5869 struct list_head *entry;
5870 u32 tail, off = req->timeout.off;
5872 spin_lock_irq(&ctx->completion_lock);
5875 * sqe->off holds how many events that need to occur for this
5876 * timeout event to be satisfied. If it isn't set, then this is
5877 * a pure timeout request, sequence isn't used.
5879 if (io_is_timeout_noseq(req)) {
5880 entry = ctx->timeout_list.prev;
5884 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5885 req->timeout.target_seq = tail + off;
5887 /* Update the last seq here in case io_flush_timeouts() hasn't.
5888 * This is safe because ->completion_lock is held, and submissions
5889 * and completions are never mixed in the same ->completion_lock section.
5891 ctx->cq_last_tm_flush = tail;
5894 * Insertion sort, ensuring the first entry in the list is always
5895 * the one we need first.
5897 list_for_each_prev(entry, &ctx->timeout_list) {
5898 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5901 if (io_is_timeout_noseq(nxt))
5903 /* nxt.seq is behind @tail, otherwise would've been completed */
5904 if (off >= nxt->timeout.target_seq - tail)
5908 list_add(&req->timeout.list, entry);
5909 data->timer.function = io_timeout_fn;
5910 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5911 spin_unlock_irq(&ctx->completion_lock);
5915 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5917 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5919 return req->user_data == (unsigned long) data;
5922 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
5924 enum io_wq_cancel cancel_ret;
5927 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr, false);
5928 switch (cancel_ret) {
5929 case IO_WQ_CANCEL_OK:
5932 case IO_WQ_CANCEL_RUNNING:
5935 case IO_WQ_CANCEL_NOTFOUND:
5943 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5944 struct io_kiocb *req, __u64 sqe_addr,
5947 unsigned long flags;
5950 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
5951 if (ret != -ENOENT) {
5952 spin_lock_irqsave(&ctx->completion_lock, flags);
5956 spin_lock_irqsave(&ctx->completion_lock, flags);
5957 ret = io_timeout_cancel(ctx, sqe_addr);
5960 ret = io_poll_cancel(ctx, sqe_addr);
5964 io_cqring_fill_event(req, ret);
5965 io_commit_cqring(ctx);
5966 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5967 io_cqring_ev_posted(ctx);
5970 req_set_fail_links(req);
5974 static int io_async_cancel_prep(struct io_kiocb *req,
5975 const struct io_uring_sqe *sqe)
5977 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5979 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5981 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5984 req->cancel.addr = READ_ONCE(sqe->addr);
5988 static int io_async_cancel(struct io_kiocb *req)
5990 struct io_ring_ctx *ctx = req->ctx;
5992 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
5996 static int io_rsrc_update_prep(struct io_kiocb *req,
5997 const struct io_uring_sqe *sqe)
5999 if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
6001 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6003 if (sqe->ioprio || sqe->rw_flags)
6006 req->rsrc_update.offset = READ_ONCE(sqe->off);
6007 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6008 if (!req->rsrc_update.nr_args)
6010 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6014 static int io_files_update(struct io_kiocb *req, bool force_nonblock,
6015 struct io_comp_state *cs)
6017 struct io_ring_ctx *ctx = req->ctx;
6018 struct io_uring_rsrc_update up;
6024 up.offset = req->rsrc_update.offset;
6025 up.data = req->rsrc_update.arg;
6027 mutex_lock(&ctx->uring_lock);
6028 ret = __io_sqe_files_update(ctx, &up, req->rsrc_update.nr_args);
6029 mutex_unlock(&ctx->uring_lock);
6032 req_set_fail_links(req);
6033 __io_req_complete(req, ret, 0, cs);
6037 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6039 switch (req->opcode) {
6042 case IORING_OP_READV:
6043 case IORING_OP_READ_FIXED:
6044 case IORING_OP_READ:
6045 return io_read_prep(req, sqe);
6046 case IORING_OP_WRITEV:
6047 case IORING_OP_WRITE_FIXED:
6048 case IORING_OP_WRITE:
6049 return io_write_prep(req, sqe);
6050 case IORING_OP_POLL_ADD:
6051 return io_poll_add_prep(req, sqe);
6052 case IORING_OP_POLL_REMOVE:
6053 return io_poll_remove_prep(req, sqe);
6054 case IORING_OP_FSYNC:
6055 return io_prep_fsync(req, sqe);
6056 case IORING_OP_SYNC_FILE_RANGE:
6057 return io_prep_sfr(req, sqe);
6058 case IORING_OP_SENDMSG:
6059 case IORING_OP_SEND:
6060 return io_sendmsg_prep(req, sqe);
6061 case IORING_OP_RECVMSG:
6062 case IORING_OP_RECV:
6063 return io_recvmsg_prep(req, sqe);
6064 case IORING_OP_CONNECT:
6065 return io_connect_prep(req, sqe);
6066 case IORING_OP_TIMEOUT:
6067 return io_timeout_prep(req, sqe, false);
6068 case IORING_OP_TIMEOUT_REMOVE:
6069 return io_timeout_remove_prep(req, sqe);
6070 case IORING_OP_ASYNC_CANCEL:
6071 return io_async_cancel_prep(req, sqe);
6072 case IORING_OP_LINK_TIMEOUT:
6073 return io_timeout_prep(req, sqe, true);
6074 case IORING_OP_ACCEPT:
6075 return io_accept_prep(req, sqe);
6076 case IORING_OP_FALLOCATE:
6077 return io_fallocate_prep(req, sqe);
6078 case IORING_OP_OPENAT:
6079 return io_openat_prep(req, sqe);
6080 case IORING_OP_CLOSE:
6081 return io_close_prep(req, sqe);
6082 case IORING_OP_FILES_UPDATE:
6083 return io_rsrc_update_prep(req, sqe);
6084 case IORING_OP_STATX:
6085 return io_statx_prep(req, sqe);
6086 case IORING_OP_FADVISE:
6087 return io_fadvise_prep(req, sqe);
6088 case IORING_OP_MADVISE:
6089 return io_madvise_prep(req, sqe);
6090 case IORING_OP_OPENAT2:
6091 return io_openat2_prep(req, sqe);
6092 case IORING_OP_EPOLL_CTL:
6093 return io_epoll_ctl_prep(req, sqe);
6094 case IORING_OP_SPLICE:
6095 return io_splice_prep(req, sqe);
6096 case IORING_OP_PROVIDE_BUFFERS:
6097 return io_provide_buffers_prep(req, sqe);
6098 case IORING_OP_REMOVE_BUFFERS:
6099 return io_remove_buffers_prep(req, sqe);
6101 return io_tee_prep(req, sqe);
6102 case IORING_OP_SHUTDOWN:
6103 return io_shutdown_prep(req, sqe);
6104 case IORING_OP_RENAMEAT:
6105 return io_renameat_prep(req, sqe);
6106 case IORING_OP_UNLINKAT:
6107 return io_unlinkat_prep(req, sqe);
6110 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6115 static int io_req_defer_prep(struct io_kiocb *req,
6116 const struct io_uring_sqe *sqe)
6120 if (io_alloc_async_data(req))
6122 return io_req_prep(req, sqe);
6125 static u32 io_get_sequence(struct io_kiocb *req)
6127 struct io_kiocb *pos;
6128 struct io_ring_ctx *ctx = req->ctx;
6129 u32 total_submitted, nr_reqs = 0;
6131 io_for_each_link(pos, req)
6134 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
6135 return total_submitted - nr_reqs;
6138 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6140 struct io_ring_ctx *ctx = req->ctx;
6141 struct io_defer_entry *de;
6145 /* Still need defer if there is pending req in defer list. */
6146 if (likely(list_empty_careful(&ctx->defer_list) &&
6147 !(req->flags & REQ_F_IO_DRAIN)))
6150 seq = io_get_sequence(req);
6151 /* Still a chance to pass the sequence check */
6152 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6155 if (!req->async_data) {
6156 ret = io_req_defer_prep(req, sqe);
6160 io_prep_async_link(req);
6161 de = kmalloc(sizeof(*de), GFP_KERNEL);
6165 spin_lock_irq(&ctx->completion_lock);
6166 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6167 spin_unlock_irq(&ctx->completion_lock);
6169 io_queue_async_work(req);
6170 return -EIOCBQUEUED;
6173 trace_io_uring_defer(ctx, req, req->user_data);
6176 list_add_tail(&de->list, &ctx->defer_list);
6177 spin_unlock_irq(&ctx->completion_lock);
6178 return -EIOCBQUEUED;
6181 static void io_req_drop_files(struct io_kiocb *req)
6183 struct io_ring_ctx *ctx = req->ctx;
6184 struct io_uring_task *tctx = req->task->io_uring;
6185 unsigned long flags;
6187 if (req->work.flags & IO_WQ_WORK_FILES) {
6188 put_files_struct(req->work.identity->files);
6189 put_nsproxy(req->work.identity->nsproxy);
6191 spin_lock_irqsave(&ctx->inflight_lock, flags);
6192 list_del(&req->inflight_entry);
6193 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
6194 req->flags &= ~REQ_F_INFLIGHT;
6195 req->work.flags &= ~IO_WQ_WORK_FILES;
6196 if (atomic_read(&tctx->in_idle))
6197 wake_up(&tctx->wait);
6200 static void __io_clean_op(struct io_kiocb *req)
6202 if (req->flags & REQ_F_BUFFER_SELECTED) {
6203 switch (req->opcode) {
6204 case IORING_OP_READV:
6205 case IORING_OP_READ_FIXED:
6206 case IORING_OP_READ:
6207 kfree((void *)(unsigned long)req->rw.addr);
6209 case IORING_OP_RECVMSG:
6210 case IORING_OP_RECV:
6211 kfree(req->sr_msg.kbuf);
6214 req->flags &= ~REQ_F_BUFFER_SELECTED;
6217 if (req->flags & REQ_F_NEED_CLEANUP) {
6218 switch (req->opcode) {
6219 case IORING_OP_READV:
6220 case IORING_OP_READ_FIXED:
6221 case IORING_OP_READ:
6222 case IORING_OP_WRITEV:
6223 case IORING_OP_WRITE_FIXED:
6224 case IORING_OP_WRITE: {
6225 struct io_async_rw *io = req->async_data;
6227 kfree(io->free_iovec);
6230 case IORING_OP_RECVMSG:
6231 case IORING_OP_SENDMSG: {
6232 struct io_async_msghdr *io = req->async_data;
6233 if (io->iov != io->fast_iov)
6237 case IORING_OP_SPLICE:
6239 io_put_file(req, req->splice.file_in,
6240 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
6242 case IORING_OP_OPENAT:
6243 case IORING_OP_OPENAT2:
6244 if (req->open.filename)
6245 putname(req->open.filename);
6247 case IORING_OP_RENAMEAT:
6248 putname(req->rename.oldpath);
6249 putname(req->rename.newpath);
6251 case IORING_OP_UNLINKAT:
6252 putname(req->unlink.filename);
6255 req->flags &= ~REQ_F_NEED_CLEANUP;
6259 static int io_issue_sqe(struct io_kiocb *req, bool force_nonblock,
6260 struct io_comp_state *cs)
6262 struct io_ring_ctx *ctx = req->ctx;
6265 switch (req->opcode) {
6267 ret = io_nop(req, cs);
6269 case IORING_OP_READV:
6270 case IORING_OP_READ_FIXED:
6271 case IORING_OP_READ:
6272 ret = io_read(req, force_nonblock, cs);
6274 case IORING_OP_WRITEV:
6275 case IORING_OP_WRITE_FIXED:
6276 case IORING_OP_WRITE:
6277 ret = io_write(req, force_nonblock, cs);
6279 case IORING_OP_FSYNC:
6280 ret = io_fsync(req, force_nonblock);
6282 case IORING_OP_POLL_ADD:
6283 ret = io_poll_add(req);
6285 case IORING_OP_POLL_REMOVE:
6286 ret = io_poll_remove(req);
6288 case IORING_OP_SYNC_FILE_RANGE:
6289 ret = io_sync_file_range(req, force_nonblock);
6291 case IORING_OP_SENDMSG:
6292 ret = io_sendmsg(req, force_nonblock, cs);
6294 case IORING_OP_SEND:
6295 ret = io_send(req, force_nonblock, cs);
6297 case IORING_OP_RECVMSG:
6298 ret = io_recvmsg(req, force_nonblock, cs);
6300 case IORING_OP_RECV:
6301 ret = io_recv(req, force_nonblock, cs);
6303 case IORING_OP_TIMEOUT:
6304 ret = io_timeout(req);
6306 case IORING_OP_TIMEOUT_REMOVE:
6307 ret = io_timeout_remove(req);
6309 case IORING_OP_ACCEPT:
6310 ret = io_accept(req, force_nonblock, cs);
6312 case IORING_OP_CONNECT:
6313 ret = io_connect(req, force_nonblock, cs);
6315 case IORING_OP_ASYNC_CANCEL:
6316 ret = io_async_cancel(req);
6318 case IORING_OP_FALLOCATE:
6319 ret = io_fallocate(req, force_nonblock);
6321 case IORING_OP_OPENAT:
6322 ret = io_openat(req, force_nonblock);
6324 case IORING_OP_CLOSE:
6325 ret = io_close(req, force_nonblock, cs);
6327 case IORING_OP_FILES_UPDATE:
6328 ret = io_files_update(req, force_nonblock, cs);
6330 case IORING_OP_STATX:
6331 ret = io_statx(req, force_nonblock);
6333 case IORING_OP_FADVISE:
6334 ret = io_fadvise(req, force_nonblock);
6336 case IORING_OP_MADVISE:
6337 ret = io_madvise(req, force_nonblock);
6339 case IORING_OP_OPENAT2:
6340 ret = io_openat2(req, force_nonblock);
6342 case IORING_OP_EPOLL_CTL:
6343 ret = io_epoll_ctl(req, force_nonblock, cs);
6345 case IORING_OP_SPLICE:
6346 ret = io_splice(req, force_nonblock);
6348 case IORING_OP_PROVIDE_BUFFERS:
6349 ret = io_provide_buffers(req, force_nonblock, cs);
6351 case IORING_OP_REMOVE_BUFFERS:
6352 ret = io_remove_buffers(req, force_nonblock, cs);
6355 ret = io_tee(req, force_nonblock);
6357 case IORING_OP_SHUTDOWN:
6358 ret = io_shutdown(req, force_nonblock);
6360 case IORING_OP_RENAMEAT:
6361 ret = io_renameat(req, force_nonblock);
6363 case IORING_OP_UNLINKAT:
6364 ret = io_unlinkat(req, force_nonblock);
6374 /* If the op doesn't have a file, we're not polling for it */
6375 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
6376 const bool in_async = io_wq_current_is_worker();
6378 /* workqueue context doesn't hold uring_lock, grab it now */
6380 mutex_lock(&ctx->uring_lock);
6382 io_iopoll_req_issued(req, in_async);
6385 mutex_unlock(&ctx->uring_lock);
6391 static struct io_wq_work *io_wq_submit_work(struct io_wq_work *work)
6393 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6394 struct io_kiocb *timeout;
6397 timeout = io_prep_linked_timeout(req);
6399 io_queue_linked_timeout(timeout);
6401 /* if NO_CANCEL is set, we must still run the work */
6402 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
6403 IO_WQ_WORK_CANCEL) {
6409 ret = io_issue_sqe(req, false, NULL);
6411 * We can get EAGAIN for polled IO even though we're
6412 * forcing a sync submission from here, since we can't
6413 * wait for request slots on the block side.
6422 struct io_ring_ctx *lock_ctx = NULL;
6424 if (req->ctx->flags & IORING_SETUP_IOPOLL)
6425 lock_ctx = req->ctx;
6428 * io_iopoll_complete() does not hold completion_lock to
6429 * complete polled io, so here for polled io, we can not call
6430 * io_req_complete() directly, otherwise there maybe concurrent
6431 * access to cqring, defer_list, etc, which is not safe. Given
6432 * that io_iopoll_complete() is always called under uring_lock,
6433 * so here for polled io, we also get uring_lock to complete
6437 mutex_lock(&lock_ctx->uring_lock);
6439 req_set_fail_links(req);
6440 io_req_complete(req, ret);
6443 mutex_unlock(&lock_ctx->uring_lock);
6446 return io_steal_work(req);
6449 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6452 struct fixed_rsrc_table *table;
6454 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
6455 return table->files[index & IORING_FILE_TABLE_MASK];
6458 static struct file *io_file_get(struct io_submit_state *state,
6459 struct io_kiocb *req, int fd, bool fixed)
6461 struct io_ring_ctx *ctx = req->ctx;
6465 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6467 fd = array_index_nospec(fd, ctx->nr_user_files);
6468 file = io_file_from_index(ctx, fd);
6469 io_set_resource_node(req);
6471 trace_io_uring_file_get(ctx, fd);
6472 file = __io_file_get(state, fd);
6475 if (file && file->f_op == &io_uring_fops &&
6476 !(req->flags & REQ_F_INFLIGHT)) {
6477 io_req_init_async(req);
6478 req->flags |= REQ_F_INFLIGHT;
6480 spin_lock_irq(&ctx->inflight_lock);
6481 list_add(&req->inflight_entry, &ctx->inflight_list);
6482 spin_unlock_irq(&ctx->inflight_lock);
6488 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6490 struct io_timeout_data *data = container_of(timer,
6491 struct io_timeout_data, timer);
6492 struct io_kiocb *prev, *req = data->req;
6493 struct io_ring_ctx *ctx = req->ctx;
6494 unsigned long flags;
6496 spin_lock_irqsave(&ctx->completion_lock, flags);
6497 prev = req->timeout.head;
6498 req->timeout.head = NULL;
6501 * We don't expect the list to be empty, that will only happen if we
6502 * race with the completion of the linked work.
6504 if (prev && refcount_inc_not_zero(&prev->refs))
6505 io_remove_next_linked(prev);
6508 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6511 req_set_fail_links(prev);
6512 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6515 io_req_complete(req, -ETIME);
6517 return HRTIMER_NORESTART;
6520 static void __io_queue_linked_timeout(struct io_kiocb *req)
6523 * If the back reference is NULL, then our linked request finished
6524 * before we got a chance to setup the timer
6526 if (req->timeout.head) {
6527 struct io_timeout_data *data = req->async_data;
6529 data->timer.function = io_link_timeout_fn;
6530 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6535 static void io_queue_linked_timeout(struct io_kiocb *req)
6537 struct io_ring_ctx *ctx = req->ctx;
6539 spin_lock_irq(&ctx->completion_lock);
6540 __io_queue_linked_timeout(req);
6541 spin_unlock_irq(&ctx->completion_lock);
6543 /* drop submission reference */
6547 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6549 struct io_kiocb *nxt = req->link;
6551 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6552 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6555 nxt->timeout.head = req;
6556 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6557 req->flags |= REQ_F_LINK_TIMEOUT;
6561 static void __io_queue_sqe(struct io_kiocb *req, struct io_comp_state *cs)
6563 struct io_kiocb *linked_timeout;
6564 const struct cred *old_creds = NULL;
6568 linked_timeout = io_prep_linked_timeout(req);
6570 if ((req->flags & REQ_F_WORK_INITIALIZED) &&
6571 (req->work.flags & IO_WQ_WORK_CREDS) &&
6572 req->work.identity->creds != current_cred()) {
6574 revert_creds(old_creds);
6575 if (old_creds == req->work.identity->creds)
6576 old_creds = NULL; /* restored original creds */
6578 old_creds = override_creds(req->work.identity->creds);
6581 ret = io_issue_sqe(req, true, cs);
6584 * We async punt it if the file wasn't marked NOWAIT, or if the file
6585 * doesn't support non-blocking read/write attempts
6587 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6588 if (!io_arm_poll_handler(req)) {
6590 * Queued up for async execution, worker will release
6591 * submit reference when the iocb is actually submitted.
6593 io_queue_async_work(req);
6597 io_queue_linked_timeout(linked_timeout);
6598 } else if (likely(!ret)) {
6599 /* drop submission reference */
6600 req = io_put_req_find_next(req);
6602 io_queue_linked_timeout(linked_timeout);
6605 if (!(req->flags & REQ_F_FORCE_ASYNC))
6607 io_queue_async_work(req);
6610 /* un-prep timeout, so it'll be killed as any other linked */
6611 req->flags &= ~REQ_F_LINK_TIMEOUT;
6612 req_set_fail_links(req);
6614 io_req_complete(req, ret);
6618 revert_creds(old_creds);
6621 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6622 struct io_comp_state *cs)
6626 ret = io_req_defer(req, sqe);
6628 if (ret != -EIOCBQUEUED) {
6630 req_set_fail_links(req);
6632 io_req_complete(req, ret);
6634 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6635 if (!req->async_data) {
6636 ret = io_req_defer_prep(req, sqe);
6640 io_queue_async_work(req);
6643 ret = io_req_prep(req, sqe);
6647 __io_queue_sqe(req, cs);
6651 static inline void io_queue_link_head(struct io_kiocb *req,
6652 struct io_comp_state *cs)
6654 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
6656 io_req_complete(req, -ECANCELED);
6658 io_queue_sqe(req, NULL, cs);
6661 struct io_submit_link {
6662 struct io_kiocb *head;
6663 struct io_kiocb *last;
6666 static int io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6667 struct io_submit_link *link, struct io_comp_state *cs)
6669 struct io_ring_ctx *ctx = req->ctx;
6673 * If we already have a head request, queue this one for async
6674 * submittal once the head completes. If we don't have a head but
6675 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6676 * submitted sync once the chain is complete. If none of those
6677 * conditions are true (normal request), then just queue it.
6680 struct io_kiocb *head = link->head;
6683 * Taking sequential execution of a link, draining both sides
6684 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6685 * requests in the link. So, it drains the head and the
6686 * next after the link request. The last one is done via
6687 * drain_next flag to persist the effect across calls.
6689 if (req->flags & REQ_F_IO_DRAIN) {
6690 head->flags |= REQ_F_IO_DRAIN;
6691 ctx->drain_next = 1;
6693 ret = io_req_defer_prep(req, sqe);
6694 if (unlikely(ret)) {
6695 /* fail even hard links since we don't submit */
6696 head->flags |= REQ_F_FAIL_LINK;
6699 trace_io_uring_link(ctx, req, head);
6700 link->last->link = req;
6703 /* last request of a link, enqueue the link */
6704 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6705 io_queue_link_head(head, cs);
6709 if (unlikely(ctx->drain_next)) {
6710 req->flags |= REQ_F_IO_DRAIN;
6711 ctx->drain_next = 0;
6713 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6714 ret = io_req_defer_prep(req, sqe);
6716 req->flags |= REQ_F_FAIL_LINK;
6720 io_queue_sqe(req, sqe, cs);
6728 * Batched submission is done, ensure local IO is flushed out.
6730 static void io_submit_state_end(struct io_submit_state *state)
6732 if (!list_empty(&state->comp.list))
6733 io_submit_flush_completions(&state->comp);
6734 if (state->plug_started)
6735 blk_finish_plug(&state->plug);
6736 io_state_file_put(state);
6737 if (state->free_reqs)
6738 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
6742 * Start submission side cache.
6744 static void io_submit_state_start(struct io_submit_state *state,
6745 struct io_ring_ctx *ctx, unsigned int max_ios)
6747 state->plug_started = false;
6749 INIT_LIST_HEAD(&state->comp.list);
6750 state->comp.ctx = ctx;
6751 state->free_reqs = 0;
6752 state->file_refs = 0;
6753 state->ios_left = max_ios;
6756 static void io_commit_sqring(struct io_ring_ctx *ctx)
6758 struct io_rings *rings = ctx->rings;
6761 * Ensure any loads from the SQEs are done at this point,
6762 * since once we write the new head, the application could
6763 * write new data to them.
6765 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6769 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6770 * that is mapped by userspace. This means that care needs to be taken to
6771 * ensure that reads are stable, as we cannot rely on userspace always
6772 * being a good citizen. If members of the sqe are validated and then later
6773 * used, it's important that those reads are done through READ_ONCE() to
6774 * prevent a re-load down the line.
6776 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6778 u32 *sq_array = ctx->sq_array;
6782 * The cached sq head (or cq tail) serves two purposes:
6784 * 1) allows us to batch the cost of updating the user visible
6786 * 2) allows the kernel side to track the head on its own, even
6787 * though the application is the one updating it.
6789 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
6790 if (likely(head < ctx->sq_entries))
6791 return &ctx->sq_sqes[head];
6793 /* drop invalid entries */
6794 ctx->cached_sq_dropped++;
6795 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6799 static inline void io_consume_sqe(struct io_ring_ctx *ctx)
6801 ctx->cached_sq_head++;
6805 * Check SQE restrictions (opcode and flags).
6807 * Returns 'true' if SQE is allowed, 'false' otherwise.
6809 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6810 struct io_kiocb *req,
6811 unsigned int sqe_flags)
6813 if (!ctx->restricted)
6816 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6819 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6820 ctx->restrictions.sqe_flags_required)
6823 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6824 ctx->restrictions.sqe_flags_required))
6830 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
6831 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
6832 IOSQE_BUFFER_SELECT)
6834 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6835 const struct io_uring_sqe *sqe,
6836 struct io_submit_state *state)
6838 unsigned int sqe_flags;
6841 req->opcode = READ_ONCE(sqe->opcode);
6842 req->user_data = READ_ONCE(sqe->user_data);
6843 req->async_data = NULL;
6848 req->fixed_rsrc_refs = NULL;
6849 /* one is dropped after submission, the other at completion */
6850 refcount_set(&req->refs, 2);
6851 req->task = current;
6854 if (unlikely(req->opcode >= IORING_OP_LAST))
6857 if (unlikely(io_sq_thread_acquire_mm_files(ctx, req)))
6860 sqe_flags = READ_ONCE(sqe->flags);
6861 /* enforce forwards compatibility on users */
6862 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6865 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6868 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6869 !io_op_defs[req->opcode].buffer_select)
6872 id = READ_ONCE(sqe->personality);
6874 struct io_identity *iod;
6876 iod = idr_find(&ctx->personality_idr, id);
6879 refcount_inc(&iod->count);
6881 __io_req_init_async(req);
6882 get_cred(iod->creds);
6883 req->work.identity = iod;
6884 req->work.flags |= IO_WQ_WORK_CREDS;
6887 /* same numerical values with corresponding REQ_F_*, safe to copy */
6888 req->flags |= sqe_flags;
6891 * Plug now if we have more than 1 IO left after this, and the target
6892 * is potentially a read/write to block based storage.
6894 if (!state->plug_started && state->ios_left > 1 &&
6895 io_op_defs[req->opcode].plug) {
6896 blk_start_plug(&state->plug);
6897 state->plug_started = true;
6901 if (io_op_defs[req->opcode].needs_file) {
6902 bool fixed = req->flags & REQ_F_FIXED_FILE;
6904 req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
6905 if (unlikely(!req->file &&
6906 !io_op_defs[req->opcode].needs_file_no_error))
6914 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6916 struct io_submit_state state;
6917 struct io_submit_link link;
6918 int i, submitted = 0;
6920 /* if we have a backlog and couldn't flush it all, return BUSY */
6921 if (test_bit(0, &ctx->sq_check_overflow)) {
6922 if (!__io_cqring_overflow_flush(ctx, false, NULL, NULL))
6926 /* make sure SQ entry isn't read before tail */
6927 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6929 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6932 percpu_counter_add(¤t->io_uring->inflight, nr);
6933 refcount_add(nr, ¤t->usage);
6935 io_submit_state_start(&state, ctx, nr);
6938 for (i = 0; i < nr; i++) {
6939 const struct io_uring_sqe *sqe;
6940 struct io_kiocb *req;
6943 sqe = io_get_sqe(ctx);
6944 if (unlikely(!sqe)) {
6945 io_consume_sqe(ctx);
6948 req = io_alloc_req(ctx, &state);
6949 if (unlikely(!req)) {
6951 submitted = -EAGAIN;
6954 io_consume_sqe(ctx);
6955 /* will complete beyond this point, count as submitted */
6958 err = io_init_req(ctx, req, sqe, &state);
6959 if (unlikely(err)) {
6962 io_req_complete(req, err);
6966 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6967 true, io_async_submit(ctx));
6968 err = io_submit_sqe(req, sqe, &link, &state.comp);
6973 if (unlikely(submitted != nr)) {
6974 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6975 struct io_uring_task *tctx = current->io_uring;
6976 int unused = nr - ref_used;
6978 percpu_ref_put_many(&ctx->refs, unused);
6979 percpu_counter_sub(&tctx->inflight, unused);
6980 put_task_struct_many(current, unused);
6983 io_queue_link_head(link.head, &state.comp);
6984 io_submit_state_end(&state);
6986 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6987 io_commit_sqring(ctx);
6992 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6994 /* Tell userspace we may need a wakeup call */
6995 spin_lock_irq(&ctx->completion_lock);
6996 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6997 spin_unlock_irq(&ctx->completion_lock);
7000 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7002 spin_lock_irq(&ctx->completion_lock);
7003 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
7004 spin_unlock_irq(&ctx->completion_lock);
7007 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7009 unsigned int to_submit;
7012 to_submit = io_sqring_entries(ctx);
7013 /* if we're handling multiple rings, cap submit size for fairness */
7014 if (cap_entries && to_submit > 8)
7017 if (!list_empty(&ctx->iopoll_list) || to_submit) {
7018 unsigned nr_events = 0;
7020 mutex_lock(&ctx->uring_lock);
7021 if (!list_empty(&ctx->iopoll_list))
7022 io_do_iopoll(ctx, &nr_events, 0);
7024 if (to_submit && !ctx->sqo_dead &&
7025 likely(!percpu_ref_is_dying(&ctx->refs)))
7026 ret = io_submit_sqes(ctx, to_submit);
7027 mutex_unlock(&ctx->uring_lock);
7030 if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
7031 wake_up(&ctx->sqo_sq_wait);
7036 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7038 struct io_ring_ctx *ctx;
7039 unsigned sq_thread_idle = 0;
7041 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7042 if (sq_thread_idle < ctx->sq_thread_idle)
7043 sq_thread_idle = ctx->sq_thread_idle;
7046 sqd->sq_thread_idle = sq_thread_idle;
7049 static void io_sqd_init_new(struct io_sq_data *sqd)
7051 struct io_ring_ctx *ctx;
7053 while (!list_empty(&sqd->ctx_new_list)) {
7054 ctx = list_first_entry(&sqd->ctx_new_list, struct io_ring_ctx, sqd_list);
7055 list_move_tail(&ctx->sqd_list, &sqd->ctx_list);
7056 complete(&ctx->sq_thread_comp);
7059 io_sqd_update_thread_idle(sqd);
7062 static int io_sq_thread(void *data)
7064 struct cgroup_subsys_state *cur_css = NULL;
7065 struct files_struct *old_files = current->files;
7066 struct nsproxy *old_nsproxy = current->nsproxy;
7067 const struct cred *old_cred = NULL;
7068 struct io_sq_data *sqd = data;
7069 struct io_ring_ctx *ctx;
7070 unsigned long timeout = 0;
7074 current->files = NULL;
7075 current->nsproxy = NULL;
7076 task_unlock(current);
7078 while (!kthread_should_stop()) {
7080 bool cap_entries, sqt_spin, needs_sched;
7083 * Any changes to the sqd lists are synchronized through the
7084 * kthread parking. This synchronizes the thread vs users,
7085 * the users are synchronized on the sqd->ctx_lock.
7087 if (kthread_should_park()) {
7090 * When sq thread is unparked, in case the previous park operation
7091 * comes from io_put_sq_data(), which means that sq thread is going
7092 * to be stopped, so here needs to have a check.
7094 if (kthread_should_stop())
7098 if (unlikely(!list_empty(&sqd->ctx_new_list))) {
7099 io_sqd_init_new(sqd);
7100 timeout = jiffies + sqd->sq_thread_idle;
7104 cap_entries = !list_is_singular(&sqd->ctx_list);
7105 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7106 if (current->cred != ctx->creds) {
7108 revert_creds(old_cred);
7109 old_cred = override_creds(ctx->creds);
7111 io_sq_thread_associate_blkcg(ctx, &cur_css);
7113 current->loginuid = ctx->loginuid;
7114 current->sessionid = ctx->sessionid;
7117 ret = __io_sq_thread(ctx, cap_entries);
7118 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
7121 io_sq_thread_drop_mm_files();
7124 if (sqt_spin || !time_after(jiffies, timeout)) {
7126 io_sq_thread_drop_mm_files();
7129 timeout = jiffies + sqd->sq_thread_idle;
7133 if (kthread_should_park())
7137 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7138 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7139 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7140 !list_empty_careful(&ctx->iopoll_list)) {
7141 needs_sched = false;
7144 if (io_sqring_entries(ctx)) {
7145 needs_sched = false;
7151 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7152 io_ring_set_wakeup_flag(ctx);
7155 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7156 io_ring_clear_wakeup_flag(ctx);
7159 finish_wait(&sqd->wait, &wait);
7160 timeout = jiffies + sqd->sq_thread_idle;
7164 io_sq_thread_drop_mm_files();
7167 io_sq_thread_unassociate_blkcg();
7169 revert_creds(old_cred);
7172 current->files = old_files;
7173 current->nsproxy = old_nsproxy;
7174 task_unlock(current);
7181 struct io_wait_queue {
7182 struct wait_queue_entry wq;
7183 struct io_ring_ctx *ctx;
7185 unsigned nr_timeouts;
7188 static inline bool io_should_wake(struct io_wait_queue *iowq)
7190 struct io_ring_ctx *ctx = iowq->ctx;
7193 * Wake up if we have enough events, or if a timeout occurred since we
7194 * started waiting. For timeouts, we always want to return to userspace,
7195 * regardless of event count.
7197 return io_cqring_events(ctx) >= iowq->to_wait ||
7198 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7201 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7202 int wake_flags, void *key)
7204 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7208 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7209 * the task, and the next invocation will do it.
7211 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
7212 return autoremove_wake_function(curr, mode, wake_flags, key);
7216 static int io_run_task_work_sig(void)
7218 if (io_run_task_work())
7220 if (!signal_pending(current))
7222 if (test_tsk_thread_flag(current, TIF_NOTIFY_SIGNAL))
7223 return -ERESTARTSYS;
7228 * Wait until events become available, if we don't already have some. The
7229 * application must reap them itself, as they reside on the shared cq ring.
7231 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7232 const sigset_t __user *sig, size_t sigsz,
7233 struct __kernel_timespec __user *uts)
7235 struct io_wait_queue iowq = {
7238 .func = io_wake_function,
7239 .entry = LIST_HEAD_INIT(iowq.wq.entry),
7242 .to_wait = min_events,
7244 struct io_rings *rings = ctx->rings;
7245 struct timespec64 ts;
7246 signed long timeout = 0;
7250 io_cqring_overflow_flush(ctx, false, NULL, NULL);
7251 if (io_cqring_events(ctx) >= min_events)
7253 if (!io_run_task_work())
7258 #ifdef CONFIG_COMPAT
7259 if (in_compat_syscall())
7260 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7264 ret = set_user_sigmask(sig, sigsz);
7271 if (get_timespec64(&ts, uts))
7273 timeout = timespec64_to_jiffies(&ts);
7276 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7277 trace_io_uring_cqring_wait(ctx, min_events);
7279 io_cqring_overflow_flush(ctx, false, NULL, NULL);
7280 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
7281 TASK_INTERRUPTIBLE);
7282 /* make sure we run task_work before checking for signals */
7283 ret = io_run_task_work_sig();
7285 finish_wait(&ctx->wait, &iowq.wq);
7290 if (io_should_wake(&iowq))
7292 if (test_bit(0, &ctx->cq_check_overflow)) {
7293 finish_wait(&ctx->wait, &iowq.wq);
7297 timeout = schedule_timeout(timeout);
7306 finish_wait(&ctx->wait, &iowq.wq);
7308 restore_saved_sigmask_unless(ret == -EINTR);
7310 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7313 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7315 #if defined(CONFIG_UNIX)
7316 if (ctx->ring_sock) {
7317 struct sock *sock = ctx->ring_sock->sk;
7318 struct sk_buff *skb;
7320 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7326 for (i = 0; i < ctx->nr_user_files; i++) {
7329 file = io_file_from_index(ctx, i);
7336 static void io_rsrc_ref_kill(struct percpu_ref *ref)
7338 struct fixed_rsrc_data *data;
7340 data = container_of(ref, struct fixed_rsrc_data, refs);
7341 complete(&data->done);
7344 static void io_sqe_rsrc_set_node(struct fixed_rsrc_data *rsrc_data,
7345 struct fixed_rsrc_ref_node *ref_node)
7347 spin_lock_bh(&rsrc_data->lock);
7348 rsrc_data->node = ref_node;
7349 list_add_tail(&ref_node->node, &rsrc_data->ref_list);
7350 spin_unlock_bh(&rsrc_data->lock);
7351 percpu_ref_get(&rsrc_data->refs);
7354 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7356 struct fixed_rsrc_data *data = ctx->file_data;
7357 struct fixed_rsrc_ref_node *backup_node, *ref_node = NULL;
7358 unsigned nr_tables, i;
7363 backup_node = alloc_fixed_file_ref_node(ctx);
7367 spin_lock_bh(&data->lock);
7368 ref_node = data->node;
7369 spin_unlock_bh(&data->lock);
7371 percpu_ref_kill(&ref_node->refs);
7373 percpu_ref_kill(&data->refs);
7375 /* wait for all refs nodes to complete */
7376 flush_delayed_work(&ctx->rsrc_put_work);
7378 ret = wait_for_completion_interruptible(&data->done);
7381 ret = io_run_task_work_sig();
7383 percpu_ref_resurrect(&data->refs);
7384 reinit_completion(&data->done);
7385 io_sqe_rsrc_set_node(data, backup_node);
7390 __io_sqe_files_unregister(ctx);
7391 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
7392 for (i = 0; i < nr_tables; i++)
7393 kfree(data->table[i].files);
7395 percpu_ref_exit(&data->refs);
7397 ctx->file_data = NULL;
7398 ctx->nr_user_files = 0;
7399 destroy_fixed_rsrc_ref_node(backup_node);
7403 static void io_put_sq_data(struct io_sq_data *sqd)
7405 if (refcount_dec_and_test(&sqd->refs)) {
7407 * The park is a bit of a work-around, without it we get
7408 * warning spews on shutdown with SQPOLL set and affinity
7409 * set to a single CPU.
7412 kthread_park(sqd->thread);
7413 kthread_stop(sqd->thread);
7420 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7422 struct io_ring_ctx *ctx_attach;
7423 struct io_sq_data *sqd;
7426 f = fdget(p->wq_fd);
7428 return ERR_PTR(-ENXIO);
7429 if (f.file->f_op != &io_uring_fops) {
7431 return ERR_PTR(-EINVAL);
7434 ctx_attach = f.file->private_data;
7435 sqd = ctx_attach->sq_data;
7438 return ERR_PTR(-EINVAL);
7441 refcount_inc(&sqd->refs);
7446 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p)
7448 struct io_sq_data *sqd;
7450 if (p->flags & IORING_SETUP_ATTACH_WQ)
7451 return io_attach_sq_data(p);
7453 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7455 return ERR_PTR(-ENOMEM);
7457 refcount_set(&sqd->refs, 1);
7458 INIT_LIST_HEAD(&sqd->ctx_list);
7459 INIT_LIST_HEAD(&sqd->ctx_new_list);
7460 mutex_init(&sqd->ctx_lock);
7461 mutex_init(&sqd->lock);
7462 init_waitqueue_head(&sqd->wait);
7466 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7467 __releases(&sqd->lock)
7471 kthread_unpark(sqd->thread);
7472 mutex_unlock(&sqd->lock);
7475 static void io_sq_thread_park(struct io_sq_data *sqd)
7476 __acquires(&sqd->lock)
7480 mutex_lock(&sqd->lock);
7481 kthread_park(sqd->thread);
7484 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
7486 struct io_sq_data *sqd = ctx->sq_data;
7491 * We may arrive here from the error branch in
7492 * io_sq_offload_create() where the kthread is created
7493 * without being waked up, thus wake it up now to make
7494 * sure the wait will complete.
7496 wake_up_process(sqd->thread);
7497 wait_for_completion(&ctx->sq_thread_comp);
7499 io_sq_thread_park(sqd);
7502 mutex_lock(&sqd->ctx_lock);
7503 list_del(&ctx->sqd_list);
7504 io_sqd_update_thread_idle(sqd);
7505 mutex_unlock(&sqd->ctx_lock);
7508 io_sq_thread_unpark(sqd);
7510 io_put_sq_data(sqd);
7511 ctx->sq_data = NULL;
7515 static void io_finish_async(struct io_ring_ctx *ctx)
7517 io_sq_thread_stop(ctx);
7520 io_wq_destroy(ctx->io_wq);
7525 #if defined(CONFIG_UNIX)
7527 * Ensure the UNIX gc is aware of our file set, so we are certain that
7528 * the io_uring can be safely unregistered on process exit, even if we have
7529 * loops in the file referencing.
7531 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7533 struct sock *sk = ctx->ring_sock->sk;
7534 struct scm_fp_list *fpl;
7535 struct sk_buff *skb;
7538 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7542 skb = alloc_skb(0, GFP_KERNEL);
7551 fpl->user = get_uid(ctx->user);
7552 for (i = 0; i < nr; i++) {
7553 struct file *file = io_file_from_index(ctx, i + offset);
7557 fpl->fp[nr_files] = get_file(file);
7558 unix_inflight(fpl->user, fpl->fp[nr_files]);
7563 fpl->max = SCM_MAX_FD;
7564 fpl->count = nr_files;
7565 UNIXCB(skb).fp = fpl;
7566 skb->destructor = unix_destruct_scm;
7567 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7568 skb_queue_head(&sk->sk_receive_queue, skb);
7570 for (i = 0; i < nr_files; i++)
7581 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7582 * causes regular reference counting to break down. We rely on the UNIX
7583 * garbage collection to take care of this problem for us.
7585 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7587 unsigned left, total;
7591 left = ctx->nr_user_files;
7593 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7595 ret = __io_sqe_files_scm(ctx, this_files, total);
7599 total += this_files;
7605 while (total < ctx->nr_user_files) {
7606 struct file *file = io_file_from_index(ctx, total);
7616 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7622 static int io_sqe_alloc_file_tables(struct fixed_rsrc_data *file_data,
7623 unsigned nr_tables, unsigned nr_files)
7627 for (i = 0; i < nr_tables; i++) {
7628 struct fixed_rsrc_table *table = &file_data->table[i];
7629 unsigned this_files;
7631 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7632 table->files = kcalloc(this_files, sizeof(struct file *),
7636 nr_files -= this_files;
7642 for (i = 0; i < nr_tables; i++) {
7643 struct fixed_rsrc_table *table = &file_data->table[i];
7644 kfree(table->files);
7649 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
7651 #if defined(CONFIG_UNIX)
7652 struct sock *sock = ctx->ring_sock->sk;
7653 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7654 struct sk_buff *skb;
7657 __skb_queue_head_init(&list);
7660 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7661 * remove this entry and rearrange the file array.
7663 skb = skb_dequeue(head);
7665 struct scm_fp_list *fp;
7667 fp = UNIXCB(skb).fp;
7668 for (i = 0; i < fp->count; i++) {
7671 if (fp->fp[i] != file)
7674 unix_notinflight(fp->user, fp->fp[i]);
7675 left = fp->count - 1 - i;
7677 memmove(&fp->fp[i], &fp->fp[i + 1],
7678 left * sizeof(struct file *));
7685 __skb_queue_tail(&list, skb);
7695 __skb_queue_tail(&list, skb);
7697 skb = skb_dequeue(head);
7700 if (skb_peek(&list)) {
7701 spin_lock_irq(&head->lock);
7702 while ((skb = __skb_dequeue(&list)) != NULL)
7703 __skb_queue_tail(head, skb);
7704 spin_unlock_irq(&head->lock);
7711 static void __io_rsrc_put_work(struct fixed_rsrc_ref_node *ref_node)
7713 struct fixed_rsrc_data *rsrc_data = ref_node->rsrc_data;
7714 struct io_ring_ctx *ctx = rsrc_data->ctx;
7715 struct io_rsrc_put *prsrc, *tmp;
7717 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7718 list_del(&prsrc->list);
7719 io_ring_file_put(ctx, prsrc->file);
7723 percpu_ref_exit(&ref_node->refs);
7725 percpu_ref_put(&rsrc_data->refs);
7728 static void io_rsrc_put_work(struct work_struct *work)
7730 struct io_ring_ctx *ctx;
7731 struct llist_node *node;
7733 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7734 node = llist_del_all(&ctx->rsrc_put_llist);
7737 struct fixed_rsrc_ref_node *ref_node;
7738 struct llist_node *next = node->next;
7740 ref_node = llist_entry(node, struct fixed_rsrc_ref_node, llist);
7741 __io_rsrc_put_work(ref_node);
7746 static void io_rsrc_data_ref_zero(struct percpu_ref *ref)
7748 struct fixed_rsrc_ref_node *ref_node;
7749 struct fixed_rsrc_data *data;
7750 struct io_ring_ctx *ctx;
7751 bool first_add = false;
7754 ref_node = container_of(ref, struct fixed_rsrc_ref_node, refs);
7755 data = ref_node->rsrc_data;
7758 spin_lock_bh(&data->lock);
7759 ref_node->done = true;
7761 while (!list_empty(&data->ref_list)) {
7762 ref_node = list_first_entry(&data->ref_list,
7763 struct fixed_rsrc_ref_node, node);
7764 /* recycle ref nodes in order */
7765 if (!ref_node->done)
7767 list_del(&ref_node->node);
7768 first_add |= llist_add(&ref_node->llist, &ctx->rsrc_put_llist);
7770 spin_unlock_bh(&data->lock);
7772 if (percpu_ref_is_dying(&data->refs))
7776 mod_delayed_work(system_wq, &ctx->rsrc_put_work, 0);
7778 queue_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7781 static struct fixed_rsrc_ref_node *alloc_fixed_file_ref_node(
7782 struct io_ring_ctx *ctx)
7784 struct fixed_rsrc_ref_node *ref_node;
7786 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7790 if (percpu_ref_init(&ref_node->refs, io_rsrc_data_ref_zero,
7795 INIT_LIST_HEAD(&ref_node->node);
7796 INIT_LIST_HEAD(&ref_node->rsrc_list);
7797 ref_node->rsrc_data = ctx->file_data;
7798 ref_node->done = false;
7802 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node)
7804 percpu_ref_exit(&ref_node->refs);
7808 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7811 __s32 __user *fds = (__s32 __user *) arg;
7812 unsigned nr_tables, i;
7814 int fd, ret = -ENOMEM;
7815 struct fixed_rsrc_ref_node *ref_node;
7816 struct fixed_rsrc_data *file_data;
7822 if (nr_args > IORING_MAX_FIXED_FILES)
7825 file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
7828 file_data->ctx = ctx;
7829 init_completion(&file_data->done);
7830 INIT_LIST_HEAD(&file_data->ref_list);
7831 spin_lock_init(&file_data->lock);
7833 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
7834 file_data->table = kcalloc(nr_tables, sizeof(*file_data->table),
7836 if (!file_data->table)
7839 if (percpu_ref_init(&file_data->refs, io_rsrc_ref_kill,
7840 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
7843 if (io_sqe_alloc_file_tables(file_data, nr_tables, nr_args))
7845 ctx->file_data = file_data;
7847 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7848 struct fixed_rsrc_table *table;
7851 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7855 /* allow sparse sets */
7865 * Don't allow io_uring instances to be registered. If UNIX
7866 * isn't enabled, then this causes a reference cycle and this
7867 * instance can never get freed. If UNIX is enabled we'll
7868 * handle it just fine, but there's still no point in allowing
7869 * a ring fd as it doesn't support regular read/write anyway.
7871 if (file->f_op == &io_uring_fops) {
7875 table = &file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7876 index = i & IORING_FILE_TABLE_MASK;
7877 table->files[index] = file;
7880 ret = io_sqe_files_scm(ctx);
7882 io_sqe_files_unregister(ctx);
7886 ref_node = alloc_fixed_file_ref_node(ctx);
7888 io_sqe_files_unregister(ctx);
7892 io_sqe_rsrc_set_node(file_data, ref_node);
7895 for (i = 0; i < ctx->nr_user_files; i++) {
7896 file = io_file_from_index(ctx, i);
7900 for (i = 0; i < nr_tables; i++)
7901 kfree(file_data->table[i].files);
7902 ctx->nr_user_files = 0;
7904 percpu_ref_exit(&file_data->refs);
7906 kfree(file_data->table);
7908 ctx->file_data = NULL;
7912 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7915 #if defined(CONFIG_UNIX)
7916 struct sock *sock = ctx->ring_sock->sk;
7917 struct sk_buff_head *head = &sock->sk_receive_queue;
7918 struct sk_buff *skb;
7921 * See if we can merge this file into an existing skb SCM_RIGHTS
7922 * file set. If there's no room, fall back to allocating a new skb
7923 * and filling it in.
7925 spin_lock_irq(&head->lock);
7926 skb = skb_peek(head);
7928 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7930 if (fpl->count < SCM_MAX_FD) {
7931 __skb_unlink(skb, head);
7932 spin_unlock_irq(&head->lock);
7933 fpl->fp[fpl->count] = get_file(file);
7934 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7936 spin_lock_irq(&head->lock);
7937 __skb_queue_head(head, skb);
7942 spin_unlock_irq(&head->lock);
7949 return __io_sqe_files_scm(ctx, 1, index);
7955 static int io_queue_rsrc_removal(struct fixed_rsrc_data *data,
7958 struct io_rsrc_put *prsrc;
7959 struct fixed_rsrc_ref_node *ref_node = data->node;
7961 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7966 list_add(&prsrc->list, &ref_node->rsrc_list);
7971 static inline int io_queue_file_removal(struct fixed_rsrc_data *data,
7974 return io_queue_rsrc_removal(data, file);
7977 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7978 struct io_uring_rsrc_update *up,
7981 struct fixed_rsrc_data *data = ctx->file_data;
7982 struct fixed_rsrc_ref_node *ref_node;
7987 bool needs_switch = false;
7989 if (check_add_overflow(up->offset, nr_args, &done))
7991 if (done > ctx->nr_user_files)
7994 ref_node = alloc_fixed_file_ref_node(ctx);
7999 fds = u64_to_user_ptr(up->data);
8001 struct fixed_rsrc_table *table;
8005 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
8009 i = array_index_nospec(up->offset, ctx->nr_user_files);
8010 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
8011 index = i & IORING_FILE_TABLE_MASK;
8012 if (table->files[index]) {
8013 file = table->files[index];
8014 err = io_queue_file_removal(data, file);
8017 table->files[index] = NULL;
8018 needs_switch = true;
8027 * Don't allow io_uring instances to be registered. If
8028 * UNIX isn't enabled, then this causes a reference
8029 * cycle and this instance can never get freed. If UNIX
8030 * is enabled we'll handle it just fine, but there's
8031 * still no point in allowing a ring fd as it doesn't
8032 * support regular read/write anyway.
8034 if (file->f_op == &io_uring_fops) {
8039 table->files[index] = file;
8040 err = io_sqe_file_register(ctx, file, i);
8042 table->files[index] = NULL;
8053 percpu_ref_kill(&data->node->refs);
8054 io_sqe_rsrc_set_node(data, ref_node);
8056 destroy_fixed_rsrc_ref_node(ref_node);
8058 return done ? done : err;
8061 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
8064 struct io_uring_rsrc_update up;
8066 if (!ctx->file_data)
8070 if (copy_from_user(&up, arg, sizeof(up)))
8075 return __io_sqe_files_update(ctx, &up, nr_args);
8078 static void io_free_work(struct io_wq_work *work)
8080 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8082 /* Consider that io_steal_work() relies on this ref */
8086 static int io_init_wq_offload(struct io_ring_ctx *ctx,
8087 struct io_uring_params *p)
8089 struct io_wq_data data;
8091 struct io_ring_ctx *ctx_attach;
8092 unsigned int concurrency;
8095 data.user = ctx->user;
8096 data.free_work = io_free_work;
8097 data.do_work = io_wq_submit_work;
8099 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
8100 /* Do QD, or 4 * CPUS, whatever is smallest */
8101 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8103 ctx->io_wq = io_wq_create(concurrency, &data);
8104 if (IS_ERR(ctx->io_wq)) {
8105 ret = PTR_ERR(ctx->io_wq);
8111 f = fdget(p->wq_fd);
8115 if (f.file->f_op != &io_uring_fops) {
8120 ctx_attach = f.file->private_data;
8121 /* @io_wq is protected by holding the fd */
8122 if (!io_wq_get(ctx_attach->io_wq, &data)) {
8127 ctx->io_wq = ctx_attach->io_wq;
8133 static int io_uring_alloc_task_context(struct task_struct *task)
8135 struct io_uring_task *tctx;
8138 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
8139 if (unlikely(!tctx))
8142 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8143 if (unlikely(ret)) {
8149 init_waitqueue_head(&tctx->wait);
8151 atomic_set(&tctx->in_idle, 0);
8152 tctx->sqpoll = false;
8153 io_init_identity(&tctx->__identity);
8154 tctx->identity = &tctx->__identity;
8155 task->io_uring = tctx;
8159 void __io_uring_free(struct task_struct *tsk)
8161 struct io_uring_task *tctx = tsk->io_uring;
8163 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8164 WARN_ON_ONCE(refcount_read(&tctx->identity->count) != 1);
8165 if (tctx->identity != &tctx->__identity)
8166 kfree(tctx->identity);
8167 percpu_counter_destroy(&tctx->inflight);
8169 tsk->io_uring = NULL;
8172 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8173 struct io_uring_params *p)
8177 if (ctx->flags & IORING_SETUP_SQPOLL) {
8178 struct io_sq_data *sqd;
8181 if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_NICE))
8184 sqd = io_get_sq_data(p);
8191 io_sq_thread_park(sqd);
8192 mutex_lock(&sqd->ctx_lock);
8193 list_add(&ctx->sqd_list, &sqd->ctx_new_list);
8194 mutex_unlock(&sqd->ctx_lock);
8195 io_sq_thread_unpark(sqd);
8197 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8198 if (!ctx->sq_thread_idle)
8199 ctx->sq_thread_idle = HZ;
8204 if (p->flags & IORING_SETUP_SQ_AFF) {
8205 int cpu = p->sq_thread_cpu;
8208 if (cpu >= nr_cpu_ids)
8210 if (!cpu_online(cpu))
8213 sqd->thread = kthread_create_on_cpu(io_sq_thread, sqd,
8214 cpu, "io_uring-sq");
8216 sqd->thread = kthread_create(io_sq_thread, sqd,
8219 if (IS_ERR(sqd->thread)) {
8220 ret = PTR_ERR(sqd->thread);
8224 ret = io_uring_alloc_task_context(sqd->thread);
8227 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8228 /* Can't have SQ_AFF without SQPOLL */
8234 ret = io_init_wq_offload(ctx, p);
8240 io_finish_async(ctx);
8244 static void io_sq_offload_start(struct io_ring_ctx *ctx)
8246 struct io_sq_data *sqd = ctx->sq_data;
8248 if ((ctx->flags & IORING_SETUP_SQPOLL) && sqd->thread)
8249 wake_up_process(sqd->thread);
8252 static inline void __io_unaccount_mem(struct user_struct *user,
8253 unsigned long nr_pages)
8255 atomic_long_sub(nr_pages, &user->locked_vm);
8258 static inline int __io_account_mem(struct user_struct *user,
8259 unsigned long nr_pages)
8261 unsigned long page_limit, cur_pages, new_pages;
8263 /* Don't allow more pages than we can safely lock */
8264 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8267 cur_pages = atomic_long_read(&user->locked_vm);
8268 new_pages = cur_pages + nr_pages;
8269 if (new_pages > page_limit)
8271 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8272 new_pages) != cur_pages);
8277 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
8278 enum io_mem_account acct)
8281 __io_unaccount_mem(ctx->user, nr_pages);
8283 if (ctx->mm_account) {
8284 if (acct == ACCT_LOCKED) {
8285 mmap_write_lock(ctx->mm_account);
8286 ctx->mm_account->locked_vm -= nr_pages;
8287 mmap_write_unlock(ctx->mm_account);
8288 }else if (acct == ACCT_PINNED) {
8289 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8294 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
8295 enum io_mem_account acct)
8299 if (ctx->limit_mem) {
8300 ret = __io_account_mem(ctx->user, nr_pages);
8305 if (ctx->mm_account) {
8306 if (acct == ACCT_LOCKED) {
8307 mmap_write_lock(ctx->mm_account);
8308 ctx->mm_account->locked_vm += nr_pages;
8309 mmap_write_unlock(ctx->mm_account);
8310 } else if (acct == ACCT_PINNED) {
8311 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8318 static void io_mem_free(void *ptr)
8325 page = virt_to_head_page(ptr);
8326 if (put_page_testzero(page))
8327 free_compound_page(page);
8330 static void *io_mem_alloc(size_t size)
8332 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8335 return (void *) __get_free_pages(gfp_flags, get_order(size));
8338 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8341 struct io_rings *rings;
8342 size_t off, sq_array_size;
8344 off = struct_size(rings, cqes, cq_entries);
8345 if (off == SIZE_MAX)
8349 off = ALIGN(off, SMP_CACHE_BYTES);
8357 sq_array_size = array_size(sizeof(u32), sq_entries);
8358 if (sq_array_size == SIZE_MAX)
8361 if (check_add_overflow(off, sq_array_size, &off))
8367 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
8371 pages = (size_t)1 << get_order(
8372 rings_size(sq_entries, cq_entries, NULL));
8373 pages += (size_t)1 << get_order(
8374 array_size(sizeof(struct io_uring_sqe), sq_entries));
8379 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8383 if (!ctx->user_bufs)
8386 for (i = 0; i < ctx->nr_user_bufs; i++) {
8387 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8389 for (j = 0; j < imu->nr_bvecs; j++)
8390 unpin_user_page(imu->bvec[j].bv_page);
8392 if (imu->acct_pages)
8393 io_unaccount_mem(ctx, imu->acct_pages, ACCT_PINNED);
8398 kfree(ctx->user_bufs);
8399 ctx->user_bufs = NULL;
8400 ctx->nr_user_bufs = 0;
8404 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8405 void __user *arg, unsigned index)
8407 struct iovec __user *src;
8409 #ifdef CONFIG_COMPAT
8411 struct compat_iovec __user *ciovs;
8412 struct compat_iovec ciov;
8414 ciovs = (struct compat_iovec __user *) arg;
8415 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8418 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8419 dst->iov_len = ciov.iov_len;
8423 src = (struct iovec __user *) arg;
8424 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8430 * Not super efficient, but this is just a registration time. And we do cache
8431 * the last compound head, so generally we'll only do a full search if we don't
8434 * We check if the given compound head page has already been accounted, to
8435 * avoid double accounting it. This allows us to account the full size of the
8436 * page, not just the constituent pages of a huge page.
8438 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8439 int nr_pages, struct page *hpage)
8443 /* check current page array */
8444 for (i = 0; i < nr_pages; i++) {
8445 if (!PageCompound(pages[i]))
8447 if (compound_head(pages[i]) == hpage)
8451 /* check previously registered pages */
8452 for (i = 0; i < ctx->nr_user_bufs; i++) {
8453 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8455 for (j = 0; j < imu->nr_bvecs; j++) {
8456 if (!PageCompound(imu->bvec[j].bv_page))
8458 if (compound_head(imu->bvec[j].bv_page) == hpage)
8466 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8467 int nr_pages, struct io_mapped_ubuf *imu,
8468 struct page **last_hpage)
8472 for (i = 0; i < nr_pages; i++) {
8473 if (!PageCompound(pages[i])) {
8478 hpage = compound_head(pages[i]);
8479 if (hpage == *last_hpage)
8481 *last_hpage = hpage;
8482 if (headpage_already_acct(ctx, pages, i, hpage))
8484 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8488 if (!imu->acct_pages)
8491 ret = io_account_mem(ctx, imu->acct_pages, ACCT_PINNED);
8493 imu->acct_pages = 0;
8497 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8498 struct io_mapped_ubuf *imu,
8499 struct page **last_hpage)
8501 struct vm_area_struct **vmas = NULL;
8502 struct page **pages = NULL;
8503 unsigned long off, start, end, ubuf;
8505 int ret, pret, nr_pages, i;
8507 ubuf = (unsigned long) iov->iov_base;
8508 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8509 start = ubuf >> PAGE_SHIFT;
8510 nr_pages = end - start;
8514 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8518 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8523 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
8529 mmap_read_lock(current->mm);
8530 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8532 if (pret == nr_pages) {
8533 /* don't support file backed memory */
8534 for (i = 0; i < nr_pages; i++) {
8535 struct vm_area_struct *vma = vmas[i];
8538 !is_file_hugepages(vma->vm_file)) {
8544 ret = pret < 0 ? pret : -EFAULT;
8546 mmap_read_unlock(current->mm);
8549 * if we did partial map, or found file backed vmas,
8550 * release any pages we did get
8553 unpin_user_pages(pages, pret);
8558 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8560 unpin_user_pages(pages, pret);
8565 off = ubuf & ~PAGE_MASK;
8566 size = iov->iov_len;
8567 for (i = 0; i < nr_pages; i++) {
8570 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8571 imu->bvec[i].bv_page = pages[i];
8572 imu->bvec[i].bv_len = vec_len;
8573 imu->bvec[i].bv_offset = off;
8577 /* store original address for later verification */
8579 imu->len = iov->iov_len;
8580 imu->nr_bvecs = nr_pages;
8588 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8592 if (!nr_args || nr_args > UIO_MAXIOV)
8595 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
8597 if (!ctx->user_bufs)
8603 static int io_buffer_validate(struct iovec *iov)
8606 * Don't impose further limits on the size and buffer
8607 * constraints here, we'll -EINVAL later when IO is
8608 * submitted if they are wrong.
8610 if (!iov->iov_base || !iov->iov_len)
8613 /* arbitrary limit, but we need something */
8614 if (iov->iov_len > SZ_1G)
8620 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8621 unsigned int nr_args)
8625 struct page *last_hpage = NULL;
8627 ret = io_buffers_map_alloc(ctx, nr_args);
8631 for (i = 0; i < nr_args; i++) {
8632 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8634 ret = io_copy_iov(ctx, &iov, arg, i);
8638 ret = io_buffer_validate(&iov);
8642 ret = io_sqe_buffer_register(ctx, &iov, imu, &last_hpage);
8646 ctx->nr_user_bufs++;
8650 io_sqe_buffers_unregister(ctx);
8655 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8657 __s32 __user *fds = arg;
8663 if (copy_from_user(&fd, fds, sizeof(*fds)))
8666 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8667 if (IS_ERR(ctx->cq_ev_fd)) {
8668 int ret = PTR_ERR(ctx->cq_ev_fd);
8669 ctx->cq_ev_fd = NULL;
8676 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8678 if (ctx->cq_ev_fd) {
8679 eventfd_ctx_put(ctx->cq_ev_fd);
8680 ctx->cq_ev_fd = NULL;
8687 static int __io_destroy_buffers(int id, void *p, void *data)
8689 struct io_ring_ctx *ctx = data;
8690 struct io_buffer *buf = p;
8692 __io_remove_buffers(ctx, buf, id, -1U);
8696 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8698 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
8699 idr_destroy(&ctx->io_buffer_idr);
8702 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8704 io_finish_async(ctx);
8705 io_sqe_buffers_unregister(ctx);
8707 if (ctx->sqo_task) {
8708 put_task_struct(ctx->sqo_task);
8709 ctx->sqo_task = NULL;
8710 mmdrop(ctx->mm_account);
8711 ctx->mm_account = NULL;
8714 #ifdef CONFIG_BLK_CGROUP
8715 if (ctx->sqo_blkcg_css)
8716 css_put(ctx->sqo_blkcg_css);
8719 io_sqe_files_unregister(ctx);
8720 io_eventfd_unregister(ctx);
8721 io_destroy_buffers(ctx);
8722 idr_destroy(&ctx->personality_idr);
8724 #if defined(CONFIG_UNIX)
8725 if (ctx->ring_sock) {
8726 ctx->ring_sock->file = NULL; /* so that iput() is called */
8727 sock_release(ctx->ring_sock);
8731 io_mem_free(ctx->rings);
8732 io_mem_free(ctx->sq_sqes);
8734 percpu_ref_exit(&ctx->refs);
8735 free_uid(ctx->user);
8736 put_cred(ctx->creds);
8737 kfree(ctx->cancel_hash);
8738 kmem_cache_free(req_cachep, ctx->fallback_req);
8742 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8744 struct io_ring_ctx *ctx = file->private_data;
8747 poll_wait(file, &ctx->cq_wait, wait);
8749 * synchronizes with barrier from wq_has_sleeper call in
8753 if (!io_sqring_full(ctx))
8754 mask |= EPOLLOUT | EPOLLWRNORM;
8755 io_cqring_overflow_flush(ctx, false, NULL, NULL);
8756 if (io_cqring_events(ctx))
8757 mask |= EPOLLIN | EPOLLRDNORM;
8762 static int io_uring_fasync(int fd, struct file *file, int on)
8764 struct io_ring_ctx *ctx = file->private_data;
8766 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8769 static int io_remove_personalities(int id, void *p, void *data)
8771 struct io_ring_ctx *ctx = data;
8772 struct io_identity *iod;
8774 iod = idr_remove(&ctx->personality_idr, id);
8776 put_cred(iod->creds);
8777 if (refcount_dec_and_test(&iod->count))
8783 static void io_ring_exit_work(struct work_struct *work)
8785 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
8789 * If we're doing polled IO and end up having requests being
8790 * submitted async (out-of-line), then completions can come in while
8791 * we're waiting for refs to drop. We need to reap these manually,
8792 * as nobody else will be looking for them.
8795 __io_uring_cancel_task_requests(ctx, NULL);
8796 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8797 io_ring_ctx_free(ctx);
8800 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8802 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8804 return req->ctx == data;
8807 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8809 mutex_lock(&ctx->uring_lock);
8810 percpu_ref_kill(&ctx->refs);
8812 if (WARN_ON_ONCE((ctx->flags & IORING_SETUP_SQPOLL) && !ctx->sqo_dead))
8815 /* if force is set, the ring is going away. always drop after that */
8816 ctx->cq_overflow_flushed = 1;
8818 __io_cqring_overflow_flush(ctx, true, NULL, NULL);
8819 mutex_unlock(&ctx->uring_lock);
8821 io_kill_timeouts(ctx, NULL, NULL);
8822 io_poll_remove_all(ctx, NULL, NULL);
8825 io_wq_cancel_cb(ctx->io_wq, io_cancel_ctx_cb, ctx, true);
8827 /* if we failed setting up the ctx, we might not have any rings */
8828 io_iopoll_try_reap_events(ctx);
8829 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
8832 * Do this upfront, so we won't have a grace period where the ring
8833 * is closed but resources aren't reaped yet. This can cause
8834 * spurious failure in setting up a new ring.
8836 io_unaccount_mem(ctx, ring_pages(ctx->sq_entries, ctx->cq_entries),
8839 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8841 * Use system_unbound_wq to avoid spawning tons of event kworkers
8842 * if we're exiting a ton of rings at the same time. It just adds
8843 * noise and overhead, there's no discernable change in runtime
8844 * over using system_wq.
8846 queue_work(system_unbound_wq, &ctx->exit_work);
8849 static int io_uring_release(struct inode *inode, struct file *file)
8851 struct io_ring_ctx *ctx = file->private_data;
8853 file->private_data = NULL;
8854 io_ring_ctx_wait_and_kill(ctx);
8858 struct io_task_cancel {
8859 struct task_struct *task;
8860 struct files_struct *files;
8863 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8865 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8866 struct io_task_cancel *cancel = data;
8869 if (cancel->files && (req->flags & REQ_F_LINK_TIMEOUT)) {
8870 unsigned long flags;
8871 struct io_ring_ctx *ctx = req->ctx;
8873 /* protect against races with linked timeouts */
8874 spin_lock_irqsave(&ctx->completion_lock, flags);
8875 ret = io_match_task(req, cancel->task, cancel->files);
8876 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8878 ret = io_match_task(req, cancel->task, cancel->files);
8883 static void io_cancel_defer_files(struct io_ring_ctx *ctx,
8884 struct task_struct *task,
8885 struct files_struct *files)
8887 struct io_defer_entry *de = NULL;
8890 spin_lock_irq(&ctx->completion_lock);
8891 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8892 if (io_match_task(de->req, task, files)) {
8893 list_cut_position(&list, &ctx->defer_list, &de->list);
8897 spin_unlock_irq(&ctx->completion_lock);
8899 while (!list_empty(&list)) {
8900 de = list_first_entry(&list, struct io_defer_entry, list);
8901 list_del_init(&de->list);
8902 req_set_fail_links(de->req);
8903 io_put_req(de->req);
8904 io_req_complete(de->req, -ECANCELED);
8909 static int io_uring_count_inflight(struct io_ring_ctx *ctx,
8910 struct task_struct *task,
8911 struct files_struct *files)
8913 struct io_kiocb *req;
8916 spin_lock_irq(&ctx->inflight_lock);
8917 list_for_each_entry(req, &ctx->inflight_list, inflight_entry)
8918 cnt += io_match_task(req, task, files);
8919 spin_unlock_irq(&ctx->inflight_lock);
8923 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
8924 struct task_struct *task,
8925 struct files_struct *files)
8927 while (!list_empty_careful(&ctx->inflight_list)) {
8928 struct io_task_cancel cancel = { .task = task, .files = files };
8932 inflight = io_uring_count_inflight(ctx, task, files);
8936 io_wq_cancel_cb(ctx->io_wq, io_cancel_task_cb, &cancel, true);
8937 io_poll_remove_all(ctx, task, files);
8938 io_kill_timeouts(ctx, task, files);
8939 io_cqring_overflow_flush(ctx, true, task, files);
8940 /* cancellations _may_ trigger task work */
8943 prepare_to_wait(&task->io_uring->wait, &wait,
8944 TASK_UNINTERRUPTIBLE);
8945 if (inflight == io_uring_count_inflight(ctx, task, files))
8947 finish_wait(&task->io_uring->wait, &wait);
8951 static void __io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
8952 struct task_struct *task)
8955 struct io_task_cancel cancel = { .task = task, .files = NULL, };
8956 enum io_wq_cancel cret;
8960 cret = io_wq_cancel_cb(ctx->io_wq, io_cancel_task_cb,
8962 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8965 /* SQPOLL thread does its own polling */
8966 if (!(ctx->flags & IORING_SETUP_SQPOLL)) {
8967 while (!list_empty_careful(&ctx->iopoll_list)) {
8968 io_iopoll_try_reap_events(ctx);
8973 ret |= io_poll_remove_all(ctx, task, NULL);
8974 ret |= io_kill_timeouts(ctx, task, NULL);
8975 ret |= io_run_task_work();
8982 static void io_disable_sqo_submit(struct io_ring_ctx *ctx)
8984 mutex_lock(&ctx->uring_lock);
8986 mutex_unlock(&ctx->uring_lock);
8988 /* make sure callers enter the ring to get error */
8990 io_ring_set_wakeup_flag(ctx);
8994 * We need to iteratively cancel requests, in case a request has dependent
8995 * hard links. These persist even for failure of cancelations, hence keep
8996 * looping until none are found.
8998 static void io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
8999 struct files_struct *files)
9001 struct task_struct *task = current;
9003 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
9004 io_disable_sqo_submit(ctx);
9005 task = ctx->sq_data->thread;
9006 atomic_inc(&task->io_uring->in_idle);
9007 io_sq_thread_park(ctx->sq_data);
9010 io_cancel_defer_files(ctx, task, files);
9011 io_cqring_overflow_flush(ctx, true, task, files);
9013 io_uring_cancel_files(ctx, task, files);
9015 __io_uring_cancel_task_requests(ctx, task);
9017 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
9018 atomic_dec(&task->io_uring->in_idle);
9020 * If the files that are going away are the ones in the thread
9021 * identity, clear them out.
9023 if (task->io_uring->identity->files == files)
9024 task->io_uring->identity->files = NULL;
9025 io_sq_thread_unpark(ctx->sq_data);
9030 * Note that this task has used io_uring. We use it for cancelation purposes.
9032 static int io_uring_add_task_file(struct io_ring_ctx *ctx, struct file *file)
9034 struct io_uring_task *tctx = current->io_uring;
9037 if (unlikely(!tctx)) {
9038 ret = io_uring_alloc_task_context(current);
9041 tctx = current->io_uring;
9043 if (tctx->last != file) {
9044 void *old = xa_load(&tctx->xa, (unsigned long)file);
9048 ret = xa_err(xa_store(&tctx->xa, (unsigned long)file,
9059 * This is race safe in that the task itself is doing this, hence it
9060 * cannot be going through the exit/cancel paths at the same time.
9061 * This cannot be modified while exit/cancel is running.
9063 if (!tctx->sqpoll && (ctx->flags & IORING_SETUP_SQPOLL))
9064 tctx->sqpoll = true;
9070 * Remove this io_uring_file -> task mapping.
9072 static void io_uring_del_task_file(struct file *file)
9074 struct io_uring_task *tctx = current->io_uring;
9076 if (tctx->last == file)
9078 file = xa_erase(&tctx->xa, (unsigned long)file);
9083 static void io_uring_remove_task_files(struct io_uring_task *tctx)
9086 unsigned long index;
9088 xa_for_each(&tctx->xa, index, file)
9089 io_uring_del_task_file(file);
9092 void __io_uring_files_cancel(struct files_struct *files)
9094 struct io_uring_task *tctx = current->io_uring;
9096 unsigned long index;
9098 /* make sure overflow events are dropped */
9099 atomic_inc(&tctx->in_idle);
9100 xa_for_each(&tctx->xa, index, file)
9101 io_uring_cancel_task_requests(file->private_data, files);
9102 atomic_dec(&tctx->in_idle);
9105 io_uring_remove_task_files(tctx);
9108 static s64 tctx_inflight(struct io_uring_task *tctx)
9110 unsigned long index;
9114 inflight = percpu_counter_sum(&tctx->inflight);
9119 * If we have SQPOLL rings, then we need to iterate and find them, and
9120 * add the pending count for those.
9122 xa_for_each(&tctx->xa, index, file) {
9123 struct io_ring_ctx *ctx = file->private_data;
9125 if (ctx->flags & IORING_SETUP_SQPOLL) {
9126 struct io_uring_task *__tctx = ctx->sqo_task->io_uring;
9128 inflight += percpu_counter_sum(&__tctx->inflight);
9136 * Find any io_uring fd that this task has registered or done IO on, and cancel
9139 void __io_uring_task_cancel(void)
9141 struct io_uring_task *tctx = current->io_uring;
9145 /* make sure overflow events are dropped */
9146 atomic_inc(&tctx->in_idle);
9148 /* trigger io_disable_sqo_submit() */
9150 __io_uring_files_cancel(NULL);
9153 /* read completions before cancelations */
9154 inflight = tctx_inflight(tctx);
9157 __io_uring_files_cancel(NULL);
9159 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9162 * If we've seen completions, retry without waiting. This
9163 * avoids a race where a completion comes in before we did
9164 * prepare_to_wait().
9166 if (inflight == tctx_inflight(tctx))
9168 finish_wait(&tctx->wait, &wait);
9171 atomic_dec(&tctx->in_idle);
9173 io_uring_remove_task_files(tctx);
9176 static int io_uring_flush(struct file *file, void *data)
9178 struct io_uring_task *tctx = current->io_uring;
9179 struct io_ring_ctx *ctx = file->private_data;
9181 if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
9182 io_uring_cancel_task_requests(ctx, NULL);
9187 /* we should have cancelled and erased it before PF_EXITING */
9188 WARN_ON_ONCE((current->flags & PF_EXITING) &&
9189 xa_load(&tctx->xa, (unsigned long)file));
9192 * fput() is pending, will be 2 if the only other ref is our potential
9193 * task file note. If the task is exiting, drop regardless of count.
9195 if (atomic_long_read(&file->f_count) != 2)
9198 if (ctx->flags & IORING_SETUP_SQPOLL) {
9199 /* there is only one file note, which is owned by sqo_task */
9200 WARN_ON_ONCE(ctx->sqo_task != current &&
9201 xa_load(&tctx->xa, (unsigned long)file));
9202 /* sqo_dead check is for when this happens after cancellation */
9203 WARN_ON_ONCE(ctx->sqo_task == current && !ctx->sqo_dead &&
9204 !xa_load(&tctx->xa, (unsigned long)file));
9206 io_disable_sqo_submit(ctx);
9209 if (!(ctx->flags & IORING_SETUP_SQPOLL) || ctx->sqo_task == current)
9210 io_uring_del_task_file(file);
9214 static void *io_uring_validate_mmap_request(struct file *file,
9215 loff_t pgoff, size_t sz)
9217 struct io_ring_ctx *ctx = file->private_data;
9218 loff_t offset = pgoff << PAGE_SHIFT;
9223 case IORING_OFF_SQ_RING:
9224 case IORING_OFF_CQ_RING:
9227 case IORING_OFF_SQES:
9231 return ERR_PTR(-EINVAL);
9234 page = virt_to_head_page(ptr);
9235 if (sz > page_size(page))
9236 return ERR_PTR(-EINVAL);
9243 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9245 size_t sz = vma->vm_end - vma->vm_start;
9249 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9251 return PTR_ERR(ptr);
9253 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9254 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9257 #else /* !CONFIG_MMU */
9259 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9261 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9264 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9266 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9269 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9270 unsigned long addr, unsigned long len,
9271 unsigned long pgoff, unsigned long flags)
9275 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9277 return PTR_ERR(ptr);
9279 return (unsigned long) ptr;
9282 #endif /* !CONFIG_MMU */
9284 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9290 if (!io_sqring_full(ctx))
9293 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9295 if (unlikely(ctx->sqo_dead)) {
9300 if (!io_sqring_full(ctx))
9304 } while (!signal_pending(current));
9306 finish_wait(&ctx->sqo_sq_wait, &wait);
9311 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9312 struct __kernel_timespec __user **ts,
9313 const sigset_t __user **sig)
9315 struct io_uring_getevents_arg arg;
9318 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9319 * is just a pointer to the sigset_t.
9321 if (!(flags & IORING_ENTER_EXT_ARG)) {
9322 *sig = (const sigset_t __user *) argp;
9328 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9329 * timespec and sigset_t pointers if good.
9331 if (*argsz != sizeof(arg))
9333 if (copy_from_user(&arg, argp, sizeof(arg)))
9335 *sig = u64_to_user_ptr(arg.sigmask);
9336 *argsz = arg.sigmask_sz;
9337 *ts = u64_to_user_ptr(arg.ts);
9341 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9342 u32, min_complete, u32, flags, const void __user *, argp,
9345 struct io_ring_ctx *ctx;
9352 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9353 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG))
9361 if (f.file->f_op != &io_uring_fops)
9365 ctx = f.file->private_data;
9366 if (!percpu_ref_tryget(&ctx->refs))
9370 if (ctx->flags & IORING_SETUP_R_DISABLED)
9374 * For SQ polling, the thread will do all submissions and completions.
9375 * Just return the requested submit count, and wake the thread if
9379 if (ctx->flags & IORING_SETUP_SQPOLL) {
9380 io_cqring_overflow_flush(ctx, false, NULL, NULL);
9383 if (unlikely(ctx->sqo_dead))
9385 if (flags & IORING_ENTER_SQ_WAKEUP)
9386 wake_up(&ctx->sq_data->wait);
9387 if (flags & IORING_ENTER_SQ_WAIT) {
9388 ret = io_sqpoll_wait_sq(ctx);
9392 submitted = to_submit;
9393 } else if (to_submit) {
9394 ret = io_uring_add_task_file(ctx, f.file);
9397 mutex_lock(&ctx->uring_lock);
9398 submitted = io_submit_sqes(ctx, to_submit);
9399 mutex_unlock(&ctx->uring_lock);
9401 if (submitted != to_submit)
9404 if (flags & IORING_ENTER_GETEVENTS) {
9405 const sigset_t __user *sig;
9406 struct __kernel_timespec __user *ts;
9408 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9412 min_complete = min(min_complete, ctx->cq_entries);
9415 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9416 * space applications don't need to do io completion events
9417 * polling again, they can rely on io_sq_thread to do polling
9418 * work, which can reduce cpu usage and uring_lock contention.
9420 if (ctx->flags & IORING_SETUP_IOPOLL &&
9421 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9422 ret = io_iopoll_check(ctx, min_complete);
9424 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9429 percpu_ref_put(&ctx->refs);
9432 return submitted ? submitted : ret;
9435 #ifdef CONFIG_PROC_FS
9436 static int io_uring_show_cred(int id, void *p, void *data)
9438 struct io_identity *iod = p;
9439 const struct cred *cred = iod->creds;
9440 struct seq_file *m = data;
9441 struct user_namespace *uns = seq_user_ns(m);
9442 struct group_info *gi;
9447 seq_printf(m, "%5d\n", id);
9448 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9449 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9450 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9451 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9452 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9453 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9454 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9455 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9456 seq_puts(m, "\n\tGroups:\t");
9457 gi = cred->group_info;
9458 for (g = 0; g < gi->ngroups; g++) {
9459 seq_put_decimal_ull(m, g ? " " : "",
9460 from_kgid_munged(uns, gi->gid[g]));
9462 seq_puts(m, "\n\tCapEff:\t");
9463 cap = cred->cap_effective;
9464 CAP_FOR_EACH_U32(__capi)
9465 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9470 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9472 struct io_sq_data *sq = NULL;
9477 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9478 * since fdinfo case grabs it in the opposite direction of normal use
9479 * cases. If we fail to get the lock, we just don't iterate any
9480 * structures that could be going away outside the io_uring mutex.
9482 has_lock = mutex_trylock(&ctx->uring_lock);
9484 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL))
9487 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9488 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9489 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9490 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9491 struct fixed_rsrc_table *table;
9494 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
9495 f = table->files[i & IORING_FILE_TABLE_MASK];
9497 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9499 seq_printf(m, "%5u: <none>\n", i);
9501 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9502 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9503 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
9505 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
9506 (unsigned int) buf->len);
9508 if (has_lock && !idr_is_empty(&ctx->personality_idr)) {
9509 seq_printf(m, "Personalities:\n");
9510 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
9512 seq_printf(m, "PollList:\n");
9513 spin_lock_irq(&ctx->completion_lock);
9514 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9515 struct hlist_head *list = &ctx->cancel_hash[i];
9516 struct io_kiocb *req;
9518 hlist_for_each_entry(req, list, hash_node)
9519 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9520 req->task->task_works != NULL);
9522 spin_unlock_irq(&ctx->completion_lock);
9524 mutex_unlock(&ctx->uring_lock);
9527 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9529 struct io_ring_ctx *ctx = f->private_data;
9531 if (percpu_ref_tryget(&ctx->refs)) {
9532 __io_uring_show_fdinfo(ctx, m);
9533 percpu_ref_put(&ctx->refs);
9538 static const struct file_operations io_uring_fops = {
9539 .release = io_uring_release,
9540 .flush = io_uring_flush,
9541 .mmap = io_uring_mmap,
9543 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9544 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9546 .poll = io_uring_poll,
9547 .fasync = io_uring_fasync,
9548 #ifdef CONFIG_PROC_FS
9549 .show_fdinfo = io_uring_show_fdinfo,
9553 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9554 struct io_uring_params *p)
9556 struct io_rings *rings;
9557 size_t size, sq_array_offset;
9559 /* make sure these are sane, as we already accounted them */
9560 ctx->sq_entries = p->sq_entries;
9561 ctx->cq_entries = p->cq_entries;
9563 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9564 if (size == SIZE_MAX)
9567 rings = io_mem_alloc(size);
9572 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9573 rings->sq_ring_mask = p->sq_entries - 1;
9574 rings->cq_ring_mask = p->cq_entries - 1;
9575 rings->sq_ring_entries = p->sq_entries;
9576 rings->cq_ring_entries = p->cq_entries;
9577 ctx->sq_mask = rings->sq_ring_mask;
9578 ctx->cq_mask = rings->cq_ring_mask;
9580 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9581 if (size == SIZE_MAX) {
9582 io_mem_free(ctx->rings);
9587 ctx->sq_sqes = io_mem_alloc(size);
9588 if (!ctx->sq_sqes) {
9589 io_mem_free(ctx->rings);
9597 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9601 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9605 ret = io_uring_add_task_file(ctx, file);
9610 fd_install(fd, file);
9615 * Allocate an anonymous fd, this is what constitutes the application
9616 * visible backing of an io_uring instance. The application mmaps this
9617 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9618 * we have to tie this fd to a socket for file garbage collection purposes.
9620 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9623 #if defined(CONFIG_UNIX)
9626 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9629 return ERR_PTR(ret);
9632 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9633 O_RDWR | O_CLOEXEC);
9634 #if defined(CONFIG_UNIX)
9636 sock_release(ctx->ring_sock);
9637 ctx->ring_sock = NULL;
9639 ctx->ring_sock->file = file;
9645 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9646 struct io_uring_params __user *params)
9648 struct user_struct *user = NULL;
9649 struct io_ring_ctx *ctx;
9656 if (entries > IORING_MAX_ENTRIES) {
9657 if (!(p->flags & IORING_SETUP_CLAMP))
9659 entries = IORING_MAX_ENTRIES;
9663 * Use twice as many entries for the CQ ring. It's possible for the
9664 * application to drive a higher depth than the size of the SQ ring,
9665 * since the sqes are only used at submission time. This allows for
9666 * some flexibility in overcommitting a bit. If the application has
9667 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9668 * of CQ ring entries manually.
9670 p->sq_entries = roundup_pow_of_two(entries);
9671 if (p->flags & IORING_SETUP_CQSIZE) {
9673 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9674 * to a power-of-two, if it isn't already. We do NOT impose
9675 * any cq vs sq ring sizing.
9679 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9680 if (!(p->flags & IORING_SETUP_CLAMP))
9682 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9684 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9685 if (p->cq_entries < p->sq_entries)
9688 p->cq_entries = 2 * p->sq_entries;
9691 user = get_uid(current_user());
9692 limit_mem = !capable(CAP_IPC_LOCK);
9695 ret = __io_account_mem(user,
9696 ring_pages(p->sq_entries, p->cq_entries));
9703 ctx = io_ring_ctx_alloc(p);
9706 __io_unaccount_mem(user, ring_pages(p->sq_entries,
9711 ctx->compat = in_compat_syscall();
9713 ctx->creds = get_current_cred();
9715 ctx->loginuid = current->loginuid;
9716 ctx->sessionid = current->sessionid;
9718 ctx->sqo_task = get_task_struct(current);
9721 * This is just grabbed for accounting purposes. When a process exits,
9722 * the mm is exited and dropped before the files, hence we need to hang
9723 * on to this mm purely for the purposes of being able to unaccount
9724 * memory (locked/pinned vm). It's not used for anything else.
9726 mmgrab(current->mm);
9727 ctx->mm_account = current->mm;
9729 #ifdef CONFIG_BLK_CGROUP
9731 * The sq thread will belong to the original cgroup it was inited in.
9732 * If the cgroup goes offline (e.g. disabling the io controller), then
9733 * issued bios will be associated with the closest cgroup later in the
9737 ctx->sqo_blkcg_css = blkcg_css();
9738 ret = css_tryget_online(ctx->sqo_blkcg_css);
9741 /* don't init against a dying cgroup, have the user try again */
9742 ctx->sqo_blkcg_css = NULL;
9749 * Account memory _before_ installing the file descriptor. Once
9750 * the descriptor is installed, it can get closed at any time. Also
9751 * do this before hitting the general error path, as ring freeing
9752 * will un-account as well.
9754 io_account_mem(ctx, ring_pages(p->sq_entries, p->cq_entries),
9756 ctx->limit_mem = limit_mem;
9758 ret = io_allocate_scq_urings(ctx, p);
9762 ret = io_sq_offload_create(ctx, p);
9766 if (!(p->flags & IORING_SETUP_R_DISABLED))
9767 io_sq_offload_start(ctx);
9769 memset(&p->sq_off, 0, sizeof(p->sq_off));
9770 p->sq_off.head = offsetof(struct io_rings, sq.head);
9771 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9772 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9773 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9774 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9775 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9776 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9778 memset(&p->cq_off, 0, sizeof(p->cq_off));
9779 p->cq_off.head = offsetof(struct io_rings, cq.head);
9780 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9781 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9782 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9783 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9784 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9785 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9787 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9788 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9789 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9790 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9791 IORING_FEAT_EXT_ARG;
9793 if (copy_to_user(params, p, sizeof(*p))) {
9798 file = io_uring_get_file(ctx);
9800 ret = PTR_ERR(file);
9805 * Install ring fd as the very last thing, so we don't risk someone
9806 * having closed it before we finish setup
9808 ret = io_uring_install_fd(ctx, file);
9810 io_disable_sqo_submit(ctx);
9811 /* fput will clean it up */
9816 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9819 io_disable_sqo_submit(ctx);
9820 io_ring_ctx_wait_and_kill(ctx);
9825 * Sets up an aio uring context, and returns the fd. Applications asks for a
9826 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9827 * params structure passed in.
9829 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9831 struct io_uring_params p;
9834 if (copy_from_user(&p, params, sizeof(p)))
9836 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9841 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9842 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9843 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9844 IORING_SETUP_R_DISABLED))
9847 return io_uring_create(entries, &p, params);
9850 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9851 struct io_uring_params __user *, params)
9853 return io_uring_setup(entries, params);
9856 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9858 struct io_uring_probe *p;
9862 size = struct_size(p, ops, nr_args);
9863 if (size == SIZE_MAX)
9865 p = kzalloc(size, GFP_KERNEL);
9870 if (copy_from_user(p, arg, size))
9873 if (memchr_inv(p, 0, size))
9876 p->last_op = IORING_OP_LAST - 1;
9877 if (nr_args > IORING_OP_LAST)
9878 nr_args = IORING_OP_LAST;
9880 for (i = 0; i < nr_args; i++) {
9882 if (!io_op_defs[i].not_supported)
9883 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9888 if (copy_to_user(arg, p, size))
9895 static int io_register_personality(struct io_ring_ctx *ctx)
9897 struct io_identity *id;
9900 id = kmalloc(sizeof(*id), GFP_KERNEL);
9904 io_init_identity(id);
9905 id->creds = get_current_cred();
9907 ret = idr_alloc_cyclic(&ctx->personality_idr, id, 1, USHRT_MAX, GFP_KERNEL);
9909 put_cred(id->creds);
9915 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9917 struct io_identity *iod;
9919 iod = idr_remove(&ctx->personality_idr, id);
9921 put_cred(iod->creds);
9922 if (refcount_dec_and_test(&iod->count))
9930 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9931 unsigned int nr_args)
9933 struct io_uring_restriction *res;
9937 /* Restrictions allowed only if rings started disabled */
9938 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9941 /* We allow only a single restrictions registration */
9942 if (ctx->restrictions.registered)
9945 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9948 size = array_size(nr_args, sizeof(*res));
9949 if (size == SIZE_MAX)
9952 res = memdup_user(arg, size);
9954 return PTR_ERR(res);
9958 for (i = 0; i < nr_args; i++) {
9959 switch (res[i].opcode) {
9960 case IORING_RESTRICTION_REGISTER_OP:
9961 if (res[i].register_op >= IORING_REGISTER_LAST) {
9966 __set_bit(res[i].register_op,
9967 ctx->restrictions.register_op);
9969 case IORING_RESTRICTION_SQE_OP:
9970 if (res[i].sqe_op >= IORING_OP_LAST) {
9975 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9977 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9978 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9980 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9981 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9990 /* Reset all restrictions if an error happened */
9992 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9994 ctx->restrictions.registered = true;
10000 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10002 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10005 if (ctx->restrictions.registered)
10006 ctx->restricted = 1;
10008 ctx->flags &= ~IORING_SETUP_R_DISABLED;
10010 io_sq_offload_start(ctx);
10015 static bool io_register_op_must_quiesce(int op)
10018 case IORING_UNREGISTER_FILES:
10019 case IORING_REGISTER_FILES_UPDATE:
10020 case IORING_REGISTER_PROBE:
10021 case IORING_REGISTER_PERSONALITY:
10022 case IORING_UNREGISTER_PERSONALITY:
10029 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10030 void __user *arg, unsigned nr_args)
10031 __releases(ctx->uring_lock)
10032 __acquires(ctx->uring_lock)
10037 * We're inside the ring mutex, if the ref is already dying, then
10038 * someone else killed the ctx or is already going through
10039 * io_uring_register().
10041 if (percpu_ref_is_dying(&ctx->refs))
10044 if (io_register_op_must_quiesce(opcode)) {
10045 percpu_ref_kill(&ctx->refs);
10048 * Drop uring mutex before waiting for references to exit. If
10049 * another thread is currently inside io_uring_enter() it might
10050 * need to grab the uring_lock to make progress. If we hold it
10051 * here across the drain wait, then we can deadlock. It's safe
10052 * to drop the mutex here, since no new references will come in
10053 * after we've killed the percpu ref.
10055 mutex_unlock(&ctx->uring_lock);
10057 ret = wait_for_completion_interruptible(&ctx->ref_comp);
10060 ret = io_run_task_work_sig();
10065 mutex_lock(&ctx->uring_lock);
10068 percpu_ref_resurrect(&ctx->refs);
10073 if (ctx->restricted) {
10074 if (opcode >= IORING_REGISTER_LAST) {
10079 if (!test_bit(opcode, ctx->restrictions.register_op)) {
10086 case IORING_REGISTER_BUFFERS:
10087 ret = io_sqe_buffers_register(ctx, arg, nr_args);
10089 case IORING_UNREGISTER_BUFFERS:
10091 if (arg || nr_args)
10093 ret = io_sqe_buffers_unregister(ctx);
10095 case IORING_REGISTER_FILES:
10096 ret = io_sqe_files_register(ctx, arg, nr_args);
10098 case IORING_UNREGISTER_FILES:
10100 if (arg || nr_args)
10102 ret = io_sqe_files_unregister(ctx);
10104 case IORING_REGISTER_FILES_UPDATE:
10105 ret = io_sqe_files_update(ctx, arg, nr_args);
10107 case IORING_REGISTER_EVENTFD:
10108 case IORING_REGISTER_EVENTFD_ASYNC:
10112 ret = io_eventfd_register(ctx, arg);
10115 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10116 ctx->eventfd_async = 1;
10118 ctx->eventfd_async = 0;
10120 case IORING_UNREGISTER_EVENTFD:
10122 if (arg || nr_args)
10124 ret = io_eventfd_unregister(ctx);
10126 case IORING_REGISTER_PROBE:
10128 if (!arg || nr_args > 256)
10130 ret = io_probe(ctx, arg, nr_args);
10132 case IORING_REGISTER_PERSONALITY:
10134 if (arg || nr_args)
10136 ret = io_register_personality(ctx);
10138 case IORING_UNREGISTER_PERSONALITY:
10142 ret = io_unregister_personality(ctx, nr_args);
10144 case IORING_REGISTER_ENABLE_RINGS:
10146 if (arg || nr_args)
10148 ret = io_register_enable_rings(ctx);
10150 case IORING_REGISTER_RESTRICTIONS:
10151 ret = io_register_restrictions(ctx, arg, nr_args);
10159 if (io_register_op_must_quiesce(opcode)) {
10160 /* bring the ctx back to life */
10161 percpu_ref_reinit(&ctx->refs);
10163 reinit_completion(&ctx->ref_comp);
10168 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10169 void __user *, arg, unsigned int, nr_args)
10171 struct io_ring_ctx *ctx;
10180 if (f.file->f_op != &io_uring_fops)
10183 ctx = f.file->private_data;
10185 mutex_lock(&ctx->uring_lock);
10186 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10187 mutex_unlock(&ctx->uring_lock);
10188 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10189 ctx->cq_ev_fd != NULL, ret);
10195 static int __init io_uring_init(void)
10197 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10198 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10199 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10202 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10203 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10204 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10205 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10206 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10207 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10208 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10209 BUILD_BUG_SQE_ELEM(8, __u64, off);
10210 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10211 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10212 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10213 BUILD_BUG_SQE_ELEM(24, __u32, len);
10214 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10215 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10216 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10217 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10218 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10219 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10220 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10221 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10222 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10223 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10224 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10225 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10226 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10227 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10228 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10229 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10230 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10231 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10232 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10234 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10235 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10236 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
10239 __initcall(io_uring_init);