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;
198 struct fixed_file_table {
202 struct fixed_file_ref_node {
203 struct percpu_ref refs;
204 struct list_head node;
205 struct list_head file_list;
206 struct fixed_file_data *file_data;
207 struct llist_node llist;
211 struct fixed_file_data {
212 struct fixed_file_table *table;
213 struct io_ring_ctx *ctx;
215 struct fixed_file_ref_node *node;
216 struct percpu_ref refs;
217 struct completion done;
218 struct list_head ref_list;
223 struct list_head list;
229 struct io_restriction {
230 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
231 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
232 u8 sqe_flags_allowed;
233 u8 sqe_flags_required;
241 /* ctx's that are using this sqd */
242 struct list_head ctx_list;
243 struct list_head ctx_new_list;
244 struct mutex ctx_lock;
246 struct task_struct *thread;
247 struct wait_queue_head wait;
249 unsigned sq_thread_idle;
254 struct percpu_ref refs;
255 } ____cacheline_aligned_in_smp;
259 unsigned int compat: 1;
260 unsigned int limit_mem: 1;
261 unsigned int cq_overflow_flushed: 1;
262 unsigned int drain_next: 1;
263 unsigned int eventfd_async: 1;
264 unsigned int restricted: 1;
265 unsigned int sqo_dead: 1;
268 * Ring buffer of indices into array of io_uring_sqe, which is
269 * mmapped by the application using the IORING_OFF_SQES offset.
271 * This indirection could e.g. be used to assign fixed
272 * io_uring_sqe entries to operations and only submit them to
273 * the queue when needed.
275 * The kernel modifies neither the indices array nor the entries
279 unsigned cached_sq_head;
282 unsigned sq_thread_idle;
283 unsigned cached_sq_dropped;
284 unsigned cached_cq_overflow;
285 unsigned long sq_check_overflow;
287 struct list_head defer_list;
288 struct list_head timeout_list;
289 struct list_head cq_overflow_list;
291 struct io_uring_sqe *sq_sqes;
292 } ____cacheline_aligned_in_smp;
294 struct io_rings *rings;
300 * For SQPOLL usage - we hold a reference to the parent task, so we
301 * have access to the ->files
303 struct task_struct *sqo_task;
305 /* Only used for accounting purposes */
306 struct mm_struct *mm_account;
308 #ifdef CONFIG_BLK_CGROUP
309 struct cgroup_subsys_state *sqo_blkcg_css;
312 struct io_sq_data *sq_data; /* if using sq thread polling */
314 struct wait_queue_head sqo_sq_wait;
315 struct list_head sqd_list;
318 * If used, fixed file set. Writers must ensure that ->refs is dead,
319 * readers must ensure that ->refs is alive as long as the file* is
320 * used. Only updated through io_uring_register(2).
322 struct fixed_file_data *file_data;
323 unsigned nr_user_files;
325 /* if used, fixed mapped user buffers */
326 unsigned nr_user_bufs;
327 struct io_mapped_ubuf *user_bufs;
329 struct user_struct *user;
331 const struct cred *creds;
335 unsigned int sessionid;
338 struct completion ref_comp;
339 struct completion sq_thread_comp;
341 /* if all else fails... */
342 struct io_kiocb *fallback_req;
344 #if defined(CONFIG_UNIX)
345 struct socket *ring_sock;
348 struct idr io_buffer_idr;
350 struct idr personality_idr;
353 unsigned cached_cq_tail;
356 atomic_t cq_timeouts;
357 unsigned cq_last_tm_flush;
358 unsigned long cq_check_overflow;
359 struct wait_queue_head cq_wait;
360 struct fasync_struct *cq_fasync;
361 struct eventfd_ctx *cq_ev_fd;
362 } ____cacheline_aligned_in_smp;
365 struct mutex uring_lock;
366 wait_queue_head_t wait;
367 } ____cacheline_aligned_in_smp;
370 spinlock_t completion_lock;
373 * ->iopoll_list is protected by the ctx->uring_lock for
374 * io_uring instances that don't use IORING_SETUP_SQPOLL.
375 * For SQPOLL, only the single threaded io_sq_thread() will
376 * manipulate the list, hence no extra locking is needed there.
378 struct list_head iopoll_list;
379 struct hlist_head *cancel_hash;
380 unsigned cancel_hash_bits;
381 bool poll_multi_file;
383 spinlock_t inflight_lock;
384 struct list_head inflight_list;
385 } ____cacheline_aligned_in_smp;
387 struct delayed_work file_put_work;
388 struct llist_head file_put_llist;
390 struct work_struct exit_work;
391 struct io_restriction restrictions;
395 * First field must be the file pointer in all the
396 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
398 struct io_poll_iocb {
400 struct wait_queue_head *head;
404 struct wait_queue_entry wait;
407 struct io_poll_remove {
414 struct file *put_file;
418 struct io_timeout_data {
419 struct io_kiocb *req;
420 struct hrtimer timer;
421 struct timespec64 ts;
422 enum hrtimer_mode mode;
427 struct sockaddr __user *addr;
428 int __user *addr_len;
430 unsigned long nofile;
450 struct list_head list;
451 /* head of the link, used by linked timeouts only */
452 struct io_kiocb *head;
455 struct io_timeout_rem {
460 struct timespec64 ts;
465 /* NOTE: kiocb has the file as the first member, so don't do it here */
473 struct sockaddr __user *addr;
480 struct user_msghdr __user *umsg;
486 struct io_buffer *kbuf;
492 bool ignore_nonblock;
493 struct filename *filename;
495 unsigned long nofile;
498 struct io_files_update {
524 struct epoll_event event;
528 struct file *file_out;
529 struct file *file_in;
536 struct io_provide_buf {
550 const char __user *filename;
551 struct statx __user *buffer;
563 struct filename *oldpath;
564 struct filename *newpath;
572 struct filename *filename;
575 struct io_completion {
577 struct list_head list;
581 struct io_async_connect {
582 struct sockaddr_storage address;
585 struct io_async_msghdr {
586 struct iovec fast_iov[UIO_FASTIOV];
588 struct sockaddr __user *uaddr;
590 struct sockaddr_storage addr;
594 struct iovec fast_iov[UIO_FASTIOV];
595 const struct iovec *free_iovec;
596 struct iov_iter iter;
598 struct wait_page_queue wpq;
602 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
603 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
604 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
605 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
606 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
607 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
613 REQ_F_LINK_TIMEOUT_BIT,
615 REQ_F_NEED_CLEANUP_BIT,
617 REQ_F_BUFFER_SELECTED_BIT,
618 REQ_F_NO_FILE_TABLE_BIT,
619 REQ_F_WORK_INITIALIZED_BIT,
620 REQ_F_LTIMEOUT_ACTIVE_BIT,
622 /* not a real bit, just to check we're not overflowing the space */
628 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
629 /* drain existing IO first */
630 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
632 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
633 /* doesn't sever on completion < 0 */
634 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
636 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
637 /* IOSQE_BUFFER_SELECT */
638 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
640 /* fail rest of links */
641 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
642 /* on inflight list */
643 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
644 /* read/write uses file position */
645 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
646 /* must not punt to workers */
647 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
648 /* has or had linked timeout */
649 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
651 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
653 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
654 /* already went through poll handler */
655 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
656 /* buffer already selected */
657 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
658 /* doesn't need file table for this request */
659 REQ_F_NO_FILE_TABLE = BIT(REQ_F_NO_FILE_TABLE_BIT),
660 /* io_wq_work is initialized */
661 REQ_F_WORK_INITIALIZED = BIT(REQ_F_WORK_INITIALIZED_BIT),
662 /* linked timeout is active, i.e. prepared by link's head */
663 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
667 struct io_poll_iocb poll;
668 struct io_poll_iocb *double_poll;
672 * NOTE! Each of the iocb union members has the file pointer
673 * as the first entry in their struct definition. So you can
674 * access the file pointer through any of the sub-structs,
675 * or directly as just 'ki_filp' in this struct.
681 struct io_poll_iocb poll;
682 struct io_poll_remove poll_remove;
683 struct io_accept accept;
685 struct io_cancel cancel;
686 struct io_timeout timeout;
687 struct io_timeout_rem timeout_rem;
688 struct io_connect connect;
689 struct io_sr_msg sr_msg;
691 struct io_close close;
692 struct io_files_update files_update;
693 struct io_fadvise fadvise;
694 struct io_madvise madvise;
695 struct io_epoll epoll;
696 struct io_splice splice;
697 struct io_provide_buf pbuf;
698 struct io_statx statx;
699 struct io_shutdown shutdown;
700 struct io_rename rename;
701 struct io_unlink unlink;
702 /* use only after cleaning per-op data, see io_clean_op() */
703 struct io_completion compl;
706 /* opcode allocated if it needs to store data for async defer */
709 /* polled IO has completed */
715 struct io_ring_ctx *ctx;
718 struct task_struct *task;
721 struct io_kiocb *link;
722 struct percpu_ref *fixed_file_refs;
725 * 1. used with ctx->iopoll_list with reads/writes
726 * 2. to track reqs with ->files (see io_op_def::file_table)
728 struct list_head inflight_entry;
729 struct callback_head task_work;
730 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
731 struct hlist_node hash_node;
732 struct async_poll *apoll;
733 struct io_wq_work work;
736 struct io_defer_entry {
737 struct list_head list;
738 struct io_kiocb *req;
742 #define IO_IOPOLL_BATCH 8
744 struct io_comp_state {
746 struct list_head list;
747 struct io_ring_ctx *ctx;
750 struct io_submit_state {
751 struct blk_plug plug;
754 * io_kiocb alloc cache
756 void *reqs[IO_IOPOLL_BATCH];
757 unsigned int free_reqs;
762 * Batch completion logic
764 struct io_comp_state comp;
767 * File reference cache
771 unsigned int file_refs;
772 unsigned int ios_left;
776 /* needs req->file assigned */
777 unsigned needs_file : 1;
778 /* don't fail if file grab fails */
779 unsigned needs_file_no_error : 1;
780 /* hash wq insertion if file is a regular file */
781 unsigned hash_reg_file : 1;
782 /* unbound wq insertion if file is a non-regular file */
783 unsigned unbound_nonreg_file : 1;
784 /* opcode is not supported by this kernel */
785 unsigned not_supported : 1;
786 /* set if opcode supports polled "wait" */
788 unsigned pollout : 1;
789 /* op supports buffer selection */
790 unsigned buffer_select : 1;
791 /* must always have async data allocated */
792 unsigned needs_async_data : 1;
793 /* should block plug */
795 /* size of async data needed, if any */
796 unsigned short async_size;
800 static const struct io_op_def io_op_defs[] = {
801 [IORING_OP_NOP] = {},
802 [IORING_OP_READV] = {
804 .unbound_nonreg_file = 1,
807 .needs_async_data = 1,
809 .async_size = sizeof(struct io_async_rw),
810 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
812 [IORING_OP_WRITEV] = {
815 .unbound_nonreg_file = 1,
817 .needs_async_data = 1,
819 .async_size = sizeof(struct io_async_rw),
820 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG |
823 [IORING_OP_FSYNC] = {
825 .work_flags = IO_WQ_WORK_BLKCG,
827 [IORING_OP_READ_FIXED] = {
829 .unbound_nonreg_file = 1,
832 .async_size = sizeof(struct io_async_rw),
833 .work_flags = IO_WQ_WORK_BLKCG | IO_WQ_WORK_MM,
835 [IORING_OP_WRITE_FIXED] = {
838 .unbound_nonreg_file = 1,
841 .async_size = sizeof(struct io_async_rw),
842 .work_flags = IO_WQ_WORK_BLKCG | IO_WQ_WORK_FSIZE |
845 [IORING_OP_POLL_ADD] = {
847 .unbound_nonreg_file = 1,
849 [IORING_OP_POLL_REMOVE] = {},
850 [IORING_OP_SYNC_FILE_RANGE] = {
852 .work_flags = IO_WQ_WORK_BLKCG,
854 [IORING_OP_SENDMSG] = {
856 .unbound_nonreg_file = 1,
858 .needs_async_data = 1,
859 .async_size = sizeof(struct io_async_msghdr),
860 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
862 [IORING_OP_RECVMSG] = {
864 .unbound_nonreg_file = 1,
867 .needs_async_data = 1,
868 .async_size = sizeof(struct io_async_msghdr),
869 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
871 [IORING_OP_TIMEOUT] = {
872 .needs_async_data = 1,
873 .async_size = sizeof(struct io_timeout_data),
874 .work_flags = IO_WQ_WORK_MM,
876 [IORING_OP_TIMEOUT_REMOVE] = {
877 /* used by timeout updates' prep() */
878 .work_flags = IO_WQ_WORK_MM,
880 [IORING_OP_ACCEPT] = {
882 .unbound_nonreg_file = 1,
884 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_FILES,
886 [IORING_OP_ASYNC_CANCEL] = {},
887 [IORING_OP_LINK_TIMEOUT] = {
888 .needs_async_data = 1,
889 .async_size = sizeof(struct io_timeout_data),
890 .work_flags = IO_WQ_WORK_MM,
892 [IORING_OP_CONNECT] = {
894 .unbound_nonreg_file = 1,
896 .needs_async_data = 1,
897 .async_size = sizeof(struct io_async_connect),
898 .work_flags = IO_WQ_WORK_MM,
900 [IORING_OP_FALLOCATE] = {
902 .work_flags = IO_WQ_WORK_BLKCG | IO_WQ_WORK_FSIZE,
904 [IORING_OP_OPENAT] = {
905 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_BLKCG |
906 IO_WQ_WORK_FS | IO_WQ_WORK_MM,
908 [IORING_OP_CLOSE] = {
910 .needs_file_no_error = 1,
911 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_BLKCG,
913 [IORING_OP_FILES_UPDATE] = {
914 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_MM,
916 [IORING_OP_STATX] = {
917 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_MM |
918 IO_WQ_WORK_FS | IO_WQ_WORK_BLKCG,
922 .unbound_nonreg_file = 1,
926 .async_size = sizeof(struct io_async_rw),
927 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
929 [IORING_OP_WRITE] = {
931 .unbound_nonreg_file = 1,
934 .async_size = sizeof(struct io_async_rw),
935 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG |
938 [IORING_OP_FADVISE] = {
940 .work_flags = IO_WQ_WORK_BLKCG,
942 [IORING_OP_MADVISE] = {
943 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
947 .unbound_nonreg_file = 1,
949 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
953 .unbound_nonreg_file = 1,
956 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_BLKCG,
958 [IORING_OP_OPENAT2] = {
959 .work_flags = IO_WQ_WORK_FILES | IO_WQ_WORK_FS |
960 IO_WQ_WORK_BLKCG | IO_WQ_WORK_MM,
962 [IORING_OP_EPOLL_CTL] = {
963 .unbound_nonreg_file = 1,
964 .work_flags = IO_WQ_WORK_FILES,
966 [IORING_OP_SPLICE] = {
969 .unbound_nonreg_file = 1,
970 .work_flags = IO_WQ_WORK_BLKCG,
972 [IORING_OP_PROVIDE_BUFFERS] = {},
973 [IORING_OP_REMOVE_BUFFERS] = {},
977 .unbound_nonreg_file = 1,
979 [IORING_OP_SHUTDOWN] = {
982 [IORING_OP_RENAMEAT] = {
983 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_FILES |
984 IO_WQ_WORK_FS | IO_WQ_WORK_BLKCG,
986 [IORING_OP_UNLINKAT] = {
987 .work_flags = IO_WQ_WORK_MM | IO_WQ_WORK_FILES |
988 IO_WQ_WORK_FS | IO_WQ_WORK_BLKCG,
992 enum io_mem_account {
997 static void __io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
998 struct task_struct *task);
1000 static void destroy_fixed_file_ref_node(struct fixed_file_ref_node *ref_node);
1001 static struct fixed_file_ref_node *alloc_fixed_file_ref_node(
1002 struct io_ring_ctx *ctx);
1004 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
1005 struct io_comp_state *cs);
1006 static void io_cqring_fill_event(struct io_kiocb *req, long res);
1007 static void io_put_req(struct io_kiocb *req);
1008 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1009 static void io_double_put_req(struct io_kiocb *req);
1010 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1011 static void __io_queue_linked_timeout(struct io_kiocb *req);
1012 static void io_queue_linked_timeout(struct io_kiocb *req);
1013 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
1014 struct io_uring_files_update *ip,
1016 static void __io_clean_op(struct io_kiocb *req);
1017 static struct file *io_file_get(struct io_submit_state *state,
1018 struct io_kiocb *req, int fd, bool fixed);
1019 static void __io_queue_sqe(struct io_kiocb *req, struct io_comp_state *cs);
1020 static void io_file_put_work(struct work_struct *work);
1022 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
1023 struct iovec **iovec, struct iov_iter *iter,
1025 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
1026 const struct iovec *fast_iov,
1027 struct iov_iter *iter, bool force);
1028 static void io_req_drop_files(struct io_kiocb *req);
1029 static void io_req_task_queue(struct io_kiocb *req);
1031 static struct kmem_cache *req_cachep;
1033 static const struct file_operations io_uring_fops;
1035 struct sock *io_uring_get_socket(struct file *file)
1037 #if defined(CONFIG_UNIX)
1038 if (file->f_op == &io_uring_fops) {
1039 struct io_ring_ctx *ctx = file->private_data;
1041 return ctx->ring_sock->sk;
1046 EXPORT_SYMBOL(io_uring_get_socket);
1048 #define io_for_each_link(pos, head) \
1049 for (pos = (head); pos; pos = pos->link)
1051 static inline void io_clean_op(struct io_kiocb *req)
1053 if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED))
1057 static inline void io_set_resource_node(struct io_kiocb *req)
1059 struct io_ring_ctx *ctx = req->ctx;
1061 if (!req->fixed_file_refs) {
1062 req->fixed_file_refs = &ctx->file_data->node->refs;
1063 percpu_ref_get(req->fixed_file_refs);
1067 static bool io_match_task(struct io_kiocb *head,
1068 struct task_struct *task,
1069 struct files_struct *files)
1071 struct io_kiocb *req;
1073 if (task && head->task != task) {
1074 /* in terms of cancelation, always match if req task is dead */
1075 if (head->task->flags & PF_EXITING)
1082 io_for_each_link(req, head) {
1083 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1085 if (req->file && req->file->f_op == &io_uring_fops)
1087 if ((req->work.flags & IO_WQ_WORK_FILES) &&
1088 req->work.identity->files == files)
1094 static void io_sq_thread_drop_mm_files(void)
1096 struct files_struct *files = current->files;
1097 struct mm_struct *mm = current->mm;
1100 kthread_unuse_mm(mm);
1105 struct nsproxy *nsproxy = current->nsproxy;
1108 current->files = NULL;
1109 current->nsproxy = NULL;
1110 task_unlock(current);
1111 put_files_struct(files);
1112 put_nsproxy(nsproxy);
1116 static int __io_sq_thread_acquire_files(struct io_ring_ctx *ctx)
1118 if (current->flags & PF_EXITING)
1121 if (!current->files) {
1122 struct files_struct *files;
1123 struct nsproxy *nsproxy;
1125 task_lock(ctx->sqo_task);
1126 files = ctx->sqo_task->files;
1128 task_unlock(ctx->sqo_task);
1131 atomic_inc(&files->count);
1132 get_nsproxy(ctx->sqo_task->nsproxy);
1133 nsproxy = ctx->sqo_task->nsproxy;
1134 task_unlock(ctx->sqo_task);
1137 current->files = files;
1138 current->nsproxy = nsproxy;
1139 task_unlock(current);
1144 static int __io_sq_thread_acquire_mm(struct io_ring_ctx *ctx)
1146 struct mm_struct *mm;
1148 if (current->flags & PF_EXITING)
1153 /* Should never happen */
1154 if (unlikely(!(ctx->flags & IORING_SETUP_SQPOLL)))
1157 task_lock(ctx->sqo_task);
1158 mm = ctx->sqo_task->mm;
1159 if (unlikely(!mm || !mmget_not_zero(mm)))
1161 task_unlock(ctx->sqo_task);
1171 static int io_sq_thread_acquire_mm_files(struct io_ring_ctx *ctx,
1172 struct io_kiocb *req)
1174 const struct io_op_def *def = &io_op_defs[req->opcode];
1177 if (def->work_flags & IO_WQ_WORK_MM) {
1178 ret = __io_sq_thread_acquire_mm(ctx);
1183 if (def->needs_file || (def->work_flags & IO_WQ_WORK_FILES)) {
1184 ret = __io_sq_thread_acquire_files(ctx);
1192 static void io_sq_thread_associate_blkcg(struct io_ring_ctx *ctx,
1193 struct cgroup_subsys_state **cur_css)
1196 #ifdef CONFIG_BLK_CGROUP
1197 /* puts the old one when swapping */
1198 if (*cur_css != ctx->sqo_blkcg_css) {
1199 kthread_associate_blkcg(ctx->sqo_blkcg_css);
1200 *cur_css = ctx->sqo_blkcg_css;
1205 static void io_sq_thread_unassociate_blkcg(void)
1207 #ifdef CONFIG_BLK_CGROUP
1208 kthread_associate_blkcg(NULL);
1212 static inline void req_set_fail_links(struct io_kiocb *req)
1214 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1215 req->flags |= REQ_F_FAIL_LINK;
1219 * None of these are dereferenced, they are simply used to check if any of
1220 * them have changed. If we're under current and check they are still the
1221 * same, we're fine to grab references to them for actual out-of-line use.
1223 static void io_init_identity(struct io_identity *id)
1225 id->files = current->files;
1226 id->mm = current->mm;
1227 #ifdef CONFIG_BLK_CGROUP
1229 id->blkcg_css = blkcg_css();
1232 id->creds = current_cred();
1233 id->nsproxy = current->nsproxy;
1234 id->fs = current->fs;
1235 id->fsize = rlimit(RLIMIT_FSIZE);
1237 id->loginuid = current->loginuid;
1238 id->sessionid = current->sessionid;
1240 refcount_set(&id->count, 1);
1243 static inline void __io_req_init_async(struct io_kiocb *req)
1245 memset(&req->work, 0, sizeof(req->work));
1246 req->flags |= REQ_F_WORK_INITIALIZED;
1250 * Note: must call io_req_init_async() for the first time you
1251 * touch any members of io_wq_work.
1253 static inline void io_req_init_async(struct io_kiocb *req)
1255 struct io_uring_task *tctx = current->io_uring;
1257 if (req->flags & REQ_F_WORK_INITIALIZED)
1260 __io_req_init_async(req);
1262 /* Grab a ref if this isn't our static identity */
1263 req->work.identity = tctx->identity;
1264 if (tctx->identity != &tctx->__identity)
1265 refcount_inc(&req->work.identity->count);
1268 static inline bool io_async_submit(struct io_ring_ctx *ctx)
1270 return ctx->flags & IORING_SETUP_SQPOLL;
1273 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1275 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1277 complete(&ctx->ref_comp);
1280 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1282 return !req->timeout.off;
1285 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1287 struct io_ring_ctx *ctx;
1290 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1294 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
1295 if (!ctx->fallback_req)
1299 * Use 5 bits less than the max cq entries, that should give us around
1300 * 32 entries per hash list if totally full and uniformly spread.
1302 hash_bits = ilog2(p->cq_entries);
1306 ctx->cancel_hash_bits = hash_bits;
1307 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1309 if (!ctx->cancel_hash)
1311 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1313 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1314 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1317 ctx->flags = p->flags;
1318 init_waitqueue_head(&ctx->sqo_sq_wait);
1319 INIT_LIST_HEAD(&ctx->sqd_list);
1320 init_waitqueue_head(&ctx->cq_wait);
1321 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1322 init_completion(&ctx->ref_comp);
1323 init_completion(&ctx->sq_thread_comp);
1324 idr_init(&ctx->io_buffer_idr);
1325 idr_init(&ctx->personality_idr);
1326 mutex_init(&ctx->uring_lock);
1327 init_waitqueue_head(&ctx->wait);
1328 spin_lock_init(&ctx->completion_lock);
1329 INIT_LIST_HEAD(&ctx->iopoll_list);
1330 INIT_LIST_HEAD(&ctx->defer_list);
1331 INIT_LIST_HEAD(&ctx->timeout_list);
1332 spin_lock_init(&ctx->inflight_lock);
1333 INIT_LIST_HEAD(&ctx->inflight_list);
1334 INIT_DELAYED_WORK(&ctx->file_put_work, io_file_put_work);
1335 init_llist_head(&ctx->file_put_llist);
1338 if (ctx->fallback_req)
1339 kmem_cache_free(req_cachep, ctx->fallback_req);
1340 kfree(ctx->cancel_hash);
1345 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1347 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1348 struct io_ring_ctx *ctx = req->ctx;
1350 return seq != ctx->cached_cq_tail
1351 + READ_ONCE(ctx->cached_cq_overflow);
1357 static void __io_commit_cqring(struct io_ring_ctx *ctx)
1359 struct io_rings *rings = ctx->rings;
1361 /* order cqe stores with ring update */
1362 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
1365 static void io_put_identity(struct io_uring_task *tctx, struct io_kiocb *req)
1367 if (req->work.identity == &tctx->__identity)
1369 if (refcount_dec_and_test(&req->work.identity->count))
1370 kfree(req->work.identity);
1373 static void io_req_clean_work(struct io_kiocb *req)
1375 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1378 req->flags &= ~REQ_F_WORK_INITIALIZED;
1380 if (req->work.flags & IO_WQ_WORK_MM) {
1381 mmdrop(req->work.identity->mm);
1382 req->work.flags &= ~IO_WQ_WORK_MM;
1384 #ifdef CONFIG_BLK_CGROUP
1385 if (req->work.flags & IO_WQ_WORK_BLKCG) {
1386 css_put(req->work.identity->blkcg_css);
1387 req->work.flags &= ~IO_WQ_WORK_BLKCG;
1390 if (req->work.flags & IO_WQ_WORK_CREDS) {
1391 put_cred(req->work.identity->creds);
1392 req->work.flags &= ~IO_WQ_WORK_CREDS;
1394 if (req->work.flags & IO_WQ_WORK_FS) {
1395 struct fs_struct *fs = req->work.identity->fs;
1397 spin_lock(&req->work.identity->fs->lock);
1400 spin_unlock(&req->work.identity->fs->lock);
1403 req->work.flags &= ~IO_WQ_WORK_FS;
1405 if (req->flags & REQ_F_INFLIGHT)
1406 io_req_drop_files(req);
1408 io_put_identity(req->task->io_uring, req);
1412 * Create a private copy of io_identity, since some fields don't match
1413 * the current context.
1415 static bool io_identity_cow(struct io_kiocb *req)
1417 struct io_uring_task *tctx = current->io_uring;
1418 const struct cred *creds = NULL;
1419 struct io_identity *id;
1421 if (req->work.flags & IO_WQ_WORK_CREDS)
1422 creds = req->work.identity->creds;
1424 id = kmemdup(req->work.identity, sizeof(*id), GFP_KERNEL);
1425 if (unlikely(!id)) {
1426 req->work.flags |= IO_WQ_WORK_CANCEL;
1431 * We can safely just re-init the creds we copied Either the field
1432 * matches the current one, or we haven't grabbed it yet. The only
1433 * exception is ->creds, through registered personalities, so handle
1434 * that one separately.
1436 io_init_identity(id);
1440 /* add one for this request */
1441 refcount_inc(&id->count);
1443 /* drop tctx and req identity references, if needed */
1444 if (tctx->identity != &tctx->__identity &&
1445 refcount_dec_and_test(&tctx->identity->count))
1446 kfree(tctx->identity);
1447 if (req->work.identity != &tctx->__identity &&
1448 refcount_dec_and_test(&req->work.identity->count))
1449 kfree(req->work.identity);
1451 req->work.identity = id;
1452 tctx->identity = id;
1456 static bool io_grab_identity(struct io_kiocb *req)
1458 const struct io_op_def *def = &io_op_defs[req->opcode];
1459 struct io_identity *id = req->work.identity;
1460 struct io_ring_ctx *ctx = req->ctx;
1462 if (def->work_flags & IO_WQ_WORK_FSIZE) {
1463 if (id->fsize != rlimit(RLIMIT_FSIZE))
1465 req->work.flags |= IO_WQ_WORK_FSIZE;
1467 #ifdef CONFIG_BLK_CGROUP
1468 if (!(req->work.flags & IO_WQ_WORK_BLKCG) &&
1469 (def->work_flags & IO_WQ_WORK_BLKCG)) {
1471 if (id->blkcg_css != blkcg_css()) {
1476 * This should be rare, either the cgroup is dying or the task
1477 * is moving cgroups. Just punt to root for the handful of ios.
1479 if (css_tryget_online(id->blkcg_css))
1480 req->work.flags |= IO_WQ_WORK_BLKCG;
1484 if (!(req->work.flags & IO_WQ_WORK_CREDS)) {
1485 if (id->creds != current_cred())
1487 get_cred(id->creds);
1488 req->work.flags |= IO_WQ_WORK_CREDS;
1491 if (!uid_eq(current->loginuid, id->loginuid) ||
1492 current->sessionid != id->sessionid)
1495 if (!(req->work.flags & IO_WQ_WORK_FS) &&
1496 (def->work_flags & IO_WQ_WORK_FS)) {
1497 if (current->fs != id->fs)
1499 spin_lock(&id->fs->lock);
1500 if (!id->fs->in_exec) {
1502 req->work.flags |= IO_WQ_WORK_FS;
1504 req->work.flags |= IO_WQ_WORK_CANCEL;
1506 spin_unlock(¤t->fs->lock);
1508 if (!(req->work.flags & IO_WQ_WORK_FILES) &&
1509 (def->work_flags & IO_WQ_WORK_FILES) &&
1510 !(req->flags & REQ_F_NO_FILE_TABLE)) {
1511 if (id->files != current->files ||
1512 id->nsproxy != current->nsproxy)
1514 atomic_inc(&id->files->count);
1515 get_nsproxy(id->nsproxy);
1517 if (!(req->flags & REQ_F_INFLIGHT)) {
1518 req->flags |= REQ_F_INFLIGHT;
1520 spin_lock_irq(&ctx->inflight_lock);
1521 list_add(&req->inflight_entry, &ctx->inflight_list);
1522 spin_unlock_irq(&ctx->inflight_lock);
1524 req->work.flags |= IO_WQ_WORK_FILES;
1526 if (!(req->work.flags & IO_WQ_WORK_MM) &&
1527 (def->work_flags & IO_WQ_WORK_MM)) {
1528 if (id->mm != current->mm)
1531 req->work.flags |= IO_WQ_WORK_MM;
1537 static void io_prep_async_work(struct io_kiocb *req)
1539 const struct io_op_def *def = &io_op_defs[req->opcode];
1540 struct io_ring_ctx *ctx = req->ctx;
1542 io_req_init_async(req);
1544 if (req->flags & REQ_F_FORCE_ASYNC)
1545 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1547 if (req->flags & REQ_F_ISREG) {
1548 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1549 io_wq_hash_work(&req->work, file_inode(req->file));
1551 if (def->unbound_nonreg_file)
1552 req->work.flags |= IO_WQ_WORK_UNBOUND;
1555 /* if we fail grabbing identity, we must COW, regrab, and retry */
1556 if (io_grab_identity(req))
1559 if (!io_identity_cow(req))
1562 /* can't fail at this point */
1563 if (!io_grab_identity(req))
1567 static void io_prep_async_link(struct io_kiocb *req)
1569 struct io_kiocb *cur;
1571 io_for_each_link(cur, req)
1572 io_prep_async_work(cur);
1575 static struct io_kiocb *__io_queue_async_work(struct io_kiocb *req)
1577 struct io_ring_ctx *ctx = req->ctx;
1578 struct io_kiocb *link = io_prep_linked_timeout(req);
1580 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1581 &req->work, req->flags);
1582 io_wq_enqueue(ctx->io_wq, &req->work);
1586 static void io_queue_async_work(struct io_kiocb *req)
1588 struct io_kiocb *link;
1590 /* init ->work of the whole link before punting */
1591 io_prep_async_link(req);
1592 link = __io_queue_async_work(req);
1595 io_queue_linked_timeout(link);
1598 static void io_kill_timeout(struct io_kiocb *req)
1600 struct io_timeout_data *io = req->async_data;
1603 ret = hrtimer_try_to_cancel(&io->timer);
1605 atomic_set(&req->ctx->cq_timeouts,
1606 atomic_read(&req->ctx->cq_timeouts) + 1);
1607 list_del_init(&req->timeout.list);
1608 io_cqring_fill_event(req, 0);
1609 io_put_req_deferred(req, 1);
1614 * Returns true if we found and killed one or more timeouts
1616 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
1617 struct files_struct *files)
1619 struct io_kiocb *req, *tmp;
1622 spin_lock_irq(&ctx->completion_lock);
1623 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1624 if (io_match_task(req, tsk, files)) {
1625 io_kill_timeout(req);
1629 spin_unlock_irq(&ctx->completion_lock);
1630 return canceled != 0;
1633 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1636 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1637 struct io_defer_entry, list);
1639 if (req_need_defer(de->req, de->seq))
1641 list_del_init(&de->list);
1642 io_req_task_queue(de->req);
1644 } while (!list_empty(&ctx->defer_list));
1647 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1651 if (list_empty(&ctx->timeout_list))
1654 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1657 u32 events_needed, events_got;
1658 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1659 struct io_kiocb, timeout.list);
1661 if (io_is_timeout_noseq(req))
1665 * Since seq can easily wrap around over time, subtract
1666 * the last seq at which timeouts were flushed before comparing.
1667 * Assuming not more than 2^31-1 events have happened since,
1668 * these subtractions won't have wrapped, so we can check if
1669 * target is in [last_seq, current_seq] by comparing the two.
1671 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1672 events_got = seq - ctx->cq_last_tm_flush;
1673 if (events_got < events_needed)
1676 list_del_init(&req->timeout.list);
1677 io_kill_timeout(req);
1678 } while (!list_empty(&ctx->timeout_list));
1680 ctx->cq_last_tm_flush = seq;
1683 static void io_commit_cqring(struct io_ring_ctx *ctx)
1685 io_flush_timeouts(ctx);
1686 __io_commit_cqring(ctx);
1688 if (unlikely(!list_empty(&ctx->defer_list)))
1689 __io_queue_deferred(ctx);
1692 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1694 struct io_rings *r = ctx->rings;
1696 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1699 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1701 struct io_rings *rings = ctx->rings;
1704 tail = ctx->cached_cq_tail;
1706 * writes to the cq entry need to come after reading head; the
1707 * control dependency is enough as we're using WRITE_ONCE to
1710 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
1713 ctx->cached_cq_tail++;
1714 return &rings->cqes[tail & ctx->cq_mask];
1717 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1721 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1723 if (!ctx->eventfd_async)
1725 return io_wq_current_is_worker();
1728 static inline unsigned __io_cqring_events(struct io_ring_ctx *ctx)
1730 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1733 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1735 /* see waitqueue_active() comment */
1738 if (waitqueue_active(&ctx->wait))
1739 wake_up(&ctx->wait);
1740 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1741 wake_up(&ctx->sq_data->wait);
1742 if (io_should_trigger_evfd(ctx))
1743 eventfd_signal(ctx->cq_ev_fd, 1);
1744 if (waitqueue_active(&ctx->cq_wait)) {
1745 wake_up_interruptible(&ctx->cq_wait);
1746 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1750 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1752 /* see waitqueue_active() comment */
1755 if (ctx->flags & IORING_SETUP_SQPOLL) {
1756 if (waitqueue_active(&ctx->wait))
1757 wake_up(&ctx->wait);
1759 if (io_should_trigger_evfd(ctx))
1760 eventfd_signal(ctx->cq_ev_fd, 1);
1761 if (waitqueue_active(&ctx->cq_wait)) {
1762 wake_up_interruptible(&ctx->cq_wait);
1763 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1767 /* Returns true if there are no backlogged entries after the flush */
1768 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1769 struct task_struct *tsk,
1770 struct files_struct *files)
1772 struct io_rings *rings = ctx->rings;
1773 struct io_kiocb *req, *tmp;
1774 struct io_uring_cqe *cqe;
1775 unsigned long flags;
1776 bool all_flushed, posted;
1779 if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
1783 spin_lock_irqsave(&ctx->completion_lock, flags);
1784 list_for_each_entry_safe(req, tmp, &ctx->cq_overflow_list, compl.list) {
1785 if (!io_match_task(req, tsk, files))
1788 cqe = io_get_cqring(ctx);
1792 list_move(&req->compl.list, &list);
1794 WRITE_ONCE(cqe->user_data, req->user_data);
1795 WRITE_ONCE(cqe->res, req->result);
1796 WRITE_ONCE(cqe->flags, req->compl.cflags);
1798 ctx->cached_cq_overflow++;
1799 WRITE_ONCE(ctx->rings->cq_overflow,
1800 ctx->cached_cq_overflow);
1805 all_flushed = list_empty(&ctx->cq_overflow_list);
1807 clear_bit(0, &ctx->sq_check_overflow);
1808 clear_bit(0, &ctx->cq_check_overflow);
1809 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1813 io_commit_cqring(ctx);
1814 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1816 io_cqring_ev_posted(ctx);
1818 while (!list_empty(&list)) {
1819 req = list_first_entry(&list, struct io_kiocb, compl.list);
1820 list_del(&req->compl.list);
1827 static void io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1828 struct task_struct *tsk,
1829 struct files_struct *files)
1831 if (test_bit(0, &ctx->cq_check_overflow)) {
1832 /* iopoll syncs against uring_lock, not completion_lock */
1833 if (ctx->flags & IORING_SETUP_IOPOLL)
1834 mutex_lock(&ctx->uring_lock);
1835 __io_cqring_overflow_flush(ctx, force, tsk, files);
1836 if (ctx->flags & IORING_SETUP_IOPOLL)
1837 mutex_unlock(&ctx->uring_lock);
1841 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1843 struct io_ring_ctx *ctx = req->ctx;
1844 struct io_uring_cqe *cqe;
1846 trace_io_uring_complete(ctx, req->user_data, res);
1849 * If we can't get a cq entry, userspace overflowed the
1850 * submission (by quite a lot). Increment the overflow count in
1853 cqe = io_get_cqring(ctx);
1855 WRITE_ONCE(cqe->user_data, req->user_data);
1856 WRITE_ONCE(cqe->res, res);
1857 WRITE_ONCE(cqe->flags, cflags);
1858 } else if (ctx->cq_overflow_flushed ||
1859 atomic_read(&req->task->io_uring->in_idle)) {
1861 * If we're in ring overflow flush mode, or in task cancel mode,
1862 * then we cannot store the request for later flushing, we need
1863 * to drop it on the floor.
1865 ctx->cached_cq_overflow++;
1866 WRITE_ONCE(ctx->rings->cq_overflow, ctx->cached_cq_overflow);
1868 if (list_empty(&ctx->cq_overflow_list)) {
1869 set_bit(0, &ctx->sq_check_overflow);
1870 set_bit(0, &ctx->cq_check_overflow);
1871 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1875 req->compl.cflags = cflags;
1876 refcount_inc(&req->refs);
1877 list_add_tail(&req->compl.list, &ctx->cq_overflow_list);
1881 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1883 __io_cqring_fill_event(req, res, 0);
1886 static void io_cqring_add_event(struct io_kiocb *req, long res, long cflags)
1888 struct io_ring_ctx *ctx = req->ctx;
1889 unsigned long flags;
1891 spin_lock_irqsave(&ctx->completion_lock, flags);
1892 __io_cqring_fill_event(req, res, cflags);
1893 io_commit_cqring(ctx);
1894 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1896 io_cqring_ev_posted(ctx);
1899 static void io_submit_flush_completions(struct io_comp_state *cs)
1901 struct io_ring_ctx *ctx = cs->ctx;
1903 spin_lock_irq(&ctx->completion_lock);
1904 while (!list_empty(&cs->list)) {
1905 struct io_kiocb *req;
1907 req = list_first_entry(&cs->list, struct io_kiocb, compl.list);
1908 list_del(&req->compl.list);
1909 __io_cqring_fill_event(req, req->result, req->compl.cflags);
1912 * io_free_req() doesn't care about completion_lock unless one
1913 * of these flags is set. REQ_F_WORK_INITIALIZED is in the list
1914 * because of a potential deadlock with req->work.fs->lock
1916 if (req->flags & (REQ_F_FAIL_LINK|REQ_F_LINK_TIMEOUT
1917 |REQ_F_WORK_INITIALIZED)) {
1918 spin_unlock_irq(&ctx->completion_lock);
1920 spin_lock_irq(&ctx->completion_lock);
1925 io_commit_cqring(ctx);
1926 spin_unlock_irq(&ctx->completion_lock);
1928 io_cqring_ev_posted(ctx);
1932 static void __io_req_complete(struct io_kiocb *req, long res, unsigned cflags,
1933 struct io_comp_state *cs)
1936 io_cqring_add_event(req, res, cflags);
1941 req->compl.cflags = cflags;
1942 list_add_tail(&req->compl.list, &cs->list);
1944 io_submit_flush_completions(cs);
1948 static void io_req_complete(struct io_kiocb *req, long res)
1950 __io_req_complete(req, res, 0, NULL);
1953 static inline bool io_is_fallback_req(struct io_kiocb *req)
1955 return req == (struct io_kiocb *)
1956 ((unsigned long) req->ctx->fallback_req & ~1UL);
1959 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1961 struct io_kiocb *req;
1963 req = ctx->fallback_req;
1964 if (!test_and_set_bit_lock(0, (unsigned long *) &ctx->fallback_req))
1970 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx,
1971 struct io_submit_state *state)
1973 if (!state->free_reqs) {
1974 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1978 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1979 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1982 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1983 * retry single alloc to be on the safe side.
1985 if (unlikely(ret <= 0)) {
1986 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1987 if (!state->reqs[0])
1991 state->free_reqs = ret;
1995 return state->reqs[state->free_reqs];
1997 return io_get_fallback_req(ctx);
2000 static inline void io_put_file(struct io_kiocb *req, struct file *file,
2007 static void io_dismantle_req(struct io_kiocb *req)
2011 if (req->async_data)
2012 kfree(req->async_data);
2014 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
2015 if (req->fixed_file_refs)
2016 percpu_ref_put(req->fixed_file_refs);
2017 io_req_clean_work(req);
2020 static void __io_free_req(struct io_kiocb *req)
2022 struct io_uring_task *tctx = req->task->io_uring;
2023 struct io_ring_ctx *ctx = req->ctx;
2025 io_dismantle_req(req);
2027 percpu_counter_dec(&tctx->inflight);
2028 if (atomic_read(&tctx->in_idle))
2029 wake_up(&tctx->wait);
2030 put_task_struct(req->task);
2032 if (likely(!io_is_fallback_req(req)))
2033 kmem_cache_free(req_cachep, req);
2035 clear_bit_unlock(0, (unsigned long *) &ctx->fallback_req);
2036 percpu_ref_put(&ctx->refs);
2039 static inline void io_remove_next_linked(struct io_kiocb *req)
2041 struct io_kiocb *nxt = req->link;
2043 req->link = nxt->link;
2047 static void io_kill_linked_timeout(struct io_kiocb *req)
2049 struct io_ring_ctx *ctx = req->ctx;
2050 struct io_kiocb *link;
2051 bool cancelled = false;
2052 unsigned long flags;
2054 spin_lock_irqsave(&ctx->completion_lock, flags);
2058 * Can happen if a linked timeout fired and link had been like
2059 * req -> link t-out -> link t-out [-> ...]
2061 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
2062 struct io_timeout_data *io = link->async_data;
2065 io_remove_next_linked(req);
2066 link->timeout.head = NULL;
2067 ret = hrtimer_try_to_cancel(&io->timer);
2069 io_cqring_fill_event(link, -ECANCELED);
2070 io_commit_cqring(ctx);
2074 req->flags &= ~REQ_F_LINK_TIMEOUT;
2075 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2078 io_cqring_ev_posted(ctx);
2084 static void io_fail_links(struct io_kiocb *req)
2086 struct io_kiocb *link, *nxt;
2087 struct io_ring_ctx *ctx = req->ctx;
2088 unsigned long flags;
2090 spin_lock_irqsave(&ctx->completion_lock, flags);
2098 trace_io_uring_fail_link(req, link);
2099 io_cqring_fill_event(link, -ECANCELED);
2102 * It's ok to free under spinlock as they're not linked anymore,
2103 * but avoid REQ_F_WORK_INITIALIZED because it may deadlock on
2106 if (link->flags & REQ_F_WORK_INITIALIZED)
2107 io_put_req_deferred(link, 2);
2109 io_double_put_req(link);
2112 io_commit_cqring(ctx);
2113 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2115 io_cqring_ev_posted(ctx);
2118 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
2120 if (req->flags & REQ_F_LINK_TIMEOUT)
2121 io_kill_linked_timeout(req);
2124 * If LINK is set, we have dependent requests in this chain. If we
2125 * didn't fail this request, queue the first one up, moving any other
2126 * dependencies to the next request. In case of failure, fail the rest
2129 if (likely(!(req->flags & REQ_F_FAIL_LINK))) {
2130 struct io_kiocb *nxt = req->link;
2139 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2141 if (likely(!(req->link) && !(req->flags & REQ_F_LINK_TIMEOUT)))
2143 return __io_req_find_next(req);
2146 static int io_req_task_work_add(struct io_kiocb *req)
2148 struct task_struct *tsk = req->task;
2149 struct io_ring_ctx *ctx = req->ctx;
2150 enum task_work_notify_mode notify;
2153 if (tsk->flags & PF_EXITING)
2157 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2158 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2159 * processing task_work. There's no reliable way to tell if TWA_RESUME
2163 if (!(ctx->flags & IORING_SETUP_SQPOLL))
2164 notify = TWA_SIGNAL;
2166 ret = task_work_add(tsk, &req->task_work, notify);
2168 wake_up_process(tsk);
2173 static void __io_req_task_cancel(struct io_kiocb *req, int error)
2175 struct io_ring_ctx *ctx = req->ctx;
2177 spin_lock_irq(&ctx->completion_lock);
2178 io_cqring_fill_event(req, error);
2179 io_commit_cqring(ctx);
2180 spin_unlock_irq(&ctx->completion_lock);
2182 io_cqring_ev_posted(ctx);
2183 req_set_fail_links(req);
2184 io_double_put_req(req);
2187 static void io_req_task_cancel(struct callback_head *cb)
2189 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2190 struct io_ring_ctx *ctx = req->ctx;
2192 __io_req_task_cancel(req, -ECANCELED);
2193 percpu_ref_put(&ctx->refs);
2196 static void __io_req_task_submit(struct io_kiocb *req)
2198 struct io_ring_ctx *ctx = req->ctx;
2200 mutex_lock(&ctx->uring_lock);
2201 if (!ctx->sqo_dead &&
2202 !__io_sq_thread_acquire_mm(ctx) &&
2203 !__io_sq_thread_acquire_files(ctx))
2204 __io_queue_sqe(req, NULL);
2206 __io_req_task_cancel(req, -EFAULT);
2207 mutex_unlock(&ctx->uring_lock);
2209 if (ctx->flags & IORING_SETUP_SQPOLL)
2210 io_sq_thread_drop_mm_files();
2213 static void io_req_task_submit(struct callback_head *cb)
2215 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2216 struct io_ring_ctx *ctx = req->ctx;
2218 __io_req_task_submit(req);
2219 percpu_ref_put(&ctx->refs);
2222 static void io_req_task_queue(struct io_kiocb *req)
2226 init_task_work(&req->task_work, io_req_task_submit);
2227 percpu_ref_get(&req->ctx->refs);
2229 ret = io_req_task_work_add(req);
2230 if (unlikely(ret)) {
2231 struct task_struct *tsk;
2233 init_task_work(&req->task_work, io_req_task_cancel);
2234 tsk = io_wq_get_task(req->ctx->io_wq);
2235 task_work_add(tsk, &req->task_work, TWA_NONE);
2236 wake_up_process(tsk);
2240 static inline void io_queue_next(struct io_kiocb *req)
2242 struct io_kiocb *nxt = io_req_find_next(req);
2245 io_req_task_queue(nxt);
2248 static void io_free_req(struct io_kiocb *req)
2255 void *reqs[IO_IOPOLL_BATCH];
2258 struct task_struct *task;
2262 static inline void io_init_req_batch(struct req_batch *rb)
2269 static void __io_req_free_batch_flush(struct io_ring_ctx *ctx,
2270 struct req_batch *rb)
2272 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
2273 percpu_ref_put_many(&ctx->refs, rb->to_free);
2277 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2278 struct req_batch *rb)
2281 __io_req_free_batch_flush(ctx, rb);
2283 struct io_uring_task *tctx = rb->task->io_uring;
2285 percpu_counter_sub(&tctx->inflight, rb->task_refs);
2286 if (atomic_read(&tctx->in_idle))
2287 wake_up(&tctx->wait);
2288 put_task_struct_many(rb->task, rb->task_refs);
2293 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req)
2295 if (unlikely(io_is_fallback_req(req))) {
2301 if (req->task != rb->task) {
2303 struct io_uring_task *tctx = rb->task->io_uring;
2305 percpu_counter_sub(&tctx->inflight, rb->task_refs);
2306 if (atomic_read(&tctx->in_idle))
2307 wake_up(&tctx->wait);
2308 put_task_struct_many(rb->task, rb->task_refs);
2310 rb->task = req->task;
2315 io_dismantle_req(req);
2316 rb->reqs[rb->to_free++] = req;
2317 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
2318 __io_req_free_batch_flush(req->ctx, rb);
2322 * Drop reference to request, return next in chain (if there is one) if this
2323 * was the last reference to this request.
2325 static struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2327 struct io_kiocb *nxt = NULL;
2329 if (refcount_dec_and_test(&req->refs)) {
2330 nxt = io_req_find_next(req);
2336 static void io_put_req(struct io_kiocb *req)
2338 if (refcount_dec_and_test(&req->refs))
2342 static void io_put_req_deferred_cb(struct callback_head *cb)
2344 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2349 static void io_free_req_deferred(struct io_kiocb *req)
2353 init_task_work(&req->task_work, io_put_req_deferred_cb);
2354 ret = io_req_task_work_add(req);
2355 if (unlikely(ret)) {
2356 struct task_struct *tsk;
2358 tsk = io_wq_get_task(req->ctx->io_wq);
2359 task_work_add(tsk, &req->task_work, TWA_NONE);
2360 wake_up_process(tsk);
2364 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2366 if (refcount_sub_and_test(refs, &req->refs))
2367 io_free_req_deferred(req);
2370 static struct io_wq_work *io_steal_work(struct io_kiocb *req)
2372 struct io_kiocb *nxt;
2375 * A ref is owned by io-wq in which context we're. So, if that's the
2376 * last one, it's safe to steal next work. False negatives are Ok,
2377 * it just will be re-punted async in io_put_work()
2379 if (refcount_read(&req->refs) != 1)
2382 nxt = io_req_find_next(req);
2383 return nxt ? &nxt->work : NULL;
2386 static void io_double_put_req(struct io_kiocb *req)
2388 /* drop both submit and complete references */
2389 if (refcount_sub_and_test(2, &req->refs))
2393 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2395 /* See comment at the top of this file */
2397 return __io_cqring_events(ctx);
2400 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2402 struct io_rings *rings = ctx->rings;
2404 /* make sure SQ entry isn't read before tail */
2405 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2408 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2410 unsigned int cflags;
2412 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2413 cflags |= IORING_CQE_F_BUFFER;
2414 req->flags &= ~REQ_F_BUFFER_SELECTED;
2419 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2421 struct io_buffer *kbuf;
2423 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2424 return io_put_kbuf(req, kbuf);
2427 static inline bool io_run_task_work(void)
2430 * Not safe to run on exiting task, and the task_work handling will
2431 * not add work to such a task.
2433 if (unlikely(current->flags & PF_EXITING))
2435 if (current->task_works) {
2436 __set_current_state(TASK_RUNNING);
2444 static void io_iopoll_queue(struct list_head *again)
2446 struct io_kiocb *req;
2449 req = list_first_entry(again, struct io_kiocb, inflight_entry);
2450 list_del(&req->inflight_entry);
2451 __io_complete_rw(req, -EAGAIN, 0, NULL);
2452 } while (!list_empty(again));
2456 * Find and free completed poll iocbs
2458 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2459 struct list_head *done)
2461 struct req_batch rb;
2462 struct io_kiocb *req;
2465 /* order with ->result store in io_complete_rw_iopoll() */
2468 io_init_req_batch(&rb);
2469 while (!list_empty(done)) {
2472 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2473 if (READ_ONCE(req->result) == -EAGAIN) {
2475 req->iopoll_completed = 0;
2476 list_move_tail(&req->inflight_entry, &again);
2479 list_del(&req->inflight_entry);
2481 if (req->flags & REQ_F_BUFFER_SELECTED)
2482 cflags = io_put_rw_kbuf(req);
2484 __io_cqring_fill_event(req, req->result, cflags);
2487 if (refcount_dec_and_test(&req->refs))
2488 io_req_free_batch(&rb, req);
2491 io_commit_cqring(ctx);
2492 io_cqring_ev_posted_iopoll(ctx);
2493 io_req_free_batch_finish(ctx, &rb);
2495 if (!list_empty(&again))
2496 io_iopoll_queue(&again);
2499 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2502 struct io_kiocb *req, *tmp;
2508 * Only spin for completions if we don't have multiple devices hanging
2509 * off our complete list, and we're under the requested amount.
2511 spin = !ctx->poll_multi_file && *nr_events < min;
2514 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2515 struct kiocb *kiocb = &req->rw.kiocb;
2518 * Move completed and retryable entries to our local lists.
2519 * If we find a request that requires polling, break out
2520 * and complete those lists first, if we have entries there.
2522 if (READ_ONCE(req->iopoll_completed)) {
2523 list_move_tail(&req->inflight_entry, &done);
2526 if (!list_empty(&done))
2529 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2533 /* iopoll may have completed current req */
2534 if (READ_ONCE(req->iopoll_completed))
2535 list_move_tail(&req->inflight_entry, &done);
2542 if (!list_empty(&done))
2543 io_iopoll_complete(ctx, nr_events, &done);
2549 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2550 * non-spinning poll check - we'll still enter the driver poll loop, but only
2551 * as a non-spinning completion check.
2553 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2556 while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2559 ret = io_do_iopoll(ctx, nr_events, min);
2562 if (*nr_events >= min)
2570 * We can't just wait for polled events to come to us, we have to actively
2571 * find and complete them.
2573 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2575 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2578 mutex_lock(&ctx->uring_lock);
2579 while (!list_empty(&ctx->iopoll_list)) {
2580 unsigned int nr_events = 0;
2582 io_do_iopoll(ctx, &nr_events, 0);
2584 /* let it sleep and repeat later if can't complete a request */
2588 * Ensure we allow local-to-the-cpu processing to take place,
2589 * in this case we need to ensure that we reap all events.
2590 * Also let task_work, etc. to progress by releasing the mutex
2592 if (need_resched()) {
2593 mutex_unlock(&ctx->uring_lock);
2595 mutex_lock(&ctx->uring_lock);
2598 mutex_unlock(&ctx->uring_lock);
2601 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2603 unsigned int nr_events = 0;
2604 int iters = 0, ret = 0;
2607 * We disallow the app entering submit/complete with polling, but we
2608 * still need to lock the ring to prevent racing with polled issue
2609 * that got punted to a workqueue.
2611 mutex_lock(&ctx->uring_lock);
2614 * Don't enter poll loop if we already have events pending.
2615 * If we do, we can potentially be spinning for commands that
2616 * already triggered a CQE (eg in error).
2618 if (test_bit(0, &ctx->cq_check_overflow))
2619 __io_cqring_overflow_flush(ctx, false, NULL, NULL);
2620 if (io_cqring_events(ctx))
2624 * If a submit got punted to a workqueue, we can have the
2625 * application entering polling for a command before it gets
2626 * issued. That app will hold the uring_lock for the duration
2627 * of the poll right here, so we need to take a breather every
2628 * now and then to ensure that the issue has a chance to add
2629 * the poll to the issued list. Otherwise we can spin here
2630 * forever, while the workqueue is stuck trying to acquire the
2633 if (!(++iters & 7)) {
2634 mutex_unlock(&ctx->uring_lock);
2636 mutex_lock(&ctx->uring_lock);
2639 ret = io_iopoll_getevents(ctx, &nr_events, min);
2643 } while (min && !nr_events && !need_resched());
2645 mutex_unlock(&ctx->uring_lock);
2649 static void kiocb_end_write(struct io_kiocb *req)
2652 * Tell lockdep we inherited freeze protection from submission
2655 if (req->flags & REQ_F_ISREG) {
2656 struct inode *inode = file_inode(req->file);
2658 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2660 file_end_write(req->file);
2663 static void io_complete_rw_common(struct kiocb *kiocb, long res,
2664 struct io_comp_state *cs)
2666 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2669 if (kiocb->ki_flags & IOCB_WRITE)
2670 kiocb_end_write(req);
2672 if (res != req->result)
2673 req_set_fail_links(req);
2674 if (req->flags & REQ_F_BUFFER_SELECTED)
2675 cflags = io_put_rw_kbuf(req);
2676 __io_req_complete(req, res, cflags, cs);
2680 static bool io_resubmit_prep(struct io_kiocb *req, int error)
2682 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2683 ssize_t ret = -ECANCELED;
2684 struct iov_iter iter;
2692 switch (req->opcode) {
2693 case IORING_OP_READV:
2694 case IORING_OP_READ_FIXED:
2695 case IORING_OP_READ:
2698 case IORING_OP_WRITEV:
2699 case IORING_OP_WRITE_FIXED:
2700 case IORING_OP_WRITE:
2704 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2709 if (!req->async_data) {
2710 ret = io_import_iovec(rw, req, &iovec, &iter, false);
2713 ret = io_setup_async_rw(req, iovec, inline_vecs, &iter, false);
2721 req_set_fail_links(req);
2726 static bool io_rw_reissue(struct io_kiocb *req, long res)
2729 umode_t mode = file_inode(req->file)->i_mode;
2732 if (!S_ISBLK(mode) && !S_ISREG(mode))
2734 if ((res != -EAGAIN && res != -EOPNOTSUPP) || io_wq_current_is_worker())
2737 lockdep_assert_held(&req->ctx->uring_lock);
2739 ret = io_sq_thread_acquire_mm_files(req->ctx, req);
2741 if (io_resubmit_prep(req, ret)) {
2742 refcount_inc(&req->refs);
2743 io_queue_async_work(req);
2751 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2752 struct io_comp_state *cs)
2754 if (!io_rw_reissue(req, res))
2755 io_complete_rw_common(&req->rw.kiocb, res, cs);
2758 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2760 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2762 __io_complete_rw(req, res, res2, NULL);
2765 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2767 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2769 if (kiocb->ki_flags & IOCB_WRITE)
2770 kiocb_end_write(req);
2772 if (res != -EAGAIN && res != req->result)
2773 req_set_fail_links(req);
2775 WRITE_ONCE(req->result, res);
2776 /* order with io_poll_complete() checking ->result */
2778 WRITE_ONCE(req->iopoll_completed, 1);
2782 * After the iocb has been issued, it's safe to be found on the poll list.
2783 * Adding the kiocb to the list AFTER submission ensures that we don't
2784 * find it from a io_iopoll_getevents() thread before the issuer is done
2785 * accessing the kiocb cookie.
2787 static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
2789 struct io_ring_ctx *ctx = req->ctx;
2792 * Track whether we have multiple files in our lists. This will impact
2793 * how we do polling eventually, not spinning if we're on potentially
2794 * different devices.
2796 if (list_empty(&ctx->iopoll_list)) {
2797 ctx->poll_multi_file = false;
2798 } else if (!ctx->poll_multi_file) {
2799 struct io_kiocb *list_req;
2801 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2803 if (list_req->file != req->file)
2804 ctx->poll_multi_file = true;
2808 * For fast devices, IO may have already completed. If it has, add
2809 * it to the front so we find it first.
2811 if (READ_ONCE(req->iopoll_completed))
2812 list_add(&req->inflight_entry, &ctx->iopoll_list);
2814 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2817 * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
2818 * task context or in io worker task context. If current task context is
2819 * sq thread, we don't need to check whether should wake up sq thread.
2821 if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
2822 wq_has_sleeper(&ctx->sq_data->wait))
2823 wake_up(&ctx->sq_data->wait);
2826 static inline void __io_state_file_put(struct io_submit_state *state)
2828 fput_many(state->file, state->file_refs);
2829 state->file_refs = 0;
2832 static inline void io_state_file_put(struct io_submit_state *state)
2834 if (state->file_refs)
2835 __io_state_file_put(state);
2839 * Get as many references to a file as we have IOs left in this submission,
2840 * assuming most submissions are for one file, or at least that each file
2841 * has more than one submission.
2843 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2848 if (state->file_refs) {
2849 if (state->fd == fd) {
2853 __io_state_file_put(state);
2855 state->file = fget_many(fd, state->ios_left);
2856 if (unlikely(!state->file))
2860 state->file_refs = state->ios_left - 1;
2864 static bool io_bdev_nowait(struct block_device *bdev)
2866 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2870 * If we tracked the file through the SCM inflight mechanism, we could support
2871 * any file. For now, just ensure that anything potentially problematic is done
2874 static bool io_file_supports_async(struct file *file, int rw)
2876 umode_t mode = file_inode(file)->i_mode;
2878 if (S_ISBLK(mode)) {
2879 if (IS_ENABLED(CONFIG_BLOCK) &&
2880 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2884 if (S_ISCHR(mode) || S_ISSOCK(mode))
2886 if (S_ISREG(mode)) {
2887 if (IS_ENABLED(CONFIG_BLOCK) &&
2888 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2889 file->f_op != &io_uring_fops)
2894 /* any ->read/write should understand O_NONBLOCK */
2895 if (file->f_flags & O_NONBLOCK)
2898 if (!(file->f_mode & FMODE_NOWAIT))
2902 return file->f_op->read_iter != NULL;
2904 return file->f_op->write_iter != NULL;
2907 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2909 struct io_ring_ctx *ctx = req->ctx;
2910 struct kiocb *kiocb = &req->rw.kiocb;
2914 if (S_ISREG(file_inode(req->file)->i_mode))
2915 req->flags |= REQ_F_ISREG;
2917 kiocb->ki_pos = READ_ONCE(sqe->off);
2918 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
2919 req->flags |= REQ_F_CUR_POS;
2920 kiocb->ki_pos = req->file->f_pos;
2922 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2923 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2924 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2928 ioprio = READ_ONCE(sqe->ioprio);
2930 ret = ioprio_check_cap(ioprio);
2934 kiocb->ki_ioprio = ioprio;
2936 kiocb->ki_ioprio = get_current_ioprio();
2938 /* don't allow async punt if RWF_NOWAIT was requested */
2939 if (kiocb->ki_flags & IOCB_NOWAIT)
2940 req->flags |= REQ_F_NOWAIT;
2942 if (ctx->flags & IORING_SETUP_IOPOLL) {
2943 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2944 !kiocb->ki_filp->f_op->iopoll)
2947 kiocb->ki_flags |= IOCB_HIPRI;
2948 kiocb->ki_complete = io_complete_rw_iopoll;
2949 req->iopoll_completed = 0;
2951 if (kiocb->ki_flags & IOCB_HIPRI)
2953 kiocb->ki_complete = io_complete_rw;
2956 req->rw.addr = READ_ONCE(sqe->addr);
2957 req->rw.len = READ_ONCE(sqe->len);
2958 req->buf_index = READ_ONCE(sqe->buf_index);
2962 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2968 case -ERESTARTNOINTR:
2969 case -ERESTARTNOHAND:
2970 case -ERESTART_RESTARTBLOCK:
2972 * We can't just restart the syscall, since previously
2973 * submitted sqes may already be in progress. Just fail this
2979 kiocb->ki_complete(kiocb, ret, 0);
2983 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2984 struct io_comp_state *cs)
2986 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2987 struct io_async_rw *io = req->async_data;
2989 /* add previously done IO, if any */
2990 if (io && io->bytes_done > 0) {
2992 ret = io->bytes_done;
2994 ret += io->bytes_done;
2997 if (req->flags & REQ_F_CUR_POS)
2998 req->file->f_pos = kiocb->ki_pos;
2999 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
3000 __io_complete_rw(req, ret, 0, cs);
3002 io_rw_done(kiocb, ret);
3005 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
3006 struct iov_iter *iter)
3008 struct io_ring_ctx *ctx = req->ctx;
3009 size_t len = req->rw.len;
3010 struct io_mapped_ubuf *imu;
3011 u16 index, buf_index = req->buf_index;
3015 if (unlikely(buf_index >= ctx->nr_user_bufs))
3017 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3018 imu = &ctx->user_bufs[index];
3019 buf_addr = req->rw.addr;
3022 if (buf_addr + len < buf_addr)
3024 /* not inside the mapped region */
3025 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
3029 * May not be a start of buffer, set size appropriately
3030 * and advance us to the beginning.
3032 offset = buf_addr - imu->ubuf;
3033 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3037 * Don't use iov_iter_advance() here, as it's really slow for
3038 * using the latter parts of a big fixed buffer - it iterates
3039 * over each segment manually. We can cheat a bit here, because
3042 * 1) it's a BVEC iter, we set it up
3043 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3044 * first and last bvec
3046 * So just find our index, and adjust the iterator afterwards.
3047 * If the offset is within the first bvec (or the whole first
3048 * bvec, just use iov_iter_advance(). This makes it easier
3049 * since we can just skip the first segment, which may not
3050 * be PAGE_SIZE aligned.
3052 const struct bio_vec *bvec = imu->bvec;
3054 if (offset <= bvec->bv_len) {
3055 iov_iter_advance(iter, offset);
3057 unsigned long seg_skip;
3059 /* skip first vec */
3060 offset -= bvec->bv_len;
3061 seg_skip = 1 + (offset >> PAGE_SHIFT);
3063 iter->bvec = bvec + seg_skip;
3064 iter->nr_segs -= seg_skip;
3065 iter->count -= bvec->bv_len + offset;
3066 iter->iov_offset = offset & ~PAGE_MASK;
3073 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3076 mutex_unlock(&ctx->uring_lock);
3079 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3082 * "Normal" inline submissions always hold the uring_lock, since we
3083 * grab it from the system call. Same is true for the SQPOLL offload.
3084 * The only exception is when we've detached the request and issue it
3085 * from an async worker thread, grab the lock for that case.
3088 mutex_lock(&ctx->uring_lock);
3091 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3092 int bgid, struct io_buffer *kbuf,
3095 struct io_buffer *head;
3097 if (req->flags & REQ_F_BUFFER_SELECTED)
3100 io_ring_submit_lock(req->ctx, needs_lock);
3102 lockdep_assert_held(&req->ctx->uring_lock);
3104 head = idr_find(&req->ctx->io_buffer_idr, bgid);
3106 if (!list_empty(&head->list)) {
3107 kbuf = list_last_entry(&head->list, struct io_buffer,
3109 list_del(&kbuf->list);
3112 idr_remove(&req->ctx->io_buffer_idr, bgid);
3114 if (*len > kbuf->len)
3117 kbuf = ERR_PTR(-ENOBUFS);
3120 io_ring_submit_unlock(req->ctx, needs_lock);
3125 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3128 struct io_buffer *kbuf;
3131 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3132 bgid = req->buf_index;
3133 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3136 req->rw.addr = (u64) (unsigned long) kbuf;
3137 req->flags |= REQ_F_BUFFER_SELECTED;
3138 return u64_to_user_ptr(kbuf->addr);
3141 #ifdef CONFIG_COMPAT
3142 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3145 struct compat_iovec __user *uiov;
3146 compat_ssize_t clen;
3150 uiov = u64_to_user_ptr(req->rw.addr);
3151 if (!access_ok(uiov, sizeof(*uiov)))
3153 if (__get_user(clen, &uiov->iov_len))
3159 buf = io_rw_buffer_select(req, &len, needs_lock);
3161 return PTR_ERR(buf);
3162 iov[0].iov_base = buf;
3163 iov[0].iov_len = (compat_size_t) len;
3168 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3171 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3175 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3178 len = iov[0].iov_len;
3181 buf = io_rw_buffer_select(req, &len, needs_lock);
3183 return PTR_ERR(buf);
3184 iov[0].iov_base = buf;
3185 iov[0].iov_len = len;
3189 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3192 if (req->flags & REQ_F_BUFFER_SELECTED) {
3193 struct io_buffer *kbuf;
3195 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3196 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3197 iov[0].iov_len = kbuf->len;
3200 if (req->rw.len != 1)
3203 #ifdef CONFIG_COMPAT
3204 if (req->ctx->compat)
3205 return io_compat_import(req, iov, needs_lock);
3208 return __io_iov_buffer_select(req, iov, needs_lock);
3211 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
3212 struct iovec **iovec, struct iov_iter *iter,
3215 void __user *buf = u64_to_user_ptr(req->rw.addr);
3216 size_t sqe_len = req->rw.len;
3220 opcode = req->opcode;
3221 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3223 return io_import_fixed(req, rw, iter);
3226 /* buffer index only valid with fixed read/write, or buffer select */
3227 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3230 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3231 if (req->flags & REQ_F_BUFFER_SELECT) {
3232 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3234 return PTR_ERR(buf);
3235 req->rw.len = sqe_len;
3238 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3243 if (req->flags & REQ_F_BUFFER_SELECT) {
3244 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3246 ret = (*iovec)->iov_len;
3247 iov_iter_init(iter, rw, *iovec, 1, ret);
3253 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3257 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3259 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3263 * For files that don't have ->read_iter() and ->write_iter(), handle them
3264 * by looping over ->read() or ->write() manually.
3266 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3268 struct kiocb *kiocb = &req->rw.kiocb;
3269 struct file *file = req->file;
3273 * Don't support polled IO through this interface, and we can't
3274 * support non-blocking either. For the latter, this just causes
3275 * the kiocb to be handled from an async context.
3277 if (kiocb->ki_flags & IOCB_HIPRI)
3279 if (kiocb->ki_flags & IOCB_NOWAIT)
3282 while (iov_iter_count(iter)) {
3286 if (!iov_iter_is_bvec(iter)) {
3287 iovec = iov_iter_iovec(iter);
3289 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3290 iovec.iov_len = req->rw.len;
3294 nr = file->f_op->read(file, iovec.iov_base,
3295 iovec.iov_len, io_kiocb_ppos(kiocb));
3297 nr = file->f_op->write(file, iovec.iov_base,
3298 iovec.iov_len, io_kiocb_ppos(kiocb));
3307 if (nr != iovec.iov_len)
3311 iov_iter_advance(iter, nr);
3317 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3318 const struct iovec *fast_iov, struct iov_iter *iter)
3320 struct io_async_rw *rw = req->async_data;
3322 memcpy(&rw->iter, iter, sizeof(*iter));
3323 rw->free_iovec = iovec;
3325 /* can only be fixed buffers, no need to do anything */
3326 if (iov_iter_is_bvec(iter))
3329 unsigned iov_off = 0;
3331 rw->iter.iov = rw->fast_iov;
3332 if (iter->iov != fast_iov) {
3333 iov_off = iter->iov - fast_iov;
3334 rw->iter.iov += iov_off;
3336 if (rw->fast_iov != fast_iov)
3337 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3338 sizeof(struct iovec) * iter->nr_segs);
3340 req->flags |= REQ_F_NEED_CLEANUP;
3344 static inline int __io_alloc_async_data(struct io_kiocb *req)
3346 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3347 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3348 return req->async_data == NULL;
3351 static int io_alloc_async_data(struct io_kiocb *req)
3353 if (!io_op_defs[req->opcode].needs_async_data)
3356 return __io_alloc_async_data(req);
3359 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3360 const struct iovec *fast_iov,
3361 struct iov_iter *iter, bool force)
3363 if (!force && !io_op_defs[req->opcode].needs_async_data)
3365 if (!req->async_data) {
3366 if (__io_alloc_async_data(req))
3369 io_req_map_rw(req, iovec, fast_iov, iter);
3374 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3376 struct io_async_rw *iorw = req->async_data;
3377 struct iovec *iov = iorw->fast_iov;
3380 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3381 if (unlikely(ret < 0))
3384 iorw->bytes_done = 0;
3385 iorw->free_iovec = iov;
3387 req->flags |= REQ_F_NEED_CLEANUP;
3391 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3395 ret = io_prep_rw(req, sqe);
3399 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3402 /* either don't need iovec imported or already have it */
3403 if (!req->async_data)
3405 return io_rw_prep_async(req, READ);
3409 * This is our waitqueue callback handler, registered through lock_page_async()
3410 * when we initially tried to do the IO with the iocb armed our waitqueue.
3411 * This gets called when the page is unlocked, and we generally expect that to
3412 * happen when the page IO is completed and the page is now uptodate. This will
3413 * queue a task_work based retry of the operation, attempting to copy the data
3414 * again. If the latter fails because the page was NOT uptodate, then we will
3415 * do a thread based blocking retry of the operation. That's the unexpected
3418 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3419 int sync, void *arg)
3421 struct wait_page_queue *wpq;
3422 struct io_kiocb *req = wait->private;
3423 struct wait_page_key *key = arg;
3426 wpq = container_of(wait, struct wait_page_queue, wait);
3428 if (!wake_page_match(wpq, key))
3431 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3432 list_del_init(&wait->entry);
3434 init_task_work(&req->task_work, io_req_task_submit);
3435 percpu_ref_get(&req->ctx->refs);
3437 /* submit ref gets dropped, acquire a new one */
3438 refcount_inc(&req->refs);
3439 ret = io_req_task_work_add(req);
3440 if (unlikely(ret)) {
3441 struct task_struct *tsk;
3443 /* queue just for cancelation */
3444 init_task_work(&req->task_work, io_req_task_cancel);
3445 tsk = io_wq_get_task(req->ctx->io_wq);
3446 task_work_add(tsk, &req->task_work, TWA_NONE);
3447 wake_up_process(tsk);
3453 * This controls whether a given IO request should be armed for async page
3454 * based retry. If we return false here, the request is handed to the async
3455 * worker threads for retry. If we're doing buffered reads on a regular file,
3456 * we prepare a private wait_page_queue entry and retry the operation. This
3457 * will either succeed because the page is now uptodate and unlocked, or it
3458 * will register a callback when the page is unlocked at IO completion. Through
3459 * that callback, io_uring uses task_work to setup a retry of the operation.
3460 * That retry will attempt the buffered read again. The retry will generally
3461 * succeed, or in rare cases where it fails, we then fall back to using the
3462 * async worker threads for a blocking retry.
3464 static bool io_rw_should_retry(struct io_kiocb *req)
3466 struct io_async_rw *rw = req->async_data;
3467 struct wait_page_queue *wait = &rw->wpq;
3468 struct kiocb *kiocb = &req->rw.kiocb;
3470 /* never retry for NOWAIT, we just complete with -EAGAIN */
3471 if (req->flags & REQ_F_NOWAIT)
3474 /* Only for buffered IO */
3475 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3479 * just use poll if we can, and don't attempt if the fs doesn't
3480 * support callback based unlocks
3482 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3485 wait->wait.func = io_async_buf_func;
3486 wait->wait.private = req;
3487 wait->wait.flags = 0;
3488 INIT_LIST_HEAD(&wait->wait.entry);
3489 kiocb->ki_flags |= IOCB_WAITQ;
3490 kiocb->ki_flags &= ~IOCB_NOWAIT;
3491 kiocb->ki_waitq = wait;
3495 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3497 if (req->file->f_op->read_iter)
3498 return call_read_iter(req->file, &req->rw.kiocb, iter);
3499 else if (req->file->f_op->read)
3500 return loop_rw_iter(READ, req, iter);
3505 static int io_read(struct io_kiocb *req, bool force_nonblock,
3506 struct io_comp_state *cs)
3508 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3509 struct kiocb *kiocb = &req->rw.kiocb;
3510 struct iov_iter __iter, *iter = &__iter;
3511 struct io_async_rw *rw = req->async_data;
3512 ssize_t io_size, ret, ret2;
3519 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3523 io_size = iov_iter_count(iter);
3524 req->result = io_size;
3527 /* Ensure we clear previously set non-block flag */
3528 if (!force_nonblock)
3529 kiocb->ki_flags &= ~IOCB_NOWAIT;
3531 kiocb->ki_flags |= IOCB_NOWAIT;
3534 /* If the file doesn't support async, just async punt */
3535 no_async = force_nonblock && !io_file_supports_async(req->file, READ);
3539 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3543 ret = io_iter_do_read(req, iter);
3547 } else if (ret == -EIOCBQUEUED) {
3550 } else if (ret == -EAGAIN) {
3551 /* IOPOLL retry should happen for io-wq threads */
3552 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3554 /* no retry on NONBLOCK marked file */
3555 if (req->file->f_flags & O_NONBLOCK)
3557 /* some cases will consume bytes even on error returns */
3558 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3561 } else if (ret < 0) {
3562 /* make sure -ERESTARTSYS -> -EINTR is done */
3566 /* read it all, or we did blocking attempt. no retry. */
3567 if (!iov_iter_count(iter) || !force_nonblock ||
3568 (req->file->f_flags & O_NONBLOCK) || !(req->flags & REQ_F_ISREG))
3573 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3580 rw = req->async_data;
3581 /* it's copied and will be cleaned with ->io */
3583 /* now use our persistent iterator, if we aren't already */
3586 rw->bytes_done += ret;
3587 /* if we can retry, do so with the callbacks armed */
3588 if (!io_rw_should_retry(req)) {
3589 kiocb->ki_flags &= ~IOCB_WAITQ;
3594 * Now retry read with the IOCB_WAITQ parts set in the iocb. If we
3595 * get -EIOCBQUEUED, then we'll get a notification when the desired
3596 * page gets unlocked. We can also get a partial read here, and if we
3597 * do, then just retry at the new offset.
3599 ret = io_iter_do_read(req, iter);
3600 if (ret == -EIOCBQUEUED) {
3603 } else if (ret > 0 && ret < io_size) {
3604 /* we got some bytes, but not all. retry. */
3608 kiocb_done(kiocb, ret, cs);
3611 /* it's reportedly faster than delegating the null check to kfree() */
3617 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3621 ret = io_prep_rw(req, sqe);
3625 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3628 /* either don't need iovec imported or already have it */
3629 if (!req->async_data)
3631 return io_rw_prep_async(req, WRITE);
3634 static int io_write(struct io_kiocb *req, bool force_nonblock,
3635 struct io_comp_state *cs)
3637 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3638 struct kiocb *kiocb = &req->rw.kiocb;
3639 struct iov_iter __iter, *iter = &__iter;
3640 struct io_async_rw *rw = req->async_data;
3641 ssize_t ret, ret2, io_size;
3647 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3651 io_size = iov_iter_count(iter);
3652 req->result = io_size;
3654 /* Ensure we clear previously set non-block flag */
3655 if (!force_nonblock)
3656 kiocb->ki_flags &= ~IOCB_NOWAIT;
3658 kiocb->ki_flags |= IOCB_NOWAIT;
3660 /* If the file doesn't support async, just async punt */
3661 if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3664 /* file path doesn't support NOWAIT for non-direct_IO */
3665 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3666 (req->flags & REQ_F_ISREG))
3669 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3674 * Open-code file_start_write here to grab freeze protection,
3675 * which will be released by another thread in
3676 * io_complete_rw(). Fool lockdep by telling it the lock got
3677 * released so that it doesn't complain about the held lock when
3678 * we return to userspace.
3680 if (req->flags & REQ_F_ISREG) {
3681 sb_start_write(file_inode(req->file)->i_sb);
3682 __sb_writers_release(file_inode(req->file)->i_sb,
3685 kiocb->ki_flags |= IOCB_WRITE;
3687 if (req->file->f_op->write_iter)
3688 ret2 = call_write_iter(req->file, kiocb, iter);
3689 else if (req->file->f_op->write)
3690 ret2 = loop_rw_iter(WRITE, req, iter);
3695 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3696 * retry them without IOCB_NOWAIT.
3698 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3700 /* no retry on NONBLOCK marked file */
3701 if (ret2 == -EAGAIN && (req->file->f_flags & O_NONBLOCK))
3703 if (!force_nonblock || ret2 != -EAGAIN) {
3704 /* IOPOLL retry should happen for io-wq threads */
3705 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3708 kiocb_done(kiocb, ret2, cs);
3711 /* some cases will consume bytes even on error returns */
3712 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3713 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3718 /* it's reportedly faster than delegating the null check to kfree() */
3724 static int io_renameat_prep(struct io_kiocb *req,
3725 const struct io_uring_sqe *sqe)
3727 struct io_rename *ren = &req->rename;
3728 const char __user *oldf, *newf;
3730 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3733 ren->old_dfd = READ_ONCE(sqe->fd);
3734 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3735 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3736 ren->new_dfd = READ_ONCE(sqe->len);
3737 ren->flags = READ_ONCE(sqe->rename_flags);
3739 ren->oldpath = getname(oldf);
3740 if (IS_ERR(ren->oldpath))
3741 return PTR_ERR(ren->oldpath);
3743 ren->newpath = getname(newf);
3744 if (IS_ERR(ren->newpath)) {
3745 putname(ren->oldpath);
3746 return PTR_ERR(ren->newpath);
3749 req->flags |= REQ_F_NEED_CLEANUP;
3753 static int io_renameat(struct io_kiocb *req, bool force_nonblock)
3755 struct io_rename *ren = &req->rename;
3761 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3762 ren->newpath, ren->flags);
3764 req->flags &= ~REQ_F_NEED_CLEANUP;
3766 req_set_fail_links(req);
3767 io_req_complete(req, ret);
3771 static int io_unlinkat_prep(struct io_kiocb *req,
3772 const struct io_uring_sqe *sqe)
3774 struct io_unlink *un = &req->unlink;
3775 const char __user *fname;
3777 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3780 un->dfd = READ_ONCE(sqe->fd);
3782 un->flags = READ_ONCE(sqe->unlink_flags);
3783 if (un->flags & ~AT_REMOVEDIR)
3786 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3787 un->filename = getname(fname);
3788 if (IS_ERR(un->filename))
3789 return PTR_ERR(un->filename);
3791 req->flags |= REQ_F_NEED_CLEANUP;
3795 static int io_unlinkat(struct io_kiocb *req, bool force_nonblock)
3797 struct io_unlink *un = &req->unlink;
3803 if (un->flags & AT_REMOVEDIR)
3804 ret = do_rmdir(un->dfd, un->filename);
3806 ret = do_unlinkat(un->dfd, un->filename);
3808 req->flags &= ~REQ_F_NEED_CLEANUP;
3810 req_set_fail_links(req);
3811 io_req_complete(req, ret);
3815 static int io_shutdown_prep(struct io_kiocb *req,
3816 const struct io_uring_sqe *sqe)
3818 #if defined(CONFIG_NET)
3819 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3821 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3825 req->shutdown.how = READ_ONCE(sqe->len);
3832 static int io_shutdown(struct io_kiocb *req, bool force_nonblock)
3834 #if defined(CONFIG_NET)
3835 struct socket *sock;
3841 sock = sock_from_file(req->file);
3842 if (unlikely(!sock))
3845 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3847 req_set_fail_links(req);
3848 io_req_complete(req, ret);
3855 static int __io_splice_prep(struct io_kiocb *req,
3856 const struct io_uring_sqe *sqe)
3858 struct io_splice* sp = &req->splice;
3859 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3861 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3865 sp->len = READ_ONCE(sqe->len);
3866 sp->flags = READ_ONCE(sqe->splice_flags);
3868 if (unlikely(sp->flags & ~valid_flags))
3871 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3872 (sp->flags & SPLICE_F_FD_IN_FIXED));
3875 req->flags |= REQ_F_NEED_CLEANUP;
3877 if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3879 * Splice operation will be punted aync, and here need to
3880 * modify io_wq_work.flags, so initialize io_wq_work firstly.
3882 io_req_init_async(req);
3883 req->work.flags |= IO_WQ_WORK_UNBOUND;
3889 static int io_tee_prep(struct io_kiocb *req,
3890 const struct io_uring_sqe *sqe)
3892 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3894 return __io_splice_prep(req, sqe);
3897 static int io_tee(struct io_kiocb *req, bool force_nonblock)
3899 struct io_splice *sp = &req->splice;
3900 struct file *in = sp->file_in;
3901 struct file *out = sp->file_out;
3902 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3908 ret = do_tee(in, out, sp->len, flags);
3910 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3911 req->flags &= ~REQ_F_NEED_CLEANUP;
3914 req_set_fail_links(req);
3915 io_req_complete(req, ret);
3919 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3921 struct io_splice* sp = &req->splice;
3923 sp->off_in = READ_ONCE(sqe->splice_off_in);
3924 sp->off_out = READ_ONCE(sqe->off);
3925 return __io_splice_prep(req, sqe);
3928 static int io_splice(struct io_kiocb *req, bool force_nonblock)
3930 struct io_splice *sp = &req->splice;
3931 struct file *in = sp->file_in;
3932 struct file *out = sp->file_out;
3933 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3934 loff_t *poff_in, *poff_out;
3940 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3941 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3944 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3946 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3947 req->flags &= ~REQ_F_NEED_CLEANUP;
3950 req_set_fail_links(req);
3951 io_req_complete(req, ret);
3956 * IORING_OP_NOP just posts a completion event, nothing else.
3958 static int io_nop(struct io_kiocb *req, struct io_comp_state *cs)
3960 struct io_ring_ctx *ctx = req->ctx;
3962 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3965 __io_req_complete(req, 0, 0, cs);
3969 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3971 struct io_ring_ctx *ctx = req->ctx;
3976 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3978 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3981 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3982 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3985 req->sync.off = READ_ONCE(sqe->off);
3986 req->sync.len = READ_ONCE(sqe->len);
3990 static int io_fsync(struct io_kiocb *req, bool force_nonblock)
3992 loff_t end = req->sync.off + req->sync.len;
3995 /* fsync always requires a blocking context */
3999 ret = vfs_fsync_range(req->file, req->sync.off,
4000 end > 0 ? end : LLONG_MAX,
4001 req->sync.flags & IORING_FSYNC_DATASYNC);
4003 req_set_fail_links(req);
4004 io_req_complete(req, ret);
4008 static int io_fallocate_prep(struct io_kiocb *req,
4009 const struct io_uring_sqe *sqe)
4011 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
4013 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4016 req->sync.off = READ_ONCE(sqe->off);
4017 req->sync.len = READ_ONCE(sqe->addr);
4018 req->sync.mode = READ_ONCE(sqe->len);
4022 static int io_fallocate(struct io_kiocb *req, bool force_nonblock)
4026 /* fallocate always requiring blocking context */
4029 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4032 req_set_fail_links(req);
4033 io_req_complete(req, ret);
4037 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4039 const char __user *fname;
4042 if (unlikely(sqe->ioprio || sqe->buf_index))
4044 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4047 /* open.how should be already initialised */
4048 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4049 req->open.how.flags |= O_LARGEFILE;
4051 req->open.dfd = READ_ONCE(sqe->fd);
4052 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4053 req->open.filename = getname(fname);
4054 if (IS_ERR(req->open.filename)) {
4055 ret = PTR_ERR(req->open.filename);
4056 req->open.filename = NULL;
4059 req->open.nofile = rlimit(RLIMIT_NOFILE);
4060 req->open.ignore_nonblock = false;
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;
4104 if (force_nonblock && !req->open.ignore_nonblock)
4107 ret = build_open_flags(&req->open.how, &op);
4111 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4115 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4118 ret = PTR_ERR(file);
4120 * A work-around to ensure that /proc/self works that way
4121 * that it should - if we get -EOPNOTSUPP back, then assume
4122 * that proc_self_get_link() failed us because we're in async
4123 * context. We should be safe to retry this from the task
4124 * itself with force_nonblock == false set, as it should not
4125 * block on lookup. Would be nice to know this upfront and
4126 * avoid the async dance, but doesn't seem feasible.
4128 if (ret == -EOPNOTSUPP && io_wq_current_is_worker()) {
4129 req->open.ignore_nonblock = true;
4130 refcount_inc(&req->refs);
4131 io_req_task_queue(req);
4135 fsnotify_open(file);
4136 fd_install(ret, file);
4139 putname(req->open.filename);
4140 req->flags &= ~REQ_F_NEED_CLEANUP;
4142 req_set_fail_links(req);
4143 io_req_complete(req, ret);
4147 static int io_openat(struct io_kiocb *req, bool force_nonblock)
4149 return io_openat2(req, force_nonblock);
4152 static int io_remove_buffers_prep(struct io_kiocb *req,
4153 const struct io_uring_sqe *sqe)
4155 struct io_provide_buf *p = &req->pbuf;
4158 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
4161 tmp = READ_ONCE(sqe->fd);
4162 if (!tmp || tmp > USHRT_MAX)
4165 memset(p, 0, sizeof(*p));
4167 p->bgid = READ_ONCE(sqe->buf_group);
4171 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4172 int bgid, unsigned nbufs)
4176 /* shouldn't happen */
4180 /* the head kbuf is the list itself */
4181 while (!list_empty(&buf->list)) {
4182 struct io_buffer *nxt;
4184 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4185 list_del(&nxt->list);
4192 idr_remove(&ctx->io_buffer_idr, bgid);
4197 static int io_remove_buffers(struct io_kiocb *req, bool force_nonblock,
4198 struct io_comp_state *cs)
4200 struct io_provide_buf *p = &req->pbuf;
4201 struct io_ring_ctx *ctx = req->ctx;
4202 struct io_buffer *head;
4205 io_ring_submit_lock(ctx, !force_nonblock);
4207 lockdep_assert_held(&ctx->uring_lock);
4210 head = idr_find(&ctx->io_buffer_idr, p->bgid);
4212 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4214 req_set_fail_links(req);
4216 /* need to hold the lock to complete IOPOLL requests */
4217 if (ctx->flags & IORING_SETUP_IOPOLL) {
4218 __io_req_complete(req, ret, 0, cs);
4219 io_ring_submit_unlock(ctx, !force_nonblock);
4221 io_ring_submit_unlock(ctx, !force_nonblock);
4222 __io_req_complete(req, ret, 0, cs);
4227 static int io_provide_buffers_prep(struct io_kiocb *req,
4228 const struct io_uring_sqe *sqe)
4230 struct io_provide_buf *p = &req->pbuf;
4233 if (sqe->ioprio || sqe->rw_flags)
4236 tmp = READ_ONCE(sqe->fd);
4237 if (!tmp || tmp > USHRT_MAX)
4240 p->addr = READ_ONCE(sqe->addr);
4241 p->len = READ_ONCE(sqe->len);
4243 if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
4246 p->bgid = READ_ONCE(sqe->buf_group);
4247 tmp = READ_ONCE(sqe->off);
4248 if (tmp > USHRT_MAX)
4254 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4256 struct io_buffer *buf;
4257 u64 addr = pbuf->addr;
4258 int i, bid = pbuf->bid;
4260 for (i = 0; i < pbuf->nbufs; i++) {
4261 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
4266 buf->len = pbuf->len;
4271 INIT_LIST_HEAD(&buf->list);
4274 list_add_tail(&buf->list, &(*head)->list);
4278 return i ? i : -ENOMEM;
4281 static int io_provide_buffers(struct io_kiocb *req, bool force_nonblock,
4282 struct io_comp_state *cs)
4284 struct io_provide_buf *p = &req->pbuf;
4285 struct io_ring_ctx *ctx = req->ctx;
4286 struct io_buffer *head, *list;
4289 io_ring_submit_lock(ctx, !force_nonblock);
4291 lockdep_assert_held(&ctx->uring_lock);
4293 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
4295 ret = io_add_buffers(p, &head);
4300 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
4303 __io_remove_buffers(ctx, head, p->bgid, -1U);
4309 req_set_fail_links(req);
4311 /* need to hold the lock to complete IOPOLL requests */
4312 if (ctx->flags & IORING_SETUP_IOPOLL) {
4313 __io_req_complete(req, ret, 0, cs);
4314 io_ring_submit_unlock(ctx, !force_nonblock);
4316 io_ring_submit_unlock(ctx, !force_nonblock);
4317 __io_req_complete(req, ret, 0, cs);
4322 static int io_epoll_ctl_prep(struct io_kiocb *req,
4323 const struct io_uring_sqe *sqe)
4325 #if defined(CONFIG_EPOLL)
4326 if (sqe->ioprio || sqe->buf_index)
4328 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4331 req->epoll.epfd = READ_ONCE(sqe->fd);
4332 req->epoll.op = READ_ONCE(sqe->len);
4333 req->epoll.fd = READ_ONCE(sqe->off);
4335 if (ep_op_has_event(req->epoll.op)) {
4336 struct epoll_event __user *ev;
4338 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4339 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4349 static int io_epoll_ctl(struct io_kiocb *req, bool force_nonblock,
4350 struct io_comp_state *cs)
4352 #if defined(CONFIG_EPOLL)
4353 struct io_epoll *ie = &req->epoll;
4356 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4357 if (force_nonblock && ret == -EAGAIN)
4361 req_set_fail_links(req);
4362 __io_req_complete(req, ret, 0, cs);
4369 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4371 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4372 if (sqe->ioprio || sqe->buf_index || sqe->off)
4374 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4377 req->madvise.addr = READ_ONCE(sqe->addr);
4378 req->madvise.len = READ_ONCE(sqe->len);
4379 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4386 static int io_madvise(struct io_kiocb *req, bool force_nonblock)
4388 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4389 struct io_madvise *ma = &req->madvise;
4395 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4397 req_set_fail_links(req);
4398 io_req_complete(req, ret);
4405 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4407 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4409 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4412 req->fadvise.offset = READ_ONCE(sqe->off);
4413 req->fadvise.len = READ_ONCE(sqe->len);
4414 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4418 static int io_fadvise(struct io_kiocb *req, bool force_nonblock)
4420 struct io_fadvise *fa = &req->fadvise;
4423 if (force_nonblock) {
4424 switch (fa->advice) {
4425 case POSIX_FADV_NORMAL:
4426 case POSIX_FADV_RANDOM:
4427 case POSIX_FADV_SEQUENTIAL:
4434 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4436 req_set_fail_links(req);
4437 io_req_complete(req, ret);
4441 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4443 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4445 if (sqe->ioprio || sqe->buf_index)
4447 if (req->flags & REQ_F_FIXED_FILE)
4450 req->statx.dfd = READ_ONCE(sqe->fd);
4451 req->statx.mask = READ_ONCE(sqe->len);
4452 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4453 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4454 req->statx.flags = READ_ONCE(sqe->statx_flags);
4459 static int io_statx(struct io_kiocb *req, bool force_nonblock)
4461 struct io_statx *ctx = &req->statx;
4464 if (force_nonblock) {
4465 /* only need file table for an actual valid fd */
4466 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
4467 req->flags |= REQ_F_NO_FILE_TABLE;
4471 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4475 req_set_fail_links(req);
4476 io_req_complete(req, ret);
4480 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4483 * If we queue this for async, it must not be cancellable. That would
4484 * leave the 'file' in an undeterminate state, and here need to modify
4485 * io_wq_work.flags, so initialize io_wq_work firstly.
4487 io_req_init_async(req);
4489 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4491 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4492 sqe->rw_flags || sqe->buf_index)
4494 if (req->flags & REQ_F_FIXED_FILE)
4497 req->close.fd = READ_ONCE(sqe->fd);
4498 if ((req->file && req->file->f_op == &io_uring_fops))
4501 req->close.put_file = NULL;
4505 static int io_close(struct io_kiocb *req, bool force_nonblock,
4506 struct io_comp_state *cs)
4508 struct io_close *close = &req->close;
4511 /* might be already done during nonblock submission */
4512 if (!close->put_file) {
4513 ret = close_fd_get_file(close->fd, &close->put_file);
4515 return (ret == -ENOENT) ? -EBADF : ret;
4518 /* if the file has a flush method, be safe and punt to async */
4519 if (close->put_file->f_op->flush && force_nonblock) {
4520 /* not safe to cancel at this point */
4521 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
4522 /* was never set, but play safe */
4523 req->flags &= ~REQ_F_NOWAIT;
4524 /* avoid grabbing files - we don't need the files */
4525 req->flags |= REQ_F_NO_FILE_TABLE;
4529 /* No ->flush() or already async, safely close from here */
4530 ret = filp_close(close->put_file, req->work.identity->files);
4532 req_set_fail_links(req);
4533 fput(close->put_file);
4534 close->put_file = NULL;
4535 __io_req_complete(req, ret, 0, cs);
4539 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4541 struct io_ring_ctx *ctx = req->ctx;
4546 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4548 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4551 req->sync.off = READ_ONCE(sqe->off);
4552 req->sync.len = READ_ONCE(sqe->len);
4553 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4557 static int io_sync_file_range(struct io_kiocb *req, bool force_nonblock)
4561 /* sync_file_range always requires a blocking context */
4565 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4568 req_set_fail_links(req);
4569 io_req_complete(req, ret);
4573 #if defined(CONFIG_NET)
4574 static int io_setup_async_msg(struct io_kiocb *req,
4575 struct io_async_msghdr *kmsg)
4577 struct io_async_msghdr *async_msg = req->async_data;
4581 if (io_alloc_async_data(req)) {
4582 if (kmsg->iov != kmsg->fast_iov)
4586 async_msg = req->async_data;
4587 req->flags |= REQ_F_NEED_CLEANUP;
4588 memcpy(async_msg, kmsg, sizeof(*kmsg));
4592 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4593 struct io_async_msghdr *iomsg)
4595 iomsg->iov = iomsg->fast_iov;
4596 iomsg->msg.msg_name = &iomsg->addr;
4597 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4598 req->sr_msg.msg_flags, &iomsg->iov);
4601 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4603 struct io_async_msghdr *async_msg = req->async_data;
4604 struct io_sr_msg *sr = &req->sr_msg;
4607 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4610 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4611 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4612 sr->len = READ_ONCE(sqe->len);
4614 #ifdef CONFIG_COMPAT
4615 if (req->ctx->compat)
4616 sr->msg_flags |= MSG_CMSG_COMPAT;
4619 if (!async_msg || !io_op_defs[req->opcode].needs_async_data)
4621 ret = io_sendmsg_copy_hdr(req, async_msg);
4623 req->flags |= REQ_F_NEED_CLEANUP;
4627 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
4628 struct io_comp_state *cs)
4630 struct io_async_msghdr iomsg, *kmsg;
4631 struct socket *sock;
4635 sock = sock_from_file(req->file);
4636 if (unlikely(!sock))
4639 if (req->async_data) {
4640 kmsg = req->async_data;
4641 kmsg->msg.msg_name = &kmsg->addr;
4642 /* if iov is set, it's allocated already */
4644 kmsg->iov = kmsg->fast_iov;
4645 kmsg->msg.msg_iter.iov = kmsg->iov;
4647 ret = io_sendmsg_copy_hdr(req, &iomsg);
4653 flags = req->sr_msg.msg_flags;
4654 if (flags & MSG_DONTWAIT)
4655 req->flags |= REQ_F_NOWAIT;
4656 else if (force_nonblock)
4657 flags |= MSG_DONTWAIT;
4659 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4660 if (force_nonblock && ret == -EAGAIN)
4661 return io_setup_async_msg(req, kmsg);
4662 if (ret == -ERESTARTSYS)
4665 if (kmsg->iov != kmsg->fast_iov)
4667 req->flags &= ~REQ_F_NEED_CLEANUP;
4669 req_set_fail_links(req);
4670 __io_req_complete(req, ret, 0, cs);
4674 static int io_send(struct io_kiocb *req, bool force_nonblock,
4675 struct io_comp_state *cs)
4677 struct io_sr_msg *sr = &req->sr_msg;
4680 struct socket *sock;
4684 sock = sock_from_file(req->file);
4685 if (unlikely(!sock))
4688 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4692 msg.msg_name = NULL;
4693 msg.msg_control = NULL;
4694 msg.msg_controllen = 0;
4695 msg.msg_namelen = 0;
4697 flags = req->sr_msg.msg_flags;
4698 if (flags & MSG_DONTWAIT)
4699 req->flags |= REQ_F_NOWAIT;
4700 else if (force_nonblock)
4701 flags |= MSG_DONTWAIT;
4703 msg.msg_flags = flags;
4704 ret = sock_sendmsg(sock, &msg);
4705 if (force_nonblock && ret == -EAGAIN)
4707 if (ret == -ERESTARTSYS)
4711 req_set_fail_links(req);
4712 __io_req_complete(req, ret, 0, cs);
4716 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4717 struct io_async_msghdr *iomsg)
4719 struct io_sr_msg *sr = &req->sr_msg;
4720 struct iovec __user *uiov;
4724 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4725 &iomsg->uaddr, &uiov, &iov_len);
4729 if (req->flags & REQ_F_BUFFER_SELECT) {
4732 if (copy_from_user(iomsg->iov, uiov, sizeof(*uiov)))
4734 sr->len = iomsg->iov[0].iov_len;
4735 iov_iter_init(&iomsg->msg.msg_iter, READ, iomsg->iov, 1,
4739 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4740 &iomsg->iov, &iomsg->msg.msg_iter,
4749 #ifdef CONFIG_COMPAT
4750 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4751 struct io_async_msghdr *iomsg)
4753 struct compat_msghdr __user *msg_compat;
4754 struct io_sr_msg *sr = &req->sr_msg;
4755 struct compat_iovec __user *uiov;
4760 msg_compat = (struct compat_msghdr __user *) sr->umsg;
4761 ret = __get_compat_msghdr(&iomsg->msg, msg_compat, &iomsg->uaddr,
4766 uiov = compat_ptr(ptr);
4767 if (req->flags & REQ_F_BUFFER_SELECT) {
4768 compat_ssize_t clen;
4772 if (!access_ok(uiov, sizeof(*uiov)))
4774 if (__get_user(clen, &uiov->iov_len))
4779 iomsg->iov[0].iov_len = clen;
4782 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4783 UIO_FASTIOV, &iomsg->iov,
4784 &iomsg->msg.msg_iter, true);
4793 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4794 struct io_async_msghdr *iomsg)
4796 iomsg->msg.msg_name = &iomsg->addr;
4797 iomsg->iov = iomsg->fast_iov;
4799 #ifdef CONFIG_COMPAT
4800 if (req->ctx->compat)
4801 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4804 return __io_recvmsg_copy_hdr(req, iomsg);
4807 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4810 struct io_sr_msg *sr = &req->sr_msg;
4811 struct io_buffer *kbuf;
4813 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4818 req->flags |= REQ_F_BUFFER_SELECTED;
4822 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4824 return io_put_kbuf(req, req->sr_msg.kbuf);
4827 static int io_recvmsg_prep(struct io_kiocb *req,
4828 const struct io_uring_sqe *sqe)
4830 struct io_async_msghdr *async_msg = req->async_data;
4831 struct io_sr_msg *sr = &req->sr_msg;
4834 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4837 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4838 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4839 sr->len = READ_ONCE(sqe->len);
4840 sr->bgid = READ_ONCE(sqe->buf_group);
4842 #ifdef CONFIG_COMPAT
4843 if (req->ctx->compat)
4844 sr->msg_flags |= MSG_CMSG_COMPAT;
4847 if (!async_msg || !io_op_defs[req->opcode].needs_async_data)
4849 ret = io_recvmsg_copy_hdr(req, async_msg);
4851 req->flags |= REQ_F_NEED_CLEANUP;
4855 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
4856 struct io_comp_state *cs)
4858 struct io_async_msghdr iomsg, *kmsg;
4859 struct socket *sock;
4860 struct io_buffer *kbuf;
4862 int ret, cflags = 0;
4864 sock = sock_from_file(req->file);
4865 if (unlikely(!sock))
4868 if (req->async_data) {
4869 kmsg = req->async_data;
4870 kmsg->msg.msg_name = &kmsg->addr;
4871 /* if iov is set, it's allocated already */
4873 kmsg->iov = kmsg->fast_iov;
4874 kmsg->msg.msg_iter.iov = kmsg->iov;
4876 ret = io_recvmsg_copy_hdr(req, &iomsg);
4882 if (req->flags & REQ_F_BUFFER_SELECT) {
4883 kbuf = io_recv_buffer_select(req, !force_nonblock);
4885 return PTR_ERR(kbuf);
4886 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4887 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->iov,
4888 1, req->sr_msg.len);
4891 flags = req->sr_msg.msg_flags;
4892 if (flags & MSG_DONTWAIT)
4893 req->flags |= REQ_F_NOWAIT;
4894 else if (force_nonblock)
4895 flags |= MSG_DONTWAIT;
4897 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4898 kmsg->uaddr, flags);
4899 if (force_nonblock && ret == -EAGAIN)
4900 return io_setup_async_msg(req, kmsg);
4901 if (ret == -ERESTARTSYS)
4904 if (req->flags & REQ_F_BUFFER_SELECTED)
4905 cflags = io_put_recv_kbuf(req);
4906 if (kmsg->iov != kmsg->fast_iov)
4908 req->flags &= ~REQ_F_NEED_CLEANUP;
4910 req_set_fail_links(req);
4911 __io_req_complete(req, ret, cflags, cs);
4915 static int io_recv(struct io_kiocb *req, bool force_nonblock,
4916 struct io_comp_state *cs)
4918 struct io_buffer *kbuf;
4919 struct io_sr_msg *sr = &req->sr_msg;
4921 void __user *buf = sr->buf;
4922 struct socket *sock;
4925 int ret, cflags = 0;
4927 sock = sock_from_file(req->file);
4928 if (unlikely(!sock))
4931 if (req->flags & REQ_F_BUFFER_SELECT) {
4932 kbuf = io_recv_buffer_select(req, !force_nonblock);
4934 return PTR_ERR(kbuf);
4935 buf = u64_to_user_ptr(kbuf->addr);
4938 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4942 msg.msg_name = NULL;
4943 msg.msg_control = NULL;
4944 msg.msg_controllen = 0;
4945 msg.msg_namelen = 0;
4946 msg.msg_iocb = NULL;
4949 flags = req->sr_msg.msg_flags;
4950 if (flags & MSG_DONTWAIT)
4951 req->flags |= REQ_F_NOWAIT;
4952 else if (force_nonblock)
4953 flags |= MSG_DONTWAIT;
4955 ret = sock_recvmsg(sock, &msg, flags);
4956 if (force_nonblock && ret == -EAGAIN)
4958 if (ret == -ERESTARTSYS)
4961 if (req->flags & REQ_F_BUFFER_SELECTED)
4962 cflags = io_put_recv_kbuf(req);
4964 req_set_fail_links(req);
4965 __io_req_complete(req, ret, cflags, cs);
4969 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4971 struct io_accept *accept = &req->accept;
4973 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4975 if (sqe->ioprio || sqe->len || sqe->buf_index)
4978 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4979 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4980 accept->flags = READ_ONCE(sqe->accept_flags);
4981 accept->nofile = rlimit(RLIMIT_NOFILE);
4985 static int io_accept(struct io_kiocb *req, bool force_nonblock,
4986 struct io_comp_state *cs)
4988 struct io_accept *accept = &req->accept;
4989 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4992 if (req->file->f_flags & O_NONBLOCK)
4993 req->flags |= REQ_F_NOWAIT;
4995 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4996 accept->addr_len, accept->flags,
4998 if (ret == -EAGAIN && force_nonblock)
5001 if (ret == -ERESTARTSYS)
5003 req_set_fail_links(req);
5005 __io_req_complete(req, ret, 0, cs);
5009 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5011 struct io_connect *conn = &req->connect;
5012 struct io_async_connect *io = req->async_data;
5014 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5016 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
5019 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5020 conn->addr_len = READ_ONCE(sqe->addr2);
5025 return move_addr_to_kernel(conn->addr, conn->addr_len,
5029 static int io_connect(struct io_kiocb *req, bool force_nonblock,
5030 struct io_comp_state *cs)
5032 struct io_async_connect __io, *io;
5033 unsigned file_flags;
5036 if (req->async_data) {
5037 io = req->async_data;
5039 ret = move_addr_to_kernel(req->connect.addr,
5040 req->connect.addr_len,
5047 file_flags = force_nonblock ? O_NONBLOCK : 0;
5049 ret = __sys_connect_file(req->file, &io->address,
5050 req->connect.addr_len, file_flags);
5051 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5052 if (req->async_data)
5054 if (io_alloc_async_data(req)) {
5058 io = req->async_data;
5059 memcpy(req->async_data, &__io, sizeof(__io));
5062 if (ret == -ERESTARTSYS)
5066 req_set_fail_links(req);
5067 __io_req_complete(req, ret, 0, cs);
5070 #else /* !CONFIG_NET */
5071 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5076 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
5077 struct io_comp_state *cs)
5082 static int io_send(struct io_kiocb *req, bool force_nonblock,
5083 struct io_comp_state *cs)
5088 static int io_recvmsg_prep(struct io_kiocb *req,
5089 const struct io_uring_sqe *sqe)
5094 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
5095 struct io_comp_state *cs)
5100 static int io_recv(struct io_kiocb *req, bool force_nonblock,
5101 struct io_comp_state *cs)
5106 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5111 static int io_accept(struct io_kiocb *req, bool force_nonblock,
5112 struct io_comp_state *cs)
5117 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5122 static int io_connect(struct io_kiocb *req, bool force_nonblock,
5123 struct io_comp_state *cs)
5127 #endif /* CONFIG_NET */
5129 struct io_poll_table {
5130 struct poll_table_struct pt;
5131 struct io_kiocb *req;
5135 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
5136 __poll_t mask, task_work_func_t func)
5140 /* for instances that support it check for an event match first: */
5141 if (mask && !(mask & poll->events))
5144 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
5146 list_del_init(&poll->wait.entry);
5149 init_task_work(&req->task_work, func);
5150 percpu_ref_get(&req->ctx->refs);
5153 * If this fails, then the task is exiting. When a task exits, the
5154 * work gets canceled, so just cancel this request as well instead
5155 * of executing it. We can't safely execute it anyway, as we may not
5156 * have the needed state needed for it anyway.
5158 ret = io_req_task_work_add(req);
5159 if (unlikely(ret)) {
5160 struct task_struct *tsk;
5162 WRITE_ONCE(poll->canceled, true);
5163 tsk = io_wq_get_task(req->ctx->io_wq);
5164 task_work_add(tsk, &req->task_work, TWA_NONE);
5165 wake_up_process(tsk);
5170 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
5171 __acquires(&req->ctx->completion_lock)
5173 struct io_ring_ctx *ctx = req->ctx;
5175 if (!req->result && !READ_ONCE(poll->canceled)) {
5176 struct poll_table_struct pt = { ._key = poll->events };
5178 req->result = vfs_poll(req->file, &pt) & poll->events;
5181 spin_lock_irq(&ctx->completion_lock);
5182 if (!req->result && !READ_ONCE(poll->canceled)) {
5183 add_wait_queue(poll->head, &poll->wait);
5190 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5192 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5193 if (req->opcode == IORING_OP_POLL_ADD)
5194 return req->async_data;
5195 return req->apoll->double_poll;
5198 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5200 if (req->opcode == IORING_OP_POLL_ADD)
5202 return &req->apoll->poll;
5205 static void io_poll_remove_double(struct io_kiocb *req)
5207 struct io_poll_iocb *poll = io_poll_get_double(req);
5209 lockdep_assert_held(&req->ctx->completion_lock);
5211 if (poll && poll->head) {
5212 struct wait_queue_head *head = poll->head;
5214 spin_lock(&head->lock);
5215 list_del_init(&poll->wait.entry);
5216 if (poll->wait.private)
5217 refcount_dec(&req->refs);
5219 spin_unlock(&head->lock);
5223 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
5225 struct io_ring_ctx *ctx = req->ctx;
5227 io_poll_remove_double(req);
5228 req->poll.done = true;
5229 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
5230 io_commit_cqring(ctx);
5233 static void io_poll_task_func(struct callback_head *cb)
5235 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5236 struct io_ring_ctx *ctx = req->ctx;
5237 struct io_kiocb *nxt;
5239 if (io_poll_rewait(req, &req->poll)) {
5240 spin_unlock_irq(&ctx->completion_lock);
5242 hash_del(&req->hash_node);
5243 io_poll_complete(req, req->result, 0);
5244 spin_unlock_irq(&ctx->completion_lock);
5246 nxt = io_put_req_find_next(req);
5247 io_cqring_ev_posted(ctx);
5249 __io_req_task_submit(nxt);
5252 percpu_ref_put(&ctx->refs);
5255 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
5256 int sync, void *key)
5258 struct io_kiocb *req = wait->private;
5259 struct io_poll_iocb *poll = io_poll_get_single(req);
5260 __poll_t mask = key_to_poll(key);
5262 /* for instances that support it check for an event match first: */
5263 if (mask && !(mask & poll->events))
5266 list_del_init(&wait->entry);
5268 if (poll && poll->head) {
5271 spin_lock(&poll->head->lock);
5272 done = list_empty(&poll->wait.entry);
5274 list_del_init(&poll->wait.entry);
5275 /* make sure double remove sees this as being gone */
5276 wait->private = NULL;
5277 spin_unlock(&poll->head->lock);
5279 /* use wait func handler, so it matches the rq type */
5280 poll->wait.func(&poll->wait, mode, sync, key);
5283 refcount_dec(&req->refs);
5287 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5288 wait_queue_func_t wake_func)
5292 poll->canceled = false;
5293 poll->events = events;
5294 INIT_LIST_HEAD(&poll->wait.entry);
5295 init_waitqueue_func_entry(&poll->wait, wake_func);
5298 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5299 struct wait_queue_head *head,
5300 struct io_poll_iocb **poll_ptr)
5302 struct io_kiocb *req = pt->req;
5305 * If poll->head is already set, it's because the file being polled
5306 * uses multiple waitqueues for poll handling (eg one for read, one
5307 * for write). Setup a separate io_poll_iocb if this happens.
5309 if (unlikely(poll->head)) {
5310 struct io_poll_iocb *poll_one = poll;
5312 /* already have a 2nd entry, fail a third attempt */
5314 pt->error = -EINVAL;
5317 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5319 pt->error = -ENOMEM;
5322 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5323 refcount_inc(&req->refs);
5324 poll->wait.private = req;
5331 if (poll->events & EPOLLEXCLUSIVE)
5332 add_wait_queue_exclusive(head, &poll->wait);
5334 add_wait_queue(head, &poll->wait);
5337 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5338 struct poll_table_struct *p)
5340 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5341 struct async_poll *apoll = pt->req->apoll;
5343 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5346 static void io_async_task_func(struct callback_head *cb)
5348 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5349 struct async_poll *apoll = req->apoll;
5350 struct io_ring_ctx *ctx = req->ctx;
5352 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
5354 if (io_poll_rewait(req, &apoll->poll)) {
5355 spin_unlock_irq(&ctx->completion_lock);
5356 percpu_ref_put(&ctx->refs);
5360 /* If req is still hashed, it cannot have been canceled. Don't check. */
5361 if (hash_hashed(&req->hash_node))
5362 hash_del(&req->hash_node);
5364 io_poll_remove_double(req);
5365 spin_unlock_irq(&ctx->completion_lock);
5367 if (!READ_ONCE(apoll->poll.canceled))
5368 __io_req_task_submit(req);
5370 __io_req_task_cancel(req, -ECANCELED);
5372 percpu_ref_put(&ctx->refs);
5373 kfree(apoll->double_poll);
5377 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5380 struct io_kiocb *req = wait->private;
5381 struct io_poll_iocb *poll = &req->apoll->poll;
5383 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5386 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5389 static void io_poll_req_insert(struct io_kiocb *req)
5391 struct io_ring_ctx *ctx = req->ctx;
5392 struct hlist_head *list;
5394 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5395 hlist_add_head(&req->hash_node, list);
5398 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5399 struct io_poll_iocb *poll,
5400 struct io_poll_table *ipt, __poll_t mask,
5401 wait_queue_func_t wake_func)
5402 __acquires(&ctx->completion_lock)
5404 struct io_ring_ctx *ctx = req->ctx;
5405 bool cancel = false;
5407 INIT_HLIST_NODE(&req->hash_node);
5408 io_init_poll_iocb(poll, mask, wake_func);
5409 poll->file = req->file;
5410 poll->wait.private = req;
5412 ipt->pt._key = mask;
5414 ipt->error = -EINVAL;
5416 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5418 spin_lock_irq(&ctx->completion_lock);
5419 if (likely(poll->head)) {
5420 spin_lock(&poll->head->lock);
5421 if (unlikely(list_empty(&poll->wait.entry))) {
5427 if (mask || ipt->error)
5428 list_del_init(&poll->wait.entry);
5430 WRITE_ONCE(poll->canceled, true);
5431 else if (!poll->done) /* actually waiting for an event */
5432 io_poll_req_insert(req);
5433 spin_unlock(&poll->head->lock);
5439 static bool io_arm_poll_handler(struct io_kiocb *req)
5441 const struct io_op_def *def = &io_op_defs[req->opcode];
5442 struct io_ring_ctx *ctx = req->ctx;
5443 struct async_poll *apoll;
5444 struct io_poll_table ipt;
5448 if (!req->file || !file_can_poll(req->file))
5450 if (req->flags & REQ_F_POLLED)
5454 else if (def->pollout)
5458 /* if we can't nonblock try, then no point in arming a poll handler */
5459 if (!io_file_supports_async(req->file, rw))
5462 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5463 if (unlikely(!apoll))
5465 apoll->double_poll = NULL;
5467 req->flags |= REQ_F_POLLED;
5472 mask |= POLLIN | POLLRDNORM;
5474 mask |= POLLOUT | POLLWRNORM;
5476 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5477 if ((req->opcode == IORING_OP_RECVMSG) &&
5478 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5481 mask |= POLLERR | POLLPRI;
5483 ipt.pt._qproc = io_async_queue_proc;
5485 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5487 if (ret || ipt.error) {
5488 io_poll_remove_double(req);
5489 spin_unlock_irq(&ctx->completion_lock);
5490 kfree(apoll->double_poll);
5494 spin_unlock_irq(&ctx->completion_lock);
5495 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5496 apoll->poll.events);
5500 static bool __io_poll_remove_one(struct io_kiocb *req,
5501 struct io_poll_iocb *poll)
5503 bool do_complete = false;
5505 spin_lock(&poll->head->lock);
5506 WRITE_ONCE(poll->canceled, true);
5507 if (!list_empty(&poll->wait.entry)) {
5508 list_del_init(&poll->wait.entry);
5511 spin_unlock(&poll->head->lock);
5512 hash_del(&req->hash_node);
5516 static bool io_poll_remove_one(struct io_kiocb *req)
5520 io_poll_remove_double(req);
5522 if (req->opcode == IORING_OP_POLL_ADD) {
5523 do_complete = __io_poll_remove_one(req, &req->poll);
5525 struct async_poll *apoll = req->apoll;
5527 /* non-poll requests have submit ref still */
5528 do_complete = __io_poll_remove_one(req, &apoll->poll);
5531 kfree(apoll->double_poll);
5537 io_cqring_fill_event(req, -ECANCELED);
5538 io_commit_cqring(req->ctx);
5539 req_set_fail_links(req);
5540 io_put_req_deferred(req, 1);
5547 * Returns true if we found and killed one or more poll requests
5549 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5550 struct files_struct *files)
5552 struct hlist_node *tmp;
5553 struct io_kiocb *req;
5556 spin_lock_irq(&ctx->completion_lock);
5557 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5558 struct hlist_head *list;
5560 list = &ctx->cancel_hash[i];
5561 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5562 if (io_match_task(req, tsk, files))
5563 posted += io_poll_remove_one(req);
5566 spin_unlock_irq(&ctx->completion_lock);
5569 io_cqring_ev_posted(ctx);
5574 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5576 struct hlist_head *list;
5577 struct io_kiocb *req;
5579 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5580 hlist_for_each_entry(req, list, hash_node) {
5581 if (sqe_addr != req->user_data)
5583 if (io_poll_remove_one(req))
5591 static int io_poll_remove_prep(struct io_kiocb *req,
5592 const struct io_uring_sqe *sqe)
5594 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5596 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5600 req->poll_remove.addr = READ_ONCE(sqe->addr);
5605 * Find a running poll command that matches one specified in sqe->addr,
5606 * and remove it if found.
5608 static int io_poll_remove(struct io_kiocb *req)
5610 struct io_ring_ctx *ctx = req->ctx;
5613 spin_lock_irq(&ctx->completion_lock);
5614 ret = io_poll_cancel(ctx, req->poll_remove.addr);
5615 spin_unlock_irq(&ctx->completion_lock);
5618 req_set_fail_links(req);
5619 io_req_complete(req, ret);
5623 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5626 struct io_kiocb *req = wait->private;
5627 struct io_poll_iocb *poll = &req->poll;
5629 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5632 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5633 struct poll_table_struct *p)
5635 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5637 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5640 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5642 struct io_poll_iocb *poll = &req->poll;
5645 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5647 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
5650 events = READ_ONCE(sqe->poll32_events);
5652 events = swahw32(events);
5654 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
5655 (events & EPOLLEXCLUSIVE);
5659 static int io_poll_add(struct io_kiocb *req)
5661 struct io_poll_iocb *poll = &req->poll;
5662 struct io_ring_ctx *ctx = req->ctx;
5663 struct io_poll_table ipt;
5666 ipt.pt._qproc = io_poll_queue_proc;
5668 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5671 if (mask) { /* no async, we'd stolen it */
5673 io_poll_complete(req, mask, 0);
5675 spin_unlock_irq(&ctx->completion_lock);
5678 io_cqring_ev_posted(ctx);
5684 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5686 struct io_timeout_data *data = container_of(timer,
5687 struct io_timeout_data, timer);
5688 struct io_kiocb *req = data->req;
5689 struct io_ring_ctx *ctx = req->ctx;
5690 unsigned long flags;
5692 spin_lock_irqsave(&ctx->completion_lock, flags);
5693 list_del_init(&req->timeout.list);
5694 atomic_set(&req->ctx->cq_timeouts,
5695 atomic_read(&req->ctx->cq_timeouts) + 1);
5697 io_cqring_fill_event(req, -ETIME);
5698 io_commit_cqring(ctx);
5699 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5701 io_cqring_ev_posted(ctx);
5702 req_set_fail_links(req);
5704 return HRTIMER_NORESTART;
5707 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5710 struct io_timeout_data *io;
5711 struct io_kiocb *req;
5714 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5715 if (user_data == req->user_data) {
5722 return ERR_PTR(ret);
5724 io = req->async_data;
5725 ret = hrtimer_try_to_cancel(&io->timer);
5727 return ERR_PTR(-EALREADY);
5728 list_del_init(&req->timeout.list);
5732 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5734 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5737 return PTR_ERR(req);
5739 req_set_fail_links(req);
5740 io_cqring_fill_event(req, -ECANCELED);
5741 io_put_req_deferred(req, 1);
5745 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5746 struct timespec64 *ts, enum hrtimer_mode mode)
5748 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5749 struct io_timeout_data *data;
5752 return PTR_ERR(req);
5754 req->timeout.off = 0; /* noseq */
5755 data = req->async_data;
5756 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5757 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5758 data->timer.function = io_timeout_fn;
5759 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5763 static int io_timeout_remove_prep(struct io_kiocb *req,
5764 const struct io_uring_sqe *sqe)
5766 struct io_timeout_rem *tr = &req->timeout_rem;
5768 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5770 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5772 if (sqe->ioprio || sqe->buf_index || sqe->len)
5775 tr->addr = READ_ONCE(sqe->addr);
5776 tr->flags = READ_ONCE(sqe->timeout_flags);
5777 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5778 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5780 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5782 } else if (tr->flags) {
5783 /* timeout removal doesn't support flags */
5791 * Remove or update an existing timeout command
5793 static int io_timeout_remove(struct io_kiocb *req)
5795 struct io_timeout_rem *tr = &req->timeout_rem;
5796 struct io_ring_ctx *ctx = req->ctx;
5799 spin_lock_irq(&ctx->completion_lock);
5800 if (req->timeout_rem.flags & IORING_TIMEOUT_UPDATE) {
5801 enum hrtimer_mode mode = (tr->flags & IORING_TIMEOUT_ABS)
5802 ? HRTIMER_MODE_ABS : HRTIMER_MODE_REL;
5804 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
5806 ret = io_timeout_cancel(ctx, tr->addr);
5809 io_cqring_fill_event(req, ret);
5810 io_commit_cqring(ctx);
5811 spin_unlock_irq(&ctx->completion_lock);
5812 io_cqring_ev_posted(ctx);
5814 req_set_fail_links(req);
5819 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5820 bool is_timeout_link)
5822 struct io_timeout_data *data;
5824 u32 off = READ_ONCE(sqe->off);
5826 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5828 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5830 if (off && is_timeout_link)
5832 flags = READ_ONCE(sqe->timeout_flags);
5833 if (flags & ~IORING_TIMEOUT_ABS)
5836 req->timeout.off = off;
5838 if (!req->async_data && io_alloc_async_data(req))
5841 data = req->async_data;
5844 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5847 if (flags & IORING_TIMEOUT_ABS)
5848 data->mode = HRTIMER_MODE_ABS;
5850 data->mode = HRTIMER_MODE_REL;
5852 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5856 static int io_timeout(struct io_kiocb *req)
5858 struct io_ring_ctx *ctx = req->ctx;
5859 struct io_timeout_data *data = req->async_data;
5860 struct list_head *entry;
5861 u32 tail, off = req->timeout.off;
5863 spin_lock_irq(&ctx->completion_lock);
5866 * sqe->off holds how many events that need to occur for this
5867 * timeout event to be satisfied. If it isn't set, then this is
5868 * a pure timeout request, sequence isn't used.
5870 if (io_is_timeout_noseq(req)) {
5871 entry = ctx->timeout_list.prev;
5875 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5876 req->timeout.target_seq = tail + off;
5878 /* Update the last seq here in case io_flush_timeouts() hasn't.
5879 * This is safe because ->completion_lock is held, and submissions
5880 * and completions are never mixed in the same ->completion_lock section.
5882 ctx->cq_last_tm_flush = tail;
5885 * Insertion sort, ensuring the first entry in the list is always
5886 * the one we need first.
5888 list_for_each_prev(entry, &ctx->timeout_list) {
5889 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5892 if (io_is_timeout_noseq(nxt))
5894 /* nxt.seq is behind @tail, otherwise would've been completed */
5895 if (off >= nxt->timeout.target_seq - tail)
5899 list_add(&req->timeout.list, entry);
5900 data->timer.function = io_timeout_fn;
5901 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5902 spin_unlock_irq(&ctx->completion_lock);
5906 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5908 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5910 return req->user_data == (unsigned long) data;
5913 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
5915 enum io_wq_cancel cancel_ret;
5918 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr, false);
5919 switch (cancel_ret) {
5920 case IO_WQ_CANCEL_OK:
5923 case IO_WQ_CANCEL_RUNNING:
5926 case IO_WQ_CANCEL_NOTFOUND:
5934 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5935 struct io_kiocb *req, __u64 sqe_addr,
5938 unsigned long flags;
5941 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
5942 if (ret != -ENOENT) {
5943 spin_lock_irqsave(&ctx->completion_lock, flags);
5947 spin_lock_irqsave(&ctx->completion_lock, flags);
5948 ret = io_timeout_cancel(ctx, sqe_addr);
5951 ret = io_poll_cancel(ctx, sqe_addr);
5955 io_cqring_fill_event(req, ret);
5956 io_commit_cqring(ctx);
5957 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5958 io_cqring_ev_posted(ctx);
5961 req_set_fail_links(req);
5965 static int io_async_cancel_prep(struct io_kiocb *req,
5966 const struct io_uring_sqe *sqe)
5968 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5970 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5972 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5975 req->cancel.addr = READ_ONCE(sqe->addr);
5979 static int io_async_cancel(struct io_kiocb *req)
5981 struct io_ring_ctx *ctx = req->ctx;
5983 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
5987 static int io_files_update_prep(struct io_kiocb *req,
5988 const struct io_uring_sqe *sqe)
5990 if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
5992 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5994 if (sqe->ioprio || sqe->rw_flags)
5997 req->files_update.offset = READ_ONCE(sqe->off);
5998 req->files_update.nr_args = READ_ONCE(sqe->len);
5999 if (!req->files_update.nr_args)
6001 req->files_update.arg = READ_ONCE(sqe->addr);
6005 static int io_files_update(struct io_kiocb *req, bool force_nonblock,
6006 struct io_comp_state *cs)
6008 struct io_ring_ctx *ctx = req->ctx;
6009 struct io_uring_files_update up;
6015 up.offset = req->files_update.offset;
6016 up.fds = req->files_update.arg;
6018 mutex_lock(&ctx->uring_lock);
6019 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
6020 mutex_unlock(&ctx->uring_lock);
6023 req_set_fail_links(req);
6024 __io_req_complete(req, ret, 0, cs);
6028 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6030 switch (req->opcode) {
6033 case IORING_OP_READV:
6034 case IORING_OP_READ_FIXED:
6035 case IORING_OP_READ:
6036 return io_read_prep(req, sqe);
6037 case IORING_OP_WRITEV:
6038 case IORING_OP_WRITE_FIXED:
6039 case IORING_OP_WRITE:
6040 return io_write_prep(req, sqe);
6041 case IORING_OP_POLL_ADD:
6042 return io_poll_add_prep(req, sqe);
6043 case IORING_OP_POLL_REMOVE:
6044 return io_poll_remove_prep(req, sqe);
6045 case IORING_OP_FSYNC:
6046 return io_prep_fsync(req, sqe);
6047 case IORING_OP_SYNC_FILE_RANGE:
6048 return io_prep_sfr(req, sqe);
6049 case IORING_OP_SENDMSG:
6050 case IORING_OP_SEND:
6051 return io_sendmsg_prep(req, sqe);
6052 case IORING_OP_RECVMSG:
6053 case IORING_OP_RECV:
6054 return io_recvmsg_prep(req, sqe);
6055 case IORING_OP_CONNECT:
6056 return io_connect_prep(req, sqe);
6057 case IORING_OP_TIMEOUT:
6058 return io_timeout_prep(req, sqe, false);
6059 case IORING_OP_TIMEOUT_REMOVE:
6060 return io_timeout_remove_prep(req, sqe);
6061 case IORING_OP_ASYNC_CANCEL:
6062 return io_async_cancel_prep(req, sqe);
6063 case IORING_OP_LINK_TIMEOUT:
6064 return io_timeout_prep(req, sqe, true);
6065 case IORING_OP_ACCEPT:
6066 return io_accept_prep(req, sqe);
6067 case IORING_OP_FALLOCATE:
6068 return io_fallocate_prep(req, sqe);
6069 case IORING_OP_OPENAT:
6070 return io_openat_prep(req, sqe);
6071 case IORING_OP_CLOSE:
6072 return io_close_prep(req, sqe);
6073 case IORING_OP_FILES_UPDATE:
6074 return io_files_update_prep(req, sqe);
6075 case IORING_OP_STATX:
6076 return io_statx_prep(req, sqe);
6077 case IORING_OP_FADVISE:
6078 return io_fadvise_prep(req, sqe);
6079 case IORING_OP_MADVISE:
6080 return io_madvise_prep(req, sqe);
6081 case IORING_OP_OPENAT2:
6082 return io_openat2_prep(req, sqe);
6083 case IORING_OP_EPOLL_CTL:
6084 return io_epoll_ctl_prep(req, sqe);
6085 case IORING_OP_SPLICE:
6086 return io_splice_prep(req, sqe);
6087 case IORING_OP_PROVIDE_BUFFERS:
6088 return io_provide_buffers_prep(req, sqe);
6089 case IORING_OP_REMOVE_BUFFERS:
6090 return io_remove_buffers_prep(req, sqe);
6092 return io_tee_prep(req, sqe);
6093 case IORING_OP_SHUTDOWN:
6094 return io_shutdown_prep(req, sqe);
6095 case IORING_OP_RENAMEAT:
6096 return io_renameat_prep(req, sqe);
6097 case IORING_OP_UNLINKAT:
6098 return io_unlinkat_prep(req, sqe);
6101 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6106 static int io_req_defer_prep(struct io_kiocb *req,
6107 const struct io_uring_sqe *sqe)
6111 if (io_alloc_async_data(req))
6113 return io_req_prep(req, sqe);
6116 static u32 io_get_sequence(struct io_kiocb *req)
6118 struct io_kiocb *pos;
6119 struct io_ring_ctx *ctx = req->ctx;
6120 u32 total_submitted, nr_reqs = 0;
6122 io_for_each_link(pos, req)
6125 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
6126 return total_submitted - nr_reqs;
6129 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6131 struct io_ring_ctx *ctx = req->ctx;
6132 struct io_defer_entry *de;
6136 /* Still need defer if there is pending req in defer list. */
6137 if (likely(list_empty_careful(&ctx->defer_list) &&
6138 !(req->flags & REQ_F_IO_DRAIN)))
6141 seq = io_get_sequence(req);
6142 /* Still a chance to pass the sequence check */
6143 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6146 if (!req->async_data) {
6147 ret = io_req_defer_prep(req, sqe);
6151 io_prep_async_link(req);
6152 de = kmalloc(sizeof(*de), GFP_KERNEL);
6156 spin_lock_irq(&ctx->completion_lock);
6157 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6158 spin_unlock_irq(&ctx->completion_lock);
6160 io_queue_async_work(req);
6161 return -EIOCBQUEUED;
6164 trace_io_uring_defer(ctx, req, req->user_data);
6167 list_add_tail(&de->list, &ctx->defer_list);
6168 spin_unlock_irq(&ctx->completion_lock);
6169 return -EIOCBQUEUED;
6172 static void io_req_drop_files(struct io_kiocb *req)
6174 struct io_ring_ctx *ctx = req->ctx;
6175 struct io_uring_task *tctx = req->task->io_uring;
6176 unsigned long flags;
6178 if (req->work.flags & IO_WQ_WORK_FILES) {
6179 put_files_struct(req->work.identity->files);
6180 put_nsproxy(req->work.identity->nsproxy);
6182 spin_lock_irqsave(&ctx->inflight_lock, flags);
6183 list_del(&req->inflight_entry);
6184 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
6185 req->flags &= ~REQ_F_INFLIGHT;
6186 req->work.flags &= ~IO_WQ_WORK_FILES;
6187 if (atomic_read(&tctx->in_idle))
6188 wake_up(&tctx->wait);
6191 static void __io_clean_op(struct io_kiocb *req)
6193 if (req->flags & REQ_F_BUFFER_SELECTED) {
6194 switch (req->opcode) {
6195 case IORING_OP_READV:
6196 case IORING_OP_READ_FIXED:
6197 case IORING_OP_READ:
6198 kfree((void *)(unsigned long)req->rw.addr);
6200 case IORING_OP_RECVMSG:
6201 case IORING_OP_RECV:
6202 kfree(req->sr_msg.kbuf);
6205 req->flags &= ~REQ_F_BUFFER_SELECTED;
6208 if (req->flags & REQ_F_NEED_CLEANUP) {
6209 switch (req->opcode) {
6210 case IORING_OP_READV:
6211 case IORING_OP_READ_FIXED:
6212 case IORING_OP_READ:
6213 case IORING_OP_WRITEV:
6214 case IORING_OP_WRITE_FIXED:
6215 case IORING_OP_WRITE: {
6216 struct io_async_rw *io = req->async_data;
6218 kfree(io->free_iovec);
6221 case IORING_OP_RECVMSG:
6222 case IORING_OP_SENDMSG: {
6223 struct io_async_msghdr *io = req->async_data;
6224 if (io->iov != io->fast_iov)
6228 case IORING_OP_SPLICE:
6230 io_put_file(req, req->splice.file_in,
6231 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
6233 case IORING_OP_OPENAT:
6234 case IORING_OP_OPENAT2:
6235 if (req->open.filename)
6236 putname(req->open.filename);
6238 case IORING_OP_RENAMEAT:
6239 putname(req->rename.oldpath);
6240 putname(req->rename.newpath);
6242 case IORING_OP_UNLINKAT:
6243 putname(req->unlink.filename);
6246 req->flags &= ~REQ_F_NEED_CLEANUP;
6250 static int io_issue_sqe(struct io_kiocb *req, bool force_nonblock,
6251 struct io_comp_state *cs)
6253 struct io_ring_ctx *ctx = req->ctx;
6256 switch (req->opcode) {
6258 ret = io_nop(req, cs);
6260 case IORING_OP_READV:
6261 case IORING_OP_READ_FIXED:
6262 case IORING_OP_READ:
6263 ret = io_read(req, force_nonblock, cs);
6265 case IORING_OP_WRITEV:
6266 case IORING_OP_WRITE_FIXED:
6267 case IORING_OP_WRITE:
6268 ret = io_write(req, force_nonblock, cs);
6270 case IORING_OP_FSYNC:
6271 ret = io_fsync(req, force_nonblock);
6273 case IORING_OP_POLL_ADD:
6274 ret = io_poll_add(req);
6276 case IORING_OP_POLL_REMOVE:
6277 ret = io_poll_remove(req);
6279 case IORING_OP_SYNC_FILE_RANGE:
6280 ret = io_sync_file_range(req, force_nonblock);
6282 case IORING_OP_SENDMSG:
6283 ret = io_sendmsg(req, force_nonblock, cs);
6285 case IORING_OP_SEND:
6286 ret = io_send(req, force_nonblock, cs);
6288 case IORING_OP_RECVMSG:
6289 ret = io_recvmsg(req, force_nonblock, cs);
6291 case IORING_OP_RECV:
6292 ret = io_recv(req, force_nonblock, cs);
6294 case IORING_OP_TIMEOUT:
6295 ret = io_timeout(req);
6297 case IORING_OP_TIMEOUT_REMOVE:
6298 ret = io_timeout_remove(req);
6300 case IORING_OP_ACCEPT:
6301 ret = io_accept(req, force_nonblock, cs);
6303 case IORING_OP_CONNECT:
6304 ret = io_connect(req, force_nonblock, cs);
6306 case IORING_OP_ASYNC_CANCEL:
6307 ret = io_async_cancel(req);
6309 case IORING_OP_FALLOCATE:
6310 ret = io_fallocate(req, force_nonblock);
6312 case IORING_OP_OPENAT:
6313 ret = io_openat(req, force_nonblock);
6315 case IORING_OP_CLOSE:
6316 ret = io_close(req, force_nonblock, cs);
6318 case IORING_OP_FILES_UPDATE:
6319 ret = io_files_update(req, force_nonblock, cs);
6321 case IORING_OP_STATX:
6322 ret = io_statx(req, force_nonblock);
6324 case IORING_OP_FADVISE:
6325 ret = io_fadvise(req, force_nonblock);
6327 case IORING_OP_MADVISE:
6328 ret = io_madvise(req, force_nonblock);
6330 case IORING_OP_OPENAT2:
6331 ret = io_openat2(req, force_nonblock);
6333 case IORING_OP_EPOLL_CTL:
6334 ret = io_epoll_ctl(req, force_nonblock, cs);
6336 case IORING_OP_SPLICE:
6337 ret = io_splice(req, force_nonblock);
6339 case IORING_OP_PROVIDE_BUFFERS:
6340 ret = io_provide_buffers(req, force_nonblock, cs);
6342 case IORING_OP_REMOVE_BUFFERS:
6343 ret = io_remove_buffers(req, force_nonblock, cs);
6346 ret = io_tee(req, force_nonblock);
6348 case IORING_OP_SHUTDOWN:
6349 ret = io_shutdown(req, force_nonblock);
6351 case IORING_OP_RENAMEAT:
6352 ret = io_renameat(req, force_nonblock);
6354 case IORING_OP_UNLINKAT:
6355 ret = io_unlinkat(req, force_nonblock);
6365 /* If the op doesn't have a file, we're not polling for it */
6366 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
6367 const bool in_async = io_wq_current_is_worker();
6369 /* workqueue context doesn't hold uring_lock, grab it now */
6371 mutex_lock(&ctx->uring_lock);
6373 io_iopoll_req_issued(req, in_async);
6376 mutex_unlock(&ctx->uring_lock);
6382 static struct io_wq_work *io_wq_submit_work(struct io_wq_work *work)
6384 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6385 struct io_kiocb *timeout;
6388 timeout = io_prep_linked_timeout(req);
6390 io_queue_linked_timeout(timeout);
6392 /* if NO_CANCEL is set, we must still run the work */
6393 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
6394 IO_WQ_WORK_CANCEL) {
6400 ret = io_issue_sqe(req, false, NULL);
6402 * We can get EAGAIN for polled IO even though we're
6403 * forcing a sync submission from here, since we can't
6404 * wait for request slots on the block side.
6413 struct io_ring_ctx *lock_ctx = NULL;
6415 if (req->ctx->flags & IORING_SETUP_IOPOLL)
6416 lock_ctx = req->ctx;
6419 * io_iopoll_complete() does not hold completion_lock to
6420 * complete polled io, so here for polled io, we can not call
6421 * io_req_complete() directly, otherwise there maybe concurrent
6422 * access to cqring, defer_list, etc, which is not safe. Given
6423 * that io_iopoll_complete() is always called under uring_lock,
6424 * so here for polled io, we also get uring_lock to complete
6428 mutex_lock(&lock_ctx->uring_lock);
6430 req_set_fail_links(req);
6431 io_req_complete(req, ret);
6434 mutex_unlock(&lock_ctx->uring_lock);
6437 return io_steal_work(req);
6440 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6443 struct fixed_file_table *table;
6445 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
6446 return table->files[index & IORING_FILE_TABLE_MASK];
6449 static struct file *io_file_get(struct io_submit_state *state,
6450 struct io_kiocb *req, int fd, bool fixed)
6452 struct io_ring_ctx *ctx = req->ctx;
6456 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6458 fd = array_index_nospec(fd, ctx->nr_user_files);
6459 file = io_file_from_index(ctx, fd);
6460 io_set_resource_node(req);
6462 trace_io_uring_file_get(ctx, fd);
6463 file = __io_file_get(state, fd);
6466 if (file && file->f_op == &io_uring_fops &&
6467 !(req->flags & REQ_F_INFLIGHT)) {
6468 io_req_init_async(req);
6469 req->flags |= REQ_F_INFLIGHT;
6471 spin_lock_irq(&ctx->inflight_lock);
6472 list_add(&req->inflight_entry, &ctx->inflight_list);
6473 spin_unlock_irq(&ctx->inflight_lock);
6479 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6481 struct io_timeout_data *data = container_of(timer,
6482 struct io_timeout_data, timer);
6483 struct io_kiocb *prev, *req = data->req;
6484 struct io_ring_ctx *ctx = req->ctx;
6485 unsigned long flags;
6487 spin_lock_irqsave(&ctx->completion_lock, flags);
6488 prev = req->timeout.head;
6489 req->timeout.head = NULL;
6492 * We don't expect the list to be empty, that will only happen if we
6493 * race with the completion of the linked work.
6495 if (prev && refcount_inc_not_zero(&prev->refs))
6496 io_remove_next_linked(prev);
6499 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6502 req_set_fail_links(prev);
6503 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6506 io_req_complete(req, -ETIME);
6508 return HRTIMER_NORESTART;
6511 static void __io_queue_linked_timeout(struct io_kiocb *req)
6514 * If the back reference is NULL, then our linked request finished
6515 * before we got a chance to setup the timer
6517 if (req->timeout.head) {
6518 struct io_timeout_data *data = req->async_data;
6520 data->timer.function = io_link_timeout_fn;
6521 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6526 static void io_queue_linked_timeout(struct io_kiocb *req)
6528 struct io_ring_ctx *ctx = req->ctx;
6530 spin_lock_irq(&ctx->completion_lock);
6531 __io_queue_linked_timeout(req);
6532 spin_unlock_irq(&ctx->completion_lock);
6534 /* drop submission reference */
6538 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6540 struct io_kiocb *nxt = req->link;
6542 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6543 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6546 nxt->timeout.head = req;
6547 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6548 req->flags |= REQ_F_LINK_TIMEOUT;
6552 static void __io_queue_sqe(struct io_kiocb *req, struct io_comp_state *cs)
6554 struct io_kiocb *linked_timeout;
6555 const struct cred *old_creds = NULL;
6559 linked_timeout = io_prep_linked_timeout(req);
6561 if ((req->flags & REQ_F_WORK_INITIALIZED) &&
6562 (req->work.flags & IO_WQ_WORK_CREDS) &&
6563 req->work.identity->creds != current_cred()) {
6565 revert_creds(old_creds);
6566 if (old_creds == req->work.identity->creds)
6567 old_creds = NULL; /* restored original creds */
6569 old_creds = override_creds(req->work.identity->creds);
6572 ret = io_issue_sqe(req, true, cs);
6575 * We async punt it if the file wasn't marked NOWAIT, or if the file
6576 * doesn't support non-blocking read/write attempts
6578 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6579 if (!io_arm_poll_handler(req)) {
6581 * Queued up for async execution, worker will release
6582 * submit reference when the iocb is actually submitted.
6584 io_queue_async_work(req);
6588 io_queue_linked_timeout(linked_timeout);
6589 } else if (likely(!ret)) {
6590 /* drop submission reference */
6591 req = io_put_req_find_next(req);
6593 io_queue_linked_timeout(linked_timeout);
6596 if (!(req->flags & REQ_F_FORCE_ASYNC))
6598 io_queue_async_work(req);
6601 /* un-prep timeout, so it'll be killed as any other linked */
6602 req->flags &= ~REQ_F_LINK_TIMEOUT;
6603 req_set_fail_links(req);
6605 io_req_complete(req, ret);
6609 revert_creds(old_creds);
6612 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6613 struct io_comp_state *cs)
6617 ret = io_req_defer(req, sqe);
6619 if (ret != -EIOCBQUEUED) {
6621 req_set_fail_links(req);
6623 io_req_complete(req, ret);
6625 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6626 if (!req->async_data) {
6627 ret = io_req_defer_prep(req, sqe);
6631 io_queue_async_work(req);
6634 ret = io_req_prep(req, sqe);
6638 __io_queue_sqe(req, cs);
6642 static inline void io_queue_link_head(struct io_kiocb *req,
6643 struct io_comp_state *cs)
6645 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
6647 io_req_complete(req, -ECANCELED);
6649 io_queue_sqe(req, NULL, cs);
6652 struct io_submit_link {
6653 struct io_kiocb *head;
6654 struct io_kiocb *last;
6657 static int io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6658 struct io_submit_link *link, struct io_comp_state *cs)
6660 struct io_ring_ctx *ctx = req->ctx;
6664 * If we already have a head request, queue this one for async
6665 * submittal once the head completes. If we don't have a head but
6666 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6667 * submitted sync once the chain is complete. If none of those
6668 * conditions are true (normal request), then just queue it.
6671 struct io_kiocb *head = link->head;
6674 * Taking sequential execution of a link, draining both sides
6675 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6676 * requests in the link. So, it drains the head and the
6677 * next after the link request. The last one is done via
6678 * drain_next flag to persist the effect across calls.
6680 if (req->flags & REQ_F_IO_DRAIN) {
6681 head->flags |= REQ_F_IO_DRAIN;
6682 ctx->drain_next = 1;
6684 ret = io_req_defer_prep(req, sqe);
6685 if (unlikely(ret)) {
6686 /* fail even hard links since we don't submit */
6687 head->flags |= REQ_F_FAIL_LINK;
6690 trace_io_uring_link(ctx, req, head);
6691 link->last->link = req;
6694 /* last request of a link, enqueue the link */
6695 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6696 io_queue_link_head(head, cs);
6700 if (unlikely(ctx->drain_next)) {
6701 req->flags |= REQ_F_IO_DRAIN;
6702 ctx->drain_next = 0;
6704 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6705 ret = io_req_defer_prep(req, sqe);
6707 req->flags |= REQ_F_FAIL_LINK;
6711 io_queue_sqe(req, sqe, cs);
6719 * Batched submission is done, ensure local IO is flushed out.
6721 static void io_submit_state_end(struct io_submit_state *state)
6723 if (!list_empty(&state->comp.list))
6724 io_submit_flush_completions(&state->comp);
6725 if (state->plug_started)
6726 blk_finish_plug(&state->plug);
6727 io_state_file_put(state);
6728 if (state->free_reqs)
6729 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
6733 * Start submission side cache.
6735 static void io_submit_state_start(struct io_submit_state *state,
6736 struct io_ring_ctx *ctx, unsigned int max_ios)
6738 state->plug_started = false;
6740 INIT_LIST_HEAD(&state->comp.list);
6741 state->comp.ctx = ctx;
6742 state->free_reqs = 0;
6743 state->file_refs = 0;
6744 state->ios_left = max_ios;
6747 static void io_commit_sqring(struct io_ring_ctx *ctx)
6749 struct io_rings *rings = ctx->rings;
6752 * Ensure any loads from the SQEs are done at this point,
6753 * since once we write the new head, the application could
6754 * write new data to them.
6756 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6760 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6761 * that is mapped by userspace. This means that care needs to be taken to
6762 * ensure that reads are stable, as we cannot rely on userspace always
6763 * being a good citizen. If members of the sqe are validated and then later
6764 * used, it's important that those reads are done through READ_ONCE() to
6765 * prevent a re-load down the line.
6767 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6769 u32 *sq_array = ctx->sq_array;
6773 * The cached sq head (or cq tail) serves two purposes:
6775 * 1) allows us to batch the cost of updating the user visible
6777 * 2) allows the kernel side to track the head on its own, even
6778 * though the application is the one updating it.
6780 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
6781 if (likely(head < ctx->sq_entries))
6782 return &ctx->sq_sqes[head];
6784 /* drop invalid entries */
6785 ctx->cached_sq_dropped++;
6786 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6790 static inline void io_consume_sqe(struct io_ring_ctx *ctx)
6792 ctx->cached_sq_head++;
6796 * Check SQE restrictions (opcode and flags).
6798 * Returns 'true' if SQE is allowed, 'false' otherwise.
6800 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6801 struct io_kiocb *req,
6802 unsigned int sqe_flags)
6804 if (!ctx->restricted)
6807 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6810 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6811 ctx->restrictions.sqe_flags_required)
6814 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6815 ctx->restrictions.sqe_flags_required))
6821 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
6822 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
6823 IOSQE_BUFFER_SELECT)
6825 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6826 const struct io_uring_sqe *sqe,
6827 struct io_submit_state *state)
6829 unsigned int sqe_flags;
6832 req->opcode = READ_ONCE(sqe->opcode);
6833 req->user_data = READ_ONCE(sqe->user_data);
6834 req->async_data = NULL;
6839 req->fixed_file_refs = NULL;
6840 /* one is dropped after submission, the other at completion */
6841 refcount_set(&req->refs, 2);
6842 req->task = current;
6845 if (unlikely(req->opcode >= IORING_OP_LAST))
6848 if (unlikely(io_sq_thread_acquire_mm_files(ctx, req)))
6851 sqe_flags = READ_ONCE(sqe->flags);
6852 /* enforce forwards compatibility on users */
6853 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6856 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6859 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6860 !io_op_defs[req->opcode].buffer_select)
6863 id = READ_ONCE(sqe->personality);
6865 struct io_identity *iod;
6867 iod = idr_find(&ctx->personality_idr, id);
6870 refcount_inc(&iod->count);
6872 __io_req_init_async(req);
6873 get_cred(iod->creds);
6874 req->work.identity = iod;
6875 req->work.flags |= IO_WQ_WORK_CREDS;
6878 /* same numerical values with corresponding REQ_F_*, safe to copy */
6879 req->flags |= sqe_flags;
6882 * Plug now if we have more than 1 IO left after this, and the target
6883 * is potentially a read/write to block based storage.
6885 if (!state->plug_started && state->ios_left > 1 &&
6886 io_op_defs[req->opcode].plug) {
6887 blk_start_plug(&state->plug);
6888 state->plug_started = true;
6892 if (io_op_defs[req->opcode].needs_file) {
6893 bool fixed = req->flags & REQ_F_FIXED_FILE;
6895 req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
6896 if (unlikely(!req->file &&
6897 !io_op_defs[req->opcode].needs_file_no_error))
6905 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6907 struct io_submit_state state;
6908 struct io_submit_link link;
6909 int i, submitted = 0;
6911 /* if we have a backlog and couldn't flush it all, return BUSY */
6912 if (test_bit(0, &ctx->sq_check_overflow)) {
6913 if (!__io_cqring_overflow_flush(ctx, false, NULL, NULL))
6917 /* make sure SQ entry isn't read before tail */
6918 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6920 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6923 percpu_counter_add(¤t->io_uring->inflight, nr);
6924 refcount_add(nr, ¤t->usage);
6926 io_submit_state_start(&state, ctx, nr);
6929 for (i = 0; i < nr; i++) {
6930 const struct io_uring_sqe *sqe;
6931 struct io_kiocb *req;
6934 sqe = io_get_sqe(ctx);
6935 if (unlikely(!sqe)) {
6936 io_consume_sqe(ctx);
6939 req = io_alloc_req(ctx, &state);
6940 if (unlikely(!req)) {
6942 submitted = -EAGAIN;
6945 io_consume_sqe(ctx);
6946 /* will complete beyond this point, count as submitted */
6949 err = io_init_req(ctx, req, sqe, &state);
6950 if (unlikely(err)) {
6953 io_req_complete(req, err);
6957 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6958 true, io_async_submit(ctx));
6959 err = io_submit_sqe(req, sqe, &link, &state.comp);
6964 if (unlikely(submitted != nr)) {
6965 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6966 struct io_uring_task *tctx = current->io_uring;
6967 int unused = nr - ref_used;
6969 percpu_ref_put_many(&ctx->refs, unused);
6970 percpu_counter_sub(&tctx->inflight, unused);
6971 put_task_struct_many(current, unused);
6974 io_queue_link_head(link.head, &state.comp);
6975 io_submit_state_end(&state);
6977 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6978 io_commit_sqring(ctx);
6983 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6985 /* Tell userspace we may need a wakeup call */
6986 spin_lock_irq(&ctx->completion_lock);
6987 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6988 spin_unlock_irq(&ctx->completion_lock);
6991 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6993 spin_lock_irq(&ctx->completion_lock);
6994 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6995 spin_unlock_irq(&ctx->completion_lock);
6998 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7000 unsigned int to_submit;
7003 to_submit = io_sqring_entries(ctx);
7004 /* if we're handling multiple rings, cap submit size for fairness */
7005 if (cap_entries && to_submit > 8)
7008 if (!list_empty(&ctx->iopoll_list) || to_submit) {
7009 unsigned nr_events = 0;
7011 mutex_lock(&ctx->uring_lock);
7012 if (!list_empty(&ctx->iopoll_list))
7013 io_do_iopoll(ctx, &nr_events, 0);
7015 if (to_submit && !ctx->sqo_dead &&
7016 likely(!percpu_ref_is_dying(&ctx->refs)))
7017 ret = io_submit_sqes(ctx, to_submit);
7018 mutex_unlock(&ctx->uring_lock);
7021 if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
7022 wake_up(&ctx->sqo_sq_wait);
7027 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7029 struct io_ring_ctx *ctx;
7030 unsigned sq_thread_idle = 0;
7032 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7033 if (sq_thread_idle < ctx->sq_thread_idle)
7034 sq_thread_idle = ctx->sq_thread_idle;
7037 sqd->sq_thread_idle = sq_thread_idle;
7040 static void io_sqd_init_new(struct io_sq_data *sqd)
7042 struct io_ring_ctx *ctx;
7044 while (!list_empty(&sqd->ctx_new_list)) {
7045 ctx = list_first_entry(&sqd->ctx_new_list, struct io_ring_ctx, sqd_list);
7046 list_move_tail(&ctx->sqd_list, &sqd->ctx_list);
7047 complete(&ctx->sq_thread_comp);
7050 io_sqd_update_thread_idle(sqd);
7053 static int io_sq_thread(void *data)
7055 struct cgroup_subsys_state *cur_css = NULL;
7056 struct files_struct *old_files = current->files;
7057 struct nsproxy *old_nsproxy = current->nsproxy;
7058 const struct cred *old_cred = NULL;
7059 struct io_sq_data *sqd = data;
7060 struct io_ring_ctx *ctx;
7061 unsigned long timeout = 0;
7065 current->files = NULL;
7066 current->nsproxy = NULL;
7067 task_unlock(current);
7069 while (!kthread_should_stop()) {
7071 bool cap_entries, sqt_spin, needs_sched;
7074 * Any changes to the sqd lists are synchronized through the
7075 * kthread parking. This synchronizes the thread vs users,
7076 * the users are synchronized on the sqd->ctx_lock.
7078 if (kthread_should_park()) {
7081 * When sq thread is unparked, in case the previous park operation
7082 * comes from io_put_sq_data(), which means that sq thread is going
7083 * to be stopped, so here needs to have a check.
7085 if (kthread_should_stop())
7089 if (unlikely(!list_empty(&sqd->ctx_new_list))) {
7090 io_sqd_init_new(sqd);
7091 timeout = jiffies + sqd->sq_thread_idle;
7095 cap_entries = !list_is_singular(&sqd->ctx_list);
7096 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7097 if (current->cred != ctx->creds) {
7099 revert_creds(old_cred);
7100 old_cred = override_creds(ctx->creds);
7102 io_sq_thread_associate_blkcg(ctx, &cur_css);
7104 current->loginuid = ctx->loginuid;
7105 current->sessionid = ctx->sessionid;
7108 ret = __io_sq_thread(ctx, cap_entries);
7109 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
7112 io_sq_thread_drop_mm_files();
7115 if (sqt_spin || !time_after(jiffies, timeout)) {
7117 io_sq_thread_drop_mm_files();
7120 timeout = jiffies + sqd->sq_thread_idle;
7124 if (kthread_should_park())
7128 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7129 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7130 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7131 !list_empty_careful(&ctx->iopoll_list)) {
7132 needs_sched = false;
7135 if (io_sqring_entries(ctx)) {
7136 needs_sched = false;
7142 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7143 io_ring_set_wakeup_flag(ctx);
7146 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7147 io_ring_clear_wakeup_flag(ctx);
7150 finish_wait(&sqd->wait, &wait);
7151 timeout = jiffies + sqd->sq_thread_idle;
7155 io_sq_thread_drop_mm_files();
7158 io_sq_thread_unassociate_blkcg();
7160 revert_creds(old_cred);
7163 current->files = old_files;
7164 current->nsproxy = old_nsproxy;
7165 task_unlock(current);
7172 struct io_wait_queue {
7173 struct wait_queue_entry wq;
7174 struct io_ring_ctx *ctx;
7176 unsigned nr_timeouts;
7179 static inline bool io_should_wake(struct io_wait_queue *iowq)
7181 struct io_ring_ctx *ctx = iowq->ctx;
7184 * Wake up if we have enough events, or if a timeout occurred since we
7185 * started waiting. For timeouts, we always want to return to userspace,
7186 * regardless of event count.
7188 return io_cqring_events(ctx) >= iowq->to_wait ||
7189 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7192 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7193 int wake_flags, void *key)
7195 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7199 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7200 * the task, and the next invocation will do it.
7202 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
7203 return autoremove_wake_function(curr, mode, wake_flags, key);
7207 static int io_run_task_work_sig(void)
7209 if (io_run_task_work())
7211 if (!signal_pending(current))
7213 if (test_tsk_thread_flag(current, TIF_NOTIFY_SIGNAL))
7214 return -ERESTARTSYS;
7219 * Wait until events become available, if we don't already have some. The
7220 * application must reap them itself, as they reside on the shared cq ring.
7222 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7223 const sigset_t __user *sig, size_t sigsz,
7224 struct __kernel_timespec __user *uts)
7226 struct io_wait_queue iowq = {
7229 .func = io_wake_function,
7230 .entry = LIST_HEAD_INIT(iowq.wq.entry),
7233 .to_wait = min_events,
7235 struct io_rings *rings = ctx->rings;
7236 struct timespec64 ts;
7237 signed long timeout = 0;
7241 io_cqring_overflow_flush(ctx, false, NULL, NULL);
7242 if (io_cqring_events(ctx) >= min_events)
7244 if (!io_run_task_work())
7249 #ifdef CONFIG_COMPAT
7250 if (in_compat_syscall())
7251 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7255 ret = set_user_sigmask(sig, sigsz);
7262 if (get_timespec64(&ts, uts))
7264 timeout = timespec64_to_jiffies(&ts);
7267 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7268 trace_io_uring_cqring_wait(ctx, min_events);
7270 io_cqring_overflow_flush(ctx, false, NULL, NULL);
7271 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
7272 TASK_INTERRUPTIBLE);
7273 /* make sure we run task_work before checking for signals */
7274 ret = io_run_task_work_sig();
7276 finish_wait(&ctx->wait, &iowq.wq);
7281 if (io_should_wake(&iowq))
7283 if (test_bit(0, &ctx->cq_check_overflow)) {
7284 finish_wait(&ctx->wait, &iowq.wq);
7288 timeout = schedule_timeout(timeout);
7297 finish_wait(&ctx->wait, &iowq.wq);
7299 restore_saved_sigmask_unless(ret == -EINTR);
7301 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7304 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7306 #if defined(CONFIG_UNIX)
7307 if (ctx->ring_sock) {
7308 struct sock *sock = ctx->ring_sock->sk;
7309 struct sk_buff *skb;
7311 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7317 for (i = 0; i < ctx->nr_user_files; i++) {
7320 file = io_file_from_index(ctx, i);
7327 static void io_file_ref_kill(struct percpu_ref *ref)
7329 struct fixed_file_data *data;
7331 data = container_of(ref, struct fixed_file_data, refs);
7332 complete(&data->done);
7335 static void io_sqe_files_set_node(struct fixed_file_data *file_data,
7336 struct fixed_file_ref_node *ref_node)
7338 spin_lock_bh(&file_data->lock);
7339 file_data->node = ref_node;
7340 list_add_tail(&ref_node->node, &file_data->ref_list);
7341 spin_unlock_bh(&file_data->lock);
7342 percpu_ref_get(&file_data->refs);
7345 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7347 struct fixed_file_data *data = ctx->file_data;
7348 struct fixed_file_ref_node *backup_node, *ref_node = NULL;
7349 unsigned nr_tables, i;
7354 backup_node = alloc_fixed_file_ref_node(ctx);
7358 spin_lock_bh(&data->lock);
7359 ref_node = data->node;
7360 spin_unlock_bh(&data->lock);
7362 percpu_ref_kill(&ref_node->refs);
7364 percpu_ref_kill(&data->refs);
7366 /* wait for all refs nodes to complete */
7367 flush_delayed_work(&ctx->file_put_work);
7369 ret = wait_for_completion_interruptible(&data->done);
7372 ret = io_run_task_work_sig();
7374 percpu_ref_resurrect(&data->refs);
7375 reinit_completion(&data->done);
7376 io_sqe_files_set_node(data, backup_node);
7381 __io_sqe_files_unregister(ctx);
7382 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
7383 for (i = 0; i < nr_tables; i++)
7384 kfree(data->table[i].files);
7386 percpu_ref_exit(&data->refs);
7388 ctx->file_data = NULL;
7389 ctx->nr_user_files = 0;
7390 destroy_fixed_file_ref_node(backup_node);
7394 static void io_put_sq_data(struct io_sq_data *sqd)
7396 if (refcount_dec_and_test(&sqd->refs)) {
7398 * The park is a bit of a work-around, without it we get
7399 * warning spews on shutdown with SQPOLL set and affinity
7400 * set to a single CPU.
7403 kthread_park(sqd->thread);
7404 kthread_stop(sqd->thread);
7411 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7413 struct io_ring_ctx *ctx_attach;
7414 struct io_sq_data *sqd;
7417 f = fdget(p->wq_fd);
7419 return ERR_PTR(-ENXIO);
7420 if (f.file->f_op != &io_uring_fops) {
7422 return ERR_PTR(-EINVAL);
7425 ctx_attach = f.file->private_data;
7426 sqd = ctx_attach->sq_data;
7429 return ERR_PTR(-EINVAL);
7432 refcount_inc(&sqd->refs);
7437 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p)
7439 struct io_sq_data *sqd;
7441 if (p->flags & IORING_SETUP_ATTACH_WQ)
7442 return io_attach_sq_data(p);
7444 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7446 return ERR_PTR(-ENOMEM);
7448 refcount_set(&sqd->refs, 1);
7449 INIT_LIST_HEAD(&sqd->ctx_list);
7450 INIT_LIST_HEAD(&sqd->ctx_new_list);
7451 mutex_init(&sqd->ctx_lock);
7452 mutex_init(&sqd->lock);
7453 init_waitqueue_head(&sqd->wait);
7457 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7458 __releases(&sqd->lock)
7462 kthread_unpark(sqd->thread);
7463 mutex_unlock(&sqd->lock);
7466 static void io_sq_thread_park(struct io_sq_data *sqd)
7467 __acquires(&sqd->lock)
7471 mutex_lock(&sqd->lock);
7472 kthread_park(sqd->thread);
7475 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
7477 struct io_sq_data *sqd = ctx->sq_data;
7482 * We may arrive here from the error branch in
7483 * io_sq_offload_create() where the kthread is created
7484 * without being waked up, thus wake it up now to make
7485 * sure the wait will complete.
7487 wake_up_process(sqd->thread);
7488 wait_for_completion(&ctx->sq_thread_comp);
7490 io_sq_thread_park(sqd);
7493 mutex_lock(&sqd->ctx_lock);
7494 list_del(&ctx->sqd_list);
7495 io_sqd_update_thread_idle(sqd);
7496 mutex_unlock(&sqd->ctx_lock);
7499 io_sq_thread_unpark(sqd);
7501 io_put_sq_data(sqd);
7502 ctx->sq_data = NULL;
7506 static void io_finish_async(struct io_ring_ctx *ctx)
7508 io_sq_thread_stop(ctx);
7511 io_wq_destroy(ctx->io_wq);
7516 #if defined(CONFIG_UNIX)
7518 * Ensure the UNIX gc is aware of our file set, so we are certain that
7519 * the io_uring can be safely unregistered on process exit, even if we have
7520 * loops in the file referencing.
7522 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7524 struct sock *sk = ctx->ring_sock->sk;
7525 struct scm_fp_list *fpl;
7526 struct sk_buff *skb;
7529 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7533 skb = alloc_skb(0, GFP_KERNEL);
7542 fpl->user = get_uid(ctx->user);
7543 for (i = 0; i < nr; i++) {
7544 struct file *file = io_file_from_index(ctx, i + offset);
7548 fpl->fp[nr_files] = get_file(file);
7549 unix_inflight(fpl->user, fpl->fp[nr_files]);
7554 fpl->max = SCM_MAX_FD;
7555 fpl->count = nr_files;
7556 UNIXCB(skb).fp = fpl;
7557 skb->destructor = unix_destruct_scm;
7558 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7559 skb_queue_head(&sk->sk_receive_queue, skb);
7561 for (i = 0; i < nr_files; i++)
7572 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7573 * causes regular reference counting to break down. We rely on the UNIX
7574 * garbage collection to take care of this problem for us.
7576 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7578 unsigned left, total;
7582 left = ctx->nr_user_files;
7584 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7586 ret = __io_sqe_files_scm(ctx, this_files, total);
7590 total += this_files;
7596 while (total < ctx->nr_user_files) {
7597 struct file *file = io_file_from_index(ctx, total);
7607 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7613 static int io_sqe_alloc_file_tables(struct fixed_file_data *file_data,
7614 unsigned nr_tables, unsigned nr_files)
7618 for (i = 0; i < nr_tables; i++) {
7619 struct fixed_file_table *table = &file_data->table[i];
7620 unsigned this_files;
7622 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7623 table->files = kcalloc(this_files, sizeof(struct file *),
7627 nr_files -= this_files;
7633 for (i = 0; i < nr_tables; i++) {
7634 struct fixed_file_table *table = &file_data->table[i];
7635 kfree(table->files);
7640 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
7642 #if defined(CONFIG_UNIX)
7643 struct sock *sock = ctx->ring_sock->sk;
7644 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7645 struct sk_buff *skb;
7648 __skb_queue_head_init(&list);
7651 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7652 * remove this entry and rearrange the file array.
7654 skb = skb_dequeue(head);
7656 struct scm_fp_list *fp;
7658 fp = UNIXCB(skb).fp;
7659 for (i = 0; i < fp->count; i++) {
7662 if (fp->fp[i] != file)
7665 unix_notinflight(fp->user, fp->fp[i]);
7666 left = fp->count - 1 - i;
7668 memmove(&fp->fp[i], &fp->fp[i + 1],
7669 left * sizeof(struct file *));
7676 __skb_queue_tail(&list, skb);
7686 __skb_queue_tail(&list, skb);
7688 skb = skb_dequeue(head);
7691 if (skb_peek(&list)) {
7692 spin_lock_irq(&head->lock);
7693 while ((skb = __skb_dequeue(&list)) != NULL)
7694 __skb_queue_tail(head, skb);
7695 spin_unlock_irq(&head->lock);
7702 struct io_file_put {
7703 struct list_head list;
7707 static void __io_file_put_work(struct fixed_file_ref_node *ref_node)
7709 struct fixed_file_data *file_data = ref_node->file_data;
7710 struct io_ring_ctx *ctx = file_data->ctx;
7711 struct io_file_put *pfile, *tmp;
7713 list_for_each_entry_safe(pfile, tmp, &ref_node->file_list, list) {
7714 list_del(&pfile->list);
7715 io_ring_file_put(ctx, pfile->file);
7719 percpu_ref_exit(&ref_node->refs);
7721 percpu_ref_put(&file_data->refs);
7724 static void io_file_put_work(struct work_struct *work)
7726 struct io_ring_ctx *ctx;
7727 struct llist_node *node;
7729 ctx = container_of(work, struct io_ring_ctx, file_put_work.work);
7730 node = llist_del_all(&ctx->file_put_llist);
7733 struct fixed_file_ref_node *ref_node;
7734 struct llist_node *next = node->next;
7736 ref_node = llist_entry(node, struct fixed_file_ref_node, llist);
7737 __io_file_put_work(ref_node);
7742 static void io_file_data_ref_zero(struct percpu_ref *ref)
7744 struct fixed_file_ref_node *ref_node;
7745 struct fixed_file_data *data;
7746 struct io_ring_ctx *ctx;
7747 bool first_add = false;
7750 ref_node = container_of(ref, struct fixed_file_ref_node, refs);
7751 data = ref_node->file_data;
7754 spin_lock_bh(&data->lock);
7755 ref_node->done = true;
7757 while (!list_empty(&data->ref_list)) {
7758 ref_node = list_first_entry(&data->ref_list,
7759 struct fixed_file_ref_node, node);
7760 /* recycle ref nodes in order */
7761 if (!ref_node->done)
7763 list_del(&ref_node->node);
7764 first_add |= llist_add(&ref_node->llist, &ctx->file_put_llist);
7766 spin_unlock_bh(&data->lock);
7768 if (percpu_ref_is_dying(&data->refs))
7772 mod_delayed_work(system_wq, &ctx->file_put_work, 0);
7774 queue_delayed_work(system_wq, &ctx->file_put_work, delay);
7777 static struct fixed_file_ref_node *alloc_fixed_file_ref_node(
7778 struct io_ring_ctx *ctx)
7780 struct fixed_file_ref_node *ref_node;
7782 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7786 if (percpu_ref_init(&ref_node->refs, io_file_data_ref_zero,
7791 INIT_LIST_HEAD(&ref_node->node);
7792 INIT_LIST_HEAD(&ref_node->file_list);
7793 ref_node->file_data = ctx->file_data;
7794 ref_node->done = false;
7798 static void destroy_fixed_file_ref_node(struct fixed_file_ref_node *ref_node)
7800 percpu_ref_exit(&ref_node->refs);
7804 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7807 __s32 __user *fds = (__s32 __user *) arg;
7808 unsigned nr_tables, i;
7810 int fd, ret = -ENOMEM;
7811 struct fixed_file_ref_node *ref_node;
7812 struct fixed_file_data *file_data;
7818 if (nr_args > IORING_MAX_FIXED_FILES)
7821 file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
7824 file_data->ctx = ctx;
7825 init_completion(&file_data->done);
7826 INIT_LIST_HEAD(&file_data->ref_list);
7827 spin_lock_init(&file_data->lock);
7829 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
7830 file_data->table = kcalloc(nr_tables, sizeof(*file_data->table),
7832 if (!file_data->table)
7835 if (percpu_ref_init(&file_data->refs, io_file_ref_kill,
7836 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
7839 if (io_sqe_alloc_file_tables(file_data, nr_tables, nr_args))
7841 ctx->file_data = file_data;
7843 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7844 struct fixed_file_table *table;
7847 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7851 /* allow sparse sets */
7861 * Don't allow io_uring instances to be registered. If UNIX
7862 * isn't enabled, then this causes a reference cycle and this
7863 * instance can never get freed. If UNIX is enabled we'll
7864 * handle it just fine, but there's still no point in allowing
7865 * a ring fd as it doesn't support regular read/write anyway.
7867 if (file->f_op == &io_uring_fops) {
7871 table = &file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7872 index = i & IORING_FILE_TABLE_MASK;
7873 table->files[index] = file;
7876 ret = io_sqe_files_scm(ctx);
7878 io_sqe_files_unregister(ctx);
7882 ref_node = alloc_fixed_file_ref_node(ctx);
7884 io_sqe_files_unregister(ctx);
7888 io_sqe_files_set_node(file_data, ref_node);
7891 for (i = 0; i < ctx->nr_user_files; i++) {
7892 file = io_file_from_index(ctx, i);
7896 for (i = 0; i < nr_tables; i++)
7897 kfree(file_data->table[i].files);
7898 ctx->nr_user_files = 0;
7900 percpu_ref_exit(&file_data->refs);
7902 kfree(file_data->table);
7904 ctx->file_data = NULL;
7908 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7911 #if defined(CONFIG_UNIX)
7912 struct sock *sock = ctx->ring_sock->sk;
7913 struct sk_buff_head *head = &sock->sk_receive_queue;
7914 struct sk_buff *skb;
7917 * See if we can merge this file into an existing skb SCM_RIGHTS
7918 * file set. If there's no room, fall back to allocating a new skb
7919 * and filling it in.
7921 spin_lock_irq(&head->lock);
7922 skb = skb_peek(head);
7924 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7926 if (fpl->count < SCM_MAX_FD) {
7927 __skb_unlink(skb, head);
7928 spin_unlock_irq(&head->lock);
7929 fpl->fp[fpl->count] = get_file(file);
7930 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7932 spin_lock_irq(&head->lock);
7933 __skb_queue_head(head, skb);
7938 spin_unlock_irq(&head->lock);
7945 return __io_sqe_files_scm(ctx, 1, index);
7951 static int io_queue_file_removal(struct fixed_file_data *data,
7954 struct io_file_put *pfile;
7955 struct fixed_file_ref_node *ref_node = data->node;
7957 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
7962 list_add(&pfile->list, &ref_node->file_list);
7967 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7968 struct io_uring_files_update *up,
7971 struct fixed_file_data *data = ctx->file_data;
7972 struct fixed_file_ref_node *ref_node;
7977 bool needs_switch = false;
7979 if (check_add_overflow(up->offset, nr_args, &done))
7981 if (done > ctx->nr_user_files)
7984 ref_node = alloc_fixed_file_ref_node(ctx);
7989 fds = u64_to_user_ptr(up->fds);
7991 struct fixed_file_table *table;
7995 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7999 i = array_index_nospec(up->offset, ctx->nr_user_files);
8000 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
8001 index = i & IORING_FILE_TABLE_MASK;
8002 if (table->files[index]) {
8003 file = table->files[index];
8004 err = io_queue_file_removal(data, file);
8007 table->files[index] = NULL;
8008 needs_switch = true;
8017 * Don't allow io_uring instances to be registered. If
8018 * UNIX isn't enabled, then this causes a reference
8019 * cycle and this instance can never get freed. If UNIX
8020 * is enabled we'll handle it just fine, but there's
8021 * still no point in allowing a ring fd as it doesn't
8022 * support regular read/write anyway.
8024 if (file->f_op == &io_uring_fops) {
8029 table->files[index] = file;
8030 err = io_sqe_file_register(ctx, file, i);
8032 table->files[index] = NULL;
8043 percpu_ref_kill(&data->node->refs);
8044 io_sqe_files_set_node(data, ref_node);
8046 destroy_fixed_file_ref_node(ref_node);
8048 return done ? done : err;
8051 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
8054 struct io_uring_files_update up;
8056 if (!ctx->file_data)
8060 if (copy_from_user(&up, arg, sizeof(up)))
8065 return __io_sqe_files_update(ctx, &up, nr_args);
8068 static void io_free_work(struct io_wq_work *work)
8070 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8072 /* Consider that io_steal_work() relies on this ref */
8076 static int io_init_wq_offload(struct io_ring_ctx *ctx,
8077 struct io_uring_params *p)
8079 struct io_wq_data data;
8081 struct io_ring_ctx *ctx_attach;
8082 unsigned int concurrency;
8085 data.user = ctx->user;
8086 data.free_work = io_free_work;
8087 data.do_work = io_wq_submit_work;
8089 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
8090 /* Do QD, or 4 * CPUS, whatever is smallest */
8091 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8093 ctx->io_wq = io_wq_create(concurrency, &data);
8094 if (IS_ERR(ctx->io_wq)) {
8095 ret = PTR_ERR(ctx->io_wq);
8101 f = fdget(p->wq_fd);
8105 if (f.file->f_op != &io_uring_fops) {
8110 ctx_attach = f.file->private_data;
8111 /* @io_wq is protected by holding the fd */
8112 if (!io_wq_get(ctx_attach->io_wq, &data)) {
8117 ctx->io_wq = ctx_attach->io_wq;
8123 static int io_uring_alloc_task_context(struct task_struct *task)
8125 struct io_uring_task *tctx;
8128 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
8129 if (unlikely(!tctx))
8132 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8133 if (unlikely(ret)) {
8139 init_waitqueue_head(&tctx->wait);
8141 atomic_set(&tctx->in_idle, 0);
8142 tctx->sqpoll = false;
8143 io_init_identity(&tctx->__identity);
8144 tctx->identity = &tctx->__identity;
8145 task->io_uring = tctx;
8149 void __io_uring_free(struct task_struct *tsk)
8151 struct io_uring_task *tctx = tsk->io_uring;
8153 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8154 WARN_ON_ONCE(refcount_read(&tctx->identity->count) != 1);
8155 if (tctx->identity != &tctx->__identity)
8156 kfree(tctx->identity);
8157 percpu_counter_destroy(&tctx->inflight);
8159 tsk->io_uring = NULL;
8162 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8163 struct io_uring_params *p)
8167 if (ctx->flags & IORING_SETUP_SQPOLL) {
8168 struct io_sq_data *sqd;
8171 if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_NICE))
8174 sqd = io_get_sq_data(p);
8181 io_sq_thread_park(sqd);
8182 mutex_lock(&sqd->ctx_lock);
8183 list_add(&ctx->sqd_list, &sqd->ctx_new_list);
8184 mutex_unlock(&sqd->ctx_lock);
8185 io_sq_thread_unpark(sqd);
8187 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8188 if (!ctx->sq_thread_idle)
8189 ctx->sq_thread_idle = HZ;
8194 if (p->flags & IORING_SETUP_SQ_AFF) {
8195 int cpu = p->sq_thread_cpu;
8198 if (cpu >= nr_cpu_ids)
8200 if (!cpu_online(cpu))
8203 sqd->thread = kthread_create_on_cpu(io_sq_thread, sqd,
8204 cpu, "io_uring-sq");
8206 sqd->thread = kthread_create(io_sq_thread, sqd,
8209 if (IS_ERR(sqd->thread)) {
8210 ret = PTR_ERR(sqd->thread);
8214 ret = io_uring_alloc_task_context(sqd->thread);
8217 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8218 /* Can't have SQ_AFF without SQPOLL */
8224 ret = io_init_wq_offload(ctx, p);
8230 io_finish_async(ctx);
8234 static void io_sq_offload_start(struct io_ring_ctx *ctx)
8236 struct io_sq_data *sqd = ctx->sq_data;
8238 if ((ctx->flags & IORING_SETUP_SQPOLL) && sqd->thread)
8239 wake_up_process(sqd->thread);
8242 static inline void __io_unaccount_mem(struct user_struct *user,
8243 unsigned long nr_pages)
8245 atomic_long_sub(nr_pages, &user->locked_vm);
8248 static inline int __io_account_mem(struct user_struct *user,
8249 unsigned long nr_pages)
8251 unsigned long page_limit, cur_pages, new_pages;
8253 /* Don't allow more pages than we can safely lock */
8254 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8257 cur_pages = atomic_long_read(&user->locked_vm);
8258 new_pages = cur_pages + nr_pages;
8259 if (new_pages > page_limit)
8261 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8262 new_pages) != cur_pages);
8267 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
8268 enum io_mem_account acct)
8271 __io_unaccount_mem(ctx->user, nr_pages);
8273 if (ctx->mm_account) {
8274 if (acct == ACCT_LOCKED) {
8275 mmap_write_lock(ctx->mm_account);
8276 ctx->mm_account->locked_vm -= nr_pages;
8277 mmap_write_unlock(ctx->mm_account);
8278 }else if (acct == ACCT_PINNED) {
8279 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8284 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
8285 enum io_mem_account acct)
8289 if (ctx->limit_mem) {
8290 ret = __io_account_mem(ctx->user, nr_pages);
8295 if (ctx->mm_account) {
8296 if (acct == ACCT_LOCKED) {
8297 mmap_write_lock(ctx->mm_account);
8298 ctx->mm_account->locked_vm += nr_pages;
8299 mmap_write_unlock(ctx->mm_account);
8300 } else if (acct == ACCT_PINNED) {
8301 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8308 static void io_mem_free(void *ptr)
8315 page = virt_to_head_page(ptr);
8316 if (put_page_testzero(page))
8317 free_compound_page(page);
8320 static void *io_mem_alloc(size_t size)
8322 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8325 return (void *) __get_free_pages(gfp_flags, get_order(size));
8328 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8331 struct io_rings *rings;
8332 size_t off, sq_array_size;
8334 off = struct_size(rings, cqes, cq_entries);
8335 if (off == SIZE_MAX)
8339 off = ALIGN(off, SMP_CACHE_BYTES);
8347 sq_array_size = array_size(sizeof(u32), sq_entries);
8348 if (sq_array_size == SIZE_MAX)
8351 if (check_add_overflow(off, sq_array_size, &off))
8357 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
8361 pages = (size_t)1 << get_order(
8362 rings_size(sq_entries, cq_entries, NULL));
8363 pages += (size_t)1 << get_order(
8364 array_size(sizeof(struct io_uring_sqe), sq_entries));
8369 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
8373 if (!ctx->user_bufs)
8376 for (i = 0; i < ctx->nr_user_bufs; i++) {
8377 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8379 for (j = 0; j < imu->nr_bvecs; j++)
8380 unpin_user_page(imu->bvec[j].bv_page);
8382 if (imu->acct_pages)
8383 io_unaccount_mem(ctx, imu->acct_pages, ACCT_PINNED);
8388 kfree(ctx->user_bufs);
8389 ctx->user_bufs = NULL;
8390 ctx->nr_user_bufs = 0;
8394 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8395 void __user *arg, unsigned index)
8397 struct iovec __user *src;
8399 #ifdef CONFIG_COMPAT
8401 struct compat_iovec __user *ciovs;
8402 struct compat_iovec ciov;
8404 ciovs = (struct compat_iovec __user *) arg;
8405 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8408 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8409 dst->iov_len = ciov.iov_len;
8413 src = (struct iovec __user *) arg;
8414 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8420 * Not super efficient, but this is just a registration time. And we do cache
8421 * the last compound head, so generally we'll only do a full search if we don't
8424 * We check if the given compound head page has already been accounted, to
8425 * avoid double accounting it. This allows us to account the full size of the
8426 * page, not just the constituent pages of a huge page.
8428 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8429 int nr_pages, struct page *hpage)
8433 /* check current page array */
8434 for (i = 0; i < nr_pages; i++) {
8435 if (!PageCompound(pages[i]))
8437 if (compound_head(pages[i]) == hpage)
8441 /* check previously registered pages */
8442 for (i = 0; i < ctx->nr_user_bufs; i++) {
8443 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8445 for (j = 0; j < imu->nr_bvecs; j++) {
8446 if (!PageCompound(imu->bvec[j].bv_page))
8448 if (compound_head(imu->bvec[j].bv_page) == hpage)
8456 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8457 int nr_pages, struct io_mapped_ubuf *imu,
8458 struct page **last_hpage)
8462 for (i = 0; i < nr_pages; i++) {
8463 if (!PageCompound(pages[i])) {
8468 hpage = compound_head(pages[i]);
8469 if (hpage == *last_hpage)
8471 *last_hpage = hpage;
8472 if (headpage_already_acct(ctx, pages, i, hpage))
8474 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8478 if (!imu->acct_pages)
8481 ret = io_account_mem(ctx, imu->acct_pages, ACCT_PINNED);
8483 imu->acct_pages = 0;
8487 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
8490 struct vm_area_struct **vmas = NULL;
8491 struct page **pages = NULL;
8492 struct page *last_hpage = NULL;
8493 int i, j, got_pages = 0;
8498 if (!nr_args || nr_args > UIO_MAXIOV)
8501 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
8503 if (!ctx->user_bufs)
8506 for (i = 0; i < nr_args; i++) {
8507 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8508 unsigned long off, start, end, ubuf;
8513 ret = io_copy_iov(ctx, &iov, arg, i);
8518 * Don't impose further limits on the size and buffer
8519 * constraints here, we'll -EINVAL later when IO is
8520 * submitted if they are wrong.
8523 if (!iov.iov_base || !iov.iov_len)
8526 /* arbitrary limit, but we need something */
8527 if (iov.iov_len > SZ_1G)
8530 ubuf = (unsigned long) iov.iov_base;
8531 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8532 start = ubuf >> PAGE_SHIFT;
8533 nr_pages = end - start;
8536 if (!pages || nr_pages > got_pages) {
8539 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
8541 vmas = kvmalloc_array(nr_pages,
8542 sizeof(struct vm_area_struct *),
8544 if (!pages || !vmas) {
8548 got_pages = nr_pages;
8551 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
8558 mmap_read_lock(current->mm);
8559 pret = pin_user_pages(ubuf, nr_pages,
8560 FOLL_WRITE | FOLL_LONGTERM,
8562 if (pret == nr_pages) {
8563 /* don't support file backed memory */
8564 for (j = 0; j < nr_pages; j++) {
8565 struct vm_area_struct *vma = vmas[j];
8568 !is_file_hugepages(vma->vm_file)) {
8574 ret = pret < 0 ? pret : -EFAULT;
8576 mmap_read_unlock(current->mm);
8579 * if we did partial map, or found file backed vmas,
8580 * release any pages we did get
8583 unpin_user_pages(pages, pret);
8588 ret = io_buffer_account_pin(ctx, pages, pret, imu, &last_hpage);
8590 unpin_user_pages(pages, pret);
8595 off = ubuf & ~PAGE_MASK;
8597 for (j = 0; j < nr_pages; j++) {
8600 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8601 imu->bvec[j].bv_page = pages[j];
8602 imu->bvec[j].bv_len = vec_len;
8603 imu->bvec[j].bv_offset = off;
8607 /* store original address for later verification */
8609 imu->len = iov.iov_len;
8610 imu->nr_bvecs = nr_pages;
8612 ctx->nr_user_bufs++;
8620 io_sqe_buffer_unregister(ctx);
8624 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8626 __s32 __user *fds = arg;
8632 if (copy_from_user(&fd, fds, sizeof(*fds)))
8635 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8636 if (IS_ERR(ctx->cq_ev_fd)) {
8637 int ret = PTR_ERR(ctx->cq_ev_fd);
8638 ctx->cq_ev_fd = NULL;
8645 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8647 if (ctx->cq_ev_fd) {
8648 eventfd_ctx_put(ctx->cq_ev_fd);
8649 ctx->cq_ev_fd = NULL;
8656 static int __io_destroy_buffers(int id, void *p, void *data)
8658 struct io_ring_ctx *ctx = data;
8659 struct io_buffer *buf = p;
8661 __io_remove_buffers(ctx, buf, id, -1U);
8665 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8667 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
8668 idr_destroy(&ctx->io_buffer_idr);
8671 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8673 io_finish_async(ctx);
8674 io_sqe_buffer_unregister(ctx);
8676 if (ctx->sqo_task) {
8677 put_task_struct(ctx->sqo_task);
8678 ctx->sqo_task = NULL;
8679 mmdrop(ctx->mm_account);
8680 ctx->mm_account = NULL;
8683 #ifdef CONFIG_BLK_CGROUP
8684 if (ctx->sqo_blkcg_css)
8685 css_put(ctx->sqo_blkcg_css);
8688 io_sqe_files_unregister(ctx);
8689 io_eventfd_unregister(ctx);
8690 io_destroy_buffers(ctx);
8691 idr_destroy(&ctx->personality_idr);
8693 #if defined(CONFIG_UNIX)
8694 if (ctx->ring_sock) {
8695 ctx->ring_sock->file = NULL; /* so that iput() is called */
8696 sock_release(ctx->ring_sock);
8700 io_mem_free(ctx->rings);
8701 io_mem_free(ctx->sq_sqes);
8703 percpu_ref_exit(&ctx->refs);
8704 free_uid(ctx->user);
8705 put_cred(ctx->creds);
8706 kfree(ctx->cancel_hash);
8707 kmem_cache_free(req_cachep, ctx->fallback_req);
8711 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8713 struct io_ring_ctx *ctx = file->private_data;
8716 poll_wait(file, &ctx->cq_wait, wait);
8718 * synchronizes with barrier from wq_has_sleeper call in
8722 if (!io_sqring_full(ctx))
8723 mask |= EPOLLOUT | EPOLLWRNORM;
8724 io_cqring_overflow_flush(ctx, false, NULL, NULL);
8725 if (io_cqring_events(ctx))
8726 mask |= EPOLLIN | EPOLLRDNORM;
8731 static int io_uring_fasync(int fd, struct file *file, int on)
8733 struct io_ring_ctx *ctx = file->private_data;
8735 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8738 static int io_remove_personalities(int id, void *p, void *data)
8740 struct io_ring_ctx *ctx = data;
8741 struct io_identity *iod;
8743 iod = idr_remove(&ctx->personality_idr, id);
8745 put_cred(iod->creds);
8746 if (refcount_dec_and_test(&iod->count))
8752 static void io_ring_exit_work(struct work_struct *work)
8754 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
8758 * If we're doing polled IO and end up having requests being
8759 * submitted async (out-of-line), then completions can come in while
8760 * we're waiting for refs to drop. We need to reap these manually,
8761 * as nobody else will be looking for them.
8764 __io_uring_cancel_task_requests(ctx, NULL);
8765 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8766 io_ring_ctx_free(ctx);
8769 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8771 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8773 return req->ctx == data;
8776 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8778 mutex_lock(&ctx->uring_lock);
8779 percpu_ref_kill(&ctx->refs);
8781 if (WARN_ON_ONCE((ctx->flags & IORING_SETUP_SQPOLL) && !ctx->sqo_dead))
8784 /* if force is set, the ring is going away. always drop after that */
8785 ctx->cq_overflow_flushed = 1;
8787 __io_cqring_overflow_flush(ctx, true, NULL, NULL);
8788 mutex_unlock(&ctx->uring_lock);
8790 io_kill_timeouts(ctx, NULL, NULL);
8791 io_poll_remove_all(ctx, NULL, NULL);
8794 io_wq_cancel_cb(ctx->io_wq, io_cancel_ctx_cb, ctx, true);
8796 /* if we failed setting up the ctx, we might not have any rings */
8797 io_iopoll_try_reap_events(ctx);
8798 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
8801 * Do this upfront, so we won't have a grace period where the ring
8802 * is closed but resources aren't reaped yet. This can cause
8803 * spurious failure in setting up a new ring.
8805 io_unaccount_mem(ctx, ring_pages(ctx->sq_entries, ctx->cq_entries),
8808 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8810 * Use system_unbound_wq to avoid spawning tons of event kworkers
8811 * if we're exiting a ton of rings at the same time. It just adds
8812 * noise and overhead, there's no discernable change in runtime
8813 * over using system_wq.
8815 queue_work(system_unbound_wq, &ctx->exit_work);
8818 static int io_uring_release(struct inode *inode, struct file *file)
8820 struct io_ring_ctx *ctx = file->private_data;
8822 file->private_data = NULL;
8823 io_ring_ctx_wait_and_kill(ctx);
8827 struct io_task_cancel {
8828 struct task_struct *task;
8829 struct files_struct *files;
8832 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8834 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8835 struct io_task_cancel *cancel = data;
8838 if (cancel->files && (req->flags & REQ_F_LINK_TIMEOUT)) {
8839 unsigned long flags;
8840 struct io_ring_ctx *ctx = req->ctx;
8842 /* protect against races with linked timeouts */
8843 spin_lock_irqsave(&ctx->completion_lock, flags);
8844 ret = io_match_task(req, cancel->task, cancel->files);
8845 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8847 ret = io_match_task(req, cancel->task, cancel->files);
8852 static void io_cancel_defer_files(struct io_ring_ctx *ctx,
8853 struct task_struct *task,
8854 struct files_struct *files)
8856 struct io_defer_entry *de = NULL;
8859 spin_lock_irq(&ctx->completion_lock);
8860 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8861 if (io_match_task(de->req, task, files)) {
8862 list_cut_position(&list, &ctx->defer_list, &de->list);
8866 spin_unlock_irq(&ctx->completion_lock);
8868 while (!list_empty(&list)) {
8869 de = list_first_entry(&list, struct io_defer_entry, list);
8870 list_del_init(&de->list);
8871 req_set_fail_links(de->req);
8872 io_put_req(de->req);
8873 io_req_complete(de->req, -ECANCELED);
8878 static int io_uring_count_inflight(struct io_ring_ctx *ctx,
8879 struct task_struct *task,
8880 struct files_struct *files)
8882 struct io_kiocb *req;
8885 spin_lock_irq(&ctx->inflight_lock);
8886 list_for_each_entry(req, &ctx->inflight_list, inflight_entry)
8887 cnt += io_match_task(req, task, files);
8888 spin_unlock_irq(&ctx->inflight_lock);
8892 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
8893 struct task_struct *task,
8894 struct files_struct *files)
8896 while (!list_empty_careful(&ctx->inflight_list)) {
8897 struct io_task_cancel cancel = { .task = task, .files = files };
8901 inflight = io_uring_count_inflight(ctx, task, files);
8905 io_wq_cancel_cb(ctx->io_wq, io_cancel_task_cb, &cancel, true);
8906 io_poll_remove_all(ctx, task, files);
8907 io_kill_timeouts(ctx, task, files);
8908 io_cqring_overflow_flush(ctx, true, task, files);
8909 /* cancellations _may_ trigger task work */
8912 prepare_to_wait(&task->io_uring->wait, &wait,
8913 TASK_UNINTERRUPTIBLE);
8914 if (inflight == io_uring_count_inflight(ctx, task, files))
8916 finish_wait(&task->io_uring->wait, &wait);
8920 static void __io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
8921 struct task_struct *task)
8924 struct io_task_cancel cancel = { .task = task, .files = NULL, };
8925 enum io_wq_cancel cret;
8929 cret = io_wq_cancel_cb(ctx->io_wq, io_cancel_task_cb,
8931 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8934 /* SQPOLL thread does its own polling */
8935 if (!(ctx->flags & IORING_SETUP_SQPOLL)) {
8936 while (!list_empty_careful(&ctx->iopoll_list)) {
8937 io_iopoll_try_reap_events(ctx);
8942 ret |= io_poll_remove_all(ctx, task, NULL);
8943 ret |= io_kill_timeouts(ctx, task, NULL);
8944 ret |= io_run_task_work();
8951 static void io_disable_sqo_submit(struct io_ring_ctx *ctx)
8953 mutex_lock(&ctx->uring_lock);
8955 mutex_unlock(&ctx->uring_lock);
8957 /* make sure callers enter the ring to get error */
8959 io_ring_set_wakeup_flag(ctx);
8963 * We need to iteratively cancel requests, in case a request has dependent
8964 * hard links. These persist even for failure of cancelations, hence keep
8965 * looping until none are found.
8967 static void io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
8968 struct files_struct *files)
8970 struct task_struct *task = current;
8972 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
8973 io_disable_sqo_submit(ctx);
8974 task = ctx->sq_data->thread;
8975 atomic_inc(&task->io_uring->in_idle);
8976 io_sq_thread_park(ctx->sq_data);
8979 io_cancel_defer_files(ctx, task, files);
8980 io_cqring_overflow_flush(ctx, true, task, files);
8982 io_uring_cancel_files(ctx, task, files);
8984 __io_uring_cancel_task_requests(ctx, task);
8986 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
8987 atomic_dec(&task->io_uring->in_idle);
8988 io_sq_thread_unpark(ctx->sq_data);
8993 * Note that this task has used io_uring. We use it for cancelation purposes.
8995 static int io_uring_add_task_file(struct io_ring_ctx *ctx, struct file *file)
8997 struct io_uring_task *tctx = current->io_uring;
9000 if (unlikely(!tctx)) {
9001 ret = io_uring_alloc_task_context(current);
9004 tctx = current->io_uring;
9006 if (tctx->last != file) {
9007 void *old = xa_load(&tctx->xa, (unsigned long)file);
9011 ret = xa_err(xa_store(&tctx->xa, (unsigned long)file,
9022 * This is race safe in that the task itself is doing this, hence it
9023 * cannot be going through the exit/cancel paths at the same time.
9024 * This cannot be modified while exit/cancel is running.
9026 if (!tctx->sqpoll && (ctx->flags & IORING_SETUP_SQPOLL))
9027 tctx->sqpoll = true;
9033 * Remove this io_uring_file -> task mapping.
9035 static void io_uring_del_task_file(struct file *file)
9037 struct io_uring_task *tctx = current->io_uring;
9039 if (tctx->last == file)
9041 file = xa_erase(&tctx->xa, (unsigned long)file);
9046 static void io_uring_remove_task_files(struct io_uring_task *tctx)
9049 unsigned long index;
9051 xa_for_each(&tctx->xa, index, file)
9052 io_uring_del_task_file(file);
9055 void __io_uring_files_cancel(struct files_struct *files)
9057 struct io_uring_task *tctx = current->io_uring;
9059 unsigned long index;
9061 /* make sure overflow events are dropped */
9062 atomic_inc(&tctx->in_idle);
9063 xa_for_each(&tctx->xa, index, file)
9064 io_uring_cancel_task_requests(file->private_data, files);
9065 atomic_dec(&tctx->in_idle);
9068 io_uring_remove_task_files(tctx);
9071 static s64 tctx_inflight(struct io_uring_task *tctx)
9073 unsigned long index;
9077 inflight = percpu_counter_sum(&tctx->inflight);
9082 * If we have SQPOLL rings, then we need to iterate and find them, and
9083 * add the pending count for those.
9085 xa_for_each(&tctx->xa, index, file) {
9086 struct io_ring_ctx *ctx = file->private_data;
9088 if (ctx->flags & IORING_SETUP_SQPOLL) {
9089 struct io_uring_task *__tctx = ctx->sqo_task->io_uring;
9091 inflight += percpu_counter_sum(&__tctx->inflight);
9099 * Find any io_uring fd that this task has registered or done IO on, and cancel
9102 void __io_uring_task_cancel(void)
9104 struct io_uring_task *tctx = current->io_uring;
9108 /* make sure overflow events are dropped */
9109 atomic_inc(&tctx->in_idle);
9111 /* trigger io_disable_sqo_submit() */
9113 __io_uring_files_cancel(NULL);
9116 /* read completions before cancelations */
9117 inflight = tctx_inflight(tctx);
9120 __io_uring_files_cancel(NULL);
9122 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9125 * If we've seen completions, retry without waiting. This
9126 * avoids a race where a completion comes in before we did
9127 * prepare_to_wait().
9129 if (inflight == tctx_inflight(tctx))
9131 finish_wait(&tctx->wait, &wait);
9134 atomic_dec(&tctx->in_idle);
9136 io_uring_remove_task_files(tctx);
9139 static int io_uring_flush(struct file *file, void *data)
9141 struct io_uring_task *tctx = current->io_uring;
9142 struct io_ring_ctx *ctx = file->private_data;
9144 if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
9145 io_uring_cancel_task_requests(ctx, NULL);
9150 /* we should have cancelled and erased it before PF_EXITING */
9151 WARN_ON_ONCE((current->flags & PF_EXITING) &&
9152 xa_load(&tctx->xa, (unsigned long)file));
9155 * fput() is pending, will be 2 if the only other ref is our potential
9156 * task file note. If the task is exiting, drop regardless of count.
9158 if (atomic_long_read(&file->f_count) != 2)
9161 if (ctx->flags & IORING_SETUP_SQPOLL) {
9162 /* there is only one file note, which is owned by sqo_task */
9163 WARN_ON_ONCE(ctx->sqo_task != current &&
9164 xa_load(&tctx->xa, (unsigned long)file));
9165 /* sqo_dead check is for when this happens after cancellation */
9166 WARN_ON_ONCE(ctx->sqo_task == current && !ctx->sqo_dead &&
9167 !xa_load(&tctx->xa, (unsigned long)file));
9169 io_disable_sqo_submit(ctx);
9172 if (!(ctx->flags & IORING_SETUP_SQPOLL) || ctx->sqo_task == current)
9173 io_uring_del_task_file(file);
9177 static void *io_uring_validate_mmap_request(struct file *file,
9178 loff_t pgoff, size_t sz)
9180 struct io_ring_ctx *ctx = file->private_data;
9181 loff_t offset = pgoff << PAGE_SHIFT;
9186 case IORING_OFF_SQ_RING:
9187 case IORING_OFF_CQ_RING:
9190 case IORING_OFF_SQES:
9194 return ERR_PTR(-EINVAL);
9197 page = virt_to_head_page(ptr);
9198 if (sz > page_size(page))
9199 return ERR_PTR(-EINVAL);
9206 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9208 size_t sz = vma->vm_end - vma->vm_start;
9212 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9214 return PTR_ERR(ptr);
9216 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9217 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9220 #else /* !CONFIG_MMU */
9222 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9224 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9227 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9229 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9232 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9233 unsigned long addr, unsigned long len,
9234 unsigned long pgoff, unsigned long flags)
9238 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9240 return PTR_ERR(ptr);
9242 return (unsigned long) ptr;
9245 #endif /* !CONFIG_MMU */
9247 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9253 if (!io_sqring_full(ctx))
9256 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9258 if (unlikely(ctx->sqo_dead)) {
9263 if (!io_sqring_full(ctx))
9267 } while (!signal_pending(current));
9269 finish_wait(&ctx->sqo_sq_wait, &wait);
9274 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9275 struct __kernel_timespec __user **ts,
9276 const sigset_t __user **sig)
9278 struct io_uring_getevents_arg arg;
9281 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9282 * is just a pointer to the sigset_t.
9284 if (!(flags & IORING_ENTER_EXT_ARG)) {
9285 *sig = (const sigset_t __user *) argp;
9291 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9292 * timespec and sigset_t pointers if good.
9294 if (*argsz != sizeof(arg))
9296 if (copy_from_user(&arg, argp, sizeof(arg)))
9298 *sig = u64_to_user_ptr(arg.sigmask);
9299 *argsz = arg.sigmask_sz;
9300 *ts = u64_to_user_ptr(arg.ts);
9304 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9305 u32, min_complete, u32, flags, const void __user *, argp,
9308 struct io_ring_ctx *ctx;
9315 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9316 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG))
9324 if (f.file->f_op != &io_uring_fops)
9328 ctx = f.file->private_data;
9329 if (!percpu_ref_tryget(&ctx->refs))
9333 if (ctx->flags & IORING_SETUP_R_DISABLED)
9337 * For SQ polling, the thread will do all submissions and completions.
9338 * Just return the requested submit count, and wake the thread if
9342 if (ctx->flags & IORING_SETUP_SQPOLL) {
9343 io_cqring_overflow_flush(ctx, false, NULL, NULL);
9346 if (unlikely(ctx->sqo_dead))
9348 if (flags & IORING_ENTER_SQ_WAKEUP)
9349 wake_up(&ctx->sq_data->wait);
9350 if (flags & IORING_ENTER_SQ_WAIT) {
9351 ret = io_sqpoll_wait_sq(ctx);
9355 submitted = to_submit;
9356 } else if (to_submit) {
9357 ret = io_uring_add_task_file(ctx, f.file);
9360 mutex_lock(&ctx->uring_lock);
9361 submitted = io_submit_sqes(ctx, to_submit);
9362 mutex_unlock(&ctx->uring_lock);
9364 if (submitted != to_submit)
9367 if (flags & IORING_ENTER_GETEVENTS) {
9368 const sigset_t __user *sig;
9369 struct __kernel_timespec __user *ts;
9371 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9375 min_complete = min(min_complete, ctx->cq_entries);
9378 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9379 * space applications don't need to do io completion events
9380 * polling again, they can rely on io_sq_thread to do polling
9381 * work, which can reduce cpu usage and uring_lock contention.
9383 if (ctx->flags & IORING_SETUP_IOPOLL &&
9384 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9385 ret = io_iopoll_check(ctx, min_complete);
9387 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9392 percpu_ref_put(&ctx->refs);
9395 return submitted ? submitted : ret;
9398 #ifdef CONFIG_PROC_FS
9399 static int io_uring_show_cred(int id, void *p, void *data)
9401 struct io_identity *iod = p;
9402 const struct cred *cred = iod->creds;
9403 struct seq_file *m = data;
9404 struct user_namespace *uns = seq_user_ns(m);
9405 struct group_info *gi;
9410 seq_printf(m, "%5d\n", id);
9411 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9412 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9413 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9414 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9415 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9416 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9417 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9418 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9419 seq_puts(m, "\n\tGroups:\t");
9420 gi = cred->group_info;
9421 for (g = 0; g < gi->ngroups; g++) {
9422 seq_put_decimal_ull(m, g ? " " : "",
9423 from_kgid_munged(uns, gi->gid[g]));
9425 seq_puts(m, "\n\tCapEff:\t");
9426 cap = cred->cap_effective;
9427 CAP_FOR_EACH_U32(__capi)
9428 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9433 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9435 struct io_sq_data *sq = NULL;
9440 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9441 * since fdinfo case grabs it in the opposite direction of normal use
9442 * cases. If we fail to get the lock, we just don't iterate any
9443 * structures that could be going away outside the io_uring mutex.
9445 has_lock = mutex_trylock(&ctx->uring_lock);
9447 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL))
9450 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9451 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9452 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9453 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9454 struct fixed_file_table *table;
9457 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
9458 f = table->files[i & IORING_FILE_TABLE_MASK];
9460 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9462 seq_printf(m, "%5u: <none>\n", i);
9464 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9465 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9466 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
9468 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
9469 (unsigned int) buf->len);
9471 if (has_lock && !idr_is_empty(&ctx->personality_idr)) {
9472 seq_printf(m, "Personalities:\n");
9473 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
9475 seq_printf(m, "PollList:\n");
9476 spin_lock_irq(&ctx->completion_lock);
9477 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9478 struct hlist_head *list = &ctx->cancel_hash[i];
9479 struct io_kiocb *req;
9481 hlist_for_each_entry(req, list, hash_node)
9482 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9483 req->task->task_works != NULL);
9485 spin_unlock_irq(&ctx->completion_lock);
9487 mutex_unlock(&ctx->uring_lock);
9490 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9492 struct io_ring_ctx *ctx = f->private_data;
9494 if (percpu_ref_tryget(&ctx->refs)) {
9495 __io_uring_show_fdinfo(ctx, m);
9496 percpu_ref_put(&ctx->refs);
9501 static const struct file_operations io_uring_fops = {
9502 .release = io_uring_release,
9503 .flush = io_uring_flush,
9504 .mmap = io_uring_mmap,
9506 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9507 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9509 .poll = io_uring_poll,
9510 .fasync = io_uring_fasync,
9511 #ifdef CONFIG_PROC_FS
9512 .show_fdinfo = io_uring_show_fdinfo,
9516 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9517 struct io_uring_params *p)
9519 struct io_rings *rings;
9520 size_t size, sq_array_offset;
9522 /* make sure these are sane, as we already accounted them */
9523 ctx->sq_entries = p->sq_entries;
9524 ctx->cq_entries = p->cq_entries;
9526 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9527 if (size == SIZE_MAX)
9530 rings = io_mem_alloc(size);
9535 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9536 rings->sq_ring_mask = p->sq_entries - 1;
9537 rings->cq_ring_mask = p->cq_entries - 1;
9538 rings->sq_ring_entries = p->sq_entries;
9539 rings->cq_ring_entries = p->cq_entries;
9540 ctx->sq_mask = rings->sq_ring_mask;
9541 ctx->cq_mask = rings->cq_ring_mask;
9543 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9544 if (size == SIZE_MAX) {
9545 io_mem_free(ctx->rings);
9550 ctx->sq_sqes = io_mem_alloc(size);
9551 if (!ctx->sq_sqes) {
9552 io_mem_free(ctx->rings);
9560 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9564 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9568 ret = io_uring_add_task_file(ctx, file);
9573 fd_install(fd, file);
9578 * Allocate an anonymous fd, this is what constitutes the application
9579 * visible backing of an io_uring instance. The application mmaps this
9580 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9581 * we have to tie this fd to a socket for file garbage collection purposes.
9583 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9586 #if defined(CONFIG_UNIX)
9589 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9592 return ERR_PTR(ret);
9595 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9596 O_RDWR | O_CLOEXEC);
9597 #if defined(CONFIG_UNIX)
9599 sock_release(ctx->ring_sock);
9600 ctx->ring_sock = NULL;
9602 ctx->ring_sock->file = file;
9608 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9609 struct io_uring_params __user *params)
9611 struct user_struct *user = NULL;
9612 struct io_ring_ctx *ctx;
9619 if (entries > IORING_MAX_ENTRIES) {
9620 if (!(p->flags & IORING_SETUP_CLAMP))
9622 entries = IORING_MAX_ENTRIES;
9626 * Use twice as many entries for the CQ ring. It's possible for the
9627 * application to drive a higher depth than the size of the SQ ring,
9628 * since the sqes are only used at submission time. This allows for
9629 * some flexibility in overcommitting a bit. If the application has
9630 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9631 * of CQ ring entries manually.
9633 p->sq_entries = roundup_pow_of_two(entries);
9634 if (p->flags & IORING_SETUP_CQSIZE) {
9636 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9637 * to a power-of-two, if it isn't already. We do NOT impose
9638 * any cq vs sq ring sizing.
9642 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9643 if (!(p->flags & IORING_SETUP_CLAMP))
9645 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9647 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9648 if (p->cq_entries < p->sq_entries)
9651 p->cq_entries = 2 * p->sq_entries;
9654 user = get_uid(current_user());
9655 limit_mem = !capable(CAP_IPC_LOCK);
9658 ret = __io_account_mem(user,
9659 ring_pages(p->sq_entries, p->cq_entries));
9666 ctx = io_ring_ctx_alloc(p);
9669 __io_unaccount_mem(user, ring_pages(p->sq_entries,
9674 ctx->compat = in_compat_syscall();
9676 ctx->creds = get_current_cred();
9678 ctx->loginuid = current->loginuid;
9679 ctx->sessionid = current->sessionid;
9681 ctx->sqo_task = get_task_struct(current);
9684 * This is just grabbed for accounting purposes. When a process exits,
9685 * the mm is exited and dropped before the files, hence we need to hang
9686 * on to this mm purely for the purposes of being able to unaccount
9687 * memory (locked/pinned vm). It's not used for anything else.
9689 mmgrab(current->mm);
9690 ctx->mm_account = current->mm;
9692 #ifdef CONFIG_BLK_CGROUP
9694 * The sq thread will belong to the original cgroup it was inited in.
9695 * If the cgroup goes offline (e.g. disabling the io controller), then
9696 * issued bios will be associated with the closest cgroup later in the
9700 ctx->sqo_blkcg_css = blkcg_css();
9701 ret = css_tryget_online(ctx->sqo_blkcg_css);
9704 /* don't init against a dying cgroup, have the user try again */
9705 ctx->sqo_blkcg_css = NULL;
9712 * Account memory _before_ installing the file descriptor. Once
9713 * the descriptor is installed, it can get closed at any time. Also
9714 * do this before hitting the general error path, as ring freeing
9715 * will un-account as well.
9717 io_account_mem(ctx, ring_pages(p->sq_entries, p->cq_entries),
9719 ctx->limit_mem = limit_mem;
9721 ret = io_allocate_scq_urings(ctx, p);
9725 ret = io_sq_offload_create(ctx, p);
9729 if (!(p->flags & IORING_SETUP_R_DISABLED))
9730 io_sq_offload_start(ctx);
9732 memset(&p->sq_off, 0, sizeof(p->sq_off));
9733 p->sq_off.head = offsetof(struct io_rings, sq.head);
9734 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9735 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9736 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9737 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9738 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9739 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9741 memset(&p->cq_off, 0, sizeof(p->cq_off));
9742 p->cq_off.head = offsetof(struct io_rings, cq.head);
9743 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9744 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9745 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9746 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9747 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9748 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9750 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9751 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9752 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9753 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9754 IORING_FEAT_EXT_ARG;
9756 if (copy_to_user(params, p, sizeof(*p))) {
9761 file = io_uring_get_file(ctx);
9763 ret = PTR_ERR(file);
9768 * Install ring fd as the very last thing, so we don't risk someone
9769 * having closed it before we finish setup
9771 ret = io_uring_install_fd(ctx, file);
9773 io_disable_sqo_submit(ctx);
9774 /* fput will clean it up */
9779 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9782 io_disable_sqo_submit(ctx);
9783 io_ring_ctx_wait_and_kill(ctx);
9788 * Sets up an aio uring context, and returns the fd. Applications asks for a
9789 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9790 * params structure passed in.
9792 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9794 struct io_uring_params p;
9797 if (copy_from_user(&p, params, sizeof(p)))
9799 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9804 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9805 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9806 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9807 IORING_SETUP_R_DISABLED))
9810 return io_uring_create(entries, &p, params);
9813 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9814 struct io_uring_params __user *, params)
9816 return io_uring_setup(entries, params);
9819 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9821 struct io_uring_probe *p;
9825 size = struct_size(p, ops, nr_args);
9826 if (size == SIZE_MAX)
9828 p = kzalloc(size, GFP_KERNEL);
9833 if (copy_from_user(p, arg, size))
9836 if (memchr_inv(p, 0, size))
9839 p->last_op = IORING_OP_LAST - 1;
9840 if (nr_args > IORING_OP_LAST)
9841 nr_args = IORING_OP_LAST;
9843 for (i = 0; i < nr_args; i++) {
9845 if (!io_op_defs[i].not_supported)
9846 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9851 if (copy_to_user(arg, p, size))
9858 static int io_register_personality(struct io_ring_ctx *ctx)
9860 struct io_identity *id;
9863 id = kmalloc(sizeof(*id), GFP_KERNEL);
9867 io_init_identity(id);
9868 id->creds = get_current_cred();
9870 ret = idr_alloc_cyclic(&ctx->personality_idr, id, 1, USHRT_MAX, GFP_KERNEL);
9872 put_cred(id->creds);
9878 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9880 struct io_identity *iod;
9882 iod = idr_remove(&ctx->personality_idr, id);
9884 put_cred(iod->creds);
9885 if (refcount_dec_and_test(&iod->count))
9893 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9894 unsigned int nr_args)
9896 struct io_uring_restriction *res;
9900 /* Restrictions allowed only if rings started disabled */
9901 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9904 /* We allow only a single restrictions registration */
9905 if (ctx->restrictions.registered)
9908 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9911 size = array_size(nr_args, sizeof(*res));
9912 if (size == SIZE_MAX)
9915 res = memdup_user(arg, size);
9917 return PTR_ERR(res);
9921 for (i = 0; i < nr_args; i++) {
9922 switch (res[i].opcode) {
9923 case IORING_RESTRICTION_REGISTER_OP:
9924 if (res[i].register_op >= IORING_REGISTER_LAST) {
9929 __set_bit(res[i].register_op,
9930 ctx->restrictions.register_op);
9932 case IORING_RESTRICTION_SQE_OP:
9933 if (res[i].sqe_op >= IORING_OP_LAST) {
9938 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9940 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9941 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9943 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9944 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9953 /* Reset all restrictions if an error happened */
9955 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9957 ctx->restrictions.registered = true;
9963 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9965 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9968 if (ctx->restrictions.registered)
9969 ctx->restricted = 1;
9971 ctx->flags &= ~IORING_SETUP_R_DISABLED;
9973 io_sq_offload_start(ctx);
9978 static bool io_register_op_must_quiesce(int op)
9981 case IORING_UNREGISTER_FILES:
9982 case IORING_REGISTER_FILES_UPDATE:
9983 case IORING_REGISTER_PROBE:
9984 case IORING_REGISTER_PERSONALITY:
9985 case IORING_UNREGISTER_PERSONALITY:
9992 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
9993 void __user *arg, unsigned nr_args)
9994 __releases(ctx->uring_lock)
9995 __acquires(ctx->uring_lock)
10000 * We're inside the ring mutex, if the ref is already dying, then
10001 * someone else killed the ctx or is already going through
10002 * io_uring_register().
10004 if (percpu_ref_is_dying(&ctx->refs))
10007 if (io_register_op_must_quiesce(opcode)) {
10008 percpu_ref_kill(&ctx->refs);
10011 * Drop uring mutex before waiting for references to exit. If
10012 * another thread is currently inside io_uring_enter() it might
10013 * need to grab the uring_lock to make progress. If we hold it
10014 * here across the drain wait, then we can deadlock. It's safe
10015 * to drop the mutex here, since no new references will come in
10016 * after we've killed the percpu ref.
10018 mutex_unlock(&ctx->uring_lock);
10020 ret = wait_for_completion_interruptible(&ctx->ref_comp);
10023 ret = io_run_task_work_sig();
10028 mutex_lock(&ctx->uring_lock);
10031 percpu_ref_resurrect(&ctx->refs);
10036 if (ctx->restricted) {
10037 if (opcode >= IORING_REGISTER_LAST) {
10042 if (!test_bit(opcode, ctx->restrictions.register_op)) {
10049 case IORING_REGISTER_BUFFERS:
10050 ret = io_sqe_buffer_register(ctx, arg, nr_args);
10052 case IORING_UNREGISTER_BUFFERS:
10054 if (arg || nr_args)
10056 ret = io_sqe_buffer_unregister(ctx);
10058 case IORING_REGISTER_FILES:
10059 ret = io_sqe_files_register(ctx, arg, nr_args);
10061 case IORING_UNREGISTER_FILES:
10063 if (arg || nr_args)
10065 ret = io_sqe_files_unregister(ctx);
10067 case IORING_REGISTER_FILES_UPDATE:
10068 ret = io_sqe_files_update(ctx, arg, nr_args);
10070 case IORING_REGISTER_EVENTFD:
10071 case IORING_REGISTER_EVENTFD_ASYNC:
10075 ret = io_eventfd_register(ctx, arg);
10078 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10079 ctx->eventfd_async = 1;
10081 ctx->eventfd_async = 0;
10083 case IORING_UNREGISTER_EVENTFD:
10085 if (arg || nr_args)
10087 ret = io_eventfd_unregister(ctx);
10089 case IORING_REGISTER_PROBE:
10091 if (!arg || nr_args > 256)
10093 ret = io_probe(ctx, arg, nr_args);
10095 case IORING_REGISTER_PERSONALITY:
10097 if (arg || nr_args)
10099 ret = io_register_personality(ctx);
10101 case IORING_UNREGISTER_PERSONALITY:
10105 ret = io_unregister_personality(ctx, nr_args);
10107 case IORING_REGISTER_ENABLE_RINGS:
10109 if (arg || nr_args)
10111 ret = io_register_enable_rings(ctx);
10113 case IORING_REGISTER_RESTRICTIONS:
10114 ret = io_register_restrictions(ctx, arg, nr_args);
10122 if (io_register_op_must_quiesce(opcode)) {
10123 /* bring the ctx back to life */
10124 percpu_ref_reinit(&ctx->refs);
10126 reinit_completion(&ctx->ref_comp);
10131 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10132 void __user *, arg, unsigned int, nr_args)
10134 struct io_ring_ctx *ctx;
10143 if (f.file->f_op != &io_uring_fops)
10146 ctx = f.file->private_data;
10148 mutex_lock(&ctx->uring_lock);
10149 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10150 mutex_unlock(&ctx->uring_lock);
10151 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10152 ctx->cq_ev_fd != NULL, ret);
10158 static int __init io_uring_init(void)
10160 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10161 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10162 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10165 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10166 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10167 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10168 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10169 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10170 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10171 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10172 BUILD_BUG_SQE_ELEM(8, __u64, off);
10173 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10174 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10175 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10176 BUILD_BUG_SQE_ELEM(24, __u32, len);
10177 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10178 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10179 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10180 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10181 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10182 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10183 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10184 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10185 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10186 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10187 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10188 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10189 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10190 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10191 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10192 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10193 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10194 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10195 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10197 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10198 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10199 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
10202 __initcall(io_uring_init);