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_cqe (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/blkdev.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
64 #include <net/af_unix.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72 #include <linux/highmem.h>
73 #include <linux/namei.h>
74 #include <linux/fsnotify.h>
75 #include <linux/fadvise.h>
76 #include <linux/eventpoll.h>
77 #include <linux/splice.h>
78 #include <linux/task_work.h>
79 #include <linux/pagemap.h>
80 #include <linux/io_uring.h>
81 #include <linux/tracehook.h>
83 #define CREATE_TRACE_POINTS
84 #include <trace/events/io_uring.h>
86 #include <uapi/linux/io_uring.h>
91 #define IORING_MAX_ENTRIES 32768
92 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
93 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
96 #define IORING_MAX_FIXED_FILES (1U << 15)
97 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
98 IORING_REGISTER_LAST + IORING_OP_LAST)
100 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
101 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
102 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
104 #define IORING_MAX_REG_BUFFERS (1U << 14)
106 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
107 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
109 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
110 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS)
112 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
115 u32 head ____cacheline_aligned_in_smp;
116 u32 tail ____cacheline_aligned_in_smp;
120 * This data is shared with the application through the mmap at offsets
121 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
123 * The offsets to the member fields are published through struct
124 * io_sqring_offsets when calling io_uring_setup.
128 * Head and tail offsets into the ring; the offsets need to be
129 * masked to get valid indices.
131 * The kernel controls head of the sq ring and the tail of the cq ring,
132 * and the application controls tail of the sq ring and the head of the
135 struct io_uring sq, cq;
137 * Bitmasks to apply to head and tail offsets (constant, equals
140 u32 sq_ring_mask, cq_ring_mask;
141 /* Ring sizes (constant, power of 2) */
142 u32 sq_ring_entries, cq_ring_entries;
144 * Number of invalid entries dropped by the kernel due to
145 * invalid index stored in array
147 * Written by the kernel, shouldn't be modified by the
148 * application (i.e. get number of "new events" by comparing to
151 * After a new SQ head value was read by the application this
152 * counter includes all submissions that were dropped reaching
153 * the new SQ head (and possibly more).
159 * Written by the kernel, shouldn't be modified by the
162 * The application needs a full memory barrier before checking
163 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
169 * Written by the application, shouldn't be modified by the
174 * Number of completion events lost because the queue was full;
175 * this should be avoided by the application by making sure
176 * there are not more requests pending than there is space in
177 * the completion queue.
179 * Written by the kernel, shouldn't be modified by the
180 * application (i.e. get number of "new events" by comparing to
183 * As completion events come in out of order this counter is not
184 * ordered with any other data.
188 * Ring buffer of completion events.
190 * The kernel writes completion events fresh every time they are
191 * produced, so the application is allowed to modify pending
194 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
197 enum io_uring_cmd_flags {
198 IO_URING_F_NONBLOCK = 1,
199 IO_URING_F_COMPLETE_DEFER = 2,
202 struct io_mapped_ubuf {
205 unsigned int nr_bvecs;
206 unsigned long acct_pages;
207 struct bio_vec bvec[];
212 struct io_overflow_cqe {
213 struct io_uring_cqe cqe;
214 struct list_head list;
217 struct io_fixed_file {
218 /* file * with additional FFS_* flags */
219 unsigned long file_ptr;
223 struct list_head list;
228 struct io_mapped_ubuf *buf;
232 struct io_file_table {
233 struct io_fixed_file *files;
236 struct io_rsrc_node {
237 struct percpu_ref refs;
238 struct list_head node;
239 struct list_head rsrc_list;
240 struct io_rsrc_data *rsrc_data;
241 struct llist_node llist;
245 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
247 struct io_rsrc_data {
248 struct io_ring_ctx *ctx;
254 struct completion done;
259 struct list_head list;
265 struct io_restriction {
266 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
267 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
268 u8 sqe_flags_allowed;
269 u8 sqe_flags_required;
274 IO_SQ_THREAD_SHOULD_STOP = 0,
275 IO_SQ_THREAD_SHOULD_PARK,
280 atomic_t park_pending;
283 /* ctx's that are using this sqd */
284 struct list_head ctx_list;
286 struct task_struct *thread;
287 struct wait_queue_head wait;
289 unsigned sq_thread_idle;
295 struct completion exited;
298 #define IO_COMPL_BATCH 32
299 #define IO_REQ_CACHE_SIZE 32
300 #define IO_REQ_ALLOC_BATCH 8
302 struct io_submit_link {
303 struct io_kiocb *head;
304 struct io_kiocb *last;
307 struct io_submit_state {
308 struct blk_plug plug;
309 struct io_submit_link link;
312 * io_kiocb alloc cache
314 void *reqs[IO_REQ_CACHE_SIZE];
315 unsigned int free_reqs;
320 * Batch completion logic
322 struct io_kiocb *compl_reqs[IO_COMPL_BATCH];
323 unsigned int compl_nr;
324 /* inline/task_work completion list, under ->uring_lock */
325 struct list_head free_list;
327 unsigned int ios_left;
331 /* const or read-mostly hot data */
333 struct percpu_ref refs;
335 struct io_rings *rings;
337 unsigned int compat: 1;
338 unsigned int drain_next: 1;
339 unsigned int eventfd_async: 1;
340 unsigned int restricted: 1;
341 unsigned int off_timeout_used: 1;
342 unsigned int drain_active: 1;
343 } ____cacheline_aligned_in_smp;
345 /* submission data */
347 struct mutex uring_lock;
350 * Ring buffer of indices into array of io_uring_sqe, which is
351 * mmapped by the application using the IORING_OFF_SQES offset.
353 * This indirection could e.g. be used to assign fixed
354 * io_uring_sqe entries to operations and only submit them to
355 * the queue when needed.
357 * The kernel modifies neither the indices array nor the entries
361 struct io_uring_sqe *sq_sqes;
362 unsigned cached_sq_head;
364 struct list_head defer_list;
367 * Fixed resources fast path, should be accessed only under
368 * uring_lock, and updated through io_uring_register(2)
370 struct io_rsrc_node *rsrc_node;
371 struct io_file_table file_table;
372 unsigned nr_user_files;
373 unsigned nr_user_bufs;
374 struct io_mapped_ubuf **user_bufs;
376 struct io_submit_state submit_state;
377 struct list_head timeout_list;
378 struct list_head ltimeout_list;
379 struct list_head cq_overflow_list;
380 struct xarray io_buffers;
381 struct xarray personalities;
383 unsigned sq_thread_idle;
384 } ____cacheline_aligned_in_smp;
386 /* IRQ completion list, under ->completion_lock */
387 struct list_head locked_free_list;
388 unsigned int locked_free_nr;
390 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
391 struct io_sq_data *sq_data; /* if using sq thread polling */
393 struct wait_queue_head sqo_sq_wait;
394 struct list_head sqd_list;
396 unsigned long check_cq_overflow;
399 unsigned cached_cq_tail;
401 struct eventfd_ctx *cq_ev_fd;
402 struct wait_queue_head poll_wait;
403 struct wait_queue_head cq_wait;
405 atomic_t cq_timeouts;
406 struct fasync_struct *cq_fasync;
407 unsigned cq_last_tm_flush;
408 } ____cacheline_aligned_in_smp;
411 spinlock_t completion_lock;
413 spinlock_t timeout_lock;
416 * ->iopoll_list is protected by the ctx->uring_lock for
417 * io_uring instances that don't use IORING_SETUP_SQPOLL.
418 * For SQPOLL, only the single threaded io_sq_thread() will
419 * manipulate the list, hence no extra locking is needed there.
421 struct list_head iopoll_list;
422 struct hlist_head *cancel_hash;
423 unsigned cancel_hash_bits;
424 bool poll_multi_queue;
425 } ____cacheline_aligned_in_smp;
427 struct io_restriction restrictions;
429 /* slow path rsrc auxilary data, used by update/register */
431 struct io_rsrc_node *rsrc_backup_node;
432 struct io_mapped_ubuf *dummy_ubuf;
433 struct io_rsrc_data *file_data;
434 struct io_rsrc_data *buf_data;
436 struct delayed_work rsrc_put_work;
437 struct llist_head rsrc_put_llist;
438 struct list_head rsrc_ref_list;
439 spinlock_t rsrc_ref_lock;
442 /* Keep this last, we don't need it for the fast path */
444 #if defined(CONFIG_UNIX)
445 struct socket *ring_sock;
447 /* hashed buffered write serialization */
448 struct io_wq_hash *hash_map;
450 /* Only used for accounting purposes */
451 struct user_struct *user;
452 struct mm_struct *mm_account;
454 /* ctx exit and cancelation */
455 struct llist_head fallback_llist;
456 struct delayed_work fallback_work;
457 struct work_struct exit_work;
458 struct list_head tctx_list;
459 struct completion ref_comp;
463 struct io_uring_task {
464 /* submission side */
467 struct wait_queue_head wait;
468 const struct io_ring_ctx *last;
470 struct percpu_counter inflight;
471 atomic_t inflight_tracked;
474 spinlock_t task_lock;
475 struct io_wq_work_list task_list;
476 struct callback_head task_work;
481 * First field must be the file pointer in all the
482 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
484 struct io_poll_iocb {
486 struct wait_queue_head *head;
490 struct wait_queue_entry wait;
493 struct io_poll_update {
499 bool update_user_data;
507 struct io_timeout_data {
508 struct io_kiocb *req;
509 struct hrtimer timer;
510 struct timespec64 ts;
511 enum hrtimer_mode mode;
517 struct sockaddr __user *addr;
518 int __user *addr_len;
521 unsigned long nofile;
541 struct list_head list;
542 /* head of the link, used by linked timeouts only */
543 struct io_kiocb *head;
544 /* for linked completions */
545 struct io_kiocb *prev;
548 struct io_timeout_rem {
553 struct timespec64 ts;
559 /* NOTE: kiocb has the file as the first member, so don't do it here */
567 struct sockaddr __user *addr;
574 struct compat_msghdr __user *umsg_compat;
575 struct user_msghdr __user *umsg;
581 struct io_buffer *kbuf;
588 struct filename *filename;
590 unsigned long nofile;
593 struct io_rsrc_update {
619 struct epoll_event event;
623 struct file *file_out;
624 struct file *file_in;
631 struct io_provide_buf {
645 const char __user *filename;
646 struct statx __user *buffer;
658 struct filename *oldpath;
659 struct filename *newpath;
667 struct filename *filename;
674 struct filename *filename;
680 struct filename *oldpath;
681 struct filename *newpath;
688 struct filename *oldpath;
689 struct filename *newpath;
693 struct io_completion {
698 struct io_async_connect {
699 struct sockaddr_storage address;
702 struct io_async_msghdr {
703 struct iovec fast_iov[UIO_FASTIOV];
704 /* points to an allocated iov, if NULL we use fast_iov instead */
705 struct iovec *free_iov;
706 struct sockaddr __user *uaddr;
708 struct sockaddr_storage addr;
712 struct iovec fast_iov[UIO_FASTIOV];
713 const struct iovec *free_iovec;
714 struct iov_iter iter;
716 struct wait_page_queue wpq;
720 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
721 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
722 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
723 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
724 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
725 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
727 /* first byte is taken by user flags, shift it to not overlap */
732 REQ_F_LINK_TIMEOUT_BIT,
733 REQ_F_NEED_CLEANUP_BIT,
735 REQ_F_BUFFER_SELECTED_BIT,
736 REQ_F_COMPLETE_INLINE_BIT,
738 REQ_F_DONT_REISSUE_BIT,
741 REQ_F_ARM_LTIMEOUT_BIT,
742 /* keep async read/write and isreg together and in order */
743 REQ_F_NOWAIT_READ_BIT,
744 REQ_F_NOWAIT_WRITE_BIT,
747 /* not a real bit, just to check we're not overflowing the space */
753 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
754 /* drain existing IO first */
755 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
757 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
758 /* doesn't sever on completion < 0 */
759 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
761 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
762 /* IOSQE_BUFFER_SELECT */
763 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
765 /* fail rest of links */
766 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
767 /* on inflight list, should be cancelled and waited on exit reliably */
768 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
769 /* read/write uses file position */
770 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
771 /* must not punt to workers */
772 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
773 /* has or had linked timeout */
774 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
776 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
777 /* already went through poll handler */
778 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
779 /* buffer already selected */
780 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
781 /* completion is deferred through io_comp_state */
782 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
783 /* caller should reissue async */
784 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
785 /* don't attempt request reissue, see io_rw_reissue() */
786 REQ_F_DONT_REISSUE = BIT(REQ_F_DONT_REISSUE_BIT),
787 /* supports async reads */
788 REQ_F_NOWAIT_READ = BIT(REQ_F_NOWAIT_READ_BIT),
789 /* supports async writes */
790 REQ_F_NOWAIT_WRITE = BIT(REQ_F_NOWAIT_WRITE_BIT),
792 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
793 /* has creds assigned */
794 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
795 /* skip refcounting if not set */
796 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
797 /* there is a linked timeout that has to be armed */
798 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
802 struct io_poll_iocb poll;
803 struct io_poll_iocb *double_poll;
806 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
808 struct io_task_work {
810 struct io_wq_work_node node;
811 struct llist_node fallback_node;
813 io_req_tw_func_t func;
817 IORING_RSRC_FILE = 0,
818 IORING_RSRC_BUFFER = 1,
822 * NOTE! Each of the iocb union members has the file pointer
823 * as the first entry in their struct definition. So you can
824 * access the file pointer through any of the sub-structs,
825 * or directly as just 'ki_filp' in this struct.
831 struct io_poll_iocb poll;
832 struct io_poll_update poll_update;
833 struct io_accept accept;
835 struct io_cancel cancel;
836 struct io_timeout timeout;
837 struct io_timeout_rem timeout_rem;
838 struct io_connect connect;
839 struct io_sr_msg sr_msg;
841 struct io_close close;
842 struct io_rsrc_update rsrc_update;
843 struct io_fadvise fadvise;
844 struct io_madvise madvise;
845 struct io_epoll epoll;
846 struct io_splice splice;
847 struct io_provide_buf pbuf;
848 struct io_statx statx;
849 struct io_shutdown shutdown;
850 struct io_rename rename;
851 struct io_unlink unlink;
852 struct io_mkdir mkdir;
853 struct io_symlink symlink;
854 struct io_hardlink hardlink;
855 /* use only after cleaning per-op data, see io_clean_op() */
856 struct io_completion compl;
859 /* opcode allocated if it needs to store data for async defer */
862 /* polled IO has completed */
868 struct io_ring_ctx *ctx;
871 struct task_struct *task;
874 struct io_kiocb *link;
875 struct percpu_ref *fixed_rsrc_refs;
877 /* used with ctx->iopoll_list with reads/writes */
878 struct list_head inflight_entry;
879 struct io_task_work io_task_work;
880 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
881 struct hlist_node hash_node;
882 struct async_poll *apoll;
883 struct io_wq_work work;
884 const struct cred *creds;
886 /* store used ubuf, so we can prevent reloading */
887 struct io_mapped_ubuf *imu;
890 struct io_tctx_node {
891 struct list_head ctx_node;
892 struct task_struct *task;
893 struct io_ring_ctx *ctx;
896 struct io_defer_entry {
897 struct list_head list;
898 struct io_kiocb *req;
903 /* needs req->file assigned */
904 unsigned needs_file : 1;
905 /* hash wq insertion if file is a regular file */
906 unsigned hash_reg_file : 1;
907 /* unbound wq insertion if file is a non-regular file */
908 unsigned unbound_nonreg_file : 1;
909 /* opcode is not supported by this kernel */
910 unsigned not_supported : 1;
911 /* set if opcode supports polled "wait" */
913 unsigned pollout : 1;
914 /* op supports buffer selection */
915 unsigned buffer_select : 1;
916 /* do prep async if is going to be punted */
917 unsigned needs_async_setup : 1;
918 /* should block plug */
920 /* size of async data needed, if any */
921 unsigned short async_size;
924 static const struct io_op_def io_op_defs[] = {
925 [IORING_OP_NOP] = {},
926 [IORING_OP_READV] = {
928 .unbound_nonreg_file = 1,
931 .needs_async_setup = 1,
933 .async_size = sizeof(struct io_async_rw),
935 [IORING_OP_WRITEV] = {
938 .unbound_nonreg_file = 1,
940 .needs_async_setup = 1,
942 .async_size = sizeof(struct io_async_rw),
944 [IORING_OP_FSYNC] = {
947 [IORING_OP_READ_FIXED] = {
949 .unbound_nonreg_file = 1,
952 .async_size = sizeof(struct io_async_rw),
954 [IORING_OP_WRITE_FIXED] = {
957 .unbound_nonreg_file = 1,
960 .async_size = sizeof(struct io_async_rw),
962 [IORING_OP_POLL_ADD] = {
964 .unbound_nonreg_file = 1,
966 [IORING_OP_POLL_REMOVE] = {},
967 [IORING_OP_SYNC_FILE_RANGE] = {
970 [IORING_OP_SENDMSG] = {
972 .unbound_nonreg_file = 1,
974 .needs_async_setup = 1,
975 .async_size = sizeof(struct io_async_msghdr),
977 [IORING_OP_RECVMSG] = {
979 .unbound_nonreg_file = 1,
982 .needs_async_setup = 1,
983 .async_size = sizeof(struct io_async_msghdr),
985 [IORING_OP_TIMEOUT] = {
986 .async_size = sizeof(struct io_timeout_data),
988 [IORING_OP_TIMEOUT_REMOVE] = {
989 /* used by timeout updates' prep() */
991 [IORING_OP_ACCEPT] = {
993 .unbound_nonreg_file = 1,
996 [IORING_OP_ASYNC_CANCEL] = {},
997 [IORING_OP_LINK_TIMEOUT] = {
998 .async_size = sizeof(struct io_timeout_data),
1000 [IORING_OP_CONNECT] = {
1002 .unbound_nonreg_file = 1,
1004 .needs_async_setup = 1,
1005 .async_size = sizeof(struct io_async_connect),
1007 [IORING_OP_FALLOCATE] = {
1010 [IORING_OP_OPENAT] = {},
1011 [IORING_OP_CLOSE] = {},
1012 [IORING_OP_FILES_UPDATE] = {},
1013 [IORING_OP_STATX] = {},
1014 [IORING_OP_READ] = {
1016 .unbound_nonreg_file = 1,
1020 .async_size = sizeof(struct io_async_rw),
1022 [IORING_OP_WRITE] = {
1025 .unbound_nonreg_file = 1,
1028 .async_size = sizeof(struct io_async_rw),
1030 [IORING_OP_FADVISE] = {
1033 [IORING_OP_MADVISE] = {},
1034 [IORING_OP_SEND] = {
1036 .unbound_nonreg_file = 1,
1039 [IORING_OP_RECV] = {
1041 .unbound_nonreg_file = 1,
1045 [IORING_OP_OPENAT2] = {
1047 [IORING_OP_EPOLL_CTL] = {
1048 .unbound_nonreg_file = 1,
1050 [IORING_OP_SPLICE] = {
1053 .unbound_nonreg_file = 1,
1055 [IORING_OP_PROVIDE_BUFFERS] = {},
1056 [IORING_OP_REMOVE_BUFFERS] = {},
1060 .unbound_nonreg_file = 1,
1062 [IORING_OP_SHUTDOWN] = {
1065 [IORING_OP_RENAMEAT] = {},
1066 [IORING_OP_UNLINKAT] = {},
1067 [IORING_OP_MKDIRAT] = {},
1068 [IORING_OP_SYMLINKAT] = {},
1069 [IORING_OP_LINKAT] = {},
1072 /* requests with any of those set should undergo io_disarm_next() */
1073 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1075 static bool io_disarm_next(struct io_kiocb *req);
1076 static void io_uring_del_tctx_node(unsigned long index);
1077 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1078 struct task_struct *task,
1080 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1082 static bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1083 long res, unsigned int cflags);
1084 static void io_put_req(struct io_kiocb *req);
1085 static void io_put_req_deferred(struct io_kiocb *req);
1086 static void io_dismantle_req(struct io_kiocb *req);
1087 static void io_queue_linked_timeout(struct io_kiocb *req);
1088 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1089 struct io_uring_rsrc_update2 *up,
1091 static void io_clean_op(struct io_kiocb *req);
1092 static struct file *io_file_get(struct io_ring_ctx *ctx,
1093 struct io_kiocb *req, int fd, bool fixed);
1094 static void __io_queue_sqe(struct io_kiocb *req);
1095 static void io_rsrc_put_work(struct work_struct *work);
1097 static void io_req_task_queue(struct io_kiocb *req);
1098 static void io_submit_flush_completions(struct io_ring_ctx *ctx);
1099 static int io_req_prep_async(struct io_kiocb *req);
1101 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1102 unsigned int issue_flags, u32 slot_index);
1103 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1105 static struct kmem_cache *req_cachep;
1107 static const struct file_operations io_uring_fops;
1109 struct sock *io_uring_get_socket(struct file *file)
1111 #if defined(CONFIG_UNIX)
1112 if (file->f_op == &io_uring_fops) {
1113 struct io_ring_ctx *ctx = file->private_data;
1115 return ctx->ring_sock->sk;
1120 EXPORT_SYMBOL(io_uring_get_socket);
1122 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1125 mutex_lock(&ctx->uring_lock);
1130 #define io_for_each_link(pos, head) \
1131 for (pos = (head); pos; pos = pos->link)
1134 * Shamelessly stolen from the mm implementation of page reference checking,
1135 * see commit f958d7b528b1 for details.
1137 #define req_ref_zero_or_close_to_overflow(req) \
1138 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1140 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1142 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1143 return atomic_inc_not_zero(&req->refs);
1146 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1148 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1151 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1152 return atomic_dec_and_test(&req->refs);
1155 static inline void req_ref_put(struct io_kiocb *req)
1157 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1158 WARN_ON_ONCE(req_ref_put_and_test(req));
1161 static inline void req_ref_get(struct io_kiocb *req)
1163 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1164 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1165 atomic_inc(&req->refs);
1168 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1170 if (!(req->flags & REQ_F_REFCOUNT)) {
1171 req->flags |= REQ_F_REFCOUNT;
1172 atomic_set(&req->refs, nr);
1176 static inline void io_req_set_refcount(struct io_kiocb *req)
1178 __io_req_set_refcount(req, 1);
1181 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1183 struct io_ring_ctx *ctx = req->ctx;
1185 if (!req->fixed_rsrc_refs) {
1186 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1187 percpu_ref_get(req->fixed_rsrc_refs);
1191 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1193 bool got = percpu_ref_tryget(ref);
1195 /* already at zero, wait for ->release() */
1197 wait_for_completion(compl);
1198 percpu_ref_resurrect(ref);
1200 percpu_ref_put(ref);
1203 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1206 struct io_kiocb *req;
1208 if (task && head->task != task)
1213 io_for_each_link(req, head) {
1214 if (req->flags & REQ_F_INFLIGHT)
1220 static inline void req_set_fail(struct io_kiocb *req)
1222 req->flags |= REQ_F_FAIL;
1225 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1231 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1233 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1235 complete(&ctx->ref_comp);
1238 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1240 return !req->timeout.off;
1243 static void io_fallback_req_func(struct work_struct *work)
1245 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1246 fallback_work.work);
1247 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1248 struct io_kiocb *req, *tmp;
1249 bool locked = false;
1251 percpu_ref_get(&ctx->refs);
1252 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1253 req->io_task_work.func(req, &locked);
1256 if (ctx->submit_state.compl_nr)
1257 io_submit_flush_completions(ctx);
1258 mutex_unlock(&ctx->uring_lock);
1260 percpu_ref_put(&ctx->refs);
1264 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1266 struct io_ring_ctx *ctx;
1269 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1274 * Use 5 bits less than the max cq entries, that should give us around
1275 * 32 entries per hash list if totally full and uniformly spread.
1277 hash_bits = ilog2(p->cq_entries);
1281 ctx->cancel_hash_bits = hash_bits;
1282 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1284 if (!ctx->cancel_hash)
1286 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1288 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1289 if (!ctx->dummy_ubuf)
1291 /* set invalid range, so io_import_fixed() fails meeting it */
1292 ctx->dummy_ubuf->ubuf = -1UL;
1294 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1295 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1298 ctx->flags = p->flags;
1299 init_waitqueue_head(&ctx->sqo_sq_wait);
1300 INIT_LIST_HEAD(&ctx->sqd_list);
1301 init_waitqueue_head(&ctx->poll_wait);
1302 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1303 init_completion(&ctx->ref_comp);
1304 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1305 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1306 mutex_init(&ctx->uring_lock);
1307 init_waitqueue_head(&ctx->cq_wait);
1308 spin_lock_init(&ctx->completion_lock);
1309 spin_lock_init(&ctx->timeout_lock);
1310 INIT_LIST_HEAD(&ctx->iopoll_list);
1311 INIT_LIST_HEAD(&ctx->defer_list);
1312 INIT_LIST_HEAD(&ctx->timeout_list);
1313 INIT_LIST_HEAD(&ctx->ltimeout_list);
1314 spin_lock_init(&ctx->rsrc_ref_lock);
1315 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1316 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1317 init_llist_head(&ctx->rsrc_put_llist);
1318 INIT_LIST_HEAD(&ctx->tctx_list);
1319 INIT_LIST_HEAD(&ctx->submit_state.free_list);
1320 INIT_LIST_HEAD(&ctx->locked_free_list);
1321 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1324 kfree(ctx->dummy_ubuf);
1325 kfree(ctx->cancel_hash);
1330 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1332 struct io_rings *r = ctx->rings;
1334 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1338 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1340 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1341 struct io_ring_ctx *ctx = req->ctx;
1343 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1349 #define FFS_ASYNC_READ 0x1UL
1350 #define FFS_ASYNC_WRITE 0x2UL
1352 #define FFS_ISREG 0x4UL
1354 #define FFS_ISREG 0x0UL
1356 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
1358 static inline bool io_req_ffs_set(struct io_kiocb *req)
1360 return IS_ENABLED(CONFIG_64BIT) && (req->flags & REQ_F_FIXED_FILE);
1363 static void io_req_track_inflight(struct io_kiocb *req)
1365 if (!(req->flags & REQ_F_INFLIGHT)) {
1366 req->flags |= REQ_F_INFLIGHT;
1367 atomic_inc(¤t->io_uring->inflight_tracked);
1371 static inline void io_unprep_linked_timeout(struct io_kiocb *req)
1373 req->flags &= ~REQ_F_LINK_TIMEOUT;
1376 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1378 if (WARN_ON_ONCE(!req->link))
1381 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1382 req->flags |= REQ_F_LINK_TIMEOUT;
1384 /* linked timeouts should have two refs once prep'ed */
1385 io_req_set_refcount(req);
1386 __io_req_set_refcount(req->link, 2);
1390 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1392 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1394 return __io_prep_linked_timeout(req);
1397 static void io_prep_async_work(struct io_kiocb *req)
1399 const struct io_op_def *def = &io_op_defs[req->opcode];
1400 struct io_ring_ctx *ctx = req->ctx;
1402 if (!(req->flags & REQ_F_CREDS)) {
1403 req->flags |= REQ_F_CREDS;
1404 req->creds = get_current_cred();
1407 req->work.list.next = NULL;
1408 req->work.flags = 0;
1409 if (req->flags & REQ_F_FORCE_ASYNC)
1410 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1412 if (req->flags & REQ_F_ISREG) {
1413 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1414 io_wq_hash_work(&req->work, file_inode(req->file));
1415 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1416 if (def->unbound_nonreg_file)
1417 req->work.flags |= IO_WQ_WORK_UNBOUND;
1420 switch (req->opcode) {
1421 case IORING_OP_SPLICE:
1423 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1424 req->work.flags |= IO_WQ_WORK_UNBOUND;
1429 static void io_prep_async_link(struct io_kiocb *req)
1431 struct io_kiocb *cur;
1433 if (req->flags & REQ_F_LINK_TIMEOUT) {
1434 struct io_ring_ctx *ctx = req->ctx;
1436 spin_lock(&ctx->completion_lock);
1437 io_for_each_link(cur, req)
1438 io_prep_async_work(cur);
1439 spin_unlock(&ctx->completion_lock);
1441 io_for_each_link(cur, req)
1442 io_prep_async_work(cur);
1446 static void io_queue_async_work(struct io_kiocb *req, bool *locked)
1448 struct io_ring_ctx *ctx = req->ctx;
1449 struct io_kiocb *link = io_prep_linked_timeout(req);
1450 struct io_uring_task *tctx = req->task->io_uring;
1452 /* must not take the lock, NULL it as a precaution */
1456 BUG_ON(!tctx->io_wq);
1458 /* init ->work of the whole link before punting */
1459 io_prep_async_link(req);
1462 * Not expected to happen, but if we do have a bug where this _can_
1463 * happen, catch it here and ensure the request is marked as
1464 * canceled. That will make io-wq go through the usual work cancel
1465 * procedure rather than attempt to run this request (or create a new
1468 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1469 req->work.flags |= IO_WQ_WORK_CANCEL;
1471 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1472 &req->work, req->flags);
1473 io_wq_enqueue(tctx->io_wq, &req->work);
1475 io_queue_linked_timeout(link);
1478 static void io_kill_timeout(struct io_kiocb *req, int status)
1479 __must_hold(&req->ctx->completion_lock)
1480 __must_hold(&req->ctx->timeout_lock)
1482 struct io_timeout_data *io = req->async_data;
1484 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1485 atomic_set(&req->ctx->cq_timeouts,
1486 atomic_read(&req->ctx->cq_timeouts) + 1);
1487 list_del_init(&req->timeout.list);
1488 io_cqring_fill_event(req->ctx, req->user_data, status, 0);
1489 io_put_req_deferred(req);
1493 static void io_queue_deferred(struct io_ring_ctx *ctx)
1495 while (!list_empty(&ctx->defer_list)) {
1496 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1497 struct io_defer_entry, list);
1499 if (req_need_defer(de->req, de->seq))
1501 list_del_init(&de->list);
1502 io_req_task_queue(de->req);
1507 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1508 __must_hold(&ctx->completion_lock)
1510 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1512 spin_lock_irq(&ctx->timeout_lock);
1513 while (!list_empty(&ctx->timeout_list)) {
1514 u32 events_needed, events_got;
1515 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1516 struct io_kiocb, timeout.list);
1518 if (io_is_timeout_noseq(req))
1522 * Since seq can easily wrap around over time, subtract
1523 * the last seq at which timeouts were flushed before comparing.
1524 * Assuming not more than 2^31-1 events have happened since,
1525 * these subtractions won't have wrapped, so we can check if
1526 * target is in [last_seq, current_seq] by comparing the two.
1528 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1529 events_got = seq - ctx->cq_last_tm_flush;
1530 if (events_got < events_needed)
1533 list_del_init(&req->timeout.list);
1534 io_kill_timeout(req, 0);
1536 ctx->cq_last_tm_flush = seq;
1537 spin_unlock_irq(&ctx->timeout_lock);
1540 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1542 if (ctx->off_timeout_used)
1543 io_flush_timeouts(ctx);
1544 if (ctx->drain_active)
1545 io_queue_deferred(ctx);
1548 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1550 if (unlikely(ctx->off_timeout_used || ctx->drain_active))
1551 __io_commit_cqring_flush(ctx);
1552 /* order cqe stores with ring update */
1553 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1556 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1558 struct io_rings *r = ctx->rings;
1560 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1563 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1565 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1568 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1570 struct io_rings *rings = ctx->rings;
1571 unsigned tail, mask = ctx->cq_entries - 1;
1574 * writes to the cq entry need to come after reading head; the
1575 * control dependency is enough as we're using WRITE_ONCE to
1578 if (__io_cqring_events(ctx) == ctx->cq_entries)
1581 tail = ctx->cached_cq_tail++;
1582 return &rings->cqes[tail & mask];
1585 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1587 if (likely(!ctx->cq_ev_fd))
1589 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1591 return !ctx->eventfd_async || io_wq_current_is_worker();
1595 * This should only get called when at least one event has been posted.
1596 * Some applications rely on the eventfd notification count only changing
1597 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1598 * 1:1 relationship between how many times this function is called (and
1599 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1601 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1604 * wake_up_all() may seem excessive, but io_wake_function() and
1605 * io_should_wake() handle the termination of the loop and only
1606 * wake as many waiters as we need to.
1608 if (wq_has_sleeper(&ctx->cq_wait))
1609 wake_up_all(&ctx->cq_wait);
1610 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1611 wake_up(&ctx->sq_data->wait);
1612 if (io_should_trigger_evfd(ctx))
1613 eventfd_signal(ctx->cq_ev_fd, 1);
1614 if (waitqueue_active(&ctx->poll_wait)) {
1615 wake_up_interruptible(&ctx->poll_wait);
1616 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1620 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1622 if (ctx->flags & IORING_SETUP_SQPOLL) {
1623 if (wq_has_sleeper(&ctx->cq_wait))
1624 wake_up_all(&ctx->cq_wait);
1626 if (io_should_trigger_evfd(ctx))
1627 eventfd_signal(ctx->cq_ev_fd, 1);
1628 if (waitqueue_active(&ctx->poll_wait)) {
1629 wake_up_interruptible(&ctx->poll_wait);
1630 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1634 /* Returns true if there are no backlogged entries after the flush */
1635 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1637 bool all_flushed, posted;
1639 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1643 spin_lock(&ctx->completion_lock);
1644 while (!list_empty(&ctx->cq_overflow_list)) {
1645 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1646 struct io_overflow_cqe *ocqe;
1650 ocqe = list_first_entry(&ctx->cq_overflow_list,
1651 struct io_overflow_cqe, list);
1653 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1655 io_account_cq_overflow(ctx);
1658 list_del(&ocqe->list);
1662 all_flushed = list_empty(&ctx->cq_overflow_list);
1664 clear_bit(0, &ctx->check_cq_overflow);
1665 WRITE_ONCE(ctx->rings->sq_flags,
1666 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1670 io_commit_cqring(ctx);
1671 spin_unlock(&ctx->completion_lock);
1673 io_cqring_ev_posted(ctx);
1677 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1681 if (test_bit(0, &ctx->check_cq_overflow)) {
1682 /* iopoll syncs against uring_lock, not completion_lock */
1683 if (ctx->flags & IORING_SETUP_IOPOLL)
1684 mutex_lock(&ctx->uring_lock);
1685 ret = __io_cqring_overflow_flush(ctx, false);
1686 if (ctx->flags & IORING_SETUP_IOPOLL)
1687 mutex_unlock(&ctx->uring_lock);
1693 /* must to be called somewhat shortly after putting a request */
1694 static inline void io_put_task(struct task_struct *task, int nr)
1696 struct io_uring_task *tctx = task->io_uring;
1698 if (likely(task == current)) {
1699 tctx->cached_refs += nr;
1701 percpu_counter_sub(&tctx->inflight, nr);
1702 if (unlikely(atomic_read(&tctx->in_idle)))
1703 wake_up(&tctx->wait);
1704 put_task_struct_many(task, nr);
1708 static void io_task_refs_refill(struct io_uring_task *tctx)
1710 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1712 percpu_counter_add(&tctx->inflight, refill);
1713 refcount_add(refill, ¤t->usage);
1714 tctx->cached_refs += refill;
1717 static inline void io_get_task_refs(int nr)
1719 struct io_uring_task *tctx = current->io_uring;
1721 tctx->cached_refs -= nr;
1722 if (unlikely(tctx->cached_refs < 0))
1723 io_task_refs_refill(tctx);
1726 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1727 long res, unsigned int cflags)
1729 struct io_overflow_cqe *ocqe;
1731 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1734 * If we're in ring overflow flush mode, or in task cancel mode,
1735 * or cannot allocate an overflow entry, then we need to drop it
1738 io_account_cq_overflow(ctx);
1741 if (list_empty(&ctx->cq_overflow_list)) {
1742 set_bit(0, &ctx->check_cq_overflow);
1743 WRITE_ONCE(ctx->rings->sq_flags,
1744 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
1747 ocqe->cqe.user_data = user_data;
1748 ocqe->cqe.res = res;
1749 ocqe->cqe.flags = cflags;
1750 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1754 static inline bool __io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1755 long res, unsigned int cflags)
1757 struct io_uring_cqe *cqe;
1759 trace_io_uring_complete(ctx, user_data, res, cflags);
1762 * If we can't get a cq entry, userspace overflowed the
1763 * submission (by quite a lot). Increment the overflow count in
1766 cqe = io_get_cqe(ctx);
1768 WRITE_ONCE(cqe->user_data, user_data);
1769 WRITE_ONCE(cqe->res, res);
1770 WRITE_ONCE(cqe->flags, cflags);
1773 return io_cqring_event_overflow(ctx, user_data, res, cflags);
1776 /* not as hot to bloat with inlining */
1777 static noinline bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1778 long res, unsigned int cflags)
1780 return __io_cqring_fill_event(ctx, user_data, res, cflags);
1783 static void io_req_complete_post(struct io_kiocb *req, long res,
1784 unsigned int cflags)
1786 struct io_ring_ctx *ctx = req->ctx;
1788 spin_lock(&ctx->completion_lock);
1789 __io_cqring_fill_event(ctx, req->user_data, res, cflags);
1791 * If we're the last reference to this request, add to our locked
1794 if (req_ref_put_and_test(req)) {
1795 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1796 if (req->flags & IO_DISARM_MASK)
1797 io_disarm_next(req);
1799 io_req_task_queue(req->link);
1803 io_dismantle_req(req);
1804 io_put_task(req->task, 1);
1805 list_add(&req->inflight_entry, &ctx->locked_free_list);
1806 ctx->locked_free_nr++;
1808 if (!percpu_ref_tryget(&ctx->refs))
1811 io_commit_cqring(ctx);
1812 spin_unlock(&ctx->completion_lock);
1815 io_cqring_ev_posted(ctx);
1816 percpu_ref_put(&ctx->refs);
1820 static inline bool io_req_needs_clean(struct io_kiocb *req)
1822 return req->flags & IO_REQ_CLEAN_FLAGS;
1825 static void io_req_complete_state(struct io_kiocb *req, long res,
1826 unsigned int cflags)
1828 if (io_req_needs_clean(req))
1831 req->compl.cflags = cflags;
1832 req->flags |= REQ_F_COMPLETE_INLINE;
1835 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1836 long res, unsigned cflags)
1838 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1839 io_req_complete_state(req, res, cflags);
1841 io_req_complete_post(req, res, cflags);
1844 static inline void io_req_complete(struct io_kiocb *req, long res)
1846 __io_req_complete(req, 0, res, 0);
1849 static void io_req_complete_failed(struct io_kiocb *req, long res)
1852 io_req_complete_post(req, res, 0);
1855 static void io_req_complete_fail_submit(struct io_kiocb *req)
1858 * We don't submit, fail them all, for that replace hardlinks with
1859 * normal links. Extra REQ_F_LINK is tolerated.
1861 req->flags &= ~REQ_F_HARDLINK;
1862 req->flags |= REQ_F_LINK;
1863 io_req_complete_failed(req, req->result);
1867 * Don't initialise the fields below on every allocation, but do that in
1868 * advance and keep them valid across allocations.
1870 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1874 req->async_data = NULL;
1875 /* not necessary, but safer to zero */
1879 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1880 struct io_submit_state *state)
1882 spin_lock(&ctx->completion_lock);
1883 list_splice_init(&ctx->locked_free_list, &state->free_list);
1884 ctx->locked_free_nr = 0;
1885 spin_unlock(&ctx->completion_lock);
1888 /* Returns true IFF there are requests in the cache */
1889 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1891 struct io_submit_state *state = &ctx->submit_state;
1895 * If we have more than a batch's worth of requests in our IRQ side
1896 * locked cache, grab the lock and move them over to our submission
1899 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
1900 io_flush_cached_locked_reqs(ctx, state);
1902 nr = state->free_reqs;
1903 while (!list_empty(&state->free_list)) {
1904 struct io_kiocb *req = list_first_entry(&state->free_list,
1905 struct io_kiocb, inflight_entry);
1907 list_del(&req->inflight_entry);
1908 state->reqs[nr++] = req;
1909 if (nr == ARRAY_SIZE(state->reqs))
1913 state->free_reqs = nr;
1918 * A request might get retired back into the request caches even before opcode
1919 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1920 * Because of that, io_alloc_req() should be called only under ->uring_lock
1921 * and with extra caution to not get a request that is still worked on.
1923 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1924 __must_hold(&ctx->uring_lock)
1926 struct io_submit_state *state = &ctx->submit_state;
1927 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1930 BUILD_BUG_ON(ARRAY_SIZE(state->reqs) < IO_REQ_ALLOC_BATCH);
1932 if (likely(state->free_reqs || io_flush_cached_reqs(ctx)))
1935 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1939 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1940 * retry single alloc to be on the safe side.
1942 if (unlikely(ret <= 0)) {
1943 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1944 if (!state->reqs[0])
1949 for (i = 0; i < ret; i++)
1950 io_preinit_req(state->reqs[i], ctx);
1951 state->free_reqs = ret;
1954 return state->reqs[state->free_reqs];
1957 static inline void io_put_file(struct file *file)
1963 static void io_dismantle_req(struct io_kiocb *req)
1965 unsigned int flags = req->flags;
1967 if (io_req_needs_clean(req))
1969 if (!(flags & REQ_F_FIXED_FILE))
1970 io_put_file(req->file);
1971 if (req->fixed_rsrc_refs)
1972 percpu_ref_put(req->fixed_rsrc_refs);
1973 if (req->async_data) {
1974 kfree(req->async_data);
1975 req->async_data = NULL;
1979 static void __io_free_req(struct io_kiocb *req)
1981 struct io_ring_ctx *ctx = req->ctx;
1983 io_dismantle_req(req);
1984 io_put_task(req->task, 1);
1986 spin_lock(&ctx->completion_lock);
1987 list_add(&req->inflight_entry, &ctx->locked_free_list);
1988 ctx->locked_free_nr++;
1989 spin_unlock(&ctx->completion_lock);
1991 percpu_ref_put(&ctx->refs);
1994 static inline void io_remove_next_linked(struct io_kiocb *req)
1996 struct io_kiocb *nxt = req->link;
1998 req->link = nxt->link;
2002 static bool io_kill_linked_timeout(struct io_kiocb *req)
2003 __must_hold(&req->ctx->completion_lock)
2004 __must_hold(&req->ctx->timeout_lock)
2006 struct io_kiocb *link = req->link;
2008 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2009 struct io_timeout_data *io = link->async_data;
2011 io_remove_next_linked(req);
2012 link->timeout.head = NULL;
2013 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2014 list_del(&link->timeout.list);
2015 io_cqring_fill_event(link->ctx, link->user_data,
2017 io_put_req_deferred(link);
2024 static void io_fail_links(struct io_kiocb *req)
2025 __must_hold(&req->ctx->completion_lock)
2027 struct io_kiocb *nxt, *link = req->link;
2031 long res = -ECANCELED;
2033 if (link->flags & REQ_F_FAIL)
2039 trace_io_uring_fail_link(req, link);
2040 io_cqring_fill_event(link->ctx, link->user_data, res, 0);
2041 io_put_req_deferred(link);
2046 static bool io_disarm_next(struct io_kiocb *req)
2047 __must_hold(&req->ctx->completion_lock)
2049 bool posted = false;
2051 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2052 struct io_kiocb *link = req->link;
2054 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2055 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2056 io_remove_next_linked(req);
2057 io_cqring_fill_event(link->ctx, link->user_data,
2059 io_put_req_deferred(link);
2062 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2063 struct io_ring_ctx *ctx = req->ctx;
2065 spin_lock_irq(&ctx->timeout_lock);
2066 posted = io_kill_linked_timeout(req);
2067 spin_unlock_irq(&ctx->timeout_lock);
2069 if (unlikely((req->flags & REQ_F_FAIL) &&
2070 !(req->flags & REQ_F_HARDLINK))) {
2071 posted |= (req->link != NULL);
2077 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
2079 struct io_kiocb *nxt;
2082 * If LINK is set, we have dependent requests in this chain. If we
2083 * didn't fail this request, queue the first one up, moving any other
2084 * dependencies to the next request. In case of failure, fail the rest
2087 if (req->flags & IO_DISARM_MASK) {
2088 struct io_ring_ctx *ctx = req->ctx;
2091 spin_lock(&ctx->completion_lock);
2092 posted = io_disarm_next(req);
2094 io_commit_cqring(req->ctx);
2095 spin_unlock(&ctx->completion_lock);
2097 io_cqring_ev_posted(ctx);
2104 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2106 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2108 return __io_req_find_next(req);
2111 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2116 if (ctx->submit_state.compl_nr)
2117 io_submit_flush_completions(ctx);
2118 mutex_unlock(&ctx->uring_lock);
2121 percpu_ref_put(&ctx->refs);
2124 static void tctx_task_work(struct callback_head *cb)
2126 bool locked = false;
2127 struct io_ring_ctx *ctx = NULL;
2128 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2132 struct io_wq_work_node *node;
2134 if (!tctx->task_list.first && locked && ctx->submit_state.compl_nr)
2135 io_submit_flush_completions(ctx);
2137 spin_lock_irq(&tctx->task_lock);
2138 node = tctx->task_list.first;
2139 INIT_WQ_LIST(&tctx->task_list);
2141 tctx->task_running = false;
2142 spin_unlock_irq(&tctx->task_lock);
2147 struct io_wq_work_node *next = node->next;
2148 struct io_kiocb *req = container_of(node, struct io_kiocb,
2151 if (req->ctx != ctx) {
2152 ctx_flush_and_put(ctx, &locked);
2154 /* if not contended, grab and improve batching */
2155 locked = mutex_trylock(&ctx->uring_lock);
2156 percpu_ref_get(&ctx->refs);
2158 req->io_task_work.func(req, &locked);
2165 ctx_flush_and_put(ctx, &locked);
2168 static void io_req_task_work_add(struct io_kiocb *req)
2170 struct task_struct *tsk = req->task;
2171 struct io_uring_task *tctx = tsk->io_uring;
2172 enum task_work_notify_mode notify;
2173 struct io_wq_work_node *node;
2174 unsigned long flags;
2177 WARN_ON_ONCE(!tctx);
2179 spin_lock_irqsave(&tctx->task_lock, flags);
2180 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2181 running = tctx->task_running;
2183 tctx->task_running = true;
2184 spin_unlock_irqrestore(&tctx->task_lock, flags);
2186 /* task_work already pending, we're done */
2191 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2192 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2193 * processing task_work. There's no reliable way to tell if TWA_RESUME
2196 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2197 if (!task_work_add(tsk, &tctx->task_work, notify)) {
2198 wake_up_process(tsk);
2202 spin_lock_irqsave(&tctx->task_lock, flags);
2203 tctx->task_running = false;
2204 node = tctx->task_list.first;
2205 INIT_WQ_LIST(&tctx->task_list);
2206 spin_unlock_irqrestore(&tctx->task_lock, flags);
2209 req = container_of(node, struct io_kiocb, io_task_work.node);
2211 if (llist_add(&req->io_task_work.fallback_node,
2212 &req->ctx->fallback_llist))
2213 schedule_delayed_work(&req->ctx->fallback_work, 1);
2217 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2219 struct io_ring_ctx *ctx = req->ctx;
2221 /* not needed for normal modes, but SQPOLL depends on it */
2222 io_tw_lock(ctx, locked);
2223 io_req_complete_failed(req, req->result);
2226 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2228 struct io_ring_ctx *ctx = req->ctx;
2230 io_tw_lock(ctx, locked);
2231 /* req->task == current here, checking PF_EXITING is safe */
2232 if (likely(!(req->task->flags & PF_EXITING)))
2233 __io_queue_sqe(req);
2235 io_req_complete_failed(req, -EFAULT);
2238 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2241 req->io_task_work.func = io_req_task_cancel;
2242 io_req_task_work_add(req);
2245 static void io_req_task_queue(struct io_kiocb *req)
2247 req->io_task_work.func = io_req_task_submit;
2248 io_req_task_work_add(req);
2251 static void io_req_task_queue_reissue(struct io_kiocb *req)
2253 req->io_task_work.func = io_queue_async_work;
2254 io_req_task_work_add(req);
2257 static inline void io_queue_next(struct io_kiocb *req)
2259 struct io_kiocb *nxt = io_req_find_next(req);
2262 io_req_task_queue(nxt);
2265 static void io_free_req(struct io_kiocb *req)
2271 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2277 struct task_struct *task;
2282 static inline void io_init_req_batch(struct req_batch *rb)
2289 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2290 struct req_batch *rb)
2293 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2295 io_put_task(rb->task, rb->task_refs);
2298 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2299 struct io_submit_state *state)
2302 io_dismantle_req(req);
2304 if (req->task != rb->task) {
2306 io_put_task(rb->task, rb->task_refs);
2307 rb->task = req->task;
2313 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2314 state->reqs[state->free_reqs++] = req;
2316 list_add(&req->inflight_entry, &state->free_list);
2319 static void io_submit_flush_completions(struct io_ring_ctx *ctx)
2320 __must_hold(&ctx->uring_lock)
2322 struct io_submit_state *state = &ctx->submit_state;
2323 int i, nr = state->compl_nr;
2324 struct req_batch rb;
2326 spin_lock(&ctx->completion_lock);
2327 for (i = 0; i < nr; i++) {
2328 struct io_kiocb *req = state->compl_reqs[i];
2330 __io_cqring_fill_event(ctx, req->user_data, req->result,
2333 io_commit_cqring(ctx);
2334 spin_unlock(&ctx->completion_lock);
2335 io_cqring_ev_posted(ctx);
2337 io_init_req_batch(&rb);
2338 for (i = 0; i < nr; i++) {
2339 struct io_kiocb *req = state->compl_reqs[i];
2341 if (req_ref_put_and_test(req))
2342 io_req_free_batch(&rb, req, &ctx->submit_state);
2345 io_req_free_batch_finish(ctx, &rb);
2346 state->compl_nr = 0;
2350 * Drop reference to request, return next in chain (if there is one) if this
2351 * was the last reference to this request.
2353 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2355 struct io_kiocb *nxt = NULL;
2357 if (req_ref_put_and_test(req)) {
2358 nxt = io_req_find_next(req);
2364 static inline void io_put_req(struct io_kiocb *req)
2366 if (req_ref_put_and_test(req))
2370 static inline void io_put_req_deferred(struct io_kiocb *req)
2372 if (req_ref_put_and_test(req)) {
2373 req->io_task_work.func = io_free_req_work;
2374 io_req_task_work_add(req);
2378 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2380 /* See comment at the top of this file */
2382 return __io_cqring_events(ctx);
2385 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2387 struct io_rings *rings = ctx->rings;
2389 /* make sure SQ entry isn't read before tail */
2390 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2393 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2395 unsigned int cflags;
2397 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2398 cflags |= IORING_CQE_F_BUFFER;
2399 req->flags &= ~REQ_F_BUFFER_SELECTED;
2404 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2406 struct io_buffer *kbuf;
2408 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
2410 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2411 return io_put_kbuf(req, kbuf);
2414 static inline bool io_run_task_work(void)
2416 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2417 __set_current_state(TASK_RUNNING);
2418 tracehook_notify_signal();
2426 * Find and free completed poll iocbs
2428 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2429 struct list_head *done)
2431 struct req_batch rb;
2432 struct io_kiocb *req;
2434 /* order with ->result store in io_complete_rw_iopoll() */
2437 io_init_req_batch(&rb);
2438 while (!list_empty(done)) {
2439 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2440 list_del(&req->inflight_entry);
2442 if (READ_ONCE(req->result) == -EAGAIN &&
2443 !(req->flags & REQ_F_DONT_REISSUE)) {
2444 req->iopoll_completed = 0;
2445 io_req_task_queue_reissue(req);
2449 __io_cqring_fill_event(ctx, req->user_data, req->result,
2450 io_put_rw_kbuf(req));
2453 if (req_ref_put_and_test(req))
2454 io_req_free_batch(&rb, req, &ctx->submit_state);
2457 io_commit_cqring(ctx);
2458 io_cqring_ev_posted_iopoll(ctx);
2459 io_req_free_batch_finish(ctx, &rb);
2462 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2465 struct io_kiocb *req, *tmp;
2470 * Only spin for completions if we don't have multiple devices hanging
2471 * off our complete list, and we're under the requested amount.
2473 spin = !ctx->poll_multi_queue && *nr_events < min;
2475 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2476 struct kiocb *kiocb = &req->rw.kiocb;
2480 * Move completed and retryable entries to our local lists.
2481 * If we find a request that requires polling, break out
2482 * and complete those lists first, if we have entries there.
2484 if (READ_ONCE(req->iopoll_completed)) {
2485 list_move_tail(&req->inflight_entry, &done);
2488 if (!list_empty(&done))
2491 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2492 if (unlikely(ret < 0))
2497 /* iopoll may have completed current req */
2498 if (READ_ONCE(req->iopoll_completed))
2499 list_move_tail(&req->inflight_entry, &done);
2502 if (!list_empty(&done))
2503 io_iopoll_complete(ctx, nr_events, &done);
2509 * We can't just wait for polled events to come to us, we have to actively
2510 * find and complete them.
2512 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2514 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2517 mutex_lock(&ctx->uring_lock);
2518 while (!list_empty(&ctx->iopoll_list)) {
2519 unsigned int nr_events = 0;
2521 io_do_iopoll(ctx, &nr_events, 0);
2523 /* let it sleep and repeat later if can't complete a request */
2527 * Ensure we allow local-to-the-cpu processing to take place,
2528 * in this case we need to ensure that we reap all events.
2529 * Also let task_work, etc. to progress by releasing the mutex
2531 if (need_resched()) {
2532 mutex_unlock(&ctx->uring_lock);
2534 mutex_lock(&ctx->uring_lock);
2537 mutex_unlock(&ctx->uring_lock);
2540 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2542 unsigned int nr_events = 0;
2546 * We disallow the app entering submit/complete with polling, but we
2547 * still need to lock the ring to prevent racing with polled issue
2548 * that got punted to a workqueue.
2550 mutex_lock(&ctx->uring_lock);
2552 * Don't enter poll loop if we already have events pending.
2553 * If we do, we can potentially be spinning for commands that
2554 * already triggered a CQE (eg in error).
2556 if (test_bit(0, &ctx->check_cq_overflow))
2557 __io_cqring_overflow_flush(ctx, false);
2558 if (io_cqring_events(ctx))
2562 * If a submit got punted to a workqueue, we can have the
2563 * application entering polling for a command before it gets
2564 * issued. That app will hold the uring_lock for the duration
2565 * of the poll right here, so we need to take a breather every
2566 * now and then to ensure that the issue has a chance to add
2567 * the poll to the issued list. Otherwise we can spin here
2568 * forever, while the workqueue is stuck trying to acquire the
2571 if (list_empty(&ctx->iopoll_list)) {
2572 u32 tail = ctx->cached_cq_tail;
2574 mutex_unlock(&ctx->uring_lock);
2576 mutex_lock(&ctx->uring_lock);
2578 /* some requests don't go through iopoll_list */
2579 if (tail != ctx->cached_cq_tail ||
2580 list_empty(&ctx->iopoll_list))
2583 ret = io_do_iopoll(ctx, &nr_events, min);
2584 } while (!ret && nr_events < min && !need_resched());
2586 mutex_unlock(&ctx->uring_lock);
2590 static void kiocb_end_write(struct io_kiocb *req)
2593 * Tell lockdep we inherited freeze protection from submission
2596 if (req->flags & REQ_F_ISREG) {
2597 struct super_block *sb = file_inode(req->file)->i_sb;
2599 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2605 static bool io_resubmit_prep(struct io_kiocb *req)
2607 struct io_async_rw *rw = req->async_data;
2610 return !io_req_prep_async(req);
2611 /* may have left rw->iter inconsistent on -EIOCBQUEUED */
2612 iov_iter_revert(&rw->iter, req->result - iov_iter_count(&rw->iter));
2616 static bool io_rw_should_reissue(struct io_kiocb *req)
2618 umode_t mode = file_inode(req->file)->i_mode;
2619 struct io_ring_ctx *ctx = req->ctx;
2621 if (!S_ISBLK(mode) && !S_ISREG(mode))
2623 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2624 !(ctx->flags & IORING_SETUP_IOPOLL)))
2627 * If ref is dying, we might be running poll reap from the exit work.
2628 * Don't attempt to reissue from that path, just let it fail with
2631 if (percpu_ref_is_dying(&ctx->refs))
2634 * Play it safe and assume not safe to re-import and reissue if we're
2635 * not in the original thread group (or in task context).
2637 if (!same_thread_group(req->task, current) || !in_task())
2642 static bool io_resubmit_prep(struct io_kiocb *req)
2646 static bool io_rw_should_reissue(struct io_kiocb *req)
2652 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2654 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2655 kiocb_end_write(req);
2656 if (res != req->result) {
2657 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2658 io_rw_should_reissue(req)) {
2659 req->flags |= REQ_F_REISSUE;
2668 static void io_req_task_complete(struct io_kiocb *req, bool *locked)
2670 unsigned int cflags = io_put_rw_kbuf(req);
2671 long res = req->result;
2674 struct io_ring_ctx *ctx = req->ctx;
2675 struct io_submit_state *state = &ctx->submit_state;
2677 io_req_complete_state(req, res, cflags);
2678 state->compl_reqs[state->compl_nr++] = req;
2679 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
2680 io_submit_flush_completions(ctx);
2682 io_req_complete_post(req, res, cflags);
2686 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2687 unsigned int issue_flags)
2689 if (__io_complete_rw_common(req, res))
2691 __io_req_complete(req, issue_flags, req->result, io_put_rw_kbuf(req));
2694 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2696 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2698 if (__io_complete_rw_common(req, res))
2701 req->io_task_work.func = io_req_task_complete;
2702 io_req_task_work_add(req);
2705 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2707 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2709 if (kiocb->ki_flags & IOCB_WRITE)
2710 kiocb_end_write(req);
2711 if (unlikely(res != req->result)) {
2712 if (!(res == -EAGAIN && io_rw_should_reissue(req) &&
2713 io_resubmit_prep(req))) {
2715 req->flags |= REQ_F_DONT_REISSUE;
2719 WRITE_ONCE(req->result, res);
2720 /* order with io_iopoll_complete() checking ->result */
2722 WRITE_ONCE(req->iopoll_completed, 1);
2726 * After the iocb has been issued, it's safe to be found on the poll list.
2727 * Adding the kiocb to the list AFTER submission ensures that we don't
2728 * find it from a io_do_iopoll() thread before the issuer is done
2729 * accessing the kiocb cookie.
2731 static void io_iopoll_req_issued(struct io_kiocb *req)
2733 struct io_ring_ctx *ctx = req->ctx;
2734 const bool in_async = io_wq_current_is_worker();
2736 /* workqueue context doesn't hold uring_lock, grab it now */
2737 if (unlikely(in_async))
2738 mutex_lock(&ctx->uring_lock);
2741 * Track whether we have multiple files in our lists. This will impact
2742 * how we do polling eventually, not spinning if we're on potentially
2743 * different devices.
2745 if (list_empty(&ctx->iopoll_list)) {
2746 ctx->poll_multi_queue = false;
2747 } else if (!ctx->poll_multi_queue) {
2748 struct io_kiocb *list_req;
2749 unsigned int queue_num0, queue_num1;
2751 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2754 if (list_req->file != req->file) {
2755 ctx->poll_multi_queue = true;
2757 queue_num0 = blk_qc_t_to_queue_num(list_req->rw.kiocb.ki_cookie);
2758 queue_num1 = blk_qc_t_to_queue_num(req->rw.kiocb.ki_cookie);
2759 if (queue_num0 != queue_num1)
2760 ctx->poll_multi_queue = true;
2765 * For fast devices, IO may have already completed. If it has, add
2766 * it to the front so we find it first.
2768 if (READ_ONCE(req->iopoll_completed))
2769 list_add(&req->inflight_entry, &ctx->iopoll_list);
2771 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2773 if (unlikely(in_async)) {
2775 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2776 * in sq thread task context or in io worker task context. If
2777 * current task context is sq thread, we don't need to check
2778 * whether should wake up sq thread.
2780 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2781 wq_has_sleeper(&ctx->sq_data->wait))
2782 wake_up(&ctx->sq_data->wait);
2784 mutex_unlock(&ctx->uring_lock);
2788 static bool io_bdev_nowait(struct block_device *bdev)
2790 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2794 * If we tracked the file through the SCM inflight mechanism, we could support
2795 * any file. For now, just ensure that anything potentially problematic is done
2798 static bool __io_file_supports_nowait(struct file *file, int rw)
2800 umode_t mode = file_inode(file)->i_mode;
2802 if (S_ISBLK(mode)) {
2803 if (IS_ENABLED(CONFIG_BLOCK) &&
2804 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2810 if (S_ISREG(mode)) {
2811 if (IS_ENABLED(CONFIG_BLOCK) &&
2812 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2813 file->f_op != &io_uring_fops)
2818 /* any ->read/write should understand O_NONBLOCK */
2819 if (file->f_flags & O_NONBLOCK)
2822 if (!(file->f_mode & FMODE_NOWAIT))
2826 return file->f_op->read_iter != NULL;
2828 return file->f_op->write_iter != NULL;
2831 static bool io_file_supports_nowait(struct io_kiocb *req, int rw)
2833 if (rw == READ && (req->flags & REQ_F_NOWAIT_READ))
2835 else if (rw == WRITE && (req->flags & REQ_F_NOWAIT_WRITE))
2838 return __io_file_supports_nowait(req->file, rw);
2841 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2843 struct io_ring_ctx *ctx = req->ctx;
2844 struct kiocb *kiocb = &req->rw.kiocb;
2845 struct file *file = req->file;
2849 if (!io_req_ffs_set(req) && S_ISREG(file_inode(file)->i_mode))
2850 req->flags |= REQ_F_ISREG;
2852 kiocb->ki_pos = READ_ONCE(sqe->off);
2853 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2854 req->flags |= REQ_F_CUR_POS;
2855 kiocb->ki_pos = file->f_pos;
2857 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2858 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2859 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2863 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2864 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2865 req->flags |= REQ_F_NOWAIT;
2867 ioprio = READ_ONCE(sqe->ioprio);
2869 ret = ioprio_check_cap(ioprio);
2873 kiocb->ki_ioprio = ioprio;
2875 kiocb->ki_ioprio = get_current_ioprio();
2877 if (ctx->flags & IORING_SETUP_IOPOLL) {
2878 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2879 !kiocb->ki_filp->f_op->iopoll)
2882 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
2883 kiocb->ki_complete = io_complete_rw_iopoll;
2884 req->iopoll_completed = 0;
2886 if (kiocb->ki_flags & IOCB_HIPRI)
2888 kiocb->ki_complete = io_complete_rw;
2891 if (req->opcode == IORING_OP_READ_FIXED ||
2892 req->opcode == IORING_OP_WRITE_FIXED) {
2894 io_req_set_rsrc_node(req);
2897 req->rw.addr = READ_ONCE(sqe->addr);
2898 req->rw.len = READ_ONCE(sqe->len);
2899 req->buf_index = READ_ONCE(sqe->buf_index);
2903 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2909 case -ERESTARTNOINTR:
2910 case -ERESTARTNOHAND:
2911 case -ERESTART_RESTARTBLOCK:
2913 * We can't just restart the syscall, since previously
2914 * submitted sqes may already be in progress. Just fail this
2920 kiocb->ki_complete(kiocb, ret, 0);
2924 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2925 unsigned int issue_flags)
2927 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2928 struct io_async_rw *io = req->async_data;
2929 bool check_reissue = kiocb->ki_complete == io_complete_rw;
2931 /* add previously done IO, if any */
2932 if (io && io->bytes_done > 0) {
2934 ret = io->bytes_done;
2936 ret += io->bytes_done;
2939 if (req->flags & REQ_F_CUR_POS)
2940 req->file->f_pos = kiocb->ki_pos;
2941 if (ret >= 0 && check_reissue)
2942 __io_complete_rw(req, ret, 0, issue_flags);
2944 io_rw_done(kiocb, ret);
2946 if (check_reissue && (req->flags & REQ_F_REISSUE)) {
2947 req->flags &= ~REQ_F_REISSUE;
2948 if (io_resubmit_prep(req)) {
2949 io_req_task_queue_reissue(req);
2952 __io_req_complete(req, issue_flags, ret,
2953 io_put_rw_kbuf(req));
2958 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2959 struct io_mapped_ubuf *imu)
2961 size_t len = req->rw.len;
2962 u64 buf_end, buf_addr = req->rw.addr;
2965 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2967 /* not inside the mapped region */
2968 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2972 * May not be a start of buffer, set size appropriately
2973 * and advance us to the beginning.
2975 offset = buf_addr - imu->ubuf;
2976 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2980 * Don't use iov_iter_advance() here, as it's really slow for
2981 * using the latter parts of a big fixed buffer - it iterates
2982 * over each segment manually. We can cheat a bit here, because
2985 * 1) it's a BVEC iter, we set it up
2986 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2987 * first and last bvec
2989 * So just find our index, and adjust the iterator afterwards.
2990 * If the offset is within the first bvec (or the whole first
2991 * bvec, just use iov_iter_advance(). This makes it easier
2992 * since we can just skip the first segment, which may not
2993 * be PAGE_SIZE aligned.
2995 const struct bio_vec *bvec = imu->bvec;
2997 if (offset <= bvec->bv_len) {
2998 iov_iter_advance(iter, offset);
3000 unsigned long seg_skip;
3002 /* skip first vec */
3003 offset -= bvec->bv_len;
3004 seg_skip = 1 + (offset >> PAGE_SHIFT);
3006 iter->bvec = bvec + seg_skip;
3007 iter->nr_segs -= seg_skip;
3008 iter->count -= bvec->bv_len + offset;
3009 iter->iov_offset = offset & ~PAGE_MASK;
3016 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
3018 struct io_ring_ctx *ctx = req->ctx;
3019 struct io_mapped_ubuf *imu = req->imu;
3020 u16 index, buf_index = req->buf_index;
3023 if (unlikely(buf_index >= ctx->nr_user_bufs))
3025 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3026 imu = READ_ONCE(ctx->user_bufs[index]);
3029 return __io_import_fixed(req, rw, iter, imu);
3032 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3035 mutex_unlock(&ctx->uring_lock);
3038 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3041 * "Normal" inline submissions always hold the uring_lock, since we
3042 * grab it from the system call. Same is true for the SQPOLL offload.
3043 * The only exception is when we've detached the request and issue it
3044 * from an async worker thread, grab the lock for that case.
3047 mutex_lock(&ctx->uring_lock);
3050 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3051 int bgid, struct io_buffer *kbuf,
3054 struct io_buffer *head;
3056 if (req->flags & REQ_F_BUFFER_SELECTED)
3059 io_ring_submit_lock(req->ctx, needs_lock);
3061 lockdep_assert_held(&req->ctx->uring_lock);
3063 head = xa_load(&req->ctx->io_buffers, bgid);
3065 if (!list_empty(&head->list)) {
3066 kbuf = list_last_entry(&head->list, struct io_buffer,
3068 list_del(&kbuf->list);
3071 xa_erase(&req->ctx->io_buffers, bgid);
3073 if (*len > kbuf->len)
3076 kbuf = ERR_PTR(-ENOBUFS);
3079 io_ring_submit_unlock(req->ctx, needs_lock);
3084 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3087 struct io_buffer *kbuf;
3090 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3091 bgid = req->buf_index;
3092 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3095 req->rw.addr = (u64) (unsigned long) kbuf;
3096 req->flags |= REQ_F_BUFFER_SELECTED;
3097 return u64_to_user_ptr(kbuf->addr);
3100 #ifdef CONFIG_COMPAT
3101 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3104 struct compat_iovec __user *uiov;
3105 compat_ssize_t clen;
3109 uiov = u64_to_user_ptr(req->rw.addr);
3110 if (!access_ok(uiov, sizeof(*uiov)))
3112 if (__get_user(clen, &uiov->iov_len))
3118 buf = io_rw_buffer_select(req, &len, needs_lock);
3120 return PTR_ERR(buf);
3121 iov[0].iov_base = buf;
3122 iov[0].iov_len = (compat_size_t) len;
3127 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3130 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3134 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3137 len = iov[0].iov_len;
3140 buf = io_rw_buffer_select(req, &len, needs_lock);
3142 return PTR_ERR(buf);
3143 iov[0].iov_base = buf;
3144 iov[0].iov_len = len;
3148 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3151 if (req->flags & REQ_F_BUFFER_SELECTED) {
3152 struct io_buffer *kbuf;
3154 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3155 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3156 iov[0].iov_len = kbuf->len;
3159 if (req->rw.len != 1)
3162 #ifdef CONFIG_COMPAT
3163 if (req->ctx->compat)
3164 return io_compat_import(req, iov, needs_lock);
3167 return __io_iov_buffer_select(req, iov, needs_lock);
3170 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3171 struct iov_iter *iter, bool needs_lock)
3173 void __user *buf = u64_to_user_ptr(req->rw.addr);
3174 size_t sqe_len = req->rw.len;
3175 u8 opcode = req->opcode;
3178 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3180 return io_import_fixed(req, rw, iter);
3183 /* buffer index only valid with fixed read/write, or buffer select */
3184 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3187 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3188 if (req->flags & REQ_F_BUFFER_SELECT) {
3189 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3191 return PTR_ERR(buf);
3192 req->rw.len = sqe_len;
3195 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3200 if (req->flags & REQ_F_BUFFER_SELECT) {
3201 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3203 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3208 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3212 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3214 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3218 * For files that don't have ->read_iter() and ->write_iter(), handle them
3219 * by looping over ->read() or ->write() manually.
3221 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3223 struct kiocb *kiocb = &req->rw.kiocb;
3224 struct file *file = req->file;
3228 * Don't support polled IO through this interface, and we can't
3229 * support non-blocking either. For the latter, this just causes
3230 * the kiocb to be handled from an async context.
3232 if (kiocb->ki_flags & IOCB_HIPRI)
3234 if (kiocb->ki_flags & IOCB_NOWAIT)
3237 while (iov_iter_count(iter)) {
3241 if (!iov_iter_is_bvec(iter)) {
3242 iovec = iov_iter_iovec(iter);
3244 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3245 iovec.iov_len = req->rw.len;
3249 nr = file->f_op->read(file, iovec.iov_base,
3250 iovec.iov_len, io_kiocb_ppos(kiocb));
3252 nr = file->f_op->write(file, iovec.iov_base,
3253 iovec.iov_len, io_kiocb_ppos(kiocb));
3262 if (nr != iovec.iov_len)
3266 iov_iter_advance(iter, nr);
3272 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3273 const struct iovec *fast_iov, struct iov_iter *iter)
3275 struct io_async_rw *rw = req->async_data;
3277 memcpy(&rw->iter, iter, sizeof(*iter));
3278 rw->free_iovec = iovec;
3280 /* can only be fixed buffers, no need to do anything */
3281 if (iov_iter_is_bvec(iter))
3284 unsigned iov_off = 0;
3286 rw->iter.iov = rw->fast_iov;
3287 if (iter->iov != fast_iov) {
3288 iov_off = iter->iov - fast_iov;
3289 rw->iter.iov += iov_off;
3291 if (rw->fast_iov != fast_iov)
3292 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3293 sizeof(struct iovec) * iter->nr_segs);
3295 req->flags |= REQ_F_NEED_CLEANUP;
3299 static inline int io_alloc_async_data(struct io_kiocb *req)
3301 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3302 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3303 return req->async_data == NULL;
3306 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3307 const struct iovec *fast_iov,
3308 struct iov_iter *iter, bool force)
3310 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3312 if (!req->async_data) {
3313 if (io_alloc_async_data(req)) {
3318 io_req_map_rw(req, iovec, fast_iov, iter);
3323 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3325 struct io_async_rw *iorw = req->async_data;
3326 struct iovec *iov = iorw->fast_iov;
3329 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3330 if (unlikely(ret < 0))
3333 iorw->bytes_done = 0;
3334 iorw->free_iovec = iov;
3336 req->flags |= REQ_F_NEED_CLEANUP;
3340 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3342 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3344 return io_prep_rw(req, sqe);
3348 * This is our waitqueue callback handler, registered through lock_page_async()
3349 * when we initially tried to do the IO with the iocb armed our waitqueue.
3350 * This gets called when the page is unlocked, and we generally expect that to
3351 * happen when the page IO is completed and the page is now uptodate. This will
3352 * queue a task_work based retry of the operation, attempting to copy the data
3353 * again. If the latter fails because the page was NOT uptodate, then we will
3354 * do a thread based blocking retry of the operation. That's the unexpected
3357 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3358 int sync, void *arg)
3360 struct wait_page_queue *wpq;
3361 struct io_kiocb *req = wait->private;
3362 struct wait_page_key *key = arg;
3364 wpq = container_of(wait, struct wait_page_queue, wait);
3366 if (!wake_page_match(wpq, key))
3369 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3370 list_del_init(&wait->entry);
3371 io_req_task_queue(req);
3376 * This controls whether a given IO request should be armed for async page
3377 * based retry. If we return false here, the request is handed to the async
3378 * worker threads for retry. If we're doing buffered reads on a regular file,
3379 * we prepare a private wait_page_queue entry and retry the operation. This
3380 * will either succeed because the page is now uptodate and unlocked, or it
3381 * will register a callback when the page is unlocked at IO completion. Through
3382 * that callback, io_uring uses task_work to setup a retry of the operation.
3383 * That retry will attempt the buffered read again. The retry will generally
3384 * succeed, or in rare cases where it fails, we then fall back to using the
3385 * async worker threads for a blocking retry.
3387 static bool io_rw_should_retry(struct io_kiocb *req)
3389 struct io_async_rw *rw = req->async_data;
3390 struct wait_page_queue *wait = &rw->wpq;