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) {
1487 atomic_set(&req->ctx->cq_timeouts,
1488 atomic_read(&req->ctx->cq_timeouts) + 1);
1489 list_del_init(&req->timeout.list);
1490 io_cqring_fill_event(req->ctx, req->user_data, status, 0);
1491 io_put_req_deferred(req);
1495 static void io_queue_deferred(struct io_ring_ctx *ctx)
1497 while (!list_empty(&ctx->defer_list)) {
1498 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1499 struct io_defer_entry, list);
1501 if (req_need_defer(de->req, de->seq))
1503 list_del_init(&de->list);
1504 io_req_task_queue(de->req);
1509 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1510 __must_hold(&ctx->completion_lock)
1512 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1514 spin_lock_irq(&ctx->timeout_lock);
1515 while (!list_empty(&ctx->timeout_list)) {
1516 u32 events_needed, events_got;
1517 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1518 struct io_kiocb, timeout.list);
1520 if (io_is_timeout_noseq(req))
1524 * Since seq can easily wrap around over time, subtract
1525 * the last seq at which timeouts were flushed before comparing.
1526 * Assuming not more than 2^31-1 events have happened since,
1527 * these subtractions won't have wrapped, so we can check if
1528 * target is in [last_seq, current_seq] by comparing the two.
1530 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1531 events_got = seq - ctx->cq_last_tm_flush;
1532 if (events_got < events_needed)
1535 list_del_init(&req->timeout.list);
1536 io_kill_timeout(req, 0);
1538 ctx->cq_last_tm_flush = seq;
1539 spin_unlock_irq(&ctx->timeout_lock);
1542 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1544 if (ctx->off_timeout_used)
1545 io_flush_timeouts(ctx);
1546 if (ctx->drain_active)
1547 io_queue_deferred(ctx);
1550 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1552 if (unlikely(ctx->off_timeout_used || ctx->drain_active))
1553 __io_commit_cqring_flush(ctx);
1554 /* order cqe stores with ring update */
1555 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1558 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1560 struct io_rings *r = ctx->rings;
1562 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1565 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1567 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1570 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1572 struct io_rings *rings = ctx->rings;
1573 unsigned tail, mask = ctx->cq_entries - 1;
1576 * writes to the cq entry need to come after reading head; the
1577 * control dependency is enough as we're using WRITE_ONCE to
1580 if (__io_cqring_events(ctx) == ctx->cq_entries)
1583 tail = ctx->cached_cq_tail++;
1584 return &rings->cqes[tail & mask];
1587 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1589 if (likely(!ctx->cq_ev_fd))
1591 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1593 return !ctx->eventfd_async || io_wq_current_is_worker();
1597 * This should only get called when at least one event has been posted.
1598 * Some applications rely on the eventfd notification count only changing
1599 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1600 * 1:1 relationship between how many times this function is called (and
1601 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1603 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1606 * wake_up_all() may seem excessive, but io_wake_function() and
1607 * io_should_wake() handle the termination of the loop and only
1608 * wake as many waiters as we need to.
1610 if (wq_has_sleeper(&ctx->cq_wait))
1611 wake_up_all(&ctx->cq_wait);
1612 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1613 wake_up(&ctx->sq_data->wait);
1614 if (io_should_trigger_evfd(ctx))
1615 eventfd_signal(ctx->cq_ev_fd, 1);
1616 if (waitqueue_active(&ctx->poll_wait)) {
1617 wake_up_interruptible(&ctx->poll_wait);
1618 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1622 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1624 /* see waitqueue_active() comment */
1627 if (ctx->flags & IORING_SETUP_SQPOLL) {
1628 if (waitqueue_active(&ctx->cq_wait))
1629 wake_up_all(&ctx->cq_wait);
1631 if (io_should_trigger_evfd(ctx))
1632 eventfd_signal(ctx->cq_ev_fd, 1);
1633 if (waitqueue_active(&ctx->poll_wait)) {
1634 wake_up_interruptible(&ctx->poll_wait);
1635 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1639 /* Returns true if there are no backlogged entries after the flush */
1640 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1642 bool all_flushed, posted;
1644 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1648 spin_lock(&ctx->completion_lock);
1649 while (!list_empty(&ctx->cq_overflow_list)) {
1650 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1651 struct io_overflow_cqe *ocqe;
1655 ocqe = list_first_entry(&ctx->cq_overflow_list,
1656 struct io_overflow_cqe, list);
1658 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1660 io_account_cq_overflow(ctx);
1663 list_del(&ocqe->list);
1667 all_flushed = list_empty(&ctx->cq_overflow_list);
1669 clear_bit(0, &ctx->check_cq_overflow);
1670 WRITE_ONCE(ctx->rings->sq_flags,
1671 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1675 io_commit_cqring(ctx);
1676 spin_unlock(&ctx->completion_lock);
1678 io_cqring_ev_posted(ctx);
1682 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1686 if (test_bit(0, &ctx->check_cq_overflow)) {
1687 /* iopoll syncs against uring_lock, not completion_lock */
1688 if (ctx->flags & IORING_SETUP_IOPOLL)
1689 mutex_lock(&ctx->uring_lock);
1690 ret = __io_cqring_overflow_flush(ctx, false);
1691 if (ctx->flags & IORING_SETUP_IOPOLL)
1692 mutex_unlock(&ctx->uring_lock);
1698 /* must to be called somewhat shortly after putting a request */
1699 static inline void io_put_task(struct task_struct *task, int nr)
1701 struct io_uring_task *tctx = task->io_uring;
1703 if (likely(task == current)) {
1704 tctx->cached_refs += nr;
1706 percpu_counter_sub(&tctx->inflight, nr);
1707 if (unlikely(atomic_read(&tctx->in_idle)))
1708 wake_up(&tctx->wait);
1709 put_task_struct_many(task, nr);
1713 static void io_task_refs_refill(struct io_uring_task *tctx)
1715 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1717 percpu_counter_add(&tctx->inflight, refill);
1718 refcount_add(refill, ¤t->usage);
1719 tctx->cached_refs += refill;
1722 static inline void io_get_task_refs(int nr)
1724 struct io_uring_task *tctx = current->io_uring;
1726 tctx->cached_refs -= nr;
1727 if (unlikely(tctx->cached_refs < 0))
1728 io_task_refs_refill(tctx);
1731 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1732 long res, unsigned int cflags)
1734 struct io_overflow_cqe *ocqe;
1736 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1739 * If we're in ring overflow flush mode, or in task cancel mode,
1740 * or cannot allocate an overflow entry, then we need to drop it
1743 io_account_cq_overflow(ctx);
1746 if (list_empty(&ctx->cq_overflow_list)) {
1747 set_bit(0, &ctx->check_cq_overflow);
1748 WRITE_ONCE(ctx->rings->sq_flags,
1749 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
1752 ocqe->cqe.user_data = user_data;
1753 ocqe->cqe.res = res;
1754 ocqe->cqe.flags = cflags;
1755 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1759 static inline bool __io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1760 long res, unsigned int cflags)
1762 struct io_uring_cqe *cqe;
1764 trace_io_uring_complete(ctx, user_data, res, cflags);
1767 * If we can't get a cq entry, userspace overflowed the
1768 * submission (by quite a lot). Increment the overflow count in
1771 cqe = io_get_cqe(ctx);
1773 WRITE_ONCE(cqe->user_data, user_data);
1774 WRITE_ONCE(cqe->res, res);
1775 WRITE_ONCE(cqe->flags, cflags);
1778 return io_cqring_event_overflow(ctx, user_data, res, cflags);
1781 /* not as hot to bloat with inlining */
1782 static noinline bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1783 long res, unsigned int cflags)
1785 return __io_cqring_fill_event(ctx, user_data, res, cflags);
1788 static void io_req_complete_post(struct io_kiocb *req, long res,
1789 unsigned int cflags)
1791 struct io_ring_ctx *ctx = req->ctx;
1793 spin_lock(&ctx->completion_lock);
1794 __io_cqring_fill_event(ctx, req->user_data, res, cflags);
1796 * If we're the last reference to this request, add to our locked
1799 if (req_ref_put_and_test(req)) {
1800 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1801 if (req->flags & IO_DISARM_MASK)
1802 io_disarm_next(req);
1804 io_req_task_queue(req->link);
1808 io_dismantle_req(req);
1809 io_put_task(req->task, 1);
1810 list_add(&req->inflight_entry, &ctx->locked_free_list);
1811 ctx->locked_free_nr++;
1813 if (!percpu_ref_tryget(&ctx->refs))
1816 io_commit_cqring(ctx);
1817 spin_unlock(&ctx->completion_lock);
1820 io_cqring_ev_posted(ctx);
1821 percpu_ref_put(&ctx->refs);
1825 static inline bool io_req_needs_clean(struct io_kiocb *req)
1827 return req->flags & IO_REQ_CLEAN_FLAGS;
1830 static void io_req_complete_state(struct io_kiocb *req, long res,
1831 unsigned int cflags)
1833 if (io_req_needs_clean(req))
1836 req->compl.cflags = cflags;
1837 req->flags |= REQ_F_COMPLETE_INLINE;
1840 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1841 long res, unsigned cflags)
1843 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1844 io_req_complete_state(req, res, cflags);
1846 io_req_complete_post(req, res, cflags);
1849 static inline void io_req_complete(struct io_kiocb *req, long res)
1851 __io_req_complete(req, 0, res, 0);
1854 static void io_req_complete_failed(struct io_kiocb *req, long res)
1857 io_req_complete_post(req, res, 0);
1860 static void io_req_complete_fail_submit(struct io_kiocb *req)
1863 * We don't submit, fail them all, for that replace hardlinks with
1864 * normal links. Extra REQ_F_LINK is tolerated.
1866 req->flags &= ~REQ_F_HARDLINK;
1867 req->flags |= REQ_F_LINK;
1868 io_req_complete_failed(req, req->result);
1872 * Don't initialise the fields below on every allocation, but do that in
1873 * advance and keep them valid across allocations.
1875 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1879 req->async_data = NULL;
1880 /* not necessary, but safer to zero */
1884 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1885 struct io_submit_state *state)
1887 spin_lock(&ctx->completion_lock);
1888 list_splice_init(&ctx->locked_free_list, &state->free_list);
1889 ctx->locked_free_nr = 0;
1890 spin_unlock(&ctx->completion_lock);
1893 /* Returns true IFF there are requests in the cache */
1894 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1896 struct io_submit_state *state = &ctx->submit_state;
1900 * If we have more than a batch's worth of requests in our IRQ side
1901 * locked cache, grab the lock and move them over to our submission
1904 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
1905 io_flush_cached_locked_reqs(ctx, state);
1907 nr = state->free_reqs;
1908 while (!list_empty(&state->free_list)) {
1909 struct io_kiocb *req = list_first_entry(&state->free_list,
1910 struct io_kiocb, inflight_entry);
1912 list_del(&req->inflight_entry);
1913 state->reqs[nr++] = req;
1914 if (nr == ARRAY_SIZE(state->reqs))
1918 state->free_reqs = nr;
1923 * A request might get retired back into the request caches even before opcode
1924 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1925 * Because of that, io_alloc_req() should be called only under ->uring_lock
1926 * and with extra caution to not get a request that is still worked on.
1928 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1929 __must_hold(&ctx->uring_lock)
1931 struct io_submit_state *state = &ctx->submit_state;
1932 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1935 BUILD_BUG_ON(ARRAY_SIZE(state->reqs) < IO_REQ_ALLOC_BATCH);
1937 if (likely(state->free_reqs || io_flush_cached_reqs(ctx)))
1940 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1944 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1945 * retry single alloc to be on the safe side.
1947 if (unlikely(ret <= 0)) {
1948 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1949 if (!state->reqs[0])
1954 for (i = 0; i < ret; i++)
1955 io_preinit_req(state->reqs[i], ctx);
1956 state->free_reqs = ret;
1959 return state->reqs[state->free_reqs];
1962 static inline void io_put_file(struct file *file)
1968 static void io_dismantle_req(struct io_kiocb *req)
1970 unsigned int flags = req->flags;
1972 if (io_req_needs_clean(req))
1974 if (!(flags & REQ_F_FIXED_FILE))
1975 io_put_file(req->file);
1976 if (req->fixed_rsrc_refs)
1977 percpu_ref_put(req->fixed_rsrc_refs);
1978 if (req->async_data) {
1979 kfree(req->async_data);
1980 req->async_data = NULL;
1984 static void __io_free_req(struct io_kiocb *req)
1986 struct io_ring_ctx *ctx = req->ctx;
1988 io_dismantle_req(req);
1989 io_put_task(req->task, 1);
1991 spin_lock(&ctx->completion_lock);
1992 list_add(&req->inflight_entry, &ctx->locked_free_list);
1993 ctx->locked_free_nr++;
1994 spin_unlock(&ctx->completion_lock);
1996 percpu_ref_put(&ctx->refs);
1999 static inline void io_remove_next_linked(struct io_kiocb *req)
2001 struct io_kiocb *nxt = req->link;
2003 req->link = nxt->link;
2007 static bool io_kill_linked_timeout(struct io_kiocb *req)
2008 __must_hold(&req->ctx->completion_lock)
2009 __must_hold(&req->ctx->timeout_lock)
2011 struct io_kiocb *link = req->link;
2013 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2014 struct io_timeout_data *io = link->async_data;
2016 io_remove_next_linked(req);
2017 link->timeout.head = NULL;
2018 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2019 list_del(&link->timeout.list);
2020 io_cqring_fill_event(link->ctx, link->user_data,
2022 io_put_req_deferred(link);
2029 static void io_fail_links(struct io_kiocb *req)
2030 __must_hold(&req->ctx->completion_lock)
2032 struct io_kiocb *nxt, *link = req->link;
2036 long res = -ECANCELED;
2038 if (link->flags & REQ_F_FAIL)
2044 trace_io_uring_fail_link(req, link);
2045 io_cqring_fill_event(link->ctx, link->user_data, res, 0);
2046 io_put_req_deferred(link);
2051 static bool io_disarm_next(struct io_kiocb *req)
2052 __must_hold(&req->ctx->completion_lock)
2054 bool posted = false;
2056 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2057 struct io_kiocb *link = req->link;
2059 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2060 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2061 io_remove_next_linked(req);
2062 io_cqring_fill_event(link->ctx, link->user_data,
2064 io_put_req_deferred(link);
2067 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2068 struct io_ring_ctx *ctx = req->ctx;
2070 spin_lock_irq(&ctx->timeout_lock);
2071 posted = io_kill_linked_timeout(req);
2072 spin_unlock_irq(&ctx->timeout_lock);
2074 if (unlikely((req->flags & REQ_F_FAIL) &&
2075 !(req->flags & REQ_F_HARDLINK))) {
2076 posted |= (req->link != NULL);
2082 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
2084 struct io_kiocb *nxt;
2087 * If LINK is set, we have dependent requests in this chain. If we
2088 * didn't fail this request, queue the first one up, moving any other
2089 * dependencies to the next request. In case of failure, fail the rest
2092 if (req->flags & IO_DISARM_MASK) {
2093 struct io_ring_ctx *ctx = req->ctx;
2096 spin_lock(&ctx->completion_lock);
2097 posted = io_disarm_next(req);
2099 io_commit_cqring(req->ctx);
2100 spin_unlock(&ctx->completion_lock);
2102 io_cqring_ev_posted(ctx);
2109 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2111 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2113 return __io_req_find_next(req);
2116 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2121 if (ctx->submit_state.compl_nr)
2122 io_submit_flush_completions(ctx);
2123 mutex_unlock(&ctx->uring_lock);
2126 percpu_ref_put(&ctx->refs);
2129 static void tctx_task_work(struct callback_head *cb)
2131 bool locked = false;
2132 struct io_ring_ctx *ctx = NULL;
2133 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2137 struct io_wq_work_node *node;
2139 if (!tctx->task_list.first && locked && ctx->submit_state.compl_nr)
2140 io_submit_flush_completions(ctx);
2142 spin_lock_irq(&tctx->task_lock);
2143 node = tctx->task_list.first;
2144 INIT_WQ_LIST(&tctx->task_list);
2146 tctx->task_running = false;
2147 spin_unlock_irq(&tctx->task_lock);
2152 struct io_wq_work_node *next = node->next;
2153 struct io_kiocb *req = container_of(node, struct io_kiocb,
2156 if (req->ctx != ctx) {
2157 ctx_flush_and_put(ctx, &locked);
2159 /* if not contended, grab and improve batching */
2160 locked = mutex_trylock(&ctx->uring_lock);
2161 percpu_ref_get(&ctx->refs);
2163 req->io_task_work.func(req, &locked);
2170 ctx_flush_and_put(ctx, &locked);
2173 static void io_req_task_work_add(struct io_kiocb *req)
2175 struct task_struct *tsk = req->task;
2176 struct io_uring_task *tctx = tsk->io_uring;
2177 enum task_work_notify_mode notify;
2178 struct io_wq_work_node *node;
2179 unsigned long flags;
2182 WARN_ON_ONCE(!tctx);
2184 spin_lock_irqsave(&tctx->task_lock, flags);
2185 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2186 running = tctx->task_running;
2188 tctx->task_running = true;
2189 spin_unlock_irqrestore(&tctx->task_lock, flags);
2191 /* task_work already pending, we're done */
2196 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2197 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2198 * processing task_work. There's no reliable way to tell if TWA_RESUME
2201 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2202 if (!task_work_add(tsk, &tctx->task_work, notify)) {
2203 wake_up_process(tsk);
2207 spin_lock_irqsave(&tctx->task_lock, flags);
2208 tctx->task_running = false;
2209 node = tctx->task_list.first;
2210 INIT_WQ_LIST(&tctx->task_list);
2211 spin_unlock_irqrestore(&tctx->task_lock, flags);
2214 req = container_of(node, struct io_kiocb, io_task_work.node);
2216 if (llist_add(&req->io_task_work.fallback_node,
2217 &req->ctx->fallback_llist))
2218 schedule_delayed_work(&req->ctx->fallback_work, 1);
2222 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2224 struct io_ring_ctx *ctx = req->ctx;
2226 /* not needed for normal modes, but SQPOLL depends on it */
2227 io_tw_lock(ctx, locked);
2228 io_req_complete_failed(req, req->result);
2231 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2233 struct io_ring_ctx *ctx = req->ctx;
2235 io_tw_lock(ctx, locked);
2236 /* req->task == current here, checking PF_EXITING is safe */
2237 if (likely(!(req->task->flags & PF_EXITING)))
2238 __io_queue_sqe(req);
2240 io_req_complete_failed(req, -EFAULT);
2243 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2246 req->io_task_work.func = io_req_task_cancel;
2247 io_req_task_work_add(req);
2250 static void io_req_task_queue(struct io_kiocb *req)
2252 req->io_task_work.func = io_req_task_submit;
2253 io_req_task_work_add(req);
2256 static void io_req_task_queue_reissue(struct io_kiocb *req)
2258 req->io_task_work.func = io_queue_async_work;
2259 io_req_task_work_add(req);
2262 static inline void io_queue_next(struct io_kiocb *req)
2264 struct io_kiocb *nxt = io_req_find_next(req);
2267 io_req_task_queue(nxt);
2270 static void io_free_req(struct io_kiocb *req)
2276 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2282 struct task_struct *task;
2287 static inline void io_init_req_batch(struct req_batch *rb)
2294 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2295 struct req_batch *rb)
2298 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2300 io_put_task(rb->task, rb->task_refs);
2303 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2304 struct io_submit_state *state)
2307 io_dismantle_req(req);
2309 if (req->task != rb->task) {
2311 io_put_task(rb->task, rb->task_refs);
2312 rb->task = req->task;
2318 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2319 state->reqs[state->free_reqs++] = req;
2321 list_add(&req->inflight_entry, &state->free_list);
2324 static void io_submit_flush_completions(struct io_ring_ctx *ctx)
2325 __must_hold(&ctx->uring_lock)
2327 struct io_submit_state *state = &ctx->submit_state;
2328 int i, nr = state->compl_nr;
2329 struct req_batch rb;
2331 spin_lock(&ctx->completion_lock);
2332 for (i = 0; i < nr; i++) {
2333 struct io_kiocb *req = state->compl_reqs[i];
2335 __io_cqring_fill_event(ctx, req->user_data, req->result,
2338 io_commit_cqring(ctx);
2339 spin_unlock(&ctx->completion_lock);
2340 io_cqring_ev_posted(ctx);
2342 io_init_req_batch(&rb);
2343 for (i = 0; i < nr; i++) {
2344 struct io_kiocb *req = state->compl_reqs[i];
2346 if (req_ref_put_and_test(req))
2347 io_req_free_batch(&rb, req, &ctx->submit_state);
2350 io_req_free_batch_finish(ctx, &rb);
2351 state->compl_nr = 0;
2355 * Drop reference to request, return next in chain (if there is one) if this
2356 * was the last reference to this request.
2358 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2360 struct io_kiocb *nxt = NULL;
2362 if (req_ref_put_and_test(req)) {
2363 nxt = io_req_find_next(req);
2369 static inline void io_put_req(struct io_kiocb *req)
2371 if (req_ref_put_and_test(req))
2375 static inline void io_put_req_deferred(struct io_kiocb *req)
2377 if (req_ref_put_and_test(req)) {
2378 req->io_task_work.func = io_free_req_work;
2379 io_req_task_work_add(req);
2383 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2385 /* See comment at the top of this file */
2387 return __io_cqring_events(ctx);
2390 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2392 struct io_rings *rings = ctx->rings;
2394 /* make sure SQ entry isn't read before tail */
2395 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2398 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2400 unsigned int cflags;
2402 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2403 cflags |= IORING_CQE_F_BUFFER;
2404 req->flags &= ~REQ_F_BUFFER_SELECTED;
2409 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2411 struct io_buffer *kbuf;
2413 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
2415 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2416 return io_put_kbuf(req, kbuf);
2419 static inline bool io_run_task_work(void)
2421 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2422 __set_current_state(TASK_RUNNING);
2423 tracehook_notify_signal();
2431 * Find and free completed poll iocbs
2433 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2434 struct list_head *done)
2436 struct req_batch rb;
2437 struct io_kiocb *req;
2439 /* order with ->result store in io_complete_rw_iopoll() */
2442 io_init_req_batch(&rb);
2443 while (!list_empty(done)) {
2444 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2445 list_del(&req->inflight_entry);
2447 if (READ_ONCE(req->result) == -EAGAIN &&
2448 !(req->flags & REQ_F_DONT_REISSUE)) {
2449 req->iopoll_completed = 0;
2450 io_req_task_queue_reissue(req);
2454 __io_cqring_fill_event(ctx, req->user_data, req->result,
2455 io_put_rw_kbuf(req));
2458 if (req_ref_put_and_test(req))
2459 io_req_free_batch(&rb, req, &ctx->submit_state);
2462 io_commit_cqring(ctx);
2463 io_cqring_ev_posted_iopoll(ctx);
2464 io_req_free_batch_finish(ctx, &rb);
2467 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2470 struct io_kiocb *req, *tmp;
2475 * Only spin for completions if we don't have multiple devices hanging
2476 * off our complete list, and we're under the requested amount.
2478 spin = !ctx->poll_multi_queue && *nr_events < min;
2480 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2481 struct kiocb *kiocb = &req->rw.kiocb;
2485 * Move completed and retryable entries to our local lists.
2486 * If we find a request that requires polling, break out
2487 * and complete those lists first, if we have entries there.
2489 if (READ_ONCE(req->iopoll_completed)) {
2490 list_move_tail(&req->inflight_entry, &done);
2493 if (!list_empty(&done))
2496 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2497 if (unlikely(ret < 0))
2502 /* iopoll may have completed current req */
2503 if (READ_ONCE(req->iopoll_completed))
2504 list_move_tail(&req->inflight_entry, &done);
2507 if (!list_empty(&done))
2508 io_iopoll_complete(ctx, nr_events, &done);
2514 * We can't just wait for polled events to come to us, we have to actively
2515 * find and complete them.
2517 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2519 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2522 mutex_lock(&ctx->uring_lock);
2523 while (!list_empty(&ctx->iopoll_list)) {
2524 unsigned int nr_events = 0;
2526 io_do_iopoll(ctx, &nr_events, 0);
2528 /* let it sleep and repeat later if can't complete a request */
2532 * Ensure we allow local-to-the-cpu processing to take place,
2533 * in this case we need to ensure that we reap all events.
2534 * Also let task_work, etc. to progress by releasing the mutex
2536 if (need_resched()) {
2537 mutex_unlock(&ctx->uring_lock);
2539 mutex_lock(&ctx->uring_lock);
2542 mutex_unlock(&ctx->uring_lock);
2545 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2547 unsigned int nr_events = 0;
2551 * We disallow the app entering submit/complete with polling, but we
2552 * still need to lock the ring to prevent racing with polled issue
2553 * that got punted to a workqueue.
2555 mutex_lock(&ctx->uring_lock);
2557 * Don't enter poll loop if we already have events pending.
2558 * If we do, we can potentially be spinning for commands that
2559 * already triggered a CQE (eg in error).
2561 if (test_bit(0, &ctx->check_cq_overflow))
2562 __io_cqring_overflow_flush(ctx, false);
2563 if (io_cqring_events(ctx))
2567 * If a submit got punted to a workqueue, we can have the
2568 * application entering polling for a command before it gets
2569 * issued. That app will hold the uring_lock for the duration
2570 * of the poll right here, so we need to take a breather every
2571 * now and then to ensure that the issue has a chance to add
2572 * the poll to the issued list. Otherwise we can spin here
2573 * forever, while the workqueue is stuck trying to acquire the
2576 if (list_empty(&ctx->iopoll_list)) {
2577 u32 tail = ctx->cached_cq_tail;
2579 mutex_unlock(&ctx->uring_lock);
2581 mutex_lock(&ctx->uring_lock);
2583 /* some requests don't go through iopoll_list */
2584 if (tail != ctx->cached_cq_tail ||
2585 list_empty(&ctx->iopoll_list))
2588 ret = io_do_iopoll(ctx, &nr_events, min);
2589 } while (!ret && nr_events < min && !need_resched());
2591 mutex_unlock(&ctx->uring_lock);
2595 static void kiocb_end_write(struct io_kiocb *req)
2598 * Tell lockdep we inherited freeze protection from submission
2601 if (req->flags & REQ_F_ISREG) {
2602 struct super_block *sb = file_inode(req->file)->i_sb;
2604 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2610 static bool io_resubmit_prep(struct io_kiocb *req)
2612 struct io_async_rw *rw = req->async_data;
2615 return !io_req_prep_async(req);
2616 /* may have left rw->iter inconsistent on -EIOCBQUEUED */
2617 iov_iter_revert(&rw->iter, req->result - iov_iter_count(&rw->iter));
2621 static bool io_rw_should_reissue(struct io_kiocb *req)
2623 umode_t mode = file_inode(req->file)->i_mode;
2624 struct io_ring_ctx *ctx = req->ctx;
2626 if (!S_ISBLK(mode) && !S_ISREG(mode))
2628 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2629 !(ctx->flags & IORING_SETUP_IOPOLL)))
2632 * If ref is dying, we might be running poll reap from the exit work.
2633 * Don't attempt to reissue from that path, just let it fail with
2636 if (percpu_ref_is_dying(&ctx->refs))
2639 * Play it safe and assume not safe to re-import and reissue if we're
2640 * not in the original thread group (or in task context).
2642 if (!same_thread_group(req->task, current) || !in_task())
2647 static bool io_resubmit_prep(struct io_kiocb *req)
2651 static bool io_rw_should_reissue(struct io_kiocb *req)
2657 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2659 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2660 kiocb_end_write(req);
2661 if (res != req->result) {
2662 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2663 io_rw_should_reissue(req)) {
2664 req->flags |= REQ_F_REISSUE;
2673 static void io_req_task_complete(struct io_kiocb *req, bool *locked)
2675 unsigned int cflags = io_put_rw_kbuf(req);
2676 long res = req->result;
2679 struct io_ring_ctx *ctx = req->ctx;
2680 struct io_submit_state *state = &ctx->submit_state;
2682 io_req_complete_state(req, res, cflags);
2683 state->compl_reqs[state->compl_nr++] = req;
2684 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
2685 io_submit_flush_completions(ctx);
2687 io_req_complete_post(req, res, cflags);
2691 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2692 unsigned int issue_flags)
2694 if (__io_complete_rw_common(req, res))
2696 __io_req_complete(req, issue_flags, req->result, io_put_rw_kbuf(req));
2699 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2701 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2703 if (__io_complete_rw_common(req, res))
2706 req->io_task_work.func = io_req_task_complete;
2707 io_req_task_work_add(req);
2710 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2712 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2714 if (kiocb->ki_flags & IOCB_WRITE)
2715 kiocb_end_write(req);
2716 if (unlikely(res != req->result)) {
2717 if (!(res == -EAGAIN && io_rw_should_reissue(req) &&
2718 io_resubmit_prep(req))) {
2720 req->flags |= REQ_F_DONT_REISSUE;
2724 WRITE_ONCE(req->result, res);
2725 /* order with io_iopoll_complete() checking ->result */
2727 WRITE_ONCE(req->iopoll_completed, 1);
2731 * After the iocb has been issued, it's safe to be found on the poll list.
2732 * Adding the kiocb to the list AFTER submission ensures that we don't
2733 * find it from a io_do_iopoll() thread before the issuer is done
2734 * accessing the kiocb cookie.
2736 static void io_iopoll_req_issued(struct io_kiocb *req)
2738 struct io_ring_ctx *ctx = req->ctx;
2739 const bool in_async = io_wq_current_is_worker();
2741 /* workqueue context doesn't hold uring_lock, grab it now */
2742 if (unlikely(in_async))
2743 mutex_lock(&ctx->uring_lock);
2746 * Track whether we have multiple files in our lists. This will impact
2747 * how we do polling eventually, not spinning if we're on potentially
2748 * different devices.
2750 if (list_empty(&ctx->iopoll_list)) {
2751 ctx->poll_multi_queue = false;
2752 } else if (!ctx->poll_multi_queue) {
2753 struct io_kiocb *list_req;
2754 unsigned int queue_num0, queue_num1;
2756 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2759 if (list_req->file != req->file) {
2760 ctx->poll_multi_queue = true;
2762 queue_num0 = blk_qc_t_to_queue_num(list_req->rw.kiocb.ki_cookie);
2763 queue_num1 = blk_qc_t_to_queue_num(req->rw.kiocb.ki_cookie);
2764 if (queue_num0 != queue_num1)
2765 ctx->poll_multi_queue = true;
2770 * For fast devices, IO may have already completed. If it has, add
2771 * it to the front so we find it first.
2773 if (READ_ONCE(req->iopoll_completed))
2774 list_add(&req->inflight_entry, &ctx->iopoll_list);
2776 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2778 if (unlikely(in_async)) {
2780 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2781 * in sq thread task context or in io worker task context. If
2782 * current task context is sq thread, we don't need to check
2783 * whether should wake up sq thread.
2785 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2786 wq_has_sleeper(&ctx->sq_data->wait))
2787 wake_up(&ctx->sq_data->wait);
2789 mutex_unlock(&ctx->uring_lock);
2793 static bool io_bdev_nowait(struct block_device *bdev)
2795 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2799 * If we tracked the file through the SCM inflight mechanism, we could support
2800 * any file. For now, just ensure that anything potentially problematic is done
2803 static bool __io_file_supports_nowait(struct file *file, int rw)
2805 umode_t mode = file_inode(file)->i_mode;
2807 if (S_ISBLK(mode)) {
2808 if (IS_ENABLED(CONFIG_BLOCK) &&
2809 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2815 if (S_ISREG(mode)) {
2816 if (IS_ENABLED(CONFIG_BLOCK) &&
2817 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2818 file->f_op != &io_uring_fops)
2823 /* any ->read/write should understand O_NONBLOCK */
2824 if (file->f_flags & O_NONBLOCK)
2827 if (!(file->f_mode & FMODE_NOWAIT))
2831 return file->f_op->read_iter != NULL;
2833 return file->f_op->write_iter != NULL;
2836 static bool io_file_supports_nowait(struct io_kiocb *req, int rw)
2838 if (rw == READ && (req->flags & REQ_F_NOWAIT_READ))
2840 else if (rw == WRITE && (req->flags & REQ_F_NOWAIT_WRITE))
2843 return __io_file_supports_nowait(req->file, rw);
2846 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2848 struct io_ring_ctx *ctx = req->ctx;
2849 struct kiocb *kiocb = &req->rw.kiocb;
2850 struct file *file = req->file;
2854 if (!io_req_ffs_set(req) && S_ISREG(file_inode(file)->i_mode))
2855 req->flags |= REQ_F_ISREG;
2857 kiocb->ki_pos = READ_ONCE(sqe->off);
2858 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2859 req->flags |= REQ_F_CUR_POS;
2860 kiocb->ki_pos = file->f_pos;
2862 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2863 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2864 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2868 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2869 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2870 req->flags |= REQ_F_NOWAIT;
2872 ioprio = READ_ONCE(sqe->ioprio);
2874 ret = ioprio_check_cap(ioprio);
2878 kiocb->ki_ioprio = ioprio;
2880 kiocb->ki_ioprio = get_current_ioprio();
2882 if (ctx->flags & IORING_SETUP_IOPOLL) {
2883 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2884 !kiocb->ki_filp->f_op->iopoll)
2887 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
2888 kiocb->ki_complete = io_complete_rw_iopoll;
2889 req->iopoll_completed = 0;
2891 if (kiocb->ki_flags & IOCB_HIPRI)
2893 kiocb->ki_complete = io_complete_rw;
2896 if (req->opcode == IORING_OP_READ_FIXED ||
2897 req->opcode == IORING_OP_WRITE_FIXED) {
2899 io_req_set_rsrc_node(req);
2902 req->rw.addr = READ_ONCE(sqe->addr);
2903 req->rw.len = READ_ONCE(sqe->len);
2904 req->buf_index = READ_ONCE(sqe->buf_index);
2908 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2914 case -ERESTARTNOINTR:
2915 case -ERESTARTNOHAND:
2916 case -ERESTART_RESTARTBLOCK:
2918 * We can't just restart the syscall, since previously
2919 * submitted sqes may already be in progress. Just fail this
2925 kiocb->ki_complete(kiocb, ret, 0);
2929 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2930 unsigned int issue_flags)
2932 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2933 struct io_async_rw *io = req->async_data;
2934 bool check_reissue = kiocb->ki_complete == io_complete_rw;
2936 /* add previously done IO, if any */
2937 if (io && io->bytes_done > 0) {
2939 ret = io->bytes_done;
2941 ret += io->bytes_done;
2944 if (req->flags & REQ_F_CUR_POS)
2945 req->file->f_pos = kiocb->ki_pos;
2946 if (ret >= 0 && check_reissue)
2947 __io_complete_rw(req, ret, 0, issue_flags);
2949 io_rw_done(kiocb, ret);
2951 if (check_reissue && (req->flags & REQ_F_REISSUE)) {
2952 req->flags &= ~REQ_F_REISSUE;
2953 if (io_resubmit_prep(req)) {
2954 io_req_task_queue_reissue(req);
2957 __io_req_complete(req, issue_flags, ret,
2958 io_put_rw_kbuf(req));
2963 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2964 struct io_mapped_ubuf *imu)
2966 size_t len = req->rw.len;
2967 u64 buf_end, buf_addr = req->rw.addr;
2970 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2972 /* not inside the mapped region */
2973 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2977 * May not be a start of buffer, set size appropriately
2978 * and advance us to the beginning.
2980 offset = buf_addr - imu->ubuf;
2981 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2985 * Don't use iov_iter_advance() here, as it's really slow for
2986 * using the latter parts of a big fixed buffer - it iterates
2987 * over each segment manually. We can cheat a bit here, because
2990 * 1) it's a BVEC iter, we set it up
2991 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2992 * first and last bvec
2994 * So just find our index, and adjust the iterator afterwards.
2995 * If the offset is within the first bvec (or the whole first
2996 * bvec, just use iov_iter_advance(). This makes it easier
2997 * since we can just skip the first segment, which may not
2998 * be PAGE_SIZE aligned.
3000 const struct bio_vec *bvec = imu->bvec;
3002 if (offset <= bvec->bv_len) {
3003 iov_iter_advance(iter, offset);
3005 unsigned long seg_skip;
3007 /* skip first vec */
3008 offset -= bvec->bv_len;
3009 seg_skip = 1 + (offset >> PAGE_SHIFT);
3011 iter->bvec = bvec + seg_skip;
3012 iter->nr_segs -= seg_skip;
3013 iter->count -= bvec->bv_len + offset;
3014 iter->iov_offset = offset & ~PAGE_MASK;
3021 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
3023 struct io_ring_ctx *ctx = req->ctx;
3024 struct io_mapped_ubuf *imu = req->imu;
3025 u16 index, buf_index = req->buf_index;
3028 if (unlikely(buf_index >= ctx->nr_user_bufs))
3030 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3031 imu = READ_ONCE(ctx->user_bufs[index]);
3034 return __io_import_fixed(req, rw, iter, imu);
3037 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3040 mutex_unlock(&ctx->uring_lock);
3043 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3046 * "Normal" inline submissions always hold the uring_lock, since we
3047 * grab it from the system call. Same is true for the SQPOLL offload.
3048 * The only exception is when we've detached the request and issue it
3049 * from an async worker thread, grab the lock for that case.
3052 mutex_lock(&ctx->uring_lock);
3055 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3056 int bgid, struct io_buffer *kbuf,
3059 struct io_buffer *head;
3061 if (req->flags & REQ_F_BUFFER_SELECTED)
3064 io_ring_submit_lock(req->ctx, needs_lock);
3066 lockdep_assert_held(&req->ctx->uring_lock);
3068 head = xa_load(&req->ctx->io_buffers, bgid);
3070 if (!list_empty(&head->list)) {
3071 kbuf = list_last_entry(&head->list, struct io_buffer,
3073 list_del(&kbuf->list);
3076 xa_erase(&req->ctx->io_buffers, bgid);
3078 if (*len > kbuf->len)
3081 kbuf = ERR_PTR(-ENOBUFS);
3084 io_ring_submit_unlock(req->ctx, needs_lock);
3089 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3092 struct io_buffer *kbuf;
3095 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3096 bgid = req->buf_index;
3097 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3100 req->rw.addr = (u64) (unsigned long) kbuf;
3101 req->flags |= REQ_F_BUFFER_SELECTED;
3102 return u64_to_user_ptr(kbuf->addr);
3105 #ifdef CONFIG_COMPAT
3106 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3109 struct compat_iovec __user *uiov;
3110 compat_ssize_t clen;
3114 uiov = u64_to_user_ptr(req->rw.addr);
3115 if (!access_ok(uiov, sizeof(*uiov)))
3117 if (__get_user(clen, &uiov->iov_len))
3123 buf = io_rw_buffer_select(req, &len, needs_lock);
3125 return PTR_ERR(buf);
3126 iov[0].iov_base = buf;
3127 iov[0].iov_len = (compat_size_t) len;
3132 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3135 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3139 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3142 len = iov[0].iov_len;
3145 buf = io_rw_buffer_select(req, &len, needs_lock);
3147 return PTR_ERR(buf);
3148 iov[0].iov_base = buf;
3149 iov[0].iov_len = len;
3153 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3156 if (req->flags & REQ_F_BUFFER_SELECTED) {
3157 struct io_buffer *kbuf;
3159 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3160 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3161 iov[0].iov_len = kbuf->len;
3164 if (req->rw.len != 1)
3167 #ifdef CONFIG_COMPAT
3168 if (req->ctx->compat)
3169 return io_compat_import(req, iov, needs_lock);
3172 return __io_iov_buffer_select(req, iov, needs_lock);
3175 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3176 struct iov_iter *iter, bool needs_lock)
3178 void __user *buf = u64_to_user_ptr(req->rw.addr);
3179 size_t sqe_len = req->rw.len;
3180 u8 opcode = req->opcode;
3183 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3185 return io_import_fixed(req, rw, iter);
3188 /* buffer index only valid with fixed read/write, or buffer select */
3189 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3192 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3193 if (req->flags & REQ_F_BUFFER_SELECT) {
3194 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3196 return PTR_ERR(buf);
3197 req->rw.len = sqe_len;
3200 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3205 if (req->flags & REQ_F_BUFFER_SELECT) {
3206 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3208 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3213 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3217 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3219 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3223 * For files that don't have ->read_iter() and ->write_iter(), handle them
3224 * by looping over ->read() or ->write() manually.
3226 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3228 struct kiocb *kiocb = &req->rw.kiocb;
3229 struct file *file = req->file;
3233 * Don't support polled IO through this interface, and we can't
3234 * support non-blocking either. For the latter, this just causes
3235 * the kiocb to be handled from an async context.
3237 if (kiocb->ki_flags & IOCB_HIPRI)
3239 if (kiocb->ki_flags & IOCB_NOWAIT)
3242 while (iov_iter_count(iter)) {
3246 if (!iov_iter_is_bvec(iter)) {
3247 iovec = iov_iter_iovec(iter);
3249 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3250 iovec.iov_len = req->rw.len;
3254 nr = file->f_op->read(file, iovec.iov_base,
3255 iovec.iov_len, io_kiocb_ppos(kiocb));
3257 nr = file->f_op->write(file, iovec.iov_base,
3258 iovec.iov_len, io_kiocb_ppos(kiocb));
3267 if (nr != iovec.iov_len)
3271 iov_iter_advance(iter, nr);
3277 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3278 const struct iovec *fast_iov, struct iov_iter *iter)
3280 struct io_async_rw *rw = req->async_data;
3282 memcpy(&rw->iter, iter, sizeof(*iter));
3283 rw->free_iovec = iovec;
3285 /* can only be fixed buffers, no need to do anything */
3286 if (iov_iter_is_bvec(iter))
3289 unsigned iov_off = 0;
3291 rw->iter.iov = rw->fast_iov;
3292 if (iter->iov != fast_iov) {
3293 iov_off = iter->iov - fast_iov;
3294 rw->iter.iov += iov_off;
3296 if (rw->fast_iov != fast_iov)
3297 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3298 sizeof(struct iovec) * iter->nr_segs);
3300 req->flags |= REQ_F_NEED_CLEANUP;
3304 static inline int io_alloc_async_data(struct io_kiocb *req)
3306 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3307 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3308 return req->async_data == NULL;
3311 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3312 const struct iovec *fast_iov,
3313 struct iov_iter *iter, bool force)
3315 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3317 if (!req->async_data) {
3318 if (io_alloc_async_data(req)) {
3323 io_req_map_rw(req, iovec, fast_iov, iter);
3328 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3330 struct io_async_rw *iorw = req->async_data;
3331 struct iovec *iov = iorw->fast_iov;
3334 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3335 if (unlikely(ret < 0))
3338 iorw->bytes_done = 0;
3339 iorw->free_iovec = iov;
3341 req->flags |= REQ_F_NEED_CLEANUP;
3345 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3347 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3349 return io_prep_rw(req, sqe);
3353 * This is our waitqueue callback handler, registered through lock_page_async()
3354 * when we initially tried to do the IO with the iocb armed our waitqueue.
3355 * This gets called when the page is unlocked, and we generally expect that to
3356 * happen when the page IO is completed and the page is now uptodate. This will
3357 * queue a task_work based retry of the operation, attempting to copy the data
3358 * again. If the latter fails because the page was NOT uptodate, then we will
3359 * do a thread based blocking retry of the operation. That's the unexpected
3362 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3363 int sync, void *arg)
3365 struct wait_page_queue *wpq;
3366 struct io_kiocb *req = wait->private;
3367 struct wait_page_key *key = arg;
3369 wpq = container_of(wait, struct wait_page_queue, wait);
3371 if (!wake_page_match(wpq, key))
3374 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3375 list_del_init(&wait->entry);
3376 io_req_task_queue(req);
3381 * This controls whether a given IO request should be armed for async page
3382 * based retry. If we return false here, the request is handed to the async
3383 * worker threads for retry. If we're doing buffered reads on a regular file,
3384 * we prepare a private wait_page_queue entry and retry the operation. This
3385 * will either succeed because the page is now uptodate and unlocked, or it
3386 * will register a callback when the page is unlocked at IO completion. Through
3387 * that callback, io_uring uses task_work to setup a retry of the operation.
3388 * That retry will attempt the buffered read again. The retry will generally
3389 * succeed, or in rare cases where it fails, we then fall back to using the
3390 * async worker threads for a blocking retry.